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