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     /* assume 0 padding, at least makes outcome deterministic */
1885     data[size] = 0;
1886     gst_buffer_unmap (obuf, data, size + 1);
1887     gst_buffer_replace (buf, obuf);
1888   }
1889 }
1890
1891 /*
1892  * gst_avi_demux_parse_stream:
1893  * @avi: calling element (used for debugging/errors).
1894  * @buf: input buffer used to parse the stream.
1895  *
1896  * Parses all subchunks in a strl chunk (which defines a single
1897  * stream). Discards the buffer after use. This function will
1898  * increment the stream counter internally.
1899  *
1900  * Returns: whether the stream was identified successfully.
1901  *          Errors are not fatal. It does indicate the stream
1902  *          was skipped.
1903  */
1904 static gboolean
1905 gst_avi_demux_parse_stream (GstAviDemux * avi, GstBuffer * buf)
1906 {
1907   GstAviStream *stream;
1908   GstElementClass *klass;
1909   GstPadTemplate *templ;
1910   GstBuffer *sub = NULL;
1911   guint offset = 4;
1912   guint32 tag = 0;
1913   gchar *codec_name = NULL, *padname = NULL;
1914   const gchar *tag_name;
1915   GstCaps *caps = NULL;
1916   GstPad *pad;
1917   GstElement *element;
1918   gboolean got_strh = FALSE, got_strf = FALSE, got_vprp = FALSE;
1919   gst_riff_vprp *vprp = NULL;
1920
1921   element = GST_ELEMENT_CAST (avi);
1922
1923   GST_DEBUG_OBJECT (avi, "Parsing stream");
1924
1925   gst_avi_demux_roundup_list (avi, &buf);
1926
1927   if (avi->num_streams >= GST_AVI_DEMUX_MAX_STREAMS) {
1928     GST_WARNING_OBJECT (avi,
1929         "maximum no of streams (%d) exceeded, ignoring stream",
1930         GST_AVI_DEMUX_MAX_STREAMS);
1931     gst_buffer_unref (buf);
1932     /* not a fatal error, let's say */
1933     return TRUE;
1934   }
1935
1936   stream = &avi->stream[avi->num_streams];
1937
1938   /* initial settings */
1939   stream->idx_duration = GST_CLOCK_TIME_NONE;
1940   stream->hdr_duration = GST_CLOCK_TIME_NONE;
1941   stream->duration = GST_CLOCK_TIME_NONE;
1942
1943   while (gst_riff_parse_chunk (element, buf, &offset, &tag, &sub)) {
1944     /* sub can be NULL if the chunk is empty */
1945     if (sub == NULL) {
1946       GST_DEBUG_OBJECT (avi, "ignoring empty chunk %" GST_FOURCC_FORMAT,
1947           GST_FOURCC_ARGS (tag));
1948       continue;
1949     }
1950     switch (tag) {
1951       case GST_RIFF_TAG_strh:
1952       {
1953         gst_riff_strh *strh;
1954
1955         if (got_strh) {
1956           GST_WARNING_OBJECT (avi, "Ignoring additional strh chunk");
1957           break;
1958         }
1959         if (!gst_riff_parse_strh (element, sub, &stream->strh)) {
1960           /* ownership given away */
1961           sub = NULL;
1962           GST_WARNING_OBJECT (avi, "Failed to parse strh chunk");
1963           goto fail;
1964         }
1965         sub = NULL;
1966         strh = stream->strh;
1967         /* sanity check; stream header frame rate matches global header
1968          * frame duration */
1969         if (stream->strh->type == GST_RIFF_FCC_vids) {
1970           GstClockTime s_dur;
1971           GstClockTime h_dur = avi->avih->us_frame * GST_USECOND;
1972
1973           s_dur = gst_util_uint64_scale (GST_SECOND, strh->scale, strh->rate);
1974           GST_DEBUG_OBJECT (avi, "verifying stream framerate %d/%d, "
1975               "frame duration = %d ms", strh->rate, strh->scale,
1976               (gint) (s_dur / GST_MSECOND));
1977           if (h_dur > (10 * GST_MSECOND) && (s_dur > 10 * h_dur)) {
1978             strh->rate = GST_SECOND / GST_USECOND;
1979             strh->scale = h_dur / GST_USECOND;
1980             GST_DEBUG_OBJECT (avi, "correcting stream framerate to %d/%d",
1981                 strh->rate, strh->scale);
1982           }
1983         }
1984         /* determine duration as indicated by header */
1985         stream->hdr_duration = gst_util_uint64_scale ((guint64) strh->length *
1986             strh->scale, GST_SECOND, (guint64) strh->rate);
1987         GST_INFO ("Stream duration according to header: %" GST_TIME_FORMAT,
1988             GST_TIME_ARGS (stream->hdr_duration));
1989         if (stream->hdr_duration == 0)
1990           stream->hdr_duration = GST_CLOCK_TIME_NONE;
1991
1992         got_strh = TRUE;
1993         break;
1994       }
1995       case GST_RIFF_TAG_strf:
1996       {
1997         gboolean res = FALSE;
1998
1999         if (got_strf) {
2000           GST_WARNING_OBJECT (avi, "Ignoring additional strf chunk");
2001           break;
2002         }
2003         if (!got_strh) {
2004           GST_ERROR_OBJECT (avi, "Found strf chunk before strh chunk");
2005           goto fail;
2006         }
2007         switch (stream->strh->type) {
2008           case GST_RIFF_FCC_vids:
2009             stream->is_vbr = TRUE;
2010             res = gst_riff_parse_strf_vids (element, sub,
2011                 &stream->strf.vids, &stream->extradata);
2012             sub = NULL;
2013             GST_DEBUG_OBJECT (element, "marking video as VBR, res %d", res);
2014             break;
2015           case GST_RIFF_FCC_auds:
2016             res =
2017                 gst_riff_parse_strf_auds (element, sub, &stream->strf.auds,
2018                 &stream->extradata);
2019             sub = NULL;
2020             if (!res)
2021               break;
2022             stream->is_vbr = (stream->strh->samplesize == 0)
2023                 && stream->strh->scale > 1
2024                 && stream->strf.auds->blockalign != 1;
2025             GST_DEBUG_OBJECT (element, "marking audio as VBR:%d, res %d",
2026                 stream->is_vbr, res);
2027             /* we need these or we have no way to come up with timestamps */
2028             if ((!stream->is_vbr && !stream->strf.auds->av_bps) ||
2029                 (stream->is_vbr && (!stream->strh->scale ||
2030                         !stream->strh->rate))) {
2031               GST_WARNING_OBJECT (element,
2032                   "invalid audio header, ignoring stream");
2033               goto fail;
2034             }
2035             /* some more sanity checks */
2036             if (stream->is_vbr) {
2037               if (stream->strf.auds->blockalign <= 4) {
2038                 /* that would mean (too) many frames per chunk,
2039                  * so not likely set as expected */
2040                 GST_DEBUG_OBJECT (element,
2041                     "suspicious blockalign %d for VBR audio; "
2042                     "overriding to 1 frame per chunk",
2043                     stream->strf.auds->blockalign);
2044                 /* this should top any likely value */
2045                 stream->strf.auds->blockalign = (1 << 12);
2046               }
2047             }
2048             break;
2049           case GST_RIFF_FCC_iavs:
2050             stream->is_vbr = TRUE;
2051             res = gst_riff_parse_strf_iavs (element, sub,
2052                 &stream->strf.iavs, &stream->extradata);
2053             sub = NULL;
2054             GST_DEBUG_OBJECT (element, "marking iavs as VBR, res %d", res);
2055             break;
2056           case GST_RIFF_FCC_txts:
2057             /* nothing to parse here */
2058             stream->is_vbr = (stream->strh->samplesize == 0)
2059                 && (stream->strh->scale > 1);
2060             res = TRUE;
2061             break;
2062           default:
2063             GST_ERROR_OBJECT (avi,
2064                 "Don´t know how to handle stream type %" GST_FOURCC_FORMAT,
2065                 GST_FOURCC_ARGS (stream->strh->type));
2066             break;
2067         }
2068         if (sub) {
2069           gst_buffer_unref (sub);
2070           sub = NULL;
2071         }
2072         if (!res)
2073           goto fail;
2074         got_strf = TRUE;
2075         break;
2076       }
2077       case GST_RIFF_TAG_vprp:
2078       {
2079         if (got_vprp) {
2080           GST_WARNING_OBJECT (avi, "Ignoring additional vprp chunk");
2081           break;
2082         }
2083         if (!got_strh) {
2084           GST_ERROR_OBJECT (avi, "Found vprp chunk before strh chunk");
2085           goto fail;
2086         }
2087         if (!got_strf) {
2088           GST_ERROR_OBJECT (avi, "Found vprp chunk before strf chunk");
2089           goto fail;
2090         }
2091
2092         if (!gst_avi_demux_riff_parse_vprp (element, sub, &vprp)) {
2093           GST_WARNING_OBJECT (avi, "Failed to parse vprp chunk");
2094           /* not considered fatal */
2095           g_free (vprp);
2096           vprp = NULL;
2097         } else
2098           got_vprp = TRUE;
2099         sub = NULL;
2100         break;
2101       }
2102       case GST_RIFF_TAG_strd:
2103         if (stream->initdata)
2104           gst_buffer_unref (stream->initdata);
2105         stream->initdata = sub;
2106         sub = NULL;
2107         break;
2108       case GST_RIFF_TAG_strn:
2109         g_free (stream->name);
2110         if (sub != NULL) {
2111           gchar *bdata;
2112           gsize bsize;
2113
2114           bdata = gst_buffer_map (sub, &bsize, NULL, GST_MAP_READ);
2115           stream->name = g_strndup (bdata, bsize);
2116           gst_buffer_unmap (sub, bdata, bsize);
2117           gst_buffer_unref (sub);
2118           sub = NULL;
2119         } else {
2120           stream->name = g_strdup ("");
2121         }
2122         GST_DEBUG_OBJECT (avi, "stream name: %s", stream->name);
2123         break;
2124       case GST_RIFF_IDIT:
2125         gst_avi_demux_parse_idit (avi, sub);
2126         break;
2127       default:
2128         if (tag == GST_MAKE_FOURCC ('i', 'n', 'd', 'x') ||
2129             tag == GST_MAKE_FOURCC ('i', 'x', '0' + avi->num_streams / 10,
2130                 '0' + avi->num_streams % 10)) {
2131           g_free (stream->indexes);
2132           gst_avi_demux_parse_superindex (avi, sub, &stream->indexes);
2133           stream->superindex = TRUE;
2134           sub = NULL;
2135           break;
2136         }
2137         GST_WARNING_OBJECT (avi,
2138             "Unknown stream header tag %" GST_FOURCC_FORMAT ", ignoring",
2139             GST_FOURCC_ARGS (tag));
2140         /* fall-through */
2141       case GST_RIFF_TAG_JUNQ:
2142       case GST_RIFF_TAG_JUNK:
2143         break;
2144     }
2145     if (sub != NULL) {
2146       gst_buffer_unref (sub);
2147       sub = NULL;
2148     }
2149   }
2150
2151   if (!got_strh) {
2152     GST_WARNING_OBJECT (avi, "Failed to find strh chunk");
2153     goto fail;
2154   }
2155
2156   if (!got_strf) {
2157     GST_WARNING_OBJECT (avi, "Failed to find strf chunk");
2158     goto fail;
2159   }
2160
2161   /* get class to figure out the template */
2162   klass = GST_ELEMENT_GET_CLASS (avi);
2163
2164   /* we now have all info, let´s set up a pad and a caps and be done */
2165   /* create stream name + pad */
2166   switch (stream->strh->type) {
2167     case GST_RIFF_FCC_vids:{
2168       guint32 fourcc;
2169
2170       fourcc = (stream->strf.vids->compression) ?
2171           stream->strf.vids->compression : stream->strh->fcc_handler;
2172       padname = g_strdup_printf ("video_%02d", avi->num_v_streams);
2173       templ = gst_element_class_get_pad_template (klass, "video_%02d");
2174       caps = gst_riff_create_video_caps (fourcc, stream->strh,
2175           stream->strf.vids, stream->extradata, stream->initdata, &codec_name);
2176       if (!caps) {
2177         caps = gst_caps_new_simple ("video/x-avi-unknown", "fourcc",
2178             GST_TYPE_FOURCC, fourcc, NULL);
2179       } else if (got_vprp && vprp) {
2180         guint32 aspect_n, aspect_d;
2181         gint n, d;
2182
2183         aspect_n = vprp->aspect >> 16;
2184         aspect_d = vprp->aspect & 0xffff;
2185         /* calculate the pixel aspect ratio using w/h and aspect ratio */
2186         n = aspect_n * stream->strf.vids->height;
2187         d = aspect_d * stream->strf.vids->width;
2188         if (n && d)
2189           gst_caps_set_simple (caps, "pixel-aspect-ratio", GST_TYPE_FRACTION,
2190               n, d, NULL);
2191         /* very local, not needed elsewhere */
2192         g_free (vprp);
2193         vprp = NULL;
2194       }
2195       tag_name = GST_TAG_VIDEO_CODEC;
2196       avi->num_v_streams++;
2197       break;
2198     }
2199     case GST_RIFF_FCC_auds:{
2200       padname = g_strdup_printf ("audio_%02d", avi->num_a_streams);
2201       templ = gst_element_class_get_pad_template (klass, "audio_%02d");
2202       caps = gst_riff_create_audio_caps (stream->strf.auds->format,
2203           stream->strh, stream->strf.auds, stream->extradata,
2204           stream->initdata, &codec_name);
2205       if (!caps) {
2206         caps = gst_caps_new_simple ("audio/x-avi-unknown", "codec_id",
2207             G_TYPE_INT, stream->strf.auds->format, NULL);
2208       }
2209       tag_name = GST_TAG_AUDIO_CODEC;
2210       avi->num_a_streams++;
2211       break;
2212     }
2213     case GST_RIFF_FCC_iavs:{
2214       guint32 fourcc = stream->strh->fcc_handler;
2215
2216       padname = g_strdup_printf ("video_%02d", avi->num_v_streams);
2217       templ = gst_element_class_get_pad_template (klass, "video_%02d");
2218       caps = gst_riff_create_iavs_caps (fourcc, stream->strh,
2219           stream->strf.iavs, stream->extradata, stream->initdata, &codec_name);
2220       if (!caps) {
2221         caps = gst_caps_new_simple ("video/x-avi-unknown", "fourcc",
2222             GST_TYPE_FOURCC, fourcc, NULL);
2223       }
2224       tag_name = GST_TAG_VIDEO_CODEC;
2225       avi->num_v_streams++;
2226       break;
2227     }
2228     case GST_RIFF_FCC_txts:{
2229       padname = g_strdup_printf ("subtitle_%02d", avi->num_t_streams);
2230       templ = gst_element_class_get_pad_template (klass, "subtitle_%02d");
2231       caps = gst_caps_new_simple ("application/x-subtitle-avi", NULL);
2232       tag_name = NULL;
2233       avi->num_t_streams++;
2234       break;
2235     }
2236     default:
2237       g_return_val_if_reached (FALSE);
2238   }
2239
2240   /* no caps means no stream */
2241   if (!caps) {
2242     GST_ERROR_OBJECT (element, "Did not find caps for stream %s", padname);
2243     goto fail;
2244   }
2245
2246   GST_DEBUG_OBJECT (element, "codec-name=%s",
2247       (codec_name ? codec_name : "NULL"));
2248   GST_DEBUG_OBJECT (element, "caps=%" GST_PTR_FORMAT, caps);
2249
2250   /* set proper settings and add it */
2251   if (stream->pad)
2252     gst_object_unref (stream->pad);
2253   pad = stream->pad = gst_pad_new_from_template (templ, padname);
2254   g_free (padname);
2255
2256   gst_pad_use_fixed_caps (pad);
2257 #if 0
2258   gst_pad_set_formats_function (pad,
2259       GST_DEBUG_FUNCPTR (gst_avi_demux_get_src_formats));
2260   gst_pad_set_event_mask_function (pad,
2261       GST_DEBUG_FUNCPTR (gst_avi_demux_get_event_mask));
2262 #endif
2263   gst_pad_set_event_function (pad,
2264       GST_DEBUG_FUNCPTR (gst_avi_demux_handle_src_event));
2265   gst_pad_set_query_type_function (pad,
2266       GST_DEBUG_FUNCPTR (gst_avi_demux_get_src_query_types));
2267   gst_pad_set_query_function (pad,
2268       GST_DEBUG_FUNCPTR (gst_avi_demux_handle_src_query));
2269 #if 0
2270   gst_pad_set_convert_function (pad,
2271       GST_DEBUG_FUNCPTR (gst_avi_demux_src_convert));
2272 #endif
2273
2274   stream->num = avi->num_streams;
2275
2276   stream->start_entry = 0;
2277   stream->step_entry = 0;
2278   stream->stop_entry = 0;
2279
2280   stream->current_entry = -1;
2281   stream->current_total = 0;
2282
2283   stream->last_flow = GST_FLOW_OK;
2284   stream->discont = TRUE;
2285
2286   stream->total_bytes = 0;
2287   stream->total_blocks = 0;
2288   stream->n_keyframes = 0;
2289
2290   stream->idx_n = 0;
2291   stream->idx_max = 0;
2292
2293   gst_pad_set_element_private (pad, stream);
2294   avi->num_streams++;
2295
2296   gst_pad_set_caps (pad, caps);
2297   gst_pad_set_active (pad, TRUE);
2298   gst_caps_unref (caps);
2299
2300   /* make tags */
2301   if (codec_name) {
2302     if (!stream->taglist)
2303       stream->taglist = gst_tag_list_new ();
2304
2305     avi->got_tags = TRUE;
2306
2307     gst_tag_list_add (stream->taglist, GST_TAG_MERGE_APPEND, tag_name,
2308         codec_name, NULL);
2309     g_free (codec_name);
2310   }
2311
2312   gst_buffer_unref (buf);
2313
2314   return TRUE;
2315
2316   /* ERRORS */
2317 fail:
2318   {
2319     /* unref any mem that may be in use */
2320     if (buf)
2321       gst_buffer_unref (buf);
2322     if (sub)
2323       gst_buffer_unref (sub);
2324     g_free (vprp);
2325     g_free (codec_name);
2326     gst_avi_demux_reset_stream (avi, stream);
2327     avi->num_streams++;
2328     return FALSE;
2329   }
2330 }
2331
2332 /*
2333  * gst_avi_demux_parse_odml:
2334  * @avi: calling element (used for debug/error).
2335  * @buf: input buffer to be used for parsing.
2336  *
2337  * Read an openDML-2.0 extension header. Fills in the frame number
2338  * in the avi demuxer object when reading succeeds.
2339  */
2340 static void
2341 gst_avi_demux_parse_odml (GstAviDemux * avi, GstBuffer * buf)
2342 {
2343   guint32 tag = 0;
2344   guint offset = 4;
2345   GstBuffer *sub = NULL;
2346
2347   while (gst_riff_parse_chunk (GST_ELEMENT_CAST (avi), buf, &offset, &tag,
2348           &sub)) {
2349     switch (tag) {
2350       case GST_RIFF_TAG_dmlh:{
2351         gst_riff_dmlh dmlh, *_dmlh;
2352         gsize size;
2353         guint8 *data;
2354
2355         /* sub == NULL is possible and means an empty buffer */
2356         if (sub == NULL)
2357           goto next;
2358
2359         data = gst_buffer_map (sub, &size, NULL, GST_MAP_READ);
2360
2361         /* check size */
2362         if (size < sizeof (gst_riff_dmlh)) {
2363           GST_ERROR_OBJECT (avi,
2364               "DMLH entry is too small (%d bytes, %d needed)",
2365               size, (int) sizeof (gst_riff_dmlh));
2366           gst_buffer_unmap (sub, data, size);
2367           goto next;
2368         }
2369         _dmlh = (gst_riff_dmlh *) data;
2370         dmlh.totalframes = GST_READ_UINT32_LE (&_dmlh->totalframes);
2371         gst_buffer_unmap (sub, data, size);
2372
2373         GST_INFO_OBJECT (avi, "dmlh tag found: totalframes: %u",
2374             dmlh.totalframes);
2375
2376         avi->avih->tot_frames = dmlh.totalframes;
2377         goto next;
2378       }
2379
2380       default:
2381         GST_WARNING_OBJECT (avi,
2382             "Unknown tag %" GST_FOURCC_FORMAT " in ODML header",
2383             GST_FOURCC_ARGS (tag));
2384         /* fall-through */
2385       case GST_RIFF_TAG_JUNQ:
2386       case GST_RIFF_TAG_JUNK:
2387       next:
2388         /* skip and move to next chunk */
2389         if (sub) {
2390           gst_buffer_unref (sub);
2391           sub = NULL;
2392         }
2393         break;
2394     }
2395   }
2396   if (buf)
2397     gst_buffer_unref (buf);
2398 }
2399
2400 /* Index helper */
2401 static guint
2402 gst_avi_demux_index_last (GstAviDemux * avi, GstAviStream * stream)
2403 {
2404   return stream->idx_n;
2405 }
2406
2407 /* find a previous entry in the index with the given flags */
2408 static guint
2409 gst_avi_demux_index_prev (GstAviDemux * avi, GstAviStream * stream,
2410     guint last, gboolean keyframe)
2411 {
2412   GstAviIndexEntry *entry;
2413   guint i;
2414
2415   for (i = last; i > 0; i--) {
2416     entry = &stream->index[i - 1];
2417     if (!keyframe || ENTRY_IS_KEYFRAME (entry)) {
2418       return i - 1;
2419     }
2420   }
2421   return 0;
2422 }
2423
2424 static guint
2425 gst_avi_demux_index_next (GstAviDemux * avi, GstAviStream * stream,
2426     guint last, gboolean keyframe)
2427 {
2428   GstAviIndexEntry *entry;
2429   gint i;
2430
2431   for (i = last + 1; i < stream->idx_n; i++) {
2432     entry = &stream->index[i];
2433     if (!keyframe || ENTRY_IS_KEYFRAME (entry)) {
2434       return i;
2435     }
2436   }
2437   return stream->idx_n - 1;
2438 }
2439
2440 static guint
2441 gst_avi_demux_index_entry_search (GstAviIndexEntry * entry, guint64 * total)
2442 {
2443   if (entry->total < *total)
2444     return -1;
2445   else if (entry->total > *total)
2446     return 1;
2447   return 0;
2448 }
2449
2450 /*
2451  * gst_avi_demux_index_for_time:
2452  * @avi: Avi object
2453  * @stream: the stream
2454  * @time: a time position
2455  *
2456  * Finds the index entry which time is less or equal than the requested time.
2457  * Try to avoid binary search when we can convert the time to an index
2458  * position directly (for example for video frames with a fixed duration).
2459  *
2460  * Returns: the found position in the index.
2461  */
2462 static guint
2463 gst_avi_demux_index_for_time (GstAviDemux * avi,
2464     GstAviStream * stream, guint64 time)
2465 {
2466   guint index = -1;
2467   guint64 total;
2468
2469   GST_LOG_OBJECT (avi, "search time:%" GST_TIME_FORMAT, GST_TIME_ARGS (time));
2470
2471   /* easy (and common) cases */
2472   if (time == 0 || stream->idx_n == 0)
2473     return 0;
2474   if (time >= stream->idx_duration)
2475     return stream->idx_n - 1;
2476
2477   /* figure out where we need to go. For that we convert the time to an
2478    * index entry or we convert it to a total and then do a binary search. */
2479   if (stream->is_vbr) {
2480     /* VBR stream next timestamp */
2481     if (stream->strh->type == GST_RIFF_FCC_auds) {
2482       total = avi_stream_convert_time_to_frames_unchecked (stream, time);
2483     } else {
2484       index = avi_stream_convert_time_to_frames_unchecked (stream, time);
2485     }
2486   } else {
2487     /* constant rate stream */
2488     total = avi_stream_convert_time_to_bytes_unchecked (stream, time);
2489   }
2490
2491   if (index == -1) {
2492     GstAviIndexEntry *entry;
2493
2494     /* no index, find index with binary search on total */
2495     GST_LOG_OBJECT (avi, "binary search for entry with total %"
2496         G_GUINT64_FORMAT, total);
2497
2498     entry = gst_util_array_binary_search (stream->index,
2499         stream->idx_n, sizeof (GstAviIndexEntry),
2500         (GCompareDataFunc) gst_avi_demux_index_entry_search,
2501         GST_SEARCH_MODE_BEFORE, &total, NULL);
2502
2503     if (entry == NULL) {
2504       GST_LOG_OBJECT (avi, "not found, assume index 0");
2505       index = 0;
2506     } else {
2507       index = entry - stream->index;
2508       GST_LOG_OBJECT (avi, "found at %u", index);
2509     }
2510   } else {
2511     GST_LOG_OBJECT (avi, "converted time to index %u", index);
2512   }
2513
2514   return index;
2515 }
2516
2517 static inline GstAviStream *
2518 gst_avi_demux_stream_for_id (GstAviDemux * avi, guint32 id)
2519 {
2520   guint stream_nr;
2521   GstAviStream *stream;
2522
2523   /* get the stream for this entry */
2524   stream_nr = CHUNKID_TO_STREAMNR (id);
2525   if (G_UNLIKELY (stream_nr >= avi->num_streams)) {
2526     GST_WARNING_OBJECT (avi, "invalid stream nr %d", stream_nr);
2527     return NULL;
2528   }
2529   stream = &avi->stream[stream_nr];
2530   if (G_UNLIKELY (!stream->strh)) {
2531     GST_WARNING_OBJECT (avi, "Unhandled stream %d, skipping", stream_nr);
2532     return NULL;
2533   }
2534   return stream;
2535 }
2536
2537 /*
2538  * gst_avi_demux_parse_index:
2539  * @avi: calling element (used for debugging/errors).
2540  * @buf: buffer containing the full index.
2541  *
2542  * Read index entries from the provided buffer.
2543  * The buffer should contain a GST_RIFF_TAG_idx1 chunk.
2544  */
2545 static gboolean
2546 gst_avi_demux_parse_index (GstAviDemux * avi, GstBuffer * buf)
2547 {
2548   guint8 *data;
2549   gsize size;
2550   guint i, num, n;
2551   gst_riff_index_entry *index;
2552   GstClockTime stamp;
2553   GstAviStream *stream;
2554   GstAviIndexEntry entry;
2555   guint32 id;
2556
2557   if (!buf)
2558     return FALSE;
2559
2560   data = gst_buffer_map (buf, &size, NULL, GST_MAP_READ);
2561
2562   stamp = gst_util_get_timestamp ();
2563
2564   /* see how many items in the index */
2565   num = size / sizeof (gst_riff_index_entry);
2566   if (num == 0)
2567     goto empty_list;
2568
2569   GST_INFO_OBJECT (avi, "Parsing index, nr_entries = %6d", num);
2570
2571   index = (gst_riff_index_entry *) data;
2572
2573   /* figure out if the index is 0 based or relative to the MOVI start */
2574   entry.offset = GST_READ_UINT32_LE (&index[0].offset);
2575   if (entry.offset < avi->offset) {
2576     avi->index_offset = avi->offset + 8;
2577     GST_DEBUG ("index_offset = %" G_GUINT64_FORMAT, avi->index_offset);
2578   } else {
2579     avi->index_offset = 0;
2580     GST_DEBUG ("index is 0 based");
2581   }
2582
2583   for (i = 0, n = 0; i < num; i++) {
2584     id = GST_READ_UINT32_LE (&index[i].id);
2585     entry.offset = GST_READ_UINT32_LE (&index[i].offset);
2586
2587     /* some sanity checks */
2588     if (G_UNLIKELY (id == GST_RIFF_rec || id == 0 ||
2589             (entry.offset == 0 && n > 0)))
2590       continue;
2591
2592     /* get the stream for this entry */
2593     stream = gst_avi_demux_stream_for_id (avi, id);
2594     if (G_UNLIKELY (!stream))
2595       continue;
2596
2597     /* handle offset and size */
2598     entry.offset += avi->index_offset + 8;
2599     entry.size = GST_READ_UINT32_LE (&index[i].size);
2600
2601     /* handle flags */
2602     if (stream->strh->type == GST_RIFF_FCC_auds) {
2603       /* all audio frames are keyframes */
2604       ENTRY_SET_KEYFRAME (&entry);
2605     } else {
2606       guint32 flags;
2607       /* else read flags */
2608       flags = GST_READ_UINT32_LE (&index[i].flags);
2609       if (flags & GST_RIFF_IF_KEYFRAME) {
2610         ENTRY_SET_KEYFRAME (&entry);
2611       } else {
2612         ENTRY_UNSET_KEYFRAME (&entry);
2613       }
2614     }
2615
2616     /* and add */
2617     if (G_UNLIKELY (!gst_avi_demux_add_index (avi, stream, num, &entry)))
2618       goto out_of_mem;
2619
2620     n++;
2621   }
2622   gst_buffer_unmap (buf, data, size);
2623   gst_buffer_unref (buf);
2624
2625   /* get stream stats now */
2626   avi->have_index = gst_avi_demux_do_index_stats (avi);
2627
2628   stamp = gst_util_get_timestamp () - stamp;
2629   GST_DEBUG_OBJECT (avi, "index parsing took %" GST_TIME_FORMAT,
2630       GST_TIME_ARGS (stamp));
2631
2632   return TRUE;
2633
2634   /* ERRORS */
2635 empty_list:
2636   {
2637     GST_DEBUG_OBJECT (avi, "empty index");
2638     gst_buffer_unmap (buf, data, size);
2639     gst_buffer_unref (buf);
2640     return FALSE;
2641   }
2642 out_of_mem:
2643   {
2644     GST_ELEMENT_ERROR (avi, RESOURCE, NO_SPACE_LEFT, (NULL),
2645         ("Cannot allocate memory for %u*%u=%u bytes",
2646             (guint) sizeof (GstAviIndexEntry), num,
2647             (guint) sizeof (GstAviIndexEntry) * num));
2648     gst_buffer_unmap (buf, data, size);
2649     gst_buffer_unref (buf);
2650     return FALSE;
2651   }
2652 }
2653
2654 /*
2655  * gst_avi_demux_stream_index:
2656  * @avi: avi demuxer object.
2657  *
2658  * Seeks to index and reads it.
2659  */
2660 static void
2661 gst_avi_demux_stream_index (GstAviDemux * avi)
2662 {
2663   GstFlowReturn res;
2664   guint64 offset = avi->offset;
2665   GstBuffer *buf;
2666   guint32 tag;
2667   guint32 size;
2668   gsize bsize;
2669   guint8 *bdata;
2670
2671   GST_DEBUG ("demux stream index at offset %" G_GUINT64_FORMAT, offset);
2672
2673   /* get chunk information */
2674   res = gst_pad_pull_range (avi->sinkpad, offset, 8, &buf);
2675   if (res != GST_FLOW_OK)
2676     goto pull_failed;
2677
2678   bdata = gst_buffer_map (buf, &bsize, NULL, GST_MAP_READ);
2679   if (bsize < 8)
2680     goto too_small;
2681
2682   /* check tag first before blindy trying to read 'size' bytes */
2683   tag = GST_READ_UINT32_LE (bdata);
2684   size = GST_READ_UINT32_LE (bdata + 4);
2685   if (tag == GST_RIFF_TAG_LIST) {
2686     /* this is the movi tag */
2687     GST_DEBUG_OBJECT (avi, "skip LIST chunk, size %" G_GUINT32_FORMAT,
2688         (8 + GST_ROUND_UP_2 (size)));
2689     offset += 8 + GST_ROUND_UP_2 (size);
2690     gst_buffer_unmap (buf, bdata, bsize);
2691     gst_buffer_unref (buf);
2692
2693     res = gst_pad_pull_range (avi->sinkpad, offset, 8, &buf);
2694     if (res != GST_FLOW_OK)
2695       goto pull_failed;
2696
2697     bdata = gst_buffer_map (buf, &bsize, NULL, GST_MAP_READ);
2698     if (bsize < 8)
2699       goto too_small;
2700
2701     tag = GST_READ_UINT32_LE (bdata);
2702     size = GST_READ_UINT32_LE (bdata + 4);
2703   }
2704   gst_buffer_unmap (buf, bdata, bsize);
2705   gst_buffer_unref (buf);
2706
2707   if (tag != GST_RIFF_TAG_idx1)
2708     goto no_index;
2709   if (!size)
2710     goto zero_index;
2711
2712   GST_DEBUG ("index found at offset %" G_GUINT64_FORMAT, offset);
2713
2714   /* read chunk, advance offset */
2715   if (gst_riff_read_chunk (GST_ELEMENT_CAST (avi),
2716           avi->sinkpad, &offset, &tag, &buf) != GST_FLOW_OK)
2717     return;
2718
2719   GST_DEBUG ("will parse index chunk size %u for tag %"
2720       GST_FOURCC_FORMAT, gst_buffer_get_size (buf), GST_FOURCC_ARGS (tag));
2721
2722   gst_avi_demux_parse_index (avi, buf);
2723
2724 #ifndef GST_DISABLE_GST_DEBUG
2725   /* debug our indexes */
2726   {
2727     gint i;
2728     GstAviStream *stream;
2729
2730     for (i = 0; i < avi->num_streams; i++) {
2731       stream = &avi->stream[i];
2732       GST_DEBUG_OBJECT (avi, "stream %u: %u frames, %" G_GINT64_FORMAT " bytes",
2733           i, stream->idx_n, stream->total_bytes);
2734     }
2735   }
2736 #endif
2737   return;
2738
2739   /* ERRORS */
2740 pull_failed:
2741   {
2742     GST_DEBUG_OBJECT (avi,
2743         "pull range failed: pos=%" G_GUINT64_FORMAT " size=8", offset);
2744     return;
2745   }
2746 too_small:
2747   {
2748     GST_DEBUG_OBJECT (avi, "Buffer is too small");
2749     gst_buffer_unmap (buf, bdata, bsize);
2750     gst_buffer_unref (buf);
2751     return;
2752   }
2753 no_index:
2754   {
2755     GST_WARNING_OBJECT (avi,
2756         "No index data (idx1) after movi chunk, but %" GST_FOURCC_FORMAT,
2757         GST_FOURCC_ARGS (tag));
2758     return;
2759   }
2760 zero_index:
2761   {
2762     GST_WARNING_OBJECT (avi, "Empty index data (idx1) after movi chunk");
2763     return;
2764   }
2765 }
2766
2767 /*
2768  * gst_avi_demux_stream_index_push:
2769  * @avi: avi demuxer object.
2770  *
2771  * Read index.
2772  */
2773 static void
2774 gst_avi_demux_stream_index_push (GstAviDemux * avi)
2775 {
2776   guint64 offset = avi->idx1_offset;
2777   GstBuffer *buf;
2778   guint32 tag;
2779   guint32 size;
2780
2781   GST_DEBUG ("demux stream index at offset %" G_GUINT64_FORMAT, offset);
2782
2783   /* get chunk information */
2784   if (!gst_avi_demux_peek_chunk (avi, &tag, &size))
2785     return;
2786
2787   /* check tag first before blindly trying to read 'size' bytes */
2788   if (tag == GST_RIFF_TAG_LIST) {
2789     /* this is the movi tag */
2790     GST_DEBUG_OBJECT (avi, "skip LIST chunk, size %" G_GUINT32_FORMAT,
2791         (8 + GST_ROUND_UP_2 (size)));
2792     avi->idx1_offset = offset + 8 + GST_ROUND_UP_2 (size);
2793     /* issue seek to allow chain function to handle it and return! */
2794     perform_seek_to_offset (avi, avi->idx1_offset);
2795     return;
2796   }
2797
2798   if (tag != GST_RIFF_TAG_idx1)
2799     goto no_index;
2800
2801   GST_DEBUG ("index found at offset %" G_GUINT64_FORMAT, offset);
2802
2803   /* flush chunk header */
2804   gst_adapter_flush (avi->adapter, 8);
2805   /* read chunk payload */
2806   buf = gst_adapter_take_buffer (avi->adapter, size);
2807   if (!buf)
2808     goto pull_failed;
2809   /* advance offset */
2810   offset += 8 + GST_ROUND_UP_2 (size);
2811
2812   GST_DEBUG ("will parse index chunk size %u for tag %"
2813       GST_FOURCC_FORMAT, gst_buffer_get_size (buf), GST_FOURCC_ARGS (tag));
2814
2815   avi->offset = avi->first_movi_offset;
2816   gst_avi_demux_parse_index (avi, buf);
2817
2818 #ifndef GST_DISABLE_GST_DEBUG
2819   /* debug our indexes */
2820   {
2821     gint i;
2822     GstAviStream *stream;
2823
2824     for (i = 0; i < avi->num_streams; i++) {
2825       stream = &avi->stream[i];
2826       GST_DEBUG_OBJECT (avi, "stream %u: %u frames, %" G_GINT64_FORMAT " bytes",
2827           i, stream->idx_n, stream->total_bytes);
2828     }
2829   }
2830 #endif
2831   return;
2832
2833   /* ERRORS */
2834 pull_failed:
2835   {
2836     GST_DEBUG_OBJECT (avi,
2837         "taking data from adapter failed: pos=%" G_GUINT64_FORMAT " size=%u",
2838         offset, size);
2839     return;
2840   }
2841 no_index:
2842   {
2843     GST_WARNING_OBJECT (avi,
2844         "No index data (idx1) after movi chunk, but %" GST_FOURCC_FORMAT,
2845         GST_FOURCC_ARGS (tag));
2846     return;
2847   }
2848 }
2849
2850 /*
2851  * gst_avi_demux_peek_tag:
2852  *
2853  * Returns the tag and size of the next chunk
2854  */
2855 static GstFlowReturn
2856 gst_avi_demux_peek_tag (GstAviDemux * avi, guint64 offset, guint32 * tag,
2857     guint * size)
2858 {
2859   GstFlowReturn res = GST_FLOW_OK;
2860   GstBuffer *buf = NULL;
2861   gsize bufsize;
2862   guint8 *bufdata;
2863
2864   res = gst_pad_pull_range (avi->sinkpad, offset, 8, &buf);
2865   if (res != GST_FLOW_OK)
2866     goto pull_failed;
2867
2868   bufdata = gst_buffer_map (buf, &bufsize, NULL, GST_MAP_READ);
2869   if (bufsize != 8)
2870     goto wrong_size;
2871
2872   *tag = GST_READ_UINT32_LE (bufdata);
2873   *size = GST_READ_UINT32_LE (bufdata + 4);
2874
2875   GST_LOG_OBJECT (avi, "Tag[%" GST_FOURCC_FORMAT "] (size:%d) %"
2876       G_GINT64_FORMAT " -- %" G_GINT64_FORMAT, GST_FOURCC_ARGS (*tag),
2877       *size, offset + 8, offset + 8 + (gint64) * size);
2878
2879 done:
2880   gst_buffer_unmap (buf, bufdata, bufsize);
2881   gst_buffer_unref (buf);
2882
2883   return res;
2884
2885   /* ERRORS */
2886 pull_failed:
2887   {
2888     GST_DEBUG_OBJECT (avi, "pull_ranged returned %s", gst_flow_get_name (res));
2889     return res;
2890   }
2891 wrong_size:
2892   {
2893     GST_DEBUG_OBJECT (avi, "got %d bytes which is <> 8 bytes", bufsize);
2894     res = GST_FLOW_ERROR;
2895     goto done;
2896   }
2897 }
2898
2899 /*
2900  * gst_avi_demux_next_data_buffer:
2901  *
2902  * Returns the offset and size of the next buffer
2903  * Position is the position of the buffer (after tag and size)
2904  */
2905 static GstFlowReturn
2906 gst_avi_demux_next_data_buffer (GstAviDemux * avi, guint64 * offset,
2907     guint32 * tag, guint * size)
2908 {
2909   guint64 off = *offset;
2910   guint _size = 0;
2911   GstFlowReturn res;
2912
2913   do {
2914     res = gst_avi_demux_peek_tag (avi, off, tag, &_size);
2915     if (res != GST_FLOW_OK)
2916       break;
2917     if (*tag == GST_RIFF_TAG_LIST || *tag == GST_RIFF_TAG_RIFF)
2918       off += 8 + 4;             /* skip tag + size + subtag */
2919     else {
2920       *offset = off + 8;
2921       *size = _size;
2922       break;
2923     }
2924   } while (TRUE);
2925
2926   return res;
2927 }
2928
2929 /*
2930  * gst_avi_demux_stream_scan:
2931  * @avi: calling element (used for debugging/errors).
2932  *
2933  * Scan the file for all chunks to "create" a new index.
2934  * pull-range based
2935  */
2936 static gboolean
2937 gst_avi_demux_stream_scan (GstAviDemux * avi)
2938 {
2939   GstFlowReturn res;
2940   GstAviStream *stream;
2941   GstFormat format;
2942   guint64 pos = 0;
2943   guint64 length;
2944   gint64 tmplength;
2945   guint32 tag = 0;
2946   guint num;
2947
2948   /* FIXME:
2949    * - implement non-seekable source support.
2950    */
2951   GST_DEBUG_OBJECT (avi, "Creating index");
2952
2953   /* get the size of the file */
2954   format = GST_FORMAT_BYTES;
2955   if (!gst_pad_query_peer_duration (avi->sinkpad, &format, &tmplength))
2956     return FALSE;
2957   length = tmplength;
2958
2959   /* guess the total amount of entries we expect */
2960   num = 16000;
2961
2962   while (TRUE) {
2963     GstAviIndexEntry entry;
2964     guint size = 0;
2965
2966     /* start reading data buffers to find the id and offset */
2967     res = gst_avi_demux_next_data_buffer (avi, &pos, &tag, &size);
2968     if (G_UNLIKELY (res != GST_FLOW_OK))
2969       break;
2970
2971     /* get stream */
2972     stream = gst_avi_demux_stream_for_id (avi, tag);
2973     if (G_UNLIKELY (!stream))
2974       goto next;
2975
2976     /* we can't figure out the keyframes, assume they all are */
2977     entry.flags = GST_AVI_KEYFRAME;
2978     entry.offset = pos;
2979     entry.size = size;
2980
2981     /* and add to the index of this stream */
2982     if (G_UNLIKELY (!gst_avi_demux_add_index (avi, stream, num, &entry)))
2983       goto out_of_mem;
2984
2985   next:
2986     /* update position */
2987     pos += GST_ROUND_UP_2 (size);
2988     if (G_UNLIKELY (pos > length)) {
2989       GST_WARNING_OBJECT (avi,
2990           "Stopping index lookup since we are further than EOF");
2991       break;
2992     }
2993   }
2994
2995   /* collect stats */
2996   avi->have_index = gst_avi_demux_do_index_stats (avi);
2997
2998   return TRUE;
2999
3000   /* ERRORS */
3001 out_of_mem:
3002   {
3003     GST_ELEMENT_ERROR (avi, RESOURCE, NO_SPACE_LEFT, (NULL),
3004         ("Cannot allocate memory for %u*%u=%u bytes",
3005             (guint) sizeof (GstAviIndexEntry), num,
3006             (guint) sizeof (GstAviIndexEntry) * num));
3007     return FALSE;
3008   }
3009 }
3010
3011 static void
3012 gst_avi_demux_calculate_durations_from_index (GstAviDemux * avi)
3013 {
3014   guint i;
3015   GstClockTime total;
3016   GstAviStream *stream;
3017
3018   total = GST_CLOCK_TIME_NONE;
3019
3020   /* all streams start at a timestamp 0 */
3021   for (i = 0; i < avi->num_streams; i++) {
3022     GstClockTime duration, hduration;
3023     gst_riff_strh *strh;
3024
3025     stream = &avi->stream[i];
3026     if (G_UNLIKELY (!stream || !stream->idx_n || !(strh = stream->strh)))
3027       continue;
3028
3029     /* get header duration for the stream */
3030     hduration = stream->hdr_duration;
3031     /* index duration calculated during parsing */
3032     duration = stream->idx_duration;
3033
3034     /* now pick a good duration */
3035     if (GST_CLOCK_TIME_IS_VALID (duration)) {
3036       /* index gave valid duration, use that */
3037       GST_INFO ("Stream %p duration according to index: %" GST_TIME_FORMAT,
3038           stream, GST_TIME_ARGS (duration));
3039     } else {
3040       /* fall back to header info to calculate a duration */
3041       duration = hduration;
3042     }
3043     GST_INFO ("Setting duration of stream #%d to %" GST_TIME_FORMAT,
3044         i, GST_TIME_ARGS (duration));
3045     /* set duration for the stream */
3046     stream->duration = duration;
3047
3048     /* find total duration */
3049     if (total == GST_CLOCK_TIME_NONE ||
3050         (GST_CLOCK_TIME_IS_VALID (duration) && duration > total))
3051       total = duration;
3052   }
3053
3054   if (GST_CLOCK_TIME_IS_VALID (total) && (total > 0)) {
3055     /* now update the duration for those streams where we had none */
3056     for (i = 0; i < avi->num_streams; i++) {
3057       stream = &avi->stream[i];
3058
3059       if (!GST_CLOCK_TIME_IS_VALID (stream->duration)
3060           || stream->duration == 0) {
3061         stream->duration = total;
3062
3063         GST_INFO ("Stream %p duration according to total: %" GST_TIME_FORMAT,
3064             stream, GST_TIME_ARGS (total));
3065       }
3066     }
3067   }
3068
3069   /* and set the total duration in the segment. */
3070   GST_INFO ("Setting total duration to: %" GST_TIME_FORMAT,
3071       GST_TIME_ARGS (total));
3072
3073   gst_segment_set_duration (&avi->segment, GST_FORMAT_TIME, total);
3074 }
3075
3076 /* returns FALSE if there are no pads to deliver event to,
3077  * otherwise TRUE (whatever the outcome of event sending),
3078  * takes ownership of the event. */
3079 static gboolean
3080 gst_avi_demux_push_event (GstAviDemux * avi, GstEvent * event)
3081 {
3082   gboolean result = FALSE;
3083   gint i;
3084
3085   GST_DEBUG_OBJECT (avi, "sending %s event to %d streams",
3086       GST_EVENT_TYPE_NAME (event), avi->num_streams);
3087
3088   for (i = 0; i < avi->num_streams; i++) {
3089     GstAviStream *stream = &avi->stream[i];
3090
3091     if (stream->pad) {
3092       result = TRUE;
3093       gst_pad_push_event (stream->pad, gst_event_ref (event));
3094     }
3095   }
3096   gst_event_unref (event);
3097   return result;
3098 }
3099
3100 static void
3101 gst_avi_demux_check_seekability (GstAviDemux * avi)
3102 {
3103   GstQuery *query;
3104   gboolean seekable = FALSE;
3105   gint64 start = -1, stop = -1;
3106
3107   query = gst_query_new_seeking (GST_FORMAT_BYTES);
3108   if (!gst_pad_peer_query (avi->sinkpad, query)) {
3109     GST_DEBUG_OBJECT (avi, "seeking query failed");
3110     goto done;
3111   }
3112
3113   gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
3114
3115   /* try harder to query upstream size if we didn't get it the first time */
3116   if (seekable && stop == -1) {
3117     GstFormat fmt = GST_FORMAT_BYTES;
3118
3119     GST_DEBUG_OBJECT (avi, "doing duration query to fix up unset stop");
3120     gst_pad_query_peer_duration (avi->sinkpad, &fmt, &stop);
3121   }
3122
3123   /* if upstream doesn't know the size, it's likely that it's not seekable in
3124    * practice even if it technically may be seekable */
3125   if (seekable && (start != 0 || stop <= start)) {
3126     GST_DEBUG_OBJECT (avi, "seekable but unknown start/stop -> disable");
3127     seekable = FALSE;
3128   }
3129
3130 done:
3131   GST_INFO_OBJECT (avi, "seekable: %d (%" G_GUINT64_FORMAT " - %"
3132       G_GUINT64_FORMAT ")", seekable, start, stop);
3133   avi->seekable = seekable;
3134
3135   gst_query_unref (query);
3136 }
3137
3138 /*
3139  * Read AVI headers when streaming
3140  */
3141 static GstFlowReturn
3142 gst_avi_demux_stream_header_push (GstAviDemux * avi)
3143 {
3144   GstFlowReturn ret = GST_FLOW_OK;
3145   guint32 tag = 0;
3146   guint32 ltag = 0;
3147   guint32 size = 0;
3148   const guint8 *data;
3149   GstBuffer *buf = NULL, *sub = NULL;
3150   guint offset = 4;
3151   gint64 stop;
3152   gint i;
3153   GstTagList *tags = NULL;
3154   guint8 fourcc[4];
3155
3156   GST_DEBUG ("Reading and parsing avi headers: %d", avi->header_state);
3157
3158   switch (avi->header_state) {
3159     case GST_AVI_DEMUX_HEADER_TAG_LIST:
3160       if (gst_avi_demux_peek_chunk (avi, &tag, &size)) {
3161         avi->offset += 8 + GST_ROUND_UP_2 (size);
3162         if (tag != GST_RIFF_TAG_LIST)
3163           goto header_no_list;
3164
3165         gst_adapter_flush (avi->adapter, 8);
3166         /* Find the 'hdrl' LIST tag */
3167         GST_DEBUG ("Reading %d bytes", size);
3168         buf = gst_adapter_take_buffer (avi->adapter, size);
3169
3170         gst_buffer_extract (buf, 0, fourcc, 4);
3171
3172         if (GST_READ_UINT32_LE (fourcc) != GST_RIFF_LIST_hdrl)
3173           goto header_no_hdrl;
3174
3175         /* mind padding */
3176         if (size & 1)
3177           gst_adapter_flush (avi->adapter, 1);
3178
3179         GST_DEBUG ("'hdrl' LIST tag found. Parsing next chunk");
3180
3181         gst_avi_demux_roundup_list (avi, &buf);
3182
3183         /* the hdrl starts with a 'avih' header */
3184         if (!gst_riff_parse_chunk (GST_ELEMENT_CAST (avi), buf, &offset, &tag,
3185                 &sub))
3186           goto header_no_avih;
3187
3188         if (tag != GST_RIFF_TAG_avih)
3189           goto header_no_avih;
3190
3191         if (!gst_avi_demux_parse_avih (avi, sub, &avi->avih))
3192           goto header_wrong_avih;
3193
3194         GST_DEBUG_OBJECT (avi, "AVI header ok, reading elemnts from header");
3195
3196         /* now, read the elements from the header until the end */
3197         while (gst_riff_parse_chunk (GST_ELEMENT_CAST (avi), buf, &offset, &tag,
3198                 &sub)) {
3199           /* sub can be NULL on empty tags */
3200           if (!sub)
3201             continue;
3202
3203           switch (tag) {
3204             case GST_RIFF_TAG_LIST:
3205               if (gst_buffer_get_size (sub) < 4)
3206                 goto next;
3207
3208               gst_buffer_extract (sub, 0, fourcc, 4);
3209
3210               switch (GST_READ_UINT32_LE (fourcc)) {
3211                 case GST_RIFF_LIST_strl:
3212                   if (!(gst_avi_demux_parse_stream (avi, sub))) {
3213                     sub = NULL;
3214                     GST_ELEMENT_WARNING (avi, STREAM, DEMUX, (NULL),
3215                         ("failed to parse stream, ignoring"));
3216                     goto next;
3217                   }
3218                   sub = NULL;
3219                   goto next;
3220                 case GST_RIFF_LIST_odml:
3221                   gst_avi_demux_parse_odml (avi, sub);
3222                   sub = NULL;
3223                   break;
3224                 default:
3225                   GST_WARNING_OBJECT (avi,
3226                       "Unknown list %" GST_FOURCC_FORMAT " in AVI header",
3227                       GST_FOURCC_ARGS (GST_READ_UINT32_LE (fourcc)));
3228                   /* fall-through */
3229                 case GST_RIFF_TAG_JUNQ:
3230                 case GST_RIFF_TAG_JUNK:
3231                   goto next;
3232                   break;
3233               }
3234             case GST_RIFF_IDIT:
3235               gst_avi_demux_parse_idit (avi, sub);
3236               goto next;
3237             default:
3238               GST_WARNING_OBJECT (avi,
3239                   "Unknown off %d tag %" GST_FOURCC_FORMAT " in AVI header",
3240                   offset, GST_FOURCC_ARGS (tag));
3241               /* fall-through */
3242             case GST_RIFF_TAG_JUNQ:
3243             case GST_RIFF_TAG_JUNK:
3244             next:
3245               /* move to next chunk */
3246               if (sub)
3247                 gst_buffer_unref (sub);
3248               sub = NULL;
3249               break;
3250           }
3251         }
3252         gst_buffer_unref (buf);
3253         GST_DEBUG ("elements parsed");
3254
3255         /* check parsed streams */
3256         if (avi->num_streams == 0) {
3257           goto no_streams;
3258         } else if (avi->num_streams != avi->avih->streams) {
3259           GST_WARNING_OBJECT (avi,
3260               "Stream header mentioned %d streams, but %d available",
3261               avi->avih->streams, avi->num_streams);
3262         }
3263         GST_DEBUG ("Get junk and info next");
3264         avi->header_state = GST_AVI_DEMUX_HEADER_INFO;
3265       } else {
3266         /* Need more data */
3267         return ret;
3268       }
3269       /* fall-though */
3270     case GST_AVI_DEMUX_HEADER_INFO:
3271       GST_DEBUG_OBJECT (avi, "skipping junk between header and data ...");
3272       while (TRUE) {
3273         if (gst_adapter_available (avi->adapter) < 12)
3274           return GST_FLOW_OK;
3275
3276         data = gst_adapter_map (avi->adapter, 12);
3277         tag = GST_READ_UINT32_LE (data);
3278         size = GST_READ_UINT32_LE (data + 4);
3279         ltag = GST_READ_UINT32_LE (data + 8);
3280         gst_adapter_unmap (avi->adapter, 0);
3281
3282         if (tag == GST_RIFF_TAG_LIST) {
3283           switch (ltag) {
3284             case GST_RIFF_LIST_movi:
3285               gst_adapter_flush (avi->adapter, 12);
3286               if (!avi->first_movi_offset)
3287                 avi->first_movi_offset = avi->offset;
3288               avi->offset += 12;
3289               avi->idx1_offset = avi->offset + size - 4;
3290               goto skipping_done;
3291             case GST_RIFF_LIST_INFO:
3292               GST_DEBUG ("Found INFO chunk");
3293               if (gst_avi_demux_peek_chunk (avi, &tag, &size)) {
3294                 GST_DEBUG ("got size %d", size);
3295                 avi->offset += 12;
3296                 gst_adapter_flush (avi->adapter, 12);
3297                 if (size > 4) {
3298                   buf = gst_adapter_take_buffer (avi->adapter, size - 4);
3299                   /* mind padding */
3300                   if (size & 1)
3301                     gst_adapter_flush (avi->adapter, 1);
3302                   gst_riff_parse_info (GST_ELEMENT_CAST (avi), buf, &tags);
3303                   if (tags) {
3304                     if (avi->globaltags) {
3305                       gst_tag_list_insert (avi->globaltags, tags,
3306                           GST_TAG_MERGE_REPLACE);
3307                     } else {
3308                       avi->globaltags = tags;
3309                     }
3310                   }
3311                   tags = NULL;
3312                   gst_buffer_unref (buf);
3313
3314                   avi->offset += GST_ROUND_UP_2 (size) - 4;
3315                 } else {
3316                   GST_DEBUG ("skipping INFO LIST prefix");
3317                 }
3318               } else {
3319                 /* Need more data */
3320                 return GST_FLOW_OK;
3321               }
3322               break;
3323             default:
3324               if (gst_avi_demux_peek_chunk (avi, &tag, &size)) {
3325                 avi->offset += 8 + GST_ROUND_UP_2 (size);
3326                 gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
3327                 // ??? goto iterate; ???
3328               } else {
3329                 /* Need more data */
3330                 return GST_FLOW_OK;
3331               }
3332               break;
3333           }
3334         } else {
3335           if (gst_avi_demux_peek_chunk (avi, &tag, &size)) {
3336             avi->offset += 8 + GST_ROUND_UP_2 (size);
3337             gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
3338             //goto iterate;
3339           } else {
3340             /* Need more data */
3341             return GST_FLOW_OK;
3342           }
3343         }
3344       }
3345       break;
3346     default:
3347       GST_WARNING ("unhandled header state: %d", avi->header_state);
3348       break;
3349   }
3350 skipping_done:
3351
3352   GST_DEBUG_OBJECT (avi, "skipping done ... (streams=%u, stream[0].indexes=%p)",
3353       avi->num_streams, avi->stream[0].indexes);
3354
3355   GST_DEBUG ("Found movi chunk. Starting to stream data");
3356   avi->state = GST_AVI_DEMUX_MOVI;
3357
3358   /* no indexes in push mode, but it still sets some variables */
3359   gst_avi_demux_calculate_durations_from_index (avi);
3360
3361   gst_avi_demux_expose_streams (avi, TRUE);
3362
3363   /* prepare all streams for index 0 */
3364   for (i = 0; i < avi->num_streams; i++)
3365     avi->stream[i].current_entry = 0;
3366
3367   /* create initial NEWSEGMENT event */
3368   if ((stop = avi->segment.stop) == GST_CLOCK_TIME_NONE)
3369     stop = avi->segment.duration;
3370
3371   GST_DEBUG_OBJECT (avi, "segment stop %" G_GINT64_FORMAT, stop);
3372
3373   if (avi->seg_event)
3374     gst_event_unref (avi->seg_event);
3375   avi->seg_event = gst_event_new_new_segment_full
3376       (FALSE, avi->segment.rate, avi->segment.applied_rate, GST_FORMAT_TIME,
3377       avi->segment.start, stop, avi->segment.time);
3378
3379   gst_avi_demux_check_seekability (avi);
3380
3381   /* at this point we know all the streams and we can signal the no more
3382    * pads signal */
3383   GST_DEBUG_OBJECT (avi, "signaling no more pads");
3384   gst_element_no_more_pads (GST_ELEMENT_CAST (avi));
3385
3386   return GST_FLOW_OK;
3387
3388   /* ERRORS */
3389 no_streams:
3390   {
3391     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("No streams found"));
3392     return GST_FLOW_ERROR;
3393   }
3394 header_no_list:
3395   {
3396     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3397         ("Invalid AVI header (no LIST at start): %"
3398             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3399     return GST_FLOW_ERROR;
3400   }
3401 header_no_hdrl:
3402   {
3403     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3404         ("Invalid AVI header (no hdrl at start): %"
3405             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3406     gst_buffer_unref (buf);
3407     return GST_FLOW_ERROR;
3408   }
3409 header_no_avih:
3410   {
3411     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3412         ("Invalid AVI header (no avih at start): %"
3413             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3414     if (sub)
3415       gst_buffer_unref (sub);
3416
3417     gst_buffer_unref (buf);
3418     return GST_FLOW_ERROR;
3419   }
3420 header_wrong_avih:
3421   {
3422     gst_buffer_unref (buf);
3423     return GST_FLOW_ERROR;
3424   }
3425 }
3426
3427 static void
3428 gst_avi_demux_add_date_tag (GstAviDemux * avi, gint y, gint m, gint d,
3429     gint h, gint min, gint s)
3430 {
3431   GDate *date;
3432   GstDateTime *dt;
3433
3434   date = g_date_new_dmy (d, m, y);
3435   if (!g_date_valid (date)) {
3436     /* bogus date */
3437     GST_WARNING_OBJECT (avi, "Refusing to add invalid date %d-%d-%d", y, m, d);
3438     g_date_free (date);
3439     return;
3440   }
3441
3442   dt = gst_date_time_new_local_time (y, m, d, h, min, s);
3443
3444   if (avi->globaltags == NULL)
3445     avi->globaltags = gst_tag_list_new ();
3446
3447   gst_tag_list_add (avi->globaltags, GST_TAG_MERGE_REPLACE, GST_TAG_DATE, date,
3448       NULL);
3449   g_date_free (date);
3450   if (dt) {
3451     gst_tag_list_add (avi->globaltags, GST_TAG_MERGE_REPLACE, GST_TAG_DATE_TIME,
3452         dt, NULL);
3453     gst_date_time_unref (dt);
3454   }
3455 }
3456
3457 static void
3458 gst_avi_demux_parse_idit_nums_only (GstAviDemux * avi, gchar * data)
3459 {
3460   gint y, m, d;
3461   gint hr = 0, min = 0, sec = 0;
3462   gint ret;
3463
3464   GST_DEBUG ("data : '%s'", data);
3465
3466   ret = sscanf (data, "%d:%d:%d %d:%d:%d", &y, &m, &d, &hr, &min, &sec);
3467   if (ret < 3) {
3468     /* Attempt YYYY/MM/DD/ HH:MM variant (found in CASIO cameras) */
3469     ret = sscanf (data, "%04d/%02d/%02d/ %d:%d", &y, &m, &d, &hr, &min);
3470     if (ret < 3) {
3471       GST_WARNING_OBJECT (avi, "Failed to parse IDIT tag");
3472       return;
3473     }
3474   }
3475   gst_avi_demux_add_date_tag (avi, y, m, d, hr, min, sec);
3476 }
3477
3478 static gint
3479 get_month_num (gchar * data, guint size)
3480 {
3481   if (g_ascii_strncasecmp (data, "jan", 3) == 0) {
3482     return 1;
3483   } else if (g_ascii_strncasecmp (data, "feb", 3) == 0) {
3484     return 2;
3485   } else if (g_ascii_strncasecmp (data, "mar", 3) == 0) {
3486     return 3;
3487   } else if (g_ascii_strncasecmp (data, "apr", 3) == 0) {
3488     return 4;
3489   } else if (g_ascii_strncasecmp (data, "may", 3) == 0) {
3490     return 5;
3491   } else if (g_ascii_strncasecmp (data, "jun", 3) == 0) {
3492     return 6;
3493   } else if (g_ascii_strncasecmp (data, "jul", 3) == 0) {
3494     return 7;
3495   } else if (g_ascii_strncasecmp (data, "aug", 3) == 0) {
3496     return 8;
3497   } else if (g_ascii_strncasecmp (data, "sep", 3) == 0) {
3498     return 9;
3499   } else if (g_ascii_strncasecmp (data, "oct", 3) == 0) {
3500     return 10;
3501   } else if (g_ascii_strncasecmp (data, "nov", 3) == 0) {
3502     return 11;
3503   } else if (g_ascii_strncasecmp (data, "dec", 3) == 0) {
3504     return 12;
3505   }
3506
3507   return 0;
3508 }
3509
3510 static void
3511 gst_avi_demux_parse_idit_text (GstAviDemux * avi, gchar * data)
3512 {
3513   gint year, month, day;
3514   gint hour, min, sec;
3515   gint ret;
3516   gchar weekday[4];
3517   gchar monthstr[4];
3518
3519   ret = sscanf (data, "%3s %3s %d %d:%d:%d %d", weekday, monthstr, &day, &hour,
3520       &min, &sec, &year);
3521   if (ret != 7) {
3522     GST_WARNING_OBJECT (avi, "Failed to parse IDIT tag");
3523     return;
3524   }
3525   month = get_month_num (monthstr, strlen (monthstr));
3526   gst_avi_demux_add_date_tag (avi, year, month, day, hour, min, sec);
3527 }
3528
3529 static void
3530 gst_avi_demux_parse_idit (GstAviDemux * avi, GstBuffer * buf)
3531 {
3532   gchar *data, *ptr;
3533   gsize size, left;
3534   gchar *safedata = NULL;
3535
3536   data = gst_buffer_map (buf, &size, NULL, GST_MAP_READ);
3537   /*
3538    * According to:
3539    * http://www.eden-foundation.org/products/code/film_date_stamp/index.html
3540    *
3541    * This tag could be in one of the below formats
3542    * 2005:08:17 11:42:43
3543    * THU OCT 26 16:46:04 2006
3544    * Mon Mar  3 09:44:56 2008
3545    *
3546    * FIXME: Our date tag doesn't include hours
3547    */
3548
3549   /* skip eventual initial whitespace */
3550   ptr = data;
3551   left = size;
3552
3553   while (left > 0 && g_ascii_isspace (ptr[0])) {
3554     ptr++;
3555     left--;
3556   }
3557
3558   if (left == 0) {
3559     goto non_parsable;
3560   }
3561
3562   /* make a safe copy to add a \0 to the end of the string */
3563   safedata = g_strndup (ptr, left);
3564
3565   /* test if the first char is a alpha or a number */
3566   if (g_ascii_isdigit (ptr[0])) {
3567     gst_avi_demux_parse_idit_nums_only (avi, safedata);
3568     g_free (safedata);
3569     return;
3570   } else if (g_ascii_isalpha (ptr[0])) {
3571     gst_avi_demux_parse_idit_text (avi, safedata);
3572     g_free (safedata);
3573     return;
3574   }
3575
3576   g_free (safedata);
3577
3578 non_parsable:
3579   GST_WARNING_OBJECT (avi, "IDIT tag has no parsable info");
3580   gst_buffer_unmap (buf, data, size);
3581 }
3582
3583 /*
3584  * Read full AVI headers.
3585  */
3586 static GstFlowReturn
3587 gst_avi_demux_stream_header_pull (GstAviDemux * avi)
3588 {
3589   GstFlowReturn res;
3590   GstBuffer *buf, *sub = NULL;
3591   guint32 tag;
3592   guint offset = 4;
3593   gint64 stop;
3594   GstElement *element = GST_ELEMENT_CAST (avi);
3595   GstClockTime stamp;
3596   GstTagList *tags = NULL;
3597   guint8 fourcc[4];
3598
3599   stamp = gst_util_get_timestamp ();
3600
3601   /* the header consists of a 'hdrl' LIST tag */
3602   res = gst_riff_read_chunk (element, avi->sinkpad, &avi->offset, &tag, &buf);
3603   if (res != GST_FLOW_OK)
3604     goto pull_range_failed;
3605   else if (tag != GST_RIFF_TAG_LIST)
3606     goto no_list;
3607   else if (gst_buffer_get_size (buf) < 4)
3608     goto no_header;
3609
3610   GST_DEBUG_OBJECT (avi, "parsing headers");
3611
3612   /* Find the 'hdrl' LIST tag */
3613   gst_buffer_extract (buf, 0, fourcc, 4);
3614   while (GST_READ_UINT32_LE (fourcc) != GST_RIFF_LIST_hdrl) {
3615     GST_LOG_OBJECT (avi, "buffer contains %" GST_FOURCC_FORMAT,
3616         GST_FOURCC_ARGS (GST_READ_UINT32_LE (fourcc)));
3617
3618     /* Eat up */
3619     gst_buffer_unref (buf);
3620
3621     /* read new chunk */
3622     res = gst_riff_read_chunk (element, avi->sinkpad, &avi->offset, &tag, &buf);
3623     if (res != GST_FLOW_OK)
3624       goto pull_range_failed;
3625     else if (tag != GST_RIFF_TAG_LIST)
3626       goto no_list;
3627     else if (gst_buffer_get_size (buf) < 4)
3628       goto no_header;
3629     gst_buffer_extract (buf, 0, fourcc, 4);
3630   }
3631
3632   GST_DEBUG_OBJECT (avi, "hdrl LIST tag found");
3633
3634   gst_avi_demux_roundup_list (avi, &buf);
3635
3636   /* the hdrl starts with a 'avih' header */
3637   if (!gst_riff_parse_chunk (element, buf, &offset, &tag, &sub))
3638     goto no_avih;
3639   else if (tag != GST_RIFF_TAG_avih)
3640     goto no_avih;
3641   else if (!gst_avi_demux_parse_avih (avi, sub, &avi->avih))
3642     goto invalid_avih;
3643
3644   GST_DEBUG_OBJECT (avi, "AVI header ok, reading elements from header");
3645
3646   /* now, read the elements from the header until the end */
3647   while (gst_riff_parse_chunk (element, buf, &offset, &tag, &sub)) {
3648     gsize size;
3649     guint8 *data;
3650
3651     /* sub can be NULL on empty tags */
3652     if (!sub)
3653       continue;
3654
3655     data = gst_buffer_map (sub, &size, NULL, GST_MAP_READ);
3656
3657     switch (tag) {
3658       case GST_RIFF_TAG_LIST:
3659         if (size < 4)
3660           goto next;
3661
3662         switch (GST_READ_UINT32_LE (data)) {
3663           case GST_RIFF_LIST_strl:
3664             if (!(gst_avi_demux_parse_stream (avi, sub))) {
3665               GST_ELEMENT_WARNING (avi, STREAM, DEMUX, (NULL),
3666                   ("failed to parse stream, ignoring"));
3667               sub = NULL;
3668             }
3669             sub = NULL;
3670             goto next;
3671           case GST_RIFF_LIST_odml:
3672             gst_avi_demux_parse_odml (avi, sub);
3673             sub = NULL;
3674             break;
3675           case GST_RIFF_LIST_INFO:
3676             gst_buffer_resize (sub, 4, -1);
3677             gst_riff_parse_info (element, sub, &tags);
3678             if (tags) {
3679               if (avi->globaltags) {
3680                 gst_tag_list_insert (avi->globaltags, tags,
3681                     GST_TAG_MERGE_REPLACE);
3682               } else {
3683                 avi->globaltags = tags;
3684               }
3685             }
3686             tags = NULL;
3687             break;
3688           default:
3689             GST_WARNING_OBJECT (avi,
3690                 "Unknown list %" GST_FOURCC_FORMAT " in AVI header",
3691                 GST_FOURCC_ARGS (GST_READ_UINT32_LE (data)));
3692             GST_MEMDUMP_OBJECT (avi, "Unknown list", data, size);
3693             /* fall-through */
3694           case GST_RIFF_TAG_JUNQ:
3695           case GST_RIFF_TAG_JUNK:
3696             goto next;
3697         }
3698         break;
3699       case GST_RIFF_IDIT:
3700         gst_avi_demux_parse_idit (avi, sub);
3701         goto next;
3702       default:
3703         GST_WARNING_OBJECT (avi,
3704             "Unknown tag %" GST_FOURCC_FORMAT " in AVI header at off %d",
3705             GST_FOURCC_ARGS (tag), offset);
3706         GST_MEMDUMP_OBJECT (avi, "Unknown tag", data, size);
3707         /* fall-through */
3708       case GST_RIFF_TAG_JUNQ:
3709       case GST_RIFF_TAG_JUNK:
3710       next:
3711         if (sub) {
3712           gst_buffer_unmap (sub, data, size);
3713           gst_buffer_unref (sub);
3714         }
3715         sub = NULL;
3716         break;
3717     }
3718   }
3719   gst_buffer_unref (buf);
3720   GST_DEBUG ("elements parsed");
3721
3722   /* check parsed streams */
3723   if (avi->num_streams == 0)
3724     goto no_streams;
3725   else if (avi->num_streams != avi->avih->streams) {
3726     GST_WARNING_OBJECT (avi,
3727         "Stream header mentioned %d streams, but %d available",
3728         avi->avih->streams, avi->num_streams);
3729   }
3730
3731   GST_DEBUG_OBJECT (avi, "skipping junk between header and data, offset=%"
3732       G_GUINT64_FORMAT, avi->offset);
3733
3734   /* Now, find the data (i.e. skip all junk between header and data) */
3735   do {
3736     guint size;
3737     gsize bsize;
3738     guint8 *data;
3739     guint32 tag, ltag;
3740
3741     res = gst_pad_pull_range (avi->sinkpad, avi->offset, 12, &buf);
3742     if (res != GST_FLOW_OK) {
3743       GST_DEBUG_OBJECT (avi, "pull_range failure while looking for tags");
3744       goto pull_range_failed;
3745     } else if (gst_buffer_get_size (buf) < 12) {
3746       GST_DEBUG_OBJECT (avi, "got %d bytes which is less than 12 bytes",
3747           gst_buffer_get_size (buf));
3748       gst_buffer_unref (buf);
3749       return GST_FLOW_ERROR;
3750     }
3751
3752     data = gst_buffer_map (buf, &bsize, NULL, GST_MAP_READ);
3753     tag = GST_READ_UINT32_LE (data);
3754     size = GST_READ_UINT32_LE (data + 4);
3755     ltag = GST_READ_UINT32_LE (data + 8);
3756
3757     GST_DEBUG ("tag %" GST_FOURCC_FORMAT ", size %u",
3758         GST_FOURCC_ARGS (tag), size);
3759     GST_MEMDUMP ("Tag content", data, bsize);
3760     gst_buffer_unmap (buf, data, bsize);
3761     gst_buffer_unref (buf);
3762
3763     switch (tag) {
3764       case GST_RIFF_TAG_LIST:{
3765         switch (ltag) {
3766           case GST_RIFF_LIST_movi:
3767             GST_DEBUG_OBJECT (avi,
3768                 "Reached the 'movi' tag, we're done with skipping");
3769             goto skipping_done;
3770           case GST_RIFF_LIST_INFO:
3771             res =
3772                 gst_riff_read_chunk (element, avi->sinkpad, &avi->offset, &tag,
3773                 &buf);
3774             if (res != GST_FLOW_OK) {
3775               GST_DEBUG_OBJECT (avi, "couldn't read INFO chunk");
3776               goto pull_range_failed;
3777             }
3778             GST_DEBUG ("got size %u", gst_buffer_get_size (buf));
3779             if (size < 4) {
3780               GST_DEBUG ("skipping INFO LIST prefix");
3781               avi->offset += (4 - GST_ROUND_UP_2 (size));
3782               gst_buffer_unref (buf);
3783               continue;
3784             }
3785
3786             sub = gst_buffer_copy_region (buf, GST_BUFFER_COPY_ALL, 4, -1);
3787             gst_riff_parse_info (element, sub, &tags);
3788             if (tags) {
3789               if (avi->globaltags) {
3790                 gst_tag_list_insert (avi->globaltags, tags,
3791                     GST_TAG_MERGE_REPLACE);
3792               } else {
3793                 avi->globaltags = tags;
3794               }
3795             }
3796             tags = NULL;
3797             if (sub) {
3798               gst_buffer_unref (sub);
3799               sub = NULL;
3800             }
3801             gst_buffer_unref (buf);
3802             /* gst_riff_read_chunk() has already advanced avi->offset */
3803             break;
3804           default:
3805             GST_WARNING_OBJECT (avi,
3806                 "Skipping unknown list tag %" GST_FOURCC_FORMAT,
3807                 GST_FOURCC_ARGS (ltag));
3808             avi->offset += 8 + GST_ROUND_UP_2 (size);
3809             break;
3810         }
3811       }
3812         break;
3813       default:
3814         GST_WARNING_OBJECT (avi, "Skipping unknown tag %" GST_FOURCC_FORMAT,
3815             GST_FOURCC_ARGS (tag));
3816         /* Fall-through */
3817       case GST_MAKE_FOURCC ('J', 'U', 'N', 'Q'):
3818       case GST_MAKE_FOURCC ('J', 'U', 'N', 'K'):
3819         /* Only get buffer for debugging if the memdump is needed  */
3820         if (gst_debug_category_get_threshold (GST_CAT_DEFAULT) >= 9) {
3821           res = gst_pad_pull_range (avi->sinkpad, avi->offset, size, &buf);
3822           if (res != GST_FLOW_OK) {
3823             GST_DEBUG_OBJECT (avi, "couldn't read INFO chunk");
3824             goto pull_range_failed;
3825           }
3826           data = gst_buffer_map (buf, &bsize, NULL, GST_MAP_READ);
3827           GST_MEMDUMP ("Junk", data, bsize);
3828           gst_buffer_unmap (buf, data, bsize);
3829           gst_buffer_unref (buf);
3830         }
3831         avi->offset += 8 + GST_ROUND_UP_2 (size);
3832         break;
3833     }
3834   } while (1);
3835 skipping_done:
3836
3837   GST_DEBUG_OBJECT (avi, "skipping done ... (streams=%u, stream[0].indexes=%p)",
3838       avi->num_streams, avi->stream[0].indexes);
3839
3840   /* create or read stream index (for seeking) */
3841   if (avi->stream[0].indexes != NULL) {
3842     /* we read a super index already (gst_avi_demux_parse_superindex() ) */
3843     gst_avi_demux_read_subindexes_pull (avi);
3844   }
3845   if (!avi->have_index) {
3846     if (avi->avih->flags & GST_RIFF_AVIH_HASINDEX)
3847       gst_avi_demux_stream_index (avi);
3848
3849     /* still no index, scan */
3850     if (!avi->have_index) {
3851       gst_avi_demux_stream_scan (avi);
3852
3853       /* still no index.. this is a fatal error for now.
3854        * FIXME, we should switch to plain push mode without seeking
3855        * instead of failing. */
3856       if (!avi->have_index)
3857         goto no_index;
3858     }
3859   }
3860   /* use the indexes now to construct nice durations */
3861   gst_avi_demux_calculate_durations_from_index (avi);
3862
3863   gst_avi_demux_expose_streams (avi, FALSE);
3864
3865   /* create initial NEWSEGMENT event */
3866   if ((stop = avi->segment.stop) == GST_CLOCK_TIME_NONE)
3867     stop = avi->segment.duration;
3868
3869   GST_DEBUG_OBJECT (avi, "segment stop %" G_GINT64_FORMAT, stop);
3870
3871   /* do initial seek to the default segment values */
3872   gst_avi_demux_do_seek (avi, &avi->segment);
3873
3874   /* prepare initial segment */
3875   if (avi->seg_event)
3876     gst_event_unref (avi->seg_event);
3877   avi->seg_event = gst_event_new_new_segment_full
3878       (FALSE, avi->segment.rate, avi->segment.applied_rate, GST_FORMAT_TIME,
3879       avi->segment.start, stop, avi->segment.time);
3880
3881   stamp = gst_util_get_timestamp () - stamp;
3882   GST_DEBUG_OBJECT (avi, "pulling header took %" GST_TIME_FORMAT,
3883       GST_TIME_ARGS (stamp));
3884
3885   /* at this point we know all the streams and we can signal the no more
3886    * pads signal */
3887   GST_DEBUG_OBJECT (avi, "signaling no more pads");
3888   gst_element_no_more_pads (GST_ELEMENT_CAST (avi));
3889
3890   return GST_FLOW_OK;
3891
3892   /* ERRORS */
3893 no_list:
3894   {
3895     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3896         ("Invalid AVI header (no LIST at start): %"
3897             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3898     gst_buffer_unref (buf);
3899     return GST_FLOW_ERROR;
3900   }
3901 no_header:
3902   {
3903     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3904         ("Invalid AVI header (no hdrl at start): %"
3905             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3906     gst_buffer_unref (buf);
3907     return GST_FLOW_ERROR;
3908   }
3909 no_avih:
3910   {
3911     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3912         ("Invalid AVI header (no avih at start): %"
3913             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3914     if (sub)
3915       gst_buffer_unref (sub);
3916     gst_buffer_unref (buf);
3917     return GST_FLOW_ERROR;
3918   }
3919 invalid_avih:
3920   {
3921     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3922         ("Invalid AVI header (cannot parse avih at start)"));
3923     gst_buffer_unref (buf);
3924     return GST_FLOW_ERROR;
3925   }
3926 no_streams:
3927   {
3928     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("No streams found"));
3929     return GST_FLOW_ERROR;
3930   }
3931 no_index:
3932   {
3933     GST_WARNING ("file without or too big index");
3934     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3935         ("Could not get/create index"));
3936     return GST_FLOW_ERROR;
3937   }
3938 pull_range_failed:
3939   {
3940     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3941         ("pull_range flow reading header: %s", gst_flow_get_name (res)));
3942     return GST_FLOW_ERROR;
3943   }
3944 }
3945
3946 /* move a stream to @index */
3947 static void
3948 gst_avi_demux_move_stream (GstAviDemux * avi, GstAviStream * stream,
3949     GstSegment * segment, guint index)
3950 {
3951   GST_DEBUG_OBJECT (avi, "Move stream %d to %u", stream->num, index);
3952
3953   if (segment->rate < 0.0) {
3954     guint next_key;
3955     /* Because we don't know the frame order we need to push from the prev keyframe
3956      * to the next keyframe. If there is a smart decoder downstream he will notice
3957      * that there are too many encoded frames send and return UNEXPECTED when there
3958      * are enough decoded frames to fill the segment. */
3959     next_key = gst_avi_demux_index_next (avi, stream, index, TRUE);
3960
3961     /* FIXME, we go back to 0, we should look at segment.start. We will however
3962      * stop earlier when the see the timestamp < segment.start */
3963     stream->start_entry = 0;
3964     stream->step_entry = index;
3965     stream->current_entry = index;
3966     stream->stop_entry = next_key;
3967
3968     GST_DEBUG_OBJECT (avi, "reverse seek: start %u, step %u, stop %u",
3969         stream->start_entry, stream->step_entry, stream->stop_entry);
3970   } else {
3971     stream->start_entry = index;
3972     stream->step_entry = index;
3973     stream->stop_entry = gst_avi_demux_index_last (avi, stream);
3974   }
3975   if (stream->current_entry != index) {
3976     GST_DEBUG_OBJECT (avi, "Move DISCONT from %u to %u",
3977         stream->current_entry, index);
3978     stream->current_entry = index;
3979     stream->discont = TRUE;
3980   }
3981
3982   /* update the buffer info */
3983   gst_avi_demux_get_buffer_info (avi, stream, index,
3984       &stream->current_timestamp, &stream->current_ts_end,
3985       &stream->current_offset, &stream->current_offset_end);
3986
3987   GST_DEBUG_OBJECT (avi, "Moved to %u, ts %" GST_TIME_FORMAT
3988       ", ts_end %" GST_TIME_FORMAT ", off %" G_GUINT64_FORMAT
3989       ", off_end %" G_GUINT64_FORMAT, index,
3990       GST_TIME_ARGS (stream->current_timestamp),
3991       GST_TIME_ARGS (stream->current_ts_end), stream->current_offset,
3992       stream->current_offset_end);
3993
3994   GST_DEBUG_OBJECT (avi, "Seeking to offset %" G_GUINT64_FORMAT,
3995       stream->index[index].offset);
3996 }
3997
3998 /*
3999  * Do the actual seeking.
4000  */
4001 static gboolean
4002 gst_avi_demux_do_seek (GstAviDemux * avi, GstSegment * segment)
4003 {
4004   GstClockTime seek_time;
4005   gboolean keyframe;
4006   guint i, index;
4007   GstAviStream *stream;
4008
4009   seek_time = segment->last_stop;
4010   keyframe = !!(segment->flags & GST_SEEK_FLAG_KEY_UNIT);
4011
4012   GST_DEBUG_OBJECT (avi, "seek to: %" GST_TIME_FORMAT
4013       " keyframe seeking:%d", GST_TIME_ARGS (seek_time), keyframe);
4014
4015   /* FIXME, this code assumes the main stream with keyframes is stream 0,
4016    * which is mostly correct... */
4017   stream = &avi->stream[avi->main_stream];
4018
4019   /* get the entry index for the requested position */
4020   index = gst_avi_demux_index_for_time (avi, stream, seek_time);
4021   GST_DEBUG_OBJECT (avi, "Got entry %u", index);
4022
4023   /* check if we are already on a keyframe */
4024   if (!ENTRY_IS_KEYFRAME (&stream->index[index])) {
4025     GST_DEBUG_OBJECT (avi, "not keyframe, searching back");
4026     /* now go to the previous keyframe, this is where we should start
4027      * decoding from. */
4028     index = gst_avi_demux_index_prev (avi, stream, index, TRUE);
4029     GST_DEBUG_OBJECT (avi, "previous keyframe at %u", index);
4030   }
4031
4032   /* move the main stream to this position */
4033   gst_avi_demux_move_stream (avi, stream, segment, index);
4034
4035   if (keyframe) {
4036     /* when seeking to a keyframe, we update the result seek time
4037      * to the time of the keyframe. */
4038     seek_time = stream->current_timestamp;
4039     GST_DEBUG_OBJECT (avi, "keyframe adjusted to %" GST_TIME_FORMAT,
4040         GST_TIME_ARGS (seek_time));
4041   }
4042
4043   /* the seek time is also the last_stop and stream time when going
4044    * forwards */
4045   segment->last_stop = seek_time;
4046   if (segment->rate > 0.0)
4047     segment->time = seek_time;
4048
4049   /* now set DISCONT and align the other streams */
4050   for (i = 0; i < avi->num_streams; i++) {
4051     GstAviStream *ostream;
4052
4053     ostream = &avi->stream[i];
4054     if ((ostream == stream) || (ostream->index == NULL))
4055       continue;
4056
4057     /* get the entry index for the requested position */
4058     index = gst_avi_demux_index_for_time (avi, ostream, seek_time);
4059
4060     /* move to previous keyframe */
4061     if (!ENTRY_IS_KEYFRAME (&ostream->index[index]))
4062       index = gst_avi_demux_index_prev (avi, ostream, index, TRUE);
4063
4064     gst_avi_demux_move_stream (avi, ostream, segment, index);
4065   }
4066   GST_DEBUG_OBJECT (avi, "done seek to: %" GST_TIME_FORMAT,
4067       GST_TIME_ARGS (seek_time));
4068
4069   return TRUE;
4070 }
4071
4072 /*
4073  * Handle seek event in pull mode.
4074  */
4075 static gboolean
4076 gst_avi_demux_handle_seek (GstAviDemux * avi, GstPad * pad, GstEvent * event)
4077 {
4078   gdouble rate;
4079   GstFormat format;
4080   GstSeekFlags flags;
4081   GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
4082   gint64 cur, stop;
4083   gboolean flush;
4084   gboolean update;
4085   GstSegment seeksegment = { 0, };
4086   gint i;
4087
4088   if (event) {
4089     GST_DEBUG_OBJECT (avi, "doing seek with event");
4090
4091     gst_event_parse_seek (event, &rate, &format, &flags,
4092         &cur_type, &cur, &stop_type, &stop);
4093
4094     /* we have to have a format as the segment format. Try to convert
4095      * if not. */
4096     if (format != GST_FORMAT_TIME) {
4097       GstFormat fmt = GST_FORMAT_TIME;
4098       gboolean res = TRUE;
4099
4100       if (cur_type != GST_SEEK_TYPE_NONE)
4101         res = gst_pad_query_convert (pad, format, cur, &fmt, &cur);
4102       if (res && stop_type != GST_SEEK_TYPE_NONE)
4103         res = gst_pad_query_convert (pad, format, stop, &fmt, &stop);
4104       if (!res)
4105         goto no_format;
4106
4107       format = fmt;
4108     }
4109     GST_DEBUG_OBJECT (avi,
4110         "seek requested: rate %g cur %" GST_TIME_FORMAT " stop %"
4111         GST_TIME_FORMAT, rate, GST_TIME_ARGS (cur), GST_TIME_ARGS (stop));
4112     /* FIXME: can we do anything with rate!=1.0 */
4113   } else {
4114     GST_DEBUG_OBJECT (avi, "doing seek without event");
4115     flags = 0;
4116     rate = 1.0;
4117   }
4118
4119   /* save flush flag */
4120   flush = flags & GST_SEEK_FLAG_FLUSH;
4121
4122   if (flush) {
4123     GstEvent *fevent = gst_event_new_flush_start ();
4124
4125     /* for a flushing seek, we send a flush_start on all pads. This will
4126      * eventually stop streaming with a WRONG_STATE. We can thus eventually
4127      * take the STREAM_LOCK. */
4128     GST_DEBUG_OBJECT (avi, "sending flush start");
4129     gst_avi_demux_push_event (avi, gst_event_ref (fevent));
4130     gst_pad_push_event (avi->sinkpad, fevent);
4131   } else {
4132     /* a non-flushing seek, we PAUSE the task so that we can take the
4133      * STREAM_LOCK */
4134     GST_DEBUG_OBJECT (avi, "non flushing seek, pausing task");
4135     gst_pad_pause_task (avi->sinkpad);
4136   }
4137
4138   /* wait for streaming to stop */
4139   GST_DEBUG_OBJECT (avi, "wait for streaming to stop");
4140   GST_PAD_STREAM_LOCK (avi->sinkpad);
4141
4142   /* copy segment, we need this because we still need the old
4143    * segment when we close the current segment. */
4144   memcpy (&seeksegment, &avi->segment, sizeof (GstSegment));
4145
4146   if (event) {
4147     GST_DEBUG_OBJECT (avi, "configuring seek");
4148     gst_segment_set_seek (&seeksegment, rate, format, flags,
4149         cur_type, cur, stop_type, stop, &update);
4150   }
4151   /* do the seek, seeksegment.last_stop contains the new position, this
4152    * actually never fails. */
4153   gst_avi_demux_do_seek (avi, &seeksegment);
4154
4155   gst_event_replace (&avi->close_seg_event, NULL);
4156   if (flush) {
4157     GstEvent *fevent = gst_event_new_flush_stop ();
4158
4159     GST_DEBUG_OBJECT (avi, "sending flush stop");
4160     gst_avi_demux_push_event (avi, gst_event_ref (fevent));
4161     gst_pad_push_event (avi->sinkpad, fevent);
4162   } else if (avi->segment_running) {
4163     /* we are running the current segment and doing a non-flushing seek,
4164      * close the segment first based on the last_stop. */
4165     GST_DEBUG_OBJECT (avi, "closing running segment %" G_GINT64_FORMAT
4166         " to %" G_GINT64_FORMAT, avi->segment.start, avi->segment.last_stop);
4167     avi->close_seg_event = gst_event_new_new_segment_full (TRUE,
4168         avi->segment.rate, avi->segment.applied_rate, avi->segment.format,
4169         avi->segment.start, avi->segment.last_stop, avi->segment.time);
4170   }
4171
4172   /* now update the real segment info */
4173   memcpy (&avi->segment, &seeksegment, sizeof (GstSegment));
4174
4175   /* post the SEGMENT_START message when we do segmented playback */
4176   if (avi->segment.flags & GST_SEEK_FLAG_SEGMENT) {
4177     gst_element_post_message (GST_ELEMENT_CAST (avi),
4178         gst_message_new_segment_start (GST_OBJECT_CAST (avi),
4179             avi->segment.format, avi->segment.last_stop));
4180   }
4181
4182   /* prepare for streaming again */
4183   if ((stop = avi->segment.stop) == GST_CLOCK_TIME_NONE)
4184     stop = avi->segment.duration;
4185
4186   /* queue the segment event for the streaming thread. */
4187   if (avi->seg_event)
4188     gst_event_unref (avi->seg_event);
4189   if (avi->segment.rate > 0.0) {
4190     /* forwards goes from last_stop to stop */
4191     avi->seg_event = gst_event_new_new_segment_full (FALSE,
4192         avi->segment.rate, avi->segment.applied_rate, avi->segment.format,
4193         avi->segment.last_stop, stop, avi->segment.time);
4194   } else {
4195     /* reverse goes from start to last_stop */
4196     avi->seg_event = gst_event_new_new_segment_full (FALSE,
4197         avi->segment.rate, avi->segment.applied_rate, avi->segment.format,
4198         avi->segment.start, avi->segment.last_stop, avi->segment.time);
4199   }
4200
4201   if (!avi->streaming) {
4202     avi->segment_running = TRUE;
4203     gst_pad_start_task (avi->sinkpad, (GstTaskFunction) gst_avi_demux_loop,
4204         avi->sinkpad);
4205   }
4206   /* reset the last flow and mark discont, seek is always DISCONT */
4207   for (i = 0; i < avi->num_streams; i++) {
4208     GST_DEBUG_OBJECT (avi, "marking DISCONT");
4209     avi->stream[i].last_flow = GST_FLOW_OK;
4210     avi->stream[i].discont = TRUE;
4211   }
4212   GST_PAD_STREAM_UNLOCK (avi->sinkpad);
4213
4214   return TRUE;
4215
4216   /* ERRORS */
4217 no_format:
4218   {
4219     GST_DEBUG_OBJECT (avi, "unsupported format given, seek aborted.");
4220     return FALSE;
4221   }
4222 }
4223
4224 /*
4225  * Handle seek event in push mode.
4226  */
4227 static gboolean
4228 avi_demux_handle_seek_push (GstAviDemux * avi, GstPad * pad, GstEvent * event)
4229 {
4230   gdouble rate;
4231   GstFormat format;
4232   GstSeekFlags flags;
4233   GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
4234   gint64 cur, stop;
4235   gboolean keyframe;
4236   GstAviStream *stream;
4237   guint index;
4238   guint n, str_num;
4239   guint64 min_offset;
4240   GstSegment seeksegment;
4241   gboolean update;
4242
4243   /* check we have the index */
4244   if (!avi->have_index) {
4245     GST_DEBUG_OBJECT (avi, "no seek index built, seek aborted.");
4246     return FALSE;
4247   } else {
4248     GST_DEBUG_OBJECT (avi, "doing push-based seek with event");
4249   }
4250
4251   gst_event_parse_seek (event, &rate, &format, &flags,
4252       &cur_type, &cur, &stop_type, &stop);
4253
4254   if (format != GST_FORMAT_TIME) {
4255     GstFormat fmt = GST_FORMAT_TIME;
4256     gboolean res = TRUE;
4257
4258     if (cur_type != GST_SEEK_TYPE_NONE)
4259       res = gst_pad_query_convert (pad, format, cur, &fmt, &cur);
4260     if (res && stop_type != GST_SEEK_TYPE_NONE)
4261       res = gst_pad_query_convert (pad, format, stop, &fmt, &stop);
4262     if (!res) {
4263       GST_DEBUG_OBJECT (avi, "unsupported format given, seek aborted.");
4264       return FALSE;
4265     }
4266
4267     format = fmt;
4268   }
4269
4270   /* let gst_segment handle any tricky stuff */
4271   GST_DEBUG_OBJECT (avi, "configuring seek");
4272   memcpy (&seeksegment, &avi->segment, sizeof (GstSegment));
4273   gst_segment_set_seek (&seeksegment, rate, format, flags,
4274       cur_type, cur, stop_type, stop, &update);
4275
4276   keyframe = !!(flags & GST_SEEK_FLAG_KEY_UNIT);
4277   cur = seeksegment.last_stop;
4278
4279   GST_DEBUG_OBJECT (avi,
4280       "Seek requested: ts %" GST_TIME_FORMAT " stop %" GST_TIME_FORMAT
4281       ", kf %u, rate %lf", GST_TIME_ARGS (cur), GST_TIME_ARGS (stop), keyframe,
4282       rate);
4283
4284   if (rate < 0) {
4285     GST_DEBUG_OBJECT (avi, "negative rate seek not supported in push mode");
4286     return FALSE;
4287   }
4288
4289   /* FIXME, this code assumes the main stream with keyframes is stream 0,
4290    * which is mostly correct... */
4291   str_num = avi->main_stream;
4292   stream = &avi->stream[str_num];
4293
4294   /* get the entry index for the requested position */
4295   index = gst_avi_demux_index_for_time (avi, stream, cur);
4296   GST_DEBUG_OBJECT (avi, "str %u: Found entry %u for %" GST_TIME_FORMAT,
4297       str_num, index, GST_TIME_ARGS (cur));
4298
4299   /* check if we are already on a keyframe */
4300   if (!ENTRY_IS_KEYFRAME (&stream->index[index])) {
4301     GST_DEBUG_OBJECT (avi, "Entry is not a keyframe - searching back");
4302     /* now go to the previous keyframe, this is where we should start
4303      * decoding from. */
4304     index = gst_avi_demux_index_prev (avi, stream, index, TRUE);
4305     GST_DEBUG_OBJECT (avi, "Found previous keyframe at %u", index);
4306   }
4307
4308   gst_avi_demux_get_buffer_info (avi, stream, index,
4309       &stream->current_timestamp, &stream->current_ts_end,
4310       &stream->current_offset, &stream->current_offset_end);
4311
4312   /* re-use cur to be the timestamp of the seek as it _will_ be */
4313   cur = stream->current_timestamp;
4314
4315   min_offset = stream->index[index].offset;
4316   avi->seek_kf_offset = min_offset - 8;
4317
4318   GST_DEBUG_OBJECT (avi,
4319       "Seek to: ts %" GST_TIME_FORMAT " (on str %u, idx %u, offset %"
4320       G_GUINT64_FORMAT ")", GST_TIME_ARGS (stream->current_timestamp), str_num,
4321       index, min_offset);
4322
4323   for (n = 0; n < avi->num_streams; n++) {
4324     GstAviStream *str = &avi->stream[n];
4325     guint idx;
4326
4327     if (n == avi->main_stream)
4328       continue;
4329
4330     /* get the entry index for the requested position */
4331     idx = gst_avi_demux_index_for_time (avi, str, cur);
4332     GST_DEBUG_OBJECT (avi, "str %u: Found entry %u for %" GST_TIME_FORMAT, n,
4333         idx, GST_TIME_ARGS (cur));
4334
4335     /* check if we are already on a keyframe */
4336     if (!ENTRY_IS_KEYFRAME (&str->index[idx])) {
4337       GST_DEBUG_OBJECT (avi, "Entry is not a keyframe - searching back");
4338       /* now go to the previous keyframe, this is where we should start
4339        * decoding from. */
4340       idx = gst_avi_demux_index_prev (avi, str, idx, TRUE);
4341       GST_DEBUG_OBJECT (avi, "Found previous keyframe at %u", idx);
4342     }
4343
4344     gst_avi_demux_get_buffer_info (avi, str, idx,
4345         &str->current_timestamp, &str->current_ts_end,
4346         &str->current_offset, &str->current_offset_end);
4347
4348     if (str->index[idx].offset < min_offset) {
4349       min_offset = str->index[idx].offset;
4350       GST_DEBUG_OBJECT (avi,
4351           "Found an earlier offset at %" G_GUINT64_FORMAT ", str %u",
4352           min_offset, n);
4353       str_num = n;
4354       stream = str;
4355       index = idx;
4356     }
4357   }
4358
4359   GST_DEBUG_OBJECT (avi,
4360       "Seek performed: str %u, offset %" G_GUINT64_FORMAT ", idx %u, ts %"
4361       GST_TIME_FORMAT ", ts_end %" GST_TIME_FORMAT ", off %" G_GUINT64_FORMAT
4362       ", off_end %" G_GUINT64_FORMAT, str_num, min_offset, index,
4363       GST_TIME_ARGS (stream->current_timestamp),
4364       GST_TIME_ARGS (stream->current_ts_end), stream->current_offset,
4365       stream->current_offset_end);
4366
4367   /* index data refers to data, not chunk header (for pull mode convenience) */
4368   min_offset -= 8;
4369   GST_DEBUG_OBJECT (avi, "seeking to chunk at offset %" G_GUINT64_FORMAT,
4370       min_offset);
4371
4372   if (!perform_seek_to_offset (avi, min_offset)) {
4373     GST_DEBUG_OBJECT (avi, "seek event failed!");
4374     return FALSE;
4375   }
4376
4377   return TRUE;
4378 }
4379
4380 /*
4381  * Handle whether we can perform the seek event or if we have to let the chain
4382  * function handle seeks to build the seek indexes first.
4383  */
4384 static gboolean
4385 gst_avi_demux_handle_seek_push (GstAviDemux * avi, GstPad * pad,
4386     GstEvent * event)
4387 {
4388   /* check for having parsed index already */
4389   if (!avi->have_index) {
4390     guint64 offset = 0;
4391     gboolean building_index;
4392
4393     GST_OBJECT_LOCK (avi);
4394     /* handle the seek event in the chain function */
4395     avi->state = GST_AVI_DEMUX_SEEK;
4396
4397     /* copy the event */
4398     if (avi->seek_event)
4399       gst_event_unref (avi->seek_event);
4400     avi->seek_event = gst_event_ref (event);
4401
4402     /* set the building_index flag so that only one thread can setup the
4403      * structures for index seeking. */
4404     building_index = avi->building_index;
4405     if (!building_index) {
4406       avi->building_index = TRUE;
4407       if (avi->stream[0].indexes) {
4408         avi->odml_stream = 0;
4409         avi->odml_subidxs = avi->stream[avi->odml_stream].indexes;
4410         offset = avi->odml_subidxs[0];
4411       } else {
4412         offset = avi->idx1_offset;
4413       }
4414     }
4415     GST_OBJECT_UNLOCK (avi);
4416
4417     if (!building_index) {
4418       /* seek to the first subindex or legacy index */
4419       GST_INFO_OBJECT (avi,
4420           "Seeking to legacy index/first subindex at %" G_GUINT64_FORMAT,
4421           offset);
4422       return perform_seek_to_offset (avi, offset);
4423     }
4424
4425     /* FIXME: we have to always return true so that we don't block the seek
4426      * thread.
4427      * Note: maybe it is OK to return true if we're still building the index */
4428     return TRUE;
4429   }
4430
4431   return avi_demux_handle_seek_push (avi, pad, event);
4432 }
4433
4434 /*
4435  * Helper for gst_avi_demux_invert()
4436  */
4437 static inline void
4438 swap_line (guint8 * d1, guint8 * d2, guint8 * tmp, gint bytes)
4439 {
4440   memcpy (tmp, d1, bytes);
4441   memcpy (d1, d2, bytes);
4442   memcpy (d2, tmp, bytes);
4443 }
4444
4445
4446 #define gst_avi_demux_is_uncompressed(fourcc)           \
4447   (fourcc &&                                            \
4448     (fourcc == GST_RIFF_DIB ||                          \
4449      fourcc == GST_RIFF_rgb ||                          \
4450      fourcc == GST_RIFF_RGB || fourcc == GST_RIFF_RAW))
4451
4452 /*
4453  * Invert DIB buffers... Takes existing buffer and
4454  * returns either the buffer or a new one (with old
4455  * one dereferenced).
4456  * FIXME: can't we preallocate tmp? and remember stride, bpp?
4457  */
4458 static GstBuffer *
4459 gst_avi_demux_invert (GstAviStream * stream, GstBuffer * buf)
4460 {
4461   GstStructure *s;
4462   gint y, w, h;
4463   gint bpp, stride;
4464   guint8 *tmp = NULL, *data;
4465   gsize size;
4466
4467   if (stream->strh->type != GST_RIFF_FCC_vids)
4468     return buf;
4469
4470   if (!gst_avi_demux_is_uncompressed (stream->strh->fcc_handler)) {
4471     return buf;                 /* Ignore non DIB buffers */
4472   }
4473
4474   s = gst_caps_get_structure (GST_PAD_CAPS (stream->pad), 0);
4475   if (!gst_structure_get_int (s, "bpp", &bpp)) {
4476     GST_WARNING ("Failed to retrieve depth from caps");
4477     return buf;
4478   }
4479
4480   if (stream->strf.vids == NULL) {
4481     GST_WARNING ("Failed to retrieve vids for stream");
4482     return buf;
4483   }
4484
4485   h = stream->strf.vids->height;
4486   w = stream->strf.vids->width;
4487   stride = w * (bpp / 8);
4488
4489   buf = gst_buffer_make_writable (buf);
4490
4491   data = gst_buffer_map (buf, &size, NULL, GST_MAP_READWRITE);
4492   if (size < (stride * h)) {
4493     GST_WARNING ("Buffer is smaller than reported Width x Height x Depth");
4494     gst_buffer_unmap (buf, data, size);
4495     return buf;
4496   }
4497
4498   tmp = g_malloc (stride);
4499
4500   for (y = 0; y < h / 2; y++) {
4501     swap_line (data + stride * y, data + stride * (h - 1 - y), tmp, stride);
4502   }
4503
4504   g_free (tmp);
4505
4506   gst_buffer_unmap (buf, data, size);
4507
4508   return buf;
4509 }
4510
4511 static void
4512 gst_avi_demux_add_assoc (GstAviDemux * avi, GstAviStream * stream,
4513     GstClockTime timestamp, guint64 offset, gboolean keyframe)
4514 {
4515   /* do not add indefinitely for open-ended streaming */
4516   if (G_UNLIKELY (avi->element_index && avi->seekable)) {
4517     GST_LOG_OBJECT (avi, "adding association %" GST_TIME_FORMAT "-> %"
4518         G_GUINT64_FORMAT, GST_TIME_ARGS (timestamp), offset);
4519     gst_index_add_association (avi->element_index, avi->index_id,
4520         keyframe ? GST_ASSOCIATION_FLAG_KEY_UNIT :
4521         GST_ASSOCIATION_FLAG_DELTA_UNIT, GST_FORMAT_TIME, timestamp,
4522         GST_FORMAT_BYTES, offset, NULL);
4523     /* current_entry is DEFAULT (frame #) */
4524     gst_index_add_association (avi->element_index, stream->index_id,
4525         keyframe ? GST_ASSOCIATION_FLAG_KEY_UNIT :
4526         GST_ASSOCIATION_FLAG_DELTA_UNIT, GST_FORMAT_TIME, timestamp,
4527         GST_FORMAT_BYTES, offset, GST_FORMAT_DEFAULT, stream->current_entry,
4528         NULL);
4529   }
4530 }
4531
4532 /*
4533  * Returns the aggregated GstFlowReturn.
4534  */
4535 static GstFlowReturn
4536 gst_avi_demux_combine_flows (GstAviDemux * avi, GstAviStream * stream,
4537     GstFlowReturn ret)
4538 {
4539   guint i;
4540   gboolean unexpected = FALSE, not_linked = TRUE;
4541
4542   /* store the value */
4543   stream->last_flow = ret;
4544
4545   /* any other error that is not-linked or eos can be returned right away */
4546   if (G_LIKELY (ret != GST_FLOW_UNEXPECTED && ret != GST_FLOW_NOT_LINKED))
4547     goto done;
4548
4549   /* only return NOT_LINKED if all other pads returned NOT_LINKED */
4550   for (i = 0; i < avi->num_streams; i++) {
4551     GstAviStream *ostream = &avi->stream[i];
4552
4553     ret = ostream->last_flow;
4554     /* no unexpected or unlinked, return */
4555     if (G_LIKELY (ret != GST_FLOW_UNEXPECTED && ret != GST_FLOW_NOT_LINKED))
4556       goto done;
4557
4558     /* we check to see if we have at least 1 unexpected or all unlinked */
4559     unexpected |= (ret == GST_FLOW_UNEXPECTED);
4560     not_linked &= (ret == GST_FLOW_NOT_LINKED);
4561   }
4562   /* when we get here, we all have unlinked or unexpected */
4563   if (not_linked)
4564     ret = GST_FLOW_NOT_LINKED;
4565   else if (unexpected)
4566     ret = GST_FLOW_UNEXPECTED;
4567 done:
4568   GST_LOG_OBJECT (avi, "combined %s to return %s",
4569       gst_flow_get_name (stream->last_flow), gst_flow_get_name (ret));
4570   return ret;
4571 }
4572
4573 /* move @stream to the next position in its index */
4574 static GstFlowReturn
4575 gst_avi_demux_advance (GstAviDemux * avi, GstAviStream * stream,
4576     GstFlowReturn ret)
4577 {
4578   guint old_entry, new_entry;
4579
4580   old_entry = stream->current_entry;
4581   /* move forwards */
4582   new_entry = old_entry + 1;
4583
4584   /* see if we reached the end */
4585   if (new_entry >= stream->stop_entry) {
4586     if (avi->segment.rate < 0.0) {
4587       if (stream->step_entry == stream->start_entry) {
4588         /* we stepped all the way to the start, eos */
4589         GST_DEBUG_OBJECT (avi, "reverse reached start %u", stream->start_entry);
4590         goto eos;
4591       }
4592       /* backwards, stop becomes step, find a new step */
4593       stream->stop_entry = stream->step_entry;
4594       stream->step_entry = gst_avi_demux_index_prev (avi, stream,
4595           stream->stop_entry, TRUE);
4596
4597       GST_DEBUG_OBJECT (avi,
4598           "reverse playback jump: start %u, step %u, stop %u",
4599           stream->start_entry, stream->step_entry, stream->stop_entry);
4600
4601       /* and start from the previous keyframe now */
4602       new_entry = stream->step_entry;
4603     } else {
4604       /* EOS */
4605       GST_DEBUG_OBJECT (avi, "forward reached stop %u", stream->stop_entry);
4606       goto eos;
4607     }
4608   }
4609
4610   if (new_entry != old_entry) {
4611     stream->current_entry = new_entry;
4612     stream->current_total = stream->index[new_entry].total;
4613
4614     if (new_entry == old_entry + 1) {
4615       GST_DEBUG_OBJECT (avi, "moved forwards from %u to %u",
4616           old_entry, new_entry);
4617       /* we simply moved one step forwards, reuse current info */
4618       stream->current_timestamp = stream->current_ts_end;
4619       stream->current_offset = stream->current_offset_end;
4620       gst_avi_demux_get_buffer_info (avi, stream, new_entry,
4621           NULL, &stream->current_ts_end, NULL, &stream->current_offset_end);
4622     } else {
4623       /* we moved DISCONT, full update */
4624       gst_avi_demux_get_buffer_info (avi, stream, new_entry,
4625           &stream->current_timestamp, &stream->current_ts_end,
4626           &stream->current_offset, &stream->current_offset_end);
4627       /* and MARK discont for this stream */
4628       stream->last_flow = GST_FLOW_OK;
4629       stream->discont = TRUE;
4630       GST_DEBUG_OBJECT (avi, "Moved from %u to %u, ts %" GST_TIME_FORMAT
4631           ", ts_end %" GST_TIME_FORMAT ", off %" G_GUINT64_FORMAT
4632           ", off_end %" G_GUINT64_FORMAT, old_entry, new_entry,
4633           GST_TIME_ARGS (stream->current_timestamp),
4634           GST_TIME_ARGS (stream->current_ts_end), stream->current_offset,
4635           stream->current_offset_end);
4636     }
4637   }
4638   return ret;
4639
4640   /* ERROR */
4641 eos:
4642   {
4643     GST_DEBUG_OBJECT (avi, "we are EOS");
4644     /* setting current_timestamp to -1 marks EOS */
4645     stream->current_timestamp = -1;
4646     return GST_FLOW_UNEXPECTED;
4647   }
4648 }
4649
4650 /* find the stream with the lowest current position when going forwards or with
4651  * the highest position when going backwards, this is the stream
4652  * we should push from next */
4653 static gint
4654 gst_avi_demux_find_next (GstAviDemux * avi, gfloat rate)
4655 {
4656   guint64 min_time, max_time;
4657   guint stream_num, i;
4658
4659   max_time = 0;
4660   min_time = G_MAXUINT64;
4661   stream_num = -1;
4662
4663   for (i = 0; i < avi->num_streams; i++) {
4664     guint64 position;
4665     GstAviStream *stream;
4666
4667     stream = &avi->stream[i];
4668
4669     /* ignore streams that finished */
4670     if (stream->last_flow == GST_FLOW_UNEXPECTED)
4671       continue;
4672
4673     position = stream->current_timestamp;
4674
4675     /* position of -1 is EOS */
4676     if (position != -1) {
4677       if (rate > 0.0 && position < min_time) {
4678         min_time = position;
4679         stream_num = i;
4680       } else if (rate < 0.0 && position >= max_time) {
4681         max_time = position;
4682         stream_num = i;
4683       }
4684     }
4685   }
4686   return stream_num;
4687 }
4688
4689 static GstFlowReturn
4690 gst_avi_demux_loop_data (GstAviDemux * avi)
4691 {
4692   GstFlowReturn ret = GST_FLOW_OK;
4693   guint stream_num;
4694   GstAviStream *stream;
4695   gboolean processed = FALSE;
4696   GstBuffer *buf;
4697   guint64 offset, size;
4698   GstClockTime timestamp, duration;
4699   guint64 out_offset, out_offset_end;
4700   gboolean keyframe;
4701   GstAviIndexEntry *entry;
4702
4703   do {
4704     stream_num = gst_avi_demux_find_next (avi, avi->segment.rate);
4705
4706     /* all are EOS */
4707     if (G_UNLIKELY (stream_num == -1)) {
4708       GST_DEBUG_OBJECT (avi, "all streams are EOS");
4709       goto eos;
4710     }
4711
4712     /* we have the stream now */
4713     stream = &avi->stream[stream_num];
4714
4715     /* skip streams without pads */
4716     if (!stream->pad) {
4717       GST_DEBUG_OBJECT (avi, "skipping entry from stream %d without pad",
4718           stream_num);
4719       goto next;
4720     }
4721
4722     /* get the timing info for the entry */
4723     timestamp = stream->current_timestamp;
4724     duration = stream->current_ts_end - timestamp;
4725     out_offset = stream->current_offset;
4726     out_offset_end = stream->current_offset_end;
4727
4728     /* get the entry data info */
4729     entry = &stream->index[stream->current_entry];
4730     offset = entry->offset;
4731     size = entry->size;
4732     keyframe = ENTRY_IS_KEYFRAME (entry);
4733
4734     /* skip empty entries */
4735     if (size == 0) {
4736       GST_DEBUG_OBJECT (avi, "Skipping entry %u (%" G_GUINT64_FORMAT ", %p)",
4737           stream->current_entry, size, stream->pad);
4738       goto next;
4739     }
4740
4741     if (avi->segment.rate > 0.0) {
4742       /* only check this for fowards playback for now */
4743       if (keyframe && GST_CLOCK_TIME_IS_VALID (avi->segment.stop)
4744           && (timestamp > avi->segment.stop)) {
4745         goto eos_stop;
4746       }
4747     }
4748
4749     GST_LOG ("reading buffer (size=%" G_GUINT64_FORMAT "), stream %d, pos %"
4750         G_GUINT64_FORMAT " (0x%" G_GINT64_MODIFIER "x), kf %d", size,
4751         stream_num, offset, offset, keyframe);
4752
4753     /* FIXME, check large chunks and cut them up */
4754
4755     /* pull in the data */
4756     ret = gst_pad_pull_range (avi->sinkpad, offset, size, &buf);
4757     if (ret != GST_FLOW_OK)
4758       goto pull_failed;
4759
4760     /* check for short buffers, this is EOS as well */
4761     if (gst_buffer_get_size (buf) < size)
4762       goto short_buffer;
4763
4764     /* invert the picture if needed */
4765     buf = gst_avi_demux_invert (stream, buf);
4766
4767     /* mark non-keyframes */
4768     if (keyframe)
4769       GST_BUFFER_FLAG_UNSET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
4770     else
4771       GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
4772
4773     GST_BUFFER_TIMESTAMP (buf) = timestamp;
4774     GST_BUFFER_DURATION (buf) = duration;
4775     GST_BUFFER_OFFSET (buf) = out_offset;
4776     GST_BUFFER_OFFSET_END (buf) = out_offset_end;
4777
4778     /* mark discont when pending */
4779     if (stream->discont) {
4780       GST_DEBUG_OBJECT (avi, "setting DISCONT flag");
4781       GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
4782       stream->discont = FALSE;
4783     }
4784
4785     gst_avi_demux_add_assoc (avi, stream, timestamp, offset, keyframe);
4786
4787     gst_buffer_set_caps (buf, GST_PAD_CAPS (stream->pad));
4788
4789     /* update current position in the segment */
4790     gst_segment_set_last_stop (&avi->segment, GST_FORMAT_TIME, timestamp);
4791
4792     GST_DEBUG_OBJECT (avi, "Pushing buffer of size %u, ts %"
4793         GST_TIME_FORMAT ", dur %" GST_TIME_FORMAT ", off %" G_GUINT64_FORMAT
4794         ", off_end %" G_GUINT64_FORMAT,
4795         gst_buffer_get_size (buf), GST_TIME_ARGS (timestamp),
4796         GST_TIME_ARGS (duration), out_offset, out_offset_end);
4797
4798     ret = gst_pad_push (stream->pad, buf);
4799
4800     /* mark as processed, we increment the frame and byte counters then
4801      * leave the while loop and return the GstFlowReturn */
4802     processed = TRUE;
4803
4804     if (avi->segment.rate < 0) {
4805       if (timestamp > avi->segment.stop && ret == GST_FLOW_UNEXPECTED) {
4806         /* In reverse playback we can get a GST_FLOW_UNEXPECTED when
4807          * we are at the end of the segment, so we just need to jump
4808          * back to the previous section. */
4809         GST_DEBUG_OBJECT (avi, "downstream has reached end of segment");
4810         ret = GST_FLOW_OK;
4811       }
4812     }
4813   next:
4814     /* move to next item */
4815     ret = gst_avi_demux_advance (avi, stream, ret);
4816
4817     /* combine flows */
4818     ret = gst_avi_demux_combine_flows (avi, stream, ret);
4819   } while (!processed);
4820
4821 beach:
4822   return ret;
4823
4824   /* special cases */
4825 eos:
4826   {
4827     GST_DEBUG_OBJECT (avi, "No samples left for any streams - EOS");
4828     ret = GST_FLOW_UNEXPECTED;
4829     goto beach;
4830   }
4831 eos_stop:
4832   {
4833     GST_LOG_OBJECT (avi, "Found keyframe after segment,"
4834         " setting EOS (%" GST_TIME_FORMAT " > %" GST_TIME_FORMAT ")",
4835         GST_TIME_ARGS (timestamp), GST_TIME_ARGS (avi->segment.stop));
4836     ret = GST_FLOW_UNEXPECTED;
4837     /* move to next stream */
4838     goto next;
4839   }
4840 pull_failed:
4841   {
4842     GST_DEBUG_OBJECT (avi, "pull range failed: pos=%" G_GUINT64_FORMAT
4843         " size=%" G_GUINT64_FORMAT, offset, size);
4844     goto beach;
4845   }
4846 short_buffer:
4847   {
4848     GST_WARNING_OBJECT (avi, "Short read at offset %" G_GUINT64_FORMAT
4849         ", only got %d/%" G_GUINT64_FORMAT " bytes (truncated file?)", offset,
4850         gst_buffer_get_size (buf), size);
4851     gst_buffer_unref (buf);
4852     ret = GST_FLOW_UNEXPECTED;
4853     goto beach;
4854   }
4855 }
4856
4857 /*
4858  * Read data. If we have an index it delegates to
4859  * gst_avi_demux_process_next_entry().
4860  */
4861 static GstFlowReturn
4862 gst_avi_demux_stream_data (GstAviDemux * avi)
4863 {
4864   guint32 tag = 0;
4865   guint32 size = 0;
4866   gint stream_nr = 0;
4867   GstFlowReturn res = GST_FLOW_OK;
4868   GstFormat format = GST_FORMAT_TIME;
4869
4870   if (G_UNLIKELY (avi->have_eos)) {
4871     /* Clean adapter, we're done */
4872     gst_adapter_clear (avi->adapter);
4873     return GST_FLOW_UNEXPECTED;
4874   }
4875
4876   if (G_UNLIKELY (avi->todrop)) {
4877     guint drop;
4878
4879     if ((drop = gst_adapter_available (avi->adapter))) {
4880       if (drop > avi->todrop)
4881         drop = avi->todrop;
4882       GST_DEBUG_OBJECT (avi, "Dropping %d bytes", drop);
4883       gst_adapter_flush (avi->adapter, drop);
4884       avi->todrop -= drop;
4885       avi->offset += drop;
4886     }
4887   }
4888
4889   /* Iterate until need more data, so adapter won't grow too much */
4890   while (1) {
4891     if (G_UNLIKELY (!gst_avi_demux_peek_chunk_info (avi, &tag, &size))) {
4892       return GST_FLOW_OK;
4893     }
4894
4895     GST_DEBUG ("Trying chunk (%" GST_FOURCC_FORMAT "), size %d",
4896         GST_FOURCC_ARGS (tag), size);
4897
4898     if (G_LIKELY ((tag & 0xff) >= '0' && (tag & 0xff) <= '9' &&
4899             ((tag >> 8) & 0xff) >= '0' && ((tag >> 8) & 0xff) <= '9')) {
4900       GST_LOG ("Chunk ok");
4901     } else if ((tag & 0xffff) == (('x' << 8) | 'i')) {
4902       GST_DEBUG ("Found sub-index tag");
4903       if (gst_avi_demux_peek_chunk (avi, &tag, &size) || size == 0) {
4904         /* accept 0 size buffer here */
4905         avi->abort_buffering = FALSE;
4906         GST_DEBUG ("  skipping %d bytes for now", size);
4907         gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
4908       }
4909       return GST_FLOW_OK;
4910     } else if (tag == GST_RIFF_TAG_RIFF) {
4911       /* RIFF tags can appear in ODML files, just jump over them */
4912       if (gst_adapter_available (avi->adapter) >= 12) {
4913         GST_DEBUG ("Found RIFF tag, skipping RIFF header");
4914         gst_adapter_flush (avi->adapter, 12);
4915         continue;
4916       }
4917       return GST_FLOW_OK;
4918     } else if (tag == GST_RIFF_TAG_idx1) {
4919       GST_DEBUG ("Found index tag");
4920       if (gst_avi_demux_peek_chunk (avi, &tag, &size) || size == 0) {
4921         /* accept 0 size buffer here */
4922         avi->abort_buffering = FALSE;
4923         GST_DEBUG ("  skipping %d bytes for now", size);
4924         gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
4925       }
4926       return GST_FLOW_OK;
4927     } else if (tag == GST_RIFF_TAG_LIST) {
4928       /* movi chunks might be grouped in rec list */
4929       if (gst_adapter_available (avi->adapter) >= 12) {
4930         GST_DEBUG ("Found LIST tag, skipping LIST header");
4931         gst_adapter_flush (avi->adapter, 12);
4932         continue;
4933       }
4934       return GST_FLOW_OK;
4935     } else if (tag == GST_RIFF_TAG_JUNK || tag == GST_RIFF_TAG_JUNQ) {
4936       /* rec list might contain JUNK chunks */
4937       GST_DEBUG ("Found JUNK tag");
4938       if (gst_avi_demux_peek_chunk (avi, &tag, &size) || size == 0) {
4939         /* accept 0 size buffer here */
4940         avi->abort_buffering = FALSE;
4941         GST_DEBUG ("  skipping %d bytes for now", size);
4942         gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
4943       }
4944       return GST_FLOW_OK;
4945     } else {
4946       GST_DEBUG ("No more stream chunks, send EOS");
4947       avi->have_eos = TRUE;
4948       return GST_FLOW_UNEXPECTED;
4949     }
4950
4951     if (G_UNLIKELY (!gst_avi_demux_peek_chunk (avi, &tag, &size))) {
4952       /* supposedly one hopes to catch a nicer chunk later on ... */
4953       /* FIXME ?? give up here rather than possibly ending up going
4954        * through the whole file */
4955       if (avi->abort_buffering) {
4956         avi->abort_buffering = FALSE;
4957         if (size) {
4958           gst_adapter_flush (avi->adapter, 8);
4959           return GST_FLOW_OK;
4960         }
4961       } else {
4962         return GST_FLOW_OK;
4963       }
4964     }
4965     GST_DEBUG ("chunk ID %" GST_FOURCC_FORMAT ", size %u",
4966         GST_FOURCC_ARGS (tag), size);
4967
4968     stream_nr = CHUNKID_TO_STREAMNR (tag);
4969
4970     if (G_UNLIKELY (stream_nr < 0 || stream_nr >= avi->num_streams)) {
4971       /* recoverable */
4972       GST_WARNING ("Invalid stream ID %d (%" GST_FOURCC_FORMAT ")",
4973           stream_nr, GST_FOURCC_ARGS (tag));
4974       avi->offset += 8 + GST_ROUND_UP_2 (size);
4975       gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
4976     } else {
4977       GstAviStream *stream;
4978       GstClockTime next_ts = 0;
4979       GstBuffer *buf = NULL;
4980       guint64 offset;
4981       gboolean saw_desired_kf = stream_nr != avi->main_stream
4982           || avi->offset >= avi->seek_kf_offset;
4983
4984       if (stream_nr == avi->main_stream && avi->offset == avi->seek_kf_offset) {
4985         GST_DEBUG_OBJECT (avi, "Desired keyframe reached");
4986         avi->seek_kf_offset = 0;
4987       }
4988
4989       if (saw_desired_kf) {
4990         gst_adapter_flush (avi->adapter, 8);
4991         /* get buffer */
4992         if (size) {
4993           buf = gst_adapter_take_buffer (avi->adapter, GST_ROUND_UP_2 (size));
4994           /* patch the size */
4995           gst_buffer_resize (buf, 0, size);
4996         } else {
4997           buf = NULL;
4998         }
4999       } else {
5000         GST_DEBUG_OBJECT (avi,
5001             "Desired keyframe not yet reached, flushing chunk");
5002         gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
5003       }
5004
5005       offset = avi->offset;
5006       avi->offset += 8 + GST_ROUND_UP_2 (size);
5007
5008       stream = &avi->stream[stream_nr];
5009
5010       /* set delay (if any)
5011          if (stream->strh->init_frames == stream->current_frame &&
5012          stream->delay == 0)
5013          stream->delay = next_ts;
5014        */
5015
5016       /* parsing of corresponding header may have failed */
5017       if (G_UNLIKELY (!stream->pad)) {
5018         GST_WARNING_OBJECT (avi, "no pad for stream ID %" GST_FOURCC_FORMAT,
5019             GST_FOURCC_ARGS (tag));
5020         if (buf)
5021           gst_buffer_unref (buf);
5022       } else {
5023         /* get time of this buffer */
5024         gst_pad_query_position (stream->pad, &format, (gint64 *) & next_ts);
5025         if (G_UNLIKELY (format != GST_FORMAT_TIME))
5026           goto wrong_format;
5027
5028         gst_avi_demux_add_assoc (avi, stream, next_ts, offset, FALSE);
5029
5030         /* increment our positions */
5031         stream->current_entry++;
5032         stream->current_total += size;
5033
5034         /* update current position in the segment */
5035         gst_segment_set_last_stop (&avi->segment, GST_FORMAT_TIME, next_ts);
5036
5037         if (saw_desired_kf && buf) {
5038           GstClockTime dur_ts = 0;
5039
5040           /* invert the picture if needed */
5041           buf = gst_avi_demux_invert (stream, buf);
5042
5043           gst_pad_query_position (stream->pad, &format, (gint64 *) & dur_ts);
5044           if (G_UNLIKELY (format != GST_FORMAT_TIME))
5045             goto wrong_format;
5046
5047           GST_BUFFER_TIMESTAMP (buf) = next_ts;
5048           GST_BUFFER_DURATION (buf) = dur_ts - next_ts;
5049           if (stream->strh->type == GST_RIFF_FCC_vids) {
5050             GST_BUFFER_OFFSET (buf) = stream->current_entry - 1;
5051             GST_BUFFER_OFFSET_END (buf) = stream->current_entry;
5052           } else {
5053             GST_BUFFER_OFFSET (buf) = GST_BUFFER_OFFSET_NONE;
5054             GST_BUFFER_OFFSET_END (buf) = GST_BUFFER_OFFSET_NONE;
5055           }
5056
5057           gst_buffer_set_caps (buf, GST_PAD_CAPS (stream->pad));
5058           GST_DEBUG_OBJECT (avi,
5059               "Pushing buffer with time=%" GST_TIME_FORMAT ", duration %"
5060               GST_TIME_FORMAT ", offset %" G_GUINT64_FORMAT
5061               " and size %d over pad %s", GST_TIME_ARGS (next_ts),
5062               GST_TIME_ARGS (GST_BUFFER_DURATION (buf)),
5063               GST_BUFFER_OFFSET (buf), size, GST_PAD_NAME (stream->pad));
5064
5065           /* mark discont when pending */
5066           if (G_UNLIKELY (stream->discont)) {
5067             GST_DEBUG_OBJECT (avi, "Setting DISCONT");
5068             GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
5069             stream->discont = FALSE;
5070           }
5071           res = gst_pad_push (stream->pad, buf);
5072           buf = NULL;
5073
5074           /* combine flows */
5075           res = gst_avi_demux_combine_flows (avi, stream, res);
5076           if (G_UNLIKELY (res != GST_FLOW_OK)) {
5077             GST_DEBUG ("Push failed; %s", gst_flow_get_name (res));
5078             return res;
5079           }
5080         }
5081       }
5082     }
5083   }
5084
5085 done:
5086   return res;
5087
5088   /* ERRORS */
5089 wrong_format:
5090   {
5091     GST_DEBUG_OBJECT (avi, "format %s != GST_FORMAT_TIME",
5092         gst_format_get_name (format));
5093     res = GST_FLOW_ERROR;
5094     goto done;
5095   }
5096 }
5097
5098 /*
5099  * Send pending tags.
5100  */
5101 static void
5102 push_tag_lists (GstAviDemux * avi)
5103 {
5104   guint i;
5105   GstTagList *tags;
5106
5107   if (!avi->got_tags)
5108     return;
5109
5110   GST_DEBUG_OBJECT (avi, "Pushing pending tag lists");
5111
5112   for (i = 0; i < avi->num_streams; i++) {
5113     GstAviStream *stream = &avi->stream[i];
5114     GstPad *pad = stream->pad;
5115
5116     tags = stream->taglist;
5117
5118     if (pad && tags) {
5119       GST_DEBUG_OBJECT (pad, "Tags: %" GST_PTR_FORMAT, tags);
5120
5121       gst_element_found_tags_for_pad (GST_ELEMENT_CAST (avi), pad, tags);
5122       stream->taglist = NULL;
5123     }
5124   }
5125
5126   if (!(tags = avi->globaltags))
5127     tags = gst_tag_list_new ();
5128
5129   gst_tag_list_add (tags, GST_TAG_MERGE_REPLACE,
5130       GST_TAG_CONTAINER_FORMAT, "AVI", NULL);
5131
5132   GST_DEBUG_OBJECT (avi, "Global tags: %" GST_PTR_FORMAT, tags);
5133   gst_element_found_tags (GST_ELEMENT_CAST (avi), tags);
5134   avi->globaltags = NULL;
5135   avi->got_tags = FALSE;
5136 }
5137
5138 static void
5139 gst_avi_demux_loop (GstPad * pad)
5140 {
5141   GstFlowReturn res;
5142   GstAviDemux *avi = GST_AVI_DEMUX (GST_PAD_PARENT (pad));
5143
5144   switch (avi->state) {
5145     case GST_AVI_DEMUX_START:
5146       res = gst_avi_demux_stream_init_pull (avi);
5147       if (G_UNLIKELY (res != GST_FLOW_OK)) {
5148         GST_WARNING ("stream_init flow: %s", gst_flow_get_name (res));
5149         goto pause;
5150       }
5151       avi->state = GST_AVI_DEMUX_HEADER;
5152       /* fall-through */
5153     case GST_AVI_DEMUX_HEADER:
5154       res = gst_avi_demux_stream_header_pull (avi);
5155       if (G_UNLIKELY (res != GST_FLOW_OK)) {
5156         GST_WARNING ("stream_header flow: %s", gst_flow_get_name (res));
5157         goto pause;
5158       }
5159       avi->state = GST_AVI_DEMUX_MOVI;
5160       break;
5161     case GST_AVI_DEMUX_MOVI:
5162       if (G_UNLIKELY (avi->close_seg_event)) {
5163         gst_avi_demux_push_event (avi, avi->close_seg_event);
5164         avi->close_seg_event = NULL;
5165       }
5166       if (G_UNLIKELY (avi->seg_event)) {
5167         gst_avi_demux_push_event (avi, avi->seg_event);
5168         avi->seg_event = NULL;
5169       }
5170       if (G_UNLIKELY (avi->got_tags)) {
5171         push_tag_lists (avi);
5172       }
5173       /* process each index entry in turn */
5174       res = gst_avi_demux_loop_data (avi);
5175
5176       /* pause when error */
5177       if (G_UNLIKELY (res != GST_FLOW_OK)) {
5178         GST_INFO ("stream_movi flow: %s", gst_flow_get_name (res));
5179         goto pause;
5180       }
5181       break;
5182     default:
5183       GST_ERROR_OBJECT (avi, "unknown state %d", avi->state);
5184       res = GST_FLOW_ERROR;
5185       goto pause;
5186   }
5187
5188   return;
5189
5190   /* ERRORS */
5191 pause:{
5192
5193     gboolean push_eos = FALSE;
5194     GST_LOG_OBJECT (avi, "pausing task, reason %s", gst_flow_get_name (res));
5195     avi->segment_running = FALSE;
5196     gst_pad_pause_task (avi->sinkpad);
5197
5198
5199     if (res == GST_FLOW_UNEXPECTED) {
5200       /* handle end-of-stream/segment */
5201       if (avi->segment.flags & GST_SEEK_FLAG_SEGMENT) {
5202         gint64 stop;
5203
5204         if ((stop = avi->segment.stop) == -1)
5205           stop = avi->segment.duration;
5206
5207         GST_INFO_OBJECT (avi, "sending segment_done");
5208
5209         gst_element_post_message
5210             (GST_ELEMENT_CAST (avi),
5211             gst_message_new_segment_done (GST_OBJECT_CAST (avi),
5212                 GST_FORMAT_TIME, stop));
5213       } else {
5214         push_eos = TRUE;
5215       }
5216     } else if (res == GST_FLOW_NOT_LINKED || res < GST_FLOW_UNEXPECTED) {
5217       /* for fatal errors we post an error message, wrong-state is
5218        * not fatal because it happens due to flushes and only means
5219        * that we should stop now. */
5220       GST_ELEMENT_ERROR (avi, STREAM, FAILED,
5221           (_("Internal data stream error.")),
5222           ("streaming stopped, reason %s", gst_flow_get_name (res)));
5223       push_eos = TRUE;
5224     }
5225     if (push_eos) {
5226       GST_INFO_OBJECT (avi, "sending eos");
5227       if (!gst_avi_demux_push_event (avi, gst_event_new_eos ()) &&
5228           (res == GST_FLOW_UNEXPECTED)) {
5229         GST_ELEMENT_ERROR (avi, STREAM, DEMUX,
5230             (NULL), ("got eos but no streams (yet)"));
5231       }
5232     }
5233   }
5234 }
5235
5236
5237 static GstFlowReturn
5238 gst_avi_demux_chain (GstPad * pad, GstBuffer * buf)
5239 {
5240   GstFlowReturn res;
5241   GstAviDemux *avi = GST_AVI_DEMUX (GST_PAD_PARENT (pad));
5242   gint i;
5243
5244   if (GST_BUFFER_IS_DISCONT (buf)) {
5245     GST_DEBUG_OBJECT (avi, "got DISCONT");
5246     gst_adapter_clear (avi->adapter);
5247     /* mark all streams DISCONT */
5248     for (i = 0; i < avi->num_streams; i++)
5249       avi->stream[i].discont = TRUE;
5250   }
5251
5252   GST_DEBUG ("Store %d bytes in adapter", gst_buffer_get_size (buf));
5253   gst_adapter_push (avi->adapter, buf);
5254
5255   switch (avi->state) {
5256     case GST_AVI_DEMUX_START:
5257       if ((res = gst_avi_demux_stream_init_push (avi)) != GST_FLOW_OK) {
5258         GST_WARNING ("stream_init flow: %s", gst_flow_get_name (res));
5259         break;
5260       }
5261       break;
5262     case GST_AVI_DEMUX_HEADER:
5263       if ((res = gst_avi_demux_stream_header_push (avi)) != GST_FLOW_OK) {
5264         GST_WARNING ("stream_header flow: %s", gst_flow_get_name (res));
5265         break;
5266       }
5267       break;
5268     case GST_AVI_DEMUX_MOVI:
5269       if (G_UNLIKELY (avi->close_seg_event)) {
5270         gst_avi_demux_push_event (avi, avi->close_seg_event);
5271         avi->close_seg_event = NULL;
5272       }
5273       if (G_UNLIKELY (avi->seg_event)) {
5274         gst_avi_demux_push_event (avi, avi->seg_event);
5275         avi->seg_event = NULL;
5276       }
5277       if (G_UNLIKELY (avi->got_tags)) {
5278         push_tag_lists (avi);
5279       }
5280       res = gst_avi_demux_stream_data (avi);
5281       break;
5282     case GST_AVI_DEMUX_SEEK:
5283     {
5284       GstEvent *event;
5285
5286       res = GST_FLOW_OK;
5287
5288       /* obtain and parse indexes */
5289       if (avi->stream[0].indexes && !gst_avi_demux_read_subindexes_push (avi))
5290         /* seek in subindex read function failed */
5291         goto index_failed;
5292
5293       if (!avi->stream[0].indexes && !avi->have_index
5294           && avi->avih->flags & GST_RIFF_AVIH_HASINDEX)
5295         gst_avi_demux_stream_index_push (avi);
5296
5297       if (avi->have_index) {
5298         /* use the indexes now to construct nice durations */
5299         gst_avi_demux_calculate_durations_from_index (avi);
5300       } else {
5301         /* still parsing indexes */
5302         break;
5303       }
5304
5305       GST_OBJECT_LOCK (avi);
5306       event = avi->seek_event;
5307       avi->seek_event = NULL;
5308       GST_OBJECT_UNLOCK (avi);
5309
5310       /* calculate and perform seek */
5311       if (!avi_demux_handle_seek_push (avi, avi->sinkpad, event))
5312         goto seek_failed;
5313
5314       gst_event_unref (event);
5315       avi->state = GST_AVI_DEMUX_MOVI;
5316       break;
5317     }
5318     default:
5319       GST_ELEMENT_ERROR (avi, STREAM, FAILED, (NULL),
5320           ("Illegal internal state"));
5321       res = GST_FLOW_ERROR;
5322       break;
5323   }
5324
5325   GST_DEBUG_OBJECT (avi, "state: %d res:%s", avi->state,
5326       gst_flow_get_name (res));
5327
5328   if (G_UNLIKELY (avi->abort_buffering))
5329     goto abort_buffering;
5330
5331   return res;
5332
5333   /* ERRORS */
5334 index_failed:
5335   {
5336     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("failed to read indexes"));
5337     return GST_FLOW_ERROR;
5338   }
5339 seek_failed:
5340   {
5341     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("push mode seek failed"));
5342     return GST_FLOW_ERROR;
5343   }
5344 abort_buffering:
5345   {
5346     avi->abort_buffering = FALSE;
5347     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("unhandled buffer size"));
5348     return GST_FLOW_ERROR;
5349   }
5350 }
5351
5352 static gboolean
5353 gst_avi_demux_sink_activate (GstPad * sinkpad)
5354 {
5355   if (gst_pad_check_pull_range (sinkpad)) {
5356     GST_DEBUG ("going to pull mode");
5357     return gst_pad_activate_pull (sinkpad, TRUE);
5358   } else {
5359     GST_DEBUG ("going to push (streaming) mode");
5360     return gst_pad_activate_push (sinkpad, TRUE);
5361   }
5362 }
5363
5364 static gboolean
5365 gst_avi_demux_sink_activate_pull (GstPad * sinkpad, gboolean active)
5366 {
5367   GstAviDemux *avi = GST_AVI_DEMUX (GST_OBJECT_PARENT (sinkpad));
5368
5369   if (active) {
5370     avi->segment_running = TRUE;
5371     avi->streaming = FALSE;
5372     return gst_pad_start_task (sinkpad, (GstTaskFunction) gst_avi_demux_loop,
5373         sinkpad);
5374   } else {
5375     avi->segment_running = FALSE;
5376     return gst_pad_stop_task (sinkpad);
5377   }
5378 }
5379
5380 static gboolean
5381 gst_avi_demux_activate_push (GstPad * pad, gboolean active)
5382 {
5383   GstAviDemux *avi = GST_AVI_DEMUX (GST_OBJECT_PARENT (pad));
5384
5385   if (active) {
5386     GST_DEBUG ("avi: activating push/chain function");
5387     avi->streaming = TRUE;
5388 #if 0
5389     /* create index for some push based seeking if not provided */
5390     GST_OBJECT_LOCK (avi);
5391     if (!avi->element_index) {
5392       GST_DEBUG_OBJECT (avi, "creating index");
5393       avi->element_index = gst_index_factory_make ("memindex");
5394     }
5395     GST_OBJECT_UNLOCK (avi);
5396     /* object lock might be taken again */
5397     gst_index_get_writer_id (avi->element_index, GST_OBJECT_CAST (avi),
5398         &avi->index_id);
5399 #endif
5400   } else {
5401     GST_DEBUG ("avi: deactivating push/chain function");
5402   }
5403
5404   return TRUE;
5405 }
5406
5407 static void
5408 gst_avi_demux_set_index (GstElement * element, GstIndex * index)
5409 {
5410   GstAviDemux *avi = GST_AVI_DEMUX (element);
5411
5412   GST_OBJECT_LOCK (avi);
5413   if (avi->element_index)
5414     gst_object_unref (avi->element_index);
5415   if (index) {
5416     avi->element_index = gst_object_ref (index);
5417   } else {
5418     avi->element_index = NULL;
5419   }
5420   GST_OBJECT_UNLOCK (avi);
5421   /* object lock might be taken again */
5422   if (index)
5423     gst_index_get_writer_id (index, GST_OBJECT_CAST (element), &avi->index_id);
5424   GST_DEBUG_OBJECT (avi, "Set index %" GST_PTR_FORMAT, avi->element_index);
5425 }
5426
5427 static GstIndex *
5428 gst_avi_demux_get_index (GstElement * element)
5429 {
5430   GstIndex *result = NULL;
5431   GstAviDemux *avi = GST_AVI_DEMUX (element);
5432
5433   GST_OBJECT_LOCK (avi);
5434   if (avi->element_index)
5435     result = gst_object_ref (avi->element_index);
5436   GST_OBJECT_UNLOCK (avi);
5437
5438   GST_DEBUG_OBJECT (avi, "Returning index %" GST_PTR_FORMAT, result);
5439
5440   return result;
5441 }
5442
5443 static GstStateChangeReturn
5444 gst_avi_demux_change_state (GstElement * element, GstStateChange transition)
5445 {
5446   GstStateChangeReturn ret;
5447   GstAviDemux *avi = GST_AVI_DEMUX (element);
5448
5449   switch (transition) {
5450     case GST_STATE_CHANGE_READY_TO_PAUSED:
5451       avi->streaming = FALSE;
5452       gst_segment_init (&avi->segment, GST_FORMAT_TIME);
5453       break;
5454     default:
5455       break;
5456   }
5457
5458   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
5459   if (ret == GST_STATE_CHANGE_FAILURE)
5460     goto done;
5461
5462   switch (transition) {
5463     case GST_STATE_CHANGE_PAUSED_TO_READY:
5464       avi->have_index = FALSE;
5465       gst_avi_demux_reset (avi);
5466       break;
5467     default:
5468       break;
5469   }
5470
5471 done:
5472   return ret;
5473 }