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