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