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