demux_mkv: respect -forceidx
[mplayer/glamo.git] / libmpdemux / demux_mkv.c
blob0cf2505965c9f2678143916a748f1e45b79437ce
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 "stream/stream.h"
35 #include "demuxer.h"
36 #include "stheader.h"
37 #include "ebml.h"
38 #include "matroska.h"
40 #include "mp_msg.h"
41 #include "help_mp.h"
43 #include "vobsub.h"
44 #include "subreader.h"
45 #include "libvo/sub.h"
47 #include "ass_mp.h"
49 #include "libavutil/common.h"
51 #ifdef CONFIG_QTX_CODECS
52 #include "loader/qtx/qtxsdk/components.h"
53 #endif
55 #if CONFIG_ZLIB
56 #include <zlib.h>
57 #endif
59 #include "libavutil/lzo.h"
60 #include "ffmpeg_files/intreadwrite.h"
61 #include "libavutil/avstring.h"
63 static const unsigned char sipr_swaps[38][2] = {
64 {0,63},{1,22},{2,44},{3,90},{5,81},{7,31},{8,86},{9,58},{10,36},{12,68},
65 {13,39},{14,73},{15,53},{16,69},{17,57},{19,88},{20,34},{21,71},{24,46},
66 {25,94},{26,54},{28,75},{29,50},{32,70},{33,92},{35,74},{38,85},{40,56},
67 {42,87},{43,65},{45,59},{48,79},{49,93},{51,89},{55,95},{61,76},{67,83},
68 {77,80}
71 // Map flavour to bytes per second
72 #define SIPR_FLAVORS 4
73 #define ATRC_FLAVORS 8
74 #define COOK_FLAVORS 34
75 static const int sipr_fl2bps[SIPR_FLAVORS] = { 813, 1062, 625, 2000 };
76 static const int atrc_fl2bps[ATRC_FLAVORS] =
77 { 8269, 11714, 13092, 16538, 18260, 22050, 33075, 44100 };
78 static const int cook_fl2bps[COOK_FLAVORS] = {
79 1000, 1378, 2024, 2584, 4005, 5513, 8010, 4005, 750, 2498,
80 4048, 5513, 8010, 11973, 8010, 2584, 4005, 2067, 2584, 2584,
81 4005, 4005, 5513, 5513, 8010, 12059, 1550, 8010, 12059, 5513,
82 12016, 16408, 22911, 33506
85 typedef struct {
86 uint32_t order, type, scope;
87 uint32_t comp_algo;
88 uint8_t *comp_settings;
89 int comp_settings_len;
90 } mkv_content_encoding_t;
92 typedef struct mkv_track {
93 int tnum;
94 char *name;
96 char *codec_id;
97 int ms_compat;
98 char *language;
100 int type;
102 uint32_t v_width, v_height, v_dwidth, v_dheight;
103 double v_frate;
105 uint32_t a_formattag;
106 uint32_t a_channels, a_bps;
107 float a_sfreq;
109 double default_duration;
111 int default_track;
113 unsigned char *private_data;
114 unsigned int private_size;
116 /* stuff for realmedia */
117 int realmedia;
118 int64_t rv_kf_base;
119 int rv_kf_pts;
120 double rv_pts; /* previous video timestamp */
121 double ra_pts; /* previous audio timestamp */
123 /** realaudio descrambling */
124 int sub_packet_size; ///< sub packet size, per stream
125 int sub_packet_h; ///< number of coded frames per block
126 int coded_framesize; ///< coded frame size, per stream
127 int audiopk_size; ///< audio packet size
128 unsigned char *audio_buf; ///< place to store reordered audio data
129 double *audio_timestamp; ///< timestamp for each audio packet
130 int sub_packet_cnt; ///< number of subpacket already received
131 int audio_filepos; ///< file position of first audio packet in block
133 /* stuff for quicktime */
134 int fix_i_bps;
135 double qt_last_a_pts;
137 int subtitle_type;
139 /* The timecodes of video frames might have to be reordered if they're
140 in display order (the timecodes, not the frames themselves!). In this
141 case demux packets have to be cached with the help of these variables. */
142 int reorder_timecodes;
143 demux_packet_t **cached_dps;
144 int num_cached_dps, num_allocated_dps;
145 double max_pts;
147 /* generic content encoding support */
148 mkv_content_encoding_t *encodings;
149 int num_encodings;
151 /* For VobSubs and SSA/ASS */
152 sh_sub_t *sh_sub;
153 } mkv_track_t;
155 typedef struct mkv_index {
156 int tnum;
157 uint64_t timecode, filepos;
158 } mkv_index_t;
160 typedef struct mkv_demuxer {
161 off_t segment_start;
163 double duration, last_pts;
164 uint64_t last_filepos;
166 mkv_track_t **tracks;
167 int num_tracks;
169 uint64_t tc_scale, cluster_tc;
171 uint64_t cluster_size;
172 uint64_t blockgroup_size;
174 mkv_index_t *indexes;
175 int num_indexes;
177 off_t *parsed_cues;
178 int parsed_cues_num;
179 off_t *parsed_seekhead;
180 int parsed_seekhead_num;
182 uint64_t *cluster_positions;
183 int num_cluster_pos;
185 int64_t skip_to_timecode;
186 int v_skip_to_keyframe, a_skip_to_keyframe;
188 int last_aid;
189 int audio_tracks[MAX_A_STREAMS];
190 } mkv_demuxer_t;
192 #define REALHEADER_SIZE 16
193 #define RVPROPERTIES_SIZE 34
194 #define RAPROPERTIES4_SIZE 56
195 #define RAPROPERTIES5_SIZE 70
198 * \brief ensures there is space for at least one additional element
199 * \param array array to grow
200 * \param nelem current number of elements in array
201 * \param elsize size of one array element
203 static void *grow_array(void *array, int nelem, size_t elsize)
205 if (!(nelem & 31))
206 array = realloc(array, (nelem + 32) * elsize);
207 return array;
210 static mkv_track_t *demux_mkv_find_track_by_num(mkv_demuxer_t *d, int n,
211 int type)
213 int i, id;
215 for (i = 0, id = 0; i < d->num_tracks; i++)
216 if (d->tracks[i] != NULL && d->tracks[i]->type == type)
217 if (id++ == n)
218 return d->tracks[i];
220 return NULL;
223 static void add_cluster_position(mkv_demuxer_t *mkv_d, uint64_t position)
225 int i = mkv_d->num_cluster_pos;
227 while (i--)
228 if (mkv_d->cluster_positions[i] == position)
229 return;
231 mkv_d->cluster_positions =
232 grow_array(mkv_d->cluster_positions, mkv_d->num_cluster_pos,
233 sizeof(uint64_t));
234 mkv_d->cluster_positions[mkv_d->num_cluster_pos++] = position;
238 #define AAC_SYNC_EXTENSION_TYPE 0x02b7
239 static int aac_get_sample_rate_index(uint32_t sample_rate)
241 static const int srates[] = {
242 92017, 75132, 55426, 46009, 37566, 27713,
243 23004, 18783, 13856, 11502, 9391, 0
245 int i = 0;
246 while (sample_rate < srates[i])
247 i++;
248 return i;
251 /** \brief Free cached demux packets
253 * Reordering the timecodes requires caching of demux packets. This function
254 * frees all these cached packets and the memory for the cached pointers
255 * itself.
257 * \param demuxer The demuxer for which the cache is to be freed.
259 static void free_cached_dps(demuxer_t *demuxer)
261 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
262 mkv_track_t *track;
263 int i, k;
265 for (k = 0; k < mkv_d->num_tracks; k++) {
266 track = mkv_d->tracks[k];
267 for (i = 0; i < track->num_cached_dps; i++)
268 free_demux_packet(track->cached_dps[i]);
269 free(track->cached_dps);
270 track->cached_dps = NULL;
271 track->num_cached_dps = 0;
272 track->num_allocated_dps = 0;
273 track->max_pts = 0;
277 static int demux_mkv_decode(mkv_track_t *track, uint8_t *src,
278 uint8_t **dest, uint32_t *size, uint32_t type)
280 int i, result;
281 int modified = 0;
283 *dest = src;
284 if (track->num_encodings <= 0)
285 return 0;
287 for (i = 0; i < track->num_encodings; i++) {
288 if (!(track->encodings[i].scope & type))
289 continue;
291 #if CONFIG_ZLIB
292 if (track->encodings[i].comp_algo == 0) {
293 /* zlib encoded track */
294 z_stream zstream;
296 zstream.zalloc = (alloc_func) 0;
297 zstream.zfree = (free_func) 0;
298 zstream.opaque = (voidpf) 0;
299 if (inflateInit(&zstream) != Z_OK) {
300 mp_tmsg(MSGT_DEMUX, MSGL_WARN,
301 "[mkv] zlib initialization failed.\n");
302 return modified;
304 zstream.next_in = (Bytef *) src;
305 zstream.avail_in = *size;
307 modified = 1;
308 *dest = NULL;
309 zstream.avail_out = *size;
310 do {
311 *size += 4000;
312 *dest = realloc(*dest, *size);
313 zstream.next_out = (Bytef *) (*dest + zstream.total_out);
314 result = inflate(&zstream, Z_NO_FLUSH);
315 if (result != Z_OK && result != Z_STREAM_END) {
316 mp_tmsg(MSGT_DEMUX, MSGL_WARN,
317 "[mkv] zlib decompression failed.\n");
318 free(*dest);
319 *dest = NULL;
320 inflateEnd(&zstream);
321 return modified;
323 zstream.avail_out += 4000;
324 } while (zstream.avail_out == 4000 && zstream.avail_in != 0
325 && result != Z_STREAM_END);
327 *size = zstream.total_out;
328 inflateEnd(&zstream);
330 #endif
331 if (track->encodings[i].comp_algo == 2) {
332 /* lzo encoded track */
333 int dstlen = *size * 3;
335 *dest = NULL;
336 while (1) {
337 int srclen = *size;
338 if (dstlen > SIZE_MAX - AV_LZO_OUTPUT_PADDING)
339 goto lzo_fail;
340 *dest = realloc(*dest, dstlen + AV_LZO_OUTPUT_PADDING);
341 result = av_lzo1x_decode(*dest, &dstlen, src, &srclen);
342 if (result == 0)
343 break;
344 if (!(result & AV_LZO_OUTPUT_FULL)) {
345 lzo_fail:
346 mp_tmsg(MSGT_DEMUX, MSGL_WARN,
347 "[mkv] lzo decompression failed.\n");
348 free(*dest);
349 *dest = NULL;
350 return modified;
352 mp_msg(MSGT_DEMUX, MSGL_DBG2,
353 "[mkv] lzo decompression buffer too small.\n");
354 dstlen *= 2;
356 *size = dstlen;
360 return modified;
364 static int demux_mkv_read_info(demuxer_t *demuxer)
366 mkv_demuxer_t *mkv_d = demuxer->priv;
367 stream_t *s = demuxer->stream;
368 uint64_t length, l;
369 int i;
370 uint64_t tc_scale = 1000000;
371 long double duration = 0.;
373 length = ebml_read_length(s, NULL);
374 while (length > 0) {
375 uint32_t id = ebml_read_id(s, &i);
376 length -= i;
377 switch (id) {
378 case MATROSKA_ID_TIMECODESCALE:
379 tc_scale = ebml_read_uint(s, &l);
380 length -= l;
381 if (tc_scale == EBML_UINT_INVALID)
382 return 1;
383 mp_msg(MSGT_DEMUX, MSGL_V,
384 "[mkv] | + timecode scale: %" PRIu64 "\n", tc_scale);
385 break;
387 case MATROSKA_ID_DURATION:
388 duration = ebml_read_float(s, &l);
389 length -= l;
390 if (duration == EBML_FLOAT_INVALID)
391 return 1;
392 break;
394 case MATROSKA_ID_SEGMENTUID:;
395 l = ebml_read_length(s, &i);
396 length -= i;
397 if (l != sizeof(demuxer->matroska_data.segment_uid)) {
398 mp_msg(MSGT_DEMUX, MSGL_INFO,
399 "[mkv] segment uid invalid length %" PRIu64 "\n", l);
400 stream_skip(s, l);
401 } else {
402 stream_read(s, demuxer->matroska_data.segment_uid, l);
403 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + segment uid");
404 for (int i = 0; i < l; i++)
405 mp_msg(MSGT_DEMUX, MSGL_V, " %02x",
406 demuxer->matroska_data.segment_uid[i]);
407 mp_msg(MSGT_DEMUX, MSGL_V, "\n");
409 length -= l;
410 break;
412 default:
413 ebml_read_skip(s, &l);
414 length -= l;
415 break;
418 mkv_d->tc_scale = tc_scale;
419 mkv_d->duration = duration * tc_scale / 1000000000.0;
420 if (duration)
421 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + duration: %.3fs\n",
422 mkv_d->duration);
424 return 0;
428 * \brief free array of kv_content_encoding_t
429 * \param encodings pointer to array
430 * \param numencodings number of encodings in array
432 static void demux_mkv_free_encodings(mkv_content_encoding_t *encodings,
433 int numencodings)
435 while (numencodings-- > 0)
436 free(encodings[numencodings].comp_settings);
437 free(encodings);
440 static int demux_mkv_read_trackencodings(demuxer_t *demuxer,
441 mkv_track_t *track)
443 stream_t *s = demuxer->stream;
444 mkv_content_encoding_t *ce, e;
445 uint64_t len1, len2, length, l;
446 int i, il, n;
448 ce = malloc(sizeof(*ce));
449 n = 0;
451 len1 = length = ebml_read_length(s, &il);
452 len1 += il;
453 while (length > 0) {
454 switch (ebml_read_id(s, &il)) {
455 case MATROSKA_ID_CONTENTENCODING:
456 memset(&e, 0, sizeof(e));
457 e.scope = 1;
459 len2 = ebml_read_length(s, &i);
460 l = len2 + i;
462 while (len2 > 0) {
463 uint64_t num, l;
464 int il;
466 switch (ebml_read_id(s, &il)) {
467 case MATROSKA_ID_CONTENTENCODINGORDER:
468 num = ebml_read_uint(s, &l);
469 if (num == EBML_UINT_INVALID)
470 goto err_out;
471 e.order = num;
472 break;
474 case MATROSKA_ID_CONTENTENCODINGSCOPE:
475 num = ebml_read_uint(s, &l);
476 if (num == EBML_UINT_INVALID)
477 goto err_out;
478 e.scope = num;
479 break;
481 case MATROSKA_ID_CONTENTENCODINGTYPE:
482 num = ebml_read_uint(s, &l);
483 if (num == EBML_UINT_INVALID)
484 goto err_out;
485 e.type = num;
486 break;
488 case MATROSKA_ID_CONTENTCOMPRESSION:;
489 uint64_t le;
491 le = ebml_read_length(s, &i);
492 l = le + i;
494 while (le > 0) {
495 uint64_t l;
496 int il;
498 switch (ebml_read_id(s, &il)) {
499 case MATROSKA_ID_CONTENTCOMPALGO:
500 num = ebml_read_uint(s, &l);
501 if (num == EBML_UINT_INVALID)
502 goto err_out;
503 e.comp_algo = num;
504 break;
506 case MATROSKA_ID_CONTENTCOMPSETTINGS:
507 l = ebml_read_length(s, &i);
508 e.comp_settings = malloc(l);
509 stream_read(s, e.comp_settings, l);
510 e.comp_settings_len = l;
511 l += i;
512 break;
514 default:
515 ebml_read_skip(s, &l);
516 break;
518 le -= l + il;
521 if (e.type == 1) {
522 mp_tmsg(MSGT_DEMUX, MSGL_WARN, "[mkv] Track "
523 "number %u has been encrypted and "
524 "decryption has not yet been\n"
525 "[mkv] implemented. Skipping track.\n",
526 track->tnum);
527 } else if (e.type != 0) {
528 mp_tmsg(MSGT_DEMUX, MSGL_WARN,
529 "[mkv] Unknown content encoding type for "
530 "track %u. Skipping track.\n",
531 track->tnum);
534 if (e.comp_algo != 0 && e.comp_algo != 2) {
535 mp_tmsg(MSGT_DEMUX, MSGL_WARN,
536 "[mkv] Track %u has been compressed with "
537 "an unknown/unsupported compression\n"
538 "[mkv] algorithm (%u). Skipping track.\n",
539 track->tnum, e.comp_algo);
541 #if !CONFIG_ZLIB
542 else if (e.comp_algo == 0) {
543 mp_tmsg(MSGT_DEMUX, MSGL_WARN,
544 "[mkv] Track %u was compressed with zlib "
545 "but mplayer has not been compiled\n"
546 "[mkv] with support for zlib compression. "
547 "Skipping track.\n",
548 track->tnum);
550 #endif
552 break;
554 default:
555 ebml_read_skip(s, &l);
556 break;
558 len2 -= l + il;
560 for (i = 0; i < n; i++)
561 if (e.order <= ce[i].order)
562 break;
563 ce = realloc(ce, (n + 1) * sizeof(*ce));
564 memmove(ce + i + 1, ce + i, (n - i) * sizeof(*ce));
565 memcpy(ce + i, &e, sizeof(e));
566 n++;
567 break;
569 default:
570 ebml_read_skip(s, &l);
571 break;
574 length -= l + il;
577 track->encodings = ce;
578 track->num_encodings = n;
579 return len1;
581 err_out:
582 demux_mkv_free_encodings(ce, n);
583 return 0;
586 static int demux_mkv_read_trackaudio(demuxer_t *demuxer, mkv_track_t *track)
588 stream_t *s = demuxer->stream;
589 uint64_t len, length, l;
590 uint64_t num;
591 long double fnum;
592 int il;
594 track->a_sfreq = 8000.0;
595 track->a_channels = 1;
597 len = length = ebml_read_length(s, &il);
598 len += il;
599 while (length > 0) {
600 switch (ebml_read_id(s, &il)) {
601 case MATROSKA_ID_AUDIOSAMPLINGFREQ:
602 fnum = ebml_read_float(s, &l);
603 if (fnum == EBML_FLOAT_INVALID)
604 return 0;
605 track->a_sfreq = fnum;
606 mp_msg(MSGT_DEMUX, MSGL_V,
607 "[mkv] | + Sampling frequency: %f\n", track->a_sfreq);
608 break;
610 case MATROSKA_ID_AUDIOBITDEPTH:
611 num = ebml_read_uint(s, &l);
612 if (num == EBML_UINT_INVALID)
613 return 0;
614 track->a_bps = num;
615 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Bit depth: %u\n",
616 track->a_bps);
617 break;
619 case MATROSKA_ID_AUDIOCHANNELS:
620 num = ebml_read_uint(s, &l);
621 if (num == EBML_UINT_INVALID)
622 return 0;
623 track->a_channels = num;
624 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Channels: %u\n",
625 track->a_channels);
626 break;
628 default:
629 ebml_read_skip(s, &l);
630 break;
632 length -= l + il;
634 return len;
637 static int demux_mkv_read_trackvideo(demuxer_t *demuxer, mkv_track_t *track)
639 stream_t *s = demuxer->stream;
640 uint64_t len, length, l;
641 uint64_t num;
642 long double fnum;
643 int il;
645 len = length = ebml_read_length(s, &il);
646 len += il;
647 while (length > 0) {
648 switch (ebml_read_id(s, &il)) {
649 case MATROSKA_ID_VIDEOFRAMERATE:
650 fnum = ebml_read_float(s, &l);
651 if (fnum == EBML_FLOAT_INVALID)
652 return 0;
653 track->v_frate = fnum;
654 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Frame rate: %f\n",
655 track->v_frate);
656 if (track->v_frate > 0)
657 track->default_duration = 1 / track->v_frate;
658 break;
660 case MATROSKA_ID_VIDEODISPLAYWIDTH:
661 num = ebml_read_uint(s, &l);
662 if (num == EBML_UINT_INVALID)
663 return 0;
664 track->v_dwidth = num;
665 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Display width: %u\n",
666 track->v_dwidth);
667 break;
669 case MATROSKA_ID_VIDEODISPLAYHEIGHT:
670 num = ebml_read_uint(s, &l);
671 if (num == EBML_UINT_INVALID)
672 return 0;
673 track->v_dheight = num;
674 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Display height: %u\n",
675 track->v_dheight);
676 break;
678 case MATROSKA_ID_VIDEOPIXELWIDTH:
679 num = ebml_read_uint(s, &l);
680 if (num == EBML_UINT_INVALID)
681 return 0;
682 track->v_width = num;
683 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Pixel width: %u\n",
684 track->v_width);
685 break;
687 case MATROSKA_ID_VIDEOPIXELHEIGHT:
688 num = ebml_read_uint(s, &l);
689 if (num == EBML_UINT_INVALID)
690 return 0;
691 track->v_height = num;
692 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Pixel height: %u\n",
693 track->v_height);
694 break;
696 default:
697 ebml_read_skip(s, &l);
698 break;
700 length -= l + il;
702 return len;
706 * \brief free any data associated with given track
707 * \param track track of which to free data
709 static void demux_mkv_free_trackentry(mkv_track_t *track)
711 free(track->name);
712 free(track->codec_id);
713 free(track->language);
714 free(track->private_data);
715 free(track->audio_buf);
716 free(track->audio_timestamp);
717 demux_mkv_free_encodings(track->encodings, track->num_encodings);
718 free(track);
721 static int demux_mkv_read_trackentry(demuxer_t *demuxer)
723 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
724 stream_t *s = demuxer->stream;
725 mkv_track_t *track;
726 uint64_t len, length, l;
727 uint64_t num;
728 int il;
730 track = calloc(1, sizeof(*track));
731 /* set default values */
732 track->default_track = 1;
733 track->name = 0;
734 track->language = strdup("eng");
736 len = length = ebml_read_length(s, &il);
737 len += il;
738 while (length > 0) {
739 switch (ebml_read_id(s, &il)) {
740 case MATROSKA_ID_TRACKNUMBER:
741 num = ebml_read_uint(s, &l);
742 if (num == EBML_UINT_INVALID)
743 goto err_out;
744 track->tnum = num;
745 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Track number: %u\n",
746 track->tnum);
747 break;
749 case MATROSKA_ID_TRACKNAME:
750 track->name = ebml_read_utf8(s, &l);
751 if (track->name == NULL)
752 goto err_out;
753 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Name: %s\n",
754 track->name);
755 break;
757 case MATROSKA_ID_TRACKTYPE:
758 num = ebml_read_uint(s, &l);
759 if (num == EBML_UINT_INVALID)
760 return 0;
761 track->type = num;
762 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Track type: ");
763 switch (track->type) {
764 case MATROSKA_TRACK_AUDIO:
765 mp_msg(MSGT_DEMUX, MSGL_V, "Audio\n");
766 break;
767 case MATROSKA_TRACK_VIDEO:
768 mp_msg(MSGT_DEMUX, MSGL_V, "Video\n");
769 break;
770 case MATROSKA_TRACK_SUBTITLE:
771 mp_msg(MSGT_DEMUX, MSGL_V, "Subtitle\n");
772 break;
773 default:
774 mp_msg(MSGT_DEMUX, MSGL_V, "unknown\n");
775 break;
777 break;
779 case MATROSKA_ID_TRACKAUDIO:
780 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Audio track\n");
781 l = demux_mkv_read_trackaudio(demuxer, track);
782 if (l == 0)
783 goto err_out;
784 break;
786 case MATROSKA_ID_TRACKVIDEO:
787 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Video track\n");
788 l = demux_mkv_read_trackvideo(demuxer, track);
789 if (l == 0)
790 goto err_out;
791 break;
793 case MATROSKA_ID_CODECID:
794 track->codec_id = ebml_read_ascii(s, &l);
795 if (track->codec_id == NULL)
796 goto err_out;
797 if (!strcmp(track->codec_id, MKV_V_MSCOMP)
798 || !strcmp(track->codec_id, MKV_A_ACM))
799 track->ms_compat = 1;
800 else if (!strcmp(track->codec_id, MKV_S_VOBSUB))
801 track->subtitle_type = MATROSKA_SUBTYPE_VOBSUB;
802 else if (!strcmp(track->codec_id, MKV_S_TEXTSSA)
803 || !strcmp(track->codec_id, MKV_S_TEXTASS)
804 || !strcmp(track->codec_id, MKV_S_SSA)
805 || !strcmp(track->codec_id, MKV_S_ASS)) {
806 track->subtitle_type = MATROSKA_SUBTYPE_SSA;
807 } else if (!strcmp(track->codec_id, MKV_S_TEXTASCII))
808 track->subtitle_type = MATROSKA_SUBTYPE_TEXT;
809 if (!strcmp(track->codec_id, MKV_S_TEXTUTF8)) {
810 track->subtitle_type = MATROSKA_SUBTYPE_TEXT;
812 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Codec ID: %s\n",
813 track->codec_id);
814 break;
816 case MATROSKA_ID_CODECPRIVATE:;
817 int x;
818 num = ebml_read_length(s, &x);
819 // audit: cheap guard against overflows later..
820 if (num > SIZE_MAX - 1000)
821 return 0;
822 l = x + num;
823 track->private_data = malloc(num + AV_LZO_INPUT_PADDING);
824 if (stream_read(s, track->private_data, num) != (int) num)
825 goto err_out;
826 track->private_size = num;
827 mp_msg(MSGT_DEMUX, MSGL_V,
828 "[mkv] | + CodecPrivate, length " "%u\n",
829 track->private_size);
830 break;
832 case MATROSKA_ID_TRACKLANGUAGE:
833 free(track->language);
834 track->language = ebml_read_utf8(s, &l);
835 if (track->language == NULL)
836 goto err_out;
837 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Language: %s\n",
838 track->language);
839 break;
841 case MATROSKA_ID_TRACKFLAGDEFAULT:
842 num = ebml_read_uint(s, &l);
843 if (num == EBML_UINT_INVALID)
844 goto err_out;
845 track->default_track = num;
846 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Default flag: %u\n",
847 track->default_track);
848 break;
850 case MATROSKA_ID_TRACKDEFAULTDURATION:
851 num = ebml_read_uint(s, &l);
852 if (num == EBML_UINT_INVALID)
853 goto err_out;
854 if (num == 0)
855 mp_msg(MSGT_DEMUX, MSGL_V,
856 "[mkv] | + Default duration: 0");
857 else {
858 track->v_frate = 1000000000.0 / num;
859 track->default_duration = num / 1000000000.0;
860 mp_msg(MSGT_DEMUX, MSGL_V,
861 "[mkv] | + Default duration: "
862 "%.3fms ( = %.3f fps)\n", num / 1000000.0,
863 track->v_frate);
865 break;
867 case MATROSKA_ID_TRACKENCODINGS:
868 l = demux_mkv_read_trackencodings(demuxer, track);
869 if (l == 0)
870 goto err_out;
871 break;
873 default:
874 ebml_read_skip(s, &l);
875 break;
877 length -= l + il;
880 mkv_d->tracks[mkv_d->num_tracks++] = track;
881 return len;
883 err_out:
884 demux_mkv_free_trackentry(track);
885 return 0;
888 static int demux_mkv_read_tracks(demuxer_t *demuxer)
890 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
891 stream_t *s = demuxer->stream;
892 uint64_t length, l;
893 int il;
895 mkv_d->tracks = malloc(sizeof(*mkv_d->tracks));
896 mkv_d->num_tracks = 0;
898 length = ebml_read_length(s, NULL);
899 while (length > 0) {
900 switch (ebml_read_id(s, &il)) {
901 case MATROSKA_ID_TRACKENTRY:
902 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + a track...\n");
903 mkv_d->tracks = realloc(mkv_d->tracks, (mkv_d->num_tracks + 1)
904 * sizeof(*mkv_d->tracks));
905 l = demux_mkv_read_trackentry(demuxer);
906 if (l == 0)
907 return 1;
908 break;
910 default:
911 ebml_read_skip(s, &l);
912 break;
914 length -= l + il;
916 return 0;
919 static int demux_mkv_read_cues(demuxer_t *demuxer)
921 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
922 stream_t *s = demuxer->stream;
923 uint64_t length, l, time, track, pos;
924 off_t off;
925 int i, il;
927 if (index_mode == 0 || index_mode == 2) {
928 ebml_read_skip(s, NULL);
929 return 0;
931 off = stream_tell(s);
932 for (i = 0; i < mkv_d->parsed_cues_num; i++)
933 if (mkv_d->parsed_cues[i] == off) {
934 ebml_read_skip(s, NULL);
935 return 0;
937 mkv_d->parsed_cues =
938 realloc(mkv_d->parsed_cues, (mkv_d->parsed_cues_num + 1)
939 * sizeof(off_t));
940 mkv_d->parsed_cues[mkv_d->parsed_cues_num++] = off;
942 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] /---- [ parsing cues ] -----------\n");
943 length = ebml_read_length(s, NULL);
945 while (length > 0) {
946 time = track = pos = EBML_UINT_INVALID;
948 switch (ebml_read_id(s, &il)) {
949 case MATROSKA_ID_POINTENTRY:;
950 uint64_t len;
952 len = ebml_read_length(s, &i);
953 l = len + i;
955 while (len > 0) {
956 uint64_t l;
957 int il;
959 switch (ebml_read_id(s, &il)) {
960 case MATROSKA_ID_CUETIME:
961 time = ebml_read_uint(s, &l);
962 break;
964 case MATROSKA_ID_CUETRACKPOSITION:;
965 uint64_t le = ebml_read_length(s, &i);
966 l = le + i;
968 while (le > 0) {
969 uint64_t l;
970 int il;
972 switch (ebml_read_id(s, &il)) {
973 case MATROSKA_ID_CUETRACK:
974 track = ebml_read_uint(s, &l);
975 break;
977 case MATROSKA_ID_CUECLUSTERPOSITION:
978 pos = ebml_read_uint(s, &l);
979 break;
981 default:
982 ebml_read_skip(s, &l);
983 break;
985 le -= l + il;
987 break;
989 default:
990 ebml_read_skip(s, &l);
991 break;
993 len -= l + il;
995 break;
997 default:
998 ebml_read_skip(s, &l);
999 break;
1002 length -= l + il;
1004 if (time != EBML_UINT_INVALID && track != EBML_UINT_INVALID
1005 && pos != EBML_UINT_INVALID) {
1006 mkv_d->indexes =
1007 grow_array(mkv_d->indexes, mkv_d->num_indexes,
1008 sizeof(mkv_index_t));
1009 mkv_d->indexes[mkv_d->num_indexes].tnum = track;
1010 mkv_d->indexes[mkv_d->num_indexes].timecode = time;
1011 mkv_d->indexes[mkv_d->num_indexes].filepos =
1012 mkv_d->segment_start + pos;
1013 mp_msg(MSGT_DEMUX, MSGL_DBG2,
1014 "[mkv] |+ found cue point " "for track %" PRIu64
1015 ": timecode %" PRIu64 ", filepos: %" PRIu64 "\n", track,
1016 time, mkv_d->segment_start + pos);
1017 mkv_d->num_indexes++;
1021 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] \\---- [ parsing cues ] -----------\n");
1022 return 0;
1025 static uint64_t read_one_chapter(struct demuxer *demuxer, stream_t *s,
1026 struct matroska_chapter *chapters,
1027 int chapter_num)
1029 uint64_t len, l;
1030 uint64_t start = 0, end = 0;
1031 struct matroska_chapter chapter = { };
1032 char *name = 0;
1033 int i;
1034 uint32_t id;
1035 bool badchapter = false;
1037 len = ebml_read_length(s, &i);
1038 uint64_t bytes_read = len + i;
1040 while (len > 0) {
1041 id = ebml_read_id(s, &i);
1042 len -= i;
1043 switch (id) {
1044 case MATROSKA_ID_CHAPTERTIMESTART:
1045 start = ebml_read_uint(s, &l) / 1000000;
1046 len -= l;
1047 break;
1049 case MATROSKA_ID_CHAPTERTIMEEND:
1050 end = ebml_read_uint(s, &l) / 1000000;
1051 len -= l;
1052 break;
1054 case MATROSKA_ID_CHAPTERDISPLAY:;
1055 uint64_t displaylen = ebml_read_length(s, &i);
1056 len -= displaylen + i;
1057 while (displaylen > 0) {
1058 id = ebml_read_id(s, &i);
1059 displaylen -= i;
1060 switch (id) {
1061 case MATROSKA_ID_CHAPSTRING:
1062 name = ebml_read_utf8(s, &l);
1063 break;
1064 default:
1065 ebml_read_skip(s, &l);
1066 break;
1068 displaylen -= l;
1070 break;
1072 case MATROSKA_ID_CHAPTERSEGMENTUID:
1073 l = ebml_read_length(s, &i);
1074 len -= l + i;
1075 if (l != sizeof(chapter.segment_uid)) {
1076 mp_msg(MSGT_DEMUX, MSGL_INFO,
1077 "[mkv] chapter segment uid invalid length %" PRIu64
1078 "\n", l);
1079 stream_skip(s, l);
1080 } else {
1081 stream_read(s, chapter.segment_uid, l);
1082 chapter.has_segment_uid = true;
1083 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] Chapter segment uid ");
1084 for (int i = 0; i < l; i++)
1085 mp_msg(MSGT_DEMUX, MSGL_V, "%02x ",
1086 chapter.segment_uid[i]);
1087 mp_msg(MSGT_DEMUX, MSGL_V, "\n");
1089 break;
1091 case MATROSKA_ID_CHAPTERSEGMENTEDITIONUID:
1092 mp_tmsg(MSGT_DEMUX, MSGL_WARN,
1093 "[mkv] Warning: unsupported edition recursion in chapter; "
1094 "will skip on playback!\n");
1095 ebml_read_skip(s, &l);
1096 len -= l;
1097 badchapter = true;
1098 break;
1100 default:
1101 ebml_read_skip(s, &l);
1102 len -= l;
1103 break;
1107 if (!name)
1108 name = strdup("(unnamed)");
1110 chapter.start = start;
1111 chapter.end = end;
1112 chapter.name = talloc_strdup(chapters, name);
1113 chapters[chapter_num] = chapter;
1115 if (badchapter) {
1116 memset(&chapter.segment_uid, 0, sizeof(chapter.segment_uid));
1117 goto cleanup;
1120 mp_msg(MSGT_DEMUX, MSGL_V,
1121 "[mkv] Chapter %u from %02d:%02d:%02d."
1122 "%03d to %02d:%02d:%02d.%03d, %s\n", chapter_num,
1123 (int) (start / 60 / 60 / 1000), (int) ((start / 60 / 1000) % 60),
1124 (int) ((start / 1000) % 60), (int) (start % 1000),
1125 (int) (end / 60 / 60 / 1000), (int) ((end / 60 / 1000) % 60),
1126 (int) ((end / 1000) % 60), (int) (end % 1000), name);
1128 cleanup:
1129 free(name);
1130 return bytes_read;
1133 static int demux_mkv_read_chapters(struct demuxer *demuxer)
1135 struct MPOpts *opts = demuxer->opts;
1136 stream_t *s = demuxer->stream;
1137 uint64_t length, l;
1138 int i;
1139 uint32_t id;
1141 if (demuxer->chapters) {
1142 ebml_read_skip(s, NULL);
1143 return 0;
1146 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] /---- [ parsing chapters ] ---------\n");
1147 length = ebml_read_length(s, NULL);
1149 struct matroska_chapter *selected_chapters = NULL;
1150 int num_selected_chapters = 0;
1151 bool have_default = false;
1152 bool have_user_specified = false;
1153 int selected_edition = -1;
1154 bool se_is_ordered = false;
1155 int cur_idx = -1;
1156 while (length > 0) {
1157 id = ebml_read_id(s, &i);
1158 length -= i;
1159 switch (id) {
1160 case MATROSKA_ID_EDITIONENTRY:
1161 cur_idx++;
1162 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] New edition %d\n", cur_idx);
1163 uint64_t editionlen = ebml_read_length(s, &i);
1164 length -= editionlen + i;
1165 bool defaultflag = false;
1166 bool ordered = false;
1167 struct matroska_chapter *chapters = NULL;
1168 int num_chapters = 0;
1169 while (editionlen > 0) {
1170 id = ebml_read_id(s, &i);
1171 editionlen -= i;
1172 switch (id) {
1173 case MATROSKA_ID_CHAPTERATOM:
1174 chapters =
1175 talloc_realloc(demuxer, chapters,
1176 struct matroska_chapter,
1177 num_chapters + 1);
1178 l = read_one_chapter(demuxer, s, chapters, num_chapters++);
1179 break;
1180 case MATROSKA_ID_EDITIONFLAGDEFAULT:
1181 defaultflag = ebml_read_uint(s, &l);
1182 mp_msg(MSGT_DEMUX, MSGL_V,
1183 "[mkv] Default edition flag: %d\n", defaultflag);
1184 break;
1185 case MATROSKA_ID_EDITIONFLAGORDERED:
1186 ordered = ebml_read_uint(s, &l);
1187 mp_msg(MSGT_DEMUX, MSGL_V,
1188 "[mkv] Ordered chapter flag: %d\n", ordered);
1189 break;
1191 default:
1192 ebml_read_skip(s, &l);
1193 break;
1195 editionlen -= l;
1197 if (cur_idx == opts->edition_id) {
1198 have_user_specified = true;
1199 mp_msg(MSGT_DEMUX, MSGL_V,
1200 "[mkv] Found user-selected edition\n");
1201 } else if (!have_user_specified && !have_default && defaultflag) {
1202 have_default = true;
1203 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] Default edition: %d\n",
1204 cur_idx);
1205 } else if (selected_edition < 0) {
1207 } else {
1208 talloc_free(chapters);
1209 break;
1211 selected_edition = cur_idx;
1212 talloc_free(selected_chapters);
1213 selected_chapters = chapters;
1214 num_selected_chapters = num_chapters;
1215 se_is_ordered = ordered;
1216 break;
1218 default:
1219 ebml_read_skip(s, &l);
1220 length -= l;
1221 break;
1224 if (cur_idx > 0)
1225 mp_msg(MSGT_DEMUX, MSGL_INFO,
1226 "[mkv] Found %d editions, will play #%d (first is 0).\n",
1227 cur_idx + 1, selected_edition);
1229 for (i = 0; i < num_selected_chapters; i++)
1230 demuxer_add_chapter(demuxer, selected_chapters[i].name,
1231 selected_chapters[i].start,
1232 selected_chapters[i].end);
1233 struct matroska_data *m = &demuxer->matroska_data;
1234 talloc_free(m->ordered_chapters);
1235 if (se_is_ordered) {
1236 m->ordered_chapters = selected_chapters;
1237 m->num_ordered_chapters = num_selected_chapters;
1238 } else {
1239 m->ordered_chapters = NULL;
1240 m->num_ordered_chapters = 0;
1241 talloc_free(selected_chapters);
1244 mp_msg(MSGT_DEMUX, MSGL_V,
1245 "[mkv] \\---- [ parsing chapters ] ---------\n");
1246 return 0;
1249 static int demux_mkv_read_tags(demuxer_t *demuxer)
1251 ebml_read_skip(demuxer->stream, NULL);
1252 return 0;
1255 static int demux_mkv_read_attachments(demuxer_t *demuxer)
1257 stream_t *s = demuxer->stream;
1258 uint64_t length, l;
1259 int il;
1261 mp_msg(MSGT_DEMUX, MSGL_V,
1262 "[mkv] /---- [ parsing attachments ] ---------\n");
1263 length = ebml_read_length(s, NULL);
1265 while (length > 0) {
1266 switch (ebml_read_id(s, &il)) {
1267 case MATROSKA_ID_ATTACHEDFILE:;
1268 uint64_t len;
1269 int i;
1270 char *name = NULL;
1271 char *mime = NULL;
1272 char *data = NULL;
1273 int data_size = 0;
1275 len = ebml_read_length(s, &i);
1276 l = len + i;
1278 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + an attachment...\n");
1280 while (len > 0) {
1281 uint64_t l;
1282 int il;
1284 switch (ebml_read_id(s, &il)) {
1285 case MATROSKA_ID_FILENAME:
1286 free(name);
1287 name = ebml_read_utf8(s, &l);
1288 if (name == NULL)
1289 goto error;
1290 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + FileName: %s\n",
1291 name);
1292 break;
1294 case MATROSKA_ID_FILEMIMETYPE:
1295 free(mime);
1296 mime = ebml_read_ascii(s, &l);
1297 if (mime == NULL)
1298 goto error;
1299 mp_msg(MSGT_DEMUX, MSGL_V,
1300 "[mkv] | + FileMimeType: %s\n", mime);
1301 break;
1303 case MATROSKA_ID_FILEDATA:;
1304 int x;
1305 uint64_t num = ebml_read_length(s, &x);
1306 l = x + num;
1307 free(data);
1308 data = malloc(num);
1309 if (stream_read(s, data, num) != (int) num) {
1310 error:
1311 free(data);
1312 free(mime);
1313 free(name);
1314 return 0;
1316 data_size = num;
1317 mp_msg(MSGT_DEMUX, MSGL_V,
1318 "[mkv] | + FileData, length " "%u\n",
1319 data_size);
1320 break;
1322 default:
1323 ebml_read_skip(s, &l);
1324 break;
1326 len -= l + il;
1329 demuxer_add_attachment(demuxer, name, mime, data, data_size);
1330 free(data);
1331 free(mime);
1332 free(name);
1333 mp_msg(MSGT_DEMUX, MSGL_V,
1334 "[mkv] Attachment: %s, %s, %u bytes\n", name, mime,
1335 data_size);
1336 break;
1338 default:
1339 ebml_read_skip(s, &l);
1340 break;
1342 length -= l + il;
1345 mp_msg(MSGT_DEMUX, MSGL_V,
1346 "[mkv] \\---- [ parsing attachments ] ---------\n");
1347 return 0;
1350 static int demux_mkv_read_seekhead(demuxer_t *demuxer)
1352 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
1353 stream_t *s = demuxer->stream;
1354 uint64_t length, l, seek_pos, saved_pos, num;
1355 uint32_t seek_id;
1356 int i, il, res = 0;
1357 off_t off;
1359 off = stream_tell(s);
1360 for (i = 0; i < mkv_d->parsed_seekhead_num; i++)
1361 if (mkv_d->parsed_seekhead[i] == off) {
1362 ebml_read_skip(s, NULL);
1363 return 0;
1365 mkv_d->parsed_seekhead = realloc(mkv_d->parsed_seekhead,
1366 (mkv_d->parsed_seekhead_num + 1) * sizeof(off_t));
1367 mkv_d->parsed_seekhead[mkv_d->parsed_seekhead_num++] = off;
1369 mp_msg(MSGT_DEMUX, MSGL_V,
1370 "[mkv] /---- [ parsing seek head ] ---------\n");
1371 length = ebml_read_length(s, NULL);
1372 /* off now holds the position of the next element after the seek head. */
1373 off = stream_tell(s) + length;
1374 while (length > 0 && !res) {
1376 seek_id = 0;
1377 seek_pos = EBML_UINT_INVALID;
1379 switch (ebml_read_id(s, &il)) {
1380 case MATROSKA_ID_SEEKENTRY:;
1381 uint64_t len = ebml_read_length(s, &i);
1382 l = len + i;
1384 while (len > 0) {
1385 uint64_t l;
1386 int il;
1388 switch (ebml_read_id(s, &il)) {
1389 case MATROSKA_ID_SEEKID:
1390 num = ebml_read_uint(s, &l);
1391 if (num != EBML_UINT_INVALID)
1392 seek_id = num;
1393 break;
1395 case MATROSKA_ID_SEEKPOSITION:
1396 seek_pos = ebml_read_uint(s, &l);
1397 break;
1399 default:
1400 ebml_read_skip(s, &l);
1401 break;
1403 len -= l + il;
1406 break;
1408 default:
1409 ebml_read_skip(s, &l);
1410 break;
1412 length -= l + il;
1414 if (seek_id == 0 || seek_id == MATROSKA_ID_CLUSTER
1415 || seek_pos == EBML_UINT_INVALID
1416 || ((mkv_d->segment_start + seek_pos) >=
1417 (uint64_t) demuxer->movi_end))
1418 continue;
1420 saved_pos = stream_tell(s);
1421 if (!stream_seek(s, mkv_d->segment_start + seek_pos))
1422 res = 1;
1423 else {
1424 if (ebml_read_id(s, &il) != seek_id)
1425 res = 1;
1426 else
1427 switch (seek_id) {
1428 case MATROSKA_ID_CUES:
1429 if (demux_mkv_read_cues(demuxer))
1430 res = 1;
1431 break;
1433 case MATROSKA_ID_TAGS:
1434 if (demux_mkv_read_tags(demuxer))
1435 res = 1;
1436 break;
1438 case MATROSKA_ID_SEEKHEAD:
1439 if (demux_mkv_read_seekhead(demuxer))
1440 res = 1;
1441 break;
1443 case MATROSKA_ID_CHAPTERS:
1444 if (demux_mkv_read_chapters(demuxer))
1445 res = 1;
1446 break;
1450 stream_seek(s, saved_pos);
1452 if (res) {
1453 /* If there was an error then try to skip this seek head. */
1454 if (stream_seek(s, off))
1455 res = 0;
1456 } else if (length > 0)
1457 stream_seek(s, stream_tell(s) + length);
1458 mp_msg(MSGT_DEMUX, MSGL_V,
1459 "[mkv] \\---- [ parsing seek head ] ---------\n");
1460 return res;
1463 static int demux_mkv_open_video(demuxer_t *demuxer, mkv_track_t *track,
1464 int vid);
1465 static int demux_mkv_open_audio(demuxer_t *demuxer, mkv_track_t *track,
1466 int aid);
1467 static int demux_mkv_open_sub(demuxer_t *demuxer, mkv_track_t *track,
1468 int sid);
1470 static void display_create_tracks(demuxer_t *demuxer)
1472 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
1473 int i, vid = 0, aid = 0, sid = 0;
1475 for (i = 0; i < mkv_d->num_tracks; i++) {
1476 char *type = "unknown", str[32];
1477 *str = '\0';
1478 switch (mkv_d->tracks[i]->type) {
1479 case MATROSKA_TRACK_VIDEO:
1480 type = "video";
1481 demux_mkv_open_video(demuxer, mkv_d->tracks[i], vid);
1482 if (mkv_d->tracks[i]->name)
1483 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VID_%d_NAME=%s\n", vid,
1484 mkv_d->tracks[i]->name);
1485 sprintf(str, "-vid %u", vid++);
1486 break;
1487 case MATROSKA_TRACK_AUDIO:
1488 type = "audio";
1489 demux_mkv_open_audio(demuxer, mkv_d->tracks[i], aid);
1490 if (mkv_d->tracks[i]->name)
1491 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AID_%d_NAME=%s\n", aid,
1492 mkv_d->tracks[i]->name);
1493 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AID_%d_LANG=%s\n", aid,
1494 mkv_d->tracks[i]->language);
1495 sprintf(str, "-aid %u, -alang %.5s", aid++,
1496 mkv_d->tracks[i]->language);
1497 break;
1498 case MATROSKA_TRACK_SUBTITLE:
1499 type = "subtitles";
1500 demux_mkv_open_sub(demuxer, mkv_d->tracks[i], sid);
1501 if (mkv_d->tracks[i]->name)
1502 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SID_%d_NAME=%s\n", sid,
1503 mkv_d->tracks[i]->name);
1504 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SID_%d_LANG=%s\n", sid,
1505 mkv_d->tracks[i]->language);
1506 sprintf(str, "-sid %u, -slang %.5s", sid++,
1507 mkv_d->tracks[i]->language);
1508 break;
1510 if (mkv_d->tracks[i]->name)
1511 mp_tmsg(MSGT_DEMUX, MSGL_INFO,
1512 "[mkv] Track ID %u: %s (%s) \"%s\", %s\n",
1513 mkv_d->tracks[i]->tnum, type, mkv_d->tracks[i]->codec_id,
1514 mkv_d->tracks[i]->name, str);
1515 else
1516 mp_tmsg(MSGT_DEMUX, MSGL_INFO, "[mkv] Track ID %u: %s (%s), %s\n",
1517 mkv_d->tracks[i]->tnum, type, mkv_d->tracks[i]->codec_id,
1518 str);
1522 typedef struct {
1523 char *id;
1524 int fourcc;
1525 int extradata;
1526 } videocodec_info_t;
1528 static const videocodec_info_t vinfo[] = {
1529 {MKV_V_MPEG1, mmioFOURCC('m', 'p', 'g', '1'), 0},
1530 {MKV_V_MPEG2, mmioFOURCC('m', 'p', 'g', '2'), 0},
1531 {MKV_V_MPEG4_SP, mmioFOURCC('m', 'p', '4', 'v'), 1},
1532 {MKV_V_MPEG4_ASP, mmioFOURCC('m', 'p', '4', 'v'), 1},
1533 {MKV_V_MPEG4_AP, mmioFOURCC('m', 'p', '4', 'v'), 1},
1534 {MKV_V_MPEG4_AVC, mmioFOURCC('a', 'v', 'c', '1'), 1},
1535 {MKV_V_THEORA, mmioFOURCC('t', 'h', 'e', 'o'), 1},
1536 {NULL, 0, 0}
1539 static int demux_mkv_open_video(demuxer_t *demuxer, mkv_track_t *track,
1540 int vid)
1542 struct MPOpts *opts = demuxer->opts;
1543 BITMAPINFOHEADER *bih;
1544 void *ImageDesc = NULL;
1545 sh_video_t *sh_v;
1547 if (track->ms_compat) { /* MS compatibility mode */
1548 BITMAPINFOHEADER *src;
1550 if (track->private_data == NULL
1551 || track->private_size < sizeof(BITMAPINFOHEADER))
1552 return 1;
1554 src = (BITMAPINFOHEADER *) track->private_data;
1555 bih = calloc(1, track->private_size);
1556 bih->biSize = le2me_32(src->biSize);
1557 bih->biWidth = le2me_32(src->biWidth);
1558 bih->biHeight = le2me_32(src->biHeight);
1559 bih->biPlanes = le2me_16(src->biPlanes);
1560 bih->biBitCount = le2me_16(src->biBitCount);
1561 bih->biCompression = le2me_32(src->biCompression);
1562 bih->biSizeImage = le2me_32(src->biSizeImage);
1563 bih->biXPelsPerMeter = le2me_32(src->biXPelsPerMeter);
1564 bih->biYPelsPerMeter = le2me_32(src->biYPelsPerMeter);
1565 bih->biClrUsed = le2me_32(src->biClrUsed);
1566 bih->biClrImportant = le2me_32(src->biClrImportant);
1567 memcpy((char *) bih + sizeof(BITMAPINFOHEADER),
1568 (char *) src + sizeof(BITMAPINFOHEADER),
1569 track->private_size - sizeof(BITMAPINFOHEADER));
1571 if (track->v_width == 0)
1572 track->v_width = bih->biWidth;
1573 if (track->v_height == 0)
1574 track->v_height = bih->biHeight;
1575 } else {
1576 bih = calloc(1, sizeof(BITMAPINFOHEADER));
1577 bih->biSize = sizeof(BITMAPINFOHEADER);
1578 bih->biWidth = track->v_width;
1579 bih->biHeight = track->v_height;
1580 bih->biBitCount = 24;
1581 bih->biSizeImage = bih->biWidth * bih->biHeight * bih->biBitCount / 8;
1583 if (track->private_size >= RVPROPERTIES_SIZE
1584 && (!strcmp(track->codec_id, MKV_V_REALV10)
1585 || !strcmp(track->codec_id, MKV_V_REALV20)
1586 || !strcmp(track->codec_id, MKV_V_REALV30)
1587 || !strcmp(track->codec_id, MKV_V_REALV40))) {
1588 unsigned char *dst, *src;
1589 uint32_t type2;
1590 unsigned int cnt;
1592 src = (uint8_t *) track->private_data + RVPROPERTIES_SIZE;
1594 cnt = track->private_size - RVPROPERTIES_SIZE;
1595 bih = realloc(bih, sizeof(BITMAPINFOHEADER) + 8 + cnt);
1596 bih->biSize = 48 + cnt;
1597 bih->biPlanes = 1;
1598 type2 = AV_RB32(src - 4);
1599 if (type2 == 0x10003000 || type2 == 0x10003001)
1600 bih->biCompression = mmioFOURCC('R', 'V', '1', '3');
1601 else
1602 bih->biCompression =
1603 mmioFOURCC('R', 'V', track->codec_id[9], '0');
1604 dst = (unsigned char *) (bih + 1);
1605 // copy type1 and type2 info from rv properties
1606 memcpy(dst, src - 8, 8);
1607 stream_read(demuxer->stream, dst + 8, cnt);
1608 track->realmedia = 1;
1610 #ifdef CONFIG_QTX_CODECS
1611 } else if (track->private_size >= sizeof(ImageDescription)
1612 && !strcmp(track->codec_id, MKV_V_QUICKTIME)) {
1613 ImageDescriptionPtr idesc;
1615 idesc = (ImageDescriptionPtr) track->private_data;
1616 idesc->idSize = be2me_32(idesc->idSize);
1617 idesc->cType = be2me_32(idesc->cType);
1618 idesc->version = be2me_16(idesc->version);
1619 idesc->revisionLevel = be2me_16(idesc->revisionLevel);
1620 idesc->vendor = be2me_32(idesc->vendor);
1621 idesc->temporalQuality = be2me_32(idesc->temporalQuality);
1622 idesc->spatialQuality = be2me_32(idesc->spatialQuality);
1623 idesc->width = be2me_16(idesc->width);
1624 idesc->height = be2me_16(idesc->height);
1625 idesc->hRes = be2me_32(idesc->hRes);
1626 idesc->vRes = be2me_32(idesc->vRes);
1627 idesc->dataSize = be2me_32(idesc->dataSize);
1628 idesc->frameCount = be2me_16(idesc->frameCount);
1629 idesc->depth = be2me_16(idesc->depth);
1630 idesc->clutID = be2me_16(idesc->clutID);
1631 bih->biPlanes = 1;
1632 bih->biCompression = idesc->cType;
1633 ImageDesc = idesc;
1634 #endif /* CONFIG_QTX_CODECS */
1636 } else {
1637 const videocodec_info_t *vi = vinfo;
1638 while (vi->id && strcmp(vi->id, track->codec_id))
1639 vi++;
1640 bih->biCompression = vi->fourcc;
1641 if (vi->extradata && track->private_data
1642 && (track->private_size > 0)) {
1643 bih->biSize += track->private_size;
1644 bih = realloc(bih, bih->biSize);
1645 memcpy(bih + 1, track->private_data, track->private_size);
1647 track->reorder_timecodes = opts->user_correct_pts == 0;
1648 if (!vi->id) {
1649 mp_tmsg(MSGT_DEMUX, MSGL_WARN, "[mkv] Unknown/unsupported "
1650 "CodecID (%s) or missing/bad CodecPrivate\n"
1651 "[mkv] data (track %u).\n",
1652 track->codec_id, track->tnum);
1653 free(bih);
1654 return 1;
1659 sh_v = new_sh_video_vid(demuxer, track->tnum, vid);
1660 sh_v->bih = bih;
1661 sh_v->format = sh_v->bih->biCompression;
1662 if (track->v_frate == 0.0)
1663 track->v_frate = 25.0;
1664 sh_v->fps = track->v_frate;
1665 sh_v->frametime = 1 / track->v_frate;
1666 sh_v->aspect = 0;
1667 if (!track->realmedia) {
1668 sh_v->disp_w = track->v_width;
1669 sh_v->disp_h = track->v_height;
1670 if (track->v_dheight)
1671 sh_v->aspect = (double) track->v_dwidth / track->v_dheight;
1672 } else {
1673 // vd_realvid.c will set aspect to disp_w/disp_h and rederive
1674 // disp_w and disp_h from the RealVideo stream contents returned
1675 // by the Real DLLs. If DisplayWidth/DisplayHeight was not set in
1676 // the Matroska file then it has already been set to PixelWidth/Height
1677 // by check_track_information.
1678 sh_v->disp_w = track->v_dwidth;
1679 sh_v->disp_h = track->v_dheight;
1681 sh_v->ImageDesc = ImageDesc;
1682 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] Aspect: %f\n", sh_v->aspect);
1684 sh_v->ds = demuxer->video;
1685 return 0;
1688 static int demux_mkv_open_audio(demuxer_t *demuxer, mkv_track_t *track,
1689 int aid)
1691 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
1692 sh_audio_t *sh_a = new_sh_audio_aid(demuxer, track->tnum, aid);
1693 if (!sh_a)
1694 return 1;
1695 mkv_d->audio_tracks[mkv_d->last_aid] = track->tnum;
1697 if (track->language && (strcmp(track->language, "und") != 0))
1698 sh_a->lang = strdup(track->language);
1699 sh_a->default_track = track->default_track;
1700 sh_a->ds = demuxer->audio;
1701 sh_a->wf = malloc(sizeof(WAVEFORMATEX));
1702 if (track->ms_compat && (track->private_size >= sizeof(WAVEFORMATEX))) {
1703 WAVEFORMATEX *wf = (WAVEFORMATEX *) track->private_data;
1704 sh_a->wf = realloc(sh_a->wf, track->private_size);
1705 sh_a->wf->wFormatTag = le2me_16(wf->wFormatTag);
1706 sh_a->wf->nChannels = le2me_16(wf->nChannels);
1707 sh_a->wf->nSamplesPerSec = le2me_32(wf->nSamplesPerSec);
1708 sh_a->wf->nAvgBytesPerSec = le2me_32(wf->nAvgBytesPerSec);
1709 sh_a->wf->nBlockAlign = le2me_16(wf->nBlockAlign);
1710 sh_a->wf->wBitsPerSample = le2me_16(wf->wBitsPerSample);
1711 sh_a->wf->cbSize = track->private_size - sizeof(WAVEFORMATEX);
1712 memcpy(sh_a->wf + 1, wf + 1,
1713 track->private_size - sizeof(WAVEFORMATEX));
1714 if (track->a_sfreq == 0.0)
1715 track->a_sfreq = sh_a->wf->nSamplesPerSec;
1716 if (track->a_channels == 0)
1717 track->a_channels = sh_a->wf->nChannels;
1718 if (track->a_bps == 0)
1719 track->a_bps = sh_a->wf->wBitsPerSample;
1720 track->a_formattag = sh_a->wf->wFormatTag;
1721 } else {
1722 memset(sh_a->wf, 0, sizeof(WAVEFORMATEX));
1723 if (!strcmp(track->codec_id, MKV_A_MP3)
1724 || !strcmp(track->codec_id, MKV_A_MP2))
1725 track->a_formattag = 0x0055;
1726 else if (!strncmp(track->codec_id, MKV_A_AC3, strlen(MKV_A_AC3)))
1727 track->a_formattag = 0x2000;
1728 else if (!strcmp(track->codec_id, MKV_A_DTS))
1729 track->a_formattag = 0x2001;
1730 else if (!strcmp(track->codec_id, MKV_A_PCM)
1731 || !strcmp(track->codec_id, MKV_A_PCM_BE))
1732 track->a_formattag = 0x0001;
1733 else if (!strcmp(track->codec_id, MKV_A_AAC_2MAIN)
1734 || !strncmp(track->codec_id, MKV_A_AAC_2LC,
1735 strlen(MKV_A_AAC_2LC))
1736 || !strcmp(track->codec_id, MKV_A_AAC_2SSR)
1737 || !strcmp(track->codec_id, MKV_A_AAC_4MAIN)
1738 || !strncmp(track->codec_id, MKV_A_AAC_4LC,
1739 strlen(MKV_A_AAC_4LC))
1740 || !strcmp(track->codec_id, MKV_A_AAC_4SSR)
1741 || !strcmp(track->codec_id, MKV_A_AAC_4LTP)
1742 || !strcmp(track->codec_id, MKV_A_AAC))
1743 track->a_formattag = mmioFOURCC('M', 'P', '4', 'A');
1744 else if (!strcmp(track->codec_id, MKV_A_VORBIS)) {
1745 if (track->private_data == NULL)
1746 return 1;
1747 track->a_formattag = mmioFOURCC('v', 'r', 'b', 's');
1748 } else if (!strcmp(track->codec_id, MKV_A_QDMC))
1749 track->a_formattag = mmioFOURCC('Q', 'D', 'M', 'C');
1750 else if (!strcmp(track->codec_id, MKV_A_QDMC2))
1751 track->a_formattag = mmioFOURCC('Q', 'D', 'M', '2');
1752 else if (!strcmp(track->codec_id, MKV_A_WAVPACK))
1753 track->a_formattag = mmioFOURCC('W', 'V', 'P', 'K');
1754 else if (!strcmp(track->codec_id, MKV_A_TRUEHD))
1755 track->a_formattag = mmioFOURCC('T', 'R', 'H', 'D');
1756 else if (!strcmp(track->codec_id, MKV_A_FLAC)) {
1757 if (track->private_data == NULL || track->private_size == 0) {
1758 mp_tmsg(MSGT_DEMUX, MSGL_WARN,
1759 "[mkv] FLAC track does not contain valid headers.\n");
1760 return 1;
1762 track->a_formattag = mmioFOURCC('f', 'L', 'a', 'C');
1763 } else if (track->private_size >= RAPROPERTIES4_SIZE) {
1764 if (!strcmp(track->codec_id, MKV_A_REAL28))
1765 track->a_formattag = mmioFOURCC('2', '8', '_', '8');
1766 else if (!strcmp(track->codec_id, MKV_A_REALATRC))
1767 track->a_formattag = mmioFOURCC('a', 't', 'r', 'c');
1768 else if (!strcmp(track->codec_id, MKV_A_REALCOOK))
1769 track->a_formattag = mmioFOURCC('c', 'o', 'o', 'k');
1770 else if (!strcmp(track->codec_id, MKV_A_REALDNET))
1771 track->a_formattag = mmioFOURCC('d', 'n', 'e', 't');
1772 else if (!strcmp(track->codec_id, MKV_A_REALSIPR))
1773 track->a_formattag = mmioFOURCC('s', 'i', 'p', 'r');
1774 } else {
1775 mp_tmsg(MSGT_DEMUX, MSGL_WARN, "[mkv] Unknown/unsupported audio "
1776 "codec ID '%s' for track %u or missing/faulty\n[mkv] "
1777 "private codec data.\n", track->codec_id, track->tnum);
1778 free_sh_audio(demuxer, track->tnum);
1779 return 1;
1783 sh_a->format = track->a_formattag;
1784 sh_a->wf->wFormatTag = track->a_formattag;
1785 sh_a->channels = track->a_channels;
1786 sh_a->wf->nChannels = track->a_channels;
1787 sh_a->samplerate = (uint32_t) track->a_sfreq;
1788 sh_a->wf->nSamplesPerSec = (uint32_t) track->a_sfreq;
1789 if (track->a_bps == 0) {
1790 sh_a->samplesize = 2;
1791 sh_a->wf->wBitsPerSample = 16;
1792 } else {
1793 sh_a->samplesize = track->a_bps / 8;
1794 sh_a->wf->wBitsPerSample = track->a_bps;
1796 if (track->a_formattag == 0x0055) { /* MP3 || MP2 */
1797 sh_a->wf->nAvgBytesPerSec = 16000;
1798 sh_a->wf->nBlockAlign = 1152;
1799 } else if ((track->a_formattag == 0x2000) /* AC3 */
1800 || (track->a_formattag == 0x2001)) { /* DTS */
1801 free(sh_a->wf);
1802 sh_a->wf = NULL;
1803 } else if (track->a_formattag == 0x0001) { /* PCM || PCM_BE */
1804 sh_a->wf->nAvgBytesPerSec = sh_a->channels * sh_a->samplerate * 2;
1805 sh_a->wf->nBlockAlign = sh_a->wf->nAvgBytesPerSec;
1806 if (!strcmp(track->codec_id, MKV_A_PCM_BE))
1807 sh_a->format = mmioFOURCC('t', 'w', 'o', 's');
1808 } else if (!strcmp(track->codec_id, MKV_A_QDMC)
1809 || !strcmp(track->codec_id, MKV_A_QDMC2)) {
1810 sh_a->wf->nAvgBytesPerSec = 16000;
1811 sh_a->wf->nBlockAlign = 1486;
1812 track->fix_i_bps = 1;
1813 track->qt_last_a_pts = 0.0;
1814 if (track->private_data != NULL) {
1815 sh_a->codecdata = malloc(track->private_size);
1816 memcpy(sh_a->codecdata, track->private_data, track->private_size);
1817 sh_a->codecdata_len = track->private_size;
1819 } else if (track->a_formattag == mmioFOURCC('M', 'P', '4', 'A')) {
1820 int profile, srate_idx;
1822 sh_a->wf->nAvgBytesPerSec = 16000;
1823 sh_a->wf->nBlockAlign = 1024;
1825 if (!strcmp(track->codec_id, MKV_A_AAC)
1826 && (NULL != track->private_data)) {
1827 sh_a->codecdata = malloc(track->private_size);
1828 memcpy(sh_a->codecdata, track->private_data, track->private_size);
1829 sh_a->codecdata_len = track->private_size;
1830 return 0;
1833 /* Recreate the 'private data' */
1834 /* which faad2 uses in its initialization */
1835 srate_idx = aac_get_sample_rate_index(sh_a->samplerate);
1836 if (!strncmp(&track->codec_id[12], "MAIN", 4))
1837 profile = 0;
1838 else if (!strncmp(&track->codec_id[12], "LC", 2))
1839 profile = 1;
1840 else if (!strncmp(&track->codec_id[12], "SSR", 3))
1841 profile = 2;
1842 else
1843 profile = 3;
1844 sh_a->codecdata = malloc(5);
1845 sh_a->codecdata[0] = ((profile + 1) << 3) | ((srate_idx & 0xE) >> 1);
1846 sh_a->codecdata[1] =
1847 ((srate_idx & 0x1) << 7) | (track->a_channels << 3);
1849 if (strstr(track->codec_id, "SBR") != NULL) {
1850 /* HE-AAC (aka SBR AAC) */
1851 sh_a->codecdata_len = 5;
1853 sh_a->samplerate *= 2;
1854 sh_a->wf->nSamplesPerSec *= 2;
1855 srate_idx = aac_get_sample_rate_index(sh_a->samplerate);
1856 sh_a->codecdata[2] = AAC_SYNC_EXTENSION_TYPE >> 3;
1857 sh_a->codecdata[3] = ((AAC_SYNC_EXTENSION_TYPE & 0x07) << 5) | 5;
1858 sh_a->codecdata[4] = (1 << 7) | (srate_idx << 3);
1859 track->default_duration = 1024.0 / (sh_a->samplerate / 2);
1860 } else {
1861 sh_a->codecdata_len = 2;
1862 track->default_duration = 1024.0 / sh_a->samplerate;
1864 } else if (track->a_formattag == mmioFOURCC('v', 'r', 'b', 's')) { /* VORBIS */
1865 sh_a->wf->cbSize = track->private_size;
1866 sh_a->wf = realloc(sh_a->wf, sizeof(WAVEFORMATEX) + sh_a->wf->cbSize);
1867 memcpy((unsigned char *) (sh_a->wf + 1), track->private_data,
1868 sh_a->wf->cbSize);
1869 } else if (track->private_size >= RAPROPERTIES4_SIZE
1870 && !strncmp(track->codec_id, MKV_A_REALATRC, 7)) {
1871 /* Common initialization for all RealAudio codecs */
1872 unsigned char *src = track->private_data;
1873 int codecdata_length, version;
1874 int flavor;
1876 sh_a->wf->nAvgBytesPerSec = 0; /* FIXME !? */
1878 version = AV_RB16(src + 4);
1879 flavor = AV_RB16(src + 22);
1880 track->coded_framesize = AV_RB32(src + 24);
1881 track->sub_packet_h = AV_RB16(src + 40);
1882 sh_a->wf->nBlockAlign = track->audiopk_size = AV_RB16(src + 42);
1883 track->sub_packet_size = AV_RB16(src + 44);
1884 if (version == 4) {
1885 src += RAPROPERTIES4_SIZE;
1886 src += src[0] + 1;
1887 src += src[0] + 1;
1888 } else
1889 src += RAPROPERTIES5_SIZE;
1891 src += 3;
1892 if (version == 5)
1893 src++;
1894 codecdata_length = AV_RB32(src);
1895 src += 4;
1896 sh_a->wf->cbSize = codecdata_length;
1897 sh_a->wf = realloc(sh_a->wf, sizeof(WAVEFORMATEX) + sh_a->wf->cbSize);
1898 memcpy(((char *) (sh_a->wf + 1)), src, codecdata_length);
1900 switch (track->a_formattag) {
1901 case mmioFOURCC('a', 't', 'r', 'c'):
1902 sh_a->wf->nAvgBytesPerSec = atrc_fl2bps[flavor];
1903 sh_a->wf->nBlockAlign = track->sub_packet_size;
1904 track->audio_buf =
1905 malloc(track->sub_packet_h * track->audiopk_size);
1906 track->audio_timestamp =
1907 malloc(track->sub_packet_h * sizeof(double));
1908 break;
1909 case mmioFOURCC('c', 'o', 'o', 'k'):
1910 sh_a->wf->nAvgBytesPerSec = cook_fl2bps[flavor];
1911 sh_a->wf->nBlockAlign = track->sub_packet_size;
1912 track->audio_buf =
1913 malloc(track->sub_packet_h * track->audiopk_size);
1914 track->audio_timestamp =
1915 malloc(track->sub_packet_h * sizeof(double));
1916 break;
1917 case mmioFOURCC('s', 'i', 'p', 'r'):
1918 sh_a->wf->nAvgBytesPerSec = sipr_fl2bps[flavor];
1919 sh_a->wf->nBlockAlign = track->coded_framesize;
1920 track->audio_buf =
1921 malloc(track->sub_packet_h * track->audiopk_size);
1922 track->audio_timestamp =
1923 malloc(track->sub_packet_h * sizeof(double));
1924 break;
1925 case mmioFOURCC('2', '8', '_', '8'):
1926 sh_a->wf->nAvgBytesPerSec = 3600;
1927 sh_a->wf->nBlockAlign = track->coded_framesize;
1928 track->audio_buf =
1929 malloc(track->sub_packet_h * track->audiopk_size);
1930 track->audio_timestamp =
1931 malloc(track->sub_packet_h * sizeof(double));
1932 break;
1935 track->realmedia = 1;
1936 } else if (!strcmp(track->codec_id, MKV_A_FLAC)
1937 || (track->a_formattag == 0xf1ac)) {
1938 unsigned char *ptr;
1939 int size;
1940 free(sh_a->wf);
1941 sh_a->wf = NULL;
1943 if (track->a_formattag == mmioFOURCC('f', 'L', 'a', 'C')) {
1944 ptr = track->private_data;
1945 size = track->private_size;
1946 } else {
1947 sh_a->format = mmioFOURCC('f', 'L', 'a', 'C');
1948 ptr = track->private_data + sizeof(WAVEFORMATEX);
1949 size = track->private_size - sizeof(WAVEFORMATEX);
1951 if (size < 4 || ptr[0] != 'f' || ptr[1] != 'L' || ptr[2] != 'a'
1952 || ptr[3] != 'C') {
1953 sh_a->codecdata = malloc(4);
1954 sh_a->codecdata_len = 4;
1955 memcpy(sh_a->codecdata, "fLaC", 4);
1956 } else {
1957 sh_a->codecdata = malloc(size);
1958 sh_a->codecdata_len = size;
1959 memcpy(sh_a->codecdata, ptr, size);
1961 } else if (track->a_formattag == mmioFOURCC('W', 'V', 'P', 'K') || track->a_formattag == mmioFOURCC('T', 'R', 'H', 'D')) { /* do nothing, still works */
1962 } else if (!track->ms_compat
1963 || (track->private_size < sizeof(WAVEFORMATEX))) {
1964 free_sh_audio(demuxer, track->tnum);
1965 return 1;
1968 return 0;
1971 static int demux_mkv_open_sub(demuxer_t *demuxer, mkv_track_t *track,
1972 int sid)
1974 if (track->subtitle_type != MATROSKA_SUBTYPE_UNKNOWN) {
1975 int size, m;
1976 uint8_t *buffer;
1977 sh_sub_t *sh = new_sh_sub_sid(demuxer, track->tnum, sid);
1978 track->sh_sub = sh;
1979 sh->type = 't';
1980 if (track->subtitle_type == MATROSKA_SUBTYPE_VOBSUB)
1981 sh->type = 'v';
1982 if (track->subtitle_type == MATROSKA_SUBTYPE_SSA)
1983 sh->type = 'a';
1984 size = track->private_size;
1985 m = demux_mkv_decode(track, track->private_data, &buffer, &size, 2);
1986 if (buffer && m) {
1987 free(track->private_data);
1988 track->private_data = buffer;
1989 track->private_size = size;
1991 sh->extradata = malloc(track->private_size);
1992 memcpy(sh->extradata, track->private_data, track->private_size);
1993 sh->extradata_len = track->private_size;
1994 if (track->language && (strcmp(track->language, "und") != 0))
1995 sh->lang = strdup(track->language);
1996 sh->default_track = track->default_track;
1997 } else {
1998 mp_tmsg(MSGT_DEMUX, MSGL_ERR,
1999 "[mkv] Subtitle type '%s' is not supported.\n",
2000 track->codec_id);
2001 return 1;
2004 return 0;
2007 static int demux_mkv_open(demuxer_t *demuxer)
2009 stream_t *s = demuxer->stream;
2010 mkv_demuxer_t *mkv_d;
2011 mkv_track_t *track;
2012 int i, version, cont = 0;
2013 char *str;
2015 stream_seek(s, s->start_pos);
2016 str = ebml_read_header(s, &version);
2017 if (str == NULL || strcmp(str, "matroska") || version > 2) {
2018 mp_msg(MSGT_DEMUX, MSGL_DBG2, "[mkv] no head found\n");
2019 return 0;
2021 free(str);
2023 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] Found the head...\n");
2025 if (ebml_read_id(s, NULL) != MATROSKA_ID_SEGMENT) {
2026 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] but no segment :(\n");
2027 return 0;
2029 ebml_read_length(s, NULL); /* return bytes number until EOF */
2031 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] + a segment...\n");
2033 mkv_d = calloc(1, sizeof(mkv_demuxer_t));
2034 demuxer->priv = mkv_d;
2035 mkv_d->tc_scale = 1000000;
2036 mkv_d->segment_start = stream_tell(s);
2037 mkv_d->parsed_cues = malloc(sizeof(off_t));
2038 mkv_d->parsed_seekhead = malloc(sizeof(off_t));
2040 while (!cont) {
2041 switch (ebml_read_id(s, NULL)) {
2042 case MATROSKA_ID_INFO:
2043 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] |+ segment information...\n");
2044 cont = demux_mkv_read_info(demuxer);
2045 break;
2047 case MATROSKA_ID_TRACKS:
2048 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] |+ segment tracks...\n");
2049 cont = demux_mkv_read_tracks(demuxer);
2050 break;
2052 case MATROSKA_ID_CUES:
2053 cont = demux_mkv_read_cues(demuxer);
2054 break;
2056 case MATROSKA_ID_TAGS:
2057 cont = demux_mkv_read_tags(demuxer);
2058 break;
2060 case MATROSKA_ID_SEEKHEAD:
2061 cont = demux_mkv_read_seekhead(demuxer);
2062 break;
2064 case MATROSKA_ID_CHAPTERS:
2065 cont = demux_mkv_read_chapters(demuxer);
2066 break;
2068 case MATROSKA_ID_ATTACHMENTS:
2069 cont = demux_mkv_read_attachments(demuxer);
2070 break;
2072 case MATROSKA_ID_CLUSTER:;
2073 int p, l;
2074 mp_msg(MSGT_DEMUX, MSGL_V,
2075 "[mkv] |+ found cluster, headers are "
2076 "parsed completely :)\n");
2077 /* get the first cluster timecode */
2078 p = stream_tell(s);
2079 l = ebml_read_length(s, NULL);
2080 while (ebml_read_id(s, NULL) != MATROSKA_ID_CLUSTERTIMECODE) {
2081 ebml_read_skip(s, NULL);
2082 if (stream_tell(s) >= p + l)
2083 break;
2085 if (stream_tell(s) < p + l) {
2086 uint64_t num = ebml_read_uint(s, NULL);
2087 if (num == EBML_UINT_INVALID)
2088 return 0;
2090 stream_seek(s, p - 4);
2091 cont = 1;
2092 break;
2094 default:
2095 cont = 1;
2096 case EBML_ID_VOID:
2097 ebml_read_skip(s, NULL);
2098 break;
2102 display_create_tracks(demuxer);
2104 /* select video track */
2105 track = NULL;
2106 if (demuxer->video->id == -1) { /* automatically select a video track */
2107 /* search for a video track that has the 'default' flag set */
2108 for (i = 0; i < mkv_d->num_tracks; i++)
2109 if (mkv_d->tracks[i]->type == MATROSKA_TRACK_VIDEO
2110 && mkv_d->tracks[i]->default_track) {
2111 track = mkv_d->tracks[i];
2112 break;
2115 if (track == NULL)
2116 /* no track has the 'default' flag set */
2117 /* let's take the first video track */
2118 for (i = 0; i < mkv_d->num_tracks; i++)
2119 if (mkv_d->tracks[i]->type == MATROSKA_TRACK_VIDEO) {
2120 track = mkv_d->tracks[i];
2121 break;
2123 } else if (demuxer->video->id != -2) /* -2 = no video at all */
2124 track =
2125 demux_mkv_find_track_by_num(mkv_d, demuxer->video->id,
2126 MATROSKA_TRACK_VIDEO);
2128 if (track && demuxer->v_streams[track->tnum]) {
2129 mp_tmsg(MSGT_DEMUX, MSGL_INFO, "[mkv] Will play video track %u.\n",
2130 track->tnum);
2131 demuxer->video->id = track->tnum;
2132 demuxer->video->sh = demuxer->v_streams[track->tnum];
2133 } else {
2134 mp_tmsg(MSGT_DEMUX, MSGL_INFO, "[mkv] No video track found/wanted.\n");
2135 demuxer->video->id = -2;
2138 /* select audio track */
2139 track = NULL;
2140 if (track == NULL)
2141 /* search for an audio track that has the 'default' flag set */
2142 for (i = 0; i < mkv_d->num_tracks; i++)
2143 if (mkv_d->tracks[i]->type == MATROSKA_TRACK_AUDIO
2144 && mkv_d->tracks[i]->default_track) {
2145 track = mkv_d->tracks[i];
2146 break;
2149 if (track == NULL)
2150 /* no track has the 'default' flag set */
2151 /* let's take the first audio track */
2152 for (i = 0; i < mkv_d->num_tracks; i++)
2153 if (mkv_d->tracks[i]->type == MATROSKA_TRACK_AUDIO) {
2154 track = mkv_d->tracks[i];
2155 break;
2158 if (track && demuxer->a_streams[track->tnum]) {
2159 demuxer->audio->id = track->tnum;
2160 demuxer->audio->sh = demuxer->a_streams[track->tnum];
2161 } else {
2162 mp_tmsg(MSGT_DEMUX, MSGL_INFO, "[mkv] No audio track found/wanted.\n");
2163 demuxer->audio->id = -2;
2167 if (demuxer->audio->id != -2)
2168 for (i = 0; i < mkv_d->num_tracks; i++) {
2169 if (mkv_d->tracks[i]->type != MATROSKA_TRACK_AUDIO)
2170 continue;
2171 if (demuxer->a_streams[track->tnum]) {
2172 mkv_d->last_aid++;
2173 if (mkv_d->last_aid == MAX_A_STREAMS)
2174 break;
2178 if (s->end_pos == 0 || (mkv_d->indexes == NULL && index_mode < 0))
2179 demuxer->seekable = 0;
2180 else {
2181 demuxer->movi_start = s->start_pos;
2182 demuxer->movi_end = s->end_pos;
2183 demuxer->seekable = 1;
2186 demuxer->accurate_seek = true;
2188 return DEMUXER_TYPE_MATROSKA;
2191 static void demux_close_mkv(demuxer_t *demuxer)
2193 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2195 if (mkv_d) {
2196 int i;
2197 free_cached_dps(demuxer);
2198 if (mkv_d->tracks) {
2199 for (i = 0; i < mkv_d->num_tracks; i++)
2200 demux_mkv_free_trackentry(mkv_d->tracks[i]);
2201 free(mkv_d->tracks);
2203 free(mkv_d->indexes);
2204 free(mkv_d->cluster_positions);
2205 free(mkv_d->parsed_cues);
2206 free(mkv_d->parsed_seekhead);
2207 free(mkv_d);
2211 static int demux_mkv_read_block_lacing(uint8_t *buffer, uint64_t *size,
2212 uint8_t *laces,
2213 uint32_t **all_lace_sizes)
2215 uint32_t total = 0, *lace_size;
2216 uint8_t flags;
2217 int i;
2219 *all_lace_sizes = NULL;
2220 lace_size = NULL;
2221 /* lacing flags */
2222 flags = *buffer++;
2223 (*size)--;
2225 switch ((flags & 0x06) >> 1) {
2226 case 0: /* no lacing */
2227 *laces = 1;
2228 lace_size = calloc(*laces, sizeof(uint32_t));
2229 lace_size[0] = *size;
2230 break;
2232 case 1: /* xiph lacing */
2233 case 2: /* fixed-size lacing */
2234 case 3: /* EBML lacing */
2235 *laces = *buffer++;
2236 (*size)--;
2237 (*laces)++;
2238 lace_size = calloc(*laces, sizeof(uint32_t));
2240 switch ((flags & 0x06) >> 1) {
2241 case 1: /* xiph lacing */
2242 for (i = 0; i < *laces - 1; i++) {
2243 lace_size[i] = 0;
2244 do {
2245 lace_size[i] += *buffer;
2246 (*size)--;
2247 } while (*buffer++ == 0xFF);
2248 total += lace_size[i];
2250 lace_size[i] = *size - total;
2251 break;
2253 case 2: /* fixed-size lacing */
2254 for (i = 0; i < *laces; i++)
2255 lace_size[i] = *size / *laces;
2256 break;
2258 case 3:; /* EBML lacing */
2259 int l;
2260 uint64_t num = ebml_read_vlen_uint(buffer, &l);
2261 if (num == EBML_UINT_INVALID) {
2262 free(lace_size);
2263 return 1;
2265 buffer += l;
2266 *size -= l;
2268 total = lace_size[0] = num;
2269 for (i = 1; i < *laces - 1; i++) {
2270 int64_t snum;
2271 snum = ebml_read_vlen_int(buffer, &l);
2272 if (snum == EBML_INT_INVALID) {
2273 free(lace_size);
2274 return 1;
2276 buffer += l;
2277 *size -= l;
2278 lace_size[i] = lace_size[i - 1] + snum;
2279 total += lace_size[i];
2281 lace_size[i] = *size - total;
2282 break;
2284 break;
2286 *all_lace_sizes = lace_size;
2287 return 0;
2290 static void handle_subtitles(demuxer_t *demuxer, mkv_track_t *track,
2291 char *block, int64_t size,
2292 uint64_t block_duration, uint64_t timecode)
2294 demux_packet_t *dp;
2296 if (block_duration == 0) {
2297 mp_msg(MSGT_DEMUX, MSGL_WARN,
2298 "[mkv] Warning: No BlockDuration for subtitle track found.\n");
2299 return;
2302 sub_utf8 = 1;
2303 dp = new_demux_packet(size);
2304 memcpy(dp->buffer, block, size);
2305 dp->pts = timecode / 1000.0;
2306 dp->endpts = (timecode + block_duration) / 1000.0;
2307 ds_add_packet(demuxer->sub, dp);
2310 double real_fix_timestamp(unsigned char *buf, unsigned int timestamp,
2311 unsigned int format, int64_t *kf_base, int *kf_pts,
2312 double *pts);
2314 static void handle_realvideo(demuxer_t *demuxer, mkv_track_t *track,
2315 uint8_t *buffer, uint32_t size, int block_bref)
2317 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2318 demux_packet_t *dp;
2319 uint32_t timestamp = mkv_d->last_pts * 1000;
2321 dp = new_demux_packet(size);
2322 memcpy(dp->buffer, buffer, size);
2324 if (mkv_d->v_skip_to_keyframe) {
2325 dp->pts = mkv_d->last_pts;
2326 track->rv_kf_base = 0;
2327 track->rv_kf_pts = timestamp;
2328 } else
2329 dp->pts =
2330 real_fix_timestamp(dp->buffer, timestamp,
2331 ((sh_video_t *) demuxer->video->sh)->bih->
2332 biCompression, &track->rv_kf_base,
2333 &track->rv_kf_pts, NULL);
2334 dp->pos = demuxer->filepos;
2335 dp->flags = block_bref ? 0 : 0x10;
2337 ds_add_packet(demuxer->video, dp);
2340 static void handle_realaudio(demuxer_t *demuxer, mkv_track_t *track,
2341 uint8_t *buffer, uint32_t size, int block_bref)
2343 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2344 int sps = track->sub_packet_size;
2345 int sph = track->sub_packet_h;
2346 int cfs = track->coded_framesize;
2347 int w = track->audiopk_size;
2348 int spc = track->sub_packet_cnt;
2349 demux_packet_t *dp;
2350 int x;
2352 if ((track->a_formattag == mmioFOURCC('2', '8', '_', '8'))
2353 || (track->a_formattag == mmioFOURCC('c', 'o', 'o', 'k'))
2354 || (track->a_formattag == mmioFOURCC('a', 't', 'r', 'c'))
2355 || (track->a_formattag == mmioFOURCC('s', 'i', 'p', 'r'))) {
2356 // if(!block_bref)
2357 // spc = track->sub_packet_cnt = 0;
2358 switch (track->a_formattag) {
2359 case mmioFOURCC('2', '8', '_', '8'):
2360 for (x = 0; x < sph / 2; x++)
2361 memcpy(track->audio_buf + x * 2 * w + spc * cfs,
2362 buffer + cfs * x, cfs);
2363 break;
2364 case mmioFOURCC('c', 'o', 'o', 'k'):
2365 case mmioFOURCC('a', 't', 'r', 'c'):
2366 for (x = 0; x < w / sps; x++)
2367 memcpy(track->audio_buf +
2368 sps * (sph * x + ((sph + 1) / 2) * (spc & 1) +
2369 (spc >> 1)), buffer + sps * x, sps);
2370 break;
2371 case mmioFOURCC('s', 'i', 'p', 'r'):
2372 memcpy(track->audio_buf + spc * w, buffer, w);
2373 if (spc == sph - 1) {
2374 int n;
2375 int bs = sph * w * 2 / 96; // nibbles per subpacket
2376 // Perform reordering
2377 for (n = 0; n < 38; n++) {
2378 int j;
2379 int i = bs * sipr_swaps[n][0];
2380 int o = bs * sipr_swaps[n][1];
2381 // swap nibbles of block 'i' with 'o' TODO: optimize
2382 for (j = 0; j < bs; j++) {
2383 int x = (i & 1) ?
2384 (track->audio_buf[i >> 1] >> 4) :
2385 (track->audio_buf[i >> 1] & 0x0F);
2386 int y = (o & 1) ?
2387 (track->audio_buf[o >> 1] >> 4) :
2388 (track->audio_buf[o >> 1] & 0x0F);
2389 if (o & 1)
2390 track->audio_buf[o >> 1] =
2391 (track->audio_buf[o >> 1] & 0x0F) | (x << 4);
2392 else
2393 track->audio_buf[o >> 1] =
2394 (track->audio_buf[o >> 1] & 0xF0) | x;
2395 if (i & 1)
2396 track->audio_buf[i >> 1] =
2397 (track->audio_buf[i >> 1] & 0x0F) | (y << 4);
2398 else
2399 track->audio_buf[i >> 1] =
2400 (track->audio_buf[i >> 1] & 0xF0) | y;
2401 ++i;
2402 ++o;
2406 break;
2408 track->audio_timestamp[track->sub_packet_cnt] =
2409 (track->ra_pts == mkv_d->last_pts) ? 0 : (mkv_d->last_pts);
2410 track->ra_pts = mkv_d->last_pts;
2411 if (track->sub_packet_cnt == 0)
2412 track->audio_filepos = demuxer->filepos;
2413 if (++(track->sub_packet_cnt) == sph) {
2414 int apk_usize =
2415 ((WAVEFORMATEX *) ((sh_audio_t *) demuxer->audio->sh)->wf)->
2416 nBlockAlign;
2417 track->sub_packet_cnt = 0;
2418 // Release all the audio packets
2419 for (x = 0; x < sph * w / apk_usize; x++) {
2420 dp = new_demux_packet(apk_usize);
2421 memcpy(dp->buffer, track->audio_buf + x * apk_usize,
2422 apk_usize);
2423 /* Put timestamp only on packets that correspond to original
2424 * audio packets in file */
2425 dp->pts = (x * apk_usize % w) ? 0 :
2426 track->audio_timestamp[x * apk_usize / w];
2427 dp->pos = track->audio_filepos; // all equal
2428 dp->flags = x ? 0 : 0x10; // Mark first packet as keyframe
2429 ds_add_packet(demuxer->audio, dp);
2432 } else { // Not a codec that require reordering
2433 dp = new_demux_packet(size);
2434 memcpy(dp->buffer, buffer, size);
2435 if (track->ra_pts == mkv_d->last_pts && !mkv_d->a_skip_to_keyframe)
2436 dp->pts = 0;
2437 else
2438 dp->pts = mkv_d->last_pts;
2439 track->ra_pts = mkv_d->last_pts;
2441 dp->pos = demuxer->filepos;
2442 dp->flags = block_bref ? 0 : 0x10;
2443 ds_add_packet(demuxer->audio, dp);
2447 /** Reorder timecodes and add cached demux packets to the queues.
2449 * Timecode reordering is needed if a video track contains B frames that
2450 * are timestamped in display order (e.g. MPEG-1, MPEG-2 or "native" MPEG-4).
2451 * MPlayer doesn't like timestamps in display order. This function adjusts
2452 * the timestamp of cached frames (which are exactly one I/P frame followed
2453 * by one or more B frames) so that they are in coding order again.
2455 * Example: The track with 25 FPS contains four frames with the timecodes
2456 * I at 0ms, P at 120ms, B at 40ms and B at 80ms. As soon as the next I
2457 * or P frame arrives these timecodes can be changed to I at 0ms, P at 40ms,
2458 * B at 80ms and B at 120ms.
2460 * This works for simple H.264 B-frame pyramids, but not for arbitrary orders.
2462 * \param demuxer The Matroska demuxer struct for this instance.
2463 * \param track The track structure whose cache should be handled.
2465 static void flush_cached_dps(demuxer_t *demuxer, mkv_track_t *track)
2467 int i, ok;
2469 if (track->num_cached_dps == 0)
2470 return;
2472 do {
2473 ok = 1;
2474 for (i = 1; i < track->num_cached_dps; i++)
2475 if (track->cached_dps[i - 1]->pts > track->cached_dps[i]->pts) {
2476 double tmp_pts = track->cached_dps[i - 1]->pts;
2477 track->cached_dps[i - 1]->pts = track->cached_dps[i]->pts;
2478 track->cached_dps[i]->pts = tmp_pts;
2479 ok = 0;
2481 } while (!ok);
2483 for (i = 0; i < track->num_cached_dps; i++)
2484 ds_add_packet(demuxer->video, track->cached_dps[i]);
2485 track->num_cached_dps = 0;
2488 /** Cache video frames if timecodes have to be reordered.
2490 * Timecode reordering is needed if a video track contains B frames that
2491 * are timestamped in display order (e.g. MPEG-1, MPEG-2 or "native" MPEG-4).
2492 * This function takes in a Matroska block read from the file, allocates a
2493 * demux packet for it, fills in its values, allocates space for storing
2494 * pointers to the cached demux packets and adds the packet to it. If
2495 * the packet contains an I or a P frame then ::flush_cached_dps is called
2496 * in order to send the old cached frames downstream.
2498 * \param demuxer The Matroska demuxer struct for this instance.
2499 * \param track The packet is meant for this track.
2500 * \param buffer The actual frame contents.
2501 * \param size The frame size in bytes.
2502 * \param block_bref A relative timecode (backward reference). If it is \c 0
2503 * then the frame is an I frame.
2504 * \param block_fref A relative timecode (forward reference). If it is \c 0
2505 * then the frame is either an I frame or a P frame depending on the value
2506 * of \a block_bref. Otherwise it's a B frame.
2508 static void handle_video_bframes(demuxer_t *demuxer, mkv_track_t *track,
2509 uint8_t *buffer, uint32_t size,
2510 int block_bref, int block_fref)
2512 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2513 demux_packet_t *dp;
2515 dp = new_demux_packet(size);
2516 memcpy(dp->buffer, buffer, size);
2517 dp->pos = demuxer->filepos;
2518 dp->pts = mkv_d->last_pts;
2519 if ((track->num_cached_dps > 0) && (dp->pts < track->max_pts))
2520 block_fref = 1;
2521 if (block_fref == 0) /* I or P frame */
2522 flush_cached_dps(demuxer, track);
2523 if (block_bref != 0) /* I frame, don't cache it */
2524 dp->flags = 0x10;
2525 if ((track->num_cached_dps + 1) > track->num_allocated_dps) {
2526 track->cached_dps = (demux_packet_t **)
2527 realloc(track->cached_dps,
2528 (track->num_cached_dps + 10) * sizeof(demux_packet_t *));
2529 track->num_allocated_dps += 10;
2531 track->cached_dps[track->num_cached_dps] = dp;
2532 track->num_cached_dps++;
2533 if (dp->pts > track->max_pts)
2534 track->max_pts = dp->pts;
2537 static int handle_block(demuxer_t *demuxer, uint8_t *block, uint64_t length,
2538 uint64_t block_duration, int64_t block_bref,
2539 int64_t block_fref, uint8_t simpleblock)
2541 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2542 mkv_track_t *track = NULL;
2543 demux_stream_t *ds = NULL;
2544 uint64_t old_length;
2545 int64_t tc;
2546 uint32_t *lace_size;
2547 uint8_t laces, flags;
2548 int i, num, tmp, use_this_block = 1;
2549 double current_pts;
2550 int16_t time;
2552 /* first byte(s): track num */
2553 num = ebml_read_vlen_uint(block, &tmp);
2554 block += tmp;
2555 /* time (relative to cluster time) */
2556 time = block[0] << 8 | block[1];
2557 block += 2;
2558 length -= tmp + 2;
2559 old_length = length;
2560 flags = block[0];
2561 if (demux_mkv_read_block_lacing(block, &length, &laces, &lace_size))
2562 return 0;
2563 block += old_length - length;
2565 tc = (time * mkv_d->tc_scale + mkv_d->cluster_tc) / 1000000.0 + 0.5;
2566 if (tc < 0)
2567 tc = 0;
2568 current_pts = tc / 1000.0;
2570 for (i = 0; i < mkv_d->num_tracks; i++)
2571 if (mkv_d->tracks[i]->tnum == num) {
2572 track = mkv_d->tracks[i];
2573 break;
2575 if (track == NULL) {
2576 free(lace_size);
2577 return 1;
2579 if (num == demuxer->audio->id) {
2580 ds = demuxer->audio;
2582 if (mkv_d->a_skip_to_keyframe) {
2583 if (simpleblock) {
2584 if (!(flags & 0x80)) /*current frame isn't a keyframe */
2585 use_this_block = 0;
2586 } else if (block_bref != 0)
2587 use_this_block = 0;
2588 } else if (mkv_d->v_skip_to_keyframe)
2589 use_this_block = 0;
2591 if (track->fix_i_bps && use_this_block) {
2592 sh_audio_t *sh = (sh_audio_t *) ds->sh;
2594 if (block_duration != 0) {
2595 sh->i_bps = length * 1000 / block_duration;
2596 track->fix_i_bps = 0;
2597 } else if (track->qt_last_a_pts == 0.0)
2598 track->qt_last_a_pts = current_pts;
2599 else if (track->qt_last_a_pts != current_pts) {
2600 sh->i_bps = length / (current_pts - track->qt_last_a_pts);
2601 track->fix_i_bps = 0;
2604 } else if (tc < mkv_d->skip_to_timecode)
2605 use_this_block = 0;
2606 else if (num == demuxer->video->id) {
2607 ds = demuxer->video;
2608 if (mkv_d->v_skip_to_keyframe) {
2609 if (simpleblock) {
2610 if (!(flags & 0x80)) /*current frame isn't a keyframe */
2611 use_this_block = 0;
2612 } else if (block_bref != 0 || block_fref != 0)
2613 use_this_block = 0;
2615 } else if (num == demuxer->sub->id) {
2616 ds = demuxer->sub;
2617 if (track->subtitle_type != MATROSKA_SUBTYPE_VOBSUB) {
2618 if (!mkv_d->v_skip_to_keyframe)
2619 handle_subtitles(demuxer, track, block, length, block_duration,
2620 tc);
2621 use_this_block = 0;
2623 } else
2624 use_this_block = 0;
2626 if (use_this_block) {
2627 mkv_d->last_pts = current_pts;
2628 mkv_d->last_filepos = demuxer->filepos;
2630 for (i = 0; i < laces; i++) {
2631 if (ds == demuxer->video && track->realmedia)
2632 handle_realvideo(demuxer, track, block, lace_size[i],
2633 block_bref);
2634 else if (ds == demuxer->audio && track->realmedia)
2635 handle_realaudio(demuxer, track, block, lace_size[i],
2636 block_bref);
2637 else if (ds == demuxer->video && track->reorder_timecodes)
2638 handle_video_bframes(demuxer, track, block, lace_size[i],
2639 block_bref, block_fref);
2640 else {
2641 int modified, size = lace_size[i];
2642 demux_packet_t *dp;
2643 uint8_t *buffer;
2644 modified = demux_mkv_decode(track, block, &buffer, &size, 1);
2645 if (buffer) {
2646 dp = new_demux_packet(size);
2647 memcpy(dp->buffer, buffer, size);
2648 if (modified)
2649 free(buffer);
2650 dp->flags = (block_bref == 0
2651 && block_fref == 0) ? 0x10 : 0;
2652 /* If default_duration is 0, assume no pts value is known
2653 * for packets after the first one (rather than all pts
2654 * values being the same) */
2655 if (i == 0 || track->default_duration)
2656 dp->pts =
2657 mkv_d->last_pts + i * track->default_duration;
2658 ds_add_packet(ds, dp);
2661 block += lace_size[i];
2664 if (ds == demuxer->video) {
2665 mkv_d->v_skip_to_keyframe = 0;
2666 mkv_d->skip_to_timecode = 0;
2667 } else if (ds == demuxer->audio)
2668 mkv_d->a_skip_to_keyframe = 0;
2670 free(lace_size);
2671 return 1;
2674 free(lace_size);
2675 return 0;
2678 static int demux_mkv_fill_buffer(demuxer_t *demuxer, demux_stream_t *ds)
2680 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2681 stream_t *s = demuxer->stream;
2682 uint64_t l;
2683 int il, tmp;
2685 while (1) {
2686 while (mkv_d->cluster_size > 0) {
2687 uint64_t block_duration = 0, block_length = 0;
2688 int64_t block_bref = 0, block_fref = 0;
2689 uint8_t *block = NULL;
2691 while (mkv_d->blockgroup_size > 0) {
2692 switch (ebml_read_id(s, &il)) {
2693 case MATROSKA_ID_BLOCKDURATION:
2694 block_duration = ebml_read_uint(s, &l);
2695 if (block_duration == EBML_UINT_INVALID) {
2696 free(block);
2697 return 0;
2699 block_duration =
2700 block_duration * mkv_d->tc_scale / 1000000.0 + 0.5;
2701 break;
2703 case MATROSKA_ID_BLOCK:
2704 block_length = ebml_read_length(s, &tmp);
2705 free(block);
2706 if (block_length > SIZE_MAX - AV_LZO_INPUT_PADDING)
2707 return 0;
2708 block = malloc(block_length + AV_LZO_INPUT_PADDING);
2709 demuxer->filepos = stream_tell(s);
2710 if (stream_read(s, block, block_length) !=
2711 (int) block_length) {
2712 free(block);
2713 return 0;
2715 l = tmp + block_length;
2716 break;
2718 case MATROSKA_ID_REFERENCEBLOCK:;
2719 int64_t num = ebml_read_int(s, &l);
2720 if (num == EBML_INT_INVALID) {
2721 free(block);
2722 return 0;
2724 if (num <= 0)
2725 block_bref = num;
2726 else
2727 block_fref = num;
2728 break;
2730 case EBML_ID_INVALID:
2731 free(block);
2732 return 0;
2734 default:
2735 ebml_read_skip(s, &l);
2736 break;
2738 mkv_d->blockgroup_size -= l + il;
2739 mkv_d->cluster_size -= l + il;
2742 if (block) {
2743 int res = handle_block(demuxer, block, block_length,
2744 block_duration, block_bref, block_fref,
2746 free(block);
2747 if (res < 0)
2748 return 0;
2749 if (res)
2750 return 1;
2753 if (mkv_d->cluster_size > 0) {
2754 switch (ebml_read_id(s, &il)) {
2755 case MATROSKA_ID_CLUSTERTIMECODE:;
2756 uint64_t num = ebml_read_uint(s, &l);
2757 if (num == EBML_UINT_INVALID)
2758 return 0;
2759 mkv_d->cluster_tc = num * mkv_d->tc_scale;
2760 break;
2762 case MATROSKA_ID_BLOCKGROUP:
2763 mkv_d->blockgroup_size = ebml_read_length(s, &tmp);
2764 l = tmp;
2765 break;
2767 case MATROSKA_ID_SIMPLEBLOCK:;
2768 int res;
2769 block_length = ebml_read_length(s, &tmp);
2770 block = malloc(block_length);
2771 demuxer->filepos = stream_tell(s);
2772 if (stream_read(s, block, block_length) !=
2773 (int) block_length) {
2774 free(block);
2775 return 0;
2777 l = tmp + block_length;
2778 res = handle_block(demuxer, block, block_length,
2779 block_duration, block_bref,
2780 block_fref, 1);
2781 free(block);
2782 mkv_d->cluster_size -= l + il;
2783 if (res < 0)
2784 return 0;
2785 else if (res)
2786 return 1;
2787 else
2788 mkv_d->cluster_size += l + il;
2789 break;
2791 case EBML_ID_INVALID:
2792 return 0;
2794 default:
2795 ebml_read_skip(s, &l);
2796 break;
2798 mkv_d->cluster_size -= l + il;
2802 if (ebml_read_id(s, &il) != MATROSKA_ID_CLUSTER)
2803 return 0;
2804 add_cluster_position(mkv_d, stream_tell(s) - il);
2805 mkv_d->cluster_size = ebml_read_length(s, NULL);
2808 return 0;
2811 static void demux_mkv_seek(demuxer_t *demuxer, float rel_seek_secs,
2812 float audio_delay, int flags)
2814 if (!(flags & (SEEK_BACKWARD | SEEK_FORWARD))) {
2815 if (flags & SEEK_ABSOLUTE || rel_seek_secs < 0)
2816 flags |= SEEK_BACKWARD;
2817 else
2818 flags |= SEEK_FORWARD;
2820 // Adjust the target a little bit to catch cases where the target position
2821 // specifies a keyframe with high, but not perfect, precision.
2822 rel_seek_secs += flags & SEEK_FORWARD ? -0.005 : 0.005;
2824 free_cached_dps(demuxer);
2825 if (!(flags & SEEK_FACTOR)) { /* time in secs */
2826 mkv_index_t *index = NULL;
2827 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2828 stream_t *s = demuxer->stream;
2829 int64_t target_timecode = 0, diff, min_diff = 0xFFFFFFFFFFFFFFFLL;
2830 int i;
2832 if (!(flags & SEEK_ABSOLUTE)) /* relative seek */
2833 target_timecode = (int64_t) (mkv_d->last_pts * 1000.0);
2834 target_timecode += (int64_t) (rel_seek_secs * 1000.0);
2835 if (target_timecode < 0)
2836 target_timecode = 0;
2838 if (mkv_d->indexes == NULL) { /* no index was found */
2839 uint64_t target_filepos, cluster_pos, max_pos;
2841 target_filepos =
2842 (uint64_t) (target_timecode * mkv_d->last_filepos /
2843 (mkv_d->last_pts * 1000.0));
2845 max_pos = mkv_d->num_cluster_pos ?
2846 mkv_d->cluster_positions[mkv_d->num_cluster_pos - 1] : 0;
2847 if (target_filepos > max_pos) {
2848 if ((off_t) max_pos > stream_tell(s))
2849 stream_seek(s, max_pos);
2850 else
2851 stream_seek(s, stream_tell(s) + mkv_d->cluster_size);
2852 /* parse all the clusters upto target_filepos */
2853 while (!s->eof && stream_tell(s) < (off_t) target_filepos) {
2854 switch (ebml_read_id(s, &i)) {
2855 case MATROSKA_ID_CLUSTER:
2856 add_cluster_position(mkv_d,
2857 (uint64_t) stream_tell(s) - i);
2858 break;
2860 case MATROSKA_ID_CUES:
2861 demux_mkv_read_cues(demuxer);
2862 break;
2864 ebml_read_skip(s, NULL);
2866 if (s->eof)
2867 stream_reset(s);
2870 if (mkv_d->indexes == NULL) {
2871 cluster_pos = mkv_d->cluster_positions[0];
2872 /* Let's find the nearest cluster */
2873 for (i = 0; i < mkv_d->num_cluster_pos; i++) {
2874 diff = mkv_d->cluster_positions[i] - target_filepos;
2875 if (flags & SEEK_BACKWARD && diff < 0 && -diff < min_diff) {
2876 cluster_pos = mkv_d->cluster_positions[i];
2877 min_diff = -diff;
2878 } else if (flags & SEEK_FORWARD
2879 && (diff < 0 ? -1 * diff : diff) < min_diff) {
2880 cluster_pos = mkv_d->cluster_positions[i];
2881 min_diff = diff < 0 ? -1 * diff : diff;
2884 mkv_d->cluster_size = mkv_d->blockgroup_size = 0;
2885 stream_seek(s, cluster_pos);
2887 } else {
2888 int seek_id = (demuxer->video->id < 0) ?
2889 demuxer->audio->id : demuxer->video->id;
2891 /* let's find the entry in the indexes with the smallest */
2892 /* difference to the wanted timecode. */
2893 for (i = 0; i < mkv_d->num_indexes; i++)
2894 if (mkv_d->indexes[i].tnum == seek_id) {
2895 diff =
2896 target_timecode -
2897 (int64_t) (mkv_d->indexes[i].timecode *
2898 mkv_d->tc_scale / 1000000.0 + 0.5);
2900 if (flags & SEEK_BACKWARD) {
2901 // Seek backward: find the last index position
2902 // before target time
2903 if (diff < 0 || diff >= min_diff)
2904 continue;
2905 } else {
2906 // Seek forward: find the first index position
2907 // after target time. If no such index exists, find last
2908 // position between current position and target time.
2909 if (diff <= 0) {
2910 if (min_diff <= 0 && diff <= min_diff)
2911 continue;
2912 } else if (diff >=
2913 FFMIN(target_timecode - mkv_d->last_pts,
2914 min_diff))
2915 continue;
2917 min_diff = diff;
2918 index = mkv_d->indexes + i;
2921 if (index) { /* We've found an entry. */
2922 mkv_d->cluster_size = mkv_d->blockgroup_size = 0;
2923 stream_seek(s, index->filepos);
2927 if (demuxer->video->id >= 0)
2928 mkv_d->v_skip_to_keyframe = 1;
2929 if (flags & SEEK_FORWARD)
2930 mkv_d->skip_to_timecode = target_timecode;
2931 else
2932 mkv_d->skip_to_timecode = index ? index->timecode : 0;
2933 mkv_d->a_skip_to_keyframe = 1;
2935 demux_mkv_fill_buffer(demuxer, NULL);
2936 } else if ((demuxer->movi_end <= 0) || !(flags & SEEK_ABSOLUTE))
2937 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] seek unsupported flags\n");
2938 else {
2939 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2940 stream_t *s = demuxer->stream;
2941 uint64_t target_filepos;
2942 mkv_index_t *index = NULL;
2943 int i;
2945 if (mkv_d->indexes == NULL) { /* not implemented without index */
2946 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] seek unsupported flags\n");
2947 return;
2950 target_filepos = (uint64_t) (demuxer->movi_end * rel_seek_secs);
2951 for (i = 0; i < mkv_d->num_indexes; i++)
2952 if (mkv_d->indexes[i].tnum == demuxer->video->id)
2953 if ((index == NULL)
2954 || ((mkv_d->indexes[i].filepos >= target_filepos)
2955 && ((index->filepos < target_filepos)
2956 || (mkv_d->indexes[i].filepos < index->filepos))))
2957 index = &mkv_d->indexes[i];
2959 if (!index)
2960 return;
2962 mkv_d->cluster_size = mkv_d->blockgroup_size = 0;
2963 stream_seek(s, index->filepos);
2965 if (demuxer->video->id >= 0)
2966 mkv_d->v_skip_to_keyframe = 1;
2967 mkv_d->skip_to_timecode = index->timecode;
2968 mkv_d->a_skip_to_keyframe = 1;
2970 demux_mkv_fill_buffer(demuxer, NULL);
2974 static int demux_mkv_control(demuxer_t *demuxer, int cmd, void *arg)
2976 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2978 switch (cmd) {
2979 case DEMUXER_CTRL_CORRECT_PTS:
2980 return DEMUXER_CTRL_OK;
2981 case DEMUXER_CTRL_GET_TIME_LENGTH:
2982 if (mkv_d->duration == 0)
2983 return DEMUXER_CTRL_DONTKNOW;
2985 *((double *) arg) = (double) mkv_d->duration;
2986 return DEMUXER_CTRL_OK;
2988 case DEMUXER_CTRL_GET_PERCENT_POS:
2989 if (mkv_d->duration == 0) {
2990 return DEMUXER_CTRL_DONTKNOW;
2993 *((int *) arg) = (int) (100 * mkv_d->last_pts / mkv_d->duration);
2994 return DEMUXER_CTRL_OK;
2996 case DEMUXER_CTRL_SWITCH_AUDIO:
2997 if (demuxer->audio && demuxer->audio->sh) {
2998 sh_audio_t *sh = demuxer->a_streams[demuxer->audio->id];
2999 int aid = *(int *) arg;
3000 if (aid < 0)
3001 aid = (sh->aid + 1) % mkv_d->last_aid;
3002 if (aid != sh->aid) {
3003 mkv_track_t *track =
3004 demux_mkv_find_track_by_num(mkv_d, aid,
3005 MATROSKA_TRACK_AUDIO);
3006 if (track) {
3007 demuxer->audio->id = track->tnum;
3008 sh = demuxer->a_streams[demuxer->audio->id];
3009 ds_free_packs(demuxer->audio);
3012 *(int *) arg = sh->aid;
3013 } else
3014 *(int *) arg = -2;
3015 return DEMUXER_CTRL_OK;
3017 default:
3018 return DEMUXER_CTRL_NOTIMPL;
3022 const demuxer_desc_t demuxer_desc_matroska = {
3023 "Matroska demuxer",
3024 "mkv",
3025 "Matroska",
3026 "Aurelien Jacobs",
3028 DEMUXER_TYPE_MATROSKA,
3029 1, // safe autodetect
3030 demux_mkv_open,
3031 demux_mkv_fill_buffer,
3032 NULL,
3033 demux_close_mkv,
3034 demux_mkv_seek,
3035 demux_mkv_control