configure: use correct arguments in signal handler tests
[mplayer/glamo.git] / libmpdemux / demux_mkv.c
blob589acc8695b0bbbdec4e1ce57dd4592739c71877
1 /*
2 * Matroska demuxer
3 * Copyright (C) 2004 Aurelien Jacobs <aurel@gnuage.org>
4 * Based on the one written by Ronald Bultje for gstreamer
5 * and on demux_mkv.cpp from Moritz Bunkus.
7 * This file is part of MPlayer.
9 * MPlayer is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * MPlayer 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
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with MPlayer; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 #include "config.h"
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <ctype.h>
29 #include <inttypes.h>
30 #include <stdbool.h>
32 #include "talloc.h"
33 #include "options.h"
34 #include "bstr.h"
35 #include "stream/stream.h"
36 #include "demuxer.h"
37 #include "stheader.h"
38 #include "ebml.h"
39 #include "matroska.h"
40 #include "demux_real.h"
42 #include "mp_msg.h"
44 #include "vobsub.h"
45 #include "subreader.h"
46 #include "libvo/sub.h"
48 #include "ass_mp.h"
50 #include "libavutil/common.h"
52 #ifdef CONFIG_QTX_CODECS
53 #include "loader/qtx/qtxsdk/components.h"
54 #endif
56 #if CONFIG_ZLIB
57 #include <zlib.h>
58 #endif
60 #include "libavutil/lzo.h"
61 #include "ffmpeg_files/intreadwrite.h"
62 #include "libavutil/avstring.h"
64 static const unsigned char sipr_swaps[38][2] = {
65 {0,63},{1,22},{2,44},{3,90},{5,81},{7,31},{8,86},{9,58},{10,36},{12,68},
66 {13,39},{14,73},{15,53},{16,69},{17,57},{19,88},{20,34},{21,71},{24,46},
67 {25,94},{26,54},{28,75},{29,50},{32,70},{33,92},{35,74},{38,85},{40,56},
68 {42,87},{43,65},{45,59},{48,79},{49,93},{51,89},{55,95},{61,76},{67,83},
69 {77,80}
72 // Map flavour to bytes per second
73 #define SIPR_FLAVORS 4
74 #define ATRC_FLAVORS 8
75 #define COOK_FLAVORS 34
76 static const int sipr_fl2bps[SIPR_FLAVORS] = { 813, 1062, 625, 2000 };
77 static const int atrc_fl2bps[ATRC_FLAVORS] = {
78 8269, 11714, 13092, 16538, 18260, 22050, 33075, 44100 };
79 static const int cook_fl2bps[COOK_FLAVORS] = {
80 1000, 1378, 2024, 2584, 4005, 5513, 8010, 4005, 750, 2498,
81 4048, 5513, 8010, 11973, 8010, 2584, 4005, 2067, 2584, 2584,
82 4005, 4005, 5513, 5513, 8010, 12059, 1550, 8010, 12059, 5513,
83 12016, 16408, 22911, 33506
86 typedef struct mkv_content_encoding {
87 uint64_t order, type, scope;
88 uint64_t comp_algo;
89 uint8_t *comp_settings;
90 int comp_settings_len;
91 } mkv_content_encoding_t;
93 typedef struct mkv_track {
94 int tnum;
95 char *name;
96 int id; // -aid / -sid / -vid option value
98 char *codec_id;
99 int ms_compat;
100 char *language;
102 int type;
104 uint32_t v_width, v_height, v_dwidth, v_dheight;
105 double v_frate;
107 uint32_t a_formattag;
108 uint32_t a_channels, a_bps;
109 float a_sfreq;
111 double default_duration;
113 int default_track;
115 unsigned char *private_data;
116 unsigned int private_size;
118 /* stuff for realmedia */
119 int realmedia;
120 int64_t rv_kf_base;
121 int rv_kf_pts;
122 double rv_pts; /* previous video timestamp */
123 double ra_pts; /* previous audio timestamp */
125 /** realaudio descrambling */
126 int sub_packet_size; ///< sub packet size, per stream
127 int sub_packet_h; ///< number of coded frames per block
128 int coded_framesize; ///< coded frame size, per stream
129 int audiopk_size; ///< audio packet size
130 unsigned char *audio_buf; ///< place to store reordered audio data
131 double *audio_timestamp; ///< timestamp for each audio packet
132 int sub_packet_cnt; ///< number of subpacket already received
133 int audio_filepos; ///< file position of first audio packet in block
135 /* stuff for quicktime */
136 int fix_i_bps;
137 double qt_last_a_pts;
139 int subtitle_type;
141 /* The timecodes of video frames might have to be reordered if they're
142 in display order (the timecodes, not the frames themselves!). In this
143 case demux packets have to be cached with the help of these variables. */
144 int reorder_timecodes;
145 demux_packet_t **cached_dps;
146 int num_cached_dps, num_allocated_dps;
147 double max_pts;
149 /* generic content encoding support */
150 mkv_content_encoding_t *encodings;
151 int num_encodings;
153 /* For VobSubs and SSA/ASS */
154 sh_sub_t *sh_sub;
155 } mkv_track_t;
157 typedef struct mkv_index {
158 int tnum;
159 uint64_t timecode, filepos;
160 } mkv_index_t;
162 typedef struct mkv_demuxer {
163 off_t segment_start;
165 double duration, last_pts;
166 uint64_t last_filepos;
168 mkv_track_t **tracks;
169 int num_tracks;
171 uint64_t tc_scale, cluster_tc;
173 uint64_t cluster_start;
174 uint64_t cluster_size;
175 uint64_t blockgroup_size;
177 mkv_index_t *indexes;
178 int num_indexes;
180 off_t *parsed_pos;
181 int num_parsed_pos;
182 bool parsed_info;
183 bool parsed_tracks;
184 bool parsed_tags;
185 bool parsed_chapters;
186 bool parsed_attachments;
188 struct cluster_pos {
189 uint64_t filepos;
190 uint64_t timecode;
191 } *cluster_positions;
192 int num_cluster_pos;
194 int64_t skip_to_timecode;
195 int v_skip_to_keyframe, a_skip_to_keyframe;
197 int num_audio_tracks;
198 } mkv_demuxer_t;
200 #define REALHEADER_SIZE 16
201 #define RVPROPERTIES_SIZE 34
202 #define RAPROPERTIES4_SIZE 56
203 #define RAPROPERTIES5_SIZE 70
206 * \brief ensures there is space for at least one additional element
207 * \param array array to grow
208 * \param nelem current number of elements in array
209 * \param elsize size of one array element
211 static void *grow_array(void *array, int nelem, size_t elsize)
213 if (!(nelem & 31))
214 array = realloc(array, (nelem + 32) * elsize);
215 return array;
218 static bool is_parsed_header(struct mkv_demuxer *mkv_d, off_t pos)
220 int low = 0;
221 int high = mkv_d->num_parsed_pos;
222 while (high > low + 1) {
223 int mid = high + low >> 1;
224 if (mkv_d->parsed_pos[mid] > pos)
225 high = mid;
226 else
227 low = mid;
229 if (mkv_d->num_parsed_pos && mkv_d->parsed_pos[low] == pos)
230 return true;
231 if (!(mkv_d->num_parsed_pos & 31))
232 mkv_d->parsed_pos = talloc_realloc(mkv_d, mkv_d->parsed_pos, off_t,
233 mkv_d->num_parsed_pos + 32);
234 mkv_d->num_parsed_pos++;
235 for (int i = mkv_d->num_parsed_pos - 1; i > low; i--)
236 mkv_d->parsed_pos[i] = mkv_d->parsed_pos[i - 1];
237 mkv_d->parsed_pos[low] = pos;
238 return false;
241 static mkv_track_t *find_track_by_num(struct mkv_demuxer *d, int n, int type)
243 for (int i = 0; i < d->num_tracks; i++)
244 if (d->tracks[i] != NULL && d->tracks[i]->type == type)
245 if (d->tracks[i]->id == n)
246 return d->tracks[i];
248 return NULL;
251 static void add_cluster_position(mkv_demuxer_t *mkv_d, uint64_t filepos,
252 uint64_t timecode)
254 if (mkv_d->indexes)
255 return;
257 int n = mkv_d->num_cluster_pos;
258 if (n > 0 && mkv_d->cluster_positions[n-1].filepos >= filepos)
259 return;
261 mkv_d->cluster_positions =
262 grow_array(mkv_d->cluster_positions, mkv_d->num_cluster_pos,
263 sizeof(*mkv_d->cluster_positions));
264 mkv_d->cluster_positions[mkv_d->num_cluster_pos++] = (struct cluster_pos){
265 .filepos = filepos,
266 .timecode = timecode,
271 #define AAC_SYNC_EXTENSION_TYPE 0x02b7
272 static int aac_get_sample_rate_index(uint32_t sample_rate)
274 static const int srates[] = {
275 92017, 75132, 55426, 46009, 37566, 27713,
276 23004, 18783, 13856, 11502, 9391, 0
278 int i = 0;
279 while (sample_rate < srates[i])
280 i++;
281 return i;
284 /** \brief Free cached demux packets
286 * Reordering the timecodes requires caching of demux packets. This function
287 * frees all these cached packets and the memory for the cached pointers
288 * itself.
290 * \param demuxer The demuxer for which the cache is to be freed.
292 static void free_cached_dps(demuxer_t *demuxer)
294 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
295 mkv_track_t *track;
296 int i, k;
298 for (k = 0; k < mkv_d->num_tracks; k++) {
299 track = mkv_d->tracks[k];
300 for (i = 0; i < track->num_cached_dps; i++)
301 free_demux_packet(track->cached_dps[i]);
302 free(track->cached_dps);
303 track->cached_dps = NULL;
304 track->num_cached_dps = 0;
305 track->num_allocated_dps = 0;
306 track->max_pts = 0;
310 static void demux_mkv_decode(mkv_track_t *track, uint8_t *src,
311 uint8_t **dest, uint32_t *size, uint32_t type)
313 uint8_t *orig_src = src;
315 *dest = src;
317 for (int i = 0; i < track->num_encodings; i++) {
318 struct mkv_content_encoding *enc = track->encodings + i;
319 if (!(enc->scope & type))
320 continue;
322 if (src != *dest && src != orig_src)
323 talloc_free(src);
324 src = *dest; // output from last iteration is new source
326 if (enc->comp_algo == 0) {
327 #if CONFIG_ZLIB
328 /* zlib encoded track */
330 if (*size == 0)
331 continue;
333 z_stream zstream;
335 zstream.zalloc = (alloc_func) 0;
336 zstream.zfree = (free_func) 0;
337 zstream.opaque = (voidpf) 0;
338 if (inflateInit(&zstream) != Z_OK) {
339 mp_tmsg(MSGT_DEMUX, MSGL_WARN,
340 "[mkv] zlib initialization failed.\n");
341 goto error;
343 zstream.next_in = (Bytef *) src;
344 zstream.avail_in = *size;
346 *dest = NULL;
347 zstream.avail_out = *size;
348 int result;
349 do {
350 *size += 4000;
351 *dest = talloc_realloc_size(NULL, *dest, *size);
352 zstream.next_out = (Bytef *) (*dest + zstream.total_out);
353 result = inflate(&zstream, Z_NO_FLUSH);
354 if (result != Z_OK && result != Z_STREAM_END) {
355 mp_tmsg(MSGT_DEMUX, MSGL_WARN,
356 "[mkv] zlib decompression failed.\n");
357 talloc_free(*dest);
358 *dest = NULL;
359 inflateEnd(&zstream);
360 goto error;
362 zstream.avail_out += 4000;
363 } while (zstream.avail_out == 4000 && zstream.avail_in != 0
364 && result != Z_STREAM_END);
366 *size = zstream.total_out;
367 inflateEnd(&zstream);
368 #endif
369 } else if (enc->comp_algo == 2) {
370 /* lzo encoded track */
371 int dstlen = *size * 3;
373 *dest = NULL;
374 while (1) {
375 int srclen = *size;
376 if (dstlen > SIZE_MAX - AV_LZO_OUTPUT_PADDING)
377 goto lzo_fail;
378 *dest = talloc_realloc_size(NULL, *dest,
379 dstlen + AV_LZO_OUTPUT_PADDING);
380 int result = av_lzo1x_decode(*dest, &dstlen, src, &srclen);
381 if (result == 0)
382 break;
383 if (!(result & AV_LZO_OUTPUT_FULL)) {
384 lzo_fail:
385 mp_tmsg(MSGT_DEMUX, MSGL_WARN,
386 "[mkv] lzo decompression failed.\n");
387 talloc_free(*dest);
388 *dest = NULL;
389 goto error;
391 mp_msg(MSGT_DEMUX, MSGL_DBG2,
392 "[mkv] lzo decompression buffer too small.\n");
393 dstlen *= 2;
395 *size = dstlen;
396 } else if (enc->comp_algo == 3) {
397 *dest = talloc_size(NULL, *size + enc->comp_settings_len);
398 memcpy(*dest, enc->comp_settings, enc->comp_settings_len);
399 memcpy(*dest + enc->comp_settings_len, src, *size);
400 *size += enc->comp_settings_len;
404 error:
405 if (src != *dest && src != orig_src)
406 talloc_free(src);
410 static int demux_mkv_read_info(demuxer_t *demuxer)
412 mkv_demuxer_t *mkv_d = demuxer->priv;
413 stream_t *s = demuxer->stream;
415 mkv_d->tc_scale = 1000000;
416 mkv_d->duration = 0;
418 struct ebml_info info = {};
419 struct ebml_parse_ctx parse_ctx = {};
420 if (ebml_read_element(s, &parse_ctx, &info, &ebml_info_desc) < 0)
421 return 1;
422 if (info.n_timecode_scale) {
423 mkv_d->tc_scale = info.timecode_scale;
424 mp_msg(MSGT_DEMUX, MSGL_V,
425 "[mkv] | + timecode scale: %" PRIu64 "\n", mkv_d->tc_scale);
427 if (info.n_duration) {
428 mkv_d->duration = info.duration * mkv_d->tc_scale / 1e9;
429 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + duration: %.3fs\n",
430 mkv_d->duration);
432 if (info.n_segment_uid) {
433 int len = info.segment_uid.len;
434 if (len != sizeof(demuxer->matroska_data.segment_uid)) {
435 mp_msg(MSGT_DEMUX, MSGL_INFO,
436 "[mkv] segment uid invalid length %d\n", len);
437 } else {
438 memcpy(demuxer->matroska_data.segment_uid, info.segment_uid.start,
439 len);
440 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + segment uid");
441 for (int i = 0; i < len; i++)
442 mp_msg(MSGT_DEMUX, MSGL_V, " %02x",
443 demuxer->matroska_data.segment_uid[i]);
444 mp_msg(MSGT_DEMUX, MSGL_V, "\n");
447 talloc_free(parse_ctx.talloc_ctx);
448 return 0;
451 static void parse_trackencodings(struct demuxer *demuxer,
452 struct mkv_track *track,
453 struct ebml_content_encodings *encodings)
455 // initial allocation to be a non-NULL context before realloc
456 mkv_content_encoding_t *ce = talloc_size(track, 1);
458 for (int n_enc = 0; n_enc < encodings->n_content_encoding; n_enc++) {
459 struct ebml_content_encoding *enc = encodings->content_encoding + n_enc;
460 struct mkv_content_encoding e = {};
461 e.order = enc->content_encoding_order;
462 if (enc->n_content_encoding_scope)
463 e.scope = enc->content_encoding_scope;
464 else
465 e.scope = 1;
466 e.type = enc->content_encoding_type;
468 if (enc->n_content_compression) {
469 struct ebml_content_compression *z = &enc->content_compression;
470 e.comp_algo = z->content_comp_algo;
471 if (z->n_content_comp_settings) {
472 int sz = z->content_comp_settings.len;
473 e.comp_settings = talloc_size(ce, sz);
474 memcpy(e.comp_settings, z->content_comp_settings.start, sz);
475 e.comp_settings_len = sz;
479 if (e.type == 1) {
480 mp_tmsg(MSGT_DEMUX, MSGL_WARN, "[mkv] Track "
481 "number %u has been encrypted and "
482 "decryption has not yet been\n"
483 "[mkv] implemented. Skipping track.\n",
484 track->tnum);
485 } else if (e.type != 0) {
486 mp_tmsg(MSGT_DEMUX, MSGL_WARN,
487 "[mkv] Unknown content encoding type for "
488 "track %u. Skipping track.\n",
489 track->tnum);
490 } else if (e.comp_algo != 0 && e.comp_algo != 2 && e.comp_algo != 3) {
491 mp_tmsg(MSGT_DEMUX, MSGL_WARN,
492 "[mkv] Track %u has been compressed with "
493 "an unknown/unsupported compression\n"
494 "[mkv] algorithm (%" PRIu64 "). Skipping track.\n",
495 track->tnum, e.comp_algo);
497 #if !CONFIG_ZLIB
498 else if (e.comp_algo == 0) {
499 mp_tmsg(MSGT_DEMUX, MSGL_WARN,
500 "[mkv] Track %u was compressed with zlib "
501 "but mplayer has not been compiled\n"
502 "[mkv] with support for zlib compression. "
503 "Skipping track.\n",
504 track->tnum);
506 #endif
507 int i;
508 for (i = 0; i < n_enc; i++)
509 if (e.order >= ce[i].order)
510 break;
511 ce = talloc_realloc_size(track, ce, (n_enc + 1) * sizeof(*ce));
512 memmove(ce + i + 1, ce + i, (n_enc - i) * sizeof(*ce));
513 memcpy(ce + i, &e, sizeof(e));
516 track->encodings = ce;
517 track->num_encodings = encodings->n_content_encoding;
520 static void parse_trackaudio(struct demuxer *demuxer, struct mkv_track *track,
521 struct ebml_audio *audio)
523 if (audio->n_sampling_frequency) {
524 track->a_sfreq = audio->sampling_frequency;
525 mp_msg(MSGT_DEMUX, MSGL_V,
526 "[mkv] | + Sampling frequency: %f\n", track->a_sfreq);
527 } else
528 track->a_sfreq = 8000;
529 if (audio->n_bit_depth) {
530 track->a_bps = audio->bit_depth;
531 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Bit depth: %u\n",
532 track->a_bps);
534 if (audio->n_channels) {
535 track->a_channels = audio->channels;
536 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Channels: %u\n",
537 track->a_channels);
538 } else
539 track->a_channels = 1;
542 static void parse_trackvideo(struct demuxer *demuxer, struct mkv_track *track,
543 struct ebml_video *video)
545 if (video->n_frame_rate) {
546 track->v_frate = video->frame_rate;
547 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Frame rate: %f\n",
548 track->v_frate);
549 if (track->v_frate > 0)
550 track->default_duration = 1 / track->v_frate;
552 if (video->n_display_width) {
553 track->v_dwidth = video->display_width;
554 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Display width: %u\n",
555 track->v_dwidth);
557 if (video->n_display_height) {
558 track->v_dheight = video->display_height;
559 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Display height: %u\n",
560 track->v_dheight);
562 if (video->n_pixel_width) {
563 track->v_width = video->pixel_width;
564 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Pixel width: %u\n",
565 track->v_width);
567 if (video->n_pixel_height) {
568 track->v_height = video->pixel_height;
569 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Pixel height: %u\n",
570 track->v_height);
575 * \brief free any data associated with given track
576 * \param track track of which to free data
578 static void demux_mkv_free_trackentry(mkv_track_t *track)
580 free(track->audio_buf);
581 free(track->audio_timestamp);
582 talloc_free(track);
585 static void parse_trackentry(struct demuxer *demuxer,
586 struct ebml_track_entry *entry)
588 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
589 struct mkv_track *track = talloc_zero_size(NULL, sizeof(*track));
591 track->tnum = entry->track_number;
592 if (track->tnum)
593 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Track number: %u\n",
594 track->tnum);
595 else
596 mp_msg(MSGT_DEMUX, MSGL_ERR, "[mkv] Missing track number!\n");
598 if (entry->n_name) {
599 track->name = talloc_strndup(track, entry->name.start,
600 entry->name.len);
601 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Name: %s\n",
602 track->name);
605 track->type = entry->track_type;
606 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Track type: ");
607 switch (track->type) {
608 case MATROSKA_TRACK_AUDIO:
609 mp_msg(MSGT_DEMUX, MSGL_V, "Audio\n");
610 break;
611 case MATROSKA_TRACK_VIDEO:
612 mp_msg(MSGT_DEMUX, MSGL_V, "Video\n");
613 break;
614 case MATROSKA_TRACK_SUBTITLE:
615 mp_msg(MSGT_DEMUX, MSGL_V, "Subtitle\n");
616 break;
617 default:
618 mp_msg(MSGT_DEMUX, MSGL_V, "unknown\n");
619 break;
622 if (entry->n_audio) {
623 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Audio track\n");
624 parse_trackaudio(demuxer, track, &entry->audio);
627 if (entry->n_video) {
628 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Video track\n");
629 parse_trackvideo(demuxer, track, &entry->video);
632 if (entry->n_codec_id) {
633 track->codec_id = talloc_strndup(track, entry->codec_id.start,
634 entry->codec_id.len);
635 if (!strcmp(track->codec_id, MKV_V_MSCOMP)
636 || !strcmp(track->codec_id, MKV_A_ACM))
637 track->ms_compat = 1;
638 else if (!strcmp(track->codec_id, MKV_S_VOBSUB))
639 track->subtitle_type = MATROSKA_SUBTYPE_VOBSUB;
640 else if (!strcmp(track->codec_id, MKV_S_TEXTSSA)
641 || !strcmp(track->codec_id, MKV_S_TEXTASS)
642 || !strcmp(track->codec_id, MKV_S_SSA)
643 || !strcmp(track->codec_id, MKV_S_ASS)) {
644 track->subtitle_type = MATROSKA_SUBTYPE_SSA;
645 } else if (!strcmp(track->codec_id, MKV_S_TEXTASCII))
646 track->subtitle_type = MATROSKA_SUBTYPE_TEXT;
647 if (!strcmp(track->codec_id, MKV_S_TEXTUTF8)) {
648 track->subtitle_type = MATROSKA_SUBTYPE_TEXT;
650 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Codec ID: %s\n",
651 track->codec_id);
652 } else
653 mp_msg(MSGT_DEMUX, MSGL_ERR, "[mkv] Missing codec ID!\n");
655 if (entry->n_codec_private) {
656 int len = entry->codec_private.len;
657 track->private_data = talloc_size(track, len + AV_LZO_INPUT_PADDING);
658 memcpy(track->private_data, entry->codec_private.start, len);
659 track->private_size = len;
660 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + CodecPrivate, length %u\n",
661 track->private_size);
664 if (entry->n_language) {
665 track->language = talloc_strndup(track, entry->language.start,
666 entry->language.len);
667 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Language: %s\n",
668 track->language);
669 } else
670 track->language = talloc_strdup(track, "eng");
672 if (entry->n_flag_default) {
673 track->default_track = entry->flag_default;
674 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Default flag: %u\n",
675 track->default_track);
676 } else
677 track->default_track = 1;
679 if (entry->n_default_duration) {
680 track->default_duration = entry->default_duration / 1e9;
681 if (entry->default_duration == 0)
682 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Default duration: 0");
683 else {
684 if (!track->v_frate)
685 track->v_frate = 1e9 / entry->default_duration;
686 mp_msg(MSGT_DEMUX, MSGL_V,
687 "[mkv] | + Default duration: %.3fms ( = %.3f fps)\n",
688 entry->default_duration / 1000000.0, track->v_frate);
692 if (entry->n_content_encodings)
693 parse_trackencodings(demuxer, track, &entry->content_encodings);
695 mkv_d->tracks[mkv_d->num_tracks++] = track;
698 static int demux_mkv_read_tracks(demuxer_t *demuxer)
700 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
701 stream_t *s = demuxer->stream;
703 struct ebml_tracks tracks = {};
704 struct ebml_parse_ctx parse_ctx = {};
705 if (ebml_read_element(s, &parse_ctx, &tracks, &ebml_tracks_desc) < 0)
706 return 1;
708 mkv_d->tracks = talloc_size(mkv_d,
709 tracks.n_track_entry * sizeof(*mkv_d->tracks));
710 for (int i = 0; i < tracks.n_track_entry; i++) {
711 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + a track...\n");
712 parse_trackentry(demuxer, &tracks.track_entry[i]);
714 talloc_free(parse_ctx.talloc_ctx);
715 return 0;
718 static int demux_mkv_read_cues(demuxer_t *demuxer)
720 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
721 stream_t *s = demuxer->stream;
723 if (index_mode == 0 || index_mode == 2) {
724 ebml_read_skip(s, NULL);
725 return 0;
728 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] /---- [ parsing cues ] -----------\n");
729 struct ebml_cues cues = {};
730 struct ebml_parse_ctx parse_ctx = {};
731 if (ebml_read_element(s, &parse_ctx, &cues, &ebml_cues_desc) < 0)
732 goto out;
733 for (int i = 0; i < cues.n_cue_point; i++) {
734 struct ebml_cue_point *cuepoint = &cues.cue_point[i];
735 if (cuepoint->n_cue_time != 1 || !cuepoint->n_cue_track_positions) {
736 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] Malformed CuePoint element\n");
737 continue;
739 uint64_t time = cuepoint->cue_time;
740 for (int i = 0; i < cuepoint->n_cue_track_positions; i++) {
741 struct ebml_cue_track_positions *trackpos =
742 &cuepoint->cue_track_positions[i];
743 uint64_t track = trackpos->cue_track;
744 uint64_t pos = trackpos->cue_cluster_position;
745 mkv_d->indexes =
746 grow_array(mkv_d->indexes, mkv_d->num_indexes,
747 sizeof(mkv_index_t));
748 mkv_d->indexes[mkv_d->num_indexes].tnum = track;
749 mkv_d->indexes[mkv_d->num_indexes].timecode = time;
750 mkv_d->indexes[mkv_d->num_indexes].filepos =
751 mkv_d->segment_start + pos;
752 mp_msg(MSGT_DEMUX, MSGL_DBG2,
753 "[mkv] |+ found cue point for track %" PRIu64
754 ": timecode %" PRIu64 ", filepos: %" PRIu64 "\n", track,
755 time, mkv_d->segment_start + pos);
756 mkv_d->num_indexes++;
760 out:
761 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] \\---- [ parsing cues ] -----------\n");
762 talloc_free(parse_ctx.talloc_ctx);
763 return 0;
766 static int demux_mkv_read_chapters(struct demuxer *demuxer)
768 struct MPOpts *opts = demuxer->opts;
769 stream_t *s = demuxer->stream;
771 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] /---- [ parsing chapters ] ---------\n");
772 struct ebml_chapters file_chapters = {};
773 struct ebml_parse_ctx parse_ctx = {};
774 if (ebml_read_element(s, &parse_ctx, &file_chapters,
775 &ebml_chapters_desc) < 0)
776 goto out;
778 int selected_edition = 0;
779 int num_editions = file_chapters.n_edition_entry;
780 struct ebml_edition_entry *editions = file_chapters.edition_entry;
781 if (opts->edition_id >= 0 && opts->edition_id < num_editions) {
782 selected_edition = opts->edition_id;
783 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] User-specified edition: %d\n",
784 selected_edition);
785 } else
786 for (int i = 0; i < num_editions; i++)
787 if (editions[i].edition_flag_default) {
788 selected_edition = i;
789 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] Default edition: %d\n", i);
790 break;
792 struct matroska_chapter *m_chapters = NULL;
793 if (editions[selected_edition].edition_flag_ordered) {
794 int count = editions[selected_edition].n_chapter_atom;
795 m_chapters = talloc_array_ptrtype(demuxer, m_chapters, count);
796 demuxer->matroska_data.ordered_chapters = m_chapters;
797 demuxer->matroska_data.num_ordered_chapters = count;
800 for (int idx = 0; idx < num_editions; idx++) {
801 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] New edition %d\n", idx);
802 int warn_level = idx == selected_edition ? MSGL_WARN : MSGL_V;
803 if (editions[idx].n_edition_flag_default)
804 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] Default edition flag: %"PRIu64
805 "\n", editions[idx].edition_flag_default);
806 if (editions[idx].n_edition_flag_ordered)
807 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] Ordered chapter flag: %"PRIu64
808 "\n", editions[idx].edition_flag_ordered);
809 for (int i = 0; i < editions[idx].n_chapter_atom; i++) {
810 struct ebml_chapter_atom *ca = editions[idx].chapter_atom + i;
811 struct matroska_chapter chapter = { };
812 struct bstr name = { "(unnamed)", 9 };
814 if (!ca->n_chapter_time_start)
815 mp_msg(MSGT_DEMUX, warn_level,
816 "[mkv] Chapter lacks start time\n");
817 chapter.start = ca->chapter_time_start / 1000000;
818 chapter.end = ca->chapter_time_end / 1000000;
820 if (ca->n_chapter_display) {
821 if (ca->n_chapter_display > 1)
822 mp_msg(MSGT_DEMUX, warn_level, "[mkv] Multiple chapter "
823 "names not supported, picking first\n");
824 if (!ca->chapter_display[0].n_chap_string)
825 mp_msg(MSGT_DEMUX, warn_level, "[mkv] Malformed chapter "
826 "name entry\n");
827 else
828 name = ca->chapter_display[0].chap_string;
831 if (ca->n_chapter_segment_uid) {
832 chapter.has_segment_uid = true;
833 int len = ca->chapter_segment_uid.len;
834 if (len != sizeof(chapter.segment_uid))
835 mp_msg(MSGT_DEMUX, warn_level,
836 "[mkv] Chapter segment uid bad length %d\n", len);
837 else if (ca->n_chapter_segment_edition_uid) {
838 mp_tmsg(MSGT_DEMUX, warn_level, "[mkv] Warning: "
839 "unsupported edition recursion in chapter; "
840 "will skip on playback!\n");
841 } else {
842 memcpy(chapter.segment_uid, ca->chapter_segment_uid.start,
843 len);
844 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] Chapter segment uid ");
845 for (int i = 0; i < len; i++)
846 mp_msg(MSGT_DEMUX, MSGL_V, "%02x ",
847 chapter.segment_uid[i]);
848 mp_msg(MSGT_DEMUX, MSGL_V, "\n");
852 mp_msg(MSGT_DEMUX, MSGL_V,
853 "[mkv] Chapter %u from %02d:%02d:%02d.%03d "
854 "to %02d:%02d:%02d.%03d, %.*s\n", i,
855 (int) (chapter.start / 60 / 60 / 1000),
856 (int) ((chapter.start / 60 / 1000) % 60),
857 (int) ((chapter.start / 1000) % 60),
858 (int) (chapter.start % 1000),
859 (int) (chapter.end / 60 / 60 / 1000),
860 (int) ((chapter.end / 60 / 1000) % 60),
861 (int) ((chapter.end / 1000) % 60),
862 (int) (chapter.end % 1000),
863 BSTR_P(name));
865 if (idx == selected_edition){
866 demuxer_add_chapter(demuxer, name, chapter.start, chapter.end);
867 if (editions[idx].edition_flag_ordered) {
868 chapter.name = talloc_strndup(m_chapters, name.start,
869 name.len);
870 m_chapters[i] = chapter;
875 if (num_editions > 1)
876 mp_msg(MSGT_DEMUX, MSGL_INFO,
877 "[mkv] Found %d editions, will play #%d (first is 0).\n",
878 num_editions, selected_edition);
880 out:
881 talloc_free(parse_ctx.talloc_ctx);
882 mp_msg(MSGT_DEMUX, MSGL_V,
883 "[mkv] \\---- [ parsing chapters ] ---------\n");
884 return 0;
887 static int demux_mkv_read_tags(demuxer_t *demuxer)
889 stream_t *s = demuxer->stream;
891 struct ebml_parse_ctx parse_ctx = {};
892 struct ebml_tags tags = {};
893 if (ebml_read_element(s, &parse_ctx, &tags, &ebml_tags_desc) < 0)
894 return 1;
896 for (int i = 0; i < tags.n_tag; i++) {
897 struct ebml_tag tag = tags.tag[i];
898 if (tag.targets.target_track_uid || tag.targets.target_edition_uid ||
899 tag.targets.target_chapter_uid || tag.targets.target_attachment_uid)
900 continue;
902 for (int j; j < tag.n_simple_tag; j++)
903 demux_info_add_bstr(demuxer, tag.simple_tag[j].tag_name, tag.simple_tag[j].tag_string);
906 return 0;
909 static int demux_mkv_read_attachments(demuxer_t *demuxer)
911 stream_t *s = demuxer->stream;
913 mp_msg(MSGT_DEMUX, MSGL_V,
914 "[mkv] /---- [ parsing attachments ] ---------\n");
916 struct ebml_attachments attachments = {};
917 struct ebml_parse_ctx parse_ctx = {};
918 if (ebml_read_element(s, &parse_ctx, &attachments,
919 &ebml_attachments_desc) < 0)
920 goto out;
922 for (int i = 0; i < attachments.n_attached_file; i++) {
923 struct ebml_attached_file *attachment = &attachments.attached_file[i];
924 if (!attachment->n_file_name || !attachment->n_file_mime_type
925 || !attachment->n_file_data) {
926 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] Malformed attachment\n");
927 continue;
929 struct bstr name = attachment->file_name;
930 struct bstr mime = attachment->file_mime_type;
931 demuxer_add_attachment(demuxer, name, mime, attachment->file_data);
932 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] Attachment: %.*s, %.*s, %zu bytes\n",
933 BSTR_P(name), BSTR_P(mime), attachment->file_data.len);
936 out:
937 talloc_free(parse_ctx.talloc_ctx);
938 mp_msg(MSGT_DEMUX, MSGL_V,
939 "[mkv] \\---- [ parsing attachments ] ---------\n");
940 return 0;
943 static int read_header_element(struct demuxer *demuxer, uint32_t id,
944 off_t at_filepos);
946 static int demux_mkv_read_seekhead(demuxer_t *demuxer)
948 struct mkv_demuxer *mkv_d = demuxer->priv;
949 struct stream *s = demuxer->stream;
950 int res = 0;
951 struct ebml_seek_head seekhead = {};
952 struct ebml_parse_ctx parse_ctx = {};
954 mp_msg(MSGT_DEMUX, MSGL_V,
955 "[mkv] /---- [ parsing seek head ] ---------\n");
956 if (ebml_read_element(s, &parse_ctx, &seekhead, &ebml_seek_head_desc) < 0) {
957 res = 1;
958 goto out;
960 /* off now holds the position of the next element after the seek head. */
961 off_t off = stream_tell(s);
962 for (int i = 0; i < seekhead.n_seek; i++) {
963 struct ebml_seek *seek = &seekhead.seek[i];
964 if (seek->n_seek_id != 1 || seek->n_seek_position != 1) {
965 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] Invalid SeekHead entry\n");
966 continue;
968 uint64_t pos = seek->seek_position + mkv_d->segment_start;
969 if (pos >= demuxer->movi_end) {
970 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] SeekHead position beyond "
971 "end of file - incomplete file?\n");
972 continue;
974 read_header_element(demuxer, seek->seek_id, pos);
976 if (!stream_seek(s, off)) {
977 mp_msg(MSGT_DEMUX, MSGL_ERR, "[mkv] Couldn't seek back after "
978 "SeekHead??\n");
979 res = 1;
981 out:
982 mp_msg(MSGT_DEMUX, MSGL_V,
983 "[mkv] \\---- [ parsing seek head ] ---------\n");
984 talloc_free(parse_ctx.talloc_ctx);
985 return res;
988 static bool seek_pos_id(struct stream *s, off_t pos, uint32_t id)
990 if (!stream_seek(s, pos)) {
991 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] Failed to seek in file\n");
992 return false;
994 if (ebml_read_id(s, NULL) != id) {
995 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] Expected element not found\n");
996 return false;
998 return true;
1001 static int read_header_element(struct demuxer *demuxer, uint32_t id,
1002 off_t at_filepos)
1004 struct mkv_demuxer *mkv_d = demuxer->priv;
1005 stream_t *s = demuxer->stream;
1006 off_t pos = stream_tell(s) - 4;
1008 switch(id) {
1009 case MATROSKA_ID_INFO:
1010 if (mkv_d->parsed_info)
1011 break;
1012 if (at_filepos && !seek_pos_id(s, at_filepos, id))
1013 return -1;
1014 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] |+ segment information...\n");
1015 mkv_d->parsed_info = true;
1016 return demux_mkv_read_info(demuxer) ? -1 : 1;
1018 case MATROSKA_ID_TRACKS:
1019 if (mkv_d->parsed_tracks)
1020 break;
1021 if (at_filepos && !seek_pos_id(s, at_filepos, id))
1022 return -1;
1023 mkv_d->parsed_tracks = true;
1024 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] |+ segment tracks...\n");
1025 return demux_mkv_read_tracks(demuxer) ? -1 : 1;
1027 case MATROSKA_ID_CUES:
1028 if (is_parsed_header(mkv_d, pos))
1029 break;
1030 if (at_filepos && !seek_pos_id(s, at_filepos, id))
1031 return -1;
1032 return demux_mkv_read_cues(demuxer) ? -1 : 1;
1034 case MATROSKA_ID_TAGS:
1035 if (mkv_d->parsed_tags)
1036 break;
1037 if (at_filepos && !seek_pos_id(s, at_filepos, id))
1038 return -1;
1039 mkv_d->parsed_tags = true;
1040 return demux_mkv_read_tags(demuxer) ? -1 : 1;
1042 case MATROSKA_ID_SEEKHEAD:
1043 if (is_parsed_header(mkv_d, pos))
1044 break;
1045 if (at_filepos && !seek_pos_id(s, at_filepos, id))
1046 return -1;
1047 return demux_mkv_read_seekhead(demuxer) ? -1 : 1;
1049 case MATROSKA_ID_CHAPTERS:
1050 if (mkv_d->parsed_chapters)
1051 break;
1052 if (at_filepos && !seek_pos_id(s, at_filepos, id))
1053 return -1;
1054 mkv_d->parsed_chapters = true;
1055 return demux_mkv_read_chapters(demuxer) ? -1 : 1;
1057 case MATROSKA_ID_ATTACHMENTS:
1058 if (mkv_d->parsed_attachments)
1059 break;
1060 if (at_filepos && !seek_pos_id(s, at_filepos, id))
1061 return -1;
1062 mkv_d->parsed_attachments = true;
1063 return demux_mkv_read_attachments(demuxer) ? -1 : 1;
1065 default:
1066 if (!at_filepos)
1067 ebml_read_skip(s, NULL);
1068 return 0;
1070 if (!at_filepos)
1071 ebml_read_skip(s, NULL);
1072 return 1;
1077 static int demux_mkv_open_video(demuxer_t *demuxer, mkv_track_t *track,
1078 int vid);
1079 static int demux_mkv_open_audio(demuxer_t *demuxer, mkv_track_t *track,
1080 int aid);
1081 static int demux_mkv_open_sub(demuxer_t *demuxer, mkv_track_t *track,
1082 int sid);
1084 static void display_create_tracks(demuxer_t *demuxer)
1086 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
1087 int i, vid = 0, aid = 0, sid = 0;
1089 for (i = 0; i < mkv_d->num_tracks; i++) {
1090 char *type = "unknown", str[32];
1091 *str = '\0';
1092 switch (mkv_d->tracks[i]->type) {
1093 case MATROSKA_TRACK_VIDEO:
1094 type = "video";
1095 mkv_d->tracks[i]->id = -1;
1096 if (vid == MAX_V_STREAMS)
1097 break;
1098 mkv_d->tracks[i]->id = vid;
1099 demux_mkv_open_video(demuxer, mkv_d->tracks[i], vid);
1100 if (mkv_d->tracks[i]->name)
1101 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VID_%d_NAME=%s\n", vid,
1102 mkv_d->tracks[i]->name);
1103 sprintf(str, "-vid %u", vid++);
1104 break;
1105 case MATROSKA_TRACK_AUDIO:
1106 type = "audio";
1107 mkv_d->tracks[i]->id = -1;
1108 if (aid == MAX_A_STREAMS)
1109 break;
1110 mkv_d->tracks[i]->id = aid;
1111 demux_mkv_open_audio(demuxer, mkv_d->tracks[i], aid);
1112 if (mkv_d->tracks[i]->name)
1113 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AID_%d_NAME=%s\n", aid,
1114 mkv_d->tracks[i]->name);
1115 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AID_%d_LANG=%s\n", aid,
1116 mkv_d->tracks[i]->language);
1117 sprintf(str, "-aid %u, -alang %.5s", aid++,
1118 mkv_d->tracks[i]->language);
1119 break;
1120 case MATROSKA_TRACK_SUBTITLE:
1121 type = "subtitles";
1122 mkv_d->tracks[i]->id = -1;
1123 if (sid == MAX_S_STREAMS)
1124 break;
1125 mkv_d->tracks[i]->id = sid;
1126 demux_mkv_open_sub(demuxer, mkv_d->tracks[i], sid);
1127 if (mkv_d->tracks[i]->name)
1128 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SID_%d_NAME=%s\n", sid,
1129 mkv_d->tracks[i]->name);
1130 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SID_%d_LANG=%s\n", sid,
1131 mkv_d->tracks[i]->language);
1132 sprintf(str, "-sid %u, -slang %.5s", sid++,
1133 mkv_d->tracks[i]->language);
1134 break;
1136 if (mkv_d->tracks[i]->name)
1137 mp_tmsg(MSGT_DEMUX, MSGL_INFO,
1138 "[mkv] Track ID %u: %s (%s) \"%s\", %s\n",
1139 mkv_d->tracks[i]->tnum, type, mkv_d->tracks[i]->codec_id,
1140 mkv_d->tracks[i]->name, str);
1141 else
1142 mp_tmsg(MSGT_DEMUX, MSGL_INFO, "[mkv] Track ID %u: %s (%s), %s\n",
1143 mkv_d->tracks[i]->tnum, type, mkv_d->tracks[i]->codec_id,
1144 str);
1146 mkv_d->num_audio_tracks = aid;
1149 typedef struct {
1150 char *id;
1151 int fourcc;
1152 int extradata;
1153 } videocodec_info_t;
1155 static const videocodec_info_t vinfo[] = {
1156 {MKV_V_MJPEG, mmioFOURCC('m', 'j', 'p', 'g'), 1},
1157 {MKV_V_MPEG1, mmioFOURCC('m', 'p', 'g', '1'), 0},
1158 {MKV_V_MPEG2, mmioFOURCC('m', 'p', 'g', '2'), 0},
1159 {MKV_V_MPEG4_SP, mmioFOURCC('m', 'p', '4', 'v'), 1},
1160 {MKV_V_MPEG4_ASP, mmioFOURCC('m', 'p', '4', 'v'), 1},
1161 {MKV_V_MPEG4_AP, mmioFOURCC('m', 'p', '4', 'v'), 1},
1162 {MKV_V_MPEG4_AVC, mmioFOURCC('a', 'v', 'c', '1'), 1},
1163 {MKV_V_THEORA, mmioFOURCC('t', 'h', 'e', 'o'), 1},
1164 {MKV_V_VP8, mmioFOURCC('V', 'P', '8', '0'), 0},
1165 {NULL, 0, 0}
1168 static int demux_mkv_open_video(demuxer_t *demuxer, mkv_track_t *track,
1169 int vid)
1171 struct MPOpts *opts = demuxer->opts;
1172 BITMAPINFOHEADER *bih;
1173 void *ImageDesc = NULL;
1174 sh_video_t *sh_v;
1176 if (track->ms_compat) { /* MS compatibility mode */
1177 BITMAPINFOHEADER *src;
1179 if (track->private_data == NULL
1180 || track->private_size < sizeof(BITMAPINFOHEADER))
1181 return 1;
1183 src = (BITMAPINFOHEADER *) track->private_data;
1184 bih = calloc(1, track->private_size);
1185 bih->biSize = le2me_32(src->biSize);
1186 bih->biWidth = le2me_32(src->biWidth);
1187 bih->biHeight = le2me_32(src->biHeight);
1188 bih->biPlanes = le2me_16(src->biPlanes);
1189 bih->biBitCount = le2me_16(src->biBitCount);
1190 bih->biCompression = le2me_32(src->biCompression);
1191 bih->biSizeImage = le2me_32(src->biSizeImage);
1192 bih->biXPelsPerMeter = le2me_32(src->biXPelsPerMeter);
1193 bih->biYPelsPerMeter = le2me_32(src->biYPelsPerMeter);
1194 bih->biClrUsed = le2me_32(src->biClrUsed);
1195 bih->biClrImportant = le2me_32(src->biClrImportant);
1196 memcpy((char *) bih + sizeof(BITMAPINFOHEADER),
1197 (char *) src + sizeof(BITMAPINFOHEADER),
1198 track->private_size - sizeof(BITMAPINFOHEADER));
1200 if (track->v_width == 0)
1201 track->v_width = bih->biWidth;
1202 if (track->v_height == 0)
1203 track->v_height = bih->biHeight;
1204 } else {
1205 bih = calloc(1, sizeof(BITMAPINFOHEADER));
1206 bih->biSize = sizeof(BITMAPINFOHEADER);
1207 bih->biWidth = track->v_width;
1208 bih->biHeight = track->v_height;
1209 bih->biBitCount = 24;
1210 bih->biSizeImage = bih->biWidth * bih->biHeight * bih->biBitCount / 8;
1212 if (track->private_size >= RVPROPERTIES_SIZE
1213 && (!strcmp(track->codec_id, MKV_V_REALV10)
1214 || !strcmp(track->codec_id, MKV_V_REALV20)
1215 || !strcmp(track->codec_id, MKV_V_REALV30)
1216 || !strcmp(track->codec_id, MKV_V_REALV40))) {
1217 unsigned char *dst, *src;
1218 uint32_t type2;
1219 unsigned int cnt;
1221 src = (uint8_t *) track->private_data + RVPROPERTIES_SIZE;
1223 cnt = track->private_size - RVPROPERTIES_SIZE;
1224 bih = realloc(bih, sizeof(BITMAPINFOHEADER) + 8 + cnt);
1225 bih->biSize = 48 + cnt;
1226 bih->biPlanes = 1;
1227 type2 = AV_RB32(src - 4);
1228 if (type2 == 0x10003000 || type2 == 0x10003001)
1229 bih->biCompression = mmioFOURCC('R', 'V', '1', '3');
1230 else
1231 bih->biCompression =
1232 mmioFOURCC('R', 'V', track->codec_id[9], '0');
1233 dst = (unsigned char *) (bih + 1);
1234 // copy type1 and type2 info from rv properties
1235 memcpy(dst, src - 8, 8 + cnt);
1236 track->realmedia = 1;
1238 #ifdef CONFIG_QTX_CODECS
1239 } else if (track->private_size >= sizeof(ImageDescription)
1240 && !strcmp(track->codec_id, MKV_V_QUICKTIME)) {
1241 ImageDescriptionPtr idesc;
1243 idesc = (ImageDescriptionPtr) track->private_data;
1244 idesc->idSize = be2me_32(idesc->idSize);
1245 idesc->cType = be2me_32(idesc->cType);
1246 idesc->version = be2me_16(idesc->version);
1247 idesc->revisionLevel = be2me_16(idesc->revisionLevel);
1248 idesc->vendor = be2me_32(idesc->vendor);
1249 idesc->temporalQuality = be2me_32(idesc->temporalQuality);
1250 idesc->spatialQuality = be2me_32(idesc->spatialQuality);
1251 idesc->width = be2me_16(idesc->width);
1252 idesc->height = be2me_16(idesc->height);
1253 idesc->hRes = be2me_32(idesc->hRes);
1254 idesc->vRes = be2me_32(idesc->vRes);
1255 idesc->dataSize = be2me_32(idesc->dataSize);
1256 idesc->frameCount = be2me_16(idesc->frameCount);
1257 idesc->depth = be2me_16(idesc->depth);
1258 idesc->clutID = be2me_16(idesc->clutID);
1259 bih->biPlanes = 1;
1260 bih->biCompression = idesc->cType;
1261 ImageDesc = idesc;
1262 #endif /* CONFIG_QTX_CODECS */
1264 } else {
1265 const videocodec_info_t *vi = vinfo;
1266 while (vi->id && strcmp(vi->id, track->codec_id))
1267 vi++;
1268 bih->biCompression = vi->fourcc;
1269 if (vi->extradata && track->private_data
1270 && (track->private_size > 0)) {
1271 bih->biSize += track->private_size;
1272 bih = realloc(bih, bih->biSize);
1273 memcpy(bih + 1, track->private_data, track->private_size);
1275 track->reorder_timecodes = opts->user_correct_pts == 0;
1276 if (!vi->id) {
1277 mp_tmsg(MSGT_DEMUX, MSGL_WARN, "[mkv] Unknown/unsupported "
1278 "CodecID (%s) or missing/bad CodecPrivate\n"
1279 "[mkv] data (track %u).\n",
1280 track->codec_id, track->tnum);
1281 free(bih);
1282 return 1;
1287 sh_v = new_sh_video(demuxer, vid);
1288 sh_v->bih = bih;
1289 sh_v->format = sh_v->bih->biCompression;
1290 if (track->v_frate == 0.0)
1291 track->v_frate = 25.0;
1292 sh_v->fps = track->v_frate;
1293 sh_v->frametime = 1 / track->v_frate;
1294 sh_v->aspect = 0;
1295 if (!track->realmedia) {
1296 sh_v->disp_w = track->v_width;
1297 sh_v->disp_h = track->v_height;
1298 if (track->v_dheight)
1299 sh_v->aspect = (double) track->v_dwidth / track->v_dheight;
1300 } else {
1301 // vd_realvid.c will set aspect to disp_w/disp_h and rederive
1302 // disp_w and disp_h from the RealVideo stream contents returned
1303 // by the Real DLLs. If DisplayWidth/DisplayHeight was not set in
1304 // the Matroska file then it has already been set to PixelWidth/Height
1305 // by check_track_information.
1306 sh_v->disp_w = track->v_dwidth;
1307 sh_v->disp_h = track->v_dheight;
1309 sh_v->ImageDesc = ImageDesc;
1310 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] Aspect: %f\n", sh_v->aspect);
1312 sh_v->ds = demuxer->video;
1313 return 0;
1316 static int demux_mkv_open_audio(demuxer_t *demuxer, mkv_track_t *track,
1317 int aid)
1319 sh_audio_t *sh_a = new_sh_audio(demuxer, aid);
1320 if (!sh_a)
1321 return 1;
1323 if (track->language && (strcmp(track->language, "und") != 0))
1324 sh_a->lang = strdup(track->language);
1325 sh_a->default_track = track->default_track;
1326 sh_a->ds = demuxer->audio;
1327 sh_a->wf = malloc(sizeof(WAVEFORMATEX));
1328 if (track->ms_compat && (track->private_size >= sizeof(WAVEFORMATEX))) {
1329 WAVEFORMATEX *wf = (WAVEFORMATEX *) track->private_data;
1330 sh_a->wf = realloc(sh_a->wf, track->private_size);
1331 sh_a->wf->wFormatTag = le2me_16(wf->wFormatTag);
1332 sh_a->wf->nChannels = le2me_16(wf->nChannels);
1333 sh_a->wf->nSamplesPerSec = le2me_32(wf->nSamplesPerSec);
1334 sh_a->wf->nAvgBytesPerSec = le2me_32(wf->nAvgBytesPerSec);
1335 sh_a->wf->nBlockAlign = le2me_16(wf->nBlockAlign);
1336 sh_a->wf->wBitsPerSample = le2me_16(wf->wBitsPerSample);
1337 sh_a->wf->cbSize = track->private_size - sizeof(WAVEFORMATEX);
1338 memcpy(sh_a->wf + 1, wf + 1,
1339 track->private_size - sizeof(WAVEFORMATEX));
1340 if (track->a_sfreq == 0.0)
1341 track->a_sfreq = sh_a->wf->nSamplesPerSec;
1342 if (track->a_channels == 0)
1343 track->a_channels = sh_a->wf->nChannels;
1344 if (track->a_bps == 0)
1345 track->a_bps = sh_a->wf->wBitsPerSample;
1346 track->a_formattag = sh_a->wf->wFormatTag;
1347 } else {
1348 memset(sh_a->wf, 0, sizeof(WAVEFORMATEX));
1349 if (!strcmp(track->codec_id, MKV_A_MP3)
1350 || !strcmp(track->codec_id, MKV_A_MP2))
1351 track->a_formattag = 0x0055;
1352 else if (!strncmp(track->codec_id, MKV_A_AC3, strlen(MKV_A_AC3)))
1353 track->a_formattag = 0x2000;
1354 else if (!strcmp(track->codec_id, MKV_A_DTS))
1355 track->a_formattag = 0x2001;
1356 else if (!strcmp(track->codec_id, MKV_A_PCM)
1357 || !strcmp(track->codec_id, MKV_A_PCM_BE))
1358 track->a_formattag = 0x0001;
1359 else if (!strcmp(track->codec_id, MKV_A_AAC_2MAIN)
1360 || !strncmp(track->codec_id, MKV_A_AAC_2LC,
1361 strlen(MKV_A_AAC_2LC))
1362 || !strcmp(track->codec_id, MKV_A_AAC_2SSR)
1363 || !strcmp(track->codec_id, MKV_A_AAC_4MAIN)
1364 || !strncmp(track->codec_id, MKV_A_AAC_4LC,
1365 strlen(MKV_A_AAC_4LC))
1366 || !strcmp(track->codec_id, MKV_A_AAC_4SSR)
1367 || !strcmp(track->codec_id, MKV_A_AAC_4LTP)
1368 || !strcmp(track->codec_id, MKV_A_AAC))
1369 track->a_formattag = mmioFOURCC('M', 'P', '4', 'A');
1370 else if (!strcmp(track->codec_id, MKV_A_VORBIS)) {
1371 if (track->private_data == NULL)
1372 return 1;
1373 track->a_formattag = mmioFOURCC('v', 'r', 'b', 's');
1374 } else if (!strcmp(track->codec_id, MKV_A_QDMC))
1375 track->a_formattag = mmioFOURCC('Q', 'D', 'M', 'C');
1376 else if (!strcmp(track->codec_id, MKV_A_QDMC2))
1377 track->a_formattag = mmioFOURCC('Q', 'D', 'M', '2');
1378 else if (!strcmp(track->codec_id, MKV_A_WAVPACK))
1379 track->a_formattag = mmioFOURCC('W', 'V', 'P', 'K');
1380 else if (!strcmp(track->codec_id, MKV_A_TRUEHD))
1381 track->a_formattag = mmioFOURCC('T', 'R', 'H', 'D');
1382 else if (!strcmp(track->codec_id, MKV_A_FLAC)) {
1383 if (track->private_data == NULL || track->private_size == 0) {
1384 mp_tmsg(MSGT_DEMUX, MSGL_WARN,
1385 "[mkv] FLAC track does not contain valid headers.\n");
1386 return 1;
1388 track->a_formattag = mmioFOURCC('f', 'L', 'a', 'C');
1389 } else if (track->private_size >= RAPROPERTIES4_SIZE) {
1390 if (!strcmp(track->codec_id, MKV_A_REAL28))
1391 track->a_formattag = mmioFOURCC('2', '8', '_', '8');
1392 else if (!strcmp(track->codec_id, MKV_A_REALATRC))
1393 track->a_formattag = mmioFOURCC('a', 't', 'r', 'c');
1394 else if (!strcmp(track->codec_id, MKV_A_REALCOOK))
1395 track->a_formattag = mmioFOURCC('c', 'o', 'o', 'k');
1396 else if (!strcmp(track->codec_id, MKV_A_REALDNET))
1397 track->a_formattag = mmioFOURCC('d', 'n', 'e', 't');
1398 else if (!strcmp(track->codec_id, MKV_A_REALSIPR))
1399 track->a_formattag = mmioFOURCC('s', 'i', 'p', 'r');
1400 } else {
1401 mp_tmsg(MSGT_DEMUX, MSGL_WARN, "[mkv] Unknown/unsupported audio "
1402 "codec ID '%s' for track %u or missing/faulty\n[mkv] "
1403 "private codec data.\n", track->codec_id, track->tnum);
1404 free_sh_audio(demuxer, track->id);
1405 return 1;
1409 sh_a->format = track->a_formattag;
1410 sh_a->wf->wFormatTag = track->a_formattag;
1411 sh_a->channels = track->a_channels;
1412 sh_a->wf->nChannels = track->a_channels;
1413 sh_a->samplerate = (uint32_t) track->a_sfreq;
1414 sh_a->wf->nSamplesPerSec = (uint32_t) track->a_sfreq;
1415 if (track->a_bps == 0) {
1416 sh_a->samplesize = 2;
1417 sh_a->wf->wBitsPerSample = 16;
1418 } else {
1419 sh_a->samplesize = track->a_bps / 8;
1420 sh_a->wf->wBitsPerSample = track->a_bps;
1422 if (track->a_formattag == 0x0055) { /* MP3 || MP2 */
1423 sh_a->wf->nAvgBytesPerSec = 16000;
1424 sh_a->wf->nBlockAlign = 1152;
1425 } else if ((track->a_formattag == 0x2000) /* AC3 */
1426 || (track->a_formattag == 0x2001)) { /* DTS */
1427 free(sh_a->wf);
1428 sh_a->wf = NULL;
1429 } else if (track->a_formattag == 0x0001) { /* PCM || PCM_BE */
1430 sh_a->wf->nAvgBytesPerSec = sh_a->channels * sh_a->samplerate * 2;
1431 sh_a->wf->nBlockAlign = sh_a->wf->nAvgBytesPerSec;
1432 if (!strcmp(track->codec_id, MKV_A_PCM_BE))
1433 sh_a->format = mmioFOURCC('t', 'w', 'o', 's');
1434 } else if (!strcmp(track->codec_id, MKV_A_QDMC)
1435 || !strcmp(track->codec_id, MKV_A_QDMC2)) {
1436 sh_a->wf->nAvgBytesPerSec = 16000;
1437 sh_a->wf->nBlockAlign = 1486;
1438 track->fix_i_bps = 1;
1439 track->qt_last_a_pts = 0.0;
1440 if (track->private_data != NULL) {
1441 sh_a->codecdata = malloc(track->private_size);
1442 memcpy(sh_a->codecdata, track->private_data, track->private_size);
1443 sh_a->codecdata_len = track->private_size;
1445 } else if (track->a_formattag == mmioFOURCC('M', 'P', '4', 'A')) {
1446 int profile, srate_idx;
1448 sh_a->wf->nAvgBytesPerSec = 16000;
1449 sh_a->wf->nBlockAlign = 1024;
1451 if (!strcmp(track->codec_id, MKV_A_AAC)
1452 && (NULL != track->private_data)) {
1453 sh_a->codecdata = malloc(track->private_size);
1454 memcpy(sh_a->codecdata, track->private_data, track->private_size);
1455 sh_a->codecdata_len = track->private_size;
1456 return 0;
1459 /* Recreate the 'private data' */
1460 /* which faad2 uses in its initialization */
1461 srate_idx = aac_get_sample_rate_index(sh_a->samplerate);
1462 if (!strncmp(&track->codec_id[12], "MAIN", 4))
1463 profile = 0;
1464 else if (!strncmp(&track->codec_id[12], "LC", 2))
1465 profile = 1;
1466 else if (!strncmp(&track->codec_id[12], "SSR", 3))
1467 profile = 2;
1468 else
1469 profile = 3;
1470 sh_a->codecdata = malloc(5);
1471 sh_a->codecdata[0] = ((profile + 1) << 3) | ((srate_idx & 0xE) >> 1);
1472 sh_a->codecdata[1] =
1473 ((srate_idx & 0x1) << 7) | (track->a_channels << 3);
1475 if (strstr(track->codec_id, "SBR") != NULL) {
1476 /* HE-AAC (aka SBR AAC) */
1477 sh_a->codecdata_len = 5;
1479 sh_a->samplerate *= 2;
1480 sh_a->wf->nSamplesPerSec *= 2;
1481 srate_idx = aac_get_sample_rate_index(sh_a->samplerate);
1482 sh_a->codecdata[2] = AAC_SYNC_EXTENSION_TYPE >> 3;
1483 sh_a->codecdata[3] = ((AAC_SYNC_EXTENSION_TYPE & 0x07) << 5) | 5;
1484 sh_a->codecdata[4] = (1 << 7) | (srate_idx << 3);
1485 track->default_duration = 1024.0 / (sh_a->samplerate / 2);
1486 } else {
1487 sh_a->codecdata_len = 2;
1488 track->default_duration = 1024.0 / sh_a->samplerate;
1490 } else if (track->a_formattag == mmioFOURCC('v', 'r', 'b', 's')) { /* VORBIS */
1491 sh_a->wf->cbSize = track->private_size;
1492 sh_a->wf = realloc(sh_a->wf, sizeof(WAVEFORMATEX) + sh_a->wf->cbSize);
1493 memcpy((unsigned char *) (sh_a->wf + 1), track->private_data,
1494 sh_a->wf->cbSize);
1495 } else if (track->private_size >= RAPROPERTIES4_SIZE
1496 && !strncmp(track->codec_id, MKV_A_REALATRC, 7)) {
1497 /* Common initialization for all RealAudio codecs */
1498 unsigned char *src = track->private_data;
1499 int codecdata_length, version;
1500 int flavor;
1502 sh_a->wf->nAvgBytesPerSec = 0; /* FIXME !? */
1504 version = AV_RB16(src + 4);
1505 flavor = AV_RB16(src + 22);
1506 track->coded_framesize = AV_RB32(src + 24);
1507 track->sub_packet_h = AV_RB16(src + 40);
1508 sh_a->wf->nBlockAlign = track->audiopk_size = AV_RB16(src + 42);
1509 track->sub_packet_size = AV_RB16(src + 44);
1510 if (version == 4) {
1511 src += RAPROPERTIES4_SIZE;
1512 src += src[0] + 1;
1513 src += src[0] + 1;
1514 } else
1515 src += RAPROPERTIES5_SIZE;
1517 src += 3;
1518 if (version == 5)
1519 src++;
1520 codecdata_length = AV_RB32(src);
1521 src += 4;
1522 sh_a->wf->cbSize = codecdata_length;
1523 sh_a->wf = realloc(sh_a->wf, sizeof(WAVEFORMATEX) + sh_a->wf->cbSize);
1524 memcpy(((char *) (sh_a->wf + 1)), src, codecdata_length);
1526 switch (track->a_formattag) {
1527 case mmioFOURCC('a', 't', 'r', 'c'):
1528 sh_a->wf->nAvgBytesPerSec = atrc_fl2bps[flavor];
1529 sh_a->wf->nBlockAlign = track->sub_packet_size;
1530 track->audio_buf =
1531 malloc(track->sub_packet_h * track->audiopk_size);
1532 track->audio_timestamp =
1533 malloc(track->sub_packet_h * sizeof(double));
1534 break;
1535 case mmioFOURCC('c', 'o', 'o', 'k'):
1536 sh_a->wf->nAvgBytesPerSec = cook_fl2bps[flavor];
1537 sh_a->wf->nBlockAlign = track->sub_packet_size;
1538 track->audio_buf =
1539 malloc(track->sub_packet_h * track->audiopk_size);
1540 track->audio_timestamp =
1541 malloc(track->sub_packet_h * sizeof(double));
1542 break;
1543 case mmioFOURCC('s', 'i', 'p', 'r'):
1544 sh_a->wf->nAvgBytesPerSec = sipr_fl2bps[flavor];
1545 sh_a->wf->nBlockAlign = track->coded_framesize;
1546 track->audio_buf =
1547 malloc(track->sub_packet_h * track->audiopk_size);
1548 track->audio_timestamp =
1549 malloc(track->sub_packet_h * sizeof(double));
1550 break;
1551 case mmioFOURCC('2', '8', '_', '8'):
1552 sh_a->wf->nAvgBytesPerSec = 3600;
1553 sh_a->wf->nBlockAlign = track->coded_framesize;
1554 track->audio_buf =
1555 malloc(track->sub_packet_h * track->audiopk_size);
1556 track->audio_timestamp =
1557 malloc(track->sub_packet_h * sizeof(double));
1558 break;
1561 track->realmedia = 1;
1562 } else if (!strcmp(track->codec_id, MKV_A_FLAC)
1563 || (track->a_formattag == 0xf1ac)) {
1564 unsigned char *ptr;
1565 int size;
1566 free(sh_a->wf);
1567 sh_a->wf = NULL;
1569 if (track->a_formattag == mmioFOURCC('f', 'L', 'a', 'C')) {
1570 ptr = track->private_data;
1571 size = track->private_size;
1572 } else {
1573 sh_a->format = mmioFOURCC('f', 'L', 'a', 'C');
1574 ptr = track->private_data + sizeof(WAVEFORMATEX);
1575 size = track->private_size - sizeof(WAVEFORMATEX);
1577 if (size < 4 || ptr[0] != 'f' || ptr[1] != 'L' || ptr[2] != 'a'
1578 || ptr[3] != 'C') {
1579 sh_a->codecdata = malloc(4);
1580 sh_a->codecdata_len = 4;
1581 memcpy(sh_a->codecdata, "fLaC", 4);
1582 } else {
1583 sh_a->codecdata = malloc(size);
1584 sh_a->codecdata_len = size;
1585 memcpy(sh_a->codecdata, ptr, size);
1587 } else if (track->a_formattag == mmioFOURCC('W', 'V', 'P', 'K') || track->a_formattag == mmioFOURCC('T', 'R', 'H', 'D')) { /* do nothing, still works */
1588 } else if (!track->ms_compat
1589 || (track->private_size < sizeof(WAVEFORMATEX))) {
1590 free_sh_audio(demuxer, track->id);
1591 return 1;
1594 return 0;
1597 static int demux_mkv_open_sub(demuxer_t *demuxer, mkv_track_t *track,
1598 int sid)
1600 if (track->subtitle_type != MATROSKA_SUBTYPE_UNKNOWN) {
1601 int size;
1602 uint8_t *buffer;
1603 sh_sub_t *sh = new_sh_sub(demuxer, sid);
1604 track->sh_sub = sh;
1605 sh->type = 't';
1606 if (track->subtitle_type == MATROSKA_SUBTYPE_VOBSUB)
1607 sh->type = 'v';
1608 if (track->subtitle_type == MATROSKA_SUBTYPE_SSA)
1609 sh->type = 'a';
1610 size = track->private_size;
1611 demux_mkv_decode(track, track->private_data, &buffer, &size, 2);
1612 if (buffer && buffer != track->private_data) {
1613 talloc_free(track->private_data);
1614 talloc_steal(track, buffer);
1615 track->private_data = buffer;
1616 track->private_size = size;
1618 sh->extradata = malloc(track->private_size);
1619 memcpy(sh->extradata, track->private_data, track->private_size);
1620 sh->extradata_len = track->private_size;
1621 if (track->language && (strcmp(track->language, "und") != 0))
1622 sh->lang = strdup(track->language);
1623 sh->default_track = track->default_track;
1624 } else {
1625 mp_tmsg(MSGT_DEMUX, MSGL_ERR,
1626 "[mkv] Subtitle type '%s' is not supported.\n",
1627 track->codec_id);
1628 return 1;
1631 return 0;
1634 static int demux_mkv_open(demuxer_t *demuxer)
1636 stream_t *s = demuxer->stream;
1637 mkv_demuxer_t *mkv_d;
1638 mkv_track_t *track;
1639 int i, cont = 0;
1641 stream_seek(s, s->start_pos);
1642 if (ebml_read_id(s, NULL) != EBML_ID_EBML)
1643 return 0;
1644 struct ebml_ebml ebml_master = {};
1645 struct ebml_parse_ctx parse_ctx = { .no_error_messages = true };
1646 if (ebml_read_element(s, &parse_ctx, &ebml_master, &ebml_ebml_desc) < 0)
1647 return 0;
1648 if (ebml_master.doc_type.start == NULL) {
1649 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] File has EBML header but no doctype."
1650 " Assuming \"matroska\".\n");
1651 } else if (bstrcmp(ebml_master.doc_type, BSTR("matroska")) != 0
1652 && bstrcmp(ebml_master.doc_type, BSTR("webm")) != 0) {
1653 mp_msg(MSGT_DEMUX, MSGL_DBG2, "[mkv] no head found\n");
1654 talloc_free(parse_ctx.talloc_ctx);
1655 return 0;
1657 if (ebml_master.doc_type_read_version > 2) {
1658 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] This looks like a Matroska file, "
1659 "but we don't support format version %"PRIu64"\n",
1660 ebml_master.doc_type_read_version);
1661 talloc_free(parse_ctx.talloc_ctx);
1662 return 0;
1664 if ((ebml_master.n_ebml_read_version
1665 && ebml_master.ebml_read_version != EBML_VERSION)
1666 || (ebml_master.n_ebml_max_size_length
1667 && ebml_master.ebml_max_size_length > 8)
1668 || (ebml_master.n_ebml_max_id_length
1669 && ebml_master.ebml_max_id_length != 4)) {
1670 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] This looks like a Matroska file, "
1671 "but the header has bad parameters\n");
1672 talloc_free(parse_ctx.talloc_ctx);
1673 return 0;
1675 talloc_free(parse_ctx.talloc_ctx);
1677 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] Found the head...\n");
1679 if (ebml_read_id(s, NULL) != MATROSKA_ID_SEGMENT) {
1680 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] but no segment :(\n");
1681 return 0;
1683 ebml_read_length(s, NULL); /* return bytes number until EOF */
1685 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] + a segment...\n");
1687 mkv_d = talloc_zero(demuxer, struct mkv_demuxer);
1688 demuxer->priv = mkv_d;
1689 mkv_d->tc_scale = 1000000;
1690 mkv_d->segment_start = stream_tell(s);
1692 while (!cont) {
1693 uint32_t id = ebml_read_id(s, NULL);
1694 switch (id) {
1695 case MATROSKA_ID_CLUSTER:
1696 mp_msg(MSGT_DEMUX, MSGL_V,
1697 "[mkv] |+ found cluster, headers are "
1698 "parsed completely :)\n");
1699 stream_seek(s, stream_tell(s) - 4);
1700 cont = 1;
1701 break;
1703 default:
1704 cont = read_header_element(demuxer, id, 0) < 1;
1705 break;
1706 case EBML_ID_VOID:
1707 ebml_read_skip(s, NULL);
1708 break;
1712 display_create_tracks(demuxer);
1714 /* select video track */
1715 track = NULL;
1716 if (demuxer->video->id == -1) { /* automatically select a video track */
1717 /* search for a video track that has the 'default' flag set */
1718 for (i = 0; i < mkv_d->num_tracks; i++)
1719 if (mkv_d->tracks[i]->type == MATROSKA_TRACK_VIDEO
1720 && mkv_d->tracks[i]->default_track) {
1721 track = mkv_d->tracks[i];
1722 break;
1725 if (track == NULL)
1726 /* no track has the 'default' flag set */
1727 /* let's take the first video track */
1728 for (i = 0; i < mkv_d->num_tracks; i++)
1729 if (mkv_d->tracks[i]->type == MATROSKA_TRACK_VIDEO
1730 && mkv_d->tracks[i]->id >= 0) {
1731 track = mkv_d->tracks[i];
1732 break;
1734 } else if (demuxer->video->id != -2) /* -2 = no video at all */
1735 track = find_track_by_num(mkv_d, demuxer->video->id,
1736 MATROSKA_TRACK_VIDEO);
1738 if (track && demuxer->v_streams[track->id]) {
1739 mp_tmsg(MSGT_DEMUX, MSGL_INFO, "[mkv] Will play video track %u.\n",
1740 track->tnum);
1741 demuxer->video->id = track->id;
1742 demuxer->video->sh = demuxer->v_streams[track->id];
1743 } else {
1744 mp_tmsg(MSGT_DEMUX, MSGL_INFO, "[mkv] No video track found/wanted.\n");
1745 demuxer->video->id = -2;
1748 /* select audio track */
1749 track = NULL;
1750 if (track == NULL)
1751 /* search for an audio track that has the 'default' flag set */
1752 for (i = 0; i < mkv_d->num_tracks; i++)
1753 if (mkv_d->tracks[i]->type == MATROSKA_TRACK_AUDIO
1754 && mkv_d->tracks[i]->default_track) {
1755 track = mkv_d->tracks[i];
1756 break;
1759 if (track == NULL)
1760 /* no track has the 'default' flag set */
1761 /* let's take the first audio track */
1762 for (i = 0; i < mkv_d->num_tracks; i++)
1763 if (mkv_d->tracks[i]->type == MATROSKA_TRACK_AUDIO
1764 && mkv_d->tracks[i]->id >= 0) {
1765 track = mkv_d->tracks[i];
1766 break;
1769 if (track && demuxer->a_streams[track->id]) {
1770 demuxer->audio->id = track->id;
1771 demuxer->audio->sh = demuxer->a_streams[track->id];
1772 } else {
1773 mp_tmsg(MSGT_DEMUX, MSGL_INFO, "[mkv] No audio track found/wanted.\n");
1774 demuxer->audio->id = -2;
1777 if (s->end_pos == 0)
1778 demuxer->seekable = 0;
1779 else {
1780 demuxer->movi_start = s->start_pos;
1781 demuxer->movi_end = s->end_pos;
1782 demuxer->seekable = 1;
1785 demuxer->accurate_seek = true;
1787 return DEMUXER_TYPE_MATROSKA;
1790 static void demux_close_mkv(demuxer_t *demuxer)
1792 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
1794 if (mkv_d) {
1795 int i;
1796 free_cached_dps(demuxer);
1797 if (mkv_d->tracks) {
1798 for (i = 0; i < mkv_d->num_tracks; i++)
1799 demux_mkv_free_trackentry(mkv_d->tracks[i]);
1801 free(mkv_d->indexes);
1802 free(mkv_d->cluster_positions);
1806 static int demux_mkv_read_block_lacing(uint8_t *buffer, uint64_t *size,
1807 uint8_t *laces,
1808 uint32_t **all_lace_sizes)
1810 uint32_t total = 0, *lace_size;
1811 uint8_t flags;
1812 int i;
1814 *all_lace_sizes = NULL;
1815 lace_size = NULL;
1816 /* lacing flags */
1817 flags = *buffer++;
1818 (*size)--;
1820 switch ((flags & 0x06) >> 1) {
1821 case 0: /* no lacing */
1822 *laces = 1;
1823 lace_size = calloc(*laces, sizeof(uint32_t));
1824 lace_size[0] = *size;
1825 break;
1827 case 1: /* xiph lacing */
1828 case 2: /* fixed-size lacing */
1829 case 3: /* EBML lacing */
1830 *laces = *buffer++;
1831 (*size)--;
1832 (*laces)++;
1833 lace_size = calloc(*laces, sizeof(uint32_t));
1835 switch ((flags & 0x06) >> 1) {
1836 case 1: /* xiph lacing */
1837 for (i = 0; i < *laces - 1; i++) {
1838 lace_size[i] = 0;
1839 do {
1840 lace_size[i] += *buffer;
1841 (*size)--;
1842 } while (*buffer++ == 0xFF);
1843 total += lace_size[i];
1845 lace_size[i] = *size - total;
1846 break;
1848 case 2: /* fixed-size lacing */
1849 for (i = 0; i < *laces; i++)
1850 lace_size[i] = *size / *laces;
1851 break;
1853 case 3:; /* EBML lacing */
1854 int l;
1855 uint64_t num = ebml_read_vlen_uint(buffer, &l);
1856 if (num == EBML_UINT_INVALID) {
1857 free(lace_size);
1858 return 1;
1860 buffer += l;
1861 *size -= l;
1863 total = lace_size[0] = num;
1864 for (i = 1; i < *laces - 1; i++) {
1865 int64_t snum;
1866 snum = ebml_read_vlen_int(buffer, &l);
1867 if (snum == EBML_INT_INVALID) {
1868 free(lace_size);
1869 return 1;
1871 buffer += l;
1872 *size -= l;
1873 lace_size[i] = lace_size[i - 1] + snum;
1874 total += lace_size[i];
1876 lace_size[i] = *size - total;
1877 break;
1879 break;
1881 *all_lace_sizes = lace_size;
1882 return 0;
1885 static void handle_subtitles(demuxer_t *demuxer, mkv_track_t *track,
1886 char *block, int64_t size,
1887 uint64_t block_duration, uint64_t timecode)
1889 demux_packet_t *dp;
1891 if (block_duration == 0) {
1892 mp_msg(MSGT_DEMUX, MSGL_WARN,
1893 "[mkv] Warning: No BlockDuration for subtitle track found.\n");
1894 return;
1897 sub_utf8 = 1;
1898 dp = new_demux_packet(size);
1899 memcpy(dp->buffer, block, size);
1900 dp->pts = timecode / 1000.0;
1901 dp->endpts = (timecode + block_duration) / 1000.0;
1902 ds_add_packet(demuxer->sub, dp);
1905 static void handle_realvideo(demuxer_t *demuxer, mkv_track_t *track,
1906 uint8_t *buffer, uint32_t size, int block_bref)
1908 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
1909 demux_packet_t *dp;
1910 uint32_t timestamp = mkv_d->last_pts * 1000;
1912 dp = new_demux_packet(size);
1913 memcpy(dp->buffer, buffer, size);
1915 if (mkv_d->v_skip_to_keyframe) {
1916 dp->pts = mkv_d->last_pts;
1917 track->rv_kf_base = 0;
1918 track->rv_kf_pts = timestamp;
1919 } else
1920 dp->pts =
1921 real_fix_timestamp(dp->buffer, timestamp,
1922 ((sh_video_t *) demuxer->video->sh)->bih->
1923 biCompression, &track->rv_kf_base,
1924 &track->rv_kf_pts, NULL);
1925 dp->pos = demuxer->filepos;
1926 dp->flags = block_bref ? 0 : 0x10;
1928 ds_add_packet(demuxer->video, dp);
1931 static void handle_realaudio(demuxer_t *demuxer, mkv_track_t *track,
1932 uint8_t *buffer, uint32_t size, int block_bref)
1934 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
1935 int sps = track->sub_packet_size;
1936 int sph = track->sub_packet_h;
1937 int cfs = track->coded_framesize;
1938 int w = track->audiopk_size;
1939 int spc = track->sub_packet_cnt;
1940 demux_packet_t *dp;
1941 int x;
1943 if ((track->a_formattag == mmioFOURCC('2', '8', '_', '8'))
1944 || (track->a_formattag == mmioFOURCC('c', 'o', 'o', 'k'))
1945 || (track->a_formattag == mmioFOURCC('a', 't', 'r', 'c'))
1946 || (track->a_formattag == mmioFOURCC('s', 'i', 'p', 'r'))) {
1947 // if(!block_bref)
1948 // spc = track->sub_packet_cnt = 0;
1949 switch (track->a_formattag) {
1950 case mmioFOURCC('2', '8', '_', '8'):
1951 for (x = 0; x < sph / 2; x++)
1952 memcpy(track->audio_buf + x * 2 * w + spc * cfs,
1953 buffer + cfs * x, cfs);
1954 break;
1955 case mmioFOURCC('c', 'o', 'o', 'k'):
1956 case mmioFOURCC('a', 't', 'r', 'c'):
1957 for (x = 0; x < w / sps; x++)
1958 memcpy(track->audio_buf +
1959 sps * (sph * x + ((sph + 1) / 2) * (spc & 1) +
1960 (spc >> 1)), buffer + sps * x, sps);
1961 break;
1962 case mmioFOURCC('s', 'i', 'p', 'r'):
1963 memcpy(track->audio_buf + spc * w, buffer, w);
1964 if (spc == sph - 1) {
1965 int n;
1966 int bs = sph * w * 2 / 96; // nibbles per subpacket
1967 // Perform reordering
1968 for (n = 0; n < 38; n++) {
1969 int j;
1970 int i = bs * sipr_swaps[n][0];
1971 int o = bs * sipr_swaps[n][1];
1972 // swap nibbles of block 'i' with 'o' TODO: optimize
1973 for (j = 0; j < bs; j++) {
1974 int x = (i & 1) ?
1975 (track->audio_buf[i >> 1] >> 4) :
1976 (track->audio_buf[i >> 1] & 0x0F);
1977 int y = (o & 1) ?
1978 (track->audio_buf[o >> 1] >> 4) :
1979 (track->audio_buf[o >> 1] & 0x0F);
1980 if (o & 1)
1981 track->audio_buf[o >> 1] =
1982 (track->audio_buf[o >> 1] & 0x0F) | (x << 4);
1983 else
1984 track->audio_buf[o >> 1] =
1985 (track->audio_buf[o >> 1] & 0xF0) | x;
1986 if (i & 1)
1987 track->audio_buf[i >> 1] =
1988 (track->audio_buf[i >> 1] & 0x0F) | (y << 4);
1989 else
1990 track->audio_buf[i >> 1] =
1991 (track->audio_buf[i >> 1] & 0xF0) | y;
1992 ++i;
1993 ++o;
1997 break;
1999 track->audio_timestamp[track->sub_packet_cnt] =
2000 (track->ra_pts == mkv_d->last_pts) ? 0 : (mkv_d->last_pts);
2001 track->ra_pts = mkv_d->last_pts;
2002 if (track->sub_packet_cnt == 0)
2003 track->audio_filepos = demuxer->filepos;
2004 if (++(track->sub_packet_cnt) == sph) {
2005 int apk_usize =
2006 ((WAVEFORMATEX *) ((sh_audio_t *) demuxer->audio->sh)->wf)->
2007 nBlockAlign;
2008 track->sub_packet_cnt = 0;
2009 // Release all the audio packets
2010 for (x = 0; x < sph * w / apk_usize; x++) {
2011 dp = new_demux_packet(apk_usize);
2012 memcpy(dp->buffer, track->audio_buf + x * apk_usize,
2013 apk_usize);
2014 /* Put timestamp only on packets that correspond to original
2015 * audio packets in file */
2016 dp->pts = (x * apk_usize % w) ? 0 :
2017 track->audio_timestamp[x * apk_usize / w];
2018 dp->pos = track->audio_filepos; // all equal
2019 dp->flags = x ? 0 : 0x10; // Mark first packet as keyframe
2020 ds_add_packet(demuxer->audio, dp);
2023 } else { // Not a codec that require reordering
2024 dp = new_demux_packet(size);
2025 memcpy(dp->buffer, buffer, size);
2026 if (track->ra_pts == mkv_d->last_pts && !mkv_d->a_skip_to_keyframe)
2027 dp->pts = 0;
2028 else
2029 dp->pts = mkv_d->last_pts;
2030 track->ra_pts = mkv_d->last_pts;
2032 dp->pos = demuxer->filepos;
2033 dp->flags = block_bref ? 0 : 0x10;
2034 ds_add_packet(demuxer->audio, dp);
2038 /** Reorder timecodes and add cached demux packets to the queues.
2040 * Timecode reordering is needed if a video track contains B frames that
2041 * are timestamped in display order (e.g. MPEG-1, MPEG-2 or "native" MPEG-4).
2042 * MPlayer doesn't like timestamps in display order. This function adjusts
2043 * the timestamp of cached frames (which are exactly one I/P frame followed
2044 * by one or more B frames) so that they are in coding order again.
2046 * Example: The track with 25 FPS contains four frames with the timecodes
2047 * I at 0ms, P at 120ms, B at 40ms and B at 80ms. As soon as the next I
2048 * or P frame arrives these timecodes can be changed to I at 0ms, P at 40ms,
2049 * B at 80ms and B at 120ms.
2051 * This works for simple H.264 B-frame pyramids, but not for arbitrary orders.
2053 * \param demuxer The Matroska demuxer struct for this instance.
2054 * \param track The track structure whose cache should be handled.
2056 static void flush_cached_dps(demuxer_t *demuxer, mkv_track_t *track)
2058 int i, ok;
2060 if (track->num_cached_dps == 0)
2061 return;
2063 do {
2064 ok = 1;
2065 for (i = 1; i < track->num_cached_dps; i++)
2066 if (track->cached_dps[i - 1]->pts > track->cached_dps[i]->pts) {
2067 double tmp_pts = track->cached_dps[i - 1]->pts;
2068 track->cached_dps[i - 1]->pts = track->cached_dps[i]->pts;
2069 track->cached_dps[i]->pts = tmp_pts;
2070 ok = 0;
2072 } while (!ok);
2074 for (i = 0; i < track->num_cached_dps; i++)
2075 ds_add_packet(demuxer->video, track->cached_dps[i]);
2076 track->num_cached_dps = 0;
2079 /** Cache video frames if timecodes have to be reordered.
2081 * Timecode reordering is needed if a video track contains B frames that
2082 * are timestamped in display order (e.g. MPEG-1, MPEG-2 or "native" MPEG-4).
2083 * This function takes in a Matroska block read from the file, allocates a
2084 * demux packet for it, fills in its values, allocates space for storing
2085 * pointers to the cached demux packets and adds the packet to it. If
2086 * the packet contains an I or a P frame then ::flush_cached_dps is called
2087 * in order to send the old cached frames downstream.
2089 * \param demuxer The Matroska demuxer struct for this instance.
2090 * \param track The packet is meant for this track.
2091 * \param buffer The actual frame contents.
2092 * \param size The frame size in bytes.
2093 * \param block_bref A relative timecode (backward reference). If it is \c 0
2094 * then the frame is an I frame.
2095 * \param block_fref A relative timecode (forward reference). If it is \c 0
2096 * then the frame is either an I frame or a P frame depending on the value
2097 * of \a block_bref. Otherwise it's a B frame.
2099 static void handle_video_bframes(demuxer_t *demuxer, mkv_track_t *track,
2100 uint8_t *buffer, uint32_t size,
2101 int block_bref, int block_fref)
2103 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2104 demux_packet_t *dp;
2106 dp = new_demux_packet(size);
2107 memcpy(dp->buffer, buffer, size);
2108 dp->pos = demuxer->filepos;
2109 dp->pts = mkv_d->last_pts;
2110 if ((track->num_cached_dps > 0) && (dp->pts < track->max_pts))
2111 block_fref = 1;
2112 if (block_fref == 0) /* I or P frame */
2113 flush_cached_dps(demuxer, track);
2114 if (block_bref != 0) /* I frame, don't cache it */
2115 dp->flags = 0x10;
2116 if ((track->num_cached_dps + 1) > track->num_allocated_dps) {
2117 track->cached_dps = (demux_packet_t **)
2118 realloc(track->cached_dps,
2119 (track->num_cached_dps + 10) * sizeof(demux_packet_t *));
2120 track->num_allocated_dps += 10;
2122 track->cached_dps[track->num_cached_dps] = dp;
2123 track->num_cached_dps++;
2124 if (dp->pts > track->max_pts)
2125 track->max_pts = dp->pts;
2128 static int handle_block(demuxer_t *demuxer, uint8_t *block, uint64_t length,
2129 uint64_t block_duration, int64_t block_bref,
2130 int64_t block_fref, uint8_t simpleblock)
2132 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2133 mkv_track_t *track = NULL;
2134 demux_stream_t *ds = NULL;
2135 uint64_t old_length;
2136 int64_t tc;
2137 uint32_t *lace_size;
2138 uint8_t laces, flags;
2139 int i, num, tmp, use_this_block = 1;
2140 double current_pts;
2141 int16_t time;
2143 /* first byte(s): track num */
2144 num = ebml_read_vlen_uint(block, &tmp);
2145 block += tmp;
2146 /* time (relative to cluster time) */
2147 time = block[0] << 8 | block[1];
2148 block += 2;
2149 length -= tmp + 2;
2150 old_length = length;
2151 flags = block[0];
2152 if (demux_mkv_read_block_lacing(block, &length, &laces, &lace_size))
2153 return 0;
2154 block += old_length - length;
2156 tc = (time * mkv_d->tc_scale + mkv_d->cluster_tc) / 1000000.0 + 0.5;
2157 if (tc < 0)
2158 tc = 0;
2159 current_pts = tc / 1000.0;
2161 for (i = 0; i < mkv_d->num_tracks; i++)
2162 if (mkv_d->tracks[i]->tnum == num) {
2163 track = mkv_d->tracks[i];
2164 break;
2166 if (track == NULL) {
2167 free(lace_size);
2168 return 1;
2170 if (track->type == MATROSKA_TRACK_AUDIO
2171 && track->id == demuxer->audio->id) {
2172 ds = demuxer->audio;
2174 if (mkv_d->a_skip_to_keyframe) {
2175 if (simpleblock) {
2176 if (!(flags & 0x80)) /*current frame isn't a keyframe */
2177 use_this_block = 0;
2178 } else if (block_bref != 0)
2179 use_this_block = 0;
2180 } else if (mkv_d->v_skip_to_keyframe)
2181 use_this_block = 0;
2183 if (track->fix_i_bps && use_this_block) {
2184 sh_audio_t *sh = (sh_audio_t *) ds->sh;
2186 if (block_duration != 0) {
2187 sh->i_bps = length * 1000 / block_duration;
2188 track->fix_i_bps = 0;
2189 } else if (track->qt_last_a_pts == 0.0)
2190 track->qt_last_a_pts = current_pts;
2191 else if (track->qt_last_a_pts != current_pts) {
2192 sh->i_bps = length / (current_pts - track->qt_last_a_pts);
2193 track->fix_i_bps = 0;
2196 } else if (tc < mkv_d->skip_to_timecode)
2197 use_this_block = 0;
2198 else if (track->type == MATROSKA_TRACK_VIDEO
2199 && track->id == demuxer->video->id) {
2200 ds = demuxer->video;
2201 if (mkv_d->v_skip_to_keyframe) {
2202 if (simpleblock) {
2203 if (!(flags & 0x80)) /*current frame isn't a keyframe */
2204 use_this_block = 0;
2205 } else if (block_bref != 0 || block_fref != 0)
2206 use_this_block = 0;
2208 } else if (track->type == MATROSKA_TRACK_SUBTITLE
2209 && track->id == demuxer->sub->id) {
2210 ds = demuxer->sub;
2211 if (track->subtitle_type != MATROSKA_SUBTYPE_VOBSUB) {
2212 uint8_t *buffer;
2213 int size = length;
2214 demux_mkv_decode(track, block, &buffer, &size, 1);
2215 handle_subtitles(demuxer, track, buffer, size, block_duration, tc);
2216 if (buffer != block)
2217 talloc_free(buffer);
2218 use_this_block = 0;
2220 } else
2221 use_this_block = 0;
2223 if (use_this_block) {
2224 mkv_d->last_pts = current_pts;
2225 mkv_d->last_filepos = demuxer->filepos;
2227 for (i = 0; i < laces; i++) {
2228 if (ds == demuxer->video && track->realmedia)
2229 handle_realvideo(demuxer, track, block, lace_size[i],
2230 block_bref);
2231 else if (ds == demuxer->audio && track->realmedia)
2232 handle_realaudio(demuxer, track, block, lace_size[i],
2233 block_bref);
2234 else if (ds == demuxer->video && track->reorder_timecodes)
2235 handle_video_bframes(demuxer, track, block, lace_size[i],
2236 block_bref, block_fref);
2237 else {
2238 int size = lace_size[i];
2239 demux_packet_t *dp;
2240 uint8_t *buffer;
2241 demux_mkv_decode(track, block, &buffer, &size, 1);
2242 if (buffer) {
2243 dp = new_demux_packet(size);
2244 memcpy(dp->buffer, buffer, size);
2245 if (buffer != block)
2246 talloc_free(buffer);
2247 dp->flags = (block_bref == 0
2248 && block_fref == 0) ? 0x10 : 0;
2249 /* If default_duration is 0, assume no pts value is known
2250 * for packets after the first one (rather than all pts
2251 * values being the same) */
2252 if (i == 0 || track->default_duration)
2253 dp->pts =
2254 mkv_d->last_pts + i * track->default_duration;
2255 ds_add_packet(ds, dp);
2258 block += lace_size[i];
2261 if (ds == demuxer->video) {
2262 mkv_d->v_skip_to_keyframe = 0;
2263 mkv_d->skip_to_timecode = 0;
2264 } else if (ds == demuxer->audio)
2265 mkv_d->a_skip_to_keyframe = 0;
2267 free(lace_size);
2268 return 1;
2271 free(lace_size);
2272 return 0;
2275 static int demux_mkv_fill_buffer(demuxer_t *demuxer, demux_stream_t *ds)
2277 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2278 stream_t *s = demuxer->stream;
2279 uint64_t l;
2280 int il, tmp;
2282 while (1) {
2283 while (mkv_d->cluster_size > 0) {
2284 uint64_t block_duration = 0, block_length = 0;
2285 int64_t block_bref = 0, block_fref = 0;
2286 uint8_t *block = NULL;
2288 while (mkv_d->blockgroup_size > 0) {
2289 switch (ebml_read_id(s, &il)) {
2290 case MATROSKA_ID_BLOCKDURATION:
2291 block_duration = ebml_read_uint(s, &l);
2292 if (block_duration == EBML_UINT_INVALID) {
2293 free(block);
2294 return 0;
2296 block_duration =
2297 block_duration * mkv_d->tc_scale / 1000000.0 + 0.5;
2298 break;
2300 case MATROSKA_ID_BLOCK:
2301 block_length = ebml_read_length(s, &tmp);
2302 free(block);
2303 if (block_length > SIZE_MAX - AV_LZO_INPUT_PADDING)
2304 return 0;
2305 block = malloc(block_length + AV_LZO_INPUT_PADDING);
2306 demuxer->filepos = stream_tell(s);
2307 if (stream_read(s, block, block_length) !=
2308 (int) block_length) {
2309 free(block);
2310 return 0;
2312 l = tmp + block_length;
2313 break;
2315 case MATROSKA_ID_REFERENCEBLOCK:;
2316 int64_t num = ebml_read_int(s, &l);
2317 if (num == EBML_INT_INVALID) {
2318 free(block);
2319 return 0;
2321 if (num <= 0)
2322 block_bref = num;
2323 else
2324 block_fref = num;
2325 break;
2327 case EBML_ID_INVALID:
2328 free(block);
2329 return 0;
2331 default:
2332 ebml_read_skip(s, &l);
2333 break;
2335 mkv_d->blockgroup_size -= l + il;
2336 mkv_d->cluster_size -= l + il;
2339 if (block) {
2340 int res = handle_block(demuxer, block, block_length,
2341 block_duration, block_bref, block_fref,
2343 free(block);
2344 if (res < 0)
2345 return 0;
2346 if (res)
2347 return 1;
2350 if (mkv_d->cluster_size > 0) {
2351 switch (ebml_read_id(s, &il)) {
2352 case MATROSKA_ID_TIMECODE:;
2353 uint64_t num = ebml_read_uint(s, &l);
2354 if (num == EBML_UINT_INVALID)
2355 return 0;
2356 mkv_d->cluster_tc = num * mkv_d->tc_scale;
2357 add_cluster_position(mkv_d, mkv_d->cluster_start,
2358 mkv_d->cluster_tc);
2359 break;
2361 case MATROSKA_ID_BLOCKGROUP:
2362 mkv_d->blockgroup_size = ebml_read_length(s, &tmp);
2363 l = tmp;
2364 break;
2366 case MATROSKA_ID_SIMPLEBLOCK:;
2367 int res;
2368 block_length = ebml_read_length(s, &tmp);
2369 block = malloc(block_length);
2370 demuxer->filepos = stream_tell(s);
2371 if (stream_read(s, block, block_length) !=
2372 (int) block_length) {
2373 free(block);
2374 return 0;
2376 l = tmp + block_length;
2377 res = handle_block(demuxer, block, block_length,
2378 block_duration, block_bref,
2379 block_fref, 1);
2380 free(block);
2381 mkv_d->cluster_size -= l + il;
2382 if (res < 0)
2383 return 0;
2384 else if (res)
2385 return 1;
2386 else
2387 mkv_d->cluster_size += l + il;
2388 break;
2390 case EBML_ID_INVALID:
2391 return 0;
2393 default:
2394 ebml_read_skip(s, &l);
2395 break;
2397 mkv_d->cluster_size -= l + il;
2401 while (ebml_read_id(s, &il) != MATROSKA_ID_CLUSTER) {
2402 ebml_read_skip(s, NULL);
2403 if (s->eof)
2404 return 0;
2406 mkv_d->cluster_start = stream_tell(s) - il;
2407 mkv_d->cluster_size = ebml_read_length(s, NULL);
2410 return 0;
2413 static void demux_mkv_seek(demuxer_t *demuxer, float rel_seek_secs,
2414 float audio_delay, int flags)
2416 mkv_demuxer_t *mkv_d = demuxer->priv;
2417 uint64_t v_tnum = -1;
2418 if (demuxer->video->id >= 0)
2419 v_tnum = find_track_by_num(mkv_d, demuxer->video->id,
2420 MATROSKA_TRACK_VIDEO)->tnum;
2421 uint64_t a_tnum = -1;
2422 if (demuxer->audio->id >= 0)
2423 a_tnum = find_track_by_num(mkv_d, demuxer->audio->id,
2424 MATROSKA_TRACK_AUDIO)->tnum;
2425 if (!(flags & (SEEK_BACKWARD | SEEK_FORWARD))) {
2426 if (flags & SEEK_ABSOLUTE || rel_seek_secs < 0)
2427 flags |= SEEK_BACKWARD;
2428 else
2429 flags |= SEEK_FORWARD;
2431 // Adjust the target a little bit to catch cases where the target position
2432 // specifies a keyframe with high, but not perfect, precision.
2433 rel_seek_secs += flags & SEEK_FORWARD ? -0.005 : 0.005;
2435 free_cached_dps(demuxer);
2436 if (!(flags & SEEK_FACTOR)) { /* time in secs */
2437 mkv_index_t *index = NULL;
2438 stream_t *s = demuxer->stream;
2439 int64_t target_timecode = 0, diff, min_diff = 0xFFFFFFFFFFFFFFFLL;
2440 int i;
2442 if (!(flags & SEEK_ABSOLUTE)) /* relative seek */
2443 target_timecode = (int64_t) (mkv_d->last_pts * 1000.0);
2444 target_timecode += (int64_t) (rel_seek_secs * 1000.0);
2445 if (target_timecode < 0)
2446 target_timecode = 0;
2448 if (mkv_d->indexes == NULL) { /* no index was found */
2449 int64_t target_tc_ns = (int64_t) (rel_seek_secs * 1e9);
2450 if (target_tc_ns < 0)
2451 target_tc_ns = 0;
2452 uint64_t max_filepos = 0;
2453 int64_t max_tc = -1;
2454 int n = mkv_d->num_cluster_pos;
2455 if (n > 0) {
2456 max_filepos = mkv_d->cluster_positions[n - 1].filepos;
2457 max_tc = mkv_d->cluster_positions[n - 1].timecode;
2460 if (target_tc_ns > max_tc) {
2461 if ((off_t) max_filepos > stream_tell(s))
2462 stream_seek(s, max_filepos);
2463 else
2464 stream_seek(s, stream_tell(s) + mkv_d->cluster_size);
2465 /* parse all the clusters upto target_filepos */
2466 while (!s->eof) {
2467 uint64_t start = stream_tell(s);
2468 uint32_t type = ebml_read_id(s, NULL);
2469 uint64_t len = ebml_read_length(s, NULL);
2470 uint64_t end = stream_tell(s) + len;
2471 if (type == MATROSKA_ID_CLUSTER) {
2472 while (!s->eof && stream_tell(s) < end) {
2473 if (ebml_read_id(s, NULL)
2474 == MATROSKA_ID_TIMECODE) {
2475 uint64_t tc = ebml_read_uint(s, NULL);
2476 tc *= mkv_d->tc_scale;
2477 add_cluster_position(mkv_d, start, tc);
2478 if (tc >= target_tc_ns)
2479 goto enough_index;
2480 break;
2484 stream_seek(s, end);
2486 enough_index:
2487 if (s->eof)
2488 stream_reset(s);
2490 if (!mkv_d->num_cluster_pos) {
2491 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] no target for seek found\n");
2492 return;
2494 uint64_t cluster_pos = mkv_d->cluster_positions[0].filepos;
2495 /* Let's find the nearest cluster */
2496 for (i = 0; i < mkv_d->num_cluster_pos; i++) {
2497 diff = mkv_d->cluster_positions[i].timecode - target_tc_ns;
2498 if (flags & SEEK_BACKWARD && diff < 0 && -diff < min_diff) {
2499 cluster_pos = mkv_d->cluster_positions[i].filepos;
2500 min_diff = -diff;
2501 } else if (flags & SEEK_FORWARD
2502 && (diff < 0 ? -1 * diff : diff) < min_diff) {
2503 cluster_pos = mkv_d->cluster_positions[i].filepos;
2504 min_diff = diff < 0 ? -1 * diff : diff;
2507 mkv_d->cluster_size = mkv_d->blockgroup_size = 0;
2508 stream_seek(s, cluster_pos);
2509 } else {
2510 int seek_id = (demuxer->video->id < 0) ?
2511 a_tnum : v_tnum;
2513 /* let's find the entry in the indexes with the smallest */
2514 /* difference to the wanted timecode. */
2515 for (i = 0; i < mkv_d->num_indexes; i++)
2516 if (mkv_d->indexes[i].tnum == seek_id) {
2517 diff =
2518 target_timecode -
2519 (int64_t) (mkv_d->indexes[i].timecode *
2520 mkv_d->tc_scale / 1000000.0 + 0.5);
2522 if (flags & SEEK_BACKWARD) {
2523 // Seek backward: find the last index position
2524 // before target time
2525 if (diff < 0 || diff >= min_diff)
2526 continue;
2527 } else {
2528 // Seek forward: find the first index position
2529 // after target time. If no such index exists, find last
2530 // position between current position and target time.
2531 if (diff <= 0) {
2532 if (min_diff <= 0 && diff <= min_diff)
2533 continue;
2534 } else if (diff >=
2535 FFMIN(target_timecode - mkv_d->last_pts,
2536 min_diff))
2537 continue;
2539 min_diff = diff;
2540 index = mkv_d->indexes + i;
2543 if (index) { /* We've found an entry. */
2544 mkv_d->cluster_size = mkv_d->blockgroup_size = 0;
2545 stream_seek(s, index->filepos);
2549 if (demuxer->video->id >= 0)
2550 mkv_d->v_skip_to_keyframe = 1;
2551 if (flags & SEEK_FORWARD)
2552 mkv_d->skip_to_timecode = target_timecode;
2553 else
2554 mkv_d->skip_to_timecode = index ? index->timecode : 0;
2555 mkv_d->a_skip_to_keyframe = 1;
2557 demux_mkv_fill_buffer(demuxer, NULL);
2558 } else if ((demuxer->movi_end <= 0) || !(flags & SEEK_ABSOLUTE))
2559 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] seek unsupported flags\n");
2560 else {
2561 stream_t *s = demuxer->stream;
2562 uint64_t target_filepos;
2563 mkv_index_t *index = NULL;
2564 int i;
2566 if (mkv_d->indexes == NULL) { /* not implemented without index */
2567 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] seek unsupported flags\n");
2568 return;
2571 target_filepos = (uint64_t) (demuxer->movi_end * rel_seek_secs);
2572 for (i = 0; i < mkv_d->num_indexes; i++)
2573 if (mkv_d->indexes[i].tnum == v_tnum)
2574 if ((index == NULL)
2575 || ((mkv_d->indexes[i].filepos >= target_filepos)
2576 && ((index->filepos < target_filepos)
2577 || (mkv_d->indexes[i].filepos < index->filepos))))
2578 index = &mkv_d->indexes[i];
2580 if (!index)
2581 return;
2583 mkv_d->cluster_size = mkv_d->blockgroup_size = 0;
2584 stream_seek(s, index->filepos);
2586 if (demuxer->video->id >= 0)
2587 mkv_d->v_skip_to_keyframe = 1;
2588 mkv_d->skip_to_timecode = index->timecode;
2589 mkv_d->a_skip_to_keyframe = 1;
2591 demux_mkv_fill_buffer(demuxer, NULL);
2595 static int demux_mkv_control(demuxer_t *demuxer, int cmd, void *arg)
2597 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2599 switch (cmd) {
2600 case DEMUXER_CTRL_CORRECT_PTS:
2601 return DEMUXER_CTRL_OK;
2602 case DEMUXER_CTRL_GET_TIME_LENGTH:
2603 if (mkv_d->duration == 0)
2604 return DEMUXER_CTRL_DONTKNOW;
2606 *((double *) arg) = (double) mkv_d->duration;
2607 return DEMUXER_CTRL_OK;
2609 case DEMUXER_CTRL_GET_PERCENT_POS:
2610 if (mkv_d->duration == 0) {
2611 return DEMUXER_CTRL_DONTKNOW;
2614 *((int *) arg) = (int) (100 * mkv_d->last_pts / mkv_d->duration);
2615 return DEMUXER_CTRL_OK;
2617 case DEMUXER_CTRL_SWITCH_AUDIO:;
2618 int new_aid = *(int *) arg;
2619 int current_aid = demuxer->audio->id;
2620 if (current_aid < 0)
2621 current_aid = -1;
2622 if (new_aid == -1) // cycle to next
2623 new_aid = (current_aid + 2) % (mkv_d->num_audio_tracks + 1) - 1;
2624 if (new_aid < 0 || new_aid >= mkv_d->num_audio_tracks)
2625 new_aid = -2;
2626 *(int *) arg = new_aid;
2627 if (current_aid != new_aid)
2628 ds_free_packs(demuxer->audio);
2629 demuxer->audio->id = new_aid;
2630 return DEMUXER_CTRL_OK;
2632 default:
2633 return DEMUXER_CTRL_NOTIMPL;
2637 const demuxer_desc_t demuxer_desc_matroska = {
2638 "Matroska demuxer",
2639 "mkv",
2640 "Matroska",
2641 "Aurelien Jacobs",
2643 DEMUXER_TYPE_MATROSKA,
2644 1, // safe autodetect
2645 demux_mkv_open,
2646 demux_mkv_fill_buffer,
2647 NULL,
2648 demux_close_mkv,
2649 demux_mkv_seek,
2650 demux_mkv_control