834af76cb4d0e4fc4629742e1325d12e519f7d0d
[platform/upstream/gst-plugins-good.git] / gst / avi / gstavidemux.c
1 /* GStreamer
2  * Copyright (C) <1999> Erik Walthinsen <omega@temple-baptist.com>
3  * Copyright (C) <2006> Nokia Corporation (contact <stefan.kost@nokia.com>)
4  * Copyright (C) <2009-2010> STEricsson <benjamin.gaignard@stericsson.com>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
19  * Boston, MA 02110-1301, USA.
20  */
21 /* Element-Checklist-Version: 5 */
22
23 /**
24  * SECTION:element-avidemux
25  *
26  * Demuxes an .avi file into raw or compressed audio and/or video streams.
27  *
28  * This element supports both push and pull-based scheduling, depending on the
29  * capabilities of the upstream elements.
30  *
31  * <refsect2>
32  * <title>Example launch line</title>
33  * |[
34  * gst-launch-1.0 filesrc location=test.avi ! avidemux name=demux  demux.audio_00 ! decodebin ! audioconvert ! audioresample ! autoaudiosink   demux.video_00 ! queue ! decodebin ! videoconvert ! videoscale ! autovideosink
35  * ]| Play (parse and decode) an .avi file and try to output it to
36  * an automatically detected soundcard and videosink. If the AVI file contains
37  * compressed audio or video data, this will only work if you have the
38  * right decoder elements/plugins installed.
39  * </refsect2>
40  */
41
42 #ifdef HAVE_CONFIG_H
43 #include "config.h"
44 #endif
45
46 #include <string.h>
47 #include <stdio.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 #include <gst/tag/tag.h>
55
56 #define DIV_ROUND_UP(s,v) (((s) + ((v)-1)) / (v))
57
58 #define GST_AVI_KEYFRAME (1 << 0)
59 #define ENTRY_IS_KEYFRAME(e) ((e)->flags == GST_AVI_KEYFRAME)
60 #define ENTRY_SET_KEYFRAME(e) ((e)->flags = GST_AVI_KEYFRAME)
61 #define ENTRY_UNSET_KEYFRAME(e) ((e)->flags = 0)
62
63
64 GST_DEBUG_CATEGORY_STATIC (avidemux_debug);
65 #define GST_CAT_DEFAULT avidemux_debug
66
67 static GstStaticPadTemplate sink_templ = GST_STATIC_PAD_TEMPLATE ("sink",
68     GST_PAD_SINK,
69     GST_PAD_ALWAYS,
70     GST_STATIC_CAPS ("video/x-msvideo")
71     );
72
73 #ifndef GST_DISABLE_GST_DEBUG
74 static const char *const snap_types[2][2] = {
75   {"any", "after"},
76   {"before", "nearest"},
77 };
78 #endif
79
80 static void gst_avi_demux_finalize (GObject * object);
81
82 static void gst_avi_demux_reset (GstAviDemux * avi);
83
84 #if 0
85 static const GstEventMask *gst_avi_demux_get_event_mask (GstPad * pad);
86 #endif
87 static gboolean gst_avi_demux_handle_src_event (GstPad * pad,
88     GstObject * parent, GstEvent * event);
89 static gboolean gst_avi_demux_handle_sink_event (GstPad * pad,
90     GstObject * parent, GstEvent * event);
91 static gboolean gst_avi_demux_push_event (GstAviDemux * avi, GstEvent * event);
92
93 #if 0
94 static const GstFormat *gst_avi_demux_get_src_formats (GstPad * pad);
95 #endif
96 static gboolean gst_avi_demux_handle_src_query (GstPad * pad,
97     GstObject * parent, GstQuery * query);
98 static gboolean gst_avi_demux_src_convert (GstPad * pad, GstFormat src_format,
99     gint64 src_value, GstFormat * dest_format, gint64 * dest_value);
100
101 static gboolean gst_avi_demux_do_seek (GstAviDemux * avi, GstSegment * segment,
102     GstSeekFlags flags);
103 static gboolean gst_avi_demux_handle_seek (GstAviDemux * avi, GstPad * pad,
104     GstEvent * event);
105 static gboolean gst_avi_demux_handle_seek_push (GstAviDemux * avi, GstPad * pad,
106     GstEvent * event);
107 static void gst_avi_demux_loop (GstPad * pad);
108 static gboolean gst_avi_demux_sink_activate (GstPad * sinkpad,
109     GstObject * parent);
110 static gboolean gst_avi_demux_sink_activate_mode (GstPad * sinkpad,
111     GstObject * parent, GstPadMode mode, gboolean active);
112 static GstFlowReturn gst_avi_demux_chain (GstPad * pad, GstObject * parent,
113     GstBuffer * buf);
114 #if 0
115 static void gst_avi_demux_set_index (GstElement * element, GstIndex * index);
116 static GstIndex *gst_avi_demux_get_index (GstElement * element);
117 #endif
118 static GstStateChangeReturn gst_avi_demux_change_state (GstElement * element,
119     GstStateChange transition);
120 static void gst_avi_demux_calculate_durations_from_index (GstAviDemux * avi);
121 static void gst_avi_demux_get_buffer_info (GstAviDemux * avi,
122     GstAviStream * stream, guint entry_n, GstClockTime * timestamp,
123     GstClockTime * ts_end, guint64 * offset, guint64 * offset_end);
124
125 static void gst_avi_demux_parse_idit (GstAviDemux * avi, GstBuffer * buf);
126 static void gst_avi_demux_parse_strd (GstAviDemux * avi, GstBuffer * buf);
127
128 static void parse_tag_value (GstAviDemux * avi, GstTagList * taglist,
129     const gchar * type, guint8 * ptr, guint tsize);
130
131 /* GObject methods */
132
133 #define gst_avi_demux_parent_class parent_class
134 G_DEFINE_TYPE (GstAviDemux, gst_avi_demux, GST_TYPE_ELEMENT);
135
136 static void
137 gst_avi_demux_class_init (GstAviDemuxClass * klass)
138 {
139   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
140   GObjectClass *gobject_class = (GObjectClass *) klass;
141   GstPadTemplate *videosrctempl, *audiosrctempl, *subsrctempl, *subpicsrctempl;
142   GstCaps *audcaps, *vidcaps, *subcaps, *subpiccaps;
143
144   GST_DEBUG_CATEGORY_INIT (avidemux_debug, "avidemux",
145       0, "Demuxer for AVI streams");
146
147   gobject_class->finalize = gst_avi_demux_finalize;
148
149   gstelement_class->change_state =
150       GST_DEBUG_FUNCPTR (gst_avi_demux_change_state);
151 #if 0
152   gstelement_class->set_index = GST_DEBUG_FUNCPTR (gst_avi_demux_set_index);
153   gstelement_class->get_index = GST_DEBUG_FUNCPTR (gst_avi_demux_get_index);
154 #endif
155
156   audcaps = gst_riff_create_audio_template_caps ();
157   gst_caps_append (audcaps, gst_caps_new_empty_simple ("audio/x-avi-unknown"));
158   audiosrctempl = gst_pad_template_new ("audio_%u",
159       GST_PAD_SRC, GST_PAD_SOMETIMES, audcaps);
160
161   vidcaps = gst_riff_create_video_template_caps ();
162   gst_caps_append (vidcaps, gst_riff_create_iavs_template_caps ());
163   gst_caps_append (vidcaps, gst_caps_new_empty_simple ("video/x-avi-unknown"));
164   videosrctempl = gst_pad_template_new ("video_%u",
165       GST_PAD_SRC, GST_PAD_SOMETIMES, vidcaps);
166
167   subcaps = gst_caps_new_empty_simple ("application/x-subtitle-avi");
168   subsrctempl = gst_pad_template_new ("subtitle_%u",
169       GST_PAD_SRC, GST_PAD_SOMETIMES, subcaps);
170   subpiccaps = gst_caps_new_empty_simple ("subpicture/x-xsub");
171   subpicsrctempl = gst_pad_template_new ("subpicture_%u",
172       GST_PAD_SRC, GST_PAD_SOMETIMES, subpiccaps);
173   gst_element_class_add_pad_template (gstelement_class, audiosrctempl);
174   gst_element_class_add_pad_template (gstelement_class, videosrctempl);
175   gst_element_class_add_pad_template (gstelement_class, subsrctempl);
176   gst_element_class_add_pad_template (gstelement_class, subpicsrctempl);
177   gst_element_class_add_static_pad_template (gstelement_class, &sink_templ);
178
179   gst_caps_unref (audcaps);
180   gst_caps_unref (vidcaps);
181   gst_caps_unref (subcaps);
182   gst_caps_unref (subpiccaps);
183
184   gst_element_class_set_static_metadata (gstelement_class, "Avi demuxer",
185       "Codec/Demuxer",
186       "Demultiplex an avi file into audio and video",
187       "Erik Walthinsen <omega@cse.ogi.edu>, "
188       "Wim Taymans <wim.taymans@chello.be>, "
189       "Thijs Vermeir <thijsvermeir@gmail.com>");
190 }
191
192 static void
193 gst_avi_demux_init (GstAviDemux * avi)
194 {
195   avi->sinkpad = gst_pad_new_from_static_template (&sink_templ, "sink");
196   gst_pad_set_activate_function (avi->sinkpad,
197       GST_DEBUG_FUNCPTR (gst_avi_demux_sink_activate));
198   gst_pad_set_activatemode_function (avi->sinkpad,
199       GST_DEBUG_FUNCPTR (gst_avi_demux_sink_activate_mode));
200   gst_pad_set_chain_function (avi->sinkpad,
201       GST_DEBUG_FUNCPTR (gst_avi_demux_chain));
202   gst_pad_set_event_function (avi->sinkpad,
203       GST_DEBUG_FUNCPTR (gst_avi_demux_handle_sink_event));
204   gst_element_add_pad (GST_ELEMENT_CAST (avi), avi->sinkpad);
205
206   avi->adapter = gst_adapter_new ();
207   avi->flowcombiner = gst_flow_combiner_new ();
208
209   gst_avi_demux_reset (avi);
210
211   GST_OBJECT_FLAG_SET (avi, GST_ELEMENT_FLAG_INDEXABLE);
212 }
213
214 static void
215 gst_avi_demux_finalize (GObject * object)
216 {
217   GstAviDemux *avi = GST_AVI_DEMUX (object);
218
219   GST_DEBUG ("AVI: finalize");
220
221   g_object_unref (avi->adapter);
222   gst_flow_combiner_free (avi->flowcombiner);
223
224   G_OBJECT_CLASS (parent_class)->finalize (object);
225 }
226
227 static void
228 gst_avi_demux_reset_stream (GstAviDemux * avi, GstAviStream * stream)
229 {
230   g_free (stream->strh);
231   g_free (stream->strf.data);
232   g_free (stream->name);
233   g_free (stream->index);
234   g_free (stream->indexes);
235   if (stream->initdata)
236     gst_buffer_unref (stream->initdata);
237   if (stream->extradata)
238     gst_buffer_unref (stream->extradata);
239   if (stream->rgb8_palette)
240     gst_buffer_unref (stream->rgb8_palette);
241   if (stream->pad) {
242     if (stream->exposed) {
243       gst_pad_set_active (stream->pad, FALSE);
244       gst_element_remove_pad (GST_ELEMENT_CAST (avi), stream->pad);
245       gst_flow_combiner_remove_pad (avi->flowcombiner, stream->pad);
246     } else
247       gst_object_unref (stream->pad);
248   }
249   if (stream->taglist) {
250     gst_tag_list_unref (stream->taglist);
251     stream->taglist = NULL;
252   }
253   memset (stream, 0, sizeof (GstAviStream));
254 }
255
256 static void
257 gst_avi_demux_reset (GstAviDemux * avi)
258 {
259   gint i;
260
261   GST_DEBUG ("AVI: reset");
262
263   for (i = 0; i < avi->num_streams; i++)
264     gst_avi_demux_reset_stream (avi, &avi->stream[i]);
265
266   avi->header_state = GST_AVI_DEMUX_HEADER_TAG_LIST;
267   avi->num_streams = 0;
268   avi->num_v_streams = 0;
269   avi->num_a_streams = 0;
270   avi->num_t_streams = 0;
271   avi->num_sp_streams = 0;
272   avi->main_stream = -1;
273
274   avi->have_group_id = FALSE;
275   avi->group_id = G_MAXUINT;
276
277   avi->state = GST_AVI_DEMUX_START;
278   avi->offset = 0;
279   avi->building_index = FALSE;
280
281   avi->index_offset = 0;
282   g_free (avi->avih);
283   avi->avih = NULL;
284
285 #if 0
286   if (avi->element_index)
287     gst_object_unref (avi->element_index);
288   avi->element_index = NULL;
289 #endif
290
291   if (avi->seg_event) {
292     gst_event_unref (avi->seg_event);
293     avi->seg_event = NULL;
294   }
295   if (avi->seek_event) {
296     gst_event_unref (avi->seek_event);
297     avi->seek_event = NULL;
298   }
299
300   if (avi->globaltags)
301     gst_tag_list_unref (avi->globaltags);
302   avi->globaltags = NULL;
303
304   avi->got_tags = TRUE;         /* we always want to push global tags */
305   avi->have_eos = FALSE;
306   avi->seekable = TRUE;
307
308   gst_adapter_clear (avi->adapter);
309
310   gst_segment_init (&avi->segment, GST_FORMAT_TIME);
311   avi->segment_seqnum = 0;
312 }
313
314
315 /* GstElement methods */
316
317 #if 0
318 static const GstFormat *
319 gst_avi_demux_get_src_formats (GstPad * pad)
320 {
321   GstAviStream *stream = gst_pad_get_element_private (pad);
322
323   static const GstFormat src_a_formats[] = {
324     GST_FORMAT_TIME,
325     GST_FORMAT_BYTES,
326     GST_FORMAT_DEFAULT,
327     0
328   };
329   static const GstFormat src_v_formats[] = {
330     GST_FORMAT_TIME,
331     GST_FORMAT_DEFAULT,
332     0
333   };
334
335   return (stream->strh->type == GST_RIFF_FCC_auds ?
336       src_a_formats : src_v_formats);
337 }
338 #endif
339
340 /* assumes stream->strf.auds->av_bps != 0 */
341 static inline GstClockTime
342 avi_stream_convert_bytes_to_time_unchecked (GstAviStream * stream,
343     guint64 bytes)
344 {
345   return gst_util_uint64_scale_int (bytes, GST_SECOND,
346       stream->strf.auds->av_bps);
347 }
348
349 static inline guint64
350 avi_stream_convert_time_to_bytes_unchecked (GstAviStream * stream,
351     GstClockTime time)
352 {
353   return gst_util_uint64_scale_int (time, stream->strf.auds->av_bps,
354       GST_SECOND);
355 }
356
357 /* assumes stream->strh->rate != 0 */
358 static inline GstClockTime
359 avi_stream_convert_frames_to_time_unchecked (GstAviStream * stream,
360     guint64 frames)
361 {
362   return gst_util_uint64_scale (frames, stream->strh->scale * GST_SECOND,
363       stream->strh->rate);
364 }
365
366 static inline guint64
367 avi_stream_convert_time_to_frames_unchecked (GstAviStream * stream,
368     GstClockTime time)
369 {
370   return gst_util_uint64_scale (time, stream->strh->rate,
371       stream->strh->scale * GST_SECOND);
372 }
373
374 static gboolean
375 gst_avi_demux_src_convert (GstPad * pad,
376     GstFormat src_format,
377     gint64 src_value, GstFormat * dest_format, gint64 * dest_value)
378 {
379   GstAviStream *stream = gst_pad_get_element_private (pad);
380   gboolean res = TRUE;
381
382   GST_LOG_OBJECT (pad,
383       "Received  src_format:%s, src_value:%" G_GUINT64_FORMAT
384       ", dest_format:%s", gst_format_get_name (src_format), src_value,
385       gst_format_get_name (*dest_format));
386
387   if (G_UNLIKELY (src_format == *dest_format)) {
388     *dest_value = src_value;
389     goto done;
390   }
391   if (G_UNLIKELY (!stream->strh || !stream->strf.data)) {
392     res = FALSE;
393     goto done;
394   }
395   if (G_UNLIKELY (stream->strh->type == GST_RIFF_FCC_vids &&
396           (src_format == GST_FORMAT_BYTES
397               || *dest_format == GST_FORMAT_BYTES))) {
398     res = FALSE;
399     goto done;
400   }
401
402   switch (src_format) {
403     case GST_FORMAT_TIME:
404       switch (*dest_format) {
405         case GST_FORMAT_BYTES:
406           *dest_value = gst_util_uint64_scale_int (src_value,
407               stream->strf.auds->av_bps, GST_SECOND);
408           break;
409         case GST_FORMAT_DEFAULT:
410           *dest_value =
411               gst_util_uint64_scale_round (src_value, stream->strh->rate,
412               stream->strh->scale * GST_SECOND);
413           break;
414         default:
415           res = FALSE;
416           break;
417       }
418       break;
419     case GST_FORMAT_BYTES:
420       switch (*dest_format) {
421         case GST_FORMAT_TIME:
422           if (stream->strf.auds->av_bps != 0) {
423             *dest_value = avi_stream_convert_bytes_to_time_unchecked (stream,
424                 src_value);
425           } else
426             res = FALSE;
427           break;
428         default:
429           res = FALSE;
430           break;
431       }
432       break;
433     case GST_FORMAT_DEFAULT:
434       switch (*dest_format) {
435         case GST_FORMAT_TIME:
436           *dest_value =
437               avi_stream_convert_frames_to_time_unchecked (stream, src_value);
438           break;
439         default:
440           res = FALSE;
441           break;
442       }
443       break;
444     default:
445       res = FALSE;
446   }
447
448 done:
449   GST_LOG_OBJECT (pad,
450       "Returning res:%d dest_format:%s dest_value:%" G_GUINT64_FORMAT, res,
451       gst_format_get_name (*dest_format), *dest_value);
452   return res;
453 }
454
455 static gboolean
456 gst_avi_demux_handle_src_query (GstPad * pad, GstObject * parent,
457     GstQuery * query)
458 {
459   gboolean res = TRUE;
460   GstAviDemux *avi = GST_AVI_DEMUX (parent);
461
462   GstAviStream *stream = gst_pad_get_element_private (pad);
463
464   if (!stream->strh || !stream->strf.data)
465     return gst_pad_query_default (pad, parent, query);
466
467   switch (GST_QUERY_TYPE (query)) {
468     case GST_QUERY_POSITION:{
469       gint64 pos = 0;
470
471       GST_DEBUG ("pos query for stream %u: frames %u, bytes %u",
472           stream->num, stream->current_entry, stream->current_total);
473
474       /* FIXME, this looks clumsy */
475       if (stream->strh->type == GST_RIFF_FCC_auds) {
476         if (stream->is_vbr) {
477           /* VBR */
478           pos = avi_stream_convert_frames_to_time_unchecked (stream,
479               stream->current_entry);
480           GST_DEBUG_OBJECT (avi, "VBR convert frame %u, time %"
481               GST_TIME_FORMAT, stream->current_entry, GST_TIME_ARGS (pos));
482         } else if (stream->strf.auds->av_bps != 0) {
483           /* CBR */
484           pos = avi_stream_convert_bytes_to_time_unchecked (stream,
485               stream->current_total);
486           GST_DEBUG_OBJECT (avi,
487               "CBR convert bytes %u, time %" GST_TIME_FORMAT,
488               stream->current_total, GST_TIME_ARGS (pos));
489         } else if (stream->idx_n != 0 && stream->total_bytes != 0) {
490           /* calculate timestamps based on percentage of length */
491           guint64 xlen = avi->avih->us_frame *
492               avi->avih->tot_frames * GST_USECOND;
493
494           pos = gst_util_uint64_scale (xlen, stream->current_total,
495               stream->total_bytes);
496           GST_DEBUG_OBJECT (avi,
497               "CBR perc convert bytes %u, time %" GST_TIME_FORMAT,
498               stream->current_total, GST_TIME_ARGS (pos));
499         } else {
500           /* we don't know */
501           res = FALSE;
502         }
503       } else {
504         if (stream->strh->rate != 0) {
505           pos = gst_util_uint64_scale ((guint64) stream->current_entry *
506               stream->strh->scale, GST_SECOND, (guint64) stream->strh->rate);
507         } else {
508           pos = stream->current_entry * avi->avih->us_frame * GST_USECOND;
509         }
510       }
511       if (res) {
512         GST_DEBUG ("pos query : %" GST_TIME_FORMAT, GST_TIME_ARGS (pos));
513         gst_query_set_position (query, GST_FORMAT_TIME, pos);
514       } else
515         GST_WARNING ("pos query failed");
516       break;
517     }
518     case GST_QUERY_DURATION:
519     {
520       GstFormat fmt;
521       GstClockTime duration;
522
523       /* only act on audio or video streams */
524       if (stream->strh->type != GST_RIFF_FCC_auds &&
525           stream->strh->type != GST_RIFF_FCC_vids &&
526           stream->strh->type != GST_RIFF_FCC_iavs) {
527         res = FALSE;
528         break;
529       }
530
531       /* take stream duration, fall back to avih duration */
532       if ((duration = stream->duration) == -1)
533         if ((duration = stream->hdr_duration) == -1)
534           duration = avi->duration;
535
536       gst_query_parse_duration (query, &fmt, NULL);
537
538       switch (fmt) {
539         case GST_FORMAT_TIME:
540           gst_query_set_duration (query, fmt, duration);
541           break;
542         case GST_FORMAT_DEFAULT:
543         {
544           gint64 dur;
545           GST_DEBUG_OBJECT (query, "total frames is %" G_GUINT32_FORMAT,
546               stream->idx_n);
547
548           if (stream->idx_n > 0)
549             gst_query_set_duration (query, fmt, stream->idx_n);
550           else if (gst_pad_query_convert (pad, GST_FORMAT_TIME,
551                   duration, fmt, &dur))
552             gst_query_set_duration (query, fmt, dur);
553           break;
554         }
555         default:
556           res = FALSE;
557           break;
558       }
559       break;
560     }
561     case GST_QUERY_SEEKING:{
562       GstFormat fmt;
563
564       gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
565       if (fmt == GST_FORMAT_TIME) {
566         gboolean seekable = TRUE;
567
568         if (avi->streaming) {
569           seekable = avi->seekable;
570         }
571
572         gst_query_set_seeking (query, GST_FORMAT_TIME, seekable,
573             0, stream->duration);
574         res = TRUE;
575       }
576       break;
577     }
578     case GST_QUERY_CONVERT:{
579       GstFormat src_fmt, dest_fmt;
580       gint64 src_val, dest_val;
581
582       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
583       if ((res = gst_avi_demux_src_convert (pad, src_fmt, src_val, &dest_fmt,
584                   &dest_val)))
585         gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
586       else
587         res = gst_pad_query_default (pad, parent, query);
588       break;
589     }
590     case GST_QUERY_SEGMENT:
591     {
592       GstFormat format;
593       gint64 start, stop;
594
595       format = avi->segment.format;
596
597       start =
598           gst_segment_to_stream_time (&avi->segment, format,
599           avi->segment.start);
600       if ((stop = avi->segment.stop) == -1)
601         stop = avi->segment.duration;
602       else
603         stop = gst_segment_to_stream_time (&avi->segment, format, stop);
604
605       gst_query_set_segment (query, avi->segment.rate, format, start, stop);
606       res = TRUE;
607       break;
608     }
609     default:
610       res = gst_pad_query_default (pad, parent, query);
611       break;
612   }
613
614   return res;
615 }
616
617 #if 0
618 static const GstEventMask *
619 gst_avi_demux_get_event_mask (GstPad * pad)
620 {
621   static const GstEventMask masks[] = {
622     {GST_EVENT_SEEK, GST_SEEK_METHOD_SET | GST_SEEK_FLAG_KEY_UNIT},
623     {0,}
624   };
625
626   return masks;
627 }
628 #endif
629
630 #if 0
631 static guint64
632 gst_avi_demux_seek_streams (GstAviDemux * avi, guint64 offset, gboolean before)
633 {
634   GstAviStream *stream;
635   GstIndexEntry *entry;
636   gint i;
637   gint64 val, min = offset;
638
639   for (i = 0; i < avi->num_streams; i++) {
640     stream = &avi->stream[i];
641
642     entry = gst_index_get_assoc_entry (avi->element_index, stream->index_id,
643         before ? GST_INDEX_LOOKUP_BEFORE : GST_INDEX_LOOKUP_AFTER,
644         GST_ASSOCIATION_FLAG_NONE, GST_FORMAT_BYTES, offset);
645
646     if (before) {
647       if (entry) {
648         gst_index_entry_assoc_map (entry, GST_FORMAT_BYTES, &val);
649         GST_DEBUG_OBJECT (avi, "stream %d, previous entry at %"
650             G_GUINT64_FORMAT, i, val);
651         if (val < min)
652           min = val;
653       }
654       continue;
655     }
656
657     if (!entry) {
658       GST_DEBUG_OBJECT (avi, "no position for stream %d, assuming at start", i);
659       stream->current_entry = 0;
660       stream->current_total = 0;
661       continue;
662     }
663
664     gst_index_entry_assoc_map (entry, GST_FORMAT_BYTES, &val);
665     GST_DEBUG_OBJECT (avi, "stream %d, next entry at %" G_GUINT64_FORMAT,
666         i, val);
667
668     gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &val);
669     stream->current_total = val;
670     gst_index_entry_assoc_map (entry, GST_FORMAT_DEFAULT, &val);
671     stream->current_entry = val;
672   }
673
674   return min;
675 }
676 #endif
677
678 static gint
679 gst_avi_demux_index_entry_offset_search (GstAviIndexEntry * entry,
680     guint64 * offset)
681 {
682   if (entry->offset < *offset)
683     return -1;
684   else if (entry->offset > *offset)
685     return 1;
686   return 0;
687 }
688
689 static guint64
690 gst_avi_demux_seek_streams_index (GstAviDemux * avi, guint64 offset,
691     gboolean before)
692 {
693   GstAviStream *stream;
694   GstAviIndexEntry *entry;
695   gint i;
696   gint64 val, min = offset;
697   guint index = 0;
698
699   for (i = 0; i < avi->num_streams; i++) {
700     stream = &avi->stream[i];
701
702     /* compensate for chunk header */
703     offset += 8;
704     entry =
705         gst_util_array_binary_search (stream->index, stream->idx_n,
706         sizeof (GstAviIndexEntry),
707         (GCompareDataFunc) gst_avi_demux_index_entry_offset_search,
708         before ? GST_SEARCH_MODE_BEFORE : GST_SEARCH_MODE_AFTER, &offset, NULL);
709     offset -= 8;
710
711     if (entry)
712       index = entry - stream->index;
713
714     if (before) {
715       if (entry) {
716         val = stream->index[index].offset;
717         GST_DEBUG_OBJECT (avi,
718             "stream %d, previous entry at %" G_GUINT64_FORMAT, i, val);
719         if (val < min)
720           min = val;
721       }
722       continue;
723     }
724
725     if (!entry) {
726       GST_DEBUG_OBJECT (avi, "no position for stream %d, assuming at start", i);
727       stream->current_entry = 0;
728       stream->current_total = 0;
729       continue;
730     }
731
732     val = stream->index[index].offset - 8;
733     GST_DEBUG_OBJECT (avi, "stream %d, next entry at %" G_GUINT64_FORMAT, i,
734         val);
735
736     stream->current_total = stream->index[index].total;
737     stream->current_entry = index;
738   }
739
740   return min;
741 }
742
743 #define GST_AVI_SEEK_PUSH_DISPLACE     (4 * GST_SECOND)
744
745 static gboolean
746 gst_avi_demux_handle_sink_event (GstPad * pad, GstObject * parent,
747     GstEvent * event)
748 {
749   gboolean res = TRUE;
750   GstAviDemux *avi = GST_AVI_DEMUX (parent);
751
752   GST_DEBUG_OBJECT (avi,
753       "have event type %s: %p on sink pad", GST_EVENT_TYPE_NAME (event), event);
754
755   switch (GST_EVENT_TYPE (event)) {
756     case GST_EVENT_SEGMENT:
757     {
758       gint64 boffset, offset = 0;
759       GstSegment segment;
760       GstEvent *segment_event;
761
762       /* some debug output */
763       gst_event_copy_segment (event, &segment);
764       GST_DEBUG_OBJECT (avi, "received newsegment %" GST_SEGMENT_FORMAT,
765           &segment);
766
767       /* chain will send initial newsegment after pads have been added */
768       if (avi->state != GST_AVI_DEMUX_MOVI) {
769         GST_DEBUG_OBJECT (avi, "still starting, eating event");
770         goto exit;
771       }
772
773       /* we only expect a BYTE segment, e.g. following a seek */
774       if (segment.format != GST_FORMAT_BYTES) {
775         GST_DEBUG_OBJECT (avi, "unsupported segment format, ignoring");
776         goto exit;
777       }
778
779       if (avi->have_index) {
780         GstAviIndexEntry *entry;
781         guint i = 0, index = 0, k = 0;
782         GstAviStream *stream;
783
784         /* compensate chunk header, stored index offset points after header */
785         boffset = segment.start + 8;
786         /* find which stream we're on */
787         do {
788           stream = &avi->stream[i];
789
790           /* find the index for start bytes offset */
791           entry = gst_util_array_binary_search (stream->index,
792               stream->idx_n, sizeof (GstAviIndexEntry),
793               (GCompareDataFunc) gst_avi_demux_index_entry_offset_search,
794               GST_SEARCH_MODE_AFTER, &boffset, NULL);
795
796           if (entry == NULL)
797             continue;
798           index = entry - stream->index;
799
800           /* we are on the stream with a chunk start offset closest to start */
801           if (!offset || stream->index[index].offset < offset) {
802             offset = stream->index[index].offset;
803             k = i;
804           }
805           /* exact match needs no further searching */
806           if (stream->index[index].offset == boffset)
807             break;
808         } while (++i < avi->num_streams);
809         boffset -= 8;
810         offset -= 8;
811         stream = &avi->stream[k];
812
813         /* so we have no idea what is to come, or where we are */
814         if (!offset) {
815           GST_WARNING_OBJECT (avi, "insufficient index data, forcing EOS");
816           goto eos;
817         }
818
819         /* get the ts corresponding to start offset bytes for the stream */
820         gst_avi_demux_get_buffer_info (avi, stream, index,
821             (GstClockTime *) & segment.time, NULL, NULL, NULL);
822 #if 0
823       } else if (avi->element_index) {
824         GstIndexEntry *entry;
825
826         /* Let's check if we have an index entry for this position */
827         entry = gst_index_get_assoc_entry (avi->element_index, avi->index_id,
828             GST_INDEX_LOOKUP_AFTER, GST_ASSOCIATION_FLAG_NONE,
829             GST_FORMAT_BYTES, segment.start);
830
831         /* we can not go where we have not yet been before ... */
832         if (!entry) {
833           GST_WARNING_OBJECT (avi, "insufficient index data, forcing EOS");
834           goto eos;
835         }
836
837         gst_index_entry_assoc_map (entry, GST_FORMAT_TIME,
838             (gint64 *) & segment.time);
839         gst_index_entry_assoc_map (entry, GST_FORMAT_BYTES, &offset);
840 #endif
841       } else {
842         GST_WARNING_OBJECT (avi, "no index data, forcing EOS");
843         goto eos;
844       }
845
846       segment.format = GST_FORMAT_TIME;
847       segment.start = segment.time;
848       segment.stop = GST_CLOCK_TIME_NONE;
849       segment.position = segment.start;
850
851       /* rescue duration */
852       segment.duration = avi->segment.duration;
853
854       /* set up segment and send downstream */
855       gst_segment_copy_into (&segment, &avi->segment);
856
857       GST_DEBUG_OBJECT (avi, "Pushing newseg %" GST_SEGMENT_FORMAT, &segment);
858       avi->segment_seqnum = gst_event_get_seqnum (event);
859       segment_event = gst_event_new_segment (&segment);
860       gst_event_set_seqnum (segment_event, gst_event_get_seqnum (event));
861       gst_avi_demux_push_event (avi, segment_event);
862
863       GST_DEBUG_OBJECT (avi, "next chunk expected at %" G_GINT64_FORMAT,
864           boffset);
865
866       /* adjust state for streaming thread accordingly */
867       if (avi->have_index)
868         gst_avi_demux_seek_streams_index (avi, offset, FALSE);
869 #if 0
870       else
871         gst_avi_demux_seek_streams (avi, offset, FALSE);
872 #endif
873
874       /* set up streaming thread */
875       g_assert (offset >= boffset);
876       avi->offset = boffset;
877       avi->todrop = offset - boffset;
878
879     exit:
880       gst_event_unref (event);
881       res = TRUE;
882       break;
883     eos:
884       /* set up for EOS */
885       avi->have_eos = TRUE;
886       goto exit;
887     }
888     case GST_EVENT_EOS:
889     {
890       if (avi->state != GST_AVI_DEMUX_MOVI) {
891         gst_event_unref (event);
892         GST_ELEMENT_ERROR (avi, STREAM, DEMUX,
893             (NULL), ("got eos and didn't receive a complete header object"));
894       } else if (!gst_avi_demux_push_event (avi, event)) {
895         GST_ELEMENT_ERROR (avi, STREAM, DEMUX,
896             (NULL), ("got eos but no streams (yet)"));
897       }
898       break;
899     }
900     case GST_EVENT_FLUSH_STOP:
901     {
902       gint i;
903
904       gst_adapter_clear (avi->adapter);
905       avi->have_eos = FALSE;
906       for (i = 0; i < avi->num_streams; i++) {
907         avi->stream[i].discont = TRUE;
908       }
909       /* fall through to default case so that the event gets passed downstream */
910     }
911     default:
912       res = gst_pad_event_default (pad, parent, event);
913       break;
914   }
915
916   return res;
917 }
918
919 static gboolean
920 gst_avi_demux_handle_src_event (GstPad * pad, GstObject * parent,
921     GstEvent * event)
922 {
923   gboolean res = TRUE;
924   GstAviDemux *avi = GST_AVI_DEMUX (parent);
925
926   GST_DEBUG_OBJECT (avi,
927       "have event type %s: %p on src pad", GST_EVENT_TYPE_NAME (event), event);
928
929   switch (GST_EVENT_TYPE (event)) {
930     case GST_EVENT_SEEK:
931       if (!avi->streaming) {
932         res = gst_avi_demux_handle_seek (avi, pad, event);
933       } else {
934         res = gst_avi_demux_handle_seek_push (avi, pad, event);
935       }
936       gst_event_unref (event);
937       break;
938     default:
939       res = gst_pad_event_default (pad, parent, event);
940       break;
941   }
942
943   return res;
944 }
945
946 /* streaming helper (push) */
947
948 /*
949  * gst_avi_demux_peek_chunk_info:
950  * @avi: Avi object
951  * @tag: holder for tag
952  * @size: holder for tag size
953  *
954  * Peek next chunk info (tag and size)
955  *
956  * Returns: TRUE when one chunk info has been got
957  */
958 static gboolean
959 gst_avi_demux_peek_chunk_info (GstAviDemux * avi, guint32 * tag, guint32 * size)
960 {
961   const guint8 *data = NULL;
962
963   if (gst_adapter_available (avi->adapter) < 8)
964     return FALSE;
965
966   data = gst_adapter_map (avi->adapter, 8);
967   *tag = GST_READ_UINT32_LE (data);
968   *size = GST_READ_UINT32_LE (data + 4);
969   gst_adapter_unmap (avi->adapter);
970
971   return TRUE;
972 }
973
974 /*
975  * gst_avi_demux_peek_chunk:
976  * @avi: Avi object
977  * @tag: holder for tag
978  * @size: holder for tag size
979  *
980  * Peek enough data for one full chunk
981  *
982  * Returns: %TRUE when one chunk has been got
983  */
984 static gboolean
985 gst_avi_demux_peek_chunk (GstAviDemux * avi, guint32 * tag, guint32 * size)
986 {
987   guint32 peek_size = 0;
988   gint available;
989
990   if (!gst_avi_demux_peek_chunk_info (avi, tag, size))
991     goto peek_failed;
992
993   /* size 0 -> empty data buffer would surprise most callers,
994    * large size -> do not bother trying to squeeze that into adapter,
995    * so we throw poor man's exception, which can be caught if caller really
996    * wants to handle 0 size chunk */
997   if (!(*size) || (*size) >= (1 << 30))
998     goto strange_size;
999
1000   peek_size = (*size + 1) & ~1;
1001   available = gst_adapter_available (avi->adapter);
1002
1003   GST_DEBUG_OBJECT (avi,
1004       "Need to peek chunk of %d bytes to read chunk %" GST_FOURCC_FORMAT
1005       ", %d bytes available", *size, GST_FOURCC_ARGS (*tag), available);
1006
1007   if (available < (8 + peek_size))
1008     goto need_more;
1009
1010   return TRUE;
1011
1012   /* ERRORS */
1013 peek_failed:
1014   {
1015     GST_INFO_OBJECT (avi, "Failed to peek");
1016     return FALSE;
1017   }
1018 strange_size:
1019   {
1020     GST_INFO_OBJECT (avi,
1021         "Invalid/unexpected chunk size %d for tag %" GST_FOURCC_FORMAT, *size,
1022         GST_FOURCC_ARGS (*tag));
1023     /* chain should give up */
1024     avi->abort_buffering = TRUE;
1025     return FALSE;
1026   }
1027 need_more:
1028   {
1029     GST_INFO_OBJECT (avi, "need more %d < %" G_GUINT32_FORMAT,
1030         available, 8 + peek_size);
1031     return FALSE;
1032   }
1033 }
1034
1035 /* AVI init */
1036
1037 /*
1038  * gst_avi_demux_parse_file_header:
1039  * @element: caller element (used for errors/debug).
1040  * @buf: input data to be used for parsing.
1041  *
1042  * "Open" a RIFF/AVI file. The buffer should be at least 12
1043  * bytes long. Takes ownership of @buf.
1044  *
1045  * Returns: TRUE if the file is a RIFF/AVI file, FALSE otherwise.
1046  *          Throws an error, caller should error out (fatal).
1047  */
1048 static gboolean
1049 gst_avi_demux_parse_file_header (GstElement * element, GstBuffer * buf)
1050 {
1051   guint32 doctype;
1052   GstClockTime stamp;
1053
1054   stamp = gst_util_get_timestamp ();
1055
1056   /* riff_parse posts an error */
1057   if (!gst_riff_parse_file_header (element, buf, &doctype))
1058     return FALSE;
1059
1060   if (doctype != GST_RIFF_RIFF_AVI)
1061     goto not_avi;
1062
1063   stamp = gst_util_get_timestamp () - stamp;
1064   GST_DEBUG_OBJECT (element, "header parsing took %" GST_TIME_FORMAT,
1065       GST_TIME_ARGS (stamp));
1066
1067   return TRUE;
1068
1069   /* ERRORS */
1070 not_avi:
1071   {
1072     GST_ELEMENT_ERROR (element, STREAM, WRONG_TYPE, (NULL),
1073         ("File is not an AVI file: 0x%" G_GINT32_MODIFIER "x", doctype));
1074     return FALSE;
1075   }
1076 }
1077
1078 /*
1079  * Read AVI file tag when streaming
1080  */
1081 static GstFlowReturn
1082 gst_avi_demux_stream_init_push (GstAviDemux * avi)
1083 {
1084   if (gst_adapter_available (avi->adapter) >= 12) {
1085     GstBuffer *tmp;
1086
1087     tmp = gst_adapter_take_buffer (avi->adapter, 12);
1088
1089     GST_DEBUG ("Parsing avi header");
1090     if (!gst_avi_demux_parse_file_header (GST_ELEMENT_CAST (avi), tmp)) {
1091       return GST_FLOW_ERROR;
1092     }
1093     GST_DEBUG ("header ok");
1094     avi->offset += 12;
1095
1096     avi->state = GST_AVI_DEMUX_HEADER;
1097   }
1098   return GST_FLOW_OK;
1099 }
1100
1101 /*
1102  * Read AVI file tag
1103  */
1104 static GstFlowReturn
1105 gst_avi_demux_stream_init_pull (GstAviDemux * avi)
1106 {
1107   GstFlowReturn res;
1108   GstBuffer *buf = NULL;
1109
1110   res = gst_pad_pull_range (avi->sinkpad, avi->offset, 12, &buf);
1111   if (res != GST_FLOW_OK)
1112     return res;
1113   else if (!gst_avi_demux_parse_file_header (GST_ELEMENT_CAST (avi), buf))
1114     goto wrong_header;
1115
1116   avi->offset += 12;
1117
1118   return GST_FLOW_OK;
1119
1120   /* ERRORS */
1121 wrong_header:
1122   {
1123     GST_DEBUG_OBJECT (avi, "error parsing file header");
1124     return GST_FLOW_ERROR;
1125   }
1126 }
1127
1128 /* AVI header handling */
1129 /*
1130  * gst_avi_demux_parse_avih:
1131  * @avi: caller element (used for errors/debug).
1132  * @buf: input data to be used for parsing.
1133  * @avih: pointer to structure (filled in by function) containing
1134  *        stream information (such as flags, number of streams, etc.).
1135  *
1136  * Read 'avih' header. Discards buffer after use.
1137  *
1138  * Returns: TRUE on success, FALSE otherwise. Throws an error if
1139  *          the header is invalid. The caller should error out
1140  *          (fatal).
1141  */
1142 static gboolean
1143 gst_avi_demux_parse_avih (GstAviDemux * avi,
1144     GstBuffer * buf, gst_riff_avih ** _avih)
1145 {
1146   gst_riff_avih *avih;
1147   gsize size;
1148
1149   if (buf == NULL)
1150     goto no_buffer;
1151
1152   size = gst_buffer_get_size (buf);
1153   if (size < sizeof (gst_riff_avih))
1154     goto avih_too_small;
1155
1156   avih = g_malloc (size);
1157   gst_buffer_extract (buf, 0, avih, size);
1158
1159 #if (G_BYTE_ORDER == G_BIG_ENDIAN)
1160   avih->us_frame = GUINT32_FROM_LE (avih->us_frame);
1161   avih->max_bps = GUINT32_FROM_LE (avih->max_bps);
1162   avih->pad_gran = GUINT32_FROM_LE (avih->pad_gran);
1163   avih->flags = GUINT32_FROM_LE (avih->flags);
1164   avih->tot_frames = GUINT32_FROM_LE (avih->tot_frames);
1165   avih->init_frames = GUINT32_FROM_LE (avih->init_frames);
1166   avih->streams = GUINT32_FROM_LE (avih->streams);
1167   avih->bufsize = GUINT32_FROM_LE (avih->bufsize);
1168   avih->width = GUINT32_FROM_LE (avih->width);
1169   avih->height = GUINT32_FROM_LE (avih->height);
1170   avih->scale = GUINT32_FROM_LE (avih->scale);
1171   avih->rate = GUINT32_FROM_LE (avih->rate);
1172   avih->start = GUINT32_FROM_LE (avih->start);
1173   avih->length = GUINT32_FROM_LE (avih->length);
1174 #endif
1175
1176   /* debug stuff */
1177   GST_INFO_OBJECT (avi, "avih tag found:");
1178   GST_INFO_OBJECT (avi, " us_frame    %u", avih->us_frame);
1179   GST_INFO_OBJECT (avi, " max_bps     %u", avih->max_bps);
1180   GST_INFO_OBJECT (avi, " pad_gran    %u", avih->pad_gran);
1181   GST_INFO_OBJECT (avi, " flags       0x%08x", avih->flags);
1182   GST_INFO_OBJECT (avi, " tot_frames  %u", avih->tot_frames);
1183   GST_INFO_OBJECT (avi, " init_frames %u", avih->init_frames);
1184   GST_INFO_OBJECT (avi, " streams     %u", avih->streams);
1185   GST_INFO_OBJECT (avi, " bufsize     %u", avih->bufsize);
1186   GST_INFO_OBJECT (avi, " width       %u", avih->width);
1187   GST_INFO_OBJECT (avi, " height      %u", avih->height);
1188   GST_INFO_OBJECT (avi, " scale       %u", avih->scale);
1189   GST_INFO_OBJECT (avi, " rate        %u", avih->rate);
1190   GST_INFO_OBJECT (avi, " start       %u", avih->start);
1191   GST_INFO_OBJECT (avi, " length      %u", avih->length);
1192
1193   *_avih = avih;
1194   gst_buffer_unref (buf);
1195
1196   if (avih->us_frame != 0 && avih->tot_frames != 0)
1197     avi->duration =
1198         (guint64) avih->us_frame * (guint64) avih->tot_frames * 1000;
1199   else
1200     avi->duration = GST_CLOCK_TIME_NONE;
1201
1202   GST_INFO_OBJECT (avi, " header duration  %" GST_TIME_FORMAT,
1203       GST_TIME_ARGS (avi->duration));
1204
1205   return TRUE;
1206
1207   /* ERRORS */
1208 no_buffer:
1209   {
1210     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("No buffer"));
1211     return FALSE;
1212   }
1213 avih_too_small:
1214   {
1215     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
1216         ("Too small avih (%" G_GSIZE_FORMAT " available, %d needed)",
1217             size, (int) sizeof (gst_riff_avih)));
1218     gst_buffer_unref (buf);
1219     return FALSE;
1220   }
1221 }
1222
1223 /*
1224  * gst_avi_demux_parse_superindex:
1225  * @avi: caller element (used for debugging/errors).
1226  * @buf: input data to use for parsing.
1227  * @locations: locations in the file (byte-offsets) that contain
1228  *             the actual indexes (see get_avi_demux_parse_subindex()).
1229  *             The array ends with GST_BUFFER_OFFSET_NONE.
1230  *
1231  * Reads superindex (openDML-2 spec stuff) from the provided data.
1232  *
1233  * Returns: TRUE on success, FALSE otherwise. Indexes should be skipped
1234  *          on error, but they are not fatal.
1235  */
1236 static gboolean
1237 gst_avi_demux_parse_superindex (GstAviDemux * avi,
1238     GstBuffer * buf, guint64 ** _indexes)
1239 {
1240   GstMapInfo map;
1241   guint8 *data;
1242   guint16 bpe = 16;
1243   guint32 num, i;
1244   guint64 *indexes;
1245   gsize size;
1246
1247   *_indexes = NULL;
1248
1249   if (buf) {
1250     gst_buffer_map (buf, &map, GST_MAP_READ);
1251     data = map.data;
1252     size = map.size;
1253   } else {
1254     data = NULL;
1255     size = 0;
1256   }
1257
1258   if (size < 24)
1259     goto too_small;
1260
1261   /* check type of index. The opendml2 specs state that
1262    * there should be 4 dwords per array entry. Type can be
1263    * either frame or field (and we don't care). */
1264   if (GST_READ_UINT16_LE (data) != 4 ||
1265       (data[2] & 0xfe) != 0x0 || data[3] != 0x0) {
1266     GST_WARNING_OBJECT (avi,
1267         "Superindex for stream has unexpected "
1268         "size_entry %d (bytes) or flags 0x%02x/0x%02x",
1269         GST_READ_UINT16_LE (data), data[2], data[3]);
1270     bpe = GST_READ_UINT16_LE (data) * 4;
1271   }
1272   num = GST_READ_UINT32_LE (&data[4]);
1273
1274   GST_DEBUG_OBJECT (avi, "got %d indexes", num);
1275
1276   /* this can't work out well ... */
1277   if (num > G_MAXUINT32 >> 1 || bpe < 8) {
1278     goto invalid_params;
1279   }
1280
1281   indexes = g_new (guint64, num + 1);
1282   for (i = 0; i < num; i++) {
1283     if (size < 24 + bpe * (i + 1))
1284       break;
1285     indexes[i] = GST_READ_UINT64_LE (&data[24 + bpe * i]);
1286     GST_DEBUG_OBJECT (avi, "index %d at %" G_GUINT64_FORMAT, i, indexes[i]);
1287   }
1288   indexes[i] = GST_BUFFER_OFFSET_NONE;
1289   *_indexes = indexes;
1290
1291   gst_buffer_unmap (buf, &map);
1292   gst_buffer_unref (buf);
1293
1294   return TRUE;
1295
1296   /* ERRORS */
1297 too_small:
1298   {
1299     GST_ERROR_OBJECT (avi,
1300         "Not enough data to parse superindex (%" G_GSIZE_FORMAT
1301         " available, 24 needed)", size);
1302     if (buf) {
1303       gst_buffer_unmap (buf, &map);
1304       gst_buffer_unref (buf);
1305     }
1306     return FALSE;
1307   }
1308 invalid_params:
1309   {
1310     GST_ERROR_OBJECT (avi, "invalid index parameters (num = %d, bpe = %d)",
1311         num, bpe);
1312     gst_buffer_unmap (buf, &map);
1313     gst_buffer_unref (buf);
1314     return FALSE;
1315   }
1316 }
1317
1318 /* add an entry to the index of a stream. @num should be an estimate of the
1319  * total amount of index entries for all streams and is used to dynamically
1320  * allocate memory for the index entries. */
1321 static inline gboolean
1322 gst_avi_demux_add_index (GstAviDemux * avi, GstAviStream * stream,
1323     guint num, GstAviIndexEntry * entry)
1324 {
1325   /* ensure index memory */
1326   if (G_UNLIKELY (stream->idx_n >= stream->idx_max)) {
1327     guint idx_max = stream->idx_max;
1328     GstAviIndexEntry *new_idx;
1329
1330     /* we need to make some more room */
1331     if (idx_max == 0) {
1332       /* initial size guess, assume each stream has an equal amount of entries,
1333        * overshoot with at least 8K */
1334       idx_max = (num / avi->num_streams) + (8192 / sizeof (GstAviIndexEntry));
1335     } else {
1336       idx_max += 8192 / sizeof (GstAviIndexEntry);
1337       GST_DEBUG_OBJECT (avi, "expanded index from %u to %u",
1338           stream->idx_max, idx_max);
1339     }
1340     new_idx = g_try_renew (GstAviIndexEntry, stream->index, idx_max);
1341     /* out of memory, if this fails stream->index is untouched. */
1342     if (G_UNLIKELY (!new_idx))
1343       return FALSE;
1344     /* use new index */
1345     stream->index = new_idx;
1346     stream->idx_max = idx_max;
1347   }
1348
1349   /* update entry total and stream stats. The entry total can be converted to
1350    * the timestamp of the entry easily. */
1351   if (stream->strh->type == GST_RIFF_FCC_auds) {
1352     gint blockalign;
1353
1354     if (stream->is_vbr) {
1355       entry->total = stream->total_blocks;
1356     } else {
1357       entry->total = stream->total_bytes;
1358     }
1359     blockalign = stream->strf.auds->blockalign;
1360     if (blockalign > 0)
1361       stream->total_blocks += DIV_ROUND_UP (entry->size, blockalign);
1362     else
1363       stream->total_blocks++;
1364   } else {
1365     if (stream->is_vbr) {
1366       entry->total = stream->idx_n;
1367     } else {
1368       entry->total = stream->total_bytes;
1369     }
1370   }
1371   stream->total_bytes += entry->size;
1372   if (ENTRY_IS_KEYFRAME (entry))
1373     stream->n_keyframes++;
1374
1375   /* and add */
1376   GST_LOG_OBJECT (avi,
1377       "Adding stream %u, index entry %d, kf %d, size %u "
1378       ", offset %" G_GUINT64_FORMAT ", total %" G_GUINT64_FORMAT, stream->num,
1379       stream->idx_n, ENTRY_IS_KEYFRAME (entry), entry->size, entry->offset,
1380       entry->total);
1381   stream->index[stream->idx_n++] = *entry;
1382
1383   return TRUE;
1384 }
1385
1386 /* given @entry_n in @stream, calculate info such as timestamps and
1387  * offsets for the entry. */
1388 static void
1389 gst_avi_demux_get_buffer_info (GstAviDemux * avi, GstAviStream * stream,
1390     guint entry_n, GstClockTime * timestamp, GstClockTime * ts_end,
1391     guint64 * offset, guint64 * offset_end)
1392 {
1393   GstAviIndexEntry *entry;
1394
1395   entry = &stream->index[entry_n];
1396
1397   if (stream->is_vbr) {
1398     /* VBR stream next timestamp */
1399     if (stream->strh->type == GST_RIFF_FCC_auds) {
1400       if (timestamp)
1401         *timestamp =
1402             avi_stream_convert_frames_to_time_unchecked (stream, entry->total);
1403       if (ts_end) {
1404         gint size = 1;
1405         if (G_LIKELY (entry_n + 1 < stream->idx_n))
1406           size = stream->index[entry_n + 1].total - entry->total;
1407         *ts_end = avi_stream_convert_frames_to_time_unchecked (stream,
1408             entry->total + size);
1409       }
1410     } else {
1411       if (timestamp)
1412         *timestamp =
1413             avi_stream_convert_frames_to_time_unchecked (stream, entry_n);
1414       if (ts_end)
1415         *ts_end = avi_stream_convert_frames_to_time_unchecked (stream,
1416             entry_n + 1);
1417     }
1418   } else if (stream->strh->type == GST_RIFF_FCC_auds) {
1419     /* constant rate stream */
1420     if (timestamp)
1421       *timestamp =
1422           avi_stream_convert_bytes_to_time_unchecked (stream, entry->total);
1423     if (ts_end)
1424       *ts_end = avi_stream_convert_bytes_to_time_unchecked (stream,
1425           entry->total + entry->size);
1426   }
1427   if (stream->strh->type == GST_RIFF_FCC_vids) {
1428     /* video offsets are the frame number */
1429     if (offset)
1430       *offset = entry_n;
1431     if (offset_end)
1432       *offset_end = entry_n + 1;
1433   } else {
1434     /* no offsets for audio */
1435     if (offset)
1436       *offset = -1;
1437     if (offset_end)
1438       *offset_end = -1;
1439   }
1440 }
1441
1442 /* collect and debug stats about the indexes for all streams.
1443  * This method is also responsible for filling in the stream duration
1444  * as measured by the amount of index entries.
1445  *
1446  * Returns TRUE if the index is not empty, else FALSE */
1447 static gboolean
1448 gst_avi_demux_do_index_stats (GstAviDemux * avi)
1449 {
1450   guint total_idx = 0;
1451   guint i;
1452 #ifndef GST_DISABLE_GST_DEBUG
1453   guint total_max = 0;
1454 #endif
1455
1456   /* get stream stats now */
1457   for (i = 0; i < avi->num_streams; i++) {
1458     GstAviStream *stream;
1459
1460     if (G_UNLIKELY (!(stream = &avi->stream[i])))
1461       continue;
1462     if (G_UNLIKELY (!stream->strh))
1463       continue;
1464     if (G_UNLIKELY (!stream->index || stream->idx_n == 0))
1465       continue;
1466
1467     /* we interested in the end_ts of the last entry, which is the total
1468      * duration of this stream */
1469     gst_avi_demux_get_buffer_info (avi, stream, stream->idx_n - 1,
1470         NULL, &stream->idx_duration, NULL, NULL);
1471
1472     total_idx += stream->idx_n;
1473 #ifndef GST_DISABLE_GST_DEBUG
1474     total_max += stream->idx_max;
1475 #endif
1476     GST_INFO_OBJECT (avi, "Stream %d, dur %" GST_TIME_FORMAT ", %6u entries, "
1477         "%5u keyframes, entry size = %2u, total size = %10u, allocated %10u",
1478         i, GST_TIME_ARGS (stream->idx_duration), stream->idx_n,
1479         stream->n_keyframes, (guint) sizeof (GstAviIndexEntry),
1480         (guint) (stream->idx_n * sizeof (GstAviIndexEntry)),
1481         (guint) (stream->idx_max * sizeof (GstAviIndexEntry)));
1482
1483     /* knowing all that we do, that also includes avg bitrate */
1484     if (!stream->taglist) {
1485       stream->taglist = gst_tag_list_new_empty ();
1486     }
1487     if (stream->total_bytes && stream->idx_duration)
1488       gst_tag_list_add (stream->taglist, GST_TAG_MERGE_REPLACE,
1489           GST_TAG_BITRATE,
1490           (guint) gst_util_uint64_scale (stream->total_bytes * 8,
1491               GST_SECOND, stream->idx_duration), NULL);
1492   }
1493   total_idx *= sizeof (GstAviIndexEntry);
1494 #ifndef GST_DISABLE_GST_DEBUG
1495   total_max *= sizeof (GstAviIndexEntry);
1496 #endif
1497   GST_INFO_OBJECT (avi, "%u bytes for index vs %u ideally, %u wasted",
1498       total_max, total_idx, total_max - total_idx);
1499
1500   if (total_idx == 0) {
1501     GST_WARNING_OBJECT (avi, "Index is empty !");
1502     return FALSE;
1503   }
1504   return TRUE;
1505 }
1506
1507 /*
1508  * gst_avi_demux_parse_subindex:
1509  * @avi: Avi object
1510  * @buf: input data to use for parsing.
1511  * @stream: stream context.
1512  * @entries_list: a list (returned by the function) containing all the
1513  *           indexes parsed in this specific subindex. The first
1514  *           entry is also a pointer to allocated memory that needs
1515  *           to be free´ed. May be NULL if no supported indexes were
1516  *           found.
1517  *
1518  * Reads superindex (openDML-2 spec stuff) from the provided data.
1519  * The buffer should contain a GST_RIFF_TAG_ix?? chunk.
1520  *
1521  * Returns: TRUE on success, FALSE otherwise. Errors are fatal, we
1522  *          throw an error, caller should bail out asap.
1523  */
1524 static gboolean
1525 gst_avi_demux_parse_subindex (GstAviDemux * avi, GstAviStream * stream,
1526     GstBuffer * buf)
1527 {
1528   GstMapInfo map;
1529   guint8 *data;
1530   guint16 bpe;
1531   guint32 num, i;
1532   guint64 baseoff;
1533
1534   if (buf == NULL)
1535     return TRUE;
1536
1537   gst_buffer_map (buf, &map, GST_MAP_READ);
1538   data = map.data;
1539
1540   /* check size */
1541   if (map.size < 24)
1542     goto too_small;
1543
1544   /* We don't support index-data yet */
1545   if (data[3] & 0x80)
1546     goto not_implemented;
1547
1548   /* check type of index. The opendml2 specs state that
1549    * there should be 4 dwords per array entry. Type can be
1550    * either frame or field (and we don't care). */
1551   bpe = (data[2] & 0x01) ? 12 : 8;
1552   if (GST_READ_UINT16_LE (data) != bpe / 4 ||
1553       (data[2] & 0xfe) != 0x0 || data[3] != 0x1) {
1554     GST_WARNING_OBJECT (avi,
1555         "Superindex for stream %d has unexpected "
1556         "size_entry %d (bytes) or flags 0x%02x/0x%02x",
1557         stream->num, GST_READ_UINT16_LE (data), data[2], data[3]);
1558     bpe = GST_READ_UINT16_LE (data) * 4;
1559   }
1560   num = GST_READ_UINT32_LE (&data[4]);
1561   baseoff = GST_READ_UINT64_LE (&data[12]);
1562
1563   /* If there's nothing, just return ! */
1564   if (num == 0)
1565     goto empty_index;
1566
1567   GST_INFO_OBJECT (avi, "Parsing subindex, nr_entries = %6d", num);
1568
1569   for (i = 0; i < num; i++) {
1570     GstAviIndexEntry entry;
1571
1572     if (map.size < 24 + bpe * (i + 1))
1573       break;
1574
1575     /* fill in offset and size. offset contains the keyframe flag in the
1576      * upper bit*/
1577     entry.offset = baseoff + GST_READ_UINT32_LE (&data[24 + bpe * i]);
1578     entry.size = GST_READ_UINT32_LE (&data[24 + bpe * i + 4]);
1579     /* handle flags */
1580     if (stream->strh->type == GST_RIFF_FCC_auds) {
1581       /* all audio frames are keyframes */
1582       ENTRY_SET_KEYFRAME (&entry);
1583     } else {
1584       /* else read flags */
1585       entry.flags = (entry.size & 0x80000000) ? 0 : GST_AVI_KEYFRAME;
1586     }
1587     entry.size &= ~0x80000000;
1588
1589     /* and add */
1590     if (G_UNLIKELY (!gst_avi_demux_add_index (avi, stream, num, &entry)))
1591       goto out_of_mem;
1592   }
1593 done:
1594   gst_buffer_unmap (buf, &map);
1595   gst_buffer_unref (buf);
1596
1597   return TRUE;
1598
1599   /* ERRORS */
1600 too_small:
1601   {
1602     GST_ERROR_OBJECT (avi,
1603         "Not enough data to parse subindex (%" G_GSIZE_FORMAT
1604         " available, 24 needed)", map.size);
1605     goto done;                  /* continue */
1606   }
1607 not_implemented:
1608   {
1609     GST_ELEMENT_ERROR (avi, STREAM, NOT_IMPLEMENTED, (NULL),
1610         ("Subindex-is-data is not implemented"));
1611     gst_buffer_unmap (buf, &map);
1612     gst_buffer_unref (buf);
1613     return FALSE;
1614   }
1615 empty_index:
1616   {
1617     GST_DEBUG_OBJECT (avi, "the index is empty");
1618     goto done;                  /* continue */
1619   }
1620 out_of_mem:
1621   {
1622     GST_ELEMENT_ERROR (avi, RESOURCE, NO_SPACE_LEFT, (NULL),
1623         ("Cannot allocate memory for %u*%u=%u bytes",
1624             (guint) sizeof (GstAviIndexEntry), num,
1625             (guint) sizeof (GstAviIndexEntry) * num));
1626     gst_buffer_unmap (buf, &map);
1627     gst_buffer_unref (buf);
1628     return FALSE;
1629   }
1630 }
1631
1632 /*
1633  * Create and push a flushing seek event upstream
1634  */
1635 static gboolean
1636 perform_seek_to_offset (GstAviDemux * demux, guint64 offset, guint32 seqnum)
1637 {
1638   GstEvent *event;
1639   gboolean res = 0;
1640
1641   GST_DEBUG_OBJECT (demux, "Seeking to %" G_GUINT64_FORMAT, offset);
1642
1643   event =
1644       gst_event_new_seek (1.0, GST_FORMAT_BYTES,
1645       GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE, GST_SEEK_TYPE_SET, offset,
1646       GST_SEEK_TYPE_NONE, -1);
1647   gst_event_set_seqnum (event, seqnum);
1648   res = gst_pad_push_event (demux->sinkpad, event);
1649
1650   if (res)
1651     demux->offset = offset;
1652   return res;
1653 }
1654
1655 /*
1656  * Read AVI index when streaming
1657  */
1658 static gboolean
1659 gst_avi_demux_read_subindexes_push (GstAviDemux * avi)
1660 {
1661   guint32 tag = 0, size;
1662   GstBuffer *buf = NULL;
1663   guint odml_stream;
1664
1665   GST_DEBUG_OBJECT (avi, "read subindexes for %d streams", avi->num_streams);
1666
1667   if (avi->odml_subidxs[avi->odml_subidx] != avi->offset)
1668     return FALSE;
1669
1670   if (!gst_avi_demux_peek_chunk (avi, &tag, &size))
1671     return TRUE;
1672
1673   /* this is the ODML chunk we expect */
1674   odml_stream = avi->odml_stream;
1675
1676   if ((tag != GST_MAKE_FOURCC ('i', 'x', '0' + odml_stream / 10,
1677               '0' + odml_stream % 10)) &&
1678       (tag != GST_MAKE_FOURCC ('0' + odml_stream / 10,
1679               '0' + odml_stream % 10, 'i', 'x'))) {
1680     GST_WARNING_OBJECT (avi, "Not an ix## chunk (%" GST_FOURCC_FORMAT ")",
1681         GST_FOURCC_ARGS (tag));
1682     return FALSE;
1683   }
1684
1685   avi->offset += 8 + GST_ROUND_UP_2 (size);
1686   /* flush chunk header so we get just the 'size' payload data */
1687   gst_adapter_flush (avi->adapter, 8);
1688   buf = gst_adapter_take_buffer (avi->adapter, size);
1689
1690   if (!gst_avi_demux_parse_subindex (avi, &avi->stream[odml_stream], buf))
1691     return FALSE;
1692
1693   /* we parsed the index, go to next subindex */
1694   avi->odml_subidx++;
1695
1696   if (avi->odml_subidxs[avi->odml_subidx] == GST_BUFFER_OFFSET_NONE) {
1697     /* we reached the end of the indexes for this stream, move to the next
1698      * stream to handle the first index */
1699     avi->odml_stream++;
1700     avi->odml_subidx = 0;
1701
1702     if (avi->odml_stream < avi->num_streams) {
1703       /* there are more indexes */
1704       avi->odml_subidxs = avi->stream[avi->odml_stream].indexes;
1705     } else {
1706       /* we're done, get stream stats now */
1707       avi->have_index = gst_avi_demux_do_index_stats (avi);
1708
1709       return TRUE;
1710     }
1711   }
1712
1713   /* seek to next index */
1714   return perform_seek_to_offset (avi, avi->odml_subidxs[avi->odml_subidx],
1715       avi->segment_seqnum);
1716 }
1717
1718 /*
1719  * Read AVI index
1720  */
1721 static void
1722 gst_avi_demux_read_subindexes_pull (GstAviDemux * avi)
1723 {
1724   guint32 tag;
1725   GstBuffer *buf;
1726   gint i, n;
1727
1728   GST_DEBUG_OBJECT (avi, "read subindexes for %d streams", avi->num_streams);
1729
1730   for (n = 0; n < avi->num_streams; n++) {
1731     GstAviStream *stream = &avi->stream[n];
1732
1733     if (stream->indexes == NULL)
1734       continue;
1735
1736     for (i = 0; stream->indexes[i] != GST_BUFFER_OFFSET_NONE; i++) {
1737       if (gst_riff_read_chunk (GST_ELEMENT_CAST (avi), avi->sinkpad,
1738               &stream->indexes[i], &tag, &buf) != GST_FLOW_OK)
1739         continue;
1740       else if ((tag != GST_MAKE_FOURCC ('i', 'x', '0' + stream->num / 10,
1741                   '0' + stream->num % 10)) &&
1742           (tag != GST_MAKE_FOURCC ('0' + stream->num / 10,
1743                   '0' + stream->num % 10, 'i', 'x'))) {
1744         /* Some ODML files (created by god knows what muxer) have a ##ix format
1745          * instead of the 'official' ix##. They are still valid though. */
1746         GST_WARNING_OBJECT (avi, "Not an ix## chunk (%" GST_FOURCC_FORMAT ")",
1747             GST_FOURCC_ARGS (tag));
1748         gst_buffer_unref (buf);
1749         continue;
1750       }
1751
1752       if (!gst_avi_demux_parse_subindex (avi, stream, buf))
1753         continue;
1754     }
1755
1756     g_free (stream->indexes);
1757     stream->indexes = NULL;
1758   }
1759   /* get stream stats now */
1760   avi->have_index = gst_avi_demux_do_index_stats (avi);
1761 }
1762
1763 /*
1764  * gst_avi_demux_riff_parse_vprp:
1765  * @element: caller element (used for debugging/error).
1766  * @buf: input data to be used for parsing, stripped from header.
1767  * @vprp: a pointer (returned by this function) to a filled-in vprp
1768  *        structure. Caller should free it.
1769  *
1770  * Parses a video stream´s vprp. This function takes ownership of @buf.
1771  *
1772  * Returns: TRUE if parsing succeeded, otherwise FALSE. The stream
1773  *          should be skipped on error, but it is not fatal.
1774  */
1775 static gboolean
1776 gst_avi_demux_riff_parse_vprp (GstElement * element,
1777     GstBuffer * buf, gst_riff_vprp ** _vprp)
1778 {
1779   gst_riff_vprp *vprp;
1780   gint k;
1781   gsize size;
1782
1783   g_return_val_if_fail (buf != NULL, FALSE);
1784   g_return_val_if_fail (_vprp != NULL, FALSE);
1785
1786   size = gst_buffer_get_size (buf);
1787
1788   if (size < G_STRUCT_OFFSET (gst_riff_vprp, field_info))
1789     goto too_small;
1790
1791   vprp = g_malloc (size);
1792   gst_buffer_extract (buf, 0, vprp, size);
1793
1794 #if (G_BYTE_ORDER == G_BIG_ENDIAN)
1795   vprp->format_token = GUINT32_FROM_LE (vprp->format_token);
1796   vprp->standard = GUINT32_FROM_LE (vprp->standard);
1797   vprp->vert_rate = GUINT32_FROM_LE (vprp->vert_rate);
1798   vprp->hor_t_total = GUINT32_FROM_LE (vprp->hor_t_total);
1799   vprp->vert_lines = GUINT32_FROM_LE (vprp->vert_lines);
1800   vprp->aspect = GUINT32_FROM_LE (vprp->aspect);
1801   vprp->width = GUINT32_FROM_LE (vprp->width);
1802   vprp->height = GUINT32_FROM_LE (vprp->height);
1803   vprp->fields = GUINT32_FROM_LE (vprp->fields);
1804 #endif
1805
1806   /* size checking */
1807   /* calculate fields based on size */
1808   k = (size - G_STRUCT_OFFSET (gst_riff_vprp, field_info)) / vprp->fields;
1809   if (vprp->fields > k) {
1810     GST_WARNING_OBJECT (element,
1811         "vprp header indicated %d fields, only %d available", vprp->fields, k);
1812     vprp->fields = k;
1813   }
1814   if (vprp->fields > GST_RIFF_VPRP_VIDEO_FIELDS) {
1815     GST_WARNING_OBJECT (element,
1816         "vprp header indicated %d fields, at most %d supported", vprp->fields,
1817         GST_RIFF_VPRP_VIDEO_FIELDS);
1818     vprp->fields = GST_RIFF_VPRP_VIDEO_FIELDS;
1819   }
1820 #if (G_BYTE_ORDER == G_BIG_ENDIAN)
1821   for (k = 0; k < vprp->fields; k++) {
1822     gst_riff_vprp_video_field_desc *fd;
1823
1824     fd = &vprp->field_info[k];
1825     fd->compressed_bm_height = GUINT32_FROM_LE (fd->compressed_bm_height);
1826     fd->compressed_bm_width = GUINT32_FROM_LE (fd->compressed_bm_width);
1827     fd->valid_bm_height = GUINT32_FROM_LE (fd->valid_bm_height);
1828     fd->valid_bm_width = GUINT16_FROM_LE (fd->valid_bm_width);
1829     fd->valid_bm_x_offset = GUINT16_FROM_LE (fd->valid_bm_x_offset);
1830     fd->valid_bm_y_offset = GUINT32_FROM_LE (fd->valid_bm_y_offset);
1831     fd->video_x_t_offset = GUINT32_FROM_LE (fd->video_x_t_offset);
1832     fd->video_y_start = GUINT32_FROM_LE (fd->video_y_start);
1833   }
1834 #endif
1835
1836   /* debug */
1837   GST_INFO_OBJECT (element, "vprp tag found in context vids:");
1838   GST_INFO_OBJECT (element, " format_token  %d", vprp->format_token);
1839   GST_INFO_OBJECT (element, " standard      %d", vprp->standard);
1840   GST_INFO_OBJECT (element, " vert_rate     %d", vprp->vert_rate);
1841   GST_INFO_OBJECT (element, " hor_t_total   %d", vprp->hor_t_total);
1842   GST_INFO_OBJECT (element, " vert_lines    %d", vprp->vert_lines);
1843   GST_INFO_OBJECT (element, " aspect        %d:%d", vprp->aspect >> 16,
1844       vprp->aspect & 0xffff);
1845   GST_INFO_OBJECT (element, " width         %d", vprp->width);
1846   GST_INFO_OBJECT (element, " height        %d", vprp->height);
1847   GST_INFO_OBJECT (element, " fields        %d", vprp->fields);
1848   for (k = 0; k < vprp->fields; k++) {
1849     gst_riff_vprp_video_field_desc *fd;
1850
1851     fd = &(vprp->field_info[k]);
1852     GST_INFO_OBJECT (element, " field %u description:", k);
1853     GST_INFO_OBJECT (element, "  compressed_bm_height  %d",
1854         fd->compressed_bm_height);
1855     GST_INFO_OBJECT (element, "  compressed_bm_width  %d",
1856         fd->compressed_bm_width);
1857     GST_INFO_OBJECT (element, "  valid_bm_height       %d",
1858         fd->valid_bm_height);
1859     GST_INFO_OBJECT (element, "  valid_bm_width        %d", fd->valid_bm_width);
1860     GST_INFO_OBJECT (element, "  valid_bm_x_offset     %d",
1861         fd->valid_bm_x_offset);
1862     GST_INFO_OBJECT (element, "  valid_bm_y_offset     %d",
1863         fd->valid_bm_y_offset);
1864     GST_INFO_OBJECT (element, "  video_x_t_offset      %d",
1865         fd->video_x_t_offset);
1866     GST_INFO_OBJECT (element, "  video_y_start         %d", fd->video_y_start);
1867   }
1868
1869   gst_buffer_unref (buf);
1870
1871   *_vprp = vprp;
1872
1873   return TRUE;
1874
1875   /* ERRORS */
1876 too_small:
1877   {
1878     GST_ERROR_OBJECT (element,
1879         "Too small vprp (%" G_GSIZE_FORMAT " available, at least %d needed)",
1880         size, (int) G_STRUCT_OFFSET (gst_riff_vprp, field_info));
1881     gst_buffer_unref (buf);
1882     return FALSE;
1883   }
1884 }
1885
1886 static void
1887 gst_avi_demux_expose_streams (GstAviDemux * avi, gboolean force)
1888 {
1889   guint i;
1890
1891   GST_DEBUG_OBJECT (avi, "force : %d", force);
1892
1893   for (i = 0; i < avi->num_streams; i++) {
1894     GstAviStream *stream = &avi->stream[i];
1895
1896     if (force || stream->idx_n != 0) {
1897       GST_LOG_OBJECT (avi, "Adding pad %s", GST_PAD_NAME (stream->pad));
1898       gst_element_add_pad ((GstElement *) avi, stream->pad);
1899       gst_flow_combiner_add_pad (avi->flowcombiner, stream->pad);
1900
1901 #if 0
1902       if (avi->element_index)
1903         gst_index_get_writer_id (avi->element_index,
1904             GST_OBJECT_CAST (stream->pad), &stream->index_id);
1905 #endif
1906
1907       stream->exposed = TRUE;
1908       if (avi->main_stream == -1)
1909         avi->main_stream = i;
1910     } else {
1911       GST_WARNING_OBJECT (avi, "Stream #%d doesn't have any entry, removing it",
1912           i);
1913       gst_avi_demux_reset_stream (avi, stream);
1914     }
1915   }
1916 }
1917
1918 /* buf contains LIST chunk data, and will be padded to even size,
1919  * since some buggy files do not account for the padding of chunks
1920  * within a LIST in the size of the LIST */
1921 static inline void
1922 gst_avi_demux_roundup_list (GstAviDemux * avi, GstBuffer ** buf)
1923 {
1924   gsize size;
1925
1926   size = gst_buffer_get_size (*buf);
1927
1928   if (G_UNLIKELY (size & 1)) {
1929     GstBuffer *obuf;
1930     GstMapInfo map;
1931
1932     GST_DEBUG_OBJECT (avi, "rounding up dubious list size %" G_GSIZE_FORMAT,
1933         size);
1934     obuf = gst_buffer_new_and_alloc (size + 1);
1935
1936     gst_buffer_map (obuf, &map, GST_MAP_WRITE);
1937     gst_buffer_extract (*buf, 0, map.data, size);
1938     /* assume 0 padding, at least makes outcome deterministic */
1939     map.data[size] = 0;
1940     gst_buffer_unmap (obuf, &map);
1941     gst_buffer_replace (buf, obuf);
1942   }
1943 }
1944
1945 static GstCaps *
1946 gst_avi_demux_check_caps (GstAviDemux * avi, GstAviStream * stream,
1947     GstCaps * caps)
1948 {
1949   GstStructure *s;
1950   const GValue *val;
1951   GstBuffer *buf;
1952
1953   caps = gst_caps_make_writable (caps);
1954
1955   s = gst_caps_get_structure (caps, 0);
1956   if (gst_structure_has_name (s, "video/x-raw")) {
1957     stream->is_raw = TRUE;
1958     stream->alignment = 32;
1959     if (!gst_structure_has_field (s, "pixel-aspect-ratio"))
1960       gst_structure_set (s, "pixel-aspect-ratio", GST_TYPE_FRACTION,
1961           1, 1, NULL);
1962     if (gst_structure_has_field_typed (s, "palette_data", GST_TYPE_BUFFER)) {
1963       gst_structure_get (s, "palette_data", GST_TYPE_BUFFER,
1964           &stream->rgb8_palette, NULL);
1965       gst_structure_remove_field (s, "palette_data");
1966       return caps;
1967     }
1968   } else if (!gst_structure_has_name (s, "video/x-h264")) {
1969     return caps;
1970   }
1971
1972   GST_DEBUG_OBJECT (avi, "checking caps %" GST_PTR_FORMAT, caps);
1973
1974   /* some muxers put invalid bytestream stuff in h264 extra data */
1975   val = gst_structure_get_value (s, "codec_data");
1976   if (val && (buf = gst_value_get_buffer (val))) {
1977     guint8 *data;
1978     gint size;
1979     GstMapInfo map;
1980
1981     gst_buffer_map (buf, &map, GST_MAP_READ);
1982     data = map.data;
1983     size = map.size;
1984     if (size >= 4) {
1985       guint32 h = GST_READ_UINT32_BE (data);
1986       gst_buffer_unmap (buf, &map);
1987       if (h == 0x01) {
1988         /* can hardly be valid AVC codec data */
1989         GST_DEBUG_OBJECT (avi,
1990             "discarding invalid codec_data containing byte-stream");
1991         /* so do not pretend to downstream that it is packetized avc */
1992         gst_structure_remove_field (s, "codec_data");
1993         /* ... but rather properly parsed bytestream */
1994         gst_structure_set (s, "stream-format", G_TYPE_STRING, "byte-stream",
1995             "alignment", G_TYPE_STRING, "au", NULL);
1996       }
1997     } else {
1998       gst_buffer_unmap (buf, &map);
1999     }
2000   }
2001
2002   return caps;
2003 }
2004
2005 /*
2006  * gst_avi_demux_parse_stream:
2007  * @avi: calling element (used for debugging/errors).
2008  * @buf: input buffer used to parse the stream.
2009  *
2010  * Parses all subchunks in a strl chunk (which defines a single
2011  * stream). Discards the buffer after use. This function will
2012  * increment the stream counter internally.
2013  *
2014  * Returns: whether the stream was identified successfully.
2015  *          Errors are not fatal. It does indicate the stream
2016  *          was skipped.
2017  */
2018 static gboolean
2019 gst_avi_demux_parse_stream (GstAviDemux * avi, GstBuffer * buf)
2020 {
2021   GstAviStream *stream;
2022   GstElementClass *klass;
2023   GstPadTemplate *templ;
2024   GstBuffer *sub = NULL;
2025   guint offset = 4;
2026   guint32 tag = 0;
2027   gchar *codec_name = NULL, *padname = NULL;
2028   const gchar *tag_name;
2029   GstCaps *caps = NULL;
2030   GstPad *pad;
2031   GstElement *element;
2032   gboolean got_strh = FALSE, got_strf = FALSE, got_vprp = FALSE;
2033   gst_riff_vprp *vprp = NULL;
2034   GstEvent *event;
2035   gchar *stream_id;
2036   GstMapInfo map;
2037   gboolean sparse = FALSE;
2038
2039   element = GST_ELEMENT_CAST (avi);
2040
2041   GST_DEBUG_OBJECT (avi, "Parsing stream");
2042
2043   gst_avi_demux_roundup_list (avi, &buf);
2044
2045   if (avi->num_streams >= GST_AVI_DEMUX_MAX_STREAMS) {
2046     GST_WARNING_OBJECT (avi,
2047         "maximum no of streams (%d) exceeded, ignoring stream",
2048         GST_AVI_DEMUX_MAX_STREAMS);
2049     gst_buffer_unref (buf);
2050     /* not a fatal error, let's say */
2051     return TRUE;
2052   }
2053
2054   stream = &avi->stream[avi->num_streams];
2055
2056   /* initial settings */
2057   stream->idx_duration = GST_CLOCK_TIME_NONE;
2058   stream->hdr_duration = GST_CLOCK_TIME_NONE;
2059   stream->duration = GST_CLOCK_TIME_NONE;
2060
2061   while (gst_riff_parse_chunk (element, buf, &offset, &tag, &sub)) {
2062     /* sub can be NULL if the chunk is empty */
2063     if (sub == NULL) {
2064       GST_DEBUG_OBJECT (avi, "ignoring empty chunk %" GST_FOURCC_FORMAT,
2065           GST_FOURCC_ARGS (tag));
2066       continue;
2067     }
2068     switch (tag) {
2069       case GST_RIFF_TAG_strh:
2070       {
2071         gst_riff_strh *strh;
2072
2073         if (got_strh) {
2074           GST_WARNING_OBJECT (avi, "Ignoring additional strh chunk");
2075           break;
2076         }
2077         if (!gst_riff_parse_strh (element, sub, &stream->strh)) {
2078           /* ownership given away */
2079           sub = NULL;
2080           GST_WARNING_OBJECT (avi, "Failed to parse strh chunk");
2081           goto fail;
2082         }
2083         sub = NULL;
2084         strh = stream->strh;
2085         /* sanity check; stream header frame rate matches global header
2086          * frame duration */
2087         if (stream->strh->type == GST_RIFF_FCC_vids) {
2088           GstClockTime s_dur;
2089           GstClockTime h_dur = avi->avih->us_frame * GST_USECOND;
2090
2091           s_dur = gst_util_uint64_scale (GST_SECOND, strh->scale, strh->rate);
2092           GST_DEBUG_OBJECT (avi, "verifying stream framerate %d/%d, "
2093               "frame duration = %d ms", strh->rate, strh->scale,
2094               (gint) (s_dur / GST_MSECOND));
2095           if (h_dur > (10 * GST_MSECOND) && (s_dur > 10 * h_dur)) {
2096             strh->rate = GST_SECOND / GST_USECOND;
2097             strh->scale = h_dur / GST_USECOND;
2098             GST_DEBUG_OBJECT (avi, "correcting stream framerate to %d/%d",
2099                 strh->rate, strh->scale);
2100           }
2101         }
2102         /* determine duration as indicated by header */
2103         stream->hdr_duration = gst_util_uint64_scale ((guint64) strh->length *
2104             strh->scale, GST_SECOND, (guint64) strh->rate);
2105         GST_INFO ("Stream duration according to header: %" GST_TIME_FORMAT,
2106             GST_TIME_ARGS (stream->hdr_duration));
2107         if (stream->hdr_duration == 0)
2108           stream->hdr_duration = GST_CLOCK_TIME_NONE;
2109
2110         got_strh = TRUE;
2111         break;
2112       }
2113       case GST_RIFF_TAG_strf:
2114       {
2115         gboolean res = FALSE;
2116
2117         if (got_strf) {
2118           GST_WARNING_OBJECT (avi, "Ignoring additional strf chunk");
2119           break;
2120         }
2121         if (!got_strh) {
2122           GST_ERROR_OBJECT (avi, "Found strf chunk before strh chunk");
2123           goto fail;
2124         }
2125         switch (stream->strh->type) {
2126           case GST_RIFF_FCC_vids:
2127             stream->is_vbr = TRUE;
2128             res = gst_riff_parse_strf_vids (element, sub,
2129                 &stream->strf.vids, &stream->extradata);
2130             sub = NULL;
2131             GST_DEBUG_OBJECT (element, "marking video as VBR, res %d", res);
2132             break;
2133           case GST_RIFF_FCC_auds:
2134             res =
2135                 gst_riff_parse_strf_auds (element, sub, &stream->strf.auds,
2136                 &stream->extradata);
2137             sub = NULL;
2138             if (!res)
2139               break;
2140             stream->is_vbr = (stream->strh->samplesize == 0)
2141                 && stream->strh->scale > 1
2142                 && stream->strf.auds->blockalign != 1;
2143             GST_DEBUG_OBJECT (element, "marking audio as VBR:%d, res %d",
2144                 stream->is_vbr, res);
2145             /* we need these or we have no way to come up with timestamps */
2146             if ((!stream->is_vbr && !stream->strf.auds->av_bps) ||
2147                 (stream->is_vbr && (!stream->strh->scale ||
2148                         !stream->strh->rate))) {
2149               GST_WARNING_OBJECT (element,
2150                   "invalid audio header, ignoring stream");
2151               goto fail;
2152             }
2153             /* some more sanity checks */
2154             if (stream->is_vbr) {
2155               if (stream->strf.auds->blockalign <= 4) {
2156                 /* that would mean (too) many frames per chunk,
2157                  * so not likely set as expected */
2158                 GST_DEBUG_OBJECT (element,
2159                     "suspicious blockalign %d for VBR audio; "
2160                     "overriding to 1 frame per chunk",
2161                     stream->strf.auds->blockalign);
2162                 /* this should top any likely value */
2163                 stream->strf.auds->blockalign = (1 << 12);
2164               }
2165             }
2166             break;
2167           case GST_RIFF_FCC_iavs:
2168             stream->is_vbr = TRUE;
2169             res = gst_riff_parse_strf_iavs (element, sub,
2170                 &stream->strf.iavs, &stream->extradata);
2171             sub = NULL;
2172             GST_DEBUG_OBJECT (element, "marking iavs as VBR, res %d", res);
2173             break;
2174           case GST_RIFF_FCC_txts:
2175             /* nothing to parse here */
2176             stream->is_vbr = (stream->strh->samplesize == 0)
2177                 && (stream->strh->scale > 1);
2178             res = TRUE;
2179             break;
2180           default:
2181             GST_ERROR_OBJECT (avi,
2182                 "Don´t know how to handle stream type %" GST_FOURCC_FORMAT,
2183                 GST_FOURCC_ARGS (stream->strh->type));
2184             break;
2185         }
2186         if (sub) {
2187           gst_buffer_unref (sub);
2188           sub = NULL;
2189         }
2190         if (!res)
2191           goto fail;
2192         got_strf = TRUE;
2193         break;
2194       }
2195       case GST_RIFF_TAG_vprp:
2196       {
2197         if (got_vprp) {
2198           GST_WARNING_OBJECT (avi, "Ignoring additional vprp chunk");
2199           break;
2200         }
2201         if (!got_strh) {
2202           GST_ERROR_OBJECT (avi, "Found vprp chunk before strh chunk");
2203           goto fail;
2204         }
2205         if (!got_strf) {
2206           GST_ERROR_OBJECT (avi, "Found vprp chunk before strf chunk");
2207           goto fail;
2208         }
2209
2210         if (!gst_avi_demux_riff_parse_vprp (element, sub, &vprp)) {
2211           GST_WARNING_OBJECT (avi, "Failed to parse vprp chunk");
2212           /* not considered fatal */
2213           g_free (vprp);
2214           vprp = NULL;
2215         } else
2216           got_vprp = TRUE;
2217         sub = NULL;
2218         break;
2219       }
2220       case GST_RIFF_TAG_strd:
2221         if (stream->initdata)
2222           gst_buffer_unref (stream->initdata);
2223         stream->initdata = sub;
2224         if (sub != NULL) {
2225           gst_avi_demux_parse_strd (avi, sub);
2226           sub = NULL;
2227         }
2228         break;
2229       case GST_RIFF_TAG_strn:
2230         g_free (stream->name);
2231
2232         gst_buffer_map (sub, &map, GST_MAP_READ);
2233
2234         if (avi->globaltags == NULL)
2235           avi->globaltags = gst_tag_list_new_empty ();
2236         parse_tag_value (avi, avi->globaltags, GST_TAG_TITLE,
2237             map.data, map.size);
2238
2239         if (gst_tag_list_get_string (avi->globaltags, GST_TAG_TITLE,
2240                 &stream->name))
2241           GST_DEBUG_OBJECT (avi, "stream name: %s", stream->name);
2242
2243         gst_buffer_unmap (sub, &map);
2244         gst_buffer_unref (sub);
2245         sub = NULL;
2246         break;
2247       case GST_RIFF_IDIT:
2248         gst_avi_demux_parse_idit (avi, sub);
2249         break;
2250       default:
2251         if (tag == GST_MAKE_FOURCC ('i', 'n', 'd', 'x') ||
2252             tag == GST_MAKE_FOURCC ('i', 'x', '0' + avi->num_streams / 10,
2253                 '0' + avi->num_streams % 10)) {
2254           g_free (stream->indexes);
2255           gst_avi_demux_parse_superindex (avi, sub, &stream->indexes);
2256           stream->superindex = TRUE;
2257           sub = NULL;
2258           break;
2259         }
2260         GST_WARNING_OBJECT (avi,
2261             "Unknown stream header tag %" GST_FOURCC_FORMAT ", ignoring",
2262             GST_FOURCC_ARGS (tag));
2263         /* Only get buffer for debugging if the memdump is needed  */
2264         if (gst_debug_category_get_threshold (GST_CAT_DEFAULT) >= 9) {
2265           GstMapInfo map;
2266
2267           gst_buffer_map (sub, &map, GST_MAP_READ);
2268           GST_MEMDUMP_OBJECT (avi, "Unknown stream header tag", map.data,
2269               map.size);
2270           gst_buffer_unmap (sub, &map);
2271         }
2272         /* fall-through */
2273       case GST_RIFF_TAG_JUNQ:
2274       case GST_RIFF_TAG_JUNK:
2275         break;
2276     }
2277     if (sub != NULL) {
2278       gst_buffer_unref (sub);
2279       sub = NULL;
2280     }
2281   }
2282
2283   if (!got_strh) {
2284     GST_WARNING_OBJECT (avi, "Failed to find strh chunk");
2285     goto fail;
2286   }
2287
2288   if (!got_strf) {
2289     GST_WARNING_OBJECT (avi, "Failed to find strf chunk");
2290     goto fail;
2291   }
2292
2293   /* get class to figure out the template */
2294   klass = GST_ELEMENT_GET_CLASS (avi);
2295
2296   /* we now have all info, let´s set up a pad and a caps and be done */
2297   /* create stream name + pad */
2298   switch (stream->strh->type) {
2299     case GST_RIFF_FCC_vids:{
2300       guint32 fourcc;
2301
2302       fourcc = (stream->strf.vids->compression) ?
2303           stream->strf.vids->compression : stream->strh->fcc_handler;
2304       caps = gst_riff_create_video_caps (fourcc, stream->strh,
2305           stream->strf.vids, stream->extradata, stream->initdata, &codec_name);
2306
2307       /* DXSB is XSUB, and it is placed inside a vids */
2308       if (!caps || (fourcc != GST_MAKE_FOURCC ('D', 'X', 'S', 'B') &&
2309               fourcc != GST_MAKE_FOURCC ('D', 'X', 'S', 'A'))) {
2310         padname = g_strdup_printf ("video_%u", avi->num_v_streams);
2311         templ = gst_element_class_get_pad_template (klass, "video_%u");
2312         if (!caps) {
2313           caps = gst_caps_new_simple ("video/x-avi-unknown", "fourcc",
2314               G_TYPE_INT, fourcc, NULL);
2315         } else if (got_vprp && vprp) {
2316           guint32 aspect_n, aspect_d;
2317           gint n, d;
2318
2319           aspect_n = vprp->aspect >> 16;
2320           aspect_d = vprp->aspect & 0xffff;
2321           /* calculate the pixel aspect ratio using w/h and aspect ratio */
2322           n = aspect_n * stream->strf.vids->height;
2323           d = aspect_d * stream->strf.vids->width;
2324           if (n && d)
2325             gst_caps_set_simple (caps, "pixel-aspect-ratio", GST_TYPE_FRACTION,
2326                 n, d, NULL);
2327         }
2328         caps = gst_avi_demux_check_caps (avi, stream, caps);
2329         tag_name = GST_TAG_VIDEO_CODEC;
2330         avi->num_v_streams++;
2331       } else {
2332         padname = g_strdup_printf ("subpicture_%u", avi->num_sp_streams);
2333         templ = gst_element_class_get_pad_template (klass, "subpicture_%u");
2334         tag_name = NULL;
2335         avi->num_sp_streams++;
2336         sparse = TRUE;
2337       }
2338       break;
2339     }
2340     case GST_RIFF_FCC_auds:{
2341       /* FIXME: Do something with the channel reorder map */
2342       padname = g_strdup_printf ("audio_%u", avi->num_a_streams);
2343       templ = gst_element_class_get_pad_template (klass, "audio_%u");
2344       caps = gst_riff_create_audio_caps (stream->strf.auds->format,
2345           stream->strh, stream->strf.auds, stream->extradata,
2346           stream->initdata, &codec_name, NULL);
2347       if (!caps) {
2348         caps = gst_caps_new_simple ("audio/x-avi-unknown", "codec_id",
2349             G_TYPE_INT, stream->strf.auds->format, NULL);
2350       }
2351       tag_name = GST_TAG_AUDIO_CODEC;
2352       avi->num_a_streams++;
2353       break;
2354     }
2355     case GST_RIFF_FCC_iavs:{
2356       guint32 fourcc = stream->strh->fcc_handler;
2357
2358       padname = g_strdup_printf ("video_%u", avi->num_v_streams);
2359       templ = gst_element_class_get_pad_template (klass, "video_%u");
2360       caps = gst_riff_create_iavs_caps (fourcc, stream->strh,
2361           stream->strf.iavs, stream->extradata, stream->initdata, &codec_name);
2362       if (!caps) {
2363         caps = gst_caps_new_simple ("video/x-avi-unknown", "fourcc",
2364             G_TYPE_INT, fourcc, NULL);
2365       }
2366       tag_name = GST_TAG_VIDEO_CODEC;
2367       avi->num_v_streams++;
2368       break;
2369     }
2370     case GST_RIFF_FCC_txts:{
2371       padname = g_strdup_printf ("subtitle_%u", avi->num_t_streams);
2372       templ = gst_element_class_get_pad_template (klass, "subtitle_%u");
2373       caps = gst_caps_new_empty_simple ("application/x-subtitle-avi");
2374       tag_name = NULL;
2375       avi->num_t_streams++;
2376       sparse = TRUE;
2377       break;
2378     }
2379     default:
2380       g_return_val_if_reached (FALSE);
2381   }
2382
2383   /* no caps means no stream */
2384   if (!caps) {
2385     GST_ERROR_OBJECT (element, "Did not find caps for stream %s", padname);
2386     goto fail;
2387   }
2388
2389   GST_DEBUG_OBJECT (element, "codec-name=%s", codec_name ? codec_name : "NULL");
2390   GST_DEBUG_OBJECT (element, "caps=%" GST_PTR_FORMAT, caps);
2391
2392   /* set proper settings and add it */
2393   if (stream->pad)
2394     gst_object_unref (stream->pad);
2395   pad = stream->pad = gst_pad_new_from_template (templ, padname);
2396   g_free (padname);
2397
2398   gst_pad_use_fixed_caps (pad);
2399 #if 0
2400   gst_pad_set_formats_function (pad,
2401       GST_DEBUG_FUNCPTR (gst_avi_demux_get_src_formats));
2402   gst_pad_set_event_mask_function (pad,
2403       GST_DEBUG_FUNCPTR (gst_avi_demux_get_event_mask));
2404 #endif
2405   gst_pad_set_event_function (pad,
2406       GST_DEBUG_FUNCPTR (gst_avi_demux_handle_src_event));
2407   gst_pad_set_query_function (pad,
2408       GST_DEBUG_FUNCPTR (gst_avi_demux_handle_src_query));
2409 #if 0
2410   gst_pad_set_convert_function (pad,
2411       GST_DEBUG_FUNCPTR (gst_avi_demux_src_convert));
2412 #endif
2413
2414   stream->num = avi->num_streams;
2415
2416   stream->start_entry = 0;
2417   stream->step_entry = 0;
2418   stream->stop_entry = 0;
2419
2420   stream->current_entry = -1;
2421   stream->current_total = 0;
2422
2423   stream->discont = TRUE;
2424
2425   stream->total_bytes = 0;
2426   stream->total_blocks = 0;
2427   stream->n_keyframes = 0;
2428
2429   stream->idx_n = 0;
2430   stream->idx_max = 0;
2431
2432   gst_pad_set_element_private (pad, stream);
2433   avi->num_streams++;
2434
2435   gst_pad_set_active (pad, TRUE);
2436   stream_id =
2437       gst_pad_create_stream_id_printf (pad, GST_ELEMENT_CAST (avi), "%03u",
2438       avi->num_streams);
2439
2440   event = gst_pad_get_sticky_event (avi->sinkpad, GST_EVENT_STREAM_START, 0);
2441   if (event) {
2442     if (gst_event_parse_group_id (event, &avi->group_id))
2443       avi->have_group_id = TRUE;
2444     else
2445       avi->have_group_id = FALSE;
2446     gst_event_unref (event);
2447   } else if (!avi->have_group_id) {
2448     avi->have_group_id = TRUE;
2449     avi->group_id = gst_util_group_id_next ();
2450   }
2451
2452   event = gst_event_new_stream_start (stream_id);
2453   if (avi->have_group_id)
2454     gst_event_set_group_id (event, avi->group_id);
2455   if (sparse)
2456     gst_event_set_stream_flags (event, GST_STREAM_FLAG_SPARSE);
2457
2458   gst_pad_push_event (pad, event);
2459   g_free (stream_id);
2460   gst_pad_set_caps (pad, caps);
2461   gst_caps_unref (caps);
2462
2463   /* make tags */
2464   if (codec_name && tag_name) {
2465     if (!stream->taglist)
2466       stream->taglist = gst_tag_list_new_empty ();
2467
2468     avi->got_tags = TRUE;
2469
2470     gst_tag_list_add (stream->taglist, GST_TAG_MERGE_APPEND, tag_name,
2471         codec_name, NULL);
2472   }
2473
2474   g_free (vprp);
2475   g_free (codec_name);
2476   gst_buffer_unref (buf);
2477
2478   return TRUE;
2479
2480   /* ERRORS */
2481 fail:
2482   {
2483     /* unref any mem that may be in use */
2484     if (buf)
2485       gst_buffer_unref (buf);
2486     if (sub)
2487       gst_buffer_unref (sub);
2488     g_free (vprp);
2489     g_free (codec_name);
2490     gst_avi_demux_reset_stream (avi, stream);
2491     avi->num_streams++;
2492     return FALSE;
2493   }
2494 }
2495
2496 /*
2497  * gst_avi_demux_parse_odml:
2498  * @avi: calling element (used for debug/error).
2499  * @buf: input buffer to be used for parsing.
2500  *
2501  * Read an openDML-2.0 extension header. Fills in the frame number
2502  * in the avi demuxer object when reading succeeds.
2503  */
2504 static void
2505 gst_avi_demux_parse_odml (GstAviDemux * avi, GstBuffer * buf)
2506 {
2507   guint32 tag = 0;
2508   guint offset = 4;
2509   GstBuffer *sub = NULL;
2510
2511   while (gst_riff_parse_chunk (GST_ELEMENT_CAST (avi), buf, &offset, &tag,
2512           &sub)) {
2513     switch (tag) {
2514       case GST_RIFF_TAG_dmlh:{
2515         gst_riff_dmlh dmlh, *_dmlh;
2516         GstMapInfo map;
2517
2518         /* sub == NULL is possible and means an empty buffer */
2519         if (sub == NULL)
2520           goto next;
2521
2522         gst_buffer_map (sub, &map, GST_MAP_READ);
2523
2524         /* check size */
2525         if (map.size < sizeof (gst_riff_dmlh)) {
2526           GST_ERROR_OBJECT (avi,
2527               "DMLH entry is too small (%" G_GSIZE_FORMAT " bytes, %d needed)",
2528               map.size, (int) sizeof (gst_riff_dmlh));
2529           gst_buffer_unmap (sub, &map);
2530           goto next;
2531         }
2532         _dmlh = (gst_riff_dmlh *) map.data;
2533         dmlh.totalframes = GST_READ_UINT32_LE (&_dmlh->totalframes);
2534         gst_buffer_unmap (sub, &map);
2535
2536         GST_INFO_OBJECT (avi, "dmlh tag found: totalframes: %u",
2537             dmlh.totalframes);
2538
2539         avi->avih->tot_frames = dmlh.totalframes;
2540         goto next;
2541       }
2542
2543       default:
2544         GST_WARNING_OBJECT (avi,
2545             "Unknown tag %" GST_FOURCC_FORMAT " in ODML header",
2546             GST_FOURCC_ARGS (tag));
2547         /* Only get buffer for debugging if the memdump is needed  */
2548         if (gst_debug_category_get_threshold (GST_CAT_DEFAULT) >= 9) {
2549           GstMapInfo map;
2550
2551           gst_buffer_map (sub, &map, GST_MAP_READ);
2552           GST_MEMDUMP_OBJECT (avi, "Unknown ODML tag", map.data, map.size);
2553           gst_buffer_unmap (sub, &map);
2554         }
2555         /* fall-through */
2556       case GST_RIFF_TAG_JUNQ:
2557       case GST_RIFF_TAG_JUNK:
2558       next:
2559         /* skip and move to next chunk */
2560         if (sub) {
2561           gst_buffer_unref (sub);
2562           sub = NULL;
2563         }
2564         break;
2565     }
2566   }
2567   if (buf)
2568     gst_buffer_unref (buf);
2569 }
2570
2571 /* Index helper */
2572 static guint
2573 gst_avi_demux_index_last (GstAviDemux * avi, GstAviStream * stream)
2574 {
2575   return stream->idx_n;
2576 }
2577
2578 /* find a previous entry in the index with the given flags */
2579 static guint
2580 gst_avi_demux_index_prev (GstAviDemux * avi, GstAviStream * stream,
2581     guint last, gboolean keyframe)
2582 {
2583   GstAviIndexEntry *entry;
2584   guint i;
2585
2586   for (i = last; i > 0; i--) {
2587     entry = &stream->index[i - 1];
2588     if (!keyframe || ENTRY_IS_KEYFRAME (entry)) {
2589       return i - 1;
2590     }
2591   }
2592   return 0;
2593 }
2594
2595 static guint
2596 gst_avi_demux_index_next (GstAviDemux * avi, GstAviStream * stream,
2597     guint last, gboolean keyframe)
2598 {
2599   GstAviIndexEntry *entry;
2600   gint i;
2601
2602   for (i = last + 1; i < stream->idx_n; i++) {
2603     entry = &stream->index[i];
2604     if (!keyframe || ENTRY_IS_KEYFRAME (entry)) {
2605       return i;
2606     }
2607   }
2608   return stream->idx_n - 1;
2609 }
2610
2611 static guint
2612 gst_avi_demux_index_entry_search (GstAviIndexEntry * entry, guint64 * total)
2613 {
2614   if (entry->total < *total)
2615     return -1;
2616   else if (entry->total > *total)
2617     return 1;
2618   return 0;
2619 }
2620
2621 /*
2622  * gst_avi_demux_index_for_time:
2623  * @avi: Avi object
2624  * @stream: the stream
2625  * @time: a time position
2626  * @next: whether to look for entry before or after @time
2627  *
2628  * Finds the index entry which time is less/more or equal than the requested time.
2629  * Try to avoid binary search when we can convert the time to an index
2630  * position directly (for example for video frames with a fixed duration).
2631  *
2632  * Returns: the found position in the index.
2633  */
2634 static guint
2635 gst_avi_demux_index_for_time (GstAviDemux * avi,
2636     GstAviStream * stream, guint64 time, gboolean next)
2637 {
2638   guint index = -1;
2639   guint64 total;
2640
2641   GST_LOG_OBJECT (avi, "search time:%" GST_TIME_FORMAT, GST_TIME_ARGS (time));
2642
2643   /* easy (and common) cases */
2644   if (time == 0 || stream->idx_n == 0)
2645     return 0;
2646   if (time >= stream->idx_duration)
2647     return stream->idx_n - 1;
2648
2649   /* figure out where we need to go. For that we convert the time to an
2650    * index entry or we convert it to a total and then do a binary search. */
2651   if (stream->is_vbr) {
2652     /* VBR stream next timestamp */
2653     if (stream->strh->type == GST_RIFF_FCC_auds) {
2654       total = avi_stream_convert_time_to_frames_unchecked (stream, time);
2655     } else {
2656       index = avi_stream_convert_time_to_frames_unchecked (stream, time);
2657       /* this entry typically undershoots the target time,
2658        * so check a bit more if next needed */
2659       if (next && index != -1) {
2660         GstClockTime itime =
2661             avi_stream_convert_frames_to_time_unchecked (stream, index);
2662         if (itime < time && index + 1 < stream->idx_n)
2663           index++;
2664       }
2665     }
2666   } else if (stream->strh->type == GST_RIFF_FCC_auds) {
2667     /* constant rate stream */
2668     total = avi_stream_convert_time_to_bytes_unchecked (stream, time);
2669   } else
2670     return -1;
2671
2672   if (index == -1) {
2673     GstAviIndexEntry *entry;
2674
2675     /* no index, find index with binary search on total */
2676     GST_LOG_OBJECT (avi, "binary search for entry with total %"
2677         G_GUINT64_FORMAT, total);
2678
2679     entry = gst_util_array_binary_search (stream->index,
2680         stream->idx_n, sizeof (GstAviIndexEntry),
2681         (GCompareDataFunc) gst_avi_demux_index_entry_search,
2682         next ? GST_SEARCH_MODE_AFTER : GST_SEARCH_MODE_BEFORE, &total, NULL);
2683
2684     if (entry == NULL) {
2685       GST_LOG_OBJECT (avi, "not found, assume index 0");
2686       index = 0;
2687     } else {
2688       index = entry - stream->index;
2689       GST_LOG_OBJECT (avi, "found at %u", index);
2690     }
2691   } else {
2692     GST_LOG_OBJECT (avi, "converted time to index %u", index);
2693   }
2694
2695   return index;
2696 }
2697
2698 static inline GstAviStream *
2699 gst_avi_demux_stream_for_id (GstAviDemux * avi, guint32 id)
2700 {
2701   guint stream_nr;
2702   GstAviStream *stream;
2703
2704   /* get the stream for this entry */
2705   stream_nr = CHUNKID_TO_STREAMNR (id);
2706   if (G_UNLIKELY (stream_nr >= avi->num_streams)) {
2707     GST_WARNING_OBJECT (avi,
2708         "invalid stream nr %d (0x%08x, %" GST_FOURCC_FORMAT ")", stream_nr, id,
2709         GST_FOURCC_ARGS (id));
2710     return NULL;
2711   }
2712   stream = &avi->stream[stream_nr];
2713   if (G_UNLIKELY (!stream->strh)) {
2714     GST_WARNING_OBJECT (avi, "Unhandled stream %d, skipping", stream_nr);
2715     return NULL;
2716   }
2717   return stream;
2718 }
2719
2720 /*
2721  * gst_avi_demux_parse_index:
2722  * @avi: calling element (used for debugging/errors).
2723  * @buf: buffer containing the full index.
2724  *
2725  * Read index entries from the provided buffer.
2726  * The buffer should contain a GST_RIFF_TAG_idx1 chunk.
2727  */
2728 static gboolean
2729 gst_avi_demux_parse_index (GstAviDemux * avi, GstBuffer * buf)
2730 {
2731   GstMapInfo map;
2732   guint i, num, n;
2733   gst_riff_index_entry *index;
2734   GstClockTime stamp;
2735   GstAviStream *stream;
2736   GstAviIndexEntry entry;
2737   guint32 id;
2738
2739   if (!buf)
2740     return FALSE;
2741
2742   gst_buffer_map (buf, &map, GST_MAP_READ);
2743
2744   stamp = gst_util_get_timestamp ();
2745
2746   /* see how many items in the index */
2747   num = map.size / sizeof (gst_riff_index_entry);
2748   if (num == 0)
2749     goto empty_list;
2750
2751   GST_INFO_OBJECT (avi, "Parsing index, nr_entries = %6d", num);
2752
2753   index = (gst_riff_index_entry *) map.data;
2754
2755   /* figure out if the index is 0 based or relative to the MOVI start */
2756   entry.offset = GST_READ_UINT32_LE (&index[0].offset);
2757   if (entry.offset < avi->offset) {
2758     avi->index_offset = avi->offset + 8;
2759     GST_DEBUG ("index_offset = %" G_GUINT64_FORMAT, avi->index_offset);
2760   } else {
2761     avi->index_offset = 0;
2762     GST_DEBUG ("index is 0 based");
2763   }
2764
2765   for (i = 0, n = 0; i < num; i++) {
2766     id = GST_READ_UINT32_LE (&index[i].id);
2767     entry.offset = GST_READ_UINT32_LE (&index[i].offset);
2768
2769     /* some sanity checks */
2770     if (G_UNLIKELY (id == GST_RIFF_rec || id == 0 ||
2771             (entry.offset == 0 && n > 0)))
2772       continue;
2773
2774     /* get the stream for this entry */
2775     stream = gst_avi_demux_stream_for_id (avi, id);
2776     if (G_UNLIKELY (!stream))
2777       continue;
2778
2779     /* handle offset and size */
2780     entry.offset += avi->index_offset + 8;
2781     entry.size = GST_READ_UINT32_LE (&index[i].size);
2782
2783     /* handle flags */
2784     if (stream->strh->type == GST_RIFF_FCC_auds) {
2785       /* all audio frames are keyframes */
2786       ENTRY_SET_KEYFRAME (&entry);
2787     } else if (stream->strh->type == GST_RIFF_FCC_vids &&
2788         stream->strf.vids->compression == GST_RIFF_DXSB) {
2789       /* all xsub frames are keyframes */
2790       ENTRY_SET_KEYFRAME (&entry);
2791     } else {
2792       guint32 flags;
2793       /* else read flags */
2794       flags = GST_READ_UINT32_LE (&index[i].flags);
2795       if (flags & GST_RIFF_IF_KEYFRAME) {
2796         ENTRY_SET_KEYFRAME (&entry);
2797       } else {
2798         ENTRY_UNSET_KEYFRAME (&entry);
2799       }
2800     }
2801
2802     /* and add */
2803     if (G_UNLIKELY (!gst_avi_demux_add_index (avi, stream, num, &entry)))
2804       goto out_of_mem;
2805
2806     n++;
2807   }
2808   gst_buffer_unmap (buf, &map);
2809   gst_buffer_unref (buf);
2810
2811   /* get stream stats now */
2812   avi->have_index = gst_avi_demux_do_index_stats (avi);
2813
2814   stamp = gst_util_get_timestamp () - stamp;
2815   GST_DEBUG_OBJECT (avi, "index parsing took %" GST_TIME_FORMAT,
2816       GST_TIME_ARGS (stamp));
2817
2818   return TRUE;
2819
2820   /* ERRORS */
2821 empty_list:
2822   {
2823     GST_DEBUG_OBJECT (avi, "empty index");
2824     gst_buffer_unmap (buf, &map);
2825     gst_buffer_unref (buf);
2826     return FALSE;
2827   }
2828 out_of_mem:
2829   {
2830     GST_ELEMENT_ERROR (avi, RESOURCE, NO_SPACE_LEFT, (NULL),
2831         ("Cannot allocate memory for %u*%u=%u bytes",
2832             (guint) sizeof (GstAviIndexEntry), num,
2833             (guint) sizeof (GstAviIndexEntry) * num));
2834     gst_buffer_unmap (buf, &map);
2835     gst_buffer_unref (buf);
2836     return FALSE;
2837   }
2838 }
2839
2840 /*
2841  * gst_avi_demux_stream_index:
2842  * @avi: avi demuxer object.
2843  *
2844  * Seeks to index and reads it.
2845  */
2846 static void
2847 gst_avi_demux_stream_index (GstAviDemux * avi)
2848 {
2849   GstFlowReturn res;
2850   guint64 offset = avi->offset;
2851   GstBuffer *buf = NULL;
2852   guint32 tag;
2853   guint32 size;
2854   GstMapInfo map;
2855
2856   GST_DEBUG ("demux stream index at offset %" G_GUINT64_FORMAT, offset);
2857
2858   /* get chunk information */
2859   res = gst_pad_pull_range (avi->sinkpad, offset, 8, &buf);
2860   if (res != GST_FLOW_OK)
2861     goto pull_failed;
2862
2863   gst_buffer_map (buf, &map, GST_MAP_READ);
2864   if (map.size < 8)
2865     goto too_small;
2866
2867   /* check tag first before blindy trying to read 'size' bytes */
2868   tag = GST_READ_UINT32_LE (map.data);
2869   size = GST_READ_UINT32_LE (map.data + 4);
2870   if (tag == GST_RIFF_TAG_LIST) {
2871     /* this is the movi tag */
2872     GST_DEBUG_OBJECT (avi, "skip LIST chunk, size %" G_GUINT32_FORMAT,
2873         (8 + GST_ROUND_UP_2 (size)));
2874     offset += 8 + GST_ROUND_UP_2 (size);
2875     gst_buffer_unmap (buf, &map);
2876     gst_buffer_unref (buf);
2877
2878     buf = NULL;
2879     res = gst_pad_pull_range (avi->sinkpad, offset, 8, &buf);
2880     if (res != GST_FLOW_OK)
2881       goto pull_failed;
2882
2883     gst_buffer_map (buf, &map, GST_MAP_READ);
2884     if (map.size < 8)
2885       goto too_small;
2886
2887     tag = GST_READ_UINT32_LE (map.data);
2888     size = GST_READ_UINT32_LE (map.data + 4);
2889   }
2890   gst_buffer_unmap (buf, &map);
2891   gst_buffer_unref (buf);
2892
2893   if (tag != GST_RIFF_TAG_idx1)
2894     goto no_index;
2895   if (!size)
2896     goto zero_index;
2897
2898   GST_DEBUG ("index found at offset %" G_GUINT64_FORMAT, offset);
2899
2900   /* read chunk, advance offset */
2901   if (gst_riff_read_chunk (GST_ELEMENT_CAST (avi),
2902           avi->sinkpad, &offset, &tag, &buf) != GST_FLOW_OK)
2903     return;
2904
2905   GST_DEBUG ("will parse index chunk size %" G_GSIZE_FORMAT " for tag %"
2906       GST_FOURCC_FORMAT, gst_buffer_get_size (buf), GST_FOURCC_ARGS (tag));
2907
2908   gst_avi_demux_parse_index (avi, buf);
2909
2910 #ifndef GST_DISABLE_GST_DEBUG
2911   /* debug our indexes */
2912   {
2913     gint i;
2914     GstAviStream *stream;
2915
2916     for (i = 0; i < avi->num_streams; i++) {
2917       stream = &avi->stream[i];
2918       GST_DEBUG_OBJECT (avi, "stream %u: %u frames, %" G_GINT64_FORMAT " bytes",
2919           i, stream->idx_n, stream->total_bytes);
2920     }
2921   }
2922 #endif
2923   return;
2924
2925   /* ERRORS */
2926 pull_failed:
2927   {
2928     GST_DEBUG_OBJECT (avi,
2929         "pull range failed: pos=%" G_GUINT64_FORMAT " size=8", offset);
2930     return;
2931   }
2932 too_small:
2933   {
2934     GST_DEBUG_OBJECT (avi, "Buffer is too small");
2935     gst_buffer_unmap (buf, &map);
2936     gst_buffer_unref (buf);
2937     return;
2938   }
2939 no_index:
2940   {
2941     GST_WARNING_OBJECT (avi,
2942         "No index data (idx1) after movi chunk, but %" GST_FOURCC_FORMAT,
2943         GST_FOURCC_ARGS (tag));
2944     return;
2945   }
2946 zero_index:
2947   {
2948     GST_WARNING_OBJECT (avi, "Empty index data (idx1) after movi chunk");
2949     return;
2950   }
2951 }
2952
2953 /*
2954  * gst_avi_demux_stream_index_push:
2955  * @avi: avi demuxer object.
2956  *
2957  * Read index.
2958  */
2959 static void
2960 gst_avi_demux_stream_index_push (GstAviDemux * avi)
2961 {
2962   guint64 offset = avi->idx1_offset;
2963   GstBuffer *buf;
2964   guint32 tag;
2965   guint32 size;
2966
2967   GST_DEBUG ("demux stream index at offset %" G_GUINT64_FORMAT, offset);
2968
2969   /* get chunk information */
2970   if (!gst_avi_demux_peek_chunk (avi, &tag, &size))
2971     return;
2972
2973   /* check tag first before blindly trying to read 'size' bytes */
2974   if (tag == GST_RIFF_TAG_LIST) {
2975     /* this is the movi tag */
2976     GST_DEBUG_OBJECT (avi, "skip LIST chunk, size %" G_GUINT32_FORMAT,
2977         (8 + GST_ROUND_UP_2 (size)));
2978     avi->idx1_offset = offset + 8 + GST_ROUND_UP_2 (size);
2979     /* issue seek to allow chain function to handle it and return! */
2980     perform_seek_to_offset (avi, avi->idx1_offset, avi->segment_seqnum);
2981     return;
2982   }
2983
2984   if (tag != GST_RIFF_TAG_idx1)
2985     goto no_index;
2986
2987   GST_DEBUG ("index found at offset %" G_GUINT64_FORMAT, offset);
2988
2989   /* flush chunk header */
2990   gst_adapter_flush (avi->adapter, 8);
2991   /* read chunk payload */
2992   buf = gst_adapter_take_buffer (avi->adapter, size);
2993   if (!buf)
2994     goto pull_failed;
2995   /* advance offset */
2996   offset += 8 + GST_ROUND_UP_2 (size);
2997
2998   GST_DEBUG ("will parse index chunk size %" G_GSIZE_FORMAT " for tag %"
2999       GST_FOURCC_FORMAT, gst_buffer_get_size (buf), GST_FOURCC_ARGS (tag));
3000
3001   avi->offset = avi->first_movi_offset;
3002   gst_avi_demux_parse_index (avi, buf);
3003
3004 #ifndef GST_DISABLE_GST_DEBUG
3005   /* debug our indexes */
3006   {
3007     gint i;
3008     GstAviStream *stream;
3009
3010     for (i = 0; i < avi->num_streams; i++) {
3011       stream = &avi->stream[i];
3012       GST_DEBUG_OBJECT (avi, "stream %u: %u frames, %" G_GINT64_FORMAT " bytes",
3013           i, stream->idx_n, stream->total_bytes);
3014     }
3015   }
3016 #endif
3017   return;
3018
3019   /* ERRORS */
3020 pull_failed:
3021   {
3022     GST_DEBUG_OBJECT (avi,
3023         "taking data from adapter failed: pos=%" G_GUINT64_FORMAT " size=%u",
3024         offset, size);
3025     return;
3026   }
3027 no_index:
3028   {
3029     GST_WARNING_OBJECT (avi,
3030         "No index data (idx1) after movi chunk, but %" GST_FOURCC_FORMAT,
3031         GST_FOURCC_ARGS (tag));
3032     return;
3033   }
3034 }
3035
3036 /*
3037  * gst_avi_demux_peek_tag:
3038  *
3039  * Returns the tag and size of the next chunk
3040  */
3041 static GstFlowReturn
3042 gst_avi_demux_peek_tag (GstAviDemux * avi, guint64 offset, guint32 * tag,
3043     guint * size)
3044 {
3045   GstFlowReturn res;
3046   GstBuffer *buf = NULL;
3047   GstMapInfo map;
3048
3049   res = gst_pad_pull_range (avi->sinkpad, offset, 8, &buf);
3050   if (res != GST_FLOW_OK)
3051     goto pull_failed;
3052
3053   gst_buffer_map (buf, &map, GST_MAP_READ);
3054   if (map.size != 8)
3055     goto wrong_size;
3056
3057   *tag = GST_READ_UINT32_LE (map.data);
3058   *size = GST_READ_UINT32_LE (map.data + 4);
3059
3060   GST_LOG_OBJECT (avi, "Tag[%" GST_FOURCC_FORMAT "] (size:%d) %"
3061       G_GINT64_FORMAT " -- %" G_GINT64_FORMAT, GST_FOURCC_ARGS (*tag),
3062       *size, offset + 8, offset + 8 + (gint64) * size);
3063
3064 done:
3065   gst_buffer_unmap (buf, &map);
3066   gst_buffer_unref (buf);
3067
3068   return res;
3069
3070   /* ERRORS */
3071 pull_failed:
3072   {
3073     GST_DEBUG_OBJECT (avi, "pull_ranged returned %s", gst_flow_get_name (res));
3074     return res;
3075   }
3076 wrong_size:
3077   {
3078     GST_DEBUG_OBJECT (avi, "got %" G_GSIZE_FORMAT " bytes which is <> 8 bytes",
3079         map.size);
3080     res = GST_FLOW_ERROR;
3081     goto done;
3082   }
3083 }
3084
3085 /*
3086  * gst_avi_demux_next_data_buffer:
3087  *
3088  * Returns the offset and size of the next buffer
3089  * Position is the position of the buffer (after tag and size)
3090  */
3091 static GstFlowReturn
3092 gst_avi_demux_next_data_buffer (GstAviDemux * avi, guint64 * offset,
3093     guint32 * tag, guint * size)
3094 {
3095   guint64 off = *offset;
3096   guint _size = 0;
3097   GstFlowReturn res;
3098
3099   do {
3100     res = gst_avi_demux_peek_tag (avi, off, tag, &_size);
3101     if (res != GST_FLOW_OK)
3102       break;
3103     if (*tag == GST_RIFF_TAG_LIST || *tag == GST_RIFF_TAG_RIFF)
3104       off += 8 + 4;             /* skip tag + size + subtag */
3105     else {
3106       *offset = off + 8;
3107       *size = _size;
3108       break;
3109     }
3110   } while (TRUE);
3111
3112   return res;
3113 }
3114
3115 /*
3116  * gst_avi_demux_stream_scan:
3117  * @avi: calling element (used for debugging/errors).
3118  *
3119  * Scan the file for all chunks to "create" a new index.
3120  * pull-range based
3121  */
3122 static gboolean
3123 gst_avi_demux_stream_scan (GstAviDemux * avi)
3124 {
3125   GstFlowReturn res;
3126   GstAviStream *stream;
3127   guint64 pos = 0;
3128   guint64 length;
3129   gint64 tmplength;
3130   guint32 tag = 0;
3131   guint num;
3132
3133   /* FIXME:
3134    * - implement non-seekable source support.
3135    */
3136   GST_DEBUG_OBJECT (avi, "Creating index");
3137
3138   /* get the size of the file */
3139   if (!gst_pad_peer_query_duration (avi->sinkpad, GST_FORMAT_BYTES, &tmplength))
3140     return FALSE;
3141   length = tmplength;
3142
3143   /* guess the total amount of entries we expect */
3144   num = 16000;
3145
3146   while (TRUE) {
3147     GstAviIndexEntry entry;
3148     guint size = 0;
3149
3150     /* start reading data buffers to find the id and offset */
3151     res = gst_avi_demux_next_data_buffer (avi, &pos, &tag, &size);
3152     if (G_UNLIKELY (res != GST_FLOW_OK))
3153       break;
3154
3155     /* get stream */
3156     stream = gst_avi_demux_stream_for_id (avi, tag);
3157     if (G_UNLIKELY (!stream))
3158       goto next;
3159
3160     /* we can't figure out the keyframes, assume they all are */
3161     entry.flags = GST_AVI_KEYFRAME;
3162     entry.offset = pos;
3163     entry.size = size;
3164
3165     /* and add to the index of this stream */
3166     if (G_UNLIKELY (!gst_avi_demux_add_index (avi, stream, num, &entry)))
3167       goto out_of_mem;
3168
3169   next:
3170     /* update position */
3171     pos += GST_ROUND_UP_2 (size);
3172     if (G_UNLIKELY (pos > length)) {
3173       GST_WARNING_OBJECT (avi,
3174           "Stopping index lookup since we are further than EOF");
3175       break;
3176     }
3177   }
3178
3179   /* collect stats */
3180   avi->have_index = gst_avi_demux_do_index_stats (avi);
3181
3182   return TRUE;
3183
3184   /* ERRORS */
3185 out_of_mem:
3186   {
3187     GST_ELEMENT_ERROR (avi, RESOURCE, NO_SPACE_LEFT, (NULL),
3188         ("Cannot allocate memory for %u*%u=%u bytes",
3189             (guint) sizeof (GstAviIndexEntry), num,
3190             (guint) sizeof (GstAviIndexEntry) * num));
3191     return FALSE;
3192   }
3193 }
3194
3195 static void
3196 gst_avi_demux_calculate_durations_from_index (GstAviDemux * avi)
3197 {
3198   guint i;
3199   GstClockTime total;
3200   GstAviStream *stream;
3201
3202   total = GST_CLOCK_TIME_NONE;
3203
3204   /* all streams start at a timestamp 0 */
3205   for (i = 0; i < avi->num_streams; i++) {
3206     GstClockTime duration, hduration;
3207     gst_riff_strh *strh;
3208
3209     stream = &avi->stream[i];
3210     if (G_UNLIKELY (!stream || !stream->idx_n || !(strh = stream->strh)))
3211       continue;
3212
3213     /* get header duration for the stream */
3214     hduration = stream->hdr_duration;
3215     /* index duration calculated during parsing */
3216     duration = stream->idx_duration;
3217
3218     /* now pick a good duration */
3219     if (GST_CLOCK_TIME_IS_VALID (duration)) {
3220       /* index gave valid duration, use that */
3221       GST_INFO ("Stream %p duration according to index: %" GST_TIME_FORMAT,
3222           stream, GST_TIME_ARGS (duration));
3223     } else {
3224       /* fall back to header info to calculate a duration */
3225       duration = hduration;
3226     }
3227     GST_INFO ("Setting duration of stream #%d to %" GST_TIME_FORMAT,
3228         i, GST_TIME_ARGS (duration));
3229     /* set duration for the stream */
3230     stream->duration = duration;
3231
3232     /* find total duration */
3233     if (total == GST_CLOCK_TIME_NONE ||
3234         (GST_CLOCK_TIME_IS_VALID (duration) && duration > total))
3235       total = duration;
3236   }
3237
3238   if (GST_CLOCK_TIME_IS_VALID (total) && (total > 0)) {
3239     /* now update the duration for those streams where we had none */
3240     for (i = 0; i < avi->num_streams; i++) {
3241       stream = &avi->stream[i];
3242
3243       if (!GST_CLOCK_TIME_IS_VALID (stream->duration)
3244           || stream->duration == 0) {
3245         stream->duration = total;
3246
3247         GST_INFO ("Stream %p duration according to total: %" GST_TIME_FORMAT,
3248             stream, GST_TIME_ARGS (total));
3249       }
3250     }
3251   }
3252
3253   /* and set the total duration in the segment. */
3254   GST_INFO ("Setting total duration to: %" GST_TIME_FORMAT,
3255       GST_TIME_ARGS (total));
3256
3257   avi->segment.duration = total;
3258 }
3259
3260 /* returns FALSE if there are no pads to deliver event to,
3261  * otherwise TRUE (whatever the outcome of event sending),
3262  * takes ownership of the event. */
3263 static gboolean
3264 gst_avi_demux_push_event (GstAviDemux * avi, GstEvent * event)
3265 {
3266   gboolean result = FALSE;
3267   gint i;
3268
3269   GST_DEBUG_OBJECT (avi, "sending %s event to %d streams",
3270       GST_EVENT_TYPE_NAME (event), avi->num_streams);
3271
3272   for (i = 0; i < avi->num_streams; i++) {
3273     GstAviStream *stream = &avi->stream[i];
3274
3275     if (stream->pad) {
3276       result = TRUE;
3277       gst_pad_push_event (stream->pad, gst_event_ref (event));
3278     }
3279   }
3280   gst_event_unref (event);
3281   return result;
3282 }
3283
3284 static void
3285 gst_avi_demux_check_seekability (GstAviDemux * avi)
3286 {
3287   GstQuery *query;
3288   gboolean seekable = FALSE;
3289   gint64 start = -1, stop = -1;
3290
3291   query = gst_query_new_seeking (GST_FORMAT_BYTES);
3292   if (!gst_pad_peer_query (avi->sinkpad, query)) {
3293     GST_DEBUG_OBJECT (avi, "seeking query failed");
3294     goto done;
3295   }
3296
3297   gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
3298
3299   /* try harder to query upstream size if we didn't get it the first time */
3300   if (seekable && stop == -1) {
3301     GST_DEBUG_OBJECT (avi, "doing duration query to fix up unset stop");
3302     gst_pad_peer_query_duration (avi->sinkpad, GST_FORMAT_BYTES, &stop);
3303   }
3304
3305   /* if upstream doesn't know the size, it's likely that it's not seekable in
3306    * practice even if it technically may be seekable */
3307   if (seekable && (start != 0 || stop <= start)) {
3308     GST_DEBUG_OBJECT (avi, "seekable but unknown start/stop -> disable");
3309     seekable = FALSE;
3310   }
3311
3312 done:
3313   GST_INFO_OBJECT (avi, "seekable: %d (%" G_GUINT64_FORMAT " - %"
3314       G_GUINT64_FORMAT ")", seekable, start, stop);
3315   avi->seekable = seekable;
3316
3317   gst_query_unref (query);
3318 }
3319
3320 /*
3321  * Read AVI headers when streaming
3322  */
3323 static GstFlowReturn
3324 gst_avi_demux_stream_header_push (GstAviDemux * avi)
3325 {
3326   GstFlowReturn ret = GST_FLOW_OK;
3327   guint32 tag = 0;
3328   guint32 ltag = 0;
3329   guint32 size = 0;
3330   const guint8 *data;
3331   GstBuffer *buf = NULL, *sub = NULL;
3332   guint offset = 4;
3333   gint i;
3334   GstTagList *tags = NULL;
3335   guint8 fourcc[4];
3336
3337   GST_DEBUG ("Reading and parsing avi headers: %d", avi->header_state);
3338
3339   switch (avi->header_state) {
3340     case GST_AVI_DEMUX_HEADER_TAG_LIST:
3341     again:
3342       if (gst_avi_demux_peek_chunk (avi, &tag, &size)) {
3343         avi->offset += 8 + GST_ROUND_UP_2 (size);
3344         if (tag != GST_RIFF_TAG_LIST)
3345           goto header_no_list;
3346
3347         gst_adapter_flush (avi->adapter, 8);
3348         /* Find the 'hdrl' LIST tag */
3349         GST_DEBUG ("Reading %d bytes", size);
3350         buf = gst_adapter_take_buffer (avi->adapter, size);
3351
3352         gst_buffer_extract (buf, 0, fourcc, 4);
3353
3354         if (GST_READ_UINT32_LE (fourcc) != GST_RIFF_LIST_hdrl) {
3355           GST_WARNING_OBJECT (avi, "Invalid AVI header (no hdrl at start): %"
3356               GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag));
3357           gst_buffer_unref (buf);
3358           goto again;
3359         }
3360
3361         /* mind padding */
3362         if (size & 1)
3363           gst_adapter_flush (avi->adapter, 1);
3364
3365         GST_DEBUG ("'hdrl' LIST tag found. Parsing next chunk");
3366
3367         gst_avi_demux_roundup_list (avi, &buf);
3368
3369         /* the hdrl starts with a 'avih' header */
3370         if (!gst_riff_parse_chunk (GST_ELEMENT_CAST (avi), buf, &offset, &tag,
3371                 &sub))
3372           goto header_no_avih;
3373
3374         if (tag != GST_RIFF_TAG_avih)
3375           goto header_no_avih;
3376
3377         if (!gst_avi_demux_parse_avih (avi, sub, &avi->avih))
3378           goto header_wrong_avih;
3379
3380         GST_DEBUG_OBJECT (avi, "AVI header ok, reading elemnts from header");
3381
3382         /* now, read the elements from the header until the end */
3383         while (gst_riff_parse_chunk (GST_ELEMENT_CAST (avi), buf, &offset, &tag,
3384                 &sub)) {
3385           /* sub can be NULL on empty tags */
3386           if (!sub)
3387             continue;
3388
3389           switch (tag) {
3390             case GST_RIFF_TAG_LIST:
3391               if (gst_buffer_get_size (sub) < 4)
3392                 goto next;
3393
3394               gst_buffer_extract (sub, 0, fourcc, 4);
3395
3396               switch (GST_READ_UINT32_LE (fourcc)) {
3397                 case GST_RIFF_LIST_strl:
3398                   if (!(gst_avi_demux_parse_stream (avi, sub))) {
3399                     sub = NULL;
3400                     GST_ELEMENT_WARNING (avi, STREAM, DEMUX, (NULL),
3401                         ("failed to parse stream, ignoring"));
3402                     goto next;
3403                   }
3404                   sub = NULL;
3405                   goto next;
3406                 case GST_RIFF_LIST_odml:
3407                   gst_avi_demux_parse_odml (avi, sub);
3408                   sub = NULL;
3409                   break;
3410                 default:
3411                   GST_WARNING_OBJECT (avi,
3412                       "Unknown list %" GST_FOURCC_FORMAT " in AVI header",
3413                       GST_FOURCC_ARGS (GST_READ_UINT32_LE (fourcc)));
3414                   /* fall-through */
3415                 case GST_RIFF_TAG_JUNQ:
3416                 case GST_RIFF_TAG_JUNK:
3417                   goto next;
3418               }
3419               break;
3420             case GST_RIFF_IDIT:
3421               gst_avi_demux_parse_idit (avi, sub);
3422               goto next;
3423             default:
3424               GST_WARNING_OBJECT (avi,
3425                   "Unknown tag %" GST_FOURCC_FORMAT " in AVI header",
3426                   GST_FOURCC_ARGS (tag));
3427               /* Only get buffer for debugging if the memdump is needed  */
3428               if (gst_debug_category_get_threshold (GST_CAT_DEFAULT) >= 9) {
3429                 GstMapInfo map;
3430
3431                 gst_buffer_map (sub, &map, GST_MAP_READ);
3432                 GST_MEMDUMP_OBJECT (avi, "Unknown tag", map.data, map.size);
3433                 gst_buffer_unmap (sub, &map);
3434               }
3435               /* fall-through */
3436             case GST_RIFF_TAG_JUNQ:
3437             case GST_RIFF_TAG_JUNK:
3438             next:
3439               /* move to next chunk */
3440               if (sub)
3441                 gst_buffer_unref (sub);
3442               sub = NULL;
3443               break;
3444           }
3445         }
3446         gst_buffer_unref (buf);
3447         GST_DEBUG ("elements parsed");
3448
3449         /* check parsed streams */
3450         if (avi->num_streams == 0) {
3451           goto no_streams;
3452         } else if (avi->num_streams != avi->avih->streams) {
3453           GST_WARNING_OBJECT (avi,
3454               "Stream header mentioned %d streams, but %d available",
3455               avi->avih->streams, avi->num_streams);
3456         }
3457         GST_DEBUG ("Get junk and info next");
3458         avi->header_state = GST_AVI_DEMUX_HEADER_INFO;
3459       } else {
3460         /* Need more data */
3461         return ret;
3462       }
3463       /* fall-though */
3464     case GST_AVI_DEMUX_HEADER_INFO:
3465       GST_DEBUG_OBJECT (avi, "skipping junk between header and data ...");
3466       while (TRUE) {
3467         if (gst_adapter_available (avi->adapter) < 12)
3468           return GST_FLOW_OK;
3469
3470         data = gst_adapter_map (avi->adapter, 12);
3471         tag = GST_READ_UINT32_LE (data);
3472         size = GST_READ_UINT32_LE (data + 4);
3473         ltag = GST_READ_UINT32_LE (data + 8);
3474         gst_adapter_unmap (avi->adapter);
3475
3476         if (tag == GST_RIFF_TAG_LIST) {
3477           switch (ltag) {
3478             case GST_RIFF_LIST_movi:
3479               gst_adapter_flush (avi->adapter, 12);
3480               if (!avi->first_movi_offset)
3481                 avi->first_movi_offset = avi->offset;
3482               avi->offset += 12;
3483               avi->idx1_offset = avi->offset + size - 4;
3484               goto skipping_done;
3485             case GST_RIFF_LIST_INFO:
3486               GST_DEBUG ("Found INFO chunk");
3487               if (gst_avi_demux_peek_chunk (avi, &tag, &size)) {
3488                 GST_DEBUG ("got size %d", size);
3489                 avi->offset += 12;
3490                 gst_adapter_flush (avi->adapter, 12);
3491                 if (size > 4) {
3492                   buf = gst_adapter_take_buffer (avi->adapter, size - 4);
3493                   /* mind padding */
3494                   if (size & 1)
3495                     gst_adapter_flush (avi->adapter, 1);
3496                   gst_riff_parse_info (GST_ELEMENT_CAST (avi), buf, &tags);
3497                   if (tags) {
3498                     if (avi->globaltags) {
3499                       gst_tag_list_insert (avi->globaltags, tags,
3500                           GST_TAG_MERGE_REPLACE);
3501                       gst_tag_list_unref (tags);
3502                     } else {
3503                       avi->globaltags = tags;
3504                     }
3505                   }
3506                   tags = NULL;
3507                   gst_buffer_unref (buf);
3508
3509                   avi->offset += GST_ROUND_UP_2 (size) - 4;
3510                 } else {
3511                   GST_DEBUG ("skipping INFO LIST prefix");
3512                 }
3513               } else {
3514                 /* Need more data */
3515                 return GST_FLOW_OK;
3516               }
3517               break;
3518             default:
3519               if (gst_avi_demux_peek_chunk (avi, &tag, &size) || size == 0) {
3520                 /* accept 0 size buffer here */
3521                 avi->abort_buffering = FALSE;
3522                 avi->offset += 8 + GST_ROUND_UP_2 (size);
3523                 gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
3524               } else {
3525                 /* Need more data */
3526                 return GST_FLOW_OK;
3527               }
3528               break;
3529           }
3530         } else {
3531           if (gst_avi_demux_peek_chunk (avi, &tag, &size) || size == 0) {
3532             /* accept 0 size buffer here */
3533             avi->abort_buffering = FALSE;
3534             avi->offset += 8 + GST_ROUND_UP_2 (size);
3535             gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
3536           } else {
3537             /* Need more data */
3538             return GST_FLOW_OK;
3539           }
3540         }
3541       }
3542       break;
3543     default:
3544       GST_WARNING ("unhandled header state: %d", avi->header_state);
3545       break;
3546   }
3547 skipping_done:
3548
3549   GST_DEBUG_OBJECT (avi, "skipping done ... (streams=%u, stream[0].indexes=%p)",
3550       avi->num_streams, avi->stream[0].indexes);
3551
3552   GST_DEBUG ("Found movi chunk. Starting to stream data");
3553   avi->state = GST_AVI_DEMUX_MOVI;
3554
3555   /* no indexes in push mode, but it still sets some variables */
3556   gst_avi_demux_calculate_durations_from_index (avi);
3557
3558   gst_avi_demux_expose_streams (avi, TRUE);
3559
3560   /* prepare all streams for index 0 */
3561   for (i = 0; i < avi->num_streams; i++)
3562     avi->stream[i].current_entry = 0;
3563
3564   /* create initial NEWSEGMENT event */
3565   if (avi->seg_event)
3566     gst_event_unref (avi->seg_event);
3567   avi->seg_event = gst_event_new_segment (&avi->segment);
3568   if (avi->segment_seqnum)
3569     gst_event_set_seqnum (avi->seg_event, avi->segment_seqnum);
3570
3571   gst_avi_demux_check_seekability (avi);
3572
3573   /* at this point we know all the streams and we can signal the no more
3574    * pads signal */
3575   GST_DEBUG_OBJECT (avi, "signaling no more pads");
3576   gst_element_no_more_pads (GST_ELEMENT_CAST (avi));
3577
3578   return GST_FLOW_OK;
3579
3580   /* ERRORS */
3581 no_streams:
3582   {
3583     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("No streams found"));
3584     return GST_FLOW_ERROR;
3585   }
3586 header_no_list:
3587   {
3588     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3589         ("Invalid AVI header (no LIST at start): %"
3590             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3591     return GST_FLOW_ERROR;
3592   }
3593 header_no_avih:
3594   {
3595     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3596         ("Invalid AVI header (no avih at start): %"
3597             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3598     if (sub)
3599       gst_buffer_unref (sub);
3600
3601     gst_buffer_unref (buf);
3602     return GST_FLOW_ERROR;
3603   }
3604 header_wrong_avih:
3605   {
3606     gst_buffer_unref (buf);
3607     return GST_FLOW_ERROR;
3608   }
3609 }
3610
3611 static void
3612 gst_avi_demux_add_date_tag (GstAviDemux * avi, gint y, gint m, gint d,
3613     gint h, gint min, gint s)
3614 {
3615   GDate *date;
3616   GstDateTime *dt;
3617
3618   date = g_date_new_dmy (d, m, y);
3619   if (!g_date_valid (date)) {
3620     /* bogus date */
3621     GST_WARNING_OBJECT (avi, "Refusing to add invalid date %d-%d-%d", y, m, d);
3622     g_date_free (date);
3623     return;
3624   }
3625
3626   dt = gst_date_time_new_local_time (y, m, d, h, min, s);
3627
3628   if (avi->globaltags == NULL)
3629     avi->globaltags = gst_tag_list_new_empty ();
3630
3631   gst_tag_list_add (avi->globaltags, GST_TAG_MERGE_REPLACE, GST_TAG_DATE, date,
3632       NULL);
3633   g_date_free (date);
3634   if (dt) {
3635     gst_tag_list_add (avi->globaltags, GST_TAG_MERGE_REPLACE, GST_TAG_DATE_TIME,
3636         dt, NULL);
3637     gst_date_time_unref (dt);
3638   }
3639 }
3640
3641 static void
3642 gst_avi_demux_parse_idit_nums_only (GstAviDemux * avi, gchar * data)
3643 {
3644   gint y, m, d;
3645   gint hr = 0, min = 0, sec = 0;
3646   gint ret;
3647
3648   GST_DEBUG ("data : '%s'", data);
3649
3650   ret = sscanf (data, "%d:%d:%d %d:%d:%d", &y, &m, &d, &hr, &min, &sec);
3651   if (ret < 3) {
3652     /* Attempt YYYY/MM/DD/ HH:MM variant (found in CASIO cameras) */
3653     ret = sscanf (data, "%04d/%02d/%02d/ %d:%d", &y, &m, &d, &hr, &min);
3654     if (ret < 3) {
3655       GST_WARNING_OBJECT (avi, "Failed to parse IDIT tag");
3656       return;
3657     }
3658   }
3659   gst_avi_demux_add_date_tag (avi, y, m, d, hr, min, sec);
3660 }
3661
3662 static gint
3663 get_month_num (gchar * data, guint size)
3664 {
3665   if (g_ascii_strncasecmp (data, "jan", 3) == 0) {
3666     return 1;
3667   } else if (g_ascii_strncasecmp (data, "feb", 3) == 0) {
3668     return 2;
3669   } else if (g_ascii_strncasecmp (data, "mar", 3) == 0) {
3670     return 3;
3671   } else if (g_ascii_strncasecmp (data, "apr", 3) == 0) {
3672     return 4;
3673   } else if (g_ascii_strncasecmp (data, "may", 3) == 0) {
3674     return 5;
3675   } else if (g_ascii_strncasecmp (data, "jun", 3) == 0) {
3676     return 6;
3677   } else if (g_ascii_strncasecmp (data, "jul", 3) == 0) {
3678     return 7;
3679   } else if (g_ascii_strncasecmp (data, "aug", 3) == 0) {
3680     return 8;
3681   } else if (g_ascii_strncasecmp (data, "sep", 3) == 0) {
3682     return 9;
3683   } else if (g_ascii_strncasecmp (data, "oct", 3) == 0) {
3684     return 10;
3685   } else if (g_ascii_strncasecmp (data, "nov", 3) == 0) {
3686     return 11;
3687   } else if (g_ascii_strncasecmp (data, "dec", 3) == 0) {
3688     return 12;
3689   }
3690
3691   return 0;
3692 }
3693
3694 static void
3695 gst_avi_demux_parse_idit_text (GstAviDemux * avi, gchar * data)
3696 {
3697   gint year, month, day;
3698   gint hour, min, sec;
3699   gint ret;
3700   gchar weekday[4];
3701   gchar monthstr[4];
3702
3703   ret = sscanf (data, "%3s %3s %d %d:%d:%d %d", weekday, monthstr, &day, &hour,
3704       &min, &sec, &year);
3705   if (ret != 7) {
3706     GST_WARNING_OBJECT (avi, "Failed to parse IDIT tag");
3707     return;
3708   }
3709   month = get_month_num (monthstr, strlen (monthstr));
3710   gst_avi_demux_add_date_tag (avi, year, month, day, hour, min, sec);
3711 }
3712
3713 static void
3714 gst_avi_demux_parse_idit (GstAviDemux * avi, GstBuffer * buf)
3715 {
3716   GstMapInfo map;
3717   gchar *ptr;
3718   gsize left;
3719   gchar *safedata = NULL;
3720
3721   gst_buffer_map (buf, &map, GST_MAP_READ);
3722   /*
3723    * According to:
3724    * http://www.eden-foundation.org/products/code/film_date_stamp/index.html
3725    *
3726    * This tag could be in one of the below formats
3727    * 2005:08:17 11:42:43
3728    * THU OCT 26 16:46:04 2006
3729    * Mon Mar  3 09:44:56 2008
3730    *
3731    * FIXME: Our date tag doesn't include hours
3732    */
3733
3734   /* skip eventual initial whitespace */
3735   ptr = (gchar *) map.data;
3736   left = map.size;
3737
3738   while (left > 0 && g_ascii_isspace (ptr[0])) {
3739     ptr++;
3740     left--;
3741   }
3742
3743   if (left == 0) {
3744     goto non_parsable;
3745   }
3746
3747   /* make a safe copy to add a \0 to the end of the string */
3748   safedata = g_strndup (ptr, left);
3749
3750   /* test if the first char is a alpha or a number */
3751   if (g_ascii_isdigit (ptr[0])) {
3752     gst_avi_demux_parse_idit_nums_only (avi, safedata);
3753     g_free (safedata);
3754     gst_buffer_unmap (buf, &map);
3755     return;
3756   } else if (g_ascii_isalpha (ptr[0])) {
3757     gst_avi_demux_parse_idit_text (avi, safedata);
3758     g_free (safedata);
3759     gst_buffer_unmap (buf, &map);
3760     return;
3761   }
3762
3763   g_free (safedata);
3764
3765 non_parsable:
3766   GST_WARNING_OBJECT (avi, "IDIT tag has no parsable info");
3767   gst_buffer_unmap (buf, &map);
3768 }
3769
3770 static void
3771 parse_tag_value (GstAviDemux * avi, GstTagList * taglist, const gchar * type,
3772     guint8 * ptr, guint tsize)
3773 {
3774   static const gchar *env_vars[] = { "GST_AVI_TAG_ENCODING",
3775     "GST_RIFF_TAG_ENCODING", "GST_TAG_ENCODING", NULL
3776   };
3777   GType tag_type;
3778   gchar *val;
3779
3780   tag_type = gst_tag_get_type (type);
3781   val = gst_tag_freeform_string_to_utf8 ((gchar *) ptr, tsize, env_vars);
3782
3783   if (val != NULL) {
3784     if (tag_type == G_TYPE_STRING) {
3785       gst_tag_list_add (taglist, GST_TAG_MERGE_APPEND, type, val, NULL);
3786     } else {
3787       GValue tag_val = { 0, };
3788
3789       g_value_init (&tag_val, tag_type);
3790       if (gst_value_deserialize (&tag_val, val)) {
3791         gst_tag_list_add_value (taglist, GST_TAG_MERGE_APPEND, type, &tag_val);
3792       } else {
3793         GST_WARNING_OBJECT (avi, "could not deserialize '%s' into a "
3794             "tag %s of type %s", val, type, g_type_name (tag_type));
3795       }
3796       g_value_unset (&tag_val);
3797     }
3798     g_free (val);
3799   } else {
3800     GST_WARNING_OBJECT (avi, "could not extract %s tag", type);
3801   }
3802 }
3803
3804 static void
3805 gst_avi_demux_parse_strd (GstAviDemux * avi, GstBuffer * buf)
3806 {
3807   GstMapInfo map;
3808   guint32 tag;
3809
3810   gst_buffer_map (buf, &map, GST_MAP_READ);
3811   if (map.size > 4) {
3812     guint8 *ptr = map.data;
3813     gsize left = map.size;
3814
3815     /* parsing based on
3816      * http://www.eden-foundation.org/products/code/film_date_stamp/index.html
3817      */
3818     tag = GST_READ_UINT32_LE (ptr);
3819     if ((tag == GST_MAKE_FOURCC ('A', 'V', 'I', 'F')) && (map.size > 98)) {
3820       gsize sub_size;
3821
3822       ptr += 98;
3823       left -= 98;
3824       if (!memcmp (ptr, "FUJIFILM", 8)) {
3825         GST_MEMDUMP_OBJECT (avi, "fujifim tag", ptr, 48);
3826
3827         ptr += 10;
3828         left -= 10;
3829         sub_size = 0;
3830         while (ptr[sub_size] && sub_size < left)
3831           sub_size++;
3832
3833         if (avi->globaltags == NULL)
3834           avi->globaltags = gst_tag_list_new_empty ();
3835
3836         gst_tag_list_add (avi->globaltags, GST_TAG_MERGE_APPEND,
3837             GST_TAG_DEVICE_MANUFACTURER, "FUJIFILM", NULL);
3838         parse_tag_value (avi, avi->globaltags, GST_TAG_DEVICE_MODEL, ptr,
3839             sub_size);
3840
3841         while (ptr[sub_size] == '\0' && sub_size < left)
3842           sub_size++;
3843
3844         ptr += sub_size;
3845         left -= sub_size;
3846         sub_size = 0;
3847         while (ptr[sub_size] && sub_size < left)
3848           sub_size++;
3849         if (ptr[4] == ':')
3850           ptr[4] = '-';
3851         if (ptr[7] == ':')
3852           ptr[7] = '-';
3853
3854         parse_tag_value (avi, avi->globaltags, GST_TAG_DATE_TIME, ptr,
3855             sub_size);
3856       }
3857     }
3858   }
3859   gst_buffer_unmap (buf, &map);
3860 }
3861
3862 /*
3863  * gst_avi_demux_parse_ncdt:
3864  * @element: caller element (used for debugging/error).
3865  * @buf: input data to be used for parsing, stripped from header.
3866  * @taglist: a pointer to a taglist (returned by this function)
3867  *           containing information about this stream. May be
3868  *           NULL if no supported tags were found.
3869  *
3870  * Parses Nikon metadata from input data.
3871  */
3872 static void
3873 gst_avi_demux_parse_ncdt (GstAviDemux * avi, GstBuffer * buf,
3874     GstTagList ** _taglist)
3875 {
3876   GstMapInfo info;
3877   guint8 *ptr;
3878   gsize left;
3879   guint tsize;
3880   guint32 tag;
3881   const gchar *type;
3882   GstTagList *taglist;
3883
3884   g_return_if_fail (_taglist != NULL);
3885
3886   if (!buf) {
3887     *_taglist = NULL;
3888     return;
3889   }
3890   gst_buffer_map (buf, &info, GST_MAP_READ);
3891
3892   taglist = gst_tag_list_new_empty ();
3893
3894   ptr = info.data;
3895   left = info.size;
3896
3897   while (left > 8) {
3898     tag = GST_READ_UINT32_LE (ptr);
3899     tsize = GST_READ_UINT32_LE (ptr + 4);
3900
3901     GST_MEMDUMP_OBJECT (avi, "tag chunk", ptr, MIN (tsize + 8, left));
3902
3903     left -= 8;
3904     ptr += 8;
3905
3906     GST_DEBUG_OBJECT (avi, "tag %" GST_FOURCC_FORMAT ", size %u",
3907         GST_FOURCC_ARGS (tag), tsize);
3908
3909     if (tsize > left) {
3910       GST_WARNING_OBJECT (avi,
3911           "Tagsize %d is larger than available data %" G_GSIZE_FORMAT,
3912           tsize, left);
3913       tsize = left;
3914     }
3915
3916     /* find out the type of metadata */
3917     switch (tag) {
3918       case GST_RIFF_LIST_nctg:
3919         while (tsize > 4) {
3920           guint16 sub_tag = GST_READ_UINT16_LE (ptr);
3921           guint16 sub_size = GST_READ_UINT16_LE (ptr + 2);
3922
3923           tsize -= 4;
3924           ptr += 4;
3925           left -= 4;
3926
3927           if (sub_size > tsize)
3928             break;
3929
3930           GST_DEBUG_OBJECT (avi, "sub-tag %u, size %u", sub_tag, sub_size);
3931           /* http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/Nikon.html#NCTG
3932            * for some reason the sub_tag has a +2 offset
3933            */
3934           switch (sub_tag) {
3935             case 0x03:         /* Make */
3936               type = GST_TAG_DEVICE_MANUFACTURER;
3937               break;
3938             case 0x04:         /* Model */
3939               type = GST_TAG_DEVICE_MODEL;
3940               break;
3941               /* TODO: 0x05: is software version, like V1.0 */
3942             case 0x06:         /* Software */
3943               type = GST_TAG_ENCODER;
3944               break;
3945             case 0x13:         /* CreationDate */
3946               type = GST_TAG_DATE_TIME;
3947               if (left > 7) {
3948                 if (ptr[4] == ':')
3949                   ptr[4] = '-';
3950                 if (ptr[7] == ':')
3951                   ptr[7] = '-';
3952               }
3953               break;
3954             default:
3955               type = NULL;
3956               break;
3957           }
3958           if (type != NULL && ptr[0] != '\0') {
3959             GST_DEBUG_OBJECT (avi, "mapped tag %u to tag %s", sub_tag, type);
3960
3961             parse_tag_value (avi, taglist, type, ptr, sub_size);
3962           }
3963
3964           ptr += sub_size;
3965           tsize -= sub_size;
3966           left -= sub_size;
3967         }
3968         break;
3969       default:
3970         type = NULL;
3971         GST_WARNING_OBJECT (avi,
3972             "Unknown ncdt (metadata) tag entry %" GST_FOURCC_FORMAT,
3973             GST_FOURCC_ARGS (tag));
3974         GST_MEMDUMP_OBJECT (avi, "Unknown ncdt", ptr, tsize);
3975         break;
3976     }
3977
3978     if (tsize & 1) {
3979       tsize++;
3980       if (tsize > left)
3981         tsize = left;
3982     }
3983
3984     ptr += tsize;
3985     left -= tsize;
3986   }
3987
3988   if (!gst_tag_list_is_empty (taglist)) {
3989     GST_INFO_OBJECT (avi, "extracted tags: %" GST_PTR_FORMAT, taglist);
3990     *_taglist = taglist;
3991   } else {
3992     *_taglist = NULL;
3993     gst_tag_list_unref (taglist);
3994   }
3995   gst_buffer_unmap (buf, &info);
3996
3997   return;
3998 }
3999
4000 /*
4001  * Read full AVI headers.
4002  */
4003 static GstFlowReturn
4004 gst_avi_demux_stream_header_pull (GstAviDemux * avi)
4005 {
4006   GstFlowReturn res;
4007   GstBuffer *buf, *sub = NULL;
4008   guint32 tag;
4009   guint offset = 4;
4010   GstElement *element = GST_ELEMENT_CAST (avi);
4011   GstClockTime stamp;
4012   GstTagList *tags = NULL;
4013   guint8 fourcc[4];
4014
4015   stamp = gst_util_get_timestamp ();
4016
4017   /* the header consists of a 'hdrl' LIST tag */
4018   res = gst_riff_read_chunk (element, avi->sinkpad, &avi->offset, &tag, &buf);
4019   if (res != GST_FLOW_OK)
4020     goto pull_range_failed;
4021   else if (tag != GST_RIFF_TAG_LIST)
4022     goto no_list;
4023   else if (gst_buffer_get_size (buf) < 4)
4024     goto no_header;
4025
4026   GST_DEBUG_OBJECT (avi, "parsing headers");
4027
4028   /* Find the 'hdrl' LIST tag */
4029   gst_buffer_extract (buf, 0, fourcc, 4);
4030   while (GST_READ_UINT32_LE (fourcc) != GST_RIFF_LIST_hdrl) {
4031     GST_LOG_OBJECT (avi, "buffer contains %" GST_FOURCC_FORMAT,
4032         GST_FOURCC_ARGS (GST_READ_UINT32_LE (fourcc)));
4033
4034     /* Eat up */
4035     gst_buffer_unref (buf);
4036
4037     /* read new chunk */
4038     res = gst_riff_read_chunk (element, avi->sinkpad, &avi->offset, &tag, &buf);
4039     if (res != GST_FLOW_OK)
4040       goto pull_range_failed;
4041     else if (tag != GST_RIFF_TAG_LIST)
4042       goto no_list;
4043     else if (gst_buffer_get_size (buf) < 4)
4044       goto no_header;
4045     gst_buffer_extract (buf, 0, fourcc, 4);
4046   }
4047
4048   GST_DEBUG_OBJECT (avi, "hdrl LIST tag found");
4049
4050   gst_avi_demux_roundup_list (avi, &buf);
4051
4052   /* the hdrl starts with a 'avih' header */
4053   if (!gst_riff_parse_chunk (element, buf, &offset, &tag, &sub))
4054     goto no_avih;
4055   else if (tag != GST_RIFF_TAG_avih)
4056     goto no_avih;
4057   else if (!gst_avi_demux_parse_avih (avi, sub, &avi->avih))
4058     goto invalid_avih;
4059
4060   GST_DEBUG_OBJECT (avi, "AVI header ok, reading elements from header");
4061
4062   /* now, read the elements from the header until the end */
4063   while (gst_riff_parse_chunk (element, buf, &offset, &tag, &sub)) {
4064     GstMapInfo map;
4065
4066     /* sub can be NULL on empty tags */
4067     if (!sub)
4068       continue;
4069
4070     gst_buffer_map (sub, &map, GST_MAP_READ);
4071
4072     switch (tag) {
4073       case GST_RIFF_TAG_LIST:
4074         if (map.size < 4)
4075           goto next;
4076
4077         switch (GST_READ_UINT32_LE (map.data)) {
4078           case GST_RIFF_LIST_strl:
4079             gst_buffer_unmap (sub, &map);
4080             if (!(gst_avi_demux_parse_stream (avi, sub))) {
4081               GST_ELEMENT_WARNING (avi, STREAM, DEMUX, (NULL),
4082                   ("failed to parse stream, ignoring"));
4083               sub = NULL;
4084             }
4085             sub = NULL;
4086             goto next;
4087           case GST_RIFF_LIST_odml:
4088             gst_buffer_unmap (sub, &map);
4089             gst_avi_demux_parse_odml (avi, sub);
4090             sub = NULL;
4091             break;
4092           case GST_RIFF_LIST_INFO:
4093             gst_buffer_unmap (sub, &map);
4094             gst_buffer_resize (sub, 4, -1);
4095             gst_riff_parse_info (element, sub, &tags);
4096             if (tags) {
4097               if (avi->globaltags) {
4098                 gst_tag_list_insert (avi->globaltags, tags,
4099                     GST_TAG_MERGE_REPLACE);
4100                 gst_tag_list_unref (tags);
4101               } else {
4102                 avi->globaltags = tags;
4103               }
4104             }
4105             tags = NULL;
4106             gst_buffer_unref (sub);
4107             sub = NULL;
4108             break;
4109           case GST_RIFF_LIST_ncdt:
4110             gst_buffer_unmap (sub, &map);
4111             gst_buffer_resize (sub, 4, -1);
4112             gst_avi_demux_parse_ncdt (avi, sub, &tags);
4113             if (tags) {
4114               if (avi->globaltags) {
4115                 gst_tag_list_insert (avi->globaltags, tags,
4116                     GST_TAG_MERGE_REPLACE);
4117                 gst_tag_list_unref (tags);
4118               } else {
4119                 avi->globaltags = tags;
4120               }
4121             }
4122             tags = NULL;
4123             gst_buffer_unref (sub);
4124             sub = NULL;
4125             break;
4126           default:
4127             GST_WARNING_OBJECT (avi,
4128                 "Unknown list %" GST_FOURCC_FORMAT " in AVI header",
4129                 GST_FOURCC_ARGS (GST_READ_UINT32_LE (map.data)));
4130             GST_MEMDUMP_OBJECT (avi, "Unknown list", map.data, map.size);
4131             /* fall-through */
4132           case GST_RIFF_TAG_JUNQ:
4133           case GST_RIFF_TAG_JUNK:
4134             goto next;
4135         }
4136         break;
4137       case GST_RIFF_IDIT:
4138         gst_avi_demux_parse_idit (avi, sub);
4139         goto next;
4140       default:
4141         GST_WARNING_OBJECT (avi,
4142             "Unknown tag %" GST_FOURCC_FORMAT " in AVI header",
4143             GST_FOURCC_ARGS (tag));
4144         GST_MEMDUMP_OBJECT (avi, "Unknown tag", map.data, map.size);
4145         /* fall-through */
4146       case GST_RIFF_TAG_JUNQ:
4147       case GST_RIFF_TAG_JUNK:
4148       next:
4149         if (sub) {
4150           gst_buffer_unmap (sub, &map);
4151           gst_buffer_unref (sub);
4152         }
4153         sub = NULL;
4154         break;
4155     }
4156   }
4157   gst_buffer_unref (buf);
4158   GST_DEBUG ("elements parsed");
4159
4160   /* check parsed streams */
4161   if (avi->num_streams == 0)
4162     goto no_streams;
4163   else if (avi->num_streams != avi->avih->streams) {
4164     GST_WARNING_OBJECT (avi,
4165         "Stream header mentioned %d streams, but %d available",
4166         avi->avih->streams, avi->num_streams);
4167   }
4168
4169   GST_DEBUG_OBJECT (avi, "skipping junk between header and data, offset=%"
4170       G_GUINT64_FORMAT, avi->offset);
4171
4172   /* Now, find the data (i.e. skip all junk between header and data) */
4173   do {
4174     GstMapInfo map;
4175     guint size;
4176     guint32 tag, ltag;
4177
4178     buf = NULL;
4179     res = gst_pad_pull_range (avi->sinkpad, avi->offset, 12, &buf);
4180     if (res != GST_FLOW_OK) {
4181       GST_DEBUG_OBJECT (avi, "pull_range failure while looking for tags");
4182       goto pull_range_failed;
4183     } else if (gst_buffer_get_size (buf) < 12) {
4184       GST_DEBUG_OBJECT (avi,
4185           "got %" G_GSIZE_FORMAT " bytes which is less than 12 bytes",
4186           gst_buffer_get_size (buf));
4187       gst_buffer_unref (buf);
4188       return GST_FLOW_ERROR;
4189     }
4190
4191     gst_buffer_map (buf, &map, GST_MAP_READ);
4192     tag = GST_READ_UINT32_LE (map.data);
4193     size = GST_READ_UINT32_LE (map.data + 4);
4194     ltag = GST_READ_UINT32_LE (map.data + 8);
4195
4196     GST_DEBUG ("tag %" GST_FOURCC_FORMAT ", size %u",
4197         GST_FOURCC_ARGS (tag), size);
4198     GST_MEMDUMP ("Tag content", map.data, map.size);
4199     gst_buffer_unmap (buf, &map);
4200     gst_buffer_unref (buf);
4201
4202     switch (tag) {
4203       case GST_RIFF_TAG_LIST:{
4204         switch (ltag) {
4205           case GST_RIFF_LIST_movi:
4206             GST_DEBUG_OBJECT (avi,
4207                 "Reached the 'movi' tag, we're done with skipping");
4208             goto skipping_done;
4209           case GST_RIFF_LIST_INFO:
4210             res =
4211                 gst_riff_read_chunk (element, avi->sinkpad, &avi->offset, &tag,
4212                 &buf);
4213             if (res != GST_FLOW_OK) {
4214               GST_DEBUG_OBJECT (avi, "couldn't read INFO chunk");
4215               goto pull_range_failed;
4216             }
4217             GST_DEBUG ("got size %" G_GSIZE_FORMAT, gst_buffer_get_size (buf));
4218             if (size < 4) {
4219               GST_DEBUG ("skipping INFO LIST prefix");
4220               avi->offset += (4 - GST_ROUND_UP_2 (size));
4221               gst_buffer_unref (buf);
4222               continue;
4223             }
4224
4225             sub = gst_buffer_copy_region (buf, GST_BUFFER_COPY_ALL, 4, -1);
4226             gst_riff_parse_info (element, sub, &tags);
4227             if (tags) {
4228               if (avi->globaltags) {
4229                 gst_tag_list_insert (avi->globaltags, tags,
4230                     GST_TAG_MERGE_REPLACE);
4231                 gst_tag_list_unref (tags);
4232               } else {
4233                 avi->globaltags = tags;
4234               }
4235             }
4236             tags = NULL;
4237             if (sub) {
4238               gst_buffer_unref (sub);
4239               sub = NULL;
4240             }
4241             gst_buffer_unref (buf);
4242             /* gst_riff_read_chunk() has already advanced avi->offset */
4243             break;
4244           case GST_RIFF_LIST_ncdt:
4245             res =
4246                 gst_riff_read_chunk (element, avi->sinkpad, &avi->offset, &tag,
4247                 &buf);
4248             if (res != GST_FLOW_OK) {
4249               GST_DEBUG_OBJECT (avi, "couldn't read ncdt chunk");
4250               goto pull_range_failed;
4251             }
4252             GST_DEBUG ("got size %" G_GSIZE_FORMAT, gst_buffer_get_size (buf));
4253             if (size < 4) {
4254               GST_DEBUG ("skipping ncdt LIST prefix");
4255               avi->offset += (4 - GST_ROUND_UP_2 (size));
4256               gst_buffer_unref (buf);
4257               continue;
4258             }
4259
4260             sub = gst_buffer_copy_region (buf, GST_BUFFER_COPY_ALL, 4, -1);
4261             gst_avi_demux_parse_ncdt (avi, sub, &tags);
4262             if (tags) {
4263               if (avi->globaltags) {
4264                 gst_tag_list_insert (avi->globaltags, tags,
4265                     GST_TAG_MERGE_REPLACE);
4266                 gst_tag_list_unref (tags);
4267               } else {
4268                 avi->globaltags = tags;
4269               }
4270             }
4271             tags = NULL;
4272             if (sub) {
4273               gst_buffer_unref (sub);
4274               sub = NULL;
4275             }
4276             gst_buffer_unref (buf);
4277             /* gst_riff_read_chunk() has already advanced avi->offset */
4278             break;
4279           default:
4280             GST_WARNING_OBJECT (avi,
4281                 "Skipping unknown list tag %" GST_FOURCC_FORMAT,
4282                 GST_FOURCC_ARGS (ltag));
4283             avi->offset += 8 + GST_ROUND_UP_2 (size);
4284             break;
4285         }
4286       }
4287         break;
4288       default:
4289         GST_WARNING_OBJECT (avi, "Skipping unknown tag %" GST_FOURCC_FORMAT,
4290             GST_FOURCC_ARGS (tag));
4291         /* Fall-through */
4292       case GST_MAKE_FOURCC ('J', 'U', 'N', 'Q'):
4293       case GST_MAKE_FOURCC ('J', 'U', 'N', 'K'):
4294         /* Only get buffer for debugging if the memdump is needed  */
4295         if (gst_debug_category_get_threshold (GST_CAT_DEFAULT) >= 9) {
4296           buf = NULL;
4297           res = gst_pad_pull_range (avi->sinkpad, avi->offset, size, &buf);
4298           if (res != GST_FLOW_OK) {
4299             GST_DEBUG_OBJECT (avi, "couldn't read INFO chunk");
4300             goto pull_range_failed;
4301           }
4302           gst_buffer_map (buf, &map, GST_MAP_READ);
4303           GST_MEMDUMP ("Junk", map.data, map.size);
4304           gst_buffer_unmap (buf, &map);
4305           gst_buffer_unref (buf);
4306         }
4307         avi->offset += 8 + GST_ROUND_UP_2 (size);
4308         break;
4309     }
4310   } while (1);
4311 skipping_done:
4312
4313   GST_DEBUG_OBJECT (avi, "skipping done ... (streams=%u, stream[0].indexes=%p)",
4314       avi->num_streams, avi->stream[0].indexes);
4315
4316   /* create or read stream index (for seeking) */
4317   if (avi->stream[0].indexes != NULL) {
4318     /* we read a super index already (gst_avi_demux_parse_superindex() ) */
4319     gst_avi_demux_read_subindexes_pull (avi);
4320   }
4321   if (!avi->have_index) {
4322     if (avi->avih->flags & GST_RIFF_AVIH_HASINDEX)
4323       gst_avi_demux_stream_index (avi);
4324
4325     /* still no index, scan */
4326     if (!avi->have_index) {
4327       gst_avi_demux_stream_scan (avi);
4328
4329       /* still no index.. this is a fatal error for now.
4330        * FIXME, we should switch to plain push mode without seeking
4331        * instead of failing. */
4332       if (!avi->have_index)
4333         goto no_index;
4334     }
4335   }
4336   /* use the indexes now to construct nice durations */
4337   gst_avi_demux_calculate_durations_from_index (avi);
4338
4339   gst_avi_demux_expose_streams (avi, FALSE);
4340
4341   /* do initial seek to the default segment values */
4342   gst_avi_demux_do_seek (avi, &avi->segment, 0);
4343
4344   /* create initial NEWSEGMENT event */
4345   if (avi->seg_event)
4346     gst_event_unref (avi->seg_event);
4347   avi->seg_event = gst_event_new_segment (&avi->segment);
4348   if (avi->segment_seqnum)
4349     gst_event_set_seqnum (avi->seg_event, avi->segment_seqnum);
4350
4351   stamp = gst_util_get_timestamp () - stamp;
4352   GST_DEBUG_OBJECT (avi, "pulling header took %" GST_TIME_FORMAT,
4353       GST_TIME_ARGS (stamp));
4354
4355   /* at this point we know all the streams and we can signal the no more
4356    * pads signal */
4357   GST_DEBUG_OBJECT (avi, "signaling no more pads");
4358   gst_element_no_more_pads (GST_ELEMENT_CAST (avi));
4359
4360   return GST_FLOW_OK;
4361
4362   /* ERRORS */
4363 no_list:
4364   {
4365     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
4366         ("Invalid AVI header (no LIST at start): %"
4367             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
4368     gst_buffer_unref (buf);
4369     return GST_FLOW_ERROR;
4370   }
4371 no_header:
4372   {
4373     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
4374         ("Invalid AVI header (no hdrl at start): %"
4375             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
4376     gst_buffer_unref (buf);
4377     return GST_FLOW_ERROR;
4378   }
4379 no_avih:
4380   {
4381     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
4382         ("Invalid AVI header (no avih at start): %"
4383             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
4384     if (sub)
4385       gst_buffer_unref (sub);
4386     gst_buffer_unref (buf);
4387     return GST_FLOW_ERROR;
4388   }
4389 invalid_avih:
4390   {
4391     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
4392         ("Invalid AVI header (cannot parse avih at start)"));
4393     gst_buffer_unref (buf);
4394     return GST_FLOW_ERROR;
4395   }
4396 no_streams:
4397   {
4398     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("No streams found"));
4399     return GST_FLOW_ERROR;
4400   }
4401 no_index:
4402   {
4403     GST_WARNING ("file without or too big index");
4404     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
4405         ("Could not get/create index"));
4406     return GST_FLOW_ERROR;
4407   }
4408 pull_range_failed:
4409   {
4410     if (res == GST_FLOW_FLUSHING)
4411       return res;
4412     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
4413         ("pull_range flow reading header: %s", gst_flow_get_name (res)));
4414     return res;
4415   }
4416 }
4417
4418 /* move a stream to @index */
4419 static void
4420 gst_avi_demux_move_stream (GstAviDemux * avi, GstAviStream * stream,
4421     GstSegment * segment, guint index)
4422 {
4423   GST_DEBUG_OBJECT (avi, "Move stream %d to %u", stream->num, index);
4424
4425   if (segment->rate < 0.0) {
4426     guint next_key;
4427     /* Because we don't know the frame order we need to push from the prev keyframe
4428      * to the next keyframe. If there is a smart decoder downstream he will notice
4429      * that there are too many encoded frames send and return EOS when there
4430      * are enough decoded frames to fill the segment. */
4431     next_key = gst_avi_demux_index_next (avi, stream, index, TRUE);
4432
4433     /* FIXME, we go back to 0, we should look at segment.start. We will however
4434      * stop earlier when the see the timestamp < segment.start */
4435     stream->start_entry = 0;
4436     stream->step_entry = index;
4437     stream->current_entry = index;
4438     stream->stop_entry = next_key;
4439
4440     GST_DEBUG_OBJECT (avi, "reverse seek: start %u, step %u, stop %u",
4441         stream->start_entry, stream->step_entry, stream->stop_entry);
4442   } else {
4443     stream->start_entry = index;
4444     stream->step_entry = index;
4445     stream->stop_entry = gst_avi_demux_index_last (avi, stream);
4446   }
4447   if (stream->current_entry != index) {
4448     GST_DEBUG_OBJECT (avi, "Move DISCONT from %u to %u",
4449         stream->current_entry, index);
4450     stream->current_entry = index;
4451     stream->discont = TRUE;
4452   }
4453
4454   /* update the buffer info */
4455   gst_avi_demux_get_buffer_info (avi, stream, index,
4456       &stream->current_timestamp, &stream->current_ts_end,
4457       &stream->current_offset, &stream->current_offset_end);
4458
4459   GST_DEBUG_OBJECT (avi, "Moved to %u, ts %" GST_TIME_FORMAT
4460       ", ts_end %" GST_TIME_FORMAT ", off %" G_GUINT64_FORMAT
4461       ", off_end %" G_GUINT64_FORMAT, index,
4462       GST_TIME_ARGS (stream->current_timestamp),
4463       GST_TIME_ARGS (stream->current_ts_end), stream->current_offset,
4464       stream->current_offset_end);
4465
4466   GST_DEBUG_OBJECT (avi, "Seeking to offset %" G_GUINT64_FORMAT,
4467       stream->index[index].offset);
4468 }
4469
4470 /*
4471  * Do the actual seeking.
4472  */
4473 static gboolean
4474 gst_avi_demux_do_seek (GstAviDemux * avi, GstSegment * segment,
4475     GstSeekFlags flags)
4476 {
4477   GstClockTime seek_time;
4478   gboolean keyframe, before, after;
4479   guint i, index;
4480   GstAviStream *stream;
4481   gboolean next;
4482
4483   seek_time = segment->position;
4484   keyframe = ! !(flags & GST_SEEK_FLAG_KEY_UNIT);
4485   before = ! !(flags & GST_SEEK_FLAG_SNAP_BEFORE);
4486   after = ! !(flags & GST_SEEK_FLAG_SNAP_AFTER);
4487
4488   GST_DEBUG_OBJECT (avi, "seek to: %" GST_TIME_FORMAT
4489       " keyframe seeking:%d, %s", GST_TIME_ARGS (seek_time), keyframe,
4490       snap_types[before ? 1 : 0][after ? 1 : 0]);
4491
4492   /* FIXME, this code assumes the main stream with keyframes is stream 0,
4493    * which is mostly correct... */
4494   stream = &avi->stream[avi->main_stream];
4495
4496   next = after && !before;
4497   if (segment->rate < 0)
4498     next = !next;
4499
4500   /* get the entry index for the requested position */
4501   index = gst_avi_demux_index_for_time (avi, stream, seek_time, next);
4502   GST_DEBUG_OBJECT (avi, "Got entry %u", index);
4503   if (index == -1)
4504     return FALSE;
4505
4506   /* check if we are already on a keyframe */
4507   if (!ENTRY_IS_KEYFRAME (&stream->index[index])) {
4508     if (next) {
4509       GST_DEBUG_OBJECT (avi, "not keyframe, searching forward");
4510       /* now go to the next keyframe, this is where we should start
4511        * decoding from. */
4512       index = gst_avi_demux_index_next (avi, stream, index, TRUE);
4513       GST_DEBUG_OBJECT (avi, "next keyframe at %u", index);
4514     } else {
4515       GST_DEBUG_OBJECT (avi, "not keyframe, searching back");
4516       /* now go to the previous keyframe, this is where we should start
4517        * decoding from. */
4518       index = gst_avi_demux_index_prev (avi, stream, index, TRUE);
4519       GST_DEBUG_OBJECT (avi, "previous keyframe at %u", index);
4520     }
4521   }
4522
4523   /* move the main stream to this position */
4524   gst_avi_demux_move_stream (avi, stream, segment, index);
4525
4526   if (keyframe) {
4527     /* when seeking to a keyframe, we update the result seek time
4528      * to the time of the keyframe. */
4529     seek_time = stream->current_timestamp;
4530     GST_DEBUG_OBJECT (avi, "keyframe adjusted to %" GST_TIME_FORMAT,
4531         GST_TIME_ARGS (seek_time));
4532     /* the seek time is always the position ... */
4533     segment->position = seek_time;
4534     /* ... and start and stream time when going forwards,
4535      * otherwise only stop time */
4536     if (segment->rate > 0.0)
4537       segment->start = segment->time = seek_time;
4538     else
4539       segment->stop = seek_time;
4540   }
4541
4542   /* now set DISCONT and align the other streams */
4543   for (i = 0; i < avi->num_streams; i++) {
4544     GstAviStream *ostream;
4545
4546     ostream = &avi->stream[i];
4547     if ((ostream == stream) || (ostream->index == NULL))
4548       continue;
4549
4550     /* get the entry index for the requested position */
4551     index = gst_avi_demux_index_for_time (avi, ostream, seek_time, FALSE);
4552     if (index == -1)
4553       continue;
4554
4555     /* move to previous keyframe */
4556     if (!ENTRY_IS_KEYFRAME (&ostream->index[index]))
4557       index = gst_avi_demux_index_prev (avi, ostream, index, TRUE);
4558
4559     gst_avi_demux_move_stream (avi, ostream, segment, index);
4560   }
4561   GST_DEBUG_OBJECT (avi, "done seek to: %" GST_TIME_FORMAT,
4562       GST_TIME_ARGS (seek_time));
4563
4564   return TRUE;
4565 }
4566
4567 /*
4568  * Handle seek event in pull mode.
4569  */
4570 static gboolean
4571 gst_avi_demux_handle_seek (GstAviDemux * avi, GstPad * pad, GstEvent * event)
4572 {
4573   gdouble rate;
4574   GstFormat format;
4575   GstSeekFlags flags;
4576   GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
4577   gint64 cur, stop;
4578   gboolean flush;
4579   gboolean update;
4580   GstSegment seeksegment = { 0, };
4581   gint i;
4582   guint32 seqnum = 0;
4583
4584   if (event) {
4585     GST_DEBUG_OBJECT (avi, "doing seek with event");
4586
4587     gst_event_parse_seek (event, &rate, &format, &flags,
4588         &cur_type, &cur, &stop_type, &stop);
4589     seqnum = gst_event_get_seqnum (event);
4590
4591     /* we have to have a format as the segment format. Try to convert
4592      * if not. */
4593     if (format != GST_FORMAT_TIME) {
4594       gboolean res = TRUE;
4595
4596       if (cur_type != GST_SEEK_TYPE_NONE)
4597         res = gst_pad_query_convert (pad, format, cur, GST_FORMAT_TIME, &cur);
4598       if (res && stop_type != GST_SEEK_TYPE_NONE)
4599         res = gst_pad_query_convert (pad, format, stop, GST_FORMAT_TIME, &stop);
4600       if (!res)
4601         goto no_format;
4602
4603       format = GST_FORMAT_TIME;
4604     }
4605     GST_DEBUG_OBJECT (avi,
4606         "seek requested: rate %g cur %" GST_TIME_FORMAT " stop %"
4607         GST_TIME_FORMAT, rate, GST_TIME_ARGS (cur), GST_TIME_ARGS (stop));
4608     /* FIXME: can we do anything with rate!=1.0 */
4609   } else {
4610     GST_DEBUG_OBJECT (avi, "doing seek without event");
4611     flags = 0;
4612     rate = 1.0;
4613   }
4614
4615   /* save flush flag */
4616   flush = flags & GST_SEEK_FLAG_FLUSH;
4617
4618   if (flush) {
4619     GstEvent *fevent = gst_event_new_flush_start ();
4620
4621     if (seqnum)
4622       gst_event_set_seqnum (fevent, seqnum);
4623     /* for a flushing seek, we send a flush_start on all pads. This will
4624      * eventually stop streaming with a WRONG_STATE. We can thus eventually
4625      * take the STREAM_LOCK. */
4626     GST_DEBUG_OBJECT (avi, "sending flush start");
4627     gst_avi_demux_push_event (avi, gst_event_ref (fevent));
4628     gst_pad_push_event (avi->sinkpad, fevent);
4629   } else {
4630     /* a non-flushing seek, we PAUSE the task so that we can take the
4631      * STREAM_LOCK */
4632     GST_DEBUG_OBJECT (avi, "non flushing seek, pausing task");
4633     gst_pad_pause_task (avi->sinkpad);
4634   }
4635
4636   /* wait for streaming to stop */
4637   GST_DEBUG_OBJECT (avi, "wait for streaming to stop");
4638   GST_PAD_STREAM_LOCK (avi->sinkpad);
4639
4640   /* copy segment, we need this because we still need the old
4641    * segment when we close the current segment. */
4642   memcpy (&seeksegment, &avi->segment, sizeof (GstSegment));
4643
4644   if (event) {
4645     GST_DEBUG_OBJECT (avi, "configuring seek");
4646     gst_segment_do_seek (&seeksegment, rate, format, flags,
4647         cur_type, cur, stop_type, stop, &update);
4648   }
4649   /* do the seek, seeksegment.position contains the new position, this
4650    * actually never fails. */
4651   gst_avi_demux_do_seek (avi, &seeksegment, flags);
4652
4653   if (flush) {
4654     GstEvent *fevent = gst_event_new_flush_stop (TRUE);
4655
4656     if (seqnum)
4657       gst_event_set_seqnum (fevent, seqnum);
4658
4659     GST_DEBUG_OBJECT (avi, "sending flush stop");
4660     gst_avi_demux_push_event (avi, gst_event_ref (fevent));
4661     gst_pad_push_event (avi->sinkpad, fevent);
4662   }
4663
4664   /* now update the real segment info */
4665   memcpy (&avi->segment, &seeksegment, sizeof (GstSegment));
4666
4667   /* post the SEGMENT_START message when we do segmented playback */
4668   if (avi->segment.flags & GST_SEEK_FLAG_SEGMENT) {
4669     GstMessage *segment_start_msg =
4670         gst_message_new_segment_start (GST_OBJECT_CAST (avi),
4671         avi->segment.format, avi->segment.position);
4672     if (seqnum)
4673       gst_message_set_seqnum (segment_start_msg, seqnum);
4674     gst_element_post_message (GST_ELEMENT_CAST (avi), segment_start_msg);
4675   }
4676
4677   /* queue the segment event for the streaming thread. */
4678   if (avi->seg_event)
4679     gst_event_unref (avi->seg_event);
4680   avi->seg_event = gst_event_new_segment (&avi->segment);
4681   if (seqnum)
4682     gst_event_set_seqnum (avi->seg_event, seqnum);
4683   avi->segment_seqnum = seqnum;
4684
4685   if (!avi->streaming) {
4686     gst_pad_start_task (avi->sinkpad, (GstTaskFunction) gst_avi_demux_loop,
4687         avi->sinkpad, NULL);
4688   }
4689   /* reset the last flow and mark discont, seek is always DISCONT */
4690   for (i = 0; i < avi->num_streams; i++) {
4691     GST_DEBUG_OBJECT (avi, "marking DISCONT");
4692     avi->stream[i].discont = TRUE;
4693   }
4694   /* likewise for the whole new segment */
4695   gst_flow_combiner_reset (avi->flowcombiner);
4696   GST_PAD_STREAM_UNLOCK (avi->sinkpad);
4697
4698   return TRUE;
4699
4700   /* ERRORS */
4701 no_format:
4702   {
4703     GST_DEBUG_OBJECT (avi, "unsupported format given, seek aborted.");
4704     return FALSE;
4705   }
4706 }
4707
4708 /*
4709  * Handle seek event in push mode.
4710  */
4711 static gboolean
4712 avi_demux_handle_seek_push (GstAviDemux * avi, GstPad * pad, GstEvent * event)
4713 {
4714   gdouble rate;
4715   GstFormat format;
4716   GstSeekFlags flags;
4717   GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
4718   gint64 cur, stop;
4719   gboolean keyframe, before, after, next;
4720   GstAviStream *stream;
4721   guint index;
4722   guint n, str_num;
4723   guint64 min_offset;
4724   GstSegment seeksegment;
4725   gboolean update;
4726
4727   /* check we have the index */
4728   if (!avi->have_index) {
4729     GST_DEBUG_OBJECT (avi, "no seek index built, seek aborted.");
4730     return FALSE;
4731   } else {
4732     GST_DEBUG_OBJECT (avi, "doing push-based seek with event");
4733   }
4734
4735   gst_event_parse_seek (event, &rate, &format, &flags,
4736       &cur_type, &cur, &stop_type, &stop);
4737
4738   if (format != GST_FORMAT_TIME) {
4739     gboolean res = TRUE;
4740
4741     if (cur_type != GST_SEEK_TYPE_NONE)
4742       res = gst_pad_query_convert (pad, format, cur, GST_FORMAT_TIME, &cur);
4743     if (res && stop_type != GST_SEEK_TYPE_NONE)
4744       res = gst_pad_query_convert (pad, format, stop, GST_FORMAT_TIME, &stop);
4745     if (!res) {
4746       GST_DEBUG_OBJECT (avi, "unsupported format given, seek aborted.");
4747       return FALSE;
4748     }
4749
4750     format = GST_FORMAT_TIME;
4751   }
4752
4753   /* let gst_segment handle any tricky stuff */
4754   GST_DEBUG_OBJECT (avi, "configuring seek");
4755   memcpy (&seeksegment, &avi->segment, sizeof (GstSegment));
4756   gst_segment_do_seek (&seeksegment, rate, format, flags,
4757       cur_type, cur, stop_type, stop, &update);
4758
4759   keyframe = ! !(flags & GST_SEEK_FLAG_KEY_UNIT);
4760   cur = seeksegment.position;
4761   before = ! !(flags & GST_SEEK_FLAG_SNAP_BEFORE);
4762   after = ! !(flags & GST_SEEK_FLAG_SNAP_AFTER);
4763
4764   GST_DEBUG_OBJECT (avi,
4765       "Seek requested: ts %" GST_TIME_FORMAT " stop %" GST_TIME_FORMAT
4766       ", kf %u, %s, rate %lf", GST_TIME_ARGS (cur), GST_TIME_ARGS (stop),
4767       keyframe, snap_types[before ? 1 : 0][after ? 1 : 0], rate);
4768
4769   if (rate < 0) {
4770     GST_DEBUG_OBJECT (avi, "negative rate seek not supported in push mode");
4771     return FALSE;
4772   }
4773
4774   /* FIXME, this code assumes the main stream with keyframes is stream 0,
4775    * which is mostly correct... */
4776   str_num = avi->main_stream;
4777   stream = &avi->stream[str_num];
4778
4779   next = after && !before;
4780   if (seeksegment.rate < 0)
4781     next = !next;
4782
4783   /* get the entry index for the requested position */
4784   index = gst_avi_demux_index_for_time (avi, stream, cur, next);
4785   GST_DEBUG_OBJECT (avi, "str %u: Found entry %u for %" GST_TIME_FORMAT,
4786       str_num, index, GST_TIME_ARGS (cur));
4787   if (index == -1)
4788     return -1;
4789
4790   /* check if we are already on a keyframe */
4791   if (!ENTRY_IS_KEYFRAME (&stream->index[index])) {
4792     if (next) {
4793       GST_DEBUG_OBJECT (avi, "Entry is not a keyframe - searching forward");
4794       /* now go to the next keyframe, this is where we should start
4795        * decoding from. */
4796       index = gst_avi_demux_index_next (avi, stream, index, TRUE);
4797       GST_DEBUG_OBJECT (avi, "Found next keyframe at %u", index);
4798     } else {
4799       GST_DEBUG_OBJECT (avi, "Entry is not a keyframe - searching back");
4800       /* now go to the previous keyframe, this is where we should start
4801        * decoding from. */
4802       index = gst_avi_demux_index_prev (avi, stream, index, TRUE);
4803       GST_DEBUG_OBJECT (avi, "Found previous keyframe at %u", index);
4804     }
4805   }
4806
4807   gst_avi_demux_get_buffer_info (avi, stream, index,
4808       &stream->current_timestamp, &stream->current_ts_end,
4809       &stream->current_offset, &stream->current_offset_end);
4810
4811   /* re-use cur to be the timestamp of the seek as it _will_ be */
4812   cur = stream->current_timestamp;
4813
4814   min_offset = stream->index[index].offset;
4815   avi->seek_kf_offset = min_offset - 8;
4816
4817   GST_DEBUG_OBJECT (avi,
4818       "Seek to: ts %" GST_TIME_FORMAT " (on str %u, idx %u, offset %"
4819       G_GUINT64_FORMAT ")", GST_TIME_ARGS (stream->current_timestamp), str_num,
4820       index, min_offset);
4821
4822   for (n = 0; n < avi->num_streams; n++) {
4823     GstAviStream *str = &avi->stream[n];
4824     guint idx;
4825
4826     if (n == avi->main_stream)
4827       continue;
4828
4829     /* get the entry index for the requested position */
4830     idx = gst_avi_demux_index_for_time (avi, str, cur, FALSE);
4831     GST_DEBUG_OBJECT (avi, "str %u: Found entry %u for %" GST_TIME_FORMAT, n,
4832         idx, GST_TIME_ARGS (cur));
4833     if (idx == -1)
4834       continue;
4835
4836     /* check if we are already on a keyframe */
4837     if (!ENTRY_IS_KEYFRAME (&str->index[idx])) {
4838       if (next) {
4839         GST_DEBUG_OBJECT (avi, "Entry is not a keyframe - searching forward");
4840         /* now go to the next keyframe, this is where we should start
4841          * decoding from. */
4842         idx = gst_avi_demux_index_next (avi, str, idx, TRUE);
4843         GST_DEBUG_OBJECT (avi, "Found next keyframe at %u", idx);
4844       } else {
4845         GST_DEBUG_OBJECT (avi, "Entry is not a keyframe - searching back");
4846         /* now go to the previous keyframe, this is where we should start
4847          * decoding from. */
4848         idx = gst_avi_demux_index_prev (avi, str, idx, TRUE);
4849         GST_DEBUG_OBJECT (avi, "Found previous keyframe at %u", idx);
4850       }
4851     }
4852
4853     gst_avi_demux_get_buffer_info (avi, str, idx,
4854         &str->current_timestamp, &str->current_ts_end,
4855         &str->current_offset, &str->current_offset_end);
4856
4857     if (str->index[idx].offset < min_offset) {
4858       min_offset = str->index[idx].offset;
4859       GST_DEBUG_OBJECT (avi,
4860           "Found an earlier offset at %" G_GUINT64_FORMAT ", str %u",
4861           min_offset, n);
4862       str_num = n;
4863       stream = str;
4864       index = idx;
4865     }
4866   }
4867
4868   GST_DEBUG_OBJECT (avi,
4869       "Seek performed: str %u, offset %" G_GUINT64_FORMAT ", idx %u, ts %"
4870       GST_TIME_FORMAT ", ts_end %" GST_TIME_FORMAT ", off %" G_GUINT64_FORMAT
4871       ", off_end %" G_GUINT64_FORMAT, str_num, min_offset, index,
4872       GST_TIME_ARGS (stream->current_timestamp),
4873       GST_TIME_ARGS (stream->current_ts_end), stream->current_offset,
4874       stream->current_offset_end);
4875
4876   /* index data refers to data, not chunk header (for pull mode convenience) */
4877   min_offset -= 8;
4878   GST_DEBUG_OBJECT (avi, "seeking to chunk at offset %" G_GUINT64_FORMAT,
4879       min_offset);
4880
4881   if (!perform_seek_to_offset (avi, min_offset, gst_event_get_seqnum (event))) {
4882     GST_DEBUG_OBJECT (avi, "seek event failed!");
4883     return FALSE;
4884   }
4885
4886   return TRUE;
4887 }
4888
4889 /*
4890  * Handle whether we can perform the seek event or if we have to let the chain
4891  * function handle seeks to build the seek indexes first.
4892  */
4893 static gboolean
4894 gst_avi_demux_handle_seek_push (GstAviDemux * avi, GstPad * pad,
4895     GstEvent * event)
4896 {
4897   /* check for having parsed index already */
4898   if (!avi->have_index) {
4899     guint64 offset = 0;
4900     gboolean building_index;
4901
4902     GST_OBJECT_LOCK (avi);
4903     /* handle the seek event in the chain function */
4904     avi->state = GST_AVI_DEMUX_SEEK;
4905
4906     /* copy the event */
4907     if (avi->seek_event)
4908       gst_event_unref (avi->seek_event);
4909     avi->seek_event = gst_event_ref (event);
4910
4911     /* set the building_index flag so that only one thread can setup the
4912      * structures for index seeking. */
4913     building_index = avi->building_index;
4914     if (!building_index) {
4915       avi->building_index = TRUE;
4916       if (avi->stream[0].indexes) {
4917         avi->odml_stream = 0;
4918         avi->odml_subidxs = avi->stream[avi->odml_stream].indexes;
4919         offset = avi->odml_subidxs[0];
4920       } else {
4921         offset = avi->idx1_offset;
4922       }
4923     }
4924     GST_OBJECT_UNLOCK (avi);
4925
4926     if (!building_index) {
4927       /* seek to the first subindex or legacy index */
4928       GST_INFO_OBJECT (avi,
4929           "Seeking to legacy index/first subindex at %" G_GUINT64_FORMAT,
4930           offset);
4931       return perform_seek_to_offset (avi, offset, gst_event_get_seqnum (event));
4932     }
4933
4934     /* FIXME: we have to always return true so that we don't block the seek
4935      * thread.
4936      * Note: maybe it is OK to return true if we're still building the index */
4937     return TRUE;
4938   }
4939
4940   return avi_demux_handle_seek_push (avi, pad, event);
4941 }
4942
4943 /*
4944  * Helper for gst_avi_demux_invert()
4945  */
4946 static inline void
4947 swap_line (guint8 * d1, guint8 * d2, guint8 * tmp, gint bytes)
4948 {
4949   memcpy (tmp, d1, bytes);
4950   memcpy (d1, d2, bytes);
4951   memcpy (d2, tmp, bytes);
4952 }
4953
4954
4955 #define gst_avi_demux_is_uncompressed(fourcc)           \
4956   (fourcc == GST_RIFF_DIB ||                            \
4957    fourcc == GST_RIFF_rgb ||                            \
4958    fourcc == GST_RIFF_RGB || fourcc == GST_RIFF_RAW)
4959
4960 /*
4961  * Invert DIB buffers... Takes existing buffer and
4962  * returns either the buffer or a new one (with old
4963  * one dereferenced).
4964  * FIXME: can't we preallocate tmp? and remember stride, bpp?
4965  */
4966 static GstBuffer *
4967 gst_avi_demux_invert (GstAviStream * stream, GstBuffer * buf)
4968 {
4969   gint y, w, h;
4970   gint bpp, stride;
4971   guint8 *tmp = NULL;
4972   GstMapInfo map;
4973   guint32 fourcc;
4974
4975   if (stream->strh->type != GST_RIFF_FCC_vids)
4976     return buf;
4977
4978   if (stream->strf.vids == NULL) {
4979     GST_WARNING ("Failed to retrieve vids for stream");
4980     return buf;
4981   }
4982
4983   fourcc = (stream->strf.vids->compression) ?
4984       stream->strf.vids->compression : stream->strh->fcc_handler;
4985   if (!gst_avi_demux_is_uncompressed (fourcc)) {
4986     return buf;                 /* Ignore non DIB buffers */
4987   }
4988
4989   /* raw rgb data is stored topdown, but instead of inverting the buffer, */
4990   /* some tools just negate the height field in the header (e.g. ffmpeg) */
4991   if (((gint32) stream->strf.vids->height) < 0)
4992     return buf;
4993
4994   h = stream->strf.vids->height;
4995   w = stream->strf.vids->width;
4996   bpp = stream->strf.vids->bit_cnt ? stream->strf.vids->bit_cnt : 8;
4997   stride = GST_ROUND_UP_4 (w * (bpp / 8));
4998
4999   buf = gst_buffer_make_writable (buf);
5000
5001   gst_buffer_map (buf, &map, GST_MAP_READWRITE);
5002   if (map.size < (stride * h)) {
5003     GST_WARNING ("Buffer is smaller than reported Width x Height x Depth");
5004     gst_buffer_unmap (buf, &map);
5005     return buf;
5006   }
5007
5008   tmp = g_malloc (stride);
5009
5010   for (y = 0; y < h / 2; y++) {
5011     swap_line (map.data + stride * y, map.data + stride * (h - 1 - y), tmp,
5012         stride);
5013   }
5014
5015   g_free (tmp);
5016
5017   gst_buffer_unmap (buf, &map);
5018
5019   /* append palette to paletted RGB8 buffer data */
5020   if (stream->rgb8_palette != NULL)
5021     buf = gst_buffer_append (buf, gst_buffer_ref (stream->rgb8_palette));
5022
5023   return buf;
5024 }
5025
5026 #if 0
5027 static void
5028 gst_avi_demux_add_assoc (GstAviDemux * avi, GstAviStream * stream,
5029     GstClockTime timestamp, guint64 offset, gboolean keyframe)
5030 {
5031   /* do not add indefinitely for open-ended streaming */
5032   if (G_UNLIKELY (avi->element_index && avi->seekable)) {
5033     GST_LOG_OBJECT (avi, "adding association %" GST_TIME_FORMAT "-> %"
5034         G_GUINT64_FORMAT, GST_TIME_ARGS (timestamp), offset);
5035     gst_index_add_association (avi->element_index, avi->index_id,
5036         keyframe ? GST_ASSOCIATION_FLAG_KEY_UNIT :
5037         GST_ASSOCIATION_FLAG_DELTA_UNIT, GST_FORMAT_TIME, timestamp,
5038         GST_FORMAT_BYTES, offset, NULL);
5039     /* current_entry is DEFAULT (frame #) */
5040     gst_index_add_association (avi->element_index, stream->index_id,
5041         keyframe ? GST_ASSOCIATION_FLAG_KEY_UNIT :
5042         GST_ASSOCIATION_FLAG_DELTA_UNIT, GST_FORMAT_TIME, timestamp,
5043         GST_FORMAT_BYTES, offset, GST_FORMAT_DEFAULT, stream->current_entry,
5044         NULL);
5045   }
5046 }
5047 #endif
5048
5049 /*
5050  * Returns the aggregated GstFlowReturn.
5051  */
5052 static GstFlowReturn
5053 gst_avi_demux_combine_flows (GstAviDemux * avi, GstAviStream * stream,
5054     GstFlowReturn ret)
5055 {
5056   GST_LOG_OBJECT (avi, "Stream %s:%s flow return: %s",
5057       GST_DEBUG_PAD_NAME (stream->pad), gst_flow_get_name (ret));
5058   ret = gst_flow_combiner_update_pad_flow (avi->flowcombiner, stream->pad, ret);
5059   GST_LOG_OBJECT (avi, "combined to return %s", gst_flow_get_name (ret));
5060
5061   return ret;
5062 }
5063
5064 /* move @stream to the next position in its index */
5065 static GstFlowReturn
5066 gst_avi_demux_advance (GstAviDemux * avi, GstAviStream * stream,
5067     GstFlowReturn ret)
5068 {
5069   guint old_entry, new_entry;
5070
5071   old_entry = stream->current_entry;
5072   /* move forwards */
5073   new_entry = old_entry + 1;
5074
5075   /* see if we reached the end */
5076   if (new_entry >= stream->stop_entry) {
5077     if (avi->segment.rate < 0.0) {
5078       if (stream->step_entry == stream->start_entry) {
5079         /* we stepped all the way to the start, eos */
5080         GST_DEBUG_OBJECT (avi, "reverse reached start %u", stream->start_entry);
5081         goto eos;
5082       }
5083       /* backwards, stop becomes step, find a new step */
5084       stream->stop_entry = stream->step_entry;
5085       stream->step_entry = gst_avi_demux_index_prev (avi, stream,
5086           stream->stop_entry, TRUE);
5087
5088       GST_DEBUG_OBJECT (avi,
5089           "reverse playback jump: start %u, step %u, stop %u",
5090           stream->start_entry, stream->step_entry, stream->stop_entry);
5091
5092       /* and start from the previous keyframe now */
5093       new_entry = stream->step_entry;
5094     } else {
5095       /* EOS */
5096       GST_DEBUG_OBJECT (avi, "forward reached stop %u", stream->stop_entry);
5097       goto eos;
5098     }
5099   }
5100
5101   if (new_entry != old_entry) {
5102     stream->current_entry = new_entry;
5103     stream->current_total = stream->index[new_entry].total;
5104
5105     if (new_entry == old_entry + 1) {
5106       GST_DEBUG_OBJECT (avi, "moved forwards from %u to %u",
5107           old_entry, new_entry);
5108       /* we simply moved one step forwards, reuse current info */
5109       stream->current_timestamp = stream->current_ts_end;
5110       stream->current_offset = stream->current_offset_end;
5111       gst_avi_demux_get_buffer_info (avi, stream, new_entry,
5112           NULL, &stream->current_ts_end, NULL, &stream->current_offset_end);
5113     } else {
5114       /* we moved DISCONT, full update */
5115       gst_avi_demux_get_buffer_info (avi, stream, new_entry,
5116           &stream->current_timestamp, &stream->current_ts_end,
5117           &stream->current_offset, &stream->current_offset_end);
5118       /* and MARK discont for this stream */
5119       stream->discont = TRUE;
5120       GST_DEBUG_OBJECT (avi, "Moved from %u to %u, ts %" GST_TIME_FORMAT
5121           ", ts_end %" GST_TIME_FORMAT ", off %" G_GUINT64_FORMAT
5122           ", off_end %" G_GUINT64_FORMAT, old_entry, new_entry,
5123           GST_TIME_ARGS (stream->current_timestamp),
5124           GST_TIME_ARGS (stream->current_ts_end), stream->current_offset,
5125           stream->current_offset_end);
5126     }
5127   }
5128   return ret;
5129
5130   /* ERROR */
5131 eos:
5132   {
5133     GST_DEBUG_OBJECT (avi, "we are EOS");
5134     /* setting current_timestamp to -1 marks EOS */
5135     stream->current_timestamp = -1;
5136     return GST_FLOW_EOS;
5137   }
5138 }
5139
5140 /* find the stream with the lowest current position when going forwards or with
5141  * the highest position when going backwards, this is the stream
5142  * we should push from next */
5143 static gint
5144 gst_avi_demux_find_next (GstAviDemux * avi, gfloat rate)
5145 {
5146   guint64 min_time, max_time;
5147   guint stream_num, i;
5148
5149   max_time = 0;
5150   min_time = G_MAXUINT64;
5151   stream_num = -1;
5152
5153   for (i = 0; i < avi->num_streams; i++) {
5154     guint64 position;
5155     GstAviStream *stream;
5156
5157     stream = &avi->stream[i];
5158
5159     /* ignore streams that finished */
5160     if (stream->pad && GST_PAD_LAST_FLOW_RETURN (stream->pad) == GST_FLOW_EOS)
5161       continue;
5162
5163     position = stream->current_timestamp;
5164
5165     /* position of -1 is EOS */
5166     if (position != -1) {
5167       if (rate > 0.0 && position < min_time) {
5168         min_time = position;
5169         stream_num = i;
5170       } else if (rate < 0.0 && position >= max_time) {
5171         max_time = position;
5172         stream_num = i;
5173       }
5174     }
5175   }
5176   return stream_num;
5177 }
5178
5179 static GstBuffer *
5180 gst_avi_demux_align_buffer (GstAviDemux * demux,
5181     GstBuffer * buffer, gsize alignment)
5182 {
5183   GstMapInfo map;
5184
5185   gst_buffer_map (buffer, &map, GST_MAP_READ);
5186
5187   if (map.size < sizeof (guintptr)) {
5188     gst_buffer_unmap (buffer, &map);
5189     return buffer;
5190   }
5191
5192   if (((guintptr) map.data) & (alignment - 1)) {
5193     GstBuffer *new_buffer;
5194     GstAllocationParams params = { 0, alignment - 1, 0, 0, };
5195
5196     new_buffer = gst_buffer_new_allocate (NULL,
5197         gst_buffer_get_size (buffer), &params);
5198
5199     /* Copy data "by hand", so ensure alignment is kept: */
5200     gst_buffer_fill (new_buffer, 0, map.data, map.size);
5201
5202     gst_buffer_copy_into (new_buffer, buffer, GST_BUFFER_COPY_METADATA, 0, -1);
5203     GST_DEBUG_OBJECT (demux,
5204         "We want output aligned on %" G_GSIZE_FORMAT ", reallocated",
5205         alignment);
5206
5207     gst_buffer_unmap (buffer, &map);
5208     gst_buffer_unref (buffer);
5209
5210     return new_buffer;
5211   }
5212
5213   gst_buffer_unmap (buffer, &map);
5214   return buffer;
5215 }
5216
5217 static GstFlowReturn
5218 gst_avi_demux_loop_data (GstAviDemux * avi)
5219 {
5220   GstFlowReturn ret = GST_FLOW_OK;
5221   guint stream_num;
5222   GstAviStream *stream;
5223   gboolean processed = FALSE;
5224   GstBuffer *buf;
5225   guint64 offset, size;
5226   GstClockTime timestamp, duration;
5227   guint64 out_offset, out_offset_end;
5228   gboolean keyframe;
5229   GstAviIndexEntry *entry;
5230
5231   do {
5232     stream_num = gst_avi_demux_find_next (avi, avi->segment.rate);
5233
5234     /* all are EOS */
5235     if (G_UNLIKELY (stream_num == -1)) {
5236       GST_DEBUG_OBJECT (avi, "all streams are EOS");
5237       goto eos;
5238     }
5239
5240     /* we have the stream now */
5241     stream = &avi->stream[stream_num];
5242
5243     /* skip streams without pads */
5244     if (!stream->pad) {
5245       GST_DEBUG_OBJECT (avi, "skipping entry from stream %d without pad",
5246           stream_num);
5247       goto next;
5248     }
5249
5250     /* get the timing info for the entry */
5251     timestamp = stream->current_timestamp;
5252     duration = stream->current_ts_end - timestamp;
5253     out_offset = stream->current_offset;
5254     out_offset_end = stream->current_offset_end;
5255
5256     /* get the entry data info */
5257     entry = &stream->index[stream->current_entry];
5258     offset = entry->offset;
5259     size = entry->size;
5260     keyframe = ENTRY_IS_KEYFRAME (entry);
5261
5262     /* skip empty entries */
5263     if (size == 0) {
5264       GST_DEBUG_OBJECT (avi, "Skipping entry %u (%" G_GUINT64_FORMAT ", %p)",
5265           stream->current_entry, size, stream->pad);
5266       goto next;
5267     }
5268
5269     if (avi->segment.rate > 0.0) {
5270       /* only check this for fowards playback for now */
5271       if (keyframe && GST_CLOCK_TIME_IS_VALID (avi->segment.stop)
5272           && (timestamp > avi->segment.stop)) {
5273         goto eos_stop;
5274       }
5275     } else {
5276       if (keyframe && GST_CLOCK_TIME_IS_VALID (avi->segment.start)
5277           && (timestamp < avi->segment.start))
5278         goto eos_stop;
5279     }
5280
5281     GST_LOG ("reading buffer (size=%" G_GUINT64_FORMAT "), stream %d, pos %"
5282         G_GUINT64_FORMAT " (0x%" G_GINT64_MODIFIER "x), kf %d", size,
5283         stream_num, offset, offset, keyframe);
5284
5285     /* FIXME, check large chunks and cut them up */
5286
5287     /* pull in the data */
5288     buf = NULL;
5289     ret = gst_pad_pull_range (avi->sinkpad, offset, size, &buf);
5290     if (ret != GST_FLOW_OK)
5291       goto pull_failed;
5292
5293     /* check for short buffers, this is EOS as well */
5294     if (gst_buffer_get_size (buf) < size)
5295       goto short_buffer;
5296
5297     /* invert the picture if needed, and append palette for RGB8P */
5298     buf = gst_avi_demux_invert (stream, buf);
5299
5300     /* mark non-keyframes */
5301     if (keyframe || stream->is_raw) {
5302       GST_BUFFER_FLAG_UNSET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
5303       GST_BUFFER_PTS (buf) = timestamp;
5304     } else {
5305       GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
5306       GST_BUFFER_PTS (buf) = GST_CLOCK_TIME_NONE;
5307     }
5308
5309     GST_BUFFER_DTS (buf) = timestamp;
5310
5311     GST_BUFFER_DURATION (buf) = duration;
5312     GST_BUFFER_OFFSET (buf) = out_offset;
5313     GST_BUFFER_OFFSET_END (buf) = out_offset_end;
5314
5315     /* mark discont when pending */
5316     if (stream->discont) {
5317       GST_DEBUG_OBJECT (avi, "setting DISCONT flag");
5318       GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
5319       stream->discont = FALSE;
5320     } else {
5321       GST_BUFFER_FLAG_UNSET (buf, GST_BUFFER_FLAG_DISCONT);
5322     }
5323 #if 0
5324     gst_avi_demux_add_assoc (avi, stream, timestamp, offset, keyframe);
5325 #endif
5326
5327     /* update current position in the segment */
5328     avi->segment.position = timestamp;
5329
5330     GST_DEBUG_OBJECT (avi, "Pushing buffer of size %" G_GSIZE_FORMAT ", ts %"
5331         GST_TIME_FORMAT ", dur %" GST_TIME_FORMAT ", off %" G_GUINT64_FORMAT
5332         ", off_end %" G_GUINT64_FORMAT,
5333         gst_buffer_get_size (buf), GST_TIME_ARGS (timestamp),
5334         GST_TIME_ARGS (duration), out_offset, out_offset_end);
5335
5336     if (stream->alignment > 1)
5337       buf = gst_avi_demux_align_buffer (avi, buf, stream->alignment);
5338     ret = gst_pad_push (stream->pad, buf);
5339
5340     /* mark as processed, we increment the frame and byte counters then
5341      * leave the while loop and return the GstFlowReturn */
5342     processed = TRUE;
5343
5344     if (avi->segment.rate < 0) {
5345       if (timestamp > avi->segment.stop && ret == GST_FLOW_EOS) {
5346         /* In reverse playback we can get a GST_FLOW_EOS when
5347          * we are at the end of the segment, so we just need to jump
5348          * back to the previous section. */
5349         GST_DEBUG_OBJECT (avi, "downstream has reached end of segment");
5350         ret = GST_FLOW_OK;
5351       }
5352     }
5353   next:
5354     /* move to next item */
5355     ret = gst_avi_demux_advance (avi, stream, ret);
5356
5357     /* combine flows */
5358     ret = gst_avi_demux_combine_flows (avi, stream, ret);
5359   } while (!processed);
5360
5361 beach:
5362   return ret;
5363
5364   /* special cases */
5365 eos:
5366   {
5367     GST_DEBUG_OBJECT (avi, "No samples left for any streams - EOS");
5368     ret = GST_FLOW_EOS;
5369     goto beach;
5370   }
5371 eos_stop:
5372   {
5373     GST_LOG_OBJECT (avi, "Found keyframe after segment,"
5374         " setting EOS (%" GST_TIME_FORMAT " > %" GST_TIME_FORMAT ")",
5375         GST_TIME_ARGS (timestamp), GST_TIME_ARGS (avi->segment.stop));
5376     ret = GST_FLOW_EOS;
5377     /* move to next stream */
5378     goto next;
5379   }
5380 pull_failed:
5381   {
5382     GST_DEBUG_OBJECT (avi, "pull range failed: pos=%" G_GUINT64_FORMAT
5383         " size=%" G_GUINT64_FORMAT, offset, size);
5384     goto beach;
5385   }
5386 short_buffer:
5387   {
5388     GST_WARNING_OBJECT (avi, "Short read at offset %" G_GUINT64_FORMAT
5389         ", only got %" G_GSIZE_FORMAT "/%" G_GUINT64_FORMAT
5390         " bytes (truncated file?)", offset, gst_buffer_get_size (buf), size);
5391     gst_buffer_unref (buf);
5392     ret = GST_FLOW_EOS;
5393     goto beach;
5394   }
5395 }
5396
5397 /*
5398  * Read data. If we have an index it delegates to
5399  * gst_avi_demux_process_next_entry().
5400  */
5401 static GstFlowReturn
5402 gst_avi_demux_stream_data (GstAviDemux * avi)
5403 {
5404   guint32 tag = 0;
5405   guint32 size = 0;
5406   gint stream_nr = 0;
5407   GstFlowReturn res = GST_FLOW_OK;
5408
5409   if (G_UNLIKELY (avi->have_eos)) {
5410     /* Clean adapter, we're done */
5411     gst_adapter_clear (avi->adapter);
5412     return GST_FLOW_EOS;
5413   }
5414
5415   if (G_UNLIKELY (avi->todrop)) {
5416     guint drop;
5417
5418     if ((drop = gst_adapter_available (avi->adapter))) {
5419       if (drop > avi->todrop)
5420         drop = avi->todrop;
5421       GST_DEBUG_OBJECT (avi, "Dropping %d bytes", drop);
5422       gst_adapter_flush (avi->adapter, drop);
5423       avi->todrop -= drop;
5424       avi->offset += drop;
5425     }
5426   }
5427
5428   /* Iterate until need more data, so adapter won't grow too much */
5429   while (1) {
5430     if (G_UNLIKELY (!gst_avi_demux_peek_chunk_info (avi, &tag, &size))) {
5431       return GST_FLOW_OK;
5432     }
5433
5434     GST_DEBUG ("Trying chunk (%" GST_FOURCC_FORMAT "), size %d",
5435         GST_FOURCC_ARGS (tag), size);
5436
5437     if (G_LIKELY ((tag & 0xff) >= '0' && (tag & 0xff) <= '9' &&
5438             ((tag >> 8) & 0xff) >= '0' && ((tag >> 8) & 0xff) <= '9')) {
5439       GST_LOG ("Chunk ok");
5440     } else if ((tag & 0xffff) == (('x' << 8) | 'i')) {
5441       GST_DEBUG ("Found sub-index tag");
5442       if (gst_avi_demux_peek_chunk (avi, &tag, &size) || size == 0) {
5443         /* accept 0 size buffer here */
5444         avi->abort_buffering = FALSE;
5445         GST_DEBUG ("  skipping %d bytes for now", size);
5446         gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
5447       }
5448       return GST_FLOW_OK;
5449     } else if (tag == GST_RIFF_TAG_RIFF) {
5450       /* RIFF tags can appear in ODML files, just jump over them */
5451       if (gst_adapter_available (avi->adapter) >= 12) {
5452         GST_DEBUG ("Found RIFF tag, skipping RIFF header");
5453         gst_adapter_flush (avi->adapter, 12);
5454         continue;
5455       }
5456       return GST_FLOW_OK;
5457     } else if (tag == GST_RIFF_TAG_idx1) {
5458       GST_DEBUG ("Found index tag");
5459       if (gst_avi_demux_peek_chunk (avi, &tag, &size) || size == 0) {
5460         /* accept 0 size buffer here */
5461         avi->abort_buffering = FALSE;
5462         GST_DEBUG ("  skipping %d bytes for now", size);
5463         gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
5464       }
5465       return GST_FLOW_OK;
5466     } else if (tag == GST_RIFF_TAG_LIST) {
5467       /* movi chunks might be grouped in rec list */
5468       if (gst_adapter_available (avi->adapter) >= 12) {
5469         GST_DEBUG ("Found LIST tag, skipping LIST header");
5470         gst_adapter_flush (avi->adapter, 12);
5471         continue;
5472       }
5473       return GST_FLOW_OK;
5474     } else if (tag == GST_RIFF_TAG_JUNK || tag == GST_RIFF_TAG_JUNQ) {
5475       /* rec list might contain JUNK chunks */
5476       GST_DEBUG ("Found JUNK tag");
5477       if (gst_avi_demux_peek_chunk (avi, &tag, &size) || size == 0) {
5478         /* accept 0 size buffer here */
5479         avi->abort_buffering = FALSE;
5480         GST_DEBUG ("  skipping %d bytes for now", size);
5481         gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
5482       }
5483       return GST_FLOW_OK;
5484     } else {
5485       GST_DEBUG ("No more stream chunks, send EOS");
5486       avi->have_eos = TRUE;
5487       return GST_FLOW_EOS;
5488     }
5489
5490     if (G_UNLIKELY (!gst_avi_demux_peek_chunk (avi, &tag, &size))) {
5491       /* supposedly one hopes to catch a nicer chunk later on ... */
5492       /* FIXME ?? give up here rather than possibly ending up going
5493        * through the whole file */
5494       if (avi->abort_buffering) {
5495         avi->abort_buffering = FALSE;
5496         if (size) {
5497           gst_adapter_flush (avi->adapter, 8);
5498           return GST_FLOW_OK;
5499         }
5500       } else {
5501         return GST_FLOW_OK;
5502       }
5503     }
5504     GST_DEBUG ("chunk ID %" GST_FOURCC_FORMAT ", size %u",
5505         GST_FOURCC_ARGS (tag), size);
5506
5507     stream_nr = CHUNKID_TO_STREAMNR (tag);
5508
5509     if (G_UNLIKELY (stream_nr < 0 || stream_nr >= avi->num_streams)) {
5510       /* recoverable */
5511       GST_WARNING ("Invalid stream ID %d (%" GST_FOURCC_FORMAT ")",
5512           stream_nr, GST_FOURCC_ARGS (tag));
5513       avi->offset += 8 + GST_ROUND_UP_2 (size);
5514       gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
5515     } else {
5516       GstAviStream *stream;
5517       GstClockTime next_ts = 0;
5518       GstBuffer *buf = NULL;
5519 #if 0
5520       guint64 offset;
5521 #endif
5522       gboolean saw_desired_kf = stream_nr != avi->main_stream
5523           || avi->offset >= avi->seek_kf_offset;
5524
5525       if (stream_nr == avi->main_stream && avi->offset == avi->seek_kf_offset) {
5526         GST_DEBUG_OBJECT (avi, "Desired keyframe reached");
5527         avi->seek_kf_offset = 0;
5528       }
5529
5530       if (saw_desired_kf) {
5531         gst_adapter_flush (avi->adapter, 8);
5532         /* get buffer */
5533         if (size) {
5534           buf = gst_adapter_take_buffer (avi->adapter, GST_ROUND_UP_2 (size));
5535           /* patch the size */
5536           gst_buffer_resize (buf, 0, size);
5537         } else {
5538           buf = NULL;
5539         }
5540       } else {
5541         GST_DEBUG_OBJECT (avi,
5542             "Desired keyframe not yet reached, flushing chunk");
5543         gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
5544       }
5545
5546 #if 0
5547       offset = avi->offset;
5548 #endif
5549       avi->offset += 8 + GST_ROUND_UP_2 (size);
5550
5551       stream = &avi->stream[stream_nr];
5552
5553       /* set delay (if any)
5554          if (stream->strh->init_frames == stream->current_frame &&
5555          stream->delay == 0)
5556          stream->delay = next_ts;
5557        */
5558
5559       /* parsing of corresponding header may have failed */
5560       if (G_UNLIKELY (!stream->pad)) {
5561         GST_WARNING_OBJECT (avi, "no pad for stream ID %" GST_FOURCC_FORMAT,
5562             GST_FOURCC_ARGS (tag));
5563         if (buf)
5564           gst_buffer_unref (buf);
5565       } else {
5566         /* get time of this buffer */
5567         gst_pad_query_position (stream->pad, GST_FORMAT_TIME,
5568             (gint64 *) & next_ts);
5569
5570 #if 0
5571         gst_avi_demux_add_assoc (avi, stream, next_ts, offset, FALSE);
5572 #endif
5573
5574         /* increment our positions */
5575         stream->current_entry++;
5576         /* as in pull mode, 'total' is either bytes (CBR) or frames (VBR) */
5577         if (stream->strh->type == GST_RIFF_FCC_auds && stream->is_vbr) {
5578           gint blockalign = stream->strf.auds->blockalign;
5579           if (blockalign > 0)
5580             stream->current_total += DIV_ROUND_UP (size, blockalign);
5581           else
5582             stream->current_total++;
5583         } else {
5584           stream->current_total += size;
5585         }
5586         GST_LOG_OBJECT (avi, "current entry %u, total %u",
5587             stream->current_entry, stream->current_total);
5588
5589         /* update current position in the segment */
5590         avi->segment.position = next_ts;
5591
5592         if (saw_desired_kf && buf) {
5593           GstClockTime dur_ts = 0;
5594
5595           /* invert the picture if needed, and append palette for RGB8P */
5596           buf = gst_avi_demux_invert (stream, buf);
5597
5598           gst_pad_query_position (stream->pad, GST_FORMAT_TIME,
5599               (gint64 *) & dur_ts);
5600
5601           GST_BUFFER_DTS (buf) = next_ts;
5602           GST_BUFFER_PTS (buf) = GST_CLOCK_TIME_NONE;
5603           GST_BUFFER_DURATION (buf) = dur_ts - next_ts;
5604           if (stream->strh->type == GST_RIFF_FCC_vids) {
5605             GST_BUFFER_OFFSET (buf) = stream->current_entry - 1;
5606             GST_BUFFER_OFFSET_END (buf) = stream->current_entry;
5607           } else {
5608             GST_BUFFER_OFFSET (buf) = GST_BUFFER_OFFSET_NONE;
5609             GST_BUFFER_OFFSET_END (buf) = GST_BUFFER_OFFSET_NONE;
5610           }
5611
5612           GST_DEBUG_OBJECT (avi,
5613               "Pushing buffer with time=%" GST_TIME_FORMAT ", duration %"
5614               GST_TIME_FORMAT ", offset %" G_GUINT64_FORMAT
5615               " and size %d over pad %s", GST_TIME_ARGS (next_ts),
5616               GST_TIME_ARGS (GST_BUFFER_DURATION (buf)),
5617               GST_BUFFER_OFFSET (buf), size, GST_PAD_NAME (stream->pad));
5618
5619           /* mark discont when pending */
5620           if (G_UNLIKELY (stream->discont)) {
5621             GST_DEBUG_OBJECT (avi, "Setting DISCONT");
5622             GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
5623             stream->discont = FALSE;
5624           } else {
5625             GST_BUFFER_FLAG_UNSET (buf, GST_BUFFER_FLAG_DISCONT);
5626           }
5627
5628           if (stream->alignment > 1)
5629             buf = gst_avi_demux_align_buffer (avi, buf, stream->alignment);
5630           res = gst_pad_push (stream->pad, buf);
5631           buf = NULL;
5632
5633           /* combine flows */
5634           res = gst_avi_demux_combine_flows (avi, stream, res);
5635           if (G_UNLIKELY (res != GST_FLOW_OK)) {
5636             GST_DEBUG ("Push failed; %s", gst_flow_get_name (res));
5637             return res;
5638           }
5639         }
5640       }
5641     }
5642   }
5643
5644   return res;
5645 }
5646
5647 /*
5648  * Send pending tags.
5649  */
5650 static void
5651 push_tag_lists (GstAviDemux * avi)
5652 {
5653   guint i;
5654   GstTagList *tags;
5655
5656   if (!avi->got_tags)
5657     return;
5658
5659   GST_DEBUG_OBJECT (avi, "Pushing pending tag lists");
5660
5661   for (i = 0; i < avi->num_streams; i++) {
5662     GstAviStream *stream = &avi->stream[i];
5663     GstPad *pad = stream->pad;
5664
5665     tags = stream->taglist;
5666
5667     if (pad && tags) {
5668       GST_DEBUG_OBJECT (pad, "Tags: %" GST_PTR_FORMAT, tags);
5669
5670       gst_pad_push_event (pad, gst_event_new_tag (tags));
5671       stream->taglist = NULL;
5672     }
5673   }
5674
5675   if (!(tags = avi->globaltags))
5676     tags = gst_tag_list_new_empty ();
5677
5678   gst_tag_list_add (tags, GST_TAG_MERGE_REPLACE,
5679       GST_TAG_CONTAINER_FORMAT, "AVI", NULL);
5680
5681   GST_DEBUG_OBJECT (avi, "Global tags: %" GST_PTR_FORMAT, tags);
5682   gst_tag_list_set_scope (tags, GST_TAG_SCOPE_GLOBAL);
5683   gst_avi_demux_push_event (avi, gst_event_new_tag (tags));
5684   avi->globaltags = NULL;
5685   avi->got_tags = FALSE;
5686 }
5687
5688 static void
5689 gst_avi_demux_loop (GstPad * pad)
5690 {
5691   GstFlowReturn res;
5692   GstAviDemux *avi = GST_AVI_DEMUX (GST_PAD_PARENT (pad));
5693
5694   switch (avi->state) {
5695     case GST_AVI_DEMUX_START:
5696       res = gst_avi_demux_stream_init_pull (avi);
5697       if (G_UNLIKELY (res != GST_FLOW_OK)) {
5698         GST_WARNING ("stream_init flow: %s", gst_flow_get_name (res));
5699         goto pause;
5700       }
5701       avi->state = GST_AVI_DEMUX_HEADER;
5702       /* fall-through */
5703     case GST_AVI_DEMUX_HEADER:
5704       res = gst_avi_demux_stream_header_pull (avi);
5705       if (G_UNLIKELY (res != GST_FLOW_OK)) {
5706         GST_WARNING ("stream_header flow: %s", gst_flow_get_name (res));
5707         goto pause;
5708       }
5709       avi->state = GST_AVI_DEMUX_MOVI;
5710       break;
5711     case GST_AVI_DEMUX_MOVI:
5712       if (G_UNLIKELY (avi->seg_event)) {
5713         gst_avi_demux_push_event (avi, avi->seg_event);
5714         avi->seg_event = NULL;
5715       }
5716       if (G_UNLIKELY (avi->got_tags)) {
5717         push_tag_lists (avi);
5718       }
5719       /* process each index entry in turn */
5720       res = gst_avi_demux_loop_data (avi);
5721
5722       /* pause when error */
5723       if (G_UNLIKELY (res != GST_FLOW_OK)) {
5724         GST_INFO ("stream_movi flow: %s", gst_flow_get_name (res));
5725         goto pause;
5726       }
5727       break;
5728     default:
5729       GST_ERROR_OBJECT (avi, "unknown state %d", avi->state);
5730       res = GST_FLOW_ERROR;
5731       goto pause;
5732   }
5733
5734   return;
5735
5736   /* ERRORS */
5737 pause:{
5738
5739     gboolean push_eos = FALSE;
5740     GST_LOG_OBJECT (avi, "pausing task, reason %s", gst_flow_get_name (res));
5741     gst_pad_pause_task (avi->sinkpad);
5742
5743     if (res == GST_FLOW_EOS) {
5744       /* handle end-of-stream/segment */
5745       /* so align our position with the end of it, if there is one
5746        * this ensures a subsequent will arrive at correct base/acc time */
5747       if (avi->segment.rate > 0.0 &&
5748           GST_CLOCK_TIME_IS_VALID (avi->segment.stop))
5749         avi->segment.position = avi->segment.stop;
5750       else if (avi->segment.rate < 0.0)
5751         avi->segment.position = avi->segment.start;
5752       if (avi->segment.flags & GST_SEEK_FLAG_SEGMENT) {
5753         gint64 stop;
5754         GstEvent *event;
5755         GstMessage *msg;
5756
5757         if ((stop = avi->segment.stop) == -1)
5758           stop = avi->segment.duration;
5759
5760         GST_INFO_OBJECT (avi, "sending segment_done");
5761
5762         msg =
5763             gst_message_new_segment_done (GST_OBJECT_CAST (avi),
5764             GST_FORMAT_TIME, stop);
5765         if (avi->segment_seqnum)
5766           gst_message_set_seqnum (msg, avi->segment_seqnum);
5767         gst_element_post_message (GST_ELEMENT_CAST (avi), msg);
5768
5769         event = gst_event_new_segment_done (GST_FORMAT_TIME, stop);
5770         if (avi->segment_seqnum)
5771           gst_event_set_seqnum (event, avi->segment_seqnum);
5772         gst_avi_demux_push_event (avi, event);
5773       } else {
5774         push_eos = TRUE;
5775       }
5776     } else if (res == GST_FLOW_NOT_LINKED || res < GST_FLOW_EOS) {
5777       /* for fatal errors we post an error message, wrong-state is
5778        * not fatal because it happens due to flushes and only means
5779        * that we should stop now. */
5780       GST_ELEMENT_FLOW_ERROR (avi, res);
5781       push_eos = TRUE;
5782     }
5783     if (push_eos) {
5784       GstEvent *event;
5785
5786       GST_INFO_OBJECT (avi, "sending eos");
5787       event = gst_event_new_eos ();
5788       if (avi->segment_seqnum)
5789         gst_event_set_seqnum (event, avi->segment_seqnum);
5790       if (!gst_avi_demux_push_event (avi, event) && (res == GST_FLOW_EOS)) {
5791         GST_ELEMENT_ERROR (avi, STREAM, DEMUX,
5792             (NULL), ("got eos but no streams (yet)"));
5793       }
5794     }
5795   }
5796 }
5797
5798
5799 static GstFlowReturn
5800 gst_avi_demux_chain (GstPad * pad, GstObject * parent, GstBuffer * buf)
5801 {
5802   GstFlowReturn res;
5803   GstAviDemux *avi = GST_AVI_DEMUX (parent);
5804   gint i;
5805
5806   if (GST_BUFFER_IS_DISCONT (buf)) {
5807     GST_DEBUG_OBJECT (avi, "got DISCONT");
5808     gst_adapter_clear (avi->adapter);
5809     /* mark all streams DISCONT */
5810     for (i = 0; i < avi->num_streams; i++)
5811       avi->stream[i].discont = TRUE;
5812   }
5813
5814   GST_DEBUG ("Store %" G_GSIZE_FORMAT " bytes in adapter",
5815       gst_buffer_get_size (buf));
5816   gst_adapter_push (avi->adapter, buf);
5817
5818   switch (avi->state) {
5819     case GST_AVI_DEMUX_START:
5820       if ((res = gst_avi_demux_stream_init_push (avi)) != GST_FLOW_OK) {
5821         GST_WARNING ("stream_init flow: %s", gst_flow_get_name (res));
5822         break;
5823       }
5824       break;
5825     case GST_AVI_DEMUX_HEADER:
5826       if ((res = gst_avi_demux_stream_header_push (avi)) != GST_FLOW_OK) {
5827         GST_WARNING ("stream_header flow: %s", gst_flow_get_name (res));
5828         break;
5829       }
5830       break;
5831     case GST_AVI_DEMUX_MOVI:
5832       if (G_UNLIKELY (avi->seg_event)) {
5833         gst_avi_demux_push_event (avi, avi->seg_event);
5834         avi->seg_event = NULL;
5835       }
5836       if (G_UNLIKELY (avi->got_tags)) {
5837         push_tag_lists (avi);
5838       }
5839       res = gst_avi_demux_stream_data (avi);
5840       break;
5841     case GST_AVI_DEMUX_SEEK:
5842     {
5843       GstEvent *event;
5844
5845       res = GST_FLOW_OK;
5846
5847       /* obtain and parse indexes */
5848       if (avi->stream[0].indexes && !gst_avi_demux_read_subindexes_push (avi))
5849         /* seek in subindex read function failed */
5850         goto index_failed;
5851
5852       if (!avi->stream[0].indexes && !avi->have_index
5853           && avi->avih->flags & GST_RIFF_AVIH_HASINDEX)
5854         gst_avi_demux_stream_index_push (avi);
5855
5856       if (avi->have_index) {
5857         /* use the indexes now to construct nice durations */
5858         gst_avi_demux_calculate_durations_from_index (avi);
5859       } else {
5860         /* still parsing indexes */
5861         break;
5862       }
5863
5864       GST_OBJECT_LOCK (avi);
5865       event = avi->seek_event;
5866       avi->seek_event = NULL;
5867       GST_OBJECT_UNLOCK (avi);
5868
5869       /* calculate and perform seek */
5870       if (!avi_demux_handle_seek_push (avi, avi->sinkpad, event)) {
5871         gst_event_unref (event);
5872         goto seek_failed;
5873       }
5874
5875       gst_event_unref (event);
5876       avi->state = GST_AVI_DEMUX_MOVI;
5877       break;
5878     }
5879     default:
5880       GST_ELEMENT_ERROR (avi, STREAM, FAILED, (NULL),
5881           ("Illegal internal state"));
5882       res = GST_FLOW_ERROR;
5883       break;
5884   }
5885
5886   GST_DEBUG_OBJECT (avi, "state: %d res:%s", avi->state,
5887       gst_flow_get_name (res));
5888
5889   if (G_UNLIKELY (avi->abort_buffering))
5890     goto abort_buffering;
5891
5892   return res;
5893
5894   /* ERRORS */
5895 index_failed:
5896   {
5897     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("failed to read indexes"));
5898     return GST_FLOW_ERROR;
5899   }
5900 seek_failed:
5901   {
5902     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("push mode seek failed"));
5903     return GST_FLOW_ERROR;
5904   }
5905 abort_buffering:
5906   {
5907     avi->abort_buffering = FALSE;
5908     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("unhandled buffer size"));
5909     return GST_FLOW_ERROR;
5910   }
5911 }
5912
5913 static gboolean
5914 gst_avi_demux_sink_activate (GstPad * sinkpad, GstObject * parent)
5915 {
5916   GstQuery *query;
5917   gboolean pull_mode;
5918
5919   query = gst_query_new_scheduling ();
5920
5921   if (!gst_pad_peer_query (sinkpad, query)) {
5922     gst_query_unref (query);
5923     goto activate_push;
5924   }
5925
5926   pull_mode = gst_query_has_scheduling_mode_with_flags (query,
5927       GST_PAD_MODE_PULL, GST_SCHEDULING_FLAG_SEEKABLE);
5928   gst_query_unref (query);
5929
5930   if (!pull_mode)
5931     goto activate_push;
5932
5933   GST_DEBUG_OBJECT (sinkpad, "activating pull");
5934   return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PULL, TRUE);
5935
5936 activate_push:
5937   {
5938     GST_DEBUG_OBJECT (sinkpad, "activating push");
5939     return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
5940   }
5941 }
5942
5943 static gboolean
5944 gst_avi_demux_sink_activate_mode (GstPad * sinkpad, GstObject * parent,
5945     GstPadMode mode, gboolean active)
5946 {
5947   gboolean res;
5948   GstAviDemux *avi = GST_AVI_DEMUX (parent);
5949
5950   switch (mode) {
5951     case GST_PAD_MODE_PULL:
5952       if (active) {
5953         avi->streaming = FALSE;
5954         res = gst_pad_start_task (sinkpad, (GstTaskFunction) gst_avi_demux_loop,
5955             sinkpad, NULL);
5956       } else {
5957         res = gst_pad_stop_task (sinkpad);
5958       }
5959       break;
5960     case GST_PAD_MODE_PUSH:
5961       if (active) {
5962         GST_DEBUG ("avi: activating push/chain function");
5963         avi->streaming = TRUE;
5964       } else {
5965         GST_DEBUG ("avi: deactivating push/chain function");
5966       }
5967       res = TRUE;
5968       break;
5969     default:
5970       res = FALSE;
5971       break;
5972   }
5973   return res;
5974 }
5975
5976 #if 0
5977 static void
5978 gst_avi_demux_set_index (GstElement * element, GstIndex * index)
5979 {
5980   GstAviDemux *avi = GST_AVI_DEMUX (element);
5981
5982   GST_OBJECT_LOCK (avi);
5983   if (avi->element_index)
5984     gst_object_unref (avi->element_index);
5985   if (index) {
5986     avi->element_index = gst_object_ref (index);
5987   } else {
5988     avi->element_index = NULL;
5989   }
5990   GST_OBJECT_UNLOCK (avi);
5991   /* object lock might be taken again */
5992   if (index)
5993     gst_index_get_writer_id (index, GST_OBJECT_CAST (element), &avi->index_id);
5994   GST_DEBUG_OBJECT (avi, "Set index %" GST_PTR_FORMAT, avi->element_index);
5995 }
5996
5997 static GstIndex *
5998 gst_avi_demux_get_index (GstElement * element)
5999 {
6000   GstIndex *result = NULL;
6001   GstAviDemux *avi = GST_AVI_DEMUX (element);
6002
6003   GST_OBJECT_LOCK (avi);
6004   if (avi->element_index)
6005     result = gst_object_ref (avi->element_index);
6006   GST_OBJECT_UNLOCK (avi);
6007
6008   GST_DEBUG_OBJECT (avi, "Returning index %" GST_PTR_FORMAT, result);
6009
6010   return result;
6011 }
6012 #endif
6013
6014 static GstStateChangeReturn
6015 gst_avi_demux_change_state (GstElement * element, GstStateChange transition)
6016 {
6017   GstStateChangeReturn ret;
6018   GstAviDemux *avi = GST_AVI_DEMUX (element);
6019
6020   switch (transition) {
6021     case GST_STATE_CHANGE_READY_TO_PAUSED:
6022       avi->streaming = FALSE;
6023       gst_segment_init (&avi->segment, GST_FORMAT_TIME);
6024       break;
6025     default:
6026       break;
6027   }
6028
6029   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
6030   if (ret == GST_STATE_CHANGE_FAILURE)
6031     goto done;
6032
6033   switch (transition) {
6034     case GST_STATE_CHANGE_PAUSED_TO_READY:
6035       avi->have_index = FALSE;
6036       gst_avi_demux_reset (avi);
6037       break;
6038     default:
6039       break;
6040   }
6041
6042 done:
6043   return ret;
6044 }