comparison libmpdemux/demux_mkv_old.cpp @ 11836:33351e4ce3de

mkv.cpp -> mkv_old.cpp, to avoid dependency name collision with mkv.c
author arpi
date Fri, 23 Jan 2004 21:34:28 +0000
parents libmpdemux/demux_mkv.cpp@7d5b1df3b952
children 8904d42e00ce
comparison
equal deleted inserted replaced
11835:7d5b1df3b952 11836:33351e4ce3de
1 // Matroska demuxer
2 // written by Moritz Bunkus <moritz@bunkus.org>
3 // License: GPL of course ;)
4
5 // $Id$
6
7 extern "C" {
8 #include "config.h"
9 }
10
11 #ifdef HAVE_MATROSKA
12
13 #include <vector>
14
15 #include <ebml/EbmlHead.h>
16 #include <ebml/EbmlSubHead.h>
17 #include <ebml/EbmlStream.h>
18 #include <ebml/EbmlContexts.h>
19 #include <ebml/EbmlVersion.h>
20 #include <ebml/StdIOCallback.h>
21
22 #include <matroska/KaxVersion.h>
23
24 #include <matroska/KaxAttachments.h>
25 #include <matroska/KaxBlock.h>
26 #include <matroska/KaxBlockData.h>
27 #include <matroska/KaxChapters.h>
28 #include <matroska/KaxCluster.h>
29 #include <matroska/KaxClusterData.h>
30 #if LIBMATROSKA_VERSION >= 000503
31 #include <matroska/KaxContentEncoding.h>
32 #endif
33 #include <matroska/KaxContexts.h>
34 #include <matroska/KaxCues.h>
35 #include <matroska/KaxCuesData.h>
36 #include <matroska/KaxInfo.h>
37 #include <matroska/KaxInfoData.h>
38 #include <matroska/KaxSeekHead.h>
39 #include <matroska/KaxSegment.h>
40 #include <matroska/KaxTracks.h>
41 #include <matroska/KaxTrackAudio.h>
42 #include <matroska/KaxTrackVideo.h>
43 #include <matroska/KaxTrackEntryData.h>
44 #include <matroska/FileKax.h>
45
46 extern "C" {
47 #include <ctype.h>
48 #include <stdlib.h>
49 #include <stdio.h>
50 #include <string.h>
51
52 #ifdef HAVE_ZLIB
53 #include <zlib.h>
54 #endif
55
56 #include "../mp_msg.h"
57 #include "../help_mp.h"
58 #include "stream.h"
59 #include "demuxer.h"
60 #include "stheader.h"
61
62 #include "../subreader.h"
63 #include "../libvo/sub.h"
64
65 }
66
67 #include "matroska.h"
68
69 using namespace libebml;
70 using namespace libmatroska;
71 using namespace std;
72
73 #if LIBEBML_VERSION < 000500
74 #error libebml version too old - need at least 0.5.0
75 #endif
76
77 // for e.g. "-slang ger"
78 extern char *dvdsub_lang;
79 extern char *audio_lang;
80 // for "-chapter x-y"
81 extern int dvd_chapter;
82 extern int dvd_last_chapter;
83
84 // default values for Matroska elements
85 #define MKVD_TIMECODESCALE 1000000 // 1000000 = 1ms
86
87 #define MKV_SUBTYPE_TEXT 1
88 #define MKV_SUBTYPE_SSA 2
89 #define MKV_SUBTYPE_VOBSUB 3
90
91 #define MKV_SUBCOMPRESSION_NONE 0
92 #define MKV_SUBCOMPRESSION_ZLIB 1
93
94 #define safefree(m) { if (m != NULL) free(m); }
95 void *safemalloc(int bytes) {
96 void *dst;
97
98 dst = malloc(bytes);
99 if (dst == NULL) {
100 mp_msg(MSGT_DEMUX, MSGL_FATAL, "[mkv] Could not allocate %d bytes of "
101 "memory.\n", bytes);
102 exit(1);
103 }
104
105 return dst;
106 }
107
108 void *safememdup(const void *src, int bytes) {
109 void *dst;
110
111 dst = safemalloc(bytes);
112 memcpy(dst, src, bytes);
113
114 return dst;
115 }
116
117 class mpstream_io_callback: public IOCallback {
118 private:
119 stream_t *s;
120 public:
121 mpstream_io_callback(stream_t *stream);
122
123 virtual uint32 read(void *buffer, size_t size);
124 virtual void setFilePointer(int64 offset, seek_mode mode = seek_beginning);
125 virtual size_t write(const void *buffer, size_t size);
126 virtual uint64 getFilePointer();
127 virtual void close();
128 };
129
130 mpstream_io_callback::mpstream_io_callback(stream_t *stream) {
131 s = stream;
132 }
133
134 uint32 mpstream_io_callback::read(void *buffer, size_t size) {
135 uint32_t result;
136
137 result = stream_read(s, (char *)buffer, size);
138
139 return result;
140 }
141
142 void mpstream_io_callback::setFilePointer(int64 offset, seek_mode mode) {
143 int64 new_pos;
144
145 if (mode == seek_beginning)
146 new_pos = offset + s->start_pos;
147 else if (mode == seek_end)
148 new_pos = s->end_pos - offset;
149 else
150 new_pos = s->pos + offset;
151
152 if (new_pos > s->end_pos) {
153 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] seek warning: new_pos %lld > end_pos "
154 "%lld\n", new_pos, s->end_pos);
155 return;
156 }
157
158 stream_seek(s, new_pos);
159 }
160
161 size_t mpstream_io_callback::write(const void */*buffer*/, size_t /*size*/) {
162 return 0;
163 }
164
165 uint64 mpstream_io_callback::getFilePointer() {
166 return s->pos - s->buf_len + s->buf_pos;
167 }
168
169 void mpstream_io_callback::close() {
170 }
171
172 typedef struct mkv_index_entry {
173 uint64_t timecode, filepos;
174 int is_key;
175 } mkv_index_entry_t;
176
177 typedef struct mkv_track_index {
178 uint32_t tnum;
179 int num_entries;
180 mkv_index_entry_t *entries;
181 } mkv_track_index_t;
182
183 typedef struct {
184 uint32_t order, type, scope;
185 uint32_t comp_algo;
186 unsigned char *comp_settings;
187 uint32_t comp_settings_len;
188 uint32_t enc_algo, sig_algo, sig_hash_algo;
189 unsigned char *enc_keyid, *sig_keyid, *signature;
190 uint32_t enc_keyid_len, sig_keyid_len, signature_len;
191 } mkv_content_encoding_t;
192
193 typedef struct {
194 int64_t start, end;
195 } mkv_chapter_t;
196
197 typedef struct mkv_track {
198 uint32_t tnum, xid;
199
200 char *codec_id;
201 int ms_compat;
202 char *language;
203
204 char type; // 'v' = video, 'a' = audio, 's' = subs
205
206 char v_fourcc[5];
207 uint32_t v_width, v_height, v_dwidth, v_dheight;
208 float v_frate;
209
210 uint32_t a_formattag;
211 uint32_t a_channels, a_bps;
212 float a_sfreq;
213
214 float default_duration;
215
216 int default_track;
217
218 void *private_data;
219 unsigned int private_size;
220
221 // For Vorbis audio
222 unsigned char *headers[3];
223 uint32_t header_sizes[3];
224
225 int ok;
226
227 // Stuff for RealMedia
228 bool realmedia;
229 demux_packet_t *rm_dp;
230 int rm_seqnum, rv_kf_base, rv_kf_pts;
231 float rv_pts; // previous video timestamp
232 float ra_pts; // previous audio timestamp
233
234 // Stuff for QuickTime
235 bool fix_i_bps;
236 float qt_last_a_pts;
237
238 // Stuff for VobSubs
239 mkv_sh_sub_t sh_sub;
240
241 // Generic content encoding support.
242 vector<mkv_content_encoding_t> *c_encodings;
243 } mkv_track_t;
244
245 typedef struct mkv_demuxer {
246 float duration, last_pts;
247 uint64_t last_filepos;
248
249 mkv_track_t **tracks;
250 int num_tracks;
251 mkv_track_t *video, *audio, *subs_track;
252
253 uint64_t tc_scale, cluster_tc, first_tc;
254
255 mpstream_io_callback *in;
256
257 uint64_t clear_subs_at[SUB_MAX_TEXT];
258
259 subtitle subs;
260 int subtitle_type;
261
262 EbmlStream *es;
263 EbmlElement *saved_l1, *saved_l2;
264 KaxSegment *segment;
265 KaxCluster *cluster;
266
267 mkv_track_index_t *index;
268 int num_indexes, cues_found, cues_searched;
269 int64_t *cluster_positions;
270 int num_cluster_pos;
271 vector<uint64_t> *parsed_seekheads;
272 vector<uint64_t> *parsed_cues;
273
274 int64_t skip_to_timecode;
275 bool v_skip_to_keyframe, a_skip_to_keyframe;
276
277 vector<mkv_chapter_t> *chapters; // No support for nested chapters atm.
278 uint64_t stop_timecode;
279 } mkv_demuxer_t;
280
281 typedef struct {
282 uint32_t chunks; // number of chunks
283 uint32_t timestamp; // timestamp from packet header
284 uint32_t len; // length of actual data
285 uint32_t chunktab; // offset to chunk offset array
286 } dp_hdr_t;
287
288 #if __GNUC__ == 2
289 #pragma pack(2)
290 #else
291 #pragma pack(push,2)
292 #endif
293
294 typedef struct {
295 uint32_t size;
296 uint32_t fourcc1;
297 uint32_t fourcc2;
298 uint16_t width;
299 uint16_t height;
300 uint16_t bpp;
301 uint32_t unknown1;
302 uint32_t fps;
303 uint32_t type1;
304 uint32_t type2;
305 } real_video_props_t;
306
307 typedef struct {
308 uint32_t fourcc1; // '.', 'r', 'a', 0xfd
309 uint16_t version1; // 4 or 5
310 uint16_t unknown1; // 00 000
311 uint32_t fourcc2; // .ra4 or .ra5
312 uint32_t unknown2; // ???
313 uint16_t version2; // 4 or 5
314 uint32_t header_size; // == 0x4e
315 uint16_t flavor; // codec flavor id
316 uint32_t coded_frame_size; // coded frame size
317 uint32_t unknown3; // big number
318 uint32_t unknown4; // bigger number
319 uint32_t unknown5; // yet another number
320 uint16_t sub_packet_h;
321 uint16_t frame_size;
322 uint16_t sub_packet_size;
323 uint16_t unknown6; // 00 00
324 uint16_t sample_rate;
325 uint16_t unknown8; // 0
326 uint16_t sample_size;
327 uint16_t channels;
328 } real_audio_v4_props_t;
329
330 typedef struct {
331 uint32_t fourcc1; // '.', 'r', 'a', 0xfd
332 uint16_t version1; // 4 or 5
333 uint16_t unknown1; // 00 000
334 uint32_t fourcc2; // .ra4 or .ra5
335 uint32_t unknown2; // ???
336 uint16_t version2; // 4 or 5
337 uint32_t header_size; // == 0x4e
338 uint16_t flavor; // codec flavor id
339 uint32_t coded_frame_size; // coded frame size
340 uint32_t unknown3; // big number
341 uint32_t unknown4; // bigger number
342 uint32_t unknown5; // yet another number
343 uint16_t sub_packet_h;
344 uint16_t frame_size;
345 uint16_t sub_packet_size;
346 uint16_t unknown6; // 00 00
347 uint8_t unknown7[6]; // 0, srate, 0
348 uint16_t sample_rate;
349 uint16_t unknown8; // 0
350 uint16_t sample_size;
351 uint16_t channels;
352 uint32_t genr; // "genr"
353 uint32_t fourcc3; // fourcc
354 } real_audio_v5_props_t;
355
356 // I have to (re)define this struct here because g++ will not compile
357 // components.h from the qtsdk if I include it.
358 typedef struct {
359 uint32_t id_size;
360 uint32_t codec_type;
361 uint32_t reserved1;
362 uint16_t reserved2;
363 uint16_t data_reference_index;
364 uint16_t version;
365 uint16_t revision;
366 uint32_t vendor;
367 uint32_t temporal_quality;
368 uint32_t spatial_quality;
369 uint16_t width;
370 uint16_t height;
371 uint32_t horizontal_resolution; // 32bit fixed-point number
372 uint32_t vertical_resolution; // 32bit fixed-point number
373 uint32_t data_size;
374 uint16_t frame_count;
375 char compressor_name[32];
376 uint16_t depth;
377 uint16_t color_table_id;
378 } qt_image_description_t;
379
380 #if __GNUC__ == 2
381 #pragma pack()
382 #else
383 #pragma pack(pop)
384 #endif
385
386 static uint16_t get_uint16(const void *buf) {
387 uint16_t ret;
388 unsigned char *tmp;
389
390 tmp = (unsigned char *) buf;
391
392 ret = tmp[1] & 0xff;
393 ret = (ret << 8) + (tmp[0] & 0xff);
394
395 return ret;
396 }
397
398 static uint32_t get_uint32(const void *buf) {
399 uint32_t ret;
400 unsigned char *tmp;
401
402 tmp = (unsigned char *) buf;
403
404 ret = tmp[3] & 0xff;
405 ret = (ret << 8) + (tmp[2] & 0xff);
406 ret = (ret << 8) + (tmp[1] & 0xff);
407 ret = (ret << 8) + (tmp[0] & 0xff);
408
409 return ret;
410 }
411
412 static uint16_t get_uint16_be(const void *buf) {
413 uint16_t ret;
414 unsigned char *tmp;
415
416 tmp = (unsigned char *) buf;
417
418 ret = tmp[0] & 0xff;
419 ret = (ret << 8) + (tmp[1] & 0xff);
420
421 return ret;
422 }
423
424 static uint32_t get_uint32_be(const void *buf) {
425 uint32_t ret;
426 unsigned char *tmp;
427
428 tmp = (unsigned char *) buf;
429
430 ret = tmp[0] & 0xff;
431 ret = (ret << 8) + (tmp[1] & 0xff);
432 ret = (ret << 8) + (tmp[2] & 0xff);
433 ret = (ret << 8) + (tmp[3] & 0xff);
434
435 return ret;
436 }
437
438 unsigned char read_char(unsigned char *p, int &pos, int size) {
439 if ((pos + 1) > size)
440 throw exception();
441 pos++;
442 return p[pos - 1];
443 }
444
445 unsigned short read_word(unsigned char *p, int &pos, int size) {
446 unsigned short v;
447
448 if ((pos + 2) > size)
449 throw exception();
450 v = p[pos];
451 v = (v << 8) | (p[pos + 1] & 0xff);
452 pos += 2;
453 return v;
454 }
455
456 unsigned int read_dword(unsigned char *p, int &pos, int size) {
457 unsigned int v;
458
459 if ((pos + 4) > size)
460 throw exception();
461 v = p[pos];
462 v = (v << 8) | (p[pos + 1] & 0xff);
463 v = (v << 8) | (p[pos + 2] & 0xff);
464 v = (v << 8) | (p[pos + 3] & 0xff);
465 pos += 4;
466 return v;
467 }
468
469 static void
470 finish_text_sub_handling(mkv_demuxer_t *mkv_d, KaxBlock *block,
471 int64_t duration, int first_line) {
472 int i;
473
474 #ifdef USE_ICONV
475 subcp_recode1(&mkv_d->subs);
476 #endif
477
478 vo_sub = &mkv_d->subs;
479 vo_osd_changed(OSDTYPE_SUBTITLE);
480
481 for (i = first_line; i <= (mkv_d->subs.lines - 1); i++)
482 mkv_d->clear_subs_at[i] = block->GlobalTimecode() / 1000000 -
483 mkv_d->first_tc + duration;
484 }
485
486 static void handle_subtitles(demuxer_t *d, KaxBlock *block, int64_t duration) {
487 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *)d->priv;
488 int len, line, state, i, first_line;
489 char *s1, *s2, *buffer;
490
491 if (duration == -1) {
492 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] Warning: No KaxBlockDuration "
493 "element for subtitle track found.\n");
494 return;
495 }
496
497 DataBuffer &data = block->GetBuffer(0);
498 len = data.Size();
499
500 buffer = (char *)data.Buffer();
501 s1 = buffer;
502
503 while (((*s1 == '\n') || (*s1 == '\r')) &&
504 ((unsigned int)(s1 - buffer) <= data.Size()))
505 s1++;
506
507 line = 0;
508 mkv_d->subs.lines++;
509 if (mkv_d->subs.lines > SUB_MAX_TEXT) {
510 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] Warning: too many sublines to "
511 "render, skipping\n");
512 mkv_d->subs.lines = SUB_MAX_TEXT;
513 return;
514 }
515 first_line = mkv_d->subs.lines - 1;
516 s2 = mkv_d->subs.text[mkv_d->subs.lines - 1];
517 state = 0;
518
519 if (mkv_d->subtitle_type == MKV_SUBTYPE_SSA) {
520 /* Matroska's SSA format does not have timecodes embedded into
521 the SAA line. Timescodes are encoded into the blocks timecode
522 and duration. */
523
524 /* Find text section. */
525 for (i = 0; (i < 8) && (*s1 != 0); s1++)
526 if (*s1 == ',')
527 i++;
528
529 if (*s1 == 0) { // Broken line?
530 mkv_d->subs.lines--;
531 return;
532 }
533
534 /* Load text. */
535 while ((unsigned int)(s1 - buffer) < data.Size()) {
536 if (*s1 == '{')
537 state = 1;
538 else if ((*s1 == '}') && (state == 1))
539 state = 2;
540
541 if (state == 0) {
542 *s2 = *s1;
543 s2++;
544 if ((s2 - mkv_d->subs.text[mkv_d->subs.lines - 1]) >= 255)
545 break;
546 }
547 s1++;
548
549 /* Newline */
550 if ((*s1 == '\\') && ((unsigned int)(s1 + 1 - buffer) < data.Size()) &&
551 ((*(s1 + 1) == 'N') || (*(s1 + 1) == 'n'))) {
552 *s2 = 0;
553 mkv_d->subs.lines++;
554 if (mkv_d->subs.lines > SUB_MAX_TEXT) {
555 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] Warning: too many sublines to "
556 "render, skipping\n");
557 mkv_d->subs.lines = SUB_MAX_TEXT;
558 finish_text_sub_handling(mkv_d, block, duration, first_line);
559 return;
560 }
561 s2 = mkv_d->subs.text[mkv_d->subs.lines - 1];
562 s1 += 2;
563 }
564
565 if (state == 2)
566 state = 0;
567 }
568 *s2 = 0;
569
570 } else {
571 while ((unsigned int)(s1 - buffer) != data.Size()) {
572 if ((*s1 == '\n') || (*s1 == '\r')) {
573 if (state == 0) { // normal char --> newline
574 if (mkv_d->subs.lines == SUB_MAX_TEXT)
575 break;
576 *s2 = 0;
577 mkv_d->clear_subs_at[mkv_d->subs.lines - 1]=
578 block->GlobalTimecode() / 1000000 - mkv_d->first_tc + duration;
579 s2 = mkv_d->subs.text[mkv_d->subs.lines];
580 mkv_d->subs.lines++;
581 state = 1;
582 }
583 } else if (*s1 == '<') // skip HTML tags
584 state = 2;
585 else if (*s1 == '>')
586 state = 0;
587 else if (state != 2) { // normal character
588 state = 0;
589 if ((s2 - mkv_d->subs.text[mkv_d->subs.lines - 1]) < 255) {
590 *s2 = *s1;
591 s2++;
592 }
593 }
594 s1++;
595 }
596
597 *s2 = 0;
598 }
599
600 finish_text_sub_handling(mkv_d, block, duration, first_line);
601 }
602
603 static mkv_track_t *new_mkv_track(mkv_demuxer_t *d) {
604 mkv_track_t *t;
605
606 t = (mkv_track_t *)safemalloc(sizeof(mkv_track_t));
607 memset(t, 0, sizeof(mkv_track_t));
608 d->tracks = (mkv_track_t **)realloc(d->tracks, (d->num_tracks + 1) *
609 sizeof(mkv_track_t *));
610 if (d->tracks == NULL)
611 return NULL;
612 d->tracks[d->num_tracks] = t;
613 d->num_tracks++;
614
615 // Set default values.
616 t->default_track = 1;
617 t->a_sfreq = 8000.0;
618 t->a_channels = 1;
619 t->language = strdup("eng");
620
621 t->c_encodings = new vector<mkv_content_encoding_t>;
622
623 return t;
624 }
625
626 static mkv_track_t *find_track_by_num(mkv_demuxer_t *d, uint32_t n,
627 char track_type) {
628 int i;
629
630 for (i = 0; i < d->num_tracks; i++)
631 if ((d->tracks[i] != NULL) && (d->tracks[i]->type == track_type) &&
632 (d->tracks[i]->xid == n))
633 return d->tracks[i];
634
635 return NULL;
636 }
637
638 static mkv_track_t *find_duplicate_track_by_num(mkv_demuxer_t *d, uint32_t n,
639 mkv_track_t *c) {
640 int i;
641
642 for (i = 0; i < d->num_tracks; i++)
643 if ((d->tracks[i] != NULL) && (d->tracks[i]->tnum == n) &&
644 (d->tracks[i] != c))
645 return d->tracks[i];
646
647 return NULL;
648 }
649
650 static mkv_track_t *find_track_by_language(mkv_demuxer_t *d, char *language,
651 mkv_track_t *c, char type = 's') {
652 int i;
653
654 for (i = 0; i < d->num_tracks; i++)
655 if ((d->tracks[i] != NULL) && (d->tracks[i] != c) &&
656 (d->tracks[i]->language != NULL) &&
657 !strcmp(d->tracks[i]->language, language) &&
658 (d->tracks[i]->type == type))
659 return d->tracks[i];
660
661 return NULL;
662 }
663
664 static bool mkv_parse_idx(mkv_track_t *t) {
665 uint32_t i, p, things_found;
666 int idx;
667 string line, s1, s2;
668 char *src;
669
670 if ((t->private_data == NULL) || (t->private_size < 1))
671 return false;
672
673 things_found = 0;
674 i = 0;
675 src = (char *)t->private_data;
676 do {
677 line = "";
678 while ((i < t->private_size) && (src[i] != '\n') && (src[i] != '\r')) {
679 if (!isspace(src[i]))
680 line += src[i];
681 i++;
682 }
683 while ((i < t->private_size) && ((src[i] == '\n') || (src[i] == '\r')))
684 i++;
685
686 if (!strncasecmp(line.c_str(), "size:", 5)) {
687 s1 = line.substr(5);
688 idx = s1.find('x');
689 if (idx >= 0) {
690 s2 = s1.substr(idx + 1);
691 s1.erase(idx);
692 t->sh_sub.width = strtol(s1.c_str(), NULL, 10);
693 t->sh_sub.height = strtol(s2.c_str(), NULL, 10);
694 things_found |= 1;
695 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] VobSub IDX parser: size: %d x %d\n",
696 t->sh_sub.width, t->sh_sub.height);
697 }
698
699 } else if (!strncasecmp(line.c_str(), "palette:", 8)) {
700 s1 = line.substr(8);
701 for (p = 0; p < 15; p++) {
702 idx = s1.find(',');
703 if (idx < 0)
704 break;
705 s2 = s1.substr(0, idx);
706 s1.erase(0, idx + 1);
707 t->sh_sub.palette[p] = (unsigned int)strtol(s2.c_str(), NULL, 16);
708 }
709 if (idx >= 0) {
710 t->sh_sub.palette[15] = (unsigned int)strtol(s1.c_str(), NULL, 16);
711 things_found |= 2;
712 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] VobSub IDX parser: palette: 0x%06x "
713 "0x%06x 0x%06x 0x%06x 0x%06x 0x%06x 0x%06x 0x%06x 0x%06x "
714 "0x%06x 0x%06x 0x%06x 0x%06x 0x%06x 0x%06x 0x%06x\n",
715 t->sh_sub.palette[0], t->sh_sub.palette[1],
716 t->sh_sub.palette[2], t->sh_sub.palette[3],
717 t->sh_sub.palette[4], t->sh_sub.palette[5],
718 t->sh_sub.palette[6], t->sh_sub.palette[7],
719 t->sh_sub.palette[8], t->sh_sub.palette[9],
720 t->sh_sub.palette[10], t->sh_sub.palette[11],
721 t->sh_sub.palette[12], t->sh_sub.palette[13],
722 t->sh_sub.palette[14], t->sh_sub.palette[15]);
723 }
724 }
725
726 } while ((i != t->private_size) && (things_found != 3));
727 t->sh_sub.type = 'v';
728
729 return (things_found == 3);
730 }
731
732 static bool reverse_encodings(mkv_track_t *track, unsigned char *&data,
733 uint32_t &size, uint32_t type) {
734 int new_size, n;
735 unsigned char *new_data, *old_data;
736 bool modified;
737 vector<mkv_content_encoding_t>::iterator ce;
738
739 if (track->c_encodings->size() == 0)
740 return false;
741
742 new_data = data;
743 new_size = size;
744 modified = false;
745 for (ce = track->c_encodings->begin(); ce < track->c_encodings->end();
746 ce++) {
747 if ((ce->scope & type) == 0)
748 continue;
749
750 #ifdef HAVE_ZLIB
751 if (ce->comp_algo == 0) {
752 int result;
753 z_stream zstream;
754
755 old_data = new_data;
756
757 zstream.zalloc = (alloc_func)0;
758 zstream.zfree = (free_func)0;
759 zstream.opaque = (voidpf)0;
760 result = inflateInit(&zstream);
761 if (result != Z_OK) {
762 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] Zlib initialization failed. "
763 "Result: %d\n", result);
764 safefree(new_data);
765 data = old_data;
766 size = new_size;
767 return modified;
768 }
769 zstream.next_in = (Bytef *)old_data;
770 zstream.avail_in = new_size;
771
772 n = 0;
773 new_data = NULL;
774 do {
775 n++;
776 new_data = (unsigned char *)realloc(new_data, n * 4000);
777 zstream.next_out = (Bytef *)&new_data[(n - 1) * 4000];
778 zstream.avail_out = 4000;
779 result = inflate(&zstream, Z_NO_FLUSH);
780 if ((result != Z_OK) && (result != Z_STREAM_END)) {
781 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] Zlib decompression failed. "
782 "Result: %d \n", result);
783 safefree(new_data);
784 data = old_data;
785 size = new_size;
786 inflateEnd(&zstream);
787 return modified;
788 }
789 } while ((zstream.avail_out == 0) &&
790 (zstream.avail_in != 0) && (result != Z_STREAM_END));
791
792 mp_msg(MSGT_DEMUX, MSGL_DBG2, "[mkv] zlib decompression: from %d to "
793 "%d \n", (int)new_size, (int)zstream.total_out);
794 new_size = zstream.total_out;
795 inflateEnd(&zstream);
796
797 if (modified)
798 safefree(old_data);
799 modified = true;
800 }
801 #endif
802 }
803
804 data = new_data;
805 size = new_size;
806
807 return modified;
808 }
809
810 static int check_track_information(mkv_demuxer_t *d) {
811 int i, track_num;
812 unsigned char *c;
813 uint32_t u, offset, length;
814 mkv_track_t *t;
815 mkv_content_encoding_t *ce;
816 BITMAPINFOHEADER *bih;
817 WAVEFORMATEX *wfe;
818
819 for (track_num = 0; track_num < d->num_tracks; track_num++) {
820 t = d->tracks[track_num];
821
822 t->ok = 1;
823 for (i = 0; i < (int)t->c_encodings->size(); i++) {
824 ce = &(*t->c_encodings)[i];
825
826 if (ce->type == 1) {
827 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] Track number %u has been "
828 "encrypted and decryption has not yet been implemented. "
829 "Skipping track.\n", t->tnum);
830 t->ok = 0;
831 break;
832 }
833
834 if (ce->type != 0) {
835 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] Unknown content encoding type %u "
836 "for track %u. Skipping track.\n", ce->type, t->tnum);
837 t->ok = 0;
838 break;
839 }
840
841 if (ce->comp_algo == 0) {
842 #if !defined(HAVE_ZLIB)
843 mp_msg(MSGT_DEMUX, MSGL_WARN, "Track %u was compressed with zlib but "
844 "mplayer has not been compiled with support for zlib "
845 "compression. Skipping track.\n", t->tnum);
846 t->ok = 0;
847 break;
848 #endif
849 } else {
850 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] Track %u has been compressed "
851 "with an unknown/unsupported compression algorithm (%u). "
852 "Skipping track.\n", t->tnum, ce->comp_algo);
853 t->ok = 0;
854 break;
855 }
856 }
857
858 if (!t->ok)
859 continue;
860 t->ok = 0;
861
862 if (t->private_data != NULL) {
863 c = (unsigned char *)t->private_data;
864 length = t->private_size;
865 if (reverse_encodings(t, c, length, 2)) {
866 safefree(t->private_data);
867 t->private_data = c;
868 t->private_size = length;
869 }
870 }
871
872 switch (t->type) {
873 case 'v': // video track
874 if (t->codec_id == NULL)
875 continue;
876 if (!strcmp(t->codec_id, MKV_V_MSCOMP)) {
877 if ((t->private_data == NULL) ||
878 (t->private_size < sizeof(BITMAPINFOHEADER))) {
879 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] WARNING: CodecID for track "
880 "%u is '" MKV_V_MSCOMP "', but there was no "
881 "BITMAPINFOHEADER struct present. Therefore we don't have "
882 "a FourCC to identify the video codec used.\n", t->tnum);
883 continue;
884 } else {
885 t->ms_compat = 1;
886
887 bih = (BITMAPINFOHEADER *)t->private_data;
888
889 u = get_uint32(&bih->biWidth);
890 if (t->v_width != u) {
891 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] WARNING: (MS "
892 "compatibility mode, track %u) "
893 "Matrosa says video width is %u, but the "
894 "BITMAPINFOHEADER says %u.\n", t->tnum, t->v_width, u);
895 if (t->v_width == 0)
896 t->v_width = u;
897 }
898
899 u = get_uint32(&bih->biHeight);
900 if (t->v_height != u) {
901 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] WARNING: (MS compatibility "
902 "mode, track %u) "
903 "Matrosa video height is %u, but the BITMAPINFOHEADER "
904 "says %u.\n", t->tnum, t->v_height, u);
905 if (t->v_height == 0)
906 t->v_height = u;
907 }
908
909 memcpy(t->v_fourcc, &bih->biCompression, 4);
910 }
911 }
912
913 if (t->v_width == 0) {
914 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] The width for track %u was "
915 "not set.\n", t->tnum);
916 continue;
917 }
918 if (t->v_height == 0) {
919 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] The height for track %u was "
920 "not set.\n", t->tnum);
921 continue;
922 }
923
924 if (t->v_dwidth == 0)
925 t->v_dwidth = t->v_width;
926 if (t->v_dheight == 0)
927 t->v_dheight = t->v_height;
928
929 // This track seems to be ok.
930 t->ok = 1;
931 mp_msg(MSGT_DEMUX, MSGL_INFO, "[mkv] Track ID %u: video (%s), "
932 "-vid %u\n", t->tnum, t->codec_id, t->xid);
933
934 break;
935
936 case 'a': // audio track
937 if (t->codec_id == NULL)
938 continue;
939 if (!strcmp(t->codec_id, MKV_A_ACM)) {
940 if ((t->private_data == NULL) ||
941 (t->private_size < sizeof(WAVEFORMATEX))) {
942 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] WARNING: CodecID for track "
943 "%u is '" MKV_A_ACM "', "
944 "but there was no WAVEFORMATEX struct present. "
945 "Therefore we don't have a format ID to identify the audio "
946 "codec used.\n", t->tnum);
947 continue;
948 } else {
949 t->ms_compat = 1;
950
951 wfe = (WAVEFORMATEX *)t->private_data;
952 u = get_uint32(&wfe->nSamplesPerSec);
953 if (((uint32_t)t->a_sfreq) != u) {
954 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] WARNING: (MS compatibility "
955 "mode for track %u) "
956 "Matroska says that there are %u samples per second, "
957 "but WAVEFORMATEX says that there are %u.\n", t->tnum,
958 (uint32_t)t->a_sfreq, u);
959 if (t->a_sfreq == 0.0)
960 t->a_sfreq = (float)u;
961 }
962
963 u = get_uint16(&wfe->nChannels);
964 if (t->a_channels != u) {
965 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] WARNING: (MS "
966 "compatibility mode for track %u) "
967 "Matroska says that there are %u channels, but the "
968 "WAVEFORMATEX says that there are %u.\n", t->tnum,
969 t->a_channels, u);
970 if (t->a_channels == 0)
971 t->a_channels = u;
972 }
973
974 u = get_uint16(&wfe->wBitsPerSample);
975 if (t->a_bps != u) {
976 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] WARNING: (MS "
977 "compatibility mode for track %u) "
978 "Matroska says that there are %u bits per sample, "
979 "but the WAVEFORMATEX says that there are %u.\n", t->tnum,
980 t->a_bps, u);
981 if (t->a_bps == 0)
982 t->a_bps = u;
983 }
984
985 t->a_formattag = get_uint16(&wfe->wFormatTag);
986 }
987 } else {
988 if (!strcmp(t->codec_id, MKV_A_MP3) ||
989 !strcmp(t->codec_id, MKV_A_MP2))
990 t->a_formattag = 0x0055;
991 else if (!strncmp(t->codec_id, MKV_A_AC3, strlen(MKV_A_AC3)))
992 t->a_formattag = 0x2000;
993 else if (!strcmp(t->codec_id, MKV_A_DTS))
994 // uses same format tag as AC3, only supported with -hwac3
995 t->a_formattag = 0x2000;
996 else if (!strcmp(t->codec_id, MKV_A_PCM) ||
997 !strcmp(t->codec_id, MKV_A_PCM_BE))
998 t->a_formattag = 0x0001;
999 else if (!strcmp(t->codec_id, MKV_A_AAC_2MAIN) ||
1000 !strncmp(t->codec_id, MKV_A_AAC_2LC,
1001 strlen(MKV_A_AAC_2LC)) ||
1002 !strcmp(t->codec_id, MKV_A_AAC_2SSR) ||
1003 !strcmp(t->codec_id, MKV_A_AAC_4MAIN) ||
1004 !strncmp(t->codec_id, MKV_A_AAC_4LC,
1005 strlen(MKV_A_AAC_4LC)) ||
1006 !strcmp(t->codec_id, MKV_A_AAC_4SSR) ||
1007 !strcmp(t->codec_id, MKV_A_AAC_4LTP))
1008 t->a_formattag = mmioFOURCC('M', 'P', '4', 'A');
1009 else if (!strcmp(t->codec_id, MKV_A_VORBIS)) {
1010 if (t->private_data == NULL) {
1011 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] WARNING: CodecID for "
1012 "track %u is '" MKV_A_VORBIS
1013 "', but there are no header packets present.", t->tnum);
1014 continue;
1015 }
1016
1017 c = (unsigned char *)t->private_data;
1018 if (c[0] != 2) {
1019 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] Vorbis track does not "
1020 "contain valid headers.\n");
1021 continue;
1022 }
1023
1024 offset = 1;
1025 for (i = 0; i < 2; i++) {
1026 length = 0;
1027 while ((c[offset] == (unsigned char )255) &&
1028 (length < t->private_size)) {
1029 length += 255;
1030 offset++;
1031 }
1032 if (offset >= (t->private_size - 1)) {
1033 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] Vorbis track does not "
1034 "contain valid headers.\n");
1035 continue;
1036 }
1037 length += c[offset];
1038 offset++;
1039 t->header_sizes[i] = length;
1040 }
1041
1042 t->headers[0] = &c[offset];
1043 t->headers[1] = &c[offset + t->header_sizes[0]];
1044 t->headers[2] = &c[offset + t->header_sizes[0] +
1045 t->header_sizes[1]];
1046 t->header_sizes[2] = t->private_size - offset -
1047 t->header_sizes[0] - t->header_sizes[1];
1048
1049 t->a_formattag = 0xFFFE;
1050 } else if (!strcmp(t->codec_id, MKV_A_QDMC) ||
1051 !strcmp(t->codec_id, MKV_A_QDMC2)) {
1052 ;
1053 } else if (!strcmp(t->codec_id, MKV_A_FLAC)) {
1054 if ((t->private_data == NULL) || (t->private_size == 0)) {
1055 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] FLAC track does not "
1056 "contain valid headers.\n");
1057 continue;
1058 }
1059 t->a_formattag = mmioFOURCC('f', 'L', 'a', 'C');
1060 } else if (t->private_size >= sizeof(real_audio_v4_props_t)) {
1061 if (!strcmp(t->codec_id, MKV_A_REAL28))
1062 t->a_formattag = mmioFOURCC('2', '8', '_', '8');
1063 else if (!strcmp(t->codec_id, MKV_A_REALATRC))
1064 t->a_formattag = mmioFOURCC('a', 't', 'r', 'c');
1065 else if (!strcmp(t->codec_id, MKV_A_REALCOOK))
1066 t->a_formattag = mmioFOURCC('c', 'o', 'o', 'k');
1067 else if (!strcmp(t->codec_id, MKV_A_REALDNET))
1068 t->a_formattag = mmioFOURCC('d', 'n', 'e', 't');
1069 else if (!strcmp(t->codec_id, MKV_A_REALSIPR))
1070 t->a_formattag = mmioFOURCC('s', 'i', 'p', 'r');
1071 } else {
1072 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] Unknown/unsupported audio "
1073 "codec ID '%s' for track %u or missing/faulty private "
1074 "codec data.\n", t->codec_id, t->tnum);
1075 continue;
1076 }
1077 }
1078
1079 if (t->a_sfreq == 0.0) {
1080 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] The sampling frequency was not "
1081 "set for track %u.\n", t->tnum);
1082 continue;
1083 }
1084
1085 if (t->a_channels == 0) {
1086 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] The number of channels was not "
1087 "set for track %u.\n", t->tnum);
1088 continue;
1089 }
1090
1091 // This track seems to be ok.
1092 t->ok = 1;
1093 mp_msg(MSGT_DEMUX, MSGL_INFO, "[mkv] Track ID %u: audio (%s), -aid "
1094 "%u%s%s\n", t->tnum, t->codec_id, t->xid,
1095 t->language != NULL ? ", -alang " : "",
1096 t->language != NULL ? t->language : "");
1097 break;
1098
1099 case 's':
1100 if (!strcmp(t->codec_id, MKV_S_VOBSUB)) {
1101 if (mkv_parse_idx(t)) {
1102 t->ok = 1;
1103 mp_msg(MSGT_DEMUX, MSGL_INFO, "[mkv] Track ID %u: subtitles (%s), "
1104 "-sid %u%s%s\n", t->tnum, t->codec_id,
1105 t->xid, t->language != NULL ? ", -slang " : "",
1106 t->language != NULL ? t->language : "");
1107 }
1108
1109 } else { // Text subtitles do not need any data
1110 t->ok = 1; // except the CodecID.
1111 mp_msg(MSGT_DEMUX, MSGL_INFO, "[mkv] Track ID %u: subtitles (%s), "
1112 "-sid %u%s%s\n", t->tnum, t->codec_id, t->xid,
1113 t->language != NULL ? ", -slang " : "",
1114 t->language != NULL ? t->language : "");
1115 }
1116 break;
1117
1118 default: // unknown track type!? error in demuxer...
1119 mp_msg(MSGT_DEMUX, MSGL_ERR, "[mkv] Error in demux_mkv.cpp: unknown "
1120 "demuxer type for track %u: '%c'\n", t->tnum, t->type);
1121 continue;
1122 }
1123
1124 if (t->ok)
1125 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] Track %u seems to be ok.\n", t->tnum);
1126 }
1127
1128 return 1;
1129 }
1130
1131 static void free_mkv_demuxer(mkv_demuxer_t *d) {
1132 int i, k;
1133
1134 if (d == NULL)
1135 return;
1136
1137 for (i = 0; i < d->num_tracks; i++)
1138 if (d->tracks[i] != NULL) {
1139 if (d->tracks[i]->private_data != NULL)
1140 free(d->tracks[i]->private_data);
1141 if (d->tracks[i]->language != NULL)
1142 free(d->tracks[i]->language);
1143 for (k = 0; k < (int)d->tracks[i]->c_encodings->size(); k++) {
1144 safefree((*d->tracks[i]->c_encodings)[k].comp_settings);
1145 safefree((*d->tracks[i]->c_encodings)[k].enc_keyid);
1146 safefree((*d->tracks[i]->c_encodings)[k].sig_keyid);
1147 safefree((*d->tracks[i]->c_encodings)[k].signature);
1148 }
1149 delete d->tracks[i]->c_encodings;
1150 free(d->tracks[i]);
1151 }
1152
1153 for (i = 0; i < d->num_indexes; i++)
1154 free(d->index[i].entries);
1155 free(d->index);
1156
1157 for (i = 0; i <= SUB_MAX_TEXT; i++)
1158 safefree(d->subs.text[i]);
1159
1160 if (d->es != NULL)
1161 delete d->es;
1162 if (d->saved_l1 != NULL)
1163 delete d->saved_l1;
1164 if (d->in != NULL)
1165 delete d->in;
1166 if (d->segment != NULL)
1167 delete d->segment;
1168 if (d->chapters != NULL)
1169 delete d->chapters;
1170
1171 free(d);
1172 }
1173
1174 static void add_index_entry(mkv_demuxer_t *d, uint32_t tnum, uint64_t filepos,
1175 uint64_t timecode, int is_key) {
1176 int i, found;
1177 mkv_index_entry_t *entry;
1178
1179 for (i = 0, found = 0; i < d->num_indexes; i++)
1180 if (d->index[i].tnum == tnum) {
1181 found = 1;
1182 break;
1183 }
1184
1185 if (!found) {
1186 d->index = (mkv_track_index_t *)realloc(d->index, (d->num_indexes + 1) *
1187 sizeof(mkv_track_index_t));
1188 if (d->index == NULL)
1189 return;
1190 i = d->num_indexes;
1191 memset(&d->index[i], 0, sizeof(mkv_track_index_t));
1192 d->index[i].tnum = tnum;
1193 d->num_indexes++;
1194 }
1195
1196 d->index[i].entries =
1197 (mkv_index_entry_t *)realloc(d->index[i].entries,
1198 (d->index[i].num_entries + 1) *
1199 sizeof(mkv_index_entry_t));
1200 if (d->index[i].entries == NULL)
1201 return;
1202 entry = &d->index[i].entries[d->index[i].num_entries];
1203 entry->filepos = filepos;
1204 entry->timecode = timecode;
1205 entry->is_key = is_key;
1206 d->index[i].num_entries++;
1207 }
1208
1209 static void add_cluster_position(mkv_demuxer_t *mkv_d, int64_t position) {
1210 mkv_d->cluster_positions = (int64_t *)realloc(mkv_d->cluster_positions,
1211 (mkv_d->num_cluster_pos + 1) *
1212 sizeof(int64_t));
1213 if (mkv_d->cluster_positions != NULL) {
1214 mkv_d->cluster_positions[mkv_d->num_cluster_pos] = position;
1215 mkv_d->num_cluster_pos++;
1216 } else
1217 mkv_d->num_cluster_pos = 0;
1218 }
1219
1220 static int find_in_vector(vector<uint64_t> &vec, uint64_t value) {
1221 unsigned int i;
1222
1223 for (i = 0; i < vec.size(); i++)
1224 if (vec[i] == value)
1225 return 1;
1226
1227 return 0;
1228 }
1229
1230 #define in_parent(p) (mkv_d->in->getFilePointer() < \
1231 (p->GetElementPosition() + p->ElementSize()))
1232 #define FINDFIRST(p, c) (static_cast<c *> \
1233 (((EbmlMaster *)p)->FindFirstElt(c::ClassInfos, false)))
1234 #define FINDNEXT(p, c, e) (static_cast<c *> \
1235 (((EbmlMaster *)p)->FindNextElt(*e, false)))
1236
1237 static void parse_cues(mkv_demuxer_t *mkv_d, uint64_t pos) {
1238 EbmlElement *l2 = NULL;
1239 EbmlStream *es;
1240 KaxCues *cues;
1241 KaxCuePoint *cpoint;
1242 KaxCueTime *ctime;
1243 KaxCueClusterPosition *ccpos;
1244 KaxCueTrack *ctrack;
1245 KaxCueTrackPositions *ctrackpos;
1246 int upper_lvl_el, i, k;
1247 uint64_t tc_scale, filepos = 0, timecode = 0;
1248 uint32_t tnum = 0;
1249 mkv_index_entry_t *entry;
1250
1251 if (find_in_vector(*mkv_d->parsed_cues, pos))
1252 return;
1253
1254 mkv_d->parsed_cues->push_back(pos);
1255
1256 mkv_d->in->setFilePointer(pos);
1257
1258 es = mkv_d->es;
1259 tc_scale = mkv_d->tc_scale;
1260 upper_lvl_el = 0;
1261
1262 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] /---- [ parsing cues ] -----------\n");
1263
1264 cues = (KaxCues *)es->FindNextElement(mkv_d->segment->Generic().Context,
1265 upper_lvl_el, 0xFFFFFFFFL, true, 1);
1266 if (cues == NULL)
1267 return;
1268
1269 if (!(EbmlId(*cues) == KaxCues::ClassInfos.GlobalId)) {
1270 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] No KaxCues element found but %s.\n"
1271 "[mkv] \\---- [ parsing cues ] -----------\n",
1272 cues->Generic().DebugName);
1273
1274 return;
1275 }
1276
1277 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] |+ found cues\n");
1278
1279 cues->Read(*es, KaxCues::ClassInfos.Context, upper_lvl_el, l2, true);
1280
1281 cpoint = FINDFIRST(cues, KaxCuePoint);
1282
1283 while (cpoint != NULL) {
1284 mp_msg(MSGT_DEMUX, MSGL_DBG2, "[mkv] | + found cue point\n");
1285
1286 ctime = FINDFIRST(cpoint, KaxCueTime);
1287 if (ctime == NULL) {
1288 cpoint = FINDNEXT(cues, KaxCuePoint, cpoint);
1289 continue;
1290 }
1291
1292 timecode = uint64(*ctime) * tc_scale / 1000000 - mkv_d->first_tc;
1293 mp_msg(MSGT_DEMUX, MSGL_DBG2, "[mkv] | + found cue time: %.3fs\n",
1294 (float)timecode / 1000.0);
1295
1296 ctrackpos = FINDFIRST(cpoint, KaxCueTrackPositions);
1297
1298 while (ctrackpos != NULL) {
1299 ctrack = FINDFIRST(ctrackpos, KaxCueTrack);
1300
1301 if (ctrack == NULL) {
1302 ctrackpos = FINDNEXT(cpoint, KaxCueTrackPositions, ctrackpos);
1303 continue;
1304 }
1305
1306 tnum = uint32(*ctrack);
1307 mp_msg(MSGT_DEMUX, MSGL_DBG2, "[mkv] | + found cue track: %u\n", tnum);
1308
1309 ccpos = FINDFIRST(ctrackpos, KaxCueClusterPosition);
1310 if (ccpos == NULL) {
1311 ctrackpos = FINDNEXT(cpoint, KaxCueTrackPositions, ctrackpos);
1312 continue;
1313 }
1314
1315 filepos = mkv_d->segment->GetGlobalPosition(uint64_t(*ccpos));
1316 mp_msg(MSGT_DEMUX, MSGL_DBG2, "[mkv] | + found cue cluster "
1317 "position: %llu\n", filepos);
1318
1319 add_index_entry(mkv_d, tnum, filepos, timecode, 1);
1320
1321 ctrackpos = FINDNEXT(cpoint, KaxCueTrackPositions, ctrackpos);
1322 }
1323
1324 cpoint = FINDNEXT(cues, KaxCuePoint, cpoint);
1325 }
1326
1327 delete cues;
1328
1329 // Debug: dump the index
1330 for (i = 0; i < mkv_d->num_indexes; i++) {
1331 mp_msg(MSGT_DEMUX, MSGL_DBG2, "[mkv] Index for track %u contains %u "
1332 "entries.\n", mkv_d->index[i].tnum, mkv_d->index[i].num_entries);
1333 for (k = 0; k < mkv_d->index[i].num_entries; k++) {
1334 entry = &mkv_d->index[i].entries[k];
1335 mp_msg(MSGT_DEMUX, MSGL_DBG2, "[mkv] %d: timecode %llu, filepos %llu, "
1336 "is key: %s\n", k, entry->timecode, entry->filepos,
1337 entry->is_key ? "yes" : "no");
1338 }
1339 }
1340
1341 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] \\---- [ parsing cues ] -----------\n");
1342
1343 mkv_d->cues_found = 1;
1344 }
1345
1346 static void parse_chapters(mkv_demuxer_t *mkv_d, uint64_t pos) {
1347 EbmlElement *l2 = NULL;
1348 EbmlStream *es;
1349 KaxChapters *kchapters;
1350 KaxEditionEntry *keentry;
1351 KaxChapterAtom *kcatom;
1352 KaxChapterTimeStart *kctstart;
1353 KaxChapterTimeEnd *kctend;
1354 int upper_lvl_el, i, k;
1355 mkv_chapter_t chapter;
1356
1357 if (mkv_d->chapters != NULL)
1358 return;
1359
1360 es = mkv_d->es;
1361 upper_lvl_el = 0;
1362
1363 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] /---- [ parsing chapters ] ---------\n");
1364
1365 mkv_d->in->setFilePointer(pos);
1366
1367 kchapters =
1368 (KaxChapters *)es->FindNextElement(mkv_d->segment->Generic().Context,
1369 upper_lvl_el, 0xFFFFFFFFL, true, 1);
1370 if (kchapters == NULL)
1371 return;
1372
1373 if (!(EbmlId(*kchapters) == KaxChapters::ClassInfos.GlobalId)) {
1374 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] No KaxChapters element found but %s.\n"
1375 "[mkv] \\---- [ parsing chapters ] ---------\n",
1376 kchapters->Generic().DebugName);
1377
1378 return;
1379 }
1380
1381 mkv_d->chapters = new vector<mkv_chapter_t>;
1382 kchapters->Read(*es, KaxChapters::ClassInfos.Context, upper_lvl_el, l2,
1383 true);
1384
1385 for (i = 0; i < (int)kchapters->ListSize(); i++) {
1386 keentry = (KaxEditionEntry *)(*kchapters)[i];
1387 if (EbmlId(*keentry) == KaxEditionEntry::ClassInfos.GlobalId) {
1388 for (k = 0; k < (int)keentry->ListSize(); k++) {
1389 kcatom = (KaxChapterAtom *)(*keentry)[k];
1390 if (EbmlId(*kcatom) == KaxChapterAtom::ClassInfos.GlobalId) {
1391 chapter.start = 0;
1392 chapter.end = 0;
1393 kctstart = FINDFIRST(kcatom, KaxChapterTimeStart);
1394 if (kctstart != NULL)
1395 chapter.start = uint64(*kctstart) / 1000000;
1396 kctend = FINDFIRST(kcatom, KaxChapterTimeEnd);
1397 if (kctend != NULL)
1398 chapter.end = uint64(*kctend) / 1000000;
1399 mkv_d->chapters->push_back(chapter);
1400 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] Chapter %u from %02d:%02d:%02d."
1401 "%03d to %02d:%02d:%02d.%03d\n", mkv_d->chapters->size(),
1402 (int)(chapter.start / 60 / 60 / 1000),
1403 (int)((chapter.start / 60 / 1000) % 60),
1404 (int)((chapter.start / 1000) % 60),
1405 (int)(chapter.start % 1000),
1406 (int)(chapter.end / 60 / 60 / 1000),
1407 (int)((chapter.end / 60 / 1000) % 60),
1408 (int)((chapter.end / 1000) % 60),
1409 (int)(chapter.end % 1000));
1410 }
1411 }
1412 }
1413 }
1414
1415 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] \\---- [ parsing chapters ] ---------\n");
1416 delete kchapters;
1417 }
1418
1419 static void parse_seekhead(mkv_demuxer_t *mkv_d, uint64_t pos) {
1420 EbmlElement *l2 = NULL;
1421 EbmlStream *es;
1422 KaxSeekHead *kseekhead;
1423 KaxSeek *kseek;
1424 KaxSeekID *ksid;
1425 KaxSeekPosition *kspos;
1426 int upper_lvl_el, i, k, s;
1427 uint64_t seek_pos;
1428 EbmlId *id;
1429 EbmlElement *e;
1430 binary *b;
1431
1432 if (find_in_vector(*mkv_d->parsed_seekheads, pos))
1433 return;
1434
1435 mkv_d->parsed_seekheads->push_back(pos);
1436
1437 es = mkv_d->es;
1438 upper_lvl_el = 0;
1439
1440 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] /---- [ parsing seek head ] ---------\n");
1441
1442 mkv_d->in->setFilePointer(pos);
1443
1444 kseekhead =
1445 (KaxSeekHead *)es->FindNextElement(mkv_d->segment->Generic().Context,
1446 upper_lvl_el, 0xFFFFFFFFL, true, 1);
1447 if (kseekhead == NULL)
1448 return;
1449
1450 if (!(EbmlId(*kseekhead) == KaxSeekHead::ClassInfos.GlobalId)) {
1451 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] No KaxSeekead element found but %s.\n"
1452 "[mkv] \\---- [ parsing seek head ] ---------\n",
1453 kseekhead->Generic().DebugName);
1454
1455 return;
1456 }
1457
1458 kseekhead->Read(*es, KaxSeekHead::ClassInfos.Context, upper_lvl_el, l2,
1459 true);
1460
1461 for (i = 0; i < (int)kseekhead->ListSize(); i++) {
1462 kseek = (KaxSeek *)(*kseekhead)[i];
1463 if (!(EbmlId(*kseek) == KaxSeek::ClassInfos.GlobalId))
1464 continue;
1465
1466 seek_pos = 0;
1467 id = NULL;
1468
1469 for (k = 0; k < (int)kseek->ListSize(); k++) {
1470 e = (*kseek)[k];
1471
1472 if (EbmlId(*e) == KaxSeekID::ClassInfos.GlobalId) {
1473 ksid = (KaxSeekID *)e;
1474
1475 b = ksid->GetBuffer();
1476 s = ksid->GetSize();
1477 if (id != NULL)
1478 delete id;
1479 id = new EbmlId(b, s);
1480
1481 } else if (EbmlId(*e) == KaxSeekPosition::ClassInfos.GlobalId) {
1482 kspos = (KaxSeekPosition *)e;
1483 seek_pos = mkv_d->segment->GetGlobalPosition(uint64(*kspos));
1484
1485 }
1486 }
1487
1488 if ((seek_pos != 0) && (id != NULL)) {
1489 if (*id == KaxSeekHead::ClassInfos.GlobalId)
1490 parse_seekhead(mkv_d, seek_pos);
1491 else if (*id == KaxCues::ClassInfos.GlobalId)
1492 parse_cues(mkv_d, seek_pos);
1493 else if (*id == KaxChapters::ClassInfos.GlobalId)
1494 parse_chapters(mkv_d, seek_pos);
1495 }
1496
1497 if (id != NULL)
1498 delete id;
1499 }
1500
1501 delete kseekhead;
1502
1503 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] \\---- [ parsing seek head ] ---------\n");
1504 }
1505
1506 #define AAC_SYNC_EXTENSION_TYPE 0x02b7
1507 static int aac_get_sample_rate_index(uint32_t sample_rate) {
1508 if (92017 <= sample_rate)
1509 return 0;
1510 else if (75132 <= sample_rate)
1511 return 1;
1512 else if (55426 <= sample_rate)
1513 return 2;
1514 else if (46009 <= sample_rate)
1515 return 3;
1516 else if (37566 <= sample_rate)
1517 return 4;
1518 else if (27713 <= sample_rate)
1519 return 5;
1520 else if (23004 <= sample_rate)
1521 return 6;
1522 else if (18783 <= sample_rate)
1523 return 7;
1524 else if (13856 <= sample_rate)
1525 return 8;
1526 else if (11502 <= sample_rate)
1527 return 9;
1528 else if (9391 <= sample_rate)
1529 return 10;
1530 else
1531 return 11;
1532 }
1533
1534 extern "C" void demux_mkv_seek(demuxer_t *demuxer, float rel_seek_secs,
1535 int flags);
1536
1537 extern "C" int demux_mkv_open(demuxer_t *demuxer) {
1538 unsigned char signature[4];
1539 stream_t *s;
1540 demux_packet_t *dp;
1541 mkv_demuxer_t *mkv_d;
1542 int upper_lvl_el, exit_loop, i, vid, sid, aid;
1543 // Elements for different levels
1544 EbmlElement *l0 = NULL, *l1 = NULL, *l2 = NULL;
1545 EbmlStream *es;
1546 mkv_track_t *track;
1547 sh_audio_t *sh_a;
1548 sh_video_t *sh_v;
1549 vector<uint64_t> seekheads_to_parse;
1550 vector<uint64_t> cues_to_parse;
1551 int64_t current_pos;
1552 qt_image_description_t *idesc;
1553
1554 #ifdef USE_ICONV
1555 subcp_open();
1556 #endif
1557
1558 s = demuxer->stream;
1559 stream_seek(s, s->start_pos);
1560 memset(signature, 0, 4);
1561 stream_read(s, (char *)signature, 4);
1562 if ((signature[0] != 0x1A) || (signature[1] != 0x45) ||
1563 (signature[2] != 0xDF) || (signature[3] != 0xA3))
1564 return 0;
1565 stream_seek(s, s->start_pos);
1566
1567 try {
1568 // structure for storing the demuxer's private data
1569 mkv_d = (mkv_demuxer_t *)safemalloc(sizeof(mkv_demuxer_t));
1570 memset(mkv_d, 0, sizeof(mkv_demuxer_t));
1571 mkv_d->duration = -1.0;
1572
1573 // Create the interface between MPlayer's IO system and
1574 // libmatroska's IO system.
1575 mkv_d->in = new mpstream_io_callback(demuxer->stream);
1576 if (mkv_d->in == NULL) {
1577 free_mkv_demuxer(mkv_d);
1578 return 0;
1579 }
1580 mpstream_io_callback &io = *static_cast<mpstream_io_callback *>(mkv_d->in);
1581 mkv_d->es = new EbmlStream(io);
1582 if (mkv_d->es == NULL) {
1583 free_mkv_demuxer(mkv_d);
1584 return 0;
1585 }
1586 es = mkv_d->es;
1587
1588 // Find the EbmlHead element. Must be the first one.
1589 l0 = es->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFFFFFFFFFULL);
1590 if (l0 == NULL) {
1591 mp_msg(MSGT_DEMUX, MSGL_ERR, "[mkv] no head found\n");
1592 free_mkv_demuxer(mkv_d);
1593 return 0;
1594 }
1595 // Don't verify its data for now.
1596 l0->SkipData(static_cast<EbmlStream &>(*es), l0->Generic().Context);
1597 delete l0;
1598 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] Found the head...\n");
1599
1600 // Next element must be a segment
1601 l0 = es->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFFFFFFFFFULL);
1602 if (l0 == NULL) {
1603 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] but no segment :(\n");
1604 free_mkv_demuxer(mkv_d);
1605 return 0;
1606 }
1607 if (!(EbmlId(*l0) == KaxSegment::ClassInfos.GlobalId)) {
1608 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] but no segment :(\n");
1609 free_mkv_demuxer(mkv_d);
1610 return 0;
1611 }
1612 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] + a segment...\n");
1613
1614 mkv_d->segment = (KaxSegment *)l0;
1615 mkv_d->tc_scale = MKVD_TIMECODESCALE;
1616 mkv_d->parsed_seekheads = new vector<uint64_t>;
1617 mkv_d->parsed_cues = new vector<uint64_t>;
1618
1619 vid = 0;
1620 aid = 0;
1621 sid = 0;
1622
1623 upper_lvl_el = 0;
1624 exit_loop = 0;
1625 // We've got our segment, so let's find the tracks
1626 l1 = es->FindNextElement(l0->Generic().Context, upper_lvl_el, 0xFFFFFFFFL,
1627 true, 1);
1628 while ((l1 != NULL) && (upper_lvl_el <= 0)) {
1629
1630 if (EbmlId(*l1) == KaxInfo::ClassInfos.GlobalId) {
1631 // General info about this Matroska file
1632 KaxTimecodeScale *ktc_scale;
1633 KaxDuration *kduration;
1634
1635 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] |+ segment information...\n");
1636
1637 l1->Read(*es, KaxInfo::ClassInfos.Context, upper_lvl_el, l2, true);
1638
1639 ktc_scale = FINDFIRST(l1, KaxTimecodeScale);
1640 if (ktc_scale != NULL) {
1641 mkv_d->tc_scale = uint64(*ktc_scale);
1642 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + timecode scale: %llu\n",
1643 mkv_d->tc_scale);
1644 } else
1645 mkv_d->tc_scale = MKVD_TIMECODESCALE;
1646
1647 kduration = FINDFIRST(l1, KaxDuration);
1648 if (kduration != NULL) {
1649 mkv_d->duration = float(*kduration) * mkv_d->tc_scale / 1000000000.0;
1650 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + duration: %.3fs\n",
1651 mkv_d->duration);
1652 }
1653
1654 l1->SkipData(*es, l1->Generic().Context);
1655
1656 } else if (EbmlId(*l1) == KaxTracks::ClassInfos.GlobalId) {
1657 // Yep, we've found our KaxTracks element. Now find all tracks
1658 // contained in this segment.
1659
1660 KaxTrackEntry *ktentry;
1661
1662 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] |+ segment tracks...\n");
1663
1664 l1->Read(*es, KaxTracks::ClassInfos.Context, upper_lvl_el, l2, true);
1665
1666 ktentry = FINDFIRST(l1, KaxTrackEntry);
1667 while (ktentry != NULL) {
1668 // We actually found a track entry :) We're happy now.
1669
1670 KaxTrackNumber *ktnum;
1671 KaxTrackDefaultDuration *kdefdur;
1672 KaxTrackType *kttype;
1673 KaxTrackAudio *ktaudio;
1674 KaxTrackVideo *ktvideo;
1675 KaxCodecID *kcodecid;
1676 KaxCodecPrivate *kcodecpriv;
1677 KaxTrackFlagDefault *ktfdefault;
1678 KaxTrackLanguage *ktlanguage;
1679 #if LIBMATROSKA_VERSION >= 000503
1680 KaxContentEncodings *kcencodings;
1681 int kcenc_idx;
1682 vector<mkv_content_encoding_t>::iterator ce_ins_it;
1683 #endif
1684
1685 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + a track...\n");
1686
1687 track = new_mkv_track(mkv_d);
1688 if (track == NULL)
1689 return 0;
1690
1691 ktnum = FINDFIRST(ktentry, KaxTrackNumber);
1692 if (ktnum != NULL) {
1693 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Track number: %u\n",
1694 uint32(*ktnum));
1695 track->tnum = uint32(*ktnum);
1696 if (find_duplicate_track_by_num(mkv_d, track->tnum, track) != NULL)
1697 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] | + WARNING: There's "
1698 "more than one track with the number %u.\n",
1699 track->tnum);
1700 }
1701
1702 kdefdur = FINDFIRST(ktentry, KaxTrackDefaultDuration);
1703 if (kdefdur != NULL) {
1704 if (uint64(*kdefdur) == 0)
1705 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Default duration: 0");
1706 else {
1707 track->v_frate = 1000000000.0 / (float)uint64(*kdefdur);
1708 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Default duration: "
1709 "%.3fms ( = %.3f fps)\n",
1710 (float)uint64(*kdefdur) / 1000000.0, track->v_frate);
1711 }
1712 track->default_duration = (float)uint64(*kdefdur) / 1000000000.0;
1713 }
1714
1715 kttype = FINDFIRST(ktentry, KaxTrackType);
1716 if (kttype != NULL) {
1717 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Track type: ");
1718
1719 switch (uint8(*kttype)) {
1720 case track_audio:
1721 mp_msg(MSGT_DEMUX, MSGL_V, "Audio\n");
1722 track->type = 'a';
1723 track->xid = aid;
1724 aid++;
1725 break;
1726 case track_video:
1727 mp_msg(MSGT_DEMUX, MSGL_V, "Video\n");
1728 track->type = 'v';
1729 track->xid = vid;
1730 vid++;
1731 break;
1732 case track_subtitle:
1733 mp_msg(MSGT_DEMUX, MSGL_V, "Subtitle\n");
1734 track->type = 's';
1735 track->xid = sid;
1736 sid++;
1737 break;
1738 default:
1739 mp_msg(MSGT_DEMUX, MSGL_V, "unknown\n");
1740 track->type = '?';
1741 break;
1742 }
1743 }
1744
1745 ktaudio = FINDFIRST(ktentry, KaxTrackAudio);
1746 if (ktaudio != NULL) {
1747 KaxAudioSamplingFreq *ka_sfreq;
1748 KaxAudioChannels *ka_channels;
1749 KaxAudioBitDepth *ka_bitdepth;
1750
1751 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Audio track\n");
1752
1753 ka_sfreq = FINDFIRST(ktaudio, KaxAudioSamplingFreq);
1754 if (ka_sfreq != NULL) {
1755 track->a_sfreq = float(*ka_sfreq);
1756 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Sampling "
1757 "frequency: %f\n", track->a_sfreq);
1758 } else
1759 track->a_sfreq = 8000.0;
1760
1761 ka_channels = FINDFIRST(ktaudio, KaxAudioChannels);
1762 if (ka_channels != NULL) {
1763 track->a_channels = uint8(*ka_channels);
1764 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Channels: %u\n",
1765 track->a_channels);
1766 } else
1767 track->a_channels = 1;
1768
1769 ka_bitdepth = FINDFIRST(ktaudio, KaxAudioBitDepth);
1770 if (ka_bitdepth != NULL) {
1771 track->a_bps = uint8(*ka_bitdepth);
1772 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Bit depth: %u\n",
1773 track->a_bps);
1774 }
1775
1776 }
1777
1778 ktvideo = FINDFIRST(ktentry, KaxTrackVideo);
1779 if (ktvideo != NULL) {
1780 KaxVideoPixelWidth *kv_pwidth;
1781 KaxVideoPixelHeight *kv_pheight;
1782 KaxVideoDisplayWidth *kv_dwidth;
1783 KaxVideoDisplayHeight *kv_dheight;
1784 KaxVideoFrameRate *kv_frate;
1785
1786 kv_pwidth = FINDFIRST(ktvideo, KaxVideoPixelWidth);
1787 if (kv_pwidth != NULL) {
1788 track->v_width = uint16(*kv_pwidth);
1789 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Pixel width: %u\n",
1790 track->v_width);
1791 }
1792
1793 kv_pheight = FINDFIRST(ktvideo, KaxVideoPixelHeight);
1794 if (kv_pheight != NULL) {
1795 track->v_height = uint16(*kv_pheight);
1796 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Pixel height: %u\n",
1797 track->v_height);
1798 }
1799
1800 kv_dwidth = FINDFIRST(ktvideo, KaxVideoDisplayWidth);
1801 if (kv_dwidth != NULL) {
1802 track->v_dwidth = uint16(*kv_dwidth);
1803 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Display width: %u\n",
1804 track->v_dwidth);
1805 }
1806
1807 kv_dheight = FINDFIRST(ktvideo, KaxVideoDisplayHeight);
1808 if (kv_dheight != NULL) {
1809 track->v_dheight = uint16(*kv_dheight);
1810 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Display height: %u\n",
1811 track->v_dheight);
1812 }
1813
1814 // For older files.
1815 kv_frate = FINDFIRST(ktvideo, KaxVideoFrameRate);
1816 if (kv_frate != NULL) {
1817 track->v_frate = float(*kv_frate);
1818 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Frame rate: %f\n",
1819 track->v_frate);
1820 }
1821
1822 }
1823
1824 kcodecid = FINDFIRST(ktentry, KaxCodecID);
1825 if (kcodecid != NULL) {
1826 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Codec ID: %s\n",
1827 string(*kcodecid).c_str());
1828 track->codec_id = strdup(string(*kcodecid).c_str());
1829 }
1830
1831 kcodecpriv = FINDFIRST(ktentry, KaxCodecPrivate);
1832 if (kcodecpriv != NULL) {
1833 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + CodecPrivate, length "
1834 "%llu\n", kcodecpriv->GetSize());
1835 track->private_size = kcodecpriv->GetSize();
1836 if (track->private_size > 0)
1837 track->private_data = safememdup(kcodecpriv->GetBuffer(),
1838 track->private_size);
1839 }
1840
1841 ktfdefault = FINDFIRST(ktentry, KaxTrackFlagDefault);
1842 if (ktfdefault != NULL) {
1843 track->default_track = uint32(*ktfdefault);
1844 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Default flag: %u\n",
1845 track->default_track);
1846 }
1847
1848 ktlanguage = FINDFIRST(ktentry, KaxTrackLanguage);
1849 if (ktlanguage != NULL) {
1850 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] | + Language: %s\n",
1851 string(*ktlanguage).c_str());
1852 if (track->language != NULL)
1853 free(track->language);
1854 track->language = strdup(string(*ktlanguage).c_str());
1855 }
1856
1857 #if LIBMATROSKA_VERSION >= 000503
1858 kcencodings = FINDFIRST(ktentry, KaxContentEncodings);
1859 if (kcencodings != NULL) {
1860 for (kcenc_idx = 0; kcenc_idx < (int)kcencodings->ListSize();
1861 kcenc_idx++) {
1862 EbmlElement *l3;
1863
1864 l3 = (*kcencodings)[kcenc_idx];
1865 if (EbmlId(*l3) == KaxContentEncoding::ClassInfos.GlobalId) {
1866 KaxContentEncoding *kcenc;
1867 KaxContentEncodingOrder *ce_order;
1868 KaxContentEncodingType *ce_type;
1869 KaxContentEncodingScope *ce_scope;
1870 KaxContentCompression *ce_comp;
1871 KaxContentEncryption *ce_enc;
1872 mkv_content_encoding_t enc;
1873
1874 memset(&enc, 0, sizeof(mkv_content_encoding_t));
1875 kcenc = static_cast<KaxContentEncoding *>(l3);
1876
1877 ce_order = FINDFIRST(kcenc, KaxContentEncodingOrder);
1878 if (ce_order != NULL)
1879 enc.order = uint32(*ce_order);
1880
1881 ce_type = FINDFIRST(kcenc, KaxContentEncodingType);
1882 if (ce_type != NULL)
1883 enc.type = uint32(*ce_type);
1884
1885 ce_scope = FINDFIRST(kcenc, KaxContentEncodingScope);
1886 if (ce_scope != NULL)
1887 enc.scope = uint32(*ce_scope);
1888 else
1889 enc.scope = 1;
1890
1891 ce_comp = FINDFIRST(kcenc, KaxContentCompression);
1892 if (ce_comp != NULL) {
1893 KaxContentCompAlgo *cc_algo;
1894 KaxContentCompSettings *cc_settings;
1895
1896 cc_algo = FINDFIRST(ce_comp, KaxContentCompAlgo);
1897 if (cc_algo != NULL)
1898 enc.comp_algo = uint32(*cc_algo);
1899
1900 cc_settings = FINDFIRST(ce_comp, KaxContentCompSettings);
1901 if (cc_settings != NULL) {
1902 enc.comp_settings =
1903 (unsigned char *)safememdup(&binary(*cc_settings),
1904 cc_settings->GetSize());
1905 enc.comp_settings_len = cc_settings->GetSize();
1906 }
1907 }
1908
1909 ce_enc = FINDFIRST(kcenc, KaxContentEncryption);
1910 if (ce_enc != NULL) {
1911 KaxContentEncAlgo *ce_ealgo;
1912 KaxContentEncKeyID *ce_ekeyid;
1913 KaxContentSigAlgo *ce_salgo;
1914 KaxContentSigHashAlgo *ce_shalgo;
1915 KaxContentSigKeyID *ce_skeyid;
1916 KaxContentSignature *ce_signature;
1917
1918 ce_ealgo = FINDFIRST(ce_enc, KaxContentEncAlgo);
1919 if (ce_ealgo != NULL)
1920 enc.enc_algo = uint32(*ce_ealgo);
1921
1922 ce_ekeyid = FINDFIRST(ce_enc, KaxContentEncKeyID);
1923 if (ce_ekeyid != NULL) {
1924 enc.enc_keyid =
1925 (unsigned char *)safememdup(&binary(*ce_ekeyid),
1926 ce_ekeyid->GetSize());
1927 enc.enc_keyid_len = ce_ekeyid->GetSize();
1928 }
1929
1930 ce_salgo = FINDFIRST(ce_enc, KaxContentSigAlgo);
1931 if (ce_salgo != NULL)
1932 enc.enc_algo = uint32(*ce_salgo);
1933
1934 ce_shalgo = FINDFIRST(ce_enc, KaxContentSigHashAlgo);
1935 if (ce_shalgo != NULL)
1936 enc.enc_algo = uint32(*ce_shalgo);
1937
1938 ce_skeyid = FINDFIRST(ce_enc, KaxContentSigKeyID);
1939 if (ce_skeyid != NULL) {
1940 enc.sig_keyid =
1941 (unsigned char *)safememdup(&binary(*ce_skeyid),
1942 ce_skeyid->GetSize());
1943 enc.sig_keyid_len = ce_skeyid->GetSize();
1944 }
1945
1946 ce_signature = FINDFIRST(ce_enc, KaxContentSignature);
1947 if (ce_signature != NULL) {
1948 enc.signature =
1949 (unsigned char *)safememdup(&binary(*ce_signature),
1950 ce_signature->GetSize());
1951 enc.signature_len = ce_signature->GetSize();
1952 }
1953
1954 }
1955
1956 ce_ins_it = track->c_encodings->begin();
1957 while ((ce_ins_it != track->c_encodings->end()) &&
1958 (enc.order <= (*ce_ins_it).order))
1959 ce_ins_it++;
1960 track->c_encodings->insert(ce_ins_it, enc);
1961 }
1962 }
1963 }
1964
1965 #endif
1966 ktentry = FINDNEXT(l1, KaxTrackEntry, ktentry);
1967 } // while (ktentry != NULL)
1968
1969 l1->SkipData(*es, l1->Generic().Context);
1970
1971 } else if (EbmlId(*l1) == KaxSeekHead::ClassInfos.GlobalId) {
1972 if (!find_in_vector(seekheads_to_parse, l1->GetElementPosition()))
1973 seekheads_to_parse.push_back(l1->GetElementPosition());
1974 l1->SkipData(*es, l1->Generic().Context);
1975
1976 } else if ((EbmlId(*l1) == KaxCues::ClassInfos.GlobalId) &&
1977 !mkv_d->cues_found) {
1978 if (!find_in_vector(cues_to_parse, l1->GetElementPosition()))
1979 cues_to_parse.push_back(l1->GetElementPosition());
1980 l1->SkipData(*es, l1->Generic().Context);
1981
1982 } else if (EbmlId(*l1) == KaxChapters::ClassInfos.GlobalId) {
1983 parse_chapters(mkv_d, l1->GetElementPosition());
1984 l1->SkipData(*es, l1->Generic().Context);
1985
1986 } else if (EbmlId(*l1) == KaxCluster::ClassInfos.GlobalId) {
1987 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] |+ found cluster, headers are "
1988 "parsed completely :)\n");
1989 add_cluster_position(mkv_d, l1->GetElementPosition());
1990 mkv_d->saved_l1 = l1;
1991 exit_loop = 1;
1992
1993 } else
1994 l1->SkipData(*es, l1->Generic().Context);
1995
1996 if (!in_parent(l0)) {
1997 delete l1;
1998 break;
1999 }
2000
2001 if (upper_lvl_el > 0) {
2002 upper_lvl_el--;
2003 if (upper_lvl_el > 0)
2004 break;
2005 delete l1;
2006 l1 = l2;
2007 continue;
2008
2009 } else if (upper_lvl_el < 0) {
2010 upper_lvl_el++;
2011 if (upper_lvl_el < 0)
2012 break;
2013
2014 }
2015
2016 if (exit_loop) // we've found the first cluster, so get out
2017 break;
2018
2019 l1->SkipData(*es, l1->Generic().Context);
2020 delete l1;
2021 l1 = es->FindNextElement(l0->Generic().Context, upper_lvl_el,
2022 0xFFFFFFFFL, true);
2023
2024 } // while (l1 != NULL)
2025
2026 if (!exit_loop) {
2027 free_mkv_demuxer(mkv_d);
2028 return 0;
2029 }
2030
2031 current_pos = io.getFilePointer();
2032
2033 // Try to find the very first timecode (cluster timecode).
2034 l2 = es->FindNextElement(l1->Generic().Context, upper_lvl_el,
2035 0xFFFFFFFFL, true, 1);
2036 if ((l2 != NULL) && !upper_lvl_el &&
2037 (EbmlId(*l2) == KaxClusterTimecode::ClassInfos.GlobalId)) {
2038 KaxClusterTimecode &ctc = *static_cast<KaxClusterTimecode *>(l2);
2039 ctc.ReadData(es->I_O());
2040 mkv_d->first_tc = uint64(ctc) * mkv_d->tc_scale / 1000000;
2041 delete l2;
2042 } else
2043 mkv_d->first_tc = 0;
2044
2045 // Parse all cues and seek heads
2046 for (i = 0; i < (int)cues_to_parse.size(); i++)
2047 parse_cues(mkv_d, cues_to_parse[i]);
2048 for (i = 0; i < (int)seekheads_to_parse.size(); i++)
2049 parse_seekhead(mkv_d, seekheads_to_parse[i]);
2050
2051 io.setFilePointer(current_pos);
2052
2053 } catch (exception &ex) {
2054 mp_msg(MSGT_DEMUX, MSGL_ERR, "[mkv] caught exception\n");
2055 return 0;
2056 }
2057
2058 if (!check_track_information(mkv_d)) {
2059 free_mkv_demuxer(mkv_d);
2060 return 0;
2061 }
2062
2063 track = NULL;
2064 if (demuxer->video->id == -1) { // Automatically select a video track.
2065 // Search for a video track that has the 'default' flag set.
2066 for (i = 0; i < mkv_d->num_tracks; i++)
2067 if ((mkv_d->tracks[i]->type == 'v') && mkv_d->tracks[i]->ok &&
2068 mkv_d->tracks[i]->default_track) {
2069 track = mkv_d->tracks[i];
2070 break;
2071 }
2072
2073 if (track == NULL)
2074 // No track has the 'default' flag set - let's take the first video
2075 // track.
2076 for (i = 0; i < mkv_d->num_tracks; i++)
2077 if ((mkv_d->tracks[i]->type == 'v') && mkv_d->tracks[i]->ok) {
2078 track = mkv_d->tracks[i];
2079 break;
2080 }
2081 } else if (demuxer->video->id != -2) // -2 = no video at all
2082 track = find_track_by_num(mkv_d, demuxer->video->id, 'v');
2083
2084 if (track) {
2085 BITMAPINFOHEADER *bih;
2086
2087 idesc = NULL;
2088
2089 if (track->ms_compat) { // MS compatibility mode
2090 BITMAPINFOHEADER *src;
2091 src = (BITMAPINFOHEADER *)track->private_data;
2092 bih = (BITMAPINFOHEADER *)safemalloc(track->private_size);
2093 memset(bih, 0, track->private_size);
2094 bih->biSize = get_uint32(&src->biSize);
2095 bih->biWidth = get_uint32(&src->biWidth);
2096 bih->biHeight = get_uint32(&src->biHeight);
2097 bih->biPlanes = get_uint16(&src->biPlanes);
2098 bih->biBitCount = get_uint16(&src->biBitCount);
2099 bih->biCompression = get_uint32(&src->biCompression);
2100 bih->biSizeImage = get_uint32(&src->biSizeImage);
2101 bih->biXPelsPerMeter = get_uint32(&src->biXPelsPerMeter);
2102 bih->biYPelsPerMeter = get_uint32(&src->biYPelsPerMeter);
2103 bih->biClrUsed = get_uint32(&src->biClrUsed);
2104 bih->biClrImportant = get_uint32(&src->biClrImportant);
2105 memcpy((char *)bih + sizeof(BITMAPINFOHEADER),
2106 (char *)src + sizeof(BITMAPINFOHEADER),
2107 track->private_size - sizeof(BITMAPINFOHEADER));
2108
2109 } else {
2110 bih = (BITMAPINFOHEADER *)safemalloc(sizeof(BITMAPINFOHEADER));
2111 memset(bih, 0, sizeof(BITMAPINFOHEADER));
2112 bih->biSize = sizeof(BITMAPINFOHEADER);
2113 bih->biWidth = track->v_width;
2114 bih->biHeight = track->v_height;
2115 bih->biBitCount = 24;
2116 bih->biSizeImage = bih->biWidth * bih->biHeight * bih->biBitCount / 8;
2117
2118 if ((track->private_size >= sizeof(real_video_props_t)) &&
2119 (!strcmp(track->codec_id, MKV_V_REALV10) ||
2120 !strcmp(track->codec_id, MKV_V_REALV20) ||
2121 !strcmp(track->codec_id, MKV_V_REALV30) ||
2122 !strcmp(track->codec_id, MKV_V_REALV40))) {
2123 unsigned char *dst, *src;
2124 real_video_props_t *rvp;
2125 uint32_t type2;
2126
2127 rvp = (real_video_props_t *)track->private_data;
2128 src = (unsigned char *)(rvp + 1);
2129
2130 bih = (BITMAPINFOHEADER *)realloc(bih, sizeof(BITMAPINFOHEADER) + 12);
2131 bih->biSize = 48;
2132 bih->biPlanes = 1;
2133 type2 = get_uint32_be(&rvp->type2);
2134 if ((type2 == 0x10003000) || (type2 == 0x10003001))
2135 bih->biCompression = mmioFOURCC('R', 'V', '1', '3');
2136 else
2137 bih->biCompression = mmioFOURCC('R', 'V', track->codec_id[9], '0');
2138 dst = (unsigned char *)(bih + 1);
2139 ((unsigned int *)dst)[0] = get_uint32_be(&rvp->type1);
2140 ((unsigned int *)dst)[1] = type2;
2141
2142 if ((bih->biCompression <= 0x30335652) &&
2143 (type2 >= 0x20200002)) {
2144 // read secondary WxH for the cmsg24[] (see vd_realvid.c)
2145 ((unsigned short *)(bih + 1))[4] = 4 * (unsigned short)src[0];
2146 ((unsigned short *)(bih + 1))[5] = 4 * (unsigned short)src[1];
2147 } else
2148 memset(&dst[8], 0, 4);
2149 track->realmedia = true;
2150
2151 #if defined(USE_QTX_CODECS)
2152 } else if ((track->private_size >= sizeof(qt_image_description_t)) &&
2153 (!strcmp(track->codec_id, MKV_V_QUICKTIME))) {
2154 idesc = (qt_image_description_t *)track->private_data;
2155 idesc->id_size = get_uint32_be(&idesc->id_size);
2156 idesc->codec_type = get_uint32(&idesc->codec_type);
2157 idesc->version = get_uint16_be(&idesc->version);
2158 idesc->revision = get_uint16_be(&idesc->revision);
2159 idesc->vendor = get_uint32_be(&idesc->vendor);
2160 idesc->temporal_quality = get_uint32_be(&idesc->temporal_quality);
2161 idesc->spatial_quality = get_uint32_be(&idesc->spatial_quality);
2162 idesc->width = get_uint16_be(&idesc->width);
2163 idesc->height = get_uint16_be(&idesc->height);
2164 idesc->horizontal_resolution =
2165 get_uint32_be(&idesc->horizontal_resolution);
2166 idesc->vertical_resolution =
2167 get_uint32_be(&idesc->vertical_resolution);
2168 idesc->data_size = get_uint32_be(&idesc->data_size);
2169 idesc->frame_count = get_uint16_be(&idesc->frame_count);
2170 idesc->depth = get_uint16_be(&idesc->depth);
2171 idesc->color_table_id = get_uint16_be(&idesc->color_table_id);
2172 bih->biPlanes = 1;
2173 bih->biCompression = idesc->codec_type;
2174 #endif // defined(USE_QTX_CODECS)
2175
2176 } else {
2177 mp_msg(MSGT_DEMUX, MSGL_WARN, "[mkv] Unknown/unsupported CodecID "
2178 "(%s) or missing/bad CodecPrivate data (track %u).\n",
2179 track->codec_id, track->tnum);
2180 demuxer->video->id = -2;
2181 }
2182 }
2183
2184 if (demuxer->video->id != -2) {
2185 mp_msg(MSGT_DEMUX, MSGL_INFO, "[mkv] Will play video track %u\n",
2186 track->tnum);
2187
2188 sh_v = new_sh_video(demuxer, track->tnum);
2189 sh_v->bih = bih;
2190 sh_v->format = sh_v->bih->biCompression;
2191 if (track->v_frate == 0.0)
2192 track->v_frate = 25.0;
2193 sh_v->fps = track->v_frate;
2194 sh_v->frametime = 1 / track->v_frate;
2195 if (!track->realmedia) {
2196 sh_v->disp_w = track->v_width;
2197 sh_v->disp_h = track->v_height;
2198 sh_v->aspect = (float)track->v_dwidth / (float)track->v_dheight;
2199 } else {
2200 // vd_realvid.c will set aspect to disp_w/disp_h and rederive
2201 // disp_w and disp_h from the RealVideo stream contents returned
2202 // by the Real DLLs. If DisplayWidth/DisplayHeight was not set in
2203 // the Matroska file then it has already been set to PixelWidth/Height
2204 // by check_track_information.
2205 sh_v->disp_w = track->v_dwidth;
2206 sh_v->disp_h = track->v_dheight;
2207 }
2208 if (idesc != NULL)
2209 sh_v->ImageDesc = idesc;
2210 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] Aspect: %f\n", sh_v->aspect);
2211
2212 demuxer->video->id = track->tnum;
2213 demuxer->video->sh = sh_v;
2214 sh_v->ds = demuxer->video;
2215
2216 mkv_d->video = track;
2217 } else
2218 free(bih);
2219
2220 } else {
2221 mp_msg(MSGT_DEMUX, MSGL_INFO, "[mkv] No video track found/wanted.\n");
2222 demuxer->video->id = -2;
2223 }
2224
2225 track = NULL;
2226 if (demuxer->audio->id == -1) { // Automatically select an audio track.
2227 // check if the user specified an audio language
2228 if (audio_lang != NULL) {
2229 track = find_track_by_language(mkv_d, audio_lang, NULL, 'a');
2230 }
2231 if (track == NULL)
2232 // no audio language specified, or language not found
2233 // Search for an audio track that has the 'default' flag set.
2234 for (i = 0; i < mkv_d->num_tracks; i++)
2235 if ((mkv_d->tracks[i]->type == 'a') && mkv_d->tracks[i]->ok &&
2236 mkv_d->tracks[i]->default_track) {
2237 track = mkv_d->tracks[i];
2238 break;
2239 }
2240
2241 if (track == NULL)
2242 // No track has the 'default' flag set - let's take the first audio
2243 // track.
2244 for (i = 0; i < mkv_d->num_tracks; i++)
2245 if ((mkv_d->tracks[i]->type == 'a') && mkv_d->tracks[i]->ok) {
2246 track = mkv_d->tracks[i];
2247 break;
2248 }
2249 } else if (demuxer->audio->id != -2) // -2 = no audio at all
2250 track = find_track_by_num(mkv_d, demuxer->audio->id, 'a');
2251
2252 if (track) {
2253 mp_msg(MSGT_DEMUX, MSGL_INFO, "[mkv] Will play audio track %u\n",
2254 track->tnum);
2255 sh_a = new_sh_audio(demuxer, track->tnum);
2256
2257 demuxer->audio->id = track->tnum;
2258 demuxer->audio->sh = sh_a;
2259 sh_a->ds = demuxer->audio;
2260
2261 mkv_d->audio = track;
2262
2263 if (track->ms_compat)
2264 sh_a->wf = (WAVEFORMATEX *)safememdup(track->private_data,
2265 track->private_size);
2266 else {
2267 sh_a->wf = (WAVEFORMATEX *)safemalloc(sizeof(WAVEFORMATEX));
2268 memset(sh_a->wf, 0, sizeof(WAVEFORMATEX));
2269 }
2270 sh_a->format = track->a_formattag;
2271 sh_a->wf->wFormatTag = track->a_formattag;
2272 sh_a->channels = track->a_channels;
2273 sh_a->wf->nChannels = track->a_channels;
2274 sh_a->samplerate = (uint32_t)track->a_sfreq;
2275 sh_a->wf->nSamplesPerSec = (uint32_t)track->a_sfreq;
2276 sh_a->samplesize = track->a_bps / 8;
2277 if (!strcmp(track->codec_id, MKV_A_MP3) ||
2278 !strcmp(track->codec_id, MKV_A_MP2)) {
2279 sh_a->wf->nAvgBytesPerSec = 16000;
2280 sh_a->wf->nBlockAlign = 1152;
2281 sh_a->wf->wBitsPerSample = 0;
2282 sh_a->samplesize = 0;
2283
2284 } else if (!strncmp(track->codec_id, MKV_A_AC3, strlen(MKV_A_AC3))) {
2285 sh_a->wf->nAvgBytesPerSec = 16000;
2286 sh_a->wf->nBlockAlign = 1536;
2287 sh_a->wf->wBitsPerSample = 0;
2288 sh_a->samplesize = 0;
2289
2290 } else if (!strcmp(track->codec_id, MKV_A_PCM) ||
2291 !strcmp(track->codec_id, MKV_A_PCM_BE)) {
2292 sh_a->wf->nAvgBytesPerSec = sh_a->channels * sh_a->samplerate * 2;
2293 sh_a->wf->nBlockAlign = sh_a->wf->nAvgBytesPerSec;
2294 sh_a->wf->wBitsPerSample = track->a_bps;
2295 if (!strcmp(track->codec_id, MKV_A_PCM_BE))
2296 sh_a->format = mmioFOURCC('t', 'w', 'o', 's');
2297
2298 } else if (!strcmp(track->codec_id, MKV_A_QDMC) ||
2299 !strcmp(track->codec_id, MKV_A_QDMC2)) {
2300 sh_a->wf->wBitsPerSample = track->a_bps;
2301 sh_a->wf->nAvgBytesPerSec = 16000;
2302 sh_a->wf->nBlockAlign = 1486;
2303 track->fix_i_bps = true;
2304 track->qt_last_a_pts = 0.0;
2305 if (track->private_data != NULL) {
2306 sh_a->codecdata = (unsigned char *)safememdup(track->private_data,
2307 track->private_size);
2308 sh_a->codecdata_len = track->private_size;
2309 }
2310 if (!strcmp(track->codec_id, MKV_A_QDMC))
2311 sh_a->format = mmioFOURCC('Q', 'D', 'M', 'C');
2312 else
2313 sh_a->format = mmioFOURCC('Q', 'D', 'M', '2');
2314
2315 } else if (track->a_formattag == mmioFOURCC('M', 'P', '4', 'A')) {
2316 int profile, srate_idx;
2317
2318 sh_a->wf->nAvgBytesPerSec = 16000;
2319 sh_a->wf->nBlockAlign = 1024;
2320 sh_a->wf->wBitsPerSample = 0;
2321 sh_a->samplesize = 0;
2322
2323 // Recreate the 'private data' which faad2 uses in its initialization.
2324 srate_idx = aac_get_sample_rate_index(sh_a->samplerate);
2325 if (!strncmp(&track->codec_id[12], "MAIN", 4))
2326 profile = 0;
2327 else if (!strncmp(&track->codec_id[12], "LC", 2))
2328 profile = 1;
2329 else if (!strncmp(&track->codec_id[12], "SSR", 3))
2330 profile = 2;
2331 else
2332 profile = 3;
2333 sh_a->codecdata = (unsigned char *)safemalloc(5);
2334 sh_a->codecdata[0] = ((profile + 1) << 3) | ((srate_idx & 0xe) >> 1);
2335 sh_a->codecdata[1] = ((srate_idx & 0x1) << 7) |
2336 (track->a_channels << 3);
2337
2338 if (strstr(track->codec_id, "SBR") != NULL) {
2339 // HE-AAC (aka SBR AAC)
2340 sh_a->codecdata_len = 5;
2341
2342 sh_a->samplerate *= 2;
2343 sh_a->wf->nSamplesPerSec *= 2;
2344 srate_idx = aac_get_sample_rate_index(sh_a->samplerate);
2345 sh_a->codecdata[2] = AAC_SYNC_EXTENSION_TYPE >> 3;
2346 sh_a->codecdata[3] = ((AAC_SYNC_EXTENSION_TYPE & 0x07) << 5) | 5;
2347 sh_a->codecdata[4] = (1 << 7) | (srate_idx << 3);
2348 track->default_duration = 1024.0 / (float)(sh_a->samplerate / 2);
2349
2350 } else {
2351 sh_a->codecdata_len = 2;
2352 track->default_duration = 1024.0 / (float)sh_a->samplerate;
2353 }
2354
2355 } else if (!strcmp(track->codec_id, MKV_A_VORBIS)) {
2356 for (i = 0; i < 3; i++) {
2357 dp = new_demux_packet(track->header_sizes[i]);
2358 memcpy(dp->buffer, track->headers[i], track->header_sizes[i]);
2359 dp->pts = 0;
2360 dp->flags = 0;
2361 ds_add_packet(demuxer->audio, dp);
2362 }
2363
2364 } else if ((track->private_size >= sizeof(real_audio_v4_props_t)) &&
2365 !strncmp(track->codec_id, MKV_A_REALATRC, 7)) {
2366 // Common initialization for all RealAudio codecs
2367 real_audio_v4_props_t *ra4p;
2368 real_audio_v5_props_t *ra5p;
2369 unsigned char *src;
2370 int codecdata_length, version;
2371
2372 ra4p = (real_audio_v4_props_t *)track->private_data;
2373 ra5p = (real_audio_v5_props_t *)track->private_data;
2374
2375 sh_a->wf->wBitsPerSample = sh_a->samplesize * 8;
2376 sh_a->wf->nAvgBytesPerSec = 0; // FIXME !?
2377 sh_a->wf->nBlockAlign = get_uint16_be(&ra4p->frame_size);
2378
2379 version = get_uint16_be(&ra4p->version1);
2380
2381 if (version == 4) {
2382 src = (unsigned char *)(ra4p + 1);
2383 src += src[0] + 1;
2384 src += src[0] + 1;
2385 } else
2386 src = (unsigned char *)(ra5p + 1);
2387
2388 src += 3;
2389 if (version == 5)
2390 src++;
2391 codecdata_length = get_uint32_be(src);
2392 src += 4;
2393 sh_a->wf->cbSize = 10 + codecdata_length;
2394 sh_a->wf = (WAVEFORMATEX *)realloc(sh_a->wf, sizeof(WAVEFORMATEX) +
2395 sh_a->wf->cbSize);
2396 ((short *)(sh_a->wf + 1))[0] = get_uint16_be(&ra4p->sub_packet_size);
2397 ((short *)(sh_a->wf + 1))[1] = get_uint16_be(&ra4p->sub_packet_h);
2398 ((short *)(sh_a->wf + 1))[2] = get_uint16_be(&ra4p->flavor);
2399 ((short *)(sh_a->wf + 1))[3] = get_uint32_be(&ra4p->coded_frame_size);
2400 ((short *)(sh_a->wf + 1))[4] = codecdata_length;
2401 memcpy(((char *)(sh_a->wf + 1)) + 10, src, codecdata_length);
2402
2403 track->realmedia = true;
2404
2405 } else if (!strcmp(track->codec_id, MKV_A_FLAC) ||
2406 (track->a_formattag == 0xf1ac)) {
2407 unsigned char *ptr;
2408 int size;
2409 free(sh_a->wf);
2410 sh_a->wf = NULL;
2411
2412 if (track->a_formattag == mmioFOURCC('f', 'L', 'a', 'C')) {
2413 ptr = (unsigned char *)track->private_data;
2414 size = track->private_size;
2415 } else {
2416 sh_a->format = mmioFOURCC('f', 'L', 'a', 'C');
2417 ptr = (unsigned char *)track->private_data + sizeof(WAVEFORMATEX);
2418 size = track->private_size - sizeof(WAVEFORMATEX);
2419 }
2420 if ((size < 4) || (ptr[0] != 'f') || (ptr[1] != 'L') ||
2421 (ptr[2] != 'a') || (ptr[3] != 'C')) {
2422 dp = new_demux_packet(4);
2423 memcpy(dp->buffer, "fLaC", 4);
2424 dp->pts = 0;
2425 dp->flags = 0;
2426 ds_add_packet(demuxer->audio, dp);
2427 }
2428 dp = new_demux_packet(size);
2429 memcpy(dp->buffer, ptr, size);
2430 dp->pts = 0;
2431 dp->flags = 0;
2432 ds_add_packet(demuxer->audio, dp);
2433 }
2434
2435 } else {
2436 mp_msg(MSGT_DEMUX, MSGL_INFO, "[mkv] No audio track found/wanted.\n");
2437 demuxer->audio->id = -2;
2438 }
2439
2440 // DO NOT automatically select a subtitle track and behave like DVD
2441 // playback: only show subtitles if the user explicitely wants them.
2442 track = NULL;
2443 if (demuxer->sub->id >= 0)
2444 track = find_track_by_num(mkv_d, demuxer->sub->id, 's');
2445 else if (dvdsub_lang != NULL)
2446 track = find_track_by_language(mkv_d, dvdsub_lang, NULL);
2447 if (track) {
2448 if (!strcmp(track->codec_id, MKV_S_VOBSUB)) {
2449 mp_msg(MSGT_DEMUX, MSGL_INFO, "[mkv] Will display subtitle track %u\n",
2450 track->tnum);
2451 mkv_d->subs_track = track;
2452 mkv_d->subtitle_type = MKV_SUBTYPE_VOBSUB;
2453 demuxer->sub->sh = (mkv_sh_sub_t *)safememdup(&track->sh_sub,
2454 sizeof(mkv_sh_sub_t));
2455 demuxer->sub->id = track->xid;
2456
2457 } else if (strcmp(track->codec_id, MKV_S_TEXTASCII) &&
2458 strcmp(track->codec_id, MKV_S_TEXTUTF8) &&
2459 strcmp(track->codec_id, MKV_S_TEXTSSA) &&
2460 strcmp(track->codec_id, "S_SSA") &&
2461 strcmp(track->codec_id, "S_ASS") &&
2462 strcmp(track->codec_id, "S_TEXT/ASS"))
2463 mp_msg(MSGT_DEMUX, MSGL_ERR, "[mkv] Subtitle type '%s' is not "
2464 "supported. Track will not be displayed.\n", track->codec_id);
2465 else {
2466 mp_msg(MSGT_DEMUX, MSGL_INFO, "[mkv] Will display subtitle track %u\n",
2467 track->tnum);
2468 mkv_d->subs_track = track;
2469 if (!mkv_d->subs.text[0]) {
2470 for (i = 0; i <= SUB_MAX_TEXT; i++)
2471 mkv_d->subs.text[i] = (char *)safemalloc(256);
2472
2473 if (!strcmp(track->codec_id, MKV_S_TEXTUTF8))
2474 sub_utf8 = 1; // Force UTF-8 conversion.
2475 if (!strcmp(track->codec_id, MKV_S_TEXTSSA) ||
2476 !strcmp(track->codec_id, "S_SSA") ||
2477 !strcmp(track->codec_id, "S_ASS") ||
2478 !strcmp(track->codec_id, "S_TEXT/ASS")) {
2479 mkv_d->subtitle_type = MKV_SUBTYPE_SSA;
2480 sub_utf8 = 1;
2481 } else
2482 mkv_d->subtitle_type = MKV_SUBTYPE_TEXT;
2483 } else
2484 mp_msg(MSGT_DEMUX, MSGL_ERR, "[mkv] File does not contain a "
2485 "subtitle track with the id %u.\n", demuxer->sub->id);
2486 demuxer->sub->sh = NULL;
2487 }
2488 }
2489
2490 demuxer->priv = mkv_d;
2491
2492 if (mkv_d->chapters != NULL) {
2493 for (i = 0; i < (int)mkv_d->chapters->size(); i++) {
2494 (*mkv_d->chapters)[i].start -= mkv_d->first_tc;
2495 (*mkv_d->chapters)[i].end -= mkv_d->first_tc;
2496 }
2497 if ((dvd_last_chapter > 0) &&
2498 (dvd_last_chapter <= (int)mkv_d->chapters->size())) {
2499 if ((*mkv_d->chapters)[dvd_last_chapter - 1].end != 0)
2500 mkv_d->stop_timecode = (*mkv_d->chapters)[dvd_last_chapter - 1].end;
2501 else if ((dvd_last_chapter + 1) <= (int)mkv_d->chapters->size())
2502 mkv_d->stop_timecode = (*mkv_d->chapters)[dvd_last_chapter].start;
2503 }
2504 }
2505
2506 if (s->end_pos == 0)
2507 demuxer->seekable = 0;
2508 else {
2509 demuxer->movi_start = s->start_pos;
2510 demuxer->movi_end = s->end_pos;
2511 demuxer->seekable = 1;
2512 if ((dvd_chapter != 1) && (mkv_d->chapters != NULL) &&
2513 (dvd_chapter <= (int)mkv_d->chapters->size()))
2514 demux_mkv_seek(demuxer, (float)(*mkv_d->chapters)[dvd_chapter - 1].start
2515 / 1000.0, 1);
2516 }
2517
2518 return 1;
2519 }
2520
2521 // Taken from demux_real.c. Thanks to the original developpers :)
2522 #define SKIP_BITS(n) buffer <<= n
2523 #define SHOW_BITS(n) ((buffer) >> (32 - (n)))
2524
2525 static float real_fix_timestamp(mkv_track_t *track, unsigned char *s,
2526 int timestamp) {
2527 float v_pts;
2528 uint32_t buffer = (s[0] << 24) + (s[1] << 16) + (s[2] << 8) + s[3];
2529 int kf = timestamp;
2530 int pict_type;
2531 int orig_kf;
2532
2533 if (!strcmp(track->codec_id, MKV_V_REALV30) ||
2534 !strcmp(track->codec_id, MKV_V_REALV40)) {
2535
2536 if (!strcmp(track->codec_id, MKV_V_REALV30)) {
2537 SKIP_BITS(3);
2538 pict_type = SHOW_BITS(2);
2539 SKIP_BITS(2 + 7);
2540 }else{
2541 SKIP_BITS(1);
2542 pict_type = SHOW_BITS(2);
2543 SKIP_BITS(2 + 7 + 3);
2544 }
2545 kf = SHOW_BITS(13); // kf= 2*SHOW_BITS(12);
2546 orig_kf = kf;
2547 if (pict_type <= 1) {
2548 // I frame, sync timestamps:
2549 track->rv_kf_base = timestamp - kf;
2550 mp_msg(MSGT_DEMUX, MSGL_V, "\nTS: base=%08X\n", track->rv_kf_base);
2551 kf = timestamp;
2552 } else {
2553 // P/B frame, merge timestamps:
2554 int tmp = timestamp - track->rv_kf_base;
2555 kf |= tmp & (~0x1fff); // combine with packet timestamp
2556 if (kf < (tmp - 4096)) // workaround wrap-around problems
2557 kf += 8192;
2558 else if (kf > (tmp + 4096))
2559 kf -= 8192;
2560 kf += track->rv_kf_base;
2561 }
2562 if (pict_type != 3) { // P || I frame -> swap timestamps
2563 int tmp = kf;
2564 kf = track->rv_kf_pts;
2565 track->rv_kf_pts = tmp;
2566 }
2567 mp_msg(MSGT_DEMUX, MSGL_V, "\nTS: %08X -> %08X (%04X) %d %02X %02X %02X "
2568 "%02X %5d\n", timestamp, kf, orig_kf, pict_type, s[0], s[1], s[2],
2569 s[3], kf - (int)(1000.0 * track->rv_pts));
2570 }
2571 v_pts = kf * 0.001f;
2572 track->rv_pts = v_pts;
2573
2574 return v_pts;
2575 }
2576
2577 static void handle_realvideo(demuxer_t *demuxer, unsigned char *data,
2578 uint32_t size, bool keyframe, int &found_data) {
2579 dp_hdr_t *hdr;
2580 int chunks, isize;
2581 mkv_demuxer_t *mkv_d;
2582 demux_stream_t *ds;
2583 demux_packet_t *dp;
2584
2585 mkv_d = (mkv_demuxer_t *)demuxer->priv;
2586 ds = demuxer->video;
2587 chunks = data[0];
2588 isize = size - 1 - (chunks + 1) * 8;
2589 dp = new_demux_packet(sizeof(dp_hdr_t) + isize + 8 * (chunks + 1));
2590 memcpy(&dp->buffer[sizeof(dp_hdr_t)], &data[1 + (chunks + 1) * 8], isize);
2591 memcpy(&dp->buffer[sizeof(dp_hdr_t) + isize], &data[1], (chunks + 1) * 8);
2592 hdr = (dp_hdr_t *)dp->buffer;
2593 hdr->len = isize;
2594 hdr->chunks = chunks;
2595 hdr->timestamp = (int)(mkv_d->last_pts * 1000);
2596 hdr->chunktab = sizeof(dp_hdr_t) + isize;
2597
2598 dp->len = sizeof(dp_hdr_t) + isize + 8 * (chunks + 1);
2599 if (mkv_d->v_skip_to_keyframe) {
2600 dp->pts = mkv_d->last_pts;
2601 mkv_d->video->rv_kf_base = 0;
2602 mkv_d->video->rv_kf_pts = hdr->timestamp;
2603 } else
2604 dp->pts = real_fix_timestamp(mkv_d->video, &dp->buffer[sizeof(dp_hdr_t)],
2605 hdr->timestamp);
2606 dp->pos = demuxer->filepos;
2607 dp->flags = keyframe ? 0x10 : 0;
2608
2609 ds_add_packet(ds, dp);
2610
2611 found_data++;
2612 }
2613
2614 static void handle_realaudio(demuxer_t *demuxer, unsigned char *data,
2615 uint32_t size, bool keyframe, int &found_data) {
2616 mkv_demuxer_t *mkv_d;
2617 demux_packet_t *dp;
2618
2619 mkv_d = (mkv_demuxer_t *)demuxer->priv;
2620
2621 dp = new_demux_packet(size);
2622 memcpy(dp->buffer, data, size);
2623 if ((mkv_d->audio->ra_pts == mkv_d->last_pts) &&
2624 !mkv_d->a_skip_to_keyframe)
2625 dp->pts = 0;
2626 else
2627 dp->pts = mkv_d->last_pts;
2628 mkv_d->audio->ra_pts = mkv_d->last_pts;
2629
2630 dp->pos = demuxer->filepos;
2631 dp->flags = keyframe ? 0x10 : 0;
2632
2633 ds_add_packet(demuxer->audio, dp);
2634
2635 found_data++;
2636 }
2637
2638 extern "C" int demux_mkv_fill_buffer(demuxer_t *d) {
2639 demux_packet_t *dp;
2640 demux_stream_t *ds;
2641 mkv_demuxer_t *mkv_d;
2642 mkv_track_t *t = NULL;
2643 int upper_lvl_el, exit_loop, found_data, i, linei, sl;
2644 char *texttmp;
2645 // Elements for different levels
2646 EbmlElement *l0 = NULL, *l1 = NULL, *l2 = NULL, *l3 = NULL;
2647 EbmlStream *es;
2648 KaxBlock *block;
2649 int64_t block_duration, block_bref, block_fref;
2650 bool use_this_block, lines_cut;
2651 float current_pts;
2652
2653 mkv_d = (mkv_demuxer_t *)d->priv;
2654 es = mkv_d->es;
2655 l0 = mkv_d->segment;
2656
2657 // End of stream
2658 if (mkv_d->saved_l1 == NULL)
2659 return 0;
2660
2661 exit_loop = 0;
2662 upper_lvl_el = 0;
2663 l1 = mkv_d->saved_l1;
2664 mkv_d->saved_l1 = NULL;
2665 found_data = 0;
2666 try {
2667 // The idea is not to handle a complete KaxCluster with each call to
2668 // demux_mkv_fill_buffer because those might be rather big.
2669 while ((l1 != NULL) && (upper_lvl_el <= 0)) {
2670
2671 if (EbmlId(*l1) == KaxCluster::ClassInfos.GlobalId) {
2672 mkv_d->cluster = (KaxCluster *)l1;
2673 if (found_data) {
2674 mkv_d->saved_l1 = l1;
2675 break;
2676 }
2677
2678 if (mkv_d->saved_l2 != NULL) {
2679 l2 = mkv_d->saved_l2;
2680 mkv_d->saved_l2 = NULL;
2681 } else
2682 l2 = es->FindNextElement(l1->Generic().Context, upper_lvl_el,
2683 0xFFFFFFFFL, true, 1);
2684 while ((l2 != NULL) && (upper_lvl_el <= 0)) {
2685
2686 // Handle at least one data packets in one call to
2687 // demux_mkv_fill_buffer - but abort if we have found that.
2688 if (found_data >= 1) {
2689 mkv_d->saved_l2 = l2;
2690 mkv_d->saved_l1 = l1;
2691 exit_loop = 1;
2692 break;
2693 }
2694
2695 if (EbmlId(*l2) == KaxClusterTimecode::ClassInfos.GlobalId) {
2696 KaxClusterTimecode &ctc = *static_cast<KaxClusterTimecode *>(l2);
2697 ctc.ReadData(es->I_O());
2698 mkv_d->cluster_tc = uint64(ctc);
2699 #if LIBEBML_VERSION >= 000404
2700 mkv_d->cluster->InitTimecode(mkv_d->cluster_tc, mkv_d->tc_scale);
2701 #else
2702 mkv_d->cluster->InitTimecode(mkv_d->cluster_tc);
2703 #endif // LIBEBML_VERSION
2704
2705 } else if (EbmlId(*l2) == KaxBlockGroup::ClassInfos.GlobalId) {
2706
2707 KaxBlockDuration *kbdur;
2708 KaxReferenceBlock *krefblock;
2709 KaxBlock *kblock;
2710
2711 block = NULL;
2712 block_duration = -1;
2713 block_bref = 0;
2714 block_fref = 0;
2715
2716 l2->Read(*es, KaxBlockGroup::ClassInfos.Context, upper_lvl_el, l3,
2717 true);
2718
2719 kbdur = FINDFIRST(l2, KaxBlockDuration);
2720 if (kbdur != NULL)
2721 block_duration = uint64(*kbdur);
2722
2723 kblock = FINDFIRST(l2, KaxBlock);
2724 if (kblock != NULL) {
2725 kblock->SetParent(*mkv_d->cluster);
2726 if ((mkv_d->stop_timecode > 0) &&
2727 ((kblock->GlobalTimecode() / 1000000 - mkv_d->first_tc) >=
2728 mkv_d->stop_timecode)) {
2729 delete l2;
2730 return 0;
2731 }
2732 }
2733
2734 krefblock = FINDFIRST(l2, KaxReferenceBlock);
2735 while (krefblock != NULL) {
2736 if (int64(*krefblock) < 0)
2737 block_bref = int64(*krefblock);
2738 else
2739 block_fref = int64(*krefblock);
2740
2741 krefblock = FINDNEXT(l2, KaxReferenceBlock, krefblock);
2742 }
2743
2744 if (kblock != NULL) {
2745 // Clear the subtitles if they're obsolete now.
2746 lines_cut = false;
2747 for (linei = 0; linei < mkv_d->subs.lines; linei++) {
2748 if (mkv_d->clear_subs_at[linei] <=
2749 (kblock->GlobalTimecode() / 1000000 - mkv_d->first_tc)) {
2750 sl = linei;
2751 texttmp = mkv_d->subs.text[sl];
2752 while (sl < mkv_d->subs.lines) {
2753 mkv_d->subs.text[sl] = mkv_d->subs.text[sl + 1];
2754 mkv_d->clear_subs_at[sl] = mkv_d->clear_subs_at[sl + 1];
2755 sl++;
2756 }
2757 mkv_d->subs.text[sl] = texttmp;
2758 mkv_d->subs.lines--;
2759 linei--;
2760 lines_cut = true;
2761 }
2762 if (lines_cut) {
2763 vo_sub = &mkv_d->subs;
2764 vo_osd_changed(OSDTYPE_SUBTITLE);
2765 }
2766 }
2767
2768 ds = NULL;
2769 if ((mkv_d->video != NULL) &&
2770 (mkv_d->video->tnum == kblock->TrackNum())) {
2771 ds = d->video;
2772 t = mkv_d->video;
2773 } else if ((mkv_d->audio != NULL) &&
2774 (mkv_d->audio->tnum == kblock->TrackNum())) {
2775 ds = d->audio;
2776 t = mkv_d->audio;
2777 } else if ((mkv_d->subs_track != NULL) &&
2778 (mkv_d->subs_track->tnum == kblock->TrackNum())) {
2779 ds = d->sub;
2780 t = mkv_d->subs_track;
2781 }
2782
2783 use_this_block = true;
2784
2785 current_pts = (float)(kblock->GlobalTimecode() / 1000000.0 -
2786 mkv_d->first_tc) / 1000.0;
2787 if (current_pts < 0.0)
2788 current_pts = 0.0;
2789
2790 if (ds == d->audio) {
2791 if (mkv_d->a_skip_to_keyframe &&
2792 (block_bref != 0))
2793 use_this_block = false;
2794
2795 else if (mkv_d->v_skip_to_keyframe)
2796 use_this_block = false;
2797
2798 if (mkv_d->audio->fix_i_bps && use_this_block) {
2799 uint32_t i, sum;
2800 sh_audio_t *sh;
2801
2802 for (i = 0, sum = 0; i < kblock->NumberFrames(); i++) {
2803 DataBuffer &data = kblock->GetBuffer(i);
2804 sum += data.Size();
2805 }
2806 sh = (sh_audio_t *)ds->sh;
2807 if (block_duration != -1) {
2808 sh->i_bps = sum * 1000 / block_duration;
2809 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] Changed i_bps to %d.\n",
2810 sh->i_bps);
2811 mkv_d->audio->fix_i_bps = false;
2812 } else if (mkv_d->audio->qt_last_a_pts == 0.0)
2813 mkv_d->audio->qt_last_a_pts = current_pts;
2814 else if (mkv_d->audio->qt_last_a_pts != current_pts) {
2815 sh->i_bps = (int)(sum / (current_pts -
2816 mkv_d->audio->qt_last_a_pts));
2817 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] Changed i_bps to %d.\n",
2818 sh->i_bps);
2819 mkv_d->audio->fix_i_bps = false;
2820 }
2821 }
2822
2823 } else if ((current_pts * 1000) < mkv_d->skip_to_timecode)
2824 use_this_block = false;
2825
2826 else if (ds == d->video) {
2827 if (mkv_d->v_skip_to_keyframe &&
2828 (block_bref != 0))
2829 use_this_block = false;
2830
2831 } else if ((mkv_d->subs_track != NULL) &&
2832 (mkv_d->subs_track->tnum == kblock->TrackNum())) {
2833 if (mkv_d->subtitle_type != MKV_SUBTYPE_VOBSUB) {
2834 if (!mkv_d->v_skip_to_keyframe)
2835 handle_subtitles(d, kblock, block_duration);
2836 use_this_block = false;
2837 }
2838
2839 } else
2840 use_this_block = false;
2841
2842 if (use_this_block) {
2843 mkv_d->last_pts = current_pts;
2844 ds->pts = current_pts;
2845 d->filepos = mkv_d->in->getFilePointer();
2846 mkv_d->last_filepos = d->filepos;
2847
2848 for (i = 0; i < (int)kblock->NumberFrames(); i++) {
2849 unsigned char *re_buffer;
2850 uint32_t re_size;
2851 bool re_modified;
2852 DataBuffer &data = kblock->GetBuffer(i);
2853
2854 re_buffer = data.Buffer();
2855 re_size = data.Size();
2856 re_modified = reverse_encodings(t, re_buffer, re_size, 1);
2857
2858 if ((ds == d->video) && mkv_d->video->realmedia)
2859 handle_realvideo(d, re_buffer, re_size, block_bref == 0,
2860 found_data);
2861
2862 else if ((ds == d->audio) && mkv_d->audio->realmedia)
2863 handle_realaudio(d, re_buffer, re_size, block_bref == 0,
2864 found_data);
2865
2866 else {
2867 dp = new_demux_packet(re_size);
2868 memcpy(dp->buffer, re_buffer, re_size);
2869 dp->flags = block_bref == 0 ? 1 : 0;
2870 dp->pts = mkv_d->last_pts + i * t->default_duration;
2871 ds_add_packet(ds, dp);
2872 found_data++;
2873 }
2874 if (re_modified)
2875 safefree(re_buffer);
2876 }
2877 if (ds == d->video) {
2878 mkv_d->v_skip_to_keyframe = false;
2879 mkv_d->skip_to_timecode = 0;
2880 } else if (ds == d->audio)
2881 mkv_d->a_skip_to_keyframe = false;
2882 }
2883
2884 delete block;
2885 } // kblock != NULL
2886
2887 } else
2888 l2->SkipData(*es, l2->Generic().Context);
2889
2890 if (!in_parent(l1)) {
2891 delete l2;
2892 break;
2893 }
2894
2895 if (upper_lvl_el > 0) {
2896 upper_lvl_el--;
2897 if (upper_lvl_el > 0)
2898 break;
2899 delete l2;
2900 l2 = l3;
2901 continue;
2902
2903 } else if (upper_lvl_el < 0) {
2904 upper_lvl_el++;
2905 if (upper_lvl_el < 0)
2906 break;
2907
2908 }
2909
2910 l2->SkipData(*es, l2->Generic().Context);
2911 delete l2;
2912 l2 = es->FindNextElement(l1->Generic().Context, upper_lvl_el,
2913 0xFFFFFFFFL, true);
2914
2915 } // while (l2 != NULL)
2916
2917 } else if (EbmlId(*l1) == KaxCues::ClassInfos.GlobalId)
2918 return 0;
2919 else
2920 l1->SkipData(*es, l1->Generic().Context);
2921
2922 if (!in_parent(l0)) {
2923 delete l1;
2924 break;
2925 }
2926
2927 if (upper_lvl_el > 0) {
2928 upper_lvl_el--;
2929 if (upper_lvl_el > 0)
2930 break;
2931 delete l1;
2932 l1 = l2;
2933 continue;
2934
2935 } else if (upper_lvl_el < 0) {
2936 upper_lvl_el++;
2937 if (upper_lvl_el < 0)
2938 break;
2939
2940 }
2941
2942 if (exit_loop)
2943 break;
2944
2945 l1->SkipData(*es, l1->Generic().Context);
2946 delete l1;
2947 l1 = es->FindNextElement(l0->Generic().Context, upper_lvl_el,
2948 0xFFFFFFFFL, true);
2949
2950 } // while (l1 != NULL)
2951 } catch (exception ex) {
2952 mp_msg(MSGT_DEMUX, MSGL_ERR, "[mkv] exception caught\n");
2953 return 0;
2954 }
2955
2956 if (found_data)
2957 return 1;
2958
2959 return 0;
2960 }
2961
2962 extern "C" void resync_audio_stream(sh_audio_t *sh_audio);
2963
2964 extern "C" void demux_mkv_seek(demuxer_t *demuxer, float rel_seek_secs,
2965 int flags) {
2966 int i, k, upper_lvl_el;
2967 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *)demuxer->priv;
2968 int64_t target_timecode, target_filepos = 0, min_diff, diff, current_pos;
2969 int64_t cluster_pos;
2970 mkv_track_index_t *index;
2971 mkv_index_entry_t *entry;
2972 EbmlElement *l1;
2973
2974 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] SEEK, relss: %.3f, flags: %d\n",
2975 rel_seek_secs, flags);
2976
2977 if (!mkv_d->cues_found && !mkv_d->cues_searched) {
2978 // We've not found an index so far. So let's skip over all level 1
2979 // elements until we either hit another segment, the end of the file
2980 // or - suprise - some cues.
2981 current_pos = mkv_d->in->getFilePointer();
2982
2983 // Skip the data but do not delete the element! This is our current
2984 // cluster, and we need it later on in demux_mkv_fill_buffer.
2985 l1 = mkv_d->saved_l1;
2986 l1->SkipData(static_cast<EbmlStream &>(*mkv_d->es), l1->Generic().Context);
2987 l1 = mkv_d->es->FindNextElement(mkv_d->segment->Generic().Context,
2988 upper_lvl_el, 0xFFFFFFFFL, true, 1);
2989 while (l1 != NULL) {
2990 if (upper_lvl_el)
2991 break;
2992
2993 if (EbmlId(*l1) == KaxCues::ClassInfos.GlobalId) {
2994 parse_cues(mkv_d, l1->GetElementPosition());
2995 delete l1;
2996 break;
2997 } else {
2998 if (EbmlId(*l1) == KaxCluster::ClassInfos.GlobalId)
2999 add_cluster_position(mkv_d, l1->GetElementPosition());
3000 l1->SkipData(static_cast<EbmlStream &>(*mkv_d->es),
3001 l1->Generic().Context);
3002 delete l1;
3003 l1 = mkv_d->es->FindNextElement(mkv_d->segment->Generic().Context,
3004 upper_lvl_el, 0xFFFFFFFFL, true, 1);
3005 }
3006 }
3007
3008 if (demuxer->stream->eof)
3009 stream_reset(demuxer->stream);
3010 mkv_d->in->setFilePointer(current_pos);
3011
3012 mkv_d->cues_searched = 1;
3013 }
3014
3015 if (!(flags & 2)) { // Time in secs
3016 if (flags & 1) // Absolute seek
3017 target_timecode = 0;
3018 else // Relative seek
3019 target_timecode = (int64_t)(mkv_d->last_pts * 1000.0);
3020 target_timecode += (int64_t)(rel_seek_secs * 1000.0);
3021 if (target_timecode < 0)
3022 target_timecode = 0;
3023
3024 min_diff = 0xFFFFFFFL;
3025
3026 // Let's find the entry in the index with the smallest difference
3027 // to the wanted timecode.
3028 entry = NULL;
3029 for (i = 0; i < mkv_d->num_indexes; i++)
3030 if (mkv_d->index[i].tnum == mkv_d->video->tnum) {
3031 index = &mkv_d->index[i];
3032 for (k = 0; k < index->num_entries; k++) {
3033 if (!index->entries[k].is_key)
3034 continue;
3035 diff = target_timecode - (int64_t)index->entries[k].timecode;
3036 if (((flags & 1) || (target_timecode <= (mkv_d->last_pts * 1000))) &&
3037 (diff >= 0) && (diff < min_diff)) {
3038 min_diff = diff;
3039 entry = &index->entries[k];
3040 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] seek BACK, solution: last_pts: "
3041 "%d, target: %d, diff: %d, entry->timecode: %d, PREV diff: "
3042 "%d, k: %d\n", (int)(mkv_d->last_pts * 1000),
3043 (int)target_timecode, (int)diff, (int)entry->timecode,
3044 k > 0 ? (int)(index->entries[k - 1].timecode -
3045 target_timecode) : 0, k);
3046
3047 } else if ((target_timecode > (mkv_d->last_pts * 1000)) &&
3048 (diff < 0) && (-diff < min_diff)) {
3049 min_diff = -diff;
3050 entry = &index->entries[k];
3051 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] seek FORW, solution: last_pts: "
3052 "%d, target: %d, diff: %d, entry->timecode: %d, NEXT diff: "
3053 "%d, k: %d\n", (int)(mkv_d->last_pts * 1000),
3054 (int)target_timecode, (int)diff, (int)entry->timecode,
3055 k < index->num_entries ?
3056 (int)(index->entries[k + 1].timecode - target_timecode) :
3057 0, k);
3058 }
3059 }
3060 break;
3061 }
3062
3063 if (mkv_d->saved_l1 != NULL)
3064 delete mkv_d->saved_l1;
3065
3066 if (mkv_d->saved_l2 != NULL) {
3067 delete mkv_d->saved_l2;
3068 mkv_d->saved_l2 = NULL;
3069 }
3070
3071 if (entry != NULL) { // We've found an entry.
3072 mkv_d->in->setFilePointer(entry->filepos);
3073 upper_lvl_el = 0;
3074 mkv_d->saved_l1 =
3075 mkv_d->es->FindNextElement(mkv_d->segment->Generic().Context,
3076 upper_lvl_el, 0xFFFFFFFFL, true, 1);
3077 } else { // We've not found an entry --> no index?
3078 target_filepos = (int64_t)(target_timecode * mkv_d->last_filepos /
3079 (mkv_d->last_pts * 1000.0));
3080 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] No index entry found. Calculated "
3081 "filepos %lld. Old timecode %lld.\n", target_filepos,
3082 (int64_t)(mkv_d->last_pts * 1000.0));
3083 // Let's find the nearest cluster so that libebml does not have to
3084 // do so much work.
3085 cluster_pos = 0;
3086 min_diff = 0x0FFFFFFFL;
3087 for (i = 0; i < mkv_d->num_cluster_pos; i++) {
3088 diff = mkv_d->cluster_positions[i] - target_filepos;
3089 if (rel_seek_secs < 0) {
3090 if ((diff > 0) && (diff < min_diff)) {
3091 cluster_pos = mkv_d->cluster_positions[i];
3092 min_diff = diff;
3093 }
3094 } else if ((diff < 0 ? -1 * diff : diff) < min_diff) {
3095 cluster_pos = mkv_d->cluster_positions[i];
3096 min_diff = diff < 0 ? -1 * diff : diff;
3097 }
3098 }
3099 if (min_diff != 0x0FFFFFFFL) {
3100 target_filepos = cluster_pos;
3101 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] New target_filepos because of "
3102 "cluster: %lld.\n", target_filepos);
3103 }
3104 if (target_filepos >= demuxer->movi_end)
3105 return;
3106 mkv_d->in->setFilePointer(target_filepos);
3107 upper_lvl_el = 0;
3108 mkv_d->saved_l1 =
3109 mkv_d->es->FindNextElement(mkv_d->segment->Generic().Context,
3110 upper_lvl_el, 0xFFFFFFFFL, true, 1);
3111 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] seek result: target_timecode %lld, "
3112 "did not find an entry. Calculated target_filspos: %lld\n",
3113 target_timecode, target_filepos);
3114 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] seek found %p (%s).\n",
3115 mkv_d->saved_l1, mkv_d->saved_l1 == NULL ? "null" :
3116 mkv_d->saved_l1->Generic().DebugName);
3117 }
3118
3119 if (mkv_d->video != NULL)
3120 mkv_d->v_skip_to_keyframe = true;
3121 if (rel_seek_secs > 0.0)
3122 mkv_d->skip_to_timecode = target_timecode;
3123
3124 mkv_d->a_skip_to_keyframe = true;
3125
3126 demux_mkv_fill_buffer(demuxer);
3127 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] New timecode: %lld\n",
3128 (int64_t)(mkv_d->last_pts * 1000.0));
3129
3130 mkv_d->subs.lines = 0;
3131 vo_sub = &mkv_d->subs;
3132 vo_osd_changed(OSDTYPE_SUBTITLE);
3133
3134 if(demuxer->audio->sh != NULL)
3135 resync_audio_stream((sh_audio_t *)demuxer->audio->sh);
3136
3137 } else
3138 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] seek unsupported flags\n");
3139
3140 }
3141
3142 extern "C" void demux_close_mkv(demuxer_t *demuxer) {
3143 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *)demuxer->priv;
3144
3145 free_mkv_demuxer(mkv_d);
3146
3147 #ifdef USE_ICONV
3148 subcp_close();
3149 #endif
3150 }
3151
3152 extern "C" int demux_mkv_control(demuxer_t *demuxer, int cmd, void *arg) {
3153 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *)demuxer->priv;
3154
3155 switch (cmd) {
3156 case DEMUXER_CTRL_GET_TIME_LENGTH:
3157 if (mkv_d->duration == -1.0)
3158 return DEMUXER_CTRL_DONTKNOW;
3159
3160 *((unsigned long *)arg) = (unsigned long)mkv_d->duration;
3161 return DEMUXER_CTRL_OK;
3162
3163 case DEMUXER_CTRL_GET_PERCENT_POS:
3164 if (mkv_d->duration == -1.0) {
3165 if (demuxer->movi_start == demuxer->movi_end)
3166 return DEMUXER_CTRL_DONTKNOW;
3167
3168 *((int *)arg) =
3169 (int)((demuxer->filepos - demuxer->movi_start) /
3170 ((demuxer->movi_end - demuxer->movi_start) / 100));
3171 return DEMUXER_CTRL_OK;
3172 }
3173
3174 *((int *)arg) = (int)(100 * mkv_d->last_pts / mkv_d->duration);
3175 return DEMUXER_CTRL_OK;
3176
3177 default:
3178 return DEMUXER_CTRL_NOTIMPL;
3179 }
3180 }
3181
3182 #endif /* HAVE_MATROSKA */