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