Merge branch 'master' into 0.11
[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_details_simple (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;
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     res = gst_pad_pull_range (avi->sinkpad, offset, 8, &buf);
2689     if (res != GST_FLOW_OK)
2690       goto pull_failed;
2691
2692     gst_buffer_map (buf, &map, GST_MAP_READ);
2693     if (map.size < 8)
2694       goto too_small;
2695
2696     tag = GST_READ_UINT32_LE (map.data);
2697     size = GST_READ_UINT32_LE (map.data + 4);
2698   }
2699   gst_buffer_unmap (buf, &map);
2700   gst_buffer_unref (buf);
2701
2702   if (tag != GST_RIFF_TAG_idx1)
2703     goto no_index;
2704   if (!size)
2705     goto zero_index;
2706
2707   GST_DEBUG ("index found at offset %" G_GUINT64_FORMAT, offset);
2708
2709   /* read chunk, advance offset */
2710   if (gst_riff_read_chunk (GST_ELEMENT_CAST (avi),
2711           avi->sinkpad, &offset, &tag, &buf) != GST_FLOW_OK)
2712     return;
2713
2714   GST_DEBUG ("will parse index chunk size %" G_GSIZE_FORMAT " for tag %"
2715       GST_FOURCC_FORMAT, gst_buffer_get_size (buf), GST_FOURCC_ARGS (tag));
2716
2717   gst_avi_demux_parse_index (avi, buf);
2718
2719 #ifndef GST_DISABLE_GST_DEBUG
2720   /* debug our indexes */
2721   {
2722     gint i;
2723     GstAviStream *stream;
2724
2725     for (i = 0; i < avi->num_streams; i++) {
2726       stream = &avi->stream[i];
2727       GST_DEBUG_OBJECT (avi, "stream %u: %u frames, %" G_GINT64_FORMAT " bytes",
2728           i, stream->idx_n, stream->total_bytes);
2729     }
2730   }
2731 #endif
2732   return;
2733
2734   /* ERRORS */
2735 pull_failed:
2736   {
2737     GST_DEBUG_OBJECT (avi,
2738         "pull range failed: pos=%" G_GUINT64_FORMAT " size=8", offset);
2739     return;
2740   }
2741 too_small:
2742   {
2743     GST_DEBUG_OBJECT (avi, "Buffer is too small");
2744     gst_buffer_unmap (buf, &map);
2745     gst_buffer_unref (buf);
2746     return;
2747   }
2748 no_index:
2749   {
2750     GST_WARNING_OBJECT (avi,
2751         "No index data (idx1) after movi chunk, but %" GST_FOURCC_FORMAT,
2752         GST_FOURCC_ARGS (tag));
2753     return;
2754   }
2755 zero_index:
2756   {
2757     GST_WARNING_OBJECT (avi, "Empty index data (idx1) after movi chunk");
2758     return;
2759   }
2760 }
2761
2762 /*
2763  * gst_avi_demux_stream_index_push:
2764  * @avi: avi demuxer object.
2765  *
2766  * Read index.
2767  */
2768 static void
2769 gst_avi_demux_stream_index_push (GstAviDemux * avi)
2770 {
2771   guint64 offset = avi->idx1_offset;
2772   GstBuffer *buf;
2773   guint32 tag;
2774   guint32 size;
2775
2776   GST_DEBUG ("demux stream index at offset %" G_GUINT64_FORMAT, offset);
2777
2778   /* get chunk information */
2779   if (!gst_avi_demux_peek_chunk (avi, &tag, &size))
2780     return;
2781
2782   /* check tag first before blindly trying to read 'size' bytes */
2783   if (tag == GST_RIFF_TAG_LIST) {
2784     /* this is the movi tag */
2785     GST_DEBUG_OBJECT (avi, "skip LIST chunk, size %" G_GUINT32_FORMAT,
2786         (8 + GST_ROUND_UP_2 (size)));
2787     avi->idx1_offset = offset + 8 + GST_ROUND_UP_2 (size);
2788     /* issue seek to allow chain function to handle it and return! */
2789     perform_seek_to_offset (avi, avi->idx1_offset);
2790     return;
2791   }
2792
2793   if (tag != GST_RIFF_TAG_idx1)
2794     goto no_index;
2795
2796   GST_DEBUG ("index found at offset %" G_GUINT64_FORMAT, offset);
2797
2798   /* flush chunk header */
2799   gst_adapter_flush (avi->adapter, 8);
2800   /* read chunk payload */
2801   buf = gst_adapter_take_buffer (avi->adapter, size);
2802   if (!buf)
2803     goto pull_failed;
2804   /* advance offset */
2805   offset += 8 + GST_ROUND_UP_2 (size);
2806
2807   GST_DEBUG ("will parse index chunk size %" G_GSIZE_FORMAT " for tag %"
2808       GST_FOURCC_FORMAT, gst_buffer_get_size (buf), GST_FOURCC_ARGS (tag));
2809
2810   avi->offset = avi->first_movi_offset;
2811   gst_avi_demux_parse_index (avi, buf);
2812
2813 #ifndef GST_DISABLE_GST_DEBUG
2814   /* debug our indexes */
2815   {
2816     gint i;
2817     GstAviStream *stream;
2818
2819     for (i = 0; i < avi->num_streams; i++) {
2820       stream = &avi->stream[i];
2821       GST_DEBUG_OBJECT (avi, "stream %u: %u frames, %" G_GINT64_FORMAT " bytes",
2822           i, stream->idx_n, stream->total_bytes);
2823     }
2824   }
2825 #endif
2826   return;
2827
2828   /* ERRORS */
2829 pull_failed:
2830   {
2831     GST_DEBUG_OBJECT (avi,
2832         "taking data from adapter failed: pos=%" G_GUINT64_FORMAT " size=%u",
2833         offset, size);
2834     return;
2835   }
2836 no_index:
2837   {
2838     GST_WARNING_OBJECT (avi,
2839         "No index data (idx1) after movi chunk, but %" GST_FOURCC_FORMAT,
2840         GST_FOURCC_ARGS (tag));
2841     return;
2842   }
2843 }
2844
2845 /*
2846  * gst_avi_demux_peek_tag:
2847  *
2848  * Returns the tag and size of the next chunk
2849  */
2850 static GstFlowReturn
2851 gst_avi_demux_peek_tag (GstAviDemux * avi, guint64 offset, guint32 * tag,
2852     guint * size)
2853 {
2854   GstFlowReturn res = GST_FLOW_OK;
2855   GstBuffer *buf = NULL;
2856   GstMapInfo map;
2857
2858   res = gst_pad_pull_range (avi->sinkpad, offset, 8, &buf);
2859   if (res != GST_FLOW_OK)
2860     goto pull_failed;
2861
2862   gst_buffer_map (buf, &map, GST_MAP_READ);
2863   if (map.size != 8)
2864     goto wrong_size;
2865
2866   *tag = GST_READ_UINT32_LE (map.data);
2867   *size = GST_READ_UINT32_LE (map.data + 4);
2868
2869   GST_LOG_OBJECT (avi, "Tag[%" GST_FOURCC_FORMAT "] (size:%d) %"
2870       G_GINT64_FORMAT " -- %" G_GINT64_FORMAT, GST_FOURCC_ARGS (*tag),
2871       *size, offset + 8, offset + 8 + (gint64) * size);
2872
2873 done:
2874   gst_buffer_unmap (buf, &map);
2875   gst_buffer_unref (buf);
2876
2877   return res;
2878
2879   /* ERRORS */
2880 pull_failed:
2881   {
2882     GST_DEBUG_OBJECT (avi, "pull_ranged returned %s", gst_flow_get_name (res));
2883     return res;
2884   }
2885 wrong_size:
2886   {
2887     GST_DEBUG_OBJECT (avi, "got %" G_GSIZE_FORMAT " bytes which is <> 8 bytes",
2888         map.size);
2889     res = GST_FLOW_ERROR;
2890     goto done;
2891   }
2892 }
2893
2894 /*
2895  * gst_avi_demux_next_data_buffer:
2896  *
2897  * Returns the offset and size of the next buffer
2898  * Position is the position of the buffer (after tag and size)
2899  */
2900 static GstFlowReturn
2901 gst_avi_demux_next_data_buffer (GstAviDemux * avi, guint64 * offset,
2902     guint32 * tag, guint * size)
2903 {
2904   guint64 off = *offset;
2905   guint _size = 0;
2906   GstFlowReturn res;
2907
2908   do {
2909     res = gst_avi_demux_peek_tag (avi, off, tag, &_size);
2910     if (res != GST_FLOW_OK)
2911       break;
2912     if (*tag == GST_RIFF_TAG_LIST || *tag == GST_RIFF_TAG_RIFF)
2913       off += 8 + 4;             /* skip tag + size + subtag */
2914     else {
2915       *offset = off + 8;
2916       *size = _size;
2917       break;
2918     }
2919   } while (TRUE);
2920
2921   return res;
2922 }
2923
2924 /*
2925  * gst_avi_demux_stream_scan:
2926  * @avi: calling element (used for debugging/errors).
2927  *
2928  * Scan the file for all chunks to "create" a new index.
2929  * pull-range based
2930  */
2931 static gboolean
2932 gst_avi_demux_stream_scan (GstAviDemux * avi)
2933 {
2934   GstFlowReturn res;
2935   GstAviStream *stream;
2936   guint64 pos = 0;
2937   guint64 length;
2938   gint64 tmplength;
2939   guint32 tag = 0;
2940   guint num;
2941
2942   /* FIXME:
2943    * - implement non-seekable source support.
2944    */
2945   GST_DEBUG_OBJECT (avi, "Creating index");
2946
2947   /* get the size of the file */
2948   if (!gst_pad_peer_query_duration (avi->sinkpad, GST_FORMAT_BYTES, &tmplength))
2949     return FALSE;
2950   length = tmplength;
2951
2952   /* guess the total amount of entries we expect */
2953   num = 16000;
2954
2955   while (TRUE) {
2956     GstAviIndexEntry entry;
2957     guint size = 0;
2958
2959     /* start reading data buffers to find the id and offset */
2960     res = gst_avi_demux_next_data_buffer (avi, &pos, &tag, &size);
2961     if (G_UNLIKELY (res != GST_FLOW_OK))
2962       break;
2963
2964     /* get stream */
2965     stream = gst_avi_demux_stream_for_id (avi, tag);
2966     if (G_UNLIKELY (!stream))
2967       goto next;
2968
2969     /* we can't figure out the keyframes, assume they all are */
2970     entry.flags = GST_AVI_KEYFRAME;
2971     entry.offset = pos;
2972     entry.size = size;
2973
2974     /* and add to the index of this stream */
2975     if (G_UNLIKELY (!gst_avi_demux_add_index (avi, stream, num, &entry)))
2976       goto out_of_mem;
2977
2978   next:
2979     /* update position */
2980     pos += GST_ROUND_UP_2 (size);
2981     if (G_UNLIKELY (pos > length)) {
2982       GST_WARNING_OBJECT (avi,
2983           "Stopping index lookup since we are further than EOF");
2984       break;
2985     }
2986   }
2987
2988   /* collect stats */
2989   avi->have_index = gst_avi_demux_do_index_stats (avi);
2990
2991   return TRUE;
2992
2993   /* ERRORS */
2994 out_of_mem:
2995   {
2996     GST_ELEMENT_ERROR (avi, RESOURCE, NO_SPACE_LEFT, (NULL),
2997         ("Cannot allocate memory for %u*%u=%u bytes",
2998             (guint) sizeof (GstAviIndexEntry), num,
2999             (guint) sizeof (GstAviIndexEntry) * num));
3000     return FALSE;
3001   }
3002 }
3003
3004 static void
3005 gst_avi_demux_calculate_durations_from_index (GstAviDemux * avi)
3006 {
3007   guint i;
3008   GstClockTime total;
3009   GstAviStream *stream;
3010
3011   total = GST_CLOCK_TIME_NONE;
3012
3013   /* all streams start at a timestamp 0 */
3014   for (i = 0; i < avi->num_streams; i++) {
3015     GstClockTime duration, hduration;
3016     gst_riff_strh *strh;
3017
3018     stream = &avi->stream[i];
3019     if (G_UNLIKELY (!stream || !stream->idx_n || !(strh = stream->strh)))
3020       continue;
3021
3022     /* get header duration for the stream */
3023     hduration = stream->hdr_duration;
3024     /* index duration calculated during parsing */
3025     duration = stream->idx_duration;
3026
3027     /* now pick a good duration */
3028     if (GST_CLOCK_TIME_IS_VALID (duration)) {
3029       /* index gave valid duration, use that */
3030       GST_INFO ("Stream %p duration according to index: %" GST_TIME_FORMAT,
3031           stream, GST_TIME_ARGS (duration));
3032     } else {
3033       /* fall back to header info to calculate a duration */
3034       duration = hduration;
3035     }
3036     GST_INFO ("Setting duration of stream #%d to %" GST_TIME_FORMAT,
3037         i, GST_TIME_ARGS (duration));
3038     /* set duration for the stream */
3039     stream->duration = duration;
3040
3041     /* find total duration */
3042     if (total == GST_CLOCK_TIME_NONE ||
3043         (GST_CLOCK_TIME_IS_VALID (duration) && duration > total))
3044       total = duration;
3045   }
3046
3047   if (GST_CLOCK_TIME_IS_VALID (total) && (total > 0)) {
3048     /* now update the duration for those streams where we had none */
3049     for (i = 0; i < avi->num_streams; i++) {
3050       stream = &avi->stream[i];
3051
3052       if (!GST_CLOCK_TIME_IS_VALID (stream->duration)
3053           || stream->duration == 0) {
3054         stream->duration = total;
3055
3056         GST_INFO ("Stream %p duration according to total: %" GST_TIME_FORMAT,
3057             stream, GST_TIME_ARGS (total));
3058       }
3059     }
3060   }
3061
3062   /* and set the total duration in the segment. */
3063   GST_INFO ("Setting total duration to: %" GST_TIME_FORMAT,
3064       GST_TIME_ARGS (total));
3065
3066   avi->segment.duration = total;
3067 }
3068
3069 /* returns FALSE if there are no pads to deliver event to,
3070  * otherwise TRUE (whatever the outcome of event sending),
3071  * takes ownership of the event. */
3072 static gboolean
3073 gst_avi_demux_push_event (GstAviDemux * avi, GstEvent * event)
3074 {
3075   gboolean result = FALSE;
3076   gint i;
3077
3078   GST_DEBUG_OBJECT (avi, "sending %s event to %d streams",
3079       GST_EVENT_TYPE_NAME (event), avi->num_streams);
3080
3081   for (i = 0; i < avi->num_streams; i++) {
3082     GstAviStream *stream = &avi->stream[i];
3083
3084     if (stream->pad) {
3085       result = TRUE;
3086       gst_pad_push_event (stream->pad, gst_event_ref (event));
3087     }
3088   }
3089   gst_event_unref (event);
3090   return result;
3091 }
3092
3093 static void
3094 gst_avi_demux_check_seekability (GstAviDemux * avi)
3095 {
3096   GstQuery *query;
3097   gboolean seekable = FALSE;
3098   gint64 start = -1, stop = -1;
3099
3100   query = gst_query_new_seeking (GST_FORMAT_BYTES);
3101   if (!gst_pad_peer_query (avi->sinkpad, query)) {
3102     GST_DEBUG_OBJECT (avi, "seeking query failed");
3103     goto done;
3104   }
3105
3106   gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
3107
3108   /* try harder to query upstream size if we didn't get it the first time */
3109   if (seekable && stop == -1) {
3110     GST_DEBUG_OBJECT (avi, "doing duration query to fix up unset stop");
3111     gst_pad_peer_query_duration (avi->sinkpad, GST_FORMAT_BYTES, &stop);
3112   }
3113
3114   /* if upstream doesn't know the size, it's likely that it's not seekable in
3115    * practice even if it technically may be seekable */
3116   if (seekable && (start != 0 || stop <= start)) {
3117     GST_DEBUG_OBJECT (avi, "seekable but unknown start/stop -> disable");
3118     seekable = FALSE;
3119   }
3120
3121 done:
3122   GST_INFO_OBJECT (avi, "seekable: %d (%" G_GUINT64_FORMAT " - %"
3123       G_GUINT64_FORMAT ")", seekable, start, stop);
3124   avi->seekable = seekable;
3125
3126   gst_query_unref (query);
3127 }
3128
3129 /*
3130  * Read AVI headers when streaming
3131  */
3132 static GstFlowReturn
3133 gst_avi_demux_stream_header_push (GstAviDemux * avi)
3134 {
3135   GstFlowReturn ret = GST_FLOW_OK;
3136   guint32 tag = 0;
3137   guint32 ltag = 0;
3138   guint32 size = 0;
3139   const guint8 *data;
3140   GstBuffer *buf = NULL, *sub = NULL;
3141   guint offset = 4;
3142   gint i;
3143   GstTagList *tags = NULL;
3144   guint8 fourcc[4];
3145
3146   GST_DEBUG ("Reading and parsing avi headers: %d", avi->header_state);
3147
3148   switch (avi->header_state) {
3149     case GST_AVI_DEMUX_HEADER_TAG_LIST:
3150       if (gst_avi_demux_peek_chunk (avi, &tag, &size)) {
3151         avi->offset += 8 + GST_ROUND_UP_2 (size);
3152         if (tag != GST_RIFF_TAG_LIST)
3153           goto header_no_list;
3154
3155         gst_adapter_flush (avi->adapter, 8);
3156         /* Find the 'hdrl' LIST tag */
3157         GST_DEBUG ("Reading %d bytes", size);
3158         buf = gst_adapter_take_buffer (avi->adapter, size);
3159
3160         gst_buffer_extract (buf, 0, fourcc, 4);
3161
3162         if (GST_READ_UINT32_LE (fourcc) != GST_RIFF_LIST_hdrl)
3163           goto header_no_hdrl;
3164
3165         /* mind padding */
3166         if (size & 1)
3167           gst_adapter_flush (avi->adapter, 1);
3168
3169         GST_DEBUG ("'hdrl' LIST tag found. Parsing next chunk");
3170
3171         gst_avi_demux_roundup_list (avi, &buf);
3172
3173         /* the hdrl starts with a 'avih' header */
3174         if (!gst_riff_parse_chunk (GST_ELEMENT_CAST (avi), buf, &offset, &tag,
3175                 &sub))
3176           goto header_no_avih;
3177
3178         if (tag != GST_RIFF_TAG_avih)
3179           goto header_no_avih;
3180
3181         if (!gst_avi_demux_parse_avih (avi, sub, &avi->avih))
3182           goto header_wrong_avih;
3183
3184         GST_DEBUG_OBJECT (avi, "AVI header ok, reading elemnts from header");
3185
3186         /* now, read the elements from the header until the end */
3187         while (gst_riff_parse_chunk (GST_ELEMENT_CAST (avi), buf, &offset, &tag,
3188                 &sub)) {
3189           /* sub can be NULL on empty tags */
3190           if (!sub)
3191             continue;
3192
3193           switch (tag) {
3194             case GST_RIFF_TAG_LIST:
3195               if (gst_buffer_get_size (sub) < 4)
3196                 goto next;
3197
3198               gst_buffer_extract (sub, 0, fourcc, 4);
3199
3200               switch (GST_READ_UINT32_LE (fourcc)) {
3201                 case GST_RIFF_LIST_strl:
3202                   if (!(gst_avi_demux_parse_stream (avi, sub))) {
3203                     sub = NULL;
3204                     GST_ELEMENT_WARNING (avi, STREAM, DEMUX, (NULL),
3205                         ("failed to parse stream, ignoring"));
3206                     goto next;
3207                   }
3208                   sub = NULL;
3209                   goto next;
3210                 case GST_RIFF_LIST_odml:
3211                   gst_avi_demux_parse_odml (avi, sub);
3212                   sub = NULL;
3213                   break;
3214                 default:
3215                   GST_WARNING_OBJECT (avi,
3216                       "Unknown list %" GST_FOURCC_FORMAT " in AVI header",
3217                       GST_FOURCC_ARGS (GST_READ_UINT32_LE (fourcc)));
3218                   /* fall-through */
3219                 case GST_RIFF_TAG_JUNQ:
3220                 case GST_RIFF_TAG_JUNK:
3221                   goto next;
3222                   break;
3223               }
3224             case GST_RIFF_IDIT:
3225               gst_avi_demux_parse_idit (avi, sub);
3226               goto next;
3227             default:
3228               GST_WARNING_OBJECT (avi,
3229                   "Unknown off %d tag %" GST_FOURCC_FORMAT " in AVI header",
3230                   offset, GST_FOURCC_ARGS (tag));
3231               /* fall-through */
3232             case GST_RIFF_TAG_JUNQ:
3233             case GST_RIFF_TAG_JUNK:
3234             next:
3235               /* move to next chunk */
3236               if (sub)
3237                 gst_buffer_unref (sub);
3238               sub = NULL;
3239               break;
3240           }
3241         }
3242         gst_buffer_unref (buf);
3243         GST_DEBUG ("elements parsed");
3244
3245         /* check parsed streams */
3246         if (avi->num_streams == 0) {
3247           goto no_streams;
3248         } else if (avi->num_streams != avi->avih->streams) {
3249           GST_WARNING_OBJECT (avi,
3250               "Stream header mentioned %d streams, but %d available",
3251               avi->avih->streams, avi->num_streams);
3252         }
3253         GST_DEBUG ("Get junk and info next");
3254         avi->header_state = GST_AVI_DEMUX_HEADER_INFO;
3255       } else {
3256         /* Need more data */
3257         return ret;
3258       }
3259       /* fall-though */
3260     case GST_AVI_DEMUX_HEADER_INFO:
3261       GST_DEBUG_OBJECT (avi, "skipping junk between header and data ...");
3262       while (TRUE) {
3263         if (gst_adapter_available (avi->adapter) < 12)
3264           return GST_FLOW_OK;
3265
3266         data = gst_adapter_map (avi->adapter, 12);
3267         tag = GST_READ_UINT32_LE (data);
3268         size = GST_READ_UINT32_LE (data + 4);
3269         ltag = GST_READ_UINT32_LE (data + 8);
3270         gst_adapter_unmap (avi->adapter);
3271
3272         if (tag == GST_RIFF_TAG_LIST) {
3273           switch (ltag) {
3274             case GST_RIFF_LIST_movi:
3275               gst_adapter_flush (avi->adapter, 12);
3276               if (!avi->first_movi_offset)
3277                 avi->first_movi_offset = avi->offset;
3278               avi->offset += 12;
3279               avi->idx1_offset = avi->offset + size - 4;
3280               goto skipping_done;
3281             case GST_RIFF_LIST_INFO:
3282               GST_DEBUG ("Found INFO chunk");
3283               if (gst_avi_demux_peek_chunk (avi, &tag, &size)) {
3284                 GST_DEBUG ("got size %d", size);
3285                 avi->offset += 12;
3286                 gst_adapter_flush (avi->adapter, 12);
3287                 if (size > 4) {
3288                   buf = gst_adapter_take_buffer (avi->adapter, size - 4);
3289                   /* mind padding */
3290                   if (size & 1)
3291                     gst_adapter_flush (avi->adapter, 1);
3292                   gst_riff_parse_info (GST_ELEMENT_CAST (avi), buf, &tags);
3293                   if (tags) {
3294                     if (avi->globaltags) {
3295                       gst_tag_list_insert (avi->globaltags, tags,
3296                           GST_TAG_MERGE_REPLACE);
3297                     } else {
3298                       avi->globaltags = tags;
3299                     }
3300                   }
3301                   tags = NULL;
3302                   gst_buffer_unref (buf);
3303
3304                   avi->offset += GST_ROUND_UP_2 (size) - 4;
3305                 } else {
3306                   GST_DEBUG ("skipping INFO LIST prefix");
3307                 }
3308               } else {
3309                 /* Need more data */
3310                 return GST_FLOW_OK;
3311               }
3312               break;
3313             default:
3314               if (gst_avi_demux_peek_chunk (avi, &tag, &size)) {
3315                 avi->offset += 8 + GST_ROUND_UP_2 (size);
3316                 gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
3317                 // ??? goto iterate; ???
3318               } else {
3319                 /* Need more data */
3320                 return GST_FLOW_OK;
3321               }
3322               break;
3323           }
3324         } else {
3325           if (gst_avi_demux_peek_chunk (avi, &tag, &size)) {
3326             avi->offset += 8 + GST_ROUND_UP_2 (size);
3327             gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
3328             //goto iterate;
3329           } else {
3330             /* Need more data */
3331             return GST_FLOW_OK;
3332           }
3333         }
3334       }
3335       break;
3336     default:
3337       GST_WARNING ("unhandled header state: %d", avi->header_state);
3338       break;
3339   }
3340 skipping_done:
3341
3342   GST_DEBUG_OBJECT (avi, "skipping done ... (streams=%u, stream[0].indexes=%p)",
3343       avi->num_streams, avi->stream[0].indexes);
3344
3345   GST_DEBUG ("Found movi chunk. Starting to stream data");
3346   avi->state = GST_AVI_DEMUX_MOVI;
3347
3348   /* no indexes in push mode, but it still sets some variables */
3349   gst_avi_demux_calculate_durations_from_index (avi);
3350
3351   gst_avi_demux_expose_streams (avi, TRUE);
3352
3353   /* prepare all streams for index 0 */
3354   for (i = 0; i < avi->num_streams; i++)
3355     avi->stream[i].current_entry = 0;
3356
3357   /* create initial NEWSEGMENT event */
3358   if (avi->seg_event)
3359     gst_event_unref (avi->seg_event);
3360   avi->seg_event = gst_event_new_segment (&avi->segment);
3361
3362   gst_avi_demux_check_seekability (avi);
3363
3364   /* at this point we know all the streams and we can signal the no more
3365    * pads signal */
3366   GST_DEBUG_OBJECT (avi, "signaling no more pads");
3367   gst_element_no_more_pads (GST_ELEMENT_CAST (avi));
3368
3369   return GST_FLOW_OK;
3370
3371   /* ERRORS */
3372 no_streams:
3373   {
3374     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("No streams found"));
3375     return GST_FLOW_ERROR;
3376   }
3377 header_no_list:
3378   {
3379     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3380         ("Invalid AVI header (no LIST at start): %"
3381             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3382     return GST_FLOW_ERROR;
3383   }
3384 header_no_hdrl:
3385   {
3386     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3387         ("Invalid AVI header (no hdrl at start): %"
3388             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3389     gst_buffer_unref (buf);
3390     return GST_FLOW_ERROR;
3391   }
3392 header_no_avih:
3393   {
3394     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3395         ("Invalid AVI header (no avih at start): %"
3396             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3397     if (sub)
3398       gst_buffer_unref (sub);
3399
3400     gst_buffer_unref (buf);
3401     return GST_FLOW_ERROR;
3402   }
3403 header_wrong_avih:
3404   {
3405     gst_buffer_unref (buf);
3406     return GST_FLOW_ERROR;
3407   }
3408 }
3409
3410 static void
3411 gst_avi_demux_add_date_tag (GstAviDemux * avi, gint y, gint m, gint d,
3412     gint h, gint min, gint s)
3413 {
3414   GDate *date;
3415   GstDateTime *dt;
3416
3417   date = g_date_new_dmy (d, m, y);
3418   if (!g_date_valid (date)) {
3419     /* bogus date */
3420     GST_WARNING_OBJECT (avi, "Refusing to add invalid date %d-%d-%d", y, m, d);
3421     g_date_free (date);
3422     return;
3423   }
3424
3425   dt = gst_date_time_new_local_time (y, m, d, h, min, s);
3426
3427   if (avi->globaltags == NULL)
3428     avi->globaltags = gst_tag_list_new_empty ();
3429
3430   gst_tag_list_add (avi->globaltags, GST_TAG_MERGE_REPLACE, GST_TAG_DATE, date,
3431       NULL);
3432   g_date_free (date);
3433   if (dt) {
3434     gst_tag_list_add (avi->globaltags, GST_TAG_MERGE_REPLACE, GST_TAG_DATE_TIME,
3435         dt, NULL);
3436     gst_date_time_unref (dt);
3437   }
3438 }
3439
3440 static void
3441 gst_avi_demux_parse_idit_nums_only (GstAviDemux * avi, gchar * data)
3442 {
3443   gint y, m, d;
3444   gint hr = 0, min = 0, sec = 0;
3445   gint ret;
3446
3447   GST_DEBUG ("data : '%s'", data);
3448
3449   ret = sscanf (data, "%d:%d:%d %d:%d:%d", &y, &m, &d, &hr, &min, &sec);
3450   if (ret < 3) {
3451     /* Attempt YYYY/MM/DD/ HH:MM variant (found in CASIO cameras) */
3452     ret = sscanf (data, "%04d/%02d/%02d/ %d:%d", &y, &m, &d, &hr, &min);
3453     if (ret < 3) {
3454       GST_WARNING_OBJECT (avi, "Failed to parse IDIT tag");
3455       return;
3456     }
3457   }
3458   gst_avi_demux_add_date_tag (avi, y, m, d, hr, min, sec);
3459 }
3460
3461 static gint
3462 get_month_num (gchar * data, guint size)
3463 {
3464   if (g_ascii_strncasecmp (data, "jan", 3) == 0) {
3465     return 1;
3466   } else if (g_ascii_strncasecmp (data, "feb", 3) == 0) {
3467     return 2;
3468   } else if (g_ascii_strncasecmp (data, "mar", 3) == 0) {
3469     return 3;
3470   } else if (g_ascii_strncasecmp (data, "apr", 3) == 0) {
3471     return 4;
3472   } else if (g_ascii_strncasecmp (data, "may", 3) == 0) {
3473     return 5;
3474   } else if (g_ascii_strncasecmp (data, "jun", 3) == 0) {
3475     return 6;
3476   } else if (g_ascii_strncasecmp (data, "jul", 3) == 0) {
3477     return 7;
3478   } else if (g_ascii_strncasecmp (data, "aug", 3) == 0) {
3479     return 8;
3480   } else if (g_ascii_strncasecmp (data, "sep", 3) == 0) {
3481     return 9;
3482   } else if (g_ascii_strncasecmp (data, "oct", 3) == 0) {
3483     return 10;
3484   } else if (g_ascii_strncasecmp (data, "nov", 3) == 0) {
3485     return 11;
3486   } else if (g_ascii_strncasecmp (data, "dec", 3) == 0) {
3487     return 12;
3488   }
3489
3490   return 0;
3491 }
3492
3493 static void
3494 gst_avi_demux_parse_idit_text (GstAviDemux * avi, gchar * data)
3495 {
3496   gint year, month, day;
3497   gint hour, min, sec;
3498   gint ret;
3499   gchar weekday[4];
3500   gchar monthstr[4];
3501
3502   ret = sscanf (data, "%3s %3s %d %d:%d:%d %d", weekday, monthstr, &day, &hour,
3503       &min, &sec, &year);
3504   if (ret != 7) {
3505     GST_WARNING_OBJECT (avi, "Failed to parse IDIT tag");
3506     return;
3507   }
3508   month = get_month_num (monthstr, strlen (monthstr));
3509   gst_avi_demux_add_date_tag (avi, year, month, day, hour, min, sec);
3510 }
3511
3512 static void
3513 gst_avi_demux_parse_idit (GstAviDemux * avi, GstBuffer * buf)
3514 {
3515   GstMapInfo map;
3516   gchar *ptr;
3517   gsize left;
3518   gchar *safedata = NULL;
3519
3520   gst_buffer_map (buf, &map, GST_MAP_READ);
3521   /*
3522    * According to:
3523    * http://www.eden-foundation.org/products/code/film_date_stamp/index.html
3524    *
3525    * This tag could be in one of the below formats
3526    * 2005:08:17 11:42:43
3527    * THU OCT 26 16:46:04 2006
3528    * Mon Mar  3 09:44:56 2008
3529    *
3530    * FIXME: Our date tag doesn't include hours
3531    */
3532
3533   /* skip eventual initial whitespace */
3534   ptr = (gchar *) map.data;
3535   left = map.size;
3536
3537   while (left > 0 && g_ascii_isspace (ptr[0])) {
3538     ptr++;
3539     left--;
3540   }
3541
3542   if (left == 0) {
3543     goto non_parsable;
3544   }
3545
3546   /* make a safe copy to add a \0 to the end of the string */
3547   safedata = g_strndup (ptr, left);
3548
3549   /* test if the first char is a alpha or a number */
3550   if (g_ascii_isdigit (ptr[0])) {
3551     gst_avi_demux_parse_idit_nums_only (avi, safedata);
3552     g_free (safedata);
3553     return;
3554   } else if (g_ascii_isalpha (ptr[0])) {
3555     gst_avi_demux_parse_idit_text (avi, safedata);
3556     g_free (safedata);
3557     return;
3558   }
3559
3560   g_free (safedata);
3561
3562 non_parsable:
3563   GST_WARNING_OBJECT (avi, "IDIT tag has no parsable info");
3564   gst_buffer_unmap (buf, &map);
3565 }
3566
3567 /*
3568  * Read full AVI headers.
3569  */
3570 static GstFlowReturn
3571 gst_avi_demux_stream_header_pull (GstAviDemux * avi)
3572 {
3573   GstFlowReturn res;
3574   GstBuffer *buf, *sub = NULL;
3575   guint32 tag;
3576   guint offset = 4;
3577   GstElement *element = GST_ELEMENT_CAST (avi);
3578   GstClockTime stamp;
3579   GstTagList *tags = NULL;
3580   guint8 fourcc[4];
3581
3582   stamp = gst_util_get_timestamp ();
3583
3584   /* the header consists of a 'hdrl' LIST tag */
3585   res = gst_riff_read_chunk (element, avi->sinkpad, &avi->offset, &tag, &buf);
3586   if (res != GST_FLOW_OK)
3587     goto pull_range_failed;
3588   else if (tag != GST_RIFF_TAG_LIST)
3589     goto no_list;
3590   else if (gst_buffer_get_size (buf) < 4)
3591     goto no_header;
3592
3593   GST_DEBUG_OBJECT (avi, "parsing headers");
3594
3595   /* Find the 'hdrl' LIST tag */
3596   gst_buffer_extract (buf, 0, fourcc, 4);
3597   while (GST_READ_UINT32_LE (fourcc) != GST_RIFF_LIST_hdrl) {
3598     GST_LOG_OBJECT (avi, "buffer contains %" GST_FOURCC_FORMAT,
3599         GST_FOURCC_ARGS (GST_READ_UINT32_LE (fourcc)));
3600
3601     /* Eat up */
3602     gst_buffer_unref (buf);
3603
3604     /* read new chunk */
3605     res = gst_riff_read_chunk (element, avi->sinkpad, &avi->offset, &tag, &buf);
3606     if (res != GST_FLOW_OK)
3607       goto pull_range_failed;
3608     else if (tag != GST_RIFF_TAG_LIST)
3609       goto no_list;
3610     else if (gst_buffer_get_size (buf) < 4)
3611       goto no_header;
3612     gst_buffer_extract (buf, 0, fourcc, 4);
3613   }
3614
3615   GST_DEBUG_OBJECT (avi, "hdrl LIST tag found");
3616
3617   gst_avi_demux_roundup_list (avi, &buf);
3618
3619   /* the hdrl starts with a 'avih' header */
3620   if (!gst_riff_parse_chunk (element, buf, &offset, &tag, &sub))
3621     goto no_avih;
3622   else if (tag != GST_RIFF_TAG_avih)
3623     goto no_avih;
3624   else if (!gst_avi_demux_parse_avih (avi, sub, &avi->avih))
3625     goto invalid_avih;
3626
3627   GST_DEBUG_OBJECT (avi, "AVI header ok, reading elements from header");
3628
3629   /* now, read the elements from the header until the end */
3630   while (gst_riff_parse_chunk (element, buf, &offset, &tag, &sub)) {
3631     GstMapInfo map;
3632
3633     /* sub can be NULL on empty tags */
3634     if (!sub)
3635       continue;
3636
3637     gst_buffer_map (sub, &map, GST_MAP_READ);
3638
3639     switch (tag) {
3640       case GST_RIFF_TAG_LIST:
3641         if (map.size < 4)
3642           goto next;
3643
3644         switch (GST_READ_UINT32_LE (map.data)) {
3645           case GST_RIFF_LIST_strl:
3646             if (!(gst_avi_demux_parse_stream (avi, sub))) {
3647               GST_ELEMENT_WARNING (avi, STREAM, DEMUX, (NULL),
3648                   ("failed to parse stream, ignoring"));
3649               sub = NULL;
3650             }
3651             sub = NULL;
3652             goto next;
3653           case GST_RIFF_LIST_odml:
3654             gst_avi_demux_parse_odml (avi, sub);
3655             sub = NULL;
3656             break;
3657           case GST_RIFF_LIST_INFO:
3658             gst_buffer_resize (sub, 4, -1);
3659             gst_riff_parse_info (element, sub, &tags);
3660             if (tags) {
3661               if (avi->globaltags) {
3662                 gst_tag_list_insert (avi->globaltags, tags,
3663                     GST_TAG_MERGE_REPLACE);
3664               } else {
3665                 avi->globaltags = tags;
3666               }
3667             }
3668             tags = NULL;
3669             break;
3670           default:
3671             GST_WARNING_OBJECT (avi,
3672                 "Unknown list %" GST_FOURCC_FORMAT " in AVI header",
3673                 GST_FOURCC_ARGS (GST_READ_UINT32_LE (map.data)));
3674             GST_MEMDUMP_OBJECT (avi, "Unknown list", map.data, map.size);
3675             /* fall-through */
3676           case GST_RIFF_TAG_JUNQ:
3677           case GST_RIFF_TAG_JUNK:
3678             goto next;
3679         }
3680         break;
3681       case GST_RIFF_IDIT:
3682         gst_avi_demux_parse_idit (avi, sub);
3683         goto next;
3684       default:
3685         GST_WARNING_OBJECT (avi,
3686             "Unknown tag %" GST_FOURCC_FORMAT " in AVI header at off %d",
3687             GST_FOURCC_ARGS (tag), offset);
3688         GST_MEMDUMP_OBJECT (avi, "Unknown tag", map.data, map.size);
3689         /* fall-through */
3690       case GST_RIFF_TAG_JUNQ:
3691       case GST_RIFF_TAG_JUNK:
3692       next:
3693         if (sub) {
3694           gst_buffer_unmap (sub, &map);
3695           gst_buffer_unref (sub);
3696         }
3697         sub = NULL;
3698         break;
3699     }
3700   }
3701   gst_buffer_unref (buf);
3702   GST_DEBUG ("elements parsed");
3703
3704   /* check parsed streams */
3705   if (avi->num_streams == 0)
3706     goto no_streams;
3707   else if (avi->num_streams != avi->avih->streams) {
3708     GST_WARNING_OBJECT (avi,
3709         "Stream header mentioned %d streams, but %d available",
3710         avi->avih->streams, avi->num_streams);
3711   }
3712
3713   GST_DEBUG_OBJECT (avi, "skipping junk between header and data, offset=%"
3714       G_GUINT64_FORMAT, avi->offset);
3715
3716   /* Now, find the data (i.e. skip all junk between header and data) */
3717   do {
3718     GstMapInfo map;
3719     guint size;
3720     guint32 tag, ltag;
3721
3722     res = gst_pad_pull_range (avi->sinkpad, avi->offset, 12, &buf);
3723     if (res != GST_FLOW_OK) {
3724       GST_DEBUG_OBJECT (avi, "pull_range failure while looking for tags");
3725       goto pull_range_failed;
3726     } else if (gst_buffer_get_size (buf) < 12) {
3727       GST_DEBUG_OBJECT (avi,
3728           "got %" G_GSIZE_FORMAT " bytes which is less than 12 bytes",
3729           gst_buffer_get_size (buf));
3730       gst_buffer_unref (buf);
3731       return GST_FLOW_ERROR;
3732     }
3733
3734     gst_buffer_map (buf, &map, GST_MAP_READ);
3735     tag = GST_READ_UINT32_LE (map.data);
3736     size = GST_READ_UINT32_LE (map.data + 4);
3737     ltag = GST_READ_UINT32_LE (map.data + 8);
3738
3739     GST_DEBUG ("tag %" GST_FOURCC_FORMAT ", size %u",
3740         GST_FOURCC_ARGS (tag), size);
3741     GST_MEMDUMP ("Tag content", map.data, map.size);
3742     gst_buffer_unmap (buf, &map);
3743     gst_buffer_unref (buf);
3744
3745     switch (tag) {
3746       case GST_RIFF_TAG_LIST:{
3747         switch (ltag) {
3748           case GST_RIFF_LIST_movi:
3749             GST_DEBUG_OBJECT (avi,
3750                 "Reached the 'movi' tag, we're done with skipping");
3751             goto skipping_done;
3752           case GST_RIFF_LIST_INFO:
3753             res =
3754                 gst_riff_read_chunk (element, avi->sinkpad, &avi->offset, &tag,
3755                 &buf);
3756             if (res != GST_FLOW_OK) {
3757               GST_DEBUG_OBJECT (avi, "couldn't read INFO chunk");
3758               goto pull_range_failed;
3759             }
3760             GST_DEBUG ("got size %" G_GSIZE_FORMAT, gst_buffer_get_size (buf));
3761             if (size < 4) {
3762               GST_DEBUG ("skipping INFO LIST prefix");
3763               avi->offset += (4 - GST_ROUND_UP_2 (size));
3764               gst_buffer_unref (buf);
3765               continue;
3766             }
3767
3768             sub = gst_buffer_copy_region (buf, GST_BUFFER_COPY_ALL, 4, -1);
3769             gst_riff_parse_info (element, sub, &tags);
3770             if (tags) {
3771               if (avi->globaltags) {
3772                 gst_tag_list_insert (avi->globaltags, tags,
3773                     GST_TAG_MERGE_REPLACE);
3774               } else {
3775                 avi->globaltags = tags;
3776               }
3777             }
3778             tags = NULL;
3779             if (sub) {
3780               gst_buffer_unref (sub);
3781               sub = NULL;
3782             }
3783             gst_buffer_unref (buf);
3784             /* gst_riff_read_chunk() has already advanced avi->offset */
3785             break;
3786           default:
3787             GST_WARNING_OBJECT (avi,
3788                 "Skipping unknown list tag %" GST_FOURCC_FORMAT,
3789                 GST_FOURCC_ARGS (ltag));
3790             avi->offset += 8 + GST_ROUND_UP_2 (size);
3791             break;
3792         }
3793       }
3794         break;
3795       default:
3796         GST_WARNING_OBJECT (avi, "Skipping unknown tag %" GST_FOURCC_FORMAT,
3797             GST_FOURCC_ARGS (tag));
3798         /* Fall-through */
3799       case GST_MAKE_FOURCC ('J', 'U', 'N', 'Q'):
3800       case GST_MAKE_FOURCC ('J', 'U', 'N', 'K'):
3801         /* Only get buffer for debugging if the memdump is needed  */
3802         if (gst_debug_category_get_threshold (GST_CAT_DEFAULT) >= 9) {
3803           res = gst_pad_pull_range (avi->sinkpad, avi->offset, size, &buf);
3804           if (res != GST_FLOW_OK) {
3805             GST_DEBUG_OBJECT (avi, "couldn't read INFO chunk");
3806             goto pull_range_failed;
3807           }
3808           gst_buffer_map (buf, &map, GST_MAP_READ);
3809           GST_MEMDUMP ("Junk", map.data, map.size);
3810           gst_buffer_unmap (buf, &map);
3811           gst_buffer_unref (buf);
3812         }
3813         avi->offset += 8 + GST_ROUND_UP_2 (size);
3814         break;
3815     }
3816   } while (1);
3817 skipping_done:
3818
3819   GST_DEBUG_OBJECT (avi, "skipping done ... (streams=%u, stream[0].indexes=%p)",
3820       avi->num_streams, avi->stream[0].indexes);
3821
3822   /* create or read stream index (for seeking) */
3823   if (avi->stream[0].indexes != NULL) {
3824     /* we read a super index already (gst_avi_demux_parse_superindex() ) */
3825     gst_avi_demux_read_subindexes_pull (avi);
3826   }
3827   if (!avi->have_index) {
3828     if (avi->avih->flags & GST_RIFF_AVIH_HASINDEX)
3829       gst_avi_demux_stream_index (avi);
3830
3831     /* still no index, scan */
3832     if (!avi->have_index) {
3833       gst_avi_demux_stream_scan (avi);
3834
3835       /* still no index.. this is a fatal error for now.
3836        * FIXME, we should switch to plain push mode without seeking
3837        * instead of failing. */
3838       if (!avi->have_index)
3839         goto no_index;
3840     }
3841   }
3842   /* use the indexes now to construct nice durations */
3843   gst_avi_demux_calculate_durations_from_index (avi);
3844
3845   gst_avi_demux_expose_streams (avi, FALSE);
3846
3847   /* do initial seek to the default segment values */
3848   gst_avi_demux_do_seek (avi, &avi->segment);
3849
3850   /* create initial NEWSEGMENT event */
3851   if (avi->seg_event)
3852     gst_event_unref (avi->seg_event);
3853   avi->seg_event = gst_event_new_segment (&avi->segment);
3854
3855   stamp = gst_util_get_timestamp () - stamp;
3856   GST_DEBUG_OBJECT (avi, "pulling header took %" GST_TIME_FORMAT,
3857       GST_TIME_ARGS (stamp));
3858
3859   /* at this point we know all the streams and we can signal the no more
3860    * pads signal */
3861   GST_DEBUG_OBJECT (avi, "signaling no more pads");
3862   gst_element_no_more_pads (GST_ELEMENT_CAST (avi));
3863
3864   return GST_FLOW_OK;
3865
3866   /* ERRORS */
3867 no_list:
3868   {
3869     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3870         ("Invalid AVI header (no LIST at start): %"
3871             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3872     gst_buffer_unref (buf);
3873     return GST_FLOW_ERROR;
3874   }
3875 no_header:
3876   {
3877     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3878         ("Invalid AVI header (no hdrl at start): %"
3879             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3880     gst_buffer_unref (buf);
3881     return GST_FLOW_ERROR;
3882   }
3883 no_avih:
3884   {
3885     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3886         ("Invalid AVI header (no avih at start): %"
3887             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
3888     if (sub)
3889       gst_buffer_unref (sub);
3890     gst_buffer_unref (buf);
3891     return GST_FLOW_ERROR;
3892   }
3893 invalid_avih:
3894   {
3895     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3896         ("Invalid AVI header (cannot parse avih at start)"));
3897     gst_buffer_unref (buf);
3898     return GST_FLOW_ERROR;
3899   }
3900 no_streams:
3901   {
3902     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("No streams found"));
3903     return GST_FLOW_ERROR;
3904   }
3905 no_index:
3906   {
3907     GST_WARNING ("file without or too big index");
3908     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3909         ("Could not get/create index"));
3910     return GST_FLOW_ERROR;
3911   }
3912 pull_range_failed:
3913   {
3914     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL),
3915         ("pull_range flow reading header: %s", gst_flow_get_name (res)));
3916     return GST_FLOW_ERROR;
3917   }
3918 }
3919
3920 /* move a stream to @index */
3921 static void
3922 gst_avi_demux_move_stream (GstAviDemux * avi, GstAviStream * stream,
3923     GstSegment * segment, guint index)
3924 {
3925   GST_DEBUG_OBJECT (avi, "Move stream %d to %u", stream->num, index);
3926
3927   if (segment->rate < 0.0) {
3928     guint next_key;
3929     /* Because we don't know the frame order we need to push from the prev keyframe
3930      * to the next keyframe. If there is a smart decoder downstream he will notice
3931      * that there are too many encoded frames send and return EOS when there
3932      * are enough decoded frames to fill the segment. */
3933     next_key = gst_avi_demux_index_next (avi, stream, index, TRUE);
3934
3935     /* FIXME, we go back to 0, we should look at segment.start. We will however
3936      * stop earlier when the see the timestamp < segment.start */
3937     stream->start_entry = 0;
3938     stream->step_entry = index;
3939     stream->current_entry = index;
3940     stream->stop_entry = next_key;
3941
3942     GST_DEBUG_OBJECT (avi, "reverse seek: start %u, step %u, stop %u",
3943         stream->start_entry, stream->step_entry, stream->stop_entry);
3944   } else {
3945     stream->start_entry = index;
3946     stream->step_entry = index;
3947     stream->stop_entry = gst_avi_demux_index_last (avi, stream);
3948   }
3949   if (stream->current_entry != index) {
3950     GST_DEBUG_OBJECT (avi, "Move DISCONT from %u to %u",
3951         stream->current_entry, index);
3952     stream->current_entry = index;
3953     stream->discont = TRUE;
3954   }
3955
3956   /* update the buffer info */
3957   gst_avi_demux_get_buffer_info (avi, stream, index,
3958       &stream->current_timestamp, &stream->current_ts_end,
3959       &stream->current_offset, &stream->current_offset_end);
3960
3961   GST_DEBUG_OBJECT (avi, "Moved to %u, ts %" GST_TIME_FORMAT
3962       ", ts_end %" GST_TIME_FORMAT ", off %" G_GUINT64_FORMAT
3963       ", off_end %" G_GUINT64_FORMAT, index,
3964       GST_TIME_ARGS (stream->current_timestamp),
3965       GST_TIME_ARGS (stream->current_ts_end), stream->current_offset,
3966       stream->current_offset_end);
3967
3968   GST_DEBUG_OBJECT (avi, "Seeking to offset %" G_GUINT64_FORMAT,
3969       stream->index[index].offset);
3970 }
3971
3972 /*
3973  * Do the actual seeking.
3974  */
3975 static gboolean
3976 gst_avi_demux_do_seek (GstAviDemux * avi, GstSegment * segment)
3977 {
3978   GstClockTime seek_time;
3979   gboolean keyframe;
3980   guint i, index;
3981   GstAviStream *stream;
3982
3983   seek_time = segment->position;
3984   keyframe = ! !(segment->flags & GST_SEEK_FLAG_KEY_UNIT);
3985
3986   GST_DEBUG_OBJECT (avi, "seek to: %" GST_TIME_FORMAT
3987       " keyframe seeking:%d", GST_TIME_ARGS (seek_time), keyframe);
3988
3989   /* FIXME, this code assumes the main stream with keyframes is stream 0,
3990    * which is mostly correct... */
3991   stream = &avi->stream[avi->main_stream];
3992
3993   /* get the entry index for the requested position */
3994   index = gst_avi_demux_index_for_time (avi, stream, seek_time);
3995   GST_DEBUG_OBJECT (avi, "Got entry %u", index);
3996
3997   /* check if we are already on a keyframe */
3998   if (!ENTRY_IS_KEYFRAME (&stream->index[index])) {
3999     GST_DEBUG_OBJECT (avi, "not keyframe, searching back");
4000     /* now go to the previous keyframe, this is where we should start
4001      * decoding from. */
4002     index = gst_avi_demux_index_prev (avi, stream, index, TRUE);
4003     GST_DEBUG_OBJECT (avi, "previous keyframe at %u", index);
4004   }
4005
4006   /* move the main stream to this position */
4007   gst_avi_demux_move_stream (avi, stream, segment, index);
4008
4009   if (keyframe) {
4010     /* when seeking to a keyframe, we update the result seek time
4011      * to the time of the keyframe. */
4012     seek_time = stream->current_timestamp;
4013     GST_DEBUG_OBJECT (avi, "keyframe adjusted to %" GST_TIME_FORMAT,
4014         GST_TIME_ARGS (seek_time));
4015   }
4016
4017   /* the seek time is also the position and stream time when going
4018    * forwards */
4019   segment->position = seek_time;
4020   if (segment->rate > 0.0)
4021     segment->time = seek_time;
4022
4023   /* now set DISCONT and align the other streams */
4024   for (i = 0; i < avi->num_streams; i++) {
4025     GstAviStream *ostream;
4026
4027     ostream = &avi->stream[i];
4028     if ((ostream == stream) || (ostream->index == NULL))
4029       continue;
4030
4031     /* get the entry index for the requested position */
4032     index = gst_avi_demux_index_for_time (avi, ostream, seek_time);
4033
4034     /* move to previous keyframe */
4035     if (!ENTRY_IS_KEYFRAME (&ostream->index[index]))
4036       index = gst_avi_demux_index_prev (avi, ostream, index, TRUE);
4037
4038     gst_avi_demux_move_stream (avi, ostream, segment, index);
4039   }
4040   GST_DEBUG_OBJECT (avi, "done seek to: %" GST_TIME_FORMAT,
4041       GST_TIME_ARGS (seek_time));
4042
4043   return TRUE;
4044 }
4045
4046 /*
4047  * Handle seek event in pull mode.
4048  */
4049 static gboolean
4050 gst_avi_demux_handle_seek (GstAviDemux * avi, GstPad * pad, GstEvent * event)
4051 {
4052   gdouble rate;
4053   GstFormat format;
4054   GstSeekFlags flags;
4055   GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
4056   gint64 cur, stop;
4057   gboolean flush;
4058   gboolean update;
4059   GstSegment seeksegment = { 0, };
4060   gint i;
4061
4062   if (event) {
4063     GST_DEBUG_OBJECT (avi, "doing seek with event");
4064
4065     gst_event_parse_seek (event, &rate, &format, &flags,
4066         &cur_type, &cur, &stop_type, &stop);
4067
4068     /* we have to have a format as the segment format. Try to convert
4069      * if not. */
4070     if (format != GST_FORMAT_TIME) {
4071       gboolean res = TRUE;
4072
4073       if (cur_type != GST_SEEK_TYPE_NONE)
4074         res = gst_pad_query_convert (pad, format, cur, GST_FORMAT_TIME, &cur);
4075       if (res && stop_type != GST_SEEK_TYPE_NONE)
4076         res = gst_pad_query_convert (pad, format, stop, GST_FORMAT_TIME, &stop);
4077       if (!res)
4078         goto no_format;
4079
4080       format = GST_FORMAT_TIME;
4081     }
4082     GST_DEBUG_OBJECT (avi,
4083         "seek requested: rate %g cur %" GST_TIME_FORMAT " stop %"
4084         GST_TIME_FORMAT, rate, GST_TIME_ARGS (cur), GST_TIME_ARGS (stop));
4085     /* FIXME: can we do anything with rate!=1.0 */
4086   } else {
4087     GST_DEBUG_OBJECT (avi, "doing seek without event");
4088     flags = 0;
4089     rate = 1.0;
4090   }
4091
4092   /* save flush flag */
4093   flush = flags & GST_SEEK_FLAG_FLUSH;
4094
4095   if (flush) {
4096     GstEvent *fevent = gst_event_new_flush_start ();
4097
4098     /* for a flushing seek, we send a flush_start on all pads. This will
4099      * eventually stop streaming with a WRONG_STATE. We can thus eventually
4100      * take the STREAM_LOCK. */
4101     GST_DEBUG_OBJECT (avi, "sending flush start");
4102     gst_avi_demux_push_event (avi, gst_event_ref (fevent));
4103     gst_pad_push_event (avi->sinkpad, fevent);
4104   } else {
4105     /* a non-flushing seek, we PAUSE the task so that we can take the
4106      * STREAM_LOCK */
4107     GST_DEBUG_OBJECT (avi, "non flushing seek, pausing task");
4108     gst_pad_pause_task (avi->sinkpad);
4109   }
4110
4111   /* wait for streaming to stop */
4112   GST_DEBUG_OBJECT (avi, "wait for streaming to stop");
4113   GST_PAD_STREAM_LOCK (avi->sinkpad);
4114
4115   /* copy segment, we need this because we still need the old
4116    * segment when we close the current segment. */
4117   memcpy (&seeksegment, &avi->segment, sizeof (GstSegment));
4118
4119   if (event) {
4120     GST_DEBUG_OBJECT (avi, "configuring seek");
4121     gst_segment_do_seek (&seeksegment, rate, format, flags,
4122         cur_type, cur, stop_type, stop, &update);
4123   }
4124   /* do the seek, seeksegment.position contains the new position, this
4125    * actually never fails. */
4126   gst_avi_demux_do_seek (avi, &seeksegment);
4127
4128   if (flush) {
4129     GstEvent *fevent = gst_event_new_flush_stop (TRUE);
4130
4131     GST_DEBUG_OBJECT (avi, "sending flush stop");
4132     gst_avi_demux_push_event (avi, gst_event_ref (fevent));
4133     gst_pad_push_event (avi->sinkpad, fevent);
4134   }
4135
4136   /* now update the real segment info */
4137   memcpy (&avi->segment, &seeksegment, sizeof (GstSegment));
4138
4139   /* post the SEGMENT_START message when we do segmented playback */
4140   if (avi->segment.flags & GST_SEEK_FLAG_SEGMENT) {
4141     gst_element_post_message (GST_ELEMENT_CAST (avi),
4142         gst_message_new_segment_start (GST_OBJECT_CAST (avi),
4143             avi->segment.format, avi->segment.position));
4144   }
4145
4146   /* queue the segment event for the streaming thread. */
4147   if (avi->seg_event)
4148     gst_event_unref (avi->seg_event);
4149   avi->seg_event = gst_event_new_segment (&avi->segment);
4150
4151   if (!avi->streaming) {
4152     gst_pad_start_task (avi->sinkpad, (GstTaskFunction) gst_avi_demux_loop,
4153         avi->sinkpad);
4154   }
4155   /* reset the last flow and mark discont, seek is always DISCONT */
4156   for (i = 0; i < avi->num_streams; i++) {
4157     GST_DEBUG_OBJECT (avi, "marking DISCONT");
4158     avi->stream[i].last_flow = GST_FLOW_OK;
4159     avi->stream[i].discont = TRUE;
4160   }
4161   GST_PAD_STREAM_UNLOCK (avi->sinkpad);
4162
4163   return TRUE;
4164
4165   /* ERRORS */
4166 no_format:
4167   {
4168     GST_DEBUG_OBJECT (avi, "unsupported format given, seek aborted.");
4169     return FALSE;
4170   }
4171 }
4172
4173 /*
4174  * Handle seek event in push mode.
4175  */
4176 static gboolean
4177 avi_demux_handle_seek_push (GstAviDemux * avi, GstPad * pad, GstEvent * event)
4178 {
4179   gdouble rate;
4180   GstFormat format;
4181   GstSeekFlags flags;
4182   GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
4183   gint64 cur, stop;
4184   gboolean keyframe;
4185   GstAviStream *stream;
4186   guint index;
4187   guint n, str_num;
4188   guint64 min_offset;
4189   GstSegment seeksegment;
4190   gboolean update;
4191
4192   /* check we have the index */
4193   if (!avi->have_index) {
4194     GST_DEBUG_OBJECT (avi, "no seek index built, seek aborted.");
4195     return FALSE;
4196   } else {
4197     GST_DEBUG_OBJECT (avi, "doing push-based seek with event");
4198   }
4199
4200   gst_event_parse_seek (event, &rate, &format, &flags,
4201       &cur_type, &cur, &stop_type, &stop);
4202
4203   if (format != GST_FORMAT_TIME) {
4204     gboolean res = TRUE;
4205
4206     if (cur_type != GST_SEEK_TYPE_NONE)
4207       res = gst_pad_query_convert (pad, format, cur, GST_FORMAT_TIME, &cur);
4208     if (res && stop_type != GST_SEEK_TYPE_NONE)
4209       res = gst_pad_query_convert (pad, format, stop, GST_FORMAT_TIME, &stop);
4210     if (!res) {
4211       GST_DEBUG_OBJECT (avi, "unsupported format given, seek aborted.");
4212       return FALSE;
4213     }
4214
4215     format = GST_FORMAT_TIME;
4216   }
4217
4218   /* let gst_segment handle any tricky stuff */
4219   GST_DEBUG_OBJECT (avi, "configuring seek");
4220   memcpy (&seeksegment, &avi->segment, sizeof (GstSegment));
4221   gst_segment_do_seek (&seeksegment, rate, format, flags,
4222       cur_type, cur, stop_type, stop, &update);
4223
4224   keyframe = ! !(flags & GST_SEEK_FLAG_KEY_UNIT);
4225   cur = seeksegment.position;
4226
4227   GST_DEBUG_OBJECT (avi,
4228       "Seek requested: ts %" GST_TIME_FORMAT " stop %" GST_TIME_FORMAT
4229       ", kf %u, rate %lf", GST_TIME_ARGS (cur), GST_TIME_ARGS (stop), keyframe,
4230       rate);
4231
4232   if (rate < 0) {
4233     GST_DEBUG_OBJECT (avi, "negative rate seek not supported in push mode");
4234     return FALSE;
4235   }
4236
4237   /* FIXME, this code assumes the main stream with keyframes is stream 0,
4238    * which is mostly correct... */
4239   str_num = avi->main_stream;
4240   stream = &avi->stream[str_num];
4241
4242   /* get the entry index for the requested position */
4243   index = gst_avi_demux_index_for_time (avi, stream, cur);
4244   GST_DEBUG_OBJECT (avi, "str %u: Found entry %u for %" GST_TIME_FORMAT,
4245       str_num, index, GST_TIME_ARGS (cur));
4246
4247   /* check if we are already on a keyframe */
4248   if (!ENTRY_IS_KEYFRAME (&stream->index[index])) {
4249     GST_DEBUG_OBJECT (avi, "Entry is not a keyframe - searching back");
4250     /* now go to the previous keyframe, this is where we should start
4251      * decoding from. */
4252     index = gst_avi_demux_index_prev (avi, stream, index, TRUE);
4253     GST_DEBUG_OBJECT (avi, "Found previous keyframe at %u", index);
4254   }
4255
4256   gst_avi_demux_get_buffer_info (avi, stream, index,
4257       &stream->current_timestamp, &stream->current_ts_end,
4258       &stream->current_offset, &stream->current_offset_end);
4259
4260   /* re-use cur to be the timestamp of the seek as it _will_ be */
4261   cur = stream->current_timestamp;
4262
4263   min_offset = stream->index[index].offset;
4264   avi->seek_kf_offset = min_offset - 8;
4265
4266   GST_DEBUG_OBJECT (avi,
4267       "Seek to: ts %" GST_TIME_FORMAT " (on str %u, idx %u, offset %"
4268       G_GUINT64_FORMAT ")", GST_TIME_ARGS (stream->current_timestamp), str_num,
4269       index, min_offset);
4270
4271   for (n = 0; n < avi->num_streams; n++) {
4272     GstAviStream *str = &avi->stream[n];
4273     guint idx;
4274
4275     if (n == avi->main_stream)
4276       continue;
4277
4278     /* get the entry index for the requested position */
4279     idx = gst_avi_demux_index_for_time (avi, str, cur);
4280     GST_DEBUG_OBJECT (avi, "str %u: Found entry %u for %" GST_TIME_FORMAT, n,
4281         idx, GST_TIME_ARGS (cur));
4282
4283     /* check if we are already on a keyframe */
4284     if (!ENTRY_IS_KEYFRAME (&str->index[idx])) {
4285       GST_DEBUG_OBJECT (avi, "Entry is not a keyframe - searching back");
4286       /* now go to the previous keyframe, this is where we should start
4287        * decoding from. */
4288       idx = gst_avi_demux_index_prev (avi, str, idx, TRUE);
4289       GST_DEBUG_OBJECT (avi, "Found previous keyframe at %u", idx);
4290     }
4291
4292     gst_avi_demux_get_buffer_info (avi, str, idx,
4293         &str->current_timestamp, &str->current_ts_end,
4294         &str->current_offset, &str->current_offset_end);
4295
4296     if (str->index[idx].offset < min_offset) {
4297       min_offset = str->index[idx].offset;
4298       GST_DEBUG_OBJECT (avi,
4299           "Found an earlier offset at %" G_GUINT64_FORMAT ", str %u",
4300           min_offset, n);
4301       str_num = n;
4302       stream = str;
4303       index = idx;
4304     }
4305   }
4306
4307   GST_DEBUG_OBJECT (avi,
4308       "Seek performed: str %u, offset %" G_GUINT64_FORMAT ", idx %u, ts %"
4309       GST_TIME_FORMAT ", ts_end %" GST_TIME_FORMAT ", off %" G_GUINT64_FORMAT
4310       ", off_end %" G_GUINT64_FORMAT, str_num, min_offset, index,
4311       GST_TIME_ARGS (stream->current_timestamp),
4312       GST_TIME_ARGS (stream->current_ts_end), stream->current_offset,
4313       stream->current_offset_end);
4314
4315   /* index data refers to data, not chunk header (for pull mode convenience) */
4316   min_offset -= 8;
4317   GST_DEBUG_OBJECT (avi, "seeking to chunk at offset %" G_GUINT64_FORMAT,
4318       min_offset);
4319
4320   if (!perform_seek_to_offset (avi, min_offset)) {
4321     GST_DEBUG_OBJECT (avi, "seek event failed!");
4322     return FALSE;
4323   }
4324
4325   return TRUE;
4326 }
4327
4328 /*
4329  * Handle whether we can perform the seek event or if we have to let the chain
4330  * function handle seeks to build the seek indexes first.
4331  */
4332 static gboolean
4333 gst_avi_demux_handle_seek_push (GstAviDemux * avi, GstPad * pad,
4334     GstEvent * event)
4335 {
4336   /* check for having parsed index already */
4337   if (!avi->have_index) {
4338     guint64 offset = 0;
4339     gboolean building_index;
4340
4341     GST_OBJECT_LOCK (avi);
4342     /* handle the seek event in the chain function */
4343     avi->state = GST_AVI_DEMUX_SEEK;
4344
4345     /* copy the event */
4346     if (avi->seek_event)
4347       gst_event_unref (avi->seek_event);
4348     avi->seek_event = gst_event_ref (event);
4349
4350     /* set the building_index flag so that only one thread can setup the
4351      * structures for index seeking. */
4352     building_index = avi->building_index;
4353     if (!building_index) {
4354       avi->building_index = TRUE;
4355       if (avi->stream[0].indexes) {
4356         avi->odml_stream = 0;
4357         avi->odml_subidxs = avi->stream[avi->odml_stream].indexes;
4358         offset = avi->odml_subidxs[0];
4359       } else {
4360         offset = avi->idx1_offset;
4361       }
4362     }
4363     GST_OBJECT_UNLOCK (avi);
4364
4365     if (!building_index) {
4366       /* seek to the first subindex or legacy index */
4367       GST_INFO_OBJECT (avi,
4368           "Seeking to legacy index/first subindex at %" G_GUINT64_FORMAT,
4369           offset);
4370       return perform_seek_to_offset (avi, offset);
4371     }
4372
4373     /* FIXME: we have to always return true so that we don't block the seek
4374      * thread.
4375      * Note: maybe it is OK to return true if we're still building the index */
4376     return TRUE;
4377   }
4378
4379   return avi_demux_handle_seek_push (avi, pad, event);
4380 }
4381
4382 /*
4383  * Helper for gst_avi_demux_invert()
4384  */
4385 static inline void
4386 swap_line (guint8 * d1, guint8 * d2, guint8 * tmp, gint bytes)
4387 {
4388   memcpy (tmp, d1, bytes);
4389   memcpy (d1, d2, bytes);
4390   memcpy (d2, tmp, bytes);
4391 }
4392
4393
4394 #define gst_avi_demux_is_uncompressed(fourcc)           \
4395   (fourcc &&                                            \
4396     (fourcc == GST_RIFF_DIB ||                          \
4397      fourcc == GST_RIFF_rgb ||                          \
4398      fourcc == GST_RIFF_RGB || fourcc == GST_RIFF_RAW))
4399
4400 /*
4401  * Invert DIB buffers... Takes existing buffer and
4402  * returns either the buffer or a new one (with old
4403  * one dereferenced).
4404  * FIXME: can't we preallocate tmp? and remember stride, bpp?
4405  */
4406 static GstBuffer *
4407 gst_avi_demux_invert (GstAviStream * stream, GstBuffer * buf)
4408 {
4409   GstStructure *s;
4410   gint y, w, h;
4411   gint bpp, stride;
4412   guint8 *tmp = NULL;
4413   GstMapInfo map;
4414   GstCaps *caps;
4415
4416   if (stream->strh->type != GST_RIFF_FCC_vids)
4417     return buf;
4418
4419   if (!gst_avi_demux_is_uncompressed (stream->strh->fcc_handler)) {
4420     return buf;                 /* Ignore non DIB buffers */
4421   }
4422
4423   caps = gst_pad_get_current_caps (stream->pad);
4424   s = gst_caps_get_structure (caps, 0);
4425   gst_caps_unref (caps);
4426
4427   if (!gst_structure_get_int (s, "bpp", &bpp)) {
4428     GST_WARNING ("Failed to retrieve depth from caps");
4429     return buf;
4430   }
4431
4432   if (stream->strf.vids == NULL) {
4433     GST_WARNING ("Failed to retrieve vids for stream");
4434     return buf;
4435   }
4436
4437   h = stream->strf.vids->height;
4438   w = stream->strf.vids->width;
4439   stride = GST_ROUND_UP_4 (w * (bpp / 8));
4440
4441   buf = gst_buffer_make_writable (buf);
4442
4443   gst_buffer_map (buf, &map, GST_MAP_READWRITE);
4444   if (map.size < (stride * h)) {
4445     GST_WARNING ("Buffer is smaller than reported Width x Height x Depth");
4446     gst_buffer_unmap (buf, &map);
4447     return buf;
4448   }
4449
4450   tmp = g_malloc (stride);
4451
4452   for (y = 0; y < h / 2; y++) {
4453     swap_line (map.data + stride * y, map.data + stride * (h - 1 - y), tmp,
4454         stride);
4455   }
4456
4457   g_free (tmp);
4458
4459   gst_buffer_unmap (buf, &map);
4460
4461   return buf;
4462 }
4463
4464 #if 0
4465 static void
4466 gst_avi_demux_add_assoc (GstAviDemux * avi, GstAviStream * stream,
4467     GstClockTime timestamp, guint64 offset, gboolean keyframe)
4468 {
4469   /* do not add indefinitely for open-ended streaming */
4470   if (G_UNLIKELY (avi->element_index && avi->seekable)) {
4471     GST_LOG_OBJECT (avi, "adding association %" GST_TIME_FORMAT "-> %"
4472         G_GUINT64_FORMAT, GST_TIME_ARGS (timestamp), offset);
4473     gst_index_add_association (avi->element_index, avi->index_id,
4474         keyframe ? GST_ASSOCIATION_FLAG_KEY_UNIT :
4475         GST_ASSOCIATION_FLAG_DELTA_UNIT, GST_FORMAT_TIME, timestamp,
4476         GST_FORMAT_BYTES, offset, NULL);
4477     /* current_entry is DEFAULT (frame #) */
4478     gst_index_add_association (avi->element_index, stream->index_id,
4479         keyframe ? GST_ASSOCIATION_FLAG_KEY_UNIT :
4480         GST_ASSOCIATION_FLAG_DELTA_UNIT, GST_FORMAT_TIME, timestamp,
4481         GST_FORMAT_BYTES, offset, GST_FORMAT_DEFAULT, stream->current_entry,
4482         NULL);
4483   }
4484 }
4485 #endif
4486
4487 /*
4488  * Returns the aggregated GstFlowReturn.
4489  */
4490 static GstFlowReturn
4491 gst_avi_demux_combine_flows (GstAviDemux * avi, GstAviStream * stream,
4492     GstFlowReturn ret)
4493 {
4494   guint i;
4495   gboolean unexpected = FALSE, not_linked = TRUE;
4496
4497   /* store the value */
4498   stream->last_flow = ret;
4499
4500   /* any other error that is not-linked or eos can be returned right away */
4501   if (G_LIKELY (ret != GST_FLOW_EOS && ret != GST_FLOW_NOT_LINKED))
4502     goto done;
4503
4504   /* only return NOT_LINKED if all other pads returned NOT_LINKED */
4505   for (i = 0; i < avi->num_streams; i++) {
4506     GstAviStream *ostream = &avi->stream[i];
4507
4508     ret = ostream->last_flow;
4509     /* no unexpected or unlinked, return */
4510     if (G_LIKELY (ret != GST_FLOW_EOS && ret != GST_FLOW_NOT_LINKED))
4511       goto done;
4512
4513     /* we check to see if we have at least 1 unexpected or all unlinked */
4514     unexpected |= (ret == GST_FLOW_EOS);
4515     not_linked &= (ret == GST_FLOW_NOT_LINKED);
4516   }
4517   /* when we get here, we all have unlinked or unexpected */
4518   if (not_linked)
4519     ret = GST_FLOW_NOT_LINKED;
4520   else if (unexpected)
4521     ret = GST_FLOW_EOS;
4522 done:
4523   GST_LOG_OBJECT (avi, "combined %s to return %s",
4524       gst_flow_get_name (stream->last_flow), gst_flow_get_name (ret));
4525   return ret;
4526 }
4527
4528 /* move @stream to the next position in its index */
4529 static GstFlowReturn
4530 gst_avi_demux_advance (GstAviDemux * avi, GstAviStream * stream,
4531     GstFlowReturn ret)
4532 {
4533   guint old_entry, new_entry;
4534
4535   old_entry = stream->current_entry;
4536   /* move forwards */
4537   new_entry = old_entry + 1;
4538
4539   /* see if we reached the end */
4540   if (new_entry >= stream->stop_entry) {
4541     if (avi->segment.rate < 0.0) {
4542       if (stream->step_entry == stream->start_entry) {
4543         /* we stepped all the way to the start, eos */
4544         GST_DEBUG_OBJECT (avi, "reverse reached start %u", stream->start_entry);
4545         goto eos;
4546       }
4547       /* backwards, stop becomes step, find a new step */
4548       stream->stop_entry = stream->step_entry;
4549       stream->step_entry = gst_avi_demux_index_prev (avi, stream,
4550           stream->stop_entry, TRUE);
4551
4552       GST_DEBUG_OBJECT (avi,
4553           "reverse playback jump: start %u, step %u, stop %u",
4554           stream->start_entry, stream->step_entry, stream->stop_entry);
4555
4556       /* and start from the previous keyframe now */
4557       new_entry = stream->step_entry;
4558     } else {
4559       /* EOS */
4560       GST_DEBUG_OBJECT (avi, "forward reached stop %u", stream->stop_entry);
4561       goto eos;
4562     }
4563   }
4564
4565   if (new_entry != old_entry) {
4566     stream->current_entry = new_entry;
4567     stream->current_total = stream->index[new_entry].total;
4568
4569     if (new_entry == old_entry + 1) {
4570       GST_DEBUG_OBJECT (avi, "moved forwards from %u to %u",
4571           old_entry, new_entry);
4572       /* we simply moved one step forwards, reuse current info */
4573       stream->current_timestamp = stream->current_ts_end;
4574       stream->current_offset = stream->current_offset_end;
4575       gst_avi_demux_get_buffer_info (avi, stream, new_entry,
4576           NULL, &stream->current_ts_end, NULL, &stream->current_offset_end);
4577     } else {
4578       /* we moved DISCONT, full update */
4579       gst_avi_demux_get_buffer_info (avi, stream, new_entry,
4580           &stream->current_timestamp, &stream->current_ts_end,
4581           &stream->current_offset, &stream->current_offset_end);
4582       /* and MARK discont for this stream */
4583       stream->last_flow = GST_FLOW_OK;
4584       stream->discont = TRUE;
4585       GST_DEBUG_OBJECT (avi, "Moved from %u to %u, ts %" GST_TIME_FORMAT
4586           ", ts_end %" GST_TIME_FORMAT ", off %" G_GUINT64_FORMAT
4587           ", off_end %" G_GUINT64_FORMAT, old_entry, new_entry,
4588           GST_TIME_ARGS (stream->current_timestamp),
4589           GST_TIME_ARGS (stream->current_ts_end), stream->current_offset,
4590           stream->current_offset_end);
4591     }
4592   }
4593   return ret;
4594
4595   /* ERROR */
4596 eos:
4597   {
4598     GST_DEBUG_OBJECT (avi, "we are EOS");
4599     /* setting current_timestamp to -1 marks EOS */
4600     stream->current_timestamp = -1;
4601     return GST_FLOW_EOS;
4602   }
4603 }
4604
4605 /* find the stream with the lowest current position when going forwards or with
4606  * the highest position when going backwards, this is the stream
4607  * we should push from next */
4608 static gint
4609 gst_avi_demux_find_next (GstAviDemux * avi, gfloat rate)
4610 {
4611   guint64 min_time, max_time;
4612   guint stream_num, i;
4613
4614   max_time = 0;
4615   min_time = G_MAXUINT64;
4616   stream_num = -1;
4617
4618   for (i = 0; i < avi->num_streams; i++) {
4619     guint64 position;
4620     GstAviStream *stream;
4621
4622     stream = &avi->stream[i];
4623
4624     /* ignore streams that finished */
4625     if (stream->last_flow == GST_FLOW_EOS)
4626       continue;
4627
4628     position = stream->current_timestamp;
4629
4630     /* position of -1 is EOS */
4631     if (position != -1) {
4632       if (rate > 0.0 && position < min_time) {
4633         min_time = position;
4634         stream_num = i;
4635       } else if (rate < 0.0 && position >= max_time) {
4636         max_time = position;
4637         stream_num = i;
4638       }
4639     }
4640   }
4641   return stream_num;
4642 }
4643
4644 static GstFlowReturn
4645 gst_avi_demux_loop_data (GstAviDemux * avi)
4646 {
4647   GstFlowReturn ret = GST_FLOW_OK;
4648   guint stream_num;
4649   GstAviStream *stream;
4650   gboolean processed = FALSE;
4651   GstBuffer *buf;
4652   guint64 offset, size;
4653   GstClockTime timestamp, duration;
4654   guint64 out_offset, out_offset_end;
4655   gboolean keyframe;
4656   GstAviIndexEntry *entry;
4657
4658   do {
4659     stream_num = gst_avi_demux_find_next (avi, avi->segment.rate);
4660
4661     /* all are EOS */
4662     if (G_UNLIKELY (stream_num == -1)) {
4663       GST_DEBUG_OBJECT (avi, "all streams are EOS");
4664       goto eos;
4665     }
4666
4667     /* we have the stream now */
4668     stream = &avi->stream[stream_num];
4669
4670     /* skip streams without pads */
4671     if (!stream->pad) {
4672       GST_DEBUG_OBJECT (avi, "skipping entry from stream %d without pad",
4673           stream_num);
4674       goto next;
4675     }
4676
4677     /* get the timing info for the entry */
4678     timestamp = stream->current_timestamp;
4679     duration = stream->current_ts_end - timestamp;
4680     out_offset = stream->current_offset;
4681     out_offset_end = stream->current_offset_end;
4682
4683     /* get the entry data info */
4684     entry = &stream->index[stream->current_entry];
4685     offset = entry->offset;
4686     size = entry->size;
4687     keyframe = ENTRY_IS_KEYFRAME (entry);
4688
4689     /* skip empty entries */
4690     if (size == 0) {
4691       GST_DEBUG_OBJECT (avi, "Skipping entry %u (%" G_GUINT64_FORMAT ", %p)",
4692           stream->current_entry, size, stream->pad);
4693       goto next;
4694     }
4695
4696     if (avi->segment.rate > 0.0) {
4697       /* only check this for fowards playback for now */
4698       if (keyframe && GST_CLOCK_TIME_IS_VALID (avi->segment.stop)
4699           && (timestamp > avi->segment.stop)) {
4700         goto eos_stop;
4701       }
4702     }
4703
4704     GST_LOG ("reading buffer (size=%" G_GUINT64_FORMAT "), stream %d, pos %"
4705         G_GUINT64_FORMAT " (0x%" G_GINT64_MODIFIER "x), kf %d", size,
4706         stream_num, offset, offset, keyframe);
4707
4708     /* FIXME, check large chunks and cut them up */
4709
4710     /* pull in the data */
4711     ret = gst_pad_pull_range (avi->sinkpad, offset, size, &buf);
4712     if (ret != GST_FLOW_OK)
4713       goto pull_failed;
4714
4715     /* check for short buffers, this is EOS as well */
4716     if (gst_buffer_get_size (buf) < size)
4717       goto short_buffer;
4718
4719     /* invert the picture if needed */
4720     buf = gst_avi_demux_invert (stream, buf);
4721
4722     /* mark non-keyframes */
4723     if (keyframe)
4724       GST_BUFFER_FLAG_UNSET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
4725     else
4726       GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
4727
4728     GST_BUFFER_TIMESTAMP (buf) = timestamp;
4729     GST_BUFFER_DURATION (buf) = duration;
4730     GST_BUFFER_OFFSET (buf) = out_offset;
4731     GST_BUFFER_OFFSET_END (buf) = out_offset_end;
4732
4733     /* mark discont when pending */
4734     if (stream->discont) {
4735       GST_DEBUG_OBJECT (avi, "setting DISCONT flag");
4736       GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
4737       stream->discont = FALSE;
4738     }
4739 #if 0
4740     gst_avi_demux_add_assoc (avi, stream, timestamp, offset, keyframe);
4741 #endif
4742
4743     /* update current position in the segment */
4744     avi->segment.position = timestamp;
4745
4746     GST_DEBUG_OBJECT (avi, "Pushing buffer of size %" G_GSIZE_FORMAT ", ts %"
4747         GST_TIME_FORMAT ", dur %" GST_TIME_FORMAT ", off %" G_GUINT64_FORMAT
4748         ", off_end %" G_GUINT64_FORMAT,
4749         gst_buffer_get_size (buf), GST_TIME_ARGS (timestamp),
4750         GST_TIME_ARGS (duration), out_offset, out_offset_end);
4751
4752     ret = gst_pad_push (stream->pad, buf);
4753
4754     /* mark as processed, we increment the frame and byte counters then
4755      * leave the while loop and return the GstFlowReturn */
4756     processed = TRUE;
4757
4758     if (avi->segment.rate < 0) {
4759       if (timestamp > avi->segment.stop && ret == GST_FLOW_EOS) {
4760         /* In reverse playback we can get a GST_FLOW_EOS when
4761          * we are at the end of the segment, so we just need to jump
4762          * back to the previous section. */
4763         GST_DEBUG_OBJECT (avi, "downstream has reached end of segment");
4764         ret = GST_FLOW_OK;
4765       }
4766     }
4767   next:
4768     /* move to next item */
4769     ret = gst_avi_demux_advance (avi, stream, ret);
4770
4771     /* combine flows */
4772     ret = gst_avi_demux_combine_flows (avi, stream, ret);
4773   } while (!processed);
4774
4775 beach:
4776   return ret;
4777
4778   /* special cases */
4779 eos:
4780   {
4781     GST_DEBUG_OBJECT (avi, "No samples left for any streams - EOS");
4782     ret = GST_FLOW_EOS;
4783     goto beach;
4784   }
4785 eos_stop:
4786   {
4787     GST_LOG_OBJECT (avi, "Found keyframe after segment,"
4788         " setting EOS (%" GST_TIME_FORMAT " > %" GST_TIME_FORMAT ")",
4789         GST_TIME_ARGS (timestamp), GST_TIME_ARGS (avi->segment.stop));
4790     ret = GST_FLOW_EOS;
4791     /* move to next stream */
4792     goto next;
4793   }
4794 pull_failed:
4795   {
4796     GST_DEBUG_OBJECT (avi, "pull range failed: pos=%" G_GUINT64_FORMAT
4797         " size=%" G_GUINT64_FORMAT, offset, size);
4798     goto beach;
4799   }
4800 short_buffer:
4801   {
4802     GST_WARNING_OBJECT (avi, "Short read at offset %" G_GUINT64_FORMAT
4803         ", only got %" G_GSIZE_FORMAT "/%" G_GUINT64_FORMAT
4804         " bytes (truncated file?)", offset, gst_buffer_get_size (buf), size);
4805     gst_buffer_unref (buf);
4806     ret = GST_FLOW_EOS;
4807     goto beach;
4808   }
4809 }
4810
4811 /*
4812  * Read data. If we have an index it delegates to
4813  * gst_avi_demux_process_next_entry().
4814  */
4815 static GstFlowReturn
4816 gst_avi_demux_stream_data (GstAviDemux * avi)
4817 {
4818   guint32 tag = 0;
4819   guint32 size = 0;
4820   gint stream_nr = 0;
4821   GstFlowReturn res = GST_FLOW_OK;
4822
4823   if (G_UNLIKELY (avi->have_eos)) {
4824     /* Clean adapter, we're done */
4825     gst_adapter_clear (avi->adapter);
4826     return GST_FLOW_EOS;
4827   }
4828
4829   if (G_UNLIKELY (avi->todrop)) {
4830     guint drop;
4831
4832     if ((drop = gst_adapter_available (avi->adapter))) {
4833       if (drop > avi->todrop)
4834         drop = avi->todrop;
4835       GST_DEBUG_OBJECT (avi, "Dropping %d bytes", drop);
4836       gst_adapter_flush (avi->adapter, drop);
4837       avi->todrop -= drop;
4838       avi->offset += drop;
4839     }
4840   }
4841
4842   /* Iterate until need more data, so adapter won't grow too much */
4843   while (1) {
4844     if (G_UNLIKELY (!gst_avi_demux_peek_chunk_info (avi, &tag, &size))) {
4845       return GST_FLOW_OK;
4846     }
4847
4848     GST_DEBUG ("Trying chunk (%" GST_FOURCC_FORMAT "), size %d",
4849         GST_FOURCC_ARGS (tag), size);
4850
4851     if (G_LIKELY ((tag & 0xff) >= '0' && (tag & 0xff) <= '9' &&
4852             ((tag >> 8) & 0xff) >= '0' && ((tag >> 8) & 0xff) <= '9')) {
4853       GST_LOG ("Chunk ok");
4854     } else if ((tag & 0xffff) == (('x' << 8) | 'i')) {
4855       GST_DEBUG ("Found sub-index tag");
4856       if (gst_avi_demux_peek_chunk (avi, &tag, &size) || size == 0) {
4857         /* accept 0 size buffer here */
4858         avi->abort_buffering = FALSE;
4859         GST_DEBUG ("  skipping %d bytes for now", size);
4860         gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
4861       }
4862       return GST_FLOW_OK;
4863     } else if (tag == GST_RIFF_TAG_RIFF) {
4864       /* RIFF tags can appear in ODML files, just jump over them */
4865       if (gst_adapter_available (avi->adapter) >= 12) {
4866         GST_DEBUG ("Found RIFF tag, skipping RIFF header");
4867         gst_adapter_flush (avi->adapter, 12);
4868         continue;
4869       }
4870       return GST_FLOW_OK;
4871     } else if (tag == GST_RIFF_TAG_idx1) {
4872       GST_DEBUG ("Found index tag");
4873       if (gst_avi_demux_peek_chunk (avi, &tag, &size) || size == 0) {
4874         /* accept 0 size buffer here */
4875         avi->abort_buffering = FALSE;
4876         GST_DEBUG ("  skipping %d bytes for now", size);
4877         gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
4878       }
4879       return GST_FLOW_OK;
4880     } else if (tag == GST_RIFF_TAG_LIST) {
4881       /* movi chunks might be grouped in rec list */
4882       if (gst_adapter_available (avi->adapter) >= 12) {
4883         GST_DEBUG ("Found LIST tag, skipping LIST header");
4884         gst_adapter_flush (avi->adapter, 12);
4885         continue;
4886       }
4887       return GST_FLOW_OK;
4888     } else if (tag == GST_RIFF_TAG_JUNK || tag == GST_RIFF_TAG_JUNQ) {
4889       /* rec list might contain JUNK chunks */
4890       GST_DEBUG ("Found JUNK tag");
4891       if (gst_avi_demux_peek_chunk (avi, &tag, &size) || size == 0) {
4892         /* accept 0 size buffer here */
4893         avi->abort_buffering = FALSE;
4894         GST_DEBUG ("  skipping %d bytes for now", size);
4895         gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
4896       }
4897       return GST_FLOW_OK;
4898     } else {
4899       GST_DEBUG ("No more stream chunks, send EOS");
4900       avi->have_eos = TRUE;
4901       return GST_FLOW_EOS;
4902     }
4903
4904     if (G_UNLIKELY (!gst_avi_demux_peek_chunk (avi, &tag, &size))) {
4905       /* supposedly one hopes to catch a nicer chunk later on ... */
4906       /* FIXME ?? give up here rather than possibly ending up going
4907        * through the whole file */
4908       if (avi->abort_buffering) {
4909         avi->abort_buffering = FALSE;
4910         if (size) {
4911           gst_adapter_flush (avi->adapter, 8);
4912           return GST_FLOW_OK;
4913         }
4914       } else {
4915         return GST_FLOW_OK;
4916       }
4917     }
4918     GST_DEBUG ("chunk ID %" GST_FOURCC_FORMAT ", size %u",
4919         GST_FOURCC_ARGS (tag), size);
4920
4921     stream_nr = CHUNKID_TO_STREAMNR (tag);
4922
4923     if (G_UNLIKELY (stream_nr < 0 || stream_nr >= avi->num_streams)) {
4924       /* recoverable */
4925       GST_WARNING ("Invalid stream ID %d (%" GST_FOURCC_FORMAT ")",
4926           stream_nr, GST_FOURCC_ARGS (tag));
4927       avi->offset += 8 + GST_ROUND_UP_2 (size);
4928       gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
4929     } else {
4930       GstAviStream *stream;
4931       GstClockTime next_ts = 0;
4932       GstBuffer *buf = NULL;
4933 #if 0
4934       guint64 offset;
4935 #endif
4936       gboolean saw_desired_kf = stream_nr != avi->main_stream
4937           || avi->offset >= avi->seek_kf_offset;
4938
4939       if (stream_nr == avi->main_stream && avi->offset == avi->seek_kf_offset) {
4940         GST_DEBUG_OBJECT (avi, "Desired keyframe reached");
4941         avi->seek_kf_offset = 0;
4942       }
4943
4944       if (saw_desired_kf) {
4945         gst_adapter_flush (avi->adapter, 8);
4946         /* get buffer */
4947         if (size) {
4948           buf = gst_adapter_take_buffer (avi->adapter, GST_ROUND_UP_2 (size));
4949           /* patch the size */
4950           gst_buffer_resize (buf, 0, size);
4951         } else {
4952           buf = NULL;
4953         }
4954       } else {
4955         GST_DEBUG_OBJECT (avi,
4956             "Desired keyframe not yet reached, flushing chunk");
4957         gst_adapter_flush (avi->adapter, 8 + GST_ROUND_UP_2 (size));
4958       }
4959
4960 #if 0
4961       offset = avi->offset;
4962 #endif
4963       avi->offset += 8 + GST_ROUND_UP_2 (size);
4964
4965       stream = &avi->stream[stream_nr];
4966
4967       /* set delay (if any)
4968          if (stream->strh->init_frames == stream->current_frame &&
4969          stream->delay == 0)
4970          stream->delay = next_ts;
4971        */
4972
4973       /* parsing of corresponding header may have failed */
4974       if (G_UNLIKELY (!stream->pad)) {
4975         GST_WARNING_OBJECT (avi, "no pad for stream ID %" GST_FOURCC_FORMAT,
4976             GST_FOURCC_ARGS (tag));
4977         if (buf)
4978           gst_buffer_unref (buf);
4979       } else {
4980         /* get time of this buffer */
4981         gst_pad_query_position (stream->pad, GST_FORMAT_TIME,
4982             (gint64 *) & next_ts);
4983
4984 #if 0
4985         gst_avi_demux_add_assoc (avi, stream, next_ts, offset, FALSE);
4986 #endif
4987
4988         /* increment our positions */
4989         stream->current_entry++;
4990         stream->current_total += size;
4991
4992         /* update current position in the segment */
4993         avi->segment.position = next_ts;
4994
4995         if (saw_desired_kf && buf) {
4996           GstClockTime dur_ts = 0;
4997
4998           /* invert the picture if needed */
4999           buf = gst_avi_demux_invert (stream, buf);
5000
5001           gst_pad_query_position (stream->pad, GST_FORMAT_TIME,
5002               (gint64 *) & dur_ts);
5003
5004           GST_BUFFER_TIMESTAMP (buf) = next_ts;
5005           GST_BUFFER_DURATION (buf) = dur_ts - next_ts;
5006           if (stream->strh->type == GST_RIFF_FCC_vids) {
5007             GST_BUFFER_OFFSET (buf) = stream->current_entry - 1;
5008             GST_BUFFER_OFFSET_END (buf) = stream->current_entry;
5009           } else {
5010             GST_BUFFER_OFFSET (buf) = GST_BUFFER_OFFSET_NONE;
5011             GST_BUFFER_OFFSET_END (buf) = GST_BUFFER_OFFSET_NONE;
5012           }
5013
5014           GST_DEBUG_OBJECT (avi,
5015               "Pushing buffer with time=%" GST_TIME_FORMAT ", duration %"
5016               GST_TIME_FORMAT ", offset %" G_GUINT64_FORMAT
5017               " and size %d over pad %s", GST_TIME_ARGS (next_ts),
5018               GST_TIME_ARGS (GST_BUFFER_DURATION (buf)),
5019               GST_BUFFER_OFFSET (buf), size, GST_PAD_NAME (stream->pad));
5020
5021           /* mark discont when pending */
5022           if (G_UNLIKELY (stream->discont)) {
5023             GST_DEBUG_OBJECT (avi, "Setting DISCONT");
5024             GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
5025             stream->discont = FALSE;
5026           }
5027           res = gst_pad_push (stream->pad, buf);
5028           buf = NULL;
5029
5030           /* combine flows */
5031           res = gst_avi_demux_combine_flows (avi, stream, res);
5032           if (G_UNLIKELY (res != GST_FLOW_OK)) {
5033             GST_DEBUG ("Push failed; %s", gst_flow_get_name (res));
5034             return res;
5035           }
5036         }
5037       }
5038     }
5039   }
5040
5041   return res;
5042 }
5043
5044 /*
5045  * Send pending tags.
5046  */
5047 static void
5048 push_tag_lists (GstAviDemux * avi)
5049 {
5050   guint i;
5051   GstTagList *tags;
5052
5053   if (!avi->got_tags)
5054     return;
5055
5056   GST_DEBUG_OBJECT (avi, "Pushing pending tag lists");
5057
5058   for (i = 0; i < avi->num_streams; i++) {
5059     GstAviStream *stream = &avi->stream[i];
5060     GstPad *pad = stream->pad;
5061
5062     tags = stream->taglist;
5063
5064     if (pad && tags) {
5065       GST_DEBUG_OBJECT (pad, "Tags: %" GST_PTR_FORMAT, tags);
5066
5067       gst_pad_push_event (pad, gst_event_new_tag (tags));
5068       stream->taglist = NULL;
5069     }
5070   }
5071
5072   if (!(tags = avi->globaltags))
5073     tags = gst_tag_list_new_empty ();
5074
5075   gst_tag_list_add (tags, GST_TAG_MERGE_REPLACE,
5076       GST_TAG_CONTAINER_FORMAT, "AVI", NULL);
5077
5078   GST_DEBUG_OBJECT (avi, "Global tags: %" GST_PTR_FORMAT, tags);
5079   gst_avi_demux_push_event (avi, gst_event_new_tag (tags));
5080   avi->globaltags = NULL;
5081   avi->got_tags = FALSE;
5082 }
5083
5084 static void
5085 gst_avi_demux_loop (GstPad * pad)
5086 {
5087   GstFlowReturn res;
5088   GstAviDemux *avi = GST_AVI_DEMUX (GST_PAD_PARENT (pad));
5089
5090   switch (avi->state) {
5091     case GST_AVI_DEMUX_START:
5092       res = gst_avi_demux_stream_init_pull (avi);
5093       if (G_UNLIKELY (res != GST_FLOW_OK)) {
5094         GST_WARNING ("stream_init flow: %s", gst_flow_get_name (res));
5095         goto pause;
5096       }
5097       avi->state = GST_AVI_DEMUX_HEADER;
5098       /* fall-through */
5099     case GST_AVI_DEMUX_HEADER:
5100       res = gst_avi_demux_stream_header_pull (avi);
5101       if (G_UNLIKELY (res != GST_FLOW_OK)) {
5102         GST_WARNING ("stream_header flow: %s", gst_flow_get_name (res));
5103         goto pause;
5104       }
5105       avi->state = GST_AVI_DEMUX_MOVI;
5106       break;
5107     case GST_AVI_DEMUX_MOVI:
5108       if (G_UNLIKELY (avi->seg_event)) {
5109         gst_avi_demux_push_event (avi, avi->seg_event);
5110         avi->seg_event = NULL;
5111       }
5112       if (G_UNLIKELY (avi->got_tags)) {
5113         push_tag_lists (avi);
5114       }
5115       /* process each index entry in turn */
5116       res = gst_avi_demux_loop_data (avi);
5117
5118       /* pause when error */
5119       if (G_UNLIKELY (res != GST_FLOW_OK)) {
5120         GST_INFO ("stream_movi flow: %s", gst_flow_get_name (res));
5121         goto pause;
5122       }
5123       break;
5124     default:
5125       GST_ERROR_OBJECT (avi, "unknown state %d", avi->state);
5126       res = GST_FLOW_ERROR;
5127       goto pause;
5128   }
5129
5130   return;
5131
5132   /* ERRORS */
5133 pause:{
5134
5135     gboolean push_eos = FALSE;
5136     GST_LOG_OBJECT (avi, "pausing task, reason %s", gst_flow_get_name (res));
5137     gst_pad_pause_task (avi->sinkpad);
5138
5139     if (res == GST_FLOW_EOS) {
5140       /* handle end-of-stream/segment */
5141       /* so align our position with the end of it, if there is one
5142        * this ensures a subsequent will arrive at correct base/acc time */
5143       if (avi->segment.rate > 0.0 &&
5144           GST_CLOCK_TIME_IS_VALID (avi->segment.stop))
5145         avi->segment.position = avi->segment.stop;
5146       else if (avi->segment.rate < 0.0)
5147         avi->segment.position = avi->segment.start;
5148       if (avi->segment.flags & GST_SEEK_FLAG_SEGMENT) {
5149         gint64 stop;
5150
5151         if ((stop = avi->segment.stop) == -1)
5152           stop = avi->segment.duration;
5153
5154         GST_INFO_OBJECT (avi, "sending segment_done");
5155
5156         gst_element_post_message
5157             (GST_ELEMENT_CAST (avi),
5158             gst_message_new_segment_done (GST_OBJECT_CAST (avi),
5159                 GST_FORMAT_TIME, stop));
5160       } else {
5161         push_eos = TRUE;
5162       }
5163     } else if (res == GST_FLOW_NOT_LINKED || res < GST_FLOW_EOS) {
5164       /* for fatal errors we post an error message, wrong-state is
5165        * not fatal because it happens due to flushes and only means
5166        * that we should stop now. */
5167       GST_ELEMENT_ERROR (avi, STREAM, FAILED,
5168           (_("Internal data stream error.")),
5169           ("streaming stopped, reason %s", gst_flow_get_name (res)));
5170       push_eos = TRUE;
5171     }
5172     if (push_eos) {
5173       GST_INFO_OBJECT (avi, "sending eos");
5174       if (!gst_avi_demux_push_event (avi, gst_event_new_eos ()) &&
5175           (res == GST_FLOW_EOS)) {
5176         GST_ELEMENT_ERROR (avi, STREAM, DEMUX,
5177             (NULL), ("got eos but no streams (yet)"));
5178       }
5179     }
5180   }
5181 }
5182
5183
5184 static GstFlowReturn
5185 gst_avi_demux_chain (GstPad * pad, GstObject * parent, GstBuffer * buf)
5186 {
5187   GstFlowReturn res;
5188   GstAviDemux *avi = GST_AVI_DEMUX (parent);
5189   gint i;
5190
5191   if (GST_BUFFER_IS_DISCONT (buf)) {
5192     GST_DEBUG_OBJECT (avi, "got DISCONT");
5193     gst_adapter_clear (avi->adapter);
5194     /* mark all streams DISCONT */
5195     for (i = 0; i < avi->num_streams; i++)
5196       avi->stream[i].discont = TRUE;
5197   }
5198
5199   GST_DEBUG ("Store %" G_GSIZE_FORMAT " bytes in adapter",
5200       gst_buffer_get_size (buf));
5201   gst_adapter_push (avi->adapter, buf);
5202
5203   switch (avi->state) {
5204     case GST_AVI_DEMUX_START:
5205       if ((res = gst_avi_demux_stream_init_push (avi)) != GST_FLOW_OK) {
5206         GST_WARNING ("stream_init flow: %s", gst_flow_get_name (res));
5207         break;
5208       }
5209       break;
5210     case GST_AVI_DEMUX_HEADER:
5211       if ((res = gst_avi_demux_stream_header_push (avi)) != GST_FLOW_OK) {
5212         GST_WARNING ("stream_header flow: %s", gst_flow_get_name (res));
5213         break;
5214       }
5215       break;
5216     case GST_AVI_DEMUX_MOVI:
5217       if (G_UNLIKELY (avi->seg_event)) {
5218         gst_avi_demux_push_event (avi, avi->seg_event);
5219         avi->seg_event = NULL;
5220       }
5221       if (G_UNLIKELY (avi->got_tags)) {
5222         push_tag_lists (avi);
5223       }
5224       res = gst_avi_demux_stream_data (avi);
5225       break;
5226     case GST_AVI_DEMUX_SEEK:
5227     {
5228       GstEvent *event;
5229
5230       res = GST_FLOW_OK;
5231
5232       /* obtain and parse indexes */
5233       if (avi->stream[0].indexes && !gst_avi_demux_read_subindexes_push (avi))
5234         /* seek in subindex read function failed */
5235         goto index_failed;
5236
5237       if (!avi->stream[0].indexes && !avi->have_index
5238           && avi->avih->flags & GST_RIFF_AVIH_HASINDEX)
5239         gst_avi_demux_stream_index_push (avi);
5240
5241       if (avi->have_index) {
5242         /* use the indexes now to construct nice durations */
5243         gst_avi_demux_calculate_durations_from_index (avi);
5244       } else {
5245         /* still parsing indexes */
5246         break;
5247       }
5248
5249       GST_OBJECT_LOCK (avi);
5250       event = avi->seek_event;
5251       avi->seek_event = NULL;
5252       GST_OBJECT_UNLOCK (avi);
5253
5254       /* calculate and perform seek */
5255       if (!avi_demux_handle_seek_push (avi, avi->sinkpad, event))
5256         goto seek_failed;
5257
5258       gst_event_unref (event);
5259       avi->state = GST_AVI_DEMUX_MOVI;
5260       break;
5261     }
5262     default:
5263       GST_ELEMENT_ERROR (avi, STREAM, FAILED, (NULL),
5264           ("Illegal internal state"));
5265       res = GST_FLOW_ERROR;
5266       break;
5267   }
5268
5269   GST_DEBUG_OBJECT (avi, "state: %d res:%s", avi->state,
5270       gst_flow_get_name (res));
5271
5272   if (G_UNLIKELY (avi->abort_buffering))
5273     goto abort_buffering;
5274
5275   return res;
5276
5277   /* ERRORS */
5278 index_failed:
5279   {
5280     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("failed to read indexes"));
5281     return GST_FLOW_ERROR;
5282   }
5283 seek_failed:
5284   {
5285     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("push mode seek failed"));
5286     return GST_FLOW_ERROR;
5287   }
5288 abort_buffering:
5289   {
5290     avi->abort_buffering = FALSE;
5291     GST_ELEMENT_ERROR (avi, STREAM, DEMUX, (NULL), ("unhandled buffer size"));
5292     return GST_FLOW_ERROR;
5293   }
5294 }
5295
5296 static gboolean
5297 gst_avi_demux_sink_activate (GstPad * sinkpad, GstObject * parent)
5298 {
5299   GstQuery *query;
5300   gboolean pull_mode;
5301
5302   query = gst_query_new_scheduling ();
5303
5304   if (!gst_pad_peer_query (sinkpad, query)) {
5305     gst_query_unref (query);
5306     goto activate_push;
5307   }
5308
5309   pull_mode = gst_query_has_scheduling_mode (query, GST_PAD_MODE_PULL);
5310   gst_query_unref (query);
5311
5312   if (!pull_mode)
5313     goto activate_push;
5314
5315   GST_DEBUG_OBJECT (sinkpad, "activating pull");
5316   return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PULL, TRUE);
5317
5318 activate_push:
5319   {
5320     GST_DEBUG_OBJECT (sinkpad, "activating push");
5321     return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
5322   }
5323 }
5324
5325 static gboolean
5326 gst_avi_demux_sink_activate_mode (GstPad * sinkpad, GstObject * parent,
5327     GstPadMode mode, gboolean active)
5328 {
5329   gboolean res;
5330   GstAviDemux *avi = GST_AVI_DEMUX (parent);
5331
5332   switch (mode) {
5333     case GST_PAD_MODE_PULL:
5334       if (active) {
5335         avi->streaming = FALSE;
5336         res = gst_pad_start_task (sinkpad, (GstTaskFunction) gst_avi_demux_loop,
5337             sinkpad);
5338       } else {
5339         res = gst_pad_stop_task (sinkpad);
5340       }
5341       break;
5342     case GST_PAD_MODE_PUSH:
5343       if (active) {
5344         GST_DEBUG ("avi: activating push/chain function");
5345         avi->streaming = TRUE;
5346       } else {
5347         GST_DEBUG ("avi: deactivating push/chain function");
5348       }
5349       res = TRUE;
5350       break;
5351     default:
5352       res = FALSE;
5353       break;
5354   }
5355   return res;
5356 }
5357
5358 #if 0
5359 static void
5360 gst_avi_demux_set_index (GstElement * element, GstIndex * index)
5361 {
5362   GstAviDemux *avi = GST_AVI_DEMUX (element);
5363
5364   GST_OBJECT_LOCK (avi);
5365   if (avi->element_index)
5366     gst_object_unref (avi->element_index);
5367   if (index) {
5368     avi->element_index = gst_object_ref (index);
5369   } else {
5370     avi->element_index = NULL;
5371   }
5372   GST_OBJECT_UNLOCK (avi);
5373   /* object lock might be taken again */
5374   if (index)
5375     gst_index_get_writer_id (index, GST_OBJECT_CAST (element), &avi->index_id);
5376   GST_DEBUG_OBJECT (avi, "Set index %" GST_PTR_FORMAT, avi->element_index);
5377 }
5378
5379 static GstIndex *
5380 gst_avi_demux_get_index (GstElement * element)
5381 {
5382   GstIndex *result = NULL;
5383   GstAviDemux *avi = GST_AVI_DEMUX (element);
5384
5385   GST_OBJECT_LOCK (avi);
5386   if (avi->element_index)
5387     result = gst_object_ref (avi->element_index);
5388   GST_OBJECT_UNLOCK (avi);
5389
5390   GST_DEBUG_OBJECT (avi, "Returning index %" GST_PTR_FORMAT, result);
5391
5392   return result;
5393 }
5394 #endif
5395
5396 static GstStateChangeReturn
5397 gst_avi_demux_change_state (GstElement * element, GstStateChange transition)
5398 {
5399   GstStateChangeReturn ret;
5400   GstAviDemux *avi = GST_AVI_DEMUX (element);
5401
5402   switch (transition) {
5403     case GST_STATE_CHANGE_READY_TO_PAUSED:
5404       avi->streaming = FALSE;
5405       gst_segment_init (&avi->segment, GST_FORMAT_TIME);
5406       break;
5407     default:
5408       break;
5409   }
5410
5411   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
5412   if (ret == GST_STATE_CHANGE_FAILURE)
5413     goto done;
5414
5415   switch (transition) {
5416     case GST_STATE_CHANGE_PAUSED_TO_READY:
5417       avi->have_index = FALSE;
5418       gst_avi_demux_reset (avi);
5419       break;
5420     default:
5421       break;
5422   }
5423
5424 done:
5425   return ret;
5426 }