matroskademux: put streamheaders on vorbis/speex/flac/theora caps to make remuxing...
[platform/upstream/gstreamer.git] / gst / matroska / matroska-demux.c
1 /* GStreamer Matroska muxer/demuxer
2  * (c) 2003 Ronald Bultje <rbultje@ronald.bitfreak.net>
3  * (c) 2006 Tim-Philipp Müller <tim centricular net>
4  * (c) 2008 Sebastian Dröge <slomo@circular-chaos.org>
5  * (c) 2011 Debarshi Ray <rishi@gnu.org>
6  *
7  * matroska-demux.c: matroska file/stream demuxer
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public
20  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22  * Boston, MA 02111-1307, USA.
23  */
24
25 /* TODO: check CRC32 if present
26  * TODO: there can be a segment after the first segment. Handle like
27  *       chained oggs. Fixes #334082
28  * TODO: Test samples: http://www.matroska.org/samples/matrix/index.html
29  *                     http://samples.mplayerhq.hu/Matroska/
30  * TODO: check if demuxing is done correct for all codecs according to spec
31  * TODO: seeking with incomplete or without CUE
32  */
33
34 /**
35  * SECTION:element-matroskademux
36  *
37  * matroskademux demuxes a Matroska file into the different contained streams.
38  *
39  * <refsect2>
40  * <title>Example launch line</title>
41  * |[
42  * gst-launch-1.0 -v filesrc location=/path/to/mkv ! matroskademux ! vorbisdec ! audioconvert ! audioresample ! autoaudiosink
43  * ]| This pipeline demuxes a Matroska file and outputs the contained Vorbis audio.
44  * </refsect2>
45  */
46
47
48 #ifdef HAVE_CONFIG_H
49 #include "config.h"
50 #endif
51
52 #include <math.h>
53 #include <string.h>
54 #include <glib/gprintf.h>
55
56 /* For AVI compatibility mode
57    and for fourcc stuff */
58 #include <gst/riff/riff-read.h>
59 #include <gst/riff/riff-ids.h>
60 #include <gst/riff/riff-media.h>
61
62 #include <gst/audio/audio.h>
63 #include <gst/tag/tag.h>
64 #include <gst/pbutils/pbutils.h>
65
66 #include "matroska-demux.h"
67 #include "matroska-ids.h"
68
69 GST_DEBUG_CATEGORY_STATIC (matroskademux_debug);
70 #define GST_CAT_DEFAULT matroskademux_debug
71
72 #define DEBUG_ELEMENT_START(demux, ebml, element) \
73     GST_DEBUG_OBJECT (demux, "Parsing " element " element at offset %" \
74         G_GUINT64_FORMAT, gst_ebml_read_get_pos (ebml))
75
76 #define DEBUG_ELEMENT_STOP(demux, ebml, element, ret) \
77     GST_DEBUG_OBJECT (demux, "Parsing " element " element " \
78         " finished with '%s'", gst_flow_get_name (ret))
79
80 enum
81 {
82   ARG_0,
83   ARG_METADATA,
84   ARG_STREAMINFO,
85   ARG_MAX_GAP_TIME
86 };
87
88 #define  DEFAULT_MAX_GAP_TIME      (2 * GST_SECOND)
89
90 static GstStaticPadTemplate sink_templ = GST_STATIC_PAD_TEMPLATE ("sink",
91     GST_PAD_SINK,
92     GST_PAD_ALWAYS,
93     GST_STATIC_CAPS ("audio/x-matroska; video/x-matroska; "
94         "video/x-matroska-3d; audio/webm; video/webm")
95     );
96
97 /* TODO: fill in caps! */
98
99 static GstStaticPadTemplate audio_src_templ =
100 GST_STATIC_PAD_TEMPLATE ("audio_%u",
101     GST_PAD_SRC,
102     GST_PAD_SOMETIMES,
103     GST_STATIC_CAPS ("ANY")
104     );
105
106 static GstStaticPadTemplate video_src_templ =
107 GST_STATIC_PAD_TEMPLATE ("video_%u",
108     GST_PAD_SRC,
109     GST_PAD_SOMETIMES,
110     GST_STATIC_CAPS ("ANY")
111     );
112
113 static GstStaticPadTemplate subtitle_src_templ =
114     GST_STATIC_PAD_TEMPLATE ("subtitle_%u",
115     GST_PAD_SRC,
116     GST_PAD_SOMETIMES,
117     GST_STATIC_CAPS ("text/x-raw, format=pango-markup; application/x-ssa; "
118         "application/x-ass;application/x-usf; subpicture/x-dvd; "
119         "subpicture/x-pgs; subtitle/x-kate; " "application/x-subtitle-unknown")
120     );
121
122 static GstFlowReturn gst_matroska_demux_parse_id (GstMatroskaDemux * demux,
123     guint32 id, guint64 length, guint needed);
124
125 /* element functions */
126 static void gst_matroska_demux_loop (GstPad * pad);
127
128 static gboolean gst_matroska_demux_element_send_event (GstElement * element,
129     GstEvent * event);
130 static gboolean gst_matroska_demux_element_query (GstElement * element,
131     GstQuery * query);
132
133 /* pad functions */
134 static gboolean gst_matroska_demux_sink_activate (GstPad * sinkpad,
135     GstObject * parent);
136 static gboolean gst_matroska_demux_sink_activate_mode (GstPad * sinkpad,
137     GstObject * parent, GstPadMode mode, gboolean active);
138
139 static gboolean gst_matroska_demux_handle_seek_event (GstMatroskaDemux * demux,
140     GstPad * pad, GstEvent * event);
141 static gboolean gst_matroska_demux_handle_src_event (GstPad * pad,
142     GstObject * parent, GstEvent * event);
143 static gboolean gst_matroska_demux_handle_src_query (GstPad * pad,
144     GstObject * parent, GstQuery * query);
145
146 static gboolean gst_matroska_demux_handle_sink_event (GstPad * pad,
147     GstObject * parent, GstEvent * event);
148 static GstFlowReturn gst_matroska_demux_chain (GstPad * pad,
149     GstObject * object, GstBuffer * buffer);
150
151 static GstStateChangeReturn
152 gst_matroska_demux_change_state (GstElement * element,
153     GstStateChange transition);
154 #if 0
155 static void
156 gst_matroska_demux_set_index (GstElement * element, GstIndex * index);
157 static GstIndex *gst_matroska_demux_get_index (GstElement * element);
158 #endif
159
160 /* caps functions */
161 static GstCaps *gst_matroska_demux_video_caps (GstMatroskaTrackVideoContext
162     * videocontext, const gchar * codec_id, guint8 * data, guint size,
163     gchar ** codec_name, guint32 * riff_fourcc);
164 static GstCaps *gst_matroska_demux_audio_caps (GstMatroskaTrackAudioContext
165     * audiocontext, const gchar * codec_id, guint8 * data, guint size,
166     gchar ** codec_name, guint16 * riff_audio_fmt);
167 static GstCaps
168     * gst_matroska_demux_subtitle_caps (GstMatroskaTrackSubtitleContext *
169     subtitlecontext, const gchar * codec_id, gpointer data, guint size);
170
171 /* stream methods */
172 static void gst_matroska_demux_reset (GstElement * element);
173 static gboolean perform_seek_to_offset (GstMatroskaDemux * demux,
174     gdouble rate, guint64 offset);
175
176 /* gobject functions */
177 static void gst_matroska_demux_set_property (GObject * object,
178     guint prop_id, const GValue * value, GParamSpec * pspec);
179 static void gst_matroska_demux_get_property (GObject * object,
180     guint prop_id, GValue * value, GParamSpec * pspec);
181
182 GType gst_matroska_demux_get_type (void);
183 #define parent_class gst_matroska_demux_parent_class
184 G_DEFINE_TYPE (GstMatroskaDemux, gst_matroska_demux, GST_TYPE_ELEMENT);
185
186 static void
187 gst_matroska_demux_finalize (GObject * object)
188 {
189   GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (object);
190
191   if (demux->common.src) {
192     g_ptr_array_free (demux->common.src, TRUE);
193     demux->common.src = NULL;
194   }
195
196   if (demux->common.global_tags) {
197     gst_tag_list_unref (demux->common.global_tags);
198     demux->common.global_tags = NULL;
199   }
200
201   g_object_unref (demux->common.adapter);
202
203   G_OBJECT_CLASS (parent_class)->finalize (object);
204 }
205
206 static void
207 gst_matroska_demux_class_init (GstMatroskaDemuxClass * klass)
208 {
209   GObjectClass *gobject_class = (GObjectClass *) klass;
210   GstElementClass *gstelement_class = (GstElementClass *) klass;
211
212   GST_DEBUG_CATEGORY_INIT (matroskademux_debug, "matroskademux", 0,
213       "Matroska demuxer");
214
215   gobject_class->finalize = gst_matroska_demux_finalize;
216
217   gobject_class->get_property = gst_matroska_demux_get_property;
218   gobject_class->set_property = gst_matroska_demux_set_property;
219
220   g_object_class_install_property (gobject_class, ARG_MAX_GAP_TIME,
221       g_param_spec_uint64 ("max-gap-time", "Maximum gap time",
222           "The demuxer sends out segment events for skipping "
223           "gaps longer than this (0 = disabled).", 0, G_MAXUINT64,
224           DEFAULT_MAX_GAP_TIME, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
225
226   gstelement_class->change_state =
227       GST_DEBUG_FUNCPTR (gst_matroska_demux_change_state);
228   gstelement_class->send_event =
229       GST_DEBUG_FUNCPTR (gst_matroska_demux_element_send_event);
230   gstelement_class->query =
231       GST_DEBUG_FUNCPTR (gst_matroska_demux_element_query);
232 #if 0
233   gstelement_class->set_index =
234       GST_DEBUG_FUNCPTR (gst_matroska_demux_set_index);
235   gstelement_class->get_index =
236       GST_DEBUG_FUNCPTR (gst_matroska_demux_get_index);
237 #endif
238
239   gst_element_class_add_pad_template (gstelement_class,
240       gst_static_pad_template_get (&video_src_templ));
241   gst_element_class_add_pad_template (gstelement_class,
242       gst_static_pad_template_get (&audio_src_templ));
243   gst_element_class_add_pad_template (gstelement_class,
244       gst_static_pad_template_get (&subtitle_src_templ));
245   gst_element_class_add_pad_template (gstelement_class,
246       gst_static_pad_template_get (&sink_templ));
247
248   gst_element_class_set_static_metadata (gstelement_class, "Matroska demuxer",
249       "Codec/Demuxer",
250       "Demuxes Matroska/WebM streams into video/audio/subtitles",
251       "GStreamer maintainers <gstreamer-devel@lists.sourceforge.net>");
252 }
253
254 static void
255 gst_matroska_demux_init (GstMatroskaDemux * demux)
256 {
257   demux->common.sinkpad = gst_pad_new_from_static_template (&sink_templ,
258       "sink");
259   gst_pad_set_activate_function (demux->common.sinkpad,
260       GST_DEBUG_FUNCPTR (gst_matroska_demux_sink_activate));
261   gst_pad_set_activatemode_function (demux->common.sinkpad,
262       GST_DEBUG_FUNCPTR (gst_matroska_demux_sink_activate_mode));
263   gst_pad_set_chain_function (demux->common.sinkpad,
264       GST_DEBUG_FUNCPTR (gst_matroska_demux_chain));
265   gst_pad_set_event_function (demux->common.sinkpad,
266       GST_DEBUG_FUNCPTR (gst_matroska_demux_handle_sink_event));
267   gst_element_add_pad (GST_ELEMENT (demux), demux->common.sinkpad);
268
269   /* initial stream no. */
270   demux->common.src = NULL;
271
272   demux->common.writing_app = NULL;
273   demux->common.muxing_app = NULL;
274   demux->common.index = NULL;
275   demux->common.global_tags = NULL;
276
277   demux->common.adapter = gst_adapter_new ();
278
279   /* property defaults */
280   demux->max_gap_time = DEFAULT_MAX_GAP_TIME;
281
282   GST_OBJECT_FLAG_SET (demux, GST_ELEMENT_FLAG_INDEXABLE);
283
284   /* finish off */
285   gst_matroska_demux_reset (GST_ELEMENT (demux));
286 }
287
288 static void
289 gst_matroska_track_free (GstMatroskaTrackContext * track)
290 {
291   g_free (track->codec_id);
292   g_free (track->codec_name);
293   g_free (track->name);
294   g_free (track->language);
295   g_free (track->codec_priv);
296   g_free (track->codec_state);
297
298   if (track->encodings != NULL) {
299     int i;
300
301     for (i = 0; i < track->encodings->len; ++i) {
302       GstMatroskaTrackEncoding *enc = &g_array_index (track->encodings,
303           GstMatroskaTrackEncoding,
304           i);
305
306       g_free (enc->comp_settings);
307     }
308     g_array_free (track->encodings, TRUE);
309   }
310
311   if (track->pending_tags)
312     gst_tag_list_unref (track->pending_tags);
313
314   if (track->index_table)
315     g_array_free (track->index_table, TRUE);
316
317   if (track->stream_headers)
318     gst_buffer_list_unref (track->stream_headers);
319
320   g_free (track);
321 }
322
323 /*
324  * Returns the aggregated GstFlowReturn.
325  */
326 static GstFlowReturn
327 gst_matroska_demux_combine_flows (GstMatroskaDemux * demux,
328     GstMatroskaTrackContext * track, GstFlowReturn ret)
329 {
330   guint i;
331
332   /* store the value */
333   track->last_flow = ret;
334
335   /* any other error that is not-linked can be returned right away */
336   if (ret != GST_FLOW_NOT_LINKED)
337     goto done;
338
339   /* only return NOT_LINKED if all other pads returned NOT_LINKED */
340   g_assert (demux->common.src->len == demux->common.num_streams);
341   for (i = 0; i < demux->common.src->len; i++) {
342     GstMatroskaTrackContext *ostream = g_ptr_array_index (demux->common.src,
343         i);
344
345     if (ostream == NULL)
346       continue;
347
348     ret = ostream->last_flow;
349     /* some other return value (must be SUCCESS but we can return
350      * other values as well) */
351     if (ret != GST_FLOW_NOT_LINKED)
352       goto done;
353   }
354   /* if we get here, all other pads were unlinked and we return
355    * NOT_LINKED then */
356 done:
357   GST_LOG_OBJECT (demux, "combined return %s", gst_flow_get_name (ret));
358   return ret;
359 }
360
361 static void
362 gst_matroska_demux_free_parsed_el (gpointer mem, gpointer user_data)
363 {
364   g_slice_free (guint64, mem);
365 }
366
367 static void
368 gst_matroska_demux_reset (GstElement * element)
369 {
370   GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (element);
371   guint i;
372
373   GST_DEBUG_OBJECT (demux, "Resetting state");
374
375   /* reset input */
376   demux->common.state = GST_MATROSKA_READ_STATE_START;
377
378   /* clean up existing streams */
379   if (demux->common.src) {
380     g_assert (demux->common.src->len == demux->common.num_streams);
381     for (i = 0; i < demux->common.src->len; i++) {
382       GstMatroskaTrackContext *context = g_ptr_array_index (demux->common.src,
383           i);
384
385       if (context->pad != NULL)
386         gst_element_remove_pad (GST_ELEMENT (demux), context->pad);
387
388       gst_caps_replace (&context->caps, NULL);
389       gst_matroska_track_free (context);
390     }
391     g_ptr_array_free (demux->common.src, TRUE);
392   }
393   demux->common.src = g_ptr_array_new ();
394
395   demux->common.num_streams = 0;
396   demux->num_a_streams = 0;
397   demux->num_t_streams = 0;
398   demux->num_v_streams = 0;
399
400   /* reset media info */
401   g_free (demux->common.writing_app);
402   demux->common.writing_app = NULL;
403   g_free (demux->common.muxing_app);
404   demux->common.muxing_app = NULL;
405
406   /* reset indexes */
407   if (demux->common.index) {
408     g_array_free (demux->common.index, TRUE);
409     demux->common.index = NULL;
410   }
411
412   if (demux->clusters) {
413     g_array_free (demux->clusters, TRUE);
414     demux->clusters = NULL;
415   }
416
417   /* reset timers */
418   demux->clock = NULL;
419   demux->common.time_scale = 1000000;
420   demux->common.created = G_MININT64;
421
422   demux->common.index_parsed = FALSE;
423   demux->tracks_parsed = FALSE;
424   demux->common.segmentinfo_parsed = FALSE;
425   demux->common.attachments_parsed = FALSE;
426   demux->common.chapters_parsed = FALSE;
427
428   g_list_foreach (demux->common.tags_parsed,
429       (GFunc) gst_matroska_demux_free_parsed_el, NULL);
430   g_list_free (demux->common.tags_parsed);
431   demux->common.tags_parsed = NULL;
432
433   g_list_foreach (demux->seek_parsed,
434       (GFunc) gst_matroska_demux_free_parsed_el, NULL);
435   g_list_free (demux->seek_parsed);
436   demux->seek_parsed = NULL;
437
438   gst_segment_init (&demux->common.segment, GST_FORMAT_TIME);
439   demux->last_stop_end = GST_CLOCK_TIME_NONE;
440   demux->seek_block = 0;
441   demux->stream_start_time = GST_CLOCK_TIME_NONE;
442   demux->to_time = GST_CLOCK_TIME_NONE;
443
444   demux->common.offset = 0;
445   demux->cluster_time = GST_CLOCK_TIME_NONE;
446   demux->cluster_offset = 0;
447   demux->next_cluster_offset = 0;
448   demux->index_offset = 0;
449   demux->seekable = FALSE;
450   demux->need_segment = FALSE;
451   demux->requested_seek_time = GST_CLOCK_TIME_NONE;
452   demux->seek_offset = -1;
453   demux->building_index = FALSE;
454   if (demux->seek_event) {
455     gst_event_unref (demux->seek_event);
456     demux->seek_event = NULL;
457   }
458
459   demux->seek_index = NULL;
460   demux->seek_entry = 0;
461
462   if (demux->new_segment) {
463     gst_event_unref (demux->new_segment);
464     demux->new_segment = NULL;
465   }
466 #if 0
467   if (demux->common.element_index) {
468     gst_object_unref (demux->common.element_index);
469     demux->common.element_index = NULL;
470   }
471   demux->common.element_index_writer_id = -1;
472 #endif
473
474   if (demux->common.global_tags) {
475     gst_tag_list_unref (demux->common.global_tags);
476   }
477   demux->common.global_tags = gst_tag_list_new_empty ();
478   gst_tag_list_set_scope (demux->common.global_tags, GST_TAG_SCOPE_GLOBAL);
479
480   if (demux->common.cached_buffer) {
481     if (demux->common.cached_data) {
482       gst_buffer_unmap (demux->common.cached_buffer, &demux->common.cached_map);
483       demux->common.cached_data = NULL;
484     }
485     gst_buffer_unref (demux->common.cached_buffer);
486     demux->common.cached_buffer = NULL;
487   }
488
489   /* free chapters TOC if any */
490   if (demux->common.toc) {
491     gst_toc_unref (demux->common.toc);
492     demux->common.toc = NULL;
493   }
494
495   demux->invalid_duration = FALSE;
496 }
497
498 static GstBuffer *
499 gst_matroska_decode_buffer (GstMatroskaTrackContext * context, GstBuffer * buf)
500 {
501   GstMapInfo map;
502   gpointer data;
503   gsize size;
504
505   g_return_val_if_fail (GST_IS_BUFFER (buf), NULL);
506
507   GST_DEBUG ("decoding buffer %p", buf);
508
509   gst_buffer_map (buf, &map, GST_MAP_READ);
510   data = map.data;
511   size = map.size;
512
513   g_return_val_if_fail (size > 0, buf);
514
515   if (gst_matroska_decode_data (context->encodings, &data, &size,
516           GST_MATROSKA_TRACK_ENCODING_SCOPE_FRAME, FALSE)) {
517     gst_buffer_unmap (buf, &map);
518     gst_buffer_unref (buf);
519     return gst_buffer_new_wrapped (data, size);
520   } else {
521     GST_DEBUG ("decode data failed");
522     gst_buffer_unmap (buf, &map);
523     gst_buffer_unref (buf);
524     return NULL;
525   }
526 }
527
528 static void
529 gst_matroska_demux_add_stream_headers_to_caps (GstMatroskaDemux * demux,
530     GstBufferList * list, GstCaps * caps)
531 {
532   GstStructure *s;
533   GValue arr_val = G_VALUE_INIT;
534   GValue buf_val = G_VALUE_INIT;
535   gint i, num;
536
537   g_assert (gst_caps_is_writable (caps));
538
539   g_value_init (&arr_val, GST_TYPE_ARRAY);
540   g_value_init (&buf_val, GST_TYPE_BUFFER);
541
542   num = gst_buffer_list_length (list);
543   for (i = 0; i < num; ++i) {
544     g_value_set_boxed (&buf_val, gst_buffer_list_get (list, i));
545     gst_value_array_append_value (&arr_val, &buf_val);
546   }
547
548   s = gst_caps_get_structure (caps, 0);
549   gst_structure_take_value (s, "streamheader", &arr_val);
550   g_value_unset (&buf_val);
551 }
552
553 static GstFlowReturn
554 gst_matroska_demux_add_stream (GstMatroskaDemux * demux, GstEbmlRead * ebml)
555 {
556   GstElementClass *klass = GST_ELEMENT_GET_CLASS (demux);
557   GstMatroskaTrackContext *context;
558   GstPadTemplate *templ = NULL;
559   GstCaps *caps = NULL;
560   gchar *padname = NULL;
561   GstFlowReturn ret;
562   guint32 id, riff_fourcc = 0;
563   guint16 riff_audio_fmt = 0;
564   GstTagList *list = NULL;
565   gchar *codec = NULL;
566   gchar *stream_id;
567
568   DEBUG_ELEMENT_START (demux, ebml, "TrackEntry");
569
570   /* start with the master */
571   if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
572     DEBUG_ELEMENT_STOP (demux, ebml, "TrackEntry", ret);
573     return ret;
574   }
575
576   /* allocate generic... if we know the type, we'll g_renew()
577    * with the precise type */
578   context = g_new0 (GstMatroskaTrackContext, 1);
579   g_ptr_array_add (demux->common.src, context);
580   context->index = demux->common.num_streams;
581   context->index_writer_id = -1;
582   context->type = 0;            /* no type yet */
583   context->default_duration = 0;
584   context->pos = 0;
585   context->set_discont = TRUE;
586   context->timecodescale = 1.0;
587   context->flags =
588       GST_MATROSKA_TRACK_ENABLED | GST_MATROSKA_TRACK_DEFAULT |
589       GST_MATROSKA_TRACK_LACING;
590   context->last_flow = GST_FLOW_OK;
591   context->from_time = GST_CLOCK_TIME_NONE;
592   context->from_offset = -1;
593   context->to_offset = G_MAXINT64;
594   context->alignment = 1;
595   demux->common.num_streams++;
596   g_assert (demux->common.src->len == demux->common.num_streams);
597
598   GST_DEBUG_OBJECT (demux, "Stream number %d", context->index);
599
600   /* try reading the trackentry headers */
601   while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
602     if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
603       break;
604
605     switch (id) {
606         /* track number (unique stream ID) */
607       case GST_MATROSKA_ID_TRACKNUMBER:{
608         guint64 num;
609
610         if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
611           break;
612
613         if (num == 0) {
614           GST_ERROR_OBJECT (demux, "Invalid TrackNumber 0");
615           ret = GST_FLOW_ERROR;
616           break;
617         } else if (!gst_matroska_read_common_tracknumber_unique (&demux->common,
618                 num)) {
619           GST_ERROR_OBJECT (demux, "TrackNumber %" G_GUINT64_FORMAT
620               " is not unique", num);
621           ret = GST_FLOW_ERROR;
622           break;
623         }
624
625         GST_DEBUG_OBJECT (demux, "TrackNumber: %" G_GUINT64_FORMAT, num);
626         context->num = num;
627         break;
628       }
629         /* track UID (unique identifier) */
630       case GST_MATROSKA_ID_TRACKUID:{
631         guint64 num;
632
633         if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
634           break;
635
636         if (num == 0) {
637           GST_ERROR_OBJECT (demux, "Invalid TrackUID 0");
638           ret = GST_FLOW_ERROR;
639           break;
640         }
641
642         GST_DEBUG_OBJECT (demux, "TrackUID: %" G_GUINT64_FORMAT, num);
643         context->uid = num;
644         break;
645       }
646
647         /* track type (video, audio, combined, subtitle, etc.) */
648       case GST_MATROSKA_ID_TRACKTYPE:{
649         guint64 track_type;
650
651         if ((ret = gst_ebml_read_uint (ebml, &id, &track_type)) != GST_FLOW_OK) {
652           break;
653         }
654
655         if (context->type != 0 && context->type != track_type) {
656           GST_WARNING_OBJECT (demux,
657               "More than one tracktype defined in a TrackEntry - skipping");
658           break;
659         } else if (track_type < 1 || track_type > 254) {
660           GST_WARNING_OBJECT (demux, "Invalid TrackType %" G_GUINT64_FORMAT,
661               track_type);
662           break;
663         }
664
665         GST_DEBUG_OBJECT (demux, "TrackType: %" G_GUINT64_FORMAT, track_type);
666
667         /* ok, so we're actually going to reallocate this thing */
668         switch (track_type) {
669           case GST_MATROSKA_TRACK_TYPE_VIDEO:
670             gst_matroska_track_init_video_context (&context);
671             break;
672           case GST_MATROSKA_TRACK_TYPE_AUDIO:
673             gst_matroska_track_init_audio_context (&context);
674             break;
675           case GST_MATROSKA_TRACK_TYPE_SUBTITLE:
676             gst_matroska_track_init_subtitle_context (&context);
677             break;
678           case GST_MATROSKA_TRACK_TYPE_COMPLEX:
679           case GST_MATROSKA_TRACK_TYPE_LOGO:
680           case GST_MATROSKA_TRACK_TYPE_BUTTONS:
681           case GST_MATROSKA_TRACK_TYPE_CONTROL:
682           default:
683             GST_WARNING_OBJECT (demux,
684                 "Unknown or unsupported TrackType %" G_GUINT64_FORMAT,
685                 track_type);
686             context->type = 0;
687             break;
688         }
689         g_ptr_array_index (demux->common.src, demux->common.num_streams - 1)
690             = context;
691         break;
692       }
693
694         /* tracktype specific stuff for video */
695       case GST_MATROSKA_ID_TRACKVIDEO:{
696         GstMatroskaTrackVideoContext *videocontext;
697
698         DEBUG_ELEMENT_START (demux, ebml, "TrackVideo");
699
700         if (!gst_matroska_track_init_video_context (&context)) {
701           GST_WARNING_OBJECT (demux,
702               "TrackVideo element in non-video track - ignoring track");
703           ret = GST_FLOW_ERROR;
704           break;
705         } else if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
706           break;
707         }
708         videocontext = (GstMatroskaTrackVideoContext *) context;
709         g_ptr_array_index (demux->common.src, demux->common.num_streams - 1)
710             = context;
711
712         while (ret == GST_FLOW_OK &&
713             gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
714           if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
715             break;
716
717           switch (id) {
718               /* Should be one level up but some broken muxers write it here. */
719             case GST_MATROSKA_ID_TRACKDEFAULTDURATION:{
720               guint64 num;
721
722               if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
723                 break;
724
725               if (num == 0) {
726                 GST_WARNING_OBJECT (demux, "Invalid TrackDefaultDuration 0");
727                 break;
728               }
729
730               GST_DEBUG_OBJECT (demux,
731                   "TrackDefaultDuration: %" G_GUINT64_FORMAT, num);
732               context->default_duration = num;
733               break;
734             }
735
736               /* video framerate */
737               /* NOTE: This one is here only for backward compatibility.
738                * Use _TRACKDEFAULDURATION one level up. */
739             case GST_MATROSKA_ID_VIDEOFRAMERATE:{
740               gdouble num;
741
742               if ((ret = gst_ebml_read_float (ebml, &id, &num)) != GST_FLOW_OK)
743                 break;
744
745               if (num <= 0.0) {
746                 GST_WARNING_OBJECT (demux, "Invalid TrackVideoFPS %lf", num);
747                 break;
748               }
749
750               GST_DEBUG_OBJECT (demux, "TrackVideoFrameRate: %lf", num);
751               if (context->default_duration == 0)
752                 context->default_duration =
753                     gst_gdouble_to_guint64 ((gdouble) GST_SECOND * (1.0 / num));
754               videocontext->default_fps = num;
755               break;
756             }
757
758               /* width of the size to display the video at */
759             case GST_MATROSKA_ID_VIDEODISPLAYWIDTH:{
760               guint64 num;
761
762               if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
763                 break;
764
765               if (num == 0) {
766                 GST_WARNING_OBJECT (demux, "Invalid TrackVideoDisplayWidth 0");
767                 break;
768               }
769
770               GST_DEBUG_OBJECT (demux,
771                   "TrackVideoDisplayWidth: %" G_GUINT64_FORMAT, num);
772               videocontext->display_width = num;
773               break;
774             }
775
776               /* height of the size to display the video at */
777             case GST_MATROSKA_ID_VIDEODISPLAYHEIGHT:{
778               guint64 num;
779
780               if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
781                 break;
782
783               if (num == 0) {
784                 GST_WARNING_OBJECT (demux, "Invalid TrackVideoDisplayHeight 0");
785                 break;
786               }
787
788               GST_DEBUG_OBJECT (demux,
789                   "TrackVideoDisplayHeight: %" G_GUINT64_FORMAT, num);
790               videocontext->display_height = num;
791               break;
792             }
793
794               /* width of the video in the file */
795             case GST_MATROSKA_ID_VIDEOPIXELWIDTH:{
796               guint64 num;
797
798               if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
799                 break;
800
801               if (num == 0) {
802                 GST_WARNING_OBJECT (demux, "Invalid TrackVideoPixelWidth 0");
803                 break;
804               }
805
806               GST_DEBUG_OBJECT (demux,
807                   "TrackVideoPixelWidth: %" G_GUINT64_FORMAT, num);
808               videocontext->pixel_width = num;
809               break;
810             }
811
812               /* height of the video in the file */
813             case GST_MATROSKA_ID_VIDEOPIXELHEIGHT:{
814               guint64 num;
815
816               if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
817                 break;
818
819               if (num == 0) {
820                 GST_WARNING_OBJECT (demux, "Invalid TrackVideoPixelHeight 0");
821                 break;
822               }
823
824               GST_DEBUG_OBJECT (demux,
825                   "TrackVideoPixelHeight: %" G_GUINT64_FORMAT, num);
826               videocontext->pixel_height = num;
827               break;
828             }
829
830               /* whether the video is interlaced */
831             case GST_MATROSKA_ID_VIDEOFLAGINTERLACED:{
832               guint64 num;
833
834               if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
835                 break;
836
837               if (num)
838                 context->flags |= GST_MATROSKA_VIDEOTRACK_INTERLACED;
839               else
840                 context->flags &= ~GST_MATROSKA_VIDEOTRACK_INTERLACED;
841               GST_DEBUG_OBJECT (demux, "TrackVideoInterlaced: %d",
842                   (context->flags & GST_MATROSKA_VIDEOTRACK_INTERLACED) ? 1 :
843                   0);
844               break;
845             }
846
847               /* aspect ratio behaviour */
848             case GST_MATROSKA_ID_VIDEOASPECTRATIOTYPE:{
849               guint64 num;
850
851               if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
852                 break;
853
854               if (num != GST_MATROSKA_ASPECT_RATIO_MODE_FREE &&
855                   num != GST_MATROSKA_ASPECT_RATIO_MODE_KEEP &&
856                   num != GST_MATROSKA_ASPECT_RATIO_MODE_FIXED) {
857                 GST_WARNING_OBJECT (demux,
858                     "Unknown TrackVideoAspectRatioType 0x%x", (guint) num);
859                 break;
860               }
861               GST_DEBUG_OBJECT (demux,
862                   "TrackVideoAspectRatioType: %" G_GUINT64_FORMAT, num);
863               videocontext->asr_mode = num;
864               break;
865             }
866
867               /* colourspace (only matters for raw video) fourcc */
868             case GST_MATROSKA_ID_VIDEOCOLOURSPACE:{
869               guint8 *data;
870               guint64 datalen;
871
872               if ((ret =
873                       gst_ebml_read_binary (ebml, &id, &data,
874                           &datalen)) != GST_FLOW_OK)
875                 break;
876
877               if (datalen != 4) {
878                 g_free (data);
879                 GST_WARNING_OBJECT (demux,
880                     "Invalid TrackVideoColourSpace length %" G_GUINT64_FORMAT,
881                     datalen);
882                 break;
883               }
884
885               memcpy (&videocontext->fourcc, data, 4);
886               GST_DEBUG_OBJECT (demux,
887                   "TrackVideoColourSpace: %" GST_FOURCC_FORMAT,
888                   GST_FOURCC_ARGS (videocontext->fourcc));
889               g_free (data);
890               break;
891             }
892
893             default:
894               GST_WARNING_OBJECT (demux,
895                   "Unknown TrackVideo subelement 0x%x - ignoring", id);
896               /* fall through */
897             case GST_MATROSKA_ID_VIDEOSTEREOMODE:
898             case GST_MATROSKA_ID_VIDEODISPLAYUNIT:
899             case GST_MATROSKA_ID_VIDEOPIXELCROPBOTTOM:
900             case GST_MATROSKA_ID_VIDEOPIXELCROPTOP:
901             case GST_MATROSKA_ID_VIDEOPIXELCROPLEFT:
902             case GST_MATROSKA_ID_VIDEOPIXELCROPRIGHT:
903             case GST_MATROSKA_ID_VIDEOGAMMAVALUE:
904               ret = gst_ebml_read_skip (ebml);
905               break;
906           }
907         }
908
909         DEBUG_ELEMENT_STOP (demux, ebml, "TrackVideo", ret);
910         break;
911       }
912
913         /* tracktype specific stuff for audio */
914       case GST_MATROSKA_ID_TRACKAUDIO:{
915         GstMatroskaTrackAudioContext *audiocontext;
916
917         DEBUG_ELEMENT_START (demux, ebml, "TrackAudio");
918
919         if (!gst_matroska_track_init_audio_context (&context)) {
920           GST_WARNING_OBJECT (demux,
921               "TrackAudio element in non-audio track - ignoring track");
922           ret = GST_FLOW_ERROR;
923           break;
924         }
925
926         if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK)
927           break;
928
929         audiocontext = (GstMatroskaTrackAudioContext *) context;
930         g_ptr_array_index (demux->common.src, demux->common.num_streams - 1)
931             = context;
932
933         while (ret == GST_FLOW_OK &&
934             gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
935           if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
936             break;
937
938           switch (id) {
939               /* samplerate */
940             case GST_MATROSKA_ID_AUDIOSAMPLINGFREQ:{
941               gdouble num;
942
943               if ((ret = gst_ebml_read_float (ebml, &id, &num)) != GST_FLOW_OK)
944                 break;
945
946
947               if (num <= 0.0) {
948                 GST_WARNING_OBJECT (demux,
949                     "Invalid TrackAudioSamplingFrequency %lf", num);
950                 break;
951               }
952
953               GST_DEBUG_OBJECT (demux, "TrackAudioSamplingFrequency: %lf", num);
954               audiocontext->samplerate = num;
955               break;
956             }
957
958               /* bitdepth */
959             case GST_MATROSKA_ID_AUDIOBITDEPTH:{
960               guint64 num;
961
962               if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
963                 break;
964
965               if (num == 0) {
966                 GST_WARNING_OBJECT (demux, "Invalid TrackAudioBitDepth 0");
967                 break;
968               }
969
970               GST_DEBUG_OBJECT (demux, "TrackAudioBitDepth: %" G_GUINT64_FORMAT,
971                   num);
972               audiocontext->bitdepth = num;
973               break;
974             }
975
976               /* channels */
977             case GST_MATROSKA_ID_AUDIOCHANNELS:{
978               guint64 num;
979
980               if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
981                 break;
982
983               if (num == 0) {
984                 GST_WARNING_OBJECT (demux, "Invalid TrackAudioChannels 0");
985                 break;
986               }
987
988               GST_DEBUG_OBJECT (demux, "TrackAudioChannels: %" G_GUINT64_FORMAT,
989                   num);
990               audiocontext->channels = num;
991               break;
992             }
993
994             default:
995               GST_WARNING_OBJECT (demux,
996                   "Unknown TrackAudio subelement 0x%x - ignoring", id);
997               /* fall through */
998             case GST_MATROSKA_ID_AUDIOCHANNELPOSITIONS:
999             case GST_MATROSKA_ID_AUDIOOUTPUTSAMPLINGFREQ:
1000               ret = gst_ebml_read_skip (ebml);
1001               break;
1002           }
1003         }
1004
1005         DEBUG_ELEMENT_STOP (demux, ebml, "TrackAudio", ret);
1006
1007         break;
1008       }
1009
1010         /* codec identifier */
1011       case GST_MATROSKA_ID_CODECID:{
1012         gchar *text;
1013
1014         if ((ret = gst_ebml_read_ascii (ebml, &id, &text)) != GST_FLOW_OK)
1015           break;
1016
1017         GST_DEBUG_OBJECT (demux, "CodecID: %s", GST_STR_NULL (text));
1018         context->codec_id = text;
1019         break;
1020       }
1021
1022         /* codec private data */
1023       case GST_MATROSKA_ID_CODECPRIVATE:{
1024         guint8 *data;
1025         guint64 size;
1026
1027         if ((ret =
1028                 gst_ebml_read_binary (ebml, &id, &data, &size)) != GST_FLOW_OK)
1029           break;
1030
1031         context->codec_priv = data;
1032         context->codec_priv_size = size;
1033
1034         GST_DEBUG_OBJECT (demux, "CodecPrivate of size %" G_GUINT64_FORMAT,
1035             size);
1036         break;
1037       }
1038
1039         /* name of the codec */
1040       case GST_MATROSKA_ID_CODECNAME:{
1041         gchar *text;
1042
1043         if ((ret = gst_ebml_read_utf8 (ebml, &id, &text)) != GST_FLOW_OK)
1044           break;
1045
1046         GST_DEBUG_OBJECT (demux, "CodecName: %s", GST_STR_NULL (text));
1047         context->codec_name = text;
1048         break;
1049       }
1050
1051         /* name of this track */
1052       case GST_MATROSKA_ID_TRACKNAME:{
1053         gchar *text;
1054
1055         if ((ret = gst_ebml_read_utf8 (ebml, &id, &text)) != GST_FLOW_OK)
1056           break;
1057
1058         context->name = text;
1059         GST_DEBUG_OBJECT (demux, "TrackName: %s", GST_STR_NULL (text));
1060         break;
1061       }
1062
1063         /* language (matters for audio/subtitles, mostly) */
1064       case GST_MATROSKA_ID_TRACKLANGUAGE:{
1065         gchar *text;
1066
1067         if ((ret = gst_ebml_read_utf8 (ebml, &id, &text)) != GST_FLOW_OK)
1068           break;
1069
1070
1071         context->language = text;
1072
1073         /* fre-ca => fre */
1074         if (strlen (context->language) >= 4 && context->language[3] == '-')
1075           context->language[3] = '\0';
1076
1077         GST_DEBUG_OBJECT (demux, "TrackLanguage: %s",
1078             GST_STR_NULL (context->language));
1079         break;
1080       }
1081
1082         /* whether this is actually used */
1083       case GST_MATROSKA_ID_TRACKFLAGENABLED:{
1084         guint64 num;
1085
1086         if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1087           break;
1088
1089         if (num)
1090           context->flags |= GST_MATROSKA_TRACK_ENABLED;
1091         else
1092           context->flags &= ~GST_MATROSKA_TRACK_ENABLED;
1093
1094         GST_DEBUG_OBJECT (demux, "TrackEnabled: %d",
1095             (context->flags & GST_MATROSKA_TRACK_ENABLED) ? 1 : 0);
1096         break;
1097       }
1098
1099         /* whether it's the default for this track type */
1100       case GST_MATROSKA_ID_TRACKFLAGDEFAULT:{
1101         guint64 num;
1102
1103         if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1104           break;
1105
1106         if (num)
1107           context->flags |= GST_MATROSKA_TRACK_DEFAULT;
1108         else
1109           context->flags &= ~GST_MATROSKA_TRACK_DEFAULT;
1110
1111         GST_DEBUG_OBJECT (demux, "TrackDefault: %d",
1112             (context->flags & GST_MATROSKA_TRACK_ENABLED) ? 1 : 0);
1113         break;
1114       }
1115
1116         /* whether the track must be used during playback */
1117       case GST_MATROSKA_ID_TRACKFLAGFORCED:{
1118         guint64 num;
1119
1120         if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1121           break;
1122
1123         if (num)
1124           context->flags |= GST_MATROSKA_TRACK_FORCED;
1125         else
1126           context->flags &= ~GST_MATROSKA_TRACK_FORCED;
1127
1128         GST_DEBUG_OBJECT (demux, "TrackForced: %d",
1129             (context->flags & GST_MATROSKA_TRACK_ENABLED) ? 1 : 0);
1130         break;
1131       }
1132
1133         /* lacing (like MPEG, where blocks don't end/start on frame
1134          * boundaries) */
1135       case GST_MATROSKA_ID_TRACKFLAGLACING:{
1136         guint64 num;
1137
1138         if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1139           break;
1140
1141         if (num)
1142           context->flags |= GST_MATROSKA_TRACK_LACING;
1143         else
1144           context->flags &= ~GST_MATROSKA_TRACK_LACING;
1145
1146         GST_DEBUG_OBJECT (demux, "TrackLacing: %d",
1147             (context->flags & GST_MATROSKA_TRACK_ENABLED) ? 1 : 0);
1148         break;
1149       }
1150
1151         /* default length (in time) of one data block in this track */
1152       case GST_MATROSKA_ID_TRACKDEFAULTDURATION:{
1153         guint64 num;
1154
1155         if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1156           break;
1157
1158
1159         if (num == 0) {
1160           GST_WARNING_OBJECT (demux, "Invalid TrackDefaultDuration 0");
1161           break;
1162         }
1163
1164         GST_DEBUG_OBJECT (demux, "TrackDefaultDuration: %" G_GUINT64_FORMAT,
1165             num);
1166         context->default_duration = num;
1167         break;
1168       }
1169
1170       case GST_MATROSKA_ID_CONTENTENCODINGS:{
1171         ret = gst_matroska_read_common_read_track_encodings (&demux->common,
1172             ebml, context);
1173         break;
1174       }
1175
1176       case GST_MATROSKA_ID_TRACKTIMECODESCALE:{
1177         gdouble num;
1178
1179         if ((ret = gst_ebml_read_float (ebml, &id, &num)) != GST_FLOW_OK)
1180           break;
1181
1182         if (num <= 0.0) {
1183           GST_WARNING_OBJECT (demux, "Invalid TrackTimeCodeScale %lf", num);
1184           break;
1185         }
1186
1187         GST_DEBUG_OBJECT (demux, "TrackTimeCodeScale: %lf", num);
1188         context->timecodescale = num;
1189         break;
1190       }
1191
1192       default:
1193         GST_WARNING ("Unknown TrackEntry subelement 0x%x - ignoring", id);
1194         /* pass-through */
1195
1196         /* we ignore these because they're nothing useful (i.e. crap)
1197          * or simply not implemented yet. */
1198       case GST_MATROSKA_ID_TRACKMINCACHE:
1199       case GST_MATROSKA_ID_TRACKMAXCACHE:
1200       case GST_MATROSKA_ID_MAXBLOCKADDITIONID:
1201       case GST_MATROSKA_ID_TRACKATTACHMENTLINK:
1202       case GST_MATROSKA_ID_TRACKOVERLAY:
1203       case GST_MATROSKA_ID_TRACKTRANSLATE:
1204       case GST_MATROSKA_ID_TRACKOFFSET:
1205       case GST_MATROSKA_ID_CODECSETTINGS:
1206       case GST_MATROSKA_ID_CODECINFOURL:
1207       case GST_MATROSKA_ID_CODECDOWNLOADURL:
1208       case GST_MATROSKA_ID_CODECDECODEALL:
1209         ret = gst_ebml_read_skip (ebml);
1210         break;
1211     }
1212   }
1213
1214   DEBUG_ELEMENT_STOP (demux, ebml, "TrackEntry", ret);
1215
1216   /* Decode codec private data if necessary */
1217   if (context->encodings && context->encodings->len > 0 && context->codec_priv
1218       && context->codec_priv_size > 0) {
1219     if (!gst_matroska_decode_data (context->encodings,
1220             &context->codec_priv, &context->codec_priv_size,
1221             GST_MATROSKA_TRACK_ENCODING_SCOPE_CODEC_DATA, TRUE)) {
1222       GST_WARNING_OBJECT (demux, "Decoding codec private data failed");
1223       ret = GST_FLOW_ERROR;
1224     }
1225   }
1226
1227   if (context->type == 0 || context->codec_id == NULL || (ret != GST_FLOW_OK
1228           && ret != GST_FLOW_EOS)) {
1229     if (ret == GST_FLOW_OK || ret == GST_FLOW_EOS)
1230       GST_WARNING_OBJECT (ebml, "Unknown stream/codec in track entry header");
1231
1232     demux->common.num_streams--;
1233     g_ptr_array_remove_index (demux->common.src, demux->common.num_streams);
1234     g_assert (demux->common.src->len == demux->common.num_streams);
1235     if (context) {
1236       gst_matroska_track_free (context);
1237     }
1238
1239     return ret;
1240   }
1241
1242   /* now create the GStreamer connectivity */
1243   switch (context->type) {
1244     case GST_MATROSKA_TRACK_TYPE_VIDEO:{
1245       GstMatroskaTrackVideoContext *videocontext =
1246           (GstMatroskaTrackVideoContext *) context;
1247
1248       padname = g_strdup_printf ("video_%u", demux->num_v_streams++);
1249       templ = gst_element_class_get_pad_template (klass, "video_%u");
1250       caps = gst_matroska_demux_video_caps (videocontext,
1251           context->codec_id, context->codec_priv,
1252           context->codec_priv_size, &codec, &riff_fourcc);
1253
1254       if (codec) {
1255         list = gst_tag_list_new (GST_TAG_VIDEO_CODEC, codec, NULL);
1256         g_free (codec);
1257       }
1258       break;
1259     }
1260
1261     case GST_MATROSKA_TRACK_TYPE_AUDIO:{
1262       GstMatroskaTrackAudioContext *audiocontext =
1263           (GstMatroskaTrackAudioContext *) context;
1264
1265       padname = g_strdup_printf ("audio_%u", demux->num_a_streams++);
1266       templ = gst_element_class_get_pad_template (klass, "audio_%u");
1267       caps = gst_matroska_demux_audio_caps (audiocontext,
1268           context->codec_id, context->codec_priv, context->codec_priv_size,
1269           &codec, &riff_audio_fmt);
1270
1271       if (codec) {
1272         list = gst_tag_list_new (GST_TAG_AUDIO_CODEC, codec, NULL);
1273         g_free (codec);
1274       }
1275       break;
1276     }
1277
1278     case GST_MATROSKA_TRACK_TYPE_SUBTITLE:{
1279       GstMatroskaTrackSubtitleContext *subtitlecontext =
1280           (GstMatroskaTrackSubtitleContext *) context;
1281
1282       padname = g_strdup_printf ("subtitle_%u", demux->num_t_streams++);
1283       templ = gst_element_class_get_pad_template (klass, "subtitle_%u");
1284       caps = gst_matroska_demux_subtitle_caps (subtitlecontext,
1285           context->codec_id, context->codec_priv, context->codec_priv_size);
1286       break;
1287     }
1288
1289     case GST_MATROSKA_TRACK_TYPE_COMPLEX:
1290     case GST_MATROSKA_TRACK_TYPE_LOGO:
1291     case GST_MATROSKA_TRACK_TYPE_BUTTONS:
1292     case GST_MATROSKA_TRACK_TYPE_CONTROL:
1293     default:
1294       /* we should already have quit by now */
1295       g_assert_not_reached ();
1296   }
1297
1298   if ((context->language == NULL || *context->language == '\0') &&
1299       (context->type == GST_MATROSKA_TRACK_TYPE_AUDIO ||
1300           context->type == GST_MATROSKA_TRACK_TYPE_SUBTITLE)) {
1301     GST_LOG ("stream %d: language=eng (assuming default)", context->index);
1302     context->language = g_strdup ("eng");
1303   }
1304
1305   if (context->language) {
1306     const gchar *lang;
1307
1308     if (!list)
1309       list = gst_tag_list_new_empty ();
1310
1311     /* Matroska contains ISO 639-2B codes, we want ISO 639-1 */
1312     lang = gst_tag_get_language_code (context->language);
1313     gst_tag_list_add (list, GST_TAG_MERGE_REPLACE,
1314         GST_TAG_LANGUAGE_CODE, (lang) ? lang : context->language, NULL);
1315   }
1316
1317   if (caps == NULL) {
1318     GST_WARNING_OBJECT (demux, "could not determine caps for stream with "
1319         "codec_id='%s'", context->codec_id);
1320     switch (context->type) {
1321       case GST_MATROSKA_TRACK_TYPE_VIDEO:
1322         caps = gst_caps_new_empty_simple ("video/x-unknown");
1323         break;
1324       case GST_MATROSKA_TRACK_TYPE_AUDIO:
1325         caps = gst_caps_new_empty_simple ("audio/x-unknown");
1326         break;
1327       case GST_MATROSKA_TRACK_TYPE_SUBTITLE:
1328         caps = gst_caps_new_empty_simple ("application/x-subtitle-unknown");
1329         break;
1330       case GST_MATROSKA_TRACK_TYPE_COMPLEX:
1331       default:
1332         caps = gst_caps_new_empty_simple ("application/x-matroska-unknown");
1333         break;
1334     }
1335     gst_caps_set_simple (caps, "codec-id", G_TYPE_STRING, context->codec_id,
1336         NULL);
1337
1338     /* add any unrecognised riff fourcc / audio format, but after codec-id */
1339     if (context->type == GST_MATROSKA_TRACK_TYPE_AUDIO && riff_audio_fmt != 0)
1340       gst_caps_set_simple (caps, "format", G_TYPE_INT, riff_audio_fmt, NULL);
1341     else if (context->type == GST_MATROSKA_TRACK_TYPE_VIDEO && riff_fourcc != 0) {
1342       gchar *fstr = g_strdup_printf ("%" GST_FOURCC_FORMAT,
1343           GST_FOURCC_ARGS (riff_fourcc));
1344       gst_caps_set_simple (caps, "fourcc", G_TYPE_STRING, fstr, NULL);
1345       g_free (fstr);
1346     }
1347   } else if (context->stream_headers != NULL) {
1348     gst_matroska_demux_add_stream_headers_to_caps (demux,
1349         context->stream_headers, caps);
1350   }
1351
1352   /* the pad in here */
1353   context->pad = gst_pad_new_from_template (templ, padname);
1354   context->caps = caps;
1355
1356   gst_pad_set_event_function (context->pad,
1357       GST_DEBUG_FUNCPTR (gst_matroska_demux_handle_src_event));
1358   gst_pad_set_query_function (context->pad,
1359       GST_DEBUG_FUNCPTR (gst_matroska_demux_handle_src_query));
1360
1361   GST_INFO_OBJECT (demux, "Adding pad '%s' with caps %" GST_PTR_FORMAT,
1362       padname, caps);
1363
1364   context->pending_tags = list;
1365
1366   gst_pad_set_element_private (context->pad, context);
1367
1368   gst_pad_use_fixed_caps (context->pad);
1369   gst_pad_set_active (context->pad, TRUE);
1370
1371   stream_id =
1372       gst_pad_create_stream_id_printf (context->pad, GST_ELEMENT_CAST (demux),
1373       "%u", context->uid);
1374   gst_pad_push_event (context->pad, gst_event_new_stream_start (stream_id));
1375   g_free (stream_id);
1376   gst_pad_set_caps (context->pad, context->caps);
1377
1378   gst_element_add_pad (GST_ELEMENT (demux), context->pad);
1379
1380   g_free (padname);
1381
1382   /* tadaah! */
1383   return ret;
1384 }
1385
1386 static gboolean
1387 gst_matroska_demux_query (GstMatroskaDemux * demux, GstPad * pad,
1388     GstQuery * query)
1389 {
1390   gboolean res = FALSE;
1391   GstMatroskaTrackContext *context = NULL;
1392
1393   if (pad) {
1394     context = gst_pad_get_element_private (pad);
1395   }
1396
1397   switch (GST_QUERY_TYPE (query)) {
1398     case GST_QUERY_POSITION:
1399     {
1400       GstFormat format;
1401
1402       gst_query_parse_position (query, &format, NULL);
1403
1404       res = TRUE;
1405       if (format == GST_FORMAT_TIME) {
1406         GST_OBJECT_LOCK (demux);
1407         if (context)
1408           gst_query_set_position (query, GST_FORMAT_TIME,
1409               MAX (context->pos, demux->stream_start_time) -
1410               demux->stream_start_time);
1411         else
1412           gst_query_set_position (query, GST_FORMAT_TIME,
1413               MAX (demux->common.segment.position, demux->stream_start_time) -
1414               demux->stream_start_time);
1415         GST_OBJECT_UNLOCK (demux);
1416       } else if (format == GST_FORMAT_DEFAULT && context
1417           && context->default_duration) {
1418         GST_OBJECT_LOCK (demux);
1419         gst_query_set_position (query, GST_FORMAT_DEFAULT,
1420             context->pos / context->default_duration);
1421         GST_OBJECT_UNLOCK (demux);
1422       } else {
1423         GST_DEBUG_OBJECT (demux,
1424             "only position query in TIME and DEFAULT format is supported");
1425         res = FALSE;
1426       }
1427
1428       break;
1429     }
1430     case GST_QUERY_DURATION:
1431     {
1432       GstFormat format;
1433
1434       gst_query_parse_duration (query, &format, NULL);
1435
1436       res = TRUE;
1437       if (format == GST_FORMAT_TIME) {
1438         GST_OBJECT_LOCK (demux);
1439         gst_query_set_duration (query, GST_FORMAT_TIME,
1440             demux->common.segment.duration);
1441         GST_OBJECT_UNLOCK (demux);
1442       } else if (format == GST_FORMAT_DEFAULT && context
1443           && context->default_duration) {
1444         GST_OBJECT_LOCK (demux);
1445         gst_query_set_duration (query, GST_FORMAT_DEFAULT,
1446             demux->common.segment.duration / context->default_duration);
1447         GST_OBJECT_UNLOCK (demux);
1448       } else {
1449         GST_DEBUG_OBJECT (demux,
1450             "only duration query in TIME and DEFAULT format is supported");
1451         res = FALSE;
1452       }
1453       break;
1454     }
1455
1456     case GST_QUERY_SEEKING:
1457     {
1458       GstFormat fmt;
1459
1460       gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
1461       GST_OBJECT_LOCK (demux);
1462       if (fmt == GST_FORMAT_TIME) {
1463         gboolean seekable;
1464
1465         if (demux->streaming) {
1466           /* assuming we'll be able to get an index ... */
1467           seekable = demux->seekable;
1468         } else {
1469           seekable = TRUE;
1470         }
1471
1472         gst_query_set_seeking (query, GST_FORMAT_TIME, seekable,
1473             0, demux->common.segment.duration);
1474         res = TRUE;
1475       }
1476       GST_OBJECT_UNLOCK (demux);
1477       break;
1478     }
1479     default:
1480       if (pad)
1481         res = gst_pad_query_default (pad, (GstObject *) demux, query);
1482       else
1483         res =
1484             GST_ELEMENT_CLASS (parent_class)->query (GST_ELEMENT_CAST (demux),
1485             query);
1486       break;
1487   }
1488
1489   return res;
1490 }
1491
1492 static gboolean
1493 gst_matroska_demux_element_query (GstElement * element, GstQuery * query)
1494 {
1495   return gst_matroska_demux_query (GST_MATROSKA_DEMUX (element), NULL, query);
1496 }
1497
1498 static gboolean
1499 gst_matroska_demux_handle_src_query (GstPad * pad, GstObject * parent,
1500     GstQuery * query)
1501 {
1502   GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (parent);
1503
1504   return gst_matroska_demux_query (demux, pad, query);
1505 }
1506
1507 /* returns FALSE if there are no pads to deliver event to,
1508  * otherwise TRUE (whatever the outcome of event sending),
1509  * takes ownership of the passed event! */
1510 static gboolean
1511 gst_matroska_demux_send_event (GstMatroskaDemux * demux, GstEvent * event)
1512 {
1513   gboolean is_segment;
1514   gboolean ret = FALSE;
1515   gint i;
1516
1517   g_return_val_if_fail (event != NULL, FALSE);
1518
1519   GST_DEBUG_OBJECT (demux, "Sending event of type %s to all source pads",
1520       GST_EVENT_TYPE_NAME (event));
1521
1522   is_segment = (GST_EVENT_TYPE (event) == GST_EVENT_SEGMENT);
1523
1524   g_assert (demux->common.src->len == demux->common.num_streams);
1525   for (i = 0; i < demux->common.src->len; i++) {
1526     GstMatroskaTrackContext *stream;
1527
1528     stream = g_ptr_array_index (demux->common.src, i);
1529     gst_event_ref (event);
1530     gst_pad_push_event (stream->pad, event);
1531     ret = TRUE;
1532
1533     /* FIXME: send global tags before stream tags */
1534     if (G_UNLIKELY (is_segment && stream->pending_tags != NULL)) {
1535       GST_DEBUG_OBJECT (demux, "Sending pending_tags %p for pad %s:%s : %"
1536           GST_PTR_FORMAT, stream->pending_tags,
1537           GST_DEBUG_PAD_NAME (stream->pad), stream->pending_tags);
1538       gst_pad_push_event (stream->pad,
1539           gst_event_new_tag (stream->pending_tags));
1540       stream->pending_tags = NULL;
1541     }
1542   }
1543
1544   if (G_UNLIKELY (is_segment && demux->common.global_tags != NULL)) {
1545     GstEvent *tag_event;
1546     gst_tag_list_add (demux->common.global_tags, GST_TAG_MERGE_REPLACE,
1547         GST_TAG_CONTAINER_FORMAT, "Matroska", NULL);
1548     GST_DEBUG_OBJECT (demux, "Sending global_tags %p : %" GST_PTR_FORMAT,
1549         demux->common.global_tags, demux->common.global_tags);
1550
1551     tag_event = gst_event_new_tag (demux->common.global_tags);
1552
1553     for (i = 0; i < demux->common.src->len; i++) {
1554       GstMatroskaTrackContext *stream;
1555
1556       stream = g_ptr_array_index (demux->common.src, i);
1557       gst_pad_push_event (stream->pad, gst_event_ref (tag_event));
1558     }
1559
1560     gst_event_unref (tag_event);
1561     demux->common.global_tags = NULL;
1562   }
1563
1564   gst_event_unref (event);
1565   return ret;
1566 }
1567
1568 static gboolean
1569 gst_matroska_demux_element_send_event (GstElement * element, GstEvent * event)
1570 {
1571   GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (element);
1572   gboolean res;
1573
1574   g_return_val_if_fail (event != NULL, FALSE);
1575
1576   if (GST_EVENT_TYPE (event) == GST_EVENT_SEEK) {
1577     res = gst_matroska_demux_handle_seek_event (demux, NULL, event);
1578   } else {
1579     GST_WARNING_OBJECT (demux, "Unhandled event of type %s",
1580         GST_EVENT_TYPE_NAME (event));
1581     res = FALSE;
1582   }
1583   gst_event_unref (event);
1584   return res;
1585 }
1586
1587 static gboolean
1588 gst_matroska_demux_move_to_entry (GstMatroskaDemux * demux,
1589     GstMatroskaIndex * entry, gboolean reset, gboolean update)
1590 {
1591   gint i;
1592
1593   GST_OBJECT_LOCK (demux);
1594
1595   if (update) {
1596     /* seek (relative to matroska segment) */
1597     /* position might be invalid; will error when streaming resumes ... */
1598     demux->common.offset = entry->pos + demux->common.ebml_segment_start;
1599     demux->next_cluster_offset = 0;
1600
1601     GST_DEBUG_OBJECT (demux,
1602         "Seeked to offset %" G_GUINT64_FORMAT ", block %d, " "time %"
1603         GST_TIME_FORMAT, entry->pos + demux->common.ebml_segment_start,
1604         entry->block, GST_TIME_ARGS (entry->time));
1605
1606     /* update the time */
1607     gst_matroska_read_common_reset_streams (&demux->common, entry->time, TRUE);
1608     demux->common.segment.position = entry->time;
1609     demux->seek_block = entry->block;
1610     demux->seek_first = TRUE;
1611     demux->last_stop_end = GST_CLOCK_TIME_NONE;
1612   }
1613
1614   for (i = 0; i < demux->common.src->len; i++) {
1615     GstMatroskaTrackContext *stream = g_ptr_array_index (demux->common.src, i);
1616
1617     if (reset) {
1618       stream->to_offset = G_MAXINT64;
1619     } else {
1620       if (stream->from_offset != -1)
1621         stream->to_offset = stream->from_offset;
1622     }
1623     stream->from_offset = -1;
1624     stream->from_time = GST_CLOCK_TIME_NONE;
1625   }
1626
1627   GST_OBJECT_UNLOCK (demux);
1628
1629   return TRUE;
1630 }
1631
1632 static gint
1633 gst_matroska_cluster_compare (gint64 * i1, gint64 * i2)
1634 {
1635   if (*i1 < *i2)
1636     return -1;
1637   else if (*i1 > *i2)
1638     return 1;
1639   else
1640     return 0;
1641 }
1642
1643 /* searches for a cluster start from @pos,
1644  * return GST_FLOW_OK and cluster position in @pos if found */
1645 static GstFlowReturn
1646 gst_matroska_demux_search_cluster (GstMatroskaDemux * demux, gint64 * pos)
1647 {
1648   gint64 newpos = *pos;
1649   gint64 orig_offset;
1650   GstFlowReturn ret = GST_FLOW_OK;
1651   const guint chunk = 64 * 1024;
1652   GstBuffer *buf = NULL;
1653   GstMapInfo map;
1654   gpointer data = NULL;
1655   gsize size;
1656   guint64 length;
1657   guint32 id;
1658   guint needed;
1659
1660   orig_offset = demux->common.offset;
1661
1662   GST_LOG_OBJECT (demux, "searching cluster following offset %" G_GINT64_FORMAT,
1663       *pos);
1664
1665   if (demux->clusters) {
1666     gint64 *cpos;
1667
1668     cpos = gst_util_array_binary_search (demux->clusters->data,
1669         demux->clusters->len, sizeof (gint64),
1670         (GCompareDataFunc) gst_matroska_cluster_compare,
1671         GST_SEARCH_MODE_AFTER, pos, NULL);
1672     /* sanity check */
1673     if (cpos) {
1674       GST_DEBUG_OBJECT (demux,
1675           "cluster reported at offset %" G_GINT64_FORMAT, *cpos);
1676       demux->common.offset = *cpos;
1677       ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
1678           GST_ELEMENT_CAST (demux), &id, &length, &needed);
1679       if (ret == GST_FLOW_OK && id == GST_MATROSKA_ID_CLUSTER) {
1680         newpos = *cpos;
1681         goto exit;
1682       }
1683     }
1684   }
1685
1686   /* read in at newpos and scan for ebml cluster id */
1687   while (1) {
1688     GstByteReader reader;
1689     gint cluster_pos;
1690
1691     if (buf != NULL) {
1692       gst_buffer_unmap (buf, &map);
1693       gst_buffer_unref (buf);
1694       buf = NULL;
1695     }
1696     ret = gst_pad_pull_range (demux->common.sinkpad, newpos, chunk, &buf);
1697     if (ret != GST_FLOW_OK)
1698       break;
1699     GST_DEBUG_OBJECT (demux,
1700         "read buffer size %" G_GSIZE_FORMAT " at offset %" G_GINT64_FORMAT,
1701         gst_buffer_get_size (buf), newpos);
1702     gst_buffer_map (buf, &map, GST_MAP_READ);
1703     data = map.data;
1704     size = map.size;
1705     gst_byte_reader_init (&reader, data, size);
1706   resume:
1707     cluster_pos = gst_byte_reader_masked_scan_uint32 (&reader, 0xffffffff,
1708         GST_MATROSKA_ID_CLUSTER, 0, gst_byte_reader_get_remaining (&reader));
1709     if (cluster_pos >= 0) {
1710       newpos += cluster_pos;
1711       /* prepare resuming at next byte */
1712       if (!gst_byte_reader_skip (&reader, cluster_pos + 1)) {
1713         GST_DEBUG_OBJECT (demux, "Need more data -> continue");
1714         continue;
1715       }
1716       GST_DEBUG_OBJECT (demux,
1717           "found cluster ebml id at offset %" G_GINT64_FORMAT, newpos);
1718       /* extra checks whether we really sync'ed to a cluster:
1719        * - either it is the first and only cluster
1720        * - either there is a cluster after this one
1721        * - either cluster length is undefined
1722        */
1723       /* ok if first cluster (there may not a subsequent one) */
1724       if (newpos == demux->first_cluster_offset) {
1725         GST_DEBUG_OBJECT (demux, "cluster is first cluster -> OK");
1726         break;
1727       }
1728       demux->common.offset = newpos;
1729       ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
1730           GST_ELEMENT_CAST (demux), &id, &length, &needed);
1731       if (ret != GST_FLOW_OK) {
1732         GST_DEBUG_OBJECT (demux, "need more data -> continue");
1733         continue;
1734       }
1735       g_assert (id == GST_MATROSKA_ID_CLUSTER);
1736       GST_DEBUG_OBJECT (demux, "cluster size %" G_GUINT64_FORMAT ", prefix %d",
1737           length, needed);
1738       /* ok if undefined length or first cluster */
1739       if (length == GST_EBML_SIZE_UNKNOWN || length == G_MAXUINT64) {
1740         GST_DEBUG_OBJECT (demux, "cluster has undefined length -> OK");
1741         break;
1742       }
1743       /* skip cluster */
1744       demux->common.offset += length + needed;
1745       ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
1746           GST_ELEMENT_CAST (demux), &id, &length, &needed);
1747       if (ret != GST_FLOW_OK)
1748         goto resume;
1749       GST_DEBUG_OBJECT (demux, "next element is %scluster",
1750           id == GST_MATROSKA_ID_CLUSTER ? "" : "not ");
1751       if (id == GST_MATROSKA_ID_CLUSTER)
1752         break;
1753       /* not ok, resume */
1754       goto resume;
1755     } else {
1756       /* partial cluster id may have been in tail of buffer */
1757       newpos += MAX (gst_byte_reader_get_remaining (&reader), 4) - 3;
1758     }
1759   }
1760
1761   if (buf) {
1762     gst_buffer_unmap (buf, &map);
1763     gst_buffer_unref (buf);
1764     buf = NULL;
1765   }
1766
1767 exit:
1768   demux->common.offset = orig_offset;
1769   *pos = newpos;
1770   return ret;
1771 }
1772
1773 /* bisect and scan through file for cluster starting before @time,
1774  * returns fake index entry with corresponding info on cluster */
1775 static GstMatroskaIndex *
1776 gst_matroska_demux_search_pos (GstMatroskaDemux * demux, GstClockTime time)
1777 {
1778   GstMatroskaIndex *entry = NULL;
1779   GstMatroskaReadState current_state;
1780   GstClockTime otime, prev_cluster_time, current_cluster_time, cluster_time;
1781   gint64 opos, newpos, startpos = 0, current_offset;
1782   gint64 prev_cluster_offset = -1, current_cluster_offset, cluster_offset;
1783   const guint chunk = 64 * 1024;
1784   GstFlowReturn ret;
1785   guint64 length;
1786   guint32 id;
1787   guint needed;
1788
1789   /* (under)estimate new position, resync using cluster ebml id,
1790    * and scan forward to appropriate cluster
1791    * (and re-estimate if need to go backward) */
1792
1793   prev_cluster_time = GST_CLOCK_TIME_NONE;
1794
1795   /* store some current state */
1796   current_state = demux->common.state;
1797   g_return_val_if_fail (current_state == GST_MATROSKA_READ_STATE_DATA, NULL);
1798
1799   current_cluster_offset = demux->cluster_offset;
1800   current_cluster_time = demux->cluster_time;
1801   current_offset = demux->common.offset;
1802
1803   demux->common.state = GST_MATROSKA_READ_STATE_SCANNING;
1804
1805   /* estimate using start and current position */
1806   GST_OBJECT_LOCK (demux);
1807   opos = demux->common.offset - demux->common.ebml_segment_start;
1808   otime = demux->common.segment.position;
1809   GST_OBJECT_UNLOCK (demux);
1810
1811   /* sanitize */
1812   time = MAX (time, demux->stream_start_time);
1813
1814   /* avoid division by zero in first estimation below */
1815   if (otime <= demux->stream_start_time)
1816     otime = time;
1817
1818 retry:
1819   GST_LOG_OBJECT (demux,
1820       "opos: %" G_GUINT64_FORMAT ", otime: %" GST_TIME_FORMAT ", %"
1821       GST_TIME_FORMAT " in stream time (start %" GST_TIME_FORMAT "), time %"
1822       GST_TIME_FORMAT, opos, GST_TIME_ARGS (otime),
1823       GST_TIME_ARGS (otime - demux->stream_start_time),
1824       GST_TIME_ARGS (demux->stream_start_time), GST_TIME_ARGS (time));
1825   newpos =
1826       gst_util_uint64_scale (opos - demux->common.ebml_segment_start,
1827       time - demux->stream_start_time,
1828       otime - demux->stream_start_time) - chunk;
1829   if (newpos < 0)
1830     newpos = 0;
1831   /* favour undershoot */
1832   newpos = newpos * 90 / 100;
1833   newpos += demux->common.ebml_segment_start;
1834
1835   GST_DEBUG_OBJECT (demux,
1836       "estimated offset for %" GST_TIME_FORMAT ": %" G_GINT64_FORMAT,
1837       GST_TIME_ARGS (time), newpos);
1838
1839   /* and at least start scanning before previous scan start to avoid looping */
1840   startpos = startpos * 90 / 100;
1841   if (startpos && startpos < newpos)
1842     newpos = startpos;
1843
1844   /* read in at newpos and scan for ebml cluster id */
1845   startpos = newpos;
1846   while (1) {
1847
1848     ret = gst_matroska_demux_search_cluster (demux, &newpos);
1849     if (ret == GST_FLOW_EOS) {
1850       /* heuristic HACK */
1851       newpos = startpos * 80 / 100;
1852       GST_DEBUG_OBJECT (demux, "EOS; "
1853           "new estimated offset for %" GST_TIME_FORMAT ": %" G_GINT64_FORMAT,
1854           GST_TIME_ARGS (time), newpos);
1855       startpos = newpos;
1856       continue;
1857     } else if (ret != GST_FLOW_OK) {
1858       goto exit;
1859     } else {
1860       break;
1861     }
1862   }
1863
1864   /* then start scanning and parsing for cluster time,
1865    * re-estimate if overshoot, otherwise next cluster and so on */
1866   demux->common.offset = newpos;
1867   demux->cluster_time = cluster_time = GST_CLOCK_TIME_NONE;
1868   while (1) {
1869     guint64 cluster_size = 0;
1870
1871     /* peek and parse some elements */
1872     ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
1873         GST_ELEMENT_CAST (demux), &id, &length, &needed);
1874     if (ret != GST_FLOW_OK)
1875       goto error;
1876     GST_LOG_OBJECT (demux, "Offset %" G_GUINT64_FORMAT ", Element id 0x%x, "
1877         "size %" G_GUINT64_FORMAT ", needed %d", demux->common.offset, id,
1878         length, needed);
1879     ret = gst_matroska_demux_parse_id (demux, id, length, needed);
1880     if (ret != GST_FLOW_OK)
1881       goto error;
1882
1883     if (id == GST_MATROSKA_ID_CLUSTER) {
1884       cluster_time = GST_CLOCK_TIME_NONE;
1885       if (length == G_MAXUINT64)
1886         cluster_size = 0;
1887       else
1888         cluster_size = length + needed;
1889     }
1890     if (demux->cluster_time != GST_CLOCK_TIME_NONE &&
1891         cluster_time == GST_CLOCK_TIME_NONE) {
1892       cluster_time = demux->cluster_time * demux->common.time_scale;
1893       cluster_offset = demux->cluster_offset;
1894       GST_DEBUG_OBJECT (demux, "found cluster at offset %" G_GINT64_FORMAT
1895           " with time %" GST_TIME_FORMAT, cluster_offset,
1896           GST_TIME_ARGS (cluster_time));
1897       if (cluster_time > time) {
1898         GST_DEBUG_OBJECT (demux, "overshot target");
1899         /* cluster overshoots */
1900         if (cluster_offset == demux->first_cluster_offset) {
1901           /* but no prev one */
1902           GST_DEBUG_OBJECT (demux, "but using first cluster anyway");
1903           prev_cluster_time = cluster_time;
1904           prev_cluster_offset = cluster_offset;
1905           break;
1906         }
1907         if (prev_cluster_time != GST_CLOCK_TIME_NONE) {
1908           /* prev cluster did not overshoot, so prev cluster is target */
1909           break;
1910         } else {
1911           /* re-estimate using this new position info */
1912           opos = cluster_offset;
1913           otime = cluster_time;
1914           goto retry;
1915         }
1916       } else {
1917         /* cluster undershoots, goto next one */
1918         prev_cluster_time = cluster_time;
1919         prev_cluster_offset = cluster_offset;
1920         /* skip cluster if length is defined,
1921          * otherwise will be skippingly parsed into */
1922         if (cluster_size) {
1923           GST_DEBUG_OBJECT (demux, "skipping to next cluster");
1924           demux->common.offset = cluster_offset + cluster_size;
1925           demux->cluster_time = GST_CLOCK_TIME_NONE;
1926         } else {
1927           GST_DEBUG_OBJECT (demux, "parsing/skipping cluster elements");
1928         }
1929       }
1930     }
1931     continue;
1932
1933   error:
1934     if (ret == GST_FLOW_EOS) {
1935       if (prev_cluster_time != GST_CLOCK_TIME_NONE)
1936         break;
1937     }
1938     goto exit;
1939   }
1940
1941   entry = g_new0 (GstMatroskaIndex, 1);
1942   entry->time = prev_cluster_time;
1943   entry->pos = prev_cluster_offset - demux->common.ebml_segment_start;
1944   GST_DEBUG_OBJECT (demux, "simulated index entry; time %" GST_TIME_FORMAT
1945       ", pos %" G_GUINT64_FORMAT, GST_TIME_ARGS (entry->time), entry->pos);
1946
1947 exit:
1948
1949   /* restore some state */
1950   demux->cluster_offset = current_cluster_offset;
1951   demux->cluster_time = current_cluster_time;
1952   demux->common.offset = current_offset;
1953   demux->common.state = current_state;
1954
1955   return entry;
1956 }
1957
1958 static gboolean
1959 gst_matroska_demux_handle_seek_event (GstMatroskaDemux * demux,
1960     GstPad * pad, GstEvent * event)
1961 {
1962   GstMatroskaIndex *entry = NULL;
1963   GstMatroskaIndex scan_entry;
1964   GstSeekFlags flags;
1965   GstSeekType cur_type, stop_type;
1966   GstFormat format;
1967   gboolean flush, keyunit, before, after, snap_next;
1968   gdouble rate;
1969   gint64 cur, stop;
1970   GstMatroskaTrackContext *track = NULL;
1971   GstSegment seeksegment = { 0, };
1972   gboolean update = TRUE;
1973   gboolean pad_locked = FALSE;
1974
1975   if (pad)
1976     track = gst_pad_get_element_private (pad);
1977
1978   gst_event_parse_seek (event, &rate, &format, &flags, &cur_type, &cur,
1979       &stop_type, &stop);
1980
1981   /* we can only seek on time */
1982   if (format != GST_FORMAT_TIME) {
1983     GST_DEBUG_OBJECT (demux, "Can only seek on TIME");
1984     return FALSE;
1985   }
1986
1987   /* copy segment, we need this because we still need the old
1988    * segment when we close the current segment. */
1989   memcpy (&seeksegment, &demux->common.segment, sizeof (GstSegment));
1990
1991   /* pull mode without index means that the actual duration is not known,
1992    * we might be playing a file that's still being recorded
1993    * so, invalidate our current duration, which is only a moving target,
1994    * and should not be used to clamp anything */
1995   if (!demux->streaming && !demux->common.index && demux->invalid_duration) {
1996     seeksegment.duration = GST_CLOCK_TIME_NONE;
1997   }
1998
1999   if (event) {
2000     GST_DEBUG_OBJECT (demux, "configuring seek");
2001     gst_segment_do_seek (&seeksegment, rate, format, flags,
2002         cur_type, cur, stop_type, stop, &update);
2003     /* compensate for clip start time, but only for SET seeks,
2004      * otherwise it is already part of the segments */
2005     if (GST_CLOCK_TIME_IS_VALID (demux->stream_start_time)) {
2006       if (cur_type == GST_SEEK_TYPE_SET) {
2007         if (rate > 0.0)
2008           seeksegment.position += demux->stream_start_time;
2009         seeksegment.start += demux->stream_start_time;
2010       }
2011       if (stop_type == GST_SEEK_TYPE_SET
2012           && GST_CLOCK_TIME_IS_VALID (seeksegment.stop)) {
2013         if (rate < 0.0)
2014           seeksegment.position += demux->stream_start_time;
2015         seeksegment.stop += demux->stream_start_time;
2016       }
2017     }
2018   }
2019
2020   /* restore segment duration (if any effect),
2021    * would be determined again when parsing, but anyway ... */
2022   seeksegment.duration = demux->common.segment.duration;
2023
2024   flush = ! !(flags & GST_SEEK_FLAG_FLUSH);
2025   keyunit = ! !(flags & GST_SEEK_FLAG_KEY_UNIT);
2026   after = ! !(flags & GST_SEEK_FLAG_SNAP_AFTER);
2027   before = ! !(flags & GST_SEEK_FLAG_SNAP_BEFORE);
2028
2029   /* always do full update if flushing,
2030    * otherwise problems might arise downstream with missing keyframes etc */
2031   update = update || flush;
2032
2033   GST_DEBUG_OBJECT (demux, "New segment %" GST_SEGMENT_FORMAT, &seeksegment);
2034
2035   /* check sanity before we start flushing and all that */
2036   snap_next = after && !before;
2037   if (seeksegment.rate < 0)
2038     snap_next = !snap_next;
2039   GST_OBJECT_LOCK (demux);
2040   track = gst_matroska_read_common_get_seek_track (&demux->common, track);
2041   if ((entry = gst_matroska_read_common_do_index_seek (&demux->common, track,
2042               seeksegment.position, &demux->seek_index, &demux->seek_entry,
2043               snap_next)) == NULL) {
2044     /* pull mode without index can scan later on */
2045     if (demux->streaming) {
2046       GST_DEBUG_OBJECT (demux, "No matching seek entry in index");
2047       GST_OBJECT_UNLOCK (demux);
2048       return FALSE;
2049     } else if (rate < 0.0) {
2050       /* FIXME: We should build an index during playback or when scanning
2051        * that can be used here. The reverse playback code requires seek_index
2052        * and seek_entry to be set!
2053        */
2054       GST_DEBUG_OBJECT (demux,
2055           "No matching seek entry in index, needed for reverse playback");
2056       GST_OBJECT_UNLOCK (demux);
2057       return FALSE;
2058     }
2059   }
2060   GST_DEBUG_OBJECT (demux, "Seek position looks sane");
2061   GST_OBJECT_UNLOCK (demux);
2062
2063   if (!update) {
2064     /* only have to update some segment,
2065      * but also still have to honour flush and so on */
2066     GST_DEBUG_OBJECT (demux, "... no update");
2067     /* bad goto, bad ... */
2068     goto next;
2069   }
2070
2071   if (demux->streaming)
2072     goto finish;
2073
2074 next:
2075   if (flush) {
2076     GST_DEBUG_OBJECT (demux, "Starting flush");
2077     gst_pad_push_event (demux->common.sinkpad, gst_event_new_flush_start ());
2078     gst_matroska_demux_send_event (demux, gst_event_new_flush_start ());
2079   } else {
2080     GST_DEBUG_OBJECT (demux, "Non-flushing seek, pausing task");
2081     gst_pad_pause_task (demux->common.sinkpad);
2082   }
2083   /* ouch */
2084   if (!update)
2085     goto exit;
2086
2087   /* now grab the stream lock so that streaming cannot continue, for
2088    * non flushing seeks when the element is in PAUSED this could block
2089    * forever. */
2090   GST_DEBUG_OBJECT (demux, "Waiting for streaming to stop");
2091   GST_PAD_STREAM_LOCK (demux->common.sinkpad);
2092   pad_locked = TRUE;
2093
2094   /* pull mode without index can do some scanning */
2095   if (!demux->streaming && !entry) {
2096     /* need to stop flushing upstream as we need it next */
2097     if (flush)
2098       gst_pad_push_event (demux->common.sinkpad,
2099           gst_event_new_flush_stop (TRUE));
2100     entry = gst_matroska_demux_search_pos (demux, seeksegment.position);
2101     /* keep local copy */
2102     if (entry) {
2103       scan_entry = *entry;
2104       g_free (entry);
2105       entry = &scan_entry;
2106     } else {
2107       GST_DEBUG_OBJECT (demux, "Scan failed to find matching position");
2108       if (flush)
2109         gst_matroska_demux_send_event (demux, gst_event_new_flush_stop (TRUE));
2110       goto seek_error;
2111     }
2112   }
2113
2114 finish:
2115   if (keyunit) {
2116     GST_DEBUG_OBJECT (demux, "seek to key unit, adjusting segment start from %"
2117         GST_TIME_FORMAT " to %" GST_TIME_FORMAT,
2118         GST_TIME_ARGS (seeksegment.start), GST_TIME_ARGS (entry->time));
2119     seeksegment.start = MAX (entry->time, demux->stream_start_time);
2120     seeksegment.position = seeksegment.start;
2121     seeksegment.time = seeksegment.start - demux->stream_start_time;
2122   }
2123
2124   if (demux->streaming) {
2125     GST_OBJECT_LOCK (demux);
2126     /* track real position we should start at */
2127     GST_DEBUG_OBJECT (demux, "storing segment start");
2128     demux->requested_seek_time = seeksegment.position;
2129     demux->seek_offset = entry->pos + demux->common.ebml_segment_start;
2130     GST_OBJECT_UNLOCK (demux);
2131     /* need to seek to cluster start to pick up cluster time */
2132     /* upstream takes care of flushing and all that
2133      * ... and newsegment event handling takes care of the rest */
2134     return perform_seek_to_offset (demux, rate,
2135         entry->pos + demux->common.ebml_segment_start);
2136   }
2137
2138 exit:
2139   if (flush) {
2140     GST_DEBUG_OBJECT (demux, "Stopping flush");
2141     gst_pad_push_event (demux->common.sinkpad, gst_event_new_flush_stop (TRUE));
2142     gst_matroska_demux_send_event (demux, gst_event_new_flush_stop (TRUE));
2143   }
2144
2145   GST_OBJECT_LOCK (demux);
2146   /* now update the real segment info */
2147   GST_DEBUG_OBJECT (demux, "Committing new seek segment");
2148   memcpy (&demux->common.segment, &seeksegment, sizeof (GstSegment));
2149   GST_OBJECT_UNLOCK (demux);
2150
2151   /* update some (segment) state */
2152   if (!gst_matroska_demux_move_to_entry (demux, entry, TRUE, update))
2153     goto seek_error;
2154
2155   /* notify start of new segment */
2156   if (demux->common.segment.flags & GST_SEEK_FLAG_SEGMENT) {
2157     GstMessage *msg;
2158
2159     msg = gst_message_new_segment_start (GST_OBJECT (demux),
2160         GST_FORMAT_TIME, demux->common.segment.start);
2161     gst_element_post_message (GST_ELEMENT (demux), msg);
2162   }
2163
2164   GST_OBJECT_LOCK (demux);
2165   if (demux->new_segment)
2166     gst_event_unref (demux->new_segment);
2167
2168   /* On port from 0.10, discarded !update (for segment.update) here, FIXME? */
2169   demux->new_segment = gst_event_new_segment (&demux->common.segment);
2170   if (demux->common.segment.rate < 0 && demux->common.segment.stop == -1)
2171     demux->to_time = demux->common.segment.position;
2172   else
2173     demux->to_time = GST_CLOCK_TIME_NONE;
2174   GST_OBJECT_UNLOCK (demux);
2175
2176   /* restart our task since it might have been stopped when we did the
2177    * flush. */
2178   gst_pad_start_task (demux->common.sinkpad,
2179       (GstTaskFunction) gst_matroska_demux_loop, demux->common.sinkpad, NULL);
2180
2181   /* streaming can continue now */
2182   if (pad_locked) {
2183     GST_PAD_STREAM_UNLOCK (demux->common.sinkpad);
2184   }
2185
2186   return TRUE;
2187
2188 seek_error:
2189   {
2190     if (pad_locked) {
2191       GST_PAD_STREAM_UNLOCK (demux->common.sinkpad);
2192     }
2193     GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL), ("Got a seek error"));
2194     return FALSE;
2195   }
2196 }
2197
2198 /*
2199  * Handle whether we can perform the seek event or if we have to let the chain
2200  * function handle seeks to build the seek indexes first.
2201  */
2202 static gboolean
2203 gst_matroska_demux_handle_seek_push (GstMatroskaDemux * demux, GstPad * pad,
2204     GstEvent * event)
2205 {
2206   GstSeekFlags flags;
2207   GstSeekType cur_type, stop_type;
2208   GstFormat format;
2209   gdouble rate;
2210   gint64 cur, stop;
2211
2212   gst_event_parse_seek (event, &rate, &format, &flags, &cur_type, &cur,
2213       &stop_type, &stop);
2214
2215   /* sanity checks */
2216
2217   /* we can only seek on time */
2218   if (format != GST_FORMAT_TIME) {
2219     GST_DEBUG_OBJECT (demux, "Can only seek on TIME");
2220     return FALSE;
2221   }
2222
2223   if (stop_type != GST_SEEK_TYPE_NONE && stop != GST_CLOCK_TIME_NONE) {
2224     GST_DEBUG_OBJECT (demux, "Seek end-time not supported in streaming mode");
2225     return FALSE;
2226   }
2227
2228   if (!(flags & GST_SEEK_FLAG_FLUSH)) {
2229     GST_DEBUG_OBJECT (demux,
2230         "Non-flushing seek not supported in streaming mode");
2231     return FALSE;
2232   }
2233
2234   if (flags & GST_SEEK_FLAG_SEGMENT) {
2235     GST_DEBUG_OBJECT (demux, "Segment seek not supported in streaming mode");
2236     return FALSE;
2237   }
2238
2239   /* check for having parsed index already */
2240   if (!demux->common.index_parsed) {
2241     gboolean building_index;
2242     guint64 offset = 0;
2243
2244     if (!demux->index_offset) {
2245       GST_DEBUG_OBJECT (demux, "no index (location); no seek in push mode");
2246       return FALSE;
2247     }
2248
2249     GST_OBJECT_LOCK (demux);
2250     /* handle the seek event in the chain function */
2251     demux->common.state = GST_MATROSKA_READ_STATE_SEEK;
2252     /* no more seek can be issued until state reset to _DATA */
2253
2254     /* copy the event */
2255     if (demux->seek_event)
2256       gst_event_unref (demux->seek_event);
2257     demux->seek_event = gst_event_ref (event);
2258
2259     /* set the building_index flag so that only one thread can setup the
2260      * structures for index seeking. */
2261     building_index = demux->building_index;
2262     if (!building_index) {
2263       demux->building_index = TRUE;
2264       offset = demux->index_offset;
2265     }
2266     GST_OBJECT_UNLOCK (demux);
2267
2268     if (!building_index) {
2269       /* seek to the first subindex or legacy index */
2270       GST_INFO_OBJECT (demux, "Seeking to Cues at %" G_GUINT64_FORMAT, offset);
2271       return perform_seek_to_offset (demux, rate, offset);
2272     }
2273
2274     /* well, we are handling it already */
2275     return TRUE;
2276   }
2277
2278   /* delegate to tweaked regular seek */
2279   return gst_matroska_demux_handle_seek_event (demux, pad, event);
2280 }
2281
2282 static gboolean
2283 gst_matroska_demux_handle_src_event (GstPad * pad, GstObject * parent,
2284     GstEvent * event)
2285 {
2286   GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (parent);
2287   gboolean res = TRUE;
2288
2289   switch (GST_EVENT_TYPE (event)) {
2290     case GST_EVENT_SEEK:
2291       /* no seeking until we are (safely) ready */
2292       if (demux->common.state != GST_MATROSKA_READ_STATE_DATA) {
2293         GST_DEBUG_OBJECT (demux, "not ready for seeking yet");
2294         return FALSE;
2295       }
2296       if (!demux->streaming)
2297         res = gst_matroska_demux_handle_seek_event (demux, pad, event);
2298       else
2299         res = gst_matroska_demux_handle_seek_push (demux, pad, event);
2300       gst_event_unref (event);
2301       break;
2302
2303     case GST_EVENT_QOS:
2304     {
2305       GstMatroskaTrackContext *context = gst_pad_get_element_private (pad);
2306       if (context->type == GST_MATROSKA_TRACK_TYPE_VIDEO) {
2307         GstMatroskaTrackVideoContext *videocontext =
2308             (GstMatroskaTrackVideoContext *) context;
2309         gdouble proportion;
2310         GstClockTimeDiff diff;
2311         GstClockTime timestamp;
2312
2313         gst_event_parse_qos (event, NULL, &proportion, &diff, &timestamp);
2314
2315         GST_OBJECT_LOCK (demux);
2316         videocontext->earliest_time = timestamp + diff;
2317         GST_OBJECT_UNLOCK (demux);
2318       }
2319       res = TRUE;
2320       gst_event_unref (event);
2321       break;
2322     }
2323
2324     case GST_EVENT_TOC_SELECT:
2325     {
2326       char *uid = NULL;
2327       GstTocEntry *entry = NULL;
2328       GstEvent *seek_event;
2329       gint64 start_pos;
2330
2331       if (!demux->common.toc) {
2332         GST_DEBUG_OBJECT (demux, "no TOC to select");
2333         return FALSE;
2334       } else {
2335         gst_event_parse_toc_select (event, &uid);
2336         if (uid != NULL) {
2337           GST_OBJECT_LOCK (demux);
2338           entry = gst_toc_find_entry (demux->common.toc, uid);
2339           if (entry == NULL) {
2340             GST_OBJECT_UNLOCK (demux);
2341             GST_WARNING_OBJECT (demux, "no TOC entry with given UID: %s", uid);
2342             res = FALSE;
2343           } else {
2344             gst_toc_entry_get_start_stop_times (entry, &start_pos, NULL);
2345             GST_OBJECT_UNLOCK (demux);
2346             seek_event = gst_event_new_seek (1.0,
2347                 GST_FORMAT_TIME,
2348                 GST_SEEK_FLAG_FLUSH,
2349                 GST_SEEK_TYPE_SET, start_pos, GST_SEEK_TYPE_SET, -1);
2350             res = gst_matroska_demux_handle_seek_event (demux, pad, seek_event);
2351             gst_event_unref (seek_event);
2352           }
2353           g_free (uid);
2354         } else {
2355           GST_WARNING_OBJECT (demux, "received empty TOC select event");
2356           res = FALSE;
2357         }
2358       }
2359       gst_event_unref (event);
2360       break;
2361     }
2362
2363       /* events we don't need to handle */
2364     case GST_EVENT_NAVIGATION:
2365       gst_event_unref (event);
2366       res = FALSE;
2367       break;
2368
2369     case GST_EVENT_LATENCY:
2370     default:
2371       res = gst_pad_push_event (demux->common.sinkpad, event);
2372       break;
2373   }
2374
2375   return res;
2376 }
2377
2378 static GstFlowReturn
2379 gst_matroska_demux_seek_to_previous_keyframe (GstMatroskaDemux * demux)
2380 {
2381   GstFlowReturn ret = GST_FLOW_EOS;
2382   gboolean done = TRUE;
2383   gint i;
2384
2385   g_return_val_if_fail (demux->seek_index, GST_FLOW_EOS);
2386   g_return_val_if_fail (demux->seek_entry < demux->seek_index->len,
2387       GST_FLOW_EOS);
2388
2389   GST_DEBUG_OBJECT (demux, "locating previous keyframe");
2390
2391   if (!demux->seek_entry) {
2392     GST_DEBUG_OBJECT (demux, "no earlier index entry");
2393     goto exit;
2394   }
2395
2396   for (i = 0; i < demux->common.src->len; i++) {
2397     GstMatroskaTrackContext *stream = g_ptr_array_index (demux->common.src, i);
2398
2399     GST_DEBUG_OBJECT (demux, "segment start %" GST_TIME_FORMAT
2400         ", stream %d at %" GST_TIME_FORMAT,
2401         GST_TIME_ARGS (demux->common.segment.start), stream->index,
2402         GST_TIME_ARGS (stream->from_time));
2403     if (GST_CLOCK_TIME_IS_VALID (stream->from_time)) {
2404       if (stream->from_time > demux->common.segment.start) {
2405         GST_DEBUG_OBJECT (demux, "stream %d not finished yet", stream->index);
2406         done = FALSE;
2407       }
2408     } else {
2409       /* nothing pushed for this stream;
2410        * likely seek entry did not start at keyframe, so all was skipped.
2411        * So we need an earlier entry */
2412       done = FALSE;
2413     }
2414   }
2415
2416   if (!done) {
2417     GstMatroskaIndex *entry;
2418
2419     entry = &g_array_index (demux->seek_index, GstMatroskaIndex,
2420         --demux->seek_entry);
2421     if (!gst_matroska_demux_move_to_entry (demux, entry, FALSE, TRUE))
2422       goto exit;
2423
2424     ret = GST_FLOW_OK;
2425   }
2426
2427 exit:
2428   return ret;
2429 }
2430
2431 static GstFlowReturn
2432 gst_matroska_demux_parse_tracks (GstMatroskaDemux * demux, GstEbmlRead * ebml)
2433 {
2434   GstFlowReturn ret = GST_FLOW_OK;
2435   guint32 id;
2436
2437   DEBUG_ELEMENT_START (demux, ebml, "Tracks");
2438
2439   if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
2440     DEBUG_ELEMENT_STOP (demux, ebml, "Tracks", ret);
2441     return ret;
2442   }
2443
2444   while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
2445     if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
2446       break;
2447
2448     switch (id) {
2449         /* one track within the "all-tracks" header */
2450       case GST_MATROSKA_ID_TRACKENTRY:
2451         ret = gst_matroska_demux_add_stream (demux, ebml);
2452         break;
2453
2454       default:
2455         ret = gst_matroska_read_common_parse_skip (&demux->common, ebml,
2456             "Track", id);
2457         break;
2458     }
2459   }
2460   DEBUG_ELEMENT_STOP (demux, ebml, "Tracks", ret);
2461
2462   demux->tracks_parsed = TRUE;
2463
2464   return ret;
2465 }
2466
2467 /*
2468  * Read signed/unsigned "EBML" numbers.
2469  * Return: number of bytes processed.
2470  */
2471
2472 static gint
2473 gst_matroska_ebmlnum_uint (guint8 * data, guint size, guint64 * num)
2474 {
2475   gint len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
2476   guint64 total;
2477
2478   if (size <= 0) {
2479     return -1;
2480   }
2481
2482   total = data[0];
2483   while (read <= 8 && !(total & len_mask)) {
2484     read++;
2485     len_mask >>= 1;
2486   }
2487   if (read > 8)
2488     return -1;
2489
2490   if ((total &= (len_mask - 1)) == len_mask - 1)
2491     num_ffs++;
2492   if (size < read)
2493     return -1;
2494   while (n < read) {
2495     if (data[n] == 0xff)
2496       num_ffs++;
2497     total = (total << 8) | data[n];
2498     n++;
2499   }
2500
2501   if (read == num_ffs && total != 0)
2502     *num = G_MAXUINT64;
2503   else
2504     *num = total;
2505
2506   return read;
2507 }
2508
2509 static gint
2510 gst_matroska_ebmlnum_sint (guint8 * data, guint size, gint64 * num)
2511 {
2512   guint64 unum;
2513   gint res;
2514
2515   /* read as unsigned number first */
2516   if ((res = gst_matroska_ebmlnum_uint (data, size, &unum)) < 0)
2517     return -1;
2518
2519   /* make signed */
2520   if (unum == G_MAXUINT64)
2521     *num = G_MAXINT64;
2522   else
2523     *num = unum - ((1 << ((7 * res) - 1)) - 1);
2524
2525   return res;
2526 }
2527
2528 /*
2529  * Mostly used for subtitles. We add void filler data for each
2530  * lagging stream to make sure we don't deadlock.
2531  */
2532
2533 static void
2534 gst_matroska_demux_sync_streams (GstMatroskaDemux * demux)
2535 {
2536   gint stream_nr;
2537
2538   GST_OBJECT_LOCK (demux);
2539
2540   GST_LOG_OBJECT (demux, "Sync to %" GST_TIME_FORMAT,
2541       GST_TIME_ARGS (demux->common.segment.position));
2542
2543   g_assert (demux->common.num_streams == demux->common.src->len);
2544   for (stream_nr = 0; stream_nr < demux->common.src->len; stream_nr++) {
2545     GstMatroskaTrackContext *context;
2546
2547     context = g_ptr_array_index (demux->common.src, stream_nr);
2548
2549     GST_LOG_OBJECT (demux,
2550         "Checking for resync on stream %d (%" GST_TIME_FORMAT ")", stream_nr,
2551         GST_TIME_ARGS (context->pos));
2552
2553     if (G_LIKELY (context->type != GST_MATROSKA_TRACK_TYPE_SUBTITLE)) {
2554       GST_LOG_OBJECT (demux, "Skipping sync on non-subtitle stream");
2555       continue;
2556     }
2557
2558     /* does it lag? 0.5 seconds is a random threshold...
2559      * lag need only be considered if we have advanced into requested segment */
2560     if (GST_CLOCK_TIME_IS_VALID (context->pos) &&
2561         GST_CLOCK_TIME_IS_VALID (demux->common.segment.position) &&
2562         demux->common.segment.position > demux->common.segment.start &&
2563         context->pos + (GST_SECOND / 2) < demux->common.segment.position) {
2564
2565       GstEvent *event;
2566       guint64 start = context->pos;
2567       guint64 stop = demux->common.segment.position - (GST_SECOND / 2);
2568
2569       GST_DEBUG_OBJECT (demux,
2570           "Synchronizing stream %d with other by advancing time from %"
2571           GST_TIME_FORMAT " to %" GST_TIME_FORMAT, stream_nr,
2572           GST_TIME_ARGS (start), GST_TIME_ARGS (stop));
2573
2574       context->pos = stop;
2575
2576       event = gst_event_new_gap (start, stop - start);
2577       GST_OBJECT_UNLOCK (demux);
2578       gst_pad_push_event (context->pad, event);
2579       GST_OBJECT_LOCK (demux);
2580     }
2581   }
2582
2583   GST_OBJECT_UNLOCK (demux);
2584 }
2585
2586 static GstFlowReturn
2587 gst_matroska_demux_push_stream_headers (GstMatroskaDemux * demux,
2588     GstMatroskaTrackContext * stream)
2589 {
2590   GstFlowReturn ret = GST_FLOW_OK;
2591   gint i, num;
2592
2593   num = gst_buffer_list_length (stream->stream_headers);
2594   for (i = 0; i < num; ++i) {
2595     GstBuffer *buf;
2596
2597     buf = gst_buffer_list_get (stream->stream_headers, i);
2598     buf = gst_buffer_copy (buf);
2599
2600     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_HEADER);
2601
2602     if (stream->set_discont) {
2603       GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
2604       stream->set_discont = FALSE;
2605     }
2606
2607     /* push out all headers in one go and use last flow return */
2608     ret = gst_pad_push (stream->pad, buf);
2609   }
2610
2611   /* don't need these any  longer */
2612   gst_buffer_list_unref (stream->stream_headers);
2613   stream->stream_headers = NULL;
2614
2615   /* combine flows */
2616   ret = gst_matroska_demux_combine_flows (demux, stream, ret);
2617
2618   return ret;
2619 }
2620
2621 static void
2622 gst_matroska_demux_push_dvd_clut_change_event (GstMatroskaDemux * demux,
2623     GstMatroskaTrackContext * stream)
2624 {
2625   gchar *buf, *start;
2626
2627   g_assert (!strcmp (stream->codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_VOBSUB));
2628
2629   if (!stream->codec_priv)
2630     return;
2631
2632   /* ideally, VobSub private data should be parsed and stored more convenient
2633    * elsewhere, but for now, only interested in a small part */
2634
2635   /* make sure we have terminating 0 */
2636   buf = g_strndup (stream->codec_priv, stream->codec_priv_size);
2637
2638   /* just locate and parse palette part */
2639   start = strstr (buf, "palette:");
2640   if (start) {
2641     gint i;
2642     guint32 clut[16];
2643     guint32 col;
2644     guint8 r, g, b, y, u, v;
2645
2646     start += 8;
2647     while (g_ascii_isspace (*start))
2648       start++;
2649     for (i = 0; i < 16; i++) {
2650       if (sscanf (start, "%06x", &col) != 1)
2651         break;
2652       start += 6;
2653       while ((*start == ',') || g_ascii_isspace (*start))
2654         start++;
2655       /* sigh, need to convert this from vobsub pseudo-RGB to YUV */
2656       r = (col >> 16) & 0xff;
2657       g = (col >> 8) & 0xff;
2658       b = col & 0xff;
2659       y = CLAMP ((0.1494 * r + 0.6061 * g + 0.2445 * b) * 219 / 255 + 16, 0,
2660           255);
2661       u = CLAMP (0.6066 * r - 0.4322 * g - 0.1744 * b + 128, 0, 255);
2662       v = CLAMP (-0.08435 * r - 0.3422 * g + 0.4266 * b + 128, 0, 255);
2663       clut[i] = (y << 16) | (u << 8) | v;
2664     }
2665
2666     /* got them all without problems; build and send event */
2667     if (i == 16) {
2668       GstStructure *s;
2669
2670       s = gst_structure_new ("application/x-gst-dvd", "event", G_TYPE_STRING,
2671           "dvd-spu-clut-change", "clut00", G_TYPE_INT, clut[0], "clut01",
2672           G_TYPE_INT, clut[1], "clut02", G_TYPE_INT, clut[2], "clut03",
2673           G_TYPE_INT, clut[3], "clut04", G_TYPE_INT, clut[4], "clut05",
2674           G_TYPE_INT, clut[5], "clut06", G_TYPE_INT, clut[6], "clut07",
2675           G_TYPE_INT, clut[7], "clut08", G_TYPE_INT, clut[8], "clut09",
2676           G_TYPE_INT, clut[9], "clut10", G_TYPE_INT, clut[10], "clut11",
2677           G_TYPE_INT, clut[11], "clut12", G_TYPE_INT, clut[12], "clut13",
2678           G_TYPE_INT, clut[13], "clut14", G_TYPE_INT, clut[14], "clut15",
2679           G_TYPE_INT, clut[15], NULL);
2680
2681       gst_pad_push_event (stream->pad,
2682           gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM, s));
2683     }
2684   }
2685   g_free (buf);
2686 }
2687
2688 static GstFlowReturn
2689 gst_matroska_demux_add_mpeg_seq_header (GstElement * element,
2690     GstMatroskaTrackContext * stream, GstBuffer ** buf)
2691 {
2692   guint8 *seq_header;
2693   guint seq_header_len;
2694   guint32 header, tmp;
2695
2696   if (stream->codec_state) {
2697     seq_header = stream->codec_state;
2698     seq_header_len = stream->codec_state_size;
2699   } else if (stream->codec_priv) {
2700     seq_header = stream->codec_priv;
2701     seq_header_len = stream->codec_priv_size;
2702   } else {
2703     return GST_FLOW_OK;
2704   }
2705
2706   /* Sequence header only needed for keyframes */
2707   if (GST_BUFFER_FLAG_IS_SET (*buf, GST_BUFFER_FLAG_DELTA_UNIT))
2708     return GST_FLOW_OK;
2709
2710   if (gst_buffer_get_size (*buf) < 4)
2711     return GST_FLOW_OK;
2712
2713   gst_buffer_extract (*buf, 0, &tmp, sizeof (guint32));
2714   header = GUINT32_FROM_BE (tmp);
2715
2716   /* Sequence start code, if not found prepend */
2717   if (header != 0x000001b3) {
2718     GstBuffer *newbuf;
2719
2720     GST_DEBUG_OBJECT (element, "Prepending MPEG sequence header");
2721
2722     newbuf = gst_buffer_new_wrapped (g_memdup (seq_header, seq_header_len),
2723         seq_header_len);
2724
2725     gst_buffer_copy_into (newbuf, *buf, GST_BUFFER_COPY_TIMESTAMPS |
2726         GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_MEMORY, 0,
2727         gst_buffer_get_size (*buf));
2728
2729     gst_buffer_unref (*buf);
2730     *buf = newbuf;
2731   }
2732
2733   return GST_FLOW_OK;
2734 }
2735
2736 static GstFlowReturn
2737 gst_matroska_demux_add_wvpk_header (GstElement * element,
2738     GstMatroskaTrackContext * stream, GstBuffer ** buf)
2739 {
2740   GstMatroskaTrackAudioContext *audiocontext =
2741       (GstMatroskaTrackAudioContext *) stream;
2742   GstBuffer *newbuf = NULL;
2743   GstMapInfo map, outmap;
2744   guint8 *buf_data, *data;
2745   Wavpack4Header wvh;
2746
2747   wvh.ck_id[0] = 'w';
2748   wvh.ck_id[1] = 'v';
2749   wvh.ck_id[2] = 'p';
2750   wvh.ck_id[3] = 'k';
2751
2752   wvh.version = GST_READ_UINT16_LE (stream->codec_priv);
2753   wvh.track_no = 0;
2754   wvh.index_no = 0;
2755   wvh.total_samples = -1;
2756   wvh.block_index = audiocontext->wvpk_block_index;
2757
2758   if (audiocontext->channels <= 2) {
2759     guint32 block_samples, tmp;
2760     gsize size = gst_buffer_get_size (*buf);
2761
2762     gst_buffer_extract (*buf, 0, &tmp, sizeof (guint32));
2763     block_samples = GUINT32_FROM_LE (tmp);
2764     /* we need to reconstruct the header of the wavpack block */
2765
2766     /* -20 because ck_size is the size of the wavpack block -8
2767      * and lace_size is the size of the wavpack block + 12
2768      * (the three guint32 of the header that already are in the buffer) */
2769     wvh.ck_size = size + sizeof (Wavpack4Header) - 20;
2770
2771     /* block_samples, flags and crc are already in the buffer */
2772     newbuf = gst_buffer_new_allocate (NULL, sizeof (Wavpack4Header) - 12, NULL);
2773
2774     gst_buffer_map (newbuf, &outmap, GST_MAP_WRITE);
2775     data = outmap.data;
2776     data[0] = 'w';
2777     data[1] = 'v';
2778     data[2] = 'p';
2779     data[3] = 'k';
2780     GST_WRITE_UINT32_LE (data + 4, wvh.ck_size);
2781     GST_WRITE_UINT16_LE (data + 8, wvh.version);
2782     GST_WRITE_UINT8 (data + 10, wvh.track_no);
2783     GST_WRITE_UINT8 (data + 11, wvh.index_no);
2784     GST_WRITE_UINT32_LE (data + 12, wvh.total_samples);
2785     GST_WRITE_UINT32_LE (data + 16, wvh.block_index);
2786
2787     /* Append data from buf: */
2788     gst_buffer_copy_into (newbuf, *buf, GST_BUFFER_COPY_TIMESTAMPS |
2789         GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_MEMORY, 0, size);
2790
2791     gst_buffer_unref (*buf);
2792     *buf = newbuf;
2793     audiocontext->wvpk_block_index += block_samples;
2794   } else {
2795     guint8 *outdata = NULL;
2796     guint outpos = 0;
2797     gsize buf_size, size, out_size = 0;
2798     guint32 block_samples, flags, crc, blocksize;
2799
2800     gst_buffer_map (*buf, &map, GST_MAP_READ);
2801     buf_data = map.data;
2802     buf_size = map.size;
2803
2804     if (buf_size < 4) {
2805       GST_ERROR_OBJECT (element, "Too small wavpack buffer");
2806       gst_buffer_unmap (*buf, &map);
2807       return GST_FLOW_ERROR;
2808     }
2809
2810     data = buf_data;
2811     size = buf_size;
2812
2813     block_samples = GST_READ_UINT32_LE (data);
2814     data += 4;
2815     size -= 4;
2816
2817     while (size > 12) {
2818       flags = GST_READ_UINT32_LE (data);
2819       data += 4;
2820       size -= 4;
2821       crc = GST_READ_UINT32_LE (data);
2822       data += 4;
2823       size -= 4;
2824       blocksize = GST_READ_UINT32_LE (data);
2825       data += 4;
2826       size -= 4;
2827
2828       if (blocksize == 0 || size < blocksize)
2829         break;
2830
2831       g_assert ((newbuf == NULL) == (outdata == NULL));
2832
2833       if (newbuf == NULL) {
2834         out_size = sizeof (Wavpack4Header) + blocksize;
2835         newbuf = gst_buffer_new_allocate (NULL, out_size, NULL);
2836
2837         gst_buffer_copy_into (newbuf, *buf,
2838             GST_BUFFER_COPY_TIMESTAMPS | GST_BUFFER_COPY_FLAGS, 0, -1);
2839
2840         outpos = 0;
2841         gst_buffer_map (newbuf, &outmap, GST_MAP_WRITE);
2842         outdata = outmap.data;
2843       } else {
2844         gst_buffer_unmap (newbuf, &outmap);
2845         out_size += sizeof (Wavpack4Header) + blocksize;
2846         gst_buffer_set_size (newbuf, out_size);
2847         gst_buffer_map (newbuf, &outmap, GST_MAP_WRITE);
2848         outdata = outmap.data;
2849       }
2850
2851       outdata[outpos] = 'w';
2852       outdata[outpos + 1] = 'v';
2853       outdata[outpos + 2] = 'p';
2854       outdata[outpos + 3] = 'k';
2855       outpos += 4;
2856
2857       GST_WRITE_UINT32_LE (outdata + outpos,
2858           blocksize + sizeof (Wavpack4Header) - 8);
2859       GST_WRITE_UINT16_LE (outdata + outpos + 4, wvh.version);
2860       GST_WRITE_UINT8 (outdata + outpos + 6, wvh.track_no);
2861       GST_WRITE_UINT8 (outdata + outpos + 7, wvh.index_no);
2862       GST_WRITE_UINT32_LE (outdata + outpos + 8, wvh.total_samples);
2863       GST_WRITE_UINT32_LE (outdata + outpos + 12, wvh.block_index);
2864       GST_WRITE_UINT32_LE (outdata + outpos + 16, block_samples);
2865       GST_WRITE_UINT32_LE (outdata + outpos + 20, flags);
2866       GST_WRITE_UINT32_LE (outdata + outpos + 24, crc);
2867       outpos += 28;
2868
2869       g_memmove (outdata + outpos, data, blocksize);
2870       outpos += blocksize;
2871       data += blocksize;
2872       size -= blocksize;
2873     }
2874     gst_buffer_unmap (*buf, &map);
2875     gst_buffer_unref (*buf);
2876
2877     if (newbuf)
2878       gst_buffer_unmap (newbuf, &outmap);
2879
2880     *buf = newbuf;
2881     audiocontext->wvpk_block_index += block_samples;
2882   }
2883
2884   return GST_FLOW_OK;
2885 }
2886
2887 /* @text must be null-terminated */
2888 static gboolean
2889 gst_matroska_demux_subtitle_chunk_has_tag (GstElement * element,
2890     const gchar * text)
2891 {
2892   gchar *tag;
2893
2894   g_return_val_if_fail (text != NULL, FALSE);
2895
2896   /* yes, this might all lead to false positives ... */
2897   tag = (gchar *) text;
2898   while ((tag = strchr (tag, '<'))) {
2899     tag++;
2900     if (*tag != '\0' && *(tag + 1) == '>') {
2901       /* some common convenience ones */
2902       /* maybe any character will do here ? */
2903       switch (*tag) {
2904         case 'b':
2905         case 'i':
2906         case 'u':
2907         case 's':
2908           return TRUE;
2909         default:
2910           return FALSE;
2911       }
2912     }
2913   }
2914
2915   if (strstr (text, "<span"))
2916     return TRUE;
2917
2918   return FALSE;
2919 }
2920
2921 static GstFlowReturn
2922 gst_matroska_demux_check_subtitle_buffer (GstElement * element,
2923     GstMatroskaTrackContext * stream, GstBuffer ** buf)
2924 {
2925   GstMatroskaTrackSubtitleContext *sub_stream;
2926   const gchar *encoding;
2927   GError *err = NULL;
2928   GstBuffer *newbuf;
2929   gchar *utf8;
2930   GstMapInfo map;
2931
2932   sub_stream = (GstMatroskaTrackSubtitleContext *) stream;
2933
2934   if (!gst_buffer_get_size (*buf) || !gst_buffer_map (*buf, &map, GST_MAP_READ))
2935     return GST_FLOW_OK;
2936
2937   if (!sub_stream->invalid_utf8) {
2938     if (g_utf8_validate ((gchar *) map.data, map.size, NULL)) {
2939       goto next;
2940     }
2941     GST_WARNING_OBJECT (element, "subtitle stream %" G_GUINT64_FORMAT
2942         " is not valid UTF-8, this is broken according to the matroska"
2943         " specification", stream->num);
2944     sub_stream->invalid_utf8 = TRUE;
2945   }
2946
2947   /* file with broken non-UTF8 subtitle, do the best we can do to fix it */
2948   encoding = g_getenv ("GST_SUBTITLE_ENCODING");
2949   if (encoding == NULL || *encoding == '\0') {
2950     /* if local encoding is UTF-8 and no encoding specified
2951      * via the environment variable, assume ISO-8859-15 */
2952     if (g_get_charset (&encoding)) {
2953       encoding = "ISO-8859-15";
2954     }
2955   }
2956
2957   utf8 =
2958       g_convert_with_fallback ((gchar *) map.data, map.size, "UTF-8", encoding,
2959       (char *) "*", NULL, NULL, &err);
2960
2961   if (err) {
2962     GST_LOG_OBJECT (element, "could not convert string from '%s' to UTF-8: %s",
2963         encoding, err->message);
2964     g_error_free (err);
2965     g_free (utf8);
2966
2967     /* invalid input encoding, fall back to ISO-8859-15 (always succeeds) */
2968     encoding = "ISO-8859-15";
2969     utf8 =
2970         g_convert_with_fallback ((gchar *) map.data, map.size, "UTF-8",
2971         encoding, (char *) "*", NULL, NULL, NULL);
2972   }
2973
2974   GST_LOG_OBJECT (element, "converted subtitle text from %s to UTF-8 %s",
2975       encoding, (err) ? "(using ISO-8859-15 as fallback)" : "");
2976
2977   if (utf8 == NULL)
2978     utf8 = g_strdup ("invalid subtitle");
2979
2980   newbuf = gst_buffer_new_wrapped (utf8, strlen (utf8));
2981   gst_buffer_copy_into (newbuf, *buf,
2982       GST_BUFFER_COPY_TIMESTAMPS | GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_META,
2983       0, -1);
2984   gst_buffer_unmap (*buf, &map);
2985   gst_buffer_unref (*buf);
2986
2987   *buf = newbuf;
2988   gst_buffer_map (*buf, &map, GST_MAP_READ);
2989
2990 next:
2991   if (sub_stream->check_markup) {
2992     /* caps claim markup text, so we need to escape text,
2993      * except if text is already markup and then needs no further escaping */
2994     sub_stream->seen_markup_tag = sub_stream->seen_markup_tag ||
2995         gst_matroska_demux_subtitle_chunk_has_tag (element, (gchar *) map.data);
2996
2997     if (!sub_stream->seen_markup_tag) {
2998       utf8 = g_markup_escape_text ((gchar *) map.data, map.size);
2999
3000       newbuf = gst_buffer_new_wrapped (utf8, strlen (utf8));
3001       gst_buffer_copy_into (newbuf, *buf,
3002           GST_BUFFER_COPY_TIMESTAMPS | GST_BUFFER_COPY_FLAGS |
3003           GST_BUFFER_COPY_META, 0, -1);
3004       gst_buffer_unmap (*buf, &map);
3005       gst_buffer_unref (*buf);
3006
3007       *buf = newbuf;
3008     }
3009   }
3010
3011   return GST_FLOW_OK;
3012 }
3013
3014 static GstFlowReturn
3015 gst_matroska_demux_check_aac (GstElement * element,
3016     GstMatroskaTrackContext * stream, GstBuffer ** buf)
3017 {
3018   guint8 data[2];
3019   guint size;
3020
3021   gst_buffer_extract (*buf, 0, data, 2);
3022   size = gst_buffer_get_size (*buf);
3023
3024   if (size > 2 && data[0] == 0xff && (data[1] >> 4 == 0x0f)) {
3025     GstStructure *s;
3026
3027     /* tss, ADTS data, remove codec_data
3028      * still assume it is at least parsed */
3029     stream->caps = gst_caps_make_writable (stream->caps);
3030     s = gst_caps_get_structure (stream->caps, 0);
3031     g_assert (s);
3032     gst_structure_remove_field (s, "codec_data");
3033     gst_pad_set_caps (stream->pad, stream->caps);
3034     GST_DEBUG_OBJECT (element, "ADTS AAC audio data; removing codec-data, "
3035         "new caps: %" GST_PTR_FORMAT, stream->caps);
3036   }
3037
3038   /* disable subsequent checking */
3039   stream->postprocess_frame = NULL;
3040
3041   return GST_FLOW_OK;
3042 }
3043
3044 static GstBuffer *
3045 gst_matroska_demux_align_buffer (GstMatroskaDemux * demux,
3046     GstBuffer * buffer, gsize alignment)
3047 {
3048   GstMapInfo map;
3049
3050   gst_buffer_map (buffer, &map, GST_MAP_READ);
3051
3052   if (map.size < sizeof (guintptr)) {
3053     gst_buffer_unmap (buffer, &map);
3054     return buffer;
3055   }
3056
3057   if (((guintptr) map.data) & (alignment - 1)) {
3058     GstBuffer *new_buffer;
3059     GstAllocationParams params = { 0, alignment - 1, 0, 0, };
3060
3061     new_buffer = gst_buffer_new_allocate (NULL,
3062         gst_buffer_get_size (buffer), &params);
3063
3064     /* Copy data "by hand", so ensure alignment is kept: */
3065     gst_buffer_fill (new_buffer, 0, map.data, map.size);
3066
3067     gst_buffer_copy_into (new_buffer, buffer, GST_BUFFER_COPY_METADATA, 0, -1);
3068     GST_DEBUG_OBJECT (demux,
3069         "We want output aligned on %" G_GSIZE_FORMAT ", reallocated",
3070         alignment);
3071
3072     gst_buffer_unmap (buffer, &map);
3073     gst_buffer_unref (buffer);
3074
3075     return new_buffer;
3076   }
3077
3078   gst_buffer_unmap (buffer, &map);
3079   return buffer;
3080 }
3081
3082 static GstFlowReturn
3083 gst_matroska_demux_parse_blockgroup_or_simpleblock (GstMatroskaDemux * demux,
3084     GstEbmlRead * ebml, guint64 cluster_time, guint64 cluster_offset,
3085     gboolean is_simpleblock)
3086 {
3087   GstMatroskaTrackContext *stream = NULL;
3088   GstFlowReturn ret = GST_FLOW_OK;
3089   gboolean readblock = FALSE;
3090   guint32 id;
3091   guint64 block_duration = -1;
3092   GstBuffer *buf = NULL;
3093   GstMapInfo map;
3094   gint stream_num = -1, n, laces = 0;
3095   guint size = 0;
3096   gint *lace_size = NULL;
3097   gint64 time = 0;
3098   gint flags = 0;
3099   gint64 referenceblock = 0;
3100   gint64 offset;
3101
3102   offset = gst_ebml_read_get_offset (ebml);
3103
3104   while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
3105     if (!is_simpleblock) {
3106       if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK) {
3107         goto data_error;
3108       }
3109     } else {
3110       id = GST_MATROSKA_ID_SIMPLEBLOCK;
3111     }
3112
3113     switch (id) {
3114         /* one block inside the group. Note, block parsing is one
3115          * of the harder things, so this code is a bit complicated.
3116          * See http://www.matroska.org/ for documentation. */
3117       case GST_MATROSKA_ID_SIMPLEBLOCK:
3118       case GST_MATROSKA_ID_BLOCK:
3119       {
3120         guint64 num;
3121         guint8 *data;
3122
3123         if (buf) {
3124           gst_buffer_unmap (buf, &map);
3125           gst_buffer_unref (buf);
3126           buf = NULL;
3127         }
3128         if ((ret = gst_ebml_read_buffer (ebml, &id, &buf)) != GST_FLOW_OK)
3129           break;
3130
3131         gst_buffer_map (buf, &map, GST_MAP_READ);
3132         data = map.data;
3133         size = map.size;
3134
3135         /* first byte(s): blocknum */
3136         if ((n = gst_matroska_ebmlnum_uint (data, size, &num)) < 0)
3137           goto data_error;
3138         data += n;
3139         size -= n;
3140
3141         /* fetch stream from num */
3142         stream_num = gst_matroska_read_common_stream_from_num (&demux->common,
3143             num);
3144         if (G_UNLIKELY (size < 3)) {
3145           GST_WARNING_OBJECT (demux, "Invalid size %u", size);
3146           /* non-fatal, try next block(group) */
3147           ret = GST_FLOW_OK;
3148           goto done;
3149         } else if (G_UNLIKELY (stream_num < 0 ||
3150                 stream_num >= demux->common.num_streams)) {
3151           /* let's not give up on a stray invalid track number */
3152           GST_WARNING_OBJECT (demux,
3153               "Invalid stream %d for track number %" G_GUINT64_FORMAT
3154               "; ignoring block", stream_num, num);
3155           goto done;
3156         }
3157
3158         stream = g_ptr_array_index (demux->common.src, stream_num);
3159
3160         /* time (relative to cluster time) */
3161         time = ((gint16) GST_READ_UINT16_BE (data));
3162         data += 2;
3163         size -= 2;
3164         flags = GST_READ_UINT8 (data);
3165         data += 1;
3166         size -= 1;
3167
3168         GST_LOG_OBJECT (demux, "time %" G_GUINT64_FORMAT ", flags %d", time,
3169             flags);
3170
3171         switch ((flags & 0x06) >> 1) {
3172           case 0x0:            /* no lacing */
3173             laces = 1;
3174             lace_size = g_new (gint, 1);
3175             lace_size[0] = size;
3176             break;
3177
3178           case 0x1:            /* xiph lacing */
3179           case 0x2:            /* fixed-size lacing */
3180           case 0x3:            /* EBML lacing */
3181             if (size == 0)
3182               goto invalid_lacing;
3183             laces = GST_READ_UINT8 (data) + 1;
3184             data += 1;
3185             size -= 1;
3186             lace_size = g_new0 (gint, laces);
3187
3188             switch ((flags & 0x06) >> 1) {
3189               case 0x1:        /* xiph lacing */  {
3190                 guint temp, total = 0;
3191
3192                 for (n = 0; ret == GST_FLOW_OK && n < laces - 1; n++) {
3193                   while (1) {
3194                     if (size == 0)
3195                       goto invalid_lacing;
3196                     temp = GST_READ_UINT8 (data);
3197                     lace_size[n] += temp;
3198                     data += 1;
3199                     size -= 1;
3200                     if (temp != 0xff)
3201                       break;
3202                   }
3203                   total += lace_size[n];
3204                 }
3205                 lace_size[n] = size - total;
3206                 break;
3207               }
3208
3209               case 0x2:        /* fixed-size lacing */
3210                 for (n = 0; n < laces; n++)
3211                   lace_size[n] = size / laces;
3212                 break;
3213
3214               case 0x3:        /* EBML lacing */  {
3215                 guint total;
3216
3217                 if ((n = gst_matroska_ebmlnum_uint (data, size, &num)) < 0)
3218                   goto data_error;
3219                 data += n;
3220                 size -= n;
3221                 total = lace_size[0] = num;
3222                 for (n = 1; ret == GST_FLOW_OK && n < laces - 1; n++) {
3223                   gint64 snum;
3224                   gint r;
3225
3226                   if ((r = gst_matroska_ebmlnum_sint (data, size, &snum)) < 0)
3227                     goto data_error;
3228                   data += r;
3229                   size -= r;
3230                   lace_size[n] = lace_size[n - 1] + snum;
3231                   total += lace_size[n];
3232                 }
3233                 if (n < laces)
3234                   lace_size[n] = size - total;
3235                 break;
3236               }
3237             }
3238             break;
3239         }
3240
3241         if (stream->send_stream_headers) {
3242           if (stream->stream_headers != NULL) {
3243             ret = gst_matroska_demux_push_stream_headers (demux, stream);
3244           } else {
3245             /* FIXME: perhaps we can just disable and skip this stream then */
3246             GST_ELEMENT_ERROR (demux, STREAM, DECODE, (NULL),
3247                 ("Failed to extract stream headers from codec private data"));
3248           }
3249           stream->send_stream_headers = FALSE;
3250         }
3251
3252         if (stream->send_dvd_event) {
3253           gst_matroska_demux_push_dvd_clut_change_event (demux, stream);
3254           /* FIXME: should we send this event again after (flushing) seek ? */
3255           stream->send_dvd_event = FALSE;
3256         }
3257
3258         if (ret != GST_FLOW_OK)
3259           break;
3260
3261         readblock = TRUE;
3262         break;
3263       }
3264
3265       case GST_MATROSKA_ID_BLOCKDURATION:{
3266         ret = gst_ebml_read_uint (ebml, &id, &block_duration);
3267         GST_DEBUG_OBJECT (demux, "BlockDuration: %" G_GUINT64_FORMAT,
3268             block_duration);
3269         break;
3270       }
3271
3272       case GST_MATROSKA_ID_REFERENCEBLOCK:{
3273         ret = gst_ebml_read_sint (ebml, &id, &referenceblock);
3274         GST_DEBUG_OBJECT (demux, "ReferenceBlock: %" G_GINT64_FORMAT,
3275             referenceblock);
3276         break;
3277       }
3278
3279       case GST_MATROSKA_ID_CODECSTATE:{
3280         guint8 *data;
3281         guint64 data_len = 0;
3282
3283         if ((ret =
3284                 gst_ebml_read_binary (ebml, &id, &data,
3285                     &data_len)) != GST_FLOW_OK)
3286           break;
3287
3288         if (G_UNLIKELY (stream == NULL)) {
3289           GST_WARNING_OBJECT (demux,
3290               "Unexpected CodecState subelement - ignoring");
3291           break;
3292         }
3293
3294         g_free (stream->codec_state);
3295         stream->codec_state = data;
3296         stream->codec_state_size = data_len;
3297
3298         /* Decode if necessary */
3299         if (stream->encodings && stream->encodings->len > 0
3300             && stream->codec_state && stream->codec_state_size > 0) {
3301           if (!gst_matroska_decode_data (stream->encodings,
3302                   &stream->codec_state, &stream->codec_state_size,
3303                   GST_MATROSKA_TRACK_ENCODING_SCOPE_CODEC_DATA, TRUE)) {
3304             GST_WARNING_OBJECT (demux, "Decoding codec state failed");
3305           }
3306         }
3307
3308         GST_DEBUG_OBJECT (demux, "CodecState of %" G_GSIZE_FORMAT " bytes",
3309             stream->codec_state_size);
3310         break;
3311       }
3312
3313       default:
3314         ret = gst_matroska_read_common_parse_skip (&demux->common, ebml,
3315             "BlockGroup", id);
3316         break;
3317
3318       case GST_MATROSKA_ID_BLOCKVIRTUAL:
3319       case GST_MATROSKA_ID_BLOCKADDITIONS:
3320       case GST_MATROSKA_ID_REFERENCEPRIORITY:
3321       case GST_MATROSKA_ID_REFERENCEVIRTUAL:
3322       case GST_MATROSKA_ID_SLICES:
3323         GST_DEBUG_OBJECT (demux,
3324             "Skipping BlockGroup subelement 0x%x - ignoring", id);
3325         ret = gst_ebml_read_skip (ebml);
3326         break;
3327     }
3328
3329     if (is_simpleblock)
3330       break;
3331   }
3332
3333   /* reading a number or so could have failed */
3334   if (ret != GST_FLOW_OK)
3335     goto data_error;
3336
3337   if (ret == GST_FLOW_OK && readblock) {
3338     gboolean invisible_frame = FALSE;
3339     gboolean delta_unit = FALSE;
3340     guint64 duration = 0;
3341     gint64 lace_time = 0;
3342
3343     stream = g_ptr_array_index (demux->common.src, stream_num);
3344
3345     if (cluster_time != GST_CLOCK_TIME_NONE) {
3346       /* FIXME: What to do with negative timestamps? Give timestamp 0 or -1?
3347        * Drop unless the lace contains timestamp 0? */
3348       if (time < 0 && (-time) > cluster_time) {
3349         lace_time = 0;
3350       } else {
3351         if (stream->timecodescale == 1.0)
3352           lace_time = (cluster_time + time) * demux->common.time_scale;
3353         else
3354           lace_time =
3355               gst_util_guint64_to_gdouble ((cluster_time + time) *
3356               demux->common.time_scale) * stream->timecodescale;
3357       }
3358     } else {
3359       lace_time = GST_CLOCK_TIME_NONE;
3360     }
3361
3362     /* need to refresh segment info ASAP */
3363     if (GST_CLOCK_TIME_IS_VALID (lace_time) && demux->need_segment) {
3364       GstSegment *segment = &demux->common.segment;
3365       guint64 clace_time;
3366
3367       if (!GST_CLOCK_TIME_IS_VALID (demux->stream_start_time)) {
3368         demux->stream_start_time = lace_time;
3369         GST_DEBUG_OBJECT (demux,
3370             "Setting stream start time to %" GST_TIME_FORMAT,
3371             GST_TIME_ARGS (lace_time));
3372       }
3373       clace_time = MAX (lace_time, demux->stream_start_time);
3374       if (GST_CLOCK_TIME_IS_VALID (demux->common.segment.position) &&
3375           demux->common.segment.position != 0) {
3376         GST_DEBUG_OBJECT (demux,
3377             "using stored seek position %" GST_TIME_FORMAT,
3378             GST_TIME_ARGS (demux->common.segment.position));
3379         clace_time = demux->common.segment.position + demux->stream_start_time;
3380         segment->position = GST_CLOCK_TIME_NONE;
3381       }
3382       segment->start = clace_time;
3383       segment->stop = GST_CLOCK_TIME_NONE;
3384       segment->time = segment->start - demux->stream_start_time;
3385       segment->position = segment->start - demux->stream_start_time;
3386       GST_DEBUG_OBJECT (demux,
3387           "generated segment starting at %" GST_TIME_FORMAT ": %"
3388           GST_SEGMENT_FORMAT, GST_TIME_ARGS (lace_time), segment);
3389       /* now convey our segment notion downstream */
3390       gst_matroska_demux_send_event (demux, gst_event_new_segment (segment));
3391       demux->need_segment = FALSE;
3392     }
3393
3394     if (block_duration != -1) {
3395       if (stream->timecodescale == 1.0)
3396         duration = gst_util_uint64_scale (block_duration,
3397             demux->common.time_scale, 1);
3398       else
3399         duration =
3400             gst_util_gdouble_to_guint64 (gst_util_guint64_to_gdouble
3401             (gst_util_uint64_scale (block_duration, demux->common.time_scale,
3402                     1)) * stream->timecodescale);
3403     } else if (stream->default_duration) {
3404       duration = stream->default_duration * laces;
3405     }
3406     /* else duration is diff between timecode of this and next block */
3407
3408     /* For SimpleBlock, look at the keyframe bit in flags. Otherwise,
3409        a ReferenceBlock implies that this is not a keyframe. In either
3410        case, it only makes sense for video streams. */
3411     if (stream->type == GST_MATROSKA_TRACK_TYPE_VIDEO) {
3412       if ((is_simpleblock && !(flags & 0x80)) || referenceblock) {
3413         delta_unit = TRUE;
3414         invisible_frame = ((flags & 0x08)) &&
3415             (strcmp (stream->codec_id, GST_MATROSKA_CODEC_ID_VIDEO_VP8) == 0);
3416       }
3417     }
3418
3419     if (delta_unit && stream->set_discont) {
3420       /* When doing seeks or such, we need to restart on key frames or
3421        * decoders might choke. */
3422       GST_DEBUG_OBJECT (demux, "skipping delta unit");
3423       goto done;
3424     }
3425
3426     for (n = 0; n < laces; n++) {
3427       GstBuffer *sub;
3428
3429       if (G_UNLIKELY (lace_size[n] > size)) {
3430         GST_WARNING_OBJECT (demux, "Invalid lace size");
3431         break;
3432       }
3433
3434       /* QoS for video track with an index. the assumption is that
3435          index entries point to keyframes, but if that is not true we
3436          will instad skip until the next keyframe. */
3437       if (GST_CLOCK_TIME_IS_VALID (lace_time) &&
3438           stream->type == GST_MATROSKA_TRACK_TYPE_VIDEO &&
3439           stream->index_table && demux->common.segment.rate > 0.0) {
3440         GstMatroskaTrackVideoContext *videocontext =
3441             (GstMatroskaTrackVideoContext *) stream;
3442         GstClockTime earliest_time;
3443         GstClockTime earliest_stream_time;
3444
3445         GST_OBJECT_LOCK (demux);
3446         earliest_time = videocontext->earliest_time;
3447         GST_OBJECT_UNLOCK (demux);
3448         earliest_stream_time = gst_segment_to_position (&demux->common.segment,
3449             GST_FORMAT_TIME, earliest_time);
3450
3451         if (GST_CLOCK_TIME_IS_VALID (lace_time) &&
3452             GST_CLOCK_TIME_IS_VALID (earliest_stream_time) &&
3453             lace_time <= earliest_stream_time) {
3454           /* find index entry (keyframe) <= earliest_stream_time */
3455           GstMatroskaIndex *entry =
3456               gst_util_array_binary_search (stream->index_table->data,
3457               stream->index_table->len, sizeof (GstMatroskaIndex),
3458               (GCompareDataFunc) gst_matroska_index_seek_find,
3459               GST_SEARCH_MODE_BEFORE, &earliest_stream_time, NULL);
3460
3461           /* if that entry (keyframe) is after the current the current
3462              buffer, we can skip pushing (and thus decoding) all
3463              buffers until that keyframe. */
3464           if (entry && GST_CLOCK_TIME_IS_VALID (entry->time) &&
3465               entry->time > lace_time) {
3466             GST_LOG_OBJECT (demux, "Skipping lace before late keyframe");
3467             stream->set_discont = TRUE;
3468             goto next_lace;
3469           }
3470         }
3471       }
3472
3473       sub = gst_buffer_copy_region (buf, GST_BUFFER_COPY_ALL,
3474           gst_buffer_get_size (buf) - size, lace_size[n]);
3475       GST_DEBUG_OBJECT (demux, "created subbuffer %p", sub);
3476
3477       if (delta_unit)
3478         GST_BUFFER_FLAG_SET (sub, GST_BUFFER_FLAG_DELTA_UNIT);
3479       else
3480         GST_BUFFER_FLAG_UNSET (sub, GST_BUFFER_FLAG_DELTA_UNIT);
3481
3482       if (invisible_frame)
3483         GST_BUFFER_FLAG_SET (sub, GST_BUFFER_FLAG_DECODE_ONLY);
3484
3485       if (stream->encodings != NULL && stream->encodings->len > 0)
3486         sub = gst_matroska_decode_buffer (stream, sub);
3487
3488       if (sub == NULL) {
3489         GST_WARNING_OBJECT (demux, "Decoding buffer failed");
3490         goto next_lace;
3491       }
3492
3493       GST_BUFFER_TIMESTAMP (sub) = lace_time;
3494
3495       if (GST_CLOCK_TIME_IS_VALID (lace_time)) {
3496         GstClockTime last_stop_end;
3497
3498         /* Check if this stream is after segment stop */
3499         if (GST_CLOCK_TIME_IS_VALID (demux->common.segment.stop) &&
3500             lace_time >= demux->common.segment.stop) {
3501           GST_DEBUG_OBJECT (demux,
3502               "Stream %d after segment stop %" GST_TIME_FORMAT, stream->index,
3503               GST_TIME_ARGS (demux->common.segment.stop));
3504           gst_buffer_unref (sub);
3505           goto eos;
3506         }
3507         if (offset >= stream->to_offset
3508             || (GST_CLOCK_TIME_IS_VALID (demux->to_time)
3509                 && lace_time > demux->to_time)) {
3510           GST_DEBUG_OBJECT (demux, "Stream %d after playback section",
3511               stream->index);
3512           gst_buffer_unref (sub);
3513           goto eos;
3514         }
3515
3516         /* handle gaps, e.g. non-zero start-time, or an cue index entry
3517          * that landed us with timestamps not quite intended */
3518         GST_OBJECT_LOCK (demux);
3519         if (demux->max_gap_time &&
3520             GST_CLOCK_TIME_IS_VALID (demux->last_stop_end) &&
3521             demux->common.segment.rate > 0.0) {
3522           GstClockTimeDiff diff;
3523
3524           /* only send segments with increasing start times,
3525            * otherwise if these go back and forth downstream (sinks) increase
3526            * accumulated time and running_time */
3527           diff = GST_CLOCK_DIFF (demux->last_stop_end, lace_time);
3528           if (diff > 0 && diff > demux->max_gap_time
3529               && lace_time > demux->common.segment.start
3530               && (!GST_CLOCK_TIME_IS_VALID (demux->common.segment.stop)
3531                   || lace_time < demux->common.segment.stop)) {
3532             GstSegment segment;
3533             GstEvent *event1, *event2;
3534             GST_DEBUG_OBJECT (demux,
3535                 "Gap of %" G_GINT64_FORMAT " ns detected in"
3536                 "stream %d (%" GST_TIME_FORMAT " -> %" GST_TIME_FORMAT "). "
3537                 "Sending updated SEGMENT events", diff,
3538                 stream->index, GST_TIME_ARGS (stream->pos),
3539                 GST_TIME_ARGS (lace_time));
3540             /* send segment events such that the gap is not accounted in
3541              * segment base time, hence running_time */
3542             /* close ahead of gap */
3543             segment = demux->common.segment;
3544             segment.start = demux->last_stop_end;
3545             segment.stop = demux->last_stop_end;
3546             segment.position = demux->last_stop_end;
3547             event1 = gst_event_new_segment (&segment);
3548             /* skip gap */
3549             segment.start = lace_time;
3550             segment.stop = demux->common.segment.stop;
3551             segment.position = lace_time;
3552             event2 = gst_event_new_segment (&segment);
3553             GST_OBJECT_UNLOCK (demux);
3554             gst_matroska_demux_send_event (demux, event1);
3555             gst_matroska_demux_send_event (demux, event2);
3556             GST_OBJECT_LOCK (demux);
3557             /* align segment view with downstream,
3558              * prevents double-counting base time when closing segment */
3559             /* FIXME: in 0.10, the segment base/accum got updated here, but
3560              * maybe we don't need that because of the double accounting
3561              * mentioned above? */
3562             demux->common.segment = segment;
3563           }
3564         }
3565
3566         if (!GST_CLOCK_TIME_IS_VALID (demux->common.segment.position)
3567             || demux->common.segment.position < lace_time) {
3568           demux->common.segment.position = lace_time;
3569         }
3570         GST_OBJECT_UNLOCK (demux);
3571
3572         last_stop_end = lace_time;
3573         if (duration) {
3574           GST_BUFFER_DURATION (sub) = duration / laces;
3575           last_stop_end += GST_BUFFER_DURATION (sub);
3576         }
3577
3578         if (!GST_CLOCK_TIME_IS_VALID (demux->last_stop_end) ||
3579             demux->last_stop_end < last_stop_end)
3580           demux->last_stop_end = last_stop_end;
3581
3582         GST_OBJECT_LOCK (demux);
3583         if (demux->common.segment.duration == -1 ||
3584             demux->stream_start_time + demux->common.segment.duration <
3585             last_stop_end) {
3586           demux->common.segment.duration =
3587               last_stop_end - demux->stream_start_time;
3588           GST_OBJECT_UNLOCK (demux);
3589           if (!demux->invalid_duration) {
3590             gst_element_post_message (GST_ELEMENT_CAST (demux),
3591                 gst_message_new_duration_changed (GST_OBJECT_CAST (demux)));
3592             demux->invalid_duration = TRUE;
3593           }
3594         } else {
3595           GST_OBJECT_UNLOCK (demux);
3596         }
3597       }
3598
3599       stream->pos = lace_time;
3600
3601       gst_matroska_demux_sync_streams (demux);
3602
3603       if (stream->set_discont) {
3604         GST_DEBUG_OBJECT (demux, "marking DISCONT");
3605         GST_BUFFER_FLAG_SET (sub, GST_BUFFER_FLAG_DISCONT);
3606         stream->set_discont = FALSE;
3607       }
3608
3609       /* reverse playback book-keeping */
3610       if (!GST_CLOCK_TIME_IS_VALID (stream->from_time))
3611         stream->from_time = lace_time;
3612       if (stream->from_offset == -1)
3613         stream->from_offset = offset;
3614
3615       GST_DEBUG_OBJECT (demux,
3616           "Pushing lace %d, data of size %" G_GSIZE_FORMAT
3617           " for stream %d, time=%" GST_TIME_FORMAT " and duration=%"
3618           GST_TIME_FORMAT, n, gst_buffer_get_size (sub), stream_num,
3619           GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (sub)),
3620           GST_TIME_ARGS (GST_BUFFER_DURATION (sub)));
3621
3622 #if 0
3623       if (demux->common.element_index) {
3624         if (stream->index_writer_id == -1)
3625           gst_index_get_writer_id (demux->common.element_index,
3626               GST_OBJECT (stream->pad), &stream->index_writer_id);
3627
3628         GST_LOG_OBJECT (demux, "adding association %" GST_TIME_FORMAT "-> %"
3629             G_GUINT64_FORMAT " for writer id %d",
3630             GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (sub)), cluster_offset,
3631             stream->index_writer_id);
3632         gst_index_add_association (demux->common.element_index,
3633             stream->index_writer_id, GST_BUFFER_FLAG_IS_SET (sub,
3634                 GST_BUFFER_FLAG_DELTA_UNIT) ? 0 : GST_ASSOCIATION_FLAG_KEY_UNIT,
3635             GST_FORMAT_TIME, GST_BUFFER_TIMESTAMP (sub), GST_FORMAT_BYTES,
3636             cluster_offset, NULL);
3637       }
3638 #endif
3639
3640       /* Postprocess the buffers depending on the codec used */
3641       if (stream->postprocess_frame) {
3642         GST_LOG_OBJECT (demux, "running post process");
3643         ret = stream->postprocess_frame (GST_ELEMENT (demux), stream, &sub);
3644       }
3645
3646       /* At this point, we have a sub-buffer pointing at data within a larger
3647          buffer. This data might not be aligned with anything. If the data is
3648          raw samples though, we want it aligned to the raw type (eg, 4 bytes
3649          for 32 bit samples, etc), or bad things will happen downstream as
3650          elements typically assume minimal alignment.
3651          Therefore, create an aligned copy if necessary. */
3652       g_assert (stream->alignment <= G_MEM_ALIGN);
3653       sub = gst_matroska_demux_align_buffer (demux, sub, stream->alignment);
3654
3655       ret = gst_pad_push (stream->pad, sub);
3656
3657       if (demux->common.segment.rate < 0) {
3658         if (lace_time > demux->common.segment.stop && ret == GST_FLOW_EOS) {
3659           /* In reverse playback we can get a GST_FLOW_EOS when
3660            * we are at the end of the segment, so we just need to jump
3661            * back to the previous section. */
3662           GST_DEBUG_OBJECT (demux, "downstream has reached end of segment");
3663           ret = GST_FLOW_OK;
3664         }
3665       }
3666       /* combine flows */
3667       ret = gst_matroska_demux_combine_flows (demux, stream, ret);
3668
3669     next_lace:
3670       size -= lace_size[n];
3671       if (lace_time != GST_CLOCK_TIME_NONE && duration)
3672         lace_time += duration / laces;
3673       else
3674         lace_time = GST_CLOCK_TIME_NONE;
3675     }
3676   }
3677
3678 done:
3679   if (buf) {
3680     gst_buffer_unmap (buf, &map);
3681     gst_buffer_unref (buf);
3682   }
3683   g_free (lace_size);
3684
3685   return ret;
3686
3687   /* EXITS */
3688 eos:
3689   {
3690     stream->eos = TRUE;
3691     ret = GST_FLOW_OK;
3692     /* combine flows */
3693     ret = gst_matroska_demux_combine_flows (demux, stream, ret);
3694     goto done;
3695   }
3696 invalid_lacing:
3697   {
3698     GST_ELEMENT_WARNING (demux, STREAM, DEMUX, (NULL), ("Invalid lacing size"));
3699     /* non-fatal, try next block(group) */
3700     ret = GST_FLOW_OK;
3701     goto done;
3702   }
3703 data_error:
3704   {
3705     GST_ELEMENT_WARNING (demux, STREAM, DEMUX, (NULL), ("Data error"));
3706     /* non-fatal, try next block(group) */
3707     ret = GST_FLOW_OK;
3708     goto done;
3709   }
3710 }
3711
3712 /* return FALSE if block(group) should be skipped (due to a seek) */
3713 static inline gboolean
3714 gst_matroska_demux_seek_block (GstMatroskaDemux * demux)
3715 {
3716   if (G_UNLIKELY (demux->seek_block)) {
3717     if (!(--demux->seek_block)) {
3718       return TRUE;
3719     } else {
3720       GST_LOG_OBJECT (demux, "should skip block due to seek");
3721       return FALSE;
3722     }
3723   } else {
3724     return TRUE;
3725   }
3726 }
3727
3728 static GstFlowReturn
3729 gst_matroska_demux_parse_contents_seekentry (GstMatroskaDemux * demux,
3730     GstEbmlRead * ebml)
3731 {
3732   GstFlowReturn ret;
3733   guint64 seek_pos = (guint64) - 1;
3734   guint32 seek_id = 0;
3735   guint32 id;
3736
3737   DEBUG_ELEMENT_START (demux, ebml, "Seek");
3738
3739   if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
3740     DEBUG_ELEMENT_STOP (demux, ebml, "Seek", ret);
3741     return ret;
3742   }
3743
3744   while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
3745     if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
3746       break;
3747
3748     switch (id) {
3749       case GST_MATROSKA_ID_SEEKID:
3750       {
3751         guint64 t;
3752
3753         if ((ret = gst_ebml_read_uint (ebml, &id, &t)) != GST_FLOW_OK)
3754           break;
3755
3756         GST_DEBUG_OBJECT (demux, "SeekID: %" G_GUINT64_FORMAT, t);
3757         seek_id = t;
3758         break;
3759       }
3760
3761       case GST_MATROSKA_ID_SEEKPOSITION:
3762       {
3763         guint64 t;
3764
3765         if ((ret = gst_ebml_read_uint (ebml, &id, &t)) != GST_FLOW_OK)
3766           break;
3767
3768         if (t > G_MAXINT64) {
3769           GST_WARNING_OBJECT (demux,
3770               "Too large SeekPosition %" G_GUINT64_FORMAT, t);
3771           break;
3772         }
3773
3774         GST_DEBUG_OBJECT (demux, "SeekPosition: %" G_GUINT64_FORMAT, t);
3775         seek_pos = t;
3776         break;
3777       }
3778
3779       default:
3780         ret = gst_matroska_read_common_parse_skip (&demux->common, ebml,
3781             "SeekHead", id);
3782         break;
3783     }
3784   }
3785
3786   if (ret != GST_FLOW_OK && ret != GST_FLOW_EOS)
3787     return ret;
3788
3789   if (!seek_id || seek_pos == (guint64) - 1) {
3790     GST_WARNING_OBJECT (demux, "Incomplete seekhead entry (0x%x/%"
3791         G_GUINT64_FORMAT ")", seek_id, seek_pos);
3792     return GST_FLOW_OK;
3793   }
3794
3795   switch (seek_id) {
3796     case GST_MATROSKA_ID_SEEKHEAD:
3797     {
3798     }
3799     case GST_MATROSKA_ID_CUES:
3800     case GST_MATROSKA_ID_TAGS:
3801     case GST_MATROSKA_ID_TRACKS:
3802     case GST_MATROSKA_ID_SEGMENTINFO:
3803     case GST_MATROSKA_ID_ATTACHMENTS:
3804     case GST_MATROSKA_ID_CHAPTERS:
3805     {
3806       guint64 before_pos, length;
3807       guint needed;
3808
3809       /* remember */
3810       length = gst_matroska_read_common_get_length (&demux->common);
3811       before_pos = demux->common.offset;
3812
3813       if (length == (guint64) - 1) {
3814         GST_DEBUG_OBJECT (demux, "no upstream length, skipping SeakHead entry");
3815         break;
3816       }
3817
3818       /* check for validity */
3819       if (seek_pos + demux->common.ebml_segment_start + 12 >= length) {
3820         GST_WARNING_OBJECT (demux,
3821             "SeekHead reference lies outside file!" " (%"
3822             G_GUINT64_FORMAT "+%" G_GUINT64_FORMAT "+12 >= %"
3823             G_GUINT64_FORMAT ")", seek_pos, demux->common.ebml_segment_start,
3824             length);
3825         break;
3826       }
3827
3828       /* only pick up index location when streaming */
3829       if (demux->streaming) {
3830         if (seek_id == GST_MATROSKA_ID_CUES) {
3831           demux->index_offset = seek_pos + demux->common.ebml_segment_start;
3832           GST_DEBUG_OBJECT (demux, "Cues located at offset %" G_GUINT64_FORMAT,
3833               demux->index_offset);
3834         }
3835         break;
3836       }
3837
3838       /* seek */
3839       demux->common.offset = seek_pos + demux->common.ebml_segment_start;
3840
3841       /* check ID */
3842       if ((ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
3843                   GST_ELEMENT_CAST (demux), &id, &length, &needed)) !=
3844           GST_FLOW_OK)
3845         goto finish;
3846
3847       if (id != seek_id) {
3848         GST_WARNING_OBJECT (demux,
3849             "We looked for ID=0x%x but got ID=0x%x (pos=%" G_GUINT64_FORMAT ")",
3850             seek_id, id, seek_pos + demux->common.ebml_segment_start);
3851       } else {
3852         /* now parse */
3853         ret = gst_matroska_demux_parse_id (demux, id, length, needed);
3854       }
3855
3856     finish:
3857       /* seek back */
3858       demux->common.offset = before_pos;
3859       break;
3860     }
3861
3862     case GST_MATROSKA_ID_CLUSTER:
3863     {
3864       guint64 pos = seek_pos + demux->common.ebml_segment_start;
3865
3866       GST_LOG_OBJECT (demux, "Cluster position");
3867       if (G_UNLIKELY (!demux->clusters))
3868         demux->clusters = g_array_sized_new (TRUE, TRUE, sizeof (guint64), 100);
3869       g_array_append_val (demux->clusters, pos);
3870       break;
3871     }
3872
3873     default:
3874       GST_DEBUG_OBJECT (demux, "Ignoring Seek entry for ID=0x%x", seek_id);
3875       break;
3876   }
3877   DEBUG_ELEMENT_STOP (demux, ebml, "Seek", ret);
3878
3879   return ret;
3880 }
3881
3882 static GstFlowReturn
3883 gst_matroska_demux_parse_contents (GstMatroskaDemux * demux, GstEbmlRead * ebml)
3884 {
3885   GstFlowReturn ret = GST_FLOW_OK;
3886   guint32 id;
3887
3888   DEBUG_ELEMENT_START (demux, ebml, "SeekHead");
3889
3890   if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
3891     DEBUG_ELEMENT_STOP (demux, ebml, "SeekHead", ret);
3892     return ret;
3893   }
3894
3895   while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
3896     if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
3897       break;
3898
3899     switch (id) {
3900       case GST_MATROSKA_ID_SEEKENTRY:
3901       {
3902         ret = gst_matroska_demux_parse_contents_seekentry (demux, ebml);
3903         /* Ignore EOS and errors here */
3904         if (ret != GST_FLOW_OK) {
3905           GST_DEBUG_OBJECT (demux, "Ignoring %s", gst_flow_get_name (ret));
3906           ret = GST_FLOW_OK;
3907         }
3908         break;
3909       }
3910
3911       default:
3912         ret = gst_matroska_read_common_parse_skip (&demux->common,
3913             ebml, "SeekHead", id);
3914         break;
3915     }
3916   }
3917
3918   DEBUG_ELEMENT_STOP (demux, ebml, "SeekHead", ret);
3919
3920   /* Sort clusters by position for easier searching */
3921   if (demux->clusters)
3922     g_array_sort (demux->clusters, (GCompareFunc) gst_matroska_cluster_compare);
3923
3924   return ret;
3925 }
3926
3927 #define GST_FLOW_OVERFLOW   GST_FLOW_CUSTOM_ERROR
3928
3929 #define MAX_BLOCK_SIZE (15 * 1024 * 1024)
3930
3931 static inline GstFlowReturn
3932 gst_matroska_demux_check_read_size (GstMatroskaDemux * demux, guint64 bytes)
3933 {
3934   if (G_UNLIKELY (bytes > MAX_BLOCK_SIZE)) {
3935     /* only a few blocks are expected/allowed to be large,
3936      * and will be recursed into, whereas others will be read and must fit */
3937     if (demux->streaming) {
3938       /* fatal in streaming case, as we can't step over easily */
3939       GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
3940           ("reading large block of size %" G_GUINT64_FORMAT " not supported; "
3941               "file might be corrupt.", bytes));
3942       return GST_FLOW_ERROR;
3943     } else {
3944       /* indicate higher level to quietly give up */
3945       GST_DEBUG_OBJECT (demux,
3946           "too large block of size %" G_GUINT64_FORMAT, bytes);
3947       return GST_FLOW_ERROR;
3948     }
3949   } else {
3950     return GST_FLOW_OK;
3951   }
3952 }
3953
3954 /* returns TRUE if we truely are in error state, and should give up */
3955 static inline gboolean
3956 gst_matroska_demux_check_parse_error (GstMatroskaDemux * demux)
3957 {
3958   if (!demux->streaming && demux->next_cluster_offset > 0) {
3959     /* just repositioning to where next cluster should be and try from there */
3960     GST_WARNING_OBJECT (demux, "parse error, trying next cluster expected at %"
3961         G_GUINT64_FORMAT, demux->next_cluster_offset);
3962     demux->common.offset = demux->next_cluster_offset;
3963     demux->next_cluster_offset = 0;
3964     return FALSE;
3965   } else {
3966     gint64 pos;
3967
3968     /* sigh, one last attempt above and beyond call of duty ...;
3969      * search for cluster mark following current pos */
3970     pos = demux->common.offset;
3971     GST_WARNING_OBJECT (demux, "parse error, looking for next cluster");
3972     if (gst_matroska_demux_search_cluster (demux, &pos) != GST_FLOW_OK) {
3973       /* did not work, give up */
3974       return TRUE;
3975     } else {
3976       GST_DEBUG_OBJECT (demux, "... found at  %" G_GUINT64_FORMAT, pos);
3977       /* try that position */
3978       demux->common.offset = pos;
3979       return FALSE;
3980     }
3981   }
3982 }
3983
3984 static inline GstFlowReturn
3985 gst_matroska_demux_flush (GstMatroskaDemux * demux, guint flush)
3986 {
3987   GST_LOG_OBJECT (demux, "skipping %d bytes", flush);
3988   demux->common.offset += flush;
3989   if (demux->streaming) {
3990     GstFlowReturn ret;
3991
3992     /* hard to skip large blocks when streaming */
3993     ret = gst_matroska_demux_check_read_size (demux, flush);
3994     if (ret != GST_FLOW_OK)
3995       return ret;
3996     if (flush <= gst_adapter_available (demux->common.adapter))
3997       gst_adapter_flush (demux->common.adapter, flush);
3998     else
3999       return GST_FLOW_EOS;
4000   }
4001   return GST_FLOW_OK;
4002 }
4003
4004 /* initializes @ebml with @bytes from input stream at current offset.
4005  * Returns EOS if insufficient available,
4006  * ERROR if too much was attempted to read. */
4007 static inline GstFlowReturn
4008 gst_matroska_demux_take (GstMatroskaDemux * demux, guint64 bytes,
4009     GstEbmlRead * ebml)
4010 {
4011   GstBuffer *buffer = NULL;
4012   GstFlowReturn ret = GST_FLOW_OK;
4013
4014   GST_LOG_OBJECT (demux, "taking %" G_GUINT64_FORMAT " bytes for parsing",
4015       bytes);
4016   ret = gst_matroska_demux_check_read_size (demux, bytes);
4017   if (G_UNLIKELY (ret != GST_FLOW_OK)) {
4018     if (!demux->streaming) {
4019       /* in pull mode, we can skip */
4020       if ((ret = gst_matroska_demux_flush (demux, bytes)) == GST_FLOW_OK)
4021         ret = GST_FLOW_OVERFLOW;
4022     } else {
4023       /* otherwise fatal */
4024       ret = GST_FLOW_ERROR;
4025     }
4026     goto exit;
4027   }
4028   if (demux->streaming) {
4029     if (gst_adapter_available (demux->common.adapter) >= bytes)
4030       buffer = gst_adapter_take_buffer (demux->common.adapter, bytes);
4031     else
4032       ret = GST_FLOW_EOS;
4033   } else
4034     ret = gst_matroska_read_common_peek_bytes (&demux->common,
4035         demux->common.offset, bytes, &buffer, NULL);
4036   if (G_LIKELY (buffer)) {
4037     gst_ebml_read_init (ebml, GST_ELEMENT_CAST (demux), buffer,
4038         demux->common.offset);
4039     demux->common.offset += bytes;
4040   }
4041 exit:
4042   return ret;
4043 }
4044
4045 static void
4046 gst_matroska_demux_check_seekability (GstMatroskaDemux * demux)
4047 {
4048   GstQuery *query;
4049   gboolean seekable = FALSE;
4050   gint64 start = -1, stop = -1;
4051
4052   query = gst_query_new_seeking (GST_FORMAT_BYTES);
4053   if (!gst_pad_peer_query (demux->common.sinkpad, query)) {
4054     GST_DEBUG_OBJECT (demux, "seeking query failed");
4055     goto done;
4056   }
4057
4058   gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
4059
4060   /* try harder to query upstream size if we didn't get it the first time */
4061   if (seekable && stop == -1) {
4062     GST_DEBUG_OBJECT (demux, "doing duration query to fix up unset stop");
4063     gst_pad_peer_query_duration (demux->common.sinkpad, GST_FORMAT_BYTES,
4064         &stop);
4065   }
4066
4067   /* if upstream doesn't know the size, it's likely that it's not seekable in
4068    * practice even if it technically may be seekable */
4069   if (seekable && (start != 0 || stop <= start)) {
4070     GST_DEBUG_OBJECT (demux, "seekable but unknown start/stop -> disable");
4071     seekable = FALSE;
4072   }
4073
4074 done:
4075   GST_INFO_OBJECT (demux, "seekable: %d (%" G_GUINT64_FORMAT " - %"
4076       G_GUINT64_FORMAT ")", seekable, start, stop);
4077   demux->seekable = seekable;
4078
4079   gst_query_unref (query);
4080 }
4081
4082 static GstFlowReturn
4083 gst_matroska_demux_find_tracks (GstMatroskaDemux * demux)
4084 {
4085   guint32 id;
4086   guint64 before_pos;
4087   guint64 length;
4088   guint needed;
4089   GstFlowReturn ret = GST_FLOW_OK;
4090
4091   GST_WARNING_OBJECT (demux,
4092       "Found Cluster element before Tracks, searching Tracks");
4093
4094   /* remember */
4095   before_pos = demux->common.offset;
4096
4097   /* Search Tracks element */
4098   while (TRUE) {
4099     ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
4100         GST_ELEMENT_CAST (demux), &id, &length, &needed);
4101     if (ret != GST_FLOW_OK)
4102       break;
4103
4104     if (id != GST_MATROSKA_ID_TRACKS) {
4105       /* we may be skipping large cluster here, so forego size check etc */
4106       /* ... but we can't skip undefined size; force error */
4107       if (length == G_MAXUINT64) {
4108         ret = gst_matroska_demux_check_read_size (demux, length);
4109         break;
4110       } else {
4111         demux->common.offset += needed;
4112         demux->common.offset += length;
4113       }
4114       continue;
4115     }
4116
4117     /* will lead to track parsing ... */
4118     ret = gst_matroska_demux_parse_id (demux, id, length, needed);
4119     break;
4120   }
4121
4122   /* seek back */
4123   demux->common.offset = before_pos;
4124
4125   return ret;
4126 }
4127
4128 #define GST_READ_CHECK(stmt)  \
4129 G_STMT_START { \
4130   if (G_UNLIKELY ((ret = (stmt)) != GST_FLOW_OK)) { \
4131     if (ret == GST_FLOW_OVERFLOW) { \
4132       ret = GST_FLOW_OK; \
4133     } \
4134     goto read_error; \
4135   } \
4136 } G_STMT_END
4137
4138 static GstFlowReturn
4139 gst_matroska_demux_parse_id (GstMatroskaDemux * demux, guint32 id,
4140     guint64 length, guint needed)
4141 {
4142   GstEbmlRead ebml = { 0, };
4143   GstFlowReturn ret = GST_FLOW_OK;
4144   guint64 read;
4145
4146   GST_LOG_OBJECT (demux, "Parsing Element id 0x%x, "
4147       "size %" G_GUINT64_FORMAT ", prefix %d", id, length, needed);
4148
4149   /* if we plan to read and parse this element, we need prefix (id + length)
4150    * and the contents */
4151   /* mind about overflow wrap-around when dealing with undefined size */
4152   read = length;
4153   if (G_LIKELY (length != G_MAXUINT64))
4154     read += needed;
4155
4156   switch (demux->common.state) {
4157     case GST_MATROSKA_READ_STATE_START:
4158       switch (id) {
4159         case GST_EBML_ID_HEADER:
4160           GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
4161           ret = gst_matroska_read_common_parse_header (&demux->common, &ebml);
4162           if (ret != GST_FLOW_OK)
4163             goto parse_failed;
4164           demux->common.state = GST_MATROSKA_READ_STATE_SEGMENT;
4165           gst_matroska_demux_check_seekability (demux);
4166           break;
4167         default:
4168           goto invalid_header;
4169           break;
4170       }
4171       break;
4172     case GST_MATROSKA_READ_STATE_SEGMENT:
4173       switch (id) {
4174         case GST_MATROSKA_ID_SEGMENT:
4175           /* eat segment prefix */
4176           GST_READ_CHECK (gst_matroska_demux_flush (demux, needed));
4177           GST_DEBUG_OBJECT (demux,
4178               "Found Segment start at offset %" G_GUINT64_FORMAT,
4179               demux->common.offset);
4180           /* seeks are from the beginning of the segment,
4181            * after the segment ID/length */
4182           demux->common.ebml_segment_start = demux->common.offset;
4183           demux->common.state = GST_MATROSKA_READ_STATE_HEADER;
4184           break;
4185         default:
4186           GST_WARNING_OBJECT (demux,
4187               "Expected a Segment ID (0x%x), but received 0x%x!",
4188               GST_MATROSKA_ID_SEGMENT, id);
4189           GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
4190           break;
4191       }
4192       break;
4193     case GST_MATROSKA_READ_STATE_SCANNING:
4194       if (id != GST_MATROSKA_ID_CLUSTER &&
4195           id != GST_MATROSKA_ID_CLUSTERTIMECODE)
4196         goto skip;
4197       /* fall-through */
4198     case GST_MATROSKA_READ_STATE_HEADER:
4199     case GST_MATROSKA_READ_STATE_DATA:
4200     case GST_MATROSKA_READ_STATE_SEEK:
4201       switch (id) {
4202         case GST_MATROSKA_ID_SEGMENTINFO:
4203           if (!demux->common.segmentinfo_parsed) {
4204             GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
4205             ret = gst_matroska_read_common_parse_info (&demux->common,
4206                 GST_ELEMENT_CAST (demux), &ebml);
4207           } else {
4208             GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
4209           }
4210           break;
4211         case GST_MATROSKA_ID_TRACKS:
4212           if (!demux->tracks_parsed) {
4213             GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
4214             ret = gst_matroska_demux_parse_tracks (demux, &ebml);
4215           } else {
4216             GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
4217           }
4218           break;
4219         case GST_MATROSKA_ID_CLUSTER:
4220           if (G_UNLIKELY (!demux->tracks_parsed)) {
4221             if (demux->streaming) {
4222               GST_DEBUG_OBJECT (demux, "Cluster before Track");
4223               goto not_streamable;
4224             } else {
4225               ret = gst_matroska_demux_find_tracks (demux);
4226               if (!demux->tracks_parsed)
4227                 goto no_tracks;
4228             }
4229           }
4230           if (G_UNLIKELY (demux->common.state
4231                   == GST_MATROSKA_READ_STATE_HEADER)) {
4232             demux->common.state = GST_MATROSKA_READ_STATE_DATA;
4233             demux->first_cluster_offset = demux->common.offset;
4234             GST_DEBUG_OBJECT (demux, "signaling no more pads");
4235             gst_element_no_more_pads (GST_ELEMENT (demux));
4236             /* send initial segment - we wait till we know the first
4237                incoming timestamp, so we can properly set the start of
4238                the segment. */
4239             demux->need_segment = TRUE;
4240           }
4241           demux->cluster_time = GST_CLOCK_TIME_NONE;
4242           demux->cluster_offset = demux->common.offset;
4243           if (G_UNLIKELY (!demux->seek_first && demux->seek_block)) {
4244             GST_DEBUG_OBJECT (demux, "seek target block %" G_GUINT64_FORMAT
4245                 " not found in Cluster, trying next Cluster's first block instead",
4246                 demux->seek_block);
4247             demux->seek_block = 0;
4248           }
4249           demux->seek_first = FALSE;
4250           /* record next cluster for recovery */
4251           if (read != G_MAXUINT64)
4252             demux->next_cluster_offset = demux->cluster_offset + read;
4253           /* eat cluster prefix */
4254           gst_matroska_demux_flush (demux, needed);
4255           break;
4256         case GST_MATROSKA_ID_CLUSTERTIMECODE:
4257         {
4258           guint64 num;
4259
4260           GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
4261           if ((ret = gst_ebml_read_uint (&ebml, &id, &num)) != GST_FLOW_OK)
4262             goto parse_failed;
4263           GST_DEBUG_OBJECT (demux, "ClusterTimeCode: %" G_GUINT64_FORMAT, num);
4264           demux->cluster_time = num;
4265 #if 0
4266           if (demux->common.element_index) {
4267             if (demux->common.element_index_writer_id == -1)
4268               gst_index_get_writer_id (demux->common.element_index,
4269                   GST_OBJECT (demux), &demux->common.element_index_writer_id);
4270             GST_LOG_OBJECT (demux, "adding association %" GST_TIME_FORMAT "-> %"
4271                 G_GUINT64_FORMAT " for writer id %d",
4272                 GST_TIME_ARGS (demux->cluster_time), demux->cluster_offset,
4273                 demux->common.element_index_writer_id);
4274             gst_index_add_association (demux->common.element_index,
4275                 demux->common.element_index_writer_id,
4276                 GST_ASSOCIATION_FLAG_KEY_UNIT,
4277                 GST_FORMAT_TIME, demux->cluster_time,
4278                 GST_FORMAT_BYTES, demux->cluster_offset, NULL);
4279           }
4280 #endif
4281           break;
4282         }
4283         case GST_MATROSKA_ID_BLOCKGROUP:
4284           if (!gst_matroska_demux_seek_block (demux))
4285             goto skip;
4286           GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
4287           DEBUG_ELEMENT_START (demux, &ebml, "BlockGroup");
4288           if ((ret = gst_ebml_read_master (&ebml, &id)) == GST_FLOW_OK) {
4289             ret = gst_matroska_demux_parse_blockgroup_or_simpleblock (demux,
4290                 &ebml, demux->cluster_time, demux->cluster_offset, FALSE);
4291           }
4292           DEBUG_ELEMENT_STOP (demux, &ebml, "BlockGroup", ret);
4293           break;
4294         case GST_MATROSKA_ID_SIMPLEBLOCK:
4295           if (!gst_matroska_demux_seek_block (demux))
4296             goto skip;
4297           GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
4298           DEBUG_ELEMENT_START (demux, &ebml, "SimpleBlock");
4299           ret = gst_matroska_demux_parse_blockgroup_or_simpleblock (demux,
4300               &ebml, demux->cluster_time, demux->cluster_offset, TRUE);
4301           DEBUG_ELEMENT_STOP (demux, &ebml, "SimpleBlock", ret);
4302           break;
4303         case GST_MATROSKA_ID_ATTACHMENTS:
4304           if (!demux->common.attachments_parsed) {
4305             GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
4306             ret = gst_matroska_read_common_parse_attachments (&demux->common,
4307                 GST_ELEMENT_CAST (demux), &ebml);
4308           } else {
4309             GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
4310           }
4311           break;
4312         case GST_MATROSKA_ID_TAGS:
4313           GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
4314           ret = gst_matroska_read_common_parse_metadata (&demux->common,
4315               GST_ELEMENT_CAST (demux), &ebml);
4316           break;
4317         case GST_MATROSKA_ID_CHAPTERS:
4318           if (!demux->common.chapters_parsed) {
4319             GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
4320             ret =
4321                 gst_matroska_read_common_parse_chapters (&demux->common, &ebml);
4322
4323             if (demux->common.toc) {
4324               gst_matroska_demux_send_event (demux,
4325                   gst_event_new_toc (demux->common.toc, FALSE));
4326             }
4327           } else
4328             GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
4329           break;
4330         case GST_MATROSKA_ID_SEEKHEAD:
4331           GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
4332           ret = gst_matroska_demux_parse_contents (demux, &ebml);
4333           break;
4334         case GST_MATROSKA_ID_CUES:
4335           if (demux->common.index_parsed) {
4336             GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
4337             break;
4338           }
4339           GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
4340           ret = gst_matroska_read_common_parse_index (&demux->common, &ebml);
4341           /* only push based; delayed index building */
4342           if (ret == GST_FLOW_OK
4343               && demux->common.state == GST_MATROSKA_READ_STATE_SEEK) {
4344             GstEvent *event;
4345
4346             GST_OBJECT_LOCK (demux);
4347             event = demux->seek_event;
4348             demux->seek_event = NULL;
4349             GST_OBJECT_UNLOCK (demux);
4350
4351             g_assert (event);
4352             /* unlikely to fail, since we managed to seek to this point */
4353             if (!gst_matroska_demux_handle_seek_event (demux, NULL, event))
4354               goto seek_failed;
4355             /* resume data handling, main thread clear to seek again */
4356             GST_OBJECT_LOCK (demux);
4357             demux->common.state = GST_MATROSKA_READ_STATE_DATA;
4358             GST_OBJECT_UNLOCK (demux);
4359           }
4360           break;
4361         case GST_MATROSKA_ID_POSITION:
4362         case GST_MATROSKA_ID_PREVSIZE:
4363         case GST_MATROSKA_ID_ENCRYPTEDBLOCK:
4364         case GST_MATROSKA_ID_SILENTTRACKS:
4365           GST_DEBUG_OBJECT (demux,
4366               "Skipping Cluster subelement 0x%x - ignoring", id);
4367           /* fall-through */
4368         default:
4369         skip:
4370           GST_DEBUG_OBJECT (demux, "skipping Element 0x%x", id);
4371           GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
4372           break;
4373       }
4374       break;
4375   }
4376
4377   if (ret == GST_FLOW_PARSE)
4378     goto parse_failed;
4379
4380 exit:
4381   gst_ebml_read_clear (&ebml);
4382   return ret;
4383
4384   /* ERRORS */
4385 read_error:
4386   {
4387     /* simply exit, maybe not enough data yet */
4388     /* no ebml to clear if read error */
4389     return ret;
4390   }
4391 parse_failed:
4392   {
4393     GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
4394         ("Failed to parse Element 0x%x", id));
4395     ret = GST_FLOW_ERROR;
4396     goto exit;
4397   }
4398 not_streamable:
4399   {
4400     GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
4401         ("File layout does not permit streaming"));
4402     ret = GST_FLOW_ERROR;
4403     goto exit;
4404   }
4405 no_tracks:
4406   {
4407     GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
4408         ("No Tracks element found"));
4409     ret = GST_FLOW_ERROR;
4410     goto exit;
4411   }
4412 invalid_header:
4413   {
4414     GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL), ("Invalid header"));
4415     ret = GST_FLOW_ERROR;
4416     goto exit;
4417   }
4418 seek_failed:
4419   {
4420     GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL), ("Failed to seek"));
4421     ret = GST_FLOW_ERROR;
4422     goto exit;
4423   }
4424 }
4425
4426 static void
4427 gst_matroska_demux_loop (GstPad * pad)
4428 {
4429   GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (GST_PAD_PARENT (pad));
4430   GstFlowReturn ret;
4431   guint32 id;
4432   guint64 length;
4433   guint needed;
4434
4435   /* If we have to close a segment, send a new segment to do this now */
4436   if (G_LIKELY (demux->common.state == GST_MATROSKA_READ_STATE_DATA)) {
4437     if (G_UNLIKELY (demux->new_segment)) {
4438       gst_matroska_demux_send_event (demux, demux->new_segment);
4439       demux->new_segment = NULL;
4440     }
4441   }
4442
4443   ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
4444       GST_ELEMENT_CAST (demux), &id, &length, &needed);
4445   if (ret == GST_FLOW_EOS)
4446     goto eos;
4447   if (ret != GST_FLOW_OK) {
4448     if (gst_matroska_demux_check_parse_error (demux))
4449       goto pause;
4450     else
4451       return;
4452   }
4453
4454   GST_LOG_OBJECT (demux, "Offset %" G_GUINT64_FORMAT ", Element id 0x%x, "
4455       "size %" G_GUINT64_FORMAT ", needed %d", demux->common.offset, id,
4456       length, needed);
4457
4458   ret = gst_matroska_demux_parse_id (demux, id, length, needed);
4459   if (ret == GST_FLOW_EOS)
4460     goto eos;
4461   if (ret != GST_FLOW_OK)
4462     goto pause;
4463
4464   /* check if we're at the end of a configured segment */
4465   if (G_LIKELY (demux->common.src->len)) {
4466     guint i;
4467
4468     g_assert (demux->common.num_streams == demux->common.src->len);
4469     for (i = 0; i < demux->common.src->len; i++) {
4470       GstMatroskaTrackContext *context = g_ptr_array_index (demux->common.src,
4471           i);
4472       GST_DEBUG_OBJECT (context->pad, "pos %" GST_TIME_FORMAT,
4473           GST_TIME_ARGS (context->pos));
4474       if (context->eos == FALSE)
4475         goto next;
4476     }
4477
4478     GST_INFO_OBJECT (demux, "All streams are EOS");
4479     ret = GST_FLOW_EOS;
4480     goto eos;
4481   }
4482
4483 next:
4484   if (G_UNLIKELY (demux->common.offset ==
4485           gst_matroska_read_common_get_length (&demux->common))) {
4486     GST_LOG_OBJECT (demux, "Reached end of stream");
4487     ret = GST_FLOW_EOS;
4488     goto eos;
4489   }
4490
4491   return;
4492
4493   /* ERRORS */
4494 eos:
4495   {
4496     if (demux->common.segment.rate < 0.0) {
4497       ret = gst_matroska_demux_seek_to_previous_keyframe (demux);
4498       if (ret == GST_FLOW_OK)
4499         return;
4500     }
4501     /* fall-through */
4502   }
4503 pause:
4504   {
4505     const gchar *reason = gst_flow_get_name (ret);
4506     gboolean push_eos = FALSE;
4507
4508     GST_LOG_OBJECT (demux, "pausing task, reason %s", reason);
4509     gst_pad_pause_task (demux->common.sinkpad);
4510
4511     if (ret == GST_FLOW_EOS) {
4512       /* perform EOS logic */
4513
4514       /* If we were in the headers, make sure we send no-more-pads.
4515          This will ensure decodebin2 does not get stuck thinking
4516          the chain is not complete yet, and waiting indefinitely. */
4517       if (G_UNLIKELY (demux->common.state == GST_MATROSKA_READ_STATE_HEADER)) {
4518         if (demux->common.src->len == 0) {
4519           GST_ELEMENT_ERROR (demux, STREAM, FAILED, (NULL),
4520               ("No pads created"));
4521         } else {
4522           GST_ELEMENT_WARNING (demux, STREAM, DEMUX, (NULL),
4523               ("Failed to finish reading headers"));
4524         }
4525         gst_element_no_more_pads (GST_ELEMENT (demux));
4526       }
4527
4528       /* Close the segment, i.e. update segment stop with the duration
4529        * if no stop was set */
4530       if (GST_CLOCK_TIME_IS_VALID (demux->last_stop_end) &&
4531           !GST_CLOCK_TIME_IS_VALID (demux->common.segment.stop) &&
4532           GST_CLOCK_TIME_IS_VALID (demux->common.segment.start) &&
4533           demux->last_stop_end > demux->common.segment.start) {
4534         GstSegment segment = demux->common.segment;
4535         GstEvent *event;
4536
4537         segment.stop = demux->last_stop_end;
4538         event = gst_event_new_segment (&segment);
4539         gst_matroska_demux_send_event (demux, event);
4540       }
4541
4542       if (demux->common.segment.flags & GST_SEEK_FLAG_SEGMENT) {
4543         gint64 stop;
4544
4545         /* for segment playback we need to post when (in stream time)
4546          * we stopped, this is either stop (when set) or the duration. */
4547         if ((stop = demux->common.segment.stop) == -1)
4548           stop = demux->last_stop_end;
4549
4550         GST_LOG_OBJECT (demux, "Sending segment done, at end of segment");
4551         gst_element_post_message (GST_ELEMENT (demux),
4552             gst_message_new_segment_done (GST_OBJECT (demux), GST_FORMAT_TIME,
4553                 stop));
4554         gst_matroska_demux_send_event (demux,
4555             gst_event_new_segment_done (GST_FORMAT_TIME, stop));
4556       } else {
4557         push_eos = TRUE;
4558       }
4559     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
4560       /* for fatal errors we post an error message */
4561       GST_ELEMENT_ERROR (demux, STREAM, FAILED, (NULL),
4562           ("stream stopped, reason %s", reason));
4563       push_eos = TRUE;
4564     }
4565     if (push_eos) {
4566       /* send EOS, and prevent hanging if no streams yet */
4567       GST_LOG_OBJECT (demux, "Sending EOS, at end of stream");
4568       if (!gst_matroska_demux_send_event (demux, gst_event_new_eos ()) &&
4569           (ret == GST_FLOW_EOS)) {
4570         GST_ELEMENT_ERROR (demux, STREAM, DEMUX,
4571             (NULL), ("got eos but no streams (yet)"));
4572       }
4573     }
4574     return;
4575   }
4576 }
4577
4578 /*
4579  * Create and push a flushing seek event upstream
4580  */
4581 static gboolean
4582 perform_seek_to_offset (GstMatroskaDemux * demux, gdouble rate, guint64 offset)
4583 {
4584   GstEvent *event;
4585   gboolean res = 0;
4586
4587   GST_DEBUG_OBJECT (demux, "Seeking to %" G_GUINT64_FORMAT, offset);
4588
4589   event =
4590       gst_event_new_seek (rate, GST_FORMAT_BYTES,
4591       GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE, GST_SEEK_TYPE_SET, offset,
4592       GST_SEEK_TYPE_NONE, -1);
4593
4594   res = gst_pad_push_event (demux->common.sinkpad, event);
4595
4596   /* segment event will update offset */
4597   return res;
4598 }
4599
4600 static GstFlowReturn
4601 gst_matroska_demux_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
4602 {
4603   GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (parent);
4604   guint available;
4605   GstFlowReturn ret = GST_FLOW_OK;
4606   guint needed = 0;
4607   guint32 id;
4608   guint64 length;
4609
4610   if (G_UNLIKELY (GST_BUFFER_IS_DISCONT (buffer))) {
4611     GST_DEBUG_OBJECT (demux, "got DISCONT");
4612     gst_adapter_clear (demux->common.adapter);
4613     GST_OBJECT_LOCK (demux);
4614     gst_matroska_read_common_reset_streams (&demux->common,
4615         GST_CLOCK_TIME_NONE, FALSE);
4616     GST_OBJECT_UNLOCK (demux);
4617   }
4618
4619   gst_adapter_push (demux->common.adapter, buffer);
4620   buffer = NULL;
4621
4622 next:
4623   available = gst_adapter_available (demux->common.adapter);
4624
4625   ret = gst_matroska_read_common_peek_id_length_push (&demux->common,
4626       GST_ELEMENT_CAST (demux), &id, &length, &needed);
4627   if (G_UNLIKELY (ret != GST_FLOW_OK && ret != GST_FLOW_EOS))
4628     return ret;
4629
4630   GST_LOG_OBJECT (demux, "Offset %" G_GUINT64_FORMAT ", Element id 0x%x, "
4631       "size %" G_GUINT64_FORMAT ", needed %d, available %d",
4632       demux->common.offset, id, length, needed, available);
4633
4634   if (needed > available)
4635     return GST_FLOW_OK;
4636
4637   ret = gst_matroska_demux_parse_id (demux, id, length, needed);
4638   if (ret == GST_FLOW_EOS) {
4639     /* need more data */
4640     return GST_FLOW_OK;
4641   } else if (ret != GST_FLOW_OK) {
4642     return ret;
4643   } else
4644     goto next;
4645 }
4646
4647 static gboolean
4648 gst_matroska_demux_handle_sink_event (GstPad * pad, GstObject * parent,
4649     GstEvent * event)
4650 {
4651   gboolean res = TRUE;
4652   GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (parent);
4653
4654   GST_DEBUG_OBJECT (demux,
4655       "have event type %s: %p on sink pad", GST_EVENT_TYPE_NAME (event), event);
4656
4657   switch (GST_EVENT_TYPE (event)) {
4658     case GST_EVENT_SEGMENT:
4659     {
4660       const GstSegment *segment;
4661
4662       /* some debug output */
4663       gst_event_parse_segment (event, &segment);
4664       /* FIXME: do we need to update segment base here (like accum in 0.10)? */
4665       GST_DEBUG_OBJECT (demux,
4666           "received format %d segment %" GST_SEGMENT_FORMAT, segment->format,
4667           segment);
4668
4669       if (demux->common.state < GST_MATROSKA_READ_STATE_DATA) {
4670         GST_DEBUG_OBJECT (demux, "still starting");
4671         goto exit;
4672       }
4673
4674       /* we only expect a BYTE segment, e.g. following a seek */
4675       if (segment->format != GST_FORMAT_BYTES) {
4676         GST_DEBUG_OBJECT (demux, "unsupported segment format, ignoring");
4677         goto exit;
4678       }
4679
4680       GST_DEBUG_OBJECT (demux, "clearing segment state");
4681       GST_OBJECT_LOCK (demux);
4682       /* clear current segment leftover */
4683       gst_adapter_clear (demux->common.adapter);
4684       /* and some streaming setup */
4685       demux->common.offset = segment->start;
4686       /* accumulate base based on current position */
4687       if (GST_CLOCK_TIME_IS_VALID (demux->common.segment.position))
4688         demux->common.segment.base +=
4689             (MAX (demux->common.segment.position, demux->stream_start_time)
4690             - demux->stream_start_time) / fabs (demux->common.segment.rate);
4691       /* do not know where we are;
4692        * need to come across a cluster and generate segment */
4693       demux->common.segment.position = GST_CLOCK_TIME_NONE;
4694       demux->cluster_time = GST_CLOCK_TIME_NONE;
4695       demux->cluster_offset = 0;
4696       demux->need_segment = TRUE;
4697       /* but keep some of the upstream segment */
4698       demux->common.segment.rate = segment->rate;
4699       /* also check if need to keep some of the requested seek position */
4700       if (demux->seek_offset == segment->start) {
4701         GST_DEBUG_OBJECT (demux, "position matches requested seek");
4702         demux->common.segment.position = demux->requested_seek_time;
4703       } else {
4704         GST_DEBUG_OBJECT (demux, "unexpected segment position");
4705       }
4706       demux->requested_seek_time = GST_CLOCK_TIME_NONE;
4707       demux->seek_offset = -1;
4708       GST_OBJECT_UNLOCK (demux);
4709     exit:
4710       /* chain will send initial segment after pads have been added,
4711        * or otherwise come up with one */
4712       GST_DEBUG_OBJECT (demux, "eating event");
4713       gst_event_unref (event);
4714       res = TRUE;
4715       break;
4716     }
4717     case GST_EVENT_EOS:
4718     {
4719       if (demux->common.state != GST_MATROSKA_READ_STATE_DATA) {
4720         gst_event_unref (event);
4721         GST_ELEMENT_ERROR (demux, STREAM, DEMUX,
4722             (NULL), ("got eos and didn't receive a complete header object"));
4723       } else if (demux->common.num_streams == 0) {
4724         GST_ELEMENT_ERROR (demux, STREAM, DEMUX,
4725             (NULL), ("got eos but no streams (yet)"));
4726       } else {
4727         gst_matroska_demux_send_event (demux, event);
4728       }
4729       break;
4730     }
4731     case GST_EVENT_FLUSH_STOP:
4732     {
4733       guint64 dur;
4734
4735       gst_adapter_clear (demux->common.adapter);
4736       GST_OBJECT_LOCK (demux);
4737       gst_matroska_read_common_reset_streams (&demux->common,
4738           GST_CLOCK_TIME_NONE, TRUE);
4739       dur = demux->common.segment.duration;
4740       gst_segment_init (&demux->common.segment, GST_FORMAT_TIME);
4741       demux->common.segment.duration = dur;
4742       demux->cluster_time = GST_CLOCK_TIME_NONE;
4743       demux->cluster_offset = 0;
4744       GST_OBJECT_UNLOCK (demux);
4745       /* fall-through */
4746     }
4747     default:
4748       res = gst_pad_event_default (pad, parent, event);
4749       break;
4750   }
4751
4752   return res;
4753 }
4754
4755 static gboolean
4756 gst_matroska_demux_sink_activate (GstPad * sinkpad, GstObject * parent)
4757 {
4758   GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (parent);
4759   GstQuery *query;
4760   gboolean pull_mode = FALSE;
4761
4762   query = gst_query_new_scheduling ();
4763
4764   if (gst_pad_peer_query (sinkpad, query))
4765     pull_mode = gst_query_has_scheduling_mode_with_flags (query,
4766         GST_PAD_MODE_PULL, GST_SCHEDULING_FLAG_SEEKABLE);
4767
4768   gst_query_unref (query);
4769
4770   if (pull_mode) {
4771     GST_DEBUG ("going to pull mode");
4772     demux->streaming = FALSE;
4773     return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PULL, TRUE);
4774   } else {
4775     GST_DEBUG ("going to push (streaming) mode");
4776     demux->streaming = TRUE;
4777     return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
4778   }
4779 }
4780
4781 static gboolean
4782 gst_matroska_demux_sink_activate_mode (GstPad * sinkpad, GstObject * parent,
4783     GstPadMode mode, gboolean active)
4784 {
4785   switch (mode) {
4786     case GST_PAD_MODE_PULL:
4787       if (active) {
4788         /* if we have a scheduler we can start the task */
4789         gst_pad_start_task (sinkpad, (GstTaskFunction) gst_matroska_demux_loop,
4790             sinkpad, NULL);
4791       } else {
4792         gst_pad_stop_task (sinkpad);
4793       }
4794       return TRUE;
4795     case GST_PAD_MODE_PUSH:
4796       return TRUE;
4797     default:
4798       return FALSE;
4799   }
4800 }
4801
4802 static void
4803 gst_duration_to_fraction (guint64 duration, gint * dest_n, gint * dest_d)
4804 {
4805   static const int common_den[] = { 1, 2, 3, 4, 1001 };
4806   int n, d;
4807   int i;
4808   guint64 a;
4809
4810   for (i = 0; i < G_N_ELEMENTS (common_den); i++) {
4811     d = common_den[i];
4812     n = floor (0.5 + (d * 1e9) / duration);
4813     a = gst_util_uint64_scale_int (1000000000, d, n);
4814     if (duration >= a - 1 && duration <= a + 1) {
4815       goto out;
4816     }
4817   }
4818
4819   gst_util_double_to_fraction (1e9 / duration, &n, &d);
4820
4821 out:
4822   /* set results */
4823   *dest_n = n;
4824   *dest_d = d;
4825 }
4826
4827 static GstCaps *
4828 gst_matroska_demux_video_caps (GstMatroskaTrackVideoContext *
4829     videocontext, const gchar * codec_id, guint8 * data, guint size,
4830     gchar ** codec_name, guint32 * riff_fourcc)
4831 {
4832   GstMatroskaTrackContext *context = (GstMatroskaTrackContext *) videocontext;
4833   GstCaps *caps = NULL;
4834
4835   g_assert (videocontext != NULL);
4836   g_assert (codec_name != NULL);
4837
4838   if (riff_fourcc)
4839     *riff_fourcc = 0;
4840
4841   /* TODO: check if we have all codec types from matroska-ids.h
4842    *       check if we have to do more special things with codec_private
4843    *
4844    * Add support for
4845    *  GST_MATROSKA_CODEC_ID_VIDEO_QUICKTIME
4846    *  GST_MATROSKA_CODEC_ID_VIDEO_SNOW
4847    */
4848
4849   if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC)) {
4850     gst_riff_strf_vids *vids = NULL;
4851
4852     if (data) {
4853       GstBuffer *buf = NULL;
4854
4855       vids = (gst_riff_strf_vids *) data;
4856
4857       /* assure size is big enough */
4858       if (size < 24) {
4859         GST_WARNING ("Too small BITMAPINFOHEADER (%d bytes)", size);
4860         return NULL;
4861       }
4862       if (size < sizeof (gst_riff_strf_vids)) {
4863         vids = g_new (gst_riff_strf_vids, 1);
4864         memcpy (vids, data, size);
4865       }
4866
4867       /* little-endian -> byte-order */
4868       vids->size = GUINT32_FROM_LE (vids->size);
4869       vids->width = GUINT32_FROM_LE (vids->width);
4870       vids->height = GUINT32_FROM_LE (vids->height);
4871       vids->planes = GUINT16_FROM_LE (vids->planes);
4872       vids->bit_cnt = GUINT16_FROM_LE (vids->bit_cnt);
4873       vids->compression = GUINT32_FROM_LE (vids->compression);
4874       vids->image_size = GUINT32_FROM_LE (vids->image_size);
4875       vids->xpels_meter = GUINT32_FROM_LE (vids->xpels_meter);
4876       vids->ypels_meter = GUINT32_FROM_LE (vids->ypels_meter);
4877       vids->num_colors = GUINT32_FROM_LE (vids->num_colors);
4878       vids->imp_colors = GUINT32_FROM_LE (vids->imp_colors);
4879
4880       if (size > sizeof (gst_riff_strf_vids)) { /* some extra_data */
4881         gsize offset = sizeof (gst_riff_strf_vids);
4882
4883         buf =
4884             gst_buffer_new_wrapped (g_memdup ((guint8 *) vids + offset,
4885                 size - offset), size - offset);
4886       }
4887
4888       if (riff_fourcc)
4889         *riff_fourcc = vids->compression;
4890
4891       caps = gst_riff_create_video_caps (vids->compression, NULL, vids,
4892           buf, NULL, codec_name);
4893
4894       if (caps == NULL) {
4895         GST_WARNING ("Unhandled RIFF fourcc %" GST_FOURCC_FORMAT,
4896             GST_FOURCC_ARGS (vids->compression));
4897       }
4898
4899       if (buf)
4900         gst_buffer_unref (buf);
4901
4902       if (vids != (gst_riff_strf_vids *) data)
4903         g_free (vids);
4904     }
4905   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_UNCOMPRESSED)) {
4906     const gchar *format = NULL;
4907
4908     switch (videocontext->fourcc) {
4909       case GST_MAKE_FOURCC ('I', '4', '2', '0'):
4910         *codec_name = g_strdup ("Raw planar YUV 4:2:0");
4911         format = "I420";
4912         break;
4913       case GST_MAKE_FOURCC ('Y', 'U', 'Y', '2'):
4914         *codec_name = g_strdup ("Raw packed YUV 4:2:2");
4915         format = "YUY2";
4916         break;
4917       case GST_MAKE_FOURCC ('Y', 'V', '1', '2'):
4918         *codec_name = g_strdup ("Raw packed YUV 4:2:0");
4919         format = "YV12";
4920         break;
4921       case GST_MAKE_FOURCC ('U', 'Y', 'V', 'Y'):
4922         *codec_name = g_strdup ("Raw packed YUV 4:2:2");
4923         format = "UYVY";
4924         break;
4925       case GST_MAKE_FOURCC ('A', 'Y', 'U', 'V'):
4926         *codec_name = g_strdup ("Raw packed YUV 4:4:4 with alpha channel");
4927         format = "AYUV";
4928         break;
4929
4930       default:
4931         GST_DEBUG ("Unknown fourcc %" GST_FOURCC_FORMAT,
4932             GST_FOURCC_ARGS (videocontext->fourcc));
4933         return NULL;
4934     }
4935
4936     caps = gst_caps_new_simple ("video/x-raw",
4937         "format", G_TYPE_STRING, format, NULL);
4938   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_SP)) {
4939     caps = gst_caps_new_simple ("video/x-divx",
4940         "divxversion", G_TYPE_INT, 4, NULL);
4941     *codec_name = g_strdup ("MPEG-4 simple profile");
4942   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_ASP) ||
4943       !strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_AP)) {
4944     caps = gst_caps_new_simple ("video/mpeg",
4945         "mpegversion", G_TYPE_INT, 4,
4946         "systemstream", G_TYPE_BOOLEAN, FALSE, NULL);
4947     if (data) {
4948       GstBuffer *priv;
4949
4950       priv = gst_buffer_new_wrapped (g_memdup (data, size), size);
4951       gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
4952       gst_buffer_unref (priv);
4953     }
4954     if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_ASP))
4955       *codec_name = g_strdup ("MPEG-4 advanced simple profile");
4956     else
4957       *codec_name = g_strdup ("MPEG-4 advanced profile");
4958   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MSMPEG4V3)) {
4959 #if 0
4960     caps = gst_caps_new_full (gst_structure_new ("video/x-divx",
4961             "divxversion", G_TYPE_INT, 3, NULL),
4962         gst_structure_new ("video/x-msmpeg",
4963             "msmpegversion", G_TYPE_INT, 43, NULL), NULL);
4964 #endif
4965     caps = gst_caps_new_simple ("video/x-msmpeg",
4966         "msmpegversion", G_TYPE_INT, 43, NULL);
4967     *codec_name = g_strdup ("Microsoft MPEG-4 v.3");
4968   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG1) ||
4969       !strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG2)) {
4970     gint mpegversion;
4971
4972     if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG1))
4973       mpegversion = 1;
4974     else
4975       mpegversion = 2;
4976
4977     caps = gst_caps_new_simple ("video/mpeg",
4978         "systemstream", G_TYPE_BOOLEAN, FALSE,
4979         "mpegversion", G_TYPE_INT, mpegversion, NULL);
4980     *codec_name = g_strdup_printf ("MPEG-%d video", mpegversion);
4981     context->postprocess_frame = gst_matroska_demux_add_mpeg_seq_header;
4982   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MJPEG)) {
4983     caps = gst_caps_new_empty_simple ("image/jpeg");
4984     *codec_name = g_strdup ("Motion-JPEG");
4985   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_AVC)) {
4986     caps = gst_caps_new_empty_simple ("video/x-h264");
4987     if (data) {
4988       GstBuffer *priv;
4989
4990       /* First byte is the version, second is the profile indication, and third
4991        * is the 5 contraint_set_flags and 3 reserved bits. Fourth byte is the
4992        * level indication. */
4993       gst_codec_utils_h264_caps_set_level_and_profile (caps, data + 1,
4994           size - 1);
4995
4996       priv = gst_buffer_new_wrapped (g_memdup (data, size), size);
4997       gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
4998       gst_buffer_unref (priv);
4999
5000       gst_caps_set_simple (caps, "stream-format", G_TYPE_STRING, "avc",
5001           "alignment", G_TYPE_STRING, "au", NULL);
5002     } else {
5003       GST_WARNING ("No codec data found, assuming output is byte-stream");
5004       gst_caps_set_simple (caps, "stream-format", G_TYPE_STRING, "byte-stream",
5005           NULL);
5006     }
5007     *codec_name = g_strdup ("H264");
5008   } else if ((!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO1)) ||
5009       (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO2)) ||
5010       (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO3)) ||
5011       (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO4))) {
5012     gint rmversion = -1;
5013
5014     if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO1))
5015       rmversion = 1;
5016     else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO2))
5017       rmversion = 2;
5018     else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO3))
5019       rmversion = 3;
5020     else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO4))
5021       rmversion = 4;
5022
5023     caps = gst_caps_new_simple ("video/x-pn-realvideo",
5024         "rmversion", G_TYPE_INT, rmversion, NULL);
5025     GST_DEBUG ("data:%p, size:0x%x", data, size);
5026     /* We need to extract the extradata ! */
5027     if (data && (size >= 0x22)) {
5028       GstBuffer *priv;
5029       guint rformat;
5030       guint subformat;
5031
5032       subformat = GST_READ_UINT32_BE (data + 0x1a);
5033       rformat = GST_READ_UINT32_BE (data + 0x1e);
5034
5035       priv =
5036           gst_buffer_new_wrapped (g_memdup (data + 0x1a, size - 0x1a),
5037           size - 0x1a);
5038       gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, "format",
5039           G_TYPE_INT, rformat, "subformat", G_TYPE_INT, subformat, NULL);
5040       gst_buffer_unref (priv);
5041
5042     }
5043     *codec_name = g_strdup_printf ("RealVideo %d.0", rmversion);
5044   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_THEORA)) {
5045     caps = gst_caps_new_empty_simple ("video/x-theora");
5046     context->stream_headers =
5047         gst_matroska_parse_xiph_stream_headers (context->codec_priv,
5048         context->codec_priv_size);
5049     /* FIXME: mark stream as broken and skip if there are no stream headers */
5050     context->send_stream_headers = TRUE;
5051   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_DIRAC)) {
5052     caps = gst_caps_new_empty_simple ("video/x-dirac");
5053     *codec_name = g_strdup_printf ("Dirac");
5054   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_VP8)) {
5055     caps = gst_caps_new_empty_simple ("video/x-vp8");
5056     *codec_name = g_strdup_printf ("On2 VP8");
5057   } else {
5058     GST_WARNING ("Unknown codec '%s', cannot build Caps", codec_id);
5059     return NULL;
5060   }
5061
5062   if (caps != NULL) {
5063     int i;
5064     GstStructure *structure;
5065
5066     for (i = 0; i < gst_caps_get_size (caps); i++) {
5067       structure = gst_caps_get_structure (caps, i);
5068
5069       /* FIXME: use the real unit here! */
5070       GST_DEBUG ("video size %dx%d, target display size %dx%d (any unit)",
5071           videocontext->pixel_width,
5072           videocontext->pixel_height,
5073           videocontext->display_width, videocontext->display_height);
5074
5075       /* pixel width and height are the w and h of the video in pixels */
5076       if (videocontext->pixel_width > 0 && videocontext->pixel_height > 0) {
5077         gint w = videocontext->pixel_width;
5078         gint h = videocontext->pixel_height;
5079
5080         gst_structure_set (structure,
5081             "width", G_TYPE_INT, w, "height", G_TYPE_INT, h, NULL);
5082       }
5083
5084       if (videocontext->display_width > 0 || videocontext->display_height > 0) {
5085         int n, d;
5086
5087         if (videocontext->display_width <= 0)
5088           videocontext->display_width = videocontext->pixel_width;
5089         if (videocontext->display_height <= 0)
5090           videocontext->display_height = videocontext->pixel_height;
5091
5092         /* calculate the pixel aspect ratio using the display and pixel w/h */
5093         n = videocontext->display_width * videocontext->pixel_height;
5094         d = videocontext->display_height * videocontext->pixel_width;
5095         GST_DEBUG ("setting PAR to %d/%d", n, d);
5096         gst_structure_set (structure, "pixel-aspect-ratio",
5097             GST_TYPE_FRACTION,
5098             videocontext->display_width * videocontext->pixel_height,
5099             videocontext->display_height * videocontext->pixel_width, NULL);
5100       }
5101
5102       if (videocontext->default_fps > 0.0) {
5103         GValue fps_double = { 0, };
5104         GValue fps_fraction = { 0, };
5105
5106         g_value_init (&fps_double, G_TYPE_DOUBLE);
5107         g_value_init (&fps_fraction, GST_TYPE_FRACTION);
5108         g_value_set_double (&fps_double, videocontext->default_fps);
5109         g_value_transform (&fps_double, &fps_fraction);
5110
5111         GST_DEBUG ("using default fps %f", videocontext->default_fps);
5112
5113         gst_structure_set_value (structure, "framerate", &fps_fraction);
5114         g_value_unset (&fps_double);
5115         g_value_unset (&fps_fraction);
5116       } else if (context->default_duration > 0) {
5117         int fps_n, fps_d;
5118
5119         gst_duration_to_fraction (context->default_duration, &fps_n, &fps_d);
5120
5121         GST_INFO ("using default duration %" G_GUINT64_FORMAT
5122             " framerate %d/%d", context->default_duration, fps_n, fps_d);
5123
5124         gst_structure_set (structure, "framerate", GST_TYPE_FRACTION,
5125             fps_n, fps_d, NULL);
5126       } else {
5127         /* sort of a hack to get most codecs to support,
5128          * even if the default_duration is missing */
5129         gst_structure_set (structure, "framerate", GST_TYPE_FRACTION,
5130             25, 1, NULL);
5131       }
5132
5133       if (videocontext->parent.flags & GST_MATROSKA_VIDEOTRACK_INTERLACED)
5134         gst_structure_set (structure, "interlace-mode", G_TYPE_STRING,
5135             "mixed", NULL);
5136     }
5137
5138     caps = gst_caps_simplify (caps);
5139   }
5140
5141   return caps;
5142 }
5143
5144 /*
5145  * Some AAC specific code... *sigh*
5146  * FIXME: maybe we should use '15' and code the sample rate explicitly
5147  * if the sample rate doesn't match the predefined rates exactly? (tpm)
5148  */
5149
5150 static gint
5151 aac_rate_idx (gint rate)
5152 {
5153   if (92017 <= rate)
5154     return 0;
5155   else if (75132 <= rate)
5156     return 1;
5157   else if (55426 <= rate)
5158     return 2;
5159   else if (46009 <= rate)
5160     return 3;
5161   else if (37566 <= rate)
5162     return 4;
5163   else if (27713 <= rate)
5164     return 5;
5165   else if (23004 <= rate)
5166     return 6;
5167   else if (18783 <= rate)
5168     return 7;
5169   else if (13856 <= rate)
5170     return 8;
5171   else if (11502 <= rate)
5172     return 9;
5173   else if (9391 <= rate)
5174     return 10;
5175   else
5176     return 11;
5177 }
5178
5179 static gint
5180 aac_profile_idx (const gchar * codec_id)
5181 {
5182   gint profile;
5183
5184   if (strlen (codec_id) <= 12)
5185     profile = 3;
5186   else if (!strncmp (&codec_id[12], "MAIN", 4))
5187     profile = 0;
5188   else if (!strncmp (&codec_id[12], "LC", 2))
5189     profile = 1;
5190   else if (!strncmp (&codec_id[12], "SSR", 3))
5191     profile = 2;
5192   else
5193     profile = 3;
5194
5195   return profile;
5196 }
5197
5198 #define AAC_SYNC_EXTENSION_TYPE 0x02b7
5199
5200 static GstCaps *
5201 gst_matroska_demux_audio_caps (GstMatroskaTrackAudioContext *
5202     audiocontext, const gchar * codec_id, guint8 * data, guint size,
5203     gchar ** codec_name, guint16 * riff_audio_fmt)
5204 {
5205   GstMatroskaTrackContext *context = (GstMatroskaTrackContext *) audiocontext;
5206   GstCaps *caps = NULL;
5207
5208   g_assert (audiocontext != NULL);
5209   g_assert (codec_name != NULL);
5210
5211   if (riff_audio_fmt)
5212     *riff_audio_fmt = 0;
5213
5214   /* TODO: check if we have all codec types from matroska-ids.h
5215    *       check if we have to do more special things with codec_private
5216    *       check if we need bitdepth in different places too
5217    *       implement channel position magic
5218    * Add support for:
5219    *  GST_MATROSKA_CODEC_ID_AUDIO_AC3_BSID9
5220    *  GST_MATROSKA_CODEC_ID_AUDIO_AC3_BSID10
5221    *  GST_MATROSKA_CODEC_ID_AUDIO_QUICKTIME_QDMC
5222    *  GST_MATROSKA_CODEC_ID_AUDIO_QUICKTIME_QDM2
5223    */
5224
5225   if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L1) ||
5226       !strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L2) ||
5227       !strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L3)) {
5228     gint layer;
5229
5230     if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L1))
5231       layer = 1;
5232     else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L2))
5233       layer = 2;
5234     else
5235       layer = 3;
5236
5237     caps = gst_caps_new_simple ("audio/mpeg",
5238         "mpegversion", G_TYPE_INT, 1, "layer", G_TYPE_INT, layer, NULL);
5239     *codec_name = g_strdup_printf ("MPEG-1 layer %d", layer);
5240   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_PCM_INT_BE) ||
5241       !strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_PCM_INT_LE)) {
5242     gboolean sign;
5243     gint endianness;
5244     GstAudioFormat format;
5245
5246     sign = (audiocontext->bitdepth != 8);
5247     if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_PCM_INT_BE))
5248       endianness = G_BIG_ENDIAN;
5249     else
5250       endianness = G_LITTLE_ENDIAN;
5251
5252     format = gst_audio_format_build_integer (sign, endianness,
5253         audiocontext->bitdepth, audiocontext->bitdepth);
5254
5255     /* FIXME: Channel mask and reordering */
5256     caps = gst_caps_new_simple ("audio/x-raw",
5257         "format", G_TYPE_STRING, gst_audio_format_to_string (format),
5258         "layout", G_TYPE_STRING, "interleaved", NULL);
5259
5260     *codec_name = g_strdup_printf ("Raw %d-bit PCM audio",
5261         audiocontext->bitdepth);
5262     context->alignment = audiocontext->bitdepth / 8;
5263   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_PCM_FLOAT)) {
5264     const gchar *format;
5265     if (audiocontext->bitdepth == 32)
5266       format = "F32LE";
5267     else
5268       format = "F64LE";
5269     /* FIXME: Channel mask and reordering */
5270     caps = gst_caps_new_simple ("audio/x-raw",
5271         "format", G_TYPE_STRING, format,
5272         "layout", G_TYPE_STRING, "interleaved", NULL);
5273     *codec_name = g_strdup_printf ("Raw %d-bit floating-point audio",
5274         audiocontext->bitdepth);
5275     context->alignment = audiocontext->bitdepth / 8;
5276   } else if (!strncmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_AC3,
5277           strlen (GST_MATROSKA_CODEC_ID_AUDIO_AC3))) {
5278     caps = gst_caps_new_simple ("audio/x-ac3",
5279         "framed", G_TYPE_BOOLEAN, TRUE, NULL);
5280     *codec_name = g_strdup ("AC-3 audio");
5281   } else if (!strncmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_EAC3,
5282           strlen (GST_MATROSKA_CODEC_ID_AUDIO_EAC3))) {
5283     caps = gst_caps_new_simple ("audio/x-eac3",
5284         "framed", G_TYPE_BOOLEAN, TRUE, NULL);
5285     *codec_name = g_strdup ("E-AC-3 audio");
5286   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_DTS)) {
5287     caps = gst_caps_new_empty_simple ("audio/x-dts");
5288     *codec_name = g_strdup ("DTS audio");
5289   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_VORBIS)) {
5290     caps = gst_caps_new_empty_simple ("audio/x-vorbis");
5291     context->stream_headers =
5292         gst_matroska_parse_xiph_stream_headers (context->codec_priv,
5293         context->codec_priv_size);
5294     /* FIXME: mark stream as broken and skip if there are no stream headers */
5295     context->send_stream_headers = TRUE;
5296   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_FLAC)) {
5297     caps = gst_caps_new_empty_simple ("audio/x-flac");
5298     context->stream_headers =
5299         gst_matroska_parse_flac_stream_headers (context->codec_priv,
5300         context->codec_priv_size);
5301     /* FIXME: mark stream as broken and skip if there are no stream headers */
5302     context->send_stream_headers = TRUE;
5303   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_SPEEX)) {
5304     caps = gst_caps_new_empty_simple ("audio/x-speex");
5305     context->stream_headers =
5306         gst_matroska_parse_speex_stream_headers (context->codec_priv,
5307         context->codec_priv_size);
5308     /* FIXME: mark stream as broken and skip if there are no stream headers */
5309     context->send_stream_headers = TRUE;
5310   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_ACM)) {
5311     gst_riff_strf_auds auds;
5312
5313     if (data) {
5314       GstBuffer *codec_data;
5315
5316       /* little-endian -> byte-order */
5317       auds.format = GST_READ_UINT16_LE (data);
5318       auds.channels = GST_READ_UINT16_LE (data + 2);
5319       auds.rate = GST_READ_UINT32_LE (data + 4);
5320       auds.av_bps = GST_READ_UINT32_LE (data + 8);
5321       auds.blockalign = GST_READ_UINT16_LE (data + 12);
5322       auds.bits_per_sample = GST_READ_UINT16_LE (data + 16);
5323
5324       /* 18 is the waveformatex size */
5325       codec_data = gst_buffer_new_wrapped_full (GST_MEMORY_FLAG_READONLY,
5326           data + 18, auds.bits_per_sample, 0, auds.bits_per_sample, NULL, NULL);
5327
5328       if (riff_audio_fmt)
5329         *riff_audio_fmt = auds.format;
5330
5331       /* FIXME: Handle reorder map */
5332       caps = gst_riff_create_audio_caps (auds.format, NULL, &auds, NULL,
5333           codec_data, codec_name, NULL);
5334       gst_buffer_unref (codec_data);
5335
5336       if (caps == NULL) {
5337         GST_WARNING ("Unhandled RIFF audio format 0x%02x", auds.format);
5338       }
5339     }
5340   } else if (g_str_has_prefix (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_AAC)) {
5341     GstBuffer *priv = NULL;
5342     gint mpegversion;
5343     gint rate_idx, profile;
5344     guint8 *data = NULL;
5345
5346     /* unspecified AAC profile with opaque private codec data */
5347     if (strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_AAC) == 0) {
5348       if (context->codec_priv_size >= 2) {
5349         guint obj_type, freq_index, explicit_freq_bytes = 0;
5350
5351         codec_id = GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG4;
5352         mpegversion = 4;
5353         freq_index = (GST_READ_UINT16_BE (context->codec_priv) & 0x780) >> 7;
5354         obj_type = (GST_READ_UINT16_BE (context->codec_priv) & 0xF800) >> 11;
5355         if (freq_index == 15)
5356           explicit_freq_bytes = 3;
5357         GST_DEBUG ("obj_type = %u, freq_index = %u", obj_type, freq_index);
5358         priv = gst_buffer_new_wrapped (g_memdup (context->codec_priv,
5359                 context->codec_priv_size), context->codec_priv_size);
5360         /* assume SBR if samplerate <= 24kHz */
5361         if (obj_type == 5 || (freq_index >= 6 && freq_index != 15) ||
5362             (context->codec_priv_size == (5 + explicit_freq_bytes))) {
5363           audiocontext->samplerate *= 2;
5364         }
5365       } else {
5366         GST_WARNING ("Opaque A_AAC codec ID, but no codec private data");
5367         /* this is pretty broken;
5368          * maybe we need to make up some default private,
5369          * or maybe ADTS data got dumped in.
5370          * Let's set up some private data now, and check actual data later */
5371         /* just try this and see what happens ... */
5372         codec_id = GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG4;
5373         context->postprocess_frame = gst_matroska_demux_check_aac;
5374       }
5375     }
5376
5377     /* make up decoder-specific data if it is not supplied */
5378     if (priv == NULL) {
5379       GstMapInfo map;
5380
5381       priv = gst_buffer_new_allocate (NULL, 5, NULL);
5382       gst_buffer_map (priv, &map, GST_MAP_WRITE);
5383       data = map.data;
5384       rate_idx = aac_rate_idx (audiocontext->samplerate);
5385       profile = aac_profile_idx (codec_id);
5386
5387       data[0] = ((profile + 1) << 3) | ((rate_idx & 0xE) >> 1);
5388       data[1] = ((rate_idx & 0x1) << 7) | (audiocontext->channels << 3);
5389
5390       if (!strncmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG2,
5391               strlen (GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG2))) {
5392         mpegversion = 2;
5393         gst_buffer_unmap (priv, &map);
5394         gst_buffer_set_size (priv, 2);
5395       } else if (!strncmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG4,
5396               strlen (GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG4))) {
5397         mpegversion = 4;
5398
5399         if (g_strrstr (codec_id, "SBR")) {
5400           /* HE-AAC (aka SBR AAC) */
5401           audiocontext->samplerate *= 2;
5402           rate_idx = aac_rate_idx (audiocontext->samplerate);
5403           data[2] = AAC_SYNC_EXTENSION_TYPE >> 3;
5404           data[3] = ((AAC_SYNC_EXTENSION_TYPE & 0x07) << 5) | 5;
5405           data[4] = (1 << 7) | (rate_idx << 3);
5406           gst_buffer_unmap (priv, &map);
5407         } else {
5408           gst_buffer_unmap (priv, &map);
5409           gst_buffer_set_size (priv, 2);
5410         }
5411       } else {
5412         gst_buffer_unmap (priv, &map);
5413         gst_buffer_unref (priv);
5414         priv = NULL;
5415         GST_ERROR ("Unknown AAC profile and no codec private data");
5416       }
5417     }
5418
5419     if (priv) {
5420       caps = gst_caps_new_simple ("audio/mpeg",
5421           "mpegversion", G_TYPE_INT, mpegversion,
5422           "framed", G_TYPE_BOOLEAN, TRUE, NULL);
5423       gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
5424       *codec_name = g_strdup_printf ("MPEG-%d AAC audio", mpegversion);
5425       gst_buffer_unref (priv);
5426     }
5427   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_TTA)) {
5428     caps = gst_caps_new_simple ("audio/x-tta",
5429         "width", G_TYPE_INT, audiocontext->bitdepth, NULL);
5430     *codec_name = g_strdup ("TTA audio");
5431   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_WAVPACK4)) {
5432     caps = gst_caps_new_simple ("audio/x-wavpack",
5433         "width", G_TYPE_INT, audiocontext->bitdepth,
5434         "framed", G_TYPE_BOOLEAN, TRUE, NULL);
5435     *codec_name = g_strdup ("Wavpack audio");
5436     context->postprocess_frame = gst_matroska_demux_add_wvpk_header;
5437     audiocontext->wvpk_block_index = 0;
5438   } else if ((!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_14_4)) ||
5439       (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_14_4)) ||
5440       (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_COOK))) {
5441     gint raversion = -1;
5442
5443     if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_14_4))
5444       raversion = 1;
5445     else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_COOK))
5446       raversion = 8;
5447     else
5448       raversion = 2;
5449
5450     caps = gst_caps_new_simple ("audio/x-pn-realaudio",
5451         "raversion", G_TYPE_INT, raversion, NULL);
5452     /* Extract extra information from caps, mapping varies based on codec */
5453     if (data && (size >= 0x50)) {
5454       GstBuffer *priv;
5455       guint flavor;
5456       guint packet_size;
5457       guint height;
5458       guint leaf_size;
5459       guint sample_width;
5460       guint extra_data_size;
5461
5462       GST_ERROR ("real audio raversion:%d", raversion);
5463       if (raversion == 8) {
5464         /* COOK */
5465         flavor = GST_READ_UINT16_BE (data + 22);
5466         packet_size = GST_READ_UINT32_BE (data + 24);
5467         height = GST_READ_UINT16_BE (data + 40);
5468         leaf_size = GST_READ_UINT16_BE (data + 44);
5469         sample_width = GST_READ_UINT16_BE (data + 58);
5470         extra_data_size = GST_READ_UINT32_BE (data + 74);
5471
5472         GST_ERROR
5473             ("flavor:%d, packet_size:%d, height:%d, leaf_size:%d, sample_width:%d, extra_data_size:%d",
5474             flavor, packet_size, height, leaf_size, sample_width,
5475             extra_data_size);
5476         gst_caps_set_simple (caps, "flavor", G_TYPE_INT, flavor, "packet_size",
5477             G_TYPE_INT, packet_size, "height", G_TYPE_INT, height, "leaf_size",
5478             G_TYPE_INT, leaf_size, "width", G_TYPE_INT, sample_width, NULL);
5479
5480         if ((size - 78) >= extra_data_size) {
5481           priv = gst_buffer_new_wrapped (g_memdup (data + 78, extra_data_size),
5482               extra_data_size);
5483           gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
5484           gst_buffer_unref (priv);
5485         }
5486       }
5487     }
5488
5489     *codec_name = g_strdup_printf ("RealAudio %d.0", raversion);
5490   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_SIPR)) {
5491     caps = gst_caps_new_empty_simple ("audio/x-sipro");
5492     *codec_name = g_strdup ("Sipro/ACELP.NET Voice Codec");
5493   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_RALF)) {
5494     caps = gst_caps_new_empty_simple ("audio/x-ralf-mpeg4-generic");
5495     *codec_name = g_strdup ("Real Audio Lossless");
5496   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_ATRC)) {
5497     caps = gst_caps_new_empty_simple ("audio/x-vnd.sony.atrac3");
5498     *codec_name = g_strdup ("Sony ATRAC3");
5499   } else {
5500     GST_WARNING ("Unknown codec '%s', cannot build Caps", codec_id);
5501     return NULL;
5502   }
5503
5504   if (caps != NULL) {
5505     if (audiocontext->samplerate > 0 && audiocontext->channels > 0) {
5506       gint i;
5507
5508       for (i = 0; i < gst_caps_get_size (caps); i++) {
5509         gst_structure_set (gst_caps_get_structure (caps, i),
5510             "channels", G_TYPE_INT, audiocontext->channels,
5511             "rate", G_TYPE_INT, audiocontext->samplerate, NULL);
5512       }
5513     }
5514
5515     caps = gst_caps_simplify (caps);
5516   }
5517
5518   return caps;
5519 }
5520
5521 static GstCaps *
5522 gst_matroska_demux_subtitle_caps (GstMatroskaTrackSubtitleContext *
5523     subtitlecontext, const gchar * codec_id, gpointer data, guint size)
5524 {
5525   GstCaps *caps = NULL;
5526   GstMatroskaTrackContext *context =
5527       (GstMatroskaTrackContext *) subtitlecontext;
5528
5529   /* for backwards compatibility */
5530   if (!g_ascii_strcasecmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_ASCII))
5531     codec_id = GST_MATROSKA_CODEC_ID_SUBTITLE_UTF8;
5532   else if (!g_ascii_strcasecmp (codec_id, "S_SSA"))
5533     codec_id = GST_MATROSKA_CODEC_ID_SUBTITLE_SSA;
5534   else if (!g_ascii_strcasecmp (codec_id, "S_ASS"))
5535     codec_id = GST_MATROSKA_CODEC_ID_SUBTITLE_ASS;
5536   else if (!g_ascii_strcasecmp (codec_id, "S_USF"))
5537     codec_id = GST_MATROSKA_CODEC_ID_SUBTITLE_USF;
5538
5539   /* TODO: Add GST_MATROSKA_CODEC_ID_SUBTITLE_BMP support
5540    * Check if we have to do something with codec_private */
5541   if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_UTF8)) {
5542     /* well, plain text simply does not have a lot of markup ... */
5543     caps = gst_caps_new_simple ("text/x-raw", "format", G_TYPE_STRING,
5544         "pango-markup", NULL);
5545     context->postprocess_frame = gst_matroska_demux_check_subtitle_buffer;
5546     subtitlecontext->check_markup = TRUE;
5547   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_SSA)) {
5548     caps = gst_caps_new_empty_simple ("application/x-ssa");
5549     context->postprocess_frame = gst_matroska_demux_check_subtitle_buffer;
5550     subtitlecontext->check_markup = FALSE;
5551   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_ASS)) {
5552     caps = gst_caps_new_empty_simple ("application/x-ass");
5553     context->postprocess_frame = gst_matroska_demux_check_subtitle_buffer;
5554     subtitlecontext->check_markup = FALSE;
5555   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_USF)) {
5556     caps = gst_caps_new_empty_simple ("application/x-usf");
5557     context->postprocess_frame = gst_matroska_demux_check_subtitle_buffer;
5558     subtitlecontext->check_markup = FALSE;
5559   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_VOBSUB)) {
5560     caps = gst_caps_new_empty_simple ("subpicture/x-dvd");
5561     ((GstMatroskaTrackContext *) subtitlecontext)->send_dvd_event = TRUE;
5562   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_HDMVPGS)) {
5563     caps = gst_caps_new_empty_simple ("subpicture/x-pgs");
5564   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_KATE)) {
5565     caps = gst_caps_new_empty_simple ("subtitle/x-kate");
5566     context->stream_headers =
5567         gst_matroska_parse_xiph_stream_headers (context->codec_priv,
5568         context->codec_priv_size);
5569     /* FIXME: mark stream as broken and skip if there are no stream headers */
5570     context->send_stream_headers = TRUE;
5571   } else {
5572     GST_DEBUG ("Unknown subtitle stream: codec_id='%s'", codec_id);
5573     caps = gst_caps_new_empty_simple ("application/x-subtitle-unknown");
5574   }
5575
5576   if (data != NULL && size > 0) {
5577     GstBuffer *buf;
5578
5579     buf = gst_buffer_new_wrapped (g_memdup (data, size), size);
5580     gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, buf, NULL);
5581     gst_buffer_unref (buf);
5582   }
5583
5584   return caps;
5585 }
5586
5587 #if 0
5588 static void
5589 gst_matroska_demux_set_index (GstElement * element, GstIndex * index)
5590 {
5591   GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (element);
5592
5593   GST_OBJECT_LOCK (demux);
5594   if (demux->common.element_index)
5595     gst_object_unref (demux->common.element_index);
5596   demux->common.element_index = index ? gst_object_ref (index) : NULL;
5597   GST_OBJECT_UNLOCK (demux);
5598   GST_DEBUG_OBJECT (demux, "Set index %" GST_PTR_FORMAT,
5599       demux->common.element_index);
5600 }
5601
5602 static GstIndex *
5603 gst_matroska_demux_get_index (GstElement * element)
5604 {
5605   GstIndex *result = NULL;
5606   GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (element);
5607
5608   GST_OBJECT_LOCK (demux);
5609   if (demux->common.element_index)
5610     result = gst_object_ref (demux->common.element_index);
5611   GST_OBJECT_UNLOCK (demux);
5612
5613   GST_DEBUG_OBJECT (demux, "Returning index %" GST_PTR_FORMAT, result);
5614
5615   return result;
5616 }
5617 #endif
5618
5619 static GstStateChangeReturn
5620 gst_matroska_demux_change_state (GstElement * element,
5621     GstStateChange transition)
5622 {
5623   GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (element);
5624   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
5625
5626   /* handle upwards state changes here */
5627   switch (transition) {
5628     default:
5629       break;
5630   }
5631
5632   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
5633
5634   /* handle downwards state changes */
5635   switch (transition) {
5636     case GST_STATE_CHANGE_PAUSED_TO_READY:
5637       gst_matroska_demux_reset (GST_ELEMENT (demux));
5638       break;
5639     default:
5640       break;
5641   }
5642
5643   return ret;
5644 }
5645
5646 static void
5647 gst_matroska_demux_set_property (GObject * object,
5648     guint prop_id, const GValue * value, GParamSpec * pspec)
5649 {
5650   GstMatroskaDemux *demux;
5651
5652   g_return_if_fail (GST_IS_MATROSKA_DEMUX (object));
5653   demux = GST_MATROSKA_DEMUX (object);
5654
5655   switch (prop_id) {
5656     case ARG_MAX_GAP_TIME:
5657       GST_OBJECT_LOCK (demux);
5658       demux->max_gap_time = g_value_get_uint64 (value);
5659       GST_OBJECT_UNLOCK (demux);
5660       break;
5661     default:
5662       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
5663       break;
5664   }
5665 }
5666
5667 static void
5668 gst_matroska_demux_get_property (GObject * object,
5669     guint prop_id, GValue * value, GParamSpec * pspec)
5670 {
5671   GstMatroskaDemux *demux;
5672
5673   g_return_if_fail (GST_IS_MATROSKA_DEMUX (object));
5674   demux = GST_MATROSKA_DEMUX (object);
5675
5676   switch (prop_id) {
5677     case ARG_MAX_GAP_TIME:
5678       GST_OBJECT_LOCK (demux);
5679       g_value_set_uint64 (value, demux->max_gap_time);
5680       GST_OBJECT_UNLOCK (demux);
5681       break;
5682     default:
5683       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
5684       break;
5685   }
5686 }
5687
5688 gboolean
5689 gst_matroska_demux_plugin_init (GstPlugin * plugin)
5690 {
5691   gst_riff_init ();
5692
5693   /* parser helper separate debug */
5694   GST_DEBUG_CATEGORY_INIT (ebmlread_debug, "ebmlread",
5695       0, "EBML stream helper class");
5696
5697   /* create an elementfactory for the matroska_demux element */
5698   if (!gst_element_register (plugin, "matroskademux",
5699           GST_RANK_PRIMARY, GST_TYPE_MATROSKA_DEMUX))
5700     return FALSE;
5701
5702   return TRUE;
5703 }