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
36 * @title: matroskademux
38 * matroskademux demuxes a Matroska file into the different contained streams.
40 * ## Example launch line
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/gstvideocodecalphameta.h>
68 #include <gst/video/video.h>
70 #include "gstmatroskaelements.h"
71 #include "matroska-demux.h"
72 #include "matroska-ids.h"
74 GST_DEBUG_CATEGORY_STATIC (matroskademux_debug);
75 #define GST_CAT_DEFAULT matroskademux_debug
77 #define DEBUG_ELEMENT_START(demux, ebml, element) \
78 GST_DEBUG_OBJECT (demux, "Parsing " element " element at offset %" \
79 G_GUINT64_FORMAT, gst_ebml_read_get_pos (ebml))
81 #define DEBUG_ELEMENT_STOP(demux, ebml, element, ret) \
82 GST_DEBUG_OBJECT (demux, "Parsing " element " element " \
83 " finished with '%s'", gst_flow_get_name (ret))
91 PROP_MAX_BACKTRACK_DISTANCE
94 #define DEFAULT_MAX_GAP_TIME (2 * GST_SECOND)
95 #define DEFAULT_MAX_BACKTRACK_DISTANCE 30
96 #define INVALID_DATA_THRESHOLD (2 * 1024 * 1024)
98 static GstStaticPadTemplate sink_templ = GST_STATIC_PAD_TEMPLATE ("sink",
101 GST_STATIC_CAPS ("audio/x-matroska; video/x-matroska; "
102 "video/x-matroska-3d; audio/webm; video/webm")
105 /* TODO: fill in caps! */
107 static GstStaticPadTemplate audio_src_templ =
108 GST_STATIC_PAD_TEMPLATE ("audio_%u",
111 GST_STATIC_CAPS ("ANY")
114 static GstStaticPadTemplate video_src_templ =
115 GST_STATIC_PAD_TEMPLATE ("video_%u",
118 GST_STATIC_CAPS ("ANY")
121 static GstStaticPadTemplate subtitle_src_templ =
122 GST_STATIC_PAD_TEMPLATE ("subtitle_%u",
125 GST_STATIC_CAPS ("text/x-raw, format=pango-markup; application/x-ssa; "
126 "application/x-ass;application/x-usf; subpicture/x-dvd; "
127 "subpicture/x-pgs; subtitle/x-kate; " "application/x-subtitle-unknown")
130 static GQuark matroska_block_additional_quark;
132 static GstFlowReturn gst_matroska_demux_parse_id (GstMatroskaDemux * demux,
133 guint32 id, guint64 length, guint needed);
135 /* element functions */
136 static void gst_matroska_demux_loop (GstPad * pad);
138 static gboolean gst_matroska_demux_element_send_event (GstElement * element,
140 static gboolean gst_matroska_demux_element_query (GstElement * element,
144 static gboolean gst_matroska_demux_sink_activate (GstPad * sinkpad,
146 static gboolean gst_matroska_demux_sink_activate_mode (GstPad * sinkpad,
147 GstObject * parent, GstPadMode mode, gboolean active);
149 static gboolean gst_matroska_demux_handle_seek_push (GstMatroskaDemux * demux,
150 GstPad * pad, GstEvent * event);
151 static gboolean gst_matroska_demux_handle_seek_event (GstMatroskaDemux * demux,
152 GstPad * pad, GstEvent * event);
153 static gboolean gst_matroska_demux_handle_src_event (GstPad * pad,
154 GstObject * parent, GstEvent * event);
155 static gboolean gst_matroska_demux_handle_src_query (GstPad * pad,
156 GstObject * parent, GstQuery * query);
158 static gboolean gst_matroska_demux_handle_sink_event (GstPad * pad,
159 GstObject * parent, GstEvent * event);
160 static gboolean gst_matroska_demux_handle_sink_query (GstPad * pad,
161 GstObject * parent, GstQuery * query);
162 static GstFlowReturn gst_matroska_demux_chain (GstPad * pad,
163 GstObject * object, GstBuffer * buffer);
165 static GstStateChangeReturn
166 gst_matroska_demux_change_state (GstElement * element,
167 GstStateChange transition);
170 gst_matroska_demux_set_index (GstElement * element, GstIndex * index);
171 static GstIndex *gst_matroska_demux_get_index (GstElement * element);
175 static GstCaps *gst_matroska_demux_video_caps (GstMatroskaTrackVideoContext
176 * videocontext, const gchar * codec_id, guint8 * data, guint size,
177 gchar ** codec_name, guint32 * riff_fourcc);
178 static GstCaps *gst_matroska_demux_audio_caps (GstMatroskaTrackAudioContext
179 * audiocontext, const gchar * codec_id, guint8 * data, guint size,
180 gchar ** codec_name, guint16 * riff_audio_fmt, GstClockTime * lead_in_ts);
182 * gst_matroska_demux_subtitle_caps (GstMatroskaTrackSubtitleContext *
183 subtitlecontext, const gchar * codec_id, gpointer data, guint size);
184 static const gchar *gst_matroska_track_encryption_algorithm_name (gint val);
185 static const gchar *gst_matroska_track_encryption_cipher_mode_name (gint val);
186 static const gchar *gst_matroska_track_encoding_scope_name (gint val);
189 static void gst_matroska_demux_reset (GstElement * element);
190 static gboolean perform_seek_to_offset (GstMatroskaDemux * demux,
191 gdouble rate, guint64 offset, guint32 seqnum, GstSeekFlags flags);
193 /* gobject functions */
194 static void gst_matroska_demux_set_property (GObject * object,
195 guint prop_id, const GValue * value, GParamSpec * pspec);
196 static void gst_matroska_demux_get_property (GObject * object,
197 guint prop_id, GValue * value, GParamSpec * pspec);
199 GType gst_matroska_demux_get_type (void);
200 #define parent_class gst_matroska_demux_parent_class
201 G_DEFINE_TYPE (GstMatroskaDemux, gst_matroska_demux, GST_TYPE_ELEMENT);
204 matroska_element_init (plugin); \
205 GST_DEBUG_CATEGORY_INIT (ebmlread_debug, "ebmlread", 0, "EBML stream helper class"); \
206 matroska_block_additional_quark = \
207 g_quark_from_static_string ("matroska-block-additional");
209 GST_ELEMENT_REGISTER_DEFINE_WITH_CODE (matroskademux, "matroskademux",
210 GST_RANK_PRIMARY, GST_TYPE_MATROSKA_DEMUX, _do_init);
213 gst_matroska_demux_finalize (GObject * object)
215 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (object);
217 gst_matroska_read_common_finalize (&demux->common);
218 gst_flow_combiner_free (demux->flowcombiner);
219 G_OBJECT_CLASS (parent_class)->finalize (object);
223 gst_matroska_demux_class_init (GstMatroskaDemuxClass * klass)
225 GObjectClass *gobject_class = (GObjectClass *) klass;
226 GstElementClass *gstelement_class = (GstElementClass *) klass;
228 GST_DEBUG_CATEGORY_INIT (matroskademux_debug, "matroskademux", 0,
231 gobject_class->finalize = gst_matroska_demux_finalize;
233 gobject_class->get_property = gst_matroska_demux_get_property;
234 gobject_class->set_property = gst_matroska_demux_set_property;
236 g_object_class_install_property (gobject_class, PROP_MAX_GAP_TIME,
237 g_param_spec_uint64 ("max-gap-time", "Maximum gap time",
238 "The demuxer sends out segment events for skipping "
239 "gaps longer than this (0 = disabled).", 0, G_MAXUINT64,
240 DEFAULT_MAX_GAP_TIME, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
242 g_object_class_install_property (gobject_class, PROP_MAX_BACKTRACK_DISTANCE,
243 g_param_spec_uint ("max-backtrack-distance",
244 "Maximum backtrack distance",
245 "Maximum backtrack distance in seconds when seeking without "
246 "and index in pull mode and search for a keyframe "
247 "(0 = disable backtracking).",
248 0, G_MAXUINT, DEFAULT_MAX_BACKTRACK_DISTANCE,
249 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
251 gstelement_class->change_state =
252 GST_DEBUG_FUNCPTR (gst_matroska_demux_change_state);
253 gstelement_class->send_event =
254 GST_DEBUG_FUNCPTR (gst_matroska_demux_element_send_event);
255 gstelement_class->query =
256 GST_DEBUG_FUNCPTR (gst_matroska_demux_element_query);
258 gstelement_class->set_index =
259 GST_DEBUG_FUNCPTR (gst_matroska_demux_set_index);
260 gstelement_class->get_index =
261 GST_DEBUG_FUNCPTR (gst_matroska_demux_get_index);
264 gst_element_class_add_static_pad_template (gstelement_class,
266 gst_element_class_add_static_pad_template (gstelement_class,
268 gst_element_class_add_static_pad_template (gstelement_class,
269 &subtitle_src_templ);
270 gst_element_class_add_static_pad_template (gstelement_class, &sink_templ);
272 gst_element_class_set_static_metadata (gstelement_class, "Matroska demuxer",
274 "Demuxes Matroska/WebM streams into video/audio/subtitles",
275 "GStreamer maintainers <gstreamer-devel@lists.freedesktop.org>");
279 gst_matroska_demux_init (GstMatroskaDemux * demux)
281 demux->common.sinkpad = gst_pad_new_from_static_template (&sink_templ,
283 gst_pad_set_activate_function (demux->common.sinkpad,
284 GST_DEBUG_FUNCPTR (gst_matroska_demux_sink_activate));
285 gst_pad_set_activatemode_function (demux->common.sinkpad,
286 GST_DEBUG_FUNCPTR (gst_matroska_demux_sink_activate_mode));
287 gst_pad_set_chain_function (demux->common.sinkpad,
288 GST_DEBUG_FUNCPTR (gst_matroska_demux_chain));
289 gst_pad_set_event_function (demux->common.sinkpad,
290 GST_DEBUG_FUNCPTR (gst_matroska_demux_handle_sink_event));
291 gst_pad_set_query_function (demux->common.sinkpad,
292 GST_DEBUG_FUNCPTR (gst_matroska_demux_handle_sink_query));
293 gst_element_add_pad (GST_ELEMENT (demux), demux->common.sinkpad);
295 /* init defaults for common read context */
296 gst_matroska_read_common_init (&demux->common);
298 /* property defaults */
299 demux->max_gap_time = DEFAULT_MAX_GAP_TIME;
300 demux->max_backtrack_distance = DEFAULT_MAX_BACKTRACK_DISTANCE;
302 GST_OBJECT_FLAG_SET (demux, GST_ELEMENT_FLAG_INDEXABLE);
304 demux->flowcombiner = gst_flow_combiner_new ();
307 gst_matroska_demux_reset (GST_ELEMENT (demux));
311 gst_matroska_demux_reset (GstElement * element)
313 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (element);
315 GST_DEBUG_OBJECT (demux, "Resetting state");
317 gst_matroska_read_common_reset (GST_ELEMENT (demux), &demux->common);
319 demux->num_a_streams = 0;
320 demux->num_t_streams = 0;
321 demux->num_v_streams = 0;
322 demux->have_nonintraonly_v_streams = FALSE;
324 demux->have_group_id = FALSE;
325 demux->group_id = G_MAXUINT;
328 demux->tracks_parsed = FALSE;
330 if (demux->clusters) {
331 g_array_free (demux->clusters, TRUE);
332 demux->clusters = NULL;
335 g_list_foreach (demux->seek_parsed,
336 (GFunc) gst_matroska_read_common_free_parsed_el, NULL);
337 g_list_free (demux->seek_parsed);
338 demux->seek_parsed = NULL;
340 demux->last_stop_end = GST_CLOCK_TIME_NONE;
341 demux->seek_block = 0;
342 demux->stream_start_time = GST_CLOCK_TIME_NONE;
343 demux->to_time = GST_CLOCK_TIME_NONE;
344 demux->cluster_time = GST_CLOCK_TIME_NONE;
345 demux->cluster_offset = 0;
346 demux->cluster_prevsize = 0;
347 demux->seen_cluster_prevsize = FALSE;
348 demux->next_cluster_offset = 0;
349 demux->stream_last_time = GST_CLOCK_TIME_NONE;
350 demux->last_cluster_offset = 0;
351 demux->index_offset = 0;
352 demux->seekable = FALSE;
353 demux->need_segment = FALSE;
354 demux->segment_seqnum = 0;
355 demux->requested_seek_time = GST_CLOCK_TIME_NONE;
356 demux->seek_offset = -1;
357 demux->audio_lead_in_ts = 0;
358 demux->building_index = FALSE;
359 if (demux->seek_event) {
360 gst_event_unref (demux->seek_event);
361 demux->seek_event = NULL;
364 demux->seek_index = NULL;
365 demux->seek_entry = 0;
367 if (demux->new_segment) {
368 gst_event_unref (demux->new_segment);
369 demux->new_segment = NULL;
372 demux->invalid_duration = FALSE;
374 demux->cached_length = G_MAXUINT64;
376 if (demux->deferred_seek_event)
377 gst_event_unref (demux->deferred_seek_event);
378 demux->deferred_seek_event = NULL;
379 demux->deferred_seek_pad = NULL;
381 gst_flow_combiner_clear (demux->flowcombiner);
385 gst_matroska_decode_buffer (GstMatroskaTrackContext * context, GstBuffer * buf)
390 GstBuffer *out_buf = buf;
392 g_return_val_if_fail (GST_IS_BUFFER (buf), NULL);
394 GST_DEBUG ("decoding buffer %p", buf);
396 gst_buffer_map (out_buf, &map, GST_MAP_READ);
400 g_return_val_if_fail (size > 0, buf);
402 if (gst_matroska_decode_data (context->encodings, &data, &size,
403 GST_MATROSKA_TRACK_ENCODING_SCOPE_FRAME, FALSE)) {
404 if (data != map.data) {
405 gst_buffer_unmap (out_buf, &map);
406 gst_buffer_unref (out_buf);
407 out_buf = gst_buffer_new_wrapped (data, size);
409 gst_buffer_unmap (out_buf, &map);
412 GST_DEBUG ("decode data failed");
413 gst_buffer_unmap (out_buf, &map);
414 gst_buffer_unref (out_buf);
417 /* Encrypted stream */
418 if (context->protection_info) {
420 GstStructure *info_protect = gst_structure_copy (context->protection_info);
421 gboolean encrypted = FALSE;
423 gst_buffer_map (out_buf, &map, GST_MAP_READ);
427 if (gst_matroska_parse_protection_meta (&data, &size, info_protect,
429 if (data != map.data) {
432 gst_buffer_unmap (out_buf, &map);
434 out_buf = gst_buffer_copy_region (tmp_buf, GST_BUFFER_COPY_ALL,
435 gst_buffer_get_size (tmp_buf) - size, size);
436 gst_buffer_unref (tmp_buf);
438 gst_buffer_add_protection_meta (out_buf, info_protect);
440 gst_structure_free (info_protect);
442 gst_buffer_unmap (out_buf, &map);
443 gst_structure_free (info_protect);
446 GST_WARNING ("Adding protection metadata failed");
447 gst_buffer_unmap (out_buf, &map);
448 gst_buffer_unref (out_buf);
449 gst_structure_free (info_protect);
458 gst_matroska_demux_add_stream_headers_to_caps (GstMatroskaDemux * demux,
459 GstBufferList * list, GstCaps * caps)
462 GValue arr_val = G_VALUE_INIT;
463 GValue buf_val = G_VALUE_INIT;
466 g_assert (gst_caps_is_writable (caps));
468 g_value_init (&arr_val, GST_TYPE_ARRAY);
469 g_value_init (&buf_val, GST_TYPE_BUFFER);
471 num = gst_buffer_list_length (list);
472 for (i = 0; i < num; ++i) {
473 g_value_set_boxed (&buf_val, gst_buffer_list_get (list, i));
474 gst_value_array_append_value (&arr_val, &buf_val);
477 s = gst_caps_get_structure (caps, 0);
478 gst_structure_take_value (s, "streamheader", &arr_val);
479 g_value_unset (&buf_val);
483 gst_matroska_demux_parse_mastering_metadata (GstMatroskaDemux * demux,
484 GstEbmlRead * ebml, GstMatroskaTrackVideoContext * video_context)
486 GstFlowReturn ret = GST_FLOW_OK;
487 GstVideoMasteringDisplayInfo minfo;
490 /* Precision defined by HEVC specification */
491 const guint chroma_scale = 50000;
492 const guint luma_scale = 10000;
494 gst_video_mastering_display_info_init (&minfo);
496 DEBUG_ELEMENT_START (demux, ebml, "MasteringMetadata");
498 if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK)
501 while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
502 if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
505 /* all sub elements have float type */
506 if ((ret = gst_ebml_read_float (ebml, &id, &num)) != GST_FLOW_OK)
509 /* chromaticity should be in [0, 1] range */
510 if (id >= GST_MATROSKA_ID_PRIMARYRCHROMATICITYX &&
511 id <= GST_MATROSKA_ID_WHITEPOINTCHROMATICITYY) {
512 if (num < 0 || num > 1.0) {
513 GST_WARNING_OBJECT (demux, "0x%x has invalid value %f", id, num);
516 } else if (id == GST_MATROSKA_ID_LUMINANCEMAX ||
517 id == GST_MATROSKA_ID_LUMINANCEMIN) {
518 /* Note: webM spec said valid range is [0, 999.9999] but
519 * 1000 cd/m^2 is generally used value on HDR. Just check guint range here.
520 * See https://www.webmproject.org/docs/container/#LuminanceMax
522 if (num < 0 || num > (gdouble) (G_MAXUINT32 / luma_scale)) {
523 GST_WARNING_OBJECT (demux, "0x%x has invalid value %f", id, num);
529 case GST_MATROSKA_ID_PRIMARYRCHROMATICITYX:
530 minfo.display_primaries[0].x = (guint16) (num * chroma_scale);
532 case GST_MATROSKA_ID_PRIMARYRCHROMATICITYY:
533 minfo.display_primaries[0].y = (guint16) (num * chroma_scale);
535 case GST_MATROSKA_ID_PRIMARYGCHROMATICITYX:
536 minfo.display_primaries[1].x = (guint16) (num * chroma_scale);
538 case GST_MATROSKA_ID_PRIMARYGCHROMATICITYY:
539 minfo.display_primaries[1].y = (guint16) (num * chroma_scale);
541 case GST_MATROSKA_ID_PRIMARYBCHROMATICITYX:
542 minfo.display_primaries[2].x = (guint16) (num * chroma_scale);
544 case GST_MATROSKA_ID_PRIMARYBCHROMATICITYY:
545 minfo.display_primaries[2].y = (guint16) (num * chroma_scale);
547 case GST_MATROSKA_ID_WHITEPOINTCHROMATICITYX:
548 minfo.white_point.x = (guint16) (num * chroma_scale);
550 case GST_MATROSKA_ID_WHITEPOINTCHROMATICITYY:
551 minfo.white_point.y = (guint16) (num * chroma_scale);
553 case GST_MATROSKA_ID_LUMINANCEMAX:
554 minfo.max_display_mastering_luminance = (guint32) (num * luma_scale);
556 case GST_MATROSKA_ID_LUMINANCEMIN:
557 minfo.min_display_mastering_luminance = (guint32) (num * luma_scale);
560 GST_FIXME_OBJECT (demux,
561 "Unsupported subelement 0x%x in MasteringMetadata", id);
562 ret = gst_ebml_read_skip (ebml);
567 video_context->mastering_display_info = minfo;
568 video_context->mastering_display_info_present = TRUE;
571 DEBUG_ELEMENT_STOP (demux, ebml, "MasteringMetadata", ret);
577 gst_matroska_demux_parse_colour (GstMatroskaDemux * demux, GstEbmlRead * ebml,
578 GstMatroskaTrackVideoContext * video_context)
581 GstVideoColorimetry colorimetry;
585 colorimetry.range = GST_VIDEO_COLOR_RANGE_UNKNOWN;
586 colorimetry.matrix = GST_VIDEO_COLOR_MATRIX_UNKNOWN;
587 colorimetry.transfer = GST_VIDEO_TRANSFER_UNKNOWN;
588 colorimetry.primaries = GST_VIDEO_COLOR_PRIMARIES_UNKNOWN;
590 DEBUG_ELEMENT_START (demux, ebml, "TrackVideoColour");
592 if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK)
595 while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
596 if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
600 case GST_MATROSKA_ID_VIDEOMATRIXCOEFFICIENTS:{
601 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
604 colorimetry.matrix = gst_video_color_matrix_from_iso ((guint) num);
608 case GST_MATROSKA_ID_VIDEORANGE:{
609 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
614 colorimetry.range = GST_VIDEO_COLOR_RANGE_UNKNOWN;
617 colorimetry.range = GST_VIDEO_COLOR_RANGE_16_235;
620 colorimetry.range = GST_VIDEO_COLOR_RANGE_0_255;
623 GST_FIXME_OBJECT (demux, "Unsupported color range %"
624 G_GUINT64_FORMAT, num);
630 case GST_MATROSKA_ID_VIDEOTRANSFERCHARACTERISTICS:{
631 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
634 colorimetry.transfer =
635 gst_video_transfer_function_from_iso ((guint) num);
639 case GST_MATROSKA_ID_VIDEOPRIMARIES:{
640 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
643 colorimetry.primaries =
644 gst_video_color_primaries_from_iso ((guint) num);
648 case GST_MATROSKA_ID_MASTERINGMETADATA:{
650 gst_matroska_demux_parse_mastering_metadata (demux, ebml,
651 video_context)) != GST_FLOW_OK)
656 case GST_MATROSKA_ID_MAXCLL:{
657 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
659 if (num > G_MAXUINT16) {
660 GST_WARNING_OBJECT (demux,
661 "Too large maxCLL value %" G_GUINT64_FORMAT, num);
663 video_context->content_light_level.max_content_light_level = num;
668 case GST_MATROSKA_ID_MAXFALL:{
669 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
671 if (num >= G_MAXUINT16) {
672 GST_WARNING_OBJECT (demux,
673 "Too large maxFALL value %" G_GUINT64_FORMAT, num);
675 video_context->content_light_level.max_frame_average_light_level =
682 GST_FIXME_OBJECT (demux, "Unsupported subelement 0x%x in Colour", id);
683 ret = gst_ebml_read_skip (ebml);
688 memcpy (&video_context->colorimetry, &colorimetry,
689 sizeof (GstVideoColorimetry));
692 DEBUG_ELEMENT_STOP (demux, ebml, "TrackVideoColour", ret);
697 gst_matroska_demux_parse_stream (GstMatroskaDemux * demux, GstEbmlRead * ebml,
698 GstMatroskaTrackContext ** dest_context)
700 GstMatroskaTrackContext *context;
701 GstCaps *caps = NULL;
702 GstTagList *cached_taglist;
704 guint32 id, riff_fourcc = 0;
705 guint16 riff_audio_fmt = 0;
708 DEBUG_ELEMENT_START (demux, ebml, "TrackEntry");
710 *dest_context = NULL;
712 /* start with the master */
713 if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
714 DEBUG_ELEMENT_STOP (demux, ebml, "TrackEntry", ret);
718 /* allocate generic... if we know the type, we'll g_renew()
719 * with the precise type */
720 context = g_new0 (GstMatroskaTrackContext, 1);
721 context->index_writer_id = -1;
722 context->type = 0; /* no type yet */
723 context->default_duration = 0;
725 context->set_discont = TRUE;
726 context->timecodescale = 1.0;
728 GST_MATROSKA_TRACK_ENABLED | GST_MATROSKA_TRACK_DEFAULT |
729 GST_MATROSKA_TRACK_LACING;
730 context->from_time = GST_CLOCK_TIME_NONE;
731 context->from_offset = -1;
732 context->to_offset = G_MAXINT64;
733 context->alignment = 1;
734 context->dts_only = FALSE;
735 context->intra_only = FALSE;
736 context->tags = gst_tag_list_new_empty ();
737 g_queue_init (&context->protection_event_queue);
738 context->protection_info = NULL;
740 GST_DEBUG_OBJECT (demux, "Parsing a TrackEntry (%d tracks parsed so far)",
741 demux->common.num_streams);
743 /* try reading the trackentry headers */
744 while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
745 if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
749 /* track number (unique stream ID) */
750 case GST_MATROSKA_ID_TRACKNUMBER:{
753 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
757 GST_ERROR_OBJECT (demux, "Invalid TrackNumber 0");
758 ret = GST_FLOW_ERROR;
762 GST_DEBUG_OBJECT (demux, "TrackNumber: %" G_GUINT64_FORMAT, num);
766 /* track UID (unique identifier) */
767 case GST_MATROSKA_ID_TRACKUID:{
770 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
774 GST_ERROR_OBJECT (demux, "Invalid TrackUID 0");
775 ret = GST_FLOW_ERROR;
779 GST_DEBUG_OBJECT (demux, "TrackUID: %" G_GUINT64_FORMAT, num);
784 /* track type (video, audio, combined, subtitle, etc.) */
785 case GST_MATROSKA_ID_TRACKTYPE:{
788 if ((ret = gst_ebml_read_uint (ebml, &id, &track_type)) != GST_FLOW_OK) {
792 if (context->type != 0 && context->type != track_type) {
793 GST_WARNING_OBJECT (demux,
794 "More than one tracktype defined in a TrackEntry - skipping");
796 } else if (track_type < 1 || track_type > 254) {
797 GST_WARNING_OBJECT (demux, "Invalid TrackType %" G_GUINT64_FORMAT,
802 GST_DEBUG_OBJECT (demux, "TrackType: %" G_GUINT64_FORMAT, track_type);
804 /* ok, so we're actually going to reallocate this thing */
805 switch (track_type) {
806 case GST_MATROSKA_TRACK_TYPE_VIDEO:
807 gst_matroska_track_init_video_context (&context);
809 case GST_MATROSKA_TRACK_TYPE_AUDIO:
810 gst_matroska_track_init_audio_context (&context);
812 case GST_MATROSKA_TRACK_TYPE_SUBTITLE:
813 gst_matroska_track_init_subtitle_context (&context);
815 case GST_MATROSKA_TRACK_TYPE_COMPLEX:
816 case GST_MATROSKA_TRACK_TYPE_LOGO:
817 case GST_MATROSKA_TRACK_TYPE_BUTTONS:
818 case GST_MATROSKA_TRACK_TYPE_CONTROL:
820 GST_WARNING_OBJECT (demux,
821 "Unknown or unsupported TrackType %" G_GUINT64_FORMAT,
829 /* tracktype specific stuff for video */
830 case GST_MATROSKA_ID_TRACKVIDEO:{
831 GstMatroskaTrackVideoContext *videocontext;
833 DEBUG_ELEMENT_START (demux, ebml, "TrackVideo");
835 if (!gst_matroska_track_init_video_context (&context)) {
836 GST_WARNING_OBJECT (demux,
837 "TrackVideo element in non-video track - ignoring track");
838 ret = GST_FLOW_ERROR;
840 } else if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
843 videocontext = (GstMatroskaTrackVideoContext *) context;
845 while (ret == GST_FLOW_OK &&
846 gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
847 if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
851 /* Should be one level up but some broken muxers write it here. */
852 case GST_MATROSKA_ID_TRACKDEFAULTDURATION:{
855 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
859 GST_WARNING_OBJECT (demux, "Invalid TrackDefaultDuration 0");
863 GST_DEBUG_OBJECT (demux,
864 "TrackDefaultDuration: %" G_GUINT64_FORMAT, num);
865 context->default_duration = num;
869 /* video framerate */
870 /* NOTE: This one is here only for backward compatibility.
871 * Use _TRACKDEFAULDURATION one level up. */
872 case GST_MATROSKA_ID_VIDEOFRAMERATE:{
875 if ((ret = gst_ebml_read_float (ebml, &id, &num)) != GST_FLOW_OK)
879 GST_WARNING_OBJECT (demux, "Invalid TrackVideoFPS %lf", num);
883 GST_DEBUG_OBJECT (demux, "TrackVideoFrameRate: %lf", num);
884 if (context->default_duration == 0)
885 context->default_duration =
886 gst_gdouble_to_guint64 ((gdouble) GST_SECOND * (1.0 / num));
887 videocontext->default_fps = num;
891 /* width of the size to display the video at */
892 case GST_MATROSKA_ID_VIDEODISPLAYWIDTH:{
895 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
899 GST_WARNING_OBJECT (demux, "Invalid TrackVideoDisplayWidth 0");
903 GST_DEBUG_OBJECT (demux,
904 "TrackVideoDisplayWidth: %" G_GUINT64_FORMAT, num);
905 videocontext->display_width = num;
909 /* height of the size to display the video at */
910 case GST_MATROSKA_ID_VIDEODISPLAYHEIGHT:{
913 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
917 GST_WARNING_OBJECT (demux, "Invalid TrackVideoDisplayHeight 0");
921 GST_DEBUG_OBJECT (demux,
922 "TrackVideoDisplayHeight: %" G_GUINT64_FORMAT, num);
923 videocontext->display_height = num;
927 /* width of the video in the file */
928 case GST_MATROSKA_ID_VIDEOPIXELWIDTH:{
931 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
935 GST_WARNING_OBJECT (demux, "Invalid TrackVideoPixelWidth 0");
939 GST_DEBUG_OBJECT (demux,
940 "TrackVideoPixelWidth: %" G_GUINT64_FORMAT, num);
941 videocontext->pixel_width = num;
945 /* height of the video in the file */
946 case GST_MATROSKA_ID_VIDEOPIXELHEIGHT:{
949 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
953 GST_WARNING_OBJECT (demux, "Invalid TrackVideoPixelHeight 0");
957 GST_DEBUG_OBJECT (demux,
958 "TrackVideoPixelHeight: %" G_GUINT64_FORMAT, num);
959 videocontext->pixel_height = num;
963 /* whether the video is interlaced */
964 case GST_MATROSKA_ID_VIDEOFLAGINTERLACED:{
967 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
971 videocontext->interlace_mode =
972 GST_MATROSKA_INTERLACE_MODE_INTERLACED;
974 videocontext->interlace_mode =
975 GST_MATROSKA_INTERLACE_MODE_PROGRESSIVE;
977 videocontext->interlace_mode =
978 GST_MATROSKA_INTERLACE_MODE_UNKNOWN;
980 GST_DEBUG_OBJECT (demux, "video track interlacing mode: %d",
981 videocontext->interlace_mode);
985 /* interlaced field order */
986 case GST_MATROSKA_ID_VIDEOFIELDORDER:{
989 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
992 if (videocontext->interlace_mode !=
993 GST_MATROSKA_INTERLACE_MODE_INTERLACED) {
994 GST_WARNING_OBJECT (demux,
995 "FieldOrder element when not interlaced - ignoring");
1000 /* turns out we're actually progressive */
1001 videocontext->interlace_mode =
1002 GST_MATROSKA_INTERLACE_MODE_PROGRESSIVE;
1004 videocontext->field_order = GST_VIDEO_FIELD_ORDER_UNKNOWN;
1006 videocontext->field_order =
1007 GST_VIDEO_FIELD_ORDER_TOP_FIELD_FIRST;
1009 videocontext->field_order =
1010 GST_VIDEO_FIELD_ORDER_BOTTOM_FIELD_FIRST;
1012 GST_FIXME_OBJECT (demux,
1013 "Unknown or unsupported FieldOrder %" G_GUINT64_FORMAT,
1015 videocontext->field_order = GST_VIDEO_FIELD_ORDER_UNKNOWN;
1018 GST_DEBUG_OBJECT (demux, "video track field order: %d",
1019 videocontext->field_order);
1023 /* aspect ratio behaviour */
1024 case GST_MATROSKA_ID_VIDEOASPECTRATIOTYPE:{
1027 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1030 if (num != GST_MATROSKA_ASPECT_RATIO_MODE_FREE &&
1031 num != GST_MATROSKA_ASPECT_RATIO_MODE_KEEP &&
1032 num != GST_MATROSKA_ASPECT_RATIO_MODE_FIXED) {
1033 GST_WARNING_OBJECT (demux,
1034 "Unknown TrackVideoAspectRatioType 0x%x", (guint) num);
1037 GST_DEBUG_OBJECT (demux,
1038 "TrackVideoAspectRatioType: %" G_GUINT64_FORMAT, num);
1039 videocontext->asr_mode = num;
1043 /* colourspace (only matters for raw video) fourcc */
1044 case GST_MATROSKA_ID_VIDEOCOLOURSPACE:{
1049 gst_ebml_read_binary (ebml, &id, &data,
1050 &datalen)) != GST_FLOW_OK)
1055 GST_WARNING_OBJECT (demux,
1056 "Invalid TrackVideoColourSpace length %" G_GUINT64_FORMAT,
1061 memcpy (&videocontext->fourcc, data, 4);
1062 GST_DEBUG_OBJECT (demux,
1063 "TrackVideoColourSpace: %" GST_FOURCC_FORMAT,
1064 GST_FOURCC_ARGS (videocontext->fourcc));
1070 case GST_MATROSKA_ID_VIDEOCOLOUR:{
1071 ret = gst_matroska_demux_parse_colour (demux, ebml, videocontext);
1075 case GST_MATROSKA_ID_VIDEOSTEREOMODE:
1079 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1082 GST_DEBUG_OBJECT (demux, "StereoMode: %" G_GUINT64_FORMAT, num);
1085 case GST_MATROSKA_STEREO_MODE_SBS_RL:
1086 videocontext->multiview_flags =
1087 GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST;
1089 case GST_MATROSKA_STEREO_MODE_SBS_LR:
1090 videocontext->multiview_mode =
1091 GST_VIDEO_MULTIVIEW_MODE_SIDE_BY_SIDE;
1093 case GST_MATROSKA_STEREO_MODE_TB_RL:
1094 videocontext->multiview_flags =
1095 GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST;
1097 case GST_MATROSKA_STEREO_MODE_TB_LR:
1098 videocontext->multiview_mode =
1099 GST_VIDEO_MULTIVIEW_MODE_TOP_BOTTOM;
1101 case GST_MATROSKA_STEREO_MODE_CHECKER_RL:
1102 videocontext->multiview_flags =
1103 GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST;
1105 case GST_MATROSKA_STEREO_MODE_CHECKER_LR:
1106 videocontext->multiview_mode =
1107 GST_VIDEO_MULTIVIEW_MODE_CHECKERBOARD;
1109 case GST_MATROSKA_STEREO_MODE_FBF_RL:
1110 videocontext->multiview_flags =
1111 GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST;
1113 case GST_MATROSKA_STEREO_MODE_FBF_LR:
1114 videocontext->multiview_mode =
1115 GST_VIDEO_MULTIVIEW_MODE_FRAME_BY_FRAME;
1116 /* FIXME: In frame-by-frame mode, left/right frame buffers are
1117 * laced within one block, and we'll need to apply FIRST_IN_BUNDLE
1118 * accordingly. See http://www.matroska.org/technical/specs/index.html#StereoMode */
1119 GST_FIXME_OBJECT (demux,
1120 "Frame-by-frame stereoscopic mode not fully implemented");
1126 case GST_MATROSKA_ID_VIDEOALPHAMODE:
1130 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1133 GST_DEBUG_OBJECT (demux, "AlphaMode: %" G_GUINT64_FORMAT, num);
1136 videocontext->alpha_mode = TRUE;
1138 videocontext->alpha_mode = FALSE;
1143 GST_WARNING_OBJECT (demux,
1144 "Unknown TrackVideo subelement 0x%x - ignoring", id);
1146 case GST_MATROSKA_ID_VIDEODISPLAYUNIT:
1147 case GST_MATROSKA_ID_VIDEOPIXELCROPBOTTOM:
1148 case GST_MATROSKA_ID_VIDEOPIXELCROPTOP:
1149 case GST_MATROSKA_ID_VIDEOPIXELCROPLEFT:
1150 case GST_MATROSKA_ID_VIDEOPIXELCROPRIGHT:
1151 case GST_MATROSKA_ID_VIDEOGAMMAVALUE:
1152 ret = gst_ebml_read_skip (ebml);
1157 DEBUG_ELEMENT_STOP (demux, ebml, "TrackVideo", ret);
1161 /* tracktype specific stuff for audio */
1162 case GST_MATROSKA_ID_TRACKAUDIO:{
1163 GstMatroskaTrackAudioContext *audiocontext;
1165 DEBUG_ELEMENT_START (demux, ebml, "TrackAudio");
1167 if (!gst_matroska_track_init_audio_context (&context)) {
1168 GST_WARNING_OBJECT (demux,
1169 "TrackAudio element in non-audio track - ignoring track");
1170 ret = GST_FLOW_ERROR;
1174 if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK)
1177 audiocontext = (GstMatroskaTrackAudioContext *) context;
1179 while (ret == GST_FLOW_OK &&
1180 gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
1181 if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
1186 case GST_MATROSKA_ID_AUDIOSAMPLINGFREQ:{
1189 if ((ret = gst_ebml_read_float (ebml, &id, &num)) != GST_FLOW_OK)
1194 GST_WARNING_OBJECT (demux,
1195 "Invalid TrackAudioSamplingFrequency %lf", num);
1199 GST_DEBUG_OBJECT (demux, "TrackAudioSamplingFrequency: %lf", num);
1200 audiocontext->samplerate = num;
1205 case GST_MATROSKA_ID_AUDIOBITDEPTH:{
1208 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1212 GST_WARNING_OBJECT (demux, "Invalid TrackAudioBitDepth 0");
1216 GST_DEBUG_OBJECT (demux, "TrackAudioBitDepth: %" G_GUINT64_FORMAT,
1218 audiocontext->bitdepth = num;
1223 case GST_MATROSKA_ID_AUDIOCHANNELS:{
1226 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1230 GST_WARNING_OBJECT (demux, "Invalid TrackAudioChannels 0");
1234 GST_DEBUG_OBJECT (demux, "TrackAudioChannels: %" G_GUINT64_FORMAT,
1236 audiocontext->channels = num;
1241 GST_WARNING_OBJECT (demux,
1242 "Unknown TrackAudio subelement 0x%x - ignoring", id);
1244 case GST_MATROSKA_ID_AUDIOCHANNELPOSITIONS:
1245 case GST_MATROSKA_ID_AUDIOOUTPUTSAMPLINGFREQ:
1246 ret = gst_ebml_read_skip (ebml);
1251 DEBUG_ELEMENT_STOP (demux, ebml, "TrackAudio", ret);
1256 /* codec identifier */
1257 case GST_MATROSKA_ID_CODECID:{
1260 if ((ret = gst_ebml_read_ascii (ebml, &id, &text)) != GST_FLOW_OK)
1263 GST_DEBUG_OBJECT (demux, "CodecID: %s", GST_STR_NULL (text));
1264 context->codec_id = text;
1268 /* codec private data */
1269 case GST_MATROSKA_ID_CODECPRIVATE:{
1274 gst_ebml_read_binary (ebml, &id, &data, &size)) != GST_FLOW_OK)
1277 context->codec_priv = data;
1278 context->codec_priv_size = size;
1280 GST_DEBUG_OBJECT (demux, "CodecPrivate of size %" G_GUINT64_FORMAT,
1285 /* name of the codec */
1286 case GST_MATROSKA_ID_CODECNAME:{
1289 if ((ret = gst_ebml_read_utf8 (ebml, &id, &text)) != GST_FLOW_OK)
1292 GST_DEBUG_OBJECT (demux, "CodecName: %s", GST_STR_NULL (text));
1293 context->codec_name = text;
1298 case GST_MATROSKA_ID_CODECDELAY:{
1301 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1304 context->codec_delay = num;
1306 GST_DEBUG_OBJECT (demux, "CodecDelay: %" GST_TIME_FORMAT,
1307 GST_TIME_ARGS (num));
1312 case GST_MATROSKA_ID_SEEKPREROLL:{
1315 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1318 context->seek_preroll = num;
1320 GST_DEBUG_OBJECT (demux, "SeekPreroll: %" GST_TIME_FORMAT,
1321 GST_TIME_ARGS (num));
1325 /* name of this track */
1326 case GST_MATROSKA_ID_TRACKNAME:{
1329 if ((ret = gst_ebml_read_utf8 (ebml, &id, &text)) != GST_FLOW_OK)
1332 context->name = text;
1333 GST_DEBUG_OBJECT (demux, "TrackName: %s", GST_STR_NULL (text));
1337 /* language (matters for audio/subtitles, mostly) */
1338 case GST_MATROSKA_ID_TRACKLANGUAGE:{
1341 if ((ret = gst_ebml_read_utf8 (ebml, &id, &text)) != GST_FLOW_OK)
1345 context->language = text;
1348 if (strlen (context->language) >= 4 && context->language[3] == '-')
1349 context->language[3] = '\0';
1351 GST_DEBUG_OBJECT (demux, "TrackLanguage: %s",
1352 GST_STR_NULL (context->language));
1356 /* whether this is actually used */
1357 case GST_MATROSKA_ID_TRACKFLAGENABLED:{
1360 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1364 context->flags |= GST_MATROSKA_TRACK_ENABLED;
1366 context->flags &= ~GST_MATROSKA_TRACK_ENABLED;
1368 GST_DEBUG_OBJECT (demux, "TrackEnabled: %d",
1369 (context->flags & GST_MATROSKA_TRACK_ENABLED) ? 1 : 0);
1373 /* whether it's the default for this track type */
1374 case GST_MATROSKA_ID_TRACKFLAGDEFAULT:{
1377 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1381 context->flags |= GST_MATROSKA_TRACK_DEFAULT;
1383 context->flags &= ~GST_MATROSKA_TRACK_DEFAULT;
1385 GST_DEBUG_OBJECT (demux, "TrackDefault: %d",
1386 (context->flags & GST_MATROSKA_TRACK_DEFAULT) ? 1 : 0);
1390 /* whether the track must be used during playback */
1391 case GST_MATROSKA_ID_TRACKFLAGFORCED:{
1394 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1398 context->flags |= GST_MATROSKA_TRACK_FORCED;
1400 context->flags &= ~GST_MATROSKA_TRACK_FORCED;
1402 GST_DEBUG_OBJECT (demux, "TrackForced: %d",
1403 (context->flags & GST_MATROSKA_TRACK_FORCED) ? 1 : 0);
1407 /* lacing (like MPEG, where blocks don't end/start on frame
1409 case GST_MATROSKA_ID_TRACKFLAGLACING:{
1412 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1416 context->flags |= GST_MATROSKA_TRACK_LACING;
1418 context->flags &= ~GST_MATROSKA_TRACK_LACING;
1420 GST_DEBUG_OBJECT (demux, "TrackLacing: %d",
1421 (context->flags & GST_MATROSKA_TRACK_LACING) ? 1 : 0);
1425 /* default length (in time) of one data block in this track */
1426 case GST_MATROSKA_ID_TRACKDEFAULTDURATION:{
1429 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1434 GST_WARNING_OBJECT (demux, "Invalid TrackDefaultDuration 0");
1438 GST_DEBUG_OBJECT (demux, "TrackDefaultDuration: %" G_GUINT64_FORMAT,
1440 context->default_duration = num;
1444 case GST_MATROSKA_ID_CONTENTENCODINGS:{
1445 ret = gst_matroska_read_common_read_track_encodings (&demux->common,
1450 case GST_MATROSKA_ID_TRACKTIMECODESCALE:{
1453 if ((ret = gst_ebml_read_float (ebml, &id, &num)) != GST_FLOW_OK)
1457 GST_WARNING_OBJECT (demux, "Invalid TrackTimeCodeScale %lf", num);
1461 GST_DEBUG_OBJECT (demux, "TrackTimeCodeScale: %lf", num);
1462 context->timecodescale = num;
1467 GST_WARNING ("Unknown TrackEntry subelement 0x%x - ignoring", id);
1470 /* we ignore these because they're nothing useful (i.e. crap)
1471 * or simply not implemented yet. */
1472 case GST_MATROSKA_ID_TRACKMINCACHE:
1473 case GST_MATROSKA_ID_TRACKMAXCACHE:
1474 case GST_MATROSKA_ID_MAXBLOCKADDITIONID:
1475 case GST_MATROSKA_ID_TRACKATTACHMENTLINK:
1476 case GST_MATROSKA_ID_TRACKOVERLAY:
1477 case GST_MATROSKA_ID_TRACKTRANSLATE:
1478 case GST_MATROSKA_ID_TRACKOFFSET:
1479 case GST_MATROSKA_ID_CODECSETTINGS:
1480 case GST_MATROSKA_ID_CODECINFOURL:
1481 case GST_MATROSKA_ID_CODECDOWNLOADURL:
1482 case GST_MATROSKA_ID_CODECDECODEALL:
1483 ret = gst_ebml_read_skip (ebml);
1488 DEBUG_ELEMENT_STOP (demux, ebml, "TrackEntry", ret);
1490 /* Decode codec private data if necessary */
1491 if (context->encodings && context->encodings->len > 0 && context->codec_priv
1492 && context->codec_priv_size > 0) {
1493 if (!gst_matroska_decode_data (context->encodings,
1494 &context->codec_priv, &context->codec_priv_size,
1495 GST_MATROSKA_TRACK_ENCODING_SCOPE_CODEC_DATA, TRUE)) {
1496 GST_WARNING_OBJECT (demux, "Decoding codec private data failed");
1497 ret = GST_FLOW_ERROR;
1501 if (context->type == 0 || context->codec_id == NULL || (ret != GST_FLOW_OK
1502 && ret != GST_FLOW_EOS)) {
1503 if (ret == GST_FLOW_OK || ret == GST_FLOW_EOS)
1504 GST_WARNING_OBJECT (ebml, "Unknown stream/codec in track entry header");
1506 gst_matroska_track_free (context);
1508 *dest_context = NULL;
1512 /* check for a cached track taglist */
1514 (GstTagList *) g_hash_table_lookup (demux->common.cached_track_taglists,
1515 GUINT_TO_POINTER (context->uid));
1517 gst_tag_list_insert (context->tags, cached_taglist, GST_TAG_MERGE_APPEND);
1520 switch (context->type) {
1521 case GST_MATROSKA_TRACK_TYPE_VIDEO:{
1522 GstMatroskaTrackVideoContext *videocontext =
1523 (GstMatroskaTrackVideoContext *) context;
1525 caps = gst_matroska_demux_video_caps (videocontext,
1526 context->codec_id, context->codec_priv,
1527 context->codec_priv_size, &codec, &riff_fourcc);
1530 gst_tag_list_add (context->tags, GST_TAG_MERGE_REPLACE,
1531 GST_TAG_VIDEO_CODEC, codec, NULL);
1532 context->tags_changed = TRUE;
1538 case GST_MATROSKA_TRACK_TYPE_AUDIO:{
1539 GstClockTime lead_in_ts = 0;
1540 GstMatroskaTrackAudioContext *audiocontext =
1541 (GstMatroskaTrackAudioContext *) context;
1543 caps = gst_matroska_demux_audio_caps (audiocontext,
1544 context->codec_id, context->codec_priv, context->codec_priv_size,
1545 &codec, &riff_audio_fmt, &lead_in_ts);
1546 if (lead_in_ts > demux->audio_lead_in_ts) {
1547 demux->audio_lead_in_ts = lead_in_ts;
1548 GST_DEBUG_OBJECT (demux, "Increased audio lead-in to %" GST_TIME_FORMAT,
1549 GST_TIME_ARGS (lead_in_ts));
1553 gst_tag_list_add (context->tags, GST_TAG_MERGE_REPLACE,
1554 GST_TAG_AUDIO_CODEC, codec, NULL);
1555 context->tags_changed = TRUE;
1561 case GST_MATROSKA_TRACK_TYPE_SUBTITLE:{
1562 GstMatroskaTrackSubtitleContext *subtitlecontext =
1563 (GstMatroskaTrackSubtitleContext *) context;
1565 caps = gst_matroska_demux_subtitle_caps (subtitlecontext,
1566 context->codec_id, context->codec_priv, context->codec_priv_size);
1570 case GST_MATROSKA_TRACK_TYPE_COMPLEX:
1571 case GST_MATROSKA_TRACK_TYPE_LOGO:
1572 case GST_MATROSKA_TRACK_TYPE_BUTTONS:
1573 case GST_MATROSKA_TRACK_TYPE_CONTROL:
1575 /* we should already have quit by now */
1576 g_assert_not_reached ();
1579 if ((context->language == NULL || *context->language == '\0') &&
1580 (context->type == GST_MATROSKA_TRACK_TYPE_AUDIO ||
1581 context->type == GST_MATROSKA_TRACK_TYPE_SUBTITLE)) {
1582 GST_LOG ("stream %d: language=eng (assuming default)", context->index);
1583 context->language = g_strdup ("eng");
1586 if (context->language) {
1589 /* Matroska contains ISO 639-2B codes, we want ISO 639-1 */
1590 lang = gst_tag_get_language_code (context->language);
1591 gst_tag_list_add (context->tags, GST_TAG_MERGE_REPLACE,
1592 GST_TAG_LANGUAGE_CODE, (lang) ? lang : context->language, NULL);
1594 if (context->name) {
1595 gst_tag_list_add (context->tags, GST_TAG_MERGE_REPLACE,
1596 GST_TAG_TITLE, context->name, NULL);
1598 context->tags_changed = TRUE;
1602 GST_WARNING_OBJECT (demux, "could not determine caps for stream with "
1603 "codec_id='%s'", context->codec_id);
1604 switch (context->type) {
1605 case GST_MATROSKA_TRACK_TYPE_VIDEO:
1606 caps = gst_caps_new_empty_simple ("video/x-unknown");
1608 case GST_MATROSKA_TRACK_TYPE_AUDIO:
1609 caps = gst_caps_new_empty_simple ("audio/x-unknown");
1611 case GST_MATROSKA_TRACK_TYPE_SUBTITLE:
1612 caps = gst_caps_new_empty_simple ("application/x-subtitle-unknown");
1614 case GST_MATROSKA_TRACK_TYPE_COMPLEX:
1616 caps = gst_caps_new_empty_simple ("application/x-matroska-unknown");
1619 gst_caps_set_simple (caps, "codec-id", G_TYPE_STRING, context->codec_id,
1622 /* add any unrecognised riff fourcc / audio format, but after codec-id */
1623 if (context->type == GST_MATROSKA_TRACK_TYPE_AUDIO && riff_audio_fmt != 0)
1624 gst_caps_set_simple (caps, "format", G_TYPE_INT, riff_audio_fmt, NULL);
1625 else if (context->type == GST_MATROSKA_TRACK_TYPE_VIDEO && riff_fourcc != 0) {
1626 gchar *fstr = g_strdup_printf ("%" GST_FOURCC_FORMAT,
1627 GST_FOURCC_ARGS (riff_fourcc));
1628 gst_caps_set_simple (caps, "fourcc", G_TYPE_STRING, fstr, NULL);
1631 } else if (context->stream_headers != NULL) {
1632 gst_matroska_demux_add_stream_headers_to_caps (demux,
1633 context->stream_headers, caps);
1636 if (context->encodings) {
1637 GstMatroskaTrackEncoding *enc;
1640 for (i = 0; i < context->encodings->len; i++) {
1641 enc = &g_array_index (context->encodings, GstMatroskaTrackEncoding, i);
1642 if (enc->type == GST_MATROSKA_ENCODING_ENCRYPTION /* encryption */ ) {
1643 GstStructure *s = gst_caps_get_structure (caps, 0);
1644 if (!gst_structure_has_name (s, "application/x-webm-enc")) {
1645 gst_structure_set (s, "original-media-type", G_TYPE_STRING,
1646 gst_structure_get_name (s), NULL);
1647 gst_structure_set (s, "encryption-algorithm", G_TYPE_STRING,
1648 gst_matroska_track_encryption_algorithm_name (enc->enc_algo),
1650 gst_structure_set (s, "encoding-scope", G_TYPE_STRING,
1651 gst_matroska_track_encoding_scope_name (enc->scope), NULL);
1652 gst_structure_set (s, "cipher-mode", G_TYPE_STRING,
1653 gst_matroska_track_encryption_cipher_mode_name
1654 (enc->enc_cipher_mode), NULL);
1655 gst_structure_set_name (s, "application/x-webm-enc");
1661 context->caps = caps;
1664 *dest_context = context;
1669 gst_matroska_demux_add_stream (GstMatroskaDemux * demux,
1670 GstMatroskaTrackContext * context)
1672 GstElementClass *klass = GST_ELEMENT_GET_CLASS (demux);
1673 gchar *padname = NULL;
1674 GstPadTemplate *templ = NULL;
1675 GstStreamFlags stream_flags;
1677 GstEvent *stream_start;
1681 g_ptr_array_add (demux->common.src, context);
1682 context->index = demux->common.num_streams++;
1683 g_assert (demux->common.src->len == demux->common.num_streams);
1684 g_ptr_array_index (demux->common.src, demux->common.num_streams - 1) =
1687 /* now create the GStreamer connectivity */
1688 switch (context->type) {
1689 case GST_MATROSKA_TRACK_TYPE_VIDEO:
1690 padname = g_strdup_printf ("video_%u", demux->num_v_streams++);
1691 templ = gst_element_class_get_pad_template (klass, "video_%u");
1693 if (!context->intra_only)
1694 demux->have_nonintraonly_v_streams = TRUE;
1697 case GST_MATROSKA_TRACK_TYPE_AUDIO:
1698 padname = g_strdup_printf ("audio_%u", demux->num_a_streams++);
1699 templ = gst_element_class_get_pad_template (klass, "audio_%u");
1702 case GST_MATROSKA_TRACK_TYPE_SUBTITLE:
1703 padname = g_strdup_printf ("subtitle_%u", demux->num_t_streams++);
1704 templ = gst_element_class_get_pad_template (klass, "subtitle_%u");
1708 /* we should already have quit by now */
1709 g_assert_not_reached ();
1712 /* the pad in here */
1713 context->pad = gst_pad_new_from_template (templ, padname);
1715 gst_pad_set_event_function (context->pad,
1716 GST_DEBUG_FUNCPTR (gst_matroska_demux_handle_src_event));
1717 gst_pad_set_query_function (context->pad,
1718 GST_DEBUG_FUNCPTR (gst_matroska_demux_handle_src_query));
1720 GST_INFO_OBJECT (demux, "Adding pad '%s' with caps %" GST_PTR_FORMAT,
1721 padname, context->caps);
1723 gst_pad_set_element_private (context->pad, context);
1725 gst_pad_use_fixed_caps (context->pad);
1726 gst_pad_set_active (context->pad, TRUE);
1729 gst_pad_create_stream_id_printf (context->pad, GST_ELEMENT_CAST (demux),
1730 "%03" G_GUINT64_FORMAT ":%03" G_GUINT64_FORMAT,
1731 context->num, context->uid);
1733 gst_pad_get_sticky_event (demux->common.sinkpad, GST_EVENT_STREAM_START,
1736 if (gst_event_parse_group_id (stream_start, &demux->group_id))
1737 demux->have_group_id = TRUE;
1739 demux->have_group_id = FALSE;
1740 gst_event_unref (stream_start);
1741 } else if (!demux->have_group_id) {
1742 demux->have_group_id = TRUE;
1743 demux->group_id = gst_util_group_id_next ();
1746 stream_start = gst_event_new_stream_start (stream_id);
1748 if (demux->have_group_id)
1749 gst_event_set_group_id (stream_start, demux->group_id);
1750 stream_flags = GST_STREAM_FLAG_NONE;
1751 if (context->type == GST_MATROSKA_TRACK_TYPE_SUBTITLE)
1752 stream_flags |= GST_STREAM_FLAG_SPARSE;
1753 if (context->flags & GST_MATROSKA_TRACK_DEFAULT)
1754 stream_flags |= GST_STREAM_FLAG_SELECT;
1755 else if (!(context->flags & GST_MATROSKA_TRACK_ENABLED))
1756 stream_flags |= GST_STREAM_FLAG_UNSELECT;
1758 gst_event_set_stream_flags (stream_start, stream_flags);
1759 gst_pad_push_event (context->pad, stream_start);
1760 gst_pad_set_caps (context->pad, context->caps);
1763 if (demux->common.global_tags) {
1764 GstEvent *tag_event;
1766 gst_tag_list_add (demux->common.global_tags, GST_TAG_MERGE_REPLACE,
1767 GST_TAG_CONTAINER_FORMAT, "Matroska", NULL);
1768 GST_DEBUG_OBJECT (context->pad, "Sending global_tags %p: %" GST_PTR_FORMAT,
1769 demux->common.global_tags, demux->common.global_tags);
1772 gst_event_new_tag (gst_tag_list_copy (demux->common.global_tags));
1774 gst_pad_push_event (context->pad, tag_event);
1777 if (G_UNLIKELY (context->tags_changed)) {
1778 GST_DEBUG_OBJECT (context->pad, "Sending tags %p: %"
1779 GST_PTR_FORMAT, context->tags, context->tags);
1780 gst_pad_push_event (context->pad,
1781 gst_event_new_tag (gst_tag_list_copy (context->tags)));
1782 context->tags_changed = FALSE;
1785 gst_element_add_pad (GST_ELEMENT (demux), context->pad);
1786 gst_flow_combiner_add_pad (demux->flowcombiner, context->pad);
1792 gst_matroska_demux_query (GstMatroskaDemux * demux, GstPad * pad,
1795 gboolean res = FALSE;
1796 GstMatroskaTrackContext *context = NULL;
1799 context = gst_pad_get_element_private (pad);
1802 switch (GST_QUERY_TYPE (query)) {
1803 case GST_QUERY_POSITION:
1807 gst_query_parse_position (query, &format, NULL);
1810 if (format == GST_FORMAT_TIME) {
1811 GST_OBJECT_LOCK (demux);
1813 gst_query_set_position (query, GST_FORMAT_TIME,
1814 MAX (context->pos, demux->stream_start_time) -
1815 demux->stream_start_time);
1817 gst_query_set_position (query, GST_FORMAT_TIME,
1818 MAX (demux->common.segment.position, demux->stream_start_time) -
1819 demux->stream_start_time);
1820 GST_OBJECT_UNLOCK (demux);
1821 } else if (format == GST_FORMAT_DEFAULT && context
1822 && context->default_duration) {
1823 GST_OBJECT_LOCK (demux);
1824 gst_query_set_position (query, GST_FORMAT_DEFAULT,
1825 context->pos / context->default_duration);
1826 GST_OBJECT_UNLOCK (demux);
1828 GST_DEBUG_OBJECT (demux,
1829 "only position query in TIME and DEFAULT format is supported");
1835 case GST_QUERY_DURATION:
1839 gst_query_parse_duration (query, &format, NULL);
1842 if (format == GST_FORMAT_TIME) {
1843 GST_OBJECT_LOCK (demux);
1844 gst_query_set_duration (query, GST_FORMAT_TIME,
1845 demux->common.segment.duration);
1846 GST_OBJECT_UNLOCK (demux);
1847 } else if (format == GST_FORMAT_DEFAULT && context
1848 && context->default_duration) {
1849 GST_OBJECT_LOCK (demux);
1850 gst_query_set_duration (query, GST_FORMAT_DEFAULT,
1851 demux->common.segment.duration / context->default_duration);
1852 GST_OBJECT_UNLOCK (demux);
1854 GST_DEBUG_OBJECT (demux,
1855 "only duration query in TIME and DEFAULT format is supported");
1861 case GST_QUERY_SEEKING:
1865 gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
1866 GST_OBJECT_LOCK (demux);
1867 if (fmt == GST_FORMAT_TIME) {
1870 if (demux->streaming) {
1871 /* assuming we'll be able to get an index ... */
1872 seekable = demux->seekable;
1877 gst_query_set_seeking (query, GST_FORMAT_TIME, seekable,
1878 0, demux->common.segment.duration);
1881 GST_OBJECT_UNLOCK (demux);
1884 case GST_QUERY_SEGMENT:
1889 format = demux->common.segment.format;
1892 gst_segment_to_stream_time (&demux->common.segment, format,
1893 demux->common.segment.start);
1894 if ((stop = demux->common.segment.stop) == -1)
1895 stop = demux->common.segment.duration;
1898 gst_segment_to_stream_time (&demux->common.segment, format, stop);
1900 gst_query_set_segment (query, demux->common.segment.rate, format, start,
1907 res = gst_pad_query_default (pad, (GstObject *) demux, query);
1910 GST_ELEMENT_CLASS (parent_class)->query (GST_ELEMENT_CAST (demux),
1919 gst_matroska_demux_element_query (GstElement * element, GstQuery * query)
1921 return gst_matroska_demux_query (GST_MATROSKA_DEMUX (element), NULL, query);
1925 gst_matroska_demux_handle_src_query (GstPad * pad, GstObject * parent,
1928 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (parent);
1930 return gst_matroska_demux_query (demux, pad, query);
1933 /* returns FALSE if there are no pads to deliver event to,
1934 * otherwise TRUE (whatever the outcome of event sending),
1935 * takes ownership of the passed event! */
1937 gst_matroska_demux_send_event (GstMatroskaDemux * demux, GstEvent * event)
1939 gboolean ret = FALSE;
1942 g_return_val_if_fail (event != NULL, FALSE);
1944 GST_DEBUG_OBJECT (demux, "Sending event of type %s to all source pads",
1945 GST_EVENT_TYPE_NAME (event));
1947 g_assert (demux->common.src->len == demux->common.num_streams);
1948 for (i = 0; i < demux->common.src->len; i++) {
1949 GstMatroskaTrackContext *stream;
1951 stream = g_ptr_array_index (demux->common.src, i);
1952 gst_event_ref (event);
1953 gst_pad_push_event (stream->pad, event);
1957 gst_event_unref (event);
1962 gst_matroska_demux_send_tags (GstMatroskaDemux * demux)
1966 if (G_UNLIKELY (demux->common.global_tags_changed)) {
1967 GstEvent *tag_event;
1968 gst_tag_list_add (demux->common.global_tags, GST_TAG_MERGE_REPLACE,
1969 GST_TAG_CONTAINER_FORMAT, "Matroska", NULL);
1970 GST_DEBUG_OBJECT (demux, "Sending global_tags %p : %" GST_PTR_FORMAT,
1971 demux->common.global_tags, demux->common.global_tags);
1974 gst_event_new_tag (gst_tag_list_copy (demux->common.global_tags));
1976 for (i = 0; i < demux->common.src->len; i++) {
1977 GstMatroskaTrackContext *stream;
1979 stream = g_ptr_array_index (demux->common.src, i);
1980 gst_pad_push_event (stream->pad, gst_event_ref (tag_event));
1983 gst_event_unref (tag_event);
1984 demux->common.global_tags_changed = FALSE;
1987 g_assert (demux->common.src->len == demux->common.num_streams);
1988 for (i = 0; i < demux->common.src->len; i++) {
1989 GstMatroskaTrackContext *stream;
1991 stream = g_ptr_array_index (demux->common.src, i);
1993 if (G_UNLIKELY (stream->tags_changed)) {
1994 GST_DEBUG_OBJECT (demux, "Sending tags %p for pad %s:%s : %"
1995 GST_PTR_FORMAT, stream->tags,
1996 GST_DEBUG_PAD_NAME (stream->pad), stream->tags);
1997 gst_pad_push_event (stream->pad,
1998 gst_event_new_tag (gst_tag_list_copy (stream->tags)));
1999 stream->tags_changed = FALSE;
2005 gst_matroska_demux_element_send_event (GstElement * element, GstEvent * event)
2007 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (element);
2010 g_return_val_if_fail (event != NULL, FALSE);
2012 if (GST_EVENT_TYPE (event) == GST_EVENT_SEEK) {
2013 /* no seeking until we are (safely) ready */
2014 if (demux->common.state != GST_MATROSKA_READ_STATE_DATA) {
2015 GST_DEBUG_OBJECT (demux,
2016 "not ready for seeking yet, deferring seek: %" GST_PTR_FORMAT, event);
2017 if (demux->deferred_seek_event)
2018 gst_event_unref (demux->deferred_seek_event);
2019 demux->deferred_seek_event = event;
2020 demux->deferred_seek_pad = NULL;
2023 if (!demux->streaming)
2024 res = gst_matroska_demux_handle_seek_event (demux, NULL, event);
2026 res = gst_matroska_demux_handle_seek_push (demux, NULL, event);
2028 GST_WARNING_OBJECT (demux, "Unhandled event of type %s",
2029 GST_EVENT_TYPE_NAME (event));
2032 gst_event_unref (event);
2037 gst_matroska_demux_move_to_entry (GstMatroskaDemux * demux,
2038 GstMatroskaIndex * entry, gboolean reset, gboolean update)
2042 GST_OBJECT_LOCK (demux);
2045 /* seek (relative to matroska segment) */
2046 /* position might be invalid; will error when streaming resumes ... */
2047 demux->common.offset = entry->pos + demux->common.ebml_segment_start;
2048 demux->next_cluster_offset = 0;
2050 GST_DEBUG_OBJECT (demux,
2051 "Seeked to offset %" G_GUINT64_FORMAT ", block %d, " "time %"
2052 GST_TIME_FORMAT, entry->pos + demux->common.ebml_segment_start,
2053 entry->block, GST_TIME_ARGS (entry->time));
2055 /* update the time */
2056 gst_matroska_read_common_reset_streams (&demux->common, entry->time, TRUE);
2057 gst_flow_combiner_reset (demux->flowcombiner);
2058 demux->common.segment.position = entry->time;
2059 demux->seek_block = entry->block;
2060 demux->seek_first = TRUE;
2061 demux->last_stop_end = GST_CLOCK_TIME_NONE;
2064 for (i = 0; i < demux->common.src->len; i++) {
2065 GstMatroskaTrackContext *stream = g_ptr_array_index (demux->common.src, i);
2068 stream->to_offset = G_MAXINT64;
2070 if (stream->from_offset != -1)
2071 stream->to_offset = stream->from_offset;
2073 stream->from_offset = -1;
2074 stream->from_time = GST_CLOCK_TIME_NONE;
2077 GST_OBJECT_UNLOCK (demux);
2083 gst_matroska_cluster_compare (gint64 * i1, gint64 * i2)
2093 /* searches for a cluster start from @pos,
2094 * return GST_FLOW_OK and cluster position in @pos if found */
2095 static GstFlowReturn
2096 gst_matroska_demux_search_cluster (GstMatroskaDemux * demux, gint64 * pos,
2099 gint64 newpos = *pos;
2101 GstFlowReturn ret = GST_FLOW_OK;
2102 const guint chunk = 128 * 1024;
2103 GstBuffer *buf = NULL;
2105 gpointer data = NULL;
2110 gint64 oldpos, oldlength;
2112 orig_offset = demux->common.offset;
2114 GST_LOG_OBJECT (demux, "searching cluster %s offset %" G_GINT64_FORMAT,
2115 forward ? "following" : "preceding", *pos);
2117 if (demux->clusters) {
2120 cpos = gst_util_array_binary_search (demux->clusters->data,
2121 demux->clusters->len, sizeof (gint64),
2122 (GCompareDataFunc) gst_matroska_cluster_compare,
2123 forward ? GST_SEARCH_MODE_AFTER : GST_SEARCH_MODE_BEFORE, pos, NULL);
2126 GST_DEBUG_OBJECT (demux,
2127 "cluster reported at offset %" G_GINT64_FORMAT, *cpos);
2128 demux->common.offset = *cpos;
2129 ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
2130 GST_ELEMENT_CAST (demux), &id, &length, &needed);
2131 if (ret == GST_FLOW_OK && id == GST_MATROSKA_ID_CLUSTER) {
2138 /* read in at newpos and scan for ebml cluster id */
2139 oldpos = oldlength = -1;
2141 GstByteReader reader;
2143 guint toread = chunk;
2146 /* never read beyond the requested target */
2147 if (G_UNLIKELY (newpos < chunk)) {
2155 gst_buffer_unmap (buf, &map);
2156 gst_buffer_unref (buf);
2159 ret = gst_pad_pull_range (demux->common.sinkpad, newpos, toread, &buf);
2160 if (ret != GST_FLOW_OK)
2162 GST_DEBUG_OBJECT (demux,
2163 "read buffer size %" G_GSIZE_FORMAT " at offset %" G_GINT64_FORMAT,
2164 gst_buffer_get_size (buf), newpos);
2165 gst_buffer_map (buf, &map, GST_MAP_READ);
2168 if (oldpos == newpos && oldlength == map.size) {
2169 GST_ERROR_OBJECT (demux, "Stuck at same position");
2170 ret = GST_FLOW_ERROR;
2174 oldlength = map.size;
2177 gst_byte_reader_init (&reader, data, size);
2180 gint found = gst_byte_reader_masked_scan_uint32 (&reader, 0xffffffff,
2181 GST_MATROSKA_ID_CLUSTER, 0, gst_byte_reader_get_remaining (&reader));
2183 cluster_pos = found;
2186 /* need last occurrence when searching backwards */
2188 cluster_pos = gst_byte_reader_get_pos (&reader) + found;
2189 gst_byte_reader_skip (&reader, found + 4);
2195 if (cluster_pos >= 0) {
2196 newpos += cluster_pos;
2197 GST_DEBUG_OBJECT (demux,
2198 "found cluster ebml id at offset %" G_GINT64_FORMAT, newpos);
2199 /* extra checks whether we really sync'ed to a cluster:
2200 * - either it is the first and only cluster
2201 * - either there is a cluster after this one
2202 * - either cluster length is undefined
2204 /* ok if first cluster (there may not a subsequent one) */
2205 if (newpos == demux->first_cluster_offset) {
2206 GST_DEBUG_OBJECT (demux, "cluster is first cluster -> OK");
2209 demux->common.offset = newpos;
2210 ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
2211 GST_ELEMENT_CAST (demux), &id, &length, &needed);
2212 if (ret != GST_FLOW_OK) {
2213 GST_DEBUG_OBJECT (demux, "need more data -> continue");
2216 g_assert (id == GST_MATROSKA_ID_CLUSTER);
2217 GST_DEBUG_OBJECT (demux, "cluster size %" G_GUINT64_FORMAT ", prefix %d",
2219 /* ok if undefined length or first cluster */
2220 if (length == GST_EBML_SIZE_UNKNOWN || length == G_MAXUINT64) {
2221 GST_DEBUG_OBJECT (demux, "cluster has undefined length -> OK");
2225 demux->common.offset += length + needed;
2226 ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
2227 GST_ELEMENT_CAST (demux), &id, &length, &needed);
2228 if (ret != GST_FLOW_OK)
2230 GST_DEBUG_OBJECT (demux, "next element is %scluster",
2231 id == GST_MATROSKA_ID_CLUSTER ? "" : "not ");
2232 if (id == GST_MATROSKA_ID_CLUSTER)
2238 /* partial cluster id may have been in tail of buffer */
2240 forward ? MAX (gst_byte_reader_get_remaining (&reader), 4) - 3 : 3;
2245 gst_buffer_unmap (buf, &map);
2246 gst_buffer_unref (buf);
2251 demux->common.offset = orig_offset;
2256 /* Three states to express: starts with I-frame, starts with delta, don't know */
2259 CLUSTER_STATUS_NONE = 0,
2260 CLUSTER_STATUS_STARTS_WITH_KEYFRAME,
2261 CLUSTER_STATUS_STARTS_WITH_DELTAUNIT,
2270 ClusterStatus status;
2273 static const gchar *
2274 cluster_status_get_nick (ClusterStatus status)
2277 case CLUSTER_STATUS_NONE:
2279 case CLUSTER_STATUS_STARTS_WITH_KEYFRAME:
2281 case CLUSTER_STATUS_STARTS_WITH_DELTAUNIT:
2287 /* Skip ebml-coded number:
2290 * 001x.. = 3 bytes, etc.
2293 bit_reader_skip_ebml_num (GstBitReader * br)
2297 if (!gst_bit_reader_peek_bits_uint8 (br, &v, 8))
2300 for (i = 0; i < 8; i++) {
2301 if ((v & (0x80 >> i)) != 0)
2304 return gst_bit_reader_skip (br, (i + 1) * 8);
2307 /* Don't probe more than that many bytes into the cluster for keyframe info
2308 * (random value, mostly for sanity checking) */
2309 #define MAX_CLUSTER_INFO_PROBE_LENGTH 256
2312 gst_matroska_demux_peek_cluster_info (GstMatroskaDemux * demux,
2313 ClusterInfo * cluster, guint64 offset)
2315 demux->common.offset = offset;
2316 demux->cluster_time = GST_CLOCK_TIME_NONE;
2318 cluster->offset = offset;
2320 cluster->prev_size = 0;
2321 cluster->time = GST_CLOCK_TIME_NONE;
2322 cluster->status = CLUSTER_STATUS_NONE;
2324 /* parse first few elements in cluster */
2331 flow = gst_matroska_read_common_peek_id_length_pull (&demux->common,
2332 GST_ELEMENT_CAST (demux), &id, &length, &needed);
2334 if (flow != GST_FLOW_OK)
2337 GST_LOG_OBJECT (demux, "Offset %" G_GUINT64_FORMAT ", Element id 0x%x, "
2338 "size %" G_GUINT64_FORMAT ", needed %d", demux->common.offset, id,
2341 /* Reached start of next cluster without finding data, stop processing */
2342 if (id == GST_MATROSKA_ID_CLUSTER && cluster->offset != offset)
2345 /* Not going to parse into these for now, stop processing */
2346 if (id == GST_MATROSKA_ID_ENCRYPTEDBLOCK
2347 || id == GST_MATROSKA_ID_BLOCKGROUP || id == GST_MATROSKA_ID_BLOCK)
2350 /* SimpleBlock: peek at headers to check if it's a keyframe */
2351 if (id == GST_MATROSKA_ID_SIMPLEBLOCK) {
2353 guint8 *d, hdr_len, v = 0;
2355 GST_DEBUG_OBJECT (demux, "SimpleBlock found");
2357 /* SimpleBlock header is max. 21 bytes */
2358 hdr_len = MIN (21, length);
2360 flow = gst_matroska_read_common_peek_bytes (&demux->common,
2361 demux->common.offset, hdr_len, NULL, &d);
2363 if (flow != GST_FLOW_OK)
2366 gst_bit_reader_init (&br, d, hdr_len);
2368 /* skip prefix: ebml id (SimpleBlock) + element length */
2369 if (!gst_bit_reader_skip (&br, 8 * needed))
2372 /* skip track number (ebml coded) */
2373 if (!bit_reader_skip_ebml_num (&br))
2377 if (!gst_bit_reader_skip (&br, 16))
2381 if (!gst_bit_reader_get_bits_uint8 (&br, &v, 8))
2384 if ((v & 0x80) != 0)
2385 cluster->status = CLUSTER_STATUS_STARTS_WITH_KEYFRAME;
2387 cluster->status = CLUSTER_STATUS_STARTS_WITH_DELTAUNIT;
2392 flow = gst_matroska_demux_parse_id (demux, id, length, needed);
2394 if (flow != GST_FLOW_OK)
2398 case GST_MATROSKA_ID_CLUSTER:
2399 if (length == G_MAXUINT64)
2402 cluster->size = length + needed;
2404 case GST_MATROSKA_ID_PREVSIZE:
2405 cluster->prev_size = demux->cluster_prevsize;
2407 case GST_MATROSKA_ID_CLUSTERTIMECODE:
2408 cluster->time = demux->cluster_time * demux->common.time_scale;
2410 case GST_MATROSKA_ID_SILENTTRACKS:
2411 case GST_EBML_ID_CRC32:
2412 /* ignore and continue */
2415 GST_WARNING_OBJECT (demux, "Unknown ebml id 0x%08x (possibly garbage), "
2419 } while (demux->common.offset - offset < MAX_CLUSTER_INFO_PROBE_LENGTH);
2423 GST_INFO_OBJECT (demux, "Cluster @ %" G_GUINT64_FORMAT ": "
2424 "time %" GST_TIME_FORMAT ", size %" G_GUINT64_FORMAT ", "
2425 "prev_size %" G_GUINT64_FORMAT ", %s", cluster->offset,
2426 GST_TIME_ARGS (cluster->time), cluster->size, cluster->prev_size,
2427 cluster_status_get_nick (cluster->status));
2429 /* return success as long as we could extract the minimum useful information */
2430 return cluster->time != GST_CLOCK_TIME_NONE;
2433 /* returns TRUE if the cluster offset was updated */
2435 gst_matroska_demux_scan_back_for_keyframe_cluster (GstMatroskaDemux * demux,
2436 gint64 * cluster_offset, GstClockTime * cluster_time)
2438 GstClockTime stream_start_time = demux->stream_start_time;
2439 guint64 first_cluster_offset = demux->first_cluster_offset;
2440 gint64 off = *cluster_offset;
2441 ClusterInfo cluster = { 0, };
2443 GST_INFO_OBJECT (demux, "Checking if cluster starts with keyframe");
2444 while (off > first_cluster_offset) {
2445 if (!gst_matroska_demux_peek_cluster_info (demux, &cluster, off)) {
2446 GST_LOG_OBJECT (demux,
2447 "Couldn't get info on cluster @ %" G_GUINT64_FORMAT, off);
2451 /* Keyframe? Then we're done */
2452 if (cluster.status == CLUSTER_STATUS_STARTS_WITH_KEYFRAME) {
2453 GST_LOG_OBJECT (demux,
2454 "Found keyframe at start of cluster @ %" G_GUINT64_FORMAT, off);
2458 /* We only scan back if we *know* we landed on a cluster that
2459 * starts with a delta frame. */
2460 if (cluster.status != CLUSTER_STATUS_STARTS_WITH_DELTAUNIT) {
2461 GST_LOG_OBJECT (demux,
2462 "No delta frame at start of cluster @ %" G_GUINT64_FORMAT, off);
2466 GST_DEBUG_OBJECT (demux, "Cluster starts with delta frame, backtracking");
2468 /* Don't scan back more than this much in time from the cluster we
2469 * originally landed on. This is mostly a sanity check in case a file
2470 * always has keyframes in the middle of clusters and never at the
2471 * beginning. Without this we would always scan back to the beginning
2472 * of the file in that case. */
2473 if (cluster.time != GST_CLOCK_TIME_NONE) {
2474 GstClockTimeDiff distance = GST_CLOCK_DIFF (cluster.time, *cluster_time);
2476 if (distance < 0 || distance > demux->max_backtrack_distance * GST_SECOND) {
2477 GST_DEBUG_OBJECT (demux, "Haven't found cluster with keyframe within "
2478 "%u secs of original seek target cluster, stopping",
2479 demux->max_backtrack_distance);
2484 /* If we have cluster prev_size we can skip back efficiently. If not,
2485 * we'll just do a brute force search for a cluster identifier */
2486 if (cluster.prev_size > 0 && off >= cluster.prev_size) {
2487 off -= cluster.prev_size;
2491 GST_LOG_OBJECT (demux, "Cluster has no or invalid prev size, searching "
2492 "for previous cluster instead then");
2494 flow = gst_matroska_demux_search_cluster (demux, &off, FALSE);
2495 if (flow != GST_FLOW_OK) {
2496 GST_DEBUG_OBJECT (demux, "cluster search yielded flow %s, stopping",
2497 gst_flow_get_name (flow));
2502 if (off <= first_cluster_offset) {
2503 GST_LOG_OBJECT (demux, "Reached first cluster, stopping");
2504 *cluster_offset = first_cluster_offset;
2505 *cluster_time = stream_start_time;
2508 GST_LOG_OBJECT (demux, "Trying prev cluster @ %" G_GUINT64_FORMAT, off);
2511 /* If we found a cluster starting with a keyframe jump to that instead,
2512 * otherwise leave everything as it was before */
2513 if (cluster.time != GST_CLOCK_TIME_NONE
2514 && (cluster.offset == first_cluster_offset
2515 || cluster.status == CLUSTER_STATUS_STARTS_WITH_KEYFRAME)) {
2516 *cluster_offset = cluster.offset;
2517 *cluster_time = cluster.time;
2524 /* bisect and scan through file for cluster starting before @time,
2525 * returns fake index entry with corresponding info on cluster */
2526 static GstMatroskaIndex *
2527 gst_matroska_demux_search_pos (GstMatroskaDemux * demux, GstClockTime time)
2529 GstMatroskaIndex *entry = NULL;
2530 GstMatroskaReadState current_state;
2531 GstClockTime otime, prev_cluster_time, current_cluster_time, cluster_time;
2533 gint64 opos, newpos, current_offset;
2534 gint64 prev_cluster_offset = -1, current_cluster_offset, cluster_offset;
2535 gint64 apos, maxpos;
2536 guint64 cluster_size = 0;
2542 /* estimate new position, resync using cluster ebml id,
2543 * and bisect further or scan forward to appropriate cluster */
2545 /* save some current global state which will be touched by our scanning */
2546 current_state = demux->common.state;
2547 g_return_val_if_fail (current_state == GST_MATROSKA_READ_STATE_DATA, NULL);
2549 current_cluster_offset = demux->cluster_offset;
2550 current_cluster_time = demux->cluster_time;
2551 current_offset = demux->common.offset;
2553 demux->common.state = GST_MATROSKA_READ_STATE_SCANNING;
2555 /* estimate using start and last known cluster */
2556 GST_OBJECT_LOCK (demux);
2557 apos = demux->first_cluster_offset;
2558 atime = demux->stream_start_time;
2559 opos = demux->last_cluster_offset;
2560 otime = demux->stream_last_time;
2561 GST_OBJECT_UNLOCK (demux);
2564 time = MAX (time, atime);
2565 otime = MAX (otime, atime);
2566 opos = MAX (opos, apos);
2568 maxpos = gst_matroska_read_common_get_length (&demux->common);
2573 * apos always refer to a cluster before target time;
2574 * opos may or may not be after target time, but if it is once so,
2575 * then also in next iteration
2579 GST_LOG_OBJECT (demux,
2580 "apos: %" G_GUINT64_FORMAT ", atime: %" GST_TIME_FORMAT ", %"
2581 GST_TIME_FORMAT " in stream time, "
2582 "opos: %" G_GUINT64_FORMAT ", otime: %" GST_TIME_FORMAT ", %"
2583 GST_TIME_FORMAT " in stream time (start %" GST_TIME_FORMAT "), time %"
2584 GST_TIME_FORMAT, apos, GST_TIME_ARGS (atime),
2585 GST_TIME_ARGS (atime - demux->stream_start_time), opos,
2586 GST_TIME_ARGS (otime), GST_TIME_ARGS (otime - demux->stream_start_time),
2587 GST_TIME_ARGS (demux->stream_start_time), GST_TIME_ARGS (time));
2589 g_assert (atime <= otime);
2590 g_assert (apos <= opos);
2591 if (time == GST_CLOCK_TIME_NONE) {
2592 GST_DEBUG_OBJECT (demux, "searching last cluster");
2595 GST_DEBUG_OBJECT (demux, "unknown file size; bailing out");
2598 } else if (otime <= atime) {
2602 gst_util_uint64_scale (opos - apos, time - atime, otime - atime);
2603 if (maxpos != -1 && newpos > maxpos)
2607 GST_DEBUG_OBJECT (demux,
2608 "estimated offset for %" GST_TIME_FORMAT ": %" G_GINT64_FORMAT,
2609 GST_TIME_ARGS (time), newpos);
2611 /* search backwards */
2612 if (newpos > apos) {
2613 ret = gst_matroska_demux_search_cluster (demux, &newpos, FALSE);
2614 if (ret != GST_FLOW_OK)
2618 /* then start scanning and parsing for cluster time,
2619 * re-estimate if possible, otherwise next cluster and so on */
2620 /* note that each re-estimate is entered with a change in apos or opos,
2621 * avoiding infinite loop */
2622 demux->common.offset = newpos;
2623 demux->cluster_time = cluster_time = GST_CLOCK_TIME_NONE;
2625 prev_cluster_time = GST_CLOCK_TIME_NONE;
2627 /* peek and parse some elements */
2628 ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
2629 GST_ELEMENT_CAST (demux), &id, &length, &needed);
2630 if (ret != GST_FLOW_OK)
2632 GST_LOG_OBJECT (demux, "Offset %" G_GUINT64_FORMAT ", Element id 0x%x, "
2633 "size %" G_GUINT64_FORMAT ", needed %d", demux->common.offset, id,
2635 ret = gst_matroska_demux_parse_id (demux, id, length, needed);
2636 if (ret != GST_FLOW_OK)
2639 if (id == GST_MATROSKA_ID_CLUSTER) {
2640 cluster_time = GST_CLOCK_TIME_NONE;
2641 if (length == G_MAXUINT64)
2644 cluster_size = length + needed;
2646 if (demux->cluster_time != GST_CLOCK_TIME_NONE &&
2647 cluster_time == GST_CLOCK_TIME_NONE) {
2648 cluster_time = demux->cluster_time * demux->common.time_scale;
2649 cluster_offset = demux->cluster_offset;
2650 GST_DEBUG_OBJECT (demux, "found cluster at offset %" G_GINT64_FORMAT
2651 " with time %" GST_TIME_FORMAT, cluster_offset,
2652 GST_TIME_ARGS (cluster_time));
2653 if (time == GST_CLOCK_TIME_NONE) {
2654 GST_DEBUG_OBJECT (demux, "found last cluster");
2655 prev_cluster_time = cluster_time;
2656 prev_cluster_offset = cluster_offset;
2659 if (cluster_time > time) {
2660 GST_DEBUG_OBJECT (demux, "overshot target");
2661 /* cluster overshoots */
2662 if (cluster_offset == demux->first_cluster_offset) {
2663 /* but no prev one */
2664 GST_DEBUG_OBJECT (demux, "but using first cluster anyway");
2665 prev_cluster_time = cluster_time;
2666 prev_cluster_offset = cluster_offset;
2669 if (prev_cluster_time != GST_CLOCK_TIME_NONE) {
2670 /* prev cluster did not overshoot, so prev cluster is target */
2673 /* re-estimate using this new position info */
2674 opos = cluster_offset;
2675 otime = cluster_time;
2679 /* cluster undershoots */
2680 GST_DEBUG_OBJECT (demux, "undershot target");
2681 /* ok if close enough */
2682 if (GST_CLOCK_DIFF (cluster_time, time) < 5 * GST_SECOND) {
2683 GST_DEBUG_OBJECT (demux, "target close enough");
2684 prev_cluster_time = cluster_time;
2685 prev_cluster_offset = cluster_offset;
2689 /* we are in between atime and otime => can bisect if worthwhile */
2690 if (prev_cluster_time != GST_CLOCK_TIME_NONE &&
2691 cluster_time > prev_cluster_time &&
2692 (GST_CLOCK_DIFF (prev_cluster_time, cluster_time) * 10 <
2693 GST_CLOCK_DIFF (cluster_time, time))) {
2694 /* we moved at least one cluster forward,
2695 * and it looks like target is still far away,
2696 * let's estimate again */
2697 GST_DEBUG_OBJECT (demux, "bisecting with new apos");
2698 apos = cluster_offset;
2699 atime = cluster_time;
2703 /* cluster undershoots, goto next one */
2704 prev_cluster_time = cluster_time;
2705 prev_cluster_offset = cluster_offset;
2706 /* skip cluster if length is defined,
2707 * otherwise will be skippingly parsed into */
2709 GST_DEBUG_OBJECT (demux, "skipping to next cluster");
2710 demux->common.offset = cluster_offset + cluster_size;
2711 demux->cluster_time = GST_CLOCK_TIME_NONE;
2713 GST_DEBUG_OBJECT (demux, "parsing/skipping cluster elements");
2720 if (ret == GST_FLOW_EOS) {
2721 if (prev_cluster_time != GST_CLOCK_TIME_NONE)
2727 /* In the bisect loop above we always undershoot and then jump forward
2728 * cluster-by-cluster until we overshoot, so if we get here we've gone
2729 * over and the previous cluster is where we need to go to. */
2730 cluster_offset = prev_cluster_offset;
2731 cluster_time = prev_cluster_time;
2733 /* If we have video and can easily backtrack, check if we landed on a cluster
2734 * that starts with a keyframe - and if not backtrack until we find one that
2736 if (demux->have_nonintraonly_v_streams && demux->max_backtrack_distance > 0) {
2737 if (gst_matroska_demux_scan_back_for_keyframe_cluster (demux,
2738 &cluster_offset, &cluster_time)) {
2739 GST_INFO_OBJECT (demux, "Adjusted cluster to %" GST_TIME_FORMAT " @ "
2740 "%" G_GUINT64_FORMAT, GST_TIME_ARGS (cluster_time), cluster_offset);
2744 entry = g_new0 (GstMatroskaIndex, 1);
2745 entry->time = cluster_time;
2746 entry->pos = cluster_offset - demux->common.ebml_segment_start;
2747 GST_DEBUG_OBJECT (demux, "simulated index entry; time %" GST_TIME_FORMAT
2748 ", pos %" G_GUINT64_FORMAT, GST_TIME_ARGS (entry->time), entry->pos);
2752 /* restore some state */
2753 demux->cluster_offset = current_cluster_offset;
2754 demux->cluster_time = current_cluster_time;
2755 demux->common.offset = current_offset;
2756 demux->common.state = current_state;
2762 gst_matroska_demux_handle_seek_event (GstMatroskaDemux * demux,
2763 GstPad * pad, GstEvent * event)
2765 GstMatroskaIndex *entry = NULL;
2766 GstMatroskaIndex scan_entry;
2768 GstSeekType cur_type, stop_type;
2770 gboolean flush, keyunit, instant_rate_change, before, after, accurate,
2774 GstMatroskaTrackContext *track = NULL;
2775 GstSegment seeksegment = { 0, };
2777 gboolean update = TRUE;
2778 gboolean pad_locked = FALSE;
2780 GstSearchMode snap_dir;
2782 g_return_val_if_fail (event != NULL, FALSE);
2785 track = gst_pad_get_element_private (pad);
2787 GST_DEBUG_OBJECT (demux, "Have seek %" GST_PTR_FORMAT, event);
2789 gst_event_parse_seek (event, &rate, &format, &flags, &cur_type, &cur,
2791 seqnum = gst_event_get_seqnum (event);
2793 /* we can only seek on time */
2794 if (format != GST_FORMAT_TIME) {
2795 GST_DEBUG_OBJECT (demux, "Can only seek on TIME");
2799 GST_DEBUG_OBJECT (demux, "configuring seek");
2801 flush = ! !(flags & GST_SEEK_FLAG_FLUSH);
2802 keyunit = ! !(flags & GST_SEEK_FLAG_KEY_UNIT);
2803 after = ! !(flags & GST_SEEK_FLAG_SNAP_AFTER);
2804 before = ! !(flags & GST_SEEK_FLAG_SNAP_BEFORE);
2805 accurate = ! !(flags & GST_SEEK_FLAG_ACCURATE);
2806 instant_rate_change = ! !(flags & GST_SEEK_FLAG_INSTANT_RATE_CHANGE);
2808 /* Directly send the instant-rate-change event here before taking the
2809 * stream-lock so that it can be applied as soon as possible */
2810 if (instant_rate_change) {
2813 /* instant rate change only supported if direction does not change. All
2814 * other requirements are already checked before creating the seek event
2815 * but let's double-check here to be sure */
2816 if ((rate > 0 && demux->common.segment.rate < 0) ||
2817 (rate < 0 && demux->common.segment.rate > 0) ||
2818 cur_type != GST_SEEK_TYPE_NONE ||
2819 stop_type != GST_SEEK_TYPE_NONE || flush) {
2820 GST_ERROR_OBJECT (demux,
2821 "Instant rate change seeks only supported in the "
2822 "same direction, without flushing and position change");
2826 ev = gst_event_new_instant_rate_change (rate /
2827 demux->common.segment.rate, (GstSegmentFlags) flags);
2828 gst_event_set_seqnum (ev, seqnum);
2829 gst_matroska_demux_send_event (demux, ev);
2833 /* copy segment, we need this because we still need the old
2834 * segment when we close the current segment. */
2835 memcpy (&seeksegment, &demux->common.segment, sizeof (GstSegment));
2837 /* pull mode without index means that the actual duration is not known,
2838 * we might be playing a file that's still being recorded
2839 * so, invalidate our current duration, which is only a moving target,
2840 * and should not be used to clamp anything */
2841 if (!demux->streaming && !demux->common.index && demux->invalid_duration) {
2842 seeksegment.duration = GST_CLOCK_TIME_NONE;
2845 /* Subtract stream_start_time so we always seek on a segment
2847 if (GST_CLOCK_TIME_IS_VALID (demux->stream_start_time)) {
2848 seeksegment.start -= demux->stream_start_time;
2849 seeksegment.position -= demux->stream_start_time;
2850 if (GST_CLOCK_TIME_IS_VALID (seeksegment.stop))
2851 seeksegment.stop -= demux->stream_start_time;
2853 seeksegment.stop = seeksegment.duration;
2856 if (!gst_segment_do_seek (&seeksegment, rate, format, flags,
2857 cur_type, cur, stop_type, stop, &update)) {
2858 GST_WARNING_OBJECT (demux, "gst_segment_do_seek() failed.");
2862 /* Restore the clip timestamp offset */
2863 if (GST_CLOCK_TIME_IS_VALID (demux->stream_start_time)) {
2864 seeksegment.position += demux->stream_start_time;
2865 seeksegment.start += demux->stream_start_time;
2866 if (!GST_CLOCK_TIME_IS_VALID (seeksegment.stop))
2867 seeksegment.stop = seeksegment.duration;
2868 if (GST_CLOCK_TIME_IS_VALID (seeksegment.stop))
2869 seeksegment.stop += demux->stream_start_time;
2872 /* restore segment duration (if any effect),
2873 * would be determined again when parsing, but anyway ... */
2874 seeksegment.duration = demux->common.segment.duration;
2876 /* always do full update if flushing,
2877 * otherwise problems might arise downstream with missing keyframes etc */
2878 update = update || flush;
2880 GST_DEBUG_OBJECT (demux, "New segment %" GST_SEGMENT_FORMAT, &seeksegment);
2882 /* check sanity before we start flushing and all that */
2883 snap_next = after && !before;
2884 if (seeksegment.rate < 0)
2885 snap_dir = snap_next ? GST_SEARCH_MODE_BEFORE : GST_SEARCH_MODE_AFTER;
2887 snap_dir = snap_next ? GST_SEARCH_MODE_AFTER : GST_SEARCH_MODE_BEFORE;
2889 GST_OBJECT_LOCK (demux);
2891 seekpos = seeksegment.position;
2893 seekpos -= MIN (seeksegment.position, demux->audio_lead_in_ts);
2896 track = gst_matroska_read_common_get_seek_track (&demux->common, track);
2897 if ((entry = gst_matroska_read_common_do_index_seek (&demux->common, track,
2898 seekpos, &demux->seek_index, &demux->seek_entry,
2899 snap_dir)) == NULL) {
2900 /* pull mode without index can scan later on */
2901 if (demux->streaming) {
2902 GST_DEBUG_OBJECT (demux, "No matching seek entry in index");
2903 GST_OBJECT_UNLOCK (demux);
2905 } else if (rate < 0.0) {
2906 /* FIXME: We should build an index during playback or when scanning
2907 * that can be used here. The reverse playback code requires seek_index
2908 * and seek_entry to be set!
2910 GST_DEBUG_OBJECT (demux,
2911 "No matching seek entry in index, needed for reverse playback");
2912 GST_OBJECT_UNLOCK (demux);
2916 GST_DEBUG_OBJECT (demux, "Seek position looks sane");
2917 GST_OBJECT_UNLOCK (demux);
2920 /* only have to update some segment,
2921 * but also still have to honour flush and so on */
2922 GST_DEBUG_OBJECT (demux, "... no update");
2923 /* bad goto, bad ... */
2927 if (demux->streaming)
2932 GstEvent *flush_event = gst_event_new_flush_start ();
2933 gst_event_set_seqnum (flush_event, seqnum);
2934 GST_DEBUG_OBJECT (demux, "Starting flush");
2935 gst_pad_push_event (demux->common.sinkpad, gst_event_ref (flush_event));
2936 gst_matroska_demux_send_event (demux, flush_event);
2938 GST_DEBUG_OBJECT (demux, "Non-flushing seek, pausing task");
2939 gst_pad_pause_task (demux->common.sinkpad);
2943 GST_PAD_STREAM_LOCK (demux->common.sinkpad);
2948 /* now grab the stream lock so that streaming cannot continue, for
2949 * non flushing seeks when the element is in PAUSED this could block
2951 GST_DEBUG_OBJECT (demux, "Waiting for streaming to stop");
2952 GST_PAD_STREAM_LOCK (demux->common.sinkpad);
2955 /* pull mode without index can do some scanning */
2956 if (!demux->streaming && !entry) {
2957 GstEvent *flush_event;
2959 /* need to stop flushing upstream as we need it next */
2961 flush_event = gst_event_new_flush_stop (TRUE);
2962 gst_event_set_seqnum (flush_event, seqnum);
2963 gst_pad_push_event (demux->common.sinkpad, flush_event);
2965 entry = gst_matroska_demux_search_pos (demux, seekpos);
2966 /* keep local copy */
2968 scan_entry = *entry;
2970 entry = &scan_entry;
2972 GST_DEBUG_OBJECT (demux, "Scan failed to find matching position");
2974 flush_event = gst_event_new_flush_stop (TRUE);
2975 gst_event_set_seqnum (flush_event, seqnum);
2976 gst_matroska_demux_send_event (demux, flush_event);
2983 if (keyunit && seeksegment.rate > 0) {
2984 GST_DEBUG_OBJECT (demux, "seek to key unit, adjusting segment start from %"
2985 GST_TIME_FORMAT " to %" GST_TIME_FORMAT,
2986 GST_TIME_ARGS (seeksegment.start), GST_TIME_ARGS (entry->time));
2987 seeksegment.start = MAX (entry->time, demux->stream_start_time);
2988 seeksegment.position = seeksegment.start;
2989 seeksegment.time = seeksegment.start - demux->stream_start_time;
2990 } else if (keyunit) {
2991 GST_DEBUG_OBJECT (demux, "seek to key unit, adjusting segment stop from %"
2992 GST_TIME_FORMAT " to %" GST_TIME_FORMAT,
2993 GST_TIME_ARGS (seeksegment.stop), GST_TIME_ARGS (entry->time));
2994 seeksegment.stop = MAX (entry->time, demux->stream_start_time);
2995 seeksegment.position = seeksegment.stop;
2998 if (demux->streaming) {
2999 GST_OBJECT_LOCK (demux);
3000 /* track real position we should start at */
3001 GST_DEBUG_OBJECT (demux, "storing segment start");
3002 demux->requested_seek_time = seeksegment.position;
3003 demux->seek_offset = entry->pos + demux->common.ebml_segment_start;
3004 GST_OBJECT_UNLOCK (demux);
3005 /* need to seek to cluster start to pick up cluster time */
3006 /* upstream takes care of flushing and all that
3007 * ... and newsegment event handling takes care of the rest */
3008 return perform_seek_to_offset (demux, rate,
3009 entry->pos + demux->common.ebml_segment_start, seqnum, flags);
3014 GstEvent *flush_event = gst_event_new_flush_stop (TRUE);
3015 gst_event_set_seqnum (flush_event, seqnum);
3016 GST_DEBUG_OBJECT (demux, "Stopping flush");
3017 gst_pad_push_event (demux->common.sinkpad, gst_event_ref (flush_event));
3018 gst_matroska_demux_send_event (demux, flush_event);
3021 GST_OBJECT_LOCK (demux);
3022 /* now update the real segment info */
3023 GST_DEBUG_OBJECT (demux, "Committing new seek segment");
3024 memcpy (&demux->common.segment, &seeksegment, sizeof (GstSegment));
3025 GST_OBJECT_UNLOCK (demux);
3027 /* update some (segment) state */
3028 if (!gst_matroska_demux_move_to_entry (demux, entry, TRUE, update))
3031 /* notify start of new segment */
3032 if (demux->common.segment.flags & GST_SEEK_FLAG_SEGMENT) {
3035 msg = gst_message_new_segment_start (GST_OBJECT (demux),
3036 GST_FORMAT_TIME, demux->common.segment.start);
3037 gst_message_set_seqnum (msg, seqnum);
3038 gst_element_post_message (GST_ELEMENT (demux), msg);
3041 GST_OBJECT_LOCK (demux);
3042 if (demux->new_segment)
3043 gst_event_unref (demux->new_segment);
3045 /* On port from 0.10, discarded !update (for segment.update) here, FIXME? */
3046 demux->new_segment = gst_event_new_segment (&demux->common.segment);
3047 gst_event_set_seqnum (demux->new_segment, seqnum);
3048 if (demux->common.segment.rate < 0 && demux->common.segment.stop == -1)
3049 demux->to_time = demux->common.segment.position;
3051 demux->to_time = GST_CLOCK_TIME_NONE;
3052 demux->segment_seqnum = seqnum;
3053 GST_OBJECT_UNLOCK (demux);
3055 /* restart our task since it might have been stopped when we did the
3057 gst_pad_start_task (demux->common.sinkpad,
3058 (GstTaskFunction) gst_matroska_demux_loop, demux->common.sinkpad, NULL);
3060 /* streaming can continue now */
3062 GST_PAD_STREAM_UNLOCK (demux->common.sinkpad);
3070 GST_PAD_STREAM_UNLOCK (demux->common.sinkpad);
3072 GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL), ("Got a seek error"));
3078 * Handle whether we can perform the seek event or if we have to let the chain
3079 * function handle seeks to build the seek indexes first.
3082 gst_matroska_demux_handle_seek_push (GstMatroskaDemux * demux, GstPad * pad,
3086 GstSeekType cur_type, stop_type;
3091 gst_event_parse_seek (event, &rate, &format, &flags, &cur_type, &cur,
3094 /* Directly send the instant-rate-change event here before taking the
3095 * stream-lock so that it can be applied as soon as possible */
3096 if (flags & GST_SEEK_FLAG_INSTANT_RATE_CHANGE) {
3100 /* instant rate change only supported if direction does not change. All
3101 * other requirements are already checked before creating the seek event
3102 * but let's double-check here to be sure */
3103 if ((rate > 0 && demux->common.segment.rate < 0) ||
3104 (rate < 0 && demux->common.segment.rate > 0) ||
3105 cur_type != GST_SEEK_TYPE_NONE ||
3106 stop_type != GST_SEEK_TYPE_NONE || (flags & GST_SEEK_FLAG_FLUSH)) {
3107 GST_ERROR_OBJECT (demux,
3108 "Instant rate change seeks only supported in the "
3109 "same direction, without flushing and position change");
3113 seqnum = gst_event_get_seqnum (event);
3114 ev = gst_event_new_instant_rate_change (rate / demux->common.segment.rate,
3115 (GstSegmentFlags) flags);
3116 gst_event_set_seqnum (ev, seqnum);
3117 gst_matroska_demux_send_event (demux, ev);
3125 /* we can only seek on time */
3126 if (format != GST_FORMAT_TIME) {
3127 GST_DEBUG_OBJECT (demux, "Can only seek on TIME");
3131 if (stop_type != GST_SEEK_TYPE_NONE && stop != GST_CLOCK_TIME_NONE) {
3132 GST_DEBUG_OBJECT (demux, "Seek end-time not supported in streaming mode");
3136 if (!(flags & GST_SEEK_FLAG_FLUSH)) {
3137 GST_DEBUG_OBJECT (demux,
3138 "Non-flushing seek not supported in streaming mode");
3142 if (flags & GST_SEEK_FLAG_SEGMENT) {
3143 GST_DEBUG_OBJECT (demux, "Segment seek not supported in streaming mode");
3147 /* check for having parsed index already */
3148 if (!demux->common.index_parsed) {
3149 gboolean building_index;
3152 if (!demux->index_offset) {
3153 GST_DEBUG_OBJECT (demux, "no index (location); no seek in push mode");
3157 GST_OBJECT_LOCK (demux);
3158 /* handle the seek event in the chain function */
3159 demux->common.state = GST_MATROSKA_READ_STATE_SEEK;
3160 /* no more seek can be issued until state reset to _DATA */
3162 /* copy the event */
3163 if (demux->seek_event)
3164 gst_event_unref (demux->seek_event);
3165 demux->seek_event = gst_event_ref (event);
3167 /* set the building_index flag so that only one thread can setup the
3168 * structures for index seeking. */
3169 building_index = demux->building_index;
3170 if (!building_index) {
3171 demux->building_index = TRUE;
3172 offset = demux->index_offset;
3174 GST_OBJECT_UNLOCK (demux);
3176 if (!building_index) {
3177 /* seek to the first subindex or legacy index */
3178 GST_INFO_OBJECT (demux, "Seeking to Cues at %" G_GUINT64_FORMAT, offset);
3179 return perform_seek_to_offset (demux, rate, offset,
3180 gst_event_get_seqnum (event), GST_SEEK_FLAG_NONE);
3183 /* well, we are handling it already */
3187 /* delegate to tweaked regular seek */
3188 return gst_matroska_demux_handle_seek_event (demux, pad, event);
3192 gst_matroska_demux_handle_src_event (GstPad * pad, GstObject * parent,
3195 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (parent);
3196 gboolean res = TRUE;
3198 switch (GST_EVENT_TYPE (event)) {
3199 case GST_EVENT_SEEK:
3200 /* no seeking until we are (safely) ready */
3201 if (demux->common.state != GST_MATROSKA_READ_STATE_DATA) {
3202 GST_DEBUG_OBJECT (demux,
3203 "not ready for seeking yet, deferring seek event: %" GST_PTR_FORMAT,
3205 if (demux->deferred_seek_event)
3206 gst_event_unref (demux->deferred_seek_event);
3207 demux->deferred_seek_event = event;
3208 demux->deferred_seek_pad = pad;
3213 guint32 seqnum = gst_event_get_seqnum (event);
3214 if (seqnum == demux->segment_seqnum) {
3215 GST_LOG_OBJECT (pad,
3216 "Drop duplicated SEEK event seqnum %" G_GUINT32_FORMAT, seqnum);
3217 gst_event_unref (event);
3222 if (!demux->streaming)
3223 res = gst_matroska_demux_handle_seek_event (demux, pad, event);
3225 res = gst_matroska_demux_handle_seek_push (demux, pad, event);
3226 gst_event_unref (event);
3231 GstMatroskaTrackContext *context = gst_pad_get_element_private (pad);
3232 if (context->type == GST_MATROSKA_TRACK_TYPE_VIDEO) {
3233 GstMatroskaTrackVideoContext *videocontext =
3234 (GstMatroskaTrackVideoContext *) context;
3236 GstClockTimeDiff diff;
3237 GstClockTime timestamp;
3239 gst_event_parse_qos (event, NULL, &proportion, &diff, ×tamp);
3241 GST_OBJECT_LOCK (demux);
3242 videocontext->earliest_time = timestamp + diff;
3243 GST_OBJECT_UNLOCK (demux);
3246 gst_event_unref (event);
3250 case GST_EVENT_TOC_SELECT:
3253 GstTocEntry *entry = NULL;
3254 GstEvent *seek_event;
3257 if (!demux->common.toc) {
3258 GST_DEBUG_OBJECT (demux, "no TOC to select");
3261 gst_event_parse_toc_select (event, &uid);
3263 GST_OBJECT_LOCK (demux);
3264 entry = gst_toc_find_entry (demux->common.toc, uid);
3265 if (entry == NULL) {
3266 GST_OBJECT_UNLOCK (demux);
3267 GST_WARNING_OBJECT (demux, "no TOC entry with given UID: %s", uid);
3270 gst_toc_entry_get_start_stop_times (entry, &start_pos, NULL);
3271 GST_OBJECT_UNLOCK (demux);
3272 seek_event = gst_event_new_seek (1.0,
3274 GST_SEEK_FLAG_FLUSH,
3275 GST_SEEK_TYPE_SET, start_pos, GST_SEEK_TYPE_SET, -1);
3276 res = gst_matroska_demux_handle_seek_event (demux, pad, seek_event);
3277 gst_event_unref (seek_event);
3281 GST_WARNING_OBJECT (demux, "received empty TOC select event");
3285 gst_event_unref (event);
3289 /* events we don't need to handle */
3290 case GST_EVENT_NAVIGATION:
3291 gst_event_unref (event);
3295 case GST_EVENT_LATENCY:
3297 res = gst_pad_push_event (demux->common.sinkpad, event);
3305 gst_matroska_demux_handle_sink_query (GstPad * pad, GstObject * parent,
3308 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (parent);
3309 gboolean res = FALSE;
3311 switch (GST_QUERY_TYPE (query)) {
3312 case GST_QUERY_BITRATE:
3314 if (G_UNLIKELY (demux->cached_length == G_MAXUINT64 ||
3315 demux->common.offset >= demux->cached_length)) {
3316 demux->cached_length =
3317 gst_matroska_read_common_get_length (&demux->common);
3320 if (demux->cached_length < G_MAXUINT64
3321 && demux->common.segment.duration > 0) {
3322 /* TODO: better results based on ranges/index tables */
3324 gst_util_uint64_scale (8 * demux->cached_length, GST_SECOND,
3325 demux->common.segment.duration);
3327 GST_LOG_OBJECT (demux, "bitrate query byte length: %" G_GUINT64_FORMAT
3328 " duration %" GST_TIME_FORMAT " resulting in a bitrate of %u",
3329 demux->cached_length,
3330 GST_TIME_ARGS (demux->common.segment.duration), bitrate);
3332 gst_query_set_bitrate (query, bitrate);
3338 res = gst_pad_query_default (pad, (GstObject *) demux, query);
3345 static GstFlowReturn
3346 gst_matroska_demux_seek_to_previous_keyframe (GstMatroskaDemux * demux)
3348 GstFlowReturn ret = GST_FLOW_EOS;
3349 gboolean done = TRUE;
3352 g_return_val_if_fail (demux->seek_index, GST_FLOW_EOS);
3353 g_return_val_if_fail (demux->seek_entry < demux->seek_index->len,
3356 GST_DEBUG_OBJECT (demux, "locating previous keyframe");
3358 if (!demux->seek_entry) {
3359 GST_DEBUG_OBJECT (demux, "no earlier index entry");
3363 for (i = 0; i < demux->common.src->len; i++) {
3364 GstMatroskaTrackContext *stream = g_ptr_array_index (demux->common.src, i);
3366 GST_DEBUG_OBJECT (demux, "segment start %" GST_TIME_FORMAT
3367 ", stream %d at %" GST_TIME_FORMAT,
3368 GST_TIME_ARGS (demux->common.segment.start), stream->index,
3369 GST_TIME_ARGS (stream->from_time));
3370 if (GST_CLOCK_TIME_IS_VALID (stream->from_time)) {
3371 if (stream->from_time > demux->common.segment.start) {
3372 GST_DEBUG_OBJECT (demux, "stream %d not finished yet", stream->index);
3376 /* nothing pushed for this stream;
3377 * likely seek entry did not start at keyframe, so all was skipped.
3378 * So we need an earlier entry */
3384 GstMatroskaIndex *entry;
3386 entry = &g_array_index (demux->seek_index, GstMatroskaIndex,
3387 --demux->seek_entry);
3388 if (!gst_matroska_demux_move_to_entry (demux, entry, FALSE, TRUE))
3398 static GstFlowReturn
3399 gst_matroska_demux_parse_tracks (GstMatroskaDemux * demux, GstEbmlRead * ebml)
3401 GstFlowReturn ret = GST_FLOW_OK;
3404 DEBUG_ELEMENT_START (demux, ebml, "Tracks");
3406 if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
3407 DEBUG_ELEMENT_STOP (demux, ebml, "Tracks", ret);
3411 while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
3412 if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
3416 /* one track within the "all-tracks" header */
3417 case GST_MATROSKA_ID_TRACKENTRY:{
3418 GstMatroskaTrackContext *track;
3419 ret = gst_matroska_demux_parse_stream (demux, ebml, &track);
3420 if (track != NULL) {
3421 if (gst_matroska_read_common_tracknumber_unique (&demux->common,
3423 gst_matroska_demux_add_stream (demux, track);
3425 GST_ERROR_OBJECT (demux,
3426 "TrackNumber %" G_GUINT64_FORMAT " is not unique", track->num);
3427 ret = GST_FLOW_ERROR;
3428 gst_matroska_track_free (track);
3436 ret = gst_matroska_read_common_parse_skip (&demux->common, ebml,
3441 DEBUG_ELEMENT_STOP (demux, ebml, "Tracks", ret);
3443 demux->tracks_parsed = TRUE;
3444 GST_DEBUG_OBJECT (demux, "signaling no more pads");
3445 gst_element_no_more_pads (GST_ELEMENT (demux));
3450 static GstFlowReturn
3451 gst_matroska_demux_update_tracks (GstMatroskaDemux * demux, GstEbmlRead * ebml)
3453 GstFlowReturn ret = GST_FLOW_OK;
3454 guint num_tracks_found = 0;
3457 GST_INFO_OBJECT (demux, "Reparsing Tracks element");
3459 DEBUG_ELEMENT_START (demux, ebml, "Tracks");
3461 if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
3462 DEBUG_ELEMENT_STOP (demux, ebml, "Tracks", ret);
3466 while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
3467 if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
3471 /* one track within the "all-tracks" header */
3472 case GST_MATROSKA_ID_TRACKENTRY:{
3473 GstMatroskaTrackContext *new_track;
3474 gint old_track_index;
3475 GstMatroskaTrackContext *old_track;
3476 ret = gst_matroska_demux_parse_stream (demux, ebml, &new_track);
3477 if (new_track == NULL)
3481 if (gst_matroska_read_common_tracknumber_unique (&demux->common,
3483 GST_ERROR_OBJECT (demux,
3484 "Unexpected new TrackNumber: %" G_GUINT64_FORMAT, new_track->num);
3485 goto track_mismatch_error;
3489 gst_matroska_read_common_stream_from_num (&demux->common,
3491 g_assert (old_track_index != -1);
3492 old_track = g_ptr_array_index (demux->common.src, old_track_index);
3494 if (old_track->type != new_track->type) {
3495 GST_ERROR_OBJECT (demux,
3496 "Mismatch reparsing track %" G_GUINT64_FORMAT
3497 " on track type. Expected %d, found %d", new_track->num,
3498 old_track->type, new_track->type);
3499 goto track_mismatch_error;
3502 if (g_strcmp0 (old_track->codec_id, new_track->codec_id) != 0) {
3503 GST_ERROR_OBJECT (demux,
3504 "Mismatch reparsing track %" G_GUINT64_FORMAT
3505 " on codec id. Expected '%s', found '%s'", new_track->num,
3506 old_track->codec_id, new_track->codec_id);
3507 goto track_mismatch_error;
3510 /* The new track matches the old track. No problems on our side.
3511 * Let's make it replace the old track. */
3512 new_track->pad = old_track->pad;
3513 new_track->index = old_track->index;
3514 new_track->pos = old_track->pos;
3515 g_ptr_array_index (demux->common.src, old_track_index) = new_track;
3516 gst_pad_set_element_private (new_track->pad, new_track);
3518 if (!gst_caps_is_equal (old_track->caps, new_track->caps)) {
3519 gst_pad_set_caps (new_track->pad, new_track->caps);
3521 gst_caps_replace (&old_track->caps, NULL);
3523 if (!gst_tag_list_is_equal (old_track->tags, new_track->tags)) {
3524 GST_DEBUG_OBJECT (old_track->pad, "Sending tags %p: %"
3525 GST_PTR_FORMAT, new_track->tags, new_track->tags);
3526 gst_pad_push_event (new_track->pad,
3527 gst_event_new_tag (gst_tag_list_copy (new_track->tags)));
3530 gst_matroska_track_free (old_track);
3533 track_mismatch_error:
3534 gst_matroska_track_free (new_track);
3536 ret = GST_FLOW_ERROR;
3541 ret = gst_matroska_read_common_parse_skip (&demux->common, ebml,
3546 DEBUG_ELEMENT_STOP (demux, ebml, "Tracks", ret);
3548 if (ret != GST_FLOW_ERROR && demux->common.num_streams != num_tracks_found) {
3549 GST_ERROR_OBJECT (demux,
3550 "Mismatch on the number of tracks. Expected %du tracks, found %du",
3551 demux->common.num_streams, num_tracks_found);
3552 ret = GST_FLOW_ERROR;
3559 * Read signed/unsigned "EBML" numbers.
3560 * Return: number of bytes processed.
3564 gst_matroska_ebmlnum_uint (guint8 * data, guint size, guint64 * num)
3566 gint len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
3574 while (read <= 8 && !(total & len_mask)) {
3581 if ((total &= (len_mask - 1)) == len_mask - 1)
3586 if (data[n] == 0xff)
3588 total = (total << 8) | data[n];
3592 if (read == num_ffs && total != 0)
3601 gst_matroska_ebmlnum_sint (guint8 * data, guint size, gint64 * num)
3606 /* read as unsigned number first */
3607 if ((res = gst_matroska_ebmlnum_uint (data, size, &unum)) < 0)
3611 if (unum == G_MAXUINT64)
3614 *num = unum - ((1 << ((7 * res) - 1)) - 1);
3620 * Mostly used for subtitles. We add void filler data for each
3621 * lagging stream to make sure we don't deadlock.
3625 gst_matroska_demux_sync_streams (GstMatroskaDemux * demux)
3627 GstClockTime gap_threshold;
3630 GST_OBJECT_LOCK (demux);
3632 GST_LOG_OBJECT (demux, "Sync to %" GST_TIME_FORMAT,
3633 GST_TIME_ARGS (demux->common.segment.position));
3635 g_assert (demux->common.num_streams == demux->common.src->len);
3636 for (stream_nr = 0; stream_nr < demux->common.src->len; stream_nr++) {
3637 GstMatroskaTrackContext *context;
3639 context = g_ptr_array_index (demux->common.src, stream_nr);
3641 GST_LOG_OBJECT (demux,
3642 "Checking for resync on stream %d (%" GST_TIME_FORMAT ")", stream_nr,
3643 GST_TIME_ARGS (context->pos));
3645 /* Only send gap events on non-subtitle streams if lagging way behind.
3646 * The 0.5 second threshold for subtitle streams is also quite random. */
3647 if (context->type == GST_MATROSKA_TRACK_TYPE_SUBTITLE)
3648 gap_threshold = GST_SECOND / 2;
3650 gap_threshold = 3 * GST_SECOND;
3652 /* Lag need only be considered if we have advanced into requested segment */
3653 if (GST_CLOCK_TIME_IS_VALID (context->pos) &&
3654 GST_CLOCK_TIME_IS_VALID (demux->common.segment.position) &&
3655 demux->common.segment.position > demux->common.segment.start &&
3656 context->pos + gap_threshold < demux->common.segment.position) {
3659 guint64 start = context->pos;
3660 guint64 stop = demux->common.segment.position - gap_threshold;
3662 GST_DEBUG_OBJECT (demux,
3663 "Synchronizing stream %d with other by advancing time from %"
3664 GST_TIME_FORMAT " to %" GST_TIME_FORMAT, stream_nr,
3665 GST_TIME_ARGS (start), GST_TIME_ARGS (stop));
3667 context->pos = stop;
3669 event = gst_event_new_gap (start, stop - start);
3670 GST_OBJECT_UNLOCK (demux);
3671 gst_pad_push_event (context->pad, event);
3672 GST_OBJECT_LOCK (demux);
3676 GST_OBJECT_UNLOCK (demux);
3679 static GstFlowReturn
3680 gst_matroska_demux_push_stream_headers (GstMatroskaDemux * demux,
3681 GstMatroskaTrackContext * stream)
3683 GstFlowReturn ret = GST_FLOW_OK;
3686 num = gst_buffer_list_length (stream->stream_headers);
3687 for (i = 0; i < num; ++i) {
3690 buf = gst_buffer_list_get (stream->stream_headers, i);
3691 buf = gst_buffer_copy (buf);
3693 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_HEADER);
3695 if (stream->set_discont) {
3696 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
3697 stream->set_discont = FALSE;
3699 GST_BUFFER_FLAG_UNSET (buf, GST_BUFFER_FLAG_DISCONT);
3702 /* push out all headers in one go and use last flow return */
3703 ret = gst_pad_push (stream->pad, buf);
3706 /* don't need these any longer */
3707 gst_buffer_list_unref (stream->stream_headers);
3708 stream->stream_headers = NULL;
3711 ret = gst_flow_combiner_update_flow (demux->flowcombiner, ret);
3717 gst_matroska_demux_push_dvd_clut_change_event (GstMatroskaDemux * demux,
3718 GstMatroskaTrackContext * stream)
3722 g_assert (!strcmp (stream->codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_VOBSUB));
3724 if (!stream->codec_priv)
3727 /* ideally, VobSub private data should be parsed and stored more convenient
3728 * elsewhere, but for now, only interested in a small part */
3730 /* make sure we have terminating 0 */
3731 buf = g_strndup (stream->codec_priv, stream->codec_priv_size);
3733 /* just locate and parse palette part */
3734 start = strstr (buf, "palette:");
3739 guint8 r, g, b, y, u, v;
3742 while (g_ascii_isspace (*start))
3744 for (i = 0; i < 16; i++) {
3745 if (sscanf (start, "%06x", &col) != 1)
3748 while ((*start == ',') || g_ascii_isspace (*start))
3750 /* sigh, need to convert this from vobsub pseudo-RGB to YUV */
3751 r = (col >> 16) & 0xff;
3752 g = (col >> 8) & 0xff;
3754 y = CLAMP ((0.1494 * r + 0.6061 * g + 0.2445 * b) * 219 / 255 + 16, 0,
3756 u = CLAMP (0.6066 * r - 0.4322 * g - 0.1744 * b + 128, 0, 255);
3757 v = CLAMP (-0.08435 * r - 0.3422 * g + 0.4266 * b + 128, 0, 255);
3758 clut[i] = (y << 16) | (u << 8) | v;
3761 /* got them all without problems; build and send event */
3765 s = gst_structure_new ("application/x-gst-dvd", "event", G_TYPE_STRING,
3766 "dvd-spu-clut-change", "clut00", G_TYPE_INT, clut[0], "clut01",
3767 G_TYPE_INT, clut[1], "clut02", G_TYPE_INT, clut[2], "clut03",
3768 G_TYPE_INT, clut[3], "clut04", G_TYPE_INT, clut[4], "clut05",
3769 G_TYPE_INT, clut[5], "clut06", G_TYPE_INT, clut[6], "clut07",
3770 G_TYPE_INT, clut[7], "clut08", G_TYPE_INT, clut[8], "clut09",
3771 G_TYPE_INT, clut[9], "clut10", G_TYPE_INT, clut[10], "clut11",
3772 G_TYPE_INT, clut[11], "clut12", G_TYPE_INT, clut[12], "clut13",
3773 G_TYPE_INT, clut[13], "clut14", G_TYPE_INT, clut[14], "clut15",
3774 G_TYPE_INT, clut[15], NULL);
3776 gst_pad_push_event (stream->pad,
3777 gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM_STICKY, s));
3784 gst_matroska_demux_push_codec_data_all (GstMatroskaDemux * demux)
3788 g_assert (demux->common.num_streams == demux->common.src->len);
3789 for (stream_nr = 0; stream_nr < demux->common.src->len; stream_nr++) {
3790 GstMatroskaTrackContext *stream;
3792 stream = g_ptr_array_index (demux->common.src, stream_nr);
3794 if (stream->send_stream_headers) {
3795 if (stream->stream_headers != NULL) {
3796 gst_matroska_demux_push_stream_headers (demux, stream);
3798 /* FIXME: perhaps we can just disable and skip this stream then */
3799 GST_ELEMENT_ERROR (demux, STREAM, DECODE, (NULL),
3800 ("Failed to extract stream headers from codec private data"));
3802 stream->send_stream_headers = FALSE;
3805 if (stream->send_dvd_event) {
3806 gst_matroska_demux_push_dvd_clut_change_event (demux, stream);
3807 /* FIXME: should we send this event again after (flushing) seek ? */
3808 stream->send_dvd_event = FALSE;
3814 static GstFlowReturn
3815 gst_matroska_demux_add_mpeg_seq_header (GstElement * element,
3816 GstMatroskaTrackContext * stream, GstBuffer ** buf)
3819 guint seq_header_len;
3820 guint32 header, tmp;
3822 if (stream->codec_state) {
3823 seq_header = stream->codec_state;
3824 seq_header_len = stream->codec_state_size;
3825 } else if (stream->codec_priv) {
3826 seq_header = stream->codec_priv;
3827 seq_header_len = stream->codec_priv_size;
3832 /* Sequence header only needed for keyframes */
3833 if (GST_BUFFER_FLAG_IS_SET (*buf, GST_BUFFER_FLAG_DELTA_UNIT))
3836 if (gst_buffer_get_size (*buf) < 4)
3839 gst_buffer_extract (*buf, 0, &tmp, sizeof (guint32));
3840 header = GUINT32_FROM_BE (tmp);
3842 /* Sequence start code, if not found prepend */
3843 if (header != 0x000001b3) {
3846 GST_DEBUG_OBJECT (element, "Prepending MPEG sequence header");
3848 newbuf = gst_buffer_new_memdup (seq_header, seq_header_len);
3850 gst_buffer_copy_into (newbuf, *buf, GST_BUFFER_COPY_TIMESTAMPS |
3851 GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_MEMORY, 0,
3852 gst_buffer_get_size (*buf));
3854 gst_buffer_unref (*buf);
3861 static GstFlowReturn
3862 gst_matroska_demux_add_wvpk_header (GstElement * element,
3863 GstMatroskaTrackContext * stream, GstBuffer ** buf)
3865 GstMatroskaTrackAudioContext *audiocontext =
3866 (GstMatroskaTrackAudioContext *) stream;
3867 GstBuffer *newbuf = NULL;
3868 GstMapInfo map, outmap;
3869 guint8 *buf_data, *data;
3877 wvh.version = GST_READ_UINT16_LE (stream->codec_priv);
3880 wvh.total_samples = -1;
3881 wvh.block_index = audiocontext->wvpk_block_index;
3883 if (audiocontext->channels <= 2) {
3884 guint32 block_samples, tmp;
3885 gsize size = gst_buffer_get_size (*buf);
3888 GST_ERROR_OBJECT (element, "Too small wavpack buffer");
3889 gst_buffer_unmap (*buf, &map);
3890 return GST_FLOW_ERROR;
3893 gst_buffer_extract (*buf, 0, &tmp, sizeof (guint32));
3894 block_samples = GUINT32_FROM_LE (tmp);
3895 /* we need to reconstruct the header of the wavpack block */
3897 /* -20 because ck_size is the size of the wavpack block -8
3898 * and lace_size is the size of the wavpack block + 12
3899 * (the three guint32 of the header that already are in the buffer) */
3900 wvh.ck_size = size + WAVPACK4_HEADER_SIZE - 20;
3902 /* block_samples, flags and crc are already in the buffer */
3903 newbuf = gst_buffer_new_allocate (NULL, WAVPACK4_HEADER_SIZE - 12, NULL);
3905 gst_buffer_map (newbuf, &outmap, GST_MAP_WRITE);
3911 GST_WRITE_UINT32_LE (data + 4, wvh.ck_size);
3912 GST_WRITE_UINT16_LE (data + 8, wvh.version);
3913 GST_WRITE_UINT8 (data + 10, wvh.track_no);
3914 GST_WRITE_UINT8 (data + 11, wvh.index_no);
3915 GST_WRITE_UINT32_LE (data + 12, wvh.total_samples);
3916 GST_WRITE_UINT32_LE (data + 16, wvh.block_index);
3917 gst_buffer_unmap (newbuf, &outmap);
3919 /* Append data from buf: */
3920 gst_buffer_copy_into (newbuf, *buf, GST_BUFFER_COPY_TIMESTAMPS |
3921 GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_MEMORY, 0, size);
3923 gst_buffer_unref (*buf);
3925 audiocontext->wvpk_block_index += block_samples;
3927 guint8 *outdata = NULL;
3928 gsize buf_size, size;
3929 guint32 block_samples, flags, crc, blocksize;
3930 GstAdapter *adapter;
3932 adapter = gst_adapter_new ();
3934 gst_buffer_map (*buf, &map, GST_MAP_READ);
3935 buf_data = map.data;
3936 buf_size = map.size;
3939 GST_ERROR_OBJECT (element, "Too small wavpack buffer");
3940 gst_buffer_unmap (*buf, &map);
3941 g_object_unref (adapter);
3942 return GST_FLOW_ERROR;
3948 block_samples = GST_READ_UINT32_LE (data);
3953 flags = GST_READ_UINT32_LE (data);
3956 crc = GST_READ_UINT32_LE (data);
3959 blocksize = GST_READ_UINT32_LE (data);
3963 if (blocksize == 0 || size < blocksize) {
3964 GST_ERROR_OBJECT (element, "Too small wavpack buffer");
3965 gst_buffer_unmap (*buf, &map);
3966 g_object_unref (adapter);
3967 return GST_FLOW_ERROR;
3970 g_assert (newbuf == NULL);
3973 gst_buffer_new_allocate (NULL, WAVPACK4_HEADER_SIZE + blocksize,
3975 gst_buffer_map (newbuf, &outmap, GST_MAP_WRITE);
3976 outdata = outmap.data;
3984 GST_WRITE_UINT32_LE (outdata, blocksize + WAVPACK4_HEADER_SIZE - 8);
3985 GST_WRITE_UINT16_LE (outdata + 4, wvh.version);
3986 GST_WRITE_UINT8 (outdata + 6, wvh.track_no);
3987 GST_WRITE_UINT8 (outdata + 7, wvh.index_no);
3988 GST_WRITE_UINT32_LE (outdata + 8, wvh.total_samples);
3989 GST_WRITE_UINT32_LE (outdata + 12, wvh.block_index);
3990 GST_WRITE_UINT32_LE (outdata + 16, block_samples);
3991 GST_WRITE_UINT32_LE (outdata + 20, flags);
3992 GST_WRITE_UINT32_LE (outdata + 24, crc);
3995 memcpy (outdata, data, blocksize);
3997 gst_buffer_unmap (newbuf, &outmap);
3998 gst_adapter_push (adapter, newbuf);
4004 gst_buffer_unmap (*buf, &map);
4006 newbuf = gst_adapter_take_buffer (adapter, gst_adapter_available (adapter));
4007 g_object_unref (adapter);
4009 gst_buffer_copy_into (newbuf, *buf,
4010 GST_BUFFER_COPY_TIMESTAMPS | GST_BUFFER_COPY_FLAGS, 0, -1);
4011 gst_buffer_unref (*buf);
4014 audiocontext->wvpk_block_index += block_samples;
4020 static GstFlowReturn
4021 gst_matroska_demux_add_prores_header (GstElement * element,
4022 GstMatroskaTrackContext * stream, GstBuffer ** buf)
4024 GstBuffer *newbuf = gst_buffer_new_allocate (NULL, 8, NULL);
4028 if (!gst_buffer_map (newbuf, &map, GST_MAP_WRITE)) {
4029 GST_ERROR ("Failed to map newly allocated buffer");
4030 return GST_FLOW_ERROR;
4033 frame_size = gst_buffer_get_size (*buf);
4035 GST_WRITE_UINT32_BE (map.data, frame_size);
4041 gst_buffer_unmap (newbuf, &map);
4042 *buf = gst_buffer_append (newbuf, *buf);
4047 /* @text must be null-terminated */
4049 gst_matroska_demux_subtitle_chunk_has_tag (GstElement * element,
4054 g_return_val_if_fail (text != NULL, FALSE);
4056 /* yes, this might all lead to false positives ... */
4057 tag = (gchar *) text;
4058 while ((tag = strchr (tag, '<'))) {
4060 if (*tag != '\0' && *(tag + 1) == '>') {
4061 /* some common convenience ones */
4062 /* maybe any character will do here ? */
4075 if (strstr (text, "<span"))
4081 static GstFlowReturn
4082 gst_matroska_demux_check_subtitle_buffer (GstElement * element,
4083 GstMatroskaTrackContext * stream, GstBuffer ** buf)
4085 GstMatroskaTrackSubtitleContext *sub_stream;
4086 const gchar *encoding;
4091 gboolean needs_unmap = TRUE;
4093 sub_stream = (GstMatroskaTrackSubtitleContext *) stream;
4095 if (!gst_buffer_get_size (*buf) || !gst_buffer_map (*buf, &map, GST_MAP_READ))
4098 /* The subtitle buffer we push out should not include a NUL terminator as
4099 * part of the data. */
4100 if (map.data[map.size - 1] == '\0') {
4101 gst_buffer_set_size (*buf, map.size - 1);
4102 gst_buffer_unmap (*buf, &map);
4103 gst_buffer_map (*buf, &map, GST_MAP_READ);
4106 if (!sub_stream->invalid_utf8) {
4107 if (g_utf8_validate ((gchar *) map.data, map.size, NULL)) {
4110 GST_WARNING_OBJECT (element, "subtitle stream %" G_GUINT64_FORMAT
4111 " is not valid UTF-8, this is broken according to the matroska"
4112 " specification", stream->num);
4113 sub_stream->invalid_utf8 = TRUE;
4116 /* file with broken non-UTF8 subtitle, do the best we can do to fix it */
4117 encoding = g_getenv ("GST_SUBTITLE_ENCODING");
4118 if (encoding == NULL || *encoding == '\0') {
4119 /* if local encoding is UTF-8 and no encoding specified
4120 * via the environment variable, assume ISO-8859-15 */
4121 if (g_get_charset (&encoding)) {
4122 encoding = "ISO-8859-15";
4127 g_convert_with_fallback ((gchar *) map.data, map.size, "UTF-8", encoding,
4128 (char *) "*", NULL, NULL, &err);
4131 GST_LOG_OBJECT (element, "could not convert string from '%s' to UTF-8: %s",
4132 encoding, err->message);
4136 /* invalid input encoding, fall back to ISO-8859-15 (always succeeds) */
4137 encoding = "ISO-8859-15";
4139 g_convert_with_fallback ((gchar *) map.data, map.size, "UTF-8",
4140 encoding, (char *) "*", NULL, NULL, NULL);
4143 GST_LOG_OBJECT (element, "converted subtitle text from %s to UTF-8 %s",
4144 encoding, (err) ? "(using ISO-8859-15 as fallback)" : "");
4147 utf8 = g_strdup ("invalid subtitle");
4149 newbuf = gst_buffer_new_wrapped (utf8, strlen (utf8));
4150 gst_buffer_unmap (*buf, &map);
4151 gst_buffer_copy_into (newbuf, *buf,
4152 GST_BUFFER_COPY_TIMESTAMPS | GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_META,
4154 gst_buffer_unref (*buf);
4157 gst_buffer_map (*buf, &map, GST_MAP_READ);
4161 if (sub_stream->check_markup) {
4162 /* caps claim markup text, so we need to escape text,
4163 * except if text is already markup and then needs no further escaping */
4164 sub_stream->seen_markup_tag = sub_stream->seen_markup_tag ||
4165 gst_matroska_demux_subtitle_chunk_has_tag (element, (gchar *) map.data);
4167 if (!sub_stream->seen_markup_tag) {
4168 utf8 = g_markup_escape_text ((gchar *) map.data, map.size);
4170 newbuf = gst_buffer_new_wrapped (utf8, strlen (utf8));
4171 gst_buffer_unmap (*buf, &map);
4172 gst_buffer_copy_into (newbuf, *buf,
4173 GST_BUFFER_COPY_TIMESTAMPS | GST_BUFFER_COPY_FLAGS |
4174 GST_BUFFER_COPY_META, 0, -1);
4175 gst_buffer_unref (*buf);
4178 needs_unmap = FALSE;
4183 gst_buffer_unmap (*buf, &map);
4188 static GstFlowReturn
4189 gst_matroska_demux_check_aac (GstElement * element,
4190 GstMatroskaTrackContext * stream, GstBuffer ** buf)
4195 gst_buffer_extract (*buf, 0, data, 2);
4196 size = gst_buffer_get_size (*buf);
4198 if (size > 2 && data[0] == 0xff && (data[1] >> 4 == 0x0f)) {
4201 /* tss, ADTS data, remove codec_data
4202 * still assume it is at least parsed */
4203 stream->caps = gst_caps_make_writable (stream->caps);
4204 s = gst_caps_get_structure (stream->caps, 0);
4206 gst_structure_remove_field (s, "codec_data");
4207 gst_pad_set_caps (stream->pad, stream->caps);
4208 GST_DEBUG_OBJECT (element, "ADTS AAC audio data; removing codec-data, "
4209 "new caps: %" GST_PTR_FORMAT, stream->caps);
4212 /* disable subsequent checking */
4213 stream->postprocess_frame = NULL;
4219 gst_matroska_demux_align_buffer (GstMatroskaDemux * demux,
4220 GstBuffer * buffer, gsize alignment)
4224 gst_buffer_map (buffer, &map, GST_MAP_READ);
4226 if (map.size < sizeof (guintptr)) {
4227 gst_buffer_unmap (buffer, &map);
4231 if (((guintptr) map.data) & (alignment - 1)) {
4232 GstBuffer *new_buffer;
4233 GstAllocationParams params = { 0, alignment - 1, 0, 0, };
4235 new_buffer = gst_buffer_new_allocate (NULL,
4236 gst_buffer_get_size (buffer), ¶ms);
4238 /* Copy data "by hand", so ensure alignment is kept: */
4239 gst_buffer_fill (new_buffer, 0, map.data, map.size);
4241 gst_buffer_copy_into (new_buffer, buffer, GST_BUFFER_COPY_METADATA, 0, -1);
4242 GST_DEBUG_OBJECT (demux,
4243 "We want output aligned on %" G_GSIZE_FORMAT ", reallocated",
4246 gst_buffer_unmap (buffer, &map);
4247 gst_buffer_unref (buffer);
4252 gst_buffer_unmap (buffer, &map);
4263 static GstFlowReturn
4264 gst_matroska_demux_parse_blockmore (GstMatroskaDemux * demux,
4265 GstEbmlRead * ebml, GQueue * additions)
4269 guint64 block_id = 1;
4270 guint64 datalen = 0;
4271 guint8 *data = NULL;
4273 ret = gst_ebml_read_master (ebml, &id); /* GST_MATROSKA_ID_BLOCKMORE */
4274 if (ret != GST_FLOW_OK)
4277 /* read all BlockMore sub-entries */
4278 while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
4280 if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
4284 case GST_MATROSKA_ID_BLOCKADDID:
4285 ret = gst_ebml_read_uint (ebml, &id, &block_id);
4289 case GST_MATROSKA_ID_BLOCKADDITIONAL:
4293 ret = gst_ebml_read_binary (ebml, &id, &data, &datalen);
4296 ret = gst_matroska_read_common_parse_skip (&demux->common, ebml,
4302 if (data != NULL && datalen > 0) {
4303 BlockAddition *blockadd = g_new (BlockAddition, 1);
4305 GST_LOG_OBJECT (demux, "BlockAddition %" G_GUINT64_FORMAT ": "
4306 "%" G_GUINT64_FORMAT " bytes", block_id, datalen);
4307 GST_MEMDUMP_OBJECT (demux, "BlockAdditional", data, datalen);
4308 blockadd->data = data;
4309 blockadd->size = datalen;
4310 blockadd->id = block_id;
4311 g_queue_push_tail (additions, blockadd);
4312 GST_LOG_OBJECT (demux, "now %d pending block additions", additions->length);
4323 static GstFlowReturn
4324 gst_matroska_demux_parse_blockadditions (GstMatroskaDemux * demux,
4325 GstEbmlRead * ebml, GQueue * additions)
4330 ret = gst_ebml_read_master (ebml, &id); /* GST_MATROSKA_ID_BLOCKADDITIONS */
4331 if (ret != GST_FLOW_OK)
4334 /* read all BlockMore sub-entries */
4335 while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
4337 if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
4340 if (id == GST_MATROSKA_ID_BLOCKMORE) {
4341 DEBUG_ELEMENT_START (demux, ebml, "BlockMore");
4342 ret = gst_matroska_demux_parse_blockmore (demux, ebml, additions);
4343 DEBUG_ELEMENT_STOP (demux, ebml, "BlockMore", ret);
4344 if (ret != GST_FLOW_OK)
4347 GST_WARNING_OBJECT (demux, "Expected BlockMore, got %x", id);
4354 static GstFlowReturn
4355 gst_matroska_demux_parse_blockgroup_or_simpleblock (GstMatroskaDemux * demux,
4356 GstEbmlRead * ebml, guint64 cluster_time, guint64 cluster_offset,
4357 gboolean is_simpleblock)
4359 GstMatroskaTrackContext *stream = NULL;
4360 GstFlowReturn ret = GST_FLOW_OK;
4361 gboolean readblock = FALSE;
4363 guint64 block_duration = -1;
4364 gint64 block_discardpadding = 0;
4365 GstBuffer *buf = NULL;
4367 gint stream_num = -1, n, laces = 0;
4369 gint *lace_size = NULL;
4372 gint64 referenceblock = 0;
4374 GstClockTime buffer_timestamp;
4375 GQueue additions = G_QUEUE_INIT;
4377 offset = gst_ebml_read_get_offset (ebml);
4379 while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
4380 if (!is_simpleblock) {
4381 if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK) {
4385 id = GST_MATROSKA_ID_SIMPLEBLOCK;
4389 /* one block inside the group. Note, block parsing is one
4390 * of the harder things, so this code is a bit complicated.
4391 * See http://www.matroska.org/ for documentation. */
4392 case GST_MATROSKA_ID_SIMPLEBLOCK:
4393 case GST_MATROSKA_ID_BLOCK:
4399 gst_buffer_unmap (buf, &map);
4400 gst_buffer_unref (buf);
4403 if ((ret = gst_ebml_read_buffer (ebml, &id, &buf)) != GST_FLOW_OK)
4406 gst_buffer_map (buf, &map, GST_MAP_READ);
4410 /* first byte(s): blocknum */
4411 if ((n = gst_matroska_ebmlnum_uint (data, size, &num)) < 0)
4416 /* fetch stream from num */
4417 stream_num = gst_matroska_read_common_stream_from_num (&demux->common,
4419 if (G_UNLIKELY (size < 3)) {
4420 GST_WARNING_OBJECT (demux, "Invalid size %u", size);
4421 /* non-fatal, try next block(group) */
4424 } else if (G_UNLIKELY (stream_num < 0 ||
4425 stream_num >= demux->common.num_streams)) {
4426 /* let's not give up on a stray invalid track number */
4427 GST_WARNING_OBJECT (demux,
4428 "Invalid stream %d for track number %" G_GUINT64_FORMAT
4429 "; ignoring block", stream_num, num);
4433 stream = g_ptr_array_index (demux->common.src, stream_num);
4435 /* time (relative to cluster time) */
4436 time = ((gint16) GST_READ_UINT16_BE (data));
4439 flags = GST_READ_UINT8 (data);
4443 GST_LOG_OBJECT (demux, "time %" G_GUINT64_FORMAT ", flags %d", time,
4446 switch ((flags & 0x06) >> 1) {
4447 case 0x0: /* no lacing */
4449 lace_size = g_new (gint, 1);
4450 lace_size[0] = size;
4453 case 0x1: /* xiph lacing */
4454 case 0x2: /* fixed-size lacing */
4455 case 0x3: /* EBML lacing */
4457 goto invalid_lacing;
4458 laces = GST_READ_UINT8 (data) + 1;
4461 lace_size = g_new0 (gint, laces);
4463 switch ((flags & 0x06) >> 1) {
4464 case 0x1: /* xiph lacing */ {
4465 guint temp, total = 0;
4467 for (n = 0; ret == GST_FLOW_OK && n < laces - 1; n++) {
4470 goto invalid_lacing;
4471 temp = GST_READ_UINT8 (data);
4472 lace_size[n] += temp;
4478 total += lace_size[n];
4480 lace_size[n] = size - total;
4484 case 0x2: /* fixed-size lacing */
4485 for (n = 0; n < laces; n++)
4486 lace_size[n] = size / laces;
4489 case 0x3: /* EBML lacing */ {
4492 if ((n = gst_matroska_ebmlnum_uint (data, size, &num)) < 0)
4496 total = lace_size[0] = num;
4497 for (n = 1; ret == GST_FLOW_OK && n < laces - 1; n++) {
4501 if ((r = gst_matroska_ebmlnum_sint (data, size, &snum)) < 0)
4505 lace_size[n] = lace_size[n - 1] + snum;
4506 total += lace_size[n];
4509 lace_size[n] = size - total;
4516 if (ret != GST_FLOW_OK)
4523 case GST_MATROSKA_ID_BLOCKADDITIONS:
4525 DEBUG_ELEMENT_START (demux, ebml, "BlockAdditions");
4526 ret = gst_matroska_demux_parse_blockadditions (demux, ebml, &additions);
4527 DEBUG_ELEMENT_STOP (demux, ebml, "BlockAdditions", ret);
4531 case GST_MATROSKA_ID_BLOCKDURATION:{
4532 ret = gst_ebml_read_uint (ebml, &id, &block_duration);
4533 GST_DEBUG_OBJECT (demux, "BlockDuration: %" G_GUINT64_FORMAT,
4538 case GST_MATROSKA_ID_DISCARDPADDING:{
4539 ret = gst_ebml_read_sint (ebml, &id, &block_discardpadding);
4540 GST_DEBUG_OBJECT (demux, "DiscardPadding: %" GST_STIME_FORMAT,
4541 GST_STIME_ARGS (block_discardpadding));
4545 case GST_MATROSKA_ID_REFERENCEBLOCK:{
4546 ret = gst_ebml_read_sint (ebml, &id, &referenceblock);
4547 GST_DEBUG_OBJECT (demux, "ReferenceBlock: %" G_GINT64_FORMAT,
4552 case GST_MATROSKA_ID_CODECSTATE:{
4554 guint64 data_len = 0;
4557 gst_ebml_read_binary (ebml, &id, &data,
4558 &data_len)) != GST_FLOW_OK)
4561 if (G_UNLIKELY (stream == NULL)) {
4562 GST_WARNING_OBJECT (demux,
4563 "Unexpected CodecState subelement - ignoring");
4567 g_free (stream->codec_state);
4568 stream->codec_state = data;
4569 stream->codec_state_size = data_len;
4571 /* Decode if necessary */
4572 if (stream->encodings && stream->encodings->len > 0
4573 && stream->codec_state && stream->codec_state_size > 0) {
4574 if (!gst_matroska_decode_data (stream->encodings,
4575 &stream->codec_state, &stream->codec_state_size,
4576 GST_MATROSKA_TRACK_ENCODING_SCOPE_CODEC_DATA, TRUE)) {
4577 GST_WARNING_OBJECT (demux, "Decoding codec state failed");
4581 GST_DEBUG_OBJECT (demux, "CodecState of %" G_GSIZE_FORMAT " bytes",
4582 stream->codec_state_size);
4587 ret = gst_matroska_read_common_parse_skip (&demux->common, ebml,
4591 case GST_MATROSKA_ID_BLOCKVIRTUAL:
4592 case GST_MATROSKA_ID_REFERENCEPRIORITY:
4593 case GST_MATROSKA_ID_REFERENCEVIRTUAL:
4594 case GST_MATROSKA_ID_SLICES:
4595 GST_DEBUG_OBJECT (demux,
4596 "Skipping BlockGroup subelement 0x%x - ignoring", id);
4597 ret = gst_ebml_read_skip (ebml);
4605 /* reading a number or so could have failed */
4606 if (ret != GST_FLOW_OK)
4609 if (ret == GST_FLOW_OK && readblock) {
4610 gboolean invisible_frame = FALSE;
4611 gboolean delta_unit = FALSE;
4612 guint64 duration = 0;
4613 gint64 lace_time = 0;
4614 GstEvent *protect_event;
4616 stream = g_ptr_array_index (demux->common.src, stream_num);
4618 if (cluster_time != GST_CLOCK_TIME_NONE) {
4619 /* FIXME: What to do with negative timestamps? Give timestamp 0 or -1?
4620 * Drop unless the lace contains timestamp 0? */
4621 if (time < 0 && (-time) > cluster_time) {
4624 if (stream->timecodescale == 1.0)
4625 lace_time = (cluster_time + time) * demux->common.time_scale;
4628 gst_util_guint64_to_gdouble ((cluster_time + time) *
4629 demux->common.time_scale) * stream->timecodescale;
4632 lace_time = GST_CLOCK_TIME_NONE;
4634 /* Send the GST_PROTECTION event */
4635 while ((protect_event = g_queue_pop_head (&stream->protection_event_queue))) {
4636 GST_TRACE_OBJECT (demux, "pushing protection event for stream %d:%s",
4637 stream->index, GST_STR_NULL (stream->name));
4638 gst_pad_push_event (stream->pad, protect_event);
4641 /* need to refresh segment info ASAP */
4642 if (GST_CLOCK_TIME_IS_VALID (lace_time) && demux->need_segment) {
4643 GstSegment *segment = &demux->common.segment;
4645 GstEvent *segment_event;
4647 if (!GST_CLOCK_TIME_IS_VALID (demux->stream_start_time)) {
4648 demux->stream_start_time = lace_time;
4649 GST_DEBUG_OBJECT (demux,
4650 "Setting stream start time to %" GST_TIME_FORMAT,
4651 GST_TIME_ARGS (lace_time));
4653 clace_time = MAX (lace_time, demux->stream_start_time);
4654 if (GST_CLOCK_TIME_IS_VALID (demux->common.segment.position) &&
4655 demux->common.segment.position != 0) {
4656 GST_DEBUG_OBJECT (demux,
4657 "using stored seek position %" GST_TIME_FORMAT,
4658 GST_TIME_ARGS (demux->common.segment.position));
4659 clace_time = demux->common.segment.position;
4660 segment->position = GST_CLOCK_TIME_NONE;
4662 segment->start = clace_time;
4663 segment->stop = demux->common.segment.stop;
4664 segment->time = segment->start - demux->stream_start_time;
4665 segment->position = segment->start - demux->stream_start_time;
4666 GST_DEBUG_OBJECT (demux,
4667 "generated segment starting at %" GST_TIME_FORMAT ": %"
4668 GST_SEGMENT_FORMAT, GST_TIME_ARGS (lace_time), segment);
4669 /* now convey our segment notion downstream */
4670 segment_event = gst_event_new_segment (segment);
4671 if (demux->segment_seqnum)
4672 gst_event_set_seqnum (segment_event, demux->segment_seqnum);
4673 gst_matroska_demux_send_event (demux, segment_event);
4674 demux->need_segment = FALSE;
4675 demux->segment_seqnum = 0;
4678 /* send pending codec data headers for all streams,
4679 * before we perform sync across all streams */
4680 gst_matroska_demux_push_codec_data_all (demux);
4682 if (block_duration != -1) {
4683 if (stream->timecodescale == 1.0)
4684 duration = gst_util_uint64_scale (block_duration,
4685 demux->common.time_scale, 1);
4688 gst_util_gdouble_to_guint64 (gst_util_guint64_to_gdouble
4689 (gst_util_uint64_scale (block_duration, demux->common.time_scale,
4690 1)) * stream->timecodescale);
4691 } else if (stream->default_duration) {
4692 duration = stream->default_duration * laces;
4694 /* else duration is diff between timecode of this and next block */
4696 if (stream->type == GST_MATROSKA_TRACK_TYPE_VIDEO) {
4697 /* For SimpleBlock, look at the keyframe bit in flags. Otherwise,
4698 a ReferenceBlock implies that this is not a keyframe. In either
4699 case, it only makes sense for video streams. */
4700 if ((is_simpleblock && !(flags & 0x80)) || referenceblock) {
4702 invisible_frame = ((flags & 0x08)) &&
4703 (!strcmp (stream->codec_id, GST_MATROSKA_CODEC_ID_VIDEO_VP8) ||
4704 !strcmp (stream->codec_id, GST_MATROSKA_CODEC_ID_VIDEO_VP9) ||
4705 !strcmp (stream->codec_id, GST_MATROSKA_CODEC_ID_VIDEO_AV1));
4708 /* If we're doing a keyframe-only trickmode, only push keyframes on video
4711 && demux->common.segment.
4712 flags & GST_SEGMENT_FLAG_TRICKMODE_KEY_UNITS) {
4713 GST_LOG_OBJECT (demux, "Skipping non-keyframe on stream %d",
4720 for (n = 0; n < laces; n++) {
4723 if (G_UNLIKELY (lace_size[n] > size)) {
4724 GST_WARNING_OBJECT (demux, "Invalid lace size");
4728 /* QoS for video track with an index. the assumption is that
4729 index entries point to keyframes, but if that is not true we
4730 will instead skip until the next keyframe. */
4731 if (GST_CLOCK_TIME_IS_VALID (lace_time) &&
4732 stream->type == GST_MATROSKA_TRACK_TYPE_VIDEO &&
4733 stream->index_table && demux->common.segment.rate > 0.0) {
4734 GstMatroskaTrackVideoContext *videocontext =
4735 (GstMatroskaTrackVideoContext *) stream;
4736 GstClockTime earliest_time;
4737 GstClockTime earliest_stream_time;
4739 GST_OBJECT_LOCK (demux);
4740 earliest_time = videocontext->earliest_time;
4741 GST_OBJECT_UNLOCK (demux);
4742 earliest_stream_time =
4743 gst_segment_position_from_running_time (&demux->common.segment,
4744 GST_FORMAT_TIME, earliest_time);
4746 if (GST_CLOCK_TIME_IS_VALID (lace_time) &&
4747 GST_CLOCK_TIME_IS_VALID (earliest_stream_time) &&
4748 lace_time <= earliest_stream_time) {
4749 /* find index entry (keyframe) <= earliest_stream_time */
4750 GstMatroskaIndex *entry =
4751 gst_util_array_binary_search (stream->index_table->data,
4752 stream->index_table->len, sizeof (GstMatroskaIndex),
4753 (GCompareDataFunc) gst_matroska_index_seek_find,
4754 GST_SEARCH_MODE_BEFORE, &earliest_stream_time, NULL);
4756 /* if that entry (keyframe) is after the current the current
4757 buffer, we can skip pushing (and thus decoding) all
4758 buffers until that keyframe. */
4759 if (entry && GST_CLOCK_TIME_IS_VALID (entry->time) &&
4760 entry->time > lace_time) {
4761 GST_LOG_OBJECT (demux, "Skipping lace before late keyframe");
4762 stream->set_discont = TRUE;
4768 sub = gst_buffer_copy_region (buf, GST_BUFFER_COPY_ALL,
4769 gst_buffer_get_size (buf) - size, lace_size[n]);
4770 GST_DEBUG_OBJECT (demux, "created subbuffer %p", sub);
4773 GST_BUFFER_FLAG_SET (sub, GST_BUFFER_FLAG_DELTA_UNIT);
4775 GST_BUFFER_FLAG_UNSET (sub, GST_BUFFER_FLAG_DELTA_UNIT);
4777 if (invisible_frame)
4778 GST_BUFFER_FLAG_SET (sub, GST_BUFFER_FLAG_DECODE_ONLY);
4780 if (stream->encodings != NULL && stream->encodings->len > 0)
4781 sub = gst_matroska_decode_buffer (stream, sub);
4784 GST_WARNING_OBJECT (demux, "Decoding buffer failed");
4788 if (!stream->dts_only) {
4789 GST_BUFFER_PTS (sub) = lace_time;
4791 GST_BUFFER_DTS (sub) = lace_time;
4792 if (stream->intra_only)
4793 GST_BUFFER_PTS (sub) = lace_time;
4796 buffer_timestamp = gst_matroska_track_get_buffer_timestamp (stream, sub);
4798 if (GST_CLOCK_TIME_IS_VALID (lace_time)) {
4799 GstClockTime last_stop_end;
4801 /* Check if this stream is after segment stop,
4802 * but only terminate if we hit the next keyframe,
4803 * to make sure that all frames potentially inside the segment
4804 * are available to the decoder for decoding / reordering.*/
4805 if (!delta_unit && GST_CLOCK_TIME_IS_VALID (demux->common.segment.stop)
4806 && lace_time >= demux->common.segment.stop) {
4807 GST_DEBUG_OBJECT (demux,
4808 "Stream %d lace time: %" GST_TIME_FORMAT " after segment stop: %"
4809 GST_TIME_FORMAT, stream->index, GST_TIME_ARGS (lace_time),
4810 GST_TIME_ARGS (demux->common.segment.stop));
4811 gst_buffer_unref (sub);
4814 if (offset >= stream->to_offset
4815 || (GST_CLOCK_TIME_IS_VALID (demux->to_time)
4816 && lace_time > demux->to_time)) {
4817 GST_DEBUG_OBJECT (demux, "Stream %d after playback section",
4819 gst_buffer_unref (sub);
4823 /* handle gaps, e.g. non-zero start-time, or an cue index entry
4824 * that landed us with timestamps not quite intended */
4825 GST_OBJECT_LOCK (demux);
4826 if (demux->max_gap_time &&
4827 GST_CLOCK_TIME_IS_VALID (demux->last_stop_end) &&
4828 demux->common.segment.rate > 0.0) {
4829 GstClockTimeDiff diff;
4831 /* only send segments with increasing start times,
4832 * otherwise if these go back and forth downstream (sinks) increase
4833 * accumulated time and running_time */
4834 diff = GST_CLOCK_DIFF (demux->last_stop_end, lace_time);
4835 if (diff > 0 && diff > demux->max_gap_time
4836 && lace_time > demux->common.segment.start
4837 && (!GST_CLOCK_TIME_IS_VALID (demux->common.segment.stop)
4838 || lace_time < demux->common.segment.stop)) {
4840 GST_DEBUG_OBJECT (demux,
4841 "Gap of %" G_GINT64_FORMAT " ns detected in"
4842 "stream %d (%" GST_TIME_FORMAT " -> %" GST_TIME_FORMAT "). "
4843 "Sending updated SEGMENT events", diff,
4844 stream->index, GST_TIME_ARGS (stream->pos),
4845 GST_TIME_ARGS (lace_time));
4847 event = gst_event_new_gap (demux->last_stop_end, diff);
4848 GST_OBJECT_UNLOCK (demux);
4849 gst_pad_push_event (stream->pad, event);
4850 GST_OBJECT_LOCK (demux);
4854 if (!GST_CLOCK_TIME_IS_VALID (demux->common.segment.position)
4855 || demux->common.segment.position < lace_time) {
4856 demux->common.segment.position = lace_time;
4858 GST_OBJECT_UNLOCK (demux);
4860 last_stop_end = lace_time;
4862 GST_BUFFER_DURATION (sub) = duration / laces;
4863 last_stop_end += GST_BUFFER_DURATION (sub);
4866 if (!GST_CLOCK_TIME_IS_VALID (demux->last_stop_end) ||
4867 demux->last_stop_end < last_stop_end)
4868 demux->last_stop_end = last_stop_end;
4870 GST_OBJECT_LOCK (demux);
4871 if (demux->common.segment.duration == -1 ||
4872 demux->stream_start_time + demux->common.segment.duration <
4874 demux->common.segment.duration =
4875 last_stop_end - demux->stream_start_time;
4876 GST_OBJECT_UNLOCK (demux);
4877 if (!demux->invalid_duration) {
4878 gst_element_post_message (GST_ELEMENT_CAST (demux),
4879 gst_message_new_duration_changed (GST_OBJECT_CAST (demux)));
4880 demux->invalid_duration = TRUE;
4883 GST_OBJECT_UNLOCK (demux);
4887 stream->pos = lace_time;
4889 gst_matroska_demux_sync_streams (demux);
4891 if (stream->set_discont) {
4892 GST_DEBUG_OBJECT (demux, "marking DISCONT");
4893 GST_BUFFER_FLAG_SET (sub, GST_BUFFER_FLAG_DISCONT);
4894 stream->set_discont = FALSE;
4896 GST_BUFFER_FLAG_UNSET (sub, GST_BUFFER_FLAG_DISCONT);
4899 /* reverse playback book-keeping */
4900 if (!GST_CLOCK_TIME_IS_VALID (stream->from_time))
4901 stream->from_time = lace_time;
4902 if (stream->from_offset == -1)
4903 stream->from_offset = offset;
4905 GST_DEBUG_OBJECT (demux,
4906 "Pushing lace %d, data of size %" G_GSIZE_FORMAT
4907 " for stream %d, time=%" GST_TIME_FORMAT " and duration=%"
4908 GST_TIME_FORMAT, n, gst_buffer_get_size (sub), stream_num,
4909 GST_TIME_ARGS (buffer_timestamp),
4910 GST_TIME_ARGS (GST_BUFFER_DURATION (sub)));
4913 if (demux->common.element_index) {
4914 if (stream->index_writer_id == -1)
4915 gst_index_get_writer_id (demux->common.element_index,
4916 GST_OBJECT (stream->pad), &stream->index_writer_id);
4918 GST_LOG_OBJECT (demux, "adding association %" GST_TIME_FORMAT "-> %"
4919 G_GUINT64_FORMAT " for writer id %d",
4920 GST_TIME_ARGS (buffer_timestamp), cluster_offset,
4921 stream->index_writer_id);
4922 gst_index_add_association (demux->common.element_index,
4923 stream->index_writer_id, GST_BUFFER_FLAG_IS_SET (sub,
4924 GST_BUFFER_FLAG_DELTA_UNIT) ? 0 : GST_ASSOCIATION_FLAG_KEY_UNIT,
4925 GST_FORMAT_TIME, buffer_timestamp, GST_FORMAT_BYTES, cluster_offset,
4930 /* Postprocess the buffers depending on the codec used */
4931 if (stream->postprocess_frame) {
4932 GST_LOG_OBJECT (demux, "running post process");
4933 ret = stream->postprocess_frame (GST_ELEMENT (demux), stream, &sub);
4936 /* At this point, we have a sub-buffer pointing at data within a larger
4937 buffer. This data might not be aligned with anything. If the data is
4938 raw samples though, we want it aligned to the raw type (eg, 4 bytes
4939 for 32 bit samples, etc), or bad things will happen downstream as
4940 elements typically assume minimal alignment.
4941 Therefore, create an aligned copy if necessary. */
4942 sub = gst_matroska_demux_align_buffer (demux, sub, stream->alignment);
4944 if (!strcmp (stream->codec_id, GST_MATROSKA_CODEC_ID_AUDIO_OPUS)) {
4945 guint64 start_clip = 0, end_clip = 0;
4947 /* Codec delay is part of the timestamps */
4948 if (GST_BUFFER_PTS_IS_VALID (sub) && stream->codec_delay) {
4949 if (GST_BUFFER_PTS (sub) > stream->codec_delay) {
4950 GST_BUFFER_PTS (sub) -= stream->codec_delay;
4952 GST_BUFFER_PTS (sub) = 0;
4954 /* Opus GstAudioClippingMeta units are scaled by 48000/sample_rate.
4955 That is, if a Opus track has audio encoded at 24000 Hz and 132
4956 samples need to be clipped, GstAudioClippingMeta.start will be
4957 set to 264. (This is also the case for buffer offsets.)
4958 Opus sample rates are always divisors of 48000 Hz, which is the
4959 maximum allowed sample rate. */
4961 gst_util_uint64_scale_round (stream->codec_delay, 48000,
4964 if (GST_BUFFER_DURATION_IS_VALID (sub)) {
4965 if (GST_BUFFER_DURATION (sub) > stream->codec_delay)
4966 GST_BUFFER_DURATION (sub) -= stream->codec_delay;
4968 GST_BUFFER_DURATION (sub) = 0;
4973 if (block_discardpadding) {
4975 gst_util_uint64_scale_round (block_discardpadding, 48000,
4979 if (start_clip || end_clip) {
4980 gst_buffer_add_audio_clipping_meta (sub, GST_FORMAT_DEFAULT,
4981 start_clip, end_clip);
4985 if (GST_BUFFER_PTS_IS_VALID (sub)) {
4986 stream->pos = GST_BUFFER_PTS (sub);
4987 if (GST_BUFFER_DURATION_IS_VALID (sub))
4988 stream->pos += GST_BUFFER_DURATION (sub);
4989 } else if (GST_BUFFER_DTS_IS_VALID (sub)) {
4990 stream->pos = GST_BUFFER_DTS (sub);
4991 if (GST_BUFFER_DURATION_IS_VALID (sub))
4992 stream->pos += GST_BUFFER_DURATION (sub);
4995 /* Attach BlockAdditions to buffer; we assume a single buffer per group
4997 if (additions.length > 0) {
4998 BlockAddition *blockadd;
5001 GST_FIXME_OBJECT (demux, "Fix block additions with laced buffers");
5003 while ((blockadd = g_queue_pop_head (&additions))) {
5004 GstMatroskaTrackVideoContext *videocontext =
5005 (GstMatroskaTrackVideoContext *) stream;
5006 if (blockadd->id == 1 && videocontext->alpha_mode
5007 && (!strcmp (stream->codec_id, GST_MATROSKA_CODEC_ID_VIDEO_VP8)
5008 || !strcmp (stream->codec_id,
5009 GST_MATROSKA_CODEC_ID_VIDEO_VP9))) {
5010 GstBuffer *alpha_buffer;
5012 GST_TRACE_OBJECT (demux, "adding block addition %u as VP8/VP9 "
5013 "alpha meta to buffer %p, %u bytes", (guint) blockadd->id, buf,
5014 (guint) blockadd->size);
5016 alpha_buffer = gst_buffer_new_wrapped (blockadd->data,
5018 gst_buffer_copy_into (alpha_buffer, sub,
5019 GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_TIMESTAMPS, 0, -1);
5020 gst_buffer_add_video_codec_alpha_meta (sub, alpha_buffer);
5022 g_free (blockadd->data);
5028 ret = gst_pad_push (stream->pad, sub);
5030 if (demux->common.segment.rate < 0) {
5031 if (lace_time > demux->common.segment.stop && ret == GST_FLOW_EOS) {
5032 /* In reverse playback we can get a GST_FLOW_EOS when
5033 * we are at the end of the segment, so we just need to jump
5034 * back to the previous section. */
5035 GST_DEBUG_OBJECT (demux, "downstream has reached end of segment");
5040 ret = gst_flow_combiner_update_pad_flow (demux->flowcombiner,
5044 size -= lace_size[n];
5045 if (lace_time != GST_CLOCK_TIME_NONE && duration)
5046 lace_time += duration / laces;
5048 lace_time = GST_CLOCK_TIME_NONE;
5054 gst_buffer_unmap (buf, &map);
5055 gst_buffer_unref (buf);
5059 BlockAddition *blockadd;
5061 while ((blockadd = g_queue_pop_head (&additions))) {
5062 g_free (blockadd->data);
5074 ret = gst_flow_combiner_update_pad_flow (demux->flowcombiner, stream->pad,
5080 GST_ELEMENT_WARNING (demux, STREAM, DEMUX, (NULL), ("Invalid lacing size"));
5081 /* non-fatal, try next block(group) */
5087 GST_ELEMENT_WARNING (demux, STREAM, DEMUX, (NULL), ("Data error"));
5088 /* non-fatal, try next block(group) */
5094 /* return FALSE if block(group) should be skipped (due to a seek) */
5095 static inline gboolean
5096 gst_matroska_demux_seek_block (GstMatroskaDemux * demux)
5098 if (G_UNLIKELY (demux->seek_block)) {
5099 if (!(--demux->seek_block)) {
5102 GST_LOG_OBJECT (demux, "should skip block due to seek");
5110 static GstFlowReturn
5111 gst_matroska_demux_parse_contents_seekentry (GstMatroskaDemux * demux,
5115 guint64 seek_pos = (guint64) - 1;
5116 guint32 seek_id = 0;
5119 DEBUG_ELEMENT_START (demux, ebml, "Seek");
5121 if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
5122 DEBUG_ELEMENT_STOP (demux, ebml, "Seek", ret);
5126 while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
5127 if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
5131 case GST_MATROSKA_ID_SEEKID:
5135 if ((ret = gst_ebml_read_uint (ebml, &id, &t)) != GST_FLOW_OK)
5138 GST_DEBUG_OBJECT (demux, "SeekID: %" G_GUINT64_FORMAT, t);
5143 case GST_MATROSKA_ID_SEEKPOSITION:
5147 if ((ret = gst_ebml_read_uint (ebml, &id, &t)) != GST_FLOW_OK)
5150 if (t > G_MAXINT64) {
5151 GST_WARNING_OBJECT (demux,
5152 "Too large SeekPosition %" G_GUINT64_FORMAT, t);
5156 GST_DEBUG_OBJECT (demux, "SeekPosition: %" G_GUINT64_FORMAT, t);
5162 ret = gst_matroska_read_common_parse_skip (&demux->common, ebml,
5168 if (ret != GST_FLOW_OK && ret != GST_FLOW_EOS)
5171 if (!seek_id || seek_pos == (guint64) - 1) {
5172 GST_WARNING_OBJECT (demux, "Incomplete seekhead entry (0x%x/%"
5173 G_GUINT64_FORMAT ")", seek_id, seek_pos);
5178 case GST_MATROSKA_ID_SEEKHEAD:
5181 case GST_MATROSKA_ID_CUES:
5182 case GST_MATROSKA_ID_TAGS:
5183 case GST_MATROSKA_ID_TRACKS:
5184 case GST_MATROSKA_ID_SEGMENTINFO:
5185 case GST_MATROSKA_ID_ATTACHMENTS:
5186 case GST_MATROSKA_ID_CHAPTERS:
5188 guint64 before_pos, length;
5192 length = gst_matroska_read_common_get_length (&demux->common);
5193 before_pos = demux->common.offset;
5195 if (length == (guint64) - 1) {
5196 GST_DEBUG_OBJECT (demux, "no upstream length, skipping SeakHead entry");
5200 /* check for validity */
5201 if (seek_pos + demux->common.ebml_segment_start + 12 >= length) {
5202 GST_WARNING_OBJECT (demux,
5203 "SeekHead reference lies outside file!" " (%"
5204 G_GUINT64_FORMAT "+%" G_GUINT64_FORMAT "+12 >= %"
5205 G_GUINT64_FORMAT ")", seek_pos, demux->common.ebml_segment_start,
5210 /* only pick up index location when streaming */
5211 if (demux->streaming) {
5212 if (seek_id == GST_MATROSKA_ID_CUES) {
5213 demux->index_offset = seek_pos + demux->common.ebml_segment_start;
5214 GST_DEBUG_OBJECT (demux, "Cues located at offset %" G_GUINT64_FORMAT,
5215 demux->index_offset);
5221 demux->common.offset = seek_pos + demux->common.ebml_segment_start;
5224 if ((ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
5225 GST_ELEMENT_CAST (demux), &id, &length, &needed)) !=
5229 if (id != seek_id) {
5230 GST_WARNING_OBJECT (demux,
5231 "We looked for ID=0x%x but got ID=0x%x (pos=%" G_GUINT64_FORMAT ")",
5232 seek_id, id, seek_pos + demux->common.ebml_segment_start);
5235 ret = gst_matroska_demux_parse_id (demux, id, length, needed);
5240 demux->common.offset = before_pos;
5244 case GST_MATROSKA_ID_CLUSTER:
5246 guint64 pos = seek_pos + demux->common.ebml_segment_start;
5248 GST_LOG_OBJECT (demux, "Cluster position");
5249 if (G_UNLIKELY (!demux->clusters))
5250 demux->clusters = g_array_sized_new (TRUE, TRUE, sizeof (guint64), 100);
5251 g_array_append_val (demux->clusters, pos);
5256 GST_DEBUG_OBJECT (demux, "Ignoring Seek entry for ID=0x%x", seek_id);
5259 DEBUG_ELEMENT_STOP (demux, ebml, "Seek", ret);
5264 static GstFlowReturn
5265 gst_matroska_demux_parse_contents (GstMatroskaDemux * demux, GstEbmlRead * ebml)
5267 GstFlowReturn ret = GST_FLOW_OK;
5270 DEBUG_ELEMENT_START (demux, ebml, "SeekHead");
5272 if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
5273 DEBUG_ELEMENT_STOP (demux, ebml, "SeekHead", ret);
5277 while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
5278 if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
5282 case GST_MATROSKA_ID_SEEKENTRY:
5284 ret = gst_matroska_demux_parse_contents_seekentry (demux, ebml);
5285 /* Ignore EOS and errors here */
5286 if (ret != GST_FLOW_OK) {
5287 GST_DEBUG_OBJECT (demux, "Ignoring %s", gst_flow_get_name (ret));
5294 ret = gst_matroska_read_common_parse_skip (&demux->common,
5295 ebml, "SeekHead", id);
5300 DEBUG_ELEMENT_STOP (demux, ebml, "SeekHead", ret);
5302 /* Sort clusters by position for easier searching */
5303 if (demux->clusters)
5304 g_array_sort (demux->clusters, (GCompareFunc) gst_matroska_cluster_compare);
5309 #define GST_FLOW_OVERFLOW GST_FLOW_CUSTOM_ERROR
5311 #define MAX_BLOCK_SIZE (15 * 1024 * 1024)
5313 static inline GstFlowReturn
5314 gst_matroska_demux_check_read_size (GstMatroskaDemux * demux, guint64 bytes)
5316 if (G_UNLIKELY (bytes > MAX_BLOCK_SIZE)) {
5317 /* only a few blocks are expected/allowed to be large,
5318 * and will be recursed into, whereas others will be read and must fit */
5319 if (demux->streaming) {
5320 /* fatal in streaming case, as we can't step over easily */
5321 GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
5322 ("reading large block of size %" G_GUINT64_FORMAT " not supported; "
5323 "file might be corrupt.", bytes));
5324 return GST_FLOW_ERROR;
5326 /* indicate higher level to quietly give up */
5327 GST_DEBUG_OBJECT (demux,
5328 "too large block of size %" G_GUINT64_FORMAT, bytes);
5329 return GST_FLOW_ERROR;
5336 /* returns TRUE if we truly are in error state, and should give up */
5337 static inline GstFlowReturn
5338 gst_matroska_demux_check_parse_error (GstMatroskaDemux * demux)
5340 if (!demux->streaming && demux->next_cluster_offset > 0) {
5341 /* just repositioning to where next cluster should be and try from there */
5342 GST_WARNING_OBJECT (demux, "parse error, trying next cluster expected at %"
5343 G_GUINT64_FORMAT, demux->next_cluster_offset);
5344 demux->common.offset = demux->next_cluster_offset;
5345 demux->next_cluster_offset = 0;
5351 /* sigh, one last attempt above and beyond call of duty ...;
5352 * search for cluster mark following current pos */
5353 pos = demux->common.offset;
5354 GST_WARNING_OBJECT (demux, "parse error, looking for next cluster");
5355 if ((ret = gst_matroska_demux_search_cluster (demux, &pos, TRUE)) !=
5357 /* did not work, give up */
5360 GST_DEBUG_OBJECT (demux, "... found at %" G_GUINT64_FORMAT, pos);
5361 /* try that position */
5362 demux->common.offset = pos;
5368 static inline GstFlowReturn
5369 gst_matroska_demux_flush (GstMatroskaDemux * demux, guint flush)
5371 GST_LOG_OBJECT (demux, "skipping %d bytes", flush);
5372 demux->common.offset += flush;
5373 if (demux->streaming) {
5376 /* hard to skip large blocks when streaming */
5377 ret = gst_matroska_demux_check_read_size (demux, flush);
5378 if (ret != GST_FLOW_OK)
5380 if (flush <= gst_adapter_available (demux->common.adapter))
5381 gst_adapter_flush (demux->common.adapter, flush);
5383 return GST_FLOW_EOS;
5388 /* initializes @ebml with @bytes from input stream at current offset.
5389 * Returns EOS if insufficient available,
5390 * ERROR if too much was attempted to read. */
5391 static inline GstFlowReturn
5392 gst_matroska_demux_take (GstMatroskaDemux * demux, guint64 bytes,
5395 GstBuffer *buffer = NULL;
5396 GstFlowReturn ret = GST_FLOW_OK;
5398 GST_LOG_OBJECT (demux, "taking %" G_GUINT64_FORMAT " bytes for parsing",
5400 ret = gst_matroska_demux_check_read_size (demux, bytes);
5401 if (G_UNLIKELY (ret != GST_FLOW_OK)) {
5402 if (!demux->streaming) {
5403 /* in pull mode, we can skip */
5404 if ((ret = gst_matroska_demux_flush (demux, bytes)) == GST_FLOW_OK)
5405 ret = GST_FLOW_OVERFLOW;
5407 /* otherwise fatal */
5408 ret = GST_FLOW_ERROR;
5412 if (demux->streaming) {
5413 if (gst_adapter_available (demux->common.adapter) >= bytes)
5414 buffer = gst_adapter_take_buffer (demux->common.adapter, bytes);
5418 ret = gst_matroska_read_common_peek_bytes (&demux->common,
5419 demux->common.offset, bytes, &buffer, NULL);
5420 if (G_LIKELY (buffer)) {
5421 gst_ebml_read_init (ebml, GST_ELEMENT_CAST (demux), buffer,
5422 demux->common.offset);
5423 demux->common.offset += bytes;
5430 gst_matroska_demux_check_seekability (GstMatroskaDemux * demux)
5433 gboolean seekable = FALSE;
5434 gint64 start = -1, stop = -1;
5436 query = gst_query_new_seeking (GST_FORMAT_BYTES);
5437 if (!gst_pad_peer_query (demux->common.sinkpad, query)) {
5438 GST_DEBUG_OBJECT (demux, "seeking query failed");
5442 gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
5444 /* try harder to query upstream size if we didn't get it the first time */
5445 if (seekable && stop == -1) {
5446 GST_DEBUG_OBJECT (demux, "doing duration query to fix up unset stop");
5447 gst_pad_peer_query_duration (demux->common.sinkpad, GST_FORMAT_BYTES,
5451 /* if upstream doesn't know the size, it's likely that it's not seekable in
5452 * practice even if it technically may be seekable */
5453 if (seekable && (start != 0 || stop <= start)) {
5454 GST_DEBUG_OBJECT (demux, "seekable but unknown start/stop -> disable");
5459 GST_INFO_OBJECT (demux, "seekable: %d (%" G_GUINT64_FORMAT " - %"
5460 G_GUINT64_FORMAT ")", seekable, start, stop);
5461 demux->seekable = seekable;
5463 gst_query_unref (query);
5466 static GstFlowReturn
5467 gst_matroska_demux_find_tracks (GstMatroskaDemux * demux)
5473 GstFlowReturn ret = GST_FLOW_OK;
5475 GST_WARNING_OBJECT (demux,
5476 "Found Cluster element before Tracks, searching Tracks");
5479 before_pos = demux->common.offset;
5481 /* Search Tracks element */
5483 ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
5484 GST_ELEMENT_CAST (demux), &id, &length, &needed);
5485 if (ret != GST_FLOW_OK)
5488 if (id != GST_MATROSKA_ID_TRACKS) {
5489 /* we may be skipping large cluster here, so forego size check etc */
5490 /* ... but we can't skip undefined size; force error */
5491 if (length == G_MAXUINT64) {
5492 ret = gst_matroska_demux_check_read_size (demux, length);
5495 demux->common.offset += needed;
5496 demux->common.offset += length;
5501 /* will lead to track parsing ... */
5502 ret = gst_matroska_demux_parse_id (demux, id, length, needed);
5507 demux->common.offset = before_pos;
5512 #define GST_READ_CHECK(stmt) \
5514 if (G_UNLIKELY ((ret = (stmt)) != GST_FLOW_OK)) { \
5515 if (ret == GST_FLOW_OVERFLOW) { \
5516 ret = GST_FLOW_OK; \
5522 static GstFlowReturn
5523 gst_matroska_demux_parse_id (GstMatroskaDemux * demux, guint32 id,
5524 guint64 length, guint needed)
5526 GstEbmlRead ebml = { 0, };
5527 GstFlowReturn ret = GST_FLOW_OK;
5530 GST_LOG_OBJECT (demux, "Parsing Element id 0x%x, "
5531 "size %" G_GUINT64_FORMAT ", prefix %d", id, length, needed);
5533 /* if we plan to read and parse this element, we need prefix (id + length)
5534 * and the contents */
5535 /* mind about overflow wrap-around when dealing with undefined size */
5537 if (G_LIKELY (length != G_MAXUINT64))
5540 switch (demux->common.state) {
5541 case GST_MATROSKA_READ_STATE_START:
5543 case GST_EBML_ID_HEADER:
5544 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5545 ret = gst_matroska_read_common_parse_header (&demux->common, &ebml);
5546 if (ret != GST_FLOW_OK)
5548 demux->common.state = GST_MATROSKA_READ_STATE_SEGMENT;
5549 gst_matroska_demux_check_seekability (demux);
5552 goto invalid_header;
5556 case GST_MATROSKA_READ_STATE_SEGMENT:
5558 case GST_MATROSKA_ID_SEGMENT:
5559 /* eat segment prefix */
5560 GST_READ_CHECK (gst_matroska_demux_flush (demux, needed));
5561 GST_DEBUG_OBJECT (demux,
5562 "Found Segment start at offset %" G_GUINT64_FORMAT " with size %"
5563 G_GUINT64_FORMAT, demux->common.offset, length);
5564 /* seeks are from the beginning of the segment,
5565 * after the segment ID/length */
5566 demux->common.ebml_segment_start = demux->common.offset;
5568 length = G_MAXUINT64;
5569 demux->common.ebml_segment_length = length;
5570 demux->common.state = GST_MATROSKA_READ_STATE_HEADER;
5573 GST_WARNING_OBJECT (demux,
5574 "Expected a Segment ID (0x%x), but received 0x%x!",
5575 GST_MATROSKA_ID_SEGMENT, id);
5576 GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
5580 case GST_MATROSKA_READ_STATE_SCANNING:
5581 if (id != GST_MATROSKA_ID_CLUSTER &&
5582 id != GST_MATROSKA_ID_PREVSIZE &&
5583 id != GST_MATROSKA_ID_CLUSTERTIMECODE) {
5584 if (demux->common.start_resync_offset != -1) {
5585 /* we need to skip byte per byte if we are scanning for a new cluster
5586 * after invalid data is found
5592 if (demux->common.start_resync_offset != -1) {
5593 GST_LOG_OBJECT (demux, "Resync done, new cluster found!");
5594 demux->common.start_resync_offset = -1;
5595 demux->common.state = demux->common.state_to_restore;
5599 case GST_MATROSKA_READ_STATE_HEADER:
5600 case GST_MATROSKA_READ_STATE_DATA:
5601 case GST_MATROSKA_READ_STATE_SEEK:
5603 case GST_EBML_ID_HEADER:
5604 GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
5605 demux->common.state = GST_MATROSKA_READ_STATE_SEGMENT;
5606 gst_matroska_demux_check_seekability (demux);
5608 case GST_MATROSKA_ID_SEGMENTINFO:
5609 if (!demux->common.segmentinfo_parsed) {
5610 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5611 ret = gst_matroska_read_common_parse_info (&demux->common,
5612 GST_ELEMENT_CAST (demux), &ebml);
5613 if (ret == GST_FLOW_OK)
5614 gst_matroska_demux_send_tags (demux);
5616 GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
5619 case GST_MATROSKA_ID_TRACKS:
5620 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5621 if (!demux->tracks_parsed) {
5622 ret = gst_matroska_demux_parse_tracks (demux, &ebml);
5624 ret = gst_matroska_demux_update_tracks (demux, &ebml);
5627 case GST_MATROSKA_ID_CLUSTER:
5628 if (G_UNLIKELY (!demux->tracks_parsed)) {
5629 if (demux->streaming) {
5630 GST_DEBUG_OBJECT (demux, "Cluster before Track");
5631 goto not_streamable;
5633 ret = gst_matroska_demux_find_tracks (demux);
5634 if (!demux->tracks_parsed)
5638 if (demux->common.state == GST_MATROSKA_READ_STATE_HEADER) {
5639 demux->common.state = GST_MATROSKA_READ_STATE_DATA;
5640 demux->first_cluster_offset = demux->common.offset;
5642 if (!demux->streaming &&
5643 !GST_CLOCK_TIME_IS_VALID (demux->common.segment.duration)) {
5644 GstMatroskaIndex *last = NULL;
5646 GST_DEBUG_OBJECT (demux,
5647 "estimating duration using last cluster");
5648 if ((last = gst_matroska_demux_search_pos (demux,
5649 GST_CLOCK_TIME_NONE)) != NULL) {
5650 demux->last_cluster_offset =
5651 last->pos + demux->common.ebml_segment_start;
5652 demux->stream_last_time = last->time;
5653 demux->common.segment.duration =
5654 demux->stream_last_time - demux->stream_start_time;
5655 /* above estimate should not be taken all too strongly */
5656 demux->invalid_duration = TRUE;
5657 GST_DEBUG_OBJECT (demux,
5658 "estimated duration as %" GST_TIME_FORMAT,
5659 GST_TIME_ARGS (demux->common.segment.duration));
5665 /* Peek at second cluster in order to figure out if we have cluster
5666 * prev_size or not (which is never set on the first cluster for
5667 * obvious reasons). This is useful in case someone initiates a
5668 * seek or direction change before we reach the second cluster. */
5669 if (!demux->streaming) {
5670 ClusterInfo cluster = { 0, };
5672 if (gst_matroska_demux_peek_cluster_info (demux, &cluster,
5673 demux->first_cluster_offset) && cluster.size > 0) {
5674 gst_matroska_demux_peek_cluster_info (demux, &cluster,
5675 demux->first_cluster_offset + cluster.size);
5677 demux->common.offset = demux->first_cluster_offset;
5680 if (demux->deferred_seek_event) {
5681 GstEvent *seek_event;
5683 seek_event = demux->deferred_seek_event;
5684 seek_pad = demux->deferred_seek_pad;
5685 demux->deferred_seek_event = NULL;
5686 demux->deferred_seek_pad = NULL;
5687 GST_DEBUG_OBJECT (demux,
5688 "Handling deferred seek event: %" GST_PTR_FORMAT, seek_event);
5689 gst_matroska_demux_handle_seek_event (demux, seek_pad,
5691 gst_event_unref (seek_event);
5694 /* send initial segment - we wait till we know the first
5695 incoming timestamp, so we can properly set the start of
5697 demux->need_segment = TRUE;
5699 demux->cluster_time = GST_CLOCK_TIME_NONE;
5700 demux->cluster_offset = demux->common.offset;
5701 demux->cluster_prevsize = 0;
5702 if (G_UNLIKELY (!demux->seek_first && demux->seek_block)) {
5703 GST_DEBUG_OBJECT (demux, "seek target block %" G_GUINT64_FORMAT
5704 " not found in Cluster, trying next Cluster's first block instead",
5706 demux->seek_block = 0;
5708 demux->seek_first = FALSE;
5709 /* record next cluster for recovery */
5710 if (read != G_MAXUINT64)
5711 demux->next_cluster_offset = demux->cluster_offset + read;
5712 /* eat cluster prefix */
5713 gst_matroska_demux_flush (demux, needed);
5715 case GST_MATROSKA_ID_CLUSTERTIMECODE:
5719 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5720 if ((ret = gst_ebml_read_uint (&ebml, &id, &num)) != GST_FLOW_OK)
5722 GST_DEBUG_OBJECT (demux, "ClusterTimeCode: %" G_GUINT64_FORMAT, num);
5723 demux->cluster_time = num;
5724 /* track last cluster */
5725 if (demux->cluster_offset > demux->last_cluster_offset) {
5726 demux->last_cluster_offset = demux->cluster_offset;
5727 demux->stream_last_time =
5728 demux->cluster_time * demux->common.time_scale;
5731 if (demux->common.element_index) {
5732 if (demux->common.element_index_writer_id == -1)
5733 gst_index_get_writer_id (demux->common.element_index,
5734 GST_OBJECT (demux), &demux->common.element_index_writer_id);
5735 GST_LOG_OBJECT (demux, "adding association %" GST_TIME_FORMAT "-> %"
5736 G_GUINT64_FORMAT " for writer id %d",
5737 GST_TIME_ARGS (demux->cluster_time), demux->cluster_offset,
5738 demux->common.element_index_writer_id);
5739 gst_index_add_association (demux->common.element_index,
5740 demux->common.element_index_writer_id,
5741 GST_ASSOCIATION_FLAG_KEY_UNIT,
5742 GST_FORMAT_TIME, demux->cluster_time,
5743 GST_FORMAT_BYTES, demux->cluster_offset, NULL);
5748 case GST_MATROSKA_ID_BLOCKGROUP:
5749 if (!gst_matroska_demux_seek_block (demux))
5751 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5752 DEBUG_ELEMENT_START (demux, &ebml, "BlockGroup");
5753 if ((ret = gst_ebml_read_master (&ebml, &id)) == GST_FLOW_OK) {
5754 ret = gst_matroska_demux_parse_blockgroup_or_simpleblock (demux,
5755 &ebml, demux->cluster_time, demux->cluster_offset, FALSE);
5757 DEBUG_ELEMENT_STOP (demux, &ebml, "BlockGroup", ret);
5759 case GST_MATROSKA_ID_SIMPLEBLOCK:
5760 if (!gst_matroska_demux_seek_block (demux))
5762 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5763 DEBUG_ELEMENT_START (demux, &ebml, "SimpleBlock");
5764 ret = gst_matroska_demux_parse_blockgroup_or_simpleblock (demux,
5765 &ebml, demux->cluster_time, demux->cluster_offset, TRUE);
5766 DEBUG_ELEMENT_STOP (demux, &ebml, "SimpleBlock", ret);
5768 case GST_MATROSKA_ID_ATTACHMENTS:
5769 if (!demux->common.attachments_parsed) {
5770 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5771 ret = gst_matroska_read_common_parse_attachments (&demux->common,
5772 GST_ELEMENT_CAST (demux), &ebml);
5773 if (ret == GST_FLOW_OK)
5774 gst_matroska_demux_send_tags (demux);
5776 GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
5779 case GST_MATROSKA_ID_TAGS:
5780 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5781 ret = gst_matroska_read_common_parse_metadata (&demux->common,
5782 GST_ELEMENT_CAST (demux), &ebml);
5783 if (ret == GST_FLOW_OK)
5784 gst_matroska_demux_send_tags (demux);
5786 case GST_MATROSKA_ID_CHAPTERS:
5787 if (!demux->common.chapters_parsed) {
5788 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5790 gst_matroska_read_common_parse_chapters (&demux->common, &ebml);
5792 if (demux->common.toc) {
5793 gst_matroska_demux_send_event (demux,
5794 gst_event_new_toc (demux->common.toc, FALSE));
5797 GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
5799 case GST_MATROSKA_ID_SEEKHEAD:
5800 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5801 ret = gst_matroska_demux_parse_contents (demux, &ebml);
5803 case GST_MATROSKA_ID_CUES:
5804 if (demux->common.index_parsed) {
5805 GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
5808 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5809 ret = gst_matroska_read_common_parse_index (&demux->common, &ebml);
5810 /* only push based; delayed index building */
5811 if (ret == GST_FLOW_OK
5812 && demux->common.state == GST_MATROSKA_READ_STATE_SEEK) {
5815 GST_OBJECT_LOCK (demux);
5816 event = demux->seek_event;
5817 demux->seek_event = NULL;
5818 GST_OBJECT_UNLOCK (demux);
5821 /* unlikely to fail, since we managed to seek to this point */
5822 if (!gst_matroska_demux_handle_seek_event (demux, NULL, event)) {
5823 gst_event_unref (event);
5826 gst_event_unref (event);
5827 /* resume data handling, main thread clear to seek again */
5828 GST_OBJECT_LOCK (demux);
5829 demux->common.state = GST_MATROSKA_READ_STATE_DATA;
5830 GST_OBJECT_UNLOCK (demux);
5833 case GST_MATROSKA_ID_PREVSIZE:{
5836 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5837 if ((ret = gst_ebml_read_uint (&ebml, &id, &num)) != GST_FLOW_OK)
5839 GST_LOG_OBJECT (demux, "ClusterPrevSize: %" G_GUINT64_FORMAT, num);
5840 demux->cluster_prevsize = num;
5841 demux->seen_cluster_prevsize = TRUE;
5844 case GST_MATROSKA_ID_POSITION:
5845 case GST_MATROSKA_ID_ENCRYPTEDBLOCK:
5846 /* The WebM doesn't support the EncryptedBlock element.
5847 * The Matroska spec doesn't give us more detail, how to parse this element,
5848 * for example the field TransformID isn't specified yet.*/
5849 case GST_MATROSKA_ID_SILENTTRACKS:
5850 GST_DEBUG_OBJECT (demux,
5851 "Skipping Cluster subelement 0x%x - ignoring", id);
5855 GST_DEBUG_OBJECT (demux, "skipping Element 0x%x", id);
5856 GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
5862 if (ret == GST_FLOW_PARSE)
5866 gst_ebml_read_clear (&ebml);
5872 /* simply exit, maybe not enough data yet */
5873 /* no ebml to clear if read error */
5878 GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
5879 ("Failed to parse Element 0x%x", id));
5880 ret = GST_FLOW_ERROR;
5885 GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
5886 ("File layout does not permit streaming"));
5887 ret = GST_FLOW_ERROR;
5892 GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
5893 ("No Tracks element found"));
5894 ret = GST_FLOW_ERROR;
5899 GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL), ("Invalid header"));
5900 ret = GST_FLOW_ERROR;
5905 GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL), ("Failed to seek"));
5906 ret = GST_FLOW_ERROR;
5912 gst_matroska_demux_loop (GstPad * pad)
5914 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (GST_PAD_PARENT (pad));
5920 /* If we have to close a segment, send a new segment to do this now */
5921 if (G_LIKELY (demux->common.state == GST_MATROSKA_READ_STATE_DATA)) {
5922 if (G_UNLIKELY (demux->new_segment)) {
5923 gst_matroska_demux_send_event (demux, demux->new_segment);
5924 demux->new_segment = NULL;
5928 ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
5929 GST_ELEMENT_CAST (demux), &id, &length, &needed);
5930 if (ret == GST_FLOW_EOS) {
5932 } else if (ret == GST_FLOW_FLUSHING) {
5934 } else if (ret != GST_FLOW_OK) {
5935 ret = gst_matroska_demux_check_parse_error (demux);
5937 /* Only handle EOS as no error if we're outside the segment already */
5938 if (ret == GST_FLOW_EOS && (demux->common.ebml_segment_length != G_MAXUINT64
5939 && demux->common.offset >=
5940 demux->common.ebml_segment_start +
5941 demux->common.ebml_segment_length))
5943 else if (ret != GST_FLOW_OK)
5949 GST_LOG_OBJECT (demux, "Offset %" G_GUINT64_FORMAT ", Element id 0x%x, "
5950 "size %" G_GUINT64_FORMAT ", needed %d", demux->common.offset, id,
5953 ret = gst_matroska_demux_parse_id (demux, id, length, needed);
5954 if (ret == GST_FLOW_EOS)
5956 if (ret != GST_FLOW_OK)
5959 /* check if we're at the end of a configured segment */
5960 if (G_LIKELY (demux->common.src->len)) {
5963 g_assert (demux->common.num_streams == demux->common.src->len);
5964 for (i = 0; i < demux->common.src->len; i++) {
5965 GstMatroskaTrackContext *context = g_ptr_array_index (demux->common.src,
5967 GST_DEBUG_OBJECT (context->pad, "pos %" GST_TIME_FORMAT,
5968 GST_TIME_ARGS (context->pos));
5969 if (context->eos == FALSE)
5973 GST_INFO_OBJECT (demux, "All streams are EOS");
5979 if (G_UNLIKELY (demux->cached_length == G_MAXUINT64 ||
5980 demux->common.offset >= demux->cached_length)) {
5981 demux->cached_length = gst_matroska_read_common_get_length (&demux->common);
5982 if (demux->common.offset == demux->cached_length) {
5983 GST_LOG_OBJECT (demux, "Reached end of stream");
5994 if (demux->common.segment.rate < 0.0) {
5995 ret = gst_matroska_demux_seek_to_previous_keyframe (demux);
5996 if (ret == GST_FLOW_OK)
6003 const gchar *reason = gst_flow_get_name (ret);
6004 gboolean push_eos = FALSE;
6006 GST_LOG_OBJECT (demux, "pausing task, reason %s", reason);
6007 gst_pad_pause_task (demux->common.sinkpad);
6009 if (ret == GST_FLOW_EOS) {
6010 /* perform EOS logic */
6012 /* If we were in the headers, make sure we send no-more-pads.
6013 This will ensure decodebin does not get stuck thinking
6014 the chain is not complete yet, and waiting indefinitely. */
6015 if (G_UNLIKELY (demux->common.state == GST_MATROSKA_READ_STATE_HEADER)) {
6016 if (demux->common.src->len == 0) {
6017 GST_ELEMENT_ERROR (demux, STREAM, FAILED, (NULL),
6018 ("No pads created"));
6020 GST_ELEMENT_WARNING (demux, STREAM, DEMUX, (NULL),
6021 ("Failed to finish reading headers"));
6023 gst_element_no_more_pads (GST_ELEMENT (demux));
6026 if (demux->common.segment.flags & GST_SEEK_FLAG_SEGMENT) {
6031 /* for segment playback we need to post when (in stream time)
6032 * we stopped, this is either stop (when set) or the duration. */
6033 if ((stop = demux->common.segment.stop) == -1)
6034 stop = demux->last_stop_end;
6036 GST_LOG_OBJECT (demux, "Sending segment done, at end of segment");
6037 msg = gst_message_new_segment_done (GST_OBJECT (demux), GST_FORMAT_TIME,
6039 if (demux->segment_seqnum)
6040 gst_message_set_seqnum (msg, demux->segment_seqnum);
6041 gst_element_post_message (GST_ELEMENT (demux), msg);
6043 event = gst_event_new_segment_done (GST_FORMAT_TIME, stop);
6044 if (demux->segment_seqnum)
6045 gst_event_set_seqnum (event, demux->segment_seqnum);
6046 gst_matroska_demux_send_event (demux, event);
6050 } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
6051 /* for fatal errors we post an error message */
6052 GST_ELEMENT_FLOW_ERROR (demux, ret);
6058 /* send EOS, and prevent hanging if no streams yet */
6059 GST_LOG_OBJECT (demux, "Sending EOS, at end of stream");
6060 event = gst_event_new_eos ();
6061 if (demux->segment_seqnum)
6062 gst_event_set_seqnum (event, demux->segment_seqnum);
6063 if (!gst_matroska_demux_send_event (demux, event) &&
6064 (ret == GST_FLOW_EOS)) {
6065 GST_ELEMENT_ERROR (demux, STREAM, DEMUX,
6066 (NULL), ("got eos but no streams (yet)"));
6074 * Create and push a flushing seek event upstream
6077 perform_seek_to_offset (GstMatroskaDemux * demux, gdouble rate, guint64 offset,
6078 guint32 seqnum, GstSeekFlags flags)
6083 GST_DEBUG_OBJECT (demux, "Seeking to %" G_GUINT64_FORMAT, offset);
6086 gst_event_new_seek (rate, GST_FORMAT_BYTES,
6087 flags | GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE,
6088 GST_SEEK_TYPE_SET, offset, GST_SEEK_TYPE_NONE, -1);
6089 gst_event_set_seqnum (event, seqnum);
6091 res = gst_pad_push_event (demux->common.sinkpad, event);
6093 /* segment event will update offset */
6097 static GstFlowReturn
6098 gst_matroska_demux_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
6100 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (parent);
6102 GstFlowReturn ret = GST_FLOW_OK;
6107 if (G_UNLIKELY (GST_BUFFER_IS_DISCONT (buffer))) {
6108 GST_DEBUG_OBJECT (demux, "got DISCONT");
6109 gst_adapter_clear (demux->common.adapter);
6110 GST_OBJECT_LOCK (demux);
6111 gst_matroska_read_common_reset_streams (&demux->common,
6112 GST_CLOCK_TIME_NONE, FALSE);
6113 GST_OBJECT_UNLOCK (demux);
6116 gst_adapter_push (demux->common.adapter, buffer);
6120 available = gst_adapter_available (demux->common.adapter);
6122 ret = gst_matroska_read_common_peek_id_length_push (&demux->common,
6123 GST_ELEMENT_CAST (demux), &id, &length, &needed);
6124 if (G_UNLIKELY (ret != GST_FLOW_OK && ret != GST_FLOW_EOS)) {
6125 if (demux->common.ebml_segment_length != G_MAXUINT64
6126 && demux->common.offset >=
6127 demux->common.ebml_segment_start + demux->common.ebml_segment_length) {
6130 gint64 bytes_scanned;
6131 if (demux->common.start_resync_offset == -1) {
6132 demux->common.start_resync_offset = demux->common.offset;
6133 demux->common.state_to_restore = demux->common.state;
6135 bytes_scanned = demux->common.offset - demux->common.start_resync_offset;
6136 if (bytes_scanned <= INVALID_DATA_THRESHOLD) {
6137 GST_WARNING_OBJECT (demux,
6138 "parse error, looking for next cluster, actual offset %"
6139 G_GUINT64_FORMAT ", start resync offset %" G_GUINT64_FORMAT,
6140 demux->common.offset, demux->common.start_resync_offset);
6141 demux->common.state = GST_MATROSKA_READ_STATE_SCANNING;
6144 GST_WARNING_OBJECT (demux,
6145 "unrecoverable parse error, next cluster not found and threshold "
6146 "exceeded, bytes scanned %" G_GINT64_FORMAT, bytes_scanned);
6152 GST_LOG_OBJECT (demux, "Offset %" G_GUINT64_FORMAT ", Element id 0x%x, "
6153 "size %" G_GUINT64_FORMAT ", needed %d, available %d",
6154 demux->common.offset, id, length, needed, available);
6156 if (needed > available)
6159 ret = gst_matroska_demux_parse_id (demux, id, length, needed);
6160 if (ret == GST_FLOW_EOS) {
6161 /* need more data */
6163 } else if (ret != GST_FLOW_OK) {
6170 gst_matroska_demux_handle_sink_event (GstPad * pad, GstObject * parent,
6173 gboolean res = TRUE;
6174 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (parent);
6176 GST_DEBUG_OBJECT (demux,
6177 "have event type %s: %p on sink pad", GST_EVENT_TYPE_NAME (event), event);
6179 switch (GST_EVENT_TYPE (event)) {
6180 case GST_EVENT_SEGMENT:
6182 const GstSegment *segment;
6184 /* some debug output */
6185 gst_event_parse_segment (event, &segment);
6186 /* FIXME: do we need to update segment base here (like accum in 0.10)? */
6187 GST_DEBUG_OBJECT (demux,
6188 "received format %d segment %" GST_SEGMENT_FORMAT, segment->format,
6191 if (demux->common.state < GST_MATROSKA_READ_STATE_DATA) {
6192 GST_DEBUG_OBJECT (demux, "still starting");
6196 /* we only expect a BYTE segment, e.g. following a seek */
6197 if (segment->format != GST_FORMAT_BYTES) {
6198 GST_DEBUG_OBJECT (demux, "unsupported segment format, ignoring");
6202 GST_DEBUG_OBJECT (demux, "clearing segment state");
6203 GST_OBJECT_LOCK (demux);
6204 /* clear current segment leftover */
6205 gst_adapter_clear (demux->common.adapter);
6206 /* and some streaming setup */
6207 demux->common.offset = segment->start;
6208 /* accumulate base based on current position */
6209 if (GST_CLOCK_TIME_IS_VALID (demux->common.segment.position))
6210 demux->common.segment.base +=
6211 (MAX (demux->common.segment.position, demux->stream_start_time)
6212 - demux->stream_start_time) / fabs (demux->common.segment.rate);
6213 /* do not know where we are;
6214 * need to come across a cluster and generate segment */
6215 demux->common.segment.position = GST_CLOCK_TIME_NONE;
6216 demux->cluster_time = GST_CLOCK_TIME_NONE;
6217 demux->cluster_offset = 0;
6218 demux->cluster_prevsize = 0;
6219 demux->need_segment = TRUE;
6220 demux->segment_seqnum = gst_event_get_seqnum (event);
6221 /* but keep some of the upstream segment */
6222 demux->common.segment.rate = segment->rate;
6223 demux->common.segment.flags = segment->flags;
6224 /* also check if need to keep some of the requested seek position */
6225 if (demux->seek_offset == segment->start) {
6226 GST_DEBUG_OBJECT (demux, "position matches requested seek");
6227 demux->common.segment.position = demux->requested_seek_time;
6229 GST_DEBUG_OBJECT (demux, "unexpected segment position");
6231 demux->requested_seek_time = GST_CLOCK_TIME_NONE;
6232 demux->seek_offset = -1;
6233 GST_OBJECT_UNLOCK (demux);
6235 /* chain will send initial segment after pads have been added,
6236 * or otherwise come up with one */
6237 GST_DEBUG_OBJECT (demux, "eating event");
6238 gst_event_unref (event);
6244 if (demux->common.state != GST_MATROSKA_READ_STATE_DATA
6245 && demux->common.state != GST_MATROSKA_READ_STATE_SCANNING) {
6246 gst_event_unref (event);
6247 GST_ELEMENT_ERROR (demux, STREAM, DEMUX,
6248 (NULL), ("got eos and didn't receive a complete header object"));
6249 } else if (demux->common.num_streams == 0) {
6250 GST_ELEMENT_ERROR (demux, STREAM, DEMUX,
6251 (NULL), ("got eos but no streams (yet)"));
6253 gst_matroska_demux_send_event (demux, event);
6257 case GST_EVENT_FLUSH_STOP:
6261 gst_adapter_clear (demux->common.adapter);
6262 GST_OBJECT_LOCK (demux);
6263 gst_matroska_read_common_reset_streams (&demux->common,
6264 GST_CLOCK_TIME_NONE, TRUE);
6265 gst_flow_combiner_reset (demux->flowcombiner);
6266 dur = demux->common.segment.duration;
6267 gst_segment_init (&demux->common.segment, GST_FORMAT_TIME);
6268 demux->common.segment.duration = dur;
6269 demux->cluster_time = GST_CLOCK_TIME_NONE;
6270 demux->cluster_offset = 0;
6271 demux->cluster_prevsize = 0;
6272 GST_OBJECT_UNLOCK (demux);
6276 res = gst_pad_event_default (pad, parent, event);
6284 gst_matroska_demux_sink_activate (GstPad * sinkpad, GstObject * parent)
6286 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (parent);
6288 gboolean pull_mode = FALSE;
6290 query = gst_query_new_scheduling ();
6292 if (gst_pad_peer_query (sinkpad, query))
6293 pull_mode = gst_query_has_scheduling_mode_with_flags (query,
6294 GST_PAD_MODE_PULL, GST_SCHEDULING_FLAG_SEEKABLE);
6296 gst_query_unref (query);
6299 GST_DEBUG ("going to pull mode");
6300 demux->streaming = FALSE;
6301 return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PULL, TRUE);
6303 GST_DEBUG ("going to push (streaming) mode");
6304 demux->streaming = TRUE;
6305 return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
6310 gst_matroska_demux_sink_activate_mode (GstPad * sinkpad, GstObject * parent,
6311 GstPadMode mode, gboolean active)
6314 case GST_PAD_MODE_PULL:
6316 /* if we have a scheduler we can start the task */
6317 gst_pad_start_task (sinkpad, (GstTaskFunction) gst_matroska_demux_loop,
6320 gst_pad_stop_task (sinkpad);
6323 case GST_PAD_MODE_PUSH:
6331 gst_matroska_demux_video_caps (GstMatroskaTrackVideoContext *
6332 videocontext, const gchar * codec_id, guint8 * data, guint size,
6333 gchar ** codec_name, guint32 * riff_fourcc)
6335 GstMatroskaTrackContext *context = (GstMatroskaTrackContext *) videocontext;
6336 GstCaps *caps = NULL;
6338 g_assert (videocontext != NULL);
6339 g_assert (codec_name != NULL);
6344 /* TODO: check if we have all codec types from matroska-ids.h
6345 * check if we have to do more special things with codec_private
6348 * GST_MATROSKA_CODEC_ID_VIDEO_QUICKTIME
6349 * GST_MATROSKA_CODEC_ID_VIDEO_SNOW
6352 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC)) {
6353 gst_riff_strf_vids *vids = NULL;
6356 GstBuffer *buf = NULL;
6358 vids = (gst_riff_strf_vids *) data;
6360 /* assure size is big enough */
6362 GST_WARNING ("Too small BITMAPINFOHEADER (%d bytes)", size);
6365 if (size < sizeof (gst_riff_strf_vids)) {
6366 vids = g_new (gst_riff_strf_vids, 1);
6367 memcpy (vids, data, size);
6370 context->dts_only = TRUE; /* VFW files only store DTS */
6372 /* little-endian -> byte-order */
6373 vids->size = GUINT32_FROM_LE (vids->size);
6374 vids->width = GUINT32_FROM_LE (vids->width);
6375 vids->height = GUINT32_FROM_LE (vids->height);
6376 vids->planes = GUINT16_FROM_LE (vids->planes);
6377 vids->bit_cnt = GUINT16_FROM_LE (vids->bit_cnt);
6378 vids->compression = GUINT32_FROM_LE (vids->compression);
6379 vids->image_size = GUINT32_FROM_LE (vids->image_size);
6380 vids->xpels_meter = GUINT32_FROM_LE (vids->xpels_meter);
6381 vids->ypels_meter = GUINT32_FROM_LE (vids->ypels_meter);
6382 vids->num_colors = GUINT32_FROM_LE (vids->num_colors);
6383 vids->imp_colors = GUINT32_FROM_LE (vids->imp_colors);
6385 if (size > sizeof (gst_riff_strf_vids)) { /* some extra_data */
6386 gsize offset = sizeof (gst_riff_strf_vids);
6388 buf = gst_buffer_new_memdup ((guint8 *) vids + offset, size - offset);
6392 *riff_fourcc = vids->compression;
6394 caps = gst_riff_create_video_caps (vids->compression, NULL, vids,
6395 buf, NULL, codec_name);
6398 GST_WARNING ("Unhandled RIFF fourcc %" GST_FOURCC_FORMAT,
6399 GST_FOURCC_ARGS (vids->compression));
6401 static GstStaticCaps intra_caps = GST_STATIC_CAPS ("image/jpeg; "
6402 "video/x-raw; image/png; video/x-dv; video/x-huffyuv; video/x-ffv; "
6403 "video/x-compressed-yuv");
6404 context->intra_only =
6405 gst_caps_can_intersect (gst_static_caps_get (&intra_caps), caps);
6409 gst_buffer_unref (buf);
6411 if (vids != (gst_riff_strf_vids *) data)
6414 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_UNCOMPRESSED)) {
6416 GstVideoFormat format;
6418 gst_video_info_init (&info);
6419 switch (videocontext->fourcc) {
6420 case GST_MAKE_FOURCC ('I', '4', '2', '0'):
6421 format = GST_VIDEO_FORMAT_I420;
6423 case GST_MAKE_FOURCC ('Y', 'U', 'Y', '2'):
6424 format = GST_VIDEO_FORMAT_YUY2;
6426 case GST_MAKE_FOURCC ('Y', 'V', '1', '2'):
6427 format = GST_VIDEO_FORMAT_YV12;
6429 case GST_MAKE_FOURCC ('U', 'Y', 'V', 'Y'):
6430 format = GST_VIDEO_FORMAT_UYVY;
6432 case GST_MAKE_FOURCC ('A', 'Y', 'U', 'V'):
6433 format = GST_VIDEO_FORMAT_AYUV;
6435 case GST_MAKE_FOURCC ('Y', '8', '0', '0'):
6436 case GST_MAKE_FOURCC ('Y', '8', ' ', ' '):
6437 format = GST_VIDEO_FORMAT_GRAY8;
6439 case GST_MAKE_FOURCC ('R', 'G', 'B', 24):
6440 format = GST_VIDEO_FORMAT_RGB;
6442 case GST_MAKE_FOURCC ('B', 'G', 'R', 24):
6443 format = GST_VIDEO_FORMAT_BGR;
6446 GST_DEBUG ("Unknown fourcc %" GST_FOURCC_FORMAT,
6447 GST_FOURCC_ARGS (videocontext->fourcc));
6451 context->intra_only = TRUE;
6453 gst_video_info_set_format (&info, format, videocontext->pixel_width,
6454 videocontext->pixel_height);
6455 caps = gst_video_info_to_caps (&info);
6456 *codec_name = gst_pb_utils_get_codec_description (caps);
6457 context->alignment = 32;
6458 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_SP)) {
6459 caps = gst_caps_new_simple ("video/x-divx",
6460 "divxversion", G_TYPE_INT, 4, NULL);
6461 *codec_name = g_strdup ("MPEG-4 simple profile");
6462 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_ASP) ||
6463 !strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_AP)) {
6464 caps = gst_caps_new_simple ("video/mpeg",
6465 "mpegversion", G_TYPE_INT, 4,
6466 "systemstream", G_TYPE_BOOLEAN, FALSE, NULL);
6470 priv = gst_buffer_new_memdup (data, size);
6471 gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
6472 gst_buffer_unref (priv);
6474 gst_codec_utils_mpeg4video_caps_set_level_and_profile (caps, data, size);
6476 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_ASP))
6477 *codec_name = g_strdup ("MPEG-4 advanced simple profile");
6479 *codec_name = g_strdup ("MPEG-4 advanced profile");
6480 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MSMPEG4V3)) {
6482 caps = gst_caps_new_full (gst_structure_new ("video/x-divx",
6483 "divxversion", G_TYPE_INT, 3, NULL),
6484 gst_structure_new ("video/x-msmpeg",
6485 "msmpegversion", G_TYPE_INT, 43, NULL), NULL);
6487 caps = gst_caps_new_simple ("video/x-msmpeg",
6488 "msmpegversion", G_TYPE_INT, 43, NULL);
6489 *codec_name = g_strdup ("Microsoft MPEG-4 v.3");
6490 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG1) ||
6491 !strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG2)) {
6494 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG1))
6499 caps = gst_caps_new_simple ("video/mpeg",
6500 "systemstream", G_TYPE_BOOLEAN, FALSE,
6501 "mpegversion", G_TYPE_INT, mpegversion, NULL);
6502 *codec_name = g_strdup_printf ("MPEG-%d video", mpegversion);
6503 context->postprocess_frame = gst_matroska_demux_add_mpeg_seq_header;
6504 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MJPEG)) {
6505 caps = gst_caps_new_empty_simple ("image/jpeg");
6506 *codec_name = g_strdup ("Motion-JPEG");
6507 context->intra_only = TRUE;
6508 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_AVC)) {
6509 caps = gst_caps_new_empty_simple ("video/x-h264");
6513 /* First byte is the version, second is the profile indication, and third
6514 * is the 5 contraint_set_flags and 3 reserved bits. Fourth byte is the
6515 * level indication. */
6516 gst_codec_utils_h264_caps_set_level_and_profile (caps, data + 1,
6519 priv = gst_buffer_new_memdup (data, size);
6520 gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
6521 gst_buffer_unref (priv);
6523 gst_caps_set_simple (caps, "stream-format", G_TYPE_STRING, "avc",
6524 "alignment", G_TYPE_STRING, "au", NULL);
6526 GST_WARNING ("No codec data found, assuming output is byte-stream");
6527 gst_caps_set_simple (caps, "stream-format", G_TYPE_STRING, "byte-stream",
6530 *codec_name = g_strdup ("H264");
6531 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEGH_HEVC)) {
6532 caps = gst_caps_new_empty_simple ("video/x-h265");
6536 gst_codec_utils_h265_caps_set_level_tier_and_profile (caps, data + 1,
6539 priv = gst_buffer_new_memdup (data, size);
6540 gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
6541 gst_buffer_unref (priv);
6543 gst_caps_set_simple (caps, "stream-format", G_TYPE_STRING, "hvc1",
6544 "alignment", G_TYPE_STRING, "au", NULL);
6546 GST_WARNING ("No codec data found, assuming output is byte-stream");
6547 gst_caps_set_simple (caps, "stream-format", G_TYPE_STRING, "byte-stream",
6550 *codec_name = g_strdup ("HEVC");
6551 } else if ((!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO1)) ||
6552 (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO2)) ||
6553 (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO3)) ||
6554 (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO4))) {
6555 gint rmversion = -1;
6557 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO1))
6559 else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO2))
6561 else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO3))
6563 else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO4))
6566 caps = gst_caps_new_simple ("video/x-pn-realvideo",
6567 "rmversion", G_TYPE_INT, rmversion, NULL);
6568 GST_DEBUG ("data:%p, size:0x%x", data, size);
6569 /* We need to extract the extradata ! */
6570 if (data && (size >= 0x22)) {
6575 subformat = GST_READ_UINT32_BE (data + 0x1a);
6576 rformat = GST_READ_UINT32_BE (data + 0x1e);
6578 priv = gst_buffer_new_memdup (data + 0x1a, size - 0x1a);
6579 gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, "format",
6580 G_TYPE_INT, rformat, "subformat", G_TYPE_INT, subformat, NULL);
6581 gst_buffer_unref (priv);
6584 *codec_name = g_strdup_printf ("RealVideo %d.0", rmversion);
6585 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_THEORA)) {
6586 caps = gst_caps_new_empty_simple ("video/x-theora");
6587 context->stream_headers =
6588 gst_matroska_parse_xiph_stream_headers (context->codec_priv,
6589 context->codec_priv_size);
6590 /* FIXME: mark stream as broken and skip if there are no stream headers */
6591 context->send_stream_headers = TRUE;
6592 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_DIRAC)) {
6593 caps = gst_caps_new_empty_simple ("video/x-dirac");
6594 *codec_name = g_strdup_printf ("Dirac");
6595 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_VP8)) {
6596 caps = gst_caps_new_empty_simple ("video/x-vp8");
6597 if (videocontext->alpha_mode)
6598 gst_caps_set_simple (caps, "codec-alpha", G_TYPE_BOOLEAN, TRUE, NULL);
6599 *codec_name = g_strdup_printf ("On2 VP8");
6600 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_VP9)) {
6601 caps = gst_caps_new_empty_simple ("video/x-vp9");
6602 if (videocontext->alpha_mode)
6603 gst_caps_set_simple (caps, "codec-alpha", G_TYPE_BOOLEAN, TRUE, NULL);
6604 *codec_name = g_strdup_printf ("On2 VP9");
6605 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_AV1)) {
6606 caps = gst_caps_new_empty_simple ("video/x-av1");
6610 priv = gst_buffer_new_memdup (data, size);
6611 gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
6612 gst_buffer_unref (priv);
6614 GST_WARNING ("No AV1 codec data found!");
6616 *codec_name = g_strdup_printf ("AOM AV1");
6617 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_PRORES)) {
6619 const gchar *variant, *variant_descr = "";
6621 /* Expect a fourcc in the codec private data */
6622 if (!data || size < 4) {
6623 GST_WARNING ("No or too small PRORESS fourcc (%d bytes)", size);
6627 fourcc = GST_STR_FOURCC (data);
6629 case GST_MAKE_FOURCC ('a', 'p', 'c', 's'):
6630 variant_descr = " 4:2:2 LT";
6633 case GST_MAKE_FOURCC ('a', 'p', 'c', 'h'):
6635 variant_descr = " 4:2:2 HQ";
6637 case GST_MAKE_FOURCC ('a', 'p', '4', 'h'):
6639 variant_descr = " 4:4:4:4";
6641 case GST_MAKE_FOURCC ('a', 'p', 'c', 'o'):
6643 variant_descr = " 4:2:2 Proxy";
6645 case GST_MAKE_FOURCC ('a', 'p', 'c', 'n'):
6647 variant = "standard";
6648 variant_descr = " 4:2:2 SD";
6652 GST_LOG ("Prores video, codec fourcc %" GST_FOURCC_FORMAT,
6653 GST_FOURCC_ARGS (fourcc));
6655 caps = gst_caps_new_simple ("video/x-prores",
6656 "format", G_TYPE_STRING, variant, NULL);
6657 *codec_name = g_strdup_printf ("Apple ProRes%s", variant_descr);
6658 context->postprocess_frame = gst_matroska_demux_add_prores_header;
6660 GST_WARNING ("Unknown codec '%s', cannot build Caps", codec_id);
6666 GstStructure *structure;
6668 for (i = 0; i < gst_caps_get_size (caps); i++) {
6669 structure = gst_caps_get_structure (caps, i);
6671 /* FIXME: use the real unit here! */
6672 GST_DEBUG ("video size %dx%d, target display size %dx%d (any unit)",
6673 videocontext->pixel_width,
6674 videocontext->pixel_height,
6675 videocontext->display_width, videocontext->display_height);
6677 /* pixel width and height are the w and h of the video in pixels */
6678 if (videocontext->pixel_width > 0 && videocontext->pixel_height > 0) {
6679 gint w = videocontext->pixel_width;
6680 gint h = videocontext->pixel_height;
6682 gst_structure_set (structure,
6683 "width", G_TYPE_INT, w, "height", G_TYPE_INT, h, NULL);
6686 if (videocontext->display_width > 0 || videocontext->display_height > 0) {
6689 if (videocontext->display_width <= 0)
6690 videocontext->display_width = videocontext->pixel_width;
6691 if (videocontext->display_height <= 0)
6692 videocontext->display_height = videocontext->pixel_height;
6694 /* calculate the pixel aspect ratio using the display and pixel w/h */
6695 n = videocontext->display_width * videocontext->pixel_height;
6696 d = videocontext->display_height * videocontext->pixel_width;
6697 GST_DEBUG ("setting PAR to %d/%d", n, d);
6698 gst_structure_set (structure, "pixel-aspect-ratio",
6700 videocontext->display_width * videocontext->pixel_height,
6701 videocontext->display_height * videocontext->pixel_width, NULL);
6704 if (videocontext->default_fps > 0.0) {
6707 gst_util_double_to_fraction (videocontext->default_fps, &fps_n, &fps_d);
6709 GST_DEBUG ("using default fps %d/%d", fps_n, fps_d);
6711 gst_structure_set (structure, "framerate", GST_TYPE_FRACTION, fps_n,
6713 } else if (context->default_duration > 0) {
6716 gst_video_guess_framerate (context->default_duration, &fps_n, &fps_d);
6718 GST_INFO ("using default duration %" G_GUINT64_FORMAT
6719 " framerate %d/%d", context->default_duration, fps_n, fps_d);
6721 gst_structure_set (structure, "framerate", GST_TYPE_FRACTION,
6722 fps_n, fps_d, NULL);
6724 gst_structure_set (structure, "framerate", GST_TYPE_FRACTION,
6728 switch (videocontext->interlace_mode) {
6729 case GST_MATROSKA_INTERLACE_MODE_PROGRESSIVE:
6730 gst_structure_set (structure,
6731 "interlace-mode", G_TYPE_STRING, "progressive", NULL);
6733 case GST_MATROSKA_INTERLACE_MODE_INTERLACED:
6734 gst_structure_set (structure,
6735 "interlace-mode", G_TYPE_STRING, "interleaved", NULL);
6737 if (videocontext->field_order != GST_VIDEO_FIELD_ORDER_UNKNOWN)
6738 gst_structure_set (structure, "field-order", G_TYPE_STRING,
6739 gst_video_field_order_to_string (videocontext->field_order),
6746 if (videocontext->multiview_mode != GST_VIDEO_MULTIVIEW_MODE_NONE) {
6747 if (gst_video_multiview_guess_half_aspect (videocontext->multiview_mode,
6748 videocontext->pixel_width, videocontext->pixel_height,
6749 videocontext->display_width * videocontext->pixel_height,
6750 videocontext->display_height * videocontext->pixel_width)) {
6751 videocontext->multiview_flags |= GST_VIDEO_MULTIVIEW_FLAGS_HALF_ASPECT;
6753 gst_caps_set_simple (caps,
6754 "multiview-mode", G_TYPE_STRING,
6755 gst_video_multiview_mode_to_caps_string
6756 (videocontext->multiview_mode), "multiview-flags",
6757 GST_TYPE_VIDEO_MULTIVIEW_FLAGSET, videocontext->multiview_flags,
6758 GST_FLAG_SET_MASK_EXACT, NULL);
6761 if (videocontext->colorimetry.range != GST_VIDEO_COLOR_RANGE_UNKNOWN ||
6762 videocontext->colorimetry.matrix != GST_VIDEO_COLOR_MATRIX_UNKNOWN ||
6763 videocontext->colorimetry.transfer != GST_VIDEO_TRANSFER_UNKNOWN ||
6764 videocontext->colorimetry.primaries !=
6765 GST_VIDEO_COLOR_PRIMARIES_UNKNOWN) {
6766 gchar *colorimetry =
6767 gst_video_colorimetry_to_string (&videocontext->colorimetry);
6768 gst_caps_set_simple (caps, "colorimetry", G_TYPE_STRING, colorimetry,
6770 GST_DEBUG ("setting colorimetry to %s", colorimetry);
6771 g_free (colorimetry);
6774 if (videocontext->mastering_display_info_present) {
6775 if (!gst_video_mastering_display_info_add_to_caps
6776 (&videocontext->mastering_display_info, caps)) {
6777 GST_WARNING ("couldn't set mastering display info to caps");
6781 if (videocontext->content_light_level.max_content_light_level &&
6782 videocontext->content_light_level.max_frame_average_light_level) {
6783 if (!gst_video_content_light_level_add_to_caps
6784 (&videocontext->content_light_level, caps)) {
6785 GST_WARNING ("couldn't set content light level to caps");
6789 caps = gst_caps_simplify (caps);
6796 * Some AAC specific code... *sigh*
6797 * FIXME: maybe we should use '15' and code the sample rate explicitly
6798 * if the sample rate doesn't match the predefined rates exactly? (tpm)
6802 aac_rate_idx (gint rate)
6806 else if (75132 <= rate)
6808 else if (55426 <= rate)
6810 else if (46009 <= rate)
6812 else if (37566 <= rate)
6814 else if (27713 <= rate)
6816 else if (23004 <= rate)
6818 else if (18783 <= rate)
6820 else if (13856 <= rate)
6822 else if (11502 <= rate)
6824 else if (9391 <= rate)
6831 aac_profile_idx (const gchar * codec_id)
6835 if (strlen (codec_id) <= 12)
6837 else if (!strncmp (&codec_id[12], "MAIN", 4))
6839 else if (!strncmp (&codec_id[12], "LC", 2))
6841 else if (!strncmp (&codec_id[12], "SSR", 3))
6850 round_up_pow2 (guint n)
6861 #define AAC_SYNC_EXTENSION_TYPE 0x02b7
6864 gst_matroska_demux_audio_caps (GstMatroskaTrackAudioContext *
6865 audiocontext, const gchar * codec_id, guint8 * data, guint size,
6866 gchar ** codec_name, guint16 * riff_audio_fmt, GstClockTime * lead_in_ts)
6868 GstMatroskaTrackContext *context = (GstMatroskaTrackContext *) audiocontext;
6869 GstCaps *caps = NULL;
6871 /* Max potential blocksize causing the longest possible lead_in_ts need, as
6872 * we don't have the exact number parsed out here */
6873 guint max_blocksize = 0;
6874 /* Original samplerate before SBR multiplications, as parsers would use */
6875 guint rate = audiocontext->samplerate;
6877 g_assert (audiocontext != NULL);
6878 g_assert (codec_name != NULL);
6881 *riff_audio_fmt = 0;
6883 /* TODO: check if we have all codec types from matroska-ids.h
6884 * check if we have to do more special things with codec_private
6885 * check if we need bitdepth in different places too
6886 * implement channel position magic
6888 * GST_MATROSKA_CODEC_ID_AUDIO_AC3_BSID9
6889 * GST_MATROSKA_CODEC_ID_AUDIO_AC3_BSID10
6890 * GST_MATROSKA_CODEC_ID_AUDIO_QUICKTIME_QDMC
6891 * GST_MATROSKA_CODEC_ID_AUDIO_QUICKTIME_QDM2
6894 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L1) ||
6895 !strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L2) ||
6896 !strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L3)) {
6899 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L1))
6901 else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L2))
6906 lead_in = 30; /* Could mp2 need as much too? */
6907 max_blocksize = 1152;
6908 caps = gst_caps_new_simple ("audio/mpeg",
6909 "mpegversion", G_TYPE_INT, 1, "layer", G_TYPE_INT, layer, NULL);
6910 *codec_name = g_strdup_printf ("MPEG-1 layer %d", layer);
6911 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_PCM_INT_BE) ||
6912 !strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_PCM_INT_LE)) {
6915 GstAudioFormat format;
6917 sign = (audiocontext->bitdepth != 8);
6918 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_PCM_INT_BE))
6919 endianness = G_BIG_ENDIAN;
6921 endianness = G_LITTLE_ENDIAN;
6923 format = gst_audio_format_build_integer (sign, endianness,
6924 audiocontext->bitdepth, audiocontext->bitdepth);
6926 /* FIXME: Channel mask and reordering */
6927 caps = gst_caps_new_simple ("audio/x-raw",
6928 "format", G_TYPE_STRING, gst_audio_format_to_string (format),
6929 "layout", G_TYPE_STRING, "interleaved",
6930 "channel-mask", GST_TYPE_BITMASK,
6931 gst_audio_channel_get_fallback_mask (audiocontext->channels), NULL);
6933 *codec_name = g_strdup_printf ("Raw %d-bit PCM audio",
6934 audiocontext->bitdepth);
6935 context->alignment = GST_ROUND_UP_8 (audiocontext->bitdepth) / 8;
6936 context->alignment = round_up_pow2 (context->alignment);
6937 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_PCM_FLOAT)) {
6938 const gchar *format;
6939 if (audiocontext->bitdepth == 32)
6943 /* FIXME: Channel mask and reordering */
6944 caps = gst_caps_new_simple ("audio/x-raw",
6945 "format", G_TYPE_STRING, format,
6946 "layout", G_TYPE_STRING, "interleaved",
6947 "channel-mask", GST_TYPE_BITMASK,
6948 gst_audio_channel_get_fallback_mask (audiocontext->channels), NULL);
6949 *codec_name = g_strdup_printf ("Raw %d-bit floating-point audio",
6950 audiocontext->bitdepth);
6951 context->alignment = audiocontext->bitdepth / 8;
6952 context->alignment = round_up_pow2 (context->alignment);
6953 } else if (!strncmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_AC3,
6954 strlen (GST_MATROSKA_CODEC_ID_AUDIO_AC3))) {
6956 max_blocksize = 1536;
6957 caps = gst_caps_new_simple ("audio/x-ac3",
6958 "framed", G_TYPE_BOOLEAN, TRUE, NULL);
6959 *codec_name = g_strdup ("AC-3 audio");
6960 } else if (!strncmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_EAC3,
6961 strlen (GST_MATROSKA_CODEC_ID_AUDIO_EAC3))) {
6963 max_blocksize = 1536;
6964 caps = gst_caps_new_simple ("audio/x-eac3",
6965 "framed", G_TYPE_BOOLEAN, TRUE, NULL);
6966 *codec_name = g_strdup ("E-AC-3 audio");
6967 } else if (!strncmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_TRUEHD,
6968 strlen (GST_MATROSKA_CODEC_ID_AUDIO_TRUEHD))) {
6969 caps = gst_caps_new_empty_simple ("audio/x-true-hd");
6970 *codec_name = g_strdup ("Dolby TrueHD");
6971 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_DTS)) {
6972 caps = gst_caps_new_empty_simple ("audio/x-dts");
6973 *codec_name = g_strdup ("DTS audio");
6974 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_VORBIS)) {
6975 caps = gst_caps_new_empty_simple ("audio/x-vorbis");
6976 context->stream_headers =
6977 gst_matroska_parse_xiph_stream_headers (context->codec_priv,
6978 context->codec_priv_size);
6979 /* FIXME: mark stream as broken and skip if there are no stream headers */
6980 context->send_stream_headers = TRUE;
6981 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_FLAC)) {
6982 caps = gst_caps_new_empty_simple ("audio/x-flac");
6983 context->stream_headers =
6984 gst_matroska_parse_flac_stream_headers (context->codec_priv,
6985 context->codec_priv_size);
6986 /* FIXME: mark stream as broken and skip if there are no stream headers */
6987 context->send_stream_headers = TRUE;
6988 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_SPEEX)) {
6989 caps = gst_caps_new_empty_simple ("audio/x-speex");
6990 context->stream_headers =
6991 gst_matroska_parse_speex_stream_headers (context->codec_priv,
6992 context->codec_priv_size);
6993 /* FIXME: mark stream as broken and skip if there are no stream headers */
6994 context->send_stream_headers = TRUE;
6995 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_OPUS)) {
6998 if (context->codec_priv_size >= 19) {
6999 if (audiocontext->samplerate)
7000 GST_WRITE_UINT32_LE ((guint8 *) context->codec_priv + 12,
7001 audiocontext->samplerate);
7002 if (context->codec_delay) {
7004 gst_util_uint64_scale_round (context->codec_delay, 48000,
7006 GST_WRITE_UINT16_LE ((guint8 *) context->codec_priv + 10, delay);
7010 gst_buffer_new_memdup (context->codec_priv, context->codec_priv_size);
7011 caps = gst_codec_utils_opus_create_caps_from_header (tmp, NULL);
7012 gst_buffer_unref (tmp);
7013 *codec_name = g_strdup ("Opus");
7014 } else if (context->codec_priv_size == 0) {
7015 GST_WARNING ("No Opus codec data found, trying to create one");
7016 if (audiocontext->channels <= 2) {
7017 guint8 streams, coupled, channels;
7021 audiocontext->samplerate == 0 ? 48000 : audiocontext->samplerate;
7023 channels = audiocontext->channels == 0 ? 2 : audiocontext->channels;
7024 if (channels == 1) {
7033 gst_codec_utils_opus_create_caps (samplerate, channels, 0, streams,
7036 *codec_name = g_strdup ("Opus");
7038 GST_WARNING ("Failed to create Opus caps from audio context");
7041 GST_WARNING ("No Opus codec data, and not enough info to create one");
7044 GST_WARNING ("Invalid Opus codec data size (got %" G_GSIZE_FORMAT
7045 ", expected 19)", context->codec_priv_size);
7047 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_ACM)) {
7048 gst_riff_strf_auds auds;
7050 if (data && size >= 18) {
7051 GstBuffer *codec_data = NULL;
7053 /* little-endian -> byte-order */
7054 auds.format = GST_READ_UINT16_LE (data);
7055 auds.channels = GST_READ_UINT16_LE (data + 2);
7056 auds.rate = GST_READ_UINT32_LE (data + 4);
7057 auds.av_bps = GST_READ_UINT32_LE (data + 8);
7058 auds.blockalign = GST_READ_UINT16_LE (data + 12);
7059 auds.bits_per_sample = GST_READ_UINT16_LE (data + 16);
7061 /* 18 is the waveformatex size */
7063 codec_data = gst_buffer_new_wrapped_full (GST_MEMORY_FLAG_READONLY,
7064 data + 18, size - 18, 0, size - 18, NULL, NULL);
7068 *riff_audio_fmt = auds.format;
7070 /* FIXME: Handle reorder map */
7071 caps = gst_riff_create_audio_caps (auds.format, NULL, &auds, codec_data,
7072 NULL, codec_name, NULL);
7074 gst_buffer_unref (codec_data);
7077 GST_WARNING ("Unhandled RIFF audio format 0x%02x", auds.format);
7080 GST_WARNING ("Invalid codec data size (%d expected, got %d)", 18, size);
7082 } else if (g_str_has_prefix (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_AAC)) {
7083 GstBuffer *priv = NULL;
7085 gint rate_idx, profile;
7086 guint8 *data = NULL;
7088 /* unspecified AAC profile with opaque private codec data */
7089 if (strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_AAC) == 0) {
7090 if (context->codec_priv_size >= 2) {
7091 guint obj_type, freq_index, explicit_freq_bytes = 0;
7093 codec_id = GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG4;
7095 freq_index = (GST_READ_UINT16_BE (context->codec_priv) & 0x780) >> 7;
7096 obj_type = (GST_READ_UINT16_BE (context->codec_priv) & 0xF800) >> 11;
7097 if (freq_index == 15)
7098 explicit_freq_bytes = 3;
7099 GST_DEBUG ("obj_type = %u, freq_index = %u", obj_type, freq_index);
7100 priv = gst_buffer_new_memdup (context->codec_priv,
7101 context->codec_priv_size);
7102 /* assume SBR if samplerate <= 24kHz */
7103 if (obj_type == 5 || (freq_index >= 6 && freq_index != 15) ||
7104 (context->codec_priv_size == (5 + explicit_freq_bytes))) {
7105 /* TODO: Commonly aacparse will reset the rate in caps to
7106 * non-multiplied - which one is correct? */
7107 audiocontext->samplerate *= 2;
7110 GST_WARNING ("Opaque A_AAC codec ID, but no codec private data");
7111 /* this is pretty broken;
7112 * maybe we need to make up some default private,
7113 * or maybe ADTS data got dumped in.
7114 * Let's set up some private data now, and check actual data later */
7115 /* just try this and see what happens ... */
7116 codec_id = GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG4;
7117 context->postprocess_frame = gst_matroska_demux_check_aac;
7121 /* make up decoder-specific data if it is not supplied */
7125 priv = gst_buffer_new_allocate (NULL, 5, NULL);
7126 gst_buffer_map (priv, &map, GST_MAP_WRITE);
7128 rate_idx = aac_rate_idx (audiocontext->samplerate);
7129 profile = aac_profile_idx (codec_id);
7131 data[0] = ((profile + 1) << 3) | ((rate_idx & 0xE) >> 1);
7132 data[1] = ((rate_idx & 0x1) << 7) | (audiocontext->channels << 3);
7134 if (!strncmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG2,
7135 strlen (GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG2))) {
7137 gst_buffer_unmap (priv, &map);
7138 gst_buffer_set_size (priv, 2);
7139 } else if (!strncmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG4,
7140 strlen (GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG4))) {
7143 if (g_strrstr (codec_id, "SBR")) {
7144 /* HE-AAC (aka SBR AAC) */
7145 audiocontext->samplerate *= 2;
7146 rate_idx = aac_rate_idx (audiocontext->samplerate);
7147 data[2] = AAC_SYNC_EXTENSION_TYPE >> 3;
7148 data[3] = ((AAC_SYNC_EXTENSION_TYPE & 0x07) << 5) | 5;
7149 data[4] = (1 << 7) | (rate_idx << 3);
7150 gst_buffer_unmap (priv, &map);
7152 gst_buffer_unmap (priv, &map);
7153 gst_buffer_set_size (priv, 2);
7156 gst_buffer_unmap (priv, &map);
7157 gst_buffer_unref (priv);
7159 GST_ERROR ("Unknown AAC profile and no codec private data");
7165 max_blocksize = 1024;
7166 caps = gst_caps_new_simple ("audio/mpeg",
7167 "mpegversion", G_TYPE_INT, mpegversion,
7168 "framed", G_TYPE_BOOLEAN, TRUE,
7169 "stream-format", G_TYPE_STRING, "raw", NULL);
7170 gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
7171 if (context->codec_priv && context->codec_priv_size > 0)
7172 gst_codec_utils_aac_caps_set_level_and_profile (caps,
7173 context->codec_priv, context->codec_priv_size);
7174 *codec_name = g_strdup_printf ("MPEG-%d AAC audio", mpegversion);
7175 gst_buffer_unref (priv);
7177 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_TTA)) {
7178 caps = gst_caps_new_simple ("audio/x-tta",
7179 "width", G_TYPE_INT, audiocontext->bitdepth, NULL);
7180 *codec_name = g_strdup ("TTA audio");
7181 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_WAVPACK4)) {
7182 caps = gst_caps_new_simple ("audio/x-wavpack",
7183 "width", G_TYPE_INT, audiocontext->bitdepth,
7184 "framed", G_TYPE_BOOLEAN, TRUE, NULL);
7185 *codec_name = g_strdup ("Wavpack audio");
7186 context->postprocess_frame = gst_matroska_demux_add_wvpk_header;
7187 audiocontext->wvpk_block_index = 0;
7188 } else if ((!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_14_4)) ||
7189 (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_28_8)) ||
7190 (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_COOK))) {
7191 gint raversion = -1;
7193 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_14_4))
7195 else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_COOK))
7200 caps = gst_caps_new_simple ("audio/x-pn-realaudio",
7201 "raversion", G_TYPE_INT, raversion, NULL);
7202 /* Extract extra information from caps, mapping varies based on codec */
7203 if (data && (size >= 0x50)) {
7210 guint extra_data_size;
7212 GST_DEBUG ("real audio raversion:%d", raversion);
7213 if (raversion == 8) {
7215 flavor = GST_READ_UINT16_BE (data + 22);
7216 packet_size = GST_READ_UINT32_BE (data + 24);
7217 height = GST_READ_UINT16_BE (data + 40);
7218 leaf_size = GST_READ_UINT16_BE (data + 44);
7219 sample_width = GST_READ_UINT16_BE (data + 58);
7220 extra_data_size = GST_READ_UINT32_BE (data + 74);
7223 ("flavor:%d, packet_size:%d, height:%d, leaf_size:%d, sample_width:%d, extra_data_size:%d",
7224 flavor, packet_size, height, leaf_size, sample_width,
7226 gst_caps_set_simple (caps, "flavor", G_TYPE_INT, flavor, "packet_size",
7227 G_TYPE_INT, packet_size, "height", G_TYPE_INT, height, "leaf_size",
7228 G_TYPE_INT, leaf_size, "width", G_TYPE_INT, sample_width, NULL);
7230 if ((size - 78) >= extra_data_size) {
7231 priv = gst_buffer_new_memdup (data + 78, extra_data_size);
7232 gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
7233 gst_buffer_unref (priv);
7238 *codec_name = g_strdup_printf ("RealAudio %d.0", raversion);
7239 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_SIPR)) {
7240 caps = gst_caps_new_empty_simple ("audio/x-sipro");
7241 *codec_name = g_strdup ("Sipro/ACELP.NET Voice Codec");
7242 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_RALF)) {
7243 caps = gst_caps_new_empty_simple ("audio/x-ralf-mpeg4-generic");
7244 *codec_name = g_strdup ("Real Audio Lossless");
7245 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_ATRC)) {
7246 caps = gst_caps_new_empty_simple ("audio/x-vnd.sony.atrac3");
7247 *codec_name = g_strdup ("Sony ATRAC3");
7249 GST_WARNING ("Unknown codec '%s', cannot build Caps", codec_id);
7254 if (audiocontext->samplerate > 0 && audiocontext->channels > 0) {
7257 for (i = 0; i < gst_caps_get_size (caps); i++) {
7258 gst_structure_set (gst_caps_get_structure (caps, i),
7259 "channels", G_TYPE_INT, audiocontext->channels,
7260 "rate", G_TYPE_INT, audiocontext->samplerate, NULL);
7264 caps = gst_caps_simplify (caps);
7267 if (lead_in_ts && lead_in && max_blocksize && rate) {
7269 gst_util_uint64_scale (GST_SECOND, max_blocksize * lead_in, rate);
7276 gst_matroska_demux_subtitle_caps (GstMatroskaTrackSubtitleContext *
7277 subtitlecontext, const gchar * codec_id, gpointer data, guint size)
7279 GstCaps *caps = NULL;
7280 GstMatroskaTrackContext *context =
7281 (GstMatroskaTrackContext *) subtitlecontext;
7283 /* for backwards compatibility */
7284 if (!g_ascii_strcasecmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_ASCII))
7285 codec_id = GST_MATROSKA_CODEC_ID_SUBTITLE_UTF8;
7286 else if (!g_ascii_strcasecmp (codec_id, "S_SSA"))
7287 codec_id = GST_MATROSKA_CODEC_ID_SUBTITLE_SSA;
7288 else if (!g_ascii_strcasecmp (codec_id, "S_ASS"))
7289 codec_id = GST_MATROSKA_CODEC_ID_SUBTITLE_ASS;
7290 else if (!g_ascii_strcasecmp (codec_id, "S_USF"))
7291 codec_id = GST_MATROSKA_CODEC_ID_SUBTITLE_USF;
7293 /* TODO: Add GST_MATROSKA_CODEC_ID_SUBTITLE_BMP support
7294 * Check if we have to do something with codec_private */
7295 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_UTF8)) {
7296 /* well, plain text simply does not have a lot of markup ... */
7297 caps = gst_caps_new_simple ("text/x-raw", "format", G_TYPE_STRING,
7298 "pango-markup", NULL);
7299 context->postprocess_frame = gst_matroska_demux_check_subtitle_buffer;
7300 subtitlecontext->check_markup = TRUE;
7301 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_SSA)) {
7302 caps = gst_caps_new_empty_simple ("application/x-ssa");
7303 context->postprocess_frame = gst_matroska_demux_check_subtitle_buffer;
7304 subtitlecontext->check_markup = FALSE;
7305 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_ASS)) {
7306 caps = gst_caps_new_empty_simple ("application/x-ass");
7307 context->postprocess_frame = gst_matroska_demux_check_subtitle_buffer;
7308 subtitlecontext->check_markup = FALSE;
7309 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_USF)) {
7310 caps = gst_caps_new_empty_simple ("application/x-usf");
7311 context->postprocess_frame = gst_matroska_demux_check_subtitle_buffer;
7312 subtitlecontext->check_markup = FALSE;
7313 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_VOBSUB)) {
7314 caps = gst_caps_new_empty_simple ("subpicture/x-dvd");
7315 ((GstMatroskaTrackContext *) subtitlecontext)->send_dvd_event = TRUE;
7316 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_HDMVPGS)) {
7317 caps = gst_caps_new_empty_simple ("subpicture/x-pgs");
7318 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_KATE)) {
7319 caps = gst_caps_new_empty_simple ("subtitle/x-kate");
7320 context->stream_headers =
7321 gst_matroska_parse_xiph_stream_headers (context->codec_priv,
7322 context->codec_priv_size);
7323 /* FIXME: mark stream as broken and skip if there are no stream headers */
7324 context->send_stream_headers = TRUE;
7326 GST_DEBUG ("Unknown subtitle stream: codec_id='%s'", codec_id);
7327 caps = gst_caps_new_empty_simple ("application/x-subtitle-unknown");
7330 if (data != NULL && size > 0) {
7333 buf = gst_buffer_new_memdup (data, size);
7334 gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, buf, NULL);
7335 gst_buffer_unref (buf);
7343 gst_matroska_demux_set_index (GstElement * element, GstIndex * index)
7345 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (element);
7347 GST_OBJECT_LOCK (demux);
7348 if (demux->common.element_index)
7349 gst_object_unref (demux->common.element_index);
7350 demux->common.element_index = index ? gst_object_ref (index) : NULL;
7351 GST_OBJECT_UNLOCK (demux);
7352 GST_DEBUG_OBJECT (demux, "Set index %" GST_PTR_FORMAT,
7353 demux->common.element_index);
7357 gst_matroska_demux_get_index (GstElement * element)
7359 GstIndex *result = NULL;
7360 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (element);
7362 GST_OBJECT_LOCK (demux);
7363 if (demux->common.element_index)
7364 result = gst_object_ref (demux->common.element_index);
7365 GST_OBJECT_UNLOCK (demux);
7367 GST_DEBUG_OBJECT (demux, "Returning index %" GST_PTR_FORMAT, result);
7373 static GstStateChangeReturn
7374 gst_matroska_demux_change_state (GstElement * element,
7375 GstStateChange transition)
7377 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (element);
7378 GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
7380 /* handle upwards state changes here */
7381 switch (transition) {
7386 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
7388 /* handle downwards state changes */
7389 switch (transition) {
7390 case GST_STATE_CHANGE_PAUSED_TO_READY:
7391 gst_matroska_demux_reset (GST_ELEMENT (demux));
7401 gst_matroska_demux_set_property (GObject * object,
7402 guint prop_id, const GValue * value, GParamSpec * pspec)
7404 GstMatroskaDemux *demux;
7406 g_return_if_fail (GST_IS_MATROSKA_DEMUX (object));
7407 demux = GST_MATROSKA_DEMUX (object);
7410 case PROP_MAX_GAP_TIME:
7411 GST_OBJECT_LOCK (demux);
7412 demux->max_gap_time = g_value_get_uint64 (value);
7413 GST_OBJECT_UNLOCK (demux);
7415 case PROP_MAX_BACKTRACK_DISTANCE:
7416 GST_OBJECT_LOCK (demux);
7417 demux->max_backtrack_distance = g_value_get_uint (value);
7418 GST_OBJECT_UNLOCK (demux);
7421 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
7427 gst_matroska_demux_get_property (GObject * object,
7428 guint prop_id, GValue * value, GParamSpec * pspec)
7430 GstMatroskaDemux *demux;
7432 g_return_if_fail (GST_IS_MATROSKA_DEMUX (object));
7433 demux = GST_MATROSKA_DEMUX (object);
7436 case PROP_MAX_GAP_TIME:
7437 GST_OBJECT_LOCK (demux);
7438 g_value_set_uint64 (value, demux->max_gap_time);
7439 GST_OBJECT_UNLOCK (demux);
7441 case PROP_MAX_BACKTRACK_DISTANCE:
7442 GST_OBJECT_LOCK (demux);
7443 g_value_set_uint (value, demux->max_backtrack_distance);
7444 GST_OBJECT_UNLOCK (demux);
7447 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
7452 static const gchar *
7453 gst_matroska_track_encryption_algorithm_name (gint val)
7456 GEnumClass *enum_class =
7457 g_type_class_ref (MATROSKA_TRACK_ENCRYPTION_ALGORITHM_TYPE);
7458 en = g_enum_get_value (G_ENUM_CLASS (enum_class), val);
7459 return en ? en->value_nick : NULL;
7462 static const gchar *
7463 gst_matroska_track_encryption_cipher_mode_name (gint val)
7466 GEnumClass *enum_class =
7467 g_type_class_ref (MATROSKA_TRACK_ENCRYPTION_CIPHER_MODE_TYPE);
7468 en = g_enum_get_value (G_ENUM_CLASS (enum_class), val);
7469 return en ? en->value_nick : NULL;
7472 static const gchar *
7473 gst_matroska_track_encoding_scope_name (gint val)
7476 GEnumClass *enum_class =
7477 g_type_class_ref (MATROSKA_TRACK_ENCODING_SCOPE_TYPE);
7479 en = g_enum_get_value (G_ENUM_CLASS (enum_class), val);
7480 return en ? en->value_nick : NULL;