avi,wav: also handle JUNQ chunk in addition to JUNK
[platform/upstream/gst-plugins-good.git] / gst / avi / gstavidemux.c
1 /* GStreamer
2  * Copyright (C) <1999> Erik Walthinsen <omega@temple-baptist.com>
3  * Copyright (C) <2006> Nokia Corporation (contact <stefan.kost@nokia.com>)
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  */
20 /* Element-Checklist-Version: 5 */
21
22 /**
23  * SECTION:element-avidemux
24  *
25  * Demuxes an .avi file into raw or compressed audio and/or video streams.
26  *
27  * This element supports both push and pull-based scheduling, depending on the
28  * capabilities of the upstream elements.
29  *
30  * <refsect2>
31  * <title>Example launch line</title>
32  * |[
33  * gst-launch filesrc location=test.avi ! avidemux name=demux  demux.audio_00 ! decodebin ! audioconvert ! audioresample ! autoaudiosink   demux.video_00 ! queue ! decodebin ! ffmpegcolorspace ! videoscale ! autovideosink
34  * ]| Play (parse and decode) an .avi file and try to output it to
35  * an automatically detected soundcard and videosink. If the AVI file contains
36  * compressed audio or video data, this will only work if you have the
37  * right decoder elements/plugins installed.
38  * </refsect2>
39  *
40  * Last reviewed on 2006-12-29 (0.10.6)
41  */
42
43 #ifdef HAVE_CONFIG_H
44 #include "config.h"
45 #endif
46
47 #include <string.h>
48 #include <stdio.h>
49
50 #include "gst/riff/riff-media.h"
51 #include "gstavidemux.h"
52 #include "avi-ids.h"
53 #include <gst/gst-i18n-plugin.h>
54 #include <gst/base/gstadapter.h>
55
56
57 #define DIV_ROUND_UP(s,v) (((s) + ((v)-1)) / (v))
58
59 GST_DEBUG_CATEGORY_STATIC (avidemux_debug);
60 #define GST_CAT_DEFAULT avidemux_debug
61
62 static GstStaticPadTemplate sink_templ = GST_STATIC_PAD_TEMPLATE ("sink",
63     GST_PAD_SINK,
64     GST_PAD_ALWAYS,
65     GST_STATIC_CAPS ("video/x-msvideo")
66     );
67
68 static void gst_avi_demux_base_init (GstAviDemuxClass * klass);
69 static void gst_avi_demux_class_init (GstAviDemuxClass * klass);
70 static void gst_avi_demux_init (GstAviDemux * avi);
71 static void gst_avi_demux_finalize (GObject * object);
72
73 static void gst_avi_demux_reset (GstAviDemux * avi);
74
75 #if 0
76 static const GstEventMask *gst_avi_demux_get_event_mask (GstPad * pad);
77 #endif
78 static gboolean gst_avi_demux_handle_src_event (GstPad * pad, GstEvent * event);
79 static gboolean gst_avi_demux_handle_sink_event (GstPad * pad,
80     GstEvent * event);
81 static gboolean gst_avi_demux_push_event (GstAviDemux * avi, GstEvent * event);
82
83 #if 0
84 static const GstFormat *gst_avi_demux_get_src_formats (GstPad * pad);
85 #endif
86 static const GstQueryType *gst_avi_demux_get_src_query_types (GstPad * pad);
87 static gboolean gst_avi_demux_handle_src_query (GstPad * pad, GstQuery * query);
88 static gboolean gst_avi_demux_src_convert (GstPad * pad, GstFormat src_format,
89     gint64 src_value, GstFormat * dest_format, gint64 * dest_value);
90
91 static gboolean gst_avi_demux_do_seek (GstAviDemux * avi, GstSegment * segment);
92 static gboolean gst_avi_demux_handle_seek (GstAviDemux * avi, GstPad * pad,
93     GstEvent * event);
94 static gboolean gst_avi_demux_handle_seek_push (GstAviDemux * avi, GstPad * pad,
95     GstEvent * event);
96 static void gst_avi_demux_loop (GstPad * pad);
97 static gboolean gst_avi_demux_sink_activate (GstPad * sinkpad);
98 static gboolean gst_avi_demux_sink_activate_pull (GstPad * sinkpad,
99     gboolean active);
100 static gboolean gst_avi_demux_activate_push (GstPad * pad, gboolean active);
101 static GstFlowReturn gst_avi_demux_chain (GstPad * pad, GstBuffer * buf);
102
103 static void gst_avi_demux_set_index (GstElement * element, GstIndex * index);
104 static GstIndex *gst_avi_demux_get_index (GstElement * element);
105 static GstStateChangeReturn gst_avi_demux_change_state (GstElement * element,
106     GstStateChange transition);
107
108 static void gst_avi_demux_parse_idit (GstAviDemux * avi, GstBuffer * buf);
109
110 static GstElementClass *parent_class = NULL;
111
112 /* GObject methods */
113
114 GType
115 gst_avi_demux_get_type (void)
116 {
117   static GType avi_demux_type = 0;
118
119   if (!avi_demux_type) {
120     static const GTypeInfo avi_demux_info = {
121       sizeof (GstAviDemuxClass),
122       (GBaseInitFunc) gst_avi_demux_base_init,
123       NULL,
124       (GClassInitFunc) gst_avi_demux_class_init,
125       NULL,
126       NULL,
127       sizeof (GstAviDemux),
128       0,
129       (GInstanceInitFunc) gst_avi_demux_init,
130     };
131
132     avi_demux_type =
133         g_type_register_static (GST_TYPE_ELEMENT,
134         "GstAviDemux", &avi_demux_info, 0);
135   }
136
137   return avi_demux_type;
138 }
139
140 static void
141 gst_avi_demux_base_init (GstAviDemuxClass * klass)
142 {
143   static const GstElementDetails gst_avi_demux_details =
144       GST_ELEMENT_DETAILS ("Avi demuxer",
145       "Codec/Demuxer",
146       "Demultiplex an avi file into audio and video",
147       "Erik Walthinsen <omega@cse.ogi.edu>\n"
148       "Wim Taymans <wim.taymans@chello.be>\n"
149       "Thijs Vermeir <thijsvermeir@gmail.com>");
150   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
151   GstPadTemplate *videosrctempl, *audiosrctempl, *subsrctempl;
152   GstCaps *audcaps, *vidcaps, *subcaps;
153
154   audcaps = gst_riff_create_audio_template_caps ();
155   gst_caps_append (audcaps, gst_caps_new_simple ("audio/x-avi-unknown", NULL));
156   audiosrctempl = gst_pad_template_new ("audio_%02d",
157       GST_PAD_SRC, GST_PAD_SOMETIMES, audcaps);
158
159   vidcaps = gst_riff_create_video_template_caps ();
160   gst_caps_append (vidcaps, gst_riff_create_iavs_template_caps ());
161   gst_caps_append (vidcaps, gst_caps_new_simple ("video/x-avi-unknown", NULL));
162   videosrctempl = gst_pad_template_new ("video_%02d",
163       GST_PAD_SRC, GST_PAD_SOMETIMES, vidcaps);
164
165   subcaps = gst_caps_new_simple ("application/x-subtitle-avi", NULL);
166   subsrctempl = gst_pad_template_new ("subtitle_%02d",
167       GST_PAD_SRC, GST_PAD_SOMETIMES, subcaps);
168   gst_element_class_add_pad_template (element_class, audiosrctempl);
169   gst_element_class_add_pad_template (element_class, videosrctempl);
170   gst_element_class_add_pad_template (element_class, subsrctempl);
171   gst_element_class_add_pad_template (element_class,
172       gst_static_pad_template_get (&sink_templ));
173   gst_element_class_set_details (element_class, &gst_avi_demux_details);
174 }
175
176 static void
177 gst_avi_demux_class_init (GstAviDemuxClass * klass)
178 {
179   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
180   GObjectClass *gobject_class = (GObjectClass *) klass;
181
182   GST_DEBUG_CATEGORY_INIT (avidemux_debug, "avidemux",
183       0, "Demuxer for AVI streams");
184
185   parent_class = g_type_class_peek_parent (klass);
186
187   gobject_class->finalize = gst_avi_demux_finalize;
188   gstelement_class->change_state =
189       GST_DEBUG_FUNCPTR (gst_avi_demux_change_state);
190
191   gstelement_class->set_index = GST_DEBUG_FUNCPTR (gst_avi_demux_set_index);
192   gstelement_class->get_index = GST_DEBUG_FUNCPTR (gst_avi_demux_get_index);
193 }
194
195 static void
196 gst_avi_demux_init (GstAviDemux * avi)
197 {
198   avi->sinkpad = gst_pad_new_from_static_template (&sink_templ, "sink");
199   gst_pad_set_activate_function (avi->sinkpad,
200       GST_DEBUG_FUNCPTR (gst_avi_demux_sink_activate));
201   gst_pad_set_activatepull_function (avi->sinkpad,
202       GST_DEBUG_FUNCPTR (gst_avi_demux_sink_activate_pull));
203   gst_pad_set_activatepush_function (avi->sinkpad,
204       GST_DEBUG_FUNCPTR (gst_avi_demux_activate_push));
205   gst_pad_set_chain_function (avi->sinkpad,
206       GST_DEBUG_FUNCPTR (gst_avi_demux_chain));
207   gst_pad_set_event_function (avi->sinkpad,
208       GST_DEBUG_FUNCPTR (gst_avi_demux_handle_sink_event));
209   gst_element_add_pad (GST_ELEMENT_CAST (avi), avi->sinkpad);
210
211   avi->adapter = gst_adapter_new ();
212
213   gst_avi_demux_reset (avi);
214 }
215
216 static void
217 gst_avi_demux_finalize (GObject * object)
218 {
219   GstAviDemux *avi = GST_AVI_DEMUX (object);
220
221   GST_DEBUG ("AVI: finalize");
222
223   g_object_unref (avi->adapter);
224
225   G_OBJECT_CLASS (parent_class)->finalize (object);
226 }
227
228 static void
229 gst_avi_demux_reset_stream (GstAviDemux * avi, GstAviStream * stream)
230 {
231   g_free (stream->strh);
232   g_free (stream->strf.data);
233   g_free (stream->name);
234   g_free (stream->index);
235   g_free (stream->indexes);
236   if (stream->initdata)
237     gst_buffer_unref (stream->initdata);
238   if (stream->extradata)
239     gst_buffer_unref (stream->extradata);
240   if (stream->pad) {
241     if (stream->exposed) {
242       gst_pad_set_active (stream->pad, FALSE);
243       gst_element_remove_pad (GST_ELEMENT_CAST (avi), stream->pad);
244     } else
245       gst_object_unref (stream->pad);
246   }
247   if (stream->taglist) {
248     gst_tag_list_free (stream->taglist);
249     stream->taglist = NULL;
250   }
251   memset (stream, 0, sizeof (GstAviStream));
252 }
253
254 static void
255 gst_avi_demux_reset (GstAviDemux * avi)
256 {
257   gint i;
258
259   GST_DEBUG ("AVI: reset");
260
261   for (i = 0; i < avi->num_streams; i++)
262     gst_avi_demux_reset_stream (avi, &avi->stream[i]);
263
264   avi->header_state = GST_AVI_DEMUX_HEADER_TAG_LIST;
265   avi->num_streams = 0;
266   avi->num_v_streams = 0;
267   avi->num_a_streams = 0;
268   avi->num_t_streams = 0;
269   avi->main_stream = -1;
270
271   avi->state = GST_AVI_DEMUX_START;
272   avi->offset = 0;
273
274   avi->index_offset = 0;
275   g_free (avi->avih);
276   avi->avih = NULL;
277
278   if (avi->element_index)
279     gst_object_unref (avi->element_index);
280   avi->element_index = NULL;
281
282   if (avi->seg_event) {
283     gst_event_unref (avi->seg_event);
284     avi->seg_event = NULL;
285   }
286
287   if (avi->globaltags)
288     gst_tag_list_free (avi->globaltags);
289   avi->globaltags = NULL;
290
291   avi->got_tags = TRUE;         /* we always want to push global tags */
292   avi->have_eos = FALSE;
293   avi->seekable = TRUE;
294
295   gst_adapter_clear (avi->adapter);
296
297   gst_segment_init (&avi->segment, GST_FORMAT_TIME);
298 }
299
300
301 /* GstElement methods */
302
303 #if 0
304 static const GstFormat *
305 gst_avi_demux_get_src_formats (GstPad * pad)
306 {
307   GstAviStream *stream = gst_pad_get_element_private (pad);
308
309   static const GstFormat src_a_formats[] = {
310     GST_FORMAT_TIME,
311     GST_FORMAT_BYTES,
312     GST_FORMAT_DEFAULT,
313     0
314   };
315   static const GstFormat src_v_formats[] = {
316     GST_FORMAT_TIME,
317     GST_FORMAT_DEFAULT,
318     0
319   };
320
321   return (stream->strh->type == GST_RIFF_FCC_auds ?
322       src_a_formats : src_v_formats);
323 }
324 #endif
325
326 /* assumes stream->strf.auds->av_bps != 0 */
327 static inline GstClockTime
328 avi_stream_convert_bytes_to_time_unchecked (GstAviStream * stream,
329     guint64 bytes)
330 {
331   return gst_util_uint64_scale_int (bytes, GST_SECOND,
332       stream->strf.auds->av_bps);
333 }
334
335 static inline guint64
336 avi_stream_convert_time_to_bytes_unchecked (GstAviStream * stream,
337     GstClockTime time)
338 {
339   return gst_util_uint64_scale_int (time, stream->strf.auds->av_bps,
340       GST_SECOND);
341 }
342
343 /* assumes stream->strh->rate != 0 */
344 static inline GstClockTime
345 avi_stream_convert_frames_to_time_unchecked (GstAviStream * stream,
346     guint64 frames)
347 {
348   return gst_util_uint64_scale (frames, stream->strh->scale * GST_SECOND,
349       stream->strh->rate);
350 }
351
352 static inline guint64
353 avi_stream_convert_time_to_frames_unchecked (GstAviStream * stream,
354     GstClockTime time)
355 {
356   return gst_util_uint64_scale (time, stream->strh->rate,
357       stream->strh->scale * GST_SECOND);
358 }
359
360 static gboolean
361 gst_avi_demux_src_convert (GstPad * pad,
362     GstFormat src_format,
363     gint64 src_value, GstFormat * dest_format, gint64 * dest_value)
364 {
365   GstAviStream *stream = gst_pad_get_element_private (pad);
366   gboolean res = TRUE;
367
368   GST_LOG_OBJECT (pad,
369       "Received  src_format:%s, src_value:%" G_GUINT64_FORMAT
370       ", dest_format:%s", gst_format_get_name (src_format), src_value,
371       gst_format_get_name (*dest_format));
372
373   if (G_UNLIKELY (src_format == *dest_format)) {
374     *dest_value = src_value;
375     goto done;
376   }
377   if (G_UNLIKELY (!stream->strh || !stream->strf.data)) {
378     res = FALSE;
379     goto done;
380   }
381   if (G_UNLIKELY (stream->strh->type == GST_RIFF_FCC_vids &&
382           (src_format == GST_FORMAT_BYTES
383               || *dest_format == GST_FORMAT_BYTES))) {
384     res = FALSE;
385     goto done;
386   }
387
388   switch (src_format) {
389     case GST_FORMAT_TIME:
390       switch (*dest_format) {
391         case GST_FORMAT_BYTES:
392           *dest_value = gst_util_uint64_scale_int (src_value,
393               stream->strf.auds->av_bps, GST_SECOND);
394           break;
395         case GST_FORMAT_DEFAULT:
396           *dest_value =
397               gst_util_uint64_scale_round (src_value, stream->strh->rate,
398               stream->strh->scale * GST_SECOND);
399           break;
400         default:
401           res = FALSE;
402           break;
403       }
404       break;
405     case GST_FORMAT_BYTES:
406       switch (*dest_format) {
407         case GST_FORMAT_TIME:
408           if (stream->strf.auds->av_bps != 0) {
409             *dest_value = avi_stream_convert_bytes_to_time_unchecked (stream,
410                 src_value);
411           } else
412             res = FALSE;
413           break;
414         default:
415           res = FALSE;
416           break;
417       }
418       break;
419     case GST_FORMAT_DEFAULT:
420       switch (*dest_format) {
421         case GST_FORMAT_TIME:
422           *dest_value =
423               avi_stream_convert_frames_to_time_unchecked (stream, src_value);
424           break;
425         default:
426           res = FALSE;
427           break;
428       }
429       break;
430     default:
431       res = FALSE;
432   }
433
434 done:
435   GST_LOG_OBJECT (pad,
436       "Returning res:%d dest_format:%s dest_value:%" G_GUINT64_FORMAT, res,
437       gst_format_get_name (*dest_format), *dest_value);
438   return res;
439 }
440
441 static const GstQueryType *
442 gst_avi_demux_get_src_query_types (GstPad * pad)
443 {
444   static const GstQueryType src_types[] = {
445     GST_QUERY_POSITION,
446     GST_QUERY_DURATION,
447     GST_QUERY_SEEKING,
448     GST_QUERY_CONVERT,
449     0
450   };
451
452   return src_types;
453 }
454
455 static gboolean
456 gst_avi_demux_handle_src_query (GstPad * pad, GstQuery * query)
457 {
458   gboolean res = TRUE;
459   GstAviDemux *avi = GST_AVI_DEMUX (gst_pad_get_parent (pad));
460
461   GstAviStream *stream = gst_pad_get_element_private (pad);
462
463   if (!stream->strh || !stream->strf.data)
464     return gst_pad_query_default (pad, query);
465
466   switch (GST_QUERY_TYPE (query)) {
467     case GST_QUERY_POSITION:{
468       gint64 pos = 0;
469
470       GST_DEBUG ("pos query for stream %u: frames %u, bytes %u",
471           stream->num, stream->current_entry, stream->current_total);
472
473       /* FIXME, this looks clumsy */
474       if (stream->strh->type == GST_RIFF_FCC_auds) {
475         if (stream->is_vbr) {
476           /* VBR */
477           pos = gst_util_uint64_scale ((gint64) stream->current_entry *
478               stream->strh->scale, GST_SECOND, (guint64) stream->strh->rate);
479           GST_DEBUG_OBJECT (avi, "VBR convert frame %u, time %"
480               GST_TIME_FORMAT, stream->current_entry, GST_TIME_ARGS (pos));
481         } else if (stream->strf.auds->av_bps != 0) {
482           /* CBR */
483           pos = gst_util_uint64_scale (stream->current_total, GST_SECOND,
484               (guint64) stream->strf.auds->av_bps);
485           GST_DEBUG_OBJECT (avi,
486               "CBR convert bytes %u, time %" GST_TIME_FORMAT,
487               stream->current_total, GST_TIME_ARGS (pos));
488         } else if (stream->idx_n != 0 && stream->total_bytes != 0) {
489           /* calculate timestamps based on percentage of length */
490           guint64 xlen = avi->avih->us_frame *
491               avi->avih->tot_frames * GST_USECOND;
492
493           if (stream->is_vbr) {
494             pos = gst_util_uint64_scale (xlen, stream->current_entry,
495                 stream->idx_n);
496             GST_DEBUG_OBJECT (avi, "VBR perc convert frame %u, time %"
497                 GST_TIME_FORMAT, stream->current_entry, GST_TIME_ARGS (pos));
498           } else {
499             pos = gst_util_uint64_scale (xlen, stream->current_total,
500                 stream->total_bytes);
501             GST_DEBUG_OBJECT (avi,
502                 "CBR perc convert bytes %u, time %" GST_TIME_FORMAT,
503                 stream->current_total, GST_TIME_ARGS (pos));
504           }
505         } else {
506           /* we don't know */
507           res = FALSE;
508         }
509       } else {
510         if (stream->strh->rate != 0) {
511           pos = gst_util_uint64_scale ((guint64) stream->current_entry *
512               stream->strh->scale, GST_SECOND, (guint64) stream->strh->rate);
513         } else {
514           pos = stream->current_entry * avi->avih->us_frame * GST_USECOND;
515         }
516       }
517       if (res) {
518         GST_DEBUG ("pos query : %" GST_TIME_FORMAT, GST_TIME_ARGS (pos));
519         gst_query_set_position (query, GST_FORMAT_TIME, pos);
520       } else
521         GST_WARNING ("pos query failed");
522       break;
523     }
524     case GST_QUERY_DURATION:
525     {
526       GstFormat fmt;
527       GstClockTime duration;
528
529       /* only act on audio or video streams */
530       if (stream->strh->type != GST_RIFF_FCC_auds &&
531           stream->strh->type != GST_RIFF_FCC_vids) {
532         res = FALSE;
533         break;
534       }
535
536       /* take stream duration, fall back to avih duration */
537       if ((duration = stream->duration) == -1)
538         duration = avi->duration;
539
540       gst_query_parse_duration (query, &fmt, NULL);
541
542       switch (fmt) {
543         case GST_FORMAT_TIME:
544           gst_query_set_duration (query, fmt, duration);
545           break;
546         case GST_FORMAT_DEFAULT:
547         {
548           gint64 dur;
549           GST_DEBUG_OBJECT (query, "total frames is %" G_GUINT32_FORMAT,
550               stream->idx_n);
551
552           if (stream->idx_n >= 0)
553             gst_query_set_duration (query, fmt, stream->idx_n);
554           else if (gst_pad_query_convert (pad, GST_FORMAT_TIME,
555                   duration, &fmt, &dur))
556             gst_query_set_duration (query, fmt, dur);
557           break;
558         }
559         default:
560           res = FALSE;
561           break;
562       }
563       break;
564     }
565     case GST_QUERY_SEEKING:{
566       GstFormat fmt;
567
568       gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
569       if (fmt == GST_FORMAT_TIME) {
570         gboolean seekable = TRUE;
571
572         if (avi->streaming) {
573           seekable = avi->seekable;
574         }
575
576         gst_query_set_seeking (query, GST_FORMAT_TIME, seekable,
577             0, stream->duration);
578         res = TRUE;
579       }
580       break;
581     }
582     case GST_QUERY_CONVERT:{
583       GstFormat src_fmt, dest_fmt;
584       gint64 src_val, dest_val;
585
586       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
587       if ((res = gst_avi_demux_src_convert (pad, src_fmt, src_val, &dest_fmt,
588                   &dest_val)))
589         gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
590       else
591         res = gst_pad_query_default (pad, query);
592       break;
593     }
594     default:
595       res = gst_pad_query_default (pad, query);
596       break;
597   }
598
599   gst_object_unref (avi);
600   return res;
601 }
602
603 #if 0
604 static const GstEventMask *
605 gst_avi_demux_get_event_mask (GstPad * pad)
606 {
607   static const GstEventMask masks[] = {
608     {GST_EVENT_SEEK, GST_SEEK_METHOD_SET | GST_SEEK_FLAG_KEY_UNIT},
609     {0,}
610   };
611
612   return masks;
613 }
614 #endif
615
616 static guint64
617 gst_avi_demux_seek_streams (GstAviDemux * avi, guint64 offset, gboolean before)
618 {
619   GstAviStream *stream;
620   GstIndexEntry *entry;
621   gint i;
622   gint64 val, min = offset;
623
624   for (i = 0; i < avi->num_streams; i++) {
625     stream = &avi->stream[i];
626
627     entry = gst_index_get_assoc_entry (avi->element_index, stream->index_id,
628         before ? GST_INDEX_LOOKUP_BEFORE : GST_INDEX_LOOKUP_AFTER,
629         GST_ASSOCIATION_FLAG_NONE, GST_FORMAT_BYTES, offset);
630
631     if (before) {
632       if (entry) {
633         GST_DEBUG_OBJECT (avi, "stream %d, previous entry at %"
634             G_GUINT64_FORMAT, i, val);
635         gst_index_entry_assoc_map (entry, GST_FORMAT_BYTES, &val);
636         if (val < min)
637           min = val;
638       }
639       continue;
640     }
641
642     if (!entry) {
643       GST_DEBUG_OBJECT (avi, "no position for stream %d, assuming at start", i);
644       stream->current_entry = 0;
645       stream->current_total = 0;
646       continue;
647     }
648
649     gst_index_entry_assoc_map (entry, GST_FORMAT_BYTES, &val);
650     GST_DEBUG_OBJECT (avi, "stream %d, next entry at %" G_GUINT64_FORMAT,
651         i, val);
652
653     gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &val);
654     stream->current_total = val;
655     gst_index_entry_assoc_map (entry, GST_FORMAT_DEFAULT, &val);
656     stream->current_entry = val;
657   }
658
659   return min;
660 }
661
662 #define GST_AVI_SEEK_PUSH_DISPLACE     (4 * GST_SECOND)
663
664 static gboolean
665 gst_avi_demux_handle_sink_event (GstPad * pad, GstEvent * event)
666 {
667   gboolean res = TRUE;
668   GstAviDemux *avi = GST_AVI_DEMUX (gst_pad_get_parent (pad));
669
670   GST_DEBUG_OBJECT (avi,
671       "have event type %s: %p on sink pad", GST_EVENT_TYPE_NAME (event), event);
672
673   switch (GST_EVENT_TYPE (event)) {
674     case GST_EVENT_NEWSEGMENT:
675     {
676       GstFormat format;
677       gdouble rate, arate;
678       gint64 start, stop, time, offset = 0;
679       gboolean update;
680       GstSegment segment;
681       GstIndexEntry *entry;
682
683       /* some debug output */
684       gst_segment_init (&segment, GST_FORMAT_UNDEFINED);
685       gst_event_parse_new_segment_full (event, &update, &rate, &arate, &format,
686           &start, &stop, &time);
687       gst_segment_set_newsegment_full (&segment, update, rate, arate, format,
688           start, stop, time);
689       GST_DEBUG_OBJECT (avi,
690           "received format %d newsegment %" GST_SEGMENT_FORMAT, format,
691           &segment);
692
693       /* chain will send initial newsegment after pads have been added */
694       if (avi->state != GST_AVI_DEMUX_MOVI) {
695         GST_DEBUG_OBJECT (avi, "still starting, eating event");
696         goto exit;
697       }
698
699       /* we only expect a BYTE segment, e.g. following a seek */
700       if (format != GST_FORMAT_BYTES) {
701         GST_DEBUG_OBJECT (avi, "unsupported segment format, ignoring");
702         goto exit;
703       }
704
705       if (!avi->element_index) {
706         GST_WARNING_OBJECT (avi, "no index data, forcing EOS");
707         goto eos;
708       }
709
710       /* Let's check if we have an index entry for this position */
711       entry = gst_index_get_assoc_entry (avi->element_index, avi->index_id,
712           GST_INDEX_LOOKUP_AFTER, GST_ASSOCIATION_FLAG_NONE,
713           GST_FORMAT_BYTES, start);
714
715       /* we can not go where we have not yet been before ... */
716       if (!entry) {
717         GST_WARNING_OBJECT (avi, "insufficient index data, forcing EOS");
718         goto eos;
719       }
720
721       offset = start;
722       gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &time);
723       gst_index_entry_assoc_map (entry, GST_FORMAT_BYTES, &start);
724       stop = GST_CLOCK_TIME_NONE;
725
726       /* compensate for slack */
727       if (time)
728         time += GST_AVI_SEEK_PUSH_DISPLACE;
729
730       /* set up segment and send downstream */
731       gst_segment_set_newsegment_full (&avi->segment, update, rate, arate,
732           GST_FORMAT_TIME, time, stop, time);
733       GST_DEBUG_OBJECT (avi, "Pushing newseg update %d, rate %g, "
734           "applied rate %g, format %d, start %" G_GINT64_FORMAT ", "
735           "stop %" G_GINT64_FORMAT, update, rate, arate, GST_FORMAT_TIME,
736           time, stop);
737       gst_avi_demux_push_event (avi,
738           gst_event_new_new_segment_full (update, rate, arate, GST_FORMAT_TIME,
739               time, stop, time));
740
741       GST_DEBUG_OBJECT (avi, "next chunk expected at %" G_GINT64_FORMAT, start);
742
743       /* adjust state for streaming thread accordingly */
744       avi->offset = offset;
745       gst_avi_demux_seek_streams (avi, offset, FALSE);
746
747       /* set up streaming thread */
748       avi->offset = offset;
749       avi->todrop = start - offset;
750
751     exit:
752       /* in any case, clear leftover in current segment, if any */
753       gst_adapter_clear (avi->adapter);
754       gst_event_unref (event);
755       res = TRUE;
756       break;
757     eos:
758       /* set up for EOS */
759       avi->have_eos = TRUE;
760       goto exit;
761     }
762     case GST_EVENT_EOS:
763     {
764       if (avi->state != GST_AVI_DEMUX_MOVI) {
765         gst_event_unref (event);
766         GST_ELEMENT_ERROR (avi, STREAM, DEMUX,
767             (NULL), ("got eos and didn't receive a complete header object"));
768       } else if (!gst_avi_demux_push_event (avi, event)) {
769         GST_ELEMENT_ERROR (avi, STREAM, DEMUX,
770             (NULL), ("got eos but no streams (yet)"));
771       }
772       break;
773     }
774     case GST_EVENT_FLUSH_STOP:
775     {
776       gint i;
777
778       gst_adapter_clear (avi->adapter);
779       avi->have_eos = FALSE;
780       for (i = 0; i < avi->num_streams; i++) {
781         avi->stream[i].last_flow = GST_FLOW_OK;
782         avi->stream[i].discont = TRUE;
783       }
784       /* fall through to default case so that the event gets passed downstream */
785     }
786     default:
787       res = gst_pad_event_default (pad, event);
788       break;
789   }
790
791   gst_object_unref (avi);
792
793   return res;
794 }
795
796 static gboolean
797 gst_avi_demux_handle_src_event (GstPad * pad, GstEvent * event)
798 {
799   gboolean res = TRUE;
800   GstAviDemux *avi = GST_AVI_DEMUX (gst_pad_get_parent (pad));
801
802   GST_DEBUG_OBJECT (avi,
803       "have event type %s: %p on src pad", GST_EVENT_TYPE_NAME (event), event);
804
805   switch (GST_EVENT_TYPE (event)) {
806     case GST_EVENT_SEEK:
807       /* handle seeking only in pull mode */
808       if (!avi->streaming) {
809         res = gst_avi_demux_handle_seek (avi, pad, event);
810       } else {
811         res = gst_avi_demux_handle_seek_push (avi, pad, event);
812       }
813       gst_event_unref (event);
814       break;
815     case GST_EVENT_QOS:
816     case GST_EVENT_NAVIGATION:
817       res = FALSE;
818       gst_event_unref (event);
819       break;
820     default:
821       res = gst_pad_event_default (pad, event);
822       break;
823   }
824
825   gst_object_unref (avi);
826
827   return res;
828 }
829
830 /* streaming helper (push) */
831
832 /*
833  * gst_avi_demux_peek_chunk_info:
834  * @avi: Avi object
835  * @tag: holder for tag
836  * @size: holder for tag size
837  *
838  * Peek next chunk info (tag and size)
839  *
840  * Returns: TRUE when one chunk info has been got
841  */
842 static gboolean
843 gst_avi_demux_peek_chunk_info (GstAviDemux * avi, guint32 * tag, guint32 * size)
844 {
845   const guint8 *data = NULL;
846
847   if (gst_adapter_available (avi->adapter) < 8)
848     return FALSE;
849
850   data = gst_adapter_peek (avi->adapter, 8);
851   *tag = GST_READ_UINT32_LE (data);
852   *size = GST_READ_UINT32_LE (data + 4);
853
854   return TRUE;
855 }
856
857 /*
858  * gst_avi_demux_peek_chunk:
859  * @avi: Avi object
860  * @tag: holder for tag
861  * @size: holder for tag size
862  *
863  * Peek enough data for one full chunk
864  *
865  * Returns: %TRUE when one chunk has been got
866  */
867 static gboolean
868 gst_avi_demux_peek_chunk (GstAviDemux * avi, guint32 * tag, guint32 * size)
869 {
870   guint32 peek_size = 0;
871   gint available;
872
873   if (!gst_avi_demux_peek_chunk_info (avi, tag, size))
874     goto peek_failed;
875
876   /* size 0 -> empty data buffer would surprise most callers,
877    * large size -> do not bother trying to squeeze that into adapter,
878    * so we throw poor man's exception, which can be caught if caller really
879    * wants to handle 0 size chunk */
880   if (!(*size) || (*size) >= (1 << 30))
881     goto strange_size;
882
883   peek_size = (*size + 1) & ~1;
884   available = gst_adapter_available (avi->adapter);
885
886   GST_DEBUG_OBJECT (avi,
887       "Need to peek chunk of %d bytes to read chunk %" GST_FOURCC_FORMAT
888       ", %d bytes available", *size, GST_FOURCC_ARGS (*tag), available);
889
890   if (available < (8 + peek_size))
891     goto need_more;
892
893   return TRUE;
894
895   /* ERRORS */
896 peek_failed:
897   {
898     GST_INFO_OBJECT (avi, "Failed to peek");
899     return FALSE;
900   }
901 strange_size:
902   {
903     GST_INFO_OBJECT (avi,
904         "Invalid/unexpected chunk size %d for tag %" GST_FOURCC_FORMAT, *size,
905         GST_FOURCC_ARGS (*tag));
906     /* chain should give up */
907     avi->abort_buffering = TRUE;
908     return FALSE;
909   }
910 need_more:
911   {
912     GST_INFO_OBJECT (avi, "need more %d < %" G_GUINT32_FORMAT,
913         available, 8 + peek_size);
914     return FALSE;
915   }
916 }
917
918 /* AVI init */
919
920 /*
921  * gst_avi_demux_parse_file_header:
922  * @element: caller element (used for errors/debug).
923  * @buf: input data to be used for parsing.
924  *
925  * "Open" a RIFF/AVI file. The buffer should be at least 12
926  * bytes long. Takes ownership of @buf.
927  *
928  * Returns: TRUE if the file is a RIFF/AVI file, FALSE otherwise.
929  *          Throws an error, caller should error out (fatal).
930  */
931 static gboolean
932 gst_avi_demux_parse_file_header (GstElement * element, GstBuffer * buf)
933 {
934   guint32 doctype;
935   GstClockTime stamp;
936
937   stamp = gst_util_get_timestamp ();
938
939   /* riff_parse posts an error */
940   if (!gst_riff_parse_file_header (element, buf, &doctype))
941     return FALSE;
942
943   if (doctype != GST_RIFF_RIFF_AVI)
944     goto not_avi;
945
946   stamp = gst_util_get_timestamp () - stamp;
947   GST_DEBUG_OBJECT (element, "header parsing took %" GST_TIME_FORMAT,
948       GST_TIME_ARGS (stamp));
949
950   return TRUE;
951
952   /* ERRORS */
953 not_avi:
954   {
955     GST_ELEMENT_ERROR (element, STREAM, WRONG_TYPE, (NULL),
956         ("File is not an AVI file: %" GST_FOURCC_FORMAT,
957             GST_FOURCC_ARGS (doctype)));
958     return FALSE;
959   }
960 }
961
962 /*
963  * Read AVI file tag when streaming
964  */
965 static GstFlowReturn
966 gst_avi_demux_stream_init_push (GstAviDemux * avi)
967 {
968   if (gst_adapter_available (avi->adapter) >= 12) {
969     GstBuffer *tmp;
970
971     tmp = gst_adapter_take_buffer (avi->adapter, 12);
972
973     GST_DEBUG ("Parsing avi header");
974     if (!gst_avi_demux_parse_file_header (GST_ELEMENT_CAST (avi), tmp)) {
975       return GST_FLOW_ERROR;
976     }
977     GST_DEBUG ("header ok");
978     avi->offset += 12;
979
980     avi->state = GST_AVI_DEMUX_HEADER;
981   }
982   return GST_FLOW_OK;
983 }
984
985 /*
986  * Read AVI file tag
987  */
988 static GstFlowReturn
989 gst_avi_demux_stream_init_pull (GstAviDemux * avi)
990 {
991   GstFlowReturn res;
992   GstBuffer *buf = NULL;
993
994   res = gst_pad_pull_range (avi->sinkpad, avi->offset, 12, &buf);
995   if (res != GST_FLOW_OK)
996     return res;
997   else if (!gst_avi_demux_parse_file_header (GST_ELEMENT_CAST (avi), buf))
998     goto wrong_header;
999
1000   avi->offset += 12;
1001
1002   return GST_FLOW_OK;
1003
1004   /* ERRORS */
1005 wrong_header:
1006   {
1007     GST_DEBUG_OBJECT (avi, "error parsing file header");
1008     return GST_FLOW_ERROR;
1009   }
1010 }
1011
1012 /* AVI header handling */
1013
1014 /*
1015  * gst_avi_demux_parse_avih:
1016  * @avi: caller element (used for errors/debug).
1017  * @buf: input data to be used for parsing.
1018  * @avih: pointer to structure (filled in by function) containing
1019  *        stream information (such as flags, number of streams, etc.).
1020  *
1021  * Read 'avih' header. Discards buffer after use.
1022  *
1023  * Returns: TRUE on success, FALSE otherwise. Throws an error if
1024  *          the header is invalid. The caller should error out
1025  *          (fatal).
1026  */
1027 static gboolean
1028 gst_avi_demux_parse_avih (GstAviDemux * avi,
1029     GstBuffer * buf, gst_riff_avih ** _avih)
1030 {
1031   gst_riff_avih *avih;
1032
1033   if (buf == NULL)
1034     goto no_buffer;
1035
1036   if (GST_BUFFER_SIZE (buf) < sizeof (gst_riff_avih))
1037     goto avih_too_small;
1038
1039   avih = g_memdup (GST_BUFFER_DATA (buf), GST_BUFFER_SIZE (buf));
1040
1041 #if (G_BYTE_ORDER == G_BIG_ENDIAN)
1042   avih->us_frame = GUINT32_FROM_LE (avih->us_frame);
1043   avih->max_bps = GUINT32_FROM_LE (avih->max_bps);
1044   avih->pad_gran = GUINT32_FROM_LE (avih->pad_gran);
1045   avih->flags = GUINT32_FROM_LE (avih->flags);
1046   avih->tot_frames = GUINT32_FROM_LE (avih->tot_frames);
1047   avih->init_frames = GUINT32_FROM_LE (avih->init_frames);
1048   avih->streams = GUINT32_FROM_LE (avih->streams);
1049   avih->bufsize = GUINT32_FROM_LE (avih->bufsize);
1050   avih->width = GUINT32_FROM_LE (avih->width);
1051   avih->height = GUINT32_FROM_LE (avih->height);
1052   avih->scale = GUINT32_FROM_LE (avih->scale);
1053   avih->rate = GUINT32_FROM_LE (avih->rate);
1054   avih->start = GUINT32_FROM_LE (avih->start);
1055   avih->length = GUINT32_FROM_LE (avih->length);
1056 #endif
1057
1058   /* debug stuff */
1059   GST_INFO_OBJECT (avi, "avih tag found:");
1060   GST_INFO_OBJECT (avi, " us_frame    %u", avih->us_frame);
1061   GST_INFO_OBJECT (avi, " max_bps     %u", avih->max_bps);
1062   GST_INFO_OBJECT (avi, " pad_gran    %u", avih->pad_gran);
1063   GST_INFO_OBJECT (avi, " flags       0x%08x", avih->flags);
1064   GST_INFO_OBJECT (avi, " tot_frames  %u", avih->tot_frames);
1065   GST_INFO_OBJECT (avi, " init_frames %u", avih->init_frames);
1066   GST_INFO_OBJECT (avi, " streams     %u", avih->streams);
1067   GST_INFO_OBJECT (avi, " bufsize     %u", avih->bufsize);
1068   GST_INFO_OBJECT (avi, " width       %u", avih->width);
1069   GST_INFO_OBJECT (avi, " height      %u", avih->height);
1070   GST_INFO_OBJECT (avi, " scale       %u", avih->scale);
1071   GST_INFO_OBJECT (avi, " rate        %u", avih->rate);
1072   GST_INFO_OBJECT (avi, " start       %u", avih->start);
1073   GST_INFO_OBJECT (avi, " length      %u", avih->length);
1074
1075   *_avih = avih;
1076   gst_buffer_unref (buf);
1077
1078   if (avih->us_frame != 0 && avih->tot_frames != 0)
1079     avi->duration =
1080         (guint64) avih->us_frame * (guint64) avih->tot_frames * 1000;
1081   else
1082     avi->duration = GST_CLOCK_TIME_NONE;
1083
1084   GST_INFO_OBJECT (avi, " header duration  %" GST_TIME_FORMAT,
1085       GST_TIME_ARGS (avi->duration));
1086
1087   return TRUE;
1088
1089   /* ERRORS */
1090 no_buffer:
1091   {
1092     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("No buffer"));
1093     return FALSE;
1094   }
1095 avih_too_small:
1096   {
1097     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
1098         ("Too small avih (%d available, %d needed)",
1099             GST_BUFFER_SIZE (buf), (int) sizeof (gst_riff_avih)));
1100     gst_buffer_unref (buf);
1101     return FALSE;
1102   }
1103 }
1104
1105 /*
1106  * gst_avi_demux_parse_superindex:
1107  * @avi: caller element (used for debugging/errors).
1108  * @buf: input data to use for parsing.
1109  * @locations: locations in the file (byte-offsets) that contain
1110  *             the actual indexes (see get_avi_demux_parse_subindex()).
1111  *             The array ends with GST_BUFFER_OFFSET_NONE.
1112  *
1113  * Reads superindex (openDML-2 spec stuff) from the provided data.
1114  *
1115  * Returns: TRUE on success, FALSE otherwise. Indexes should be skipped
1116  *          on error, but they are not fatal.
1117  */
1118 static gboolean
1119 gst_avi_demux_parse_superindex (GstAviDemux * avi,
1120     GstBuffer * buf, guint64 ** _indexes)
1121 {
1122   guint8 *data;
1123   guint16 bpe = 16;
1124   guint32 num, i;
1125   guint64 *indexes;
1126   guint size;
1127
1128   *_indexes = NULL;
1129
1130   size = buf ? GST_BUFFER_SIZE (buf) : 0;
1131   if (size < 24)
1132     goto too_small;
1133
1134   data = GST_BUFFER_DATA (buf);
1135
1136   /* check type of index. The opendml2 specs state that
1137    * there should be 4 dwords per array entry. Type can be
1138    * either frame or field (and we don't care). */
1139   if (GST_READ_UINT16_LE (data) != 4 ||
1140       (data[2] & 0xfe) != 0x0 || data[3] != 0x0) {
1141     GST_WARNING_OBJECT (avi,
1142         "Superindex for stream has unexpected "
1143         "size_entry %d (bytes) or flags 0x%02x/0x%02x",
1144         GST_READ_UINT16_LE (data), data[2], data[3]);
1145     bpe = GST_READ_UINT16_LE (data) * 4;
1146   }
1147   num = GST_READ_UINT32_LE (&data[4]);
1148
1149   GST_DEBUG_OBJECT (avi, "got %d indexes", num);
1150
1151   indexes = g_new (guint64, num + 1);
1152   for (i = 0; i < num; i++) {
1153     if (size < 24 + bpe * (i + 1))
1154       break;
1155     indexes[i] = GST_READ_UINT64_LE (&data[24 + bpe * i]);
1156     GST_DEBUG_OBJECT (avi, "index %d at %" G_GUINT64_FORMAT, i, indexes[i]);
1157   }
1158   indexes[i] = GST_BUFFER_OFFSET_NONE;
1159   *_indexes = indexes;
1160
1161   gst_buffer_unref (buf);
1162
1163   return TRUE;
1164
1165   /* ERRORS */
1166 too_small:
1167   {
1168     GST_ERROR_OBJECT (avi,
1169         "Not enough data to parse superindex (%d available, 24 needed)", size);
1170     if (buf)
1171       gst_buffer_unref (buf);
1172     return FALSE;
1173   }
1174 }
1175
1176 /* add an entry to the index of a stream. @num should be an estimate of the
1177  * total amount of index entries for all streams and is used to dynamically
1178  * allocate memory for the index entries. */
1179 static inline gboolean
1180 gst_avi_demux_add_index (GstAviDemux * avi, GstAviStream * stream,
1181     guint num, GstAviIndexEntry * entry)
1182 {
1183   /* ensure index memory */
1184   if (G_UNLIKELY (stream->idx_n >= stream->idx_max)) {
1185     guint idx_max = stream->idx_max;
1186     GstAviIndexEntry *new_idx;
1187
1188     /* we need to make some more room */
1189     if (idx_max == 0) {
1190       /* initial size guess, assume each stream has an equal amount of entries,
1191        * overshoot with at least 8K */
1192       idx_max = (num / avi->num_streams) + (8192 / sizeof (GstAviIndexEntry));
1193     } else {
1194       idx_max += 8192 / sizeof (GstAviIndexEntry);
1195       GST_DEBUG_OBJECT (avi, "expanded index from %u to %u",
1196           stream->idx_max, idx_max);
1197     }
1198     new_idx = g_try_renew (GstAviIndexEntry, stream->index, idx_max);
1199     /* out of memory, if this fails stream->index is untouched. */
1200     if (G_UNLIKELY (!new_idx))
1201       return FALSE;
1202     /* use new index */
1203     stream->index = new_idx;
1204     stream->idx_max = idx_max;
1205   }
1206
1207   /* update entry total and stream stats. The entry total can be converted to
1208    * the timestamp of the entry easily. */
1209   if (stream->strh->type == GST_RIFF_FCC_auds) {
1210     gint blockalign;
1211
1212     if (stream->is_vbr) {
1213       entry->total = stream->total_blocks;
1214     } else {
1215       entry->total = stream->total_bytes;
1216     }
1217     blockalign = stream->strf.auds->blockalign;
1218     if (blockalign > 0)
1219       stream->total_blocks += DIV_ROUND_UP (entry->size, blockalign);
1220     else
1221       stream->total_blocks++;
1222   } else {
1223     if (stream->is_vbr) {
1224       entry->total = stream->idx_n;
1225     } else {
1226       entry->total = stream->total_bytes;
1227     }
1228   }
1229   stream->total_bytes += entry->size;
1230   if (ENTRY_IS_KEYFRAME (entry))
1231     stream->n_keyframes++;
1232
1233   /* and add */
1234   GST_LOG_OBJECT (avi,
1235       "Adding stream %u, index entry %d, kf %d, size %u "
1236       ", offset %" G_GUINT64_FORMAT ", total %" G_GUINT64_FORMAT, stream->num,
1237       stream->idx_n, ENTRY_IS_KEYFRAME (entry), entry->size, entry->offset,
1238       entry->total);
1239   stream->index[stream->idx_n++] = *entry;
1240
1241   return TRUE;
1242 }
1243
1244 /* given @entry_n in @stream, calculate info such as timestamps and
1245  * offsets for the entry. */
1246 static void
1247 gst_avi_demux_get_buffer_info (GstAviDemux * avi, GstAviStream * stream,
1248     guint entry_n, GstClockTime * timestamp, GstClockTime * ts_end,
1249     guint64 * offset, guint64 * offset_end)
1250 {
1251   GstAviIndexEntry *entry;
1252
1253   entry = &stream->index[entry_n];
1254
1255   if (stream->is_vbr) {
1256     /* VBR stream next timestamp */
1257     if (stream->strh->type == GST_RIFF_FCC_auds) {
1258       if (timestamp)
1259         *timestamp =
1260             avi_stream_convert_frames_to_time_unchecked (stream, entry->total);
1261       if (ts_end)
1262         *ts_end = avi_stream_convert_frames_to_time_unchecked (stream,
1263             entry->total + 1);
1264     } else {
1265       if (timestamp)
1266         *timestamp =
1267             avi_stream_convert_frames_to_time_unchecked (stream, entry_n);
1268       if (ts_end)
1269         *ts_end = avi_stream_convert_frames_to_time_unchecked (stream,
1270             entry_n + 1);
1271     }
1272   } else if (stream->strh->type == GST_RIFF_FCC_auds) {
1273     /* constant rate stream */
1274     if (timestamp)
1275       *timestamp =
1276           avi_stream_convert_bytes_to_time_unchecked (stream, entry->total);
1277     if (ts_end)
1278       *ts_end = avi_stream_convert_bytes_to_time_unchecked (stream,
1279           entry->total + entry->size);
1280   }
1281   if (stream->strh->type == GST_RIFF_FCC_vids) {
1282     /* video offsets are the frame number */
1283     if (offset)
1284       *offset = entry_n;
1285     if (offset_end)
1286       *offset_end = entry_n + 1;
1287   } else {
1288     /* no offsets for audio */
1289     if (offset)
1290       *offset = -1;
1291     if (offset_end)
1292       *offset_end = -1;
1293   }
1294 }
1295
1296 /* collect and debug stats about the indexes for all streams.
1297  * This method is also responsible for filling in the stream duration
1298  * as measured by the amount of index entries.
1299  *
1300  * Returns TRUE if the index is not empty, else FALSE */
1301 static gboolean
1302 gst_avi_demux_do_index_stats (GstAviDemux * avi)
1303 {
1304   guint total_idx = 0;
1305   guint i;
1306 #ifndef GST_DISABLE_GST_DEBUG
1307   guint total_max = 0;
1308 #endif
1309
1310   /* get stream stats now */
1311   for (i = 0; i < avi->num_streams; i++) {
1312     GstAviStream *stream;
1313
1314     if (G_UNLIKELY (!(stream = &avi->stream[i])))
1315       continue;
1316     if (G_UNLIKELY (!stream->strh))
1317       continue;
1318     if (G_UNLIKELY (!stream->index || stream->idx_n == 0))
1319       continue;
1320
1321     /* we interested in the end_ts of the last entry, which is the total
1322      * duration of this stream */
1323     gst_avi_demux_get_buffer_info (avi, stream, stream->idx_n - 1,
1324         NULL, &stream->idx_duration, NULL, NULL);
1325
1326     total_idx += stream->idx_n;
1327 #ifndef GST_DISABLE_GST_DEBUG
1328     total_max += stream->idx_max;
1329 #endif
1330     GST_INFO_OBJECT (avi, "Stream %d, dur %" GST_TIME_FORMAT ", %6u entries, "
1331         "%5u keyframes, entry size = %2u, total size = %10u, allocated %10u",
1332         i, GST_TIME_ARGS (stream->idx_duration), stream->idx_n,
1333         stream->n_keyframes, (guint) sizeof (GstAviIndexEntry),
1334         (guint) (stream->idx_n * sizeof (GstAviIndexEntry)),
1335         (guint) (stream->idx_max * sizeof (GstAviIndexEntry)));
1336   }
1337   total_idx *= sizeof (GstAviIndexEntry);
1338 #ifndef GST_DISABLE_GST_DEBUG
1339   total_max *= sizeof (GstAviIndexEntry);
1340 #endif
1341   GST_INFO_OBJECT (avi, "%u bytes for index vs %u ideally, %u wasted",
1342       total_max, total_idx, total_max - total_idx);
1343
1344   if (total_idx == 0) {
1345     GST_WARNING_OBJECT (avi, "Index is empty !");
1346     return FALSE;
1347   }
1348   return TRUE;
1349 }
1350
1351 /*
1352  * gst_avi_demux_parse_subindex:
1353  * @avi: Avi object
1354  * @buf: input data to use for parsing.
1355  * @stream: stream context.
1356  * @entries_list: a list (returned by the function) containing all the
1357  *           indexes parsed in this specific subindex. The first
1358  *           entry is also a pointer to allocated memory that needs
1359  *           to be free´ed. May be NULL if no supported indexes were
1360  *           found.
1361  *
1362  * Reads superindex (openDML-2 spec stuff) from the provided data.
1363  * The buffer should contain a GST_RIFF_TAG_ix?? chunk.
1364  *
1365  * Returns: TRUE on success, FALSE otherwise. Errors are fatal, we
1366  *          throw an error, caller should bail out asap.
1367  */
1368 static gboolean
1369 gst_avi_demux_parse_subindex (GstAviDemux * avi, GstAviStream * stream,
1370     GstBuffer * buf)
1371 {
1372   guint8 *data;
1373   guint16 bpe;
1374   guint32 num, i;
1375   guint64 baseoff;
1376   guint size;
1377
1378   if (!buf)
1379     return TRUE;
1380
1381   size = GST_BUFFER_SIZE (buf);
1382
1383   /* check size */
1384   if (size < 24)
1385     goto too_small;
1386
1387   data = GST_BUFFER_DATA (buf);
1388
1389   /* We don't support index-data yet */
1390   if (data[3] & 0x80)
1391     goto not_implemented;
1392
1393   /* check type of index. The opendml2 specs state that
1394    * there should be 4 dwords per array entry. Type can be
1395    * either frame or field (and we don't care). */
1396   bpe = (data[2] & 0x01) ? 12 : 8;
1397   if (GST_READ_UINT16_LE (data) != bpe / 4 ||
1398       (data[2] & 0xfe) != 0x0 || data[3] != 0x1) {
1399     GST_WARNING_OBJECT (avi,
1400         "Superindex for stream %d has unexpected "
1401         "size_entry %d (bytes) or flags 0x%02x/0x%02x",
1402         stream->num, GST_READ_UINT16_LE (data), data[2], data[3]);
1403     bpe = GST_READ_UINT16_LE (data) * 4;
1404   }
1405   num = GST_READ_UINT32_LE (&data[4]);
1406   baseoff = GST_READ_UINT64_LE (&data[12]);
1407
1408   /* If there's nothing, just return ! */
1409   if (num == 0)
1410     goto empty_index;
1411
1412   GST_INFO_OBJECT (avi, "Parsing subindex, nr_entries = %6d", num);
1413
1414   for (i = 0; i < num; i++) {
1415     GstAviIndexEntry entry;
1416
1417     if (size < 24 + bpe * (i + 1))
1418       break;
1419
1420     /* fill in offset and size. offset contains the keyframe flag in the
1421      * upper bit*/
1422     entry.offset = baseoff + GST_READ_UINT32_LE (&data[24 + bpe * i]);
1423     entry.size = GST_READ_UINT32_LE (&data[24 + bpe * i + 4]);
1424     /* handle flags */
1425     if (stream->strh->type == GST_RIFF_FCC_auds) {
1426       /* all audio frames are keyframes */
1427       ENTRY_SET_KEYFRAME (&entry);
1428     } else {
1429       /* else read flags */
1430       entry.flags = (entry.size & 0x80000000) ? 0 : GST_AVI_KEYFRAME;
1431     }
1432     entry.size &= ~0x80000000;
1433
1434     /* and add */
1435     if (G_UNLIKELY (!gst_avi_demux_add_index (avi, stream, num, &entry)))
1436       goto out_of_mem;
1437   }
1438   gst_buffer_unref (buf);
1439
1440   return TRUE;
1441
1442   /* ERRORS */
1443 too_small:
1444   {
1445     GST_ERROR_OBJECT (avi,
1446         "Not enough data to parse subindex (%d available, 24 needed)", size);
1447     gst_buffer_unref (buf);
1448     return TRUE;                /* continue */
1449   }
1450 not_implemented:
1451   {
1452     GST_ELEMENT_ERROR (avi, STREAM, NOT_IMPLEMENTED, (NULL),
1453         ("Subindex-is-data is not implemented"));
1454     gst_buffer_unref (buf);
1455     return FALSE;
1456   }
1457 empty_index:
1458   {
1459     GST_DEBUG_OBJECT (avi, "the index is empty");
1460     gst_buffer_unref (buf);
1461     return TRUE;
1462   }
1463 out_of_mem:
1464   {
1465     GST_ELEMENT_ERROR (avi, RESOURCE, NO_SPACE_LEFT, (NULL),
1466         ("Cannot allocate memory for %u*%u=%u bytes",
1467             (guint) sizeof (GstAviIndexEntry), num,
1468             (guint) sizeof (GstAviIndexEntry) * num));
1469     gst_buffer_unref (buf);
1470     return FALSE;
1471   }
1472 }
1473
1474 #if 0
1475 /*
1476  * Read AVI index when streaming
1477  */
1478 static void
1479 gst_avi_demux_read_subindexes_push (GstAviDemux * avi)
1480 {
1481   guint32 tag = 0, size;
1482   GstBuffer *buf = NULL;
1483   gint i, n;
1484
1485   GST_DEBUG_OBJECT (avi, "read subindexes for %d streams", avi->num_streams);
1486
1487   for (n = 0; n < avi->num_streams; n++) {
1488     GstAviStream *stream = &avi->stream[n];
1489
1490     for (i = 0; stream->indexes[i] != GST_BUFFER_OFFSET_NONE; i++) {
1491       if (!gst_avi_demux_peek_chunk (avi, &tag, &size))
1492         continue;
1493       else if ((tag != GST_MAKE_FOURCC ('i', 'x', '0' + stream->num / 10,
1494                   '0' + stream->num % 10)) &&
1495           (tag != GST_MAKE_FOURCC ('0' + stream->num / 10,
1496                   '0' + stream->num % 10, 'i', 'x'))) {
1497         GST_WARNING_OBJECT (avi, "Not an ix## chunk (%" GST_FOURCC_FORMAT ")",
1498             GST_FOURCC_ARGS (tag));
1499         continue;
1500       }
1501
1502       avi->offset += 8 + GST_ROUND_UP_2 (size);
1503
1504       buf = gst_buffer_new ();
1505       GST_BUFFER_DATA (buf) = gst_adapter_take (avi->adapter, size);
1506       GST_BUFFER_SIZE (buf) = size;
1507
1508       if (!gst_avi_demux_parse_subindex (avi, stream, buf))
1509         continue;
1510     }
1511
1512     g_free (stream->indexes);
1513     stream->indexes = NULL;
1514   }
1515   /* get stream stats now */
1516   avi->have_index = gst_avi_demux_do_index_stats (avi);
1517 }
1518 #endif
1519
1520 /*
1521  * Read AVI index
1522  */
1523 static void
1524 gst_avi_demux_read_subindexes_pull (GstAviDemux * avi)
1525 {
1526   guint32 tag;
1527   GstBuffer *buf;
1528   gint i, n;
1529
1530   GST_DEBUG_OBJECT (avi, "read subindexes for %d streams", avi->num_streams);
1531
1532   for (n = 0; n < avi->num_streams; n++) {
1533     GstAviStream *stream = &avi->stream[n];
1534
1535     if (stream->indexes == NULL)
1536       continue;
1537
1538     for (i = 0; stream->indexes[i] != GST_BUFFER_OFFSET_NONE; i++) {
1539       if (gst_riff_read_chunk (GST_ELEMENT_CAST (avi), avi->sinkpad,
1540               &stream->indexes[i], &tag, &buf) != GST_FLOW_OK)
1541         continue;
1542       else if ((tag != GST_MAKE_FOURCC ('i', 'x', '0' + stream->num / 10,
1543                   '0' + stream->num % 10)) &&
1544           (tag != GST_MAKE_FOURCC ('0' + stream->num / 10,
1545                   '0' + stream->num % 10, 'i', 'x'))) {
1546         /* Some ODML files (created by god knows what muxer) have a ##ix format
1547          * instead of the 'official' ix##. They are still valid though. */
1548         GST_WARNING_OBJECT (avi, "Not an ix## chunk (%" GST_FOURCC_FORMAT ")",
1549             GST_FOURCC_ARGS (tag));
1550         gst_buffer_unref (buf);
1551         continue;
1552       }
1553
1554       if (!gst_avi_demux_parse_subindex (avi, stream, buf))
1555         continue;
1556     }
1557
1558     g_free (stream->indexes);
1559     stream->indexes = NULL;
1560   }
1561   /* get stream stats now */
1562   avi->have_index = gst_avi_demux_do_index_stats (avi);
1563 }
1564
1565 /*
1566  * gst_avi_demux_riff_parse_vprp:
1567  * @element: caller element (used for debugging/error).
1568  * @buf: input data to be used for parsing, stripped from header.
1569  * @vprp: a pointer (returned by this function) to a filled-in vprp
1570  *        structure. Caller should free it.
1571  *
1572  * Parses a video stream´s vprp. This function takes ownership of @buf.
1573  *
1574  * Returns: TRUE if parsing succeeded, otherwise FALSE. The stream
1575  *          should be skipped on error, but it is not fatal.
1576  */
1577 static gboolean
1578 gst_avi_demux_riff_parse_vprp (GstElement * element,
1579     GstBuffer * buf, gst_riff_vprp ** _vprp)
1580 {
1581   gst_riff_vprp *vprp;
1582   gint k;
1583
1584   g_return_val_if_fail (buf != NULL, FALSE);
1585   g_return_val_if_fail (_vprp != NULL, FALSE);
1586
1587   if (GST_BUFFER_SIZE (buf) < G_STRUCT_OFFSET (gst_riff_vprp, field_info))
1588     goto too_small;
1589
1590   vprp = g_memdup (GST_BUFFER_DATA (buf), GST_BUFFER_SIZE (buf));
1591
1592 #if (G_BYTE_ORDER == G_BIG_ENDIAN)
1593   vprp->format_token = GUINT32_FROM_LE (vprp->format_token);
1594   vprp->standard = GUINT32_FROM_LE (vprp->standard);
1595   vprp->vert_rate = GUINT32_FROM_LE (vprp->vert_rate);
1596   vprp->hor_t_total = GUINT32_FROM_LE (vprp->hor_t_total);
1597   vprp->vert_lines = GUINT32_FROM_LE (vprp->vert_lines);
1598   vprp->aspect = GUINT32_FROM_LE (vprp->aspect);
1599   vprp->width = GUINT32_FROM_LE (vprp->width);
1600   vprp->height = GUINT32_FROM_LE (vprp->height);
1601   vprp->fields = GUINT32_FROM_LE (vprp->fields);
1602 #endif
1603
1604   /* size checking */
1605   /* calculate fields based on size */
1606   k = (GST_BUFFER_SIZE (buf) - G_STRUCT_OFFSET (gst_riff_vprp, field_info)) /
1607       vprp->fields;
1608   if (vprp->fields > k) {
1609     GST_WARNING_OBJECT (element,
1610         "vprp header indicated %d fields, only %d available", vprp->fields, k);
1611     vprp->fields = k;
1612   }
1613   if (vprp->fields > GST_RIFF_VPRP_VIDEO_FIELDS) {
1614     GST_WARNING_OBJECT (element,
1615         "vprp header indicated %d fields, at most %d supported", vprp->fields,
1616         GST_RIFF_VPRP_VIDEO_FIELDS);
1617     vprp->fields = GST_RIFF_VPRP_VIDEO_FIELDS;
1618   }
1619 #if (G_BYTE_ORDER == G_BIG_ENDIAN)
1620   for (k = 0; k < vprp->fields; k++) {
1621     gst_riff_vprp_video_field_desc *fd;
1622
1623     fd = &vprp->field_info[k];
1624     fd->compressed_bm_height = GUINT32_FROM_LE (fd->compressed_bm_height);
1625     fd->compressed_bm_width = GUINT32_FROM_LE (fd->compressed_bm_width);
1626     fd->valid_bm_height = GUINT32_FROM_LE (fd->valid_bm_height);
1627     fd->valid_bm_width = GUINT16_FROM_LE (fd->valid_bm_width);
1628     fd->valid_bm_x_offset = GUINT16_FROM_LE (fd->valid_bm_x_offset);
1629     fd->valid_bm_y_offset = GUINT32_FROM_LE (fd->valid_bm_y_offset);
1630     fd->video_x_t_offset = GUINT32_FROM_LE (fd->video_x_t_offset);
1631     fd->video_y_start = GUINT32_FROM_LE (fd->video_y_start);
1632   }
1633 #endif
1634
1635   /* debug */
1636   GST_INFO_OBJECT (element, "vprp tag found in context vids:");
1637   GST_INFO_OBJECT (element, " format_token  %d", vprp->format_token);
1638   GST_INFO_OBJECT (element, " standard      %d", vprp->standard);
1639   GST_INFO_OBJECT (element, " vert_rate     %d", vprp->vert_rate);
1640   GST_INFO_OBJECT (element, " hor_t_total   %d", vprp->hor_t_total);
1641   GST_INFO_OBJECT (element, " vert_lines    %d", vprp->vert_lines);
1642   GST_INFO_OBJECT (element, " aspect        %d:%d", vprp->aspect >> 16,
1643       vprp->aspect & 0xffff);
1644   GST_INFO_OBJECT (element, " width         %d", vprp->width);
1645   GST_INFO_OBJECT (element, " height        %d", vprp->height);
1646   GST_INFO_OBJECT (element, " fields        %d", vprp->fields);
1647   for (k = 0; k < vprp->fields; k++) {
1648     gst_riff_vprp_video_field_desc *fd;
1649
1650     fd = &(vprp->field_info[k]);
1651     GST_INFO_OBJECT (element, " field %u description:", k);
1652     GST_INFO_OBJECT (element, "  compressed_bm_height  %d",
1653         fd->compressed_bm_height);
1654     GST_INFO_OBJECT (element, "  compressed_bm_width  %d",
1655         fd->compressed_bm_width);
1656     GST_INFO_OBJECT (element, "  valid_bm_height       %d",
1657         fd->valid_bm_height);
1658     GST_INFO_OBJECT (element, "  valid_bm_width        %d", fd->valid_bm_width);
1659     GST_INFO_OBJECT (element, "  valid_bm_x_offset     %d",
1660         fd->valid_bm_x_offset);
1661     GST_INFO_OBJECT (element, "  valid_bm_y_offset     %d",
1662         fd->valid_bm_y_offset);
1663     GST_INFO_OBJECT (element, "  video_x_t_offset      %d",
1664         fd->video_x_t_offset);
1665     GST_INFO_OBJECT (element, "  video_y_start         %d", fd->video_y_start);
1666   }
1667
1668   gst_buffer_unref (buf);
1669
1670   *_vprp = vprp;
1671
1672   return TRUE;
1673
1674   /* ERRORS */
1675 too_small:
1676   {
1677     GST_ERROR_OBJECT (element,
1678         "Too small vprp (%d available, at least %d needed)",
1679         GST_BUFFER_SIZE (buf),
1680         (int) G_STRUCT_OFFSET (gst_riff_vprp, field_info));
1681     gst_buffer_unref (buf);
1682     return FALSE;
1683   }
1684 }
1685
1686 static void
1687 gst_avi_demux_expose_streams (GstAviDemux * avi, gboolean force)
1688 {
1689   guint i;
1690
1691   GST_DEBUG_OBJECT (avi, "force : %d", force);
1692
1693   for (i = 0; i < avi->num_streams; i++) {
1694     GstAviStream *stream = &avi->stream[i];
1695
1696     if (force || stream->idx_n != 0) {
1697       GST_LOG_OBJECT (avi, "Added pad %s with caps %" GST_PTR_FORMAT,
1698           GST_PAD_NAME (stream->pad), GST_PAD_CAPS (stream->pad));
1699       gst_element_add_pad ((GstElement *) avi, stream->pad);
1700       stream->exposed = TRUE;
1701       if (avi->main_stream == -1)
1702         avi->main_stream = i;
1703     } else {
1704       GST_WARNING_OBJECT (avi, "Stream #%d doesn't have any entry, removing it",
1705           i);
1706       gst_avi_demux_reset_stream (avi, stream);
1707     }
1708   }
1709 }
1710
1711 /*
1712  * gst_avi_demux_parse_stream:
1713  * @avi: calling element (used for debugging/errors).
1714  * @buf: input buffer used to parse the stream.
1715  *
1716  * Parses all subchunks in a strl chunk (which defines a single
1717  * stream). Discards the buffer after use. This function will
1718  * increment the stream counter internally.
1719  *
1720  * Returns: whether the stream was identified successfully.
1721  *          Errors are not fatal. It does indicate the stream
1722  *          was skipped.
1723  */
1724 static gboolean
1725 gst_avi_demux_parse_stream (GstAviDemux * avi, GstBuffer * buf)
1726 {
1727   GstAviStream *stream;
1728   GstElementClass *klass;
1729   GstPadTemplate *templ;
1730   GstBuffer *sub = NULL;
1731   guint offset = 4;
1732   guint32 tag = 0;
1733   gchar *codec_name = NULL, *padname = NULL;
1734   const gchar *tag_name;
1735   GstCaps *caps = NULL;
1736   GstPad *pad;
1737   GstElement *element;
1738   gboolean got_strh = FALSE, got_strf = FALSE, got_vprp = FALSE;
1739   gst_riff_vprp *vprp = NULL;
1740
1741   element = GST_ELEMENT_CAST (avi);
1742
1743   GST_DEBUG_OBJECT (avi, "Parsing stream");
1744
1745   if (avi->num_streams >= GST_AVI_DEMUX_MAX_STREAMS) {
1746     GST_WARNING_OBJECT (avi,
1747         "maximum no of streams (%d) exceeded, ignoring stream",
1748         GST_AVI_DEMUX_MAX_STREAMS);
1749     gst_buffer_unref (buf);
1750     /* not a fatal error, let's say */
1751     return TRUE;
1752   }
1753
1754   stream = &avi->stream[avi->num_streams];
1755
1756   /* initial settings */
1757   stream->idx_duration = GST_CLOCK_TIME_NONE;
1758   stream->hdr_duration = GST_CLOCK_TIME_NONE;
1759   stream->duration = GST_CLOCK_TIME_NONE;
1760
1761   while (gst_riff_parse_chunk (element, buf, &offset, &tag, &sub)) {
1762     /* sub can be NULL if the chunk is empty */
1763     if (sub == NULL) {
1764       GST_DEBUG_OBJECT (avi, "ignoring empty chunk %" GST_FOURCC_FORMAT,
1765           GST_FOURCC_ARGS (tag));
1766       continue;
1767     }
1768     switch (tag) {
1769       case GST_RIFF_TAG_strh:
1770       {
1771         gst_riff_strh *strh;
1772
1773         if (got_strh) {
1774           GST_WARNING_OBJECT (avi, "Ignoring additional strh chunk");
1775           break;
1776         }
1777         if (!gst_riff_parse_strh (element, sub, &stream->strh)) {
1778           /* ownership given away */
1779           sub = NULL;
1780           GST_WARNING_OBJECT (avi, "Failed to parse strh chunk");
1781           goto fail;
1782         }
1783         sub = NULL;
1784         strh = stream->strh;
1785         /* sanity check; stream header frame rate matches global header
1786          * frame duration */
1787         if (stream->strh->type == GST_RIFF_FCC_vids) {
1788           GstClockTime s_dur;
1789           GstClockTime h_dur = avi->avih->us_frame * GST_USECOND;
1790
1791           s_dur = gst_util_uint64_scale (GST_SECOND, strh->scale, strh->rate);
1792           GST_DEBUG_OBJECT (avi, "verifying stream framerate %d/%d, "
1793               "frame duration = %d ms", strh->rate, strh->scale,
1794               (gint) (s_dur / GST_MSECOND));
1795           if (h_dur > (10 * GST_MSECOND) && (s_dur > 10 * h_dur)) {
1796             strh->rate = GST_SECOND / GST_USECOND;
1797             strh->scale = h_dur / GST_USECOND;
1798             GST_DEBUG_OBJECT (avi, "correcting stream framerate to %d/%d",
1799                 strh->rate, strh->scale);
1800           }
1801         }
1802         /* determine duration as indicated by header */
1803         stream->hdr_duration = gst_util_uint64_scale ((guint64) strh->length *
1804             strh->scale, GST_SECOND, (guint64) strh->rate);
1805         GST_INFO ("Stream duration according to header: %" GST_TIME_FORMAT,
1806             GST_TIME_ARGS (stream->hdr_duration));
1807         if (stream->hdr_duration == 0)
1808           stream->hdr_duration = GST_CLOCK_TIME_NONE;
1809
1810         got_strh = TRUE;
1811         break;
1812       }
1813       case GST_RIFF_TAG_strf:
1814       {
1815         gboolean res = FALSE;
1816
1817         if (got_strf) {
1818           GST_WARNING_OBJECT (avi, "Ignoring additional strf chunk");
1819           break;
1820         }
1821         if (!got_strh) {
1822           GST_ERROR_OBJECT (avi, "Found strf chunk before strh chunk");
1823           goto fail;
1824         }
1825         switch (stream->strh->type) {
1826           case GST_RIFF_FCC_vids:
1827             stream->is_vbr = TRUE;
1828             res = gst_riff_parse_strf_vids (element, sub,
1829                 &stream->strf.vids, &stream->extradata);
1830             sub = NULL;
1831             GST_DEBUG_OBJECT (element, "marking video as VBR, res %d", res);
1832             break;
1833           case GST_RIFF_FCC_auds:
1834             stream->is_vbr = (stream->strh->samplesize == 0)
1835                 && stream->strh->scale > 1;
1836             res =
1837                 gst_riff_parse_strf_auds (element, sub, &stream->strf.auds,
1838                 &stream->extradata);
1839             sub = NULL;
1840             GST_DEBUG_OBJECT (element, "marking audio as VBR:%d, res %d",
1841                 stream->is_vbr, res);
1842             break;
1843           case GST_RIFF_FCC_iavs:
1844             stream->is_vbr = TRUE;
1845             res = gst_riff_parse_strf_iavs (element, sub,
1846                 &stream->strf.iavs, &stream->extradata);
1847             sub = NULL;
1848             GST_DEBUG_OBJECT (element, "marking iavs as VBR, res %d", res);
1849             break;
1850           case GST_RIFF_FCC_txts:
1851             /* nothing to parse here */
1852             stream->is_vbr = (stream->strh->samplesize == 0)
1853                 && (stream->strh->scale > 1);
1854             res = TRUE;
1855             break;
1856           default:
1857             GST_ERROR_OBJECT (avi,
1858                 "Don´t know how to handle stream type %" GST_FOURCC_FORMAT,
1859                 GST_FOURCC_ARGS (stream->strh->type));
1860             break;
1861         }
1862         if (sub) {
1863           gst_buffer_unref (sub);
1864           sub = NULL;
1865         }
1866         if (!res)
1867           goto fail;
1868         got_strf = TRUE;
1869         break;
1870       }
1871       case GST_RIFF_TAG_vprp:
1872       {
1873         if (got_vprp) {
1874           GST_WARNING_OBJECT (avi, "Ignoring additional vprp chunk");
1875           break;
1876         }
1877         if (!got_strh) {
1878           GST_ERROR_OBJECT (avi, "Found vprp chunk before strh chunk");
1879           goto fail;
1880         }
1881         if (!got_strf) {
1882           GST_ERROR_OBJECT (avi, "Found vprp chunk before strf chunk");
1883           goto fail;
1884         }
1885
1886         if (!gst_avi_demux_riff_parse_vprp (element, sub, &vprp)) {
1887           GST_WARNING_OBJECT (avi, "Failed to parse vprp chunk");
1888           /* not considered fatal */
1889           g_free (vprp);
1890           vprp = NULL;
1891         } else
1892           got_vprp = TRUE;
1893         sub = NULL;
1894         break;
1895       }
1896       case GST_RIFF_TAG_strd:
1897         if (stream->initdata)
1898           gst_buffer_unref (stream->initdata);
1899         stream->initdata = sub;
1900         sub = NULL;
1901         break;
1902       case GST_RIFF_TAG_strn:
1903         g_free (stream->name);
1904         if (sub != NULL) {
1905           stream->name =
1906               g_strndup ((gchar *) GST_BUFFER_DATA (sub),
1907               (gsize) GST_BUFFER_SIZE (sub));
1908           gst_buffer_unref (sub);
1909           sub = NULL;
1910         } else {
1911           stream->name = g_strdup ("");
1912         }
1913         GST_DEBUG_OBJECT (avi, "stream name: %s", stream->name);
1914         break;
1915       default:
1916         if (tag == GST_MAKE_FOURCC ('i', 'n', 'd', 'x') ||
1917             tag == GST_MAKE_FOURCC ('i', 'x', '0' + avi->num_streams / 10,
1918                 '0' + avi->num_streams % 10)) {
1919           g_free (stream->indexes);
1920           gst_avi_demux_parse_superindex (avi, sub, &stream->indexes);
1921           stream->superindex = TRUE;
1922           sub = NULL;
1923           break;
1924         }
1925         GST_WARNING_OBJECT (avi,
1926             "Unknown stream header tag %" GST_FOURCC_FORMAT ", ignoring",
1927             GST_FOURCC_ARGS (tag));
1928         /* fall-through */
1929       case GST_RIFF_TAG_JUNQ:
1930       case GST_RIFF_TAG_JUNK:
1931         break;
1932     }
1933     if (sub != NULL) {
1934       gst_buffer_unref (sub);
1935       sub = NULL;
1936     }
1937   }
1938
1939   if (!got_strh) {
1940     GST_WARNING_OBJECT (avi, "Failed to find strh chunk");
1941     goto fail;
1942   }
1943
1944   if (!got_strf) {
1945     GST_WARNING_OBJECT (avi, "Failed to find strf chunk");
1946     goto fail;
1947   }
1948
1949   /* get class to figure out the template */
1950   klass = GST_ELEMENT_GET_CLASS (avi);
1951
1952   /* we now have all info, let´s set up a pad and a caps and be done */
1953   /* create stream name + pad */
1954   switch (stream->strh->type) {
1955     case GST_RIFF_FCC_vids:{
1956       guint32 fourcc;
1957
1958       fourcc = (stream->strf.vids->compression) ?
1959           stream->strf.vids->compression : stream->strh->fcc_handler;
1960       padname = g_strdup_printf ("video_%02d", avi->num_v_streams);
1961       templ = gst_element_class_get_pad_template (klass, "video_%02d");
1962       caps = gst_riff_create_video_caps (fourcc, stream->strh,
1963           stream->strf.vids, stream->extradata, stream->initdata, &codec_name);
1964       if (!caps) {
1965         caps = gst_caps_new_simple ("video/x-avi-unknown", "fourcc",
1966             GST_TYPE_FOURCC, fourcc, NULL);
1967       } else if (got_vprp && vprp) {
1968         guint32 aspect_n, aspect_d;
1969         gint n, d;
1970
1971         aspect_n = vprp->aspect >> 16;
1972         aspect_d = vprp->aspect & 0xffff;
1973         /* calculate the pixel aspect ratio using w/h and aspect ratio */
1974         n = aspect_n * stream->strf.vids->height;
1975         d = aspect_d * stream->strf.vids->width;
1976         if (n && d)
1977           gst_caps_set_simple (caps, "pixel-aspect-ratio", GST_TYPE_FRACTION,
1978               n, d, NULL);
1979         /* very local, not needed elsewhere */
1980         g_free (vprp);
1981         vprp = NULL;
1982       }
1983       tag_name = GST_TAG_VIDEO_CODEC;
1984       avi->num_v_streams++;
1985       break;
1986     }
1987     case GST_RIFF_FCC_auds:{
1988       padname = g_strdup_printf ("audio_%02d", avi->num_a_streams);
1989       templ = gst_element_class_get_pad_template (klass, "audio_%02d");
1990       caps = gst_riff_create_audio_caps (stream->strf.auds->format,
1991           stream->strh, stream->strf.auds, stream->extradata,
1992           stream->initdata, &codec_name);
1993       if (!caps) {
1994         caps = gst_caps_new_simple ("audio/x-avi-unknown", "codec_id",
1995             G_TYPE_INT, stream->strf.auds->format, NULL);
1996       }
1997       tag_name = GST_TAG_AUDIO_CODEC;
1998       avi->num_a_streams++;
1999       break;
2000     }
2001     case GST_RIFF_FCC_iavs:{
2002       guint32 fourcc = stream->strh->fcc_handler;
2003
2004       padname = g_strdup_printf ("video_%02d", avi->num_v_streams);
2005       templ = gst_element_class_get_pad_template (klass, "video_%02d");
2006       caps = gst_riff_create_iavs_caps (fourcc, stream->strh,
2007           stream->strf.iavs, stream->extradata, stream->initdata, &codec_name);
2008       if (!caps) {
2009         caps = gst_caps_new_simple ("video/x-avi-unknown", "fourcc",
2010             GST_TYPE_FOURCC, fourcc, NULL);
2011       }
2012       tag_name = GST_TAG_VIDEO_CODEC;
2013       avi->num_v_streams++;
2014       break;
2015     }
2016     case GST_RIFF_FCC_txts:{
2017       padname = g_strdup_printf ("subtitle_%02d", avi->num_t_streams);
2018       templ = gst_element_class_get_pad_template (klass, "subtitle_%02d");
2019       caps = gst_caps_new_simple ("application/x-subtitle-avi", NULL);
2020       tag_name = NULL;
2021       avi->num_t_streams++;
2022       break;
2023     }
2024     default:
2025       g_assert_not_reached ();
2026   }
2027
2028   /* no caps means no stream */
2029   if (!caps) {
2030     GST_ERROR_OBJECT (element, "Did not find caps for stream %s", padname);
2031     goto fail;
2032   }
2033
2034   GST_DEBUG_OBJECT (element, "codec-name=%s",
2035       (codec_name ? codec_name : "NULL"));
2036   GST_DEBUG_OBJECT (element, "caps=%" GST_PTR_FORMAT, caps);
2037
2038   /* set proper settings and add it */
2039   if (stream->pad)
2040     gst_object_unref (stream->pad);
2041   pad = stream->pad = gst_pad_new_from_template (templ, padname);
2042   g_free (padname);
2043
2044   gst_pad_use_fixed_caps (pad);
2045 #if 0
2046   gst_pad_set_formats_function (pad,
2047       GST_DEBUG_FUNCPTR (gst_avi_demux_get_src_formats));
2048   gst_pad_set_event_mask_function (pad,
2049       GST_DEBUG_FUNCPTR (gst_avi_demux_get_event_mask));
2050 #endif
2051   gst_pad_set_event_function (pad,
2052       GST_DEBUG_FUNCPTR (gst_avi_demux_handle_src_event));
2053   gst_pad_set_query_type_function (pad,
2054       GST_DEBUG_FUNCPTR (gst_avi_demux_get_src_query_types));
2055   gst_pad_set_query_function (pad,
2056       GST_DEBUG_FUNCPTR (gst_avi_demux_handle_src_query));
2057 #if 0
2058   gst_pad_set_convert_function (pad,
2059       GST_DEBUG_FUNCPTR (gst_avi_demux_src_convert));
2060 #endif
2061
2062   if (avi->element_index)
2063     gst_index_get_writer_id (avi->element_index, GST_OBJECT_CAST (stream->pad),
2064         &stream->index_id);
2065
2066   stream->num = avi->num_streams;
2067
2068   stream->start_entry = 0;
2069   stream->step_entry = 0;
2070   stream->stop_entry = 0;
2071
2072   stream->current_entry = -1;
2073   stream->current_total = 0;
2074
2075   stream->last_flow = GST_FLOW_OK;
2076   stream->discont = TRUE;
2077
2078   stream->total_bytes = 0;
2079   stream->total_blocks = 0;
2080   stream->n_keyframes = 0;
2081
2082   stream->idx_n = 0;
2083   stream->idx_max = 0;
2084
2085   gst_pad_set_element_private (pad, stream);
2086   avi->num_streams++;
2087
2088   gst_pad_set_caps (pad, caps);
2089   gst_pad_set_active (pad, TRUE);
2090   gst_caps_unref (caps);
2091
2092   /* make tags */
2093   if (codec_name) {
2094     if (!stream->taglist)
2095       stream->taglist = gst_tag_list_new ();
2096
2097     avi->got_tags = TRUE;
2098
2099     gst_tag_list_add (stream->taglist, GST_TAG_MERGE_APPEND, tag_name,
2100         codec_name, NULL);
2101     g_free (codec_name);
2102   }
2103
2104   gst_buffer_unref (buf);
2105
2106   return TRUE;
2107
2108   /* ERRORS */
2109 fail:
2110   {
2111     /* unref any mem that may be in use */
2112     if (buf)
2113       gst_buffer_unref (buf);
2114     if (sub)
2115       gst_buffer_unref (sub);
2116     g_free (vprp);
2117     g_free (codec_name);
2118     gst_avi_demux_reset_stream (avi, stream);
2119     avi->num_streams++;
2120     return FALSE;
2121   }
2122 }
2123
2124 /*
2125  * gst_avi_demux_parse_odml:
2126  * @avi: calling element (used for debug/error).
2127  * @buf: input buffer to be used for parsing.
2128  *
2129  * Read an openDML-2.0 extension header. Fills in the frame number
2130  * in the avi demuxer object when reading succeeds.
2131  */
2132 static void
2133 gst_avi_demux_parse_odml (GstAviDemux * avi, GstBuffer * buf)
2134 {
2135   guint32 tag = 0;
2136   guint offset = 4;
2137   GstBuffer *sub = NULL;
2138
2139   while (gst_riff_parse_chunk (GST_ELEMENT_CAST (avi), buf, &offset, &tag,
2140           &sub)) {
2141     switch (tag) {
2142       case GST_RIFF_TAG_dmlh:{
2143         gst_riff_dmlh dmlh, *_dmlh;
2144         guint size;
2145
2146         /* sub == NULL is possible and means an empty buffer */
2147         size = sub ? GST_BUFFER_SIZE (sub) : 0;
2148
2149         /* check size */
2150         if (size < sizeof (gst_riff_dmlh)) {
2151           GST_ERROR_OBJECT (avi,
2152               "DMLH entry is too small (%d bytes, %d needed)",
2153               size, (int) sizeof (gst_riff_dmlh));
2154           goto next;
2155         }
2156         _dmlh = (gst_riff_dmlh *) GST_BUFFER_DATA (sub);
2157         dmlh.totalframes = GST_READ_UINT32_LE (&_dmlh->totalframes);
2158
2159         GST_INFO_OBJECT (avi, "dmlh tag found: totalframes: %u",
2160             dmlh.totalframes);
2161
2162         avi->avih->tot_frames = dmlh.totalframes;
2163         goto next;
2164       }
2165
2166       default:
2167         GST_WARNING_OBJECT (avi,
2168             "Unknown tag %" GST_FOURCC_FORMAT " in ODML header",
2169             GST_FOURCC_ARGS (tag));
2170         /* fall-through */
2171       case GST_RIFF_TAG_JUNQ:
2172       case GST_RIFF_TAG_JUNK:
2173       next:
2174         /* skip and move to next chunk */
2175         if (sub) {
2176           gst_buffer_unref (sub);
2177           sub = NULL;
2178         }
2179         break;
2180     }
2181   }
2182   if (buf)
2183     gst_buffer_unref (buf);
2184 }
2185
2186 /* Index helper */
2187 static guint
2188 gst_avi_demux_index_last (GstAviDemux * avi, GstAviStream * stream)
2189 {
2190   return stream->idx_n - 1;
2191 }
2192
2193 /* find a previous entry in the index with the given flags */
2194 static guint
2195 gst_avi_demux_index_prev (GstAviDemux * avi, GstAviStream * stream,
2196     guint last, gboolean keyframe)
2197 {
2198   GstAviIndexEntry *entry;
2199   guint i;
2200
2201   for (i = last; i > 0; i--) {
2202     entry = &stream->index[i - 1];
2203     if (!keyframe || ENTRY_IS_KEYFRAME (entry)) {
2204       return i - 1;
2205     }
2206   }
2207   return 0;
2208 }
2209
2210 static guint
2211 gst_avi_demux_index_next (GstAviDemux * avi, GstAviStream * stream,
2212     guint last, gboolean keyframe)
2213 {
2214   GstAviIndexEntry *entry;
2215   gint i;
2216
2217   for (i = last + 1; i < stream->idx_n; i++) {
2218     entry = &stream->index[i];
2219     if (!keyframe || ENTRY_IS_KEYFRAME (entry)) {
2220       return i;
2221     }
2222   }
2223   return stream->idx_n - 1;
2224 }
2225
2226 static guint
2227 gst_avi_demux_index_entry_search (GstAviIndexEntry * entry, guint64 * total)
2228 {
2229   if (entry->total < *total)
2230     return -1;
2231   else if (entry->total > *total)
2232     return 1;
2233   return 0;
2234 }
2235
2236 /*
2237  * gst_avi_demux_index_for_time:
2238  * @avi: Avi object
2239  * @stream: the stream
2240  * @time: a time position
2241  *
2242  * Finds the index entry which time is less or equal than the requested time.
2243  * Try to avoid binary search when we can convert the time to an index
2244  * position directly (for example for video frames with a fixed duration).
2245  *
2246  * Returns: the found position in the index.
2247  */
2248 static guint
2249 gst_avi_demux_index_for_time (GstAviDemux * avi,
2250     GstAviStream * stream, guint64 time)
2251 {
2252   guint index = -1;
2253   guint64 total;
2254
2255   GST_LOG_OBJECT (avi, "search time:%" GST_TIME_FORMAT, GST_TIME_ARGS (time));
2256
2257   /* easy (and common) cases */
2258   if (time == 0 || stream->idx_n == 0)
2259     return 0;
2260   if (time >= stream->idx_duration)
2261     return stream->idx_n - 1;
2262
2263   /* figure out where we need to go. For that we convert the time to an
2264    * index entry or we convert it to a total and then do a binary search. */
2265   if (stream->is_vbr) {
2266     /* VBR stream next timestamp */
2267     if (stream->strh->type == GST_RIFF_FCC_auds) {
2268       total = avi_stream_convert_time_to_frames_unchecked (stream, time);
2269     } else {
2270       index = avi_stream_convert_time_to_frames_unchecked (stream, time);
2271     }
2272   } else {
2273     /* constant rate stream */
2274     total = avi_stream_convert_time_to_bytes_unchecked (stream, time);
2275   }
2276
2277   if (index == -1) {
2278     GstAviIndexEntry *entry;
2279
2280     /* no index, find index with binary search on total */
2281     GST_LOG_OBJECT (avi, "binary search for entry with total %"
2282         G_GUINT64_FORMAT, total);
2283
2284     entry = gst_util_array_binary_search (stream->index,
2285         stream->idx_n, sizeof (GstAviIndexEntry),
2286         (GCompareDataFunc) gst_avi_demux_index_entry_search,
2287         GST_SEARCH_MODE_BEFORE, &total, NULL);
2288
2289     if (entry == NULL) {
2290       GST_LOG_OBJECT (avi, "not found, assume index 0");
2291       index = 0;
2292     } else {
2293       index = entry - stream->index;
2294       GST_LOG_OBJECT (avi, "found at %u", index);
2295     }
2296   } else {
2297     GST_LOG_OBJECT (avi, "converted time to index %u", index);
2298   }
2299
2300   return index;
2301 }
2302
2303 static inline GstAviStream *
2304 gst_avi_demux_stream_for_id (GstAviDemux * avi, guint32 id)
2305 {
2306   guint stream_nr;
2307   GstAviStream *stream;
2308
2309   /* get the stream for this entry */
2310   stream_nr = CHUNKID_TO_STREAMNR (id);
2311   if (G_UNLIKELY (stream_nr >= avi->num_streams)) {
2312     GST_WARNING_OBJECT (avi, "invalid stream nr %d", stream_nr);
2313     return NULL;
2314   }
2315   stream = &avi->stream[stream_nr];
2316   if (G_UNLIKELY (!stream->strh)) {
2317     GST_WARNING_OBJECT (avi, "Unhandled stream %d, skipping", stream_nr);
2318     return NULL;
2319   }
2320   return stream;
2321 }
2322
2323 /*
2324  * gst_avi_demux_parse_index:
2325  * @avi: calling element (used for debugging/errors).
2326  * @buf: buffer containing the full index.
2327  *
2328  * Read index entries from the provided buffer.
2329  * The buffer should contain a GST_RIFF_TAG_idx1 chunk.
2330  */
2331 static gboolean
2332 gst_avi_demux_parse_index (GstAviDemux * avi, GstBuffer * buf)
2333 {
2334   guint64 pos_before;
2335   guint8 *data;
2336   guint size;
2337   guint i, num, n;
2338   gst_riff_index_entry *index;
2339   GstClockTime stamp;
2340   GstAviStream *stream;
2341   GstAviIndexEntry entry;
2342   guint32 id;
2343
2344   if (!buf)
2345     return FALSE;
2346
2347   data = GST_BUFFER_DATA (buf);
2348   size = GST_BUFFER_SIZE (buf);
2349
2350   stamp = gst_util_get_timestamp ();
2351
2352   /* see how many items in the index */
2353   num = size / sizeof (gst_riff_index_entry);
2354   if (num == 0)
2355     goto empty_list;
2356
2357   GST_INFO_OBJECT (avi, "Parsing index, nr_entries = %6d", num);
2358
2359   index = (gst_riff_index_entry *) data;
2360   pos_before = avi->offset;
2361
2362   /* figure out if the index is 0 based or relative to the MOVI start */
2363   entry.offset = GST_READ_UINT32_LE (&index[0].offset);
2364   if (entry.offset < avi->offset) {
2365     avi->index_offset = avi->offset + 8;
2366     GST_DEBUG ("index_offset = %" G_GUINT64_FORMAT, avi->index_offset);
2367   } else {
2368     avi->index_offset = 0;
2369     GST_DEBUG ("index is 0 based");
2370   }
2371
2372   for (i = 0, n = 0; i < num; i++) {
2373     id = GST_READ_UINT32_LE (&index[i].id);
2374     entry.offset = GST_READ_UINT32_LE (&index[i].offset);
2375
2376     /* some sanity checks */
2377     if (G_UNLIKELY (id == GST_RIFF_rec || id == 0 ||
2378             (entry.offset == 0 && n > 0)))
2379       continue;
2380
2381     /* get the stream for this entry */
2382     stream = gst_avi_demux_stream_for_id (avi, id);
2383     if (G_UNLIKELY (!stream))
2384       continue;
2385
2386     /* handle offset and size */
2387     entry.offset += avi->index_offset + 8;
2388     entry.size = GST_READ_UINT32_LE (&index[i].size);
2389
2390     /* handle flags */
2391     if (stream->strh->type == GST_RIFF_FCC_auds) {
2392       /* all audio frames are keyframes */
2393       ENTRY_SET_KEYFRAME (&entry);
2394     } else {
2395       guint32 flags;
2396       /* else read flags */
2397       flags = GST_READ_UINT32_LE (&index[i].flags);
2398       if (flags & GST_RIFF_IF_KEYFRAME) {
2399         ENTRY_SET_KEYFRAME (&entry);
2400       } else {
2401         ENTRY_UNSET_KEYFRAME (&entry);
2402       }
2403     }
2404
2405     /* and add */
2406     if (G_UNLIKELY (!gst_avi_demux_add_index (avi, stream, num, &entry)))
2407       goto out_of_mem;
2408
2409     n++;
2410   }
2411   gst_buffer_unref (buf);
2412
2413   /* get stream stats now */
2414   avi->have_index = gst_avi_demux_do_index_stats (avi);
2415
2416   stamp = gst_util_get_timestamp () - stamp;
2417   GST_DEBUG_OBJECT (avi, "index parsing took %" GST_TIME_FORMAT,
2418       GST_TIME_ARGS (stamp));
2419
2420   return TRUE;
2421
2422   /* ERRORS */
2423 empty_list:
2424   {
2425     GST_DEBUG_OBJECT (avi, "empty index");
2426     gst_buffer_unref (buf);
2427     return FALSE;
2428   }
2429 out_of_mem:
2430   {
2431     GST_ELEMENT_ERROR (avi, RESOURCE, NO_SPACE_LEFT, (NULL),
2432         ("Cannot allocate memory for %u*%u=%u bytes",
2433             (guint) sizeof (GstAviIndexEntry), num,
2434             (guint) sizeof (GstAviIndexEntry) * num));
2435     gst_buffer_unref (buf);
2436     return FALSE;
2437   }
2438 }
2439
2440 /*
2441  * gst_avi_demux_stream_index:
2442  * @avi: avi demuxer object.
2443  *
2444  * Seeks to index and reads it.
2445  */
2446 static void
2447 gst_avi_demux_stream_index (GstAviDemux * avi)
2448 {
2449   GstFlowReturn res;
2450   guint64 offset = avi->offset;
2451   GstBuffer *buf;
2452   guint32 tag;
2453   guint32 size;
2454
2455   GST_DEBUG ("demux stream index at offset %" G_GUINT64_FORMAT, offset);
2456
2457   /* get chunk information */
2458   res = gst_pad_pull_range (avi->sinkpad, offset, 8, &buf);
2459   if (res != GST_FLOW_OK)
2460     goto pull_failed;
2461   else if (GST_BUFFER_SIZE (buf) < 8)
2462     goto too_small;
2463
2464   /* check tag first before blindy trying to read 'size' bytes */
2465   tag = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf));
2466   size = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf) + 4);
2467   if (tag == GST_RIFF_TAG_LIST) {
2468     /* this is the movi tag */
2469     GST_DEBUG_OBJECT (avi, "skip LIST chunk, size %" G_GUINT32_FORMAT,
2470         (8 + GST_ROUND_UP_2 (size)));
2471     offset += 8 + GST_ROUND_UP_2 (size);
2472     gst_buffer_unref (buf);
2473     res = gst_pad_pull_range (avi->sinkpad, offset, 8, &buf);
2474     if (res != GST_FLOW_OK)
2475       goto pull_failed;
2476     else if (GST_BUFFER_SIZE (buf) < 8)
2477       goto too_small;
2478     tag = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf));
2479     size = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf) + 4);
2480   }
2481
2482   if (tag != GST_RIFF_TAG_idx1)
2483     goto no_index;
2484   if (!size)
2485     goto zero_index;
2486
2487   gst_buffer_unref (buf);
2488
2489   GST_DEBUG ("index found at offset %" G_GUINT64_FORMAT, offset);
2490
2491   /* read chunk, advance offset */
2492   if (gst_riff_read_chunk (GST_ELEMENT_CAST (avi),
2493           avi->sinkpad, &offset, &tag, &buf) != GST_FLOW_OK)
2494     return;
2495
2496   GST_DEBUG ("will parse index chunk size %u for tag %"
2497       GST_FOURCC_FORMAT, GST_BUFFER_SIZE (buf), GST_FOURCC_ARGS (tag));
2498
2499   gst_avi_demux_parse_index (avi, buf);
2500
2501 #ifndef GST_DISABLE_GST_DEBUG
2502   /* debug our indexes */
2503   {
2504     gint i;
2505     GstAviStream *stream;
2506
2507     for (i = 0; i < avi->num_streams; i++) {
2508       stream = &avi->stream[i];
2509       GST_DEBUG_OBJECT (avi, "stream %u: %u frames, %" G_GINT64_FORMAT " bytes",
2510           i, stream->idx_n, stream->total_bytes);
2511     }
2512   }
2513 #endif
2514   return;
2515
2516   /* ERRORS */
2517 pull_failed:
2518   {
2519     GST_DEBUG_OBJECT (avi,
2520         "pull range failed: pos=%" G_GUINT64_FORMAT " size=8", offset);
2521     return;
2522   }
2523 too_small:
2524   {
2525     GST_DEBUG_OBJECT (avi, "Buffer is too small");
2526     gst_buffer_unref (buf);
2527     return;
2528   }
2529 no_index:
2530   {
2531     GST_WARNING_OBJECT (avi,
2532         "No index data (idx1) after movi chunk, but %" GST_FOURCC_FORMAT,
2533         GST_FOURCC_ARGS (tag));
2534     gst_buffer_unref (buf);
2535     return;
2536   }
2537 zero_index:
2538   {
2539     GST_WARNING_OBJECT (avi, "Empty index data (idx1) after movi chunk");
2540     gst_buffer_unref (buf);
2541     return;
2542   }
2543 }
2544
2545 /*
2546  * gst_avi_demux_peek_tag:
2547  *
2548  * Returns the tag and size of the next chunk
2549  */
2550 static GstFlowReturn
2551 gst_avi_demux_peek_tag (GstAviDemux * avi, guint64 offset, guint32 * tag,
2552     guint * size)
2553 {
2554   GstFlowReturn res = GST_FLOW_OK;
2555   GstBuffer *buf = NULL;
2556   guint bufsize;
2557   guint8 *bufdata;
2558
2559   res = gst_pad_pull_range (avi->sinkpad, offset, 8, &buf);
2560   if (res != GST_FLOW_OK)
2561     goto pull_failed;
2562
2563   bufsize = GST_BUFFER_SIZE (buf);
2564   if (bufsize != 8)
2565     goto wrong_size;
2566
2567   bufdata = GST_BUFFER_DATA (buf);
2568
2569   *tag = GST_READ_UINT32_LE (bufdata);
2570   *size = GST_READ_UINT32_LE (bufdata + 4);
2571
2572   GST_LOG_OBJECT (avi, "Tag[%" GST_FOURCC_FORMAT "] (size:%d) %"
2573       G_GINT64_FORMAT " -- %" G_GINT64_FORMAT, GST_FOURCC_ARGS (*tag),
2574       *size, offset + 8, offset + 8 + (gint64) * size);
2575
2576 done:
2577   gst_buffer_unref (buf);
2578
2579   return res;
2580
2581   /* ERRORS */
2582 pull_failed:
2583   {
2584     GST_DEBUG_OBJECT (avi, "pull_ranged returned %s", gst_flow_get_name (res));
2585     return res;
2586   }
2587 wrong_size:
2588   {
2589     GST_DEBUG_OBJECT (avi, "got %d bytes which is <> 8 bytes", bufsize);
2590     res = GST_FLOW_ERROR;
2591     goto done;
2592   }
2593 }
2594
2595 /*
2596  * gst_avi_demux_next_data_buffer:
2597  *
2598  * Returns the offset and size of the next buffer
2599  * Position is the position of the buffer (after tag and size)
2600  */
2601 static GstFlowReturn
2602 gst_avi_demux_next_data_buffer (GstAviDemux * avi, guint64 * offset,
2603     guint32 * tag, guint * size)
2604 {
2605   guint64 off = *offset;
2606   guint _size = 0;
2607   GstFlowReturn res;
2608
2609   do {
2610     res = gst_avi_demux_peek_tag (avi, off, tag, &_size);
2611     if (res != GST_FLOW_OK)
2612       break;
2613     if (*tag == GST_RIFF_TAG_LIST || *tag == GST_RIFF_TAG_RIFF)
2614       off += 8 + 4;             /* skip tag + size + subtag */
2615     else {
2616       *offset = off + 8;
2617       *size = _size;
2618       break;
2619     }
2620   } while (TRUE);
2621
2622   return res;
2623 }
2624
2625 /*
2626  * gst_avi_demux_stream_scan:
2627  * @avi: calling element (used for debugging/errors).
2628  *
2629  * Scan the file for all chunks to "create" a new index.
2630  * pull-range based
2631  */
2632 static gboolean
2633 gst_avi_demux_stream_scan (GstAviDemux * avi)
2634 {
2635   GstFlowReturn res;
2636   GstAviStream *stream;
2637   GstFormat format;
2638   guint64 pos = 0;
2639   guint64 length;
2640   gint64 tmplength;
2641   guint32 tag = 0;
2642   guint num;
2643
2644   /* FIXME:
2645    * - implement non-seekable source support.
2646    */
2647   GST_DEBUG_OBJECT (avi, "Creating index");
2648
2649   /* get the size of the file */
2650   format = GST_FORMAT_BYTES;
2651   if (!gst_pad_query_peer_duration (avi->sinkpad, &format, &tmplength))
2652     return FALSE;
2653   length = tmplength;
2654
2655   /* guess the total amount of entries we expect */
2656   num = 16000;
2657
2658   while (TRUE) {
2659     GstAviIndexEntry entry;
2660     guint size = 0;
2661
2662     /* start reading data buffers to find the id and offset */
2663     res = gst_avi_demux_next_data_buffer (avi, &pos, &tag, &size);
2664     if (G_UNLIKELY (res != GST_FLOW_OK))
2665       break;
2666
2667     /* get stream */
2668     stream = gst_avi_demux_stream_for_id (avi, tag);
2669     if (G_UNLIKELY (!stream))
2670       goto next;
2671
2672     /* we can't figure out the keyframes, assume they all are */
2673     entry.flags = GST_AVI_KEYFRAME;
2674     entry.offset = pos;
2675     entry.size = size;
2676
2677     /* and add to the index of this stream */
2678     if (G_UNLIKELY (!gst_avi_demux_add_index (avi, stream, num, &entry)))
2679       goto out_of_mem;
2680
2681   next:
2682     /* update position */
2683     pos += GST_ROUND_UP_2 (size);
2684     if (G_UNLIKELY (pos > length)) {
2685       GST_WARNING_OBJECT (avi,
2686           "Stopping index lookup since we are further than EOF");
2687       break;
2688     }
2689   }
2690
2691   /* collect stats */
2692   avi->have_index = gst_avi_demux_do_index_stats (avi);
2693
2694
2695   return TRUE;
2696
2697   /* ERRORS */
2698 out_of_mem:
2699   {
2700     GST_ELEMENT_ERROR (avi, RESOURCE, NO_SPACE_LEFT, (NULL),
2701         ("Cannot allocate memory for %u*%u=%u bytes",
2702             (guint) sizeof (GstAviIndexEntry), num,
2703             (guint) sizeof (GstAviIndexEntry) * num));
2704     return FALSE;
2705   }
2706 }
2707
2708 static void
2709 gst_avi_demux_calculate_durations_from_index (GstAviDemux * avi)
2710 {
2711   guint i;
2712   GstClockTime total;
2713   GstAviStream *stream;
2714
2715   total = GST_CLOCK_TIME_NONE;
2716
2717   /* all streams start at a timestamp 0 */
2718   for (i = 0; i < avi->num_streams; i++) {
2719     GstClockTime duration, hduration;
2720     gst_riff_strh *strh;
2721
2722     stream = &avi->stream[i];
2723     if (G_UNLIKELY (!stream || !stream->idx_n || !(strh = stream->strh)))
2724       continue;
2725
2726     /* get header duration for the stream */
2727     hduration = stream->hdr_duration;
2728     /* index duration calculated during parsing */
2729     duration = stream->idx_duration;
2730
2731     /* now pick a good duration */
2732     if (GST_CLOCK_TIME_IS_VALID (duration)) {
2733       /* index gave valid duration, use that */
2734       GST_INFO ("Stream %p duration according to index: %" GST_TIME_FORMAT,
2735           stream, GST_TIME_ARGS (duration));
2736     } else {
2737       /* fall back to header info to calculate a duration */
2738       duration = hduration;
2739     }
2740     GST_INFO ("Setting duration of stream #%d to %" GST_TIME_FORMAT,
2741         i, GST_TIME_ARGS (duration));
2742     /* set duration for the stream */
2743     stream->duration = duration;
2744
2745     /* find total duration */
2746     if (total == GST_CLOCK_TIME_NONE ||
2747         (GST_CLOCK_TIME_IS_VALID (duration) && duration > total))
2748       total = duration;
2749   }
2750
2751   if (GST_CLOCK_TIME_IS_VALID (total) && (total > 0)) {
2752     /* now update the duration for those streams where we had none */
2753     for (i = 0; i < avi->num_streams; i++) {
2754       stream = &avi->stream[i];
2755
2756       if (!GST_CLOCK_TIME_IS_VALID (stream->duration)
2757           || stream->duration == 0) {
2758         stream->duration = total;
2759
2760         GST_INFO ("Stream %p duration according to total: %" GST_TIME_FORMAT,
2761             stream, GST_TIME_ARGS (total));
2762       }
2763     }
2764   }
2765
2766   /* and set the total duration in the segment. */
2767   GST_INFO ("Setting total duration to: %" GST_TIME_FORMAT,
2768       GST_TIME_ARGS (total));
2769
2770   gst_segment_set_duration (&avi->segment, GST_FORMAT_TIME, total);
2771 }
2772
2773 /* returns FALSE if there are no pads to deliver event to,
2774  * otherwise TRUE (whatever the outcome of event sending),
2775  * takes ownership of the event. */
2776 static gboolean
2777 gst_avi_demux_push_event (GstAviDemux * avi, GstEvent * event)
2778 {
2779   gboolean result = FALSE;
2780   gint i;
2781
2782   GST_DEBUG_OBJECT (avi, "sending %s event to %d streams",
2783       GST_EVENT_TYPE_NAME (event), avi->num_streams);
2784
2785   for (i = 0; i < avi->num_streams; i++) {
2786     GstAviStream *stream = &avi->stream[i];
2787
2788     if (stream->pad) {
2789       result = TRUE;
2790       gst_pad_push_event (stream->pad, gst_event_ref (event));
2791     }
2792   }
2793   gst_event_unref (event);
2794   return result;
2795 }
2796
2797 static void
2798 gst_avi_demux_check_seekability (GstAviDemux * avi)
2799 {
2800   GstQuery *query;
2801   gboolean seekable = FALSE;
2802   gint64 start = -1, stop = -1;
2803
2804   query = gst_query_new_seeking (GST_FORMAT_BYTES);
2805   if (!gst_pad_peer_query (avi->sinkpad, query)) {
2806     GST_DEBUG_OBJECT (avi, "seeking query failed");
2807     goto done;
2808   }
2809
2810   gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
2811
2812   /* try harder to query upstream size if we didn't get it the first time */
2813   if (seekable && stop == -1) {
2814     GstFormat fmt = GST_FORMAT_BYTES;
2815
2816     GST_DEBUG_OBJECT (avi, "doing duration query to fix up unset stop");
2817     gst_pad_query_peer_duration (avi->sinkpad, &fmt, &stop);
2818   }
2819
2820   /* if upstream doesn't know the size, it's likely that it's not seekable in
2821    * practice even if it technically may be seekable */
2822   if (seekable && (start != 0 || stop <= start)) {
2823     GST_DEBUG_OBJECT (avi, "seekable but unknown start/stop -> disable");
2824     seekable = FALSE;
2825   }
2826
2827   if (!avi->element_index) {
2828     GST_DEBUG_OBJECT (avi, "no index");
2829     seekable = FALSE;
2830   }
2831
2832 done:
2833   GST_INFO_OBJECT (avi, "seekable: %d (%" G_GUINT64_FORMAT " - %"
2834       G_GUINT64_FORMAT ")", seekable, start, stop);
2835   avi->seekable = seekable;
2836
2837   gst_query_unref (query);
2838 }
2839
2840 /*
2841  * Read AVI headers when streaming
2842  */
2843 static GstFlowReturn
2844 gst_avi_demux_stream_header_push (GstAviDemux * avi)
2845 {
2846   GstFlowReturn ret = GST_FLOW_OK;
2847   guint32 tag = 0;
2848   guint32 ltag = 0;
2849   guint32 size = 0;
2850   const guint8 *data;
2851   GstBuffer *buf = NULL, *sub = NULL;
2852   guint offset = 4;
2853   gint64 stop;
2854   gint i;
2855   GstTagList *tags = NULL;
2856
2857   GST_DEBUG ("Reading and parsing avi headers: %d", avi->header_state);
2858
2859   switch (avi->header_state) {
2860     case GST_AVI_DEMUX_HEADER_TAG_LIST:
2861       if (gst_avi_demux_peek_chunk (avi, &tag, &size)) {
2862         avi->offset += 8 + GST_ROUND_UP_2 (size);
2863         if (tag != GST_RIFF_TAG_LIST)
2864           goto header_no_list;
2865
2866         gst_adapter_flush (avi->adapter, 8);
2867         /* Find the 'hdrl' LIST tag */
2868         GST_DEBUG ("Reading %d bytes", size);
2869         buf = gst_adapter_take_buffer (avi->adapter, size);
2870
2871         if (GST_READ_UINT32_LE (GST_BUFFER_DATA (buf)) != GST_RIFF_LIST_hdrl)
2872           goto header_no_hdrl;
2873
2874         /* mind padding */
2875         if (size & 1)
2876           gst_adapter_flush (avi->adapter, 1);
2877
2878         GST_DEBUG ("'hdrl' LIST tag found. Parsing next chunk");
2879
2880         /* the hdrl starts with a 'avih' header */
2881         if (!gst_riff_parse_chunk (GST_ELEMENT_CAST (avi), buf, &offset, &tag,
2882                 &sub))
2883           goto header_no_avih;
2884
2885         if (tag != GST_RIFF_TAG_avih)
2886           goto header_no_avih;
2887
2888         if (!gst_avi_demux_parse_avih (avi, sub, &avi->avih))
2889           goto header_wrong_avih;
2890
2891         GST_DEBUG_OBJECT (avi, "AVI header ok, reading elemnts from header");
2892
2893         /* now, read the elements from the header until the end */
2894         while (gst_riff_parse_chunk (GST_ELEMENT_CAST (avi), buf, &offset, &tag,
2895                 &sub)) {
2896           /* sub can be NULL on empty tags */
2897           if (!sub)
2898             continue;
2899
2900           switch (tag) {
2901             case GST_RIFF_TAG_LIST:
2902               if (GST_BUFFER_SIZE (sub) < 4)
2903                 goto next;
2904
2905               switch (GST_READ_UINT32_LE (GST_BUFFER_DATA (sub))) {
2906                 case GST_RIFF_LIST_strl:
2907                   if (!(gst_avi_demux_parse_stream (avi, sub))) {
2908                     sub = NULL;
2909                     GST_ELEMENT_WARNING (avi, STREAM, DEMUX, (NULL),
2910                         ("failed to parse stream, ignoring"));
2911                     goto next;
2912                   }
2913                   sub = NULL;
2914                   goto next;
2915                 case GST_RIFF_LIST_odml:
2916                   gst_avi_demux_parse_odml (avi, sub);
2917                   sub = NULL;
2918                   break;
2919                 default:
2920                   GST_WARNING_OBJECT (avi,
2921                       "Unknown list %" GST_FOURCC_FORMAT " in AVI header",
2922                       GST_FOURCC_ARGS (GST_READ_UINT32_LE (GST_BUFFER_DATA
2923                               (sub))));
2924                   /* fall-through */
2925                 case GST_RIFF_TAG_JUNQ:
2926                 case GST_RIFF_TAG_JUNK:
2927                   goto next;
2928               }
2929               break;
2930             case GST_RIFF_IDIT:
2931               gst_avi_demux_parse_idit (avi, sub);
2932               goto next;
2933             default:
2934               GST_WARNING_OBJECT (avi,
2935                   "Unknown off %d tag %" GST_FOURCC_FORMAT " in AVI header",
2936                   offset, GST_FOURCC_ARGS (tag));
2937               /* fall-through */
2938             case GST_RIFF_TAG_JUNQ:
2939             case GST_RIFF_TAG_JUNK:
2940             next:
2941               /* move to next chunk */
2942               if (sub)
2943                 gst_buffer_unref (sub);
2944               sub = NULL;
2945               break;
2946           }
2947         }
2948         gst_buffer_unref (buf);
2949         GST_DEBUG ("elements parsed");
2950
2951         /* check parsed streams */
2952         if (avi->num_streams == 0) {
2953           goto no_streams;
2954         } else if (avi->num_streams != avi->avih->streams) {
2955           GST_WARNING_OBJECT (avi,
2956               "Stream header mentioned %d streams, but %d available",
2957               avi->avih->streams, avi->num_streams);
2958         }
2959         GST_DEBUG ("Get junk and info next");
2960         avi->header_state = GST_AVI_DEMUX_HEADER_INFO;
2961       } else {
2962         /* Need more data */
2963         return ret;
2964       }
2965       /* fall-though */
2966     case GST_AVI_DEMUX_HEADER_INFO:
2967       GST_DEBUG_OBJECT (avi, "skipping junk between header and data ...");
2968       while (TRUE) {
2969         if (gst_adapter_available (avi->adapter) < 12)
2970           return GST_FLOW_OK;
2971
2972         data = gst_adapter_peek (avi->adapter, 12);
2973         tag = GST_READ_UINT32_LE (data);
2974         size = GST_READ_UINT32_LE (data + 4);
2975         ltag = GST_READ_UINT32_LE (data + 8);
2976
2977         if (tag == GST_RIFF_TAG_LIST) {
2978           switch (ltag) {
2979             case GST_RIFF_LIST_movi:
2980               gst_adapter_flush (avi->adapter, 12);
2981               avi->offset += 12;
2982               goto skipping_done;
2983             case GST_RIFF_LIST_INFO:
2984               GST_DEBUG ("Found INFO chunk");
2985               if (gst_avi_demux_peek_chunk (avi, &tag, &size)) {
2986                 GST_DEBUG ("got size %d", size);
2987                 avi->offset += 12;
2988                 gst_adapter_flush (avi->adapter, 12);
2989                 if (size > 4) {
2990                   buf = gst_adapter_take_buffer (avi->adapter, size - 4);
2991                   /* mind padding */
2992                   if (size & 1)
2993                     gst_adapter_flush (avi->adapter, 1);
2994                   gst_riff_parse_info (GST_ELEMENT_CAST (avi), buf, &tags);
2995                   if (tags) {
2996                     if (avi->globaltags) {
2997                       gst_tag_list_insert (avi->globaltags, tags,
2998                           GST_TAG_MERGE_REPLACE);
2999                     } else {
3000                       avi->globaltags = tags;
3001                     }
3002                   }
3003                   tags = NULL;
3004                   gst_buffer_unref (buf);
3005
3006                   avi->offset += GST_ROUND_UP_2 (size) - 4;
3007                 } else {
3008                   GST_DEBUG ("skipping INFO LIST prefix");
3009                 }
3010               } else {
3011                 /* Need more data */
3012                 return GST_FLOW_OK;
3013               }
3014               break;
3015             default:
3016               if (gst_avi_demux_peek_chunk (avi, &tag, &size)) {
3017                 avi->offset += 8 + GST_ROUND_UP_2 (size);
3018                 gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
3019                 // ??? goto iterate; ???
3020               } else {
3021                 /* Need more data */
3022                 return GST_FLOW_OK;
3023               }
3024               break;
3025           }
3026         } else {
3027           if (gst_avi_demux_peek_chunk (avi, &tag, &size)) {
3028             avi->offset += 8 + GST_ROUND_UP_2 (size);
3029             gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
3030             //goto iterate;
3031           } else {
3032             /* Need more data */
3033             return GST_FLOW_OK;
3034           }
3035         }
3036       }
3037       break;
3038     default:
3039       GST_WARNING ("unhandled header state: %d", avi->header_state);
3040       break;
3041   }
3042 skipping_done:
3043
3044   GST_DEBUG_OBJECT (avi, "skipping done ... (streams=%u, stream[0].indexes=%p)",
3045       avi->num_streams, avi->stream[0].indexes);
3046
3047   GST_DEBUG ("Found movi chunk. Starting to stream data");
3048   avi->state = GST_AVI_DEMUX_MOVI;
3049
3050   /* no indexes in push mode, but it still sets some variables */
3051   gst_avi_demux_calculate_durations_from_index (avi);
3052
3053   gst_avi_demux_expose_streams (avi, TRUE);
3054
3055   /* prepare all streams for index 0 */
3056   for (i = 0; i < avi->num_streams; i++)
3057     avi->stream[i].current_entry = 0;
3058
3059   /* create initial NEWSEGMENT event */
3060   if ((stop = avi->segment.stop) == GST_CLOCK_TIME_NONE)
3061     stop = avi->segment.duration;
3062
3063   GST_DEBUG_OBJECT (avi, "segment stop %" G_GINT64_FORMAT, stop);
3064
3065   if (avi->seg_event)
3066     gst_event_unref (avi->seg_event);
3067   avi->seg_event = gst_event_new_new_segment_full
3068       (FALSE, avi->segment.rate, avi->segment.applied_rate, GST_FORMAT_TIME,
3069       avi->segment.start, stop, avi->segment.time);
3070
3071   gst_avi_demux_check_seekability (avi);
3072
3073   /* at this point we know all the streams and we can signal the no more
3074    * pads signal */
3075   GST_DEBUG_OBJECT (avi, "signaling no more pads");
3076   gst_element_no_more_pads (GST_ELEMENT_CAST (avi));
3077
3078   return GST_FLOW_OK;
3079
3080   /* ERRORS */
3081 no_streams:
3082   {
3083     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("No streams found"));
3084     return GST_FLOW_ERROR;
3085   }
3086 header_no_list:
3087   {
3088     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3089         ("Invalid AVI header (no LIST at start): %"
3090             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3091     return GST_FLOW_ERROR;
3092   }
3093 header_no_hdrl:
3094   {
3095     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3096         ("Invalid AVI header (no hdrl at start): %"
3097             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3098     gst_buffer_unref (buf);
3099     return GST_FLOW_ERROR;
3100   }
3101 header_no_avih:
3102   {
3103     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3104         ("Invalid AVI header (no avih at start): %"
3105             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3106     if (sub)
3107       gst_buffer_unref (sub);
3108
3109     gst_buffer_unref (buf);
3110     return GST_FLOW_ERROR;
3111   }
3112 header_wrong_avih:
3113   {
3114     gst_buffer_unref (buf);
3115     return GST_FLOW_ERROR;
3116   }
3117 }
3118
3119 static void
3120 gst_avi_demux_add_date_tag (GstAviDemux * avi, gint y, gint m, gint d)
3121 {
3122   GDate *date;
3123   date = g_date_new_dmy (d, m, y);
3124   if (!g_date_valid (date)) {
3125     /* bogus date */
3126     GST_WARNING_OBJECT (avi, "Refusing to add invalid date %d-%d-%d", y, m, d);
3127     g_date_free (date);
3128     return;
3129   }
3130
3131   if (avi->globaltags == NULL)
3132     avi->globaltags = gst_tag_list_new ();
3133
3134   gst_tag_list_add (avi->globaltags, GST_TAG_MERGE_REPLACE, GST_TAG_DATE, date,
3135       NULL);
3136   g_date_free (date);
3137 }
3138
3139 static void
3140 gst_avi_demux_parse_idit_nums_only (GstAviDemux * avi, gchar * data)
3141 {
3142   gint y, m, d;
3143   gint ret;
3144
3145   ret = sscanf (data, "%d:%d:%d", &y, &m, &d);
3146   if (ret != 3) {
3147     GST_WARNING_OBJECT (avi, "Failed to parse IDIT tag");
3148     return;
3149   }
3150   gst_avi_demux_add_date_tag (avi, y, m, d);
3151 }
3152
3153 static gint
3154 get_month_num (gchar * data, guint size)
3155 {
3156   if (g_ascii_strncasecmp (data, "jan", 3) == 0) {
3157     return 1;
3158   } else if (g_ascii_strncasecmp (data, "feb", 3) == 0) {
3159     return 2;
3160   } else if (g_ascii_strncasecmp (data, "mar", 3) == 0) {
3161     return 3;
3162   } else if (g_ascii_strncasecmp (data, "apr", 3) == 0) {
3163     return 4;
3164   } else if (g_ascii_strncasecmp (data, "may", 3) == 0) {
3165     return 5;
3166   } else if (g_ascii_strncasecmp (data, "jun", 3) == 0) {
3167     return 6;
3168   } else if (g_ascii_strncasecmp (data, "jul", 3) == 0) {
3169     return 7;
3170   } else if (g_ascii_strncasecmp (data, "aug", 3) == 0) {
3171     return 8;
3172   } else if (g_ascii_strncasecmp (data, "sep", 3) == 0) {
3173     return 9;
3174   } else if (g_ascii_strncasecmp (data, "oct", 3) == 0) {
3175     return 10;
3176   } else if (g_ascii_strncasecmp (data, "nov", 3) == 0) {
3177     return 11;
3178   } else if (g_ascii_strncasecmp (data, "dec", 3) == 0) {
3179     return 12;
3180   }
3181
3182   return 0;
3183 }
3184
3185 static void
3186 gst_avi_demux_parse_idit_text (GstAviDemux * avi, gchar * data)
3187 {
3188   gint year, month, day;
3189   gint hour, min, sec;
3190   gint ret;
3191   gchar weekday[4];
3192   gchar monthstr[4];
3193
3194   ret = sscanf (data, "%3s %3s %d %d:%d:%d %d", weekday, monthstr, &day, &hour,
3195       &min, &sec, &year);
3196   if (ret != 7) {
3197     GST_WARNING_OBJECT (avi, "Failed to parse IDIT tag");
3198     return;
3199   }
3200   month = get_month_num (monthstr, strlen (monthstr));
3201   gst_avi_demux_add_date_tag (avi, year, month, day);
3202 }
3203
3204 static void
3205 gst_avi_demux_parse_idit (GstAviDemux * avi, GstBuffer * buf)
3206 {
3207   gchar *data = (gchar *) GST_BUFFER_DATA (buf);
3208   guint size = GST_BUFFER_SIZE (buf);
3209   gchar *safedata = NULL;
3210
3211   /*
3212    * According to:
3213    * http://www.eden-foundation.org/products/code/film_date_stamp/index.html
3214    *
3215    * This tag could be in one of the below formats
3216    * 2005:08:17 11:42:43
3217    * THU OCT 26 16:46:04 2006
3218    * Mon Mar  3 09:44:56 2008
3219    *
3220    * FIXME: Our date tag doesn't include hours
3221    */
3222
3223   /* skip eventual initial whitespace */
3224   while (size > 0 && g_ascii_isspace (data[0])) {
3225     data++;
3226     size--;
3227   }
3228
3229   if (size == 0) {
3230     goto non_parsable;
3231   }
3232
3233   /* make a safe copy to add a \0 to the end of the string */
3234   safedata = g_strndup (data, size);
3235
3236   /* test if the first char is a alpha or a number */
3237   if (g_ascii_isdigit (data[0])) {
3238     gst_avi_demux_parse_idit_nums_only (avi, safedata);
3239     g_free (safedata);
3240     return;
3241   } else if (g_ascii_isalpha (data[0])) {
3242     gst_avi_demux_parse_idit_text (avi, safedata);
3243     g_free (safedata);
3244     return;
3245   }
3246
3247   g_free (safedata);
3248
3249 non_parsable:
3250   GST_WARNING_OBJECT (avi, "IDIT tag has no parsable info");
3251 }
3252
3253 /*
3254  * Read full AVI headers.
3255  */
3256 static GstFlowReturn
3257 gst_avi_demux_stream_header_pull (GstAviDemux * avi)
3258 {
3259   GstFlowReturn res;
3260   GstBuffer *buf, *sub = NULL;
3261   guint32 tag;
3262   guint offset = 4;
3263   gint64 stop;
3264   GstElement *element = GST_ELEMENT_CAST (avi);
3265   GstClockTime stamp;
3266   GstTagList *tags = NULL;
3267
3268   stamp = gst_util_get_timestamp ();
3269
3270   /* the header consists of a 'hdrl' LIST tag */
3271   res = gst_riff_read_chunk (element, avi->sinkpad, &avi->offset, &tag, &buf);
3272   if (res != GST_FLOW_OK)
3273     goto pull_range_failed;
3274   else if (tag != GST_RIFF_TAG_LIST)
3275     goto no_list;
3276   else if (GST_BUFFER_SIZE (buf) < 4)
3277     goto no_header;
3278
3279   GST_DEBUG_OBJECT (avi, "parsing headers");
3280
3281   /* Find the 'hdrl' LIST tag */
3282   while (GST_READ_UINT32_LE (GST_BUFFER_DATA (buf)) != GST_RIFF_LIST_hdrl) {
3283     GST_LOG_OBJECT (avi, "buffer contains %" GST_FOURCC_FORMAT,
3284         GST_FOURCC_ARGS (GST_READ_UINT32_LE (GST_BUFFER_DATA (buf))));
3285
3286     /* Eat up */
3287     gst_buffer_unref (buf);
3288
3289     /* read new chunk */
3290     res = gst_riff_read_chunk (element, avi->sinkpad, &avi->offset, &tag, &buf);
3291     if (res != GST_FLOW_OK)
3292       goto pull_range_failed;
3293     else if (tag != GST_RIFF_TAG_LIST)
3294       goto no_list;
3295     else if (GST_BUFFER_SIZE (buf) < 4)
3296       goto no_header;
3297   }
3298
3299   GST_DEBUG_OBJECT (avi, "hdrl LIST tag found");
3300
3301   /* the hdrl starts with a 'avih' header */
3302   if (!gst_riff_parse_chunk (element, buf, &offset, &tag, &sub))
3303     goto no_avih;
3304   else if (tag != GST_RIFF_TAG_avih)
3305     goto no_avih;
3306   else if (!gst_avi_demux_parse_avih (avi, sub, &avi->avih))
3307     goto invalid_avih;
3308
3309   GST_DEBUG_OBJECT (avi, "AVI header ok, reading elements from header");
3310
3311   /* now, read the elements from the header until the end */
3312   while (gst_riff_parse_chunk (element, buf, &offset, &tag, &sub)) {
3313     /* sub can be NULL on empty tags */
3314     if (!sub)
3315       continue;
3316
3317     switch (tag) {
3318       case GST_RIFF_TAG_LIST:
3319       {
3320         guint8 *data;
3321         guint32 fourcc;
3322
3323         if (GST_BUFFER_SIZE (sub) < 4)
3324           goto next;
3325
3326         data = GST_BUFFER_DATA (sub);
3327         fourcc = GST_READ_UINT32_LE (data);
3328
3329         switch (fourcc) {
3330           case GST_RIFF_LIST_strl:
3331             if (!(gst_avi_demux_parse_stream (avi, sub))) {
3332               GST_ELEMENT_WARNING (avi, STREAM, DEMUX, (NULL),
3333                   ("failed to parse stream, ignoring"));
3334               sub = NULL;
3335             }
3336             sub = NULL;
3337             goto next;
3338           case GST_RIFF_LIST_odml:
3339             gst_avi_demux_parse_odml (avi, sub);
3340             sub = NULL;
3341             break;
3342           case GST_RIFF_LIST_INFO:
3343             GST_BUFFER_DATA (sub) = data + 4;
3344             GST_BUFFER_SIZE (sub) -= 4;
3345             gst_riff_parse_info (element, sub, &tags);
3346             if (tags) {
3347               if (avi->globaltags) {
3348                 gst_tag_list_insert (avi->globaltags, tags,
3349                     GST_TAG_MERGE_REPLACE);
3350               } else {
3351                 avi->globaltags = tags;
3352               }
3353             }
3354             tags = NULL;
3355             break;
3356           default:
3357             GST_WARNING_OBJECT (avi,
3358                 "Unknown list %" GST_FOURCC_FORMAT " in AVI header",
3359                 GST_FOURCC_ARGS (fourcc));
3360             GST_MEMDUMP_OBJECT (avi, "Unknown list", GST_BUFFER_DATA (sub),
3361                 GST_BUFFER_SIZE (sub));
3362             /* fall-through */
3363           case GST_RIFF_TAG_JUNQ:
3364           case GST_RIFF_TAG_JUNK:
3365             goto next;
3366         }
3367         break;
3368       }
3369       case GST_RIFF_IDIT:
3370         gst_avi_demux_parse_idit (avi, sub);
3371         goto next;
3372       default:
3373         GST_WARNING_OBJECT (avi,
3374             "Unknown tag %" GST_FOURCC_FORMAT " in AVI header at off %d",
3375             GST_FOURCC_ARGS (tag), offset);
3376         GST_MEMDUMP_OBJECT (avi, "Unknown tag", GST_BUFFER_DATA (sub),
3377             GST_BUFFER_SIZE (sub));
3378         /* fall-through */
3379       case GST_RIFF_TAG_JUNQ:
3380       case GST_RIFF_TAG_JUNK:
3381       next:
3382         if (sub)
3383           gst_buffer_unref (sub);
3384         sub = NULL;
3385         break;
3386     }
3387   }
3388   gst_buffer_unref (buf);
3389   GST_DEBUG ("elements parsed");
3390
3391   /* check parsed streams */
3392   if (avi->num_streams == 0)
3393     goto no_streams;
3394   else if (avi->num_streams != avi->avih->streams) {
3395     GST_WARNING_OBJECT (avi,
3396         "Stream header mentioned %d streams, but %d available",
3397         avi->avih->streams, avi->num_streams);
3398   }
3399
3400   GST_DEBUG_OBJECT (avi, "skipping junk between header and data, offset=%"
3401       G_GUINT64_FORMAT, avi->offset);
3402
3403   /* Now, find the data (i.e. skip all junk between header and data) */
3404   do {
3405     guint size;
3406     guint8 *data;
3407     guint32 tag, ltag;
3408
3409     res = gst_pad_pull_range (avi->sinkpad, avi->offset, 12, &buf);
3410     if (res != GST_FLOW_OK) {
3411       GST_DEBUG_OBJECT (avi, "pull_range failure while looking for tags");
3412       goto pull_range_failed;
3413     } else if (GST_BUFFER_SIZE (buf) < 12) {
3414       GST_DEBUG_OBJECT (avi, "got %d bytes which is less than 12 bytes",
3415           GST_BUFFER_SIZE (buf));
3416       gst_buffer_unref (buf);
3417       return GST_FLOW_ERROR;
3418     }
3419
3420     data = GST_BUFFER_DATA (buf);
3421
3422     tag = GST_READ_UINT32_LE (data);
3423     size = GST_READ_UINT32_LE (data + 4);
3424     ltag = GST_READ_UINT32_LE (data + 8);
3425
3426     GST_DEBUG ("tag %" GST_FOURCC_FORMAT ", size %u",
3427         GST_FOURCC_ARGS (tag), size);
3428     GST_MEMDUMP ("Tag content", data, GST_BUFFER_SIZE (buf));
3429     gst_buffer_unref (buf);
3430
3431     switch (tag) {
3432       case GST_RIFF_TAG_LIST:{
3433         switch (ltag) {
3434           case GST_RIFF_LIST_movi:
3435             GST_DEBUG_OBJECT (avi,
3436                 "Reached the 'movi' tag, we're done with skipping");
3437             goto skipping_done;
3438           case GST_RIFF_LIST_INFO:
3439             res =
3440                 gst_riff_read_chunk (element, avi->sinkpad, &avi->offset, &tag,
3441                 &buf);
3442             if (res != GST_FLOW_OK) {
3443               GST_DEBUG_OBJECT (avi, "couldn't read INFO chunk");
3444               goto pull_range_failed;
3445             }
3446             GST_DEBUG ("got size %u", GST_BUFFER_SIZE (buf));
3447             if (size < 4) {
3448               GST_DEBUG ("skipping INFO LIST prefix");
3449               avi->offset += (4 - GST_ROUND_UP_2 (size));
3450               gst_buffer_unref (buf);
3451               continue;
3452             }
3453
3454             sub = gst_buffer_create_sub (buf, 4, GST_BUFFER_SIZE (buf) - 4);
3455             gst_riff_parse_info (element, sub, &tags);
3456             if (tags) {
3457               if (avi->globaltags) {
3458                 gst_tag_list_insert (avi->globaltags, tags,
3459                     GST_TAG_MERGE_REPLACE);
3460               } else {
3461                 avi->globaltags = tags;
3462               }
3463             }
3464             tags = NULL;
3465             if (sub) {
3466               gst_buffer_unref (sub);
3467               sub = NULL;
3468             }
3469             gst_buffer_unref (buf);
3470             /* gst_riff_read_chunk() has already advanced avi->offset */
3471             break;
3472           default:
3473             GST_WARNING_OBJECT (avi,
3474                 "Skipping unknown list tag %" GST_FOURCC_FORMAT,
3475                 GST_FOURCC_ARGS (ltag));
3476             avi->offset += 8 + GST_ROUND_UP_2 (size);
3477             break;
3478         }
3479       }
3480         break;
3481       default:
3482         GST_WARNING_OBJECT (avi, "Skipping unknown tag %" GST_FOURCC_FORMAT,
3483             GST_FOURCC_ARGS (tag));
3484         /* Fall-through */
3485       case GST_MAKE_FOURCC ('J', 'U', 'N', 'Q'):
3486       case GST_MAKE_FOURCC ('J', 'U', 'N', 'K'):
3487         /* Only get buffer for debugging if the memdump is needed  */
3488         if (gst_debug_category_get_threshold (GST_CAT_DEFAULT) >= 9) {
3489           res = gst_pad_pull_range (avi->sinkpad, avi->offset, size, &buf);
3490           if (res != GST_FLOW_OK) {
3491             GST_DEBUG_OBJECT (avi, "couldn't read INFO chunk");
3492             goto pull_range_failed;
3493           }
3494           GST_MEMDUMP ("Junk", GST_BUFFER_DATA (buf), GST_BUFFER_SIZE (buf));
3495           gst_buffer_unref (buf);
3496         }
3497         avi->offset += 8 + GST_ROUND_UP_2 (size);
3498         break;
3499     }
3500   } while (1);
3501 skipping_done:
3502
3503   GST_DEBUG_OBJECT (avi, "skipping done ... (streams=%u, stream[0].indexes=%p)",
3504       avi->num_streams, avi->stream[0].indexes);
3505
3506   /* create or read stream index (for seeking) */
3507   if (avi->stream[0].indexes != NULL) {
3508     /* we read a super index already (gst_avi_demux_parse_superindex() ) */
3509     gst_avi_demux_read_subindexes_pull (avi);
3510   }
3511   if (!avi->have_index) {
3512     if (avi->avih->flags & GST_RIFF_AVIH_HASINDEX)
3513       gst_avi_demux_stream_index (avi);
3514
3515     /* still no index, scan */
3516     if (!avi->have_index) {
3517       gst_avi_demux_stream_scan (avi);
3518
3519       /* still no index.. this is a fatal error for now.
3520        * FIXME, we should switch to plain push mode without seeking
3521        * instead of failing. */
3522       if (!avi->have_index)
3523         goto no_index;
3524     }
3525   }
3526   /* use the indexes now to construct nice durations */
3527   gst_avi_demux_calculate_durations_from_index (avi);
3528
3529   gst_avi_demux_expose_streams (avi, FALSE);
3530
3531   /* create initial NEWSEGMENT event */
3532   if ((stop = avi->segment.stop) == GST_CLOCK_TIME_NONE)
3533     stop = avi->segment.duration;
3534
3535   GST_DEBUG_OBJECT (avi, "segment stop %" G_GINT64_FORMAT, stop);
3536
3537   /* do initial seek to the default segment values */
3538   gst_avi_demux_do_seek (avi, &avi->segment);
3539
3540   /* prepare initial segment */
3541   if (avi->seg_event)
3542     gst_event_unref (avi->seg_event);
3543   avi->seg_event = gst_event_new_new_segment_full
3544       (FALSE, avi->segment.rate, avi->segment.applied_rate, GST_FORMAT_TIME,
3545       avi->segment.start, stop, avi->segment.time);
3546
3547   stamp = gst_util_get_timestamp () - stamp;
3548   GST_DEBUG_OBJECT (avi, "pulling header took %" GST_TIME_FORMAT,
3549       GST_TIME_ARGS (stamp));
3550
3551   /* at this point we know all the streams and we can signal the no more
3552    * pads signal */
3553   GST_DEBUG_OBJECT (avi, "signaling no more pads");
3554   gst_element_no_more_pads (GST_ELEMENT_CAST (avi));
3555
3556   return GST_FLOW_OK;
3557
3558   /* ERRORS */
3559 no_list:
3560   {
3561     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3562         ("Invalid AVI header (no LIST at start): %"
3563             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3564     gst_buffer_unref (buf);
3565     return GST_FLOW_ERROR;
3566   }
3567 no_header:
3568   {
3569     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3570         ("Invalid AVI header (no hdrl at start): %"
3571             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3572     gst_buffer_unref (buf);
3573     return GST_FLOW_ERROR;
3574   }
3575 no_avih:
3576   {
3577     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3578         ("Invalid AVI header (no avih at start): %"
3579             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3580     if (sub)
3581       gst_buffer_unref (sub);
3582     gst_buffer_unref (buf);
3583     return GST_FLOW_ERROR;
3584   }
3585 invalid_avih:
3586   {
3587     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3588         ("Invalid AVI header (cannot parse avih at start)"));
3589     gst_buffer_unref (buf);
3590     return GST_FLOW_ERROR;
3591   }
3592 no_streams:
3593   {
3594     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("No streams found"));
3595     return GST_FLOW_ERROR;
3596   }
3597 no_index:
3598   {
3599     GST_WARNING ("file without or too big index");
3600     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3601         ("Could not get/create index"));
3602     return GST_FLOW_ERROR;
3603   }
3604 pull_range_failed:
3605   {
3606     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3607         ("pull_range flow reading header: %s", gst_flow_get_name (res)));
3608     return GST_FLOW_ERROR;
3609   }
3610 }
3611
3612 /* move a stream to @index */
3613 static void
3614 gst_avi_demux_move_stream (GstAviDemux * avi, GstAviStream * stream,
3615     GstSegment * segment, guint index)
3616 {
3617   GST_DEBUG_OBJECT (avi, "Move stream %d to %u", stream->num, index);
3618
3619   if (segment->rate < 0.0) {
3620     guint next_key;
3621     /* Because we don't know the frame order we need to push from the prev keyframe
3622      * to the next keyframe. If there is a smart decoder downstream he will notice
3623      * that there are too many encoded frames send and return UNEXPECTED when there
3624      * are enough decoded frames to fill the segment. */
3625     next_key = gst_avi_demux_index_next (avi, stream, index, TRUE);
3626
3627     /* FIXME, we go back to 0, we should look at segment.start. We will however
3628      * stop earlier when the see the timestamp < segment.start */
3629     stream->start_entry = 0;
3630     stream->step_entry = index;
3631     stream->current_entry = index;
3632     stream->stop_entry = next_key;
3633
3634     GST_DEBUG_OBJECT (avi, "reverse seek: start %u, step %u, stop %u",
3635         stream->start_entry, stream->step_entry, stream->stop_entry);
3636   } else {
3637     stream->start_entry = index;
3638     stream->step_entry = index;
3639     stream->stop_entry = gst_avi_demux_index_last (avi, stream);
3640   }
3641   if (stream->current_entry != index) {
3642     GST_DEBUG_OBJECT (avi, "Move DISCONT from %u to %u",
3643         stream->current_entry, index);
3644     stream->current_entry = index;
3645     stream->discont = TRUE;
3646   }
3647
3648   /* update the buffer info */
3649   gst_avi_demux_get_buffer_info (avi, stream, index,
3650       &stream->current_timestamp, &stream->current_ts_end,
3651       &stream->current_offset, &stream->current_offset_end);
3652
3653   GST_DEBUG_OBJECT (avi, "Moved to %u, ts %" GST_TIME_FORMAT
3654       ", ts_end %" GST_TIME_FORMAT ", off %" G_GUINT64_FORMAT
3655       ", off_end %" G_GUINT64_FORMAT, index,
3656       GST_TIME_ARGS (stream->current_timestamp),
3657       GST_TIME_ARGS (stream->current_ts_end), stream->current_offset,
3658       stream->current_offset_end);
3659 }
3660
3661 /*
3662  * Do the actual seeking.
3663  */
3664 static gboolean
3665 gst_avi_demux_do_seek (GstAviDemux * avi, GstSegment * segment)
3666 {
3667   GstClockTime seek_time;
3668   gboolean keyframe;
3669   guint i, index;
3670   GstAviStream *stream;
3671
3672   seek_time = segment->last_stop;
3673   keyframe = !!(segment->flags & GST_SEEK_FLAG_KEY_UNIT);
3674
3675   GST_DEBUG_OBJECT (avi, "seek to: %" GST_TIME_FORMAT
3676       " keyframe seeking:%d", GST_TIME_ARGS (seek_time), keyframe);
3677
3678   /* FIXME, this code assumes the main stream with keyframes is stream 0,
3679    * which is mostly correct... */
3680   stream = &avi->stream[avi->main_stream];
3681
3682   /* get the entry index for the requested position */
3683   index = gst_avi_demux_index_for_time (avi, stream, seek_time);
3684   GST_DEBUG_OBJECT (avi, "Got entry %u", index);
3685
3686   /* check if we are already on a keyframe */
3687   if (!ENTRY_IS_KEYFRAME (&stream->index[index])) {
3688     GST_DEBUG_OBJECT (avi, "not keyframe, searching back");
3689     /* now go to the previous keyframe, this is where we should start
3690      * decoding from. */
3691     index = gst_avi_demux_index_prev (avi, stream, index, TRUE);
3692     GST_DEBUG_OBJECT (avi, "previous keyframe at %u", index);
3693   }
3694
3695   /* move the main stream to this position */
3696   gst_avi_demux_move_stream (avi, stream, segment, index);
3697
3698   if (keyframe) {
3699     /* when seeking to a keyframe, we update the result seek time
3700      * to the time of the keyframe. */
3701     seek_time = stream->current_timestamp;
3702     GST_DEBUG_OBJECT (avi, "keyframe adjusted to %" GST_TIME_FORMAT,
3703         GST_TIME_ARGS (seek_time));
3704   }
3705
3706   /* the seek time is also the last_stop and stream time when going
3707    * forwards */
3708   segment->last_stop = seek_time;
3709   if (segment->rate > 0.0)
3710     segment->time = seek_time;
3711
3712   /* now set DISCONT and align the other streams */
3713   for (i = 0; i < avi->num_streams; i++) {
3714     GstAviStream *ostream;
3715
3716     ostream = &avi->stream[i];
3717     if ((ostream == stream) || (ostream->index == NULL))
3718       continue;
3719
3720     /* get the entry index for the requested position */
3721     index = gst_avi_demux_index_for_time (avi, ostream, seek_time);
3722
3723     /* move to previous keyframe */
3724     if (!ENTRY_IS_KEYFRAME (&ostream->index[index]))
3725       index = gst_avi_demux_index_prev (avi, ostream, index, TRUE);
3726
3727     gst_avi_demux_move_stream (avi, ostream, segment, index);
3728   }
3729   GST_DEBUG_OBJECT (avi, "done seek to: %" GST_TIME_FORMAT,
3730       GST_TIME_ARGS (seek_time));
3731
3732   return TRUE;
3733 }
3734
3735 /*
3736  * Handle seek event.
3737  */
3738 static gboolean
3739 gst_avi_demux_handle_seek (GstAviDemux * avi, GstPad * pad, GstEvent * event)
3740 {
3741   gdouble rate;
3742   GstFormat format;
3743   GstSeekFlags flags;
3744   GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
3745   gint64 cur, stop;
3746   gboolean flush;
3747   gboolean update;
3748   GstSegment seeksegment = { 0, };
3749   gint i;
3750
3751   if (event) {
3752     GST_DEBUG_OBJECT (avi, "doing seek with event");
3753
3754     gst_event_parse_seek (event, &rate, &format, &flags,
3755         &cur_type, &cur, &stop_type, &stop);
3756
3757     /* we have to have a format as the segment format. Try to convert
3758      * if not. */
3759     if (format != GST_FORMAT_TIME) {
3760       GstFormat fmt = GST_FORMAT_TIME;
3761       gboolean res = TRUE;
3762
3763       if (cur_type != GST_SEEK_TYPE_NONE)
3764         res = gst_pad_query_convert (pad, format, cur, &fmt, &cur);
3765       if (res && stop_type != GST_SEEK_TYPE_NONE)
3766         res = gst_pad_query_convert (pad, format, stop, &fmt, &stop);
3767       if (!res)
3768         goto no_format;
3769
3770       format = fmt;
3771     }
3772     GST_DEBUG_OBJECT (avi,
3773         "seek requested: rate %g cur %" GST_TIME_FORMAT " stop %"
3774         GST_TIME_FORMAT, rate, GST_TIME_ARGS (cur), GST_TIME_ARGS (stop));
3775     /* FIXME: can we do anything with rate!=1.0 */
3776   } else {
3777     GST_DEBUG_OBJECT (avi, "doing seek without event");
3778     flags = 0;
3779     rate = 1.0;
3780   }
3781
3782   /* save flush flag */
3783   flush = flags & GST_SEEK_FLAG_FLUSH;
3784
3785   if (flush) {
3786     GstEvent *fevent = gst_event_new_flush_start ();
3787
3788     /* for a flushing seek, we send a flush_start on all pads. This will
3789      * eventually stop streaming with a WRONG_STATE. We can thus eventually
3790      * take the STREAM_LOCK. */
3791     GST_DEBUG_OBJECT (avi, "sending flush start");
3792     gst_avi_demux_push_event (avi, gst_event_ref (fevent));
3793     gst_pad_push_event (avi->sinkpad, fevent);
3794   } else {
3795     /* a non-flushing seek, we PAUSE the task so that we can take the
3796      * STREAM_LOCK */
3797     GST_DEBUG_OBJECT (avi, "non flushing seek, pausing task");
3798     gst_pad_pause_task (avi->sinkpad);
3799   }
3800
3801   /* wait for streaming to stop */
3802   GST_DEBUG_OBJECT (avi, "wait for streaming to stop");
3803   GST_PAD_STREAM_LOCK (avi->sinkpad);
3804
3805   /* copy segment, we need this because we still need the old
3806    * segment when we close the current segment. */
3807   memcpy (&seeksegment, &avi->segment, sizeof (GstSegment));
3808
3809   if (event) {
3810     GST_DEBUG_OBJECT (avi, "configuring seek");
3811     gst_segment_set_seek (&seeksegment, rate, format, flags,
3812         cur_type, cur, stop_type, stop, &update);
3813   }
3814   /* do the seek, seeksegment.last_stop contains the new position, this
3815    * actually never fails. */
3816   gst_avi_demux_do_seek (avi, &seeksegment);
3817
3818   if (flush) {
3819     GstEvent *fevent = gst_event_new_flush_stop ();
3820
3821     GST_DEBUG_OBJECT (avi, "sending flush stop");
3822     gst_avi_demux_push_event (avi, gst_event_ref (fevent));
3823     gst_pad_push_event (avi->sinkpad, fevent);
3824
3825     /* reset the last flow and mark discont, FLUSH is always DISCONT */
3826     for (i = 0; i < avi->num_streams; i++) {
3827       GST_DEBUG_OBJECT (avi, "marking DISCONT");
3828       avi->stream[i].last_flow = GST_FLOW_OK;
3829       avi->stream[i].discont = TRUE;
3830     }
3831   } else if (avi->segment_running) {
3832     GstEvent *seg;
3833
3834     /* we are running the current segment and doing a non-flushing seek,
3835      * close the segment first based on the last_stop. */
3836     GST_DEBUG_OBJECT (avi, "closing running segment %" G_GINT64_FORMAT
3837         " to %" G_GINT64_FORMAT, avi->segment.start, avi->segment.last_stop);
3838     seg = gst_event_new_new_segment_full (TRUE,
3839         avi->segment.rate, avi->segment.applied_rate, avi->segment.format,
3840         avi->segment.start, avi->segment.last_stop, avi->segment.time);
3841     gst_avi_demux_push_event (avi, seg);
3842   }
3843
3844   /* now update the real segment info */
3845   memcpy (&avi->segment, &seeksegment, sizeof (GstSegment));
3846
3847   /* post the SEGMENT_START message when we do segmented playback */
3848   if (avi->segment.flags & GST_SEEK_FLAG_SEGMENT) {
3849     gst_element_post_message (GST_ELEMENT_CAST (avi),
3850         gst_message_new_segment_start (GST_OBJECT_CAST (avi),
3851             avi->segment.format, avi->segment.last_stop));
3852   }
3853
3854   /* prepare for streaming again */
3855   if ((stop = avi->segment.stop) == GST_CLOCK_TIME_NONE)
3856     stop = avi->segment.duration;
3857
3858   /* queue the segment event for the streaming thread. */
3859   if (avi->seg_event)
3860     gst_event_unref (avi->seg_event);
3861   if (avi->segment.rate > 0.0) {
3862     /* forwards goes from last_stop to stop */
3863     avi->seg_event = gst_event_new_new_segment_full (FALSE,
3864         avi->segment.rate, avi->segment.applied_rate, avi->segment.format,
3865         avi->segment.last_stop, stop, avi->segment.time);
3866   } else {
3867     /* reverse goes from start to last_stop */
3868     avi->seg_event = gst_event_new_new_segment_full (FALSE,
3869         avi->segment.rate, avi->segment.applied_rate, avi->segment.format,
3870         avi->segment.start, avi->segment.last_stop, avi->segment.time);
3871   }
3872
3873   if (!avi->streaming) {
3874     avi->segment_running = TRUE;
3875     gst_pad_start_task (avi->sinkpad, (GstTaskFunction) gst_avi_demux_loop,
3876         avi->sinkpad);
3877   }
3878   GST_PAD_STREAM_UNLOCK (avi->sinkpad);
3879
3880   return TRUE;
3881
3882   /* ERRORS */
3883 no_format:
3884   {
3885     GST_DEBUG_OBJECT (avi, "unsupported format given, seek aborted.");
3886     return FALSE;
3887   }
3888 }
3889
3890 static gboolean
3891 gst_avi_demux_handle_seek_push (GstAviDemux * avi, GstPad * pad,
3892     GstEvent * event)
3893 {
3894   gdouble rate;
3895   GstFormat format;
3896   GstSeekFlags flags;
3897   GstSeekType cur_type, stop_type;
3898   gint64 cur, stop;
3899   gboolean res;
3900   gint64 byte_cur;
3901   gint64 time = 0;
3902   GstIndexEntry *entry;
3903
3904   GST_DEBUG_OBJECT (avi, "doing push-based seek");
3905
3906   gst_event_parse_seek (event, &rate, &format, &flags,
3907       &cur_type, &cur, &stop_type, &stop);
3908
3909   if (stop_type != GST_SEEK_TYPE_NONE)
3910     goto unsupported_seek;
3911   stop = -1;
3912
3913   /* only forward streaming and seeking is possible */
3914   if (rate <= 0)
3915     goto unsupported_seek;
3916
3917   /* only TIME */
3918   if (format != GST_FORMAT_TIME)
3919     goto unsupported_format;
3920
3921   /* not really advisable otherwise */
3922   if ((flags & GST_SEEK_FLAG_FLUSH) == 0)
3923     goto unsupported_seek;
3924
3925   /* should have index, let's check anyway */
3926   if (!avi->element_index)
3927     goto abort_seek;
3928
3929   /* find reasonable corresponding BYTE position
3930    * note that we have no keyframe info in push mode whatsoever,
3931    * so we can not cater for related stuff in any way */
3932
3933   /* some slack aiming for a keyframe */
3934   if (cur < GST_AVI_SEEK_PUSH_DISPLACE)
3935     cur = 0;
3936   else
3937     cur -= GST_AVI_SEEK_PUSH_DISPLACE;
3938
3939   entry = gst_index_get_assoc_entry (avi->element_index, avi->index_id,
3940       GST_INDEX_LOOKUP_BEFORE, GST_ASSOCIATION_FLAG_NONE, GST_FORMAT_TIME, cur);
3941
3942   if (!entry)
3943     goto abort_seek;
3944
3945   gst_index_entry_assoc_map (entry, GST_FORMAT_BYTES, &byte_cur);
3946   gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &time);
3947
3948   GST_DEBUG_OBJECT (avi, "found index entry for %" GST_TIME_FORMAT
3949       " at %" GST_TIME_FORMAT ", located at offset %" G_GINT64_FORMAT,
3950       GST_TIME_ARGS (cur), GST_TIME_ARGS (time), byte_cur);
3951
3952   /* adjust offset to be in each stream's region */
3953   byte_cur = gst_avi_demux_seek_streams (avi, byte_cur, TRUE);
3954
3955   /* let's not try push seeking if target and entry are too far apart */
3956   if (cur - time > 30 * GST_SECOND)
3957     goto abort_seek;
3958
3959   GST_DEBUG_OBJECT (avi, "Pushing BYTE seek rate %g, "
3960       "start %" G_GINT64_FORMAT ", stop %" G_GINT64_FORMAT, rate, byte_cur,
3961       stop);
3962   /* BYTE seek event */
3963   event = gst_event_new_seek (rate, GST_FORMAT_BYTES, flags, cur_type, byte_cur,
3964       stop_type, stop);
3965   res = gst_pad_push_event (avi->sinkpad, event);
3966
3967   return res;
3968
3969   /* ERRORS */
3970 abort_seek:
3971   {
3972     GST_DEBUG_OBJECT (avi, "could not determine byte position to seek to, "
3973         "seek aborted.");
3974     return FALSE;
3975   }
3976 unsupported_seek:
3977   {
3978     GST_DEBUG_OBJECT (avi, "unsupported seek, seek aborted.");
3979     return FALSE;
3980   }
3981 unsupported_format:
3982   {
3983     GST_DEBUG_OBJECT (avi, "unsupported format given, seek aborted.");
3984     return FALSE;
3985   }
3986 }
3987
3988 /*
3989  * Helper for gst_avi_demux_invert()
3990  */
3991 static inline void
3992 swap_line (guint8 * d1, guint8 * d2, guint8 * tmp, gint bytes)
3993 {
3994   memcpy (tmp, d1, bytes);
3995   memcpy (d1, d2, bytes);
3996   memcpy (d2, tmp, bytes);
3997 }
3998
3999
4000 #define gst_avi_demux_is_uncompressed(fourcc)           \
4001   (fourcc == GST_RIFF_DIB ||                            \
4002    fourcc == GST_RIFF_rgb ||                            \
4003    fourcc == GST_RIFF_RGB || fourcc == GST_RIFF_RAW)
4004
4005 /*
4006  * Invert DIB buffers... Takes existing buffer and
4007  * returns either the buffer or a new one (with old
4008  * one dereferenced).
4009  * FIXME: can't we preallocate tmp? and remember stride, bpp?
4010  */
4011 static GstBuffer *
4012 gst_avi_demux_invert (GstAviStream * stream, GstBuffer * buf)
4013 {
4014   GstStructure *s;
4015   gint y, w, h;
4016   gint bpp, stride;
4017   guint8 *tmp = NULL;
4018
4019   if (stream->strh->type != GST_RIFF_FCC_vids)
4020     return buf;
4021
4022   if (!gst_avi_demux_is_uncompressed (stream->strh->fcc_handler)) {
4023     return buf;                 /* Ignore non DIB buffers */
4024   }
4025
4026   s = gst_caps_get_structure (GST_PAD_CAPS (stream->pad), 0);
4027   if (!gst_structure_get_int (s, "bpp", &bpp)) {
4028     GST_WARNING ("Failed to retrieve depth from caps");
4029     return buf;
4030   }
4031
4032   if (stream->strf.vids == NULL) {
4033     GST_WARNING ("Failed to retrieve vids for stream");
4034     return buf;
4035   }
4036
4037   h = stream->strf.vids->height;
4038   w = stream->strf.vids->width;
4039   stride = w * (bpp / 8);
4040
4041   buf = gst_buffer_make_writable (buf);
4042   if (GST_BUFFER_SIZE (buf) < (stride * h)) {
4043     GST_WARNING ("Buffer is smaller than reported Width x Height x Depth");
4044     return buf;
4045   }
4046
4047   tmp = g_malloc (stride);
4048
4049   for (y = 0; y < h / 2; y++) {
4050     swap_line (GST_BUFFER_DATA (buf) + stride * y,
4051         GST_BUFFER_DATA (buf) + stride * (h - 1 - y), tmp, stride);
4052   }
4053
4054   g_free (tmp);
4055
4056   return buf;
4057 }
4058
4059 static void
4060 gst_avi_demux_add_assoc (GstAviDemux * avi, GstAviStream * stream,
4061     GstClockTime timestamp, guint64 offset, gboolean keyframe)
4062 {
4063   /* do not add indefinitely for open-ended streaming */
4064   if (G_UNLIKELY (avi->element_index && avi->seekable)) {
4065     GST_LOG_OBJECT (avi, "adding association %" GST_TIME_FORMAT "-> %"
4066         G_GUINT64_FORMAT, GST_TIME_ARGS (timestamp), offset);
4067     gst_index_add_association (avi->element_index, avi->index_id,
4068         keyframe ? GST_ASSOCIATION_FLAG_KEY_UNIT : GST_ASSOCIATION_FLAG_NONE,
4069         GST_FORMAT_TIME, timestamp, GST_FORMAT_BYTES, offset, NULL);
4070     /* well, current_total determines TIME and entry DEFAULT (frame #) ... */
4071     gst_index_add_association (avi->element_index, stream->index_id,
4072         GST_ASSOCIATION_FLAG_NONE,
4073         GST_FORMAT_TIME, stream->current_total, GST_FORMAT_BYTES, offset,
4074         GST_FORMAT_DEFAULT, stream->current_entry, NULL);
4075   }
4076 }
4077
4078 /*
4079  * Returns the aggregated GstFlowReturn.
4080  */
4081 static GstFlowReturn
4082 gst_avi_demux_combine_flows (GstAviDemux * avi, GstAviStream * stream,
4083     GstFlowReturn ret)
4084 {
4085   guint i;
4086   gboolean unexpected = FALSE, not_linked = TRUE;
4087
4088   /* store the value */
4089   stream->last_flow = ret;
4090
4091   /* any other error that is not-linked or eos can be returned right away */
4092   if (G_LIKELY (ret != GST_FLOW_UNEXPECTED && ret != GST_FLOW_NOT_LINKED))
4093     goto done;
4094
4095   /* only return NOT_LINKED if all other pads returned NOT_LINKED */
4096   for (i = 0; i < avi->num_streams; i++) {
4097     GstAviStream *ostream = &avi->stream[i];
4098
4099     ret = ostream->last_flow;
4100     /* no unexpected or unlinked, return */
4101     if (G_LIKELY (ret != GST_FLOW_UNEXPECTED && ret != GST_FLOW_NOT_LINKED))
4102       goto done;
4103
4104     /* we check to see if we have at least 1 unexpected or all unlinked */
4105     unexpected |= (ret == GST_FLOW_UNEXPECTED);
4106     not_linked &= (ret == GST_FLOW_NOT_LINKED);
4107   }
4108   /* when we get here, we all have unlinked or unexpected */
4109   if (not_linked)
4110     ret = GST_FLOW_NOT_LINKED;
4111   else if (unexpected)
4112     ret = GST_FLOW_UNEXPECTED;
4113 done:
4114   GST_LOG_OBJECT (avi, "combined %s to return %s",
4115       gst_flow_get_name (stream->last_flow), gst_flow_get_name (ret));
4116   return ret;
4117 }
4118
4119 /* move @stream to the next position in its index */
4120 static GstFlowReturn
4121 gst_avi_demux_advance (GstAviDemux * avi, GstAviStream * stream,
4122     GstFlowReturn ret)
4123 {
4124   guint old_entry, new_entry;
4125
4126   old_entry = stream->current_entry;
4127   /* move forwards */
4128   new_entry = old_entry + 1;
4129
4130   /* see if we reached the end */
4131   if (new_entry > stream->stop_entry) {
4132     if (avi->segment.rate < 0.0) {
4133       if (stream->step_entry == stream->start_entry) {
4134         /* we stepped all the way to the start, eos */
4135         GST_DEBUG_OBJECT (avi, "reverse reached start %u", stream->start_entry);
4136         goto eos;
4137       }
4138       /* backwards, stop becomes step, find a new step */
4139       stream->stop_entry = stream->step_entry;
4140       stream->step_entry = gst_avi_demux_index_prev (avi, stream,
4141           stream->stop_entry, TRUE);
4142
4143       GST_DEBUG_OBJECT (avi,
4144           "reverse playback jump: start %u, step %u, stop %u",
4145           stream->start_entry, stream->step_entry, stream->stop_entry);
4146
4147       /* and start from the previous keyframe now */
4148       new_entry = stream->step_entry;
4149     } else {
4150       /* EOS */
4151       GST_DEBUG_OBJECT (avi, "forward reached stop %u", stream->stop_entry);
4152       goto eos;
4153     }
4154   }
4155
4156   if (new_entry != old_entry) {
4157     stream->current_entry = new_entry;
4158     stream->current_total = stream->index[new_entry].total;
4159
4160     if (new_entry == old_entry + 1) {
4161       GST_DEBUG_OBJECT (avi, "moved forwards from %u to %u",
4162           old_entry, new_entry);
4163       /* we simply moved one step forwards, reuse current info */
4164       stream->current_timestamp = stream->current_ts_end;
4165       stream->current_offset = stream->current_offset_end;
4166       gst_avi_demux_get_buffer_info (avi, stream, new_entry,
4167           NULL, &stream->current_ts_end, NULL, &stream->current_offset_end);
4168     } else {
4169       /* we moved DISCONT, full update */
4170       gst_avi_demux_get_buffer_info (avi, stream, new_entry,
4171           &stream->current_timestamp, &stream->current_ts_end,
4172           &stream->current_offset, &stream->current_offset_end);
4173       /* and MARK discont for this stream */
4174       stream->last_flow = GST_FLOW_OK;
4175       stream->discont = TRUE;
4176       GST_DEBUG_OBJECT (avi, "Moved from %u to %u, ts %" GST_TIME_FORMAT
4177           ", ts_end %" GST_TIME_FORMAT ", off %" G_GUINT64_FORMAT
4178           ", off_end %" G_GUINT64_FORMAT, old_entry, new_entry,
4179           GST_TIME_ARGS (stream->current_timestamp),
4180           GST_TIME_ARGS (stream->current_ts_end), stream->current_offset,
4181           stream->current_offset_end);
4182     }
4183   }
4184   return ret;
4185
4186   /* ERROR */
4187 eos:
4188   {
4189     GST_DEBUG_OBJECT (avi, "we are EOS");
4190     /* setting current_timestamp to -1 marks EOS */
4191     stream->current_timestamp = -1;
4192     return GST_FLOW_UNEXPECTED;
4193   }
4194 }
4195
4196 /* find the stream with the lowest current position when going forwards or with
4197  * the highest position when going backwards, this is the stream
4198  * we should push from next */
4199 static gint
4200 gst_avi_demux_find_next (GstAviDemux * avi, gfloat rate)
4201 {
4202   guint64 min_time, max_time;
4203   guint stream_num, i;
4204
4205   max_time = 0;
4206   min_time = G_MAXUINT64;
4207   stream_num = -1;
4208
4209   for (i = 0; i < avi->num_streams; i++) {
4210     guint64 position;
4211     GstAviStream *stream;
4212
4213     stream = &avi->stream[i];
4214
4215     /* ignore streams that finished */
4216     if (stream->last_flow == GST_FLOW_UNEXPECTED)
4217       continue;
4218
4219     position = stream->current_timestamp;
4220
4221     /* position of -1 is EOS */
4222     if (position != -1) {
4223       if (rate > 0.0 && position < min_time) {
4224         min_time = position;
4225         stream_num = i;
4226       } else if (rate < 0.0 && position >= max_time) {
4227         max_time = position;
4228         stream_num = i;
4229       }
4230     }
4231   }
4232   return stream_num;
4233 }
4234
4235 static GstFlowReturn
4236 gst_avi_demux_loop_data (GstAviDemux * avi)
4237 {
4238   GstFlowReturn ret = GST_FLOW_OK;
4239   guint stream_num;
4240   GstAviStream *stream;
4241   gboolean processed = FALSE;
4242   GstBuffer *buf;
4243   guint64 offset, size;
4244   GstClockTime timestamp, duration;
4245   guint64 out_offset, out_offset_end;
4246   gboolean keyframe;
4247   GstAviIndexEntry *entry;
4248
4249   do {
4250     stream_num = gst_avi_demux_find_next (avi, avi->segment.rate);
4251
4252     /* all are EOS */
4253     if (G_UNLIKELY (stream_num == -1)) {
4254       GST_DEBUG_OBJECT (avi, "all streams are EOS");
4255       goto eos;
4256     }
4257
4258     /* we have the stream now */
4259     stream = &avi->stream[stream_num];
4260
4261     /* skip streams without pads */
4262     if (!stream->pad) {
4263       GST_DEBUG_OBJECT (avi, "skipping entry from stream %d without pad",
4264           stream_num);
4265       goto next;
4266     }
4267
4268     /* get the timing info for the entry */
4269     timestamp = stream->current_timestamp;
4270     duration = stream->current_ts_end - timestamp;
4271     out_offset = stream->current_offset;
4272     out_offset_end = stream->current_offset_end;
4273
4274     /* get the entry data info */
4275     entry = &stream->index[stream->current_entry];
4276     offset = entry->offset;
4277     size = entry->size;
4278     keyframe = ENTRY_IS_KEYFRAME (entry);
4279
4280     /* skip empty entries */
4281     if (size == 0) {
4282       GST_DEBUG_OBJECT (avi, "Skipping entry %u (%" G_GUINT64_FORMAT ", %p)",
4283           stream->current_entry, size, stream->pad);
4284       goto next;
4285     }
4286
4287     if (avi->segment.rate > 0.0) {
4288       /* only check this for fowards playback for now */
4289       if (keyframe && GST_CLOCK_TIME_IS_VALID (avi->segment.stop)
4290           && (timestamp > avi->segment.stop)) {
4291         goto eos_stop;
4292       }
4293     }
4294
4295     GST_LOG ("reading buffer (size=%" G_GUINT64_FORMAT "), stream %d, pos %"
4296         G_GUINT64_FORMAT " (0x%" G_GINT64_MODIFIER "x), kf %d", size,
4297         stream_num, offset, offset, keyframe);
4298
4299     /* FIXME, check large chunks and cut them up */
4300
4301     /* pull in the data */
4302     ret = gst_pad_pull_range (avi->sinkpad, offset, size, &buf);
4303     if (ret != GST_FLOW_OK)
4304       goto pull_failed;
4305
4306     /* check for short buffers, this is EOS as well */
4307     if (GST_BUFFER_SIZE (buf) < size)
4308       goto short_buffer;
4309
4310     /* invert the picture if needed */
4311     buf = gst_avi_demux_invert (stream, buf);
4312
4313     /* mark non-keyframes */
4314     if (keyframe)
4315       GST_BUFFER_FLAG_UNSET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
4316     else
4317       GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
4318
4319     GST_BUFFER_TIMESTAMP (buf) = timestamp;
4320     GST_BUFFER_DURATION (buf) = duration;
4321     GST_BUFFER_OFFSET (buf) = out_offset;
4322     GST_BUFFER_OFFSET_END (buf) = out_offset_end;
4323
4324     /* mark discont when pending */
4325     if (stream->discont) {
4326       GST_DEBUG_OBJECT (avi, "setting DISCONT flag");
4327       GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
4328       stream->discont = FALSE;
4329     }
4330
4331     gst_avi_demux_add_assoc (avi, stream, timestamp, offset, keyframe);
4332
4333     gst_buffer_set_caps (buf, GST_PAD_CAPS (stream->pad));
4334
4335     /* update current position in the segment */
4336     gst_segment_set_last_stop (&avi->segment, GST_FORMAT_TIME, timestamp);
4337
4338     GST_DEBUG_OBJECT (avi, "Pushing buffer of size %u, ts %"
4339         GST_TIME_FORMAT ", dur %" GST_TIME_FORMAT ", off %" G_GUINT64_FORMAT
4340         ", off_end %" G_GUINT64_FORMAT,
4341         GST_BUFFER_SIZE (buf), GST_TIME_ARGS (timestamp),
4342         GST_TIME_ARGS (duration), out_offset, out_offset_end);
4343
4344     ret = gst_pad_push (stream->pad, buf);
4345
4346     /* mark as processed, we increment the frame and byte counters then
4347      * leave the while loop and return the GstFlowReturn */
4348     processed = TRUE;
4349
4350     if (avi->segment.rate < 0) {
4351       if (timestamp > avi->segment.stop && ret == GST_FLOW_UNEXPECTED) {
4352         /* In reverse playback we can get a GST_FLOW_UNEXPECTED when
4353          * we are at the end of the segment, so we just need to jump
4354          * back to the previous section. */
4355         GST_DEBUG_OBJECT (avi, "downstream has reached end of segment");
4356         ret = GST_FLOW_OK;
4357       }
4358     }
4359   next:
4360     /* move to next item */
4361     ret = gst_avi_demux_advance (avi, stream, ret);
4362
4363     /* combine flows */
4364     ret = gst_avi_demux_combine_flows (avi, stream, ret);
4365   } while (!processed);
4366
4367 beach:
4368   return ret;
4369
4370   /* special cases */
4371 eos:
4372   {
4373     GST_DEBUG_OBJECT (avi, "No samples left for any streams - EOS");
4374     ret = GST_FLOW_UNEXPECTED;
4375     goto beach;
4376   }
4377 eos_stop:
4378   {
4379     GST_LOG_OBJECT (avi, "Found keyframe after segment,"
4380         " setting EOS (%" GST_TIME_FORMAT " > %" GST_TIME_FORMAT ")",
4381         GST_TIME_ARGS (timestamp), GST_TIME_ARGS (avi->segment.stop));
4382     ret = GST_FLOW_UNEXPECTED;
4383     /* move to next stream */
4384     goto next;
4385   }
4386 pull_failed:
4387   {
4388     GST_DEBUG_OBJECT (avi, "pull range failed: pos=%" G_GUINT64_FORMAT
4389         " size=%" G_GUINT64_FORMAT, offset, size);
4390     goto beach;
4391   }
4392 short_buffer:
4393   {
4394     GST_WARNING_OBJECT (avi, "Short read at offset %" G_GUINT64_FORMAT
4395         ", only got %d/%" G_GUINT64_FORMAT " bytes (truncated file?)", offset,
4396         GST_BUFFER_SIZE (buf), size);
4397     gst_buffer_unref (buf);
4398     ret = GST_FLOW_UNEXPECTED;
4399     goto beach;
4400   }
4401 }
4402
4403 /*
4404  * Read data. If we have an index it delegates to
4405  * gst_avi_demux_process_next_entry().
4406  */
4407 static GstFlowReturn
4408 gst_avi_demux_stream_data (GstAviDemux * avi)
4409 {
4410   guint32 tag = 0;
4411   guint32 size = 0;
4412   gint stream_nr = 0;
4413   GstFlowReturn res = GST_FLOW_OK;
4414   GstFormat format = GST_FORMAT_TIME;
4415
4416   if (G_UNLIKELY (avi->have_eos)) {
4417     /* Clean adapter, we're done */
4418     gst_adapter_clear (avi->adapter);
4419     return GST_FLOW_UNEXPECTED;
4420   }
4421
4422   if (G_UNLIKELY (avi->todrop)) {
4423     guint drop;
4424
4425     if ((drop = gst_adapter_available (avi->adapter))) {
4426       if (drop > avi->todrop)
4427         drop = avi->todrop;
4428       GST_DEBUG_OBJECT (avi, "Dropping %d bytes", drop);
4429       gst_adapter_flush (avi->adapter, drop);
4430       avi->todrop -= drop;
4431       avi->offset += drop;
4432     }
4433   }
4434
4435   /* Iterate until need more data, so adapter won't grow too much */
4436   while (1) {
4437     if (G_UNLIKELY (!gst_avi_demux_peek_chunk_info (avi, &tag, &size))) {
4438       return GST_FLOW_OK;
4439     }
4440
4441     GST_DEBUG ("Trying chunk (%" GST_FOURCC_FORMAT "), size %d",
4442         GST_FOURCC_ARGS (tag), size);
4443
4444     if (G_LIKELY ((tag & 0xff) >= '0' && (tag & 0xff) <= '9' &&
4445             ((tag >> 8) & 0xff) >= '0' && ((tag >> 8) & 0xff) <= '9')) {
4446       GST_LOG ("Chunk ok");
4447     } else if ((tag & 0xffff) == (('x' << 8) | 'i')) {
4448       GST_DEBUG ("Found sub-index tag");
4449       if (gst_avi_demux_peek_chunk (avi, &tag, &size) || size == 0) {
4450         /* accept 0 size buffer here */
4451         avi->abort_buffering = FALSE;
4452         GST_DEBUG ("  skipping %d bytes for now", size);
4453         gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
4454       }
4455       return GST_FLOW_OK;
4456     } else if (tag == GST_RIFF_TAG_RIFF) {
4457       /* RIFF tags can appear in ODML files, just jump over them */
4458       if (gst_adapter_available (avi->adapter) >= 12) {
4459         GST_DEBUG ("Found RIFF tag, skipping RIFF header");
4460         gst_adapter_flush (avi->adapter, 12);
4461         continue;
4462       }
4463       return GST_FLOW_OK;
4464     } else if (tag == GST_RIFF_TAG_idx1) {
4465       GST_DEBUG ("Found index tag");
4466       if (gst_avi_demux_peek_chunk (avi, &tag, &size) || size == 0) {
4467         /* accept 0 size buffer here */
4468         avi->abort_buffering = FALSE;
4469         GST_DEBUG ("  skipping %d bytes for now", size);
4470         gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
4471       }
4472       return GST_FLOW_OK;
4473     } else if (tag == GST_RIFF_TAG_LIST) {
4474       /* movi chunks might be grouped in rec list */
4475       if (gst_adapter_available (avi->adapter) >= 12) {
4476         GST_DEBUG ("Found LIST tag, skipping LIST header");
4477         gst_adapter_flush (avi->adapter, 12);
4478         continue;
4479       }
4480       return GST_FLOW_OK;
4481     } else if (tag == GST_RIFF_TAG_JUNK || tag == GST_RIFF_TAG_JUNQ) {
4482       /* rec list might contain JUNK chunks */
4483       GST_DEBUG ("Found JUNK tag");
4484       if (gst_avi_demux_peek_chunk (avi, &tag, &size) || size == 0) {
4485         /* accept 0 size buffer here */
4486         avi->abort_buffering = FALSE;
4487         GST_DEBUG ("  skipping %d bytes for now", size);
4488         gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
4489       }
4490       return GST_FLOW_OK;
4491     } else {
4492       GST_DEBUG ("No more stream chunks, send EOS");
4493       avi->have_eos = TRUE;
4494       return GST_FLOW_UNEXPECTED;
4495     }
4496
4497     if (G_UNLIKELY (!gst_avi_demux_peek_chunk (avi, &tag, &size))) {
4498       /* supposedly one hopes to catch a nicer chunk later on ... */
4499       /* FIXME ?? give up here rather than possibly ending up going
4500        * through the whole file */
4501       if (avi->abort_buffering) {
4502         avi->abort_buffering = FALSE;
4503         gst_adapter_flush (avi->adapter, 8);
4504       }
4505       return GST_FLOW_OK;
4506     }
4507     GST_DEBUG ("chunk ID %" GST_FOURCC_FORMAT ", size %u",
4508         GST_FOURCC_ARGS (tag), size);
4509
4510     stream_nr = CHUNKID_TO_STREAMNR (tag);
4511
4512     if (G_UNLIKELY (stream_nr < 0 || stream_nr >= avi->num_streams)) {
4513       /* recoverable */
4514       GST_WARNING ("Invalid stream ID %d (%" GST_FOURCC_FORMAT ")",
4515           stream_nr, GST_FOURCC_ARGS (tag));
4516       avi->offset += 8 + GST_ROUND_UP_2 (size);
4517       gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
4518     } else {
4519       GstAviStream *stream;
4520       GstClockTime next_ts = 0;
4521       GstBuffer *buf;
4522       guint64 offset;
4523
4524       gst_adapter_flush (avi->adapter, 8);
4525
4526       /* get buffer */
4527       buf = gst_adapter_take_buffer (avi->adapter, GST_ROUND_UP_2 (size));
4528       /* patch the size */
4529       GST_BUFFER_SIZE (buf) = size;
4530       offset = avi->offset;
4531       avi->offset += 8 + GST_ROUND_UP_2 (size);
4532
4533       stream = &avi->stream[stream_nr];
4534
4535       /* set delay (if any)
4536          if (stream->strh->init_frames == stream->current_frame &&
4537          stream->delay == 0)
4538          stream->delay = next_ts;
4539        */
4540
4541       /* parsing of corresponding header may have failed */
4542       if (G_UNLIKELY (!stream->pad)) {
4543         GST_WARNING_OBJECT (avi, "no pad for stream ID %" GST_FOURCC_FORMAT,
4544             GST_FOURCC_ARGS (tag));
4545         gst_buffer_unref (buf);
4546       } else {
4547         GstClockTime dur_ts = 0;
4548
4549         /* get time of this buffer */
4550         gst_pad_query_position (stream->pad, &format, (gint64 *) & next_ts);
4551         if (G_UNLIKELY (format != GST_FORMAT_TIME))
4552           goto wrong_format;
4553
4554         gst_avi_demux_add_assoc (avi, stream, next_ts, offset, FALSE);
4555
4556         /* increment our positions */
4557         stream->current_entry++;
4558         stream->current_total += size;
4559
4560         /* invert the picture if needed */
4561         buf = gst_avi_demux_invert (stream, buf);
4562
4563         gst_pad_query_position (stream->pad, &format, (gint64 *) & dur_ts);
4564         if (G_UNLIKELY (format != GST_FORMAT_TIME))
4565           goto wrong_format;
4566
4567         GST_BUFFER_TIMESTAMP (buf) = next_ts;
4568         GST_BUFFER_DURATION (buf) = dur_ts - next_ts;
4569         if (stream->strh->type == GST_RIFF_FCC_vids) {
4570           GST_BUFFER_OFFSET (buf) = stream->current_entry - 1;
4571           GST_BUFFER_OFFSET_END (buf) = stream->current_entry;
4572         } else {
4573           GST_BUFFER_OFFSET (buf) = GST_BUFFER_OFFSET_NONE;
4574           GST_BUFFER_OFFSET_END (buf) = GST_BUFFER_OFFSET_NONE;
4575         }
4576
4577         gst_buffer_set_caps (buf, GST_PAD_CAPS (stream->pad));
4578         GST_DEBUG_OBJECT (avi,
4579             "Pushing buffer with time=%" GST_TIME_FORMAT ", duration %"
4580             GST_TIME_FORMAT ", offset %" G_GUINT64_FORMAT
4581             " and size %d over pad %s", GST_TIME_ARGS (next_ts),
4582             GST_TIME_ARGS (GST_BUFFER_DURATION (buf)), GST_BUFFER_OFFSET (buf),
4583             size, GST_PAD_NAME (stream->pad));
4584
4585         /* update current position in the segment */
4586         gst_segment_set_last_stop (&avi->segment, GST_FORMAT_TIME, next_ts);
4587
4588         /* mark discont when pending */
4589         if (G_UNLIKELY (stream->discont)) {
4590           GST_DEBUG_OBJECT (avi, "Setting DISCONT");
4591           GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
4592           stream->discont = FALSE;
4593         }
4594         res = gst_pad_push (stream->pad, buf);
4595
4596         /* combine flows */
4597         res = gst_avi_demux_combine_flows (avi, stream, res);
4598         if (G_UNLIKELY (res != GST_FLOW_OK)) {
4599           GST_DEBUG ("Push failed; %s", gst_flow_get_name (res));
4600           return res;
4601         }
4602       }
4603     }
4604   }
4605
4606 done:
4607   return res;
4608
4609   /* ERRORS */
4610 wrong_format:
4611   {
4612     GST_DEBUG_OBJECT (avi, "format %s != GST_FORMAT_TIME",
4613         gst_format_get_name (format));
4614     res = GST_FLOW_ERROR;
4615     goto done;
4616   }
4617 }
4618
4619 /*
4620  * Send pending tags.
4621  */
4622 static void
4623 push_tag_lists (GstAviDemux * avi)
4624 {
4625   guint i;
4626   GstTagList *tags;
4627
4628   if (!avi->got_tags)
4629     return;
4630
4631   GST_DEBUG_OBJECT (avi, "Pushing pending tag lists");
4632
4633   for (i = 0; i < avi->num_streams; i++) {
4634     GstAviStream *stream = &avi->stream[i];
4635     GstPad *pad = stream->pad;
4636
4637     tags = stream->taglist;
4638
4639     if (pad && tags) {
4640       GST_DEBUG_OBJECT (pad, "Tags: %" GST_PTR_FORMAT, tags);
4641
4642       gst_element_found_tags_for_pad (GST_ELEMENT_CAST (avi), pad, tags);
4643       stream->taglist = NULL;
4644     }
4645   }
4646
4647   if (!(tags = avi->globaltags))
4648     tags = gst_tag_list_new ();
4649
4650   gst_tag_list_add (tags, GST_TAG_MERGE_REPLACE,
4651       GST_TAG_CONTAINER_FORMAT, "AVI", NULL);
4652
4653   GST_DEBUG_OBJECT (avi, "Global tags: %" GST_PTR_FORMAT, tags);
4654   gst_element_found_tags (GST_ELEMENT_CAST (avi), tags);
4655   avi->globaltags = NULL;
4656   avi->got_tags = FALSE;
4657 }
4658
4659 static void
4660 gst_avi_demux_loop (GstPad * pad)
4661 {
4662   GstFlowReturn res;
4663   GstAviDemux *avi = GST_AVI_DEMUX (GST_PAD_PARENT (pad));
4664
4665   switch (avi->state) {
4666     case GST_AVI_DEMUX_START:
4667       res = gst_avi_demux_stream_init_pull (avi);
4668       if (G_UNLIKELY (res != GST_FLOW_OK)) {
4669         GST_WARNING ("stream_init flow: %s", gst_flow_get_name (res));
4670         goto pause;
4671       }
4672       avi->state = GST_AVI_DEMUX_HEADER;
4673       /* fall-through */
4674     case GST_AVI_DEMUX_HEADER:
4675       res = gst_avi_demux_stream_header_pull (avi);
4676       if (G_UNLIKELY (res != GST_FLOW_OK)) {
4677         GST_WARNING ("stream_header flow: %s", gst_flow_get_name (res));
4678         goto pause;
4679       }
4680       avi->state = GST_AVI_DEMUX_MOVI;
4681       break;
4682     case GST_AVI_DEMUX_MOVI:
4683       if (G_UNLIKELY (avi->seg_event)) {
4684         gst_avi_demux_push_event (avi, avi->seg_event);
4685         avi->seg_event = NULL;
4686       }
4687       if (G_UNLIKELY (avi->got_tags)) {
4688         push_tag_lists (avi);
4689       }
4690       /* process each index entry in turn */
4691       res = gst_avi_demux_loop_data (avi);
4692
4693       /* pause when error */
4694       if (G_UNLIKELY (res != GST_FLOW_OK)) {
4695         GST_INFO ("stream_movi flow: %s", gst_flow_get_name (res));
4696         goto pause;
4697       }
4698       break;
4699     default:
4700       GST_ERROR_OBJECT (avi, "unknown state %d", avi->state);
4701       res = GST_FLOW_ERROR;
4702       goto pause;
4703   }
4704
4705   return;
4706
4707   /* ERRORS */
4708 pause:
4709   GST_LOG_OBJECT (avi, "pausing task, reason %s", gst_flow_get_name (res));
4710   avi->segment_running = FALSE;
4711   gst_pad_pause_task (avi->sinkpad);
4712
4713   if (GST_FLOW_IS_FATAL (res) || (res == GST_FLOW_NOT_LINKED)) {
4714     gboolean push_eos = TRUE;
4715
4716     if (res == GST_FLOW_UNEXPECTED) {
4717       /* handle end-of-stream/segment */
4718       if (avi->segment.flags & GST_SEEK_FLAG_SEGMENT) {
4719         gint64 stop;
4720
4721         if ((stop = avi->segment.stop) == -1)
4722           stop = avi->segment.duration;
4723
4724         GST_INFO_OBJECT (avi, "sending segment_done");
4725
4726         gst_element_post_message
4727             (GST_ELEMENT_CAST (avi),
4728             gst_message_new_segment_done (GST_OBJECT_CAST (avi),
4729                 GST_FORMAT_TIME, stop));
4730         push_eos = FALSE;
4731       }
4732     } else {
4733       /* for fatal errors we post an error message */
4734       GST_ELEMENT_ERROR (avi, STREAM, FAILED,
4735           (_("Internal data stream error.")),
4736           ("streaming stopped, reason %s", gst_flow_get_name (res)));
4737     }
4738     if (push_eos) {
4739       GST_INFO_OBJECT (avi, "sending eos");
4740       if (!gst_avi_demux_push_event (avi, gst_event_new_eos ()) &&
4741           (res == GST_FLOW_UNEXPECTED)) {
4742         GST_ELEMENT_ERROR (avi, STREAM, DEMUX,
4743             (NULL), ("got eos but no streams (yet)"));
4744       }
4745     }
4746   }
4747 }
4748
4749
4750 static GstFlowReturn
4751 gst_avi_demux_chain (GstPad * pad, GstBuffer * buf)
4752 {
4753   GstFlowReturn res;
4754   GstAviDemux *avi = GST_AVI_DEMUX (GST_PAD_PARENT (pad));
4755   gint i;
4756
4757   if (GST_BUFFER_IS_DISCONT (buf)) {
4758     GST_DEBUG_OBJECT (avi, "got DISCONT");
4759     gst_adapter_clear (avi->adapter);
4760     /* mark all streams DISCONT */
4761     for (i = 0; i < avi->num_streams; i++)
4762       avi->stream[i].discont = TRUE;
4763   }
4764
4765   GST_DEBUG ("Store %d bytes in adapter", GST_BUFFER_SIZE (buf));
4766   gst_adapter_push (avi->adapter, buf);
4767
4768   switch (avi->state) {
4769     case GST_AVI_DEMUX_START:
4770       if ((res = gst_avi_demux_stream_init_push (avi)) != GST_FLOW_OK) {
4771         GST_WARNING ("stream_init flow: %s", gst_flow_get_name (res));
4772         break;
4773       }
4774       break;
4775     case GST_AVI_DEMUX_HEADER:
4776       if ((res = gst_avi_demux_stream_header_push (avi)) != GST_FLOW_OK) {
4777         GST_WARNING ("stream_header flow: %s", gst_flow_get_name (res));
4778         break;
4779       }
4780       break;
4781     case GST_AVI_DEMUX_MOVI:
4782       if (G_UNLIKELY (avi->seg_event)) {
4783         gst_avi_demux_push_event (avi, avi->seg_event);
4784         avi->seg_event = NULL;
4785       }
4786       if (G_UNLIKELY (avi->got_tags)) {
4787         push_tag_lists (avi);
4788       }
4789       res = gst_avi_demux_stream_data (avi);
4790       break;
4791     default:
4792       GST_ELEMENT_ERROR (avi, STREAM, FAILED, (NULL),
4793           ("Illegal internal state"));
4794       res = GST_FLOW_ERROR;
4795       break;
4796   }
4797
4798   GST_DEBUG_OBJECT (avi, "state: %d res:%s", avi->state,
4799       gst_flow_get_name (res));
4800
4801   if (G_UNLIKELY (avi->abort_buffering)) {
4802     avi->abort_buffering = FALSE;
4803     res = GST_FLOW_ERROR;
4804     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("unhandled buffer size"));
4805   }
4806
4807   return res;
4808 }
4809
4810 static gboolean
4811 gst_avi_demux_sink_activate (GstPad * sinkpad)
4812 {
4813   if (gst_pad_check_pull_range (sinkpad)) {
4814     GST_DEBUG ("going to pull mode");
4815     return gst_pad_activate_pull (sinkpad, TRUE);
4816   } else {
4817     GST_DEBUG ("going to push (streaming) mode");
4818     return gst_pad_activate_push (sinkpad, TRUE);
4819   }
4820 }
4821
4822 static gboolean
4823 gst_avi_demux_sink_activate_pull (GstPad * sinkpad, gboolean active)
4824 {
4825   GstAviDemux *avi = GST_AVI_DEMUX (GST_OBJECT_PARENT (sinkpad));
4826
4827   if (active) {
4828     avi->segment_running = TRUE;
4829     avi->streaming = FALSE;
4830     return gst_pad_start_task (sinkpad, (GstTaskFunction) gst_avi_demux_loop,
4831         sinkpad);
4832   } else {
4833     avi->segment_running = FALSE;
4834     return gst_pad_stop_task (sinkpad);
4835   }
4836 }
4837
4838 static gboolean
4839 gst_avi_demux_activate_push (GstPad * pad, gboolean active)
4840 {
4841   GstAviDemux *avi = GST_AVI_DEMUX (GST_OBJECT_PARENT (pad));
4842
4843   if (active) {
4844     GST_DEBUG ("avi: activating push/chain function");
4845     avi->streaming = TRUE;
4846 #if 0
4847     /* create index for some push based seeking if not provided */
4848     GST_OBJECT_LOCK (avi);
4849     if (!avi->element_index) {
4850       GST_DEBUG_OBJECT (avi, "creating index");
4851       avi->element_index = gst_index_factory_make ("memindex");
4852     }
4853     GST_OBJECT_UNLOCK (avi);
4854     /* object lock might be taken again */
4855     gst_index_get_writer_id (avi->element_index, GST_OBJECT_CAST (avi),
4856         &avi->index_id);
4857 #endif
4858   } else {
4859     GST_DEBUG ("avi: deactivating push/chain function");
4860   }
4861
4862   return TRUE;
4863 }
4864
4865 static void
4866 gst_avi_demux_set_index (GstElement * element, GstIndex * index)
4867 {
4868   GstAviDemux *avi = GST_AVI_DEMUX (element);
4869
4870   GST_OBJECT_LOCK (avi);
4871   if (avi->element_index)
4872     gst_object_unref (avi->element_index);
4873   if (index) {
4874     avi->element_index = gst_object_ref (index);
4875   } else {
4876     avi->element_index = NULL;
4877   }
4878   GST_OBJECT_UNLOCK (avi);
4879   /* object lock might be taken again */
4880   if (index)
4881     gst_index_get_writer_id (index, GST_OBJECT_CAST (element), &avi->index_id);
4882   GST_DEBUG_OBJECT (avi, "Set index %" GST_PTR_FORMAT, avi->element_index);
4883 }
4884
4885 static GstIndex *
4886 gst_avi_demux_get_index (GstElement * element)
4887 {
4888   GstIndex *result = NULL;
4889   GstAviDemux *avi = GST_AVI_DEMUX (element);
4890
4891   GST_OBJECT_LOCK (avi);
4892   if (avi->element_index)
4893     result = gst_object_ref (avi->element_index);
4894   GST_OBJECT_UNLOCK (avi);
4895
4896   GST_DEBUG_OBJECT (avi, "Returning index %" GST_PTR_FORMAT, result);
4897
4898   return result;
4899 }
4900
4901 static GstStateChangeReturn
4902 gst_avi_demux_change_state (GstElement * element, GstStateChange transition)
4903 {
4904   GstStateChangeReturn ret;
4905   GstAviDemux *avi = GST_AVI_DEMUX (element);
4906
4907   switch (transition) {
4908     case GST_STATE_CHANGE_READY_TO_PAUSED:
4909       avi->streaming = FALSE;
4910       gst_segment_init (&avi->segment, GST_FORMAT_TIME);
4911       break;
4912     default:
4913       break;
4914   }
4915
4916   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
4917   if (ret == GST_STATE_CHANGE_FAILURE)
4918     goto done;
4919
4920   switch (transition) {
4921     case GST_STATE_CHANGE_PAUSED_TO_READY:
4922       gst_avi_demux_reset (avi);
4923       break;
4924     default:
4925       break;
4926   }
4927
4928 done:
4929   return ret;
4930 }