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