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