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