VP6F has to be flipped for binary decoder.
[mplayer/glamo.git] / libmpdemux / demux_mkv.c
blobaa900d343a2660a53af658a0e33d102b0b99fece
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 arrayp array to grow
208 * \param nelem current number of elements in array
209 * \param elsize size of one array element
211 static void av_noinline grow_array(void *arrayp, int nelem, size_t elsize) {
212 void **array = arrayp;
213 void *oldp = *array;
214 if (nelem & 31)
215 return;
216 if (nelem > UINT_MAX / elsize - 32)
217 *array = NULL;
218 else
219 *array = realloc(*array, (nelem + 32) * elsize);
220 if (!*array)
221 free(oldp);
224 static mkv_track_t *
225 demux_mkv_find_track_by_num (mkv_demuxer_t *d, int n, int type)
227 int i, id;
229 for (i=0, id=0; i < d->num_tracks; i++)
230 if (d->tracks[i] != NULL && d->tracks[i]->type == type)
231 if (id++ == n)
232 return d->tracks[i];
234 return NULL;
237 static void
238 add_cluster_position (mkv_demuxer_t *mkv_d, uint64_t position)
240 int i = mkv_d->num_cluster_pos;
242 while (i--)
243 if (mkv_d->cluster_positions[i] == position)
244 return;
246 grow_array(&mkv_d->cluster_positions, mkv_d->num_cluster_pos,
247 sizeof(uint64_t));
248 if (!mkv_d->cluster_positions) {
249 mkv_d->num_cluster_pos = 0;
250 return;
252 mkv_d->cluster_positions[mkv_d->num_cluster_pos++] = position;
256 #define AAC_SYNC_EXTENSION_TYPE 0x02b7
257 static int
258 aac_get_sample_rate_index (uint32_t sample_rate)
260 static const int srates[] = {92017, 75132, 55426, 46009, 37566, 27713, 23004, 18783, 13856, 11502, 9391, 0};
261 int i = 0;
262 while (sample_rate < srates[i]) i++;
263 return i;
266 /** \brief Free cached demux packets
268 * Reordering the timecodes requires caching of demux packets. This function
269 * frees all these cached packets and the memory for the cached pointers
270 * itself.
272 * \param demuxer The demuxer for which the cache is to be freed.
274 static void
275 free_cached_dps (demuxer_t *demuxer)
277 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
278 mkv_track_t *track;
279 int i, k;
281 for (k = 0; k < mkv_d->num_tracks; k++)
283 track = mkv_d->tracks[k];
284 for (i = 0; i < track->num_cached_dps; i++)
285 free_demux_packet (track->cached_dps[i]);
286 free(track->cached_dps);
287 track->cached_dps = NULL;
288 track->num_cached_dps = 0;
289 track->num_allocated_dps = 0;
290 track->max_pts = 0;
294 static int
295 demux_mkv_decode (mkv_track_t *track, uint8_t *src, uint8_t **dest,
296 uint32_t *size, uint32_t type)
298 int i, result;
299 int modified = 0;
301 *dest = src;
302 if (track->num_encodings <= 0)
303 return 0;
305 for (i=0; i<track->num_encodings; i++)
307 if (!(track->encodings[i].scope & type))
308 continue;
310 #if CONFIG_ZLIB
311 if (track->encodings[i].comp_algo == 0)
313 /* zlib encoded track */
314 z_stream zstream;
316 zstream.zalloc = (alloc_func) 0;
317 zstream.zfree = (free_func) 0;
318 zstream.opaque = (voidpf) 0;
319 if (inflateInit (&zstream) != Z_OK)
321 mp_msg (MSGT_DEMUX, MSGL_WARN,
322 MSGTR_MPDEMUX_MKV_ZlibInitializationFailed);
323 return modified;
325 zstream.next_in = (Bytef *) src;
326 zstream.avail_in = *size;
328 modified = 1;
329 *dest = NULL;
330 zstream.avail_out = *size;
331 do {
332 *size += 4000;
333 *dest = realloc (*dest, *size);
334 zstream.next_out = (Bytef *) (*dest + zstream.total_out);
335 result = inflate (&zstream, Z_NO_FLUSH);
336 if (result != Z_OK && result != Z_STREAM_END)
338 mp_msg (MSGT_DEMUX, MSGL_WARN,
339 MSGTR_MPDEMUX_MKV_ZlibDecompressionFailed);
340 free(*dest);
341 *dest = NULL;
342 inflateEnd (&zstream);
343 return modified;
345 zstream.avail_out += 4000;
346 } while (zstream.avail_out == 4000 &&
347 zstream.avail_in != 0 && result != Z_STREAM_END);
349 *size = zstream.total_out;
350 inflateEnd (&zstream);
352 #endif
353 if (track->encodings[i].comp_algo == 2)
355 /* lzo encoded track */
356 int dstlen = *size * 3;
358 *dest = NULL;
359 while (1)
361 int srclen = *size;
362 if (dstlen > SIZE_MAX - AV_LZO_OUTPUT_PADDING) goto lzo_fail;
363 *dest = realloc (*dest, dstlen + AV_LZO_OUTPUT_PADDING);
364 result = av_lzo1x_decode (*dest, &dstlen, src, &srclen);
365 if (result == 0)
366 break;
367 if (!(result & AV_LZO_OUTPUT_FULL))
369 lzo_fail:
370 mp_msg (MSGT_DEMUX, MSGL_WARN,
371 MSGTR_MPDEMUX_MKV_LzoDecompressionFailed);
372 free(*dest);
373 *dest = NULL;
374 return modified;
376 mp_msg (MSGT_DEMUX, MSGL_DBG2,
377 "[mkv] lzo decompression buffer too small.\n");
378 dstlen *= 2;
380 *size = dstlen;
384 return modified;
388 static int
389 demux_mkv_read_info (demuxer_t *demuxer)
391 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
392 stream_t *s = demuxer->stream;
393 uint64_t length, l;
394 int il;
395 uint64_t tc_scale = 1000000;
396 long double duration = 0.;
398 length = ebml_read_length (s, NULL);
399 while (length > 0)
401 switch (ebml_read_id (s, &il))
403 case MATROSKA_ID_TIMECODESCALE:
405 uint64_t num = ebml_read_uint (s, &l);
406 if (num == EBML_UINT_INVALID)
407 return 1;
408 tc_scale = num;
409 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + timecode scale: %"PRIu64"\n",
410 tc_scale);
411 break;
414 case MATROSKA_ID_DURATION:
416 long double num = ebml_read_float (s, &l);
417 if (num == EBML_FLOAT_INVALID)
418 return 1;
419 duration = num;
420 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + duration: %.3Lfs\n",
421 duration * tc_scale / 1000000000.0);
422 break;
425 default:
426 ebml_read_skip (s, &l);
427 break;
429 length -= l + il;
431 mkv_d->tc_scale = tc_scale;
432 mkv_d->duration = duration * tc_scale / 1000000000.0;
433 return 0;
437 * \brief free array of kv_content_encoding_t
438 * \param encodings pointer to array
439 * \param numencodings number of encodings in array
441 static void
442 demux_mkv_free_encodings(mkv_content_encoding_t *encodings, int numencodings)
444 while (numencodings-- > 0)
445 free(encodings[numencodings].comp_settings);
446 free(encodings);
449 static int
450 demux_mkv_read_trackencodings (demuxer_t *demuxer, mkv_track_t *track)
452 stream_t *s = demuxer->stream;
453 mkv_content_encoding_t *ce, e;
454 uint64_t len, length, l;
455 int il, n;
457 ce = malloc (sizeof (*ce));
458 n = 0;
460 len = length = ebml_read_length (s, &il);
461 len += il;
462 while (length > 0)
464 switch (ebml_read_id (s, &il))
466 case MATROSKA_ID_CONTENTENCODING:
468 uint64_t len;
469 int i;
471 memset (&e, 0, sizeof (e));
472 e.scope = 1;
474 len = ebml_read_length (s, &i);
475 l = len + i;
477 while (len > 0)
479 uint64_t num, l;
480 int il;
482 switch (ebml_read_id (s, &il))
484 case MATROSKA_ID_CONTENTENCODINGORDER:
485 num = ebml_read_uint (s, &l);
486 if (num == EBML_UINT_INVALID)
487 goto err_out;
488 e.order = num;
489 break;
491 case MATROSKA_ID_CONTENTENCODINGSCOPE:
492 num = ebml_read_uint (s, &l);
493 if (num == EBML_UINT_INVALID)
494 goto err_out;
495 e.scope = num;
496 break;
498 case MATROSKA_ID_CONTENTENCODINGTYPE:
499 num = ebml_read_uint (s, &l);
500 if (num == EBML_UINT_INVALID)
501 goto err_out;
502 e.type = num;
503 break;
505 case MATROSKA_ID_CONTENTCOMPRESSION:
507 uint64_t le;
509 le = ebml_read_length (s, &i);
510 l = le + i;
512 while (le > 0)
514 uint64_t l;
515 int il;
517 switch (ebml_read_id (s, &il))
519 case MATROSKA_ID_CONTENTCOMPALGO:
520 num = ebml_read_uint (s, &l);
521 if (num == EBML_UINT_INVALID)
522 goto err_out;
523 e.comp_algo = num;
524 break;
526 case MATROSKA_ID_CONTENTCOMPSETTINGS:
527 l = ebml_read_length (s, &i);
528 e.comp_settings = malloc (l);
529 stream_read (s, e.comp_settings, l);
530 e.comp_settings_len = l;
531 l += i;
532 break;
534 default:
535 ebml_read_skip (s, &l);
536 break;
538 le -= l + il;
541 if (e.type == 1)
543 mp_msg(MSGT_DEMUX, MSGL_WARN,
544 MSGTR_MPDEMUX_MKV_TrackEncrypted, track->tnum);
546 else if (e.type != 0)
548 mp_msg(MSGT_DEMUX, MSGL_WARN,
549 MSGTR_MPDEMUX_MKV_UnknownContentEncoding, track->tnum);
552 if (e.comp_algo != 0 && e.comp_algo != 2)
554 mp_msg (MSGT_DEMUX, MSGL_WARN,
555 MSGTR_MPDEMUX_MKV_UnknownCompression,
556 track->tnum, e.comp_algo);
558 #if !CONFIG_ZLIB
559 else if (e.comp_algo == 0)
561 mp_msg (MSGT_DEMUX, MSGL_WARN,
562 MSGTR_MPDEMUX_MKV_ZlibCompressionUnsupported,
563 track->tnum);
565 #endif
567 break;
570 default:
571 ebml_read_skip (s, &l);
572 break;
574 len -= l + il;
576 for (i=0; i<n; i++)
577 if (e.order <= ce[i].order)
578 break;
579 ce = realloc (ce, (n+1) *sizeof (*ce));
580 memmove (ce+i+1, ce+i, (n-i) * sizeof (*ce));
581 memcpy (ce+i, &e, sizeof (e));
582 n++;
583 break;
586 default:
587 ebml_read_skip (s, &l);
588 break;
591 length -= l + il;
594 track->encodings = ce;
595 track->num_encodings = n;
596 return len;
598 err_out:
599 demux_mkv_free_encodings(ce, n);
600 return 0;
603 static int
604 demux_mkv_read_trackaudio (demuxer_t *demuxer, mkv_track_t *track)
606 stream_t *s = demuxer->stream;
607 uint64_t len, length, l;
608 int il;
610 track->a_sfreq = 8000.0;
611 track->a_channels = 1;
613 len = length = ebml_read_length (s, &il);
614 len += il;
615 while (length > 0)
617 switch (ebml_read_id (s, &il))
619 case MATROSKA_ID_AUDIOSAMPLINGFREQ:
621 long double num = ebml_read_float (s, &l);
622 if (num == EBML_FLOAT_INVALID)
623 return 0;
624 track->a_sfreq = num;
625 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Sampling frequency: %f\n",
626 track->a_sfreq);
627 break;
630 case MATROSKA_ID_AUDIOBITDEPTH:
632 uint64_t num = ebml_read_uint (s, &l);
633 if (num == EBML_UINT_INVALID)
634 return 0;
635 track->a_bps = num;
636 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Bit depth: %u\n",
637 track->a_bps);
638 break;
641 case MATROSKA_ID_AUDIOCHANNELS:
643 uint64_t num = ebml_read_uint (s, &l);
644 if (num == EBML_UINT_INVALID)
645 return 0;
646 track->a_channels = num;
647 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Channels: %u\n",
648 track->a_channels);
649 break;
652 default:
653 ebml_read_skip (s, &l);
654 break;
656 length -= l + il;
658 return len;
661 static int
662 demux_mkv_read_trackvideo (demuxer_t *demuxer, mkv_track_t *track)
664 stream_t *s = demuxer->stream;
665 uint64_t len, length, l;
666 int il;
668 len = length = ebml_read_length (s, &il);
669 len += il;
670 while (length > 0)
672 switch (ebml_read_id (s, &il))
674 case MATROSKA_ID_VIDEOFRAMERATE:
676 long double num = ebml_read_float (s, &l);
677 if (num == EBML_FLOAT_INVALID)
678 return 0;
679 track->v_frate = num;
680 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Frame rate: %f\n",
681 track->v_frate);
682 if (track->v_frate > 0)
683 track->default_duration = 1 / track->v_frate;
684 break;
687 case MATROSKA_ID_VIDEODISPLAYWIDTH:
689 uint64_t num = ebml_read_uint (s, &l);
690 if (num == EBML_UINT_INVALID)
691 return 0;
692 track->v_dwidth = num;
693 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Display width: %u\n",
694 track->v_dwidth);
695 break;
698 case MATROSKA_ID_VIDEODISPLAYHEIGHT:
700 uint64_t num = ebml_read_uint (s, &l);
701 if (num == EBML_UINT_INVALID)
702 return 0;
703 track->v_dheight = num;
704 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Display height: %u\n",
705 track->v_dheight);
706 break;
709 case MATROSKA_ID_VIDEOPIXELWIDTH:
711 uint64_t num = ebml_read_uint (s, &l);
712 if (num == EBML_UINT_INVALID)
713 return 0;
714 track->v_width = num;
715 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Pixel width: %u\n",
716 track->v_width);
717 break;
720 case MATROSKA_ID_VIDEOPIXELHEIGHT:
722 uint64_t num = ebml_read_uint (s, &l);
723 if (num == EBML_UINT_INVALID)
724 return 0;
725 track->v_height = num;
726 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Pixel height: %u\n",
727 track->v_height);
728 break;
731 default:
732 ebml_read_skip (s, &l);
733 break;
735 length -= l + il;
737 return len;
741 * \brief free any data associated with given track
742 * \param track track of which to free data
744 static void
745 demux_mkv_free_trackentry(mkv_track_t *track) {
746 free (track->name);
747 free (track->codec_id);
748 free (track->language);
749 free (track->private_data);
750 free (track->audio_buf);
751 free (track->audio_timestamp);
752 demux_mkv_free_encodings(track->encodings, track->num_encodings);
753 free(track);
756 static int
757 demux_mkv_read_trackentry (demuxer_t *demuxer)
759 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
760 stream_t *s = demuxer->stream;
761 mkv_track_t *track;
762 uint64_t len, length, l;
763 int il;
765 track = calloc (1, sizeof (*track));
766 /* set default values */
767 track->default_track = 1;
768 track->name = 0;
769 track->language = strdup("eng");
771 len = length = ebml_read_length (s, &il);
772 len += il;
773 while (length > 0)
775 switch (ebml_read_id (s, &il))
777 case MATROSKA_ID_TRACKNUMBER:
779 uint64_t num = ebml_read_uint (s, &l);
780 if (num == EBML_UINT_INVALID)
781 goto err_out;
782 track->tnum = num;
783 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Track number: %u\n",
784 track->tnum);
785 break;
788 case MATROSKA_ID_TRACKNAME:
790 track->name = ebml_read_utf8 (s, &l);
791 if (track->name == NULL)
792 goto err_out;
793 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Name: %s\n",
794 track->name);
795 break;
798 case MATROSKA_ID_TRACKTYPE:
800 uint64_t num = ebml_read_uint (s, &l);
801 if (num == EBML_UINT_INVALID)
802 return 0;
803 track->type = num;
804 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Track type: ");
805 switch (track->type)
807 case MATROSKA_TRACK_AUDIO:
808 mp_msg (MSGT_DEMUX, MSGL_V, "Audio\n");
809 break;
810 case MATROSKA_TRACK_VIDEO:
811 mp_msg (MSGT_DEMUX, MSGL_V, "Video\n");
812 break;
813 case MATROSKA_TRACK_SUBTITLE:
814 mp_msg (MSGT_DEMUX, MSGL_V, "Subtitle\n");
815 break;
816 default:
817 mp_msg (MSGT_DEMUX, MSGL_V, "unknown\n");
818 break;
820 break;
823 case MATROSKA_ID_TRACKAUDIO:
824 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Audio track\n");
825 l = demux_mkv_read_trackaudio (demuxer, track);
826 if (l == 0)
827 goto err_out;
828 break;
830 case MATROSKA_ID_TRACKVIDEO:
831 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Video track\n");
832 l = demux_mkv_read_trackvideo (demuxer, track);
833 if (l == 0)
834 goto err_out;
835 break;
837 case MATROSKA_ID_CODECID:
838 track->codec_id = ebml_read_ascii (s, &l);
839 if (track->codec_id == NULL)
840 goto err_out;
841 if (!strcmp (track->codec_id, MKV_V_MSCOMP) ||
842 !strcmp (track->codec_id, MKV_A_ACM))
843 track->ms_compat = 1;
844 else if (!strcmp (track->codec_id, MKV_S_VOBSUB))
845 track->subtitle_type = MATROSKA_SUBTYPE_VOBSUB;
846 else if (!strcmp (track->codec_id, MKV_S_TEXTSSA)
847 || !strcmp (track->codec_id, MKV_S_TEXTASS)
848 || !strcmp (track->codec_id, MKV_S_SSA)
849 || !strcmp (track->codec_id, MKV_S_ASS))
851 track->subtitle_type = MATROSKA_SUBTYPE_SSA;
853 else if (!strcmp (track->codec_id, MKV_S_TEXTASCII))
854 track->subtitle_type = MATROSKA_SUBTYPE_TEXT;
855 if (!strcmp (track->codec_id, MKV_S_TEXTUTF8))
857 track->subtitle_type = MATROSKA_SUBTYPE_TEXT;
859 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Codec ID: %s\n",
860 track->codec_id);
861 break;
863 case MATROSKA_ID_CODECPRIVATE:
865 int x;
866 uint64_t num = ebml_read_length (s, &x);
867 // audit: cheap guard against overflows later..
868 if (num > SIZE_MAX - 1000) return 0;
869 l = x + num;
870 track->private_data = malloc (num + AV_LZO_INPUT_PADDING);
871 if (stream_read(s, track->private_data, num) != (int) num)
872 goto err_out;
873 track->private_size = num;
874 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + CodecPrivate, length "
875 "%u\n", track->private_size);
876 break;
879 case MATROSKA_ID_TRACKLANGUAGE:
880 free(track->language);
881 track->language = ebml_read_utf8 (s, &l);
882 if (track->language == NULL)
883 goto err_out;
884 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Language: %s\n",
885 track->language);
886 break;
888 case MATROSKA_ID_TRACKFLAGDEFAULT:
890 uint64_t num = ebml_read_uint (s, &l);
891 if (num == EBML_UINT_INVALID)
892 goto err_out;
893 track->default_track = num;
894 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Default flag: %u\n",
895 track->default_track);
896 break;
899 case MATROSKA_ID_TRACKDEFAULTDURATION:
901 uint64_t num = ebml_read_uint (s, &l);
902 if (num == EBML_UINT_INVALID)
903 goto err_out;
904 if (num == 0)
905 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Default duration: 0");
906 else
908 track->v_frate = 1000000000.0 / num;
909 track->default_duration = num / 1000000000.0;
910 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Default duration: "
911 "%.3fms ( = %.3f fps)\n",num/1000000.0,track->v_frate);
913 break;
916 case MATROSKA_ID_TRACKENCODINGS:
917 l = demux_mkv_read_trackencodings (demuxer, track);
918 if (l == 0)
919 goto err_out;
920 break;
922 default:
923 ebml_read_skip (s, &l);
924 break;
926 length -= l + il;
929 mkv_d->tracks[mkv_d->num_tracks++] = track;
930 return len;
932 err_out:
933 demux_mkv_free_trackentry(track);
934 return 0;
937 static int
938 demux_mkv_read_tracks (demuxer_t *demuxer)
940 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
941 stream_t *s = demuxer->stream;
942 uint64_t length, l;
943 int il;
945 mkv_d->tracks = malloc (sizeof (*mkv_d->tracks));
946 mkv_d->num_tracks = 0;
948 length = ebml_read_length (s, NULL);
949 while (length > 0)
951 switch (ebml_read_id (s, &il))
953 case MATROSKA_ID_TRACKENTRY:
954 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + a track...\n");
955 mkv_d->tracks = realloc (mkv_d->tracks,
956 (mkv_d->num_tracks+1)
957 *sizeof (*mkv_d->tracks));
958 l = demux_mkv_read_trackentry (demuxer);
959 if (l == 0)
960 return 1;
961 break;
963 default:
964 ebml_read_skip (s, &l);
965 break;
967 length -= l + il;
969 return 0;
972 static int
973 demux_mkv_read_cues (demuxer_t *demuxer)
975 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
976 stream_t *s = demuxer->stream;
977 uint64_t length, l, time, track, pos;
978 off_t off;
979 int i, il;
981 if (index_mode == 0) {
982 ebml_read_skip (s, NULL);
983 return 0;
985 off = stream_tell (s);
986 for (i=0; i<mkv_d->parsed_cues_num; i++)
987 if (mkv_d->parsed_cues[i] == off)
989 ebml_read_skip (s, NULL);
990 return 0;
992 mkv_d->parsed_cues = realloc (mkv_d->parsed_cues,
993 (mkv_d->parsed_cues_num+1)
994 * sizeof (off_t));
995 mkv_d->parsed_cues[mkv_d->parsed_cues_num++] = off;
997 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] /---- [ parsing cues ] -----------\n");
998 length = ebml_read_length (s, NULL);
1000 while (length > 0)
1002 time = track = pos = EBML_UINT_INVALID;
1004 switch (ebml_read_id (s, &il))
1006 case MATROSKA_ID_POINTENTRY:
1008 uint64_t len;
1010 len = ebml_read_length (s, &i);
1011 l = len + i;
1013 while (len > 0)
1015 uint64_t l;
1016 int il;
1018 switch (ebml_read_id (s, &il))
1020 case MATROSKA_ID_CUETIME:
1021 time = ebml_read_uint (s, &l);
1022 break;
1024 case MATROSKA_ID_CUETRACKPOSITION:
1026 uint64_t le;
1028 le = ebml_read_length (s, &i);
1029 l = le + i;
1031 while (le > 0)
1033 uint64_t l;
1034 int il;
1036 switch (ebml_read_id (s, &il))
1038 case MATROSKA_ID_CUETRACK:
1039 track = ebml_read_uint (s, &l);
1040 break;
1042 case MATROSKA_ID_CUECLUSTERPOSITION:
1043 pos = ebml_read_uint (s, &l);
1044 break;
1046 default:
1047 ebml_read_skip (s, &l);
1048 break;
1050 le -= l + il;
1052 break;
1055 default:
1056 ebml_read_skip (s, &l);
1057 break;
1059 len -= l + il;
1061 break;
1064 default:
1065 ebml_read_skip (s, &l);
1066 break;
1069 length -= l + il;
1071 if (time != EBML_UINT_INVALID && track != EBML_UINT_INVALID
1072 && pos != EBML_UINT_INVALID)
1074 grow_array(&mkv_d->indexes, mkv_d->num_indexes, sizeof(mkv_index_t));
1075 if (!mkv_d->indexes) {
1076 mkv_d->num_indexes = 0;
1077 break;
1079 mkv_d->indexes[mkv_d->num_indexes].tnum = track;
1080 mkv_d->indexes[mkv_d->num_indexes].timecode = time;
1081 mkv_d->indexes[mkv_d->num_indexes].filepos =mkv_d->segment_start+pos;
1082 mp_msg (MSGT_DEMUX, MSGL_DBG2, "[mkv] |+ found cue point "
1083 "for track %"PRIu64": timecode %"PRIu64", filepos: %"PRIu64"\n",
1084 track, time, mkv_d->segment_start + pos);
1085 mkv_d->num_indexes++;
1089 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] \\---- [ parsing cues ] -----------\n");
1090 return 0;
1093 static int
1094 demux_mkv_read_chapters (demuxer_t *demuxer)
1096 stream_t *s = demuxer->stream;
1097 uint64_t length, l;
1098 int il;
1100 if (demuxer->chapters)
1102 ebml_read_skip (s, NULL);
1103 return 0;
1106 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] /---- [ parsing chapters ] ---------\n");
1107 length = ebml_read_length (s, NULL);
1109 while (length > 0)
1111 switch (ebml_read_id (s, &il))
1113 case MATROSKA_ID_EDITIONENTRY:
1115 uint64_t len;
1116 int i;
1118 len = ebml_read_length (s, &i);
1119 l = len + i;
1121 while (len > 0)
1123 uint64_t l;
1124 int il;
1126 switch (ebml_read_id (s, &il))
1128 case MATROSKA_ID_CHAPTERATOM:
1130 uint64_t len, start=0, end=0;
1131 char* name = 0;
1132 int i;
1133 int cid;
1135 len = ebml_read_length (s, &i);
1136 l = len + i;
1138 while (len > 0)
1140 uint64_t l;
1141 int il;
1143 switch (ebml_read_id (s, &il))
1145 case MATROSKA_ID_CHAPTERTIMESTART:
1146 start = ebml_read_uint (s, &l) / 1000000;
1147 break;
1149 case MATROSKA_ID_CHAPTERTIMEEND:
1150 end = ebml_read_uint (s, &l) / 1000000;
1151 break;
1153 case MATROSKA_ID_CHAPTERDISPLAY:
1155 uint64_t len;
1156 int i;
1158 len = ebml_read_length (s, &i);
1159 l = len + i;
1160 while (len > 0)
1162 uint64_t l;
1163 int il;
1165 switch (ebml_read_id (s, &il))
1167 case MATROSKA_ID_CHAPSTRING:
1168 name = ebml_read_utf8 (s, &l);
1169 break;
1170 default:
1171 ebml_read_skip (s, &l);
1172 break;
1174 len -= l + il;
1177 break;
1179 default:
1180 ebml_read_skip (s, &l);
1181 break;
1183 len -= l + il;
1186 if (!name)
1187 name = strdup("(unnamed)");
1189 cid = demuxer_add_chapter(demuxer, name, start, end);
1191 mp_msg(MSGT_DEMUX, MSGL_V,
1192 "[mkv] Chapter %u from %02d:%02d:%02d."
1193 "%03d to %02d:%02d:%02d.%03d, %s\n",
1194 cid,
1195 (int) (start / 60 / 60 / 1000),
1196 (int) ((start / 60 / 1000) % 60),
1197 (int) ((start / 1000) % 60),
1198 (int) (start % 1000),
1199 (int) (end / 60 / 60 / 1000),
1200 (int) ((end / 60 / 1000) % 60),
1201 (int) ((end / 1000) % 60),
1202 (int) (end % 1000), name);
1204 free(name);
1205 break;
1208 default:
1209 ebml_read_skip (s, &l);
1210 break;
1212 len -= l + il;
1214 break;
1217 default:
1218 ebml_read_skip (s, &l);
1219 break;
1222 length -= l + il;
1225 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] \\---- [ parsing chapters ] ---------\n");
1226 return 0;
1229 static int
1230 demux_mkv_read_tags (demuxer_t *demuxer)
1232 ebml_read_skip (demuxer->stream, NULL);
1233 return 0;
1236 static int
1237 demux_mkv_read_attachments (demuxer_t *demuxer)
1239 stream_t *s = demuxer->stream;
1240 uint64_t length, l;
1241 int il;
1243 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] /---- [ parsing attachments ] ---------\n");
1244 length = ebml_read_length (s, NULL);
1246 while (length > 0)
1248 switch (ebml_read_id (s, &il))
1250 case MATROSKA_ID_ATTACHEDFILE:
1252 uint64_t len;
1253 int i;
1254 char* name = NULL;
1255 char* mime = NULL;
1256 char* data = NULL;
1257 int data_size = 0;
1259 len = ebml_read_length (s, &i);
1260 l = len + i;
1262 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + an attachment...\n");
1264 while (len > 0)
1266 uint64_t l;
1267 int il;
1269 switch (ebml_read_id (s, &il))
1271 case MATROSKA_ID_FILENAME:
1272 name = ebml_read_utf8 (s, &l);
1273 if (name == NULL)
1274 return 0;
1275 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + FileName: %s\n",
1276 name);
1277 break;
1279 case MATROSKA_ID_FILEMIMETYPE:
1280 mime = ebml_read_ascii (s, &l);
1281 if (mime == NULL)
1282 return 0;
1283 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + FileMimeType: %s\n",
1284 mime);
1285 break;
1287 case MATROSKA_ID_FILEDATA:
1289 int x;
1290 uint64_t num = ebml_read_length (s, &x);
1291 l = x + num;
1292 free(data);
1293 data = malloc (num);
1294 if (stream_read(s, data, num) != (int) num)
1296 free(data);
1297 return 0;
1299 data_size = num;
1300 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + FileData, length "
1301 "%u\n", data_size);
1302 break;
1305 default:
1306 ebml_read_skip (s, &l);
1307 break;
1309 len -= l + il;
1312 demuxer_add_attachment(demuxer, name, mime, data, data_size);
1313 mp_msg(MSGT_DEMUX, MSGL_V,
1314 "[mkv] Attachment: %s, %s, %u bytes\n",
1315 name, mime, data_size);
1316 break;
1319 default:
1320 ebml_read_skip (s, &l);
1321 break;
1323 length -= l + il;
1326 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] \\---- [ parsing attachments ] ---------\n");
1327 return 0;
1330 static int
1331 demux_mkv_read_seekhead (demuxer_t *demuxer)
1333 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
1334 stream_t *s = demuxer->stream;
1335 uint64_t length, l, seek_pos, saved_pos, num;
1336 uint32_t seek_id;
1337 int i, il, res = 0;
1338 off_t off;
1340 off = stream_tell (s);
1341 for (i=0; i<mkv_d->parsed_seekhead_num; i++)
1342 if (mkv_d->parsed_seekhead[i] == off)
1344 ebml_read_skip (s, NULL);
1345 return 0;
1347 mkv_d->parsed_seekhead = realloc (mkv_d->parsed_seekhead,
1348 (mkv_d->parsed_seekhead_num+1)
1349 * sizeof (off_t));
1350 mkv_d->parsed_seekhead[mkv_d->parsed_seekhead_num++] = off;
1352 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] /---- [ parsing seek head ] ---------\n");
1353 length = ebml_read_length (s, NULL);
1354 /* off now holds the position of the next element after the seek head. */
1355 off = stream_tell (s) + length;
1356 while (length > 0 && !res)
1359 seek_id = 0;
1360 seek_pos = EBML_UINT_INVALID;
1362 switch (ebml_read_id (s, &il))
1364 case MATROSKA_ID_SEEKENTRY:
1366 uint64_t len;
1368 len = ebml_read_length (s, &i);
1369 l = len + i;
1371 while (len > 0)
1373 uint64_t l;
1374 int il;
1376 switch (ebml_read_id (s, &il))
1378 case MATROSKA_ID_SEEKID:
1379 num = ebml_read_uint (s, &l);
1380 if (num != EBML_UINT_INVALID)
1381 seek_id = num;
1382 break;
1384 case MATROSKA_ID_SEEKPOSITION:
1385 seek_pos = ebml_read_uint (s, &l);
1386 break;
1388 default:
1389 ebml_read_skip (s, &l);
1390 break;
1392 len -= l + il;
1395 break;
1398 default:
1399 ebml_read_skip (s, &l);
1400 break;
1402 length -= l + il;
1404 if (seek_id == 0 || seek_id == MATROSKA_ID_CLUSTER
1405 || seek_pos == EBML_UINT_INVALID ||
1406 ((mkv_d->segment_start + seek_pos) >= (uint64_t)demuxer->movi_end))
1407 continue;
1409 saved_pos = stream_tell (s);
1410 if (!stream_seek (s, mkv_d->segment_start + seek_pos))
1411 res = 1;
1412 else
1414 if (ebml_read_id (s, &il) != seek_id)
1415 res = 1;
1416 else
1417 switch (seek_id)
1419 case MATROSKA_ID_CUES:
1420 if (demux_mkv_read_cues (demuxer))
1421 res = 1;
1422 break;
1424 case MATROSKA_ID_TAGS:
1425 if (demux_mkv_read_tags (demuxer))
1426 res = 1;
1427 break;
1429 case MATROSKA_ID_SEEKHEAD:
1430 if (demux_mkv_read_seekhead (demuxer))
1431 res = 1;
1432 break;
1434 case MATROSKA_ID_CHAPTERS:
1435 if (demux_mkv_read_chapters (demuxer))
1436 res = 1;
1437 break;
1441 stream_seek (s, saved_pos);
1443 if (res)
1445 /* If there was an error then try to skip this seek head. */
1446 if (stream_seek (s, off))
1447 res = 0;
1449 else
1450 if (length > 0)
1451 stream_seek (s, stream_tell (s) + length);
1452 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] \\---- [ parsing seek head ] ---------\n");
1453 return res;
1456 static int
1457 demux_mkv_open_video (demuxer_t *demuxer, mkv_track_t *track, int vid);
1458 static int
1459 demux_mkv_open_audio (demuxer_t *demuxer, mkv_track_t *track, int aid);
1460 static int
1461 demux_mkv_open_sub (demuxer_t *demuxer, mkv_track_t *track, int sid);
1463 static void
1464 display_create_tracks (demuxer_t *demuxer)
1466 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *)demuxer->priv;
1467 int i, vid=0, aid=0, sid=0;
1469 for (i=0; i<mkv_d->num_tracks; i++)
1471 char *type = "unknown", str[32];
1472 *str = '\0';
1473 switch (mkv_d->tracks[i]->type)
1475 case MATROSKA_TRACK_VIDEO:
1476 type = "video";
1477 demux_mkv_open_video(demuxer, mkv_d->tracks[i], vid);
1478 if (mkv_d->tracks[i]->name)
1479 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VID_%d_NAME=%s\n", vid, mkv_d->tracks[i]->name);
1480 sprintf (str, "-vid %u", vid++);
1481 break;
1482 case MATROSKA_TRACK_AUDIO:
1483 type = "audio";
1484 demux_mkv_open_audio(demuxer, mkv_d->tracks[i], aid);
1485 if (mkv_d->tracks[i]->name)
1486 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AID_%d_NAME=%s\n", aid, mkv_d->tracks[i]->name);
1487 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AID_%d_LANG=%s\n", aid, mkv_d->tracks[i]->language);
1488 sprintf (str, "-aid %u, -alang %.5s",aid++,mkv_d->tracks[i]->language);
1489 break;
1490 case MATROSKA_TRACK_SUBTITLE:
1491 type = "subtitles";
1492 demux_mkv_open_sub(demuxer, mkv_d->tracks[i], sid);
1493 if (mkv_d->tracks[i]->name)
1494 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SID_%d_NAME=%s\n", sid, mkv_d->tracks[i]->name);
1495 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SID_%d_LANG=%s\n", sid, mkv_d->tracks[i]->language);
1496 sprintf (str, "-sid %u, -slang %.5s",sid++,mkv_d->tracks[i]->language);
1497 break;
1499 if (mkv_d->tracks[i]->name)
1500 mp_msg(MSGT_DEMUX, MSGL_INFO, MSGTR_MPDEMUX_MKV_TrackIDName,
1501 mkv_d->tracks[i]->tnum, type, mkv_d->tracks[i]->codec_id, mkv_d->tracks[i]->name, str);
1502 else
1503 mp_msg(MSGT_DEMUX, MSGL_INFO, MSGTR_MPDEMUX_MKV_TrackID,
1504 mkv_d->tracks[i]->tnum, type, mkv_d->tracks[i]->codec_id, str);
1508 typedef struct {
1509 char *id;
1510 int fourcc;
1511 int extradata;
1512 } videocodec_info_t;
1514 static const videocodec_info_t vinfo[] = {
1515 { MKV_V_MPEG1, mmioFOURCC('m', 'p', 'g', '1'), 0 },
1516 { MKV_V_MPEG2, mmioFOURCC('m', 'p', 'g', '2'), 0 },
1517 { MKV_V_MPEG4_SP, mmioFOURCC('m', 'p', '4', 'v'), 1 },
1518 { MKV_V_MPEG4_ASP, mmioFOURCC('m', 'p', '4', 'v'), 1 },
1519 { MKV_V_MPEG4_AP, mmioFOURCC('m', 'p', '4', 'v'), 1 },
1520 { MKV_V_MPEG4_AVC, mmioFOURCC('a', 'v', 'c', '1'), 1 },
1521 { MKV_V_THEORA, mmioFOURCC('t', 'h', 'e', 'o'), 1 },
1522 { NULL, 0, 0 }
1525 static int
1526 demux_mkv_open_video (demuxer_t *demuxer, mkv_track_t *track, int vid)
1528 BITMAPINFOHEADER *bih;
1529 void *ImageDesc = NULL;
1530 sh_video_t *sh_v;
1532 if (track->ms_compat) /* MS compatibility mode */
1534 BITMAPINFOHEADER *src;
1536 if (track->private_data == NULL
1537 || track->private_size < sizeof (BITMAPINFOHEADER))
1538 return 1;
1540 src = (BITMAPINFOHEADER *) track->private_data;
1541 bih = calloc (1, track->private_size);
1542 bih->biSize = le2me_32 (src->biSize);
1543 bih->biWidth = le2me_32 (src->biWidth);
1544 bih->biHeight = le2me_32 (src->biHeight);
1545 bih->biPlanes = le2me_16 (src->biPlanes);
1546 bih->biBitCount = le2me_16 (src->biBitCount);
1547 bih->biCompression = le2me_32 (src->biCompression);
1548 bih->biSizeImage = le2me_32 (src->biSizeImage);
1549 bih->biXPelsPerMeter = le2me_32 (src->biXPelsPerMeter);
1550 bih->biYPelsPerMeter = le2me_32 (src->biYPelsPerMeter);
1551 bih->biClrUsed = le2me_32 (src->biClrUsed);
1552 bih->biClrImportant = le2me_32 (src->biClrImportant);
1553 memcpy((char *) bih + sizeof (BITMAPINFOHEADER),
1554 (char *) src + sizeof (BITMAPINFOHEADER),
1555 track->private_size - sizeof (BITMAPINFOHEADER));
1557 if (track->v_width == 0)
1558 track->v_width = bih->biWidth;
1559 if (track->v_height == 0)
1560 track->v_height = bih->biHeight;
1562 else
1564 bih = calloc (1, sizeof (BITMAPINFOHEADER));
1565 bih->biSize = sizeof (BITMAPINFOHEADER);
1566 bih->biWidth = track->v_width;
1567 bih->biHeight = track->v_height;
1568 bih->biBitCount = 24;
1569 bih->biSizeImage = bih->biWidth * bih->biHeight * bih->biBitCount/8;
1571 if (track->private_size >= RVPROPERTIES_SIZE
1572 && (!strcmp (track->codec_id, MKV_V_REALV10)
1573 || !strcmp (track->codec_id, MKV_V_REALV20)
1574 || !strcmp (track->codec_id, MKV_V_REALV30)
1575 || !strcmp (track->codec_id, MKV_V_REALV40)))
1577 unsigned char *dst, *src;
1578 uint32_t type2;
1579 unsigned int cnt;
1581 src = (uint8_t *)track->private_data + RVPROPERTIES_SIZE;
1583 cnt = track->private_size - RVPROPERTIES_SIZE;
1584 bih = realloc(bih, sizeof (BITMAPINFOHEADER)+8+cnt);
1585 bih->biSize = 48+cnt;
1586 bih->biPlanes = 1;
1587 type2 = AV_RB32(src - 4);
1588 if (type2 == 0x10003000 || type2 == 0x10003001)
1589 bih->biCompression=mmioFOURCC('R','V','1','3');
1590 else
1591 bih->biCompression=mmioFOURCC('R','V',track->codec_id[9],'0');
1592 dst = (unsigned char *) (bih + 1);
1593 // copy type1 and type2 info from rv properties
1594 memcpy(dst, src - 8, 8);
1595 stream_read(demuxer->stream, dst+8, cnt);
1596 track->realmedia = 1;
1598 #ifdef CONFIG_QTX_CODECS
1600 else if (track->private_size >= sizeof (ImageDescription)
1601 && !strcmp(track->codec_id, MKV_V_QUICKTIME))
1603 ImageDescriptionPtr idesc;
1605 idesc = (ImageDescriptionPtr) track->private_data;
1606 idesc->idSize = be2me_32 (idesc->idSize);
1607 idesc->cType = be2me_32 (idesc->cType);
1608 idesc->version = be2me_16 (idesc->version);
1609 idesc->revisionLevel = be2me_16 (idesc->revisionLevel);
1610 idesc->vendor = be2me_32 (idesc->vendor);
1611 idesc->temporalQuality = be2me_32 (idesc->temporalQuality);
1612 idesc->spatialQuality = be2me_32 (idesc->spatialQuality);
1613 idesc->width = be2me_16 (idesc->width);
1614 idesc->height = be2me_16 (idesc->height);
1615 idesc->hRes = be2me_32 (idesc->hRes);
1616 idesc->vRes = be2me_32 (idesc->vRes);
1617 idesc->dataSize = be2me_32 (idesc->dataSize);
1618 idesc->frameCount = be2me_16 (idesc->frameCount);
1619 idesc->depth = be2me_16 (idesc->depth);
1620 idesc->clutID = be2me_16 (idesc->clutID);
1621 bih->biPlanes = 1;
1622 bih->biCompression = idesc->cType;
1623 ImageDesc = idesc;
1624 #endif /* CONFIG_QTX_CODECS */
1627 else
1629 const videocodec_info_t *vi = vinfo;
1630 while (vi->id && strcmp(vi->id, track->codec_id)) vi++;
1631 bih->biCompression = vi->fourcc;
1632 if (vi->extradata && track->private_data && (track->private_size > 0))
1634 bih->biSize += track->private_size;
1635 bih = realloc (bih, bih->biSize);
1636 memcpy (bih + 1, track->private_data, track->private_size);
1638 track->reorder_timecodes = user_correct_pts == 0;
1639 if (!vi->id) {
1640 mp_msg (MSGT_DEMUX,MSGL_WARN, MSGTR_MPDEMUX_MKV_UnknownCodecID,
1641 track->codec_id, track->tnum);
1642 free(bih);
1643 return 1;
1648 sh_v = new_sh_video_vid (demuxer, track->tnum, vid);
1649 sh_v->bih = bih;
1650 sh_v->format = sh_v->bih->biCompression;
1651 if (track->v_frate == 0.0)
1652 track->v_frate = 25.0;
1653 sh_v->fps = track->v_frate;
1654 sh_v->frametime = 1 / track->v_frate;
1655 sh_v->aspect = 0;
1656 if (!track->realmedia)
1658 sh_v->disp_w = track->v_width;
1659 sh_v->disp_h = track->v_height;
1660 if (track->v_dheight)
1661 sh_v->aspect = (float)track->v_dwidth / (float)track->v_dheight;
1663 else
1665 // vd_realvid.c will set aspect to disp_w/disp_h and rederive
1666 // disp_w and disp_h from the RealVideo stream contents returned
1667 // by the Real DLLs. If DisplayWidth/DisplayHeight was not set in
1668 // the Matroska file then it has already been set to PixelWidth/Height
1669 // by check_track_information.
1670 sh_v->disp_w = track->v_dwidth;
1671 sh_v->disp_h = track->v_dheight;
1673 sh_v->ImageDesc = ImageDesc;
1674 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] Aspect: %f\n", sh_v->aspect);
1676 sh_v->ds = demuxer->video;
1677 return 0;
1680 static int
1681 demux_mkv_open_audio (demuxer_t *demuxer, mkv_track_t *track, int aid)
1683 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
1684 sh_audio_t *sh_a = new_sh_audio_aid(demuxer, track->tnum, aid);
1685 demux_packet_t *dp;
1686 if(!sh_a) return 1;
1687 mkv_d->audio_tracks[mkv_d->last_aid] = track->tnum;
1689 if (track->language && (strcmp(track->language, "und") != 0))
1690 sh_a->lang = strdup(track->language);
1691 sh_a->default_track = track->default_track;
1692 sh_a->ds = demuxer->audio;
1693 sh_a->wf = malloc (sizeof (WAVEFORMATEX));
1694 if (track->ms_compat && (track->private_size >= sizeof(WAVEFORMATEX)))
1696 WAVEFORMATEX *wf = (WAVEFORMATEX *)track->private_data;
1697 sh_a->wf = realloc(sh_a->wf, track->private_size);
1698 sh_a->wf->wFormatTag = le2me_16 (wf->wFormatTag);
1699 sh_a->wf->nChannels = le2me_16 (wf->nChannels);
1700 sh_a->wf->nSamplesPerSec = le2me_32 (wf->nSamplesPerSec);
1701 sh_a->wf->nAvgBytesPerSec = le2me_32 (wf->nAvgBytesPerSec);
1702 sh_a->wf->nBlockAlign = le2me_16 (wf->nBlockAlign);
1703 sh_a->wf->wBitsPerSample = le2me_16 (wf->wBitsPerSample);
1704 sh_a->wf->cbSize = track->private_size - sizeof(WAVEFORMATEX);
1705 memcpy(sh_a->wf + 1, wf + 1, track->private_size - sizeof(WAVEFORMATEX));
1706 if (track->a_sfreq == 0.0)
1707 track->a_sfreq = sh_a->wf->nSamplesPerSec;
1708 if (track->a_channels == 0)
1709 track->a_channels = sh_a->wf->nChannels;
1710 if (track->a_bps == 0)
1711 track->a_bps = sh_a->wf->wBitsPerSample;
1712 track->a_formattag = sh_a->wf->wFormatTag;
1714 else
1716 memset(sh_a->wf, 0, sizeof (WAVEFORMATEX));
1717 if (!strcmp(track->codec_id, MKV_A_MP3) ||
1718 !strcmp(track->codec_id, MKV_A_MP2))
1719 track->a_formattag = 0x0055;
1720 else if (!strncmp(track->codec_id, MKV_A_AC3, strlen(MKV_A_AC3)))
1721 track->a_formattag = 0x2000;
1722 else if (!strcmp(track->codec_id, MKV_A_DTS))
1723 track->a_formattag = 0x2001;
1724 else if (!strcmp(track->codec_id, MKV_A_PCM) ||
1725 !strcmp(track->codec_id, MKV_A_PCM_BE))
1726 track->a_formattag = 0x0001;
1727 else if (!strcmp(track->codec_id, MKV_A_AAC_2MAIN) ||
1728 !strncmp(track->codec_id, MKV_A_AAC_2LC,
1729 strlen(MKV_A_AAC_2LC)) ||
1730 !strcmp(track->codec_id, MKV_A_AAC_2SSR) ||
1731 !strcmp(track->codec_id, MKV_A_AAC_4MAIN) ||
1732 !strncmp(track->codec_id, MKV_A_AAC_4LC,
1733 strlen(MKV_A_AAC_4LC)) ||
1734 !strcmp(track->codec_id, MKV_A_AAC_4SSR) ||
1735 !strcmp(track->codec_id, MKV_A_AAC_4LTP) ||
1736 !strcmp(track->codec_id, MKV_A_AAC))
1737 track->a_formattag = mmioFOURCC('M', 'P', '4', 'A');
1738 else if (!strcmp(track->codec_id, MKV_A_VORBIS))
1740 if (track->private_data == NULL)
1741 return 1;
1742 track->a_formattag = mmioFOURCC('v', 'r', 'b', 's');
1744 else if (!strcmp(track->codec_id, MKV_A_QDMC))
1745 track->a_formattag = mmioFOURCC('Q', 'D', 'M', 'C');
1746 else if (!strcmp(track->codec_id, MKV_A_QDMC2))
1747 track->a_formattag = mmioFOURCC('Q', 'D', 'M', '2');
1748 else if (!strcmp(track->codec_id, MKV_A_WAVPACK))
1749 track->a_formattag = mmioFOURCC('W', 'V', 'P', 'K');
1750 else if (!strcmp(track->codec_id, MKV_A_TRUEHD))
1751 track->a_formattag = mmioFOURCC('T', 'R', 'H', 'D');
1752 else if (!strcmp(track->codec_id, MKV_A_FLAC))
1754 if (track->private_data == NULL || track->private_size == 0)
1756 mp_msg (MSGT_DEMUX, MSGL_WARN,
1757 MSGTR_MPDEMUX_MKV_FlacTrackDoesNotContainValidHeaders);
1758 return 1;
1760 track->a_formattag = mmioFOURCC ('f', 'L', 'a', 'C');
1762 else if (track->private_size >= RAPROPERTIES4_SIZE)
1764 if (!strcmp(track->codec_id, MKV_A_REAL28))
1765 track->a_formattag = mmioFOURCC('2', '8', '_', '8');
1766 else if (!strcmp(track->codec_id, MKV_A_REALATRC))
1767 track->a_formattag = mmioFOURCC('a', 't', 'r', 'c');
1768 else if (!strcmp(track->codec_id, MKV_A_REALCOOK))
1769 track->a_formattag = mmioFOURCC('c', 'o', 'o', 'k');
1770 else if (!strcmp(track->codec_id, MKV_A_REALDNET))
1771 track->a_formattag = mmioFOURCC('d', 'n', 'e', 't');
1772 else if (!strcmp(track->codec_id, MKV_A_REALSIPR))
1773 track->a_formattag = mmioFOURCC('s', 'i', 'p', 'r');
1775 else
1777 mp_msg (MSGT_DEMUX, MSGL_WARN, MSGTR_MPDEMUX_MKV_UnknownAudioCodec,
1778 track->codec_id, track->tnum);
1779 free_sh_audio(demuxer, track->tnum);
1780 return 1;
1784 sh_a->format = track->a_formattag;
1785 sh_a->wf->wFormatTag = track->a_formattag;
1786 sh_a->channels = track->a_channels;
1787 sh_a->wf->nChannels = track->a_channels;
1788 sh_a->samplerate = (uint32_t) track->a_sfreq;
1789 sh_a->wf->nSamplesPerSec = (uint32_t) track->a_sfreq;
1790 if (track->a_bps == 0)
1792 sh_a->samplesize = 2;
1793 sh_a->wf->wBitsPerSample = 16;
1795 else
1797 sh_a->samplesize = track->a_bps / 8;
1798 sh_a->wf->wBitsPerSample = track->a_bps;
1800 if (track->a_formattag == 0x0055) /* MP3 || MP2 */
1802 sh_a->wf->nAvgBytesPerSec = 16000;
1803 sh_a->wf->nBlockAlign = 1152;
1805 else if ((track->a_formattag == 0x2000) || /* AC3 */
1806 (track->a_formattag == 0x2001)) /* DTS */
1808 free(sh_a->wf);
1809 sh_a->wf = NULL;
1811 else if (track->a_formattag == 0x0001) /* PCM || PCM_BE */
1813 sh_a->wf->nAvgBytesPerSec = sh_a->channels * sh_a->samplerate*2;
1814 sh_a->wf->nBlockAlign = sh_a->wf->nAvgBytesPerSec;
1815 if (!strcmp(track->codec_id, MKV_A_PCM_BE))
1816 sh_a->format = mmioFOURCC('t', 'w', 'o', 's');
1818 else if (!strcmp(track->codec_id, MKV_A_QDMC) ||
1819 !strcmp(track->codec_id, MKV_A_QDMC2))
1821 sh_a->wf->nAvgBytesPerSec = 16000;
1822 sh_a->wf->nBlockAlign = 1486;
1823 track->fix_i_bps = 1;
1824 track->qt_last_a_pts = 0.0;
1825 if (track->private_data != NULL)
1827 sh_a->codecdata=malloc(track->private_size);
1828 memcpy (sh_a->codecdata, track->private_data,
1829 track->private_size);
1830 sh_a->codecdata_len = track->private_size;
1833 else if (track->a_formattag == mmioFOURCC('M', 'P', '4', 'A'))
1835 int profile, srate_idx;
1837 sh_a->wf->nAvgBytesPerSec = 16000;
1838 sh_a->wf->nBlockAlign = 1024;
1840 if (!strcmp (track->codec_id, MKV_A_AAC) &&
1841 (NULL != track->private_data))
1843 sh_a->codecdata=malloc(track->private_size);
1844 memcpy (sh_a->codecdata, track->private_data,
1845 track->private_size);
1846 sh_a->codecdata_len = track->private_size;
1847 return 0;
1850 /* Recreate the 'private data' */
1851 /* which faad2 uses in its initialization */
1852 srate_idx = aac_get_sample_rate_index (sh_a->samplerate);
1853 if (!strncmp (&track->codec_id[12], "MAIN", 4))
1854 profile = 0;
1855 else if (!strncmp (&track->codec_id[12], "LC", 2))
1856 profile = 1;
1857 else if (!strncmp (&track->codec_id[12], "SSR", 3))
1858 profile = 2;
1859 else
1860 profile = 3;
1861 sh_a->codecdata = malloc (5);
1862 sh_a->codecdata[0] = ((profile+1) << 3) | ((srate_idx&0xE) >> 1);
1863 sh_a->codecdata[1] = ((srate_idx&0x1)<<7)|(track->a_channels<<3);
1865 if (strstr(track->codec_id, "SBR") != NULL)
1867 /* HE-AAC (aka SBR AAC) */
1868 sh_a->codecdata_len = 5;
1870 sh_a->samplerate *= 2;
1871 sh_a->wf->nSamplesPerSec *= 2;
1872 srate_idx = aac_get_sample_rate_index(sh_a->samplerate);
1873 sh_a->codecdata[2] = AAC_SYNC_EXTENSION_TYPE >> 3;
1874 sh_a->codecdata[3] = ((AAC_SYNC_EXTENSION_TYPE&0x07)<<5) | 5;
1875 sh_a->codecdata[4] = (1 << 7) | (srate_idx << 3);
1876 track->default_duration = 1024.0 / (sh_a->samplerate / 2);
1878 else
1880 sh_a->codecdata_len = 2;
1881 track->default_duration = 1024.0 / (float)sh_a->samplerate;
1884 else if (track->a_formattag == mmioFOURCC('v', 'r', 'b', 's')) /* VORBIS */
1886 sh_a->wf->cbSize = track->private_size;
1887 sh_a->wf = realloc(sh_a->wf, sizeof(WAVEFORMATEX) + sh_a->wf->cbSize);
1888 memcpy((unsigned char *) (sh_a->wf+1), track->private_data, sh_a->wf->cbSize);
1890 else if (track->private_size >= RAPROPERTIES4_SIZE
1891 && !strncmp (track->codec_id, MKV_A_REALATRC, 7))
1893 /* Common initialization for all RealAudio codecs */
1894 unsigned char *src = track->private_data;
1895 int codecdata_length, version;
1896 int flavor;
1898 sh_a->wf->nAvgBytesPerSec = 0; /* FIXME !? */
1900 version = AV_RB16(src + 4);
1901 flavor = AV_RB16(src + 22);
1902 track->coded_framesize = AV_RB32(src + 24);
1903 track->sub_packet_h = AV_RB16(src + 40);
1904 sh_a->wf->nBlockAlign =
1905 track->audiopk_size = AV_RB16(src + 42);
1906 track->sub_packet_size = AV_RB16(src + 44);
1907 if (version == 4)
1909 src += RAPROPERTIES4_SIZE;
1910 src += src[0] + 1;
1911 src += src[0] + 1;
1913 else
1914 src += RAPROPERTIES5_SIZE;
1916 src += 3;
1917 if (version == 5)
1918 src++;
1919 codecdata_length = AV_RB32(src);
1920 src += 4;
1921 sh_a->wf->cbSize = codecdata_length;
1922 sh_a->wf = realloc (sh_a->wf,
1923 sizeof (WAVEFORMATEX) +
1924 sh_a->wf->cbSize);
1925 memcpy(((char *)(sh_a->wf + 1)), src, codecdata_length);
1927 switch (track->a_formattag) {
1928 case mmioFOURCC('a', 't', 'r', 'c'):
1929 sh_a->wf->nAvgBytesPerSec = atrc_fl2bps[flavor];
1930 sh_a->wf->nBlockAlign = track->sub_packet_size;
1931 track->audio_buf = malloc(track->sub_packet_h * track->audiopk_size);
1932 track->audio_timestamp = malloc(track->sub_packet_h * sizeof(float));
1933 break;
1934 case mmioFOURCC('c', 'o', 'o', 'k'):
1935 sh_a->wf->nAvgBytesPerSec = cook_fl2bps[flavor];
1936 sh_a->wf->nBlockAlign = track->sub_packet_size;
1937 track->audio_buf = malloc(track->sub_packet_h * track->audiopk_size);
1938 track->audio_timestamp = malloc(track->sub_packet_h * sizeof(float));
1939 break;
1940 case mmioFOURCC('s', 'i', 'p', 'r'):
1941 sh_a->wf->nAvgBytesPerSec = sipr_fl2bps[flavor];
1942 sh_a->wf->nBlockAlign = track->coded_framesize;
1943 track->audio_buf = malloc(track->sub_packet_h * track->audiopk_size);
1944 track->audio_timestamp = malloc(track->sub_packet_h * sizeof(float));
1945 break;
1946 case mmioFOURCC('2', '8', '_', '8'):
1947 sh_a->wf->nAvgBytesPerSec = 3600;
1948 sh_a->wf->nBlockAlign = track->coded_framesize;
1949 track->audio_buf = malloc(track->sub_packet_h * track->audiopk_size);
1950 track->audio_timestamp = malloc(track->sub_packet_h * sizeof(float));
1951 break;
1954 track->realmedia = 1;
1956 else if (!strcmp(track->codec_id, MKV_A_FLAC) ||
1957 (track->a_formattag == 0xf1ac))
1959 unsigned char *ptr;
1960 int size;
1961 free(sh_a->wf);
1962 sh_a->wf = NULL;
1964 if (track->a_formattag == mmioFOURCC('f', 'L', 'a', 'C'))
1966 ptr = (unsigned char *)track->private_data;
1967 size = track->private_size;
1969 else
1971 sh_a->format = mmioFOURCC('f', 'L', 'a', 'C');
1972 ptr = (unsigned char *) track->private_data
1973 + sizeof (WAVEFORMATEX);
1974 size = track->private_size - sizeof (WAVEFORMATEX);
1976 if (size < 4 || ptr[0] != 'f' || ptr[1] != 'L' ||
1977 ptr[2] != 'a' || ptr[3] != 'C')
1979 dp = new_demux_packet (4);
1980 memcpy (dp->buffer, "fLaC", 4);
1982 else
1984 dp = new_demux_packet (size);
1985 memcpy (dp->buffer, ptr, size);
1987 dp->pts = 0;
1988 dp->flags = 0;
1989 ds_add_packet (demuxer->audio, dp);
1991 else if (track->a_formattag == mmioFOURCC('W', 'V', 'P', 'K') ||
1992 track->a_formattag == mmioFOURCC('T', 'R', 'H', 'D'))
1993 { /* do nothing, still works */ }
1994 else if (!track->ms_compat || (track->private_size < sizeof(WAVEFORMATEX)))
1996 free_sh_audio(demuxer, track->tnum);
1997 return 1;
2000 return 0;
2003 static int
2004 demux_mkv_open_sub (demuxer_t *demuxer, mkv_track_t *track, int sid)
2006 if (track->subtitle_type != MATROSKA_SUBTYPE_UNKNOWN)
2008 int size, m;
2009 uint8_t *buffer;
2010 sh_sub_t *sh = new_sh_sub_sid(demuxer, track->tnum, sid);
2011 track->sh_sub = sh;
2012 sh->type = 't';
2013 if (track->subtitle_type == MATROSKA_SUBTYPE_VOBSUB)
2014 sh->type = 'v';
2015 if (track->subtitle_type == MATROSKA_SUBTYPE_SSA)
2016 sh->type = 'a';
2017 size = track->private_size;
2018 m = demux_mkv_decode (track,track->private_data,&buffer,&size,2);
2019 if (buffer && m)
2021 free (track->private_data);
2022 track->private_data = buffer;
2023 track->private_size = size;
2025 sh->extradata=malloc(track->private_size);
2026 memcpy (sh->extradata, track->private_data,
2027 track->private_size);
2028 sh->extradata_len = track->private_size;
2029 if (track->language && (strcmp(track->language, "und") != 0))
2030 sh->lang = strdup(track->language);
2031 sh->default_track = track->default_track;
2033 else
2035 mp_msg (MSGT_DEMUX, MSGL_ERR, MSGTR_MPDEMUX_MKV_SubtitleTypeNotSupported,
2036 track->codec_id);
2037 return 1;
2040 return 0;
2043 static void demux_mkv_seek (demuxer_t *demuxer, float rel_seek_secs, float audio_delay, int flags);
2045 static int
2046 demux_mkv_open (demuxer_t *demuxer)
2048 stream_t *s = demuxer->stream;
2049 mkv_demuxer_t *mkv_d;
2050 mkv_track_t *track;
2051 int i, version, cont = 0;
2052 char *str;
2054 stream_seek(s, s->start_pos);
2055 str = ebml_read_header (s, &version);
2056 if (str == NULL || strcmp (str, "matroska") || version > 2)
2058 mp_msg (MSGT_DEMUX, MSGL_DBG2, "[mkv] no head found\n");
2059 return 0;
2061 free (str);
2063 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] Found the head...\n");
2065 if (ebml_read_id (s, NULL) != MATROSKA_ID_SEGMENT)
2067 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] but no segment :(\n");
2068 return 0;
2070 ebml_read_length (s, NULL); /* return bytes number until EOF */
2072 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] + a segment...\n");
2074 mkv_d = calloc (1, sizeof (mkv_demuxer_t));
2075 demuxer->priv = mkv_d;
2076 mkv_d->tc_scale = 1000000;
2077 mkv_d->segment_start = stream_tell (s);
2078 mkv_d->parsed_cues = malloc (sizeof (off_t));
2079 mkv_d->parsed_seekhead = malloc (sizeof (off_t));
2081 while (!cont)
2083 switch (ebml_read_id (s, NULL))
2085 case MATROSKA_ID_INFO:
2086 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] |+ segment information...\n");
2087 cont = demux_mkv_read_info (demuxer);
2088 break;
2090 case MATROSKA_ID_TRACKS:
2091 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] |+ segment tracks...\n");
2092 cont = demux_mkv_read_tracks (demuxer);
2093 break;
2095 case MATROSKA_ID_CUES:
2096 cont = demux_mkv_read_cues (demuxer);
2097 break;
2099 case MATROSKA_ID_TAGS:
2100 cont = demux_mkv_read_tags (demuxer);
2101 break;
2103 case MATROSKA_ID_SEEKHEAD:
2104 cont = demux_mkv_read_seekhead (demuxer);
2105 break;
2107 case MATROSKA_ID_CHAPTERS:
2108 cont = demux_mkv_read_chapters (demuxer);
2109 break;
2111 case MATROSKA_ID_ATTACHMENTS:
2112 cont = demux_mkv_read_attachments (demuxer);
2113 break;
2115 case MATROSKA_ID_CLUSTER:
2117 int p, l;
2118 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] |+ found cluster, headers are "
2119 "parsed completely :)\n");
2120 /* get the first cluster timecode */
2121 p = stream_tell(s);
2122 l = ebml_read_length (s, NULL);
2123 while (ebml_read_id (s, NULL) != MATROSKA_ID_CLUSTERTIMECODE)
2125 ebml_read_skip (s, NULL);
2126 if (stream_tell (s) >= p + l)
2127 break;
2129 if (stream_tell (s) < p + l)
2131 uint64_t num = ebml_read_uint (s, NULL);
2132 if (num == EBML_UINT_INVALID)
2133 return 0;
2134 mkv_d->first_tc = num * mkv_d->tc_scale / 1000000.0;
2135 mkv_d->has_first_tc = 1;
2137 stream_seek (s, p - 4);
2138 cont = 1;
2139 break;
2142 default:
2143 cont = 1;
2144 case EBML_ID_VOID:
2145 ebml_read_skip (s, NULL);
2146 break;
2150 display_create_tracks (demuxer);
2152 /* select video track */
2153 track = NULL;
2154 if (demuxer->video->id == -1) /* automatically select a video track */
2156 /* search for a video track that has the 'default' flag set */
2157 for (i=0; i<mkv_d->num_tracks; i++)
2158 if (mkv_d->tracks[i]->type == MATROSKA_TRACK_VIDEO
2159 && mkv_d->tracks[i]->default_track)
2161 track = mkv_d->tracks[i];
2162 break;
2165 if (track == NULL)
2166 /* no track has the 'default' flag set */
2167 /* let's take the first video track */
2168 for (i=0; i<mkv_d->num_tracks; i++)
2169 if (mkv_d->tracks[i]->type == MATROSKA_TRACK_VIDEO)
2171 track = mkv_d->tracks[i];
2172 break;
2175 else if (demuxer->video->id != -2) /* -2 = no video at all */
2176 track = demux_mkv_find_track_by_num (mkv_d, demuxer->video->id,
2177 MATROSKA_TRACK_VIDEO);
2179 if (track && demuxer->v_streams[track->tnum])
2181 mp_msg (MSGT_DEMUX, MSGL_INFO,
2182 MSGTR_MPDEMUX_MKV_WillPlayVideoTrack, track->tnum);
2183 demuxer->video->id = track->tnum;
2184 demuxer->video->sh = demuxer->v_streams[track->tnum];
2186 else
2188 mp_msg (MSGT_DEMUX, MSGL_INFO, MSGTR_MPDEMUX_MKV_NoVideoTrackFound);
2189 demuxer->video->id = -2;
2192 /* select audio track */
2193 track = NULL;
2194 if (track == NULL)
2195 /* search for an audio track that has the 'default' flag set */
2196 for (i=0; i < mkv_d->num_tracks; i++)
2197 if (mkv_d->tracks[i]->type == MATROSKA_TRACK_AUDIO
2198 && mkv_d->tracks[i]->default_track)
2200 track = mkv_d->tracks[i];
2201 break;
2204 if (track == NULL)
2205 /* no track has the 'default' flag set */
2206 /* let's take the first audio track */
2207 for (i=0; i < mkv_d->num_tracks; i++)
2208 if (mkv_d->tracks[i]->type == MATROSKA_TRACK_AUDIO)
2210 track = mkv_d->tracks[i];
2211 break;
2214 if (track && demuxer->a_streams[track->tnum])
2216 demuxer->audio->id = track->tnum;
2217 demuxer->audio->sh = demuxer->a_streams[track->tnum];
2219 else
2221 mp_msg (MSGT_DEMUX, MSGL_INFO, MSGTR_MPDEMUX_MKV_NoAudioTrackFound);
2222 demuxer->audio->id = -2;
2226 if(demuxer->audio->id != -2)
2227 for (i=0; i < mkv_d->num_tracks; i++)
2229 if(mkv_d->tracks[i]->type != MATROSKA_TRACK_AUDIO)
2230 continue;
2231 if(demuxer->a_streams[track->tnum])
2233 mkv_d->last_aid++;
2234 if(mkv_d->last_aid == MAX_A_STREAMS)
2235 break;
2239 if (demuxer->chapters)
2241 for (i=0; i < (int)demuxer->num_chapters; i++)
2243 demuxer->chapters[i].start -= mkv_d->first_tc;
2244 demuxer->chapters[i].end -= mkv_d->first_tc;
2246 if (dvd_last_chapter > 0 && dvd_last_chapter <= demuxer->num_chapters)
2248 if (demuxer->chapters[dvd_last_chapter-1].end != 0)
2249 mkv_d->stop_timecode = demuxer->chapters[dvd_last_chapter-1].end;
2250 else if (dvd_last_chapter + 1 <= demuxer->num_chapters)
2251 mkv_d->stop_timecode = demuxer->chapters[dvd_last_chapter].start;
2255 if (s->end_pos == 0 || (mkv_d->indexes == NULL && index_mode < 0))
2256 demuxer->seekable = 0;
2257 else
2259 demuxer->movi_start = s->start_pos;
2260 demuxer->movi_end = s->end_pos;
2261 demuxer->seekable = 1;
2264 return DEMUXER_TYPE_MATROSKA;
2267 static void
2268 demux_close_mkv (demuxer_t *demuxer)
2270 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2272 if (mkv_d)
2274 int i;
2275 free_cached_dps (demuxer);
2276 if (mkv_d->tracks)
2278 for (i=0; i<mkv_d->num_tracks; i++)
2279 demux_mkv_free_trackentry(mkv_d->tracks[i]);
2280 free (mkv_d->tracks);
2282 free (mkv_d->indexes);
2283 free (mkv_d->cluster_positions);
2284 free (mkv_d->parsed_cues);
2285 free (mkv_d->parsed_seekhead);
2286 free (mkv_d);
2290 static int
2291 demux_mkv_read_block_lacing (uint8_t *buffer, uint64_t *size,
2292 uint8_t *laces, uint32_t **all_lace_sizes)
2294 uint32_t total = 0, *lace_size;
2295 uint8_t flags;
2296 int i;
2298 *all_lace_sizes = NULL;
2299 lace_size = NULL;
2300 /* lacing flags */
2301 flags = *buffer++;
2302 (*size)--;
2304 switch ((flags & 0x06) >> 1)
2306 case 0: /* no lacing */
2307 *laces = 1;
2308 lace_size = calloc(*laces, sizeof(uint32_t));
2309 lace_size[0] = *size;
2310 break;
2312 case 1: /* xiph lacing */
2313 case 2: /* fixed-size lacing */
2314 case 3: /* EBML lacing */
2315 *laces = *buffer++;
2316 (*size)--;
2317 (*laces)++;
2318 lace_size = calloc(*laces, sizeof(uint32_t));
2320 switch ((flags & 0x06) >> 1)
2322 case 1: /* xiph lacing */
2323 for (i=0; i < *laces-1; i++)
2325 lace_size[i] = 0;
2328 lace_size[i] += *buffer;
2329 (*size)--;
2330 } while (*buffer++ == 0xFF);
2331 total += lace_size[i];
2333 lace_size[i] = *size - total;
2334 break;
2336 case 2: /* fixed-size lacing */
2337 for (i=0; i < *laces; i++)
2338 lace_size[i] = *size / *laces;
2339 break;
2341 case 3: /* EBML lacing */
2343 int l;
2344 uint64_t num = ebml_read_vlen_uint (buffer, &l);
2345 if (num == EBML_UINT_INVALID) {
2346 free(lace_size);
2347 return 1;
2349 buffer += l;
2350 *size -= l;
2352 total = lace_size[0] = num;
2353 for (i=1; i < *laces-1; i++)
2355 int64_t snum;
2356 snum = ebml_read_vlen_int (buffer, &l);
2357 if (snum == EBML_INT_INVALID) {
2358 free(lace_size);
2359 return 1;
2361 buffer += l;
2362 *size -= l;
2363 lace_size[i] = lace_size[i-1] + snum;
2364 total += lace_size[i];
2366 lace_size[i] = *size - total;
2367 break;
2370 break;
2372 *all_lace_sizes = lace_size;
2373 return 0;
2376 static void
2377 handle_subtitles(demuxer_t *demuxer, mkv_track_t *track, char *block,
2378 int64_t size, uint64_t block_duration, uint64_t timecode)
2380 demux_packet_t *dp;
2382 if (block_duration == 0)
2384 mp_msg (MSGT_DEMUX, MSGL_WARN,
2385 MSGTR_MPDEMUX_MKV_NoBlockDurationForSubtitleTrackFound);
2386 return;
2389 sub_utf8 = 1;
2390 dp = new_demux_packet(size);
2391 memcpy(dp->buffer, block, size);
2392 dp->pts = timecode / 1000.0f;
2393 dp->endpts = (timecode + block_duration) / 1000.0f;
2394 ds_add_packet(demuxer->sub, dp);
2397 double real_fix_timestamp(unsigned char *buf, unsigned int timestamp, unsigned int format, int64_t *kf_base, int *kf_pts, double *pts);
2399 static void
2400 handle_realvideo (demuxer_t *demuxer, mkv_track_t *track, uint8_t *buffer,
2401 uint32_t size, int block_bref)
2403 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2404 demux_packet_t *dp;
2405 uint32_t timestamp = mkv_d->last_pts * 1000;
2407 dp = new_demux_packet (size);
2408 memcpy (dp->buffer, buffer, size);
2410 if (mkv_d->v_skip_to_keyframe)
2412 dp->pts = mkv_d->last_pts;
2413 track->rv_kf_base = 0;
2414 track->rv_kf_pts = timestamp;
2416 else
2417 dp->pts = real_fix_timestamp (dp->buffer, timestamp,
2418 ((sh_video_t*)demuxer->video->sh)->bih->biCompression,
2419 &track->rv_kf_base, &track->rv_kf_pts, NULL);
2420 dp->pos = demuxer->filepos;
2421 dp->flags = block_bref ? 0 : 0x10;
2423 ds_add_packet(demuxer->video, dp);
2426 static void
2427 handle_realaudio (demuxer_t *demuxer, mkv_track_t *track, uint8_t *buffer,
2428 uint32_t size, int block_bref)
2430 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2431 int sps = track->sub_packet_size;
2432 int sph = track->sub_packet_h;
2433 int cfs = track->coded_framesize;
2434 int w = track->audiopk_size;
2435 int spc = track->sub_packet_cnt;
2436 demux_packet_t *dp;
2437 int x;
2439 if ((track->a_formattag == mmioFOURCC('2', '8', '_', '8')) ||
2440 (track->a_formattag == mmioFOURCC('c', 'o', 'o', 'k')) ||
2441 (track->a_formattag == mmioFOURCC('a', 't', 'r', 'c')) ||
2442 (track->a_formattag == mmioFOURCC('s', 'i', 'p', 'r')))
2444 // if(!block_bref)
2445 // spc = track->sub_packet_cnt = 0;
2446 switch (track->a_formattag) {
2447 case mmioFOURCC('2', '8', '_', '8'):
2448 for (x = 0; x < sph / 2; x++)
2449 memcpy(track->audio_buf + x * 2 * w + spc * cfs, buffer + cfs * x, cfs);
2450 break;
2451 case mmioFOURCC('c', 'o', 'o', 'k'):
2452 case mmioFOURCC('a', 't', 'r', 'c'):
2453 for (x = 0; x < w / sps; x++)
2454 memcpy(track->audio_buf + sps * (sph * x + ((sph + 1) / 2) * (spc & 1) + (spc >> 1)), buffer + sps * x, sps);
2455 break;
2456 case mmioFOURCC('s', 'i', 'p', 'r'):
2457 memcpy(track->audio_buf + spc * w, buffer, w);
2458 if (spc == sph - 1)
2460 int n;
2461 int bs = sph * w * 2 / 96; // nibbles per subpacket
2462 // Perform reordering
2463 for(n=0; n < 38; n++)
2465 int j;
2466 int i = bs * sipr_swaps[n][0];
2467 int o = bs * sipr_swaps[n][1];
2468 // swap nibbles of block 'i' with 'o' TODO: optimize
2469 for(j = 0;j < bs; j++)
2471 int x = (i & 1) ? (track->audio_buf[i >> 1] >> 4) : (track->audio_buf[i >> 1] & 0x0F);
2472 int y = (o & 1) ? (track->audio_buf[o >> 1] >> 4) : (track->audio_buf[o >> 1] & 0x0F);
2473 if(o & 1)
2474 track->audio_buf[o >> 1] = (track->audio_buf[o >> 1] & 0x0F) | (x << 4);
2475 else
2476 track->audio_buf[o >> 1] = (track->audio_buf[o >> 1] & 0xF0) | x;
2477 if(i & 1)
2478 track->audio_buf[i >> 1] = (track->audio_buf[i >> 1] & 0x0F) | (y << 4);
2479 else
2480 track->audio_buf[i >> 1] = (track->audio_buf[i >> 1] & 0xF0) | y;
2481 ++i; ++o;
2485 break;
2487 track->audio_timestamp[track->sub_packet_cnt] = (track->ra_pts == mkv_d->last_pts) ? 0 : (mkv_d->last_pts);
2488 track->ra_pts = mkv_d->last_pts;
2489 if (track->sub_packet_cnt == 0)
2490 track->audio_filepos = demuxer->filepos;
2491 if (++(track->sub_packet_cnt) == sph)
2493 int apk_usize = ((WAVEFORMATEX*)((sh_audio_t*)demuxer->audio->sh)->wf)->nBlockAlign;
2494 track->sub_packet_cnt = 0;
2495 // Release all the audio packets
2496 for (x = 0; x < sph*w/apk_usize; x++)
2498 dp = new_demux_packet(apk_usize);
2499 memcpy(dp->buffer, track->audio_buf + x * apk_usize, apk_usize);
2500 /* Put timestamp only on packets that correspond to original audio packets in file */
2501 dp->pts = (x * apk_usize % w) ? 0 : track->audio_timestamp[x * apk_usize / w];
2502 dp->pos = track->audio_filepos; // all equal
2503 dp->flags = x ? 0 : 0x10; // Mark first packet as keyframe
2504 ds_add_packet(demuxer->audio, dp);
2507 } else { // Not a codec that require reordering
2508 dp = new_demux_packet (size);
2509 memcpy(dp->buffer, buffer, size);
2510 if (track->ra_pts == mkv_d->last_pts && !mkv_d->a_skip_to_keyframe)
2511 dp->pts = 0;
2512 else
2513 dp->pts = mkv_d->last_pts;
2514 track->ra_pts = mkv_d->last_pts;
2516 dp->pos = demuxer->filepos;
2517 dp->flags = block_bref ? 0 : 0x10;
2518 ds_add_packet (demuxer->audio, dp);
2522 /** Reorder timecodes and add cached demux packets to the queues.
2524 * Timecode reordering is needed if a video track contains B frames that
2525 * are timestamped in display order (e.g. MPEG-1, MPEG-2 or "native" MPEG-4).
2526 * MPlayer doesn't like timestamps in display order. This function adjusts
2527 * the timestamp of cached frames (which are exactly one I/P frame followed
2528 * by one or more B frames) so that they are in coding order again.
2530 * Example: The track with 25 FPS contains four frames with the timecodes
2531 * I at 0ms, P at 120ms, B at 40ms and B at 80ms. As soon as the next I
2532 * or P frame arrives these timecodes can be changed to I at 0ms, P at 40ms,
2533 * B at 80ms and B at 120ms.
2535 * This works for simple H.264 B-frame pyramids, but not for arbitrary orders.
2537 * \param demuxer The Matroska demuxer struct for this instance.
2538 * \param track The track structure whose cache should be handled.
2540 static void
2541 flush_cached_dps (demuxer_t *demuxer, mkv_track_t *track)
2543 int i, ok;
2545 if (track->num_cached_dps == 0)
2546 return;
2548 do {
2549 ok = 1;
2550 for (i = 1; i < track->num_cached_dps; i++)
2551 if (track->cached_dps[i - 1]->pts > track->cached_dps[i]->pts) {
2552 float tmp_pts = track->cached_dps[i - 1]->pts;
2553 track->cached_dps[i - 1]->pts = track->cached_dps[i]->pts;
2554 track->cached_dps[i]->pts = tmp_pts;
2555 ok = 0;
2557 } while (!ok);
2559 for (i = 0; i < track->num_cached_dps; i++)
2560 ds_add_packet (demuxer->video, track->cached_dps[i]);
2561 track->num_cached_dps = 0;
2564 /** Cache video frames if timecodes have to be reordered.
2566 * Timecode reordering is needed if a video track contains B frames that
2567 * are timestamped in display order (e.g. MPEG-1, MPEG-2 or "native" MPEG-4).
2568 * This function takes in a Matroska block read from the file, allocates a
2569 * demux packet for it, fills in its values, allocates space for storing
2570 * pointers to the cached demux packets and adds the packet to it. If
2571 * the packet contains an I or a P frame then ::flush_cached_dps is called
2572 * in order to send the old cached frames downstream.
2574 * \param demuxer The Matroska demuxer struct for this instance.
2575 * \param track The packet is meant for this track.
2576 * \param buffer The actual frame contents.
2577 * \param size The frame size in bytes.
2578 * \param block_bref A relative timecode (backward reference). If it is \c 0
2579 * then the frame is an I frame.
2580 * \param block_fref A relative timecode (forward reference). If it is \c 0
2581 * then the frame is either an I frame or a P frame depending on the value
2582 * of \a block_bref. Otherwise it's a B frame.
2584 static void
2585 handle_video_bframes (demuxer_t *demuxer, mkv_track_t *track, uint8_t *buffer,
2586 uint32_t size, int block_bref, int block_fref)
2588 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2589 demux_packet_t *dp;
2591 dp = new_demux_packet (size);
2592 memcpy(dp->buffer, buffer, size);
2593 dp->pos = demuxer->filepos;
2594 dp->pts = mkv_d->last_pts;
2595 if ((track->num_cached_dps > 0) && (dp->pts < track->max_pts))
2596 block_fref = 1;
2597 if (block_fref == 0) /* I or P frame */
2598 flush_cached_dps (demuxer, track);
2599 if (block_bref != 0) /* I frame, don't cache it */
2600 dp->flags = 0x10;
2601 if ((track->num_cached_dps + 1) > track->num_allocated_dps)
2603 track->cached_dps = (demux_packet_t **)
2604 realloc(track->cached_dps, (track->num_cached_dps + 10) *
2605 sizeof(demux_packet_t *));
2606 track->num_allocated_dps += 10;
2608 track->cached_dps[track->num_cached_dps] = dp;
2609 track->num_cached_dps++;
2610 if (dp->pts > track->max_pts)
2611 track->max_pts = dp->pts;
2614 static int
2615 handle_block (demuxer_t *demuxer, uint8_t *block, uint64_t length,
2616 uint64_t block_duration, int64_t block_bref, int64_t block_fref, uint8_t simpleblock)
2618 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2619 mkv_track_t *track = NULL;
2620 demux_stream_t *ds = NULL;
2621 uint64_t old_length;
2622 int64_t tc;
2623 uint32_t *lace_size;
2624 uint8_t laces, flags;
2625 int i, num, tmp, use_this_block = 1;
2626 float current_pts;
2627 int16_t time;
2629 /* first byte(s): track num */
2630 num = ebml_read_vlen_uint (block, &tmp);
2631 block += tmp;
2632 /* time (relative to cluster time) */
2633 time = block[0] << 8 | block[1];
2634 block += 2;
2635 length -= tmp + 2;
2636 old_length = length;
2637 flags = block[0];
2638 if (demux_mkv_read_block_lacing (block, &length, &laces, &lace_size))
2639 return 0;
2640 block += old_length - length;
2642 tc = ((time*mkv_d->tc_scale+mkv_d->cluster_tc) /1000000.0 - mkv_d->first_tc);
2643 if (tc < 0)
2644 tc = 0;
2645 if (mkv_d->stop_timecode > 0 && tc > mkv_d->stop_timecode) {
2646 free(lace_size);
2647 return -1;
2649 current_pts = tc / 1000.0;
2651 for (i=0; i<mkv_d->num_tracks; i++)
2652 if (mkv_d->tracks[i]->tnum == num) {
2653 track = mkv_d->tracks[i];
2654 break;
2656 if (track == NULL)
2658 free(lace_size);
2659 return 1;
2661 if (num == demuxer->audio->id)
2663 ds = demuxer->audio;
2665 if (mkv_d->a_skip_to_keyframe)
2667 if (simpleblock)
2669 if (!(flags&0x80)) /*current frame isn't a keyframe*/
2670 use_this_block = 0;
2672 else if (block_bref != 0)
2673 use_this_block = 0;
2675 else if (mkv_d->v_skip_to_keyframe)
2676 use_this_block = 0;
2678 if (track->fix_i_bps && use_this_block)
2680 sh_audio_t *sh = (sh_audio_t *) ds->sh;
2682 if (block_duration != 0)
2684 sh->i_bps = length * 1000 / block_duration;
2685 track->fix_i_bps = 0;
2687 else if (track->qt_last_a_pts == 0.0)
2688 track->qt_last_a_pts = current_pts;
2689 else if(track->qt_last_a_pts != current_pts)
2691 sh->i_bps = length / (current_pts - track->qt_last_a_pts);
2692 track->fix_i_bps = 0;
2696 else if (tc < mkv_d->skip_to_timecode)
2697 use_this_block = 0;
2698 else if (num == demuxer->video->id)
2700 ds = demuxer->video;
2701 if (mkv_d->v_skip_to_keyframe)
2703 if (simpleblock)
2705 if (!(flags&0x80)) /*current frame isn't a keyframe*/
2706 use_this_block = 0;
2708 else if (block_bref != 0 || block_fref != 0)
2709 use_this_block = 0;
2712 else if (num == demuxer->sub->id)
2714 ds = demuxer->sub;
2715 if (track->subtitle_type != MATROSKA_SUBTYPE_VOBSUB)
2717 if (!mkv_d->v_skip_to_keyframe)
2718 handle_subtitles (demuxer, track, block, length,
2719 block_duration, tc);
2720 use_this_block = 0;
2723 else
2724 use_this_block = 0;
2726 if (use_this_block)
2728 mkv_d->last_pts = current_pts;
2729 mkv_d->last_filepos = demuxer->filepos;
2731 for (i=0; i < laces; i++)
2733 if (ds == demuxer->video && track->realmedia)
2734 handle_realvideo (demuxer, track, block, lace_size[i], block_bref);
2735 else if (ds == demuxer->audio && track->realmedia)
2736 handle_realaudio (demuxer, track, block, lace_size[i], block_bref);
2737 else if (ds == demuxer->video && track->reorder_timecodes)
2738 handle_video_bframes (demuxer, track, block, lace_size[i],
2739 block_bref, block_fref);
2740 else
2742 int modified, size = lace_size[i];
2743 demux_packet_t *dp;
2744 uint8_t *buffer;
2745 modified = demux_mkv_decode (track, block, &buffer, &size, 1);
2746 if (buffer)
2748 dp = new_demux_packet (size);
2749 memcpy (dp->buffer, buffer, size);
2750 if (modified)
2751 free (buffer);
2752 dp->flags = (block_bref == 0 && block_fref == 0) ? 0x10 : 0;
2753 /* If default_duration is 0, assume no pts value is known
2754 * for packets after the first one (rather than all pts
2755 * values being the same) */
2756 if (i == 0 || track->default_duration)
2757 dp->pts = mkv_d->last_pts + i * track->default_duration;
2758 ds_add_packet (ds, dp);
2761 block += lace_size[i];
2764 if (ds == demuxer->video)
2766 mkv_d->v_skip_to_keyframe = 0;
2767 mkv_d->skip_to_timecode = 0;
2769 else if (ds == demuxer->audio)
2770 mkv_d->a_skip_to_keyframe = 0;
2772 free(lace_size);
2773 return 1;
2776 free(lace_size);
2777 return 0;
2780 static int
2781 demux_mkv_fill_buffer (demuxer_t *demuxer, demux_stream_t *ds)
2783 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2784 stream_t *s = demuxer->stream;
2785 uint64_t l;
2786 int il, tmp;
2788 while (1)
2790 while (mkv_d->cluster_size > 0)
2792 uint64_t block_duration = 0, block_length = 0;
2793 int64_t block_bref = 0, block_fref = 0;
2794 uint8_t *block = NULL;
2796 while (mkv_d->blockgroup_size > 0)
2798 switch (ebml_read_id (s, &il))
2800 case MATROSKA_ID_BLOCKDURATION:
2802 block_duration = ebml_read_uint (s, &l);
2803 if (block_duration == EBML_UINT_INVALID) {
2804 free(block);
2805 return 0;
2807 block_duration *= mkv_d->tc_scale / 1000000.0;
2808 break;
2811 case MATROSKA_ID_BLOCK:
2812 block_length = ebml_read_length (s, &tmp);
2813 free(block);
2814 if (block_length > SIZE_MAX - AV_LZO_INPUT_PADDING) return 0;
2815 block = malloc (block_length + AV_LZO_INPUT_PADDING);
2816 demuxer->filepos = stream_tell (s);
2817 if (stream_read (s,block,block_length) != (int) block_length)
2819 free(block);
2820 return 0;
2822 l = tmp + block_length;
2823 break;
2825 case MATROSKA_ID_REFERENCEBLOCK:
2827 int64_t num = ebml_read_int (s, &l);
2828 if (num == EBML_INT_INVALID) {
2829 free(block);
2830 return 0;
2832 if (num <= 0)
2833 block_bref = num;
2834 else
2835 block_fref = num;
2836 break;
2839 case EBML_ID_INVALID:
2840 free(block);
2841 return 0;
2843 default:
2844 ebml_read_skip (s, &l);
2845 break;
2847 mkv_d->blockgroup_size -= l + il;
2848 mkv_d->cluster_size -= l + il;
2851 if (block)
2853 int res = handle_block (demuxer, block, block_length,
2854 block_duration, block_bref, block_fref, 0);
2855 free (block);
2856 if (res < 0)
2857 return 0;
2858 if (res)
2859 return 1;
2862 if (mkv_d->cluster_size > 0)
2864 switch (ebml_read_id (s, &il))
2866 case MATROSKA_ID_CLUSTERTIMECODE:
2868 uint64_t num = ebml_read_uint (s, &l);
2869 if (num == EBML_UINT_INVALID)
2870 return 0;
2871 if (!mkv_d->has_first_tc)
2873 mkv_d->first_tc = num * mkv_d->tc_scale / 1000000.0;
2874 mkv_d->has_first_tc = 1;
2876 mkv_d->cluster_tc = num * mkv_d->tc_scale;
2877 break;
2880 case MATROSKA_ID_BLOCKGROUP:
2881 mkv_d->blockgroup_size = ebml_read_length (s, &tmp);
2882 l = tmp;
2883 break;
2885 case MATROSKA_ID_SIMPLEBLOCK:
2887 int res;
2888 block_length = ebml_read_length (s, &tmp);
2889 block = malloc (block_length);
2890 demuxer->filepos = stream_tell (s);
2891 if (stream_read (s,block,block_length) != (int) block_length)
2893 free(block);
2894 return 0;
2896 l = tmp + block_length;
2897 res = handle_block (demuxer, block, block_length,
2898 block_duration, block_bref, block_fref, 1);
2899 free (block);
2900 mkv_d->cluster_size -= l + il;
2901 if (res < 0)
2902 return 0;
2903 else if (res)
2904 return 1;
2905 else mkv_d->cluster_size += l + il;
2906 break;
2908 case EBML_ID_INVALID:
2909 return 0;
2911 default:
2912 ebml_read_skip (s, &l);
2913 break;
2915 mkv_d->cluster_size -= l + il;
2919 if (ebml_read_id (s, &il) != MATROSKA_ID_CLUSTER)
2920 return 0;
2921 add_cluster_position(mkv_d, stream_tell(s)-il);
2922 mkv_d->cluster_size = ebml_read_length (s, NULL);
2925 return 0;
2928 static void
2929 demux_mkv_seek (demuxer_t *demuxer, float rel_seek_secs, float audio_delay, int flags)
2931 free_cached_dps (demuxer);
2932 if (!(flags & SEEK_FACTOR)) /* time in secs */
2934 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2935 stream_t *s = demuxer->stream;
2936 int64_t target_timecode = 0, diff, min_diff=0xFFFFFFFFFFFFFFFLL;
2937 int i;
2939 if (!(flags & SEEK_ABSOLUTE)) /* relative seek */
2940 target_timecode = (int64_t) (mkv_d->last_pts * 1000.0);
2941 target_timecode += (int64_t)(rel_seek_secs * 1000.0);
2942 if (target_timecode < 0)
2943 target_timecode = 0;
2945 if (mkv_d->indexes == NULL) /* no index was found */
2947 uint64_t target_filepos, cluster_pos, max_pos;
2949 target_filepos = (uint64_t) (target_timecode * mkv_d->last_filepos
2950 / (mkv_d->last_pts * 1000.0));
2952 max_pos = mkv_d->num_cluster_pos ? mkv_d->cluster_positions[mkv_d->num_cluster_pos-1] : 0;
2953 if (target_filepos > max_pos)
2955 if ((off_t) max_pos > stream_tell (s))
2956 stream_seek (s, max_pos);
2957 else
2958 stream_seek (s, stream_tell (s) + mkv_d->cluster_size);
2959 /* parse all the clusters upto target_filepos */
2960 while (!s->eof && stream_tell(s) < (off_t) target_filepos)
2962 switch (ebml_read_id (s, &i))
2964 case MATROSKA_ID_CLUSTER:
2965 add_cluster_position(mkv_d, (uint64_t) stream_tell(s)-i);
2966 break;
2968 case MATROSKA_ID_CUES:
2969 demux_mkv_read_cues (demuxer);
2970 break;
2972 ebml_read_skip (s, NULL);
2974 if (s->eof)
2975 stream_reset(s);
2978 if (mkv_d->indexes == NULL)
2980 cluster_pos = mkv_d->cluster_positions[0];
2981 /* Let's find the nearest cluster */
2982 for (i=0; i < mkv_d->num_cluster_pos; i++)
2984 diff = mkv_d->cluster_positions[i] - target_filepos;
2985 if (rel_seek_secs < 0 && diff < 0 && -diff < min_diff)
2987 cluster_pos = mkv_d->cluster_positions[i];
2988 min_diff = -diff;
2990 else if (rel_seek_secs > 0
2991 && (diff < 0 ? -1 * diff : diff) < min_diff)
2993 cluster_pos = mkv_d->cluster_positions[i];
2994 min_diff = diff < 0 ? -1 * diff : diff;
2997 mkv_d->cluster_size = mkv_d->blockgroup_size = 0;
2998 stream_seek (s, cluster_pos);
3001 else
3003 mkv_index_t *index = NULL;
3004 int seek_id = (demuxer->video->id < 0) ? demuxer->audio->id : demuxer->video->id;
3006 /* let's find the entry in the indexes with the smallest */
3007 /* difference to the wanted timecode. */
3008 for (i=0; i < mkv_d->num_indexes; i++)
3009 if (mkv_d->indexes[i].tnum == seek_id)
3011 diff = target_timecode + mkv_d->first_tc -
3012 (int64_t) mkv_d->indexes[i].timecode * mkv_d->tc_scale / 1000000.0;
3014 if ((flags & SEEK_ABSOLUTE || target_timecode <= mkv_d->last_pts*1000)) {
3015 // Absolute seek or seek backward: find the last index
3016 // position before target time
3017 if (diff < 0 || diff >= min_diff)
3018 continue;
3020 else {
3021 // Relative seek forward: find the first index position
3022 // after target time. If no such index exists, find last
3023 // position between current position and target time.
3024 if (diff <= 0) {
3025 if (min_diff <= 0 && diff <= min_diff)
3026 continue;
3028 else if (diff >= FFMIN(target_timecode - mkv_d->last_pts,
3029 min_diff))
3030 continue;
3032 min_diff = diff;
3033 index = mkv_d->indexes + i;
3036 if (index) /* We've found an entry. */
3038 mkv_d->cluster_size = mkv_d->blockgroup_size = 0;
3039 stream_seek (s, index->filepos);
3043 if (demuxer->video->id >= 0)
3044 mkv_d->v_skip_to_keyframe = 1;
3045 if (rel_seek_secs > 0.0)
3046 mkv_d->skip_to_timecode = target_timecode;
3047 mkv_d->a_skip_to_keyframe = 1;
3049 demux_mkv_fill_buffer(demuxer, NULL);
3051 else if ((demuxer->movi_end <= 0) || !(flags & SEEK_ABSOLUTE))
3052 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] seek unsupported flags\n");
3053 else
3055 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
3056 stream_t *s = demuxer->stream;
3057 uint64_t target_filepos;
3058 mkv_index_t *index = NULL;
3059 int i;
3061 if (mkv_d->indexes == NULL) /* no index was found */
3062 { /* I'm lazy... */
3063 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] seek unsupported flags\n");
3064 return;
3067 target_filepos = (uint64_t)(demuxer->movi_end * rel_seek_secs);
3068 for (i=0; i < mkv_d->num_indexes; i++)
3069 if (mkv_d->indexes[i].tnum == demuxer->video->id)
3070 if ((index == NULL) ||
3071 ((mkv_d->indexes[i].filepos >= target_filepos) &&
3072 ((index->filepos < target_filepos) ||
3073 (mkv_d->indexes[i].filepos < index->filepos))))
3074 index = &mkv_d->indexes[i];
3076 if (!index)
3077 return;
3079 mkv_d->cluster_size = mkv_d->blockgroup_size = 0;
3080 stream_seek (s, index->filepos);
3082 if (demuxer->video->id >= 0)
3083 mkv_d->v_skip_to_keyframe = 1;
3084 mkv_d->skip_to_timecode = index->timecode;
3085 mkv_d->a_skip_to_keyframe = 1;
3087 demux_mkv_fill_buffer(demuxer, NULL);
3091 static int
3092 demux_mkv_control (demuxer_t *demuxer, int cmd, void *arg)
3094 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
3096 switch (cmd)
3098 case DEMUXER_CTRL_CORRECT_PTS:
3099 return DEMUXER_CTRL_OK;
3100 case DEMUXER_CTRL_GET_TIME_LENGTH:
3101 if (mkv_d->duration == 0)
3102 return DEMUXER_CTRL_DONTKNOW;
3104 *((double *)arg) = (double)mkv_d->duration;
3105 return DEMUXER_CTRL_OK;
3107 case DEMUXER_CTRL_GET_PERCENT_POS:
3108 if (mkv_d->duration == 0)
3110 return DEMUXER_CTRL_DONTKNOW;
3113 *((int *) arg) = (int) (100 * mkv_d->last_pts / mkv_d->duration);
3114 return DEMUXER_CTRL_OK;
3116 case DEMUXER_CTRL_SWITCH_AUDIO:
3117 if (demuxer->audio && demuxer->audio->sh) {
3118 sh_audio_t *sh = demuxer->a_streams[demuxer->audio->id];
3119 int aid = *(int*)arg;
3120 if (aid < 0)
3121 aid = (sh->aid + 1) % mkv_d->last_aid;
3122 if (aid != sh->aid) {
3123 mkv_track_t *track = demux_mkv_find_track_by_num (mkv_d, aid, MATROSKA_TRACK_AUDIO);
3124 if (track) {
3125 demuxer->audio->id = track->tnum;
3126 sh = demuxer->a_streams[demuxer->audio->id];
3127 ds_free_packs(demuxer->audio);
3130 *(int*)arg = sh->aid;
3131 } else
3132 *(int*)arg = -2;
3133 return DEMUXER_CTRL_OK;
3135 default:
3136 return DEMUXER_CTRL_NOTIMPL;
3140 const demuxer_desc_t demuxer_desc_matroska = {
3141 "Matroska demuxer",
3142 "mkv",
3143 "Matroska",
3144 "Aurelien Jacobs",
3146 DEMUXER_TYPE_MATROSKA,
3147 1, // safe autodetect
3148 demux_mkv_open,
3149 demux_mkv_fill_buffer,
3150 NULL,
3151 demux_close_mkv,
3152 demux_mkv_seek,
3153 demux_mkv_control