ati_hack only makes sense when PBOs are used, not with mesa_buffer.
[mplayer/glamo.git] / libmpdemux / demux_mkv.c
blobb63f466e8655de8f477b9a773e21cd4cfa5e01ff
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 #ifdef 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 int rv_kf_base, rv_kf_pts;
102 float rv_pts; /* previous video timestamp */
103 float ra_pts; /* previous audio timestamp */
105 /** realaudio descrambling */
106 int sub_packet_size; ///< sub packet size, per stream
107 int sub_packet_h; ///< number of coded frames per block
108 int coded_framesize; ///< coded frame size, per stream
109 int audiopk_size; ///< audio packet size
110 unsigned char *audio_buf; ///< place to store reordered audio data
111 float *audio_timestamp; ///< timestamp for each audio packet
112 int sub_packet_cnt; ///< number of subpacket already received
113 int audio_filepos; ///< file position of first audio packet in block
115 /* stuff for quicktime */
116 int fix_i_bps;
117 float qt_last_a_pts;
119 int subtitle_type;
121 /* The timecodes of video frames might have to be reordered if they're
122 in display order (the timecodes, not the frames themselves!). In this
123 case demux packets have to be cached with the help of these variables. */
124 int reorder_timecodes;
125 demux_packet_t **cached_dps;
126 int num_cached_dps, num_allocated_dps;
127 float max_pts;
129 /* generic content encoding support */
130 mkv_content_encoding_t *encodings;
131 int num_encodings;
133 /* For VobSubs and SSA/ASS */
134 sh_sub_t *sh_sub;
135 } mkv_track_t;
137 typedef struct mkv_index
139 int tnum;
140 uint64_t timecode, filepos;
141 } mkv_index_t;
143 typedef struct mkv_demuxer
145 off_t segment_start;
147 float duration, last_pts;
148 uint64_t last_filepos;
150 mkv_track_t **tracks;
151 int num_tracks;
153 uint64_t tc_scale, cluster_tc, first_tc;
154 int has_first_tc;
156 uint64_t cluster_size;
157 uint64_t blockgroup_size;
159 mkv_index_t *indexes;
160 int num_indexes;
162 off_t *parsed_cues;
163 int parsed_cues_num;
164 off_t *parsed_seekhead;
165 int parsed_seekhead_num;
167 uint64_t *cluster_positions;
168 int num_cluster_pos;
170 int64_t skip_to_timecode;
171 int v_skip_to_keyframe, a_skip_to_keyframe;
173 int64_t stop_timecode;
175 int last_aid;
176 int audio_tracks[MAX_A_STREAMS];
177 } mkv_demuxer_t;
179 #define REALHEADER_SIZE 16
180 #define RVPROPERTIES_SIZE 34
181 #define RAPROPERTIES4_SIZE 56
182 #define RAPROPERTIES5_SIZE 70
184 /* for e.g. "-slang ger" */
185 extern char *dvdsub_lang;
186 extern char *audio_lang;
187 extern int dvdsub_id;
190 * \brief ensures there is space for at least one additional element
191 * \param array array to grow
192 * \param nelem current number of elements in array
193 * \param elsize size of one array element
195 static void grow_array(void **array, int nelem, size_t elsize) {
196 if (!(nelem & 31))
197 *array = realloc(*array, (nelem + 32) * elsize);
200 static mkv_track_t *
201 demux_mkv_find_track_by_num (mkv_demuxer_t *d, int n, int type)
203 int i, id;
205 for (i=0, id=0; i < d->num_tracks; i++)
206 if (d->tracks[i] != NULL && d->tracks[i]->type == type)
207 if (id++ == n)
208 return d->tracks[i];
210 return NULL;
213 static void
214 add_cluster_position (mkv_demuxer_t *mkv_d, uint64_t position)
216 int i = mkv_d->num_cluster_pos;
218 while (i--)
219 if (mkv_d->cluster_positions[i] == position)
220 return;
222 grow_array(&mkv_d->cluster_positions, mkv_d->num_cluster_pos,
223 sizeof(uint64_t));
224 mkv_d->cluster_positions[mkv_d->num_cluster_pos++] = position;
228 #define AAC_SYNC_EXTENSION_TYPE 0x02b7
229 static int
230 aac_get_sample_rate_index (uint32_t sample_rate)
232 if (92017 <= sample_rate)
233 return 0;
234 else if (75132 <= sample_rate)
235 return 1;
236 else if (55426 <= sample_rate)
237 return 2;
238 else if (46009 <= sample_rate)
239 return 3;
240 else if (37566 <= sample_rate)
241 return 4;
242 else if (27713 <= sample_rate)
243 return 5;
244 else if (23004 <= sample_rate)
245 return 6;
246 else if (18783 <= sample_rate)
247 return 7;
248 else if (13856 <= sample_rate)
249 return 8;
250 else if (11502 <= sample_rate)
251 return 9;
252 else if (9391 <= sample_rate)
253 return 10;
254 else
255 return 11;
258 /** \brief Free cached demux packets
260 * Reordering the timecodes requires caching of demux packets. This function
261 * frees all these cached packets and the memory for the cached pointers
262 * itself.
264 * \param demuxer The demuxer for which the cache is to be freed.
266 static void
267 free_cached_dps (demuxer_t *demuxer)
269 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
270 mkv_track_t *track;
271 int i, k;
273 for (k = 0; k < mkv_d->num_tracks; k++)
275 track = mkv_d->tracks[k];
276 for (i = 0; i < track->num_cached_dps; i++)
277 free_demux_packet (track->cached_dps[i]);
278 free(track->cached_dps);
279 track->cached_dps = NULL;
280 track->num_cached_dps = 0;
281 track->num_allocated_dps = 0;
282 track->max_pts = 0;
286 static int
287 demux_mkv_decode (mkv_track_t *track, uint8_t *src, uint8_t **dest,
288 uint32_t *size, uint32_t type)
290 int i, result;
291 int modified = 0;
293 *dest = src;
294 if (track->num_encodings <= 0)
295 return 0;
297 for (i=0; i<track->num_encodings; i++)
299 if (!(track->encodings[i].scope & type))
300 continue;
302 #ifdef CONFIG_ZLIB
303 if (track->encodings[i].comp_algo == 0)
305 /* zlib encoded track */
306 z_stream zstream;
308 zstream.zalloc = (alloc_func) 0;
309 zstream.zfree = (free_func) 0;
310 zstream.opaque = (voidpf) 0;
311 if (inflateInit (&zstream) != Z_OK)
313 mp_msg (MSGT_DEMUX, MSGL_WARN,
314 MSGTR_MPDEMUX_MKV_ZlibInitializationFailed);
315 return modified;
317 zstream.next_in = (Bytef *) src;
318 zstream.avail_in = *size;
320 modified = 1;
321 *dest = NULL;
322 zstream.avail_out = *size;
323 do {
324 *size += 4000;
325 *dest = realloc (*dest, *size);
326 zstream.next_out = (Bytef *) (*dest + zstream.total_out);
327 result = inflate (&zstream, Z_NO_FLUSH);
328 if (result != Z_OK && result != Z_STREAM_END)
330 mp_msg (MSGT_DEMUX, MSGL_WARN,
331 MSGTR_MPDEMUX_MKV_ZlibDecompressionFailed);
332 free(*dest);
333 *dest = NULL;
334 inflateEnd (&zstream);
335 return modified;
337 zstream.avail_out += 4000;
338 } while (zstream.avail_out == 4000 &&
339 zstream.avail_in != 0 && result != Z_STREAM_END);
341 *size = zstream.total_out;
342 inflateEnd (&zstream);
344 #endif
345 if (track->encodings[i].comp_algo == 2)
347 /* lzo encoded track */
348 int dstlen = *size * 3;
350 *dest = NULL;
351 while (1)
353 int srclen = *size;
354 if (dstlen > SIZE_MAX - LZO_OUTPUT_PADDING) goto lzo_fail;
355 *dest = realloc (*dest, dstlen + LZO_OUTPUT_PADDING);
356 result = lzo1x_decode (*dest, &dstlen, src, &srclen);
357 if (result == 0)
358 break;
359 if (!(result & LZO_OUTPUT_FULL))
361 lzo_fail:
362 mp_msg (MSGT_DEMUX, MSGL_WARN,
363 MSGTR_MPDEMUX_MKV_LzoDecompressionFailed);
364 free(*dest);
365 *dest = NULL;
366 return modified;
368 mp_msg (MSGT_DEMUX, MSGL_DBG2,
369 "[mkv] lzo decompression buffer too small.\n");
370 dstlen *= 2;
372 *size = dstlen;
376 return modified;
380 static int
381 demux_mkv_read_info (demuxer_t *demuxer)
383 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
384 stream_t *s = demuxer->stream;
385 uint64_t length, l;
386 int il;
387 uint64_t tc_scale = 1000000;
388 long double duration = 0.;
390 length = ebml_read_length (s, NULL);
391 while (length > 0)
393 switch (ebml_read_id (s, &il))
395 case MATROSKA_ID_TIMECODESCALE:
397 uint64_t num = ebml_read_uint (s, &l);
398 if (num == EBML_UINT_INVALID)
399 return 1;
400 tc_scale = num;
401 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + timecode scale: %"PRIu64"\n",
402 tc_scale);
403 break;
406 case MATROSKA_ID_DURATION:
408 long double num = ebml_read_float (s, &l);
409 if (num == EBML_FLOAT_INVALID)
410 return 1;
411 duration = num;
412 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + duration: %.3Lfs\n",
413 duration * tc_scale / 1000000000.0);
414 break;
417 default:
418 ebml_read_skip (s, &l);
419 break;
421 length -= l + il;
423 mkv_d->tc_scale = tc_scale;
424 mkv_d->duration = duration * tc_scale / 1000000000.0;
425 return 0;
429 * \brief free array of kv_content_encoding_t
430 * \param encodings pointer to array
431 * \param numencodings number of encodings in array
433 static void
434 demux_mkv_free_encodings(mkv_content_encoding_t *encodings, int numencodings)
436 while (numencodings-- > 0)
437 free(encodings[numencodings].comp_settings);
438 free(encodings);
441 static int
442 demux_mkv_read_trackencodings (demuxer_t *demuxer, mkv_track_t *track)
444 stream_t *s = demuxer->stream;
445 mkv_content_encoding_t *ce, e;
446 uint64_t len, length, l;
447 int il, n;
449 ce = malloc (sizeof (*ce));
450 n = 0;
452 len = length = ebml_read_length (s, &il);
453 len += il;
454 while (length > 0)
456 switch (ebml_read_id (s, &il))
458 case MATROSKA_ID_CONTENTENCODING:
460 uint64_t len;
461 int i;
463 memset (&e, 0, sizeof (e));
464 e.scope = 1;
466 len = ebml_read_length (s, &i);
467 l = len + i;
469 while (len > 0)
471 uint64_t num, l;
472 int il;
474 switch (ebml_read_id (s, &il))
476 case MATROSKA_ID_CONTENTENCODINGORDER:
477 num = ebml_read_uint (s, &l);
478 if (num == EBML_UINT_INVALID)
479 goto err_out;
480 e.order = num;
481 break;
483 case MATROSKA_ID_CONTENTENCODINGSCOPE:
484 num = ebml_read_uint (s, &l);
485 if (num == EBML_UINT_INVALID)
486 goto err_out;
487 e.scope = num;
488 break;
490 case MATROSKA_ID_CONTENTENCODINGTYPE:
491 num = ebml_read_uint (s, &l);
492 if (num == EBML_UINT_INVALID)
493 goto err_out;
494 e.type = num;
495 break;
497 case MATROSKA_ID_CONTENTCOMPRESSION:
499 uint64_t le;
501 le = ebml_read_length (s, &i);
502 l = le + i;
504 while (le > 0)
506 uint64_t l;
507 int il;
509 switch (ebml_read_id (s, &il))
511 case MATROSKA_ID_CONTENTCOMPALGO:
512 num = ebml_read_uint (s, &l);
513 if (num == EBML_UINT_INVALID)
514 goto err_out;
515 e.comp_algo = num;
516 break;
518 case MATROSKA_ID_CONTENTCOMPSETTINGS:
519 l = ebml_read_length (s, &i);
520 e.comp_settings = malloc (l);
521 stream_read (s, e.comp_settings, l);
522 e.comp_settings_len = l;
523 l += i;
524 break;
526 default:
527 ebml_read_skip (s, &l);
528 break;
530 le -= l + il;
533 if (e.type == 1)
535 mp_msg(MSGT_DEMUX, MSGL_WARN,
536 MSGTR_MPDEMUX_MKV_TrackEncrypted, track->tnum);
538 else if (e.type != 0)
540 mp_msg(MSGT_DEMUX, MSGL_WARN,
541 MSGTR_MPDEMUX_MKV_UnknownContentEncoding, track->tnum);
544 if (e.comp_algo != 0 && e.comp_algo != 2)
546 mp_msg (MSGT_DEMUX, MSGL_WARN,
547 MSGTR_MPDEMUX_MKV_UnknownCompression,
548 track->tnum, e.comp_algo);
550 #ifndef CONFIG_ZLIB
551 else if (e.comp_algo == 0)
553 mp_msg (MSGT_DEMUX, MSGL_WARN,
554 MSGTR_MPDEMUX_MKV_ZlibCompressionUnsupported,
555 track->tnum);
557 #endif
559 break;
562 default:
563 ebml_read_skip (s, &l);
564 break;
566 len -= l + il;
568 for (i=0; i<n; i++)
569 if (e.order <= ce[i].order)
570 break;
571 ce = realloc (ce, (n+1) *sizeof (*ce));
572 memmove (ce+i+1, ce+i, (n-i) * sizeof (*ce));
573 memcpy (ce+i, &e, sizeof (e));
574 n++;
575 break;
578 default:
579 ebml_read_skip (s, &l);
580 break;
583 length -= l + il;
586 track->encodings = ce;
587 track->num_encodings = n;
588 return len;
590 err_out:
591 demux_mkv_free_encodings(ce, n);
592 return 0;
595 static int
596 demux_mkv_read_trackaudio (demuxer_t *demuxer, mkv_track_t *track)
598 stream_t *s = demuxer->stream;
599 uint64_t len, length, l;
600 int il;
602 track->a_sfreq = 8000.0;
603 track->a_channels = 1;
605 len = length = ebml_read_length (s, &il);
606 len += il;
607 while (length > 0)
609 switch (ebml_read_id (s, &il))
611 case MATROSKA_ID_AUDIOSAMPLINGFREQ:
613 long double num = ebml_read_float (s, &l);
614 if (num == EBML_FLOAT_INVALID)
615 return 0;
616 track->a_sfreq = num;
617 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Sampling frequency: %f\n",
618 track->a_sfreq);
619 break;
622 case MATROSKA_ID_AUDIOBITDEPTH:
624 uint64_t num = ebml_read_uint (s, &l);
625 if (num == EBML_UINT_INVALID)
626 return 0;
627 track->a_bps = num;
628 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Bit depth: %u\n",
629 track->a_bps);
630 break;
633 case MATROSKA_ID_AUDIOCHANNELS:
635 uint64_t num = ebml_read_uint (s, &l);
636 if (num == EBML_UINT_INVALID)
637 return 0;
638 track->a_channels = num;
639 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Channels: %u\n",
640 track->a_channels);
641 break;
644 default:
645 ebml_read_skip (s, &l);
646 break;
648 length -= l + il;
650 return len;
653 static int
654 demux_mkv_read_trackvideo (demuxer_t *demuxer, mkv_track_t *track)
656 stream_t *s = demuxer->stream;
657 uint64_t len, length, l;
658 int il;
660 len = length = ebml_read_length (s, &il);
661 len += il;
662 while (length > 0)
664 switch (ebml_read_id (s, &il))
666 case MATROSKA_ID_VIDEOFRAMERATE:
668 long double num = ebml_read_float (s, &l);
669 if (num == EBML_FLOAT_INVALID)
670 return 0;
671 track->v_frate = num;
672 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Frame rate: %f\n",
673 track->v_frate);
674 if (track->v_frate > 0)
675 track->default_duration = 1 / track->v_frate;
676 break;
679 case MATROSKA_ID_VIDEODISPLAYWIDTH:
681 uint64_t num = ebml_read_uint (s, &l);
682 if (num == EBML_UINT_INVALID)
683 return 0;
684 track->v_dwidth = num;
685 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Display width: %u\n",
686 track->v_dwidth);
687 break;
690 case MATROSKA_ID_VIDEODISPLAYHEIGHT:
692 uint64_t num = ebml_read_uint (s, &l);
693 if (num == EBML_UINT_INVALID)
694 return 0;
695 track->v_dheight = num;
696 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Display height: %u\n",
697 track->v_dheight);
698 break;
701 case MATROSKA_ID_VIDEOPIXELWIDTH:
703 uint64_t num = ebml_read_uint (s, &l);
704 if (num == EBML_UINT_INVALID)
705 return 0;
706 track->v_width = num;
707 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Pixel width: %u\n",
708 track->v_width);
709 break;
712 case MATROSKA_ID_VIDEOPIXELHEIGHT:
714 uint64_t num = ebml_read_uint (s, &l);
715 if (num == EBML_UINT_INVALID)
716 return 0;
717 track->v_height = num;
718 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Pixel height: %u\n",
719 track->v_height);
720 break;
723 default:
724 ebml_read_skip (s, &l);
725 break;
727 length -= l + il;
729 return len;
733 * \brief free any data associated with given track
734 * \param track track of which to free data
736 static void
737 demux_mkv_free_trackentry(mkv_track_t *track) {
738 free (track->name);
739 free (track->codec_id);
740 free (track->language);
741 free (track->private_data);
742 free (track->audio_buf);
743 free (track->audio_timestamp);
744 demux_mkv_free_encodings(track->encodings, track->num_encodings);
745 free(track);
748 static int
749 demux_mkv_read_trackentry (demuxer_t *demuxer)
751 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
752 stream_t *s = demuxer->stream;
753 mkv_track_t *track;
754 uint64_t len, length, l;
755 int il;
757 track = calloc (1, sizeof (*track));
758 /* set default values */
759 track->default_track = 1;
760 track->name = 0;
761 track->language = strdup("eng");
763 len = length = ebml_read_length (s, &il);
764 len += il;
765 while (length > 0)
767 switch (ebml_read_id (s, &il))
769 case MATROSKA_ID_TRACKNUMBER:
771 uint64_t num = ebml_read_uint (s, &l);
772 if (num == EBML_UINT_INVALID)
773 goto err_out;
774 track->tnum = num;
775 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Track number: %u\n",
776 track->tnum);
777 break;
780 case MATROSKA_ID_TRACKNAME:
782 track->name = ebml_read_utf8 (s, &l);
783 if (track->name == NULL)
784 goto err_out;
785 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Name: %s\n",
786 track->name);
787 break;
790 case MATROSKA_ID_TRACKTYPE:
792 uint64_t num = ebml_read_uint (s, &l);
793 if (num == EBML_UINT_INVALID)
794 return 0;
795 track->type = num;
796 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Track type: ");
797 switch (track->type)
799 case MATROSKA_TRACK_AUDIO:
800 mp_msg (MSGT_DEMUX, MSGL_V, "Audio\n");
801 break;
802 case MATROSKA_TRACK_VIDEO:
803 mp_msg (MSGT_DEMUX, MSGL_V, "Video\n");
804 break;
805 case MATROSKA_TRACK_SUBTITLE:
806 mp_msg (MSGT_DEMUX, MSGL_V, "Subtitle\n");
807 break;
808 default:
809 mp_msg (MSGT_DEMUX, MSGL_V, "unknown\n");
810 break;
812 break;
815 case MATROSKA_ID_TRACKAUDIO:
816 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Audio track\n");
817 l = demux_mkv_read_trackaudio (demuxer, track);
818 if (l == 0)
819 goto err_out;
820 break;
822 case MATROSKA_ID_TRACKVIDEO:
823 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Video track\n");
824 l = demux_mkv_read_trackvideo (demuxer, track);
825 if (l == 0)
826 goto err_out;
827 break;
829 case MATROSKA_ID_CODECID:
830 track->codec_id = ebml_read_ascii (s, &l);
831 if (track->codec_id == NULL)
832 goto err_out;
833 if (!strcmp (track->codec_id, MKV_V_MSCOMP) ||
834 !strcmp (track->codec_id, MKV_A_ACM))
835 track->ms_compat = 1;
836 else if (!strcmp (track->codec_id, MKV_S_VOBSUB))
837 track->subtitle_type = MATROSKA_SUBTYPE_VOBSUB;
838 else if (!strcmp (track->codec_id, MKV_S_TEXTSSA)
839 || !strcmp (track->codec_id, MKV_S_TEXTASS)
840 || !strcmp (track->codec_id, MKV_S_SSA)
841 || !strcmp (track->codec_id, MKV_S_ASS))
843 track->subtitle_type = MATROSKA_SUBTYPE_SSA;
845 else if (!strcmp (track->codec_id, MKV_S_TEXTASCII))
846 track->subtitle_type = MATROSKA_SUBTYPE_TEXT;
847 if (!strcmp (track->codec_id, MKV_S_TEXTUTF8))
849 track->subtitle_type = MATROSKA_SUBTYPE_TEXT;
851 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Codec ID: %s\n",
852 track->codec_id);
853 break;
855 case MATROSKA_ID_CODECPRIVATE:
857 int x;
858 uint64_t num = ebml_read_length (s, &x);
859 // audit: cheap guard against overflows later..
860 if (num > SIZE_MAX - 1000) return 0;
861 l = x + num;
862 track->private_data = malloc (num + LZO_INPUT_PADDING);
863 if (stream_read(s, track->private_data, num) != (int) num)
864 goto err_out;
865 track->private_size = num;
866 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + CodecPrivate, length "
867 "%u\n", track->private_size);
868 break;
871 case MATROSKA_ID_TRACKLANGUAGE:
872 free(track->language);
873 track->language = ebml_read_utf8 (s, &l);
874 if (track->language == NULL)
875 goto err_out;
876 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Language: %s\n",
877 track->language);
878 break;
880 case MATROSKA_ID_TRACKFLAGDEFAULT:
882 uint64_t num = ebml_read_uint (s, &l);
883 if (num == EBML_UINT_INVALID)
884 goto err_out;
885 track->default_track = num;
886 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Default flag: %u\n",
887 track->default_track);
888 break;
891 case MATROSKA_ID_TRACKDEFAULTDURATION:
893 uint64_t num = ebml_read_uint (s, &l);
894 if (num == EBML_UINT_INVALID)
895 goto err_out;
896 if (num == 0)
897 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Default duration: 0");
898 else
900 track->v_frate = 1000000000.0 / num;
901 track->default_duration = num / 1000000000.0;
902 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Default duration: "
903 "%.3fms ( = %.3f fps)\n",num/1000000.0,track->v_frate);
905 break;
908 case MATROSKA_ID_TRACKENCODINGS:
909 l = demux_mkv_read_trackencodings (demuxer, track);
910 if (l == 0)
911 goto err_out;
912 break;
914 default:
915 ebml_read_skip (s, &l);
916 break;
918 length -= l + il;
921 mkv_d->tracks[mkv_d->num_tracks++] = track;
922 return len;
924 err_out:
925 demux_mkv_free_trackentry(track);
926 return 0;
929 static int
930 demux_mkv_read_tracks (demuxer_t *demuxer)
932 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
933 stream_t *s = demuxer->stream;
934 uint64_t length, l;
935 int il;
937 mkv_d->tracks = malloc (sizeof (*mkv_d->tracks));
938 mkv_d->num_tracks = 0;
940 length = ebml_read_length (s, NULL);
941 while (length > 0)
943 switch (ebml_read_id (s, &il))
945 case MATROSKA_ID_TRACKENTRY:
946 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + a track...\n");
947 mkv_d->tracks = realloc (mkv_d->tracks,
948 (mkv_d->num_tracks+1)
949 *sizeof (*mkv_d->tracks));
950 l = demux_mkv_read_trackentry (demuxer);
951 if (l == 0)
952 return 1;
953 break;
955 default:
956 ebml_read_skip (s, &l);
957 break;
959 length -= l + il;
961 return 0;
964 static int
965 demux_mkv_read_cues (demuxer_t *demuxer)
967 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
968 stream_t *s = demuxer->stream;
969 uint64_t length, l, time, track, pos;
970 off_t off;
971 int i, il;
973 if (index_mode == 0) {
974 ebml_read_skip (s, NULL);
975 return 0;
977 off = stream_tell (s);
978 for (i=0; i<mkv_d->parsed_cues_num; i++)
979 if (mkv_d->parsed_cues[i] == off)
981 ebml_read_skip (s, NULL);
982 return 0;
984 mkv_d->parsed_cues = realloc (mkv_d->parsed_cues,
985 (mkv_d->parsed_cues_num+1)
986 * sizeof (off_t));
987 mkv_d->parsed_cues[mkv_d->parsed_cues_num++] = off;
989 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] /---- [ parsing cues ] -----------\n");
990 length = ebml_read_length (s, NULL);
992 while (length > 0)
994 time = track = pos = EBML_UINT_INVALID;
996 switch (ebml_read_id (s, &il))
998 case MATROSKA_ID_POINTENTRY:
1000 uint64_t len;
1002 len = ebml_read_length (s, &i);
1003 l = len + i;
1005 while (len > 0)
1007 uint64_t l;
1008 int il;
1010 switch (ebml_read_id (s, &il))
1012 case MATROSKA_ID_CUETIME:
1013 time = ebml_read_uint (s, &l);
1014 break;
1016 case MATROSKA_ID_CUETRACKPOSITION:
1018 uint64_t le;
1020 le = ebml_read_length (s, &i);
1021 l = le + i;
1023 while (le > 0)
1025 uint64_t l;
1026 int il;
1028 switch (ebml_read_id (s, &il))
1030 case MATROSKA_ID_CUETRACK:
1031 track = ebml_read_uint (s, &l);
1032 break;
1034 case MATROSKA_ID_CUECLUSTERPOSITION:
1035 pos = ebml_read_uint (s, &l);
1036 break;
1038 default:
1039 ebml_read_skip (s, &l);
1040 break;
1042 le -= l + il;
1044 break;
1047 default:
1048 ebml_read_skip (s, &l);
1049 break;
1051 len -= l + il;
1053 break;
1056 default:
1057 ebml_read_skip (s, &l);
1058 break;
1061 length -= l + il;
1063 if (time != EBML_UINT_INVALID && track != EBML_UINT_INVALID
1064 && pos != EBML_UINT_INVALID)
1066 grow_array(&mkv_d->indexes, mkv_d->num_indexes, sizeof(mkv_index_t));
1067 mkv_d->indexes[mkv_d->num_indexes].tnum = track;
1068 mkv_d->indexes[mkv_d->num_indexes].timecode = time;
1069 mkv_d->indexes[mkv_d->num_indexes].filepos =mkv_d->segment_start+pos;
1070 mp_msg (MSGT_DEMUX, MSGL_DBG2, "[mkv] |+ found cue point "
1071 "for track %"PRIu64": timecode %"PRIu64", filepos: %"PRIu64"\n",
1072 track, time, mkv_d->segment_start + pos);
1073 mkv_d->num_indexes++;
1077 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] \\---- [ parsing cues ] -----------\n");
1078 return 0;
1081 static int
1082 demux_mkv_read_chapters (demuxer_t *demuxer)
1084 stream_t *s = demuxer->stream;
1085 uint64_t length, l;
1086 int il;
1088 if (demuxer->chapters)
1090 ebml_read_skip (s, NULL);
1091 return 0;
1094 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] /---- [ parsing chapters ] ---------\n");
1095 length = ebml_read_length (s, NULL);
1097 while (length > 0)
1099 switch (ebml_read_id (s, &il))
1101 case MATROSKA_ID_EDITIONENTRY:
1103 uint64_t len;
1104 int i;
1106 len = ebml_read_length (s, &i);
1107 l = len + i;
1109 while (len > 0)
1111 uint64_t l;
1112 int il;
1114 switch (ebml_read_id (s, &il))
1116 case MATROSKA_ID_CHAPTERATOM:
1118 uint64_t len, start=0, end=0;
1119 char* name = 0;
1120 int i;
1121 int cid;
1123 len = ebml_read_length (s, &i);
1124 l = len + i;
1126 while (len > 0)
1128 uint64_t l;
1129 int il;
1131 switch (ebml_read_id (s, &il))
1133 case MATROSKA_ID_CHAPTERTIMESTART:
1134 start = ebml_read_uint (s, &l) / 1000000;
1135 break;
1137 case MATROSKA_ID_CHAPTERTIMEEND:
1138 end = ebml_read_uint (s, &l) / 1000000;
1139 break;
1141 case MATROSKA_ID_CHAPTERDISPLAY:
1143 uint64_t len;
1144 int i;
1146 len = ebml_read_length (s, &i);
1147 l = len + i;
1148 while (len > 0)
1150 uint64_t l;
1151 int il;
1153 switch (ebml_read_id (s, &il))
1155 case MATROSKA_ID_CHAPSTRING:
1156 name = ebml_read_utf8 (s, &l);
1157 break;
1158 default:
1159 ebml_read_skip (s, &l);
1160 break;
1162 len -= l + il;
1165 break;
1167 default:
1168 ebml_read_skip (s, &l);
1169 break;
1171 len -= l + il;
1174 if (!name)
1175 name = strdup("(unnamed)");
1177 cid = demuxer_add_chapter(demuxer, name, start, end);
1179 mp_msg(MSGT_DEMUX, MSGL_V,
1180 "[mkv] Chapter %u from %02d:%02d:%02d."
1181 "%03d to %02d:%02d:%02d.%03d, %s\n",
1182 cid,
1183 (int) (start / 60 / 60 / 1000),
1184 (int) ((start / 60 / 1000) % 60),
1185 (int) ((start / 1000) % 60),
1186 (int) (start % 1000),
1187 (int) (end / 60 / 60 / 1000),
1188 (int) ((end / 60 / 1000) % 60),
1189 (int) ((end / 1000) % 60),
1190 (int) (end % 1000), name);
1192 free(name);
1193 break;
1196 default:
1197 ebml_read_skip (s, &l);
1198 break;
1200 len -= l + il;
1202 break;
1205 default:
1206 ebml_read_skip (s, &l);
1207 break;
1210 length -= l + il;
1213 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] \\---- [ parsing chapters ] ---------\n");
1214 return 0;
1217 static int
1218 demux_mkv_read_tags (demuxer_t *demuxer)
1220 ebml_read_skip (demuxer->stream, NULL);
1221 return 0;
1224 static int
1225 demux_mkv_read_attachments (demuxer_t *demuxer)
1227 stream_t *s = demuxer->stream;
1228 uint64_t length, l;
1229 int il;
1231 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] /---- [ parsing attachments ] ---------\n");
1232 length = ebml_read_length (s, NULL);
1234 while (length > 0)
1236 switch (ebml_read_id (s, &il))
1238 case MATROSKA_ID_ATTACHEDFILE:
1240 uint64_t len;
1241 int i;
1242 char* name = NULL;
1243 char* mime = NULL;
1244 char* data = NULL;
1245 int data_size = 0;
1247 len = ebml_read_length (s, &i);
1248 l = len + i;
1250 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + an attachment...\n");
1252 while (len > 0)
1254 uint64_t l;
1255 int il;
1257 switch (ebml_read_id (s, &il))
1259 case MATROSKA_ID_FILENAME:
1260 name = ebml_read_utf8 (s, &l);
1261 if (name == NULL)
1262 return 0;
1263 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + FileName: %s\n",
1264 name);
1265 break;
1267 case MATROSKA_ID_FILEMIMETYPE:
1268 mime = ebml_read_ascii (s, &l);
1269 if (mime == NULL)
1270 return 0;
1271 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + FileMimeType: %s\n",
1272 mime);
1273 break;
1275 case MATROSKA_ID_FILEDATA:
1277 int x;
1278 uint64_t num = ebml_read_length (s, &x);
1279 l = x + num;
1280 free(data);
1281 data = malloc (num);
1282 if (stream_read(s, data, num) != (int) num)
1284 free(data);
1285 return 0;
1287 data_size = num;
1288 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + FileData, length "
1289 "%u\n", data_size);
1290 break;
1293 default:
1294 ebml_read_skip (s, &l);
1295 break;
1297 len -= l + il;
1300 demuxer_add_attachment(demuxer, name, mime, data, data_size);
1301 mp_msg(MSGT_DEMUX, MSGL_V,
1302 "[mkv] Attachment: %s, %s, %u bytes\n",
1303 name, mime, data_size);
1304 break;
1307 default:
1308 ebml_read_skip (s, &l);
1309 break;
1311 length -= l + il;
1314 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] \\---- [ parsing attachments ] ---------\n");
1315 return 0;
1318 static int
1319 demux_mkv_read_seekhead (demuxer_t *demuxer)
1321 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
1322 stream_t *s = demuxer->stream;
1323 uint64_t length, l, seek_pos, saved_pos, num;
1324 uint32_t seek_id;
1325 int i, il, res = 0;
1326 off_t off;
1328 off = stream_tell (s);
1329 for (i=0; i<mkv_d->parsed_seekhead_num; i++)
1330 if (mkv_d->parsed_seekhead[i] == off)
1332 ebml_read_skip (s, NULL);
1333 return 0;
1335 mkv_d->parsed_seekhead = realloc (mkv_d->parsed_seekhead,
1336 (mkv_d->parsed_seekhead_num+1)
1337 * sizeof (off_t));
1338 mkv_d->parsed_seekhead[mkv_d->parsed_seekhead_num++] = off;
1340 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] /---- [ parsing seek head ] ---------\n");
1341 length = ebml_read_length (s, NULL);
1342 /* off now holds the position of the next element after the seek head. */
1343 off = stream_tell (s) + length;
1344 while (length > 0 && !res)
1347 seek_id = 0;
1348 seek_pos = EBML_UINT_INVALID;
1350 switch (ebml_read_id (s, &il))
1352 case MATROSKA_ID_SEEKENTRY:
1354 uint64_t len;
1356 len = ebml_read_length (s, &i);
1357 l = len + i;
1359 while (len > 0)
1361 uint64_t l;
1362 int il;
1364 switch (ebml_read_id (s, &il))
1366 case MATROSKA_ID_SEEKID:
1367 num = ebml_read_uint (s, &l);
1368 if (num != EBML_UINT_INVALID)
1369 seek_id = num;
1370 break;
1372 case MATROSKA_ID_SEEKPOSITION:
1373 seek_pos = ebml_read_uint (s, &l);
1374 break;
1376 default:
1377 ebml_read_skip (s, &l);
1378 break;
1380 len -= l + il;
1383 break;
1386 default:
1387 ebml_read_skip (s, &l);
1388 break;
1390 length -= l + il;
1392 if (seek_id == 0 || seek_id == MATROSKA_ID_CLUSTER
1393 || seek_pos == EBML_UINT_INVALID ||
1394 ((mkv_d->segment_start + seek_pos) >= (uint64_t)demuxer->movi_end))
1395 continue;
1397 saved_pos = stream_tell (s);
1398 if (!stream_seek (s, mkv_d->segment_start + seek_pos))
1399 res = 1;
1400 else
1402 if (ebml_read_id (s, &il) != seek_id)
1403 res = 1;
1404 else
1405 switch (seek_id)
1407 case MATROSKA_ID_CUES:
1408 if (demux_mkv_read_cues (demuxer))
1409 res = 1;
1410 break;
1412 case MATROSKA_ID_TAGS:
1413 if (demux_mkv_read_tags (demuxer))
1414 res = 1;
1415 break;
1417 case MATROSKA_ID_SEEKHEAD:
1418 if (demux_mkv_read_seekhead (demuxer))
1419 res = 1;
1420 break;
1422 case MATROSKA_ID_CHAPTERS:
1423 if (demux_mkv_read_chapters (demuxer))
1424 res = 1;
1425 break;
1429 stream_seek (s, saved_pos);
1431 if (res)
1433 /* If there was an error then try to skip this seek head. */
1434 if (stream_seek (s, off))
1435 res = 0;
1437 else
1438 if (length > 0)
1439 stream_seek (s, stream_tell (s) + length);
1440 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] \\---- [ parsing seek head ] ---------\n");
1441 return res;
1444 static int
1445 demux_mkv_open_video (demuxer_t *demuxer, mkv_track_t *track, int vid);
1446 static int
1447 demux_mkv_open_audio (demuxer_t *demuxer, mkv_track_t *track, int aid);
1448 static int
1449 demux_mkv_open_sub (demuxer_t *demuxer, mkv_track_t *track, int sid);
1451 static void
1452 display_create_tracks (demuxer_t *demuxer)
1454 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *)demuxer->priv;
1455 int i, vid=0, aid=0, sid=0;
1457 for (i=0; i<mkv_d->num_tracks; i++)
1459 char *type = "unknown", str[32];
1460 *str = '\0';
1461 switch (mkv_d->tracks[i]->type)
1463 case MATROSKA_TRACK_VIDEO:
1464 type = "video";
1465 demux_mkv_open_video(demuxer, mkv_d->tracks[i], vid);
1466 if (mkv_d->tracks[i]->name)
1467 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VID_%d_NAME=%s\n", vid, mkv_d->tracks[i]->name);
1468 sprintf (str, "-vid %u", vid++);
1469 break;
1470 case MATROSKA_TRACK_AUDIO:
1471 type = "audio";
1472 demux_mkv_open_audio(demuxer, mkv_d->tracks[i], aid);
1473 if (mkv_d->tracks[i]->name)
1474 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AID_%d_NAME=%s\n", aid, mkv_d->tracks[i]->name);
1475 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AID_%d_LANG=%s\n", aid, mkv_d->tracks[i]->language);
1476 sprintf (str, "-aid %u, -alang %.5s",aid++,mkv_d->tracks[i]->language);
1477 break;
1478 case MATROSKA_TRACK_SUBTITLE:
1479 type = "subtitles";
1480 demux_mkv_open_sub(demuxer, mkv_d->tracks[i], sid);
1481 if (mkv_d->tracks[i]->name)
1482 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SID_%d_NAME=%s\n", sid, mkv_d->tracks[i]->name);
1483 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SID_%d_LANG=%s\n", sid, mkv_d->tracks[i]->language);
1484 sprintf (str, "-sid %u, -slang %.5s",sid++,mkv_d->tracks[i]->language);
1485 break;
1487 if (mkv_d->tracks[i]->name)
1488 mp_msg(MSGT_DEMUX, MSGL_INFO, MSGTR_MPDEMUX_MKV_TrackIDName,
1489 mkv_d->tracks[i]->tnum, type, mkv_d->tracks[i]->codec_id, mkv_d->tracks[i]->name, str);
1490 else
1491 mp_msg(MSGT_DEMUX, MSGL_INFO, MSGTR_MPDEMUX_MKV_TrackID,
1492 mkv_d->tracks[i]->tnum, type, mkv_d->tracks[i]->codec_id, str);
1496 typedef struct {
1497 char *id;
1498 int fourcc;
1499 int extradata;
1500 } videocodec_info_t;
1502 static const videocodec_info_t vinfo[] = {
1503 { MKV_V_MPEG1, mmioFOURCC('m', 'p', 'g', '1'), 0 },
1504 { MKV_V_MPEG2, mmioFOURCC('m', 'p', 'g', '2'), 0 },
1505 { MKV_V_MPEG4_SP, mmioFOURCC('m', 'p', '4', 'v'), 1 },
1506 { MKV_V_MPEG4_ASP, mmioFOURCC('m', 'p', '4', 'v'), 1 },
1507 { MKV_V_MPEG4_AP, mmioFOURCC('m', 'p', '4', 'v'), 1 },
1508 { MKV_V_MPEG4_AVC, mmioFOURCC('a', 'v', 'c', '1'), 1 },
1509 { MKV_V_THEORA, mmioFOURCC('t', 'h', 'e', 'o'), 1 },
1510 { NULL, 0, 0 }
1513 static int
1514 demux_mkv_open_video (demuxer_t *demuxer, mkv_track_t *track, int vid)
1516 BITMAPINFOHEADER *bih;
1517 void *ImageDesc = NULL;
1518 sh_video_t *sh_v;
1520 if (track->ms_compat) /* MS compatibility mode */
1522 BITMAPINFOHEADER *src;
1524 if (track->private_data == NULL
1525 || track->private_size < sizeof (BITMAPINFOHEADER))
1526 return 1;
1528 src = (BITMAPINFOHEADER *) track->private_data;
1529 bih = calloc (1, track->private_size);
1530 bih->biSize = le2me_32 (src->biSize);
1531 bih->biWidth = le2me_32 (src->biWidth);
1532 bih->biHeight = le2me_32 (src->biHeight);
1533 bih->biPlanes = le2me_16 (src->biPlanes);
1534 bih->biBitCount = le2me_16 (src->biBitCount);
1535 bih->biCompression = le2me_32 (src->biCompression);
1536 bih->biSizeImage = le2me_32 (src->biSizeImage);
1537 bih->biXPelsPerMeter = le2me_32 (src->biXPelsPerMeter);
1538 bih->biYPelsPerMeter = le2me_32 (src->biYPelsPerMeter);
1539 bih->biClrUsed = le2me_32 (src->biClrUsed);
1540 bih->biClrImportant = le2me_32 (src->biClrImportant);
1541 memcpy((char *) bih + sizeof (BITMAPINFOHEADER),
1542 (char *) src + sizeof (BITMAPINFOHEADER),
1543 track->private_size - sizeof (BITMAPINFOHEADER));
1545 if (track->v_width == 0)
1546 track->v_width = bih->biWidth;
1547 if (track->v_height == 0)
1548 track->v_height = bih->biHeight;
1550 else
1552 bih = calloc (1, sizeof (BITMAPINFOHEADER));
1553 bih->biSize = sizeof (BITMAPINFOHEADER);
1554 bih->biWidth = track->v_width;
1555 bih->biHeight = track->v_height;
1556 bih->biBitCount = 24;
1557 bih->biSizeImage = bih->biWidth * bih->biHeight * bih->biBitCount/8;
1559 if (track->private_size >= RVPROPERTIES_SIZE
1560 && (!strcmp (track->codec_id, MKV_V_REALV10)
1561 || !strcmp (track->codec_id, MKV_V_REALV20)
1562 || !strcmp (track->codec_id, MKV_V_REALV30)
1563 || !strcmp (track->codec_id, MKV_V_REALV40)))
1565 unsigned char *dst, *src;
1566 uint32_t type2;
1567 unsigned int cnt;
1569 src = track->private_data + RVPROPERTIES_SIZE;
1571 cnt = track->private_size - RVPROPERTIES_SIZE;
1572 bih = realloc(bih, sizeof (BITMAPINFOHEADER)+8+cnt);
1573 bih->biSize = 48+cnt;
1574 bih->biPlanes = 1;
1575 type2 = AV_RB32(src - 4);
1576 if (type2 == 0x10003000 || type2 == 0x10003001)
1577 bih->biCompression=mmioFOURCC('R','V','1','3');
1578 else
1579 bih->biCompression=mmioFOURCC('R','V',track->codec_id[9],'0');
1580 dst = (unsigned char *) (bih + 1);
1581 // copy type1 and type2 info from rv properties
1582 memcpy(dst, src - 8, 8);
1583 stream_read(demuxer->stream, dst+8, cnt);
1584 track->realmedia = 1;
1586 #ifdef CONFIG_QTX_CODECS
1588 else if (track->private_size >= sizeof (ImageDescription)
1589 && !strcmp(track->codec_id, MKV_V_QUICKTIME))
1591 ImageDescriptionPtr idesc;
1593 idesc = (ImageDescriptionPtr) track->private_data;
1594 idesc->idSize = be2me_32 (idesc->idSize);
1595 idesc->cType = be2me_32 (idesc->cType);
1596 idesc->version = be2me_16 (idesc->version);
1597 idesc->revisionLevel = be2me_16 (idesc->revisionLevel);
1598 idesc->vendor = be2me_32 (idesc->vendor);
1599 idesc->temporalQuality = be2me_32 (idesc->temporalQuality);
1600 idesc->spatialQuality = be2me_32 (idesc->spatialQuality);
1601 idesc->width = be2me_16 (idesc->width);
1602 idesc->height = be2me_16 (idesc->height);
1603 idesc->hRes = be2me_32 (idesc->hRes);
1604 idesc->vRes = be2me_32 (idesc->vRes);
1605 idesc->dataSize = be2me_32 (idesc->dataSize);
1606 idesc->frameCount = be2me_16 (idesc->frameCount);
1607 idesc->depth = be2me_16 (idesc->depth);
1608 idesc->clutID = be2me_16 (idesc->clutID);
1609 bih->biPlanes = 1;
1610 bih->biCompression = idesc->cType;
1611 ImageDesc = idesc;
1612 #endif /* CONFIG_QTX_CODECS */
1615 else
1617 const videocodec_info_t *vi = vinfo;
1618 while (vi->id && strcmp(vi->id, track->codec_id)) vi++;
1619 bih->biCompression = vi->fourcc;
1620 if (vi->extradata && track->private_data && (track->private_size > 0))
1622 bih->biSize += track->private_size;
1623 bih = realloc (bih, bih->biSize);
1624 memcpy (bih + 1, track->private_data, track->private_size);
1626 track->reorder_timecodes = user_correct_pts == 0;
1627 if (!vi->id) {
1628 mp_msg (MSGT_DEMUX,MSGL_WARN, MSGTR_MPDEMUX_MKV_UnknownCodecID,
1629 track->codec_id, track->tnum);
1630 free(bih);
1631 return 1;
1636 sh_v = new_sh_video_vid (demuxer, track->tnum, vid);
1637 sh_v->bih = bih;
1638 sh_v->format = sh_v->bih->biCompression;
1639 if (track->v_frate == 0.0)
1640 track->v_frate = 25.0;
1641 sh_v->fps = track->v_frate;
1642 sh_v->frametime = 1 / track->v_frate;
1643 sh_v->aspect = 0;
1644 if (!track->realmedia)
1646 sh_v->disp_w = track->v_width;
1647 sh_v->disp_h = track->v_height;
1648 if (track->v_dheight)
1649 sh_v->aspect = (float)track->v_dwidth / (float)track->v_dheight;
1651 else
1653 // vd_realvid.c will set aspect to disp_w/disp_h and rederive
1654 // disp_w and disp_h from the RealVideo stream contents returned
1655 // by the Real DLLs. If DisplayWidth/DisplayHeight was not set in
1656 // the Matroska file then it has already been set to PixelWidth/Height
1657 // by check_track_information.
1658 sh_v->disp_w = track->v_dwidth;
1659 sh_v->disp_h = track->v_dheight;
1661 sh_v->ImageDesc = ImageDesc;
1662 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] Aspect: %f\n", sh_v->aspect);
1664 sh_v->ds = demuxer->video;
1665 return 0;
1668 static int
1669 demux_mkv_open_audio (demuxer_t *demuxer, mkv_track_t *track, int aid)
1671 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
1672 sh_audio_t *sh_a = new_sh_audio_aid(demuxer, track->tnum, aid);
1673 demux_packet_t *dp;
1674 if(!sh_a) return 1;
1675 mkv_d->audio_tracks[mkv_d->last_aid] = track->tnum;
1677 if (track->language && (strcmp(track->language, "und") != 0))
1678 sh_a->lang = strdup(track->language);
1679 sh_a->default_track = track->default_track;
1680 sh_a->ds = demuxer->audio;
1681 sh_a->wf = malloc (sizeof (WAVEFORMATEX));
1682 if (track->ms_compat && (track->private_size >= sizeof(WAVEFORMATEX)))
1684 WAVEFORMATEX *wf = (WAVEFORMATEX *)track->private_data;
1685 sh_a->wf = realloc(sh_a->wf, track->private_size);
1686 sh_a->wf->wFormatTag = le2me_16 (wf->wFormatTag);
1687 sh_a->wf->nChannels = le2me_16 (wf->nChannels);
1688 sh_a->wf->nSamplesPerSec = le2me_32 (wf->nSamplesPerSec);
1689 sh_a->wf->nAvgBytesPerSec = le2me_32 (wf->nAvgBytesPerSec);
1690 sh_a->wf->nBlockAlign = le2me_16 (wf->nBlockAlign);
1691 sh_a->wf->wBitsPerSample = le2me_16 (wf->wBitsPerSample);
1692 sh_a->wf->cbSize = track->private_size - sizeof(WAVEFORMATEX);
1693 memcpy(sh_a->wf + 1, wf + 1, track->private_size - sizeof(WAVEFORMATEX));
1694 if (track->a_sfreq == 0.0)
1695 track->a_sfreq = sh_a->wf->nSamplesPerSec;
1696 if (track->a_channels == 0)
1697 track->a_channels = sh_a->wf->nChannels;
1698 if (track->a_bps == 0)
1699 track->a_bps = sh_a->wf->wBitsPerSample;
1700 track->a_formattag = sh_a->wf->wFormatTag;
1702 else
1704 memset(sh_a->wf, 0, sizeof (WAVEFORMATEX));
1705 if (!strcmp(track->codec_id, MKV_A_MP3) ||
1706 !strcmp(track->codec_id, MKV_A_MP2))
1707 track->a_formattag = 0x0055;
1708 else if (!strncmp(track->codec_id, MKV_A_AC3, strlen(MKV_A_AC3)))
1709 track->a_formattag = 0x2000;
1710 else if (!strcmp(track->codec_id, MKV_A_DTS))
1711 track->a_formattag = 0x2001;
1712 else if (!strcmp(track->codec_id, MKV_A_PCM) ||
1713 !strcmp(track->codec_id, MKV_A_PCM_BE))
1714 track->a_formattag = 0x0001;
1715 else if (!strcmp(track->codec_id, MKV_A_AAC_2MAIN) ||
1716 !strncmp(track->codec_id, MKV_A_AAC_2LC,
1717 strlen(MKV_A_AAC_2LC)) ||
1718 !strcmp(track->codec_id, MKV_A_AAC_2SSR) ||
1719 !strcmp(track->codec_id, MKV_A_AAC_4MAIN) ||
1720 !strncmp(track->codec_id, MKV_A_AAC_4LC,
1721 strlen(MKV_A_AAC_4LC)) ||
1722 !strcmp(track->codec_id, MKV_A_AAC_4SSR) ||
1723 !strcmp(track->codec_id, MKV_A_AAC_4LTP) ||
1724 !strcmp(track->codec_id, MKV_A_AAC))
1725 track->a_formattag = mmioFOURCC('M', 'P', '4', 'A');
1726 else if (!strcmp(track->codec_id, MKV_A_VORBIS))
1728 if (track->private_data == NULL)
1729 return 1;
1730 track->a_formattag = mmioFOURCC('v', 'r', 'b', 's');
1732 else if (!strcmp(track->codec_id, MKV_A_QDMC))
1733 track->a_formattag = mmioFOURCC('Q', 'D', 'M', 'C');
1734 else if (!strcmp(track->codec_id, MKV_A_QDMC2))
1735 track->a_formattag = mmioFOURCC('Q', 'D', 'M', '2');
1736 else if (!strcmp(track->codec_id, MKV_A_WAVPACK))
1737 track->a_formattag = mmioFOURCC('W', 'V', 'P', 'K');
1738 else if (!strcmp(track->codec_id, MKV_A_FLAC))
1740 if (track->private_data == NULL || track->private_size == 0)
1742 mp_msg (MSGT_DEMUX, MSGL_WARN,
1743 MSGTR_MPDEMUX_MKV_FlacTrackDoesNotContainValidHeaders);
1744 return 1;
1746 track->a_formattag = mmioFOURCC ('f', 'L', 'a', 'C');
1748 else if (track->private_size >= RAPROPERTIES4_SIZE)
1750 if (!strcmp(track->codec_id, MKV_A_REAL28))
1751 track->a_formattag = mmioFOURCC('2', '8', '_', '8');
1752 else if (!strcmp(track->codec_id, MKV_A_REALATRC))
1753 track->a_formattag = mmioFOURCC('a', 't', 'r', 'c');
1754 else if (!strcmp(track->codec_id, MKV_A_REALCOOK))
1755 track->a_formattag = mmioFOURCC('c', 'o', 'o', 'k');
1756 else if (!strcmp(track->codec_id, MKV_A_REALDNET))
1757 track->a_formattag = mmioFOURCC('d', 'n', 'e', 't');
1758 else if (!strcmp(track->codec_id, MKV_A_REALSIPR))
1759 track->a_formattag = mmioFOURCC('s', 'i', 'p', 'r');
1761 else
1763 mp_msg (MSGT_DEMUX, MSGL_WARN, MSGTR_MPDEMUX_MKV_UnknownAudioCodec,
1764 track->codec_id, track->tnum);
1765 free_sh_audio(demuxer, track->tnum);
1766 return 1;
1770 sh_a->format = track->a_formattag;
1771 sh_a->wf->wFormatTag = track->a_formattag;
1772 sh_a->channels = track->a_channels;
1773 sh_a->wf->nChannels = track->a_channels;
1774 sh_a->samplerate = (uint32_t) track->a_sfreq;
1775 sh_a->wf->nSamplesPerSec = (uint32_t) track->a_sfreq;
1776 if (track->a_bps == 0)
1778 sh_a->samplesize = 2;
1779 sh_a->wf->wBitsPerSample = 16;
1781 else
1783 sh_a->samplesize = track->a_bps / 8;
1784 sh_a->wf->wBitsPerSample = track->a_bps;
1786 if (track->a_formattag == 0x0055) /* MP3 || MP2 */
1788 sh_a->wf->nAvgBytesPerSec = 16000;
1789 sh_a->wf->nBlockAlign = 1152;
1791 else if ((track->a_formattag == 0x2000) || /* AC3 */
1792 (track->a_formattag == 0x2001)) /* DTS */
1794 free(sh_a->wf);
1795 sh_a->wf = NULL;
1797 else if (track->a_formattag == 0x0001) /* PCM || PCM_BE */
1799 sh_a->wf->nAvgBytesPerSec = sh_a->channels * sh_a->samplerate*2;
1800 sh_a->wf->nBlockAlign = sh_a->wf->nAvgBytesPerSec;
1801 if (!strcmp(track->codec_id, MKV_A_PCM_BE))
1802 sh_a->format = mmioFOURCC('t', 'w', 'o', 's');
1804 else if (!strcmp(track->codec_id, MKV_A_QDMC) ||
1805 !strcmp(track->codec_id, MKV_A_QDMC2))
1807 sh_a->wf->nAvgBytesPerSec = 16000;
1808 sh_a->wf->nBlockAlign = 1486;
1809 track->fix_i_bps = 1;
1810 track->qt_last_a_pts = 0.0;
1811 if (track->private_data != NULL)
1813 sh_a->codecdata=malloc(track->private_size);
1814 memcpy (sh_a->codecdata, track->private_data,
1815 track->private_size);
1816 sh_a->codecdata_len = track->private_size;
1819 else if (track->a_formattag == mmioFOURCC('M', 'P', '4', 'A'))
1821 int profile, srate_idx;
1823 sh_a->wf->nAvgBytesPerSec = 16000;
1824 sh_a->wf->nBlockAlign = 1024;
1826 if (!strcmp (track->codec_id, MKV_A_AAC) &&
1827 (NULL != track->private_data))
1829 sh_a->codecdata=malloc(track->private_size);
1830 memcpy (sh_a->codecdata, track->private_data,
1831 track->private_size);
1832 sh_a->codecdata_len = track->private_size;
1833 return 0;
1836 /* Recreate the 'private data' */
1837 /* which faad2 uses in its initialization */
1838 srate_idx = aac_get_sample_rate_index (sh_a->samplerate);
1839 if (!strncmp (&track->codec_id[12], "MAIN", 4))
1840 profile = 0;
1841 else if (!strncmp (&track->codec_id[12], "LC", 2))
1842 profile = 1;
1843 else if (!strncmp (&track->codec_id[12], "SSR", 3))
1844 profile = 2;
1845 else
1846 profile = 3;
1847 sh_a->codecdata = malloc (5);
1848 sh_a->codecdata[0] = ((profile+1) << 3) | ((srate_idx&0xE) >> 1);
1849 sh_a->codecdata[1] = ((srate_idx&0x1)<<7)|(track->a_channels<<3);
1851 if (strstr(track->codec_id, "SBR") != NULL)
1853 /* HE-AAC (aka SBR AAC) */
1854 sh_a->codecdata_len = 5;
1856 sh_a->samplerate *= 2;
1857 sh_a->wf->nSamplesPerSec *= 2;
1858 srate_idx = aac_get_sample_rate_index(sh_a->samplerate);
1859 sh_a->codecdata[2] = AAC_SYNC_EXTENSION_TYPE >> 3;
1860 sh_a->codecdata[3] = ((AAC_SYNC_EXTENSION_TYPE&0x07)<<5) | 5;
1861 sh_a->codecdata[4] = (1 << 7) | (srate_idx << 3);
1862 track->default_duration = 1024.0 / (sh_a->samplerate / 2);
1864 else
1866 sh_a->codecdata_len = 2;
1867 track->default_duration = 1024.0 / (float)sh_a->samplerate;
1870 else if (track->a_formattag == mmioFOURCC('v', 'r', 'b', 's')) /* VORBIS */
1872 sh_a->wf->cbSize = track->private_size;
1873 sh_a->wf = realloc(sh_a->wf, sizeof(WAVEFORMATEX) + sh_a->wf->cbSize);
1874 memcpy((unsigned char *) (sh_a->wf+1), track->private_data, sh_a->wf->cbSize);
1876 else if (track->private_size >= RAPROPERTIES4_SIZE
1877 && !strncmp (track->codec_id, MKV_A_REALATRC, 7))
1879 /* Common initialization for all RealAudio codecs */
1880 unsigned char *src = track->private_data;
1881 int codecdata_length, version;
1882 int flavor;
1884 sh_a->wf->nAvgBytesPerSec = 0; /* FIXME !? */
1886 version = AV_RB16(src + 4);
1887 flavor = AV_RB16(src + 22);
1888 track->coded_framesize = AV_RB32(src + 24);
1889 track->sub_packet_h = AV_RB16(src + 40);
1890 sh_a->wf->nBlockAlign =
1891 track->audiopk_size = AV_RB16(src + 42);
1892 track->sub_packet_size = AV_RB16(src + 44);
1893 if (version == 4)
1895 src += RAPROPERTIES4_SIZE;
1896 src += src[0] + 1;
1897 src += src[0] + 1;
1899 else
1900 src += RAPROPERTIES5_SIZE;
1902 src += 3;
1903 if (version == 5)
1904 src++;
1905 codecdata_length = AV_RB32(src);
1906 src += 4;
1907 sh_a->wf->cbSize = codecdata_length;
1908 sh_a->wf = realloc (sh_a->wf,
1909 sizeof (WAVEFORMATEX) +
1910 sh_a->wf->cbSize);
1911 memcpy(((char *)(sh_a->wf + 1)), src, codecdata_length);
1913 switch (track->a_formattag) {
1914 case mmioFOURCC('a', 't', 'r', 'c'):
1915 sh_a->wf->nAvgBytesPerSec = atrc_fl2bps[flavor];
1916 sh_a->wf->nBlockAlign = track->sub_packet_size;
1917 track->audio_buf = malloc(track->sub_packet_h * track->audiopk_size);
1918 track->audio_timestamp = malloc(track->sub_packet_h * sizeof(float));
1919 break;
1920 case mmioFOURCC('c', 'o', 'o', 'k'):
1921 sh_a->wf->nAvgBytesPerSec = cook_fl2bps[flavor];
1922 sh_a->wf->nBlockAlign = track->sub_packet_size;
1923 track->audio_buf = malloc(track->sub_packet_h * track->audiopk_size);
1924 track->audio_timestamp = malloc(track->sub_packet_h * sizeof(float));
1925 break;
1926 case mmioFOURCC('s', 'i', 'p', 'r'):
1927 sh_a->wf->nAvgBytesPerSec = sipr_fl2bps[flavor];
1928 sh_a->wf->nBlockAlign = track->coded_framesize;
1929 track->audio_buf = malloc(track->sub_packet_h * track->audiopk_size);
1930 track->audio_timestamp = malloc(track->sub_packet_h * sizeof(float));
1931 break;
1932 case mmioFOURCC('2', '8', '_', '8'):
1933 sh_a->wf->nAvgBytesPerSec = 3600;
1934 sh_a->wf->nBlockAlign = track->coded_framesize;
1935 track->audio_buf = malloc(track->sub_packet_h * track->audiopk_size);
1936 track->audio_timestamp = malloc(track->sub_packet_h * sizeof(float));
1937 break;
1940 track->realmedia = 1;
1942 else if (!strcmp(track->codec_id, MKV_A_FLAC) ||
1943 (track->a_formattag == 0xf1ac))
1945 unsigned char *ptr;
1946 int size;
1947 free(sh_a->wf);
1948 sh_a->wf = NULL;
1950 if (track->a_formattag == mmioFOURCC('f', 'L', 'a', 'C'))
1952 ptr = (unsigned char *)track->private_data;
1953 size = track->private_size;
1955 else
1957 sh_a->format = mmioFOURCC('f', 'L', 'a', 'C');
1958 ptr = (unsigned char *) track->private_data
1959 + sizeof (WAVEFORMATEX);
1960 size = track->private_size - sizeof (WAVEFORMATEX);
1962 if (size < 4 || ptr[0] != 'f' || ptr[1] != 'L' ||
1963 ptr[2] != 'a' || ptr[3] != 'C')
1965 dp = new_demux_packet (4);
1966 memcpy (dp->buffer, "fLaC", 4);
1968 else
1970 dp = new_demux_packet (size);
1971 memcpy (dp->buffer, ptr, size);
1973 dp->pts = 0;
1974 dp->flags = 0;
1975 ds_add_packet (demuxer->audio, dp);
1977 else if (track->a_formattag == mmioFOURCC('W', 'V', 'P', 'K'))
1978 { /* do nothing, still works */ }
1979 else if (!track->ms_compat || (track->private_size < sizeof(WAVEFORMATEX)))
1981 free_sh_audio(demuxer, track->tnum);
1982 return 1;
1985 return 0;
1988 static int
1989 demux_mkv_open_sub (demuxer_t *demuxer, mkv_track_t *track, int sid)
1991 if (track->subtitle_type != MATROSKA_SUBTYPE_UNKNOWN)
1993 int size, m;
1994 uint8_t *buffer;
1995 sh_sub_t *sh = new_sh_sub_sid(demuxer, track->tnum, sid);
1996 track->sh_sub = sh;
1997 sh->type = 't';
1998 if (track->subtitle_type == MATROSKA_SUBTYPE_VOBSUB)
1999 sh->type = 'v';
2000 if (track->subtitle_type == MATROSKA_SUBTYPE_SSA)
2001 sh->type = 'a';
2002 size = track->private_size;
2003 m = demux_mkv_decode (track,track->private_data,&buffer,&size,2);
2004 if (buffer && m)
2006 free (track->private_data);
2007 track->private_data = buffer;
2008 track->private_size = size;
2010 sh->extradata=malloc(track->private_size);
2011 memcpy (sh->extradata, track->private_data,
2012 track->private_size);
2013 sh->extradata_len = track->private_size;
2014 if (track->language && (strcmp(track->language, "und") != 0))
2015 sh->lang = strdup(track->language);
2016 sh->default_track = track->default_track;
2018 else
2020 mp_msg (MSGT_DEMUX, MSGL_ERR, MSGTR_MPDEMUX_MKV_SubtitleTypeNotSupported,
2021 track->codec_id);
2022 return 1;
2025 return 0;
2028 static void demux_mkv_seek (demuxer_t *demuxer, float rel_seek_secs, float audio_delay, int flags);
2030 static int
2031 demux_mkv_open (demuxer_t *demuxer)
2033 stream_t *s = demuxer->stream;
2034 mkv_demuxer_t *mkv_d;
2035 mkv_track_t *track;
2036 int i, version, cont = 0;
2037 char *str;
2039 stream_seek(s, s->start_pos);
2040 str = ebml_read_header (s, &version);
2041 if (str == NULL || strcmp (str, "matroska") || version > 2)
2043 mp_msg (MSGT_DEMUX, MSGL_DBG2, "[mkv] no head found\n");
2044 return 0;
2046 free (str);
2048 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] Found the head...\n");
2050 if (ebml_read_id (s, NULL) != MATROSKA_ID_SEGMENT)
2052 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] but no segment :(\n");
2053 return 0;
2055 ebml_read_length (s, NULL); /* return bytes number until EOF */
2057 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] + a segment...\n");
2059 mkv_d = calloc (1, sizeof (mkv_demuxer_t));
2060 demuxer->priv = mkv_d;
2061 mkv_d->tc_scale = 1000000;
2062 mkv_d->segment_start = stream_tell (s);
2063 mkv_d->parsed_cues = malloc (sizeof (off_t));
2064 mkv_d->parsed_seekhead = malloc (sizeof (off_t));
2066 while (!cont)
2068 switch (ebml_read_id (s, NULL))
2070 case MATROSKA_ID_INFO:
2071 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] |+ segment information...\n");
2072 cont = demux_mkv_read_info (demuxer);
2073 break;
2075 case MATROSKA_ID_TRACKS:
2076 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] |+ segment tracks...\n");
2077 cont = demux_mkv_read_tracks (demuxer);
2078 break;
2080 case MATROSKA_ID_CUES:
2081 cont = demux_mkv_read_cues (demuxer);
2082 break;
2084 case MATROSKA_ID_TAGS:
2085 cont = demux_mkv_read_tags (demuxer);
2086 break;
2088 case MATROSKA_ID_SEEKHEAD:
2089 cont = demux_mkv_read_seekhead (demuxer);
2090 break;
2092 case MATROSKA_ID_CHAPTERS:
2093 cont = demux_mkv_read_chapters (demuxer);
2094 break;
2096 case MATROSKA_ID_ATTACHMENTS:
2097 cont = demux_mkv_read_attachments (demuxer);
2098 break;
2100 case MATROSKA_ID_CLUSTER:
2102 int p, l;
2103 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] |+ found cluster, headers are "
2104 "parsed completely :)\n");
2105 /* get the first cluster timecode */
2106 p = stream_tell(s);
2107 l = ebml_read_length (s, NULL);
2108 while (ebml_read_id (s, NULL) != MATROSKA_ID_CLUSTERTIMECODE)
2110 ebml_read_skip (s, NULL);
2111 if (stream_tell (s) >= p + l)
2112 break;
2114 if (stream_tell (s) < p + l)
2116 uint64_t num = ebml_read_uint (s, NULL);
2117 if (num == EBML_UINT_INVALID)
2118 return 0;
2119 mkv_d->first_tc = num * mkv_d->tc_scale / 1000000.0;
2120 mkv_d->has_first_tc = 1;
2122 stream_seek (s, p - 4);
2123 cont = 1;
2124 break;
2127 default:
2128 cont = 1;
2129 case EBML_ID_VOID:
2130 ebml_read_skip (s, NULL);
2131 break;
2135 display_create_tracks (demuxer);
2137 /* select video track */
2138 track = NULL;
2139 if (demuxer->video->id == -1) /* automatically select a video track */
2141 /* search for a video track that has the 'default' flag set */
2142 for (i=0; i<mkv_d->num_tracks; i++)
2143 if (mkv_d->tracks[i]->type == MATROSKA_TRACK_VIDEO
2144 && mkv_d->tracks[i]->default_track)
2146 track = mkv_d->tracks[i];
2147 break;
2150 if (track == NULL)
2151 /* no track has the 'default' flag set */
2152 /* let's take the first video track */
2153 for (i=0; i<mkv_d->num_tracks; i++)
2154 if (mkv_d->tracks[i]->type == MATROSKA_TRACK_VIDEO)
2156 track = mkv_d->tracks[i];
2157 break;
2160 else if (demuxer->video->id != -2) /* -2 = no video at all */
2161 track = demux_mkv_find_track_by_num (mkv_d, demuxer->video->id,
2162 MATROSKA_TRACK_VIDEO);
2164 if (track && demuxer->v_streams[track->tnum])
2166 mp_msg (MSGT_DEMUX, MSGL_INFO,
2167 MSGTR_MPDEMUX_MKV_WillPlayVideoTrack, track->tnum);
2168 demuxer->video->id = track->tnum;
2169 demuxer->video->sh = demuxer->v_streams[track->tnum];
2171 else
2173 mp_msg (MSGT_DEMUX, MSGL_INFO, MSGTR_MPDEMUX_MKV_NoVideoTrackFound);
2174 demuxer->video->id = -2;
2177 /* select audio track */
2178 track = NULL;
2179 if (track == NULL)
2180 /* search for an audio track that has the 'default' flag set */
2181 for (i=0; i < mkv_d->num_tracks; i++)
2182 if (mkv_d->tracks[i]->type == MATROSKA_TRACK_AUDIO
2183 && mkv_d->tracks[i]->default_track)
2185 track = mkv_d->tracks[i];
2186 break;
2189 if (track == NULL)
2190 /* no track has the 'default' flag set */
2191 /* let's take the first audio track */
2192 for (i=0; i < mkv_d->num_tracks; i++)
2193 if (mkv_d->tracks[i]->type == MATROSKA_TRACK_AUDIO)
2195 track = mkv_d->tracks[i];
2196 break;
2199 if (track && demuxer->a_streams[track->tnum])
2201 demuxer->audio->id = track->tnum;
2202 demuxer->audio->sh = demuxer->a_streams[track->tnum];
2204 else
2206 mp_msg (MSGT_DEMUX, MSGL_INFO, MSGTR_MPDEMUX_MKV_NoAudioTrackFound);
2207 demuxer->audio->id = -2;
2211 if(demuxer->audio->id != -2)
2212 for (i=0; i < mkv_d->num_tracks; i++)
2214 if(mkv_d->tracks[i]->type != MATROSKA_TRACK_AUDIO)
2215 continue;
2216 if(demuxer->a_streams[track->tnum])
2218 mkv_d->last_aid++;
2219 if(mkv_d->last_aid == MAX_A_STREAMS)
2220 break;
2224 if (demuxer->chapters)
2226 for (i=0; i < (int)demuxer->num_chapters; i++)
2228 demuxer->chapters[i].start -= mkv_d->first_tc;
2229 demuxer->chapters[i].end -= mkv_d->first_tc;
2231 if (dvd_last_chapter > 0 && dvd_last_chapter <= demuxer->num_chapters)
2233 if (demuxer->chapters[dvd_last_chapter-1].end != 0)
2234 mkv_d->stop_timecode = demuxer->chapters[dvd_last_chapter-1].end;
2235 else if (dvd_last_chapter + 1 <= demuxer->num_chapters)
2236 mkv_d->stop_timecode = demuxer->chapters[dvd_last_chapter].start;
2240 if (s->end_pos == 0 || (mkv_d->indexes == NULL && index_mode < 0))
2241 demuxer->seekable = 0;
2242 else
2244 demuxer->movi_start = s->start_pos;
2245 demuxer->movi_end = s->end_pos;
2246 demuxer->seekable = 1;
2249 return DEMUXER_TYPE_MATROSKA;
2252 static void
2253 demux_close_mkv (demuxer_t *demuxer)
2255 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2257 if (mkv_d)
2259 int i;
2260 free_cached_dps (demuxer);
2261 if (mkv_d->tracks)
2263 for (i=0; i<mkv_d->num_tracks; i++)
2264 demux_mkv_free_trackentry(mkv_d->tracks[i]);
2265 free (mkv_d->tracks);
2267 free (mkv_d->indexes);
2268 free (mkv_d->cluster_positions);
2269 free (mkv_d->parsed_cues);
2270 free (mkv_d->parsed_seekhead);
2271 free (mkv_d);
2275 static int
2276 demux_mkv_read_block_lacing (uint8_t *buffer, uint64_t *size,
2277 uint8_t *laces, uint32_t **all_lace_sizes)
2279 uint32_t total = 0, *lace_size;
2280 uint8_t flags;
2281 int i;
2283 *all_lace_sizes = NULL;
2284 lace_size = NULL;
2285 /* lacing flags */
2286 flags = *buffer++;
2287 (*size)--;
2289 switch ((flags & 0x06) >> 1)
2291 case 0: /* no lacing */
2292 *laces = 1;
2293 lace_size = calloc(*laces, sizeof(uint32_t));
2294 lace_size[0] = *size;
2295 break;
2297 case 1: /* xiph lacing */
2298 case 2: /* fixed-size lacing */
2299 case 3: /* EBML lacing */
2300 *laces = *buffer++;
2301 (*size)--;
2302 (*laces)++;
2303 lace_size = calloc(*laces, sizeof(uint32_t));
2305 switch ((flags & 0x06) >> 1)
2307 case 1: /* xiph lacing */
2308 for (i=0; i < *laces-1; i++)
2310 lace_size[i] = 0;
2313 lace_size[i] += *buffer;
2314 (*size)--;
2315 } while (*buffer++ == 0xFF);
2316 total += lace_size[i];
2318 lace_size[i] = *size - total;
2319 break;
2321 case 2: /* fixed-size lacing */
2322 for (i=0; i < *laces; i++)
2323 lace_size[i] = *size / *laces;
2324 break;
2326 case 3: /* EBML lacing */
2328 int l;
2329 uint64_t num = ebml_read_vlen_uint (buffer, &l);
2330 if (num == EBML_UINT_INVALID) {
2331 free(lace_size);
2332 return 1;
2334 buffer += l;
2335 *size -= l;
2337 total = lace_size[0] = num;
2338 for (i=1; i < *laces-1; i++)
2340 int64_t snum;
2341 snum = ebml_read_vlen_int (buffer, &l);
2342 if (snum == EBML_INT_INVALID) {
2343 free(lace_size);
2344 return 1;
2346 buffer += l;
2347 *size -= l;
2348 lace_size[i] = lace_size[i-1] + snum;
2349 total += lace_size[i];
2351 lace_size[i] = *size - total;
2352 break;
2355 break;
2357 *all_lace_sizes = lace_size;
2358 return 0;
2361 static void
2362 handle_subtitles(demuxer_t *demuxer, mkv_track_t *track, char *block,
2363 int64_t size, uint64_t block_duration, uint64_t timecode)
2365 demux_packet_t *dp;
2367 if (block_duration == 0)
2369 mp_msg (MSGT_DEMUX, MSGL_WARN,
2370 MSGTR_MPDEMUX_MKV_NoBlockDurationForSubtitleTrackFound);
2371 return;
2374 sub_utf8 = 1;
2375 dp = new_demux_packet(size);
2376 memcpy(dp->buffer, block, size);
2377 dp->pts = timecode / 1000.0f;
2378 dp->endpts = (timecode + block_duration) / 1000.0f;
2379 ds_add_packet(demuxer->sub, dp);
2382 // Taken from demux_real.c. Thanks to the original developpers :)
2383 #define SKIP_BITS(n) buffer <<= n
2384 #define SHOW_BITS(n) ((buffer) >> (32 - (n)))
2386 static float real_fix_timestamp(mkv_track_t *track, unsigned char *s,
2387 int timestamp) {
2388 float v_pts;
2389 uint32_t buffer = (s[0] << 24) + (s[1] << 16) + (s[2] << 8) + s[3];
2390 int kf = timestamp;
2391 int pict_type;
2392 int orig_kf;
2394 if (!strcmp(track->codec_id, MKV_V_REALV30) ||
2395 !strcmp(track->codec_id, MKV_V_REALV40)) {
2397 if (!strcmp(track->codec_id, MKV_V_REALV30)) {
2398 SKIP_BITS(3);
2399 pict_type = SHOW_BITS(2);
2400 SKIP_BITS(2 + 7);
2401 }else{
2402 SKIP_BITS(1);
2403 pict_type = SHOW_BITS(2);
2404 SKIP_BITS(2 + 7 + 3);
2406 kf = SHOW_BITS(13); // kf= 2*SHOW_BITS(12);
2407 orig_kf = kf;
2408 if (pict_type <= 1) {
2409 // I frame, sync timestamps:
2410 track->rv_kf_base = timestamp - kf;
2411 mp_msg(MSGT_DEMUX, MSGL_DBG2, "\nTS: base=%08X\n", track->rv_kf_base);
2412 kf = timestamp;
2413 } else {
2414 // P/B frame, merge timestamps:
2415 int tmp = timestamp - track->rv_kf_base;
2416 kf |= tmp & (~0x1fff); // combine with packet timestamp
2417 if (kf < (tmp - 4096)) // workaround wrap-around problems
2418 kf += 8192;
2419 else if (kf > (tmp + 4096))
2420 kf -= 8192;
2421 kf += track->rv_kf_base;
2423 if (pict_type != 3) { // P || I frame -> swap timestamps
2424 int tmp = kf;
2425 kf = track->rv_kf_pts;
2426 track->rv_kf_pts = tmp;
2428 mp_msg(MSGT_DEMUX, MSGL_DBG2, "\nTS: %08X -> %08X (%04X) %d %02X %02X %02X "
2429 "%02X %5d\n", timestamp, kf, orig_kf, pict_type, s[0], s[1], s[2],
2430 s[3], kf - (int)(1000.0 * track->rv_pts));
2432 v_pts = kf * 0.001f;
2433 track->rv_pts = v_pts;
2435 return v_pts;
2438 static void
2439 handle_realvideo (demuxer_t *demuxer, mkv_track_t *track, uint8_t *buffer,
2440 uint32_t size, int block_bref)
2442 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2443 demux_packet_t *dp;
2444 uint32_t timestamp = mkv_d->last_pts * 1000;
2445 uint32_t *hdr;
2446 uint8_t chunks;
2447 int isize;
2448 #ifdef WORDS_BIGENDIAN
2449 uint8_t *p;
2450 int i;
2451 #endif
2453 chunks = *buffer++;
2454 isize = --size - (chunks+1)*8;
2455 dp = new_demux_packet (REALHEADER_SIZE + size);
2456 memcpy (dp->buffer + REALHEADER_SIZE, buffer + (chunks+1)*8, isize);
2457 #ifdef WORDS_BIGENDIAN
2458 p = (uint8_t *)(dp->buffer + REALHEADER_SIZE + isize);
2459 for (i = 0; i<(chunks+1)*8; i+=4) {
2460 p[i] = *((uint8_t *)buffer+i+3);
2461 p[i+1] = *((uint8_t *)buffer+i+2);
2462 p[i+2] = *((uint8_t *)buffer+i+1);
2463 p[i+3] = *((uint8_t *)buffer+i);
2465 #else
2466 memcpy (dp->buffer + REALHEADER_SIZE + isize, buffer, (chunks+1)*8);
2467 #endif
2469 hdr = dp->buffer;
2470 *hdr++ = chunks; // number of chunks
2471 *hdr++ = timestamp; // timestamp from packet header
2472 *hdr++ = isize; // length of actual data
2473 *hdr++ = REALHEADER_SIZE + isize; // offset to chunk offset array
2475 if (mkv_d->v_skip_to_keyframe)
2477 dp->pts = mkv_d->last_pts;
2478 track->rv_kf_base = 0;
2479 track->rv_kf_pts = timestamp;
2481 else
2482 dp->pts = real_fix_timestamp (track, dp->buffer + REALHEADER_SIZE,
2483 timestamp);
2484 dp->pos = demuxer->filepos;
2485 dp->flags = block_bref ? 0 : 0x10;
2487 ds_add_packet(demuxer->video, dp);
2490 static void
2491 handle_realaudio (demuxer_t *demuxer, mkv_track_t *track, uint8_t *buffer,
2492 uint32_t size, int block_bref)
2494 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2495 int sps = track->sub_packet_size;
2496 int sph = track->sub_packet_h;
2497 int cfs = track->coded_framesize;
2498 int w = track->audiopk_size;
2499 int spc = track->sub_packet_cnt;
2500 demux_packet_t *dp;
2501 int x;
2503 if ((track->a_formattag == mmioFOURCC('2', '8', '_', '8')) ||
2504 (track->a_formattag == mmioFOURCC('c', 'o', 'o', 'k')) ||
2505 (track->a_formattag == mmioFOURCC('a', 't', 'r', 'c')) ||
2506 (track->a_formattag == mmioFOURCC('s', 'i', 'p', 'r')))
2508 // if(!block_bref)
2509 // spc = track->sub_packet_cnt = 0;
2510 switch (track->a_formattag) {
2511 case mmioFOURCC('2', '8', '_', '8'):
2512 for (x = 0; x < sph / 2; x++)
2513 memcpy(track->audio_buf + x * 2 * w + spc * cfs, buffer + cfs * x, cfs);
2514 break;
2515 case mmioFOURCC('c', 'o', 'o', 'k'):
2516 case mmioFOURCC('a', 't', 'r', 'c'):
2517 for (x = 0; x < w / sps; x++)
2518 memcpy(track->audio_buf + sps * (sph * x + ((sph + 1) / 2) * (spc & 1) + (spc >> 1)), buffer + sps * x, sps);
2519 break;
2520 case mmioFOURCC('s', 'i', 'p', 'r'):
2521 memcpy(track->audio_buf + spc * w, buffer, w);
2522 if (spc == sph - 1)
2524 int n;
2525 int bs = sph * w * 2 / 96; // nibbles per subpacket
2526 // Perform reordering
2527 for(n=0; n < 38; n++)
2529 int j;
2530 int i = bs * sipr_swaps[n][0];
2531 int o = bs * sipr_swaps[n][1];
2532 // swap nibbles of block 'i' with 'o' TODO: optimize
2533 for(j = 0;j < bs; j++)
2535 int x = (i & 1) ? (track->audio_buf[i >> 1] >> 4) : (track->audio_buf[i >> 1] & 0x0F);
2536 int y = (o & 1) ? (track->audio_buf[o >> 1] >> 4) : (track->audio_buf[o >> 1] & 0x0F);
2537 if(o & 1)
2538 track->audio_buf[o >> 1] = (track->audio_buf[o >> 1] & 0x0F) | (x << 4);
2539 else
2540 track->audio_buf[o >> 1] = (track->audio_buf[o >> 1] & 0xF0) | x;
2541 if(i & 1)
2542 track->audio_buf[i >> 1] = (track->audio_buf[i >> 1] & 0x0F) | (y << 4);
2543 else
2544 track->audio_buf[i >> 1] = (track->audio_buf[i >> 1] & 0xF0) | y;
2545 ++i; ++o;
2549 break;
2551 track->audio_timestamp[track->sub_packet_cnt] = (track->ra_pts == mkv_d->last_pts) ? 0 : (mkv_d->last_pts);
2552 track->ra_pts = mkv_d->last_pts;
2553 if (track->sub_packet_cnt == 0)
2554 track->audio_filepos = demuxer->filepos;
2555 if (++(track->sub_packet_cnt) == sph)
2557 int apk_usize = ((WAVEFORMATEX*)((sh_audio_t*)demuxer->audio->sh)->wf)->nBlockAlign;
2558 track->sub_packet_cnt = 0;
2559 // Release all the audio packets
2560 for (x = 0; x < sph*w/apk_usize; x++)
2562 dp = new_demux_packet(apk_usize);
2563 memcpy(dp->buffer, track->audio_buf + x * apk_usize, apk_usize);
2564 /* Put timestamp only on packets that correspond to original audio packets in file */
2565 dp->pts = (x * apk_usize % w) ? 0 : track->audio_timestamp[x * apk_usize / w];
2566 dp->pos = track->audio_filepos; // all equal
2567 dp->flags = x ? 0 : 0x10; // Mark first packet as keyframe
2568 ds_add_packet(demuxer->audio, dp);
2571 } else { // Not a codec that require reordering
2572 dp = new_demux_packet (size);
2573 memcpy(dp->buffer, buffer, size);
2574 if (track->ra_pts == mkv_d->last_pts && !mkv_d->a_skip_to_keyframe)
2575 dp->pts = 0;
2576 else
2577 dp->pts = mkv_d->last_pts;
2578 track->ra_pts = mkv_d->last_pts;
2580 dp->pos = demuxer->filepos;
2581 dp->flags = block_bref ? 0 : 0x10;
2582 ds_add_packet (demuxer->audio, dp);
2586 /** Reorder timecodes and add cached demux packets to the queues.
2588 * Timecode reordering is needed if a video track contains B frames that
2589 * are timestamped in display order (e.g. MPEG-1, MPEG-2 or "native" MPEG-4).
2590 * MPlayer doesn't like timestamps in display order. This function adjusts
2591 * the timestamp of cached frames (which are exactly one I/P frame followed
2592 * by one or more B frames) so that they are in coding order again.
2594 * Example: The track with 25 FPS contains four frames with the timecodes
2595 * I at 0ms, P at 120ms, B at 40ms and B at 80ms. As soon as the next I
2596 * or P frame arrives these timecodes can be changed to I at 0ms, P at 40ms,
2597 * B at 80ms and B at 120ms.
2599 * This works for simple H.264 B-frame pyramids, but not for arbitrary orders.
2601 * \param demuxer The Matroska demuxer struct for this instance.
2602 * \param track The track structure whose cache should be handled.
2604 static void
2605 flush_cached_dps (demuxer_t *demuxer, mkv_track_t *track)
2607 int i, ok;
2609 if (track->num_cached_dps == 0)
2610 return;
2612 do {
2613 ok = 1;
2614 for (i = 1; i < track->num_cached_dps; i++)
2615 if (track->cached_dps[i - 1]->pts > track->cached_dps[i]->pts) {
2616 float tmp_pts = track->cached_dps[i - 1]->pts;
2617 track->cached_dps[i - 1]->pts = track->cached_dps[i]->pts;
2618 track->cached_dps[i]->pts = tmp_pts;
2619 ok = 0;
2621 } while (!ok);
2623 for (i = 0; i < track->num_cached_dps; i++)
2624 ds_add_packet (demuxer->video, track->cached_dps[i]);
2625 track->num_cached_dps = 0;
2628 /** Cache video frames if timecodes have to be reordered.
2630 * Timecode reordering is needed if a video track contains B frames that
2631 * are timestamped in display order (e.g. MPEG-1, MPEG-2 or "native" MPEG-4).
2632 * This function takes in a Matroska block read from the file, allocates a
2633 * demux packet for it, fills in its values, allocates space for storing
2634 * pointers to the cached demux packets and adds the packet to it. If
2635 * the packet contains an I or a P frame then ::flush_cached_dps is called
2636 * in order to send the old cached frames downstream.
2638 * \param demuxer The Matroska demuxer struct for this instance.
2639 * \param track The packet is meant for this track.
2640 * \param buffer The actual frame contents.
2641 * \param size The frame size in bytes.
2642 * \param block_bref A relative timecode (backward reference). If it is \c 0
2643 * then the frame is an I frame.
2644 * \param block_fref A relative timecode (forward reference). If it is \c 0
2645 * then the frame is either an I frame or a P frame depending on the value
2646 * of \a block_bref. Otherwise it's a B frame.
2648 static void
2649 handle_video_bframes (demuxer_t *demuxer, mkv_track_t *track, uint8_t *buffer,
2650 uint32_t size, int block_bref, int block_fref)
2652 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2653 demux_packet_t *dp;
2655 dp = new_demux_packet (size);
2656 memcpy(dp->buffer, buffer, size);
2657 dp->pos = demuxer->filepos;
2658 dp->pts = mkv_d->last_pts;
2659 if ((track->num_cached_dps > 0) && (dp->pts < track->max_pts))
2660 block_fref = 1;
2661 if (block_fref == 0) /* I or P frame */
2662 flush_cached_dps (demuxer, track);
2663 if (block_bref != 0) /* I frame, don't cache it */
2664 dp->flags = 0x10;
2665 if ((track->num_cached_dps + 1) > track->num_allocated_dps)
2667 track->cached_dps = (demux_packet_t **)
2668 realloc(track->cached_dps, (track->num_cached_dps + 10) *
2669 sizeof(demux_packet_t *));
2670 track->num_allocated_dps += 10;
2672 track->cached_dps[track->num_cached_dps] = dp;
2673 track->num_cached_dps++;
2674 if (dp->pts > track->max_pts)
2675 track->max_pts = dp->pts;
2678 static int
2679 handle_block (demuxer_t *demuxer, uint8_t *block, uint64_t length,
2680 uint64_t block_duration, int64_t block_bref, int64_t block_fref, uint8_t simpleblock)
2682 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2683 mkv_track_t *track = NULL;
2684 demux_stream_t *ds = NULL;
2685 uint64_t old_length;
2686 int64_t tc;
2687 uint32_t *lace_size;
2688 uint8_t laces, flags;
2689 int i, num, tmp, use_this_block = 1;
2690 float current_pts;
2691 int16_t time;
2693 /* first byte(s): track num */
2694 num = ebml_read_vlen_uint (block, &tmp);
2695 block += tmp;
2696 /* time (relative to cluster time) */
2697 time = block[0] << 8 | block[1];
2698 block += 2;
2699 length -= tmp + 2;
2700 old_length = length;
2701 flags = block[0];
2702 if (demux_mkv_read_block_lacing (block, &length, &laces, &lace_size))
2703 return 0;
2704 block += old_length - length;
2706 tc = ((time*mkv_d->tc_scale+mkv_d->cluster_tc) /1000000.0 - mkv_d->first_tc);
2707 if (tc < 0)
2708 tc = 0;
2709 if (mkv_d->stop_timecode > 0 && tc > mkv_d->stop_timecode) {
2710 free(lace_size);
2711 return -1;
2713 current_pts = tc / 1000.0;
2715 for (i=0; i<mkv_d->num_tracks; i++)
2716 if (mkv_d->tracks[i]->tnum == num) {
2717 track = mkv_d->tracks[i];
2718 break;
2720 if (track == NULL)
2722 free(lace_size);
2723 return 1;
2725 if (num == demuxer->audio->id)
2727 ds = demuxer->audio;
2729 if (mkv_d->a_skip_to_keyframe)
2731 if (simpleblock)
2733 if (!(flags&0x80)) /*current frame isn't a keyframe*/
2734 use_this_block = 0;
2736 else if (block_bref != 0)
2737 use_this_block = 0;
2739 else if (mkv_d->v_skip_to_keyframe)
2740 use_this_block = 0;
2742 if (track->fix_i_bps && use_this_block)
2744 sh_audio_t *sh = (sh_audio_t *) ds->sh;
2746 if (block_duration != 0)
2748 sh->i_bps = length * 1000 / block_duration;
2749 track->fix_i_bps = 0;
2751 else if (track->qt_last_a_pts == 0.0)
2752 track->qt_last_a_pts = current_pts;
2753 else if(track->qt_last_a_pts != current_pts)
2755 sh->i_bps = length / (current_pts - track->qt_last_a_pts);
2756 track->fix_i_bps = 0;
2760 else if (tc < mkv_d->skip_to_timecode)
2761 use_this_block = 0;
2762 else if (num == demuxer->video->id)
2764 ds = demuxer->video;
2765 if (mkv_d->v_skip_to_keyframe)
2767 if (simpleblock)
2769 if (!(flags&0x80)) /*current frame isn't a keyframe*/
2770 use_this_block = 0;
2772 else if (block_bref != 0 || block_fref != 0)
2773 use_this_block = 0;
2776 else if (num == demuxer->sub->id)
2778 ds = demuxer->sub;
2779 if (track->subtitle_type != MATROSKA_SUBTYPE_VOBSUB)
2781 if (!mkv_d->v_skip_to_keyframe)
2782 handle_subtitles (demuxer, track, block, length,
2783 block_duration, tc);
2784 use_this_block = 0;
2787 else
2788 use_this_block = 0;
2790 if (use_this_block)
2792 mkv_d->last_pts = current_pts;
2793 mkv_d->last_filepos = demuxer->filepos;
2795 for (i=0; i < laces; i++)
2797 if (ds == demuxer->video && track->realmedia)
2798 handle_realvideo (demuxer, track, block, lace_size[i], block_bref);
2799 else if (ds == demuxer->audio && track->realmedia)
2800 handle_realaudio (demuxer, track, block, lace_size[i], block_bref);
2801 else if (ds == demuxer->video && track->reorder_timecodes)
2802 handle_video_bframes (demuxer, track, block, lace_size[i],
2803 block_bref, block_fref);
2804 else
2806 int modified, size = lace_size[i];
2807 demux_packet_t *dp;
2808 uint8_t *buffer;
2809 modified = demux_mkv_decode (track, block, &buffer, &size, 1);
2810 if (buffer)
2812 dp = new_demux_packet (size);
2813 memcpy (dp->buffer, buffer, size);
2814 if (modified)
2815 free (buffer);
2816 dp->flags = (block_bref == 0 && block_fref == 0) ? 0x10 : 0;
2817 /* If default_duration is 0, assume no pts value is known
2818 * for packets after the first one (rather than all pts
2819 * values being the same) */
2820 if (i == 0 || track->default_duration)
2821 dp->pts = mkv_d->last_pts + i * track->default_duration;
2822 ds_add_packet (ds, dp);
2825 block += lace_size[i];
2828 if (ds == demuxer->video)
2830 mkv_d->v_skip_to_keyframe = 0;
2831 mkv_d->skip_to_timecode = 0;
2833 else if (ds == demuxer->audio)
2834 mkv_d->a_skip_to_keyframe = 0;
2836 free(lace_size);
2837 return 1;
2840 free(lace_size);
2841 return 0;
2844 static int
2845 demux_mkv_fill_buffer (demuxer_t *demuxer, demux_stream_t *ds)
2847 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2848 stream_t *s = demuxer->stream;
2849 uint64_t l;
2850 int il, tmp;
2852 while (1)
2854 while (mkv_d->cluster_size > 0)
2856 uint64_t block_duration = 0, block_length = 0;
2857 int64_t block_bref = 0, block_fref = 0;
2858 uint8_t *block = NULL;
2860 while (mkv_d->blockgroup_size > 0)
2862 switch (ebml_read_id (s, &il))
2864 case MATROSKA_ID_BLOCKDURATION:
2866 block_duration = ebml_read_uint (s, &l);
2867 if (block_duration == EBML_UINT_INVALID) {
2868 free(block);
2869 return 0;
2871 block_duration *= mkv_d->tc_scale / 1000000.0;
2872 break;
2875 case MATROSKA_ID_BLOCK:
2876 block_length = ebml_read_length (s, &tmp);
2877 free(block);
2878 if (block_length > SIZE_MAX - LZO_INPUT_PADDING) return 0;
2879 block = malloc (block_length + LZO_INPUT_PADDING);
2880 demuxer->filepos = stream_tell (s);
2881 if (stream_read (s,block,block_length) != (int) block_length)
2883 free(block);
2884 return 0;
2886 l = tmp + block_length;
2887 break;
2889 case MATROSKA_ID_REFERENCEBLOCK:
2891 int64_t num = ebml_read_int (s, &l);
2892 if (num == EBML_INT_INVALID) {
2893 free(block);
2894 return 0;
2896 if (num <= 0)
2897 block_bref = num;
2898 else
2899 block_fref = num;
2900 break;
2903 case EBML_ID_INVALID:
2904 free(block);
2905 return 0;
2907 default:
2908 ebml_read_skip (s, &l);
2909 break;
2911 mkv_d->blockgroup_size -= l + il;
2912 mkv_d->cluster_size -= l + il;
2915 if (block)
2917 int res = handle_block (demuxer, block, block_length,
2918 block_duration, block_bref, block_fref, 0);
2919 free (block);
2920 if (res < 0)
2921 return 0;
2922 if (res)
2923 return 1;
2926 if (mkv_d->cluster_size > 0)
2928 switch (ebml_read_id (s, &il))
2930 case MATROSKA_ID_CLUSTERTIMECODE:
2932 uint64_t num = ebml_read_uint (s, &l);
2933 if (num == EBML_UINT_INVALID)
2934 return 0;
2935 if (!mkv_d->has_first_tc)
2937 mkv_d->first_tc = num * mkv_d->tc_scale / 1000000.0;
2938 mkv_d->has_first_tc = 1;
2940 mkv_d->cluster_tc = num * mkv_d->tc_scale;
2941 break;
2944 case MATROSKA_ID_BLOCKGROUP:
2945 mkv_d->blockgroup_size = ebml_read_length (s, &tmp);
2946 l = tmp;
2947 break;
2949 case MATROSKA_ID_SIMPLEBLOCK:
2951 int res;
2952 block_length = ebml_read_length (s, &tmp);
2953 block = malloc (block_length);
2954 demuxer->filepos = stream_tell (s);
2955 if (stream_read (s,block,block_length) != (int) block_length)
2957 free(block);
2958 return 0;
2960 l = tmp + block_length;
2961 res = handle_block (demuxer, block, block_length,
2962 block_duration, block_bref, block_fref, 1);
2963 free (block);
2964 mkv_d->cluster_size -= l + il;
2965 if (res < 0)
2966 return 0;
2967 else if (res)
2968 return 1;
2969 else mkv_d->cluster_size += l + il;
2970 break;
2972 case EBML_ID_INVALID:
2973 return 0;
2975 default:
2976 ebml_read_skip (s, &l);
2977 break;
2979 mkv_d->cluster_size -= l + il;
2983 if (ebml_read_id (s, &il) != MATROSKA_ID_CLUSTER)
2984 return 0;
2985 add_cluster_position(mkv_d, stream_tell(s)-il);
2986 mkv_d->cluster_size = ebml_read_length (s, NULL);
2989 return 0;
2992 static void
2993 demux_mkv_seek (demuxer_t *demuxer, float rel_seek_secs, float audio_delay, int flags)
2995 free_cached_dps (demuxer);
2996 if (!(flags & SEEK_FACTOR)) /* time in secs */
2998 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2999 stream_t *s = demuxer->stream;
3000 int64_t target_timecode = 0, diff, min_diff=0xFFFFFFFFFFFFFFFLL;
3001 int i;
3003 if (!(flags & SEEK_ABSOLUTE)) /* relative seek */
3004 target_timecode = (int64_t) (mkv_d->last_pts * 1000.0);
3005 target_timecode += (int64_t)(rel_seek_secs * 1000.0);
3006 if (target_timecode < 0)
3007 target_timecode = 0;
3009 if (mkv_d->indexes == NULL) /* no index was found */
3011 uint64_t target_filepos, cluster_pos, max_pos;
3013 target_filepos = (uint64_t) (target_timecode * mkv_d->last_filepos
3014 / (mkv_d->last_pts * 1000.0));
3016 max_pos = mkv_d->cluster_positions[mkv_d->num_cluster_pos-1];
3017 if (target_filepos > max_pos)
3019 if ((off_t) max_pos > stream_tell (s))
3020 stream_seek (s, max_pos);
3021 else
3022 stream_seek (s, stream_tell (s) + mkv_d->cluster_size);
3023 /* parse all the clusters upto target_filepos */
3024 while (!s->eof && stream_tell(s) < (off_t) target_filepos)
3026 switch (ebml_read_id (s, &i))
3028 case MATROSKA_ID_CLUSTER:
3029 add_cluster_position(mkv_d, (uint64_t) stream_tell(s)-i);
3030 break;
3032 case MATROSKA_ID_CUES:
3033 demux_mkv_read_cues (demuxer);
3034 break;
3036 ebml_read_skip (s, NULL);
3038 if (s->eof)
3039 stream_reset(s);
3042 if (mkv_d->indexes == NULL)
3044 cluster_pos = mkv_d->cluster_positions[0];
3045 /* Let's find the nearest cluster */
3046 for (i=0; i < mkv_d->num_cluster_pos; i++)
3048 diff = mkv_d->cluster_positions[i] - target_filepos;
3049 if (rel_seek_secs < 0 && diff < 0 && -diff < min_diff)
3051 cluster_pos = mkv_d->cluster_positions[i];
3052 min_diff = -diff;
3054 else if (rel_seek_secs > 0
3055 && (diff < 0 ? -1 * diff : diff) < min_diff)
3057 cluster_pos = mkv_d->cluster_positions[i];
3058 min_diff = diff < 0 ? -1 * diff : diff;
3061 mkv_d->cluster_size = mkv_d->blockgroup_size = 0;
3062 stream_seek (s, cluster_pos);
3065 else
3067 mkv_index_t *index = NULL;
3068 int seek_id = (demuxer->video->id < 0) ? demuxer->audio->id : demuxer->video->id;
3070 /* let's find the entry in the indexes with the smallest */
3071 /* difference to the wanted timecode. */
3072 for (i=0; i < mkv_d->num_indexes; i++)
3073 if (mkv_d->indexes[i].tnum == seek_id)
3075 diff = target_timecode + mkv_d->first_tc -
3076 (int64_t) mkv_d->indexes[i].timecode * mkv_d->tc_scale / 1000000.0;
3078 if ((flags & SEEK_ABSOLUTE || target_timecode <= mkv_d->last_pts*1000)) {
3079 // Absolute seek or seek backward: find the last index
3080 // position before target time
3081 if (diff < 0 || diff >= min_diff)
3082 continue;
3084 else {
3085 // Relative seek forward: find the first index position
3086 // after target time. If no such index exists, find last
3087 // position between current position and target time.
3088 if (diff <= 0) {
3089 if (min_diff <= 0 && diff <= min_diff)
3090 continue;
3092 else if (diff >= FFMIN(target_timecode - mkv_d->last_pts,
3093 min_diff))
3094 continue;
3096 min_diff = diff;
3097 index = mkv_d->indexes + i;
3100 if (index) /* We've found an entry. */
3102 mkv_d->cluster_size = mkv_d->blockgroup_size = 0;
3103 stream_seek (s, index->filepos);
3107 if (demuxer->video->id >= 0)
3108 mkv_d->v_skip_to_keyframe = 1;
3109 if (rel_seek_secs > 0.0)
3110 mkv_d->skip_to_timecode = target_timecode;
3111 mkv_d->a_skip_to_keyframe = 1;
3113 demux_mkv_fill_buffer(demuxer, NULL);
3115 else if ((demuxer->movi_end <= 0) || !(flags & SEEK_ABSOLUTE))
3116 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] seek unsupported flags\n");
3117 else
3119 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
3120 stream_t *s = demuxer->stream;
3121 uint64_t target_filepos;
3122 mkv_index_t *index = NULL;
3123 int i;
3125 if (mkv_d->indexes == NULL) /* no index was found */
3126 { /* I'm lazy... */
3127 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] seek unsupported flags\n");
3128 return;
3131 target_filepos = (uint64_t)(demuxer->movi_end * rel_seek_secs);
3132 for (i=0; i < mkv_d->num_indexes; i++)
3133 if (mkv_d->indexes[i].tnum == demuxer->video->id)
3134 if ((index == NULL) ||
3135 ((mkv_d->indexes[i].filepos >= target_filepos) &&
3136 ((index->filepos < target_filepos) ||
3137 (mkv_d->indexes[i].filepos < index->filepos))))
3138 index = &mkv_d->indexes[i];
3140 if (!index)
3141 return;
3143 mkv_d->cluster_size = mkv_d->blockgroup_size = 0;
3144 stream_seek (s, index->filepos);
3146 if (demuxer->video->id >= 0)
3147 mkv_d->v_skip_to_keyframe = 1;
3148 mkv_d->skip_to_timecode = index->timecode;
3149 mkv_d->a_skip_to_keyframe = 1;
3151 demux_mkv_fill_buffer(demuxer, NULL);
3155 static int
3156 demux_mkv_control (demuxer_t *demuxer, int cmd, void *arg)
3158 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
3160 switch (cmd)
3162 case DEMUXER_CTRL_CORRECT_PTS:
3163 return DEMUXER_CTRL_OK;
3164 case DEMUXER_CTRL_GET_TIME_LENGTH:
3165 if (mkv_d->duration == 0)
3166 return DEMUXER_CTRL_DONTKNOW;
3168 *((double *)arg) = (double)mkv_d->duration;
3169 return DEMUXER_CTRL_OK;
3171 case DEMUXER_CTRL_GET_PERCENT_POS:
3172 if (mkv_d->duration == 0)
3174 return DEMUXER_CTRL_DONTKNOW;
3177 *((int *) arg) = (int) (100 * mkv_d->last_pts / mkv_d->duration);
3178 return DEMUXER_CTRL_OK;
3180 case DEMUXER_CTRL_SWITCH_AUDIO:
3181 if (demuxer->audio && demuxer->audio->sh) {
3182 sh_audio_t *sh = demuxer->a_streams[demuxer->audio->id];
3183 int aid = *(int*)arg;
3184 if (aid < 0)
3185 aid = (sh->aid + 1) % mkv_d->last_aid;
3186 if (aid != sh->aid) {
3187 mkv_track_t *track = demux_mkv_find_track_by_num (mkv_d, aid, MATROSKA_TRACK_AUDIO);
3188 if (track) {
3189 demuxer->audio->id = track->tnum;
3190 sh = demuxer->a_streams[demuxer->audio->id];
3191 ds_free_packs(demuxer->audio);
3194 *(int*)arg = sh->aid;
3195 } else
3196 *(int*)arg = -2;
3197 return DEMUXER_CTRL_OK;
3199 default:
3200 return DEMUXER_CTRL_NOTIMPL;
3204 const demuxer_desc_t demuxer_desc_matroska = {
3205 "Matroska demuxer",
3206 "mkv",
3207 "Matroska",
3208 "Aurelien Jacobs",
3210 DEMUXER_TYPE_MATROSKA,
3211 1, // safe autodetect
3212 demux_mkv_open,
3213 demux_mkv_fill_buffer,
3214 NULL,
3215 demux_close_mkv,
3216 demux_mkv_seek,
3217 demux_mkv_control