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