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