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