avidemux: add new index parsing code
[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, %6u/%6u 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               (gint) (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_index2:
1986  * @avi: calling element (used for debugging/errors).
1987  * @buf: buffer containing the full index.
1988  *
1989  * Read index entries from the provided buffer.
1990  * The buffer should contain a GST_RIFF_TAG_idx1 chunk.
1991  */
1992 static void
1993 gst_avi_demux_parse_index2 (GstAviDemux * avi, GstBuffer * buf)
1994 {
1995   guint64 pos_before;
1996   guint8 *data;
1997   guint size;
1998   guint i, num, n;
1999   gst_riff_index_entry *index;
2000   GstClockTime stamp;
2001   avi_stream_context *stream;
2002 #ifndef GST_DISABLE_GST_DEBUG
2003   guint total_idx = 0, total_max = 0;
2004 #endif
2005
2006   if (!buf)
2007     goto empty_list;
2008
2009   data = GST_BUFFER_DATA (buf);
2010   size = GST_BUFFER_SIZE (buf);
2011
2012   stamp = gst_util_get_timestamp ();
2013
2014   num = size / sizeof (gst_riff_index_entry);
2015   if (num == 0)
2016     goto empty_list;
2017
2018   index = (gst_riff_index_entry *) data;
2019
2020   pos_before = avi->offset;
2021   GST_INFO_OBJECT (avi, "Parsing index, nr_entries = %6d", num);
2022
2023   for (i = 0, n = 0; i < num; i++) {
2024     GstAviIndexEntry entry;
2025     guint32 id;
2026     guint stream_nr;
2027
2028     id = GST_READ_UINT32_LE (&index[i].id);
2029     entry.offset = GST_READ_UINT32_LE (&index[i].offset);
2030
2031     /* some sanity checks */
2032     if (G_UNLIKELY (id == GST_RIFF_rec || id == 0 ||
2033             (entry.offset == 0 && n > 0)))
2034       continue;
2035
2036     /* get the stream for this entry */
2037     stream_nr = CHUNKID_TO_STREAMNR (id);
2038     if (G_UNLIKELY (stream_nr >= avi->num_streams)) {
2039       GST_WARNING_OBJECT (avi,
2040           "Index entry %d has invalid stream nr %d", i, stream_nr);
2041       continue;
2042     }
2043     stream = &avi->stream[stream_nr];
2044     if (G_UNLIKELY (!stream->strh)) {
2045       GST_WARNING_OBJECT (avi, "Unhandled stream %d, skipping", stream_nr);
2046       continue;
2047     }
2048
2049     /* handle flags */
2050     if (stream->strh->type == GST_RIFF_FCC_auds) {
2051       /* all audio frames are keyframes */
2052       entry.flags = GST_AVI_INDEX_ENTRY_FLAG_KEYFRAME;
2053       stream->n_keyframes++;
2054     } else {
2055       entry.flags = GST_READ_UINT32_LE (&index[i].flags);
2056       if (entry.flags & GST_RIFF_IF_KEYFRAME) {
2057         entry.flags = GST_AVI_INDEX_ENTRY_FLAG_KEYFRAME;
2058         stream->n_keyframes++;
2059       } else {
2060         entry.flags = 0;
2061       }
2062     }
2063
2064     /* handle size */
2065     entry.size = GST_READ_UINT32_LE (&index[i].size);
2066
2067     /* add to the index */
2068     if (stream->idx_n >= stream->idx_max) {
2069       /* we need to make some more room */
2070       if (stream->idx_max == 0) {
2071         /* initial size guess, assume each stream has an equal amount of entries,
2072          * overshoot with at least 8K */
2073         stream->idx_max =
2074             (num / avi->num_streams) + (8192 / sizeof (GstAviIndexEntry));
2075       } else {
2076         stream->idx_max += 8192 / sizeof (GstAviIndexEntry);
2077         GST_CAT_DEBUG (GST_CAT_PERFORMANCE, "expanded index to %u",
2078             stream->idx_max);
2079       }
2080       stream->index = g_try_renew (GstAviIndexEntry, stream->index,
2081           stream->idx_max);
2082       if (G_UNLIKELY (!stream->index))
2083         goto out_of_mem;
2084     }
2085     if (stream->idx_n == 0) {
2086       /* first entry, set total bytes to 0 */
2087       entry.total = 0;
2088     } else {
2089       /* calculate bytes based on previous entry */
2090       entry.total = stream->index[stream->idx_n - 1].total +
2091           stream->index[stream->idx_n - 1].size;
2092     }
2093     /* and copy */
2094     GST_LOG_OBJECT (avi,
2095         "Adding stream %d, index entry %d, flags %02x, size %u "
2096         ", offset %" G_GUINT64_FORMAT ", total %" G_GUINT64_FORMAT, stream_nr,
2097         stream->idx_n, entry.flags, entry.size, entry.offset, entry.total);
2098     stream->index[stream->idx_n++] = entry;
2099
2100     /* figure out if the index is 0 based or relative to the MOVI start */
2101     if (G_UNLIKELY (n == 0)) {
2102       if (entry.offset < pos_before)
2103         avi->index_offset = pos_before + 8;
2104       else
2105         avi->index_offset = 0;
2106       GST_DEBUG ("index_offset = %" G_GUINT64_FORMAT, avi->index_offset);
2107     }
2108     n++;
2109   }
2110   /* get stream stats now */
2111   for (i = 0; i < avi->num_streams; i++) {
2112     GstAviIndexEntry *entry;
2113     guint64 total;
2114
2115     if (!(stream = &avi->stream[i]))
2116       continue;
2117     if (!stream->strh)
2118       continue;
2119     if (!stream->index || stream->idx_n == 0)
2120       continue;
2121
2122     entry = &stream->index[stream->idx_n - 1];
2123     total = entry->total + entry->size;
2124
2125     /* calculate duration */
2126     if (stream->is_vbr) {
2127       /* VBR stream next timestamp */
2128       if (stream->strh->type == GST_RIFF_FCC_auds) {
2129         stream->idx_duration =
2130             avi_stream_convert_frames_to_time_unchecked (stream, total);
2131       } else {
2132         stream->idx_duration =
2133             avi_stream_convert_frames_to_time_unchecked (stream, stream->idx_n);
2134       }
2135     } else {
2136       /* constant rate stream */
2137       stream->idx_duration = avi_stream_convert_bytes_to_time_unchecked (stream,
2138           total);
2139     }
2140 #ifndef GST_DISABLE_GST_DEBUG
2141     total_idx += stream->idx_n;
2142     total_max += stream->idx_max;
2143 #endif
2144     GST_INFO_OBJECT (avi, "Stream %d, dur %" GST_TIME_FORMAT ", %6u entries, "
2145         "%5lu keyframes, entry size = %2u, total size = %10u, allocated %10u",
2146         i, GST_TIME_ARGS (stream->idx_duration), stream->idx_n,
2147         stream->n_keyframes, (guint) sizeof (GstAviIndexEntry),
2148         (guint) (stream->idx_n * sizeof (GstAviIndexEntry)),
2149         (guint) (stream->idx_max * sizeof (GstAviIndexEntry)));
2150   }
2151 #ifndef GST_DISABLE_GST_DEBUG
2152   total_idx *= sizeof (GstAviIndexEntry);
2153   total_max *= sizeof (GstAviIndexEntry);
2154 #endif
2155   GST_INFO_OBJECT (avi, "%u bytes for index vs %u ideally, %u wasted",
2156       total_max, total_idx, total_max - total_idx);
2157
2158   stamp = gst_util_get_timestamp () - stamp;
2159   GST_CAT_DEBUG (GST_CAT_PERFORMANCE, "parsing index %" GST_TIME_FORMAT,
2160       GST_TIME_ARGS (stamp));
2161
2162   return;
2163
2164   /* ERRORS */
2165 empty_list:
2166   {
2167     GST_DEBUG_OBJECT (avi, "empty index");
2168     return;
2169   }
2170 out_of_mem:
2171   {
2172     GST_ELEMENT_ERROR (avi, RESOURCE, NO_SPACE_LEFT, (NULL),
2173         ("Cannot allocate memory for %u*%u=%u bytes",
2174             (guint) sizeof (GstAviIndexEntry), num,
2175             (guint) sizeof (GstAviIndexEntry) * num));
2176     return;
2177   }
2178 }
2179
2180 /*
2181  * gst_avi_demux_parse_index:
2182  * @avi: calling element (used for debugging/errors).
2183  * @buf: buffer containing the full index.
2184  * @entries_list: list (returned by this function) containing the index
2185  *                entries parsed from the buffer. The first in the list
2186  *                is also a pointer to the allocated data and should be
2187  *                free'ed at some point.
2188  *
2189  * Read index entries from the provided buffer. Takes ownership of @buf.
2190  * The buffer should contain a GST_RIFF_TAG_idx1 chunk.
2191  */
2192 static void
2193 gst_avi_demux_parse_index (GstAviDemux * avi,
2194     GstBuffer * buf, GList ** _entries_list)
2195 {
2196   guint64 pos_before = avi->offset;
2197   gst_avi_index_entry *entries = NULL;
2198   guint8 *data;
2199   GList *entries_list = NULL;
2200   guint i, num, n;
2201 #ifndef GST_DISABLE_GST_DEBUG
2202   gulong _nr_keyframes = 0;
2203 #endif
2204   GstClockTime stamp;
2205
2206   if (!buf || !GST_BUFFER_SIZE (buf)) {
2207     *_entries_list = NULL;
2208     GST_DEBUG ("empty index");
2209     if (buf)
2210       gst_buffer_unref (buf);
2211     return;
2212   }
2213
2214   stamp = gst_util_get_timestamp ();
2215
2216   data = GST_BUFFER_DATA (buf);
2217   num = GST_BUFFER_SIZE (buf) / sizeof (gst_riff_index_entry);
2218   if (!(entries = g_try_new (gst_avi_index_entry, num)))
2219     goto out_of_mem;
2220
2221   GST_INFO_OBJECT (avi, "Parsing index, nr_entries = %6d", num);
2222
2223   for (i = 0, n = 0; i < num; i++) {
2224     gint64 next_ts;
2225     gst_riff_index_entry entry, *_entry;
2226     avi_stream_context *stream;
2227     guint stream_nr;
2228     gst_avi_index_entry *target;
2229
2230     _entry = &((gst_riff_index_entry *) data)[i];
2231     entry.id = GST_READ_UINT32_LE (&_entry->id);
2232     entry.offset = GST_READ_UINT32_LE (&_entry->offset);
2233     entry.flags = GST_READ_UINT32_LE (&_entry->flags);
2234     entry.size = GST_READ_UINT32_LE (&_entry->size);
2235     target = &entries[n];
2236
2237     if (entry.id == GST_RIFF_rec || entry.id == 0 ||
2238         (entry.offset == 0 && n > 0))
2239       continue;
2240
2241     stream_nr = CHUNKID_TO_STREAMNR (entry.id);
2242     if (stream_nr >= avi->num_streams) {
2243       GST_WARNING_OBJECT (avi,
2244           "Index entry %d has invalid stream nr %d", i, stream_nr);
2245       continue;
2246     }
2247     target->stream_nr = stream_nr;
2248     stream = &avi->stream[stream_nr];
2249
2250     if (!stream->strh) {
2251       GST_WARNING_OBJECT (avi, "Unhandled stream %d, skipping", stream_nr);
2252       continue;
2253     }
2254
2255     target->index_nr = i;
2256     target->flags =
2257         (entry.flags & GST_RIFF_IF_KEYFRAME) ? GST_AVI_INDEX_ENTRY_FLAG_KEYFRAME
2258         : 0;
2259     target->size = entry.size;
2260     target->offset = entry.offset + 8;
2261
2262     /* figure out if the index is 0 based or relative to the MOVI start */
2263     if (n == 0) {
2264       if (target->offset < pos_before)
2265         avi->index_offset = pos_before + 8;
2266       else
2267         avi->index_offset = 0;
2268       GST_DEBUG ("index_offset = %" G_GUINT64_FORMAT, avi->index_offset);
2269     }
2270
2271     if (stream->strh->type == GST_RIFF_FCC_auds) {
2272       /* all audio frames are keyframes */
2273       target->flags |= GST_AVI_INDEX_ENTRY_FLAG_KEYFRAME;
2274     }
2275 #ifndef GST_DISABLE_GST_DEBUG
2276     if (target->flags & GST_AVI_INDEX_ENTRY_FLAG_KEYFRAME)
2277       _nr_keyframes++;
2278 #endif
2279
2280     /* stream duration unknown, now we can calculate it */
2281     if (stream->idx_duration == -1)
2282       stream->idx_duration = 0;
2283
2284     /* timestamps */
2285     target->ts = stream->idx_duration;
2286     if (stream->is_vbr) {
2287       /* VBR stream next timestamp */
2288       if (stream->strh->type == GST_RIFF_FCC_auds) {
2289         next_ts = avi_stream_convert_frames_to_time_unchecked (stream,
2290             stream->total_blocks + 1);
2291       } else {
2292         next_ts = avi_stream_convert_frames_to_time_unchecked (stream,
2293             stream->total_frames + 1);
2294       }
2295     } else {
2296       /* constant rate stream */
2297       next_ts = avi_stream_convert_bytes_to_time_unchecked (stream,
2298           stream->total_bytes + target->size);
2299     }
2300     /* duration is next - current */
2301     target->dur = next_ts - target->ts;
2302
2303     /* stream position */
2304     target->bytes_before = stream->total_bytes;
2305     target->frames_before = stream->total_frames;
2306
2307     stream->total_bytes += target->size;
2308     stream->total_frames++;
2309     if (stream->strh->type == GST_RIFF_FCC_auds) {
2310       if (stream->strf.auds->blockalign > 0)
2311         stream->total_blocks +=
2312             (target->size + stream->strf.auds->blockalign -
2313             1) / stream->strf.auds->blockalign;
2314       else
2315         stream->total_blocks++;
2316     }
2317     stream->idx_duration = next_ts;
2318
2319     GST_LOG_OBJECT (avi,
2320         "Adding index entry %d (%6u), flags %02x, stream %d, size %u "
2321         ", offset %" G_GUINT64_FORMAT ", time %" GST_TIME_FORMAT ", dur %"
2322         GST_TIME_FORMAT,
2323         target->index_nr, stream->total_frames - 1, target->flags,
2324         target->stream_nr, target->size, target->offset,
2325         GST_TIME_ARGS (target->ts), GST_TIME_ARGS (target->dur));
2326     entries_list = g_list_prepend (entries_list, target);
2327
2328     n++;
2329   }
2330
2331   GST_INFO_OBJECT (avi, "Parsed index, %6u/%6u entries, %5lu keyframes, "
2332       "entry size = %2u, total size = %10u", n, num, _nr_keyframes,
2333       (guint) sizeof (gst_avi_index_entry),
2334       (guint) (n * sizeof (gst_avi_index_entry)));
2335
2336   gst_buffer_unref (buf);
2337
2338   if (n > 0) {
2339     *_entries_list = g_list_reverse (entries_list);
2340   } else {
2341     g_free (entries);
2342   }
2343
2344   stamp = gst_util_get_timestamp () - stamp;
2345   GST_CAT_DEBUG (GST_CAT_PERFORMANCE, "parsing index %" GST_TIME_FORMAT,
2346       GST_TIME_ARGS (stamp));
2347
2348   return;
2349
2350   /* ERRORS */
2351 out_of_mem:
2352   {
2353     GST_ELEMENT_ERROR (avi, RESOURCE, NO_SPACE_LEFT, (NULL),
2354         ("Cannot allocate memory for %u*%u=%u bytes",
2355             (guint) sizeof (gst_avi_index_entry), num,
2356             (guint) sizeof (gst_avi_index_entry) * num));
2357     gst_buffer_unref (buf);
2358   }
2359 }
2360
2361 /*
2362  * gst_avi_demux_stream_index:
2363  * @avi: avi demuxer object.
2364  * @index: list of index entries, returned by this function.
2365  * @alloc_list: list of allocated data, returned by this function.
2366  *
2367  * Seeks to index and reads it.
2368  */
2369 static void
2370 gst_avi_demux_stream_index (GstAviDemux * avi,
2371     GList ** index, GList ** alloc_list)
2372 {
2373   GstFlowReturn res;
2374   guint64 offset = avi->offset;
2375   GstBuffer *buf;
2376   guint32 tag;
2377   guint32 size;
2378
2379   GST_DEBUG ("demux stream index at offset %" G_GUINT64_FORMAT, offset);
2380
2381   *alloc_list = NULL;
2382   *index = NULL;
2383
2384   /* get chunk information */
2385   res = gst_pad_pull_range (avi->sinkpad, offset, 8, &buf);
2386   if (res != GST_FLOW_OK)
2387     goto pull_failed;
2388   else if (GST_BUFFER_SIZE (buf) < 8)
2389     goto too_small;
2390
2391   /* check tag first before blindy trying to read 'size' bytes */
2392   tag = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf));
2393   size = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf) + 4);
2394   if (tag == GST_RIFF_TAG_LIST) {
2395     /* this is the movi tag */
2396     GST_DEBUG_OBJECT (avi, "skip LIST chunk, size %" G_GUINT32_FORMAT,
2397         (8 + ((size + 1) & ~1)));
2398     offset += 8 + ((size + 1) & ~1);
2399     gst_buffer_unref (buf);
2400     res = gst_pad_pull_range (avi->sinkpad, offset, 8, &buf);
2401     if (res != GST_FLOW_OK)
2402       goto pull_failed;
2403     else if (GST_BUFFER_SIZE (buf) < 8)
2404       goto too_small;
2405     tag = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf));
2406     size = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf) + 4);
2407   }
2408
2409   if (tag != GST_RIFF_TAG_idx1)
2410     goto no_index;
2411   if (!size)
2412     goto zero_index;
2413
2414   gst_buffer_unref (buf);
2415
2416   GST_DEBUG ("index found at offset %" G_GUINT64_FORMAT, offset);
2417
2418   /* read chunk, advance offset */
2419   if (gst_riff_read_chunk (GST_ELEMENT_CAST (avi),
2420           avi->sinkpad, &offset, &tag, &buf) != GST_FLOW_OK)
2421     return;
2422
2423   GST_DEBUG ("will parse index chunk size %u for tag %"
2424       GST_FOURCC_FORMAT, GST_BUFFER_SIZE (buf), GST_FOURCC_ARGS (tag));
2425
2426   gst_avi_demux_parse_index2 (avi, buf);
2427   gst_avi_demux_parse_index (avi, buf, index);
2428   if (*index)
2429     *alloc_list = g_list_append (*alloc_list, (*index)->data);
2430
2431 #ifndef GST_DISABLE_GST_DEBUG
2432   /* debug our indexes */
2433   {
2434     gint i;
2435     avi_stream_context *stream;
2436
2437     for (i = 0; i < avi->num_streams; i++) {
2438       stream = &avi->stream[i];
2439       GST_DEBUG_OBJECT (avi, "stream %u: %u frames, %" G_GINT64_FORMAT " bytes",
2440           i, stream->total_frames, stream->total_bytes);
2441     }
2442   }
2443 #endif
2444   return;
2445
2446   /* ERRORS */
2447 pull_failed:
2448   {
2449     GST_DEBUG_OBJECT (avi,
2450         "pull range failed: pos=%" G_GUINT64_FORMAT " size=8", offset);
2451     return;
2452   }
2453 too_small:
2454   {
2455     GST_DEBUG_OBJECT (avi, "Buffer is too small");
2456     gst_buffer_unref (buf);
2457     return;
2458   }
2459 no_index:
2460   {
2461     GST_WARNING_OBJECT (avi,
2462         "No index data (idx1) after movi chunk, but %" GST_FOURCC_FORMAT,
2463         GST_FOURCC_ARGS (tag));
2464     gst_buffer_unref (buf);
2465     return;
2466   }
2467 zero_index:
2468   {
2469     GST_WARNING_OBJECT (avi, "Empty index data (idx1) after movi chunk");
2470     gst_buffer_unref (buf);
2471     return;
2472   }
2473 }
2474
2475 #if 0
2476 /*
2477  * Sync to next data chunk.
2478  */
2479 static gboolean
2480 gst_avi_demux_skip (GstAviDemux * avi, gboolean prevent_eos)
2481 {
2482   GstRiffRead *riff = GST_RIFF_READ (avi);
2483
2484   if (prevent_eos) {
2485     guint64 pos, length;
2486     guint size;
2487     guint8 *data;
2488
2489     pos = gst_bytestream_tell (riff->bs);
2490     length = gst_bytestream_length (riff->bs);
2491
2492     if (pos + 8 > length)
2493       return FALSE;
2494
2495     if (gst_bytestream_peek_bytes (riff->bs, &data, 8) != 8)
2496       return FALSE;
2497
2498     size = GST_READ_UINT32_LE (&data[4]);
2499     if (size & 1)
2500       size++;
2501
2502     /* Note, we're going to skip which might involve seeks. Therefore,
2503      * we need 1 byte more! */
2504     if (pos + 8 + size >= length)
2505       return FALSE;
2506   }
2507
2508   return gst_riff_read_skip (riff);
2509 }
2510
2511 static gboolean
2512 gst_avi_demux_sync (GstAviDemux * avi, guint32 * ret_tag, gboolean prevent_eos)
2513 {
2514   GstRiffRead *riff = GST_RIFF_READ (avi);
2515   guint32 tag;
2516   guint64 length = gst_bytestream_length (riff->bs);
2517
2518   if (prevent_eos && gst_bytestream_tell (riff->bs) + 12 >= length)
2519     return FALSE;
2520
2521   /* peek first (for the end of this 'list/movi' section) */
2522   if (!(tag = gst_riff_peek_tag (riff, &avi->level_up)))
2523     return FALSE;
2524
2525   /* if we're at top-level, we didn't read the 'movi'
2526    * list tag yet. This can also be 'AVIX' in case of
2527    * openDML-2.0 AVI files. Lastly, it might be idx1,
2528    * in which case we skip it so we come at EOS. */
2529   while (1) {
2530     if (prevent_eos && gst_bytestream_tell (riff->bs) + 12 >= length)
2531       return FALSE;
2532
2533     if (!(tag = gst_riff_peek_tag (riff, NULL)))
2534       return FALSE;
2535
2536     switch (tag) {
2537       case GST_RIFF_TAG_LIST:
2538         if (!(tag = gst_riff_peek_list (riff)))
2539           return FALSE;
2540
2541         switch (tag) {
2542           case GST_RIFF_LIST_AVIX:
2543             if (!gst_riff_read_list (riff, &tag))
2544               return FALSE;
2545             break;
2546
2547           case GST_RIFF_LIST_movi:
2548             if (!gst_riff_read_list (riff, &tag))
2549               return FALSE;
2550             /* fall-through */
2551
2552           case GST_RIFF_rec:
2553             goto done;
2554
2555           default:
2556             GST_WARNING ("Unknown list %" GST_FOURCC_FORMAT " before AVI data",
2557                 GST_FOURCC_ARGS (tag));
2558             /* fall-through */
2559
2560           case GST_RIFF_TAG_JUNK:
2561             if (!gst_avi_demux_skip (avi, prevent_eos))
2562               return FALSE;
2563             break;
2564         }
2565         break;
2566
2567       default:
2568         if ((tag & 0xff) >= '0' && (tag & 0xff) <= '9' &&
2569             ((tag >> 8) & 0xff) >= '0' && ((tag >> 8) & 0xff) <= '9') {
2570           goto done;
2571         }
2572         /* pass-through */
2573
2574       case GST_RIFF_TAG_idx1:
2575       case GST_RIFF_TAG_JUNK:
2576         if (!gst_avi_demux_skip (avi, prevent_eos)) {
2577           return FALSE;
2578         }
2579         break;
2580     }
2581   }
2582 done:
2583   /* And then, we get the data */
2584   if (prevent_eos && gst_bytestream_tell (riff->bs) + 12 >= length)
2585     return FALSE;
2586
2587   if (!(tag = gst_riff_peek_tag (riff, NULL)))
2588     return FALSE;
2589
2590   /* Support for rec-list files */
2591   switch (tag) {
2592     case GST_RIFF_TAG_LIST:
2593       if (!(tag = gst_riff_peek_list (riff)))
2594         return FALSE;
2595       if (tag == GST_RIFF_rec) {
2596         /* Simply skip the list */
2597         if (!gst_riff_read_list (riff, &tag))
2598           return FALSE;
2599         if (!(tag = gst_riff_peek_tag (riff, NULL)))
2600           return FALSE;
2601       }
2602       break;
2603
2604     case GST_RIFF_TAG_JUNK:
2605       gst_avi_demux_skip (avi, prevent_eos);
2606       return FALSE;
2607   }
2608
2609   if (ret_tag)
2610     *ret_tag = tag;
2611
2612   return TRUE;
2613 }
2614 #endif
2615
2616 /*
2617  * gst_avi_demux_peek_tag:
2618  *
2619  * Returns the tag and size of the next chunk
2620  */
2621 static GstFlowReturn
2622 gst_avi_demux_peek_tag (GstAviDemux * avi, guint64 offset, guint32 * tag,
2623     guint * size)
2624 {
2625   GstFlowReturn res = GST_FLOW_OK;
2626   GstBuffer *buf = NULL;
2627   guint bufsize;
2628
2629   res = gst_pad_pull_range (avi->sinkpad, offset, 8, &buf);
2630   if (res != GST_FLOW_OK)
2631     goto pull_failed;
2632
2633   bufsize = GST_BUFFER_SIZE (buf);
2634   if (bufsize != 8)
2635     goto wrong_size;
2636
2637   *tag = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf));
2638   *size = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf) + 4);
2639
2640   GST_LOG_OBJECT (avi, "Tag[%" GST_FOURCC_FORMAT "] (size:%d) %"
2641       G_GINT64_FORMAT " -- %" G_GINT64_FORMAT, GST_FOURCC_ARGS (*tag),
2642       *size, offset + 8, offset + 8 + (gint64) * size);
2643 done:
2644   gst_buffer_unref (buf);
2645
2646   return res;
2647
2648   /* ERRORS */
2649 pull_failed:
2650   {
2651     GST_DEBUG_OBJECT (avi, "pull_ranged returned %s", gst_flow_get_name (res));
2652     return res;
2653   }
2654 wrong_size:
2655   {
2656     GST_DEBUG_OBJECT (avi, "got %d bytes which is <> 8 bytes", bufsize);
2657     res = GST_FLOW_ERROR;
2658     goto done;
2659   }
2660 }
2661
2662 /*
2663  * gst_avi_demux_next_data_buffer:
2664  *
2665  * Returns the offset and size of the next buffer
2666  * Position is the position of the buffer (after tag and size)
2667  */
2668 static GstFlowReturn
2669 gst_avi_demux_next_data_buffer (GstAviDemux * avi, guint64 * offset,
2670     guint32 * tag, guint * size)
2671 {
2672   guint64 off = *offset;
2673   guint _size = 0;
2674   GstFlowReturn res;
2675
2676   do {
2677     res = gst_avi_demux_peek_tag (avi, off, tag, &_size);
2678     if (res != GST_FLOW_OK)
2679       break;
2680     if (*tag == GST_RIFF_TAG_LIST || *tag == GST_RIFF_TAG_RIFF)
2681       off += 8 + 4;             /* skip tag + size + subtag */
2682     else {
2683       *offset = off + 8;
2684       *size = _size;
2685       break;
2686     }
2687   } while (TRUE);
2688
2689   return res;
2690 }
2691
2692 /*
2693  * gst_avi_demux_stream_scan:
2694  * @avi: calling element (used for debugging/errors).
2695  * @index: list of index entries, returned by this function.
2696  * @alloc_list: list of allocated data, returned by this function.
2697  *
2698  * Scan the file for all chunks to "create" a new index.
2699  * Return value indicates if we can continue reading the stream. It
2700  * does not say anything about whether we created an index.
2701  *
2702  * pull-range based
2703  */
2704 static gboolean
2705 gst_avi_demux_stream_scan (GstAviDemux * avi,
2706     GList ** index, GList ** alloc_list)
2707 {
2708   GstFlowReturn res;
2709   gst_avi_index_entry *entry, *entries = NULL;
2710   avi_stream_context *stream;
2711   GstFormat format;
2712   guint64 pos = avi->offset;
2713   guint64 length;
2714   gint64 tmplength;
2715   guint32 tag = 0;
2716   GList *list = NULL;
2717   guint index_size = 0;
2718
2719   /* FIXME:
2720    * - implement non-seekable source support.
2721    */
2722   GST_DEBUG_OBJECT (avi,
2723       "Creating index %s existing index, starting at offset %" G_GUINT64_FORMAT,
2724       ((*index) ? "with" : "without"), pos);
2725
2726   format = GST_FORMAT_BYTES;
2727   if (!gst_pad_query_peer_duration (avi->sinkpad, &format, &tmplength))
2728     return FALSE;
2729
2730   length = tmplength;
2731
2732   if (*index) {
2733     entry = g_list_last (*index)->data;
2734     pos = entry->offset + avi->index_offset + entry->size;
2735     if (entry->size & 1)
2736       pos++;
2737
2738     if (pos >= length) {
2739       GST_LOG_OBJECT (avi, "Complete index, we're done");
2740       return TRUE;
2741     }
2742
2743     GST_LOG_OBJECT (avi, "Incomplete index, seeking to last valid entry @ %"
2744         G_GUINT64_FORMAT " of %" G_GUINT64_FORMAT " (%"
2745         G_GUINT64_FORMAT "+%u)", pos, length, entry->offset, entry->size);
2746   }
2747
2748   while (TRUE) {
2749     guint stream_nr;
2750     guint size = 0;
2751
2752     res = gst_avi_demux_next_data_buffer (avi, &pos, &tag, &size);
2753     if (G_UNLIKELY (res != GST_FLOW_OK))
2754       break;
2755
2756     /* check valid stream */
2757     stream_nr = CHUNKID_TO_STREAMNR (tag);
2758     if (G_UNLIKELY (stream_nr >= avi->num_streams)) {
2759       GST_WARNING_OBJECT (avi,
2760           "Index entry has invalid stream nr %d", stream_nr);
2761       goto next;
2762     }
2763
2764     stream = &avi->stream[stream_nr];
2765     if (G_UNLIKELY (stream->pad == NULL)) {
2766       GST_WARNING_OBJECT (avi,
2767           "Stream %d does not have an output pad, can't create new index",
2768           stream_nr);
2769       goto next;
2770     }
2771
2772     /* pre-allocate */
2773     if (G_UNLIKELY (index_size % 1024 == 0)) {
2774       entries = g_new (gst_avi_index_entry, 1024);
2775       *alloc_list = g_list_prepend (*alloc_list, entries);
2776     }
2777     entry = &entries[index_size % 1024];
2778
2779     entry->index_nr = index_size++;
2780     entry->stream_nr = stream_nr;
2781     entry->flags = GST_AVI_INDEX_ENTRY_FLAG_KEYFRAME;
2782     entry->offset = pos - avi->index_offset;
2783     entry->size = size;
2784
2785     /* timestamps, get timestamps of two consecutive frames to calculate
2786      * timestamp and duration. */
2787     format = GST_FORMAT_TIME;
2788     if (stream->is_vbr) {
2789       /* VBR stream */
2790       entry->ts = avi_stream_convert_frames_to_time_unchecked (stream,
2791           stream->total_frames);
2792       entry->dur = avi_stream_convert_frames_to_time_unchecked (stream,
2793           stream->total_frames + 1);
2794     } else {
2795       /* constant rate stream */
2796       entry->ts = avi_stream_convert_bytes_to_time_unchecked (stream,
2797           stream->total_bytes);
2798       entry->dur = avi_stream_convert_bytes_to_time_unchecked (stream,
2799           stream->total_bytes + entry->size);
2800     }
2801     entry->dur -= entry->ts;
2802
2803     /* stream position */
2804     entry->bytes_before = stream->total_bytes;
2805     stream->total_bytes += entry->size;
2806     entry->frames_before = stream->total_frames;
2807     stream->total_frames++;
2808     stream->idx_duration = entry->ts + entry->dur;
2809
2810     list = g_list_prepend (list, entry);
2811     GST_DEBUG_OBJECT (avi, "Added index entry %d (in stream: %d), offset %"
2812         G_GUINT64_FORMAT ", time %" GST_TIME_FORMAT " for stream %d",
2813         index_size - 1, entry->frames_before, entry->offset,
2814         GST_TIME_ARGS (entry->ts), entry->stream_nr);
2815
2816   next:
2817     /* update position */
2818     pos += GST_ROUND_UP_2 (size);
2819     if (G_UNLIKELY (pos > length)) {
2820       GST_WARNING_OBJECT (avi,
2821           "Stopping index lookup since we are further than EOF");
2822       break;
2823     }
2824   }
2825
2826   /* FIXME: why is this disabled */
2827 #if 0
2828   while (gst_avi_demux_sync (avi, &tag, TRUE)) {
2829     guint stream_nr = CHUNKID_TO_STREAMNR (tag);
2830     guint8 *data;
2831     GstFormat format = GST_FORMAT_TIME;
2832
2833     if (stream_nr >= avi->num_streams)
2834       goto next;
2835     stream = &avi->stream[stream_nr];
2836
2837     /* get chunk size */
2838     if (gst_bytestream_peek_bytes (riff->bs, &data, 8) != 8)
2839       goto next;
2840
2841     /* fill in */
2842     entry->index_nr = index_size++;
2843     entry->stream_nr = stream_nr;
2844     entry->flags = GST_AVI_INDEX_ENTRY_FLAG_KEYFRAME;
2845     entry->offset = gst_bytestream_tell (riff->bs) + 8 - avi->index_offset;
2846     entry->size = GST_READ_UINT32_LE (&data[4]);
2847
2848     /* timestamps */
2849     if (stream->is_vbr) {
2850       /* VBR stream */
2851       entry->ts = avi_stream_convert_frames_to_time_unchecked (stream,
2852           stream->total_frames);
2853       entry->dur = avi_stream_convert_frames_to_time_unchecked (stream,
2854           stream->total_frames + 1);
2855     } else {
2856       /* constant rate stream */
2857       entry->ts = avi_stream_convert_bytes_to_time_unchecked (stream,
2858           stream->total_bytes);
2859       entry->dur = avi_stream_convert_bytes_to_time_unchecked (stream,
2860           stream->total_bytes + entry->size);
2861     }
2862     entry->dur -= entry->ts;
2863
2864     /* stream position */
2865     entry->bytes_before = stream->total_bytes;
2866     stream->total_bytes += entry->size;
2867     entry->frames_before = stream->total_frames;
2868     stream->total_frames++;
2869
2870     list = g_list_prepend (list, entry);
2871     GST_DEBUG_OBJECT (avi, "Added index entry %d (in stream: %d), offset %"
2872         G_GUINT64_FORMAT ", time %" GST_TIME_FORMAT " for stream %d",
2873         index_size - 1, entry->frames_before, entry->offset,
2874         GST_TIME_ARGS (entry->ts), entry->stream_nr);
2875
2876   next:
2877     if (!gst_avi_demux_skip (avi, TRUE))
2878       break;
2879   }
2880   /* seek back */
2881   if (!(event = gst_riff_read_seek (riff, pos))) {
2882     g_list_free (list);
2883     return FALSE;
2884   }
2885   gst_event_unref (event);
2886
2887 #endif
2888
2889   GST_DEBUG_OBJECT (avi, "index created, %d items", index_size);
2890
2891   *index = g_list_concat (*index, g_list_reverse (list));
2892
2893   return TRUE;
2894 }
2895
2896 /*
2897  * gst_avi_demux_massage_index:
2898  * @avi: calling element (used for debugging/errors).
2899  *
2900  * We're going to go over each entry in the index and finetune
2901  * some things we don't like about AVI. For example, a single
2902  * chunk might be too long. Also, individual streams might be
2903  * out-of-sync. In the first case, we cut the chunk in several
2904  * smaller pieces. In the second case, we re-order chunk reading
2905  * order. The end result should be a smoother playing AVI.
2906  */
2907 static gboolean
2908 gst_avi_demux_massage_index (GstAviDemux * avi,
2909     GList * list, GList * alloc_list)
2910 {
2911   gst_avi_index_entry *entry;
2912   avi_stream_context *stream;
2913   guint i;
2914   GList *node;
2915   gint64 delay = G_GINT64_CONSTANT (0);
2916   GstClockTime stamp;
2917
2918   stamp = gst_util_get_timestamp ();
2919
2920   GST_LOG_OBJECT (avi, "Starting index massage, nr_entries = %d",
2921       list ? g_list_length (list) : 0);
2922
2923   if (list) {
2924 #ifndef GST_DISABLE_GST_DEBUG
2925     guint num_added_total = 0;
2926     guint num_per_stream[GST_AVI_DEMUX_MAX_STREAMS] = { 0, };
2927 #endif
2928     GST_LOG_OBJECT (avi,
2929         "I'm now going to cut large chunks into smaller pieces");
2930
2931     /* cut chunks in small (seekable) pieces
2932      * FIXME: this should be a property where a value of
2933      * GST_CLOCK_TIME_NONE would disable the chunking
2934      */
2935 #define MAX_DURATION (GST_SECOND / 2)
2936     for (i = 0; i < avi->num_streams; i++) {
2937       /* only chop streams that have exactly *one* chunk */
2938       if (avi->stream[i].total_frames != 1)
2939         continue;
2940
2941       for (node = list; node != NULL; node = node->next) {
2942         entry = node->data;
2943
2944         if (entry->stream_nr != i)
2945           continue;
2946
2947         /* check for max duration of a single buffer. I suppose that
2948          * the allocation of index entries could be improved. */
2949         stream = &avi->stream[entry->stream_nr];
2950         if (entry->dur > MAX_DURATION
2951             && stream->strh->type == GST_RIFF_FCC_auds) {
2952           guint32 ideal_size;
2953           gst_avi_index_entry *entries;
2954           guint old_size, num_added;
2955           GList *node2;
2956
2957           /* cut in 1/10th of a second */
2958           ideal_size = stream->strf.auds->av_bps / 10;
2959
2960           /* ensure chunk size is multiple of blockalign */
2961           if (stream->strf.auds->blockalign > 1)
2962             ideal_size -= ideal_size % stream->strf.auds->blockalign;
2963
2964           /* copy index */
2965           old_size = entry->size;
2966           num_added = (entry->size - 1) / ideal_size;
2967           avi->index_size += num_added;
2968           entries = g_malloc (sizeof (gst_avi_index_entry) * num_added);
2969           alloc_list = g_list_prepend (alloc_list, entries);
2970           for (node2 = node->next; node2 != NULL; node2 = node2->next) {
2971             gst_avi_index_entry *entry2 = node2->data;
2972
2973             entry2->index_nr += num_added;
2974             if (entry2->stream_nr == entry->stream_nr)
2975               entry2->frames_before += num_added;
2976           }
2977
2978           /* new sized index chunks */
2979           for (i = 0; i < num_added + 1; i++) {
2980             gst_avi_index_entry *entry2;
2981
2982             if (i == 0) {
2983               entry2 = entry;
2984             } else {
2985               entry2 = &entries[i - 1];
2986               list = g_list_insert_before (list, node->next, entry2);
2987               entry = node->data;
2988               node = node->next;
2989               memcpy (entry2, entry, sizeof (gst_avi_index_entry));
2990             }
2991
2992             if (old_size >= ideal_size) {
2993               entry2->size = ideal_size;
2994               old_size -= ideal_size;
2995             } else {
2996               entry2->size = old_size;
2997             }
2998
2999             entry2->dur = GST_SECOND * entry2->size / stream->strf.auds->av_bps;
3000             if (i != 0) {
3001               entry2->index_nr++;
3002               entry2->ts += entry->dur;
3003               entry2->offset += entry->size;
3004               entry2->bytes_before += entry->size;
3005               entry2->frames_before++;
3006             }
3007           }
3008 #ifndef GST_DISABLE_GST_DEBUG
3009           num_added_total += num_added;
3010 #endif
3011         }
3012       }
3013     }
3014 #ifndef GST_DISABLE_GST_DEBUG
3015     if (num_added_total)
3016       GST_LOG ("added %u new index entries", num_added_total);
3017 #endif
3018
3019     GST_LOG_OBJECT (avi, "I'm now going to reorder the index entries for time");
3020
3021     /* re-order for time */
3022     list = g_list_sort (list, (GCompareFunc) sort);
3023
3024     /* make a continous array out of the list */
3025     avi->index_size = g_list_length (list);
3026     avi->index_entries = g_try_new (gst_avi_index_entry, avi->index_size);
3027     if (!avi->index_entries)
3028       goto out_of_mem;
3029
3030     entry = (gst_avi_index_entry *) (list->data);
3031     delay = entry->ts;
3032
3033     GST_LOG_OBJECT (avi,
3034         "Building index array, nr_entries = %d (time offset = %"
3035         GST_TIME_FORMAT, avi->index_size, GST_TIME_ARGS (delay));
3036
3037     for (i = 0, node = list; node != NULL; node = node->next, i++) {
3038       entry = node->data;
3039       entry->index_nr = i;
3040       entry->ts -= delay;
3041       memcpy (&avi->index_entries[i], entry, sizeof (gst_avi_index_entry));
3042 #ifndef GST_DISABLE_GST_DEBUG
3043       num_per_stream[entry->stream_nr]++;
3044 #endif
3045
3046       GST_LOG_OBJECT (avi, "Sorted index entry %3d for stream %d of size %6u"
3047           " at offset %7" G_GUINT64_FORMAT ", time %" GST_TIME_FORMAT
3048           " dur %" GST_TIME_FORMAT,
3049           avi->index_entries[i].index_nr, entry->stream_nr, entry->size,
3050           entry->offset, GST_TIME_ARGS (entry->ts), GST_TIME_ARGS (entry->dur));
3051     }
3052     if (delay) {
3053       for (i = 0; i < avi->num_streams; i++) {
3054         stream = &avi->stream[i];
3055         stream->idx_duration -= delay;
3056       }
3057     }
3058 #ifndef GST_DISABLE_GST_DEBUG
3059     {
3060       gchar str[GST_AVI_DEMUX_MAX_STREAMS * (1 + 6 + 2)];
3061       gchar *pad_name;
3062
3063       for (i = 0; i < avi->num_streams; i++) {
3064         if (!avi->stream[i].pad)
3065           continue;
3066         pad_name = GST_OBJECT_NAME (avi->stream[i].pad);
3067         sprintf (&str[i * (1 + 6 + 2)], " %6u %c", num_per_stream[i],
3068             pad_name[0]);
3069       }
3070       GST_LOG_OBJECT (avi, "indizies per stream:%20s", str);
3071     }
3072 #endif
3073
3074     GST_LOG_OBJECT (avi, "Freeing original index list");
3075     /* all the node->data in list point to alloc_list chunks */
3076
3077     g_list_free (list);
3078   }
3079   if (alloc_list) {
3080     g_list_foreach (alloc_list, (GFunc) g_free, NULL);
3081     g_list_free (alloc_list);
3082   }
3083 #ifndef GST_DISABLE_GST_DEBUG
3084   for (i = 0; i < avi->num_streams; i++) {
3085     GST_LOG_OBJECT (avi, "Stream %d, %d frames, %8" G_GUINT64_FORMAT " bytes",
3086         i, avi->stream[i].total_frames, avi->stream[i].total_bytes);
3087   }
3088 #endif
3089
3090   GST_LOG_OBJECT (avi, "Index massaging done");
3091
3092   stamp = gst_util_get_timestamp () - stamp;
3093
3094   GST_CAT_DEBUG (GST_CAT_PERFORMANCE, "massaging index %" GST_TIME_FORMAT,
3095       GST_TIME_ARGS (stamp));
3096
3097   return TRUE;
3098
3099   /* ERRORS */
3100 out_of_mem:
3101   {
3102     GST_WARNING_OBJECT (avi, "Out of memory for %" G_GSIZE_FORMAT " bytes",
3103         sizeof (gst_avi_index_entry) * avi->index_size);
3104     return FALSE;
3105   }
3106 }
3107
3108 static void
3109 gst_avi_demux_calculate_durations_from_index (GstAviDemux * avi)
3110 {
3111   gint stream;
3112   GstClockTime total;
3113
3114   total = GST_CLOCK_TIME_NONE;
3115
3116   /* all streams start at a timestamp 0 */
3117   for (stream = 0; stream < avi->num_streams; stream++) {
3118     GstClockTime duration, hduration;
3119     avi_stream_context *streamc = &avi->stream[stream];
3120     gst_riff_strh *strh = streamc->strh;
3121
3122     if (!strh)
3123       continue;
3124
3125     /* get header duration for the stream */
3126     hduration = streamc->hdr_duration;
3127
3128     /* index duration calculated during parsing, invariant under massage */
3129     duration = streamc->idx_duration;
3130
3131     /* now pick a good duration */
3132     if (GST_CLOCK_TIME_IS_VALID (duration)) {
3133       /* index gave valid duration, use that */
3134       GST_INFO ("Stream %d duration according to index: %" GST_TIME_FORMAT,
3135           stream, GST_TIME_ARGS (duration));
3136     } else {
3137       /* fall back to header info to calculate a duration */
3138       duration = hduration;
3139     }
3140     /* set duration for the stream */
3141     streamc->duration = duration;
3142
3143     /* find total duration */
3144     if (total == GST_CLOCK_TIME_NONE || duration > total)
3145       total = duration;
3146   }
3147
3148   if (GST_CLOCK_TIME_IS_VALID (total) && (total > 0)) {
3149     /* now update the duration for those streams where we had none */
3150     for (stream = 0; stream < avi->num_streams; stream++) {
3151       avi_stream_context *streamc = &avi->stream[stream];
3152
3153       if (!GST_CLOCK_TIME_IS_VALID (streamc->duration)
3154           || streamc->duration == 0) {
3155         streamc->duration = total;
3156
3157         GST_INFO ("Stream %d duration according to total: %" GST_TIME_FORMAT,
3158             stream, GST_TIME_ARGS (total));
3159       }
3160     }
3161   }
3162
3163   /* and set the total duration in the segment. */
3164   GST_INFO ("Setting total duration to: %" GST_TIME_FORMAT,
3165       GST_TIME_ARGS (total));
3166
3167   gst_segment_set_duration (&avi->segment, GST_FORMAT_TIME, total);
3168 }
3169
3170 /* returns FALSE if there are no pads to deliver event to,
3171  * otherwise TRUE (whatever the outcome of event sending) */
3172 static gboolean
3173 gst_avi_demux_push_event (GstAviDemux * avi, GstEvent * event)
3174 {
3175   gboolean result = FALSE;
3176   gint i;
3177
3178   GST_DEBUG_OBJECT (avi, "sending %s event to %d streams",
3179       GST_EVENT_TYPE_NAME (event), avi->num_streams);
3180
3181   if (avi->num_streams) {
3182     for (i = 0; i < avi->num_streams; i++) {
3183       avi_stream_context *stream = &avi->stream[i];
3184
3185       if (stream->pad) {
3186         result = TRUE;
3187         gst_pad_push_event (stream->pad, gst_event_ref (event));
3188       }
3189     }
3190   }
3191   gst_event_unref (event);
3192   return result;
3193 }
3194
3195 /*
3196  * Read AVI headers when streaming
3197  */
3198 static GstFlowReturn
3199 gst_avi_demux_stream_header_push (GstAviDemux * avi)
3200 {
3201   GstFlowReturn ret = GST_FLOW_OK;
3202   guint32 tag = 0;
3203   guint32 ltag = 0;
3204   guint32 size = 0;
3205   const guint8 *data;
3206   GstBuffer *buf = NULL, *sub = NULL;
3207   guint offset = 4;
3208   gint64 stop;
3209
3210   GST_DEBUG ("Reading and parsing avi headers: %d", avi->header_state);
3211
3212   switch (avi->header_state) {
3213     case GST_AVI_DEMUX_HEADER_TAG_LIST:
3214       if (gst_avi_demux_peek_chunk (avi, &tag, &size)) {
3215         avi->offset += 8 + ((size + 1) & ~1);
3216         if (tag != GST_RIFF_TAG_LIST)
3217           goto header_no_list;
3218
3219         gst_adapter_flush (avi->adapter, 8);
3220         /* Find the 'hdrl' LIST tag */
3221         GST_DEBUG ("Reading %d bytes", size);
3222         buf = gst_adapter_take_buffer (avi->adapter, size);
3223
3224         if (GST_READ_UINT32_LE (GST_BUFFER_DATA (buf)) != GST_RIFF_LIST_hdrl)
3225           goto header_no_hdrl;
3226
3227         /* mind padding */
3228         if (size & 1)
3229           gst_adapter_flush (avi->adapter, 1);
3230
3231         GST_DEBUG ("'hdrl' LIST tag found. Parsing next chunk");
3232
3233         /* the hdrl starts with a 'avih' header */
3234         if (!gst_riff_parse_chunk (GST_ELEMENT (avi), buf, &offset, &tag, &sub))
3235           goto header_no_avih;
3236
3237         if (tag != GST_RIFF_TAG_avih)
3238           goto header_no_avih;
3239
3240         if (!gst_avi_demux_parse_avih (GST_ELEMENT (avi), sub, &avi->avih))
3241           goto header_wrong_avih;
3242
3243         GST_DEBUG_OBJECT (avi, "AVI header ok, reading elemnts from header");
3244
3245         /* now, read the elements from the header until the end */
3246         while (gst_riff_parse_chunk (GST_ELEMENT (avi), buf, &offset, &tag,
3247                 &sub)) {
3248           /* sub can be NULL on empty tags */
3249           if (!sub)
3250             continue;
3251
3252           switch (tag) {
3253             case GST_RIFF_TAG_LIST:
3254               if (GST_BUFFER_SIZE (sub) < 4)
3255                 goto next;
3256
3257               switch (GST_READ_UINT32_LE (GST_BUFFER_DATA (sub))) {
3258                 case GST_RIFF_LIST_strl:
3259                   if (!(gst_avi_demux_parse_stream (avi, sub))) {
3260                     sub = NULL;
3261                     GST_ELEMENT_WARNING (avi, STREAM, DEMUX, (NULL),
3262                         ("failed to parse stream, ignoring"));
3263                     goto next;
3264                   }
3265                   sub = NULL;
3266                   goto next;
3267                 case GST_RIFF_LIST_odml:
3268                   gst_avi_demux_parse_odml (avi, sub);
3269                   sub = NULL;
3270                   break;
3271                 default:
3272                   GST_WARNING_OBJECT (avi,
3273                       "Unknown list %" GST_FOURCC_FORMAT " in AVI header",
3274                       GST_FOURCC_ARGS (GST_READ_UINT32_LE (GST_BUFFER_DATA
3275                               (sub))));
3276                   /* fall-through */
3277                 case GST_RIFF_TAG_JUNK:
3278                   goto next;
3279               }
3280               break;
3281             default:
3282               GST_WARNING_OBJECT (avi,
3283                   "Unknown off %d tag %" GST_FOURCC_FORMAT " in AVI header",
3284                   offset, GST_FOURCC_ARGS (tag));
3285               /* fall-through */
3286             case GST_RIFF_TAG_JUNK:
3287             next:
3288               /* move to next chunk */
3289               if (sub)
3290                 gst_buffer_unref (sub);
3291               sub = NULL;
3292               break;
3293           }
3294         }
3295         gst_buffer_unref (buf);
3296         GST_DEBUG ("elements parsed");
3297
3298         /* check parsed streams */
3299         if (avi->num_streams == 0) {
3300           goto no_streams;
3301         } else if (avi->num_streams != avi->avih->streams) {
3302           GST_WARNING_OBJECT (avi,
3303               "Stream header mentioned %d streams, but %d available",
3304               avi->avih->streams, avi->num_streams);
3305         }
3306         GST_DEBUG ("Get junk and info next");
3307         avi->header_state = GST_AVI_DEMUX_HEADER_INFO;
3308       } else {
3309         /* Need more data */
3310         return ret;
3311       }
3312       /* fall-though */
3313     case GST_AVI_DEMUX_HEADER_INFO:
3314       GST_DEBUG_OBJECT (avi, "skipping junk between header and data ...");
3315       while (TRUE) {
3316         if (gst_adapter_available (avi->adapter) < 12)
3317           return GST_FLOW_OK;
3318
3319         data = gst_adapter_peek (avi->adapter, 12);
3320         tag = GST_READ_UINT32_LE (data);
3321         size = GST_READ_UINT32_LE (data + 4);
3322         ltag = GST_READ_UINT32_LE (data + 8);
3323
3324         if (tag == GST_RIFF_TAG_LIST) {
3325           switch (ltag) {
3326             case GST_RIFF_LIST_movi:
3327               gst_adapter_flush (avi->adapter, 12);
3328               avi->offset += 12;
3329               goto skipping_done;
3330             case GST_RIFF_LIST_INFO:
3331               GST_DEBUG ("Found INFO chunk");
3332               if (gst_avi_demux_peek_chunk (avi, &tag, &size)) {
3333                 GST_DEBUG ("got size %d", size);
3334                 avi->offset += 12;
3335                 gst_adapter_flush (avi->adapter, 12);
3336                 if (size > 4) {
3337                   buf = gst_adapter_take_buffer (avi->adapter, size - 4);
3338                   /* mind padding */
3339                   if (size & 1)
3340                     gst_adapter_flush (avi->adapter, 1);
3341                   gst_riff_parse_info (GST_ELEMENT (avi), buf,
3342                       &avi->globaltags);
3343                   gst_buffer_unref (buf);
3344
3345                   avi->offset += ((size + 1) & ~1) - 4;
3346                 } else {
3347                   GST_DEBUG ("skipping INFO LIST prefix");
3348                 }
3349               } else {
3350                 /* Need more data */
3351                 return GST_FLOW_OK;
3352               }
3353               break;
3354             default:
3355               if (gst_avi_demux_peek_chunk (avi, &tag, &size)) {
3356                 avi->offset += 8 + ((size + 1) & ~1);
3357                 gst_adapter_flush (avi->adapter, 8 + ((size + 1) & ~1));
3358                 // ??? goto iterate; ???
3359               } else {
3360                 /* Need more data */
3361                 return GST_FLOW_OK;
3362               }
3363               break;
3364           }
3365         } else {
3366           if (gst_avi_demux_peek_chunk (avi, &tag, &size)) {
3367             avi->offset += 8 + ((size + 1) & ~1);
3368             gst_adapter_flush (avi->adapter, 8 + ((size + 1) & ~1));
3369             //goto iterate;
3370           } else {
3371             /* Need more data */
3372             return GST_FLOW_OK;
3373           }
3374         }
3375       }
3376       break;
3377     default:
3378       GST_WARNING ("unhandled header state: %d", avi->header_state);
3379       break;
3380   }
3381 skipping_done:
3382
3383   GST_DEBUG_OBJECT (avi, "skipping done ... (streams=%u, stream[0].indexes=%p)",
3384       avi->num_streams, avi->stream[0].indexes);
3385
3386   GST_DEBUG ("Found movi chunk. Starting to stream data");
3387   avi->state = GST_AVI_DEMUX_MOVI;
3388
3389 #if 0
3390   /*GList *index = NULL, *alloc = NULL; */
3391
3392   /* ######################## this need to be integrated with the state */
3393   /* create or read stream index (for seeking) */
3394   if (avi->stream[0].indexes != NULL) {
3395     gst_avi_demux_read_subindexes_push (avi, &index, &alloc);
3396   }
3397   if (!index) {
3398     if (avi->avih->flags & GST_RIFF_AVIH_HASINDEX) {
3399       gst_avi_demux_stream_index (avi, &index, &alloc);
3400     }
3401     /* some indexes are incomplete, continue streaming from there */
3402     if (!index)
3403       gst_avi_demux_stream_scan (avi, &index, &alloc);
3404   }
3405
3406   /* this is a fatal error */
3407   if (!index)
3408     goto no_index;
3409
3410   if (!gst_avi_demux_massage_index (avi, index, alloc))
3411     goto no_index;
3412
3413   gst_avi_demux_calculate_durations_from_index (avi);
3414   /* ######################## */
3415 #endif
3416
3417   /* create initial NEWSEGMENT event */
3418   if ((stop = avi->segment.stop) == GST_CLOCK_TIME_NONE)
3419     stop = avi->segment.duration;
3420
3421   GST_DEBUG_OBJECT (avi, "segment stop %" G_GINT64_FORMAT, stop);
3422
3423   if (avi->seek_event)
3424     gst_event_unref (avi->seek_event);
3425   avi->seek_event = gst_event_new_new_segment
3426       (FALSE, avi->segment.rate, GST_FORMAT_TIME,
3427       avi->segment.start, stop, avi->segment.start);
3428
3429   /* at this point we know all the streams and we can signal the no more
3430    * pads signal */
3431   GST_DEBUG_OBJECT (avi, "signaling no more pads");
3432   gst_element_no_more_pads (GST_ELEMENT (avi));
3433
3434   return GST_FLOW_OK;
3435
3436   /* ERRORS */
3437 no_streams:
3438   {
3439     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("No streams found"));
3440     return GST_FLOW_ERROR;
3441   }
3442 header_no_list:
3443   {
3444     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3445         ("Invalid AVI header (no LIST at start): %"
3446             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3447     return GST_FLOW_ERROR;
3448   }
3449 header_no_hdrl:
3450   {
3451     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3452         ("Invalid AVI header (no hdrl at start): %"
3453             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3454     gst_buffer_unref (buf);
3455     return GST_FLOW_ERROR;
3456   }
3457 header_no_avih:
3458   {
3459     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3460         ("Invalid AVI header (no avih at start): %"
3461             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3462     if (sub)
3463       gst_buffer_unref (sub);
3464
3465     gst_buffer_unref (buf);
3466     return GST_FLOW_ERROR;
3467   }
3468 header_wrong_avih:
3469   {
3470     gst_buffer_unref (buf);
3471     return GST_FLOW_ERROR;
3472   }
3473 }
3474
3475 /*
3476  * Read full AVI headers.
3477  */
3478 static GstFlowReturn
3479 gst_avi_demux_stream_header_pull (GstAviDemux * avi)
3480 {
3481   GstFlowReturn res;
3482   GstBuffer *buf, *sub = NULL;
3483   guint32 tag;
3484   GList *index = NULL, *alloc = NULL;
3485   guint offset = 4;
3486   gint64 stop;
3487   GstElement *element = GST_ELEMENT_CAST (avi);
3488   GstClockTime stamp;
3489
3490   stamp = gst_util_get_timestamp ();
3491
3492   /* the header consists of a 'hdrl' LIST tag */
3493   res = gst_riff_read_chunk (element, avi->sinkpad, &avi->offset, &tag, &buf);
3494   if (res != GST_FLOW_OK)
3495     goto pull_range_failed;
3496   else if (tag != GST_RIFF_TAG_LIST)
3497     goto no_list;
3498   else if (GST_BUFFER_SIZE (buf) < 4)
3499     goto no_header;
3500
3501   GST_DEBUG_OBJECT (avi, "parsing headers");
3502
3503   /* Find the 'hdrl' LIST tag */
3504   while (GST_READ_UINT32_LE (GST_BUFFER_DATA (buf)) != GST_RIFF_LIST_hdrl) {
3505     GST_LOG_OBJECT (avi, "buffer contains %" GST_FOURCC_FORMAT,
3506         GST_FOURCC_ARGS (GST_READ_UINT32_LE (GST_BUFFER_DATA (buf))));
3507
3508     /* Eat up */
3509     gst_buffer_unref (buf);
3510
3511     /* read new chunk */
3512     res = gst_riff_read_chunk (element, avi->sinkpad, &avi->offset, &tag, &buf);
3513     if (res != GST_FLOW_OK)
3514       goto pull_range_failed;
3515     else if (tag != GST_RIFF_TAG_LIST)
3516       goto no_list;
3517     else if (GST_BUFFER_SIZE (buf) < 4)
3518       goto no_header;
3519   }
3520
3521   GST_DEBUG_OBJECT (avi, "hdrl LIST tag found");
3522
3523   /* the hdrl starts with a 'avih' header */
3524   if (!gst_riff_parse_chunk (element, buf, &offset, &tag, &sub))
3525     goto no_avih;
3526   else if (tag != GST_RIFF_TAG_avih)
3527     goto no_avih;
3528   else if (!gst_avi_demux_parse_avih (element, sub, &avi->avih))
3529     goto invalid_avih;
3530
3531   GST_DEBUG_OBJECT (avi, "AVI header ok, reading elements from header");
3532
3533   /* now, read the elements from the header until the end */
3534   while (gst_riff_parse_chunk (element, buf, &offset, &tag, &sub)) {
3535     /* sub can be NULL on empty tags */
3536     if (!sub)
3537       continue;
3538
3539     switch (tag) {
3540       case GST_RIFF_TAG_LIST:
3541       {
3542         guint8 *data;
3543         guint32 fourcc;
3544
3545         if (GST_BUFFER_SIZE (sub) < 4)
3546           goto next;
3547
3548         data = GST_BUFFER_DATA (sub);
3549         fourcc = GST_READ_UINT32_LE (data);
3550
3551         switch (fourcc) {
3552           case GST_RIFF_LIST_strl:
3553             if (!(gst_avi_demux_parse_stream (avi, sub))) {
3554               GST_ELEMENT_WARNING (avi, STREAM, DEMUX, (NULL),
3555                   ("failed to parse stream, ignoring"));
3556               sub = NULL;
3557             }
3558             sub = NULL;
3559             goto next;
3560           case GST_RIFF_LIST_odml:
3561             gst_avi_demux_parse_odml (avi, sub);
3562             sub = NULL;
3563             break;
3564           default:
3565             GST_WARNING_OBJECT (avi,
3566                 "Unknown list %" GST_FOURCC_FORMAT " in AVI header",
3567                 GST_FOURCC_ARGS (fourcc));
3568             GST_MEMDUMP_OBJECT (avi, "Unknown list", GST_BUFFER_DATA (sub),
3569                 GST_BUFFER_SIZE (sub));
3570             /* fall-through */
3571           case GST_RIFF_TAG_JUNK:
3572             goto next;
3573         }
3574         break;
3575       }
3576       default:
3577         GST_WARNING_OBJECT (avi,
3578             "Unknown tag %" GST_FOURCC_FORMAT " in AVI header at off %d",
3579             GST_FOURCC_ARGS (tag), offset);
3580         GST_MEMDUMP_OBJECT (avi, "Unknown tag", GST_BUFFER_DATA (sub),
3581             GST_BUFFER_SIZE (sub));
3582         /* fall-through */
3583       case GST_RIFF_TAG_JUNK:
3584       next:
3585         if (sub)
3586           gst_buffer_unref (sub);
3587         sub = NULL;
3588         break;
3589     }
3590   }
3591   gst_buffer_unref (buf);
3592   GST_DEBUG ("elements parsed");
3593
3594   /* check parsed streams */
3595   if (avi->num_streams == 0)
3596     goto no_streams;
3597   else if (avi->num_streams != avi->avih->streams) {
3598     GST_WARNING_OBJECT (avi,
3599         "Stream header mentioned %d streams, but %d available",
3600         avi->avih->streams, avi->num_streams);
3601   }
3602
3603   GST_DEBUG_OBJECT (avi, "skipping junk between header and data, offset=%"
3604       G_GUINT64_FORMAT, avi->offset);
3605
3606   /* Now, find the data (i.e. skip all junk between header and data) */
3607   do {
3608     guint size;
3609     guint32 tag, ltag;
3610
3611     res = gst_pad_pull_range (avi->sinkpad, avi->offset, 12, &buf);
3612     if (res != GST_FLOW_OK) {
3613       GST_DEBUG_OBJECT (avi, "pull_range failure while looking for tags");
3614       goto pull_range_failed;
3615     } else if (GST_BUFFER_SIZE (buf) < 12) {
3616       GST_DEBUG_OBJECT (avi, "got %d bytes which is less than 12 bytes",
3617           GST_BUFFER_SIZE (buf));
3618       gst_buffer_unref (buf);
3619       return GST_FLOW_ERROR;
3620     }
3621
3622     tag = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf));
3623     size = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf) + 4);
3624     ltag = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf) + 8);
3625
3626     GST_DEBUG ("tag %" GST_FOURCC_FORMAT ", size %u",
3627         GST_FOURCC_ARGS (tag), size);
3628     GST_MEMDUMP ("Tag content", GST_BUFFER_DATA (buf), GST_BUFFER_SIZE (buf));
3629     gst_buffer_unref (buf);
3630
3631     switch (tag) {
3632       case GST_RIFF_TAG_LIST:{
3633         switch (ltag) {
3634           case GST_RIFF_LIST_movi:
3635             GST_DEBUG_OBJECT (avi,
3636                 "Reached the 'movi' tag, we're done with skipping");
3637             goto skipping_done;
3638           case GST_RIFF_LIST_INFO:
3639             res =
3640                 gst_riff_read_chunk (element, avi->sinkpad, &avi->offset, &tag,
3641                 &buf);
3642             if (res != GST_FLOW_OK) {
3643               GST_DEBUG_OBJECT (avi, "couldn't read INFO chunk");
3644               goto pull_range_failed;
3645             }
3646             GST_DEBUG ("got size %u", GST_BUFFER_SIZE (buf));
3647             if (size < 4) {
3648               GST_DEBUG ("skipping INFO LIST prefix");
3649               avi->offset += (4 - GST_ROUND_UP_2 (size));
3650               gst_buffer_unref (buf);
3651               continue;
3652             }
3653
3654             sub = gst_buffer_create_sub (buf, 4, GST_BUFFER_SIZE (buf) - 4);
3655             gst_riff_parse_info (element, sub, &avi->globaltags);
3656             if (sub) {
3657               gst_buffer_unref (sub);
3658               sub = NULL;
3659             }
3660             gst_buffer_unref (buf);
3661             /* gst_riff_read_chunk() has already advanced avi->offset */
3662             break;
3663           default:
3664             GST_WARNING_OBJECT (avi,
3665                 "Skipping unknown list tag %" GST_FOURCC_FORMAT,
3666                 GST_FOURCC_ARGS (ltag));
3667             avi->offset += 8 + ((size + 1) & ~1);
3668             break;
3669         }
3670       }
3671         break;
3672       default:
3673         GST_WARNING_OBJECT (avi, "Skipping unknown tag %" GST_FOURCC_FORMAT,
3674             GST_FOURCC_ARGS (tag));
3675         /* Fall-through */
3676       case GST_MAKE_FOURCC ('J', 'U', 'N', 'Q'):
3677       case GST_MAKE_FOURCC ('J', 'U', 'N', 'K'):
3678         avi->offset += 8 + ((size + 1) & ~1);
3679         break;
3680     }
3681   } while (1);
3682 skipping_done:
3683
3684   GST_DEBUG_OBJECT (avi, "skipping done ... (streams=%u, stream[0].indexes=%p)",
3685       avi->num_streams, avi->stream[0].indexes);
3686
3687   /* create or read stream index (for seeking) */
3688   if (avi->stream[0].indexes != NULL) {
3689     /* we read a super index already (gst_avi_demux_parse_superindex() ) */
3690     gst_avi_demux_read_subindexes_pull (avi, &index, &alloc);
3691   }
3692   if (!index) {
3693     if (avi->avih->flags & GST_RIFF_AVIH_HASINDEX) {
3694       gst_avi_demux_stream_index (avi, &index, &alloc);
3695     }
3696     /* some indexes are incomplete, continue streaming from there */
3697     if (!index)
3698       gst_avi_demux_stream_scan (avi, &index, &alloc);
3699   }
3700
3701   /* this is a fatal error */
3702   if (!index)
3703     goto no_index;
3704
3705   if (!gst_avi_demux_massage_index (avi, index, alloc))
3706     goto no_index;
3707
3708   gst_avi_demux_calculate_durations_from_index (avi);
3709
3710   /* create initial NEWSEGMENT event */
3711   if ((stop = avi->segment.stop) == GST_CLOCK_TIME_NONE)
3712     stop = avi->segment.duration;
3713
3714   GST_DEBUG_OBJECT (avi, "segment stop %" G_GINT64_FORMAT, stop);
3715
3716   if (avi->seek_event)
3717     gst_event_unref (avi->seek_event);
3718   avi->seek_event = gst_event_new_new_segment
3719       (FALSE, avi->segment.rate, GST_FORMAT_TIME,
3720       avi->segment.start, stop, avi->segment.start);
3721
3722   stamp = gst_util_get_timestamp () - stamp;
3723   GST_CAT_DEBUG (GST_CAT_PERFORMANCE, "pulling header %" GST_TIME_FORMAT,
3724       GST_TIME_ARGS (stamp));
3725
3726   /* at this point we know all the streams and we can signal the no more
3727    * pads signal */
3728   GST_DEBUG_OBJECT (avi, "signaling no more pads");
3729   gst_element_no_more_pads (GST_ELEMENT_CAST (avi));
3730
3731   return GST_FLOW_OK;
3732
3733   /* ERRORS */
3734 no_list:
3735   {
3736     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3737         ("Invalid AVI header (no LIST at start): %"
3738             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3739     gst_buffer_unref (buf);
3740     return GST_FLOW_ERROR;
3741   }
3742 no_header:
3743   {
3744     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3745         ("Invalid AVI header (no hdrl at start): %"
3746             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3747     gst_buffer_unref (buf);
3748     return GST_FLOW_ERROR;
3749   }
3750 no_avih:
3751   {
3752     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3753         ("Invalid AVI header (no avih at start): %"
3754             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3755     if (sub)
3756       gst_buffer_unref (sub);
3757     gst_buffer_unref (buf);
3758     return GST_FLOW_ERROR;
3759   }
3760 invalid_avih:
3761   {
3762     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3763         ("Invalid AVI header (cannot parse avih at start)"));
3764     gst_buffer_unref (buf);
3765     return GST_FLOW_ERROR;
3766   }
3767 no_streams:
3768   {
3769     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("No streams found"));
3770     return GST_FLOW_ERROR;
3771   }
3772 no_index:
3773   {
3774     GST_WARNING ("file without or too big index");
3775     g_list_free (index);
3776     g_list_foreach (alloc, (GFunc) g_free, NULL);
3777     g_list_free (alloc);
3778
3779     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3780         ("Could not get/create index"));
3781     return GST_FLOW_ERROR;
3782   }
3783 pull_range_failed:
3784   {
3785     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3786         ("pull_range flow reading header: %s", gst_flow_get_name (res)));
3787     return GST_FLOW_ERROR;
3788   }
3789 }
3790
3791 /*
3792  * Do the actual seeking.
3793  */
3794 static gboolean
3795 gst_avi_demux_do_seek (GstAviDemux * avi, GstSegment * segment)
3796 {
3797   GstClockTime seek_time;
3798   gboolean keyframe;
3799   gst_avi_index_entry *entry, *kentry;
3800   gint old_entry;
3801
3802   seek_time = segment->last_stop;
3803   keyframe = !!(segment->flags & GST_SEEK_FLAG_KEY_UNIT);
3804
3805   /* FIXME: if we seek in an openDML file, we will have multiple
3806    * primary levels. Seeking in between those will cause havoc. */
3807
3808   /* save old position so we can see if we must mark a discont. */
3809   old_entry = avi->current_entry;
3810
3811   /* get the entry for the requested position, which is always in last_stop.
3812    * we search the index entry for stream 0, since all entries are sorted by
3813    * time and stream we automagically are positioned for the other streams as
3814    * well. FIXME, this code assumes the main stream with keyframes is stream 0,
3815    * which is mostly correct... */
3816   if (!(entry = gst_avi_demux_index_entry_for_time (avi, 0, seek_time)))
3817     goto no_entry;
3818
3819   GST_DEBUG_OBJECT (avi,
3820       "Got requested entry %d [stream:%d / ts:%" GST_TIME_FORMAT
3821       " / duration:%" GST_TIME_FORMAT "]", entry->index_nr,
3822       entry->stream_nr, GST_TIME_ARGS (entry->ts), GST_TIME_ARGS (entry->dur));
3823
3824   /* check if we are already on a keyframe */
3825   if (!(entry->flags & GST_AVI_INDEX_ENTRY_FLAG_KEYFRAME)) {
3826     /* now go to the previous keyframe, this is where we should start
3827      * decoding from. */
3828     if (!(kentry = gst_avi_demux_index_prev (avi, 0, entry->index_nr,
3829                 GST_AVI_INDEX_ENTRY_FLAG_KEYFRAME))) {
3830       goto no_entry;
3831     }
3832   } else {
3833     /* we were on a keyframe */
3834     kentry = entry;
3835   }
3836
3837   GST_DEBUG_OBJECT (avi,
3838       "Got keyframe entry %d [stream:%d / ts:%" GST_TIME_FORMAT
3839       " / duration:%" GST_TIME_FORMAT "]", kentry->index_nr,
3840       entry->stream_nr, GST_TIME_ARGS (kentry->ts),
3841       GST_TIME_ARGS (kentry->dur));
3842
3843   /* we must start decoding at the keyframe */
3844   avi->current_entry = kentry->index_nr;
3845
3846   if (segment->rate < 0.0) {
3847     gst_avi_index_entry *next_keyframe;
3848
3849     /* Because we don't know the frame order we need to push from the prev keyframe
3850      * to the next keyframe. If there is a smart decoder downstream he will notice
3851      * that there are too many encoded frames send and return UNEXPECTED when there
3852      * are enough decoded frames to fill the segment.
3853      */
3854     next_keyframe =
3855         gst_avi_demux_index_next (avi, 0, kentry->index_nr,
3856         GST_AVI_INDEX_ENTRY_FLAG_KEYFRAME);
3857     if (!next_keyframe)
3858       next_keyframe = gst_avi_demux_index_last (avi, 0);
3859
3860     avi->reverse_start_index = kentry->index_nr;
3861     avi->reverse_stop_index = next_keyframe->index_nr;
3862
3863     GST_DEBUG_OBJECT (avi, "reverse seek: start idx (%d) and stop idx (%d)",
3864         avi->reverse_start_index, avi->reverse_stop_index);
3865   }
3866
3867   if (keyframe) {
3868     /* when seeking to a keyframe, we update the result seek time
3869      * to the time of the keyframe. */
3870     seek_time = avi->index_entries[avi->current_entry].ts;
3871   }
3872
3873 next:
3874   /* if we changed position, mark a DISCONT on all streams */
3875   if (avi->current_entry != old_entry) {
3876     gint i;
3877
3878     for (i = 0; i < avi->num_streams; i++) {
3879       avi->stream[i].discont = TRUE;
3880     }
3881   }
3882
3883   GST_DEBUG_OBJECT (avi, "seek: %" GST_TIME_FORMAT
3884       " keyframe seeking:%d", GST_TIME_ARGS (seek_time), keyframe);
3885
3886   /* the seek time is also the last_stop and stream time */
3887   segment->last_stop = seek_time;
3888   segment->time = seek_time;
3889
3890   return TRUE;
3891
3892 no_entry:
3893   {
3894     /* we could not find an entry for the given time */
3895     GST_WARNING_OBJECT (avi,
3896         "Couldn't find AviIndexEntry for time:%" GST_TIME_FORMAT,
3897         GST_TIME_ARGS (seek_time));
3898     if (avi->current_entry >= avi->index_size && avi->index_size > 0)
3899       avi->current_entry = avi->index_size - 1;
3900
3901     goto next;
3902   }
3903 }
3904
3905 /*
3906  * Handle seek event.
3907  */
3908 static gboolean
3909 gst_avi_demux_handle_seek (GstAviDemux * avi, GstPad * pad, GstEvent * event)
3910 {
3911   gdouble rate;
3912   GstFormat format;
3913   GstSeekFlags flags;
3914   GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
3915   gint64 cur, stop;
3916   gboolean flush;
3917   gboolean update;
3918   GstSegment seeksegment = { 0, };
3919
3920   if (event) {
3921     GST_DEBUG_OBJECT (avi, "doing seek with event");
3922
3923     gst_event_parse_seek (event, &rate, &format, &flags,
3924         &cur_type, &cur, &stop_type, &stop);
3925
3926     /* we have to have a format as the segment format. Try to convert
3927      * if not. */
3928     if (format != GST_FORMAT_TIME) {
3929       GstFormat fmt = GST_FORMAT_TIME;
3930       gboolean res = TRUE;
3931
3932       if (cur_type != GST_SEEK_TYPE_NONE)
3933         res = gst_pad_query_convert (pad, format, cur, &fmt, &cur);
3934       if (res && stop_type != GST_SEEK_TYPE_NONE)
3935         res = gst_pad_query_convert (pad, format, stop, &fmt, &stop);
3936       if (!res)
3937         goto no_format;
3938
3939       format = fmt;
3940     }
3941     GST_DEBUG_OBJECT (avi,
3942         "seek requested: rate %g cur %" GST_TIME_FORMAT " stop %"
3943         GST_TIME_FORMAT, rate, GST_TIME_ARGS (cur), GST_TIME_ARGS (stop));
3944     /* FIXME: can we do anything with rate!=1.0 */
3945   } else {
3946     GST_DEBUG_OBJECT (avi, "doing seek without event");
3947     flags = 0;
3948     rate = 1.0;
3949   }
3950
3951   /* save flush flag */
3952   flush = flags & GST_SEEK_FLAG_FLUSH;
3953
3954   if (flush) {
3955     GstEvent *event = gst_event_new_flush_start ();
3956
3957     /* for a flushing seek, we send a flush_start on all pads. This will
3958      * eventually stop streaming with a WRONG_STATE. We can thus eventually
3959      * take the STREAM_LOCK. */
3960     GST_DEBUG_OBJECT (avi, "sending flush start");
3961     gst_avi_demux_push_event (avi, gst_event_ref (event));
3962     gst_pad_push_event (avi->sinkpad, event);
3963   } else {
3964     /* a non-flushing seek, we PAUSE the task so that we can take the
3965      * STREAM_LOCK */
3966     GST_DEBUG_OBJECT (avi, "non flushing seek, pausing task");
3967     gst_pad_pause_task (avi->sinkpad);
3968   }
3969
3970   /* wait for streaming to stop */
3971   GST_DEBUG_OBJECT (avi, "wait for streaming to stop");
3972   GST_PAD_STREAM_LOCK (avi->sinkpad);
3973
3974   /* copy segment, we need this because we still need the old
3975    * segment when we close the current segment. */
3976   memcpy (&seeksegment, &avi->segment, sizeof (GstSegment));
3977
3978   if (event) {
3979     GST_DEBUG_OBJECT (avi, "configuring seek");
3980     gst_segment_set_seek (&seeksegment, rate, format, flags,
3981         cur_type, cur, stop_type, stop, &update);
3982   }
3983
3984   /* do the seek, seeksegment.last_stop contains the new position, this
3985    * actually never fails. */
3986   gst_avi_demux_do_seek (avi, &seeksegment);
3987
3988   if (flush) {
3989     gint i;
3990
3991     GST_DEBUG_OBJECT (avi, "sending flush stop");
3992     gst_avi_demux_push_event (avi, gst_event_new_flush_stop ());
3993     gst_pad_push_event (avi->sinkpad, gst_event_new_flush_stop ());
3994     /* reset the last flow and mark discont, FLUSH is always DISCONT */
3995     for (i = 0; i < avi->num_streams; i++) {
3996       avi->stream[i].last_flow = GST_FLOW_OK;
3997       avi->stream[i].discont = TRUE;
3998     }
3999   } else if (avi->segment_running) {
4000     GstEvent *seg;
4001
4002     /* we are running the current segment and doing a non-flushing seek,
4003      * close the segment first based on the last_stop. */
4004     GST_DEBUG_OBJECT (avi, "closing running segment %" G_GINT64_FORMAT
4005         " to %" G_GINT64_FORMAT, avi->segment.start, avi->segment.last_stop);
4006     seg = gst_event_new_new_segment (TRUE,
4007         avi->segment.rate, avi->segment.format,
4008         avi->segment.start, avi->segment.last_stop, avi->segment.time);
4009     gst_avi_demux_push_event (avi, seg);
4010   }
4011
4012   /* now update the real segment info */
4013   memcpy (&avi->segment, &seeksegment, sizeof (GstSegment));
4014
4015   /* post the SEGMENT_START message when we do segmented playback */
4016   if (avi->segment.flags & GST_SEEK_FLAG_SEGMENT) {
4017     gst_element_post_message (GST_ELEMENT (avi),
4018         gst_message_new_segment_start (GST_OBJECT (avi),
4019             avi->segment.format, avi->segment.last_stop));
4020   }
4021
4022   /* prepare for streaming again */
4023   if ((stop = avi->segment.stop) == GST_CLOCK_TIME_NONE)
4024     stop = avi->segment.duration;
4025
4026   /* queue the segment event for the streaming thread. */
4027   if (avi->seek_event)
4028     gst_event_unref (avi->seek_event);
4029   if (avi->segment.rate > 0.0) {
4030     avi->seek_event = gst_event_new_new_segment (FALSE,
4031         avi->segment.rate, avi->segment.format,
4032         avi->segment.last_stop, stop, avi->segment.time);
4033   } else {
4034     avi->seek_event = gst_event_new_new_segment (FALSE,
4035         avi->segment.rate, avi->segment.format,
4036         avi->segment.start, avi->segment.last_stop, avi->segment.start);
4037   }
4038
4039   if (!avi->streaming) {
4040     avi->segment_running = TRUE;
4041     gst_pad_start_task (avi->sinkpad, (GstTaskFunction) gst_avi_demux_loop,
4042         avi->sinkpad);
4043   }
4044   GST_PAD_STREAM_UNLOCK (avi->sinkpad);
4045
4046   return TRUE;
4047
4048   /* ERRORS */
4049 no_format:
4050   {
4051     GST_DEBUG_OBJECT (avi, "unsupported format given, seek aborted.");
4052     return FALSE;
4053   }
4054 }
4055
4056 /*
4057  * Helper for gst_avi_demux_invert()
4058  */
4059 static inline void
4060 swap_line (guint8 * d1, guint8 * d2, guint8 * tmp, gint bytes)
4061 {
4062   memcpy (tmp, d1, bytes);
4063   memcpy (d1, d2, bytes);
4064   memcpy (d2, tmp, bytes);
4065 }
4066
4067
4068 #define gst_avi_demux_is_uncompressed(fourcc)           \
4069   (fourcc == GST_RIFF_DIB ||                            \
4070    fourcc == GST_RIFF_rgb ||                            \
4071    fourcc == GST_RIFF_RGB || fourcc == GST_RIFF_RAW)
4072
4073 /*
4074  * Invert DIB buffers... Takes existing buffer and
4075  * returns either the buffer or a new one (with old
4076  * one dereferenced).
4077  * FIXME: can't we preallocate tmp? and remember stride, bpp?
4078  */
4079 static GstBuffer *
4080 gst_avi_demux_invert (avi_stream_context * stream, GstBuffer * buf)
4081 {
4082   GstStructure *s;
4083   gint y, w, h;
4084   gint bpp, stride;
4085   guint8 *tmp = NULL;
4086
4087   if (stream->strh->type != GST_RIFF_FCC_vids)
4088     return buf;
4089
4090   if (!gst_avi_demux_is_uncompressed (stream->strh->fcc_handler)) {
4091     return buf;                 /* Ignore non DIB buffers */
4092   }
4093
4094   s = gst_caps_get_structure (GST_PAD_CAPS (stream->pad), 0);
4095   if (!gst_structure_get_int (s, "bpp", &bpp)) {
4096     GST_WARNING ("Failed to retrieve depth from caps");
4097     return buf;
4098   }
4099
4100   if (stream->strf.vids == NULL) {
4101     GST_WARNING ("Failed to retrieve vids for stream");
4102     return buf;
4103   }
4104
4105   h = stream->strf.vids->height;
4106   w = stream->strf.vids->width;
4107   stride = w * (bpp / 8);
4108
4109   buf = gst_buffer_make_writable (buf);
4110   if (GST_BUFFER_SIZE (buf) < (stride * h)) {
4111     GST_WARNING ("Buffer is smaller than reported Width x Height x Depth");
4112     return buf;
4113   }
4114
4115   tmp = g_malloc (stride);
4116
4117   for (y = 0; y < h / 2; y++) {
4118     swap_line (GST_BUFFER_DATA (buf) + stride * y,
4119         GST_BUFFER_DATA (buf) + stride * (h - 1 - y), tmp, stride);
4120   }
4121
4122   g_free (tmp);
4123
4124   return buf;
4125 }
4126
4127 /*
4128  * Returns the aggregated GstFlowReturn.
4129  */
4130 static GstFlowReturn
4131 gst_avi_demux_combine_flows (GstAviDemux * avi, avi_stream_context * stream,
4132     GstFlowReturn ret)
4133 {
4134   guint i;
4135
4136   /* store the value */
4137   stream->last_flow = ret;
4138
4139   /* any other error that is not-linked can be returned right away */
4140   if (G_UNLIKELY (ret != GST_FLOW_NOT_LINKED))
4141     goto done;
4142
4143   /* only return NOT_LINKED if all other pads returned NOT_LINKED */
4144   for (i = 0; i < avi->num_streams; i++) {
4145     avi_stream_context *ostream = &avi->stream[i];
4146
4147     ret = ostream->last_flow;
4148     /* some other return value (must be SUCCESS but we can return
4149      * other values as well) */
4150     if (G_UNLIKELY (ret != GST_FLOW_NOT_LINKED))
4151       goto done;
4152   }
4153   /* if we get here, all other pads were unlinked and we return
4154    * NOT_LINKED then */
4155 done:
4156   GST_LOG_OBJECT (avi, "combined return %s", gst_flow_get_name (ret));
4157   return ret;
4158 }
4159
4160 /*
4161  * prepare the avi element for a reverse jump to a prev keyframe
4162  * this function will return the start entry. if the function returns
4163  * NULL there was no prev keyframe.
4164  */
4165 static gst_avi_index_entry *
4166 gst_avi_demux_step_reverse (GstAviDemux * avi)
4167 {
4168   gst_avi_index_entry *entry;
4169   gint i;
4170
4171   avi->reverse_stop_index = avi->reverse_start_index;
4172   entry =
4173       gst_avi_demux_index_prev (avi, 0, avi->reverse_stop_index,
4174       GST_AVI_INDEX_ENTRY_FLAG_KEYFRAME);
4175   if (!entry) {
4176     GST_DEBUG_OBJECT (avi, "no valid index entry found index %d",
4177         avi->reverse_stop_index);
4178     return NULL;
4179   }
4180   avi->current_entry = avi->reverse_start_index = entry->index_nr;
4181   GST_DEBUG_OBJECT (avi,
4182       "reverse playback jump: start idx (%d) and stop idx (%d)",
4183       avi->reverse_start_index, avi->reverse_stop_index);
4184   gst_segment_set_last_stop (&avi->segment, GST_FORMAT_TIME, entry->ts);
4185   for (i = 0; i < avi->num_streams; i++) {
4186     avi->stream[i].last_flow = GST_FLOW_OK;
4187     avi->stream[i].discont = TRUE;
4188   }
4189   return entry;
4190 }
4191
4192 /*
4193  * Read data from one index entry
4194  */
4195 static GstFlowReturn
4196 gst_avi_demux_process_next_entry (GstAviDemux * avi)
4197 {
4198   GstFlowReturn res = GST_FLOW_OK;
4199   gboolean processed = FALSE;
4200   avi_stream_context *stream;
4201   gst_avi_index_entry *entry;
4202   GstBuffer *buf;
4203
4204   do {
4205     /* see if we are at the end */
4206     if ((avi->segment.rate > 0 && avi->current_entry >= avi->index_size))
4207       goto eos;
4208
4209     /* get next entry, this will work as we checked for the index size above */
4210     entry = &avi->index_entries[avi->current_entry++];
4211
4212     /* check for reverse playback */
4213     if (avi->segment.rate < 0 && avi->current_entry > avi->reverse_stop_index) {
4214       GST_LOG_OBJECT (avi, "stop_index %d reached", avi->reverse_stop_index);
4215
4216       /* check if we have pushed enough data for this segment */
4217       if (avi->reverse_start_index == 0)
4218         goto eos_reverse_zero;
4219       if (avi->index_entries[avi->reverse_start_index].ts < avi->segment.start)
4220         goto eos_reverse_segment;
4221
4222       if (!(entry = gst_avi_demux_step_reverse (avi)))
4223         goto eos;
4224
4225       avi->current_entry++;
4226     }
4227
4228     /* see if we have a valid stream, ignore if not
4229      * FIXME: can't we check this when building the index?
4230      *   we check it in _parse_index(), _stream_scan()
4231      */
4232     if (entry->stream_nr >= avi->num_streams) {
4233       GST_WARNING_OBJECT (avi,
4234           "Entry %d has non-existing stream nr %d",
4235           avi->current_entry - 1, entry->stream_nr);
4236       continue;
4237     }
4238
4239     /* get stream now */
4240     stream = &avi->stream[entry->stream_nr];
4241
4242     if (avi->segment.rate > 0.0) {
4243       /* only check this for fowards playback for now */
4244       if ((entry->flags & GST_AVI_INDEX_ENTRY_FLAG_KEYFRAME)
4245           && GST_CLOCK_TIME_IS_VALID (entry->ts)
4246           && GST_CLOCK_TIME_IS_VALID (avi->segment.stop)
4247           && (entry->ts > avi->segment.stop)) {
4248         goto eos_stop;
4249       }
4250     }
4251
4252     /* skip empty entries */
4253     if (entry->size == 0 || !stream->pad) {
4254       GST_DEBUG_OBJECT (avi, "Skipping entry %d (%d, %p)",
4255           avi->current_entry - 1, entry->size, stream->pad);
4256       goto next;
4257     }
4258
4259     GST_LOG ("reading buffer (size=%d) from stream %d at current pos %"
4260         G_GUINT64_FORMAT " (%llx)", entry->size, entry->stream_nr,
4261         avi->index_offset + entry->offset, avi->index_offset + entry->offset);
4262
4263     /* pull in the data */
4264     res = gst_pad_pull_range (avi->sinkpad, entry->offset +
4265         avi->index_offset, entry->size, &buf);
4266     if (res != GST_FLOW_OK)
4267       goto pull_failed;
4268
4269     /* check for short buffers, this is EOS as well */
4270     if (GST_BUFFER_SIZE (buf) < entry->size)
4271       goto short_buffer;
4272
4273     /* invert the picture if needed */
4274     buf = gst_avi_demux_invert (stream, buf);
4275
4276     /* mark non-keyframes */
4277     if (!(entry->flags & GST_AVI_INDEX_ENTRY_FLAG_KEYFRAME))
4278       GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
4279
4280     GST_BUFFER_TIMESTAMP (buf) = entry->ts;
4281     GST_BUFFER_DURATION (buf) = entry->dur;
4282     if (stream->strh->type == GST_RIFF_FCC_vids) {
4283       if (stream->current_frame >= 0)
4284         GST_BUFFER_OFFSET (buf) = stream->current_frame;
4285       else {
4286         gint64 framenum;
4287         GstFormat fmt = GST_FORMAT_DEFAULT;
4288
4289         if (gst_pad_query_convert (stream->pad, GST_FORMAT_TIME, entry->ts,
4290                 &fmt, &framenum))
4291           GST_BUFFER_OFFSET (buf) = framenum;
4292         else
4293           GST_BUFFER_OFFSET (buf) = GST_BUFFER_OFFSET_NONE;
4294       }
4295     } else
4296       GST_BUFFER_OFFSET (buf) = GST_BUFFER_OFFSET_NONE;
4297     GST_BUFFER_OFFSET_END (buf) = GST_BUFFER_OFFSET_NONE;
4298     gst_buffer_set_caps (buf, GST_PAD_CAPS (stream->pad));
4299
4300     GST_DEBUG_OBJECT (avi, "Pushing buffer of size %d, offset %"
4301         G_GUINT64_FORMAT " and time %"
4302         GST_TIME_FORMAT " on pad %s",
4303         GST_BUFFER_SIZE (buf), GST_BUFFER_OFFSET (buf),
4304         GST_TIME_ARGS (entry->ts), GST_PAD_NAME (stream->pad));
4305
4306     /* update current position in the segment */
4307     gst_segment_set_last_stop (&avi->segment, GST_FORMAT_TIME, entry->ts);
4308
4309     /* mark discont when pending */
4310     if (stream->discont) {
4311       GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
4312       stream->discont = FALSE;
4313     }
4314
4315     res = gst_pad_push (stream->pad, buf);
4316
4317     /* mark as processed, we increment the frame and byte counters then
4318      * leave the while loop and return the GstFlowReturn */
4319     processed = TRUE;
4320     GST_DEBUG_OBJECT (avi, "Processed buffer %d: %s", entry->index_nr,
4321         gst_flow_get_name (res));
4322
4323     if (avi->segment.rate < 0
4324         && entry->ts > avi->segment.stop && res == GST_FLOW_UNEXPECTED) {
4325       /* In reverse playback we can get a GST_FLOW_UNEXPECTED when
4326        * we are at the end of the segment, so we just need to jump
4327        * back to the previous section.
4328        */
4329       GST_DEBUG_OBJECT (avi, "downstream has reached end of segment");
4330
4331       if (!(entry = gst_avi_demux_step_reverse (avi)))
4332         goto eos;
4333
4334       res = GST_FLOW_OK;
4335
4336       stream->current_frame = entry->frames_before;
4337       stream->current_byte = entry->bytes_before;
4338
4339       continue;
4340     }
4341
4342     /* combine flows */
4343     res = gst_avi_demux_combine_flows (avi, stream, res);
4344
4345   next:
4346     stream->current_frame = entry->frames_before + 1;
4347     stream->current_byte = entry->bytes_before + entry->size;
4348   } while (!processed);
4349
4350 beach:
4351   GST_DEBUG_OBJECT (avi, "returning %s", gst_flow_get_name (res));
4352
4353   return res;
4354
4355   /* ERRORS */
4356 eos:
4357   {
4358     GST_LOG_OBJECT (avi, "Handled last index entry, setting EOS (%d > %d)",
4359         avi->current_entry, avi->index_size);
4360     /* we mark the first stream as EOS */
4361     res = GST_FLOW_UNEXPECTED;
4362     goto beach;
4363   }
4364 eos_stop:
4365   {
4366     GST_LOG_OBJECT (avi, "Found keyframe after segment,"
4367         " setting EOS (%" GST_TIME_FORMAT " > %" GST_TIME_FORMAT ")",
4368         GST_TIME_ARGS (entry->ts), GST_TIME_ARGS (avi->segment.stop));
4369     res = GST_FLOW_UNEXPECTED;
4370     goto beach;
4371   }
4372 eos_reverse_zero:
4373   {
4374     GST_DEBUG_OBJECT (avi, "start_index was 0, setting EOS");
4375     res = GST_FLOW_UNEXPECTED;
4376     goto beach;
4377   }
4378 eos_reverse_segment:
4379   {
4380     GST_DEBUG_OBJECT (avi, "full segment pushed, setting EOS");
4381     res = GST_FLOW_UNEXPECTED;
4382     goto beach;
4383   }
4384 pull_failed:
4385   {
4386     GST_DEBUG_OBJECT (avi,
4387         "pull range failed: pos=%" G_GUINT64_FORMAT " size=%d",
4388         entry->offset + avi->index_offset, entry->size);
4389     goto beach;
4390   }
4391 short_buffer:
4392   {
4393     GST_WARNING_OBJECT (avi, "Short read at offset %" G_GUINT64_FORMAT
4394         ", only got %d/%d bytes (truncated file?)", entry->offset +
4395         avi->index_offset, GST_BUFFER_SIZE (buf), entry->size);
4396     gst_buffer_unref (buf);
4397     res = GST_FLOW_UNEXPECTED;
4398     goto beach;
4399   }
4400 }
4401
4402 /*
4403  * Read data. If we have an index it delegates to
4404  * gst_avi_demux_process_next_entry().
4405  */
4406 static GstFlowReturn
4407 gst_avi_demux_stream_data (GstAviDemux * avi)
4408 {
4409   guint32 tag = 0;
4410   guint32 size = 0;
4411   gint stream_nr = 0;
4412   GstFlowReturn res = GST_FLOW_OK;
4413   GstFormat format = GST_FORMAT_TIME;
4414
4415   /* if we have a avi->index_entries[], we don't want to read
4416    * the stream linearly, but seek to the next ts/index_entry. */
4417   if (G_LIKELY (avi->index_entries != NULL))
4418     return gst_avi_demux_process_next_entry (avi);
4419
4420   if (G_UNLIKELY (avi->have_eos)) {
4421     /* Clean adapter, we're done */
4422     gst_adapter_clear (avi->adapter);
4423     return res;
4424   }
4425
4426   /*
4427      if (!gst_avi_demux_sync (avi, &tag, FALSE))
4428      return FALSE;
4429    */
4430
4431   /* Iterate until need more data, so adapter won't grow too much */
4432   while (1) {
4433     if (G_UNLIKELY (!gst_avi_demux_peek_chunk_info (avi, &tag, &size))) {
4434       return GST_FLOW_OK;
4435     }
4436
4437     GST_DEBUG ("Trying chunk (%" GST_FOURCC_FORMAT "), size %d",
4438         GST_FOURCC_ARGS (tag), size);
4439
4440     if (G_LIKELY ((tag & 0xff) >= '0' && (tag & 0xff) <= '9' &&
4441             ((tag >> 8) & 0xff) >= '0' && ((tag >> 8) & 0xff) <= '9')) {
4442       GST_LOG ("Chunk ok");
4443     } else if ((tag & 0xffff) == (('x' << 8) | 'i')) {
4444       GST_DEBUG ("Found sub-index tag");
4445       if (gst_avi_demux_peek_chunk (avi, &tag, &size) || size == 0) {
4446         /* accept 0 size buffer here */
4447         avi->abort_buffering = FALSE;
4448         GST_DEBUG ("  skipping %d bytes for now", size);
4449         gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
4450       }
4451       return GST_FLOW_OK;
4452     } else if (tag == GST_RIFF_TAG_idx1) {
4453       GST_DEBUG ("Found index tag, stream done");
4454       avi->have_eos = TRUE;
4455       return GST_FLOW_UNEXPECTED;
4456     } else if (tag == GST_RIFF_TAG_LIST) {
4457       /* movi chunks might be grouped in rec list */
4458       if (gst_adapter_available (avi->adapter) >= 12) {
4459         GST_DEBUG ("Found LIST tag, skipping LIST header");
4460         gst_adapter_flush (avi->adapter, 12);
4461         continue;
4462       }
4463       return GST_FLOW_OK;
4464     } else if (tag == GST_RIFF_TAG_JUNK) {
4465       /* rec list might contain JUNK chunks */
4466       GST_DEBUG ("Found JUNK tag");
4467       if (gst_avi_demux_peek_chunk (avi, &tag, &size) || size == 0) {
4468         /* accept 0 size buffer here */
4469         avi->abort_buffering = FALSE;
4470         GST_DEBUG ("  skipping %d bytes for now", size);
4471         gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
4472       }
4473       return GST_FLOW_OK;
4474     } else {
4475       GST_DEBUG ("No more stream chunks, send EOS");
4476       avi->have_eos = TRUE;
4477       return GST_FLOW_UNEXPECTED;
4478     }
4479
4480     if (G_UNLIKELY (!gst_avi_demux_peek_chunk (avi, &tag, &size))) {
4481       /* supposedly one hopes to catch a nicer chunk later on ... */
4482       /* FIXME ?? give up here rather than possibly ending up going
4483        * through the whole file */
4484       if (avi->abort_buffering) {
4485         avi->abort_buffering = FALSE;
4486         gst_adapter_flush (avi->adapter, 8);
4487       }
4488       return GST_FLOW_OK;
4489     }
4490     GST_DEBUG ("chunk ID %" GST_FOURCC_FORMAT ", size %u",
4491         GST_FOURCC_ARGS (tag), size);
4492
4493     stream_nr = CHUNKID_TO_STREAMNR (tag);
4494
4495     if (G_UNLIKELY (stream_nr < 0 || stream_nr >= avi->num_streams)) {
4496       /* recoverable */
4497       GST_WARNING ("Invalid stream ID %d (%" GST_FOURCC_FORMAT ")",
4498           stream_nr, GST_FOURCC_ARGS (tag));
4499       avi->offset += 8 + ((size + 1) & ~1);
4500       gst_adapter_flush (avi->adapter, 8 + ((size + 1) & ~1));
4501     } else {
4502       avi_stream_context *stream;
4503       GstClockTime next_ts = 0;
4504       GstBuffer *buf;
4505
4506       gst_adapter_flush (avi->adapter, 8);
4507
4508       /* get buffer */
4509       buf = gst_adapter_take_buffer (avi->adapter, ((size + 1) & ~1));
4510       /* patch the size */
4511       GST_BUFFER_SIZE (buf) = size;
4512       avi->offset += 8 + ((size + 1) & ~1);
4513
4514       stream = &avi->stream[stream_nr];
4515
4516       /* set delay (if any)
4517          if (stream->strh->init_frames == stream->current_frame &&
4518          stream->delay == 0)
4519          stream->delay = next_ts;
4520        */
4521
4522
4523       /* parsing of corresponding header may have failed */
4524       if (G_UNLIKELY (!stream->pad)) {
4525         GST_WARNING_OBJECT (avi, "no pad for stream ID %" GST_FOURCC_FORMAT,
4526             GST_FOURCC_ARGS (tag));
4527         gst_buffer_unref (buf);
4528       } else {
4529         GstClockTime dur_ts = 0;
4530
4531         /* get time of this buffer */
4532         gst_pad_query_position (stream->pad, &format, (gint64 *) & next_ts);
4533         if (G_UNLIKELY (format != GST_FORMAT_TIME))
4534           goto wrong_format;
4535
4536         stream->current_frame++;
4537         stream->current_byte += size;
4538
4539         /* invert the picture if needed */
4540         buf = gst_avi_demux_invert (stream, buf);
4541
4542         gst_pad_query_position (stream->pad, &format, (gint64 *) & dur_ts);
4543         if (G_UNLIKELY (format != GST_FORMAT_TIME))
4544           goto wrong_format;
4545
4546         GST_BUFFER_TIMESTAMP (buf) = next_ts;
4547         GST_BUFFER_DURATION (buf) = dur_ts - next_ts;
4548         if (stream->strh->type == GST_RIFF_FCC_vids)
4549           GST_BUFFER_OFFSET (buf) = stream->current_frame - 1;
4550         else
4551           GST_BUFFER_OFFSET (buf) = GST_BUFFER_OFFSET_NONE;
4552
4553         gst_buffer_set_caps (buf, GST_PAD_CAPS (stream->pad));
4554         GST_DEBUG_OBJECT (avi,
4555             "Pushing buffer with time=%" GST_TIME_FORMAT ", duration %"
4556             GST_TIME_FORMAT ", offset %" G_GUINT64_FORMAT
4557             " and size %d over pad %s", GST_TIME_ARGS (next_ts),
4558             GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)), GST_BUFFER_OFFSET (buf),
4559             size, GST_PAD_NAME (stream->pad));
4560
4561         /* update current position in the segment */
4562         gst_segment_set_last_stop (&avi->segment, GST_FORMAT_TIME, next_ts);
4563
4564         /* mark discont when pending */
4565         if (G_UNLIKELY (stream->discont)) {
4566           GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
4567           stream->discont = FALSE;
4568         }
4569         res = gst_pad_push (stream->pad, buf);
4570
4571         /* combine flows */
4572         res = gst_avi_demux_combine_flows (avi, stream, res);
4573         if (G_UNLIKELY (res != GST_FLOW_OK)) {
4574           GST_DEBUG ("Push failed; %s", gst_flow_get_name (res));
4575           return res;
4576         }
4577       }
4578     }
4579   }
4580
4581 done:
4582   return res;
4583
4584   /* ERRORS */
4585 wrong_format:
4586   {
4587     GST_DEBUG_OBJECT (avi, "format %s != GST_FORMAT_TIME",
4588         gst_format_get_name (format));
4589     res = GST_FLOW_ERROR;
4590     goto done;
4591   }
4592 }
4593
4594 /*
4595  * Send pending tags.
4596  */
4597 static void
4598 push_tag_lists (GstAviDemux * avi)
4599 {
4600   guint i;
4601
4602   if (!avi->got_tags)
4603     return;
4604
4605   GST_DEBUG_OBJECT (avi, "Pushing pending tag lists");
4606
4607   for (i = 0; i < avi->num_streams; i++)
4608     if (avi->stream[i].pad && avi->stream[i].taglist) {
4609       GST_DEBUG_OBJECT (avi->stream[i].pad, "Tags: %" GST_PTR_FORMAT,
4610           avi->stream[i].taglist);
4611       gst_element_found_tags_for_pad (GST_ELEMENT (avi), avi->stream[i].pad,
4612           avi->stream[i].taglist);
4613       avi->stream[i].taglist = NULL;
4614     }
4615
4616   if (avi->globaltags == NULL)
4617     avi->globaltags = gst_tag_list_new ();
4618
4619   gst_tag_list_add (avi->globaltags, GST_TAG_MERGE_REPLACE,
4620       GST_TAG_CONTAINER_FORMAT, "AVI", NULL);
4621
4622   GST_DEBUG_OBJECT (avi, "Global tags: %" GST_PTR_FORMAT, avi->globaltags);
4623   gst_element_found_tags (GST_ELEMENT (avi), avi->globaltags);
4624   avi->globaltags = NULL;
4625   avi->got_tags = FALSE;
4626 }
4627
4628 static void
4629 gst_avi_demux_loop (GstPad * pad)
4630 {
4631   GstFlowReturn res;
4632   GstAviDemux *avi = GST_AVI_DEMUX (GST_PAD_PARENT (pad));
4633
4634   switch (avi->state) {
4635     case GST_AVI_DEMUX_START:
4636       if (G_UNLIKELY ((res =
4637                   gst_avi_demux_stream_init_pull (avi)) != GST_FLOW_OK)) {
4638         GST_WARNING ("stream_init flow: %s", gst_flow_get_name (res));
4639         goto pause;
4640       }
4641       avi->state = GST_AVI_DEMUX_HEADER;
4642       /* fall-through */
4643     case GST_AVI_DEMUX_HEADER:
4644       if (G_UNLIKELY ((res =
4645                   gst_avi_demux_stream_header_pull (avi)) != GST_FLOW_OK)) {
4646         GST_WARNING ("stream_header flow: %s", gst_flow_get_name (res));
4647         goto pause;
4648       }
4649       avi->state = GST_AVI_DEMUX_MOVI;
4650       break;
4651     case GST_AVI_DEMUX_MOVI:
4652       if (G_UNLIKELY (avi->seek_event)) {
4653         gst_avi_demux_push_event (avi, avi->seek_event);
4654         avi->seek_event = NULL;
4655       }
4656       if (G_UNLIKELY (avi->got_tags)) {
4657         push_tag_lists (avi);
4658       }
4659       /* process each index entry in turn */
4660       res = gst_avi_demux_stream_data (avi);
4661
4662       /* pause when error */
4663       if (G_UNLIKELY (res != GST_FLOW_OK)) {
4664         GST_INFO ("stream_movi flow: %s", gst_flow_get_name (res));
4665         goto pause;
4666       }
4667       break;
4668     default:
4669       GST_ERROR_OBJECT (avi, "unknown state %d", avi->state);
4670       res = GST_FLOW_ERROR;
4671       goto pause;
4672   }
4673
4674   GST_LOG_OBJECT (avi, "state: %d res:%s", avi->state, gst_flow_get_name (res));
4675
4676   return;
4677
4678   /* ERRORS */
4679 pause:
4680   GST_LOG_OBJECT (avi, "pausing task, reason %s", gst_flow_get_name (res));
4681   avi->segment_running = FALSE;
4682   gst_pad_pause_task (avi->sinkpad);
4683
4684   if (GST_FLOW_IS_FATAL (res) || (res == GST_FLOW_NOT_LINKED)) {
4685     gboolean push_eos = TRUE;
4686
4687     if (res == GST_FLOW_UNEXPECTED) {
4688       /* handle end-of-stream/segment */
4689       if (avi->segment.flags & GST_SEEK_FLAG_SEGMENT) {
4690         gint64 stop;
4691
4692         if ((stop = avi->segment.stop) == -1)
4693           stop = avi->segment.duration;
4694
4695         GST_INFO_OBJECT (avi, "sending segment_done");
4696
4697         gst_element_post_message
4698             (GST_ELEMENT (avi),
4699             gst_message_new_segment_done (GST_OBJECT (avi), GST_FORMAT_TIME,
4700                 stop));
4701         push_eos = FALSE;
4702       }
4703     } else {
4704       /* for fatal errors we post an error message */
4705       GST_ELEMENT_ERROR (avi, STREAM, FAILED,
4706           (_("Internal data stream error.")),
4707           ("streaming stopped, reason %s", gst_flow_get_name (res)));
4708     }
4709     if (push_eos) {
4710       GST_INFO_OBJECT (avi, "sending eos");
4711       if (!gst_avi_demux_push_event (avi, gst_event_new_eos ()) &&
4712           (res == GST_FLOW_UNEXPECTED)) {
4713         GST_ELEMENT_ERROR (avi, STREAM, DEMUX,
4714             (NULL), ("got eos but no streams (yet)"));
4715       }
4716     }
4717   }
4718 }
4719
4720
4721 static GstFlowReturn
4722 gst_avi_demux_chain (GstPad * pad, GstBuffer * buf)
4723 {
4724   GstFlowReturn res;
4725   GstAviDemux *avi = GST_AVI_DEMUX (GST_PAD_PARENT (pad));
4726
4727   GST_DEBUG ("Store %d bytes in adapter", GST_BUFFER_SIZE (buf));
4728   gst_adapter_push (avi->adapter, buf);
4729
4730   switch (avi->state) {
4731     case GST_AVI_DEMUX_START:
4732       if ((res = gst_avi_demux_stream_init_push (avi)) != GST_FLOW_OK) {
4733         GST_WARNING ("stream_init flow: %s", gst_flow_get_name (res));
4734         break;
4735       }
4736       break;
4737     case GST_AVI_DEMUX_HEADER:
4738       if ((res = gst_avi_demux_stream_header_push (avi)) != GST_FLOW_OK) {
4739         GST_WARNING ("stream_header flow: %s", gst_flow_get_name (res));
4740         break;
4741       }
4742       break;
4743     case GST_AVI_DEMUX_MOVI:
4744       if (G_UNLIKELY (avi->seek_event)) {
4745         gst_avi_demux_push_event (avi, avi->seek_event);
4746         avi->seek_event = NULL;
4747       }
4748       if (G_UNLIKELY (avi->got_tags)) {
4749         push_tag_lists (avi);
4750       }
4751       res = gst_avi_demux_stream_data (avi);
4752       break;
4753     default:
4754       GST_ELEMENT_ERROR (avi, STREAM, FAILED, (NULL),
4755           ("Illegal internal state"));
4756       res = GST_FLOW_ERROR;
4757       break;
4758   }
4759
4760   GST_DEBUG_OBJECT (avi, "state: %d res:%s", avi->state,
4761       gst_flow_get_name (res));
4762
4763   if (G_UNLIKELY (avi->abort_buffering)) {
4764     avi->abort_buffering = FALSE;
4765     res = GST_FLOW_ERROR;
4766     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, NULL, ("unhandled buffer size"));
4767   }
4768
4769   return res;
4770 }
4771
4772 static gboolean
4773 gst_avi_demux_sink_activate (GstPad * sinkpad)
4774 {
4775   if (gst_pad_check_pull_range (sinkpad)) {
4776     GST_DEBUG ("going to pull mode");
4777     return gst_pad_activate_pull (sinkpad, TRUE);
4778   } else {
4779     GST_DEBUG ("going to push (streaming) mode");
4780     return gst_pad_activate_push (sinkpad, TRUE);
4781   }
4782 }
4783
4784 static gboolean
4785 gst_avi_demux_sink_activate_pull (GstPad * sinkpad, gboolean active)
4786 {
4787   GstAviDemux *avi = GST_AVI_DEMUX (GST_OBJECT_PARENT (sinkpad));
4788
4789   if (active) {
4790     avi->segment_running = TRUE;
4791     avi->streaming = FALSE;
4792     return gst_pad_start_task (sinkpad, (GstTaskFunction) gst_avi_demux_loop,
4793         sinkpad);
4794   } else {
4795     avi->segment_running = FALSE;
4796     return gst_pad_stop_task (sinkpad);
4797   }
4798 }
4799
4800 static gboolean
4801 gst_avi_demux_activate_push (GstPad * pad, gboolean active)
4802 {
4803   GstAviDemux *avi = GST_AVI_DEMUX (GST_OBJECT_PARENT (pad));
4804
4805   if (active) {
4806     GST_DEBUG ("avi: activating push/chain function");
4807     avi->streaming = TRUE;
4808   } else {
4809     GST_DEBUG ("avi: deactivating push/chain function");
4810   }
4811
4812   return TRUE;
4813 }
4814
4815 static GstStateChangeReturn
4816 gst_avi_demux_change_state (GstElement * element, GstStateChange transition)
4817 {
4818   GstStateChangeReturn ret;
4819   GstAviDemux *avi = GST_AVI_DEMUX (element);
4820
4821   switch (transition) {
4822     case GST_STATE_CHANGE_READY_TO_PAUSED:
4823       avi->streaming = FALSE;
4824       gst_segment_init (&avi->segment, GST_FORMAT_TIME);
4825       break;
4826     default:
4827       break;
4828   }
4829
4830   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
4831   if (ret == GST_STATE_CHANGE_FAILURE)
4832     goto done;
4833
4834   switch (transition) {
4835     case GST_STATE_CHANGE_PAUSED_TO_READY:
4836       gst_avi_demux_reset (avi);
4837       break;
4838     default:
4839       break;
4840   }
4841
4842 done:
4843   return ret;
4844 }