avidemux: Replace deprecated GST_DISABLE_DEBUG with correct macro. Fixes #587826
[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_GST_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
1870     _entry = &((gst_riff_index_entry *) data)[i];
1871     entry.id = GST_READ_UINT32_LE (&_entry->id);
1872     entry.offset = GST_READ_UINT32_LE (&_entry->offset);
1873     entry.flags = GST_READ_UINT32_LE (&_entry->flags);
1874     entry.size = GST_READ_UINT32_LE (&_entry->size);
1875     target = &entries[n];
1876
1877     if (entry.id == GST_RIFF_rec || entry.id == 0 ||
1878         (entry.offset == 0 && n > 0))
1879       continue;
1880
1881     stream_nr = CHUNKID_TO_STREAMNR (entry.id);
1882     if (stream_nr >= avi->num_streams) {
1883       GST_WARNING_OBJECT (avi,
1884           "Index entry %d has invalid stream nr %d", i, stream_nr);
1885       continue;
1886     }
1887     target->stream_nr = stream_nr;
1888     stream = &avi->stream[stream_nr];
1889
1890     if (!stream->strh) {
1891       GST_WARNING_OBJECT (avi, "Unhandled stream %d, skipping", stream_nr);
1892       continue;
1893     }
1894
1895     target->index_nr = i;
1896     target->flags =
1897         (entry.flags & GST_RIFF_IF_KEYFRAME) ? GST_AVI_INDEX_ENTRY_FLAG_KEYFRAME
1898         : 0;
1899     target->size = entry.size;
1900     target->offset = entry.offset + 8;
1901
1902     /* figure out if the index is 0 based or relative to the MOVI start */
1903     if (n == 0) {
1904       if (target->offset < pos_before)
1905         avi->index_offset = pos_before + 8;
1906       else
1907         avi->index_offset = 0;
1908       GST_DEBUG ("index_offset = %" G_GUINT64_FORMAT, avi->index_offset);
1909     }
1910
1911     if (stream->strh->type == GST_RIFF_FCC_auds) {
1912       /* all audio frames are keyframes */
1913       target->flags |= GST_AVI_INDEX_ENTRY_FLAG_KEYFRAME;
1914     }
1915 #ifndef GST_DISABLE_GST_DEBUG
1916     if (target->flags & GST_AVI_INDEX_ENTRY_FLAG_KEYFRAME)
1917       _nr_keyframes++;
1918 #endif
1919
1920     /* stream duration unknown, now we can calculate it */
1921     if (stream->idx_duration == -1)
1922       stream->idx_duration = 0;
1923
1924     /* timestamps */
1925     target->ts = stream->idx_duration;
1926     if (stream->is_vbr) {
1927       /* VBR stream next timestamp */
1928       if (stream->strh->type == GST_RIFF_FCC_auds) {
1929         next_ts = avi_stream_convert_frames_to_time_unchecked (stream,
1930             stream->total_blocks + 1);
1931       } else {
1932         next_ts = avi_stream_convert_frames_to_time_unchecked (stream,
1933             stream->total_frames + 1);
1934       }
1935     } else {
1936       /* constant rate stream */
1937       next_ts = avi_stream_convert_bytes_to_time_unchecked (stream,
1938           stream->total_bytes + target->size);
1939     }
1940     /* duration is next - current */
1941     target->dur = next_ts - target->ts;
1942
1943     /* stream position */
1944     target->bytes_before = stream->total_bytes;
1945     target->frames_before = stream->total_frames;
1946
1947     stream->total_bytes += target->size;
1948     stream->total_frames++;
1949     if (stream->strh->type == GST_RIFF_FCC_auds) {
1950       if (stream->strf.auds->blockalign > 0)
1951         stream->total_blocks +=
1952             (target->size + stream->strf.auds->blockalign -
1953             1) / stream->strf.auds->blockalign;
1954       else
1955         stream->total_blocks++;
1956     }
1957     stream->idx_duration = next_ts;
1958
1959     GST_LOG_OBJECT (avi,
1960         "Adding index entry %d (%6u), flags %02x, stream %d, size %u "
1961         ", offset %" G_GUINT64_FORMAT ", time %" GST_TIME_FORMAT ", dur %"
1962         GST_TIME_FORMAT,
1963         target->index_nr, stream->total_frames - 1, target->flags,
1964         target->stream_nr, target->size, target->offset,
1965         GST_TIME_ARGS (target->ts), GST_TIME_ARGS (target->dur));
1966     entries_list = g_list_prepend (entries_list, target);
1967
1968     n++;
1969   }
1970
1971   GST_INFO ("Parsed index, %6d entries, %5ld keyframes, entry size = %2d, "
1972       "total size = %10d", num, _nr_keyframes,
1973       (gint) sizeof (gst_avi_index_entry),
1974       (gint) (num * sizeof (gst_avi_index_entry)));
1975
1976   gst_buffer_unref (buf);
1977
1978   if (n > 0) {
1979     *_entries_list = g_list_reverse (entries_list);
1980   } else {
1981     g_free (entries);
1982   }
1983   return;
1984
1985   /* ERRORS */
1986 out_of_mem:
1987   {
1988     GST_ELEMENT_ERROR (avi, RESOURCE, NO_SPACE_LEFT, (NULL),
1989         ("Cannot allocate memory for %u*%u=%u bytes",
1990             (guint) sizeof (gst_avi_index_entry), num,
1991             (guint) sizeof (gst_avi_index_entry) * num));
1992     gst_buffer_unref (buf);
1993   }
1994 }
1995
1996 /*
1997  * gst_avi_demux_stream_index:
1998  * @avi: avi demuxer object.
1999  * @index: list of index entries, returned by this function.
2000  * @alloc_list: list of allocated data, returned by this function.
2001  *
2002  * Seeks to index and reads it.
2003  */
2004 static void
2005 gst_avi_demux_stream_index (GstAviDemux * avi,
2006     GList ** index, GList ** alloc_list)
2007 {
2008   GstFlowReturn res;
2009   guint64 offset = avi->offset;
2010   GstBuffer *buf;
2011   guint32 tag;
2012   guint32 size;
2013   gint i;
2014
2015   GST_DEBUG ("demux stream index at offset %" G_GUINT64_FORMAT, offset);
2016
2017   *alloc_list = NULL;
2018   *index = NULL;
2019
2020   /* get chunk information */
2021   res = gst_pad_pull_range (avi->sinkpad, offset, 8, &buf);
2022   if (res != GST_FLOW_OK)
2023     goto pull_failed;
2024   else if (GST_BUFFER_SIZE (buf) < 8)
2025     goto too_small;
2026
2027   /* check tag first before blindy trying to read 'size' bytes */
2028   tag = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf));
2029   size = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf) + 4);
2030   if (tag == GST_RIFF_TAG_LIST) {
2031     /* this is the movi tag */
2032     GST_DEBUG_OBJECT (avi, "skip LIST chunk, size %" G_GUINT32_FORMAT,
2033         (8 + ((size + 1) & ~1)));
2034     offset += 8 + ((size + 1) & ~1);
2035     gst_buffer_unref (buf);
2036     res = gst_pad_pull_range (avi->sinkpad, offset, 8, &buf);
2037     if (res != GST_FLOW_OK)
2038       goto pull_failed;
2039     else if (GST_BUFFER_SIZE (buf) < 8)
2040       goto too_small;
2041     tag = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf));
2042     size = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf) + 4);
2043   }
2044
2045   if (tag != GST_RIFF_TAG_idx1)
2046     goto no_index;
2047   if (!size)
2048     goto zero_index;
2049
2050   gst_buffer_unref (buf);
2051
2052   GST_DEBUG ("index found at offset %" G_GUINT64_FORMAT, offset);
2053
2054   /* read chunk, advance offset */
2055   if (gst_riff_read_chunk (GST_ELEMENT_CAST (avi),
2056           avi->sinkpad, &offset, &tag, &buf) != GST_FLOW_OK)
2057     return;
2058
2059   GST_INFO ("will parse index chunk size %u for tag %"
2060       GST_FOURCC_FORMAT, GST_BUFFER_SIZE (buf), GST_FOURCC_ARGS (tag));
2061
2062   gst_avi_demux_parse_index (avi, buf, index);
2063   if (*index)
2064     *alloc_list = g_list_append (*alloc_list, (*index)->data);
2065
2066   /* debug our indexes */
2067   for (i = 0; i < avi->num_streams; i++) {
2068     avi_stream_context *stream;
2069
2070     stream = &avi->stream[i];
2071     GST_DEBUG_OBJECT (avi, "stream %u: %u frames, %" G_GINT64_FORMAT " bytes",
2072         i, stream->total_frames, stream->total_bytes);
2073   }
2074   return;
2075
2076   /* ERRORS */
2077 pull_failed:
2078   {
2079     GST_DEBUG_OBJECT (avi,
2080         "pull range failed: pos=%" G_GUINT64_FORMAT " size=8", offset);
2081     return;
2082   }
2083 too_small:
2084   {
2085     GST_DEBUG_OBJECT (avi, "Buffer is too small");
2086     gst_buffer_unref (buf);
2087     return;
2088   }
2089 no_index:
2090   {
2091     GST_WARNING_OBJECT (avi,
2092         "No index data (idx1) after movi chunk, but %" GST_FOURCC_FORMAT,
2093         GST_FOURCC_ARGS (tag));
2094     gst_buffer_unref (buf);
2095     return;
2096   }
2097 zero_index:
2098   {
2099     GST_WARNING_OBJECT (avi, "Empty index data (idx1) after movi chunk");
2100     gst_buffer_unref (buf);
2101     return;
2102   }
2103 }
2104
2105 #if 0
2106 /*
2107  * Sync to next data chunk.
2108  */
2109 static gboolean
2110 gst_avi_demux_skip (GstAviDemux * avi, gboolean prevent_eos)
2111 {
2112   GstRiffRead *riff = GST_RIFF_READ (avi);
2113
2114   if (prevent_eos) {
2115     guint64 pos, length;
2116     guint size;
2117     guint8 *data;
2118
2119     pos = gst_bytestream_tell (riff->bs);
2120     length = gst_bytestream_length (riff->bs);
2121
2122     if (pos + 8 > length)
2123       return FALSE;
2124
2125     if (gst_bytestream_peek_bytes (riff->bs, &data, 8) != 8)
2126       return FALSE;
2127
2128     size = GST_READ_UINT32_LE (&data[4]);
2129     if (size & 1)
2130       size++;
2131
2132     /* Note, we're going to skip which might involve seeks. Therefore,
2133      * we need 1 byte more! */
2134     if (pos + 8 + size >= length)
2135       return FALSE;
2136   }
2137
2138   return gst_riff_read_skip (riff);
2139 }
2140
2141 static gboolean
2142 gst_avi_demux_sync (GstAviDemux * avi, guint32 * ret_tag, gboolean prevent_eos)
2143 {
2144   GstRiffRead *riff = GST_RIFF_READ (avi);
2145   guint32 tag;
2146   guint64 length = gst_bytestream_length (riff->bs);
2147
2148   if (prevent_eos && gst_bytestream_tell (riff->bs) + 12 >= length)
2149     return FALSE;
2150
2151   /* peek first (for the end of this 'list/movi' section) */
2152   if (!(tag = gst_riff_peek_tag (riff, &avi->level_up)))
2153     return FALSE;
2154
2155   /* if we're at top-level, we didn't read the 'movi'
2156    * list tag yet. This can also be 'AVIX' in case of
2157    * openDML-2.0 AVI files. Lastly, it might be idx1,
2158    * in which case we skip it so we come at EOS. */
2159   while (1) {
2160     if (prevent_eos && gst_bytestream_tell (riff->bs) + 12 >= length)
2161       return FALSE;
2162
2163     if (!(tag = gst_riff_peek_tag (riff, NULL)))
2164       return FALSE;
2165
2166     switch (tag) {
2167       case GST_RIFF_TAG_LIST:
2168         if (!(tag = gst_riff_peek_list (riff)))
2169           return FALSE;
2170
2171         switch (tag) {
2172           case GST_RIFF_LIST_AVIX:
2173             if (!gst_riff_read_list (riff, &tag))
2174               return FALSE;
2175             break;
2176
2177           case GST_RIFF_LIST_movi:
2178             if (!gst_riff_read_list (riff, &tag))
2179               return FALSE;
2180             /* fall-through */
2181
2182           case GST_RIFF_rec:
2183             goto done;
2184
2185           default:
2186             GST_WARNING ("Unknown list %" GST_FOURCC_FORMAT " before AVI data",
2187                 GST_FOURCC_ARGS (tag));
2188             /* fall-through */
2189
2190           case GST_RIFF_TAG_JUNK:
2191             if (!gst_avi_demux_skip (avi, prevent_eos))
2192               return FALSE;
2193             break;
2194         }
2195         break;
2196
2197       default:
2198         if ((tag & 0xff) >= '0' && (tag & 0xff) <= '9' &&
2199             ((tag >> 8) & 0xff) >= '0' && ((tag >> 8) & 0xff) <= '9') {
2200           goto done;
2201         }
2202         /* pass-through */
2203
2204       case GST_RIFF_TAG_idx1:
2205       case GST_RIFF_TAG_JUNK:
2206         if (!gst_avi_demux_skip (avi, prevent_eos)) {
2207           return FALSE;
2208         }
2209         break;
2210     }
2211   }
2212 done:
2213   /* And then, we get the data */
2214   if (prevent_eos && gst_bytestream_tell (riff->bs) + 12 >= length)
2215     return FALSE;
2216
2217   if (!(tag = gst_riff_peek_tag (riff, NULL)))
2218     return FALSE;
2219
2220   /* Support for rec-list files */
2221   switch (tag) {
2222     case GST_RIFF_TAG_LIST:
2223       if (!(tag = gst_riff_peek_list (riff)))
2224         return FALSE;
2225       if (tag == GST_RIFF_rec) {
2226         /* Simply skip the list */
2227         if (!gst_riff_read_list (riff, &tag))
2228           return FALSE;
2229         if (!(tag = gst_riff_peek_tag (riff, NULL)))
2230           return FALSE;
2231       }
2232       break;
2233
2234     case GST_RIFF_TAG_JUNK:
2235       gst_avi_demux_skip (avi, prevent_eos);
2236       return FALSE;
2237   }
2238
2239   if (ret_tag)
2240     *ret_tag = tag;
2241
2242   return TRUE;
2243 }
2244 #endif
2245
2246 /*
2247  * gst_avi_demux_peek_tag:
2248  *
2249  * Returns the tag and size of the next chunk
2250  */
2251 static GstFlowReturn
2252 gst_avi_demux_peek_tag (GstAviDemux * avi, guint64 offset, guint32 * tag,
2253     guint * size)
2254 {
2255   GstFlowReturn res = GST_FLOW_OK;
2256   GstBuffer *buf = NULL;
2257   guint bufsize;
2258
2259   res = gst_pad_pull_range (avi->sinkpad, offset, 8, &buf);
2260   if (res != GST_FLOW_OK)
2261     goto pull_failed;
2262
2263   bufsize = GST_BUFFER_SIZE (buf);
2264   if (bufsize != 8)
2265     goto wrong_size;
2266
2267   *tag = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf));
2268   *size = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf) + 4);
2269
2270   GST_LOG_OBJECT (avi, "Tag[%" GST_FOURCC_FORMAT "] (size:%d) %"
2271       G_GINT64_FORMAT " -- %" G_GINT64_FORMAT, GST_FOURCC_ARGS (*tag),
2272       *size, offset + 8, offset + 8 + (gint64) * size);
2273 done:
2274   gst_buffer_unref (buf);
2275
2276   return res;
2277
2278   /* ERRORS */
2279 pull_failed:
2280   {
2281     GST_DEBUG_OBJECT (avi, "pull_ranged returned %s", gst_flow_get_name (res));
2282     return res;
2283   }
2284 wrong_size:
2285   {
2286     GST_DEBUG_OBJECT (avi, "got %d bytes which is <> 8 bytes", bufsize);
2287     res = GST_FLOW_ERROR;
2288     goto done;
2289   }
2290 }
2291
2292 /*
2293  * gst_avi_demux_next_data_buffer:
2294  *
2295  * Returns the offset and size of the next buffer
2296  * Position is the position of the buffer (after tag and size)
2297  */
2298 static GstFlowReturn
2299 gst_avi_demux_next_data_buffer (GstAviDemux * avi, guint64 * offset,
2300     guint32 * tag, guint * size)
2301 {
2302   guint64 off = *offset;
2303   guint _size = 0;
2304   GstFlowReturn res;
2305
2306   do {
2307     res = gst_avi_demux_peek_tag (avi, off, tag, &_size);
2308     if (res != GST_FLOW_OK)
2309       break;
2310     if (*tag == GST_RIFF_TAG_LIST)
2311       off += 8 + 4;             /* skip tag + size + subtag */
2312     else {
2313       *offset = off + 8;
2314       *size = _size;
2315       break;
2316     }
2317   } while (TRUE);
2318
2319   return res;
2320 }
2321
2322 /*
2323  * gst_avi_demux_stream_scan:
2324  * @avi: calling element (used for debugging/errors).
2325  * @index: list of index entries, returned by this function.
2326  * @alloc_list: list of allocated data, returned by this function.
2327  *
2328  * Scan the file for all chunks to "create" a new index.
2329  * Return value indicates if we can continue reading the stream. It
2330  * does not say anything about whether we created an index.
2331  *
2332  * pull-range based
2333  */
2334 static gboolean
2335 gst_avi_demux_stream_scan (GstAviDemux * avi,
2336     GList ** index, GList ** alloc_list)
2337 {
2338   GstFlowReturn res;
2339   gst_avi_index_entry *entry, *entries = NULL;
2340   avi_stream_context *stream;
2341   GstFormat format;
2342   guint64 pos = avi->offset;
2343   guint64 length;
2344   gint64 tmplength;
2345   guint32 tag = 0;
2346   GList *list = NULL;
2347   guint index_size = 0;
2348
2349   /* FIXME:
2350    * - implement non-seekable source support.
2351    */
2352   GST_DEBUG_OBJECT (avi,
2353       "Creating index %s existing index, starting at offset %" G_GUINT64_FORMAT,
2354       ((*index) ? "with" : "without"), pos);
2355
2356   format = GST_FORMAT_BYTES;
2357   if (!gst_pad_query_peer_duration (avi->sinkpad, &format, &tmplength))
2358     return FALSE;
2359
2360   length = tmplength;
2361
2362   if (*index) {
2363     entry = g_list_last (*index)->data;
2364     pos = entry->offset + avi->index_offset + entry->size;
2365     if (entry->size & 1)
2366       pos++;
2367
2368     if (pos >= length) {
2369       GST_LOG_OBJECT (avi, "Complete index, we're done");
2370       return TRUE;
2371     }
2372
2373     GST_LOG_OBJECT (avi, "Incomplete index, seeking to last valid entry @ %"
2374         G_GUINT64_FORMAT " of %" G_GUINT64_FORMAT " (%"
2375         G_GUINT64_FORMAT "+%u)", pos, length, entry->offset, entry->size);
2376   }
2377
2378   while (TRUE) {
2379     guint stream_nr;
2380     guint size = 0;
2381
2382     res = gst_avi_demux_next_data_buffer (avi, &pos, &tag, &size);
2383     if (G_UNLIKELY (res != GST_FLOW_OK))
2384       break;
2385
2386     /* check valid stream */
2387     stream_nr = CHUNKID_TO_STREAMNR (tag);
2388     if (G_UNLIKELY (stream_nr >= avi->num_streams)) {
2389       GST_WARNING_OBJECT (avi,
2390           "Index entry has invalid stream nr %d", stream_nr);
2391       goto next;
2392     }
2393
2394     stream = &avi->stream[stream_nr];
2395     if (G_UNLIKELY (stream->pad == NULL)) {
2396       GST_WARNING_OBJECT (avi,
2397           "Stream %d does not have an output pad, can't create new index",
2398           stream_nr);
2399       goto next;
2400     }
2401
2402     /* pre-allocate */
2403     if (G_UNLIKELY (index_size % 1024 == 0)) {
2404       entries = g_new (gst_avi_index_entry, 1024);
2405       *alloc_list = g_list_prepend (*alloc_list, entries);
2406     }
2407     entry = &entries[index_size % 1024];
2408
2409     entry->index_nr = index_size++;
2410     entry->stream_nr = stream_nr;
2411     entry->flags = GST_AVI_INDEX_ENTRY_FLAG_KEYFRAME;
2412     entry->offset = pos - avi->index_offset;
2413     entry->size = size;
2414
2415     /* timestamps, get timestamps of two consecutive frames to calculate
2416      * timestamp and duration. */
2417     format = GST_FORMAT_TIME;
2418     if (stream->is_vbr) {
2419       /* VBR stream */
2420       entry->ts = avi_stream_convert_frames_to_time_unchecked (stream,
2421           stream->total_frames);
2422       entry->dur = avi_stream_convert_frames_to_time_unchecked (stream,
2423           stream->total_frames + 1);
2424     } else {
2425       /* constant rate stream */
2426       entry->ts = avi_stream_convert_bytes_to_time_unchecked (stream,
2427           stream->total_bytes);
2428       entry->dur = avi_stream_convert_bytes_to_time_unchecked (stream,
2429           stream->total_bytes + entry->size);
2430     }
2431     entry->dur -= entry->ts;
2432
2433     /* stream position */
2434     entry->bytes_before = stream->total_bytes;
2435     stream->total_bytes += entry->size;
2436     entry->frames_before = stream->total_frames;
2437     stream->total_frames++;
2438     stream->idx_duration = entry->ts + entry->dur;
2439
2440     list = g_list_prepend (list, entry);
2441     GST_DEBUG_OBJECT (avi, "Added index entry %d (in stream: %d), offset %"
2442         G_GUINT64_FORMAT ", time %" GST_TIME_FORMAT " for stream %d",
2443         index_size - 1, entry->frames_before, entry->offset,
2444         GST_TIME_ARGS (entry->ts), entry->stream_nr);
2445
2446   next:
2447     /* update position */
2448     pos += GST_ROUND_UP_2 (size);
2449     if (G_UNLIKELY (pos > length)) {
2450       GST_WARNING_OBJECT (avi,
2451           "Stopping index lookup since we are further than EOF");
2452       break;
2453     }
2454   }
2455
2456   /* FIXME: why is this disabled */
2457 #if 0
2458   while (gst_avi_demux_sync (avi, &tag, TRUE)) {
2459     guint stream_nr = CHUNKID_TO_STREAMNR (tag);
2460     guint8 *data;
2461     GstFormat format = GST_FORMAT_TIME;
2462
2463     if (stream_nr >= avi->num_streams)
2464       goto next;
2465     stream = &avi->stream[stream_nr];
2466
2467     /* get chunk size */
2468     if (gst_bytestream_peek_bytes (riff->bs, &data, 8) != 8)
2469       goto next;
2470
2471     /* fill in */
2472     entry->index_nr = index_size++;
2473     entry->stream_nr = stream_nr;
2474     entry->flags = GST_AVI_INDEX_ENTRY_FLAG_KEYFRAME;
2475     entry->offset = gst_bytestream_tell (riff->bs) + 8 - avi->index_offset;
2476     entry->size = GST_READ_UINT32_LE (&data[4]);
2477
2478     /* timestamps */
2479     if (stream->is_vbr) {
2480       /* VBR stream */
2481       entry->ts = avi_stream_convert_frames_to_time_unchecked (stream,
2482           stream->total_frames);
2483       entry->dur = avi_stream_convert_frames_to_time_unchecked (stream,
2484           stream->total_frames + 1);
2485     } else {
2486       /* constant rate stream */
2487       entry->ts = avi_stream_convert_bytes_to_time_unchecked (stream,
2488           stream->total_bytes);
2489       entry->dur = avi_stream_convert_bytes_to_time_unchecked (stream,
2490           stream->total_bytes + entry->size);
2491     }
2492     entry->dur -= entry->ts;
2493
2494     /* stream position */
2495     entry->bytes_before = stream->total_bytes;
2496     stream->total_bytes += entry->size;
2497     entry->frames_before = stream->total_frames;
2498     stream->total_frames++;
2499
2500     list = g_list_prepend (list, entry);
2501     GST_DEBUG_OBJECT (avi, "Added index entry %d (in stream: %d), offset %"
2502         G_GUINT64_FORMAT ", time %" GST_TIME_FORMAT " for stream %d",
2503         index_size - 1, entry->frames_before, entry->offset,
2504         GST_TIME_ARGS (entry->ts), entry->stream_nr);
2505
2506   next:
2507     if (!gst_avi_demux_skip (avi, TRUE))
2508       break;
2509   }
2510   /* seek back */
2511   if (!(event = gst_riff_read_seek (riff, pos))) {
2512     g_list_free (list);
2513     return FALSE;
2514   }
2515   gst_event_unref (event);
2516
2517 #endif
2518
2519   GST_DEBUG_OBJECT (avi, "index created, %d items", index_size);
2520
2521   *index = g_list_concat (*index, g_list_reverse (list));
2522
2523   return TRUE;
2524 }
2525
2526 /*
2527  * gst_avi_demux_massage_index:
2528  * @avi: calling element (used for debugging/errors).
2529  *
2530  * We're going to go over each entry in the index and finetune
2531  * some things we don't like about AVI. For example, a single
2532  * chunk might be too long. Also, individual streams might be
2533  * out-of-sync. In the first case, we cut the chunk in several
2534  * smaller pieces. In the second case, we re-order chunk reading
2535  * order. The end result should be a smoother playing AVI.
2536  */
2537 static gboolean
2538 gst_avi_demux_massage_index (GstAviDemux * avi,
2539     GList * list, GList * alloc_list)
2540 {
2541   gst_avi_index_entry *entry;
2542   avi_stream_context *stream;
2543   guint i;
2544   GList *node;
2545   gint64 delay = G_GINT64_CONSTANT (0);
2546
2547   GST_LOG_OBJECT (avi, "Starting index massage, nr_entries = %d",
2548       list ? g_list_length (list) : 0);
2549
2550   if (list) {
2551 #ifndef GST_DISABLE_GST_DEBUG
2552     guint num_added_total = 0;
2553     guint num_per_stream[GST_AVI_DEMUX_MAX_STREAMS] = { 0, };
2554 #endif
2555     GST_LOG_OBJECT (avi,
2556         "I'm now going to cut large chunks into smaller pieces");
2557
2558     /* cut chunks in small (seekable) pieces
2559      * FIXME: this should be a property where a value of
2560      * GST_CLOCK_TIME_NONE would disable the chunking
2561      */
2562 #define MAX_DURATION (GST_SECOND / 2)
2563     for (i = 0; i < avi->num_streams; i++) {
2564       /* only chop streams that have exactly *one* chunk */
2565       if (avi->stream[i].total_frames != 1)
2566         continue;
2567
2568       for (node = list; node != NULL; node = node->next) {
2569         entry = node->data;
2570
2571         if (entry->stream_nr != i)
2572           continue;
2573
2574         /* check for max duration of a single buffer. I suppose that
2575          * the allocation of index entries could be improved. */
2576         stream = &avi->stream[entry->stream_nr];
2577         if (entry->dur > MAX_DURATION
2578             && stream->strh->type == GST_RIFF_FCC_auds) {
2579           guint32 ideal_size;
2580           gst_avi_index_entry *entries;
2581           guint old_size, num_added;
2582           GList *node2;
2583
2584           /* cut in 1/10th of a second */
2585           ideal_size = stream->strf.auds->av_bps / 10;
2586
2587           /* ensure chunk size is multiple of blockalign */
2588           if (stream->strf.auds->blockalign > 1)
2589             ideal_size -= ideal_size % stream->strf.auds->blockalign;
2590
2591           /* copy index */
2592           old_size = entry->size;
2593           num_added = (entry->size - 1) / ideal_size;
2594           avi->index_size += num_added;
2595           entries = g_malloc (sizeof (gst_avi_index_entry) * num_added);
2596           alloc_list = g_list_prepend (alloc_list, entries);
2597           for (node2 = node->next; node2 != NULL; node2 = node2->next) {
2598             gst_avi_index_entry *entry2 = node2->data;
2599
2600             entry2->index_nr += num_added;
2601             if (entry2->stream_nr == entry->stream_nr)
2602               entry2->frames_before += num_added;
2603           }
2604
2605           /* new sized index chunks */
2606           for (i = 0; i < num_added + 1; i++) {
2607             gst_avi_index_entry *entry2;
2608
2609             if (i == 0) {
2610               entry2 = entry;
2611             } else {
2612               entry2 = &entries[i - 1];
2613               list = g_list_insert_before (list, node->next, entry2);
2614               entry = node->data;
2615               node = node->next;
2616               memcpy (entry2, entry, sizeof (gst_avi_index_entry));
2617             }
2618
2619             if (old_size >= ideal_size) {
2620               entry2->size = ideal_size;
2621               old_size -= ideal_size;
2622             } else {
2623               entry2->size = old_size;
2624             }
2625
2626             entry2->dur = GST_SECOND * entry2->size / stream->strf.auds->av_bps;
2627             if (i != 0) {
2628               entry2->index_nr++;
2629               entry2->ts += entry->dur;
2630               entry2->offset += entry->size;
2631               entry2->bytes_before += entry->size;
2632               entry2->frames_before++;
2633             }
2634           }
2635 #ifndef GST_DISABLE_GST_DEBUG
2636           num_added_total += num_added;
2637 #endif
2638         }
2639       }
2640     }
2641 #ifndef GST_DISABLE_GST_DEBUG
2642     if (num_added_total)
2643       GST_LOG ("added %u new index entries", num_added_total);
2644 #endif
2645
2646     GST_LOG_OBJECT (avi, "I'm now going to reorder the index entries for time");
2647
2648     /* re-order for time */
2649     list = g_list_sort (list, (GCompareFunc) sort);
2650
2651     /* make a continous array out of the list */
2652     avi->index_size = g_list_length (list);
2653     avi->index_entries = g_try_new (gst_avi_index_entry, avi->index_size);
2654     if (!avi->index_entries)
2655       goto out_of_mem;
2656
2657     entry = (gst_avi_index_entry *) (list->data);
2658     delay = entry->ts;
2659
2660     GST_LOG_OBJECT (avi,
2661         "Building index array, nr_entries = %d (time offset = %"
2662         GST_TIME_FORMAT, avi->index_size, GST_TIME_ARGS (delay));
2663
2664     for (i = 0, node = list; node != NULL; node = node->next, i++) {
2665       entry = node->data;
2666       entry->index_nr = i;
2667       entry->ts -= delay;
2668       memcpy (&avi->index_entries[i], entry, sizeof (gst_avi_index_entry));
2669 #ifndef GST_DISABLE_GST_DEBUG
2670       num_per_stream[entry->stream_nr]++;
2671 #endif
2672
2673       GST_LOG_OBJECT (avi, "Sorted index entry %3d for stream %d of size %6u"
2674           " at offset %7" G_GUINT64_FORMAT ", time %" GST_TIME_FORMAT
2675           " dur %" GST_TIME_FORMAT,
2676           avi->index_entries[i].index_nr, entry->stream_nr, entry->size,
2677           entry->offset, GST_TIME_ARGS (entry->ts), GST_TIME_ARGS (entry->dur));
2678     }
2679     if (delay) {
2680       for (i = 0; i < avi->num_streams; i++) {
2681         stream = &avi->stream[i];
2682         stream->idx_duration -= delay;
2683       }
2684     }
2685 #ifndef GST_DISABLE_GST_DEBUG
2686     {
2687       gchar str[GST_AVI_DEMUX_MAX_STREAMS * (1 + 6 + 2)];
2688       gchar *pad_name;
2689
2690       for (i = 0; i < avi->num_streams; i++) {
2691         if (!avi->stream[i].pad)
2692           continue;
2693         pad_name = GST_OBJECT_NAME (avi->stream[i].pad);
2694         sprintf (&str[i * (1 + 6 + 2)], " %6u %c", num_per_stream[i],
2695             pad_name[0]);
2696       }
2697       GST_LOG_OBJECT (avi, "indizies per stream:%20s", str);
2698     }
2699 #endif
2700
2701     GST_LOG_OBJECT (avi, "Freeing original index list");
2702     /* all the node->data in list point to alloc_list chunks */
2703
2704     g_list_free (list);
2705   }
2706   if (alloc_list) {
2707     g_list_foreach (alloc_list, (GFunc) g_free, NULL);
2708     g_list_free (alloc_list);
2709   }
2710 #ifndef GST_DISABLE_GST_DEBUG
2711   for (i = 0; i < avi->num_streams; i++) {
2712     GST_LOG_OBJECT (avi, "Stream %d, %d frames, %8" G_GUINT64_FORMAT " bytes",
2713         i, avi->stream[i].total_frames, avi->stream[i].total_bytes);
2714   }
2715 #endif
2716
2717   GST_LOG_OBJECT (avi, "Index massaging done");
2718   return TRUE;
2719
2720   /* ERRORS */
2721 out_of_mem:
2722   GST_WARNING_OBJECT (avi, "Out of memory for %" G_GSIZE_FORMAT " bytes",
2723       sizeof (gst_avi_index_entry) * avi->index_size);
2724   return FALSE;
2725 }
2726
2727 static void
2728 gst_avi_demux_calculate_durations_from_index (GstAviDemux * avi)
2729 {
2730   gst_avi_index_entry *entry;
2731   gint stream;
2732   GstClockTime total;
2733
2734   total = GST_CLOCK_TIME_NONE;
2735
2736   /* all streams start at a timestamp 0 */
2737   for (stream = 0; stream < avi->num_streams; stream++) {
2738     GstClockTime duration, hduration;
2739     avi_stream_context *streamc = &avi->stream[stream];
2740     gst_riff_strh *strh = streamc->strh;
2741
2742     if (!strh)
2743       continue;
2744     /* get header duration */
2745     hduration = gst_util_uint64_scale ((guint64) strh->length *
2746         strh->scale, GST_SECOND, (guint64) strh->rate);
2747
2748     GST_INFO ("Stream %d duration according to header: %" GST_TIME_FORMAT,
2749         stream, GST_TIME_ARGS (hduration));
2750
2751     if (hduration == 0)
2752       hduration = GST_CLOCK_TIME_NONE;
2753
2754     /* set duration for the stream */
2755     streamc->hdr_duration = hduration;
2756
2757     /* get last index entry to get duration */
2758     if ((entry = gst_avi_demux_index_last (avi, stream)))
2759       duration = entry->ts + entry->dur;
2760     else
2761       duration = GST_CLOCK_TIME_NONE;
2762
2763     streamc->idx_duration = duration;
2764
2765     /* now pick a good duration */
2766     if (GST_CLOCK_TIME_IS_VALID (duration)) {
2767       /* index gave valid duration, use that */
2768       GST_INFO ("Stream %d duration according to index: %" GST_TIME_FORMAT,
2769           stream, GST_TIME_ARGS (duration));
2770     } else {
2771       /* fall back to header info to calculate a duration */
2772       duration = hduration;
2773     }
2774     /* set duration for the stream */
2775     streamc->duration = duration;
2776
2777     /* find total duration */
2778     if (total == GST_CLOCK_TIME_NONE || duration > total)
2779       total = duration;
2780   }
2781
2782   if (GST_CLOCK_TIME_IS_VALID (total) && (total > 0)) {
2783     /* now update the duration for those streams where we had none */
2784     for (stream = 0; stream < avi->num_streams; stream++) {
2785       avi_stream_context *streamc = &avi->stream[stream];
2786
2787       if (!GST_CLOCK_TIME_IS_VALID (streamc->duration)
2788           || streamc->duration == 0) {
2789         streamc->duration = total;
2790
2791         GST_INFO ("Stream %d duration according to total: %" GST_TIME_FORMAT,
2792             stream, GST_TIME_ARGS (total));
2793       }
2794     }
2795   }
2796
2797   /* and set the total duration in the segment. */
2798   GST_INFO ("Setting total duration to: %" GST_TIME_FORMAT,
2799       GST_TIME_ARGS (total));
2800
2801   gst_segment_set_duration (&avi->segment, GST_FORMAT_TIME, total);
2802 }
2803
2804 static gboolean
2805 gst_avi_demux_push_event (GstAviDemux * avi, GstEvent * event)
2806 {
2807   gboolean result = FALSE;
2808   gint i;
2809
2810   GST_DEBUG_OBJECT (avi, "sending %s event to %d streams",
2811       GST_EVENT_TYPE_NAME (event), avi->num_streams);
2812
2813   if (avi->num_streams) {
2814     for (i = 0; i < avi->num_streams; i++) {
2815       avi_stream_context *stream = &avi->stream[i];
2816
2817       if (stream->pad) {
2818         if (gst_pad_push_event (stream->pad, gst_event_ref (event)))
2819           result = TRUE;
2820       }
2821     }
2822   }
2823   gst_event_unref (event);
2824   return result;
2825 }
2826
2827 /*
2828  * Read AVI headers when streaming
2829  */
2830 static GstFlowReturn
2831 gst_avi_demux_stream_header_push (GstAviDemux * avi)
2832 {
2833   GstFlowReturn ret = GST_FLOW_OK;
2834   guint32 tag = 0;
2835   guint32 ltag = 0;
2836   guint32 size = 0;
2837   const guint8 *data;
2838   GstBuffer *buf = NULL, *sub = NULL;
2839   guint offset = 4;
2840   gint64 stop;
2841
2842   GST_DEBUG ("Reading and parsing avi headers: %d", avi->header_state);
2843
2844   switch (avi->header_state) {
2845     case GST_AVI_DEMUX_HEADER_TAG_LIST:
2846       if (gst_avi_demux_peek_chunk (avi, &tag, &size)) {
2847         avi->offset += 8 + ((size + 1) & ~1);
2848         if (tag != GST_RIFF_TAG_LIST)
2849           goto header_no_list;
2850
2851         gst_adapter_flush (avi->adapter, 8);
2852         /* Find the 'hdrl' LIST tag */
2853         GST_DEBUG ("Reading %d bytes", size);
2854         buf = gst_adapter_take_buffer (avi->adapter, size);
2855
2856         if (GST_READ_UINT32_LE (GST_BUFFER_DATA (buf)) != GST_RIFF_LIST_hdrl)
2857           goto header_no_hdrl;
2858
2859         GST_DEBUG ("'hdrl' LIST tag found. Parsing next chunk");
2860
2861         /* the hdrl starts with a 'avih' header */
2862         if (!gst_riff_parse_chunk (GST_ELEMENT (avi), buf, &offset, &tag, &sub))
2863           goto header_no_avih;
2864
2865         if (tag != GST_RIFF_TAG_avih)
2866           goto header_no_avih;
2867
2868         if (!gst_avi_demux_parse_avih (GST_ELEMENT (avi), sub, &avi->avih))
2869           goto header_wrong_avih;
2870
2871         GST_DEBUG_OBJECT (avi, "AVI header ok, reading elemnts from header");
2872
2873         /* now, read the elements from the header until the end */
2874         while (gst_riff_parse_chunk (GST_ELEMENT (avi), buf, &offset, &tag,
2875                 &sub)) {
2876           /* sub can be NULL on empty tags */
2877           if (!sub)
2878             continue;
2879
2880           switch (tag) {
2881             case GST_RIFF_TAG_LIST:
2882               if (GST_BUFFER_SIZE (sub) < 4)
2883                 goto next;
2884
2885               switch (GST_READ_UINT32_LE (GST_BUFFER_DATA (sub))) {
2886                 case GST_RIFF_LIST_strl:
2887                   if (!(gst_avi_demux_parse_stream (avi, sub))) {
2888                     GST_ELEMENT_WARNING (avi, STREAM, DEMUX, (NULL),
2889                         ("failed to parse stream, ignoring"));
2890                     goto next;
2891                   }
2892                   goto next;
2893                 case GST_RIFF_LIST_odml:
2894                   gst_avi_demux_parse_odml (avi, sub);
2895                   break;
2896                 default:
2897                   GST_WARNING_OBJECT (avi,
2898                       "Unknown list %" GST_FOURCC_FORMAT " in AVI header",
2899                       GST_FOURCC_ARGS (GST_READ_UINT32_LE (GST_BUFFER_DATA
2900                               (sub))));
2901                   /* fall-through */
2902                 case GST_RIFF_TAG_JUNK:
2903                   goto next;
2904               }
2905               break;
2906             default:
2907               GST_WARNING_OBJECT (avi,
2908                   "Unknown off %d tag %" GST_FOURCC_FORMAT " in AVI header",
2909                   offset, GST_FOURCC_ARGS (tag));
2910               /* fall-through */
2911             case GST_RIFF_TAG_JUNK:
2912             next:
2913               /* move to next chunk */
2914               gst_buffer_unref (sub);
2915               sub = NULL;
2916               break;
2917           }
2918         }
2919         gst_buffer_unref (buf);
2920         GST_DEBUG ("elements parsed");
2921
2922         /* check parsed streams */
2923         if (avi->num_streams == 0) {
2924           goto no_streams;
2925         } else if (avi->num_streams != avi->avih->streams) {
2926           GST_WARNING_OBJECT (avi,
2927               "Stream header mentioned %d streams, but %d available",
2928               avi->avih->streams, avi->num_streams);
2929         }
2930         GST_DEBUG ("Get junk and info next");
2931         avi->header_state = GST_AVI_DEMUX_HEADER_INFO;
2932       } else {
2933         /* Need more data */
2934         return ret;
2935       }
2936       /* fall-though */
2937     case GST_AVI_DEMUX_HEADER_INFO:
2938       GST_DEBUG_OBJECT (avi, "skipping junk between header and data ...");
2939       while (TRUE) {
2940         if (gst_adapter_available (avi->adapter) < 12)
2941           return GST_FLOW_OK;
2942
2943         data = gst_adapter_peek (avi->adapter, 12);
2944         tag = GST_READ_UINT32_LE (data);
2945         size = GST_READ_UINT32_LE (data + 4);
2946         ltag = GST_READ_UINT32_LE (data + 8);
2947
2948         if (tag == GST_RIFF_TAG_LIST) {
2949           switch (ltag) {
2950             case GST_RIFF_LIST_movi:
2951               gst_adapter_flush (avi->adapter, 12);
2952               avi->offset += 12;
2953               goto skipping_done;
2954             case GST_RIFF_LIST_INFO:
2955               GST_DEBUG ("Found INFO chunk");
2956               if (gst_avi_demux_peek_chunk (avi, &tag, &size)) {
2957                 avi->offset += 12;
2958                 gst_adapter_flush (avi->adapter, 12);
2959                 buf = gst_adapter_take_buffer (avi->adapter, size - 4);
2960                 gst_riff_parse_info (GST_ELEMENT (avi), buf, &avi->globaltags);
2961                 gst_buffer_unref (buf);
2962
2963                 avi->offset += ((size + 1) & ~1) - 4;
2964               } else {
2965                 /* Need more data */
2966                 return GST_FLOW_OK;
2967               }
2968               break;
2969             default:
2970               if (gst_avi_demux_peek_chunk (avi, &tag, &size)) {
2971                 avi->offset += 8 + ((size + 1) & ~1);
2972                 gst_adapter_flush (avi->adapter, 8 + ((size + 1) & ~1));
2973                 // ??? goto iterate; ???
2974               } else {
2975                 /* Need more data */
2976                 return GST_FLOW_OK;
2977               }
2978               break;
2979           }
2980         } else {
2981           if (gst_avi_demux_peek_chunk (avi, &tag, &size)) {
2982             avi->offset += 8 + ((size + 1) & ~1);
2983             gst_adapter_flush (avi->adapter, 8 + ((size + 1) & ~1));
2984             //goto iterate;
2985           } else {
2986             /* Need more data */
2987             return GST_FLOW_OK;
2988           }
2989         }
2990       }
2991       break;
2992     default:
2993       GST_WARNING ("unhandled header state: %d", avi->header_state);
2994       break;
2995   }
2996 skipping_done:
2997
2998   GST_DEBUG_OBJECT (avi, "skipping done ... (streams=%u, stream[0].indexes=%p)",
2999       avi->num_streams, avi->stream[0].indexes);
3000
3001   GST_DEBUG ("Found movi chunk. Starting to stream data");
3002   avi->state = GST_AVI_DEMUX_MOVI;
3003
3004 #if 0
3005   /*GList *index = NULL, *alloc = NULL; */
3006
3007   /* ######################## this need to be integrated with the state */
3008   /* create or read stream index (for seeking) */
3009   if (avi->stream[0].indexes != NULL) {
3010     gst_avi_demux_read_subindexes_push (avi, &index, &alloc);
3011   }
3012   if (!index) {
3013     if (avi->avih->flags & GST_RIFF_AVIH_HASINDEX) {
3014       gst_avi_demux_stream_index (avi, &index, &alloc);
3015     }
3016     /* some indexes are incomplete, continue streaming from there */
3017     if (!index)
3018       gst_avi_demux_stream_scan (avi, &index, &alloc);
3019   }
3020
3021   /* this is a fatal error */
3022   if (!index)
3023     goto no_index;
3024
3025   if (!gst_avi_demux_massage_index (avi, index, alloc))
3026     goto no_index;
3027
3028   gst_avi_demux_calculate_durations_from_index (avi);
3029   /* ######################## */
3030 #endif
3031
3032   /* create initial NEWSEGMENT event */
3033   if ((stop = avi->segment.stop) == GST_CLOCK_TIME_NONE)
3034     stop = avi->segment.duration;
3035
3036   GST_DEBUG_OBJECT (avi, "segment stop %" G_GINT64_FORMAT, stop);
3037
3038   if (avi->seek_event)
3039     gst_event_unref (avi->seek_event);
3040   avi->seek_event = gst_event_new_new_segment
3041       (FALSE, avi->segment.rate, GST_FORMAT_TIME,
3042       avi->segment.start, stop, avi->segment.start);
3043
3044   /* at this point we know all the streams and we can signal the no more
3045    * pads signal */
3046   GST_DEBUG_OBJECT (avi, "signaling no more pads");
3047   gst_element_no_more_pads (GST_ELEMENT (avi));
3048
3049   return GST_FLOW_OK;
3050
3051   /* ERRORS */
3052 no_streams:
3053   {
3054     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("No streams found"));
3055     return GST_FLOW_ERROR;
3056   }
3057 header_no_list:
3058   {
3059     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3060         ("Invalid AVI header (no LIST at start): %"
3061             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3062     return GST_FLOW_ERROR;
3063   }
3064 header_no_hdrl:
3065   {
3066     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3067         ("Invalid AVI header (no hdrl at start): %"
3068             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3069     gst_buffer_unref (buf);
3070     return GST_FLOW_ERROR;
3071   }
3072 header_no_avih:
3073   {
3074     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3075         ("Invalid AVI header (no avih at start): %"
3076             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3077     if (sub)
3078       gst_buffer_unref (sub);
3079
3080     gst_buffer_unref (buf);
3081     return GST_FLOW_ERROR;
3082   }
3083 header_wrong_avih:
3084   {
3085     gst_buffer_unref (buf);
3086     return GST_FLOW_ERROR;
3087   }
3088 }
3089
3090 /*
3091  * Read full AVI headers.
3092  */
3093 static GstFlowReturn
3094 gst_avi_demux_stream_header_pull (GstAviDemux * avi)
3095 {
3096   GstFlowReturn res;
3097   GstBuffer *buf, *sub = NULL;
3098   guint32 tag;
3099   GList *index = NULL, *alloc = NULL;
3100   guint offset = 4;
3101   gint64 stop;
3102   GstElement *element = GST_ELEMENT_CAST (avi);
3103
3104   /* the header consists of a 'hdrl' LIST tag */
3105   res = gst_riff_read_chunk (element, avi->sinkpad, &avi->offset, &tag, &buf);
3106   if (res != GST_FLOW_OK)
3107     goto pull_range_failed;
3108   else if (tag != GST_RIFF_TAG_LIST)
3109     goto no_list;
3110   else if (GST_BUFFER_SIZE (buf) < 4)
3111     goto no_header;
3112
3113   GST_DEBUG_OBJECT (avi, "parsing headers");
3114
3115   /* Find the 'hdrl' LIST tag */
3116   while (GST_READ_UINT32_LE (GST_BUFFER_DATA (buf)) != GST_RIFF_LIST_hdrl) {
3117     GST_LOG_OBJECT (avi, "buffer contains %" GST_FOURCC_FORMAT,
3118         GST_FOURCC_ARGS (GST_READ_UINT32_LE (GST_BUFFER_DATA (buf))));
3119
3120     /* Eat up */
3121     gst_buffer_unref (buf);
3122
3123     /* read new chunk */
3124     res = gst_riff_read_chunk (element, avi->sinkpad, &avi->offset, &tag, &buf);
3125     if (res != GST_FLOW_OK)
3126       goto pull_range_failed;
3127     else if (tag != GST_RIFF_TAG_LIST)
3128       goto no_list;
3129     else if (GST_BUFFER_SIZE (buf) < 4)
3130       goto no_header;
3131   }
3132
3133   GST_DEBUG_OBJECT (avi, "hdrl LIST tag found");
3134
3135   /* the hdrl starts with a 'avih' header */
3136   if (!gst_riff_parse_chunk (element, buf, &offset, &tag, &sub))
3137     goto no_avih;
3138   else if (tag != GST_RIFF_TAG_avih)
3139     goto no_avih;
3140   else if (!gst_avi_demux_parse_avih (element, sub, &avi->avih))
3141     goto invalid_avih;
3142
3143   GST_DEBUG_OBJECT (avi, "AVI header ok, reading elements from header");
3144
3145   /* now, read the elements from the header until the end */
3146   while (gst_riff_parse_chunk (element, buf, &offset, &tag, &sub)) {
3147     /* sub can be NULL on empty tags */
3148     if (!sub)
3149       continue;
3150
3151     switch (tag) {
3152       case GST_RIFF_TAG_LIST:
3153       {
3154         guint8 *data;
3155         guint32 fourcc;
3156
3157         if (GST_BUFFER_SIZE (sub) < 4)
3158           goto next;
3159
3160         data = GST_BUFFER_DATA (sub);
3161         fourcc = GST_READ_UINT32_LE (data);
3162
3163         switch (fourcc) {
3164           case GST_RIFF_LIST_strl:
3165             if (!(gst_avi_demux_parse_stream (avi, sub))) {
3166               GST_ELEMENT_WARNING (avi, STREAM, DEMUX, (NULL),
3167                   ("faile to parse stream, ignoring"));
3168               sub = NULL;
3169             }
3170             goto next;
3171           case GST_RIFF_LIST_odml:
3172             gst_avi_demux_parse_odml (avi, sub);
3173             break;
3174           default:
3175             GST_WARNING_OBJECT (avi,
3176                 "Unknown list %" GST_FOURCC_FORMAT " in AVI header",
3177                 GST_FOURCC_ARGS (fourcc));
3178             GST_MEMDUMP_OBJECT (avi, "Unknown list", GST_BUFFER_DATA (sub),
3179                 GST_BUFFER_SIZE (sub));
3180             /* fall-through */
3181           case GST_RIFF_TAG_JUNK:
3182             goto next;
3183         }
3184         break;
3185       }
3186       default:
3187         GST_WARNING_OBJECT (avi,
3188             "Unknown tag %" GST_FOURCC_FORMAT " in AVI header at off %d",
3189             GST_FOURCC_ARGS (tag), offset);
3190         GST_MEMDUMP_OBJECT (avi, "Unknown tag", GST_BUFFER_DATA (sub),
3191             GST_BUFFER_SIZE (sub));
3192         /* fall-through */
3193       case GST_RIFF_TAG_JUNK:
3194       next:
3195         if (sub)
3196           gst_buffer_unref (sub);
3197         sub = NULL;
3198         break;
3199     }
3200   }
3201   gst_buffer_unref (buf);
3202   GST_DEBUG ("elements parsed");
3203
3204   /* check parsed streams */
3205   if (avi->num_streams == 0)
3206     goto no_streams;
3207   else if (avi->num_streams != avi->avih->streams) {
3208     GST_WARNING_OBJECT (avi,
3209         "Stream header mentioned %d streams, but %d available",
3210         avi->avih->streams, avi->num_streams);
3211   }
3212
3213   GST_DEBUG_OBJECT (avi, "skipping junk between header and data, offset=%"
3214       G_GUINT64_FORMAT, avi->offset);
3215
3216   /* Now, find the data (i.e. skip all junk between header and data) */
3217   do {
3218     guint size;
3219     guint32 tag, ltag;
3220
3221     res = gst_pad_pull_range (avi->sinkpad, avi->offset, 12, &buf);
3222     if (res != GST_FLOW_OK) {
3223       GST_DEBUG_OBJECT (avi, "pull_range failure while looking for tags");
3224       goto pull_range_failed;
3225     } else if (GST_BUFFER_SIZE (buf) < 12) {
3226       GST_DEBUG_OBJECT (avi, "got %d bytes which is less than 12 bytes",
3227           GST_BUFFER_SIZE (buf));
3228       gst_buffer_unref (buf);
3229       return GST_FLOW_ERROR;
3230     }
3231
3232     tag = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf));
3233     size = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf) + 4);
3234     ltag = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf) + 8);
3235
3236     GST_DEBUG ("tag %" GST_FOURCC_FORMAT ", size %u",
3237         GST_FOURCC_ARGS (tag), size);
3238     GST_MEMDUMP ("Tag content", GST_BUFFER_DATA (buf), GST_BUFFER_SIZE (buf));
3239     gst_buffer_unref (buf);
3240
3241     switch (tag) {
3242       case GST_RIFF_TAG_LIST:{
3243         switch (ltag) {
3244           case GST_RIFF_LIST_movi:
3245             GST_DEBUG_OBJECT (avi,
3246                 "Reached the 'movi' tag, we're done with skipping");
3247             goto skipping_done;
3248           case GST_RIFF_LIST_INFO:
3249             res =
3250                 gst_riff_read_chunk (element, avi->sinkpad, &avi->offset, &tag,
3251                 &buf);
3252             if (res != GST_FLOW_OK) {
3253               GST_DEBUG_OBJECT (avi, "couldn't read INFO chunk");
3254               goto pull_range_failed;
3255             }
3256             GST_DEBUG ("got size %u", GST_BUFFER_SIZE (buf));
3257
3258             sub = gst_buffer_create_sub (buf, 4, GST_BUFFER_SIZE (buf) - 4);
3259             gst_riff_parse_info (element, sub, &avi->globaltags);
3260             if (sub) {
3261               gst_buffer_unref (sub);
3262               sub = NULL;
3263             }
3264             gst_buffer_unref (buf);
3265             /* gst_riff_read_chunk() has already advanced avi->offset */
3266             break;
3267           default:
3268             GST_WARNING_OBJECT (avi,
3269                 "Skipping unknown list tag %" GST_FOURCC_FORMAT,
3270                 GST_FOURCC_ARGS (ltag));
3271             avi->offset += 8 + ((size + 1) & ~1);
3272             break;
3273         }
3274       }
3275         break;
3276       default:
3277         GST_WARNING_OBJECT (avi, "Skipping unknown tag %" GST_FOURCC_FORMAT,
3278             GST_FOURCC_ARGS (tag));
3279         /* Fall-through */
3280       case GST_MAKE_FOURCC ('J', 'U', 'N', 'Q'):
3281       case GST_MAKE_FOURCC ('J', 'U', 'N', 'K'):
3282         avi->offset += 8 + ((size + 1) & ~1);
3283         break;
3284     }
3285   } while (1);
3286 skipping_done:
3287
3288   GST_DEBUG_OBJECT (avi, "skipping done ... (streams=%u, stream[0].indexes=%p)",
3289       avi->num_streams, avi->stream[0].indexes);
3290
3291   /* create or read stream index (for seeking) */
3292   if (avi->stream[0].indexes != NULL) {
3293     /* we read a super index already (gst_avi_demux_parse_superindex() ) */
3294     gst_avi_demux_read_subindexes_pull (avi, &index, &alloc);
3295   }
3296   if (!index) {
3297     if (avi->avih->flags & GST_RIFF_AVIH_HASINDEX) {
3298       gst_avi_demux_stream_index (avi, &index, &alloc);
3299     }
3300     /* some indexes are incomplete, continue streaming from there */
3301     if (!index)
3302       gst_avi_demux_stream_scan (avi, &index, &alloc);
3303   }
3304
3305   /* this is a fatal error */
3306   if (!index)
3307     goto no_index;
3308
3309   if (!gst_avi_demux_massage_index (avi, index, alloc))
3310     goto no_index;
3311
3312   gst_avi_demux_calculate_durations_from_index (avi);
3313
3314   /* create initial NEWSEGMENT event */
3315   if ((stop = avi->segment.stop) == GST_CLOCK_TIME_NONE)
3316     stop = avi->segment.duration;
3317
3318   GST_DEBUG_OBJECT (avi, "segment stop %" G_GINT64_FORMAT, stop);
3319
3320   if (avi->seek_event)
3321     gst_event_unref (avi->seek_event);
3322   avi->seek_event = gst_event_new_new_segment
3323       (FALSE, avi->segment.rate, GST_FORMAT_TIME,
3324       avi->segment.start, stop, avi->segment.start);
3325
3326   /* at this point we know all the streams and we can signal the no more
3327    * pads signal */
3328   GST_DEBUG_OBJECT (avi, "signaling no more pads");
3329   gst_element_no_more_pads (GST_ELEMENT_CAST (avi));
3330
3331   return GST_FLOW_OK;
3332
3333   /* ERRORS */
3334 no_list:
3335   {
3336     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3337         ("Invalid AVI header (no LIST at start): %"
3338             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3339     gst_buffer_unref (buf);
3340     return GST_FLOW_ERROR;
3341   }
3342 no_header:
3343   {
3344     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3345         ("Invalid AVI header (no hdrl at start): %"
3346             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3347     gst_buffer_unref (buf);
3348     return GST_FLOW_ERROR;
3349   }
3350 no_avih:
3351   {
3352     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3353         ("Invalid AVI header (no avih at start): %"
3354             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3355     if (sub)
3356       gst_buffer_unref (sub);
3357     gst_buffer_unref (buf);
3358     return GST_FLOW_ERROR;
3359   }
3360 invalid_avih:
3361   {
3362     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3363         ("Invalid AVI header (cannot parse avih at start)"));
3364     if (sub)
3365       gst_buffer_unref (sub);
3366     gst_buffer_unref (buf);
3367     return GST_FLOW_ERROR;
3368   }
3369 no_streams:
3370   {
3371     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("No streams found"));
3372     return GST_FLOW_ERROR;
3373   }
3374 no_index:
3375   {
3376     GST_WARNING ("file without or too big index");
3377     g_list_free (index);
3378     g_list_foreach (alloc, (GFunc) g_free, NULL);
3379     g_list_free (alloc);
3380
3381     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3382         ("Could not get/create index"));
3383     return GST_FLOW_ERROR;
3384   }
3385 pull_range_failed:
3386   {
3387     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3388         ("pull_range flow reading header: %s", gst_flow_get_name (res)));
3389     return GST_FLOW_ERROR;
3390   }
3391 }
3392
3393 /*
3394  * Do the actual seeking.
3395  */
3396 static gboolean
3397 gst_avi_demux_do_seek (GstAviDemux * avi, GstSegment * segment)
3398 {
3399   GstClockTime seek_time;
3400   gboolean keyframe;
3401   gst_avi_index_entry *entry, *kentry;
3402   gint old_entry;
3403
3404   seek_time = segment->last_stop;
3405   keyframe = !!(segment->flags & GST_SEEK_FLAG_KEY_UNIT);
3406
3407   /* FIXME: if we seek in an openDML file, we will have multiple
3408    * primary levels. Seeking in between those will cause havoc. */
3409
3410   /* save old position so we can see if we must mark a discont. */
3411   old_entry = avi->current_entry;
3412
3413   /* get the entry for the requested position, which is always in last_stop.
3414    * we search the index entry for stream 0, since all entries are sorted by
3415    * time and stream we automagically are positioned for the other streams as
3416    * well. FIXME, this code assumes the main stream with keyframes is stream 0,
3417    * which is mostly correct... */
3418   if (!(entry = gst_avi_demux_index_entry_for_time (avi, 0, seek_time)))
3419     goto no_entry;
3420
3421   GST_DEBUG_OBJECT (avi,
3422       "Got requested entry %d [stream:%d / ts:%" GST_TIME_FORMAT
3423       " / duration:%" GST_TIME_FORMAT "]", entry->index_nr,
3424       entry->stream_nr, GST_TIME_ARGS (entry->ts), GST_TIME_ARGS (entry->dur));
3425
3426   /* check if we are already on a keyframe */
3427   if (!(entry->flags & GST_AVI_INDEX_ENTRY_FLAG_KEYFRAME)) {
3428     /* now go to the previous keyframe, this is where we should start
3429      * decoding from. */
3430     if (!(kentry = gst_avi_demux_index_prev (avi, 0, entry->index_nr,
3431                 GST_AVI_INDEX_ENTRY_FLAG_KEYFRAME))) {
3432       goto no_entry;
3433     }
3434   } else {
3435     /* we were on a keyframe */
3436     kentry = entry;
3437   }
3438
3439   GST_DEBUG_OBJECT (avi,
3440       "Got keyframe entry %d [stream:%d / ts:%" GST_TIME_FORMAT
3441       " / duration:%" GST_TIME_FORMAT "]", kentry->index_nr,
3442       entry->stream_nr, GST_TIME_ARGS (kentry->ts),
3443       GST_TIME_ARGS (kentry->dur));
3444
3445   /* we must start decoding at the keyframe */
3446   avi->current_entry = kentry->index_nr;
3447
3448   if (segment->rate < 0.0) {
3449     gst_avi_index_entry *next_keyframe;
3450
3451     /* Because we don't know the frame order we need to push from the prev keyframe
3452      * to the next keyframe. If there is a smart decoder downstream he will notice
3453      * that there are too many encoded frames send and return UNEXPECTED when there
3454      * are enough decoded frames to fill the segment.
3455      */
3456     next_keyframe =
3457         gst_avi_demux_index_next (avi, 0, kentry->index_nr,
3458         GST_AVI_INDEX_ENTRY_FLAG_KEYFRAME);
3459     if (!next_keyframe)
3460       next_keyframe = gst_avi_demux_index_last (avi, 0);
3461
3462     avi->reverse_start_index = kentry->index_nr;
3463     avi->reverse_stop_index = next_keyframe->index_nr;
3464
3465     GST_DEBUG_OBJECT (avi, "reverse seek: start idx (%d) and stop idx (%d)",
3466         avi->reverse_start_index, avi->reverse_stop_index);
3467   }
3468
3469   if (keyframe) {
3470     /* when seeking to a keyframe, we update the result seek time
3471      * to the time of the keyframe. */
3472     seek_time = avi->index_entries[avi->current_entry].ts;
3473   }
3474
3475 next:
3476   /* if we changed position, mark a DISCONT on all streams */
3477   if (avi->current_entry != old_entry) {
3478     gint i;
3479
3480     for (i = 0; i < avi->num_streams; i++) {
3481       avi->stream[i].discont = TRUE;
3482     }
3483   }
3484
3485   GST_DEBUG_OBJECT (avi, "seek: %" GST_TIME_FORMAT
3486       " keyframe seeking:%d", GST_TIME_ARGS (seek_time), keyframe);
3487
3488   /* the seek time is also the last_stop and stream time */
3489   segment->last_stop = seek_time;
3490   segment->time = seek_time;
3491
3492   return TRUE;
3493
3494 no_entry:
3495   {
3496     /* we could not find an entry for the given time */
3497     GST_WARNING_OBJECT (avi,
3498         "Couldn't find AviIndexEntry for time:%" GST_TIME_FORMAT,
3499         GST_TIME_ARGS (seek_time));
3500     if (avi->current_entry >= avi->index_size && avi->index_size > 0)
3501       avi->current_entry = avi->index_size - 1;
3502
3503     goto next;
3504   }
3505 }
3506
3507 /*
3508  * Handle seek event.
3509  */
3510 static gboolean
3511 gst_avi_demux_handle_seek (GstAviDemux * avi, GstPad * pad, GstEvent * event)
3512 {
3513   gdouble rate;
3514   GstFormat format;
3515   GstSeekFlags flags;
3516   GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
3517   gint64 cur, stop;
3518   gboolean flush;
3519   gboolean update;
3520   GstSegment seeksegment = { 0, };
3521
3522   if (event) {
3523     GST_DEBUG_OBJECT (avi, "doing seek with event");
3524
3525     gst_event_parse_seek (event, &rate, &format, &flags,
3526         &cur_type, &cur, &stop_type, &stop);
3527
3528     /* we have to have a format as the segment format. Try to convert
3529      * if not. */
3530     if (format != GST_FORMAT_TIME) {
3531       GstFormat fmt = GST_FORMAT_TIME;
3532       gboolean res = TRUE;
3533
3534       if (cur_type != GST_SEEK_TYPE_NONE)
3535         res = gst_pad_query_convert (pad, format, cur, &fmt, &cur);
3536       if (res && stop_type != GST_SEEK_TYPE_NONE)
3537         res = gst_pad_query_convert (pad, format, stop, &fmt, &stop);
3538       if (!res)
3539         goto no_format;
3540
3541       format = fmt;
3542     }
3543     GST_DEBUG_OBJECT (avi,
3544         "seek requested: rate %g cur %" GST_TIME_FORMAT " stop %"
3545         GST_TIME_FORMAT, rate, GST_TIME_ARGS (cur), GST_TIME_ARGS (stop));
3546     /* FIXME: can we do anything with rate!=1.0 */
3547   } else {
3548     GST_DEBUG_OBJECT (avi, "doing seek without event");
3549     flags = 0;
3550     rate = 1.0;
3551   }
3552
3553   /* save flush flag */
3554   flush = flags & GST_SEEK_FLAG_FLUSH;
3555
3556   if (flush) {
3557     GstEvent *event = gst_event_new_flush_start ();
3558
3559     /* for a flushing seek, we send a flush_start on all pads. This will
3560      * eventually stop streaming with a WRONG_STATE. We can thus eventually
3561      * take the STREAM_LOCK. */
3562     GST_DEBUG_OBJECT (avi, "sending flush start");
3563     gst_avi_demux_push_event (avi, gst_event_ref (event));
3564     gst_pad_push_event (avi->sinkpad, event);
3565   } else {
3566     /* a non-flushing seek, we PAUSE the task so that we can take the
3567      * STREAM_LOCK */
3568     GST_DEBUG_OBJECT (avi, "non flushing seek, pausing task");
3569     gst_pad_pause_task (avi->sinkpad);
3570   }
3571
3572   /* wait for streaming to stop */
3573   GST_DEBUG_OBJECT (avi, "wait for streaming to stop");
3574   GST_PAD_STREAM_LOCK (avi->sinkpad);
3575
3576   /* copy segment, we need this because we still need the old
3577    * segment when we close the current segment. */
3578   memcpy (&seeksegment, &avi->segment, sizeof (GstSegment));
3579
3580   if (event) {
3581     GST_DEBUG_OBJECT (avi, "configuring seek");
3582     gst_segment_set_seek (&seeksegment, rate, format, flags,
3583         cur_type, cur, stop_type, stop, &update);
3584   }
3585
3586   /* do the seek, seeksegment.last_stop contains the new position, this
3587    * actually never fails. */
3588   gst_avi_demux_do_seek (avi, &seeksegment);
3589
3590   if (flush) {
3591     gint i;
3592
3593     GST_DEBUG_OBJECT (avi, "sending flush stop");
3594     gst_avi_demux_push_event (avi, gst_event_new_flush_stop ());
3595     gst_pad_push_event (avi->sinkpad, gst_event_new_flush_stop ());
3596     /* reset the last flow and mark discont, FLUSH is always DISCONT */
3597     for (i = 0; i < avi->num_streams; i++) {
3598       avi->stream[i].last_flow = GST_FLOW_OK;
3599       avi->stream[i].discont = TRUE;
3600     }
3601   } else if (avi->segment_running) {
3602     GstEvent *seg;
3603
3604     /* we are running the current segment and doing a non-flushing seek,
3605      * close the segment first based on the last_stop. */
3606     GST_DEBUG_OBJECT (avi, "closing running segment %" G_GINT64_FORMAT
3607         " to %" G_GINT64_FORMAT, avi->segment.start, avi->segment.last_stop);
3608     seg = gst_event_new_new_segment (TRUE,
3609         avi->segment.rate, avi->segment.format,
3610         avi->segment.start, avi->segment.last_stop, avi->segment.time);
3611     gst_avi_demux_push_event (avi, seg);
3612   }
3613
3614   /* now update the real segment info */
3615   memcpy (&avi->segment, &seeksegment, sizeof (GstSegment));
3616
3617   /* post the SEGMENT_START message when we do segmented playback */
3618   if (avi->segment.flags & GST_SEEK_FLAG_SEGMENT) {
3619     gst_element_post_message (GST_ELEMENT (avi),
3620         gst_message_new_segment_start (GST_OBJECT (avi),
3621             avi->segment.format, avi->segment.last_stop));
3622   }
3623
3624   /* prepare for streaming again */
3625   if ((stop = avi->segment.stop) == GST_CLOCK_TIME_NONE)
3626     stop = avi->segment.duration;
3627
3628   /* queue the segment event for the streaming thread. */
3629   if (avi->seek_event)
3630     gst_event_unref (avi->seek_event);
3631   if (avi->segment.rate > 0.0) {
3632     avi->seek_event = gst_event_new_new_segment (FALSE,
3633         avi->segment.rate, avi->segment.format,
3634         avi->segment.last_stop, stop, avi->segment.time);
3635   } else {
3636     avi->seek_event = gst_event_new_new_segment (FALSE,
3637         avi->segment.rate, avi->segment.format,
3638         avi->segment.start, avi->segment.last_stop, avi->segment.start);
3639   }
3640
3641   if (!avi->streaming) {
3642     avi->segment_running = TRUE;
3643     gst_pad_start_task (avi->sinkpad, (GstTaskFunction) gst_avi_demux_loop,
3644         avi->sinkpad);
3645   }
3646   GST_PAD_STREAM_UNLOCK (avi->sinkpad);
3647
3648   return TRUE;
3649
3650   /* ERRORS */
3651 no_format:
3652   {
3653     GST_DEBUG_OBJECT (avi, "unsupported format given, seek aborted.");
3654     return FALSE;
3655   }
3656 }
3657
3658 /*
3659  * Helper for gst_avi_demux_invert()
3660  */
3661 static inline void
3662 swap_line (guint8 * d1, guint8 * d2, guint8 * tmp, gint bytes)
3663 {
3664   memcpy (tmp, d1, bytes);
3665   memcpy (d1, d2, bytes);
3666   memcpy (d2, tmp, bytes);
3667 }
3668
3669
3670 #define gst_avi_demux_is_uncompressed(fourcc)           \
3671   (fourcc == GST_RIFF_DIB ||                            \
3672    fourcc == GST_RIFF_rgb ||                            \
3673    fourcc == GST_RIFF_RGB || fourcc == GST_RIFF_RAW)
3674
3675 /*
3676  * Invert DIB buffers... Takes existing buffer and
3677  * returns either the buffer or a new one (with old
3678  * one dereferenced).
3679  * FIXME: can't we preallocate tmp? and remember stride, bpp?
3680  */
3681 static GstBuffer *
3682 gst_avi_demux_invert (avi_stream_context * stream, GstBuffer * buf)
3683 {
3684   GstStructure *s;
3685   gint y, w, h;
3686   gint bpp, stride;
3687   guint8 *tmp = NULL;
3688
3689   if (stream->strh->type != GST_RIFF_FCC_vids)
3690     return buf;
3691
3692   if (!gst_avi_demux_is_uncompressed (stream->strh->fcc_handler)) {
3693     return buf;                 /* Ignore non DIB buffers */
3694   }
3695
3696   s = gst_caps_get_structure (GST_PAD_CAPS (stream->pad), 0);
3697   if (!gst_structure_get_int (s, "bpp", &bpp)) {
3698     GST_WARNING ("Failed to retrieve depth from caps");
3699     return buf;
3700   }
3701
3702   if (stream->strf.vids == NULL) {
3703     GST_WARNING ("Failed to retrieve vids for stream");
3704     return buf;
3705   }
3706
3707   h = stream->strf.vids->height;
3708   w = stream->strf.vids->width;
3709   stride = w * (bpp / 8);
3710
3711   buf = gst_buffer_make_writable (buf);
3712   if (GST_BUFFER_SIZE (buf) < (stride * h)) {
3713     GST_WARNING ("Buffer is smaller than reported Width x Height x Depth");
3714     return buf;
3715   }
3716
3717   tmp = g_malloc (stride);
3718
3719   for (y = 0; y < h / 2; y++) {
3720     swap_line (GST_BUFFER_DATA (buf) + stride * y,
3721         GST_BUFFER_DATA (buf) + stride * (h - 1 - y), tmp, stride);
3722   }
3723
3724   g_free (tmp);
3725
3726   return buf;
3727 }
3728
3729 /*
3730  * Returns the aggregated GstFlowReturn.
3731  */
3732 static GstFlowReturn
3733 gst_avi_demux_combine_flows (GstAviDemux * avi, avi_stream_context * stream,
3734     GstFlowReturn ret)
3735 {
3736   guint i;
3737
3738   /* store the value */
3739   stream->last_flow = ret;
3740
3741   /* any other error that is not-linked can be returned right away */
3742   if (G_UNLIKELY (ret != GST_FLOW_NOT_LINKED))
3743     goto done;
3744
3745   /* only return NOT_LINKED if all other pads returned NOT_LINKED */
3746   for (i = 0; i < avi->num_streams; i++) {
3747     avi_stream_context *ostream = &avi->stream[i];
3748
3749     ret = ostream->last_flow;
3750     /* some other return value (must be SUCCESS but we can return
3751      * other values as well) */
3752     if (G_UNLIKELY (ret != GST_FLOW_NOT_LINKED))
3753       goto done;
3754   }
3755   /* if we get here, all other pads were unlinked and we return
3756    * NOT_LINKED then */
3757 done:
3758   GST_LOG_OBJECT (avi, "combined return %s", gst_flow_get_name (ret));
3759   return ret;
3760 }
3761
3762 /*
3763  * prepare the avi element for a reverse jump to a prev keyframe
3764  * this function will return the start entry. if the function returns
3765  * NULL there was no prev keyframe.
3766  */
3767 static gst_avi_index_entry *
3768 gst_avi_demux_step_reverse (GstAviDemux * avi)
3769 {
3770   gst_avi_index_entry *entry;
3771   gint i;
3772
3773   avi->reverse_stop_index = avi->reverse_start_index;
3774   entry =
3775       gst_avi_demux_index_prev (avi, 0, avi->reverse_stop_index,
3776       GST_AVI_INDEX_ENTRY_FLAG_KEYFRAME);
3777   if (!entry) {
3778     GST_DEBUG_OBJECT (avi, "no valid index entry found index %d",
3779         avi->reverse_stop_index);
3780     return NULL;
3781   }
3782   avi->current_entry = avi->reverse_start_index = entry->index_nr;
3783   GST_DEBUG_OBJECT (avi,
3784       "reverse playback jump: start idx (%d) and stop idx (%d)",
3785       avi->reverse_start_index, avi->reverse_stop_index);
3786   gst_segment_set_last_stop (&avi->segment, GST_FORMAT_TIME, entry->ts);
3787   for (i = 0; i < avi->num_streams; i++) {
3788     avi->stream[i].last_flow = GST_FLOW_OK;
3789     avi->stream[i].discont = TRUE;
3790   }
3791   return entry;
3792 }
3793
3794 /*
3795  * Read data from one index entry
3796  */
3797 static GstFlowReturn
3798 gst_avi_demux_process_next_entry (GstAviDemux * avi)
3799 {
3800   GstFlowReturn res = GST_FLOW_OK;
3801   gboolean processed = FALSE;
3802   avi_stream_context *stream;
3803   gst_avi_index_entry *entry;
3804   GstBuffer *buf;
3805
3806   do {
3807     /* see if we are at the end */
3808     if ((avi->segment.rate > 0 && avi->current_entry >= avi->index_size))
3809       goto eos;
3810
3811     /* get next entry, this will work as we checked for the index size above */
3812     entry = &avi->index_entries[avi->current_entry++];
3813
3814     /* check for reverse playback */
3815     if (avi->segment.rate < 0 && avi->current_entry > avi->reverse_stop_index) {
3816       GST_LOG_OBJECT (avi, "stop_index %d reached", avi->reverse_stop_index);
3817
3818       /* check if we have pushed enough data for this segment */
3819       if (avi->reverse_start_index == 0)
3820         goto eos_reverse_zero;
3821       if (avi->index_entries[avi->reverse_start_index].ts < avi->segment.start)
3822         goto eos_reverse_segment;
3823
3824       if (!(entry = gst_avi_demux_step_reverse (avi)))
3825         goto eos;
3826
3827       avi->current_entry++;
3828     }
3829
3830     /* see if we have a valid stream, ignore if not
3831      * FIXME: can't we check this when building the index?
3832      *   we check it in _parse_index(), _stream_scan()
3833      */
3834     if (entry->stream_nr >= avi->num_streams) {
3835       GST_WARNING_OBJECT (avi,
3836           "Entry %d has non-existing stream nr %d",
3837           avi->current_entry - 1, entry->stream_nr);
3838       continue;
3839     }
3840
3841     /* get stream now */
3842     stream = &avi->stream[entry->stream_nr];
3843
3844     if (avi->segment.rate > 0.0) {
3845       /* only check this for fowards playback for now */
3846       if ((entry->flags & GST_AVI_INDEX_ENTRY_FLAG_KEYFRAME)
3847           && GST_CLOCK_TIME_IS_VALID (entry->ts)
3848           && GST_CLOCK_TIME_IS_VALID (avi->segment.stop)
3849           && (entry->ts > avi->segment.stop)) {
3850         goto eos_stop;
3851       }
3852     }
3853
3854     /* skip empty entries */
3855     if (entry->size == 0 || !stream->pad) {
3856       GST_DEBUG_OBJECT (avi, "Skipping entry %d (%d, %p)",
3857           avi->current_entry - 1, entry->size, stream->pad);
3858       goto next;
3859     }
3860
3861     GST_LOG ("reading buffer (size=%d) from stream %d at current pos %"
3862         G_GUINT64_FORMAT " (%llx)", entry->size, entry->stream_nr,
3863         avi->index_offset + entry->offset, avi->index_offset + entry->offset);
3864
3865     /* pull in the data */
3866     res = gst_pad_pull_range (avi->sinkpad, entry->offset +
3867         avi->index_offset, entry->size, &buf);
3868     if (res != GST_FLOW_OK)
3869       goto pull_failed;
3870
3871     /* check for short buffers, this is EOS as well */
3872     if (GST_BUFFER_SIZE (buf) < entry->size)
3873       goto short_buffer;
3874
3875     /* invert the picture if needed */
3876     buf = gst_avi_demux_invert (stream, buf);
3877
3878     /* mark non-keyframes */
3879     if (!(entry->flags & GST_AVI_INDEX_ENTRY_FLAG_KEYFRAME))
3880       GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
3881
3882     GST_BUFFER_TIMESTAMP (buf) = entry->ts;
3883     GST_BUFFER_DURATION (buf) = entry->dur;
3884     GST_BUFFER_OFFSET (buf) = GST_BUFFER_OFFSET_NONE;
3885     GST_BUFFER_OFFSET_END (buf) = GST_BUFFER_OFFSET_NONE;
3886     gst_buffer_set_caps (buf, GST_PAD_CAPS (stream->pad));
3887
3888     GST_DEBUG_OBJECT (avi, "Pushing buffer of size %d and time %"
3889         GST_TIME_FORMAT " on pad %s",
3890         GST_BUFFER_SIZE (buf), GST_TIME_ARGS (entry->ts),
3891         GST_PAD_NAME (stream->pad));
3892
3893     /* update current position in the segment */
3894     gst_segment_set_last_stop (&avi->segment, GST_FORMAT_TIME, entry->ts);
3895
3896     /* mark discont when pending */
3897     if (stream->discont) {
3898       GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
3899       stream->discont = FALSE;
3900     }
3901
3902     res = gst_pad_push (stream->pad, buf);
3903
3904     /* mark as processed, we increment the frame and byte counters then
3905      * leave the while loop and return the GstFlowReturn */
3906     processed = TRUE;
3907     GST_DEBUG_OBJECT (avi, "Processed buffer %d: %s", entry->index_nr,
3908         gst_flow_get_name (res));
3909
3910     if (avi->segment.rate < 0
3911         && entry->ts > avi->segment.stop && res == GST_FLOW_UNEXPECTED) {
3912       /* In reverse playback we can get a GST_FLOW_UNEXPECTED when
3913        * we are at the end of the segment, so we just need to jump
3914        * back to the previous section.
3915        */
3916       GST_DEBUG_OBJECT (avi, "downstream has reached end of segment");
3917
3918       if (!(entry = gst_avi_demux_step_reverse (avi)))
3919         goto eos;
3920
3921       res = GST_FLOW_OK;
3922
3923       stream->current_frame = entry->frames_before;
3924       stream->current_byte = entry->bytes_before;
3925
3926       continue;
3927     }
3928
3929     /* combine flows */
3930     res = gst_avi_demux_combine_flows (avi, stream, res);
3931
3932   next:
3933     stream->current_frame = entry->frames_before + 1;
3934     stream->current_byte = entry->bytes_before + entry->size;
3935   } while (!processed);
3936
3937 beach:
3938   GST_DEBUG_OBJECT (avi, "returning %s", gst_flow_get_name (res));
3939
3940   return res;
3941
3942   /* ERRORS */
3943 eos:
3944   {
3945     GST_LOG_OBJECT (avi, "Handled last index entry, setting EOS (%d > %d)",
3946         avi->current_entry, avi->index_size);
3947     /* we mark the first stream as EOS */
3948     res = GST_FLOW_UNEXPECTED;
3949     goto beach;
3950   }
3951 eos_stop:
3952   {
3953     GST_LOG_OBJECT (avi, "Found keyframe after segment,"
3954         " setting EOS (%" GST_TIME_FORMAT " > %" GST_TIME_FORMAT ")",
3955         GST_TIME_ARGS (entry->ts), GST_TIME_ARGS (avi->segment.stop));
3956     res = GST_FLOW_UNEXPECTED;
3957     goto beach;
3958   }
3959 eos_reverse_zero:
3960   {
3961     GST_DEBUG_OBJECT (avi, "start_index was 0, setting EOS");
3962     res = GST_FLOW_UNEXPECTED;
3963     goto beach;
3964   }
3965 eos_reverse_segment:
3966   {
3967     GST_DEBUG_OBJECT (avi, "full segment pushed, setting EOS");
3968     res = GST_FLOW_UNEXPECTED;
3969     goto beach;
3970   }
3971 pull_failed:
3972   {
3973     GST_DEBUG_OBJECT (avi,
3974         "pull range failed: pos=%" G_GUINT64_FORMAT " size=%d",
3975         entry->offset + avi->index_offset, entry->size);
3976     goto beach;
3977   }
3978 short_buffer:
3979   {
3980     GST_WARNING_OBJECT (avi, "Short read at offset %" G_GUINT64_FORMAT
3981         ", only got %d/%d bytes (truncated file?)", entry->offset +
3982         avi->index_offset, GST_BUFFER_SIZE (buf), entry->size);
3983     gst_buffer_unref (buf);
3984     res = GST_FLOW_UNEXPECTED;
3985     goto beach;
3986   }
3987 }
3988
3989 /*
3990  * Read data. If we have an index it delegates to
3991  * gst_avi_demux_process_next_entry().
3992  */
3993 static GstFlowReturn
3994 gst_avi_demux_stream_data (GstAviDemux * avi)
3995 {
3996   guint32 tag = 0;
3997   guint32 size = 0;
3998   gint stream_nr = 0;
3999   GstFlowReturn res = GST_FLOW_OK;
4000   GstFormat format = GST_FORMAT_TIME;
4001
4002   /* if we have a avi->index_entries[], we don't want to read
4003    * the stream linearly, but seek to the next ts/index_entry. */
4004   if (G_LIKELY (avi->index_entries != NULL))
4005     return gst_avi_demux_process_next_entry (avi);
4006
4007   if (G_UNLIKELY (avi->have_eos)) {
4008     /* Clean adapter, we're done */
4009     gst_adapter_clear (avi->adapter);
4010     return res;
4011   }
4012
4013   /*
4014      if (!gst_avi_demux_sync (avi, &tag, FALSE))
4015      return FALSE;
4016    */
4017
4018   /* Iterate until need more data, so adapter won't grow too much */
4019   while (1) {
4020     if (G_UNLIKELY (!gst_avi_demux_peek_chunk_info (avi, &tag, &size))) {
4021       return GST_FLOW_OK;
4022     }
4023
4024     GST_DEBUG ("Trying chunk (%" GST_FOURCC_FORMAT "), size %d",
4025         GST_FOURCC_ARGS (tag), size);
4026
4027     if (G_LIKELY ((tag & 0xff) >= '0' && (tag & 0xff) <= '9' &&
4028             ((tag >> 8) & 0xff) >= '0' && ((tag >> 8) & 0xff) <= '9')) {
4029       GST_LOG ("Chunk ok");
4030     } else if ((tag & 0xffff) == (('x' << 8) | 'i')) {
4031       GST_DEBUG ("Found sub-index tag");
4032       if (gst_avi_demux_peek_chunk (avi, &tag, &size)) {
4033         if ((size > 0) && (size != -1)) {
4034           GST_DEBUG ("  skipping %d bytes for now", size);
4035           gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
4036         }
4037       }
4038       return GST_FLOW_OK;
4039     } else if (tag == GST_RIFF_TAG_JUNK) {
4040       GST_DEBUG ("JUNK chunk, skipping");
4041     } else if (tag == GST_RIFF_TAG_idx1) {
4042       GST_DEBUG ("Found index tag, stream done");
4043       avi->have_eos = TRUE;
4044       return GST_FLOW_UNEXPECTED;
4045     } else if (tag == GST_RIFF_TAG_LIST) {
4046       /* movi chunks might be grouped in rec list */
4047       if (gst_adapter_available (avi->adapter) >= 12) {
4048         GST_DEBUG ("Found LIST tag, skipping LIST header");
4049         gst_adapter_flush (avi->adapter, 12);
4050         continue;
4051       }
4052       return GST_FLOW_OK;
4053     } else if (tag == GST_RIFF_TAG_JUNK) {
4054       /* rec list might contain JUNK chunks */
4055       GST_DEBUG ("Found JUNK tag");
4056       if (gst_avi_demux_peek_chunk (avi, &tag, &size)) {
4057         if ((size > 0) && (size != -1)) {
4058           GST_DEBUG ("  skipping %d bytes for now", size);
4059           gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
4060           continue;
4061         }
4062       }
4063       return GST_FLOW_OK;
4064     } else {
4065       GST_DEBUG ("No more stream chunks, send EOS");
4066       avi->have_eos = TRUE;
4067       return GST_FLOW_UNEXPECTED;
4068     }
4069
4070     if (G_UNLIKELY (!gst_avi_demux_peek_chunk (avi, &tag, &size))) {
4071       if ((size == 0) || (size == -1))
4072         gst_adapter_flush (avi->adapter, 8);
4073       return GST_FLOW_OK;
4074     }
4075     GST_DEBUG ("chunk ID %" GST_FOURCC_FORMAT ", size %u",
4076         GST_FOURCC_ARGS (tag), size);
4077
4078     stream_nr = CHUNKID_TO_STREAMNR (tag);
4079
4080     if (G_UNLIKELY (stream_nr < 0 || stream_nr >= avi->num_streams)) {
4081       /* recoverable */
4082       GST_WARNING ("Invalid stream ID %d (%" GST_FOURCC_FORMAT ")",
4083           stream_nr, GST_FOURCC_ARGS (tag));
4084       avi->offset += 8 + ((size + 1) & ~1);
4085       gst_adapter_flush (avi->adapter, 8 + ((size + 1) & ~1));
4086     } else {
4087       avi_stream_context *stream;
4088       GstClockTime next_ts = 0;
4089       GstBuffer *buf;
4090
4091       gst_adapter_flush (avi->adapter, 8);
4092
4093       /* get buffer */
4094       buf = gst_adapter_take_buffer (avi->adapter, ((size + 1) & ~1));
4095       /* patch the size */
4096       GST_BUFFER_SIZE (buf) = size;
4097       avi->offset += 8 + ((size + 1) & ~1);
4098
4099       /* get time of this buffer */
4100       stream = &avi->stream[stream_nr];
4101       gst_pad_query_position (stream->pad, &format, (gint64 *) & next_ts);
4102       if (G_UNLIKELY (format != GST_FORMAT_TIME))
4103         goto wrong_format;
4104
4105       /* set delay (if any)
4106          if (stream->strh->init_frames == stream->current_frame &&
4107          stream->delay == 0)
4108          stream->delay = next_ts;
4109        */
4110
4111       stream->current_frame++;
4112       stream->current_byte += size;
4113
4114       if (G_UNLIKELY (!stream->pad)) {
4115         GST_WARNING ("No pad.");
4116         gst_buffer_unref (buf);
4117       } else {
4118         GstClockTime dur_ts = 0;
4119
4120         /* invert the picture if needed */
4121         buf = gst_avi_demux_invert (stream, buf);
4122
4123         gst_pad_query_position (stream->pad, &format, (gint64 *) & dur_ts);
4124         if (G_UNLIKELY (format != GST_FORMAT_TIME))
4125           goto wrong_format;
4126
4127         GST_BUFFER_TIMESTAMP (buf) = next_ts;
4128         GST_BUFFER_DURATION (buf) = dur_ts - next_ts;
4129         gst_buffer_set_caps (buf, GST_PAD_CAPS (stream->pad));
4130         GST_DEBUG_OBJECT (avi,
4131             "Pushing buffer with time=%" GST_TIME_FORMAT
4132             " and size %d over pad %s", GST_TIME_ARGS (next_ts), size,
4133             GST_PAD_NAME (stream->pad));
4134
4135         /* update current position in the segment */
4136         gst_segment_set_last_stop (&avi->segment, GST_FORMAT_TIME, next_ts);
4137
4138         /* mark discont when pending */
4139         if (G_UNLIKELY (stream->discont)) {
4140           GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
4141           stream->discont = FALSE;
4142         }
4143         res = gst_pad_push (stream->pad, buf);
4144
4145         /* combine flows */
4146         res = gst_avi_demux_combine_flows (avi, stream, res);
4147         if (G_UNLIKELY (res != GST_FLOW_OK)) {
4148           GST_DEBUG ("Push failed; %s", gst_flow_get_name (res));
4149           return res;
4150         }
4151       }
4152     }
4153   }
4154
4155 done:
4156   return res;
4157
4158   /* ERRORS */
4159 wrong_format:
4160   {
4161     GST_DEBUG_OBJECT (avi, "format %s != GST_FORMAT_TIME",
4162         gst_format_get_name (format));
4163     res = GST_FLOW_ERROR;
4164     goto done;
4165   }
4166 }
4167
4168 /*
4169  * Send pending tags.
4170  */
4171 static void
4172 push_tag_lists (GstAviDemux * avi)
4173 {
4174   guint i;
4175
4176   if (!avi->got_tags)
4177     return;
4178
4179   GST_DEBUG_OBJECT (avi, "Pushing pending tag lists");
4180
4181   for (i = 0; i < avi->num_streams; i++)
4182     if (avi->stream[i].pad && avi->stream[i].taglist) {
4183       GST_DEBUG_OBJECT (avi->stream[i].pad, "Tags: %" GST_PTR_FORMAT,
4184           avi->stream[i].taglist);
4185       gst_element_found_tags_for_pad (GST_ELEMENT (avi), avi->stream[i].pad,
4186           avi->stream[i].taglist);
4187       avi->stream[i].taglist = NULL;
4188     }
4189
4190   if (avi->globaltags == NULL)
4191     avi->globaltags = gst_tag_list_new ();
4192
4193   gst_tag_list_add (avi->globaltags, GST_TAG_MERGE_REPLACE,
4194       GST_TAG_CONTAINER_FORMAT, "AVI", NULL);
4195
4196   GST_DEBUG_OBJECT (avi, "Global tags: %" GST_PTR_FORMAT, avi->globaltags);
4197   gst_element_found_tags (GST_ELEMENT (avi), avi->globaltags);
4198   avi->globaltags = NULL;
4199   avi->got_tags = FALSE;
4200 }
4201
4202 static void
4203 gst_avi_demux_loop (GstPad * pad)
4204 {
4205   GstFlowReturn res;
4206   GstAviDemux *avi = GST_AVI_DEMUX (GST_PAD_PARENT (pad));
4207
4208   switch (avi->state) {
4209     case GST_AVI_DEMUX_START:
4210       if (G_UNLIKELY ((res =
4211                   gst_avi_demux_stream_init_pull (avi)) != GST_FLOW_OK)) {
4212         GST_WARNING ("stream_init flow: %s", gst_flow_get_name (res));
4213         goto pause;
4214       }
4215       avi->state = GST_AVI_DEMUX_HEADER;
4216       /* fall-through */
4217     case GST_AVI_DEMUX_HEADER:
4218       if (G_UNLIKELY ((res =
4219                   gst_avi_demux_stream_header_pull (avi)) != GST_FLOW_OK)) {
4220         GST_WARNING ("stream_header flow: %s", gst_flow_get_name (res));
4221         goto pause;
4222       }
4223       avi->state = GST_AVI_DEMUX_MOVI;
4224       break;
4225     case GST_AVI_DEMUX_MOVI:
4226       if (G_UNLIKELY (avi->seek_event)) {
4227         gst_avi_demux_push_event (avi, avi->seek_event);
4228         avi->seek_event = NULL;
4229       }
4230       if (G_UNLIKELY (avi->got_tags)) {
4231         push_tag_lists (avi);
4232       }
4233       /* process each index entry in turn */
4234       res = gst_avi_demux_stream_data (avi);
4235
4236       /* pause when error */
4237       if (G_UNLIKELY (res != GST_FLOW_OK)) {
4238         GST_INFO ("stream_movi flow: %s", gst_flow_get_name (res));
4239         goto pause;
4240       }
4241       break;
4242     default:
4243       GST_ERROR_OBJECT (avi, "unknown state %d", avi->state);
4244       res = GST_FLOW_ERROR;
4245       goto pause;
4246   }
4247
4248   GST_LOG_OBJECT (avi, "state: %d res:%s", avi->state, gst_flow_get_name (res));
4249
4250   return;
4251
4252   /* ERRORS */
4253 pause:
4254   GST_LOG_OBJECT (avi, "pausing task, reason %s", gst_flow_get_name (res));
4255   avi->segment_running = FALSE;
4256   gst_pad_pause_task (avi->sinkpad);
4257
4258   if (GST_FLOW_IS_FATAL (res) || (res == GST_FLOW_NOT_LINKED)) {
4259     gboolean push_eos = TRUE;
4260
4261     if (res == GST_FLOW_UNEXPECTED) {
4262       /* handle end-of-stream/segment */
4263       if (avi->segment.flags & GST_SEEK_FLAG_SEGMENT) {
4264         gint64 stop;
4265
4266         if ((stop = avi->segment.stop) == -1)
4267           stop = avi->segment.duration;
4268
4269         GST_INFO_OBJECT (avi, "sending segment_done");
4270
4271         gst_element_post_message
4272             (GST_ELEMENT (avi),
4273             gst_message_new_segment_done (GST_OBJECT (avi), GST_FORMAT_TIME,
4274                 stop));
4275         push_eos = FALSE;
4276       }
4277     } else {
4278       /* for fatal errors we post an error message */
4279       GST_ELEMENT_ERROR (avi, STREAM, FAILED,
4280           (_("Internal data stream error.")),
4281           ("streaming stopped, reason %s", gst_flow_get_name (res)));
4282     }
4283     if (push_eos) {
4284       GST_INFO_OBJECT (avi, "sending eos");
4285       gst_avi_demux_push_event (avi, gst_event_new_eos ());
4286     }
4287   }
4288 }
4289
4290
4291 static GstFlowReturn
4292 gst_avi_demux_chain (GstPad * pad, GstBuffer * buf)
4293 {
4294   GstFlowReturn res;
4295   GstAviDemux *avi = GST_AVI_DEMUX (GST_PAD_PARENT (pad));
4296
4297   GST_DEBUG ("Store %d bytes in adapter", GST_BUFFER_SIZE (buf));
4298   gst_adapter_push (avi->adapter, buf);
4299
4300   switch (avi->state) {
4301     case GST_AVI_DEMUX_START:
4302       if ((res = gst_avi_demux_stream_init_push (avi)) != GST_FLOW_OK) {
4303         GST_WARNING ("stream_init flow: %s", gst_flow_get_name (res));
4304         break;
4305       }
4306       break;
4307     case GST_AVI_DEMUX_HEADER:
4308       if ((res = gst_avi_demux_stream_header_push (avi)) != GST_FLOW_OK) {
4309         GST_WARNING ("stream_header flow: %s", gst_flow_get_name (res));
4310         break;
4311       }
4312       break;
4313     case GST_AVI_DEMUX_MOVI:
4314       if (G_UNLIKELY (avi->seek_event)) {
4315         gst_avi_demux_push_event (avi, avi->seek_event);
4316         avi->seek_event = NULL;
4317       }
4318       if (G_UNLIKELY (avi->got_tags)) {
4319         push_tag_lists (avi);
4320       }
4321       res = gst_avi_demux_stream_data (avi);
4322       break;
4323     default:
4324       GST_ELEMENT_ERROR (avi, STREAM, FAILED, (NULL),
4325           ("Illegal internal state"));
4326       res = GST_FLOW_ERROR;
4327       break;
4328   }
4329
4330   GST_DEBUG_OBJECT (avi, "state: %d res:%s", avi->state,
4331       gst_flow_get_name (res));
4332
4333   return res;
4334 }
4335
4336 static gboolean
4337 gst_avi_demux_sink_activate (GstPad * sinkpad)
4338 {
4339   if (gst_pad_check_pull_range (sinkpad)) {
4340     GST_DEBUG ("going to pull mode");
4341     return gst_pad_activate_pull (sinkpad, TRUE);
4342   } else {
4343     GST_DEBUG ("going to push (streaming) mode");
4344     return gst_pad_activate_push (sinkpad, TRUE);
4345   }
4346 }
4347
4348 static gboolean
4349 gst_avi_demux_sink_activate_pull (GstPad * sinkpad, gboolean active)
4350 {
4351   GstAviDemux *avi = GST_AVI_DEMUX (GST_OBJECT_PARENT (sinkpad));
4352
4353   if (active) {
4354     avi->segment_running = TRUE;
4355     avi->streaming = FALSE;
4356     return gst_pad_start_task (sinkpad, (GstTaskFunction) gst_avi_demux_loop,
4357         sinkpad);
4358   } else {
4359     avi->segment_running = FALSE;
4360     return gst_pad_stop_task (sinkpad);
4361   }
4362 }
4363
4364 static gboolean
4365 gst_avi_demux_activate_push (GstPad * pad, gboolean active)
4366 {
4367   GstAviDemux *avi = GST_AVI_DEMUX (GST_OBJECT_PARENT (pad));
4368
4369   if (active) {
4370     GST_DEBUG ("avi: activating push/chain function");
4371     avi->streaming = TRUE;
4372   } else {
4373     GST_DEBUG ("avi: deactivating push/chain function");
4374   }
4375
4376   return TRUE;
4377 }
4378
4379 static GstStateChangeReturn
4380 gst_avi_demux_change_state (GstElement * element, GstStateChange transition)
4381 {
4382   GstStateChangeReturn ret;
4383   GstAviDemux *avi = GST_AVI_DEMUX (element);
4384
4385   switch (transition) {
4386     case GST_STATE_CHANGE_READY_TO_PAUSED:
4387       avi->streaming = FALSE;
4388       gst_segment_init (&avi->segment, GST_FORMAT_TIME);
4389       break;
4390     default:
4391       break;
4392   }
4393
4394   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
4395   if (ret == GST_STATE_CHANGE_FAILURE)
4396     goto done;
4397
4398   switch (transition) {
4399     case GST_STATE_CHANGE_PAUSED_TO_READY:
4400       gst_avi_demux_reset (avi);
4401       break;
4402     default:
4403       break;
4404   }
4405
4406 done:
4407   return ret;
4408 }