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