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