Get rid of completely pointless vt_doit variable
[mplayer/glamo.git] / libmpdemux / demux_mkv.c
blobcb4d9717550185f612c659cb0ede85f7d2413bfe
1 /*
2 * Matroska demuxer
3 * Copyright (C) 2004 Aurelien Jacobs <aurel@gnuage.org>
4 * Based on the one written by Ronald Bultje for gstreamer
5 * and on demux_mkv.cpp from Moritz Bunkus.
7 * This file is part of MPlayer.
9 * MPlayer is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * MPlayer is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with MPlayer; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 #include "config.h"
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <ctype.h>
29 #include <inttypes.h>
31 #include "stream/stream.h"
32 #include "demuxer.h"
33 #include "stheader.h"
34 #include "ebml.h"
35 #include "matroska.h"
37 #include "mp_msg.h"
38 #include "help_mp.h"
40 #include "vobsub.h"
41 #include "subreader.h"
42 #include "libvo/sub.h"
44 #include "libass/ass.h"
45 #include "libass/ass_mp.h"
47 #include "libavutil/common.h"
49 #ifdef CONFIG_QTX_CODECS
50 #include "loader/qtx/qtxsdk/components.h"
51 #endif
53 #if CONFIG_ZLIB
54 #include <zlib.h>
55 #endif
57 #include "libavutil/lzo.h"
58 #include "libavutil/intreadwrite.h"
59 #include "libavutil/avstring.h"
61 static const unsigned char sipr_swaps[38][2]={
62 {0,63},{1,22},{2,44},{3,90},{5,81},{7,31},{8,86},{9,58},{10,36},{12,68},
63 {13,39},{14,73},{15,53},{16,69},{17,57},{19,88},{20,34},{21,71},{24,46},
64 {25,94},{26,54},{28,75},{29,50},{32,70},{33,92},{35,74},{38,85},{40,56},
65 {42,87},{43,65},{45,59},{48,79},{49,93},{51,89},{55,95},{61,76},{67,83},
66 {77,80} };
68 // Map flavour to bytes per second
69 #define SIPR_FLAVORS 4
70 #define ATRC_FLAVORS 8
71 #define COOK_FLAVORS 34
72 static const int sipr_fl2bps[SIPR_FLAVORS] = {813, 1062, 625, 2000};
73 static const int atrc_fl2bps[ATRC_FLAVORS] =
74 {8269, 11714, 13092, 16538, 18260, 22050, 33075, 44100};
75 static const int cook_fl2bps[COOK_FLAVORS] =
76 { 1000, 1378, 2024, 2584, 4005, 5513, 8010, 4005, 750, 2498,
77 4048, 5513, 8010, 11973, 8010, 2584, 4005, 2067, 2584, 2584,
78 4005, 4005, 5513, 5513, 8010, 12059, 1550, 8010, 12059, 5513,
79 12016, 16408, 22911, 33506};
81 typedef struct
83 uint32_t order, type, scope;
84 uint32_t comp_algo;
85 uint8_t *comp_settings;
86 int comp_settings_len;
87 } mkv_content_encoding_t;
89 typedef struct mkv_track
91 int tnum;
92 char *name;
94 char *codec_id;
95 int ms_compat;
96 char *language;
98 int type;
100 uint32_t v_width, v_height, v_dwidth, v_dheight;
101 float v_frate;
103 uint32_t a_formattag;
104 uint32_t a_channels, a_bps;
105 float a_sfreq;
107 float default_duration;
109 int default_track;
111 void *private_data;
112 unsigned int private_size;
114 /* stuff for realmedia */
115 int realmedia;
116 int64_t rv_kf_base;
117 int rv_kf_pts;
118 float rv_pts; /* previous video timestamp */
119 float ra_pts; /* previous audio timestamp */
121 /** realaudio descrambling */
122 int sub_packet_size; ///< sub packet size, per stream
123 int sub_packet_h; ///< number of coded frames per block
124 int coded_framesize; ///< coded frame size, per stream
125 int audiopk_size; ///< audio packet size
126 unsigned char *audio_buf; ///< place to store reordered audio data
127 float *audio_timestamp; ///< timestamp for each audio packet
128 int sub_packet_cnt; ///< number of subpacket already received
129 int audio_filepos; ///< file position of first audio packet in block
131 /* stuff for quicktime */
132 int fix_i_bps;
133 float qt_last_a_pts;
135 int subtitle_type;
137 /* The timecodes of video frames might have to be reordered if they're
138 in display order (the timecodes, not the frames themselves!). In this
139 case demux packets have to be cached with the help of these variables. */
140 int reorder_timecodes;
141 demux_packet_t **cached_dps;
142 int num_cached_dps, num_allocated_dps;
143 float max_pts;
145 /* generic content encoding support */
146 mkv_content_encoding_t *encodings;
147 int num_encodings;
149 /* For VobSubs and SSA/ASS */
150 sh_sub_t *sh_sub;
151 } mkv_track_t;
153 typedef struct mkv_index
155 int tnum;
156 uint64_t timecode, filepos;
157 } mkv_index_t;
159 typedef struct mkv_demuxer
161 off_t segment_start;
163 float duration, last_pts;
164 uint64_t last_filepos;
166 mkv_track_t **tracks;
167 int num_tracks;
169 uint64_t tc_scale, cluster_tc, first_tc;
170 int has_first_tc;
172 uint64_t cluster_size;
173 uint64_t blockgroup_size;
175 mkv_index_t *indexes;
176 int num_indexes;
178 off_t *parsed_cues;
179 int parsed_cues_num;
180 off_t *parsed_seekhead;
181 int parsed_seekhead_num;
183 uint64_t *cluster_positions;
184 int num_cluster_pos;
186 int64_t skip_to_timecode;
187 int v_skip_to_keyframe, a_skip_to_keyframe;
189 int64_t stop_timecode;
191 int last_aid;
192 int audio_tracks[MAX_A_STREAMS];
193 } mkv_demuxer_t;
195 #define REALHEADER_SIZE 16
196 #define RVPROPERTIES_SIZE 34
197 #define RAPROPERTIES4_SIZE 56
198 #define RAPROPERTIES5_SIZE 70
200 /* for e.g. "-slang ger" */
201 extern char *dvdsub_lang;
202 extern char *audio_lang;
203 extern int dvdsub_id;
206 * \brief ensures there is space for at least one additional element
207 * \param array array to grow
208 * \param nelem current number of elements in array
209 * \param elsize size of one array element
211 static void grow_array(void **array, int nelem, size_t elsize) {
212 if (!(nelem & 31))
213 *array = realloc(*array, (nelem + 32) * elsize);
216 static mkv_track_t *
217 demux_mkv_find_track_by_num (mkv_demuxer_t *d, int n, int type)
219 int i, id;
221 for (i=0, id=0; i < d->num_tracks; i++)
222 if (d->tracks[i] != NULL && d->tracks[i]->type == type)
223 if (id++ == n)
224 return d->tracks[i];
226 return NULL;
229 static void
230 add_cluster_position (mkv_demuxer_t *mkv_d, uint64_t position)
232 int i = mkv_d->num_cluster_pos;
234 while (i--)
235 if (mkv_d->cluster_positions[i] == position)
236 return;
238 grow_array(&mkv_d->cluster_positions, mkv_d->num_cluster_pos,
239 sizeof(uint64_t));
240 mkv_d->cluster_positions[mkv_d->num_cluster_pos++] = position;
244 #define AAC_SYNC_EXTENSION_TYPE 0x02b7
245 static int
246 aac_get_sample_rate_index (uint32_t sample_rate)
248 if (92017 <= sample_rate)
249 return 0;
250 else if (75132 <= sample_rate)
251 return 1;
252 else if (55426 <= sample_rate)
253 return 2;
254 else if (46009 <= sample_rate)
255 return 3;
256 else if (37566 <= sample_rate)
257 return 4;
258 else if (27713 <= sample_rate)
259 return 5;
260 else if (23004 <= sample_rate)
261 return 6;
262 else if (18783 <= sample_rate)
263 return 7;
264 else if (13856 <= sample_rate)
265 return 8;
266 else if (11502 <= sample_rate)
267 return 9;
268 else if (9391 <= sample_rate)
269 return 10;
270 else
271 return 11;
274 /** \brief Free cached demux packets
276 * Reordering the timecodes requires caching of demux packets. This function
277 * frees all these cached packets and the memory for the cached pointers
278 * itself.
280 * \param demuxer The demuxer for which the cache is to be freed.
282 static void
283 free_cached_dps (demuxer_t *demuxer)
285 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
286 mkv_track_t *track;
287 int i, k;
289 for (k = 0; k < mkv_d->num_tracks; k++)
291 track = mkv_d->tracks[k];
292 for (i = 0; i < track->num_cached_dps; i++)
293 free_demux_packet (track->cached_dps[i]);
294 free(track->cached_dps);
295 track->cached_dps = NULL;
296 track->num_cached_dps = 0;
297 track->num_allocated_dps = 0;
298 track->max_pts = 0;
302 static int
303 demux_mkv_decode (mkv_track_t *track, uint8_t *src, uint8_t **dest,
304 uint32_t *size, uint32_t type)
306 int i, result;
307 int modified = 0;
309 *dest = src;
310 if (track->num_encodings <= 0)
311 return 0;
313 for (i=0; i<track->num_encodings; i++)
315 if (!(track->encodings[i].scope & type))
316 continue;
318 #if CONFIG_ZLIB
319 if (track->encodings[i].comp_algo == 0)
321 /* zlib encoded track */
322 z_stream zstream;
324 zstream.zalloc = (alloc_func) 0;
325 zstream.zfree = (free_func) 0;
326 zstream.opaque = (voidpf) 0;
327 if (inflateInit (&zstream) != Z_OK)
329 mp_msg (MSGT_DEMUX, MSGL_WARN,
330 MSGTR_MPDEMUX_MKV_ZlibInitializationFailed);
331 return modified;
333 zstream.next_in = (Bytef *) src;
334 zstream.avail_in = *size;
336 modified = 1;
337 *dest = NULL;
338 zstream.avail_out = *size;
339 do {
340 *size += 4000;
341 *dest = realloc (*dest, *size);
342 zstream.next_out = (Bytef *) (*dest + zstream.total_out);
343 result = inflate (&zstream, Z_NO_FLUSH);
344 if (result != Z_OK && result != Z_STREAM_END)
346 mp_msg (MSGT_DEMUX, MSGL_WARN,
347 MSGTR_MPDEMUX_MKV_ZlibDecompressionFailed);
348 free(*dest);
349 *dest = NULL;
350 inflateEnd (&zstream);
351 return modified;
353 zstream.avail_out += 4000;
354 } while (zstream.avail_out == 4000 &&
355 zstream.avail_in != 0 && result != Z_STREAM_END);
357 *size = zstream.total_out;
358 inflateEnd (&zstream);
360 #endif
361 if (track->encodings[i].comp_algo == 2)
363 /* lzo encoded track */
364 int dstlen = *size * 3;
366 *dest = NULL;
367 while (1)
369 int srclen = *size;
370 if (dstlen > SIZE_MAX - AV_LZO_OUTPUT_PADDING) goto lzo_fail;
371 *dest = realloc (*dest, dstlen + AV_LZO_OUTPUT_PADDING);
372 result = av_lzo1x_decode (*dest, &dstlen, src, &srclen);
373 if (result == 0)
374 break;
375 if (!(result & AV_LZO_OUTPUT_FULL))
377 lzo_fail:
378 mp_msg (MSGT_DEMUX, MSGL_WARN,
379 MSGTR_MPDEMUX_MKV_LzoDecompressionFailed);
380 free(*dest);
381 *dest = NULL;
382 return modified;
384 mp_msg (MSGT_DEMUX, MSGL_DBG2,
385 "[mkv] lzo decompression buffer too small.\n");
386 dstlen *= 2;
388 *size = dstlen;
392 return modified;
396 static int
397 demux_mkv_read_info (demuxer_t *demuxer)
399 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
400 stream_t *s = demuxer->stream;
401 uint64_t length, l;
402 int il;
403 uint64_t tc_scale = 1000000;
404 long double duration = 0.;
406 length = ebml_read_length (s, NULL);
407 while (length > 0)
409 switch (ebml_read_id (s, &il))
411 case MATROSKA_ID_TIMECODESCALE:
413 uint64_t num = ebml_read_uint (s, &l);
414 if (num == EBML_UINT_INVALID)
415 return 1;
416 tc_scale = num;
417 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + timecode scale: %"PRIu64"\n",
418 tc_scale);
419 break;
422 case MATROSKA_ID_DURATION:
424 long double num = ebml_read_float (s, &l);
425 if (num == EBML_FLOAT_INVALID)
426 return 1;
427 duration = num;
428 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + duration: %.3Lfs\n",
429 duration * tc_scale / 1000000000.0);
430 break;
433 default:
434 ebml_read_skip (s, &l);
435 break;
437 length -= l + il;
439 mkv_d->tc_scale = tc_scale;
440 mkv_d->duration = duration * tc_scale / 1000000000.0;
441 return 0;
445 * \brief free array of kv_content_encoding_t
446 * \param encodings pointer to array
447 * \param numencodings number of encodings in array
449 static void
450 demux_mkv_free_encodings(mkv_content_encoding_t *encodings, int numencodings)
452 while (numencodings-- > 0)
453 free(encodings[numencodings].comp_settings);
454 free(encodings);
457 static int
458 demux_mkv_read_trackencodings (demuxer_t *demuxer, mkv_track_t *track)
460 stream_t *s = demuxer->stream;
461 mkv_content_encoding_t *ce, e;
462 uint64_t len, length, l;
463 int il, n;
465 ce = malloc (sizeof (*ce));
466 n = 0;
468 len = length = ebml_read_length (s, &il);
469 len += il;
470 while (length > 0)
472 switch (ebml_read_id (s, &il))
474 case MATROSKA_ID_CONTENTENCODING:
476 uint64_t len;
477 int i;
479 memset (&e, 0, sizeof (e));
480 e.scope = 1;
482 len = ebml_read_length (s, &i);
483 l = len + i;
485 while (len > 0)
487 uint64_t num, l;
488 int il;
490 switch (ebml_read_id (s, &il))
492 case MATROSKA_ID_CONTENTENCODINGORDER:
493 num = ebml_read_uint (s, &l);
494 if (num == EBML_UINT_INVALID)
495 goto err_out;
496 e.order = num;
497 break;
499 case MATROSKA_ID_CONTENTENCODINGSCOPE:
500 num = ebml_read_uint (s, &l);
501 if (num == EBML_UINT_INVALID)
502 goto err_out;
503 e.scope = num;
504 break;
506 case MATROSKA_ID_CONTENTENCODINGTYPE:
507 num = ebml_read_uint (s, &l);
508 if (num == EBML_UINT_INVALID)
509 goto err_out;
510 e.type = num;
511 break;
513 case MATROSKA_ID_CONTENTCOMPRESSION:
515 uint64_t le;
517 le = ebml_read_length (s, &i);
518 l = le + i;
520 while (le > 0)
522 uint64_t l;
523 int il;
525 switch (ebml_read_id (s, &il))
527 case MATROSKA_ID_CONTENTCOMPALGO:
528 num = ebml_read_uint (s, &l);
529 if (num == EBML_UINT_INVALID)
530 goto err_out;
531 e.comp_algo = num;
532 break;
534 case MATROSKA_ID_CONTENTCOMPSETTINGS:
535 l = ebml_read_length (s, &i);
536 e.comp_settings = malloc (l);
537 stream_read (s, e.comp_settings, l);
538 e.comp_settings_len = l;
539 l += i;
540 break;
542 default:
543 ebml_read_skip (s, &l);
544 break;
546 le -= l + il;
549 if (e.type == 1)
551 mp_msg(MSGT_DEMUX, MSGL_WARN,
552 MSGTR_MPDEMUX_MKV_TrackEncrypted, track->tnum);
554 else if (e.type != 0)
556 mp_msg(MSGT_DEMUX, MSGL_WARN,
557 MSGTR_MPDEMUX_MKV_UnknownContentEncoding, track->tnum);
560 if (e.comp_algo != 0 && e.comp_algo != 2)
562 mp_msg (MSGT_DEMUX, MSGL_WARN,
563 MSGTR_MPDEMUX_MKV_UnknownCompression,
564 track->tnum, e.comp_algo);
566 #if !CONFIG_ZLIB
567 else if (e.comp_algo == 0)
569 mp_msg (MSGT_DEMUX, MSGL_WARN,
570 MSGTR_MPDEMUX_MKV_ZlibCompressionUnsupported,
571 track->tnum);
573 #endif
575 break;
578 default:
579 ebml_read_skip (s, &l);
580 break;
582 len -= l + il;
584 for (i=0; i<n; i++)
585 if (e.order <= ce[i].order)
586 break;
587 ce = realloc (ce, (n+1) *sizeof (*ce));
588 memmove (ce+i+1, ce+i, (n-i) * sizeof (*ce));
589 memcpy (ce+i, &e, sizeof (e));
590 n++;
591 break;
594 default:
595 ebml_read_skip (s, &l);
596 break;
599 length -= l + il;
602 track->encodings = ce;
603 track->num_encodings = n;
604 return len;
606 err_out:
607 demux_mkv_free_encodings(ce, n);
608 return 0;
611 static int
612 demux_mkv_read_trackaudio (demuxer_t *demuxer, mkv_track_t *track)
614 stream_t *s = demuxer->stream;
615 uint64_t len, length, l;
616 int il;
618 track->a_sfreq = 8000.0;
619 track->a_channels = 1;
621 len = length = ebml_read_length (s, &il);
622 len += il;
623 while (length > 0)
625 switch (ebml_read_id (s, &il))
627 case MATROSKA_ID_AUDIOSAMPLINGFREQ:
629 long double num = ebml_read_float (s, &l);
630 if (num == EBML_FLOAT_INVALID)
631 return 0;
632 track->a_sfreq = num;
633 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Sampling frequency: %f\n",
634 track->a_sfreq);
635 break;
638 case MATROSKA_ID_AUDIOBITDEPTH:
640 uint64_t num = ebml_read_uint (s, &l);
641 if (num == EBML_UINT_INVALID)
642 return 0;
643 track->a_bps = num;
644 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Bit depth: %u\n",
645 track->a_bps);
646 break;
649 case MATROSKA_ID_AUDIOCHANNELS:
651 uint64_t num = ebml_read_uint (s, &l);
652 if (num == EBML_UINT_INVALID)
653 return 0;
654 track->a_channels = num;
655 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Channels: %u\n",
656 track->a_channels);
657 break;
660 default:
661 ebml_read_skip (s, &l);
662 break;
664 length -= l + il;
666 return len;
669 static int
670 demux_mkv_read_trackvideo (demuxer_t *demuxer, mkv_track_t *track)
672 stream_t *s = demuxer->stream;
673 uint64_t len, length, l;
674 int il;
676 len = length = ebml_read_length (s, &il);
677 len += il;
678 while (length > 0)
680 switch (ebml_read_id (s, &il))
682 case MATROSKA_ID_VIDEOFRAMERATE:
684 long double num = ebml_read_float (s, &l);
685 if (num == EBML_FLOAT_INVALID)
686 return 0;
687 track->v_frate = num;
688 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Frame rate: %f\n",
689 track->v_frate);
690 if (track->v_frate > 0)
691 track->default_duration = 1 / track->v_frate;
692 break;
695 case MATROSKA_ID_VIDEODISPLAYWIDTH:
697 uint64_t num = ebml_read_uint (s, &l);
698 if (num == EBML_UINT_INVALID)
699 return 0;
700 track->v_dwidth = num;
701 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Display width: %u\n",
702 track->v_dwidth);
703 break;
706 case MATROSKA_ID_VIDEODISPLAYHEIGHT:
708 uint64_t num = ebml_read_uint (s, &l);
709 if (num == EBML_UINT_INVALID)
710 return 0;
711 track->v_dheight = num;
712 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Display height: %u\n",
713 track->v_dheight);
714 break;
717 case MATROSKA_ID_VIDEOPIXELWIDTH:
719 uint64_t num = ebml_read_uint (s, &l);
720 if (num == EBML_UINT_INVALID)
721 return 0;
722 track->v_width = num;
723 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Pixel width: %u\n",
724 track->v_width);
725 break;
728 case MATROSKA_ID_VIDEOPIXELHEIGHT:
730 uint64_t num = ebml_read_uint (s, &l);
731 if (num == EBML_UINT_INVALID)
732 return 0;
733 track->v_height = num;
734 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Pixel height: %u\n",
735 track->v_height);
736 break;
739 default:
740 ebml_read_skip (s, &l);
741 break;
743 length -= l + il;
745 return len;
749 * \brief free any data associated with given track
750 * \param track track of which to free data
752 static void
753 demux_mkv_free_trackentry(mkv_track_t *track) {
754 free (track->name);
755 free (track->codec_id);
756 free (track->language);
757 free (track->private_data);
758 free (track->audio_buf);
759 free (track->audio_timestamp);
760 demux_mkv_free_encodings(track->encodings, track->num_encodings);
761 free(track);
764 static int
765 demux_mkv_read_trackentry (demuxer_t *demuxer)
767 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
768 stream_t *s = demuxer->stream;
769 mkv_track_t *track;
770 uint64_t len, length, l;
771 int il;
773 track = calloc (1, sizeof (*track));
774 /* set default values */
775 track->default_track = 1;
776 track->name = 0;
777 track->language = strdup("eng");
779 len = length = ebml_read_length (s, &il);
780 len += il;
781 while (length > 0)
783 switch (ebml_read_id (s, &il))
785 case MATROSKA_ID_TRACKNUMBER:
787 uint64_t num = ebml_read_uint (s, &l);
788 if (num == EBML_UINT_INVALID)
789 goto err_out;
790 track->tnum = num;
791 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Track number: %u\n",
792 track->tnum);
793 break;
796 case MATROSKA_ID_TRACKNAME:
798 track->name = ebml_read_utf8 (s, &l);
799 if (track->name == NULL)
800 goto err_out;
801 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Name: %s\n",
802 track->name);
803 break;
806 case MATROSKA_ID_TRACKTYPE:
808 uint64_t num = ebml_read_uint (s, &l);
809 if (num == EBML_UINT_INVALID)
810 return 0;
811 track->type = num;
812 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Track type: ");
813 switch (track->type)
815 case MATROSKA_TRACK_AUDIO:
816 mp_msg (MSGT_DEMUX, MSGL_V, "Audio\n");
817 break;
818 case MATROSKA_TRACK_VIDEO:
819 mp_msg (MSGT_DEMUX, MSGL_V, "Video\n");
820 break;
821 case MATROSKA_TRACK_SUBTITLE:
822 mp_msg (MSGT_DEMUX, MSGL_V, "Subtitle\n");
823 break;
824 default:
825 mp_msg (MSGT_DEMUX, MSGL_V, "unknown\n");
826 break;
828 break;
831 case MATROSKA_ID_TRACKAUDIO:
832 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Audio track\n");
833 l = demux_mkv_read_trackaudio (demuxer, track);
834 if (l == 0)
835 goto err_out;
836 break;
838 case MATROSKA_ID_TRACKVIDEO:
839 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Video track\n");
840 l = demux_mkv_read_trackvideo (demuxer, track);
841 if (l == 0)
842 goto err_out;
843 break;
845 case MATROSKA_ID_CODECID:
846 track->codec_id = ebml_read_ascii (s, &l);
847 if (track->codec_id == NULL)
848 goto err_out;
849 if (!strcmp (track->codec_id, MKV_V_MSCOMP) ||
850 !strcmp (track->codec_id, MKV_A_ACM))
851 track->ms_compat = 1;
852 else if (!strcmp (track->codec_id, MKV_S_VOBSUB))
853 track->subtitle_type = MATROSKA_SUBTYPE_VOBSUB;
854 else if (!strcmp (track->codec_id, MKV_S_TEXTSSA)
855 || !strcmp (track->codec_id, MKV_S_TEXTASS)
856 || !strcmp (track->codec_id, MKV_S_SSA)
857 || !strcmp (track->codec_id, MKV_S_ASS))
859 track->subtitle_type = MATROSKA_SUBTYPE_SSA;
861 else if (!strcmp (track->codec_id, MKV_S_TEXTASCII))
862 track->subtitle_type = MATROSKA_SUBTYPE_TEXT;
863 if (!strcmp (track->codec_id, MKV_S_TEXTUTF8))
865 track->subtitle_type = MATROSKA_SUBTYPE_TEXT;
867 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Codec ID: %s\n",
868 track->codec_id);
869 break;
871 case MATROSKA_ID_CODECPRIVATE:
873 int x;
874 uint64_t num = ebml_read_length (s, &x);
875 // audit: cheap guard against overflows later..
876 if (num > SIZE_MAX - 1000) return 0;
877 l = x + num;
878 track->private_data = malloc (num + AV_LZO_INPUT_PADDING);
879 if (stream_read(s, track->private_data, num) != (int) num)
880 goto err_out;
881 track->private_size = num;
882 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + CodecPrivate, length "
883 "%u\n", track->private_size);
884 break;
887 case MATROSKA_ID_TRACKLANGUAGE:
888 free(track->language);
889 track->language = ebml_read_utf8 (s, &l);
890 if (track->language == NULL)
891 goto err_out;
892 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Language: %s\n",
893 track->language);
894 break;
896 case MATROSKA_ID_TRACKFLAGDEFAULT:
898 uint64_t num = ebml_read_uint (s, &l);
899 if (num == EBML_UINT_INVALID)
900 goto err_out;
901 track->default_track = num;
902 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Default flag: %u\n",
903 track->default_track);
904 break;
907 case MATROSKA_ID_TRACKDEFAULTDURATION:
909 uint64_t num = ebml_read_uint (s, &l);
910 if (num == EBML_UINT_INVALID)
911 goto err_out;
912 if (num == 0)
913 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Default duration: 0");
914 else
916 track->v_frate = 1000000000.0 / num;
917 track->default_duration = num / 1000000000.0;
918 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Default duration: "
919 "%.3fms ( = %.3f fps)\n",num/1000000.0,track->v_frate);
921 break;
924 case MATROSKA_ID_TRACKENCODINGS:
925 l = demux_mkv_read_trackencodings (demuxer, track);
926 if (l == 0)
927 goto err_out;
928 break;
930 default:
931 ebml_read_skip (s, &l);
932 break;
934 length -= l + il;
937 mkv_d->tracks[mkv_d->num_tracks++] = track;
938 return len;
940 err_out:
941 demux_mkv_free_trackentry(track);
942 return 0;
945 static int
946 demux_mkv_read_tracks (demuxer_t *demuxer)
948 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
949 stream_t *s = demuxer->stream;
950 uint64_t length, l;
951 int il;
953 mkv_d->tracks = malloc (sizeof (*mkv_d->tracks));
954 mkv_d->num_tracks = 0;
956 length = ebml_read_length (s, NULL);
957 while (length > 0)
959 switch (ebml_read_id (s, &il))
961 case MATROSKA_ID_TRACKENTRY:
962 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + a track...\n");
963 mkv_d->tracks = realloc (mkv_d->tracks,
964 (mkv_d->num_tracks+1)
965 *sizeof (*mkv_d->tracks));
966 l = demux_mkv_read_trackentry (demuxer);
967 if (l == 0)
968 return 1;
969 break;
971 default:
972 ebml_read_skip (s, &l);
973 break;
975 length -= l + il;
977 return 0;
980 static int
981 demux_mkv_read_cues (demuxer_t *demuxer)
983 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
984 stream_t *s = demuxer->stream;
985 uint64_t length, l, time, track, pos;
986 off_t off;
987 int i, il;
989 if (index_mode == 0) {
990 ebml_read_skip (s, NULL);
991 return 0;
993 off = stream_tell (s);
994 for (i=0; i<mkv_d->parsed_cues_num; i++)
995 if (mkv_d->parsed_cues[i] == off)
997 ebml_read_skip (s, NULL);
998 return 0;
1000 mkv_d->parsed_cues = realloc (mkv_d->parsed_cues,
1001 (mkv_d->parsed_cues_num+1)
1002 * sizeof (off_t));
1003 mkv_d->parsed_cues[mkv_d->parsed_cues_num++] = off;
1005 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] /---- [ parsing cues ] -----------\n");
1006 length = ebml_read_length (s, NULL);
1008 while (length > 0)
1010 time = track = pos = EBML_UINT_INVALID;
1012 switch (ebml_read_id (s, &il))
1014 case MATROSKA_ID_POINTENTRY:
1016 uint64_t len;
1018 len = ebml_read_length (s, &i);
1019 l = len + i;
1021 while (len > 0)
1023 uint64_t l;
1024 int il;
1026 switch (ebml_read_id (s, &il))
1028 case MATROSKA_ID_CUETIME:
1029 time = ebml_read_uint (s, &l);
1030 break;
1032 case MATROSKA_ID_CUETRACKPOSITION:
1034 uint64_t le;
1036 le = ebml_read_length (s, &i);
1037 l = le + i;
1039 while (le > 0)
1041 uint64_t l;
1042 int il;
1044 switch (ebml_read_id (s, &il))
1046 case MATROSKA_ID_CUETRACK:
1047 track = ebml_read_uint (s, &l);
1048 break;
1050 case MATROSKA_ID_CUECLUSTERPOSITION:
1051 pos = ebml_read_uint (s, &l);
1052 break;
1054 default:
1055 ebml_read_skip (s, &l);
1056 break;
1058 le -= l + il;
1060 break;
1063 default:
1064 ebml_read_skip (s, &l);
1065 break;
1067 len -= l + il;
1069 break;
1072 default:
1073 ebml_read_skip (s, &l);
1074 break;
1077 length -= l + il;
1079 if (time != EBML_UINT_INVALID && track != EBML_UINT_INVALID
1080 && pos != EBML_UINT_INVALID)
1082 grow_array(&mkv_d->indexes, mkv_d->num_indexes, sizeof(mkv_index_t));
1083 mkv_d->indexes[mkv_d->num_indexes].tnum = track;
1084 mkv_d->indexes[mkv_d->num_indexes].timecode = time;
1085 mkv_d->indexes[mkv_d->num_indexes].filepos =mkv_d->segment_start+pos;
1086 mp_msg (MSGT_DEMUX, MSGL_DBG2, "[mkv] |+ found cue point "
1087 "for track %"PRIu64": timecode %"PRIu64", filepos: %"PRIu64"\n",
1088 track, time, mkv_d->segment_start + pos);
1089 mkv_d->num_indexes++;
1093 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] \\---- [ parsing cues ] -----------\n");
1094 return 0;
1097 static int
1098 demux_mkv_read_chapters (demuxer_t *demuxer)
1100 stream_t *s = demuxer->stream;
1101 uint64_t length, l;
1102 int il;
1104 if (demuxer->chapters)
1106 ebml_read_skip (s, NULL);
1107 return 0;
1110 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] /---- [ parsing chapters ] ---------\n");
1111 length = ebml_read_length (s, NULL);
1113 while (length > 0)
1115 switch (ebml_read_id (s, &il))
1117 case MATROSKA_ID_EDITIONENTRY:
1119 uint64_t len;
1120 int i;
1122 len = ebml_read_length (s, &i);
1123 l = len + i;
1125 while (len > 0)
1127 uint64_t l;
1128 int il;
1130 switch (ebml_read_id (s, &il))
1132 case MATROSKA_ID_CHAPTERATOM:
1134 uint64_t len, start=0, end=0;
1135 char* name = 0;
1136 int i;
1137 int cid;
1139 len = ebml_read_length (s, &i);
1140 l = len + i;
1142 while (len > 0)
1144 uint64_t l;
1145 int il;
1147 switch (ebml_read_id (s, &il))
1149 case MATROSKA_ID_CHAPTERTIMESTART:
1150 start = ebml_read_uint (s, &l) / 1000000;
1151 break;
1153 case MATROSKA_ID_CHAPTERTIMEEND:
1154 end = ebml_read_uint (s, &l) / 1000000;
1155 break;
1157 case MATROSKA_ID_CHAPTERDISPLAY:
1159 uint64_t len;
1160 int i;
1162 len = ebml_read_length (s, &i);
1163 l = len + i;
1164 while (len > 0)
1166 uint64_t l;
1167 int il;
1169 switch (ebml_read_id (s, &il))
1171 case MATROSKA_ID_CHAPSTRING:
1172 name = ebml_read_utf8 (s, &l);
1173 break;
1174 default:
1175 ebml_read_skip (s, &l);
1176 break;
1178 len -= l + il;
1181 break;
1183 default:
1184 ebml_read_skip (s, &l);
1185 break;
1187 len -= l + il;
1190 if (!name)
1191 name = strdup("(unnamed)");
1193 cid = demuxer_add_chapter(demuxer, name, start, end);
1195 mp_msg(MSGT_DEMUX, MSGL_V,
1196 "[mkv] Chapter %u from %02d:%02d:%02d."
1197 "%03d to %02d:%02d:%02d.%03d, %s\n",
1198 cid,
1199 (int) (start / 60 / 60 / 1000),
1200 (int) ((start / 60 / 1000) % 60),
1201 (int) ((start / 1000) % 60),
1202 (int) (start % 1000),
1203 (int) (end / 60 / 60 / 1000),
1204 (int) ((end / 60 / 1000) % 60),
1205 (int) ((end / 1000) % 60),
1206 (int) (end % 1000), name);
1208 free(name);
1209 break;
1212 default:
1213 ebml_read_skip (s, &l);
1214 break;
1216 len -= l + il;
1218 break;
1221 default:
1222 ebml_read_skip (s, &l);
1223 break;
1226 length -= l + il;
1229 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] \\---- [ parsing chapters ] ---------\n");
1230 return 0;
1233 static int
1234 demux_mkv_read_tags (demuxer_t *demuxer)
1236 ebml_read_skip (demuxer->stream, NULL);
1237 return 0;
1240 static int
1241 demux_mkv_read_attachments (demuxer_t *demuxer)
1243 stream_t *s = demuxer->stream;
1244 uint64_t length, l;
1245 int il;
1247 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] /---- [ parsing attachments ] ---------\n");
1248 length = ebml_read_length (s, NULL);
1250 while (length > 0)
1252 switch (ebml_read_id (s, &il))
1254 case MATROSKA_ID_ATTACHEDFILE:
1256 uint64_t len;
1257 int i;
1258 char* name = NULL;
1259 char* mime = NULL;
1260 char* data = NULL;
1261 int data_size = 0;
1263 len = ebml_read_length (s, &i);
1264 l = len + i;
1266 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + an attachment...\n");
1268 while (len > 0)
1270 uint64_t l;
1271 int il;
1273 switch (ebml_read_id (s, &il))
1275 case MATROSKA_ID_FILENAME:
1276 name = ebml_read_utf8 (s, &l);
1277 if (name == NULL)
1278 return 0;
1279 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + FileName: %s\n",
1280 name);
1281 break;
1283 case MATROSKA_ID_FILEMIMETYPE:
1284 mime = ebml_read_ascii (s, &l);
1285 if (mime == NULL)
1286 return 0;
1287 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + FileMimeType: %s\n",
1288 mime);
1289 break;
1291 case MATROSKA_ID_FILEDATA:
1293 int x;
1294 uint64_t num = ebml_read_length (s, &x);
1295 l = x + num;
1296 free(data);
1297 data = malloc (num);
1298 if (stream_read(s, data, num) != (int) num)
1300 free(data);
1301 return 0;
1303 data_size = num;
1304 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + FileData, length "
1305 "%u\n", data_size);
1306 break;
1309 default:
1310 ebml_read_skip (s, &l);
1311 break;
1313 len -= l + il;
1316 demuxer_add_attachment(demuxer, name, mime, data, data_size);
1317 mp_msg(MSGT_DEMUX, MSGL_V,
1318 "[mkv] Attachment: %s, %s, %u bytes\n",
1319 name, mime, data_size);
1320 break;
1323 default:
1324 ebml_read_skip (s, &l);
1325 break;
1327 length -= l + il;
1330 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] \\---- [ parsing attachments ] ---------\n");
1331 return 0;
1334 static int
1335 demux_mkv_read_seekhead (demuxer_t *demuxer)
1337 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
1338 stream_t *s = demuxer->stream;
1339 uint64_t length, l, seek_pos, saved_pos, num;
1340 uint32_t seek_id;
1341 int i, il, res = 0;
1342 off_t off;
1344 off = stream_tell (s);
1345 for (i=0; i<mkv_d->parsed_seekhead_num; i++)
1346 if (mkv_d->parsed_seekhead[i] == off)
1348 ebml_read_skip (s, NULL);
1349 return 0;
1351 mkv_d->parsed_seekhead = realloc (mkv_d->parsed_seekhead,
1352 (mkv_d->parsed_seekhead_num+1)
1353 * sizeof (off_t));
1354 mkv_d->parsed_seekhead[mkv_d->parsed_seekhead_num++] = off;
1356 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] /---- [ parsing seek head ] ---------\n");
1357 length = ebml_read_length (s, NULL);
1358 /* off now holds the position of the next element after the seek head. */
1359 off = stream_tell (s) + length;
1360 while (length > 0 && !res)
1363 seek_id = 0;
1364 seek_pos = EBML_UINT_INVALID;
1366 switch (ebml_read_id (s, &il))
1368 case MATROSKA_ID_SEEKENTRY:
1370 uint64_t len;
1372 len = ebml_read_length (s, &i);
1373 l = len + i;
1375 while (len > 0)
1377 uint64_t l;
1378 int il;
1380 switch (ebml_read_id (s, &il))
1382 case MATROSKA_ID_SEEKID:
1383 num = ebml_read_uint (s, &l);
1384 if (num != EBML_UINT_INVALID)
1385 seek_id = num;
1386 break;
1388 case MATROSKA_ID_SEEKPOSITION:
1389 seek_pos = ebml_read_uint (s, &l);
1390 break;
1392 default:
1393 ebml_read_skip (s, &l);
1394 break;
1396 len -= l + il;
1399 break;
1402 default:
1403 ebml_read_skip (s, &l);
1404 break;
1406 length -= l + il;
1408 if (seek_id == 0 || seek_id == MATROSKA_ID_CLUSTER
1409 || seek_pos == EBML_UINT_INVALID ||
1410 ((mkv_d->segment_start + seek_pos) >= (uint64_t)demuxer->movi_end))
1411 continue;
1413 saved_pos = stream_tell (s);
1414 if (!stream_seek (s, mkv_d->segment_start + seek_pos))
1415 res = 1;
1416 else
1418 if (ebml_read_id (s, &il) != seek_id)
1419 res = 1;
1420 else
1421 switch (seek_id)
1423 case MATROSKA_ID_CUES:
1424 if (demux_mkv_read_cues (demuxer))
1425 res = 1;
1426 break;
1428 case MATROSKA_ID_TAGS:
1429 if (demux_mkv_read_tags (demuxer))
1430 res = 1;
1431 break;
1433 case MATROSKA_ID_SEEKHEAD:
1434 if (demux_mkv_read_seekhead (demuxer))
1435 res = 1;
1436 break;
1438 case MATROSKA_ID_CHAPTERS:
1439 if (demux_mkv_read_chapters (demuxer))
1440 res = 1;
1441 break;
1445 stream_seek (s, saved_pos);
1447 if (res)
1449 /* If there was an error then try to skip this seek head. */
1450 if (stream_seek (s, off))
1451 res = 0;
1453 else
1454 if (length > 0)
1455 stream_seek (s, stream_tell (s) + length);
1456 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] \\---- [ parsing seek head ] ---------\n");
1457 return res;
1460 static int
1461 demux_mkv_open_video (demuxer_t *demuxer, mkv_track_t *track, int vid);
1462 static int
1463 demux_mkv_open_audio (demuxer_t *demuxer, mkv_track_t *track, int aid);
1464 static int
1465 demux_mkv_open_sub (demuxer_t *demuxer, mkv_track_t *track, int sid);
1467 static void
1468 display_create_tracks (demuxer_t *demuxer)
1470 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *)demuxer->priv;
1471 int i, vid=0, aid=0, sid=0;
1473 for (i=0; i<mkv_d->num_tracks; i++)
1475 char *type = "unknown", str[32];
1476 *str = '\0';
1477 switch (mkv_d->tracks[i]->type)
1479 case MATROSKA_TRACK_VIDEO:
1480 type = "video";
1481 demux_mkv_open_video(demuxer, mkv_d->tracks[i], vid);
1482 if (mkv_d->tracks[i]->name)
1483 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VID_%d_NAME=%s\n", vid, mkv_d->tracks[i]->name);
1484 sprintf (str, "-vid %u", vid++);
1485 break;
1486 case MATROSKA_TRACK_AUDIO:
1487 type = "audio";
1488 demux_mkv_open_audio(demuxer, mkv_d->tracks[i], aid);
1489 if (mkv_d->tracks[i]->name)
1490 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AID_%d_NAME=%s\n", aid, mkv_d->tracks[i]->name);
1491 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AID_%d_LANG=%s\n", aid, mkv_d->tracks[i]->language);
1492 sprintf (str, "-aid %u, -alang %.5s",aid++,mkv_d->tracks[i]->language);
1493 break;
1494 case MATROSKA_TRACK_SUBTITLE:
1495 type = "subtitles";
1496 demux_mkv_open_sub(demuxer, mkv_d->tracks[i], sid);
1497 if (mkv_d->tracks[i]->name)
1498 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SID_%d_NAME=%s\n", sid, mkv_d->tracks[i]->name);
1499 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SID_%d_LANG=%s\n", sid, mkv_d->tracks[i]->language);
1500 sprintf (str, "-sid %u, -slang %.5s",sid++,mkv_d->tracks[i]->language);
1501 break;
1503 if (mkv_d->tracks[i]->name)
1504 mp_msg(MSGT_DEMUX, MSGL_INFO, MSGTR_MPDEMUX_MKV_TrackIDName,
1505 mkv_d->tracks[i]->tnum, type, mkv_d->tracks[i]->codec_id, mkv_d->tracks[i]->name, str);
1506 else
1507 mp_msg(MSGT_DEMUX, MSGL_INFO, MSGTR_MPDEMUX_MKV_TrackID,
1508 mkv_d->tracks[i]->tnum, type, mkv_d->tracks[i]->codec_id, str);
1512 typedef struct {
1513 char *id;
1514 int fourcc;
1515 int extradata;
1516 } videocodec_info_t;
1518 static const videocodec_info_t vinfo[] = {
1519 { MKV_V_MPEG1, mmioFOURCC('m', 'p', 'g', '1'), 0 },
1520 { MKV_V_MPEG2, mmioFOURCC('m', 'p', 'g', '2'), 0 },
1521 { MKV_V_MPEG4_SP, mmioFOURCC('m', 'p', '4', 'v'), 1 },
1522 { MKV_V_MPEG4_ASP, mmioFOURCC('m', 'p', '4', 'v'), 1 },
1523 { MKV_V_MPEG4_AP, mmioFOURCC('m', 'p', '4', 'v'), 1 },
1524 { MKV_V_MPEG4_AVC, mmioFOURCC('a', 'v', 'c', '1'), 1 },
1525 { MKV_V_THEORA, mmioFOURCC('t', 'h', 'e', 'o'), 1 },
1526 { NULL, 0, 0 }
1529 static int
1530 demux_mkv_open_video (demuxer_t *demuxer, mkv_track_t *track, int vid)
1532 BITMAPINFOHEADER *bih;
1533 void *ImageDesc = NULL;
1534 sh_video_t *sh_v;
1536 if (track->ms_compat) /* MS compatibility mode */
1538 BITMAPINFOHEADER *src;
1540 if (track->private_data == NULL
1541 || track->private_size < sizeof (BITMAPINFOHEADER))
1542 return 1;
1544 src = (BITMAPINFOHEADER *) track->private_data;
1545 bih = calloc (1, track->private_size);
1546 bih->biSize = le2me_32 (src->biSize);
1547 bih->biWidth = le2me_32 (src->biWidth);
1548 bih->biHeight = le2me_32 (src->biHeight);
1549 bih->biPlanes = le2me_16 (src->biPlanes);
1550 bih->biBitCount = le2me_16 (src->biBitCount);
1551 bih->biCompression = le2me_32 (src->biCompression);
1552 bih->biSizeImage = le2me_32 (src->biSizeImage);
1553 bih->biXPelsPerMeter = le2me_32 (src->biXPelsPerMeter);
1554 bih->biYPelsPerMeter = le2me_32 (src->biYPelsPerMeter);
1555 bih->biClrUsed = le2me_32 (src->biClrUsed);
1556 bih->biClrImportant = le2me_32 (src->biClrImportant);
1557 memcpy((char *) bih + sizeof (BITMAPINFOHEADER),
1558 (char *) src + sizeof (BITMAPINFOHEADER),
1559 track->private_size - sizeof (BITMAPINFOHEADER));
1561 if (track->v_width == 0)
1562 track->v_width = bih->biWidth;
1563 if (track->v_height == 0)
1564 track->v_height = bih->biHeight;
1566 else
1568 bih = calloc (1, sizeof (BITMAPINFOHEADER));
1569 bih->biSize = sizeof (BITMAPINFOHEADER);
1570 bih->biWidth = track->v_width;
1571 bih->biHeight = track->v_height;
1572 bih->biBitCount = 24;
1573 bih->biSizeImage = bih->biWidth * bih->biHeight * bih->biBitCount/8;
1575 if (track->private_size >= RVPROPERTIES_SIZE
1576 && (!strcmp (track->codec_id, MKV_V_REALV10)
1577 || !strcmp (track->codec_id, MKV_V_REALV20)
1578 || !strcmp (track->codec_id, MKV_V_REALV30)
1579 || !strcmp (track->codec_id, MKV_V_REALV40)))
1581 unsigned char *dst, *src;
1582 uint32_t type2;
1583 unsigned int cnt;
1585 src = track->private_data + RVPROPERTIES_SIZE;
1587 cnt = track->private_size - RVPROPERTIES_SIZE;
1588 bih = realloc(bih, sizeof (BITMAPINFOHEADER)+8+cnt);
1589 bih->biSize = 48+cnt;
1590 bih->biPlanes = 1;
1591 type2 = AV_RB32(src - 4);
1592 if (type2 == 0x10003000 || type2 == 0x10003001)
1593 bih->biCompression=mmioFOURCC('R','V','1','3');
1594 else
1595 bih->biCompression=mmioFOURCC('R','V',track->codec_id[9],'0');
1596 dst = (unsigned char *) (bih + 1);
1597 // copy type1 and type2 info from rv properties
1598 memcpy(dst, src - 8, 8);
1599 stream_read(demuxer->stream, dst+8, cnt);
1600 track->realmedia = 1;
1602 #ifdef CONFIG_QTX_CODECS
1604 else if (track->private_size >= sizeof (ImageDescription)
1605 && !strcmp(track->codec_id, MKV_V_QUICKTIME))
1607 ImageDescriptionPtr idesc;
1609 idesc = (ImageDescriptionPtr) track->private_data;
1610 idesc->idSize = be2me_32 (idesc->idSize);
1611 idesc->cType = be2me_32 (idesc->cType);
1612 idesc->version = be2me_16 (idesc->version);
1613 idesc->revisionLevel = be2me_16 (idesc->revisionLevel);
1614 idesc->vendor = be2me_32 (idesc->vendor);
1615 idesc->temporalQuality = be2me_32 (idesc->temporalQuality);
1616 idesc->spatialQuality = be2me_32 (idesc->spatialQuality);
1617 idesc->width = be2me_16 (idesc->width);
1618 idesc->height = be2me_16 (idesc->height);
1619 idesc->hRes = be2me_32 (idesc->hRes);
1620 idesc->vRes = be2me_32 (idesc->vRes);
1621 idesc->dataSize = be2me_32 (idesc->dataSize);
1622 idesc->frameCount = be2me_16 (idesc->frameCount);
1623 idesc->depth = be2me_16 (idesc->depth);
1624 idesc->clutID = be2me_16 (idesc->clutID);
1625 bih->biPlanes = 1;
1626 bih->biCompression = idesc->cType;
1627 ImageDesc = idesc;
1628 #endif /* CONFIG_QTX_CODECS */
1631 else
1633 const videocodec_info_t *vi = vinfo;
1634 while (vi->id && strcmp(vi->id, track->codec_id)) vi++;
1635 bih->biCompression = vi->fourcc;
1636 if (vi->extradata && track->private_data && (track->private_size > 0))
1638 bih->biSize += track->private_size;
1639 bih = realloc (bih, bih->biSize);
1640 memcpy (bih + 1, track->private_data, track->private_size);
1642 track->reorder_timecodes = user_correct_pts == 0;
1643 if (!vi->id) {
1644 mp_msg (MSGT_DEMUX,MSGL_WARN, MSGTR_MPDEMUX_MKV_UnknownCodecID,
1645 track->codec_id, track->tnum);
1646 free(bih);
1647 return 1;
1652 sh_v = new_sh_video_vid (demuxer, track->tnum, vid);
1653 sh_v->bih = bih;
1654 sh_v->format = sh_v->bih->biCompression;
1655 if (track->v_frate == 0.0)
1656 track->v_frate = 25.0;
1657 sh_v->fps = track->v_frate;
1658 sh_v->frametime = 1 / track->v_frate;
1659 sh_v->aspect = 0;
1660 if (!track->realmedia)
1662 sh_v->disp_w = track->v_width;
1663 sh_v->disp_h = track->v_height;
1664 if (track->v_dheight)
1665 sh_v->aspect = (float)track->v_dwidth / (float)track->v_dheight;
1667 else
1669 // vd_realvid.c will set aspect to disp_w/disp_h and rederive
1670 // disp_w and disp_h from the RealVideo stream contents returned
1671 // by the Real DLLs. If DisplayWidth/DisplayHeight was not set in
1672 // the Matroska file then it has already been set to PixelWidth/Height
1673 // by check_track_information.
1674 sh_v->disp_w = track->v_dwidth;
1675 sh_v->disp_h = track->v_dheight;
1677 sh_v->ImageDesc = ImageDesc;
1678 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] Aspect: %f\n", sh_v->aspect);
1680 sh_v->ds = demuxer->video;
1681 return 0;
1684 static int
1685 demux_mkv_open_audio (demuxer_t *demuxer, mkv_track_t *track, int aid)
1687 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
1688 sh_audio_t *sh_a = new_sh_audio_aid(demuxer, track->tnum, aid);
1689 demux_packet_t *dp;
1690 if(!sh_a) return 1;
1691 mkv_d->audio_tracks[mkv_d->last_aid] = track->tnum;
1693 if (track->language && (strcmp(track->language, "und") != 0))
1694 sh_a->lang = strdup(track->language);
1695 sh_a->default_track = track->default_track;
1696 sh_a->ds = demuxer->audio;
1697 sh_a->wf = malloc (sizeof (WAVEFORMATEX));
1698 if (track->ms_compat && (track->private_size >= sizeof(WAVEFORMATEX)))
1700 WAVEFORMATEX *wf = (WAVEFORMATEX *)track->private_data;
1701 sh_a->wf = realloc(sh_a->wf, track->private_size);
1702 sh_a->wf->wFormatTag = le2me_16 (wf->wFormatTag);
1703 sh_a->wf->nChannels = le2me_16 (wf->nChannels);
1704 sh_a->wf->nSamplesPerSec = le2me_32 (wf->nSamplesPerSec);
1705 sh_a->wf->nAvgBytesPerSec = le2me_32 (wf->nAvgBytesPerSec);
1706 sh_a->wf->nBlockAlign = le2me_16 (wf->nBlockAlign);
1707 sh_a->wf->wBitsPerSample = le2me_16 (wf->wBitsPerSample);
1708 sh_a->wf->cbSize = track->private_size - sizeof(WAVEFORMATEX);
1709 memcpy(sh_a->wf + 1, wf + 1, track->private_size - sizeof(WAVEFORMATEX));
1710 if (track->a_sfreq == 0.0)
1711 track->a_sfreq = sh_a->wf->nSamplesPerSec;
1712 if (track->a_channels == 0)
1713 track->a_channels = sh_a->wf->nChannels;
1714 if (track->a_bps == 0)
1715 track->a_bps = sh_a->wf->wBitsPerSample;
1716 track->a_formattag = sh_a->wf->wFormatTag;
1718 else
1720 memset(sh_a->wf, 0, sizeof (WAVEFORMATEX));
1721 if (!strcmp(track->codec_id, MKV_A_MP3) ||
1722 !strcmp(track->codec_id, MKV_A_MP2))
1723 track->a_formattag = 0x0055;
1724 else if (!strncmp(track->codec_id, MKV_A_AC3, strlen(MKV_A_AC3)))
1725 track->a_formattag = 0x2000;
1726 else if (!strcmp(track->codec_id, MKV_A_DTS))
1727 track->a_formattag = 0x2001;
1728 else if (!strcmp(track->codec_id, MKV_A_PCM) ||
1729 !strcmp(track->codec_id, MKV_A_PCM_BE))
1730 track->a_formattag = 0x0001;
1731 else if (!strcmp(track->codec_id, MKV_A_AAC_2MAIN) ||
1732 !strncmp(track->codec_id, MKV_A_AAC_2LC,
1733 strlen(MKV_A_AAC_2LC)) ||
1734 !strcmp(track->codec_id, MKV_A_AAC_2SSR) ||
1735 !strcmp(track->codec_id, MKV_A_AAC_4MAIN) ||
1736 !strncmp(track->codec_id, MKV_A_AAC_4LC,
1737 strlen(MKV_A_AAC_4LC)) ||
1738 !strcmp(track->codec_id, MKV_A_AAC_4SSR) ||
1739 !strcmp(track->codec_id, MKV_A_AAC_4LTP) ||
1740 !strcmp(track->codec_id, MKV_A_AAC))
1741 track->a_formattag = mmioFOURCC('M', 'P', '4', 'A');
1742 else if (!strcmp(track->codec_id, MKV_A_VORBIS))
1744 if (track->private_data == NULL)
1745 return 1;
1746 track->a_formattag = mmioFOURCC('v', 'r', 'b', 's');
1748 else if (!strcmp(track->codec_id, MKV_A_QDMC))
1749 track->a_formattag = mmioFOURCC('Q', 'D', 'M', 'C');
1750 else if (!strcmp(track->codec_id, MKV_A_QDMC2))
1751 track->a_formattag = mmioFOURCC('Q', 'D', 'M', '2');
1752 else if (!strcmp(track->codec_id, MKV_A_WAVPACK))
1753 track->a_formattag = mmioFOURCC('W', 'V', 'P', 'K');
1754 else if (!strcmp(track->codec_id, MKV_A_FLAC))
1756 if (track->private_data == NULL || track->private_size == 0)
1758 mp_msg (MSGT_DEMUX, MSGL_WARN,
1759 MSGTR_MPDEMUX_MKV_FlacTrackDoesNotContainValidHeaders);
1760 return 1;
1762 track->a_formattag = mmioFOURCC ('f', 'L', 'a', 'C');
1764 else if (track->private_size >= RAPROPERTIES4_SIZE)
1766 if (!strcmp(track->codec_id, MKV_A_REAL28))
1767 track->a_formattag = mmioFOURCC('2', '8', '_', '8');
1768 else if (!strcmp(track->codec_id, MKV_A_REALATRC))
1769 track->a_formattag = mmioFOURCC('a', 't', 'r', 'c');
1770 else if (!strcmp(track->codec_id, MKV_A_REALCOOK))
1771 track->a_formattag = mmioFOURCC('c', 'o', 'o', 'k');
1772 else if (!strcmp(track->codec_id, MKV_A_REALDNET))
1773 track->a_formattag = mmioFOURCC('d', 'n', 'e', 't');
1774 else if (!strcmp(track->codec_id, MKV_A_REALSIPR))
1775 track->a_formattag = mmioFOURCC('s', 'i', 'p', 'r');
1777 else
1779 mp_msg (MSGT_DEMUX, MSGL_WARN, MSGTR_MPDEMUX_MKV_UnknownAudioCodec,
1780 track->codec_id, track->tnum);
1781 free_sh_audio(demuxer, track->tnum);
1782 return 1;
1786 sh_a->format = track->a_formattag;
1787 sh_a->wf->wFormatTag = track->a_formattag;
1788 sh_a->channels = track->a_channels;
1789 sh_a->wf->nChannels = track->a_channels;
1790 sh_a->samplerate = (uint32_t) track->a_sfreq;
1791 sh_a->wf->nSamplesPerSec = (uint32_t) track->a_sfreq;
1792 if (track->a_bps == 0)
1794 sh_a->samplesize = 2;
1795 sh_a->wf->wBitsPerSample = 16;
1797 else
1799 sh_a->samplesize = track->a_bps / 8;
1800 sh_a->wf->wBitsPerSample = track->a_bps;
1802 if (track->a_formattag == 0x0055) /* MP3 || MP2 */
1804 sh_a->wf->nAvgBytesPerSec = 16000;
1805 sh_a->wf->nBlockAlign = 1152;
1807 else if ((track->a_formattag == 0x2000) || /* AC3 */
1808 (track->a_formattag == 0x2001)) /* DTS */
1810 free(sh_a->wf);
1811 sh_a->wf = NULL;
1813 else if (track->a_formattag == 0x0001) /* PCM || PCM_BE */
1815 sh_a->wf->nAvgBytesPerSec = sh_a->channels * sh_a->samplerate*2;
1816 sh_a->wf->nBlockAlign = sh_a->wf->nAvgBytesPerSec;
1817 if (!strcmp(track->codec_id, MKV_A_PCM_BE))
1818 sh_a->format = mmioFOURCC('t', 'w', 'o', 's');
1820 else if (!strcmp(track->codec_id, MKV_A_QDMC) ||
1821 !strcmp(track->codec_id, MKV_A_QDMC2))
1823 sh_a->wf->nAvgBytesPerSec = 16000;
1824 sh_a->wf->nBlockAlign = 1486;
1825 track->fix_i_bps = 1;
1826 track->qt_last_a_pts = 0.0;
1827 if (track->private_data != NULL)
1829 sh_a->codecdata=malloc(track->private_size);
1830 memcpy (sh_a->codecdata, track->private_data,
1831 track->private_size);
1832 sh_a->codecdata_len = track->private_size;
1835 else if (track->a_formattag == mmioFOURCC('M', 'P', '4', 'A'))
1837 int profile, srate_idx;
1839 sh_a->wf->nAvgBytesPerSec = 16000;
1840 sh_a->wf->nBlockAlign = 1024;
1842 if (!strcmp (track->codec_id, MKV_A_AAC) &&
1843 (NULL != track->private_data))
1845 sh_a->codecdata=malloc(track->private_size);
1846 memcpy (sh_a->codecdata, track->private_data,
1847 track->private_size);
1848 sh_a->codecdata_len = track->private_size;
1849 return 0;
1852 /* Recreate the 'private data' */
1853 /* which faad2 uses in its initialization */
1854 srate_idx = aac_get_sample_rate_index (sh_a->samplerate);
1855 if (!strncmp (&track->codec_id[12], "MAIN", 4))
1856 profile = 0;
1857 else if (!strncmp (&track->codec_id[12], "LC", 2))
1858 profile = 1;
1859 else if (!strncmp (&track->codec_id[12], "SSR", 3))
1860 profile = 2;
1861 else
1862 profile = 3;
1863 sh_a->codecdata = malloc (5);
1864 sh_a->codecdata[0] = ((profile+1) << 3) | ((srate_idx&0xE) >> 1);
1865 sh_a->codecdata[1] = ((srate_idx&0x1)<<7)|(track->a_channels<<3);
1867 if (strstr(track->codec_id, "SBR") != NULL)
1869 /* HE-AAC (aka SBR AAC) */
1870 sh_a->codecdata_len = 5;
1872 sh_a->samplerate *= 2;
1873 sh_a->wf->nSamplesPerSec *= 2;
1874 srate_idx = aac_get_sample_rate_index(sh_a->samplerate);
1875 sh_a->codecdata[2] = AAC_SYNC_EXTENSION_TYPE >> 3;
1876 sh_a->codecdata[3] = ((AAC_SYNC_EXTENSION_TYPE&0x07)<<5) | 5;
1877 sh_a->codecdata[4] = (1 << 7) | (srate_idx << 3);
1878 track->default_duration = 1024.0 / (sh_a->samplerate / 2);
1880 else
1882 sh_a->codecdata_len = 2;
1883 track->default_duration = 1024.0 / (float)sh_a->samplerate;
1886 else if (track->a_formattag == mmioFOURCC('v', 'r', 'b', 's')) /* VORBIS */
1888 sh_a->wf->cbSize = track->private_size;
1889 sh_a->wf = realloc(sh_a->wf, sizeof(WAVEFORMATEX) + sh_a->wf->cbSize);
1890 memcpy((unsigned char *) (sh_a->wf+1), track->private_data, sh_a->wf->cbSize);
1892 else if (track->private_size >= RAPROPERTIES4_SIZE
1893 && !strncmp (track->codec_id, MKV_A_REALATRC, 7))
1895 /* Common initialization for all RealAudio codecs */
1896 unsigned char *src = track->private_data;
1897 int codecdata_length, version;
1898 int flavor;
1900 sh_a->wf->nAvgBytesPerSec = 0; /* FIXME !? */
1902 version = AV_RB16(src + 4);
1903 flavor = AV_RB16(src + 22);
1904 track->coded_framesize = AV_RB32(src + 24);
1905 track->sub_packet_h = AV_RB16(src + 40);
1906 sh_a->wf->nBlockAlign =
1907 track->audiopk_size = AV_RB16(src + 42);
1908 track->sub_packet_size = AV_RB16(src + 44);
1909 if (version == 4)
1911 src += RAPROPERTIES4_SIZE;
1912 src += src[0] + 1;
1913 src += src[0] + 1;
1915 else
1916 src += RAPROPERTIES5_SIZE;
1918 src += 3;
1919 if (version == 5)
1920 src++;
1921 codecdata_length = AV_RB32(src);
1922 src += 4;
1923 sh_a->wf->cbSize = codecdata_length;
1924 sh_a->wf = realloc (sh_a->wf,
1925 sizeof (WAVEFORMATEX) +
1926 sh_a->wf->cbSize);
1927 memcpy(((char *)(sh_a->wf + 1)), src, codecdata_length);
1929 switch (track->a_formattag) {
1930 case mmioFOURCC('a', 't', 'r', 'c'):
1931 sh_a->wf->nAvgBytesPerSec = atrc_fl2bps[flavor];
1932 sh_a->wf->nBlockAlign = track->sub_packet_size;
1933 track->audio_buf = malloc(track->sub_packet_h * track->audiopk_size);
1934 track->audio_timestamp = malloc(track->sub_packet_h * sizeof(float));
1935 break;
1936 case mmioFOURCC('c', 'o', 'o', 'k'):
1937 sh_a->wf->nAvgBytesPerSec = cook_fl2bps[flavor];
1938 sh_a->wf->nBlockAlign = track->sub_packet_size;
1939 track->audio_buf = malloc(track->sub_packet_h * track->audiopk_size);
1940 track->audio_timestamp = malloc(track->sub_packet_h * sizeof(float));
1941 break;
1942 case mmioFOURCC('s', 'i', 'p', 'r'):
1943 sh_a->wf->nAvgBytesPerSec = sipr_fl2bps[flavor];
1944 sh_a->wf->nBlockAlign = track->coded_framesize;
1945 track->audio_buf = malloc(track->sub_packet_h * track->audiopk_size);
1946 track->audio_timestamp = malloc(track->sub_packet_h * sizeof(float));
1947 break;
1948 case mmioFOURCC('2', '8', '_', '8'):
1949 sh_a->wf->nAvgBytesPerSec = 3600;
1950 sh_a->wf->nBlockAlign = track->coded_framesize;
1951 track->audio_buf = malloc(track->sub_packet_h * track->audiopk_size);
1952 track->audio_timestamp = malloc(track->sub_packet_h * sizeof(float));
1953 break;
1956 track->realmedia = 1;
1958 else if (!strcmp(track->codec_id, MKV_A_FLAC) ||
1959 (track->a_formattag == 0xf1ac))
1961 unsigned char *ptr;
1962 int size;
1963 free(sh_a->wf);
1964 sh_a->wf = NULL;
1966 if (track->a_formattag == mmioFOURCC('f', 'L', 'a', 'C'))
1968 ptr = (unsigned char *)track->private_data;
1969 size = track->private_size;
1971 else
1973 sh_a->format = mmioFOURCC('f', 'L', 'a', 'C');
1974 ptr = (unsigned char *) track->private_data
1975 + sizeof (WAVEFORMATEX);
1976 size = track->private_size - sizeof (WAVEFORMATEX);
1978 if (size < 4 || ptr[0] != 'f' || ptr[1] != 'L' ||
1979 ptr[2] != 'a' || ptr[3] != 'C')
1981 dp = new_demux_packet (4);
1982 memcpy (dp->buffer, "fLaC", 4);
1984 else
1986 dp = new_demux_packet (size);
1987 memcpy (dp->buffer, ptr, size);
1989 dp->pts = 0;
1990 dp->flags = 0;
1991 ds_add_packet (demuxer->audio, dp);
1993 else if (track->a_formattag == mmioFOURCC('W', 'V', 'P', 'K'))
1994 { /* do nothing, still works */ }
1995 else if (!track->ms_compat || (track->private_size < sizeof(WAVEFORMATEX)))
1997 free_sh_audio(demuxer, track->tnum);
1998 return 1;
2001 return 0;
2004 static int
2005 demux_mkv_open_sub (demuxer_t *demuxer, mkv_track_t *track, int sid)
2007 if (track->subtitle_type != MATROSKA_SUBTYPE_UNKNOWN)
2009 int size, m;
2010 uint8_t *buffer;
2011 sh_sub_t *sh = new_sh_sub_sid(demuxer, track->tnum, sid);
2012 track->sh_sub = sh;
2013 sh->type = 't';
2014 if (track->subtitle_type == MATROSKA_SUBTYPE_VOBSUB)
2015 sh->type = 'v';
2016 if (track->subtitle_type == MATROSKA_SUBTYPE_SSA)
2017 sh->type = 'a';
2018 size = track->private_size;
2019 m = demux_mkv_decode (track,track->private_data,&buffer,&size,2);
2020 if (buffer && m)
2022 free (track->private_data);
2023 track->private_data = buffer;
2024 track->private_size = size;
2026 sh->extradata=malloc(track->private_size);
2027 memcpy (sh->extradata, track->private_data,
2028 track->private_size);
2029 sh->extradata_len = track->private_size;
2030 if (track->language && (strcmp(track->language, "und") != 0))
2031 sh->lang = strdup(track->language);
2032 sh->default_track = track->default_track;
2034 else
2036 mp_msg (MSGT_DEMUX, MSGL_ERR, MSGTR_MPDEMUX_MKV_SubtitleTypeNotSupported,
2037 track->codec_id);
2038 return 1;
2041 return 0;
2044 static void demux_mkv_seek (demuxer_t *demuxer, float rel_seek_secs, float audio_delay, int flags);
2046 static int
2047 demux_mkv_open (demuxer_t *demuxer)
2049 stream_t *s = demuxer->stream;
2050 mkv_demuxer_t *mkv_d;
2051 mkv_track_t *track;
2052 int i, version, cont = 0;
2053 char *str;
2055 stream_seek(s, s->start_pos);
2056 str = ebml_read_header (s, &version);
2057 if (str == NULL || strcmp (str, "matroska") || version > 2)
2059 mp_msg (MSGT_DEMUX, MSGL_DBG2, "[mkv] no head found\n");
2060 return 0;
2062 free (str);
2064 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] Found the head...\n");
2066 if (ebml_read_id (s, NULL) != MATROSKA_ID_SEGMENT)
2068 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] but no segment :(\n");
2069 return 0;
2071 ebml_read_length (s, NULL); /* return bytes number until EOF */
2073 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] + a segment...\n");
2075 mkv_d = calloc (1, sizeof (mkv_demuxer_t));
2076 demuxer->priv = mkv_d;
2077 mkv_d->tc_scale = 1000000;
2078 mkv_d->segment_start = stream_tell (s);
2079 mkv_d->parsed_cues = malloc (sizeof (off_t));
2080 mkv_d->parsed_seekhead = malloc (sizeof (off_t));
2082 while (!cont)
2084 switch (ebml_read_id (s, NULL))
2086 case MATROSKA_ID_INFO:
2087 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] |+ segment information...\n");
2088 cont = demux_mkv_read_info (demuxer);
2089 break;
2091 case MATROSKA_ID_TRACKS:
2092 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] |+ segment tracks...\n");
2093 cont = demux_mkv_read_tracks (demuxer);
2094 break;
2096 case MATROSKA_ID_CUES:
2097 cont = demux_mkv_read_cues (demuxer);
2098 break;
2100 case MATROSKA_ID_TAGS:
2101 cont = demux_mkv_read_tags (demuxer);
2102 break;
2104 case MATROSKA_ID_SEEKHEAD:
2105 cont = demux_mkv_read_seekhead (demuxer);
2106 break;
2108 case MATROSKA_ID_CHAPTERS:
2109 cont = demux_mkv_read_chapters (demuxer);
2110 break;
2112 case MATROSKA_ID_ATTACHMENTS:
2113 cont = demux_mkv_read_attachments (demuxer);
2114 break;
2116 case MATROSKA_ID_CLUSTER:
2118 int p, l;
2119 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] |+ found cluster, headers are "
2120 "parsed completely :)\n");
2121 /* get the first cluster timecode */
2122 p = stream_tell(s);
2123 l = ebml_read_length (s, NULL);
2124 while (ebml_read_id (s, NULL) != MATROSKA_ID_CLUSTERTIMECODE)
2126 ebml_read_skip (s, NULL);
2127 if (stream_tell (s) >= p + l)
2128 break;
2130 if (stream_tell (s) < p + l)
2132 uint64_t num = ebml_read_uint (s, NULL);
2133 if (num == EBML_UINT_INVALID)
2134 return 0;
2135 mkv_d->first_tc = num * mkv_d->tc_scale / 1000000.0;
2136 mkv_d->has_first_tc = 1;
2138 stream_seek (s, p - 4);
2139 cont = 1;
2140 break;
2143 default:
2144 cont = 1;
2145 case EBML_ID_VOID:
2146 ebml_read_skip (s, NULL);
2147 break;
2151 display_create_tracks (demuxer);
2153 /* select video track */
2154 track = NULL;
2155 if (demuxer->video->id == -1) /* automatically select a video track */
2157 /* search for a video track that has the 'default' flag set */
2158 for (i=0; i<mkv_d->num_tracks; i++)
2159 if (mkv_d->tracks[i]->type == MATROSKA_TRACK_VIDEO
2160 && mkv_d->tracks[i]->default_track)
2162 track = mkv_d->tracks[i];
2163 break;
2166 if (track == NULL)
2167 /* no track has the 'default' flag set */
2168 /* let's take the first video track */
2169 for (i=0; i<mkv_d->num_tracks; i++)
2170 if (mkv_d->tracks[i]->type == MATROSKA_TRACK_VIDEO)
2172 track = mkv_d->tracks[i];
2173 break;
2176 else if (demuxer->video->id != -2) /* -2 = no video at all */
2177 track = demux_mkv_find_track_by_num (mkv_d, demuxer->video->id,
2178 MATROSKA_TRACK_VIDEO);
2180 if (track && demuxer->v_streams[track->tnum])
2182 mp_msg (MSGT_DEMUX, MSGL_INFO,
2183 MSGTR_MPDEMUX_MKV_WillPlayVideoTrack, track->tnum);
2184 demuxer->video->id = track->tnum;
2185 demuxer->video->sh = demuxer->v_streams[track->tnum];
2187 else
2189 mp_msg (MSGT_DEMUX, MSGL_INFO, MSGTR_MPDEMUX_MKV_NoVideoTrackFound);
2190 demuxer->video->id = -2;
2193 /* select audio track */
2194 track = NULL;
2195 if (track == NULL)
2196 /* search for an audio track that has the 'default' flag set */
2197 for (i=0; i < mkv_d->num_tracks; i++)
2198 if (mkv_d->tracks[i]->type == MATROSKA_TRACK_AUDIO
2199 && mkv_d->tracks[i]->default_track)
2201 track = mkv_d->tracks[i];
2202 break;
2205 if (track == NULL)
2206 /* no track has the 'default' flag set */
2207 /* let's take the first audio track */
2208 for (i=0; i < mkv_d->num_tracks; i++)
2209 if (mkv_d->tracks[i]->type == MATROSKA_TRACK_AUDIO)
2211 track = mkv_d->tracks[i];
2212 break;
2215 if (track && demuxer->a_streams[track->tnum])
2217 demuxer->audio->id = track->tnum;
2218 demuxer->audio->sh = demuxer->a_streams[track->tnum];
2220 else
2222 mp_msg (MSGT_DEMUX, MSGL_INFO, MSGTR_MPDEMUX_MKV_NoAudioTrackFound);
2223 demuxer->audio->id = -2;
2227 if(demuxer->audio->id != -2)
2228 for (i=0; i < mkv_d->num_tracks; i++)
2230 if(mkv_d->tracks[i]->type != MATROSKA_TRACK_AUDIO)
2231 continue;
2232 if(demuxer->a_streams[track->tnum])
2234 mkv_d->last_aid++;
2235 if(mkv_d->last_aid == MAX_A_STREAMS)
2236 break;
2240 if (demuxer->chapters)
2242 for (i=0; i < (int)demuxer->num_chapters; i++)
2244 demuxer->chapters[i].start -= mkv_d->first_tc;
2245 demuxer->chapters[i].end -= mkv_d->first_tc;
2247 if (dvd_last_chapter > 0 && dvd_last_chapter <= demuxer->num_chapters)
2249 if (demuxer->chapters[dvd_last_chapter-1].end != 0)
2250 mkv_d->stop_timecode = demuxer->chapters[dvd_last_chapter-1].end;
2251 else if (dvd_last_chapter + 1 <= demuxer->num_chapters)
2252 mkv_d->stop_timecode = demuxer->chapters[dvd_last_chapter].start;
2256 if (s->end_pos == 0 || (mkv_d->indexes == NULL && index_mode < 0))
2257 demuxer->seekable = 0;
2258 else
2260 demuxer->movi_start = s->start_pos;
2261 demuxer->movi_end = s->end_pos;
2262 demuxer->seekable = 1;
2265 return DEMUXER_TYPE_MATROSKA;
2268 static void
2269 demux_close_mkv (demuxer_t *demuxer)
2271 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2273 if (mkv_d)
2275 int i;
2276 free_cached_dps (demuxer);
2277 if (mkv_d->tracks)
2279 for (i=0; i<mkv_d->num_tracks; i++)
2280 demux_mkv_free_trackentry(mkv_d->tracks[i]);
2281 free (mkv_d->tracks);
2283 free (mkv_d->indexes);
2284 free (mkv_d->cluster_positions);
2285 free (mkv_d->parsed_cues);
2286 free (mkv_d->parsed_seekhead);
2287 free (mkv_d);
2291 static int
2292 demux_mkv_read_block_lacing (uint8_t *buffer, uint64_t *size,
2293 uint8_t *laces, uint32_t **all_lace_sizes)
2295 uint32_t total = 0, *lace_size;
2296 uint8_t flags;
2297 int i;
2299 *all_lace_sizes = NULL;
2300 lace_size = NULL;
2301 /* lacing flags */
2302 flags = *buffer++;
2303 (*size)--;
2305 switch ((flags & 0x06) >> 1)
2307 case 0: /* no lacing */
2308 *laces = 1;
2309 lace_size = calloc(*laces, sizeof(uint32_t));
2310 lace_size[0] = *size;
2311 break;
2313 case 1: /* xiph lacing */
2314 case 2: /* fixed-size lacing */
2315 case 3: /* EBML lacing */
2316 *laces = *buffer++;
2317 (*size)--;
2318 (*laces)++;
2319 lace_size = calloc(*laces, sizeof(uint32_t));
2321 switch ((flags & 0x06) >> 1)
2323 case 1: /* xiph lacing */
2324 for (i=0; i < *laces-1; i++)
2326 lace_size[i] = 0;
2329 lace_size[i] += *buffer;
2330 (*size)--;
2331 } while (*buffer++ == 0xFF);
2332 total += lace_size[i];
2334 lace_size[i] = *size - total;
2335 break;
2337 case 2: /* fixed-size lacing */
2338 for (i=0; i < *laces; i++)
2339 lace_size[i] = *size / *laces;
2340 break;
2342 case 3: /* EBML lacing */
2344 int l;
2345 uint64_t num = ebml_read_vlen_uint (buffer, &l);
2346 if (num == EBML_UINT_INVALID) {
2347 free(lace_size);
2348 return 1;
2350 buffer += l;
2351 *size -= l;
2353 total = lace_size[0] = num;
2354 for (i=1; i < *laces-1; i++)
2356 int64_t snum;
2357 snum = ebml_read_vlen_int (buffer, &l);
2358 if (snum == EBML_INT_INVALID) {
2359 free(lace_size);
2360 return 1;
2362 buffer += l;
2363 *size -= l;
2364 lace_size[i] = lace_size[i-1] + snum;
2365 total += lace_size[i];
2367 lace_size[i] = *size - total;
2368 break;
2371 break;
2373 *all_lace_sizes = lace_size;
2374 return 0;
2377 static void
2378 handle_subtitles(demuxer_t *demuxer, mkv_track_t *track, char *block,
2379 int64_t size, uint64_t block_duration, uint64_t timecode)
2381 demux_packet_t *dp;
2383 if (block_duration == 0)
2385 mp_msg (MSGT_DEMUX, MSGL_WARN,
2386 MSGTR_MPDEMUX_MKV_NoBlockDurationForSubtitleTrackFound);
2387 return;
2390 sub_utf8 = 1;
2391 dp = new_demux_packet(size);
2392 memcpy(dp->buffer, block, size);
2393 dp->pts = timecode / 1000.0f;
2394 dp->endpts = (timecode + block_duration) / 1000.0f;
2395 ds_add_packet(demuxer->sub, dp);
2398 double real_fix_timestamp(unsigned char *buf, unsigned int timestamp, unsigned int format, int64_t *kf_base, int *kf_pts, double *pts);
2400 static void
2401 handle_realvideo (demuxer_t *demuxer, mkv_track_t *track, uint8_t *buffer,
2402 uint32_t size, int block_bref)
2404 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2405 demux_packet_t *dp;
2406 uint32_t timestamp = mkv_d->last_pts * 1000;
2408 dp = new_demux_packet (size);
2409 memcpy (dp->buffer, buffer, size);
2411 if (mkv_d->v_skip_to_keyframe)
2413 dp->pts = mkv_d->last_pts;
2414 track->rv_kf_base = 0;
2415 track->rv_kf_pts = timestamp;
2417 else
2418 dp->pts = real_fix_timestamp (dp->buffer, timestamp,
2419 ((sh_video_t*)demuxer->video->sh)->bih->biCompression,
2420 &track->rv_kf_base, &track->rv_kf_pts, NULL);
2421 dp->pos = demuxer->filepos;
2422 dp->flags = block_bref ? 0 : 0x10;
2424 ds_add_packet(demuxer->video, dp);
2427 static void
2428 handle_realaudio (demuxer_t *demuxer, mkv_track_t *track, uint8_t *buffer,
2429 uint32_t size, int block_bref)
2431 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2432 int sps = track->sub_packet_size;
2433 int sph = track->sub_packet_h;
2434 int cfs = track->coded_framesize;
2435 int w = track->audiopk_size;
2436 int spc = track->sub_packet_cnt;
2437 demux_packet_t *dp;
2438 int x;
2440 if ((track->a_formattag == mmioFOURCC('2', '8', '_', '8')) ||
2441 (track->a_formattag == mmioFOURCC('c', 'o', 'o', 'k')) ||
2442 (track->a_formattag == mmioFOURCC('a', 't', 'r', 'c')) ||
2443 (track->a_formattag == mmioFOURCC('s', 'i', 'p', 'r')))
2445 // if(!block_bref)
2446 // spc = track->sub_packet_cnt = 0;
2447 switch (track->a_formattag) {
2448 case mmioFOURCC('2', '8', '_', '8'):
2449 for (x = 0; x < sph / 2; x++)
2450 memcpy(track->audio_buf + x * 2 * w + spc * cfs, buffer + cfs * x, cfs);
2451 break;
2452 case mmioFOURCC('c', 'o', 'o', 'k'):
2453 case mmioFOURCC('a', 't', 'r', 'c'):
2454 for (x = 0; x < w / sps; x++)
2455 memcpy(track->audio_buf + sps * (sph * x + ((sph + 1) / 2) * (spc & 1) + (spc >> 1)), buffer + sps * x, sps);
2456 break;
2457 case mmioFOURCC('s', 'i', 'p', 'r'):
2458 memcpy(track->audio_buf + spc * w, buffer, w);
2459 if (spc == sph - 1)
2461 int n;
2462 int bs = sph * w * 2 / 96; // nibbles per subpacket
2463 // Perform reordering
2464 for(n=0; n < 38; n++)
2466 int j;
2467 int i = bs * sipr_swaps[n][0];
2468 int o = bs * sipr_swaps[n][1];
2469 // swap nibbles of block 'i' with 'o' TODO: optimize
2470 for(j = 0;j < bs; j++)
2472 int x = (i & 1) ? (track->audio_buf[i >> 1] >> 4) : (track->audio_buf[i >> 1] & 0x0F);
2473 int y = (o & 1) ? (track->audio_buf[o >> 1] >> 4) : (track->audio_buf[o >> 1] & 0x0F);
2474 if(o & 1)
2475 track->audio_buf[o >> 1] = (track->audio_buf[o >> 1] & 0x0F) | (x << 4);
2476 else
2477 track->audio_buf[o >> 1] = (track->audio_buf[o >> 1] & 0xF0) | x;
2478 if(i & 1)
2479 track->audio_buf[i >> 1] = (track->audio_buf[i >> 1] & 0x0F) | (y << 4);
2480 else
2481 track->audio_buf[i >> 1] = (track->audio_buf[i >> 1] & 0xF0) | y;
2482 ++i; ++o;
2486 break;
2488 track->audio_timestamp[track->sub_packet_cnt] = (track->ra_pts == mkv_d->last_pts) ? 0 : (mkv_d->last_pts);
2489 track->ra_pts = mkv_d->last_pts;
2490 if (track->sub_packet_cnt == 0)
2491 track->audio_filepos = demuxer->filepos;
2492 if (++(track->sub_packet_cnt) == sph)
2494 int apk_usize = ((WAVEFORMATEX*)((sh_audio_t*)demuxer->audio->sh)->wf)->nBlockAlign;
2495 track->sub_packet_cnt = 0;
2496 // Release all the audio packets
2497 for (x = 0; x < sph*w/apk_usize; x++)
2499 dp = new_demux_packet(apk_usize);
2500 memcpy(dp->buffer, track->audio_buf + x * apk_usize, apk_usize);
2501 /* Put timestamp only on packets that correspond to original audio packets in file */
2502 dp->pts = (x * apk_usize % w) ? 0 : track->audio_timestamp[x * apk_usize / w];
2503 dp->pos = track->audio_filepos; // all equal
2504 dp->flags = x ? 0 : 0x10; // Mark first packet as keyframe
2505 ds_add_packet(demuxer->audio, dp);
2508 } else { // Not a codec that require reordering
2509 dp = new_demux_packet (size);
2510 memcpy(dp->buffer, buffer, size);
2511 if (track->ra_pts == mkv_d->last_pts && !mkv_d->a_skip_to_keyframe)
2512 dp->pts = 0;
2513 else
2514 dp->pts = mkv_d->last_pts;
2515 track->ra_pts = mkv_d->last_pts;
2517 dp->pos = demuxer->filepos;
2518 dp->flags = block_bref ? 0 : 0x10;
2519 ds_add_packet (demuxer->audio, dp);
2523 /** Reorder timecodes and add cached demux packets to the queues.
2525 * Timecode reordering is needed if a video track contains B frames that
2526 * are timestamped in display order (e.g. MPEG-1, MPEG-2 or "native" MPEG-4).
2527 * MPlayer doesn't like timestamps in display order. This function adjusts
2528 * the timestamp of cached frames (which are exactly one I/P frame followed
2529 * by one or more B frames) so that they are in coding order again.
2531 * Example: The track with 25 FPS contains four frames with the timecodes
2532 * I at 0ms, P at 120ms, B at 40ms and B at 80ms. As soon as the next I
2533 * or P frame arrives these timecodes can be changed to I at 0ms, P at 40ms,
2534 * B at 80ms and B at 120ms.
2536 * This works for simple H.264 B-frame pyramids, but not for arbitrary orders.
2538 * \param demuxer The Matroska demuxer struct for this instance.
2539 * \param track The track structure whose cache should be handled.
2541 static void
2542 flush_cached_dps (demuxer_t *demuxer, mkv_track_t *track)
2544 int i, ok;
2546 if (track->num_cached_dps == 0)
2547 return;
2549 do {
2550 ok = 1;
2551 for (i = 1; i < track->num_cached_dps; i++)
2552 if (track->cached_dps[i - 1]->pts > track->cached_dps[i]->pts) {
2553 float tmp_pts = track->cached_dps[i - 1]->pts;
2554 track->cached_dps[i - 1]->pts = track->cached_dps[i]->pts;
2555 track->cached_dps[i]->pts = tmp_pts;
2556 ok = 0;
2558 } while (!ok);
2560 for (i = 0; i < track->num_cached_dps; i++)
2561 ds_add_packet (demuxer->video, track->cached_dps[i]);
2562 track->num_cached_dps = 0;
2565 /** Cache video frames if timecodes have to be reordered.
2567 * Timecode reordering is needed if a video track contains B frames that
2568 * are timestamped in display order (e.g. MPEG-1, MPEG-2 or "native" MPEG-4).
2569 * This function takes in a Matroska block read from the file, allocates a
2570 * demux packet for it, fills in its values, allocates space for storing
2571 * pointers to the cached demux packets and adds the packet to it. If
2572 * the packet contains an I or a P frame then ::flush_cached_dps is called
2573 * in order to send the old cached frames downstream.
2575 * \param demuxer The Matroska demuxer struct for this instance.
2576 * \param track The packet is meant for this track.
2577 * \param buffer The actual frame contents.
2578 * \param size The frame size in bytes.
2579 * \param block_bref A relative timecode (backward reference). If it is \c 0
2580 * then the frame is an I frame.
2581 * \param block_fref A relative timecode (forward reference). If it is \c 0
2582 * then the frame is either an I frame or a P frame depending on the value
2583 * of \a block_bref. Otherwise it's a B frame.
2585 static void
2586 handle_video_bframes (demuxer_t *demuxer, mkv_track_t *track, uint8_t *buffer,
2587 uint32_t size, int block_bref, int block_fref)
2589 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2590 demux_packet_t *dp;
2592 dp = new_demux_packet (size);
2593 memcpy(dp->buffer, buffer, size);
2594 dp->pos = demuxer->filepos;
2595 dp->pts = mkv_d->last_pts;
2596 if ((track->num_cached_dps > 0) && (dp->pts < track->max_pts))
2597 block_fref = 1;
2598 if (block_fref == 0) /* I or P frame */
2599 flush_cached_dps (demuxer, track);
2600 if (block_bref != 0) /* I frame, don't cache it */
2601 dp->flags = 0x10;
2602 if ((track->num_cached_dps + 1) > track->num_allocated_dps)
2604 track->cached_dps = (demux_packet_t **)
2605 realloc(track->cached_dps, (track->num_cached_dps + 10) *
2606 sizeof(demux_packet_t *));
2607 track->num_allocated_dps += 10;
2609 track->cached_dps[track->num_cached_dps] = dp;
2610 track->num_cached_dps++;
2611 if (dp->pts > track->max_pts)
2612 track->max_pts = dp->pts;
2615 static int
2616 handle_block (demuxer_t *demuxer, uint8_t *block, uint64_t length,
2617 uint64_t block_duration, int64_t block_bref, int64_t block_fref, uint8_t simpleblock)
2619 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2620 mkv_track_t *track = NULL;
2621 demux_stream_t *ds = NULL;
2622 uint64_t old_length;
2623 int64_t tc;
2624 uint32_t *lace_size;
2625 uint8_t laces, flags;
2626 int i, num, tmp, use_this_block = 1;
2627 float current_pts;
2628 int16_t time;
2630 /* first byte(s): track num */
2631 num = ebml_read_vlen_uint (block, &tmp);
2632 block += tmp;
2633 /* time (relative to cluster time) */
2634 time = block[0] << 8 | block[1];
2635 block += 2;
2636 length -= tmp + 2;
2637 old_length = length;
2638 flags = block[0];
2639 if (demux_mkv_read_block_lacing (block, &length, &laces, &lace_size))
2640 return 0;
2641 block += old_length - length;
2643 tc = ((time*mkv_d->tc_scale+mkv_d->cluster_tc) /1000000.0 - mkv_d->first_tc);
2644 if (tc < 0)
2645 tc = 0;
2646 if (mkv_d->stop_timecode > 0 && tc > mkv_d->stop_timecode) {
2647 free(lace_size);
2648 return -1;
2650 current_pts = tc / 1000.0;
2652 for (i=0; i<mkv_d->num_tracks; i++)
2653 if (mkv_d->tracks[i]->tnum == num) {
2654 track = mkv_d->tracks[i];
2655 break;
2657 if (track == NULL)
2659 free(lace_size);
2660 return 1;
2662 if (num == demuxer->audio->id)
2664 ds = demuxer->audio;
2666 if (mkv_d->a_skip_to_keyframe)
2668 if (simpleblock)
2670 if (!(flags&0x80)) /*current frame isn't a keyframe*/
2671 use_this_block = 0;
2673 else if (block_bref != 0)
2674 use_this_block = 0;
2676 else if (mkv_d->v_skip_to_keyframe)
2677 use_this_block = 0;
2679 if (track->fix_i_bps && use_this_block)
2681 sh_audio_t *sh = (sh_audio_t *) ds->sh;
2683 if (block_duration != 0)
2685 sh->i_bps = length * 1000 / block_duration;
2686 track->fix_i_bps = 0;
2688 else if (track->qt_last_a_pts == 0.0)
2689 track->qt_last_a_pts = current_pts;
2690 else if(track->qt_last_a_pts != current_pts)
2692 sh->i_bps = length / (current_pts - track->qt_last_a_pts);
2693 track->fix_i_bps = 0;
2697 else if (tc < mkv_d->skip_to_timecode)
2698 use_this_block = 0;
2699 else if (num == demuxer->video->id)
2701 ds = demuxer->video;
2702 if (mkv_d->v_skip_to_keyframe)
2704 if (simpleblock)
2706 if (!(flags&0x80)) /*current frame isn't a keyframe*/
2707 use_this_block = 0;
2709 else if (block_bref != 0 || block_fref != 0)
2710 use_this_block = 0;
2713 else if (num == demuxer->sub->id)
2715 ds = demuxer->sub;
2716 if (track->subtitle_type != MATROSKA_SUBTYPE_VOBSUB)
2718 if (!mkv_d->v_skip_to_keyframe)
2719 handle_subtitles (demuxer, track, block, length,
2720 block_duration, tc);
2721 use_this_block = 0;
2724 else
2725 use_this_block = 0;
2727 if (use_this_block)
2729 mkv_d->last_pts = current_pts;
2730 mkv_d->last_filepos = demuxer->filepos;
2732 for (i=0; i < laces; i++)
2734 if (ds == demuxer->video && track->realmedia)
2735 handle_realvideo (demuxer, track, block, lace_size[i], block_bref);
2736 else if (ds == demuxer->audio && track->realmedia)
2737 handle_realaudio (demuxer, track, block, lace_size[i], block_bref);
2738 else if (ds == demuxer->video && track->reorder_timecodes)
2739 handle_video_bframes (demuxer, track, block, lace_size[i],
2740 block_bref, block_fref);
2741 else
2743 int modified, size = lace_size[i];
2744 demux_packet_t *dp;
2745 uint8_t *buffer;
2746 modified = demux_mkv_decode (track, block, &buffer, &size, 1);
2747 if (buffer)
2749 dp = new_demux_packet (size);
2750 memcpy (dp->buffer, buffer, size);
2751 if (modified)
2752 free (buffer);
2753 dp->flags = (block_bref == 0 && block_fref == 0) ? 0x10 : 0;
2754 /* If default_duration is 0, assume no pts value is known
2755 * for packets after the first one (rather than all pts
2756 * values being the same) */
2757 if (i == 0 || track->default_duration)
2758 dp->pts = mkv_d->last_pts + i * track->default_duration;
2759 ds_add_packet (ds, dp);
2762 block += lace_size[i];
2765 if (ds == demuxer->video)
2767 mkv_d->v_skip_to_keyframe = 0;
2768 mkv_d->skip_to_timecode = 0;
2770 else if (ds == demuxer->audio)
2771 mkv_d->a_skip_to_keyframe = 0;
2773 free(lace_size);
2774 return 1;
2777 free(lace_size);
2778 return 0;
2781 static int
2782 demux_mkv_fill_buffer (demuxer_t *demuxer, demux_stream_t *ds)
2784 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2785 stream_t *s = demuxer->stream;
2786 uint64_t l;
2787 int il, tmp;
2789 while (1)
2791 while (mkv_d->cluster_size > 0)
2793 uint64_t block_duration = 0, block_length = 0;
2794 int64_t block_bref = 0, block_fref = 0;
2795 uint8_t *block = NULL;
2797 while (mkv_d->blockgroup_size > 0)
2799 switch (ebml_read_id (s, &il))
2801 case MATROSKA_ID_BLOCKDURATION:
2803 block_duration = ebml_read_uint (s, &l);
2804 if (block_duration == EBML_UINT_INVALID) {
2805 free(block);
2806 return 0;
2808 block_duration *= mkv_d->tc_scale / 1000000.0;
2809 break;
2812 case MATROSKA_ID_BLOCK:
2813 block_length = ebml_read_length (s, &tmp);
2814 free(block);
2815 if (block_length > SIZE_MAX - AV_LZO_INPUT_PADDING) return 0;
2816 block = malloc (block_length + AV_LZO_INPUT_PADDING);
2817 demuxer->filepos = stream_tell (s);
2818 if (stream_read (s,block,block_length) != (int) block_length)
2820 free(block);
2821 return 0;
2823 l = tmp + block_length;
2824 break;
2826 case MATROSKA_ID_REFERENCEBLOCK:
2828 int64_t num = ebml_read_int (s, &l);
2829 if (num == EBML_INT_INVALID) {
2830 free(block);
2831 return 0;
2833 if (num <= 0)
2834 block_bref = num;
2835 else
2836 block_fref = num;
2837 break;
2840 case EBML_ID_INVALID:
2841 free(block);
2842 return 0;
2844 default:
2845 ebml_read_skip (s, &l);
2846 break;
2848 mkv_d->blockgroup_size -= l + il;
2849 mkv_d->cluster_size -= l + il;
2852 if (block)
2854 int res = handle_block (demuxer, block, block_length,
2855 block_duration, block_bref, block_fref, 0);
2856 free (block);
2857 if (res < 0)
2858 return 0;
2859 if (res)
2860 return 1;
2863 if (mkv_d->cluster_size > 0)
2865 switch (ebml_read_id (s, &il))
2867 case MATROSKA_ID_CLUSTERTIMECODE:
2869 uint64_t num = ebml_read_uint (s, &l);
2870 if (num == EBML_UINT_INVALID)
2871 return 0;
2872 if (!mkv_d->has_first_tc)
2874 mkv_d->first_tc = num * mkv_d->tc_scale / 1000000.0;
2875 mkv_d->has_first_tc = 1;
2877 mkv_d->cluster_tc = num * mkv_d->tc_scale;
2878 break;
2881 case MATROSKA_ID_BLOCKGROUP:
2882 mkv_d->blockgroup_size = ebml_read_length (s, &tmp);
2883 l = tmp;
2884 break;
2886 case MATROSKA_ID_SIMPLEBLOCK:
2888 int res;
2889 block_length = ebml_read_length (s, &tmp);
2890 block = malloc (block_length);
2891 demuxer->filepos = stream_tell (s);
2892 if (stream_read (s,block,block_length) != (int) block_length)
2894 free(block);
2895 return 0;
2897 l = tmp + block_length;
2898 res = handle_block (demuxer, block, block_length,
2899 block_duration, block_bref, block_fref, 1);
2900 free (block);
2901 mkv_d->cluster_size -= l + il;
2902 if (res < 0)
2903 return 0;
2904 else if (res)
2905 return 1;
2906 else mkv_d->cluster_size += l + il;
2907 break;
2909 case EBML_ID_INVALID:
2910 return 0;
2912 default:
2913 ebml_read_skip (s, &l);
2914 break;
2916 mkv_d->cluster_size -= l + il;
2920 if (ebml_read_id (s, &il) != MATROSKA_ID_CLUSTER)
2921 return 0;
2922 add_cluster_position(mkv_d, stream_tell(s)-il);
2923 mkv_d->cluster_size = ebml_read_length (s, NULL);
2926 return 0;
2929 static void
2930 demux_mkv_seek (demuxer_t *demuxer, float rel_seek_secs, float audio_delay, int flags)
2932 free_cached_dps (demuxer);
2933 if (!(flags & SEEK_FACTOR)) /* time in secs */
2935 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2936 stream_t *s = demuxer->stream;
2937 int64_t target_timecode = 0, diff, min_diff=0xFFFFFFFFFFFFFFFLL;
2938 int i;
2940 if (!(flags & SEEK_ABSOLUTE)) /* relative seek */
2941 target_timecode = (int64_t) (mkv_d->last_pts * 1000.0);
2942 target_timecode += (int64_t)(rel_seek_secs * 1000.0);
2943 if (target_timecode < 0)
2944 target_timecode = 0;
2946 if (mkv_d->indexes == NULL) /* no index was found */
2948 uint64_t target_filepos, cluster_pos, max_pos;
2950 target_filepos = (uint64_t) (target_timecode * mkv_d->last_filepos
2951 / (mkv_d->last_pts * 1000.0));
2953 max_pos = mkv_d->cluster_positions[mkv_d->num_cluster_pos-1];
2954 if (target_filepos > max_pos)
2956 if ((off_t) max_pos > stream_tell (s))
2957 stream_seek (s, max_pos);
2958 else
2959 stream_seek (s, stream_tell (s) + mkv_d->cluster_size);
2960 /* parse all the clusters upto target_filepos */
2961 while (!s->eof && stream_tell(s) < (off_t) target_filepos)
2963 switch (ebml_read_id (s, &i))
2965 case MATROSKA_ID_CLUSTER:
2966 add_cluster_position(mkv_d, (uint64_t) stream_tell(s)-i);
2967 break;
2969 case MATROSKA_ID_CUES:
2970 demux_mkv_read_cues (demuxer);
2971 break;
2973 ebml_read_skip (s, NULL);
2975 if (s->eof)
2976 stream_reset(s);
2979 if (mkv_d->indexes == NULL)
2981 cluster_pos = mkv_d->cluster_positions[0];
2982 /* Let's find the nearest cluster */
2983 for (i=0; i < mkv_d->num_cluster_pos; i++)
2985 diff = mkv_d->cluster_positions[i] - target_filepos;
2986 if (rel_seek_secs < 0 && diff < 0 && -diff < min_diff)
2988 cluster_pos = mkv_d->cluster_positions[i];
2989 min_diff = -diff;
2991 else if (rel_seek_secs > 0
2992 && (diff < 0 ? -1 * diff : diff) < min_diff)
2994 cluster_pos = mkv_d->cluster_positions[i];
2995 min_diff = diff < 0 ? -1 * diff : diff;
2998 mkv_d->cluster_size = mkv_d->blockgroup_size = 0;
2999 stream_seek (s, cluster_pos);
3002 else
3004 mkv_index_t *index = NULL;
3005 int seek_id = (demuxer->video->id < 0) ? demuxer->audio->id : demuxer->video->id;
3007 /* let's find the entry in the indexes with the smallest */
3008 /* difference to the wanted timecode. */
3009 for (i=0; i < mkv_d->num_indexes; i++)
3010 if (mkv_d->indexes[i].tnum == seek_id)
3012 diff = target_timecode + mkv_d->first_tc -
3013 (int64_t) mkv_d->indexes[i].timecode * mkv_d->tc_scale / 1000000.0;
3015 if ((flags & SEEK_ABSOLUTE || target_timecode <= mkv_d->last_pts*1000)) {
3016 // Absolute seek or seek backward: find the last index
3017 // position before target time
3018 if (diff < 0 || diff >= min_diff)
3019 continue;
3021 else {
3022 // Relative seek forward: find the first index position
3023 // after target time. If no such index exists, find last
3024 // position between current position and target time.
3025 if (diff <= 0) {
3026 if (min_diff <= 0 && diff <= min_diff)
3027 continue;
3029 else if (diff >= FFMIN(target_timecode - mkv_d->last_pts,
3030 min_diff))
3031 continue;
3033 min_diff = diff;
3034 index = mkv_d->indexes + i;
3037 if (index) /* We've found an entry. */
3039 mkv_d->cluster_size = mkv_d->blockgroup_size = 0;
3040 stream_seek (s, index->filepos);
3044 if (demuxer->video->id >= 0)
3045 mkv_d->v_skip_to_keyframe = 1;
3046 if (rel_seek_secs > 0.0)
3047 mkv_d->skip_to_timecode = target_timecode;
3048 mkv_d->a_skip_to_keyframe = 1;
3050 demux_mkv_fill_buffer(demuxer, NULL);
3052 else if ((demuxer->movi_end <= 0) || !(flags & SEEK_ABSOLUTE))
3053 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] seek unsupported flags\n");
3054 else
3056 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
3057 stream_t *s = demuxer->stream;
3058 uint64_t target_filepos;
3059 mkv_index_t *index = NULL;
3060 int i;
3062 if (mkv_d->indexes == NULL) /* no index was found */
3063 { /* I'm lazy... */
3064 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] seek unsupported flags\n");
3065 return;
3068 target_filepos = (uint64_t)(demuxer->movi_end * rel_seek_secs);
3069 for (i=0; i < mkv_d->num_indexes; i++)
3070 if (mkv_d->indexes[i].tnum == demuxer->video->id)
3071 if ((index == NULL) ||
3072 ((mkv_d->indexes[i].filepos >= target_filepos) &&
3073 ((index->filepos < target_filepos) ||
3074 (mkv_d->indexes[i].filepos < index->filepos))))
3075 index = &mkv_d->indexes[i];
3077 if (!index)
3078 return;
3080 mkv_d->cluster_size = mkv_d->blockgroup_size = 0;
3081 stream_seek (s, index->filepos);
3083 if (demuxer->video->id >= 0)
3084 mkv_d->v_skip_to_keyframe = 1;
3085 mkv_d->skip_to_timecode = index->timecode;
3086 mkv_d->a_skip_to_keyframe = 1;
3088 demux_mkv_fill_buffer(demuxer, NULL);
3092 static int
3093 demux_mkv_control (demuxer_t *demuxer, int cmd, void *arg)
3095 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
3097 switch (cmd)
3099 case DEMUXER_CTRL_CORRECT_PTS:
3100 return DEMUXER_CTRL_OK;
3101 case DEMUXER_CTRL_GET_TIME_LENGTH:
3102 if (mkv_d->duration == 0)
3103 return DEMUXER_CTRL_DONTKNOW;
3105 *((double *)arg) = (double)mkv_d->duration;
3106 return DEMUXER_CTRL_OK;
3108 case DEMUXER_CTRL_GET_PERCENT_POS:
3109 if (mkv_d->duration == 0)
3111 return DEMUXER_CTRL_DONTKNOW;
3114 *((int *) arg) = (int) (100 * mkv_d->last_pts / mkv_d->duration);
3115 return DEMUXER_CTRL_OK;
3117 case DEMUXER_CTRL_SWITCH_AUDIO:
3118 if (demuxer->audio && demuxer->audio->sh) {
3119 sh_audio_t *sh = demuxer->a_streams[demuxer->audio->id];
3120 int aid = *(int*)arg;
3121 if (aid < 0)
3122 aid = (sh->aid + 1) % mkv_d->last_aid;
3123 if (aid != sh->aid) {
3124 mkv_track_t *track = demux_mkv_find_track_by_num (mkv_d, aid, MATROSKA_TRACK_AUDIO);
3125 if (track) {
3126 demuxer->audio->id = track->tnum;
3127 sh = demuxer->a_streams[demuxer->audio->id];
3128 ds_free_packs(demuxer->audio);
3131 *(int*)arg = sh->aid;
3132 } else
3133 *(int*)arg = -2;
3134 return DEMUXER_CTRL_OK;
3136 default:
3137 return DEMUXER_CTRL_NOTIMPL;
3141 const demuxer_desc_t demuxer_desc_matroska = {
3142 "Matroska demuxer",
3143 "mkv",
3144 "Matroska",
3145 "Aurelien Jacobs",
3147 DEMUXER_TYPE_MATROSKA,
3148 1, // safe autodetect
3149 demux_mkv_open,
3150 demux_mkv_fill_buffer,
3151 NULL,
3152 demux_close_mkv,
3153 demux_mkv_seek,
3154 demux_mkv_control