avidemux: use segment_full when we can
[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 total_idx = 0;
1275   guint i;
1276 #ifndef GST_DISABLE_GST_DEBUG
1277   guint total_max = 0;
1278 #endif
1279
1280   /* get stream stats now */
1281   for (i = 0; i < avi->num_streams; i++) {
1282     GstAviStream *stream;
1283
1284     if (G_UNLIKELY (!(stream = &avi->stream[i])))
1285       continue;
1286     if (G_UNLIKELY (!stream->strh))
1287       continue;
1288     if (G_UNLIKELY (!stream->index || stream->idx_n == 0))
1289       continue;
1290
1291     /* we interested in the end_ts of the last entry, which is the total
1292      * duration of this stream */
1293     gst_avi_demux_get_buffer_info (avi, stream, stream->idx_n - 1,
1294         NULL, &stream->idx_duration, NULL, NULL);
1295
1296     total_idx += stream->idx_n;
1297 #ifndef GST_DISABLE_GST_DEBUG
1298     total_max += stream->idx_max;
1299 #endif
1300     GST_INFO_OBJECT (avi, "Stream %d, dur %" GST_TIME_FORMAT ", %6u entries, "
1301         "%5u keyframes, entry size = %2u, total size = %10u, allocated %10u",
1302         i, GST_TIME_ARGS (stream->idx_duration), stream->idx_n,
1303         stream->n_keyframes, (guint) sizeof (GstAviIndexEntry),
1304         (guint) (stream->idx_n * sizeof (GstAviIndexEntry)),
1305         (guint) (stream->idx_max * sizeof (GstAviIndexEntry)));
1306   }
1307   total_idx *= sizeof (GstAviIndexEntry);
1308 #ifndef GST_DISABLE_GST_DEBUG
1309   total_max *= sizeof (GstAviIndexEntry);
1310 #endif
1311   GST_INFO_OBJECT (avi, "%u bytes for index vs %u ideally, %u wasted",
1312       total_max, total_idx, total_max - total_idx);
1313
1314   if (total_idx == 0) {
1315     GST_WARNING_OBJECT (avi, "Index is empty !");
1316     return FALSE;
1317   }
1318   return TRUE;
1319 }
1320
1321 /*
1322  * gst_avi_demux_parse_subindex:
1323  * @avi: Avi object
1324  * @buf: input data to use for parsing.
1325  * @stream: stream context.
1326  * @entries_list: a list (returned by the function) containing all the
1327  *           indexes parsed in this specific subindex. The first
1328  *           entry is also a pointer to allocated memory that needs
1329  *           to be free´ed. May be NULL if no supported indexes were
1330  *           found.
1331  *
1332  * Reads superindex (openDML-2 spec stuff) from the provided data.
1333  * The buffer should contain a GST_RIFF_TAG_ix?? chunk.
1334  *
1335  * Returns: TRUE on success, FALSE otherwise. Errors are fatal, we
1336  *          throw an error, caller should bail out asap.
1337  */
1338 static gboolean
1339 gst_avi_demux_parse_subindex (GstAviDemux * avi, GstAviStream * stream,
1340     GstBuffer * buf)
1341 {
1342   guint8 *data;
1343   guint16 bpe;
1344   guint32 num, i;
1345   guint64 baseoff;
1346   guint size;
1347
1348   if (!buf)
1349     return TRUE;
1350
1351   size = GST_BUFFER_SIZE (buf);
1352
1353   /* check size */
1354   if (size < 24)
1355     goto too_small;
1356
1357   data = GST_BUFFER_DATA (buf);
1358
1359   /* We don't support index-data yet */
1360   if (data[3] & 0x80)
1361     goto not_implemented;
1362
1363   /* check type of index. The opendml2 specs state that
1364    * there should be 4 dwords per array entry. Type can be
1365    * either frame or field (and we don't care). */
1366   bpe = (data[2] & 0x01) ? 12 : 8;
1367   if (GST_READ_UINT16_LE (data) != bpe / 4 ||
1368       (data[2] & 0xfe) != 0x0 || data[3] != 0x1) {
1369     GST_WARNING_OBJECT (avi,
1370         "Superindex for stream %d has unexpected "
1371         "size_entry %d (bytes) or flags 0x%02x/0x%02x",
1372         stream->num, GST_READ_UINT16_LE (data), data[2], data[3]);
1373     bpe = GST_READ_UINT16_LE (data) * 4;
1374   }
1375   num = GST_READ_UINT32_LE (&data[4]);
1376   baseoff = GST_READ_UINT64_LE (&data[12]);
1377
1378   /* If there's nothing, just return ! */
1379   if (num == 0)
1380     goto empty_index;
1381
1382   GST_INFO_OBJECT (avi, "Parsing subindex, nr_entries = %6d", num);
1383
1384   for (i = 0; i < num; i++) {
1385     GstAviIndexEntry entry;
1386
1387     if (size < 24 + bpe * (i + 1))
1388       break;
1389
1390     /* fill in offset and size. offset contains the keyframe flag in the
1391      * upper bit*/
1392     entry.offset = baseoff + GST_READ_UINT32_LE (&data[24 + bpe * i]);
1393     entry.size = GST_READ_UINT32_LE (&data[24 + bpe * i + 4]);
1394     /* handle flags */
1395     if (stream->strh->type == GST_RIFF_FCC_auds) {
1396       /* all audio frames are keyframes */
1397       ENTRY_SET_KEYFRAME (&entry);
1398     } else {
1399       /* else read flags */
1400       entry.flags = (entry.size & 0x80000000) ? 0 : GST_AVI_KEYFRAME;
1401     }
1402     entry.size &= ~0x80000000;
1403
1404     /* and add */
1405     if (G_UNLIKELY (!gst_avi_demux_add_index (avi, stream, num, &entry)))
1406       goto out_of_mem;
1407   }
1408   gst_buffer_unref (buf);
1409
1410   return TRUE;
1411
1412   /* ERRORS */
1413 too_small:
1414   {
1415     GST_ERROR_OBJECT (avi,
1416         "Not enough data to parse subindex (%d available, 24 needed)", size);
1417     gst_buffer_unref (buf);
1418     return TRUE;                /* continue */
1419   }
1420 not_implemented:
1421   {
1422     GST_ELEMENT_ERROR (avi, STREAM, NOT_IMPLEMENTED, (NULL),
1423         ("Subindex-is-data is not implemented"));
1424     gst_buffer_unref (buf);
1425     return FALSE;
1426   }
1427 empty_index:
1428   {
1429     GST_DEBUG_OBJECT (avi, "the index is empty");
1430     gst_buffer_unref (buf);
1431     return TRUE;
1432   }
1433 out_of_mem:
1434   {
1435     GST_ELEMENT_ERROR (avi, RESOURCE, NO_SPACE_LEFT, (NULL),
1436         ("Cannot allocate memory for %u*%u=%u bytes",
1437             (guint) sizeof (GstAviIndexEntry), num,
1438             (guint) sizeof (GstAviIndexEntry) * num));
1439     gst_buffer_unref (buf);
1440     return FALSE;
1441   }
1442 }
1443
1444 #if 0
1445 /*
1446  * Read AVI index when streaming
1447  */
1448 static void
1449 gst_avi_demux_read_subindexes_push (GstAviDemux * avi)
1450 {
1451   guint32 tag = 0, size;
1452   GstBuffer *buf = NULL;
1453   gint i, n;
1454
1455   GST_DEBUG_OBJECT (avi, "read subindexes for %d streams", avi->num_streams);
1456
1457   for (n = 0; n < avi->num_streams; n++) {
1458     GstAviStream *stream = &avi->stream[n];
1459
1460     for (i = 0; stream->indexes[i] != GST_BUFFER_OFFSET_NONE; i++) {
1461       if (!gst_avi_demux_peek_chunk (avi, &tag, &size))
1462         continue;
1463       else if ((tag != GST_MAKE_FOURCC ('i', 'x', '0' + stream->num / 10,
1464                   '0' + stream->num % 10)) &&
1465           (tag != GST_MAKE_FOURCC ('0' + stream->num / 10,
1466                   '0' + stream->num % 10, 'i', 'x'))) {
1467         GST_WARNING_OBJECT (avi, "Not an ix## chunk (%" GST_FOURCC_FORMAT ")",
1468             GST_FOURCC_ARGS (tag));
1469         continue;
1470       }
1471
1472       avi->offset += 8 + GST_ROUND_UP_2 (size);
1473
1474       buf = gst_buffer_new ();
1475       GST_BUFFER_DATA (buf) = gst_adapter_take (avi->adapter, size);
1476       GST_BUFFER_SIZE (buf) = size;
1477
1478       if (!gst_avi_demux_parse_subindex (avi, stream, buf))
1479         continue;
1480     }
1481
1482     g_free (stream->indexes);
1483     stream->indexes = NULL;
1484   }
1485   /* get stream stats now */
1486   avi->have_index = gst_avi_demux_do_index_stats (avi);
1487 }
1488 #endif
1489
1490 /*
1491  * Read AVI index
1492  */
1493 static void
1494 gst_avi_demux_read_subindexes_pull (GstAviDemux * avi)
1495 {
1496   guint32 tag;
1497   GstBuffer *buf;
1498   gint i, n;
1499
1500   GST_DEBUG_OBJECT (avi, "read subindexes for %d streams", avi->num_streams);
1501
1502   for (n = 0; n < avi->num_streams; n++) {
1503     GstAviStream *stream = &avi->stream[n];
1504
1505     for (i = 0; stream->indexes[i] != GST_BUFFER_OFFSET_NONE; i++) {
1506       if (gst_riff_read_chunk (GST_ELEMENT_CAST (avi), avi->sinkpad,
1507               &stream->indexes[i], &tag, &buf) != GST_FLOW_OK)
1508         continue;
1509       else if ((tag != GST_MAKE_FOURCC ('i', 'x', '0' + stream->num / 10,
1510                   '0' + stream->num % 10)) &&
1511           (tag != GST_MAKE_FOURCC ('0' + stream->num / 10,
1512                   '0' + stream->num % 10, 'i', 'x'))) {
1513         /* Some ODML files (created by god knows what muxer) have a ##ix format
1514          * instead of the 'official' ix##. They are still valid though. */
1515         GST_WARNING_OBJECT (avi, "Not an ix## chunk (%" GST_FOURCC_FORMAT ")",
1516             GST_FOURCC_ARGS (tag));
1517         gst_buffer_unref (buf);
1518         continue;
1519       }
1520
1521       if (!gst_avi_demux_parse_subindex (avi, stream, buf))
1522         continue;
1523     }
1524
1525     g_free (stream->indexes);
1526     stream->indexes = NULL;
1527   }
1528   /* get stream stats now */
1529   avi->have_index = gst_avi_demux_do_index_stats (avi);
1530 }
1531
1532 /*
1533  * gst_avi_demux_riff_parse_vprp:
1534  * @element: caller element (used for debugging/error).
1535  * @buf: input data to be used for parsing, stripped from header.
1536  * @vprp: a pointer (returned by this function) to a filled-in vprp
1537  *        structure. Caller should free it.
1538  *
1539  * Parses a video stream´s vprp. This function takes ownership of @buf.
1540  *
1541  * Returns: TRUE if parsing succeeded, otherwise FALSE. The stream
1542  *          should be skipped on error, but it is not fatal.
1543  */
1544 static gboolean
1545 gst_avi_demux_riff_parse_vprp (GstElement * element,
1546     GstBuffer * buf, gst_riff_vprp ** _vprp)
1547 {
1548   gst_riff_vprp *vprp;
1549   gint k;
1550
1551   g_return_val_if_fail (buf != NULL, FALSE);
1552   g_return_val_if_fail (_vprp != NULL, FALSE);
1553
1554   if (GST_BUFFER_SIZE (buf) < G_STRUCT_OFFSET (gst_riff_vprp, field_info))
1555     goto too_small;
1556
1557   vprp = g_memdup (GST_BUFFER_DATA (buf), GST_BUFFER_SIZE (buf));
1558
1559 #if (G_BYTE_ORDER == G_BIG_ENDIAN)
1560   vprp->format_token = GUINT32_FROM_LE (vprp->format_token);
1561   vprp->standard = GUINT32_FROM_LE (vprp->standard);
1562   vprp->vert_rate = GUINT32_FROM_LE (vprp->vert_rate);
1563   vprp->hor_t_total = GUINT32_FROM_LE (vprp->hor_t_total);
1564   vprp->vert_lines = GUINT32_FROM_LE (vprp->vert_lines);
1565   vprp->aspect = GUINT32_FROM_LE (vprp->aspect);
1566   vprp->width = GUINT32_FROM_LE (vprp->width);
1567   vprp->height = GUINT32_FROM_LE (vprp->height);
1568   vprp->fields = GUINT32_FROM_LE (vprp->fields);
1569 #endif
1570
1571   /* size checking */
1572   /* calculate fields based on size */
1573   k = (GST_BUFFER_SIZE (buf) - G_STRUCT_OFFSET (gst_riff_vprp, field_info)) /
1574       vprp->fields;
1575   if (vprp->fields > k) {
1576     GST_WARNING_OBJECT (element,
1577         "vprp header indicated %d fields, only %d available", vprp->fields, k);
1578     vprp->fields = k;
1579   }
1580   if (vprp->fields > GST_RIFF_VPRP_VIDEO_FIELDS) {
1581     GST_WARNING_OBJECT (element,
1582         "vprp header indicated %d fields, at most %d supported", vprp->fields,
1583         GST_RIFF_VPRP_VIDEO_FIELDS);
1584     vprp->fields = GST_RIFF_VPRP_VIDEO_FIELDS;
1585   }
1586 #if (G_BYTE_ORDER == G_BIG_ENDIAN)
1587   for (k = 0; k < vprp->fields; k++) {
1588     gst_riff_vprp_video_field_desc *fd;
1589
1590     fd = &vprp->field_info[k];
1591     fd->compressed_bm_height = GUINT32_FROM_LE (fd->compressed_bm_height);
1592     fd->compressed_bm_width = GUINT32_FROM_LE (fd->compressed_bm_width);
1593     fd->valid_bm_height = GUINT32_FROM_LE (fd->valid_bm_height);
1594     fd->valid_bm_width = GUINT16_FROM_LE (fd->valid_bm_width);
1595     fd->valid_bm_x_offset = GUINT16_FROM_LE (fd->valid_bm_x_offset);
1596     fd->valid_bm_y_offset = GUINT32_FROM_LE (fd->valid_bm_y_offset);
1597     fd->video_x_t_offset = GUINT32_FROM_LE (fd->video_x_t_offset);
1598     fd->video_y_start = GUINT32_FROM_LE (fd->video_y_start);
1599   }
1600 #endif
1601
1602   /* debug */
1603   GST_INFO_OBJECT (element, "vprp tag found in context vids:");
1604   GST_INFO_OBJECT (element, " format_token  %d", vprp->format_token);
1605   GST_INFO_OBJECT (element, " standard      %d", vprp->standard);
1606   GST_INFO_OBJECT (element, " vert_rate     %d", vprp->vert_rate);
1607   GST_INFO_OBJECT (element, " hor_t_total   %d", vprp->hor_t_total);
1608   GST_INFO_OBJECT (element, " vert_lines    %d", vprp->vert_lines);
1609   GST_INFO_OBJECT (element, " aspect        %d:%d", vprp->aspect >> 16,
1610       vprp->aspect & 0xffff);
1611   GST_INFO_OBJECT (element, " width         %d", vprp->width);
1612   GST_INFO_OBJECT (element, " height        %d", vprp->height);
1613   GST_INFO_OBJECT (element, " fields        %d", vprp->fields);
1614   for (k = 0; k < vprp->fields; k++) {
1615     gst_riff_vprp_video_field_desc *fd;
1616
1617     fd = &(vprp->field_info[k]);
1618     GST_INFO_OBJECT (element, " field %u description:", k);
1619     GST_INFO_OBJECT (element, "  compressed_bm_height  %d",
1620         fd->compressed_bm_height);
1621     GST_INFO_OBJECT (element, "  compressed_bm_width  %d",
1622         fd->compressed_bm_width);
1623     GST_INFO_OBJECT (element, "  valid_bm_height       %d",
1624         fd->valid_bm_height);
1625     GST_INFO_OBJECT (element, "  valid_bm_width        %d", fd->valid_bm_width);
1626     GST_INFO_OBJECT (element, "  valid_bm_x_offset     %d",
1627         fd->valid_bm_x_offset);
1628     GST_INFO_OBJECT (element, "  valid_bm_y_offset     %d",
1629         fd->valid_bm_y_offset);
1630     GST_INFO_OBJECT (element, "  video_x_t_offset      %d",
1631         fd->video_x_t_offset);
1632     GST_INFO_OBJECT (element, "  video_y_start         %d", fd->video_y_start);
1633   }
1634
1635   gst_buffer_unref (buf);
1636
1637   *_vprp = vprp;
1638
1639   return TRUE;
1640
1641   /* ERRORS */
1642 too_small:
1643   {
1644     GST_ERROR_OBJECT (element,
1645         "Too small vprp (%d available, at least %d needed)",
1646         GST_BUFFER_SIZE (buf),
1647         (int) G_STRUCT_OFFSET (gst_riff_vprp, field_info));
1648     gst_buffer_unref (buf);
1649     return FALSE;
1650   }
1651 }
1652
1653 static void
1654 gst_avi_demux_expose_streams (GstAviDemux * avi, gboolean force)
1655 {
1656   guint i;
1657
1658   GST_DEBUG_OBJECT (avi, "force : %d", force);
1659
1660   for (i = 0; i < avi->num_streams; i++) {
1661     GstAviStream *stream = &avi->stream[i];
1662
1663     if (force || stream->idx_n != 0) {
1664       GST_LOG_OBJECT (avi, "Added pad %s with caps %" GST_PTR_FORMAT,
1665           GST_PAD_NAME (stream->pad), GST_PAD_CAPS (stream->pad));
1666       gst_element_add_pad ((GstElement *) avi, stream->pad);
1667       stream->exposed = TRUE;
1668       if (avi->main_stream == -1)
1669         avi->main_stream = i;
1670     } else {
1671       GST_WARNING_OBJECT (avi, "Stream #%d doesn't have any entry, removing it",
1672           i);
1673       gst_avi_demux_reset_stream (avi, stream);
1674     }
1675   }
1676 }
1677
1678 /*
1679  * gst_avi_demux_parse_stream:
1680  * @avi: calling element (used for debugging/errors).
1681  * @buf: input buffer used to parse the stream.
1682  *
1683  * Parses all subchunks in a strl chunk (which defines a single
1684  * stream). Discards the buffer after use. This function will
1685  * increment the stream counter internally.
1686  *
1687  * Returns: whether the stream was identified successfully.
1688  *          Errors are not fatal. It does indicate the stream
1689  *          was skipped.
1690  */
1691 static gboolean
1692 gst_avi_demux_parse_stream (GstAviDemux * avi, GstBuffer * buf)
1693 {
1694   GstAviStream *stream;
1695   GstElementClass *klass;
1696   GstPadTemplate *templ;
1697   GstBuffer *sub = NULL;
1698   guint offset = 4;
1699   guint32 tag = 0;
1700   gchar *codec_name = NULL, *padname = NULL;
1701   const gchar *tag_name;
1702   GstCaps *caps = NULL;
1703   GstPad *pad;
1704   GstElement *element;
1705   gboolean got_strh = FALSE, got_strf = FALSE, got_vprp = FALSE;
1706   gst_riff_vprp *vprp = NULL;
1707
1708   element = GST_ELEMENT_CAST (avi);
1709
1710   GST_DEBUG_OBJECT (avi, "Parsing stream");
1711
1712   if (avi->num_streams >= GST_AVI_DEMUX_MAX_STREAMS) {
1713     GST_WARNING_OBJECT (avi,
1714         "maximum no of streams (%d) exceeded, ignoring stream",
1715         GST_AVI_DEMUX_MAX_STREAMS);
1716     gst_buffer_unref (buf);
1717     /* not a fatal error, let's say */
1718     return TRUE;
1719   }
1720
1721   stream = &avi->stream[avi->num_streams];
1722
1723   /* initial settings */
1724   stream->idx_duration = GST_CLOCK_TIME_NONE;
1725   stream->hdr_duration = GST_CLOCK_TIME_NONE;
1726   stream->duration = GST_CLOCK_TIME_NONE;
1727
1728   while (gst_riff_parse_chunk (element, buf, &offset, &tag, &sub)) {
1729     /* sub can be NULL if the chunk is empty */
1730     if (sub == NULL) {
1731       GST_DEBUG_OBJECT (avi, "ignoring empty chunk %" GST_FOURCC_FORMAT,
1732           GST_FOURCC_ARGS (tag));
1733       continue;
1734     }
1735     switch (tag) {
1736       case GST_RIFF_TAG_strh:
1737       {
1738         gst_riff_strh *strh;
1739
1740         if (got_strh) {
1741           GST_WARNING_OBJECT (avi, "Ignoring additional strh chunk");
1742           break;
1743         }
1744         if (!gst_riff_parse_strh (element, sub, &stream->strh)) {
1745           /* ownership given away */
1746           sub = NULL;
1747           GST_WARNING_OBJECT (avi, "Failed to parse strh chunk");
1748           goto fail;
1749         }
1750         sub = NULL;
1751         strh = stream->strh;
1752         /* sanity check; stream header frame rate matches global header
1753          * frame duration */
1754         if (stream->strh->type == GST_RIFF_FCC_vids) {
1755           GstClockTime s_dur;
1756           GstClockTime h_dur = avi->avih->us_frame * GST_USECOND;
1757
1758           s_dur = gst_util_uint64_scale (GST_SECOND, strh->scale, strh->rate);
1759           GST_DEBUG_OBJECT (avi, "verifying stream framerate %d/%d, "
1760               "frame duration = %d ms", strh->rate, strh->scale,
1761               (gint) (s_dur / GST_MSECOND));
1762           if (h_dur > (10 * GST_MSECOND) && (s_dur > 10 * h_dur)) {
1763             strh->rate = GST_SECOND / GST_USECOND;
1764             strh->scale = h_dur / GST_USECOND;
1765             GST_DEBUG_OBJECT (avi, "correcting stream framerate to %d/%d",
1766                 strh->rate, strh->scale);
1767           }
1768         }
1769         /* determine duration as indicated by header */
1770         stream->hdr_duration = gst_util_uint64_scale ((guint64) strh->length *
1771             strh->scale, GST_SECOND, (guint64) strh->rate);
1772         GST_INFO ("Stream duration according to header: %" GST_TIME_FORMAT,
1773             GST_TIME_ARGS (stream->hdr_duration));
1774         if (stream->hdr_duration == 0)
1775           stream->hdr_duration = GST_CLOCK_TIME_NONE;
1776
1777         got_strh = TRUE;
1778         break;
1779       }
1780       case GST_RIFF_TAG_strf:
1781       {
1782         gboolean res = FALSE;
1783
1784         if (got_strf) {
1785           GST_WARNING_OBJECT (avi, "Ignoring additional strf chunk");
1786           break;
1787         }
1788         if (!got_strh) {
1789           GST_ERROR_OBJECT (avi, "Found strf chunk before strh chunk");
1790           goto fail;
1791         }
1792         switch (stream->strh->type) {
1793           case GST_RIFF_FCC_vids:
1794             stream->is_vbr = TRUE;
1795             res = gst_riff_parse_strf_vids (element, sub,
1796                 &stream->strf.vids, &stream->extradata);
1797             sub = NULL;
1798             GST_DEBUG_OBJECT (element, "marking video as VBR, res %d", res);
1799             break;
1800           case GST_RIFF_FCC_auds:
1801             stream->is_vbr = (stream->strh->samplesize == 0)
1802                 && stream->strh->scale > 1;
1803             res =
1804                 gst_riff_parse_strf_auds (element, sub, &stream->strf.auds,
1805                 &stream->extradata);
1806             sub = NULL;
1807             GST_DEBUG_OBJECT (element, "marking audio as VBR:%d, res %d",
1808                 stream->is_vbr, res);
1809             break;
1810           case GST_RIFF_FCC_iavs:
1811             stream->is_vbr = TRUE;
1812             res = gst_riff_parse_strf_iavs (element, sub,
1813                 &stream->strf.iavs, &stream->extradata);
1814             sub = NULL;
1815             GST_DEBUG_OBJECT (element, "marking iavs as VBR, res %d", res);
1816             break;
1817           case GST_RIFF_FCC_txts:
1818             /* nothing to parse here */
1819             stream->is_vbr = (stream->strh->samplesize == 0)
1820                 && (stream->strh->scale > 1);
1821             res = TRUE;
1822             break;
1823           default:
1824             GST_ERROR_OBJECT (avi,
1825                 "Don´t know how to handle stream type %" GST_FOURCC_FORMAT,
1826                 GST_FOURCC_ARGS (stream->strh->type));
1827             break;
1828         }
1829         if (sub) {
1830           gst_buffer_unref (sub);
1831           sub = NULL;
1832         }
1833         if (!res)
1834           goto fail;
1835         got_strf = TRUE;
1836         break;
1837       }
1838       case GST_RIFF_TAG_vprp:
1839       {
1840         if (got_vprp) {
1841           GST_WARNING_OBJECT (avi, "Ignoring additional vprp chunk");
1842           break;
1843         }
1844         if (!got_strh) {
1845           GST_ERROR_OBJECT (avi, "Found vprp chunk before strh chunk");
1846           goto fail;
1847         }
1848         if (!got_strf) {
1849           GST_ERROR_OBJECT (avi, "Found vprp chunk before strf chunk");
1850           goto fail;
1851         }
1852
1853         if (!gst_avi_demux_riff_parse_vprp (element, sub, &vprp)) {
1854           GST_WARNING_OBJECT (avi, "Failed to parse vprp chunk");
1855           /* not considered fatal */
1856           g_free (vprp);
1857           vprp = NULL;
1858         } else
1859           got_vprp = TRUE;
1860         sub = NULL;
1861         break;
1862       }
1863       case GST_RIFF_TAG_strd:
1864         if (stream->initdata)
1865           gst_buffer_unref (stream->initdata);
1866         stream->initdata = sub;
1867         sub = NULL;
1868         break;
1869       case GST_RIFF_TAG_strn:
1870         g_free (stream->name);
1871         if (sub != NULL) {
1872           stream->name =
1873               g_strndup ((gchar *) GST_BUFFER_DATA (sub),
1874               (gsize) GST_BUFFER_SIZE (sub));
1875           gst_buffer_unref (sub);
1876           sub = NULL;
1877         } else {
1878           stream->name = g_strdup ("");
1879         }
1880         GST_DEBUG_OBJECT (avi, "stream name: %s", stream->name);
1881         break;
1882       default:
1883         if (tag == GST_MAKE_FOURCC ('i', 'n', 'd', 'x') ||
1884             tag == GST_MAKE_FOURCC ('i', 'x', '0' + avi->num_streams / 10,
1885                 '0' + avi->num_streams % 10)) {
1886           g_free (stream->indexes);
1887           gst_avi_demux_parse_superindex (avi, sub, &stream->indexes);
1888           stream->superindex = TRUE;
1889           sub = NULL;
1890           break;
1891         }
1892         GST_WARNING_OBJECT (avi,
1893             "Unknown stream header tag %" GST_FOURCC_FORMAT ", ignoring",
1894             GST_FOURCC_ARGS (tag));
1895         /* fall-through */
1896       case GST_RIFF_TAG_JUNK:
1897         break;
1898     }
1899     if (sub != NULL) {
1900       gst_buffer_unref (sub);
1901       sub = NULL;
1902     }
1903   }
1904
1905   if (!got_strh) {
1906     GST_WARNING_OBJECT (avi, "Failed to find strh chunk");
1907     goto fail;
1908   }
1909
1910   if (!got_strf) {
1911     GST_WARNING_OBJECT (avi, "Failed to find strf chunk");
1912     goto fail;
1913   }
1914
1915   /* get class to figure out the template */
1916   klass = GST_ELEMENT_GET_CLASS (avi);
1917
1918   /* we now have all info, let´s set up a pad and a caps and be done */
1919   /* create stream name + pad */
1920   switch (stream->strh->type) {
1921     case GST_RIFF_FCC_vids:{
1922       guint32 fourcc;
1923
1924       fourcc = (stream->strf.vids->compression) ?
1925           stream->strf.vids->compression : stream->strh->fcc_handler;
1926       padname = g_strdup_printf ("video_%02d", avi->num_v_streams);
1927       templ = gst_element_class_get_pad_template (klass, "video_%02d");
1928       caps = gst_riff_create_video_caps (fourcc, stream->strh,
1929           stream->strf.vids, stream->extradata, stream->initdata, &codec_name);
1930       if (!caps) {
1931         caps = gst_caps_new_simple ("video/x-avi-unknown", "fourcc",
1932             GST_TYPE_FOURCC, fourcc, NULL);
1933       } else if (got_vprp && vprp) {
1934         guint32 aspect_n, aspect_d;
1935         gint n, d;
1936
1937         aspect_n = vprp->aspect >> 16;
1938         aspect_d = vprp->aspect & 0xffff;
1939         /* calculate the pixel aspect ratio using w/h and aspect ratio */
1940         n = aspect_n * stream->strf.vids->height;
1941         d = aspect_d * stream->strf.vids->width;
1942         if (n && d)
1943           gst_caps_set_simple (caps, "pixel-aspect-ratio", GST_TYPE_FRACTION,
1944               n, d, NULL);
1945         /* very local, not needed elsewhere */
1946         g_free (vprp);
1947         vprp = NULL;
1948       }
1949       tag_name = GST_TAG_VIDEO_CODEC;
1950       avi->num_v_streams++;
1951       break;
1952     }
1953     case GST_RIFF_FCC_auds:{
1954       padname = g_strdup_printf ("audio_%02d", avi->num_a_streams);
1955       templ = gst_element_class_get_pad_template (klass, "audio_%02d");
1956       caps = gst_riff_create_audio_caps (stream->strf.auds->format,
1957           stream->strh, stream->strf.auds, stream->extradata,
1958           stream->initdata, &codec_name);
1959       if (!caps) {
1960         caps = gst_caps_new_simple ("audio/x-avi-unknown", "codec_id",
1961             G_TYPE_INT, stream->strf.auds->format, NULL);
1962       }
1963       tag_name = GST_TAG_AUDIO_CODEC;
1964       avi->num_a_streams++;
1965       break;
1966     }
1967     case GST_RIFF_FCC_iavs:{
1968       guint32 fourcc = stream->strh->fcc_handler;
1969
1970       padname = g_strdup_printf ("video_%02d", avi->num_v_streams);
1971       templ = gst_element_class_get_pad_template (klass, "video_%02d");
1972       caps = gst_riff_create_iavs_caps (fourcc, stream->strh,
1973           stream->strf.iavs, stream->extradata, stream->initdata, &codec_name);
1974       if (!caps) {
1975         caps = gst_caps_new_simple ("video/x-avi-unknown", "fourcc",
1976             GST_TYPE_FOURCC, fourcc, NULL);
1977       }
1978       tag_name = GST_TAG_VIDEO_CODEC;
1979       avi->num_v_streams++;
1980       break;
1981     }
1982     case GST_RIFF_FCC_txts:{
1983       padname = g_strdup_printf ("subtitle_%02d", avi->num_t_streams);
1984       templ = gst_element_class_get_pad_template (klass, "subtitle_%02d");
1985       caps = gst_caps_new_simple ("application/x-subtitle-avi", NULL);
1986       tag_name = NULL;
1987       avi->num_t_streams++;
1988       break;
1989     }
1990     default:
1991       g_assert_not_reached ();
1992   }
1993
1994   /* no caps means no stream */
1995   if (!caps) {
1996     GST_ERROR_OBJECT (element, "Did not find caps for stream %s", padname);
1997     goto fail;
1998   }
1999
2000   GST_DEBUG_OBJECT (element, "codec-name=%s",
2001       (codec_name ? codec_name : "NULL"));
2002   GST_DEBUG_OBJECT (element, "caps=%" GST_PTR_FORMAT, caps);
2003
2004   /* set proper settings and add it */
2005   if (stream->pad)
2006     gst_object_unref (stream->pad);
2007   pad = stream->pad = gst_pad_new_from_template (templ, padname);
2008   g_free (padname);
2009
2010   gst_pad_use_fixed_caps (pad);
2011 #if 0
2012   gst_pad_set_formats_function (pad,
2013       GST_DEBUG_FUNCPTR (gst_avi_demux_get_src_formats));
2014   gst_pad_set_event_mask_function (pad,
2015       GST_DEBUG_FUNCPTR (gst_avi_demux_get_event_mask));
2016 #endif
2017   gst_pad_set_event_function (pad,
2018       GST_DEBUG_FUNCPTR (gst_avi_demux_handle_src_event));
2019   gst_pad_set_query_type_function (pad,
2020       GST_DEBUG_FUNCPTR (gst_avi_demux_get_src_query_types));
2021   gst_pad_set_query_function (pad,
2022       GST_DEBUG_FUNCPTR (gst_avi_demux_handle_src_query));
2023 #if 0
2024   gst_pad_set_convert_function (pad,
2025       GST_DEBUG_FUNCPTR (gst_avi_demux_src_convert));
2026 #endif
2027
2028   if (avi->element_index)
2029     gst_index_get_writer_id (avi->element_index, GST_OBJECT (stream->pad),
2030         &stream->index_id);
2031
2032   stream->num = avi->num_streams;
2033
2034   stream->start_entry = 0;
2035   stream->step_entry = 0;
2036   stream->stop_entry = 0;
2037
2038   stream->current_entry = -1;
2039   stream->current_total = 0;
2040
2041   stream->last_flow = GST_FLOW_OK;
2042   stream->discont = TRUE;
2043
2044   stream->total_bytes = 0;
2045   stream->total_blocks = 0;
2046   stream->n_keyframes = 0;
2047
2048   stream->idx_n = 0;
2049   stream->idx_max = 0;
2050
2051   gst_pad_set_element_private (pad, stream);
2052   avi->num_streams++;
2053
2054   gst_pad_set_caps (pad, caps);
2055   gst_pad_set_active (pad, TRUE);
2056   gst_caps_unref (caps);
2057
2058   /* make tags */
2059   if (codec_name) {
2060     if (!stream->taglist)
2061       stream->taglist = gst_tag_list_new ();
2062
2063     avi->got_tags = TRUE;
2064
2065     gst_tag_list_add (stream->taglist, GST_TAG_MERGE_APPEND, tag_name,
2066         codec_name, NULL);
2067     g_free (codec_name);
2068   }
2069
2070   gst_buffer_unref (buf);
2071
2072   return TRUE;
2073
2074   /* ERRORS */
2075 fail:
2076   {
2077     /* unref any mem that may be in use */
2078     if (buf)
2079       gst_buffer_unref (buf);
2080     if (sub)
2081       gst_buffer_unref (sub);
2082     g_free (vprp);
2083     g_free (codec_name);
2084     gst_avi_demux_reset_stream (avi, stream);
2085     avi->num_streams++;
2086     return FALSE;
2087   }
2088 }
2089
2090 /*
2091  * gst_avi_demux_parse_odml:
2092  * @avi: calling element (used for debug/error).
2093  * @buf: input buffer to be used for parsing.
2094  *
2095  * Read an openDML-2.0 extension header. Fills in the frame number
2096  * in the avi demuxer object when reading succeeds.
2097  */
2098 static void
2099 gst_avi_demux_parse_odml (GstAviDemux * avi, GstBuffer * buf)
2100 {
2101   guint32 tag = 0;
2102   guint offset = 4;
2103   GstBuffer *sub = NULL;
2104
2105   while (gst_riff_parse_chunk (GST_ELEMENT_CAST (avi), buf, &offset, &tag,
2106           &sub)) {
2107     switch (tag) {
2108       case GST_RIFF_TAG_dmlh:{
2109         gst_riff_dmlh dmlh, *_dmlh;
2110         guint size;
2111
2112         /* sub == NULL is possible and means an empty buffer */
2113         size = sub ? GST_BUFFER_SIZE (sub) : 0;
2114
2115         /* check size */
2116         if (size < sizeof (gst_riff_dmlh)) {
2117           GST_ERROR_OBJECT (avi,
2118               "DMLH entry is too small (%d bytes, %d needed)",
2119               size, (int) sizeof (gst_riff_dmlh));
2120           goto next;
2121         }
2122         _dmlh = (gst_riff_dmlh *) GST_BUFFER_DATA (sub);
2123         dmlh.totalframes = GST_READ_UINT32_LE (&_dmlh->totalframes);
2124
2125         GST_INFO_OBJECT (avi, "dmlh tag found: totalframes: %u",
2126             dmlh.totalframes);
2127
2128         avi->avih->tot_frames = dmlh.totalframes;
2129         goto next;
2130       }
2131
2132       default:
2133         GST_WARNING_OBJECT (avi,
2134             "Unknown tag %" GST_FOURCC_FORMAT " in ODML header",
2135             GST_FOURCC_ARGS (tag));
2136         /* fall-through */
2137       case GST_RIFF_TAG_JUNK:
2138       next:
2139         /* skip and move to next chunk */
2140         if (sub) {
2141           gst_buffer_unref (sub);
2142           sub = NULL;
2143         }
2144         break;
2145     }
2146   }
2147   if (buf)
2148     gst_buffer_unref (buf);
2149 }
2150
2151 /* Index helper */
2152 static guint
2153 gst_avi_demux_index_last (GstAviDemux * avi, GstAviStream * stream)
2154 {
2155   return stream->idx_n - 1;
2156 }
2157
2158 /* find a previous entry in the index with the given flags */
2159 static guint
2160 gst_avi_demux_index_prev (GstAviDemux * avi, GstAviStream * stream,
2161     guint last, gboolean keyframe)
2162 {
2163   GstAviIndexEntry *entry;
2164   guint i;
2165
2166   for (i = last; i > 0; i--) {
2167     entry = &stream->index[i - 1];
2168     if (!keyframe || ENTRY_IS_KEYFRAME (entry)) {
2169       return i - 1;
2170     }
2171   }
2172   return 0;
2173 }
2174
2175 static guint
2176 gst_avi_demux_index_next (GstAviDemux * avi, GstAviStream * stream,
2177     guint last, gboolean keyframe)
2178 {
2179   GstAviIndexEntry *entry;
2180   gint i;
2181
2182   for (i = last + 1; i < stream->idx_n; i++) {
2183     entry = &stream->index[i];
2184     if (!keyframe || ENTRY_IS_KEYFRAME (entry)) {
2185       return i;
2186     }
2187   }
2188   return stream->idx_n - 1;
2189 }
2190
2191 static guint
2192 gst_avi_demux_index_entry_search (GstAviIndexEntry * entry, guint64 * total)
2193 {
2194   if (entry->total < *total)
2195     return -1;
2196   else if (entry->total > *total)
2197     return 1;
2198   return 0;
2199 }
2200
2201 /*
2202  * gst_avi_demux_index_for_time:
2203  * @avi: Avi object
2204  * @stream: the stream
2205  * @time: a time position
2206  *
2207  * Finds the index entry which time is less or equal than the requested time.
2208  * Try to avoid binary search when we can convert the time to an index
2209  * position directly (for example for video frames with a fixed duration).
2210  *
2211  * Returns: the found position in the index.
2212  */
2213 static guint
2214 gst_avi_demux_index_for_time (GstAviDemux * avi,
2215     GstAviStream * stream, guint64 time)
2216 {
2217   guint index = -1;
2218   guint64 total;
2219
2220   GST_LOG_OBJECT (avi, "search time:%" GST_TIME_FORMAT, GST_TIME_ARGS (time));
2221
2222   /* easy (and common) cases */
2223   if (time == 0 || stream->idx_n == 0)
2224     return 0;
2225   if (time >= stream->idx_duration)
2226     return stream->idx_n - 1;
2227
2228   /* figure out where we need to go. For that we convert the time to an
2229    * index entry or we convert it to a total and then do a binary search. */
2230   if (stream->is_vbr) {
2231     /* VBR stream next timestamp */
2232     if (stream->strh->type == GST_RIFF_FCC_auds) {
2233       total = avi_stream_convert_time_to_frames_unchecked (stream, time);
2234     } else {
2235       index = avi_stream_convert_time_to_frames_unchecked (stream, time);
2236     }
2237   } else {
2238     /* constant rate stream */
2239     total = avi_stream_convert_time_to_bytes_unchecked (stream, time);
2240   }
2241
2242   if (index == -1) {
2243     GstAviIndexEntry *entry;
2244
2245     /* no index, find index with binary search on total */
2246     GST_LOG_OBJECT (avi, "binary search for entry with total %"
2247         G_GUINT64_FORMAT, total);
2248
2249     entry = gst_util_array_binary_search (stream->index,
2250         stream->idx_n, sizeof (GstAviIndexEntry),
2251         (GCompareDataFunc) gst_avi_demux_index_entry_search,
2252         GST_SEARCH_MODE_BEFORE, &total, NULL);
2253
2254     if (entry == NULL) {
2255       GST_LOG_OBJECT (avi, "not found, assume index 0");
2256       index = 0;
2257     } else {
2258       index = entry - stream->index;
2259       GST_LOG_OBJECT (avi, "found at %u", index);
2260     }
2261   } else {
2262     GST_LOG_OBJECT (avi, "converted time to index %u", index);
2263   }
2264
2265   return index;
2266 }
2267
2268 static inline GstAviStream *
2269 gst_avi_demux_stream_for_id (GstAviDemux * avi, guint32 id)
2270 {
2271   guint stream_nr;
2272   GstAviStream *stream;
2273
2274   /* get the stream for this entry */
2275   stream_nr = CHUNKID_TO_STREAMNR (id);
2276   if (G_UNLIKELY (stream_nr >= avi->num_streams)) {
2277     GST_WARNING_OBJECT (avi, "invalid stream nr %d", stream_nr);
2278     return NULL;
2279   }
2280   stream = &avi->stream[stream_nr];
2281   if (G_UNLIKELY (!stream->strh)) {
2282     GST_WARNING_OBJECT (avi, "Unhandled stream %d, skipping", stream_nr);
2283     return NULL;
2284   }
2285   return stream;
2286 }
2287
2288 /*
2289  * gst_avi_demux_parse_index:
2290  * @avi: calling element (used for debugging/errors).
2291  * @buf: buffer containing the full index.
2292  *
2293  * Read index entries from the provided buffer.
2294  * The buffer should contain a GST_RIFF_TAG_idx1 chunk.
2295  */
2296 static gboolean
2297 gst_avi_demux_parse_index (GstAviDemux * avi, GstBuffer * buf)
2298 {
2299   guint64 pos_before;
2300   guint8 *data;
2301   guint size;
2302   guint i, num, n;
2303   gst_riff_index_entry *index;
2304   GstClockTime stamp;
2305   GstAviStream *stream;
2306   GstAviIndexEntry entry;
2307   guint32 id;
2308
2309   if (!buf)
2310     return FALSE;
2311
2312   data = GST_BUFFER_DATA (buf);
2313   size = GST_BUFFER_SIZE (buf);
2314
2315   stamp = gst_util_get_timestamp ();
2316
2317   /* see how many items in the index */
2318   num = size / sizeof (gst_riff_index_entry);
2319   if (num == 0)
2320     goto empty_list;
2321
2322   GST_INFO_OBJECT (avi, "Parsing index, nr_entries = %6d", num);
2323
2324   index = (gst_riff_index_entry *) data;
2325   pos_before = avi->offset;
2326
2327   /* figure out if the index is 0 based or relative to the MOVI start */
2328   entry.offset = GST_READ_UINT32_LE (&index[0].offset);
2329   if (entry.offset < avi->offset) {
2330     avi->index_offset = avi->offset + 8;
2331     GST_DEBUG ("index_offset = %" G_GUINT64_FORMAT, avi->index_offset);
2332   } else {
2333     avi->index_offset = 0;
2334     GST_DEBUG ("index is 0 based");
2335   }
2336
2337   for (i = 0, n = 0; i < num; i++) {
2338     id = GST_READ_UINT32_LE (&index[i].id);
2339     entry.offset = GST_READ_UINT32_LE (&index[i].offset);
2340
2341     /* some sanity checks */
2342     if (G_UNLIKELY (id == GST_RIFF_rec || id == 0 ||
2343             (entry.offset == 0 && n > 0)))
2344       continue;
2345
2346     /* get the stream for this entry */
2347     stream = gst_avi_demux_stream_for_id (avi, id);
2348     if (G_UNLIKELY (!stream))
2349       continue;
2350
2351     /* handle offset and size */
2352     entry.offset += avi->index_offset + 8;
2353     entry.size = GST_READ_UINT32_LE (&index[i].size);
2354
2355     /* handle flags */
2356     if (stream->strh->type == GST_RIFF_FCC_auds) {
2357       /* all audio frames are keyframes */
2358       ENTRY_SET_KEYFRAME (&entry);
2359     } else {
2360       guint32 flags;
2361       /* else read flags */
2362       flags = GST_READ_UINT32_LE (&index[i].flags);
2363       if (flags & GST_RIFF_IF_KEYFRAME) {
2364         ENTRY_SET_KEYFRAME (&entry);
2365       } else {
2366         ENTRY_UNSET_KEYFRAME (&entry);
2367       }
2368     }
2369
2370     /* and add */
2371     if (G_UNLIKELY (!gst_avi_demux_add_index (avi, stream, num, &entry)))
2372       goto out_of_mem;
2373
2374     n++;
2375   }
2376   gst_buffer_unref (buf);
2377
2378   /* get stream stats now */
2379   avi->have_index = gst_avi_demux_do_index_stats (avi);
2380
2381   stamp = gst_util_get_timestamp () - stamp;
2382   GST_DEBUG_OBJECT (avi, "parsing index %" GST_TIME_FORMAT,
2383       GST_TIME_ARGS (stamp));
2384
2385   return TRUE;
2386
2387   /* ERRORS */
2388 empty_list:
2389   {
2390     GST_DEBUG_OBJECT (avi, "empty index");
2391     gst_buffer_unref (buf);
2392     return FALSE;
2393   }
2394 out_of_mem:
2395   {
2396     GST_ELEMENT_ERROR (avi, RESOURCE, NO_SPACE_LEFT, (NULL),
2397         ("Cannot allocate memory for %u*%u=%u bytes",
2398             (guint) sizeof (GstAviIndexEntry), num,
2399             (guint) sizeof (GstAviIndexEntry) * num));
2400     gst_buffer_unref (buf);
2401     return FALSE;
2402   }
2403 }
2404
2405 /*
2406  * gst_avi_demux_stream_index:
2407  * @avi: avi demuxer object.
2408  *
2409  * Seeks to index and reads it.
2410  */
2411 static void
2412 gst_avi_demux_stream_index (GstAviDemux * avi)
2413 {
2414   GstFlowReturn res;
2415   guint64 offset = avi->offset;
2416   GstBuffer *buf;
2417   guint32 tag;
2418   guint32 size;
2419
2420   GST_DEBUG ("demux stream index at offset %" G_GUINT64_FORMAT, offset);
2421
2422   /* get chunk information */
2423   res = gst_pad_pull_range (avi->sinkpad, offset, 8, &buf);
2424   if (res != GST_FLOW_OK)
2425     goto pull_failed;
2426   else if (GST_BUFFER_SIZE (buf) < 8)
2427     goto too_small;
2428
2429   /* check tag first before blindy trying to read 'size' bytes */
2430   tag = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf));
2431   size = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf) + 4);
2432   if (tag == GST_RIFF_TAG_LIST) {
2433     /* this is the movi tag */
2434     GST_DEBUG_OBJECT (avi, "skip LIST chunk, size %" G_GUINT32_FORMAT,
2435         (8 + GST_ROUND_UP_2 (size)));
2436     offset += 8 + GST_ROUND_UP_2 (size);
2437     gst_buffer_unref (buf);
2438     res = gst_pad_pull_range (avi->sinkpad, offset, 8, &buf);
2439     if (res != GST_FLOW_OK)
2440       goto pull_failed;
2441     else if (GST_BUFFER_SIZE (buf) < 8)
2442       goto too_small;
2443     tag = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf));
2444     size = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf) + 4);
2445   }
2446
2447   if (tag != GST_RIFF_TAG_idx1)
2448     goto no_index;
2449   if (!size)
2450     goto zero_index;
2451
2452   gst_buffer_unref (buf);
2453
2454   GST_DEBUG ("index found at offset %" G_GUINT64_FORMAT, offset);
2455
2456   /* read chunk, advance offset */
2457   if (gst_riff_read_chunk (GST_ELEMENT_CAST (avi),
2458           avi->sinkpad, &offset, &tag, &buf) != GST_FLOW_OK)
2459     return;
2460
2461   GST_DEBUG ("will parse index chunk size %u for tag %"
2462       GST_FOURCC_FORMAT, GST_BUFFER_SIZE (buf), GST_FOURCC_ARGS (tag));
2463
2464   gst_avi_demux_parse_index (avi, buf);
2465
2466 #ifndef GST_DISABLE_GST_DEBUG
2467   /* debug our indexes */
2468   {
2469     gint i;
2470     GstAviStream *stream;
2471
2472     for (i = 0; i < avi->num_streams; i++) {
2473       stream = &avi->stream[i];
2474       GST_DEBUG_OBJECT (avi, "stream %u: %u frames, %" G_GINT64_FORMAT " bytes",
2475           i, stream->idx_n, stream->total_bytes);
2476     }
2477   }
2478 #endif
2479   return;
2480
2481   /* ERRORS */
2482 pull_failed:
2483   {
2484     GST_DEBUG_OBJECT (avi,
2485         "pull range failed: pos=%" G_GUINT64_FORMAT " size=8", offset);
2486     return;
2487   }
2488 too_small:
2489   {
2490     GST_DEBUG_OBJECT (avi, "Buffer is too small");
2491     gst_buffer_unref (buf);
2492     return;
2493   }
2494 no_index:
2495   {
2496     GST_WARNING_OBJECT (avi,
2497         "No index data (idx1) after movi chunk, but %" GST_FOURCC_FORMAT,
2498         GST_FOURCC_ARGS (tag));
2499     gst_buffer_unref (buf);
2500     return;
2501   }
2502 zero_index:
2503   {
2504     GST_WARNING_OBJECT (avi, "Empty index data (idx1) after movi chunk");
2505     gst_buffer_unref (buf);
2506     return;
2507   }
2508 }
2509
2510 /*
2511  * gst_avi_demux_peek_tag:
2512  *
2513  * Returns the tag and size of the next chunk
2514  */
2515 static GstFlowReturn
2516 gst_avi_demux_peek_tag (GstAviDemux * avi, guint64 offset, guint32 * tag,
2517     guint * size)
2518 {
2519   GstFlowReturn res = GST_FLOW_OK;
2520   GstBuffer *buf = NULL;
2521   guint bufsize;
2522   guint8 *bufdata;
2523
2524   res = gst_pad_pull_range (avi->sinkpad, offset, 8, &buf);
2525   if (res != GST_FLOW_OK)
2526     goto pull_failed;
2527
2528   bufsize = GST_BUFFER_SIZE (buf);
2529   if (bufsize != 8)
2530     goto wrong_size;
2531
2532   bufdata = GST_BUFFER_DATA (buf);
2533
2534   *tag = GST_READ_UINT32_LE (bufdata);
2535   *size = GST_READ_UINT32_LE (bufdata + 4);
2536
2537   GST_LOG_OBJECT (avi, "Tag[%" GST_FOURCC_FORMAT "] (size:%d) %"
2538       G_GINT64_FORMAT " -- %" G_GINT64_FORMAT, GST_FOURCC_ARGS (*tag),
2539       *size, offset + 8, offset + 8 + (gint64) * size);
2540
2541 done:
2542   gst_buffer_unref (buf);
2543
2544   return res;
2545
2546   /* ERRORS */
2547 pull_failed:
2548   {
2549     GST_DEBUG_OBJECT (avi, "pull_ranged returned %s", gst_flow_get_name (res));
2550     return res;
2551   }
2552 wrong_size:
2553   {
2554     GST_DEBUG_OBJECT (avi, "got %d bytes which is <> 8 bytes", bufsize);
2555     res = GST_FLOW_ERROR;
2556     goto done;
2557   }
2558 }
2559
2560 /*
2561  * gst_avi_demux_next_data_buffer:
2562  *
2563  * Returns the offset and size of the next buffer
2564  * Position is the position of the buffer (after tag and size)
2565  */
2566 static GstFlowReturn
2567 gst_avi_demux_next_data_buffer (GstAviDemux * avi, guint64 * offset,
2568     guint32 * tag, guint * size)
2569 {
2570   guint64 off = *offset;
2571   guint _size = 0;
2572   GstFlowReturn res;
2573
2574   do {
2575     res = gst_avi_demux_peek_tag (avi, off, tag, &_size);
2576     if (res != GST_FLOW_OK)
2577       break;
2578     if (*tag == GST_RIFF_TAG_LIST || *tag == GST_RIFF_TAG_RIFF)
2579       off += 8 + 4;             /* skip tag + size + subtag */
2580     else {
2581       *offset = off + 8;
2582       *size = _size;
2583       break;
2584     }
2585   } while (TRUE);
2586
2587   return res;
2588 }
2589
2590 /*
2591  * gst_avi_demux_stream_scan:
2592  * @avi: calling element (used for debugging/errors).
2593  *
2594  * Scan the file for all chunks to "create" a new index.
2595  * pull-range based
2596  */
2597 static gboolean
2598 gst_avi_demux_stream_scan (GstAviDemux * avi)
2599 {
2600   GstFlowReturn res;
2601   GstAviStream *stream;
2602   GstFormat format;
2603   guint64 pos = 0;
2604   guint64 length;
2605   gint64 tmplength;
2606   guint32 tag = 0;
2607   guint num;
2608
2609   /* FIXME:
2610    * - implement non-seekable source support.
2611    */
2612   GST_DEBUG_OBJECT (avi, "Creating index");
2613
2614   /* get the size of the file */
2615   format = GST_FORMAT_BYTES;
2616   if (!gst_pad_query_peer_duration (avi->sinkpad, &format, &tmplength))
2617     return FALSE;
2618   length = tmplength;
2619
2620   /* guess the total amount of entries we expect */
2621   num = 16000;
2622
2623   while (TRUE) {
2624     GstAviIndexEntry entry;
2625     guint size = 0;
2626
2627     /* start reading data buffers to find the id and offset */
2628     res = gst_avi_demux_next_data_buffer (avi, &pos, &tag, &size);
2629     if (G_UNLIKELY (res != GST_FLOW_OK))
2630       break;
2631
2632     /* get stream */
2633     stream = gst_avi_demux_stream_for_id (avi, tag);
2634     if (G_UNLIKELY (!stream))
2635       goto next;
2636
2637     /* we can't figure out the keyframes, assume they all are */
2638     entry.flags = GST_AVI_KEYFRAME;
2639     entry.offset = pos;
2640     entry.size = size;
2641
2642     /* and add to the index of this stream */
2643     if (G_UNLIKELY (!gst_avi_demux_add_index (avi, stream, num, &entry)))
2644       goto out_of_mem;
2645
2646   next:
2647     /* update position */
2648     pos += GST_ROUND_UP_2 (size);
2649     if (G_UNLIKELY (pos > length)) {
2650       GST_WARNING_OBJECT (avi,
2651           "Stopping index lookup since we are further than EOF");
2652       break;
2653     }
2654   }
2655
2656   /* collect stats */
2657   avi->have_index = gst_avi_demux_do_index_stats (avi);
2658
2659
2660   return TRUE;
2661
2662   /* ERRORS */
2663 out_of_mem:
2664   {
2665     GST_ELEMENT_ERROR (avi, RESOURCE, NO_SPACE_LEFT, (NULL),
2666         ("Cannot allocate memory for %u*%u=%u bytes",
2667             (guint) sizeof (GstAviIndexEntry), num,
2668             (guint) sizeof (GstAviIndexEntry) * num));
2669     return FALSE;
2670   }
2671 }
2672
2673 static void
2674 gst_avi_demux_calculate_durations_from_index (GstAviDemux * avi)
2675 {
2676   guint i;
2677   GstClockTime total;
2678   GstAviStream *stream;
2679
2680   total = GST_CLOCK_TIME_NONE;
2681
2682   /* all streams start at a timestamp 0 */
2683   for (i = 0; i < avi->num_streams; i++) {
2684     GstClockTime duration, hduration;
2685     gst_riff_strh *strh;
2686
2687     stream = &avi->stream[i];
2688     if (G_UNLIKELY (!stream || !stream->idx_n || !(strh = stream->strh)))
2689       continue;
2690
2691     /* get header duration for the stream */
2692     hduration = stream->hdr_duration;
2693     /* index duration calculated during parsing */
2694     duration = stream->idx_duration;
2695
2696     /* now pick a good duration */
2697     if (GST_CLOCK_TIME_IS_VALID (duration)) {
2698       /* index gave valid duration, use that */
2699       GST_INFO ("Stream %p duration according to index: %" GST_TIME_FORMAT,
2700           stream, GST_TIME_ARGS (duration));
2701     } else {
2702       /* fall back to header info to calculate a duration */
2703       duration = hduration;
2704     }
2705     GST_INFO ("Setting duration of stream #%d to %" GST_TIME_FORMAT,
2706         i, GST_TIME_ARGS (duration));
2707     /* set duration for the stream */
2708     stream->duration = duration;
2709
2710     /* find total duration */
2711     if (total == GST_CLOCK_TIME_NONE ||
2712         (GST_CLOCK_TIME_IS_VALID (duration) && duration > total))
2713       total = duration;
2714   }
2715
2716   if (GST_CLOCK_TIME_IS_VALID (total) && (total > 0)) {
2717     /* now update the duration for those streams where we had none */
2718     for (i = 0; i < avi->num_streams; i++) {
2719       stream = &avi->stream[i];
2720
2721       if (!GST_CLOCK_TIME_IS_VALID (stream->duration)
2722           || stream->duration == 0) {
2723         stream->duration = total;
2724
2725         GST_INFO ("Stream %p duration according to total: %" GST_TIME_FORMAT,
2726             stream, GST_TIME_ARGS (total));
2727       }
2728     }
2729   }
2730
2731   /* and set the total duration in the segment. */
2732   GST_INFO ("Setting total duration to: %" GST_TIME_FORMAT,
2733       GST_TIME_ARGS (total));
2734
2735   gst_segment_set_duration (&avi->segment, GST_FORMAT_TIME, total);
2736 }
2737
2738 /* returns FALSE if there are no pads to deliver event to,
2739  * otherwise TRUE (whatever the outcome of event sending),
2740  * takes ownership of the event. */
2741 static gboolean
2742 gst_avi_demux_push_event (GstAviDemux * avi, GstEvent * event)
2743 {
2744   gboolean result = FALSE;
2745   gint i;
2746
2747   GST_DEBUG_OBJECT (avi, "sending %s event to %d streams",
2748       GST_EVENT_TYPE_NAME (event), avi->num_streams);
2749
2750   for (i = 0; i < avi->num_streams; i++) {
2751     GstAviStream *stream = &avi->stream[i];
2752
2753     if (stream->pad) {
2754       result = TRUE;
2755       gst_pad_push_event (stream->pad, gst_event_ref (event));
2756     }
2757   }
2758   gst_event_unref (event);
2759   return result;
2760 }
2761
2762 static void
2763 gst_avi_demux_check_seekability (GstAviDemux * avi)
2764 {
2765   GstQuery *query;
2766   gboolean seekable = FALSE;
2767   gint64 start = -1, stop = -1;
2768
2769   query = gst_query_new_seeking (GST_FORMAT_BYTES);
2770   if (!gst_pad_peer_query (avi->sinkpad, query)) {
2771     GST_DEBUG_OBJECT (avi, "seeking query failed");
2772     goto done;
2773   }
2774
2775   gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
2776
2777   /* try harder to query upstream size if we didn't get it the first time */
2778   if (seekable && stop == -1) {
2779     GstFormat fmt = GST_FORMAT_BYTES;
2780
2781     GST_DEBUG_OBJECT (avi, "doing duration query to fix up unset stop");
2782     gst_pad_query_peer_duration (avi->sinkpad, &fmt, &stop);
2783   }
2784
2785   /* if upstream doesn't know the size, it's likely that it's not seekable in
2786    * practice even if it technically may be seekable */
2787   if (seekable && (start != 0 || stop <= start)) {
2788     GST_DEBUG_OBJECT (avi, "seekable but unknown start/stop -> disable");
2789     seekable = FALSE;
2790   }
2791
2792   if (!avi->element_index) {
2793     GST_DEBUG_OBJECT (avi, "no index");
2794     seekable = FALSE;
2795   }
2796
2797 done:
2798   GST_INFO_OBJECT (avi, "seekable: %d (%" G_GUINT64_FORMAT " - %"
2799       G_GUINT64_FORMAT ")", seekable, start, stop);
2800   avi->seekable = seekable;
2801
2802   gst_query_unref (query);
2803 }
2804
2805 /*
2806  * Read AVI headers when streaming
2807  */
2808 static GstFlowReturn
2809 gst_avi_demux_stream_header_push (GstAviDemux * avi)
2810 {
2811   GstFlowReturn ret = GST_FLOW_OK;
2812   guint32 tag = 0;
2813   guint32 ltag = 0;
2814   guint32 size = 0;
2815   const guint8 *data;
2816   GstBuffer *buf = NULL, *sub = NULL;
2817   guint offset = 4;
2818   gint64 stop;
2819
2820   GST_DEBUG ("Reading and parsing avi headers: %d", avi->header_state);
2821
2822   switch (avi->header_state) {
2823     case GST_AVI_DEMUX_HEADER_TAG_LIST:
2824       if (gst_avi_demux_peek_chunk (avi, &tag, &size)) {
2825         avi->offset += 8 + GST_ROUND_UP_2 (size);
2826         if (tag != GST_RIFF_TAG_LIST)
2827           goto header_no_list;
2828
2829         gst_adapter_flush (avi->adapter, 8);
2830         /* Find the 'hdrl' LIST tag */
2831         GST_DEBUG ("Reading %d bytes", size);
2832         buf = gst_adapter_take_buffer (avi->adapter, size);
2833
2834         if (GST_READ_UINT32_LE (GST_BUFFER_DATA (buf)) != GST_RIFF_LIST_hdrl)
2835           goto header_no_hdrl;
2836
2837         /* mind padding */
2838         if (size & 1)
2839           gst_adapter_flush (avi->adapter, 1);
2840
2841         GST_DEBUG ("'hdrl' LIST tag found. Parsing next chunk");
2842
2843         /* the hdrl starts with a 'avih' header */
2844         if (!gst_riff_parse_chunk (GST_ELEMENT (avi), buf, &offset, &tag, &sub))
2845           goto header_no_avih;
2846
2847         if (tag != GST_RIFF_TAG_avih)
2848           goto header_no_avih;
2849
2850         if (!gst_avi_demux_parse_avih (GST_ELEMENT (avi), sub, &avi->avih))
2851           goto header_wrong_avih;
2852
2853         GST_DEBUG_OBJECT (avi, "AVI header ok, reading elemnts from header");
2854
2855         /* now, read the elements from the header until the end */
2856         while (gst_riff_parse_chunk (GST_ELEMENT (avi), buf, &offset, &tag,
2857                 &sub)) {
2858           /* sub can be NULL on empty tags */
2859           if (!sub)
2860             continue;
2861
2862           switch (tag) {
2863             case GST_RIFF_TAG_LIST:
2864               if (GST_BUFFER_SIZE (sub) < 4)
2865                 goto next;
2866
2867               switch (GST_READ_UINT32_LE (GST_BUFFER_DATA (sub))) {
2868                 case GST_RIFF_LIST_strl:
2869                   if (!(gst_avi_demux_parse_stream (avi, sub))) {
2870                     sub = NULL;
2871                     GST_ELEMENT_WARNING (avi, STREAM, DEMUX, (NULL),
2872                         ("failed to parse stream, ignoring"));
2873                     goto next;
2874                   }
2875                   sub = NULL;
2876                   goto next;
2877                 case GST_RIFF_LIST_odml:
2878                   gst_avi_demux_parse_odml (avi, sub);
2879                   sub = NULL;
2880                   break;
2881                 default:
2882                   GST_WARNING_OBJECT (avi,
2883                       "Unknown list %" GST_FOURCC_FORMAT " in AVI header",
2884                       GST_FOURCC_ARGS (GST_READ_UINT32_LE (GST_BUFFER_DATA
2885                               (sub))));
2886                   /* fall-through */
2887                 case GST_RIFF_TAG_JUNK:
2888                   goto next;
2889               }
2890               break;
2891             default:
2892               GST_WARNING_OBJECT (avi,
2893                   "Unknown off %d tag %" GST_FOURCC_FORMAT " in AVI header",
2894                   offset, GST_FOURCC_ARGS (tag));
2895               /* fall-through */
2896             case GST_RIFF_TAG_JUNK:
2897             next:
2898               /* move to next chunk */
2899               if (sub)
2900                 gst_buffer_unref (sub);
2901               sub = NULL;
2902               break;
2903           }
2904         }
2905         gst_buffer_unref (buf);
2906         GST_DEBUG ("elements parsed");
2907
2908         /* check parsed streams */
2909         if (avi->num_streams == 0) {
2910           goto no_streams;
2911         } else if (avi->num_streams != avi->avih->streams) {
2912           GST_WARNING_OBJECT (avi,
2913               "Stream header mentioned %d streams, but %d available",
2914               avi->avih->streams, avi->num_streams);
2915         }
2916         GST_DEBUG ("Get junk and info next");
2917         avi->header_state = GST_AVI_DEMUX_HEADER_INFO;
2918       } else {
2919         /* Need more data */
2920         return ret;
2921       }
2922       /* fall-though */
2923     case GST_AVI_DEMUX_HEADER_INFO:
2924       GST_DEBUG_OBJECT (avi, "skipping junk between header and data ...");
2925       while (TRUE) {
2926         if (gst_adapter_available (avi->adapter) < 12)
2927           return GST_FLOW_OK;
2928
2929         data = gst_adapter_peek (avi->adapter, 12);
2930         tag = GST_READ_UINT32_LE (data);
2931         size = GST_READ_UINT32_LE (data + 4);
2932         ltag = GST_READ_UINT32_LE (data + 8);
2933
2934         if (tag == GST_RIFF_TAG_LIST) {
2935           switch (ltag) {
2936             case GST_RIFF_LIST_movi:
2937               gst_adapter_flush (avi->adapter, 12);
2938               avi->offset += 12;
2939               goto skipping_done;
2940             case GST_RIFF_LIST_INFO:
2941               GST_DEBUG ("Found INFO chunk");
2942               if (gst_avi_demux_peek_chunk (avi, &tag, &size)) {
2943                 GST_DEBUG ("got size %d", size);
2944                 avi->offset += 12;
2945                 gst_adapter_flush (avi->adapter, 12);
2946                 if (size > 4) {
2947                   buf = gst_adapter_take_buffer (avi->adapter, size - 4);
2948                   /* mind padding */
2949                   if (size & 1)
2950                     gst_adapter_flush (avi->adapter, 1);
2951                   gst_riff_parse_info (GST_ELEMENT (avi), buf,
2952                       &avi->globaltags);
2953                   gst_buffer_unref (buf);
2954
2955                   avi->offset += GST_ROUND_UP_2 (size) - 4;
2956                 } else {
2957                   GST_DEBUG ("skipping INFO LIST prefix");
2958                 }
2959               } else {
2960                 /* Need more data */
2961                 return GST_FLOW_OK;
2962               }
2963               break;
2964             default:
2965               if (gst_avi_demux_peek_chunk (avi, &tag, &size)) {
2966                 avi->offset += 8 + GST_ROUND_UP_2 (size);
2967                 gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
2968                 // ??? goto iterate; ???
2969               } else {
2970                 /* Need more data */
2971                 return GST_FLOW_OK;
2972               }
2973               break;
2974           }
2975         } else {
2976           if (gst_avi_demux_peek_chunk (avi, &tag, &size)) {
2977             avi->offset += 8 + GST_ROUND_UP_2 (size);
2978             gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
2979             //goto iterate;
2980           } else {
2981             /* Need more data */
2982             return GST_FLOW_OK;
2983           }
2984         }
2985       }
2986       break;
2987     default:
2988       GST_WARNING ("unhandled header state: %d", avi->header_state);
2989       break;
2990   }
2991 skipping_done:
2992
2993   GST_DEBUG_OBJECT (avi, "skipping done ... (streams=%u, stream[0].indexes=%p)",
2994       avi->num_streams, avi->stream[0].indexes);
2995
2996   GST_DEBUG ("Found movi chunk. Starting to stream data");
2997   avi->state = GST_AVI_DEMUX_MOVI;
2998
2999   /* no indexes in push mode, but it still sets some variables */
3000   gst_avi_demux_calculate_durations_from_index (avi);
3001
3002   gst_avi_demux_expose_streams (avi, TRUE);
3003
3004   /* create initial NEWSEGMENT event */
3005   if ((stop = avi->segment.stop) == GST_CLOCK_TIME_NONE)
3006     stop = avi->segment.duration;
3007
3008   GST_DEBUG_OBJECT (avi, "segment stop %" G_GINT64_FORMAT, stop);
3009
3010   if (avi->seek_event)
3011     gst_event_unref (avi->seek_event);
3012   avi->seek_event = gst_event_new_new_segment_full
3013       (FALSE, avi->segment.rate, avi->segment.applied_rate, GST_FORMAT_TIME,
3014       avi->segment.start, stop, avi->segment.time);
3015
3016   gst_avi_demux_check_seekability (avi);
3017
3018   /* at this point we know all the streams and we can signal the no more
3019    * pads signal */
3020   GST_DEBUG_OBJECT (avi, "signaling no more pads");
3021   gst_element_no_more_pads (GST_ELEMENT (avi));
3022
3023   return GST_FLOW_OK;
3024
3025   /* ERRORS */
3026 no_streams:
3027   {
3028     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("No streams found"));
3029     return GST_FLOW_ERROR;
3030   }
3031 header_no_list:
3032   {
3033     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3034         ("Invalid AVI header (no LIST at start): %"
3035             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3036     return GST_FLOW_ERROR;
3037   }
3038 header_no_hdrl:
3039   {
3040     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3041         ("Invalid AVI header (no hdrl at start): %"
3042             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3043     gst_buffer_unref (buf);
3044     return GST_FLOW_ERROR;
3045   }
3046 header_no_avih:
3047   {
3048     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3049         ("Invalid AVI header (no avih at start): %"
3050             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3051     if (sub)
3052       gst_buffer_unref (sub);
3053
3054     gst_buffer_unref (buf);
3055     return GST_FLOW_ERROR;
3056   }
3057 header_wrong_avih:
3058   {
3059     gst_buffer_unref (buf);
3060     return GST_FLOW_ERROR;
3061   }
3062 }
3063
3064 /*
3065  * Read full AVI headers.
3066  */
3067 static GstFlowReturn
3068 gst_avi_demux_stream_header_pull (GstAviDemux * avi)
3069 {
3070   GstFlowReturn res;
3071   GstBuffer *buf, *sub = NULL;
3072   guint32 tag;
3073   guint offset = 4;
3074   gint64 stop;
3075   GstElement *element = GST_ELEMENT_CAST (avi);
3076   GstClockTime stamp;
3077
3078   stamp = gst_util_get_timestamp ();
3079
3080   /* the header consists of a 'hdrl' LIST tag */
3081   res = gst_riff_read_chunk (element, avi->sinkpad, &avi->offset, &tag, &buf);
3082   if (res != GST_FLOW_OK)
3083     goto pull_range_failed;
3084   else if (tag != GST_RIFF_TAG_LIST)
3085     goto no_list;
3086   else if (GST_BUFFER_SIZE (buf) < 4)
3087     goto no_header;
3088
3089   GST_DEBUG_OBJECT (avi, "parsing headers");
3090
3091   /* Find the 'hdrl' LIST tag */
3092   while (GST_READ_UINT32_LE (GST_BUFFER_DATA (buf)) != GST_RIFF_LIST_hdrl) {
3093     GST_LOG_OBJECT (avi, "buffer contains %" GST_FOURCC_FORMAT,
3094         GST_FOURCC_ARGS (GST_READ_UINT32_LE (GST_BUFFER_DATA (buf))));
3095
3096     /* Eat up */
3097     gst_buffer_unref (buf);
3098
3099     /* read new chunk */
3100     res = gst_riff_read_chunk (element, avi->sinkpad, &avi->offset, &tag, &buf);
3101     if (res != GST_FLOW_OK)
3102       goto pull_range_failed;
3103     else if (tag != GST_RIFF_TAG_LIST)
3104       goto no_list;
3105     else if (GST_BUFFER_SIZE (buf) < 4)
3106       goto no_header;
3107   }
3108
3109   GST_DEBUG_OBJECT (avi, "hdrl LIST tag found");
3110
3111   /* the hdrl starts with a 'avih' header */
3112   if (!gst_riff_parse_chunk (element, buf, &offset, &tag, &sub))
3113     goto no_avih;
3114   else if (tag != GST_RIFF_TAG_avih)
3115     goto no_avih;
3116   else if (!gst_avi_demux_parse_avih (element, sub, &avi->avih))
3117     goto invalid_avih;
3118
3119   GST_DEBUG_OBJECT (avi, "AVI header ok, reading elements from header");
3120
3121   /* now, read the elements from the header until the end */
3122   while (gst_riff_parse_chunk (element, buf, &offset, &tag, &sub)) {
3123     /* sub can be NULL on empty tags */
3124     if (!sub)
3125       continue;
3126
3127     switch (tag) {
3128       case GST_RIFF_TAG_LIST:
3129       {
3130         guint8 *data;
3131         guint32 fourcc;
3132
3133         if (GST_BUFFER_SIZE (sub) < 4)
3134           goto next;
3135
3136         data = GST_BUFFER_DATA (sub);
3137         fourcc = GST_READ_UINT32_LE (data);
3138
3139         switch (fourcc) {
3140           case GST_RIFF_LIST_strl:
3141             if (!(gst_avi_demux_parse_stream (avi, sub))) {
3142               GST_ELEMENT_WARNING (avi, STREAM, DEMUX, (NULL),
3143                   ("failed to parse stream, ignoring"));
3144               sub = NULL;
3145             }
3146             sub = NULL;
3147             goto next;
3148           case GST_RIFF_LIST_odml:
3149             gst_avi_demux_parse_odml (avi, sub);
3150             sub = NULL;
3151             break;
3152           case GST_RIFF_LIST_INFO:
3153             GST_BUFFER_DATA (sub) = data + 4;
3154             GST_BUFFER_SIZE (sub) -= 4;
3155             gst_riff_parse_info (element, sub, &avi->globaltags);
3156             break;
3157           default:
3158             GST_WARNING_OBJECT (avi,
3159                 "Unknown list %" GST_FOURCC_FORMAT " in AVI header",
3160                 GST_FOURCC_ARGS (fourcc));
3161             GST_MEMDUMP_OBJECT (avi, "Unknown list", GST_BUFFER_DATA (sub),
3162                 GST_BUFFER_SIZE (sub));
3163             /* fall-through */
3164           case GST_RIFF_TAG_JUNK:
3165             goto next;
3166         }
3167         break;
3168       }
3169       default:
3170         GST_WARNING_OBJECT (avi,
3171             "Unknown tag %" GST_FOURCC_FORMAT " in AVI header at off %d",
3172             GST_FOURCC_ARGS (tag), offset);
3173         GST_MEMDUMP_OBJECT (avi, "Unknown tag", GST_BUFFER_DATA (sub),
3174             GST_BUFFER_SIZE (sub));
3175         /* fall-through */
3176       case GST_RIFF_TAG_JUNK:
3177       next:
3178         if (sub)
3179           gst_buffer_unref (sub);
3180         sub = NULL;
3181         break;
3182     }
3183   }
3184   gst_buffer_unref (buf);
3185   GST_DEBUG ("elements parsed");
3186
3187   /* check parsed streams */
3188   if (avi->num_streams == 0)
3189     goto no_streams;
3190   else if (avi->num_streams != avi->avih->streams) {
3191     GST_WARNING_OBJECT (avi,
3192         "Stream header mentioned %d streams, but %d available",
3193         avi->avih->streams, avi->num_streams);
3194   }
3195
3196   GST_DEBUG_OBJECT (avi, "skipping junk between header and data, offset=%"
3197       G_GUINT64_FORMAT, avi->offset);
3198
3199   /* Now, find the data (i.e. skip all junk between header and data) */
3200   do {
3201     guint size;
3202     guint8 *data;
3203     guint32 tag, ltag;
3204
3205     res = gst_pad_pull_range (avi->sinkpad, avi->offset, 12, &buf);
3206     if (res != GST_FLOW_OK) {
3207       GST_DEBUG_OBJECT (avi, "pull_range failure while looking for tags");
3208       goto pull_range_failed;
3209     } else if (GST_BUFFER_SIZE (buf) < 12) {
3210       GST_DEBUG_OBJECT (avi, "got %d bytes which is less than 12 bytes",
3211           GST_BUFFER_SIZE (buf));
3212       gst_buffer_unref (buf);
3213       return GST_FLOW_ERROR;
3214     }
3215
3216     data = GST_BUFFER_DATA (buf);
3217
3218     tag = GST_READ_UINT32_LE (data);
3219     size = GST_READ_UINT32_LE (data + 4);
3220     ltag = GST_READ_UINT32_LE (data + 8);
3221
3222     GST_DEBUG ("tag %" GST_FOURCC_FORMAT ", size %u",
3223         GST_FOURCC_ARGS (tag), size);
3224     GST_MEMDUMP ("Tag content", data, GST_BUFFER_SIZE (buf));
3225     gst_buffer_unref (buf);
3226
3227     switch (tag) {
3228       case GST_RIFF_TAG_LIST:{
3229         switch (ltag) {
3230           case GST_RIFF_LIST_movi:
3231             GST_DEBUG_OBJECT (avi,
3232                 "Reached the 'movi' tag, we're done with skipping");
3233             goto skipping_done;
3234           case GST_RIFF_LIST_INFO:
3235             res =
3236                 gst_riff_read_chunk (element, avi->sinkpad, &avi->offset, &tag,
3237                 &buf);
3238             if (res != GST_FLOW_OK) {
3239               GST_DEBUG_OBJECT (avi, "couldn't read INFO chunk");
3240               goto pull_range_failed;
3241             }
3242             GST_DEBUG ("got size %u", GST_BUFFER_SIZE (buf));
3243             if (size < 4) {
3244               GST_DEBUG ("skipping INFO LIST prefix");
3245               avi->offset += (4 - GST_ROUND_UP_2 (size));
3246               gst_buffer_unref (buf);
3247               continue;
3248             }
3249
3250             sub = gst_buffer_create_sub (buf, 4, GST_BUFFER_SIZE (buf) - 4);
3251             gst_riff_parse_info (element, sub, &avi->globaltags);
3252             if (sub) {
3253               gst_buffer_unref (sub);
3254               sub = NULL;
3255             }
3256             gst_buffer_unref (buf);
3257             /* gst_riff_read_chunk() has already advanced avi->offset */
3258             break;
3259           default:
3260             GST_WARNING_OBJECT (avi,
3261                 "Skipping unknown list tag %" GST_FOURCC_FORMAT,
3262                 GST_FOURCC_ARGS (ltag));
3263             avi->offset += 8 + GST_ROUND_UP_2 (size);
3264             break;
3265         }
3266       }
3267         break;
3268       default:
3269         GST_WARNING_OBJECT (avi, "Skipping unknown tag %" GST_FOURCC_FORMAT,
3270             GST_FOURCC_ARGS (tag));
3271         /* Fall-through */
3272       case GST_MAKE_FOURCC ('J', 'U', 'N', 'Q'):
3273       case GST_MAKE_FOURCC ('J', 'U', 'N', 'K'):
3274         /* Only get buffer for debugging if the memdump is needed  */
3275         if (gst_debug_category_get_threshold (GST_CAT_DEFAULT) >= 9) {
3276           res = gst_pad_pull_range (avi->sinkpad, avi->offset, size, &buf);
3277           if (res != GST_FLOW_OK) {
3278             GST_DEBUG_OBJECT (avi, "couldn't read INFO chunk");
3279             goto pull_range_failed;
3280           }
3281           GST_MEMDUMP ("Junk", GST_BUFFER_DATA (buf), GST_BUFFER_SIZE (buf));
3282           gst_buffer_unref (buf);
3283         }
3284         avi->offset += 8 + GST_ROUND_UP_2 (size);
3285         break;
3286     }
3287   } while (1);
3288 skipping_done:
3289
3290   GST_DEBUG_OBJECT (avi, "skipping done ... (streams=%u, stream[0].indexes=%p)",
3291       avi->num_streams, avi->stream[0].indexes);
3292
3293   /* create or read stream index (for seeking) */
3294   if (avi->stream[0].indexes != NULL) {
3295     /* we read a super index already (gst_avi_demux_parse_superindex() ) */
3296     gst_avi_demux_read_subindexes_pull (avi);
3297   }
3298   if (!avi->have_index) {
3299     if (avi->avih->flags & GST_RIFF_AVIH_HASINDEX)
3300       gst_avi_demux_stream_index (avi);
3301
3302     /* still no index, scan */
3303     if (!avi->have_index) {
3304       gst_avi_demux_stream_scan (avi);
3305
3306       /* still no index.. this is a fatal error for now.
3307        * FIXME, we should switch to plain push mode without seeking
3308        * instead of failing. */
3309       if (!avi->have_index)
3310         goto no_index;
3311     }
3312   }
3313   /* use the indexes now to construct nice durations */
3314   gst_avi_demux_calculate_durations_from_index (avi);
3315
3316   gst_avi_demux_expose_streams (avi, FALSE);
3317
3318   /* create initial NEWSEGMENT event */
3319   if ((stop = avi->segment.stop) == GST_CLOCK_TIME_NONE)
3320     stop = avi->segment.duration;
3321
3322   GST_DEBUG_OBJECT (avi, "segment stop %" G_GINT64_FORMAT, stop);
3323
3324   /* do initial seek to the default segment values */
3325   gst_avi_demux_do_seek (avi, &avi->segment);
3326
3327   /* prepare initial segment */
3328   if (avi->seek_event)
3329     gst_event_unref (avi->seek_event);
3330   avi->seek_event = gst_event_new_new_segment_full
3331       (FALSE, avi->segment.rate, avi->segment.applied_rate, GST_FORMAT_TIME,
3332       avi->segment.start, stop, avi->segment.time);
3333
3334   stamp = gst_util_get_timestamp () - stamp;
3335   GST_DEBUG_OBJECT (avi, "pulling header %" GST_TIME_FORMAT,
3336       GST_TIME_ARGS (stamp));
3337
3338   /* at this point we know all the streams and we can signal the no more
3339    * pads signal */
3340   GST_DEBUG_OBJECT (avi, "signaling no more pads");
3341   gst_element_no_more_pads (GST_ELEMENT_CAST (avi));
3342
3343   return GST_FLOW_OK;
3344
3345   /* ERRORS */
3346 no_list:
3347   {
3348     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3349         ("Invalid AVI header (no LIST at start): %"
3350             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3351     gst_buffer_unref (buf);
3352     return GST_FLOW_ERROR;
3353   }
3354 no_header:
3355   {
3356     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3357         ("Invalid AVI header (no hdrl at start): %"
3358             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3359     gst_buffer_unref (buf);
3360     return GST_FLOW_ERROR;
3361   }
3362 no_avih:
3363   {
3364     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3365         ("Invalid AVI header (no avih at start): %"
3366             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3367     if (sub)
3368       gst_buffer_unref (sub);
3369     gst_buffer_unref (buf);
3370     return GST_FLOW_ERROR;
3371   }
3372 invalid_avih:
3373   {
3374     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3375         ("Invalid AVI header (cannot parse avih at start)"));
3376     gst_buffer_unref (buf);
3377     return GST_FLOW_ERROR;
3378   }
3379 no_streams:
3380   {
3381     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("No streams found"));
3382     return GST_FLOW_ERROR;
3383   }
3384 no_index:
3385   {
3386     GST_WARNING ("file without or too big index");
3387     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3388         ("Could not get/create index"));
3389     return GST_FLOW_ERROR;
3390   }
3391 pull_range_failed:
3392   {
3393     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3394         ("pull_range flow reading header: %s", gst_flow_get_name (res)));
3395     return GST_FLOW_ERROR;
3396   }
3397 }
3398
3399 /* move a stream to @index */
3400 static void
3401 gst_avi_demux_move_stream (GstAviDemux * avi, GstAviStream * stream,
3402     GstSegment * segment, guint index)
3403 {
3404   GST_DEBUG_OBJECT (avi, "Move stream %d to %u", stream->num, index);
3405
3406   if (segment->rate < 0.0) {
3407     guint next_key;
3408     /* Because we don't know the frame order we need to push from the prev keyframe
3409      * to the next keyframe. If there is a smart decoder downstream he will notice
3410      * that there are too many encoded frames send and return UNEXPECTED when there
3411      * are enough decoded frames to fill the segment. */
3412     next_key = gst_avi_demux_index_next (avi, stream, index, TRUE);
3413
3414     /* FIXME, we go back to 0, we should look at segment.start. We will however
3415      * stop earlier when the see the timestamp < segment.start */
3416     stream->start_entry = 0;
3417     stream->step_entry = index;
3418     stream->current_entry = index;
3419     stream->stop_entry = next_key;
3420
3421     GST_DEBUG_OBJECT (avi, "reverse seek: start %u, step %u, stop %u",
3422         stream->start_entry, stream->step_entry, stream->stop_entry);
3423   } else {
3424     stream->start_entry = index;
3425     stream->step_entry = index;
3426     stream->stop_entry = gst_avi_demux_index_last (avi, stream);
3427   }
3428   if (stream->current_entry != index) {
3429     GST_DEBUG_OBJECT (avi, "Move DISCONT from %u to %u",
3430         stream->current_entry, index);
3431     stream->current_entry = index;
3432     stream->discont = TRUE;
3433   }
3434
3435   /* update the buffer info */
3436   gst_avi_demux_get_buffer_info (avi, stream, index,
3437       &stream->current_timestamp, &stream->current_ts_end,
3438       &stream->current_offset, &stream->current_offset_end);
3439
3440   GST_DEBUG_OBJECT (avi, "Moved to %u, ts %" GST_TIME_FORMAT
3441       ", ts_end %" GST_TIME_FORMAT ", off %" G_GUINT64_FORMAT
3442       ", off_end %" G_GUINT64_FORMAT, index,
3443       GST_TIME_ARGS (stream->current_timestamp),
3444       GST_TIME_ARGS (stream->current_ts_end), stream->current_offset,
3445       stream->current_offset_end);
3446 }
3447
3448 /*
3449  * Do the actual seeking.
3450  */
3451 static gboolean
3452 gst_avi_demux_do_seek (GstAviDemux * avi, GstSegment * segment)
3453 {
3454   GstClockTime seek_time;
3455   gboolean keyframe;
3456   guint i, index;
3457   GstAviStream *stream;
3458
3459   seek_time = segment->last_stop;
3460   keyframe = !!(segment->flags & GST_SEEK_FLAG_KEY_UNIT);
3461
3462   GST_DEBUG_OBJECT (avi, "seek to: %" GST_TIME_FORMAT
3463       " keyframe seeking:%d", GST_TIME_ARGS (seek_time), keyframe);
3464
3465   /* FIXME, this code assumes the main stream with keyframes is stream 0,
3466    * which is mostly correct... */
3467   stream = &avi->stream[avi->main_stream];
3468
3469   /* get the entry index for the requested position */
3470   index = gst_avi_demux_index_for_time (avi, stream, seek_time);
3471   GST_DEBUG_OBJECT (avi, "Got entry %u", index);
3472
3473   /* check if we are already on a keyframe */
3474   if (!ENTRY_IS_KEYFRAME (&stream->index[index])) {
3475     GST_DEBUG_OBJECT (avi, "not keyframe, searching back");
3476     /* now go to the previous keyframe, this is where we should start
3477      * decoding from. */
3478     index = gst_avi_demux_index_prev (avi, stream, index, TRUE);
3479     GST_DEBUG_OBJECT (avi, "previous keyframe at %u", index);
3480   }
3481
3482   /* move the main stream to this position */
3483   gst_avi_demux_move_stream (avi, stream, segment, index);
3484
3485   if (keyframe) {
3486     /* when seeking to a keyframe, we update the result seek time
3487      * to the time of the keyframe. */
3488     seek_time = stream->current_timestamp;
3489     GST_DEBUG_OBJECT (avi, "keyframe adjusted to %" GST_TIME_FORMAT,
3490         GST_TIME_ARGS (seek_time));
3491   }
3492
3493   /* the seek time is also the last_stop and stream time when going
3494    * forwards */
3495   segment->last_stop = seek_time;
3496   if (segment->rate > 0.0)
3497     segment->time = seek_time;
3498
3499   /* now set DISCONT and align the other streams */
3500   for (i = 0; i < avi->num_streams; i++) {
3501     GstAviStream *ostream;
3502
3503     ostream = &avi->stream[i];
3504     if ((ostream == stream) || (ostream->index == NULL))
3505       continue;
3506
3507     /* get the entry index for the requested position */
3508     index = gst_avi_demux_index_for_time (avi, ostream, seek_time);
3509
3510     /* move to previous keyframe */
3511     if (!ENTRY_IS_KEYFRAME (&ostream->index[index]))
3512       index = gst_avi_demux_index_prev (avi, ostream, index, TRUE);
3513
3514     gst_avi_demux_move_stream (avi, ostream, segment, index);
3515   }
3516   GST_DEBUG_OBJECT (avi, "done seek to: %" GST_TIME_FORMAT,
3517       GST_TIME_ARGS (seek_time));
3518
3519   return TRUE;
3520 }
3521
3522 /*
3523  * Handle seek event.
3524  */
3525 static gboolean
3526 gst_avi_demux_handle_seek (GstAviDemux * avi, GstPad * pad, GstEvent * event)
3527 {
3528   gdouble rate;
3529   GstFormat format;
3530   GstSeekFlags flags;
3531   GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
3532   gint64 cur, stop;
3533   gboolean flush;
3534   gboolean update;
3535   GstSegment seeksegment = { 0, };
3536   gint i;
3537
3538   if (event) {
3539     GST_DEBUG_OBJECT (avi, "doing seek with event");
3540
3541     gst_event_parse_seek (event, &rate, &format, &flags,
3542         &cur_type, &cur, &stop_type, &stop);
3543
3544     /* we have to have a format as the segment format. Try to convert
3545      * if not. */
3546     if (format != GST_FORMAT_TIME) {
3547       GstFormat fmt = GST_FORMAT_TIME;
3548       gboolean res = TRUE;
3549
3550       if (cur_type != GST_SEEK_TYPE_NONE)
3551         res = gst_pad_query_convert (pad, format, cur, &fmt, &cur);
3552       if (res && stop_type != GST_SEEK_TYPE_NONE)
3553         res = gst_pad_query_convert (pad, format, stop, &fmt, &stop);
3554       if (!res)
3555         goto no_format;
3556
3557       format = fmt;
3558     }
3559     GST_DEBUG_OBJECT (avi,
3560         "seek requested: rate %g cur %" GST_TIME_FORMAT " stop %"
3561         GST_TIME_FORMAT, rate, GST_TIME_ARGS (cur), GST_TIME_ARGS (stop));
3562     /* FIXME: can we do anything with rate!=1.0 */
3563   } else {
3564     GST_DEBUG_OBJECT (avi, "doing seek without event");
3565     flags = 0;
3566     rate = 1.0;
3567   }
3568
3569   /* save flush flag */
3570   flush = flags & GST_SEEK_FLAG_FLUSH;
3571
3572   if (flush) {
3573     GstEvent *fevent = gst_event_new_flush_start ();
3574
3575     /* for a flushing seek, we send a flush_start on all pads. This will
3576      * eventually stop streaming with a WRONG_STATE. We can thus eventually
3577      * take the STREAM_LOCK. */
3578     GST_DEBUG_OBJECT (avi, "sending flush start");
3579     gst_avi_demux_push_event (avi, gst_event_ref (fevent));
3580     gst_pad_push_event (avi->sinkpad, fevent);
3581   } else {
3582     /* a non-flushing seek, we PAUSE the task so that we can take the
3583      * STREAM_LOCK */
3584     GST_DEBUG_OBJECT (avi, "non flushing seek, pausing task");
3585     gst_pad_pause_task (avi->sinkpad);
3586   }
3587
3588   /* wait for streaming to stop */
3589   GST_DEBUG_OBJECT (avi, "wait for streaming to stop");
3590   GST_PAD_STREAM_LOCK (avi->sinkpad);
3591
3592   /* copy segment, we need this because we still need the old
3593    * segment when we close the current segment. */
3594   memcpy (&seeksegment, &avi->segment, sizeof (GstSegment));
3595
3596   if (event) {
3597     GST_DEBUG_OBJECT (avi, "configuring seek");
3598     gst_segment_set_seek (&seeksegment, rate, format, flags,
3599         cur_type, cur, stop_type, stop, &update);
3600   }
3601   /* do the seek, seeksegment.last_stop contains the new position, this
3602    * actually never fails. */
3603   gst_avi_demux_do_seek (avi, &seeksegment);
3604
3605   if (flush) {
3606     GstEvent *fevent = gst_event_new_flush_stop ();
3607
3608     GST_DEBUG_OBJECT (avi, "sending flush stop");
3609     gst_avi_demux_push_event (avi, gst_event_ref (fevent));
3610     gst_pad_push_event (avi->sinkpad, fevent);
3611
3612     /* reset the last flow and mark discont, FLUSH is always DISCONT */
3613     for (i = 0; i < avi->num_streams; i++) {
3614       avi->stream[i].last_flow = GST_FLOW_OK;
3615       avi->stream[i].discont = TRUE;
3616     }
3617   } else if (avi->segment_running) {
3618     GstEvent *seg;
3619
3620     /* we are running the current segment and doing a non-flushing seek,
3621      * close the segment first based on the last_stop. */
3622     GST_DEBUG_OBJECT (avi, "closing running segment %" G_GINT64_FORMAT
3623         " to %" G_GINT64_FORMAT, avi->segment.start, avi->segment.last_stop);
3624     seg = gst_event_new_new_segment_full (TRUE,
3625         avi->segment.rate, avi->segment.applied_rate, avi->segment.format,
3626         avi->segment.start, avi->segment.last_stop, avi->segment.time);
3627     gst_avi_demux_push_event (avi, seg);
3628   }
3629
3630   /* now update the real segment info */
3631   memcpy (&avi->segment, &seeksegment, sizeof (GstSegment));
3632
3633   /* post the SEGMENT_START message when we do segmented playback */
3634   if (avi->segment.flags & GST_SEEK_FLAG_SEGMENT) {
3635     gst_element_post_message (GST_ELEMENT (avi),
3636         gst_message_new_segment_start (GST_OBJECT (avi),
3637             avi->segment.format, avi->segment.last_stop));
3638   }
3639
3640   /* prepare for streaming again */
3641   if ((stop = avi->segment.stop) == GST_CLOCK_TIME_NONE)
3642     stop = avi->segment.duration;
3643
3644   /* queue the segment event for the streaming thread. */
3645   if (avi->seek_event)
3646     gst_event_unref (avi->seek_event);
3647   if (avi->segment.rate > 0.0) {
3648     /* forwards goes from last_stop to stop */
3649     avi->seek_event = gst_event_new_new_segment_full (FALSE,
3650         avi->segment.rate, avi->segment.applied_rate, avi->segment.format,
3651         avi->segment.last_stop, stop, avi->segment.time);
3652   } else {
3653     /* reverse goes from start to last_stop */
3654     avi->seek_event = gst_event_new_new_segment_full (FALSE,
3655         avi->segment.rate, avi->segment.applied_rate, avi->segment.format,
3656         avi->segment.start, avi->segment.last_stop, avi->segment.time);
3657   }
3658
3659   if (!avi->streaming) {
3660     avi->segment_running = TRUE;
3661     gst_pad_start_task (avi->sinkpad, (GstTaskFunction) gst_avi_demux_loop,
3662         avi->sinkpad);
3663   }
3664   GST_PAD_STREAM_UNLOCK (avi->sinkpad);
3665
3666   return TRUE;
3667
3668   /* ERRORS */
3669 no_format:
3670   {
3671     GST_DEBUG_OBJECT (avi, "unsupported format given, seek aborted.");
3672     return FALSE;
3673   }
3674 }
3675
3676 static gboolean
3677 gst_avi_demux_handle_seek_push (GstAviDemux * avi, GstPad * pad,
3678     GstEvent * event)
3679 {
3680   gdouble rate;
3681   GstFormat format;
3682   GstSeekFlags flags;
3683   GstSeekType cur_type, stop_type;
3684   gint64 cur, stop;
3685   gboolean res;
3686   gint64 byte_cur;
3687   gint64 time = 0;
3688   GstIndexEntry *entry;
3689
3690   GST_DEBUG_OBJECT (avi, "doing push-based seek");
3691
3692   gst_event_parse_seek (event, &rate, &format, &flags,
3693       &cur_type, &cur, &stop_type, &stop);
3694
3695   if (stop_type != GST_SEEK_TYPE_NONE)
3696     goto unsupported_seek;
3697   stop = -1;
3698
3699   /* only forward streaming and seeking is possible */
3700   if (rate <= 0)
3701     goto unsupported_seek;
3702
3703   /* only TIME */
3704   if (format != GST_FORMAT_TIME)
3705     goto unsupported_format;
3706
3707   /* not really advisable otherwise */
3708   if ((flags & GST_SEEK_FLAG_FLUSH) == 0)
3709     goto unsupported_seek;
3710
3711   /* should have index, let's check anyway */
3712   if (!avi->element_index)
3713     goto abort_seek;
3714
3715   /* find reasonable corresponding BYTE position
3716    * note that we have no keyframe info in push mode whatsoever,
3717    * so we can not cater for related stuff in any way */
3718
3719   /* some slack aiming for a keyframe */
3720   if (cur < GST_AVI_SEEK_PUSH_DISPLACE)
3721     cur = 0;
3722   else
3723     cur -= GST_AVI_SEEK_PUSH_DISPLACE;
3724
3725   entry = gst_index_get_assoc_entry (avi->element_index, avi->index_id,
3726       GST_INDEX_LOOKUP_BEFORE, GST_ASSOCIATION_FLAG_NONE, GST_FORMAT_TIME, cur);
3727
3728   if (!entry)
3729     goto abort_seek;
3730
3731   gst_index_entry_assoc_map (entry, GST_FORMAT_BYTES, &byte_cur);
3732   gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &time);
3733
3734   GST_DEBUG_OBJECT (avi, "found index entry for %" GST_TIME_FORMAT
3735       " at %" GST_TIME_FORMAT ", located at offset %" G_GINT64_FORMAT,
3736       GST_TIME_ARGS (cur), GST_TIME_ARGS (time), byte_cur);
3737
3738   /* adjust offset to be in each stream's region */
3739   byte_cur = gst_avi_demux_seek_streams (avi, byte_cur, TRUE);
3740
3741   /* let's not try push seeking if target and entry are too far apart */
3742   if (cur - time > 30 * GST_SECOND)
3743     goto abort_seek;
3744
3745   GST_DEBUG_OBJECT (avi, "Pushing BYTE seek rate %g, "
3746       "start %" G_GINT64_FORMAT ", stop %" G_GINT64_FORMAT, rate, byte_cur,
3747       stop);
3748   /* BYTE seek event */
3749   event = gst_event_new_seek (rate, GST_FORMAT_BYTES, flags, cur_type, byte_cur,
3750       stop_type, stop);
3751   res = gst_pad_push_event (avi->sinkpad, event);
3752
3753   return res;
3754
3755   /* ERRORS */
3756 abort_seek:
3757   {
3758     GST_DEBUG_OBJECT (avi, "could not determine byte position to seek to, "
3759         "seek aborted.");
3760     return FALSE;
3761   }
3762 unsupported_seek:
3763   {
3764     GST_DEBUG_OBJECT (avi, "unsupported seek, seek aborted.");
3765     return FALSE;
3766   }
3767 unsupported_format:
3768   {
3769     GST_DEBUG_OBJECT (avi, "unsupported format given, seek aborted.");
3770     return FALSE;
3771   }
3772 }
3773
3774 /*
3775  * Helper for gst_avi_demux_invert()
3776  */
3777 static inline void
3778 swap_line (guint8 * d1, guint8 * d2, guint8 * tmp, gint bytes)
3779 {
3780   memcpy (tmp, d1, bytes);
3781   memcpy (d1, d2, bytes);
3782   memcpy (d2, tmp, bytes);
3783 }
3784
3785
3786 #define gst_avi_demux_is_uncompressed(fourcc)           \
3787   (fourcc == GST_RIFF_DIB ||                            \
3788    fourcc == GST_RIFF_rgb ||                            \
3789    fourcc == GST_RIFF_RGB || fourcc == GST_RIFF_RAW)
3790
3791 /*
3792  * Invert DIB buffers... Takes existing buffer and
3793  * returns either the buffer or a new one (with old
3794  * one dereferenced).
3795  * FIXME: can't we preallocate tmp? and remember stride, bpp?
3796  */
3797 static GstBuffer *
3798 gst_avi_demux_invert (GstAviStream * stream, GstBuffer * buf)
3799 {
3800   GstStructure *s;
3801   gint y, w, h;
3802   gint bpp, stride;
3803   guint8 *tmp = NULL;
3804
3805   if (stream->strh->type != GST_RIFF_FCC_vids)
3806     return buf;
3807
3808   if (!gst_avi_demux_is_uncompressed (stream->strh->fcc_handler)) {
3809     return buf;                 /* Ignore non DIB buffers */
3810   }
3811
3812   s = gst_caps_get_structure (GST_PAD_CAPS (stream->pad), 0);
3813   if (!gst_structure_get_int (s, "bpp", &bpp)) {
3814     GST_WARNING ("Failed to retrieve depth from caps");
3815     return buf;
3816   }
3817
3818   if (stream->strf.vids == NULL) {
3819     GST_WARNING ("Failed to retrieve vids for stream");
3820     return buf;
3821   }
3822
3823   h = stream->strf.vids->height;
3824   w = stream->strf.vids->width;
3825   stride = w * (bpp / 8);
3826
3827   buf = gst_buffer_make_writable (buf);
3828   if (GST_BUFFER_SIZE (buf) < (stride * h)) {
3829     GST_WARNING ("Buffer is smaller than reported Width x Height x Depth");
3830     return buf;
3831   }
3832
3833   tmp = g_malloc (stride);
3834
3835   for (y = 0; y < h / 2; y++) {
3836     swap_line (GST_BUFFER_DATA (buf) + stride * y,
3837         GST_BUFFER_DATA (buf) + stride * (h - 1 - y), tmp, stride);
3838   }
3839
3840   g_free (tmp);
3841
3842   return buf;
3843 }
3844
3845 static void
3846 gst_avi_demux_add_assoc (GstAviDemux * avi, GstAviStream * stream,
3847     GstClockTime timestamp, guint64 offset, gboolean keyframe)
3848 {
3849   /* do not add indefinitely for open-ended streaming */
3850   if (G_UNLIKELY (avi->element_index && avi->seekable)) {
3851     GST_LOG_OBJECT (avi, "adding association %" GST_TIME_FORMAT "-> %"
3852         G_GUINT64_FORMAT, GST_TIME_ARGS (timestamp), offset);
3853     gst_index_add_association (avi->element_index, avi->index_id,
3854         keyframe ? GST_ASSOCIATION_FLAG_KEY_UNIT : GST_ASSOCIATION_FLAG_NONE,
3855         GST_FORMAT_TIME, timestamp, GST_FORMAT_BYTES, offset, NULL);
3856     /* well, current_total determines TIME and entry DEFAULT (frame #) ... */
3857     gst_index_add_association (avi->element_index, stream->index_id,
3858         GST_ASSOCIATION_FLAG_NONE,
3859         GST_FORMAT_TIME, stream->current_total, GST_FORMAT_BYTES, offset,
3860         GST_FORMAT_DEFAULT, stream->current_entry, NULL);
3861   }
3862 }
3863
3864 /*
3865  * Returns the aggregated GstFlowReturn.
3866  */
3867 static GstFlowReturn
3868 gst_avi_demux_combine_flows (GstAviDemux * avi, GstAviStream * stream,
3869     GstFlowReturn ret)
3870 {
3871   guint i;
3872   gboolean unexpected = FALSE, not_linked = TRUE;
3873
3874   /* store the value */
3875   stream->last_flow = ret;
3876
3877   /* any other error that is not-linked or eos can be returned right away */
3878   if (G_LIKELY (ret != GST_FLOW_UNEXPECTED && ret != GST_FLOW_NOT_LINKED))
3879     goto done;
3880
3881   /* only return NOT_LINKED if all other pads returned NOT_LINKED */
3882   for (i = 0; i < avi->num_streams; i++) {
3883     GstAviStream *ostream = &avi->stream[i];
3884
3885     ret = ostream->last_flow;
3886     /* no unexpected or unlinked, return */
3887     if (G_LIKELY (ret != GST_FLOW_UNEXPECTED && ret != GST_FLOW_NOT_LINKED))
3888       goto done;
3889
3890     /* we check to see if we have at least 1 unexpected or all unlinked */
3891     unexpected |= (ret == GST_FLOW_UNEXPECTED);
3892     not_linked &= (ret == GST_FLOW_NOT_LINKED);
3893   }
3894   /* when we get here, we all have unlinked or unexpected */
3895   if (not_linked)
3896     ret = GST_FLOW_NOT_LINKED;
3897   else if (unexpected)
3898     ret = GST_FLOW_UNEXPECTED;
3899 done:
3900   GST_LOG_OBJECT (avi, "combined %s to return %s",
3901       gst_flow_get_name (stream->last_flow), gst_flow_get_name (ret));
3902   return ret;
3903 }
3904
3905 /* move @stream to the next position in its index */
3906 static GstFlowReturn
3907 gst_avi_demux_advance (GstAviDemux * avi, GstAviStream * stream,
3908     GstFlowReturn ret)
3909 {
3910   guint old_entry, new_entry;
3911
3912   old_entry = stream->current_entry;
3913   /* move forwards */
3914   new_entry = old_entry + 1;
3915
3916   /* see if we reached the end */
3917   if (new_entry > stream->stop_entry) {
3918     if (avi->segment.rate < 0.0) {
3919       if (stream->step_entry == stream->start_entry) {
3920         /* we stepped all the way to the start, eos */
3921         GST_DEBUG_OBJECT (avi, "reverse reached start %u", stream->start_entry);
3922         goto eos;
3923       }
3924       /* backwards, stop becomes step, find a new step */
3925       stream->stop_entry = stream->step_entry;
3926       stream->step_entry = gst_avi_demux_index_prev (avi, stream,
3927           stream->stop_entry, TRUE);
3928
3929       GST_DEBUG_OBJECT (avi,
3930           "reverse playback jump: start %u, step %u, stop %u",
3931           stream->start_entry, stream->step_entry, stream->stop_entry);
3932
3933       /* and start from the previous keyframe now */
3934       new_entry = stream->step_entry;
3935     } else {
3936       /* EOS */
3937       GST_DEBUG_OBJECT (avi, "forward reached stop %u", stream->stop_entry);
3938       goto eos;
3939     }
3940   }
3941
3942   if (new_entry != old_entry) {
3943     stream->current_entry = new_entry;
3944     stream->current_total = stream->index[new_entry].total;
3945
3946     if (new_entry == old_entry + 1) {
3947       GST_DEBUG_OBJECT (avi, "moved forwards from %u to %u",
3948           old_entry, new_entry);
3949       /* we simply moved one step forwards, reuse current info */
3950       stream->current_timestamp = stream->current_ts_end;
3951       stream->current_offset = stream->current_offset_end;
3952       gst_avi_demux_get_buffer_info (avi, stream, new_entry,
3953           NULL, &stream->current_ts_end, NULL, &stream->current_offset_end);
3954     } else {
3955       /* we moved DISCONT, full update */
3956       gst_avi_demux_get_buffer_info (avi, stream, new_entry,
3957           &stream->current_timestamp, &stream->current_ts_end,
3958           &stream->current_offset, &stream->current_offset_end);
3959       /* and MARK discont for this stream */
3960       stream->last_flow = GST_FLOW_OK;
3961       stream->discont = TRUE;
3962       GST_DEBUG_OBJECT (avi, "Moved from %u to %u, ts %" GST_TIME_FORMAT
3963           ", ts_end %" GST_TIME_FORMAT ", off %" G_GUINT64_FORMAT
3964           ", off_end %" G_GUINT64_FORMAT, old_entry, new_entry,
3965           GST_TIME_ARGS (stream->current_timestamp),
3966           GST_TIME_ARGS (stream->current_ts_end), stream->current_offset,
3967           stream->current_offset_end);
3968     }
3969   }
3970   return ret;
3971
3972   /* ERROR */
3973 eos:
3974   {
3975     GST_DEBUG_OBJECT (avi, "we are EOS");
3976     /* setting current_timestamp to -1 marks EOS */
3977     stream->current_timestamp = -1;
3978     return GST_FLOW_UNEXPECTED;
3979   }
3980 }
3981
3982 /* find the stream with the lowest current position when going forwards or with
3983  * the highest position when going backwards, this is the stream
3984  * we should push from next */
3985 static gint
3986 gst_avi_demux_find_next (GstAviDemux * avi, gfloat rate)
3987 {
3988   guint64 min_time, max_time;
3989   guint stream_num, i;
3990
3991   max_time = 0;
3992   min_time = G_MAXUINT64;
3993   stream_num = -1;
3994
3995   for (i = 0; i < avi->num_streams; i++) {
3996     guint64 position;
3997     GstAviStream *stream;
3998
3999     stream = &avi->stream[i];
4000     position = stream->current_timestamp;
4001
4002     /* position of -1 is EOS */
4003     if (position != -1) {
4004       if (rate > 0.0 && position < min_time) {
4005         min_time = position;
4006         stream_num = i;
4007       } else if (rate < 0.0 && position >= max_time) {
4008         max_time = position;
4009         stream_num = i;
4010       }
4011     }
4012   }
4013   return stream_num;
4014 }
4015
4016 static GstFlowReturn
4017 gst_avi_demux_loop_data (GstAviDemux * avi)
4018 {
4019   GstFlowReturn ret = GST_FLOW_OK;
4020   guint stream_num;
4021   GstAviStream *stream;
4022   gboolean processed = FALSE;
4023   GstBuffer *buf;
4024   guint64 offset, size;
4025   GstClockTime timestamp, duration;
4026   guint64 out_offset, out_offset_end;
4027   gboolean keyframe;
4028   GstAviIndexEntry *entry;
4029
4030   do {
4031     stream_num = gst_avi_demux_find_next (avi, avi->segment.rate);
4032
4033     /* all are EOS */
4034     if (G_UNLIKELY (stream_num == -1)) {
4035       GST_DEBUG_OBJECT (avi, "all streams are EOS");
4036       goto eos;
4037     }
4038
4039     /* we have the stream now */
4040     stream = &avi->stream[stream_num];
4041
4042     /* skip streams without pads */
4043     if (!stream->pad) {
4044       GST_DEBUG_OBJECT (avi, "skipping entry from stream %d without pad",
4045           stream_num);
4046       goto next;
4047     }
4048
4049     /* get the timing info for the entry */
4050     timestamp = stream->current_timestamp;
4051     duration = stream->current_ts_end - timestamp;
4052     out_offset = stream->current_offset;
4053     out_offset_end = stream->current_offset_end;
4054
4055     /* get the entry data info */
4056     entry = &stream->index[stream->current_entry];
4057     offset = entry->offset;
4058     size = entry->size;
4059     keyframe = ENTRY_IS_KEYFRAME (entry);
4060
4061     /* skip empty entries */
4062     if (size == 0) {
4063       GST_DEBUG_OBJECT (avi, "Skipping entry %u (%" G_GUINT64_FORMAT ", %p)",
4064           stream->current_entry, size, stream->pad);
4065       goto next;
4066     }
4067
4068     if (avi->segment.rate > 0.0) {
4069       /* only check this for fowards playback for now */
4070       if (keyframe && GST_CLOCK_TIME_IS_VALID (avi->segment.stop)
4071           && (timestamp > avi->segment.stop)) {
4072         goto eos_stop;
4073       }
4074     }
4075
4076     GST_LOG ("reading buffer (size=%" G_GUINT64_FORMAT "), stream %d, pos %"
4077         G_GUINT64_FORMAT " (0x%" G_GINT64_MODIFIER "x), kf %d", size,
4078         stream_num, offset, offset, keyframe);
4079
4080     /* FIXME, check large chunks and cut them up */
4081
4082     /* pull in the data */
4083     ret = gst_pad_pull_range (avi->sinkpad, offset, size, &buf);
4084     if (ret != GST_FLOW_OK)
4085       goto pull_failed;
4086
4087     /* check for short buffers, this is EOS as well */
4088     if (GST_BUFFER_SIZE (buf) < size)
4089       goto short_buffer;
4090
4091     /* invert the picture if needed */
4092     buf = gst_avi_demux_invert (stream, buf);
4093
4094     /* mark non-keyframes */
4095     if (keyframe)
4096       GST_BUFFER_FLAG_UNSET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
4097     else
4098       GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
4099
4100     GST_BUFFER_TIMESTAMP (buf) = timestamp;
4101     GST_BUFFER_DURATION (buf) = duration;
4102     GST_BUFFER_OFFSET (buf) = out_offset;
4103     GST_BUFFER_OFFSET_END (buf) = out_offset_end;
4104
4105     /* mark discont when pending */
4106     if (stream->discont) {
4107       GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
4108       stream->discont = FALSE;
4109     }
4110
4111     gst_avi_demux_add_assoc (avi, stream, timestamp, offset, keyframe);
4112
4113     gst_buffer_set_caps (buf, GST_PAD_CAPS (stream->pad));
4114
4115     /* update current position in the segment */
4116     gst_segment_set_last_stop (&avi->segment, GST_FORMAT_TIME, timestamp);
4117
4118     GST_DEBUG_OBJECT (avi, "Pushing buffer of size %u, ts %"
4119         GST_TIME_FORMAT ", dur %" GST_TIME_FORMAT ", off %" G_GUINT64_FORMAT
4120         ", off_end %" G_GUINT64_FORMAT,
4121         GST_BUFFER_SIZE (buf), GST_TIME_ARGS (timestamp),
4122         GST_TIME_ARGS (duration), out_offset, out_offset_end);
4123
4124     ret = gst_pad_push (stream->pad, buf);
4125
4126     /* mark as processed, we increment the frame and byte counters then
4127      * leave the while loop and return the GstFlowReturn */
4128     processed = TRUE;
4129
4130     if (avi->segment.rate < 0) {
4131       if (timestamp > avi->segment.stop && ret == GST_FLOW_UNEXPECTED) {
4132         /* In reverse playback we can get a GST_FLOW_UNEXPECTED when
4133          * we are at the end of the segment, so we just need to jump
4134          * back to the previous section. */
4135         GST_DEBUG_OBJECT (avi, "downstream has reached end of segment");
4136         ret = GST_FLOW_OK;
4137       }
4138     }
4139   next:
4140     /* move to next item */
4141     ret = gst_avi_demux_advance (avi, stream, ret);
4142
4143     /* combine flows */
4144     ret = gst_avi_demux_combine_flows (avi, stream, ret);
4145   } while (!processed);
4146
4147 beach:
4148   return ret;
4149
4150   /* special cases */
4151 eos:
4152   {
4153     GST_DEBUG_OBJECT (avi, "No samples left for any streams - EOS");
4154     ret = GST_FLOW_UNEXPECTED;
4155     goto beach;
4156   }
4157 eos_stop:
4158   {
4159     GST_LOG_OBJECT (avi, "Found keyframe after segment,"
4160         " setting EOS (%" GST_TIME_FORMAT " > %" GST_TIME_FORMAT ")",
4161         GST_TIME_ARGS (timestamp), GST_TIME_ARGS (avi->segment.stop));
4162     ret = GST_FLOW_UNEXPECTED;
4163     goto beach;
4164   }
4165 pull_failed:
4166   {
4167     GST_DEBUG_OBJECT (avi, "pull range failed: pos=%" G_GUINT64_FORMAT
4168         " size=%" G_GUINT64_FORMAT, offset, size);
4169     goto beach;
4170   }
4171 short_buffer:
4172   {
4173     GST_WARNING_OBJECT (avi, "Short read at offset %" G_GUINT64_FORMAT
4174         ", only got %d/%" G_GUINT64_FORMAT " bytes (truncated file?)", offset,
4175         GST_BUFFER_SIZE (buf), size);
4176     gst_buffer_unref (buf);
4177     ret = GST_FLOW_UNEXPECTED;
4178     goto beach;
4179   }
4180 }
4181
4182 /*
4183  * Read data. If we have an index it delegates to
4184  * gst_avi_demux_process_next_entry().
4185  */
4186 static GstFlowReturn
4187 gst_avi_demux_stream_data (GstAviDemux * avi)
4188 {
4189   guint32 tag = 0;
4190   guint32 size = 0;
4191   gint stream_nr = 0;
4192   GstFlowReturn res = GST_FLOW_OK;
4193   GstFormat format = GST_FORMAT_TIME;
4194
4195   if (G_UNLIKELY (avi->have_eos)) {
4196     /* Clean adapter, we're done */
4197     gst_adapter_clear (avi->adapter);
4198     return GST_FLOW_UNEXPECTED;
4199   }
4200
4201   if (G_UNLIKELY (avi->todrop)) {
4202     guint drop;
4203
4204     if ((drop = gst_adapter_available (avi->adapter))) {
4205       if (drop > avi->todrop)
4206         drop = avi->todrop;
4207       GST_DEBUG_OBJECT (avi, "Dropping %d bytes", drop);
4208       gst_adapter_flush (avi->adapter, drop);
4209       avi->todrop -= drop;
4210       avi->offset += drop;
4211     }
4212   }
4213
4214   /* Iterate until need more data, so adapter won't grow too much */
4215   while (1) {
4216     if (G_UNLIKELY (!gst_avi_demux_peek_chunk_info (avi, &tag, &size))) {
4217       return GST_FLOW_OK;
4218     }
4219
4220     GST_DEBUG ("Trying chunk (%" GST_FOURCC_FORMAT "), size %d",
4221         GST_FOURCC_ARGS (tag), size);
4222
4223     if (G_LIKELY ((tag & 0xff) >= '0' && (tag & 0xff) <= '9' &&
4224             ((tag >> 8) & 0xff) >= '0' && ((tag >> 8) & 0xff) <= '9')) {
4225       GST_LOG ("Chunk ok");
4226     } else if ((tag & 0xffff) == (('x' << 8) | 'i')) {
4227       GST_DEBUG ("Found sub-index tag");
4228       if (gst_avi_demux_peek_chunk (avi, &tag, &size) || size == 0) {
4229         /* accept 0 size buffer here */
4230         avi->abort_buffering = FALSE;
4231         GST_DEBUG ("  skipping %d bytes for now", size);
4232         gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
4233       }
4234       return GST_FLOW_OK;
4235     } else if (tag == GST_RIFF_TAG_idx1) {
4236       GST_DEBUG ("Found index tag, stream done");
4237       avi->have_eos = TRUE;
4238       return GST_FLOW_UNEXPECTED;
4239     } else if (tag == GST_RIFF_TAG_LIST) {
4240       /* movi chunks might be grouped in rec list */
4241       if (gst_adapter_available (avi->adapter) >= 12) {
4242         GST_DEBUG ("Found LIST tag, skipping LIST header");
4243         gst_adapter_flush (avi->adapter, 12);
4244         continue;
4245       }
4246       return GST_FLOW_OK;
4247     } else if (tag == GST_RIFF_TAG_JUNK) {
4248       /* rec list might contain JUNK chunks */
4249       GST_DEBUG ("Found JUNK tag");
4250       if (gst_avi_demux_peek_chunk (avi, &tag, &size) || size == 0) {
4251         /* accept 0 size buffer here */
4252         avi->abort_buffering = FALSE;
4253         GST_DEBUG ("  skipping %d bytes for now", size);
4254         gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
4255       }
4256       return GST_FLOW_OK;
4257     } else {
4258       GST_DEBUG ("No more stream chunks, send EOS");
4259       avi->have_eos = TRUE;
4260       return GST_FLOW_UNEXPECTED;
4261     }
4262
4263     if (G_UNLIKELY (!gst_avi_demux_peek_chunk (avi, &tag, &size))) {
4264       /* supposedly one hopes to catch a nicer chunk later on ... */
4265       /* FIXME ?? give up here rather than possibly ending up going
4266        * through the whole file */
4267       if (avi->abort_buffering) {
4268         avi->abort_buffering = FALSE;
4269         gst_adapter_flush (avi->adapter, 8);
4270       }
4271       return GST_FLOW_OK;
4272     }
4273     GST_DEBUG ("chunk ID %" GST_FOURCC_FORMAT ", size %u",
4274         GST_FOURCC_ARGS (tag), size);
4275
4276     stream_nr = CHUNKID_TO_STREAMNR (tag);
4277
4278     if (G_UNLIKELY (stream_nr < 0 || stream_nr >= avi->num_streams)) {
4279       /* recoverable */
4280       GST_WARNING ("Invalid stream ID %d (%" GST_FOURCC_FORMAT ")",
4281           stream_nr, GST_FOURCC_ARGS (tag));
4282       avi->offset += 8 + GST_ROUND_UP_2 (size);
4283       gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
4284     } else {
4285       GstAviStream *stream;
4286       GstClockTime next_ts = 0;
4287       GstBuffer *buf;
4288       guint64 offset;
4289
4290       gst_adapter_flush (avi->adapter, 8);
4291
4292       /* get buffer */
4293       buf = gst_adapter_take_buffer (avi->adapter, GST_ROUND_UP_2 (size));
4294       /* patch the size */
4295       GST_BUFFER_SIZE (buf) = size;
4296       offset = avi->offset;
4297       avi->offset += 8 + GST_ROUND_UP_2 (size);
4298
4299       stream = &avi->stream[stream_nr];
4300
4301       /* set delay (if any)
4302          if (stream->strh->init_frames == stream->current_frame &&
4303          stream->delay == 0)
4304          stream->delay = next_ts;
4305        */
4306
4307       /* parsing of corresponding header may have failed */
4308       if (G_UNLIKELY (!stream->pad)) {
4309         GST_WARNING_OBJECT (avi, "no pad for stream ID %" GST_FOURCC_FORMAT,
4310             GST_FOURCC_ARGS (tag));
4311         gst_buffer_unref (buf);
4312       } else {
4313         GstClockTime dur_ts = 0;
4314
4315         /* get time of this buffer */
4316         gst_pad_query_position (stream->pad, &format, (gint64 *) & next_ts);
4317         if (G_UNLIKELY (format != GST_FORMAT_TIME))
4318           goto wrong_format;
4319
4320         gst_avi_demux_add_assoc (avi, stream, next_ts, offset, FALSE);
4321
4322         /* increment our positions */
4323         stream->current_entry++;
4324         stream->current_total += size;
4325
4326         /* invert the picture if needed */
4327         buf = gst_avi_demux_invert (stream, buf);
4328
4329         gst_pad_query_position (stream->pad, &format, (gint64 *) & dur_ts);
4330         if (G_UNLIKELY (format != GST_FORMAT_TIME))
4331           goto wrong_format;
4332
4333         GST_BUFFER_TIMESTAMP (buf) = next_ts;
4334         GST_BUFFER_DURATION (buf) = dur_ts - next_ts;
4335         if (stream->strh->type == GST_RIFF_FCC_vids) {
4336           GST_BUFFER_OFFSET (buf) = stream->current_entry - 1;
4337           GST_BUFFER_OFFSET_END (buf) = stream->current_entry;
4338         } else {
4339           GST_BUFFER_OFFSET (buf) = GST_BUFFER_OFFSET_NONE;
4340           GST_BUFFER_OFFSET_END (buf) = GST_BUFFER_OFFSET_NONE;
4341         }
4342
4343         gst_buffer_set_caps (buf, GST_PAD_CAPS (stream->pad));
4344         GST_DEBUG_OBJECT (avi,
4345             "Pushing buffer with time=%" GST_TIME_FORMAT ", duration %"
4346             GST_TIME_FORMAT ", offset %" G_GUINT64_FORMAT
4347             " and size %d over pad %s", GST_TIME_ARGS (next_ts),
4348             GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)), GST_BUFFER_OFFSET (buf),
4349             size, GST_PAD_NAME (stream->pad));
4350
4351         /* update current position in the segment */
4352         gst_segment_set_last_stop (&avi->segment, GST_FORMAT_TIME, next_ts);
4353
4354         /* mark discont when pending */
4355         if (G_UNLIKELY (stream->discont)) {
4356           GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
4357           stream->discont = FALSE;
4358         }
4359         res = gst_pad_push (stream->pad, buf);
4360
4361         /* combine flows */
4362         res = gst_avi_demux_combine_flows (avi, stream, res);
4363         if (G_UNLIKELY (res != GST_FLOW_OK)) {
4364           GST_DEBUG ("Push failed; %s", gst_flow_get_name (res));
4365           return res;
4366         }
4367       }
4368     }
4369   }
4370
4371 done:
4372   return res;
4373
4374   /* ERRORS */
4375 wrong_format:
4376   {
4377     GST_DEBUG_OBJECT (avi, "format %s != GST_FORMAT_TIME",
4378         gst_format_get_name (format));
4379     res = GST_FLOW_ERROR;
4380     goto done;
4381   }
4382 }
4383
4384 /*
4385  * Send pending tags.
4386  */
4387 static void
4388 push_tag_lists (GstAviDemux * avi)
4389 {
4390   guint i;
4391   GstTagList *tags;
4392
4393   if (!avi->got_tags)
4394     return;
4395
4396   GST_DEBUG_OBJECT (avi, "Pushing pending tag lists");
4397
4398   for (i = 0; i < avi->num_streams; i++) {
4399     GstAviStream *stream = &avi->stream[i];
4400     GstPad *pad = stream->pad;
4401
4402     tags = stream->taglist;
4403
4404     if (pad && tags) {
4405       GST_DEBUG_OBJECT (pad, "Tags: %" GST_PTR_FORMAT, tags);
4406
4407       gst_element_found_tags_for_pad (GST_ELEMENT_CAST (avi), pad, tags);
4408       stream->taglist = NULL;
4409     }
4410   }
4411
4412   if (!(tags = avi->globaltags))
4413     tags = gst_tag_list_new ();
4414
4415   gst_tag_list_add (tags, GST_TAG_MERGE_REPLACE,
4416       GST_TAG_CONTAINER_FORMAT, "AVI", NULL);
4417
4418   GST_DEBUG_OBJECT (avi, "Global tags: %" GST_PTR_FORMAT, tags);
4419   gst_element_found_tags (GST_ELEMENT_CAST (avi), tags);
4420   avi->globaltags = NULL;
4421   avi->got_tags = FALSE;
4422 }
4423
4424 static void
4425 gst_avi_demux_loop (GstPad * pad)
4426 {
4427   GstFlowReturn res;
4428   GstAviDemux *avi = GST_AVI_DEMUX (GST_PAD_PARENT (pad));
4429
4430   switch (avi->state) {
4431     case GST_AVI_DEMUX_START:
4432       res = gst_avi_demux_stream_init_pull (avi);
4433       if (G_UNLIKELY (res != GST_FLOW_OK)) {
4434         GST_WARNING ("stream_init flow: %s", gst_flow_get_name (res));
4435         goto pause;
4436       }
4437       avi->state = GST_AVI_DEMUX_HEADER;
4438       /* fall-through */
4439     case GST_AVI_DEMUX_HEADER:
4440       res = gst_avi_demux_stream_header_pull (avi);
4441       if (G_UNLIKELY (res != GST_FLOW_OK)) {
4442         GST_WARNING ("stream_header flow: %s", gst_flow_get_name (res));
4443         goto pause;
4444       }
4445       avi->state = GST_AVI_DEMUX_MOVI;
4446       break;
4447     case GST_AVI_DEMUX_MOVI:
4448       if (G_UNLIKELY (avi->seek_event)) {
4449         gst_avi_demux_push_event (avi, avi->seek_event);
4450         avi->seek_event = NULL;
4451       }
4452       if (G_UNLIKELY (avi->got_tags)) {
4453         push_tag_lists (avi);
4454       }
4455       /* process each index entry in turn */
4456       res = gst_avi_demux_loop_data (avi);
4457
4458       /* pause when error */
4459       if (G_UNLIKELY (res != GST_FLOW_OK)) {
4460         GST_INFO ("stream_movi flow: %s", gst_flow_get_name (res));
4461         goto pause;
4462       }
4463       break;
4464     default:
4465       GST_ERROR_OBJECT (avi, "unknown state %d", avi->state);
4466       res = GST_FLOW_ERROR;
4467       goto pause;
4468   }
4469
4470   return;
4471
4472   /* ERRORS */
4473 pause:
4474   GST_LOG_OBJECT (avi, "pausing task, reason %s", gst_flow_get_name (res));
4475   avi->segment_running = FALSE;
4476   gst_pad_pause_task (avi->sinkpad);
4477
4478   if (GST_FLOW_IS_FATAL (res) || (res == GST_FLOW_NOT_LINKED)) {
4479     gboolean push_eos = TRUE;
4480
4481     if (res == GST_FLOW_UNEXPECTED) {
4482       /* handle end-of-stream/segment */
4483       if (avi->segment.flags & GST_SEEK_FLAG_SEGMENT) {
4484         gint64 stop;
4485
4486         if ((stop = avi->segment.stop) == -1)
4487           stop = avi->segment.duration;
4488
4489         GST_INFO_OBJECT (avi, "sending segment_done");
4490
4491         gst_element_post_message
4492             (GST_ELEMENT (avi),
4493             gst_message_new_segment_done (GST_OBJECT (avi), GST_FORMAT_TIME,
4494                 stop));
4495         push_eos = FALSE;
4496       }
4497     } else {
4498       /* for fatal errors we post an error message */
4499       GST_ELEMENT_ERROR (avi, STREAM, FAILED,
4500           (_("Internal data stream error.")),
4501           ("streaming stopped, reason %s", gst_flow_get_name (res)));
4502     }
4503     if (push_eos) {
4504       GST_INFO_OBJECT (avi, "sending eos");
4505       if (!gst_avi_demux_push_event (avi, gst_event_new_eos ()) &&
4506           (res == GST_FLOW_UNEXPECTED)) {
4507         GST_ELEMENT_ERROR (avi, STREAM, DEMUX,
4508             (NULL), ("got eos but no streams (yet)"));
4509       }
4510     }
4511   }
4512 }
4513
4514
4515 static GstFlowReturn
4516 gst_avi_demux_chain (GstPad * pad, GstBuffer * buf)
4517 {
4518   GstFlowReturn res;
4519   GstAviDemux *avi = GST_AVI_DEMUX (GST_PAD_PARENT (pad));
4520
4521   GST_DEBUG ("Store %d bytes in adapter", GST_BUFFER_SIZE (buf));
4522   gst_adapter_push (avi->adapter, buf);
4523
4524   switch (avi->state) {
4525     case GST_AVI_DEMUX_START:
4526       if ((res = gst_avi_demux_stream_init_push (avi)) != GST_FLOW_OK) {
4527         GST_WARNING ("stream_init flow: %s", gst_flow_get_name (res));
4528         break;
4529       }
4530       break;
4531     case GST_AVI_DEMUX_HEADER:
4532       if ((res = gst_avi_demux_stream_header_push (avi)) != GST_FLOW_OK) {
4533         GST_WARNING ("stream_header flow: %s", gst_flow_get_name (res));
4534         break;
4535       }
4536       break;
4537     case GST_AVI_DEMUX_MOVI:
4538       if (G_UNLIKELY (avi->seek_event)) {
4539         gst_avi_demux_push_event (avi, avi->seek_event);
4540         avi->seek_event = NULL;
4541       }
4542       if (G_UNLIKELY (avi->got_tags)) {
4543         push_tag_lists (avi);
4544       }
4545       res = gst_avi_demux_stream_data (avi);
4546       break;
4547     default:
4548       GST_ELEMENT_ERROR (avi, STREAM, FAILED, (NULL),
4549           ("Illegal internal state"));
4550       res = GST_FLOW_ERROR;
4551       break;
4552   }
4553
4554   GST_DEBUG_OBJECT (avi, "state: %d res:%s", avi->state,
4555       gst_flow_get_name (res));
4556
4557   if (G_UNLIKELY (avi->abort_buffering)) {
4558     avi->abort_buffering = FALSE;
4559     res = GST_FLOW_ERROR;
4560     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("unhandled buffer size"));
4561   }
4562
4563   return res;
4564 }
4565
4566 static gboolean
4567 gst_avi_demux_sink_activate (GstPad * sinkpad)
4568 {
4569   if (gst_pad_check_pull_range (sinkpad)) {
4570     GST_DEBUG ("going to pull mode");
4571     return gst_pad_activate_pull (sinkpad, TRUE);
4572   } else {
4573     GST_DEBUG ("going to push (streaming) mode");
4574     return gst_pad_activate_push (sinkpad, TRUE);
4575   }
4576 }
4577
4578 static gboolean
4579 gst_avi_demux_sink_activate_pull (GstPad * sinkpad, gboolean active)
4580 {
4581   GstAviDemux *avi = GST_AVI_DEMUX (GST_OBJECT_PARENT (sinkpad));
4582
4583   if (active) {
4584     avi->segment_running = TRUE;
4585     avi->streaming = FALSE;
4586     return gst_pad_start_task (sinkpad, (GstTaskFunction) gst_avi_demux_loop,
4587         sinkpad);
4588   } else {
4589     avi->segment_running = FALSE;
4590     return gst_pad_stop_task (sinkpad);
4591   }
4592 }
4593
4594 static gboolean
4595 gst_avi_demux_activate_push (GstPad * pad, gboolean active)
4596 {
4597   GstAviDemux *avi = GST_AVI_DEMUX (GST_OBJECT_PARENT (pad));
4598
4599   if (active) {
4600     GST_DEBUG ("avi: activating push/chain function");
4601     avi->streaming = TRUE;
4602 #if 0
4603     /* create index for some push based seeking if not provided */
4604     GST_OBJECT_LOCK (avi);
4605     if (!avi->element_index) {
4606       GST_DEBUG_OBJECT (avi, "creating index");
4607       avi->element_index = gst_index_factory_make ("memindex");
4608     }
4609     GST_OBJECT_UNLOCK (avi);
4610     /* object lock might be taken again */
4611     gst_index_get_writer_id (avi->element_index, GST_OBJECT (avi),
4612         &avi->index_id);
4613 #endif
4614   } else {
4615     GST_DEBUG ("avi: deactivating push/chain function");
4616   }
4617
4618   return TRUE;
4619 }
4620
4621 static void
4622 gst_avi_demux_set_index (GstElement * element, GstIndex * index)
4623 {
4624   GstAviDemux *avi = GST_AVI_DEMUX (element);
4625
4626   GST_OBJECT_LOCK (avi);
4627   if (avi->element_index)
4628     gst_object_unref (avi->element_index);
4629   if (index) {
4630     avi->element_index = gst_object_ref (index);
4631   } else {
4632     avi->element_index = NULL;
4633   }
4634   GST_OBJECT_UNLOCK (avi);
4635   /* object lock might be taken again */
4636   if (index)
4637     gst_index_get_writer_id (index, GST_OBJECT (element), &avi->index_id);
4638   GST_DEBUG_OBJECT (avi, "Set index %" GST_PTR_FORMAT, avi->element_index);
4639 }
4640
4641 static GstIndex *
4642 gst_avi_demux_get_index (GstElement * element)
4643 {
4644   GstIndex *result = NULL;
4645   GstAviDemux *avi = GST_AVI_DEMUX (element);
4646
4647   GST_OBJECT_LOCK (avi);
4648   if (avi->element_index)
4649     result = gst_object_ref (avi->element_index);
4650   GST_OBJECT_UNLOCK (avi);
4651
4652   GST_DEBUG_OBJECT (avi, "Returning index %" GST_PTR_FORMAT, result);
4653
4654   return result;
4655 }
4656
4657 static GstStateChangeReturn
4658 gst_avi_demux_change_state (GstElement * element, GstStateChange transition)
4659 {
4660   GstStateChangeReturn ret;
4661   GstAviDemux *avi = GST_AVI_DEMUX (element);
4662
4663   switch (transition) {
4664     case GST_STATE_CHANGE_READY_TO_PAUSED:
4665       avi->streaming = FALSE;
4666       gst_segment_init (&avi->segment, GST_FORMAT_TIME);
4667       break;
4668     default:
4669       break;
4670   }
4671
4672   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
4673   if (ret == GST_STATE_CHANGE_FAILURE)
4674     goto done;
4675
4676   switch (transition) {
4677     case GST_STATE_CHANGE_PAUSED_TO_READY:
4678       gst_avi_demux_reset (avi);
4679       break;
4680     default:
4681       break;
4682   }
4683
4684 done:
4685   return ret;
4686 }