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