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