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