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