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