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_ebml_offset = G_MAXUINT64;
330 if (demux->clusters) {
331 g_array_unref (demux->clusters);
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;
3403 guint64 ebml_offset = ebml->offset;
3405 DEBUG_ELEMENT_START (demux, ebml, "Tracks");
3407 if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
3408 DEBUG_ELEMENT_STOP (demux, ebml, "Tracks", ret);
3412 while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
3413 if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
3417 /* one track within the "all-tracks" header */
3418 case GST_MATROSKA_ID_TRACKENTRY:{
3419 GstMatroskaTrackContext *track;
3420 ret = gst_matroska_demux_parse_stream (demux, ebml, &track);
3421 if (track != NULL) {
3422 if (gst_matroska_read_common_tracknumber_unique (&demux->common,
3424 gst_matroska_demux_add_stream (demux, track);
3426 GST_ERROR_OBJECT (demux,
3427 "TrackNumber %" G_GUINT64_FORMAT " is not unique", track->num);
3428 ret = GST_FLOW_ERROR;
3429 gst_matroska_track_free (track);
3437 ret = gst_matroska_read_common_parse_skip (&demux->common, ebml,
3442 DEBUG_ELEMENT_STOP (demux, ebml, "Tracks", ret);
3444 demux->tracks_ebml_offset = ebml_offset;
3445 GST_DEBUG_OBJECT (demux, "signaling no more pads");
3446 gst_element_no_more_pads (GST_ELEMENT (demux));
3451 static GstFlowReturn
3452 gst_matroska_demux_update_tracks (GstMatroskaDemux * demux, GstEbmlRead * ebml)
3454 GstFlowReturn ret = GST_FLOW_OK;
3455 guint num_tracks_found = 0;
3458 GST_INFO_OBJECT (demux, "Reparsing Tracks element");
3460 DEBUG_ELEMENT_START (demux, ebml, "Tracks");
3462 if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
3463 DEBUG_ELEMENT_STOP (demux, ebml, "Tracks", ret);
3467 while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
3468 if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
3472 /* one track within the "all-tracks" header */
3473 case GST_MATROSKA_ID_TRACKENTRY:{
3474 GstMatroskaTrackContext *new_track;
3475 gint old_track_index;
3476 GstMatroskaTrackContext *old_track;
3477 ret = gst_matroska_demux_parse_stream (demux, ebml, &new_track);
3478 if (new_track == NULL)
3482 if (gst_matroska_read_common_tracknumber_unique (&demux->common,
3484 GST_ERROR_OBJECT (demux,
3485 "Unexpected new TrackNumber: %" G_GUINT64_FORMAT, new_track->num);
3486 goto track_mismatch_error;
3490 gst_matroska_read_common_stream_from_num (&demux->common,
3492 g_assert (old_track_index != -1);
3493 old_track = g_ptr_array_index (demux->common.src, old_track_index);
3495 if (old_track->type != new_track->type) {
3496 GST_ERROR_OBJECT (demux,
3497 "Mismatch reparsing track %" G_GUINT64_FORMAT
3498 " on track type. Expected %d, found %d", new_track->num,
3499 old_track->type, new_track->type);
3500 goto track_mismatch_error;
3503 if (g_strcmp0 (old_track->codec_id, new_track->codec_id) != 0) {
3504 GST_ERROR_OBJECT (demux,
3505 "Mismatch reparsing track %" G_GUINT64_FORMAT
3506 " on codec id. Expected '%s', found '%s'", new_track->num,
3507 old_track->codec_id, new_track->codec_id);
3508 goto track_mismatch_error;
3511 /* The new track matches the old track. No problems on our side.
3512 * Let's make it replace the old track. */
3513 new_track->pad = old_track->pad;
3514 new_track->index = old_track->index;
3515 new_track->pos = old_track->pos;
3517 /* If index table is empty, do not ref it, we will try to fallback
3518 * to the generic one from read-common in such case */
3519 if (old_track->index_table && old_track->index_table->len > 0)
3520 new_track->index_table = g_array_ref (old_track->index_table);
3522 g_ptr_array_index (demux->common.src, old_track_index) = new_track;
3523 gst_pad_set_element_private (new_track->pad, new_track);
3525 if (!gst_caps_is_equal (old_track->caps, new_track->caps)) {
3526 gst_pad_set_caps (new_track->pad, new_track->caps);
3528 gst_caps_replace (&old_track->caps, NULL);
3530 if (!gst_tag_list_is_equal (old_track->tags, new_track->tags)) {
3531 GST_DEBUG_OBJECT (old_track->pad, "Sending tags %p: %"
3532 GST_PTR_FORMAT, new_track->tags, new_track->tags);
3533 gst_pad_push_event (new_track->pad,
3534 gst_event_new_tag (gst_tag_list_copy (new_track->tags)));
3537 gst_matroska_track_free (old_track);
3540 track_mismatch_error:
3541 gst_matroska_track_free (new_track);
3543 ret = GST_FLOW_ERROR;
3548 ret = gst_matroska_read_common_parse_skip (&demux->common, ebml,
3553 DEBUG_ELEMENT_STOP (demux, ebml, "Tracks", ret);
3555 if (ret != GST_FLOW_ERROR && demux->common.num_streams != num_tracks_found) {
3556 GST_ERROR_OBJECT (demux,
3557 "Mismatch on the number of tracks. Expected %du tracks, found %du",
3558 demux->common.num_streams, num_tracks_found);
3559 ret = GST_FLOW_ERROR;
3566 * Read signed/unsigned "EBML" numbers.
3567 * Return: number of bytes processed.
3571 gst_matroska_ebmlnum_uint (guint8 * data, guint size, guint64 * num)
3573 gint len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
3581 while (read <= 8 && !(total & len_mask)) {
3588 if ((total &= (len_mask - 1)) == len_mask - 1)
3593 if (data[n] == 0xff)
3595 total = (total << 8) | data[n];
3599 if (read == num_ffs && total != 0)
3608 gst_matroska_ebmlnum_sint (guint8 * data, guint size, gint64 * num)
3613 /* read as unsigned number first */
3614 if ((res = gst_matroska_ebmlnum_uint (data, size, &unum)) < 0)
3618 if (unum == G_MAXUINT64)
3621 *num = unum - ((1 << ((7 * res) - 1)) - 1);
3627 * Mostly used for subtitles. We add void filler data for each
3628 * lagging stream to make sure we don't deadlock.
3632 gst_matroska_demux_sync_streams (GstMatroskaDemux * demux)
3634 GstClockTime gap_threshold;
3637 GST_OBJECT_LOCK (demux);
3639 GST_LOG_OBJECT (demux, "Sync to %" GST_TIME_FORMAT,
3640 GST_TIME_ARGS (demux->common.segment.position));
3642 g_assert (demux->common.num_streams == demux->common.src->len);
3643 for (stream_nr = 0; stream_nr < demux->common.src->len; stream_nr++) {
3644 GstMatroskaTrackContext *context;
3646 context = g_ptr_array_index (demux->common.src, stream_nr);
3648 GST_LOG_OBJECT (demux,
3649 "Checking for resync on stream %d (%" GST_TIME_FORMAT ")", stream_nr,
3650 GST_TIME_ARGS (context->pos));
3652 /* Only send gap events on non-subtitle streams if lagging way behind.
3653 * The 0.5 second threshold for subtitle streams is also quite random. */
3654 if (context->type == GST_MATROSKA_TRACK_TYPE_SUBTITLE)
3655 gap_threshold = GST_SECOND / 2;
3657 gap_threshold = 3 * GST_SECOND;
3659 /* Lag need only be considered if we have advanced into requested segment */
3660 if (GST_CLOCK_TIME_IS_VALID (context->pos) &&
3661 GST_CLOCK_TIME_IS_VALID (demux->common.segment.position) &&
3662 demux->common.segment.position > demux->common.segment.start &&
3663 context->pos + gap_threshold < demux->common.segment.position) {
3666 guint64 start = context->pos;
3667 guint64 stop = demux->common.segment.position - gap_threshold;
3669 GST_DEBUG_OBJECT (demux,
3670 "Synchronizing stream %d with other by advancing time from %"
3671 GST_TIME_FORMAT " to %" GST_TIME_FORMAT, stream_nr,
3672 GST_TIME_ARGS (start), GST_TIME_ARGS (stop));
3674 context->pos = stop;
3676 event = gst_event_new_gap (start, stop - start);
3677 GST_OBJECT_UNLOCK (demux);
3678 gst_pad_push_event (context->pad, event);
3679 GST_OBJECT_LOCK (demux);
3683 GST_OBJECT_UNLOCK (demux);
3686 static GstFlowReturn
3687 gst_matroska_demux_push_stream_headers (GstMatroskaDemux * demux,
3688 GstMatroskaTrackContext * stream)
3690 GstFlowReturn ret = GST_FLOW_OK;
3693 num = gst_buffer_list_length (stream->stream_headers);
3694 for (i = 0; i < num; ++i) {
3697 buf = gst_buffer_list_get (stream->stream_headers, i);
3698 buf = gst_buffer_copy (buf);
3700 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_HEADER);
3702 if (stream->set_discont) {
3703 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
3704 stream->set_discont = FALSE;
3706 GST_BUFFER_FLAG_UNSET (buf, GST_BUFFER_FLAG_DISCONT);
3709 /* push out all headers in one go and use last flow return */
3710 ret = gst_pad_push (stream->pad, buf);
3713 /* don't need these any longer */
3714 gst_buffer_list_unref (stream->stream_headers);
3715 stream->stream_headers = NULL;
3718 ret = gst_flow_combiner_update_flow (demux->flowcombiner, ret);
3724 gst_matroska_demux_push_dvd_clut_change_event (GstMatroskaDemux * demux,
3725 GstMatroskaTrackContext * stream)
3729 g_assert (!strcmp (stream->codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_VOBSUB));
3731 if (!stream->codec_priv)
3734 /* ideally, VobSub private data should be parsed and stored more convenient
3735 * elsewhere, but for now, only interested in a small part */
3737 /* make sure we have terminating 0 */
3738 buf = g_strndup (stream->codec_priv, stream->codec_priv_size);
3740 /* just locate and parse palette part */
3741 start = strstr (buf, "palette:");
3746 guint8 r, g, b, y, u, v;
3749 while (g_ascii_isspace (*start))
3751 for (i = 0; i < 16; i++) {
3752 if (sscanf (start, "%06x", &col) != 1)
3755 while ((*start == ',') || g_ascii_isspace (*start))
3757 /* sigh, need to convert this from vobsub pseudo-RGB to YUV */
3758 r = (col >> 16) & 0xff;
3759 g = (col >> 8) & 0xff;
3761 y = CLAMP ((0.1494 * r + 0.6061 * g + 0.2445 * b) * 219 / 255 + 16, 0,
3763 u = CLAMP (0.6066 * r - 0.4322 * g - 0.1744 * b + 128, 0, 255);
3764 v = CLAMP (-0.08435 * r - 0.3422 * g + 0.4266 * b + 128, 0, 255);
3765 clut[i] = (y << 16) | (u << 8) | v;
3768 /* got them all without problems; build and send event */
3772 s = gst_structure_new ("application/x-gst-dvd", "event", G_TYPE_STRING,
3773 "dvd-spu-clut-change", "clut00", G_TYPE_INT, clut[0], "clut01",
3774 G_TYPE_INT, clut[1], "clut02", G_TYPE_INT, clut[2], "clut03",
3775 G_TYPE_INT, clut[3], "clut04", G_TYPE_INT, clut[4], "clut05",
3776 G_TYPE_INT, clut[5], "clut06", G_TYPE_INT, clut[6], "clut07",
3777 G_TYPE_INT, clut[7], "clut08", G_TYPE_INT, clut[8], "clut09",
3778 G_TYPE_INT, clut[9], "clut10", G_TYPE_INT, clut[10], "clut11",
3779 G_TYPE_INT, clut[11], "clut12", G_TYPE_INT, clut[12], "clut13",
3780 G_TYPE_INT, clut[13], "clut14", G_TYPE_INT, clut[14], "clut15",
3781 G_TYPE_INT, clut[15], NULL);
3783 gst_pad_push_event (stream->pad,
3784 gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM_STICKY, s));
3791 gst_matroska_demux_push_codec_data_all (GstMatroskaDemux * demux)
3795 g_assert (demux->common.num_streams == demux->common.src->len);
3796 for (stream_nr = 0; stream_nr < demux->common.src->len; stream_nr++) {
3797 GstMatroskaTrackContext *stream;
3799 stream = g_ptr_array_index (demux->common.src, stream_nr);
3801 if (stream->send_stream_headers) {
3802 if (stream->stream_headers != NULL) {
3803 gst_matroska_demux_push_stream_headers (demux, stream);
3805 /* FIXME: perhaps we can just disable and skip this stream then */
3806 GST_ELEMENT_ERROR (demux, STREAM, DECODE, (NULL),
3807 ("Failed to extract stream headers from codec private data"));
3809 stream->send_stream_headers = FALSE;
3812 if (stream->send_dvd_event) {
3813 gst_matroska_demux_push_dvd_clut_change_event (demux, stream);
3814 /* FIXME: should we send this event again after (flushing) seek ? */
3815 stream->send_dvd_event = FALSE;
3821 static GstFlowReturn
3822 gst_matroska_demux_add_mpeg_seq_header (GstElement * element,
3823 GstMatroskaTrackContext * stream, GstBuffer ** buf)
3826 guint seq_header_len;
3827 guint32 header, tmp;
3829 if (stream->codec_state) {
3830 seq_header = stream->codec_state;
3831 seq_header_len = stream->codec_state_size;
3832 } else if (stream->codec_priv) {
3833 seq_header = stream->codec_priv;
3834 seq_header_len = stream->codec_priv_size;
3839 /* Sequence header only needed for keyframes */
3840 if (GST_BUFFER_FLAG_IS_SET (*buf, GST_BUFFER_FLAG_DELTA_UNIT))
3843 if (gst_buffer_get_size (*buf) < 4)
3846 gst_buffer_extract (*buf, 0, &tmp, sizeof (guint32));
3847 header = GUINT32_FROM_BE (tmp);
3849 /* Sequence start code, if not found prepend */
3850 if (header != 0x000001b3) {
3853 GST_DEBUG_OBJECT (element, "Prepending MPEG sequence header");
3855 newbuf = gst_buffer_new_memdup (seq_header, seq_header_len);
3857 gst_buffer_copy_into (newbuf, *buf, GST_BUFFER_COPY_TIMESTAMPS |
3858 GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_MEMORY, 0,
3859 gst_buffer_get_size (*buf));
3861 gst_buffer_unref (*buf);
3868 static GstFlowReturn
3869 gst_matroska_demux_add_wvpk_header (GstElement * element,
3870 GstMatroskaTrackContext * stream, GstBuffer ** buf)
3872 GstMatroskaTrackAudioContext *audiocontext =
3873 (GstMatroskaTrackAudioContext *) stream;
3874 GstBuffer *newbuf = NULL;
3875 GstMapInfo map, outmap;
3876 guint8 *buf_data, *data;
3884 wvh.version = GST_READ_UINT16_LE (stream->codec_priv);
3887 wvh.total_samples = -1;
3888 wvh.block_index = audiocontext->wvpk_block_index;
3890 if (audiocontext->channels <= 2) {
3891 guint32 block_samples, tmp;
3892 gsize size = gst_buffer_get_size (*buf);
3895 GST_ERROR_OBJECT (element, "Too small wavpack buffer");
3896 gst_buffer_unmap (*buf, &map);
3897 return GST_FLOW_ERROR;
3900 gst_buffer_extract (*buf, 0, &tmp, sizeof (guint32));
3901 block_samples = GUINT32_FROM_LE (tmp);
3902 /* we need to reconstruct the header of the wavpack block */
3904 /* -20 because ck_size is the size of the wavpack block -8
3905 * and lace_size is the size of the wavpack block + 12
3906 * (the three guint32 of the header that already are in the buffer) */
3907 wvh.ck_size = size + WAVPACK4_HEADER_SIZE - 20;
3909 /* block_samples, flags and crc are already in the buffer */
3910 newbuf = gst_buffer_new_allocate (NULL, WAVPACK4_HEADER_SIZE - 12, NULL);
3912 gst_buffer_map (newbuf, &outmap, GST_MAP_WRITE);
3918 GST_WRITE_UINT32_LE (data + 4, wvh.ck_size);
3919 GST_WRITE_UINT16_LE (data + 8, wvh.version);
3920 GST_WRITE_UINT8 (data + 10, wvh.track_no);
3921 GST_WRITE_UINT8 (data + 11, wvh.index_no);
3922 GST_WRITE_UINT32_LE (data + 12, wvh.total_samples);
3923 GST_WRITE_UINT32_LE (data + 16, wvh.block_index);
3924 gst_buffer_unmap (newbuf, &outmap);
3926 /* Append data from buf: */
3927 gst_buffer_copy_into (newbuf, *buf, GST_BUFFER_COPY_TIMESTAMPS |
3928 GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_MEMORY, 0, size);
3930 gst_buffer_unref (*buf);
3932 audiocontext->wvpk_block_index += block_samples;
3934 guint8 *outdata = NULL;
3935 gsize buf_size, size;
3936 guint32 block_samples, flags, crc, blocksize;
3937 GstAdapter *adapter;
3939 adapter = gst_adapter_new ();
3941 gst_buffer_map (*buf, &map, GST_MAP_READ);
3942 buf_data = map.data;
3943 buf_size = map.size;
3946 GST_ERROR_OBJECT (element, "Too small wavpack buffer");
3947 gst_buffer_unmap (*buf, &map);
3948 g_object_unref (adapter);
3949 return GST_FLOW_ERROR;
3955 block_samples = GST_READ_UINT32_LE (data);
3960 flags = GST_READ_UINT32_LE (data);
3963 crc = GST_READ_UINT32_LE (data);
3966 blocksize = GST_READ_UINT32_LE (data);
3970 if (blocksize == 0 || size < blocksize) {
3971 GST_ERROR_OBJECT (element, "Too small wavpack buffer");
3972 gst_buffer_unmap (*buf, &map);
3973 g_object_unref (adapter);
3974 return GST_FLOW_ERROR;
3977 g_assert (newbuf == NULL);
3980 gst_buffer_new_allocate (NULL, WAVPACK4_HEADER_SIZE + blocksize,
3982 gst_buffer_map (newbuf, &outmap, GST_MAP_WRITE);
3983 outdata = outmap.data;
3991 GST_WRITE_UINT32_LE (outdata, blocksize + WAVPACK4_HEADER_SIZE - 8);
3992 GST_WRITE_UINT16_LE (outdata + 4, wvh.version);
3993 GST_WRITE_UINT8 (outdata + 6, wvh.track_no);
3994 GST_WRITE_UINT8 (outdata + 7, wvh.index_no);
3995 GST_WRITE_UINT32_LE (outdata + 8, wvh.total_samples);
3996 GST_WRITE_UINT32_LE (outdata + 12, wvh.block_index);
3997 GST_WRITE_UINT32_LE (outdata + 16, block_samples);
3998 GST_WRITE_UINT32_LE (outdata + 20, flags);
3999 GST_WRITE_UINT32_LE (outdata + 24, crc);
4002 memcpy (outdata, data, blocksize);
4004 gst_buffer_unmap (newbuf, &outmap);
4005 gst_adapter_push (adapter, newbuf);
4011 gst_buffer_unmap (*buf, &map);
4013 newbuf = gst_adapter_take_buffer (adapter, gst_adapter_available (adapter));
4014 g_object_unref (adapter);
4016 gst_buffer_copy_into (newbuf, *buf,
4017 GST_BUFFER_COPY_TIMESTAMPS | GST_BUFFER_COPY_FLAGS, 0, -1);
4018 gst_buffer_unref (*buf);
4021 audiocontext->wvpk_block_index += block_samples;
4027 static GstFlowReturn
4028 gst_matroska_demux_add_prores_header (GstElement * element,
4029 GstMatroskaTrackContext * stream, GstBuffer ** buf)
4031 GstBuffer *newbuf = gst_buffer_new_allocate (NULL, 8, NULL);
4035 if (!gst_buffer_map (newbuf, &map, GST_MAP_WRITE)) {
4036 GST_ERROR ("Failed to map newly allocated buffer");
4037 return GST_FLOW_ERROR;
4040 frame_size = gst_buffer_get_size (*buf);
4042 GST_WRITE_UINT32_BE (map.data, frame_size);
4048 gst_buffer_unmap (newbuf, &map);
4049 *buf = gst_buffer_append (newbuf, *buf);
4054 /* @text must be null-terminated */
4056 gst_matroska_demux_subtitle_chunk_has_tag (GstElement * element,
4061 g_return_val_if_fail (text != NULL, FALSE);
4063 /* yes, this might all lead to false positives ... */
4064 tag = (gchar *) text;
4065 while ((tag = strchr (tag, '<'))) {
4067 if (*tag != '\0' && *(tag + 1) == '>') {
4068 /* some common convenience ones */
4069 /* maybe any character will do here ? */
4082 if (strstr (text, "<span"))
4088 static GstFlowReturn
4089 gst_matroska_demux_check_subtitle_buffer (GstElement * element,
4090 GstMatroskaTrackContext * stream, GstBuffer ** buf)
4092 GstMatroskaTrackSubtitleContext *sub_stream;
4093 const gchar *encoding;
4098 gboolean needs_unmap = TRUE;
4100 sub_stream = (GstMatroskaTrackSubtitleContext *) stream;
4102 if (!gst_buffer_get_size (*buf) || !gst_buffer_map (*buf, &map, GST_MAP_READ))
4105 /* The subtitle buffer we push out should not include a NUL terminator as
4106 * part of the data. */
4107 if (map.data[map.size - 1] == '\0') {
4108 gst_buffer_set_size (*buf, map.size - 1);
4109 gst_buffer_unmap (*buf, &map);
4110 gst_buffer_map (*buf, &map, GST_MAP_READ);
4113 if (!sub_stream->invalid_utf8) {
4114 if (g_utf8_validate ((gchar *) map.data, map.size, NULL)) {
4117 GST_WARNING_OBJECT (element, "subtitle stream %" G_GUINT64_FORMAT
4118 " is not valid UTF-8, this is broken according to the matroska"
4119 " specification", stream->num);
4120 sub_stream->invalid_utf8 = TRUE;
4123 /* file with broken non-UTF8 subtitle, do the best we can do to fix it */
4124 encoding = g_getenv ("GST_SUBTITLE_ENCODING");
4125 if (encoding == NULL || *encoding == '\0') {
4126 /* if local encoding is UTF-8 and no encoding specified
4127 * via the environment variable, assume ISO-8859-15 */
4128 if (g_get_charset (&encoding)) {
4129 encoding = "ISO-8859-15";
4134 g_convert_with_fallback ((gchar *) map.data, map.size, "UTF-8", encoding,
4135 (char *) "*", NULL, NULL, &err);
4138 GST_LOG_OBJECT (element, "could not convert string from '%s' to UTF-8: %s",
4139 encoding, err->message);
4143 /* invalid input encoding, fall back to ISO-8859-15 (always succeeds) */
4144 encoding = "ISO-8859-15";
4146 g_convert_with_fallback ((gchar *) map.data, map.size, "UTF-8",
4147 encoding, (char *) "*", NULL, NULL, NULL);
4150 GST_LOG_OBJECT (element, "converted subtitle text from %s to UTF-8 %s",
4151 encoding, (err) ? "(using ISO-8859-15 as fallback)" : "");
4154 utf8 = g_strdup ("invalid subtitle");
4156 newbuf = gst_buffer_new_wrapped (utf8, strlen (utf8));
4157 gst_buffer_unmap (*buf, &map);
4158 gst_buffer_copy_into (newbuf, *buf,
4159 GST_BUFFER_COPY_TIMESTAMPS | GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_META,
4161 gst_buffer_unref (*buf);
4164 gst_buffer_map (*buf, &map, GST_MAP_READ);
4168 if (sub_stream->check_markup) {
4169 /* caps claim markup text, so we need to escape text,
4170 * except if text is already markup and then needs no further escaping */
4171 sub_stream->seen_markup_tag = sub_stream->seen_markup_tag ||
4172 gst_matroska_demux_subtitle_chunk_has_tag (element, (gchar *) map.data);
4174 if (!sub_stream->seen_markup_tag) {
4175 utf8 = g_markup_escape_text ((gchar *) map.data, map.size);
4177 newbuf = gst_buffer_new_wrapped (utf8, strlen (utf8));
4178 gst_buffer_unmap (*buf, &map);
4179 gst_buffer_copy_into (newbuf, *buf,
4180 GST_BUFFER_COPY_TIMESTAMPS | GST_BUFFER_COPY_FLAGS |
4181 GST_BUFFER_COPY_META, 0, -1);
4182 gst_buffer_unref (*buf);
4185 needs_unmap = FALSE;
4190 gst_buffer_unmap (*buf, &map);
4195 static GstFlowReturn
4196 gst_matroska_demux_check_aac (GstElement * element,
4197 GstMatroskaTrackContext * stream, GstBuffer ** buf)
4202 gst_buffer_extract (*buf, 0, data, 2);
4203 size = gst_buffer_get_size (*buf);
4205 if (size > 2 && data[0] == 0xff && (data[1] >> 4 == 0x0f)) {
4208 /* tss, ADTS data, remove codec_data
4209 * still assume it is at least parsed */
4210 stream->caps = gst_caps_make_writable (stream->caps);
4211 s = gst_caps_get_structure (stream->caps, 0);
4213 gst_structure_remove_field (s, "codec_data");
4214 gst_pad_set_caps (stream->pad, stream->caps);
4215 GST_DEBUG_OBJECT (element, "ADTS AAC audio data; removing codec-data, "
4216 "new caps: %" GST_PTR_FORMAT, stream->caps);
4219 /* disable subsequent checking */
4220 stream->postprocess_frame = NULL;
4226 gst_matroska_demux_align_buffer (GstMatroskaDemux * demux,
4227 GstBuffer * buffer, gsize alignment)
4231 gst_buffer_map (buffer, &map, GST_MAP_READ);
4233 if (map.size < sizeof (guintptr)) {
4234 gst_buffer_unmap (buffer, &map);
4238 if (((guintptr) map.data) & (alignment - 1)) {
4239 GstBuffer *new_buffer;
4240 GstAllocationParams params = { 0, alignment - 1, 0, 0, };
4242 new_buffer = gst_buffer_new_allocate (NULL,
4243 gst_buffer_get_size (buffer), ¶ms);
4245 /* Copy data "by hand", so ensure alignment is kept: */
4246 gst_buffer_fill (new_buffer, 0, map.data, map.size);
4248 gst_buffer_copy_into (new_buffer, buffer, GST_BUFFER_COPY_METADATA, 0, -1);
4249 GST_DEBUG_OBJECT (demux,
4250 "We want output aligned on %" G_GSIZE_FORMAT ", reallocated",
4253 gst_buffer_unmap (buffer, &map);
4254 gst_buffer_unref (buffer);
4259 gst_buffer_unmap (buffer, &map);
4270 static GstFlowReturn
4271 gst_matroska_demux_parse_blockmore (GstMatroskaDemux * demux,
4272 GstEbmlRead * ebml, GQueue * additions)
4276 guint64 block_id = 1;
4277 guint64 datalen = 0;
4278 guint8 *data = NULL;
4280 ret = gst_ebml_read_master (ebml, &id); /* GST_MATROSKA_ID_BLOCKMORE */
4281 if (ret != GST_FLOW_OK)
4284 /* read all BlockMore sub-entries */
4285 while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
4287 if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
4291 case GST_MATROSKA_ID_BLOCKADDID:
4292 ret = gst_ebml_read_uint (ebml, &id, &block_id);
4296 case GST_MATROSKA_ID_BLOCKADDITIONAL:
4300 ret = gst_ebml_read_binary (ebml, &id, &data, &datalen);
4303 ret = gst_matroska_read_common_parse_skip (&demux->common, ebml,
4309 if (data != NULL && datalen > 0) {
4310 BlockAddition *blockadd = g_new (BlockAddition, 1);
4312 GST_LOG_OBJECT (demux, "BlockAddition %" G_GUINT64_FORMAT ": "
4313 "%" G_GUINT64_FORMAT " bytes", block_id, datalen);
4314 GST_MEMDUMP_OBJECT (demux, "BlockAdditional", data, datalen);
4315 blockadd->data = data;
4316 blockadd->size = datalen;
4317 blockadd->id = block_id;
4318 g_queue_push_tail (additions, blockadd);
4319 GST_LOG_OBJECT (demux, "now %d pending block additions", additions->length);
4330 static GstFlowReturn
4331 gst_matroska_demux_parse_blockadditions (GstMatroskaDemux * demux,
4332 GstEbmlRead * ebml, GQueue * additions)
4337 ret = gst_ebml_read_master (ebml, &id); /* GST_MATROSKA_ID_BLOCKADDITIONS */
4338 if (ret != GST_FLOW_OK)
4341 /* read all BlockMore sub-entries */
4342 while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
4344 if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
4347 if (id == GST_MATROSKA_ID_BLOCKMORE) {
4348 DEBUG_ELEMENT_START (demux, ebml, "BlockMore");
4349 ret = gst_matroska_demux_parse_blockmore (demux, ebml, additions);
4350 DEBUG_ELEMENT_STOP (demux, ebml, "BlockMore", ret);
4351 if (ret != GST_FLOW_OK)
4354 GST_WARNING_OBJECT (demux, "Expected BlockMore, got %x", id);
4361 static GstFlowReturn
4362 gst_matroska_demux_parse_blockgroup_or_simpleblock (GstMatroskaDemux * demux,
4363 GstEbmlRead * ebml, guint64 cluster_time, guint64 cluster_offset,
4364 gboolean is_simpleblock)
4366 GstMatroskaTrackContext *stream = NULL;
4367 GstFlowReturn ret = GST_FLOW_OK;
4368 gboolean readblock = FALSE;
4370 guint64 block_duration = -1;
4371 gint64 block_discardpadding = 0;
4372 GstBuffer *buf = NULL;
4374 gint stream_num = -1, n, laces = 0;
4376 gint *lace_size = NULL;
4379 gint64 referenceblock = 0;
4381 GstClockTime buffer_timestamp;
4382 GQueue additions = G_QUEUE_INIT;
4384 offset = gst_ebml_read_get_offset (ebml);
4386 while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
4387 if (!is_simpleblock) {
4388 if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK) {
4392 id = GST_MATROSKA_ID_SIMPLEBLOCK;
4396 /* one block inside the group. Note, block parsing is one
4397 * of the harder things, so this code is a bit complicated.
4398 * See http://www.matroska.org/ for documentation. */
4399 case GST_MATROSKA_ID_SIMPLEBLOCK:
4400 case GST_MATROSKA_ID_BLOCK:
4406 gst_buffer_unmap (buf, &map);
4407 gst_buffer_unref (buf);
4410 if ((ret = gst_ebml_read_buffer (ebml, &id, &buf)) != GST_FLOW_OK)
4413 gst_buffer_map (buf, &map, GST_MAP_READ);
4417 /* first byte(s): blocknum */
4418 if ((n = gst_matroska_ebmlnum_uint (data, size, &num)) < 0)
4423 /* fetch stream from num */
4424 stream_num = gst_matroska_read_common_stream_from_num (&demux->common,
4426 if (G_UNLIKELY (size < 3)) {
4427 GST_WARNING_OBJECT (demux, "Invalid size %u", size);
4428 /* non-fatal, try next block(group) */
4431 } else if (G_UNLIKELY (stream_num < 0 ||
4432 stream_num >= demux->common.num_streams)) {
4433 /* let's not give up on a stray invalid track number */
4434 GST_WARNING_OBJECT (demux,
4435 "Invalid stream %d for track number %" G_GUINT64_FORMAT
4436 "; ignoring block", stream_num, num);
4440 stream = g_ptr_array_index (demux->common.src, stream_num);
4442 /* time (relative to cluster time) */
4443 time = ((gint16) GST_READ_UINT16_BE (data));
4446 flags = GST_READ_UINT8 (data);
4450 GST_LOG_OBJECT (demux, "time %" G_GUINT64_FORMAT ", flags %d", time,
4453 switch ((flags & 0x06) >> 1) {
4454 case 0x0: /* no lacing */
4456 lace_size = g_new (gint, 1);
4457 lace_size[0] = size;
4460 case 0x1: /* xiph lacing */
4461 case 0x2: /* fixed-size lacing */
4462 case 0x3: /* EBML lacing */
4464 goto invalid_lacing;
4465 laces = GST_READ_UINT8 (data) + 1;
4468 lace_size = g_new0 (gint, laces);
4470 switch ((flags & 0x06) >> 1) {
4471 case 0x1: /* xiph lacing */ {
4472 guint temp, total = 0;
4474 for (n = 0; ret == GST_FLOW_OK && n < laces - 1; n++) {
4477 goto invalid_lacing;
4478 temp = GST_READ_UINT8 (data);
4479 lace_size[n] += temp;
4485 total += lace_size[n];
4487 lace_size[n] = size - total;
4491 case 0x2: /* fixed-size lacing */
4492 for (n = 0; n < laces; n++)
4493 lace_size[n] = size / laces;
4496 case 0x3: /* EBML lacing */ {
4499 if ((n = gst_matroska_ebmlnum_uint (data, size, &num)) < 0)
4503 total = lace_size[0] = num;
4504 for (n = 1; ret == GST_FLOW_OK && n < laces - 1; n++) {
4508 if ((r = gst_matroska_ebmlnum_sint (data, size, &snum)) < 0)
4512 lace_size[n] = lace_size[n - 1] + snum;
4513 total += lace_size[n];
4516 lace_size[n] = size - total;
4523 if (ret != GST_FLOW_OK)
4530 case GST_MATROSKA_ID_BLOCKADDITIONS:
4532 DEBUG_ELEMENT_START (demux, ebml, "BlockAdditions");
4533 ret = gst_matroska_demux_parse_blockadditions (demux, ebml, &additions);
4534 DEBUG_ELEMENT_STOP (demux, ebml, "BlockAdditions", ret);
4538 case GST_MATROSKA_ID_BLOCKDURATION:{
4539 ret = gst_ebml_read_uint (ebml, &id, &block_duration);
4540 GST_DEBUG_OBJECT (demux, "BlockDuration: %" G_GUINT64_FORMAT,
4545 case GST_MATROSKA_ID_DISCARDPADDING:{
4546 ret = gst_ebml_read_sint (ebml, &id, &block_discardpadding);
4547 GST_DEBUG_OBJECT (demux, "DiscardPadding: %" GST_STIME_FORMAT,
4548 GST_STIME_ARGS (block_discardpadding));
4552 case GST_MATROSKA_ID_REFERENCEBLOCK:{
4553 ret = gst_ebml_read_sint (ebml, &id, &referenceblock);
4554 GST_DEBUG_OBJECT (demux, "ReferenceBlock: %" G_GINT64_FORMAT,
4559 case GST_MATROSKA_ID_CODECSTATE:{
4561 guint64 data_len = 0;
4564 gst_ebml_read_binary (ebml, &id, &data,
4565 &data_len)) != GST_FLOW_OK)
4568 if (G_UNLIKELY (stream == NULL)) {
4569 GST_WARNING_OBJECT (demux,
4570 "Unexpected CodecState subelement - ignoring");
4574 g_free (stream->codec_state);
4575 stream->codec_state = data;
4576 stream->codec_state_size = data_len;
4578 /* Decode if necessary */
4579 if (stream->encodings && stream->encodings->len > 0
4580 && stream->codec_state && stream->codec_state_size > 0) {
4581 if (!gst_matroska_decode_data (stream->encodings,
4582 &stream->codec_state, &stream->codec_state_size,
4583 GST_MATROSKA_TRACK_ENCODING_SCOPE_CODEC_DATA, TRUE)) {
4584 GST_WARNING_OBJECT (demux, "Decoding codec state failed");
4588 GST_DEBUG_OBJECT (demux, "CodecState of %" G_GSIZE_FORMAT " bytes",
4589 stream->codec_state_size);
4594 ret = gst_matroska_read_common_parse_skip (&demux->common, ebml,
4598 case GST_MATROSKA_ID_BLOCKVIRTUAL:
4599 case GST_MATROSKA_ID_REFERENCEPRIORITY:
4600 case GST_MATROSKA_ID_REFERENCEVIRTUAL:
4601 case GST_MATROSKA_ID_SLICES:
4602 GST_DEBUG_OBJECT (demux,
4603 "Skipping BlockGroup subelement 0x%x - ignoring", id);
4604 ret = gst_ebml_read_skip (ebml);
4612 /* reading a number or so could have failed */
4613 if (ret != GST_FLOW_OK)
4616 if (ret == GST_FLOW_OK && readblock) {
4617 gboolean invisible_frame = FALSE;
4618 gboolean delta_unit = FALSE;
4619 guint64 duration = 0;
4620 gint64 lace_time = 0;
4621 gboolean keep_seek_start = TRUE;
4622 GstEvent *protect_event;
4624 stream = g_ptr_array_index (demux->common.src, stream_num);
4626 if (cluster_time != GST_CLOCK_TIME_NONE) {
4627 /* FIXME: What to do with negative timestamps? Give timestamp 0 or -1?
4628 * Drop unless the lace contains timestamp 0? */
4629 if (time < 0 && (-time) > cluster_time) {
4632 if (stream->timecodescale == 1.0)
4633 lace_time = (cluster_time + time) * demux->common.time_scale;
4636 gst_util_guint64_to_gdouble ((cluster_time + time) *
4637 demux->common.time_scale) * stream->timecodescale;
4640 lace_time = GST_CLOCK_TIME_NONE;
4642 /* Send the GST_PROTECTION event */
4643 while ((protect_event = g_queue_pop_head (&stream->protection_event_queue))) {
4644 GST_TRACE_OBJECT (demux, "pushing protection event for stream %d:%s",
4645 stream->index, GST_STR_NULL (stream->name));
4646 gst_pad_push_event (stream->pad, protect_event);
4649 /* need to refresh segment info ASAP */
4650 if (GST_CLOCK_TIME_IS_VALID (lace_time)
4651 && GST_CLOCK_TIME_IS_VALID (demux->stream_start_time)
4652 && lace_time < demux->stream_start_time) {
4654 (demux->common.segment.start > demux->stream_start_time);
4655 demux->stream_start_time = lace_time;
4656 demux->need_segment = TRUE;
4659 if (GST_CLOCK_TIME_IS_VALID (lace_time) && demux->need_segment) {
4660 GstSegment *segment = &demux->common.segment;
4662 GstEvent *segment_event;
4664 if (!GST_CLOCK_TIME_IS_VALID (demux->stream_start_time)) {
4665 demux->stream_start_time = lace_time;
4666 GST_DEBUG_OBJECT (demux,
4667 "Setting stream start time to %" GST_TIME_FORMAT,
4668 GST_TIME_ARGS (lace_time));
4670 clace_time = MAX (lace_time, demux->stream_start_time);
4672 && GST_CLOCK_TIME_IS_VALID (demux->common.segment.position)
4673 && demux->common.segment.position != 0) {
4674 GST_DEBUG_OBJECT (demux, "using stored seek position %" GST_TIME_FORMAT,
4675 GST_TIME_ARGS (demux->common.segment.position));
4676 clace_time = demux->common.segment.position;
4678 segment->start = clace_time;
4679 segment->stop = demux->common.segment.stop;
4680 segment->time = segment->start - demux->stream_start_time;
4681 segment->position = segment->start - demux->stream_start_time;
4682 GST_DEBUG_OBJECT (demux,
4683 "generated segment starting at %" GST_TIME_FORMAT ": %"
4684 GST_SEGMENT_FORMAT, GST_TIME_ARGS (lace_time), segment);
4685 /* now convey our segment notion downstream */
4686 segment_event = gst_event_new_segment (segment);
4687 if (demux->segment_seqnum)
4688 gst_event_set_seqnum (segment_event, demux->segment_seqnum);
4689 gst_matroska_demux_send_event (demux, segment_event);
4690 demux->need_segment = FALSE;
4691 demux->segment_seqnum = 0;
4694 /* send pending codec data headers for all streams,
4695 * before we perform sync across all streams */
4696 gst_matroska_demux_push_codec_data_all (demux);
4698 if (block_duration != -1) {
4699 if (stream->timecodescale == 1.0)
4700 duration = gst_util_uint64_scale (block_duration,
4701 demux->common.time_scale, 1);
4704 gst_util_gdouble_to_guint64 (gst_util_guint64_to_gdouble
4705 (gst_util_uint64_scale (block_duration, demux->common.time_scale,
4706 1)) * stream->timecodescale);
4707 } else if (stream->default_duration) {
4708 duration = stream->default_duration * laces;
4710 /* else duration is diff between timecode of this and next block */
4712 if (stream->type == GST_MATROSKA_TRACK_TYPE_VIDEO) {
4713 /* For SimpleBlock, look at the keyframe bit in flags. Otherwise,
4714 a ReferenceBlock implies that this is not a keyframe. In either
4715 case, it only makes sense for video streams. */
4716 if ((is_simpleblock && !(flags & 0x80)) || referenceblock) {
4718 invisible_frame = ((flags & 0x08)) &&
4719 (!strcmp (stream->codec_id, GST_MATROSKA_CODEC_ID_VIDEO_VP8) ||
4720 !strcmp (stream->codec_id, GST_MATROSKA_CODEC_ID_VIDEO_VP9) ||
4721 !strcmp (stream->codec_id, GST_MATROSKA_CODEC_ID_VIDEO_AV1));
4724 /* If we're doing a keyframe-only trickmode, only push keyframes on video
4727 && demux->common.segment.
4728 flags & GST_SEGMENT_FLAG_TRICKMODE_KEY_UNITS) {
4729 GST_LOG_OBJECT (demux, "Skipping non-keyframe on stream %d",
4736 for (n = 0; n < laces; n++) {
4739 if (G_UNLIKELY (lace_size[n] > size)) {
4740 GST_WARNING_OBJECT (demux, "Invalid lace size");
4744 /* QoS for video track with an index. the assumption is that
4745 index entries point to keyframes, but if that is not true we
4746 will instead skip until the next keyframe. */
4747 if (GST_CLOCK_TIME_IS_VALID (lace_time) &&
4748 stream->type == GST_MATROSKA_TRACK_TYPE_VIDEO &&
4749 stream->index_table && demux->common.segment.rate > 0.0) {
4750 GstMatroskaTrackVideoContext *videocontext =
4751 (GstMatroskaTrackVideoContext *) stream;
4752 GstClockTime earliest_time;
4753 GstClockTime earliest_stream_time;
4755 GST_OBJECT_LOCK (demux);
4756 earliest_time = videocontext->earliest_time;
4757 GST_OBJECT_UNLOCK (demux);
4758 earliest_stream_time =
4759 gst_segment_position_from_running_time (&demux->common.segment,
4760 GST_FORMAT_TIME, earliest_time);
4762 if (GST_CLOCK_TIME_IS_VALID (lace_time) &&
4763 GST_CLOCK_TIME_IS_VALID (earliest_stream_time) &&
4764 lace_time <= earliest_stream_time) {
4765 /* find index entry (keyframe) <= earliest_stream_time */
4766 GstMatroskaIndex *entry =
4767 gst_util_array_binary_search (stream->index_table->data,
4768 stream->index_table->len, sizeof (GstMatroskaIndex),
4769 (GCompareDataFunc) gst_matroska_index_seek_find,
4770 GST_SEARCH_MODE_BEFORE, &earliest_stream_time, NULL);
4772 /* if that entry (keyframe) is after the current the current
4773 buffer, we can skip pushing (and thus decoding) all
4774 buffers until that keyframe. */
4775 if (entry && GST_CLOCK_TIME_IS_VALID (entry->time) &&
4776 entry->time > lace_time) {
4777 GST_LOG_OBJECT (demux, "Skipping lace before late keyframe");
4778 stream->set_discont = TRUE;
4784 sub = gst_buffer_copy_region (buf, GST_BUFFER_COPY_ALL,
4785 gst_buffer_get_size (buf) - size, lace_size[n]);
4786 GST_DEBUG_OBJECT (demux, "created subbuffer %p", sub);
4789 GST_BUFFER_FLAG_SET (sub, GST_BUFFER_FLAG_DELTA_UNIT);
4791 GST_BUFFER_FLAG_UNSET (sub, GST_BUFFER_FLAG_DELTA_UNIT);
4793 if (invisible_frame)
4794 GST_BUFFER_FLAG_SET (sub, GST_BUFFER_FLAG_DECODE_ONLY);
4796 if (stream->encodings != NULL && stream->encodings->len > 0)
4797 sub = gst_matroska_decode_buffer (stream, sub);
4800 GST_WARNING_OBJECT (demux, "Decoding buffer failed");
4804 if (!stream->dts_only) {
4805 GST_BUFFER_PTS (sub) = lace_time;
4807 GST_BUFFER_DTS (sub) = lace_time;
4808 if (stream->intra_only)
4809 GST_BUFFER_PTS (sub) = lace_time;
4812 buffer_timestamp = gst_matroska_track_get_buffer_timestamp (stream, sub);
4814 if (GST_CLOCK_TIME_IS_VALID (lace_time)) {
4815 GstClockTime last_stop_end;
4817 /* Check if this stream is after segment stop,
4818 * but only terminate if we hit the next keyframe,
4819 * to make sure that all frames potentially inside the segment
4820 * are available to the decoder for decoding / reordering.*/
4821 if (!delta_unit && GST_CLOCK_TIME_IS_VALID (demux->common.segment.stop)
4822 && lace_time >= demux->common.segment.stop) {
4823 GST_DEBUG_OBJECT (demux,
4824 "Stream %d lace time: %" GST_TIME_FORMAT " after segment stop: %"
4825 GST_TIME_FORMAT, stream->index, GST_TIME_ARGS (lace_time),
4826 GST_TIME_ARGS (demux->common.segment.stop));
4827 gst_buffer_unref (sub);
4830 if (offset >= stream->to_offset
4831 || (GST_CLOCK_TIME_IS_VALID (demux->to_time)
4832 && lace_time > demux->to_time)) {
4833 GST_DEBUG_OBJECT (demux, "Stream %d after playback section",
4835 gst_buffer_unref (sub);
4839 /* handle gaps, e.g. non-zero start-time, or an cue index entry
4840 * that landed us with timestamps not quite intended */
4841 GST_OBJECT_LOCK (demux);
4842 if (demux->max_gap_time &&
4843 GST_CLOCK_TIME_IS_VALID (demux->last_stop_end) &&
4844 demux->common.segment.rate > 0.0) {
4845 GstClockTimeDiff diff;
4847 /* only send segments with increasing start times,
4848 * otherwise if these go back and forth downstream (sinks) increase
4849 * accumulated time and running_time */
4850 diff = GST_CLOCK_DIFF (demux->last_stop_end, lace_time);
4851 if (diff > 0 && diff > demux->max_gap_time
4852 && lace_time > demux->common.segment.start
4853 && (!GST_CLOCK_TIME_IS_VALID (demux->common.segment.stop)
4854 || lace_time < demux->common.segment.stop)) {
4856 GST_DEBUG_OBJECT (demux,
4857 "Gap of %" G_GINT64_FORMAT " ns detected in"
4858 "stream %d (%" GST_TIME_FORMAT " -> %" GST_TIME_FORMAT "). "
4859 "Sending updated SEGMENT events", diff,
4860 stream->index, GST_TIME_ARGS (stream->pos),
4861 GST_TIME_ARGS (lace_time));
4863 event = gst_event_new_gap (demux->last_stop_end, diff);
4864 GST_OBJECT_UNLOCK (demux);
4865 gst_pad_push_event (stream->pad, event);
4866 GST_OBJECT_LOCK (demux);
4870 if (!GST_CLOCK_TIME_IS_VALID (demux->common.segment.position)
4871 || demux->common.segment.position < lace_time) {
4872 demux->common.segment.position = lace_time;
4874 GST_OBJECT_UNLOCK (demux);
4876 last_stop_end = lace_time;
4878 GST_BUFFER_DURATION (sub) = duration / laces;
4879 last_stop_end += GST_BUFFER_DURATION (sub);
4882 if (!GST_CLOCK_TIME_IS_VALID (demux->last_stop_end) ||
4883 demux->last_stop_end < last_stop_end)
4884 demux->last_stop_end = last_stop_end;
4886 GST_OBJECT_LOCK (demux);
4887 if (demux->common.segment.duration == -1 ||
4888 demux->stream_start_time + demux->common.segment.duration <
4890 demux->common.segment.duration =
4891 last_stop_end - demux->stream_start_time;
4892 GST_OBJECT_UNLOCK (demux);
4893 if (!demux->invalid_duration) {
4894 gst_element_post_message (GST_ELEMENT_CAST (demux),
4895 gst_message_new_duration_changed (GST_OBJECT_CAST (demux)));
4896 demux->invalid_duration = TRUE;
4899 GST_OBJECT_UNLOCK (demux);
4903 stream->pos = lace_time;
4905 gst_matroska_demux_sync_streams (demux);
4907 if (stream->set_discont) {
4908 GST_DEBUG_OBJECT (demux, "marking DISCONT");
4909 GST_BUFFER_FLAG_SET (sub, GST_BUFFER_FLAG_DISCONT);
4910 stream->set_discont = FALSE;
4912 GST_BUFFER_FLAG_UNSET (sub, GST_BUFFER_FLAG_DISCONT);
4915 /* reverse playback book-keeping */
4916 if (!GST_CLOCK_TIME_IS_VALID (stream->from_time))
4917 stream->from_time = lace_time;
4918 if (stream->from_offset == -1)
4919 stream->from_offset = offset;
4921 GST_DEBUG_OBJECT (demux,
4922 "Pushing lace %d, data of size %" G_GSIZE_FORMAT
4923 " for stream %d, time=%" GST_TIME_FORMAT " and duration=%"
4924 GST_TIME_FORMAT, n, gst_buffer_get_size (sub), stream_num,
4925 GST_TIME_ARGS (buffer_timestamp),
4926 GST_TIME_ARGS (GST_BUFFER_DURATION (sub)));
4929 if (demux->common.element_index) {
4930 if (stream->index_writer_id == -1)
4931 gst_index_get_writer_id (demux->common.element_index,
4932 GST_OBJECT (stream->pad), &stream->index_writer_id);
4934 GST_LOG_OBJECT (demux, "adding association %" GST_TIME_FORMAT "-> %"
4935 G_GUINT64_FORMAT " for writer id %d",
4936 GST_TIME_ARGS (buffer_timestamp), cluster_offset,
4937 stream->index_writer_id);
4938 gst_index_add_association (demux->common.element_index,
4939 stream->index_writer_id, GST_BUFFER_FLAG_IS_SET (sub,
4940 GST_BUFFER_FLAG_DELTA_UNIT) ? 0 : GST_ASSOCIATION_FLAG_KEY_UNIT,
4941 GST_FORMAT_TIME, buffer_timestamp, GST_FORMAT_BYTES, cluster_offset,
4946 /* Postprocess the buffers depending on the codec used */
4947 if (stream->postprocess_frame) {
4948 GST_LOG_OBJECT (demux, "running post process");
4949 ret = stream->postprocess_frame (GST_ELEMENT (demux), stream, &sub);
4952 /* At this point, we have a sub-buffer pointing at data within a larger
4953 buffer. This data might not be aligned with anything. If the data is
4954 raw samples though, we want it aligned to the raw type (eg, 4 bytes
4955 for 32 bit samples, etc), or bad things will happen downstream as
4956 elements typically assume minimal alignment.
4957 Therefore, create an aligned copy if necessary. */
4958 sub = gst_matroska_demux_align_buffer (demux, sub, stream->alignment);
4960 if (!strcmp (stream->codec_id, GST_MATROSKA_CODEC_ID_AUDIO_OPUS)) {
4961 guint64 start_clip = 0, end_clip = 0;
4963 /* Codec delay is part of the timestamps */
4964 if (GST_BUFFER_PTS_IS_VALID (sub) && stream->codec_delay) {
4965 if (GST_BUFFER_PTS (sub) > stream->codec_delay) {
4966 GST_BUFFER_PTS (sub) -= stream->codec_delay;
4968 GST_BUFFER_PTS (sub) = 0;
4970 /* Opus GstAudioClippingMeta units are scaled by 48000/sample_rate.
4971 That is, if a Opus track has audio encoded at 24000 Hz and 132
4972 samples need to be clipped, GstAudioClippingMeta.start will be
4973 set to 264. (This is also the case for buffer offsets.)
4974 Opus sample rates are always divisors of 48000 Hz, which is the
4975 maximum allowed sample rate. */
4977 gst_util_uint64_scale_round (stream->codec_delay, 48000,
4980 if (GST_BUFFER_DURATION_IS_VALID (sub)) {
4981 if (GST_BUFFER_DURATION (sub) > stream->codec_delay)
4982 GST_BUFFER_DURATION (sub) -= stream->codec_delay;
4984 GST_BUFFER_DURATION (sub) = 0;
4989 if (block_discardpadding) {
4991 gst_util_uint64_scale_round (block_discardpadding, 48000,
4995 if (start_clip || end_clip) {
4996 gst_buffer_add_audio_clipping_meta (sub, GST_FORMAT_DEFAULT,
4997 start_clip, end_clip);
5001 if (GST_BUFFER_PTS_IS_VALID (sub)) {
5002 stream->pos = GST_BUFFER_PTS (sub);
5003 if (GST_BUFFER_DURATION_IS_VALID (sub))
5004 stream->pos += GST_BUFFER_DURATION (sub);
5005 } else if (GST_BUFFER_DTS_IS_VALID (sub)) {
5006 stream->pos = GST_BUFFER_DTS (sub);
5007 if (GST_BUFFER_DURATION_IS_VALID (sub))
5008 stream->pos += GST_BUFFER_DURATION (sub);
5011 /* Attach BlockAdditions to buffer; we assume a single buffer per group
5013 if (additions.length > 0) {
5014 BlockAddition *blockadd;
5017 GST_FIXME_OBJECT (demux, "Fix block additions with laced buffers");
5019 while ((blockadd = g_queue_pop_head (&additions))) {
5020 GstMatroskaTrackVideoContext *videocontext =
5021 (GstMatroskaTrackVideoContext *) stream;
5022 if (blockadd->id == 1 && videocontext->alpha_mode
5023 && (!strcmp (stream->codec_id, GST_MATROSKA_CODEC_ID_VIDEO_VP8)
5024 || !strcmp (stream->codec_id,
5025 GST_MATROSKA_CODEC_ID_VIDEO_VP9))) {
5026 GstBuffer *alpha_buffer;
5028 GST_TRACE_OBJECT (demux, "adding block addition %u as VP8/VP9 "
5029 "alpha meta to buffer %p, %u bytes", (guint) blockadd->id, buf,
5030 (guint) blockadd->size);
5032 alpha_buffer = gst_buffer_new_wrapped (blockadd->data,
5034 gst_buffer_copy_into (alpha_buffer, sub,
5035 GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_TIMESTAMPS, 0, -1);
5036 gst_buffer_add_video_codec_alpha_meta (sub, alpha_buffer);
5038 g_free (blockadd->data);
5044 ret = gst_pad_push (stream->pad, sub);
5046 if (demux->common.segment.rate < 0) {
5047 if (lace_time > demux->common.segment.stop && ret == GST_FLOW_EOS) {
5048 /* In reverse playback we can get a GST_FLOW_EOS when
5049 * we are at the end of the segment, so we just need to jump
5050 * back to the previous section. */
5051 GST_DEBUG_OBJECT (demux, "downstream has reached end of segment");
5056 ret = gst_flow_combiner_update_pad_flow (demux->flowcombiner,
5060 size -= lace_size[n];
5061 if (lace_time != GST_CLOCK_TIME_NONE && duration)
5062 lace_time += duration / laces;
5064 lace_time = GST_CLOCK_TIME_NONE;
5070 gst_buffer_unmap (buf, &map);
5071 gst_buffer_unref (buf);
5075 BlockAddition *blockadd;
5077 while ((blockadd = g_queue_pop_head (&additions))) {
5078 g_free (blockadd->data);
5090 ret = gst_flow_combiner_update_pad_flow (demux->flowcombiner, stream->pad,
5096 GST_ELEMENT_WARNING (demux, STREAM, DEMUX, (NULL), ("Invalid lacing size"));
5097 /* non-fatal, try next block(group) */
5103 GST_ELEMENT_WARNING (demux, STREAM, DEMUX, (NULL), ("Data error"));
5104 /* non-fatal, try next block(group) */
5110 /* return FALSE if block(group) should be skipped (due to a seek) */
5111 static inline gboolean
5112 gst_matroska_demux_seek_block (GstMatroskaDemux * demux)
5114 if (G_UNLIKELY (demux->seek_block)) {
5115 if (!(--demux->seek_block)) {
5118 GST_LOG_OBJECT (demux, "should skip block due to seek");
5126 static GstFlowReturn
5127 gst_matroska_demux_parse_contents_seekentry (GstMatroskaDemux * demux,
5131 guint64 seek_pos = (guint64) - 1;
5132 guint32 seek_id = 0;
5135 DEBUG_ELEMENT_START (demux, ebml, "Seek");
5137 if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
5138 DEBUG_ELEMENT_STOP (demux, ebml, "Seek", ret);
5142 while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
5143 if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
5147 case GST_MATROSKA_ID_SEEKID:
5151 if ((ret = gst_ebml_read_uint (ebml, &id, &t)) != GST_FLOW_OK)
5154 GST_DEBUG_OBJECT (demux, "SeekID: %" G_GUINT64_FORMAT, t);
5159 case GST_MATROSKA_ID_SEEKPOSITION:
5163 if ((ret = gst_ebml_read_uint (ebml, &id, &t)) != GST_FLOW_OK)
5166 if (t > G_MAXINT64) {
5167 GST_WARNING_OBJECT (demux,
5168 "Too large SeekPosition %" G_GUINT64_FORMAT, t);
5172 GST_DEBUG_OBJECT (demux, "SeekPosition: %" G_GUINT64_FORMAT, t);
5178 ret = gst_matroska_read_common_parse_skip (&demux->common, ebml,
5184 if (ret != GST_FLOW_OK && ret != GST_FLOW_EOS)
5187 if (!seek_id || seek_pos == (guint64) - 1) {
5188 GST_WARNING_OBJECT (demux, "Incomplete seekhead entry (0x%x/%"
5189 G_GUINT64_FORMAT ")", seek_id, seek_pos);
5194 case GST_MATROSKA_ID_SEEKHEAD:
5197 case GST_MATROSKA_ID_CUES:
5198 case GST_MATROSKA_ID_TAGS:
5199 case GST_MATROSKA_ID_TRACKS:
5200 case GST_MATROSKA_ID_SEGMENTINFO:
5201 case GST_MATROSKA_ID_ATTACHMENTS:
5202 case GST_MATROSKA_ID_CHAPTERS:
5204 guint64 before_pos, length;
5208 length = gst_matroska_read_common_get_length (&demux->common);
5209 before_pos = demux->common.offset;
5211 if (length == (guint64) - 1) {
5212 GST_DEBUG_OBJECT (demux, "no upstream length, skipping SeakHead entry");
5216 /* check for validity */
5217 if (seek_pos + demux->common.ebml_segment_start + 12 >= length) {
5218 GST_WARNING_OBJECT (demux,
5219 "SeekHead reference lies outside file!" " (%"
5220 G_GUINT64_FORMAT "+%" G_GUINT64_FORMAT "+12 >= %"
5221 G_GUINT64_FORMAT ")", seek_pos, demux->common.ebml_segment_start,
5226 /* only pick up index location when streaming */
5227 if (demux->streaming) {
5228 if (seek_id == GST_MATROSKA_ID_CUES) {
5229 demux->index_offset = seek_pos + demux->common.ebml_segment_start;
5230 GST_DEBUG_OBJECT (demux, "Cues located at offset %" G_GUINT64_FORMAT,
5231 demux->index_offset);
5237 demux->common.offset = seek_pos + demux->common.ebml_segment_start;
5240 if ((ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
5241 GST_ELEMENT_CAST (demux), &id, &length, &needed)) !=
5245 if (id != seek_id) {
5246 GST_WARNING_OBJECT (demux,
5247 "We looked for ID=0x%x but got ID=0x%x (pos=%" G_GUINT64_FORMAT ")",
5248 seek_id, id, seek_pos + demux->common.ebml_segment_start);
5251 ret = gst_matroska_demux_parse_id (demux, id, length, needed);
5256 demux->common.offset = before_pos;
5260 case GST_MATROSKA_ID_CLUSTER:
5262 guint64 pos = seek_pos + demux->common.ebml_segment_start;
5264 GST_LOG_OBJECT (demux, "Cluster position");
5265 if (G_UNLIKELY (!demux->clusters))
5266 demux->clusters = g_array_sized_new (TRUE, TRUE, sizeof (guint64), 100);
5267 g_array_append_val (demux->clusters, pos);
5272 GST_DEBUG_OBJECT (demux, "Ignoring Seek entry for ID=0x%x", seek_id);
5275 DEBUG_ELEMENT_STOP (demux, ebml, "Seek", ret);
5280 static GstFlowReturn
5281 gst_matroska_demux_parse_contents (GstMatroskaDemux * demux, GstEbmlRead * ebml)
5283 GstFlowReturn ret = GST_FLOW_OK;
5286 DEBUG_ELEMENT_START (demux, ebml, "SeekHead");
5288 if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
5289 DEBUG_ELEMENT_STOP (demux, ebml, "SeekHead", ret);
5293 while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
5294 if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
5298 case GST_MATROSKA_ID_SEEKENTRY:
5300 ret = gst_matroska_demux_parse_contents_seekentry (demux, ebml);
5301 /* Ignore EOS and errors here */
5302 if (ret != GST_FLOW_OK) {
5303 GST_DEBUG_OBJECT (demux, "Ignoring %s", gst_flow_get_name (ret));
5310 ret = gst_matroska_read_common_parse_skip (&demux->common,
5311 ebml, "SeekHead", id);
5316 DEBUG_ELEMENT_STOP (demux, ebml, "SeekHead", ret);
5318 /* Sort clusters by position for easier searching */
5319 if (demux->clusters)
5320 g_array_sort (demux->clusters, (GCompareFunc) gst_matroska_cluster_compare);
5325 #define GST_FLOW_OVERFLOW GST_FLOW_CUSTOM_ERROR
5327 #define MAX_BLOCK_SIZE (15 * 1024 * 1024)
5329 static inline GstFlowReturn
5330 gst_matroska_demux_check_read_size (GstMatroskaDemux * demux, guint64 bytes)
5332 if (G_UNLIKELY (bytes > MAX_BLOCK_SIZE)) {
5333 /* only a few blocks are expected/allowed to be large,
5334 * and will be recursed into, whereas others will be read and must fit */
5335 if (demux->streaming) {
5336 /* fatal in streaming case, as we can't step over easily */
5337 GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
5338 ("reading large block of size %" G_GUINT64_FORMAT " not supported; "
5339 "file might be corrupt.", bytes));
5340 return GST_FLOW_ERROR;
5342 /* indicate higher level to quietly give up */
5343 GST_DEBUG_OBJECT (demux,
5344 "too large block of size %" G_GUINT64_FORMAT, bytes);
5345 return GST_FLOW_ERROR;
5352 /* returns TRUE if we truly are in error state, and should give up */
5353 static inline GstFlowReturn
5354 gst_matroska_demux_check_parse_error (GstMatroskaDemux * demux)
5356 if (!demux->streaming && demux->next_cluster_offset > 0) {
5357 /* just repositioning to where next cluster should be and try from there */
5358 GST_WARNING_OBJECT (demux, "parse error, trying next cluster expected at %"
5359 G_GUINT64_FORMAT, demux->next_cluster_offset);
5360 demux->common.offset = demux->next_cluster_offset;
5361 demux->next_cluster_offset = 0;
5367 /* sigh, one last attempt above and beyond call of duty ...;
5368 * search for cluster mark following current pos */
5369 pos = demux->common.offset;
5370 GST_WARNING_OBJECT (demux, "parse error, looking for next cluster");
5371 if ((ret = gst_matroska_demux_search_cluster (demux, &pos, TRUE)) !=
5373 /* did not work, give up */
5376 GST_DEBUG_OBJECT (demux, "... found at %" G_GUINT64_FORMAT, pos);
5377 /* try that position */
5378 demux->common.offset = pos;
5384 static inline GstFlowReturn
5385 gst_matroska_demux_flush (GstMatroskaDemux * demux, guint flush)
5387 GST_LOG_OBJECT (demux, "skipping %d bytes", flush);
5388 demux->common.offset += flush;
5389 if (demux->streaming) {
5392 /* hard to skip large blocks when streaming */
5393 ret = gst_matroska_demux_check_read_size (demux, flush);
5394 if (ret != GST_FLOW_OK)
5396 if (flush <= gst_adapter_available (demux->common.adapter))
5397 gst_adapter_flush (demux->common.adapter, flush);
5399 return GST_FLOW_EOS;
5404 /* initializes @ebml with @bytes from input stream at current offset.
5405 * Returns EOS if insufficient available,
5406 * ERROR if too much was attempted to read. */
5407 static inline GstFlowReturn
5408 gst_matroska_demux_take (GstMatroskaDemux * demux, guint64 bytes,
5411 GstBuffer *buffer = NULL;
5412 GstFlowReturn ret = GST_FLOW_OK;
5414 GST_LOG_OBJECT (demux, "taking %" G_GUINT64_FORMAT " bytes for parsing",
5416 ret = gst_matroska_demux_check_read_size (demux, bytes);
5417 if (G_UNLIKELY (ret != GST_FLOW_OK)) {
5418 if (!demux->streaming) {
5419 /* in pull mode, we can skip */
5420 if ((ret = gst_matroska_demux_flush (demux, bytes)) == GST_FLOW_OK)
5421 ret = GST_FLOW_OVERFLOW;
5423 /* otherwise fatal */
5424 ret = GST_FLOW_ERROR;
5428 if (demux->streaming) {
5429 if (gst_adapter_available (demux->common.adapter) >= bytes)
5430 buffer = gst_adapter_take_buffer (demux->common.adapter, bytes);
5434 ret = gst_matroska_read_common_peek_bytes (&demux->common,
5435 demux->common.offset, bytes, &buffer, NULL);
5436 if (G_LIKELY (buffer)) {
5437 gst_ebml_read_init (ebml, GST_ELEMENT_CAST (demux), buffer,
5438 demux->common.offset);
5439 demux->common.offset += bytes;
5446 gst_matroska_demux_check_seekability (GstMatroskaDemux * demux)
5449 gboolean seekable = FALSE;
5450 gint64 start = -1, stop = -1;
5452 query = gst_query_new_seeking (GST_FORMAT_BYTES);
5453 if (!gst_pad_peer_query (demux->common.sinkpad, query)) {
5454 GST_DEBUG_OBJECT (demux, "seeking query failed");
5458 gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
5460 /* try harder to query upstream size if we didn't get it the first time */
5461 if (seekable && stop == -1) {
5462 GST_DEBUG_OBJECT (demux, "doing duration query to fix up unset stop");
5463 gst_pad_peer_query_duration (demux->common.sinkpad, GST_FORMAT_BYTES,
5467 /* if upstream doesn't know the size, it's likely that it's not seekable in
5468 * practice even if it technically may be seekable */
5469 if (seekable && (start != 0 || stop <= start)) {
5470 GST_DEBUG_OBJECT (demux, "seekable but unknown start/stop -> disable");
5475 GST_INFO_OBJECT (demux, "seekable: %d (%" G_GUINT64_FORMAT " - %"
5476 G_GUINT64_FORMAT ")", seekable, start, stop);
5477 demux->seekable = seekable;
5479 gst_query_unref (query);
5482 static GstFlowReturn
5483 gst_matroska_demux_find_tracks (GstMatroskaDemux * demux)
5489 GstFlowReturn ret = GST_FLOW_OK;
5491 GST_WARNING_OBJECT (demux,
5492 "Found Cluster element before Tracks, searching Tracks");
5495 before_pos = demux->common.offset;
5497 /* Search Tracks element */
5499 ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
5500 GST_ELEMENT_CAST (demux), &id, &length, &needed);
5501 if (ret != GST_FLOW_OK)
5504 if (id != GST_MATROSKA_ID_TRACKS) {
5505 /* we may be skipping large cluster here, so forego size check etc */
5506 /* ... but we can't skip undefined size; force error */
5507 if (length == G_MAXUINT64) {
5508 ret = gst_matroska_demux_check_read_size (demux, length);
5511 demux->common.offset += needed;
5512 demux->common.offset += length;
5517 /* will lead to track parsing ... */
5518 ret = gst_matroska_demux_parse_id (demux, id, length, needed);
5523 demux->common.offset = before_pos;
5528 #define GST_READ_CHECK(stmt) \
5530 if (G_UNLIKELY ((ret = (stmt)) != GST_FLOW_OK)) { \
5531 if (ret == GST_FLOW_OVERFLOW) { \
5532 ret = GST_FLOW_OK; \
5538 static GstFlowReturn
5539 gst_matroska_demux_parse_id (GstMatroskaDemux * demux, guint32 id,
5540 guint64 length, guint needed)
5542 GstEbmlRead ebml = { 0, };
5543 GstFlowReturn ret = GST_FLOW_OK;
5546 GST_LOG_OBJECT (demux, "Parsing Element id 0x%x, "
5547 "size %" G_GUINT64_FORMAT ", prefix %d", id, length, needed);
5549 /* if we plan to read and parse this element, we need prefix (id + length)
5550 * and the contents */
5551 /* mind about overflow wrap-around when dealing with undefined size */
5553 if (G_LIKELY (length != G_MAXUINT64))
5556 switch (demux->common.state) {
5557 case GST_MATROSKA_READ_STATE_START:
5559 case GST_EBML_ID_HEADER:
5560 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5561 ret = gst_matroska_read_common_parse_header (&demux->common, &ebml);
5562 if (ret != GST_FLOW_OK)
5564 demux->common.state = GST_MATROSKA_READ_STATE_SEGMENT;
5565 gst_matroska_demux_check_seekability (demux);
5568 goto invalid_header;
5572 case GST_MATROSKA_READ_STATE_SEGMENT:
5574 case GST_MATROSKA_ID_SEGMENT:
5575 /* eat segment prefix */
5576 GST_READ_CHECK (gst_matroska_demux_flush (demux, needed));
5577 GST_DEBUG_OBJECT (demux,
5578 "Found Segment start at offset %" G_GUINT64_FORMAT " with size %"
5579 G_GUINT64_FORMAT, demux->common.offset, length);
5580 /* seeks are from the beginning of the segment,
5581 * after the segment ID/length */
5582 demux->common.ebml_segment_start = demux->common.offset;
5584 length = G_MAXUINT64;
5585 demux->common.ebml_segment_length = length;
5586 demux->common.state = GST_MATROSKA_READ_STATE_HEADER;
5589 GST_WARNING_OBJECT (demux,
5590 "Expected a Segment ID (0x%x), but received 0x%x!",
5591 GST_MATROSKA_ID_SEGMENT, id);
5592 GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
5596 case GST_MATROSKA_READ_STATE_SCANNING:
5597 if (id != GST_MATROSKA_ID_CLUSTER &&
5598 id != GST_MATROSKA_ID_PREVSIZE &&
5599 id != GST_MATROSKA_ID_CLUSTERTIMECODE) {
5600 if (demux->common.start_resync_offset != -1) {
5601 /* we need to skip byte per byte if we are scanning for a new cluster
5602 * after invalid data is found
5608 if (demux->common.start_resync_offset != -1) {
5609 GST_LOG_OBJECT (demux, "Resync done, new cluster found!");
5610 demux->common.start_resync_offset = -1;
5611 demux->common.state = demux->common.state_to_restore;
5615 case GST_MATROSKA_READ_STATE_HEADER:
5616 case GST_MATROSKA_READ_STATE_DATA:
5617 case GST_MATROSKA_READ_STATE_SEEK:
5619 case GST_EBML_ID_HEADER:
5620 GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
5621 demux->common.state = GST_MATROSKA_READ_STATE_SEGMENT;
5622 gst_matroska_demux_check_seekability (demux);
5624 case GST_MATROSKA_ID_SEGMENTINFO:
5625 if (!demux->common.segmentinfo_parsed) {
5626 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5627 ret = gst_matroska_read_common_parse_info (&demux->common,
5628 GST_ELEMENT_CAST (demux), &ebml);
5629 if (ret == GST_FLOW_OK)
5630 gst_matroska_demux_send_tags (demux);
5632 GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
5635 case GST_MATROSKA_ID_TRACKS:
5636 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5637 if (demux->tracks_ebml_offset == G_MAXUINT64) {
5638 ret = gst_matroska_demux_parse_tracks (demux, &ebml);
5639 } else if (demux->tracks_ebml_offset != ebml.offset) {
5640 /* This is a new Tracks entry, as can happen in MSE
5642 ret = gst_matroska_demux_update_tracks (demux, &ebml);
5645 case GST_MATROSKA_ID_CLUSTER:
5646 if (G_UNLIKELY (demux->tracks_ebml_offset == G_MAXUINT64)) {
5647 if (demux->streaming) {
5648 GST_DEBUG_OBJECT (demux, "Cluster before Track");
5649 goto not_streamable;
5651 ret = gst_matroska_demux_find_tracks (demux);
5652 if (demux->tracks_ebml_offset == G_MAXUINT64)
5656 if (demux->common.state == GST_MATROSKA_READ_STATE_HEADER) {
5657 demux->common.state = GST_MATROSKA_READ_STATE_DATA;
5658 demux->first_cluster_offset = demux->common.offset;
5660 if (!demux->streaming &&
5661 !GST_CLOCK_TIME_IS_VALID (demux->common.segment.duration)) {
5662 GstMatroskaIndex *last = NULL;
5664 GST_DEBUG_OBJECT (demux,
5665 "estimating duration using last cluster");
5666 if ((last = gst_matroska_demux_search_pos (demux,
5667 GST_CLOCK_TIME_NONE)) != NULL) {
5668 demux->last_cluster_offset =
5669 last->pos + demux->common.ebml_segment_start;
5670 demux->stream_last_time = last->time;
5671 demux->common.segment.duration =
5672 demux->stream_last_time - demux->stream_start_time;
5673 /* above estimate should not be taken all too strongly */
5674 demux->invalid_duration = TRUE;
5675 GST_DEBUG_OBJECT (demux,
5676 "estimated duration as %" GST_TIME_FORMAT,
5677 GST_TIME_ARGS (demux->common.segment.duration));
5683 /* Peek at second cluster in order to figure out if we have cluster
5684 * prev_size or not (which is never set on the first cluster for
5685 * obvious reasons). This is useful in case someone initiates a
5686 * seek or direction change before we reach the second cluster. */
5687 if (!demux->streaming) {
5688 ClusterInfo cluster = { 0, };
5690 if (gst_matroska_demux_peek_cluster_info (demux, &cluster,
5691 demux->first_cluster_offset) && cluster.size > 0) {
5692 gst_matroska_demux_peek_cluster_info (demux, &cluster,
5693 demux->first_cluster_offset + cluster.size);
5695 demux->common.offset = demux->first_cluster_offset;
5698 if (demux->deferred_seek_event) {
5699 GstEvent *seek_event;
5701 seek_event = demux->deferred_seek_event;
5702 seek_pad = demux->deferred_seek_pad;
5703 demux->deferred_seek_event = NULL;
5704 demux->deferred_seek_pad = NULL;
5705 GST_DEBUG_OBJECT (demux,
5706 "Handling deferred seek event: %" GST_PTR_FORMAT, seek_event);
5707 gst_matroska_demux_handle_seek_event (demux, seek_pad,
5709 gst_event_unref (seek_event);
5712 /* send initial segment - we wait till we know the first
5713 incoming timestamp, so we can properly set the start of
5715 demux->need_segment = TRUE;
5717 demux->cluster_time = GST_CLOCK_TIME_NONE;
5718 demux->cluster_offset = demux->common.offset;
5719 demux->cluster_prevsize = 0;
5720 if (G_UNLIKELY (!demux->seek_first && demux->seek_block)) {
5721 GST_DEBUG_OBJECT (demux, "seek target block %" G_GUINT64_FORMAT
5722 " not found in Cluster, trying next Cluster's first block instead",
5724 demux->seek_block = 0;
5726 demux->seek_first = FALSE;
5727 /* record next cluster for recovery */
5728 if (read != G_MAXUINT64)
5729 demux->next_cluster_offset = demux->cluster_offset + read;
5730 /* eat cluster prefix */
5731 gst_matroska_demux_flush (demux, needed);
5733 case GST_MATROSKA_ID_CLUSTERTIMECODE:
5737 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5738 if ((ret = gst_ebml_read_uint (&ebml, &id, &num)) != GST_FLOW_OK)
5740 GST_DEBUG_OBJECT (demux, "ClusterTimeCode: %" G_GUINT64_FORMAT, num);
5741 demux->cluster_time = num;
5742 /* track last cluster */
5743 if (demux->cluster_offset > demux->last_cluster_offset) {
5744 demux->last_cluster_offset = demux->cluster_offset;
5745 demux->stream_last_time =
5746 demux->cluster_time * demux->common.time_scale;
5749 if (demux->common.element_index) {
5750 if (demux->common.element_index_writer_id == -1)
5751 gst_index_get_writer_id (demux->common.element_index,
5752 GST_OBJECT (demux), &demux->common.element_index_writer_id);
5753 GST_LOG_OBJECT (demux, "adding association %" GST_TIME_FORMAT "-> %"
5754 G_GUINT64_FORMAT " for writer id %d",
5755 GST_TIME_ARGS (demux->cluster_time), demux->cluster_offset,
5756 demux->common.element_index_writer_id);
5757 gst_index_add_association (demux->common.element_index,
5758 demux->common.element_index_writer_id,
5759 GST_ASSOCIATION_FLAG_KEY_UNIT,
5760 GST_FORMAT_TIME, demux->cluster_time,
5761 GST_FORMAT_BYTES, demux->cluster_offset, NULL);
5766 case GST_MATROSKA_ID_BLOCKGROUP:
5767 if (!gst_matroska_demux_seek_block (demux))
5769 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5770 DEBUG_ELEMENT_START (demux, &ebml, "BlockGroup");
5771 if ((ret = gst_ebml_read_master (&ebml, &id)) == GST_FLOW_OK) {
5772 ret = gst_matroska_demux_parse_blockgroup_or_simpleblock (demux,
5773 &ebml, demux->cluster_time, demux->cluster_offset, FALSE);
5775 DEBUG_ELEMENT_STOP (demux, &ebml, "BlockGroup", ret);
5777 case GST_MATROSKA_ID_SIMPLEBLOCK:
5778 if (!gst_matroska_demux_seek_block (demux))
5780 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5781 DEBUG_ELEMENT_START (demux, &ebml, "SimpleBlock");
5782 ret = gst_matroska_demux_parse_blockgroup_or_simpleblock (demux,
5783 &ebml, demux->cluster_time, demux->cluster_offset, TRUE);
5784 DEBUG_ELEMENT_STOP (demux, &ebml, "SimpleBlock", ret);
5786 case GST_MATROSKA_ID_ATTACHMENTS:
5787 if (!demux->common.attachments_parsed) {
5788 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5789 ret = gst_matroska_read_common_parse_attachments (&demux->common,
5790 GST_ELEMENT_CAST (demux), &ebml);
5791 if (ret == GST_FLOW_OK)
5792 gst_matroska_demux_send_tags (demux);
5794 GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
5797 case GST_MATROSKA_ID_TAGS:
5798 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5799 ret = gst_matroska_read_common_parse_metadata (&demux->common,
5800 GST_ELEMENT_CAST (demux), &ebml);
5801 if (ret == GST_FLOW_OK)
5802 gst_matroska_demux_send_tags (demux);
5804 case GST_MATROSKA_ID_CHAPTERS:
5805 if (!demux->common.chapters_parsed) {
5806 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5808 gst_matroska_read_common_parse_chapters (&demux->common, &ebml);
5810 if (demux->common.toc) {
5811 gst_matroska_demux_send_event (demux,
5812 gst_event_new_toc (demux->common.toc, FALSE));
5815 GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
5817 case GST_MATROSKA_ID_SEEKHEAD:
5818 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5819 ret = gst_matroska_demux_parse_contents (demux, &ebml);
5821 case GST_MATROSKA_ID_CUES:
5822 if (demux->common.index_parsed) {
5823 GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
5826 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5827 ret = gst_matroska_read_common_parse_index (&demux->common, &ebml);
5828 /* only push based; delayed index building */
5829 if (ret == GST_FLOW_OK
5830 && demux->common.state == GST_MATROSKA_READ_STATE_SEEK) {
5833 GST_OBJECT_LOCK (demux);
5834 event = demux->seek_event;
5835 demux->seek_event = NULL;
5836 GST_OBJECT_UNLOCK (demux);
5839 /* unlikely to fail, since we managed to seek to this point */
5840 if (!gst_matroska_demux_handle_seek_event (demux, NULL, event)) {
5841 gst_event_unref (event);
5844 gst_event_unref (event);
5845 /* resume data handling, main thread clear to seek again */
5846 GST_OBJECT_LOCK (demux);
5847 demux->common.state = GST_MATROSKA_READ_STATE_DATA;
5848 GST_OBJECT_UNLOCK (demux);
5851 case GST_MATROSKA_ID_PREVSIZE:{
5854 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
5855 if ((ret = gst_ebml_read_uint (&ebml, &id, &num)) != GST_FLOW_OK)
5857 GST_LOG_OBJECT (demux, "ClusterPrevSize: %" G_GUINT64_FORMAT, num);
5858 demux->cluster_prevsize = num;
5859 demux->seen_cluster_prevsize = TRUE;
5862 case GST_MATROSKA_ID_POSITION:
5863 case GST_MATROSKA_ID_ENCRYPTEDBLOCK:
5864 /* The WebM doesn't support the EncryptedBlock element.
5865 * The Matroska spec doesn't give us more detail, how to parse this element,
5866 * for example the field TransformID isn't specified yet.*/
5867 case GST_MATROSKA_ID_SILENTTRACKS:
5868 GST_DEBUG_OBJECT (demux,
5869 "Skipping Cluster subelement 0x%x - ignoring", id);
5873 GST_DEBUG_OBJECT (demux, "skipping Element 0x%x", id);
5874 GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
5880 if (ret == GST_FLOW_PARSE)
5884 gst_ebml_read_clear (&ebml);
5890 /* simply exit, maybe not enough data yet */
5891 /* no ebml to clear if read error */
5896 GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
5897 ("Failed to parse Element 0x%x", id));
5898 ret = GST_FLOW_ERROR;
5903 GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
5904 ("File layout does not permit streaming"));
5905 ret = GST_FLOW_ERROR;
5910 GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
5911 ("No Tracks element found"));
5912 ret = GST_FLOW_ERROR;
5917 GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL), ("Invalid header"));
5918 ret = GST_FLOW_ERROR;
5923 GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL), ("Failed to seek"));
5924 ret = GST_FLOW_ERROR;
5930 gst_matroska_demux_loop (GstPad * pad)
5932 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (GST_PAD_PARENT (pad));
5938 /* If we have to close a segment, send a new segment to do this now */
5939 if (G_LIKELY (demux->common.state == GST_MATROSKA_READ_STATE_DATA)) {
5940 if (G_UNLIKELY (demux->new_segment)) {
5941 gst_matroska_demux_send_event (demux, demux->new_segment);
5942 demux->new_segment = NULL;
5946 ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
5947 GST_ELEMENT_CAST (demux), &id, &length, &needed);
5948 if (ret == GST_FLOW_EOS) {
5950 } else if (ret == GST_FLOW_FLUSHING) {
5952 } else if (ret != GST_FLOW_OK) {
5953 ret = gst_matroska_demux_check_parse_error (demux);
5955 /* Only handle EOS as no error if we're outside the segment already */
5956 if (ret == GST_FLOW_EOS && (demux->common.ebml_segment_length != G_MAXUINT64
5957 && demux->common.offset >=
5958 demux->common.ebml_segment_start +
5959 demux->common.ebml_segment_length))
5961 else if (ret != GST_FLOW_OK)
5967 GST_LOG_OBJECT (demux, "Offset %" G_GUINT64_FORMAT ", Element id 0x%x, "
5968 "size %" G_GUINT64_FORMAT ", needed %d", demux->common.offset, id,
5971 ret = gst_matroska_demux_parse_id (demux, id, length, needed);
5972 if (ret == GST_FLOW_EOS)
5974 if (ret != GST_FLOW_OK)
5977 /* check if we're at the end of a configured segment */
5978 if (G_LIKELY (demux->common.src->len)) {
5981 g_assert (demux->common.num_streams == demux->common.src->len);
5982 for (i = 0; i < demux->common.src->len; i++) {
5983 GstMatroskaTrackContext *context = g_ptr_array_index (demux->common.src,
5985 GST_DEBUG_OBJECT (context->pad, "pos %" GST_TIME_FORMAT,
5986 GST_TIME_ARGS (context->pos));
5987 if (context->eos == FALSE)
5991 GST_INFO_OBJECT (demux, "All streams are EOS");
5997 if (G_UNLIKELY (demux->cached_length == G_MAXUINT64 ||
5998 demux->common.offset >= demux->cached_length)) {
5999 demux->cached_length = gst_matroska_read_common_get_length (&demux->common);
6000 if (demux->common.offset == demux->cached_length) {
6001 GST_LOG_OBJECT (demux, "Reached end of stream");
6012 if (demux->common.segment.rate < 0.0) {
6013 ret = gst_matroska_demux_seek_to_previous_keyframe (demux);
6014 if (ret == GST_FLOW_OK)
6021 const gchar *reason = gst_flow_get_name (ret);
6022 gboolean push_eos = FALSE;
6024 GST_LOG_OBJECT (demux, "pausing task, reason %s", reason);
6025 gst_pad_pause_task (demux->common.sinkpad);
6027 if (ret == GST_FLOW_EOS) {
6028 /* perform EOS logic */
6030 /* If we were in the headers, make sure we send no-more-pads.
6031 This will ensure decodebin does not get stuck thinking
6032 the chain is not complete yet, and waiting indefinitely. */
6033 if (G_UNLIKELY (demux->common.state == GST_MATROSKA_READ_STATE_HEADER)) {
6034 if (demux->common.src->len == 0) {
6035 GST_ELEMENT_ERROR (demux, STREAM, FAILED, (NULL),
6036 ("No pads created"));
6038 GST_ELEMENT_WARNING (demux, STREAM, DEMUX, (NULL),
6039 ("Failed to finish reading headers"));
6041 gst_element_no_more_pads (GST_ELEMENT (demux));
6044 if (demux->common.segment.flags & GST_SEEK_FLAG_SEGMENT) {
6049 /* for segment playback we need to post when (in stream time)
6050 * we stopped, this is either stop (when set) or the duration. */
6051 if ((stop = demux->common.segment.stop) == -1)
6052 stop = demux->last_stop_end;
6054 GST_LOG_OBJECT (demux, "Sending segment done, at end of segment");
6055 msg = gst_message_new_segment_done (GST_OBJECT (demux), GST_FORMAT_TIME,
6057 if (demux->segment_seqnum)
6058 gst_message_set_seqnum (msg, demux->segment_seqnum);
6059 gst_element_post_message (GST_ELEMENT (demux), msg);
6061 event = gst_event_new_segment_done (GST_FORMAT_TIME, stop);
6062 if (demux->segment_seqnum)
6063 gst_event_set_seqnum (event, demux->segment_seqnum);
6064 gst_matroska_demux_send_event (demux, event);
6068 } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
6069 /* for fatal errors we post an error message */
6070 GST_ELEMENT_FLOW_ERROR (demux, ret);
6076 /* send EOS, and prevent hanging if no streams yet */
6077 GST_LOG_OBJECT (demux, "Sending EOS, at end of stream");
6078 event = gst_event_new_eos ();
6079 if (demux->segment_seqnum)
6080 gst_event_set_seqnum (event, demux->segment_seqnum);
6081 if (!gst_matroska_demux_send_event (demux, event) &&
6082 (ret == GST_FLOW_EOS)) {
6083 GST_ELEMENT_ERROR (demux, STREAM, DEMUX,
6084 (NULL), ("got eos but no streams (yet)"));
6092 * Create and push a flushing seek event upstream
6095 perform_seek_to_offset (GstMatroskaDemux * demux, gdouble rate, guint64 offset,
6096 guint32 seqnum, GstSeekFlags flags)
6101 GST_DEBUG_OBJECT (demux, "Seeking to %" G_GUINT64_FORMAT, offset);
6104 gst_event_new_seek (rate, GST_FORMAT_BYTES,
6105 flags | GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE,
6106 GST_SEEK_TYPE_SET, offset, GST_SEEK_TYPE_NONE, -1);
6107 gst_event_set_seqnum (event, seqnum);
6109 res = gst_pad_push_event (demux->common.sinkpad, event);
6111 /* segment event will update offset */
6115 static GstFlowReturn
6116 gst_matroska_demux_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
6118 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (parent);
6120 GstFlowReturn ret = GST_FLOW_OK;
6125 if (G_UNLIKELY (GST_BUFFER_IS_DISCONT (buffer))) {
6126 GST_DEBUG_OBJECT (demux, "got DISCONT");
6127 gst_adapter_clear (demux->common.adapter);
6128 GST_OBJECT_LOCK (demux);
6129 gst_matroska_read_common_reset_streams (&demux->common,
6130 GST_CLOCK_TIME_NONE, FALSE);
6131 GST_OBJECT_UNLOCK (demux);
6134 gst_adapter_push (demux->common.adapter, buffer);
6138 available = gst_adapter_available (demux->common.adapter);
6140 ret = gst_matroska_read_common_peek_id_length_push (&demux->common,
6141 GST_ELEMENT_CAST (demux), &id, &length, &needed);
6142 if (G_UNLIKELY (ret != GST_FLOW_OK && ret != GST_FLOW_EOS)) {
6143 if (demux->common.ebml_segment_length != G_MAXUINT64
6144 && demux->common.offset >=
6145 demux->common.ebml_segment_start + demux->common.ebml_segment_length) {
6148 gint64 bytes_scanned;
6149 if (demux->common.start_resync_offset == -1) {
6150 demux->common.start_resync_offset = demux->common.offset;
6151 demux->common.state_to_restore = demux->common.state;
6153 bytes_scanned = demux->common.offset - demux->common.start_resync_offset;
6154 if (bytes_scanned <= INVALID_DATA_THRESHOLD) {
6155 GST_WARNING_OBJECT (demux,
6156 "parse error, looking for next cluster, actual offset %"
6157 G_GUINT64_FORMAT ", start resync offset %" G_GUINT64_FORMAT,
6158 demux->common.offset, demux->common.start_resync_offset);
6159 demux->common.state = GST_MATROSKA_READ_STATE_SCANNING;
6162 GST_WARNING_OBJECT (demux,
6163 "unrecoverable parse error, next cluster not found and threshold "
6164 "exceeded, bytes scanned %" G_GINT64_FORMAT, bytes_scanned);
6170 GST_LOG_OBJECT (demux, "Offset %" G_GUINT64_FORMAT ", Element id 0x%x, "
6171 "size %" G_GUINT64_FORMAT ", needed %d, available %d",
6172 demux->common.offset, id, length, needed, available);
6174 if (needed > available)
6177 ret = gst_matroska_demux_parse_id (demux, id, length, needed);
6178 if (ret == GST_FLOW_EOS) {
6179 /* need more data */
6181 } else if (ret != GST_FLOW_OK) {
6188 gst_matroska_demux_handle_sink_event (GstPad * pad, GstObject * parent,
6191 gboolean res = TRUE;
6192 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (parent);
6194 GST_DEBUG_OBJECT (demux,
6195 "have event type %s: %p on sink pad", GST_EVENT_TYPE_NAME (event), event);
6197 switch (GST_EVENT_TYPE (event)) {
6198 case GST_EVENT_SEGMENT:
6200 const GstSegment *segment;
6202 /* some debug output */
6203 gst_event_parse_segment (event, &segment);
6204 /* FIXME: do we need to update segment base here (like accum in 0.10)? */
6205 GST_DEBUG_OBJECT (demux,
6206 "received format %d segment %" GST_SEGMENT_FORMAT, segment->format,
6209 if (demux->common.state < GST_MATROSKA_READ_STATE_DATA) {
6210 GST_DEBUG_OBJECT (demux, "still starting");
6214 /* we only expect a BYTE segment, e.g. following a seek */
6215 if (segment->format != GST_FORMAT_BYTES) {
6216 GST_DEBUG_OBJECT (demux, "unsupported segment format, ignoring");
6220 GST_DEBUG_OBJECT (demux, "clearing segment state");
6221 GST_OBJECT_LOCK (demux);
6222 /* clear current segment leftover */
6223 gst_adapter_clear (demux->common.adapter);
6224 /* and some streaming setup */
6225 demux->common.offset = segment->start;
6226 /* accumulate base based on current position */
6227 if (GST_CLOCK_TIME_IS_VALID (demux->common.segment.position))
6228 demux->common.segment.base +=
6229 (MAX (demux->common.segment.position, demux->stream_start_time)
6230 - demux->stream_start_time) / fabs (demux->common.segment.rate);
6231 /* do not know where we are;
6232 * need to come across a cluster and generate segment */
6233 demux->common.segment.position = GST_CLOCK_TIME_NONE;
6234 demux->cluster_time = GST_CLOCK_TIME_NONE;
6235 demux->cluster_offset = 0;
6236 demux->cluster_prevsize = 0;
6237 demux->need_segment = TRUE;
6238 demux->segment_seqnum = gst_event_get_seqnum (event);
6239 /* but keep some of the upstream segment */
6240 demux->common.segment.rate = segment->rate;
6241 demux->common.segment.flags = segment->flags;
6242 /* also check if need to keep some of the requested seek position */
6243 if (demux->seek_offset == segment->start) {
6244 GST_DEBUG_OBJECT (demux, "position matches requested seek");
6245 demux->common.segment.position = demux->requested_seek_time;
6247 GST_DEBUG_OBJECT (demux, "unexpected segment position");
6249 demux->requested_seek_time = GST_CLOCK_TIME_NONE;
6250 demux->seek_offset = -1;
6251 GST_OBJECT_UNLOCK (demux);
6253 /* chain will send initial segment after pads have been added,
6254 * or otherwise come up with one */
6255 GST_DEBUG_OBJECT (demux, "eating event");
6256 gst_event_unref (event);
6262 if (demux->common.state != GST_MATROSKA_READ_STATE_DATA
6263 && demux->common.state != GST_MATROSKA_READ_STATE_SCANNING) {
6264 gst_event_unref (event);
6265 GST_ELEMENT_ERROR (demux, STREAM, DEMUX,
6266 (NULL), ("got eos and didn't receive a complete header object"));
6267 } else if (demux->common.num_streams == 0) {
6268 GST_ELEMENT_ERROR (demux, STREAM, DEMUX,
6269 (NULL), ("got eos but no streams (yet)"));
6271 gst_matroska_demux_send_event (demux, event);
6275 case GST_EVENT_FLUSH_STOP:
6279 gst_adapter_clear (demux->common.adapter);
6280 GST_OBJECT_LOCK (demux);
6281 gst_matroska_read_common_reset_streams (&demux->common,
6282 GST_CLOCK_TIME_NONE, TRUE);
6283 gst_flow_combiner_reset (demux->flowcombiner);
6284 dur = demux->common.segment.duration;
6285 gst_segment_init (&demux->common.segment, GST_FORMAT_TIME);
6286 demux->common.segment.duration = dur;
6287 demux->cluster_time = GST_CLOCK_TIME_NONE;
6288 demux->cluster_offset = 0;
6289 demux->cluster_prevsize = 0;
6290 GST_OBJECT_UNLOCK (demux);
6294 res = gst_pad_event_default (pad, parent, event);
6302 gst_matroska_demux_sink_activate (GstPad * sinkpad, GstObject * parent)
6304 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (parent);
6306 gboolean pull_mode = FALSE;
6308 query = gst_query_new_scheduling ();
6310 if (gst_pad_peer_query (sinkpad, query))
6311 pull_mode = gst_query_has_scheduling_mode_with_flags (query,
6312 GST_PAD_MODE_PULL, GST_SCHEDULING_FLAG_SEEKABLE);
6314 gst_query_unref (query);
6317 GST_DEBUG ("going to pull mode");
6318 demux->streaming = FALSE;
6319 return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PULL, TRUE);
6321 GST_DEBUG ("going to push (streaming) mode");
6322 demux->streaming = TRUE;
6323 return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
6328 gst_matroska_demux_sink_activate_mode (GstPad * sinkpad, GstObject * parent,
6329 GstPadMode mode, gboolean active)
6332 case GST_PAD_MODE_PULL:
6334 /* if we have a scheduler we can start the task */
6335 gst_pad_start_task (sinkpad, (GstTaskFunction) gst_matroska_demux_loop,
6338 gst_pad_stop_task (sinkpad);
6341 case GST_PAD_MODE_PUSH:
6349 gst_matroska_demux_video_caps (GstMatroskaTrackVideoContext *
6350 videocontext, const gchar * codec_id, guint8 * data, guint size,
6351 gchar ** codec_name, guint32 * riff_fourcc)
6353 GstMatroskaTrackContext *context = (GstMatroskaTrackContext *) videocontext;
6354 GstCaps *caps = NULL;
6356 g_assert (videocontext != NULL);
6357 g_assert (codec_name != NULL);
6362 /* TODO: check if we have all codec types from matroska-ids.h
6363 * check if we have to do more special things with codec_private
6366 * GST_MATROSKA_CODEC_ID_VIDEO_QUICKTIME
6367 * GST_MATROSKA_CODEC_ID_VIDEO_SNOW
6370 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC)) {
6371 gst_riff_strf_vids *vids = NULL;
6374 GstBuffer *buf = NULL;
6376 vids = (gst_riff_strf_vids *) data;
6378 /* assure size is big enough */
6380 GST_WARNING ("Too small BITMAPINFOHEADER (%d bytes)", size);
6383 if (size < sizeof (gst_riff_strf_vids)) {
6384 vids = g_new (gst_riff_strf_vids, 1);
6385 memcpy (vids, data, size);
6388 context->dts_only = TRUE; /* VFW files only store DTS */
6390 /* little-endian -> byte-order */
6391 vids->size = GUINT32_FROM_LE (vids->size);
6392 vids->width = GUINT32_FROM_LE (vids->width);
6393 vids->height = GUINT32_FROM_LE (vids->height);
6394 vids->planes = GUINT16_FROM_LE (vids->planes);
6395 vids->bit_cnt = GUINT16_FROM_LE (vids->bit_cnt);
6396 vids->compression = GUINT32_FROM_LE (vids->compression);
6397 vids->image_size = GUINT32_FROM_LE (vids->image_size);
6398 vids->xpels_meter = GUINT32_FROM_LE (vids->xpels_meter);
6399 vids->ypels_meter = GUINT32_FROM_LE (vids->ypels_meter);
6400 vids->num_colors = GUINT32_FROM_LE (vids->num_colors);
6401 vids->imp_colors = GUINT32_FROM_LE (vids->imp_colors);
6403 if (size > sizeof (gst_riff_strf_vids)) { /* some extra_data */
6404 gsize offset = sizeof (gst_riff_strf_vids);
6406 buf = gst_buffer_new_memdup ((guint8 *) vids + offset, size - offset);
6410 *riff_fourcc = vids->compression;
6412 caps = gst_riff_create_video_caps (vids->compression, NULL, vids,
6413 buf, NULL, codec_name);
6416 GST_WARNING ("Unhandled RIFF fourcc %" GST_FOURCC_FORMAT,
6417 GST_FOURCC_ARGS (vids->compression));
6419 static GstStaticCaps intra_caps = GST_STATIC_CAPS ("image/jpeg; "
6420 "video/x-raw; image/png; video/x-dv; video/x-huffyuv; video/x-ffv; "
6421 "video/x-compressed-yuv");
6422 context->intra_only =
6423 gst_caps_can_intersect (gst_static_caps_get (&intra_caps), caps);
6427 gst_buffer_unref (buf);
6429 if (vids != (gst_riff_strf_vids *) data)
6432 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_UNCOMPRESSED)) {
6434 GstVideoFormat format;
6436 gst_video_info_init (&info);
6437 switch (videocontext->fourcc) {
6438 case GST_MAKE_FOURCC ('I', '4', '2', '0'):
6439 format = GST_VIDEO_FORMAT_I420;
6441 case GST_MAKE_FOURCC ('Y', 'U', 'Y', '2'):
6442 format = GST_VIDEO_FORMAT_YUY2;
6444 case GST_MAKE_FOURCC ('Y', 'V', '1', '2'):
6445 format = GST_VIDEO_FORMAT_YV12;
6447 case GST_MAKE_FOURCC ('U', 'Y', 'V', 'Y'):
6448 format = GST_VIDEO_FORMAT_UYVY;
6450 case GST_MAKE_FOURCC ('A', 'Y', 'U', 'V'):
6451 format = GST_VIDEO_FORMAT_AYUV;
6453 case GST_MAKE_FOURCC ('Y', '8', '0', '0'):
6454 case GST_MAKE_FOURCC ('Y', '8', ' ', ' '):
6455 format = GST_VIDEO_FORMAT_GRAY8;
6457 case GST_MAKE_FOURCC ('R', 'G', 'B', 24):
6458 format = GST_VIDEO_FORMAT_RGB;
6460 case GST_MAKE_FOURCC ('B', 'G', 'R', 24):
6461 format = GST_VIDEO_FORMAT_BGR;
6464 GST_DEBUG ("Unknown fourcc %" GST_FOURCC_FORMAT,
6465 GST_FOURCC_ARGS (videocontext->fourcc));
6469 context->intra_only = TRUE;
6471 gst_video_info_set_format (&info, format, videocontext->pixel_width,
6472 videocontext->pixel_height);
6473 caps = gst_video_info_to_caps (&info);
6474 *codec_name = gst_pb_utils_get_codec_description (caps);
6475 context->alignment = 32;
6476 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_SP)) {
6477 caps = gst_caps_new_simple ("video/x-divx",
6478 "divxversion", G_TYPE_INT, 4, NULL);
6479 *codec_name = g_strdup ("MPEG-4 simple profile");
6480 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_ASP) ||
6481 !strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_AP)) {
6482 caps = gst_caps_new_simple ("video/mpeg",
6483 "mpegversion", G_TYPE_INT, 4,
6484 "systemstream", G_TYPE_BOOLEAN, FALSE, NULL);
6488 priv = gst_buffer_new_memdup (data, size);
6489 gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
6490 gst_buffer_unref (priv);
6492 gst_codec_utils_mpeg4video_caps_set_level_and_profile (caps, data, size);
6494 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_ASP))
6495 *codec_name = g_strdup ("MPEG-4 advanced simple profile");
6497 *codec_name = g_strdup ("MPEG-4 advanced profile");
6498 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MSMPEG4V3)) {
6500 caps = gst_caps_new_full (gst_structure_new ("video/x-divx",
6501 "divxversion", G_TYPE_INT, 3, NULL),
6502 gst_structure_new ("video/x-msmpeg",
6503 "msmpegversion", G_TYPE_INT, 43, NULL), NULL);
6505 caps = gst_caps_new_simple ("video/x-msmpeg",
6506 "msmpegversion", G_TYPE_INT, 43, NULL);
6507 *codec_name = g_strdup ("Microsoft MPEG-4 v.3");
6508 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG1) ||
6509 !strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG2)) {
6512 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG1))
6517 caps = gst_caps_new_simple ("video/mpeg",
6518 "systemstream", G_TYPE_BOOLEAN, FALSE,
6519 "mpegversion", G_TYPE_INT, mpegversion, NULL);
6520 *codec_name = g_strdup_printf ("MPEG-%d video", mpegversion);
6521 context->postprocess_frame = gst_matroska_demux_add_mpeg_seq_header;
6522 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MJPEG)) {
6523 caps = gst_caps_new_empty_simple ("image/jpeg");
6524 *codec_name = g_strdup ("Motion-JPEG");
6525 context->intra_only = TRUE;
6526 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_AVC)) {
6527 caps = gst_caps_new_empty_simple ("video/x-h264");
6531 /* First byte is the version, second is the profile indication, and third
6532 * is the 5 contraint_set_flags and 3 reserved bits. Fourth byte is the
6533 * level indication. */
6534 gst_codec_utils_h264_caps_set_level_and_profile (caps, data + 1,
6537 priv = gst_buffer_new_memdup (data, size);
6538 gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
6539 gst_buffer_unref (priv);
6541 gst_caps_set_simple (caps, "stream-format", G_TYPE_STRING, "avc",
6542 "alignment", G_TYPE_STRING, "au", NULL);
6544 GST_WARNING ("No codec data found, assuming output is byte-stream");
6545 gst_caps_set_simple (caps, "stream-format", G_TYPE_STRING, "byte-stream",
6548 *codec_name = g_strdup ("H264");
6549 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEGH_HEVC)) {
6550 caps = gst_caps_new_empty_simple ("video/x-h265");
6554 gst_codec_utils_h265_caps_set_level_tier_and_profile (caps, data + 1,
6557 priv = gst_buffer_new_memdup (data, size);
6558 gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
6559 gst_buffer_unref (priv);
6561 gst_caps_set_simple (caps, "stream-format", G_TYPE_STRING, "hvc1",
6562 "alignment", G_TYPE_STRING, "au", NULL);
6564 GST_WARNING ("No codec data found, assuming output is byte-stream");
6565 gst_caps_set_simple (caps, "stream-format", G_TYPE_STRING, "byte-stream",
6568 *codec_name = g_strdup ("HEVC");
6569 } else if ((!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO1)) ||
6570 (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO2)) ||
6571 (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO3)) ||
6572 (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO4))) {
6573 gint rmversion = -1;
6575 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO1))
6577 else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO2))
6579 else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO3))
6581 else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO4))
6584 caps = gst_caps_new_simple ("video/x-pn-realvideo",
6585 "rmversion", G_TYPE_INT, rmversion, NULL);
6586 GST_DEBUG ("data:%p, size:0x%x", data, size);
6587 /* We need to extract the extradata ! */
6588 if (data && (size >= 0x22)) {
6593 subformat = GST_READ_UINT32_BE (data + 0x1a);
6594 rformat = GST_READ_UINT32_BE (data + 0x1e);
6596 priv = gst_buffer_new_memdup (data + 0x1a, size - 0x1a);
6597 gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, "format",
6598 G_TYPE_INT, rformat, "subformat", G_TYPE_INT, subformat, NULL);
6599 gst_buffer_unref (priv);
6602 *codec_name = g_strdup_printf ("RealVideo %d.0", rmversion);
6603 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_THEORA)) {
6604 caps = gst_caps_new_empty_simple ("video/x-theora");
6605 context->stream_headers =
6606 gst_matroska_parse_xiph_stream_headers (context->codec_priv,
6607 context->codec_priv_size);
6608 /* FIXME: mark stream as broken and skip if there are no stream headers */
6609 context->send_stream_headers = TRUE;
6610 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_DIRAC)) {
6611 caps = gst_caps_new_empty_simple ("video/x-dirac");
6612 *codec_name = g_strdup_printf ("Dirac");
6613 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_VP8)) {
6614 caps = gst_caps_new_empty_simple ("video/x-vp8");
6615 if (videocontext->alpha_mode)
6616 gst_caps_set_simple (caps, "codec-alpha", G_TYPE_BOOLEAN, TRUE, NULL);
6617 *codec_name = g_strdup_printf ("On2 VP8");
6618 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_VP9)) {
6619 caps = gst_caps_new_empty_simple ("video/x-vp9");
6620 if (videocontext->alpha_mode)
6621 gst_caps_set_simple (caps, "codec-alpha", G_TYPE_BOOLEAN, TRUE, NULL);
6622 *codec_name = g_strdup_printf ("On2 VP9");
6623 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_AV1)) {
6624 caps = gst_caps_new_simple ("video/x-av1",
6625 "alignment", G_TYPE_STRING, "tu", NULL);
6629 priv = gst_buffer_new_memdup (data, size);
6630 gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
6631 gst_buffer_unref (priv);
6633 GST_WARNING ("No AV1 codec data found!");
6635 *codec_name = g_strdup_printf ("AOM AV1");
6636 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_FFV1)) {
6638 gst_caps_new_simple ("video/x-ffv", "ffvversion", G_TYPE_INT, 1, NULL);
6642 priv = gst_buffer_new_memdup (data, size);
6643 gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
6644 gst_buffer_unref (priv);
6646 GST_WARNING ("No FFV1 codec data found!");
6648 *codec_name = g_strdup_printf ("FFMpeg v1");
6649 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_PRORES)) {
6651 const gchar *variant, *variant_descr = "";
6653 /* Expect a fourcc in the codec private data */
6654 if (data && size >= 4) {
6655 fourcc = GST_STR_FOURCC (data);
6657 GST_WARNING ("No ProRes codec data found, picking 'standard 422 SD'");
6661 case GST_MAKE_FOURCC ('a', 'p', 'c', 's'):
6662 variant_descr = " 4:2:2 LT";
6665 case GST_MAKE_FOURCC ('a', 'p', 'c', 'h'):
6667 variant_descr = " 4:2:2 HQ";
6669 case GST_MAKE_FOURCC ('a', 'p', '4', 'h'):
6671 variant_descr = " 4:4:4:4";
6673 case GST_MAKE_FOURCC ('a', 'p', 'c', 'o'):
6675 variant_descr = " 4:2:2 Proxy";
6677 case GST_MAKE_FOURCC ('a', 'p', 'c', 'n'):
6679 variant = "standard";
6680 variant_descr = " 4:2:2 SD";
6684 GST_LOG ("Prores video, codec fourcc %" GST_FOURCC_FORMAT,
6685 GST_FOURCC_ARGS (fourcc));
6687 caps = gst_caps_new_simple ("video/x-prores",
6688 "format", G_TYPE_STRING, variant, NULL);
6689 *codec_name = g_strdup_printf ("Apple ProRes%s", variant_descr);
6690 context->postprocess_frame = gst_matroska_demux_add_prores_header;
6692 GST_WARNING ("Unknown codec '%s', cannot build Caps", codec_id);
6698 GstStructure *structure;
6700 for (i = 0; i < gst_caps_get_size (caps); i++) {
6701 structure = gst_caps_get_structure (caps, i);
6703 /* FIXME: use the real unit here! */
6704 GST_DEBUG ("video size %dx%d, target display size %dx%d (any unit)",
6705 videocontext->pixel_width,
6706 videocontext->pixel_height,
6707 videocontext->display_width, videocontext->display_height);
6709 /* pixel width and height are the w and h of the video in pixels */
6710 if (videocontext->pixel_width > 0 && videocontext->pixel_height > 0) {
6711 gint w = videocontext->pixel_width;
6712 gint h = videocontext->pixel_height;
6714 gst_structure_set (structure,
6715 "width", G_TYPE_INT, w, "height", G_TYPE_INT, h, NULL);
6718 if (videocontext->display_width > 0 || videocontext->display_height > 0) {
6721 if (videocontext->display_width <= 0)
6722 videocontext->display_width = videocontext->pixel_width;
6723 if (videocontext->display_height <= 0)
6724 videocontext->display_height = videocontext->pixel_height;
6726 /* calculate the pixel aspect ratio using the display and pixel w/h */
6727 n = videocontext->display_width * videocontext->pixel_height;
6728 d = videocontext->display_height * videocontext->pixel_width;
6729 GST_DEBUG ("setting PAR to %d/%d", n, d);
6730 gst_structure_set (structure, "pixel-aspect-ratio",
6732 videocontext->display_width * videocontext->pixel_height,
6733 videocontext->display_height * videocontext->pixel_width, NULL);
6736 if (videocontext->default_fps > 0.0) {
6739 gst_util_double_to_fraction (videocontext->default_fps, &fps_n, &fps_d);
6741 GST_DEBUG ("using default fps %d/%d", fps_n, fps_d);
6743 gst_structure_set (structure, "framerate", GST_TYPE_FRACTION, fps_n,
6745 } else if (context->default_duration > 0) {
6748 gst_video_guess_framerate (context->default_duration, &fps_n, &fps_d);
6750 GST_INFO ("using default duration %" G_GUINT64_FORMAT
6751 " framerate %d/%d", context->default_duration, fps_n, fps_d);
6753 gst_structure_set (structure, "framerate", GST_TYPE_FRACTION,
6754 fps_n, fps_d, NULL);
6756 gst_structure_set (structure, "framerate", GST_TYPE_FRACTION,
6760 switch (videocontext->interlace_mode) {
6761 case GST_MATROSKA_INTERLACE_MODE_PROGRESSIVE:
6762 gst_structure_set (structure,
6763 "interlace-mode", G_TYPE_STRING, "progressive", NULL);
6765 case GST_MATROSKA_INTERLACE_MODE_INTERLACED:
6766 gst_structure_set (structure,
6767 "interlace-mode", G_TYPE_STRING, "interleaved", NULL);
6769 if (videocontext->field_order != GST_VIDEO_FIELD_ORDER_UNKNOWN)
6770 gst_structure_set (structure, "field-order", G_TYPE_STRING,
6771 gst_video_field_order_to_string (videocontext->field_order),
6778 if (videocontext->multiview_mode != GST_VIDEO_MULTIVIEW_MODE_NONE) {
6779 if (gst_video_multiview_guess_half_aspect (videocontext->multiview_mode,
6780 videocontext->pixel_width, videocontext->pixel_height,
6781 videocontext->display_width * videocontext->pixel_height,
6782 videocontext->display_height * videocontext->pixel_width)) {
6783 videocontext->multiview_flags |= GST_VIDEO_MULTIVIEW_FLAGS_HALF_ASPECT;
6785 gst_caps_set_simple (caps,
6786 "multiview-mode", G_TYPE_STRING,
6787 gst_video_multiview_mode_to_caps_string
6788 (videocontext->multiview_mode), "multiview-flags",
6789 GST_TYPE_VIDEO_MULTIVIEW_FLAGSET, videocontext->multiview_flags,
6790 GST_FLAG_SET_MASK_EXACT, NULL);
6793 if (videocontext->colorimetry.range != GST_VIDEO_COLOR_RANGE_UNKNOWN ||
6794 videocontext->colorimetry.matrix != GST_VIDEO_COLOR_MATRIX_UNKNOWN ||
6795 videocontext->colorimetry.transfer != GST_VIDEO_TRANSFER_UNKNOWN ||
6796 videocontext->colorimetry.primaries !=
6797 GST_VIDEO_COLOR_PRIMARIES_UNKNOWN) {
6798 gchar *colorimetry =
6799 gst_video_colorimetry_to_string (&videocontext->colorimetry);
6800 gst_caps_set_simple (caps, "colorimetry", G_TYPE_STRING, colorimetry,
6802 GST_DEBUG ("setting colorimetry to %s", colorimetry);
6803 g_free (colorimetry);
6806 if (videocontext->mastering_display_info_present) {
6807 if (!gst_video_mastering_display_info_add_to_caps
6808 (&videocontext->mastering_display_info, caps)) {
6809 GST_WARNING ("couldn't set mastering display info to caps");
6813 if (videocontext->content_light_level.max_content_light_level &&
6814 videocontext->content_light_level.max_frame_average_light_level) {
6815 if (!gst_video_content_light_level_add_to_caps
6816 (&videocontext->content_light_level, caps)) {
6817 GST_WARNING ("couldn't set content light level to caps");
6821 caps = gst_caps_simplify (caps);
6828 * Some AAC specific code... *sigh*
6829 * FIXME: maybe we should use '15' and code the sample rate explicitly
6830 * if the sample rate doesn't match the predefined rates exactly? (tpm)
6834 aac_rate_idx (gint rate)
6838 else if (75132 <= rate)
6840 else if (55426 <= rate)
6842 else if (46009 <= rate)
6844 else if (37566 <= rate)
6846 else if (27713 <= rate)
6848 else if (23004 <= rate)
6850 else if (18783 <= rate)
6852 else if (13856 <= rate)
6854 else if (11502 <= rate)
6856 else if (9391 <= rate)
6863 aac_profile_idx (const gchar * codec_id)
6867 if (strlen (codec_id) <= 12)
6869 else if (!strncmp (&codec_id[12], "MAIN", 4))
6871 else if (!strncmp (&codec_id[12], "LC", 2))
6873 else if (!strncmp (&codec_id[12], "SSR", 3))
6882 round_up_pow2 (guint n)
6893 #define AAC_SYNC_EXTENSION_TYPE 0x02b7
6896 gst_matroska_demux_audio_caps (GstMatroskaTrackAudioContext *
6897 audiocontext, const gchar * codec_id, guint8 * data, guint size,
6898 gchar ** codec_name, guint16 * riff_audio_fmt, GstClockTime * lead_in_ts)
6900 GstMatroskaTrackContext *context = (GstMatroskaTrackContext *) audiocontext;
6901 GstCaps *caps = NULL;
6903 /* Max potential blocksize causing the longest possible lead_in_ts need, as
6904 * we don't have the exact number parsed out here */
6905 guint max_blocksize = 0;
6906 /* Original samplerate before SBR multiplications, as parsers would use */
6907 guint rate = audiocontext->samplerate;
6909 g_assert (audiocontext != NULL);
6910 g_assert (codec_name != NULL);
6913 *riff_audio_fmt = 0;
6915 /* TODO: check if we have all codec types from matroska-ids.h
6916 * check if we have to do more special things with codec_private
6917 * check if we need bitdepth in different places too
6918 * implement channel position magic
6920 * GST_MATROSKA_CODEC_ID_AUDIO_AC3_BSID9
6921 * GST_MATROSKA_CODEC_ID_AUDIO_AC3_BSID10
6922 * GST_MATROSKA_CODEC_ID_AUDIO_QUICKTIME_QDMC
6923 * GST_MATROSKA_CODEC_ID_AUDIO_QUICKTIME_QDM2
6926 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L1) ||
6927 !strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L2) ||
6928 !strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L3)) {
6931 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L1))
6933 else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L2))
6938 lead_in = 30; /* Could mp2 need as much too? */
6939 max_blocksize = 1152;
6940 caps = gst_caps_new_simple ("audio/mpeg",
6941 "mpegversion", G_TYPE_INT, 1, "layer", G_TYPE_INT, layer, NULL);
6942 *codec_name = g_strdup_printf ("MPEG-1 layer %d", layer);
6943 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_PCM_INT_BE) ||
6944 !strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_PCM_INT_LE)) {
6947 GstAudioFormat format;
6949 sign = (audiocontext->bitdepth != 8);
6950 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_PCM_INT_BE))
6951 endianness = G_BIG_ENDIAN;
6953 endianness = G_LITTLE_ENDIAN;
6955 format = gst_audio_format_build_integer (sign, endianness,
6956 audiocontext->bitdepth, audiocontext->bitdepth);
6958 /* FIXME: Channel mask and reordering */
6959 caps = gst_caps_new_simple ("audio/x-raw",
6960 "format", G_TYPE_STRING, gst_audio_format_to_string (format),
6961 "layout", G_TYPE_STRING, "interleaved",
6962 "channel-mask", GST_TYPE_BITMASK,
6963 gst_audio_channel_get_fallback_mask (audiocontext->channels), NULL);
6965 *codec_name = g_strdup_printf ("Raw %d-bit PCM audio",
6966 audiocontext->bitdepth);
6967 context->alignment = GST_ROUND_UP_8 (audiocontext->bitdepth) / 8;
6968 context->alignment = round_up_pow2 (context->alignment);
6969 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_PCM_FLOAT)) {
6970 const gchar *format;
6971 if (audiocontext->bitdepth == 32)
6975 /* FIXME: Channel mask and reordering */
6976 caps = gst_caps_new_simple ("audio/x-raw",
6977 "format", G_TYPE_STRING, format,
6978 "layout", G_TYPE_STRING, "interleaved",
6979 "channel-mask", GST_TYPE_BITMASK,
6980 gst_audio_channel_get_fallback_mask (audiocontext->channels), NULL);
6981 *codec_name = g_strdup_printf ("Raw %d-bit floating-point audio",
6982 audiocontext->bitdepth);
6983 context->alignment = audiocontext->bitdepth / 8;
6984 context->alignment = round_up_pow2 (context->alignment);
6985 } else if (!strncmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_AC3,
6986 strlen (GST_MATROSKA_CODEC_ID_AUDIO_AC3))) {
6988 max_blocksize = 1536;
6989 caps = gst_caps_new_simple ("audio/x-ac3",
6990 "framed", G_TYPE_BOOLEAN, TRUE, NULL);
6991 *codec_name = g_strdup ("AC-3 audio");
6992 } else if (!strncmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_EAC3,
6993 strlen (GST_MATROSKA_CODEC_ID_AUDIO_EAC3))) {
6995 max_blocksize = 1536;
6996 caps = gst_caps_new_simple ("audio/x-eac3",
6997 "framed", G_TYPE_BOOLEAN, TRUE, NULL);
6998 *codec_name = g_strdup ("E-AC-3 audio");
6999 } else if (!strncmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_TRUEHD,
7000 strlen (GST_MATROSKA_CODEC_ID_AUDIO_TRUEHD))) {
7001 caps = gst_caps_new_empty_simple ("audio/x-true-hd");
7002 *codec_name = g_strdup ("Dolby TrueHD");
7003 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_DTS)) {
7004 caps = gst_caps_new_empty_simple ("audio/x-dts");
7005 *codec_name = g_strdup ("DTS audio");
7006 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_VORBIS)) {
7007 caps = gst_caps_new_empty_simple ("audio/x-vorbis");
7008 context->stream_headers =
7009 gst_matroska_parse_xiph_stream_headers (context->codec_priv,
7010 context->codec_priv_size);
7011 /* FIXME: mark stream as broken and skip if there are no stream headers */
7012 context->send_stream_headers = TRUE;
7013 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_FLAC)) {
7014 caps = gst_caps_new_empty_simple ("audio/x-flac");
7015 context->stream_headers =
7016 gst_matroska_parse_flac_stream_headers (context->codec_priv,
7017 context->codec_priv_size);
7018 /* FIXME: mark stream as broken and skip if there are no stream headers */
7019 context->send_stream_headers = TRUE;
7020 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_SPEEX)) {
7021 caps = gst_caps_new_empty_simple ("audio/x-speex");
7022 context->stream_headers =
7023 gst_matroska_parse_speex_stream_headers (context->codec_priv,
7024 context->codec_priv_size);
7025 /* FIXME: mark stream as broken and skip if there are no stream headers */
7026 context->send_stream_headers = TRUE;
7027 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_OPUS)) {
7030 if (context->codec_priv_size >= 19) {
7031 if (audiocontext->samplerate)
7032 GST_WRITE_UINT32_LE ((guint8 *) context->codec_priv + 12,
7033 audiocontext->samplerate);
7034 if (context->codec_delay) {
7036 gst_util_uint64_scale_round (context->codec_delay, 48000,
7038 GST_WRITE_UINT16_LE ((guint8 *) context->codec_priv + 10, delay);
7042 gst_buffer_new_memdup (context->codec_priv, context->codec_priv_size);
7043 caps = gst_codec_utils_opus_create_caps_from_header (tmp, NULL);
7044 gst_buffer_unref (tmp);
7045 *codec_name = g_strdup ("Opus");
7046 } else if (context->codec_priv_size == 0) {
7047 GST_WARNING ("No Opus codec data found, trying to create one");
7048 if (audiocontext->channels <= 2) {
7049 guint8 streams, coupled, channels;
7053 audiocontext->samplerate == 0 ? 48000 : audiocontext->samplerate;
7055 channels = audiocontext->channels == 0 ? 2 : audiocontext->channels;
7056 if (channels == 1) {
7065 gst_codec_utils_opus_create_caps (samplerate, channels, 0, streams,
7068 *codec_name = g_strdup ("Opus");
7070 GST_WARNING ("Failed to create Opus caps from audio context");
7073 GST_WARNING ("No Opus codec data, and not enough info to create one");
7076 GST_WARNING ("Invalid Opus codec data size (got %" G_GSIZE_FORMAT
7077 ", expected 19)", context->codec_priv_size);
7079 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_ACM)) {
7080 gst_riff_strf_auds auds;
7082 if (data && size >= 18) {
7083 GstBuffer *codec_data = NULL;
7085 /* little-endian -> byte-order */
7086 auds.format = GST_READ_UINT16_LE (data);
7087 auds.channels = GST_READ_UINT16_LE (data + 2);
7088 auds.rate = GST_READ_UINT32_LE (data + 4);
7089 auds.av_bps = GST_READ_UINT32_LE (data + 8);
7090 auds.blockalign = GST_READ_UINT16_LE (data + 12);
7091 auds.bits_per_sample = GST_READ_UINT16_LE (data + 16);
7093 /* 18 is the waveformatex size */
7095 codec_data = gst_buffer_new_wrapped_full (GST_MEMORY_FLAG_READONLY,
7096 data + 18, size - 18, 0, size - 18, NULL, NULL);
7100 *riff_audio_fmt = auds.format;
7102 /* FIXME: Handle reorder map */
7103 caps = gst_riff_create_audio_caps (auds.format, NULL, &auds, codec_data,
7104 NULL, codec_name, NULL);
7106 gst_buffer_unref (codec_data);
7109 GST_WARNING ("Unhandled RIFF audio format 0x%02x", auds.format);
7112 GST_WARNING ("Invalid codec data size (%d expected, got %d)", 18, size);
7114 } else if (g_str_has_prefix (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_AAC)) {
7115 GstBuffer *priv = NULL;
7117 gint rate_idx, profile;
7118 guint8 *data = NULL;
7120 /* unspecified AAC profile with opaque private codec data */
7121 if (strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_AAC) == 0) {
7122 if (context->codec_priv_size >= 2) {
7123 guint obj_type, freq_index, explicit_freq_bytes = 0;
7125 codec_id = GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG4;
7127 freq_index = (GST_READ_UINT16_BE (context->codec_priv) & 0x780) >> 7;
7128 obj_type = (GST_READ_UINT16_BE (context->codec_priv) & 0xF800) >> 11;
7129 if (freq_index == 15)
7130 explicit_freq_bytes = 3;
7131 GST_DEBUG ("obj_type = %u, freq_index = %u", obj_type, freq_index);
7132 priv = gst_buffer_new_memdup (context->codec_priv,
7133 context->codec_priv_size);
7134 /* assume SBR if samplerate <= 24kHz */
7135 if (obj_type == 5 || (freq_index >= 6 && freq_index != 15) ||
7136 (context->codec_priv_size == (5 + explicit_freq_bytes))) {
7137 /* TODO: Commonly aacparse will reset the rate in caps to
7138 * non-multiplied - which one is correct? */
7139 audiocontext->samplerate *= 2;
7142 GST_WARNING ("Opaque A_AAC codec ID, but no codec private data");
7143 /* this is pretty broken;
7144 * maybe we need to make up some default private,
7145 * or maybe ADTS data got dumped in.
7146 * Let's set up some private data now, and check actual data later */
7147 /* just try this and see what happens ... */
7148 codec_id = GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG4;
7149 context->postprocess_frame = gst_matroska_demux_check_aac;
7153 /* make up decoder-specific data if it is not supplied */
7157 priv = gst_buffer_new_allocate (NULL, 5, NULL);
7158 gst_buffer_map (priv, &map, GST_MAP_WRITE);
7160 rate_idx = aac_rate_idx (audiocontext->samplerate);
7161 profile = aac_profile_idx (codec_id);
7163 data[0] = ((profile + 1) << 3) | ((rate_idx & 0xE) >> 1);
7164 data[1] = ((rate_idx & 0x1) << 7) | (audiocontext->channels << 3);
7166 if (!strncmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG2,
7167 strlen (GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG2))) {
7169 gst_buffer_unmap (priv, &map);
7170 gst_buffer_set_size (priv, 2);
7171 } else if (!strncmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG4,
7172 strlen (GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG4))) {
7175 if (g_strrstr (codec_id, "SBR")) {
7176 /* HE-AAC (aka SBR AAC) */
7177 audiocontext->samplerate *= 2;
7178 rate_idx = aac_rate_idx (audiocontext->samplerate);
7179 data[2] = AAC_SYNC_EXTENSION_TYPE >> 3;
7180 data[3] = ((AAC_SYNC_EXTENSION_TYPE & 0x07) << 5) | 5;
7181 data[4] = (1 << 7) | (rate_idx << 3);
7182 gst_buffer_unmap (priv, &map);
7184 gst_buffer_unmap (priv, &map);
7185 gst_buffer_set_size (priv, 2);
7188 gst_buffer_unmap (priv, &map);
7189 gst_buffer_unref (priv);
7191 GST_ERROR ("Unknown AAC profile and no codec private data");
7197 max_blocksize = 1024;
7198 caps = gst_caps_new_simple ("audio/mpeg",
7199 "mpegversion", G_TYPE_INT, mpegversion,
7200 "framed", G_TYPE_BOOLEAN, TRUE,
7201 "stream-format", G_TYPE_STRING, "raw", NULL);
7202 gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
7203 if (context->codec_priv && context->codec_priv_size > 0)
7204 gst_codec_utils_aac_caps_set_level_and_profile (caps,
7205 context->codec_priv, context->codec_priv_size);
7206 *codec_name = g_strdup_printf ("MPEG-%d AAC audio", mpegversion);
7207 gst_buffer_unref (priv);
7209 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_TTA)) {
7210 caps = gst_caps_new_simple ("audio/x-tta",
7211 "width", G_TYPE_INT, audiocontext->bitdepth, NULL);
7212 *codec_name = g_strdup ("TTA audio");
7213 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_WAVPACK4)) {
7214 caps = gst_caps_new_simple ("audio/x-wavpack",
7215 "width", G_TYPE_INT, audiocontext->bitdepth,
7216 "framed", G_TYPE_BOOLEAN, TRUE, NULL);
7217 *codec_name = g_strdup ("Wavpack audio");
7218 context->postprocess_frame = gst_matroska_demux_add_wvpk_header;
7219 audiocontext->wvpk_block_index = 0;
7220 } else if ((!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_14_4)) ||
7221 (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_28_8)) ||
7222 (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_COOK))) {
7223 gint raversion = -1;
7225 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_14_4))
7227 else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_COOK))
7232 caps = gst_caps_new_simple ("audio/x-pn-realaudio",
7233 "raversion", G_TYPE_INT, raversion, NULL);
7234 /* Extract extra information from caps, mapping varies based on codec */
7235 if (data && (size >= 0x50)) {
7242 guint extra_data_size;
7244 GST_DEBUG ("real audio raversion:%d", raversion);
7245 if (raversion == 8) {
7247 flavor = GST_READ_UINT16_BE (data + 22);
7248 packet_size = GST_READ_UINT32_BE (data + 24);
7249 height = GST_READ_UINT16_BE (data + 40);
7250 leaf_size = GST_READ_UINT16_BE (data + 44);
7251 sample_width = GST_READ_UINT16_BE (data + 58);
7252 extra_data_size = GST_READ_UINT32_BE (data + 74);
7255 ("flavor:%d, packet_size:%d, height:%d, leaf_size:%d, sample_width:%d, extra_data_size:%d",
7256 flavor, packet_size, height, leaf_size, sample_width,
7258 gst_caps_set_simple (caps, "flavor", G_TYPE_INT, flavor, "packet_size",
7259 G_TYPE_INT, packet_size, "height", G_TYPE_INT, height, "leaf_size",
7260 G_TYPE_INT, leaf_size, "width", G_TYPE_INT, sample_width, NULL);
7262 if ((size - 78) >= extra_data_size) {
7263 priv = gst_buffer_new_memdup (data + 78, extra_data_size);
7264 gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
7265 gst_buffer_unref (priv);
7270 *codec_name = g_strdup_printf ("RealAudio %d.0", raversion);
7271 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_SIPR)) {
7272 caps = gst_caps_new_empty_simple ("audio/x-sipro");
7273 *codec_name = g_strdup ("Sipro/ACELP.NET Voice Codec");
7274 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_RALF)) {
7275 caps = gst_caps_new_empty_simple ("audio/x-ralf-mpeg4-generic");
7276 *codec_name = g_strdup ("Real Audio Lossless");
7277 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_ATRC)) {
7278 caps = gst_caps_new_empty_simple ("audio/x-vnd.sony.atrac3");
7279 *codec_name = g_strdup ("Sony ATRAC3");
7281 GST_WARNING ("Unknown codec '%s', cannot build Caps", codec_id);
7286 if (audiocontext->samplerate > 0 && audiocontext->channels > 0) {
7289 for (i = 0; i < gst_caps_get_size (caps); i++) {
7290 gst_structure_set (gst_caps_get_structure (caps, i),
7291 "channels", G_TYPE_INT, audiocontext->channels,
7292 "rate", G_TYPE_INT, audiocontext->samplerate, NULL);
7296 caps = gst_caps_simplify (caps);
7299 if (lead_in_ts && lead_in && max_blocksize && rate) {
7301 gst_util_uint64_scale (GST_SECOND, max_blocksize * lead_in, rate);
7308 gst_matroska_demux_subtitle_caps (GstMatroskaTrackSubtitleContext *
7309 subtitlecontext, const gchar * codec_id, gpointer data, guint size)
7311 GstCaps *caps = NULL;
7312 GstMatroskaTrackContext *context =
7313 (GstMatroskaTrackContext *) subtitlecontext;
7315 /* for backwards compatibility */
7316 if (!g_ascii_strcasecmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_ASCII))
7317 codec_id = GST_MATROSKA_CODEC_ID_SUBTITLE_UTF8;
7318 else if (!g_ascii_strcasecmp (codec_id, "S_SSA"))
7319 codec_id = GST_MATROSKA_CODEC_ID_SUBTITLE_SSA;
7320 else if (!g_ascii_strcasecmp (codec_id, "S_ASS"))
7321 codec_id = GST_MATROSKA_CODEC_ID_SUBTITLE_ASS;
7322 else if (!g_ascii_strcasecmp (codec_id, "S_USF"))
7323 codec_id = GST_MATROSKA_CODEC_ID_SUBTITLE_USF;
7325 /* TODO: Add GST_MATROSKA_CODEC_ID_SUBTITLE_BMP support
7326 * Check if we have to do something with codec_private */
7327 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_UTF8)) {
7328 /* well, plain text simply does not have a lot of markup ... */
7329 caps = gst_caps_new_simple ("text/x-raw", "format", G_TYPE_STRING,
7330 "pango-markup", NULL);
7331 context->postprocess_frame = gst_matroska_demux_check_subtitle_buffer;
7332 subtitlecontext->check_markup = TRUE;
7333 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_SSA)) {
7334 caps = gst_caps_new_empty_simple ("application/x-ssa");
7335 context->postprocess_frame = gst_matroska_demux_check_subtitle_buffer;
7336 subtitlecontext->check_markup = FALSE;
7337 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_ASS)) {
7338 caps = gst_caps_new_empty_simple ("application/x-ass");
7339 context->postprocess_frame = gst_matroska_demux_check_subtitle_buffer;
7340 subtitlecontext->check_markup = FALSE;
7341 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_USF)) {
7342 caps = gst_caps_new_empty_simple ("application/x-usf");
7343 context->postprocess_frame = gst_matroska_demux_check_subtitle_buffer;
7344 subtitlecontext->check_markup = FALSE;
7345 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_VOBSUB)) {
7346 caps = gst_caps_new_empty_simple ("subpicture/x-dvd");
7347 ((GstMatroskaTrackContext *) subtitlecontext)->send_dvd_event = TRUE;
7348 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_HDMVPGS)) {
7349 caps = gst_caps_new_empty_simple ("subpicture/x-pgs");
7350 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_KATE)) {
7351 caps = gst_caps_new_empty_simple ("subtitle/x-kate");
7352 context->stream_headers =
7353 gst_matroska_parse_xiph_stream_headers (context->codec_priv,
7354 context->codec_priv_size);
7355 /* FIXME: mark stream as broken and skip if there are no stream headers */
7356 context->send_stream_headers = TRUE;
7358 GST_DEBUG ("Unknown subtitle stream: codec_id='%s'", codec_id);
7359 caps = gst_caps_new_empty_simple ("application/x-subtitle-unknown");
7362 if (data != NULL && size > 0) {
7365 buf = gst_buffer_new_memdup (data, size);
7366 gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, buf, NULL);
7367 gst_buffer_unref (buf);
7375 gst_matroska_demux_set_index (GstElement * element, GstIndex * index)
7377 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (element);
7379 GST_OBJECT_LOCK (demux);
7380 if (demux->common.element_index)
7381 gst_object_unref (demux->common.element_index);
7382 demux->common.element_index = index ? gst_object_ref (index) : NULL;
7383 GST_OBJECT_UNLOCK (demux);
7384 GST_DEBUG_OBJECT (demux, "Set index %" GST_PTR_FORMAT,
7385 demux->common.element_index);
7389 gst_matroska_demux_get_index (GstElement * element)
7391 GstIndex *result = NULL;
7392 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (element);
7394 GST_OBJECT_LOCK (demux);
7395 if (demux->common.element_index)
7396 result = gst_object_ref (demux->common.element_index);
7397 GST_OBJECT_UNLOCK (demux);
7399 GST_DEBUG_OBJECT (demux, "Returning index %" GST_PTR_FORMAT, result);
7405 static GstStateChangeReturn
7406 gst_matroska_demux_change_state (GstElement * element,
7407 GstStateChange transition)
7409 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (element);
7410 GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
7412 /* handle upwards state changes here */
7413 switch (transition) {
7418 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
7420 /* handle downwards state changes */
7421 switch (transition) {
7422 case GST_STATE_CHANGE_PAUSED_TO_READY:
7423 gst_matroska_demux_reset (GST_ELEMENT (demux));
7433 gst_matroska_demux_set_property (GObject * object,
7434 guint prop_id, const GValue * value, GParamSpec * pspec)
7436 GstMatroskaDemux *demux;
7438 g_return_if_fail (GST_IS_MATROSKA_DEMUX (object));
7439 demux = GST_MATROSKA_DEMUX (object);
7442 case PROP_MAX_GAP_TIME:
7443 GST_OBJECT_LOCK (demux);
7444 demux->max_gap_time = g_value_get_uint64 (value);
7445 GST_OBJECT_UNLOCK (demux);
7447 case PROP_MAX_BACKTRACK_DISTANCE:
7448 GST_OBJECT_LOCK (demux);
7449 demux->max_backtrack_distance = g_value_get_uint (value);
7450 GST_OBJECT_UNLOCK (demux);
7453 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
7459 gst_matroska_demux_get_property (GObject * object,
7460 guint prop_id, GValue * value, GParamSpec * pspec)
7462 GstMatroskaDemux *demux;
7464 g_return_if_fail (GST_IS_MATROSKA_DEMUX (object));
7465 demux = GST_MATROSKA_DEMUX (object);
7468 case PROP_MAX_GAP_TIME:
7469 GST_OBJECT_LOCK (demux);
7470 g_value_set_uint64 (value, demux->max_gap_time);
7471 GST_OBJECT_UNLOCK (demux);
7473 case PROP_MAX_BACKTRACK_DISTANCE:
7474 GST_OBJECT_LOCK (demux);
7475 g_value_set_uint (value, demux->max_backtrack_distance);
7476 GST_OBJECT_UNLOCK (demux);
7479 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
7484 static const gchar *
7485 gst_matroska_track_encryption_algorithm_name (gint val)
7488 GEnumClass *enum_class =
7489 g_type_class_ref (MATROSKA_TRACK_ENCRYPTION_ALGORITHM_TYPE);
7490 en = g_enum_get_value (G_ENUM_CLASS (enum_class), val);
7491 return en ? en->value_nick : NULL;
7494 static const gchar *
7495 gst_matroska_track_encryption_cipher_mode_name (gint val)
7498 GEnumClass *enum_class =
7499 g_type_class_ref (MATROSKA_TRACK_ENCRYPTION_CIPHER_MODE_TYPE);
7500 en = g_enum_get_value (G_ENUM_CLASS (enum_class), val);
7501 return en ? en->value_nick : NULL;
7504 static const gchar *
7505 gst_matroska_track_encoding_scope_name (gint val)
7508 GEnumClass *enum_class =
7509 g_type_class_ref (MATROSKA_TRACK_ENCODING_SCOPE_TYPE);
7511 en = g_enum_get_value (G_ENUM_CLASS (enum_class), val);
7512 return en ? en->value_nick : NULL;