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