avidemux: Properly mark presence of index.
[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  *
1266  * Returns TRUE if the index is not empty, else FALSE */
1267 static gboolean
1268 gst_avi_demux_do_index_stats (GstAviDemux * avi)
1269 {
1270   guint i;
1271 #ifndef GST_DISABLE_GST_DEBUG
1272   guint total_idx = 0, total_max = 0;
1273 #endif
1274
1275   /* get stream stats now */
1276   for (i = 0; i < avi->num_streams; i++) {
1277     GstAviStream *stream;
1278
1279     if (G_UNLIKELY (!(stream = &avi->stream[i])))
1280       continue;
1281     if (G_UNLIKELY (!stream->strh))
1282       continue;
1283     if (G_UNLIKELY (!stream->index || stream->idx_n == 0))
1284       continue;
1285
1286     /* we interested in the end_ts of the last entry, which is the total
1287      * duration of this stream */
1288     gst_avi_demux_get_buffer_info (avi, stream, stream->idx_n - 1,
1289         NULL, &stream->idx_duration, NULL, NULL);
1290
1291 #ifndef GST_DISABLE_GST_DEBUG
1292     total_idx += stream->idx_n;
1293     total_max += stream->idx_max;
1294 #endif
1295     GST_INFO_OBJECT (avi, "Stream %d, dur %" GST_TIME_FORMAT ", %6u entries, "
1296         "%5u keyframes, entry size = %2u, total size = %10u, allocated %10u",
1297         i, GST_TIME_ARGS (stream->idx_duration), stream->idx_n,
1298         stream->n_keyframes, (guint) sizeof (GstAviIndexEntry),
1299         (guint) (stream->idx_n * sizeof (GstAviIndexEntry)),
1300         (guint) (stream->idx_max * sizeof (GstAviIndexEntry)));
1301   }
1302 #ifndef GST_DISABLE_GST_DEBUG
1303   total_idx *= sizeof (GstAviIndexEntry);
1304   total_max *= sizeof (GstAviIndexEntry);
1305 #endif
1306   GST_INFO_OBJECT (avi, "%u bytes for index vs %u ideally, %u wasted",
1307       total_max, total_idx, total_max - total_idx);
1308
1309   if (total_idx == 0) {
1310     GST_WARNING_OBJECT (avi, "Index is empty !");
1311     return FALSE;
1312   }
1313   return TRUE;
1314 }
1315
1316 /*
1317  * gst_avi_demux_parse_subindex:
1318  * @avi: Avi object
1319  * @buf: input data to use for parsing.
1320  * @stream: stream context.
1321  * @entries_list: a list (returned by the function) containing all the
1322  *           indexes parsed in this specific subindex. The first
1323  *           entry is also a pointer to allocated memory that needs
1324  *           to be free´ed. May be NULL if no supported indexes were
1325  *           found.
1326  *
1327  * Reads superindex (openDML-2 spec stuff) from the provided data.
1328  * The buffer should contain a GST_RIFF_TAG_ix?? chunk.
1329  *
1330  * Returns: TRUE on success, FALSE otherwise. Errors are fatal, we
1331  *          throw an error, caller should bail out asap.
1332  */
1333 static gboolean
1334 gst_avi_demux_parse_subindex (GstAviDemux * avi, GstAviStream * stream,
1335     GstBuffer * buf)
1336 {
1337   guint8 *data;
1338   guint16 bpe;
1339   guint32 num, i;
1340   guint64 baseoff;
1341   guint size;
1342
1343   if (!buf)
1344     return TRUE;
1345
1346   size = GST_BUFFER_SIZE (buf);
1347
1348   /* check size */
1349   if (size < 24)
1350     goto too_small;
1351
1352   data = GST_BUFFER_DATA (buf);
1353
1354   /* We don't support index-data yet */
1355   if (data[3] & 0x80)
1356     goto not_implemented;
1357
1358   /* check type of index. The opendml2 specs state that
1359    * there should be 4 dwords per array entry. Type can be
1360    * either frame or field (and we don't care). */
1361   bpe = (data[2] & 0x01) ? 12 : 8;
1362   if (GST_READ_UINT16_LE (data) != bpe / 4 ||
1363       (data[2] & 0xfe) != 0x0 || data[3] != 0x1) {
1364     GST_WARNING_OBJECT (avi,
1365         "Superindex for stream %d has unexpected "
1366         "size_entry %d (bytes) or flags 0x%02x/0x%02x",
1367         stream->num, GST_READ_UINT16_LE (data), data[2], data[3]);
1368     bpe = GST_READ_UINT16_LE (data) * 4;
1369   }
1370   num = GST_READ_UINT32_LE (&data[4]);
1371   baseoff = GST_READ_UINT64_LE (&data[12]);
1372
1373   /* If there's nothing, just return ! */
1374   if (num == 0)
1375     goto empty_index;
1376
1377   GST_INFO_OBJECT (avi, "Parsing subindex, nr_entries = %6d", num);
1378
1379   for (i = 0; i < num; i++) {
1380     GstAviIndexEntry entry;
1381
1382     if (size < 24 + bpe * (i + 1))
1383       break;
1384
1385     /* fill in offset and size. offset contains the keyframe flag in the
1386      * upper bit*/
1387     entry.offset = baseoff + GST_READ_UINT32_LE (&data[24 + bpe * i]);
1388     entry.size = GST_READ_UINT32_LE (&data[24 + bpe * i + 4]);
1389     /* handle flags */
1390     if (stream->strh->type == GST_RIFF_FCC_auds) {
1391       /* all audio frames are keyframes */
1392       ENTRY_SET_KEYFRAME (&entry);
1393     } else {
1394       /* else read flags */
1395       entry.flags = (entry.size & 0x80000000) ? 0 : GST_AVI_KEYFRAME;
1396     }
1397     entry.size &= ~0x80000000;
1398
1399     /* and add */
1400     if (G_UNLIKELY (!gst_avi_demux_add_index (avi, stream, num, &entry)))
1401       goto out_of_mem;
1402   }
1403   gst_buffer_unref (buf);
1404
1405   return TRUE;
1406
1407   /* ERRORS */
1408 too_small:
1409   {
1410     GST_ERROR_OBJECT (avi,
1411         "Not enough data to parse subindex (%d available, 24 needed)", size);
1412     gst_buffer_unref (buf);
1413     return TRUE;                /* continue */
1414   }
1415 not_implemented:
1416   {
1417     GST_ELEMENT_ERROR (avi, STREAM, NOT_IMPLEMENTED, (NULL),
1418         ("Subindex-is-data is not implemented"));
1419     gst_buffer_unref (buf);
1420     return FALSE;
1421   }
1422 empty_index:
1423   {
1424     GST_DEBUG_OBJECT (avi, "the index is empty");
1425     gst_buffer_unref (buf);
1426     return TRUE;
1427   }
1428 out_of_mem:
1429   {
1430     GST_ELEMENT_ERROR (avi, RESOURCE, NO_SPACE_LEFT, (NULL),
1431         ("Cannot allocate memory for %u*%u=%u bytes",
1432             (guint) sizeof (GstAviIndexEntry), num,
1433             (guint) sizeof (GstAviIndexEntry) * num));
1434     gst_buffer_unref (buf);
1435     return FALSE;
1436   }
1437 }
1438
1439 #if 0
1440 /*
1441  * Read AVI index when streaming
1442  */
1443 static void
1444 gst_avi_demux_read_subindexes_push (GstAviDemux * avi)
1445 {
1446   guint32 tag = 0, size;
1447   GstBuffer *buf = NULL;
1448   gint i, n;
1449
1450   GST_DEBUG_OBJECT (avi, "read subindexes for %d streams", avi->num_streams);
1451
1452   for (n = 0; n < avi->num_streams; n++) {
1453     GstAviStream *stream = &avi->stream[n];
1454
1455     for (i = 0; stream->indexes[i] != GST_BUFFER_OFFSET_NONE; i++) {
1456       if (!gst_avi_demux_peek_chunk (avi, &tag, &size))
1457         continue;
1458       else if ((tag != GST_MAKE_FOURCC ('i', 'x', '0' + stream->num / 10,
1459                   '0' + stream->num % 10)) &&
1460           (tag != GST_MAKE_FOURCC ('0' + stream->num / 10,
1461                   '0' + stream->num % 10, 'i', 'x'))) {
1462         GST_WARNING_OBJECT (avi, "Not an ix## chunk (%" GST_FOURCC_FORMAT ")",
1463             GST_FOURCC_ARGS (tag));
1464         continue;
1465       }
1466
1467       avi->offset += 8 + GST_ROUND_UP_2 (size);
1468
1469       buf = gst_buffer_new ();
1470       GST_BUFFER_DATA (buf) = gst_adapter_take (avi->adapter, size);
1471       GST_BUFFER_SIZE (buf) = size;
1472
1473       if (!gst_avi_demux_parse_subindex (avi, stream, buf))
1474         continue;
1475     }
1476
1477     g_free (stream->indexes);
1478     stream->indexes = NULL;
1479   }
1480   /* get stream stats now */
1481   avi->have_index = gst_avi_demux_do_index_stats (avi);
1482 }
1483 #endif
1484
1485 /*
1486  * Read AVI index
1487  */
1488 static void
1489 gst_avi_demux_read_subindexes_pull (GstAviDemux * avi)
1490 {
1491   guint32 tag;
1492   GstBuffer *buf;
1493   gint i, n;
1494
1495   GST_DEBUG_OBJECT (avi, "read subindexes for %d streams", avi->num_streams);
1496
1497   for (n = 0; n < avi->num_streams; n++) {
1498     GstAviStream *stream = &avi->stream[n];
1499
1500     for (i = 0; stream->indexes[i] != GST_BUFFER_OFFSET_NONE; i++) {
1501       if (gst_riff_read_chunk (GST_ELEMENT_CAST (avi), avi->sinkpad,
1502               &stream->indexes[i], &tag, &buf) != GST_FLOW_OK)
1503         continue;
1504       else if ((tag != GST_MAKE_FOURCC ('i', 'x', '0' + stream->num / 10,
1505                   '0' + stream->num % 10)) &&
1506           (tag != GST_MAKE_FOURCC ('0' + stream->num / 10,
1507                   '0' + stream->num % 10, 'i', 'x'))) {
1508         /* Some ODML files (created by god knows what muxer) have a ##ix format
1509          * instead of the 'official' ix##. They are still valid though. */
1510         GST_WARNING_OBJECT (avi, "Not an ix## chunk (%" GST_FOURCC_FORMAT ")",
1511             GST_FOURCC_ARGS (tag));
1512         gst_buffer_unref (buf);
1513         continue;
1514       }
1515
1516       if (!gst_avi_demux_parse_subindex (avi, stream, buf))
1517         continue;
1518     }
1519
1520     g_free (stream->indexes);
1521     stream->indexes = NULL;
1522   }
1523   /* get stream stats now */
1524   avi->have_index = gst_avi_demux_do_index_stats (avi);
1525 }
1526
1527 /*
1528  * gst_avi_demux_riff_parse_vprp:
1529  * @element: caller element (used for debugging/error).
1530  * @buf: input data to be used for parsing, stripped from header.
1531  * @vprp: a pointer (returned by this function) to a filled-in vprp
1532  *        structure. Caller should free it.
1533  *
1534  * Parses a video stream´s vprp. This function takes ownership of @buf.
1535  *
1536  * Returns: TRUE if parsing succeeded, otherwise FALSE. The stream
1537  *          should be skipped on error, but it is not fatal.
1538  */
1539 static gboolean
1540 gst_avi_demux_riff_parse_vprp (GstElement * element,
1541     GstBuffer * buf, gst_riff_vprp ** _vprp)
1542 {
1543   gst_riff_vprp *vprp;
1544   gint k;
1545
1546   g_return_val_if_fail (buf != NULL, FALSE);
1547   g_return_val_if_fail (_vprp != NULL, FALSE);
1548
1549   if (GST_BUFFER_SIZE (buf) < G_STRUCT_OFFSET (gst_riff_vprp, field_info))
1550     goto too_small;
1551
1552   vprp = g_memdup (GST_BUFFER_DATA (buf), GST_BUFFER_SIZE (buf));
1553
1554 #if (G_BYTE_ORDER == G_BIG_ENDIAN)
1555   vprp->format_token = GUINT32_FROM_LE (vprp->format_token);
1556   vprp->standard = GUINT32_FROM_LE (vprp->standard);
1557   vprp->vert_rate = GUINT32_FROM_LE (vprp->vert_rate);
1558   vprp->hor_t_total = GUINT32_FROM_LE (vprp->hor_t_total);
1559   vprp->vert_lines = GUINT32_FROM_LE (vprp->vert_lines);
1560   vprp->aspect = GUINT32_FROM_LE (vprp->aspect);
1561   vprp->width = GUINT32_FROM_LE (vprp->width);
1562   vprp->height = GUINT32_FROM_LE (vprp->height);
1563   vprp->fields = GUINT32_FROM_LE (vprp->fields);
1564 #endif
1565
1566   /* size checking */
1567   /* calculate fields based on size */
1568   k = (GST_BUFFER_SIZE (buf) - G_STRUCT_OFFSET (gst_riff_vprp, field_info)) /
1569       vprp->fields;
1570   if (vprp->fields > k) {
1571     GST_WARNING_OBJECT (element,
1572         "vprp header indicated %d fields, only %d available", vprp->fields, k);
1573     vprp->fields = k;
1574   }
1575   if (vprp->fields > GST_RIFF_VPRP_VIDEO_FIELDS) {
1576     GST_WARNING_OBJECT (element,
1577         "vprp header indicated %d fields, at most %d supported", vprp->fields,
1578         GST_RIFF_VPRP_VIDEO_FIELDS);
1579     vprp->fields = GST_RIFF_VPRP_VIDEO_FIELDS;
1580   }
1581 #if (G_BYTE_ORDER == G_BIG_ENDIAN)
1582   for (k = 0; k < vprp->fields; k++) {
1583     gst_riff_vprp_video_field_desc *fd;
1584
1585     fd = &vprp->field_info[k];
1586     fd->compressed_bm_height = GUINT32_FROM_LE (fd->compressed_bm_height);
1587     fd->compressed_bm_width = GUINT32_FROM_LE (fd->compressed_bm_width);
1588     fd->valid_bm_height = GUINT32_FROM_LE (fd->valid_bm_height);
1589     fd->valid_bm_width = GUINT16_FROM_LE (fd->valid_bm_width);
1590     fd->valid_bm_x_offset = GUINT16_FROM_LE (fd->valid_bm_x_offset);
1591     fd->valid_bm_y_offset = GUINT32_FROM_LE (fd->valid_bm_y_offset);
1592     fd->video_x_t_offset = GUINT32_FROM_LE (fd->video_x_t_offset);
1593     fd->video_y_start = GUINT32_FROM_LE (fd->video_y_start);
1594   }
1595 #endif
1596
1597   /* debug */
1598   GST_INFO_OBJECT (element, "vprp tag found in context vids:");
1599   GST_INFO_OBJECT (element, " format_token  %d", vprp->format_token);
1600   GST_INFO_OBJECT (element, " standard      %d", vprp->standard);
1601   GST_INFO_OBJECT (element, " vert_rate     %d", vprp->vert_rate);
1602   GST_INFO_OBJECT (element, " hor_t_total   %d", vprp->hor_t_total);
1603   GST_INFO_OBJECT (element, " vert_lines    %d", vprp->vert_lines);
1604   GST_INFO_OBJECT (element, " aspect        %d:%d", vprp->aspect >> 16,
1605       vprp->aspect & 0xffff);
1606   GST_INFO_OBJECT (element, " width         %d", vprp->width);
1607   GST_INFO_OBJECT (element, " height        %d", vprp->height);
1608   GST_INFO_OBJECT (element, " fields        %d", vprp->fields);
1609   for (k = 0; k < vprp->fields; k++) {
1610     gst_riff_vprp_video_field_desc *fd;
1611
1612     fd = &(vprp->field_info[k]);
1613     GST_INFO_OBJECT (element, " field %u description:", k);
1614     GST_INFO_OBJECT (element, "  compressed_bm_height  %d",
1615         fd->compressed_bm_height);
1616     GST_INFO_OBJECT (element, "  compressed_bm_width  %d",
1617         fd->compressed_bm_width);
1618     GST_INFO_OBJECT (element, "  valid_bm_height       %d",
1619         fd->valid_bm_height);
1620     GST_INFO_OBJECT (element, "  valid_bm_width        %d", fd->valid_bm_width);
1621     GST_INFO_OBJECT (element, "  valid_bm_x_offset     %d",
1622         fd->valid_bm_x_offset);
1623     GST_INFO_OBJECT (element, "  valid_bm_y_offset     %d",
1624         fd->valid_bm_y_offset);
1625     GST_INFO_OBJECT (element, "  video_x_t_offset      %d",
1626         fd->video_x_t_offset);
1627     GST_INFO_OBJECT (element, "  video_y_start         %d", fd->video_y_start);
1628   }
1629
1630   gst_buffer_unref (buf);
1631
1632   *_vprp = vprp;
1633
1634   return TRUE;
1635
1636   /* ERRORS */
1637 too_small:
1638   {
1639     GST_ERROR_OBJECT (element,
1640         "Too small vprp (%d available, at least %d needed)",
1641         GST_BUFFER_SIZE (buf),
1642         (int) G_STRUCT_OFFSET (gst_riff_vprp, field_info));
1643     gst_buffer_unref (buf);
1644     return FALSE;
1645   }
1646 }
1647
1648 /*
1649  * gst_avi_demux_parse_stream:
1650  * @avi: calling element (used for debugging/errors).
1651  * @buf: input buffer used to parse the stream.
1652  *
1653  * Parses all subchunks in a strl chunk (which defines a single
1654  * stream). Discards the buffer after use. This function will
1655  * increment the stream counter internally.
1656  *
1657  * Returns: whether the stream was identified successfully.
1658  *          Errors are not fatal. It does indicate the stream
1659  *          was skipped.
1660  */
1661 static gboolean
1662 gst_avi_demux_parse_stream (GstAviDemux * avi, GstBuffer * buf)
1663 {
1664   GstAviStream *stream;
1665   GstElementClass *klass;
1666   GstPadTemplate *templ;
1667   GstBuffer *sub = NULL;
1668   guint offset = 4;
1669   guint32 tag = 0;
1670   gchar *codec_name = NULL, *padname = NULL;
1671   const gchar *tag_name;
1672   GstCaps *caps = NULL;
1673   GstPad *pad;
1674   GstElement *element;
1675   gboolean got_strh = FALSE, got_strf = FALSE, got_vprp = FALSE;
1676   gst_riff_vprp *vprp = NULL;
1677
1678   element = GST_ELEMENT_CAST (avi);
1679
1680   GST_DEBUG_OBJECT (avi, "Parsing stream");
1681
1682   if (avi->num_streams >= GST_AVI_DEMUX_MAX_STREAMS) {
1683     GST_WARNING_OBJECT (avi,
1684         "maximum no of streams (%d) exceeded, ignoring stream",
1685         GST_AVI_DEMUX_MAX_STREAMS);
1686     gst_buffer_unref (buf);
1687     /* not a fatal error, let's say */
1688     return TRUE;
1689   }
1690
1691   stream = &avi->stream[avi->num_streams];
1692
1693   /* initial settings */
1694   stream->idx_duration = GST_CLOCK_TIME_NONE;
1695   stream->hdr_duration = GST_CLOCK_TIME_NONE;
1696   stream->duration = GST_CLOCK_TIME_NONE;
1697
1698   while (gst_riff_parse_chunk (element, buf, &offset, &tag, &sub)) {
1699     /* sub can be NULL if the chunk is empty */
1700     if (sub == NULL) {
1701       GST_DEBUG_OBJECT (avi, "ignoring empty chunk %" GST_FOURCC_FORMAT,
1702           GST_FOURCC_ARGS (tag));
1703       continue;
1704     }
1705     switch (tag) {
1706       case GST_RIFF_TAG_strh:
1707       {
1708         gst_riff_strh *strh;
1709
1710         if (got_strh) {
1711           GST_WARNING_OBJECT (avi, "Ignoring additional strh chunk");
1712           break;
1713         }
1714         if (!gst_riff_parse_strh (element, sub, &stream->strh)) {
1715           /* ownership given away */
1716           sub = NULL;
1717           GST_WARNING_OBJECT (avi, "Failed to parse strh chunk");
1718           goto fail;
1719         }
1720         sub = NULL;
1721         strh = stream->strh;
1722         /* sanity check; stream header frame rate matches global header
1723          * frame duration */
1724         if (stream->strh->type == GST_RIFF_FCC_vids) {
1725           GstClockTime s_dur;
1726           GstClockTime h_dur = avi->avih->us_frame * GST_USECOND;
1727
1728           s_dur = gst_util_uint64_scale (GST_SECOND, strh->scale, strh->rate);
1729           GST_DEBUG_OBJECT (avi, "verifying stream framerate %d/%d, "
1730               "frame duration = %d ms", strh->rate, strh->scale,
1731               (gint) (s_dur / GST_MSECOND));
1732           if (h_dur > (10 * GST_MSECOND) && (s_dur > 10 * h_dur)) {
1733             strh->rate = GST_SECOND / GST_USECOND;
1734             strh->scale = h_dur / GST_USECOND;
1735             GST_DEBUG_OBJECT (avi, "correcting stream framerate to %d/%d",
1736                 strh->rate, strh->scale);
1737           }
1738         }
1739         /* determine duration as indicated by header */
1740         stream->hdr_duration = gst_util_uint64_scale ((guint64) strh->length *
1741             strh->scale, GST_SECOND, (guint64) strh->rate);
1742         GST_INFO ("Stream duration according to header: %" GST_TIME_FORMAT,
1743             GST_TIME_ARGS (stream->hdr_duration));
1744         if (stream->hdr_duration == 0)
1745           stream->hdr_duration = GST_CLOCK_TIME_NONE;
1746
1747         got_strh = TRUE;
1748         break;
1749       }
1750       case GST_RIFF_TAG_strf:
1751       {
1752         gboolean res = FALSE;
1753
1754         if (got_strf) {
1755           GST_WARNING_OBJECT (avi, "Ignoring additional strf chunk");
1756           break;
1757         }
1758         if (!got_strh) {
1759           GST_ERROR_OBJECT (avi, "Found strf chunk before strh chunk");
1760           goto fail;
1761         }
1762         switch (stream->strh->type) {
1763           case GST_RIFF_FCC_vids:
1764             stream->is_vbr = TRUE;
1765             res = gst_riff_parse_strf_vids (element, sub,
1766                 &stream->strf.vids, &stream->extradata);
1767             sub = NULL;
1768             GST_DEBUG_OBJECT (element, "marking video as VBR, res %d", res);
1769             break;
1770           case GST_RIFF_FCC_auds:
1771             stream->is_vbr = (stream->strh->samplesize == 0)
1772                 && stream->strh->scale > 1;
1773             res =
1774                 gst_riff_parse_strf_auds (element, sub, &stream->strf.auds,
1775                 &stream->extradata);
1776             sub = NULL;
1777             GST_DEBUG_OBJECT (element, "marking audio as VBR:%d, res %d",
1778                 stream->is_vbr, res);
1779             break;
1780           case GST_RIFF_FCC_iavs:
1781             stream->is_vbr = TRUE;
1782             res = gst_riff_parse_strf_iavs (element, sub,
1783                 &stream->strf.iavs, &stream->extradata);
1784             sub = NULL;
1785             GST_DEBUG_OBJECT (element, "marking iavs as VBR, res %d", res);
1786             break;
1787           case GST_RIFF_FCC_txts:
1788             /* nothing to parse here */
1789             stream->is_vbr = (stream->strh->samplesize == 0)
1790                 && (stream->strh->scale > 1);
1791             res = TRUE;
1792             break;
1793           default:
1794             GST_ERROR_OBJECT (avi,
1795                 "Don´t know how to handle stream type %" GST_FOURCC_FORMAT,
1796                 GST_FOURCC_ARGS (stream->strh->type));
1797             break;
1798         }
1799         if (sub) {
1800           gst_buffer_unref (sub);
1801           sub = NULL;
1802         }
1803         if (!res)
1804           goto fail;
1805         got_strf = TRUE;
1806         break;
1807       }
1808       case GST_RIFF_TAG_vprp:
1809       {
1810         if (got_vprp) {
1811           GST_WARNING_OBJECT (avi, "Ignoring additional vprp chunk");
1812           break;
1813         }
1814         if (!got_strh) {
1815           GST_ERROR_OBJECT (avi, "Found vprp chunk before strh chunk");
1816           goto fail;
1817         }
1818         if (!got_strf) {
1819           GST_ERROR_OBJECT (avi, "Found vprp chunk before strf chunk");
1820           goto fail;
1821         }
1822
1823         if (!gst_avi_demux_riff_parse_vprp (element, sub, &vprp)) {
1824           GST_WARNING_OBJECT (avi, "Failed to parse vprp chunk");
1825           /* not considered fatal */
1826           g_free (vprp);
1827           vprp = NULL;
1828         } else
1829           got_vprp = TRUE;
1830         sub = NULL;
1831         break;
1832       }
1833       case GST_RIFF_TAG_strd:
1834         if (stream->initdata)
1835           gst_buffer_unref (stream->initdata);
1836         stream->initdata = sub;
1837         sub = NULL;
1838         break;
1839       case GST_RIFF_TAG_strn:
1840         g_free (stream->name);
1841         if (sub != NULL) {
1842           stream->name =
1843               g_strndup ((gchar *) GST_BUFFER_DATA (sub),
1844               (gsize) GST_BUFFER_SIZE (sub));
1845           gst_buffer_unref (sub);
1846           sub = NULL;
1847         } else {
1848           stream->name = g_strdup ("");
1849         }
1850         GST_DEBUG_OBJECT (avi, "stream name: %s", stream->name);
1851         break;
1852       default:
1853         if (tag == GST_MAKE_FOURCC ('i', 'n', 'd', 'x') ||
1854             tag == GST_MAKE_FOURCC ('i', 'x', '0' + avi->num_streams / 10,
1855                 '0' + avi->num_streams % 10)) {
1856           g_free (stream->indexes);
1857           gst_avi_demux_parse_superindex (avi, sub, &stream->indexes);
1858           stream->superindex = TRUE;
1859           sub = NULL;
1860           break;
1861         }
1862         GST_WARNING_OBJECT (avi,
1863             "Unknown stream header tag %" GST_FOURCC_FORMAT ", ignoring",
1864             GST_FOURCC_ARGS (tag));
1865         /* fall-through */
1866       case GST_RIFF_TAG_JUNK:
1867         break;
1868     }
1869     if (sub != NULL) {
1870       gst_buffer_unref (sub);
1871       sub = NULL;
1872     }
1873   }
1874
1875   if (!got_strh) {
1876     GST_WARNING_OBJECT (avi, "Failed to find strh chunk");
1877     goto fail;
1878   }
1879
1880   if (!got_strf) {
1881     GST_WARNING_OBJECT (avi, "Failed to find strf chunk");
1882     goto fail;
1883   }
1884
1885   /* get class to figure out the template */
1886   klass = GST_ELEMENT_GET_CLASS (avi);
1887
1888   /* we now have all info, let´s set up a pad and a caps and be done */
1889   /* create stream name + pad */
1890   switch (stream->strh->type) {
1891     case GST_RIFF_FCC_vids:{
1892       guint32 fourcc;
1893
1894       fourcc = (stream->strf.vids->compression) ?
1895           stream->strf.vids->compression : stream->strh->fcc_handler;
1896       padname = g_strdup_printf ("video_%02d", avi->num_v_streams);
1897       templ = gst_element_class_get_pad_template (klass, "video_%02d");
1898       caps = gst_riff_create_video_caps (fourcc, stream->strh,
1899           stream->strf.vids, stream->extradata, stream->initdata, &codec_name);
1900       if (!caps) {
1901         caps = gst_caps_new_simple ("video/x-avi-unknown", "fourcc",
1902             GST_TYPE_FOURCC, fourcc, NULL);
1903       } else if (got_vprp && vprp) {
1904         guint32 aspect_n, aspect_d;
1905         gint n, d;
1906
1907         aspect_n = vprp->aspect >> 16;
1908         aspect_d = vprp->aspect & 0xffff;
1909         /* calculate the pixel aspect ratio using w/h and aspect ratio */
1910         n = aspect_n * stream->strf.vids->height;
1911         d = aspect_d * stream->strf.vids->width;
1912         if (n && d)
1913           gst_caps_set_simple (caps, "pixel-aspect-ratio", GST_TYPE_FRACTION,
1914               n, d, NULL);
1915         /* very local, not needed elsewhere */
1916         g_free (vprp);
1917         vprp = NULL;
1918       }
1919       tag_name = GST_TAG_VIDEO_CODEC;
1920       avi->num_v_streams++;
1921       break;
1922     }
1923     case GST_RIFF_FCC_auds:{
1924       padname = g_strdup_printf ("audio_%02d", avi->num_a_streams);
1925       templ = gst_element_class_get_pad_template (klass, "audio_%02d");
1926       caps = gst_riff_create_audio_caps (stream->strf.auds->format,
1927           stream->strh, stream->strf.auds, stream->extradata,
1928           stream->initdata, &codec_name);
1929       if (!caps) {
1930         caps = gst_caps_new_simple ("audio/x-avi-unknown", "codec_id",
1931             G_TYPE_INT, stream->strf.auds->format, NULL);
1932       }
1933       tag_name = GST_TAG_AUDIO_CODEC;
1934       avi->num_a_streams++;
1935       break;
1936     }
1937     case GST_RIFF_FCC_iavs:{
1938       guint32 fourcc = stream->strh->fcc_handler;
1939
1940       padname = g_strdup_printf ("video_%02d", avi->num_v_streams);
1941       templ = gst_element_class_get_pad_template (klass, "video_%02d");
1942       caps = gst_riff_create_iavs_caps (fourcc, stream->strh,
1943           stream->strf.iavs, stream->extradata, stream->initdata, &codec_name);
1944       if (!caps) {
1945         caps = gst_caps_new_simple ("video/x-avi-unknown", "fourcc",
1946             GST_TYPE_FOURCC, fourcc, NULL);
1947       }
1948       tag_name = GST_TAG_VIDEO_CODEC;
1949       avi->num_v_streams++;
1950       break;
1951     }
1952     case GST_RIFF_FCC_txts:{
1953       padname = g_strdup_printf ("subtitle_%02d", avi->num_t_streams);
1954       templ = gst_element_class_get_pad_template (klass, "subtitle_%02d");
1955       caps = gst_caps_new_simple ("application/x-subtitle-avi", NULL);
1956       tag_name = NULL;
1957       avi->num_t_streams++;
1958       break;
1959     }
1960     default:
1961       g_assert_not_reached ();
1962   }
1963
1964   /* no caps means no stream */
1965   if (!caps) {
1966     GST_ERROR_OBJECT (element, "Did not find caps for stream %s", padname);
1967     goto fail;
1968   }
1969
1970   GST_DEBUG_OBJECT (element, "codec-name=%s",
1971       (codec_name ? codec_name : "NULL"));
1972   GST_DEBUG_OBJECT (element, "caps=%" GST_PTR_FORMAT, caps);
1973
1974   /* set proper settings and add it */
1975   if (stream->pad)
1976     gst_object_unref (stream->pad);
1977   pad = stream->pad = gst_pad_new_from_template (templ, padname);
1978   g_free (padname);
1979
1980   gst_pad_use_fixed_caps (pad);
1981 #if 0
1982   gst_pad_set_formats_function (pad,
1983       GST_DEBUG_FUNCPTR (gst_avi_demux_get_src_formats));
1984   gst_pad_set_event_mask_function (pad,
1985       GST_DEBUG_FUNCPTR (gst_avi_demux_get_event_mask));
1986 #endif
1987   gst_pad_set_event_function (pad,
1988       GST_DEBUG_FUNCPTR (gst_avi_demux_handle_src_event));
1989   gst_pad_set_query_type_function (pad,
1990       GST_DEBUG_FUNCPTR (gst_avi_demux_get_src_query_types));
1991   gst_pad_set_query_function (pad,
1992       GST_DEBUG_FUNCPTR (gst_avi_demux_handle_src_query));
1993 #if 0
1994   gst_pad_set_convert_function (pad,
1995       GST_DEBUG_FUNCPTR (gst_avi_demux_src_convert));
1996 #endif
1997
1998   if (avi->element_index)
1999     gst_index_get_writer_id (avi->element_index, GST_OBJECT (stream->pad),
2000         &stream->index_id);
2001
2002   stream->num = avi->num_streams;
2003
2004   stream->start_entry = 0;
2005   stream->step_entry = 0;
2006   stream->stop_entry = 0;
2007
2008   stream->current_entry = -1;
2009   stream->current_total = 0;
2010
2011   stream->last_flow = GST_FLOW_OK;
2012   stream->discont = TRUE;
2013
2014   stream->total_bytes = 0;
2015   stream->total_blocks = 0;
2016   stream->n_keyframes = 0;
2017
2018   stream->idx_n = 0;
2019   stream->idx_max = 0;
2020
2021   gst_pad_set_element_private (pad, stream);
2022   avi->num_streams++;
2023
2024   gst_pad_set_caps (pad, caps);
2025   gst_pad_set_active (pad, TRUE);
2026   gst_element_add_pad (GST_ELEMENT (avi), pad);
2027
2028   GST_LOG_OBJECT (element, "Added pad %s with caps %" GST_PTR_FORMAT,
2029       GST_PAD_NAME (pad), caps);
2030   gst_caps_unref (caps);
2031
2032   /* make tags */
2033   if (codec_name) {
2034     if (!stream->taglist)
2035       stream->taglist = gst_tag_list_new ();
2036
2037     avi->got_tags = TRUE;
2038
2039     gst_tag_list_add (stream->taglist, GST_TAG_MERGE_APPEND, tag_name,
2040         codec_name, NULL);
2041     g_free (codec_name);
2042   }
2043
2044   gst_buffer_unref (buf);
2045
2046   return TRUE;
2047
2048   /* ERRORS */
2049 fail:
2050   {
2051     /* unref any mem that may be in use */
2052     if (buf)
2053       gst_buffer_unref (buf);
2054     if (sub)
2055       gst_buffer_unref (sub);
2056     g_free (vprp);
2057     g_free (codec_name);
2058     gst_avi_demux_reset_stream (avi, stream);
2059     avi->num_streams++;
2060     return FALSE;
2061   }
2062 }
2063
2064 /*
2065  * gst_avi_demux_parse_odml:
2066  * @avi: calling element (used for debug/error).
2067  * @buf: input buffer to be used for parsing.
2068  *
2069  * Read an openDML-2.0 extension header. Fills in the frame number
2070  * in the avi demuxer object when reading succeeds.
2071  */
2072 static void
2073 gst_avi_demux_parse_odml (GstAviDemux * avi, GstBuffer * buf)
2074 {
2075   guint32 tag = 0;
2076   guint offset = 4;
2077   GstBuffer *sub = NULL;
2078
2079   while (gst_riff_parse_chunk (GST_ELEMENT_CAST (avi), buf, &offset, &tag,
2080           &sub)) {
2081     switch (tag) {
2082       case GST_RIFF_TAG_dmlh:{
2083         gst_riff_dmlh dmlh, *_dmlh;
2084         guint size;
2085
2086         /* sub == NULL is possible and means an empty buffer */
2087         size = sub ? GST_BUFFER_SIZE (sub) : 0;
2088
2089         /* check size */
2090         if (size < sizeof (gst_riff_dmlh)) {
2091           GST_ERROR_OBJECT (avi,
2092               "DMLH entry is too small (%d bytes, %d needed)",
2093               size, (int) sizeof (gst_riff_dmlh));
2094           goto next;
2095         }
2096         _dmlh = (gst_riff_dmlh *) GST_BUFFER_DATA (sub);
2097         dmlh.totalframes = GST_READ_UINT32_LE (&_dmlh->totalframes);
2098
2099         GST_INFO_OBJECT (avi, "dmlh tag found: totalframes: %u",
2100             dmlh.totalframes);
2101
2102         avi->avih->tot_frames = dmlh.totalframes;
2103         goto next;
2104       }
2105
2106       default:
2107         GST_WARNING_OBJECT (avi,
2108             "Unknown tag %" GST_FOURCC_FORMAT " in ODML header",
2109             GST_FOURCC_ARGS (tag));
2110         /* fall-through */
2111       case GST_RIFF_TAG_JUNK:
2112       next:
2113         /* skip and move to next chunk */
2114         if (sub) {
2115           gst_buffer_unref (sub);
2116           sub = NULL;
2117         }
2118         break;
2119     }
2120   }
2121   if (buf)
2122     gst_buffer_unref (buf);
2123 }
2124
2125 /* Index helper */
2126 static guint
2127 gst_avi_demux_index_last (GstAviDemux * avi, GstAviStream * stream)
2128 {
2129   return stream->idx_n - 1;
2130 }
2131
2132 /* find a previous entry in the index with the given flags */
2133 static guint
2134 gst_avi_demux_index_prev (GstAviDemux * avi, GstAviStream * stream,
2135     guint last, gboolean keyframe)
2136 {
2137   GstAviIndexEntry *entry;
2138   guint i;
2139
2140   for (i = last; i > 0; i--) {
2141     entry = &stream->index[i - 1];
2142     if (!keyframe || ENTRY_IS_KEYFRAME (entry)) {
2143       return i - 1;
2144     }
2145   }
2146   return 0;
2147 }
2148
2149 static guint
2150 gst_avi_demux_index_next (GstAviDemux * avi, GstAviStream * stream,
2151     guint last, gboolean keyframe)
2152 {
2153   GstAviIndexEntry *entry;
2154   gint i;
2155
2156   for (i = last + 1; i < stream->idx_n; i++) {
2157     entry = &stream->index[i];
2158     if (!keyframe || ENTRY_IS_KEYFRAME (entry)) {
2159       return i;
2160     }
2161   }
2162   return stream->idx_n - 1;
2163 }
2164
2165 static guint
2166 gst_avi_demux_index_entry_search (GstAviIndexEntry * entry, guint64 * total)
2167 {
2168   if (entry->total < *total)
2169     return -1;
2170   else if (entry->total > *total)
2171     return 1;
2172   return 0;
2173 }
2174
2175 /*
2176  * gst_avi_demux_index_for_time:
2177  * @avi: Avi object
2178  * @stream: the stream
2179  * @time: a time position
2180  *
2181  * Finds the index entry which time is less or equal than the requested time.
2182  * Try to avoid binary search when we can convert the time to an index
2183  * position directly (for example for video frames with a fixed duration).
2184  *
2185  * Returns: the found position in the index.
2186  */
2187 static guint
2188 gst_avi_demux_index_for_time (GstAviDemux * avi,
2189     GstAviStream * stream, guint64 time)
2190 {
2191   guint index = -1;
2192   guint64 total;
2193
2194   GST_LOG_OBJECT (avi, "search time:%" GST_TIME_FORMAT, GST_TIME_ARGS (time));
2195
2196   /* easy (and common) cases */
2197   if (time == 0 || stream->idx_n == 0)
2198     return 0;
2199   if (time >= stream->idx_duration)
2200     return stream->idx_n - 1;
2201
2202   /* figure out where we need to go. For that we convert the time to an
2203    * index entry or we convert it to a total and then do a binary search. */
2204   if (stream->is_vbr) {
2205     /* VBR stream next timestamp */
2206     if (stream->strh->type == GST_RIFF_FCC_auds) {
2207       total = avi_stream_convert_time_to_frames_unchecked (stream, time);
2208     } else {
2209       index = avi_stream_convert_time_to_frames_unchecked (stream, time);
2210     }
2211   } else {
2212     /* constant rate stream */
2213     total = avi_stream_convert_time_to_bytes_unchecked (stream, time);
2214   }
2215
2216   if (index == -1) {
2217     GstAviIndexEntry *entry;
2218
2219     /* no index, find index with binary search on total */
2220     GST_LOG_OBJECT (avi, "binary search for entry with total %"
2221         G_GUINT64_FORMAT, total);
2222
2223     entry = gst_util_array_binary_search (stream->index,
2224         stream->idx_n, sizeof (GstAviIndexEntry),
2225         (GCompareDataFunc) gst_avi_demux_index_entry_search,
2226         GST_SEARCH_MODE_BEFORE, &total, NULL);
2227
2228     if (entry == NULL) {
2229       GST_LOG_OBJECT (avi, "not found, assume index 0");
2230       index = 0;
2231     } else {
2232       index = entry - stream->index;
2233       GST_LOG_OBJECT (avi, "found at %u", index);
2234     }
2235   } else {
2236     GST_LOG_OBJECT (avi, "converted time to index %u", index);
2237   }
2238
2239   return index;
2240 }
2241
2242 static inline GstAviStream *
2243 gst_avi_demux_stream_for_id (GstAviDemux * avi, guint32 id)
2244 {
2245   guint stream_nr;
2246   GstAviStream *stream;
2247
2248   /* get the stream for this entry */
2249   stream_nr = CHUNKID_TO_STREAMNR (id);
2250   if (G_UNLIKELY (stream_nr >= avi->num_streams)) {
2251     GST_WARNING_OBJECT (avi, "invalid stream nr %d", stream_nr);
2252     return NULL;
2253   }
2254   stream = &avi->stream[stream_nr];
2255   if (G_UNLIKELY (!stream->strh)) {
2256     GST_WARNING_OBJECT (avi, "Unhandled stream %d, skipping", stream_nr);
2257     return NULL;
2258   }
2259   return stream;
2260 }
2261
2262 /*
2263  * gst_avi_demux_parse_index:
2264  * @avi: calling element (used for debugging/errors).
2265  * @buf: buffer containing the full index.
2266  *
2267  * Read index entries from the provided buffer.
2268  * The buffer should contain a GST_RIFF_TAG_idx1 chunk.
2269  */
2270 static gboolean
2271 gst_avi_demux_parse_index (GstAviDemux * avi, GstBuffer * buf)
2272 {
2273   guint64 pos_before;
2274   guint8 *data;
2275   guint size;
2276   guint i, num, n;
2277   gst_riff_index_entry *index;
2278   GstClockTime stamp;
2279   GstAviStream *stream;
2280   GstAviIndexEntry entry;
2281   guint32 id;
2282
2283   if (!buf)
2284     return FALSE;
2285
2286   data = GST_BUFFER_DATA (buf);
2287   size = GST_BUFFER_SIZE (buf);
2288
2289   stamp = gst_util_get_timestamp ();
2290
2291   /* see how many items in the index */
2292   num = size / sizeof (gst_riff_index_entry);
2293   if (num == 0)
2294     goto empty_list;
2295
2296   GST_INFO_OBJECT (avi, "Parsing index, nr_entries = %6d", num);
2297
2298   index = (gst_riff_index_entry *) data;
2299   pos_before = avi->offset;
2300
2301   /* figure out if the index is 0 based or relative to the MOVI start */
2302   entry.offset = GST_READ_UINT32_LE (&index[0].offset);
2303   if (entry.offset < avi->offset) {
2304     avi->index_offset = avi->offset + 8;
2305     GST_DEBUG ("index_offset = %" G_GUINT64_FORMAT, avi->index_offset);
2306   } else {
2307     avi->index_offset = 0;
2308     GST_DEBUG ("index is 0 based");
2309   }
2310
2311   for (i = 0, n = 0; i < num; i++) {
2312     id = GST_READ_UINT32_LE (&index[i].id);
2313     entry.offset = GST_READ_UINT32_LE (&index[i].offset);
2314
2315     /* some sanity checks */
2316     if (G_UNLIKELY (id == GST_RIFF_rec || id == 0 ||
2317             (entry.offset == 0 && n > 0)))
2318       continue;
2319
2320     /* get the stream for this entry */
2321     stream = gst_avi_demux_stream_for_id (avi, id);
2322     if (G_UNLIKELY (!stream))
2323       continue;
2324
2325     /* handle offset and size */
2326     entry.offset += avi->index_offset + 8;
2327     entry.size = GST_READ_UINT32_LE (&index[i].size);
2328
2329     /* handle flags */
2330     if (stream->strh->type == GST_RIFF_FCC_auds) {
2331       /* all audio frames are keyframes */
2332       ENTRY_SET_KEYFRAME (&entry);
2333     } else {
2334       guint32 flags;
2335       /* else read flags */
2336       flags = GST_READ_UINT32_LE (&index[i].flags);
2337       if (flags & GST_RIFF_IF_KEYFRAME) {
2338         ENTRY_SET_KEYFRAME (&entry);
2339       } else {
2340         ENTRY_UNSET_KEYFRAME (&entry);
2341       }
2342     }
2343
2344     /* and add */
2345     if (G_UNLIKELY (!gst_avi_demux_add_index (avi, stream, num, &entry)))
2346       goto out_of_mem;
2347
2348     n++;
2349   }
2350   gst_buffer_unref (buf);
2351
2352   /* get stream stats now */
2353   avi->have_index = gst_avi_demux_do_index_stats (avi);
2354
2355   stamp = gst_util_get_timestamp () - stamp;
2356   GST_DEBUG_OBJECT (avi, "parsing index %" GST_TIME_FORMAT,
2357       GST_TIME_ARGS (stamp));
2358
2359   return TRUE;
2360
2361   /* ERRORS */
2362 empty_list:
2363   {
2364     GST_DEBUG_OBJECT (avi, "empty index");
2365     gst_buffer_unref (buf);
2366     return FALSE;
2367   }
2368 out_of_mem:
2369   {
2370     GST_ELEMENT_ERROR (avi, RESOURCE, NO_SPACE_LEFT, (NULL),
2371         ("Cannot allocate memory for %u*%u=%u bytes",
2372             (guint) sizeof (GstAviIndexEntry), num,
2373             (guint) sizeof (GstAviIndexEntry) * num));
2374     gst_buffer_unref (buf);
2375     return FALSE;
2376   }
2377 }
2378
2379 /*
2380  * gst_avi_demux_stream_index:
2381  * @avi: avi demuxer object.
2382  *
2383  * Seeks to index and reads it.
2384  */
2385 static void
2386 gst_avi_demux_stream_index (GstAviDemux * avi)
2387 {
2388   GstFlowReturn res;
2389   guint64 offset = avi->offset;
2390   GstBuffer *buf;
2391   guint32 tag;
2392   guint32 size;
2393
2394   GST_DEBUG ("demux stream index at offset %" G_GUINT64_FORMAT, offset);
2395
2396   /* get chunk information */
2397   res = gst_pad_pull_range (avi->sinkpad, offset, 8, &buf);
2398   if (res != GST_FLOW_OK)
2399     goto pull_failed;
2400   else if (GST_BUFFER_SIZE (buf) < 8)
2401     goto too_small;
2402
2403   /* check tag first before blindy trying to read 'size' bytes */
2404   tag = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf));
2405   size = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf) + 4);
2406   if (tag == GST_RIFF_TAG_LIST) {
2407     /* this is the movi tag */
2408     GST_DEBUG_OBJECT (avi, "skip LIST chunk, size %" G_GUINT32_FORMAT,
2409         (8 + GST_ROUND_UP_2 (size)));
2410     offset += 8 + GST_ROUND_UP_2 (size);
2411     gst_buffer_unref (buf);
2412     res = gst_pad_pull_range (avi->sinkpad, offset, 8, &buf);
2413     if (res != GST_FLOW_OK)
2414       goto pull_failed;
2415     else if (GST_BUFFER_SIZE (buf) < 8)
2416       goto too_small;
2417     tag = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf));
2418     size = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf) + 4);
2419   }
2420
2421   if (tag != GST_RIFF_TAG_idx1)
2422     goto no_index;
2423   if (!size)
2424     goto zero_index;
2425
2426   gst_buffer_unref (buf);
2427
2428   GST_DEBUG ("index found at offset %" G_GUINT64_FORMAT, offset);
2429
2430   /* read chunk, advance offset */
2431   if (gst_riff_read_chunk (GST_ELEMENT_CAST (avi),
2432           avi->sinkpad, &offset, &tag, &buf) != GST_FLOW_OK)
2433     return;
2434
2435   GST_DEBUG ("will parse index chunk size %u for tag %"
2436       GST_FOURCC_FORMAT, GST_BUFFER_SIZE (buf), GST_FOURCC_ARGS (tag));
2437
2438   gst_avi_demux_parse_index (avi, buf);
2439
2440 #ifndef GST_DISABLE_GST_DEBUG
2441   /* debug our indexes */
2442   {
2443     gint i;
2444     GstAviStream *stream;
2445
2446     for (i = 0; i < avi->num_streams; i++) {
2447       stream = &avi->stream[i];
2448       GST_DEBUG_OBJECT (avi, "stream %u: %u frames, %" G_GINT64_FORMAT " bytes",
2449           i, stream->idx_n, stream->total_bytes);
2450     }
2451   }
2452 #endif
2453   return;
2454
2455   /* ERRORS */
2456 pull_failed:
2457   {
2458     GST_DEBUG_OBJECT (avi,
2459         "pull range failed: pos=%" G_GUINT64_FORMAT " size=8", offset);
2460     return;
2461   }
2462 too_small:
2463   {
2464     GST_DEBUG_OBJECT (avi, "Buffer is too small");
2465     gst_buffer_unref (buf);
2466     return;
2467   }
2468 no_index:
2469   {
2470     GST_WARNING_OBJECT (avi,
2471         "No index data (idx1) after movi chunk, but %" GST_FOURCC_FORMAT,
2472         GST_FOURCC_ARGS (tag));
2473     gst_buffer_unref (buf);
2474     return;
2475   }
2476 zero_index:
2477   {
2478     GST_WARNING_OBJECT (avi, "Empty index data (idx1) after movi chunk");
2479     gst_buffer_unref (buf);
2480     return;
2481   }
2482 }
2483
2484 /*
2485  * gst_avi_demux_peek_tag:
2486  *
2487  * Returns the tag and size of the next chunk
2488  */
2489 static GstFlowReturn
2490 gst_avi_demux_peek_tag (GstAviDemux * avi, guint64 offset, guint32 * tag,
2491     guint * size)
2492 {
2493   GstFlowReturn res = GST_FLOW_OK;
2494   GstBuffer *buf = NULL;
2495   guint bufsize;
2496   guint8 *bufdata;
2497
2498   res = gst_pad_pull_range (avi->sinkpad, offset, 8, &buf);
2499   if (res != GST_FLOW_OK)
2500     goto pull_failed;
2501
2502   bufsize = GST_BUFFER_SIZE (buf);
2503   if (bufsize != 8)
2504     goto wrong_size;
2505
2506   bufdata = GST_BUFFER_DATA (buf);
2507
2508   *tag = GST_READ_UINT32_LE (bufdata);
2509   *size = GST_READ_UINT32_LE (bufdata + 4);
2510
2511   GST_LOG_OBJECT (avi, "Tag[%" GST_FOURCC_FORMAT "] (size:%d) %"
2512       G_GINT64_FORMAT " -- %" G_GINT64_FORMAT, GST_FOURCC_ARGS (*tag),
2513       *size, offset + 8, offset + 8 + (gint64) * size);
2514
2515 done:
2516   gst_buffer_unref (buf);
2517
2518   return res;
2519
2520   /* ERRORS */
2521 pull_failed:
2522   {
2523     GST_DEBUG_OBJECT (avi, "pull_ranged returned %s", gst_flow_get_name (res));
2524     return res;
2525   }
2526 wrong_size:
2527   {
2528     GST_DEBUG_OBJECT (avi, "got %d bytes which is <> 8 bytes", bufsize);
2529     res = GST_FLOW_ERROR;
2530     goto done;
2531   }
2532 }
2533
2534 /*
2535  * gst_avi_demux_next_data_buffer:
2536  *
2537  * Returns the offset and size of the next buffer
2538  * Position is the position of the buffer (after tag and size)
2539  */
2540 static GstFlowReturn
2541 gst_avi_demux_next_data_buffer (GstAviDemux * avi, guint64 * offset,
2542     guint32 * tag, guint * size)
2543 {
2544   guint64 off = *offset;
2545   guint _size = 0;
2546   GstFlowReturn res;
2547
2548   do {
2549     res = gst_avi_demux_peek_tag (avi, off, tag, &_size);
2550     if (res != GST_FLOW_OK)
2551       break;
2552     if (*tag == GST_RIFF_TAG_LIST || *tag == GST_RIFF_TAG_RIFF)
2553       off += 8 + 4;             /* skip tag + size + subtag */
2554     else {
2555       *offset = off + 8;
2556       *size = _size;
2557       break;
2558     }
2559   } while (TRUE);
2560
2561   return res;
2562 }
2563
2564 /*
2565  * gst_avi_demux_stream_scan:
2566  * @avi: calling element (used for debugging/errors).
2567  *
2568  * Scan the file for all chunks to "create" a new index.
2569  * pull-range based
2570  */
2571 static gboolean
2572 gst_avi_demux_stream_scan (GstAviDemux * avi)
2573 {
2574   GstFlowReturn res;
2575   GstAviStream *stream;
2576   GstFormat format;
2577   guint64 pos = 0;
2578   guint64 length;
2579   gint64 tmplength;
2580   guint32 tag = 0;
2581   guint num;
2582
2583   /* FIXME:
2584    * - implement non-seekable source support.
2585    */
2586   GST_DEBUG_OBJECT (avi, "Creating index");
2587
2588   /* get the size of the file */
2589   format = GST_FORMAT_BYTES;
2590   if (!gst_pad_query_peer_duration (avi->sinkpad, &format, &tmplength))
2591     return FALSE;
2592   length = tmplength;
2593
2594   /* guess the total amount of entries we expect */
2595   num = 16000;
2596
2597   while (TRUE) {
2598     GstAviIndexEntry entry;
2599     guint size = 0;
2600
2601     /* start reading data buffers to find the id and offset */
2602     res = gst_avi_demux_next_data_buffer (avi, &pos, &tag, &size);
2603     if (G_UNLIKELY (res != GST_FLOW_OK))
2604       break;
2605
2606     /* get stream */
2607     stream = gst_avi_demux_stream_for_id (avi, tag);
2608     if (G_UNLIKELY (!stream))
2609       goto next;
2610
2611     /* we can't figure out the keyframes, assume they all are */
2612     entry.flags = GST_AVI_KEYFRAME;
2613     entry.offset = pos;
2614     entry.size = size;
2615
2616     /* and add to the index of this stream */
2617     if (G_UNLIKELY (!gst_avi_demux_add_index (avi, stream, num, &entry)))
2618       goto out_of_mem;
2619
2620   next:
2621     /* update position */
2622     pos += GST_ROUND_UP_2 (size);
2623     if (G_UNLIKELY (pos > length)) {
2624       GST_WARNING_OBJECT (avi,
2625           "Stopping index lookup since we are further than EOF");
2626       break;
2627     }
2628   }
2629
2630   /* collect stats */
2631   avi->have_index = gst_avi_demux_do_index_stats (avi);
2632
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   gboolean unexpected = FALSE, not_linked = TRUE;
3824
3825   /* store the value */
3826   stream->last_flow = ret;
3827
3828   /* any other error that is not-linked or eos can be returned right away */
3829   if (G_LIKELY (ret != GST_FLOW_UNEXPECTED && ret != GST_FLOW_NOT_LINKED))
3830     goto done;
3831
3832   /* only return NOT_LINKED if all other pads returned NOT_LINKED */
3833   for (i = 0; i < avi->num_streams; i++) {
3834     GstAviStream *ostream = &avi->stream[i];
3835
3836     ret = ostream->last_flow;
3837     /* no unexpected or unlinked, return */
3838     if (G_LIKELY (ret != GST_FLOW_UNEXPECTED && ret != GST_FLOW_NOT_LINKED))
3839       goto done;
3840
3841     /* we check to see if we have at least 1 unexpected or all unlinked */
3842     unexpected |= (ret == GST_FLOW_UNEXPECTED);
3843     not_linked &= (ret == GST_FLOW_NOT_LINKED);
3844   }
3845   /* when we get here, we all have unlinked or unexpected */
3846   if (not_linked)
3847     ret = GST_FLOW_NOT_LINKED;
3848   else if (unexpected)
3849     ret = GST_FLOW_UNEXPECTED;
3850 done:
3851   GST_LOG_OBJECT (avi, "combined %s to return %s",
3852       gst_flow_get_name (stream->last_flow), gst_flow_get_name (ret));
3853   return ret;
3854 }
3855
3856 /* move @stream to the next position in its index */
3857 static GstFlowReturn
3858 gst_avi_demux_advance (GstAviDemux * avi, GstAviStream * stream,
3859     GstFlowReturn ret)
3860 {
3861   guint old_entry, new_entry;
3862
3863   old_entry = stream->current_entry;
3864   /* move forwards */
3865   new_entry = old_entry + 1;
3866
3867   /* see if we reached the end */
3868   if (new_entry >= stream->stop_entry) {
3869     if (avi->segment.rate < 0.0) {
3870       if (stream->step_entry == stream->start_entry) {
3871         /* we stepped all the way to the start, eos */
3872         GST_DEBUG_OBJECT (avi, "reverse reached start %u", stream->start_entry);
3873         goto eos;
3874       }
3875       /* backwards, stop becomes step, find a new step */
3876       stream->stop_entry = stream->step_entry;
3877       stream->step_entry = gst_avi_demux_index_prev (avi, stream,
3878           stream->stop_entry, TRUE);
3879
3880       GST_DEBUG_OBJECT (avi,
3881           "reverse playback jump: start %u, step %u, stop %u",
3882           stream->start_entry, stream->step_entry, stream->stop_entry);
3883
3884       /* and start from the previous keyframe now */
3885       new_entry = stream->step_entry;
3886     } else {
3887       /* EOS */
3888       GST_DEBUG_OBJECT (avi, "forward reached stop %u", stream->stop_entry);
3889       goto eos;
3890     }
3891   }
3892
3893   if (new_entry != old_entry) {
3894     stream->current_entry = new_entry;
3895     stream->current_total = stream->index[new_entry].total;
3896
3897     if (new_entry == old_entry + 1) {
3898       GST_DEBUG_OBJECT (avi, "moved forwards from %u to %u",
3899           old_entry, new_entry);
3900       /* we simply moved one step forwards, reuse current info */
3901       stream->current_timestamp = stream->current_ts_end;
3902       stream->current_offset = stream->current_offset_end;
3903       gst_avi_demux_get_buffer_info (avi, stream, new_entry,
3904           NULL, &stream->current_ts_end, NULL, &stream->current_offset_end);
3905     } else {
3906       /* we moved DISCONT, full update */
3907       gst_avi_demux_get_buffer_info (avi, stream, new_entry,
3908           &stream->current_timestamp, &stream->current_ts_end,
3909           &stream->current_offset, &stream->current_offset_end);
3910       /* and MARK discont for this stream */
3911       stream->last_flow = GST_FLOW_OK;
3912       stream->discont = TRUE;
3913       GST_DEBUG_OBJECT (avi, "Moved from %u to %u, ts %" GST_TIME_FORMAT
3914           ", ts_end %" GST_TIME_FORMAT ", off %" G_GUINT64_FORMAT
3915           ", off_end %" G_GUINT64_FORMAT, old_entry, new_entry,
3916           GST_TIME_ARGS (stream->current_timestamp),
3917           GST_TIME_ARGS (stream->current_ts_end), stream->current_offset,
3918           stream->current_offset_end);
3919     }
3920   }
3921   return ret;
3922
3923   /* ERROR */
3924 eos:
3925   {
3926     GST_DEBUG_OBJECT (avi, "we are EOS");
3927     /* setting current_timestamp to -1 marks EOS */
3928     stream->current_timestamp = -1;
3929     return GST_FLOW_UNEXPECTED;
3930   }
3931 }
3932
3933 /* find the stream with the lowest current position when going forwards or with
3934  * the highest position when going backwards, this is the stream
3935  * we should push from next */
3936 static gint
3937 gst_avi_demux_find_next (GstAviDemux * avi, gfloat rate)
3938 {
3939   guint64 min_time, max_time;
3940   guint stream_num, i;
3941
3942   max_time = 0;
3943   min_time = G_MAXUINT64;
3944   stream_num = -1;
3945
3946   for (i = 0; i < avi->num_streams; i++) {
3947     guint64 position;
3948     GstAviStream *stream;
3949
3950     stream = &avi->stream[i];
3951     position = stream->current_timestamp;
3952
3953     /* position of -1 is EOS */
3954     if (position != -1) {
3955       if (rate > 0.0 && position < min_time) {
3956         min_time = position;
3957         stream_num = i;
3958       } else if (rate < 0.0 && position >= max_time) {
3959         max_time = position;
3960         stream_num = i;
3961       }
3962     }
3963   }
3964   return stream_num;
3965 }
3966
3967 static GstFlowReturn
3968 gst_avi_demux_loop_data (GstAviDemux * avi)
3969 {
3970   GstFlowReturn ret = GST_FLOW_OK;
3971   guint stream_num;
3972   GstAviStream *stream;
3973   gboolean processed = FALSE;
3974   GstBuffer *buf;
3975   guint64 offset, size;
3976   GstClockTime timestamp, duration;
3977   guint64 out_offset, out_offset_end;
3978   gboolean keyframe;
3979   GstAviIndexEntry *entry;
3980
3981   do {
3982     stream_num = gst_avi_demux_find_next (avi, avi->segment.rate);
3983
3984     /* all are EOS */
3985     if (G_UNLIKELY (stream_num == -1)) {
3986       GST_DEBUG_OBJECT (avi, "all streams are EOS");
3987       goto eos;
3988     }
3989
3990     /* we have the stream now */
3991     stream = &avi->stream[stream_num];
3992
3993     /* skip streams without pads */
3994     if (!stream->pad) {
3995       GST_DEBUG_OBJECT (avi, "skipping entry from stream %d without pad",
3996           stream_num);
3997       goto next;
3998     }
3999
4000     /* get the timing info for the entry */
4001     timestamp = stream->current_timestamp;
4002     duration = stream->current_ts_end - timestamp;
4003     out_offset = stream->current_offset;
4004     out_offset_end = stream->current_offset_end;
4005
4006     /* get the entry data info */
4007     entry = &stream->index[stream->current_entry];
4008     offset = entry->offset;
4009     size = entry->size;
4010     keyframe = ENTRY_IS_KEYFRAME (entry);
4011
4012     /* skip empty entries */
4013     if (size == 0) {
4014       GST_DEBUG_OBJECT (avi, "Skipping entry %u (%" G_GUINT64_FORMAT ", %p)",
4015           stream->current_entry, size, stream->pad);
4016       goto next;
4017     }
4018
4019     if (avi->segment.rate > 0.0) {
4020       /* only check this for fowards playback for now */
4021       if (keyframe && GST_CLOCK_TIME_IS_VALID (avi->segment.stop)
4022           && (timestamp > avi->segment.stop)) {
4023         goto eos_stop;
4024       }
4025     }
4026
4027     GST_LOG ("reading buffer (size=%" G_GUINT64_FORMAT "), stream %d, pos %"
4028         G_GUINT64_FORMAT " (0x%" G_GINT64_MODIFIER "x), kf %d", size,
4029         stream_num, offset, offset, keyframe);
4030
4031     /* FIXME, check large chunks and cut them up */
4032
4033     /* pull in the data */
4034     ret = gst_pad_pull_range (avi->sinkpad, offset, size, &buf);
4035     if (ret != GST_FLOW_OK)
4036       goto pull_failed;
4037
4038     /* check for short buffers, this is EOS as well */
4039     if (GST_BUFFER_SIZE (buf) < size)
4040       goto short_buffer;
4041
4042     /* invert the picture if needed */
4043     buf = gst_avi_demux_invert (stream, buf);
4044
4045     /* mark non-keyframes */
4046     if (keyframe)
4047       GST_BUFFER_FLAG_UNSET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
4048     else
4049       GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
4050
4051     GST_BUFFER_TIMESTAMP (buf) = timestamp;
4052     GST_BUFFER_DURATION (buf) = duration;
4053     GST_BUFFER_OFFSET (buf) = out_offset;
4054     GST_BUFFER_OFFSET_END (buf) = out_offset_end;
4055
4056     /* mark discont when pending */
4057     if (stream->discont) {
4058       GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
4059       stream->discont = FALSE;
4060     }
4061
4062     gst_avi_demux_add_assoc (avi, stream, timestamp, offset, keyframe);
4063
4064     gst_buffer_set_caps (buf, GST_PAD_CAPS (stream->pad));
4065
4066     /* update current position in the segment */
4067     gst_segment_set_last_stop (&avi->segment, GST_FORMAT_TIME, timestamp);
4068
4069     GST_DEBUG_OBJECT (avi, "Pushing buffer of size %u, ts %"
4070         GST_TIME_FORMAT ", dur %" GST_TIME_FORMAT ", off %" G_GUINT64_FORMAT
4071         ", off_end %" G_GUINT64_FORMAT,
4072         GST_BUFFER_SIZE (buf), GST_TIME_ARGS (timestamp),
4073         GST_TIME_ARGS (duration), out_offset, out_offset_end);
4074
4075     ret = gst_pad_push (stream->pad, buf);
4076
4077     /* mark as processed, we increment the frame and byte counters then
4078      * leave the while loop and return the GstFlowReturn */
4079     processed = TRUE;
4080
4081     if (avi->segment.rate < 0) {
4082       if (timestamp > avi->segment.stop && ret == GST_FLOW_UNEXPECTED) {
4083         /* In reverse playback we can get a GST_FLOW_UNEXPECTED when
4084          * we are at the end of the segment, so we just need to jump
4085          * back to the previous section. */
4086         GST_DEBUG_OBJECT (avi, "downstream has reached end of segment");
4087         ret = GST_FLOW_OK;
4088       }
4089     }
4090   next:
4091     /* move to next item */
4092     ret = gst_avi_demux_advance (avi, stream, ret);
4093
4094     /* combine flows */
4095     ret = gst_avi_demux_combine_flows (avi, stream, ret);
4096   } while (!processed);
4097
4098 beach:
4099   return ret;
4100
4101   /* special cases */
4102 eos:
4103   {
4104     GST_DEBUG_OBJECT (avi, "No samples left for any streams - EOS");
4105     ret = GST_FLOW_UNEXPECTED;
4106     goto beach;
4107   }
4108 eos_stop:
4109   {
4110     GST_LOG_OBJECT (avi, "Found keyframe after segment,"
4111         " setting EOS (%" GST_TIME_FORMAT " > %" GST_TIME_FORMAT ")",
4112         GST_TIME_ARGS (timestamp), GST_TIME_ARGS (avi->segment.stop));
4113     ret = GST_FLOW_UNEXPECTED;
4114     goto beach;
4115   }
4116 pull_failed:
4117   {
4118     GST_DEBUG_OBJECT (avi, "pull range failed: pos=%" G_GUINT64_FORMAT
4119         " size=%" G_GUINT64_FORMAT, offset, size);
4120     goto beach;
4121   }
4122 short_buffer:
4123   {
4124     GST_WARNING_OBJECT (avi, "Short read at offset %" G_GUINT64_FORMAT
4125         ", only got %d/%" G_GUINT64_FORMAT " bytes (truncated file?)", offset,
4126         GST_BUFFER_SIZE (buf), size);
4127     gst_buffer_unref (buf);
4128     ret = GST_FLOW_UNEXPECTED;
4129     goto beach;
4130   }
4131 }
4132
4133 /*
4134  * Read data. If we have an index it delegates to
4135  * gst_avi_demux_process_next_entry().
4136  */
4137 static GstFlowReturn
4138 gst_avi_demux_stream_data (GstAviDemux * avi)
4139 {
4140   guint32 tag = 0;
4141   guint32 size = 0;
4142   gint stream_nr = 0;
4143   GstFlowReturn res = GST_FLOW_OK;
4144   GstFormat format = GST_FORMAT_TIME;
4145
4146   if (G_UNLIKELY (avi->have_eos)) {
4147     /* Clean adapter, we're done */
4148     gst_adapter_clear (avi->adapter);
4149     return GST_FLOW_UNEXPECTED;
4150   }
4151
4152   if (G_UNLIKELY (avi->todrop)) {
4153     guint drop;
4154
4155     if ((drop = gst_adapter_available (avi->adapter))) {
4156       if (drop > avi->todrop)
4157         drop = avi->todrop;
4158       GST_DEBUG_OBJECT (avi, "Dropping %d bytes", drop);
4159       gst_adapter_flush (avi->adapter, drop);
4160       avi->todrop -= drop;
4161       avi->offset += drop;
4162     }
4163   }
4164
4165   /* Iterate until need more data, so adapter won't grow too much */
4166   while (1) {
4167     if (G_UNLIKELY (!gst_avi_demux_peek_chunk_info (avi, &tag, &size))) {
4168       return GST_FLOW_OK;
4169     }
4170
4171     GST_DEBUG ("Trying chunk (%" GST_FOURCC_FORMAT "), size %d",
4172         GST_FOURCC_ARGS (tag), size);
4173
4174     if (G_LIKELY ((tag & 0xff) >= '0' && (tag & 0xff) <= '9' &&
4175             ((tag >> 8) & 0xff) >= '0' && ((tag >> 8) & 0xff) <= '9')) {
4176       GST_LOG ("Chunk ok");
4177     } else if ((tag & 0xffff) == (('x' << 8) | 'i')) {
4178       GST_DEBUG ("Found sub-index tag");
4179       if (gst_avi_demux_peek_chunk (avi, &tag, &size) || size == 0) {
4180         /* accept 0 size buffer here */
4181         avi->abort_buffering = FALSE;
4182         GST_DEBUG ("  skipping %d bytes for now", size);
4183         gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
4184       }
4185       return GST_FLOW_OK;
4186     } else if (tag == GST_RIFF_TAG_idx1) {
4187       GST_DEBUG ("Found index tag, stream done");
4188       avi->have_eos = TRUE;
4189       return GST_FLOW_UNEXPECTED;
4190     } else if (tag == GST_RIFF_TAG_LIST) {
4191       /* movi chunks might be grouped in rec list */
4192       if (gst_adapter_available (avi->adapter) >= 12) {
4193         GST_DEBUG ("Found LIST tag, skipping LIST header");
4194         gst_adapter_flush (avi->adapter, 12);
4195         continue;
4196       }
4197       return GST_FLOW_OK;
4198     } else if (tag == GST_RIFF_TAG_JUNK) {
4199       /* rec list might contain JUNK chunks */
4200       GST_DEBUG ("Found JUNK tag");
4201       if (gst_avi_demux_peek_chunk (avi, &tag, &size) || size == 0) {
4202         /* accept 0 size buffer here */
4203         avi->abort_buffering = FALSE;
4204         GST_DEBUG ("  skipping %d bytes for now", size);
4205         gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
4206       }
4207       return GST_FLOW_OK;
4208     } else {
4209       GST_DEBUG ("No more stream chunks, send EOS");
4210       avi->have_eos = TRUE;
4211       return GST_FLOW_UNEXPECTED;
4212     }
4213
4214     if (G_UNLIKELY (!gst_avi_demux_peek_chunk (avi, &tag, &size))) {
4215       /* supposedly one hopes to catch a nicer chunk later on ... */
4216       /* FIXME ?? give up here rather than possibly ending up going
4217        * through the whole file */
4218       if (avi->abort_buffering) {
4219         avi->abort_buffering = FALSE;
4220         gst_adapter_flush (avi->adapter, 8);
4221       }
4222       return GST_FLOW_OK;
4223     }
4224     GST_DEBUG ("chunk ID %" GST_FOURCC_FORMAT ", size %u",
4225         GST_FOURCC_ARGS (tag), size);
4226
4227     stream_nr = CHUNKID_TO_STREAMNR (tag);
4228
4229     if (G_UNLIKELY (stream_nr < 0 || stream_nr >= avi->num_streams)) {
4230       /* recoverable */
4231       GST_WARNING ("Invalid stream ID %d (%" GST_FOURCC_FORMAT ")",
4232           stream_nr, GST_FOURCC_ARGS (tag));
4233       avi->offset += 8 + GST_ROUND_UP_2 (size);
4234       gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
4235     } else {
4236       GstAviStream *stream;
4237       GstClockTime next_ts = 0;
4238       GstBuffer *buf;
4239       guint64 offset;
4240
4241       gst_adapter_flush (avi->adapter, 8);
4242
4243       /* get buffer */
4244       buf = gst_adapter_take_buffer (avi->adapter, GST_ROUND_UP_2 (size));
4245       /* patch the size */
4246       GST_BUFFER_SIZE (buf) = size;
4247       offset = avi->offset;
4248       avi->offset += 8 + GST_ROUND_UP_2 (size);
4249
4250       stream = &avi->stream[stream_nr];
4251
4252       /* set delay (if any)
4253          if (stream->strh->init_frames == stream->current_frame &&
4254          stream->delay == 0)
4255          stream->delay = next_ts;
4256        */
4257
4258       /* parsing of corresponding header may have failed */
4259       if (G_UNLIKELY (!stream->pad)) {
4260         GST_WARNING_OBJECT (avi, "no pad for stream ID %" GST_FOURCC_FORMAT,
4261             GST_FOURCC_ARGS (tag));
4262         gst_buffer_unref (buf);
4263       } else {
4264         GstClockTime dur_ts = 0;
4265
4266         /* get time of this buffer */
4267         gst_pad_query_position (stream->pad, &format, (gint64 *) & next_ts);
4268         if (G_UNLIKELY (format != GST_FORMAT_TIME))
4269           goto wrong_format;
4270
4271         gst_avi_demux_add_assoc (avi, stream, next_ts, offset, FALSE);
4272
4273         /* increment our positions */
4274         stream->current_entry++;
4275         stream->current_total += size;
4276
4277         /* invert the picture if needed */
4278         buf = gst_avi_demux_invert (stream, buf);
4279
4280         gst_pad_query_position (stream->pad, &format, (gint64 *) & dur_ts);
4281         if (G_UNLIKELY (format != GST_FORMAT_TIME))
4282           goto wrong_format;
4283
4284         GST_BUFFER_TIMESTAMP (buf) = next_ts;
4285         GST_BUFFER_DURATION (buf) = dur_ts - next_ts;
4286         if (stream->strh->type == GST_RIFF_FCC_vids) {
4287           GST_BUFFER_OFFSET (buf) = stream->current_entry - 1;
4288           GST_BUFFER_OFFSET_END (buf) = stream->current_entry;
4289         } else {
4290           GST_BUFFER_OFFSET (buf) = GST_BUFFER_OFFSET_NONE;
4291           GST_BUFFER_OFFSET_END (buf) = GST_BUFFER_OFFSET_NONE;
4292         }
4293
4294         gst_buffer_set_caps (buf, GST_PAD_CAPS (stream->pad));
4295         GST_DEBUG_OBJECT (avi,
4296             "Pushing buffer with time=%" GST_TIME_FORMAT ", duration %"
4297             GST_TIME_FORMAT ", offset %" G_GUINT64_FORMAT
4298             " and size %d over pad %s", GST_TIME_ARGS (next_ts),
4299             GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)), GST_BUFFER_OFFSET (buf),
4300             size, GST_PAD_NAME (stream->pad));
4301
4302         /* update current position in the segment */
4303         gst_segment_set_last_stop (&avi->segment, GST_FORMAT_TIME, next_ts);
4304
4305         /* mark discont when pending */
4306         if (G_UNLIKELY (stream->discont)) {
4307           GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
4308           stream->discont = FALSE;
4309         }
4310         res = gst_pad_push (stream->pad, buf);
4311
4312         /* combine flows */
4313         res = gst_avi_demux_combine_flows (avi, stream, res);
4314         if (G_UNLIKELY (res != GST_FLOW_OK)) {
4315           GST_DEBUG ("Push failed; %s", gst_flow_get_name (res));
4316           return res;
4317         }
4318       }
4319     }
4320   }
4321
4322 done:
4323   return res;
4324
4325   /* ERRORS */
4326 wrong_format:
4327   {
4328     GST_DEBUG_OBJECT (avi, "format %s != GST_FORMAT_TIME",
4329         gst_format_get_name (format));
4330     res = GST_FLOW_ERROR;
4331     goto done;
4332   }
4333 }
4334
4335 /*
4336  * Send pending tags.
4337  */
4338 static void
4339 push_tag_lists (GstAviDemux * avi)
4340 {
4341   guint i;
4342   GstTagList *tags;
4343
4344   if (!avi->got_tags)
4345     return;
4346
4347   GST_DEBUG_OBJECT (avi, "Pushing pending tag lists");
4348
4349   for (i = 0; i < avi->num_streams; i++) {
4350     GstAviStream *stream = &avi->stream[i];
4351     GstPad *pad = stream->pad;
4352
4353     tags = stream->taglist;
4354
4355     if (pad && tags) {
4356       GST_DEBUG_OBJECT (pad, "Tags: %" GST_PTR_FORMAT, tags);
4357
4358       gst_element_found_tags_for_pad (GST_ELEMENT_CAST (avi), pad, tags);
4359       stream->taglist = NULL;
4360     }
4361   }
4362
4363   if (!(tags = avi->globaltags))
4364     tags = gst_tag_list_new ();
4365
4366   gst_tag_list_add (tags, GST_TAG_MERGE_REPLACE,
4367       GST_TAG_CONTAINER_FORMAT, "AVI", NULL);
4368
4369   GST_DEBUG_OBJECT (avi, "Global tags: %" GST_PTR_FORMAT, tags);
4370   gst_element_found_tags (GST_ELEMENT_CAST (avi), tags);
4371   avi->globaltags = NULL;
4372   avi->got_tags = FALSE;
4373 }
4374
4375 static void
4376 gst_avi_demux_loop (GstPad * pad)
4377 {
4378   GstFlowReturn res;
4379   GstAviDemux *avi = GST_AVI_DEMUX (GST_PAD_PARENT (pad));
4380
4381   switch (avi->state) {
4382     case GST_AVI_DEMUX_START:
4383       res = gst_avi_demux_stream_init_pull (avi);
4384       if (G_UNLIKELY (res != GST_FLOW_OK)) {
4385         GST_WARNING ("stream_init flow: %s", gst_flow_get_name (res));
4386         goto pause;
4387       }
4388       avi->state = GST_AVI_DEMUX_HEADER;
4389       /* fall-through */
4390     case GST_AVI_DEMUX_HEADER:
4391       res = gst_avi_demux_stream_header_pull (avi);
4392       if (G_UNLIKELY (res != GST_FLOW_OK)) {
4393         GST_WARNING ("stream_header flow: %s", gst_flow_get_name (res));
4394         goto pause;
4395       }
4396       avi->state = GST_AVI_DEMUX_MOVI;
4397       break;
4398     case GST_AVI_DEMUX_MOVI:
4399       if (G_UNLIKELY (avi->seek_event)) {
4400         gst_avi_demux_push_event (avi, avi->seek_event);
4401         avi->seek_event = NULL;
4402       }
4403       if (G_UNLIKELY (avi->got_tags)) {
4404         push_tag_lists (avi);
4405       }
4406       /* process each index entry in turn */
4407       res = gst_avi_demux_loop_data (avi);
4408
4409       /* pause when error */
4410       if (G_UNLIKELY (res != GST_FLOW_OK)) {
4411         GST_INFO ("stream_movi flow: %s", gst_flow_get_name (res));
4412         goto pause;
4413       }
4414       break;
4415     default:
4416       GST_ERROR_OBJECT (avi, "unknown state %d", avi->state);
4417       res = GST_FLOW_ERROR;
4418       goto pause;
4419   }
4420
4421   return;
4422
4423   /* ERRORS */
4424 pause:
4425   GST_LOG_OBJECT (avi, "pausing task, reason %s", gst_flow_get_name (res));
4426   avi->segment_running = FALSE;
4427   gst_pad_pause_task (avi->sinkpad);
4428
4429   if (GST_FLOW_IS_FATAL (res) || (res == GST_FLOW_NOT_LINKED)) {
4430     gboolean push_eos = TRUE;
4431
4432     if (res == GST_FLOW_UNEXPECTED) {
4433       /* handle end-of-stream/segment */
4434       if (avi->segment.flags & GST_SEEK_FLAG_SEGMENT) {
4435         gint64 stop;
4436
4437         if ((stop = avi->segment.stop) == -1)
4438           stop = avi->segment.duration;
4439
4440         GST_INFO_OBJECT (avi, "sending segment_done");
4441
4442         gst_element_post_message
4443             (GST_ELEMENT (avi),
4444             gst_message_new_segment_done (GST_OBJECT (avi), GST_FORMAT_TIME,
4445                 stop));
4446         push_eos = FALSE;
4447       }
4448     } else {
4449       /* for fatal errors we post an error message */
4450       GST_ELEMENT_ERROR (avi, STREAM, FAILED,
4451           (_("Internal data stream error.")),
4452           ("streaming stopped, reason %s", gst_flow_get_name (res)));
4453     }
4454     if (push_eos) {
4455       GST_INFO_OBJECT (avi, "sending eos");
4456       if (!gst_avi_demux_push_event (avi, gst_event_new_eos ()) &&
4457           (res == GST_FLOW_UNEXPECTED)) {
4458         GST_ELEMENT_ERROR (avi, STREAM, DEMUX,
4459             (NULL), ("got eos but no streams (yet)"));
4460       }
4461     }
4462   }
4463 }
4464
4465
4466 static GstFlowReturn
4467 gst_avi_demux_chain (GstPad * pad, GstBuffer * buf)
4468 {
4469   GstFlowReturn res;
4470   GstAviDemux *avi = GST_AVI_DEMUX (GST_PAD_PARENT (pad));
4471
4472   GST_DEBUG ("Store %d bytes in adapter", GST_BUFFER_SIZE (buf));
4473   gst_adapter_push (avi->adapter, buf);
4474
4475   switch (avi->state) {
4476     case GST_AVI_DEMUX_START:
4477       if ((res = gst_avi_demux_stream_init_push (avi)) != GST_FLOW_OK) {
4478         GST_WARNING ("stream_init flow: %s", gst_flow_get_name (res));
4479         break;
4480       }
4481       break;
4482     case GST_AVI_DEMUX_HEADER:
4483       if ((res = gst_avi_demux_stream_header_push (avi)) != GST_FLOW_OK) {
4484         GST_WARNING ("stream_header flow: %s", gst_flow_get_name (res));
4485         break;
4486       }
4487       break;
4488     case GST_AVI_DEMUX_MOVI:
4489       if (G_UNLIKELY (avi->seek_event)) {
4490         gst_avi_demux_push_event (avi, avi->seek_event);
4491         avi->seek_event = NULL;
4492       }
4493       if (G_UNLIKELY (avi->got_tags)) {
4494         push_tag_lists (avi);
4495       }
4496       res = gst_avi_demux_stream_data (avi);
4497       break;
4498     default:
4499       GST_ELEMENT_ERROR (avi, STREAM, FAILED, (NULL),
4500           ("Illegal internal state"));
4501       res = GST_FLOW_ERROR;
4502       break;
4503   }
4504
4505   GST_DEBUG_OBJECT (avi, "state: %d res:%s", avi->state,
4506       gst_flow_get_name (res));
4507
4508   if (G_UNLIKELY (avi->abort_buffering)) {
4509     avi->abort_buffering = FALSE;
4510     res = GST_FLOW_ERROR;
4511     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("unhandled buffer size"));
4512   }
4513
4514   return res;
4515 }
4516
4517 static gboolean
4518 gst_avi_demux_sink_activate (GstPad * sinkpad)
4519 {
4520   if (gst_pad_check_pull_range (sinkpad)) {
4521     GST_DEBUG ("going to pull mode");
4522     return gst_pad_activate_pull (sinkpad, TRUE);
4523   } else {
4524     GST_DEBUG ("going to push (streaming) mode");
4525     return gst_pad_activate_push (sinkpad, TRUE);
4526   }
4527 }
4528
4529 static gboolean
4530 gst_avi_demux_sink_activate_pull (GstPad * sinkpad, gboolean active)
4531 {
4532   GstAviDemux *avi = GST_AVI_DEMUX (GST_OBJECT_PARENT (sinkpad));
4533
4534   if (active) {
4535     avi->segment_running = TRUE;
4536     avi->streaming = FALSE;
4537     return gst_pad_start_task (sinkpad, (GstTaskFunction) gst_avi_demux_loop,
4538         sinkpad);
4539   } else {
4540     avi->segment_running = FALSE;
4541     return gst_pad_stop_task (sinkpad);
4542   }
4543 }
4544
4545 static gboolean
4546 gst_avi_demux_activate_push (GstPad * pad, gboolean active)
4547 {
4548   GstAviDemux *avi = GST_AVI_DEMUX (GST_OBJECT_PARENT (pad));
4549
4550   if (active) {
4551     GST_DEBUG ("avi: activating push/chain function");
4552     avi->streaming = TRUE;
4553 #if 0
4554     /* create index for some push based seeking if not provided */
4555     GST_OBJECT_LOCK (avi);
4556     if (!avi->element_index) {
4557       GST_DEBUG_OBJECT (avi, "creating index");
4558       avi->element_index = gst_index_factory_make ("memindex");
4559     }
4560     GST_OBJECT_UNLOCK (avi);
4561     /* object lock might be taken again */
4562     gst_index_get_writer_id (avi->element_index, GST_OBJECT (avi),
4563         &avi->index_id);
4564 #endif
4565   } else {
4566     GST_DEBUG ("avi: deactivating push/chain function");
4567   }
4568
4569   return TRUE;
4570 }
4571
4572 static void
4573 gst_avi_demux_set_index (GstElement * element, GstIndex * index)
4574 {
4575   GstAviDemux *avi = GST_AVI_DEMUX (element);
4576
4577   GST_OBJECT_LOCK (avi);
4578   if (avi->element_index)
4579     gst_object_unref (avi->element_index);
4580   if (index) {
4581     avi->element_index = gst_object_ref (index);
4582   } else {
4583     avi->element_index = NULL;
4584   }
4585   GST_OBJECT_UNLOCK (avi);
4586   /* object lock might be taken again */
4587   if (index)
4588     gst_index_get_writer_id (index, GST_OBJECT (element), &avi->index_id);
4589   GST_DEBUG_OBJECT (avi, "Set index %" GST_PTR_FORMAT, avi->element_index);
4590 }
4591
4592 static GstIndex *
4593 gst_avi_demux_get_index (GstElement * element)
4594 {
4595   GstIndex *result = NULL;
4596   GstAviDemux *avi = GST_AVI_DEMUX (element);
4597
4598   GST_OBJECT_LOCK (avi);
4599   if (avi->element_index)
4600     result = gst_object_ref (avi->element_index);
4601   GST_OBJECT_UNLOCK (avi);
4602
4603   GST_DEBUG_OBJECT (avi, "Returning index %" GST_PTR_FORMAT, result);
4604
4605   return result;
4606 }
4607
4608 static GstStateChangeReturn
4609 gst_avi_demux_change_state (GstElement * element, GstStateChange transition)
4610 {
4611   GstStateChangeReturn ret;
4612   GstAviDemux *avi = GST_AVI_DEMUX (element);
4613
4614   switch (transition) {
4615     case GST_STATE_CHANGE_READY_TO_PAUSED:
4616       avi->streaming = FALSE;
4617       gst_segment_init (&avi->segment, GST_FORMAT_TIME);
4618       break;
4619     default:
4620       break;
4621   }
4622
4623   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
4624   if (ret == GST_STATE_CHANGE_FAILURE)
4625     goto done;
4626
4627   switch (transition) {
4628     case GST_STATE_CHANGE_PAUSED_TO_READY:
4629       gst_avi_demux_reset (avi);
4630       break;
4631     default:
4632       break;
4633   }
4634
4635 done:
4636   return ret;
4637 }