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