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