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