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