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