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