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