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>
7 * matroska-demux.c: matroska file/stream demuxer
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.
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.
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.
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
35 * SECTION:element-matroskademux
37 * matroskademux demuxes a Matroska file into the different contained streams.
40 * <title>Example launch line</title>
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.
54 #include <glib/gprintf.h>
56 #include <gst/base/base.h>
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>
64 #include <gst/audio/audio.h>
65 #include <gst/tag/tag.h>
66 #include <gst/pbutils/pbutils.h>
67 #include <gst/video/video.h>
69 #include "matroska-demux.h"
70 #include "matroska-ids.h"
72 GST_DEBUG_CATEGORY_STATIC (matroskademux_debug);
73 #define GST_CAT_DEFAULT matroskademux_debug
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))
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))
91 #define DEFAULT_MAX_GAP_TIME (2 * GST_SECOND)
92 #define INVALID_DATA_THRESHOLD (2 * 1024 * 1024)
94 static GstStaticPadTemplate sink_templ = GST_STATIC_PAD_TEMPLATE ("sink",
97 GST_STATIC_CAPS ("audio/x-matroska; video/x-matroska; "
98 "video/x-matroska-3d; audio/webm; video/webm")
101 /* TODO: fill in caps! */
103 static GstStaticPadTemplate audio_src_templ =
104 GST_STATIC_PAD_TEMPLATE ("audio_%u",
107 GST_STATIC_CAPS ("ANY")
110 static GstStaticPadTemplate video_src_templ =
111 GST_STATIC_PAD_TEMPLATE ("video_%u",
114 GST_STATIC_CAPS ("ANY")
117 static GstStaticPadTemplate subtitle_src_templ =
118 GST_STATIC_PAD_TEMPLATE ("subtitle_%u",
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")
126 static GstFlowReturn gst_matroska_demux_parse_id (GstMatroskaDemux * demux,
127 guint32 id, guint64 length, guint needed);
129 /* element functions */
130 static void gst_matroska_demux_loop (GstPad * pad);
132 static gboolean gst_matroska_demux_element_send_event (GstElement * element,
134 static gboolean gst_matroska_demux_element_query (GstElement * element,
138 static gboolean gst_matroska_demux_sink_activate (GstPad * sinkpad,
140 static gboolean gst_matroska_demux_sink_activate_mode (GstPad * sinkpad,
141 GstObject * parent, GstPadMode mode, gboolean active);
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);
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);
155 static GstStateChangeReturn
156 gst_matroska_demux_change_state (GstElement * element,
157 GstStateChange transition);
160 gst_matroska_demux_set_index (GstElement * element, GstIndex * index);
161 static GstIndex *gst_matroska_demux_get_index (GstElement * element);
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);
172 * gst_matroska_demux_subtitle_caps (GstMatroskaTrackSubtitleContext *
173 subtitlecontext, const gchar * codec_id, gpointer data, guint size);
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);
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);
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);
191 gst_matroska_demux_finalize (GObject * object)
193 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (object);
195 gst_matroska_read_common_finalize (&demux->common);
196 gst_flow_combiner_free (demux->flowcombiner);
197 G_OBJECT_CLASS (parent_class)->finalize (object);
201 gst_matroska_demux_class_init (GstMatroskaDemuxClass * klass)
203 GObjectClass *gobject_class = (GObjectClass *) klass;
204 GstElementClass *gstelement_class = (GstElementClass *) klass;
206 GST_DEBUG_CATEGORY_INIT (matroskademux_debug, "matroskademux", 0,
209 gobject_class->finalize = gst_matroska_demux_finalize;
211 gobject_class->get_property = gst_matroska_demux_get_property;
212 gobject_class->set_property = gst_matroska_demux_set_property;
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));
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);
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);
233 gst_element_class_add_static_pad_template (gstelement_class,
235 gst_element_class_add_static_pad_template (gstelement_class,
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);
241 gst_element_class_set_static_metadata (gstelement_class, "Matroska demuxer",
243 "Demuxes Matroska/WebM streams into video/audio/subtitles",
244 "GStreamer maintainers <gstreamer-devel@lists.freedesktop.org>");
248 gst_matroska_demux_init (GstMatroskaDemux * demux)
250 demux->common.sinkpad = gst_pad_new_from_static_template (&sink_templ,
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);
262 /* init defaults for common read context */
263 gst_matroska_read_common_init (&demux->common);
265 /* property defaults */
266 demux->max_gap_time = DEFAULT_MAX_GAP_TIME;
268 GST_OBJECT_FLAG_SET (demux, GST_ELEMENT_FLAG_INDEXABLE);
270 demux->flowcombiner = gst_flow_combiner_new ();
273 gst_matroska_demux_reset (GST_ELEMENT (demux));
277 gst_matroska_demux_reset (GstElement * element)
279 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (element);
281 GST_DEBUG_OBJECT (demux, "Resetting state");
283 gst_matroska_read_common_reset (GST_ELEMENT (demux), &demux->common);
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;
290 demux->have_group_id = FALSE;
291 demux->group_id = G_MAXUINT;
294 demux->tracks_parsed = FALSE;
296 if (demux->clusters) {
297 g_array_free (demux->clusters, TRUE);
298 demux->clusters = NULL;
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;
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;
329 demux->seek_index = NULL;
330 demux->seek_entry = 0;
332 if (demux->new_segment) {
333 gst_event_unref (demux->new_segment);
334 demux->new_segment = NULL;
337 demux->invalid_duration = FALSE;
339 demux->cached_length = G_MAXUINT64;
341 gst_flow_combiner_clear (demux->flowcombiner);
345 gst_matroska_decode_buffer (GstMatroskaTrackContext * context, GstBuffer * buf)
351 g_return_val_if_fail (GST_IS_BUFFER (buf), NULL);
353 GST_DEBUG ("decoding buffer %p", buf);
355 gst_buffer_map (buf, &map, GST_MAP_READ);
359 g_return_val_if_fail (size > 0, buf);
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);
367 GST_DEBUG ("decode data failed");
368 gst_buffer_unmap (buf, &map);
369 gst_buffer_unref (buf);
375 gst_matroska_demux_add_stream_headers_to_caps (GstMatroskaDemux * demux,
376 GstBufferList * list, GstCaps * caps)
379 GValue arr_val = G_VALUE_INIT;
380 GValue buf_val = G_VALUE_INIT;
383 g_assert (gst_caps_is_writable (caps));
385 g_value_init (&arr_val, GST_TYPE_ARRAY);
386 g_value_init (&buf_val, GST_TYPE_BUFFER);
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);
394 s = gst_caps_get_structure (caps, 0);
395 gst_structure_take_value (s, "streamheader", &arr_val);
396 g_value_unset (&buf_val);
400 gst_matroska_demux_parse_colour (GstMatroskaDemux * demux, GstEbmlRead * ebml,
401 GstMatroskaTrackVideoContext * video_context)
404 GstVideoColorimetry colorimetry;
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;
413 DEBUG_ELEMENT_START (demux, ebml, "TrackVideoColour");
415 if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK)
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)
423 case GST_MATROSKA_ID_VIDEOMATRIXCOEFFICIENTS:{
424 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
429 colorimetry.matrix = GST_VIDEO_COLOR_MATRIX_RGB;
432 colorimetry.matrix = GST_VIDEO_COLOR_MATRIX_BT709;
435 colorimetry.matrix = GST_VIDEO_COLOR_MATRIX_UNKNOWN;
438 colorimetry.matrix = GST_VIDEO_COLOR_MATRIX_FCC;
440 /* FIXME: "5: BT470BG" is undefined in GstVideoColorMatrix
441 * but it's functionally same as "6: BT601" */
444 colorimetry.matrix = GST_VIDEO_COLOR_MATRIX_BT601;
447 colorimetry.matrix = GST_VIDEO_COLOR_MATRIX_SMPTE240M;
450 colorimetry.matrix = GST_VIDEO_COLOR_MATRIX_BT2020;
453 GST_FIXME_OBJECT (demux, "Unsupported color matrix coefficients %"
454 G_GUINT64_FORMAT, num);
460 case GST_MATROSKA_ID_VIDEORANGE:{
461 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
466 colorimetry.range = GST_VIDEO_COLOR_RANGE_UNKNOWN;
469 colorimetry.range = GST_VIDEO_COLOR_RANGE_16_235;
472 colorimetry.range = GST_VIDEO_COLOR_RANGE_0_255;
475 GST_FIXME_OBJECT (demux, "Unsupported color range %"
476 G_GUINT64_FORMAT, num);
482 case GST_MATROSKA_ID_VIDEOTRANSFERCHARACTERISTICS:{
483 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
487 /* FIXME: "6: BT601" and "14: BT2020_10" are undefined in
488 * GstVideoTransferFunction, but functionally same as "1: BT709" */
492 colorimetry.transfer = GST_VIDEO_TRANSFER_BT709;
495 colorimetry.transfer = GST_VIDEO_TRANSFER_UNKNOWN;
498 colorimetry.transfer = GST_VIDEO_TRANSFER_GAMMA22;
501 colorimetry.transfer = GST_VIDEO_TRANSFER_GAMMA28;
504 colorimetry.transfer = GST_VIDEO_TRANSFER_SMPTE240M;
507 colorimetry.transfer = GST_VIDEO_TRANSFER_GAMMA10;
510 colorimetry.transfer = GST_VIDEO_TRANSFER_LOG100;
513 colorimetry.transfer = GST_VIDEO_TRANSFER_LOG316;
516 colorimetry.transfer = GST_VIDEO_TRANSFER_SRGB;
519 colorimetry.transfer = GST_VIDEO_TRANSFER_BT2020_12;
522 GST_FIXME_OBJECT (demux,
523 "Unsupported color transfer characteristics %"
524 G_GUINT64_FORMAT, num);
530 case GST_MATROSKA_ID_VIDEOPRIMARIES:{
531 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
536 colorimetry.primaries = GST_VIDEO_COLOR_PRIMARIES_BT709;
539 colorimetry.primaries = GST_VIDEO_COLOR_PRIMARIES_UNKNOWN;
542 colorimetry.primaries = GST_VIDEO_COLOR_PRIMARIES_BT470M;
545 colorimetry.primaries = GST_VIDEO_COLOR_PRIMARIES_BT470BG;
548 colorimetry.primaries = GST_VIDEO_COLOR_PRIMARIES_SMPTE170M;
551 colorimetry.primaries = GST_VIDEO_COLOR_PRIMARIES_SMPTE240M;
554 colorimetry.primaries = GST_VIDEO_COLOR_PRIMARIES_FILM;
557 colorimetry.primaries = GST_VIDEO_COLOR_PRIMARIES_BT2020;
560 GST_FIXME_OBJECT (demux, "Unsupported color primaries %"
561 G_GUINT64_FORMAT, num);
568 GST_FIXME_OBJECT (demux, "Unsupported subelement 0x%x in Colour", id);
569 ret = gst_ebml_read_skip (ebml);
574 memcpy (&video_context->colorimetry, &colorimetry,
575 sizeof (GstVideoColorimetry));
578 DEBUG_ELEMENT_STOP (demux, ebml, "TrackVideoColour", ret);
583 gst_matroska_demux_add_stream (GstMatroskaDemux * demux, GstEbmlRead * ebml)
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;
593 guint32 id, riff_fourcc = 0;
594 guint16 riff_audio_fmt = 0;
595 GstEvent *stream_start;
599 DEBUG_ELEMENT_START (demux, ebml, "TrackEntry");
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);
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;
616 context->set_discont = TRUE;
617 context->timecodescale = 1.0;
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);
631 GST_DEBUG_OBJECT (demux, "Stream number %d", context->index);
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)
639 /* track number (unique stream ID) */
640 case GST_MATROSKA_ID_TRACKNUMBER:{
643 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
647 GST_ERROR_OBJECT (demux, "Invalid TrackNumber 0");
648 ret = GST_FLOW_ERROR;
650 } else if (!gst_matroska_read_common_tracknumber_unique (&demux->common,
652 GST_ERROR_OBJECT (demux, "TrackNumber %" G_GUINT64_FORMAT
653 " is not unique", num);
654 ret = GST_FLOW_ERROR;
658 GST_DEBUG_OBJECT (demux, "TrackNumber: %" G_GUINT64_FORMAT, num);
662 /* track UID (unique identifier) */
663 case GST_MATROSKA_ID_TRACKUID:{
666 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
670 GST_ERROR_OBJECT (demux, "Invalid TrackUID 0");
671 ret = GST_FLOW_ERROR;
675 GST_DEBUG_OBJECT (demux, "TrackUID: %" G_GUINT64_FORMAT, num);
680 /* track type (video, audio, combined, subtitle, etc.) */
681 case GST_MATROSKA_ID_TRACKTYPE:{
684 if ((ret = gst_ebml_read_uint (ebml, &id, &track_type)) != GST_FLOW_OK) {
688 if (context->type != 0 && context->type != track_type) {
689 GST_WARNING_OBJECT (demux,
690 "More than one tracktype defined in a TrackEntry - skipping");
692 } else if (track_type < 1 || track_type > 254) {
693 GST_WARNING_OBJECT (demux, "Invalid TrackType %" G_GUINT64_FORMAT,
698 GST_DEBUG_OBJECT (demux, "TrackType: %" G_GUINT64_FORMAT, track_type);
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);
705 case GST_MATROSKA_TRACK_TYPE_AUDIO:
706 gst_matroska_track_init_audio_context (&context);
708 case GST_MATROSKA_TRACK_TYPE_SUBTITLE:
709 gst_matroska_track_init_subtitle_context (&context);
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:
716 GST_WARNING_OBJECT (demux,
717 "Unknown or unsupported TrackType %" G_GUINT64_FORMAT,
722 g_ptr_array_index (demux->common.src, demux->common.num_streams - 1)
727 /* tracktype specific stuff for video */
728 case GST_MATROSKA_ID_TRACKVIDEO:{
729 GstMatroskaTrackVideoContext *videocontext;
731 DEBUG_ELEMENT_START (demux, ebml, "TrackVideo");
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;
738 } else if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
741 videocontext = (GstMatroskaTrackVideoContext *) context;
742 g_ptr_array_index (demux->common.src, demux->common.num_streams - 1)
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)
751 /* Should be one level up but some broken muxers write it here. */
752 case GST_MATROSKA_ID_TRACKDEFAULTDURATION:{
755 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
759 GST_WARNING_OBJECT (demux, "Invalid TrackDefaultDuration 0");
763 GST_DEBUG_OBJECT (demux,
764 "TrackDefaultDuration: %" G_GUINT64_FORMAT, num);
765 context->default_duration = num;
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:{
775 if ((ret = gst_ebml_read_float (ebml, &id, &num)) != GST_FLOW_OK)
779 GST_WARNING_OBJECT (demux, "Invalid TrackVideoFPS %lf", num);
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;
791 /* width of the size to display the video at */
792 case GST_MATROSKA_ID_VIDEODISPLAYWIDTH:{
795 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
799 GST_WARNING_OBJECT (demux, "Invalid TrackVideoDisplayWidth 0");
803 GST_DEBUG_OBJECT (demux,
804 "TrackVideoDisplayWidth: %" G_GUINT64_FORMAT, num);
805 videocontext->display_width = num;
809 /* height of the size to display the video at */
810 case GST_MATROSKA_ID_VIDEODISPLAYHEIGHT:{
813 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
817 GST_WARNING_OBJECT (demux, "Invalid TrackVideoDisplayHeight 0");
821 GST_DEBUG_OBJECT (demux,
822 "TrackVideoDisplayHeight: %" G_GUINT64_FORMAT, num);
823 videocontext->display_height = num;
827 /* width of the video in the file */
828 case GST_MATROSKA_ID_VIDEOPIXELWIDTH:{
831 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
835 GST_WARNING_OBJECT (demux, "Invalid TrackVideoPixelWidth 0");
839 GST_DEBUG_OBJECT (demux,
840 "TrackVideoPixelWidth: %" G_GUINT64_FORMAT, num);
841 videocontext->pixel_width = num;
845 /* height of the video in the file */
846 case GST_MATROSKA_ID_VIDEOPIXELHEIGHT:{
849 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
853 GST_WARNING_OBJECT (demux, "Invalid TrackVideoPixelHeight 0");
857 GST_DEBUG_OBJECT (demux,
858 "TrackVideoPixelHeight: %" G_GUINT64_FORMAT, num);
859 videocontext->pixel_height = num;
863 /* whether the video is interlaced */
864 case GST_MATROSKA_ID_VIDEOFLAGINTERLACED:{
867 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
871 videocontext->interlace_mode =
872 GST_MATROSKA_INTERLACE_MODE_INTERLACED;
874 videocontext->interlace_mode =
875 GST_MATROSKA_INTERLACE_MODE_PROGRESSIVE;
877 videocontext->interlace_mode =
878 GST_MATROSKA_INTERLACE_MODE_UNKNOWN;
880 GST_DEBUG_OBJECT (demux, "video track interlacing mode: %d",
881 videocontext->interlace_mode);
885 /* aspect ratio behaviour */
886 case GST_MATROSKA_ID_VIDEOASPECTRATIOTYPE:{
889 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
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);
899 GST_DEBUG_OBJECT (demux,
900 "TrackVideoAspectRatioType: %" G_GUINT64_FORMAT, num);
901 videocontext->asr_mode = num;
905 /* colourspace (only matters for raw video) fourcc */
906 case GST_MATROSKA_ID_VIDEOCOLOURSPACE:{
911 gst_ebml_read_binary (ebml, &id, &data,
912 &datalen)) != GST_FLOW_OK)
917 GST_WARNING_OBJECT (demux,
918 "Invalid TrackVideoColourSpace length %" G_GUINT64_FORMAT,
923 memcpy (&videocontext->fourcc, data, 4);
924 GST_DEBUG_OBJECT (demux,
925 "TrackVideoColourSpace: %" GST_FOURCC_FORMAT,
926 GST_FOURCC_ARGS (videocontext->fourcc));
932 case GST_MATROSKA_ID_VIDEOCOLOUR:{
933 ret = gst_matroska_demux_parse_colour (demux, ebml, videocontext);
937 case GST_MATROSKA_ID_VIDEOSTEREOMODE:
941 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
944 GST_DEBUG_OBJECT (demux, "StereoMode: %" G_GUINT64_FORMAT, num);
947 case GST_MATROSKA_STEREO_MODE_SBS_RL:
948 videocontext->multiview_flags =
949 GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST;
951 case GST_MATROSKA_STEREO_MODE_SBS_LR:
952 videocontext->multiview_mode =
953 GST_VIDEO_MULTIVIEW_MODE_SIDE_BY_SIDE;
955 case GST_MATROSKA_STEREO_MODE_TB_RL:
956 videocontext->multiview_flags =
957 GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST;
959 case GST_MATROSKA_STEREO_MODE_TB_LR:
960 videocontext->multiview_mode =
961 GST_VIDEO_MULTIVIEW_MODE_TOP_BOTTOM;
963 case GST_MATROSKA_STEREO_MODE_CHECKER_RL:
964 videocontext->multiview_flags =
965 GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST;
967 case GST_MATROSKA_STEREO_MODE_CHECKER_LR:
968 videocontext->multiview_mode =
969 GST_VIDEO_MULTIVIEW_MODE_CHECKERBOARD;
971 case GST_MATROSKA_STEREO_MODE_FBF_RL:
972 videocontext->multiview_flags =
973 GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST;
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");
989 GST_WARNING_OBJECT (demux,
990 "Unknown TrackVideo subelement 0x%x - ignoring", id);
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);
1003 DEBUG_ELEMENT_STOP (demux, ebml, "TrackVideo", ret);
1007 /* tracktype specific stuff for audio */
1008 case GST_MATROSKA_ID_TRACKAUDIO:{
1009 GstMatroskaTrackAudioContext *audiocontext;
1011 DEBUG_ELEMENT_START (demux, ebml, "TrackAudio");
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;
1020 if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK)
1023 audiocontext = (GstMatroskaTrackAudioContext *) context;
1024 g_ptr_array_index (demux->common.src, demux->common.num_streams - 1)
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)
1034 case GST_MATROSKA_ID_AUDIOSAMPLINGFREQ:{
1037 if ((ret = gst_ebml_read_float (ebml, &id, &num)) != GST_FLOW_OK)
1042 GST_WARNING_OBJECT (demux,
1043 "Invalid TrackAudioSamplingFrequency %lf", num);
1047 GST_DEBUG_OBJECT (demux, "TrackAudioSamplingFrequency: %lf", num);
1048 audiocontext->samplerate = num;
1053 case GST_MATROSKA_ID_AUDIOBITDEPTH:{
1056 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1060 GST_WARNING_OBJECT (demux, "Invalid TrackAudioBitDepth 0");
1064 GST_DEBUG_OBJECT (demux, "TrackAudioBitDepth: %" G_GUINT64_FORMAT,
1066 audiocontext->bitdepth = num;
1071 case GST_MATROSKA_ID_AUDIOCHANNELS:{
1074 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1078 GST_WARNING_OBJECT (demux, "Invalid TrackAudioChannels 0");
1082 GST_DEBUG_OBJECT (demux, "TrackAudioChannels: %" G_GUINT64_FORMAT,
1084 audiocontext->channels = num;
1089 GST_WARNING_OBJECT (demux,
1090 "Unknown TrackAudio subelement 0x%x - ignoring", id);
1092 case GST_MATROSKA_ID_AUDIOCHANNELPOSITIONS:
1093 case GST_MATROSKA_ID_AUDIOOUTPUTSAMPLINGFREQ:
1094 ret = gst_ebml_read_skip (ebml);
1099 DEBUG_ELEMENT_STOP (demux, ebml, "TrackAudio", ret);
1104 /* codec identifier */
1105 case GST_MATROSKA_ID_CODECID:{
1108 if ((ret = gst_ebml_read_ascii (ebml, &id, &text)) != GST_FLOW_OK)
1111 GST_DEBUG_OBJECT (demux, "CodecID: %s", GST_STR_NULL (text));
1112 context->codec_id = text;
1116 /* codec private data */
1117 case GST_MATROSKA_ID_CODECPRIVATE:{
1122 gst_ebml_read_binary (ebml, &id, &data, &size)) != GST_FLOW_OK)
1125 context->codec_priv = data;
1126 context->codec_priv_size = size;
1128 GST_DEBUG_OBJECT (demux, "CodecPrivate of size %" G_GUINT64_FORMAT,
1133 /* name of the codec */
1134 case GST_MATROSKA_ID_CODECNAME:{
1137 if ((ret = gst_ebml_read_utf8 (ebml, &id, &text)) != GST_FLOW_OK)
1140 GST_DEBUG_OBJECT (demux, "CodecName: %s", GST_STR_NULL (text));
1141 context->codec_name = text;
1146 case GST_MATROSKA_ID_CODECDELAY:{
1149 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1152 context->codec_delay = num;
1154 GST_DEBUG_OBJECT (demux, "CodecDelay: %" GST_TIME_FORMAT,
1155 GST_TIME_ARGS (num));
1160 case GST_MATROSKA_ID_SEEKPREROLL:{
1163 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1166 context->seek_preroll = num;
1168 GST_DEBUG_OBJECT (demux, "SeekPreroll: %" GST_TIME_FORMAT,
1169 GST_TIME_ARGS (num));
1173 /* name of this track */
1174 case GST_MATROSKA_ID_TRACKNAME:{
1177 if ((ret = gst_ebml_read_utf8 (ebml, &id, &text)) != GST_FLOW_OK)
1180 context->name = text;
1181 GST_DEBUG_OBJECT (demux, "TrackName: %s", GST_STR_NULL (text));
1185 /* language (matters for audio/subtitles, mostly) */
1186 case GST_MATROSKA_ID_TRACKLANGUAGE:{
1189 if ((ret = gst_ebml_read_utf8 (ebml, &id, &text)) != GST_FLOW_OK)
1193 context->language = text;
1196 if (strlen (context->language) >= 4 && context->language[3] == '-')
1197 context->language[3] = '\0';
1199 GST_DEBUG_OBJECT (demux, "TrackLanguage: %s",
1200 GST_STR_NULL (context->language));
1204 /* whether this is actually used */
1205 case GST_MATROSKA_ID_TRACKFLAGENABLED:{
1208 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1212 context->flags |= GST_MATROSKA_TRACK_ENABLED;
1214 context->flags &= ~GST_MATROSKA_TRACK_ENABLED;
1216 GST_DEBUG_OBJECT (demux, "TrackEnabled: %d",
1217 (context->flags & GST_MATROSKA_TRACK_ENABLED) ? 1 : 0);
1221 /* whether it's the default for this track type */
1222 case GST_MATROSKA_ID_TRACKFLAGDEFAULT:{
1225 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1229 context->flags |= GST_MATROSKA_TRACK_DEFAULT;
1231 context->flags &= ~GST_MATROSKA_TRACK_DEFAULT;
1233 GST_DEBUG_OBJECT (demux, "TrackDefault: %d",
1234 (context->flags & GST_MATROSKA_TRACK_DEFAULT) ? 1 : 0);
1238 /* whether the track must be used during playback */
1239 case GST_MATROSKA_ID_TRACKFLAGFORCED:{
1242 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1246 context->flags |= GST_MATROSKA_TRACK_FORCED;
1248 context->flags &= ~GST_MATROSKA_TRACK_FORCED;
1250 GST_DEBUG_OBJECT (demux, "TrackForced: %d",
1251 (context->flags & GST_MATROSKA_TRACK_FORCED) ? 1 : 0);
1255 /* lacing (like MPEG, where blocks don't end/start on frame
1257 case GST_MATROSKA_ID_TRACKFLAGLACING:{
1260 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1264 context->flags |= GST_MATROSKA_TRACK_LACING;
1266 context->flags &= ~GST_MATROSKA_TRACK_LACING;
1268 GST_DEBUG_OBJECT (demux, "TrackLacing: %d",
1269 (context->flags & GST_MATROSKA_TRACK_LACING) ? 1 : 0);
1273 /* default length (in time) of one data block in this track */
1274 case GST_MATROSKA_ID_TRACKDEFAULTDURATION:{
1277 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1282 GST_WARNING_OBJECT (demux, "Invalid TrackDefaultDuration 0");
1286 GST_DEBUG_OBJECT (demux, "TrackDefaultDuration: %" G_GUINT64_FORMAT,
1288 context->default_duration = num;
1292 case GST_MATROSKA_ID_CONTENTENCODINGS:{
1293 ret = gst_matroska_read_common_read_track_encodings (&demux->common,
1298 case GST_MATROSKA_ID_TRACKTIMECODESCALE:{
1301 if ((ret = gst_ebml_read_float (ebml, &id, &num)) != GST_FLOW_OK)
1305 GST_WARNING_OBJECT (demux, "Invalid TrackTimeCodeScale %lf", num);
1309 GST_DEBUG_OBJECT (demux, "TrackTimeCodeScale: %lf", num);
1310 context->timecodescale = num;
1315 GST_WARNING ("Unknown TrackEntry subelement 0x%x - ignoring", id);
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);
1336 DEBUG_ELEMENT_STOP (demux, ebml, "TrackEntry", ret);
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;
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");
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);
1362 /* check for a cached track taglist */
1364 (GstTagList *) g_hash_table_lookup (demux->common.cached_track_taglists,
1365 GUINT_TO_POINTER (context->uid));
1367 gst_tag_list_insert (context->tags, cached_taglist, GST_TAG_MERGE_APPEND);
1369 /* now create the GStreamer connectivity */
1370 switch (context->type) {
1371 case GST_MATROSKA_TRACK_TYPE_VIDEO:{
1372 GstMatroskaTrackVideoContext *videocontext =
1373 (GstMatroskaTrackVideoContext *) context;
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);
1381 if (!context->intra_only)
1382 demux->have_nonintraonly_v_streams = TRUE;
1385 gst_tag_list_add (context->tags, GST_TAG_MERGE_REPLACE,
1386 GST_TAG_VIDEO_CODEC, codec, NULL);
1387 context->tags_changed = TRUE;
1393 case GST_MATROSKA_TRACK_TYPE_AUDIO:{
1394 GstMatroskaTrackAudioContext *audiocontext =
1395 (GstMatroskaTrackAudioContext *) context;
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);
1404 gst_tag_list_add (context->tags, GST_TAG_MERGE_REPLACE,
1405 GST_TAG_AUDIO_CODEC, codec, NULL);
1406 context->tags_changed = TRUE;
1412 case GST_MATROSKA_TRACK_TYPE_SUBTITLE:{
1413 GstMatroskaTrackSubtitleContext *subtitlecontext =
1414 (GstMatroskaTrackSubtitleContext *) context;
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);
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:
1428 /* we should already have quit by now */
1429 g_assert_not_reached ();
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");
1439 if (context->language) {
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);
1447 if (context->name) {
1448 gst_tag_list_add (context->tags, GST_TAG_MERGE_REPLACE,
1449 GST_TAG_TITLE, context->name, NULL);
1451 context->tags_changed = TRUE;
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");
1461 case GST_MATROSKA_TRACK_TYPE_AUDIO:
1462 caps = gst_caps_new_empty_simple ("audio/x-unknown");
1464 case GST_MATROSKA_TRACK_TYPE_SUBTITLE:
1465 caps = gst_caps_new_empty_simple ("application/x-subtitle-unknown");
1467 case GST_MATROSKA_TRACK_TYPE_COMPLEX:
1469 caps = gst_caps_new_empty_simple ("application/x-matroska-unknown");
1472 gst_caps_set_simple (caps, "codec-id", G_TYPE_STRING, context->codec_id,
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);
1484 } else if (context->stream_headers != NULL) {
1485 gst_matroska_demux_add_stream_headers_to_caps (demux,
1486 context->stream_headers, caps);
1489 /* the pad in here */
1490 context->pad = gst_pad_new_from_template (templ, padname);
1491 context->caps = caps;
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));
1498 GST_INFO_OBJECT (demux, "Adding pad '%s' with caps %" GST_PTR_FORMAT,
1501 gst_pad_set_element_private (context->pad, context);
1503 gst_pad_use_fixed_caps (context->pad);
1504 gst_pad_set_active (context->pad, TRUE);
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);
1511 gst_pad_get_sticky_event (demux->common.sinkpad, GST_EVENT_STREAM_START,
1514 if (gst_event_parse_group_id (stream_start, &demux->group_id))
1515 demux->have_group_id = TRUE;
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 ();
1524 stream_start = gst_event_new_stream_start (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;
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);
1541 if (demux->common.global_tags) {
1542 GstEvent *tag_event;
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);
1550 gst_event_new_tag (gst_tag_list_copy (demux->common.global_tags));
1552 gst_pad_push_event (context->pad, tag_event);
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;
1563 gst_element_add_pad (GST_ELEMENT (demux), context->pad);
1564 gst_flow_combiner_add_pad (demux->flowcombiner, context->pad);
1573 gst_matroska_demux_query (GstMatroskaDemux * demux, GstPad * pad,
1576 gboolean res = FALSE;
1577 GstMatroskaTrackContext *context = NULL;
1580 context = gst_pad_get_element_private (pad);
1583 switch (GST_QUERY_TYPE (query)) {
1584 case GST_QUERY_POSITION:
1588 gst_query_parse_position (query, &format, NULL);
1591 if (format == GST_FORMAT_TIME) {
1592 GST_OBJECT_LOCK (demux);
1594 gst_query_set_position (query, GST_FORMAT_TIME,
1595 MAX (context->pos, demux->stream_start_time) -
1596 demux->stream_start_time);
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);
1609 GST_DEBUG_OBJECT (demux,
1610 "only position query in TIME and DEFAULT format is supported");
1616 case GST_QUERY_DURATION:
1620 gst_query_parse_duration (query, &format, NULL);
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);
1635 GST_DEBUG_OBJECT (demux,
1636 "only duration query in TIME and DEFAULT format is supported");
1642 case GST_QUERY_SEEKING:
1646 gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
1647 GST_OBJECT_LOCK (demux);
1648 if (fmt == GST_FORMAT_TIME) {
1651 if (demux->streaming) {
1652 /* assuming we'll be able to get an index ... */
1653 seekable = demux->seekable;
1658 gst_query_set_seeking (query, GST_FORMAT_TIME, seekable,
1659 0, demux->common.segment.duration);
1662 GST_OBJECT_UNLOCK (demux);
1665 case GST_QUERY_SEGMENT:
1670 format = demux->common.segment.format;
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;
1679 gst_segment_to_stream_time (&demux->common.segment, format, stop);
1681 gst_query_set_segment (query, demux->common.segment.rate, format, start,
1688 res = gst_pad_query_default (pad, (GstObject *) demux, query);
1691 GST_ELEMENT_CLASS (parent_class)->query (GST_ELEMENT_CAST (demux),
1700 gst_matroska_demux_element_query (GstElement * element, GstQuery * query)
1702 return gst_matroska_demux_query (GST_MATROSKA_DEMUX (element), NULL, query);
1706 gst_matroska_demux_handle_src_query (GstPad * pad, GstObject * parent,
1709 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (parent);
1711 return gst_matroska_demux_query (demux, pad, query);
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! */
1718 gst_matroska_demux_send_event (GstMatroskaDemux * demux, GstEvent * event)
1720 gboolean ret = FALSE;
1723 g_return_val_if_fail (event != NULL, FALSE);
1725 GST_DEBUG_OBJECT (demux, "Sending event of type %s to all source pads",
1726 GST_EVENT_TYPE_NAME (event));
1728 g_assert (demux->common.src->len == demux->common.num_streams);
1729 for (i = 0; i < demux->common.src->len; i++) {
1730 GstMatroskaTrackContext *stream;
1732 stream = g_ptr_array_index (demux->common.src, i);
1733 gst_event_ref (event);
1734 gst_pad_push_event (stream->pad, event);
1738 gst_event_unref (event);
1743 gst_matroska_demux_send_tags (GstMatroskaDemux * demux)
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);
1755 gst_event_new_tag (gst_tag_list_copy (demux->common.global_tags));
1757 for (i = 0; i < demux->common.src->len; i++) {
1758 GstMatroskaTrackContext *stream;
1760 stream = g_ptr_array_index (demux->common.src, i);
1761 gst_pad_push_event (stream->pad, gst_event_ref (tag_event));
1764 gst_event_unref (tag_event);
1765 demux->common.global_tags_changed = FALSE;
1768 g_assert (demux->common.src->len == demux->common.num_streams);
1769 for (i = 0; i < demux->common.src->len; i++) {
1770 GstMatroskaTrackContext *stream;
1772 stream = g_ptr_array_index (demux->common.src, i);
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;
1786 gst_matroska_demux_element_send_event (GstElement * element, GstEvent * event)
1788 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (element);
1791 g_return_val_if_fail (event != NULL, FALSE);
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);
1800 res = gst_matroska_demux_handle_seek_event (demux, NULL, event);
1802 GST_WARNING_OBJECT (demux, "Unhandled event of type %s",
1803 GST_EVENT_TYPE_NAME (event));
1806 gst_event_unref (event);
1811 gst_matroska_demux_move_to_entry (GstMatroskaDemux * demux,
1812 GstMatroskaIndex * entry, gboolean reset, gboolean update)
1816 GST_OBJECT_LOCK (demux);
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;
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));
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;
1838 for (i = 0; i < demux->common.src->len; i++) {
1839 GstMatroskaTrackContext *stream = g_ptr_array_index (demux->common.src, i);
1842 stream->to_offset = G_MAXINT64;
1844 if (stream->from_offset != -1)
1845 stream->to_offset = stream->from_offset;
1847 stream->from_offset = -1;
1848 stream->from_time = GST_CLOCK_TIME_NONE;
1851 GST_OBJECT_UNLOCK (demux);
1857 gst_matroska_cluster_compare (gint64 * i1, gint64 * i2)
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,
1873 gint64 newpos = *pos;
1875 GstFlowReturn ret = GST_FLOW_OK;
1876 const guint chunk = 128 * 1024;
1877 GstBuffer *buf = NULL;
1879 gpointer data = NULL;
1884 gint64 oldpos, oldlength;
1886 orig_offset = demux->common.offset;
1888 GST_LOG_OBJECT (demux, "searching cluster %s offset %" G_GINT64_FORMAT,
1889 forward ? "following" : "preceding", *pos);
1891 if (demux->clusters) {
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);
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) {
1912 /* read in at newpos and scan for ebml cluster id */
1913 oldpos = oldlength = -1;
1915 GstByteReader reader;
1917 guint toread = chunk;
1920 /* never read beyond the requested target */
1921 if (G_UNLIKELY (newpos < chunk)) {
1929 gst_buffer_unmap (buf, &map);
1930 gst_buffer_unref (buf);
1933 ret = gst_pad_pull_range (demux->common.sinkpad, newpos, toread, &buf);
1934 if (ret != GST_FLOW_OK)
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);
1942 if (oldpos == newpos && oldlength == map.size) {
1943 GST_ERROR_OBJECT (demux, "Stuck at same position");
1944 ret = GST_FLOW_ERROR;
1948 oldlength = map.size;
1951 gst_byte_reader_init (&reader, data, size);
1954 gint found = gst_byte_reader_masked_scan_uint32 (&reader, 0xffffffff,
1955 GST_MATROSKA_ID_CLUSTER, 0, gst_byte_reader_get_remaining (&reader));
1957 cluster_pos = found;
1960 /* need last occurrence when searching backwards */
1962 cluster_pos = gst_byte_reader_get_pos (&reader) + found;
1963 gst_byte_reader_skip (&reader, found + 4);
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
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");
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");
1990 g_assert (id == GST_MATROSKA_ID_CLUSTER);
1991 GST_DEBUG_OBJECT (demux, "cluster size %" G_GUINT64_FORMAT ", prefix %d",
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");
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)
2004 GST_DEBUG_OBJECT (demux, "next element is %scluster",
2005 id == GST_MATROSKA_ID_CLUSTER ? "" : "not ");
2006 if (id == GST_MATROSKA_ID_CLUSTER)
2012 /* partial cluster id may have been in tail of buffer */
2014 forward ? MAX (gst_byte_reader_get_remaining (&reader), 4) - 3 : 3;
2019 gst_buffer_unmap (buf, &map);
2020 gst_buffer_unref (buf);
2025 demux->common.offset = orig_offset;
2030 /* Three states to express: starts with I-frame, starts with delta, don't know */
2033 CLUSTER_STATUS_NONE = 0,
2034 CLUSTER_STATUS_STARTS_WITH_KEYFRAME,
2035 CLUSTER_STATUS_STARTS_WITH_DELTAUNIT,
2044 ClusterStatus status;
2047 static const gchar *
2048 cluster_status_get_nick (ClusterStatus status)
2051 case CLUSTER_STATUS_NONE:
2053 case CLUSTER_STATUS_STARTS_WITH_KEYFRAME:
2055 case CLUSTER_STATUS_STARTS_WITH_DELTAUNIT:
2061 /* Skip ebml-coded number:
2064 * 001x.. = 3 bytes, etc.
2067 bit_reader_skip_ebml_num (GstBitReader * br)
2071 if (!gst_bit_reader_peek_bits_uint8 (br, &v, 8))
2074 for (i = 0; i < 8; i++) {
2075 if ((v & (0x80 >> i)) != 0)
2078 return gst_bit_reader_skip (br, (i + 1) * 8);
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
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
2092 gst_matroska_demux_peek_cluster_info (GstMatroskaDemux * demux,
2093 ClusterInfo * cluster, guint64 offset)
2095 demux->common.offset = offset;
2096 demux->cluster_time = GST_CLOCK_TIME_NONE;
2098 cluster->offset = offset;
2100 cluster->prev_size = 0;
2101 cluster->time = GST_CLOCK_TIME_NONE;
2102 cluster->status = CLUSTER_STATUS_NONE;
2104 /* parse first few elements in cluster */
2111 flow = gst_matroska_read_common_peek_id_length_pull (&demux->common,
2112 GST_ELEMENT_CAST (demux), &id, &length, &needed);
2114 if (flow != GST_FLOW_OK)
2117 GST_LOG_OBJECT (demux, "Offset %" G_GUINT64_FORMAT ", Element id 0x%x, "
2118 "size %" G_GUINT64_FORMAT ", needed %d", demux->common.offset, id,
2121 /* Reached start of next cluster without finding data, stop processing */
2122 if (id == GST_MATROSKA_ID_CLUSTER && cluster->offset != offset)
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)
2130 /* SimpleBlock: peek at headers to check if it's a keyframe */
2131 if (id == GST_MATROSKA_ID_SIMPLEBLOCK) {
2133 guint8 *d, hdr_len, v = 0;
2135 GST_DEBUG_OBJECT (demux, "SimpleBlock found");
2137 /* SimpleBlock header is max. 21 bytes */
2138 hdr_len = MIN (21, length);
2140 flow = gst_matroska_read_common_peek_bytes (&demux->common,
2141 demux->common.offset, hdr_len, NULL, &d);
2143 if (flow != GST_FLOW_OK)
2146 gst_bit_reader_init (&br, d, hdr_len);
2148 /* skip prefix: ebml id (SimpleBlock) + element length */
2149 if (!gst_bit_reader_skip (&br, 8 * needed))
2152 /* skip track number (ebml coded) */
2153 if (!bit_reader_skip_ebml_num (&br))
2157 if (!gst_bit_reader_skip (&br, 16))
2161 if (!gst_bit_reader_get_bits_uint8 (&br, &v, 8))
2164 if ((v & 0x80) != 0)
2165 cluster->status = CLUSTER_STATUS_STARTS_WITH_KEYFRAME;
2167 cluster->status = CLUSTER_STATUS_STARTS_WITH_DELTAUNIT;
2172 flow = gst_matroska_demux_parse_id (demux, id, length, needed);
2174 if (flow != GST_FLOW_OK)
2178 case GST_MATROSKA_ID_CLUSTER:
2179 if (length == G_MAXUINT64)
2182 cluster->size = length + needed;
2184 case GST_MATROSKA_ID_PREVSIZE:
2185 cluster->prev_size = demux->cluster_prevsize;
2187 case GST_MATROSKA_ID_CLUSTERTIMECODE:
2188 cluster->time = demux->cluster_time * demux->common.time_scale;
2190 case GST_MATROSKA_ID_SILENTTRACKS:
2191 /* ignore and continue */
2194 GST_WARNING_OBJECT (demux, "Unknown ebml id 0x%08x (possibly garbage), "
2198 } while (demux->common.offset - offset < MAX_CLUSTER_INFO_PROBE_LENGTH);
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));
2208 /* return success as long as we could extract the minimum useful information */
2209 return cluster->time != GST_CLOCK_TIME_NONE;
2212 /* returns TRUE if the cluster offset was updated */
2214 gst_matroska_demux_scan_back_for_keyframe_cluster (GstMatroskaDemux * demux,
2215 gint64 * cluster_offset, GstClockTime * cluster_time)
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, };
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);
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);
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);
2245 GST_DEBUG_OBJECT (demux, "Cluster starts with delta frame, backtracking");
2247 if (cluster.prev_size == 0 || cluster.prev_size > off) {
2248 GST_LOG_OBJECT (demux, "Cluster has no or invalid prev size, stopping");
2252 if (cluster.time != GST_CLOCK_TIME_NONE) {
2253 GstClockTimeDiff distance = GST_CLOCK_DIFF (cluster.time, *cluster_time);
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);
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;
2270 GST_LOG_OBJECT (demux, "Trying prev cluster @ %" G_GUINT64_FORMAT, off);
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;
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)
2291 GstMatroskaIndex *entry = NULL;
2292 GstMatroskaReadState current_state;
2293 GstClockTime otime, prev_cluster_time, current_cluster_time, cluster_time;
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;
2304 /* estimate new position, resync using cluster ebml id,
2305 * and bisect further or scan forward to appropriate cluster */
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);
2311 current_cluster_offset = demux->cluster_offset;
2312 current_cluster_time = demux->cluster_time;
2313 current_offset = demux->common.offset;
2315 demux->common.state = GST_MATROSKA_READ_STATE_SCANNING;
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);
2326 time = MAX (time, atime);
2327 otime = MAX (otime, atime);
2328 opos = MAX (opos, apos);
2330 maxpos = gst_matroska_read_common_get_length (&demux->common);
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
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));
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");
2357 GST_DEBUG_OBJECT (demux, "unknown file size; bailing out");
2360 } else if (otime <= atime) {
2364 gst_util_uint64_scale (opos - apos, time - atime, otime - atime);
2365 if (maxpos != -1 && newpos > maxpos)
2369 GST_DEBUG_OBJECT (demux,
2370 "estimated offset for %" GST_TIME_FORMAT ": %" G_GINT64_FORMAT,
2371 GST_TIME_ARGS (time), newpos);
2373 /* search backwards */
2374 if (newpos > apos) {
2375 ret = gst_matroska_demux_search_cluster (demux, &newpos, FALSE);
2376 if (ret != GST_FLOW_OK)
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;
2387 prev_cluster_time = GST_CLOCK_TIME_NONE;
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)
2394 GST_LOG_OBJECT (demux, "Offset %" G_GUINT64_FORMAT ", Element id 0x%x, "
2395 "size %" G_GUINT64_FORMAT ", needed %d", demux->common.offset, id,
2397 ret = gst_matroska_demux_parse_id (demux, id, length, needed);
2398 if (ret != GST_FLOW_OK)
2401 if (id == GST_MATROSKA_ID_CLUSTER) {
2402 cluster_time = GST_CLOCK_TIME_NONE;
2403 if (length == G_MAXUINT64)
2406 cluster_size = length + needed;
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;
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;
2431 if (prev_cluster_time != GST_CLOCK_TIME_NONE) {
2432 /* prev cluster did not overshoot, so prev cluster is target */
2435 /* re-estimate using this new position info */
2436 opos = cluster_offset;
2437 otime = cluster_time;
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;
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;
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 */
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;
2475 GST_DEBUG_OBJECT (demux, "parsing/skipping cluster elements");
2482 if (ret == GST_FLOW_EOS) {
2483 if (prev_cluster_time != GST_CLOCK_TIME_NONE)
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;
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
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);
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");
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);
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;
2527 gst_matroska_demux_handle_seek_event (GstMatroskaDemux * demux,
2528 GstPad * pad, GstEvent * event)
2530 GstMatroskaIndex *entry = NULL;
2531 GstMatroskaIndex scan_entry;
2533 GstSeekType cur_type, stop_type;
2535 gboolean flush, keyunit, before, after, snap_next;
2538 GstMatroskaTrackContext *track = NULL;
2539 GstSegment seeksegment = { 0, };
2540 gboolean update = TRUE;
2541 gboolean pad_locked = FALSE;
2543 GstSearchMode snap_dir;
2545 g_return_val_if_fail (event != NULL, FALSE);
2548 track = gst_pad_get_element_private (pad);
2550 GST_DEBUG_OBJECT (demux, "Have seek %" GST_PTR_FORMAT, event);
2552 gst_event_parse_seek (event, &rate, &format, &flags, &cur_type, &cur,
2554 seqnum = gst_event_get_seqnum (event);
2556 /* we can only seek on time */
2557 if (format != GST_FORMAT_TIME) {
2558 GST_DEBUG_OBJECT (demux, "Can only seek on TIME");
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));
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;
2574 GST_DEBUG_OBJECT (demux, "configuring seek");
2575 /* Subtract stream_start_time so we always seek on a segment
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;
2583 seeksegment.stop = seeksegment.duration;
2586 gst_segment_do_seek (&seeksegment, rate, format, flags,
2587 cur_type, cur, stop_type, stop, &update);
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;
2599 /* restore segment duration (if any effect),
2600 * would be determined again when parsing, but anyway ... */
2601 seeksegment.duration = demux->common.segment.duration;
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);
2608 /* always do full update if flushing,
2609 * otherwise problems might arise downstream with missing keyframes etc */
2610 update = update || flush;
2612 GST_DEBUG_OBJECT (demux, "New segment %" GST_SEGMENT_FORMAT, &seeksegment);
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;
2619 snap_dir = snap_next ? GST_SEARCH_MODE_AFTER : GST_SEARCH_MODE_BEFORE;
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);
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!
2636 GST_DEBUG_OBJECT (demux,
2637 "No matching seek entry in index, needed for reverse playback");
2638 GST_OBJECT_UNLOCK (demux);
2642 GST_DEBUG_OBJECT (demux, "Seek position looks sane");
2643 GST_OBJECT_UNLOCK (demux);
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 ... */
2653 if (demux->streaming)
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);
2664 GST_DEBUG_OBJECT (demux, "Non-flushing seek, pausing task");
2665 gst_pad_pause_task (demux->common.sinkpad);
2669 GST_PAD_STREAM_LOCK (demux->common.sinkpad);
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
2677 GST_DEBUG_OBJECT (demux, "Waiting for streaming to stop");
2678 GST_PAD_STREAM_LOCK (demux->common.sinkpad);
2681 /* pull mode without index can do some scanning */
2682 if (!demux->streaming && !entry) {
2683 GstEvent *flush_event;
2685 /* need to stop flushing upstream as we need it next */
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);
2691 entry = gst_matroska_demux_search_pos (demux, seeksegment.position);
2692 /* keep local copy */
2694 scan_entry = *entry;
2696 entry = &scan_entry;
2698 GST_DEBUG_OBJECT (demux, "Scan failed to find matching position");
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);
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;
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);
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);
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);
2753 /* update some (segment) state */
2754 if (!gst_matroska_demux_move_to_entry (demux, entry, TRUE, update))
2757 /* notify start of new segment */
2758 if (demux->common.segment.flags & GST_SEEK_FLAG_SEGMENT) {
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);
2767 GST_OBJECT_LOCK (demux);
2768 if (demux->new_segment)
2769 gst_event_unref (demux->new_segment);
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;
2777 demux->to_time = GST_CLOCK_TIME_NONE;
2778 demux->segment_seqnum = seqnum;
2779 GST_OBJECT_UNLOCK (demux);
2781 /* restart our task since it might have been stopped when we did the
2783 gst_pad_start_task (demux->common.sinkpad,
2784 (GstTaskFunction) gst_matroska_demux_loop, demux->common.sinkpad, NULL);
2786 /* streaming can continue now */
2788 GST_PAD_STREAM_UNLOCK (demux->common.sinkpad);
2796 GST_PAD_STREAM_UNLOCK (demux->common.sinkpad);
2798 GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL), ("Got a seek error"));
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.
2808 gst_matroska_demux_handle_seek_push (GstMatroskaDemux * demux, GstPad * pad,
2812 GstSeekType cur_type, stop_type;
2817 gst_event_parse_seek (event, &rate, &format, &flags, &cur_type, &cur,
2822 /* we can only seek on time */
2823 if (format != GST_FORMAT_TIME) {
2824 GST_DEBUG_OBJECT (demux, "Can only seek on TIME");
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");
2833 if (!(flags & GST_SEEK_FLAG_FLUSH)) {
2834 GST_DEBUG_OBJECT (demux,
2835 "Non-flushing seek not supported in streaming mode");
2839 if (flags & GST_SEEK_FLAG_SEGMENT) {
2840 GST_DEBUG_OBJECT (demux, "Segment seek not supported in streaming mode");
2844 /* check for having parsed index already */
2845 if (!demux->common.index_parsed) {
2846 gboolean building_index;
2849 if (!demux->index_offset) {
2850 GST_DEBUG_OBJECT (demux, "no index (location); no seek in push mode");
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 */
2859 /* copy the event */
2860 if (demux->seek_event)
2861 gst_event_unref (demux->seek_event);
2862 demux->seek_event = gst_event_ref (event);
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;
2871 GST_OBJECT_UNLOCK (demux);
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);
2880 /* well, we are handling it already */
2884 /* delegate to tweaked regular seek */
2885 return gst_matroska_demux_handle_seek_event (demux, pad, event);
2889 gst_matroska_demux_handle_src_event (GstPad * pad, GstObject * parent,
2892 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (parent);
2893 gboolean res = TRUE;
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);
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);
2914 if (!demux->streaming)
2915 res = gst_matroska_demux_handle_seek_event (demux, pad, event);
2917 res = gst_matroska_demux_handle_seek_push (demux, pad, event);
2918 gst_event_unref (event);
2923 GstMatroskaTrackContext *context = gst_pad_get_element_private (pad);
2924 if (context->type == GST_MATROSKA_TRACK_TYPE_VIDEO) {
2925 GstMatroskaTrackVideoContext *videocontext =
2926 (GstMatroskaTrackVideoContext *) context;
2928 GstClockTimeDiff diff;
2929 GstClockTime timestamp;
2931 gst_event_parse_qos (event, NULL, &proportion, &diff, ×tamp);
2933 GST_OBJECT_LOCK (demux);
2934 videocontext->earliest_time = timestamp + diff;
2935 GST_OBJECT_UNLOCK (demux);
2938 gst_event_unref (event);
2942 case GST_EVENT_TOC_SELECT:
2945 GstTocEntry *entry = NULL;
2946 GstEvent *seek_event;
2949 if (!demux->common.toc) {
2950 GST_DEBUG_OBJECT (demux, "no TOC to select");
2953 gst_event_parse_toc_select (event, &uid);
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);
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,
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);
2973 GST_WARNING_OBJECT (demux, "received empty TOC select event");
2977 gst_event_unref (event);
2981 /* events we don't need to handle */
2982 case GST_EVENT_NAVIGATION:
2983 gst_event_unref (event);
2987 case GST_EVENT_LATENCY:
2989 res = gst_pad_push_event (demux->common.sinkpad, event);
2996 static GstFlowReturn
2997 gst_matroska_demux_seek_to_previous_keyframe (GstMatroskaDemux * demux)
2999 GstFlowReturn ret = GST_FLOW_EOS;
3000 gboolean done = TRUE;
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,
3007 GST_DEBUG_OBJECT (demux, "locating previous keyframe");
3009 if (!demux->seek_entry) {
3010 GST_DEBUG_OBJECT (demux, "no earlier index entry");
3014 for (i = 0; i < demux->common.src->len; i++) {
3015 GstMatroskaTrackContext *stream = g_ptr_array_index (demux->common.src, i);
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);
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 */
3035 GstMatroskaIndex *entry;
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))
3049 static GstFlowReturn
3050 gst_matroska_demux_parse_tracks (GstMatroskaDemux * demux, GstEbmlRead * ebml)
3052 GstFlowReturn ret = GST_FLOW_OK;
3055 DEBUG_ELEMENT_START (demux, ebml, "Tracks");
3057 if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
3058 DEBUG_ELEMENT_STOP (demux, ebml, "Tracks", ret);
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)
3067 /* one track within the "all-tracks" header */
3068 case GST_MATROSKA_ID_TRACKENTRY:
3069 ret = gst_matroska_demux_add_stream (demux, ebml);
3073 ret = gst_matroska_read_common_parse_skip (&demux->common, ebml,
3078 DEBUG_ELEMENT_STOP (demux, ebml, "Tracks", ret);
3080 demux->tracks_parsed = TRUE;
3086 * Read signed/unsigned "EBML" numbers.
3087 * Return: number of bytes processed.
3091 gst_matroska_ebmlnum_uint (guint8 * data, guint size, guint64 * num)
3093 gint len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
3101 while (read <= 8 && !(total & len_mask)) {
3108 if ((total &= (len_mask - 1)) == len_mask - 1)
3113 if (data[n] == 0xff)
3115 total = (total << 8) | data[n];
3119 if (read == num_ffs && total != 0)
3128 gst_matroska_ebmlnum_sint (guint8 * data, guint size, gint64 * num)
3133 /* read as unsigned number first */
3134 if ((res = gst_matroska_ebmlnum_uint (data, size, &unum)) < 0)
3138 if (unum == G_MAXUINT64)
3141 *num = unum - ((1 << ((7 * res) - 1)) - 1);
3147 * Mostly used for subtitles. We add void filler data for each
3148 * lagging stream to make sure we don't deadlock.
3152 gst_matroska_demux_sync_streams (GstMatroskaDemux * demux)
3154 GstClockTime gap_threshold;
3157 GST_OBJECT_LOCK (demux);
3159 GST_LOG_OBJECT (demux, "Sync to %" GST_TIME_FORMAT,
3160 GST_TIME_ARGS (demux->common.segment.position));
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;
3166 context = g_ptr_array_index (demux->common.src, stream_nr);
3168 GST_LOG_OBJECT (demux,
3169 "Checking for resync on stream %d (%" GST_TIME_FORMAT ")", stream_nr,
3170 GST_TIME_ARGS (context->pos));
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;
3177 gap_threshold = 3 * GST_SECOND;
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) {
3186 guint64 start = context->pos;
3187 guint64 stop = demux->common.segment.position - gap_threshold;
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));
3194 context->pos = stop;
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);
3203 GST_OBJECT_UNLOCK (demux);
3206 static GstFlowReturn
3207 gst_matroska_demux_push_stream_headers (GstMatroskaDemux * demux,
3208 GstMatroskaTrackContext * stream)
3210 GstFlowReturn ret = GST_FLOW_OK;
3213 num = gst_buffer_list_length (stream->stream_headers);
3214 for (i = 0; i < num; ++i) {
3217 buf = gst_buffer_list_get (stream->stream_headers, i);
3218 buf = gst_buffer_copy (buf);
3220 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_HEADER);
3222 if (stream->set_discont) {
3223 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
3224 stream->set_discont = FALSE;
3226 GST_BUFFER_FLAG_UNSET (buf, GST_BUFFER_FLAG_DISCONT);
3229 /* push out all headers in one go and use last flow return */
3230 ret = gst_pad_push (stream->pad, buf);
3233 /* don't need these any longer */
3234 gst_buffer_list_unref (stream->stream_headers);
3235 stream->stream_headers = NULL;
3238 ret = gst_flow_combiner_update_flow (demux->flowcombiner, ret);
3244 gst_matroska_demux_push_dvd_clut_change_event (GstMatroskaDemux * demux,
3245 GstMatroskaTrackContext * stream)
3249 g_assert (!strcmp (stream->codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_VOBSUB));
3251 if (!stream->codec_priv)
3254 /* ideally, VobSub private data should be parsed and stored more convenient
3255 * elsewhere, but for now, only interested in a small part */
3257 /* make sure we have terminating 0 */
3258 buf = g_strndup (stream->codec_priv, stream->codec_priv_size);
3260 /* just locate and parse palette part */
3261 start = strstr (buf, "palette:");
3266 guint8 r, g, b, y, u, v;
3269 while (g_ascii_isspace (*start))
3271 for (i = 0; i < 16; i++) {
3272 if (sscanf (start, "%06x", &col) != 1)
3275 while ((*start == ',') || g_ascii_isspace (*start))
3277 /* sigh, need to convert this from vobsub pseudo-RGB to YUV */
3278 r = (col >> 16) & 0xff;
3279 g = (col >> 8) & 0xff;
3281 y = CLAMP ((0.1494 * r + 0.6061 * g + 0.2445 * b) * 219 / 255 + 16, 0,
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;
3288 /* got them all without problems; build and send event */
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);
3303 gst_pad_push_event (stream->pad,
3304 gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM_STICKY, s));
3311 gst_matroska_demux_push_codec_data_all (GstMatroskaDemux * demux)
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;
3319 stream = g_ptr_array_index (demux->common.src, stream_nr);
3321 if (stream->send_stream_headers) {
3322 if (stream->stream_headers != NULL) {
3323 gst_matroska_demux_push_stream_headers (demux, stream);
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"));
3329 stream->send_stream_headers = FALSE;
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;
3341 static GstFlowReturn
3342 gst_matroska_demux_add_mpeg_seq_header (GstElement * element,
3343 GstMatroskaTrackContext * stream, GstBuffer ** buf)
3346 guint seq_header_len;
3347 guint32 header, tmp;
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;
3359 /* Sequence header only needed for keyframes */
3360 if (GST_BUFFER_FLAG_IS_SET (*buf, GST_BUFFER_FLAG_DELTA_UNIT))
3363 if (gst_buffer_get_size (*buf) < 4)
3366 gst_buffer_extract (*buf, 0, &tmp, sizeof (guint32));
3367 header = GUINT32_FROM_BE (tmp);
3369 /* Sequence start code, if not found prepend */
3370 if (header != 0x000001b3) {
3373 GST_DEBUG_OBJECT (element, "Prepending MPEG sequence header");
3375 newbuf = gst_buffer_new_wrapped (g_memdup (seq_header, seq_header_len),
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));
3382 gst_buffer_unref (*buf);
3389 static GstFlowReturn
3390 gst_matroska_demux_add_wvpk_header (GstElement * element,
3391 GstMatroskaTrackContext * stream, GstBuffer ** buf)
3393 GstMatroskaTrackAudioContext *audiocontext =
3394 (GstMatroskaTrackAudioContext *) stream;
3395 GstBuffer *newbuf = NULL;
3396 GstMapInfo map, outmap;
3397 guint8 *buf_data, *data;
3405 wvh.version = GST_READ_UINT16_LE (stream->codec_priv);
3408 wvh.total_samples = -1;
3409 wvh.block_index = audiocontext->wvpk_block_index;
3411 if (audiocontext->channels <= 2) {
3412 guint32 block_samples, tmp;
3413 gsize size = gst_buffer_get_size (*buf);
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 */
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;
3424 /* block_samples, flags and crc are already in the buffer */
3425 newbuf = gst_buffer_new_allocate (NULL, sizeof (Wavpack4Header) - 12, NULL);
3427 gst_buffer_map (newbuf, &outmap, GST_MAP_WRITE);
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);
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);
3445 gst_buffer_unref (*buf);
3447 audiocontext->wvpk_block_index += block_samples;
3449 guint8 *outdata = NULL;
3451 gsize buf_size, size, out_size = 0;
3452 guint32 block_samples, flags, crc, blocksize;
3454 gst_buffer_map (*buf, &map, GST_MAP_READ);
3455 buf_data = map.data;
3456 buf_size = map.size;
3459 GST_ERROR_OBJECT (element, "Too small wavpack buffer");
3460 gst_buffer_unmap (*buf, &map);
3461 return GST_FLOW_ERROR;
3467 block_samples = GST_READ_UINT32_LE (data);
3472 flags = GST_READ_UINT32_LE (data);
3475 crc = GST_READ_UINT32_LE (data);
3478 blocksize = GST_READ_UINT32_LE (data);
3482 if (blocksize == 0 || size < blocksize)
3485 g_assert ((newbuf == NULL) == (outdata == NULL));
3487 if (newbuf == NULL) {
3488 out_size = sizeof (Wavpack4Header) + blocksize;
3489 newbuf = gst_buffer_new_allocate (NULL, out_size, NULL);
3491 gst_buffer_copy_into (newbuf, *buf,
3492 GST_BUFFER_COPY_TIMESTAMPS | GST_BUFFER_COPY_FLAGS, 0, -1);
3495 gst_buffer_map (newbuf, &outmap, GST_MAP_WRITE);
3496 outdata = outmap.data;
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;
3505 outdata[outpos] = 'w';
3506 outdata[outpos + 1] = 'v';
3507 outdata[outpos + 2] = 'p';
3508 outdata[outpos + 3] = 'k';
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);
3523 memmove (outdata + outpos, data, blocksize);
3524 outpos += blocksize;
3528 gst_buffer_unmap (*buf, &map);
3529 gst_buffer_unref (*buf);
3532 gst_buffer_unmap (newbuf, &outmap);
3535 audiocontext->wvpk_block_index += block_samples;
3541 static GstFlowReturn
3542 gst_matroska_demux_add_prores_header (GstElement * element,
3543 GstMatroskaTrackContext * stream, GstBuffer ** buf)
3545 GstBuffer *newbuf = gst_buffer_new_allocate (NULL, 8, NULL);
3549 if (!gst_buffer_map (newbuf, &map, GST_MAP_WRITE)) {
3550 GST_ERROR ("Failed to map newly allocated buffer");
3551 return GST_FLOW_ERROR;
3554 frame_size = gst_buffer_get_size (*buf);
3556 GST_WRITE_UINT32_BE (map.data, frame_size);
3562 gst_buffer_unmap (newbuf, &map);
3563 *buf = gst_buffer_append (newbuf, *buf);
3568 /* @text must be null-terminated */
3570 gst_matroska_demux_subtitle_chunk_has_tag (GstElement * element,
3575 g_return_val_if_fail (text != NULL, FALSE);
3577 /* yes, this might all lead to false positives ... */
3578 tag = (gchar *) text;
3579 while ((tag = strchr (tag, '<'))) {
3581 if (*tag != '\0' && *(tag + 1) == '>') {
3582 /* some common convenience ones */
3583 /* maybe any character will do here ? */
3596 if (strstr (text, "<span"))
3602 static GstFlowReturn
3603 gst_matroska_demux_check_subtitle_buffer (GstElement * element,
3604 GstMatroskaTrackContext * stream, GstBuffer ** buf)
3606 GstMatroskaTrackSubtitleContext *sub_stream;
3607 const gchar *encoding;
3612 gboolean needs_unmap = TRUE;
3614 sub_stream = (GstMatroskaTrackSubtitleContext *) stream;
3616 if (!gst_buffer_get_size (*buf) || !gst_buffer_map (*buf, &map, GST_MAP_READ))
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);
3627 if (!sub_stream->invalid_utf8) {
3628 if (g_utf8_validate ((gchar *) map.data, map.size, NULL)) {
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;
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";
3648 g_convert_with_fallback ((gchar *) map.data, map.size, "UTF-8", encoding,
3649 (char *) "*", NULL, NULL, &err);
3652 GST_LOG_OBJECT (element, "could not convert string from '%s' to UTF-8: %s",
3653 encoding, err->message);
3657 /* invalid input encoding, fall back to ISO-8859-15 (always succeeds) */
3658 encoding = "ISO-8859-15";
3660 g_convert_with_fallback ((gchar *) map.data, map.size, "UTF-8",
3661 encoding, (char *) "*", NULL, NULL, NULL);
3664 GST_LOG_OBJECT (element, "converted subtitle text from %s to UTF-8 %s",
3665 encoding, (err) ? "(using ISO-8859-15 as fallback)" : "");
3668 utf8 = g_strdup ("invalid subtitle");
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,
3675 gst_buffer_unref (*buf);
3678 gst_buffer_map (*buf, &map, GST_MAP_READ);
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);
3688 if (!sub_stream->seen_markup_tag) {
3689 utf8 = g_markup_escape_text ((gchar *) map.data, map.size);
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);
3699 needs_unmap = FALSE;
3704 gst_buffer_unmap (*buf, &map);
3709 static GstFlowReturn
3710 gst_matroska_demux_check_aac (GstElement * element,
3711 GstMatroskaTrackContext * stream, GstBuffer ** buf)
3716 gst_buffer_extract (*buf, 0, data, 2);
3717 size = gst_buffer_get_size (*buf);
3719 if (size > 2 && data[0] == 0xff && (data[1] >> 4 == 0x0f)) {
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);
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);
3733 /* disable subsequent checking */
3734 stream->postprocess_frame = NULL;
3740 gst_matroska_demux_align_buffer (GstMatroskaDemux * demux,
3741 GstBuffer * buffer, gsize alignment)
3745 gst_buffer_map (buffer, &map, GST_MAP_READ);
3747 if (map.size < sizeof (guintptr)) {
3748 gst_buffer_unmap (buffer, &map);
3752 if (((guintptr) map.data) & (alignment - 1)) {
3753 GstBuffer *new_buffer;
3754 GstAllocationParams params = { 0, alignment - 1, 0, 0, };
3756 new_buffer = gst_buffer_new_allocate (NULL,
3757 gst_buffer_get_size (buffer), ¶ms);
3759 /* Copy data "by hand", so ensure alignment is kept: */
3760 gst_buffer_fill (new_buffer, 0, map.data, map.size);
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",
3767 gst_buffer_unmap (buffer, &map);
3768 gst_buffer_unref (buffer);
3773 gst_buffer_unmap (buffer, &map);
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)
3782 GstMatroskaTrackContext *stream = NULL;
3783 GstFlowReturn ret = GST_FLOW_OK;
3784 gboolean readblock = FALSE;
3786 guint64 block_duration = -1;
3787 gint64 block_discardpadding = 0;
3788 GstBuffer *buf = NULL;
3790 gint stream_num = -1, n, laces = 0;
3792 gint *lace_size = NULL;
3795 gint64 referenceblock = 0;
3797 GstClockTime buffer_timestamp;
3799 offset = gst_ebml_read_get_offset (ebml);
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) {
3807 id = GST_MATROSKA_ID_SIMPLEBLOCK;
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:
3821 gst_buffer_unmap (buf, &map);
3822 gst_buffer_unref (buf);
3825 if ((ret = gst_ebml_read_buffer (ebml, &id, &buf)) != GST_FLOW_OK)
3828 gst_buffer_map (buf, &map, GST_MAP_READ);
3832 /* first byte(s): blocknum */
3833 if ((n = gst_matroska_ebmlnum_uint (data, size, &num)) < 0)
3838 /* fetch stream from num */
3839 stream_num = gst_matroska_read_common_stream_from_num (&demux->common,
3841 if (G_UNLIKELY (size < 3)) {
3842 GST_WARNING_OBJECT (demux, "Invalid size %u", size);
3843 /* non-fatal, try next block(group) */
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);
3855 stream = g_ptr_array_index (demux->common.src, stream_num);
3857 /* time (relative to cluster time) */
3858 time = ((gint16) GST_READ_UINT16_BE (data));
3861 flags = GST_READ_UINT8 (data);
3865 GST_LOG_OBJECT (demux, "time %" G_GUINT64_FORMAT ", flags %d", time,
3868 switch ((flags & 0x06) >> 1) {
3869 case 0x0: /* no lacing */
3871 lace_size = g_new (gint, 1);
3872 lace_size[0] = size;
3875 case 0x1: /* xiph lacing */
3876 case 0x2: /* fixed-size lacing */
3877 case 0x3: /* EBML lacing */
3879 goto invalid_lacing;
3880 laces = GST_READ_UINT8 (data) + 1;
3883 lace_size = g_new0 (gint, laces);
3885 switch ((flags & 0x06) >> 1) {
3886 case 0x1: /* xiph lacing */ {
3887 guint temp, total = 0;
3889 for (n = 0; ret == GST_FLOW_OK && n < laces - 1; n++) {
3892 goto invalid_lacing;
3893 temp = GST_READ_UINT8 (data);
3894 lace_size[n] += temp;
3900 total += lace_size[n];
3902 lace_size[n] = size - total;
3906 case 0x2: /* fixed-size lacing */
3907 for (n = 0; n < laces; n++)
3908 lace_size[n] = size / laces;
3911 case 0x3: /* EBML lacing */ {
3914 if ((n = gst_matroska_ebmlnum_uint (data, size, &num)) < 0)
3918 total = lace_size[0] = num;
3919 for (n = 1; ret == GST_FLOW_OK && n < laces - 1; n++) {
3923 if ((r = gst_matroska_ebmlnum_sint (data, size, &snum)) < 0)
3927 lace_size[n] = lace_size[n - 1] + snum;
3928 total += lace_size[n];
3931 lace_size[n] = size - total;
3938 if (ret != GST_FLOW_OK)
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,
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));
3959 case GST_MATROSKA_ID_REFERENCEBLOCK:{
3960 ret = gst_ebml_read_sint (ebml, &id, &referenceblock);
3961 GST_DEBUG_OBJECT (demux, "ReferenceBlock: %" G_GINT64_FORMAT,
3966 case GST_MATROSKA_ID_CODECSTATE:{
3968 guint64 data_len = 0;
3971 gst_ebml_read_binary (ebml, &id, &data,
3972 &data_len)) != GST_FLOW_OK)
3975 if (G_UNLIKELY (stream == NULL)) {
3976 GST_WARNING_OBJECT (demux,
3977 "Unexpected CodecState subelement - ignoring");
3981 g_free (stream->codec_state);
3982 stream->codec_state = data;
3983 stream->codec_state_size = data_len;
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");
3995 GST_DEBUG_OBJECT (demux, "CodecState of %" G_GSIZE_FORMAT " bytes",
3996 stream->codec_state_size);
4001 ret = gst_matroska_read_common_parse_skip (&demux->common, ebml,
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);
4020 /* reading a number or so could have failed */
4021 if (ret != GST_FLOW_OK)
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;
4030 stream = g_ptr_array_index (demux->common.src, stream_num);
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) {
4038 if (stream->timecodescale == 1.0)
4039 lace_time = (cluster_time + time) * demux->common.time_scale;
4042 gst_util_guint64_to_gdouble ((cluster_time + time) *
4043 demux->common.time_scale) * stream->timecodescale;
4046 lace_time = GST_CLOCK_TIME_NONE;
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;
4053 GstEvent *segment_event;
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));
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;
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;
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);
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);
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;
4102 /* else duration is diff between timecode of this and next block */
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) {
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));
4116 /* If we're doing a keyframe-only trickmode, only push keyframes on video
4120 segment.flags & GST_SEGMENT_FLAG_TRICKMODE_KEY_UNITS) {
4121 GST_LOG_OBJECT (demux, "Skipping non-keyframe on stream %d",
4128 for (n = 0; n < laces; n++) {
4131 if (G_UNLIKELY (lace_size[n] > size)) {
4132 GST_WARNING_OBJECT (demux, "Invalid lace size");
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;
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);
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);
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;
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);
4181 GST_BUFFER_FLAG_SET (sub, GST_BUFFER_FLAG_DELTA_UNIT);
4183 GST_BUFFER_FLAG_UNSET (sub, GST_BUFFER_FLAG_DELTA_UNIT);
4185 if (invisible_frame)
4186 GST_BUFFER_FLAG_SET (sub, GST_BUFFER_FLAG_DECODE_ONLY);
4188 if (stream->encodings != NULL && stream->encodings->len > 0)
4189 sub = gst_matroska_decode_buffer (stream, sub);
4192 GST_WARNING_OBJECT (demux, "Decoding buffer failed");
4196 if (!stream->dts_only) {
4197 GST_BUFFER_PTS (sub) = lace_time;
4199 GST_BUFFER_DTS (sub) = lace_time;
4200 if (stream->intra_only)
4201 GST_BUFFER_PTS (sub) = lace_time;
4204 buffer_timestamp = gst_matroska_track_get_buffer_timestamp (stream, sub);
4206 if (GST_CLOCK_TIME_IS_VALID (lace_time)) {
4207 GstClockTime last_stop_end;
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);
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",
4223 gst_buffer_unref (sub);
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;
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)) {
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));
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);
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;
4262 GST_OBJECT_UNLOCK (demux);
4264 last_stop_end = lace_time;
4266 GST_BUFFER_DURATION (sub) = duration / laces;
4267 last_stop_end += GST_BUFFER_DURATION (sub);
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;
4274 GST_OBJECT_LOCK (demux);
4275 if (demux->common.segment.duration == -1 ||
4276 demux->stream_start_time + demux->common.segment.duration <
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;
4287 GST_OBJECT_UNLOCK (demux);
4291 stream->pos = lace_time;
4293 gst_matroska_demux_sync_streams (demux);
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;
4300 GST_BUFFER_FLAG_UNSET (sub, GST_BUFFER_FLAG_DISCONT);
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;
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)));
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);
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,
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);
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);
4348 if (!strcmp (stream->codec_id, GST_MATROSKA_CODEC_ID_AUDIO_OPUS)) {
4349 guint64 start_clip = 0, end_clip = 0;
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;
4356 GST_BUFFER_PTS (sub) = 0;
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. */
4365 gst_util_uint64_scale_round (stream->codec_delay, 48000,
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;
4372 GST_BUFFER_DURATION (sub) = 0;
4377 if (block_discardpadding) {
4379 gst_util_uint64_scale_round (block_discardpadding, 48000,
4383 if (start_clip || end_clip) {
4384 gst_buffer_add_audio_clipping_meta (sub, GST_FORMAT_DEFAULT,
4385 start_clip, end_clip);
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);
4399 ret = gst_pad_push (stream->pad, sub);
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");
4411 ret = gst_flow_combiner_update_pad_flow (demux->flowcombiner,
4415 size -= lace_size[n];
4416 if (lace_time != GST_CLOCK_TIME_NONE && duration)
4417 lace_time += duration / laces;
4419 lace_time = GST_CLOCK_TIME_NONE;
4425 gst_buffer_unmap (buf, &map);
4426 gst_buffer_unref (buf);
4438 ret = gst_flow_combiner_update_pad_flow (demux->flowcombiner, stream->pad,
4444 GST_ELEMENT_WARNING (demux, STREAM, DEMUX, (NULL), ("Invalid lacing size"));
4445 /* non-fatal, try next block(group) */
4451 GST_ELEMENT_WARNING (demux, STREAM, DEMUX, (NULL), ("Data error"));
4452 /* non-fatal, try next block(group) */
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)
4462 if (G_UNLIKELY (demux->seek_block)) {
4463 if (!(--demux->seek_block)) {
4466 GST_LOG_OBJECT (demux, "should skip block due to seek");
4474 static GstFlowReturn
4475 gst_matroska_demux_parse_contents_seekentry (GstMatroskaDemux * demux,
4479 guint64 seek_pos = (guint64) - 1;
4480 guint32 seek_id = 0;
4483 DEBUG_ELEMENT_START (demux, ebml, "Seek");
4485 if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
4486 DEBUG_ELEMENT_STOP (demux, ebml, "Seek", ret);
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)
4495 case GST_MATROSKA_ID_SEEKID:
4499 if ((ret = gst_ebml_read_uint (ebml, &id, &t)) != GST_FLOW_OK)
4502 GST_DEBUG_OBJECT (demux, "SeekID: %" G_GUINT64_FORMAT, t);
4507 case GST_MATROSKA_ID_SEEKPOSITION:
4511 if ((ret = gst_ebml_read_uint (ebml, &id, &t)) != GST_FLOW_OK)
4514 if (t > G_MAXINT64) {
4515 GST_WARNING_OBJECT (demux,
4516 "Too large SeekPosition %" G_GUINT64_FORMAT, t);
4520 GST_DEBUG_OBJECT (demux, "SeekPosition: %" G_GUINT64_FORMAT, t);
4526 ret = gst_matroska_read_common_parse_skip (&demux->common, ebml,
4532 if (ret != GST_FLOW_OK && ret != GST_FLOW_EOS)
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);
4542 case GST_MATROSKA_ID_SEEKHEAD:
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:
4552 guint64 before_pos, length;
4556 length = gst_matroska_read_common_get_length (&demux->common);
4557 before_pos = demux->common.offset;
4559 if (length == (guint64) - 1) {
4560 GST_DEBUG_OBJECT (demux, "no upstream length, skipping SeakHead entry");
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,
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);
4585 demux->common.offset = seek_pos + demux->common.ebml_segment_start;
4588 if ((ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
4589 GST_ELEMENT_CAST (demux), &id, &length, &needed)) !=
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);
4599 ret = gst_matroska_demux_parse_id (demux, id, length, needed);
4604 demux->common.offset = before_pos;
4608 case GST_MATROSKA_ID_CLUSTER:
4610 guint64 pos = seek_pos + demux->common.ebml_segment_start;
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);
4620 GST_DEBUG_OBJECT (demux, "Ignoring Seek entry for ID=0x%x", seek_id);
4623 DEBUG_ELEMENT_STOP (demux, ebml, "Seek", ret);
4628 static GstFlowReturn
4629 gst_matroska_demux_parse_contents (GstMatroskaDemux * demux, GstEbmlRead * ebml)
4631 GstFlowReturn ret = GST_FLOW_OK;
4634 DEBUG_ELEMENT_START (demux, ebml, "SeekHead");
4636 if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
4637 DEBUG_ELEMENT_STOP (demux, ebml, "SeekHead", ret);
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)
4646 case GST_MATROSKA_ID_SEEKENTRY:
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));
4658 ret = gst_matroska_read_common_parse_skip (&demux->common,
4659 ebml, "SeekHead", id);
4664 DEBUG_ELEMENT_STOP (demux, ebml, "SeekHead", ret);
4666 /* Sort clusters by position for easier searching */
4667 if (demux->clusters)
4668 g_array_sort (demux->clusters, (GCompareFunc) gst_matroska_cluster_compare);
4673 #define GST_FLOW_OVERFLOW GST_FLOW_CUSTOM_ERROR
4675 #define MAX_BLOCK_SIZE (15 * 1024 * 1024)
4677 static inline GstFlowReturn
4678 gst_matroska_demux_check_read_size (GstMatroskaDemux * demux, guint64 bytes)
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;
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;
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)
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;
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)) !=
4721 /* did not work, give up */
4724 GST_DEBUG_OBJECT (demux, "... found at %" G_GUINT64_FORMAT, pos);
4725 /* try that position */
4726 demux->common.offset = pos;
4732 static inline GstFlowReturn
4733 gst_matroska_demux_flush (GstMatroskaDemux * demux, guint flush)
4735 GST_LOG_OBJECT (demux, "skipping %d bytes", flush);
4736 demux->common.offset += flush;
4737 if (demux->streaming) {
4740 /* hard to skip large blocks when streaming */
4741 ret = gst_matroska_demux_check_read_size (demux, flush);
4742 if (ret != GST_FLOW_OK)
4744 if (flush <= gst_adapter_available (demux->common.adapter))
4745 gst_adapter_flush (demux->common.adapter, flush);
4747 return GST_FLOW_EOS;
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,
4759 GstBuffer *buffer = NULL;
4760 GstFlowReturn ret = GST_FLOW_OK;
4762 GST_LOG_OBJECT (demux, "taking %" G_GUINT64_FORMAT " bytes for parsing",
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;
4771 /* otherwise fatal */
4772 ret = GST_FLOW_ERROR;
4776 if (demux->streaming) {
4777 if (gst_adapter_available (demux->common.adapter) >= bytes)
4778 buffer = gst_adapter_take_buffer (demux->common.adapter, bytes);
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;
4794 gst_matroska_demux_check_seekability (GstMatroskaDemux * demux)
4797 gboolean seekable = FALSE;
4798 gint64 start = -1, stop = -1;
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");
4806 gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
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,
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");
4823 GST_INFO_OBJECT (demux, "seekable: %d (%" G_GUINT64_FORMAT " - %"
4824 G_GUINT64_FORMAT ")", seekable, start, stop);
4825 demux->seekable = seekable;
4827 gst_query_unref (query);
4830 static GstFlowReturn
4831 gst_matroska_demux_find_tracks (GstMatroskaDemux * demux)
4837 GstFlowReturn ret = GST_FLOW_OK;
4839 GST_WARNING_OBJECT (demux,
4840 "Found Cluster element before Tracks, searching Tracks");
4843 before_pos = demux->common.offset;
4845 /* Search Tracks element */
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)
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);
4859 demux->common.offset += needed;
4860 demux->common.offset += length;
4865 /* will lead to track parsing ... */
4866 ret = gst_matroska_demux_parse_id (demux, id, length, needed);
4871 demux->common.offset = before_pos;
4876 #define GST_READ_CHECK(stmt) \
4878 if (G_UNLIKELY ((ret = (stmt)) != GST_FLOW_OK)) { \
4879 if (ret == GST_FLOW_OVERFLOW) { \
4880 ret = GST_FLOW_OK; \
4886 static GstFlowReturn
4887 gst_matroska_demux_parse_id (GstMatroskaDemux * demux, guint32 id,
4888 guint64 length, guint needed)
4890 GstEbmlRead ebml = { 0, };
4891 GstFlowReturn ret = GST_FLOW_OK;
4894 GST_LOG_OBJECT (demux, "Parsing Element id 0x%x, "
4895 "size %" G_GUINT64_FORMAT ", prefix %d", id, length, needed);
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 */
4901 if (G_LIKELY (length != G_MAXUINT64))
4904 switch (demux->common.state) {
4905 case GST_MATROSKA_READ_STATE_START:
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)
4912 demux->common.state = GST_MATROSKA_READ_STATE_SEGMENT;
4913 gst_matroska_demux_check_seekability (demux);
4916 goto invalid_header;
4920 case GST_MATROSKA_READ_STATE_SEGMENT:
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;
4932 length = G_MAXUINT64;
4933 demux->common.ebml_segment_length = length;
4934 demux->common.state = GST_MATROSKA_READ_STATE_HEADER;
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));
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
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;
4963 case GST_MATROSKA_READ_STATE_HEADER:
4964 case GST_MATROSKA_READ_STATE_DATA:
4965 case GST_MATROSKA_READ_STATE_SEEK:
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);
4975 GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
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);
4983 GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
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;
4992 ret = gst_matroska_demux_find_tracks (demux);
4993 if (!demux->tracks_parsed)
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;
5001 if (!demux->streaming &&
5002 !GST_CLOCK_TIME_IS_VALID (demux->common.segment.duration)) {
5003 GstMatroskaIndex *last = NULL;
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));
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, };
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);
5034 demux->common.offset = demux->first_cluster_offset;
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
5042 demux->need_segment = TRUE;
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",
5051 demux->seek_block = 0;
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);
5060 case GST_MATROSKA_ID_CLUSTERTIMECODE:
5064 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5065 if ((ret = gst_ebml_read_uint (&ebml, &id, &num)) != GST_FLOW_OK)
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;
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);
5093 case GST_MATROSKA_ID_BLOCKGROUP:
5094 if (!gst_matroska_demux_seek_block (demux))
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);
5102 DEBUG_ELEMENT_STOP (demux, &ebml, "BlockGroup", ret);
5104 case GST_MATROSKA_ID_SIMPLEBLOCK:
5105 if (!gst_matroska_demux_seek_block (demux))
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);
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);
5121 GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
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);
5131 case GST_MATROSKA_ID_CHAPTERS:
5132 if (!demux->common.chapters_parsed) {
5133 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5135 gst_matroska_read_common_parse_chapters (&demux->common, &ebml);
5137 if (demux->common.toc) {
5138 gst_matroska_demux_send_event (demux,
5139 gst_event_new_toc (demux->common.toc, FALSE));
5142 GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
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);
5148 case GST_MATROSKA_ID_CUES:
5149 if (demux->common.index_parsed) {
5150 GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
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) {
5160 GST_OBJECT_LOCK (demux);
5161 event = demux->seek_event;
5162 demux->seek_event = NULL;
5163 GST_OBJECT_UNLOCK (demux);
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);
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);
5178 case GST_MATROSKA_ID_PREVSIZE:{
5181 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5182 if ((ret = gst_ebml_read_uint (&ebml, &id, &num)) != GST_FLOW_OK)
5184 GST_LOG_OBJECT (demux, "ClusterPrevSize: %" G_GUINT64_FORMAT, num);
5185 demux->cluster_prevsize = num;
5186 demux->seen_cluster_prevsize = TRUE;
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);
5197 GST_DEBUG_OBJECT (demux, "skipping Element 0x%x", id);
5198 GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
5204 if (ret == GST_FLOW_PARSE)
5208 gst_ebml_read_clear (&ebml);
5214 /* simply exit, maybe not enough data yet */
5215 /* no ebml to clear if read error */
5220 GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
5221 ("Failed to parse Element 0x%x", id));
5222 ret = GST_FLOW_ERROR;
5227 GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
5228 ("File layout does not permit streaming"));
5229 ret = GST_FLOW_ERROR;
5234 GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
5235 ("No Tracks element found"));
5236 ret = GST_FLOW_ERROR;
5241 GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL), ("Invalid header"));
5242 ret = GST_FLOW_ERROR;
5247 GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL), ("Failed to seek"));
5248 ret = GST_FLOW_ERROR;
5254 gst_matroska_demux_loop (GstPad * pad)
5256 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (GST_PAD_PARENT (pad));
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;
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) {
5274 } else if (ret == GST_FLOW_FLUSHING) {
5276 } else if (ret != GST_FLOW_OK) {
5277 ret = gst_matroska_demux_check_parse_error (demux);
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))
5285 else if (ret != GST_FLOW_OK)
5291 GST_LOG_OBJECT (demux, "Offset %" G_GUINT64_FORMAT ", Element id 0x%x, "
5292 "size %" G_GUINT64_FORMAT ", needed %d", demux->common.offset, id,
5295 ret = gst_matroska_demux_parse_id (demux, id, length, needed);
5296 if (ret == GST_FLOW_EOS)
5298 if (ret != GST_FLOW_OK)
5301 /* check if we're at the end of a configured segment */
5302 if (G_LIKELY (demux->common.src->len)) {
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,
5309 GST_DEBUG_OBJECT (context->pad, "pos %" GST_TIME_FORMAT,
5310 GST_TIME_ARGS (context->pos));
5311 if (context->eos == FALSE)
5315 GST_INFO_OBJECT (demux, "All streams are EOS");
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");
5336 if (demux->common.segment.rate < 0.0) {
5337 ret = gst_matroska_demux_seek_to_previous_keyframe (demux);
5338 if (ret == GST_FLOW_OK)
5345 const gchar *reason = gst_flow_get_name (ret);
5346 gboolean push_eos = FALSE;
5348 GST_LOG_OBJECT (demux, "pausing task, reason %s", reason);
5349 gst_pad_pause_task (demux->common.sinkpad);
5351 if (ret == GST_FLOW_EOS) {
5352 /* perform EOS logic */
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"));
5362 GST_ELEMENT_WARNING (demux, STREAM, DEMUX, (NULL),
5363 ("Failed to finish reading headers"));
5365 gst_element_no_more_pads (GST_ELEMENT (demux));
5368 if (demux->common.segment.flags & GST_SEEK_FLAG_SEGMENT) {
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;
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,
5381 if (demux->segment_seqnum)
5382 gst_message_set_seqnum (msg, demux->segment_seqnum);
5383 gst_element_post_message (GST_ELEMENT (demux), msg);
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);
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);
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)"));
5416 * Create and push a flushing seek event upstream
5419 perform_seek_to_offset (GstMatroskaDemux * demux, gdouble rate, guint64 offset,
5420 guint32 seqnum, GstSeekFlags flags)
5425 GST_DEBUG_OBJECT (demux, "Seeking to %" G_GUINT64_FORMAT, offset);
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);
5433 res = gst_pad_push_event (demux->common.sinkpad, event);
5435 /* segment event will update offset */
5439 static GstFlowReturn
5440 gst_matroska_demux_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
5442 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (parent);
5444 GstFlowReturn ret = GST_FLOW_OK;
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);
5458 gst_adapter_push (demux->common.adapter, buffer);
5462 available = gst_adapter_available (demux->common.adapter);
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) {
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;
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;
5486 GST_WARNING_OBJECT (demux,
5487 "unrecoverable parse error, next cluster not found and threshold "
5488 "exceeded, bytes scanned %" G_GINT64_FORMAT, bytes_scanned);
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);
5498 if (needed > available)
5501 ret = gst_matroska_demux_parse_id (demux, id, length, needed);
5502 if (ret == GST_FLOW_EOS) {
5503 /* need more data */
5505 } else if (ret != GST_FLOW_OK) {
5512 gst_matroska_demux_handle_sink_event (GstPad * pad, GstObject * parent,
5515 gboolean res = TRUE;
5516 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (parent);
5518 GST_DEBUG_OBJECT (demux,
5519 "have event type %s: %p on sink pad", GST_EVENT_TYPE_NAME (event), event);
5521 switch (GST_EVENT_TYPE (event)) {
5522 case GST_EVENT_SEGMENT:
5524 const GstSegment *segment;
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,
5533 if (demux->common.state < GST_MATROSKA_READ_STATE_DATA) {
5534 GST_DEBUG_OBJECT (demux, "still starting");
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");
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;
5571 GST_DEBUG_OBJECT (demux, "unexpected segment position");
5573 demux->requested_seek_time = GST_CLOCK_TIME_NONE;
5574 demux->seek_offset = -1;
5575 GST_OBJECT_UNLOCK (demux);
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);
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)"));
5595 gst_matroska_demux_send_event (demux, event);
5599 case GST_EVENT_FLUSH_STOP:
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);
5618 res = gst_pad_event_default (pad, parent, event);
5626 gst_matroska_demux_sink_activate (GstPad * sinkpad, GstObject * parent)
5628 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (parent);
5630 gboolean pull_mode = FALSE;
5632 query = gst_query_new_scheduling ();
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);
5638 gst_query_unref (query);
5641 GST_DEBUG ("going to pull mode");
5642 demux->streaming = FALSE;
5643 return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PULL, TRUE);
5645 GST_DEBUG ("going to push (streaming) mode");
5646 demux->streaming = TRUE;
5647 return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
5652 gst_matroska_demux_sink_activate_mode (GstPad * sinkpad, GstObject * parent,
5653 GstPadMode mode, gboolean active)
5656 case GST_PAD_MODE_PULL:
5658 /* if we have a scheduler we can start the task */
5659 gst_pad_start_task (sinkpad, (GstTaskFunction) gst_matroska_demux_loop,
5662 gst_pad_stop_task (sinkpad);
5665 case GST_PAD_MODE_PUSH:
5673 gst_matroska_demux_video_caps (GstMatroskaTrackVideoContext *
5674 videocontext, const gchar * codec_id, guint8 * data, guint size,
5675 gchar ** codec_name, guint32 * riff_fourcc)
5677 GstMatroskaTrackContext *context = (GstMatroskaTrackContext *) videocontext;
5678 GstCaps *caps = NULL;
5680 g_assert (videocontext != NULL);
5681 g_assert (codec_name != NULL);
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
5690 * GST_MATROSKA_CODEC_ID_VIDEO_QUICKTIME
5691 * GST_MATROSKA_CODEC_ID_VIDEO_SNOW
5694 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC)) {
5695 gst_riff_strf_vids *vids = NULL;
5698 GstBuffer *buf = NULL;
5700 vids = (gst_riff_strf_vids *) data;
5702 /* assure size is big enough */
5704 GST_WARNING ("Too small BITMAPINFOHEADER (%d bytes)", size);
5707 if (size < sizeof (gst_riff_strf_vids)) {
5708 vids = g_new (gst_riff_strf_vids, 1);
5709 memcpy (vids, data, size);
5712 context->dts_only = TRUE; /* VFW files only store DTS */
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);
5727 if (size > sizeof (gst_riff_strf_vids)) { /* some extra_data */
5728 gsize offset = sizeof (gst_riff_strf_vids);
5731 gst_buffer_new_wrapped (g_memdup ((guint8 *) vids + offset,
5732 size - offset), size - offset);
5736 *riff_fourcc = vids->compression;
5738 caps = gst_riff_create_video_caps (vids->compression, NULL, vids,
5739 buf, NULL, codec_name);
5742 GST_WARNING ("Unhandled RIFF fourcc %" GST_FOURCC_FORMAT,
5743 GST_FOURCC_ARGS (vids->compression));
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);
5753 gst_buffer_unref (buf);
5755 if (vids != (gst_riff_strf_vids *) data)
5758 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_UNCOMPRESSED)) {
5760 GstVideoFormat format;
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;
5767 case GST_MAKE_FOURCC ('Y', 'U', 'Y', '2'):
5768 format = GST_VIDEO_FORMAT_YUY2;
5770 case GST_MAKE_FOURCC ('Y', 'V', '1', '2'):
5771 format = GST_VIDEO_FORMAT_YV12;
5773 case GST_MAKE_FOURCC ('U', 'Y', 'V', 'Y'):
5774 format = GST_VIDEO_FORMAT_UYVY;
5776 case GST_MAKE_FOURCC ('A', 'Y', 'U', 'V'):
5777 format = GST_VIDEO_FORMAT_AYUV;
5779 case GST_MAKE_FOURCC ('Y', '8', '0', '0'):
5780 case GST_MAKE_FOURCC ('Y', '8', ' ', ' '):
5781 format = GST_VIDEO_FORMAT_GRAY8;
5783 case GST_MAKE_FOURCC ('R', 'G', 'B', 24):
5784 format = GST_VIDEO_FORMAT_RGB;
5786 case GST_MAKE_FOURCC ('B', 'G', 'R', 24):
5787 format = GST_VIDEO_FORMAT_BGR;
5790 GST_DEBUG ("Unknown fourcc %" GST_FOURCC_FORMAT,
5791 GST_FOURCC_ARGS (videocontext->fourcc));
5795 context->intra_only = TRUE;
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);
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);
5818 gst_codec_utils_mpeg4video_caps_set_level_and_profile (caps, data, size);
5820 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_ASP))
5821 *codec_name = g_strdup ("MPEG-4 advanced simple profile");
5823 *codec_name = g_strdup ("MPEG-4 advanced profile");
5824 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MSMPEG4V3)) {
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);
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)) {
5838 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG1))
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");
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,
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);
5867 gst_caps_set_simple (caps, "stream-format", G_TYPE_STRING, "avc",
5868 "alignment", G_TYPE_STRING, "au", NULL);
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",
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");
5880 gst_codec_utils_h265_caps_set_level_tier_and_profile (caps, data + 1,
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);
5887 gst_caps_set_simple (caps, "stream-format", G_TYPE_STRING, "hvc1",
5888 "alignment", G_TYPE_STRING, "au", NULL);
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",
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;
5901 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO1))
5903 else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO2))
5905 else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO3))
5907 else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO4))
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)) {
5919 subformat = GST_READ_UINT32_BE (data + 0x1a);
5920 rformat = GST_READ_UINT32_BE (data + 0x1e);
5923 gst_buffer_new_wrapped (g_memdup (data + 0x1a, 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);
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");
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);
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",
5960 *codec_name = g_strdup_printf ("AOM AV1");
5961 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_PRORES)) {
5963 const gchar *variant, *variant_descr = "";
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);
5971 fourcc = GST_STR_FOURCC (data);
5973 case GST_MAKE_FOURCC ('a', 'p', 'c', 's'):
5974 variant_descr = " 4:2:2 LT";
5977 case GST_MAKE_FOURCC ('a', 'p', 'c', 'h'):
5979 variant_descr = " 4:2:2 HQ";
5981 case GST_MAKE_FOURCC ('a', 'p', '4', 'h'):
5983 variant_descr = " 4:4:4:4";
5985 case GST_MAKE_FOURCC ('a', 'p', 'c', 'o'):
5987 variant_descr = " 4:2:2 Proxy";
5989 case GST_MAKE_FOURCC ('a', 'p', 'c', 'n'):
5991 variant = "standard";
5992 variant_descr = " 4:2:2 SD";
5996 GST_LOG ("Prores video, codec fourcc %" GST_FOURCC_FORMAT,
5997 GST_FOURCC_ARGS (fourcc));
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;
6004 GST_WARNING ("Unknown codec '%s', cannot build Caps", codec_id);
6010 GstStructure *structure;
6012 for (i = 0; i < gst_caps_get_size (caps); i++) {
6013 structure = gst_caps_get_structure (caps, i);
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);
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;
6026 gst_structure_set (structure,
6027 "width", G_TYPE_INT, w, "height", G_TYPE_INT, h, NULL);
6030 if (videocontext->display_width > 0 || videocontext->display_height > 0) {
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;
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",
6044 videocontext->display_width * videocontext->pixel_height,
6045 videocontext->display_height * videocontext->pixel_width, NULL);
6048 if (videocontext->default_fps > 0.0) {
6051 gst_util_double_to_fraction (videocontext->default_fps, &fps_n, &fps_d);
6053 GST_DEBUG ("using default fps %d/%d", fps_n, fps_d);
6055 gst_structure_set (structure, "framerate", GST_TYPE_FRACTION, fps_n,
6057 } else if (context->default_duration > 0) {
6060 gst_video_guess_framerate (context->default_duration, &fps_n, &fps_d);
6062 GST_INFO ("using default duration %" G_GUINT64_FORMAT
6063 " framerate %d/%d", context->default_duration, fps_n, fps_d);
6065 gst_structure_set (structure, "framerate", GST_TYPE_FRACTION,
6066 fps_n, fps_d, NULL);
6068 gst_structure_set (structure, "framerate", GST_TYPE_FRACTION,
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);
6077 case GST_MATROSKA_INTERLACE_MODE_INTERLACED:
6078 gst_structure_set (structure,
6079 "interlace-mode", G_TYPE_STRING, "mixed", NULL);
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;
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);
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,
6109 GST_DEBUG ("setting colorimetry to %s", colorimetry);
6110 g_free (colorimetry);
6113 caps = gst_caps_simplify (caps);
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)
6126 aac_rate_idx (gint rate)
6130 else if (75132 <= rate)
6132 else if (55426 <= rate)
6134 else if (46009 <= rate)
6136 else if (37566 <= rate)
6138 else if (27713 <= rate)
6140 else if (23004 <= rate)
6142 else if (18783 <= rate)
6144 else if (13856 <= rate)
6146 else if (11502 <= rate)
6148 else if (9391 <= rate)
6155 aac_profile_idx (const gchar * codec_id)
6159 if (strlen (codec_id) <= 12)
6161 else if (!strncmp (&codec_id[12], "MAIN", 4))
6163 else if (!strncmp (&codec_id[12], "LC", 2))
6165 else if (!strncmp (&codec_id[12], "SSR", 3))
6174 round_up_pow2 (guint n)
6185 #define AAC_SYNC_EXTENSION_TYPE 0x02b7
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)
6192 GstMatroskaTrackContext *context = (GstMatroskaTrackContext *) audiocontext;
6193 GstCaps *caps = NULL;
6195 g_assert (audiocontext != NULL);
6196 g_assert (codec_name != NULL);
6199 *riff_audio_fmt = 0;
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
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
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)) {
6217 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L1))
6219 else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L2))
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)) {
6231 GstAudioFormat format;
6233 sign = (audiocontext->bitdepth != 8);
6234 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_PCM_INT_BE))
6235 endianness = G_BIG_ENDIAN;
6237 endianness = G_LITTLE_ENDIAN;
6239 format = gst_audio_format_build_integer (sign, endianness,
6240 audiocontext->bitdepth, audiocontext->bitdepth);
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);
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)
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)) {
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) {
6316 gst_util_uint64_scale_round (context->codec_delay, 48000,
6318 GST_WRITE_UINT16_LE ((guint8 *) context->codec_priv + 10, delay);
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;
6334 audiocontext->samplerate == 0 ? 48000 : audiocontext->samplerate;
6335 channels = audiocontext->channels == 0 ? 2 : audiocontext->channels;
6336 if (channels == 1) {
6345 gst_codec_utils_opus_create_caps (samplerate, channels, 0, streams,
6348 *codec_name = g_strdup ("Opus");
6350 GST_WARNING ("Failed to create Opus caps from audio context");
6353 GST_WARNING ("No Opus codec data, and not enough info to create one");
6356 GST_WARNING ("Invalid Opus codec data size (got %" G_GSIZE_FORMAT
6357 ", expected 19)", context->codec_priv_size);
6359 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_ACM)) {
6360 gst_riff_strf_auds auds;
6362 if (data && size >= 18) {
6363 GstBuffer *codec_data = NULL;
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);
6373 /* 18 is the waveformatex size */
6375 codec_data = gst_buffer_new_wrapped_full (GST_MEMORY_FLAG_READONLY,
6376 data + 18, size - 18, 0, size - 18, NULL, NULL);
6380 *riff_audio_fmt = auds.format;
6382 /* FIXME: Handle reorder map */
6383 caps = gst_riff_create_audio_caps (auds.format, NULL, &auds, NULL,
6384 codec_data, codec_name, NULL);
6386 gst_buffer_unref (codec_data);
6389 GST_WARNING ("Unhandled RIFF audio format 0x%02x", auds.format);
6392 GST_WARNING ("Invalid codec data size (%d expected, got %d)", 18, size);
6394 } else if (g_str_has_prefix (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_AAC)) {
6395 GstBuffer *priv = NULL;
6397 gint rate_idx, profile;
6398 guint8 *data = NULL;
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;
6405 codec_id = GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG4;
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;
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;
6431 /* make up decoder-specific data if it is not supplied */
6435 priv = gst_buffer_new_allocate (NULL, 5, NULL);
6436 gst_buffer_map (priv, &map, GST_MAP_WRITE);
6438 rate_idx = aac_rate_idx (audiocontext->samplerate);
6439 profile = aac_profile_idx (codec_id);
6441 data[0] = ((profile + 1) << 3) | ((rate_idx & 0xE) >> 1);
6442 data[1] = ((rate_idx & 0x1) << 7) | (audiocontext->channels << 3);
6444 if (!strncmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG2,
6445 strlen (GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG2))) {
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))) {
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);
6462 gst_buffer_unmap (priv, &map);
6463 gst_buffer_set_size (priv, 2);
6466 gst_buffer_unmap (priv, &map);
6467 gst_buffer_unref (priv);
6469 GST_ERROR ("Unknown AAC profile and no codec private data");
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);
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;
6501 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_14_4))
6503 else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_COOK))
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)) {
6518 guint extra_data_size;
6520 GST_DEBUG ("real audio raversion:%d", raversion);
6521 if (raversion == 8) {
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);
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,
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);
6538 if ((size - 78) >= extra_data_size) {
6539 priv = gst_buffer_new_wrapped (g_memdup (data + 78, extra_data_size),
6541 gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
6542 gst_buffer_unref (priv);
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");
6558 GST_WARNING ("Unknown codec '%s', cannot build Caps", codec_id);
6563 if (audiocontext->samplerate > 0 && audiocontext->channels > 0) {
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);
6573 caps = gst_caps_simplify (caps);
6580 gst_matroska_demux_subtitle_caps (GstMatroskaTrackSubtitleContext *
6581 subtitlecontext, const gchar * codec_id, gpointer data, guint size)
6583 GstCaps *caps = NULL;
6584 GstMatroskaTrackContext *context =
6585 (GstMatroskaTrackContext *) subtitlecontext;
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;
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;
6630 GST_DEBUG ("Unknown subtitle stream: codec_id='%s'", codec_id);
6631 caps = gst_caps_new_empty_simple ("application/x-subtitle-unknown");
6634 if (data != NULL && size > 0) {
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);
6647 gst_matroska_demux_set_index (GstElement * element, GstIndex * index)
6649 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (element);
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);
6661 gst_matroska_demux_get_index (GstElement * element)
6663 GstIndex *result = NULL;
6664 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (element);
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);
6671 GST_DEBUG_OBJECT (demux, "Returning index %" GST_PTR_FORMAT, result);
6677 static GstStateChangeReturn
6678 gst_matroska_demux_change_state (GstElement * element,
6679 GstStateChange transition)
6681 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (element);
6682 GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
6684 /* handle upwards state changes here */
6685 switch (transition) {
6690 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
6692 /* handle downwards state changes */
6693 switch (transition) {
6694 case GST_STATE_CHANGE_PAUSED_TO_READY:
6695 gst_matroska_demux_reset (GST_ELEMENT (demux));
6705 gst_matroska_demux_set_property (GObject * object,
6706 guint prop_id, const GValue * value, GParamSpec * pspec)
6708 GstMatroskaDemux *demux;
6710 g_return_if_fail (GST_IS_MATROSKA_DEMUX (object));
6711 demux = GST_MATROSKA_DEMUX (object);
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);
6720 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
6726 gst_matroska_demux_get_property (GObject * object,
6727 guint prop_id, GValue * value, GParamSpec * pspec)
6729 GstMatroskaDemux *demux;
6731 g_return_if_fail (GST_IS_MATROSKA_DEMUX (object));
6732 demux = GST_MATROSKA_DEMUX (object);
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);
6741 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
6747 gst_matroska_demux_plugin_init (GstPlugin * plugin)
6751 /* parser helper separate debug */
6752 GST_DEBUG_CATEGORY_INIT (ebmlread_debug, "ebmlread",
6753 0, "EBML stream helper class");
6755 /* create an elementfactory for the matroska_demux element */
6756 if (!gst_element_register (plugin, "matroskademux",
6757 GST_RANK_PRIMARY, GST_TYPE_MATROSKA_DEMUX))