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., 59 Temple Place - Suite 330,
22 * Boston, MA 02111-1307, USA.
25 /* TODO: check CRC32 if present
26 * TODO: there can be a segment after the first segment. Handle like
27 * chained oggs. Fixes #334082
28 * TODO: Test samples: http://www.matroska.org/samples/matrix/index.html
29 * http://samples.mplayerhq.hu/Matroska/
30 * TODO: check if demuxing is done correct for all codecs according to spec
31 * TODO: seeking with incomplete or without CUE
35 * SECTION:element-matroskademux
37 * matroskademux demuxes a Matroska file into the different contained streams.
40 * <title>Example launch line</title>
42 * gst-launch -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 /* For AVI compatibility mode
57 and for fourcc stuff */
58 #include <gst/riff/riff-read.h>
59 #include <gst/riff/riff-ids.h>
60 #include <gst/riff/riff-media.h>
62 #include <gst/tag/tag.h>
64 #include <gst/pbutils/pbutils.h>
66 #include "matroska-demux.h"
67 #include "matroska-ids.h"
69 GST_DEBUG_CATEGORY_STATIC (matroskademux_debug);
70 #define GST_CAT_DEFAULT matroskademux_debug
72 #define DEBUG_ELEMENT_START(demux, ebml, element) \
73 GST_DEBUG_OBJECT (demux, "Parsing " element " element at offset %" \
74 G_GUINT64_FORMAT, gst_ebml_read_get_pos (ebml))
76 #define DEBUG_ELEMENT_STOP(demux, ebml, element, ret) \
77 GST_DEBUG_OBJECT (demux, "Parsing " element " element " \
78 " finished with '%s'", gst_flow_get_name (ret))
87 static GstStaticPadTemplate sink_templ = GST_STATIC_PAD_TEMPLATE ("sink",
90 GST_STATIC_CAPS ("video/x-matroska; video/webm")
93 /* TODO: fill in caps! */
95 static GstStaticPadTemplate audio_src_templ =
96 GST_STATIC_PAD_TEMPLATE ("audio_%02d",
99 GST_STATIC_CAPS ("ANY")
102 static GstStaticPadTemplate video_src_templ =
103 GST_STATIC_PAD_TEMPLATE ("video_%02d",
106 GST_STATIC_CAPS ("ANY")
109 static GstStaticPadTemplate subtitle_src_templ =
110 GST_STATIC_PAD_TEMPLATE ("subtitle_%02d",
113 GST_STATIC_CAPS ("text/x-pango-markup; application/x-ssa; "
114 "application/x-ass;application/x-usf; video/x-dvd-subpicture; "
115 "subpicture/x-pgs; subtitle/x-kate; " "application/x-subtitle-unknown")
118 static GstFlowReturn gst_matroska_demux_parse_id (GstMatroskaDemux * demux,
119 guint32 id, guint64 length, guint needed);
121 /* element functions */
122 static void gst_matroska_demux_loop (GstPad * pad);
124 static gboolean gst_matroska_demux_element_send_event (GstElement * element,
126 static gboolean gst_matroska_demux_element_query (GstElement * element,
130 static gboolean gst_matroska_demux_sink_activate_pull (GstPad * sinkpad,
132 static gboolean gst_matroska_demux_sink_activate (GstPad * sinkpad);
134 static gboolean gst_matroska_demux_handle_seek_event (GstMatroskaDemux * demux,
135 GstPad * pad, GstEvent * event);
136 static gboolean gst_matroska_demux_handle_src_event (GstPad * pad,
138 static const GstQueryType *gst_matroska_demux_get_src_query_types (GstPad *
140 static gboolean gst_matroska_demux_handle_src_query (GstPad * pad,
143 static gboolean gst_matroska_demux_handle_sink_event (GstPad * pad,
145 static GstFlowReturn gst_matroska_demux_chain (GstPad * pad,
148 static GstStateChangeReturn
149 gst_matroska_demux_change_state (GstElement * element,
150 GstStateChange transition);
152 gst_matroska_demux_set_index (GstElement * element, GstIndex * index);
153 static GstIndex *gst_matroska_demux_get_index (GstElement * element);
156 static GstCaps *gst_matroska_demux_video_caps (GstMatroskaTrackVideoContext
157 * videocontext, const gchar * codec_id, guint8 * data, guint size,
158 gchar ** codec_name, guint32 * riff_fourcc);
159 static GstCaps *gst_matroska_demux_audio_caps (GstMatroskaTrackAudioContext
160 * audiocontext, const gchar * codec_id, guint8 * data, guint size,
161 gchar ** codec_name, guint16 * riff_audio_fmt);
163 * gst_matroska_demux_subtitle_caps (GstMatroskaTrackSubtitleContext *
164 subtitlecontext, const gchar * codec_id, gpointer data, guint size);
167 static void gst_matroska_demux_reset (GstElement * element);
168 static gboolean perform_seek_to_offset (GstMatroskaDemux * demux,
171 GType gst_matroska_demux_get_type (void);
172 GST_BOILERPLATE (GstMatroskaDemux, gst_matroska_demux, GstElement,
176 gst_matroska_demux_base_init (gpointer klass)
178 GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
180 gst_element_class_add_pad_template (element_class,
181 gst_static_pad_template_get (&video_src_templ));
182 gst_element_class_add_pad_template (element_class,
183 gst_static_pad_template_get (&audio_src_templ));
184 gst_element_class_add_pad_template (element_class,
185 gst_static_pad_template_get (&subtitle_src_templ));
186 gst_element_class_add_pad_template (element_class,
187 gst_static_pad_template_get (&sink_templ));
189 gst_element_class_set_details_simple (element_class, "Matroska demuxer",
191 "Demuxes Matroska/WebM streams into video/audio/subtitles",
192 "GStreamer maintainers <gstreamer-devel@lists.sourceforge.net>");
196 gst_matroska_demux_finalize (GObject * object)
198 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (object);
200 if (demux->common.src) {
201 g_ptr_array_free (demux->common.src, TRUE);
202 demux->common.src = NULL;
205 if (demux->common.global_tags) {
206 gst_tag_list_free (demux->common.global_tags);
207 demux->common.global_tags = NULL;
210 g_object_unref (demux->common.adapter);
212 G_OBJECT_CLASS (parent_class)->finalize (object);
216 gst_matroska_demux_class_init (GstMatroskaDemuxClass * klass)
218 GObjectClass *gobject_class = (GObjectClass *) klass;
219 GstElementClass *gstelement_class = (GstElementClass *) klass;
221 GST_DEBUG_CATEGORY_INIT (matroskademux_debug, "matroskademux", 0,
224 gobject_class->finalize = gst_matroska_demux_finalize;
226 gstelement_class->change_state =
227 GST_DEBUG_FUNCPTR (gst_matroska_demux_change_state);
228 gstelement_class->send_event =
229 GST_DEBUG_FUNCPTR (gst_matroska_demux_element_send_event);
230 gstelement_class->query =
231 GST_DEBUG_FUNCPTR (gst_matroska_demux_element_query);
233 gstelement_class->set_index =
234 GST_DEBUG_FUNCPTR (gst_matroska_demux_set_index);
235 gstelement_class->get_index =
236 GST_DEBUG_FUNCPTR (gst_matroska_demux_get_index);
240 gst_matroska_demux_init (GstMatroskaDemux * demux,
241 GstMatroskaDemuxClass * klass)
243 demux->common.sinkpad = gst_pad_new_from_static_template (&sink_templ,
245 gst_pad_set_activate_function (demux->common.sinkpad,
246 GST_DEBUG_FUNCPTR (gst_matroska_demux_sink_activate));
247 gst_pad_set_activatepull_function (demux->common.sinkpad,
248 GST_DEBUG_FUNCPTR (gst_matroska_demux_sink_activate_pull));
249 gst_pad_set_chain_function (demux->common.sinkpad,
250 GST_DEBUG_FUNCPTR (gst_matroska_demux_chain));
251 gst_pad_set_event_function (demux->common.sinkpad,
252 GST_DEBUG_FUNCPTR (gst_matroska_demux_handle_sink_event));
253 gst_element_add_pad (GST_ELEMENT (demux), demux->common.sinkpad);
255 /* initial stream no. */
256 demux->common.src = NULL;
258 demux->common.writing_app = NULL;
259 demux->common.muxing_app = NULL;
260 demux->common.index = NULL;
261 demux->common.global_tags = NULL;
263 demux->common.adapter = gst_adapter_new ();
266 gst_matroska_demux_reset (GST_ELEMENT (demux));
270 gst_matroska_track_free (GstMatroskaTrackContext * track)
272 g_free (track->codec_id);
273 g_free (track->codec_name);
274 g_free (track->name);
275 g_free (track->language);
276 g_free (track->codec_priv);
277 g_free (track->codec_state);
279 if (track->encodings != NULL) {
282 for (i = 0; i < track->encodings->len; ++i) {
283 GstMatroskaTrackEncoding *enc = &g_array_index (track->encodings,
284 GstMatroskaTrackEncoding,
287 g_free (enc->comp_settings);
289 g_array_free (track->encodings, TRUE);
292 if (track->pending_tags)
293 gst_tag_list_free (track->pending_tags);
295 if (track->index_table)
296 g_array_free (track->index_table, TRUE);
302 * Returns the aggregated GstFlowReturn.
305 gst_matroska_demux_combine_flows (GstMatroskaDemux * demux,
306 GstMatroskaTrackContext * track, GstFlowReturn ret)
310 /* store the value */
311 track->last_flow = ret;
313 /* any other error that is not-linked can be returned right away */
314 if (ret != GST_FLOW_NOT_LINKED)
317 /* only return NOT_LINKED if all other pads returned NOT_LINKED */
318 g_assert (demux->common.src->len == demux->common.num_streams);
319 for (i = 0; i < demux->common.src->len; i++) {
320 GstMatroskaTrackContext *ostream = g_ptr_array_index (demux->common.src,
326 ret = ostream->last_flow;
327 /* some other return value (must be SUCCESS but we can return
328 * other values as well) */
329 if (ret != GST_FLOW_NOT_LINKED)
332 /* if we get here, all other pads were unlinked and we return
335 GST_LOG_OBJECT (demux, "combined return %s", gst_flow_get_name (ret));
340 gst_matroska_demux_free_parsed_el (gpointer mem, gpointer user_data)
342 g_slice_free (guint64, mem);
346 gst_matroska_demux_reset (GstElement * element)
348 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (element);
351 GST_DEBUG_OBJECT (demux, "Resetting state");
354 demux->common.state = GST_MATROSKA_READ_STATE_START;
356 /* clean up existing streams */
357 if (demux->common.src) {
358 g_assert (demux->common.src->len == demux->common.num_streams);
359 for (i = 0; i < demux->common.src->len; i++) {
360 GstMatroskaTrackContext *context = g_ptr_array_index (demux->common.src,
363 if (context->pad != NULL)
364 gst_element_remove_pad (GST_ELEMENT (demux), context->pad);
366 gst_caps_replace (&context->caps, NULL);
367 gst_matroska_track_free (context);
369 g_ptr_array_free (demux->common.src, TRUE);
371 demux->common.src = g_ptr_array_new ();
373 demux->common.num_streams = 0;
374 demux->num_a_streams = 0;
375 demux->num_t_streams = 0;
376 demux->num_v_streams = 0;
378 /* reset media info */
379 g_free (demux->common.writing_app);
380 demux->common.writing_app = NULL;
381 g_free (demux->common.muxing_app);
382 demux->common.muxing_app = NULL;
385 if (demux->common.index) {
386 g_array_free (demux->common.index, TRUE);
387 demux->common.index = NULL;
390 if (demux->clusters) {
391 g_array_free (demux->clusters, TRUE);
392 demux->clusters = NULL;
397 demux->common.time_scale = 1000000;
398 demux->common.created = G_MININT64;
400 demux->common.index_parsed = FALSE;
401 demux->tracks_parsed = FALSE;
402 demux->common.segmentinfo_parsed = FALSE;
403 demux->common.attachments_parsed = FALSE;
405 g_list_foreach (demux->common.tags_parsed,
406 (GFunc) gst_matroska_demux_free_parsed_el, NULL);
407 g_list_free (demux->common.tags_parsed);
408 demux->common.tags_parsed = NULL;
410 g_list_foreach (demux->seek_parsed,
411 (GFunc) gst_matroska_demux_free_parsed_el, NULL);
412 g_list_free (demux->seek_parsed);
413 demux->seek_parsed = NULL;
415 gst_segment_init (&demux->common.segment, GST_FORMAT_TIME);
416 demux->last_stop_end = GST_CLOCK_TIME_NONE;
417 demux->seek_block = 0;
419 demux->common.offset = 0;
420 demux->cluster_time = GST_CLOCK_TIME_NONE;
421 demux->cluster_offset = 0;
422 demux->next_cluster_offset = 0;
423 demux->index_offset = 0;
424 demux->seekable = FALSE;
425 demux->need_newsegment = FALSE;
426 demux->building_index = FALSE;
427 if (demux->seek_event) {
428 gst_event_unref (demux->seek_event);
429 demux->seek_event = NULL;
432 demux->seek_index = NULL;
433 demux->seek_entry = 0;
435 if (demux->close_segment) {
436 gst_event_unref (demux->close_segment);
437 demux->close_segment = NULL;
440 if (demux->new_segment) {
441 gst_event_unref (demux->new_segment);
442 demux->new_segment = NULL;
445 if (demux->common.element_index) {
446 gst_object_unref (demux->common.element_index);
447 demux->common.element_index = NULL;
449 demux->common.element_index_writer_id = -1;
451 if (demux->common.global_tags) {
452 gst_tag_list_free (demux->common.global_tags);
454 demux->common.global_tags = gst_tag_list_new ();
456 if (demux->common.cached_buffer) {
457 gst_buffer_unref (demux->common.cached_buffer);
458 demux->common.cached_buffer = NULL;
463 gst_matroska_decode_buffer (GstMatroskaTrackContext * context, GstBuffer * buf)
469 g_return_val_if_fail (GST_IS_BUFFER (buf), NULL);
471 GST_DEBUG ("decoding buffer %p", buf);
473 data = GST_BUFFER_DATA (buf);
474 size = GST_BUFFER_SIZE (buf);
476 g_return_val_if_fail (data != NULL && size > 0, buf);
478 if (gst_matroska_decode_data (context->encodings, &data, &size,
479 GST_MATROSKA_TRACK_ENCODING_SCOPE_FRAME, FALSE)) {
480 new_buf = gst_buffer_new ();
481 GST_BUFFER_MALLOCDATA (new_buf) = (guint8 *) data;
482 GST_BUFFER_DATA (new_buf) = (guint8 *) data;
483 GST_BUFFER_SIZE (new_buf) = size;
485 gst_buffer_unref (buf);
490 GST_DEBUG ("decode data failed");
491 gst_buffer_unref (buf);
497 gst_matroska_demux_add_stream (GstMatroskaDemux * demux, GstEbmlRead * ebml)
499 GstElementClass *klass = GST_ELEMENT_GET_CLASS (demux);
500 GstMatroskaTrackContext *context;
501 GstPadTemplate *templ = NULL;
502 GstCaps *caps = NULL;
503 gchar *padname = NULL;
505 guint32 id, riff_fourcc = 0;
506 guint16 riff_audio_fmt = 0;
507 GstTagList *list = NULL;
510 DEBUG_ELEMENT_START (demux, ebml, "TrackEntry");
512 /* start with the master */
513 if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
514 DEBUG_ELEMENT_STOP (demux, ebml, "TrackEntry", ret);
518 /* allocate generic... if we know the type, we'll g_renew()
519 * with the precise type */
520 context = g_new0 (GstMatroskaTrackContext, 1);
521 g_ptr_array_add (demux->common.src, context);
522 context->index = demux->common.num_streams;
523 context->index_writer_id = -1;
524 context->type = 0; /* no type yet */
525 context->default_duration = 0;
527 context->set_discont = TRUE;
528 context->timecodescale = 1.0;
530 GST_MATROSKA_TRACK_ENABLED | GST_MATROSKA_TRACK_DEFAULT |
531 GST_MATROSKA_TRACK_LACING;
532 context->last_flow = GST_FLOW_OK;
533 context->to_offset = G_MAXINT64;
534 demux->common.num_streams++;
535 g_assert (demux->common.src->len == demux->common.num_streams);
537 GST_DEBUG_OBJECT (demux, "Stream number %d", context->index);
539 /* try reading the trackentry headers */
540 while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
541 if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
545 /* track number (unique stream ID) */
546 case GST_MATROSKA_ID_TRACKNUMBER:{
549 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
553 GST_ERROR_OBJECT (demux, "Invalid TrackNumber 0");
554 ret = GST_FLOW_ERROR;
556 } else if (!gst_matroska_read_common_tracknumber_unique (&demux->common,
558 GST_ERROR_OBJECT (demux, "TrackNumber %" G_GUINT64_FORMAT
559 " is not unique", num);
560 ret = GST_FLOW_ERROR;
564 GST_DEBUG_OBJECT (demux, "TrackNumber: %" G_GUINT64_FORMAT, num);
568 /* track UID (unique identifier) */
569 case GST_MATROSKA_ID_TRACKUID:{
572 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
576 GST_ERROR_OBJECT (demux, "Invalid TrackUID 0");
577 ret = GST_FLOW_ERROR;
581 GST_DEBUG_OBJECT (demux, "TrackUID: %" G_GUINT64_FORMAT, num);
586 /* track type (video, audio, combined, subtitle, etc.) */
587 case GST_MATROSKA_ID_TRACKTYPE:{
590 if ((ret = gst_ebml_read_uint (ebml, &id, &track_type)) != GST_FLOW_OK) {
594 if (context->type != 0 && context->type != track_type) {
595 GST_WARNING_OBJECT (demux,
596 "More than one tracktype defined in a TrackEntry - skipping");
598 } else if (track_type < 1 || track_type > 254) {
599 GST_WARNING_OBJECT (demux, "Invalid TrackType %" G_GUINT64_FORMAT,
604 GST_DEBUG_OBJECT (demux, "TrackType: %" G_GUINT64_FORMAT, track_type);
606 /* ok, so we're actually going to reallocate this thing */
607 switch (track_type) {
608 case GST_MATROSKA_TRACK_TYPE_VIDEO:
609 gst_matroska_track_init_video_context (&context);
611 case GST_MATROSKA_TRACK_TYPE_AUDIO:
612 gst_matroska_track_init_audio_context (&context);
614 case GST_MATROSKA_TRACK_TYPE_SUBTITLE:
615 gst_matroska_track_init_subtitle_context (&context);
617 case GST_MATROSKA_TRACK_TYPE_COMPLEX:
618 case GST_MATROSKA_TRACK_TYPE_LOGO:
619 case GST_MATROSKA_TRACK_TYPE_BUTTONS:
620 case GST_MATROSKA_TRACK_TYPE_CONTROL:
622 GST_WARNING_OBJECT (demux,
623 "Unknown or unsupported TrackType %" G_GUINT64_FORMAT,
628 g_ptr_array_index (demux->common.src, demux->common.num_streams - 1)
633 /* tracktype specific stuff for video */
634 case GST_MATROSKA_ID_TRACKVIDEO:{
635 GstMatroskaTrackVideoContext *videocontext;
637 DEBUG_ELEMENT_START (demux, ebml, "TrackVideo");
639 if (!gst_matroska_track_init_video_context (&context)) {
640 GST_WARNING_OBJECT (demux,
641 "TrackVideo element in non-video track - ignoring track");
642 ret = GST_FLOW_ERROR;
644 } else if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
647 videocontext = (GstMatroskaTrackVideoContext *) context;
648 g_ptr_array_index (demux->common.src, demux->common.num_streams - 1)
651 while (ret == GST_FLOW_OK &&
652 gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
653 if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
657 /* Should be one level up but some broken muxers write it here. */
658 case GST_MATROSKA_ID_TRACKDEFAULTDURATION:{
661 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
665 GST_WARNING_OBJECT (demux, "Invalid TrackDefaultDuration 0");
669 GST_DEBUG_OBJECT (demux,
670 "TrackDefaultDuration: %" G_GUINT64_FORMAT, num);
671 context->default_duration = num;
675 /* video framerate */
676 /* NOTE: This one is here only for backward compatibility.
677 * Use _TRACKDEFAULDURATION one level up. */
678 case GST_MATROSKA_ID_VIDEOFRAMERATE:{
681 if ((ret = gst_ebml_read_float (ebml, &id, &num)) != GST_FLOW_OK)
685 GST_WARNING_OBJECT (demux, "Invalid TrackVideoFPS %lf", num);
689 GST_DEBUG_OBJECT (demux, "TrackVideoFrameRate: %lf", num);
690 if (context->default_duration == 0)
691 context->default_duration =
692 gst_gdouble_to_guint64 ((gdouble) GST_SECOND * (1.0 / num));
693 videocontext->default_fps = num;
697 /* width of the size to display the video at */
698 case GST_MATROSKA_ID_VIDEODISPLAYWIDTH:{
701 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
705 GST_WARNING_OBJECT (demux, "Invalid TrackVideoDisplayWidth 0");
709 GST_DEBUG_OBJECT (demux,
710 "TrackVideoDisplayWidth: %" G_GUINT64_FORMAT, num);
711 videocontext->display_width = num;
715 /* height of the size to display the video at */
716 case GST_MATROSKA_ID_VIDEODISPLAYHEIGHT:{
719 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
723 GST_WARNING_OBJECT (demux, "Invalid TrackVideoDisplayHeight 0");
727 GST_DEBUG_OBJECT (demux,
728 "TrackVideoDisplayHeight: %" G_GUINT64_FORMAT, num);
729 videocontext->display_height = num;
733 /* width of the video in the file */
734 case GST_MATROSKA_ID_VIDEOPIXELWIDTH:{
737 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
741 GST_WARNING_OBJECT (demux, "Invalid TrackVideoPixelWidth 0");
745 GST_DEBUG_OBJECT (demux,
746 "TrackVideoPixelWidth: %" G_GUINT64_FORMAT, num);
747 videocontext->pixel_width = num;
751 /* height of the video in the file */
752 case GST_MATROSKA_ID_VIDEOPIXELHEIGHT:{
755 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
759 GST_WARNING_OBJECT (demux, "Invalid TrackVideoPixelHeight 0");
763 GST_DEBUG_OBJECT (demux,
764 "TrackVideoPixelHeight: %" G_GUINT64_FORMAT, num);
765 videocontext->pixel_height = num;
769 /* whether the video is interlaced */
770 case GST_MATROSKA_ID_VIDEOFLAGINTERLACED:{
773 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
777 context->flags |= GST_MATROSKA_VIDEOTRACK_INTERLACED;
779 context->flags &= ~GST_MATROSKA_VIDEOTRACK_INTERLACED;
780 GST_DEBUG_OBJECT (demux, "TrackVideoInterlaced: %d",
781 (context->flags & GST_MATROSKA_VIDEOTRACK_INTERLACED) ? 1 :
786 /* aspect ratio behaviour */
787 case GST_MATROSKA_ID_VIDEOASPECTRATIOTYPE:{
790 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
793 if (num != GST_MATROSKA_ASPECT_RATIO_MODE_FREE &&
794 num != GST_MATROSKA_ASPECT_RATIO_MODE_KEEP &&
795 num != GST_MATROSKA_ASPECT_RATIO_MODE_FIXED) {
796 GST_WARNING_OBJECT (demux,
797 "Unknown TrackVideoAspectRatioType 0x%x", (guint) num);
800 GST_DEBUG_OBJECT (demux,
801 "TrackVideoAspectRatioType: %" G_GUINT64_FORMAT, num);
802 videocontext->asr_mode = num;
806 /* colourspace (only matters for raw video) fourcc */
807 case GST_MATROSKA_ID_VIDEOCOLOURSPACE:{
812 gst_ebml_read_binary (ebml, &id, &data,
813 &datalen)) != GST_FLOW_OK)
818 GST_WARNING_OBJECT (demux,
819 "Invalid TrackVideoColourSpace length %" G_GUINT64_FORMAT,
824 memcpy (&videocontext->fourcc, data, 4);
825 GST_DEBUG_OBJECT (demux,
826 "TrackVideoColourSpace: %" GST_FOURCC_FORMAT,
827 GST_FOURCC_ARGS (videocontext->fourcc));
833 GST_WARNING_OBJECT (demux,
834 "Unknown TrackVideo subelement 0x%x - ignoring", id);
836 case GST_MATROSKA_ID_VIDEOSTEREOMODE:
837 case GST_MATROSKA_ID_VIDEODISPLAYUNIT:
838 case GST_MATROSKA_ID_VIDEOPIXELCROPBOTTOM:
839 case GST_MATROSKA_ID_VIDEOPIXELCROPTOP:
840 case GST_MATROSKA_ID_VIDEOPIXELCROPLEFT:
841 case GST_MATROSKA_ID_VIDEOPIXELCROPRIGHT:
842 case GST_MATROSKA_ID_VIDEOGAMMAVALUE:
843 ret = gst_ebml_read_skip (ebml);
848 DEBUG_ELEMENT_STOP (demux, ebml, "TrackVideo", ret);
852 /* tracktype specific stuff for audio */
853 case GST_MATROSKA_ID_TRACKAUDIO:{
854 GstMatroskaTrackAudioContext *audiocontext;
856 DEBUG_ELEMENT_START (demux, ebml, "TrackAudio");
858 if (!gst_matroska_track_init_audio_context (&context)) {
859 GST_WARNING_OBJECT (demux,
860 "TrackAudio element in non-audio track - ignoring track");
861 ret = GST_FLOW_ERROR;
865 if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK)
868 audiocontext = (GstMatroskaTrackAudioContext *) context;
869 g_ptr_array_index (demux->common.src, demux->common.num_streams - 1)
872 while (ret == GST_FLOW_OK &&
873 gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
874 if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
879 case GST_MATROSKA_ID_AUDIOSAMPLINGFREQ:{
882 if ((ret = gst_ebml_read_float (ebml, &id, &num)) != GST_FLOW_OK)
887 GST_WARNING_OBJECT (demux,
888 "Invalid TrackAudioSamplingFrequency %lf", num);
892 GST_DEBUG_OBJECT (demux, "TrackAudioSamplingFrequency: %lf", num);
893 audiocontext->samplerate = num;
898 case GST_MATROSKA_ID_AUDIOBITDEPTH:{
901 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
905 GST_WARNING_OBJECT (demux, "Invalid TrackAudioBitDepth 0");
909 GST_DEBUG_OBJECT (demux, "TrackAudioBitDepth: %" G_GUINT64_FORMAT,
911 audiocontext->bitdepth = num;
916 case GST_MATROSKA_ID_AUDIOCHANNELS:{
919 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
923 GST_WARNING_OBJECT (demux, "Invalid TrackAudioChannels 0");
927 GST_DEBUG_OBJECT (demux, "TrackAudioChannels: %" G_GUINT64_FORMAT,
929 audiocontext->channels = num;
934 GST_WARNING_OBJECT (demux,
935 "Unknown TrackAudio subelement 0x%x - ignoring", id);
937 case GST_MATROSKA_ID_AUDIOCHANNELPOSITIONS:
938 case GST_MATROSKA_ID_AUDIOOUTPUTSAMPLINGFREQ:
939 ret = gst_ebml_read_skip (ebml);
944 DEBUG_ELEMENT_STOP (demux, ebml, "TrackAudio", ret);
949 /* codec identifier */
950 case GST_MATROSKA_ID_CODECID:{
953 if ((ret = gst_ebml_read_ascii (ebml, &id, &text)) != GST_FLOW_OK)
956 GST_DEBUG_OBJECT (demux, "CodecID: %s", GST_STR_NULL (text));
957 context->codec_id = text;
961 /* codec private data */
962 case GST_MATROSKA_ID_CODECPRIVATE:{
967 gst_ebml_read_binary (ebml, &id, &data, &size)) != GST_FLOW_OK)
970 context->codec_priv = data;
971 context->codec_priv_size = size;
973 GST_DEBUG_OBJECT (demux, "CodecPrivate of size %" G_GUINT64_FORMAT,
978 /* name of the codec */
979 case GST_MATROSKA_ID_CODECNAME:{
982 if ((ret = gst_ebml_read_utf8 (ebml, &id, &text)) != GST_FLOW_OK)
985 GST_DEBUG_OBJECT (demux, "CodecName: %s", GST_STR_NULL (text));
986 context->codec_name = text;
990 /* name of this track */
991 case GST_MATROSKA_ID_TRACKNAME:{
994 if ((ret = gst_ebml_read_utf8 (ebml, &id, &text)) != GST_FLOW_OK)
997 context->name = text;
998 GST_DEBUG_OBJECT (demux, "TrackName: %s", GST_STR_NULL (text));
1002 /* language (matters for audio/subtitles, mostly) */
1003 case GST_MATROSKA_ID_TRACKLANGUAGE:{
1006 if ((ret = gst_ebml_read_utf8 (ebml, &id, &text)) != GST_FLOW_OK)
1010 context->language = text;
1013 if (strlen (context->language) >= 4 && context->language[3] == '-')
1014 context->language[3] = '\0';
1016 GST_DEBUG_OBJECT (demux, "TrackLanguage: %s",
1017 GST_STR_NULL (context->language));
1021 /* whether this is actually used */
1022 case GST_MATROSKA_ID_TRACKFLAGENABLED:{
1025 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1029 context->flags |= GST_MATROSKA_TRACK_ENABLED;
1031 context->flags &= ~GST_MATROSKA_TRACK_ENABLED;
1033 GST_DEBUG_OBJECT (demux, "TrackEnabled: %d",
1034 (context->flags & GST_MATROSKA_TRACK_ENABLED) ? 1 : 0);
1038 /* whether it's the default for this track type */
1039 case GST_MATROSKA_ID_TRACKFLAGDEFAULT:{
1042 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1046 context->flags |= GST_MATROSKA_TRACK_DEFAULT;
1048 context->flags &= ~GST_MATROSKA_TRACK_DEFAULT;
1050 GST_DEBUG_OBJECT (demux, "TrackDefault: %d",
1051 (context->flags & GST_MATROSKA_TRACK_ENABLED) ? 1 : 0);
1055 /* whether the track must be used during playback */
1056 case GST_MATROSKA_ID_TRACKFLAGFORCED:{
1059 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1063 context->flags |= GST_MATROSKA_TRACK_FORCED;
1065 context->flags &= ~GST_MATROSKA_TRACK_FORCED;
1067 GST_DEBUG_OBJECT (demux, "TrackForced: %d",
1068 (context->flags & GST_MATROSKA_TRACK_ENABLED) ? 1 : 0);
1072 /* lacing (like MPEG, where blocks don't end/start on frame
1074 case GST_MATROSKA_ID_TRACKFLAGLACING:{
1077 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1081 context->flags |= GST_MATROSKA_TRACK_LACING;
1083 context->flags &= ~GST_MATROSKA_TRACK_LACING;
1085 GST_DEBUG_OBJECT (demux, "TrackLacing: %d",
1086 (context->flags & GST_MATROSKA_TRACK_ENABLED) ? 1 : 0);
1090 /* default length (in time) of one data block in this track */
1091 case GST_MATROSKA_ID_TRACKDEFAULTDURATION:{
1094 if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1099 GST_WARNING_OBJECT (demux, "Invalid TrackDefaultDuration 0");
1103 GST_DEBUG_OBJECT (demux, "TrackDefaultDuration: %" G_GUINT64_FORMAT,
1105 context->default_duration = num;
1109 case GST_MATROSKA_ID_CONTENTENCODINGS:{
1110 ret = gst_matroska_read_common_read_track_encodings (&demux->common,
1115 case GST_MATROSKA_ID_TRACKTIMECODESCALE:{
1118 if ((ret = gst_ebml_read_float (ebml, &id, &num)) != GST_FLOW_OK)
1122 GST_WARNING_OBJECT (demux, "Invalid TrackTimeCodeScale %lf", num);
1126 GST_DEBUG_OBJECT (demux, "TrackTimeCodeScale: %lf", num);
1127 context->timecodescale = num;
1132 GST_WARNING ("Unknown TrackEntry subelement 0x%x - ignoring", id);
1135 /* we ignore these because they're nothing useful (i.e. crap)
1136 * or simply not implemented yet. */
1137 case GST_MATROSKA_ID_TRACKMINCACHE:
1138 case GST_MATROSKA_ID_TRACKMAXCACHE:
1139 case GST_MATROSKA_ID_MAXBLOCKADDITIONID:
1140 case GST_MATROSKA_ID_TRACKATTACHMENTLINK:
1141 case GST_MATROSKA_ID_TRACKOVERLAY:
1142 case GST_MATROSKA_ID_TRACKTRANSLATE:
1143 case GST_MATROSKA_ID_TRACKOFFSET:
1144 case GST_MATROSKA_ID_CODECSETTINGS:
1145 case GST_MATROSKA_ID_CODECINFOURL:
1146 case GST_MATROSKA_ID_CODECDOWNLOADURL:
1147 case GST_MATROSKA_ID_CODECDECODEALL:
1148 ret = gst_ebml_read_skip (ebml);
1153 DEBUG_ELEMENT_STOP (demux, ebml, "TrackEntry", ret);
1155 /* Decode codec private data if necessary */
1156 if (context->encodings && context->encodings->len > 0 && context->codec_priv
1157 && context->codec_priv_size > 0) {
1158 if (!gst_matroska_decode_data (context->encodings,
1159 &context->codec_priv, &context->codec_priv_size,
1160 GST_MATROSKA_TRACK_ENCODING_SCOPE_CODEC_DATA, TRUE)) {
1161 GST_WARNING_OBJECT (demux, "Decoding codec private data failed");
1162 ret = GST_FLOW_ERROR;
1166 if (context->type == 0 || context->codec_id == NULL || (ret != GST_FLOW_OK
1167 && ret != GST_FLOW_UNEXPECTED)) {
1168 if (ret == GST_FLOW_OK || ret == GST_FLOW_UNEXPECTED)
1169 GST_WARNING_OBJECT (ebml, "Unknown stream/codec in track entry header");
1171 demux->common.num_streams--;
1172 g_ptr_array_remove_index (demux->common.src, demux->common.num_streams);
1173 g_assert (demux->common.src->len == demux->common.num_streams);
1175 gst_matroska_track_free (context);
1181 /* now create the GStreamer connectivity */
1182 switch (context->type) {
1183 case GST_MATROSKA_TRACK_TYPE_VIDEO:{
1184 GstMatroskaTrackVideoContext *videocontext =
1185 (GstMatroskaTrackVideoContext *) context;
1187 padname = g_strdup_printf ("video_%02d", demux->num_v_streams++);
1188 templ = gst_element_class_get_pad_template (klass, "video_%02d");
1189 caps = gst_matroska_demux_video_caps (videocontext,
1190 context->codec_id, (guint8 *) context->codec_priv,
1191 context->codec_priv_size, &codec, &riff_fourcc);
1194 list = gst_tag_list_new ();
1195 gst_tag_list_add (list, GST_TAG_MERGE_REPLACE,
1196 GST_TAG_VIDEO_CODEC, codec, NULL);
1202 case GST_MATROSKA_TRACK_TYPE_AUDIO:{
1203 GstMatroskaTrackAudioContext *audiocontext =
1204 (GstMatroskaTrackAudioContext *) context;
1206 padname = g_strdup_printf ("audio_%02d", demux->num_a_streams++);
1207 templ = gst_element_class_get_pad_template (klass, "audio_%02d");
1208 caps = gst_matroska_demux_audio_caps (audiocontext,
1209 context->codec_id, context->codec_priv, context->codec_priv_size,
1210 &codec, &riff_audio_fmt);
1213 list = gst_tag_list_new ();
1214 gst_tag_list_add (list, GST_TAG_MERGE_REPLACE,
1215 GST_TAG_AUDIO_CODEC, codec, NULL);
1221 case GST_MATROSKA_TRACK_TYPE_SUBTITLE:{
1222 GstMatroskaTrackSubtitleContext *subtitlecontext =
1223 (GstMatroskaTrackSubtitleContext *) context;
1225 padname = g_strdup_printf ("subtitle_%02d", demux->num_t_streams++);
1226 templ = gst_element_class_get_pad_template (klass, "subtitle_%02d");
1227 caps = gst_matroska_demux_subtitle_caps (subtitlecontext,
1228 context->codec_id, context->codec_priv, context->codec_priv_size);
1232 case GST_MATROSKA_TRACK_TYPE_COMPLEX:
1233 case GST_MATROSKA_TRACK_TYPE_LOGO:
1234 case GST_MATROSKA_TRACK_TYPE_BUTTONS:
1235 case GST_MATROSKA_TRACK_TYPE_CONTROL:
1237 /* we should already have quit by now */
1238 g_assert_not_reached ();
1241 if ((context->language == NULL || *context->language == '\0') &&
1242 (context->type == GST_MATROSKA_TRACK_TYPE_AUDIO ||
1243 context->type == GST_MATROSKA_TRACK_TYPE_SUBTITLE)) {
1244 GST_LOG ("stream %d: language=eng (assuming default)", context->index);
1245 context->language = g_strdup ("eng");
1248 if (context->language) {
1252 list = gst_tag_list_new ();
1254 /* Matroska contains ISO 639-2B codes, we want ISO 639-1 */
1255 lang = gst_tag_get_language_code (context->language);
1256 gst_tag_list_add (list, GST_TAG_MERGE_REPLACE,
1257 GST_TAG_LANGUAGE_CODE, (lang) ? lang : context->language, NULL);
1261 GST_WARNING_OBJECT (demux, "could not determine caps for stream with "
1262 "codec_id='%s'", context->codec_id);
1263 switch (context->type) {
1264 case GST_MATROSKA_TRACK_TYPE_VIDEO:
1265 caps = gst_caps_new_simple ("video/x-unknown", NULL);
1267 case GST_MATROSKA_TRACK_TYPE_AUDIO:
1268 caps = gst_caps_new_simple ("audio/x-unknown", NULL);
1270 case GST_MATROSKA_TRACK_TYPE_SUBTITLE:
1271 caps = gst_caps_new_simple ("application/x-subtitle-unknown", NULL);
1273 case GST_MATROSKA_TRACK_TYPE_COMPLEX:
1275 caps = gst_caps_new_simple ("application/x-matroska-unknown", NULL);
1278 gst_caps_set_simple (caps, "codec-id", G_TYPE_STRING, context->codec_id,
1281 /* add any unrecognised riff fourcc / audio format, but after codec-id */
1282 if (context->type == GST_MATROSKA_TRACK_TYPE_AUDIO && riff_audio_fmt != 0)
1283 gst_caps_set_simple (caps, "format", G_TYPE_INT, riff_audio_fmt, NULL);
1284 else if (context->type == GST_MATROSKA_TRACK_TYPE_VIDEO && riff_fourcc != 0)
1285 gst_caps_set_simple (caps, "fourcc", GST_TYPE_FOURCC, riff_fourcc, NULL);
1288 /* the pad in here */
1289 context->pad = gst_pad_new_from_template (templ, padname);
1290 context->caps = caps;
1292 gst_pad_set_event_function (context->pad,
1293 GST_DEBUG_FUNCPTR (gst_matroska_demux_handle_src_event));
1294 gst_pad_set_query_type_function (context->pad,
1295 GST_DEBUG_FUNCPTR (gst_matroska_demux_get_src_query_types));
1296 gst_pad_set_query_function (context->pad,
1297 GST_DEBUG_FUNCPTR (gst_matroska_demux_handle_src_query));
1299 GST_INFO_OBJECT (demux, "Adding pad '%s' with caps %" GST_PTR_FORMAT,
1302 context->pending_tags = list;
1304 gst_pad_set_element_private (context->pad, context);
1306 gst_pad_use_fixed_caps (context->pad);
1307 gst_pad_set_caps (context->pad, context->caps);
1308 gst_pad_set_active (context->pad, TRUE);
1309 gst_element_add_pad (GST_ELEMENT (demux), context->pad);
1317 static const GstQueryType *
1318 gst_matroska_demux_get_src_query_types (GstPad * pad)
1320 static const GstQueryType query_types[] = {
1331 gst_matroska_demux_query (GstMatroskaDemux * demux, GstPad * pad,
1334 gboolean res = FALSE;
1335 GstMatroskaTrackContext *context = NULL;
1338 context = gst_pad_get_element_private (pad);
1341 switch (GST_QUERY_TYPE (query)) {
1342 case GST_QUERY_POSITION:
1346 gst_query_parse_position (query, &format, NULL);
1348 if (format == GST_FORMAT_TIME) {
1349 GST_OBJECT_LOCK (demux);
1351 gst_query_set_position (query, GST_FORMAT_TIME, context->pos);
1353 gst_query_set_position (query, GST_FORMAT_TIME,
1354 demux->common.segment.last_stop);
1355 GST_OBJECT_UNLOCK (demux);
1356 } else if (format == GST_FORMAT_DEFAULT && context
1357 && context->default_duration) {
1358 GST_OBJECT_LOCK (demux);
1359 gst_query_set_position (query, GST_FORMAT_DEFAULT,
1360 context->pos / context->default_duration);
1361 GST_OBJECT_UNLOCK (demux);
1363 GST_DEBUG_OBJECT (demux,
1364 "only position query in TIME and DEFAULT format is supported");
1370 case GST_QUERY_DURATION:
1374 gst_query_parse_duration (query, &format, NULL);
1376 if (format == GST_FORMAT_TIME) {
1377 GST_OBJECT_LOCK (demux);
1378 gst_query_set_duration (query, GST_FORMAT_TIME,
1379 demux->common.segment.duration);
1380 GST_OBJECT_UNLOCK (demux);
1381 } else if (format == GST_FORMAT_DEFAULT && context
1382 && context->default_duration) {
1383 GST_OBJECT_LOCK (demux);
1384 gst_query_set_duration (query, GST_FORMAT_DEFAULT,
1385 demux->common.segment.duration / context->default_duration);
1386 GST_OBJECT_UNLOCK (demux);
1388 GST_DEBUG_OBJECT (demux,
1389 "only duration query in TIME and DEFAULT format is supported");
1396 case GST_QUERY_SEEKING:
1400 gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
1401 GST_OBJECT_LOCK (demux);
1402 if (fmt == GST_FORMAT_TIME) {
1405 if (demux->streaming) {
1406 /* assuming we'll be able to get an index ... */
1407 seekable = demux->seekable;
1412 gst_query_set_seeking (query, GST_FORMAT_TIME, seekable,
1413 0, demux->common.segment.duration);
1416 GST_OBJECT_UNLOCK (demux);
1420 res = gst_pad_query_default (pad, query);
1428 gst_matroska_demux_element_query (GstElement * element, GstQuery * query)
1430 return gst_matroska_demux_query (GST_MATROSKA_DEMUX (element), NULL, query);
1434 gst_matroska_demux_handle_src_query (GstPad * pad, GstQuery * query)
1437 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (gst_pad_get_parent (pad));
1439 ret = gst_matroska_demux_query (demux, pad, query);
1441 gst_object_unref (demux);
1446 /* returns FALSE if there are no pads to deliver event to,
1447 * otherwise TRUE (whatever the outcome of event sending),
1448 * takes ownership of the passed event! */
1450 gst_matroska_demux_send_event (GstMatroskaDemux * demux, GstEvent * event)
1452 gboolean is_newsegment;
1453 gboolean ret = FALSE;
1456 g_return_val_if_fail (event != NULL, FALSE);
1458 GST_DEBUG_OBJECT (demux, "Sending event of type %s to all source pads",
1459 GST_EVENT_TYPE_NAME (event));
1461 is_newsegment = (GST_EVENT_TYPE (event) == GST_EVENT_NEWSEGMENT);
1463 g_assert (demux->common.src->len == demux->common.num_streams);
1464 for (i = 0; i < demux->common.src->len; i++) {
1465 GstMatroskaTrackContext *stream;
1467 stream = g_ptr_array_index (demux->common.src, i);
1468 gst_event_ref (event);
1469 gst_pad_push_event (stream->pad, event);
1472 /* FIXME: send global tags before stream tags */
1473 if (G_UNLIKELY (is_newsegment && stream->pending_tags != NULL)) {
1474 GST_DEBUG_OBJECT (demux, "Sending pending_tags %p for pad %s:%s : %"
1475 GST_PTR_FORMAT, stream->pending_tags,
1476 GST_DEBUG_PAD_NAME (stream->pad), stream->pending_tags);
1477 gst_element_found_tags_for_pad (GST_ELEMENT (demux), stream->pad,
1478 stream->pending_tags);
1479 stream->pending_tags = NULL;
1483 if (G_UNLIKELY (is_newsegment && demux->common.global_tags != NULL)) {
1484 gst_tag_list_add (demux->common.global_tags, GST_TAG_MERGE_REPLACE,
1485 GST_TAG_CONTAINER_FORMAT, "Matroska", NULL);
1486 GST_DEBUG_OBJECT (demux, "Sending global_tags %p : %" GST_PTR_FORMAT,
1487 demux->common.global_tags, demux->common.global_tags);
1488 gst_element_found_tags (GST_ELEMENT (demux), demux->common.global_tags);
1489 demux->common.global_tags = NULL;
1492 gst_event_unref (event);
1497 gst_matroska_demux_element_send_event (GstElement * element, GstEvent * event)
1499 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (element);
1502 g_return_val_if_fail (event != NULL, FALSE);
1504 if (GST_EVENT_TYPE (event) == GST_EVENT_SEEK) {
1505 res = gst_matroska_demux_handle_seek_event (demux, NULL, event);
1507 GST_WARNING_OBJECT (demux, "Unhandled event of type %s",
1508 GST_EVENT_TYPE_NAME (event));
1511 gst_event_unref (event);
1516 gst_matroska_demux_move_to_entry (GstMatroskaDemux * demux,
1517 GstMatroskaIndex * entry, gboolean reset)
1521 GST_OBJECT_LOCK (demux);
1523 /* seek (relative to matroska segment) */
1524 /* position might be invalid; will error when streaming resumes ... */
1525 demux->common.offset = entry->pos + demux->common.ebml_segment_start;
1527 GST_DEBUG_OBJECT (demux, "Seeked to offset %" G_GUINT64_FORMAT ", block %d, "
1528 "time %" GST_TIME_FORMAT, entry->pos + demux->common.ebml_segment_start,
1529 entry->block, GST_TIME_ARGS (entry->time));
1531 /* update the time */
1532 gst_matroska_read_common_reset_streams (&demux->common, entry->time, TRUE);
1533 demux->common.segment.last_stop = entry->time;
1534 demux->seek_block = entry->block;
1535 demux->seek_first = TRUE;
1536 demux->last_stop_end = GST_CLOCK_TIME_NONE;
1538 for (i = 0; i < demux->common.src->len; i++) {
1539 GstMatroskaTrackContext *stream = g_ptr_array_index (demux->common.src, i);
1542 stream->to_offset = G_MAXINT64;
1544 if (stream->from_offset != -1)
1545 stream->to_offset = stream->from_offset;
1547 stream->from_offset = -1;
1550 GST_OBJECT_UNLOCK (demux);
1556 gst_matroska_cluster_compare (gint64 * i1, gint64 * i2)
1566 /* searches for a cluster start from @pos,
1567 * return GST_FLOW_OK and cluster position in @pos if found */
1568 static GstFlowReturn
1569 gst_matroska_demux_search_cluster (GstMatroskaDemux * demux, gint64 * pos)
1571 gint64 newpos = *pos;
1573 GstFlowReturn ret = GST_FLOW_OK;
1574 const guint chunk = 64 * 1024;
1575 GstBuffer *buf = NULL;
1580 orig_offset = demux->common.offset;
1582 GST_LOG_OBJECT (demux, "searching cluster following offset %" G_GINT64_FORMAT,
1585 if (demux->clusters) {
1588 cpos = gst_util_array_binary_search (demux->clusters->data,
1589 demux->clusters->len, sizeof (gint64),
1590 (GCompareDataFunc) gst_matroska_cluster_compare,
1591 GST_SEARCH_MODE_AFTER, pos, NULL);
1594 GST_DEBUG_OBJECT (demux,
1595 "cluster reported at offset %" G_GINT64_FORMAT, *cpos);
1596 demux->common.offset = *cpos;
1597 ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
1598 GST_ELEMENT_CAST (demux), &id, &length, &needed);
1599 if (ret == GST_FLOW_OK && id == GST_MATROSKA_ID_CLUSTER) {
1606 /* read in at newpos and scan for ebml cluster id */
1608 GstByteReader reader;
1612 gst_buffer_unref (buf);
1615 ret = gst_pad_pull_range (demux->common.sinkpad, newpos, chunk, &buf);
1616 if (ret != GST_FLOW_OK)
1618 GST_DEBUG_OBJECT (demux, "read buffer size %d at offset %" G_GINT64_FORMAT,
1619 GST_BUFFER_SIZE (buf), newpos);
1620 gst_byte_reader_init_from_buffer (&reader, buf);
1622 cluster_pos = gst_byte_reader_masked_scan_uint32 (&reader, 0xffffffff,
1623 GST_MATROSKA_ID_CLUSTER, 0, gst_byte_reader_get_remaining (&reader));
1624 if (cluster_pos >= 0) {
1625 newpos += cluster_pos;
1626 /* prepare resuming at next byte */
1627 gst_byte_reader_skip (&reader, cluster_pos + 1);
1628 GST_DEBUG_OBJECT (demux,
1629 "found cluster ebml id at offset %" G_GINT64_FORMAT, newpos);
1630 /* extra checks whether we really sync'ed to a cluster:
1631 * - either it is the first and only cluster
1632 * - either there is a cluster after this one
1633 * - either cluster length is undefined
1635 /* ok if first cluster (there may not a subsequent one) */
1636 if (newpos == demux->first_cluster_offset) {
1637 GST_DEBUG_OBJECT (demux, "cluster is first cluster -> OK");
1640 demux->common.offset = newpos;
1641 ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
1642 GST_ELEMENT_CAST (demux), &id, &length, &needed);
1643 if (ret != GST_FLOW_OK) {
1644 GST_DEBUG_OBJECT (demux, "need more data -> continue");
1647 g_assert (id == GST_MATROSKA_ID_CLUSTER);
1648 GST_DEBUG_OBJECT (demux, "cluster size %" G_GUINT64_FORMAT ", prefix %d",
1650 /* ok if undefined length or first cluster */
1651 if (length == GST_EBML_SIZE_UNKNOWN || length == G_MAXUINT64) {
1652 GST_DEBUG_OBJECT (demux, "cluster has undefined length -> OK");
1656 demux->common.offset += length + needed;
1657 ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
1658 GST_ELEMENT_CAST (demux), &id, &length, &needed);
1659 if (ret != GST_FLOW_OK)
1661 GST_DEBUG_OBJECT (demux, "next element is %scluster",
1662 id == GST_MATROSKA_ID_CLUSTER ? "" : "not ");
1663 if (id == GST_MATROSKA_ID_CLUSTER)
1665 /* not ok, resume */
1668 /* partial cluster id may have been in tail of buffer */
1669 newpos += MAX (gst_byte_reader_get_remaining (&reader), 4) - 3;
1674 gst_buffer_unref (buf);
1679 demux->common.offset = orig_offset;
1684 /* bisect and scan through file for cluster starting before @time,
1685 * returns fake index entry with corresponding info on cluster */
1686 static GstMatroskaIndex *
1687 gst_matroska_demux_search_pos (GstMatroskaDemux * demux, GstClockTime time)
1689 GstMatroskaIndex *entry = NULL;
1690 GstMatroskaReadState current_state;
1691 GstClockTime otime, prev_cluster_time, current_cluster_time, cluster_time;
1692 gint64 opos, newpos, startpos = 0, current_offset;
1693 gint64 prev_cluster_offset = -1, current_cluster_offset, cluster_offset;
1694 const guint chunk = 64 * 1024;
1695 GstBuffer *buf = NULL;
1701 /* (under)estimate new position, resync using cluster ebml id,
1702 * and scan forward to appropriate cluster
1703 * (and re-estimate if need to go backward) */
1705 prev_cluster_time = GST_CLOCK_TIME_NONE;
1707 /* store some current state */
1708 current_state = demux->common.state;
1709 g_return_val_if_fail (current_state == GST_MATROSKA_READ_STATE_DATA, NULL);
1711 current_cluster_offset = demux->cluster_offset;
1712 current_cluster_time = demux->cluster_time;
1713 current_offset = demux->common.offset;
1715 demux->common.state = GST_MATROSKA_READ_STATE_SCANNING;
1717 /* estimate using start and current position */
1718 GST_OBJECT_LOCK (demux);
1719 opos = demux->common.offset - demux->common.ebml_segment_start;
1720 otime = demux->common.segment.last_stop;
1721 GST_OBJECT_UNLOCK (demux);
1723 /* avoid division by zero in first estimation below */
1728 GST_LOG_OBJECT (demux,
1729 "opos: %" G_GUINT64_FORMAT ", otime: %" GST_TIME_FORMAT, opos,
1730 GST_TIME_ARGS (otime));
1731 newpos = gst_util_uint64_scale (opos, time, otime) - chunk;
1734 /* favour undershoot */
1735 newpos = newpos * 90 / 100;
1736 newpos += demux->common.ebml_segment_start;
1738 GST_DEBUG_OBJECT (demux,
1739 "estimated offset for %" GST_TIME_FORMAT ": %" G_GINT64_FORMAT,
1740 GST_TIME_ARGS (time), newpos);
1742 /* and at least start scanning before previous scan start to avoid looping */
1743 startpos = startpos * 90 / 100;
1744 if (startpos && startpos < newpos)
1747 /* read in at newpos and scan for ebml cluster id */
1751 ret = gst_matroska_demux_search_cluster (demux, &newpos);
1752 if (ret == GST_FLOW_UNEXPECTED) {
1753 /* heuristic HACK */
1754 newpos = startpos * 80 / 100;
1755 GST_DEBUG_OBJECT (demux, "EOS; "
1756 "new estimated offset for %" GST_TIME_FORMAT ": %" G_GINT64_FORMAT,
1757 GST_TIME_ARGS (time), newpos);
1760 } else if (ret != GST_FLOW_OK) {
1767 /* then start scanning and parsing for cluster time,
1768 * re-estimate if overshoot, otherwise next cluster and so on */
1769 demux->common.offset = newpos;
1770 demux->cluster_time = cluster_time = GST_CLOCK_TIME_NONE;
1772 guint64 cluster_size = 0;
1774 /* peek and parse some elements */
1775 ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
1776 GST_ELEMENT_CAST (demux), &id, &length, &needed);
1777 if (ret != GST_FLOW_OK)
1779 GST_LOG_OBJECT (demux, "Offset %" G_GUINT64_FORMAT ", Element id 0x%x, "
1780 "size %" G_GUINT64_FORMAT ", needed %d", demux->common.offset, id,
1782 ret = gst_matroska_demux_parse_id (demux, id, length, needed);
1783 if (ret != GST_FLOW_OK)
1786 if (id == GST_MATROSKA_ID_CLUSTER) {
1787 cluster_time = GST_CLOCK_TIME_NONE;
1788 if (length == G_MAXUINT64)
1791 cluster_size = length + needed;
1793 if (demux->cluster_time != GST_CLOCK_TIME_NONE &&
1794 cluster_time == GST_CLOCK_TIME_NONE) {
1795 cluster_time = demux->cluster_time * demux->common.time_scale;
1796 cluster_offset = demux->cluster_offset;
1797 GST_DEBUG_OBJECT (demux, "found cluster at offset %" G_GINT64_FORMAT
1798 " with time %" GST_TIME_FORMAT, cluster_offset,
1799 GST_TIME_ARGS (cluster_time));
1800 if (cluster_time > time) {
1801 GST_DEBUG_OBJECT (demux, "overshot target");
1802 /* cluster overshoots */
1803 if (cluster_offset == demux->first_cluster_offset) {
1804 /* but no prev one */
1805 GST_DEBUG_OBJECT (demux, "but using first cluster anyway");
1806 prev_cluster_time = cluster_time;
1807 prev_cluster_offset = cluster_offset;
1810 if (prev_cluster_time != GST_CLOCK_TIME_NONE) {
1811 /* prev cluster did not overshoot, so prev cluster is target */
1814 /* re-estimate using this new position info */
1815 opos = cluster_offset;
1816 otime = cluster_time;
1820 /* cluster undershoots, goto next one */
1821 prev_cluster_time = cluster_time;
1822 prev_cluster_offset = cluster_offset;
1823 /* skip cluster if length is defined,
1824 * otherwise will be skippingly parsed into */
1826 GST_DEBUG_OBJECT (demux, "skipping to next cluster");
1827 demux->common.offset = cluster_offset + cluster_size;
1828 demux->cluster_time = GST_CLOCK_TIME_NONE;
1830 GST_DEBUG_OBJECT (demux, "parsing/skipping cluster elements");
1837 if (ret == GST_FLOW_UNEXPECTED) {
1838 if (prev_cluster_time != GST_CLOCK_TIME_NONE)
1844 entry = g_new0 (GstMatroskaIndex, 1);
1845 entry->time = prev_cluster_time;
1846 entry->pos = prev_cluster_offset - demux->common.ebml_segment_start;
1847 GST_DEBUG_OBJECT (demux, "simulated index entry; time %" GST_TIME_FORMAT
1848 ", pos %" G_GUINT64_FORMAT, GST_TIME_ARGS (entry->time), entry->pos);
1852 gst_buffer_unref (buf);
1854 /* restore some state */
1855 demux->cluster_offset = current_cluster_offset;
1856 demux->cluster_time = current_cluster_time;
1857 demux->common.offset = current_offset;
1858 demux->common.state = current_state;
1864 gst_matroska_demux_handle_seek_event (GstMatroskaDemux * demux,
1865 GstPad * pad, GstEvent * event)
1867 GstMatroskaIndex *entry = NULL;
1868 GstMatroskaIndex scan_entry;
1870 GstSeekType cur_type, stop_type;
1872 gboolean flush, keyunit;
1875 GstMatroskaTrackContext *track = NULL;
1876 GstSegment seeksegment = { 0, };
1880 track = gst_pad_get_element_private (pad);
1882 gst_event_parse_seek (event, &rate, &format, &flags, &cur_type, &cur,
1885 /* we can only seek on time */
1886 if (format != GST_FORMAT_TIME) {
1887 GST_DEBUG_OBJECT (demux, "Can only seek on TIME");
1891 /* copy segment, we need this because we still need the old
1892 * segment when we close the current segment. */
1893 memcpy (&seeksegment, &demux->common.segment, sizeof (GstSegment));
1896 GST_DEBUG_OBJECT (demux, "configuring seek");
1897 gst_segment_set_seek (&seeksegment, rate, format, flags,
1898 cur_type, cur, stop_type, stop, &update);
1901 GST_DEBUG_OBJECT (demux, "New segment %" GST_SEGMENT_FORMAT, &seeksegment);
1903 /* check sanity before we start flushing and all that */
1904 GST_OBJECT_LOCK (demux);
1905 track = gst_matroska_read_common_get_seek_track (&demux->common, track);
1906 if ((entry = gst_matroska_read_common_do_index_seek (&demux->common, track,
1907 seeksegment.last_stop, &demux->seek_index, &demux->seek_entry)) ==
1909 /* pull mode without index can scan later on */
1910 if (demux->common.index || demux->streaming) {
1911 GST_DEBUG_OBJECT (demux, "No matching seek entry in index");
1912 GST_OBJECT_UNLOCK (demux);
1916 GST_DEBUG_OBJECT (demux, "Seek position looks sane");
1917 GST_OBJECT_UNLOCK (demux);
1919 if (demux->streaming) {
1920 /* need to seek to cluster start to pick up cluster time */
1921 /* upstream takes care of flushing and all that
1922 * ... and newsegment event handling takes care of the rest */
1923 return perform_seek_to_offset (demux,
1924 entry->pos + demux->common.ebml_segment_start);
1927 flush = !!(flags & GST_SEEK_FLAG_FLUSH);
1928 keyunit = !!(flags & GST_SEEK_FLAG_KEY_UNIT);
1931 GST_DEBUG_OBJECT (demux, "Starting flush");
1932 gst_pad_push_event (demux->common.sinkpad, gst_event_new_flush_start ());
1933 gst_matroska_demux_send_event (demux, gst_event_new_flush_start ());
1935 GST_DEBUG_OBJECT (demux, "Non-flushing seek, pausing task");
1936 gst_pad_pause_task (demux->common.sinkpad);
1939 /* now grab the stream lock so that streaming cannot continue, for
1940 * non flushing seeks when the element is in PAUSED this could block
1942 GST_DEBUG_OBJECT (demux, "Waiting for streaming to stop");
1943 GST_PAD_STREAM_LOCK (demux->common.sinkpad);
1945 /* pull mode without index can do some scanning */
1946 if (!demux->streaming && !demux->common.index) {
1947 /* need to stop flushing upstream as we need it next */
1949 gst_pad_push_event (demux->common.sinkpad, gst_event_new_flush_stop ());
1950 entry = gst_matroska_demux_search_pos (demux, seeksegment.last_stop);
1951 /* keep local copy */
1953 scan_entry = *entry;
1955 entry = &scan_entry;
1957 GST_DEBUG_OBJECT (demux, "Scan failed to find matching position");
1959 gst_matroska_demux_send_event (demux, gst_event_new_flush_stop ());
1965 GST_DEBUG_OBJECT (demux, "seek to key unit, adjusting segment start to %"
1966 GST_TIME_FORMAT, GST_TIME_ARGS (entry->time));
1967 seeksegment.start = entry->time;
1968 seeksegment.last_stop = entry->time;
1969 seeksegment.time = entry->time;
1973 GST_DEBUG_OBJECT (demux, "Stopping flush");
1974 gst_pad_push_event (demux->common.sinkpad, gst_event_new_flush_stop ());
1975 gst_matroska_demux_send_event (demux, gst_event_new_flush_stop ());
1976 } else if (demux->segment_running) {
1977 GST_DEBUG_OBJECT (demux, "Closing currently running segment");
1979 GST_OBJECT_LOCK (demux);
1980 if (demux->close_segment)
1981 gst_event_unref (demux->close_segment);
1983 demux->close_segment = gst_event_new_new_segment (TRUE,
1984 demux->common.segment.rate, GST_FORMAT_TIME,
1985 demux->common.segment.start, demux->common.segment.last_stop,
1986 demux->common.segment.time);
1987 GST_OBJECT_UNLOCK (demux);
1990 GST_OBJECT_LOCK (demux);
1991 /* now update the real segment info */
1992 GST_DEBUG_OBJECT (demux, "Committing new seek segment");
1993 memcpy (&demux->common.segment, &seeksegment, sizeof (GstSegment));
1994 GST_OBJECT_UNLOCK (demux);
1996 /* update some (segment) state */
1997 if (!gst_matroska_demux_move_to_entry (demux, entry, TRUE))
2000 /* notify start of new segment */
2001 if (demux->common.segment.flags & GST_SEEK_FLAG_SEGMENT) {
2004 msg = gst_message_new_segment_start (GST_OBJECT (demux),
2005 GST_FORMAT_TIME, demux->common.segment.start);
2006 gst_element_post_message (GST_ELEMENT (demux), msg);
2009 GST_OBJECT_LOCK (demux);
2010 if (demux->new_segment)
2011 gst_event_unref (demux->new_segment);
2012 demux->new_segment = gst_event_new_new_segment_full (FALSE,
2013 demux->common.segment.rate, demux->common.segment.applied_rate,
2014 demux->common.segment.format, demux->common.segment.start,
2015 demux->common.segment.stop, demux->common.segment.time);
2016 GST_OBJECT_UNLOCK (demux);
2018 /* restart our task since it might have been stopped when we did the
2020 demux->segment_running = TRUE;
2021 gst_pad_start_task (demux->common.sinkpad,
2022 (GstTaskFunction) gst_matroska_demux_loop, demux->common.sinkpad);
2024 /* streaming can continue now */
2025 GST_PAD_STREAM_UNLOCK (demux->common.sinkpad);
2031 GST_PAD_STREAM_UNLOCK (demux->common.sinkpad);
2032 GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL), ("Got a seek error"));
2038 * Handle whether we can perform the seek event or if we have to let the chain
2039 * function handle seeks to build the seek indexes first.
2042 gst_matroska_demux_handle_seek_push (GstMatroskaDemux * demux, GstPad * pad,
2046 GstSeekType cur_type, stop_type;
2051 gst_event_parse_seek (event, &rate, &format, &flags, &cur_type, &cur,
2056 /* we can only seek on time */
2057 if (format != GST_FORMAT_TIME) {
2058 GST_DEBUG_OBJECT (demux, "Can only seek on TIME");
2062 if (stop_type != GST_SEEK_TYPE_NONE && stop != GST_CLOCK_TIME_NONE) {
2063 GST_DEBUG_OBJECT (demux, "Seek end-time not supported in streaming mode");
2067 if (!(flags & GST_SEEK_FLAG_FLUSH)) {
2068 GST_DEBUG_OBJECT (demux,
2069 "Non-flushing seek not supported in streaming mode");
2073 if (flags & GST_SEEK_FLAG_SEGMENT) {
2074 GST_DEBUG_OBJECT (demux, "Segment seek not supported in streaming mode");
2078 /* check for having parsed index already */
2079 if (!demux->common.index_parsed) {
2080 gboolean building_index;
2083 if (!demux->index_offset) {
2084 GST_DEBUG_OBJECT (demux, "no index (location); no seek in push mode");
2088 GST_OBJECT_LOCK (demux);
2089 /* handle the seek event in the chain function */
2090 demux->common.state = GST_MATROSKA_READ_STATE_SEEK;
2091 /* no more seek can be issued until state reset to _DATA */
2093 /* copy the event */
2094 if (demux->seek_event)
2095 gst_event_unref (demux->seek_event);
2096 demux->seek_event = gst_event_ref (event);
2098 /* set the building_index flag so that only one thread can setup the
2099 * structures for index seeking. */
2100 building_index = demux->building_index;
2101 if (!building_index) {
2102 demux->building_index = TRUE;
2103 offset = demux->index_offset;
2105 GST_OBJECT_UNLOCK (demux);
2107 if (!building_index) {
2108 /* seek to the first subindex or legacy index */
2109 GST_INFO_OBJECT (demux, "Seeking to Cues at %" G_GUINT64_FORMAT, offset);
2110 return perform_seek_to_offset (demux, offset);
2113 /* well, we are handling it already */
2117 /* delegate to tweaked regular seek */
2118 return gst_matroska_demux_handle_seek_event (demux, pad, event);
2122 gst_matroska_demux_handle_src_event (GstPad * pad, GstEvent * event)
2124 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (gst_pad_get_parent (pad));
2125 gboolean res = TRUE;
2127 switch (GST_EVENT_TYPE (event)) {
2128 case GST_EVENT_SEEK:
2129 /* no seeking until we are (safely) ready */
2130 if (demux->common.state != GST_MATROSKA_READ_STATE_DATA) {
2131 GST_DEBUG_OBJECT (demux, "not ready for seeking yet");
2134 if (!demux->streaming)
2135 res = gst_matroska_demux_handle_seek_event (demux, pad, event);
2137 res = gst_matroska_demux_handle_seek_push (demux, pad, event);
2138 gst_event_unref (event);
2143 GstMatroskaTrackContext *context = gst_pad_get_element_private (pad);
2144 if (context->type == GST_MATROSKA_TRACK_TYPE_VIDEO) {
2145 GstMatroskaTrackVideoContext *videocontext =
2146 (GstMatroskaTrackVideoContext *) context;
2148 GstClockTimeDiff diff;
2149 GstClockTime timestamp;
2151 gst_event_parse_qos (event, &proportion, &diff, ×tamp);
2153 GST_OBJECT_LOCK (demux);
2154 videocontext->earliest_time = timestamp + diff;
2155 GST_OBJECT_UNLOCK (demux);
2158 gst_event_unref (event);
2162 /* events we don't need to handle */
2163 case GST_EVENT_NAVIGATION:
2164 gst_event_unref (event);
2168 case GST_EVENT_LATENCY:
2170 res = gst_pad_push_event (demux->common.sinkpad, event);
2174 gst_object_unref (demux);
2179 static GstFlowReturn
2180 gst_matroska_demux_seek_to_previous_keyframe (GstMatroskaDemux * demux)
2182 GstFlowReturn ret = GST_FLOW_UNEXPECTED;
2183 gboolean done = TRUE;
2186 g_return_val_if_fail (demux->seek_index, GST_FLOW_UNEXPECTED);
2187 g_return_val_if_fail (demux->seek_entry < demux->seek_index->len,
2188 GST_FLOW_UNEXPECTED);
2190 GST_DEBUG_OBJECT (demux, "locating previous keyframe");
2192 if (!demux->seek_entry) {
2193 GST_DEBUG_OBJECT (demux, "no earlier index entry");
2197 for (i = 0; i < demux->common.src->len; i++) {
2198 GstMatroskaTrackContext *stream = g_ptr_array_index (demux->common.src, i);
2200 GST_DEBUG_OBJECT (demux, "segment start %" GST_TIME_FORMAT
2201 ", stream %d at %" GST_TIME_FORMAT,
2202 GST_TIME_ARGS (demux->common.segment.start), stream->index,
2203 GST_TIME_ARGS (stream->from_time));
2204 if (GST_CLOCK_TIME_IS_VALID (stream->from_time)) {
2205 if (stream->from_time > demux->common.segment.start) {
2206 GST_DEBUG_OBJECT (demux, "stream %d not finished yet", stream->index);
2210 /* nothing pushed for this stream;
2211 * likely seek entry did not start at keyframe, so all was skipped.
2212 * So we need an earlier entry */
2218 GstMatroskaIndex *entry;
2220 entry = &g_array_index (demux->seek_index, GstMatroskaIndex,
2221 --demux->seek_entry);
2222 if (!gst_matroska_demux_move_to_entry (demux, entry, FALSE))
2232 static GstFlowReturn
2233 gst_matroska_demux_parse_tracks (GstMatroskaDemux * demux, GstEbmlRead * ebml)
2235 GstFlowReturn ret = GST_FLOW_OK;
2238 DEBUG_ELEMENT_START (demux, ebml, "Tracks");
2240 if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
2241 DEBUG_ELEMENT_STOP (demux, ebml, "Tracks", ret);
2245 while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
2246 if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
2250 /* one track within the "all-tracks" header */
2251 case GST_MATROSKA_ID_TRACKENTRY:
2252 ret = gst_matroska_demux_add_stream (demux, ebml);
2256 ret = gst_matroska_read_common_parse_skip (&demux->common, ebml,
2261 DEBUG_ELEMENT_STOP (demux, ebml, "Tracks", ret);
2263 demux->tracks_parsed = TRUE;
2269 * Read signed/unsigned "EBML" numbers.
2270 * Return: number of bytes processed.
2274 gst_matroska_ebmlnum_uint (guint8 * data, guint size, guint64 * num)
2276 gint len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
2284 while (read <= 8 && !(total & len_mask)) {
2291 if ((total &= (len_mask - 1)) == len_mask - 1)
2296 if (data[n] == 0xff)
2298 total = (total << 8) | data[n];
2302 if (read == num_ffs && total != 0)
2311 gst_matroska_ebmlnum_sint (guint8 * data, guint size, gint64 * num)
2316 /* read as unsigned number first */
2317 if ((res = gst_matroska_ebmlnum_uint (data, size, &unum)) < 0)
2321 if (unum == G_MAXUINT64)
2324 *num = unum - ((1 << ((7 * res) - 1)) - 1);
2330 * Mostly used for subtitles. We add void filler data for each
2331 * lagging stream to make sure we don't deadlock.
2335 gst_matroska_demux_sync_streams (GstMatroskaDemux * demux)
2339 GST_OBJECT_LOCK (demux);
2341 GST_LOG_OBJECT (demux, "Sync to %" GST_TIME_FORMAT,
2342 GST_TIME_ARGS (demux->common.segment.last_stop));
2344 g_assert (demux->common.num_streams == demux->common.src->len);
2345 for (stream_nr = 0; stream_nr < demux->common.src->len; stream_nr++) {
2346 GstMatroskaTrackContext *context;
2348 context = g_ptr_array_index (demux->common.src, stream_nr);
2350 GST_LOG_OBJECT (demux,
2351 "Checking for resync on stream %d (%" GST_TIME_FORMAT ")", stream_nr,
2352 GST_TIME_ARGS (context->pos));
2354 if (G_LIKELY (context->type != GST_MATROSKA_TRACK_TYPE_SUBTITLE)) {
2355 GST_LOG_OBJECT (demux, "Skipping sync on non-subtitle stream");
2359 /* does it lag? 0.5 seconds is a random threshold...
2360 * lag need only be considered if we have advanced into requested segment */
2361 if (GST_CLOCK_TIME_IS_VALID (context->pos) &&
2362 GST_CLOCK_TIME_IS_VALID (demux->common.segment.last_stop) &&
2363 demux->common.segment.last_stop > demux->common.segment.start &&
2364 context->pos + (GST_SECOND / 2) < demux->common.segment.last_stop) {
2368 new_start = demux->common.segment.last_stop - (GST_SECOND / 2);
2369 if (GST_CLOCK_TIME_IS_VALID (demux->common.segment.stop))
2370 new_start = MIN (new_start, demux->common.segment.stop);
2371 GST_DEBUG_OBJECT (demux,
2372 "Synchronizing stream %d with others by advancing time " "from %"
2373 GST_TIME_FORMAT " to %" GST_TIME_FORMAT, stream_nr,
2374 GST_TIME_ARGS (context->pos), GST_TIME_ARGS (new_start));
2376 context->pos = new_start;
2378 /* advance stream time */
2379 event = gst_event_new_new_segment (TRUE, demux->common.segment.rate,
2380 demux->common.segment.format, new_start, demux->common.segment.stop,
2382 GST_OBJECT_UNLOCK (demux);
2383 gst_pad_push_event (context->pad, event);
2384 GST_OBJECT_LOCK (demux);
2388 GST_OBJECT_UNLOCK (demux);
2391 static GstFlowReturn
2392 gst_matroska_demux_push_hdr_buf (GstMatroskaDemux * demux,
2393 GstMatroskaTrackContext * stream, guint8 * data, guint len)
2395 GstFlowReturn ret, cret;
2396 GstBuffer *header_buf;
2398 header_buf = gst_buffer_new_and_alloc (len);
2399 gst_buffer_set_caps (header_buf, stream->caps);
2400 memcpy (GST_BUFFER_DATA (header_buf), data, len);
2402 if (stream->set_discont) {
2403 GST_BUFFER_FLAG_SET (header_buf, GST_BUFFER_FLAG_DISCONT);
2404 stream->set_discont = FALSE;
2407 ret = gst_pad_push (stream->pad, header_buf);
2410 cret = gst_matroska_demux_combine_flows (demux, stream, ret);
2415 static GstFlowReturn
2416 gst_matroska_demux_push_flac_codec_priv_data (GstMatroskaDemux * demux,
2417 GstMatroskaTrackContext * stream)
2423 GST_LOG_OBJECT (demux, "priv data size = %u", stream->codec_priv_size);
2425 pdata = (guint8 *) stream->codec_priv;
2427 /* need at least 'fLaC' marker + STREAMINFO metadata block */
2428 if (stream->codec_priv_size < ((4) + (4 + 34))) {
2429 GST_WARNING_OBJECT (demux, "not enough codec priv data for flac headers");
2430 return GST_FLOW_ERROR;
2433 if (memcmp (pdata, "fLaC", 4) != 0) {
2434 GST_WARNING_OBJECT (demux, "no flac marker at start of stream headers");
2435 return GST_FLOW_ERROR;
2438 ret = gst_matroska_demux_push_hdr_buf (demux, stream, pdata, 4);
2439 if (ret != GST_FLOW_OK)
2442 off = 4; /* skip fLaC marker */
2443 while (off < stream->codec_priv_size) {
2444 len = GST_READ_UINT8 (pdata + off + 1) << 16;
2445 len |= GST_READ_UINT8 (pdata + off + 2) << 8;
2446 len |= GST_READ_UINT8 (pdata + off + 3);
2448 GST_DEBUG_OBJECT (demux, "header packet: len=%u bytes, flags=0x%02x",
2449 len, (guint) pdata[off]);
2451 ret = gst_matroska_demux_push_hdr_buf (demux, stream, pdata + off, len + 4);
2452 if (ret != GST_FLOW_OK)
2460 static GstFlowReturn
2461 gst_matroska_demux_push_speex_codec_priv_data (GstMatroskaDemux * demux,
2462 GstMatroskaTrackContext * stream)
2467 GST_LOG_OBJECT (demux, "priv data size = %u", stream->codec_priv_size);
2469 pdata = (guint8 *) stream->codec_priv;
2471 /* need at least 'fLaC' marker + STREAMINFO metadata block */
2472 if (stream->codec_priv_size < 80) {
2473 GST_WARNING_OBJECT (demux, "not enough codec priv data for speex headers");
2474 return GST_FLOW_ERROR;
2477 if (memcmp (pdata, "Speex ", 8) != 0) {
2478 GST_WARNING_OBJECT (demux, "no Speex marker at start of stream headers");
2479 return GST_FLOW_ERROR;
2482 ret = gst_matroska_demux_push_hdr_buf (demux, stream, pdata, 80);
2483 if (ret != GST_FLOW_OK)
2486 if (stream->codec_priv_size == 80)
2489 return gst_matroska_demux_push_hdr_buf (demux, stream, pdata + 80,
2490 stream->codec_priv_size - 80);
2493 static GstFlowReturn
2494 gst_matroska_demux_push_xiph_codec_priv_data (GstMatroskaDemux * demux,
2495 GstMatroskaTrackContext * stream)
2498 guint8 *p = (guint8 *) stream->codec_priv;
2499 gint i, offset, num_packets;
2500 guint *length, last;
2502 if (stream->codec_priv == NULL || stream->codec_priv_size == 0) {
2503 GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
2504 ("Missing codec private data for xiph headers, broken file"));
2505 return GST_FLOW_ERROR;
2508 /* start of the stream and vorbis audio or theora video, need to
2509 * send the codec_priv data as first three packets */
2510 num_packets = p[0] + 1;
2511 GST_DEBUG_OBJECT (demux, "%u stream headers, total length=%u bytes",
2512 (guint) num_packets, stream->codec_priv_size);
2514 length = g_alloca (num_packets * sizeof (guint));
2518 /* first packets, read length values */
2519 for (i = 0; i < num_packets - 1; i++) {
2521 while (offset < stream->codec_priv_size) {
2522 length[i] += p[offset];
2523 if (p[offset++] != 0xff)
2528 if (offset + last > stream->codec_priv_size)
2529 return GST_FLOW_ERROR;
2531 /* last packet is the remaining size */
2532 length[i] = stream->codec_priv_size - offset - last;
2534 for (i = 0; i < num_packets; i++) {
2535 GST_DEBUG_OBJECT (demux, "buffer %d: length=%u bytes", i,
2537 if (offset + length[i] > stream->codec_priv_size)
2538 return GST_FLOW_ERROR;
2541 gst_matroska_demux_push_hdr_buf (demux, stream, p + offset, length[i]);
2542 if (ret != GST_FLOW_OK)
2545 offset += length[i];
2551 gst_matroska_demux_push_dvd_clut_change_event (GstMatroskaDemux * demux,
2552 GstMatroskaTrackContext * stream)
2556 g_assert (!strcmp (stream->codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_VOBSUB));
2558 if (!stream->codec_priv)
2561 /* ideally, VobSub private data should be parsed and stored more convenient
2562 * elsewhere, but for now, only interested in a small part */
2564 /* make sure we have terminating 0 */
2565 buf = g_strndup ((gchar *) stream->codec_priv, stream->codec_priv_size);
2567 /* just locate and parse palette part */
2568 start = strstr (buf, "palette:");
2573 guint8 r, g, b, y, u, v;
2576 while (g_ascii_isspace (*start))
2578 for (i = 0; i < 16; i++) {
2579 if (sscanf (start, "%06x", &col) != 1)
2582 while ((*start == ',') || g_ascii_isspace (*start))
2584 /* sigh, need to convert this from vobsub pseudo-RGB to YUV */
2585 r = (col >> 16) & 0xff;
2586 g = (col >> 8) & 0xff;
2588 y = CLAMP ((0.1494 * r + 0.6061 * g + 0.2445 * b) * 219 / 255 + 16, 0,
2590 u = CLAMP (0.6066 * r - 0.4322 * g - 0.1744 * b + 128, 0, 255);
2591 v = CLAMP (-0.08435 * r - 0.3422 * g + 0.4266 * b + 128, 0, 255);
2592 clut[i] = (y << 16) | (u << 8) | v;
2595 /* got them all without problems; build and send event */
2599 s = gst_structure_new ("application/x-gst-dvd", "event", G_TYPE_STRING,
2600 "dvd-spu-clut-change", "clut00", G_TYPE_INT, clut[0], "clut01",
2601 G_TYPE_INT, clut[1], "clut02", G_TYPE_INT, clut[2], "clut03",
2602 G_TYPE_INT, clut[3], "clut04", G_TYPE_INT, clut[4], "clut05",
2603 G_TYPE_INT, clut[5], "clut06", G_TYPE_INT, clut[6], "clut07",
2604 G_TYPE_INT, clut[7], "clut08", G_TYPE_INT, clut[8], "clut09",
2605 G_TYPE_INT, clut[9], "clut10", G_TYPE_INT, clut[10], "clut11",
2606 G_TYPE_INT, clut[11], "clut12", G_TYPE_INT, clut[12], "clut13",
2607 G_TYPE_INT, clut[13], "clut14", G_TYPE_INT, clut[14], "clut15",
2608 G_TYPE_INT, clut[15], NULL);
2610 gst_pad_push_event (stream->pad,
2611 gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM, s));
2617 static GstFlowReturn
2618 gst_matroska_demux_add_mpeg_seq_header (GstElement * element,
2619 GstMatroskaTrackContext * stream, GstBuffer ** buf)
2622 guint seq_header_len;
2625 if (stream->codec_state) {
2626 seq_header = stream->codec_state;
2627 seq_header_len = stream->codec_state_size;
2628 } else if (stream->codec_priv) {
2629 seq_header = stream->codec_priv;
2630 seq_header_len = stream->codec_priv_size;
2635 /* Sequence header only needed for keyframes */
2636 if (GST_BUFFER_FLAG_IS_SET (*buf, GST_BUFFER_FLAG_DELTA_UNIT))
2639 if (GST_BUFFER_SIZE (*buf) < 4)
2642 header = GST_READ_UINT32_BE (GST_BUFFER_DATA (*buf));
2643 /* Sequence start code, if not found prepend */
2644 if (header != 0x000001b3) {
2647 newbuf = gst_buffer_new_and_alloc (GST_BUFFER_SIZE (*buf) + seq_header_len);
2648 gst_buffer_set_caps (newbuf, stream->caps);
2650 GST_DEBUG_OBJECT (element, "Prepending MPEG sequence header");
2651 gst_buffer_copy_metadata (newbuf, *buf, GST_BUFFER_COPY_TIMESTAMPS |
2652 GST_BUFFER_COPY_FLAGS);
2653 g_memmove (GST_BUFFER_DATA (newbuf), seq_header, seq_header_len);
2654 g_memmove (GST_BUFFER_DATA (newbuf) + seq_header_len,
2655 GST_BUFFER_DATA (*buf), GST_BUFFER_SIZE (*buf));
2656 gst_buffer_unref (*buf);
2663 static GstFlowReturn
2664 gst_matroska_demux_add_wvpk_header (GstElement * element,
2665 GstMatroskaTrackContext * stream, GstBuffer ** buf)
2667 GstMatroskaTrackAudioContext *audiocontext =
2668 (GstMatroskaTrackAudioContext *) stream;
2669 GstBuffer *newbuf = NULL;
2679 wvh.version = GST_READ_UINT16_LE (stream->codec_priv);
2682 wvh.total_samples = -1;
2683 wvh.block_index = audiocontext->wvpk_block_index;
2685 if (audiocontext->channels <= 2) {
2686 guint32 block_samples;
2688 block_samples = GST_READ_UINT32_LE (GST_BUFFER_DATA (*buf));
2689 /* we need to reconstruct the header of the wavpack block */
2691 /* -20 because ck_size is the size of the wavpack block -8
2692 * and lace_size is the size of the wavpack block + 12
2693 * (the three guint32 of the header that already are in the buffer) */
2694 wvh.ck_size = GST_BUFFER_SIZE (*buf) + sizeof (Wavpack4Header) - 20;
2696 /* block_samples, flags and crc are already in the buffer */
2697 newlen = GST_BUFFER_SIZE (*buf) + sizeof (Wavpack4Header) - 12;
2698 newbuf = gst_buffer_new_and_alloc (newlen);
2699 gst_buffer_set_caps (newbuf, stream->caps);
2701 data = GST_BUFFER_DATA (newbuf);
2706 GST_WRITE_UINT32_LE (data + 4, wvh.ck_size);
2707 GST_WRITE_UINT16_LE (data + 8, wvh.version);
2708 GST_WRITE_UINT8 (data + 10, wvh.track_no);
2709 GST_WRITE_UINT8 (data + 11, wvh.index_no);
2710 GST_WRITE_UINT32_LE (data + 12, wvh.total_samples);
2711 GST_WRITE_UINT32_LE (data + 16, wvh.block_index);
2712 g_memmove (data + 20, GST_BUFFER_DATA (*buf), GST_BUFFER_SIZE (*buf));
2713 gst_buffer_copy_metadata (newbuf, *buf,
2714 GST_BUFFER_COPY_TIMESTAMPS | GST_BUFFER_COPY_FLAGS);
2715 gst_buffer_unref (*buf);
2717 audiocontext->wvpk_block_index += block_samples;
2722 guint32 block_samples, flags, crc, blocksize;
2724 data = GST_BUFFER_DATA (*buf);
2725 size = GST_BUFFER_SIZE (*buf);
2728 GST_ERROR_OBJECT (element, "Too small wavpack buffer");
2729 return GST_FLOW_ERROR;
2732 block_samples = GST_READ_UINT32_LE (data);
2737 flags = GST_READ_UINT32_LE (data);
2740 crc = GST_READ_UINT32_LE (data);
2743 blocksize = GST_READ_UINT32_LE (data);
2747 if (blocksize == 0 || size < blocksize)
2750 if (newbuf == NULL) {
2751 newbuf = gst_buffer_new_and_alloc (sizeof (Wavpack4Header) + blocksize);
2752 gst_buffer_set_caps (newbuf, stream->caps);
2754 gst_buffer_copy_metadata (newbuf, *buf,
2755 GST_BUFFER_COPY_TIMESTAMPS | GST_BUFFER_COPY_FLAGS);
2758 outdata = GST_BUFFER_DATA (newbuf);
2760 GST_BUFFER_SIZE (newbuf) += sizeof (Wavpack4Header) + blocksize;
2761 GST_BUFFER_DATA (newbuf) =
2762 g_realloc (GST_BUFFER_DATA (newbuf), GST_BUFFER_SIZE (newbuf));
2763 GST_BUFFER_MALLOCDATA (newbuf) = GST_BUFFER_DATA (newbuf);
2764 outdata = GST_BUFFER_DATA (newbuf);
2767 outdata[outpos] = 'w';
2768 outdata[outpos + 1] = 'v';
2769 outdata[outpos + 2] = 'p';
2770 outdata[outpos + 3] = 'k';
2773 GST_WRITE_UINT32_LE (outdata + outpos,
2774 blocksize + sizeof (Wavpack4Header) - 8);
2775 GST_WRITE_UINT16_LE (outdata + outpos + 4, wvh.version);
2776 GST_WRITE_UINT8 (outdata + outpos + 6, wvh.track_no);
2777 GST_WRITE_UINT8 (outdata + outpos + 7, wvh.index_no);
2778 GST_WRITE_UINT32_LE (outdata + outpos + 8, wvh.total_samples);
2779 GST_WRITE_UINT32_LE (outdata + outpos + 12, wvh.block_index);
2780 GST_WRITE_UINT32_LE (outdata + outpos + 16, block_samples);
2781 GST_WRITE_UINT32_LE (outdata + outpos + 20, flags);
2782 GST_WRITE_UINT32_LE (outdata + outpos + 24, crc);
2785 g_memmove (outdata + outpos, data, blocksize);
2786 outpos += blocksize;
2790 gst_buffer_unref (*buf);
2792 audiocontext->wvpk_block_index += block_samples;
2798 /* @text must be null-terminated */
2800 gst_matroska_demux_subtitle_chunk_has_tag (GstElement * element,
2805 /* yes, this might all lead to false positives ... */
2806 tag = (gchar *) text;
2807 while ((tag = strchr (tag, '<'))) {
2809 if (*tag != '\0' && *(tag + 1) == '>') {
2810 /* some common convenience ones */
2811 /* maybe any character will do here ? */
2824 if (strstr (text, "<span"))
2830 static GstFlowReturn
2831 gst_matroska_demux_check_subtitle_buffer (GstElement * element,
2832 GstMatroskaTrackContext * stream, GstBuffer ** buf)
2834 GstMatroskaTrackSubtitleContext *sub_stream;
2835 const gchar *encoding, *data;
2841 sub_stream = (GstMatroskaTrackSubtitleContext *) stream;
2843 data = (const gchar *) GST_BUFFER_DATA (*buf);
2844 size = GST_BUFFER_SIZE (*buf);
2846 if (!sub_stream->invalid_utf8) {
2847 if (g_utf8_validate (data, size, NULL)) {
2850 GST_WARNING_OBJECT (element, "subtitle stream %d is not valid UTF-8, this "
2851 "is broken according to the matroska specification", stream->num);
2852 sub_stream->invalid_utf8 = TRUE;
2855 /* file with broken non-UTF8 subtitle, do the best we can do to fix it */
2856 encoding = g_getenv ("GST_SUBTITLE_ENCODING");
2857 if (encoding == NULL || *encoding == '\0') {
2858 /* if local encoding is UTF-8 and no encoding specified
2859 * via the environment variable, assume ISO-8859-15 */
2860 if (g_get_charset (&encoding)) {
2861 encoding = "ISO-8859-15";
2865 utf8 = g_convert_with_fallback (data, size, "UTF-8", encoding, (char *) "*",
2869 GST_LOG_OBJECT (element, "could not convert string from '%s' to UTF-8: %s",
2870 encoding, err->message);
2874 /* invalid input encoding, fall back to ISO-8859-15 (always succeeds) */
2875 encoding = "ISO-8859-15";
2876 utf8 = g_convert_with_fallback (data, size, "UTF-8", encoding, (char *) "*",
2880 GST_LOG_OBJECT (element, "converted subtitle text from %s to UTF-8 %s",
2881 encoding, (err) ? "(using ISO-8859-15 as fallback)" : "");
2884 utf8 = g_strdup ("invalid subtitle");
2886 newbuf = gst_buffer_new ();
2887 GST_BUFFER_MALLOCDATA (newbuf) = (guint8 *) utf8;
2888 GST_BUFFER_DATA (newbuf) = (guint8 *) utf8;
2889 GST_BUFFER_SIZE (newbuf) = strlen (utf8);
2890 gst_buffer_copy_metadata (newbuf, *buf,
2891 GST_BUFFER_COPY_TIMESTAMPS | GST_BUFFER_COPY_FLAGS);
2892 gst_buffer_unref (*buf);
2895 data = (const gchar *) GST_BUFFER_DATA (*buf);
2896 size = GST_BUFFER_SIZE (*buf);
2899 /* caps claim markup text, so we need to escape text,
2900 * except if text is already markup and then needs no further escaping */
2901 sub_stream->seen_markup_tag = sub_stream->seen_markup_tag ||
2902 gst_matroska_demux_subtitle_chunk_has_tag (element, data);
2904 if (!sub_stream->seen_markup_tag) {
2905 utf8 = g_markup_escape_text (data, size);
2907 newbuf = gst_buffer_new ();
2908 GST_BUFFER_MALLOCDATA (newbuf) = (guint8 *) utf8;
2909 GST_BUFFER_DATA (newbuf) = (guint8 *) utf8;
2910 GST_BUFFER_SIZE (newbuf) = strlen (utf8);
2911 gst_buffer_copy_metadata (newbuf, *buf,
2912 GST_BUFFER_COPY_TIMESTAMPS | GST_BUFFER_COPY_FLAGS);
2913 gst_buffer_unref (*buf);
2921 static GstFlowReturn
2922 gst_matroska_demux_check_aac (GstElement * element,
2923 GstMatroskaTrackContext * stream, GstBuffer ** buf)
2928 data = GST_BUFFER_DATA (*buf);
2929 size = GST_BUFFER_SIZE (*buf);
2931 if (size > 2 && data[0] == 0xff && (data[1] >> 4 == 0x0f)) {
2935 /* tss, ADTS data, remove codec_data
2936 * still assume it is at least parsed */
2937 new_caps = gst_caps_copy (stream->caps);
2938 s = gst_caps_get_structure (new_caps, 0);
2940 gst_structure_remove_field (s, "codec_data");
2941 gst_caps_replace (&stream->caps, new_caps);
2942 gst_pad_set_caps (stream->pad, new_caps);
2943 gst_buffer_set_caps (*buf, new_caps);
2944 GST_DEBUG_OBJECT (element, "ADTS AAC audio data; removing codec-data, "
2945 "new caps: %" GST_PTR_FORMAT, new_caps);
2946 gst_caps_unref (new_caps);
2949 /* disable subsequent checking */
2950 stream->postprocess_frame = NULL;
2955 static GstFlowReturn
2956 gst_matroska_demux_parse_blockgroup_or_simpleblock (GstMatroskaDemux * demux,
2957 GstEbmlRead * ebml, guint64 cluster_time, guint64 cluster_offset,
2958 gboolean is_simpleblock)
2960 GstMatroskaTrackContext *stream = NULL;
2961 GstFlowReturn ret = GST_FLOW_OK;
2962 gboolean readblock = FALSE;
2964 guint64 block_duration = -1;
2965 GstBuffer *buf = NULL;
2966 gint stream_num = -1, n, laces = 0;
2968 gint *lace_size = NULL;
2971 gint64 referenceblock = 0;
2974 offset = gst_ebml_read_get_offset (ebml);
2976 while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
2977 if (!is_simpleblock) {
2978 if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK) {
2982 id = GST_MATROSKA_ID_SIMPLEBLOCK;
2986 /* one block inside the group. Note, block parsing is one
2987 * of the harder things, so this code is a bit complicated.
2988 * See http://www.matroska.org/ for documentation. */
2989 case GST_MATROSKA_ID_SIMPLEBLOCK:
2990 case GST_MATROSKA_ID_BLOCK:
2996 gst_buffer_unref (buf);
2999 if ((ret = gst_ebml_read_buffer (ebml, &id, &buf)) != GST_FLOW_OK)
3002 data = GST_BUFFER_DATA (buf);
3003 size = GST_BUFFER_SIZE (buf);
3005 /* first byte(s): blocknum */
3006 if ((n = gst_matroska_ebmlnum_uint (data, size, &num)) < 0)
3011 /* fetch stream from num */
3012 stream_num = gst_matroska_read_common_stream_from_num (&demux->common,
3014 if (G_UNLIKELY (size < 3)) {
3015 GST_WARNING_OBJECT (demux, "Invalid size %u", size);
3016 /* non-fatal, try next block(group) */
3019 } else if (G_UNLIKELY (stream_num < 0 ||
3020 stream_num >= demux->common.num_streams)) {
3021 /* let's not give up on a stray invalid track number */
3022 GST_WARNING_OBJECT (demux,
3023 "Invalid stream %d for track number %" G_GUINT64_FORMAT
3024 "; ignoring block", stream_num, num);
3028 stream = g_ptr_array_index (demux->common.src, stream_num);
3030 /* time (relative to cluster time) */
3031 time = ((gint16) GST_READ_UINT16_BE (data));
3034 flags = GST_READ_UINT8 (data);
3038 GST_LOG_OBJECT (demux, "time %" G_GUINT64_FORMAT ", flags %d", time,
3041 switch ((flags & 0x06) >> 1) {
3042 case 0x0: /* no lacing */
3044 lace_size = g_new (gint, 1);
3045 lace_size[0] = size;
3048 case 0x1: /* xiph lacing */
3049 case 0x2: /* fixed-size lacing */
3050 case 0x3: /* EBML lacing */
3052 goto invalid_lacing;
3053 laces = GST_READ_UINT8 (data) + 1;
3056 lace_size = g_new0 (gint, laces);
3058 switch ((flags & 0x06) >> 1) {
3059 case 0x1: /* xiph lacing */ {
3060 guint temp, total = 0;
3062 for (n = 0; ret == GST_FLOW_OK && n < laces - 1; n++) {
3065 goto invalid_lacing;
3066 temp = GST_READ_UINT8 (data);
3067 lace_size[n] += temp;
3073 total += lace_size[n];
3075 lace_size[n] = size - total;
3079 case 0x2: /* fixed-size lacing */
3080 for (n = 0; n < laces; n++)
3081 lace_size[n] = size / laces;
3084 case 0x3: /* EBML lacing */ {
3087 if ((n = gst_matroska_ebmlnum_uint (data, size, &num)) < 0)
3091 total = lace_size[0] = num;
3092 for (n = 1; ret == GST_FLOW_OK && n < laces - 1; n++) {
3096 if ((r = gst_matroska_ebmlnum_sint (data, size, &snum)) < 0)
3100 lace_size[n] = lace_size[n - 1] + snum;
3101 total += lace_size[n];
3104 lace_size[n] = size - total;
3111 if (stream->send_xiph_headers) {
3112 ret = gst_matroska_demux_push_xiph_codec_priv_data (demux, stream);
3113 stream->send_xiph_headers = FALSE;
3116 if (stream->send_flac_headers) {
3117 ret = gst_matroska_demux_push_flac_codec_priv_data (demux, stream);
3118 stream->send_flac_headers = FALSE;
3121 if (stream->send_speex_headers) {
3122 ret = gst_matroska_demux_push_speex_codec_priv_data (demux, stream);
3123 stream->send_speex_headers = FALSE;
3126 if (stream->send_dvd_event) {
3127 gst_matroska_demux_push_dvd_clut_change_event (demux, stream);
3128 /* FIXME: should we send this event again after (flushing) seek ? */
3129 stream->send_dvd_event = FALSE;
3132 if (ret != GST_FLOW_OK)
3139 case GST_MATROSKA_ID_BLOCKDURATION:{
3140 ret = gst_ebml_read_uint (ebml, &id, &block_duration);
3141 GST_DEBUG_OBJECT (demux, "BlockDuration: %" G_GUINT64_FORMAT,
3146 case GST_MATROSKA_ID_REFERENCEBLOCK:{
3147 ret = gst_ebml_read_sint (ebml, &id, &referenceblock);
3148 GST_DEBUG_OBJECT (demux, "ReferenceBlock: %" G_GINT64_FORMAT,
3153 case GST_MATROSKA_ID_CODECSTATE:{
3155 guint64 data_len = 0;
3158 gst_ebml_read_binary (ebml, &id, &data,
3159 &data_len)) != GST_FLOW_OK)
3162 if (G_UNLIKELY (stream == NULL)) {
3163 GST_WARNING_OBJECT (demux,
3164 "Unexpected CodecState subelement - ignoring");
3168 g_free (stream->codec_state);
3169 stream->codec_state = data;
3170 stream->codec_state_size = data_len;
3172 /* Decode if necessary */
3173 if (stream->encodings && stream->encodings->len > 0
3174 && stream->codec_state && stream->codec_state_size > 0) {
3175 if (!gst_matroska_decode_data (stream->encodings,
3176 &stream->codec_state, &stream->codec_state_size,
3177 GST_MATROSKA_TRACK_ENCODING_SCOPE_CODEC_DATA, TRUE)) {
3178 GST_WARNING_OBJECT (demux, "Decoding codec state failed");
3182 GST_DEBUG_OBJECT (demux, "CodecState of %u bytes",
3183 stream->codec_state_size);
3188 ret = gst_matroska_read_common_parse_skip (&demux->common, ebml,
3192 case GST_MATROSKA_ID_BLOCKVIRTUAL:
3193 case GST_MATROSKA_ID_BLOCKADDITIONS:
3194 case GST_MATROSKA_ID_REFERENCEPRIORITY:
3195 case GST_MATROSKA_ID_REFERENCEVIRTUAL:
3196 case GST_MATROSKA_ID_SLICES:
3197 GST_DEBUG_OBJECT (demux,
3198 "Skipping BlockGroup subelement 0x%x - ignoring", id);
3199 ret = gst_ebml_read_skip (ebml);
3207 /* reading a number or so could have failed */
3208 if (ret != GST_FLOW_OK)
3211 if (ret == GST_FLOW_OK && readblock) {
3212 guint64 duration = 0;
3213 gint64 lace_time = 0;
3214 gboolean delta_unit;
3216 stream = g_ptr_array_index (demux->common.src, stream_num);
3218 if (cluster_time != GST_CLOCK_TIME_NONE) {
3219 /* FIXME: What to do with negative timestamps? Give timestamp 0 or -1?
3220 * Drop unless the lace contains timestamp 0? */
3221 if (time < 0 && (-time) > cluster_time) {
3224 if (stream->timecodescale == 1.0)
3225 lace_time = (cluster_time + time) * demux->common.time_scale;
3228 gst_util_guint64_to_gdouble ((cluster_time + time) *
3229 demux->common.time_scale) * stream->timecodescale;
3232 lace_time = GST_CLOCK_TIME_NONE;
3235 /* need to refresh segment info ASAP */
3236 if (GST_CLOCK_TIME_IS_VALID (lace_time) && demux->need_newsegment) {
3237 GST_DEBUG_OBJECT (demux,
3238 "generating segment starting at %" GST_TIME_FORMAT,
3239 GST_TIME_ARGS (lace_time));
3240 /* pretend we seeked here */
3241 gst_segment_set_seek (&demux->common.segment, demux->common.segment.rate,
3242 GST_FORMAT_TIME, 0, GST_SEEK_TYPE_SET, lace_time,
3243 GST_SEEK_TYPE_SET, GST_CLOCK_TIME_NONE, NULL);
3244 /* now convey our segment notion downstream */
3245 gst_matroska_demux_send_event (demux, gst_event_new_new_segment (FALSE,
3246 demux->common.segment.rate, demux->common.segment.format,
3247 demux->common.segment.start, demux->common.segment.stop,
3248 demux->common.segment.start));
3249 demux->need_newsegment = FALSE;
3252 if (block_duration != -1) {
3253 if (stream->timecodescale == 1.0)
3254 duration = gst_util_uint64_scale (block_duration,
3255 demux->common.time_scale, 1);
3258 gst_util_gdouble_to_guint64 (gst_util_guint64_to_gdouble
3259 (gst_util_uint64_scale (block_duration, demux->common.time_scale,
3260 1)) * stream->timecodescale);
3261 } else if (stream->default_duration) {
3262 duration = stream->default_duration * laces;
3264 /* else duration is diff between timecode of this and next block */
3266 /* For SimpleBlock, look at the keyframe bit in flags. Otherwise,
3267 a ReferenceBlock implies that this is not a keyframe. In either
3268 case, it only makes sense for video streams. */
3269 delta_unit = stream->type == GST_MATROSKA_TRACK_TYPE_VIDEO &&
3270 ((is_simpleblock && !(flags & 0x80)) || referenceblock);
3272 if (delta_unit && stream->set_discont) {
3273 /* When doing seeks or such, we need to restart on key frames or
3274 * decoders might choke. */
3275 GST_DEBUG_OBJECT (demux, "skipping delta unit");
3279 for (n = 0; n < laces; n++) {
3282 if (G_UNLIKELY (lace_size[n] > size)) {
3283 GST_WARNING_OBJECT (demux, "Invalid lace size");
3287 /* QoS for video track with an index. the assumption is that
3288 index entries point to keyframes, but if that is not true we
3289 will instad skip until the next keyframe. */
3290 if (GST_CLOCK_TIME_IS_VALID (lace_time) &&
3291 stream->type == GST_MATROSKA_TRACK_TYPE_VIDEO &&
3292 stream->index_table && demux->common.segment.rate > 0.0) {
3293 GstMatroskaTrackVideoContext *videocontext =
3294 (GstMatroskaTrackVideoContext *) stream;
3295 GstClockTime earliest_time;
3296 GstClockTime earliest_stream_time;
3298 GST_OBJECT_LOCK (demux);
3299 earliest_time = videocontext->earliest_time;
3300 GST_OBJECT_UNLOCK (demux);
3301 earliest_stream_time = gst_segment_to_position (&demux->common.segment,
3302 GST_FORMAT_TIME, earliest_time);
3304 if (GST_CLOCK_TIME_IS_VALID (lace_time) &&
3305 GST_CLOCK_TIME_IS_VALID (earliest_stream_time) &&
3306 lace_time <= earliest_stream_time) {
3307 /* find index entry (keyframe) <= earliest_stream_time */
3308 GstMatroskaIndex *entry =
3309 gst_util_array_binary_search (stream->index_table->data,
3310 stream->index_table->len, sizeof (GstMatroskaIndex),
3311 (GCompareDataFunc) gst_matroska_index_seek_find,
3312 GST_SEARCH_MODE_BEFORE, &earliest_stream_time, NULL);
3314 /* if that entry (keyframe) is after the current the current
3315 buffer, we can skip pushing (and thus decoding) all
3316 buffers until that keyframe. */
3317 if (entry && GST_CLOCK_TIME_IS_VALID (entry->time) &&
3318 entry->time > lace_time) {
3319 GST_LOG_OBJECT (demux, "Skipping lace before late keyframe");
3320 stream->set_discont = TRUE;
3326 sub = gst_buffer_create_sub (buf,
3327 GST_BUFFER_SIZE (buf) - size, lace_size[n]);
3328 GST_DEBUG_OBJECT (demux, "created subbuffer %p", sub);
3331 GST_BUFFER_FLAG_SET (sub, GST_BUFFER_FLAG_DELTA_UNIT);
3333 GST_BUFFER_FLAG_UNSET (sub, GST_BUFFER_FLAG_DELTA_UNIT);
3335 if (stream->encodings != NULL && stream->encodings->len > 0)
3336 sub = gst_matroska_decode_buffer (stream, sub);
3339 GST_WARNING_OBJECT (demux, "Decoding buffer failed");
3343 GST_BUFFER_TIMESTAMP (sub) = lace_time;
3345 if (GST_CLOCK_TIME_IS_VALID (lace_time)) {
3346 GstClockTime last_stop_end;
3348 /* Check if this stream is after segment stop */
3349 if (GST_CLOCK_TIME_IS_VALID (demux->common.segment.stop) &&
3350 lace_time >= demux->common.segment.stop) {
3351 GST_DEBUG_OBJECT (demux,
3352 "Stream %d after segment stop %" GST_TIME_FORMAT, stream->index,
3353 GST_TIME_ARGS (demux->common.segment.stop));
3354 gst_buffer_unref (sub);
3357 if (offset >= stream->to_offset) {
3358 GST_DEBUG_OBJECT (demux, "Stream %d after playback section",
3360 gst_buffer_unref (sub);
3364 /* handle gaps, e.g. non-zero start-time, or an cue index entry
3365 * that landed us with timestamps not quite intended */
3366 GST_OBJECT_LOCK (demux);
3367 if (GST_CLOCK_TIME_IS_VALID (demux->common.segment.last_stop) &&
3368 demux->common.segment.rate > 0.0) {
3369 GstClockTimeDiff diff;
3370 GstEvent *event1, *event2;
3372 /* only send newsegments with increasing start times,
3373 * otherwise if these go back and forth downstream (sinks) increase
3374 * accumulated time and running_time */
3375 diff = GST_CLOCK_DIFF (demux->common.segment.last_stop, lace_time);
3376 if (diff > 2 * GST_SECOND && lace_time > demux->common.segment.start
3377 && (!GST_CLOCK_TIME_IS_VALID (demux->common.segment.stop)
3378 || lace_time < demux->common.segment.stop)) {
3379 GST_DEBUG_OBJECT (demux,
3380 "Gap of %" G_GINT64_FORMAT " ns detected in"
3381 "stream %d (%" GST_TIME_FORMAT " -> %" GST_TIME_FORMAT "). "
3382 "Sending updated NEWSEGMENT events", diff,
3383 stream->index, GST_TIME_ARGS (stream->pos),
3384 GST_TIME_ARGS (lace_time));
3385 /* send newsegment events such that the gap is not accounted in
3386 * accum time, hence running_time */
3387 /* close ahead of gap */
3388 event1 = gst_event_new_new_segment (TRUE,
3389 demux->common.segment.rate,
3390 demux->common.segment.format,
3391 demux->common.segment.last_stop,
3392 demux->common.segment.last_stop,
3393 demux->common.segment.last_stop);
3395 event2 = gst_event_new_new_segment (FALSE,
3396 demux->common.segment.rate,
3397 demux->common.segment.format, lace_time,
3398 demux->common.segment.stop, lace_time);
3399 GST_OBJECT_UNLOCK (demux);
3400 gst_matroska_demux_send_event (demux, event1);
3401 gst_matroska_demux_send_event (demux, event2);
3402 GST_OBJECT_LOCK (demux);
3403 /* align segment view with downstream,
3404 * prevents double-counting accum when closing segment */
3405 gst_segment_set_newsegment (&demux->common.segment, FALSE,
3406 demux->common.segment.rate, demux->common.segment.format,
3407 lace_time, demux->common.segment.stop, lace_time);
3408 demux->common.segment.last_stop = lace_time;
3412 if (!GST_CLOCK_TIME_IS_VALID (demux->common.segment.last_stop)
3413 || demux->common.segment.last_stop < lace_time) {
3414 demux->common.segment.last_stop = lace_time;
3416 GST_OBJECT_UNLOCK (demux);
3418 last_stop_end = lace_time;
3420 GST_BUFFER_DURATION (sub) = duration / laces;
3421 last_stop_end += GST_BUFFER_DURATION (sub);
3424 if (!GST_CLOCK_TIME_IS_VALID (demux->last_stop_end) ||
3425 demux->last_stop_end < last_stop_end)
3426 demux->last_stop_end = last_stop_end;
3428 GST_OBJECT_LOCK (demux);
3429 if (demux->common.segment.duration == -1 ||
3430 demux->common.segment.duration < lace_time) {
3431 gst_segment_set_duration (&demux->common.segment, GST_FORMAT_TIME,
3433 GST_OBJECT_UNLOCK (demux);
3434 gst_element_post_message (GST_ELEMENT_CAST (demux),
3435 gst_message_new_duration (GST_OBJECT_CAST (demux),
3436 GST_FORMAT_TIME, GST_CLOCK_TIME_NONE));
3438 GST_OBJECT_UNLOCK (demux);
3442 stream->pos = lace_time;
3444 gst_matroska_demux_sync_streams (demux);
3446 if (stream->set_discont) {
3447 GST_DEBUG_OBJECT (demux, "marking DISCONT");
3448 GST_BUFFER_FLAG_SET (sub, GST_BUFFER_FLAG_DISCONT);
3449 stream->set_discont = FALSE;
3452 /* reverse playback book-keeping */
3453 if (!GST_CLOCK_TIME_IS_VALID (stream->from_time))
3454 stream->from_time = lace_time;
3455 if (stream->from_offset == -1)
3456 stream->from_offset = offset;
3458 GST_DEBUG_OBJECT (demux,
3459 "Pushing lace %d, data of size %d for stream %d, time=%"
3460 GST_TIME_FORMAT " and duration=%" GST_TIME_FORMAT, n,
3461 GST_BUFFER_SIZE (sub), stream_num,
3462 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (sub)),
3463 GST_TIME_ARGS (GST_BUFFER_DURATION (sub)));
3465 if (demux->common.element_index) {
3466 if (stream->index_writer_id == -1)
3467 gst_index_get_writer_id (demux->common.element_index,
3468 GST_OBJECT (stream->pad), &stream->index_writer_id);
3470 GST_LOG_OBJECT (demux, "adding association %" GST_TIME_FORMAT "-> %"
3471 G_GUINT64_FORMAT " for writer id %d",
3472 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (sub)), cluster_offset,
3473 stream->index_writer_id);
3474 gst_index_add_association (demux->common.element_index,
3475 stream->index_writer_id, GST_BUFFER_FLAG_IS_SET (sub,
3476 GST_BUFFER_FLAG_DELTA_UNIT) ? 0 : GST_ASSOCIATION_FLAG_KEY_UNIT,
3477 GST_FORMAT_TIME, GST_BUFFER_TIMESTAMP (sub), GST_FORMAT_BYTES,
3478 cluster_offset, NULL);
3481 gst_buffer_set_caps (sub, GST_PAD_CAPS (stream->pad));
3483 /* Postprocess the buffers depending on the codec used */
3484 if (stream->postprocess_frame) {
3485 GST_LOG_OBJECT (demux, "running post process");
3486 ret = stream->postprocess_frame (GST_ELEMENT (demux), stream, &sub);
3489 ret = gst_pad_push (stream->pad, sub);
3490 if (demux->common.segment.rate < 0) {
3491 if (lace_time > demux->common.segment.stop
3492 && ret == GST_FLOW_UNEXPECTED) {
3493 /* In reverse playback we can get a GST_FLOW_UNEXPECTED when
3494 * we are at the end of the segment, so we just need to jump
3495 * back to the previous section. */
3496 GST_DEBUG_OBJECT (demux, "downstream has reached end of segment");
3501 ret = gst_matroska_demux_combine_flows (demux, stream, ret);
3504 size -= lace_size[n];
3505 if (lace_time != GST_CLOCK_TIME_NONE && duration)
3506 lace_time += duration / laces;
3508 lace_time = GST_CLOCK_TIME_NONE;
3514 gst_buffer_unref (buf);
3525 ret = gst_matroska_demux_combine_flows (demux, stream, ret);
3530 GST_ELEMENT_WARNING (demux, STREAM, DEMUX, (NULL), ("Invalid lacing size"));
3531 /* non-fatal, try next block(group) */
3537 GST_ELEMENT_WARNING (demux, STREAM, DEMUX, (NULL), ("Data error"));
3538 /* non-fatal, try next block(group) */
3544 /* return FALSE if block(group) should be skipped (due to a seek) */
3545 static inline gboolean
3546 gst_matroska_demux_seek_block (GstMatroskaDemux * demux)
3548 if (G_UNLIKELY (demux->seek_block)) {
3549 if (!(--demux->seek_block)) {
3552 GST_LOG_OBJECT (demux, "should skip block due to seek");
3560 static GstFlowReturn
3561 gst_matroska_demux_parse_contents_seekentry (GstMatroskaDemux * demux,
3565 guint64 seek_pos = (guint64) - 1;
3566 guint32 seek_id = 0;
3569 DEBUG_ELEMENT_START (demux, ebml, "Seek");
3571 if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
3572 DEBUG_ELEMENT_STOP (demux, ebml, "Seek", ret);
3576 while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
3577 if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
3581 case GST_MATROSKA_ID_SEEKID:
3585 if ((ret = gst_ebml_read_uint (ebml, &id, &t)) != GST_FLOW_OK)
3588 GST_DEBUG_OBJECT (demux, "SeekID: %" G_GUINT64_FORMAT, t);
3593 case GST_MATROSKA_ID_SEEKPOSITION:
3597 if ((ret = gst_ebml_read_uint (ebml, &id, &t)) != GST_FLOW_OK)
3600 if (t > G_MAXINT64) {
3601 GST_WARNING_OBJECT (demux,
3602 "Too large SeekPosition %" G_GUINT64_FORMAT, t);
3606 GST_DEBUG_OBJECT (demux, "SeekPosition: %" G_GUINT64_FORMAT, t);
3612 ret = gst_matroska_read_common_parse_skip (&demux->common, ebml,
3618 if (ret != GST_FLOW_OK && ret != GST_FLOW_UNEXPECTED)
3621 if (!seek_id || seek_pos == (guint64) - 1) {
3622 GST_WARNING_OBJECT (demux, "Incomplete seekhead entry (0x%x/%"
3623 G_GUINT64_FORMAT ")", seek_id, seek_pos);
3628 case GST_MATROSKA_ID_SEEKHEAD:
3631 case GST_MATROSKA_ID_CUES:
3632 case GST_MATROSKA_ID_TAGS:
3633 case GST_MATROSKA_ID_TRACKS:
3634 case GST_MATROSKA_ID_SEGMENTINFO:
3635 case GST_MATROSKA_ID_ATTACHMENTS:
3636 case GST_MATROSKA_ID_CHAPTERS:
3638 guint64 before_pos, length;
3642 length = gst_matroska_read_common_get_length (&demux->common);
3643 before_pos = demux->common.offset;
3645 if (length == (guint64) - 1) {
3646 GST_DEBUG_OBJECT (demux, "no upstream length, skipping SeakHead entry");
3650 /* check for validity */
3651 if (seek_pos + demux->common.ebml_segment_start + 12 >= length) {
3652 GST_WARNING_OBJECT (demux,
3653 "SeekHead reference lies outside file!" " (%"
3654 G_GUINT64_FORMAT "+%" G_GUINT64_FORMAT "+12 >= %"
3655 G_GUINT64_FORMAT ")", seek_pos, demux->common.ebml_segment_start,
3660 /* only pick up index location when streaming */
3661 if (demux->streaming) {
3662 if (seek_id == GST_MATROSKA_ID_CUES) {
3663 demux->index_offset = seek_pos + demux->common.ebml_segment_start;
3664 GST_DEBUG_OBJECT (demux, "Cues located at offset %" G_GUINT64_FORMAT,
3665 demux->index_offset);
3671 demux->common.offset = seek_pos + demux->common.ebml_segment_start;
3674 if ((ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
3675 GST_ELEMENT_CAST (demux), &id, &length, &needed)) !=
3679 if (id != seek_id) {
3680 GST_WARNING_OBJECT (demux,
3681 "We looked for ID=0x%x but got ID=0x%x (pos=%" G_GUINT64_FORMAT ")",
3682 seek_id, id, seek_pos + demux->common.ebml_segment_start);
3685 ret = gst_matroska_demux_parse_id (demux, id, length, needed);
3690 demux->common.offset = before_pos;
3694 case GST_MATROSKA_ID_CLUSTER:
3696 guint64 pos = seek_pos + demux->common.ebml_segment_start;
3698 GST_LOG_OBJECT (demux, "Cluster position");
3699 if (G_UNLIKELY (!demux->clusters))
3700 demux->clusters = g_array_sized_new (TRUE, TRUE, sizeof (guint64), 100);
3701 g_array_append_val (demux->clusters, pos);
3706 GST_DEBUG_OBJECT (demux, "Ignoring Seek entry for ID=0x%x", seek_id);
3709 DEBUG_ELEMENT_STOP (demux, ebml, "Seek", ret);
3714 static GstFlowReturn
3715 gst_matroska_demux_parse_contents (GstMatroskaDemux * demux, GstEbmlRead * ebml)
3717 GstFlowReturn ret = GST_FLOW_OK;
3720 DEBUG_ELEMENT_START (demux, ebml, "SeekHead");
3722 if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
3723 DEBUG_ELEMENT_STOP (demux, ebml, "SeekHead", ret);
3727 while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
3728 if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
3732 case GST_MATROSKA_ID_SEEKENTRY:
3734 ret = gst_matroska_demux_parse_contents_seekentry (demux, ebml);
3735 /* Ignore EOS and errors here */
3736 if (ret != GST_FLOW_OK) {
3737 GST_DEBUG_OBJECT (demux, "Ignoring %s", gst_flow_get_name (ret));
3744 ret = gst_matroska_read_common_parse_skip (&demux->common,
3745 ebml, "SeekHead", id);
3750 DEBUG_ELEMENT_STOP (demux, ebml, "SeekHead", ret);
3752 /* Sort clusters by position for easier searching */
3753 if (demux->clusters)
3754 g_array_sort (demux->clusters, (GCompareFunc) gst_matroska_cluster_compare);
3759 #define GST_FLOW_OVERFLOW GST_FLOW_CUSTOM_ERROR
3761 #define MAX_BLOCK_SIZE (15 * 1024 * 1024)
3763 static inline GstFlowReturn
3764 gst_matroska_demux_check_read_size (GstMatroskaDemux * demux, guint64 bytes)
3766 if (G_UNLIKELY (bytes > MAX_BLOCK_SIZE)) {
3767 /* only a few blocks are expected/allowed to be large,
3768 * and will be recursed into, whereas others will be read and must fit */
3769 if (demux->streaming) {
3770 /* fatal in streaming case, as we can't step over easily */
3771 GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
3772 ("reading large block of size %" G_GUINT64_FORMAT " not supported; "
3773 "file might be corrupt.", bytes));
3774 return GST_FLOW_ERROR;
3776 /* indicate higher level to quietly give up */
3777 GST_DEBUG_OBJECT (demux,
3778 "too large block of size %" G_GUINT64_FORMAT, bytes);
3779 return GST_FLOW_ERROR;
3786 /* returns TRUE if we truely are in error state, and should give up */
3787 static inline gboolean
3788 gst_matroska_demux_check_parse_error (GstMatroskaDemux * demux)
3790 if (!demux->streaming && demux->next_cluster_offset > 0) {
3791 /* just repositioning to where next cluster should be and try from there */
3792 GST_WARNING_OBJECT (demux, "parse error, trying next cluster expected at %"
3793 G_GUINT64_FORMAT, demux->next_cluster_offset);
3794 demux->common.offset = demux->next_cluster_offset;
3795 demux->next_cluster_offset = 0;
3800 /* sigh, one last attempt above and beyond call of duty ...;
3801 * search for cluster mark following current pos */
3802 pos = demux->common.offset;
3803 GST_WARNING_OBJECT (demux, "parse error, looking for next cluster");
3804 if (gst_matroska_demux_search_cluster (demux, &pos) != GST_FLOW_OK) {
3805 /* did not work, give up */
3808 GST_DEBUG_OBJECT (demux, "... found at %" G_GUINT64_FORMAT, pos);
3809 /* try that position */
3810 demux->common.offset = pos;
3816 static inline GstFlowReturn
3817 gst_matroska_demux_flush (GstMatroskaDemux * demux, guint flush)
3819 GST_LOG_OBJECT (demux, "skipping %d bytes", flush);
3820 demux->common.offset += flush;
3821 if (demux->streaming) {
3824 /* hard to skip large blocks when streaming */
3825 ret = gst_matroska_demux_check_read_size (demux, flush);
3826 if (ret != GST_FLOW_OK)
3828 if (flush <= gst_adapter_available (demux->common.adapter))
3829 gst_adapter_flush (demux->common.adapter, flush);
3831 return GST_FLOW_UNEXPECTED;
3836 /* initializes @ebml with @bytes from input stream at current offset.
3837 * Returns UNEXPECTED if insufficient available,
3838 * ERROR if too much was attempted to read. */
3839 static inline GstFlowReturn
3840 gst_matroska_demux_take (GstMatroskaDemux * demux, guint64 bytes,
3843 GstBuffer *buffer = NULL;
3844 GstFlowReturn ret = GST_FLOW_OK;
3846 GST_LOG_OBJECT (demux, "taking %" G_GUINT64_FORMAT " bytes for parsing",
3848 ret = gst_matroska_demux_check_read_size (demux, bytes);
3849 if (G_UNLIKELY (ret != GST_FLOW_OK)) {
3850 if (!demux->streaming) {
3851 /* in pull mode, we can skip */
3852 if ((ret = gst_matroska_demux_flush (demux, bytes)) == GST_FLOW_OK)
3853 ret = GST_FLOW_OVERFLOW;
3855 /* otherwise fatal */
3856 ret = GST_FLOW_ERROR;
3860 if (demux->streaming) {
3861 if (gst_adapter_available (demux->common.adapter) >= bytes)
3862 buffer = gst_adapter_take_buffer (demux->common.adapter, bytes);
3864 ret = GST_FLOW_UNEXPECTED;
3866 ret = gst_matroska_read_common_peek_bytes (&demux->common,
3867 demux->common.offset, bytes, &buffer, NULL);
3868 if (G_LIKELY (buffer)) {
3869 gst_ebml_read_init (ebml, GST_ELEMENT_CAST (demux), buffer,
3870 demux->common.offset);
3871 demux->common.offset += bytes;
3878 gst_matroska_demux_check_seekability (GstMatroskaDemux * demux)
3881 gboolean seekable = FALSE;
3882 gint64 start = -1, stop = -1;
3884 query = gst_query_new_seeking (GST_FORMAT_BYTES);
3885 if (!gst_pad_peer_query (demux->common.sinkpad, query)) {
3886 GST_DEBUG_OBJECT (demux, "seeking query failed");
3890 gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
3892 /* try harder to query upstream size if we didn't get it the first time */
3893 if (seekable && stop == -1) {
3894 GstFormat fmt = GST_FORMAT_BYTES;
3896 GST_DEBUG_OBJECT (demux, "doing duration query to fix up unset stop");
3897 gst_pad_query_peer_duration (demux->common.sinkpad, &fmt, &stop);
3900 /* if upstream doesn't know the size, it's likely that it's not seekable in
3901 * practice even if it technically may be seekable */
3902 if (seekable && (start != 0 || stop <= start)) {
3903 GST_DEBUG_OBJECT (demux, "seekable but unknown start/stop -> disable");
3908 GST_INFO_OBJECT (demux, "seekable: %d (%" G_GUINT64_FORMAT " - %"
3909 G_GUINT64_FORMAT ")", seekable, start, stop);
3910 demux->seekable = seekable;
3912 gst_query_unref (query);
3915 static GstFlowReturn
3916 gst_matroska_demux_find_tracks (GstMatroskaDemux * demux)
3922 GstFlowReturn ret = GST_FLOW_OK;
3924 GST_WARNING_OBJECT (demux,
3925 "Found Cluster element before Tracks, searching Tracks");
3928 before_pos = demux->common.offset;
3930 /* Search Tracks element */
3932 ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
3933 GST_ELEMENT_CAST (demux), &id, &length, &needed);
3934 if (ret != GST_FLOW_OK)
3937 if (id != GST_MATROSKA_ID_TRACKS) {
3938 /* we may be skipping large cluster here, so forego size check etc */
3939 /* ... but we can't skip undefined size; force error */
3940 if (length == G_MAXUINT64) {
3941 ret = gst_matroska_demux_check_read_size (demux, length);
3944 demux->common.offset += needed;
3945 demux->common.offset += length;
3950 /* will lead to track parsing ... */
3951 ret = gst_matroska_demux_parse_id (demux, id, length, needed);
3956 demux->common.offset = before_pos;
3961 #define GST_READ_CHECK(stmt) \
3963 if (G_UNLIKELY ((ret = (stmt)) != GST_FLOW_OK)) { \
3964 if (ret == GST_FLOW_OVERFLOW) { \
3965 ret = GST_FLOW_OK; \
3971 static GstFlowReturn
3972 gst_matroska_demux_parse_id (GstMatroskaDemux * demux, guint32 id,
3973 guint64 length, guint needed)
3975 GstEbmlRead ebml = { 0, };
3976 GstFlowReturn ret = GST_FLOW_OK;
3979 GST_LOG_OBJECT (demux, "Parsing Element id 0x%x, "
3980 "size %" G_GUINT64_FORMAT ", prefix %d", id, length, needed);
3982 /* if we plan to read and parse this element, we need prefix (id + length)
3983 * and the contents */
3984 /* mind about overflow wrap-around when dealing with undefined size */
3986 if (G_LIKELY (length != G_MAXUINT64))
3989 switch (demux->common.state) {
3990 case GST_MATROSKA_READ_STATE_START:
3992 case GST_EBML_ID_HEADER:
3993 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
3994 ret = gst_matroska_read_common_parse_header (&demux->common, &ebml);
3995 if (ret != GST_FLOW_OK)
3997 demux->common.state = GST_MATROSKA_READ_STATE_SEGMENT;
3998 gst_matroska_demux_check_seekability (demux);
4001 goto invalid_header;
4005 case GST_MATROSKA_READ_STATE_SEGMENT:
4007 case GST_MATROSKA_ID_SEGMENT:
4008 /* eat segment prefix */
4009 GST_READ_CHECK (gst_matroska_demux_flush (demux, needed));
4010 GST_DEBUG_OBJECT (demux,
4011 "Found Segment start at offset %" G_GUINT64_FORMAT,
4012 demux->common.offset);
4013 /* seeks are from the beginning of the segment,
4014 * after the segment ID/length */
4015 demux->common.ebml_segment_start = demux->common.offset;
4016 demux->common.state = GST_MATROSKA_READ_STATE_HEADER;
4019 GST_WARNING_OBJECT (demux,
4020 "Expected a Segment ID (0x%x), but received 0x%x!",
4021 GST_MATROSKA_ID_SEGMENT, id);
4022 GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
4026 case GST_MATROSKA_READ_STATE_SCANNING:
4027 if (id != GST_MATROSKA_ID_CLUSTER &&
4028 id != GST_MATROSKA_ID_CLUSTERTIMECODE)
4031 case GST_MATROSKA_READ_STATE_HEADER:
4032 case GST_MATROSKA_READ_STATE_DATA:
4033 case GST_MATROSKA_READ_STATE_SEEK:
4035 case GST_MATROSKA_ID_SEGMENTINFO:
4036 if (!demux->common.segmentinfo_parsed) {
4037 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
4038 ret = gst_matroska_read_common_parse_info (&demux->common,
4039 GST_ELEMENT_CAST (demux), &ebml);
4041 GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
4044 case GST_MATROSKA_ID_TRACKS:
4045 if (!demux->tracks_parsed) {
4046 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
4047 ret = gst_matroska_demux_parse_tracks (demux, &ebml);
4049 GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
4052 case GST_MATROSKA_ID_CLUSTER:
4053 if (G_UNLIKELY (!demux->tracks_parsed)) {
4054 if (demux->streaming) {
4055 GST_DEBUG_OBJECT (demux, "Cluster before Track");
4056 goto not_streamable;
4058 ret = gst_matroska_demux_find_tracks (demux);
4059 if (!demux->tracks_parsed)
4063 if (G_UNLIKELY (demux->common.state
4064 == GST_MATROSKA_READ_STATE_HEADER)) {
4065 demux->common.state = GST_MATROSKA_READ_STATE_DATA;
4066 demux->first_cluster_offset = demux->common.offset;
4067 GST_DEBUG_OBJECT (demux, "signaling no more pads");
4068 gst_element_no_more_pads (GST_ELEMENT (demux));
4069 /* send initial newsegment */
4070 gst_matroska_demux_send_event (demux,
4071 gst_event_new_new_segment (FALSE, 1.0,
4073 (demux->common.segment.duration >
4074 0) ? demux->common.segment.duration : -1, 0));
4076 demux->cluster_time = GST_CLOCK_TIME_NONE;
4077 demux->cluster_offset = demux->common.offset;
4078 if (G_UNLIKELY (!demux->seek_first && demux->seek_block)) {
4079 GST_DEBUG_OBJECT (demux, "seek target block %" G_GUINT64_FORMAT
4080 " not found in Cluster, trying next Cluster's first block instead",
4082 demux->seek_block = 0;
4084 demux->seek_first = FALSE;
4085 /* record next cluster for recovery */
4086 if (read != G_MAXUINT64)
4087 demux->next_cluster_offset = demux->cluster_offset + read;
4088 /* eat cluster prefix */
4089 gst_matroska_demux_flush (demux, needed);
4091 case GST_MATROSKA_ID_CLUSTERTIMECODE:
4095 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
4096 if ((ret = gst_ebml_read_uint (&ebml, &id, &num)) != GST_FLOW_OK)
4098 GST_DEBUG_OBJECT (demux, "ClusterTimeCode: %" G_GUINT64_FORMAT, num);
4099 demux->cluster_time = num;
4100 if (demux->common.element_index) {
4101 if (demux->common.element_index_writer_id == -1)
4102 gst_index_get_writer_id (demux->common.element_index,
4103 GST_OBJECT (demux), &demux->common.element_index_writer_id);
4104 GST_LOG_OBJECT (demux, "adding association %" GST_TIME_FORMAT "-> %"
4105 G_GUINT64_FORMAT " for writer id %d",
4106 GST_TIME_ARGS (demux->cluster_time), demux->cluster_offset,
4107 demux->common.element_index_writer_id);
4108 gst_index_add_association (demux->common.element_index,
4109 demux->common.element_index_writer_id,
4110 GST_ASSOCIATION_FLAG_KEY_UNIT,
4111 GST_FORMAT_TIME, demux->cluster_time,
4112 GST_FORMAT_BYTES, demux->cluster_offset, NULL);
4116 case GST_MATROSKA_ID_BLOCKGROUP:
4117 if (!gst_matroska_demux_seek_block (demux))
4119 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
4120 DEBUG_ELEMENT_START (demux, &ebml, "BlockGroup");
4121 if ((ret = gst_ebml_read_master (&ebml, &id)) == GST_FLOW_OK) {
4122 ret = gst_matroska_demux_parse_blockgroup_or_simpleblock (demux,
4123 &ebml, demux->cluster_time, demux->cluster_offset, FALSE);
4125 DEBUG_ELEMENT_STOP (demux, &ebml, "BlockGroup", ret);
4127 case GST_MATROSKA_ID_SIMPLEBLOCK:
4128 if (!gst_matroska_demux_seek_block (demux))
4130 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
4131 DEBUG_ELEMENT_START (demux, &ebml, "SimpleBlock");
4132 ret = gst_matroska_demux_parse_blockgroup_or_simpleblock (demux,
4133 &ebml, demux->cluster_time, demux->cluster_offset, TRUE);
4134 DEBUG_ELEMENT_STOP (demux, &ebml, "SimpleBlock", ret);
4136 case GST_MATROSKA_ID_ATTACHMENTS:
4137 if (!demux->common.attachments_parsed) {
4138 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
4139 ret = gst_matroska_read_common_parse_attachments (&demux->common,
4140 GST_ELEMENT_CAST (demux), &ebml);
4142 GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
4145 case GST_MATROSKA_ID_TAGS:
4146 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
4147 ret = gst_matroska_read_common_parse_metadata (&demux->common,
4148 GST_ELEMENT_CAST (demux), &ebml);
4150 case GST_MATROSKA_ID_CHAPTERS:
4151 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
4152 ret = gst_matroska_read_common_parse_chapters (&demux->common, &ebml);
4154 case GST_MATROSKA_ID_SEEKHEAD:
4155 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
4156 ret = gst_matroska_demux_parse_contents (demux, &ebml);
4158 case GST_MATROSKA_ID_CUES:
4159 if (demux->common.index_parsed) {
4160 GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
4163 GST_READ_CHECK (gst_matroska_demux_take (demux, read, &ebml));
4164 ret = gst_matroska_read_common_parse_index (&demux->common, &ebml);
4165 /* only push based; delayed index building */
4166 if (ret == GST_FLOW_OK
4167 && demux->common.state == GST_MATROSKA_READ_STATE_SEEK) {
4170 GST_OBJECT_LOCK (demux);
4171 event = demux->seek_event;
4172 demux->seek_event = NULL;
4173 GST_OBJECT_UNLOCK (demux);
4176 /* unlikely to fail, since we managed to seek to this point */
4177 if (!gst_matroska_demux_handle_seek_event (demux, NULL, event))
4179 /* resume data handling, main thread clear to seek again */
4180 GST_OBJECT_LOCK (demux);
4181 demux->common.state = GST_MATROSKA_READ_STATE_DATA;
4182 GST_OBJECT_UNLOCK (demux);
4185 case GST_MATROSKA_ID_POSITION:
4186 case GST_MATROSKA_ID_PREVSIZE:
4187 case GST_MATROSKA_ID_ENCRYPTEDBLOCK:
4188 case GST_MATROSKA_ID_SILENTTRACKS:
4189 GST_DEBUG_OBJECT (demux,
4190 "Skipping Cluster subelement 0x%x - ignoring", id);
4194 GST_DEBUG_OBJECT (demux, "skipping Element 0x%x", id);
4195 GST_READ_CHECK (gst_matroska_demux_flush (demux, read));
4201 if (ret == GST_FLOW_PARSE)
4205 gst_ebml_read_clear (&ebml);
4211 /* simply exit, maybe not enough data yet */
4212 /* no ebml to clear if read error */
4217 GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
4218 ("Failed to parse Element 0x%x", id));
4219 ret = GST_FLOW_ERROR;
4224 GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
4225 ("File layout does not permit streaming"));
4226 ret = GST_FLOW_ERROR;
4231 GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
4232 ("No Tracks element found"));
4233 ret = GST_FLOW_ERROR;
4238 GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL), ("Invalid header"));
4239 ret = GST_FLOW_ERROR;
4244 GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL), ("Failed to seek"));
4245 ret = GST_FLOW_ERROR;
4251 gst_matroska_demux_loop (GstPad * pad)
4253 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (GST_PAD_PARENT (pad));
4259 /* If we have to close a segment, send a new segment to do this now */
4260 if (G_LIKELY (demux->common.state == GST_MATROSKA_READ_STATE_DATA)) {
4261 if (G_UNLIKELY (demux->close_segment)) {
4262 gst_matroska_demux_send_event (demux, demux->close_segment);
4263 demux->close_segment = NULL;
4265 if (G_UNLIKELY (demux->new_segment)) {
4266 gst_matroska_demux_send_event (demux, demux->new_segment);
4267 demux->new_segment = NULL;
4271 ret = gst_matroska_read_common_peek_id_length_pull (&demux->common,
4272 GST_ELEMENT_CAST (demux), &id, &length, &needed);
4273 if (ret == GST_FLOW_UNEXPECTED)
4275 if (ret != GST_FLOW_OK) {
4276 if (gst_matroska_demux_check_parse_error (demux))
4282 GST_LOG_OBJECT (demux, "Offset %" G_GUINT64_FORMAT ", Element id 0x%x, "
4283 "size %" G_GUINT64_FORMAT ", needed %d", demux->common.offset, id,
4286 ret = gst_matroska_demux_parse_id (demux, id, length, needed);
4287 if (ret == GST_FLOW_UNEXPECTED)
4289 if (ret != GST_FLOW_OK)
4292 /* check if we're at the end of a configured segment */
4293 if (G_LIKELY (demux->common.src->len)) {
4296 g_assert (demux->common.num_streams == demux->common.src->len);
4297 for (i = 0; i < demux->common.src->len; i++) {
4298 GstMatroskaTrackContext *context = g_ptr_array_index (demux->common.src,
4300 GST_DEBUG_OBJECT (context->pad, "pos %" GST_TIME_FORMAT,
4301 GST_TIME_ARGS (context->pos));
4302 if (context->eos == FALSE)
4306 GST_INFO_OBJECT (demux, "All streams are EOS");
4307 ret = GST_FLOW_UNEXPECTED;
4312 if (G_UNLIKELY (demux->common.offset ==
4313 gst_matroska_read_common_get_length (&demux->common))) {
4314 GST_LOG_OBJECT (demux, "Reached end of stream");
4315 ret = GST_FLOW_UNEXPECTED;
4324 if (demux->common.segment.rate < 0.0) {
4325 ret = gst_matroska_demux_seek_to_previous_keyframe (demux);
4326 if (ret == GST_FLOW_OK)
4333 const gchar *reason = gst_flow_get_name (ret);
4334 gboolean push_eos = FALSE;
4336 GST_LOG_OBJECT (demux, "pausing task, reason %s", reason);
4337 demux->segment_running = FALSE;
4338 gst_pad_pause_task (demux->common.sinkpad);
4340 if (ret == GST_FLOW_UNEXPECTED) {
4341 /* perform EOS logic */
4343 /* Close the segment, i.e. update segment stop with the duration
4344 * if no stop was set */
4345 if (GST_CLOCK_TIME_IS_VALID (demux->last_stop_end) &&
4346 !GST_CLOCK_TIME_IS_VALID (demux->common.segment.stop)) {
4348 gst_event_new_new_segment_full (TRUE, demux->common.segment.rate,
4349 demux->common.segment.applied_rate, demux->common.segment.format,
4350 demux->common.segment.start,
4351 MAX (demux->last_stop_end, demux->common.segment.start),
4352 demux->common.segment.time);
4353 gst_matroska_demux_send_event (demux, event);
4356 if (demux->common.segment.flags & GST_SEEK_FLAG_SEGMENT) {
4359 /* for segment playback we need to post when (in stream time)
4360 * we stopped, this is either stop (when set) or the duration. */
4361 if ((stop = demux->common.segment.stop) == -1)
4362 stop = demux->last_stop_end;
4364 GST_LOG_OBJECT (demux, "Sending segment done, at end of segment");
4365 gst_element_post_message (GST_ELEMENT (demux),
4366 gst_message_new_segment_done (GST_OBJECT (demux), GST_FORMAT_TIME,
4371 } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_UNEXPECTED) {
4372 /* for fatal errors we post an error message */
4373 GST_ELEMENT_ERROR (demux, STREAM, FAILED, (NULL),
4374 ("stream stopped, reason %s", reason));
4378 /* send EOS, and prevent hanging if no streams yet */
4379 GST_LOG_OBJECT (demux, "Sending EOS, at end of stream");
4380 if (!gst_matroska_demux_send_event (demux, gst_event_new_eos ()) &&
4381 (ret == GST_FLOW_UNEXPECTED)) {
4382 GST_ELEMENT_ERROR (demux, STREAM, DEMUX,
4383 (NULL), ("got eos but no streams (yet)"));
4391 * Create and push a flushing seek event upstream
4394 perform_seek_to_offset (GstMatroskaDemux * demux, guint64 offset)
4399 GST_DEBUG_OBJECT (demux, "Seeking to %" G_GUINT64_FORMAT, offset);
4402 gst_event_new_seek (1.0, GST_FORMAT_BYTES,
4403 GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE, GST_SEEK_TYPE_SET, offset,
4404 GST_SEEK_TYPE_NONE, -1);
4406 res = gst_pad_push_event (demux->common.sinkpad, event);
4408 /* newsegment event will update offset */
4412 static GstFlowReturn
4413 gst_matroska_demux_chain (GstPad * pad, GstBuffer * buffer)
4415 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (GST_PAD_PARENT (pad));
4417 GstFlowReturn ret = GST_FLOW_OK;
4422 if (G_UNLIKELY (GST_BUFFER_IS_DISCONT (buffer))) {
4423 GST_DEBUG_OBJECT (demux, "got DISCONT");
4424 gst_adapter_clear (demux->common.adapter);
4425 GST_OBJECT_LOCK (demux);
4426 gst_matroska_read_common_reset_streams (&demux->common,
4427 GST_CLOCK_TIME_NONE, FALSE);
4428 GST_OBJECT_UNLOCK (demux);
4431 gst_adapter_push (demux->common.adapter, buffer);
4435 available = gst_adapter_available (demux->common.adapter);
4437 ret = gst_matroska_read_common_peek_id_length_push (&demux->common,
4438 GST_ELEMENT_CAST (demux), &id, &length, &needed);
4439 if (G_UNLIKELY (ret != GST_FLOW_OK && ret != GST_FLOW_UNEXPECTED))
4442 GST_LOG_OBJECT (demux, "Offset %" G_GUINT64_FORMAT ", Element id 0x%x, "
4443 "size %" G_GUINT64_FORMAT ", needed %d, available %d",
4444 demux->common.offset, id, length, needed, available);
4446 if (needed > available)
4449 ret = gst_matroska_demux_parse_id (demux, id, length, needed);
4450 if (ret == GST_FLOW_UNEXPECTED) {
4451 /* need more data */
4453 } else if (ret != GST_FLOW_OK) {
4460 gst_matroska_demux_handle_sink_event (GstPad * pad, GstEvent * event)
4462 gboolean res = TRUE;
4463 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (GST_PAD_PARENT (pad));
4465 GST_DEBUG_OBJECT (demux,
4466 "have event type %s: %p on sink pad", GST_EVENT_TYPE_NAME (event), event);
4468 switch (GST_EVENT_TYPE (event)) {
4469 case GST_EVENT_NEWSEGMENT:
4472 gdouble rate, arate;
4473 gint64 start, stop, time = 0;
4477 /* some debug output */
4478 gst_segment_init (&segment, GST_FORMAT_UNDEFINED);
4479 gst_event_parse_new_segment_full (event, &update, &rate, &arate, &format,
4480 &start, &stop, &time);
4481 gst_segment_set_newsegment_full (&segment, update, rate, arate, format,
4483 GST_DEBUG_OBJECT (demux,
4484 "received format %d newsegment %" GST_SEGMENT_FORMAT, format,
4487 if (demux->common.state < GST_MATROSKA_READ_STATE_DATA) {
4488 GST_DEBUG_OBJECT (demux, "still starting");
4492 /* we only expect a BYTE segment, e.g. following a seek */
4493 if (format != GST_FORMAT_BYTES) {
4494 GST_DEBUG_OBJECT (demux, "unsupported segment format, ignoring");
4498 GST_DEBUG_OBJECT (demux, "clearing segment state");
4499 GST_OBJECT_LOCK (demux);
4500 /* clear current segment leftover */
4501 gst_adapter_clear (demux->common.adapter);
4502 /* and some streaming setup */
4503 demux->common.offset = start;
4504 /* do not know where we are;
4505 * need to come across a cluster and generate newsegment */
4506 demux->common.segment.last_stop = GST_CLOCK_TIME_NONE;
4507 demux->cluster_time = GST_CLOCK_TIME_NONE;
4508 demux->cluster_offset = 0;
4509 demux->need_newsegment = TRUE;
4510 /* but keep some of the upstream segment */
4511 demux->common.segment.rate = rate;
4512 GST_OBJECT_UNLOCK (demux);
4514 /* chain will send initial newsegment after pads have been added,
4515 * or otherwise come up with one */
4516 GST_DEBUG_OBJECT (demux, "eating event");
4517 gst_event_unref (event);
4523 if (demux->common.state != GST_MATROSKA_READ_STATE_DATA) {
4524 gst_event_unref (event);
4525 GST_ELEMENT_ERROR (demux, STREAM, DEMUX,
4526 (NULL), ("got eos and didn't receive a complete header object"));
4527 } else if (demux->common.num_streams == 0) {
4528 GST_ELEMENT_ERROR (demux, STREAM, DEMUX,
4529 (NULL), ("got eos but no streams (yet)"));
4531 gst_matroska_demux_send_event (demux, event);
4535 case GST_EVENT_FLUSH_STOP:
4537 gst_adapter_clear (demux->common.adapter);
4538 GST_OBJECT_LOCK (demux);
4539 gst_matroska_read_common_reset_streams (&demux->common,
4540 GST_CLOCK_TIME_NONE, TRUE);
4541 demux->common.segment.last_stop = GST_CLOCK_TIME_NONE;
4542 demux->cluster_time = GST_CLOCK_TIME_NONE;
4543 demux->cluster_offset = 0;
4544 GST_OBJECT_UNLOCK (demux);
4548 res = gst_pad_event_default (pad, event);
4556 gst_matroska_demux_sink_activate (GstPad * sinkpad)
4558 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (GST_PAD_PARENT (sinkpad));
4560 if (gst_pad_check_pull_range (sinkpad)) {
4561 GST_DEBUG ("going to pull mode");
4562 demux->streaming = FALSE;
4563 return gst_pad_activate_pull (sinkpad, TRUE);
4565 GST_DEBUG ("going to push (streaming) mode");
4566 demux->streaming = TRUE;
4567 return gst_pad_activate_push (sinkpad, TRUE);
4574 gst_matroska_demux_sink_activate_pull (GstPad * sinkpad, gboolean active)
4576 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (GST_PAD_PARENT (sinkpad));
4579 /* if we have a scheduler we can start the task */
4580 demux->segment_running = TRUE;
4581 gst_pad_start_task (sinkpad, (GstTaskFunction) gst_matroska_demux_loop,
4584 demux->segment_running = FALSE;
4585 gst_pad_stop_task (sinkpad);
4592 gst_duration_to_fraction (guint64 duration, gint * dest_n, gint * dest_d)
4594 static const int common_den[] = { 1, 2, 3, 4, 1001 };
4599 for (i = 0; i < G_N_ELEMENTS (common_den); i++) {
4601 n = floor (0.5 + (d * 1e9) / duration);
4602 a = gst_util_uint64_scale_int (1000000000, d, n);
4603 if (duration >= a - 1 && duration <= a + 1) {
4608 gst_util_double_to_fraction (1e9 / duration, &n, &d);
4617 gst_matroska_demux_video_caps (GstMatroskaTrackVideoContext *
4618 videocontext, const gchar * codec_id, guint8 * data, guint size,
4619 gchar ** codec_name, guint32 * riff_fourcc)
4621 GstMatroskaTrackContext *context = (GstMatroskaTrackContext *) videocontext;
4622 GstCaps *caps = NULL;
4624 g_assert (videocontext != NULL);
4625 g_assert (codec_name != NULL);
4627 context->send_xiph_headers = FALSE;
4628 context->send_flac_headers = FALSE;
4629 context->send_speex_headers = FALSE;
4634 /* TODO: check if we have all codec types from matroska-ids.h
4635 * check if we have to do more special things with codec_private
4638 * GST_MATROSKA_CODEC_ID_VIDEO_QUICKTIME
4639 * GST_MATROSKA_CODEC_ID_VIDEO_SNOW
4642 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC)) {
4643 gst_riff_strf_vids *vids = NULL;
4646 GstBuffer *buf = NULL;
4648 vids = (gst_riff_strf_vids *) data;
4650 /* assure size is big enough */
4652 GST_WARNING ("Too small BITMAPINFOHEADER (%d bytes)", size);
4655 if (size < sizeof (gst_riff_strf_vids)) {
4656 vids = g_new (gst_riff_strf_vids, 1);
4657 memcpy (vids, data, size);
4660 /* little-endian -> byte-order */
4661 vids->size = GUINT32_FROM_LE (vids->size);
4662 vids->width = GUINT32_FROM_LE (vids->width);
4663 vids->height = GUINT32_FROM_LE (vids->height);
4664 vids->planes = GUINT16_FROM_LE (vids->planes);
4665 vids->bit_cnt = GUINT16_FROM_LE (vids->bit_cnt);
4666 vids->compression = GUINT32_FROM_LE (vids->compression);
4667 vids->image_size = GUINT32_FROM_LE (vids->image_size);
4668 vids->xpels_meter = GUINT32_FROM_LE (vids->xpels_meter);
4669 vids->ypels_meter = GUINT32_FROM_LE (vids->ypels_meter);
4670 vids->num_colors = GUINT32_FROM_LE (vids->num_colors);
4671 vids->imp_colors = GUINT32_FROM_LE (vids->imp_colors);
4673 if (size > sizeof (gst_riff_strf_vids)) { /* some extra_data */
4674 buf = gst_buffer_new_and_alloc (size - sizeof (gst_riff_strf_vids));
4675 memcpy (GST_BUFFER_DATA (buf),
4676 (guint8 *) vids + sizeof (gst_riff_strf_vids),
4677 GST_BUFFER_SIZE (buf));
4681 *riff_fourcc = vids->compression;
4683 caps = gst_riff_create_video_caps (vids->compression, NULL, vids,
4684 buf, NULL, codec_name);
4687 GST_WARNING ("Unhandled RIFF fourcc %" GST_FOURCC_FORMAT,
4688 GST_FOURCC_ARGS (vids->compression));
4692 gst_buffer_unref (buf);
4694 if (vids != (gst_riff_strf_vids *) data)
4697 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_UNCOMPRESSED)) {
4700 switch (videocontext->fourcc) {
4701 case GST_MAKE_FOURCC ('I', '4', '2', '0'):
4702 *codec_name = g_strdup ("Raw planar YUV 4:2:0");
4703 fourcc = videocontext->fourcc;
4705 case GST_MAKE_FOURCC ('Y', 'U', 'Y', '2'):
4706 *codec_name = g_strdup ("Raw packed YUV 4:2:2");
4707 fourcc = videocontext->fourcc;
4709 case GST_MAKE_FOURCC ('Y', 'V', '1', '2'):
4710 *codec_name = g_strdup ("Raw packed YUV 4:2:0");
4711 fourcc = videocontext->fourcc;
4713 case GST_MAKE_FOURCC ('U', 'Y', 'V', 'Y'):
4714 *codec_name = g_strdup ("Raw packed YUV 4:2:2");
4715 fourcc = videocontext->fourcc;
4717 case GST_MAKE_FOURCC ('A', 'Y', 'U', 'V'):
4718 *codec_name = g_strdup ("Raw packed YUV 4:4:4 with alpha channel");
4719 fourcc = videocontext->fourcc;
4723 GST_DEBUG ("Unknown fourcc %" GST_FOURCC_FORMAT,
4724 GST_FOURCC_ARGS (videocontext->fourcc));
4728 caps = gst_caps_new_simple ("video/x-raw-yuv",
4729 "format", GST_TYPE_FOURCC, fourcc, NULL);
4730 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_SP)) {
4731 caps = gst_caps_new_simple ("video/x-divx",
4732 "divxversion", G_TYPE_INT, 4, NULL);
4733 *codec_name = g_strdup ("MPEG-4 simple profile");
4734 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_ASP) ||
4735 !strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_AP)) {
4737 caps = gst_caps_new_full (gst_structure_new ("video/x-divx",
4738 "divxversion", G_TYPE_INT, 5, NULL),
4739 gst_structure_new ("video/x-xvid", NULL),
4740 gst_structure_new ("video/mpeg",
4741 "mpegversion", G_TYPE_INT, 4,
4742 "systemstream", G_TYPE_BOOLEAN, FALSE, NULL), NULL);
4744 caps = gst_caps_new_simple ("video/mpeg",
4745 "mpegversion", G_TYPE_INT, 4,
4746 "systemstream", G_TYPE_BOOLEAN, FALSE, NULL);
4748 GstBuffer *priv = gst_buffer_new_and_alloc (size);
4750 memcpy (GST_BUFFER_DATA (priv), data, size);
4751 gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
4752 gst_buffer_unref (priv);
4754 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_ASP))
4755 *codec_name = g_strdup ("MPEG-4 advanced simple profile");
4757 *codec_name = g_strdup ("MPEG-4 advanced profile");
4758 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MSMPEG4V3)) {
4760 caps = gst_caps_new_full (gst_structure_new ("video/x-divx",
4761 "divxversion", G_TYPE_INT, 3, NULL),
4762 gst_structure_new ("video/x-msmpeg",
4763 "msmpegversion", G_TYPE_INT, 43, NULL), NULL);
4765 caps = gst_caps_new_simple ("video/x-msmpeg",
4766 "msmpegversion", G_TYPE_INT, 43, NULL);
4767 *codec_name = g_strdup ("Microsoft MPEG-4 v.3");
4768 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG1) ||
4769 !strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG2)) {
4772 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG1))
4777 caps = gst_caps_new_simple ("video/mpeg",
4778 "systemstream", G_TYPE_BOOLEAN, FALSE,
4779 "mpegversion", G_TYPE_INT, mpegversion, NULL);
4780 *codec_name = g_strdup_printf ("MPEG-%d video", mpegversion);
4781 context->postprocess_frame = gst_matroska_demux_add_mpeg_seq_header;
4782 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MJPEG)) {
4783 caps = gst_caps_new_simple ("image/jpeg", NULL);
4784 *codec_name = g_strdup ("Motion-JPEG");
4785 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_MPEG4_AVC)) {
4786 caps = gst_caps_new_simple ("video/x-h264", NULL);
4788 GstBuffer *priv = gst_buffer_new_and_alloc (size);
4790 /* First byte is the version, second is the profile indication, and third
4791 * is the 5 contraint_set_flags and 3 reserved bits. Fourth byte is the
4792 * level indication. */
4793 gst_codec_utils_h264_caps_set_level_and_profile (caps, data + 1,
4796 memcpy (GST_BUFFER_DATA (priv), data, size);
4797 gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
4798 gst_buffer_unref (priv);
4800 gst_caps_set_simple (caps, "stream-format", G_TYPE_STRING, "avc",
4801 "alignment", G_TYPE_STRING, "au", NULL);
4803 GST_WARNING ("No codec data found, assuming output is byte-stream");
4804 gst_caps_set_simple (caps, "stream-format", G_TYPE_STRING, "byte-stream",
4807 *codec_name = g_strdup ("H264");
4808 } else if ((!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO1)) ||
4809 (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO2)) ||
4810 (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO3)) ||
4811 (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO4))) {
4812 gint rmversion = -1;
4814 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO1))
4816 else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO2))
4818 else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO3))
4820 else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_REALVIDEO4))
4823 caps = gst_caps_new_simple ("video/x-pn-realvideo",
4824 "rmversion", G_TYPE_INT, rmversion, NULL);
4825 GST_DEBUG ("data:%p, size:0x%x", data, size);
4826 /* We need to extract the extradata ! */
4827 if (data && (size >= 0x22)) {
4832 subformat = GST_READ_UINT32_BE (data + 0x1a);
4833 rformat = GST_READ_UINT32_BE (data + 0x1e);
4835 priv = gst_buffer_new_and_alloc (size - 0x1a);
4837 memcpy (GST_BUFFER_DATA (priv), data + 0x1a, size - 0x1a);
4838 gst_caps_set_simple (caps,
4839 "codec_data", GST_TYPE_BUFFER, priv,
4840 "format", G_TYPE_INT, rformat,
4841 "subformat", G_TYPE_INT, subformat, NULL);
4842 gst_buffer_unref (priv);
4845 *codec_name = g_strdup_printf ("RealVideo %d.0", rmversion);
4846 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_THEORA)) {
4847 caps = gst_caps_new_simple ("video/x-theora", NULL);
4848 context->send_xiph_headers = TRUE;
4849 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_DIRAC)) {
4850 caps = gst_caps_new_simple ("video/x-dirac", NULL);
4851 *codec_name = g_strdup_printf ("Dirac");
4852 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_VIDEO_VP8)) {
4853 caps = gst_caps_new_simple ("video/x-vp8", NULL);
4854 *codec_name = g_strdup_printf ("On2 VP8");
4856 GST_WARNING ("Unknown codec '%s', cannot build Caps", codec_id);
4862 GstStructure *structure;
4864 for (i = 0; i < gst_caps_get_size (caps); i++) {
4865 structure = gst_caps_get_structure (caps, i);
4867 /* FIXME: use the real unit here! */
4868 GST_DEBUG ("video size %dx%d, target display size %dx%d (any unit)",
4869 videocontext->pixel_width,
4870 videocontext->pixel_height,
4871 videocontext->display_width, videocontext->display_height);
4873 /* pixel width and height are the w and h of the video in pixels */
4874 if (videocontext->pixel_width > 0 && videocontext->pixel_height > 0) {
4875 gint w = videocontext->pixel_width;
4877 gint h = videocontext->pixel_height;
4879 gst_structure_set (structure,
4880 "width", G_TYPE_INT, w, "height", G_TYPE_INT, h, NULL);
4883 if (videocontext->display_width > 0 && videocontext->display_height > 0) {
4886 /* calculate the pixel aspect ratio using the display and pixel w/h */
4887 n = videocontext->display_width * videocontext->pixel_height;
4888 d = videocontext->display_height * videocontext->pixel_width;
4889 GST_DEBUG ("setting PAR to %d/%d", n, d);
4890 gst_structure_set (structure, "pixel-aspect-ratio",
4892 videocontext->display_width * videocontext->pixel_height,
4893 videocontext->display_height * videocontext->pixel_width, NULL);
4896 if (videocontext->default_fps > 0.0) {
4897 GValue fps_double = { 0, };
4898 GValue fps_fraction = { 0, };
4900 g_value_init (&fps_double, G_TYPE_DOUBLE);
4901 g_value_init (&fps_fraction, GST_TYPE_FRACTION);
4902 g_value_set_double (&fps_double, videocontext->default_fps);
4903 g_value_transform (&fps_double, &fps_fraction);
4905 GST_DEBUG ("using default fps %f", videocontext->default_fps);
4907 gst_structure_set_value (structure, "framerate", &fps_fraction);
4908 g_value_unset (&fps_double);
4909 g_value_unset (&fps_fraction);
4910 } else if (context->default_duration > 0) {
4913 gst_duration_to_fraction (context->default_duration, &fps_n, &fps_d);
4915 GST_INFO ("using default duration %" G_GUINT64_FORMAT
4916 " framerate %d/%d", context->default_duration, fps_n, fps_d);
4918 gst_structure_set (structure, "framerate", GST_TYPE_FRACTION,
4919 fps_n, fps_d, NULL);
4921 /* sort of a hack to get most codecs to support,
4922 * even if the default_duration is missing */
4923 gst_structure_set (structure, "framerate", GST_TYPE_FRACTION,
4927 if (videocontext->parent.flags & GST_MATROSKA_VIDEOTRACK_INTERLACED)
4928 gst_structure_set (structure, "interlaced", G_TYPE_BOOLEAN, TRUE, NULL);
4931 gst_caps_do_simplify (caps);
4938 * Some AAC specific code... *sigh*
4939 * FIXME: maybe we should use '15' and code the sample rate explicitly
4940 * if the sample rate doesn't match the predefined rates exactly? (tpm)
4944 aac_rate_idx (gint rate)
4948 else if (75132 <= rate)
4950 else if (55426 <= rate)
4952 else if (46009 <= rate)
4954 else if (37566 <= rate)
4956 else if (27713 <= rate)
4958 else if (23004 <= rate)
4960 else if (18783 <= rate)
4962 else if (13856 <= rate)
4964 else if (11502 <= rate)
4966 else if (9391 <= rate)
4973 aac_profile_idx (const gchar * codec_id)
4977 if (strlen (codec_id) <= 12)
4979 else if (!strncmp (&codec_id[12], "MAIN", 4))
4981 else if (!strncmp (&codec_id[12], "LC", 2))
4983 else if (!strncmp (&codec_id[12], "SSR", 3))
4991 #define AAC_SYNC_EXTENSION_TYPE 0x02b7
4994 gst_matroska_demux_audio_caps (GstMatroskaTrackAudioContext *
4995 audiocontext, const gchar * codec_id, guint8 * data, guint size,
4996 gchar ** codec_name, guint16 * riff_audio_fmt)
4998 GstMatroskaTrackContext *context = (GstMatroskaTrackContext *) audiocontext;
4999 GstCaps *caps = NULL;
5001 g_assert (audiocontext != NULL);
5002 g_assert (codec_name != NULL);
5005 *riff_audio_fmt = 0;
5007 context->send_xiph_headers = FALSE;
5008 context->send_flac_headers = FALSE;
5009 context->send_speex_headers = FALSE;
5011 /* TODO: check if we have all codec types from matroska-ids.h
5012 * check if we have to do more special things with codec_private
5013 * check if we need bitdepth in different places too
5014 * implement channel position magic
5016 * GST_MATROSKA_CODEC_ID_AUDIO_AC3_BSID9
5017 * GST_MATROSKA_CODEC_ID_AUDIO_AC3_BSID10
5018 * GST_MATROSKA_CODEC_ID_AUDIO_QUICKTIME_QDMC
5019 * GST_MATROSKA_CODEC_ID_AUDIO_QUICKTIME_QDM2
5022 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L1) ||
5023 !strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L2) ||
5024 !strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L3)) {
5027 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L1))
5029 else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_MPEG1_L2))
5034 caps = gst_caps_new_simple ("audio/mpeg",
5035 "mpegversion", G_TYPE_INT, 1, "layer", G_TYPE_INT, layer, NULL);
5036 *codec_name = g_strdup_printf ("MPEG-1 layer %d", layer);
5037 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_PCM_INT_BE) ||
5038 !strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_PCM_INT_LE)) {
5041 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_PCM_INT_BE))
5042 endianness = G_BIG_ENDIAN;
5044 endianness = G_LITTLE_ENDIAN;
5046 caps = gst_caps_new_simple ("audio/x-raw-int",
5047 "width", G_TYPE_INT, audiocontext->bitdepth,
5048 "depth", G_TYPE_INT, audiocontext->bitdepth,
5049 "signed", G_TYPE_BOOLEAN, audiocontext->bitdepth != 8,
5050 "endianness", G_TYPE_INT, endianness, NULL);
5052 *codec_name = g_strdup_printf ("Raw %d-bit PCM audio",
5053 audiocontext->bitdepth);
5054 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_PCM_FLOAT)) {
5055 caps = gst_caps_new_simple ("audio/x-raw-float",
5056 "endianness", G_TYPE_INT, G_LITTLE_ENDIAN,
5057 "width", G_TYPE_INT, audiocontext->bitdepth, NULL);
5058 *codec_name = g_strdup_printf ("Raw %d-bit floating-point audio",
5059 audiocontext->bitdepth);
5060 } else if (!strncmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_AC3,
5061 strlen (GST_MATROSKA_CODEC_ID_AUDIO_AC3))) {
5062 caps = gst_caps_new_simple ("audio/x-ac3",
5063 "framed", G_TYPE_BOOLEAN, TRUE, NULL);
5064 *codec_name = g_strdup ("AC-3 audio");
5065 } else if (!strncmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_EAC3,
5066 strlen (GST_MATROSKA_CODEC_ID_AUDIO_EAC3))) {
5067 caps = gst_caps_new_simple ("audio/x-eac3",
5068 "framed", G_TYPE_BOOLEAN, TRUE, NULL);
5069 *codec_name = g_strdup ("E-AC-3 audio");
5070 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_DTS)) {
5071 caps = gst_caps_new_simple ("audio/x-dts", NULL);
5072 *codec_name = g_strdup ("DTS audio");
5073 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_VORBIS)) {
5074 caps = gst_caps_new_simple ("audio/x-vorbis", NULL);
5075 context->send_xiph_headers = TRUE;
5076 /* vorbis decoder does tags */
5077 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_FLAC)) {
5078 caps = gst_caps_new_simple ("audio/x-flac", NULL);
5079 context->send_flac_headers = TRUE;
5080 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_SPEEX)) {
5081 caps = gst_caps_new_simple ("audio/x-speex", NULL);
5082 context->send_speex_headers = TRUE;
5083 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_ACM)) {
5084 gst_riff_strf_auds auds;
5087 GstBuffer *codec_data = gst_buffer_new ();
5089 /* little-endian -> byte-order */
5090 auds.format = GST_READ_UINT16_LE (data);
5091 auds.channels = GST_READ_UINT16_LE (data + 2);
5092 auds.rate = GST_READ_UINT32_LE (data + 4);
5093 auds.av_bps = GST_READ_UINT32_LE (data + 8);
5094 auds.blockalign = GST_READ_UINT16_LE (data + 12);
5095 auds.size = GST_READ_UINT16_LE (data + 16);
5097 /* 18 is the waveformatex size */
5098 gst_buffer_set_data (codec_data, data + 18, auds.size);
5101 *riff_audio_fmt = auds.format;
5103 caps = gst_riff_create_audio_caps (auds.format, NULL, &auds, NULL,
5104 codec_data, codec_name);
5105 gst_buffer_unref (codec_data);
5108 GST_WARNING ("Unhandled RIFF audio format 0x%02x", auds.format);
5111 } else if (g_str_has_prefix (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_AAC)) {
5112 GstBuffer *priv = NULL;
5114 gint rate_idx, profile;
5115 guint8 *data = NULL;
5117 /* unspecified AAC profile with opaque private codec data */
5118 if (strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_AAC) == 0) {
5119 if (context->codec_priv_size >= 2) {
5120 guint obj_type, freq_index, explicit_freq_bytes = 0;
5122 codec_id = GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG4;
5124 freq_index = (GST_READ_UINT16_BE (context->codec_priv) & 0x780) >> 7;
5125 obj_type = (GST_READ_UINT16_BE (context->codec_priv) & 0xF800) >> 11;
5126 if (freq_index == 15)
5127 explicit_freq_bytes = 3;
5128 GST_DEBUG ("obj_type = %u, freq_index = %u", obj_type, freq_index);
5129 priv = gst_buffer_new_and_alloc (context->codec_priv_size);
5130 memcpy (GST_BUFFER_DATA (priv), context->codec_priv,
5131 context->codec_priv_size);
5132 /* assume SBR if samplerate <= 24kHz */
5133 if (obj_type == 5 || (freq_index >= 6 && freq_index != 15) ||
5134 (context->codec_priv_size == (5 + explicit_freq_bytes))) {
5135 audiocontext->samplerate *= 2;
5138 GST_WARNING ("Opaque A_AAC codec ID, but no codec private data");
5139 /* this is pretty broken;
5140 * maybe we need to make up some default private,
5141 * or maybe ADTS data got dumped in.
5142 * Let's set up some private data now, and check actual data later */
5143 /* just try this and see what happens ... */
5144 codec_id = GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG4;
5145 context->postprocess_frame = gst_matroska_demux_check_aac;
5149 /* make up decoder-specific data if it is not supplied */
5151 priv = gst_buffer_new_and_alloc (5);
5152 data = GST_BUFFER_DATA (priv);
5153 rate_idx = aac_rate_idx (audiocontext->samplerate);
5154 profile = aac_profile_idx (codec_id);
5156 data[0] = ((profile + 1) << 3) | ((rate_idx & 0xE) >> 1);
5157 data[1] = ((rate_idx & 0x1) << 7) | (audiocontext->channels << 3);
5158 GST_BUFFER_SIZE (priv) = 2;
5160 if (!strncmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG2,
5161 strlen (GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG2))) {
5163 } else if (!strncmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG4,
5164 strlen (GST_MATROSKA_CODEC_ID_AUDIO_AAC_MPEG4))) {
5167 if (g_strrstr (codec_id, "SBR")) {
5168 /* HE-AAC (aka SBR AAC) */
5169 audiocontext->samplerate *= 2;
5170 rate_idx = aac_rate_idx (audiocontext->samplerate);
5171 data[2] = AAC_SYNC_EXTENSION_TYPE >> 3;
5172 data[3] = ((AAC_SYNC_EXTENSION_TYPE & 0x07) << 5) | 5;
5173 data[4] = (1 << 7) | (rate_idx << 3);
5174 GST_BUFFER_SIZE (priv) = 5;
5177 gst_buffer_unref (priv);
5179 GST_ERROR ("Unknown AAC profile and no codec private data");
5184 caps = gst_caps_new_simple ("audio/mpeg",
5185 "mpegversion", G_TYPE_INT, mpegversion,
5186 "framed", G_TYPE_BOOLEAN, TRUE, NULL);
5187 gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
5188 *codec_name = g_strdup_printf ("MPEG-%d AAC audio", mpegversion);
5190 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_TTA)) {
5191 caps = gst_caps_new_simple ("audio/x-tta",
5192 "width", G_TYPE_INT, audiocontext->bitdepth, NULL);
5193 *codec_name = g_strdup ("TTA audio");
5194 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_WAVPACK4)) {
5195 caps = gst_caps_new_simple ("audio/x-wavpack",
5196 "width", G_TYPE_INT, audiocontext->bitdepth,
5197 "framed", G_TYPE_BOOLEAN, TRUE, NULL);
5198 *codec_name = g_strdup ("Wavpack audio");
5199 context->postprocess_frame = gst_matroska_demux_add_wvpk_header;
5200 audiocontext->wvpk_block_index = 0;
5201 } else if ((!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_14_4)) ||
5202 (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_14_4)) ||
5203 (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_COOK))) {
5204 gint raversion = -1;
5206 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_14_4))
5208 else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_COOK))
5213 caps = gst_caps_new_simple ("audio/x-pn-realaudio",
5214 "raversion", G_TYPE_INT, raversion, NULL);
5215 /* Extract extra information from caps, mapping varies based on codec */
5216 if (data && (size >= 0x50)) {
5223 guint extra_data_size;
5225 GST_ERROR ("real audio raversion:%d", raversion);
5226 if (raversion == 8) {
5228 flavor = GST_READ_UINT16_BE (data + 22);
5229 packet_size = GST_READ_UINT32_BE (data + 24);
5230 height = GST_READ_UINT16_BE (data + 40);
5231 leaf_size = GST_READ_UINT16_BE (data + 44);
5232 sample_width = GST_READ_UINT16_BE (data + 58);
5233 extra_data_size = GST_READ_UINT32_BE (data + 74);
5236 ("flavor:%d, packet_size:%d, height:%d, leaf_size:%d, sample_width:%d, extra_data_size:%d",
5237 flavor, packet_size, height, leaf_size, sample_width,
5239 gst_caps_set_simple (caps, "flavor", G_TYPE_INT, flavor, "packet_size",
5240 G_TYPE_INT, packet_size, "height", G_TYPE_INT, height, "leaf_size",
5241 G_TYPE_INT, leaf_size, "width", G_TYPE_INT, sample_width, NULL);
5243 if ((size - 78) >= extra_data_size) {
5244 priv = gst_buffer_new_and_alloc (extra_data_size);
5245 memcpy (GST_BUFFER_DATA (priv), data + 78, extra_data_size);
5246 gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, priv, NULL);
5247 gst_buffer_unref (priv);
5252 *codec_name = g_strdup_printf ("RealAudio %d.0", raversion);
5253 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_SIPR)) {
5254 caps = gst_caps_new_simple ("audio/x-sipro", NULL);
5255 *codec_name = g_strdup ("Sipro/ACELP.NET Voice Codec");
5256 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_RALF)) {
5257 caps = gst_caps_new_simple ("audio/x-ralf-mpeg4-generic", NULL);
5258 *codec_name = g_strdup ("Real Audio Lossless");
5259 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_AUDIO_REAL_ATRC)) {
5260 caps = gst_caps_new_simple ("audio/x-vnd.sony.atrac3", NULL);
5261 *codec_name = g_strdup ("Sony ATRAC3");
5263 GST_WARNING ("Unknown codec '%s', cannot build Caps", codec_id);
5268 if (audiocontext->samplerate > 0 && audiocontext->channels > 0) {
5271 for (i = 0; i < gst_caps_get_size (caps); i++) {
5272 gst_structure_set (gst_caps_get_structure (caps, i),
5273 "channels", G_TYPE_INT, audiocontext->channels,
5274 "rate", G_TYPE_INT, audiocontext->samplerate, NULL);
5278 gst_caps_do_simplify (caps);
5285 gst_matroska_demux_subtitle_caps (GstMatroskaTrackSubtitleContext *
5286 subtitlecontext, const gchar * codec_id, gpointer data, guint size)
5288 GstCaps *caps = NULL;
5289 GstMatroskaTrackContext *context =
5290 (GstMatroskaTrackContext *) subtitlecontext;
5292 /* for backwards compatibility */
5293 if (!g_ascii_strcasecmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_ASCII))
5294 codec_id = GST_MATROSKA_CODEC_ID_SUBTITLE_UTF8;
5295 else if (!g_ascii_strcasecmp (codec_id, "S_SSA"))
5296 codec_id = GST_MATROSKA_CODEC_ID_SUBTITLE_SSA;
5297 else if (!g_ascii_strcasecmp (codec_id, "S_ASS"))
5298 codec_id = GST_MATROSKA_CODEC_ID_SUBTITLE_ASS;
5299 else if (!g_ascii_strcasecmp (codec_id, "S_USF"))
5300 codec_id = GST_MATROSKA_CODEC_ID_SUBTITLE_USF;
5302 /* TODO: Add GST_MATROSKA_CODEC_ID_SUBTITLE_BMP support
5303 * Check if we have to do something with codec_private */
5304 if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_UTF8)) {
5305 /* well, plain text simply does not have a lot of markup ... */
5306 caps = gst_caps_new_simple ("text/x-pango-markup", NULL);
5307 context->postprocess_frame = gst_matroska_demux_check_subtitle_buffer;
5308 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_SSA)) {
5309 caps = gst_caps_new_simple ("application/x-ssa", NULL);
5310 context->postprocess_frame = gst_matroska_demux_check_subtitle_buffer;
5311 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_ASS)) {
5312 caps = gst_caps_new_simple ("application/x-ass", NULL);
5313 context->postprocess_frame = gst_matroska_demux_check_subtitle_buffer;
5314 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_USF)) {
5315 caps = gst_caps_new_simple ("application/x-usf", NULL);
5316 context->postprocess_frame = gst_matroska_demux_check_subtitle_buffer;
5317 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_VOBSUB)) {
5318 caps = gst_caps_new_simple ("video/x-dvd-subpicture", NULL);
5319 ((GstMatroskaTrackContext *) subtitlecontext)->send_dvd_event = TRUE;
5320 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_HDMVPGS)) {
5321 caps = gst_caps_new_simple ("subpicture/x-pgs", NULL);
5322 } else if (!strcmp (codec_id, GST_MATROSKA_CODEC_ID_SUBTITLE_KATE)) {
5323 caps = gst_caps_new_simple ("subtitle/x-kate", NULL);
5324 context->send_xiph_headers = TRUE;
5326 GST_DEBUG ("Unknown subtitle stream: codec_id='%s'", codec_id);
5327 caps = gst_caps_new_simple ("application/x-subtitle-unknown", NULL);
5330 if (data != NULL && size > 0) {
5333 buf = gst_buffer_new_and_alloc (size);
5334 memcpy (GST_BUFFER_DATA (buf), data, size);
5335 gst_caps_set_simple (caps, "codec_data", GST_TYPE_BUFFER, buf, NULL);
5336 gst_buffer_unref (buf);
5343 gst_matroska_demux_set_index (GstElement * element, GstIndex * index)
5345 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (element);
5347 GST_OBJECT_LOCK (demux);
5348 if (demux->common.element_index)
5349 gst_object_unref (demux->common.element_index);
5350 demux->common.element_index = index ? gst_object_ref (index) : NULL;
5351 GST_OBJECT_UNLOCK (demux);
5352 GST_DEBUG_OBJECT (demux, "Set index %" GST_PTR_FORMAT,
5353 demux->common.element_index);
5357 gst_matroska_demux_get_index (GstElement * element)
5359 GstIndex *result = NULL;
5360 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (element);
5362 GST_OBJECT_LOCK (demux);
5363 if (demux->common.element_index)
5364 result = gst_object_ref (demux->common.element_index);
5365 GST_OBJECT_UNLOCK (demux);
5367 GST_DEBUG_OBJECT (demux, "Returning index %" GST_PTR_FORMAT, result);
5372 static GstStateChangeReturn
5373 gst_matroska_demux_change_state (GstElement * element,
5374 GstStateChange transition)
5376 GstMatroskaDemux *demux = GST_MATROSKA_DEMUX (element);
5377 GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
5379 /* handle upwards state changes here */
5380 switch (transition) {
5385 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
5387 /* handle downwards state changes */
5388 switch (transition) {
5389 case GST_STATE_CHANGE_PAUSED_TO_READY:
5390 gst_matroska_demux_reset (GST_ELEMENT (demux));
5400 gst_matroska_demux_plugin_init (GstPlugin * plugin)
5404 /* parser helper separate debug */
5405 GST_DEBUG_CATEGORY_INIT (ebmlread_debug, "ebmlread",
5406 0, "EBML stream helper class");
5408 /* create an elementfactory for the matroska_demux element */
5409 if (!gst_element_register (plugin, "matroskademux",
5410 GST_RANK_PRIMARY, GST_TYPE_MATROSKA_DEMUX))