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