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