Remove the grayscale and 4:2:2 RTjpeg code, it is neither used nor is there
[mplayer/glamo.git] / libmpdemux / demux_mkv.c
blob6d4429377c86eb25e90b07e7addba3b9aee184eb
1 /*
2 * native Matroska demuxer
3 * Written by 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.
6 * Licence: GPL
7 */
9 #include "config.h"
11 #include <stdlib.h>
12 #include <stdio.h>
13 #include <ctype.h>
14 #include <inttypes.h>
16 #include "stream/stream.h"
17 #include "demuxer.h"
18 #include "stheader.h"
19 #include "ebml.h"
20 #include "matroska.h"
22 #include "mp_msg.h"
23 #include "help_mp.h"
25 #include "vobsub.h"
26 #include "subreader.h"
27 #include "libvo/sub.h"
29 #include "libass/ass.h"
30 #include "libass/ass_mp.h"
32 #include "libavutil/common.h"
34 #ifdef CONFIG_QTX_CODECS
35 #include "loader/qtx/qtxsdk/components.h"
36 #endif
38 #if CONFIG_ZLIB
39 #include <zlib.h>
40 #endif
42 #include "libavutil/lzo.h"
43 #include "libavutil/intreadwrite.h"
44 #include "libavutil/avstring.h"
46 static const unsigned char sipr_swaps[38][2]={
47 {0,63},{1,22},{2,44},{3,90},{5,81},{7,31},{8,86},{9,58},{10,36},{12,68},
48 {13,39},{14,73},{15,53},{16,69},{17,57},{19,88},{20,34},{21,71},{24,46},
49 {25,94},{26,54},{28,75},{29,50},{32,70},{33,92},{35,74},{38,85},{40,56},
50 {42,87},{43,65},{45,59},{48,79},{49,93},{51,89},{55,95},{61,76},{67,83},
51 {77,80} };
53 // Map flavour to bytes per second
54 #define SIPR_FLAVORS 4
55 #define ATRC_FLAVORS 8
56 #define COOK_FLAVORS 34
57 static const int sipr_fl2bps[SIPR_FLAVORS] = {813, 1062, 625, 2000};
58 static const int atrc_fl2bps[ATRC_FLAVORS] =
59 {8269, 11714, 13092, 16538, 18260, 22050, 33075, 44100};
60 static const int cook_fl2bps[COOK_FLAVORS] =
61 { 1000, 1378, 2024, 2584, 4005, 5513, 8010, 4005, 750, 2498,
62 4048, 5513, 8010, 11973, 8010, 2584, 4005, 2067, 2584, 2584,
63 4005, 4005, 5513, 5513, 8010, 12059, 1550, 8010, 12059, 5513,
64 12016, 16408, 22911, 33506};
66 typedef struct
68 uint32_t order, type, scope;
69 uint32_t comp_algo;
70 uint8_t *comp_settings;
71 int comp_settings_len;
72 } mkv_content_encoding_t;
74 typedef struct mkv_track
76 int tnum;
77 char *name;
79 char *codec_id;
80 int ms_compat;
81 char *language;
83 int type;
85 uint32_t v_width, v_height, v_dwidth, v_dheight;
86 float v_frate;
88 uint32_t a_formattag;
89 uint32_t a_channels, a_bps;
90 float a_sfreq;
92 float default_duration;
94 int default_track;
96 void *private_data;
97 unsigned int private_size;
99 /* stuff for realmedia */
100 int realmedia;
101 int64_t rv_kf_base;
102 int rv_kf_pts;
103 float rv_pts; /* previous video timestamp */
104 float ra_pts; /* previous audio timestamp */
106 /** realaudio descrambling */
107 int sub_packet_size; ///< sub packet size, per stream
108 int sub_packet_h; ///< number of coded frames per block
109 int coded_framesize; ///< coded frame size, per stream
110 int audiopk_size; ///< audio packet size
111 unsigned char *audio_buf; ///< place to store reordered audio data
112 float *audio_timestamp; ///< timestamp for each audio packet
113 int sub_packet_cnt; ///< number of subpacket already received
114 int audio_filepos; ///< file position of first audio packet in block
116 /* stuff for quicktime */
117 int fix_i_bps;
118 float qt_last_a_pts;
120 int subtitle_type;
122 /* The timecodes of video frames might have to be reordered if they're
123 in display order (the timecodes, not the frames themselves!). In this
124 case demux packets have to be cached with the help of these variables. */
125 int reorder_timecodes;
126 demux_packet_t **cached_dps;
127 int num_cached_dps, num_allocated_dps;
128 float max_pts;
130 /* generic content encoding support */
131 mkv_content_encoding_t *encodings;
132 int num_encodings;
134 /* For VobSubs and SSA/ASS */
135 sh_sub_t *sh_sub;
136 } mkv_track_t;
138 typedef struct mkv_index
140 int tnum;
141 uint64_t timecode, filepos;
142 } mkv_index_t;
144 typedef struct mkv_demuxer
146 off_t segment_start;
148 float duration, last_pts;
149 uint64_t last_filepos;
151 mkv_track_t **tracks;
152 int num_tracks;
154 uint64_t tc_scale, cluster_tc, first_tc;
155 int has_first_tc;
157 uint64_t cluster_size;
158 uint64_t blockgroup_size;
160 mkv_index_t *indexes;
161 int num_indexes;
163 off_t *parsed_cues;
164 int parsed_cues_num;
165 off_t *parsed_seekhead;
166 int parsed_seekhead_num;
168 uint64_t *cluster_positions;
169 int num_cluster_pos;
171 int64_t skip_to_timecode;
172 int v_skip_to_keyframe, a_skip_to_keyframe;
174 int64_t stop_timecode;
176 int last_aid;
177 int audio_tracks[MAX_A_STREAMS];
178 } mkv_demuxer_t;
180 #define REALHEADER_SIZE 16
181 #define RVPROPERTIES_SIZE 34
182 #define RAPROPERTIES4_SIZE 56
183 #define RAPROPERTIES5_SIZE 70
185 /* for e.g. "-slang ger" */
186 extern char *dvdsub_lang;
187 extern char *audio_lang;
188 extern int dvdsub_id;
191 * \brief ensures there is space for at least one additional element
192 * \param array array to grow
193 * \param nelem current number of elements in array
194 * \param elsize size of one array element
196 static void grow_array(void **array, int nelem, size_t elsize) {
197 if (!(nelem & 31))
198 *array = realloc(*array, (nelem + 32) * elsize);
201 static mkv_track_t *
202 demux_mkv_find_track_by_num (mkv_demuxer_t *d, int n, int type)
204 int i, id;
206 for (i=0, id=0; i < d->num_tracks; i++)
207 if (d->tracks[i] != NULL && d->tracks[i]->type == type)
208 if (id++ == n)
209 return d->tracks[i];
211 return NULL;
214 static void
215 add_cluster_position (mkv_demuxer_t *mkv_d, uint64_t position)
217 int i = mkv_d->num_cluster_pos;
219 while (i--)
220 if (mkv_d->cluster_positions[i] == position)
221 return;
223 grow_array(&mkv_d->cluster_positions, mkv_d->num_cluster_pos,
224 sizeof(uint64_t));
225 mkv_d->cluster_positions[mkv_d->num_cluster_pos++] = position;
229 #define AAC_SYNC_EXTENSION_TYPE 0x02b7
230 static int
231 aac_get_sample_rate_index (uint32_t sample_rate)
233 if (92017 <= sample_rate)
234 return 0;
235 else if (75132 <= sample_rate)
236 return 1;
237 else if (55426 <= sample_rate)
238 return 2;
239 else if (46009 <= sample_rate)
240 return 3;
241 else if (37566 <= sample_rate)
242 return 4;
243 else if (27713 <= sample_rate)
244 return 5;
245 else if (23004 <= sample_rate)
246 return 6;
247 else if (18783 <= sample_rate)
248 return 7;
249 else if (13856 <= sample_rate)
250 return 8;
251 else if (11502 <= sample_rate)
252 return 9;
253 else if (9391 <= sample_rate)
254 return 10;
255 else
256 return 11;
259 /** \brief Free cached demux packets
261 * Reordering the timecodes requires caching of demux packets. This function
262 * frees all these cached packets and the memory for the cached pointers
263 * itself.
265 * \param demuxer The demuxer for which the cache is to be freed.
267 static void
268 free_cached_dps (demuxer_t *demuxer)
270 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
271 mkv_track_t *track;
272 int i, k;
274 for (k = 0; k < mkv_d->num_tracks; k++)
276 track = mkv_d->tracks[k];
277 for (i = 0; i < track->num_cached_dps; i++)
278 free_demux_packet (track->cached_dps[i]);
279 free(track->cached_dps);
280 track->cached_dps = NULL;
281 track->num_cached_dps = 0;
282 track->num_allocated_dps = 0;
283 track->max_pts = 0;
287 static int
288 demux_mkv_decode (mkv_track_t *track, uint8_t *src, uint8_t **dest,
289 uint32_t *size, uint32_t type)
291 int i, result;
292 int modified = 0;
294 *dest = src;
295 if (track->num_encodings <= 0)
296 return 0;
298 for (i=0; i<track->num_encodings; i++)
300 if (!(track->encodings[i].scope & type))
301 continue;
303 #if CONFIG_ZLIB
304 if (track->encodings[i].comp_algo == 0)
306 /* zlib encoded track */
307 z_stream zstream;
309 zstream.zalloc = (alloc_func) 0;
310 zstream.zfree = (free_func) 0;
311 zstream.opaque = (voidpf) 0;
312 if (inflateInit (&zstream) != Z_OK)
314 mp_msg (MSGT_DEMUX, MSGL_WARN,
315 MSGTR_MPDEMUX_MKV_ZlibInitializationFailed);
316 return modified;
318 zstream.next_in = (Bytef *) src;
319 zstream.avail_in = *size;
321 modified = 1;
322 *dest = NULL;
323 zstream.avail_out = *size;
324 do {
325 *size += 4000;
326 *dest = realloc (*dest, *size);
327 zstream.next_out = (Bytef *) (*dest + zstream.total_out);
328 result = inflate (&zstream, Z_NO_FLUSH);
329 if (result != Z_OK && result != Z_STREAM_END)
331 mp_msg (MSGT_DEMUX, MSGL_WARN,
332 MSGTR_MPDEMUX_MKV_ZlibDecompressionFailed);
333 free(*dest);
334 *dest = NULL;
335 inflateEnd (&zstream);
336 return modified;
338 zstream.avail_out += 4000;
339 } while (zstream.avail_out == 4000 &&
340 zstream.avail_in != 0 && result != Z_STREAM_END);
342 *size = zstream.total_out;
343 inflateEnd (&zstream);
345 #endif
346 if (track->encodings[i].comp_algo == 2)
348 /* lzo encoded track */
349 int dstlen = *size * 3;
351 *dest = NULL;
352 while (1)
354 int srclen = *size;
355 if (dstlen > SIZE_MAX - AV_LZO_OUTPUT_PADDING) goto lzo_fail;
356 *dest = realloc (*dest, dstlen + AV_LZO_OUTPUT_PADDING);
357 result = av_lzo1x_decode (*dest, &dstlen, src, &srclen);
358 if (result == 0)
359 break;
360 if (!(result & AV_LZO_OUTPUT_FULL))
362 lzo_fail:
363 mp_msg (MSGT_DEMUX, MSGL_WARN,
364 MSGTR_MPDEMUX_MKV_LzoDecompressionFailed);
365 free(*dest);
366 *dest = NULL;
367 return modified;
369 mp_msg (MSGT_DEMUX, MSGL_DBG2,
370 "[mkv] lzo decompression buffer too small.\n");
371 dstlen *= 2;
373 *size = dstlen;
377 return modified;
381 static int
382 demux_mkv_read_info (demuxer_t *demuxer)
384 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
385 stream_t *s = demuxer->stream;
386 uint64_t length, l;
387 int il;
388 uint64_t tc_scale = 1000000;
389 long double duration = 0.;
391 length = ebml_read_length (s, NULL);
392 while (length > 0)
394 switch (ebml_read_id (s, &il))
396 case MATROSKA_ID_TIMECODESCALE:
398 uint64_t num = ebml_read_uint (s, &l);
399 if (num == EBML_UINT_INVALID)
400 return 1;
401 tc_scale = num;
402 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + timecode scale: %"PRIu64"\n",
403 tc_scale);
404 break;
407 case MATROSKA_ID_DURATION:
409 long double num = ebml_read_float (s, &l);
410 if (num == EBML_FLOAT_INVALID)
411 return 1;
412 duration = num;
413 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + duration: %.3Lfs\n",
414 duration * tc_scale / 1000000000.0);
415 break;
418 default:
419 ebml_read_skip (s, &l);
420 break;
422 length -= l + il;
424 mkv_d->tc_scale = tc_scale;
425 mkv_d->duration = duration * tc_scale / 1000000000.0;
426 return 0;
430 * \brief free array of kv_content_encoding_t
431 * \param encodings pointer to array
432 * \param numencodings number of encodings in array
434 static void
435 demux_mkv_free_encodings(mkv_content_encoding_t *encodings, int numencodings)
437 while (numencodings-- > 0)
438 free(encodings[numencodings].comp_settings);
439 free(encodings);
442 static int
443 demux_mkv_read_trackencodings (demuxer_t *demuxer, mkv_track_t *track)
445 stream_t *s = demuxer->stream;
446 mkv_content_encoding_t *ce, e;
447 uint64_t len, length, l;
448 int il, n;
450 ce = malloc (sizeof (*ce));
451 n = 0;
453 len = length = ebml_read_length (s, &il);
454 len += il;
455 while (length > 0)
457 switch (ebml_read_id (s, &il))
459 case MATROSKA_ID_CONTENTENCODING:
461 uint64_t len;
462 int i;
464 memset (&e, 0, sizeof (e));
465 e.scope = 1;
467 len = ebml_read_length (s, &i);
468 l = len + i;
470 while (len > 0)
472 uint64_t num, l;
473 int il;
475 switch (ebml_read_id (s, &il))
477 case MATROSKA_ID_CONTENTENCODINGORDER:
478 num = ebml_read_uint (s, &l);
479 if (num == EBML_UINT_INVALID)
480 goto err_out;
481 e.order = num;
482 break;
484 case MATROSKA_ID_CONTENTENCODINGSCOPE:
485 num = ebml_read_uint (s, &l);
486 if (num == EBML_UINT_INVALID)
487 goto err_out;
488 e.scope = num;
489 break;
491 case MATROSKA_ID_CONTENTENCODINGTYPE:
492 num = ebml_read_uint (s, &l);
493 if (num == EBML_UINT_INVALID)
494 goto err_out;
495 e.type = num;
496 break;
498 case MATROSKA_ID_CONTENTCOMPRESSION:
500 uint64_t le;
502 le = ebml_read_length (s, &i);
503 l = le + i;
505 while (le > 0)
507 uint64_t l;
508 int il;
510 switch (ebml_read_id (s, &il))
512 case MATROSKA_ID_CONTENTCOMPALGO:
513 num = ebml_read_uint (s, &l);
514 if (num == EBML_UINT_INVALID)
515 goto err_out;
516 e.comp_algo = num;
517 break;
519 case MATROSKA_ID_CONTENTCOMPSETTINGS:
520 l = ebml_read_length (s, &i);
521 e.comp_settings = malloc (l);
522 stream_read (s, e.comp_settings, l);
523 e.comp_settings_len = l;
524 l += i;
525 break;
527 default:
528 ebml_read_skip (s, &l);
529 break;
531 le -= l + il;
534 if (e.type == 1)
536 mp_msg(MSGT_DEMUX, MSGL_WARN,
537 MSGTR_MPDEMUX_MKV_TrackEncrypted, track->tnum);
539 else if (e.type != 0)
541 mp_msg(MSGT_DEMUX, MSGL_WARN,
542 MSGTR_MPDEMUX_MKV_UnknownContentEncoding, track->tnum);
545 if (e.comp_algo != 0 && e.comp_algo != 2)
547 mp_msg (MSGT_DEMUX, MSGL_WARN,
548 MSGTR_MPDEMUX_MKV_UnknownCompression,
549 track->tnum, e.comp_algo);
551 #if !CONFIG_ZLIB
552 else if (e.comp_algo == 0)
554 mp_msg (MSGT_DEMUX, MSGL_WARN,
555 MSGTR_MPDEMUX_MKV_ZlibCompressionUnsupported,
556 track->tnum);
558 #endif
560 break;
563 default:
564 ebml_read_skip (s, &l);
565 break;
567 len -= l + il;
569 for (i=0; i<n; i++)
570 if (e.order <= ce[i].order)
571 break;
572 ce = realloc (ce, (n+1) *sizeof (*ce));
573 memmove (ce+i+1, ce+i, (n-i) * sizeof (*ce));
574 memcpy (ce+i, &e, sizeof (e));
575 n++;
576 break;
579 default:
580 ebml_read_skip (s, &l);
581 break;
584 length -= l + il;
587 track->encodings = ce;
588 track->num_encodings = n;
589 return len;
591 err_out:
592 demux_mkv_free_encodings(ce, n);
593 return 0;
596 static int
597 demux_mkv_read_trackaudio (demuxer_t *demuxer, mkv_track_t *track)
599 stream_t *s = demuxer->stream;
600 uint64_t len, length, l;
601 int il;
603 track->a_sfreq = 8000.0;
604 track->a_channels = 1;
606 len = length = ebml_read_length (s, &il);
607 len += il;
608 while (length > 0)
610 switch (ebml_read_id (s, &il))
612 case MATROSKA_ID_AUDIOSAMPLINGFREQ:
614 long double num = ebml_read_float (s, &l);
615 if (num == EBML_FLOAT_INVALID)
616 return 0;
617 track->a_sfreq = num;
618 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Sampling frequency: %f\n",
619 track->a_sfreq);
620 break;
623 case MATROSKA_ID_AUDIOBITDEPTH:
625 uint64_t num = ebml_read_uint (s, &l);
626 if (num == EBML_UINT_INVALID)
627 return 0;
628 track->a_bps = num;
629 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Bit depth: %u\n",
630 track->a_bps);
631 break;
634 case MATROSKA_ID_AUDIOCHANNELS:
636 uint64_t num = ebml_read_uint (s, &l);
637 if (num == EBML_UINT_INVALID)
638 return 0;
639 track->a_channels = num;
640 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Channels: %u\n",
641 track->a_channels);
642 break;
645 default:
646 ebml_read_skip (s, &l);
647 break;
649 length -= l + il;
651 return len;
654 static int
655 demux_mkv_read_trackvideo (demuxer_t *demuxer, mkv_track_t *track)
657 stream_t *s = demuxer->stream;
658 uint64_t len, length, l;
659 int il;
661 len = length = ebml_read_length (s, &il);
662 len += il;
663 while (length > 0)
665 switch (ebml_read_id (s, &il))
667 case MATROSKA_ID_VIDEOFRAMERATE:
669 long double num = ebml_read_float (s, &l);
670 if (num == EBML_FLOAT_INVALID)
671 return 0;
672 track->v_frate = num;
673 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Frame rate: %f\n",
674 track->v_frate);
675 if (track->v_frate > 0)
676 track->default_duration = 1 / track->v_frate;
677 break;
680 case MATROSKA_ID_VIDEODISPLAYWIDTH:
682 uint64_t num = ebml_read_uint (s, &l);
683 if (num == EBML_UINT_INVALID)
684 return 0;
685 track->v_dwidth = num;
686 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Display width: %u\n",
687 track->v_dwidth);
688 break;
691 case MATROSKA_ID_VIDEODISPLAYHEIGHT:
693 uint64_t num = ebml_read_uint (s, &l);
694 if (num == EBML_UINT_INVALID)
695 return 0;
696 track->v_dheight = num;
697 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Display height: %u\n",
698 track->v_dheight);
699 break;
702 case MATROSKA_ID_VIDEOPIXELWIDTH:
704 uint64_t num = ebml_read_uint (s, &l);
705 if (num == EBML_UINT_INVALID)
706 return 0;
707 track->v_width = num;
708 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Pixel width: %u\n",
709 track->v_width);
710 break;
713 case MATROSKA_ID_VIDEOPIXELHEIGHT:
715 uint64_t num = ebml_read_uint (s, &l);
716 if (num == EBML_UINT_INVALID)
717 return 0;
718 track->v_height = num;
719 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Pixel height: %u\n",
720 track->v_height);
721 break;
724 default:
725 ebml_read_skip (s, &l);
726 break;
728 length -= l + il;
730 return len;
734 * \brief free any data associated with given track
735 * \param track track of which to free data
737 static void
738 demux_mkv_free_trackentry(mkv_track_t *track) {
739 free (track->name);
740 free (track->codec_id);
741 free (track->language);
742 free (track->private_data);
743 free (track->audio_buf);
744 free (track->audio_timestamp);
745 demux_mkv_free_encodings(track->encodings, track->num_encodings);
746 free(track);
749 static int
750 demux_mkv_read_trackentry (demuxer_t *demuxer)
752 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
753 stream_t *s = demuxer->stream;
754 mkv_track_t *track;
755 uint64_t len, length, l;
756 int il;
758 track = calloc (1, sizeof (*track));
759 /* set default values */
760 track->default_track = 1;
761 track->name = 0;
762 track->language = strdup("eng");
764 len = length = ebml_read_length (s, &il);
765 len += il;
766 while (length > 0)
768 switch (ebml_read_id (s, &il))
770 case MATROSKA_ID_TRACKNUMBER:
772 uint64_t num = ebml_read_uint (s, &l);
773 if (num == EBML_UINT_INVALID)
774 goto err_out;
775 track->tnum = num;
776 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Track number: %u\n",
777 track->tnum);
778 break;
781 case MATROSKA_ID_TRACKNAME:
783 track->name = ebml_read_utf8 (s, &l);
784 if (track->name == NULL)
785 goto err_out;
786 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Name: %s\n",
787 track->name);
788 break;
791 case MATROSKA_ID_TRACKTYPE:
793 uint64_t num = ebml_read_uint (s, &l);
794 if (num == EBML_UINT_INVALID)
795 return 0;
796 track->type = num;
797 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Track type: ");
798 switch (track->type)
800 case MATROSKA_TRACK_AUDIO:
801 mp_msg (MSGT_DEMUX, MSGL_V, "Audio\n");
802 break;
803 case MATROSKA_TRACK_VIDEO:
804 mp_msg (MSGT_DEMUX, MSGL_V, "Video\n");
805 break;
806 case MATROSKA_TRACK_SUBTITLE:
807 mp_msg (MSGT_DEMUX, MSGL_V, "Subtitle\n");
808 break;
809 default:
810 mp_msg (MSGT_DEMUX, MSGL_V, "unknown\n");
811 break;
813 break;
816 case MATROSKA_ID_TRACKAUDIO:
817 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Audio track\n");
818 l = demux_mkv_read_trackaudio (demuxer, track);
819 if (l == 0)
820 goto err_out;
821 break;
823 case MATROSKA_ID_TRACKVIDEO:
824 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Video track\n");
825 l = demux_mkv_read_trackvideo (demuxer, track);
826 if (l == 0)
827 goto err_out;
828 break;
830 case MATROSKA_ID_CODECID:
831 track->codec_id = ebml_read_ascii (s, &l);
832 if (track->codec_id == NULL)
833 goto err_out;
834 if (!strcmp (track->codec_id, MKV_V_MSCOMP) ||
835 !strcmp (track->codec_id, MKV_A_ACM))
836 track->ms_compat = 1;
837 else if (!strcmp (track->codec_id, MKV_S_VOBSUB))
838 track->subtitle_type = MATROSKA_SUBTYPE_VOBSUB;
839 else if (!strcmp (track->codec_id, MKV_S_TEXTSSA)
840 || !strcmp (track->codec_id, MKV_S_TEXTASS)
841 || !strcmp (track->codec_id, MKV_S_SSA)
842 || !strcmp (track->codec_id, MKV_S_ASS))
844 track->subtitle_type = MATROSKA_SUBTYPE_SSA;
846 else if (!strcmp (track->codec_id, MKV_S_TEXTASCII))
847 track->subtitle_type = MATROSKA_SUBTYPE_TEXT;
848 if (!strcmp (track->codec_id, MKV_S_TEXTUTF8))
850 track->subtitle_type = MATROSKA_SUBTYPE_TEXT;
852 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Codec ID: %s\n",
853 track->codec_id);
854 break;
856 case MATROSKA_ID_CODECPRIVATE:
858 int x;
859 uint64_t num = ebml_read_length (s, &x);
860 // audit: cheap guard against overflows later..
861 if (num > SIZE_MAX - 1000) return 0;
862 l = x + num;
863 track->private_data = malloc (num + AV_LZO_INPUT_PADDING);
864 if (stream_read(s, track->private_data, num) != (int) num)
865 goto err_out;
866 track->private_size = num;
867 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + CodecPrivate, length "
868 "%u\n", track->private_size);
869 break;
872 case MATROSKA_ID_TRACKLANGUAGE:
873 free(track->language);
874 track->language = ebml_read_utf8 (s, &l);
875 if (track->language == NULL)
876 goto err_out;
877 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Language: %s\n",
878 track->language);
879 break;
881 case MATROSKA_ID_TRACKFLAGDEFAULT:
883 uint64_t num = ebml_read_uint (s, &l);
884 if (num == EBML_UINT_INVALID)
885 goto err_out;
886 track->default_track = num;
887 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Default flag: %u\n",
888 track->default_track);
889 break;
892 case MATROSKA_ID_TRACKDEFAULTDURATION:
894 uint64_t num = ebml_read_uint (s, &l);
895 if (num == EBML_UINT_INVALID)
896 goto err_out;
897 if (num == 0)
898 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Default duration: 0");
899 else
901 track->v_frate = 1000000000.0 / num;
902 track->default_duration = num / 1000000000.0;
903 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Default duration: "
904 "%.3fms ( = %.3f fps)\n",num/1000000.0,track->v_frate);
906 break;
909 case MATROSKA_ID_TRACKENCODINGS:
910 l = demux_mkv_read_trackencodings (demuxer, track);
911 if (l == 0)
912 goto err_out;
913 break;
915 default:
916 ebml_read_skip (s, &l);
917 break;
919 length -= l + il;
922 mkv_d->tracks[mkv_d->num_tracks++] = track;
923 return len;
925 err_out:
926 demux_mkv_free_trackentry(track);
927 return 0;
930 static int
931 demux_mkv_read_tracks (demuxer_t *demuxer)
933 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
934 stream_t *s = demuxer->stream;
935 uint64_t length, l;
936 int il;
938 mkv_d->tracks = malloc (sizeof (*mkv_d->tracks));
939 mkv_d->num_tracks = 0;
941 length = ebml_read_length (s, NULL);
942 while (length > 0)
944 switch (ebml_read_id (s, &il))
946 case MATROSKA_ID_TRACKENTRY:
947 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + a track...\n");
948 mkv_d->tracks = realloc (mkv_d->tracks,
949 (mkv_d->num_tracks+1)
950 *sizeof (*mkv_d->tracks));
951 l = demux_mkv_read_trackentry (demuxer);
952 if (l == 0)
953 return 1;
954 break;
956 default:
957 ebml_read_skip (s, &l);
958 break;
960 length -= l + il;
962 return 0;
965 static int
966 demux_mkv_read_cues (demuxer_t *demuxer)
968 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
969 stream_t *s = demuxer->stream;
970 uint64_t length, l, time, track, pos;
971 off_t off;
972 int i, il;
974 if (index_mode == 0) {
975 ebml_read_skip (s, NULL);
976 return 0;
978 off = stream_tell (s);
979 for (i=0; i<mkv_d->parsed_cues_num; i++)
980 if (mkv_d->parsed_cues[i] == off)
982 ebml_read_skip (s, NULL);
983 return 0;
985 mkv_d->parsed_cues = realloc (mkv_d->parsed_cues,
986 (mkv_d->parsed_cues_num+1)
987 * sizeof (off_t));
988 mkv_d->parsed_cues[mkv_d->parsed_cues_num++] = off;
990 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] /---- [ parsing cues ] -----------\n");
991 length = ebml_read_length (s, NULL);
993 while (length > 0)
995 time = track = pos = EBML_UINT_INVALID;
997 switch (ebml_read_id (s, &il))
999 case MATROSKA_ID_POINTENTRY:
1001 uint64_t len;
1003 len = ebml_read_length (s, &i);
1004 l = len + i;
1006 while (len > 0)
1008 uint64_t l;
1009 int il;
1011 switch (ebml_read_id (s, &il))
1013 case MATROSKA_ID_CUETIME:
1014 time = ebml_read_uint (s, &l);
1015 break;
1017 case MATROSKA_ID_CUETRACKPOSITION:
1019 uint64_t le;
1021 le = ebml_read_length (s, &i);
1022 l = le + i;
1024 while (le > 0)
1026 uint64_t l;
1027 int il;
1029 switch (ebml_read_id (s, &il))
1031 case MATROSKA_ID_CUETRACK:
1032 track = ebml_read_uint (s, &l);
1033 break;
1035 case MATROSKA_ID_CUECLUSTERPOSITION:
1036 pos = ebml_read_uint (s, &l);
1037 break;
1039 default:
1040 ebml_read_skip (s, &l);
1041 break;
1043 le -= l + il;
1045 break;
1048 default:
1049 ebml_read_skip (s, &l);
1050 break;
1052 len -= l + il;
1054 break;
1057 default:
1058 ebml_read_skip (s, &l);
1059 break;
1062 length -= l + il;
1064 if (time != EBML_UINT_INVALID && track != EBML_UINT_INVALID
1065 && pos != EBML_UINT_INVALID)
1067 grow_array(&mkv_d->indexes, mkv_d->num_indexes, sizeof(mkv_index_t));
1068 mkv_d->indexes[mkv_d->num_indexes].tnum = track;
1069 mkv_d->indexes[mkv_d->num_indexes].timecode = time;
1070 mkv_d->indexes[mkv_d->num_indexes].filepos =mkv_d->segment_start+pos;
1071 mp_msg (MSGT_DEMUX, MSGL_DBG2, "[mkv] |+ found cue point "
1072 "for track %"PRIu64": timecode %"PRIu64", filepos: %"PRIu64"\n",
1073 track, time, mkv_d->segment_start + pos);
1074 mkv_d->num_indexes++;
1078 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] \\---- [ parsing cues ] -----------\n");
1079 return 0;
1082 static int
1083 demux_mkv_read_chapters (demuxer_t *demuxer)
1085 stream_t *s = demuxer->stream;
1086 uint64_t length, l;
1087 int il;
1089 if (demuxer->chapters)
1091 ebml_read_skip (s, NULL);
1092 return 0;
1095 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] /---- [ parsing chapters ] ---------\n");
1096 length = ebml_read_length (s, NULL);
1098 while (length > 0)
1100 switch (ebml_read_id (s, &il))
1102 case MATROSKA_ID_EDITIONENTRY:
1104 uint64_t len;
1105 int i;
1107 len = ebml_read_length (s, &i);
1108 l = len + i;
1110 while (len > 0)
1112 uint64_t l;
1113 int il;
1115 switch (ebml_read_id (s, &il))
1117 case MATROSKA_ID_CHAPTERATOM:
1119 uint64_t len, start=0, end=0;
1120 char* name = 0;
1121 int i;
1122 int cid;
1124 len = ebml_read_length (s, &i);
1125 l = len + i;
1127 while (len > 0)
1129 uint64_t l;
1130 int il;
1132 switch (ebml_read_id (s, &il))
1134 case MATROSKA_ID_CHAPTERTIMESTART:
1135 start = ebml_read_uint (s, &l) / 1000000;
1136 break;
1138 case MATROSKA_ID_CHAPTERTIMEEND:
1139 end = ebml_read_uint (s, &l) / 1000000;
1140 break;
1142 case MATROSKA_ID_CHAPTERDISPLAY:
1144 uint64_t len;
1145 int i;
1147 len = ebml_read_length (s, &i);
1148 l = len + i;
1149 while (len > 0)
1151 uint64_t l;
1152 int il;
1154 switch (ebml_read_id (s, &il))
1156 case MATROSKA_ID_CHAPSTRING:
1157 name = ebml_read_utf8 (s, &l);
1158 break;
1159 default:
1160 ebml_read_skip (s, &l);
1161 break;
1163 len -= l + il;
1166 break;
1168 default:
1169 ebml_read_skip (s, &l);
1170 break;
1172 len -= l + il;
1175 if (!name)
1176 name = strdup("(unnamed)");
1178 cid = demuxer_add_chapter(demuxer, name, start, end);
1180 mp_msg(MSGT_DEMUX, MSGL_V,
1181 "[mkv] Chapter %u from %02d:%02d:%02d."
1182 "%03d to %02d:%02d:%02d.%03d, %s\n",
1183 cid,
1184 (int) (start / 60 / 60 / 1000),
1185 (int) ((start / 60 / 1000) % 60),
1186 (int) ((start / 1000) % 60),
1187 (int) (start % 1000),
1188 (int) (end / 60 / 60 / 1000),
1189 (int) ((end / 60 / 1000) % 60),
1190 (int) ((end / 1000) % 60),
1191 (int) (end % 1000), name);
1193 free(name);
1194 break;
1197 default:
1198 ebml_read_skip (s, &l);
1199 break;
1201 len -= l + il;
1203 break;
1206 default:
1207 ebml_read_skip (s, &l);
1208 break;
1211 length -= l + il;
1214 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] \\---- [ parsing chapters ] ---------\n");
1215 return 0;
1218 static int
1219 demux_mkv_read_tags (demuxer_t *demuxer)
1221 ebml_read_skip (demuxer->stream, NULL);
1222 return 0;
1225 static int
1226 demux_mkv_read_attachments (demuxer_t *demuxer)
1228 stream_t *s = demuxer->stream;
1229 uint64_t length, l;
1230 int il;
1232 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] /---- [ parsing attachments ] ---------\n");
1233 length = ebml_read_length (s, NULL);
1235 while (length > 0)
1237 switch (ebml_read_id (s, &il))
1239 case MATROSKA_ID_ATTACHEDFILE:
1241 uint64_t len;
1242 int i;
1243 char* name = NULL;
1244 char* mime = NULL;
1245 char* data = NULL;
1246 int data_size = 0;
1248 len = ebml_read_length (s, &i);
1249 l = len + i;
1251 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + an attachment...\n");
1253 while (len > 0)
1255 uint64_t l;
1256 int il;
1258 switch (ebml_read_id (s, &il))
1260 case MATROSKA_ID_FILENAME:
1261 name = ebml_read_utf8 (s, &l);
1262 if (name == NULL)
1263 return 0;
1264 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + FileName: %s\n",
1265 name);
1266 break;
1268 case MATROSKA_ID_FILEMIMETYPE:
1269 mime = ebml_read_ascii (s, &l);
1270 if (mime == NULL)
1271 return 0;
1272 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + FileMimeType: %s\n",
1273 mime);
1274 break;
1276 case MATROSKA_ID_FILEDATA:
1278 int x;
1279 uint64_t num = ebml_read_length (s, &x);
1280 l = x + num;
1281 free(data);
1282 data = malloc (num);
1283 if (stream_read(s, data, num) != (int) num)
1285 free(data);
1286 return 0;
1288 data_size = num;
1289 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + FileData, length "
1290 "%u\n", data_size);
1291 break;
1294 default:
1295 ebml_read_skip (s, &l);
1296 break;
1298 len -= l + il;
1301 demuxer_add_attachment(demuxer, name, mime, data, data_size);
1302 mp_msg(MSGT_DEMUX, MSGL_V,
1303 "[mkv] Attachment: %s, %s, %u bytes\n",
1304 name, mime, data_size);
1305 break;
1308 default:
1309 ebml_read_skip (s, &l);
1310 break;
1312 length -= l + il;
1315 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] \\---- [ parsing attachments ] ---------\n");
1316 return 0;
1319 static int
1320 demux_mkv_read_seekhead (demuxer_t *demuxer)
1322 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
1323 stream_t *s = demuxer->stream;
1324 uint64_t length, l, seek_pos, saved_pos, num;
1325 uint32_t seek_id;
1326 int i, il, res = 0;
1327 off_t off;
1329 off = stream_tell (s);
1330 for (i=0; i<mkv_d->parsed_seekhead_num; i++)
1331 if (mkv_d->parsed_seekhead[i] == off)
1333 ebml_read_skip (s, NULL);
1334 return 0;
1336 mkv_d->parsed_seekhead = realloc (mkv_d->parsed_seekhead,
1337 (mkv_d->parsed_seekhead_num+1)
1338 * sizeof (off_t));
1339 mkv_d->parsed_seekhead[mkv_d->parsed_seekhead_num++] = off;
1341 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] /---- [ parsing seek head ] ---------\n");
1342 length = ebml_read_length (s, NULL);
1343 /* off now holds the position of the next element after the seek head. */
1344 off = stream_tell (s) + length;
1345 while (length > 0 && !res)
1348 seek_id = 0;
1349 seek_pos = EBML_UINT_INVALID;
1351 switch (ebml_read_id (s, &il))
1353 case MATROSKA_ID_SEEKENTRY:
1355 uint64_t len;
1357 len = ebml_read_length (s, &i);
1358 l = len + i;
1360 while (len > 0)
1362 uint64_t l;
1363 int il;
1365 switch (ebml_read_id (s, &il))
1367 case MATROSKA_ID_SEEKID:
1368 num = ebml_read_uint (s, &l);
1369 if (num != EBML_UINT_INVALID)
1370 seek_id = num;
1371 break;
1373 case MATROSKA_ID_SEEKPOSITION:
1374 seek_pos = ebml_read_uint (s, &l);
1375 break;
1377 default:
1378 ebml_read_skip (s, &l);
1379 break;
1381 len -= l + il;
1384 break;
1387 default:
1388 ebml_read_skip (s, &l);
1389 break;
1391 length -= l + il;
1393 if (seek_id == 0 || seek_id == MATROSKA_ID_CLUSTER
1394 || seek_pos == EBML_UINT_INVALID ||
1395 ((mkv_d->segment_start + seek_pos) >= (uint64_t)demuxer->movi_end))
1396 continue;
1398 saved_pos = stream_tell (s);
1399 if (!stream_seek (s, mkv_d->segment_start + seek_pos))
1400 res = 1;
1401 else
1403 if (ebml_read_id (s, &il) != seek_id)
1404 res = 1;
1405 else
1406 switch (seek_id)
1408 case MATROSKA_ID_CUES:
1409 if (demux_mkv_read_cues (demuxer))
1410 res = 1;
1411 break;
1413 case MATROSKA_ID_TAGS:
1414 if (demux_mkv_read_tags (demuxer))
1415 res = 1;
1416 break;
1418 case MATROSKA_ID_SEEKHEAD:
1419 if (demux_mkv_read_seekhead (demuxer))
1420 res = 1;
1421 break;
1423 case MATROSKA_ID_CHAPTERS:
1424 if (demux_mkv_read_chapters (demuxer))
1425 res = 1;
1426 break;
1430 stream_seek (s, saved_pos);
1432 if (res)
1434 /* If there was an error then try to skip this seek head. */
1435 if (stream_seek (s, off))
1436 res = 0;
1438 else
1439 if (length > 0)
1440 stream_seek (s, stream_tell (s) + length);
1441 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] \\---- [ parsing seek head ] ---------\n");
1442 return res;
1445 static int
1446 demux_mkv_open_video (demuxer_t *demuxer, mkv_track_t *track, int vid);
1447 static int
1448 demux_mkv_open_audio (demuxer_t *demuxer, mkv_track_t *track, int aid);
1449 static int
1450 demux_mkv_open_sub (demuxer_t *demuxer, mkv_track_t *track, int sid);
1452 static void
1453 display_create_tracks (demuxer_t *demuxer)
1455 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *)demuxer->priv;
1456 int i, vid=0, aid=0, sid=0;
1458 for (i=0; i<mkv_d->num_tracks; i++)
1460 char *type = "unknown", str[32];
1461 *str = '\0';
1462 switch (mkv_d->tracks[i]->type)
1464 case MATROSKA_TRACK_VIDEO:
1465 type = "video";
1466 demux_mkv_open_video(demuxer, mkv_d->tracks[i], vid);
1467 if (mkv_d->tracks[i]->name)
1468 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VID_%d_NAME=%s\n", vid, mkv_d->tracks[i]->name);
1469 sprintf (str, "-vid %u", vid++);
1470 break;
1471 case MATROSKA_TRACK_AUDIO:
1472 type = "audio";
1473 demux_mkv_open_audio(demuxer, mkv_d->tracks[i], aid);
1474 if (mkv_d->tracks[i]->name)
1475 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AID_%d_NAME=%s\n", aid, mkv_d->tracks[i]->name);
1476 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AID_%d_LANG=%s\n", aid, mkv_d->tracks[i]->language);
1477 sprintf (str, "-aid %u, -alang %.5s",aid++,mkv_d->tracks[i]->language);
1478 break;
1479 case MATROSKA_TRACK_SUBTITLE:
1480 type = "subtitles";
1481 demux_mkv_open_sub(demuxer, mkv_d->tracks[i], sid);
1482 if (mkv_d->tracks[i]->name)
1483 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SID_%d_NAME=%s\n", sid, mkv_d->tracks[i]->name);
1484 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SID_%d_LANG=%s\n", sid, mkv_d->tracks[i]->language);
1485 sprintf (str, "-sid %u, -slang %.5s",sid++,mkv_d->tracks[i]->language);
1486 break;
1488 if (mkv_d->tracks[i]->name)
1489 mp_msg(MSGT_DEMUX, MSGL_INFO, MSGTR_MPDEMUX_MKV_TrackIDName,
1490 mkv_d->tracks[i]->tnum, type, mkv_d->tracks[i]->codec_id, mkv_d->tracks[i]->name, str);
1491 else
1492 mp_msg(MSGT_DEMUX, MSGL_INFO, MSGTR_MPDEMUX_MKV_TrackID,
1493 mkv_d->tracks[i]->tnum, type, mkv_d->tracks[i]->codec_id, str);
1497 typedef struct {
1498 char *id;
1499 int fourcc;
1500 int extradata;
1501 } videocodec_info_t;
1503 static const videocodec_info_t vinfo[] = {
1504 { MKV_V_MPEG1, mmioFOURCC('m', 'p', 'g', '1'), 0 },
1505 { MKV_V_MPEG2, mmioFOURCC('m', 'p', 'g', '2'), 0 },
1506 { MKV_V_MPEG4_SP, mmioFOURCC('m', 'p', '4', 'v'), 1 },
1507 { MKV_V_MPEG4_ASP, mmioFOURCC('m', 'p', '4', 'v'), 1 },
1508 { MKV_V_MPEG4_AP, mmioFOURCC('m', 'p', '4', 'v'), 1 },
1509 { MKV_V_MPEG4_AVC, mmioFOURCC('a', 'v', 'c', '1'), 1 },
1510 { MKV_V_THEORA, mmioFOURCC('t', 'h', 'e', 'o'), 1 },
1511 { NULL, 0, 0 }
1514 static int
1515 demux_mkv_open_video (demuxer_t *demuxer, mkv_track_t *track, int vid)
1517 BITMAPINFOHEADER *bih;
1518 void *ImageDesc = NULL;
1519 sh_video_t *sh_v;
1521 if (track->ms_compat) /* MS compatibility mode */
1523 BITMAPINFOHEADER *src;
1525 if (track->private_data == NULL
1526 || track->private_size < sizeof (BITMAPINFOHEADER))
1527 return 1;
1529 src = (BITMAPINFOHEADER *) track->private_data;
1530 bih = calloc (1, track->private_size);
1531 bih->biSize = le2me_32 (src->biSize);
1532 bih->biWidth = le2me_32 (src->biWidth);
1533 bih->biHeight = le2me_32 (src->biHeight);
1534 bih->biPlanes = le2me_16 (src->biPlanes);
1535 bih->biBitCount = le2me_16 (src->biBitCount);
1536 bih->biCompression = le2me_32 (src->biCompression);
1537 bih->biSizeImage = le2me_32 (src->biSizeImage);
1538 bih->biXPelsPerMeter = le2me_32 (src->biXPelsPerMeter);
1539 bih->biYPelsPerMeter = le2me_32 (src->biYPelsPerMeter);
1540 bih->biClrUsed = le2me_32 (src->biClrUsed);
1541 bih->biClrImportant = le2me_32 (src->biClrImportant);
1542 memcpy((char *) bih + sizeof (BITMAPINFOHEADER),
1543 (char *) src + sizeof (BITMAPINFOHEADER),
1544 track->private_size - sizeof (BITMAPINFOHEADER));
1546 if (track->v_width == 0)
1547 track->v_width = bih->biWidth;
1548 if (track->v_height == 0)
1549 track->v_height = bih->biHeight;
1551 else
1553 bih = calloc (1, sizeof (BITMAPINFOHEADER));
1554 bih->biSize = sizeof (BITMAPINFOHEADER);
1555 bih->biWidth = track->v_width;
1556 bih->biHeight = track->v_height;
1557 bih->biBitCount = 24;
1558 bih->biSizeImage = bih->biWidth * bih->biHeight * bih->biBitCount/8;
1560 if (track->private_size >= RVPROPERTIES_SIZE
1561 && (!strcmp (track->codec_id, MKV_V_REALV10)
1562 || !strcmp (track->codec_id, MKV_V_REALV20)
1563 || !strcmp (track->codec_id, MKV_V_REALV30)
1564 || !strcmp (track->codec_id, MKV_V_REALV40)))
1566 unsigned char *dst, *src;
1567 uint32_t type2;
1568 unsigned int cnt;
1570 src = track->private_data + RVPROPERTIES_SIZE;
1572 cnt = track->private_size - RVPROPERTIES_SIZE;
1573 bih = realloc(bih, sizeof (BITMAPINFOHEADER)+8+cnt);
1574 bih->biSize = 48+cnt;
1575 bih->biPlanes = 1;
1576 type2 = AV_RB32(src - 4);
1577 if (type2 == 0x10003000 || type2 == 0x10003001)
1578 bih->biCompression=mmioFOURCC('R','V','1','3');
1579 else
1580 bih->biCompression=mmioFOURCC('R','V',track->codec_id[9],'0');
1581 dst = (unsigned char *) (bih + 1);
1582 // copy type1 and type2 info from rv properties
1583 memcpy(dst, src - 8, 8);
1584 stream_read(demuxer->stream, dst+8, cnt);
1585 track->realmedia = 1;
1587 #ifdef CONFIG_QTX_CODECS
1589 else if (track->private_size >= sizeof (ImageDescription)
1590 && !strcmp(track->codec_id, MKV_V_QUICKTIME))
1592 ImageDescriptionPtr idesc;
1594 idesc = (ImageDescriptionPtr) track->private_data;
1595 idesc->idSize = be2me_32 (idesc->idSize);
1596 idesc->cType = be2me_32 (idesc->cType);
1597 idesc->version = be2me_16 (idesc->version);
1598 idesc->revisionLevel = be2me_16 (idesc->revisionLevel);
1599 idesc->vendor = be2me_32 (idesc->vendor);
1600 idesc->temporalQuality = be2me_32 (idesc->temporalQuality);
1601 idesc->spatialQuality = be2me_32 (idesc->spatialQuality);
1602 idesc->width = be2me_16 (idesc->width);
1603 idesc->height = be2me_16 (idesc->height);
1604 idesc->hRes = be2me_32 (idesc->hRes);
1605 idesc->vRes = be2me_32 (idesc->vRes);
1606 idesc->dataSize = be2me_32 (idesc->dataSize);
1607 idesc->frameCount = be2me_16 (idesc->frameCount);
1608 idesc->depth = be2me_16 (idesc->depth);
1609 idesc->clutID = be2me_16 (idesc->clutID);
1610 bih->biPlanes = 1;
1611 bih->biCompression = idesc->cType;
1612 ImageDesc = idesc;
1613 #endif /* CONFIG_QTX_CODECS */
1616 else
1618 const videocodec_info_t *vi = vinfo;
1619 while (vi->id && strcmp(vi->id, track->codec_id)) vi++;
1620 bih->biCompression = vi->fourcc;
1621 if (vi->extradata && track->private_data && (track->private_size > 0))
1623 bih->biSize += track->private_size;
1624 bih = realloc (bih, bih->biSize);
1625 memcpy (bih + 1, track->private_data, track->private_size);
1627 track->reorder_timecodes = user_correct_pts == 0;
1628 if (!vi->id) {
1629 mp_msg (MSGT_DEMUX,MSGL_WARN, MSGTR_MPDEMUX_MKV_UnknownCodecID,
1630 track->codec_id, track->tnum);
1631 free(bih);
1632 return 1;
1637 sh_v = new_sh_video_vid (demuxer, track->tnum, vid);
1638 sh_v->bih = bih;
1639 sh_v->format = sh_v->bih->biCompression;
1640 if (track->v_frate == 0.0)
1641 track->v_frate = 25.0;
1642 sh_v->fps = track->v_frate;
1643 sh_v->frametime = 1 / track->v_frate;
1644 sh_v->aspect = 0;
1645 if (!track->realmedia)
1647 sh_v->disp_w = track->v_width;
1648 sh_v->disp_h = track->v_height;
1649 if (track->v_dheight)
1650 sh_v->aspect = (float)track->v_dwidth / (float)track->v_dheight;
1652 else
1654 // vd_realvid.c will set aspect to disp_w/disp_h and rederive
1655 // disp_w and disp_h from the RealVideo stream contents returned
1656 // by the Real DLLs. If DisplayWidth/DisplayHeight was not set in
1657 // the Matroska file then it has already been set to PixelWidth/Height
1658 // by check_track_information.
1659 sh_v->disp_w = track->v_dwidth;
1660 sh_v->disp_h = track->v_dheight;
1662 sh_v->ImageDesc = ImageDesc;
1663 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] Aspect: %f\n", sh_v->aspect);
1665 sh_v->ds = demuxer->video;
1666 return 0;
1669 static int
1670 demux_mkv_open_audio (demuxer_t *demuxer, mkv_track_t *track, int aid)
1672 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
1673 sh_audio_t *sh_a = new_sh_audio_aid(demuxer, track->tnum, aid);
1674 demux_packet_t *dp;
1675 if(!sh_a) return 1;
1676 mkv_d->audio_tracks[mkv_d->last_aid] = track->tnum;
1678 if (track->language && (strcmp(track->language, "und") != 0))
1679 sh_a->lang = strdup(track->language);
1680 sh_a->default_track = track->default_track;
1681 sh_a->ds = demuxer->audio;
1682 sh_a->wf = malloc (sizeof (WAVEFORMATEX));
1683 if (track->ms_compat && (track->private_size >= sizeof(WAVEFORMATEX)))
1685 WAVEFORMATEX *wf = (WAVEFORMATEX *)track->private_data;
1686 sh_a->wf = realloc(sh_a->wf, track->private_size);
1687 sh_a->wf->wFormatTag = le2me_16 (wf->wFormatTag);
1688 sh_a->wf->nChannels = le2me_16 (wf->nChannels);
1689 sh_a->wf->nSamplesPerSec = le2me_32 (wf->nSamplesPerSec);
1690 sh_a->wf->nAvgBytesPerSec = le2me_32 (wf->nAvgBytesPerSec);
1691 sh_a->wf->nBlockAlign = le2me_16 (wf->nBlockAlign);
1692 sh_a->wf->wBitsPerSample = le2me_16 (wf->wBitsPerSample);
1693 sh_a->wf->cbSize = track->private_size - sizeof(WAVEFORMATEX);
1694 memcpy(sh_a->wf + 1, wf + 1, track->private_size - sizeof(WAVEFORMATEX));
1695 if (track->a_sfreq == 0.0)
1696 track->a_sfreq = sh_a->wf->nSamplesPerSec;
1697 if (track->a_channels == 0)
1698 track->a_channels = sh_a->wf->nChannels;
1699 if (track->a_bps == 0)
1700 track->a_bps = sh_a->wf->wBitsPerSample;
1701 track->a_formattag = sh_a->wf->wFormatTag;
1703 else
1705 memset(sh_a->wf, 0, sizeof (WAVEFORMATEX));
1706 if (!strcmp(track->codec_id, MKV_A_MP3) ||
1707 !strcmp(track->codec_id, MKV_A_MP2))
1708 track->a_formattag = 0x0055;
1709 else if (!strncmp(track->codec_id, MKV_A_AC3, strlen(MKV_A_AC3)))
1710 track->a_formattag = 0x2000;
1711 else if (!strcmp(track->codec_id, MKV_A_DTS))
1712 track->a_formattag = 0x2001;
1713 else if (!strcmp(track->codec_id, MKV_A_PCM) ||
1714 !strcmp(track->codec_id, MKV_A_PCM_BE))
1715 track->a_formattag = 0x0001;
1716 else if (!strcmp(track->codec_id, MKV_A_AAC_2MAIN) ||
1717 !strncmp(track->codec_id, MKV_A_AAC_2LC,
1718 strlen(MKV_A_AAC_2LC)) ||
1719 !strcmp(track->codec_id, MKV_A_AAC_2SSR) ||
1720 !strcmp(track->codec_id, MKV_A_AAC_4MAIN) ||
1721 !strncmp(track->codec_id, MKV_A_AAC_4LC,
1722 strlen(MKV_A_AAC_4LC)) ||
1723 !strcmp(track->codec_id, MKV_A_AAC_4SSR) ||
1724 !strcmp(track->codec_id, MKV_A_AAC_4LTP) ||
1725 !strcmp(track->codec_id, MKV_A_AAC))
1726 track->a_formattag = mmioFOURCC('M', 'P', '4', 'A');
1727 else if (!strcmp(track->codec_id, MKV_A_VORBIS))
1729 if (track->private_data == NULL)
1730 return 1;
1731 track->a_formattag = mmioFOURCC('v', 'r', 'b', 's');
1733 else if (!strcmp(track->codec_id, MKV_A_QDMC))
1734 track->a_formattag = mmioFOURCC('Q', 'D', 'M', 'C');
1735 else if (!strcmp(track->codec_id, MKV_A_QDMC2))
1736 track->a_formattag = mmioFOURCC('Q', 'D', 'M', '2');
1737 else if (!strcmp(track->codec_id, MKV_A_WAVPACK))
1738 track->a_formattag = mmioFOURCC('W', 'V', 'P', 'K');
1739 else if (!strcmp(track->codec_id, MKV_A_FLAC))
1741 if (track->private_data == NULL || track->private_size == 0)
1743 mp_msg (MSGT_DEMUX, MSGL_WARN,
1744 MSGTR_MPDEMUX_MKV_FlacTrackDoesNotContainValidHeaders);
1745 return 1;
1747 track->a_formattag = mmioFOURCC ('f', 'L', 'a', 'C');
1749 else if (track->private_size >= RAPROPERTIES4_SIZE)
1751 if (!strcmp(track->codec_id, MKV_A_REAL28))
1752 track->a_formattag = mmioFOURCC('2', '8', '_', '8');
1753 else if (!strcmp(track->codec_id, MKV_A_REALATRC))
1754 track->a_formattag = mmioFOURCC('a', 't', 'r', 'c');
1755 else if (!strcmp(track->codec_id, MKV_A_REALCOOK))
1756 track->a_formattag = mmioFOURCC('c', 'o', 'o', 'k');
1757 else if (!strcmp(track->codec_id, MKV_A_REALDNET))
1758 track->a_formattag = mmioFOURCC('d', 'n', 'e', 't');
1759 else if (!strcmp(track->codec_id, MKV_A_REALSIPR))
1760 track->a_formattag = mmioFOURCC('s', 'i', 'p', 'r');
1762 else
1764 mp_msg (MSGT_DEMUX, MSGL_WARN, MSGTR_MPDEMUX_MKV_UnknownAudioCodec,
1765 track->codec_id, track->tnum);
1766 free_sh_audio(demuxer, track->tnum);
1767 return 1;
1771 sh_a->format = track->a_formattag;
1772 sh_a->wf->wFormatTag = track->a_formattag;
1773 sh_a->channels = track->a_channels;
1774 sh_a->wf->nChannels = track->a_channels;
1775 sh_a->samplerate = (uint32_t) track->a_sfreq;
1776 sh_a->wf->nSamplesPerSec = (uint32_t) track->a_sfreq;
1777 if (track->a_bps == 0)
1779 sh_a->samplesize = 2;
1780 sh_a->wf->wBitsPerSample = 16;
1782 else
1784 sh_a->samplesize = track->a_bps / 8;
1785 sh_a->wf->wBitsPerSample = track->a_bps;
1787 if (track->a_formattag == 0x0055) /* MP3 || MP2 */
1789 sh_a->wf->nAvgBytesPerSec = 16000;
1790 sh_a->wf->nBlockAlign = 1152;
1792 else if ((track->a_formattag == 0x2000) || /* AC3 */
1793 (track->a_formattag == 0x2001)) /* DTS */
1795 free(sh_a->wf);
1796 sh_a->wf = NULL;
1798 else if (track->a_formattag == 0x0001) /* PCM || PCM_BE */
1800 sh_a->wf->nAvgBytesPerSec = sh_a->channels * sh_a->samplerate*2;
1801 sh_a->wf->nBlockAlign = sh_a->wf->nAvgBytesPerSec;
1802 if (!strcmp(track->codec_id, MKV_A_PCM_BE))
1803 sh_a->format = mmioFOURCC('t', 'w', 'o', 's');
1805 else if (!strcmp(track->codec_id, MKV_A_QDMC) ||
1806 !strcmp(track->codec_id, MKV_A_QDMC2))
1808 sh_a->wf->nAvgBytesPerSec = 16000;
1809 sh_a->wf->nBlockAlign = 1486;
1810 track->fix_i_bps = 1;
1811 track->qt_last_a_pts = 0.0;
1812 if (track->private_data != NULL)
1814 sh_a->codecdata=malloc(track->private_size);
1815 memcpy (sh_a->codecdata, track->private_data,
1816 track->private_size);
1817 sh_a->codecdata_len = track->private_size;
1820 else if (track->a_formattag == mmioFOURCC('M', 'P', '4', 'A'))
1822 int profile, srate_idx;
1824 sh_a->wf->nAvgBytesPerSec = 16000;
1825 sh_a->wf->nBlockAlign = 1024;
1827 if (!strcmp (track->codec_id, MKV_A_AAC) &&
1828 (NULL != track->private_data))
1830 sh_a->codecdata=malloc(track->private_size);
1831 memcpy (sh_a->codecdata, track->private_data,
1832 track->private_size);
1833 sh_a->codecdata_len = track->private_size;
1834 return 0;
1837 /* Recreate the 'private data' */
1838 /* which faad2 uses in its initialization */
1839 srate_idx = aac_get_sample_rate_index (sh_a->samplerate);
1840 if (!strncmp (&track->codec_id[12], "MAIN", 4))
1841 profile = 0;
1842 else if (!strncmp (&track->codec_id[12], "LC", 2))
1843 profile = 1;
1844 else if (!strncmp (&track->codec_id[12], "SSR", 3))
1845 profile = 2;
1846 else
1847 profile = 3;
1848 sh_a->codecdata = malloc (5);
1849 sh_a->codecdata[0] = ((profile+1) << 3) | ((srate_idx&0xE) >> 1);
1850 sh_a->codecdata[1] = ((srate_idx&0x1)<<7)|(track->a_channels<<3);
1852 if (strstr(track->codec_id, "SBR") != NULL)
1854 /* HE-AAC (aka SBR AAC) */
1855 sh_a->codecdata_len = 5;
1857 sh_a->samplerate *= 2;
1858 sh_a->wf->nSamplesPerSec *= 2;
1859 srate_idx = aac_get_sample_rate_index(sh_a->samplerate);
1860 sh_a->codecdata[2] = AAC_SYNC_EXTENSION_TYPE >> 3;
1861 sh_a->codecdata[3] = ((AAC_SYNC_EXTENSION_TYPE&0x07)<<5) | 5;
1862 sh_a->codecdata[4] = (1 << 7) | (srate_idx << 3);
1863 track->default_duration = 1024.0 / (sh_a->samplerate / 2);
1865 else
1867 sh_a->codecdata_len = 2;
1868 track->default_duration = 1024.0 / (float)sh_a->samplerate;
1871 else if (track->a_formattag == mmioFOURCC('v', 'r', 'b', 's')) /* VORBIS */
1873 sh_a->wf->cbSize = track->private_size;
1874 sh_a->wf = realloc(sh_a->wf, sizeof(WAVEFORMATEX) + sh_a->wf->cbSize);
1875 memcpy((unsigned char *) (sh_a->wf+1), track->private_data, sh_a->wf->cbSize);
1877 else if (track->private_size >= RAPROPERTIES4_SIZE
1878 && !strncmp (track->codec_id, MKV_A_REALATRC, 7))
1880 /* Common initialization for all RealAudio codecs */
1881 unsigned char *src = track->private_data;
1882 int codecdata_length, version;
1883 int flavor;
1885 sh_a->wf->nAvgBytesPerSec = 0; /* FIXME !? */
1887 version = AV_RB16(src + 4);
1888 flavor = AV_RB16(src + 22);
1889 track->coded_framesize = AV_RB32(src + 24);
1890 track->sub_packet_h = AV_RB16(src + 40);
1891 sh_a->wf->nBlockAlign =
1892 track->audiopk_size = AV_RB16(src + 42);
1893 track->sub_packet_size = AV_RB16(src + 44);
1894 if (version == 4)
1896 src += RAPROPERTIES4_SIZE;
1897 src += src[0] + 1;
1898 src += src[0] + 1;
1900 else
1901 src += RAPROPERTIES5_SIZE;
1903 src += 3;
1904 if (version == 5)
1905 src++;
1906 codecdata_length = AV_RB32(src);
1907 src += 4;
1908 sh_a->wf->cbSize = codecdata_length;
1909 sh_a->wf = realloc (sh_a->wf,
1910 sizeof (WAVEFORMATEX) +
1911 sh_a->wf->cbSize);
1912 memcpy(((char *)(sh_a->wf + 1)), src, codecdata_length);
1914 switch (track->a_formattag) {
1915 case mmioFOURCC('a', 't', 'r', 'c'):
1916 sh_a->wf->nAvgBytesPerSec = atrc_fl2bps[flavor];
1917 sh_a->wf->nBlockAlign = track->sub_packet_size;
1918 track->audio_buf = malloc(track->sub_packet_h * track->audiopk_size);
1919 track->audio_timestamp = malloc(track->sub_packet_h * sizeof(float));
1920 break;
1921 case mmioFOURCC('c', 'o', 'o', 'k'):
1922 sh_a->wf->nAvgBytesPerSec = cook_fl2bps[flavor];
1923 sh_a->wf->nBlockAlign = track->sub_packet_size;
1924 track->audio_buf = malloc(track->sub_packet_h * track->audiopk_size);
1925 track->audio_timestamp = malloc(track->sub_packet_h * sizeof(float));
1926 break;
1927 case mmioFOURCC('s', 'i', 'p', 'r'):
1928 sh_a->wf->nAvgBytesPerSec = sipr_fl2bps[flavor];
1929 sh_a->wf->nBlockAlign = track->coded_framesize;
1930 track->audio_buf = malloc(track->sub_packet_h * track->audiopk_size);
1931 track->audio_timestamp = malloc(track->sub_packet_h * sizeof(float));
1932 break;
1933 case mmioFOURCC('2', '8', '_', '8'):
1934 sh_a->wf->nAvgBytesPerSec = 3600;
1935 sh_a->wf->nBlockAlign = track->coded_framesize;
1936 track->audio_buf = malloc(track->sub_packet_h * track->audiopk_size);
1937 track->audio_timestamp = malloc(track->sub_packet_h * sizeof(float));
1938 break;
1941 track->realmedia = 1;
1943 else if (!strcmp(track->codec_id, MKV_A_FLAC) ||
1944 (track->a_formattag == 0xf1ac))
1946 unsigned char *ptr;
1947 int size;
1948 free(sh_a->wf);
1949 sh_a->wf = NULL;
1951 if (track->a_formattag == mmioFOURCC('f', 'L', 'a', 'C'))
1953 ptr = (unsigned char *)track->private_data;
1954 size = track->private_size;
1956 else
1958 sh_a->format = mmioFOURCC('f', 'L', 'a', 'C');
1959 ptr = (unsigned char *) track->private_data
1960 + sizeof (WAVEFORMATEX);
1961 size = track->private_size - sizeof (WAVEFORMATEX);
1963 if (size < 4 || ptr[0] != 'f' || ptr[1] != 'L' ||
1964 ptr[2] != 'a' || ptr[3] != 'C')
1966 dp = new_demux_packet (4);
1967 memcpy (dp->buffer, "fLaC", 4);
1969 else
1971 dp = new_demux_packet (size);
1972 memcpy (dp->buffer, ptr, size);
1974 dp->pts = 0;
1975 dp->flags = 0;
1976 ds_add_packet (demuxer->audio, dp);
1978 else if (track->a_formattag == mmioFOURCC('W', 'V', 'P', 'K'))
1979 { /* do nothing, still works */ }
1980 else if (!track->ms_compat || (track->private_size < sizeof(WAVEFORMATEX)))
1982 free_sh_audio(demuxer, track->tnum);
1983 return 1;
1986 return 0;
1989 static int
1990 demux_mkv_open_sub (demuxer_t *demuxer, mkv_track_t *track, int sid)
1992 if (track->subtitle_type != MATROSKA_SUBTYPE_UNKNOWN)
1994 int size, m;
1995 uint8_t *buffer;
1996 sh_sub_t *sh = new_sh_sub_sid(demuxer, track->tnum, sid);
1997 track->sh_sub = sh;
1998 sh->type = 't';
1999 if (track->subtitle_type == MATROSKA_SUBTYPE_VOBSUB)
2000 sh->type = 'v';
2001 if (track->subtitle_type == MATROSKA_SUBTYPE_SSA)
2002 sh->type = 'a';
2003 size = track->private_size;
2004 m = demux_mkv_decode (track,track->private_data,&buffer,&size,2);
2005 if (buffer && m)
2007 free (track->private_data);
2008 track->private_data = buffer;
2009 track->private_size = size;
2011 sh->extradata=malloc(track->private_size);
2012 memcpy (sh->extradata, track->private_data,
2013 track->private_size);
2014 sh->extradata_len = track->private_size;
2015 if (track->language && (strcmp(track->language, "und") != 0))
2016 sh->lang = strdup(track->language);
2017 sh->default_track = track->default_track;
2019 else
2021 mp_msg (MSGT_DEMUX, MSGL_ERR, MSGTR_MPDEMUX_MKV_SubtitleTypeNotSupported,
2022 track->codec_id);
2023 return 1;
2026 return 0;
2029 static void demux_mkv_seek (demuxer_t *demuxer, float rel_seek_secs, float audio_delay, int flags);
2031 static int
2032 demux_mkv_open (demuxer_t *demuxer)
2034 stream_t *s = demuxer->stream;
2035 mkv_demuxer_t *mkv_d;
2036 mkv_track_t *track;
2037 int i, version, cont = 0;
2038 char *str;
2040 stream_seek(s, s->start_pos);
2041 str = ebml_read_header (s, &version);
2042 if (str == NULL || strcmp (str, "matroska") || version > 2)
2044 mp_msg (MSGT_DEMUX, MSGL_DBG2, "[mkv] no head found\n");
2045 return 0;
2047 free (str);
2049 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] Found the head...\n");
2051 if (ebml_read_id (s, NULL) != MATROSKA_ID_SEGMENT)
2053 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] but no segment :(\n");
2054 return 0;
2056 ebml_read_length (s, NULL); /* return bytes number until EOF */
2058 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] + a segment...\n");
2060 mkv_d = calloc (1, sizeof (mkv_demuxer_t));
2061 demuxer->priv = mkv_d;
2062 mkv_d->tc_scale = 1000000;
2063 mkv_d->segment_start = stream_tell (s);
2064 mkv_d->parsed_cues = malloc (sizeof (off_t));
2065 mkv_d->parsed_seekhead = malloc (sizeof (off_t));
2067 while (!cont)
2069 switch (ebml_read_id (s, NULL))
2071 case MATROSKA_ID_INFO:
2072 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] |+ segment information...\n");
2073 cont = demux_mkv_read_info (demuxer);
2074 break;
2076 case MATROSKA_ID_TRACKS:
2077 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] |+ segment tracks...\n");
2078 cont = demux_mkv_read_tracks (demuxer);
2079 break;
2081 case MATROSKA_ID_CUES:
2082 cont = demux_mkv_read_cues (demuxer);
2083 break;
2085 case MATROSKA_ID_TAGS:
2086 cont = demux_mkv_read_tags (demuxer);
2087 break;
2089 case MATROSKA_ID_SEEKHEAD:
2090 cont = demux_mkv_read_seekhead (demuxer);
2091 break;
2093 case MATROSKA_ID_CHAPTERS:
2094 cont = demux_mkv_read_chapters (demuxer);
2095 break;
2097 case MATROSKA_ID_ATTACHMENTS:
2098 cont = demux_mkv_read_attachments (demuxer);
2099 break;
2101 case MATROSKA_ID_CLUSTER:
2103 int p, l;
2104 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] |+ found cluster, headers are "
2105 "parsed completely :)\n");
2106 /* get the first cluster timecode */
2107 p = stream_tell(s);
2108 l = ebml_read_length (s, NULL);
2109 while (ebml_read_id (s, NULL) != MATROSKA_ID_CLUSTERTIMECODE)
2111 ebml_read_skip (s, NULL);
2112 if (stream_tell (s) >= p + l)
2113 break;
2115 if (stream_tell (s) < p + l)
2117 uint64_t num = ebml_read_uint (s, NULL);
2118 if (num == EBML_UINT_INVALID)
2119 return 0;
2120 mkv_d->first_tc = num * mkv_d->tc_scale / 1000000.0;
2121 mkv_d->has_first_tc = 1;
2123 stream_seek (s, p - 4);
2124 cont = 1;
2125 break;
2128 default:
2129 cont = 1;
2130 case EBML_ID_VOID:
2131 ebml_read_skip (s, NULL);
2132 break;
2136 display_create_tracks (demuxer);
2138 /* select video track */
2139 track = NULL;
2140 if (demuxer->video->id == -1) /* automatically select a video track */
2142 /* search for a video track that has the 'default' flag set */
2143 for (i=0; i<mkv_d->num_tracks; i++)
2144 if (mkv_d->tracks[i]->type == MATROSKA_TRACK_VIDEO
2145 && mkv_d->tracks[i]->default_track)
2147 track = mkv_d->tracks[i];
2148 break;
2151 if (track == NULL)
2152 /* no track has the 'default' flag set */
2153 /* let's take the first video track */
2154 for (i=0; i<mkv_d->num_tracks; i++)
2155 if (mkv_d->tracks[i]->type == MATROSKA_TRACK_VIDEO)
2157 track = mkv_d->tracks[i];
2158 break;
2161 else if (demuxer->video->id != -2) /* -2 = no video at all */
2162 track = demux_mkv_find_track_by_num (mkv_d, demuxer->video->id,
2163 MATROSKA_TRACK_VIDEO);
2165 if (track && demuxer->v_streams[track->tnum])
2167 mp_msg (MSGT_DEMUX, MSGL_INFO,
2168 MSGTR_MPDEMUX_MKV_WillPlayVideoTrack, track->tnum);
2169 demuxer->video->id = track->tnum;
2170 demuxer->video->sh = demuxer->v_streams[track->tnum];
2172 else
2174 mp_msg (MSGT_DEMUX, MSGL_INFO, MSGTR_MPDEMUX_MKV_NoVideoTrackFound);
2175 demuxer->video->id = -2;
2178 /* select audio track */
2179 track = NULL;
2180 if (track == NULL)
2181 /* search for an audio track that has the 'default' flag set */
2182 for (i=0; i < mkv_d->num_tracks; i++)
2183 if (mkv_d->tracks[i]->type == MATROSKA_TRACK_AUDIO
2184 && mkv_d->tracks[i]->default_track)
2186 track = mkv_d->tracks[i];
2187 break;
2190 if (track == NULL)
2191 /* no track has the 'default' flag set */
2192 /* let's take the first audio track */
2193 for (i=0; i < mkv_d->num_tracks; i++)
2194 if (mkv_d->tracks[i]->type == MATROSKA_TRACK_AUDIO)
2196 track = mkv_d->tracks[i];
2197 break;
2200 if (track && demuxer->a_streams[track->tnum])
2202 demuxer->audio->id = track->tnum;
2203 demuxer->audio->sh = demuxer->a_streams[track->tnum];
2205 else
2207 mp_msg (MSGT_DEMUX, MSGL_INFO, MSGTR_MPDEMUX_MKV_NoAudioTrackFound);
2208 demuxer->audio->id = -2;
2212 if(demuxer->audio->id != -2)
2213 for (i=0; i < mkv_d->num_tracks; i++)
2215 if(mkv_d->tracks[i]->type != MATROSKA_TRACK_AUDIO)
2216 continue;
2217 if(demuxer->a_streams[track->tnum])
2219 mkv_d->last_aid++;
2220 if(mkv_d->last_aid == MAX_A_STREAMS)
2221 break;
2225 if (demuxer->chapters)
2227 for (i=0; i < (int)demuxer->num_chapters; i++)
2229 demuxer->chapters[i].start -= mkv_d->first_tc;
2230 demuxer->chapters[i].end -= mkv_d->first_tc;
2232 if (dvd_last_chapter > 0 && dvd_last_chapter <= demuxer->num_chapters)
2234 if (demuxer->chapters[dvd_last_chapter-1].end != 0)
2235 mkv_d->stop_timecode = demuxer->chapters[dvd_last_chapter-1].end;
2236 else if (dvd_last_chapter + 1 <= demuxer->num_chapters)
2237 mkv_d->stop_timecode = demuxer->chapters[dvd_last_chapter].start;
2241 if (s->end_pos == 0 || (mkv_d->indexes == NULL && index_mode < 0))
2242 demuxer->seekable = 0;
2243 else
2245 demuxer->movi_start = s->start_pos;
2246 demuxer->movi_end = s->end_pos;
2247 demuxer->seekable = 1;
2250 return DEMUXER_TYPE_MATROSKA;
2253 static void
2254 demux_close_mkv (demuxer_t *demuxer)
2256 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2258 if (mkv_d)
2260 int i;
2261 free_cached_dps (demuxer);
2262 if (mkv_d->tracks)
2264 for (i=0; i<mkv_d->num_tracks; i++)
2265 demux_mkv_free_trackentry(mkv_d->tracks[i]);
2266 free (mkv_d->tracks);
2268 free (mkv_d->indexes);
2269 free (mkv_d->cluster_positions);
2270 free (mkv_d->parsed_cues);
2271 free (mkv_d->parsed_seekhead);
2272 free (mkv_d);
2276 static int
2277 demux_mkv_read_block_lacing (uint8_t *buffer, uint64_t *size,
2278 uint8_t *laces, uint32_t **all_lace_sizes)
2280 uint32_t total = 0, *lace_size;
2281 uint8_t flags;
2282 int i;
2284 *all_lace_sizes = NULL;
2285 lace_size = NULL;
2286 /* lacing flags */
2287 flags = *buffer++;
2288 (*size)--;
2290 switch ((flags & 0x06) >> 1)
2292 case 0: /* no lacing */
2293 *laces = 1;
2294 lace_size = calloc(*laces, sizeof(uint32_t));
2295 lace_size[0] = *size;
2296 break;
2298 case 1: /* xiph lacing */
2299 case 2: /* fixed-size lacing */
2300 case 3: /* EBML lacing */
2301 *laces = *buffer++;
2302 (*size)--;
2303 (*laces)++;
2304 lace_size = calloc(*laces, sizeof(uint32_t));
2306 switch ((flags & 0x06) >> 1)
2308 case 1: /* xiph lacing */
2309 for (i=0; i < *laces-1; i++)
2311 lace_size[i] = 0;
2314 lace_size[i] += *buffer;
2315 (*size)--;
2316 } while (*buffer++ == 0xFF);
2317 total += lace_size[i];
2319 lace_size[i] = *size - total;
2320 break;
2322 case 2: /* fixed-size lacing */
2323 for (i=0; i < *laces; i++)
2324 lace_size[i] = *size / *laces;
2325 break;
2327 case 3: /* EBML lacing */
2329 int l;
2330 uint64_t num = ebml_read_vlen_uint (buffer, &l);
2331 if (num == EBML_UINT_INVALID) {
2332 free(lace_size);
2333 return 1;
2335 buffer += l;
2336 *size -= l;
2338 total = lace_size[0] = num;
2339 for (i=1; i < *laces-1; i++)
2341 int64_t snum;
2342 snum = ebml_read_vlen_int (buffer, &l);
2343 if (snum == EBML_INT_INVALID) {
2344 free(lace_size);
2345 return 1;
2347 buffer += l;
2348 *size -= l;
2349 lace_size[i] = lace_size[i-1] + snum;
2350 total += lace_size[i];
2352 lace_size[i] = *size - total;
2353 break;
2356 break;
2358 *all_lace_sizes = lace_size;
2359 return 0;
2362 static void
2363 handle_subtitles(demuxer_t *demuxer, mkv_track_t *track, char *block,
2364 int64_t size, uint64_t block_duration, uint64_t timecode)
2366 demux_packet_t *dp;
2368 if (block_duration == 0)
2370 mp_msg (MSGT_DEMUX, MSGL_WARN,
2371 MSGTR_MPDEMUX_MKV_NoBlockDurationForSubtitleTrackFound);
2372 return;
2375 sub_utf8 = 1;
2376 dp = new_demux_packet(size);
2377 memcpy(dp->buffer, block, size);
2378 dp->pts = timecode / 1000.0f;
2379 dp->endpts = (timecode + block_duration) / 1000.0f;
2380 ds_add_packet(demuxer->sub, dp);
2383 double real_fix_timestamp(unsigned char *buf, unsigned int timestamp, unsigned int format, int64_t *kf_base, int *kf_pts, double *pts);
2385 static void
2386 handle_realvideo (demuxer_t *demuxer, mkv_track_t *track, uint8_t *buffer,
2387 uint32_t size, int block_bref)
2389 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2390 demux_packet_t *dp;
2391 uint32_t timestamp = mkv_d->last_pts * 1000;
2393 dp = new_demux_packet (size);
2394 memcpy (dp->buffer, buffer, size);
2396 if (mkv_d->v_skip_to_keyframe)
2398 dp->pts = mkv_d->last_pts;
2399 track->rv_kf_base = 0;
2400 track->rv_kf_pts = timestamp;
2402 else
2403 dp->pts = real_fix_timestamp (dp->buffer, timestamp,
2404 ((sh_video_t*)demuxer->video->sh)->bih->biCompression,
2405 &track->rv_kf_base, &track->rv_kf_pts, NULL);
2406 dp->pos = demuxer->filepos;
2407 dp->flags = block_bref ? 0 : 0x10;
2409 ds_add_packet(demuxer->video, dp);
2412 static void
2413 handle_realaudio (demuxer_t *demuxer, mkv_track_t *track, uint8_t *buffer,
2414 uint32_t size, int block_bref)
2416 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2417 int sps = track->sub_packet_size;
2418 int sph = track->sub_packet_h;
2419 int cfs = track->coded_framesize;
2420 int w = track->audiopk_size;
2421 int spc = track->sub_packet_cnt;
2422 demux_packet_t *dp;
2423 int x;
2425 if ((track->a_formattag == mmioFOURCC('2', '8', '_', '8')) ||
2426 (track->a_formattag == mmioFOURCC('c', 'o', 'o', 'k')) ||
2427 (track->a_formattag == mmioFOURCC('a', 't', 'r', 'c')) ||
2428 (track->a_formattag == mmioFOURCC('s', 'i', 'p', 'r')))
2430 // if(!block_bref)
2431 // spc = track->sub_packet_cnt = 0;
2432 switch (track->a_formattag) {
2433 case mmioFOURCC('2', '8', '_', '8'):
2434 for (x = 0; x < sph / 2; x++)
2435 memcpy(track->audio_buf + x * 2 * w + spc * cfs, buffer + cfs * x, cfs);
2436 break;
2437 case mmioFOURCC('c', 'o', 'o', 'k'):
2438 case mmioFOURCC('a', 't', 'r', 'c'):
2439 for (x = 0; x < w / sps; x++)
2440 memcpy(track->audio_buf + sps * (sph * x + ((sph + 1) / 2) * (spc & 1) + (spc >> 1)), buffer + sps * x, sps);
2441 break;
2442 case mmioFOURCC('s', 'i', 'p', 'r'):
2443 memcpy(track->audio_buf + spc * w, buffer, w);
2444 if (spc == sph - 1)
2446 int n;
2447 int bs = sph * w * 2 / 96; // nibbles per subpacket
2448 // Perform reordering
2449 for(n=0; n < 38; n++)
2451 int j;
2452 int i = bs * sipr_swaps[n][0];
2453 int o = bs * sipr_swaps[n][1];
2454 // swap nibbles of block 'i' with 'o' TODO: optimize
2455 for(j = 0;j < bs; j++)
2457 int x = (i & 1) ? (track->audio_buf[i >> 1] >> 4) : (track->audio_buf[i >> 1] & 0x0F);
2458 int y = (o & 1) ? (track->audio_buf[o >> 1] >> 4) : (track->audio_buf[o >> 1] & 0x0F);
2459 if(o & 1)
2460 track->audio_buf[o >> 1] = (track->audio_buf[o >> 1] & 0x0F) | (x << 4);
2461 else
2462 track->audio_buf[o >> 1] = (track->audio_buf[o >> 1] & 0xF0) | x;
2463 if(i & 1)
2464 track->audio_buf[i >> 1] = (track->audio_buf[i >> 1] & 0x0F) | (y << 4);
2465 else
2466 track->audio_buf[i >> 1] = (track->audio_buf[i >> 1] & 0xF0) | y;
2467 ++i; ++o;
2471 break;
2473 track->audio_timestamp[track->sub_packet_cnt] = (track->ra_pts == mkv_d->last_pts) ? 0 : (mkv_d->last_pts);
2474 track->ra_pts = mkv_d->last_pts;
2475 if (track->sub_packet_cnt == 0)
2476 track->audio_filepos = demuxer->filepos;
2477 if (++(track->sub_packet_cnt) == sph)
2479 int apk_usize = ((WAVEFORMATEX*)((sh_audio_t*)demuxer->audio->sh)->wf)->nBlockAlign;
2480 track->sub_packet_cnt = 0;
2481 // Release all the audio packets
2482 for (x = 0; x < sph*w/apk_usize; x++)
2484 dp = new_demux_packet(apk_usize);
2485 memcpy(dp->buffer, track->audio_buf + x * apk_usize, apk_usize);
2486 /* Put timestamp only on packets that correspond to original audio packets in file */
2487 dp->pts = (x * apk_usize % w) ? 0 : track->audio_timestamp[x * apk_usize / w];
2488 dp->pos = track->audio_filepos; // all equal
2489 dp->flags = x ? 0 : 0x10; // Mark first packet as keyframe
2490 ds_add_packet(demuxer->audio, dp);
2493 } else { // Not a codec that require reordering
2494 dp = new_demux_packet (size);
2495 memcpy(dp->buffer, buffer, size);
2496 if (track->ra_pts == mkv_d->last_pts && !mkv_d->a_skip_to_keyframe)
2497 dp->pts = 0;
2498 else
2499 dp->pts = mkv_d->last_pts;
2500 track->ra_pts = mkv_d->last_pts;
2502 dp->pos = demuxer->filepos;
2503 dp->flags = block_bref ? 0 : 0x10;
2504 ds_add_packet (demuxer->audio, dp);
2508 /** Reorder timecodes and add cached demux packets to the queues.
2510 * Timecode reordering is needed if a video track contains B frames that
2511 * are timestamped in display order (e.g. MPEG-1, MPEG-2 or "native" MPEG-4).
2512 * MPlayer doesn't like timestamps in display order. This function adjusts
2513 * the timestamp of cached frames (which are exactly one I/P frame followed
2514 * by one or more B frames) so that they are in coding order again.
2516 * Example: The track with 25 FPS contains four frames with the timecodes
2517 * I at 0ms, P at 120ms, B at 40ms and B at 80ms. As soon as the next I
2518 * or P frame arrives these timecodes can be changed to I at 0ms, P at 40ms,
2519 * B at 80ms and B at 120ms.
2521 * This works for simple H.264 B-frame pyramids, but not for arbitrary orders.
2523 * \param demuxer The Matroska demuxer struct for this instance.
2524 * \param track The track structure whose cache should be handled.
2526 static void
2527 flush_cached_dps (demuxer_t *demuxer, mkv_track_t *track)
2529 int i, ok;
2531 if (track->num_cached_dps == 0)
2532 return;
2534 do {
2535 ok = 1;
2536 for (i = 1; i < track->num_cached_dps; i++)
2537 if (track->cached_dps[i - 1]->pts > track->cached_dps[i]->pts) {
2538 float tmp_pts = track->cached_dps[i - 1]->pts;
2539 track->cached_dps[i - 1]->pts = track->cached_dps[i]->pts;
2540 track->cached_dps[i]->pts = tmp_pts;
2541 ok = 0;
2543 } while (!ok);
2545 for (i = 0; i < track->num_cached_dps; i++)
2546 ds_add_packet (demuxer->video, track->cached_dps[i]);
2547 track->num_cached_dps = 0;
2550 /** Cache video frames if timecodes have to be reordered.
2552 * Timecode reordering is needed if a video track contains B frames that
2553 * are timestamped in display order (e.g. MPEG-1, MPEG-2 or "native" MPEG-4).
2554 * This function takes in a Matroska block read from the file, allocates a
2555 * demux packet for it, fills in its values, allocates space for storing
2556 * pointers to the cached demux packets and adds the packet to it. If
2557 * the packet contains an I or a P frame then ::flush_cached_dps is called
2558 * in order to send the old cached frames downstream.
2560 * \param demuxer The Matroska demuxer struct for this instance.
2561 * \param track The packet is meant for this track.
2562 * \param buffer The actual frame contents.
2563 * \param size The frame size in bytes.
2564 * \param block_bref A relative timecode (backward reference). If it is \c 0
2565 * then the frame is an I frame.
2566 * \param block_fref A relative timecode (forward reference). If it is \c 0
2567 * then the frame is either an I frame or a P frame depending on the value
2568 * of \a block_bref. Otherwise it's a B frame.
2570 static void
2571 handle_video_bframes (demuxer_t *demuxer, mkv_track_t *track, uint8_t *buffer,
2572 uint32_t size, int block_bref, int block_fref)
2574 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2575 demux_packet_t *dp;
2577 dp = new_demux_packet (size);
2578 memcpy(dp->buffer, buffer, size);
2579 dp->pos = demuxer->filepos;
2580 dp->pts = mkv_d->last_pts;
2581 if ((track->num_cached_dps > 0) && (dp->pts < track->max_pts))
2582 block_fref = 1;
2583 if (block_fref == 0) /* I or P frame */
2584 flush_cached_dps (demuxer, track);
2585 if (block_bref != 0) /* I frame, don't cache it */
2586 dp->flags = 0x10;
2587 if ((track->num_cached_dps + 1) > track->num_allocated_dps)
2589 track->cached_dps = (demux_packet_t **)
2590 realloc(track->cached_dps, (track->num_cached_dps + 10) *
2591 sizeof(demux_packet_t *));
2592 track->num_allocated_dps += 10;
2594 track->cached_dps[track->num_cached_dps] = dp;
2595 track->num_cached_dps++;
2596 if (dp->pts > track->max_pts)
2597 track->max_pts = dp->pts;
2600 static int
2601 handle_block (demuxer_t *demuxer, uint8_t *block, uint64_t length,
2602 uint64_t block_duration, int64_t block_bref, int64_t block_fref, uint8_t simpleblock)
2604 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2605 mkv_track_t *track = NULL;
2606 demux_stream_t *ds = NULL;
2607 uint64_t old_length;
2608 int64_t tc;
2609 uint32_t *lace_size;
2610 uint8_t laces, flags;
2611 int i, num, tmp, use_this_block = 1;
2612 float current_pts;
2613 int16_t time;
2615 /* first byte(s): track num */
2616 num = ebml_read_vlen_uint (block, &tmp);
2617 block += tmp;
2618 /* time (relative to cluster time) */
2619 time = block[0] << 8 | block[1];
2620 block += 2;
2621 length -= tmp + 2;
2622 old_length = length;
2623 flags = block[0];
2624 if (demux_mkv_read_block_lacing (block, &length, &laces, &lace_size))
2625 return 0;
2626 block += old_length - length;
2628 tc = ((time*mkv_d->tc_scale+mkv_d->cluster_tc) /1000000.0 - mkv_d->first_tc);
2629 if (tc < 0)
2630 tc = 0;
2631 if (mkv_d->stop_timecode > 0 && tc > mkv_d->stop_timecode) {
2632 free(lace_size);
2633 return -1;
2635 current_pts = tc / 1000.0;
2637 for (i=0; i<mkv_d->num_tracks; i++)
2638 if (mkv_d->tracks[i]->tnum == num) {
2639 track = mkv_d->tracks[i];
2640 break;
2642 if (track == NULL)
2644 free(lace_size);
2645 return 1;
2647 if (num == demuxer->audio->id)
2649 ds = demuxer->audio;
2651 if (mkv_d->a_skip_to_keyframe)
2653 if (simpleblock)
2655 if (!(flags&0x80)) /*current frame isn't a keyframe*/
2656 use_this_block = 0;
2658 else if (block_bref != 0)
2659 use_this_block = 0;
2661 else if (mkv_d->v_skip_to_keyframe)
2662 use_this_block = 0;
2664 if (track->fix_i_bps && use_this_block)
2666 sh_audio_t *sh = (sh_audio_t *) ds->sh;
2668 if (block_duration != 0)
2670 sh->i_bps = length * 1000 / block_duration;
2671 track->fix_i_bps = 0;
2673 else if (track->qt_last_a_pts == 0.0)
2674 track->qt_last_a_pts = current_pts;
2675 else if(track->qt_last_a_pts != current_pts)
2677 sh->i_bps = length / (current_pts - track->qt_last_a_pts);
2678 track->fix_i_bps = 0;
2682 else if (tc < mkv_d->skip_to_timecode)
2683 use_this_block = 0;
2684 else if (num == demuxer->video->id)
2686 ds = demuxer->video;
2687 if (mkv_d->v_skip_to_keyframe)
2689 if (simpleblock)
2691 if (!(flags&0x80)) /*current frame isn't a keyframe*/
2692 use_this_block = 0;
2694 else if (block_bref != 0 || block_fref != 0)
2695 use_this_block = 0;
2698 else if (num == demuxer->sub->id)
2700 ds = demuxer->sub;
2701 if (track->subtitle_type != MATROSKA_SUBTYPE_VOBSUB)
2703 if (!mkv_d->v_skip_to_keyframe)
2704 handle_subtitles (demuxer, track, block, length,
2705 block_duration, tc);
2706 use_this_block = 0;
2709 else
2710 use_this_block = 0;
2712 if (use_this_block)
2714 mkv_d->last_pts = current_pts;
2715 mkv_d->last_filepos = demuxer->filepos;
2717 for (i=0; i < laces; i++)
2719 if (ds == demuxer->video && track->realmedia)
2720 handle_realvideo (demuxer, track, block, lace_size[i], block_bref);
2721 else if (ds == demuxer->audio && track->realmedia)
2722 handle_realaudio (demuxer, track, block, lace_size[i], block_bref);
2723 else if (ds == demuxer->video && track->reorder_timecodes)
2724 handle_video_bframes (demuxer, track, block, lace_size[i],
2725 block_bref, block_fref);
2726 else
2728 int modified, size = lace_size[i];
2729 demux_packet_t *dp;
2730 uint8_t *buffer;
2731 modified = demux_mkv_decode (track, block, &buffer, &size, 1);
2732 if (buffer)
2734 dp = new_demux_packet (size);
2735 memcpy (dp->buffer, buffer, size);
2736 if (modified)
2737 free (buffer);
2738 dp->flags = (block_bref == 0 && block_fref == 0) ? 0x10 : 0;
2739 /* If default_duration is 0, assume no pts value is known
2740 * for packets after the first one (rather than all pts
2741 * values being the same) */
2742 if (i == 0 || track->default_duration)
2743 dp->pts = mkv_d->last_pts + i * track->default_duration;
2744 ds_add_packet (ds, dp);
2747 block += lace_size[i];
2750 if (ds == demuxer->video)
2752 mkv_d->v_skip_to_keyframe = 0;
2753 mkv_d->skip_to_timecode = 0;
2755 else if (ds == demuxer->audio)
2756 mkv_d->a_skip_to_keyframe = 0;
2758 free(lace_size);
2759 return 1;
2762 free(lace_size);
2763 return 0;
2766 static int
2767 demux_mkv_fill_buffer (demuxer_t *demuxer, demux_stream_t *ds)
2769 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2770 stream_t *s = demuxer->stream;
2771 uint64_t l;
2772 int il, tmp;
2774 while (1)
2776 while (mkv_d->cluster_size > 0)
2778 uint64_t block_duration = 0, block_length = 0;
2779 int64_t block_bref = 0, block_fref = 0;
2780 uint8_t *block = NULL;
2782 while (mkv_d->blockgroup_size > 0)
2784 switch (ebml_read_id (s, &il))
2786 case MATROSKA_ID_BLOCKDURATION:
2788 block_duration = ebml_read_uint (s, &l);
2789 if (block_duration == EBML_UINT_INVALID) {
2790 free(block);
2791 return 0;
2793 block_duration *= mkv_d->tc_scale / 1000000.0;
2794 break;
2797 case MATROSKA_ID_BLOCK:
2798 block_length = ebml_read_length (s, &tmp);
2799 free(block);
2800 if (block_length > SIZE_MAX - AV_LZO_INPUT_PADDING) return 0;
2801 block = malloc (block_length + AV_LZO_INPUT_PADDING);
2802 demuxer->filepos = stream_tell (s);
2803 if (stream_read (s,block,block_length) != (int) block_length)
2805 free(block);
2806 return 0;
2808 l = tmp + block_length;
2809 break;
2811 case MATROSKA_ID_REFERENCEBLOCK:
2813 int64_t num = ebml_read_int (s, &l);
2814 if (num == EBML_INT_INVALID) {
2815 free(block);
2816 return 0;
2818 if (num <= 0)
2819 block_bref = num;
2820 else
2821 block_fref = num;
2822 break;
2825 case EBML_ID_INVALID:
2826 free(block);
2827 return 0;
2829 default:
2830 ebml_read_skip (s, &l);
2831 break;
2833 mkv_d->blockgroup_size -= l + il;
2834 mkv_d->cluster_size -= l + il;
2837 if (block)
2839 int res = handle_block (demuxer, block, block_length,
2840 block_duration, block_bref, block_fref, 0);
2841 free (block);
2842 if (res < 0)
2843 return 0;
2844 if (res)
2845 return 1;
2848 if (mkv_d->cluster_size > 0)
2850 switch (ebml_read_id (s, &il))
2852 case MATROSKA_ID_CLUSTERTIMECODE:
2854 uint64_t num = ebml_read_uint (s, &l);
2855 if (num == EBML_UINT_INVALID)
2856 return 0;
2857 if (!mkv_d->has_first_tc)
2859 mkv_d->first_tc = num * mkv_d->tc_scale / 1000000.0;
2860 mkv_d->has_first_tc = 1;
2862 mkv_d->cluster_tc = num * mkv_d->tc_scale;
2863 break;
2866 case MATROSKA_ID_BLOCKGROUP:
2867 mkv_d->blockgroup_size = ebml_read_length (s, &tmp);
2868 l = tmp;
2869 break;
2871 case MATROSKA_ID_SIMPLEBLOCK:
2873 int res;
2874 block_length = ebml_read_length (s, &tmp);
2875 block = malloc (block_length);
2876 demuxer->filepos = stream_tell (s);
2877 if (stream_read (s,block,block_length) != (int) block_length)
2879 free(block);
2880 return 0;
2882 l = tmp + block_length;
2883 res = handle_block (demuxer, block, block_length,
2884 block_duration, block_bref, block_fref, 1);
2885 free (block);
2886 mkv_d->cluster_size -= l + il;
2887 if (res < 0)
2888 return 0;
2889 else if (res)
2890 return 1;
2891 else mkv_d->cluster_size += l + il;
2892 break;
2894 case EBML_ID_INVALID:
2895 return 0;
2897 default:
2898 ebml_read_skip (s, &l);
2899 break;
2901 mkv_d->cluster_size -= l + il;
2905 if (ebml_read_id (s, &il) != MATROSKA_ID_CLUSTER)
2906 return 0;
2907 add_cluster_position(mkv_d, stream_tell(s)-il);
2908 mkv_d->cluster_size = ebml_read_length (s, NULL);
2911 return 0;
2914 static void
2915 demux_mkv_seek (demuxer_t *demuxer, float rel_seek_secs, float audio_delay, int flags)
2917 free_cached_dps (demuxer);
2918 if (!(flags & SEEK_FACTOR)) /* time in secs */
2920 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2921 stream_t *s = demuxer->stream;
2922 int64_t target_timecode = 0, diff, min_diff=0xFFFFFFFFFFFFFFFLL;
2923 int i;
2925 if (!(flags & SEEK_ABSOLUTE)) /* relative seek */
2926 target_timecode = (int64_t) (mkv_d->last_pts * 1000.0);
2927 target_timecode += (int64_t)(rel_seek_secs * 1000.0);
2928 if (target_timecode < 0)
2929 target_timecode = 0;
2931 if (mkv_d->indexes == NULL) /* no index was found */
2933 uint64_t target_filepos, cluster_pos, max_pos;
2935 target_filepos = (uint64_t) (target_timecode * mkv_d->last_filepos
2936 / (mkv_d->last_pts * 1000.0));
2938 max_pos = mkv_d->cluster_positions[mkv_d->num_cluster_pos-1];
2939 if (target_filepos > max_pos)
2941 if ((off_t) max_pos > stream_tell (s))
2942 stream_seek (s, max_pos);
2943 else
2944 stream_seek (s, stream_tell (s) + mkv_d->cluster_size);
2945 /* parse all the clusters upto target_filepos */
2946 while (!s->eof && stream_tell(s) < (off_t) target_filepos)
2948 switch (ebml_read_id (s, &i))
2950 case MATROSKA_ID_CLUSTER:
2951 add_cluster_position(mkv_d, (uint64_t) stream_tell(s)-i);
2952 break;
2954 case MATROSKA_ID_CUES:
2955 demux_mkv_read_cues (demuxer);
2956 break;
2958 ebml_read_skip (s, NULL);
2960 if (s->eof)
2961 stream_reset(s);
2964 if (mkv_d->indexes == NULL)
2966 cluster_pos = mkv_d->cluster_positions[0];
2967 /* Let's find the nearest cluster */
2968 for (i=0; i < mkv_d->num_cluster_pos; i++)
2970 diff = mkv_d->cluster_positions[i] - target_filepos;
2971 if (rel_seek_secs < 0 && diff < 0 && -diff < min_diff)
2973 cluster_pos = mkv_d->cluster_positions[i];
2974 min_diff = -diff;
2976 else if (rel_seek_secs > 0
2977 && (diff < 0 ? -1 * diff : diff) < min_diff)
2979 cluster_pos = mkv_d->cluster_positions[i];
2980 min_diff = diff < 0 ? -1 * diff : diff;
2983 mkv_d->cluster_size = mkv_d->blockgroup_size = 0;
2984 stream_seek (s, cluster_pos);
2987 else
2989 mkv_index_t *index = NULL;
2990 int seek_id = (demuxer->video->id < 0) ? demuxer->audio->id : demuxer->video->id;
2992 /* let's find the entry in the indexes with the smallest */
2993 /* difference to the wanted timecode. */
2994 for (i=0; i < mkv_d->num_indexes; i++)
2995 if (mkv_d->indexes[i].tnum == seek_id)
2997 diff = target_timecode + mkv_d->first_tc -
2998 (int64_t) mkv_d->indexes[i].timecode * mkv_d->tc_scale / 1000000.0;
3000 if ((flags & SEEK_ABSOLUTE || target_timecode <= mkv_d->last_pts*1000)) {
3001 // Absolute seek or seek backward: find the last index
3002 // position before target time
3003 if (diff < 0 || diff >= min_diff)
3004 continue;
3006 else {
3007 // Relative seek forward: find the first index position
3008 // after target time. If no such index exists, find last
3009 // position between current position and target time.
3010 if (diff <= 0) {
3011 if (min_diff <= 0 && diff <= min_diff)
3012 continue;
3014 else if (diff >= FFMIN(target_timecode - mkv_d->last_pts,
3015 min_diff))
3016 continue;
3018 min_diff = diff;
3019 index = mkv_d->indexes + i;
3022 if (index) /* We've found an entry. */
3024 mkv_d->cluster_size = mkv_d->blockgroup_size = 0;
3025 stream_seek (s, index->filepos);
3029 if (demuxer->video->id >= 0)
3030 mkv_d->v_skip_to_keyframe = 1;
3031 if (rel_seek_secs > 0.0)
3032 mkv_d->skip_to_timecode = target_timecode;
3033 mkv_d->a_skip_to_keyframe = 1;
3035 demux_mkv_fill_buffer(demuxer, NULL);
3037 else if ((demuxer->movi_end <= 0) || !(flags & SEEK_ABSOLUTE))
3038 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] seek unsupported flags\n");
3039 else
3041 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
3042 stream_t *s = demuxer->stream;
3043 uint64_t target_filepos;
3044 mkv_index_t *index = NULL;
3045 int i;
3047 if (mkv_d->indexes == NULL) /* no index was found */
3048 { /* I'm lazy... */
3049 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] seek unsupported flags\n");
3050 return;
3053 target_filepos = (uint64_t)(demuxer->movi_end * rel_seek_secs);
3054 for (i=0; i < mkv_d->num_indexes; i++)
3055 if (mkv_d->indexes[i].tnum == demuxer->video->id)
3056 if ((index == NULL) ||
3057 ((mkv_d->indexes[i].filepos >= target_filepos) &&
3058 ((index->filepos < target_filepos) ||
3059 (mkv_d->indexes[i].filepos < index->filepos))))
3060 index = &mkv_d->indexes[i];
3062 if (!index)
3063 return;
3065 mkv_d->cluster_size = mkv_d->blockgroup_size = 0;
3066 stream_seek (s, index->filepos);
3068 if (demuxer->video->id >= 0)
3069 mkv_d->v_skip_to_keyframe = 1;
3070 mkv_d->skip_to_timecode = index->timecode;
3071 mkv_d->a_skip_to_keyframe = 1;
3073 demux_mkv_fill_buffer(demuxer, NULL);
3077 static int
3078 demux_mkv_control (demuxer_t *demuxer, int cmd, void *arg)
3080 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
3082 switch (cmd)
3084 case DEMUXER_CTRL_CORRECT_PTS:
3085 return DEMUXER_CTRL_OK;
3086 case DEMUXER_CTRL_GET_TIME_LENGTH:
3087 if (mkv_d->duration == 0)
3088 return DEMUXER_CTRL_DONTKNOW;
3090 *((double *)arg) = (double)mkv_d->duration;
3091 return DEMUXER_CTRL_OK;
3093 case DEMUXER_CTRL_GET_PERCENT_POS:
3094 if (mkv_d->duration == 0)
3096 return DEMUXER_CTRL_DONTKNOW;
3099 *((int *) arg) = (int) (100 * mkv_d->last_pts / mkv_d->duration);
3100 return DEMUXER_CTRL_OK;
3102 case DEMUXER_CTRL_SWITCH_AUDIO:
3103 if (demuxer->audio && demuxer->audio->sh) {
3104 sh_audio_t *sh = demuxer->a_streams[demuxer->audio->id];
3105 int aid = *(int*)arg;
3106 if (aid < 0)
3107 aid = (sh->aid + 1) % mkv_d->last_aid;
3108 if (aid != sh->aid) {
3109 mkv_track_t *track = demux_mkv_find_track_by_num (mkv_d, aid, MATROSKA_TRACK_AUDIO);
3110 if (track) {
3111 demuxer->audio->id = track->tnum;
3112 sh = demuxer->a_streams[demuxer->audio->id];
3113 ds_free_packs(demuxer->audio);
3116 *(int*)arg = sh->aid;
3117 } else
3118 *(int*)arg = -2;
3119 return DEMUXER_CTRL_OK;
3121 default:
3122 return DEMUXER_CTRL_NOTIMPL;
3126 const demuxer_desc_t demuxer_desc_matroska = {
3127 "Matroska demuxer",
3128 "mkv",
3129 "Matroska",
3130 "Aurelien Jacobs",
3132 DEMUXER_TYPE_MATROSKA,
3133 1, // safe autodetect
3134 demux_mkv_open,
3135 demux_mkv_fill_buffer,
3136 NULL,
3137 demux_close_mkv,
3138 demux_mkv_seek,
3139 demux_mkv_control