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