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