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