avidemux: Fix coverity issue (Resource leak)
[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 #ifdef TIZEN_FEATURE_AVIDEMUX_MODIFICATION
2387     g_free (padname);
2388 #endif
2389     goto fail;
2390   }
2391
2392   GST_DEBUG_OBJECT (element, "codec-name=%s", codec_name ? codec_name : "NULL");
2393   GST_DEBUG_OBJECT (element, "caps=%" GST_PTR_FORMAT, caps);
2394
2395   /* set proper settings and add it */
2396   if (stream->pad)
2397     gst_object_unref (stream->pad);
2398   pad = stream->pad = gst_pad_new_from_template (templ, padname);
2399   g_free (padname);
2400
2401   gst_pad_use_fixed_caps (pad);
2402 #if 0
2403   gst_pad_set_formats_function (pad,
2404       GST_DEBUG_FUNCPTR (gst_avi_demux_get_src_formats));
2405   gst_pad_set_event_mask_function (pad,
2406       GST_DEBUG_FUNCPTR (gst_avi_demux_get_event_mask));
2407 #endif
2408   gst_pad_set_event_function (pad,
2409       GST_DEBUG_FUNCPTR (gst_avi_demux_handle_src_event));
2410   gst_pad_set_query_function (pad,
2411       GST_DEBUG_FUNCPTR (gst_avi_demux_handle_src_query));
2412 #if 0
2413   gst_pad_set_convert_function (pad,
2414       GST_DEBUG_FUNCPTR (gst_avi_demux_src_convert));
2415 #endif
2416
2417   stream->num = avi->num_streams;
2418
2419   stream->start_entry = 0;
2420   stream->step_entry = 0;
2421   stream->stop_entry = 0;
2422
2423   stream->current_entry = -1;
2424   stream->current_total = 0;
2425
2426   stream->discont = TRUE;
2427
2428   stream->total_bytes = 0;
2429   stream->total_blocks = 0;
2430   stream->n_keyframes = 0;
2431
2432   stream->idx_n = 0;
2433   stream->idx_max = 0;
2434
2435   gst_pad_set_element_private (pad, stream);
2436   avi->num_streams++;
2437
2438   gst_pad_set_active (pad, TRUE);
2439   stream_id =
2440       gst_pad_create_stream_id_printf (pad, GST_ELEMENT_CAST (avi), "%03u",
2441       avi->num_streams);
2442
2443   event = gst_pad_get_sticky_event (avi->sinkpad, GST_EVENT_STREAM_START, 0);
2444   if (event) {
2445     if (gst_event_parse_group_id (event, &avi->group_id))
2446       avi->have_group_id = TRUE;
2447     else
2448       avi->have_group_id = FALSE;
2449     gst_event_unref (event);
2450   } else if (!avi->have_group_id) {
2451     avi->have_group_id = TRUE;
2452     avi->group_id = gst_util_group_id_next ();
2453   }
2454
2455   event = gst_event_new_stream_start (stream_id);
2456   if (avi->have_group_id)
2457     gst_event_set_group_id (event, avi->group_id);
2458   if (sparse)
2459     gst_event_set_stream_flags (event, GST_STREAM_FLAG_SPARSE);
2460
2461   gst_pad_push_event (pad, event);
2462   g_free (stream_id);
2463   gst_pad_set_caps (pad, caps);
2464   gst_caps_unref (caps);
2465
2466   /* make tags */
2467   if (codec_name && tag_name) {
2468     if (!stream->taglist)
2469       stream->taglist = gst_tag_list_new_empty ();
2470
2471     avi->got_tags = TRUE;
2472
2473     gst_tag_list_add (stream->taglist, GST_TAG_MERGE_APPEND, tag_name,
2474         codec_name, NULL);
2475   }
2476
2477   g_free (vprp);
2478   g_free (codec_name);
2479   gst_buffer_unref (buf);
2480
2481   return TRUE;
2482
2483   /* ERRORS */
2484 fail:
2485   {
2486     /* unref any mem that may be in use */
2487     if (buf)
2488       gst_buffer_unref (buf);
2489     if (sub)
2490       gst_buffer_unref (sub);
2491     g_free (vprp);
2492     g_free (codec_name);
2493     gst_avi_demux_reset_stream (avi, stream);
2494     avi->num_streams++;
2495     return FALSE;
2496   }
2497 }
2498
2499 /*
2500  * gst_avi_demux_parse_odml:
2501  * @avi: calling element (used for debug/error).
2502  * @buf: input buffer to be used for parsing.
2503  *
2504  * Read an openDML-2.0 extension header. Fills in the frame number
2505  * in the avi demuxer object when reading succeeds.
2506  */
2507 static void
2508 gst_avi_demux_parse_odml (GstAviDemux * avi, GstBuffer * buf)
2509 {
2510   guint32 tag = 0;
2511   guint offset = 4;
2512   GstBuffer *sub = NULL;
2513
2514   while (gst_riff_parse_chunk (GST_ELEMENT_CAST (avi), buf, &offset, &tag,
2515           &sub)) {
2516     switch (tag) {
2517       case GST_RIFF_TAG_dmlh:{
2518         gst_riff_dmlh dmlh, *_dmlh;
2519         GstMapInfo map;
2520
2521         /* sub == NULL is possible and means an empty buffer */
2522         if (sub == NULL)
2523           goto next;
2524
2525         gst_buffer_map (sub, &map, GST_MAP_READ);
2526
2527         /* check size */
2528         if (map.size < sizeof (gst_riff_dmlh)) {
2529           GST_ERROR_OBJECT (avi,
2530               "DMLH entry is too small (%" G_GSIZE_FORMAT " bytes, %d needed)",
2531               map.size, (int) sizeof (gst_riff_dmlh));
2532           gst_buffer_unmap (sub, &map);
2533           goto next;
2534         }
2535         _dmlh = (gst_riff_dmlh *) map.data;
2536         dmlh.totalframes = GST_READ_UINT32_LE (&_dmlh->totalframes);
2537         gst_buffer_unmap (sub, &map);
2538
2539         GST_INFO_OBJECT (avi, "dmlh tag found: totalframes: %u",
2540             dmlh.totalframes);
2541
2542         avi->avih->tot_frames = dmlh.totalframes;
2543         goto next;
2544       }
2545
2546       default:
2547         GST_WARNING_OBJECT (avi,
2548             "Unknown tag %" GST_FOURCC_FORMAT " in ODML header",
2549             GST_FOURCC_ARGS (tag));
2550         /* Only get buffer for debugging if the memdump is needed  */
2551         if (gst_debug_category_get_threshold (GST_CAT_DEFAULT) >= 9) {
2552           GstMapInfo map;
2553
2554           gst_buffer_map (sub, &map, GST_MAP_READ);
2555           GST_MEMDUMP_OBJECT (avi, "Unknown ODML tag", map.data, map.size);
2556           gst_buffer_unmap (sub, &map);
2557         }
2558         /* fall-through */
2559       case GST_RIFF_TAG_JUNQ:
2560       case GST_RIFF_TAG_JUNK:
2561       next:
2562         /* skip and move to next chunk */
2563         if (sub) {
2564           gst_buffer_unref (sub);
2565           sub = NULL;
2566         }
2567         break;
2568     }
2569   }
2570   if (buf)
2571     gst_buffer_unref (buf);
2572 }
2573
2574 /* Index helper */
2575 static guint
2576 gst_avi_demux_index_last (GstAviDemux * avi, GstAviStream * stream)
2577 {
2578   return stream->idx_n;
2579 }
2580
2581 /* find a previous entry in the index with the given flags */
2582 static guint
2583 gst_avi_demux_index_prev (GstAviDemux * avi, GstAviStream * stream,
2584     guint last, gboolean keyframe)
2585 {
2586   GstAviIndexEntry *entry;
2587   guint i;
2588
2589   for (i = last; i > 0; i--) {
2590     entry = &stream->index[i - 1];
2591     if (!keyframe || ENTRY_IS_KEYFRAME (entry)) {
2592       return i - 1;
2593     }
2594   }
2595   return 0;
2596 }
2597
2598 static guint
2599 gst_avi_demux_index_next (GstAviDemux * avi, GstAviStream * stream,
2600     guint last, gboolean keyframe)
2601 {
2602   GstAviIndexEntry *entry;
2603   gint i;
2604
2605   for (i = last + 1; i < stream->idx_n; i++) {
2606     entry = &stream->index[i];
2607     if (!keyframe || ENTRY_IS_KEYFRAME (entry)) {
2608       return i;
2609     }
2610   }
2611   return stream->idx_n - 1;
2612 }
2613
2614 static guint
2615 gst_avi_demux_index_entry_search (GstAviIndexEntry * entry, guint64 * total)
2616 {
2617   if (entry->total < *total)
2618     return -1;
2619   else if (entry->total > *total)
2620     return 1;
2621   return 0;
2622 }
2623
2624 /*
2625  * gst_avi_demux_index_for_time:
2626  * @avi: Avi object
2627  * @stream: the stream
2628  * @time: a time position
2629  * @next: whether to look for entry before or after @time
2630  *
2631  * Finds the index entry which time is less/more or equal than the requested time.
2632  * Try to avoid binary search when we can convert the time to an index
2633  * position directly (for example for video frames with a fixed duration).
2634  *
2635  * Returns: the found position in the index.
2636  */
2637 static guint
2638 gst_avi_demux_index_for_time (GstAviDemux * avi,
2639     GstAviStream * stream, guint64 time, gboolean next)
2640 {
2641   guint index = -1;
2642   guint64 total;
2643
2644   GST_LOG_OBJECT (avi, "search time:%" GST_TIME_FORMAT, GST_TIME_ARGS (time));
2645
2646   /* easy (and common) cases */
2647   if (time == 0 || stream->idx_n == 0)
2648     return 0;
2649   if (time >= stream->idx_duration)
2650     return stream->idx_n - 1;
2651
2652   /* figure out where we need to go. For that we convert the time to an
2653    * index entry or we convert it to a total and then do a binary search. */
2654   if (stream->is_vbr) {
2655     /* VBR stream next timestamp */
2656     if (stream->strh->type == GST_RIFF_FCC_auds) {
2657       total = avi_stream_convert_time_to_frames_unchecked (stream, time);
2658     } else {
2659       index = avi_stream_convert_time_to_frames_unchecked (stream, time);
2660       /* this entry typically undershoots the target time,
2661        * so check a bit more if next needed */
2662       if (next && index != -1) {
2663         GstClockTime itime =
2664             avi_stream_convert_frames_to_time_unchecked (stream, index);
2665         if (itime < time && index + 1 < stream->idx_n)
2666           index++;
2667       }
2668     }
2669   } else if (stream->strh->type == GST_RIFF_FCC_auds) {
2670     /* constant rate stream */
2671     total = avi_stream_convert_time_to_bytes_unchecked (stream, time);
2672   } else
2673     return -1;
2674
2675   if (index == -1) {
2676     GstAviIndexEntry *entry;
2677
2678     /* no index, find index with binary search on total */
2679     GST_LOG_OBJECT (avi, "binary search for entry with total %"
2680         G_GUINT64_FORMAT, total);
2681
2682     entry = gst_util_array_binary_search (stream->index,
2683         stream->idx_n, sizeof (GstAviIndexEntry),
2684         (GCompareDataFunc) gst_avi_demux_index_entry_search,
2685         next ? GST_SEARCH_MODE_AFTER : GST_SEARCH_MODE_BEFORE, &total, NULL);
2686
2687     if (entry == NULL) {
2688       GST_LOG_OBJECT (avi, "not found, assume index 0");
2689       index = 0;
2690     } else {
2691       index = entry - stream->index;
2692       GST_LOG_OBJECT (avi, "found at %u", index);
2693     }
2694   } else {
2695     GST_LOG_OBJECT (avi, "converted time to index %u", index);
2696   }
2697
2698   return index;
2699 }
2700
2701 static inline GstAviStream *
2702 gst_avi_demux_stream_for_id (GstAviDemux * avi, guint32 id)
2703 {
2704   guint stream_nr;
2705   GstAviStream *stream;
2706
2707   /* get the stream for this entry */
2708   stream_nr = CHUNKID_TO_STREAMNR (id);
2709   if (G_UNLIKELY (stream_nr >= avi->num_streams)) {
2710     GST_WARNING_OBJECT (avi,
2711         "invalid stream nr %d (0x%08x, %" GST_FOURCC_FORMAT ")", stream_nr, id,
2712         GST_FOURCC_ARGS (id));
2713     return NULL;
2714   }
2715   stream = &avi->stream[stream_nr];
2716   if (G_UNLIKELY (!stream->strh)) {
2717     GST_WARNING_OBJECT (avi, "Unhandled stream %d, skipping", stream_nr);
2718     return NULL;
2719   }
2720   return stream;
2721 }
2722
2723 /*
2724  * gst_avi_demux_parse_index:
2725  * @avi: calling element (used for debugging/errors).
2726  * @buf: buffer containing the full index.
2727  *
2728  * Read index entries from the provided buffer.
2729  * The buffer should contain a GST_RIFF_TAG_idx1 chunk.
2730  */
2731 static gboolean
2732 gst_avi_demux_parse_index (GstAviDemux * avi, GstBuffer * buf)
2733 {
2734   GstMapInfo map;
2735   guint i, num, n;
2736   gst_riff_index_entry *index;
2737   GstClockTime stamp;
2738   GstAviStream *stream;
2739   GstAviIndexEntry entry;
2740   guint32 id;
2741
2742   if (!buf)
2743     return FALSE;
2744
2745   gst_buffer_map (buf, &map, GST_MAP_READ);
2746
2747   stamp = gst_util_get_timestamp ();
2748
2749   /* see how many items in the index */
2750   num = map.size / sizeof (gst_riff_index_entry);
2751   if (num == 0)
2752     goto empty_list;
2753
2754   GST_INFO_OBJECT (avi, "Parsing index, nr_entries = %6d", num);
2755
2756   index = (gst_riff_index_entry *) map.data;
2757
2758   /* figure out if the index is 0 based or relative to the MOVI start */
2759   entry.offset = GST_READ_UINT32_LE (&index[0].offset);
2760   if (entry.offset < avi->offset) {
2761     avi->index_offset = avi->offset + 8;
2762     GST_DEBUG ("index_offset = %" G_GUINT64_FORMAT, avi->index_offset);
2763   } else {
2764     avi->index_offset = 0;
2765     GST_DEBUG ("index is 0 based");
2766   }
2767
2768   for (i = 0, n = 0; i < num; i++) {
2769     id = GST_READ_UINT32_LE (&index[i].id);
2770     entry.offset = GST_READ_UINT32_LE (&index[i].offset);
2771
2772     /* some sanity checks */
2773     if (G_UNLIKELY (id == GST_RIFF_rec || id == 0 ||
2774             (entry.offset == 0 && n > 0)))
2775       continue;
2776
2777     /* get the stream for this entry */
2778     stream = gst_avi_demux_stream_for_id (avi, id);
2779     if (G_UNLIKELY (!stream))
2780       continue;
2781
2782     /* handle offset and size */
2783     entry.offset += avi->index_offset + 8;
2784     entry.size = GST_READ_UINT32_LE (&index[i].size);
2785
2786     /* handle flags */
2787     if (stream->strh->type == GST_RIFF_FCC_auds) {
2788       /* all audio frames are keyframes */
2789       ENTRY_SET_KEYFRAME (&entry);
2790     } else if (stream->strh->type == GST_RIFF_FCC_vids &&
2791         stream->strf.vids->compression == GST_RIFF_DXSB) {
2792       /* all xsub frames are keyframes */
2793       ENTRY_SET_KEYFRAME (&entry);
2794     } else {
2795       guint32 flags;
2796       /* else read flags */
2797       flags = GST_READ_UINT32_LE (&index[i].flags);
2798       if (flags & GST_RIFF_IF_KEYFRAME) {
2799         ENTRY_SET_KEYFRAME (&entry);
2800       } else {
2801         ENTRY_UNSET_KEYFRAME (&entry);
2802       }
2803     }
2804
2805     /* and add */
2806     if (G_UNLIKELY (!gst_avi_demux_add_index (avi, stream, num, &entry)))
2807       goto out_of_mem;
2808
2809     n++;
2810   }
2811   gst_buffer_unmap (buf, &map);
2812   gst_buffer_unref (buf);
2813
2814   /* get stream stats now */
2815   avi->have_index = gst_avi_demux_do_index_stats (avi);
2816
2817   stamp = gst_util_get_timestamp () - stamp;
2818   GST_DEBUG_OBJECT (avi, "index parsing took %" GST_TIME_FORMAT,
2819       GST_TIME_ARGS (stamp));
2820
2821   return TRUE;
2822
2823   /* ERRORS */
2824 empty_list:
2825   {
2826     GST_DEBUG_OBJECT (avi, "empty index");
2827     gst_buffer_unmap (buf, &map);
2828     gst_buffer_unref (buf);
2829     return FALSE;
2830   }
2831 out_of_mem:
2832   {
2833     GST_ELEMENT_ERROR (avi, RESOURCE, NO_SPACE_LEFT, (NULL),
2834         ("Cannot allocate memory for %u*%u=%u bytes",
2835             (guint) sizeof (GstAviIndexEntry), num,
2836             (guint) sizeof (GstAviIndexEntry) * num));
2837     gst_buffer_unmap (buf, &map);
2838     gst_buffer_unref (buf);
2839     return FALSE;
2840   }
2841 }
2842
2843 /*
2844  * gst_avi_demux_stream_index:
2845  * @avi: avi demuxer object.
2846  *
2847  * Seeks to index and reads it.
2848  */
2849 static void
2850 gst_avi_demux_stream_index (GstAviDemux * avi)
2851 {
2852   GstFlowReturn res;
2853   guint64 offset = avi->offset;
2854   GstBuffer *buf = NULL;
2855   guint32 tag;
2856   guint32 size;
2857   GstMapInfo map;
2858
2859   GST_DEBUG ("demux stream index at offset %" G_GUINT64_FORMAT, offset);
2860
2861   /* get chunk information */
2862   res = gst_pad_pull_range (avi->sinkpad, offset, 8, &buf);
2863   if (res != GST_FLOW_OK)
2864     goto pull_failed;
2865
2866   gst_buffer_map (buf, &map, GST_MAP_READ);
2867   if (map.size < 8)
2868     goto too_small;
2869
2870   /* check tag first before blindy trying to read 'size' bytes */
2871   tag = GST_READ_UINT32_LE (map.data);
2872   size = GST_READ_UINT32_LE (map.data + 4);
2873   if (tag == GST_RIFF_TAG_LIST) {
2874     /* this is the movi tag */
2875     GST_DEBUG_OBJECT (avi, "skip LIST chunk, size %" G_GUINT32_FORMAT,
2876         (8 + GST_ROUND_UP_2 (size)));
2877     offset += 8 + GST_ROUND_UP_2 (size);
2878     gst_buffer_unmap (buf, &map);
2879     gst_buffer_unref (buf);
2880
2881     buf = NULL;
2882     res = gst_pad_pull_range (avi->sinkpad, offset, 8, &buf);
2883     if (res != GST_FLOW_OK)
2884       goto pull_failed;
2885
2886     gst_buffer_map (buf, &map, GST_MAP_READ);
2887     if (map.size < 8)
2888       goto too_small;
2889
2890     tag = GST_READ_UINT32_LE (map.data);
2891     size = GST_READ_UINT32_LE (map.data + 4);
2892   }
2893   gst_buffer_unmap (buf, &map);
2894   gst_buffer_unref (buf);
2895
2896   if (tag != GST_RIFF_TAG_idx1)
2897     goto no_index;
2898   if (!size)
2899     goto zero_index;
2900
2901   GST_DEBUG ("index found at offset %" G_GUINT64_FORMAT, offset);
2902
2903   /* read chunk, advance offset */
2904   if (gst_riff_read_chunk (GST_ELEMENT_CAST (avi),
2905           avi->sinkpad, &offset, &tag, &buf) != GST_FLOW_OK)
2906     return;
2907
2908   GST_DEBUG ("will parse index chunk size %" G_GSIZE_FORMAT " for tag %"
2909       GST_FOURCC_FORMAT, gst_buffer_get_size (buf), GST_FOURCC_ARGS (tag));
2910
2911   gst_avi_demux_parse_index (avi, buf);
2912
2913 #ifndef GST_DISABLE_GST_DEBUG
2914   /* debug our indexes */
2915   {
2916     gint i;
2917     GstAviStream *stream;
2918
2919     for (i = 0; i < avi->num_streams; i++) {
2920       stream = &avi->stream[i];
2921       GST_DEBUG_OBJECT (avi, "stream %u: %u frames, %" G_GINT64_FORMAT " bytes",
2922           i, stream->idx_n, stream->total_bytes);
2923     }
2924   }
2925 #endif
2926   return;
2927
2928   /* ERRORS */
2929 pull_failed:
2930   {
2931     GST_DEBUG_OBJECT (avi,
2932         "pull range failed: pos=%" G_GUINT64_FORMAT " size=8", offset);
2933     return;
2934   }
2935 too_small:
2936   {
2937     GST_DEBUG_OBJECT (avi, "Buffer is too small");
2938     gst_buffer_unmap (buf, &map);
2939     gst_buffer_unref (buf);
2940     return;
2941   }
2942 no_index:
2943   {
2944     GST_WARNING_OBJECT (avi,
2945         "No index data (idx1) after movi chunk, but %" GST_FOURCC_FORMAT,
2946         GST_FOURCC_ARGS (tag));
2947     return;
2948   }
2949 zero_index:
2950   {
2951     GST_WARNING_OBJECT (avi, "Empty index data (idx1) after movi chunk");
2952     return;
2953   }
2954 }
2955
2956 /*
2957  * gst_avi_demux_stream_index_push:
2958  * @avi: avi demuxer object.
2959  *
2960  * Read index.
2961  */
2962 static void
2963 gst_avi_demux_stream_index_push (GstAviDemux * avi)
2964 {
2965   guint64 offset = avi->idx1_offset;
2966   GstBuffer *buf;
2967   guint32 tag;
2968   guint32 size;
2969
2970   GST_DEBUG ("demux stream index at offset %" G_GUINT64_FORMAT, offset);
2971
2972   /* get chunk information */
2973   if (!gst_avi_demux_peek_chunk (avi, &tag, &size))
2974     return;
2975
2976   /* check tag first before blindly trying to read 'size' bytes */
2977   if (tag == GST_RIFF_TAG_LIST) {
2978     /* this is the movi tag */
2979     GST_DEBUG_OBJECT (avi, "skip LIST chunk, size %" G_GUINT32_FORMAT,
2980         (8 + GST_ROUND_UP_2 (size)));
2981     avi->idx1_offset = offset + 8 + GST_ROUND_UP_2 (size);
2982     /* issue seek to allow chain function to handle it and return! */
2983     perform_seek_to_offset (avi, avi->idx1_offset, avi->segment_seqnum);
2984     return;
2985   }
2986
2987   if (tag != GST_RIFF_TAG_idx1)
2988     goto no_index;
2989
2990   GST_DEBUG ("index found at offset %" G_GUINT64_FORMAT, offset);
2991
2992   /* flush chunk header */
2993   gst_adapter_flush (avi->adapter, 8);
2994   /* read chunk payload */
2995   buf = gst_adapter_take_buffer (avi->adapter, size);
2996   if (!buf)
2997     goto pull_failed;
2998   /* advance offset */
2999   offset += 8 + GST_ROUND_UP_2 (size);
3000
3001   GST_DEBUG ("will parse index chunk size %" G_GSIZE_FORMAT " for tag %"
3002       GST_FOURCC_FORMAT, gst_buffer_get_size (buf), GST_FOURCC_ARGS (tag));
3003
3004   avi->offset = avi->first_movi_offset;
3005   gst_avi_demux_parse_index (avi, buf);
3006
3007 #ifndef GST_DISABLE_GST_DEBUG
3008   /* debug our indexes */
3009   {
3010     gint i;
3011     GstAviStream *stream;
3012
3013     for (i = 0; i < avi->num_streams; i++) {
3014       stream = &avi->stream[i];
3015       GST_DEBUG_OBJECT (avi, "stream %u: %u frames, %" G_GINT64_FORMAT " bytes",
3016           i, stream->idx_n, stream->total_bytes);
3017     }
3018   }
3019 #endif
3020   return;
3021
3022   /* ERRORS */
3023 pull_failed:
3024   {
3025     GST_DEBUG_OBJECT (avi,
3026         "taking data from adapter failed: pos=%" G_GUINT64_FORMAT " size=%u",
3027         offset, size);
3028     return;
3029   }
3030 no_index:
3031   {
3032     GST_WARNING_OBJECT (avi,
3033         "No index data (idx1) after movi chunk, but %" GST_FOURCC_FORMAT,
3034         GST_FOURCC_ARGS (tag));
3035     return;
3036   }
3037 }
3038
3039 /*
3040  * gst_avi_demux_peek_tag:
3041  *
3042  * Returns the tag and size of the next chunk
3043  */
3044 static GstFlowReturn
3045 gst_avi_demux_peek_tag (GstAviDemux * avi, guint64 offset, guint32 * tag,
3046     guint * size)
3047 {
3048   GstFlowReturn res;
3049   GstBuffer *buf = NULL;
3050   GstMapInfo map;
3051
3052   res = gst_pad_pull_range (avi->sinkpad, offset, 8, &buf);
3053   if (res != GST_FLOW_OK)
3054     goto pull_failed;
3055
3056   gst_buffer_map (buf, &map, GST_MAP_READ);
3057   if (map.size != 8)
3058     goto wrong_size;
3059
3060   *tag = GST_READ_UINT32_LE (map.data);
3061   *size = GST_READ_UINT32_LE (map.data + 4);
3062
3063   GST_LOG_OBJECT (avi, "Tag[%" GST_FOURCC_FORMAT "] (size:%d) %"
3064       G_GINT64_FORMAT " -- %" G_GINT64_FORMAT, GST_FOURCC_ARGS (*tag),
3065       *size, offset + 8, offset + 8 + (gint64) * size);
3066
3067 done:
3068   gst_buffer_unmap (buf, &map);
3069   gst_buffer_unref (buf);
3070
3071   return res;
3072
3073   /* ERRORS */
3074 pull_failed:
3075   {
3076     GST_DEBUG_OBJECT (avi, "pull_ranged returned %s", gst_flow_get_name (res));
3077     return res;
3078   }
3079 wrong_size:
3080   {
3081     GST_DEBUG_OBJECT (avi, "got %" G_GSIZE_FORMAT " bytes which is <> 8 bytes",
3082         map.size);
3083     res = GST_FLOW_ERROR;
3084     goto done;
3085   }
3086 }
3087
3088 /*
3089  * gst_avi_demux_next_data_buffer:
3090  *
3091  * Returns the offset and size of the next buffer
3092  * Position is the position of the buffer (after tag and size)
3093  */
3094 static GstFlowReturn
3095 gst_avi_demux_next_data_buffer (GstAviDemux * avi, guint64 * offset,
3096     guint32 * tag, guint * size)
3097 {
3098   guint64 off = *offset;
3099   guint _size = 0;
3100   GstFlowReturn res;
3101
3102   do {
3103     res = gst_avi_demux_peek_tag (avi, off, tag, &_size);
3104     if (res != GST_FLOW_OK)
3105       break;
3106     if (*tag == GST_RIFF_TAG_LIST || *tag == GST_RIFF_TAG_RIFF)
3107       off += 8 + 4;             /* skip tag + size + subtag */
3108     else {
3109       *offset = off + 8;
3110       *size = _size;
3111       break;
3112     }
3113   } while (TRUE);
3114
3115   return res;
3116 }
3117
3118 /*
3119  * gst_avi_demux_stream_scan:
3120  * @avi: calling element (used for debugging/errors).
3121  *
3122  * Scan the file for all chunks to "create" a new index.
3123  * pull-range based
3124  */
3125 static gboolean
3126 gst_avi_demux_stream_scan (GstAviDemux * avi)
3127 {
3128   GstFlowReturn res;
3129   GstAviStream *stream;
3130   guint64 pos = 0;
3131   guint64 length;
3132   gint64 tmplength;
3133   guint32 tag = 0;
3134   guint num;
3135
3136   /* FIXME:
3137    * - implement non-seekable source support.
3138    */
3139   GST_DEBUG_OBJECT (avi, "Creating index");
3140
3141   /* get the size of the file */
3142   if (!gst_pad_peer_query_duration (avi->sinkpad, GST_FORMAT_BYTES, &tmplength))
3143     return FALSE;
3144   length = tmplength;
3145
3146   /* guess the total amount of entries we expect */
3147   num = 16000;
3148
3149   while (TRUE) {
3150     GstAviIndexEntry entry;
3151     guint size = 0;
3152
3153     /* start reading data buffers to find the id and offset */
3154     res = gst_avi_demux_next_data_buffer (avi, &pos, &tag, &size);
3155     if (G_UNLIKELY (res != GST_FLOW_OK))
3156       break;
3157
3158     /* get stream */
3159     stream = gst_avi_demux_stream_for_id (avi, tag);
3160     if (G_UNLIKELY (!stream))
3161       goto next;
3162
3163     /* we can't figure out the keyframes, assume they all are */
3164     entry.flags = GST_AVI_KEYFRAME;
3165     entry.offset = pos;
3166     entry.size = size;
3167
3168     /* and add to the index of this stream */
3169     if (G_UNLIKELY (!gst_avi_demux_add_index (avi, stream, num, &entry)))
3170       goto out_of_mem;
3171
3172   next:
3173     /* update position */
3174     pos += GST_ROUND_UP_2 (size);
3175     if (G_UNLIKELY (pos > length)) {
3176       GST_WARNING_OBJECT (avi,
3177           "Stopping index lookup since we are further than EOF");
3178       break;
3179     }
3180   }
3181
3182   /* collect stats */
3183   avi->have_index = gst_avi_demux_do_index_stats (avi);
3184
3185   return TRUE;
3186
3187   /* ERRORS */
3188 out_of_mem:
3189   {
3190     GST_ELEMENT_ERROR (avi, RESOURCE, NO_SPACE_LEFT, (NULL),
3191         ("Cannot allocate memory for %u*%u=%u bytes",
3192             (guint) sizeof (GstAviIndexEntry), num,
3193             (guint) sizeof (GstAviIndexEntry) * num));
3194     return FALSE;
3195   }
3196 }
3197
3198 static void
3199 gst_avi_demux_calculate_durations_from_index (GstAviDemux * avi)
3200 {
3201   guint i;
3202   GstClockTime total;
3203   GstAviStream *stream;
3204
3205   total = GST_CLOCK_TIME_NONE;
3206
3207   /* all streams start at a timestamp 0 */
3208   for (i = 0; i < avi->num_streams; i++) {
3209     GstClockTime duration, hduration;
3210     gst_riff_strh *strh;
3211
3212     stream = &avi->stream[i];
3213     if (G_UNLIKELY (!stream || !stream->idx_n || !(strh = stream->strh)))
3214       continue;
3215
3216     /* get header duration for the stream */
3217     hduration = stream->hdr_duration;
3218     /* index duration calculated during parsing */
3219     duration = stream->idx_duration;
3220
3221     /* now pick a good duration */
3222     if (GST_CLOCK_TIME_IS_VALID (duration)) {
3223       /* index gave valid duration, use that */
3224       GST_INFO ("Stream %p duration according to index: %" GST_TIME_FORMAT,
3225           stream, GST_TIME_ARGS (duration));
3226     } else {
3227       /* fall back to header info to calculate a duration */
3228       duration = hduration;
3229     }
3230     GST_INFO ("Setting duration of stream #%d to %" GST_TIME_FORMAT,
3231         i, GST_TIME_ARGS (duration));
3232     /* set duration for the stream */
3233     stream->duration = duration;
3234
3235     /* find total duration */
3236     if (total == GST_CLOCK_TIME_NONE ||
3237         (GST_CLOCK_TIME_IS_VALID (duration) && duration > total))
3238       total = duration;
3239   }
3240
3241   if (GST_CLOCK_TIME_IS_VALID (total) && (total > 0)) {
3242     /* now update the duration for those streams where we had none */
3243     for (i = 0; i < avi->num_streams; i++) {
3244       stream = &avi->stream[i];
3245
3246       if (!GST_CLOCK_TIME_IS_VALID (stream->duration)
3247           || stream->duration == 0) {
3248         stream->duration = total;
3249
3250         GST_INFO ("Stream %p duration according to total: %" GST_TIME_FORMAT,
3251             stream, GST_TIME_ARGS (total));
3252       }
3253     }
3254   }
3255
3256   /* and set the total duration in the segment. */
3257   GST_INFO ("Setting total duration to: %" GST_TIME_FORMAT,
3258       GST_TIME_ARGS (total));
3259
3260   avi->segment.duration = total;
3261 }
3262
3263 /* returns FALSE if there are no pads to deliver event to,
3264  * otherwise TRUE (whatever the outcome of event sending),
3265  * takes ownership of the event. */
3266 static gboolean
3267 gst_avi_demux_push_event (GstAviDemux * avi, GstEvent * event)
3268 {
3269   gboolean result = FALSE;
3270   gint i;
3271
3272   GST_DEBUG_OBJECT (avi, "sending %s event to %d streams",
3273       GST_EVENT_TYPE_NAME (event), avi->num_streams);
3274
3275   for (i = 0; i < avi->num_streams; i++) {
3276     GstAviStream *stream = &avi->stream[i];
3277
3278     if (stream->pad) {
3279       result = TRUE;
3280       gst_pad_push_event (stream->pad, gst_event_ref (event));
3281     }
3282   }
3283   gst_event_unref (event);
3284   return result;
3285 }
3286
3287 static void
3288 gst_avi_demux_check_seekability (GstAviDemux * avi)
3289 {
3290   GstQuery *query;
3291   gboolean seekable = FALSE;
3292   gint64 start = -1, stop = -1;
3293
3294   query = gst_query_new_seeking (GST_FORMAT_BYTES);
3295   if (!gst_pad_peer_query (avi->sinkpad, query)) {
3296     GST_DEBUG_OBJECT (avi, "seeking query failed");
3297     goto done;
3298   }
3299
3300   gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
3301
3302   /* try harder to query upstream size if we didn't get it the first time */
3303   if (seekable && stop == -1) {
3304     GST_DEBUG_OBJECT (avi, "doing duration query to fix up unset stop");
3305     gst_pad_peer_query_duration (avi->sinkpad, GST_FORMAT_BYTES, &stop);
3306   }
3307
3308   /* if upstream doesn't know the size, it's likely that it's not seekable in
3309    * practice even if it technically may be seekable */
3310   if (seekable && (start != 0 || stop <= start)) {
3311     GST_DEBUG_OBJECT (avi, "seekable but unknown start/stop -> disable");
3312     seekable = FALSE;
3313   }
3314
3315 done:
3316   GST_INFO_OBJECT (avi, "seekable: %d (%" G_GUINT64_FORMAT " - %"
3317       G_GUINT64_FORMAT ")", seekable, start, stop);
3318   avi->seekable = seekable;
3319
3320   gst_query_unref (query);
3321 }
3322
3323 /*
3324  * Read AVI headers when streaming
3325  */
3326 static GstFlowReturn
3327 gst_avi_demux_stream_header_push (GstAviDemux * avi)
3328 {
3329   GstFlowReturn ret = GST_FLOW_OK;
3330   guint32 tag = 0;
3331   guint32 ltag = 0;
3332   guint32 size = 0;
3333   const guint8 *data;
3334   GstBuffer *buf = NULL, *sub = NULL;
3335   guint offset = 4;
3336   gint i;
3337   GstTagList *tags = NULL;
3338   guint8 fourcc[4];
3339
3340   GST_DEBUG ("Reading and parsing avi headers: %d", avi->header_state);
3341
3342   switch (avi->header_state) {
3343     case GST_AVI_DEMUX_HEADER_TAG_LIST:
3344     again:
3345       if (gst_avi_demux_peek_chunk (avi, &tag, &size)) {
3346         avi->offset += 8 + GST_ROUND_UP_2 (size);
3347         if (tag != GST_RIFF_TAG_LIST)
3348           goto header_no_list;
3349
3350         gst_adapter_flush (avi->adapter, 8);
3351         /* Find the 'hdrl' LIST tag */
3352         GST_DEBUG ("Reading %d bytes", size);
3353         buf = gst_adapter_take_buffer (avi->adapter, size);
3354
3355         gst_buffer_extract (buf, 0, fourcc, 4);
3356
3357         if (GST_READ_UINT32_LE (fourcc) != GST_RIFF_LIST_hdrl) {
3358           GST_WARNING_OBJECT (avi, "Invalid AVI header (no hdrl at start): %"
3359               GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag));
3360           gst_buffer_unref (buf);
3361           goto again;
3362         }
3363
3364         /* mind padding */
3365         if (size & 1)
3366           gst_adapter_flush (avi->adapter, 1);
3367
3368         GST_DEBUG ("'hdrl' LIST tag found. Parsing next chunk");
3369
3370         gst_avi_demux_roundup_list (avi, &buf);
3371
3372         /* the hdrl starts with a 'avih' header */
3373         if (!gst_riff_parse_chunk (GST_ELEMENT_CAST (avi), buf, &offset, &tag,
3374                 &sub))
3375           goto header_no_avih;
3376
3377         if (tag != GST_RIFF_TAG_avih)
3378           goto header_no_avih;
3379
3380         if (!gst_avi_demux_parse_avih (avi, sub, &avi->avih))
3381           goto header_wrong_avih;
3382
3383         GST_DEBUG_OBJECT (avi, "AVI header ok, reading elemnts from header");
3384
3385         /* now, read the elements from the header until the end */
3386         while (gst_riff_parse_chunk (GST_ELEMENT_CAST (avi), buf, &offset, &tag,
3387                 &sub)) {
3388           /* sub can be NULL on empty tags */
3389           if (!sub)
3390             continue;
3391
3392           switch (tag) {
3393             case GST_RIFF_TAG_LIST:
3394               if (gst_buffer_get_size (sub) < 4)
3395                 goto next;
3396
3397               gst_buffer_extract (sub, 0, fourcc, 4);
3398
3399               switch (GST_READ_UINT32_LE (fourcc)) {
3400                 case GST_RIFF_LIST_strl:
3401                   if (!(gst_avi_demux_parse_stream (avi, sub))) {
3402                     sub = NULL;
3403                     GST_ELEMENT_WARNING (avi, STREAM, DEMUX, (NULL),
3404                         ("failed to parse stream, ignoring"));
3405                     goto next;
3406                   }
3407                   sub = NULL;
3408                   goto next;
3409                 case GST_RIFF_LIST_odml:
3410                   gst_avi_demux_parse_odml (avi, sub);
3411                   sub = NULL;
3412                   break;
3413                 default:
3414                   GST_WARNING_OBJECT (avi,
3415                       "Unknown list %" GST_FOURCC_FORMAT " in AVI header",
3416                       GST_FOURCC_ARGS (GST_READ_UINT32_LE (fourcc)));
3417                   /* fall-through */
3418                 case GST_RIFF_TAG_JUNQ:
3419                 case GST_RIFF_TAG_JUNK:
3420                   goto next;
3421               }
3422               break;
3423             case GST_RIFF_IDIT:
3424               gst_avi_demux_parse_idit (avi, sub);
3425               goto next;
3426             default:
3427               GST_WARNING_OBJECT (avi,
3428                   "Unknown tag %" GST_FOURCC_FORMAT " in AVI header",
3429                   GST_FOURCC_ARGS (tag));
3430               /* Only get buffer for debugging if the memdump is needed  */
3431               if (gst_debug_category_get_threshold (GST_CAT_DEFAULT) >= 9) {
3432                 GstMapInfo map;
3433
3434                 gst_buffer_map (sub, &map, GST_MAP_READ);
3435                 GST_MEMDUMP_OBJECT (avi, "Unknown tag", map.data, map.size);
3436                 gst_buffer_unmap (sub, &map);
3437               }
3438               /* fall-through */
3439             case GST_RIFF_TAG_JUNQ:
3440             case GST_RIFF_TAG_JUNK:
3441             next:
3442               /* move to next chunk */
3443               if (sub)
3444                 gst_buffer_unref (sub);
3445               sub = NULL;
3446               break;
3447           }
3448         }
3449         gst_buffer_unref (buf);
3450         GST_DEBUG ("elements parsed");
3451
3452         /* check parsed streams */
3453         if (avi->num_streams == 0) {
3454           goto no_streams;
3455         } else if (avi->num_streams != avi->avih->streams) {
3456           GST_WARNING_OBJECT (avi,
3457               "Stream header mentioned %d streams, but %d available",
3458               avi->avih->streams, avi->num_streams);
3459         }
3460         GST_DEBUG ("Get junk and info next");
3461         avi->header_state = GST_AVI_DEMUX_HEADER_INFO;
3462       } else {
3463         /* Need more data */
3464         return ret;
3465       }
3466       /* fall-though */
3467     case GST_AVI_DEMUX_HEADER_INFO:
3468       GST_DEBUG_OBJECT (avi, "skipping junk between header and data ...");
3469       while (TRUE) {
3470         if (gst_adapter_available (avi->adapter) < 12)
3471           return GST_FLOW_OK;
3472
3473         data = gst_adapter_map (avi->adapter, 12);
3474         tag = GST_READ_UINT32_LE (data);
3475         size = GST_READ_UINT32_LE (data + 4);
3476         ltag = GST_READ_UINT32_LE (data + 8);
3477         gst_adapter_unmap (avi->adapter);
3478
3479         if (tag == GST_RIFF_TAG_LIST) {
3480           switch (ltag) {
3481             case GST_RIFF_LIST_movi:
3482               gst_adapter_flush (avi->adapter, 12);
3483               if (!avi->first_movi_offset)
3484                 avi->first_movi_offset = avi->offset;
3485               avi->offset += 12;
3486               avi->idx1_offset = avi->offset + size - 4;
3487               goto skipping_done;
3488             case GST_RIFF_LIST_INFO:
3489               GST_DEBUG ("Found INFO chunk");
3490               if (gst_avi_demux_peek_chunk (avi, &tag, &size)) {
3491                 GST_DEBUG ("got size %d", size);
3492                 avi->offset += 12;
3493                 gst_adapter_flush (avi->adapter, 12);
3494                 if (size > 4) {
3495                   buf = gst_adapter_take_buffer (avi->adapter, size - 4);
3496                   /* mind padding */
3497                   if (size & 1)
3498                     gst_adapter_flush (avi->adapter, 1);
3499                   gst_riff_parse_info (GST_ELEMENT_CAST (avi), buf, &tags);
3500                   if (tags) {
3501                     if (avi->globaltags) {
3502                       gst_tag_list_insert (avi->globaltags, tags,
3503                           GST_TAG_MERGE_REPLACE);
3504                       gst_tag_list_unref (tags);
3505                     } else {
3506                       avi->globaltags = tags;
3507                     }
3508                   }
3509                   tags = NULL;
3510                   gst_buffer_unref (buf);
3511
3512                   avi->offset += GST_ROUND_UP_2 (size) - 4;
3513                 } else {
3514                   GST_DEBUG ("skipping INFO LIST prefix");
3515                 }
3516               } else {
3517                 /* Need more data */
3518                 return GST_FLOW_OK;
3519               }
3520               break;
3521             default:
3522               if (gst_avi_demux_peek_chunk (avi, &tag, &size) || size == 0) {
3523                 /* accept 0 size buffer here */
3524                 avi->abort_buffering = FALSE;
3525                 avi->offset += 8 + GST_ROUND_UP_2 (size);
3526                 gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
3527               } else {
3528                 /* Need more data */
3529                 return GST_FLOW_OK;
3530               }
3531               break;
3532           }
3533         } else {
3534           if (gst_avi_demux_peek_chunk (avi, &tag, &size) || size == 0) {
3535             /* accept 0 size buffer here */
3536             avi->abort_buffering = FALSE;
3537             avi->offset += 8 + GST_ROUND_UP_2 (size);
3538             gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
3539           } else {
3540             /* Need more data */
3541             return GST_FLOW_OK;
3542           }
3543         }
3544       }
3545       break;
3546     default:
3547       GST_WARNING ("unhandled header state: %d", avi->header_state);
3548       break;
3549   }
3550 skipping_done:
3551
3552   GST_DEBUG_OBJECT (avi, "skipping done ... (streams=%u, stream[0].indexes=%p)",
3553       avi->num_streams, avi->stream[0].indexes);
3554
3555   GST_DEBUG ("Found movi chunk. Starting to stream data");
3556   avi->state = GST_AVI_DEMUX_MOVI;
3557
3558   /* no indexes in push mode, but it still sets some variables */
3559   gst_avi_demux_calculate_durations_from_index (avi);
3560
3561   gst_avi_demux_expose_streams (avi, TRUE);
3562
3563   /* prepare all streams for index 0 */
3564   for (i = 0; i < avi->num_streams; i++)
3565     avi->stream[i].current_entry = 0;
3566
3567   /* create initial NEWSEGMENT event */
3568   if (avi->seg_event)
3569     gst_event_unref (avi->seg_event);
3570   avi->seg_event = gst_event_new_segment (&avi->segment);
3571   if (avi->segment_seqnum)
3572     gst_event_set_seqnum (avi->seg_event, avi->segment_seqnum);
3573
3574   gst_avi_demux_check_seekability (avi);
3575
3576   /* at this point we know all the streams and we can signal the no more
3577    * pads signal */
3578   GST_DEBUG_OBJECT (avi, "signaling no more pads");
3579   gst_element_no_more_pads (GST_ELEMENT_CAST (avi));
3580
3581   return GST_FLOW_OK;
3582
3583   /* ERRORS */
3584 no_streams:
3585   {
3586     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("No streams found"));
3587     return GST_FLOW_ERROR;
3588   }
3589 header_no_list:
3590   {
3591     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3592         ("Invalid AVI header (no LIST at start): %"
3593             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3594     return GST_FLOW_ERROR;
3595   }
3596 header_no_avih:
3597   {
3598     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3599         ("Invalid AVI header (no avih at start): %"
3600             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3601     if (sub)
3602       gst_buffer_unref (sub);
3603
3604     gst_buffer_unref (buf);
3605     return GST_FLOW_ERROR;
3606   }
3607 header_wrong_avih:
3608   {
3609     gst_buffer_unref (buf);
3610     return GST_FLOW_ERROR;
3611   }
3612 }
3613
3614 static void
3615 gst_avi_demux_add_date_tag (GstAviDemux * avi, gint y, gint m, gint d,
3616     gint h, gint min, gint s)
3617 {
3618   GDate *date;
3619   GstDateTime *dt;
3620
3621   date = g_date_new_dmy (d, m, y);
3622   if (!g_date_valid (date)) {
3623     /* bogus date */
3624     GST_WARNING_OBJECT (avi, "Refusing to add invalid date %d-%d-%d", y, m, d);
3625     g_date_free (date);
3626     return;
3627   }
3628
3629   dt = gst_date_time_new_local_time (y, m, d, h, min, s);
3630
3631   if (avi->globaltags == NULL)
3632     avi->globaltags = gst_tag_list_new_empty ();
3633
3634   gst_tag_list_add (avi->globaltags, GST_TAG_MERGE_REPLACE, GST_TAG_DATE, date,
3635       NULL);
3636   g_date_free (date);
3637   if (dt) {
3638     gst_tag_list_add (avi->globaltags, GST_TAG_MERGE_REPLACE, GST_TAG_DATE_TIME,
3639         dt, NULL);
3640     gst_date_time_unref (dt);
3641   }
3642 }
3643
3644 static void
3645 gst_avi_demux_parse_idit_nums_only (GstAviDemux * avi, gchar * data)
3646 {
3647   gint y, m, d;
3648   gint hr = 0, min = 0, sec = 0;
3649   gint ret;
3650
3651   GST_DEBUG ("data : '%s'", data);
3652
3653   ret = sscanf (data, "%d:%d:%d %d:%d:%d", &y, &m, &d, &hr, &min, &sec);
3654   if (ret < 3) {
3655     /* Attempt YYYY/MM/DD/ HH:MM variant (found in CASIO cameras) */
3656     ret = sscanf (data, "%04d/%02d/%02d/ %d:%d", &y, &m, &d, &hr, &min);
3657     if (ret < 3) {
3658       GST_WARNING_OBJECT (avi, "Failed to parse IDIT tag");
3659       return;
3660     }
3661   }
3662   gst_avi_demux_add_date_tag (avi, y, m, d, hr, min, sec);
3663 }
3664
3665 static gint
3666 get_month_num (gchar * data, guint size)
3667 {
3668   if (g_ascii_strncasecmp (data, "jan", 3) == 0) {
3669     return 1;
3670   } else if (g_ascii_strncasecmp (data, "feb", 3) == 0) {
3671     return 2;
3672   } else if (g_ascii_strncasecmp (data, "mar", 3) == 0) {
3673     return 3;
3674   } else if (g_ascii_strncasecmp (data, "apr", 3) == 0) {
3675     return 4;
3676   } else if (g_ascii_strncasecmp (data, "may", 3) == 0) {
3677     return 5;
3678   } else if (g_ascii_strncasecmp (data, "jun", 3) == 0) {
3679     return 6;
3680   } else if (g_ascii_strncasecmp (data, "jul", 3) == 0) {
3681     return 7;
3682   } else if (g_ascii_strncasecmp (data, "aug", 3) == 0) {
3683     return 8;
3684   } else if (g_ascii_strncasecmp (data, "sep", 3) == 0) {
3685     return 9;
3686   } else if (g_ascii_strncasecmp (data, "oct", 3) == 0) {
3687     return 10;
3688   } else if (g_ascii_strncasecmp (data, "nov", 3) == 0) {
3689     return 11;
3690   } else if (g_ascii_strncasecmp (data, "dec", 3) == 0) {
3691     return 12;
3692   }
3693
3694   return 0;
3695 }
3696
3697 static void
3698 gst_avi_demux_parse_idit_text (GstAviDemux * avi, gchar * data)
3699 {
3700   gint year, month, day;
3701   gint hour, min, sec;
3702   gint ret;
3703   gchar weekday[4];
3704   gchar monthstr[4];
3705
3706   ret = sscanf (data, "%3s %3s %d %d:%d:%d %d", weekday, monthstr, &day, &hour,
3707       &min, &sec, &year);
3708   if (ret != 7) {
3709     GST_WARNING_OBJECT (avi, "Failed to parse IDIT tag");
3710     return;
3711   }
3712   month = get_month_num (monthstr, strlen (monthstr));
3713   gst_avi_demux_add_date_tag (avi, year, month, day, hour, min, sec);
3714 }
3715
3716 static void
3717 gst_avi_demux_parse_idit (GstAviDemux * avi, GstBuffer * buf)
3718 {
3719   GstMapInfo map;
3720   gchar *ptr;
3721   gsize left;
3722   gchar *safedata = NULL;
3723
3724   gst_buffer_map (buf, &map, GST_MAP_READ);
3725   /*
3726    * According to:
3727    * http://www.eden-foundation.org/products/code/film_date_stamp/index.html
3728    *
3729    * This tag could be in one of the below formats
3730    * 2005:08:17 11:42:43
3731    * THU OCT 26 16:46:04 2006
3732    * Mon Mar  3 09:44:56 2008
3733    *
3734    * FIXME: Our date tag doesn't include hours
3735    */
3736
3737   /* skip eventual initial whitespace */
3738   ptr = (gchar *) map.data;
3739   left = map.size;
3740
3741   while (left > 0 && g_ascii_isspace (ptr[0])) {
3742     ptr++;
3743     left--;
3744   }
3745
3746   if (left == 0) {
3747     goto non_parsable;
3748   }
3749
3750   /* make a safe copy to add a \0 to the end of the string */
3751   safedata = g_strndup (ptr, left);
3752
3753   /* test if the first char is a alpha or a number */
3754   if (g_ascii_isdigit (ptr[0])) {
3755     gst_avi_demux_parse_idit_nums_only (avi, safedata);
3756     g_free (safedata);
3757     gst_buffer_unmap (buf, &map);
3758     return;
3759   } else if (g_ascii_isalpha (ptr[0])) {
3760     gst_avi_demux_parse_idit_text (avi, safedata);
3761     g_free (safedata);
3762     gst_buffer_unmap (buf, &map);
3763     return;
3764   }
3765
3766   g_free (safedata);
3767
3768 non_parsable:
3769   GST_WARNING_OBJECT (avi, "IDIT tag has no parsable info");
3770   gst_buffer_unmap (buf, &map);
3771 }
3772
3773 static void
3774 parse_tag_value (GstAviDemux * avi, GstTagList * taglist, const gchar * type,
3775     guint8 * ptr, guint tsize)
3776 {
3777   static const gchar *env_vars[] = { "GST_AVI_TAG_ENCODING",
3778     "GST_RIFF_TAG_ENCODING", "GST_TAG_ENCODING", NULL
3779   };
3780   GType tag_type;
3781   gchar *val;
3782
3783   tag_type = gst_tag_get_type (type);
3784   val = gst_tag_freeform_string_to_utf8 ((gchar *) ptr, tsize, env_vars);
3785
3786   if (val != NULL) {
3787     if (tag_type == G_TYPE_STRING) {
3788       gst_tag_list_add (taglist, GST_TAG_MERGE_APPEND, type, val, NULL);
3789     } else {
3790       GValue tag_val = { 0, };
3791
3792       g_value_init (&tag_val, tag_type);
3793       if (gst_value_deserialize (&tag_val, val)) {
3794         gst_tag_list_add_value (taglist, GST_TAG_MERGE_APPEND, type, &tag_val);
3795       } else {
3796         GST_WARNING_OBJECT (avi, "could not deserialize '%s' into a "
3797             "tag %s of type %s", val, type, g_type_name (tag_type));
3798       }
3799       g_value_unset (&tag_val);
3800     }
3801     g_free (val);
3802   } else {
3803     GST_WARNING_OBJECT (avi, "could not extract %s tag", type);
3804   }
3805 }
3806
3807 static void
3808 gst_avi_demux_parse_strd (GstAviDemux * avi, GstBuffer * buf)
3809 {
3810   GstMapInfo map;
3811   guint32 tag;
3812
3813   gst_buffer_map (buf, &map, GST_MAP_READ);
3814   if (map.size > 4) {
3815     guint8 *ptr = map.data;
3816     gsize left = map.size;
3817
3818     /* parsing based on
3819      * http://www.eden-foundation.org/products/code/film_date_stamp/index.html
3820      */
3821     tag = GST_READ_UINT32_LE (ptr);
3822     if ((tag == GST_MAKE_FOURCC ('A', 'V', 'I', 'F')) && (map.size > 98)) {
3823       gsize sub_size;
3824
3825       ptr += 98;
3826       left -= 98;
3827       if (!memcmp (ptr, "FUJIFILM", 8)) {
3828         GST_MEMDUMP_OBJECT (avi, "fujifim tag", ptr, 48);
3829
3830         ptr += 10;
3831         left -= 10;
3832         sub_size = 0;
3833         while (ptr[sub_size] && sub_size < left)
3834           sub_size++;
3835
3836         if (avi->globaltags == NULL)
3837           avi->globaltags = gst_tag_list_new_empty ();
3838
3839         gst_tag_list_add (avi->globaltags, GST_TAG_MERGE_APPEND,
3840             GST_TAG_DEVICE_MANUFACTURER, "FUJIFILM", NULL);
3841         parse_tag_value (avi, avi->globaltags, GST_TAG_DEVICE_MODEL, ptr,
3842             sub_size);
3843
3844         while (ptr[sub_size] == '\0' && sub_size < left)
3845           sub_size++;
3846
3847         ptr += sub_size;
3848         left -= sub_size;
3849         sub_size = 0;
3850         while (ptr[sub_size] && sub_size < left)
3851           sub_size++;
3852         if (ptr[4] == ':')
3853           ptr[4] = '-';
3854         if (ptr[7] == ':')
3855           ptr[7] = '-';
3856
3857         parse_tag_value (avi, avi->globaltags, GST_TAG_DATE_TIME, ptr,
3858             sub_size);
3859       }
3860     }
3861   }
3862   gst_buffer_unmap (buf, &map);
3863 }
3864
3865 /*
3866  * gst_avi_demux_parse_ncdt:
3867  * @element: caller element (used for debugging/error).
3868  * @buf: input data to be used for parsing, stripped from header.
3869  * @taglist: a pointer to a taglist (returned by this function)
3870  *           containing information about this stream. May be
3871  *           NULL if no supported tags were found.
3872  *
3873  * Parses Nikon metadata from input data.
3874  */
3875 static void
3876 gst_avi_demux_parse_ncdt (GstAviDemux * avi, GstBuffer * buf,
3877     GstTagList ** _taglist)
3878 {
3879   GstMapInfo info;
3880   guint8 *ptr;
3881   gsize left;
3882   guint tsize;
3883   guint32 tag;
3884   const gchar *type;
3885   GstTagList *taglist;
3886
3887   g_return_if_fail (_taglist != NULL);
3888
3889   if (!buf) {
3890     *_taglist = NULL;
3891     return;
3892   }
3893   gst_buffer_map (buf, &info, GST_MAP_READ);
3894
3895   taglist = gst_tag_list_new_empty ();
3896
3897   ptr = info.data;
3898   left = info.size;
3899
3900   while (left > 8) {
3901     tag = GST_READ_UINT32_LE (ptr);
3902     tsize = GST_READ_UINT32_LE (ptr + 4);
3903
3904     GST_MEMDUMP_OBJECT (avi, "tag chunk", ptr, MIN (tsize + 8, left));
3905
3906     left -= 8;
3907     ptr += 8;
3908
3909     GST_DEBUG_OBJECT (avi, "tag %" GST_FOURCC_FORMAT ", size %u",
3910         GST_FOURCC_ARGS (tag), tsize);
3911
3912     if (tsize > left) {
3913       GST_WARNING_OBJECT (avi,
3914           "Tagsize %d is larger than available data %" G_GSIZE_FORMAT,
3915           tsize, left);
3916       tsize = left;
3917     }
3918
3919     /* find out the type of metadata */
3920     switch (tag) {
3921       case GST_RIFF_LIST_nctg:
3922         while (tsize > 4) {
3923           guint16 sub_tag = GST_READ_UINT16_LE (ptr);
3924           guint16 sub_size = GST_READ_UINT16_LE (ptr + 2);
3925
3926           tsize -= 4;
3927           ptr += 4;
3928           left -= 4;
3929
3930           if (sub_size > tsize)
3931             break;
3932
3933           GST_DEBUG_OBJECT (avi, "sub-tag %u, size %u", sub_tag, sub_size);
3934           /* http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/Nikon.html#NCTG
3935            * for some reason the sub_tag has a +2 offset
3936            */
3937           switch (sub_tag) {
3938             case 0x03:         /* Make */
3939               type = GST_TAG_DEVICE_MANUFACTURER;
3940               break;
3941             case 0x04:         /* Model */
3942               type = GST_TAG_DEVICE_MODEL;
3943               break;
3944               /* TODO: 0x05: is software version, like V1.0 */
3945             case 0x06:         /* Software */
3946               type = GST_TAG_ENCODER;
3947               break;
3948             case 0x13:         /* CreationDate */
3949               type = GST_TAG_DATE_TIME;
3950               if (left > 7) {
3951                 if (ptr[4] == ':')
3952                   ptr[4] = '-';
3953                 if (ptr[7] == ':')
3954                   ptr[7] = '-';
3955               }
3956               break;
3957             default:
3958               type = NULL;
3959               break;
3960           }
3961           if (type != NULL && ptr[0] != '\0') {
3962             GST_DEBUG_OBJECT (avi, "mapped tag %u to tag %s", sub_tag, type);
3963
3964             parse_tag_value (avi, taglist, type, ptr, sub_size);
3965           }
3966
3967           ptr += sub_size;
3968           tsize -= sub_size;
3969           left -= sub_size;
3970         }
3971         break;
3972       default:
3973         type = NULL;
3974         GST_WARNING_OBJECT (avi,
3975             "Unknown ncdt (metadata) tag entry %" GST_FOURCC_FORMAT,
3976             GST_FOURCC_ARGS (tag));
3977         GST_MEMDUMP_OBJECT (avi, "Unknown ncdt", ptr, tsize);
3978         break;
3979     }
3980
3981     if (tsize & 1) {
3982       tsize++;
3983       if (tsize > left)
3984         tsize = left;
3985     }
3986
3987     ptr += tsize;
3988     left -= tsize;
3989   }
3990
3991   if (!gst_tag_list_is_empty (taglist)) {
3992     GST_INFO_OBJECT (avi, "extracted tags: %" GST_PTR_FORMAT, taglist);
3993     *_taglist = taglist;
3994   } else {
3995     *_taglist = NULL;
3996     gst_tag_list_unref (taglist);
3997   }
3998   gst_buffer_unmap (buf, &info);
3999
4000   return;
4001 }
4002
4003 /*
4004  * Read full AVI headers.
4005  */
4006 static GstFlowReturn
4007 gst_avi_demux_stream_header_pull (GstAviDemux * avi)
4008 {
4009   GstFlowReturn res;
4010   GstBuffer *buf, *sub = NULL;
4011   guint32 tag;
4012   guint offset = 4;
4013   GstElement *element = GST_ELEMENT_CAST (avi);
4014   GstClockTime stamp;
4015   GstTagList *tags = NULL;
4016   guint8 fourcc[4];
4017
4018   stamp = gst_util_get_timestamp ();
4019
4020   /* the header consists of a 'hdrl' LIST tag */
4021   res = gst_riff_read_chunk (element, avi->sinkpad, &avi->offset, &tag, &buf);
4022   if (res != GST_FLOW_OK)
4023     goto pull_range_failed;
4024   else if (tag != GST_RIFF_TAG_LIST)
4025     goto no_list;
4026   else if (gst_buffer_get_size (buf) < 4)
4027     goto no_header;
4028
4029   GST_DEBUG_OBJECT (avi, "parsing headers");
4030
4031   /* Find the 'hdrl' LIST tag */
4032   gst_buffer_extract (buf, 0, fourcc, 4);
4033   while (GST_READ_UINT32_LE (fourcc) != GST_RIFF_LIST_hdrl) {
4034     GST_LOG_OBJECT (avi, "buffer contains %" GST_FOURCC_FORMAT,
4035         GST_FOURCC_ARGS (GST_READ_UINT32_LE (fourcc)));
4036
4037     /* Eat up */
4038     gst_buffer_unref (buf);
4039
4040     /* read new chunk */
4041     res = gst_riff_read_chunk (element, avi->sinkpad, &avi->offset, &tag, &buf);
4042     if (res != GST_FLOW_OK)
4043       goto pull_range_failed;
4044     else if (tag != GST_RIFF_TAG_LIST)
4045       goto no_list;
4046     else if (gst_buffer_get_size (buf) < 4)
4047       goto no_header;
4048     gst_buffer_extract (buf, 0, fourcc, 4);
4049   }
4050
4051   GST_DEBUG_OBJECT (avi, "hdrl LIST tag found");
4052
4053   gst_avi_demux_roundup_list (avi, &buf);
4054
4055   /* the hdrl starts with a 'avih' header */
4056   if (!gst_riff_parse_chunk (element, buf, &offset, &tag, &sub))
4057     goto no_avih;
4058   else if (tag != GST_RIFF_TAG_avih)
4059     goto no_avih;
4060   else if (!gst_avi_demux_parse_avih (avi, sub, &avi->avih))
4061     goto invalid_avih;
4062
4063   GST_DEBUG_OBJECT (avi, "AVI header ok, reading elements from header");
4064
4065   /* now, read the elements from the header until the end */
4066   while (gst_riff_parse_chunk (element, buf, &offset, &tag, &sub)) {
4067     GstMapInfo map;
4068
4069     /* sub can be NULL on empty tags */
4070     if (!sub)
4071       continue;
4072
4073     gst_buffer_map (sub, &map, GST_MAP_READ);
4074
4075     switch (tag) {
4076       case GST_RIFF_TAG_LIST:
4077         if (map.size < 4)
4078           goto next;
4079
4080         switch (GST_READ_UINT32_LE (map.data)) {
4081           case GST_RIFF_LIST_strl:
4082             gst_buffer_unmap (sub, &map);
4083             if (!(gst_avi_demux_parse_stream (avi, sub))) {
4084               GST_ELEMENT_WARNING (avi, STREAM, DEMUX, (NULL),
4085                   ("failed to parse stream, ignoring"));
4086               sub = NULL;
4087             }
4088             sub = NULL;
4089             goto next;
4090           case GST_RIFF_LIST_odml:
4091             gst_buffer_unmap (sub, &map);
4092             gst_avi_demux_parse_odml (avi, sub);
4093             sub = NULL;
4094             break;
4095           case GST_RIFF_LIST_INFO:
4096             gst_buffer_unmap (sub, &map);
4097             gst_buffer_resize (sub, 4, -1);
4098             gst_riff_parse_info (element, sub, &tags);
4099             if (tags) {
4100               if (avi->globaltags) {
4101                 gst_tag_list_insert (avi->globaltags, tags,
4102                     GST_TAG_MERGE_REPLACE);
4103                 gst_tag_list_unref (tags);
4104               } else {
4105                 avi->globaltags = tags;
4106               }
4107             }
4108             tags = NULL;
4109             gst_buffer_unref (sub);
4110             sub = NULL;
4111             break;
4112           case GST_RIFF_LIST_ncdt:
4113             gst_buffer_unmap (sub, &map);
4114             gst_buffer_resize (sub, 4, -1);
4115             gst_avi_demux_parse_ncdt (avi, sub, &tags);
4116             if (tags) {
4117               if (avi->globaltags) {
4118                 gst_tag_list_insert (avi->globaltags, tags,
4119                     GST_TAG_MERGE_REPLACE);
4120                 gst_tag_list_unref (tags);
4121               } else {
4122                 avi->globaltags = tags;
4123               }
4124             }
4125             tags = NULL;
4126             gst_buffer_unref (sub);
4127             sub = NULL;
4128             break;
4129           default:
4130             GST_WARNING_OBJECT (avi,
4131                 "Unknown list %" GST_FOURCC_FORMAT " in AVI header",
4132                 GST_FOURCC_ARGS (GST_READ_UINT32_LE (map.data)));
4133             GST_MEMDUMP_OBJECT (avi, "Unknown list", map.data, map.size);
4134             /* fall-through */
4135           case GST_RIFF_TAG_JUNQ:
4136           case GST_RIFF_TAG_JUNK:
4137             goto next;
4138         }
4139         break;
4140       case GST_RIFF_IDIT:
4141         gst_avi_demux_parse_idit (avi, sub);
4142         goto next;
4143       default:
4144         GST_WARNING_OBJECT (avi,
4145             "Unknown tag %" GST_FOURCC_FORMAT " in AVI header",
4146             GST_FOURCC_ARGS (tag));
4147         GST_MEMDUMP_OBJECT (avi, "Unknown tag", map.data, map.size);
4148         /* fall-through */
4149       case GST_RIFF_TAG_JUNQ:
4150       case GST_RIFF_TAG_JUNK:
4151       next:
4152         if (sub) {
4153           gst_buffer_unmap (sub, &map);
4154           gst_buffer_unref (sub);
4155         }
4156         sub = NULL;
4157         break;
4158     }
4159   }
4160   gst_buffer_unref (buf);
4161   GST_DEBUG ("elements parsed");
4162
4163   /* check parsed streams */
4164   if (avi->num_streams == 0)
4165     goto no_streams;
4166   else if (avi->num_streams != avi->avih->streams) {
4167     GST_WARNING_OBJECT (avi,
4168         "Stream header mentioned %d streams, but %d available",
4169         avi->avih->streams, avi->num_streams);
4170   }
4171
4172   GST_DEBUG_OBJECT (avi, "skipping junk between header and data, offset=%"
4173       G_GUINT64_FORMAT, avi->offset);
4174
4175   /* Now, find the data (i.e. skip all junk between header and data) */
4176   do {
4177     GstMapInfo map;
4178     guint size;
4179     guint32 tag, ltag;
4180
4181     buf = NULL;
4182     res = gst_pad_pull_range (avi->sinkpad, avi->offset, 12, &buf);
4183     if (res != GST_FLOW_OK) {
4184       GST_DEBUG_OBJECT (avi, "pull_range failure while looking for tags");
4185       goto pull_range_failed;
4186     } else if (gst_buffer_get_size (buf) < 12) {
4187       GST_DEBUG_OBJECT (avi,
4188           "got %" G_GSIZE_FORMAT " bytes which is less than 12 bytes",
4189           gst_buffer_get_size (buf));
4190       gst_buffer_unref (buf);
4191       return GST_FLOW_ERROR;
4192     }
4193
4194     gst_buffer_map (buf, &map, GST_MAP_READ);
4195     tag = GST_READ_UINT32_LE (map.data);
4196     size = GST_READ_UINT32_LE (map.data + 4);
4197     ltag = GST_READ_UINT32_LE (map.data + 8);
4198
4199     GST_DEBUG ("tag %" GST_FOURCC_FORMAT ", size %u",
4200         GST_FOURCC_ARGS (tag), size);
4201     GST_MEMDUMP ("Tag content", map.data, map.size);
4202     gst_buffer_unmap (buf, &map);
4203     gst_buffer_unref (buf);
4204
4205     switch (tag) {
4206       case GST_RIFF_TAG_LIST:{
4207         switch (ltag) {
4208           case GST_RIFF_LIST_movi:
4209             GST_DEBUG_OBJECT (avi,
4210                 "Reached the 'movi' tag, we're done with skipping");
4211             goto skipping_done;
4212           case GST_RIFF_LIST_INFO:
4213             res =
4214                 gst_riff_read_chunk (element, avi->sinkpad, &avi->offset, &tag,
4215                 &buf);
4216             if (res != GST_FLOW_OK) {
4217               GST_DEBUG_OBJECT (avi, "couldn't read INFO chunk");
4218               goto pull_range_failed;
4219             }
4220             GST_DEBUG ("got size %" G_GSIZE_FORMAT, gst_buffer_get_size (buf));
4221             if (size < 4) {
4222               GST_DEBUG ("skipping INFO LIST prefix");
4223               avi->offset += (4 - GST_ROUND_UP_2 (size));
4224               gst_buffer_unref (buf);
4225               continue;
4226             }
4227
4228             sub = gst_buffer_copy_region (buf, GST_BUFFER_COPY_ALL, 4, -1);
4229             gst_riff_parse_info (element, sub, &tags);
4230             if (tags) {
4231               if (avi->globaltags) {
4232                 gst_tag_list_insert (avi->globaltags, tags,
4233                     GST_TAG_MERGE_REPLACE);
4234                 gst_tag_list_unref (tags);
4235               } else {
4236                 avi->globaltags = tags;
4237               }
4238             }
4239             tags = NULL;
4240             if (sub) {
4241               gst_buffer_unref (sub);
4242               sub = NULL;
4243             }
4244             gst_buffer_unref (buf);
4245             /* gst_riff_read_chunk() has already advanced avi->offset */
4246             break;
4247           case GST_RIFF_LIST_ncdt:
4248             res =
4249                 gst_riff_read_chunk (element, avi->sinkpad, &avi->offset, &tag,
4250                 &buf);
4251             if (res != GST_FLOW_OK) {
4252               GST_DEBUG_OBJECT (avi, "couldn't read ncdt chunk");
4253               goto pull_range_failed;
4254             }
4255             GST_DEBUG ("got size %" G_GSIZE_FORMAT, gst_buffer_get_size (buf));
4256             if (size < 4) {
4257               GST_DEBUG ("skipping ncdt LIST prefix");
4258               avi->offset += (4 - GST_ROUND_UP_2 (size));
4259               gst_buffer_unref (buf);
4260               continue;
4261             }
4262
4263             sub = gst_buffer_copy_region (buf, GST_BUFFER_COPY_ALL, 4, -1);
4264             gst_avi_demux_parse_ncdt (avi, sub, &tags);
4265             if (tags) {
4266               if (avi->globaltags) {
4267                 gst_tag_list_insert (avi->globaltags, tags,
4268                     GST_TAG_MERGE_REPLACE);
4269                 gst_tag_list_unref (tags);
4270               } else {
4271                 avi->globaltags = tags;
4272               }
4273             }
4274             tags = NULL;
4275             if (sub) {
4276               gst_buffer_unref (sub);
4277               sub = NULL;
4278             }
4279             gst_buffer_unref (buf);
4280             /* gst_riff_read_chunk() has already advanced avi->offset */
4281             break;
4282           default:
4283             GST_WARNING_OBJECT (avi,
4284                 "Skipping unknown list tag %" GST_FOURCC_FORMAT,
4285                 GST_FOURCC_ARGS (ltag));
4286             avi->offset += 8 + GST_ROUND_UP_2 (size);
4287             break;
4288         }
4289       }
4290         break;
4291       default:
4292         GST_WARNING_OBJECT (avi, "Skipping unknown tag %" GST_FOURCC_FORMAT,
4293             GST_FOURCC_ARGS (tag));
4294         /* Fall-through */
4295       case GST_MAKE_FOURCC ('J', 'U', 'N', 'Q'):
4296       case GST_MAKE_FOURCC ('J', 'U', 'N', 'K'):
4297         /* Only get buffer for debugging if the memdump is needed  */
4298         if (gst_debug_category_get_threshold (GST_CAT_DEFAULT) >= 9) {
4299           buf = NULL;
4300           res = gst_pad_pull_range (avi->sinkpad, avi->offset, size, &buf);
4301           if (res != GST_FLOW_OK) {
4302             GST_DEBUG_OBJECT (avi, "couldn't read INFO chunk");
4303             goto pull_range_failed;
4304           }
4305           gst_buffer_map (buf, &map, GST_MAP_READ);
4306           GST_MEMDUMP ("Junk", map.data, map.size);
4307           gst_buffer_unmap (buf, &map);
4308           gst_buffer_unref (buf);
4309         }
4310         avi->offset += 8 + GST_ROUND_UP_2 (size);
4311         break;
4312     }
4313   } while (1);
4314 skipping_done:
4315
4316   GST_DEBUG_OBJECT (avi, "skipping done ... (streams=%u, stream[0].indexes=%p)",
4317       avi->num_streams, avi->stream[0].indexes);
4318
4319   /* create or read stream index (for seeking) */
4320   if (avi->stream[0].indexes != NULL) {
4321     /* we read a super index already (gst_avi_demux_parse_superindex() ) */
4322     gst_avi_demux_read_subindexes_pull (avi);
4323   }
4324   if (!avi->have_index) {
4325     if (avi->avih->flags & GST_RIFF_AVIH_HASINDEX)
4326       gst_avi_demux_stream_index (avi);
4327
4328     /* still no index, scan */
4329     if (!avi->have_index) {
4330       gst_avi_demux_stream_scan (avi);
4331
4332       /* still no index.. this is a fatal error for now.
4333        * FIXME, we should switch to plain push mode without seeking
4334        * instead of failing. */
4335       if (!avi->have_index)
4336         goto no_index;
4337     }
4338   }
4339   /* use the indexes now to construct nice durations */
4340   gst_avi_demux_calculate_durations_from_index (avi);
4341
4342   gst_avi_demux_expose_streams (avi, FALSE);
4343
4344   /* do initial seek to the default segment values */
4345   gst_avi_demux_do_seek (avi, &avi->segment, 0);
4346
4347   /* create initial NEWSEGMENT event */
4348   if (avi->seg_event)
4349     gst_event_unref (avi->seg_event);
4350   avi->seg_event = gst_event_new_segment (&avi->segment);
4351   if (avi->segment_seqnum)
4352     gst_event_set_seqnum (avi->seg_event, avi->segment_seqnum);
4353
4354   stamp = gst_util_get_timestamp () - stamp;
4355   GST_DEBUG_OBJECT (avi, "pulling header took %" GST_TIME_FORMAT,
4356       GST_TIME_ARGS (stamp));
4357
4358   /* at this point we know all the streams and we can signal the no more
4359    * pads signal */
4360   GST_DEBUG_OBJECT (avi, "signaling no more pads");
4361   gst_element_no_more_pads (GST_ELEMENT_CAST (avi));
4362
4363   return GST_FLOW_OK;
4364
4365   /* ERRORS */
4366 no_list:
4367   {
4368     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
4369         ("Invalid AVI header (no LIST at start): %"
4370             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
4371     gst_buffer_unref (buf);
4372     return GST_FLOW_ERROR;
4373   }
4374 no_header:
4375   {
4376     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
4377         ("Invalid AVI header (no hdrl at start): %"
4378             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
4379     gst_buffer_unref (buf);
4380     return GST_FLOW_ERROR;
4381   }
4382 no_avih:
4383   {
4384     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
4385         ("Invalid AVI header (no avih at start): %"
4386             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
4387     if (sub)
4388       gst_buffer_unref (sub);
4389     gst_buffer_unref (buf);
4390     return GST_FLOW_ERROR;
4391   }
4392 invalid_avih:
4393   {
4394     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
4395         ("Invalid AVI header (cannot parse avih at start)"));
4396     gst_buffer_unref (buf);
4397     return GST_FLOW_ERROR;
4398   }
4399 no_streams:
4400   {
4401     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("No streams found"));
4402     return GST_FLOW_ERROR;
4403   }
4404 no_index:
4405   {
4406     GST_WARNING ("file without or too big index");
4407     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
4408         ("Could not get/create index"));
4409     return GST_FLOW_ERROR;
4410   }
4411 pull_range_failed:
4412   {
4413     if (res == GST_FLOW_FLUSHING)
4414       return res;
4415     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
4416         ("pull_range flow reading header: %s", gst_flow_get_name (res)));
4417     return res;
4418   }
4419 }
4420
4421 /* move a stream to @index */
4422 static void
4423 gst_avi_demux_move_stream (GstAviDemux * avi, GstAviStream * stream,
4424     GstSegment * segment, guint index)
4425 {
4426   GST_DEBUG_OBJECT (avi, "Move stream %d to %u", stream->num, index);
4427
4428   if (segment->rate < 0.0) {
4429     guint next_key;
4430     /* Because we don't know the frame order we need to push from the prev keyframe
4431      * to the next keyframe. If there is a smart decoder downstream he will notice
4432      * that there are too many encoded frames send and return EOS when there
4433      * are enough decoded frames to fill the segment. */
4434     next_key = gst_avi_demux_index_next (avi, stream, index, TRUE);
4435
4436     /* FIXME, we go back to 0, we should look at segment.start. We will however
4437      * stop earlier when the see the timestamp < segment.start */
4438     stream->start_entry = 0;
4439     stream->step_entry = index;
4440     stream->current_entry = index;
4441     stream->stop_entry = next_key;
4442
4443     GST_DEBUG_OBJECT (avi, "reverse seek: start %u, step %u, stop %u",
4444         stream->start_entry, stream->step_entry, stream->stop_entry);
4445   } else {
4446     stream->start_entry = index;
4447     stream->step_entry = index;
4448     stream->stop_entry = gst_avi_demux_index_last (avi, stream);
4449   }
4450   if (stream->current_entry != index) {
4451     GST_DEBUG_OBJECT (avi, "Move DISCONT from %u to %u",
4452         stream->current_entry, index);
4453     stream->current_entry = index;
4454     stream->discont = TRUE;
4455   }
4456
4457   /* update the buffer info */
4458   gst_avi_demux_get_buffer_info (avi, stream, index,
4459       &stream->current_timestamp, &stream->current_ts_end,
4460       &stream->current_offset, &stream->current_offset_end);
4461
4462   GST_DEBUG_OBJECT (avi, "Moved to %u, ts %" GST_TIME_FORMAT
4463       ", ts_end %" GST_TIME_FORMAT ", off %" G_GUINT64_FORMAT
4464       ", off_end %" G_GUINT64_FORMAT, index,
4465       GST_TIME_ARGS (stream->current_timestamp),
4466       GST_TIME_ARGS (stream->current_ts_end), stream->current_offset,
4467       stream->current_offset_end);
4468
4469   GST_DEBUG_OBJECT (avi, "Seeking to offset %" G_GUINT64_FORMAT,
4470       stream->index[index].offset);
4471 }
4472
4473 /*
4474  * Do the actual seeking.
4475  */
4476 static gboolean
4477 gst_avi_demux_do_seek (GstAviDemux * avi, GstSegment * segment,
4478     GstSeekFlags flags)
4479 {
4480   GstClockTime seek_time;
4481   gboolean keyframe, before, after;
4482   guint i, index;
4483   GstAviStream *stream;
4484   gboolean next;
4485
4486   seek_time = segment->position;
4487   keyframe = ! !(flags & GST_SEEK_FLAG_KEY_UNIT);
4488   before = ! !(flags & GST_SEEK_FLAG_SNAP_BEFORE);
4489   after = ! !(flags & GST_SEEK_FLAG_SNAP_AFTER);
4490
4491   GST_DEBUG_OBJECT (avi, "seek to: %" GST_TIME_FORMAT
4492       " keyframe seeking:%d, %s", GST_TIME_ARGS (seek_time), keyframe,
4493       snap_types[before ? 1 : 0][after ? 1 : 0]);
4494
4495   /* FIXME, this code assumes the main stream with keyframes is stream 0,
4496    * which is mostly correct... */
4497   stream = &avi->stream[avi->main_stream];
4498
4499   next = after && !before;
4500   if (segment->rate < 0)
4501     next = !next;
4502
4503   /* get the entry index for the requested position */
4504   index = gst_avi_demux_index_for_time (avi, stream, seek_time, next);
4505   GST_DEBUG_OBJECT (avi, "Got entry %u", index);
4506   if (index == -1)
4507     return FALSE;
4508
4509   /* check if we are already on a keyframe */
4510   if (!ENTRY_IS_KEYFRAME (&stream->index[index])) {
4511     if (next) {
4512       GST_DEBUG_OBJECT (avi, "not keyframe, searching forward");
4513       /* now go to the next keyframe, this is where we should start
4514        * decoding from. */
4515       index = gst_avi_demux_index_next (avi, stream, index, TRUE);
4516       GST_DEBUG_OBJECT (avi, "next keyframe at %u", index);
4517     } else {
4518       GST_DEBUG_OBJECT (avi, "not keyframe, searching back");
4519       /* now go to the previous keyframe, this is where we should start
4520        * decoding from. */
4521       index = gst_avi_demux_index_prev (avi, stream, index, TRUE);
4522       GST_DEBUG_OBJECT (avi, "previous keyframe at %u", index);
4523     }
4524   }
4525
4526   /* move the main stream to this position */
4527   gst_avi_demux_move_stream (avi, stream, segment, index);
4528
4529   if (keyframe) {
4530     /* when seeking to a keyframe, we update the result seek time
4531      * to the time of the keyframe. */
4532     seek_time = stream->current_timestamp;
4533     GST_DEBUG_OBJECT (avi, "keyframe adjusted to %" GST_TIME_FORMAT,
4534         GST_TIME_ARGS (seek_time));
4535     /* the seek time is always the position ... */
4536     segment->position = seek_time;
4537     /* ... and start and stream time when going forwards,
4538      * otherwise only stop time */
4539     if (segment->rate > 0.0)
4540       segment->start = segment->time = seek_time;
4541     else
4542       segment->stop = seek_time;
4543   }
4544
4545   /* now set DISCONT and align the other streams */
4546   for (i = 0; i < avi->num_streams; i++) {
4547     GstAviStream *ostream;
4548
4549     ostream = &avi->stream[i];
4550     if ((ostream == stream) || (ostream->index == NULL))
4551       continue;
4552
4553     /* get the entry index for the requested position */
4554     index = gst_avi_demux_index_for_time (avi, ostream, seek_time, FALSE);
4555     if (index == -1)
4556       continue;
4557
4558     /* move to previous keyframe */
4559     if (!ENTRY_IS_KEYFRAME (&ostream->index[index]))
4560       index = gst_avi_demux_index_prev (avi, ostream, index, TRUE);
4561
4562     gst_avi_demux_move_stream (avi, ostream, segment, index);
4563   }
4564   GST_DEBUG_OBJECT (avi, "done seek to: %" GST_TIME_FORMAT,
4565       GST_TIME_ARGS (seek_time));
4566
4567   return TRUE;
4568 }
4569
4570 /*
4571  * Handle seek event in pull mode.
4572  */
4573 static gboolean
4574 gst_avi_demux_handle_seek (GstAviDemux * avi, GstPad * pad, GstEvent * event)
4575 {
4576   gdouble rate;
4577   GstFormat format;
4578   GstSeekFlags flags;
4579   GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
4580   gint64 cur, stop;
4581   gboolean flush;
4582   gboolean update;
4583   GstSegment seeksegment = { 0, };
4584   gint i;
4585   guint32 seqnum = 0;
4586
4587   if (event) {
4588     GST_DEBUG_OBJECT (avi, "doing seek with event");
4589
4590     gst_event_parse_seek (event, &rate, &format, &flags,
4591         &cur_type, &cur, &stop_type, &stop);
4592     seqnum = gst_event_get_seqnum (event);
4593
4594     /* we have to have a format as the segment format. Try to convert
4595      * if not. */
4596     if (format != GST_FORMAT_TIME) {
4597       gboolean res = TRUE;
4598
4599       if (cur_type != GST_SEEK_TYPE_NONE)
4600         res = gst_pad_query_convert (pad, format, cur, GST_FORMAT_TIME, &cur);
4601       if (res && stop_type != GST_SEEK_TYPE_NONE)
4602         res = gst_pad_query_convert (pad, format, stop, GST_FORMAT_TIME, &stop);
4603       if (!res)
4604         goto no_format;
4605
4606       format = GST_FORMAT_TIME;
4607     }
4608     GST_DEBUG_OBJECT (avi,
4609         "seek requested: rate %g cur %" GST_TIME_FORMAT " stop %"
4610         GST_TIME_FORMAT, rate, GST_TIME_ARGS (cur), GST_TIME_ARGS (stop));
4611     /* FIXME: can we do anything with rate!=1.0 */
4612   } else {
4613     GST_DEBUG_OBJECT (avi, "doing seek without event");
4614     flags = 0;
4615     rate = 1.0;
4616   }
4617
4618   /* save flush flag */
4619   flush = flags & GST_SEEK_FLAG_FLUSH;
4620
4621   if (flush) {
4622     GstEvent *fevent = gst_event_new_flush_start ();
4623
4624     if (seqnum)
4625       gst_event_set_seqnum (fevent, seqnum);
4626     /* for a flushing seek, we send a flush_start on all pads. This will
4627      * eventually stop streaming with a WRONG_STATE. We can thus eventually
4628      * take the STREAM_LOCK. */
4629     GST_DEBUG_OBJECT (avi, "sending flush start");
4630     gst_avi_demux_push_event (avi, gst_event_ref (fevent));
4631     gst_pad_push_event (avi->sinkpad, fevent);
4632   } else {
4633     /* a non-flushing seek, we PAUSE the task so that we can take the
4634      * STREAM_LOCK */
4635     GST_DEBUG_OBJECT (avi, "non flushing seek, pausing task");
4636     gst_pad_pause_task (avi->sinkpad);
4637   }
4638
4639   /* wait for streaming to stop */
4640   GST_DEBUG_OBJECT (avi, "wait for streaming to stop");
4641   GST_PAD_STREAM_LOCK (avi->sinkpad);
4642
4643   /* copy segment, we need this because we still need the old
4644    * segment when we close the current segment. */
4645   memcpy (&seeksegment, &avi->segment, sizeof (GstSegment));
4646
4647   if (event) {
4648     GST_DEBUG_OBJECT (avi, "configuring seek");
4649     gst_segment_do_seek (&seeksegment, rate, format, flags,
4650         cur_type, cur, stop_type, stop, &update);
4651   }
4652   /* do the seek, seeksegment.position contains the new position, this
4653    * actually never fails. */
4654   gst_avi_demux_do_seek (avi, &seeksegment, flags);
4655
4656   if (flush) {
4657     GstEvent *fevent = gst_event_new_flush_stop (TRUE);
4658
4659     if (seqnum)
4660       gst_event_set_seqnum (fevent, seqnum);
4661
4662     GST_DEBUG_OBJECT (avi, "sending flush stop");
4663     gst_avi_demux_push_event (avi, gst_event_ref (fevent));
4664     gst_pad_push_event (avi->sinkpad, fevent);
4665   }
4666
4667   /* now update the real segment info */
4668   memcpy (&avi->segment, &seeksegment, sizeof (GstSegment));
4669
4670   /* post the SEGMENT_START message when we do segmented playback */
4671   if (avi->segment.flags & GST_SEEK_FLAG_SEGMENT) {
4672     GstMessage *segment_start_msg =
4673         gst_message_new_segment_start (GST_OBJECT_CAST (avi),
4674         avi->segment.format, avi->segment.position);
4675     if (seqnum)
4676       gst_message_set_seqnum (segment_start_msg, seqnum);
4677     gst_element_post_message (GST_ELEMENT_CAST (avi), segment_start_msg);
4678   }
4679
4680   /* queue the segment event for the streaming thread. */
4681   if (avi->seg_event)
4682     gst_event_unref (avi->seg_event);
4683   avi->seg_event = gst_event_new_segment (&avi->segment);
4684   if (seqnum)
4685     gst_event_set_seqnum (avi->seg_event, seqnum);
4686   avi->segment_seqnum = seqnum;
4687
4688   if (!avi->streaming) {
4689     gst_pad_start_task (avi->sinkpad, (GstTaskFunction) gst_avi_demux_loop,
4690         avi->sinkpad, NULL);
4691   }
4692   /* reset the last flow and mark discont, seek is always DISCONT */
4693   for (i = 0; i < avi->num_streams; i++) {
4694     GST_DEBUG_OBJECT (avi, "marking DISCONT");
4695     avi->stream[i].discont = TRUE;
4696   }
4697   /* likewise for the whole new segment */
4698   gst_flow_combiner_reset (avi->flowcombiner);
4699   GST_PAD_STREAM_UNLOCK (avi->sinkpad);
4700
4701   return TRUE;
4702
4703   /* ERRORS */
4704 no_format:
4705   {
4706     GST_DEBUG_OBJECT (avi, "unsupported format given, seek aborted.");
4707     return FALSE;
4708   }
4709 }
4710
4711 /*
4712  * Handle seek event in push mode.
4713  */
4714 static gboolean
4715 avi_demux_handle_seek_push (GstAviDemux * avi, GstPad * pad, GstEvent * event)
4716 {
4717   gdouble rate;
4718   GstFormat format;
4719   GstSeekFlags flags;
4720   GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
4721   gint64 cur, stop;
4722   gboolean keyframe, before, after, next;
4723   GstAviStream *stream;
4724   guint index;
4725   guint n, str_num;
4726   guint64 min_offset;
4727   GstSegment seeksegment;
4728   gboolean update;
4729
4730   /* check we have the index */
4731   if (!avi->have_index) {
4732     GST_DEBUG_OBJECT (avi, "no seek index built, seek aborted.");
4733     return FALSE;
4734   } else {
4735     GST_DEBUG_OBJECT (avi, "doing push-based seek with event");
4736   }
4737
4738   gst_event_parse_seek (event, &rate, &format, &flags,
4739       &cur_type, &cur, &stop_type, &stop);
4740
4741   if (format != GST_FORMAT_TIME) {
4742     gboolean res = TRUE;
4743
4744     if (cur_type != GST_SEEK_TYPE_NONE)
4745       res = gst_pad_query_convert (pad, format, cur, GST_FORMAT_TIME, &cur);
4746     if (res && stop_type != GST_SEEK_TYPE_NONE)
4747       res = gst_pad_query_convert (pad, format, stop, GST_FORMAT_TIME, &stop);
4748     if (!res) {
4749       GST_DEBUG_OBJECT (avi, "unsupported format given, seek aborted.");
4750       return FALSE;
4751     }
4752
4753     format = GST_FORMAT_TIME;
4754   }
4755
4756   /* let gst_segment handle any tricky stuff */
4757   GST_DEBUG_OBJECT (avi, "configuring seek");
4758   memcpy (&seeksegment, &avi->segment, sizeof (GstSegment));
4759   gst_segment_do_seek (&seeksegment, rate, format, flags,
4760       cur_type, cur, stop_type, stop, &update);
4761
4762   keyframe = ! !(flags & GST_SEEK_FLAG_KEY_UNIT);
4763   cur = seeksegment.position;
4764   before = ! !(flags & GST_SEEK_FLAG_SNAP_BEFORE);
4765   after = ! !(flags & GST_SEEK_FLAG_SNAP_AFTER);
4766
4767   GST_DEBUG_OBJECT (avi,
4768       "Seek requested: ts %" GST_TIME_FORMAT " stop %" GST_TIME_FORMAT
4769       ", kf %u, %s, rate %lf", GST_TIME_ARGS (cur), GST_TIME_ARGS (stop),
4770       keyframe, snap_types[before ? 1 : 0][after ? 1 : 0], rate);
4771
4772   if (rate < 0) {
4773     GST_DEBUG_OBJECT (avi, "negative rate seek not supported in push mode");
4774     return FALSE;
4775   }
4776
4777   /* FIXME, this code assumes the main stream with keyframes is stream 0,
4778    * which is mostly correct... */
4779   str_num = avi->main_stream;
4780   stream = &avi->stream[str_num];
4781
4782   next = after && !before;
4783   if (seeksegment.rate < 0)
4784     next = !next;
4785
4786   /* get the entry index for the requested position */
4787   index = gst_avi_demux_index_for_time (avi, stream, cur, next);
4788   GST_DEBUG_OBJECT (avi, "str %u: Found entry %u for %" GST_TIME_FORMAT,
4789       str_num, index, GST_TIME_ARGS (cur));
4790   if (index == -1)
4791     return -1;
4792
4793   /* check if we are already on a keyframe */
4794   if (!ENTRY_IS_KEYFRAME (&stream->index[index])) {
4795     if (next) {
4796       GST_DEBUG_OBJECT (avi, "Entry is not a keyframe - searching forward");
4797       /* now go to the next keyframe, this is where we should start
4798        * decoding from. */
4799       index = gst_avi_demux_index_next (avi, stream, index, TRUE);
4800       GST_DEBUG_OBJECT (avi, "Found next keyframe at %u", index);
4801     } else {
4802       GST_DEBUG_OBJECT (avi, "Entry is not a keyframe - searching back");
4803       /* now go to the previous keyframe, this is where we should start
4804        * decoding from. */
4805       index = gst_avi_demux_index_prev (avi, stream, index, TRUE);
4806       GST_DEBUG_OBJECT (avi, "Found previous keyframe at %u", index);
4807     }
4808   }
4809
4810   gst_avi_demux_get_buffer_info (avi, stream, index,
4811       &stream->current_timestamp, &stream->current_ts_end,
4812       &stream->current_offset, &stream->current_offset_end);
4813
4814   /* re-use cur to be the timestamp of the seek as it _will_ be */
4815   cur = stream->current_timestamp;
4816
4817   min_offset = stream->index[index].offset;
4818   avi->seek_kf_offset = min_offset - 8;
4819
4820   GST_DEBUG_OBJECT (avi,
4821       "Seek to: ts %" GST_TIME_FORMAT " (on str %u, idx %u, offset %"
4822       G_GUINT64_FORMAT ")", GST_TIME_ARGS (stream->current_timestamp), str_num,
4823       index, min_offset);
4824
4825   for (n = 0; n < avi->num_streams; n++) {
4826     GstAviStream *str = &avi->stream[n];
4827     guint idx;
4828
4829     if (n == avi->main_stream)
4830       continue;
4831
4832     /* get the entry index for the requested position */
4833     idx = gst_avi_demux_index_for_time (avi, str, cur, FALSE);
4834     GST_DEBUG_OBJECT (avi, "str %u: Found entry %u for %" GST_TIME_FORMAT, n,
4835         idx, GST_TIME_ARGS (cur));
4836     if (idx == -1)
4837       continue;
4838
4839     /* check if we are already on a keyframe */
4840     if (!ENTRY_IS_KEYFRAME (&str->index[idx])) {
4841       if (next) {
4842         GST_DEBUG_OBJECT (avi, "Entry is not a keyframe - searching forward");
4843         /* now go to the next keyframe, this is where we should start
4844          * decoding from. */
4845         idx = gst_avi_demux_index_next (avi, str, idx, TRUE);
4846         GST_DEBUG_OBJECT (avi, "Found next keyframe at %u", idx);
4847       } else {
4848         GST_DEBUG_OBJECT (avi, "Entry is not a keyframe - searching back");
4849         /* now go to the previous keyframe, this is where we should start
4850          * decoding from. */
4851         idx = gst_avi_demux_index_prev (avi, str, idx, TRUE);
4852         GST_DEBUG_OBJECT (avi, "Found previous keyframe at %u", idx);
4853       }
4854     }
4855
4856     gst_avi_demux_get_buffer_info (avi, str, idx,
4857         &str->current_timestamp, &str->current_ts_end,
4858         &str->current_offset, &str->current_offset_end);
4859
4860     if (str->index[idx].offset < min_offset) {
4861       min_offset = str->index[idx].offset;
4862       GST_DEBUG_OBJECT (avi,
4863           "Found an earlier offset at %" G_GUINT64_FORMAT ", str %u",
4864           min_offset, n);
4865       str_num = n;
4866       stream = str;
4867       index = idx;
4868     }
4869   }
4870
4871   GST_DEBUG_OBJECT (avi,
4872       "Seek performed: str %u, offset %" G_GUINT64_FORMAT ", idx %u, ts %"
4873       GST_TIME_FORMAT ", ts_end %" GST_TIME_FORMAT ", off %" G_GUINT64_FORMAT
4874       ", off_end %" G_GUINT64_FORMAT, str_num, min_offset, index,
4875       GST_TIME_ARGS (stream->current_timestamp),
4876       GST_TIME_ARGS (stream->current_ts_end), stream->current_offset,
4877       stream->current_offset_end);
4878
4879   /* index data refers to data, not chunk header (for pull mode convenience) */
4880   min_offset -= 8;
4881   GST_DEBUG_OBJECT (avi, "seeking to chunk at offset %" G_GUINT64_FORMAT,
4882       min_offset);
4883
4884   if (!perform_seek_to_offset (avi, min_offset, gst_event_get_seqnum (event))) {
4885     GST_DEBUG_OBJECT (avi, "seek event failed!");
4886     return FALSE;
4887   }
4888
4889   return TRUE;
4890 }
4891
4892 /*
4893  * Handle whether we can perform the seek event or if we have to let the chain
4894  * function handle seeks to build the seek indexes first.
4895  */
4896 static gboolean
4897 gst_avi_demux_handle_seek_push (GstAviDemux * avi, GstPad * pad,
4898     GstEvent * event)
4899 {
4900   /* check for having parsed index already */
4901   if (!avi->have_index) {
4902     guint64 offset = 0;
4903     gboolean building_index;
4904
4905     GST_OBJECT_LOCK (avi);
4906     /* handle the seek event in the chain function */
4907     avi->state = GST_AVI_DEMUX_SEEK;
4908
4909     /* copy the event */
4910     if (avi->seek_event)
4911       gst_event_unref (avi->seek_event);
4912     avi->seek_event = gst_event_ref (event);
4913
4914     /* set the building_index flag so that only one thread can setup the
4915      * structures for index seeking. */
4916     building_index = avi->building_index;
4917     if (!building_index) {
4918       avi->building_index = TRUE;
4919       if (avi->stream[0].indexes) {
4920         avi->odml_stream = 0;
4921         avi->odml_subidxs = avi->stream[avi->odml_stream].indexes;
4922         offset = avi->odml_subidxs[0];
4923       } else {
4924         offset = avi->idx1_offset;
4925       }
4926     }
4927     GST_OBJECT_UNLOCK (avi);
4928
4929     if (!building_index) {
4930       /* seek to the first subindex or legacy index */
4931       GST_INFO_OBJECT (avi,
4932           "Seeking to legacy index/first subindex at %" G_GUINT64_FORMAT,
4933           offset);
4934       return perform_seek_to_offset (avi, offset, gst_event_get_seqnum (event));
4935     }
4936
4937     /* FIXME: we have to always return true so that we don't block the seek
4938      * thread.
4939      * Note: maybe it is OK to return true if we're still building the index */
4940     return TRUE;
4941   }
4942
4943   return avi_demux_handle_seek_push (avi, pad, event);
4944 }
4945
4946 /*
4947  * Helper for gst_avi_demux_invert()
4948  */
4949 static inline void
4950 swap_line (guint8 * d1, guint8 * d2, guint8 * tmp, gint bytes)
4951 {
4952   memcpy (tmp, d1, bytes);
4953   memcpy (d1, d2, bytes);
4954   memcpy (d2, tmp, bytes);
4955 }
4956
4957
4958 #define gst_avi_demux_is_uncompressed(fourcc)           \
4959   (fourcc == GST_RIFF_DIB ||                            \
4960    fourcc == GST_RIFF_rgb ||                            \
4961    fourcc == GST_RIFF_RGB || fourcc == GST_RIFF_RAW)
4962
4963 /*
4964  * Invert DIB buffers... Takes existing buffer and
4965  * returns either the buffer or a new one (with old
4966  * one dereferenced).
4967  * FIXME: can't we preallocate tmp? and remember stride, bpp?
4968  */
4969 static GstBuffer *
4970 gst_avi_demux_invert (GstAviStream * stream, GstBuffer * buf)
4971 {
4972   gint y, w, h;
4973   gint bpp, stride;
4974   guint8 *tmp = NULL;
4975   GstMapInfo map;
4976   guint32 fourcc;
4977
4978   if (stream->strh->type != GST_RIFF_FCC_vids)
4979     return buf;
4980
4981   if (stream->strf.vids == NULL) {
4982     GST_WARNING ("Failed to retrieve vids for stream");
4983     return buf;
4984   }
4985
4986   fourcc = (stream->strf.vids->compression) ?
4987       stream->strf.vids->compression : stream->strh->fcc_handler;
4988   if (!gst_avi_demux_is_uncompressed (fourcc)) {
4989     return buf;                 /* Ignore non DIB buffers */
4990   }
4991
4992   /* raw rgb data is stored topdown, but instead of inverting the buffer, */
4993   /* some tools just negate the height field in the header (e.g. ffmpeg) */
4994   if (((gint32) stream->strf.vids->height) < 0)
4995     return buf;
4996
4997   h = stream->strf.vids->height;
4998   w = stream->strf.vids->width;
4999   bpp = stream->strf.vids->bit_cnt ? stream->strf.vids->bit_cnt : 8;
5000   stride = GST_ROUND_UP_4 (w * (bpp / 8));
5001
5002   buf = gst_buffer_make_writable (buf);
5003
5004   gst_buffer_map (buf, &map, GST_MAP_READWRITE);
5005   if (map.size < (stride * h)) {
5006     GST_WARNING ("Buffer is smaller than reported Width x Height x Depth");
5007     gst_buffer_unmap (buf, &map);
5008     return buf;
5009   }
5010
5011   tmp = g_malloc (stride);
5012
5013   for (y = 0; y < h / 2; y++) {
5014     swap_line (map.data + stride * y, map.data + stride * (h - 1 - y), tmp,
5015         stride);
5016   }
5017
5018   g_free (tmp);
5019
5020   gst_buffer_unmap (buf, &map);
5021
5022   /* append palette to paletted RGB8 buffer data */
5023   if (stream->rgb8_palette != NULL)
5024     buf = gst_buffer_append (buf, gst_buffer_ref (stream->rgb8_palette));
5025
5026   return buf;
5027 }
5028
5029 #if 0
5030 static void
5031 gst_avi_demux_add_assoc (GstAviDemux * avi, GstAviStream * stream,
5032     GstClockTime timestamp, guint64 offset, gboolean keyframe)
5033 {
5034   /* do not add indefinitely for open-ended streaming */
5035   if (G_UNLIKELY (avi->element_index && avi->seekable)) {
5036     GST_LOG_OBJECT (avi, "adding association %" GST_TIME_FORMAT "-> %"
5037         G_GUINT64_FORMAT, GST_TIME_ARGS (timestamp), offset);
5038     gst_index_add_association (avi->element_index, avi->index_id,
5039         keyframe ? GST_ASSOCIATION_FLAG_KEY_UNIT :
5040         GST_ASSOCIATION_FLAG_DELTA_UNIT, GST_FORMAT_TIME, timestamp,
5041         GST_FORMAT_BYTES, offset, NULL);
5042     /* current_entry is DEFAULT (frame #) */
5043     gst_index_add_association (avi->element_index, stream->index_id,
5044         keyframe ? GST_ASSOCIATION_FLAG_KEY_UNIT :
5045         GST_ASSOCIATION_FLAG_DELTA_UNIT, GST_FORMAT_TIME, timestamp,
5046         GST_FORMAT_BYTES, offset, GST_FORMAT_DEFAULT, stream->current_entry,
5047         NULL);
5048   }
5049 }
5050 #endif
5051
5052 /*
5053  * Returns the aggregated GstFlowReturn.
5054  */
5055 static GstFlowReturn
5056 gst_avi_demux_combine_flows (GstAviDemux * avi, GstAviStream * stream,
5057     GstFlowReturn ret)
5058 {
5059   GST_LOG_OBJECT (avi, "Stream %s:%s flow return: %s",
5060       GST_DEBUG_PAD_NAME (stream->pad), gst_flow_get_name (ret));
5061   ret = gst_flow_combiner_update_pad_flow (avi->flowcombiner, stream->pad, ret);
5062   GST_LOG_OBJECT (avi, "combined to return %s", gst_flow_get_name (ret));
5063
5064   return ret;
5065 }
5066
5067 /* move @stream to the next position in its index */
5068 static GstFlowReturn
5069 gst_avi_demux_advance (GstAviDemux * avi, GstAviStream * stream,
5070     GstFlowReturn ret)
5071 {
5072   guint old_entry, new_entry;
5073
5074   old_entry = stream->current_entry;
5075   /* move forwards */
5076   new_entry = old_entry + 1;
5077
5078   /* see if we reached the end */
5079   if (new_entry >= stream->stop_entry) {
5080     if (avi->segment.rate < 0.0) {
5081       if (stream->step_entry == stream->start_entry) {
5082         /* we stepped all the way to the start, eos */
5083         GST_DEBUG_OBJECT (avi, "reverse reached start %u", stream->start_entry);
5084         goto eos;
5085       }
5086       /* backwards, stop becomes step, find a new step */
5087       stream->stop_entry = stream->step_entry;
5088       stream->step_entry = gst_avi_demux_index_prev (avi, stream,
5089           stream->stop_entry, TRUE);
5090
5091       GST_DEBUG_OBJECT (avi,
5092           "reverse playback jump: start %u, step %u, stop %u",
5093           stream->start_entry, stream->step_entry, stream->stop_entry);
5094
5095       /* and start from the previous keyframe now */
5096       new_entry = stream->step_entry;
5097     } else {
5098       /* EOS */
5099       GST_DEBUG_OBJECT (avi, "forward reached stop %u", stream->stop_entry);
5100       goto eos;
5101     }
5102   }
5103
5104   if (new_entry != old_entry) {
5105     stream->current_entry = new_entry;
5106     stream->current_total = stream->index[new_entry].total;
5107
5108     if (new_entry == old_entry + 1) {
5109       GST_DEBUG_OBJECT (avi, "moved forwards from %u to %u",
5110           old_entry, new_entry);
5111       /* we simply moved one step forwards, reuse current info */
5112       stream->current_timestamp = stream->current_ts_end;
5113       stream->current_offset = stream->current_offset_end;
5114       gst_avi_demux_get_buffer_info (avi, stream, new_entry,
5115           NULL, &stream->current_ts_end, NULL, &stream->current_offset_end);
5116     } else {
5117       /* we moved DISCONT, full update */
5118       gst_avi_demux_get_buffer_info (avi, stream, new_entry,
5119           &stream->current_timestamp, &stream->current_ts_end,
5120           &stream->current_offset, &stream->current_offset_end);
5121       /* and MARK discont for this stream */
5122       stream->discont = TRUE;
5123       GST_DEBUG_OBJECT (avi, "Moved from %u to %u, ts %" GST_TIME_FORMAT
5124           ", ts_end %" GST_TIME_FORMAT ", off %" G_GUINT64_FORMAT
5125           ", off_end %" G_GUINT64_FORMAT, old_entry, new_entry,
5126           GST_TIME_ARGS (stream->current_timestamp),
5127           GST_TIME_ARGS (stream->current_ts_end), stream->current_offset,
5128           stream->current_offset_end);
5129     }
5130   }
5131   return ret;
5132
5133   /* ERROR */
5134 eos:
5135   {
5136     GST_DEBUG_OBJECT (avi, "we are EOS");
5137     /* setting current_timestamp to -1 marks EOS */
5138     stream->current_timestamp = -1;
5139     return GST_FLOW_EOS;
5140   }
5141 }
5142
5143 /* find the stream with the lowest current position when going forwards or with
5144  * the highest position when going backwards, this is the stream
5145  * we should push from next */
5146 static gint
5147 gst_avi_demux_find_next (GstAviDemux * avi, gfloat rate)
5148 {
5149   guint64 min_time, max_time;
5150   guint stream_num, i;
5151
5152   max_time = 0;
5153   min_time = G_MAXUINT64;
5154   stream_num = -1;
5155
5156   for (i = 0; i < avi->num_streams; i++) {
5157     guint64 position;
5158     GstAviStream *stream;
5159
5160     stream = &avi->stream[i];
5161
5162     /* ignore streams that finished */
5163     if (stream->pad && GST_PAD_LAST_FLOW_RETURN (stream->pad) == GST_FLOW_EOS)
5164       continue;
5165
5166     position = stream->current_timestamp;
5167
5168     /* position of -1 is EOS */
5169     if (position != -1) {
5170       if (rate > 0.0 && position < min_time) {
5171         min_time = position;
5172         stream_num = i;
5173       } else if (rate < 0.0 && position >= max_time) {
5174         max_time = position;
5175         stream_num = i;
5176       }
5177     }
5178   }
5179   return stream_num;
5180 }
5181
5182 static GstBuffer *
5183 gst_avi_demux_align_buffer (GstAviDemux * demux,
5184     GstBuffer * buffer, gsize alignment)
5185 {
5186   GstMapInfo map;
5187
5188   gst_buffer_map (buffer, &map, GST_MAP_READ);
5189
5190   if (map.size < sizeof (guintptr)) {
5191     gst_buffer_unmap (buffer, &map);
5192     return buffer;
5193   }
5194
5195   if (((guintptr) map.data) & (alignment - 1)) {
5196     GstBuffer *new_buffer;
5197     GstAllocationParams params = { 0, alignment - 1, 0, 0, };
5198
5199     new_buffer = gst_buffer_new_allocate (NULL,
5200         gst_buffer_get_size (buffer), &params);
5201
5202     /* Copy data "by hand", so ensure alignment is kept: */
5203     gst_buffer_fill (new_buffer, 0, map.data, map.size);
5204
5205     gst_buffer_copy_into (new_buffer, buffer, GST_BUFFER_COPY_METADATA, 0, -1);
5206     GST_DEBUG_OBJECT (demux,
5207         "We want output aligned on %" G_GSIZE_FORMAT ", reallocated",
5208         alignment);
5209
5210     gst_buffer_unmap (buffer, &map);
5211     gst_buffer_unref (buffer);
5212
5213     return new_buffer;
5214   }
5215
5216   gst_buffer_unmap (buffer, &map);
5217   return buffer;
5218 }
5219
5220 static GstFlowReturn
5221 gst_avi_demux_loop_data (GstAviDemux * avi)
5222 {
5223   GstFlowReturn ret = GST_FLOW_OK;
5224   guint stream_num;
5225   GstAviStream *stream;
5226   gboolean processed = FALSE;
5227   GstBuffer *buf;
5228   guint64 offset, size;
5229   GstClockTime timestamp, duration;
5230   guint64 out_offset, out_offset_end;
5231   gboolean keyframe;
5232   GstAviIndexEntry *entry;
5233
5234   do {
5235     stream_num = gst_avi_demux_find_next (avi, avi->segment.rate);
5236
5237     /* all are EOS */
5238     if (G_UNLIKELY (stream_num == -1)) {
5239       GST_DEBUG_OBJECT (avi, "all streams are EOS");
5240       goto eos;
5241     }
5242
5243     /* we have the stream now */
5244     stream = &avi->stream[stream_num];
5245
5246     /* skip streams without pads */
5247     if (!stream->pad) {
5248       GST_DEBUG_OBJECT (avi, "skipping entry from stream %d without pad",
5249           stream_num);
5250       goto next;
5251     }
5252
5253     /* get the timing info for the entry */
5254     timestamp = stream->current_timestamp;
5255     duration = stream->current_ts_end - timestamp;
5256     out_offset = stream->current_offset;
5257     out_offset_end = stream->current_offset_end;
5258
5259     /* get the entry data info */
5260     entry = &stream->index[stream->current_entry];
5261     offset = entry->offset;
5262     size = entry->size;
5263     keyframe = ENTRY_IS_KEYFRAME (entry);
5264
5265     /* skip empty entries */
5266     if (size == 0) {
5267       GST_DEBUG_OBJECT (avi, "Skipping entry %u (%" G_GUINT64_FORMAT ", %p)",
5268           stream->current_entry, size, stream->pad);
5269       goto next;
5270     }
5271
5272     if (avi->segment.rate > 0.0) {
5273       /* only check this for fowards playback for now */
5274       if (keyframe && GST_CLOCK_TIME_IS_VALID (avi->segment.stop)
5275           && (timestamp > avi->segment.stop)) {
5276         goto eos_stop;
5277       }
5278     } else {
5279       if (keyframe && GST_CLOCK_TIME_IS_VALID (avi->segment.start)
5280           && (timestamp < avi->segment.start))
5281         goto eos_stop;
5282     }
5283
5284     GST_LOG ("reading buffer (size=%" G_GUINT64_FORMAT "), stream %d, pos %"
5285         G_GUINT64_FORMAT " (0x%" G_GINT64_MODIFIER "x), kf %d", size,
5286         stream_num, offset, offset, keyframe);
5287
5288     /* FIXME, check large chunks and cut them up */
5289
5290     /* pull in the data */
5291     buf = NULL;
5292     ret = gst_pad_pull_range (avi->sinkpad, offset, size, &buf);
5293     if (ret != GST_FLOW_OK)
5294       goto pull_failed;
5295
5296     /* check for short buffers, this is EOS as well */
5297     if (gst_buffer_get_size (buf) < size)
5298       goto short_buffer;
5299
5300     /* invert the picture if needed, and append palette for RGB8P */
5301     buf = gst_avi_demux_invert (stream, buf);
5302
5303     /* mark non-keyframes */
5304     if (keyframe || stream->is_raw) {
5305       GST_BUFFER_FLAG_UNSET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
5306       GST_BUFFER_PTS (buf) = timestamp;
5307     } else {
5308       GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
5309       GST_BUFFER_PTS (buf) = GST_CLOCK_TIME_NONE;
5310     }
5311
5312     GST_BUFFER_DTS (buf) = timestamp;
5313
5314     GST_BUFFER_DURATION (buf) = duration;
5315     GST_BUFFER_OFFSET (buf) = out_offset;
5316     GST_BUFFER_OFFSET_END (buf) = out_offset_end;
5317
5318     /* mark discont when pending */
5319     if (stream->discont) {
5320       GST_DEBUG_OBJECT (avi, "setting DISCONT flag");
5321       GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
5322       stream->discont = FALSE;
5323     } else {
5324       GST_BUFFER_FLAG_UNSET (buf, GST_BUFFER_FLAG_DISCONT);
5325     }
5326 #if 0
5327     gst_avi_demux_add_assoc (avi, stream, timestamp, offset, keyframe);
5328 #endif
5329
5330     /* update current position in the segment */
5331     avi->segment.position = timestamp;
5332
5333     GST_DEBUG_OBJECT (avi, "Pushing buffer of size %" G_GSIZE_FORMAT ", ts %"
5334         GST_TIME_FORMAT ", dur %" GST_TIME_FORMAT ", off %" G_GUINT64_FORMAT
5335         ", off_end %" G_GUINT64_FORMAT,
5336         gst_buffer_get_size (buf), GST_TIME_ARGS (timestamp),
5337         GST_TIME_ARGS (duration), out_offset, out_offset_end);
5338
5339     if (stream->alignment > 1)
5340       buf = gst_avi_demux_align_buffer (avi, buf, stream->alignment);
5341     ret = gst_pad_push (stream->pad, buf);
5342
5343     /* mark as processed, we increment the frame and byte counters then
5344      * leave the while loop and return the GstFlowReturn */
5345     processed = TRUE;
5346
5347     if (avi->segment.rate < 0) {
5348       if (timestamp > avi->segment.stop && ret == GST_FLOW_EOS) {
5349         /* In reverse playback we can get a GST_FLOW_EOS when
5350          * we are at the end of the segment, so we just need to jump
5351          * back to the previous section. */
5352         GST_DEBUG_OBJECT (avi, "downstream has reached end of segment");
5353         ret = GST_FLOW_OK;
5354       }
5355     }
5356   next:
5357     /* move to next item */
5358     ret = gst_avi_demux_advance (avi, stream, ret);
5359
5360     /* combine flows */
5361     ret = gst_avi_demux_combine_flows (avi, stream, ret);
5362   } while (!processed);
5363
5364 beach:
5365   return ret;
5366
5367   /* special cases */
5368 eos:
5369   {
5370     GST_DEBUG_OBJECT (avi, "No samples left for any streams - EOS");
5371     ret = GST_FLOW_EOS;
5372     goto beach;
5373   }
5374 eos_stop:
5375   {
5376     GST_LOG_OBJECT (avi, "Found keyframe after segment,"
5377         " setting EOS (%" GST_TIME_FORMAT " > %" GST_TIME_FORMAT ")",
5378         GST_TIME_ARGS (timestamp), GST_TIME_ARGS (avi->segment.stop));
5379     ret = GST_FLOW_EOS;
5380     /* move to next stream */
5381     goto next;
5382   }
5383 pull_failed:
5384   {
5385     GST_DEBUG_OBJECT (avi, "pull range failed: pos=%" G_GUINT64_FORMAT
5386         " size=%" G_GUINT64_FORMAT, offset, size);
5387     goto beach;
5388   }
5389 short_buffer:
5390   {
5391     GST_WARNING_OBJECT (avi, "Short read at offset %" G_GUINT64_FORMAT
5392         ", only got %" G_GSIZE_FORMAT "/%" G_GUINT64_FORMAT
5393         " bytes (truncated file?)", offset, gst_buffer_get_size (buf), size);
5394     gst_buffer_unref (buf);
5395     ret = GST_FLOW_EOS;
5396     goto beach;
5397   }
5398 }
5399
5400 /*
5401  * Read data. If we have an index it delegates to
5402  * gst_avi_demux_process_next_entry().
5403  */
5404 static GstFlowReturn
5405 gst_avi_demux_stream_data (GstAviDemux * avi)
5406 {
5407   guint32 tag = 0;
5408   guint32 size = 0;
5409   gint stream_nr = 0;
5410   GstFlowReturn res = GST_FLOW_OK;
5411
5412   if (G_UNLIKELY (avi->have_eos)) {
5413     /* Clean adapter, we're done */
5414     gst_adapter_clear (avi->adapter);
5415     return GST_FLOW_EOS;
5416   }
5417
5418   if (G_UNLIKELY (avi->todrop)) {
5419     guint drop;
5420
5421     if ((drop = gst_adapter_available (avi->adapter))) {
5422       if (drop > avi->todrop)
5423         drop = avi->todrop;
5424       GST_DEBUG_OBJECT (avi, "Dropping %d bytes", drop);
5425       gst_adapter_flush (avi->adapter, drop);
5426       avi->todrop -= drop;
5427       avi->offset += drop;
5428     }
5429   }
5430
5431   /* Iterate until need more data, so adapter won't grow too much */
5432   while (1) {
5433     if (G_UNLIKELY (!gst_avi_demux_peek_chunk_info (avi, &tag, &size))) {
5434       return GST_FLOW_OK;
5435     }
5436
5437     GST_DEBUG ("Trying chunk (%" GST_FOURCC_FORMAT "), size %d",
5438         GST_FOURCC_ARGS (tag), size);
5439
5440     if (G_LIKELY ((tag & 0xff) >= '0' && (tag & 0xff) <= '9' &&
5441             ((tag >> 8) & 0xff) >= '0' && ((tag >> 8) & 0xff) <= '9')) {
5442       GST_LOG ("Chunk ok");
5443     } else if ((tag & 0xffff) == (('x' << 8) | 'i')) {
5444       GST_DEBUG ("Found sub-index tag");
5445       if (gst_avi_demux_peek_chunk (avi, &tag, &size) || size == 0) {
5446         /* accept 0 size buffer here */
5447         avi->abort_buffering = FALSE;
5448         GST_DEBUG ("  skipping %d bytes for now", size);
5449         gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
5450       }
5451       return GST_FLOW_OK;
5452     } else if (tag == GST_RIFF_TAG_RIFF) {
5453       /* RIFF tags can appear in ODML files, just jump over them */
5454       if (gst_adapter_available (avi->adapter) >= 12) {
5455         GST_DEBUG ("Found RIFF tag, skipping RIFF header");
5456         gst_adapter_flush (avi->adapter, 12);
5457         continue;
5458       }
5459       return GST_FLOW_OK;
5460     } else if (tag == GST_RIFF_TAG_idx1) {
5461       GST_DEBUG ("Found index tag");
5462       if (gst_avi_demux_peek_chunk (avi, &tag, &size) || size == 0) {
5463         /* accept 0 size buffer here */
5464         avi->abort_buffering = FALSE;
5465         GST_DEBUG ("  skipping %d bytes for now", size);
5466         gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
5467       }
5468       return GST_FLOW_OK;
5469     } else if (tag == GST_RIFF_TAG_LIST) {
5470       /* movi chunks might be grouped in rec list */
5471       if (gst_adapter_available (avi->adapter) >= 12) {
5472         GST_DEBUG ("Found LIST tag, skipping LIST header");
5473         gst_adapter_flush (avi->adapter, 12);
5474         continue;
5475       }
5476       return GST_FLOW_OK;
5477     } else if (tag == GST_RIFF_TAG_JUNK || tag == GST_RIFF_TAG_JUNQ) {
5478       /* rec list might contain JUNK chunks */
5479       GST_DEBUG ("Found JUNK tag");
5480       if (gst_avi_demux_peek_chunk (avi, &tag, &size) || size == 0) {
5481         /* accept 0 size buffer here */
5482         avi->abort_buffering = FALSE;
5483         GST_DEBUG ("  skipping %d bytes for now", size);
5484         gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
5485       }
5486       return GST_FLOW_OK;
5487     } else {
5488       GST_DEBUG ("No more stream chunks, send EOS");
5489       avi->have_eos = TRUE;
5490       return GST_FLOW_EOS;
5491     }
5492
5493     if (G_UNLIKELY (!gst_avi_demux_peek_chunk (avi, &tag, &size))) {
5494       /* supposedly one hopes to catch a nicer chunk later on ... */
5495       /* FIXME ?? give up here rather than possibly ending up going
5496        * through the whole file */
5497       if (avi->abort_buffering) {
5498         avi->abort_buffering = FALSE;
5499         if (size) {
5500           gst_adapter_flush (avi->adapter, 8);
5501           return GST_FLOW_OK;
5502         }
5503       } else {
5504         return GST_FLOW_OK;
5505       }
5506     }
5507     GST_DEBUG ("chunk ID %" GST_FOURCC_FORMAT ", size %u",
5508         GST_FOURCC_ARGS (tag), size);
5509
5510     stream_nr = CHUNKID_TO_STREAMNR (tag);
5511
5512     if (G_UNLIKELY (stream_nr < 0 || stream_nr >= avi->num_streams)) {
5513       /* recoverable */
5514       GST_WARNING ("Invalid stream ID %d (%" GST_FOURCC_FORMAT ")",
5515           stream_nr, GST_FOURCC_ARGS (tag));
5516       avi->offset += 8 + GST_ROUND_UP_2 (size);
5517       gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
5518     } else {
5519       GstAviStream *stream;
5520       GstClockTime next_ts = 0;
5521       GstBuffer *buf = NULL;
5522 #if 0
5523       guint64 offset;
5524 #endif
5525       gboolean saw_desired_kf = stream_nr != avi->main_stream
5526           || avi->offset >= avi->seek_kf_offset;
5527
5528       if (stream_nr == avi->main_stream && avi->offset == avi->seek_kf_offset) {
5529         GST_DEBUG_OBJECT (avi, "Desired keyframe reached");
5530         avi->seek_kf_offset = 0;
5531       }
5532
5533       if (saw_desired_kf) {
5534         gst_adapter_flush (avi->adapter, 8);
5535         /* get buffer */
5536         if (size) {
5537           buf = gst_adapter_take_buffer (avi->adapter, GST_ROUND_UP_2 (size));
5538           /* patch the size */
5539           gst_buffer_resize (buf, 0, size);
5540         } else {
5541           buf = NULL;
5542         }
5543       } else {
5544         GST_DEBUG_OBJECT (avi,
5545             "Desired keyframe not yet reached, flushing chunk");
5546         gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
5547       }
5548
5549 #if 0
5550       offset = avi->offset;
5551 #endif
5552       avi->offset += 8 + GST_ROUND_UP_2 (size);
5553
5554       stream = &avi->stream[stream_nr];
5555
5556       /* set delay (if any)
5557          if (stream->strh->init_frames == stream->current_frame &&
5558          stream->delay == 0)
5559          stream->delay = next_ts;
5560        */
5561
5562       /* parsing of corresponding header may have failed */
5563       if (G_UNLIKELY (!stream->pad)) {
5564         GST_WARNING_OBJECT (avi, "no pad for stream ID %" GST_FOURCC_FORMAT,
5565             GST_FOURCC_ARGS (tag));
5566         if (buf)
5567           gst_buffer_unref (buf);
5568       } else {
5569         /* get time of this buffer */
5570         gst_pad_query_position (stream->pad, GST_FORMAT_TIME,
5571             (gint64 *) & next_ts);
5572
5573 #if 0
5574         gst_avi_demux_add_assoc (avi, stream, next_ts, offset, FALSE);
5575 #endif
5576
5577         /* increment our positions */
5578         stream->current_entry++;
5579         /* as in pull mode, 'total' is either bytes (CBR) or frames (VBR) */
5580         if (stream->strh->type == GST_RIFF_FCC_auds && stream->is_vbr) {
5581           gint blockalign = stream->strf.auds->blockalign;
5582           if (blockalign > 0)
5583             stream->current_total += DIV_ROUND_UP (size, blockalign);
5584           else
5585             stream->current_total++;
5586         } else {
5587           stream->current_total += size;
5588         }
5589         GST_LOG_OBJECT (avi, "current entry %u, total %u",
5590             stream->current_entry, stream->current_total);
5591
5592         /* update current position in the segment */
5593         avi->segment.position = next_ts;
5594
5595         if (saw_desired_kf && buf) {
5596           GstClockTime dur_ts = 0;
5597
5598           /* invert the picture if needed, and append palette for RGB8P */
5599           buf = gst_avi_demux_invert (stream, buf);
5600
5601           gst_pad_query_position (stream->pad, GST_FORMAT_TIME,
5602               (gint64 *) & dur_ts);
5603
5604           GST_BUFFER_DTS (buf) = next_ts;
5605           GST_BUFFER_PTS (buf) = GST_CLOCK_TIME_NONE;
5606           GST_BUFFER_DURATION (buf) = dur_ts - next_ts;
5607           if (stream->strh->type == GST_RIFF_FCC_vids) {
5608             GST_BUFFER_OFFSET (buf) = stream->current_entry - 1;
5609             GST_BUFFER_OFFSET_END (buf) = stream->current_entry;
5610           } else {
5611             GST_BUFFER_OFFSET (buf) = GST_BUFFER_OFFSET_NONE;
5612             GST_BUFFER_OFFSET_END (buf) = GST_BUFFER_OFFSET_NONE;
5613           }
5614
5615           GST_DEBUG_OBJECT (avi,
5616               "Pushing buffer with time=%" GST_TIME_FORMAT ", duration %"
5617               GST_TIME_FORMAT ", offset %" G_GUINT64_FORMAT
5618               " and size %d over pad %s", GST_TIME_ARGS (next_ts),
5619               GST_TIME_ARGS (GST_BUFFER_DURATION (buf)),
5620               GST_BUFFER_OFFSET (buf), size, GST_PAD_NAME (stream->pad));
5621
5622           /* mark discont when pending */
5623           if (G_UNLIKELY (stream->discont)) {
5624             GST_DEBUG_OBJECT (avi, "Setting DISCONT");
5625             GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
5626             stream->discont = FALSE;
5627           } else {
5628             GST_BUFFER_FLAG_UNSET (buf, GST_BUFFER_FLAG_DISCONT);
5629           }
5630
5631           if (stream->alignment > 1)
5632             buf = gst_avi_demux_align_buffer (avi, buf, stream->alignment);
5633           res = gst_pad_push (stream->pad, buf);
5634           buf = NULL;
5635
5636           /* combine flows */
5637           res = gst_avi_demux_combine_flows (avi, stream, res);
5638           if (G_UNLIKELY (res != GST_FLOW_OK)) {
5639             GST_DEBUG ("Push failed; %s", gst_flow_get_name (res));
5640             return res;
5641           }
5642         }
5643       }
5644     }
5645   }
5646
5647   return res;
5648 }
5649
5650 /*
5651  * Send pending tags.
5652  */
5653 static void
5654 push_tag_lists (GstAviDemux * avi)
5655 {
5656   guint i;
5657   GstTagList *tags;
5658
5659   if (!avi->got_tags)
5660     return;
5661
5662   GST_DEBUG_OBJECT (avi, "Pushing pending tag lists");
5663
5664   for (i = 0; i < avi->num_streams; i++) {
5665     GstAviStream *stream = &avi->stream[i];
5666     GstPad *pad = stream->pad;
5667
5668     tags = stream->taglist;
5669
5670     if (pad && tags) {
5671       GST_DEBUG_OBJECT (pad, "Tags: %" GST_PTR_FORMAT, tags);
5672
5673       gst_pad_push_event (pad, gst_event_new_tag (tags));
5674       stream->taglist = NULL;
5675     }
5676   }
5677
5678   if (!(tags = avi->globaltags))
5679     tags = gst_tag_list_new_empty ();
5680
5681   gst_tag_list_add (tags, GST_TAG_MERGE_REPLACE,
5682       GST_TAG_CONTAINER_FORMAT, "AVI", NULL);
5683
5684   GST_DEBUG_OBJECT (avi, "Global tags: %" GST_PTR_FORMAT, tags);
5685   gst_tag_list_set_scope (tags, GST_TAG_SCOPE_GLOBAL);
5686   gst_avi_demux_push_event (avi, gst_event_new_tag (tags));
5687   avi->globaltags = NULL;
5688   avi->got_tags = FALSE;
5689 }
5690
5691 static void
5692 gst_avi_demux_loop (GstPad * pad)
5693 {
5694   GstFlowReturn res;
5695   GstAviDemux *avi = GST_AVI_DEMUX (GST_PAD_PARENT (pad));
5696
5697   switch (avi->state) {
5698     case GST_AVI_DEMUX_START:
5699       res = gst_avi_demux_stream_init_pull (avi);
5700       if (G_UNLIKELY (res != GST_FLOW_OK)) {
5701         GST_WARNING ("stream_init flow: %s", gst_flow_get_name (res));
5702         goto pause;
5703       }
5704       avi->state = GST_AVI_DEMUX_HEADER;
5705       /* fall-through */
5706     case GST_AVI_DEMUX_HEADER:
5707       res = gst_avi_demux_stream_header_pull (avi);
5708       if (G_UNLIKELY (res != GST_FLOW_OK)) {
5709         GST_WARNING ("stream_header flow: %s", gst_flow_get_name (res));
5710         goto pause;
5711       }
5712       avi->state = GST_AVI_DEMUX_MOVI;
5713       break;
5714     case GST_AVI_DEMUX_MOVI:
5715       if (G_UNLIKELY (avi->seg_event)) {
5716         gst_avi_demux_push_event (avi, avi->seg_event);
5717         avi->seg_event = NULL;
5718       }
5719       if (G_UNLIKELY (avi->got_tags)) {
5720         push_tag_lists (avi);
5721       }
5722       /* process each index entry in turn */
5723       res = gst_avi_demux_loop_data (avi);
5724
5725       /* pause when error */
5726       if (G_UNLIKELY (res != GST_FLOW_OK)) {
5727         GST_INFO ("stream_movi flow: %s", gst_flow_get_name (res));
5728         goto pause;
5729       }
5730       break;
5731     default:
5732       GST_ERROR_OBJECT (avi, "unknown state %d", avi->state);
5733       res = GST_FLOW_ERROR;
5734       goto pause;
5735   }
5736
5737   return;
5738
5739   /* ERRORS */
5740 pause:{
5741
5742     gboolean push_eos = FALSE;
5743     GST_LOG_OBJECT (avi, "pausing task, reason %s", gst_flow_get_name (res));
5744     gst_pad_pause_task (avi->sinkpad);
5745
5746     if (res == GST_FLOW_EOS) {
5747       /* handle end-of-stream/segment */
5748       /* so align our position with the end of it, if there is one
5749        * this ensures a subsequent will arrive at correct base/acc time */
5750       if (avi->segment.rate > 0.0 &&
5751           GST_CLOCK_TIME_IS_VALID (avi->segment.stop))
5752         avi->segment.position = avi->segment.stop;
5753       else if (avi->segment.rate < 0.0)
5754         avi->segment.position = avi->segment.start;
5755       if (avi->segment.flags & GST_SEEK_FLAG_SEGMENT) {
5756         gint64 stop;
5757         GstEvent *event;
5758         GstMessage *msg;
5759
5760         if ((stop = avi->segment.stop) == -1)
5761           stop = avi->segment.duration;
5762
5763         GST_INFO_OBJECT (avi, "sending segment_done");
5764
5765         msg =
5766             gst_message_new_segment_done (GST_OBJECT_CAST (avi),
5767             GST_FORMAT_TIME, stop);
5768         if (avi->segment_seqnum)
5769           gst_message_set_seqnum (msg, avi->segment_seqnum);
5770         gst_element_post_message (GST_ELEMENT_CAST (avi), msg);
5771
5772         event = gst_event_new_segment_done (GST_FORMAT_TIME, stop);
5773         if (avi->segment_seqnum)
5774           gst_event_set_seqnum (event, avi->segment_seqnum);
5775         gst_avi_demux_push_event (avi, event);
5776       } else {
5777         push_eos = TRUE;
5778       }
5779     } else if (res == GST_FLOW_NOT_LINKED || res < GST_FLOW_EOS) {
5780       /* for fatal errors we post an error message, wrong-state is
5781        * not fatal because it happens due to flushes and only means
5782        * that we should stop now. */
5783       GST_ELEMENT_FLOW_ERROR (avi, res);
5784       push_eos = TRUE;
5785     }
5786     if (push_eos) {
5787       GstEvent *event;
5788
5789       GST_INFO_OBJECT (avi, "sending eos");
5790       event = gst_event_new_eos ();
5791       if (avi->segment_seqnum)
5792         gst_event_set_seqnum (event, avi->segment_seqnum);
5793       if (!gst_avi_demux_push_event (avi, event) && (res == GST_FLOW_EOS)) {
5794         GST_ELEMENT_ERROR (avi, STREAM, DEMUX,
5795             (NULL), ("got eos but no streams (yet)"));
5796       }
5797     }
5798   }
5799 }
5800
5801
5802 static GstFlowReturn
5803 gst_avi_demux_chain (GstPad * pad, GstObject * parent, GstBuffer * buf)
5804 {
5805   GstFlowReturn res;
5806   GstAviDemux *avi = GST_AVI_DEMUX (parent);
5807   gint i;
5808
5809   if (GST_BUFFER_IS_DISCONT (buf)) {
5810     GST_DEBUG_OBJECT (avi, "got DISCONT");
5811     gst_adapter_clear (avi->adapter);
5812     /* mark all streams DISCONT */
5813     for (i = 0; i < avi->num_streams; i++)
5814       avi->stream[i].discont = TRUE;
5815   }
5816
5817   GST_DEBUG ("Store %" G_GSIZE_FORMAT " bytes in adapter",
5818       gst_buffer_get_size (buf));
5819   gst_adapter_push (avi->adapter, buf);
5820
5821   switch (avi->state) {
5822     case GST_AVI_DEMUX_START:
5823       if ((res = gst_avi_demux_stream_init_push (avi)) != GST_FLOW_OK) {
5824         GST_WARNING ("stream_init flow: %s", gst_flow_get_name (res));
5825         break;
5826       }
5827       break;
5828     case GST_AVI_DEMUX_HEADER:
5829       if ((res = gst_avi_demux_stream_header_push (avi)) != GST_FLOW_OK) {
5830         GST_WARNING ("stream_header flow: %s", gst_flow_get_name (res));
5831         break;
5832       }
5833       break;
5834     case GST_AVI_DEMUX_MOVI:
5835       if (G_UNLIKELY (avi->seg_event)) {
5836         gst_avi_demux_push_event (avi, avi->seg_event);
5837         avi->seg_event = NULL;
5838       }
5839       if (G_UNLIKELY (avi->got_tags)) {
5840         push_tag_lists (avi);
5841       }
5842       res = gst_avi_demux_stream_data (avi);
5843       break;
5844     case GST_AVI_DEMUX_SEEK:
5845     {
5846       GstEvent *event;
5847
5848       res = GST_FLOW_OK;
5849
5850       /* obtain and parse indexes */
5851       if (avi->stream[0].indexes && !gst_avi_demux_read_subindexes_push (avi))
5852         /* seek in subindex read function failed */
5853         goto index_failed;
5854
5855       if (!avi->stream[0].indexes && !avi->have_index
5856           && avi->avih->flags & GST_RIFF_AVIH_HASINDEX)
5857         gst_avi_demux_stream_index_push (avi);
5858
5859       if (avi->have_index) {
5860         /* use the indexes now to construct nice durations */
5861         gst_avi_demux_calculate_durations_from_index (avi);
5862       } else {
5863         /* still parsing indexes */
5864         break;
5865       }
5866
5867       GST_OBJECT_LOCK (avi);
5868       event = avi->seek_event;
5869       avi->seek_event = NULL;
5870       GST_OBJECT_UNLOCK (avi);
5871
5872       /* calculate and perform seek */
5873       if (!avi_demux_handle_seek_push (avi, avi->sinkpad, event)) {
5874         gst_event_unref (event);
5875         goto seek_failed;
5876       }
5877
5878       gst_event_unref (event);
5879       avi->state = GST_AVI_DEMUX_MOVI;
5880       break;
5881     }
5882     default:
5883       GST_ELEMENT_ERROR (avi, STREAM, FAILED, (NULL),
5884           ("Illegal internal state"));
5885       res = GST_FLOW_ERROR;
5886       break;
5887   }
5888
5889   GST_DEBUG_OBJECT (avi, "state: %d res:%s", avi->state,
5890       gst_flow_get_name (res));
5891
5892   if (G_UNLIKELY (avi->abort_buffering))
5893     goto abort_buffering;
5894
5895   return res;
5896
5897   /* ERRORS */
5898 index_failed:
5899   {
5900     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("failed to read indexes"));
5901     return GST_FLOW_ERROR;
5902   }
5903 seek_failed:
5904   {
5905     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("push mode seek failed"));
5906     return GST_FLOW_ERROR;
5907   }
5908 abort_buffering:
5909   {
5910     avi->abort_buffering = FALSE;
5911     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("unhandled buffer size"));
5912     return GST_FLOW_ERROR;
5913   }
5914 }
5915
5916 static gboolean
5917 gst_avi_demux_sink_activate (GstPad * sinkpad, GstObject * parent)
5918 {
5919   GstQuery *query;
5920   gboolean pull_mode;
5921
5922   query = gst_query_new_scheduling ();
5923
5924   if (!gst_pad_peer_query (sinkpad, query)) {
5925     gst_query_unref (query);
5926     goto activate_push;
5927   }
5928
5929   pull_mode = gst_query_has_scheduling_mode_with_flags (query,
5930       GST_PAD_MODE_PULL, GST_SCHEDULING_FLAG_SEEKABLE);
5931   gst_query_unref (query);
5932
5933   if (!pull_mode)
5934     goto activate_push;
5935
5936   GST_DEBUG_OBJECT (sinkpad, "activating pull");
5937   return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PULL, TRUE);
5938
5939 activate_push:
5940   {
5941     GST_DEBUG_OBJECT (sinkpad, "activating push");
5942     return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
5943   }
5944 }
5945
5946 static gboolean
5947 gst_avi_demux_sink_activate_mode (GstPad * sinkpad, GstObject * parent,
5948     GstPadMode mode, gboolean active)
5949 {
5950   gboolean res;
5951   GstAviDemux *avi = GST_AVI_DEMUX (parent);
5952
5953   switch (mode) {
5954     case GST_PAD_MODE_PULL:
5955       if (active) {
5956         avi->streaming = FALSE;
5957         res = gst_pad_start_task (sinkpad, (GstTaskFunction) gst_avi_demux_loop,
5958             sinkpad, NULL);
5959       } else {
5960         res = gst_pad_stop_task (sinkpad);
5961       }
5962       break;
5963     case GST_PAD_MODE_PUSH:
5964       if (active) {
5965         GST_DEBUG ("avi: activating push/chain function");
5966         avi->streaming = TRUE;
5967       } else {
5968         GST_DEBUG ("avi: deactivating push/chain function");
5969       }
5970       res = TRUE;
5971       break;
5972     default:
5973       res = FALSE;
5974       break;
5975   }
5976   return res;
5977 }
5978
5979 #if 0
5980 static void
5981 gst_avi_demux_set_index (GstElement * element, GstIndex * index)
5982 {
5983   GstAviDemux *avi = GST_AVI_DEMUX (element);
5984
5985   GST_OBJECT_LOCK (avi);
5986   if (avi->element_index)
5987     gst_object_unref (avi->element_index);
5988   if (index) {
5989     avi->element_index = gst_object_ref (index);
5990   } else {
5991     avi->element_index = NULL;
5992   }
5993   GST_OBJECT_UNLOCK (avi);
5994   /* object lock might be taken again */
5995   if (index)
5996     gst_index_get_writer_id (index, GST_OBJECT_CAST (element), &avi->index_id);
5997   GST_DEBUG_OBJECT (avi, "Set index %" GST_PTR_FORMAT, avi->element_index);
5998 }
5999
6000 static GstIndex *
6001 gst_avi_demux_get_index (GstElement * element)
6002 {
6003   GstIndex *result = NULL;
6004   GstAviDemux *avi = GST_AVI_DEMUX (element);
6005
6006   GST_OBJECT_LOCK (avi);
6007   if (avi->element_index)
6008     result = gst_object_ref (avi->element_index);
6009   GST_OBJECT_UNLOCK (avi);
6010
6011   GST_DEBUG_OBJECT (avi, "Returning index %" GST_PTR_FORMAT, result);
6012
6013   return result;
6014 }
6015 #endif
6016
6017 static GstStateChangeReturn
6018 gst_avi_demux_change_state (GstElement * element, GstStateChange transition)
6019 {
6020   GstStateChangeReturn ret;
6021   GstAviDemux *avi = GST_AVI_DEMUX (element);
6022
6023   switch (transition) {
6024     case GST_STATE_CHANGE_READY_TO_PAUSED:
6025       avi->streaming = FALSE;
6026       gst_segment_init (&avi->segment, GST_FORMAT_TIME);
6027       break;
6028     default:
6029       break;
6030   }
6031
6032   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
6033   if (ret == GST_STATE_CHANGE_FAILURE)
6034     goto done;
6035
6036   switch (transition) {
6037     case GST_STATE_CHANGE_PAUSED_TO_READY:
6038       avi->have_index = FALSE;
6039       gst_avi_demux_reset (avi);
6040       break;
6041     default:
6042       break;
6043   }
6044
6045 done:
6046   return ret;
6047 }