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