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