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