matroska: demux: update stream_start_time
[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     gboolean keep_seek_start = TRUE;
4615     GstEvent *protect_event;
4616
4617     stream = g_ptr_array_index (demux->common.src, stream_num);
4618
4619     if (cluster_time != GST_CLOCK_TIME_NONE) {
4620       /* FIXME: What to do with negative timestamps? Give timestamp 0 or -1?
4621        * Drop unless the lace contains timestamp 0? */
4622       if (time < 0 && (-time) > cluster_time) {
4623         lace_time = 0;
4624       } else {
4625         if (stream->timecodescale == 1.0)
4626           lace_time = (cluster_time + time) * demux->common.time_scale;
4627         else
4628           lace_time =
4629               gst_util_guint64_to_gdouble ((cluster_time + time) *
4630               demux->common.time_scale) * stream->timecodescale;
4631       }
4632     } else {
4633       lace_time = GST_CLOCK_TIME_NONE;
4634     }
4635     /* Send the GST_PROTECTION event */
4636     while ((protect_event = g_queue_pop_head (&stream->protection_event_queue))) {
4637       GST_TRACE_OBJECT (demux, "pushing protection event for stream %d:%s",
4638           stream->index, GST_STR_NULL (stream->name));
4639       gst_pad_push_event (stream->pad, protect_event);
4640     }
4641
4642     /* need to refresh segment info ASAP */
4643     if (GST_CLOCK_TIME_IS_VALID (lace_time)
4644         && GST_CLOCK_TIME_IS_VALID (demux->stream_start_time)
4645         && lace_time < demux->stream_start_time) {
4646       keep_seek_start =
4647           (demux->common.segment.start > demux->stream_start_time);
4648       demux->stream_start_time = lace_time;
4649       demux->need_segment = TRUE;
4650     }
4651
4652     if (GST_CLOCK_TIME_IS_VALID (lace_time) && demux->need_segment) {
4653       GstSegment *segment = &demux->common.segment;
4654       guint64 clace_time;
4655       GstEvent *segment_event;
4656
4657       if (!GST_CLOCK_TIME_IS_VALID (demux->stream_start_time)) {
4658         demux->stream_start_time = lace_time;
4659         GST_DEBUG_OBJECT (demux,
4660             "Setting stream start time to %" GST_TIME_FORMAT,
4661             GST_TIME_ARGS (lace_time));
4662       }
4663       clace_time = MAX (lace_time, demux->stream_start_time);
4664       if (keep_seek_start
4665           && GST_CLOCK_TIME_IS_VALID (demux->common.segment.position)
4666           && demux->common.segment.position != 0) {
4667         GST_DEBUG_OBJECT (demux, "using stored seek position %" GST_TIME_FORMAT,
4668             GST_TIME_ARGS (demux->common.segment.position));
4669         clace_time = demux->common.segment.position;
4670       }
4671       segment->start = clace_time;
4672       segment->stop = demux->common.segment.stop;
4673       segment->time = segment->start - demux->stream_start_time;
4674       segment->position = segment->start - demux->stream_start_time;
4675       GST_DEBUG_OBJECT (demux,
4676           "generated segment starting at %" GST_TIME_FORMAT ": %"
4677           GST_SEGMENT_FORMAT, GST_TIME_ARGS (lace_time), segment);
4678       /* now convey our segment notion downstream */
4679       segment_event = gst_event_new_segment (segment);
4680       if (demux->segment_seqnum)
4681         gst_event_set_seqnum (segment_event, demux->segment_seqnum);
4682       gst_matroska_demux_send_event (demux, segment_event);
4683       demux->need_segment = FALSE;
4684       demux->segment_seqnum = 0;
4685     }
4686
4687     /* send pending codec data headers for all streams,
4688      * before we perform sync across all streams */
4689     gst_matroska_demux_push_codec_data_all (demux);
4690
4691     if (block_duration != -1) {
4692       if (stream->timecodescale == 1.0)
4693         duration = gst_util_uint64_scale (block_duration,
4694             demux->common.time_scale, 1);
4695       else
4696         duration =
4697             gst_util_gdouble_to_guint64 (gst_util_guint64_to_gdouble
4698             (gst_util_uint64_scale (block_duration, demux->common.time_scale,
4699                     1)) * stream->timecodescale);
4700     } else if (stream->default_duration) {
4701       duration = stream->default_duration * laces;
4702     }
4703     /* else duration is diff between timecode of this and next block */
4704
4705     if (stream->type == GST_MATROSKA_TRACK_TYPE_VIDEO) {
4706       /* For SimpleBlock, look at the keyframe bit in flags. Otherwise,
4707          a ReferenceBlock implies that this is not a keyframe. In either
4708          case, it only makes sense for video streams. */
4709       if ((is_simpleblock && !(flags & 0x80)) || referenceblock) {
4710         delta_unit = TRUE;
4711         invisible_frame = ((flags & 0x08)) &&
4712             (!strcmp (stream->codec_id, GST_MATROSKA_CODEC_ID_VIDEO_VP8) ||
4713             !strcmp (stream->codec_id, GST_MATROSKA_CODEC_ID_VIDEO_VP9) ||
4714             !strcmp (stream->codec_id, GST_MATROSKA_CODEC_ID_VIDEO_AV1));
4715       }
4716
4717       /* If we're doing a keyframe-only trickmode, only push keyframes on video
4718        * streams */
4719       if (delta_unit
4720           && demux->common.segment.
4721           flags & GST_SEGMENT_FLAG_TRICKMODE_KEY_UNITS) {
4722         GST_LOG_OBJECT (demux, "Skipping non-keyframe on stream %d",
4723             stream->index);
4724         ret = GST_FLOW_OK;
4725         goto done;
4726       }
4727     }
4728
4729     for (n = 0; n < laces; n++) {
4730       GstBuffer *sub;
4731
4732       if (G_UNLIKELY (lace_size[n] > size)) {
4733         GST_WARNING_OBJECT (demux, "Invalid lace size");
4734         break;
4735       }
4736
4737       /* QoS for video track with an index. the assumption is that
4738          index entries point to keyframes, but if that is not true we
4739          will instead skip until the next keyframe. */
4740       if (GST_CLOCK_TIME_IS_VALID (lace_time) &&
4741           stream->type == GST_MATROSKA_TRACK_TYPE_VIDEO &&
4742           stream->index_table && demux->common.segment.rate > 0.0) {
4743         GstMatroskaTrackVideoContext *videocontext =
4744             (GstMatroskaTrackVideoContext *) stream;
4745         GstClockTime earliest_time;
4746         GstClockTime earliest_stream_time;
4747
4748         GST_OBJECT_LOCK (demux);
4749         earliest_time = videocontext->earliest_time;
4750         GST_OBJECT_UNLOCK (demux);
4751         earliest_stream_time =
4752             gst_segment_position_from_running_time (&demux->common.segment,
4753             GST_FORMAT_TIME, earliest_time);
4754
4755         if (GST_CLOCK_TIME_IS_VALID (lace_time) &&
4756             GST_CLOCK_TIME_IS_VALID (earliest_stream_time) &&
4757             lace_time <= earliest_stream_time) {
4758           /* find index entry (keyframe) <= earliest_stream_time */
4759           GstMatroskaIndex *entry =
4760               gst_util_array_binary_search (stream->index_table->data,
4761               stream->index_table->len, sizeof (GstMatroskaIndex),
4762               (GCompareDataFunc) gst_matroska_index_seek_find,
4763               GST_SEARCH_MODE_BEFORE, &earliest_stream_time, NULL);
4764
4765           /* if that entry (keyframe) is after the current the current
4766              buffer, we can skip pushing (and thus decoding) all
4767              buffers until that keyframe. */
4768           if (entry && GST_CLOCK_TIME_IS_VALID (entry->time) &&
4769               entry->time > lace_time) {
4770             GST_LOG_OBJECT (demux, "Skipping lace before late keyframe");
4771             stream->set_discont = TRUE;
4772             goto next_lace;
4773           }
4774         }
4775       }
4776
4777       sub = gst_buffer_copy_region (buf, GST_BUFFER_COPY_ALL,
4778           gst_buffer_get_size (buf) - size, lace_size[n]);
4779       GST_DEBUG_OBJECT (demux, "created subbuffer %p", sub);
4780
4781       if (delta_unit)
4782         GST_BUFFER_FLAG_SET (sub, GST_BUFFER_FLAG_DELTA_UNIT);
4783       else
4784         GST_BUFFER_FLAG_UNSET (sub, GST_BUFFER_FLAG_DELTA_UNIT);
4785
4786       if (invisible_frame)
4787         GST_BUFFER_FLAG_SET (sub, GST_BUFFER_FLAG_DECODE_ONLY);
4788
4789       if (stream->encodings != NULL && stream->encodings->len > 0)
4790         sub = gst_matroska_decode_buffer (stream, sub);
4791
4792       if (sub == NULL) {
4793         GST_WARNING_OBJECT (demux, "Decoding buffer failed");
4794         goto next_lace;
4795       }
4796
4797       if (!stream->dts_only) {
4798         GST_BUFFER_PTS (sub) = lace_time;
4799       } else {
4800         GST_BUFFER_DTS (sub) = lace_time;
4801         if (stream->intra_only)
4802           GST_BUFFER_PTS (sub) = lace_time;
4803       }
4804
4805       buffer_timestamp = gst_matroska_track_get_buffer_timestamp (stream, sub);
4806
4807       if (GST_CLOCK_TIME_IS_VALID (lace_time)) {
4808         GstClockTime last_stop_end;
4809
4810         /* Check if this stream is after segment stop,
4811          * but only terminate if we hit the next keyframe,
4812          * to make sure that all frames potentially inside the segment
4813          * are available to the decoder for decoding / reordering.*/
4814         if (!delta_unit && GST_CLOCK_TIME_IS_VALID (demux->common.segment.stop)
4815             && lace_time >= demux->common.segment.stop) {
4816           GST_DEBUG_OBJECT (demux,
4817               "Stream %d lace time: %" GST_TIME_FORMAT " after segment stop: %"
4818               GST_TIME_FORMAT, stream->index, GST_TIME_ARGS (lace_time),
4819               GST_TIME_ARGS (demux->common.segment.stop));
4820           gst_buffer_unref (sub);
4821           goto eos;
4822         }
4823         if (offset >= stream->to_offset
4824             || (GST_CLOCK_TIME_IS_VALID (demux->to_time)
4825                 && lace_time > demux->to_time)) {
4826           GST_DEBUG_OBJECT (demux, "Stream %d after playback section",
4827               stream->index);
4828           gst_buffer_unref (sub);
4829           goto eos;
4830         }
4831
4832         /* handle gaps, e.g. non-zero start-time, or an cue index entry
4833          * that landed us with timestamps not quite intended */
4834         GST_OBJECT_LOCK (demux);
4835         if (demux->max_gap_time &&
4836             GST_CLOCK_TIME_IS_VALID (demux->last_stop_end) &&
4837             demux->common.segment.rate > 0.0) {
4838           GstClockTimeDiff diff;
4839
4840           /* only send segments with increasing start times,
4841            * otherwise if these go back and forth downstream (sinks) increase
4842            * accumulated time and running_time */
4843           diff = GST_CLOCK_DIFF (demux->last_stop_end, lace_time);
4844           if (diff > 0 && diff > demux->max_gap_time
4845               && lace_time > demux->common.segment.start
4846               && (!GST_CLOCK_TIME_IS_VALID (demux->common.segment.stop)
4847                   || lace_time < demux->common.segment.stop)) {
4848             GstEvent *event;
4849             GST_DEBUG_OBJECT (demux,
4850                 "Gap of %" G_GINT64_FORMAT " ns detected in"
4851                 "stream %d (%" GST_TIME_FORMAT " -> %" GST_TIME_FORMAT "). "
4852                 "Sending updated SEGMENT events", diff,
4853                 stream->index, GST_TIME_ARGS (stream->pos),
4854                 GST_TIME_ARGS (lace_time));
4855
4856             event = gst_event_new_gap (demux->last_stop_end, diff);
4857             GST_OBJECT_UNLOCK (demux);
4858             gst_pad_push_event (stream->pad, event);
4859             GST_OBJECT_LOCK (demux);
4860           }
4861         }
4862
4863         if (!GST_CLOCK_TIME_IS_VALID (demux->common.segment.position)
4864             || demux->common.segment.position < lace_time) {
4865           demux->common.segment.position = lace_time;
4866         }
4867         GST_OBJECT_UNLOCK (demux);
4868
4869         last_stop_end = lace_time;
4870         if (duration) {
4871           GST_BUFFER_DURATION (sub) = duration / laces;
4872           last_stop_end += GST_BUFFER_DURATION (sub);
4873         }
4874
4875         if (!GST_CLOCK_TIME_IS_VALID (demux->last_stop_end) ||
4876             demux->last_stop_end < last_stop_end)
4877           demux->last_stop_end = last_stop_end;
4878
4879         GST_OBJECT_LOCK (demux);
4880         if (demux->common.segment.duration == -1 ||
4881             demux->stream_start_time + demux->common.segment.duration <
4882             last_stop_end) {
4883           demux->common.segment.duration =
4884               last_stop_end - demux->stream_start_time;
4885           GST_OBJECT_UNLOCK (demux);
4886           if (!demux->invalid_duration) {
4887             gst_element_post_message (GST_ELEMENT_CAST (demux),
4888                 gst_message_new_duration_changed (GST_OBJECT_CAST (demux)));
4889             demux->invalid_duration = TRUE;
4890           }
4891         } else {
4892           GST_OBJECT_UNLOCK (demux);
4893         }
4894       }
4895
4896       stream->pos = lace_time;
4897
4898       gst_matroska_demux_sync_streams (demux);
4899
4900       if (stream->set_discont) {
4901         GST_DEBUG_OBJECT (demux, "marking DISCONT");
4902         GST_BUFFER_FLAG_SET (sub, GST_BUFFER_FLAG_DISCONT);
4903         stream->set_discont = FALSE;
4904       } else {
4905         GST_BUFFER_FLAG_UNSET (sub, GST_BUFFER_FLAG_DISCONT);
4906       }
4907
4908       /* reverse playback book-keeping */
4909       if (!GST_CLOCK_TIME_IS_VALID (stream->from_time))
4910         stream->from_time = lace_time;
4911       if (stream->from_offset == -1)
4912         stream->from_offset = offset;
4913
4914       GST_DEBUG_OBJECT (demux,
4915           "Pushing lace %d, data of size %" G_GSIZE_FORMAT
4916           " for stream %d, time=%" GST_TIME_FORMAT " and duration=%"
4917           GST_TIME_FORMAT, n, gst_buffer_get_size (sub), stream_num,
4918           GST_TIME_ARGS (buffer_timestamp),
4919           GST_TIME_ARGS (GST_BUFFER_DURATION (sub)));
4920
4921 #if 0
4922       if (demux->common.element_index) {
4923         if (stream->index_writer_id == -1)
4924           gst_index_get_writer_id (demux->common.element_index,
4925               GST_OBJECT (stream->pad), &stream->index_writer_id);
4926
4927         GST_LOG_OBJECT (demux, "adding association %" GST_TIME_FORMAT "-> %"
4928             G_GUINT64_FORMAT " for writer id %d",
4929             GST_TIME_ARGS (buffer_timestamp), cluster_offset,
4930             stream->index_writer_id);
4931         gst_index_add_association (demux->common.element_index,
4932             stream->index_writer_id, GST_BUFFER_FLAG_IS_SET (sub,
4933                 GST_BUFFER_FLAG_DELTA_UNIT) ? 0 : GST_ASSOCIATION_FLAG_KEY_UNIT,
4934             GST_FORMAT_TIME, buffer_timestamp, GST_FORMAT_BYTES, cluster_offset,
4935             NULL);
4936       }
4937 #endif
4938
4939       /* Postprocess the buffers depending on the codec used */
4940       if (stream->postprocess_frame) {
4941         GST_LOG_OBJECT (demux, "running post process");
4942         ret = stream->postprocess_frame (GST_ELEMENT (demux), stream, &sub);
4943       }
4944
4945       /* At this point, we have a sub-buffer pointing at data within a larger
4946          buffer. This data might not be aligned with anything. If the data is
4947          raw samples though, we want it aligned to the raw type (eg, 4 bytes
4948          for 32 bit samples, etc), or bad things will happen downstream as
4949          elements typically assume minimal alignment.
4950          Therefore, create an aligned copy if necessary. */
4951       sub = gst_matroska_demux_align_buffer (demux, sub, stream->alignment);
4952
4953       if (!strcmp (stream->codec_id, GST_MATROSKA_CODEC_ID_AUDIO_OPUS)) {
4954         guint64 start_clip = 0, end_clip = 0;
4955
4956         /* Codec delay is part of the timestamps */
4957         if (GST_BUFFER_PTS_IS_VALID (sub) && stream->codec_delay) {
4958           if (GST_BUFFER_PTS (sub) > stream->codec_delay) {
4959             GST_BUFFER_PTS (sub) -= stream->codec_delay;
4960           } else {
4961             GST_BUFFER_PTS (sub) = 0;
4962
4963             /* Opus GstAudioClippingMeta units are scaled by 48000/sample_rate.
4964                That is, if a Opus track has audio encoded at 24000 Hz and 132
4965                samples need to be clipped, GstAudioClippingMeta.start will be
4966                set to 264. (This is also the case for buffer offsets.)
4967                Opus sample rates are always divisors of 48000 Hz, which is the
4968                maximum allowed sample rate. */
4969             start_clip =
4970                 gst_util_uint64_scale_round (stream->codec_delay, 48000,
4971                 GST_SECOND);
4972
4973             if (GST_BUFFER_DURATION_IS_VALID (sub)) {
4974               if (GST_BUFFER_DURATION (sub) > stream->codec_delay)
4975                 GST_BUFFER_DURATION (sub) -= stream->codec_delay;
4976               else
4977                 GST_BUFFER_DURATION (sub) = 0;
4978             }
4979           }
4980         }
4981
4982         if (block_discardpadding) {
4983           end_clip =
4984               gst_util_uint64_scale_round (block_discardpadding, 48000,
4985               GST_SECOND);
4986         }
4987
4988         if (start_clip || end_clip) {
4989           gst_buffer_add_audio_clipping_meta (sub, GST_FORMAT_DEFAULT,
4990               start_clip, end_clip);
4991         }
4992       }
4993
4994       if (GST_BUFFER_PTS_IS_VALID (sub)) {
4995         stream->pos = GST_BUFFER_PTS (sub);
4996         if (GST_BUFFER_DURATION_IS_VALID (sub))
4997           stream->pos += GST_BUFFER_DURATION (sub);
4998       } else if (GST_BUFFER_DTS_IS_VALID (sub)) {
4999         stream->pos = GST_BUFFER_DTS (sub);
5000         if (GST_BUFFER_DURATION_IS_VALID (sub))
5001           stream->pos += GST_BUFFER_DURATION (sub);
5002       }
5003
5004       /* Attach BlockAdditions to buffer; we assume a single buffer per group
5005        * in this case */
5006       if (additions.length > 0) {
5007         BlockAddition *blockadd;
5008
5009         if (laces > 2)
5010           GST_FIXME_OBJECT (demux, "Fix block additions with laced buffers");
5011
5012         while ((blockadd = g_queue_pop_head (&additions))) {
5013           GstMatroskaTrackVideoContext *videocontext =
5014               (GstMatroskaTrackVideoContext *) stream;
5015           if (blockadd->id == 1 && videocontext->alpha_mode
5016               && (!strcmp (stream->codec_id, GST_MATROSKA_CODEC_ID_VIDEO_VP8)
5017                   || !strcmp (stream->codec_id,
5018                       GST_MATROSKA_CODEC_ID_VIDEO_VP9))) {
5019             GstBuffer *alpha_buffer;
5020
5021             GST_TRACE_OBJECT (demux, "adding block addition %u as VP8/VP9 "
5022                 "alpha meta to buffer %p, %u bytes", (guint) blockadd->id, buf,
5023                 (guint) blockadd->size);
5024
5025             alpha_buffer = gst_buffer_new_wrapped (blockadd->data,
5026                 blockadd->size);
5027             gst_buffer_copy_into (alpha_buffer, sub,
5028                 GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_TIMESTAMPS, 0, -1);
5029             gst_buffer_add_video_codec_alpha_meta (sub, alpha_buffer);
5030           } else {
5031             g_free (blockadd->data);
5032           }
5033           g_free (blockadd);
5034         }
5035       }
5036
5037       ret = gst_pad_push (stream->pad, sub);
5038
5039       if (demux->common.segment.rate < 0) {
5040         if (lace_time > demux->common.segment.stop && ret == GST_FLOW_EOS) {
5041           /* In reverse playback we can get a GST_FLOW_EOS when
5042            * we are at the end of the segment, so we just need to jump
5043            * back to the previous section. */
5044           GST_DEBUG_OBJECT (demux, "downstream has reached end of segment");
5045           ret = GST_FLOW_OK;
5046         }
5047       }
5048       /* combine flows */
5049       ret = gst_flow_combiner_update_pad_flow (demux->flowcombiner,
5050           stream->pad, ret);
5051
5052     next_lace:
5053       size -= lace_size[n];
5054       if (lace_time != GST_CLOCK_TIME_NONE && duration)
5055         lace_time += duration / laces;
5056       else
5057         lace_time = GST_CLOCK_TIME_NONE;
5058     }
5059   }
5060
5061 done:
5062   if (buf) {
5063     gst_buffer_unmap (buf, &map);
5064     gst_buffer_unref (buf);
5065   }
5066   g_free (lace_size);
5067   {
5068     BlockAddition *blockadd;
5069
5070     while ((blockadd = g_queue_pop_head (&additions))) {
5071       g_free (blockadd->data);
5072       g_free (blockadd);
5073     }
5074   }
5075   return ret;
5076
5077   /* EXITS */
5078 eos:
5079   {
5080     stream->eos = TRUE;
5081     ret = GST_FLOW_OK;
5082     /* combine flows */
5083     ret = gst_flow_combiner_update_pad_flow (demux->flowcombiner, stream->pad,
5084         ret);
5085     goto done;
5086   }
5087 invalid_lacing:
5088   {
5089     GST_ELEMENT_WARNING (demux, STREAM, DEMUX, (NULL), ("Invalid lacing size"));
5090     /* non-fatal, try next block(group) */
5091     ret = GST_FLOW_OK;
5092     goto done;
5093   }
5094 data_error:
5095   {
5096     GST_ELEMENT_WARNING (demux, STREAM, DEMUX, (NULL), ("Data error"));
5097     /* non-fatal, try next block(group) */
5098     ret = GST_FLOW_OK;
5099     goto done;
5100   }
5101 }
5102
5103 /* return FALSE if block(group) should be skipped (due to a seek) */
5104 static inline gboolean
5105 gst_matroska_demux_seek_block (GstMatroskaDemux * demux)
5106 {
5107   if (G_UNLIKELY (demux->seek_block)) {
5108     if (!(--demux->seek_block)) {
5109       return TRUE;
5110     } else {
5111       GST_LOG_OBJECT (demux, "should skip block due to seek");
5112       return FALSE;
5113     }
5114   } else {
5115     return TRUE;
5116   }
5117 }
5118
5119 static GstFlowReturn
5120 gst_matroska_demux_parse_contents_seekentry (GstMatroskaDemux * demux,
5121     GstEbmlRead * ebml)
5122 {
5123   GstFlowReturn ret;
5124   guint64 seek_pos = (guint64) - 1;
5125   guint32 seek_id = 0;
5126   guint32 id;
5127
5128   DEBUG_ELEMENT_START (demux, ebml, "Seek");
5129
5130   if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
5131     DEBUG_ELEMENT_STOP (demux, ebml, "Seek", ret);
5132     return ret;
5133   }
5134
5135   while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
5136     if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
5137       break;
5138
5139     switch (id) {
5140       case GST_MATROSKA_ID_SEEKID:
5141       {
5142         guint64 t;
5143
5144         if ((ret = gst_ebml_read_uint (ebml, &id, &t)) != GST_FLOW_OK)
5145           break;
5146
5147         GST_DEBUG_OBJECT (demux, "SeekID: %" G_GUINT64_FORMAT, t);
5148         seek_id = t;
5149         break;
5150       }
5151
5152       case GST_MATROSKA_ID_SEEKPOSITION:
5153       {
5154         guint64 t;
5155
5156         if ((ret = gst_ebml_read_uint (ebml, &id, &t)) != GST_FLOW_OK)
5157           break;
5158
5159         if (t > G_MAXINT64) {
5160           GST_WARNING_OBJECT (demux,
5161               "Too large SeekPosition %" G_GUINT64_FORMAT, t);
5162           break;
5163         }
5164
5165         GST_DEBUG_OBJECT (demux, "SeekPosition: %" G_GUINT64_FORMAT, t);
5166         seek_pos = t;
5167         break;
5168       }
5169
5170       default:
5171         ret = gst_matroska_read_common_parse_skip (&demux->common, ebml,
5172             "SeekHead", id);
5173         break;
5174     }
5175   }
5176
5177   if (ret != GST_FLOW_OK && ret != GST_FLOW_EOS)
5178     return ret;
5179
5180   if (!seek_id || seek_pos == (guint64) - 1) {
5181     GST_WARNING_OBJECT (demux, "Incomplete seekhead entry (0x%x/%"
5182         G_GUINT64_FORMAT ")", seek_id, seek_pos);
5183     return GST_FLOW_OK;
5184   }
5185
5186   switch (seek_id) {
5187     case GST_MATROSKA_ID_SEEKHEAD:
5188     {
5189     }
5190     case GST_MATROSKA_ID_CUES:
5191     case GST_MATROSKA_ID_TAGS:
5192     case GST_MATROSKA_ID_TRACKS:
5193     case GST_MATROSKA_ID_SEGMENTINFO:
5194     case GST_MATROSKA_ID_ATTACHMENTS:
5195     case GST_MATROSKA_ID_CHAPTERS:
5196     {
5197       guint64 before_pos, length;
5198       guint needed;
5199
5200       /* remember */
5201       length = gst_matroska_read_common_get_length (&demux->common);
5202       before_pos = demux->common.offset;
5203
5204       if (length == (guint64) - 1) {
5205         GST_DEBUG_OBJECT (demux, "no upstream length, skipping SeakHead entry");
5206         break;
5207       }
5208
5209       /* check for validity */
5210       if (seek_pos + demux->common.ebml_segment_start + 12 >= length) {
5211         GST_WARNING_OBJECT (demux,
5212             "SeekHead reference lies outside file!" " (%"
5213             G_GUINT64_FORMAT "+%" G_GUINT64_FORMAT "+12 >= %"
5214             G_GUINT64_FORMAT ")", seek_pos, demux->common.ebml_segment_start,
5215             length);
5216         break;
5217       }
5218
5219       /* only pick up index location when streaming */
5220       if (demux->streaming) {
5221         if (seek_id == GST_MATROSKA_ID_CUES) {
5222           demux->index_offset = seek_pos + demux->common.ebml_segment_start;
5223           GST_DEBUG_OBJECT (demux, "Cues located at offset %" G_GUINT64_FORMAT,
5224               demux->index_offset);
5225         }
5226         break;
5227       }
5228
5229       /* seek */
5230       demux->common.offset = seek_pos + demux->common.ebml_segment_start;
5231
5232       /* check ID */
5233       if ((ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
5234                   GST_ELEMENT_CAST (demux), &id, &length, &needed)) !=
5235           GST_FLOW_OK)
5236         goto finish;
5237
5238       if (id != seek_id) {
5239         GST_WARNING_OBJECT (demux,
5240             "We looked for ID=0x%x but got ID=0x%x (pos=%" G_GUINT64_FORMAT ")",
5241             seek_id, id, seek_pos + demux->common.ebml_segment_start);
5242       } else {
5243         /* now parse */
5244         ret = gst_matroska_demux_parse_id (demux, id, length, needed);
5245       }
5246
5247     finish:
5248       /* seek back */
5249       demux->common.offset = before_pos;
5250       break;
5251     }
5252
5253     case GST_MATROSKA_ID_CLUSTER:
5254     {
5255       guint64 pos = seek_pos + demux->common.ebml_segment_start;
5256
5257       GST_LOG_OBJECT (demux, "Cluster position");
5258       if (G_UNLIKELY (!demux->clusters))
5259         demux->clusters = g_array_sized_new (TRUE, TRUE, sizeof (guint64), 100);
5260       g_array_append_val (demux->clusters, pos);
5261       break;
5262     }
5263
5264     default:
5265       GST_DEBUG_OBJECT (demux, "Ignoring Seek entry for ID=0x%x", seek_id);
5266       break;
5267   }
5268   DEBUG_ELEMENT_STOP (demux, ebml, "Seek", ret);
5269
5270   return ret;
5271 }
5272
5273 static GstFlowReturn
5274 gst_matroska_demux_parse_contents (GstMatroskaDemux * demux, GstEbmlRead * ebml)
5275 {
5276   GstFlowReturn ret = GST_FLOW_OK;
5277   guint32 id;
5278
5279   DEBUG_ELEMENT_START (demux, ebml, "SeekHead");
5280
5281   if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
5282     DEBUG_ELEMENT_STOP (demux, ebml, "SeekHead", ret);
5283     return ret;
5284   }
5285
5286   while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
5287     if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
5288       break;
5289
5290     switch (id) {
5291       case GST_MATROSKA_ID_SEEKENTRY:
5292       {
5293         ret = gst_matroska_demux_parse_contents_seekentry (demux, ebml);
5294         /* Ignore EOS and errors here */
5295         if (ret != GST_FLOW_OK) {
5296           GST_DEBUG_OBJECT (demux, "Ignoring %s", gst_flow_get_name (ret));
5297           ret = GST_FLOW_OK;
5298         }
5299         break;
5300       }
5301
5302       default:
5303         ret = gst_matroska_read_common_parse_skip (&demux->common,
5304             ebml, "SeekHead", id);
5305         break;
5306     }
5307   }
5308
5309   DEBUG_ELEMENT_STOP (demux, ebml, "SeekHead", ret);
5310
5311   /* Sort clusters by position for easier searching */
5312   if (demux->clusters)
5313     g_array_sort (demux->clusters, (GCompareFunc) gst_matroska_cluster_compare);
5314
5315   return ret;
5316 }
5317
5318 #define GST_FLOW_OVERFLOW   GST_FLOW_CUSTOM_ERROR
5319
5320 #define MAX_BLOCK_SIZE (15 * 1024 * 1024)
5321
5322 static inline GstFlowReturn
5323 gst_matroska_demux_check_read_size (GstMatroskaDemux * demux, guint64 bytes)
5324 {
5325   if (G_UNLIKELY (bytes > MAX_BLOCK_SIZE)) {
5326     /* only a few blocks are expected/allowed to be large,
5327      * and will be recursed into, whereas others will be read and must fit */
5328     if (demux->streaming) {
5329       /* fatal in streaming case, as we can't step over easily */
5330       GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
5331           ("reading large block of size %" G_GUINT64_FORMAT " not supported; "
5332               "file might be corrupt.", bytes));
5333       return GST_FLOW_ERROR;
5334     } else {
5335       /* indicate higher level to quietly give up */
5336       GST_DEBUG_OBJECT (demux,
5337           "too large block of size %" G_GUINT64_FORMAT, bytes);
5338       return GST_FLOW_ERROR;
5339     }
5340   } else {
5341     return GST_FLOW_OK;
5342   }
5343 }
5344
5345 /* returns TRUE if we truly are in error state, and should give up */
5346 static inline GstFlowReturn
5347 gst_matroska_demux_check_parse_error (GstMatroskaDemux * demux)
5348 {
5349   if (!demux->streaming && demux->next_cluster_offset > 0) {
5350     /* just repositioning to where next cluster should be and try from there */
5351     GST_WARNING_OBJECT (demux, "parse error, trying next cluster expected at %"
5352         G_GUINT64_FORMAT, demux->next_cluster_offset);
5353     demux->common.offset = demux->next_cluster_offset;
5354     demux->next_cluster_offset = 0;
5355     return GST_FLOW_OK;
5356   } else {
5357     gint64 pos;
5358     GstFlowReturn ret;
5359
5360     /* sigh, one last attempt above and beyond call of duty ...;
5361      * search for cluster mark following current pos */
5362     pos = demux->common.offset;
5363     GST_WARNING_OBJECT (demux, "parse error, looking for next cluster");
5364     if ((ret = gst_matroska_demux_search_cluster (demux, &pos, TRUE)) !=
5365         GST_FLOW_OK) {
5366       /* did not work, give up */
5367       return ret;
5368     } else {
5369       GST_DEBUG_OBJECT (demux, "... found at  %" G_GUINT64_FORMAT, pos);
5370       /* try that position */
5371       demux->common.offset = pos;
5372       return GST_FLOW_OK;
5373     }
5374   }
5375 }
5376
5377 static inline GstFlowReturn
5378 gst_matroska_demux_flush (GstMatroskaDemux * demux, guint flush)
5379 {
5380   GST_LOG_OBJECT (demux, "skipping %d bytes", flush);
5381   demux->common.offset += flush;
5382   if (demux->streaming) {
5383     GstFlowReturn ret;
5384
5385     /* hard to skip large blocks when streaming */
5386     ret = gst_matroska_demux_check_read_size (demux, flush);
5387     if (ret != GST_FLOW_OK)
5388       return ret;
5389     if (flush <= gst_adapter_available (demux->common.adapter))
5390       gst_adapter_flush (demux->common.adapter, flush);
5391     else
5392       return GST_FLOW_EOS;
5393   }
5394   return GST_FLOW_OK;
5395 }
5396
5397 /* initializes @ebml with @bytes from input stream at current offset.
5398  * Returns EOS if insufficient available,
5399  * ERROR if too much was attempted to read. */
5400 static inline GstFlowReturn
5401 gst_matroska_demux_take (GstMatroskaDemux * demux, guint64 bytes,
5402     GstEbmlRead * ebml)
5403 {
5404   GstBuffer *buffer = NULL;
5405   GstFlowReturn ret = GST_FLOW_OK;
5406
5407   GST_LOG_OBJECT (demux, "taking %" G_GUINT64_FORMAT " bytes for parsing",
5408       bytes);
5409   ret = gst_matroska_demux_check_read_size (demux, bytes);
5410   if (G_UNLIKELY (ret != GST_FLOW_OK)) {
5411     if (!demux->streaming) {
5412       /* in pull mode, we can skip */
5413       if ((ret = gst_matroska_demux_flush (demux, bytes)) == GST_FLOW_OK)
5414         ret = GST_FLOW_OVERFLOW;
5415     } else {
5416       /* otherwise fatal */
5417       ret = GST_FLOW_ERROR;
5418     }
5419     goto exit;
5420   }
5421   if (demux->streaming) {
5422     if (gst_adapter_available (demux->common.adapter) >= bytes)
5423       buffer = gst_adapter_take_buffer (demux->common.adapter, bytes);
5424     else
5425       ret = GST_FLOW_EOS;
5426   } else
5427     ret = gst_matroska_read_common_peek_bytes (&demux->common,
5428         demux->common.offset, bytes, &buffer, NULL);
5429   if (G_LIKELY (buffer)) {
5430     gst_ebml_read_init (ebml, GST_ELEMENT_CAST (demux), buffer,
5431         demux->common.offset);
5432     demux->common.offset += bytes;
5433   }
5434 exit:
5435   return ret;
5436 }
5437
5438 static void
5439 gst_matroska_demux_check_seekability (GstMatroskaDemux * demux)
5440 {
5441   GstQuery *query;
5442   gboolean seekable = FALSE;
5443   gint64 start = -1, stop = -1;
5444
5445   query = gst_query_new_seeking (GST_FORMAT_BYTES);
5446   if (!gst_pad_peer_query (demux->common.sinkpad, query)) {
5447     GST_DEBUG_OBJECT (demux, "seeking query failed");
5448     goto done;
5449   }
5450
5451   gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
5452
5453   /* try harder to query upstream size if we didn't get it the first time */
5454   if (seekable && stop == -1) {
5455     GST_DEBUG_OBJECT (demux, "doing duration query to fix up unset stop");
5456     gst_pad_peer_query_duration (demux->common.sinkpad, GST_FORMAT_BYTES,
5457         &stop);
5458   }
5459
5460   /* if upstream doesn't know the size, it's likely that it's not seekable in
5461    * practice even if it technically may be seekable */
5462   if (seekable && (start != 0 || stop <= start)) {
5463     GST_DEBUG_OBJECT (demux, "seekable but unknown start/stop -> disable");
5464     seekable = FALSE;
5465   }
5466
5467 done:
5468   GST_INFO_OBJECT (demux, "seekable: %d (%" G_GUINT64_FORMAT " - %"
5469       G_GUINT64_FORMAT ")", seekable, start, stop);
5470   demux->seekable = seekable;
5471
5472   gst_query_unref (query);
5473 }
5474
5475 static GstFlowReturn
5476 gst_matroska_demux_find_tracks (GstMatroskaDemux * demux)
5477 {
5478   guint32 id;
5479   guint64 before_pos;
5480   guint64 length;
5481   guint needed;
5482   GstFlowReturn ret = GST_FLOW_OK;
5483
5484   GST_WARNING_OBJECT (demux,
5485       "Found Cluster element before Tracks, searching Tracks");
5486
5487   /* remember */
5488   before_pos = demux->common.offset;
5489
5490   /* Search Tracks element */
5491   while (TRUE) {
5492     ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
5493         GST_ELEMENT_CAST (demux), &id, &length, &needed);
5494     if (ret != GST_FLOW_OK)
5495       break;
5496
5497     if (id != GST_MATROSKA_ID_TRACKS) {
5498       /* we may be skipping large cluster here, so forego size check etc */
5499       /* ... but we can't skip undefined size; force error */
5500       if (length == G_MAXUINT64) {
5501         ret = gst_matroska_demux_check_read_size (demux, length);
5502         break;
5503       } else {
5504         demux->common.offset += needed;
5505         demux->common.offset += length;
5506       }
5507       continue;
5508     }
5509
5510     /* will lead to track parsing ... */
5511     ret = gst_matroska_demux_parse_id (demux, id, length, needed);
5512     break;
5513   }
5514
5515   /* seek back */
5516   demux->common.offset = before_pos;
5517
5518   return ret;
5519 }
5520
5521 #define GST_READ_CHECK(stmt)  \
5522 G_STMT_START { \
5523   if (G_UNLIKELY ((ret = (stmt)) != GST_FLOW_OK)) { \
5524     if (ret == GST_FLOW_OVERFLOW) { \
5525       ret = GST_FLOW_OK; \
5526     } \
5527     goto read_error; \
5528   } \
5529 } G_STMT_END
5530
5531 static GstFlowReturn
5532 gst_matroska_demux_parse_id (GstMatroskaDemux * demux, guint32 id,
5533     guint64 length, guint needed)
5534 {
5535   GstEbmlRead ebml = { 0, };
5536   GstFlowReturn ret = GST_FLOW_OK;
5537   guint64 read;
5538
5539   GST_LOG_OBJECT (demux, "Parsing Element id 0x%x, "
5540       "size %" G_GUINT64_FORMAT ", prefix %d", id, length, needed);
5541
5542   /* if we plan to read and parse this element, we need prefix (id + length)
5543    * and the contents */
5544   /* mind about overflow wrap-around when dealing with undefined size */
5545   read = length;
5546   if (G_LIKELY (length != G_MAXUINT64))
5547     read += needed;
5548
5549   switch (demux->common.state) {
5550     case GST_MATROSKA_READ_STATE_START:
5551       switch (id) {
5552         case GST_EBML_ID_HEADER:
5553           GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5554           ret = gst_matroska_read_common_parse_header (&demux->common, &ebml);
5555           if (ret != GST_FLOW_OK)
5556             goto parse_failed;
5557           demux->common.state = GST_MATROSKA_READ_STATE_SEGMENT;
5558           gst_matroska_demux_check_seekability (demux);
5559           break;
5560         default:
5561           goto invalid_header;
5562           break;
5563       }
5564       break;
5565     case GST_MATROSKA_READ_STATE_SEGMENT:
5566       switch (id) {
5567         case GST_MATROSKA_ID_SEGMENT:
5568           /* eat segment prefix */
5569           GST_READ_CHECK (gst_matroska_demux_flush (demux, needed));
5570           GST_DEBUG_OBJECT (demux,
5571               "Found Segment start at offset %" G_GUINT64_FORMAT " with size %"
5572               G_GUINT64_FORMAT, demux->common.offset, length);
5573           /* seeks are from the beginning of the segment,
5574            * after the segment ID/length */
5575           demux->common.ebml_segment_start = demux->common.offset;
5576           if (length == 0)
5577             length = G_MAXUINT64;
5578           demux->common.ebml_segment_length = length;
5579           demux->common.state = GST_MATROSKA_READ_STATE_HEADER;
5580           break;
5581         default:
5582           GST_WARNING_OBJECT (demux,
5583               "Expected a Segment ID (0x%x), but received 0x%x!",
5584               GST_MATROSKA_ID_SEGMENT, id);
5585           GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
5586           break;
5587       }
5588       break;
5589     case GST_MATROSKA_READ_STATE_SCANNING:
5590       if (id != GST_MATROSKA_ID_CLUSTER &&
5591           id != GST_MATROSKA_ID_PREVSIZE &&
5592           id != GST_MATROSKA_ID_CLUSTERTIMECODE) {
5593         if (demux->common.start_resync_offset != -1) {
5594           /* we need to skip byte per byte if we are scanning for a new cluster
5595            * after invalid data is found
5596            */
5597           read = 1;
5598         }
5599         goto skip;
5600       } else {
5601         if (demux->common.start_resync_offset != -1) {
5602           GST_LOG_OBJECT (demux, "Resync done, new cluster found!");
5603           demux->common.start_resync_offset = -1;
5604           demux->common.state = demux->common.state_to_restore;
5605         }
5606       }
5607       /* fall-through */
5608     case GST_MATROSKA_READ_STATE_HEADER:
5609     case GST_MATROSKA_READ_STATE_DATA:
5610     case GST_MATROSKA_READ_STATE_SEEK:
5611       switch (id) {
5612         case GST_EBML_ID_HEADER:
5613           GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
5614           demux->common.state = GST_MATROSKA_READ_STATE_SEGMENT;
5615           gst_matroska_demux_check_seekability (demux);
5616           break;
5617         case GST_MATROSKA_ID_SEGMENTINFO:
5618           if (!demux->common.segmentinfo_parsed) {
5619             GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5620             ret = gst_matroska_read_common_parse_info (&demux->common,
5621                 GST_ELEMENT_CAST (demux), &ebml);
5622             if (ret == GST_FLOW_OK)
5623               gst_matroska_demux_send_tags (demux);
5624           } else {
5625             GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
5626           }
5627           break;
5628         case GST_MATROSKA_ID_TRACKS:
5629           GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5630           if (!demux->tracks_parsed) {
5631             ret = gst_matroska_demux_parse_tracks (demux, &ebml);
5632           } else {
5633             ret = gst_matroska_demux_update_tracks (demux, &ebml);
5634           }
5635           break;
5636         case GST_MATROSKA_ID_CLUSTER:
5637           if (G_UNLIKELY (!demux->tracks_parsed)) {
5638             if (demux->streaming) {
5639               GST_DEBUG_OBJECT (demux, "Cluster before Track");
5640               goto not_streamable;
5641             } else {
5642               ret = gst_matroska_demux_find_tracks (demux);
5643               if (!demux->tracks_parsed)
5644                 goto no_tracks;
5645             }
5646           }
5647           if (demux->common.state == GST_MATROSKA_READ_STATE_HEADER) {
5648             demux->common.state = GST_MATROSKA_READ_STATE_DATA;
5649             demux->first_cluster_offset = demux->common.offset;
5650
5651             if (!demux->streaming &&
5652                 !GST_CLOCK_TIME_IS_VALID (demux->common.segment.duration)) {
5653               GstMatroskaIndex *last = NULL;
5654
5655               GST_DEBUG_OBJECT (demux,
5656                   "estimating duration using last cluster");
5657               if ((last = gst_matroska_demux_search_pos (demux,
5658                           GST_CLOCK_TIME_NONE)) != NULL) {
5659                 demux->last_cluster_offset =
5660                     last->pos + demux->common.ebml_segment_start;
5661                 demux->stream_last_time = last->time;
5662                 demux->common.segment.duration =
5663                     demux->stream_last_time - demux->stream_start_time;
5664                 /* above estimate should not be taken all too strongly */
5665                 demux->invalid_duration = TRUE;
5666                 GST_DEBUG_OBJECT (demux,
5667                     "estimated duration as %" GST_TIME_FORMAT,
5668                     GST_TIME_ARGS (demux->common.segment.duration));
5669
5670                 g_free (last);
5671               }
5672             }
5673
5674             /* Peek at second cluster in order to figure out if we have cluster
5675              * prev_size or not (which is never set on the first cluster for
5676              * obvious reasons). This is useful in case someone initiates a
5677              * seek or direction change before we reach the second cluster. */
5678             if (!demux->streaming) {
5679               ClusterInfo cluster = { 0, };
5680
5681               if (gst_matroska_demux_peek_cluster_info (demux, &cluster,
5682                       demux->first_cluster_offset) && cluster.size > 0) {
5683                 gst_matroska_demux_peek_cluster_info (demux, &cluster,
5684                     demux->first_cluster_offset + cluster.size);
5685               }
5686               demux->common.offset = demux->first_cluster_offset;
5687             }
5688
5689             if (demux->deferred_seek_event) {
5690               GstEvent *seek_event;
5691               GstPad *seek_pad;
5692               seek_event = demux->deferred_seek_event;
5693               seek_pad = demux->deferred_seek_pad;
5694               demux->deferred_seek_event = NULL;
5695               demux->deferred_seek_pad = NULL;
5696               GST_DEBUG_OBJECT (demux,
5697                   "Handling deferred seek event: %" GST_PTR_FORMAT, seek_event);
5698               gst_matroska_demux_handle_seek_event (demux, seek_pad,
5699                   seek_event);
5700               gst_event_unref (seek_event);
5701             }
5702
5703             /* send initial segment - we wait till we know the first
5704                incoming timestamp, so we can properly set the start of
5705                the segment. */
5706             demux->need_segment = TRUE;
5707           }
5708           demux->cluster_time = GST_CLOCK_TIME_NONE;
5709           demux->cluster_offset = demux->common.offset;
5710           demux->cluster_prevsize = 0;
5711           if (G_UNLIKELY (!demux->seek_first && demux->seek_block)) {
5712             GST_DEBUG_OBJECT (demux, "seek target block %" G_GUINT64_FORMAT
5713                 " not found in Cluster, trying next Cluster's first block instead",
5714                 demux->seek_block);
5715             demux->seek_block = 0;
5716           }
5717           demux->seek_first = FALSE;
5718           /* record next cluster for recovery */
5719           if (read != G_MAXUINT64)
5720             demux->next_cluster_offset = demux->cluster_offset + read;
5721           /* eat cluster prefix */
5722           gst_matroska_demux_flush (demux, needed);
5723           break;
5724         case GST_MATROSKA_ID_CLUSTERTIMECODE:
5725         {
5726           guint64 num;
5727
5728           GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5729           if ((ret = gst_ebml_read_uint (&ebml, &id, &num)) != GST_FLOW_OK)
5730             goto parse_failed;
5731           GST_DEBUG_OBJECT (demux, "ClusterTimeCode: %" G_GUINT64_FORMAT, num);
5732           demux->cluster_time = num;
5733           /* track last cluster */
5734           if (demux->cluster_offset > demux->last_cluster_offset) {
5735             demux->last_cluster_offset = demux->cluster_offset;
5736             demux->stream_last_time =
5737                 demux->cluster_time * demux->common.time_scale;
5738           }
5739 #if 0
5740           if (demux->common.element_index) {
5741             if (demux->common.element_index_writer_id == -1)
5742               gst_index_get_writer_id (demux->common.element_index,
5743                   GST_OBJECT (demux), &demux->common.element_index_writer_id);
5744             GST_LOG_OBJECT (demux, "adding association %" GST_TIME_FORMAT "-> %"
5745                 G_GUINT64_FORMAT " for writer id %d",
5746                 GST_TIME_ARGS (demux->cluster_time), demux->cluster_offset,
5747                 demux->common.element_index_writer_id);
5748             gst_index_add_association (demux->common.element_index,
5749                 demux->common.element_index_writer_id,
5750                 GST_ASSOCIATION_FLAG_KEY_UNIT,
5751                 GST_FORMAT_TIME, demux->cluster_time,
5752                 GST_FORMAT_BYTES, demux->cluster_offset, NULL);
5753           }
5754 #endif
5755           break;
5756         }
5757         case GST_MATROSKA_ID_BLOCKGROUP:
5758           if (!gst_matroska_demux_seek_block (demux))
5759             goto skip;
5760           GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5761           DEBUG_ELEMENT_START (demux, &ebml, "BlockGroup");
5762           if ((ret = gst_ebml_read_master (&ebml, &id)) == GST_FLOW_OK) {
5763             ret = gst_matroska_demux_parse_blockgroup_or_simpleblock (demux,
5764                 &ebml, demux->cluster_time, demux->cluster_offset, FALSE);
5765           }
5766           DEBUG_ELEMENT_STOP (demux, &ebml, "BlockGroup", ret);
5767           break;
5768         case GST_MATROSKA_ID_SIMPLEBLOCK:
5769           if (!gst_matroska_demux_seek_block (demux))
5770             goto skip;
5771           GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5772           DEBUG_ELEMENT_START (demux, &ebml, "SimpleBlock");
5773           ret = gst_matroska_demux_parse_blockgroup_or_simpleblock (demux,
5774               &ebml, demux->cluster_time, demux->cluster_offset, TRUE);
5775           DEBUG_ELEMENT_STOP (demux, &ebml, "SimpleBlock", ret);
5776           break;
5777         case GST_MATROSKA_ID_ATTACHMENTS:
5778           if (!demux->common.attachments_parsed) {
5779             GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5780             ret = gst_matroska_read_common_parse_attachments (&demux->common,
5781                 GST_ELEMENT_CAST (demux), &ebml);
5782             if (ret == GST_FLOW_OK)
5783               gst_matroska_demux_send_tags (demux);
5784           } else {
5785             GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
5786           }
5787           break;
5788         case GST_MATROSKA_ID_TAGS:
5789           GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5790           ret = gst_matroska_read_common_parse_metadata (&demux->common,
5791               GST_ELEMENT_CAST (demux), &ebml);
5792           if (ret == GST_FLOW_OK)
5793             gst_matroska_demux_send_tags (demux);
5794           break;
5795         case GST_MATROSKA_ID_CHAPTERS:
5796           if (!demux->common.chapters_parsed) {
5797             GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5798             ret =
5799                 gst_matroska_read_common_parse_chapters (&demux->common, &ebml);
5800
5801             if (demux->common.toc) {
5802               gst_matroska_demux_send_event (demux,
5803                   gst_event_new_toc (demux->common.toc, FALSE));
5804             }
5805           } else
5806             GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
5807           break;
5808         case GST_MATROSKA_ID_SEEKHEAD:
5809           GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5810           ret = gst_matroska_demux_parse_contents (demux, &ebml);
5811           break;
5812         case GST_MATROSKA_ID_CUES:
5813           if (demux->common.index_parsed) {
5814             GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
5815             break;
5816           }
5817           GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5818           ret = gst_matroska_read_common_parse_index (&demux->common, &ebml);
5819           /* only push based; delayed index building */
5820           if (ret == GST_FLOW_OK
5821               && demux->common.state == GST_MATROSKA_READ_STATE_SEEK) {
5822             GstEvent *event;
5823
5824             GST_OBJECT_LOCK (demux);
5825             event = demux->seek_event;
5826             demux->seek_event = NULL;
5827             GST_OBJECT_UNLOCK (demux);
5828
5829             g_assert (event);
5830             /* unlikely to fail, since we managed to seek to this point */
5831             if (!gst_matroska_demux_handle_seek_event (demux, NULL, event)) {
5832               gst_event_unref (event);
5833               goto seek_failed;
5834             }
5835             gst_event_unref (event);
5836             /* resume data handling, main thread clear to seek again */
5837             GST_OBJECT_LOCK (demux);
5838             demux->common.state = GST_MATROSKA_READ_STATE_DATA;
5839             GST_OBJECT_UNLOCK (demux);
5840           }
5841           break;
5842         case GST_MATROSKA_ID_PREVSIZE:{
5843           guint64 num;
5844
5845           GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5846           if ((ret = gst_ebml_read_uint (&ebml, &id, &num)) != GST_FLOW_OK)
5847             goto parse_failed;
5848           GST_LOG_OBJECT (demux, "ClusterPrevSize: %" G_GUINT64_FORMAT, num);
5849           demux->cluster_prevsize = num;
5850           demux->seen_cluster_prevsize = TRUE;
5851           break;
5852         }
5853         case GST_MATROSKA_ID_POSITION:
5854         case GST_MATROSKA_ID_ENCRYPTEDBLOCK:
5855           /* The WebM doesn't support the EncryptedBlock element.
5856            * The Matroska spec doesn't give us more detail, how to parse this element,
5857            * for example the field TransformID isn't specified yet.*/
5858         case GST_MATROSKA_ID_SILENTTRACKS:
5859           GST_DEBUG_OBJECT (demux,
5860               "Skipping Cluster subelement 0x%x - ignoring", id);
5861           /* fall-through */
5862         default:
5863         skip:
5864           GST_DEBUG_OBJECT (demux, "skipping Element 0x%x", id);
5865           GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
5866           break;
5867       }
5868       break;
5869   }
5870
5871   if (ret == GST_FLOW_PARSE)
5872     goto parse_failed;
5873
5874 exit:
5875   gst_ebml_read_clear (&ebml);
5876   return ret;
5877
5878   /* ERRORS */
5879 read_error:
5880   {
5881     /* simply exit, maybe not enough data yet */
5882     /* no ebml to clear if read error */
5883     return ret;
5884   }
5885 parse_failed:
5886   {
5887     GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
5888         ("Failed to parse Element 0x%x", id));
5889     ret = GST_FLOW_ERROR;
5890     goto exit;
5891   }
5892 not_streamable:
5893   {
5894     GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
5895         ("File layout does not permit streaming"));
5896     ret = GST_FLOW_ERROR;
5897     goto exit;
5898   }
5899 no_tracks:
5900   {
5901     GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
5902         ("No Tracks element found"));
5903     ret = GST_FLOW_ERROR;
5904     goto exit;
5905   }
5906 invalid_header:
5907   {
5908     GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL), ("Invalid header"));
5909     ret = GST_FLOW_ERROR;
5910     goto exit;
5911   }
5912 seek_failed:
5913   {
5914     GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL), ("Failed to seek"));
5915     ret = GST_FLOW_ERROR;
5916     goto exit;
5917   }
5918 }
5919
5920 static void
5921 gst_matroska_demux_loop (GstPad * pad)
5922 {
5923   GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (GST_PAD_PARENT (pad));
5924   GstFlowReturn ret;
5925   guint32 id;
5926   guint64 length;
5927   guint needed;
5928
5929   /* If we have to close a segment, send a new segment to do this now */
5930   if (G_LIKELY (demux->common.state == GST_MATROSKA_READ_STATE_DATA)) {
5931     if (G_UNLIKELY (demux->new_segment)) {
5932       gst_matroska_demux_send_event (demux, demux->new_segment);
5933       demux->new_segment = NULL;
5934     }
5935   }
5936
5937   ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
5938       GST_ELEMENT_CAST (demux), &id, &length, &needed);
5939   if (ret == GST_FLOW_EOS) {
5940     goto eos;
5941   } else if (ret == GST_FLOW_FLUSHING) {
5942     goto pause;
5943   } else if (ret != GST_FLOW_OK) {
5944     ret = gst_matroska_demux_check_parse_error (demux);
5945
5946     /* Only handle EOS as no error if we're outside the segment already */
5947     if (ret == GST_FLOW_EOS && (demux->common.ebml_segment_length != G_MAXUINT64
5948             && demux->common.offset >=
5949             demux->common.ebml_segment_start +
5950             demux->common.ebml_segment_length))
5951       goto eos;
5952     else if (ret != GST_FLOW_OK)
5953       goto pause;
5954     else
5955       return;
5956   }
5957
5958   GST_LOG_OBJECT (demux, "Offset %" G_GUINT64_FORMAT ", Element id 0x%x, "
5959       "size %" G_GUINT64_FORMAT ", needed %d", demux->common.offset, id,
5960       length, needed);
5961
5962   ret = gst_matroska_demux_parse_id (demux, id, length, needed);
5963   if (ret == GST_FLOW_EOS)
5964     goto eos;
5965   if (ret != GST_FLOW_OK)
5966     goto pause;
5967
5968   /* check if we're at the end of a configured segment */
5969   if (G_LIKELY (demux->common.src->len)) {
5970     guint i;
5971
5972     g_assert (demux->common.num_streams == demux->common.src->len);
5973     for (i = 0; i < demux->common.src->len; i++) {
5974       GstMatroskaTrackContext *context = g_ptr_array_index (demux->common.src,
5975           i);
5976       GST_DEBUG_OBJECT (context->pad, "pos %" GST_TIME_FORMAT,
5977           GST_TIME_ARGS (context->pos));
5978       if (context->eos == FALSE)
5979         goto next;
5980     }
5981
5982     GST_INFO_OBJECT (demux, "All streams are EOS");
5983     ret = GST_FLOW_EOS;
5984     goto eos;
5985   }
5986
5987 next:
5988   if (G_UNLIKELY (demux->cached_length == G_MAXUINT64 ||
5989           demux->common.offset >= demux->cached_length)) {
5990     demux->cached_length = gst_matroska_read_common_get_length (&demux->common);
5991     if (demux->common.offset == demux->cached_length) {
5992       GST_LOG_OBJECT (demux, "Reached end of stream");
5993       ret = GST_FLOW_EOS;
5994       goto eos;
5995     }
5996   }
5997
5998   return;
5999
6000   /* ERRORS */
6001 eos:
6002   {
6003     if (demux->common.segment.rate < 0.0) {
6004       ret = gst_matroska_demux_seek_to_previous_keyframe (demux);
6005       if (ret == GST_FLOW_OK)
6006         return;
6007     }
6008     /* fall-through */
6009   }
6010 pause:
6011   {
6012     const gchar *reason = gst_flow_get_name (ret);
6013     gboolean push_eos = FALSE;
6014
6015     GST_LOG_OBJECT (demux, "pausing task, reason %s", reason);
6016     gst_pad_pause_task (demux->common.sinkpad);
6017
6018     if (ret == GST_FLOW_EOS) {
6019       /* perform EOS logic */
6020
6021       /* If we were in the headers, make sure we send no-more-pads.
6022          This will ensure decodebin does not get stuck thinking
6023          the chain is not complete yet, and waiting indefinitely. */
6024       if (G_UNLIKELY (demux->common.state == GST_MATROSKA_READ_STATE_HEADER)) {
6025         if (demux->common.src->len == 0) {
6026           GST_ELEMENT_ERROR (demux, STREAM, FAILED, (NULL),
6027               ("No pads created"));
6028         } else {
6029           GST_ELEMENT_WARNING (demux, STREAM, DEMUX, (NULL),
6030               ("Failed to finish reading headers"));
6031         }
6032         gst_element_no_more_pads (GST_ELEMENT (demux));
6033       }
6034
6035       if (demux->common.segment.flags & GST_SEEK_FLAG_SEGMENT) {
6036         GstEvent *event;
6037         GstMessage *msg;
6038         gint64 stop;
6039
6040         /* for segment playback we need to post when (in stream time)
6041          * we stopped, this is either stop (when set) or the duration. */
6042         if ((stop = demux->common.segment.stop) == -1)
6043           stop = demux->last_stop_end;
6044
6045         GST_LOG_OBJECT (demux, "Sending segment done, at end of segment");
6046         msg = gst_message_new_segment_done (GST_OBJECT (demux), GST_FORMAT_TIME,
6047             stop);
6048         if (demux->segment_seqnum)
6049           gst_message_set_seqnum (msg, demux->segment_seqnum);
6050         gst_element_post_message (GST_ELEMENT (demux), msg);
6051
6052         event = gst_event_new_segment_done (GST_FORMAT_TIME, stop);
6053         if (demux->segment_seqnum)
6054           gst_event_set_seqnum (event, demux->segment_seqnum);
6055         gst_matroska_demux_send_event (demux, event);
6056       } else {
6057         push_eos = TRUE;
6058       }
6059     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
6060       /* for fatal errors we post an error message */
6061       GST_ELEMENT_FLOW_ERROR (demux, ret);
6062       push_eos = TRUE;
6063     }
6064     if (push_eos) {
6065       GstEvent *event;
6066
6067       /* send EOS, and prevent hanging if no streams yet */
6068       GST_LOG_OBJECT (demux, "Sending EOS, at end of stream");
6069       event = gst_event_new_eos ();
6070       if (demux->segment_seqnum)
6071         gst_event_set_seqnum (event, demux->segment_seqnum);
6072       if (!gst_matroska_demux_send_event (demux, event) &&
6073           (ret == GST_FLOW_EOS)) {
6074         GST_ELEMENT_ERROR (demux, STREAM, DEMUX,
6075             (NULL), ("got eos but no streams (yet)"));
6076       }
6077     }
6078     return;
6079   }
6080 }
6081
6082 /*
6083  * Create and push a flushing seek event upstream
6084  */
6085 static gboolean
6086 perform_seek_to_offset (GstMatroskaDemux * demux, gdouble rate, guint64 offset,
6087     guint32 seqnum, GstSeekFlags flags)
6088 {
6089   GstEvent *event;
6090   gboolean res = 0;
6091
6092   GST_DEBUG_OBJECT (demux, "Seeking to %" G_GUINT64_FORMAT, offset);
6093
6094   event =
6095       gst_event_new_seek (rate, GST_FORMAT_BYTES,
6096       flags | GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE,
6097       GST_SEEK_TYPE_SET, offset, GST_SEEK_TYPE_NONE, -1);
6098   gst_event_set_seqnum (event, seqnum);
6099
6100   res = gst_pad_push_event (demux->common.sinkpad, event);
6101
6102   /* segment event will update offset */
6103   return res;
6104 }
6105
6106 static GstFlowReturn
6107 gst_matroska_demux_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
6108 {
6109   GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (parent);
6110   guint available;
6111   GstFlowReturn ret = GST_FLOW_OK;
6112   guint needed = 0;
6113   guint32 id;
6114   guint64 length;
6115
6116   if (G_UNLIKELY (GST_BUFFER_IS_DISCONT (buffer))) {
6117     GST_DEBUG_OBJECT (demux, "got DISCONT");
6118     gst_adapter_clear (demux->common.adapter);
6119     GST_OBJECT_LOCK (demux);
6120     gst_matroska_read_common_reset_streams (&demux->common,
6121         GST_CLOCK_TIME_NONE, FALSE);
6122     GST_OBJECT_UNLOCK (demux);
6123   }
6124
6125   gst_adapter_push (demux->common.adapter, buffer);
6126   buffer = NULL;
6127
6128 next:
6129   available = gst_adapter_available (demux->common.adapter);
6130
6131   ret = gst_matroska_read_common_peek_id_length_push (&demux->common,
6132       GST_ELEMENT_CAST (demux), &id, &length, &needed);
6133   if (G_UNLIKELY (ret != GST_FLOW_OK && ret != GST_FLOW_EOS)) {
6134     if (demux->common.ebml_segment_length != G_MAXUINT64
6135         && demux->common.offset >=
6136         demux->common.ebml_segment_start + demux->common.ebml_segment_length) {
6137       return GST_FLOW_OK;
6138     } else {
6139       gint64 bytes_scanned;
6140       if (demux->common.start_resync_offset == -1) {
6141         demux->common.start_resync_offset = demux->common.offset;
6142         demux->common.state_to_restore = demux->common.state;
6143       }
6144       bytes_scanned = demux->common.offset - demux->common.start_resync_offset;
6145       if (bytes_scanned <= INVALID_DATA_THRESHOLD) {
6146         GST_WARNING_OBJECT (demux,
6147             "parse error, looking for next cluster, actual offset %"
6148             G_GUINT64_FORMAT ", start resync offset %" G_GUINT64_FORMAT,
6149             demux->common.offset, demux->common.start_resync_offset);
6150         demux->common.state = GST_MATROSKA_READ_STATE_SCANNING;
6151         ret = GST_FLOW_OK;
6152       } else {
6153         GST_WARNING_OBJECT (demux,
6154             "unrecoverable parse error, next cluster not found and threshold "
6155             "exceeded, bytes scanned %" G_GINT64_FORMAT, bytes_scanned);
6156         return ret;
6157       }
6158     }
6159   }
6160
6161   GST_LOG_OBJECT (demux, "Offset %" G_GUINT64_FORMAT ", Element id 0x%x, "
6162       "size %" G_GUINT64_FORMAT ", needed %d, available %d",
6163       demux->common.offset, id, length, needed, available);
6164
6165   if (needed > available)
6166     return GST_FLOW_OK;
6167
6168   ret = gst_matroska_demux_parse_id (demux, id, length, needed);
6169   if (ret == GST_FLOW_EOS) {
6170     /* need more data */
6171     return GST_FLOW_OK;
6172   } else if (ret != GST_FLOW_OK) {
6173     return ret;
6174   } else
6175     goto next;
6176 }
6177
6178 static gboolean
6179 gst_matroska_demux_handle_sink_event (GstPad * pad, GstObject * parent,
6180     GstEvent * event)
6181 {
6182   gboolean res = TRUE;
6183   GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (parent);
6184
6185   GST_DEBUG_OBJECT (demux,
6186       "have event type %s: %p on sink pad", GST_EVENT_TYPE_NAME (event), event);
6187
6188   switch (GST_EVENT_TYPE (event)) {
6189     case GST_EVENT_SEGMENT:
6190     {
6191       const GstSegment *segment;
6192
6193       /* some debug output */
6194       gst_event_parse_segment (event, &segment);
6195       /* FIXME: do we need to update segment base here (like accum in 0.10)? */
6196       GST_DEBUG_OBJECT (demux,
6197           "received format %d segment %" GST_SEGMENT_FORMAT, segment->format,
6198           segment);
6199
6200       if (demux->common.state < GST_MATROSKA_READ_STATE_DATA) {
6201         GST_DEBUG_OBJECT (demux, "still starting");
6202         goto exit;
6203       }
6204
6205       /* we only expect a BYTE segment, e.g. following a seek */
6206       if (segment->format != GST_FORMAT_BYTES) {
6207         GST_DEBUG_OBJECT (demux, "unsupported segment format, ignoring");
6208         goto exit;
6209       }
6210
6211       GST_DEBUG_OBJECT (demux, "clearing segment state");
6212       GST_OBJECT_LOCK (demux);
6213       /* clear current segment leftover */
6214       gst_adapter_clear (demux->common.adapter);
6215       /* and some streaming setup */
6216       demux->common.offset = segment->start;
6217       /* accumulate base based on current position */
6218       if (GST_CLOCK_TIME_IS_VALID (demux->common.segment.position))
6219         demux->common.segment.base +=
6220             (MAX (demux->common.segment.position, demux->stream_start_time)
6221             - demux->stream_start_time) / fabs (demux->common.segment.rate);
6222       /* do not know where we are;
6223        * need to come across a cluster and generate segment */
6224       demux->common.segment.position = GST_CLOCK_TIME_NONE;
6225       demux->cluster_time = GST_CLOCK_TIME_NONE;
6226       demux->cluster_offset = 0;
6227       demux->cluster_prevsize = 0;
6228       demux->need_segment = TRUE;
6229       demux->segment_seqnum = gst_event_get_seqnum (event);
6230       /* but keep some of the upstream segment */
6231       demux->common.segment.rate = segment->rate;
6232       demux->common.segment.flags = segment->flags;
6233       /* also check if need to keep some of the requested seek position */
6234       if (demux->seek_offset == segment->start) {
6235         GST_DEBUG_OBJECT (demux, "position matches requested seek");
6236         demux->common.segment.position = demux->requested_seek_time;
6237       } else {
6238         GST_DEBUG_OBJECT (demux, "unexpected segment position");
6239       }
6240       demux->requested_seek_time = GST_CLOCK_TIME_NONE;
6241       demux->seek_offset = -1;
6242       GST_OBJECT_UNLOCK (demux);
6243     exit:
6244       /* chain will send initial segment after pads have been added,
6245        * or otherwise come up with one */
6246       GST_DEBUG_OBJECT (demux, "eating event");
6247       gst_event_unref (event);
6248       res = TRUE;
6249       break;
6250     }
6251     case GST_EVENT_EOS:
6252     {
6253       if (demux->common.state != GST_MATROSKA_READ_STATE_DATA
6254           && demux->common.state != GST_MATROSKA_READ_STATE_SCANNING) {
6255         gst_event_unref (event);
6256         GST_ELEMENT_ERROR (demux, STREAM, DEMUX,
6257             (NULL), ("got eos and didn't receive a complete header object"));
6258       } else if (demux->common.num_streams == 0) {
6259         GST_ELEMENT_ERROR (demux, STREAM, DEMUX,
6260             (NULL), ("got eos but no streams (yet)"));
6261       } else {
6262         gst_matroska_demux_send_event (demux, event);
6263       }
6264       break;
6265     }
6266     case GST_EVENT_FLUSH_STOP:
6267     {
6268       guint64 dur;
6269
6270       gst_adapter_clear (demux->common.adapter);
6271       GST_OBJECT_LOCK (demux);
6272       gst_matroska_read_common_reset_streams (&demux->common,
6273           GST_CLOCK_TIME_NONE, TRUE);
6274       gst_flow_combiner_reset (demux->flowcombiner);
6275       dur = demux->common.segment.duration;
6276       gst_segment_init (&demux->common.segment, GST_FORMAT_TIME);
6277       demux->common.segment.duration = dur;
6278       demux->cluster_time = GST_CLOCK_TIME_NONE;
6279       demux->cluster_offset = 0;
6280       demux->cluster_prevsize = 0;
6281       GST_OBJECT_UNLOCK (demux);
6282       /* fall-through */
6283     }
6284     default:
6285       res = gst_pad_event_default (pad, parent, event);
6286       break;
6287   }
6288
6289   return res;
6290 }
6291
6292 static gboolean
6293 gst_matroska_demux_sink_activate (GstPad * sinkpad, GstObject * parent)
6294 {
6295   GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (parent);
6296   GstQuery *query;
6297   gboolean pull_mode = FALSE;
6298
6299   query = gst_query_new_scheduling ();
6300
6301   if (gst_pad_peer_query (sinkpad, query))
6302     pull_mode = gst_query_has_scheduling_mode_with_flags (query,
6303         GST_PAD_MODE_PULL, GST_SCHEDULING_FLAG_SEEKABLE);
6304
6305   gst_query_unref (query);
6306
6307   if (pull_mode) {
6308     GST_DEBUG ("going to pull mode");
6309     demux->streaming = FALSE;
6310     return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PULL, TRUE);
6311   } else {
6312     GST_DEBUG ("going to push (streaming) mode");
6313     demux->streaming = TRUE;
6314     return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
6315   }
6316 }
6317
6318 static gboolean
6319 gst_matroska_demux_sink_activate_mode (GstPad * sinkpad, GstObject * parent,
6320     GstPadMode mode, gboolean active)
6321 {
6322   switch (mode) {
6323     case GST_PAD_MODE_PULL:
6324       if (active) {
6325         /* if we have a scheduler we can start the task */
6326         gst_pad_start_task (sinkpad, (GstTaskFunction) gst_matroska_demux_loop,
6327             sinkpad, NULL);
6328       } else {
6329         gst_pad_stop_task (sinkpad);
6330       }
6331       return TRUE;
6332     case GST_PAD_MODE_PUSH:
6333       return TRUE;
6334     default:
6335       return FALSE;
6336   }
6337 }
6338
6339 static GstCaps *
6340 gst_matroska_demux_video_caps (GstMatroskaTrackVideoContext *
6341     videocontext, const gchar * codec_id, guint8 * data, guint size,
6342     gchar ** codec_name, guint32 * riff_fourcc)
6343 {
6344   GstMatroskaTrackContext *context = (GstMatroskaTrackContext *) videocontext;
6345   GstCaps *caps = NULL;
6346
6347   g_assert (videocontext != NULL);
6348   g_assert (codec_name != NULL);
6349
6350   if (riff_fourcc)
6351     *riff_fourcc = 0;
6352
6353   /* TODO: check if we have all codec types from matroska-ids.h
6354    *       check if we have to do more special things with codec_private
6355    *
6356    * Add support for
6357    *  GST_MATROSKA_CODEC_ID_VIDEO_QUICKTIME
6358    *  GST_MATROSKA_CODEC_ID_VIDEO_SNOW
6359    */
6360
6361   if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC)) {
6362     gst_riff_strf_vids *vids = NULL;
6363
6364     if (data) {
6365       GstBuffer *buf = NULL;
6366
6367       vids = (gst_riff_strf_vids *) data;
6368
6369       /* assure size is big enough */
6370       if (size < 24) {
6371         GST_WARNING ("Too small BITMAPINFOHEADER (%d bytes)", size);
6372         return NULL;
6373       }
6374       if (size < sizeof (gst_riff_strf_vids)) {
6375         vids = g_new (gst_riff_strf_vids, 1);
6376         memcpy (vids, data, size);
6377       }
6378
6379       context->dts_only = TRUE; /* VFW files only store DTS */
6380
6381       /* little-endian -> byte-order */
6382       vids->size = GUINT32_FROM_LE (vids->size);
6383       vids->width = GUINT32_FROM_LE (vids->width);
6384       vids->height = GUINT32_FROM_LE (vids->height);
6385       vids->planes = GUINT16_FROM_LE (vids->planes);
6386       vids->bit_cnt = GUINT16_FROM_LE (vids->bit_cnt);
6387       vids->compression = GUINT32_FROM_LE (vids->compression);
6388       vids->image_size = GUINT32_FROM_LE (vids->image_size);
6389       vids->xpels_meter = GUINT32_FROM_LE (vids->xpels_meter);
6390       vids->ypels_meter = GUINT32_FROM_LE (vids->ypels_meter);
6391       vids->num_colors = GUINT32_FROM_LE (vids->num_colors);
6392       vids->imp_colors = GUINT32_FROM_LE (vids->imp_colors);
6393
6394       if (size > sizeof (gst_riff_strf_vids)) { /* some extra_data */
6395         gsize offset = sizeof (gst_riff_strf_vids);
6396
6397         buf = gst_buffer_new_memdup ((guint8 *) vids + offset, size - offset);
6398       }
6399
6400       if (riff_fourcc)
6401         *riff_fourcc = vids->compression;
6402
6403       caps = gst_riff_create_video_caps (vids->compression, NULL, vids,
6404           buf, NULL, codec_name);
6405
6406       if (caps == NULL) {
6407         GST_WARNING ("Unhandled RIFF fourcc %" GST_FOURCC_FORMAT,
6408             GST_FOURCC_ARGS (vids->compression));
6409       } else {
6410         static GstStaticCaps intra_caps = GST_STATIC_CAPS ("image/jpeg; "
6411             "video/x-raw; image/png; video/x-dv; video/x-huffyuv; video/x-ffv; "
6412             "video/x-compressed-yuv");
6413         context->intra_only =
6414             gst_caps_can_intersect (gst_static_caps_get (&intra_caps), caps);
6415       }
6416
6417       if (buf)
6418         gst_buffer_unref (buf);
6419
6420       if (vids != (gst_riff_strf_vids *) data)
6421         g_free (vids);
6422     }
6423   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_UNCOMPRESSED)) {
6424     GstVideoInfo info;
6425     GstVideoFormat format;
6426
6427     gst_video_info_init (&info);
6428     switch (videocontext->fourcc) {
6429       case GST_MAKE_FOURCC ('I', '4', '2', '0'):
6430         format = GST_VIDEO_FORMAT_I420;
6431         break;
6432       case GST_MAKE_FOURCC ('Y', 'U', 'Y', '2'):
6433         format = GST_VIDEO_FORMAT_YUY2;
6434         break;
6435       case GST_MAKE_FOURCC ('Y', 'V', '1', '2'):
6436         format = GST_VIDEO_FORMAT_YV12;
6437         break;
6438       case GST_MAKE_FOURCC ('U', 'Y', 'V', 'Y'):
6439         format = GST_VIDEO_FORMAT_UYVY;
6440         break;
6441       case GST_MAKE_FOURCC ('A', 'Y', 'U', 'V'):
6442         format = GST_VIDEO_FORMAT_AYUV;
6443         break;
6444       case GST_MAKE_FOURCC ('Y', '8', '0', '0'):
6445       case GST_MAKE_FOURCC ('Y', '8', ' ', ' '):
6446         format = GST_VIDEO_FORMAT_GRAY8;
6447         break;
6448       case GST_MAKE_FOURCC ('R', 'G', 'B', 24):
6449         format = GST_VIDEO_FORMAT_RGB;
6450         break;
6451       case GST_MAKE_FOURCC ('B', 'G', 'R', 24):
6452         format = GST_VIDEO_FORMAT_BGR;
6453         break;
6454       default:
6455         GST_DEBUG ("Unknown fourcc %" GST_FOURCC_FORMAT,
6456             GST_FOURCC_ARGS (videocontext->fourcc));
6457         return NULL;
6458     }
6459
6460     context->intra_only = TRUE;
6461
6462     gst_video_info_set_format (&info, format, videocontext->pixel_width,
6463         videocontext->pixel_height);
6464     caps = gst_video_info_to_caps (&info);
6465     *codec_name = gst_pb_utils_get_codec_description (caps);
6466     context->alignment = 32;
6467   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_SP)) {
6468     caps = gst_caps_new_simple ("video/x-divx",
6469         "divxversion", G_TYPE_INT, 4, NULL);
6470     *codec_name = g_strdup ("MPEG-4 simple profile");
6471   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_ASP) ||
6472       !strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_AP)) {
6473     caps = gst_caps_new_simple ("video/mpeg",
6474         "mpegversion", G_TYPE_INT, 4,
6475         "systemstream", G_TYPE_BOOLEAN, FALSE, NULL);
6476     if (data) {
6477       GstBuffer *priv;
6478
6479       priv = gst_buffer_new_memdup (data, size);
6480       gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
6481       gst_buffer_unref (priv);
6482
6483       gst_codec_utils_mpeg4video_caps_set_level_and_profile (caps, data, size);
6484     }
6485     if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_ASP))
6486       *codec_name = g_strdup ("MPEG-4 advanced simple profile");
6487     else
6488       *codec_name = g_strdup ("MPEG-4 advanced profile");
6489   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MSMPEG4V3)) {
6490 #if 0
6491     caps = gst_caps_new_full (gst_structure_new ("video/x-divx",
6492             "divxversion", G_TYPE_INT, 3, NULL),
6493         gst_structure_new ("video/x-msmpeg",
6494             "msmpegversion", G_TYPE_INT, 43, NULL), NULL);
6495 #endif
6496     caps = gst_caps_new_simple ("video/x-msmpeg",
6497         "msmpegversion", G_TYPE_INT, 43, NULL);
6498     *codec_name = g_strdup ("Microsoft MPEG-4 v.3");
6499   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG1) ||
6500       !strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG2)) {
6501     gint mpegversion;
6502
6503     if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG1))
6504       mpegversion = 1;
6505     else
6506       mpegversion = 2;
6507
6508     caps = gst_caps_new_simple ("video/mpeg",
6509         "systemstream", G_TYPE_BOOLEAN, FALSE,
6510         "mpegversion", G_TYPE_INT, mpegversion, NULL);
6511     *codec_name = g_strdup_printf ("MPEG-%d video", mpegversion);
6512     context->postprocess_frame = gst_matroska_demux_add_mpeg_seq_header;
6513   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MJPEG)) {
6514     caps = gst_caps_new_empty_simple ("image/jpeg");
6515     *codec_name = g_strdup ("Motion-JPEG");
6516     context->intra_only = TRUE;
6517   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_AVC)) {
6518     caps = gst_caps_new_empty_simple ("video/x-h264");
6519     if (data) {
6520       GstBuffer *priv;
6521
6522       /* First byte is the version, second is the profile indication, and third
6523        * is the 5 contraint_set_flags and 3 reserved bits. Fourth byte is the
6524        * level indication. */
6525       gst_codec_utils_h264_caps_set_level_and_profile (caps, data + 1,
6526           size - 1);
6527
6528       priv = gst_buffer_new_memdup (data, size);
6529       gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
6530       gst_buffer_unref (priv);
6531
6532       gst_caps_set_simple (caps, "stream-format", G_TYPE_STRING, "avc",
6533           "alignment", G_TYPE_STRING, "au", NULL);
6534     } else {
6535       GST_WARNING ("No codec data found, assuming output is byte-stream");
6536       gst_caps_set_simple (caps, "stream-format", G_TYPE_STRING, "byte-stream",
6537           NULL);
6538     }
6539     *codec_name = g_strdup ("H264");
6540   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEGH_HEVC)) {
6541     caps = gst_caps_new_empty_simple ("video/x-h265");
6542     if (data) {
6543       GstBuffer *priv;
6544
6545       gst_codec_utils_h265_caps_set_level_tier_and_profile (caps, data + 1,
6546           size - 1);
6547
6548       priv = gst_buffer_new_memdup (data, size);
6549       gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
6550       gst_buffer_unref (priv);
6551
6552       gst_caps_set_simple (caps, "stream-format", G_TYPE_STRING, "hvc1",
6553           "alignment", G_TYPE_STRING, "au", NULL);
6554     } else {
6555       GST_WARNING ("No codec data found, assuming output is byte-stream");
6556       gst_caps_set_simple (caps, "stream-format", G_TYPE_STRING, "byte-stream",
6557           NULL);
6558     }
6559     *codec_name = g_strdup ("HEVC");
6560   } else if ((!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO1)) ||
6561       (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO2)) ||
6562       (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO3)) ||
6563       (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO4))) {
6564     gint rmversion = -1;
6565
6566     if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO1))
6567       rmversion = 1;
6568     else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO2))
6569       rmversion = 2;
6570     else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO3))
6571       rmversion = 3;
6572     else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO4))
6573       rmversion = 4;
6574
6575     caps = gst_caps_new_simple ("video/x-pn-realvideo",
6576         "rmversion", G_TYPE_INT, rmversion, NULL);
6577     GST_DEBUG ("data:%p, size:0x%x", data, size);
6578     /* We need to extract the extradata ! */
6579     if (data && (size >= 0x22)) {
6580       GstBuffer *priv;
6581       guint rformat;
6582       guint subformat;
6583
6584       subformat = GST_READ_UINT32_BE (data + 0x1a);
6585       rformat = GST_READ_UINT32_BE (data + 0x1e);
6586
6587       priv = gst_buffer_new_memdup (data + 0x1a, size - 0x1a);
6588       gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, "format",
6589           G_TYPE_INT, rformat, "subformat", G_TYPE_INT, subformat, NULL);
6590       gst_buffer_unref (priv);
6591
6592     }
6593     *codec_name = g_strdup_printf ("RealVideo %d.0", rmversion);
6594   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_THEORA)) {
6595     caps = gst_caps_new_empty_simple ("video/x-theora");
6596     context->stream_headers =
6597         gst_matroska_parse_xiph_stream_headers (context->codec_priv,
6598         context->codec_priv_size);
6599     /* FIXME: mark stream as broken and skip if there are no stream headers */
6600     context->send_stream_headers = TRUE;
6601   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_DIRAC)) {
6602     caps = gst_caps_new_empty_simple ("video/x-dirac");
6603     *codec_name = g_strdup_printf ("Dirac");
6604   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_VP8)) {
6605     caps = gst_caps_new_empty_simple ("video/x-vp8");
6606     if (videocontext->alpha_mode)
6607       gst_caps_set_simple (caps, "codec-alpha", G_TYPE_BOOLEAN, TRUE, NULL);
6608     *codec_name = g_strdup_printf ("On2 VP8");
6609   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_VP9)) {
6610     caps = gst_caps_new_empty_simple ("video/x-vp9");
6611     if (videocontext->alpha_mode)
6612       gst_caps_set_simple (caps, "codec-alpha", G_TYPE_BOOLEAN, TRUE, NULL);
6613     *codec_name = g_strdup_printf ("On2 VP9");
6614   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_AV1)) {
6615     caps = gst_caps_new_empty_simple ("video/x-av1");
6616     if (data) {
6617       GstBuffer *priv;
6618
6619       priv = gst_buffer_new_memdup (data, size);
6620       gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
6621       gst_buffer_unref (priv);
6622     } else {
6623       GST_WARNING ("No AV1 codec data found!");
6624     }
6625     *codec_name = g_strdup_printf ("AOM AV1");
6626   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_PRORES)) {
6627     guint32 fourcc;
6628     const gchar *variant, *variant_descr = "";
6629
6630     /* Expect a fourcc in the codec private data */
6631     if (!data || size < 4) {
6632       GST_WARNING ("No or too small PRORESS fourcc (%d bytes)", size);
6633       return NULL;
6634     }
6635
6636     fourcc = GST_STR_FOURCC (data);
6637     switch (fourcc) {
6638       case GST_MAKE_FOURCC ('a', 'p', 'c', 's'):
6639         variant_descr = " 4:2:2 LT";
6640         variant = "lt";
6641         break;
6642       case GST_MAKE_FOURCC ('a', 'p', 'c', 'h'):
6643         variant = "hq";
6644         variant_descr = " 4:2:2 HQ";
6645         break;
6646       case GST_MAKE_FOURCC ('a', 'p', '4', 'h'):
6647         variant = "4444";
6648         variant_descr = " 4:4:4:4";
6649         break;
6650       case GST_MAKE_FOURCC ('a', 'p', 'c', 'o'):
6651         variant = "proxy";
6652         variant_descr = " 4:2:2 Proxy";
6653         break;
6654       case GST_MAKE_FOURCC ('a', 'p', 'c', 'n'):
6655       default:
6656         variant = "standard";
6657         variant_descr = " 4:2:2 SD";
6658         break;
6659     }
6660
6661     GST_LOG ("Prores video, codec fourcc %" GST_FOURCC_FORMAT,
6662         GST_FOURCC_ARGS (fourcc));
6663
6664     caps = gst_caps_new_simple ("video/x-prores",
6665         "format", G_TYPE_STRING, variant, NULL);
6666     *codec_name = g_strdup_printf ("Apple ProRes%s", variant_descr);
6667     context->postprocess_frame = gst_matroska_demux_add_prores_header;
6668   } else {
6669     GST_WARNING ("Unknown codec '%s', cannot build Caps", codec_id);
6670     return NULL;
6671   }
6672
6673   if (caps != NULL) {
6674     int i;
6675     GstStructure *structure;
6676
6677     for (i = 0; i < gst_caps_get_size (caps); i++) {
6678       structure = gst_caps_get_structure (caps, i);
6679
6680       /* FIXME: use the real unit here! */
6681       GST_DEBUG ("video size %dx%d, target display size %dx%d (any unit)",
6682           videocontext->pixel_width,
6683           videocontext->pixel_height,
6684           videocontext->display_width, videocontext->display_height);
6685
6686       /* pixel width and height are the w and h of the video in pixels */
6687       if (videocontext->pixel_width > 0 && videocontext->pixel_height > 0) {
6688         gint w = videocontext->pixel_width;
6689         gint h = videocontext->pixel_height;
6690
6691         gst_structure_set (structure,
6692             "width", G_TYPE_INT, w, "height", G_TYPE_INT, h, NULL);
6693       }
6694
6695       if (videocontext->display_width > 0 || videocontext->display_height > 0) {
6696         int n, d;
6697
6698         if (videocontext->display_width <= 0)
6699           videocontext->display_width = videocontext->pixel_width;
6700         if (videocontext->display_height <= 0)
6701           videocontext->display_height = videocontext->pixel_height;
6702
6703         /* calculate the pixel aspect ratio using the display and pixel w/h */
6704         n = videocontext->display_width * videocontext->pixel_height;
6705         d = videocontext->display_height * videocontext->pixel_width;
6706         GST_DEBUG ("setting PAR to %d/%d", n, d);
6707         gst_structure_set (structure, "pixel-aspect-ratio",
6708             GST_TYPE_FRACTION,
6709             videocontext->display_width * videocontext->pixel_height,
6710             videocontext->display_height * videocontext->pixel_width, NULL);
6711       }
6712
6713       if (videocontext->default_fps > 0.0) {
6714         gint fps_n, fps_d;
6715
6716         gst_util_double_to_fraction (videocontext->default_fps, &fps_n, &fps_d);
6717
6718         GST_DEBUG ("using default fps %d/%d", fps_n, fps_d);
6719
6720         gst_structure_set (structure, "framerate", GST_TYPE_FRACTION, fps_n,
6721             fps_d, NULL);
6722       } else if (context->default_duration > 0) {
6723         int fps_n, fps_d;
6724
6725         gst_video_guess_framerate (context->default_duration, &fps_n, &fps_d);
6726
6727         GST_INFO ("using default duration %" G_GUINT64_FORMAT
6728             " framerate %d/%d", context->default_duration, fps_n, fps_d);
6729
6730         gst_structure_set (structure, "framerate", GST_TYPE_FRACTION,
6731             fps_n, fps_d, NULL);
6732       } else {
6733         gst_structure_set (structure, "framerate", GST_TYPE_FRACTION,
6734             0, 1, NULL);
6735       }
6736
6737       switch (videocontext->interlace_mode) {
6738         case GST_MATROSKA_INTERLACE_MODE_PROGRESSIVE:
6739           gst_structure_set (structure,
6740               "interlace-mode", G_TYPE_STRING, "progressive", NULL);
6741           break;
6742         case GST_MATROSKA_INTERLACE_MODE_INTERLACED:
6743           gst_structure_set (structure,
6744               "interlace-mode", G_TYPE_STRING, "interleaved", NULL);
6745
6746           if (videocontext->field_order != GST_VIDEO_FIELD_ORDER_UNKNOWN)
6747             gst_structure_set (structure, "field-order", G_TYPE_STRING,
6748                 gst_video_field_order_to_string (videocontext->field_order),
6749                 NULL);
6750           break;
6751         default:
6752           break;
6753       }
6754     }
6755     if (videocontext->multiview_mode != GST_VIDEO_MULTIVIEW_MODE_NONE) {
6756       if (gst_video_multiview_guess_half_aspect (videocontext->multiview_mode,
6757               videocontext->pixel_width, videocontext->pixel_height,
6758               videocontext->display_width * videocontext->pixel_height,
6759               videocontext->display_height * videocontext->pixel_width)) {
6760         videocontext->multiview_flags |= GST_VIDEO_MULTIVIEW_FLAGS_HALF_ASPECT;
6761       }
6762       gst_caps_set_simple (caps,
6763           "multiview-mode", G_TYPE_STRING,
6764           gst_video_multiview_mode_to_caps_string
6765           (videocontext->multiview_mode), "multiview-flags",
6766           GST_TYPE_VIDEO_MULTIVIEW_FLAGSET, videocontext->multiview_flags,
6767           GST_FLAG_SET_MASK_EXACT, NULL);
6768     }
6769
6770     if (videocontext->colorimetry.range != GST_VIDEO_COLOR_RANGE_UNKNOWN ||
6771         videocontext->colorimetry.matrix != GST_VIDEO_COLOR_MATRIX_UNKNOWN ||
6772         videocontext->colorimetry.transfer != GST_VIDEO_TRANSFER_UNKNOWN ||
6773         videocontext->colorimetry.primaries !=
6774         GST_VIDEO_COLOR_PRIMARIES_UNKNOWN) {
6775       gchar *colorimetry =
6776           gst_video_colorimetry_to_string (&videocontext->colorimetry);
6777       gst_caps_set_simple (caps, "colorimetry", G_TYPE_STRING, colorimetry,
6778           NULL);
6779       GST_DEBUG ("setting colorimetry to %s", colorimetry);
6780       g_free (colorimetry);
6781     }
6782
6783     if (videocontext->mastering_display_info_present) {
6784       if (!gst_video_mastering_display_info_add_to_caps
6785           (&videocontext->mastering_display_info, caps)) {
6786         GST_WARNING ("couldn't set mastering display info to caps");
6787       }
6788     }
6789
6790     if (videocontext->content_light_level.max_content_light_level &&
6791         videocontext->content_light_level.max_frame_average_light_level) {
6792       if (!gst_video_content_light_level_add_to_caps
6793           (&videocontext->content_light_level, caps)) {
6794         GST_WARNING ("couldn't set content light level to caps");
6795       }
6796     }
6797
6798     caps = gst_caps_simplify (caps);
6799   }
6800
6801   return caps;
6802 }
6803
6804 /*
6805  * Some AAC specific code... *sigh*
6806  * FIXME: maybe we should use '15' and code the sample rate explicitly
6807  * if the sample rate doesn't match the predefined rates exactly? (tpm)
6808  */
6809
6810 static gint
6811 aac_rate_idx (gint rate)
6812 {
6813   if (92017 <= rate)
6814     return 0;
6815   else if (75132 <= rate)
6816     return 1;
6817   else if (55426 <= rate)
6818     return 2;
6819   else if (46009 <= rate)
6820     return 3;
6821   else if (37566 <= rate)
6822     return 4;
6823   else if (27713 <= rate)
6824     return 5;
6825   else if (23004 <= rate)
6826     return 6;
6827   else if (18783 <= rate)
6828     return 7;
6829   else if (13856 <= rate)
6830     return 8;
6831   else if (11502 <= rate)
6832     return 9;
6833   else if (9391 <= rate)
6834     return 10;
6835   else
6836     return 11;
6837 }
6838
6839 static gint
6840 aac_profile_idx (const gchar * codec_id)
6841 {
6842   gint profile;
6843
6844   if (strlen (codec_id) <= 12)
6845     profile = 3;
6846   else if (!strncmp (&codec_id[12], "MAIN", 4))
6847     profile = 0;
6848   else if (!strncmp (&codec_id[12], "LC", 2))
6849     profile = 1;
6850   else if (!strncmp (&codec_id[12], "SSR", 3))
6851     profile = 2;
6852   else
6853     profile = 3;
6854
6855   return profile;
6856 }
6857
6858 static guint
6859 round_up_pow2 (guint n)
6860 {
6861   n = n - 1;
6862   n = n | (n >> 1);
6863   n = n | (n >> 2);
6864   n = n | (n >> 4);
6865   n = n | (n >> 8);
6866   n = n | (n >> 16);
6867   return n + 1;
6868 }
6869
6870 #define AAC_SYNC_EXTENSION_TYPE 0x02b7
6871
6872 static GstCaps *
6873 gst_matroska_demux_audio_caps (GstMatroskaTrackAudioContext *
6874     audiocontext, const gchar * codec_id, guint8 * data, guint size,
6875     gchar ** codec_name, guint16 * riff_audio_fmt, GstClockTime * lead_in_ts)
6876 {
6877   GstMatroskaTrackContext *context = (GstMatroskaTrackContext *) audiocontext;
6878   GstCaps *caps = NULL;
6879   guint lead_in = 0;
6880   /* Max potential blocksize causing the longest possible lead_in_ts need, as
6881    * we don't have the exact number parsed out here */
6882   guint max_blocksize = 0;
6883   /* Original samplerate before SBR multiplications, as parsers would use */
6884   guint rate = audiocontext->samplerate;
6885
6886   g_assert (audiocontext != NULL);
6887   g_assert (codec_name != NULL);
6888
6889   if (riff_audio_fmt)
6890     *riff_audio_fmt = 0;
6891
6892   /* TODO: check if we have all codec types from matroska-ids.h
6893    *       check if we have to do more special things with codec_private
6894    *       check if we need bitdepth in different places too
6895    *       implement channel position magic
6896    * Add support for:
6897    *  GST_MATROSKA_CODEC_ID_AUDIO_AC3_BSID9
6898    *  GST_MATROSKA_CODEC_ID_AUDIO_AC3_BSID10
6899    *  GST_MATROSKA_CODEC_ID_AUDIO_QUICKTIME_QDMC
6900    *  GST_MATROSKA_CODEC_ID_AUDIO_QUICKTIME_QDM2
6901    */
6902
6903   if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L1) ||
6904       !strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L2) ||
6905       !strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L3)) {
6906     gint layer;
6907
6908     if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L1))
6909       layer = 1;
6910     else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L2))
6911       layer = 2;
6912     else
6913       layer = 3;
6914
6915     lead_in = 30;               /* Could mp2 need as much too? */
6916     max_blocksize = 1152;
6917     caps = gst_caps_new_simple ("audio/mpeg",
6918         "mpegversion", G_TYPE_INT, 1, "layer", G_TYPE_INT, layer, NULL);
6919     *codec_name = g_strdup_printf ("MPEG-1 layer %d", layer);
6920   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_PCM_INT_BE) ||
6921       !strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_PCM_INT_LE)) {
6922     gboolean sign;
6923     gint endianness;
6924     GstAudioFormat format;
6925
6926     sign = (audiocontext->bitdepth != 8);
6927     if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_PCM_INT_BE))
6928       endianness = G_BIG_ENDIAN;
6929     else
6930       endianness = G_LITTLE_ENDIAN;
6931
6932     format = gst_audio_format_build_integer (sign, endianness,
6933         audiocontext->bitdepth, audiocontext->bitdepth);
6934
6935     /* FIXME: Channel mask and reordering */
6936     caps = gst_caps_new_simple ("audio/x-raw",
6937         "format", G_TYPE_STRING, gst_audio_format_to_string (format),
6938         "layout", G_TYPE_STRING, "interleaved",
6939         "channel-mask", GST_TYPE_BITMASK,
6940         gst_audio_channel_get_fallback_mask (audiocontext->channels), NULL);
6941
6942     *codec_name = g_strdup_printf ("Raw %d-bit PCM audio",
6943         audiocontext->bitdepth);
6944     context->alignment = GST_ROUND_UP_8 (audiocontext->bitdepth) / 8;
6945     context->alignment = round_up_pow2 (context->alignment);
6946   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_PCM_FLOAT)) {
6947     const gchar *format;
6948     if (audiocontext->bitdepth == 32)
6949       format = "F32LE";
6950     else
6951       format = "F64LE";
6952     /* FIXME: Channel mask and reordering */
6953     caps = gst_caps_new_simple ("audio/x-raw",
6954         "format", G_TYPE_STRING, format,
6955         "layout", G_TYPE_STRING, "interleaved",
6956         "channel-mask", GST_TYPE_BITMASK,
6957         gst_audio_channel_get_fallback_mask (audiocontext->channels), NULL);
6958     *codec_name = g_strdup_printf ("Raw %d-bit floating-point audio",
6959         audiocontext->bitdepth);
6960     context->alignment = audiocontext->bitdepth / 8;
6961     context->alignment = round_up_pow2 (context->alignment);
6962   } else if (!strncmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_AC3,
6963           strlen (GST_MATROSKA_CODEC_ID_AUDIO_AC3))) {
6964     lead_in = 2;
6965     max_blocksize = 1536;
6966     caps = gst_caps_new_simple ("audio/x-ac3",
6967         "framed", G_TYPE_BOOLEAN, TRUE, NULL);
6968     *codec_name = g_strdup ("AC-3 audio");
6969   } else if (!strncmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_EAC3,
6970           strlen (GST_MATROSKA_CODEC_ID_AUDIO_EAC3))) {
6971     lead_in = 2;
6972     max_blocksize = 1536;
6973     caps = gst_caps_new_simple ("audio/x-eac3",
6974         "framed", G_TYPE_BOOLEAN, TRUE, NULL);
6975     *codec_name = g_strdup ("E-AC-3 audio");
6976   } else if (!strncmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_TRUEHD,
6977           strlen (GST_MATROSKA_CODEC_ID_AUDIO_TRUEHD))) {
6978     caps = gst_caps_new_empty_simple ("audio/x-true-hd");
6979     *codec_name = g_strdup ("Dolby TrueHD");
6980   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_DTS)) {
6981     caps = gst_caps_new_empty_simple ("audio/x-dts");
6982     *codec_name = g_strdup ("DTS audio");
6983   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_VORBIS)) {
6984     caps = gst_caps_new_empty_simple ("audio/x-vorbis");
6985     context->stream_headers =
6986         gst_matroska_parse_xiph_stream_headers (context->codec_priv,
6987         context->codec_priv_size);
6988     /* FIXME: mark stream as broken and skip if there are no stream headers */
6989     context->send_stream_headers = TRUE;
6990   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_FLAC)) {
6991     caps = gst_caps_new_empty_simple ("audio/x-flac");
6992     context->stream_headers =
6993         gst_matroska_parse_flac_stream_headers (context->codec_priv,
6994         context->codec_priv_size);
6995     /* FIXME: mark stream as broken and skip if there are no stream headers */
6996     context->send_stream_headers = TRUE;
6997   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_SPEEX)) {
6998     caps = gst_caps_new_empty_simple ("audio/x-speex");
6999     context->stream_headers =
7000         gst_matroska_parse_speex_stream_headers (context->codec_priv,
7001         context->codec_priv_size);
7002     /* FIXME: mark stream as broken and skip if there are no stream headers */
7003     context->send_stream_headers = TRUE;
7004   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_OPUS)) {
7005     GstBuffer *tmp;
7006
7007     if (context->codec_priv_size >= 19) {
7008       if (audiocontext->samplerate)
7009         GST_WRITE_UINT32_LE ((guint8 *) context->codec_priv + 12,
7010             audiocontext->samplerate);
7011       if (context->codec_delay) {
7012         guint64 delay =
7013             gst_util_uint64_scale_round (context->codec_delay, 48000,
7014             GST_SECOND);
7015         GST_WRITE_UINT16_LE ((guint8 *) context->codec_priv + 10, delay);
7016       }
7017
7018       tmp =
7019           gst_buffer_new_memdup (context->codec_priv, context->codec_priv_size);
7020       caps = gst_codec_utils_opus_create_caps_from_header (tmp, NULL);
7021       gst_buffer_unref (tmp);
7022       *codec_name = g_strdup ("Opus");
7023     } else if (context->codec_priv_size == 0) {
7024       GST_WARNING ("No Opus codec data found, trying to create one");
7025       if (audiocontext->channels <= 2) {
7026         guint8 streams, coupled, channels;
7027         guint32 samplerate;
7028
7029         samplerate =
7030             audiocontext->samplerate == 0 ? 48000 : audiocontext->samplerate;
7031         rate = samplerate;
7032         channels = audiocontext->channels == 0 ? 2 : audiocontext->channels;
7033         if (channels == 1) {
7034           streams = 1;
7035           coupled = 0;
7036         } else {
7037           streams = 1;
7038           coupled = 1;
7039         }
7040
7041         caps =
7042             gst_codec_utils_opus_create_caps (samplerate, channels, 0, streams,
7043             coupled, NULL);
7044         if (caps) {
7045           *codec_name = g_strdup ("Opus");
7046         } else {
7047           GST_WARNING ("Failed to create Opus caps from audio context");
7048         }
7049       } else {
7050         GST_WARNING ("No Opus codec data, and not enough info to create one");
7051       }
7052     } else {
7053       GST_WARNING ("Invalid Opus codec data size (got %" G_GSIZE_FORMAT
7054           ", expected 19)", context->codec_priv_size);
7055     }
7056   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_ACM)) {
7057     gst_riff_strf_auds auds;
7058
7059     if (data && size >= 18) {
7060       GstBuffer *codec_data = NULL;
7061
7062       /* little-endian -> byte-order */
7063       auds.format = GST_READ_UINT16_LE (data);
7064       auds.channels = GST_READ_UINT16_LE (data + 2);
7065       auds.rate = GST_READ_UINT32_LE (data + 4);
7066       auds.av_bps = GST_READ_UINT32_LE (data + 8);
7067       auds.blockalign = GST_READ_UINT16_LE (data + 12);
7068       auds.bits_per_sample = GST_READ_UINT16_LE (data + 16);
7069
7070       /* 18 is the waveformatex size */
7071       if (size > 18) {
7072         codec_data = gst_buffer_new_wrapped_full (GST_MEMORY_FLAG_READONLY,
7073             data + 18, size - 18, 0, size - 18, NULL, NULL);
7074       }
7075
7076       if (riff_audio_fmt)
7077         *riff_audio_fmt = auds.format;
7078
7079       /* FIXME: Handle reorder map */
7080       caps = gst_riff_create_audio_caps (auds.format, NULL, &auds, codec_data,
7081           NULL, codec_name, NULL);
7082       if (codec_data)
7083         gst_buffer_unref (codec_data);
7084
7085       if (caps == NULL) {
7086         GST_WARNING ("Unhandled RIFF audio format 0x%02x", auds.format);
7087       }
7088     } else {
7089       GST_WARNING ("Invalid codec data size (%d expected, got %d)", 18, size);
7090     }
7091   } else if (g_str_has_prefix (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_AAC)) {
7092     GstBuffer *priv = NULL;
7093     gint mpegversion;
7094     gint rate_idx, profile;
7095     guint8 *data = NULL;
7096
7097     /* unspecified AAC profile with opaque private codec data */
7098     if (strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_AAC) == 0) {
7099       if (context->codec_priv_size >= 2) {
7100         guint obj_type, freq_index, explicit_freq_bytes = 0;
7101
7102         codec_id = GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG4;
7103         mpegversion = 4;
7104         freq_index = (GST_READ_UINT16_BE (context->codec_priv) & 0x780) >> 7;
7105         obj_type = (GST_READ_UINT16_BE (context->codec_priv) & 0xF800) >> 11;
7106         if (freq_index == 15)
7107           explicit_freq_bytes = 3;
7108         GST_DEBUG ("obj_type = %u, freq_index = %u", obj_type, freq_index);
7109         priv = gst_buffer_new_memdup (context->codec_priv,
7110             context->codec_priv_size);
7111         /* assume SBR if samplerate <= 24kHz */
7112         if (obj_type == 5 || (freq_index >= 6 && freq_index != 15) ||
7113             (context->codec_priv_size == (5 + explicit_freq_bytes))) {
7114           /* TODO: Commonly aacparse will reset the rate in caps to
7115            * non-multiplied - which one is correct? */
7116           audiocontext->samplerate *= 2;
7117         }
7118       } else {
7119         GST_WARNING ("Opaque A_AAC codec ID, but no codec private data");
7120         /* this is pretty broken;
7121          * maybe we need to make up some default private,
7122          * or maybe ADTS data got dumped in.
7123          * Let's set up some private data now, and check actual data later */
7124         /* just try this and see what happens ... */
7125         codec_id = GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG4;
7126         context->postprocess_frame = gst_matroska_demux_check_aac;
7127       }
7128     }
7129
7130     /* make up decoder-specific data if it is not supplied */
7131     if (priv == NULL) {
7132       GstMapInfo map;
7133
7134       priv = gst_buffer_new_allocate (NULL, 5, NULL);
7135       gst_buffer_map (priv, &map, GST_MAP_WRITE);
7136       data = map.data;
7137       rate_idx = aac_rate_idx (audiocontext->samplerate);
7138       profile = aac_profile_idx (codec_id);
7139
7140       data[0] = ((profile + 1) << 3) | ((rate_idx & 0xE) >> 1);
7141       data[1] = ((rate_idx & 0x1) << 7) | (audiocontext->channels << 3);
7142
7143       if (!strncmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG2,
7144               strlen (GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG2))) {
7145         mpegversion = 2;
7146         gst_buffer_unmap (priv, &map);
7147         gst_buffer_set_size (priv, 2);
7148       } else if (!strncmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG4,
7149               strlen (GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG4))) {
7150         mpegversion = 4;
7151
7152         if (g_strrstr (codec_id, "SBR")) {
7153           /* HE-AAC (aka SBR AAC) */
7154           audiocontext->samplerate *= 2;
7155           rate_idx = aac_rate_idx (audiocontext->samplerate);
7156           data[2] = AAC_SYNC_EXTENSION_TYPE >> 3;
7157           data[3] = ((AAC_SYNC_EXTENSION_TYPE & 0x07) << 5) | 5;
7158           data[4] = (1 << 7) | (rate_idx << 3);
7159           gst_buffer_unmap (priv, &map);
7160         } else {
7161           gst_buffer_unmap (priv, &map);
7162           gst_buffer_set_size (priv, 2);
7163         }
7164       } else {
7165         gst_buffer_unmap (priv, &map);
7166         gst_buffer_unref (priv);
7167         priv = NULL;
7168         GST_ERROR ("Unknown AAC profile and no codec private data");
7169       }
7170     }
7171
7172     if (priv) {
7173       lead_in = 2;
7174       max_blocksize = 1024;
7175       caps = gst_caps_new_simple ("audio/mpeg",
7176           "mpegversion", G_TYPE_INT, mpegversion,
7177           "framed", G_TYPE_BOOLEAN, TRUE,
7178           "stream-format", G_TYPE_STRING, "raw", NULL);
7179       gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
7180       if (context->codec_priv && context->codec_priv_size > 0)
7181         gst_codec_utils_aac_caps_set_level_and_profile (caps,
7182             context->codec_priv, context->codec_priv_size);
7183       *codec_name = g_strdup_printf ("MPEG-%d AAC audio", mpegversion);
7184       gst_buffer_unref (priv);
7185     }
7186   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_TTA)) {
7187     caps = gst_caps_new_simple ("audio/x-tta",
7188         "width", G_TYPE_INT, audiocontext->bitdepth, NULL);
7189     *codec_name = g_strdup ("TTA audio");
7190   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_WAVPACK4)) {
7191     caps = gst_caps_new_simple ("audio/x-wavpack",
7192         "width", G_TYPE_INT, audiocontext->bitdepth,
7193         "framed", G_TYPE_BOOLEAN, TRUE, NULL);
7194     *codec_name = g_strdup ("Wavpack audio");
7195     context->postprocess_frame = gst_matroska_demux_add_wvpk_header;
7196     audiocontext->wvpk_block_index = 0;
7197   } else if ((!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_14_4)) ||
7198       (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_28_8)) ||
7199       (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_COOK))) {
7200     gint raversion = -1;
7201
7202     if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_14_4))
7203       raversion = 1;
7204     else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_COOK))
7205       raversion = 8;
7206     else
7207       raversion = 2;
7208
7209     caps = gst_caps_new_simple ("audio/x-pn-realaudio",
7210         "raversion", G_TYPE_INT, raversion, NULL);
7211     /* Extract extra information from caps, mapping varies based on codec */
7212     if (data && (size >= 0x50)) {
7213       GstBuffer *priv;
7214       guint flavor;
7215       guint packet_size;
7216       guint height;
7217       guint leaf_size;
7218       guint sample_width;
7219       guint extra_data_size;
7220
7221       GST_DEBUG ("real audio raversion:%d", raversion);
7222       if (raversion == 8) {
7223         /* COOK */
7224         flavor = GST_READ_UINT16_BE (data + 22);
7225         packet_size = GST_READ_UINT32_BE (data + 24);
7226         height = GST_READ_UINT16_BE (data + 40);
7227         leaf_size = GST_READ_UINT16_BE (data + 44);
7228         sample_width = GST_READ_UINT16_BE (data + 58);
7229         extra_data_size = GST_READ_UINT32_BE (data + 74);
7230
7231         GST_DEBUG
7232             ("flavor:%d, packet_size:%d, height:%d, leaf_size:%d, sample_width:%d, extra_data_size:%d",
7233             flavor, packet_size, height, leaf_size, sample_width,
7234             extra_data_size);
7235         gst_caps_set_simple (caps, "flavor", G_TYPE_INT, flavor, "packet_size",
7236             G_TYPE_INT, packet_size, "height", G_TYPE_INT, height, "leaf_size",
7237             G_TYPE_INT, leaf_size, "width", G_TYPE_INT, sample_width, NULL);
7238
7239         if ((size - 78) >= extra_data_size) {
7240           priv = gst_buffer_new_memdup (data + 78, extra_data_size);
7241           gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
7242           gst_buffer_unref (priv);
7243         }
7244       }
7245     }
7246
7247     *codec_name = g_strdup_printf ("RealAudio %d.0", raversion);
7248   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_SIPR)) {
7249     caps = gst_caps_new_empty_simple ("audio/x-sipro");
7250     *codec_name = g_strdup ("Sipro/ACELP.NET Voice Codec");
7251   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_RALF)) {
7252     caps = gst_caps_new_empty_simple ("audio/x-ralf-mpeg4-generic");
7253     *codec_name = g_strdup ("Real Audio Lossless");
7254   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_ATRC)) {
7255     caps = gst_caps_new_empty_simple ("audio/x-vnd.sony.atrac3");
7256     *codec_name = g_strdup ("Sony ATRAC3");
7257   } else {
7258     GST_WARNING ("Unknown codec '%s', cannot build Caps", codec_id);
7259     return NULL;
7260   }
7261
7262   if (caps != NULL) {
7263     if (audiocontext->samplerate > 0 && audiocontext->channels > 0) {
7264       gint i;
7265
7266       for (i = 0; i < gst_caps_get_size (caps); i++) {
7267         gst_structure_set (gst_caps_get_structure (caps, i),
7268             "channels", G_TYPE_INT, audiocontext->channels,
7269             "rate", G_TYPE_INT, audiocontext->samplerate, NULL);
7270       }
7271     }
7272
7273     caps = gst_caps_simplify (caps);
7274   }
7275
7276   if (lead_in_ts && lead_in && max_blocksize && rate) {
7277     *lead_in_ts =
7278         gst_util_uint64_scale (GST_SECOND, max_blocksize * lead_in, rate);
7279   }
7280
7281   return caps;
7282 }
7283
7284 static GstCaps *
7285 gst_matroska_demux_subtitle_caps (GstMatroskaTrackSubtitleContext *
7286     subtitlecontext, const gchar * codec_id, gpointer data, guint size)
7287 {
7288   GstCaps *caps = NULL;
7289   GstMatroskaTrackContext *context =
7290       (GstMatroskaTrackContext *) subtitlecontext;
7291
7292   /* for backwards compatibility */
7293   if (!g_ascii_strcasecmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_ASCII))
7294     codec_id = GST_MATROSKA_CODEC_ID_SUBTITLE_UTF8;
7295   else if (!g_ascii_strcasecmp (codec_id, "S_SSA"))
7296     codec_id = GST_MATROSKA_CODEC_ID_SUBTITLE_SSA;
7297   else if (!g_ascii_strcasecmp (codec_id, "S_ASS"))
7298     codec_id = GST_MATROSKA_CODEC_ID_SUBTITLE_ASS;
7299   else if (!g_ascii_strcasecmp (codec_id, "S_USF"))
7300     codec_id = GST_MATROSKA_CODEC_ID_SUBTITLE_USF;
7301
7302   /* TODO: Add GST_MATROSKA_CODEC_ID_SUBTITLE_BMP support
7303    * Check if we have to do something with codec_private */
7304   if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_UTF8)) {
7305     /* well, plain text simply does not have a lot of markup ... */
7306     caps = gst_caps_new_simple ("text/x-raw", "format", G_TYPE_STRING,
7307         "pango-markup", NULL);
7308     context->postprocess_frame = gst_matroska_demux_check_subtitle_buffer;
7309     subtitlecontext->check_markup = TRUE;
7310   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_SSA)) {
7311     caps = gst_caps_new_empty_simple ("application/x-ssa");
7312     context->postprocess_frame = gst_matroska_demux_check_subtitle_buffer;
7313     subtitlecontext->check_markup = FALSE;
7314   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_ASS)) {
7315     caps = gst_caps_new_empty_simple ("application/x-ass");
7316     context->postprocess_frame = gst_matroska_demux_check_subtitle_buffer;
7317     subtitlecontext->check_markup = FALSE;
7318   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_USF)) {
7319     caps = gst_caps_new_empty_simple ("application/x-usf");
7320     context->postprocess_frame = gst_matroska_demux_check_subtitle_buffer;
7321     subtitlecontext->check_markup = FALSE;
7322   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_VOBSUB)) {
7323     caps = gst_caps_new_empty_simple ("subpicture/x-dvd");
7324     ((GstMatroskaTrackContext *) subtitlecontext)->send_dvd_event = TRUE;
7325   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_HDMVPGS)) {
7326     caps = gst_caps_new_empty_simple ("subpicture/x-pgs");
7327   } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_KATE)) {
7328     caps = gst_caps_new_empty_simple ("subtitle/x-kate");
7329     context->stream_headers =
7330         gst_matroska_parse_xiph_stream_headers (context->codec_priv,
7331         context->codec_priv_size);
7332     /* FIXME: mark stream as broken and skip if there are no stream headers */
7333     context->send_stream_headers = TRUE;
7334   } else {
7335     GST_DEBUG ("Unknown subtitle stream: codec_id='%s'", codec_id);
7336     caps = gst_caps_new_empty_simple ("application/x-subtitle-unknown");
7337   }
7338
7339   if (data != NULL && size > 0) {
7340     GstBuffer *buf;
7341
7342     buf = gst_buffer_new_memdup (data, size);
7343     gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, buf, NULL);
7344     gst_buffer_unref (buf);
7345   }
7346
7347   return caps;
7348 }
7349
7350 #if 0
7351 static void
7352 gst_matroska_demux_set_index (GstElement * element, GstIndex * index)
7353 {
7354   GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (element);
7355
7356   GST_OBJECT_LOCK (demux);
7357   if (demux->common.element_index)
7358     gst_object_unref (demux->common.element_index);
7359   demux->common.element_index = index ? gst_object_ref (index) : NULL;
7360   GST_OBJECT_UNLOCK (demux);
7361   GST_DEBUG_OBJECT (demux, "Set index %" GST_PTR_FORMAT,
7362       demux->common.element_index);
7363 }
7364
7365 static GstIndex *
7366 gst_matroska_demux_get_index (GstElement * element)
7367 {
7368   GstIndex *result = NULL;
7369   GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (element);
7370
7371   GST_OBJECT_LOCK (demux);
7372   if (demux->common.element_index)
7373     result = gst_object_ref (demux->common.element_index);
7374   GST_OBJECT_UNLOCK (demux);
7375
7376   GST_DEBUG_OBJECT (demux, "Returning index %" GST_PTR_FORMAT, result);
7377
7378   return result;
7379 }
7380 #endif
7381
7382 static GstStateChangeReturn
7383 gst_matroska_demux_change_state (GstElement * element,
7384     GstStateChange transition)
7385 {
7386   GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (element);
7387   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
7388
7389   /* handle upwards state changes here */
7390   switch (transition) {
7391     default:
7392       break;
7393   }
7394
7395   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
7396
7397   /* handle downwards state changes */
7398   switch (transition) {
7399     case GST_STATE_CHANGE_PAUSED_TO_READY:
7400       gst_matroska_demux_reset (GST_ELEMENT (demux));
7401       break;
7402     default:
7403       break;
7404   }
7405
7406   return ret;
7407 }
7408
7409 static void
7410 gst_matroska_demux_set_property (GObject * object,
7411     guint prop_id, const GValue * value, GParamSpec * pspec)
7412 {
7413   GstMatroskaDemux *demux;
7414
7415   g_return_if_fail (GST_IS_MATROSKA_DEMUX (object));
7416   demux = GST_MATROSKA_DEMUX (object);
7417
7418   switch (prop_id) {
7419     case PROP_MAX_GAP_TIME:
7420       GST_OBJECT_LOCK (demux);
7421       demux->max_gap_time = g_value_get_uint64 (value);
7422       GST_OBJECT_UNLOCK (demux);
7423       break;
7424     case PROP_MAX_BACKTRACK_DISTANCE:
7425       GST_OBJECT_LOCK (demux);
7426       demux->max_backtrack_distance = g_value_get_uint (value);
7427       GST_OBJECT_UNLOCK (demux);
7428       break;
7429     default:
7430       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
7431       break;
7432   }
7433 }
7434
7435 static void
7436 gst_matroska_demux_get_property (GObject * object,
7437     guint prop_id, GValue * value, GParamSpec * pspec)
7438 {
7439   GstMatroskaDemux *demux;
7440
7441   g_return_if_fail (GST_IS_MATROSKA_DEMUX (object));
7442   demux = GST_MATROSKA_DEMUX (object);
7443
7444   switch (prop_id) {
7445     case PROP_MAX_GAP_TIME:
7446       GST_OBJECT_LOCK (demux);
7447       g_value_set_uint64 (value, demux->max_gap_time);
7448       GST_OBJECT_UNLOCK (demux);
7449       break;
7450     case PROP_MAX_BACKTRACK_DISTANCE:
7451       GST_OBJECT_LOCK (demux);
7452       g_value_set_uint (value, demux->max_backtrack_distance);
7453       GST_OBJECT_UNLOCK (demux);
7454       break;
7455     default:
7456       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
7457       break;
7458   }
7459 }
7460
7461 static const gchar *
7462 gst_matroska_track_encryption_algorithm_name (gint val)
7463 {
7464   GEnumValue *en;
7465   GEnumClass *enum_class =
7466       g_type_class_ref (MATROSKA_TRACK_ENCRYPTION_ALGORITHM_TYPE);
7467   en = g_enum_get_value (G_ENUM_CLASS (enum_class), val);
7468   return en ? en->value_nick : NULL;
7469 }
7470
7471 static const gchar *
7472 gst_matroska_track_encryption_cipher_mode_name (gint val)
7473 {
7474   GEnumValue *en;
7475   GEnumClass *enum_class =
7476       g_type_class_ref (MATROSKA_TRACK_ENCRYPTION_CIPHER_MODE_TYPE);
7477   en = g_enum_get_value (G_ENUM_CLASS (enum_class), val);
7478   return en ? en->value_nick : NULL;
7479 }
7480
7481 static const gchar *
7482 gst_matroska_track_encoding_scope_name (gint val)
7483 {
7484   GEnumValue *en;
7485   GEnumClass *enum_class =
7486       g_type_class_ref (MATROSKA_TRACK_ENCODING_SCOPE_TYPE);
7487
7488   en = g_enum_get_value (G_ENUM_CLASS (enum_class), val);
7489   return en ? en->value_nick : NULL;
7490 }