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