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