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