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