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