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