matroskademux: use g_memdup2() as g_memdup() is deprecated
[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., 51 Franklin St, Fifth Floor,
22  * Boston, MA 02110-1301, 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  * @title: matroskademux
37  *
38  * matroskademux demuxes a Matroska file into the different contained streams.
39  *
40  * ## Example launch line
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  *
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 #include <gst/base/base.h>
57
58 /* For AVI compatibility mode
59    and for fourcc stuff */
60 #include <gst/riff/riff-read.h>
61 #include <gst/riff/riff-ids.h>
62 #include <gst/riff/riff-media.h>
63
64 #include <gst/audio/audio.h>
65 #include <gst/tag/tag.h>
66 #include <gst/pbutils/pbutils.h>
67 #include <gst/video/gstvideocodecalphameta.h>
68 #include <gst/video/video.h>
69
70 #include "gstmatroskaelements.h"
71 #include "matroska-demux.h"
72 #include "matroska-ids.h"
73
74 GST_DEBUG_CATEGORY_STATIC (matroskademux_debug);
75 #define GST_CAT_DEFAULT matroskademux_debug
76
77 #define DEBUG_ELEMENT_START(demux, ebml, element) \
78     GST_DEBUG_OBJECT (demux, "Parsing " element " element at offset %" \
79         G_GUINT64_FORMAT, gst_ebml_read_get_pos (ebml))
80
81 #define DEBUG_ELEMENT_STOP(demux, ebml, element, ret) \
82     GST_DEBUG_OBJECT (demux, "Parsing " element " element " \
83         " finished with '%s'", gst_flow_get_name (ret))
84
85 enum
86 {
87   PROP_0,
88   PROP_METADATA,
89   PROP_STREAMINFO,
90   PROP_MAX_GAP_TIME,
91   PROP_MAX_BACKTRACK_DISTANCE
92 };
93
94 #define DEFAULT_MAX_GAP_TIME           (2 * GST_SECOND)
95 #define DEFAULT_MAX_BACKTRACK_DISTANCE 30
96 #define INVALID_DATA_THRESHOLD         (2 * 1024 * 1024)
97
98 static GstStaticPadTemplate sink_templ = GST_STATIC_PAD_TEMPLATE ("sink",
99     GST_PAD_SINK,
100     GST_PAD_ALWAYS,
101     GST_STATIC_CAPS ("audio/x-matroska; video/x-matroska; "
102         "video/x-matroska-3d; audio/webm; video/webm")
103     );
104
105 /* TODO: fill in caps! */
106
107 static GstStaticPadTemplate audio_src_templ =
108 GST_STATIC_PAD_TEMPLATE ("audio_%u",
109     GST_PAD_SRC,
110     GST_PAD_SOMETIMES,
111     GST_STATIC_CAPS ("ANY")
112     );
113
114 static GstStaticPadTemplate video_src_templ =
115 GST_STATIC_PAD_TEMPLATE ("video_%u",
116     GST_PAD_SRC,
117     GST_PAD_SOMETIMES,
118     GST_STATIC_CAPS ("ANY")
119     );
120
121 static GstStaticPadTemplate subtitle_src_templ =
122     GST_STATIC_PAD_TEMPLATE ("subtitle_%u",
123     GST_PAD_SRC,
124     GST_PAD_SOMETIMES,
125     GST_STATIC_CAPS ("text/x-raw, format=pango-markup; application/x-ssa; "
126         "application/x-ass;application/x-usf; subpicture/x-dvd; "
127         "subpicture/x-pgs; subtitle/x-kate; " "application/x-subtitle-unknown")
128     );
129
130 static GQuark matroska_block_additional_quark;
131
132 static GstFlowReturn gst_matroska_demux_parse_id (GstMatroskaDemux * demux,
133     guint32 id, guint64 length, guint needed);
134
135 /* element functions */
136 static void gst_matroska_demux_loop (GstPad * pad);
137
138 static gboolean gst_matroska_demux_element_send_event (GstElement * element,
139     GstEvent * event);
140 static gboolean gst_matroska_demux_element_query (GstElement * element,
141     GstQuery * query);
142
143 /* pad functions */
144 static gboolean gst_matroska_demux_sink_activate (GstPad * sinkpad,
145     GstObject * parent);
146 static gboolean gst_matroska_demux_sink_activate_mode (GstPad * sinkpad,
147     GstObject * parent, GstPadMode mode, gboolean active);
148
149 static gboolean gst_matroska_demux_handle_seek_push (GstMatroskaDemux * demux,
150     GstPad * pad, GstEvent * event);
151 static gboolean gst_matroska_demux_handle_seek_event (GstMatroskaDemux * demux,
152     GstPad * pad, GstEvent * event);
153 static gboolean gst_matroska_demux_handle_src_event (GstPad * pad,
154     GstObject * parent, GstEvent * event);
155 static gboolean gst_matroska_demux_handle_src_query (GstPad * pad,
156     GstObject * parent, GstQuery * query);
157
158 static gboolean gst_matroska_demux_handle_sink_event (GstPad * pad,
159     GstObject * parent, GstEvent * event);
160 static gboolean gst_matroska_demux_handle_sink_query (GstPad * pad,
161     GstObject * parent, GstQuery * query);
162 static GstFlowReturn gst_matroska_demux_chain (GstPad * pad,
163     GstObject * object, GstBuffer * buffer);
164
165 static GstStateChangeReturn
166 gst_matroska_demux_change_state (GstElement * element,
167     GstStateChange transition);
168 #if 0
169 static void
170 gst_matroska_demux_set_index (GstElement * element, GstIndex * index);
171 static GstIndex *gst_matroska_demux_get_index (GstElement * element);
172 #endif
173
174 /* caps functions */
175 static GstCaps *gst_matroska_demux_video_caps (GstMatroskaTrackVideoContext
176     * videocontext, const gchar * codec_id, guint8 * data, guint size,
177     gchar ** codec_name, guint32 * riff_fourcc);
178 static GstCaps *gst_matroska_demux_audio_caps (GstMatroskaTrackAudioContext
179     * audiocontext, const gchar * codec_id, guint8 * data, guint size,
180     gchar ** codec_name, guint16 * riff_audio_fmt, GstClockTime * lead_in_ts);
181 static GstCaps
182     * gst_matroska_demux_subtitle_caps (GstMatroskaTrackSubtitleContext *
183     subtitlecontext, const gchar * codec_id, gpointer data, guint size);
184 static const gchar *gst_matroska_track_encryption_algorithm_name (gint val);
185 static const gchar *gst_matroska_track_encryption_cipher_mode_name (gint val);
186 static const gchar *gst_matroska_track_encoding_scope_name (gint val);
187
188 /* stream methods */
189 static void gst_matroska_demux_reset (GstElement * element);
190 static gboolean perform_seek_to_offset (GstMatroskaDemux * demux,
191     gdouble rate, guint64 offset, guint32 seqnum, GstSeekFlags flags);
192
193 /* gobject functions */
194 static void gst_matroska_demux_set_property (GObject * object,
195     guint prop_id, const GValue * value, GParamSpec * pspec);
196 static void gst_matroska_demux_get_property (GObject * object,
197     guint prop_id, GValue * value, GParamSpec * pspec);
198
199 GType gst_matroska_demux_get_type (void);
200 #define parent_class gst_matroska_demux_parent_class
201 G_DEFINE_TYPE (GstMatroskaDemux, gst_matroska_demux, GST_TYPE_ELEMENT);
202 #define _do_init \
203   gst_riff_init (); \
204   matroska_element_init (plugin); \
205   GST_DEBUG_CATEGORY_INIT (ebmlread_debug, "ebmlread", 0, "EBML stream helper class"); \
206   matroska_block_additional_quark = \
207       g_quark_from_static_string ("matroska-block-additional");
208
209 GST_ELEMENT_REGISTER_DEFINE_WITH_CODE (matroskademux, "matroskademux",
210     GST_RANK_PRIMARY, GST_TYPE_MATROSKA_DEMUX, _do_init);
211
212 static void
213 gst_matroska_demux_finalize (GObject * object)
214 {
215   GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (object);
216
217   gst_matroska_read_common_finalize (&demux->common);
218   gst_flow_combiner_free (demux->flowcombiner);
219   G_OBJECT_CLASS (parent_class)->finalize (object);
220 }
221
222 static void
223 gst_matroska_demux_class_init (GstMatroskaDemuxClass * klass)
224 {
225   GObjectClass *gobject_class = (GObjectClass *) klass;
226   GstElementClass *gstelement_class = (GstElementClass *) klass;
227
228   GST_DEBUG_CATEGORY_INIT (matroskademux_debug, "matroskademux", 0,
229       "Matroska demuxer");
230
231   gobject_class->finalize = gst_matroska_demux_finalize;
232
233   gobject_class->get_property = gst_matroska_demux_get_property;
234   gobject_class->set_property = gst_matroska_demux_set_property;
235
236   g_object_class_install_property (gobject_class, PROP_MAX_GAP_TIME,
237       g_param_spec_uint64 ("max-gap-time", "Maximum gap time",
238           "The demuxer sends out segment events for skipping "
239           "gaps longer than this (0 = disabled).", 0, G_MAXUINT64,
240           DEFAULT_MAX_GAP_TIME, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
241
242   g_object_class_install_property (gobject_class, PROP_MAX_BACKTRACK_DISTANCE,
243       g_param_spec_uint ("max-backtrack-distance",
244           "Maximum backtrack distance",
245           "Maximum backtrack distance in seconds when seeking without "
246           "and index in pull mode and search for a keyframe "
247           "(0 = disable backtracking).",
248           0, G_MAXUINT, DEFAULT_MAX_BACKTRACK_DISTANCE,
249           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
250
251   gstelement_class->change_state =
252       GST_DEBUG_FUNCPTR (gst_matroska_demux_change_state);
253   gstelement_class->send_event =
254       GST_DEBUG_FUNCPTR (gst_matroska_demux_element_send_event);
255   gstelement_class->query =
256       GST_DEBUG_FUNCPTR (gst_matroska_demux_element_query);
257 #if 0
258   gstelement_class->set_index =
259       GST_DEBUG_FUNCPTR (gst_matroska_demux_set_index);
260   gstelement_class->get_index =
261       GST_DEBUG_FUNCPTR (gst_matroska_demux_get_index);
262 #endif
263
264   gst_element_class_add_static_pad_template (gstelement_class,
265       &video_src_templ);
266   gst_element_class_add_static_pad_template (gstelement_class,
267       &audio_src_templ);
268   gst_element_class_add_static_pad_template (gstelement_class,
269       &subtitle_src_templ);
270   gst_element_class_add_static_pad_template (gstelement_class, &sink_templ);
271
272   gst_element_class_set_static_metadata (gstelement_class, "Matroska demuxer",
273       "Codec/Demuxer",
274       "Demuxes Matroska/WebM streams into video/audio/subtitles",
275       "GStreamer maintainers <gstreamer-devel@lists.freedesktop.org>");
276 }
277
278 static void
279 gst_matroska_demux_init (GstMatroskaDemux * demux)
280 {
281   demux->common.sinkpad = gst_pad_new_from_static_template (&sink_templ,
282       "sink");
283   gst_pad_set_activate_function (demux->common.sinkpad,
284       GST_DEBUG_FUNCPTR (gst_matroska_demux_sink_activate));
285   gst_pad_set_activatemode_function (demux->common.sinkpad,
286       GST_DEBUG_FUNCPTR (gst_matroska_demux_sink_activate_mode));
287   gst_pad_set_chain_function (demux->common.sinkpad,
288       GST_DEBUG_FUNCPTR (gst_matroska_demux_chain));
289   gst_pad_set_event_function (demux->common.sinkpad,
290       GST_DEBUG_FUNCPTR (gst_matroska_demux_handle_sink_event));
291   gst_pad_set_query_function (demux->common.sinkpad,
292       GST_DEBUG_FUNCPTR (gst_matroska_demux_handle_sink_query));
293   gst_element_add_pad (GST_ELEMENT (demux), demux->common.sinkpad);
294
295   /* init defaults for common read context */
296   gst_matroska_read_common_init (&demux->common);
297
298   /* property defaults */
299   demux->max_gap_time = DEFAULT_MAX_GAP_TIME;
300   demux->max_backtrack_distance = DEFAULT_MAX_BACKTRACK_DISTANCE;
301
302   GST_OBJECT_FLAG_SET (demux, GST_ELEMENT_FLAG_INDEXABLE);
303
304   demux->flowcombiner = gst_flow_combiner_new ();
305
306   /* finish off */
307   gst_matroska_demux_reset (GST_ELEMENT (demux));
308 }
309
310 static void
311 gst_matroska_demux_reset (GstElement * element)
312 {
313   GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (element);
314
315   GST_DEBUG_OBJECT (demux, "Resetting state");
316
317   gst_matroska_read_common_reset (GST_ELEMENT (demux), &demux->common);
318
319   demux->num_a_streams = 0;
320   demux->num_t_streams = 0;
321   demux->num_v_streams = 0;
322   demux->have_nonintraonly_v_streams = FALSE;
323
324   demux->have_group_id = FALSE;
325   demux->group_id = G_MAXUINT;
326
327   demux->clock = NULL;
328   demux->tracks_parsed = FALSE;
329
330   if (demux->clusters) {
331     g_array_free (demux->clusters, TRUE);
332     demux->clusters = NULL;
333   }
334
335   g_list_foreach (demux->seek_parsed,
336       (GFunc) gst_matroska_read_common_free_parsed_el, NULL);
337   g_list_free (demux->seek_parsed);
338   demux->seek_parsed = NULL;
339
340   demux->last_stop_end = GST_CLOCK_TIME_NONE;
341   demux->seek_block = 0;
342   demux->stream_start_time = GST_CLOCK_TIME_NONE;
343   demux->to_time = GST_CLOCK_TIME_NONE;
344   demux->cluster_time = GST_CLOCK_TIME_NONE;
345   demux->cluster_offset = 0;
346   demux->cluster_prevsize = 0;
347   demux->seen_cluster_prevsize = FALSE;
348   demux->next_cluster_offset = 0;
349   demux->stream_last_time = GST_CLOCK_TIME_NONE;
350   demux->last_cluster_offset = 0;
351   demux->index_offset = 0;
352   demux->seekable = FALSE;
353   demux->need_segment = FALSE;
354   demux->segment_seqnum = 0;
355   demux->requested_seek_time = GST_CLOCK_TIME_NONE;
356   demux->seek_offset = -1;
357   demux->audio_lead_in_ts = 0;
358   demux->building_index = FALSE;
359   if (demux->seek_event) {
360     gst_event_unref (demux->seek_event);
361     demux->seek_event = NULL;
362   }
363
364   demux->seek_index = NULL;
365   demux->seek_entry = 0;
366
367   if (demux->new_segment) {
368     gst_event_unref (demux->new_segment);
369     demux->new_segment = NULL;
370   }
371
372   demux->invalid_duration = FALSE;
373
374   demux->cached_length = G_MAXUINT64;
375
376   if (demux->deferred_seek_event)
377     gst_event_unref (demux->deferred_seek_event);
378   demux->deferred_seek_event = NULL;
379   demux->deferred_seek_pad = NULL;
380
381   gst_flow_combiner_clear (demux->flowcombiner);
382 }
383
384 static GstBuffer *
385 gst_matroska_decode_buffer (GstMatroskaTrackContext * context, GstBuffer * buf)
386 {
387   GstMapInfo map;
388   gpointer data;
389   gsize size;
390   GstBuffer *out_buf = buf;
391
392   g_return_val_if_fail (GST_IS_BUFFER (buf), NULL);
393
394   GST_DEBUG ("decoding buffer %p", buf);
395
396   gst_buffer_map (out_buf, &map, GST_MAP_READ);
397   data = map.data;
398   size = map.size;
399
400   g_return_val_if_fail (size > 0, buf);
401
402   if (gst_matroska_decode_data (context->encodings, &data, &size,
403           GST_MATROSKA_TRACK_ENCODING_SCOPE_FRAME, FALSE)) {
404     if (data != map.data) {
405       gst_buffer_unmap (out_buf, &map);
406       gst_buffer_unref (out_buf);
407       out_buf = gst_buffer_new_wrapped (data, size);
408     } else {
409       gst_buffer_unmap (out_buf, &map);
410     }
411   } else {
412     GST_DEBUG ("decode data failed");
413     gst_buffer_unmap (out_buf, &map);
414     gst_buffer_unref (out_buf);
415     return NULL;
416   }
417   /* Encrypted stream */
418   if (context->protection_info) {
419
420     GstStructure *info_protect = gst_structure_copy (context->protection_info);
421     gboolean encrypted = FALSE;
422
423     gst_buffer_map (out_buf, &map, GST_MAP_READ);
424     data = map.data;
425     size = map.size;
426
427     if (gst_matroska_parse_protection_meta (&data, &size, info_protect,
428             &encrypted)) {
429       if (data != map.data) {
430         GstBuffer *tmp_buf;
431
432         gst_buffer_unmap (out_buf, &map);
433         tmp_buf = out_buf;
434         out_buf = gst_buffer_copy_region (tmp_buf, GST_BUFFER_COPY_ALL,
435             gst_buffer_get_size (tmp_buf) - size, size);
436         gst_buffer_unref (tmp_buf);
437         if (encrypted)
438           gst_buffer_add_protection_meta (out_buf, info_protect);
439         else
440           gst_structure_free (info_protect);
441       } else {
442         gst_buffer_unmap (out_buf, &map);
443         gst_structure_free (info_protect);
444       }
445     } else {
446       GST_WARNING ("Adding protection metadata failed");
447       gst_buffer_unmap (out_buf, &map);
448       gst_buffer_unref (out_buf);
449       gst_structure_free (info_protect);
450       return NULL;
451     }
452   }
453
454   return out_buf;
455 }
456
457 static void
458 gst_matroska_demux_add_stream_headers_to_caps (GstMatroskaDemux * demux,
459     GstBufferList * list, GstCaps * caps)
460 {
461   GstStructure *s;
462   GValue arr_val = G_VALUE_INIT;
463   GValue buf_val = G_VALUE_INIT;
464   gint i, num;
465
466   g_assert (gst_caps_is_writable (caps));
467
468   g_value_init (&arr_val, GST_TYPE_ARRAY);
469   g_value_init (&buf_val, GST_TYPE_BUFFER);
470
471   num = gst_buffer_list_length (list);
472   for (i = 0; i < num; ++i) {
473     g_value_set_boxed (&buf_val, gst_buffer_list_get (list, i));
474     gst_value_array_append_value (&arr_val, &buf_val);
475   }
476
477   s = gst_caps_get_structure (caps, 0);
478   gst_structure_take_value (s, "streamheader", &arr_val);
479   g_value_unset (&buf_val);
480 }
481
482 static GstFlowReturn
483 gst_matroska_demux_parse_mastering_metadata (GstMatroskaDemux * demux,
484     GstEbmlRead * ebml, GstMatroskaTrackVideoContext * video_context)
485 {
486   GstFlowReturn ret = GST_FLOW_OK;
487   GstVideoMasteringDisplayInfo minfo;
488   guint32 id;
489   gdouble num;
490   /* Precision defined by HEVC specification */
491   const guint chroma_scale = 50000;
492   const guint luma_scale = 10000;
493
494   gst_video_mastering_display_info_init (&minfo);
495
496   DEBUG_ELEMENT_START (demux, ebml, "MasteringMetadata");
497
498   if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK)
499     goto beach;
500
501   while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
502     if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
503       goto beach;
504
505     /* all sub elements have float type */
506     if ((ret = gst_ebml_read_float (ebml, &id, &num)) != GST_FLOW_OK)
507       goto beach;
508
509     /* chromaticity should be in [0, 1] range */
510     if (id >= GST_MATROSKA_ID_PRIMARYRCHROMATICITYX &&
511         id <= GST_MATROSKA_ID_WHITEPOINTCHROMATICITYY) {
512       if (num < 0 || num > 1.0) {
513         GST_WARNING_OBJECT (demux, "0x%x has invalid value %f", id, num);
514         goto beach;
515       }
516     } else if (id == GST_MATROSKA_ID_LUMINANCEMAX ||
517         id == GST_MATROSKA_ID_LUMINANCEMIN) {
518       /* Note: webM spec said valid range is [0, 999.9999] but
519        * 1000 cd/m^2 is generally used value on HDR. Just check guint range here.
520        * See https://www.webmproject.org/docs/container/#LuminanceMax
521        */
522       if (num < 0 || num > (gdouble) (G_MAXUINT32 / luma_scale)) {
523         GST_WARNING_OBJECT (demux, "0x%x has invalid value %f", id, num);
524         goto beach;
525       }
526     }
527
528     switch (id) {
529       case GST_MATROSKA_ID_PRIMARYRCHROMATICITYX:
530         minfo.display_primaries[0].x = (guint16) (num * chroma_scale);
531         break;
532       case GST_MATROSKA_ID_PRIMARYRCHROMATICITYY:
533         minfo.display_primaries[0].y = (guint16) (num * chroma_scale);
534         break;
535       case GST_MATROSKA_ID_PRIMARYGCHROMATICITYX:
536         minfo.display_primaries[1].x = (guint16) (num * chroma_scale);
537         break;
538       case GST_MATROSKA_ID_PRIMARYGCHROMATICITYY:
539         minfo.display_primaries[1].y = (guint16) (num * chroma_scale);
540         break;
541       case GST_MATROSKA_ID_PRIMARYBCHROMATICITYX:
542         minfo.display_primaries[2].x = (guint16) (num * chroma_scale);
543         break;
544       case GST_MATROSKA_ID_PRIMARYBCHROMATICITYY:
545         minfo.display_primaries[2].y = (guint16) (num * chroma_scale);
546         break;
547       case GST_MATROSKA_ID_WHITEPOINTCHROMATICITYX:
548         minfo.white_point.x = (guint16) (num * chroma_scale);
549         break;
550       case GST_MATROSKA_ID_WHITEPOINTCHROMATICITYY:
551         minfo.white_point.y = (guint16) (num * chroma_scale);
552         break;
553       case GST_MATROSKA_ID_LUMINANCEMAX:
554         minfo.max_display_mastering_luminance = (guint32) (num * luma_scale);
555         break;
556       case GST_MATROSKA_ID_LUMINANCEMIN:
557         minfo.min_display_mastering_luminance = (guint32) (num * luma_scale);
558         break;
559       default:
560         GST_FIXME_OBJECT (demux,
561             "Unsupported subelement 0x%x in MasteringMetadata", id);
562         ret = gst_ebml_read_skip (ebml);
563         break;
564     }
565   }
566
567   video_context->mastering_display_info = minfo;
568   video_context->mastering_display_info_present = TRUE;
569
570 beach:
571   DEBUG_ELEMENT_STOP (demux, ebml, "MasteringMetadata", ret);
572
573   return ret;
574 }
575
576 static GstFlowReturn
577 gst_matroska_demux_parse_colour (GstMatroskaDemux * demux, GstEbmlRead * ebml,
578     GstMatroskaTrackVideoContext * video_context)
579 {
580   GstFlowReturn ret;
581   GstVideoColorimetry colorimetry;
582   guint32 id;
583   guint64 num;
584
585   colorimetry.range = GST_VIDEO_COLOR_RANGE_UNKNOWN;
586   colorimetry.matrix = GST_VIDEO_COLOR_MATRIX_UNKNOWN;
587   colorimetry.transfer = GST_VIDEO_TRANSFER_UNKNOWN;
588   colorimetry.primaries = GST_VIDEO_COLOR_PRIMARIES_UNKNOWN;
589
590   DEBUG_ELEMENT_START (demux, ebml, "TrackVideoColour");
591
592   if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK)
593     goto beach;
594
595   while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
596     if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
597       goto beach;
598
599     switch (id) {
600       case GST_MATROSKA_ID_VIDEOMATRIXCOEFFICIENTS:{
601         if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
602           goto beach;
603
604         colorimetry.matrix = gst_video_color_matrix_from_iso ((guint) num);
605         break;
606       }
607
608       case GST_MATROSKA_ID_VIDEORANGE:{
609         if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
610           goto beach;
611
612         switch (num) {
613           case 0:
614             colorimetry.range = GST_VIDEO_COLOR_RANGE_UNKNOWN;
615             break;
616           case 1:
617             colorimetry.range = GST_VIDEO_COLOR_RANGE_16_235;
618             break;
619           case 2:
620             colorimetry.range = GST_VIDEO_COLOR_RANGE_0_255;
621             break;
622           default:
623             GST_FIXME_OBJECT (demux, "Unsupported color range  %"
624                 G_GUINT64_FORMAT, num);
625             break;
626         }
627         break;
628       }
629
630       case GST_MATROSKA_ID_VIDEOTRANSFERCHARACTERISTICS:{
631         if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
632           goto beach;
633
634         colorimetry.transfer =
635             gst_video_transfer_function_from_iso ((guint) num);
636         break;
637       }
638
639       case GST_MATROSKA_ID_VIDEOPRIMARIES:{
640         if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
641           goto beach;
642
643         colorimetry.primaries =
644             gst_video_color_primaries_from_iso ((guint) num);
645         break;
646       }
647
648       case GST_MATROSKA_ID_MASTERINGMETADATA:{
649         if ((ret =
650                 gst_matroska_demux_parse_mastering_metadata (demux, ebml,
651                     video_context)) != GST_FLOW_OK)
652           goto beach;
653         break;
654       }
655
656       case GST_MATROSKA_ID_MAXCLL:{
657         if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
658           goto beach;
659         if (num > G_MAXUINT16) {
660           GST_WARNING_OBJECT (demux,
661               "Too large maxCLL value %" G_GUINT64_FORMAT, num);
662         } else {
663           video_context->content_light_level.max_content_light_level = num;
664         }
665         break;
666       }
667
668       case GST_MATROSKA_ID_MAXFALL:{
669         if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
670           goto beach;
671         if (num >= G_MAXUINT16) {
672           GST_WARNING_OBJECT (demux,
673               "Too large maxFALL value %" G_GUINT64_FORMAT, num);
674         } else {
675           video_context->content_light_level.max_frame_average_light_level =
676               num;
677         }
678         break;
679       }
680
681       default:
682         GST_FIXME_OBJECT (demux, "Unsupported subelement 0x%x in Colour", id);
683         ret = gst_ebml_read_skip (ebml);
684         break;
685     }
686   }
687
688   memcpy (&video_context->colorimetry, &colorimetry,
689       sizeof (GstVideoColorimetry));
690
691 beach:
692   DEBUG_ELEMENT_STOP (demux, ebml, "TrackVideoColour", ret);
693   return ret;
694 }
695
696 static GstFlowReturn
697 gst_matroska_demux_parse_stream (GstMatroskaDemux * demux, GstEbmlRead * ebml,
698     GstMatroskaTrackContext ** dest_context)
699 {
700   GstMatroskaTrackContext *context;
701   GstCaps *caps = NULL;
702   GstTagList *cached_taglist;
703   GstFlowReturn ret;
704   guint32 id, riff_fourcc = 0;
705   guint16 riff_audio_fmt = 0;
706   gchar *codec = NULL;
707
708   DEBUG_ELEMENT_START (demux, ebml, "TrackEntry");
709
710   *dest_context = NULL;
711
712   /* start with the master */
713   if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
714     DEBUG_ELEMENT_STOP (demux, ebml, "TrackEntry", ret);
715     return ret;
716   }
717
718   /* allocate generic... if we know the type, we'll g_renew()
719    * with the precise type */
720   context = g_new0 (GstMatroskaTrackContext, 1);
721   context->index_writer_id = -1;
722   context->type = 0;            /* no type yet */
723   context->default_duration = 0;
724   context->pos = 0;
725   context->set_discont = TRUE;
726   context->timecodescale = 1.0;
727   context->flags =
728       GST_MATROSKA_TRACK_ENABLED | GST_MATROSKA_TRACK_DEFAULT |
729       GST_MATROSKA_TRACK_LACING;
730   context->from_time = GST_CLOCK_TIME_NONE;
731   context->from_offset = -1;
732   context->to_offset = G_MAXINT64;
733   context->alignment = 1;
734   context->dts_only = FALSE;
735   context->intra_only = FALSE;
736   context->tags = gst_tag_list_new_empty ();
737   g_queue_init (&context->protection_event_queue);
738   context->protection_info = NULL;
739
740   GST_DEBUG_OBJECT (demux, "Parsing a TrackEntry (%d tracks parsed so far)",
741       demux->common.num_streams);
742
743   /* try reading the trackentry headers */
744   while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
745     if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
746       break;
747
748     switch (id) {
749         /* track number (unique stream ID) */
750       case GST_MATROSKA_ID_TRACKNUMBER:{
751         guint64 num;
752
753         if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
754           break;
755
756         if (num == 0) {
757           GST_ERROR_OBJECT (demux, "Invalid TrackNumber 0");
758           ret = GST_FLOW_ERROR;
759           break;
760         }
761
762         GST_DEBUG_OBJECT (demux, "TrackNumber: %" G_GUINT64_FORMAT, num);
763         context->num = num;
764         break;
765       }
766         /* track UID (unique identifier) */
767       case GST_MATROSKA_ID_TRACKUID:{
768         guint64 num;
769
770         if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
771           break;
772
773         if (num == 0) {
774           GST_ERROR_OBJECT (demux, "Invalid TrackUID 0");
775           ret = GST_FLOW_ERROR;
776           break;
777         }
778
779         GST_DEBUG_OBJECT (demux, "TrackUID: %" G_GUINT64_FORMAT, num);
780         context->uid = num;
781         break;
782       }
783
784         /* track type (video, audio, combined, subtitle, etc.) */
785       case GST_MATROSKA_ID_TRACKTYPE:{
786         guint64 track_type;
787
788         if ((ret = gst_ebml_read_uint (ebml, &id, &track_type)) != GST_FLOW_OK) {
789           break;
790         }
791
792         if (context->type != 0 && context->type != track_type) {
793           GST_WARNING_OBJECT (demux,
794               "More than one tracktype defined in a TrackEntry - skipping");
795           break;
796         } else if (track_type < 1 || track_type > 254) {
797           GST_WARNING_OBJECT (demux, "Invalid TrackType %" G_GUINT64_FORMAT,
798               track_type);
799           break;
800         }
801
802         GST_DEBUG_OBJECT (demux, "TrackType: %" G_GUINT64_FORMAT, track_type);
803
804         /* ok, so we're actually going to reallocate this thing */
805         switch (track_type) {
806           case GST_MATROSKA_TRACK_TYPE_VIDEO:
807             gst_matroska_track_init_video_context (&context);
808             break;
809           case GST_MATROSKA_TRACK_TYPE_AUDIO:
810             gst_matroska_track_init_audio_context (&context);
811             break;
812           case GST_MATROSKA_TRACK_TYPE_SUBTITLE:
813             gst_matroska_track_init_subtitle_context (&context);
814             break;
815           case GST_MATROSKA_TRACK_TYPE_COMPLEX:
816           case GST_MATROSKA_TRACK_TYPE_LOGO:
817           case GST_MATROSKA_TRACK_TYPE_BUTTONS:
818           case GST_MATROSKA_TRACK_TYPE_CONTROL:
819           default:
820             GST_WARNING_OBJECT (demux,
821                 "Unknown or unsupported TrackType %" G_GUINT64_FORMAT,
822                 track_type);
823             context->type = 0;
824             break;
825         }
826         break;
827       }
828
829         /* tracktype specific stuff for video */
830       case GST_MATROSKA_ID_TRACKVIDEO:{
831         GstMatroskaTrackVideoContext *videocontext;
832
833         DEBUG_ELEMENT_START (demux, ebml, "TrackVideo");
834
835         if (!gst_matroska_track_init_video_context (&context)) {
836           GST_WARNING_OBJECT (demux,
837               "TrackVideo element in non-video track - ignoring track");
838           ret = GST_FLOW_ERROR;
839           break;
840         } else if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
841           break;
842         }
843         videocontext = (GstMatroskaTrackVideoContext *) context;
844
845         while (ret == GST_FLOW_OK &&
846             gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
847           if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
848             break;
849
850           switch (id) {
851               /* Should be one level up but some broken muxers write it here. */
852             case GST_MATROSKA_ID_TRACKDEFAULTDURATION:{
853               guint64 num;
854
855               if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
856                 break;
857
858               if (num == 0) {
859                 GST_WARNING_OBJECT (demux, "Invalid TrackDefaultDuration 0");
860                 break;
861               }
862
863               GST_DEBUG_OBJECT (demux,
864                   "TrackDefaultDuration: %" G_GUINT64_FORMAT, num);
865               context->default_duration = num;
866               break;
867             }
868
869               /* video framerate */
870               /* NOTE: This one is here only for backward compatibility.
871                * Use _TRACKDEFAULDURATION one level up. */
872             case GST_MATROSKA_ID_VIDEOFRAMERATE:{
873               gdouble num;
874
875               if ((ret = gst_ebml_read_float (ebml, &id, &num)) != GST_FLOW_OK)
876                 break;
877
878               if (num <= 0.0) {
879                 GST_WARNING_OBJECT (demux, "Invalid TrackVideoFPS %lf", num);
880                 break;
881               }
882
883               GST_DEBUG_OBJECT (demux, "TrackVideoFrameRate: %lf", num);
884               if (context->default_duration == 0)
885                 context->default_duration =
886                     gst_gdouble_to_guint64 ((gdouble) GST_SECOND * (1.0 / num));
887               videocontext->default_fps = num;
888               break;
889             }
890
891               /* width of the size to display the video at */
892             case GST_MATROSKA_ID_VIDEODISPLAYWIDTH:{
893               guint64 num;
894
895               if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
896                 break;
897
898               if (num == 0) {
899                 GST_WARNING_OBJECT (demux, "Invalid TrackVideoDisplayWidth 0");
900                 break;
901               }
902
903               GST_DEBUG_OBJECT (demux,
904                   "TrackVideoDisplayWidth: %" G_GUINT64_FORMAT, num);
905               videocontext->display_width = num;
906               break;
907             }
908
909               /* height of the size to display the video at */
910             case GST_MATROSKA_ID_VIDEODISPLAYHEIGHT:{
911               guint64 num;
912
913               if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
914                 break;
915
916               if (num == 0) {
917                 GST_WARNING_OBJECT (demux, "Invalid TrackVideoDisplayHeight 0");
918                 break;
919               }
920
921               GST_DEBUG_OBJECT (demux,
922                   "TrackVideoDisplayHeight: %" G_GUINT64_FORMAT, num);
923               videocontext->display_height = num;
924               break;
925             }
926
927               /* width of the video in the file */
928             case GST_MATROSKA_ID_VIDEOPIXELWIDTH:{
929               guint64 num;
930
931               if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
932                 break;
933
934               if (num == 0) {
935                 GST_WARNING_OBJECT (demux, "Invalid TrackVideoPixelWidth 0");
936                 break;
937               }
938
939               GST_DEBUG_OBJECT (demux,
940                   "TrackVideoPixelWidth: %" G_GUINT64_FORMAT, num);
941               videocontext->pixel_width = num;
942               break;
943             }
944
945               /* height of the video in the file */
946             case GST_MATROSKA_ID_VIDEOPIXELHEIGHT:{
947               guint64 num;
948
949               if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
950                 break;
951
952               if (num == 0) {
953                 GST_WARNING_OBJECT (demux, "Invalid TrackVideoPixelHeight 0");
954                 break;
955               }
956
957               GST_DEBUG_OBJECT (demux,
958                   "TrackVideoPixelHeight: %" G_GUINT64_FORMAT, num);
959               videocontext->pixel_height = num;
960               break;
961             }
962
963               /* whether the video is interlaced */
964             case GST_MATROSKA_ID_VIDEOFLAGINTERLACED:{
965               guint64 num;
966
967               if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
968                 break;
969
970               if (num == 1)
971                 videocontext->interlace_mode =
972                     GST_MATROSKA_INTERLACE_MODE_INTERLACED;
973               else if (num == 2)
974                 videocontext->interlace_mode =
975                     GST_MATROSKA_INTERLACE_MODE_PROGRESSIVE;
976               else
977                 videocontext->interlace_mode =
978                     GST_MATROSKA_INTERLACE_MODE_UNKNOWN;
979
980               GST_DEBUG_OBJECT (demux, "video track interlacing mode: %d",
981                   videocontext->interlace_mode);
982               break;
983             }
984
985               /* interlaced field order */
986             case GST_MATROSKA_ID_VIDEOFIELDORDER:{
987               guint64 num;
988
989               if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
990                 break;
991
992               if (videocontext->interlace_mode !=
993                   GST_MATROSKA_INTERLACE_MODE_INTERLACED) {
994                 GST_WARNING_OBJECT (demux,
995                     "FieldOrder element when not interlaced - ignoring");
996                 break;
997               }
998
999               if (num == 0)
1000                 /* turns out we're actually progressive */
1001                 videocontext->interlace_mode =
1002                     GST_MATROSKA_INTERLACE_MODE_PROGRESSIVE;
1003               else if (num == 2)
1004                 videocontext->field_order = GST_VIDEO_FIELD_ORDER_UNKNOWN;
1005               else if (num == 9)
1006                 videocontext->field_order =
1007                     GST_VIDEO_FIELD_ORDER_TOP_FIELD_FIRST;
1008               else if (num == 14)
1009                 videocontext->field_order =
1010                     GST_VIDEO_FIELD_ORDER_BOTTOM_FIELD_FIRST;
1011               else {
1012                 GST_FIXME_OBJECT (demux,
1013                     "Unknown or unsupported FieldOrder %" G_GUINT64_FORMAT,
1014                     num);
1015                 videocontext->field_order = GST_VIDEO_FIELD_ORDER_UNKNOWN;
1016               }
1017
1018               GST_DEBUG_OBJECT (demux, "video track field order: %d",
1019                   videocontext->field_order);
1020               break;
1021             }
1022
1023               /* aspect ratio behaviour */
1024             case GST_MATROSKA_ID_VIDEOASPECTRATIOTYPE:{
1025               guint64 num;
1026
1027               if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1028                 break;
1029
1030               if (num != GST_MATROSKA_ASPECT_RATIO_MODE_FREE &&
1031                   num != GST_MATROSKA_ASPECT_RATIO_MODE_KEEP &&
1032                   num != GST_MATROSKA_ASPECT_RATIO_MODE_FIXED) {
1033                 GST_WARNING_OBJECT (demux,
1034                     "Unknown TrackVideoAspectRatioType 0x%x", (guint) num);
1035                 break;
1036               }
1037               GST_DEBUG_OBJECT (demux,
1038                   "TrackVideoAspectRatioType: %" G_GUINT64_FORMAT, num);
1039               videocontext->asr_mode = num;
1040               break;
1041             }
1042
1043               /* colourspace (only matters for raw video) fourcc */
1044             case GST_MATROSKA_ID_VIDEOCOLOURSPACE:{
1045               guint8 *data;
1046               guint64 datalen;
1047
1048               if ((ret =
1049                       gst_ebml_read_binary (ebml, &id, &data,
1050                           &datalen)) != GST_FLOW_OK)
1051                 break;
1052
1053               if (datalen != 4) {
1054                 g_free (data);
1055                 GST_WARNING_OBJECT (demux,
1056                     "Invalid TrackVideoColourSpace length %" G_GUINT64_FORMAT,
1057                     datalen);
1058                 break;
1059               }
1060
1061               memcpy (&videocontext->fourcc, data, 4);
1062               GST_DEBUG_OBJECT (demux,
1063                   "TrackVideoColourSpace: %" GST_FOURCC_FORMAT,
1064                   GST_FOURCC_ARGS (videocontext->fourcc));
1065               g_free (data);
1066               break;
1067             }
1068
1069               /* color info */
1070             case GST_MATROSKA_ID_VIDEOCOLOUR:{
1071               ret = gst_matroska_demux_parse_colour (demux, ebml, videocontext);
1072               break;
1073             }
1074
1075             case GST_MATROSKA_ID_VIDEOSTEREOMODE:
1076             {
1077               guint64 num;
1078
1079               if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1080                 break;
1081
1082               GST_DEBUG_OBJECT (demux, "StereoMode: %" G_GUINT64_FORMAT, num);
1083
1084               switch (num) {
1085                 case GST_MATROSKA_STEREO_MODE_SBS_RL:
1086                   videocontext->multiview_flags =
1087                       GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST;
1088                   /* fall through */
1089                 case GST_MATROSKA_STEREO_MODE_SBS_LR:
1090                   videocontext->multiview_mode =
1091                       GST_VIDEO_MULTIVIEW_MODE_SIDE_BY_SIDE;
1092                   break;
1093                 case GST_MATROSKA_STEREO_MODE_TB_RL:
1094                   videocontext->multiview_flags =
1095                       GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST;
1096                   /* fall through */
1097                 case GST_MATROSKA_STEREO_MODE_TB_LR:
1098                   videocontext->multiview_mode =
1099                       GST_VIDEO_MULTIVIEW_MODE_TOP_BOTTOM;
1100                   break;
1101                 case GST_MATROSKA_STEREO_MODE_CHECKER_RL:
1102                   videocontext->multiview_flags =
1103                       GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST;
1104                   /* fall through */
1105                 case GST_MATROSKA_STEREO_MODE_CHECKER_LR:
1106                   videocontext->multiview_mode =
1107                       GST_VIDEO_MULTIVIEW_MODE_CHECKERBOARD;
1108                   break;
1109                 case GST_MATROSKA_STEREO_MODE_FBF_RL:
1110                   videocontext->multiview_flags =
1111                       GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST;
1112                   /* fall through */
1113                 case GST_MATROSKA_STEREO_MODE_FBF_LR:
1114                   videocontext->multiview_mode =
1115                       GST_VIDEO_MULTIVIEW_MODE_FRAME_BY_FRAME;
1116                   /* FIXME: In frame-by-frame mode, left/right frame buffers are
1117                    * laced within one block, and we'll need to apply FIRST_IN_BUNDLE
1118                    * accordingly. See http://www.matroska.org/technical/specs/index.html#StereoMode */
1119                   GST_FIXME_OBJECT (demux,
1120                       "Frame-by-frame stereoscopic mode not fully implemented");
1121                   break;
1122               }
1123               break;
1124             }
1125
1126             case GST_MATROSKA_ID_VIDEOALPHAMODE:
1127             {
1128               guint64 num;
1129
1130               if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1131                 break;
1132
1133               GST_DEBUG_OBJECT (demux, "AlphaMode: %" G_GUINT64_FORMAT, num);
1134
1135               if (num == 1)
1136                 videocontext->alpha_mode = TRUE;
1137               else
1138                 videocontext->alpha_mode = FALSE;
1139               break;
1140             }
1141
1142             default:
1143               GST_WARNING_OBJECT (demux,
1144                   "Unknown TrackVideo subelement 0x%x - ignoring", id);
1145               /* fall through */
1146             case GST_MATROSKA_ID_VIDEODISPLAYUNIT:
1147             case GST_MATROSKA_ID_VIDEOPIXELCROPBOTTOM:
1148             case GST_MATROSKA_ID_VIDEOPIXELCROPTOP:
1149             case GST_MATROSKA_ID_VIDEOPIXELCROPLEFT:
1150             case GST_MATROSKA_ID_VIDEOPIXELCROPRIGHT:
1151             case GST_MATROSKA_ID_VIDEOGAMMAVALUE:
1152               ret = gst_ebml_read_skip (ebml);
1153               break;
1154           }
1155         }
1156
1157         DEBUG_ELEMENT_STOP (demux, ebml, "TrackVideo", ret);
1158         break;
1159       }
1160
1161         /* tracktype specific stuff for audio */
1162       case GST_MATROSKA_ID_TRACKAUDIO:{
1163         GstMatroskaTrackAudioContext *audiocontext;
1164
1165         DEBUG_ELEMENT_START (demux, ebml, "TrackAudio");
1166
1167         if (!gst_matroska_track_init_audio_context (&context)) {
1168           GST_WARNING_OBJECT (demux,
1169               "TrackAudio element in non-audio track - ignoring track");
1170           ret = GST_FLOW_ERROR;
1171           break;
1172         }
1173
1174         if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK)
1175           break;
1176
1177         audiocontext = (GstMatroskaTrackAudioContext *) context;
1178
1179         while (ret == GST_FLOW_OK &&
1180             gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
1181           if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
1182             break;
1183
1184           switch (id) {
1185               /* samplerate */
1186             case GST_MATROSKA_ID_AUDIOSAMPLINGFREQ:{
1187               gdouble num;
1188
1189               if ((ret = gst_ebml_read_float (ebml, &id, &num)) != GST_FLOW_OK)
1190                 break;
1191
1192
1193               if (num <= 0.0) {
1194                 GST_WARNING_OBJECT (demux,
1195                     "Invalid TrackAudioSamplingFrequency %lf", num);
1196                 break;
1197               }
1198
1199               GST_DEBUG_OBJECT (demux, "TrackAudioSamplingFrequency: %lf", num);
1200               audiocontext->samplerate = num;
1201               break;
1202             }
1203
1204               /* bitdepth */
1205             case GST_MATROSKA_ID_AUDIOBITDEPTH:{
1206               guint64 num;
1207
1208               if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1209                 break;
1210
1211               if (num == 0) {
1212                 GST_WARNING_OBJECT (demux, "Invalid TrackAudioBitDepth 0");
1213                 break;
1214               }
1215
1216               GST_DEBUG_OBJECT (demux, "TrackAudioBitDepth: %" G_GUINT64_FORMAT,
1217                   num);
1218               audiocontext->bitdepth = num;
1219               break;
1220             }
1221
1222               /* channels */
1223             case GST_MATROSKA_ID_AUDIOCHANNELS:{
1224               guint64 num;
1225
1226               if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1227                 break;
1228
1229               if (num == 0) {
1230                 GST_WARNING_OBJECT (demux, "Invalid TrackAudioChannels 0");
1231                 break;
1232               }
1233
1234               GST_DEBUG_OBJECT (demux, "TrackAudioChannels: %" G_GUINT64_FORMAT,
1235                   num);
1236               audiocontext->channels = num;
1237               break;
1238             }
1239
1240             default:
1241               GST_WARNING_OBJECT (demux,
1242                   "Unknown TrackAudio subelement 0x%x - ignoring", id);
1243               /* fall through */
1244             case GST_MATROSKA_ID_AUDIOCHANNELPOSITIONS:
1245             case GST_MATROSKA_ID_AUDIOOUTPUTSAMPLINGFREQ:
1246               ret = gst_ebml_read_skip (ebml);
1247               break;
1248           }
1249         }
1250
1251         DEBUG_ELEMENT_STOP (demux, ebml, "TrackAudio", ret);
1252
1253         break;
1254       }
1255
1256         /* codec identifier */
1257       case GST_MATROSKA_ID_CODECID:{
1258         gchar *text;
1259
1260         if ((ret = gst_ebml_read_ascii (ebml, &id, &text)) != GST_FLOW_OK)
1261           break;
1262
1263         GST_DEBUG_OBJECT (demux, "CodecID: %s", GST_STR_NULL (text));
1264         context->codec_id = text;
1265         break;
1266       }
1267
1268         /* codec private data */
1269       case GST_MATROSKA_ID_CODECPRIVATE:{
1270         guint8 *data;
1271         guint64 size;
1272
1273         if ((ret =
1274                 gst_ebml_read_binary (ebml, &id, &data, &size)) != GST_FLOW_OK)
1275           break;
1276
1277         context->codec_priv = data;
1278         context->codec_priv_size = size;
1279
1280         GST_DEBUG_OBJECT (demux, "CodecPrivate of size %" G_GUINT64_FORMAT,
1281             size);
1282         break;
1283       }
1284
1285         /* name of the codec */
1286       case GST_MATROSKA_ID_CODECNAME:{
1287         gchar *text;
1288
1289         if ((ret = gst_ebml_read_utf8 (ebml, &id, &text)) != GST_FLOW_OK)
1290           break;
1291
1292         GST_DEBUG_OBJECT (demux, "CodecName: %s", GST_STR_NULL (text));
1293         context->codec_name = text;
1294         break;
1295       }
1296
1297         /* codec delay */
1298       case GST_MATROSKA_ID_CODECDELAY:{
1299         guint64 num;
1300
1301         if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1302           break;
1303
1304         context->codec_delay = num;
1305
1306         GST_DEBUG_OBJECT (demux, "CodecDelay: %" GST_TIME_FORMAT,
1307             GST_TIME_ARGS (num));
1308         break;
1309       }
1310
1311         /* codec delay */
1312       case GST_MATROSKA_ID_SEEKPREROLL:{
1313         guint64 num;
1314
1315         if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1316           break;
1317
1318         context->seek_preroll = num;
1319
1320         GST_DEBUG_OBJECT (demux, "SeekPreroll: %" GST_TIME_FORMAT,
1321             GST_TIME_ARGS (num));
1322         break;
1323       }
1324
1325         /* name of this track */
1326       case GST_MATROSKA_ID_TRACKNAME:{
1327         gchar *text;
1328
1329         if ((ret = gst_ebml_read_utf8 (ebml, &id, &text)) != GST_FLOW_OK)
1330           break;
1331
1332         context->name = text;
1333         GST_DEBUG_OBJECT (demux, "TrackName: %s", GST_STR_NULL (text));
1334         break;
1335       }
1336
1337         /* language (matters for audio/subtitles, mostly) */
1338       case GST_MATROSKA_ID_TRACKLANGUAGE:{
1339         gchar *text;
1340
1341         if ((ret = gst_ebml_read_utf8 (ebml, &id, &text)) != GST_FLOW_OK)
1342           break;
1343
1344
1345         context->language = text;
1346
1347         /* fre-ca => fre */
1348         if (strlen (context->language) >= 4 && context->language[3] == '-')
1349           context->language[3] = '\0';
1350
1351         GST_DEBUG_OBJECT (demux, "TrackLanguage: %s",
1352             GST_STR_NULL (context->language));
1353         break;
1354       }
1355
1356         /* whether this is actually used */
1357       case GST_MATROSKA_ID_TRACKFLAGENABLED:{
1358         guint64 num;
1359
1360         if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1361           break;
1362
1363         if (num)
1364           context->flags |= GST_MATROSKA_TRACK_ENABLED;
1365         else
1366           context->flags &= ~GST_MATROSKA_TRACK_ENABLED;
1367
1368         GST_DEBUG_OBJECT (demux, "TrackEnabled: %d",
1369             (context->flags & GST_MATROSKA_TRACK_ENABLED) ? 1 : 0);
1370         break;
1371       }
1372
1373         /* whether it's the default for this track type */
1374       case GST_MATROSKA_ID_TRACKFLAGDEFAULT:{
1375         guint64 num;
1376
1377         if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1378           break;
1379
1380         if (num)
1381           context->flags |= GST_MATROSKA_TRACK_DEFAULT;
1382         else
1383           context->flags &= ~GST_MATROSKA_TRACK_DEFAULT;
1384
1385         GST_DEBUG_OBJECT (demux, "TrackDefault: %d",
1386             (context->flags & GST_MATROSKA_TRACK_DEFAULT) ? 1 : 0);
1387         break;
1388       }
1389
1390         /* whether the track must be used during playback */
1391       case GST_MATROSKA_ID_TRACKFLAGFORCED:{
1392         guint64 num;
1393
1394         if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1395           break;
1396
1397         if (num)
1398           context->flags |= GST_MATROSKA_TRACK_FORCED;
1399         else
1400           context->flags &= ~GST_MATROSKA_TRACK_FORCED;
1401
1402         GST_DEBUG_OBJECT (demux, "TrackForced: %d",
1403             (context->flags & GST_MATROSKA_TRACK_FORCED) ? 1 : 0);
1404         break;
1405       }
1406
1407         /* lacing (like MPEG, where blocks don't end/start on frame
1408          * boundaries) */
1409       case GST_MATROSKA_ID_TRACKFLAGLACING:{
1410         guint64 num;
1411
1412         if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1413           break;
1414
1415         if (num)
1416           context->flags |= GST_MATROSKA_TRACK_LACING;
1417         else
1418           context->flags &= ~GST_MATROSKA_TRACK_LACING;
1419
1420         GST_DEBUG_OBJECT (demux, "TrackLacing: %d",
1421             (context->flags & GST_MATROSKA_TRACK_LACING) ? 1 : 0);
1422         break;
1423       }
1424
1425         /* default length (in time) of one data block in this track */
1426       case GST_MATROSKA_ID_TRACKDEFAULTDURATION:{
1427         guint64 num;
1428
1429         if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1430           break;
1431
1432
1433         if (num == 0) {
1434           GST_WARNING_OBJECT (demux, "Invalid TrackDefaultDuration 0");
1435           break;
1436         }
1437
1438         GST_DEBUG_OBJECT (demux, "TrackDefaultDuration: %" G_GUINT64_FORMAT,
1439             num);
1440         context->default_duration = num;
1441         break;
1442       }
1443
1444       case GST_MATROSKA_ID_CONTENTENCODINGS:{
1445         ret = gst_matroska_read_common_read_track_encodings (&demux->common,
1446             ebml, context);
1447         break;
1448       }
1449
1450       case GST_MATROSKA_ID_TRACKTIMECODESCALE:{
1451         gdouble num;
1452
1453         if ((ret = gst_ebml_read_float (ebml, &id, &num)) != GST_FLOW_OK)
1454           break;
1455
1456         if (num <= 0.0) {
1457           GST_WARNING_OBJECT (demux, "Invalid TrackTimeCodeScale %lf", num);
1458           break;
1459         }
1460
1461         GST_DEBUG_OBJECT (demux, "TrackTimeCodeScale: %lf", num);
1462         context->timecodescale = num;
1463         break;
1464       }
1465
1466       default:
1467         GST_WARNING ("Unknown TrackEntry subelement 0x%x - ignoring", id);
1468         /* pass-through */
1469
1470         /* we ignore these because they're nothing useful (i.e. crap)
1471          * or simply not implemented yet. */
1472       case GST_MATROSKA_ID_TRACKMINCACHE:
1473       case GST_MATROSKA_ID_TRACKMAXCACHE:
1474       case GST_MATROSKA_ID_MAXBLOCKADDITIONID:
1475       case GST_MATROSKA_ID_TRACKATTACHMENTLINK:
1476       case GST_MATROSKA_ID_TRACKOVERLAY:
1477       case GST_MATROSKA_ID_TRACKTRANSLATE:
1478       case GST_MATROSKA_ID_TRACKOFFSET:
1479       case GST_MATROSKA_ID_CODECSETTINGS:
1480       case GST_MATROSKA_ID_CODECINFOURL:
1481       case GST_MATROSKA_ID_CODECDOWNLOADURL:
1482       case GST_MATROSKA_ID_CODECDECODEALL:
1483         ret = gst_ebml_read_skip (ebml);
1484         break;
1485     }
1486   }
1487
1488   DEBUG_ELEMENT_STOP (demux, ebml, "TrackEntry", ret);
1489
1490   /* Decode codec private data if necessary */
1491   if (context->encodings && context->encodings->len > 0 && context->codec_priv
1492       && context->codec_priv_size > 0) {
1493     if (!gst_matroska_decode_data (context->encodings,
1494             &context->codec_priv, &context->codec_priv_size,
1495             GST_MATROSKA_TRACK_ENCODING_SCOPE_CODEC_DATA, TRUE)) {
1496       GST_WARNING_OBJECT (demux, "Decoding codec private data failed");
1497       ret = GST_FLOW_ERROR;
1498     }
1499   }
1500
1501   if (context->type == 0 || context->codec_id == NULL || (ret != GST_FLOW_OK
1502           && ret != GST_FLOW_EOS)) {
1503     if (ret == GST_FLOW_OK || ret == GST_FLOW_EOS)
1504       GST_WARNING_OBJECT (ebml, "Unknown stream/codec in track entry header");
1505
1506     gst_matroska_track_free (context);
1507     context = NULL;
1508     *dest_context = NULL;
1509     return ret;
1510   }
1511
1512   /* check for a cached track taglist  */
1513   cached_taglist =
1514       (GstTagList *) g_hash_table_lookup (demux->common.cached_track_taglists,
1515       GUINT_TO_POINTER (context->uid));
1516   if (cached_taglist)
1517     gst_tag_list_insert (context->tags, cached_taglist, GST_TAG_MERGE_APPEND);
1518
1519   /* compute caps */
1520   switch (context->type) {
1521     case GST_MATROSKA_TRACK_TYPE_VIDEO:{
1522       GstMatroskaTrackVideoContext *videocontext =
1523           (GstMatroskaTrackVideoContext *) context;
1524
1525       caps = gst_matroska_demux_video_caps (videocontext,
1526           context->codec_id, context->codec_priv,
1527           context->codec_priv_size, &codec, &riff_fourcc);
1528
1529       if (codec) {
1530         gst_tag_list_add (context->tags, GST_TAG_MERGE_REPLACE,
1531             GST_TAG_VIDEO_CODEC, codec, NULL);
1532         context->tags_changed = TRUE;
1533         g_free (codec);
1534       }
1535       break;
1536     }
1537
1538     case GST_MATROSKA_TRACK_TYPE_AUDIO:{
1539       GstClockTime lead_in_ts = 0;
1540       GstMatroskaTrackAudioContext *audiocontext =
1541           (GstMatroskaTrackAudioContext *) context;
1542
1543       caps = gst_matroska_demux_audio_caps (audiocontext,
1544           context->codec_id, context->codec_priv, context->codec_priv_size,
1545           &codec, &riff_audio_fmt, &lead_in_ts);
1546       if (lead_in_ts > demux->audio_lead_in_ts) {
1547         demux->audio_lead_in_ts = lead_in_ts;
1548         GST_DEBUG_OBJECT (demux, "Increased audio lead-in to %" GST_TIME_FORMAT,
1549             GST_TIME_ARGS (lead_in_ts));
1550       }
1551
1552       if (codec) {
1553         gst_tag_list_add (context->tags, GST_TAG_MERGE_REPLACE,
1554             GST_TAG_AUDIO_CODEC, codec, NULL);
1555         context->tags_changed = TRUE;
1556         g_free (codec);
1557       }
1558       break;
1559     }
1560
1561     case GST_MATROSKA_TRACK_TYPE_SUBTITLE:{
1562       GstMatroskaTrackSubtitleContext *subtitlecontext =
1563           (GstMatroskaTrackSubtitleContext *) context;
1564
1565       caps = gst_matroska_demux_subtitle_caps (subtitlecontext,
1566           context->codec_id, context->codec_priv, context->codec_priv_size);
1567       break;
1568     }
1569
1570     case GST_MATROSKA_TRACK_TYPE_COMPLEX:
1571     case GST_MATROSKA_TRACK_TYPE_LOGO:
1572     case GST_MATROSKA_TRACK_TYPE_BUTTONS:
1573     case GST_MATROSKA_TRACK_TYPE_CONTROL:
1574     default:
1575       /* we should already have quit by now */
1576       g_assert_not_reached ();
1577   }
1578
1579   if ((context->language == NULL || *context->language == '\0') &&
1580       (context->type == GST_MATROSKA_TRACK_TYPE_AUDIO ||
1581           context->type == GST_MATROSKA_TRACK_TYPE_SUBTITLE)) {
1582     GST_LOG ("stream %d: language=eng (assuming default)", context->index);
1583     context->language = g_strdup ("eng");
1584   }
1585
1586   if (context->language) {
1587     const gchar *lang;
1588
1589     /* Matroska contains ISO 639-2B codes, we want ISO 639-1 */
1590     lang = gst_tag_get_language_code (context->language);
1591     gst_tag_list_add (context->tags, GST_TAG_MERGE_REPLACE,
1592         GST_TAG_LANGUAGE_CODE, (lang) ? lang : context->language, NULL);
1593
1594     if (context->name) {
1595       gst_tag_list_add (context->tags, GST_TAG_MERGE_REPLACE,
1596           GST_TAG_TITLE, context->name, NULL);
1597     }
1598     context->tags_changed = TRUE;
1599   }
1600
1601   if (caps == NULL) {
1602     GST_WARNING_OBJECT (demux, "could not determine caps for stream with "
1603         "codec_id='%s'", context->codec_id);
1604     switch (context->type) {
1605       case GST_MATROSKA_TRACK_TYPE_VIDEO:
1606         caps = gst_caps_new_empty_simple ("video/x-unknown");
1607         break;
1608       case GST_MATROSKA_TRACK_TYPE_AUDIO:
1609         caps = gst_caps_new_empty_simple ("audio/x-unknown");
1610         break;
1611       case GST_MATROSKA_TRACK_TYPE_SUBTITLE:
1612         caps = gst_caps_new_empty_simple ("application/x-subtitle-unknown");
1613         break;
1614       case GST_MATROSKA_TRACK_TYPE_COMPLEX:
1615       default:
1616         caps = gst_caps_new_empty_simple ("application/x-matroska-unknown");
1617         break;
1618     }
1619     gst_caps_set_simple (caps, "codec-id", G_TYPE_STRING, context->codec_id,
1620         NULL);
1621
1622     /* add any unrecognised riff fourcc / audio format, but after codec-id */
1623     if (context->type == GST_MATROSKA_TRACK_TYPE_AUDIO && riff_audio_fmt != 0)
1624       gst_caps_set_simple (caps, "format", G_TYPE_INT, riff_audio_fmt, NULL);
1625     else if (context->type == GST_MATROSKA_TRACK_TYPE_VIDEO && riff_fourcc != 0) {
1626       gchar *fstr = g_strdup_printf ("%" GST_FOURCC_FORMAT,
1627           GST_FOURCC_ARGS (riff_fourcc));
1628       gst_caps_set_simple (caps, "fourcc", G_TYPE_STRING, fstr, NULL);
1629       g_free (fstr);
1630     }
1631   } else if (context->stream_headers != NULL) {
1632     gst_matroska_demux_add_stream_headers_to_caps (demux,
1633         context->stream_headers, caps);
1634   }
1635
1636   if (context->encodings) {
1637     GstMatroskaTrackEncoding *enc;
1638     guint i;
1639
1640     for (i = 0; i < context->encodings->len; i++) {
1641       enc = &g_array_index (context->encodings, GstMatroskaTrackEncoding, i);
1642       if (enc->type == GST_MATROSKA_ENCODING_ENCRYPTION /* encryption */ ) {
1643         GstStructure *s = gst_caps_get_structure (caps, 0);
1644         if (!gst_structure_has_name (s, "application/x-webm-enc")) {
1645           gst_structure_set (s, "original-media-type", G_TYPE_STRING,
1646               gst_structure_get_name (s), NULL);
1647           gst_structure_set (s, "encryption-algorithm", G_TYPE_STRING,
1648               gst_matroska_track_encryption_algorithm_name (enc->enc_algo),
1649               NULL);
1650           gst_structure_set (s, "encoding-scope", G_TYPE_STRING,
1651               gst_matroska_track_encoding_scope_name (enc->scope), NULL);
1652           gst_structure_set (s, "cipher-mode", G_TYPE_STRING,
1653               gst_matroska_track_encryption_cipher_mode_name
1654               (enc->enc_cipher_mode), NULL);
1655           gst_structure_set_name (s, "application/x-webm-enc");
1656         }
1657       }
1658     }
1659   }
1660
1661   context->caps = caps;
1662
1663   /* tadaah! */
1664   *dest_context = context;
1665   return ret;
1666 }
1667
1668 static void
1669 gst_matroska_demux_add_stream (GstMatroskaDemux * demux,
1670     GstMatroskaTrackContext * context)
1671 {
1672   GstElementClass *klass = GST_ELEMENT_GET_CLASS (demux);
1673   gchar *padname = NULL;
1674   GstPadTemplate *templ = NULL;
1675   GstStreamFlags stream_flags;
1676
1677   GstEvent *stream_start;
1678
1679   gchar *stream_id;
1680
1681   g_ptr_array_add (demux->common.src, context);
1682   context->index = demux->common.num_streams++;
1683   g_assert (demux->common.src->len == demux->common.num_streams);
1684   g_ptr_array_index (demux->common.src, demux->common.num_streams - 1) =
1685       context;
1686
1687   /* now create the GStreamer connectivity */
1688   switch (context->type) {
1689     case GST_MATROSKA_TRACK_TYPE_VIDEO:
1690       padname = g_strdup_printf ("video_%u", demux->num_v_streams++);
1691       templ = gst_element_class_get_pad_template (klass, "video_%u");
1692
1693       if (!context->intra_only)
1694         demux->have_nonintraonly_v_streams = TRUE;
1695       break;
1696
1697     case GST_MATROSKA_TRACK_TYPE_AUDIO:
1698       padname = g_strdup_printf ("audio_%u", demux->num_a_streams++);
1699       templ = gst_element_class_get_pad_template (klass, "audio_%u");
1700       break;
1701
1702     case GST_MATROSKA_TRACK_TYPE_SUBTITLE:
1703       padname = g_strdup_printf ("subtitle_%u", demux->num_t_streams++);
1704       templ = gst_element_class_get_pad_template (klass, "subtitle_%u");
1705       break;
1706
1707     default:
1708       /* we should already have quit by now */
1709       g_assert_not_reached ();
1710   }
1711
1712   /* the pad in here */
1713   context->pad = gst_pad_new_from_template (templ, padname);
1714
1715   gst_pad_set_event_function (context->pad,
1716       GST_DEBUG_FUNCPTR (gst_matroska_demux_handle_src_event));
1717   gst_pad_set_query_function (context->pad,
1718       GST_DEBUG_FUNCPTR (gst_matroska_demux_handle_src_query));
1719
1720   GST_INFO_OBJECT (demux, "Adding pad '%s' with caps %" GST_PTR_FORMAT,
1721       padname, context->caps);
1722
1723   gst_pad_set_element_private (context->pad, context);
1724
1725   gst_pad_use_fixed_caps (context->pad);
1726   gst_pad_set_active (context->pad, TRUE);
1727
1728   stream_id =
1729       gst_pad_create_stream_id_printf (context->pad, GST_ELEMENT_CAST (demux),
1730       "%03" G_GUINT64_FORMAT ":%03" G_GUINT64_FORMAT,
1731       context->num, context->uid);
1732   stream_start =
1733       gst_pad_get_sticky_event (demux->common.sinkpad, GST_EVENT_STREAM_START,
1734       0);
1735   if (stream_start) {
1736     if (gst_event_parse_group_id (stream_start, &demux->group_id))
1737       demux->have_group_id = TRUE;
1738     else
1739       demux->have_group_id = FALSE;
1740     gst_event_unref (stream_start);
1741   } else if (!demux->have_group_id) {
1742     demux->have_group_id = TRUE;
1743     demux->group_id = gst_util_group_id_next ();
1744   }
1745
1746   stream_start = gst_event_new_stream_start (stream_id);
1747   g_free (stream_id);
1748   if (demux->have_group_id)
1749     gst_event_set_group_id (stream_start, demux->group_id);
1750   stream_flags = GST_STREAM_FLAG_NONE;
1751   if (context->type == GST_MATROSKA_TRACK_TYPE_SUBTITLE)
1752     stream_flags |= GST_STREAM_FLAG_SPARSE;
1753   if (context->flags & GST_MATROSKA_TRACK_DEFAULT)
1754     stream_flags |= GST_STREAM_FLAG_SELECT;
1755   else if (!(context->flags & GST_MATROSKA_TRACK_ENABLED))
1756     stream_flags |= GST_STREAM_FLAG_UNSELECT;
1757
1758   gst_event_set_stream_flags (stream_start, stream_flags);
1759   gst_pad_push_event (context->pad, stream_start);
1760   gst_pad_set_caps (context->pad, context->caps);
1761
1762
1763   if (demux->common.global_tags) {
1764     GstEvent *tag_event;
1765
1766     gst_tag_list_add (demux->common.global_tags, GST_TAG_MERGE_REPLACE,
1767         GST_TAG_CONTAINER_FORMAT, "Matroska", NULL);
1768     GST_DEBUG_OBJECT (context->pad, "Sending global_tags %p: %" GST_PTR_FORMAT,
1769         demux->common.global_tags, demux->common.global_tags);
1770
1771     tag_event =
1772         gst_event_new_tag (gst_tag_list_copy (demux->common.global_tags));
1773
1774     gst_pad_push_event (context->pad, tag_event);
1775   }
1776
1777   if (G_UNLIKELY (context->tags_changed)) {
1778     GST_DEBUG_OBJECT (context->pad, "Sending tags %p: %"
1779         GST_PTR_FORMAT, context->tags, context->tags);
1780     gst_pad_push_event (context->pad,
1781         gst_event_new_tag (gst_tag_list_copy (context->tags)));
1782     context->tags_changed = FALSE;
1783   }
1784
1785   gst_element_add_pad (GST_ELEMENT (demux), context->pad);
1786   gst_flow_combiner_add_pad (demux->flowcombiner, context->pad);
1787
1788   g_free (padname);
1789 }
1790
1791 static gboolean
1792 gst_matroska_demux_query (GstMatroskaDemux * demux, GstPad * pad,
1793     GstQuery * query)
1794 {
1795   gboolean res = FALSE;
1796   GstMatroskaTrackContext *context = NULL;
1797
1798   if (pad) {
1799     context = gst_pad_get_element_private (pad);
1800   }
1801
1802   switch (GST_QUERY_TYPE (query)) {
1803     case GST_QUERY_POSITION:
1804     {
1805       GstFormat format;
1806
1807       gst_query_parse_position (query, &format, NULL);
1808
1809       res = TRUE;
1810       if (format == GST_FORMAT_TIME) {
1811         GST_OBJECT_LOCK (demux);
1812         if (context)
1813           gst_query_set_position (query, GST_FORMAT_TIME,
1814               MAX (context->pos, demux->stream_start_time) -
1815               demux->stream_start_time);
1816         else
1817           gst_query_set_position (query, GST_FORMAT_TIME,
1818               MAX (demux->common.segment.position, demux->stream_start_time) -
1819               demux->stream_start_time);
1820         GST_OBJECT_UNLOCK (demux);
1821       } else if (format == GST_FORMAT_DEFAULT && context
1822           && context->default_duration) {
1823         GST_OBJECT_LOCK (demux);
1824         gst_query_set_position (query, GST_FORMAT_DEFAULT,
1825             context->pos / context->default_duration);
1826         GST_OBJECT_UNLOCK (demux);
1827       } else {
1828         GST_DEBUG_OBJECT (demux,
1829             "only position query in TIME and DEFAULT format is supported");
1830         res = FALSE;
1831       }
1832
1833       break;
1834     }
1835     case GST_QUERY_DURATION:
1836     {
1837       GstFormat format;
1838
1839       gst_query_parse_duration (query, &format, NULL);
1840
1841       res = TRUE;
1842       if (format == GST_FORMAT_TIME) {
1843         GST_OBJECT_LOCK (demux);
1844         gst_query_set_duration (query, GST_FORMAT_TIME,
1845             demux->common.segment.duration);
1846         GST_OBJECT_UNLOCK (demux);
1847       } else if (format == GST_FORMAT_DEFAULT && context
1848           && context->default_duration) {
1849         GST_OBJECT_LOCK (demux);
1850         gst_query_set_duration (query, GST_FORMAT_DEFAULT,
1851             demux->common.segment.duration / context->default_duration);
1852         GST_OBJECT_UNLOCK (demux);
1853       } else {
1854         GST_DEBUG_OBJECT (demux,
1855             "only duration query in TIME and DEFAULT format is supported");
1856         res = FALSE;
1857       }
1858       break;
1859     }
1860
1861     case GST_QUERY_SEEKING:
1862     {
1863       GstFormat fmt;
1864
1865       gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
1866       GST_OBJECT_LOCK (demux);
1867       if (fmt == GST_FORMAT_TIME) {
1868         gboolean seekable;
1869
1870         if (demux->streaming) {
1871           /* assuming we'll be able to get an index ... */
1872           seekable = demux->seekable;
1873         } else {
1874           seekable = TRUE;
1875         }
1876
1877         gst_query_set_seeking (query, GST_FORMAT_TIME, seekable,
1878             0, demux->common.segment.duration);
1879         res = TRUE;
1880       }
1881       GST_OBJECT_UNLOCK (demux);
1882       break;
1883     }
1884     case GST_QUERY_SEGMENT:
1885     {
1886       GstFormat format;
1887       gint64 start, stop;
1888
1889       format = demux->common.segment.format;
1890
1891       start =
1892           gst_segment_to_stream_time (&demux->common.segment, format,
1893           demux->common.segment.start);
1894       if ((stop = demux->common.segment.stop) == -1)
1895         stop = demux->common.segment.duration;
1896       else
1897         stop =
1898             gst_segment_to_stream_time (&demux->common.segment, format, stop);
1899
1900       gst_query_set_segment (query, demux->common.segment.rate, format, start,
1901           stop);
1902       res = TRUE;
1903       break;
1904     }
1905     default:
1906       if (pad)
1907         res = gst_pad_query_default (pad, (GstObject *) demux, query);
1908       else
1909         res =
1910             GST_ELEMENT_CLASS (parent_class)->query (GST_ELEMENT_CAST (demux),
1911             query);
1912       break;
1913   }
1914
1915   return res;
1916 }
1917
1918 static gboolean
1919 gst_matroska_demux_element_query (GstElement * element, GstQuery * query)
1920 {
1921   return gst_matroska_demux_query (GST_MATROSKA_DEMUX (element), NULL, query);
1922 }
1923
1924 static gboolean
1925 gst_matroska_demux_handle_src_query (GstPad * pad, GstObject * parent,
1926     GstQuery * query)
1927 {
1928   GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (parent);
1929
1930   return gst_matroska_demux_query (demux, pad, query);
1931 }
1932
1933 /* returns FALSE if there are no pads to deliver event to,
1934  * otherwise TRUE (whatever the outcome of event sending),
1935  * takes ownership of the passed event! */
1936 static gboolean
1937 gst_matroska_demux_send_event (GstMatroskaDemux * demux, GstEvent * event)
1938 {
1939   gboolean ret = FALSE;
1940   gint i;
1941
1942   g_return_val_if_fail (event != NULL, FALSE);
1943
1944   GST_DEBUG_OBJECT (demux, "Sending event of type %s to all source pads",
1945       GST_EVENT_TYPE_NAME (event));
1946
1947   g_assert (demux->common.src->len == demux->common.num_streams);
1948   for (i = 0; i < demux->common.src->len; i++) {
1949     GstMatroskaTrackContext *stream;
1950
1951     stream = g_ptr_array_index (demux->common.src, i);
1952     gst_event_ref (event);
1953     gst_pad_push_event (stream->pad, event);
1954     ret = TRUE;
1955   }
1956
1957   gst_event_unref (event);
1958   return ret;
1959 }
1960
1961 static void
1962 gst_matroska_demux_send_tags (GstMatroskaDemux * demux)
1963 {
1964   gint i;
1965
1966   if (G_UNLIKELY (demux->common.global_tags_changed)) {
1967     GstEvent *tag_event;
1968     gst_tag_list_add (demux->common.global_tags, GST_TAG_MERGE_REPLACE,
1969         GST_TAG_CONTAINER_FORMAT, "Matroska", NULL);
1970     GST_DEBUG_OBJECT (demux, "Sending global_tags %p : %" GST_PTR_FORMAT,
1971         demux->common.global_tags, demux->common.global_tags);
1972
1973     tag_event =
1974         gst_event_new_tag (gst_tag_list_copy (demux->common.global_tags));
1975
1976     for (i = 0; i < demux->common.src->len; i++) {
1977       GstMatroskaTrackContext *stream;
1978
1979       stream = g_ptr_array_index (demux->common.src, i);
1980       gst_pad_push_event (stream->pad, gst_event_ref (tag_event));
1981     }
1982
1983     gst_event_unref (tag_event);
1984     demux->common.global_tags_changed = FALSE;
1985   }
1986
1987   g_assert (demux->common.src->len == demux->common.num_streams);
1988   for (i = 0; i < demux->common.src->len; i++) {
1989     GstMatroskaTrackContext *stream;
1990
1991     stream = g_ptr_array_index (demux->common.src, i);
1992
1993     if (G_UNLIKELY (stream->tags_changed)) {
1994       GST_DEBUG_OBJECT (demux, "Sending tags %p for pad %s:%s : %"
1995           GST_PTR_FORMAT, stream->tags,
1996           GST_DEBUG_PAD_NAME (stream->pad), stream->tags);
1997       gst_pad_push_event (stream->pad,
1998           gst_event_new_tag (gst_tag_list_copy (stream->tags)));
1999       stream->tags_changed = FALSE;
2000     }
2001   }
2002 }
2003
2004 static gboolean
2005 gst_matroska_demux_element_send_event (GstElement * element, GstEvent * event)
2006 {
2007   GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (element);
2008   gboolean res;
2009
2010   g_return_val_if_fail (event != NULL, FALSE);
2011
2012   if (GST_EVENT_TYPE (event) == GST_EVENT_SEEK) {
2013     /* no seeking until we are (safely) ready */
2014     if (demux->common.state != GST_MATROSKA_READ_STATE_DATA) {
2015       GST_DEBUG_OBJECT (demux,
2016           "not ready for seeking yet, deferring seek: %" GST_PTR_FORMAT, event);
2017       if (demux->deferred_seek_event)
2018         gst_event_unref (demux->deferred_seek_event);
2019       demux->deferred_seek_event = event;
2020       demux->deferred_seek_pad = NULL;
2021       return TRUE;
2022     }
2023     if (!demux->streaming)
2024       res = gst_matroska_demux_handle_seek_event (demux, NULL, event);
2025     else
2026       res = gst_matroska_demux_handle_seek_push (demux, NULL, event);
2027   } else {
2028     GST_WARNING_OBJECT (demux, "Unhandled event of type %s",
2029         GST_EVENT_TYPE_NAME (event));
2030     res = FALSE;
2031   }
2032   gst_event_unref (event);
2033   return res;
2034 }
2035
2036 static gboolean
2037 gst_matroska_demux_move_to_entry (GstMatroskaDemux * demux,
2038     GstMatroskaIndex * entry, gboolean reset, gboolean update)
2039 {
2040   gint i;
2041
2042   GST_OBJECT_LOCK (demux);
2043
2044   if (update) {
2045     /* seek (relative to matroska segment) */
2046     /* position might be invalid; will error when streaming resumes ... */
2047     demux->common.offset = entry->pos + demux->common.ebml_segment_start;
2048     demux->next_cluster_offset = 0;
2049
2050     GST_DEBUG_OBJECT (demux,
2051         "Seeked to offset %" G_GUINT64_FORMAT ", block %d, " "time %"
2052         GST_TIME_FORMAT, entry->pos + demux->common.ebml_segment_start,
2053         entry->block, GST_TIME_ARGS (entry->time));
2054
2055     /* update the time */
2056     gst_matroska_read_common_reset_streams (&demux->common, entry->time, TRUE);
2057     gst_flow_combiner_reset (demux->flowcombiner);
2058     demux->common.segment.position = entry->time;
2059     demux->seek_block = entry->block;
2060     demux->seek_first = TRUE;
2061     demux->last_stop_end = GST_CLOCK_TIME_NONE;
2062   }
2063
2064   for (i = 0; i < demux->common.src->len; i++) {
2065     GstMatroskaTrackContext *stream = g_ptr_array_index (demux->common.src, i);
2066
2067     if (reset) {
2068       stream->to_offset = G_MAXINT64;
2069     } else {
2070       if (stream->from_offset != -1)
2071         stream->to_offset = stream->from_offset;
2072     }
2073     stream->from_offset = -1;
2074     stream->from_time = GST_CLOCK_TIME_NONE;
2075   }
2076
2077   GST_OBJECT_UNLOCK (demux);
2078
2079   return TRUE;
2080 }
2081
2082 static gint
2083 gst_matroska_cluster_compare (gint64 * i1, gint64 * i2)
2084 {
2085   if (*i1 < *i2)
2086     return -1;
2087   else if (*i1 > *i2)
2088     return 1;
2089   else
2090     return 0;
2091 }
2092
2093 /* searches for a cluster start from @pos,
2094  * return GST_FLOW_OK and cluster position in @pos if found */
2095 static GstFlowReturn
2096 gst_matroska_demux_search_cluster (GstMatroskaDemux * demux, gint64 * pos,
2097     gboolean forward)
2098 {
2099   gint64 newpos = *pos;
2100   gint64 orig_offset;
2101   GstFlowReturn ret = GST_FLOW_OK;
2102   const guint chunk = 128 * 1024;
2103   GstBuffer *buf = NULL;
2104   GstMapInfo map;
2105   gpointer data = NULL;
2106   gsize size;
2107   guint64 length;
2108   guint32 id;
2109   guint needed;
2110   gint64 oldpos, oldlength;
2111
2112   orig_offset = demux->common.offset;
2113
2114   GST_LOG_OBJECT (demux, "searching cluster %s offset %" G_GINT64_FORMAT,
2115       forward ? "following" : "preceding", *pos);
2116
2117   if (demux->clusters) {
2118     gint64 *cpos;
2119
2120     cpos = gst_util_array_binary_search (demux->clusters->data,
2121         demux->clusters->len, sizeof (gint64),
2122         (GCompareDataFunc) gst_matroska_cluster_compare,
2123         forward ? GST_SEARCH_MODE_AFTER : GST_SEARCH_MODE_BEFORE, pos, NULL);
2124     /* sanity check */
2125     if (cpos) {
2126       GST_DEBUG_OBJECT (demux,
2127           "cluster reported at offset %" G_GINT64_FORMAT, *cpos);
2128       demux->common.offset = *cpos;
2129       ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
2130           GST_ELEMENT_CAST (demux), &id, &length, &needed);
2131       if (ret == GST_FLOW_OK && id == GST_MATROSKA_ID_CLUSTER) {
2132         newpos = *cpos;
2133         goto exit;
2134       }
2135     }
2136   }
2137
2138   /* read in at newpos and scan for ebml cluster id */
2139   oldpos = oldlength = -1;
2140   while (1) {
2141     GstByteReader reader;
2142     gint cluster_pos;
2143     guint toread = chunk;
2144
2145     if (!forward) {
2146       /* never read beyond the requested target */
2147       if (G_UNLIKELY (newpos < chunk)) {
2148         toread = newpos;
2149         newpos = 0;
2150       } else {
2151         newpos -= chunk;
2152       }
2153     }
2154     if (buf != NULL) {
2155       gst_buffer_unmap (buf, &map);
2156       gst_buffer_unref (buf);
2157       buf = NULL;
2158     }
2159     ret = gst_pad_pull_range (demux->common.sinkpad, newpos, toread, &buf);
2160     if (ret != GST_FLOW_OK)
2161       break;
2162     GST_DEBUG_OBJECT (demux,
2163         "read buffer size %" G_GSIZE_FORMAT " at offset %" G_GINT64_FORMAT,
2164         gst_buffer_get_size (buf), newpos);
2165     gst_buffer_map (buf, &map, GST_MAP_READ);
2166     data = map.data;
2167     size = map.size;
2168     if (oldpos == newpos && oldlength == map.size) {
2169       GST_ERROR_OBJECT (demux, "Stuck at same position");
2170       ret = GST_FLOW_ERROR;
2171       goto exit;
2172     } else {
2173       oldpos = newpos;
2174       oldlength = map.size;
2175     }
2176
2177     gst_byte_reader_init (&reader, data, size);
2178     cluster_pos = -1;
2179     while (1) {
2180       gint found = gst_byte_reader_masked_scan_uint32 (&reader, 0xffffffff,
2181           GST_MATROSKA_ID_CLUSTER, 0, gst_byte_reader_get_remaining (&reader));
2182       if (forward) {
2183         cluster_pos = found;
2184         break;
2185       }
2186       /* need last occurrence when searching backwards */
2187       if (found >= 0) {
2188         cluster_pos = gst_byte_reader_get_pos (&reader) + found;
2189         gst_byte_reader_skip (&reader, found + 4);
2190       } else {
2191         break;
2192       }
2193     }
2194
2195     if (cluster_pos >= 0) {
2196       newpos += cluster_pos;
2197       GST_DEBUG_OBJECT (demux,
2198           "found cluster ebml id at offset %" G_GINT64_FORMAT, newpos);
2199       /* extra checks whether we really sync'ed to a cluster:
2200        * - either it is the first and only cluster
2201        * - either there is a cluster after this one
2202        * - either cluster length is undefined
2203        */
2204       /* ok if first cluster (there may not a subsequent one) */
2205       if (newpos == demux->first_cluster_offset) {
2206         GST_DEBUG_OBJECT (demux, "cluster is first cluster -> OK");
2207         break;
2208       }
2209       demux->common.offset = newpos;
2210       ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
2211           GST_ELEMENT_CAST (demux), &id, &length, &needed);
2212       if (ret != GST_FLOW_OK) {
2213         GST_DEBUG_OBJECT (demux, "need more data -> continue");
2214         goto next;
2215       }
2216       g_assert (id == GST_MATROSKA_ID_CLUSTER);
2217       GST_DEBUG_OBJECT (demux, "cluster size %" G_GUINT64_FORMAT ", prefix %d",
2218           length, needed);
2219       /* ok if undefined length or first cluster */
2220       if (length == GST_EBML_SIZE_UNKNOWN || length == G_MAXUINT64) {
2221         GST_DEBUG_OBJECT (demux, "cluster has undefined length -> OK");
2222         break;
2223       }
2224       /* skip cluster */
2225       demux->common.offset += length + needed;
2226       ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
2227           GST_ELEMENT_CAST (demux), &id, &length, &needed);
2228       if (ret != GST_FLOW_OK)
2229         goto next;
2230       GST_DEBUG_OBJECT (demux, "next element is %scluster",
2231           id == GST_MATROSKA_ID_CLUSTER ? "" : "not ");
2232       if (id == GST_MATROSKA_ID_CLUSTER)
2233         break;
2234     next:
2235       if (forward)
2236         newpos += 1;
2237     } else {
2238       /* partial cluster id may have been in tail of buffer */
2239       newpos +=
2240           forward ? MAX (gst_byte_reader_get_remaining (&reader), 4) - 3 : 3;
2241     }
2242   }
2243
2244   if (buf) {
2245     gst_buffer_unmap (buf, &map);
2246     gst_buffer_unref (buf);
2247     buf = NULL;
2248   }
2249
2250 exit:
2251   demux->common.offset = orig_offset;
2252   *pos = newpos;
2253   return ret;
2254 }
2255
2256 /* Three states to express: starts with I-frame, starts with delta, don't know */
2257 typedef enum
2258 {
2259   CLUSTER_STATUS_NONE = 0,
2260   CLUSTER_STATUS_STARTS_WITH_KEYFRAME,
2261   CLUSTER_STATUS_STARTS_WITH_DELTAUNIT,
2262 } ClusterStatus;
2263
2264 typedef struct
2265 {
2266   guint64 offset;
2267   guint64 size;
2268   guint64 prev_size;
2269   GstClockTime time;
2270   ClusterStatus status;
2271 } ClusterInfo;
2272
2273 static const gchar *
2274 cluster_status_get_nick (ClusterStatus status)
2275 {
2276   switch (status) {
2277     case CLUSTER_STATUS_NONE:
2278       return "none";
2279     case CLUSTER_STATUS_STARTS_WITH_KEYFRAME:
2280       return "key";
2281     case CLUSTER_STATUS_STARTS_WITH_DELTAUNIT:
2282       return "delta";
2283   }
2284   return "???";
2285 }
2286
2287 /* Skip ebml-coded number:
2288  *  1xxx.. = 1 byte
2289  *  01xx.. = 2 bytes
2290  *  001x.. = 3 bytes, etc.
2291  */
2292 static gboolean
2293 bit_reader_skip_ebml_num (GstBitReader * br)
2294 {
2295   guint8 i, v = 0;
2296
2297   if (!gst_bit_reader_peek_bits_uint8 (br, &v, 8))
2298     return FALSE;
2299
2300   for (i = 0; i < 8; i++) {
2301     if ((v & (0x80 >> i)) != 0)
2302       break;
2303   }
2304   return gst_bit_reader_skip (br, (i + 1) * 8);
2305 }
2306
2307 /* Don't probe more than that many bytes into the cluster for keyframe info
2308  * (random value, mostly for sanity checking) */
2309 #define MAX_CLUSTER_INFO_PROBE_LENGTH 256
2310
2311 static gboolean
2312 gst_matroska_demux_peek_cluster_info (GstMatroskaDemux * demux,
2313     ClusterInfo * cluster, guint64 offset)
2314 {
2315   demux->common.offset = offset;
2316   demux->cluster_time = GST_CLOCK_TIME_NONE;
2317
2318   cluster->offset = offset;
2319   cluster->size = 0;
2320   cluster->prev_size = 0;
2321   cluster->time = GST_CLOCK_TIME_NONE;
2322   cluster->status = CLUSTER_STATUS_NONE;
2323
2324   /* parse first few elements in cluster */
2325   do {
2326     GstFlowReturn flow;
2327     guint64 length;
2328     guint32 id;
2329     guint needed;
2330
2331     flow = gst_matroska_read_common_peek_id_length_pull (&demux->common,
2332         GST_ELEMENT_CAST (demux), &id, &length, &needed);
2333
2334     if (flow != GST_FLOW_OK)
2335       break;
2336
2337     GST_LOG_OBJECT (demux, "Offset %" G_GUINT64_FORMAT ", Element id 0x%x, "
2338         "size %" G_GUINT64_FORMAT ", needed %d", demux->common.offset, id,
2339         length, needed);
2340
2341     /* Reached start of next cluster without finding data, stop processing */
2342     if (id == GST_MATROSKA_ID_CLUSTER && cluster->offset != offset)
2343       break;
2344
2345     /* Not going to parse into these for now, stop processing */
2346     if (id == GST_MATROSKA_ID_ENCRYPTEDBLOCK
2347         || id == GST_MATROSKA_ID_BLOCKGROUP || id == GST_MATROSKA_ID_BLOCK)
2348       break;
2349
2350     /* SimpleBlock: peek at headers to check if it's a keyframe */
2351     if (id == GST_MATROSKA_ID_SIMPLEBLOCK) {
2352       GstBitReader br;
2353       guint8 *d, hdr_len, v = 0;
2354
2355       GST_DEBUG_OBJECT (demux, "SimpleBlock found");
2356
2357       /* SimpleBlock header is max. 21 bytes */
2358       hdr_len = MIN (21, length);
2359
2360       flow = gst_matroska_read_common_peek_bytes (&demux->common,
2361           demux->common.offset, hdr_len, NULL, &d);
2362
2363       if (flow != GST_FLOW_OK)
2364         break;
2365
2366       gst_bit_reader_init (&br, d, hdr_len);
2367
2368       /* skip prefix: ebml id (SimpleBlock) + element length */
2369       if (!gst_bit_reader_skip (&br, 8 * needed))
2370         break;
2371
2372       /* skip track number (ebml coded) */
2373       if (!bit_reader_skip_ebml_num (&br))
2374         break;
2375
2376       /* skip Timecode */
2377       if (!gst_bit_reader_skip (&br, 16))
2378         break;
2379
2380       /* read flags */
2381       if (!gst_bit_reader_get_bits_uint8 (&br, &v, 8))
2382         break;
2383
2384       if ((v & 0x80) != 0)
2385         cluster->status = CLUSTER_STATUS_STARTS_WITH_KEYFRAME;
2386       else
2387         cluster->status = CLUSTER_STATUS_STARTS_WITH_DELTAUNIT;
2388
2389       break;
2390     }
2391
2392     flow = gst_matroska_demux_parse_id (demux, id, length, needed);
2393
2394     if (flow != GST_FLOW_OK)
2395       break;
2396
2397     switch (id) {
2398       case GST_MATROSKA_ID_CLUSTER:
2399         if (length == G_MAXUINT64)
2400           cluster->size = 0;
2401         else
2402           cluster->size = length + needed;
2403         break;
2404       case GST_MATROSKA_ID_PREVSIZE:
2405         cluster->prev_size = demux->cluster_prevsize;
2406         break;
2407       case GST_MATROSKA_ID_CLUSTERTIMECODE:
2408         cluster->time = demux->cluster_time * demux->common.time_scale;
2409         break;
2410       case GST_MATROSKA_ID_SILENTTRACKS:
2411       case GST_EBML_ID_CRC32:
2412         /* ignore and continue */
2413         break;
2414       default:
2415         GST_WARNING_OBJECT (demux, "Unknown ebml id 0x%08x (possibly garbage), "
2416             "bailing out", id);
2417         goto out;
2418     }
2419   } while (demux->common.offset - offset < MAX_CLUSTER_INFO_PROBE_LENGTH);
2420
2421 out:
2422
2423   GST_INFO_OBJECT (demux, "Cluster @ %" G_GUINT64_FORMAT ": "
2424       "time %" GST_TIME_FORMAT ", size %" G_GUINT64_FORMAT ", "
2425       "prev_size %" G_GUINT64_FORMAT ", %s", cluster->offset,
2426       GST_TIME_ARGS (cluster->time), cluster->size, cluster->prev_size,
2427       cluster_status_get_nick (cluster->status));
2428
2429   /* return success as long as we could extract the minimum useful information */
2430   return cluster->time != GST_CLOCK_TIME_NONE;
2431 }
2432
2433 /* returns TRUE if the cluster offset was updated */
2434 static gboolean
2435 gst_matroska_demux_scan_back_for_keyframe_cluster (GstMatroskaDemux * demux,
2436     gint64 * cluster_offset, GstClockTime * cluster_time)
2437 {
2438   GstClockTime stream_start_time = demux->stream_start_time;
2439   guint64 first_cluster_offset = demux->first_cluster_offset;
2440   gint64 off = *cluster_offset;
2441   ClusterInfo cluster = { 0, };
2442
2443   GST_INFO_OBJECT (demux, "Checking if cluster starts with keyframe");
2444   while (off > first_cluster_offset) {
2445     if (!gst_matroska_demux_peek_cluster_info (demux, &cluster, off)) {
2446       GST_LOG_OBJECT (demux,
2447           "Couldn't get info on cluster @ %" G_GUINT64_FORMAT, off);
2448       break;
2449     }
2450
2451     /* Keyframe? Then we're done */
2452     if (cluster.status == CLUSTER_STATUS_STARTS_WITH_KEYFRAME) {
2453       GST_LOG_OBJECT (demux,
2454           "Found keyframe at start of cluster @ %" G_GUINT64_FORMAT, off);
2455       break;
2456     }
2457
2458     /* We only scan back if we *know* we landed on a cluster that
2459      * starts with a delta frame. */
2460     if (cluster.status != CLUSTER_STATUS_STARTS_WITH_DELTAUNIT) {
2461       GST_LOG_OBJECT (demux,
2462           "No delta frame at start of cluster @ %" G_GUINT64_FORMAT, off);
2463       break;
2464     }
2465
2466     GST_DEBUG_OBJECT (demux, "Cluster starts with delta frame, backtracking");
2467
2468     /* Don't scan back more than this much in time from the cluster we
2469      * originally landed on. This is mostly a sanity check in case a file
2470      * always has keyframes in the middle of clusters and never at the
2471      * beginning. Without this we would always scan back to the beginning
2472      * of the file in that case. */
2473     if (cluster.time != GST_CLOCK_TIME_NONE) {
2474       GstClockTimeDiff distance = GST_CLOCK_DIFF (cluster.time, *cluster_time);
2475
2476       if (distance < 0 || distance > demux->max_backtrack_distance * GST_SECOND) {
2477         GST_DEBUG_OBJECT (demux, "Haven't found cluster with keyframe within "
2478             "%u secs of original seek target cluster, stopping",
2479             demux->max_backtrack_distance);
2480         break;
2481       }
2482     }
2483
2484     /* If we have cluster prev_size we can skip back efficiently. If not,
2485      * we'll just do a brute force search for a cluster identifier */
2486     if (cluster.prev_size > 0 && off >= cluster.prev_size) {
2487       off -= cluster.prev_size;
2488     } else {
2489       GstFlowReturn flow;
2490
2491       GST_LOG_OBJECT (demux, "Cluster has no or invalid prev size, searching "
2492           "for previous cluster instead then");
2493
2494       flow = gst_matroska_demux_search_cluster (demux, &off, FALSE);
2495       if (flow != GST_FLOW_OK) {
2496         GST_DEBUG_OBJECT (demux, "cluster search yielded flow %s, stopping",
2497             gst_flow_get_name (flow));
2498         break;
2499       }
2500     }
2501
2502     if (off <= first_cluster_offset) {
2503       GST_LOG_OBJECT (demux, "Reached first cluster, stopping");
2504       *cluster_offset = first_cluster_offset;
2505       *cluster_time = stream_start_time;
2506       return TRUE;
2507     }
2508     GST_LOG_OBJECT (demux, "Trying prev cluster @ %" G_GUINT64_FORMAT, off);
2509   }
2510
2511   /* If we found a cluster starting with a keyframe jump to that instead,
2512    * otherwise leave everything as it was before */
2513   if (cluster.time != GST_CLOCK_TIME_NONE
2514       && (cluster.offset == first_cluster_offset
2515           || cluster.status == CLUSTER_STATUS_STARTS_WITH_KEYFRAME)) {
2516     *cluster_offset = cluster.offset;
2517     *cluster_time = cluster.time;
2518     return TRUE;
2519   }
2520
2521   return FALSE;
2522 }
2523
2524 /* bisect and scan through file for cluster starting before @time,
2525  * returns fake index entry with corresponding info on cluster */
2526 static GstMatroskaIndex *
2527 gst_matroska_demux_search_pos (GstMatroskaDemux * demux, GstClockTime time)
2528 {
2529   GstMatroskaIndex *entry = NULL;
2530   GstMatroskaReadState current_state;
2531   GstClockTime otime, prev_cluster_time, current_cluster_time, cluster_time;
2532   GstClockTime atime;
2533   gint64 opos, newpos, current_offset;
2534   gint64 prev_cluster_offset = -1, current_cluster_offset, cluster_offset;
2535   gint64 apos, maxpos;
2536   guint64 cluster_size = 0;
2537   GstFlowReturn ret;
2538   guint64 length;
2539   guint32 id;
2540   guint needed;
2541
2542   /* estimate new position, resync using cluster ebml id,
2543    * and bisect further or scan forward to appropriate cluster */
2544
2545   /* save some current global state which will be touched by our scanning */
2546   current_state = demux->common.state;
2547   g_return_val_if_fail (current_state == GST_MATROSKA_READ_STATE_DATA, NULL);
2548
2549   current_cluster_offset = demux->cluster_offset;
2550   current_cluster_time = demux->cluster_time;
2551   current_offset = demux->common.offset;
2552
2553   demux->common.state = GST_MATROSKA_READ_STATE_SCANNING;
2554
2555   /* estimate using start and last known cluster */
2556   GST_OBJECT_LOCK (demux);
2557   apos = demux->first_cluster_offset;
2558   atime = demux->stream_start_time;
2559   opos = demux->last_cluster_offset;
2560   otime = demux->stream_last_time;
2561   GST_OBJECT_UNLOCK (demux);
2562
2563   /* sanitize */
2564   time = MAX (time, atime);
2565   otime = MAX (otime, atime);
2566   opos = MAX (opos, apos);
2567
2568   maxpos = gst_matroska_read_common_get_length (&demux->common);
2569
2570   /* invariants;
2571    * apos <= opos
2572    * atime <= otime
2573    * apos always refer to a cluster before target time;
2574    * opos may or may not be after target time, but if it is once so,
2575    * then also in next iteration
2576    * */
2577
2578 retry:
2579   GST_LOG_OBJECT (demux,
2580       "apos: %" G_GUINT64_FORMAT ", atime: %" GST_TIME_FORMAT ", %"
2581       GST_TIME_FORMAT " in stream time, "
2582       "opos: %" G_GUINT64_FORMAT ", otime: %" GST_TIME_FORMAT ", %"
2583       GST_TIME_FORMAT " in stream time (start %" GST_TIME_FORMAT "), time %"
2584       GST_TIME_FORMAT, apos, GST_TIME_ARGS (atime),
2585       GST_TIME_ARGS (atime - demux->stream_start_time), opos,
2586       GST_TIME_ARGS (otime), GST_TIME_ARGS (otime - demux->stream_start_time),
2587       GST_TIME_ARGS (demux->stream_start_time), GST_TIME_ARGS (time));
2588
2589   g_assert (atime <= otime);
2590   g_assert (apos <= opos);
2591   if (time == GST_CLOCK_TIME_NONE) {
2592     GST_DEBUG_OBJECT (demux, "searching last cluster");
2593     newpos = maxpos;
2594     if (newpos == -1) {
2595       GST_DEBUG_OBJECT (demux, "unknown file size; bailing out");
2596       goto exit;
2597     }
2598   } else if (otime <= atime) {
2599     newpos = apos;
2600   } else {
2601     newpos = apos +
2602         gst_util_uint64_scale (opos - apos, time - atime, otime - atime);
2603     if (maxpos != -1 && newpos > maxpos)
2604       newpos = maxpos;
2605   }
2606
2607   GST_DEBUG_OBJECT (demux,
2608       "estimated offset for %" GST_TIME_FORMAT ": %" G_GINT64_FORMAT,
2609       GST_TIME_ARGS (time), newpos);
2610
2611   /* search backwards */
2612   if (newpos > apos) {
2613     ret = gst_matroska_demux_search_cluster (demux, &newpos, FALSE);
2614     if (ret != GST_FLOW_OK)
2615       goto exit;
2616   }
2617
2618   /* then start scanning and parsing for cluster time,
2619    * re-estimate if possible, otherwise next cluster and so on */
2620   /* note that each re-estimate is entered with a change in apos or opos,
2621    * avoiding infinite loop */
2622   demux->common.offset = newpos;
2623   demux->cluster_time = cluster_time = GST_CLOCK_TIME_NONE;
2624   cluster_size = 0;
2625   prev_cluster_time = GST_CLOCK_TIME_NONE;
2626   while (1) {
2627     /* peek and parse some elements */
2628     ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
2629         GST_ELEMENT_CAST (demux), &id, &length, &needed);
2630     if (ret != GST_FLOW_OK)
2631       goto error;
2632     GST_LOG_OBJECT (demux, "Offset %" G_GUINT64_FORMAT ", Element id 0x%x, "
2633         "size %" G_GUINT64_FORMAT ", needed %d", demux->common.offset, id,
2634         length, needed);
2635     ret = gst_matroska_demux_parse_id (demux, id, length, needed);
2636     if (ret != GST_FLOW_OK)
2637       goto error;
2638
2639     if (id == GST_MATROSKA_ID_CLUSTER) {
2640       cluster_time = GST_CLOCK_TIME_NONE;
2641       if (length == G_MAXUINT64)
2642         cluster_size = 0;
2643       else
2644         cluster_size = length + needed;
2645     }
2646     if (demux->cluster_time != GST_CLOCK_TIME_NONE &&
2647         cluster_time == GST_CLOCK_TIME_NONE) {
2648       cluster_time = demux->cluster_time * demux->common.time_scale;
2649       cluster_offset = demux->cluster_offset;
2650       GST_DEBUG_OBJECT (demux, "found cluster at offset %" G_GINT64_FORMAT
2651           " with time %" GST_TIME_FORMAT, cluster_offset,
2652           GST_TIME_ARGS (cluster_time));
2653       if (time == GST_CLOCK_TIME_NONE) {
2654         GST_DEBUG_OBJECT (demux, "found last cluster");
2655         prev_cluster_time = cluster_time;
2656         prev_cluster_offset = cluster_offset;
2657         break;
2658       }
2659       if (cluster_time > time) {
2660         GST_DEBUG_OBJECT (demux, "overshot target");
2661         /* cluster overshoots */
2662         if (cluster_offset == demux->first_cluster_offset) {
2663           /* but no prev one */
2664           GST_DEBUG_OBJECT (demux, "but using first cluster anyway");
2665           prev_cluster_time = cluster_time;
2666           prev_cluster_offset = cluster_offset;
2667           break;
2668         }
2669         if (prev_cluster_time != GST_CLOCK_TIME_NONE) {
2670           /* prev cluster did not overshoot, so prev cluster is target */
2671           break;
2672         } else {
2673           /* re-estimate using this new position info */
2674           opos = cluster_offset;
2675           otime = cluster_time;
2676           goto retry;
2677         }
2678       } else {
2679         /* cluster undershoots */
2680         GST_DEBUG_OBJECT (demux, "undershot target");
2681         /* ok if close enough */
2682         if (GST_CLOCK_DIFF (cluster_time, time) < 5 * GST_SECOND) {
2683           GST_DEBUG_OBJECT (demux, "target close enough");
2684           prev_cluster_time = cluster_time;
2685           prev_cluster_offset = cluster_offset;
2686           break;
2687         }
2688         if (otime > time) {
2689           /* we are in between atime and otime => can bisect if worthwhile */
2690           if (prev_cluster_time != GST_CLOCK_TIME_NONE &&
2691               cluster_time > prev_cluster_time &&
2692               (GST_CLOCK_DIFF (prev_cluster_time, cluster_time) * 10 <
2693                   GST_CLOCK_DIFF (cluster_time, time))) {
2694             /* we moved at least one cluster forward,
2695              * and it looks like target is still far away,
2696              * let's estimate again */
2697             GST_DEBUG_OBJECT (demux, "bisecting with new apos");
2698             apos = cluster_offset;
2699             atime = cluster_time;
2700             goto retry;
2701           }
2702         }
2703         /* cluster undershoots, goto next one */
2704         prev_cluster_time = cluster_time;
2705         prev_cluster_offset = cluster_offset;
2706         /* skip cluster if length is defined,
2707          * otherwise will be skippingly parsed into */
2708         if (cluster_size) {
2709           GST_DEBUG_OBJECT (demux, "skipping to next cluster");
2710           demux->common.offset = cluster_offset + cluster_size;
2711           demux->cluster_time = GST_CLOCK_TIME_NONE;
2712         } else {
2713           GST_DEBUG_OBJECT (demux, "parsing/skipping cluster elements");
2714         }
2715       }
2716     }
2717     continue;
2718
2719   error:
2720     if (ret == GST_FLOW_EOS) {
2721       if (prev_cluster_time != GST_CLOCK_TIME_NONE)
2722         break;
2723     }
2724     goto exit;
2725   }
2726
2727   /* In the bisect loop above we always undershoot and then jump forward
2728    * cluster-by-cluster until we overshoot, so if we get here we've gone
2729    * over and the previous cluster is where we need to go to. */
2730   cluster_offset = prev_cluster_offset;
2731   cluster_time = prev_cluster_time;
2732
2733   /* If we have video and can easily backtrack, check if we landed on a cluster
2734    * that starts with a keyframe - and if not backtrack until we find one that
2735    * does. */
2736   if (demux->have_nonintraonly_v_streams && demux->max_backtrack_distance > 0) {
2737     if (gst_matroska_demux_scan_back_for_keyframe_cluster (demux,
2738             &cluster_offset, &cluster_time)) {
2739       GST_INFO_OBJECT (demux, "Adjusted cluster to %" GST_TIME_FORMAT " @ "
2740           "%" G_GUINT64_FORMAT, GST_TIME_ARGS (cluster_time), cluster_offset);
2741     }
2742   }
2743
2744   entry = g_new0 (GstMatroskaIndex, 1);
2745   entry->time = cluster_time;
2746   entry->pos = cluster_offset - demux->common.ebml_segment_start;
2747   GST_DEBUG_OBJECT (demux, "simulated index entry; time %" GST_TIME_FORMAT
2748       ", pos %" G_GUINT64_FORMAT, GST_TIME_ARGS (entry->time), entry->pos);
2749
2750 exit:
2751
2752   /* restore some state */
2753   demux->cluster_offset = current_cluster_offset;
2754   demux->cluster_time = current_cluster_time;
2755   demux->common.offset = current_offset;
2756   demux->common.state = current_state;
2757
2758   return entry;
2759 }
2760
2761 static gboolean
2762 gst_matroska_demux_handle_seek_event (GstMatroskaDemux * demux,
2763     GstPad * pad, GstEvent * event)
2764 {
2765   GstMatroskaIndex *entry = NULL;
2766   GstMatroskaIndex scan_entry;
2767   GstSeekFlags flags;
2768   GstSeekType cur_type, stop_type;
2769   GstFormat format;
2770   gboolean flush, keyunit, instant_rate_change, before, after, accurate,
2771       snap_next;
2772   gdouble rate;
2773   gint64 cur, stop;
2774   GstMatroskaTrackContext *track = NULL;
2775   GstSegment seeksegment = { 0, };
2776   guint64 seekpos;
2777   gboolean update = TRUE;
2778   gboolean pad_locked = FALSE;
2779   guint32 seqnum;
2780   GstSearchMode snap_dir;
2781
2782   g_return_val_if_fail (event != NULL, FALSE);
2783
2784   if (pad)
2785     track = gst_pad_get_element_private (pad);
2786
2787   GST_DEBUG_OBJECT (demux, "Have seek %" GST_PTR_FORMAT, event);
2788
2789   gst_event_parse_seek (event, &rate, &format, &flags, &cur_type, &cur,
2790       &stop_type, &stop);
2791   seqnum = gst_event_get_seqnum (event);
2792
2793   /* we can only seek on time */
2794   if (format != GST_FORMAT_TIME) {
2795     GST_DEBUG_OBJECT (demux, "Can only seek on TIME");
2796     return FALSE;
2797   }
2798
2799   GST_DEBUG_OBJECT (demux, "configuring seek");
2800
2801   flush = ! !(flags & GST_SEEK_FLAG_FLUSH);
2802   keyunit = ! !(flags & GST_SEEK_FLAG_KEY_UNIT);
2803   after = ! !(flags & GST_SEEK_FLAG_SNAP_AFTER);
2804   before = ! !(flags & GST_SEEK_FLAG_SNAP_BEFORE);
2805   accurate = ! !(flags & GST_SEEK_FLAG_ACCURATE);
2806   instant_rate_change = ! !(flags & GST_SEEK_FLAG_INSTANT_RATE_CHANGE);
2807
2808   /* Directly send the instant-rate-change event here before taking the
2809    * stream-lock so that it can be applied as soon as possible */
2810   if (instant_rate_change) {
2811     GstEvent *ev;
2812
2813     /* instant rate change only supported if direction does not change. All
2814      * other requirements are already checked before creating the seek event
2815      * but let's double-check here to be sure */
2816     if ((rate > 0 && demux->common.segment.rate < 0) ||
2817         (rate < 0 && demux->common.segment.rate > 0) ||
2818         cur_type != GST_SEEK_TYPE_NONE ||
2819         stop_type != GST_SEEK_TYPE_NONE || flush) {
2820       GST_ERROR_OBJECT (demux,
2821           "Instant rate change seeks only supported in the "
2822           "same direction, without flushing and position change");
2823       return FALSE;
2824     }
2825
2826     ev = gst_event_new_instant_rate_change (rate /
2827         demux->common.segment.rate, (GstSegmentFlags) flags);
2828     gst_event_set_seqnum (ev, seqnum);
2829     gst_matroska_demux_send_event (demux, ev);
2830     return TRUE;
2831   }
2832
2833   /* copy segment, we need this because we still need the old
2834    * segment when we close the current segment. */
2835   memcpy (&seeksegment, &demux->common.segment, sizeof (GstSegment));
2836
2837   /* pull mode without index means that the actual duration is not known,
2838    * we might be playing a file that's still being recorded
2839    * so, invalidate our current duration, which is only a moving target,
2840    * and should not be used to clamp anything */
2841   if (!demux->streaming && !demux->common.index && demux->invalid_duration) {
2842     seeksegment.duration = GST_CLOCK_TIME_NONE;
2843   }
2844
2845   /* Subtract stream_start_time so we always seek on a segment
2846    * in stream time */
2847   if (GST_CLOCK_TIME_IS_VALID (demux->stream_start_time)) {
2848     seeksegment.start -= demux->stream_start_time;
2849     seeksegment.position -= demux->stream_start_time;
2850     if (GST_CLOCK_TIME_IS_VALID (seeksegment.stop))
2851       seeksegment.stop -= demux->stream_start_time;
2852     else
2853       seeksegment.stop = seeksegment.duration;
2854   }
2855
2856   if (!gst_segment_do_seek (&seeksegment, rate, format, flags,
2857           cur_type, cur, stop_type, stop, &update)) {
2858     GST_WARNING_OBJECT (demux, "gst_segment_do_seek() failed.");
2859     return FALSE;
2860   }
2861
2862   /* Restore the clip timestamp offset */
2863   if (GST_CLOCK_TIME_IS_VALID (demux->stream_start_time)) {
2864     seeksegment.position += demux->stream_start_time;
2865     seeksegment.start += demux->stream_start_time;
2866     if (!GST_CLOCK_TIME_IS_VALID (seeksegment.stop))
2867       seeksegment.stop = seeksegment.duration;
2868     if (GST_CLOCK_TIME_IS_VALID (seeksegment.stop))
2869       seeksegment.stop += demux->stream_start_time;
2870   }
2871
2872   /* restore segment duration (if any effect),
2873    * would be determined again when parsing, but anyway ... */
2874   seeksegment.duration = demux->common.segment.duration;
2875
2876   /* always do full update if flushing,
2877    * otherwise problems might arise downstream with missing keyframes etc */
2878   update = update || flush;
2879
2880   GST_DEBUG_OBJECT (demux, "New segment %" GST_SEGMENT_FORMAT, &seeksegment);
2881
2882   /* check sanity before we start flushing and all that */
2883   snap_next = after && !before;
2884   if (seeksegment.rate < 0)
2885     snap_dir = snap_next ? GST_SEARCH_MODE_BEFORE : GST_SEARCH_MODE_AFTER;
2886   else
2887     snap_dir = snap_next ? GST_SEARCH_MODE_AFTER : GST_SEARCH_MODE_BEFORE;
2888
2889   GST_OBJECT_LOCK (demux);
2890
2891   seekpos = seeksegment.position;
2892   if (accurate) {
2893     seekpos -= MIN (seeksegment.position, demux->audio_lead_in_ts);
2894   }
2895
2896   track = gst_matroska_read_common_get_seek_track (&demux->common, track);
2897   if ((entry = gst_matroska_read_common_do_index_seek (&demux->common, track,
2898               seekpos, &demux->seek_index, &demux->seek_entry,
2899               snap_dir)) == NULL) {
2900     /* pull mode without index can scan later on */
2901     if (demux->streaming) {
2902       GST_DEBUG_OBJECT (demux, "No matching seek entry in index");
2903       GST_OBJECT_UNLOCK (demux);
2904       return FALSE;
2905     } else if (rate < 0.0) {
2906       /* FIXME: We should build an index during playback or when scanning
2907        * that can be used here. The reverse playback code requires seek_index
2908        * and seek_entry to be set!
2909        */
2910       GST_DEBUG_OBJECT (demux,
2911           "No matching seek entry in index, needed for reverse playback");
2912       GST_OBJECT_UNLOCK (demux);
2913       return FALSE;
2914     }
2915   }
2916   GST_DEBUG_OBJECT (demux, "Seek position looks sane");
2917   GST_OBJECT_UNLOCK (demux);
2918
2919   if (!update) {
2920     /* only have to update some segment,
2921      * but also still have to honour flush and so on */
2922     GST_DEBUG_OBJECT (demux, "... no update");
2923     /* bad goto, bad ... */
2924     goto next;
2925   }
2926
2927   if (demux->streaming)
2928     goto finish;
2929
2930 next:
2931   if (flush) {
2932     GstEvent *flush_event = gst_event_new_flush_start ();
2933     gst_event_set_seqnum (flush_event, seqnum);
2934     GST_DEBUG_OBJECT (demux, "Starting flush");
2935     gst_pad_push_event (demux->common.sinkpad, gst_event_ref (flush_event));
2936     gst_matroska_demux_send_event (demux, flush_event);
2937   } else {
2938     GST_DEBUG_OBJECT (demux, "Non-flushing seek, pausing task");
2939     gst_pad_pause_task (demux->common.sinkpad);
2940   }
2941   /* ouch */
2942   if (!update) {
2943     GST_PAD_STREAM_LOCK (demux->common.sinkpad);
2944     pad_locked = TRUE;
2945     goto exit;
2946   }
2947
2948   /* now grab the stream lock so that streaming cannot continue, for
2949    * non flushing seeks when the element is in PAUSED this could block
2950    * forever. */
2951   GST_DEBUG_OBJECT (demux, "Waiting for streaming to stop");
2952   GST_PAD_STREAM_LOCK (demux->common.sinkpad);
2953   pad_locked = TRUE;
2954
2955   /* pull mode without index can do some scanning */
2956   if (!demux->streaming && !entry) {
2957     GstEvent *flush_event;
2958
2959     /* need to stop flushing upstream as we need it next */
2960     if (flush) {
2961       flush_event = gst_event_new_flush_stop (TRUE);
2962       gst_event_set_seqnum (flush_event, seqnum);
2963       gst_pad_push_event (demux->common.sinkpad, flush_event);
2964     }
2965     entry = gst_matroska_demux_search_pos (demux, seekpos);
2966     /* keep local copy */
2967     if (entry) {
2968       scan_entry = *entry;
2969       g_free (entry);
2970       entry = &scan_entry;
2971     } else {
2972       GST_DEBUG_OBJECT (demux, "Scan failed to find matching position");
2973       if (flush) {
2974         flush_event = gst_event_new_flush_stop (TRUE);
2975         gst_event_set_seqnum (flush_event, seqnum);
2976         gst_matroska_demux_send_event (demux, flush_event);
2977       }
2978       goto seek_error;
2979     }
2980   }
2981
2982 finish:
2983   if (keyunit && seeksegment.rate > 0) {
2984     GST_DEBUG_OBJECT (demux, "seek to key unit, adjusting segment start from %"
2985         GST_TIME_FORMAT " to %" GST_TIME_FORMAT,
2986         GST_TIME_ARGS (seeksegment.start), GST_TIME_ARGS (entry->time));
2987     seeksegment.start = MAX (entry->time, demux->stream_start_time);
2988     seeksegment.position = seeksegment.start;
2989     seeksegment.time = seeksegment.start - demux->stream_start_time;
2990   } else if (keyunit) {
2991     GST_DEBUG_OBJECT (demux, "seek to key unit, adjusting segment stop from %"
2992         GST_TIME_FORMAT " to %" GST_TIME_FORMAT,
2993         GST_TIME_ARGS (seeksegment.stop), GST_TIME_ARGS (entry->time));
2994     seeksegment.stop = MAX (entry->time, demux->stream_start_time);
2995     seeksegment.position = seeksegment.stop;
2996   }
2997
2998   if (demux->streaming) {
2999     GST_OBJECT_LOCK (demux);
3000     /* track real position we should start at */
3001     GST_DEBUG_OBJECT (demux, "storing segment start");
3002     demux->requested_seek_time = seeksegment.position;
3003     demux->seek_offset = entry->pos + demux->common.ebml_segment_start;
3004     GST_OBJECT_UNLOCK (demux);
3005     /* need to seek to cluster start to pick up cluster time */
3006     /* upstream takes care of flushing and all that
3007      * ... and newsegment event handling takes care of the rest */
3008     return perform_seek_to_offset (demux, rate,
3009         entry->pos + demux->common.ebml_segment_start, seqnum, flags);
3010   }
3011
3012 exit:
3013   if (flush) {
3014     GstEvent *flush_event = gst_event_new_flush_stop (TRUE);
3015     gst_event_set_seqnum (flush_event, seqnum);
3016     GST_DEBUG_OBJECT (demux, "Stopping flush");
3017     gst_pad_push_event (demux->common.sinkpad, gst_event_ref (flush_event));
3018     gst_matroska_demux_send_event (demux, flush_event);
3019   }
3020
3021   GST_OBJECT_LOCK (demux);
3022   /* now update the real segment info */
3023   GST_DEBUG_OBJECT (demux, "Committing new seek segment");
3024   memcpy (&demux->common.segment, &seeksegment, sizeof (GstSegment));
3025   GST_OBJECT_UNLOCK (demux);
3026
3027   /* update some (segment) state */
3028   if (!gst_matroska_demux_move_to_entry (demux, entry, TRUE, update))
3029     goto seek_error;
3030
3031   /* notify start of new segment */
3032   if (demux->common.segment.flags & GST_SEEK_FLAG_SEGMENT) {
3033     GstMessage *msg;
3034
3035     msg = gst_message_new_segment_start (GST_OBJECT (demux),
3036         GST_FORMAT_TIME, demux->common.segment.start);
3037     gst_message_set_seqnum (msg, seqnum);
3038     gst_element_post_message (GST_ELEMENT (demux), msg);
3039   }
3040
3041   GST_OBJECT_LOCK (demux);
3042   if (demux->new_segment)
3043     gst_event_unref (demux->new_segment);
3044
3045   /* On port from 0.10, discarded !update (for segment.update) here, FIXME? */
3046   demux->new_segment = gst_event_new_segment (&demux->common.segment);
3047   gst_event_set_seqnum (demux->new_segment, seqnum);
3048   if (demux->common.segment.rate < 0 && demux->common.segment.stop == -1)
3049     demux->to_time = demux->common.segment.position;
3050   else
3051     demux->to_time = GST_CLOCK_TIME_NONE;
3052   demux->segment_seqnum = seqnum;
3053   GST_OBJECT_UNLOCK (demux);
3054
3055   /* restart our task since it might have been stopped when we did the
3056    * flush. */
3057   gst_pad_start_task (demux->common.sinkpad,
3058       (GstTaskFunction) gst_matroska_demux_loop, demux->common.sinkpad, NULL);
3059
3060   /* streaming can continue now */
3061   if (pad_locked) {
3062     GST_PAD_STREAM_UNLOCK (demux->common.sinkpad);
3063   }
3064
3065   return TRUE;
3066
3067 seek_error:
3068   {
3069     if (pad_locked) {
3070       GST_PAD_STREAM_UNLOCK (demux->common.sinkpad);
3071     }
3072     GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL), ("Got a seek error"));
3073     return FALSE;
3074   }
3075 }
3076
3077 /*
3078  * Handle whether we can perform the seek event or if we have to let the chain
3079  * function handle seeks to build the seek indexes first.
3080  */
3081 static gboolean
3082 gst_matroska_demux_handle_seek_push (GstMatroskaDemux * demux, GstPad * pad,
3083     GstEvent * event)
3084 {
3085   GstSeekFlags flags;
3086   GstSeekType cur_type, stop_type;
3087   GstFormat format;
3088   gdouble rate;
3089   gint64 cur, stop;
3090
3091   gst_event_parse_seek (event, &rate, &format, &flags, &cur_type, &cur,
3092       &stop_type, &stop);
3093
3094   /* Directly send the instant-rate-change event here before taking the
3095    * stream-lock so that it can be applied as soon as possible */
3096   if (flags & GST_SEEK_FLAG_INSTANT_RATE_CHANGE) {
3097     guint32 seqnum;
3098     GstEvent *ev;
3099
3100     /* instant rate change only supported if direction does not change. All
3101      * other requirements are already checked before creating the seek event
3102      * but let's double-check here to be sure */
3103     if ((rate > 0 && demux->common.segment.rate < 0) ||
3104         (rate < 0 && demux->common.segment.rate > 0) ||
3105         cur_type != GST_SEEK_TYPE_NONE ||
3106         stop_type != GST_SEEK_TYPE_NONE || (flags & GST_SEEK_FLAG_FLUSH)) {
3107       GST_ERROR_OBJECT (demux,
3108           "Instant rate change seeks only supported in the "
3109           "same direction, without flushing and position change");
3110       return FALSE;
3111     }
3112
3113     seqnum = gst_event_get_seqnum (event);
3114     ev = gst_event_new_instant_rate_change (rate / demux->common.segment.rate,
3115         (GstSegmentFlags) flags);
3116     gst_event_set_seqnum (ev, seqnum);
3117     gst_matroska_demux_send_event (demux, ev);
3118     return TRUE;
3119   }
3120
3121
3122
3123   /* sanity checks */
3124
3125   /* we can only seek on time */
3126   if (format != GST_FORMAT_TIME) {
3127     GST_DEBUG_OBJECT (demux, "Can only seek on TIME");
3128     return FALSE;
3129   }
3130
3131   if (stop_type != GST_SEEK_TYPE_NONE && stop != GST_CLOCK_TIME_NONE) {
3132     GST_DEBUG_OBJECT (demux, "Seek end-time not supported in streaming mode");
3133     return FALSE;
3134   }
3135
3136   if (!(flags & GST_SEEK_FLAG_FLUSH)) {
3137     GST_DEBUG_OBJECT (demux,
3138         "Non-flushing seek not supported in streaming mode");
3139     return FALSE;
3140   }
3141
3142   if (flags & GST_SEEK_FLAG_SEGMENT) {
3143     GST_DEBUG_OBJECT (demux, "Segment seek not supported in streaming mode");
3144     return FALSE;
3145   }
3146
3147   /* check for having parsed index already */
3148   if (!demux->common.index_parsed) {
3149     gboolean building_index;
3150     guint64 offset = 0;
3151
3152     if (!demux->index_offset) {
3153       GST_DEBUG_OBJECT (demux, "no index (location); no seek in push mode");
3154       return FALSE;
3155     }
3156
3157     GST_OBJECT_LOCK (demux);
3158     /* handle the seek event in the chain function */
3159     demux->common.state = GST_MATROSKA_READ_STATE_SEEK;
3160     /* no more seek can be issued until state reset to _DATA */
3161
3162     /* copy the event */
3163     if (demux->seek_event)
3164       gst_event_unref (demux->seek_event);
3165     demux->seek_event = gst_event_ref (event);
3166
3167     /* set the building_index flag so that only one thread can setup the
3168      * structures for index seeking. */
3169     building_index = demux->building_index;
3170     if (!building_index) {
3171       demux->building_index = TRUE;
3172       offset = demux->index_offset;
3173     }
3174     GST_OBJECT_UNLOCK (demux);
3175
3176     if (!building_index) {
3177       /* seek to the first subindex or legacy index */
3178       GST_INFO_OBJECT (demux, "Seeking to Cues at %" G_GUINT64_FORMAT, offset);
3179       return perform_seek_to_offset (demux, rate, offset,
3180           gst_event_get_seqnum (event), GST_SEEK_FLAG_NONE);
3181     }
3182
3183     /* well, we are handling it already */
3184     return TRUE;
3185   }
3186
3187   /* delegate to tweaked regular seek */
3188   return gst_matroska_demux_handle_seek_event (demux, pad, event);
3189 }
3190
3191 static gboolean
3192 gst_matroska_demux_handle_src_event (GstPad * pad, GstObject * parent,
3193     GstEvent * event)
3194 {
3195   GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (parent);
3196   gboolean res = TRUE;
3197
3198   switch (GST_EVENT_TYPE (event)) {
3199     case GST_EVENT_SEEK:
3200       /* no seeking until we are (safely) ready */
3201       if (demux->common.state != GST_MATROSKA_READ_STATE_DATA) {
3202         GST_DEBUG_OBJECT (demux,
3203             "not ready for seeking yet, deferring seek event: %" GST_PTR_FORMAT,
3204             event);
3205         if (demux->deferred_seek_event)
3206           gst_event_unref (demux->deferred_seek_event);
3207         demux->deferred_seek_event = event;
3208         demux->deferred_seek_pad = pad;
3209         return TRUE;
3210       }
3211
3212       {
3213         guint32 seqnum = gst_event_get_seqnum (event);
3214         if (seqnum == demux->segment_seqnum) {
3215           GST_LOG_OBJECT (pad,
3216               "Drop duplicated SEEK event seqnum %" G_GUINT32_FORMAT, seqnum);
3217           gst_event_unref (event);
3218           return TRUE;
3219         }
3220       }
3221
3222       if (!demux->streaming)
3223         res = gst_matroska_demux_handle_seek_event (demux, pad, event);
3224       else
3225         res = gst_matroska_demux_handle_seek_push (demux, pad, event);
3226       gst_event_unref (event);
3227       break;
3228
3229     case GST_EVENT_QOS:
3230     {
3231       GstMatroskaTrackContext *context = gst_pad_get_element_private (pad);
3232       if (context->type == GST_MATROSKA_TRACK_TYPE_VIDEO) {
3233         GstMatroskaTrackVideoContext *videocontext =
3234             (GstMatroskaTrackVideoContext *) context;
3235         gdouble proportion;
3236         GstClockTimeDiff diff;
3237         GstClockTime timestamp;
3238
3239         gst_event_parse_qos (event, NULL, &proportion, &diff, &timestamp);
3240
3241         GST_OBJECT_LOCK (demux);
3242         videocontext->earliest_time = timestamp + diff;
3243         GST_OBJECT_UNLOCK (demux);
3244       }
3245       res = TRUE;
3246       gst_event_unref (event);
3247       break;
3248     }
3249
3250     case GST_EVENT_TOC_SELECT:
3251     {
3252       char *uid = NULL;
3253       GstTocEntry *entry = NULL;
3254       GstEvent *seek_event;
3255       gint64 start_pos;
3256
3257       if (!demux->common.toc) {
3258         GST_DEBUG_OBJECT (demux, "no TOC to select");
3259         return FALSE;
3260       } else {
3261         gst_event_parse_toc_select (event, &uid);
3262         if (uid != NULL) {
3263           GST_OBJECT_LOCK (demux);
3264           entry = gst_toc_find_entry (demux->common.toc, uid);
3265           if (entry == NULL) {
3266             GST_OBJECT_UNLOCK (demux);
3267             GST_WARNING_OBJECT (demux, "no TOC entry with given UID: %s", uid);
3268             res = FALSE;
3269           } else {
3270             gst_toc_entry_get_start_stop_times (entry, &start_pos, NULL);
3271             GST_OBJECT_UNLOCK (demux);
3272             seek_event = gst_event_new_seek (1.0,
3273                 GST_FORMAT_TIME,
3274                 GST_SEEK_FLAG_FLUSH,
3275                 GST_SEEK_TYPE_SET, start_pos, GST_SEEK_TYPE_SET, -1);
3276             res = gst_matroska_demux_handle_seek_event (demux, pad, seek_event);
3277             gst_event_unref (seek_event);
3278           }
3279           g_free (uid);
3280         } else {
3281           GST_WARNING_OBJECT (demux, "received empty TOC select event");
3282           res = FALSE;
3283         }
3284       }
3285       gst_event_unref (event);
3286       break;
3287     }
3288
3289       /* events we don't need to handle */
3290     case GST_EVENT_NAVIGATION:
3291       gst_event_unref (event);
3292       res = FALSE;
3293       break;
3294
3295     case GST_EVENT_LATENCY:
3296     default:
3297       res = gst_pad_push_event (demux->common.sinkpad, event);
3298       break;
3299   }
3300
3301   return res;
3302 }
3303
3304 static gboolean
3305 gst_matroska_demux_handle_sink_query (GstPad * pad, GstObject * parent,
3306     GstQuery * query)
3307 {
3308   GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (parent);
3309   gboolean res = FALSE;
3310
3311   switch (GST_QUERY_TYPE (query)) {
3312     case GST_QUERY_BITRATE:
3313     {
3314       if (G_UNLIKELY (demux->cached_length == G_MAXUINT64 ||
3315               demux->common.offset >= demux->cached_length)) {
3316         demux->cached_length =
3317             gst_matroska_read_common_get_length (&demux->common);
3318       }
3319
3320       if (demux->cached_length < G_MAXUINT64
3321           && demux->common.segment.duration > 0) {
3322         /* TODO: better results based on ranges/index tables */
3323         guint bitrate =
3324             gst_util_uint64_scale (8 * demux->cached_length, GST_SECOND,
3325             demux->common.segment.duration);
3326
3327         GST_LOG_OBJECT (demux, "bitrate query byte length: %" G_GUINT64_FORMAT
3328             " duration %" GST_TIME_FORMAT " resulting in a bitrate of %u",
3329             demux->cached_length,
3330             GST_TIME_ARGS (demux->common.segment.duration), bitrate);
3331
3332         gst_query_set_bitrate (query, bitrate);
3333         res = TRUE;
3334       }
3335       break;
3336     }
3337     default:
3338       res = gst_pad_query_default (pad, (GstObject *) demux, query);
3339       break;
3340   }
3341
3342   return res;
3343 }
3344
3345 static GstFlowReturn
3346 gst_matroska_demux_seek_to_previous_keyframe (GstMatroskaDemux * demux)
3347 {
3348   GstFlowReturn ret = GST_FLOW_EOS;
3349   gboolean done = TRUE;
3350   gint i;
3351
3352   g_return_val_if_fail (demux->seek_index, GST_FLOW_EOS);
3353   g_return_val_if_fail (demux->seek_entry < demux->seek_index->len,
3354       GST_FLOW_EOS);
3355
3356   GST_DEBUG_OBJECT (demux, "locating previous keyframe");
3357
3358   if (!demux->seek_entry) {
3359     GST_DEBUG_OBJECT (demux, "no earlier index entry");
3360     goto exit;
3361   }
3362
3363   for (i = 0; i < demux->common.src->len; i++) {
3364     GstMatroskaTrackContext *stream = g_ptr_array_index (demux->common.src, i);
3365
3366     GST_DEBUG_OBJECT (demux, "segment start %" GST_TIME_FORMAT
3367         ", stream %d at %" GST_TIME_FORMAT,
3368         GST_TIME_ARGS (demux->common.segment.start), stream->index,
3369         GST_TIME_ARGS (stream->from_time));
3370     if (GST_CLOCK_TIME_IS_VALID (stream->from_time)) {
3371       if (stream->from_time > demux->common.segment.start) {
3372         GST_DEBUG_OBJECT (demux, "stream %d not finished yet", stream->index);
3373         done = FALSE;
3374       }
3375     } else {
3376       /* nothing pushed for this stream;
3377        * likely seek entry did not start at keyframe, so all was skipped.
3378        * So we need an earlier entry */
3379       done = FALSE;
3380     }
3381   }
3382
3383   if (!done) {
3384     GstMatroskaIndex *entry;
3385
3386     entry = &g_array_index (demux->seek_index, GstMatroskaIndex,
3387         --demux->seek_entry);
3388     if (!gst_matroska_demux_move_to_entry (demux, entry, FALSE, TRUE))
3389       goto exit;
3390
3391     ret = GST_FLOW_OK;
3392   }
3393
3394 exit:
3395   return ret;
3396 }
3397
3398 static GstFlowReturn
3399 gst_matroska_demux_parse_tracks (GstMatroskaDemux * demux, GstEbmlRead * ebml)
3400 {
3401   GstFlowReturn ret = GST_FLOW_OK;
3402   guint32 id;
3403
3404   DEBUG_ELEMENT_START (demux, ebml, "Tracks");
3405
3406   if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
3407     DEBUG_ELEMENT_STOP (demux, ebml, "Tracks", ret);
3408     return ret;
3409   }
3410
3411   while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
3412     if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
3413       break;
3414
3415     switch (id) {
3416         /* one track within the "all-tracks" header */
3417       case GST_MATROSKA_ID_TRACKENTRY:{
3418         GstMatroskaTrackContext *track;
3419         ret = gst_matroska_demux_parse_stream (demux, ebml, &track);
3420         if (track != NULL) {
3421           if (gst_matroska_read_common_tracknumber_unique (&demux->common,
3422                   track->num)) {
3423             gst_matroska_demux_add_stream (demux, track);
3424           } else {
3425             GST_ERROR_OBJECT (demux,
3426                 "TrackNumber %" G_GUINT64_FORMAT " is not unique", track->num);
3427             ret = GST_FLOW_ERROR;
3428             gst_matroska_track_free (track);
3429             track = NULL;
3430           }
3431         }
3432         break;
3433       }
3434
3435       default:
3436         ret = gst_matroska_read_common_parse_skip (&demux->common, ebml,
3437             "Track", id);
3438         break;
3439     }
3440   }
3441   DEBUG_ELEMENT_STOP (demux, ebml, "Tracks", ret);
3442
3443   demux->tracks_parsed = TRUE;
3444   GST_DEBUG_OBJECT (demux, "signaling no more pads");
3445   gst_element_no_more_pads (GST_ELEMENT (demux));
3446
3447   return ret;
3448 }
3449
3450 static GstFlowReturn
3451 gst_matroska_demux_update_tracks (GstMatroskaDemux * demux, GstEbmlRead * ebml)
3452 {
3453   GstFlowReturn ret = GST_FLOW_OK;
3454   guint num_tracks_found = 0;
3455   guint32 id;
3456
3457   GST_INFO_OBJECT (demux, "Reparsing Tracks element");
3458
3459   DEBUG_ELEMENT_START (demux, ebml, "Tracks");
3460
3461   if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
3462     DEBUG_ELEMENT_STOP (demux, ebml, "Tracks", ret);
3463     return ret;
3464   }
3465
3466   while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
3467     if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
3468       break;
3469
3470     switch (id) {
3471         /* one track within the "all-tracks" header */
3472       case GST_MATROSKA_ID_TRACKENTRY:{
3473         GstMatroskaTrackContext *new_track;
3474         gint old_track_index;
3475         GstMatroskaTrackContext *old_track;
3476         ret = gst_matroska_demux_parse_stream (demux, ebml, &new_track);
3477         if (new_track == NULL)
3478           break;
3479         num_tracks_found++;
3480
3481         if (gst_matroska_read_common_tracknumber_unique (&demux->common,
3482                 new_track->num)) {
3483           GST_ERROR_OBJECT (demux,
3484               "Unexpected new TrackNumber: %" G_GUINT64_FORMAT, new_track->num);
3485           goto track_mismatch_error;
3486         }
3487
3488         old_track_index =
3489             gst_matroska_read_common_stream_from_num (&demux->common,
3490             new_track->num);
3491         g_assert (old_track_index != -1);
3492         old_track = g_ptr_array_index (demux->common.src, old_track_index);
3493
3494         if (old_track->type != new_track->type) {
3495           GST_ERROR_OBJECT (demux,
3496               "Mismatch reparsing track %" G_GUINT64_FORMAT
3497               " on track type. Expected %d, found %d", new_track->num,
3498               old_track->type, new_track->type);
3499           goto track_mismatch_error;
3500         }
3501
3502         if (g_strcmp0 (old_track->codec_id, new_track->codec_id) != 0) {
3503           GST_ERROR_OBJECT (demux,
3504               "Mismatch reparsing track %" G_GUINT64_FORMAT
3505               " on codec id. Expected '%s', found '%s'", new_track->num,
3506               old_track->codec_id, new_track->codec_id);
3507           goto track_mismatch_error;
3508         }
3509
3510         /* The new track matches the old track. No problems on our side.
3511          * Let's make it replace the old track. */
3512         new_track->pad = old_track->pad;
3513         new_track->index = old_track->index;
3514         new_track->pos = old_track->pos;
3515         g_ptr_array_index (demux->common.src, old_track_index) = new_track;
3516         gst_pad_set_element_private (new_track->pad, new_track);
3517
3518         if (!gst_caps_is_equal (old_track->caps, new_track->caps)) {
3519           gst_pad_set_caps (new_track->pad, new_track->caps);
3520         }
3521         gst_caps_replace (&old_track->caps, NULL);
3522
3523         if (!gst_tag_list_is_equal (old_track->tags, new_track->tags)) {
3524           GST_DEBUG_OBJECT (old_track->pad, "Sending tags %p: %"
3525               GST_PTR_FORMAT, new_track->tags, new_track->tags);
3526           gst_pad_push_event (new_track->pad,
3527               gst_event_new_tag (gst_tag_list_copy (new_track->tags)));
3528         }
3529
3530         gst_matroska_track_free (old_track);
3531         break;
3532
3533       track_mismatch_error:
3534         gst_matroska_track_free (new_track);
3535         new_track = NULL;
3536         ret = GST_FLOW_ERROR;
3537         break;
3538       }
3539
3540       default:
3541         ret = gst_matroska_read_common_parse_skip (&demux->common, ebml,
3542             "Track", id);
3543         break;
3544     }
3545   }
3546   DEBUG_ELEMENT_STOP (demux, ebml, "Tracks", ret);
3547
3548   if (ret != GST_FLOW_ERROR && demux->common.num_streams != num_tracks_found) {
3549     GST_ERROR_OBJECT (demux,
3550         "Mismatch on the number of tracks. Expected %du tracks, found %du",
3551         demux->common.num_streams, num_tracks_found);
3552     ret = GST_FLOW_ERROR;
3553   }
3554
3555   return ret;
3556 }
3557
3558 /*
3559  * Read signed/unsigned "EBML" numbers.
3560  * Return: number of bytes processed.
3561  */
3562
3563 static gint
3564 gst_matroska_ebmlnum_uint (guint8 * data, guint size, guint64 * num)
3565 {
3566   gint len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
3567   guint64 total;
3568
3569   if (size <= 0) {
3570     return -1;
3571   }
3572
3573   total = data[0];
3574   while (read <= 8 && !(total & len_mask)) {
3575     read++;
3576     len_mask >>= 1;
3577   }
3578   if (read > 8)
3579     return -1;
3580
3581   if ((total &= (len_mask - 1)) == len_mask - 1)
3582     num_ffs++;
3583   if (size < read)
3584     return -1;
3585   while (n < read) {
3586     if (data[n] == 0xff)
3587       num_ffs++;
3588     total = (total << 8) | data[n];
3589     n++;
3590   }
3591
3592   if (read == num_ffs && total != 0)
3593     *num = G_MAXUINT64;
3594   else
3595     *num = total;
3596
3597   return read;
3598 }
3599
3600 static gint
3601 gst_matroska_ebmlnum_sint (guint8 * data, guint size, gint64 * num)
3602 {
3603   guint64 unum;
3604   gint res;
3605
3606   /* read as unsigned number first */
3607   if ((res = gst_matroska_ebmlnum_uint (data, size, &unum)) < 0)
3608     return -1;
3609
3610   /* make signed */
3611   if (unum == G_MAXUINT64)
3612     *num = G_MAXINT64;
3613   else
3614     *num = unum - ((1 << ((7 * res) - 1)) - 1);
3615
3616   return res;
3617 }
3618
3619 /*
3620  * Mostly used for subtitles. We add void filler data for each
3621  * lagging stream to make sure we don't deadlock.
3622  */
3623
3624 static void
3625 gst_matroska_demux_sync_streams (GstMatroskaDemux * demux)
3626 {
3627   GstClockTime gap_threshold;
3628   gint stream_nr;
3629
3630   GST_OBJECT_LOCK (demux);
3631
3632   GST_LOG_OBJECT (demux, "Sync to %" GST_TIME_FORMAT,
3633       GST_TIME_ARGS (demux->common.segment.position));
3634
3635   g_assert (demux->common.num_streams == demux->common.src->len);
3636   for (stream_nr = 0; stream_nr < demux->common.src->len; stream_nr++) {
3637     GstMatroskaTrackContext *context;
3638
3639     context = g_ptr_array_index (demux->common.src, stream_nr);
3640
3641     GST_LOG_OBJECT (demux,
3642         "Checking for resync on stream %d (%" GST_TIME_FORMAT ")", stream_nr,
3643         GST_TIME_ARGS (context->pos));
3644
3645     /* Only send gap events on non-subtitle streams if lagging way behind.
3646      * The 0.5 second threshold for subtitle streams is also quite random. */
3647     if (context->type == GST_MATROSKA_TRACK_TYPE_SUBTITLE)
3648       gap_threshold = GST_SECOND / 2;
3649     else
3650       gap_threshold = 3 * GST_SECOND;
3651
3652     /* Lag need only be considered if we have advanced into requested segment */
3653     if (GST_CLOCK_TIME_IS_VALID (context->pos) &&
3654         GST_CLOCK_TIME_IS_VALID (demux->common.segment.position) &&
3655         demux->common.segment.position > demux->common.segment.start &&
3656         context->pos + gap_threshold < demux->common.segment.position) {
3657
3658       GstEvent *event;
3659       guint64 start = context->pos;
3660       guint64 stop = demux->common.segment.position - gap_threshold;
3661
3662       GST_DEBUG_OBJECT (demux,
3663           "Synchronizing stream %d with other by advancing time from %"
3664           GST_TIME_FORMAT " to %" GST_TIME_FORMAT, stream_nr,
3665           GST_TIME_ARGS (start), GST_TIME_ARGS (stop));
3666
3667       context->pos = stop;
3668
3669       event = gst_event_new_gap (start, stop - start);
3670       GST_OBJECT_UNLOCK (demux);
3671       gst_pad_push_event (context->pad, event);
3672       GST_OBJECT_LOCK (demux);
3673     }
3674   }
3675
3676   GST_OBJECT_UNLOCK (demux);
3677 }
3678
3679 static GstFlowReturn
3680 gst_matroska_demux_push_stream_headers (GstMatroskaDemux * demux,
3681     GstMatroskaTrackContext * stream)
3682 {
3683   GstFlowReturn ret = GST_FLOW_OK;
3684   gint i, num;
3685
3686   num = gst_buffer_list_length (stream->stream_headers);
3687   for (i = 0; i < num; ++i) {
3688     GstBuffer *buf;
3689
3690     buf = gst_buffer_list_get (stream->stream_headers, i);
3691     buf = gst_buffer_copy (buf);
3692
3693     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_HEADER);
3694
3695     if (stream->set_discont) {
3696       GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
3697       stream->set_discont = FALSE;
3698     } else {
3699       GST_BUFFER_FLAG_UNSET (buf, GST_BUFFER_FLAG_DISCONT);
3700     }
3701
3702     /* push out all headers in one go and use last flow return */
3703     ret = gst_pad_push (stream->pad, buf);
3704   }
3705
3706   /* don't need these any  longer */
3707   gst_buffer_list_unref (stream->stream_headers);
3708   stream->stream_headers = NULL;
3709
3710   /* combine flows */
3711   ret = gst_flow_combiner_update_flow (demux->flowcombiner, ret);
3712
3713   return ret;
3714 }
3715
3716 static void
3717 gst_matroska_demux_push_dvd_clut_change_event (GstMatroskaDemux * demux,
3718     GstMatroskaTrackContext * stream)
3719 {
3720   gchar *buf, *start;
3721
3722   g_assert (!strcmp (stream->codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_VOBSUB));
3723
3724   if (!stream->codec_priv)
3725     return;
3726
3727   /* ideally, VobSub private data should be parsed and stored more convenient
3728    * elsewhere, but for now, only interested in a small part */
3729
3730   /* make sure we have terminating 0 */
3731   buf = g_strndup (stream->codec_priv, stream->codec_priv_size);
3732
3733   /* just locate and parse palette part */
3734   start = strstr (buf, "palette:");
3735   if (start) {
3736     gint i;
3737     guint32 clut[16];
3738     guint32 col;
3739     guint8 r, g, b, y, u, v;
3740
3741     start += 8;
3742     while (g_ascii_isspace (*start))
3743       start++;
3744     for (i = 0; i < 16; i++) {
3745       if (sscanf (start, "%06x", &col) != 1)
3746         break;
3747       start += 6;
3748       while ((*start == ',') || g_ascii_isspace (*start))
3749         start++;
3750       /* sigh, need to convert this from vobsub pseudo-RGB to YUV */
3751       r = (col >> 16) & 0xff;
3752       g = (col >> 8) & 0xff;
3753       b = col & 0xff;
3754       y = CLAMP ((0.1494 * r + 0.6061 * g + 0.2445 * b) * 219 / 255 + 16, 0,
3755           255);
3756       u = CLAMP (0.6066 * r - 0.4322 * g - 0.1744 * b + 128, 0, 255);
3757       v = CLAMP (-0.08435 * r - 0.3422 * g + 0.4266 * b + 128, 0, 255);
3758       clut[i] = (y << 16) | (u << 8) | v;
3759     }
3760
3761     /* got them all without problems; build and send event */
3762     if (i == 16) {
3763       GstStructure *s;
3764
3765       s = gst_structure_new ("application/x-gst-dvd", "event", G_TYPE_STRING,
3766           "dvd-spu-clut-change", "clut00", G_TYPE_INT, clut[0], "clut01",
3767           G_TYPE_INT, clut[1], "clut02", G_TYPE_INT, clut[2], "clut03",
3768           G_TYPE_INT, clut[3], "clut04", G_TYPE_INT, clut[4], "clut05",
3769           G_TYPE_INT, clut[5], "clut06", G_TYPE_INT, clut[6], "clut07",
3770           G_TYPE_INT, clut[7], "clut08", G_TYPE_INT, clut[8], "clut09",
3771           G_TYPE_INT, clut[9], "clut10", G_TYPE_INT, clut[10], "clut11",
3772           G_TYPE_INT, clut[11], "clut12", G_TYPE_INT, clut[12], "clut13",
3773           G_TYPE_INT, clut[13], "clut14", G_TYPE_INT, clut[14], "clut15",
3774           G_TYPE_INT, clut[15], NULL);
3775
3776       gst_pad_push_event (stream->pad,
3777           gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM_STICKY, s));
3778     }
3779   }
3780   g_free (buf);
3781 }
3782
3783 static void
3784 gst_matroska_demux_push_codec_data_all (GstMatroskaDemux * demux)
3785 {
3786   gint stream_nr;
3787
3788   g_assert (demux->common.num_streams == demux->common.src->len);
3789   for (stream_nr = 0; stream_nr < demux->common.src->len; stream_nr++) {
3790     GstMatroskaTrackContext *stream;
3791
3792     stream = g_ptr_array_index (demux->common.src, stream_nr);
3793
3794     if (stream->send_stream_headers) {
3795       if (stream->stream_headers != NULL) {
3796         gst_matroska_demux_push_stream_headers (demux, stream);
3797       } else {
3798         /* FIXME: perhaps we can just disable and skip this stream then */
3799         GST_ELEMENT_ERROR (demux, STREAM, DECODE, (NULL),
3800             ("Failed to extract stream headers from codec private data"));
3801       }
3802       stream->send_stream_headers = FALSE;
3803     }
3804
3805     if (stream->send_dvd_event) {
3806       gst_matroska_demux_push_dvd_clut_change_event (demux, stream);
3807       /* FIXME: should we send this event again after (flushing) seek ? */
3808       stream->send_dvd_event = FALSE;
3809     }
3810   }
3811
3812 }
3813
3814 static GstFlowReturn
3815 gst_matroska_demux_add_mpeg_seq_header (GstElement * element,
3816     GstMatroskaTrackContext * stream, GstBuffer ** buf)
3817 {
3818   guint8 *seq_header;
3819   guint seq_header_len;
3820   guint32 header, tmp;
3821
3822   if (stream->codec_state) {
3823     seq_header = stream->codec_state;
3824     seq_header_len = stream->codec_state_size;
3825   } else if (stream->codec_priv) {
3826     seq_header = stream->codec_priv;
3827     seq_header_len = stream->codec_priv_size;
3828   } else {
3829     return GST_FLOW_OK;
3830   }
3831
3832   /* Sequence header only needed for keyframes */
3833   if (GST_BUFFER_FLAG_IS_SET (*buf, GST_BUFFER_FLAG_DELTA_UNIT))
3834     return GST_FLOW_OK;
3835
3836   if (gst_buffer_get_size (*buf) < 4)
3837     return GST_FLOW_OK;
3838
3839   gst_buffer_extract (*buf, 0, &tmp, sizeof (guint32));
3840   header = GUINT32_FROM_BE (tmp);
3841
3842   /* Sequence start code, if not found prepend */
3843   if (header != 0x000001b3) {
3844     GstBuffer *newbuf;
3845
3846     GST_DEBUG_OBJECT (element, "Prepending MPEG sequence header");
3847
3848     newbuf = gst_buffer_new_memdup (seq_header, seq_header_len);
3849
3850     gst_buffer_copy_into (newbuf, *buf, GST_BUFFER_COPY_TIMESTAMPS |
3851         GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_MEMORY, 0,
3852         gst_buffer_get_size (*buf));
3853
3854     gst_buffer_unref (*buf);
3855     *buf = newbuf;
3856   }
3857
3858   return GST_FLOW_OK;
3859 }
3860
3861 static GstFlowReturn
3862 gst_matroska_demux_add_wvpk_header (GstElement * element,
3863     GstMatroskaTrackContext * stream, GstBuffer ** buf)
3864 {
3865   GstMatroskaTrackAudioContext *audiocontext =
3866       (GstMatroskaTrackAudioContext *) stream;
3867   GstBuffer *newbuf = NULL;
3868   GstMapInfo map, outmap;
3869   guint8 *buf_data, *data;
3870   Wavpack4Header wvh;
3871
3872   wvh.ck_id[0] = 'w';
3873   wvh.ck_id[1] = 'v';
3874   wvh.ck_id[2] = 'p';
3875   wvh.ck_id[3] = 'k';
3876
3877   wvh.version = GST_READ_UINT16_LE (stream->codec_priv);
3878   wvh.track_no = 0;
3879   wvh.index_no = 0;
3880   wvh.total_samples = -1;
3881   wvh.block_index = audiocontext->wvpk_block_index;
3882
3883   if (audiocontext->channels <= 2) {
3884     guint32 block_samples, tmp;
3885     gsize size = gst_buffer_get_size (*buf);
3886
3887     if (size < 4) {
3888       GST_ERROR_OBJECT (element, "Too small wavpack buffer");
3889       gst_buffer_unmap (*buf, &map);
3890       return GST_FLOW_ERROR;
3891     }
3892
3893     gst_buffer_extract (*buf, 0, &tmp, sizeof (guint32));
3894     block_samples = GUINT32_FROM_LE (tmp);
3895     /* we need to reconstruct the header of the wavpack block */
3896
3897     /* -20 because ck_size is the size of the wavpack block -8
3898      * and lace_size is the size of the wavpack block + 12
3899      * (the three guint32 of the header that already are in the buffer) */
3900     wvh.ck_size = size + WAVPACK4_HEADER_SIZE - 20;
3901
3902     /* block_samples, flags and crc are already in the buffer */
3903     newbuf = gst_buffer_new_allocate (NULL, WAVPACK4_HEADER_SIZE - 12, NULL);
3904
3905     gst_buffer_map (newbuf, &outmap, GST_MAP_WRITE);
3906     data = outmap.data;
3907     data[0] = 'w';
3908     data[1] = 'v';
3909     data[2] = 'p';
3910     data[3] = 'k';
3911     GST_WRITE_UINT32_LE (data + 4, wvh.ck_size);
3912     GST_WRITE_UINT16_LE (data + 8, wvh.version);
3913     GST_WRITE_UINT8 (data + 10, wvh.track_no);
3914     GST_WRITE_UINT8 (data + 11, wvh.index_no);
3915     GST_WRITE_UINT32_LE (data + 12, wvh.total_samples);
3916     GST_WRITE_UINT32_LE (data + 16, wvh.block_index);
3917     gst_buffer_unmap (newbuf, &outmap);
3918
3919     /* Append data from buf: */
3920     gst_buffer_copy_into (newbuf, *buf, GST_BUFFER_COPY_TIMESTAMPS |
3921         GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_MEMORY, 0, size);
3922
3923     gst_buffer_unref (*buf);
3924     *buf = newbuf;
3925     audiocontext->wvpk_block_index += block_samples;
3926   } else {
3927     guint8 *outdata = NULL;
3928     gsize buf_size, size;
3929     guint32 block_samples, flags, crc, blocksize;
3930     GstAdapter *adapter;
3931
3932     adapter = gst_adapter_new ();
3933
3934     gst_buffer_map (*buf, &map, GST_MAP_READ);
3935     buf_data = map.data;
3936     buf_size = map.size;
3937
3938     if (buf_size < 4) {
3939       GST_ERROR_OBJECT (element, "Too small wavpack buffer");
3940       gst_buffer_unmap (*buf, &map);
3941       g_object_unref (adapter);
3942       return GST_FLOW_ERROR;
3943     }
3944
3945     data = buf_data;
3946     size = buf_size;
3947
3948     block_samples = GST_READ_UINT32_LE (data);
3949     data += 4;
3950     size -= 4;
3951
3952     while (size > 12) {
3953       flags = GST_READ_UINT32_LE (data);
3954       data += 4;
3955       size -= 4;
3956       crc = GST_READ_UINT32_LE (data);
3957       data += 4;
3958       size -= 4;
3959       blocksize = GST_READ_UINT32_LE (data);
3960       data += 4;
3961       size -= 4;
3962
3963       if (blocksize == 0 || size < blocksize) {
3964         GST_ERROR_OBJECT (element, "Too small wavpack buffer");
3965         gst_buffer_unmap (*buf, &map);
3966         g_object_unref (adapter);
3967         return GST_FLOW_ERROR;
3968       }
3969
3970       g_assert (newbuf == NULL);
3971
3972       newbuf =
3973           gst_buffer_new_allocate (NULL, WAVPACK4_HEADER_SIZE + blocksize,
3974           NULL);
3975       gst_buffer_map (newbuf, &outmap, GST_MAP_WRITE);
3976       outdata = outmap.data;
3977
3978       outdata[0] = 'w';
3979       outdata[1] = 'v';
3980       outdata[2] = 'p';
3981       outdata[3] = 'k';
3982       outdata += 4;
3983
3984       GST_WRITE_UINT32_LE (outdata, blocksize + WAVPACK4_HEADER_SIZE - 8);
3985       GST_WRITE_UINT16_LE (outdata + 4, wvh.version);
3986       GST_WRITE_UINT8 (outdata + 6, wvh.track_no);
3987       GST_WRITE_UINT8 (outdata + 7, wvh.index_no);
3988       GST_WRITE_UINT32_LE (outdata + 8, wvh.total_samples);
3989       GST_WRITE_UINT32_LE (outdata + 12, wvh.block_index);
3990       GST_WRITE_UINT32_LE (outdata + 16, block_samples);
3991       GST_WRITE_UINT32_LE (outdata + 20, flags);
3992       GST_WRITE_UINT32_LE (outdata + 24, crc);
3993       outdata += 28;
3994
3995       memcpy (outdata, data, blocksize);
3996
3997       gst_buffer_unmap (newbuf, &outmap);
3998       gst_adapter_push (adapter, newbuf);
3999       newbuf = NULL;
4000
4001       data += blocksize;
4002       size -= blocksize;
4003     }
4004     gst_buffer_unmap (*buf, &map);
4005
4006     newbuf = gst_adapter_take_buffer (adapter, gst_adapter_available (adapter));
4007     g_object_unref (adapter);
4008
4009     gst_buffer_copy_into (newbuf, *buf,
4010         GST_BUFFER_COPY_TIMESTAMPS | GST_BUFFER_COPY_FLAGS, 0, -1);
4011     gst_buffer_unref (*buf);
4012     *buf = newbuf;
4013
4014     audiocontext->wvpk_block_index += block_samples;
4015   }
4016
4017   return GST_FLOW_OK;
4018 }
4019
4020 static GstFlowReturn
4021 gst_matroska_demux_add_prores_header (GstElement * element,
4022     GstMatroskaTrackContext * stream, GstBuffer ** buf)
4023 {
4024   GstBuffer *newbuf = gst_buffer_new_allocate (NULL, 8, NULL);
4025   GstMapInfo map;
4026   guint32 frame_size;
4027
4028   if (!gst_buffer_map (newbuf, &map, GST_MAP_WRITE)) {
4029     GST_ERROR ("Failed to map newly allocated buffer");
4030     return GST_FLOW_ERROR;
4031   }
4032
4033   frame_size = gst_buffer_get_size (*buf);
4034
4035   GST_WRITE_UINT32_BE (map.data, frame_size);
4036   map.data[4] = 'i';
4037   map.data[5] = 'c';
4038   map.data[6] = 'p';
4039   map.data[7] = 'f';
4040
4041   gst_buffer_unmap (newbuf, &map);
4042   *buf = gst_buffer_append (newbuf, *buf);
4043
4044   return GST_FLOW_OK;
4045 }
4046
4047 /* @text must be null-terminated */
4048 static gboolean
4049 gst_matroska_demux_subtitle_chunk_has_tag (GstElement * element,
4050     const gchar * text)
4051 {
4052   gchar *tag;
4053
4054   g_return_val_if_fail (text != NULL, FALSE);
4055
4056   /* yes, this might all lead to false positives ... */
4057   tag = (gchar *) text;
4058   while ((tag = strchr (tag, '<'))) {
4059     tag++;
4060     if (*tag != '\0' && *(tag + 1) == '>') {
4061       /* some common convenience ones */
4062       /* maybe any character will do here ? */
4063       switch (*tag) {
4064         case 'b':
4065         case 'i':
4066         case 'u':
4067         case 's':
4068           return TRUE;
4069         default:
4070           return FALSE;
4071       }
4072     }
4073   }
4074
4075   if (strstr (text, "<span"))
4076     return TRUE;
4077
4078   return FALSE;
4079 }
4080
4081 static GstFlowReturn
4082 gst_matroska_demux_check_subtitle_buffer (GstElement * element,
4083     GstMatroskaTrackContext * stream, GstBuffer ** buf)
4084 {
4085   GstMatroskaTrackSubtitleContext *sub_stream;
4086   const gchar *encoding;
4087   GError *err = NULL;
4088   GstBuffer *newbuf;
4089   gchar *utf8;
4090   GstMapInfo map;
4091   gboolean needs_unmap = TRUE;
4092
4093   sub_stream = (GstMatroskaTrackSubtitleContext *) stream;
4094
4095   if (!gst_buffer_get_size (*buf) || !gst_buffer_map (*buf, &map, GST_MAP_READ))
4096     return GST_FLOW_OK;
4097
4098   /* The subtitle buffer we push out should not include a NUL terminator as
4099    * part of the data. */
4100   if (map.data[map.size - 1] == '\0') {
4101     gst_buffer_set_size (*buf, map.size - 1);
4102     gst_buffer_unmap (*buf, &map);
4103     gst_buffer_map (*buf, &map, GST_MAP_READ);
4104   }
4105
4106   if (!sub_stream->invalid_utf8) {
4107     if (g_utf8_validate ((gchar *) map.data, map.size, NULL)) {
4108       goto next;
4109     }
4110     GST_WARNING_OBJECT (element, "subtitle stream %" G_GUINT64_FORMAT
4111         " is not valid UTF-8, this is broken according to the matroska"
4112         " specification", stream->num);
4113     sub_stream->invalid_utf8 = TRUE;
4114   }
4115
4116   /* file with broken non-UTF8 subtitle, do the best we can do to fix it */
4117   encoding = g_getenv ("GST_SUBTITLE_ENCODING");
4118   if (encoding == NULL || *encoding == '\0') {
4119     /* if local encoding is UTF-8 and no encoding specified
4120      * via the environment variable, assume ISO-8859-15 */
4121     if (g_get_charset (&encoding)) {
4122       encoding = "ISO-8859-15";
4123     }
4124   }
4125
4126   utf8 =
4127       g_convert_with_fallback ((gchar *) map.data, map.size, "UTF-8", encoding,
4128       (char *) "*", NULL, NULL, &err);
4129
4130   if (err) {
4131     GST_LOG_OBJECT (element, "could not convert string from '%s' to UTF-8: %s",
4132         encoding, err->message);
4133     g_error_free (err);
4134     g_free (utf8);
4135
4136     /* invalid input encoding, fall back to ISO-8859-15 (always succeeds) */
4137     encoding = "ISO-8859-15";
4138     utf8 =
4139         g_convert_with_fallback ((gchar *) map.data, map.size, "UTF-8",
4140         encoding, (char *) "*", NULL, NULL, NULL);
4141   }
4142
4143   GST_LOG_OBJECT (element, "converted subtitle text from %s to UTF-8 %s",
4144       encoding, (err) ? "(using ISO-8859-15 as fallback)" : "");
4145
4146   if (utf8 == NULL)
4147     utf8 = g_strdup ("invalid subtitle");
4148
4149   newbuf = gst_buffer_new_wrapped (utf8, strlen (utf8));
4150   gst_buffer_unmap (*buf, &map);
4151   gst_buffer_copy_into (newbuf, *buf,
4152       GST_BUFFER_COPY_TIMESTAMPS | GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_META,
4153       0, -1);
4154   gst_buffer_unref (*buf);
4155
4156   *buf = newbuf;
4157   gst_buffer_map (*buf, &map, GST_MAP_READ);
4158
4159 next:
4160
4161   if (sub_stream->check_markup) {
4162     /* caps claim markup text, so we need to escape text,
4163      * except if text is already markup and then needs no further escaping */
4164     sub_stream->seen_markup_tag = sub_stream->seen_markup_tag ||
4165         gst_matroska_demux_subtitle_chunk_has_tag (element, (gchar *) map.data);
4166
4167     if (!sub_stream->seen_markup_tag) {
4168       utf8 = g_markup_escape_text ((gchar *) map.data, map.size);
4169
4170       newbuf = gst_buffer_new_wrapped (utf8, strlen (utf8));
4171       gst_buffer_unmap (*buf, &map);
4172       gst_buffer_copy_into (newbuf, *buf,
4173           GST_BUFFER_COPY_TIMESTAMPS | GST_BUFFER_COPY_FLAGS |
4174           GST_BUFFER_COPY_META, 0, -1);
4175       gst_buffer_unref (*buf);
4176
4177       *buf = newbuf;
4178       needs_unmap = FALSE;
4179     }
4180   }
4181
4182   if (needs_unmap)
4183     gst_buffer_unmap (*buf, &map);
4184
4185   return GST_FLOW_OK;
4186 }
4187
4188 static GstFlowReturn
4189 gst_matroska_demux_check_aac (GstElement * element,
4190     GstMatroskaTrackContext * stream, GstBuffer ** buf)
4191 {
4192   guint8 data[2];
4193   guint size;
4194
4195   gst_buffer_extract (*buf, 0, data, 2);
4196   size = gst_buffer_get_size (*buf);
4197
4198   if (size > 2 && data[0] == 0xff && (data[1] >> 4 == 0x0f)) {
4199     GstStructure *s;
4200
4201     /* tss, ADTS data, remove codec_data
4202      * still assume it is at least parsed */
4203     stream->caps = gst_caps_make_writable (stream->caps);
4204     s = gst_caps_get_structure (stream->caps, 0);
4205     g_assert (s);
4206     gst_structure_remove_field (s, "codec_data");
4207     gst_pad_set_caps (stream->pad, stream->caps);
4208     GST_DEBUG_OBJECT (element, "ADTS AAC audio data; removing codec-data, "
4209         "new caps: %" GST_PTR_FORMAT, stream->caps);
4210   }
4211
4212   /* disable subsequent checking */
4213   stream->postprocess_frame = NULL;
4214
4215   return GST_FLOW_OK;
4216 }
4217
4218 static GstBuffer *
4219 gst_matroska_demux_align_buffer (GstMatroskaDemux * demux,
4220     GstBuffer * buffer, gsize alignment)
4221 {
4222   GstMapInfo map;
4223
4224   gst_buffer_map (buffer, &map, GST_MAP_READ);
4225
4226   if (map.size < sizeof (guintptr)) {
4227     gst_buffer_unmap (buffer, &map);
4228     return buffer;
4229   }
4230
4231   if (((guintptr) map.data) & (alignment - 1)) {
4232     GstBuffer *new_buffer;
4233     GstAllocationParams params = { 0, alignment - 1, 0, 0, };
4234
4235     new_buffer = gst_buffer_new_allocate (NULL,
4236         gst_buffer_get_size (buffer), &params);
4237
4238     /* Copy data "by hand", so ensure alignment is kept: */
4239     gst_buffer_fill (new_buffer, 0, map.data, map.size);
4240
4241     gst_buffer_copy_into (new_buffer, buffer, GST_BUFFER_COPY_METADATA, 0, -1);
4242     GST_DEBUG_OBJECT (demux,
4243         "We want output aligned on %" G_GSIZE_FORMAT ", reallocated",
4244         alignment);
4245
4246     gst_buffer_unmap (buffer, &map);
4247     gst_buffer_unref (buffer);
4248
4249     return new_buffer;
4250   }
4251
4252   gst_buffer_unmap (buffer, &map);
4253   return buffer;
4254 }
4255
4256 typedef struct
4257 {
4258   guint8 *data;
4259   gsize size;
4260   guint64 id;
4261 } BlockAddition;
4262
4263 static GstFlowReturn
4264 gst_matroska_demux_parse_blockmore (GstMatroskaDemux * demux,
4265     GstEbmlRead * ebml, GQueue * additions)
4266 {
4267   GstFlowReturn ret;
4268   guint32 id;
4269   guint64 block_id = 1;
4270   guint64 datalen = 0;
4271   guint8 *data = NULL;
4272
4273   ret = gst_ebml_read_master (ebml, &id);       /* GST_MATROSKA_ID_BLOCKMORE */
4274   if (ret != GST_FLOW_OK)
4275     return ret;
4276
4277   /* read all BlockMore sub-entries */
4278   while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
4279
4280     if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
4281       break;
4282
4283     switch (id) {
4284       case GST_MATROSKA_ID_BLOCKADDID:
4285         ret = gst_ebml_read_uint (ebml, &id, &block_id);
4286         if (block_id == 0)
4287           block_id = 1;
4288         break;
4289       case GST_MATROSKA_ID_BLOCKADDITIONAL:
4290         g_free (data);
4291         data = NULL;
4292         datalen = 0;
4293         ret = gst_ebml_read_binary (ebml, &id, &data, &datalen);
4294         break;
4295       default:
4296         ret = gst_matroska_read_common_parse_skip (&demux->common, ebml,
4297             "BlockMore", id);
4298         break;
4299     }
4300   }
4301
4302   if (data != NULL && datalen > 0) {
4303     BlockAddition *blockadd = g_new (BlockAddition, 1);
4304
4305     GST_LOG_OBJECT (demux, "BlockAddition %" G_GUINT64_FORMAT ": "
4306         "%" G_GUINT64_FORMAT " bytes", block_id, datalen);
4307     GST_MEMDUMP_OBJECT (demux, "BlockAdditional", data, datalen);
4308     blockadd->data = data;
4309     blockadd->size = datalen;
4310     blockadd->id = block_id;
4311     g_queue_push_tail (additions, blockadd);
4312     GST_LOG_OBJECT (demux, "now %d pending block additions", additions->length);
4313   }
4314
4315   return ret;
4316 }
4317
4318 /* BLOCKADDITIONS
4319  *  BLOCKMORE
4320  *    BLOCKADDID
4321  *    BLOCKADDITIONAL
4322  */
4323 static GstFlowReturn
4324 gst_matroska_demux_parse_blockadditions (GstMatroskaDemux * demux,
4325     GstEbmlRead * ebml, GQueue * additions)
4326 {
4327   GstFlowReturn ret;
4328   guint32 id;
4329
4330   ret = gst_ebml_read_master (ebml, &id);       /* GST_MATROSKA_ID_BLOCKADDITIONS */
4331   if (ret != GST_FLOW_OK)
4332     return ret;
4333
4334   /* read all BlockMore sub-entries */
4335   while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
4336
4337     if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
4338       break;
4339
4340     if (id == GST_MATROSKA_ID_BLOCKMORE) {
4341       DEBUG_ELEMENT_START (demux, ebml, "BlockMore");
4342       ret = gst_matroska_demux_parse_blockmore (demux, ebml, additions);
4343       DEBUG_ELEMENT_STOP (demux, ebml, "BlockMore", ret);
4344       if (ret != GST_FLOW_OK)
4345         break;
4346     } else {
4347       GST_WARNING_OBJECT (demux, "Expected BlockMore, got %x", id);
4348     }
4349   }
4350
4351   return ret;
4352 }
4353
4354 static GstFlowReturn
4355 gst_matroska_demux_parse_blockgroup_or_simpleblock (GstMatroskaDemux * demux,
4356     GstEbmlRead * ebml, guint64 cluster_time, guint64 cluster_offset,
4357     gboolean is_simpleblock)
4358 {
4359   GstMatroskaTrackContext *stream = NULL;
4360   GstFlowReturn ret = GST_FLOW_OK;
4361   gboolean readblock = FALSE;
4362   guint32 id;
4363   guint64 block_duration = -1;
4364   gint64 block_discardpadding = 0;
4365   GstBuffer *buf = NULL;
4366   GstMapInfo map;
4367   gint stream_num = -1, n, laces = 0;
4368   guint size = 0;
4369   gint *lace_size = NULL;
4370   gint64 time = 0;
4371   gint flags = 0;
4372   gint64 referenceblock = 0;
4373   gint64 offset;
4374   GstClockTime buffer_timestamp;
4375   GQueue additions = G_QUEUE_INIT;
4376
4377   offset = gst_ebml_read_get_offset (ebml);
4378
4379   while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
4380     if (!is_simpleblock) {
4381       if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK) {
4382         goto data_error;
4383       }
4384     } else {
4385       id = GST_MATROSKA_ID_SIMPLEBLOCK;
4386     }
4387
4388     switch (id) {
4389         /* one block inside the group. Note, block parsing is one
4390          * of the harder things, so this code is a bit complicated.
4391          * See http://www.matroska.org/ for documentation. */
4392       case GST_MATROSKA_ID_SIMPLEBLOCK:
4393       case GST_MATROSKA_ID_BLOCK:
4394       {
4395         guint64 num;
4396         guint8 *data;
4397
4398         if (buf) {
4399           gst_buffer_unmap (buf, &map);
4400           gst_buffer_unref (buf);
4401           buf = NULL;
4402         }
4403         if ((ret = gst_ebml_read_buffer (ebml, &id, &buf)) != GST_FLOW_OK)
4404           break;
4405
4406         gst_buffer_map (buf, &map, GST_MAP_READ);
4407         data = map.data;
4408         size = map.size;
4409
4410         /* first byte(s): blocknum */
4411         if ((n = gst_matroska_ebmlnum_uint (data, size, &num)) < 0)
4412           goto data_error;
4413         data += n;
4414         size -= n;
4415
4416         /* fetch stream from num */
4417         stream_num = gst_matroska_read_common_stream_from_num (&demux->common,
4418             num);
4419         if (G_UNLIKELY (size < 3)) {
4420           GST_WARNING_OBJECT (demux, "Invalid size %u", size);
4421           /* non-fatal, try next block(group) */
4422           ret = GST_FLOW_OK;
4423           goto done;
4424         } else if (G_UNLIKELY (stream_num < 0 ||
4425                 stream_num >= demux->common.num_streams)) {
4426           /* let's not give up on a stray invalid track number */
4427           GST_WARNING_OBJECT (demux,
4428               "Invalid stream %d for track number %" G_GUINT64_FORMAT
4429               "; ignoring block", stream_num, num);
4430           goto done;
4431         }
4432
4433         stream = g_ptr_array_index (demux->common.src, stream_num);
4434
4435         /* time (relative to cluster time) */
4436         time = ((gint16) GST_READ_UINT16_BE (data));
4437         data += 2;
4438         size -= 2;
4439         flags = GST_READ_UINT8 (data);
4440         data += 1;
4441         size -= 1;
4442
4443         GST_LOG_OBJECT (demux, "time %" G_GUINT64_FORMAT ", flags %d", time,
4444             flags);
4445
4446         switch ((flags & 0x06) >> 1) {
4447           case 0x0:            /* no lacing */
4448             laces = 1;
4449             lace_size = g_new (gint, 1);
4450             lace_size[0] = size;
4451             break;
4452
4453           case 0x1:            /* xiph lacing */
4454           case 0x2:            /* fixed-size lacing */
4455           case 0x3:            /* EBML lacing */
4456             if (size == 0)
4457               goto invalid_lacing;
4458             laces = GST_READ_UINT8 (data) + 1;
4459             data += 1;
4460             size -= 1;
4461             lace_size = g_new0 (gint, laces);
4462
4463             switch ((flags & 0x06) >> 1) {
4464               case 0x1:        /* xiph lacing */  {
4465                 guint temp, total = 0;
4466
4467                 for (n = 0; ret == GST_FLOW_OK && n < laces - 1; n++) {
4468                   while (1) {
4469                     if (size == 0)
4470                       goto invalid_lacing;
4471                     temp = GST_READ_UINT8 (data);
4472                     lace_size[n] += temp;
4473                     data += 1;
4474                     size -= 1;
4475                     if (temp != 0xff)
4476                       break;
4477                   }
4478                   total += lace_size[n];
4479                 }
4480                 lace_size[n] = size - total;
4481                 break;
4482               }
4483
4484               case 0x2:        /* fixed-size lacing */
4485                 for (n = 0; n < laces; n++)
4486                   lace_size[n] = size / laces;
4487                 break;
4488
4489               case 0x3:        /* EBML lacing */  {
4490                 guint total;
4491
4492                 if ((n = gst_matroska_ebmlnum_uint (data, size, &num)) < 0)
4493                   goto data_error;
4494                 data += n;
4495                 size -= n;
4496                 total = lace_size[0] = num;
4497                 for (n = 1; ret == GST_FLOW_OK && n < laces - 1; n++) {
4498                   gint64 snum;
4499                   gint r;
4500
4501                   if ((r = gst_matroska_ebmlnum_sint (data, size, &snum)) < 0)
4502                     goto data_error;
4503                   data += r;
4504                   size -= r;
4505                   lace_size[n] = lace_size[n - 1] + snum;
4506                   total += lace_size[n];
4507                 }
4508                 if (n < laces)
4509                   lace_size[n] = size - total;
4510                 break;
4511               }
4512             }
4513             break;
4514         }
4515
4516         if (ret != GST_FLOW_OK)
4517           break;
4518
4519         readblock = TRUE;
4520         break;
4521       }
4522
4523       case GST_MATROSKA_ID_BLOCKADDITIONS:
4524       {
4525         DEBUG_ELEMENT_START (demux, ebml, "BlockAdditions");
4526         ret = gst_matroska_demux_parse_blockadditions (demux, ebml, &additions);
4527         DEBUG_ELEMENT_STOP (demux, ebml, "BlockAdditions", ret);
4528         break;
4529       }
4530
4531       case GST_MATROSKA_ID_BLOCKDURATION:{
4532         ret = gst_ebml_read_uint (ebml, &id, &block_duration);
4533         GST_DEBUG_OBJECT (demux, "BlockDuration: %" G_GUINT64_FORMAT,
4534             block_duration);
4535         break;
4536       }
4537
4538       case GST_MATROSKA_ID_DISCARDPADDING:{
4539         ret = gst_ebml_read_sint (ebml, &id, &block_discardpadding);
4540         GST_DEBUG_OBJECT (demux, "DiscardPadding: %" GST_STIME_FORMAT,
4541             GST_STIME_ARGS (block_discardpadding));
4542         break;
4543       }
4544
4545       case GST_MATROSKA_ID_REFERENCEBLOCK:{
4546         ret = gst_ebml_read_sint (ebml, &id, &referenceblock);
4547         GST_DEBUG_OBJECT (demux, "ReferenceBlock: %" G_GINT64_FORMAT,
4548             referenceblock);
4549         break;
4550       }
4551
4552       case GST_MATROSKA_ID_CODECSTATE:{
4553         guint8 *data;
4554         guint64 data_len = 0;
4555
4556         if ((ret =
4557                 gst_ebml_read_binary (ebml, &id, &data,
4558                     &data_len)) != GST_FLOW_OK)
4559           break;
4560
4561         if (G_UNLIKELY (stream == NULL)) {
4562           GST_WARNING_OBJECT (demux,
4563               "Unexpected CodecState subelement - ignoring");
4564           break;
4565         }
4566
4567         g_free (stream->codec_state);
4568         stream->codec_state = data;
4569         stream->codec_state_size = data_len;
4570
4571         /* Decode if necessary */
4572         if (stream->encodings && stream->encodings->len > 0
4573             && stream->codec_state && stream->codec_state_size > 0) {
4574           if (!gst_matroska_decode_data (stream->encodings,
4575                   &stream->codec_state, &stream->codec_state_size,
4576                   GST_MATROSKA_TRACK_ENCODING_SCOPE_CODEC_DATA, TRUE)) {
4577             GST_WARNING_OBJECT (demux, "Decoding codec state failed");
4578           }
4579         }
4580
4581         GST_DEBUG_OBJECT (demux, "CodecState of %" G_GSIZE_FORMAT " bytes",
4582             stream->codec_state_size);
4583         break;
4584       }
4585
4586       default:
4587         ret = gst_matroska_read_common_parse_skip (&demux->common, ebml,
4588             "BlockGroup", id);
4589         break;
4590
4591       case GST_MATROSKA_ID_BLOCKVIRTUAL:
4592       case GST_MATROSKA_ID_REFERENCEPRIORITY:
4593       case GST_MATROSKA_ID_REFERENCEVIRTUAL:
4594       case GST_MATROSKA_ID_SLICES:
4595         GST_DEBUG_OBJECT (demux,
4596             "Skipping BlockGroup subelement 0x%x - ignoring", id);
4597         ret = gst_ebml_read_skip (ebml);
4598         break;
4599     }
4600
4601     if (is_simpleblock)
4602       break;
4603   }
4604
4605   /* reading a number or so could have failed */
4606   if (ret != GST_FLOW_OK)
4607     goto data_error;
4608
4609   if (ret == GST_FLOW_OK && readblock) {
4610     gboolean invisible_frame = FALSE;
4611     gboolean delta_unit = FALSE;
4612     guint64 duration = 0;
4613     gint64 lace_time = 0;
4614     GstEvent *protect_event;
4615
4616     stream = g_ptr_array_index (demux->common.src, stream_num);
4617
4618     if (cluster_time != GST_CLOCK_TIME_NONE) {
4619       /* FIXME: What to do with negative timestamps? Give timestamp 0 or -1?
4620        * Drop unless the lace contains timestamp 0? */
4621       if (time < 0 && (-time) > cluster_time) {
4622         lace_time = 0;
4623       } else {
4624         if (stream->timecodescale == 1.0)
4625           lace_time = (cluster_time + time) * demux->common.time_scale;
4626         else
4627           lace_time =
4628               gst_util_guint64_to_gdouble ((cluster_time + time) *
4629               demux->common.time_scale) * stream->timecodescale;
4630       }
4631     } else {
4632       lace_time = GST_CLOCK_TIME_NONE;
4633     }
4634     /* Send the GST_PROTECTION event */
4635     while ((protect_event = g_queue_pop_head (&stream->protection_event_queue))) {
4636       GST_TRACE_OBJECT (demux, "pushing protection event for stream %d:%s",
4637           stream->index, GST_STR_NULL (stream->name));
4638       gst_pad_push_event (stream->pad, protect_event);
4639     }
4640
4641     /* need to refresh segment info ASAP */
4642     if (GST_CLOCK_TIME_IS_VALID (lace_time) && demux->need_segment) {
4643       GstSegment *segment = &demux->common.segment;
4644       guint64 clace_time;
4645       GstEvent *segment_event;
4646
4647       if (!GST_CLOCK_TIME_IS_VALID (demux->stream_start_time)) {
4648         demux->stream_start_time = lace_time;
4649         GST_DEBUG_OBJECT (demux,
4650             "Setting stream start time to %" GST_TIME_FORMAT,
4651             GST_TIME_ARGS (lace_time));
4652       }
4653       clace_time = MAX (lace_time, demux->stream_start_time);
4654       if (GST_CLOCK_TIME_IS_VALID (demux->common.segment.position) &&
4655           demux->common.segment.position != 0) {
4656         GST_DEBUG_OBJECT (demux,
4657             "using stored seek position %" GST_TIME_FORMAT,
4658             GST_TIME_ARGS (demux->common.segment.position));
4659         clace_time = demux->common.segment.position;
4660         segment->position = GST_CLOCK_TIME_NONE;
4661       }
4662       segment->start = clace_time;
4663       segment->stop = demux->common.segment.stop;
4664       segment->time = segment->start - demux->stream_start_time;
4665       segment->position = segment->start - demux->stream_start_time;
4666       GST_DEBUG_OBJECT (demux,
4667           "generated segment starting at %" GST_TIME_FORMAT ": %"
4668           GST_SEGMENT_FORMAT, GST_TIME_ARGS (lace_time), segment);
4669       /* now convey our segment notion downstream */
4670       segment_event = gst_event_new_segment (segment);
4671       if (demux->segment_seqnum)
4672         gst_event_set_seqnum (segment_event, demux->segment_seqnum);
4673       gst_matroska_demux_send_event (demux, segment_event);
4674       demux->need_segment = FALSE;
4675       demux->segment_seqnum = 0;
4676     }
4677
4678     /* send pending codec data headers for all streams,
4679      * before we perform sync across all streams */
4680     gst_matroska_demux_push_codec_data_all (demux);
4681
4682     if (block_duration != -1) {
4683       if (stream->timecodescale == 1.0)
4684         duration = gst_util_uint64_scale (block_duration,
4685             demux->common.time_scale, 1);
4686       else
4687         duration =
4688             gst_util_gdouble_to_guint64 (gst_util_guint64_to_gdouble
4689             (gst_util_uint64_scale (block_duration, demux->common.time_scale,
4690                     1)) * stream->timecodescale);
4691     } else if (stream->default_duration) {
4692       duration = stream->default_duration * laces;
4693     }
4694     /* else duration is diff between timecode of this and next block */
4695
4696     if (stream->type == GST_MATROSKA_TRACK_TYPE_VIDEO) {
4697       /* For SimpleBlock, look at the keyframe bit in flags. Otherwise,
4698          a ReferenceBlock implies that this is not a keyframe. In either
4699          case, it only makes sense for video streams. */
4700       if ((is_simpleblock && !(flags & 0x80)) || referenceblock) {
4701         delta_unit = TRUE;
4702         invisible_frame = ((flags & 0x08)) &&
4703             (!strcmp (stream->codec_id, GST_MATROSKA_CODEC_ID_VIDEO_VP8) ||
4704             !strcmp (stream->codec_id, GST_MATROSKA_CODEC_ID_VIDEO_VP9) ||
4705             !strcmp (stream->codec_id, GST_MATROSKA_CODEC_ID_VIDEO_AV1));
4706       }
4707
4708       /* If we're doing a keyframe-only trickmode, only push keyframes on video
4709        * streams */
4710       if (delta_unit
4711           && demux->common.segment.
4712           flags & GST_SEGMENT_FLAG_TRICKMODE_KEY_UNITS) {
4713         GST_LOG_OBJECT (demux, "Skipping non-keyframe on stream %d",
4714             stream->index);
4715         ret = GST_FLOW_OK;
4716         goto done;
4717       }
4718     }
4719
4720     for (n = 0; n < laces; n++) {
4721       GstBuffer *sub;
4722
4723       if (G_UNLIKELY (lace_size[n] > size)) {
4724         GST_WARNING_OBJECT (demux, "Invalid lace size");
4725         break;
4726       }
4727
4728       /* QoS for video track with an index. the assumption is that
4729          index entries point to keyframes, but if that is not true we
4730          will instead skip until the next keyframe. */
4731       if (GST_CLOCK_TIME_IS_VALID (lace_time) &&
4732           stream->type == GST_MATROSKA_TRACK_TYPE_VIDEO &&
4733           stream->index_table && demux->common.segment.rate > 0.0) {
4734         GstMatroskaTrackVideoContext *videocontext =
4735             (GstMatroskaTrackVideoContext *) stream;
4736         GstClockTime earliest_time;
4737         GstClockTime earliest_stream_time;
4738
4739         GST_OBJECT_LOCK (demux);
4740         earliest_time = videocontext->earliest_time;
4741         GST_OBJECT_UNLOCK (demux);
4742         earliest_stream_time =
4743             gst_segment_position_from_running_time (&demux->common.segment,
4744             GST_FORMAT_TIME, earliest_time);
4745
4746         if (GST_CLOCK_TIME_IS_VALID (lace_time) &&
4747             GST_CLOCK_TIME_IS_VALID (earliest_stream_time) &&
4748             lace_time <= earliest_stream_time) {
4749           /* find index entry (keyframe) <= earliest_stream_time */
4750           GstMatroskaIndex *entry =
4751               gst_util_array_binary_search (stream->index_table->data,
4752               stream->index_table->len, sizeof (GstMatroskaIndex),
4753               (GCompareDataFunc) gst_matroska_index_seek_find,
4754               GST_SEARCH_MODE_BEFORE, &earliest_stream_time, NULL);
4755
4756           /* if that entry (keyframe) is after the current the current
4757              buffer, we can skip pushing (and thus decoding) all
4758              buffers until that keyframe. */
4759           if (entry && GST_CLOCK_TIME_IS_VALID (entry->time) &&
4760               entry->time > lace_time) {
4761             GST_LOG_OBJECT (demux, "Skipping lace before late keyframe");
4762             stream->set_discont = TRUE;
4763             goto next_lace;
4764           }
4765         }
4766       }
4767
4768       sub = gst_buffer_copy_region (buf, GST_BUFFER_COPY_ALL,
4769           gst_buffer_get_size (buf) - size, lace_size[n]);
4770       GST_DEBUG_OBJECT (demux, "created subbuffer %p", sub);
4771
4772       if (delta_unit)
4773         GST_BUFFER_FLAG_SET (sub, GST_BUFFER_FLAG_DELTA_UNIT);
4774       else
4775         GST_BUFFER_FLAG_UNSET (sub, GST_BUFFER_FLAG_DELTA_UNIT);
4776
4777       if (invisible_frame)
4778         GST_BUFFER_FLAG_SET (sub, GST_BUFFER_FLAG_DECODE_ONLY);
4779
4780       if (stream->encodings != NULL && stream->encodings->len > 0)
4781         sub = gst_matroska_decode_buffer (stream, sub);
4782
4783       if (sub == NULL) {
4784         GST_WARNING_OBJECT (demux, "Decoding buffer failed");
4785         goto next_lace;
4786       }
4787
4788       if (!stream->dts_only) {
4789         GST_BUFFER_PTS (sub) = lace_time;
4790       } else {
4791         GST_BUFFER_DTS (sub) = lace_time;
4792         if (stream->intra_only)
4793           GST_BUFFER_PTS (sub) = lace_time;
4794       }
4795
4796       buffer_timestamp = gst_matroska_track_get_buffer_timestamp (stream, sub);
4797
4798       if (GST_CLOCK_TIME_IS_VALID (lace_time)) {
4799         GstClockTime last_stop_end;
4800
4801         /* Check if this stream is after segment stop,
4802          * but only terminate if we hit the next keyframe,
4803          * to make sure that all frames potentially inside the segment
4804          * are available to the decoder for decoding / reordering.*/
4805         if (!delta_unit && GST_CLOCK_TIME_IS_VALID (demux->common.segment.stop)
4806             && lace_time >= demux->common.segment.stop) {
4807           GST_DEBUG_OBJECT (demux,
4808               "Stream %d lace time: %" GST_TIME_FORMAT " after segment stop: %"
4809               GST_TIME_FORMAT, stream->index, GST_TIME_ARGS (lace_time),
4810               GST_TIME_ARGS (demux->common.segment.stop));
4811           gst_buffer_unref (sub);
4812           goto eos;
4813         }
4814         if (offset >= stream->to_offset
4815             || (GST_CLOCK_TIME_IS_VALID (demux->to_time)
4816                 && lace_time > demux->to_time)) {
4817           GST_DEBUG_OBJECT (demux, "Stream %d after playback section",
4818               stream->index);
4819           gst_buffer_unref (sub);
4820           goto eos;
4821         }
4822
4823         /* handle gaps, e.g. non-zero start-time, or an cue index entry
4824          * that landed us with timestamps not quite intended */
4825         GST_OBJECT_LOCK (demux);
4826         if (demux->max_gap_time &&
4827             GST_CLOCK_TIME_IS_VALID (demux->last_stop_end) &&
4828             demux->common.segment.rate > 0.0) {
4829           GstClockTimeDiff diff;
4830
4831           /* only send segments with increasing start times,
4832            * otherwise if these go back and forth downstream (sinks) increase
4833            * accumulated time and running_time */
4834           diff = GST_CLOCK_DIFF (demux->last_stop_end, lace_time);
4835           if (diff > 0 && diff > demux->max_gap_time
4836               && lace_time > demux->common.segment.start
4837               && (!GST_CLOCK_TIME_IS_VALID (demux->common.segment.stop)
4838                   || lace_time < demux->common.segment.stop)) {
4839             GstEvent *event;
4840             GST_DEBUG_OBJECT (demux,
4841                 "Gap of %" G_GINT64_FORMAT " ns detected in"
4842                 "stream %d (%" GST_TIME_FORMAT " -> %" GST_TIME_FORMAT "). "
4843                 "Sending updated SEGMENT events", diff,
4844                 stream->index, GST_TIME_ARGS (stream->pos),
4845                 GST_TIME_ARGS (lace_time));
4846
4847             event = gst_event_new_gap (demux->last_stop_end, diff);
4848             GST_OBJECT_UNLOCK (demux);
4849             gst_pad_push_event (stream->pad, event);
4850             GST_OBJECT_LOCK (demux);
4851           }
4852         }
4853
4854         if (!GST_CLOCK_TIME_IS_VALID (demux->common.segment.position)
4855             || demux->common.segment.position < lace_time) {
4856           demux->common.segment.position = lace_time;
4857         }
4858         GST_OBJECT_UNLOCK (demux);
4859
4860         last_stop_end = lace_time;
4861         if (duration) {
4862           GST_BUFFER_DURATION (sub) = duration / laces;
4863           last_stop_end += GST_BUFFER_DURATION (sub);
4864         }
4865
4866         if (!GST_CLOCK_TIME_IS_VALID (demux->last_stop_end) ||
4867             demux->last_stop_end < last_stop_end)
4868           demux->last_stop_end = last_stop_end;
4869
4870         GST_OBJECT_LOCK (demux);
4871         if (demux->common.segment.duration == -1 ||
4872             demux->stream_start_time + demux->common.segment.duration <
4873             last_stop_end) {
4874           demux->common.segment.duration =
4875               last_stop_end - demux->stream_start_time;
4876           GST_OBJECT_UNLOCK (demux);
4877           if (!demux->invalid_duration) {
4878             gst_element_post_message (GST_ELEMENT_CAST (demux),
4879                 gst_message_new_duration_changed (GST_OBJECT_CAST (demux)));
4880             demux->invalid_duration = TRUE;
4881           }
4882         } else {
4883           GST_OBJECT_UNLOCK (demux);
4884         }
4885       }
4886
4887       stream->pos = lace_time;
4888
4889       gst_matroska_demux_sync_streams (demux);
4890
4891       if (stream->set_discont) {
4892         GST_DEBUG_OBJECT (demux, "marking DISCONT");
4893         GST_BUFFER_FLAG_SET (sub, GST_BUFFER_FLAG_DISCONT);
4894         stream->set_discont = FALSE;
4895       } else {
4896         GST_BUFFER_FLAG_UNSET (sub, GST_BUFFER_FLAG_DISCONT);
4897       }
4898
4899       /* reverse playback book-keeping */
4900       if (!GST_CLOCK_TIME_IS_VALID (stream->from_time))
4901         stream->from_time = lace_time;
4902       if (stream->from_offset == -1)
4903         stream->from_offset = offset;
4904
4905       GST_DEBUG_OBJECT (demux,
4906           "Pushing lace %d, data of size %" G_GSIZE_FORMAT
4907           " for stream %d, time=%" GST_TIME_FORMAT " and duration=%"
4908           GST_TIME_FORMAT, n, gst_buffer_get_size (sub), stream_num,
4909           GST_TIME_ARGS (buffer_timestamp),
4910           GST_TIME_ARGS (GST_BUFFER_DURATION (sub)));
4911
4912 #if 0
4913       if (demux->common.element_index) {
4914         if (stream->index_writer_id == -1)
4915           gst_index_get_writer_id (demux->common.element_index,
4916               GST_OBJECT (stream->pad), &stream->index_writer_id);
4917
4918         GST_LOG_OBJECT (demux, "adding association %" GST_TIME_FORMAT "-> %"
4919             G_GUINT64_FORMAT " for writer id %d",
4920             GST_TIME_ARGS (buffer_timestamp), cluster_offset,
4921             stream->index_writer_id);
4922         gst_index_add_association (demux->common.element_index,
4923             stream->index_writer_id, GST_BUFFER_FLAG_IS_SET (sub,
4924                 GST_BUFFER_FLAG_DELTA_UNIT) ? 0 : GST_ASSOCIATION_FLAG_KEY_UNIT,
4925             GST_FORMAT_TIME, buffer_timestamp, GST_FORMAT_BYTES, cluster_offset,
4926             NULL);
4927       }
4928 #endif
4929
4930       /* Postprocess the buffers depending on the codec used */
4931       if (stream->postprocess_frame) {
4932         GST_LOG_OBJECT (demux, "running post process");
4933         ret = stream->postprocess_frame (GST_ELEMENT (demux), stream, &sub);
4934       }
4935
4936       /* At this point, we have a sub-buffer pointing at data within a larger
4937          buffer. This data might not be aligned with anything. If the data is
4938          raw samples though, we want it aligned to the raw type (eg, 4 bytes
4939          for 32 bit samples, etc), or bad things will happen downstream as
4940          elements typically assume minimal alignment.
4941          Therefore, create an aligned copy if necessary. */
4942       sub = gst_matroska_demux_align_buffer (demux, sub, stream->alignment);
4943
4944       if (!strcmp (stream->codec_id, GST_MATROSKA_CODEC_ID_AUDIO_OPUS)) {
4945         guint64 start_clip = 0, end_clip = 0;
4946
4947         /* Codec delay is part of the timestamps */
4948         if (GST_BUFFER_PTS_IS_VALID (sub) && stream->codec_delay) {
4949           if (GST_BUFFER_PTS (sub) > stream->codec_delay) {
4950             GST_BUFFER_PTS (sub) -= stream->codec_delay;
4951           } else {
4952             GST_BUFFER_PTS (sub) = 0;
4953
4954             /* Opus GstAudioClippingMeta units are scaled by 48000/sample_rate.
4955                That is, if a Opus track has audio encoded at 24000 Hz and 132
4956                samples need to be clipped, GstAudioClippingMeta.start will be
4957                set to 264. (This is also the case for buffer offsets.)
4958                Opus sample rates are always divisors of 48000 Hz, which is the
4959                maximum allowed sample rate. */
4960             start_clip =
4961                 gst_util_uint64_scale_round (stream->codec_delay, 48000,
4962                 GST_SECOND);
4963
4964             if (GST_BUFFER_DURATION_IS_VALID (sub)) {
4965               if (GST_BUFFER_DURATION (sub) > stream->codec_delay)
4966                 GST_BUFFER_DURATION (sub) -= stream->codec_delay;
4967               else
4968                 GST_BUFFER_DURATION (sub) = 0;
4969             }
4970           }
4971         }
4972
4973         if (block_discardpadding) {
4974           end_clip =
4975               gst_util_uint64_scale_round (block_discardpadding, 48000,
4976               GST_SECOND);
4977         }
4978
4979         if (start_clip || end_clip) {
4980           gst_buffer_add_audio_clipping_meta (sub, GST_FORMAT_DEFAULT,
4981               start_clip, end_clip);
4982         }
4983       }
4984
4985       if (GST_BUFFER_PTS_IS_VALID (sub)) {
4986         stream->pos = GST_BUFFER_PTS (sub);
4987         if (GST_BUFFER_DURATION_IS_VALID (sub))
4988           stream->pos += GST_BUFFER_DURATION (sub);
4989       } else if (GST_BUFFER_DTS_IS_VALID (sub)) {
4990         stream->pos = GST_BUFFER_DTS (sub);
4991         if (GST_BUFFER_DURATION_IS_VALID (sub))
4992           stream->pos += GST_BUFFER_DURATION (sub);
4993       }
4994
4995       /* Attach BlockAdditions to buffer; we assume a single buffer per group
4996        * in this case */
4997       if (additions.length > 0) {
4998         BlockAddition *blockadd;
4999
5000         if (laces > 2)
5001           GST_FIXME_OBJECT (demux, "Fix block additions with laced buffers");
5002
5003         while ((blockadd = g_queue_pop_head (&additions))) {
5004           GstMatroskaTrackVideoContext *videocontext =
5005               (GstMatroskaTrackVideoContext *) stream;
5006           if (blockadd->id == 1 && videocontext->alpha_mode
5007               && (!strcmp (stream->codec_id, GST_MATROSKA_CODEC_ID_VIDEO_VP8)
5008                   || !strcmp (stream->codec_id,
5009                       GST_MATROSKA_CODEC_ID_VIDEO_VP9))) {
5010             GstBuffer *alpha_buffer;
5011
5012             GST_TRACE_OBJECT (demux, "adding block addition %u as VP8/VP9 "
5013                 "alpha meta to buffer %p, %u bytes", (guint) blockadd->id, buf,
5014                 (guint) blockadd->size);
5015
5016             alpha_buffer = gst_buffer_new_wrapped (blockadd->data,
5017                 blockadd->size);
5018             gst_buffer_copy_into (alpha_buffer, sub,
5019                 GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_TIMESTAMPS, 0, -1);
5020             gst_buffer_add_video_codec_alpha_meta (sub, alpha_buffer);
5021           } else {
5022             g_free (blockadd->data);
5023           }
5024           g_free (blockadd);
5025         }
5026       }
5027
5028       ret = gst_pad_push (stream->pad, sub);
5029
5030       if (demux->common.segment.rate < 0) {
5031         if (lace_time > demux->common.segment.stop && ret == GST_FLOW_EOS) {
5032           /* In reverse playback we can get a GST_FLOW_EOS when
5033            * we are at the end of the segment, so we just need to jump
5034            * back to the previous section. */
5035           GST_DEBUG_OBJECT (demux, "downstream has reached end of segment");
5036           ret = GST_FLOW_OK;
5037         }
5038       }
5039       /* combine flows */
5040       ret = gst_flow_combiner_update_pad_flow (demux->flowcombiner,
5041           stream->pad, ret);
5042
5043     next_lace:
5044       size -= lace_size[n];
5045       if (lace_time != GST_CLOCK_TIME_NONE && duration)
5046         lace_time += duration / laces;
5047       else
5048         lace_time = GST_CLOCK_TIME_NONE;
5049     }
5050   }
5051
5052 done:
5053   if (buf) {
5054     gst_buffer_unmap (buf, &map);
5055     gst_buffer_unref (buf);
5056   }
5057   g_free (lace_size);
5058   {
5059     BlockAddition *blockadd;
5060
5061     while ((blockadd = g_queue_pop_head (&additions))) {
5062       g_free (blockadd->data);
5063       g_free (blockadd);
5064     }
5065   }
5066   return ret;
5067
5068   /* EXITS */
5069 eos:
5070   {
5071     stream->eos = TRUE;
5072     ret = GST_FLOW_OK;
5073     /* combine flows */
5074     ret = gst_flow_combiner_update_pad_flow (demux->flowcombiner, stream->pad,
5075         ret);
5076     goto done;
5077   }
5078 invalid_lacing:
5079   {
5080     GST_ELEMENT_WARNING (demux, STREAM, DEMUX, (NULL), ("Invalid lacing size"));
5081     /* non-fatal, try next block(group) */
5082     ret = GST_FLOW_OK;
5083     goto done;
5084   }
5085 data_error:
5086   {
5087     GST_ELEMENT_WARNING (demux, STREAM, DEMUX, (NULL), ("Data error"));
5088     /* non-fatal, try next block(group) */
5089     ret = GST_FLOW_OK;
5090     goto done;
5091   }
5092 }
5093
5094 /* return FALSE if block(group) should be skipped (due to a seek) */
5095 static inline gboolean
5096 gst_matroska_demux_seek_block (GstMatroskaDemux * demux)
5097 {
5098   if (G_UNLIKELY (demux->seek_block)) {
5099     if (!(--demux->seek_block)) {
5100       return TRUE;
5101     } else {
5102       GST_LOG_OBJECT (demux, "should skip block due to seek");
5103       return FALSE;
5104     }
5105   } else {
5106     return TRUE;
5107   }
5108 }
5109
5110 static GstFlowReturn
5111 gst_matroska_demux_parse_contents_seekentry (GstMatroskaDemux * demux,
5112     GstEbmlRead * ebml)
5113 {
5114   GstFlowReturn ret;
5115   guint64 seek_pos = (guint64) - 1;
5116   guint32 seek_id = 0;
5117   guint32 id;
5118
5119   DEBUG_ELEMENT_START (demux, ebml, "Seek");
5120
5121   if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
5122     DEBUG_ELEMENT_STOP (demux, ebml, "Seek", ret);
5123     return ret;
5124   }
5125
5126   while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
5127     if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
5128       break;
5129
5130     switch (id) {
5131       case GST_MATROSKA_ID_SEEKID:
5132       {
5133         guint64 t;
5134
5135         if ((ret = gst_ebml_read_uint (ebml, &id, &t)) != GST_FLOW_OK)
5136           break;
5137
5138         GST_DEBUG_OBJECT (demux, "SeekID: %" G_GUINT64_FORMAT, t);
5139         seek_id = t;
5140         break;
5141       }
5142
5143       case GST_MATROSKA_ID_SEEKPOSITION:
5144       {
5145         guint64 t;
5146
5147         if ((ret = gst_ebml_read_uint (ebml, &id, &t)) != GST_FLOW_OK)
5148           break;
5149
5150         if (t > G_MAXINT64) {
5151           GST_WARNING_OBJECT (demux,
5152               "Too large SeekPosition %" G_GUINT64_FORMAT, t);
5153           break;
5154         }
5155
5156         GST_DEBUG_OBJECT (demux, "SeekPosition: %" G_GUINT64_FORMAT, t);
5157         seek_pos = t;
5158         break;
5159       }
5160
5161       default:
5162         ret = gst_matroska_read_common_parse_skip (&demux->common, ebml,
5163             "SeekHead", id);
5164         break;
5165     }
5166   }
5167
5168   if (ret != GST_FLOW_OK && ret != GST_FLOW_EOS)
5169     return ret;
5170
5171   if (!seek_id || seek_pos == (guint64) - 1) {
5172     GST_WARNING_OBJECT (demux, "Incomplete seekhead entry (0x%x/%"
5173         G_GUINT64_FORMAT ")", seek_id, seek_pos);
5174     return GST_FLOW_OK;
5175   }
5176
5177   switch (seek_id) {
5178     case GST_MATROSKA_ID_SEEKHEAD:
5179     {
5180     }
5181     case GST_MATROSKA_ID_CUES:
5182     case GST_MATROSKA_ID_TAGS:
5183     case GST_MATROSKA_ID_TRACKS:
5184     case GST_MATROSKA_ID_SEGMENTINFO:
5185     case GST_MATROSKA_ID_ATTACHMENTS:
5186     case GST_MATROSKA_ID_CHAPTERS:
5187     {
5188       guint64 before_pos, length;
5189       guint needed;
5190
5191       /* remember */
5192       length = gst_matroska_read_common_get_length (&demux->common);
5193       before_pos = demux->common.offset;
5194
5195       if (length == (guint64) - 1) {
5196         GST_DEBUG_OBJECT (demux, "no upstream length, skipping SeakHead entry");
5197         break;
5198       }
5199
5200       /* check for validity */
5201       if (seek_pos + demux->common.ebml_segment_start + 12 >= length) {
5202         GST_WARNING_OBJECT (demux,
5203             "SeekHead reference lies outside file!" " (%"
5204             G_GUINT64_FORMAT "+%" G_GUINT64_FORMAT "+12 >= %"
5205             G_GUINT64_FORMAT ")", seek_pos, demux->common.ebml_segment_start,
5206             length);
5207         break;
5208       }
5209
5210       /* only pick up index location when streaming */
5211       if (demux->streaming) {
5212         if (seek_id == GST_MATROSKA_ID_CUES) {
5213           demux->index_offset = seek_pos + demux->common.ebml_segment_start;
5214           GST_DEBUG_OBJECT (demux, "Cues located at offset %" G_GUINT64_FORMAT,
5215               demux->index_offset);
5216         }
5217         break;
5218       }
5219
5220       /* seek */
5221       demux->common.offset = seek_pos + demux->common.ebml_segment_start;
5222
5223       /* check ID */
5224       if ((ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
5225                   GST_ELEMENT_CAST (demux), &id, &length, &needed)) !=
5226           GST_FLOW_OK)
5227         goto finish;
5228
5229       if (id != seek_id) {
5230         GST_WARNING_OBJECT (demux,
5231             "We looked for ID=0x%x but got ID=0x%x (pos=%" G_GUINT64_FORMAT ")",
5232             seek_id, id, seek_pos + demux->common.ebml_segment_start);
5233       } else {
5234         /* now parse */
5235         ret = gst_matroska_demux_parse_id (demux, id, length, needed);
5236       }
5237
5238     finish:
5239       /* seek back */
5240       demux->common.offset = before_pos;
5241       break;
5242     }
5243
5244     case GST_MATROSKA_ID_CLUSTER:
5245     {
5246       guint64 pos = seek_pos + demux->common.ebml_segment_start;
5247
5248       GST_LOG_OBJECT (demux, "Cluster position");
5249       if (G_UNLIKELY (!demux->clusters))
5250         demux->clusters = g_array_sized_new (TRUE, TRUE, sizeof (guint64), 100);
5251       g_array_append_val (demux->clusters, pos);
5252       break;
5253     }
5254
5255     default:
5256       GST_DEBUG_OBJECT (demux, "Ignoring Seek entry for ID=0x%x", seek_id);
5257       break;
5258   }
5259   DEBUG_ELEMENT_STOP (demux, ebml, "Seek", ret);
5260
5261   return ret;
5262 }
5263
5264 static GstFlowReturn
5265 gst_matroska_demux_parse_contents (GstMatroskaDemux * demux, GstEbmlRead * ebml)
5266 {
5267   GstFlowReturn ret = GST_FLOW_OK;
5268   guint32 id;
5269
5270   DEBUG_ELEMENT_START (demux, ebml, "SeekHead");
5271
5272   if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
5273     DEBUG_ELEMENT_STOP (demux, ebml, "SeekHead", ret);
5274     return ret;
5275   }
5276
5277   while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
5278     if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
5279       break;
5280
5281     switch (id) {
5282       case GST_MATROSKA_ID_SEEKENTRY:
5283       {
5284         ret = gst_matroska_demux_parse_contents_seekentry (demux, ebml);
5285         /* Ignore EOS and errors here */
5286         if (ret != GST_FLOW_OK) {
5287           GST_DEBUG_OBJECT (demux, "Ignoring %s", gst_flow_get_name (ret));
5288           ret = GST_FLOW_OK;
5289         }
5290         break;
5291       }
5292
5293       default:
5294         ret = gst_matroska_read_common_parse_skip (&demux->common,
5295             ebml, "SeekHead", id);
5296         break;
5297     }
5298   }
5299
5300   DEBUG_ELEMENT_STOP (demux, ebml, "SeekHead", ret);
5301
5302   /* Sort clusters by position for easier searching */
5303   if (demux->clusters)
5304     g_array_sort (demux->clusters, (GCompareFunc) gst_matroska_cluster_compare);
5305
5306   return ret;
5307 }
5308
5309 #define GST_FLOW_OVERFLOW   GST_FLOW_CUSTOM_ERROR
5310
5311 #define MAX_BLOCK_SIZE (15 * 1024 * 1024)
5312
5313 static inline GstFlowReturn
5314 gst_matroska_demux_check_read_size (GstMatroskaDemux * demux, guint64 bytes)
5315 {
5316   if (G_UNLIKELY (bytes > MAX_BLOCK_SIZE)) {
5317     /* only a few blocks are expected/allowed to be large,
5318      * and will be recursed into, whereas others will be read and must fit */
5319     if (demux->streaming) {
5320       /* fatal in streaming case, as we can't step over easily */
5321       GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
5322           ("reading large block of size %" G_GUINT64_FORMAT " not supported; "
5323               "file might be corrupt.", bytes));
5324       return GST_FLOW_ERROR;
5325     } else {
5326       /* indicate higher level to quietly give up */
5327       GST_DEBUG_OBJECT (demux,
5328           "too large block of size %" G_GUINT64_FORMAT, bytes);
5329       return GST_FLOW_ERROR;
5330     }
5331   } else {
5332     return GST_FLOW_OK;
5333   }
5334 }
5335
5336 /* returns TRUE if we truly are in error state, and should give up */
5337 static inline GstFlowReturn
5338 gst_matroska_demux_check_parse_error (GstMatroskaDemux * demux)
5339 {
5340   if (!demux->streaming && demux->next_cluster_offset > 0) {
5341     /* just repositioning to where next cluster should be and try from there */
5342     GST_WARNING_OBJECT (demux, "parse error, trying next cluster expected at %"
5343         G_GUINT64_FORMAT, demux->next_cluster_offset);
5344     demux->common.offset = demux->next_cluster_offset;
5345     demux->next_cluster_offset = 0;
5346     return GST_FLOW_OK;
5347   } else {
5348     gint64 pos;
5349     GstFlowReturn ret;
5350
5351     /* sigh, one last attempt above and beyond call of duty ...;
5352      * search for cluster mark following current pos */
5353     pos = demux->common.offset;
5354     GST_WARNING_OBJECT (demux, "parse error, looking for next cluster");
5355     if ((ret = gst_matroska_demux_search_cluster (demux, &pos, TRUE)) !=
5356         GST_FLOW_OK) {
5357       /* did not work, give up */
5358       return ret;
5359     } else {
5360       GST_DEBUG_OBJECT (demux, "... found at  %" G_GUINT64_FORMAT, pos);
5361       /* try that position */
5362       demux->common.offset = pos;
5363       return GST_FLOW_OK;
5364     }
5365   }
5366 }
5367
5368 static inline GstFlowReturn
5369 gst_matroska_demux_flush (GstMatroskaDemux * demux, guint flush)
5370 {
5371   GST_LOG_OBJECT (demux, "skipping %d bytes", flush);
5372   demux->common.offset += flush;
5373   if (demux->streaming) {
5374     GstFlowReturn ret;
5375
5376     /* hard to skip large blocks when streaming */
5377     ret = gst_matroska_demux_check_read_size (demux, flush);
5378     if (ret != GST_FLOW_OK)
5379       return ret;
5380     if (flush <= gst_adapter_available (demux->common.adapter))
5381       gst_adapter_flush (demux->common.adapter, flush);
5382     else
5383       return GST_FLOW_EOS;
5384   }
5385   return GST_FLOW_OK;
5386 }
5387
5388 /* initializes @ebml with @bytes from input stream at current offset.
5389  * Returns EOS if insufficient available,
5390  * ERROR if too much was attempted to read. */
5391 static inline GstFlowReturn
5392 gst_matroska_demux_take (GstMatroskaDemux * demux, guint64 bytes,
5393     GstEbmlRead * ebml)
5394 {
5395   GstBuffer *buffer = NULL;
5396   GstFlowReturn ret = GST_FLOW_OK;
5397
5398   GST_LOG_OBJECT (demux, "taking %" G_GUINT64_FORMAT " bytes for parsing",
5399       bytes);
5400   ret = gst_matroska_demux_check_read_size (demux, bytes);
5401   if (G_UNLIKELY (ret != GST_FLOW_OK)) {
5402     if (!demux->streaming) {
5403       /* in pull mode, we can skip */
5404       if ((ret = gst_matroska_demux_flush (demux, bytes)) == GST_FLOW_OK)
5405         ret = GST_FLOW_OVERFLOW;
5406     } else {
5407       /* otherwise fatal */
5408       ret = GST_FLOW_ERROR;
5409     }
5410     goto exit;
5411   }
5412   if (demux->streaming) {
5413     if (gst_adapter_available (demux->common.adapter) >= bytes)
5414       buffer = gst_adapter_take_buffer (demux->common.adapter, bytes);
5415     else
5416       ret = GST_FLOW_EOS;
5417   } else
5418     ret = gst_matroska_read_common_peek_bytes (&demux->common,
5419         demux->common.offset, bytes, &buffer, NULL);
5420   if (G_LIKELY (buffer)) {
5421     gst_ebml_read_init (ebml, GST_ELEMENT_CAST (demux), buffer,
5422         demux->common.offset);
5423     demux->common.offset += bytes;
5424   }
5425 exit:
5426   return ret;
5427 }
5428
5429 static void
5430 gst_matroska_demux_check_seekability (GstMatroskaDemux * demux)
5431 {
5432   GstQuery *query;
5433   gboolean seekable = FALSE;
5434   gint64 start = -1, stop = -1;
5435
5436   query = gst_query_new_seeking (GST_FORMAT_BYTES);
5437   if (!gst_pad_peer_query (demux->common.sinkpad, query)) {
5438     GST_DEBUG_OBJECT (demux, "seeking query failed");
5439     goto done;
5440   }
5441
5442   gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
5443
5444   /* try harder to query upstream size if we didn't get it the first time */
5445   if (seekable && stop == -1) {
5446     GST_DEBUG_OBJECT (demux, "doing duration query to fix up unset stop");
5447     gst_pad_peer_query_duration (demux->common.sinkpad, GST_FORMAT_BYTES,
5448         &stop);
5449   }
5450
5451   /* if upstream doesn't know the size, it's likely that it's not seekable in
5452    * practice even if it technically may be seekable */
5453   if (seekable && (start != 0 || stop <= start)) {
5454     GST_DEBUG_OBJECT (demux, "seekable but unknown start/stop -> disable");
5455     seekable = FALSE;
5456   }
5457
5458 done:
5459   GST_INFO_OBJECT (demux, "seekable: %d (%" G_GUINT64_FORMAT " - %"
5460       G_GUINT64_FORMAT ")", seekable, start, stop);
5461   demux->seekable = seekable;
5462
5463   gst_query_unref (query);
5464 }
5465
5466 static GstFlowReturn
5467 gst_matroska_demux_find_tracks (GstMatroskaDemux * demux)
5468 {
5469   guint32 id;
5470   guint64 before_pos;
5471   guint64 length;
5472   guint needed;
5473   GstFlowReturn ret = GST_FLOW_OK;
5474
5475   GST_WARNING_OBJECT (demux,
5476       "Found Cluster element before Tracks, searching Tracks");
5477
5478   /* remember */
5479   before_pos = demux->common.offset;
5480
5481   /* Search Tracks element */
5482   while (TRUE) {
5483     ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
5484         GST_ELEMENT_CAST (demux), &id, &length, &needed);
5485     if (ret != GST_FLOW_OK)
5486       break;
5487
5488     if (id != GST_MATROSKA_ID_TRACKS) {
5489       /* we may be skipping large cluster here, so forego size check etc */
5490       /* ... but we can't skip undefined size; force error */
5491       if (length == G_MAXUINT64) {
5492         ret = gst_matroska_demux_check_read_size (demux, length);
5493         break;
5494       } else {
5495         demux->common.offset += needed;
5496         demux->common.offset += length;
5497       }
5498       continue;
5499     }
5500
5501     /* will lead to track parsing ... */
5502     ret = gst_matroska_demux_parse_id (demux, id, length, needed);
5503     break;
5504   }
5505
5506   /* seek back */
5507   demux->common.offset = before_pos;
5508
5509   return ret;
5510 }
5511
5512 #define GST_READ_CHECK(stmt)  \
5513 G_STMT_START { \
5514   if (G_UNLIKELY ((ret = (stmt)) != GST_FLOW_OK)) { \
5515     if (ret == GST_FLOW_OVERFLOW) { \
5516       ret = GST_FLOW_OK; \
5517     } \
5518     goto read_error; \
5519   } \
5520 } G_STMT_END
5521
5522 static GstFlowReturn
5523 gst_matroska_demux_parse_id (GstMatroskaDemux * demux, guint32 id,
5524     guint64 length, guint needed)
5525 {
5526   GstEbmlRead ebml = { 0, };
5527   GstFlowReturn ret = GST_FLOW_OK;
5528   guint64 read;
5529
5530   GST_LOG_OBJECT (demux, "Parsing Element id 0x%x, "
5531       "size %" G_GUINT64_FORMAT ", prefix %d", id, length, needed);
5532
5533   /* if we plan to read and parse this element, we need prefix (id + length)
5534    * and the contents */
5535   /* mind about overflow wrap-around when dealing with undefined size */
5536   read = length;
5537   if (G_LIKELY (length != G_MAXUINT64))
5538     read += needed;
5539
5540   switch (demux->common.state) {
5541     case GST_MATROSKA_READ_STATE_START:
5542       switch (id) {
5543         case GST_EBML_ID_HEADER:
5544           GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5545           ret = gst_matroska_read_common_parse_header (&demux->common, &ebml);
5546           if (ret != GST_FLOW_OK)
5547             goto parse_failed;
5548           demux->common.state = GST_MATROSKA_READ_STATE_SEGMENT;
5549           gst_matroska_demux_check_seekability (demux);
5550           break;
5551         default:
5552           goto invalid_header;
5553           break;
5554       }
5555       break;
5556     case GST_MATROSKA_READ_STATE_SEGMENT:
5557       switch (id) {
5558         case GST_MATROSKA_ID_SEGMENT:
5559           /* eat segment prefix */
5560           GST_READ_CHECK (gst_matroska_demux_flush (demux, needed));
5561           GST_DEBUG_OBJECT (demux,
5562               "Found Segment start at offset %" G_GUINT64_FORMAT " with size %"
5563               G_GUINT64_FORMAT, demux->common.offset, length);
5564           /* seeks are from the beginning of the segment,
5565            * after the segment ID/length */
5566           demux->common.ebml_segment_start = demux->common.offset;
5567           if (length == 0)
5568             length = G_MAXUINT64;
5569           demux->common.ebml_segment_length = length;
5570           demux->common.state = GST_MATROSKA_READ_STATE_HEADER;
5571           break;
5572         default:
5573           GST_WARNING_OBJECT (demux,
5574               "Expected a Segment ID (0x%x), but received 0x%x!",
5575               GST_MATROSKA_ID_SEGMENT, id);
5576           GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
5577           break;
5578       }
5579       break;
5580     case GST_MATROSKA_READ_STATE_SCANNING:
5581       if (id != GST_MATROSKA_ID_CLUSTER &&
5582           id != GST_MATROSKA_ID_PREVSIZE &&
5583           id != GST_MATROSKA_ID_CLUSTERTIMECODE) {
5584         if (demux->common.start_resync_offset != -1) {
5585           /* we need to skip byte per byte if we are scanning for a new cluster
5586            * after invalid data is found
5587            */
5588           read = 1;
5589         }
5590         goto skip;
5591       } else {
5592         if (demux->common.start_resync_offset != -1) {
5593           GST_LOG_OBJECT (demux, "Resync done, new cluster found!");
5594           demux->common.start_resync_offset = -1;
5595           demux->common.state = demux->common.state_to_restore;
5596         }
5597       }
5598       /* fall-through */
5599     case GST_MATROSKA_READ_STATE_HEADER:
5600     case GST_MATROSKA_READ_STATE_DATA:
5601     case GST_MATROSKA_READ_STATE_SEEK:
5602       switch (id) {
5603         case GST_EBML_ID_HEADER:
5604           GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
5605           demux->common.state = GST_MATROSKA_READ_STATE_SEGMENT;
5606           gst_matroska_demux_check_seekability (demux);
5607           break;
5608         case GST_MATROSKA_ID_SEGMENTINFO:
5609           if (!demux->common.segmentinfo_parsed) {
5610             GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5611             ret = gst_matroska_read_common_parse_info (&demux->common,
5612                 GST_ELEMENT_CAST (demux), &ebml);
5613             if (ret == GST_FLOW_OK)
5614               gst_matroska_demux_send_tags (demux);
5615           } else {
5616             GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
5617           }
5618           break;
5619         case GST_MATROSKA_ID_TRACKS:
5620           GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5621           if (!demux->tracks_parsed) {
5622             ret = gst_matroska_demux_parse_tracks (demux, &ebml);
5623           } else {
5624             ret = gst_matroska_demux_update_tracks (demux, &ebml);
5625           }
5626           break;
5627         case GST_MATROSKA_ID_CLUSTER:
5628           if (G_UNLIKELY (!demux->tracks_parsed)) {
5629             if (demux->streaming) {
5630               GST_DEBUG_OBJECT (demux, "Cluster before Track");
5631               goto not_streamable;
5632             } else {
5633               ret = gst_matroska_demux_find_tracks (demux);
5634               if (!demux->tracks_parsed)
5635                 goto no_tracks;
5636             }
5637           }
5638           if (demux->common.state == GST_MATROSKA_READ_STATE_HEADER) {
5639             demux->common.state = GST_MATROSKA_READ_STATE_DATA;
5640             demux->first_cluster_offset = demux->common.offset;
5641
5642             if (!demux->streaming &&
5643                 !GST_CLOCK_TIME_IS_VALID (demux->common.segment.duration)) {
5644               GstMatroskaIndex *last = NULL;
5645
5646               GST_DEBUG_OBJECT (demux,
5647                   "estimating duration using last cluster");
5648               if ((last = gst_matroska_demux_search_pos (demux,
5649                           GST_CLOCK_TIME_NONE)) != NULL) {
5650                 demux->last_cluster_offset =
5651                     last->pos + demux->common.ebml_segment_start;
5652                 demux->stream_last_time = last->time;
5653                 demux->common.segment.duration =
5654                     demux->stream_last_time - demux->stream_start_time;
5655                 /* above estimate should not be taken all too strongly */
5656                 demux->invalid_duration = TRUE;
5657                 GST_DEBUG_OBJECT (demux,
5658                     "estimated duration as %" GST_TIME_FORMAT,
5659                     GST_TIME_ARGS (demux->common.segment.duration));
5660
5661                 g_free (last);
5662               }
5663             }
5664
5665             /* Peek at second cluster in order to figure out if we have cluster
5666              * prev_size or not (which is never set on the first cluster for
5667              * obvious reasons). This is useful in case someone initiates a
5668              * seek or direction change before we reach the second cluster. */
5669             if (!demux->streaming) {
5670               ClusterInfo cluster = { 0, };
5671
5672               if (gst_matroska_demux_peek_cluster_info (demux, &cluster,
5673                       demux->first_cluster_offset) && cluster.size > 0) {
5674                 gst_matroska_demux_peek_cluster_info (demux, &cluster,
5675                     demux->first_cluster_offset + cluster.size);
5676               }
5677               demux->common.offset = demux->first_cluster_offset;
5678             }
5679
5680             if (demux->deferred_seek_event) {
5681               GstEvent *seek_event;
5682               GstPad *seek_pad;
5683               seek_event = demux->deferred_seek_event;
5684               seek_pad = demux->deferred_seek_pad;
5685               demux->deferred_seek_event = NULL;
5686               demux->deferred_seek_pad = NULL;
5687               GST_DEBUG_OBJECT (demux,
5688                   "Handling deferred seek event: %" GST_PTR_FORMAT, seek_event);
5689               gst_matroska_demux_handle_seek_event (demux, seek_pad,
5690                   seek_event);
5691               gst_event_unref (seek_event);
5692             }
5693
5694             /* send initial segment - we wait till we know the first
5695                incoming timestamp, so we can properly set the start of
5696                the segment. */
5697             demux->need_segment = TRUE;
5698           }
5699           demux->cluster_time = GST_CLOCK_TIME_NONE;
5700           demux->cluster_offset = demux->common.offset;
5701           demux->cluster_prevsize = 0;
5702           if (G_UNLIKELY (!demux->seek_first && demux->seek_block)) {
5703             GST_DEBUG_OBJECT (demux, "seek target block %" G_GUINT64_FORMAT
5704                 " not found in Cluster, trying next Cluster's first block instead",
5705                 demux->seek_block);
5706             demux->seek_block = 0;
5707           }
5708           demux->seek_first = FALSE;
5709           /* record next cluster for recovery */
5710           if (read != G_MAXUINT64)
5711             demux->next_cluster_offset = demux->cluster_offset + read;
5712           /* eat cluster prefix */
5713           gst_matroska_demux_flush (demux, needed);
5714           break;
5715         case GST_MATROSKA_ID_CLUSTERTIMECODE:
5716         {
5717           guint64 num;
5718
5719           GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5720           if ((ret = gst_ebml_read_uint (&ebml, &id, &num)) != GST_FLOW_OK)
5721             goto parse_failed;
5722           GST_DEBUG_OBJECT (demux, "ClusterTimeCode: %" G_GUINT64_FORMAT, num);
5723           demux->cluster_time = num;
5724           /* track last cluster */
5725           if (demux->cluster_offset > demux->last_cluster_offset) {
5726             demux->last_cluster_offset = demux->cluster_offset;
5727             demux->stream_last_time =
5728                 demux->cluster_time * demux->common.time_scale;
5729           }
5730 #if 0
5731           if (demux->common.element_index) {
5732             if (demux->common.element_index_writer_id == -1)
5733               gst_index_get_writer_id (demux->common.element_index,
5734                   GST_OBJECT (demux), &demux->common.element_index_writer_id);
5735             GST_LOG_OBJECT (demux, "adding association %" GST_TIME_FORMAT "-> %"
5736                 G_GUINT64_FORMAT " for writer id %d",
5737                 GST_TIME_ARGS (demux->cluster_time), demux->cluster_offset,
5738                 demux->common.element_index_writer_id);
5739             gst_index_add_association (demux->common.element_index,
5740                 demux->common.element_index_writer_id,
5741                 GST_ASSOCIATION_FLAG_KEY_UNIT,
5742                 GST_FORMAT_TIME, demux->cluster_time,
5743                 GST_FORMAT_BYTES, demux->cluster_offset, NULL);
5744           }
5745 #endif
5746           break;
5747         }
5748         case GST_MATROSKA_ID_BLOCKGROUP:
5749           if (!gst_matroska_demux_seek_block (demux))
5750             goto skip;
5751           GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5752           DEBUG_ELEMENT_START (demux, &ebml, "BlockGroup");
5753           if ((ret = gst_ebml_read_master (&ebml, &id)) == GST_FLOW_OK) {
5754             ret = gst_matroska_demux_parse_blockgroup_or_simpleblock (demux,
5755                 &ebml, demux->cluster_time, demux->cluster_offset, FALSE);
5756           }
5757           DEBUG_ELEMENT_STOP (demux, &ebml, "BlockGroup", ret);
5758           break;
5759         case GST_MATROSKA_ID_SIMPLEBLOCK:
5760           if (!gst_matroska_demux_seek_block (demux))
5761             goto skip;
5762           GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5763           DEBUG_ELEMENT_START (demux, &ebml, "SimpleBlock");
5764           ret = gst_matroska_demux_parse_blockgroup_or_simpleblock (demux,
5765               &ebml, demux->cluster_time, demux->cluster_offset, TRUE);
5766           DEBUG_ELEMENT_STOP (demux, &ebml, "SimpleBlock", ret);
5767           break;
5768         case GST_MATROSKA_ID_ATTACHMENTS:
5769           if (!demux->common.attachments_parsed) {
5770             GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5771             ret = gst_matroska_read_common_parse_attachments (&demux->common,
5772                 GST_ELEMENT_CAST (demux), &ebml);
5773             if (ret == GST_FLOW_OK)
5774               gst_matroska_demux_send_tags (demux);
5775           } else {
5776             GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
5777           }
5778           break;
5779         case GST_MATROSKA_ID_TAGS:
5780           GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5781           ret = gst_matroska_read_common_parse_metadata (&demux->common,
5782               GST_ELEMENT_CAST (demux), &ebml);
5783           if (ret == GST_FLOW_OK)
5784             gst_matroska_demux_send_tags (demux);
5785           break;
5786         case GST_MATROSKA_ID_CHAPTERS:
5787           if (!demux->common.chapters_parsed) {
5788             GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5789             ret =
5790                 gst_matroska_read_common_parse_chapters (&demux->common, &ebml);
5791
5792             if (demux->common.toc) {
5793               gst_matroska_demux_send_event (demux,
5794                   gst_event_new_toc (demux->common.toc, FALSE));
5795             }
5796           } else
5797             GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
5798           break;
5799         case GST_MATROSKA_ID_SEEKHEAD:
5800           GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5801           ret = gst_matroska_demux_parse_contents (demux, &ebml);
5802           break;
5803         case GST_MATROSKA_ID_CUES:
5804           if (demux->common.index_parsed) {
5805             GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
5806             break;
5807           }
5808           GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5809           ret = gst_matroska_read_common_parse_index (&demux->common, &ebml);
5810           /* only push based; delayed index building */
5811           if (ret == GST_FLOW_OK
5812               && demux->common.state == GST_MATROSKA_READ_STATE_SEEK) {
5813             GstEvent *event;
5814
5815             GST_OBJECT_LOCK (demux);
5816             event = demux->seek_event;
5817             demux->seek_event = NULL;
5818             GST_OBJECT_UNLOCK (demux);
5819
5820             g_assert (event);
5821             /* unlikely to fail, since we managed to seek to this point */
5822             if (!gst_matroska_demux_handle_seek_event (demux, NULL, event)) {
5823               gst_event_unref (event);
5824               goto seek_failed;
5825             }
5826             gst_event_unref (event);
5827             /* resume data handling, main thread clear to seek again */
5828             GST_OBJECT_LOCK (demux);
5829             demux->common.state = GST_MATROSKA_READ_STATE_DATA;
5830             GST_OBJECT_UNLOCK (demux);
5831           }
5832           break;
5833         case GST_MATROSKA_ID_PREVSIZE:{
5834           guint64 num;
5835
5836           GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5837           if ((ret = gst_ebml_read_uint (&ebml, &id, &num)) != GST_FLOW_OK)
5838             goto parse_failed;
5839           GST_LOG_OBJECT (demux, "ClusterPrevSize: %" G_GUINT64_FORMAT, num);
5840           demux->cluster_prevsize = num;
5841           demux->seen_cluster_prevsize = TRUE;
5842           break;
5843         }
5844         case GST_MATROSKA_ID_POSITION:
5845         case GST_MATROSKA_ID_ENCRYPTEDBLOCK:
5846           /* The WebM doesn't support the EncryptedBlock element.
5847            * The Matroska spec doesn't give us more detail, how to parse this element,
5848            * for example the field TransformID isn't specified yet.*/
5849         case GST_MATROSKA_ID_SILENTTRACKS:
5850           GST_DEBUG_OBJECT (demux,
5851               "Skipping Cluster subelement 0x%x - ignoring", id);
5852           /* fall-through */
5853         default:
5854         skip:
5855           GST_DEBUG_OBJECT (demux, "skipping Element 0x%x", id);
5856           GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
5857           break;
5858       }
5859       break;
5860   }
5861
5862   if (ret == GST_FLOW_PARSE)
5863     goto parse_failed;
5864
5865 exit:
5866   gst_ebml_read_clear (&ebml);
5867   return ret;
5868
5869   /* ERRORS */
5870 read_error:
5871   {
5872     /* simply exit, maybe not enough data yet */
5873     /* no ebml to clear if read error */
5874     return ret;
5875   }
5876 parse_failed:
5877   {
5878     GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
5879         ("Failed to parse Element 0x%x", id));
5880     ret = GST_FLOW_ERROR;
5881     goto exit;
5882   }
5883 not_streamable:
5884   {
5885     GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
5886         ("File layout does not permit streaming"));
5887     ret = GST_FLOW_ERROR;
5888     goto exit;
5889   }
5890 no_tracks:
5891   {
5892     GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
5893         ("No Tracks element found"));
5894     ret = GST_FLOW_ERROR;
5895     goto exit;
5896   }
5897 invalid_header:
5898   {
5899     GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL), ("Invalid header"));
5900     ret = GST_FLOW_ERROR;
5901     goto exit;
5902   }
5903 seek_failed:
5904   {
5905     GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL), ("Failed to seek"));
5906     ret = GST_FLOW_ERROR;
5907     goto exit;
5908   }
5909 }
5910
5911 static void
5912 gst_matroska_demux_loop (GstPad * pad)
5913 {
5914   GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (GST_PAD_PARENT (pad));
5915   GstFlowReturn ret;
5916   guint32 id;
5917   guint64 length;
5918   guint needed;
5919
5920   /* If we have to close a segment, send a new segment to do this now */
5921   if (G_LIKELY (demux->common.state == GST_MATROSKA_READ_STATE_DATA)) {
5922     if (G_UNLIKELY (demux->new_segment)) {
5923       gst_matroska_demux_send_event (demux, demux->new_segment);
5924       demux->new_segment = NULL;
5925     }
5926   }
5927
5928   ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
5929       GST_ELEMENT_CAST (demux), &id, &length, &needed);
5930   if (ret == GST_FLOW_EOS) {
5931     goto eos;
5932   } else if (ret == GST_FLOW_FLUSHING) {
5933     goto pause;
5934   } else if (ret != GST_FLOW_OK) {
5935     ret = gst_matroska_demux_check_parse_error (demux);
5936
5937     /* Only handle EOS as no error if we're outside the segment already */
5938     if (ret == GST_FLOW_EOS && (demux->common.ebml_segment_length != G_MAXUINT64
5939             && demux->common.offset >=
5940             demux->common.ebml_segment_start +
5941             demux->common.ebml_segment_length))
5942       goto eos;
5943     else if (ret != GST_FLOW_OK)
5944       goto pause;
5945     else
5946       return;
5947   }
5948
5949   GST_LOG_OBJECT (demux, "Offset %" G_GUINT64_FORMAT ", Element id 0x%x, "
5950       "size %" G_GUINT64_FORMAT ", needed %d", demux->common.offset, id,
5951       length, needed);
5952
5953   ret = gst_matroska_demux_parse_id (demux, id, length, needed);
5954   if (ret == GST_FLOW_EOS)
5955     goto eos;
5956   if (ret != GST_FLOW_OK)
5957     goto pause;
5958
5959   /* check if we're at the end of a configured segment */
5960   if (G_LIKELY (demux->common.src->len)) {
5961     guint i;
5962
5963     g_assert (demux->common.num_streams == demux->common.src->len);
5964     for (i = 0; i < demux->common.src->len; i++) {
5965       GstMatroskaTrackContext *context = g_ptr_array_index (demux->common.src,
5966           i);
5967       GST_DEBUG_OBJECT (context->pad, "pos %" GST_TIME_FORMAT,
5968           GST_TIME_ARGS (context->pos));
5969       if (context->eos == FALSE)
5970         goto next;
5971     }
5972
5973     GST_INFO_OBJECT (demux, "All streams are EOS");
5974     ret = GST_FLOW_EOS;
5975     goto eos;
5976   }
5977
5978 next:
5979   if (G_UNLIKELY (demux->cached_length == G_MAXUINT64 ||
5980           demux->common.offset >= demux->cached_length)) {
5981     demux->cached_length = gst_matroska_read_common_get_length (&demux->common);
5982     if (demux->common.offset == demux->cached_length) {
5983       GST_LOG_OBJECT (demux, "Reached end of stream");
5984       ret = GST_FLOW_EOS;
5985       goto eos;
5986     }
5987   }
5988
5989   return;
5990
5991   /* ERRORS */
5992 eos:
5993   {
5994     if (demux->common.segment.rate < 0.0) {
5995       ret = gst_matroska_demux_seek_to_previous_keyframe (demux);
5996       if (ret == GST_FLOW_OK)
5997         return;
5998     }
5999     /* fall-through */
6000   }
6001 pause:
6002   {
6003     const gchar *reason = gst_flow_get_name (ret);
6004     gboolean push_eos = FALSE;
6005
6006     GST_LOG_OBJECT (demux, "pausing task, reason %s", reason);
6007     gst_pad_pause_task (demux->common.sinkpad);
6008
6009     if (ret == GST_FLOW_EOS) {
6010       /* perform EOS logic */
6011
6012       /* If we were in the headers, make sure we send no-more-pads.
6013          This will ensure decodebin does not get stuck thinking
6014          the chain is not complete yet, and waiting indefinitely. */
6015       if (G_UNLIKELY (demux->common.state == GST_MATROSKA_READ_STATE_HEADER)) {
6016         if (demux->common.src->len == 0) {
6017           GST_ELEMENT_ERROR (demux, STREAM, FAILED, (NULL),
6018               ("No pads created"));
6019         } else {
6020           GST_ELEMENT_WARNING (demux, STREAM, DEMUX, (NULL),
6021               ("Failed to finish reading headers"));
6022         }
6023         gst_element_no_more_pads (GST_ELEMENT (demux));
6024       }
6025
6026       if (demux->common.segment.flags & GST_SEEK_FLAG_SEGMENT) {
6027         GstEvent *event;
6028         GstMessage *msg;
6029         gint64 stop;
6030
6031         /* for segment playback we need to post when (in stream time)
6032          * we stopped, this is either stop (when set) or the duration. */
6033         if ((stop = demux->common.segment.stop) == -1)
6034           stop = demux->last_stop_end;
6035
6036         GST_LOG_OBJECT (demux, "Sending segment done, at end of segment");
6037         msg = gst_message_new_segment_done (GST_OBJECT (demux), GST_FORMAT_TIME,
6038             stop);
6039         if (demux->segment_seqnum)
6040           gst_message_set_seqnum (msg, demux->segment_seqnum);
6041         gst_element_post_message (GST_ELEMENT (demux), msg);
6042
6043         event = gst_event_new_segment_done (GST_FORMAT_TIME, stop);
6044         if (demux->segment_seqnum)
6045           gst_event_set_seqnum (event, demux->segment_seqnum);
6046         gst_matroska_demux_send_event (demux, event);
6047       } else {
6048         push_eos = TRUE;
6049       }
6050     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
6051       /* for fatal errors we post an error message */
6052       GST_ELEMENT_FLOW_ERROR (demux, ret);
6053       push_eos = TRUE;
6054     }
6055     if (push_eos) {
6056       GstEvent *event;
6057
6058       /* send EOS, and prevent hanging if no streams yet */
6059       GST_LOG_OBJECT (demux, "Sending EOS, at end of stream");
6060       event = gst_event_new_eos ();
6061       if (demux->segment_seqnum)
6062         gst_event_set_seqnum (event, demux->segment_seqnum);
6063       if (!gst_matroska_demux_send_event (demux, event) &&
6064           (ret == GST_FLOW_EOS)) {
6065         GST_ELEMENT_ERROR (demux, STREAM, DEMUX,
6066             (NULL), ("got eos but no streams (yet)"));
6067       }
6068     }
6069     return;
6070   }
6071 }
6072
6073 /*
6074  * Create and push a flushing seek event upstream
6075  */
6076 static gboolean
6077 perform_seek_to_offset (GstMatroskaDemux * demux, gdouble rate, guint64 offset,
6078     guint32 seqnum, GstSeekFlags flags)
6079 {
6080   GstEvent *event;
6081   gboolean res = 0;
6082
6083   GST_DEBUG_OBJECT (demux, "Seeking to %" G_GUINT64_FORMAT, offset);
6084
6085   event =
6086       gst_event_new_seek (rate, GST_FORMAT_BYTES,
6087       flags | GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE,
6088       GST_SEEK_TYPE_SET, offset, GST_SEEK_TYPE_NONE, -1);
6089   gst_event_set_seqnum (event, seqnum);
6090
6091   res = gst_pad_push_event (demux->common.sinkpad, event);
6092
6093   /* segment event will update offset */
6094   return res;
6095 }
6096
6097 static GstFlowReturn
6098 gst_matroska_demux_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
6099 {
6100   GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (parent);
6101   guint available;
6102   GstFlowReturn ret = GST_FLOW_OK;
6103   guint needed = 0;
6104   guint32 id;
6105   guint64 length;
6106
6107   if (G_UNLIKELY (GST_BUFFER_IS_DISCONT (buffer))) {
6108     GST_DEBUG_OBJECT (demux, "got DISCONT");
6109     gst_adapter_clear (demux->common.adapter);
6110     GST_OBJECT_LOCK (demux);
6111     gst_matroska_read_common_reset_streams (&demux->common,
6112         GST_CLOCK_TIME_NONE, FALSE);
6113     GST_OBJECT_UNLOCK (demux);
6114   }
6115
6116   gst_adapter_push (demux->common.adapter, buffer);
6117   buffer = NULL;
6118
6119 next:
6120   available = gst_adapter_available (demux->common.adapter);
6121
6122   ret = gst_matroska_read_common_peek_id_length_push (&demux->common,
6123       GST_ELEMENT_CAST (demux), &id, &length, &needed);
6124   if (G_UNLIKELY (ret != GST_FLOW_OK && ret != GST_FLOW_EOS)) {
6125     if (demux->common.ebml_segment_length != G_MAXUINT64
6126         && demux->common.offset >=
6127         demux->common.ebml_segment_start + demux->common.ebml_segment_length) {
6128       return GST_FLOW_OK;
6129     } else {
6130       gint64 bytes_scanned;
6131       if (demux->common.start_resync_offset == -1) {
6132         demux->common.start_resync_offset = demux->common.offset;
6133         demux->common.state_to_restore = demux->common.state;
6134       }
6135       bytes_scanned = demux->common.offset - demux->common.start_resync_offset;
6136       if (bytes_scanned <= INVALID_DATA_THRESHOLD) {
6137         GST_WARNING_OBJECT (demux,
6138             "parse error, looking for next cluster, actual offset %"
6139             G_GUINT64_FORMAT ", start resync offset %" G_GUINT64_FORMAT,
6140             demux->common.offset, demux->common.start_resync_offset);
6141         demux->common.state = GST_MATROSKA_READ_STATE_SCANNING;
6142         ret = GST_FLOW_OK;
6143       } else {
6144         GST_WARNING_OBJECT (demux,
6145             "unrecoverable parse error, next cluster not found and threshold "
6146             "exceeded, bytes scanned %" G_GINT64_FORMAT, bytes_scanned);
6147         return ret;
6148       }
6149     }
6150   }
6151
6152   GST_LOG_OBJECT (demux, "Offset %" G_GUINT64_FORMAT ", Element id 0x%x, "
6153       "size %" G_GUINT64_FORMAT ", needed %d, available %d",
6154       demux->common.offset, id, length, needed, available);
6155
6156   if (needed > available)
6157     return GST_FLOW_OK;
6158
6159   ret = gst_matroska_demux_parse_id (demux, id, length, needed);
6160   if (ret == GST_FLOW_EOS) {
6161     /* need more data */
6162     return GST_FLOW_OK;
6163   } else if (ret != GST_FLOW_OK) {
6164     return ret;
6165   } else
6166     goto next;
6167 }
6168
6169 static gboolean
6170 gst_matroska_demux_handle_sink_event (GstPad * pad, GstObject * parent,
6171     GstEvent * event)
6172 {
6173   gboolean res = TRUE;
6174   GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (parent);
6175
6176   GST_DEBUG_OBJECT (demux,
6177       "have event type %s: %p on sink pad", GST_EVENT_TYPE_NAME (event), event);
6178
6179   switch (GST_EVENT_TYPE (event)) {
6180     case GST_EVENT_SEGMENT:
6181     {
6182       const GstSegment *segment;
6183
6184       /* some debug output */
6185       gst_event_parse_segment (event, &segment);
6186       /* FIXME: do we need to update segment base here (like accum in 0.10)? */
6187       GST_DEBUG_OBJECT (demux,
6188           "received format %d segment %" GST_SEGMENT_FORMAT, segment->format,
6189           segment);
6190
6191       if (demux->common.state < GST_MATROSKA_READ_STATE_DATA) {
6192         GST_DEBUG_OBJECT (demux, "still starting");
6193         goto exit;
6194       }
6195
6196       /* we only expect a BYTE segment, e.g. following a seek */
6197       if (segment->format != GST_FORMAT_BYTES) {
6198         GST_DEBUG_OBJECT (demux, "unsupported segment format, ignoring");
6199         goto exit;
6200       }
6201
6202       GST_DEBUG_OBJECT (demux, "clearing segment state");
6203       GST_OBJECT_LOCK (demux);
6204       /* clear current segment leftover */
6205       gst_adapter_clear (demux->common.adapter);
6206       /* and some streaming setup */
6207       demux->common.offset = segment->start;
6208       /* accumulate base based on current position */
6209       if (GST_CLOCK_TIME_IS_VALID (demux->common.segment.position))
6210         demux->common.segment.base +=
6211             (MAX (demux->common.segment.position, demux->stream_start_time)
6212             - demux->stream_start_time) / fabs (demux->common.segment.rate);
6213       /* do not know where we are;
6214        * need to come across a cluster and generate segment */
6215       demux->common.segment.position = GST_CLOCK_TIME_NONE;
6216       demux->cluster_time = GST_CLOCK_TIME_NONE;
6217       demux->cluster_offset = 0;
6218       demux->cluster_prevsize = 0;
6219       demux->need_segment = TRUE;
6220       demux->segment_seqnum = gst_event_get_seqnum (event);
6221       /* but keep some of the upstream segment */
6222       demux->common.segment.rate = segment->rate;
6223       demux->common.segment.flags = segment->flags;
6224       /* also check if need to keep some of the requested seek position */
6225       if (demux->seek_offset == segment->start) {
6226         GST_DEBUG_OBJECT (demux, "position matches requested seek");
6227         demux->common.segment.position = demux->requested_seek_time;
6228       } else {
6229         GST_DEBUG_OBJECT (demux, "unexpected segment position");
6230       }
6231       demux->requested_seek_time = GST_CLOCK_TIME_NONE;
6232       demux->seek_offset = -1;
6233       GST_OBJECT_UNLOCK (demux);
6234     exit:
6235       /* chain will send initial segment after pads have been added,
6236        * or otherwise come up with one */
6237       GST_DEBUG_OBJECT (demux, "eating event");
6238       gst_event_unref (event);
6239       res = TRUE;
6240       break;
6241     }
6242     case GST_EVENT_EOS:
6243     {
6244       if (demux->common.state != GST_MATROSKA_READ_STATE_DATA
6245           && demux->common.state != GST_MATROSKA_READ_STATE_SCANNING) {
6246         gst_event_unref (event);
6247         GST_ELEMENT_ERROR (demux, STREAM, DEMUX,
6248             (NULL), ("got eos and didn't receive a complete header object"));
6249       } else if (demux->common.num_streams == 0) {
6250         GST_ELEMENT_ERROR (demux, STREAM, DEMUX,
6251             (NULL), ("got eos but no streams (yet)"));
6252       } else {
6253         gst_matroska_demux_send_event (demux, event);
6254       }
6255       break;
6256     }
6257     case GST_EVENT_FLUSH_STOP:
6258     {
6259       guint64 dur;
6260
6261       gst_adapter_clear (demux->common.adapter);
6262       GST_OBJECT_LOCK (demux);
6263       gst_matroska_read_common_reset_streams (&demux->common,
6264           GST_CLOCK_TIME_NONE, TRUE);
6265       gst_flow_combiner_reset (demux->flowcombiner);
6266       dur = demux->common.segment.duration;
6267       gst_segment_init (&demux->common.segment, GST_FORMAT_TIME);
6268       demux->common.segment.duration = dur;
6269       demux->cluster_time = GST_CLOCK_TIME_NONE;
6270       demux->cluster_offset = 0;
6271       demux->cluster_prevsize = 0;
6272       GST_OBJECT_UNLOCK (demux);
6273       /* fall-through */
6274     }
6275     default:
6276       res = gst_pad_event_default (pad, parent, event);
6277       break;
6278   }
6279
6280   return res;
6281 }
6282
6283 static gboolean
6284 gst_matroska_demux_sink_activate (GstPad * sinkpad, GstObject * parent)
6285 {
6286   GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (parent);
6287   GstQuery *query;
6288   gboolean pull_mode = FALSE;
6289
6290   query = gst_query_new_scheduling ();
6291
6292   if (gst_pad_peer_query (sinkpad, query))
6293     pull_mode = gst_query_has_scheduling_mode_with_flags (query,
6294         GST_PAD_MODE_PULL, GST_SCHEDULING_FLAG_SEEKABLE);
6295
6296   gst_query_unref (query);
6297
6298   if (pull_mode) {
6299     GST_DEBUG ("going to pull mode");
6300     demux->streaming = FALSE;
6301     return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PULL, TRUE);
6302   } else {
6303     GST_DEBUG ("going to push (streaming) mode");
6304     demux->streaming = TRUE;
6305     return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
6306   }
6307 }
6308
6309 static gboolean
6310 gst_matroska_demux_sink_activate_mode (GstPad * sinkpad, GstObject * parent,
6311     GstPadMode mode, gboolean active)
6312 {
6313   switch (mode) {
6314     case GST_PAD_MODE_PULL:
6315       if (active) {
6316         /* if we have a scheduler we can start the task */
6317         gst_pad_start_task (sinkpad, (GstTaskFunction) gst_matroska_demux_loop,
6318             sinkpad, NULL);
6319       } else {
6320         gst_pad_stop_task (sinkpad);
6321       }
6322       return TRUE;
6323     case GST_PAD_MODE_PUSH:
6324       return TRUE;
6325     default:
6326       return FALSE;
6327   }
6328 }
6329
6330 static GstCaps *
6331 gst_matroska_demux_video_caps (GstMatroskaTrackVideoContext *
6332     videocontext, const gchar * codec_id, guint8 * data, guint size,
6333     gchar ** codec_name, guint32 * riff_fourcc)
6334 {
6335   GstMatroskaTrackContext *context = (GstMatroskaTrackContext *) videocontext;
6336   GstCaps *caps = NULL;
6337
6338   g_assert (videocontext != NULL);
6339   g_assert (codec_name != NULL);
6340
6341   if (riff_fourcc)
6342     *riff_fourcc = 0;
6343
6344   /* TODO: check if we have all codec types from matroska-ids.h
6345    *       check if we have to do more special things with codec_private
6346    *
6347    * Add support for
6348    *  GST_MATROSKA_CODEC_ID_VIDEO_QUICKTIME
6349    *  GST_MATROSKA_CODEC_ID_VIDEO_SNOW
6350    */
6351
6352   if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC)) {
6353     gst_riff_strf_vids *vids = NULL;
6354
6355     if (data) {
6356       GstBuffer *buf = NULL;
6357
6358       vids = (gst_riff_strf_vids *) data;
6359
6360       /* assure size is big enough */
6361       if (size < 24) {
6362         GST_WARNING ("Too small BITMAPINFOHEADER (%d bytes)", size);
6363         return NULL;
6364       }
6365       if (size < sizeof (gst_riff_strf_vids)) {
6366         vids = g_new (gst_riff_strf_vids, 1);
6367         memcpy (vids, data, size);
6368       }
6369
6370       context->dts_only = TRUE; /* VFW files only store DTS */
6371
6372       /* little-endian -> byte-order */
6373       vids->size = GUINT32_FROM_LE (vids->size);
6374       vids->width = GUINT32_FROM_LE (vids->width);
6375       vids->height = GUINT32_FROM_LE (vids->height);
6376       vids->planes = GUINT16_FROM_LE (vids->planes);
6377       vids->bit_cnt = GUINT16_FROM_LE (vids->bit_cnt);
6378       vids->compression = GUINT32_FROM_LE (vids->compression);
6379       vids->image_size = GUINT32_FROM_LE (vids->image_size);
6380       vids->xpels_meter = GUINT32_FROM_LE (vids->xpels_meter);
6381       vids->ypels_meter = GUINT32_FROM_LE (vids->ypels_meter);
6382       vids->num_colors = GUINT32_FROM_LE (vids->num_colors);
6383       vids->imp_colors = GUINT32_FROM_LE (vids->imp_colors);
6384
6385       if (size > sizeof (gst_riff_strf_vids)) { /* some extra_data */
6386         gsize offset = sizeof (gst_riff_strf_vids);
6387
6388         buf = gst_buffer_new_memdup ((guint8 *) vids + offset, size - offset);
6389       }
6390
6391       if (riff_fourcc)
6392         *riff_fourcc = vids->compression;
6393
6394       caps = gst_riff_create_video_caps (vids->compression, NULL, vids,
6395           buf, NULL, codec_name);
6396
6397       if (caps == NULL) {
6398         GST_WARNING ("Unhandled RIFF fourcc %" GST_FOURCC_FORMAT,
6399             GST_FOURCC_ARGS (vids->compression));
6400       } else {
6401         static GstStaticCaps intra_caps = GST_STATIC_CAPS ("image/jpeg; "
6402             "video/x-raw; image/png; video/x-dv; video/x-huffyuv; video/x-ffv; "
6403             "video/x-compressed-yuv");
6404         context->intra_only =
6405             gst_caps_can_intersect (gst_static_caps_get (&intra_caps), caps);
6406       }
6407
6408       if (buf)
6409         gst_buffer_unref (buf);
6410
6411       if (vids != (gst_riff_strf_vids *) data)
6412         g_free (vids);
6413     }
6414   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_UNCOMPRESSED)) {
6415     GstVideoInfo info;
6416     GstVideoFormat format;
6417
6418     gst_video_info_init (&info);
6419     switch (videocontext->fourcc) {
6420       case GST_MAKE_FOURCC ('I', '4', '2', '0'):
6421         format = GST_VIDEO_FORMAT_I420;
6422         break;
6423       case GST_MAKE_FOURCC ('Y', 'U', 'Y', '2'):
6424         format = GST_VIDEO_FORMAT_YUY2;
6425         break;
6426       case GST_MAKE_FOURCC ('Y', 'V', '1', '2'):
6427         format = GST_VIDEO_FORMAT_YV12;
6428         break;
6429       case GST_MAKE_FOURCC ('U', 'Y', 'V', 'Y'):
6430         format = GST_VIDEO_FORMAT_UYVY;
6431         break;
6432       case GST_MAKE_FOURCC ('A', 'Y', 'U', 'V'):
6433         format = GST_VIDEO_FORMAT_AYUV;
6434         break;
6435       case GST_MAKE_FOURCC ('Y', '8', '0', '0'):
6436       case GST_MAKE_FOURCC ('Y', '8', ' ', ' '):
6437         format = GST_VIDEO_FORMAT_GRAY8;
6438         break;
6439       case GST_MAKE_FOURCC ('R', 'G', 'B', 24):
6440         format = GST_VIDEO_FORMAT_RGB;
6441         break;
6442       case GST_MAKE_FOURCC ('B', 'G', 'R', 24):
6443         format = GST_VIDEO_FORMAT_BGR;
6444         break;
6445       default:
6446         GST_DEBUG ("Unknown fourcc %" GST_FOURCC_FORMAT,
6447             GST_FOURCC_ARGS (videocontext->fourcc));
6448         return NULL;
6449     }
6450
6451     context->intra_only = TRUE;
6452
6453     gst_video_info_set_format (&info, format, videocontext->pixel_width,
6454         videocontext->pixel_height);
6455     caps = gst_video_info_to_caps (&info);
6456     *codec_name = gst_pb_utils_get_codec_description (caps);
6457     context->alignment = 32;
6458   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_SP)) {
6459     caps = gst_caps_new_simple ("video/x-divx",
6460         "divxversion", G_TYPE_INT, 4, NULL);
6461     *codec_name = g_strdup ("MPEG-4 simple profile");
6462   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_ASP) ||
6463       !strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_AP)) {
6464     caps = gst_caps_new_simple ("video/mpeg",
6465         "mpegversion", G_TYPE_INT, 4,
6466         "systemstream", G_TYPE_BOOLEAN, FALSE, NULL);
6467     if (data) {
6468       GstBuffer *priv;
6469
6470       priv = gst_buffer_new_memdup (data, size);
6471       gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
6472       gst_buffer_unref (priv);
6473
6474       gst_codec_utils_mpeg4video_caps_set_level_and_profile (caps, data, size);
6475     }
6476     if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_ASP))
6477       *codec_name = g_strdup ("MPEG-4 advanced simple profile");
6478     else
6479       *codec_name = g_strdup ("MPEG-4 advanced profile");
6480   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MSMPEG4V3)) {
6481 #if 0
6482     caps = gst_caps_new_full (gst_structure_new ("video/x-divx",
6483             "divxversion", G_TYPE_INT, 3, NULL),
6484         gst_structure_new ("video/x-msmpeg",
6485             "msmpegversion", G_TYPE_INT, 43, NULL), NULL);
6486 #endif
6487     caps = gst_caps_new_simple ("video/x-msmpeg",
6488         "msmpegversion", G_TYPE_INT, 43, NULL);
6489     *codec_name = g_strdup ("Microsoft MPEG-4 v.3");
6490   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG1) ||
6491       !strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG2)) {
6492     gint mpegversion;
6493
6494     if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG1))
6495       mpegversion = 1;
6496     else
6497       mpegversion = 2;
6498
6499     caps = gst_caps_new_simple ("video/mpeg",
6500         "systemstream", G_TYPE_BOOLEAN, FALSE,
6501         "mpegversion", G_TYPE_INT, mpegversion, NULL);
6502     *codec_name = g_strdup_printf ("MPEG-%d video", mpegversion);
6503     context->postprocess_frame = gst_matroska_demux_add_mpeg_seq_header;
6504   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MJPEG)) {
6505     caps = gst_caps_new_empty_simple ("image/jpeg");
6506     *codec_name = g_strdup ("Motion-JPEG");
6507     context->intra_only = TRUE;
6508   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_AVC)) {
6509     caps = gst_caps_new_empty_simple ("video/x-h264");
6510     if (data) {
6511       GstBuffer *priv;
6512
6513       /* First byte is the version, second is the profile indication, and third
6514        * is the 5 contraint_set_flags and 3 reserved bits. Fourth byte is the
6515        * level indication. */
6516       gst_codec_utils_h264_caps_set_level_and_profile (caps, data + 1,
6517           size - 1);
6518
6519       priv = gst_buffer_new_memdup (data, size);
6520       gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
6521       gst_buffer_unref (priv);
6522
6523       gst_caps_set_simple (caps, "stream-format", G_TYPE_STRING, "avc",
6524           "alignment", G_TYPE_STRING, "au", NULL);
6525     } else {
6526       GST_WARNING ("No codec data found, assuming output is byte-stream");
6527       gst_caps_set_simple (caps, "stream-format", G_TYPE_STRING, "byte-stream",
6528           NULL);
6529     }
6530     *codec_name = g_strdup ("H264");
6531   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEGH_HEVC)) {
6532     caps = gst_caps_new_empty_simple ("video/x-h265");
6533     if (data) {
6534       GstBuffer *priv;
6535
6536       gst_codec_utils_h265_caps_set_level_tier_and_profile (caps, data + 1,
6537           size - 1);
6538
6539       priv = gst_buffer_new_memdup (data, size);
6540       gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
6541       gst_buffer_unref (priv);
6542
6543       gst_caps_set_simple (caps, "stream-format", G_TYPE_STRING, "hvc1",
6544           "alignment", G_TYPE_STRING, "au", NULL);
6545     } else {
6546       GST_WARNING ("No codec data found, assuming output is byte-stream");
6547       gst_caps_set_simple (caps, "stream-format", G_TYPE_STRING, "byte-stream",
6548           NULL);
6549     }
6550     *codec_name = g_strdup ("HEVC");
6551   } else if ((!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO1)) ||
6552       (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO2)) ||
6553       (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO3)) ||
6554       (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO4))) {
6555     gint rmversion = -1;
6556
6557     if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO1))
6558       rmversion = 1;
6559     else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO2))
6560       rmversion = 2;
6561     else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO3))
6562       rmversion = 3;
6563     else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO4))
6564       rmversion = 4;
6565
6566     caps = gst_caps_new_simple ("video/x-pn-realvideo",
6567         "rmversion", G_TYPE_INT, rmversion, NULL);
6568     GST_DEBUG ("data:%p, size:0x%x", data, size);
6569     /* We need to extract the extradata ! */
6570     if (data && (size >= 0x22)) {
6571       GstBuffer *priv;
6572       guint rformat;
6573       guint subformat;
6574
6575       subformat = GST_READ_UINT32_BE (data + 0x1a);
6576       rformat = GST_READ_UINT32_BE (data + 0x1e);
6577
6578       priv = gst_buffer_new_memdup (data + 0x1a, size - 0x1a);
6579       gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, "format",
6580           G_TYPE_INT, rformat, "subformat", G_TYPE_INT, subformat, NULL);
6581       gst_buffer_unref (priv);
6582
6583     }
6584     *codec_name = g_strdup_printf ("RealVideo %d.0", rmversion);
6585   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_THEORA)) {
6586     caps = gst_caps_new_empty_simple ("video/x-theora");
6587     context->stream_headers =
6588         gst_matroska_parse_xiph_stream_headers (context->codec_priv,
6589         context->codec_priv_size);
6590     /* FIXME: mark stream as broken and skip if there are no stream headers */
6591     context->send_stream_headers = TRUE;
6592   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_DIRAC)) {
6593     caps = gst_caps_new_empty_simple ("video/x-dirac");
6594     *codec_name = g_strdup_printf ("Dirac");
6595   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_VP8)) {
6596     caps = gst_caps_new_empty_simple ("video/x-vp8");
6597     if (videocontext->alpha_mode)
6598       gst_caps_set_simple (caps, "codec-alpha", G_TYPE_BOOLEAN, TRUE, NULL);
6599     *codec_name = g_strdup_printf ("On2 VP8");
6600   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_VP9)) {
6601     caps = gst_caps_new_empty_simple ("video/x-vp9");
6602     if (videocontext->alpha_mode)
6603       gst_caps_set_simple (caps, "codec-alpha", G_TYPE_BOOLEAN, TRUE, NULL);
6604     *codec_name = g_strdup_printf ("On2 VP9");
6605   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_AV1)) {
6606     caps = gst_caps_new_empty_simple ("video/x-av1");
6607     if (data) {
6608       GstBuffer *priv;
6609
6610       priv = gst_buffer_new_memdup (data, size);
6611       gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
6612       gst_buffer_unref (priv);
6613     } else {
6614       GST_WARNING ("No AV1 codec data found!");
6615     }
6616     *codec_name = g_strdup_printf ("AOM AV1");
6617   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_PRORES)) {
6618     guint32 fourcc;
6619     const gchar *variant, *variant_descr = "";
6620
6621     /* Expect a fourcc in the codec private data */
6622     if (!data || size < 4) {
6623       GST_WARNING ("No or too small PRORESS fourcc (%d bytes)", size);
6624       return NULL;
6625     }
6626
6627     fourcc = GST_STR_FOURCC (data);
6628     switch (fourcc) {
6629       case GST_MAKE_FOURCC ('a', 'p', 'c', 's'):
6630         variant_descr = " 4:2:2 LT";
6631         variant = "lt";
6632         break;
6633       case GST_MAKE_FOURCC ('a', 'p', 'c', 'h'):
6634         variant = "hq";
6635         variant_descr = " 4:2:2 HQ";
6636         break;
6637       case GST_MAKE_FOURCC ('a', 'p', '4', 'h'):
6638         variant = "4444";
6639         variant_descr = " 4:4:4:4";
6640         break;
6641       case GST_MAKE_FOURCC ('a', 'p', 'c', 'o'):
6642         variant = "proxy";
6643         variant_descr = " 4:2:2 Proxy";
6644         break;
6645       case GST_MAKE_FOURCC ('a', 'p', 'c', 'n'):
6646       default:
6647         variant = "standard";
6648         variant_descr = " 4:2:2 SD";
6649         break;
6650     }
6651
6652     GST_LOG ("Prores video, codec fourcc %" GST_FOURCC_FORMAT,
6653         GST_FOURCC_ARGS (fourcc));
6654
6655     caps = gst_caps_new_simple ("video/x-prores",
6656         "format", G_TYPE_STRING, variant, NULL);
6657     *codec_name = g_strdup_printf ("Apple ProRes%s", variant_descr);
6658     context->postprocess_frame = gst_matroska_demux_add_prores_header;
6659   } else {
6660     GST_WARNING ("Unknown codec '%s', cannot build Caps", codec_id);
6661     return NULL;
6662   }
6663
6664   if (caps != NULL) {
6665     int i;
6666     GstStructure *structure;
6667
6668     for (i = 0; i < gst_caps_get_size (caps); i++) {
6669       structure = gst_caps_get_structure (caps, i);
6670
6671       /* FIXME: use the real unit here! */
6672       GST_DEBUG ("video size %dx%d, target display size %dx%d (any unit)",
6673           videocontext->pixel_width,
6674           videocontext->pixel_height,
6675           videocontext->display_width, videocontext->display_height);
6676
6677       /* pixel width and height are the w and h of the video in pixels */
6678       if (videocontext->pixel_width > 0 && videocontext->pixel_height > 0) {
6679         gint w = videocontext->pixel_width;
6680         gint h = videocontext->pixel_height;
6681
6682         gst_structure_set (structure,
6683             "width", G_TYPE_INT, w, "height", G_TYPE_INT, h, NULL);
6684       }
6685
6686       if (videocontext->display_width > 0 || videocontext->display_height > 0) {
6687         int n, d;
6688
6689         if (videocontext->display_width <= 0)
6690           videocontext->display_width = videocontext->pixel_width;
6691         if (videocontext->display_height <= 0)
6692           videocontext->display_height = videocontext->pixel_height;
6693
6694         /* calculate the pixel aspect ratio using the display and pixel w/h */
6695         n = videocontext->display_width * videocontext->pixel_height;
6696         d = videocontext->display_height * videocontext->pixel_width;
6697         GST_DEBUG ("setting PAR to %d/%d", n, d);
6698         gst_structure_set (structure, "pixel-aspect-ratio",
6699             GST_TYPE_FRACTION,
6700             videocontext->display_width * videocontext->pixel_height,
6701             videocontext->display_height * videocontext->pixel_width, NULL);
6702       }
6703
6704       if (videocontext->default_fps > 0.0) {
6705         gint fps_n, fps_d;
6706
6707         gst_util_double_to_fraction (videocontext->default_fps, &fps_n, &fps_d);
6708
6709         GST_DEBUG ("using default fps %d/%d", fps_n, fps_d);
6710
6711         gst_structure_set (structure, "framerate", GST_TYPE_FRACTION, fps_n,
6712             fps_d, NULL);
6713       } else if (context->default_duration > 0) {
6714         int fps_n, fps_d;
6715
6716         gst_video_guess_framerate (context->default_duration, &fps_n, &fps_d);
6717
6718         GST_INFO ("using default duration %" G_GUINT64_FORMAT
6719             " framerate %d/%d", context->default_duration, fps_n, fps_d);
6720
6721         gst_structure_set (structure, "framerate", GST_TYPE_FRACTION,
6722             fps_n, fps_d, NULL);
6723       } else {
6724         gst_structure_set (structure, "framerate", GST_TYPE_FRACTION,
6725             0, 1, NULL);
6726       }
6727
6728       switch (videocontext->interlace_mode) {
6729         case GST_MATROSKA_INTERLACE_MODE_PROGRESSIVE:
6730           gst_structure_set (structure,
6731               "interlace-mode", G_TYPE_STRING, "progressive", NULL);
6732           break;
6733         case GST_MATROSKA_INTERLACE_MODE_INTERLACED:
6734           gst_structure_set (structure,
6735               "interlace-mode", G_TYPE_STRING, "interleaved", NULL);
6736
6737           if (videocontext->field_order != GST_VIDEO_FIELD_ORDER_UNKNOWN)
6738             gst_structure_set (structure, "field-order", G_TYPE_STRING,
6739                 gst_video_field_order_to_string (videocontext->field_order),
6740                 NULL);
6741           break;
6742         default:
6743           break;
6744       }
6745     }
6746     if (videocontext->multiview_mode != GST_VIDEO_MULTIVIEW_MODE_NONE) {
6747       if (gst_video_multiview_guess_half_aspect (videocontext->multiview_mode,
6748               videocontext->pixel_width, videocontext->pixel_height,
6749               videocontext->display_width * videocontext->pixel_height,
6750               videocontext->display_height * videocontext->pixel_width)) {
6751         videocontext->multiview_flags |= GST_VIDEO_MULTIVIEW_FLAGS_HALF_ASPECT;
6752       }
6753       gst_caps_set_simple (caps,
6754           "multiview-mode", G_TYPE_STRING,
6755           gst_video_multiview_mode_to_caps_string
6756           (videocontext->multiview_mode), "multiview-flags",
6757           GST_TYPE_VIDEO_MULTIVIEW_FLAGSET, videocontext->multiview_flags,
6758           GST_FLAG_SET_MASK_EXACT, NULL);
6759     }
6760
6761     if (videocontext->colorimetry.range != GST_VIDEO_COLOR_RANGE_UNKNOWN ||
6762         videocontext->colorimetry.matrix != GST_VIDEO_COLOR_MATRIX_UNKNOWN ||
6763         videocontext->colorimetry.transfer != GST_VIDEO_TRANSFER_UNKNOWN ||
6764         videocontext->colorimetry.primaries !=
6765         GST_VIDEO_COLOR_PRIMARIES_UNKNOWN) {
6766       gchar *colorimetry =
6767           gst_video_colorimetry_to_string (&videocontext->colorimetry);
6768       gst_caps_set_simple (caps, "colorimetry", G_TYPE_STRING, colorimetry,
6769           NULL);
6770       GST_DEBUG ("setting colorimetry to %s", colorimetry);
6771       g_free (colorimetry);
6772     }
6773
6774     if (videocontext->mastering_display_info_present) {
6775       if (!gst_video_mastering_display_info_add_to_caps
6776           (&videocontext->mastering_display_info, caps)) {
6777         GST_WARNING ("couldn't set mastering display info to caps");
6778       }
6779     }
6780
6781     if (videocontext->content_light_level.max_content_light_level &&
6782         videocontext->content_light_level.max_frame_average_light_level) {
6783       if (!gst_video_content_light_level_add_to_caps
6784           (&videocontext->content_light_level, caps)) {
6785         GST_WARNING ("couldn't set content light level to caps");
6786       }
6787     }
6788
6789     caps = gst_caps_simplify (caps);
6790   }
6791
6792   return caps;
6793 }
6794
6795 /*
6796  * Some AAC specific code... *sigh*
6797  * FIXME: maybe we should use '15' and code the sample rate explicitly
6798  * if the sample rate doesn't match the predefined rates exactly? (tpm)
6799  */
6800
6801 static gint
6802 aac_rate_idx (gint rate)
6803 {
6804   if (92017 <= rate)
6805     return 0;
6806   else if (75132 <= rate)
6807     return 1;
6808   else if (55426 <= rate)
6809     return 2;
6810   else if (46009 <= rate)
6811     return 3;
6812   else if (37566 <= rate)
6813     return 4;
6814   else if (27713 <= rate)
6815     return 5;
6816   else if (23004 <= rate)
6817     return 6;
6818   else if (18783 <= rate)
6819     return 7;
6820   else if (13856 <= rate)
6821     return 8;
6822   else if (11502 <= rate)
6823     return 9;
6824   else if (9391 <= rate)
6825     return 10;
6826   else
6827     return 11;
6828 }
6829
6830 static gint
6831 aac_profile_idx (const gchar * codec_id)
6832 {
6833   gint profile;
6834
6835   if (strlen (codec_id) <= 12)
6836     profile = 3;
6837   else if (!strncmp (&codec_id[12], "MAIN", 4))
6838     profile = 0;
6839   else if (!strncmp (&codec_id[12], "LC", 2))
6840     profile = 1;
6841   else if (!strncmp (&codec_id[12], "SSR", 3))
6842     profile = 2;
6843   else
6844     profile = 3;
6845
6846   return profile;
6847 }
6848
6849 static guint
6850 round_up_pow2 (guint n)
6851 {
6852   n = n - 1;
6853   n = n | (n >> 1);
6854   n = n | (n >> 2);
6855   n = n | (n >> 4);
6856   n = n | (n >> 8);
6857   n = n | (n >> 16);
6858   return n + 1;
6859 }
6860
6861 #define AAC_SYNC_EXTENSION_TYPE 0x02b7
6862
6863 static GstCaps *
6864 gst_matroska_demux_audio_caps (GstMatroskaTrackAudioContext *
6865     audiocontext, const gchar * codec_id, guint8 * data, guint size,
6866     gchar ** codec_name, guint16 * riff_audio_fmt, GstClockTime * lead_in_ts)
6867 {
6868   GstMatroskaTrackContext *context = (GstMatroskaTrackContext *) audiocontext;
6869   GstCaps *caps = NULL;
6870   guint lead_in = 0;
6871   /* Max potential blocksize causing the longest possible lead_in_ts need, as
6872    * we don't have the exact number parsed out here */
6873   guint max_blocksize = 0;
6874   /* Original samplerate before SBR multiplications, as parsers would use */
6875   guint rate = audiocontext->samplerate;
6876
6877   g_assert (audiocontext != NULL);
6878   g_assert (codec_name != NULL);
6879
6880   if (riff_audio_fmt)
6881     *riff_audio_fmt = 0;
6882
6883   /* TODO: check if we have all codec types from matroska-ids.h
6884    *       check if we have to do more special things with codec_private
6885    *       check if we need bitdepth in different places too
6886    *       implement channel position magic
6887    * Add support for:
6888    *  GST_MATROSKA_CODEC_ID_AUDIO_AC3_BSID9
6889    *  GST_MATROSKA_CODEC_ID_AUDIO_AC3_BSID10
6890    *  GST_MATROSKA_CODEC_ID_AUDIO_QUICKTIME_QDMC
6891    *  GST_MATROSKA_CODEC_ID_AUDIO_QUICKTIME_QDM2
6892    */
6893
6894   if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L1) ||
6895       !strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L2) ||
6896       !strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L3)) {
6897     gint layer;
6898
6899     if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L1))
6900       layer = 1;
6901     else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L2))
6902       layer = 2;
6903     else
6904       layer = 3;
6905
6906     lead_in = 30;               /* Could mp2 need as much too? */
6907     max_blocksize = 1152;
6908     caps = gst_caps_new_simple ("audio/mpeg",
6909         "mpegversion", G_TYPE_INT, 1, "layer", G_TYPE_INT, layer, NULL);
6910     *codec_name = g_strdup_printf ("MPEG-1 layer %d", layer);
6911   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_PCM_INT_BE) ||
6912       !strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_PCM_INT_LE)) {
6913     gboolean sign;
6914     gint endianness;
6915     GstAudioFormat format;
6916
6917     sign = (audiocontext->bitdepth != 8);
6918     if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_PCM_INT_BE))
6919       endianness = G_BIG_ENDIAN;
6920     else
6921       endianness = G_LITTLE_ENDIAN;
6922
6923     format = gst_audio_format_build_integer (sign, endianness,
6924         audiocontext->bitdepth, audiocontext->bitdepth);
6925
6926     /* FIXME: Channel mask and reordering */
6927     caps = gst_caps_new_simple ("audio/x-raw",
6928         "format", G_TYPE_STRING, gst_audio_format_to_string (format),
6929         "layout", G_TYPE_STRING, "interleaved",
6930         "channel-mask", GST_TYPE_BITMASK,
6931         gst_audio_channel_get_fallback_mask (audiocontext->channels), NULL);
6932
6933     *codec_name = g_strdup_printf ("Raw %d-bit PCM audio",
6934         audiocontext->bitdepth);
6935     context->alignment = GST_ROUND_UP_8 (audiocontext->bitdepth) / 8;
6936     context->alignment = round_up_pow2 (context->alignment);
6937   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_PCM_FLOAT)) {
6938     const gchar *format;
6939     if (audiocontext->bitdepth == 32)
6940       format = "F32LE";
6941     else
6942       format = "F64LE";
6943     /* FIXME: Channel mask and reordering */
6944     caps = gst_caps_new_simple ("audio/x-raw",
6945         "format", G_TYPE_STRING, format,
6946         "layout", G_TYPE_STRING, "interleaved",
6947         "channel-mask", GST_TYPE_BITMASK,
6948         gst_audio_channel_get_fallback_mask (audiocontext->channels), NULL);
6949     *codec_name = g_strdup_printf ("Raw %d-bit floating-point audio",
6950         audiocontext->bitdepth);
6951     context->alignment = audiocontext->bitdepth / 8;
6952     context->alignment = round_up_pow2 (context->alignment);
6953   } else if (!strncmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_AC3,
6954           strlen (GST_MATROSKA_CODEC_ID_AUDIO_AC3))) {
6955     lead_in = 2;
6956     max_blocksize = 1536;
6957     caps = gst_caps_new_simple ("audio/x-ac3",
6958         "framed", G_TYPE_BOOLEAN, TRUE, NULL);
6959     *codec_name = g_strdup ("AC-3 audio");
6960   } else if (!strncmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_EAC3,
6961           strlen (GST_MATROSKA_CODEC_ID_AUDIO_EAC3))) {
6962     lead_in = 2;
6963     max_blocksize = 1536;
6964     caps = gst_caps_new_simple ("audio/x-eac3",
6965         "framed", G_TYPE_BOOLEAN, TRUE, NULL);
6966     *codec_name = g_strdup ("E-AC-3 audio");
6967   } else if (!strncmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_TRUEHD,
6968           strlen (GST_MATROSKA_CODEC_ID_AUDIO_TRUEHD))) {
6969     caps = gst_caps_new_empty_simple ("audio/x-true-hd");
6970     *codec_name = g_strdup ("Dolby TrueHD");
6971   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_DTS)) {
6972     caps = gst_caps_new_empty_simple ("audio/x-dts");
6973     *codec_name = g_strdup ("DTS audio");
6974   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_VORBIS)) {
6975     caps = gst_caps_new_empty_simple ("audio/x-vorbis");
6976     context->stream_headers =
6977         gst_matroska_parse_xiph_stream_headers (context->codec_priv,
6978         context->codec_priv_size);
6979     /* FIXME: mark stream as broken and skip if there are no stream headers */
6980     context->send_stream_headers = TRUE;
6981   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_FLAC)) {
6982     caps = gst_caps_new_empty_simple ("audio/x-flac");
6983     context->stream_headers =
6984         gst_matroska_parse_flac_stream_headers (context->codec_priv,
6985         context->codec_priv_size);
6986     /* FIXME: mark stream as broken and skip if there are no stream headers */
6987     context->send_stream_headers = TRUE;
6988   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_SPEEX)) {
6989     caps = gst_caps_new_empty_simple ("audio/x-speex");
6990     context->stream_headers =
6991         gst_matroska_parse_speex_stream_headers (context->codec_priv,
6992         context->codec_priv_size);
6993     /* FIXME: mark stream as broken and skip if there are no stream headers */
6994     context->send_stream_headers = TRUE;
6995   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_OPUS)) {
6996     GstBuffer *tmp;
6997
6998     if (context->codec_priv_size >= 19) {
6999       if (audiocontext->samplerate)
7000         GST_WRITE_UINT32_LE ((guint8 *) context->codec_priv + 12,
7001             audiocontext->samplerate);
7002       if (context->codec_delay) {
7003         guint64 delay =
7004             gst_util_uint64_scale_round (context->codec_delay, 48000,
7005             GST_SECOND);
7006         GST_WRITE_UINT16_LE ((guint8 *) context->codec_priv + 10, delay);
7007       }
7008
7009       tmp =
7010           gst_buffer_new_memdup (context->codec_priv, context->codec_priv_size);
7011       caps = gst_codec_utils_opus_create_caps_from_header (tmp, NULL);
7012       gst_buffer_unref (tmp);
7013       *codec_name = g_strdup ("Opus");
7014     } else if (context->codec_priv_size == 0) {
7015       GST_WARNING ("No Opus codec data found, trying to create one");
7016       if (audiocontext->channels <= 2) {
7017         guint8 streams, coupled, channels;
7018         guint32 samplerate;
7019
7020         samplerate =
7021             audiocontext->samplerate == 0 ? 48000 : audiocontext->samplerate;
7022         rate = samplerate;
7023         channels = audiocontext->channels == 0 ? 2 : audiocontext->channels;
7024         if (channels == 1) {
7025           streams = 1;
7026           coupled = 0;
7027         } else {
7028           streams = 1;
7029           coupled = 1;
7030         }
7031
7032         caps =
7033             gst_codec_utils_opus_create_caps (samplerate, channels, 0, streams,
7034             coupled, NULL);
7035         if (caps) {
7036           *codec_name = g_strdup ("Opus");
7037         } else {
7038           GST_WARNING ("Failed to create Opus caps from audio context");
7039         }
7040       } else {
7041         GST_WARNING ("No Opus codec data, and not enough info to create one");
7042       }
7043     } else {
7044       GST_WARNING ("Invalid Opus codec data size (got %" G_GSIZE_FORMAT
7045           ", expected 19)", context->codec_priv_size);
7046     }
7047   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_ACM)) {
7048     gst_riff_strf_auds auds;
7049
7050     if (data && size >= 18) {
7051       GstBuffer *codec_data = NULL;
7052
7053       /* little-endian -> byte-order */
7054       auds.format = GST_READ_UINT16_LE (data);
7055       auds.channels = GST_READ_UINT16_LE (data + 2);
7056       auds.rate = GST_READ_UINT32_LE (data + 4);
7057       auds.av_bps = GST_READ_UINT32_LE (data + 8);
7058       auds.blockalign = GST_READ_UINT16_LE (data + 12);
7059       auds.bits_per_sample = GST_READ_UINT16_LE (data + 16);
7060
7061       /* 18 is the waveformatex size */
7062       if (size > 18) {
7063         codec_data = gst_buffer_new_wrapped_full (GST_MEMORY_FLAG_READONLY,
7064             data + 18, size - 18, 0, size - 18, NULL, NULL);
7065       }
7066
7067       if (riff_audio_fmt)
7068         *riff_audio_fmt = auds.format;
7069
7070       /* FIXME: Handle reorder map */
7071       caps = gst_riff_create_audio_caps (auds.format, NULL, &auds, codec_data,
7072           NULL, codec_name, NULL);
7073       if (codec_data)
7074         gst_buffer_unref (codec_data);
7075
7076       if (caps == NULL) {
7077         GST_WARNING ("Unhandled RIFF audio format 0x%02x", auds.format);
7078       }
7079     } else {
7080       GST_WARNING ("Invalid codec data size (%d expected, got %d)", 18, size);
7081     }
7082   } else if (g_str_has_prefix (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_AAC)) {
7083     GstBuffer *priv = NULL;
7084     gint mpegversion;
7085     gint rate_idx, profile;
7086     guint8 *data = NULL;
7087
7088     /* unspecified AAC profile with opaque private codec data */
7089     if (strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_AAC) == 0) {
7090       if (context->codec_priv_size >= 2) {
7091         guint obj_type, freq_index, explicit_freq_bytes = 0;
7092
7093         codec_id = GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG4;
7094         mpegversion = 4;
7095         freq_index = (GST_READ_UINT16_BE (context->codec_priv) & 0x780) >> 7;
7096         obj_type = (GST_READ_UINT16_BE (context->codec_priv) & 0xF800) >> 11;
7097         if (freq_index == 15)
7098           explicit_freq_bytes = 3;
7099         GST_DEBUG ("obj_type = %u, freq_index = %u", obj_type, freq_index);
7100         priv = gst_buffer_new_memdup (context->codec_priv,
7101             context->codec_priv_size);
7102         /* assume SBR if samplerate <= 24kHz */
7103         if (obj_type == 5 || (freq_index >= 6 && freq_index != 15) ||
7104             (context->codec_priv_size == (5 + explicit_freq_bytes))) {
7105           /* TODO: Commonly aacparse will reset the rate in caps to
7106            * non-multiplied - which one is correct? */
7107           audiocontext->samplerate *= 2;
7108         }
7109       } else {
7110         GST_WARNING ("Opaque A_AAC codec ID, but no codec private data");
7111         /* this is pretty broken;
7112          * maybe we need to make up some default private,
7113          * or maybe ADTS data got dumped in.
7114          * Let's set up some private data now, and check actual data later */
7115         /* just try this and see what happens ... */
7116         codec_id = GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG4;
7117         context->postprocess_frame = gst_matroska_demux_check_aac;
7118       }
7119     }
7120
7121     /* make up decoder-specific data if it is not supplied */
7122     if (priv == NULL) {
7123       GstMapInfo map;
7124
7125       priv = gst_buffer_new_allocate (NULL, 5, NULL);
7126       gst_buffer_map (priv, &map, GST_MAP_WRITE);
7127       data = map.data;
7128       rate_idx = aac_rate_idx (audiocontext->samplerate);
7129       profile = aac_profile_idx (codec_id);
7130
7131       data[0] = ((profile + 1) << 3) | ((rate_idx & 0xE) >> 1);
7132       data[1] = ((rate_idx & 0x1) << 7) | (audiocontext->channels << 3);
7133
7134       if (!strncmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG2,
7135               strlen (GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG2))) {
7136         mpegversion = 2;
7137         gst_buffer_unmap (priv, &map);
7138         gst_buffer_set_size (priv, 2);
7139       } else if (!strncmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG4,
7140               strlen (GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG4))) {
7141         mpegversion = 4;
7142
7143         if (g_strrstr (codec_id, "SBR")) {
7144           /* HE-AAC (aka SBR AAC) */
7145           audiocontext->samplerate *= 2;
7146           rate_idx = aac_rate_idx (audiocontext->samplerate);
7147           data[2] = AAC_SYNC_EXTENSION_TYPE >> 3;
7148           data[3] = ((AAC_SYNC_EXTENSION_TYPE & 0x07) << 5) | 5;
7149           data[4] = (1 << 7) | (rate_idx << 3);
7150           gst_buffer_unmap (priv, &map);
7151         } else {
7152           gst_buffer_unmap (priv, &map);
7153           gst_buffer_set_size (priv, 2);
7154         }
7155       } else {
7156         gst_buffer_unmap (priv, &map);
7157         gst_buffer_unref (priv);
7158         priv = NULL;
7159         GST_ERROR ("Unknown AAC profile and no codec private data");
7160       }
7161     }
7162
7163     if (priv) {
7164       lead_in = 2;
7165       max_blocksize = 1024;
7166       caps = gst_caps_new_simple ("audio/mpeg",
7167           "mpegversion", G_TYPE_INT, mpegversion,
7168           "framed", G_TYPE_BOOLEAN, TRUE,
7169           "stream-format", G_TYPE_STRING, "raw", NULL);
7170       gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
7171       if (context->codec_priv && context->codec_priv_size > 0)
7172         gst_codec_utils_aac_caps_set_level_and_profile (caps,
7173             context->codec_priv, context->codec_priv_size);
7174       *codec_name = g_strdup_printf ("MPEG-%d AAC audio", mpegversion);
7175       gst_buffer_unref (priv);
7176     }
7177   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_TTA)) {
7178     caps = gst_caps_new_simple ("audio/x-tta",
7179         "width", G_TYPE_INT, audiocontext->bitdepth, NULL);
7180     *codec_name = g_strdup ("TTA audio");
7181   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_WAVPACK4)) {
7182     caps = gst_caps_new_simple ("audio/x-wavpack",
7183         "width", G_TYPE_INT, audiocontext->bitdepth,
7184         "framed", G_TYPE_BOOLEAN, TRUE, NULL);
7185     *codec_name = g_strdup ("Wavpack audio");
7186     context->postprocess_frame = gst_matroska_demux_add_wvpk_header;
7187     audiocontext->wvpk_block_index = 0;
7188   } else if ((!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_14_4)) ||
7189       (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_28_8)) ||
7190       (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_COOK))) {
7191     gint raversion = -1;
7192
7193     if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_14_4))
7194       raversion = 1;
7195     else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_COOK))
7196       raversion = 8;
7197     else
7198       raversion = 2;
7199
7200     caps = gst_caps_new_simple ("audio/x-pn-realaudio",
7201         "raversion", G_TYPE_INT, raversion, NULL);
7202     /* Extract extra information from caps, mapping varies based on codec */
7203     if (data && (size >= 0x50)) {
7204       GstBuffer *priv;
7205       guint flavor;
7206       guint packet_size;
7207       guint height;
7208       guint leaf_size;
7209       guint sample_width;
7210       guint extra_data_size;
7211
7212       GST_DEBUG ("real audio raversion:%d", raversion);
7213       if (raversion == 8) {
7214         /* COOK */
7215         flavor = GST_READ_UINT16_BE (data + 22);
7216         packet_size = GST_READ_UINT32_BE (data + 24);
7217         height = GST_READ_UINT16_BE (data + 40);
7218         leaf_size = GST_READ_UINT16_BE (data + 44);
7219         sample_width = GST_READ_UINT16_BE (data + 58);
7220         extra_data_size = GST_READ_UINT32_BE (data + 74);
7221
7222         GST_DEBUG
7223             ("flavor:%d, packet_size:%d, height:%d, leaf_size:%d, sample_width:%d, extra_data_size:%d",
7224             flavor, packet_size, height, leaf_size, sample_width,
7225             extra_data_size);
7226         gst_caps_set_simple (caps, "flavor", G_TYPE_INT, flavor, "packet_size",
7227             G_TYPE_INT, packet_size, "height", G_TYPE_INT, height, "leaf_size",
7228             G_TYPE_INT, leaf_size, "width", G_TYPE_INT, sample_width, NULL);
7229
7230         if ((size - 78) >= extra_data_size) {
7231           priv = gst_buffer_new_memdup (data + 78, extra_data_size);
7232           gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
7233           gst_buffer_unref (priv);
7234         }
7235       }
7236     }
7237
7238     *codec_name = g_strdup_printf ("RealAudio %d.0", raversion);
7239   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_SIPR)) {
7240     caps = gst_caps_new_empty_simple ("audio/x-sipro");
7241     *codec_name = g_strdup ("Sipro/ACELP.NET Voice Codec");
7242   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_RALF)) {
7243     caps = gst_caps_new_empty_simple ("audio/x-ralf-mpeg4-generic");
7244     *codec_name = g_strdup ("Real Audio Lossless");
7245   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_ATRC)) {
7246     caps = gst_caps_new_empty_simple ("audio/x-vnd.sony.atrac3");
7247     *codec_name = g_strdup ("Sony ATRAC3");
7248   } else {
7249     GST_WARNING ("Unknown codec '%s', cannot build Caps", codec_id);
7250     return NULL;
7251   }
7252
7253   if (caps != NULL) {
7254     if (audiocontext->samplerate > 0 && audiocontext->channels > 0) {
7255       gint i;
7256
7257       for (i = 0; i < gst_caps_get_size (caps); i++) {
7258         gst_structure_set (gst_caps_get_structure (caps, i),
7259             "channels", G_TYPE_INT, audiocontext->channels,
7260             "rate", G_TYPE_INT, audiocontext->samplerate, NULL);
7261       }
7262     }
7263
7264     caps = gst_caps_simplify (caps);
7265   }
7266
7267   if (lead_in_ts && lead_in && max_blocksize && rate) {
7268     *lead_in_ts =
7269         gst_util_uint64_scale (GST_SECOND, max_blocksize * lead_in, rate);
7270   }
7271
7272   return caps;
7273 }
7274
7275 static GstCaps *
7276 gst_matroska_demux_subtitle_caps (GstMatroskaTrackSubtitleContext *
7277     subtitlecontext, const gchar * codec_id, gpointer data, guint size)
7278 {
7279   GstCaps *caps = NULL;
7280   GstMatroskaTrackContext *context =
7281       (GstMatroskaTrackContext *) subtitlecontext;
7282
7283   /* for backwards compatibility */
7284   if (!g_ascii_strcasecmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_ASCII))
7285     codec_id = GST_MATROSKA_CODEC_ID_SUBTITLE_UTF8;
7286   else if (!g_ascii_strcasecmp (codec_id, "S_SSA"))
7287     codec_id = GST_MATROSKA_CODEC_ID_SUBTITLE_SSA;
7288   else if (!g_ascii_strcasecmp (codec_id, "S_ASS"))
7289     codec_id = GST_MATROSKA_CODEC_ID_SUBTITLE_ASS;
7290   else if (!g_ascii_strcasecmp (codec_id, "S_USF"))
7291     codec_id = GST_MATROSKA_CODEC_ID_SUBTITLE_USF;
7292
7293   /* TODO: Add GST_MATROSKA_CODEC_ID_SUBTITLE_BMP support
7294    * Check if we have to do something with codec_private */
7295   if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_UTF8)) {
7296     /* well, plain text simply does not have a lot of markup ... */
7297     caps = gst_caps_new_simple ("text/x-raw", "format", G_TYPE_STRING,
7298         "pango-markup", NULL);
7299     context->postprocess_frame = gst_matroska_demux_check_subtitle_buffer;
7300     subtitlecontext->check_markup = TRUE;
7301   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_SSA)) {
7302     caps = gst_caps_new_empty_simple ("application/x-ssa");
7303     context->postprocess_frame = gst_matroska_demux_check_subtitle_buffer;
7304     subtitlecontext->check_markup = FALSE;
7305   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_ASS)) {
7306     caps = gst_caps_new_empty_simple ("application/x-ass");
7307     context->postprocess_frame = gst_matroska_demux_check_subtitle_buffer;
7308     subtitlecontext->check_markup = FALSE;
7309   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_USF)) {
7310     caps = gst_caps_new_empty_simple ("application/x-usf");
7311     context->postprocess_frame = gst_matroska_demux_check_subtitle_buffer;
7312     subtitlecontext->check_markup = FALSE;
7313   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_VOBSUB)) {
7314     caps = gst_caps_new_empty_simple ("subpicture/x-dvd");
7315     ((GstMatroskaTrackContext *) subtitlecontext)->send_dvd_event = TRUE;
7316   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_HDMVPGS)) {
7317     caps = gst_caps_new_empty_simple ("subpicture/x-pgs");
7318   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_KATE)) {
7319     caps = gst_caps_new_empty_simple ("subtitle/x-kate");
7320     context->stream_headers =
7321         gst_matroska_parse_xiph_stream_headers (context->codec_priv,
7322         context->codec_priv_size);
7323     /* FIXME: mark stream as broken and skip if there are no stream headers */
7324     context->send_stream_headers = TRUE;
7325   } else {
7326     GST_DEBUG ("Unknown subtitle stream: codec_id='%s'", codec_id);
7327     caps = gst_caps_new_empty_simple ("application/x-subtitle-unknown");
7328   }
7329
7330   if (data != NULL && size > 0) {
7331     GstBuffer *buf;
7332
7333     buf = gst_buffer_new_memdup (data, size);
7334     gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, buf, NULL);
7335     gst_buffer_unref (buf);
7336   }
7337
7338   return caps;
7339 }
7340
7341 #if 0
7342 static void
7343 gst_matroska_demux_set_index (GstElement * element, GstIndex * index)
7344 {
7345   GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (element);
7346
7347   GST_OBJECT_LOCK (demux);
7348   if (demux->common.element_index)
7349     gst_object_unref (demux->common.element_index);
7350   demux->common.element_index = index ? gst_object_ref (index) : NULL;
7351   GST_OBJECT_UNLOCK (demux);
7352   GST_DEBUG_OBJECT (demux, "Set index %" GST_PTR_FORMAT,
7353       demux->common.element_index);
7354 }
7355
7356 static GstIndex *
7357 gst_matroska_demux_get_index (GstElement * element)
7358 {
7359   GstIndex *result = NULL;
7360   GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (element);
7361
7362   GST_OBJECT_LOCK (demux);
7363   if (demux->common.element_index)
7364     result = gst_object_ref (demux->common.element_index);
7365   GST_OBJECT_UNLOCK (demux);
7366
7367   GST_DEBUG_OBJECT (demux, "Returning index %" GST_PTR_FORMAT, result);
7368
7369   return result;
7370 }
7371 #endif
7372
7373 static GstStateChangeReturn
7374 gst_matroska_demux_change_state (GstElement * element,
7375     GstStateChange transition)
7376 {
7377   GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (element);
7378   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
7379
7380   /* handle upwards state changes here */
7381   switch (transition) {
7382     default:
7383       break;
7384   }
7385
7386   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
7387
7388   /* handle downwards state changes */
7389   switch (transition) {
7390     case GST_STATE_CHANGE_PAUSED_TO_READY:
7391       gst_matroska_demux_reset (GST_ELEMENT (demux));
7392       break;
7393     default:
7394       break;
7395   }
7396
7397   return ret;
7398 }
7399
7400 static void
7401 gst_matroska_demux_set_property (GObject * object,
7402     guint prop_id, const GValue * value, GParamSpec * pspec)
7403 {
7404   GstMatroskaDemux *demux;
7405
7406   g_return_if_fail (GST_IS_MATROSKA_DEMUX (object));
7407   demux = GST_MATROSKA_DEMUX (object);
7408
7409   switch (prop_id) {
7410     case PROP_MAX_GAP_TIME:
7411       GST_OBJECT_LOCK (demux);
7412       demux->max_gap_time = g_value_get_uint64 (value);
7413       GST_OBJECT_UNLOCK (demux);
7414       break;
7415     case PROP_MAX_BACKTRACK_DISTANCE:
7416       GST_OBJECT_LOCK (demux);
7417       demux->max_backtrack_distance = g_value_get_uint (value);
7418       GST_OBJECT_UNLOCK (demux);
7419       break;
7420     default:
7421       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
7422       break;
7423   }
7424 }
7425
7426 static void
7427 gst_matroska_demux_get_property (GObject * object,
7428     guint prop_id, GValue * value, GParamSpec * pspec)
7429 {
7430   GstMatroskaDemux *demux;
7431
7432   g_return_if_fail (GST_IS_MATROSKA_DEMUX (object));
7433   demux = GST_MATROSKA_DEMUX (object);
7434
7435   switch (prop_id) {
7436     case PROP_MAX_GAP_TIME:
7437       GST_OBJECT_LOCK (demux);
7438       g_value_set_uint64 (value, demux->max_gap_time);
7439       GST_OBJECT_UNLOCK (demux);
7440       break;
7441     case PROP_MAX_BACKTRACK_DISTANCE:
7442       GST_OBJECT_LOCK (demux);
7443       g_value_set_uint (value, demux->max_backtrack_distance);
7444       GST_OBJECT_UNLOCK (demux);
7445       break;
7446     default:
7447       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
7448       break;
7449   }
7450 }
7451
7452 static const gchar *
7453 gst_matroska_track_encryption_algorithm_name (gint val)
7454 {
7455   GEnumValue *en;
7456   GEnumClass *enum_class =
7457       g_type_class_ref (MATROSKA_TRACK_ENCRYPTION_ALGORITHM_TYPE);
7458   en = g_enum_get_value (G_ENUM_CLASS (enum_class), val);
7459   return en ? en->value_nick : NULL;
7460 }
7461
7462 static const gchar *
7463 gst_matroska_track_encryption_cipher_mode_name (gint val)
7464 {
7465   GEnumValue *en;
7466   GEnumClass *enum_class =
7467       g_type_class_ref (MATROSKA_TRACK_ENCRYPTION_CIPHER_MODE_TYPE);
7468   en = g_enum_get_value (G_ENUM_CLASS (enum_class), val);
7469   return en ? en->value_nick : NULL;
7470 }
7471
7472 static const gchar *
7473 gst_matroska_track_encoding_scope_name (gint val)
7474 {
7475   GEnumValue *en;
7476   GEnumClass *enum_class =
7477       g_type_class_ref (MATROSKA_TRACK_ENCODING_SCOPE_TYPE);
7478
7479   en = g_enum_get_value (G_ENUM_CLASS (enum_class), val);
7480   return en ? en->value_nick : NULL;
7481 }