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