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