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