Add explanatory comments to the #endif part of multiple inclusion guards.
[mplayer/greg.git] / libmpdemux / demux_mkv.c
blobe7307156ca5c851a71e62d46a90b6ed17f8a7feb
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 USE_QTX_CODECS
35 #include "loader/qtx/qtxsdk/components.h"
36 #endif
38 #ifdef HAVE_ZLIB
39 #include <zlib.h>
40 #endif
42 #ifdef USE_LIBAVUTIL_SO
43 #include <ffmpeg/lzo.h>
44 #include <ffmpeg/intreadwrite.h>
45 #else
46 #include "libavutil/lzo.h"
47 #include "libavutil/intreadwrite.h"
48 #endif
49 #include "libavutil/avstring.h"
51 static unsigned char sipr_swaps[38][2]={
52 {0,63},{1,22},{2,44},{3,90},{5,81},{7,31},{8,86},{9,58},{10,36},{12,68},
53 {13,39},{14,73},{15,53},{16,69},{17,57},{19,88},{20,34},{21,71},{24,46},
54 {25,94},{26,54},{28,75},{29,50},{32,70},{33,92},{35,74},{38,85},{40,56},
55 {42,87},{43,65},{45,59},{48,79},{49,93},{51,89},{55,95},{61,76},{67,83},
56 {77,80} };
58 // Map flavour to bytes per second
59 #define SIPR_FLAVORS 4
60 #define ATRC_FLAVORS 8
61 #define COOK_FLAVORS 34
62 static int sipr_fl2bps[SIPR_FLAVORS] = {813, 1062, 625, 2000};
63 static int atrc_fl2bps[ATRC_FLAVORS] = {8269, 11714, 13092, 16538, 18260, 22050, 33075, 44100};
64 static int cook_fl2bps[COOK_FLAVORS] = {1000, 1378, 2024, 2584, 4005, 5513, 8010, 4005, 750, 2498,
65 4048, 5513, 8010, 11973, 8010, 2584, 4005, 2067, 2584, 2584,
66 4005, 4005, 5513, 5513, 8010, 12059, 1550, 8010, 12059, 5513,
67 12016, 16408, 22911, 33506};
69 typedef struct
71 uint32_t order, type, scope;
72 uint32_t comp_algo;
73 uint8_t *comp_settings;
74 int comp_settings_len;
75 } mkv_content_encoding_t;
77 typedef struct mkv_track
79 int tnum;
80 char *name;
82 char *codec_id;
83 int ms_compat;
84 char *language;
86 int type;
88 uint32_t v_width, v_height, v_dwidth, v_dheight;
89 float v_frate;
91 uint32_t a_formattag;
92 uint32_t a_channels, a_bps;
93 float a_sfreq;
95 float default_duration;
97 int default_track;
99 void *private_data;
100 unsigned int private_size;
102 /* stuff for realmedia */
103 int realmedia;
104 int rv_kf_base, rv_kf_pts;
105 float rv_pts; /* previous video timestamp */
106 float ra_pts; /* previous audio timestamp */
108 /** realaudio descrambling */
109 int sub_packet_size; ///< sub packet size, per stream
110 int sub_packet_h; ///< number of coded frames per block
111 int coded_framesize; ///< coded frame size, per stream
112 int audiopk_size; ///< audio packet size
113 unsigned char *audio_buf; ///< place to store reordered audio data
114 float *audio_timestamp; ///< timestamp for each audio packet
115 int sub_packet_cnt; ///< number of subpacket already received
116 int audio_filepos; ///< file position of first audio packet in block
118 /* stuff for quicktime */
119 int fix_i_bps;
120 float qt_last_a_pts;
122 int subtitle_type;
124 /* The timecodes of video frames might have to be reordered if they're
125 in display order (the timecodes, not the frames themselves!). In this
126 case demux packets have to be cached with the help of these variables. */
127 int reorder_timecodes;
128 demux_packet_t **cached_dps;
129 int num_cached_dps, num_allocated_dps;
130 float max_pts;
132 /* generic content encoding support */
133 mkv_content_encoding_t *encodings;
134 int num_encodings;
136 /* For VobSubs and SSA/ASS */
137 sh_sub_t *sh_sub;
138 } mkv_track_t;
140 typedef struct mkv_index
142 int tnum;
143 uint64_t timecode, filepos;
144 } mkv_index_t;
146 typedef struct mkv_attachment
148 char* name;
149 char* mime;
150 uint64_t uid;
151 void* data;
152 unsigned int data_size;
153 } mkv_attachment_t;
155 typedef struct mkv_demuxer
157 off_t segment_start;
159 float duration, last_pts;
160 uint64_t last_filepos;
162 mkv_track_t **tracks;
163 int num_tracks;
165 uint64_t tc_scale, cluster_tc, first_tc;
166 int has_first_tc;
168 uint64_t cluster_size;
169 uint64_t blockgroup_size;
171 mkv_index_t *indexes;
172 int num_indexes;
174 off_t *parsed_cues;
175 int parsed_cues_num;
176 off_t *parsed_seekhead;
177 int parsed_seekhead_num;
179 uint64_t *cluster_positions;
180 int num_cluster_pos;
182 int64_t skip_to_timecode;
183 int v_skip_to_keyframe, a_skip_to_keyframe;
185 int64_t stop_timecode;
187 int last_aid;
188 int audio_tracks[MAX_A_STREAMS];
190 mkv_attachment_t *attachments;
191 int num_attachments;
192 } mkv_demuxer_t;
194 #define REALHEADER_SIZE 16
195 #define RVPROPERTIES_SIZE 34
196 #define RAPROPERTIES4_SIZE 56
197 #define RAPROPERTIES5_SIZE 70
199 /* for e.g. "-slang ger" */
200 extern char *dvdsub_lang;
201 extern char *audio_lang;
202 extern int dvdsub_id;
205 * \brief ensures there is space for at least one additional element
206 * \param array array to grow
207 * \param nelem current number of elements in array
208 * \param elsize size of one array element
210 static void grow_array(void **array, int nelem, size_t elsize) {
211 if (!(nelem & 31))
212 *array = realloc(*array, (nelem + 32) * elsize);
215 static mkv_track_t *
216 demux_mkv_find_track_by_num (mkv_demuxer_t *d, int n, int type)
218 int i, id;
220 for (i=0, id=0; i < d->num_tracks; i++)
221 if (d->tracks[i] != NULL && d->tracks[i]->type == type)
222 if (id++ == n)
223 return d->tracks[i];
225 return NULL;
228 static mkv_track_t *
229 demux_mkv_find_track_by_language (mkv_demuxer_t *d, char *language, int type)
231 int i, len;
233 language += strspn(language,",");
234 while((len = strcspn(language,",")) > 0)
236 for (i=0; i < d->num_tracks; i++)
237 if (d->tracks[i] != NULL && d->tracks[i]->language != NULL &&
238 d->tracks[i]->type == type &&
239 !strncmp(d->tracks[i]->language, language, len))
240 return d->tracks[i];
241 language += len;
242 language += strspn(language,",");
245 return NULL;
248 static void
249 add_cluster_position (mkv_demuxer_t *mkv_d, uint64_t position)
251 int i = mkv_d->num_cluster_pos;
253 while (i--)
254 if (mkv_d->cluster_positions[i] == position)
255 return;
257 grow_array(&mkv_d->cluster_positions, mkv_d->num_cluster_pos,
258 sizeof(uint64_t));
259 mkv_d->cluster_positions[mkv_d->num_cluster_pos++] = position;
263 #define AAC_SYNC_EXTENSION_TYPE 0x02b7
264 static int
265 aac_get_sample_rate_index (uint32_t sample_rate)
267 if (92017 <= sample_rate)
268 return 0;
269 else if (75132 <= sample_rate)
270 return 1;
271 else if (55426 <= sample_rate)
272 return 2;
273 else if (46009 <= sample_rate)
274 return 3;
275 else if (37566 <= sample_rate)
276 return 4;
277 else if (27713 <= sample_rate)
278 return 5;
279 else if (23004 <= sample_rate)
280 return 6;
281 else if (18783 <= sample_rate)
282 return 7;
283 else if (13856 <= sample_rate)
284 return 8;
285 else if (11502 <= sample_rate)
286 return 9;
287 else if (9391 <= sample_rate)
288 return 10;
289 else
290 return 11;
294 static int
295 vobsub_parse_size (sh_sub_t *sh, const char *start)
297 if (sscanf(&start[6], "%dx%d", &sh->width, &sh->height) == 2)
299 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] VobSub size: %ux%u\n",
300 sh->width, sh->height);
301 return 1;
303 return 0;
306 static int
307 vobsub_parse_palette (sh_sub_t *sh, const char *start)
309 int i;
311 start += 8;
312 while (isspace(*start))
313 start++;
314 for (i = 0; i < 16; i++)
316 unsigned int tmp;
317 if (sscanf(start, "%06x", &tmp) != 1)
318 break;
319 sh->palette[i] = vobsub_palette_to_yuv(tmp);
320 start += 6;
321 while ((*start == ',') || isspace(*start))
322 start++;
324 if (i == 16)
326 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] VobSub palette: %06x,%06x,"
327 "%06x,%06x,%06x,%06x,%06x,%06x,%06x,%06x,%06x,%06x,%06x,"
328 "%06x,%06x,%06x\n", sh->palette[0],
329 sh->palette[1], sh->palette[2],
330 sh->palette[3], sh->palette[4],
331 sh->palette[5], sh->palette[6],
332 sh->palette[7], sh->palette[8],
333 sh->palette[9], sh->palette[10],
334 sh->palette[11], sh->palette[12],
335 sh->palette[13], sh->palette[14],
336 sh->palette[15]);
337 sh->has_palette = 1;
338 return 2;
340 return 0;
343 static int
344 vobsub_parse_custom_colors (sh_sub_t *sh, const char *start)
346 int use_custom_colors, i;
347 const char *p;
348 unsigned int tridx = 0;
350 use_custom_colors = 0;
351 start += 14;
352 while (isspace(*start))
353 start++;
354 if (!strncasecmp(start, "ON", 2) || (*start == '1'))
355 use_custom_colors = 1;
356 else if (!strncasecmp(start, "OFF", 3) || (*start == '0'))
357 use_custom_colors = 0;
358 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] VobSub custom colors: %s\n",
359 use_custom_colors ? "ON" : "OFF");
360 if ((p = strstr(start, "tridx:")) != NULL)
361 tridx = strtoul(p + 6, NULL, 2);
362 if ((start = strstr(start, "colors:")) != NULL)
364 start += 7;
365 while (isspace(*start))
366 start++;
367 for (i = 0; i < 4; i++)
369 unsigned int tmp;
370 if (sscanf(start, "%06x", &tmp) != 1)
371 break;
372 sh->colors[i] = vobsub_rgb_to_yuv(tmp);
373 if ((tridx << i) & 0x08)
374 sh->colors[i] |= 1 << 31;
375 start += 6;
376 while ((*start == ',') || isspace(*start))
377 start++;
379 if (i == 4)
381 sh->custom_colors = 4;
382 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] VobSub colors: %08x,"
383 "%08x,%08x,%08x\n", sh->colors[0],
384 sh->colors[1], sh->colors[2],
385 sh->colors[3]);
388 if (!use_custom_colors)
389 sh->custom_colors = 0;
390 return 4;
393 static int
394 vobsub_parse_forced_subs (sh_sub_t *sh, const char *start)
396 start += 12;
397 while (isspace(*start))
398 start++;
399 if (!strncasecmp(start, "on", 2) || (*start == '1'))
400 sh->forced_subs_only = 1;
401 else if (!strncasecmp(start, "off", 3) || (*start == '0'))
402 sh->forced_subs_only = 0;
403 else
404 return 0;
405 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] VobSub forced subs: %d\n",
406 sh->forced_subs_only);
407 return 8;
410 /** \brief Free cached demux packets
412 * Reordering the timecodes requires caching of demux packets. This function
413 * frees all these cached packets and the memory for the cached pointers
414 * itself.
416 * \param demuxer The demuxer for which the cache is to be freed.
418 static void
419 free_cached_dps (demuxer_t *demuxer)
421 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
422 mkv_track_t *track;
423 int i, k;
425 for (k = 0; k < mkv_d->num_tracks; k++)
427 track = mkv_d->tracks[k];
428 for (i = 0; i < track->num_cached_dps; i++)
429 free_demux_packet (track->cached_dps[i]);
430 free(track->cached_dps);
431 track->cached_dps = NULL;
432 track->num_cached_dps = 0;
433 track->num_allocated_dps = 0;
434 track->max_pts = 0;
438 static int
439 demux_mkv_parse_idx (mkv_track_t *t)
441 int things_found, last;
442 char *buf, *pos, *start;
444 if ((t->private_data == NULL) || (t->private_size == 0))
445 return 0;
447 things_found = 0;
448 buf = malloc(t->private_size + 1);
449 if (buf == NULL)
450 return 0;
451 memcpy(buf, t->private_data, t->private_size);
452 buf[t->private_size] = 0;
453 t->sh_sub->has_palette = 0;
455 pos = buf;
456 start = buf;
457 last = 0;
460 if ((*pos == 0) || (*pos == '\r') || (*pos == '\n'))
462 if (*pos == 0)
463 last = 1;
464 *pos = 0;
466 if (!strncasecmp(start, "size: ", 6))
467 things_found |= vobsub_parse_size(t->sh_sub, start);
468 else if (!strncasecmp(start, "palette:", 8))
469 things_found |= vobsub_parse_palette(t->sh_sub, start);
470 else if (!strncasecmp(start, "custom colors:", 14))
471 things_found |= vobsub_parse_custom_colors(t->sh_sub, start);
472 else if (!strncasecmp(start, "forced subs:", 12))
473 things_found |= vobsub_parse_forced_subs(t->sh_sub, start);
475 if (last)
476 break;
479 pos++;
481 while ((*pos == '\r') || (*pos == '\n'));
482 start = pos;
484 else
485 pos++;
487 while (!last && (*start != 0));
489 free(buf);
491 return (things_found & 3) == 3;
495 static int
496 demux_mkv_decode (mkv_track_t *track, uint8_t *src, uint8_t **dest,
497 uint32_t *size, uint32_t type)
499 int i, result;
500 int modified = 0;
502 *dest = src;
503 if (track->num_encodings <= 0)
504 return 0;
506 for (i=0; i<track->num_encodings; i++)
508 if (!(track->encodings[i].scope & type))
509 continue;
511 #ifdef HAVE_ZLIB
512 if (track->encodings[i].comp_algo == 0)
514 /* zlib encoded track */
515 z_stream zstream;
517 zstream.zalloc = (alloc_func) 0;
518 zstream.zfree = (free_func) 0;
519 zstream.opaque = (voidpf) 0;
520 if (inflateInit (&zstream) != Z_OK)
522 mp_msg (MSGT_DEMUX, MSGL_WARN,
523 MSGTR_MPDEMUX_MKV_ZlibInitializationFailed);
524 return modified;
526 zstream.next_in = (Bytef *) src;
527 zstream.avail_in = *size;
529 modified = 1;
530 *dest = NULL;
531 zstream.avail_out = *size;
532 do {
533 *size += 4000;
534 *dest = realloc (*dest, *size);
535 zstream.next_out = (Bytef *) (*dest + zstream.total_out);
536 result = inflate (&zstream, Z_NO_FLUSH);
537 if (result != Z_OK && result != Z_STREAM_END)
539 mp_msg (MSGT_DEMUX, MSGL_WARN,
540 MSGTR_MPDEMUX_MKV_ZlibDecompressionFailed);
541 free(*dest);
542 *dest = NULL;
543 inflateEnd (&zstream);
544 return modified;
546 zstream.avail_out += 4000;
547 } while (zstream.avail_out == 4000 &&
548 zstream.avail_in != 0 && result != Z_STREAM_END);
550 *size = zstream.total_out;
551 inflateEnd (&zstream);
553 #endif
554 if (track->encodings[i].comp_algo == 2)
556 /* lzo encoded track */
557 int dstlen = *size * 3;
559 *dest = NULL;
560 while (1)
562 int srclen = *size;
563 if (dstlen > SIZE_MAX - LZO_OUTPUT_PADDING) goto lzo_fail;
564 *dest = realloc (*dest, dstlen + LZO_OUTPUT_PADDING);
565 result = lzo1x_decode (*dest, &dstlen, src, &srclen);
566 if (result == 0)
567 break;
568 if (!(result & LZO_OUTPUT_FULL))
570 lzo_fail:
571 mp_msg (MSGT_DEMUX, MSGL_WARN,
572 MSGTR_MPDEMUX_MKV_LzoDecompressionFailed);
573 free(*dest);
574 *dest = NULL;
575 return modified;
577 mp_msg (MSGT_DEMUX, MSGL_DBG2,
578 "[mkv] lzo decompression buffer too small.\n");
579 dstlen *= 2;
581 *size = dstlen;
585 return modified;
589 static int
590 demux_mkv_read_info (demuxer_t *demuxer)
592 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
593 stream_t *s = demuxer->stream;
594 uint64_t length, l;
595 int il;
596 uint64_t tc_scale = 1000000;
597 long double duration = 0.;
599 length = ebml_read_length (s, NULL);
600 while (length > 0)
602 switch (ebml_read_id (s, &il))
604 case MATROSKA_ID_TIMECODESCALE:
606 uint64_t num = ebml_read_uint (s, &l);
607 if (num == EBML_UINT_INVALID)
608 return 1;
609 tc_scale = num;
610 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + timecode scale: %"PRIu64"\n",
611 tc_scale);
612 break;
615 case MATROSKA_ID_DURATION:
617 long double num = ebml_read_float (s, &l);
618 if (num == EBML_FLOAT_INVALID)
619 return 1;
620 duration = num;
621 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + duration: %.3Lfs\n",
622 duration * tc_scale / 1000000000.0);
623 break;
626 default:
627 ebml_read_skip (s, &l);
628 break;
630 length -= l + il;
632 mkv_d->tc_scale = tc_scale;
633 mkv_d->duration = duration * tc_scale / 1000000000.0;
634 return 0;
638 * \brief free array of kv_content_encoding_t
639 * \param encodings pointer to array
640 * \param numencodings number of encodings in array
642 static void
643 demux_mkv_free_encodings(mkv_content_encoding_t *encodings, int numencodings)
645 while (numencodings-- > 0)
646 free(encodings[numencodings].comp_settings);
647 free(encodings);
650 static int
651 demux_mkv_read_trackencodings (demuxer_t *demuxer, mkv_track_t *track)
653 stream_t *s = demuxer->stream;
654 mkv_content_encoding_t *ce, e;
655 uint64_t len, length, l;
656 int il, n;
658 ce = malloc (sizeof (*ce));
659 n = 0;
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_CONTENTENCODING:
669 uint64_t len;
670 int i;
672 memset (&e, 0, sizeof (e));
673 e.scope = 1;
675 len = ebml_read_length (s, &i);
676 l = len + i;
678 while (len > 0)
680 uint64_t num, l;
681 int il;
683 switch (ebml_read_id (s, &il))
685 case MATROSKA_ID_CONTENTENCODINGORDER:
686 num = ebml_read_uint (s, &l);
687 if (num == EBML_UINT_INVALID)
688 goto err_out;
689 e.order = num;
690 break;
692 case MATROSKA_ID_CONTENTENCODINGSCOPE:
693 num = ebml_read_uint (s, &l);
694 if (num == EBML_UINT_INVALID)
695 goto err_out;
696 e.scope = num;
697 break;
699 case MATROSKA_ID_CONTENTENCODINGTYPE:
700 num = ebml_read_uint (s, &l);
701 if (num == EBML_UINT_INVALID)
702 goto err_out;
703 e.type = num;
704 break;
706 case MATROSKA_ID_CONTENTCOMPRESSION:
708 uint64_t le;
710 le = ebml_read_length (s, &i);
711 l = le + i;
713 while (le > 0)
715 uint64_t l;
716 int il;
718 switch (ebml_read_id (s, &il))
720 case MATROSKA_ID_CONTENTCOMPALGO:
721 num = ebml_read_uint (s, &l);
722 if (num == EBML_UINT_INVALID)
723 goto err_out;
724 e.comp_algo = num;
725 break;
727 case MATROSKA_ID_CONTENTCOMPSETTINGS:
728 l = ebml_read_length (s, &i);
729 e.comp_settings = malloc (l);
730 stream_read (s, e.comp_settings, l);
731 e.comp_settings_len = l;
732 l += i;
733 break;
735 default:
736 ebml_read_skip (s, &l);
737 break;
739 le -= l + il;
742 if (e.type == 1)
744 mp_msg(MSGT_DEMUX, MSGL_WARN,
745 MSGTR_MPDEMUX_MKV_TrackEncrypted, track->tnum);
747 else if (e.type != 0)
749 mp_msg(MSGT_DEMUX, MSGL_WARN,
750 MSGTR_MPDEMUX_MKV_UnknownContentEncoding, track->tnum);
753 if (e.comp_algo != 0 && e.comp_algo != 2)
755 mp_msg (MSGT_DEMUX, MSGL_WARN,
756 MSGTR_MPDEMUX_MKV_UnknownCompression,
757 track->tnum, e.comp_algo);
759 #ifndef HAVE_ZLIB
760 else if (e.comp_algo == 0)
762 mp_msg (MSGT_DEMUX, MSGL_WARN,
763 MSGTR_MPDEMUX_MKV_ZlibCompressionUnsupported,
764 track->tnum);
766 #endif
768 break;
771 default:
772 ebml_read_skip (s, &l);
773 break;
775 len -= l + il;
777 for (i=0; i<n; i++)
778 if (e.order <= ce[i].order)
779 break;
780 ce = realloc (ce, (n+1) *sizeof (*ce));
781 memmove (ce+i+1, ce+i, (n-i) * sizeof (*ce));
782 memcpy (ce+i, &e, sizeof (e));
783 n++;
784 break;
787 default:
788 ebml_read_skip (s, &l);
789 break;
792 length -= l + il;
795 track->encodings = ce;
796 track->num_encodings = n;
797 return len;
799 err_out:
800 demux_mkv_free_encodings(ce, n);
801 return 0;
804 static int
805 demux_mkv_read_trackaudio (demuxer_t *demuxer, mkv_track_t *track)
807 stream_t *s = demuxer->stream;
808 uint64_t len, length, l;
809 int il;
811 track->a_sfreq = 8000.0;
812 track->a_channels = 1;
814 len = length = ebml_read_length (s, &il);
815 len += il;
816 while (length > 0)
818 switch (ebml_read_id (s, &il))
820 case MATROSKA_ID_AUDIOSAMPLINGFREQ:
822 long double num = ebml_read_float (s, &l);
823 if (num == EBML_FLOAT_INVALID)
824 return 0;
825 track->a_sfreq = num;
826 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Sampling frequency: %f\n",
827 track->a_sfreq);
828 break;
831 case MATROSKA_ID_AUDIOBITDEPTH:
833 uint64_t num = ebml_read_uint (s, &l);
834 if (num == EBML_UINT_INVALID)
835 return 0;
836 track->a_bps = num;
837 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Bit depth: %u\n",
838 track->a_bps);
839 break;
842 case MATROSKA_ID_AUDIOCHANNELS:
844 uint64_t num = ebml_read_uint (s, &l);
845 if (num == EBML_UINT_INVALID)
846 return 0;
847 track->a_channels = num;
848 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Channels: %u\n",
849 track->a_channels);
850 break;
853 default:
854 ebml_read_skip (s, &l);
855 break;
857 length -= l + il;
859 return len;
862 static int
863 demux_mkv_read_trackvideo (demuxer_t *demuxer, mkv_track_t *track)
865 stream_t *s = demuxer->stream;
866 uint64_t len, length, l;
867 int il;
869 len = length = ebml_read_length (s, &il);
870 len += il;
871 while (length > 0)
873 switch (ebml_read_id (s, &il))
875 case MATROSKA_ID_VIDEOFRAMERATE:
877 long double num = ebml_read_float (s, &l);
878 if (num == EBML_FLOAT_INVALID)
879 return 0;
880 track->v_frate = num;
881 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Frame rate: %f\n",
882 track->v_frate);
883 if (track->v_frate > 0)
884 track->default_duration = 1 / track->v_frate;
885 break;
888 case MATROSKA_ID_VIDEODISPLAYWIDTH:
890 uint64_t num = ebml_read_uint (s, &l);
891 if (num == EBML_UINT_INVALID)
892 return 0;
893 track->v_dwidth = num;
894 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Display width: %u\n",
895 track->v_dwidth);
896 break;
899 case MATROSKA_ID_VIDEODISPLAYHEIGHT:
901 uint64_t num = ebml_read_uint (s, &l);
902 if (num == EBML_UINT_INVALID)
903 return 0;
904 track->v_dheight = num;
905 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Display height: %u\n",
906 track->v_dheight);
907 break;
910 case MATROSKA_ID_VIDEOPIXELWIDTH:
912 uint64_t num = ebml_read_uint (s, &l);
913 if (num == EBML_UINT_INVALID)
914 return 0;
915 track->v_width = num;
916 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Pixel width: %u\n",
917 track->v_width);
918 break;
921 case MATROSKA_ID_VIDEOPIXELHEIGHT:
923 uint64_t num = ebml_read_uint (s, &l);
924 if (num == EBML_UINT_INVALID)
925 return 0;
926 track->v_height = num;
927 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Pixel height: %u\n",
928 track->v_height);
929 break;
932 default:
933 ebml_read_skip (s, &l);
934 break;
936 length -= l + il;
938 return len;
942 * \brief free any data associated with given track
943 * \param track track of which to free data
945 static void
946 demux_mkv_free_trackentry(mkv_track_t *track) {
947 if (track->name)
948 free (track->name);
949 if (track->codec_id)
950 free (track->codec_id);
951 if (track->language)
952 free (track->language);
953 if (track->private_data)
954 free (track->private_data);
955 if (track->audio_buf)
956 free (track->audio_buf);
957 if (track->audio_timestamp)
958 free (track->audio_timestamp);
959 #ifdef USE_ASS
960 if (track->sh_sub && track->sh_sub->ass_track)
961 ass_free_track (track->sh_sub->ass_track);
962 #endif
963 demux_mkv_free_encodings(track->encodings, track->num_encodings);
964 free(track);
967 static int
968 demux_mkv_read_trackentry (demuxer_t *demuxer)
970 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
971 stream_t *s = demuxer->stream;
972 mkv_track_t *track;
973 uint64_t len, length, l;
974 int il;
976 track = calloc (1, sizeof (*track));
977 /* set default values */
978 track->default_track = 1;
979 track->name = 0;
980 track->language = strdup("eng");
982 len = length = ebml_read_length (s, &il);
983 len += il;
984 while (length > 0)
986 switch (ebml_read_id (s, &il))
988 case MATROSKA_ID_TRACKNUMBER:
990 uint64_t num = ebml_read_uint (s, &l);
991 if (num == EBML_UINT_INVALID)
992 goto err_out;
993 track->tnum = num;
994 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Track number: %u\n",
995 track->tnum);
996 break;
999 case MATROSKA_ID_TRACKNAME:
1001 track->name = ebml_read_utf8 (s, &l);
1002 if (track->name == NULL)
1003 goto err_out;
1004 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Name: %s\n",
1005 track->name);
1006 break;
1009 case MATROSKA_ID_TRACKTYPE:
1011 uint64_t num = ebml_read_uint (s, &l);
1012 if (num == EBML_UINT_INVALID)
1013 return 0;
1014 track->type = num;
1015 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Track type: ");
1016 switch (track->type)
1018 case MATROSKA_TRACK_AUDIO:
1019 mp_msg (MSGT_DEMUX, MSGL_V, "Audio\n");
1020 break;
1021 case MATROSKA_TRACK_VIDEO:
1022 mp_msg (MSGT_DEMUX, MSGL_V, "Video\n");
1023 break;
1024 case MATROSKA_TRACK_SUBTITLE:
1025 mp_msg (MSGT_DEMUX, MSGL_V, "Subtitle\n");
1026 break;
1027 default:
1028 mp_msg (MSGT_DEMUX, MSGL_V, "unknown\n");
1029 break;
1031 break;
1034 case MATROSKA_ID_TRACKAUDIO:
1035 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Audio track\n");
1036 l = demux_mkv_read_trackaudio (demuxer, track);
1037 if (l == 0)
1038 goto err_out;
1039 break;
1041 case MATROSKA_ID_TRACKVIDEO:
1042 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Video track\n");
1043 l = demux_mkv_read_trackvideo (demuxer, track);
1044 if (l == 0)
1045 goto err_out;
1046 break;
1048 case MATROSKA_ID_CODECID:
1049 track->codec_id = ebml_read_ascii (s, &l);
1050 if (track->codec_id == NULL)
1051 goto err_out;
1052 if (!strcmp (track->codec_id, MKV_V_MSCOMP) ||
1053 !strcmp (track->codec_id, MKV_A_ACM))
1054 track->ms_compat = 1;
1055 else if (!strcmp (track->codec_id, MKV_S_VOBSUB))
1056 track->subtitle_type = MATROSKA_SUBTYPE_VOBSUB;
1057 else if (!strcmp (track->codec_id, MKV_S_TEXTSSA)
1058 || !strcmp (track->codec_id, MKV_S_TEXTASS)
1059 || !strcmp (track->codec_id, MKV_S_SSA)
1060 || !strcmp (track->codec_id, MKV_S_ASS))
1062 track->subtitle_type = MATROSKA_SUBTYPE_SSA;
1064 else if (!strcmp (track->codec_id, MKV_S_TEXTASCII))
1065 track->subtitle_type = MATROSKA_SUBTYPE_TEXT;
1066 if (!strcmp (track->codec_id, MKV_S_TEXTUTF8))
1068 track->subtitle_type = MATROSKA_SUBTYPE_TEXT;
1070 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Codec ID: %s\n",
1071 track->codec_id);
1072 break;
1074 case MATROSKA_ID_CODECPRIVATE:
1076 int x;
1077 uint64_t num = ebml_read_length (s, &x);
1078 // audit: cheap guard against overflows later..
1079 if (num > SIZE_MAX - 1000) return 0;
1080 l = x + num;
1081 track->private_data = malloc (num + LZO_INPUT_PADDING);
1082 if (stream_read(s, track->private_data, num) != (int) num)
1083 goto err_out;
1084 track->private_size = num;
1085 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + CodecPrivate, length "
1086 "%u\n", track->private_size);
1087 break;
1090 case MATROSKA_ID_TRACKLANGUAGE:
1091 free(track->language);
1092 track->language = ebml_read_utf8 (s, &l);
1093 if (track->language == NULL)
1094 goto err_out;
1095 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Language: %s\n",
1096 track->language);
1097 break;
1099 case MATROSKA_ID_TRACKFLAGDEFAULT:
1101 uint64_t num = ebml_read_uint (s, &l);
1102 if (num == EBML_UINT_INVALID)
1103 goto err_out;
1104 track->default_track = num;
1105 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Default flag: %u\n",
1106 track->default_track);
1107 break;
1110 case MATROSKA_ID_TRACKDEFAULTDURATION:
1112 uint64_t num = ebml_read_uint (s, &l);
1113 if (num == EBML_UINT_INVALID)
1114 goto err_out;
1115 if (num == 0)
1116 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Default duration: 0");
1117 else
1119 track->v_frate = 1000000000.0 / num;
1120 track->default_duration = num / 1000000000.0;
1121 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + Default duration: "
1122 "%.3fms ( = %.3f fps)\n",num/1000000.0,track->v_frate);
1124 break;
1127 case MATROSKA_ID_TRACKENCODINGS:
1128 l = demux_mkv_read_trackencodings (demuxer, track);
1129 if (l == 0)
1130 goto err_out;
1131 break;
1133 default:
1134 ebml_read_skip (s, &l);
1135 break;
1137 length -= l + il;
1140 mkv_d->tracks[mkv_d->num_tracks++] = track;
1141 return len;
1143 err_out:
1144 demux_mkv_free_trackentry(track);
1145 return 0;
1148 static int
1149 demux_mkv_read_tracks (demuxer_t *demuxer)
1151 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
1152 stream_t *s = demuxer->stream;
1153 uint64_t length, l;
1154 int il;
1156 mkv_d->tracks = malloc (sizeof (*mkv_d->tracks));
1157 mkv_d->num_tracks = 0;
1159 length = ebml_read_length (s, NULL);
1160 while (length > 0)
1162 switch (ebml_read_id (s, &il))
1164 case MATROSKA_ID_TRACKENTRY:
1165 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + a track...\n");
1166 mkv_d->tracks = realloc (mkv_d->tracks,
1167 (mkv_d->num_tracks+1)
1168 *sizeof (*mkv_d->tracks));
1169 l = demux_mkv_read_trackentry (demuxer);
1170 if (l == 0)
1171 return 1;
1172 break;
1174 default:
1175 ebml_read_skip (s, &l);
1176 break;
1178 length -= l + il;
1180 return 0;
1183 static int
1184 demux_mkv_read_cues (demuxer_t *demuxer)
1186 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
1187 stream_t *s = demuxer->stream;
1188 uint64_t length, l, time, track, pos;
1189 off_t off;
1190 int i, il;
1192 if (index_mode == 0) {
1193 ebml_read_skip (s, NULL);
1194 return 0;
1196 off = stream_tell (s);
1197 for (i=0; i<mkv_d->parsed_cues_num; i++)
1198 if (mkv_d->parsed_cues[i] == off)
1200 ebml_read_skip (s, NULL);
1201 return 0;
1203 mkv_d->parsed_cues = realloc (mkv_d->parsed_cues,
1204 (mkv_d->parsed_cues_num+1)
1205 * sizeof (off_t));
1206 mkv_d->parsed_cues[mkv_d->parsed_cues_num++] = off;
1208 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] /---- [ parsing cues ] -----------\n");
1209 length = ebml_read_length (s, NULL);
1211 while (length > 0)
1213 time = track = pos = EBML_UINT_INVALID;
1215 switch (ebml_read_id (s, &il))
1217 case MATROSKA_ID_POINTENTRY:
1219 uint64_t len;
1221 len = ebml_read_length (s, &i);
1222 l = len + i;
1224 while (len > 0)
1226 uint64_t l;
1227 int il;
1229 switch (ebml_read_id (s, &il))
1231 case MATROSKA_ID_CUETIME:
1232 time = ebml_read_uint (s, &l);
1233 break;
1235 case MATROSKA_ID_CUETRACKPOSITION:
1237 uint64_t le;
1239 le = ebml_read_length (s, &i);
1240 l = le + i;
1242 while (le > 0)
1244 uint64_t l;
1245 int il;
1247 switch (ebml_read_id (s, &il))
1249 case MATROSKA_ID_CUETRACK:
1250 track = ebml_read_uint (s, &l);
1251 break;
1253 case MATROSKA_ID_CUECLUSTERPOSITION:
1254 pos = ebml_read_uint (s, &l);
1255 break;
1257 default:
1258 ebml_read_skip (s, &l);
1259 break;
1261 le -= l + il;
1263 break;
1266 default:
1267 ebml_read_skip (s, &l);
1268 break;
1270 len -= l + il;
1272 break;
1275 default:
1276 ebml_read_skip (s, &l);
1277 break;
1280 length -= l + il;
1282 if (time != EBML_UINT_INVALID && track != EBML_UINT_INVALID
1283 && pos != EBML_UINT_INVALID)
1285 grow_array(&mkv_d->indexes, mkv_d->num_indexes, sizeof(mkv_index_t));
1286 mkv_d->indexes[mkv_d->num_indexes].tnum = track;
1287 mkv_d->indexes[mkv_d->num_indexes].timecode = time;
1288 mkv_d->indexes[mkv_d->num_indexes].filepos =mkv_d->segment_start+pos;
1289 mp_msg (MSGT_DEMUX, MSGL_DBG2, "[mkv] |+ found cue point "
1290 "for track %"PRIu64": timecode %"PRIu64", filepos: %"PRIu64"\n",
1291 track, time, mkv_d->segment_start + pos);
1292 mkv_d->num_indexes++;
1296 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] \\---- [ parsing cues ] -----------\n");
1297 return 0;
1300 static int
1301 demux_mkv_read_chapters (demuxer_t *demuxer)
1303 stream_t *s = demuxer->stream;
1304 uint64_t length, l;
1305 int il;
1307 if (demuxer->chapters)
1309 ebml_read_skip (s, NULL);
1310 return 0;
1313 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] /---- [ parsing chapters ] ---------\n");
1314 length = ebml_read_length (s, NULL);
1316 while (length > 0)
1318 switch (ebml_read_id (s, &il))
1320 case MATROSKA_ID_EDITIONENTRY:
1322 uint64_t len;
1323 int i;
1325 len = ebml_read_length (s, &i);
1326 l = len + i;
1328 while (len > 0)
1330 uint64_t l;
1331 int il;
1333 switch (ebml_read_id (s, &il))
1335 case MATROSKA_ID_CHAPTERATOM:
1337 uint64_t len, start=0, end=0;
1338 char* name = 0;
1339 int i;
1340 int cid;
1342 len = ebml_read_length (s, &i);
1343 l = len + i;
1345 while (len > 0)
1347 uint64_t l;
1348 int il;
1350 switch (ebml_read_id (s, &il))
1352 case MATROSKA_ID_CHAPTERTIMESTART:
1353 start = ebml_read_uint (s, &l) / 1000000;
1354 break;
1356 case MATROSKA_ID_CHAPTERTIMEEND:
1357 end = ebml_read_uint (s, &l) / 1000000;
1358 break;
1360 case MATROSKA_ID_CHAPTERDISPLAY:
1362 uint64_t len;
1363 int i;
1365 len = ebml_read_length (s, &i);
1366 l = len + i;
1367 while (len > 0)
1369 uint64_t l;
1370 int il;
1372 switch (ebml_read_id (s, &il))
1374 case MATROSKA_ID_CHAPSTRING:
1375 name = ebml_read_utf8 (s, &l);
1376 break;
1377 default:
1378 ebml_read_skip (s, &l);
1379 break;
1381 len -= l + il;
1384 break;
1386 default:
1387 ebml_read_skip (s, &l);
1388 break;
1390 len -= l + il;
1393 if (!name)
1394 name = strdup("(unnamed)");
1396 cid = demuxer_add_chapter(demuxer, name, start, end);
1398 mp_msg(MSGT_DEMUX, MSGL_V,
1399 "[mkv] Chapter %u from %02d:%02d:%02d."
1400 "%03d to %02d:%02d:%02d.%03d, %s\n",
1401 cid,
1402 (int) (start / 60 / 60 / 1000),
1403 (int) ((start / 60 / 1000) % 60),
1404 (int) ((start / 1000) % 60),
1405 (int) (start % 1000),
1406 (int) (end / 60 / 60 / 1000),
1407 (int) ((end / 60 / 1000) % 60),
1408 (int) ((end / 1000) % 60),
1409 (int) (end % 1000), name);
1411 free(name);
1412 break;
1415 default:
1416 ebml_read_skip (s, &l);
1417 break;
1419 len -= l + il;
1421 break;
1424 default:
1425 ebml_read_skip (s, &l);
1426 break;
1429 length -= l + il;
1432 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] \\---- [ parsing chapters ] ---------\n");
1433 return 0;
1436 static int
1437 demux_mkv_read_tags (demuxer_t *demuxer)
1439 ebml_read_skip (demuxer->stream, NULL);
1440 return 0;
1443 static int
1444 demux_mkv_read_attachments (demuxer_t *demuxer)
1446 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
1447 stream_t *s = demuxer->stream;
1448 uint64_t length, l;
1449 int il;
1451 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] /---- [ parsing attachments ] ---------\n");
1452 length = ebml_read_length (s, NULL);
1454 while (length > 0)
1456 switch (ebml_read_id (s, &il))
1458 case MATROSKA_ID_ATTACHEDFILE:
1460 uint64_t len;
1461 int i;
1462 char* name = NULL;
1463 char* mime = NULL;
1464 uint64_t uid = 0;
1465 char* data = NULL;
1466 int data_size = 0;
1468 len = ebml_read_length (s, &i);
1469 l = len + i;
1471 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + an attachment...\n");
1473 grow_array(&mkv_d->attachments, mkv_d->num_attachments,
1474 sizeof(*mkv_d->attachments));
1476 while (len > 0)
1478 uint64_t l;
1479 int il;
1481 switch (ebml_read_id (s, &il))
1483 case MATROSKA_ID_FILENAME:
1484 name = ebml_read_utf8 (s, &l);
1485 if (name == NULL)
1486 return 0;
1487 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + FileName: %s\n",
1488 name);
1489 break;
1491 case MATROSKA_ID_FILEMIMETYPE:
1492 mime = ebml_read_ascii (s, &l);
1493 if (mime == NULL)
1494 return 0;
1495 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + FileMimeType: %s\n",
1496 mime);
1497 break;
1499 case MATROSKA_ID_FILEUID:
1500 uid = ebml_read_uint (s, &l);
1501 break;
1503 case MATROSKA_ID_FILEDATA:
1505 int x;
1506 uint64_t num = ebml_read_length (s, &x);
1507 l = x + num;
1508 free(data);
1509 data = malloc (num);
1510 if (stream_read(s, data, num) != (int) num)
1512 free(data);
1513 return 0;
1515 data_size = num;
1516 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + FileData, length "
1517 "%u\n", data_size);
1518 break;
1521 default:
1522 ebml_read_skip (s, &l);
1523 break;
1525 len -= l + il;
1528 mkv_d->attachments[mkv_d->num_attachments].name = name;
1529 mkv_d->attachments[mkv_d->num_attachments].mime = mime;
1530 mkv_d->attachments[mkv_d->num_attachments].uid = uid;
1531 mkv_d->attachments[mkv_d->num_attachments].data = data;
1532 mkv_d->attachments[mkv_d->num_attachments].data_size = data_size;
1533 mkv_d->num_attachments ++;
1534 mp_msg(MSGT_DEMUX, MSGL_V,
1535 "[mkv] Attachment: %s, %s, %u bytes\n",
1536 name, mime, data_size);
1537 #ifdef USE_ASS
1538 if (ass_library &&
1539 extract_embedded_fonts && name && data && data_size &&
1540 mime && (strcmp(mime, "application/x-truetype-font") == 0 ||
1541 strcmp(mime, "application/x-font") == 0))
1542 ass_add_font(ass_library, name, data, data_size);
1543 #endif
1544 break;
1547 default:
1548 ebml_read_skip (s, &l);
1549 break;
1551 length -= l + il;
1554 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] \\---- [ parsing attachments ] ---------\n");
1555 return 0;
1558 static int
1559 demux_mkv_read_seekhead (demuxer_t *demuxer)
1561 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
1562 stream_t *s = demuxer->stream;
1563 uint64_t length, l, seek_pos, saved_pos, num;
1564 uint32_t seek_id;
1565 int i, il, res = 0;
1566 off_t off;
1568 off = stream_tell (s);
1569 for (i=0; i<mkv_d->parsed_seekhead_num; i++)
1570 if (mkv_d->parsed_seekhead[i] == off)
1572 ebml_read_skip (s, NULL);
1573 return 0;
1575 mkv_d->parsed_seekhead = realloc (mkv_d->parsed_seekhead,
1576 (mkv_d->parsed_seekhead_num+1)
1577 * sizeof (off_t));
1578 mkv_d->parsed_seekhead[mkv_d->parsed_seekhead_num++] = off;
1580 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] /---- [ parsing seek head ] ---------\n");
1581 length = ebml_read_length (s, NULL);
1582 /* off now holds the position of the next element after the seek head. */
1583 off = stream_tell (s) + length;
1584 while (length > 0 && !res)
1587 seek_id = 0;
1588 seek_pos = EBML_UINT_INVALID;
1590 switch (ebml_read_id (s, &il))
1592 case MATROSKA_ID_SEEKENTRY:
1594 uint64_t len;
1596 len = ebml_read_length (s, &i);
1597 l = len + i;
1599 while (len > 0)
1601 uint64_t l;
1602 int il;
1604 switch (ebml_read_id (s, &il))
1606 case MATROSKA_ID_SEEKID:
1607 num = ebml_read_uint (s, &l);
1608 if (num != EBML_UINT_INVALID)
1609 seek_id = num;
1610 break;
1612 case MATROSKA_ID_SEEKPOSITION:
1613 seek_pos = ebml_read_uint (s, &l);
1614 break;
1616 default:
1617 ebml_read_skip (s, &l);
1618 break;
1620 len -= l + il;
1623 break;
1626 default:
1627 ebml_read_skip (s, &l);
1628 break;
1630 length -= l + il;
1632 if (seek_id == 0 || seek_id == MATROSKA_ID_CLUSTER
1633 || seek_pos == EBML_UINT_INVALID ||
1634 ((mkv_d->segment_start + seek_pos) >= (uint64_t)demuxer->movi_end))
1635 continue;
1637 saved_pos = stream_tell (s);
1638 if (!stream_seek (s, mkv_d->segment_start + seek_pos))
1639 res = 1;
1640 else
1642 if (ebml_read_id (s, &il) != seek_id)
1643 res = 1;
1644 else
1645 switch (seek_id)
1647 case MATROSKA_ID_CUES:
1648 if (demux_mkv_read_cues (demuxer))
1649 res = 1;
1650 break;
1652 case MATROSKA_ID_TAGS:
1653 if (demux_mkv_read_tags (demuxer))
1654 res = 1;
1655 break;
1657 case MATROSKA_ID_SEEKHEAD:
1658 if (demux_mkv_read_seekhead (demuxer))
1659 res = 1;
1660 break;
1662 case MATROSKA_ID_CHAPTERS:
1663 if (demux_mkv_read_chapters (demuxer))
1664 res = 1;
1665 break;
1669 stream_seek (s, saved_pos);
1671 if (res)
1673 /* If there was an error then try to skip this seek head. */
1674 if (stream_seek (s, off))
1675 res = 0;
1677 else
1678 if (length > 0)
1679 stream_seek (s, stream_tell (s) + length);
1680 mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] \\---- [ parsing seek head ] ---------\n");
1681 return res;
1684 static int
1685 demux_mkv_open_video (demuxer_t *demuxer, mkv_track_t *track, int vid);
1686 static int
1687 demux_mkv_open_audio (demuxer_t *demuxer, mkv_track_t *track, int aid);
1688 static int
1689 demux_mkv_open_sub (demuxer_t *demuxer, mkv_track_t *track, int sid);
1691 static void
1692 display_create_tracks (demuxer_t *demuxer)
1694 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *)demuxer->priv;
1695 int i, vid=0, aid=0, sid=0;
1697 for (i=0; i<mkv_d->num_tracks; i++)
1699 char *type = "unknown", str[32];
1700 *str = '\0';
1701 switch (mkv_d->tracks[i]->type)
1703 case MATROSKA_TRACK_VIDEO:
1704 type = "video";
1705 demux_mkv_open_video(demuxer, mkv_d->tracks[i], vid);
1706 if (mkv_d->tracks[i]->name)
1707 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VID_%d_NAME=%s\n", vid, mkv_d->tracks[i]->name);
1708 sprintf (str, "-vid %u", vid++);
1709 break;
1710 case MATROSKA_TRACK_AUDIO:
1711 type = "audio";
1712 demux_mkv_open_audio(demuxer, mkv_d->tracks[i], aid);
1713 if (mkv_d->tracks[i]->name)
1714 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AID_%d_NAME=%s\n", aid, mkv_d->tracks[i]->name);
1715 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AID_%d_LANG=%s\n", aid, mkv_d->tracks[i]->language);
1716 sprintf (str, "-aid %u, -alang %.5s",aid++,mkv_d->tracks[i]->language);
1717 break;
1718 case MATROSKA_TRACK_SUBTITLE:
1719 type = "subtitles";
1720 demux_mkv_open_sub(demuxer, mkv_d->tracks[i], sid);
1721 if (mkv_d->tracks[i]->name)
1722 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SID_%d_NAME=%s\n", sid, mkv_d->tracks[i]->name);
1723 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SID_%d_LANG=%s\n", sid, mkv_d->tracks[i]->language);
1724 sprintf (str, "-sid %u, -slang %.5s",sid++,mkv_d->tracks[i]->language);
1725 break;
1727 if (mkv_d->tracks[i]->name)
1728 mp_msg(MSGT_DEMUX, MSGL_INFO, MSGTR_MPDEMUX_MKV_TrackIDName,
1729 mkv_d->tracks[i]->tnum, type, mkv_d->tracks[i]->codec_id, mkv_d->tracks[i]->name, str);
1730 else
1731 mp_msg(MSGT_DEMUX, MSGL_INFO, MSGTR_MPDEMUX_MKV_TrackID,
1732 mkv_d->tracks[i]->tnum, type, mkv_d->tracks[i]->codec_id, str);
1736 typedef struct {
1737 char *id;
1738 int fourcc;
1739 int extradata;
1740 } videocodec_info_t;
1742 static const videocodec_info_t vinfo[] = {
1743 { MKV_V_MPEG1, mmioFOURCC('m', 'p', 'g', '1'), 0 },
1744 { MKV_V_MPEG2, mmioFOURCC('m', 'p', 'g', '2'), 0 },
1745 { MKV_V_MPEG4_SP, mmioFOURCC('m', 'p', '4', 'v'), 1 },
1746 { MKV_V_MPEG4_ASP, mmioFOURCC('m', 'p', '4', 'v'), 1 },
1747 { MKV_V_MPEG4_AP, mmioFOURCC('m', 'p', '4', 'v'), 1 },
1748 { MKV_V_MPEG4_AVC, mmioFOURCC('a', 'v', 'c', '1'), 1 },
1749 { MKV_V_THEORA, mmioFOURCC('t', 'h', 'e', 'o'), 1 },
1750 { NULL, 0, 0 }
1753 static int
1754 demux_mkv_open_video (demuxer_t *demuxer, mkv_track_t *track, int vid)
1756 BITMAPINFOHEADER *bih;
1757 void *ImageDesc = NULL;
1758 sh_video_t *sh_v;
1760 if (track->ms_compat) /* MS compatibility mode */
1762 BITMAPINFOHEADER *src;
1764 if (track->private_data == NULL
1765 || track->private_size < sizeof (BITMAPINFOHEADER))
1766 return 1;
1768 src = (BITMAPINFOHEADER *) track->private_data;
1769 bih = calloc (1, track->private_size);
1770 bih->biSize = le2me_32 (src->biSize);
1771 bih->biWidth = le2me_32 (src->biWidth);
1772 bih->biHeight = le2me_32 (src->biHeight);
1773 bih->biPlanes = le2me_16 (src->biPlanes);
1774 bih->biBitCount = le2me_16 (src->biBitCount);
1775 bih->biCompression = le2me_32 (src->biCompression);
1776 bih->biSizeImage = le2me_32 (src->biSizeImage);
1777 bih->biXPelsPerMeter = le2me_32 (src->biXPelsPerMeter);
1778 bih->biYPelsPerMeter = le2me_32 (src->biYPelsPerMeter);
1779 bih->biClrUsed = le2me_32 (src->biClrUsed);
1780 bih->biClrImportant = le2me_32 (src->biClrImportant);
1781 memcpy((char *) bih + sizeof (BITMAPINFOHEADER),
1782 (char *) src + sizeof (BITMAPINFOHEADER),
1783 track->private_size - sizeof (BITMAPINFOHEADER));
1785 if (track->v_width == 0)
1786 track->v_width = bih->biWidth;
1787 if (track->v_height == 0)
1788 track->v_height = bih->biHeight;
1790 else
1792 bih = calloc (1, sizeof (BITMAPINFOHEADER));
1793 bih->biSize = sizeof (BITMAPINFOHEADER);
1794 bih->biWidth = track->v_width;
1795 bih->biHeight = track->v_height;
1796 bih->biBitCount = 24;
1797 bih->biSizeImage = bih->biWidth * bih->biHeight * bih->biBitCount/8;
1799 if (track->private_size >= RVPROPERTIES_SIZE
1800 && (!strcmp (track->codec_id, MKV_V_REALV10)
1801 || !strcmp (track->codec_id, MKV_V_REALV20)
1802 || !strcmp (track->codec_id, MKV_V_REALV30)
1803 || !strcmp (track->codec_id, MKV_V_REALV40)))
1805 unsigned char *dst, *src;
1806 uint32_t type2;
1807 unsigned int cnt;
1809 src = track->private_data + RVPROPERTIES_SIZE;
1811 cnt = track->private_size - RVPROPERTIES_SIZE;
1812 bih = realloc(bih, sizeof (BITMAPINFOHEADER)+8+cnt);
1813 bih->biSize = 48+cnt;
1814 bih->biPlanes = 1;
1815 type2 = AV_RB32(src - 4);
1816 if (type2 == 0x10003000 || type2 == 0x10003001)
1817 bih->biCompression=mmioFOURCC('R','V','1','3');
1818 else
1819 bih->biCompression=mmioFOURCC('R','V',track->codec_id[9],'0');
1820 dst = (unsigned char *) (bih + 1);
1821 // copy type1 and type2 info from rv properties
1822 memcpy(dst, src - 8, 8);
1823 stream_read(demuxer->stream, dst+8, cnt);
1824 track->realmedia = 1;
1826 #ifdef USE_QTX_CODECS
1828 else if (track->private_size >= sizeof (ImageDescription)
1829 && !strcmp(track->codec_id, MKV_V_QUICKTIME))
1831 ImageDescriptionPtr idesc;
1833 idesc = (ImageDescriptionPtr) track->private_data;
1834 idesc->idSize = be2me_32 (idesc->idSize);
1835 idesc->cType = be2me_32 (idesc->cType);
1836 idesc->version = be2me_16 (idesc->version);
1837 idesc->revisionLevel = be2me_16 (idesc->revisionLevel);
1838 idesc->vendor = be2me_32 (idesc->vendor);
1839 idesc->temporalQuality = be2me_32 (idesc->temporalQuality);
1840 idesc->spatialQuality = be2me_32 (idesc->spatialQuality);
1841 idesc->width = be2me_16 (idesc->width);
1842 idesc->height = be2me_16 (idesc->height);
1843 idesc->hRes = be2me_32 (idesc->hRes);
1844 idesc->vRes = be2me_32 (idesc->vRes);
1845 idesc->dataSize = be2me_32 (idesc->dataSize);
1846 idesc->frameCount = be2me_16 (idesc->frameCount);
1847 idesc->depth = be2me_16 (idesc->depth);
1848 idesc->clutID = be2me_16 (idesc->clutID);
1849 bih->biPlanes = 1;
1850 bih->biCompression = idesc->cType;
1851 ImageDesc = idesc;
1852 #endif /* USE_QTX_CODECS */
1855 else
1857 const videocodec_info_t *vi = vinfo;
1858 while (vi->id && strcmp(vi->id, track->codec_id)) vi++;
1859 bih->biCompression = vi->fourcc;
1860 if (vi->extradata && track->private_data && (track->private_size > 0))
1862 bih->biSize += track->private_size;
1863 bih = realloc (bih, bih->biSize);
1864 memcpy (bih + 1, track->private_data, track->private_size);
1866 track->reorder_timecodes = !correct_pts;
1867 if (!vi->id) {
1868 mp_msg (MSGT_DEMUX,MSGL_WARN, MSGTR_MPDEMUX_MKV_UnknownCodecID,
1869 track->codec_id, track->tnum);
1870 free(bih);
1871 return 1;
1876 sh_v = new_sh_video_vid (demuxer, track->tnum, vid);
1877 sh_v->bih = bih;
1878 sh_v->format = sh_v->bih->biCompression;
1879 if (track->v_frate == 0.0)
1880 track->v_frate = 25.0;
1881 sh_v->fps = track->v_frate;
1882 sh_v->frametime = 1 / track->v_frate;
1883 sh_v->aspect = 0;
1884 if (!track->realmedia)
1886 sh_v->disp_w = track->v_width;
1887 sh_v->disp_h = track->v_height;
1888 if (track->v_dheight)
1889 sh_v->aspect = (float)track->v_dwidth / (float)track->v_dheight;
1891 else
1893 // vd_realvid.c will set aspect to disp_w/disp_h and rederive
1894 // disp_w and disp_h from the RealVideo stream contents returned
1895 // by the Real DLLs. If DisplayWidth/DisplayHeight was not set in
1896 // the Matroska file then it has already been set to PixelWidth/Height
1897 // by check_track_information.
1898 sh_v->disp_w = track->v_dwidth;
1899 sh_v->disp_h = track->v_dheight;
1901 sh_v->ImageDesc = ImageDesc;
1902 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] Aspect: %f\n", sh_v->aspect);
1904 sh_v->ds = demuxer->video;
1905 return 0;
1908 static int
1909 demux_mkv_open_audio (demuxer_t *demuxer, mkv_track_t *track, int aid)
1911 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
1912 sh_audio_t *sh_a = new_sh_audio_aid(demuxer, track->tnum, aid);
1913 demux_packet_t *dp;
1914 if(!sh_a) return 1;
1915 mkv_d->audio_tracks[mkv_d->last_aid] = track->tnum;
1917 sh_a->ds = demuxer->audio;
1918 sh_a->wf = malloc (sizeof (WAVEFORMATEX));
1919 if (track->ms_compat && (track->private_size >= sizeof(WAVEFORMATEX)))
1921 WAVEFORMATEX *wf = (WAVEFORMATEX *)track->private_data;
1922 sh_a->wf = realloc(sh_a->wf, track->private_size);
1923 sh_a->wf->wFormatTag = le2me_16 (wf->wFormatTag);
1924 sh_a->wf->nChannels = le2me_16 (wf->nChannels);
1925 sh_a->wf->nSamplesPerSec = le2me_32 (wf->nSamplesPerSec);
1926 sh_a->wf->nAvgBytesPerSec = le2me_32 (wf->nAvgBytesPerSec);
1927 sh_a->wf->nBlockAlign = le2me_16 (wf->nBlockAlign);
1928 sh_a->wf->wBitsPerSample = le2me_16 (wf->wBitsPerSample);
1929 sh_a->wf->cbSize = track->private_size - sizeof(WAVEFORMATEX);
1930 memcpy(sh_a->wf + 1, wf + 1, track->private_size - sizeof(WAVEFORMATEX));
1931 if (track->a_sfreq == 0.0)
1932 track->a_sfreq = sh_a->wf->nSamplesPerSec;
1933 if (track->a_channels == 0)
1934 track->a_channels = sh_a->wf->nChannels;
1935 if (track->a_bps == 0)
1936 track->a_bps = sh_a->wf->wBitsPerSample;
1937 track->a_formattag = sh_a->wf->wFormatTag;
1939 else
1941 memset(sh_a->wf, 0, sizeof (WAVEFORMATEX));
1942 if (!strcmp(track->codec_id, MKV_A_MP3) ||
1943 !strcmp(track->codec_id, MKV_A_MP2))
1944 track->a_formattag = 0x0055;
1945 else if (!strncmp(track->codec_id, MKV_A_AC3, strlen(MKV_A_AC3)))
1946 track->a_formattag = 0x2000;
1947 else if (!strcmp(track->codec_id, MKV_A_DTS))
1948 track->a_formattag = 0x2001;
1949 else if (!strcmp(track->codec_id, MKV_A_PCM) ||
1950 !strcmp(track->codec_id, MKV_A_PCM_BE))
1951 track->a_formattag = 0x0001;
1952 else if (!strcmp(track->codec_id, MKV_A_AAC_2MAIN) ||
1953 !strncmp(track->codec_id, MKV_A_AAC_2LC,
1954 strlen(MKV_A_AAC_2LC)) ||
1955 !strcmp(track->codec_id, MKV_A_AAC_2SSR) ||
1956 !strcmp(track->codec_id, MKV_A_AAC_4MAIN) ||
1957 !strncmp(track->codec_id, MKV_A_AAC_4LC,
1958 strlen(MKV_A_AAC_4LC)) ||
1959 !strcmp(track->codec_id, MKV_A_AAC_4SSR) ||
1960 !strcmp(track->codec_id, MKV_A_AAC_4LTP) ||
1961 !strcmp(track->codec_id, MKV_A_AAC))
1962 track->a_formattag = mmioFOURCC('M', 'P', '4', 'A');
1963 else if (!strcmp(track->codec_id, MKV_A_VORBIS))
1965 if (track->private_data == NULL)
1966 return 1;
1967 track->a_formattag = mmioFOURCC('v', 'r', 'b', 's');
1969 else if (!strcmp(track->codec_id, MKV_A_QDMC))
1970 track->a_formattag = mmioFOURCC('Q', 'D', 'M', 'C');
1971 else if (!strcmp(track->codec_id, MKV_A_QDMC2))
1972 track->a_formattag = mmioFOURCC('Q', 'D', 'M', '2');
1973 else if (!strcmp(track->codec_id, MKV_A_WAVPACK))
1974 track->a_formattag = mmioFOURCC('W', 'V', 'P', 'K');
1975 else if (!strcmp(track->codec_id, MKV_A_FLAC))
1977 if (track->private_data == NULL || track->private_size == 0)
1979 mp_msg (MSGT_DEMUX, MSGL_WARN,
1980 MSGTR_MPDEMUX_MKV_FlacTrackDoesNotContainValidHeaders);
1981 return 1;
1983 track->a_formattag = mmioFOURCC ('f', 'L', 'a', 'C');
1985 else if (track->private_size >= RAPROPERTIES4_SIZE)
1987 if (!strcmp(track->codec_id, MKV_A_REAL28))
1988 track->a_formattag = mmioFOURCC('2', '8', '_', '8');
1989 else if (!strcmp(track->codec_id, MKV_A_REALATRC))
1990 track->a_formattag = mmioFOURCC('a', 't', 'r', 'c');
1991 else if (!strcmp(track->codec_id, MKV_A_REALCOOK))
1992 track->a_formattag = mmioFOURCC('c', 'o', 'o', 'k');
1993 else if (!strcmp(track->codec_id, MKV_A_REALDNET))
1994 track->a_formattag = mmioFOURCC('d', 'n', 'e', 't');
1995 else if (!strcmp(track->codec_id, MKV_A_REALSIPR))
1996 track->a_formattag = mmioFOURCC('s', 'i', 'p', 'r');
1998 else
2000 mp_msg (MSGT_DEMUX, MSGL_WARN, MSGTR_MPDEMUX_MKV_UnknownAudioCodec,
2001 track->codec_id, track->tnum);
2002 free_sh_audio(demuxer, track->tnum);
2003 return 1;
2007 sh_a->format = track->a_formattag;
2008 sh_a->wf->wFormatTag = track->a_formattag;
2009 sh_a->channels = track->a_channels;
2010 sh_a->wf->nChannels = track->a_channels;
2011 sh_a->samplerate = (uint32_t) track->a_sfreq;
2012 sh_a->wf->nSamplesPerSec = (uint32_t) track->a_sfreq;
2013 if (track->a_bps == 0)
2015 sh_a->samplesize = 2;
2016 sh_a->wf->wBitsPerSample = 16;
2018 else
2020 sh_a->samplesize = track->a_bps / 8;
2021 sh_a->wf->wBitsPerSample = track->a_bps;
2023 if (track->a_formattag == 0x0055) /* MP3 || MP2 */
2025 sh_a->wf->nAvgBytesPerSec = 16000;
2026 sh_a->wf->nBlockAlign = 1152;
2028 else if ((track->a_formattag == 0x2000) || /* AC3 */
2029 (track->a_formattag == 0x2001)) /* DTS */
2031 free(sh_a->wf);
2032 sh_a->wf = NULL;
2034 else if (track->a_formattag == 0x0001) /* PCM || PCM_BE */
2036 sh_a->wf->nAvgBytesPerSec = sh_a->channels * sh_a->samplerate*2;
2037 sh_a->wf->nBlockAlign = sh_a->wf->nAvgBytesPerSec;
2038 if (!strcmp(track->codec_id, MKV_A_PCM_BE))
2039 sh_a->format = mmioFOURCC('t', 'w', 'o', 's');
2041 else if (!strcmp(track->codec_id, MKV_A_QDMC) ||
2042 !strcmp(track->codec_id, MKV_A_QDMC2))
2044 sh_a->wf->nAvgBytesPerSec = 16000;
2045 sh_a->wf->nBlockAlign = 1486;
2046 track->fix_i_bps = 1;
2047 track->qt_last_a_pts = 0.0;
2048 if (track->private_data != NULL)
2050 sh_a->codecdata=malloc(track->private_size);
2051 memcpy (sh_a->codecdata, track->private_data,
2052 track->private_size);
2053 sh_a->codecdata_len = track->private_size;
2056 else if (track->a_formattag == mmioFOURCC('M', 'P', '4', 'A'))
2058 int profile, srate_idx;
2060 sh_a->wf->nAvgBytesPerSec = 16000;
2061 sh_a->wf->nBlockAlign = 1024;
2063 if (!strcmp (track->codec_id, MKV_A_AAC) &&
2064 (NULL != track->private_data))
2066 sh_a->codecdata=malloc(track->private_size);
2067 memcpy (sh_a->codecdata, track->private_data,
2068 track->private_size);
2069 sh_a->codecdata_len = track->private_size;
2070 return 0;
2073 /* Recreate the 'private data' */
2074 /* which faad2 uses in its initialization */
2075 srate_idx = aac_get_sample_rate_index (sh_a->samplerate);
2076 if (!strncmp (&track->codec_id[12], "MAIN", 4))
2077 profile = 0;
2078 else if (!strncmp (&track->codec_id[12], "LC", 2))
2079 profile = 1;
2080 else if (!strncmp (&track->codec_id[12], "SSR", 3))
2081 profile = 2;
2082 else
2083 profile = 3;
2084 sh_a->codecdata = malloc (5);
2085 sh_a->codecdata[0] = ((profile+1) << 3) | ((srate_idx&0xE) >> 1);
2086 sh_a->codecdata[1] = ((srate_idx&0x1)<<7)|(track->a_channels<<3);
2088 if (strstr(track->codec_id, "SBR") != NULL)
2090 /* HE-AAC (aka SBR AAC) */
2091 sh_a->codecdata_len = 5;
2093 sh_a->samplerate *= 2;
2094 sh_a->wf->nSamplesPerSec *= 2;
2095 srate_idx = aac_get_sample_rate_index(sh_a->samplerate);
2096 sh_a->codecdata[2] = AAC_SYNC_EXTENSION_TYPE >> 3;
2097 sh_a->codecdata[3] = ((AAC_SYNC_EXTENSION_TYPE&0x07)<<5) | 5;
2098 sh_a->codecdata[4] = (1 << 7) | (srate_idx << 3);
2099 track->default_duration = 1024.0 / (sh_a->samplerate / 2);
2101 else
2103 sh_a->codecdata_len = 2;
2104 track->default_duration = 1024.0 / (float)sh_a->samplerate;
2107 else if (track->a_formattag == mmioFOURCC('v', 'r', 'b', 's')) /* VORBIS */
2109 sh_a->wf->cbSize = track->private_size;
2110 sh_a->wf = realloc(sh_a->wf, sizeof(WAVEFORMATEX) + sh_a->wf->cbSize);
2111 memcpy((unsigned char *) (sh_a->wf+1), track->private_data, sh_a->wf->cbSize);
2113 else if (track->private_size >= RAPROPERTIES4_SIZE
2114 && !strncmp (track->codec_id, MKV_A_REALATRC, 7))
2116 /* Common initialization for all RealAudio codecs */
2117 unsigned char *src = track->private_data;
2118 int codecdata_length, version;
2119 int flavor;
2121 sh_a->wf->nAvgBytesPerSec = 0; /* FIXME !? */
2123 version = AV_RB16(src + 4);
2124 flavor = AV_RB16(src + 22);
2125 track->coded_framesize = AV_RB32(src + 24);
2126 track->sub_packet_h = AV_RB16(src + 40);
2127 sh_a->wf->nBlockAlign =
2128 track->audiopk_size = AV_RB16(src + 42);
2129 track->sub_packet_size = AV_RB16(src + 44);
2130 if (version == 4)
2132 src += RAPROPERTIES4_SIZE;
2133 src += src[0] + 1;
2134 src += src[0] + 1;
2136 else
2137 src += RAPROPERTIES5_SIZE;
2139 src += 3;
2140 if (version == 5)
2141 src++;
2142 codecdata_length = AV_RB32(src);
2143 src += 4;
2144 sh_a->wf->cbSize = codecdata_length;
2145 sh_a->wf = realloc (sh_a->wf,
2146 sizeof (WAVEFORMATEX) +
2147 sh_a->wf->cbSize);
2148 memcpy(((char *)(sh_a->wf + 1)), src, codecdata_length);
2150 switch (track->a_formattag) {
2151 case mmioFOURCC('a', 't', 'r', 'c'):
2152 sh_a->wf->nAvgBytesPerSec = atrc_fl2bps[flavor];
2153 sh_a->wf->nBlockAlign = track->sub_packet_size;
2154 track->audio_buf = malloc(track->sub_packet_h * track->audiopk_size);
2155 track->audio_timestamp = malloc(track->sub_packet_h * sizeof(float));
2156 break;
2157 case mmioFOURCC('c', 'o', 'o', 'k'):
2158 sh_a->wf->nAvgBytesPerSec = cook_fl2bps[flavor];
2159 sh_a->wf->nBlockAlign = track->sub_packet_size;
2160 track->audio_buf = malloc(track->sub_packet_h * track->audiopk_size);
2161 track->audio_timestamp = malloc(track->sub_packet_h * sizeof(float));
2162 break;
2163 case mmioFOURCC('s', 'i', 'p', 'r'):
2164 sh_a->wf->nAvgBytesPerSec = sipr_fl2bps[flavor];
2165 sh_a->wf->nBlockAlign = track->coded_framesize;
2166 track->audio_buf = malloc(track->sub_packet_h * track->audiopk_size);
2167 track->audio_timestamp = malloc(track->sub_packet_h * sizeof(float));
2168 break;
2169 case mmioFOURCC('2', '8', '_', '8'):
2170 sh_a->wf->nAvgBytesPerSec = 3600;
2171 sh_a->wf->nBlockAlign = track->coded_framesize;
2172 track->audio_buf = malloc(track->sub_packet_h * track->audiopk_size);
2173 track->audio_timestamp = malloc(track->sub_packet_h * sizeof(float));
2174 break;
2177 track->realmedia = 1;
2179 else if (!strcmp(track->codec_id, MKV_A_FLAC) ||
2180 (track->a_formattag == 0xf1ac))
2182 unsigned char *ptr;
2183 int size;
2184 free(sh_a->wf);
2185 sh_a->wf = NULL;
2187 if (track->a_formattag == mmioFOURCC('f', 'L', 'a', 'C'))
2189 ptr = (unsigned char *)track->private_data;
2190 size = track->private_size;
2192 else
2194 sh_a->format = mmioFOURCC('f', 'L', 'a', 'C');
2195 ptr = (unsigned char *) track->private_data
2196 + sizeof (WAVEFORMATEX);
2197 size = track->private_size - sizeof (WAVEFORMATEX);
2199 if (size < 4 || ptr[0] != 'f' || ptr[1] != 'L' ||
2200 ptr[2] != 'a' || ptr[3] != 'C')
2202 dp = new_demux_packet (4);
2203 memcpy (dp->buffer, "fLaC", 4);
2205 else
2207 dp = new_demux_packet (size);
2208 memcpy (dp->buffer, ptr, size);
2210 dp->pts = 0;
2211 dp->flags = 0;
2212 ds_add_packet (demuxer->audio, dp);
2214 else if (track->a_formattag == mmioFOURCC('W', 'V', 'P', 'K'))
2215 { /* do nothing, still works */ }
2216 else if (!track->ms_compat || (track->private_size < sizeof(WAVEFORMATEX)))
2218 free_sh_audio(demuxer, track->tnum);
2219 return 1;
2222 return 0;
2225 /** \brief Parse the private data for VobSub subtitle tracks.
2227 This function tries to parse the private data for all VobSub tracks.
2228 The private data contains the normal text from the original .idx file.
2229 Things like the palette, subtitle dimensions and custom colors are
2230 stored here.
2232 \param demuxer The generic demuxer.
2234 static void
2235 demux_mkv_parse_vobsub_data (demuxer_t *demuxer)
2237 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2238 mkv_track_t *track;
2239 int i, m, size;
2240 uint8_t *buffer;
2242 for (i = 0; i < mkv_d->num_tracks; i++)
2244 track = mkv_d->tracks[i];
2245 if ((track->type != MATROSKA_TRACK_SUBTITLE) ||
2246 (track->subtitle_type != MATROSKA_SUBTYPE_VOBSUB))
2247 continue;
2249 size = track->private_size;
2250 m = demux_mkv_decode (track,track->private_data,&buffer,&size,2);
2251 if (buffer && m)
2253 free (track->private_data);
2254 track->private_data = buffer;
2255 track->private_size = size;
2257 if (!demux_mkv_parse_idx (track))
2259 free (track->private_data);
2260 track->private_data = NULL;
2261 track->private_size = 0;
2266 /** \brief Parse the private data for SSA/ASS subtitle tracks.
2268 This function tries to parse the private data for all SSA/ASS tracks.
2269 The private data contains the normal text from the original script,
2270 from the start to the beginning of 'Events' section, including '[Events]' line.
2272 \param demuxer The generic demuxer.
2274 #ifdef USE_ASS
2275 static void
2276 demux_mkv_parse_ass_data (demuxer_t *demuxer)
2278 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2279 mkv_track_t *track;
2280 int i, m, size;
2281 uint8_t *buffer;
2283 for (i = 0; i < mkv_d->num_tracks; i++)
2285 track = mkv_d->tracks[i];
2286 if (track->type != MATROSKA_TRACK_SUBTITLE ||
2287 track->subtitle_type == MATROSKA_SUBTYPE_VOBSUB)
2288 continue;
2290 if (track->subtitle_type == MATROSKA_SUBTYPE_SSA)
2292 track->sh_sub->ass_track = ass_new_track(ass_library);
2293 size = track->private_size;
2294 m = demux_mkv_decode (track,track->private_data,&buffer,&size,2);
2295 if (buffer && m)
2297 free (track->private_data);
2298 track->private_data = buffer;
2299 track->private_size = size;
2301 ass_process_codec_private(track->sh_sub->ass_track, track->private_data, track->private_size);
2305 #endif
2307 static int
2308 demux_mkv_open_sub (demuxer_t *demuxer, mkv_track_t *track, int sid)
2310 if (track->subtitle_type != MATROSKA_SUBTYPE_UNKNOWN)
2312 sh_sub_t *sh = new_sh_sub_sid(demuxer, track->tnum, sid);
2313 track->sh_sub = sh;
2314 sh->type = 't';
2315 if (track->subtitle_type == MATROSKA_SUBTYPE_VOBSUB)
2316 sh->type = 'v';
2317 if (track->subtitle_type == MATROSKA_SUBTYPE_SSA)
2318 sh->type = 'a';
2320 else
2322 mp_msg (MSGT_DEMUX, MSGL_ERR, MSGTR_MPDEMUX_MKV_SubtitleTypeNotSupported,
2323 track->codec_id);
2324 return 1;
2327 return 0;
2330 static void demux_mkv_seek (demuxer_t *demuxer, float rel_seek_secs, float audio_delay, int flags);
2332 /** \brief Given a matroska track number and type, find the id that mplayer would ask for.
2333 * \param d The demuxer for which the subtitle id should be returned.
2334 * \param num The matroska track number we are looking up.
2335 * \param type The track type.
2337 static int demux_mkv_reverse_id(mkv_demuxer_t *d, int num, int type)
2339 int i, id;
2341 for (i=0, id=0; i < d->num_tracks; i++)
2342 if (d->tracks[i] != NULL && d->tracks[i]->type == type) {
2343 if (d->tracks[i]->tnum == num)
2344 return id;
2345 id++;
2348 return -1;
2351 static int
2352 demux_mkv_open (demuxer_t *demuxer)
2354 stream_t *s = demuxer->stream;
2355 mkv_demuxer_t *mkv_d;
2356 mkv_track_t *track;
2357 int i, version, cont = 0;
2358 char *str;
2360 stream_seek(s, s->start_pos);
2361 str = ebml_read_header (s, &version);
2362 if (str == NULL || strcmp (str, "matroska") || version > 2)
2364 mp_msg (MSGT_DEMUX, MSGL_DBG2, "[mkv] no head found\n");
2365 return 0;
2367 free (str);
2369 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] Found the head...\n");
2371 if (ebml_read_id (s, NULL) != MATROSKA_ID_SEGMENT)
2373 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] but no segment :(\n");
2374 return 0;
2376 ebml_read_length (s, NULL); /* return bytes number until EOF */
2378 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] + a segment...\n");
2380 mkv_d = calloc (1, sizeof (mkv_demuxer_t));
2381 demuxer->priv = mkv_d;
2382 mkv_d->tc_scale = 1000000;
2383 mkv_d->segment_start = stream_tell (s);
2384 mkv_d->parsed_cues = malloc (sizeof (off_t));
2385 mkv_d->parsed_seekhead = malloc (sizeof (off_t));
2387 while (!cont)
2389 switch (ebml_read_id (s, NULL))
2391 case MATROSKA_ID_INFO:
2392 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] |+ segment information...\n");
2393 cont = demux_mkv_read_info (demuxer);
2394 break;
2396 case MATROSKA_ID_TRACKS:
2397 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] |+ segment tracks...\n");
2398 cont = demux_mkv_read_tracks (demuxer);
2399 break;
2401 case MATROSKA_ID_CUES:
2402 cont = demux_mkv_read_cues (demuxer);
2403 break;
2405 case MATROSKA_ID_TAGS:
2406 cont = demux_mkv_read_tags (demuxer);
2407 break;
2409 case MATROSKA_ID_SEEKHEAD:
2410 cont = demux_mkv_read_seekhead (demuxer);
2411 break;
2413 case MATROSKA_ID_CHAPTERS:
2414 cont = demux_mkv_read_chapters (demuxer);
2415 break;
2417 case MATROSKA_ID_ATTACHMENTS:
2418 cont = demux_mkv_read_attachments (demuxer);
2419 break;
2421 case MATROSKA_ID_CLUSTER:
2423 int p, l;
2424 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] |+ found cluster, headers are "
2425 "parsed completely :)\n");
2426 /* get the first cluster timecode */
2427 p = stream_tell(s);
2428 l = ebml_read_length (s, NULL);
2429 while (ebml_read_id (s, NULL) != MATROSKA_ID_CLUSTERTIMECODE)
2431 ebml_read_skip (s, NULL);
2432 if (stream_tell (s) >= p + l)
2433 break;
2435 if (stream_tell (s) < p + l)
2437 uint64_t num = ebml_read_uint (s, NULL);
2438 if (num == EBML_UINT_INVALID)
2439 return 0;
2440 mkv_d->first_tc = num * mkv_d->tc_scale / 1000000.0;
2441 mkv_d->has_first_tc = 1;
2443 stream_seek (s, p - 4);
2444 cont = 1;
2445 break;
2448 default:
2449 cont = 1;
2450 case EBML_ID_VOID:
2451 ebml_read_skip (s, NULL);
2452 break;
2456 display_create_tracks (demuxer);
2458 /* select video track */
2459 track = NULL;
2460 if (demuxer->video->id == -1) /* automatically select a video track */
2462 /* search for a video track that has the 'default' flag set */
2463 for (i=0; i<mkv_d->num_tracks; i++)
2464 if (mkv_d->tracks[i]->type == MATROSKA_TRACK_VIDEO
2465 && mkv_d->tracks[i]->default_track)
2467 track = mkv_d->tracks[i];
2468 break;
2471 if (track == NULL)
2472 /* no track has the 'default' flag set */
2473 /* let's take the first video track */
2474 for (i=0; i<mkv_d->num_tracks; i++)
2475 if (mkv_d->tracks[i]->type == MATROSKA_TRACK_VIDEO)
2477 track = mkv_d->tracks[i];
2478 break;
2481 else if (demuxer->video->id != -2) /* -2 = no video at all */
2482 track = demux_mkv_find_track_by_num (mkv_d, demuxer->video->id,
2483 MATROSKA_TRACK_VIDEO);
2485 if (track && demuxer->v_streams[track->tnum])
2487 mp_msg (MSGT_DEMUX, MSGL_INFO,
2488 MSGTR_MPDEMUX_MKV_WillPlayVideoTrack, track->tnum);
2489 demuxer->video->id = track->tnum;
2490 demuxer->video->sh = demuxer->v_streams[track->tnum];
2492 else
2494 mp_msg (MSGT_DEMUX, MSGL_INFO, MSGTR_MPDEMUX_MKV_NoVideoTrackFound);
2495 demuxer->video->id = -2;
2498 /* select audio track */
2499 track = NULL;
2500 if (demuxer->audio->id == -1) /* automatically select an audio track */
2502 /* check if the user specified an audio language */
2503 if (audio_lang != NULL)
2504 track = demux_mkv_find_track_by_language(mkv_d, audio_lang,
2505 MATROSKA_TRACK_AUDIO);
2506 if (track == NULL)
2507 /* no audio language specified, or language not found */
2508 /* search for an audio track that has the 'default' flag set */
2509 for (i=0; i < mkv_d->num_tracks; i++)
2510 if (mkv_d->tracks[i]->type == MATROSKA_TRACK_AUDIO
2511 && mkv_d->tracks[i]->default_track)
2513 track = mkv_d->tracks[i];
2514 break;
2517 if (track == NULL)
2518 /* no track has the 'default' flag set */
2519 /* let's take the first audio track */
2520 for (i=0; i < mkv_d->num_tracks; i++)
2521 if (mkv_d->tracks[i]->type == MATROSKA_TRACK_AUDIO)
2523 track = mkv_d->tracks[i];
2524 break;
2527 else if (demuxer->audio->id != -2) /* -2 = no audio at all */
2528 track = demux_mkv_find_track_by_num (mkv_d, demuxer->audio->id,
2529 MATROSKA_TRACK_AUDIO);
2530 if (track && demuxer->a_streams[track->tnum])
2532 demuxer->audio->id = track->tnum;
2533 demuxer->audio->sh = demuxer->a_streams[track->tnum];
2535 else
2537 mp_msg (MSGT_DEMUX, MSGL_INFO, MSGTR_MPDEMUX_MKV_NoAudioTrackFound);
2538 demuxer->audio->id = -2;
2542 if(demuxer->audio->id != -2)
2543 for (i=0; i < mkv_d->num_tracks; i++)
2545 if(mkv_d->tracks[i]->type != MATROSKA_TRACK_AUDIO)
2546 continue;
2547 if(demuxer->a_streams[track->tnum])
2549 mkv_d->last_aid++;
2550 if(mkv_d->last_aid == MAX_A_STREAMS)
2551 break;
2555 demux_mkv_parse_vobsub_data (demuxer);
2556 #ifdef USE_ASS
2557 if (ass_enabled)
2558 demux_mkv_parse_ass_data (demuxer);
2559 #endif
2560 /* DO NOT automatically select a subtitle track and behave like DVD */
2561 /* playback: only show subtitles if the user explicitely wants them. */
2562 track = NULL;
2563 if (demuxer->sub->id >= 0)
2564 track = demux_mkv_find_track_by_num (mkv_d, demuxer->sub->id,
2565 MATROSKA_TRACK_SUBTITLE);
2566 else if (dvdsub_lang != NULL)
2567 track = demux_mkv_find_track_by_language (mkv_d, dvdsub_lang,
2568 MATROSKA_TRACK_SUBTITLE);
2570 if (track)
2572 mp_msg (MSGT_DEMUX, MSGL_INFO,
2573 MSGTR_MPDEMUX_MKV_WillDisplaySubtitleTrack, track->tnum);
2574 dvdsub_id = demux_mkv_reverse_id(mkv_d, track->tnum, MATROSKA_TRACK_SUBTITLE);
2575 demuxer->sub->id = track->tnum;
2576 demuxer->sub->sh = demuxer->s_streams[track->tnum];
2578 else
2579 demuxer->sub->id = -2;
2581 if (demuxer->chapters)
2583 for (i=0; i < (int)demuxer->num_chapters; i++)
2585 demuxer->chapters[i].start -= mkv_d->first_tc;
2586 demuxer->chapters[i].end -= mkv_d->first_tc;
2588 if (dvd_last_chapter > 0 && dvd_last_chapter <= demuxer->num_chapters)
2590 if (demuxer->chapters[dvd_last_chapter-1].end != 0)
2591 mkv_d->stop_timecode = demuxer->chapters[dvd_last_chapter-1].end;
2592 else if (dvd_last_chapter + 1 <= demuxer->num_chapters)
2593 mkv_d->stop_timecode = demuxer->chapters[dvd_last_chapter].start;
2597 if (s->end_pos == 0 || (mkv_d->indexes == NULL && index_mode < 0))
2598 demuxer->seekable = 0;
2599 else
2601 demuxer->movi_start = s->start_pos;
2602 demuxer->movi_end = s->end_pos;
2603 demuxer->seekable = 1;
2604 if (demuxer->chapters && dvd_chapter>1 && dvd_chapter<=demuxer->num_chapters)
2606 if (!mkv_d->has_first_tc)
2608 mkv_d->first_tc = 0;
2609 mkv_d->has_first_tc = 1;
2611 demux_mkv_seek (demuxer,
2612 demuxer->chapters[dvd_chapter-1].start/1000.0, 0.0, 1);
2616 return DEMUXER_TYPE_MATROSKA;
2619 static void
2620 demux_close_mkv (demuxer_t *demuxer)
2622 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2624 if (mkv_d)
2626 int i;
2627 free_cached_dps (demuxer);
2628 if (mkv_d->tracks)
2630 for (i=0; i<mkv_d->num_tracks; i++)
2631 demux_mkv_free_trackentry(mkv_d->tracks[i]);
2632 free (mkv_d->tracks);
2634 if (mkv_d->indexes)
2635 free (mkv_d->indexes);
2636 if (mkv_d->cluster_positions)
2637 free (mkv_d->cluster_positions);
2638 if (mkv_d->parsed_cues)
2639 free (mkv_d->parsed_cues);
2640 if (mkv_d->parsed_seekhead)
2641 free (mkv_d->parsed_seekhead);
2642 if (mkv_d->attachments) {
2643 for (i = 0; i < mkv_d->num_attachments; ++i) {
2644 if (mkv_d->attachments[i].name)
2645 free (mkv_d->attachments[i].name);
2646 if (mkv_d->attachments[i].mime)
2647 free (mkv_d->attachments[i].mime);
2648 if (mkv_d->attachments[i].data)
2649 free (mkv_d->attachments[i].data);
2651 free (mkv_d->attachments);
2653 free (mkv_d);
2657 static int
2658 demux_mkv_read_block_lacing (uint8_t *buffer, uint64_t *size,
2659 uint8_t *laces, uint32_t **all_lace_sizes)
2661 uint32_t total = 0, *lace_size;
2662 uint8_t flags;
2663 int i;
2665 *all_lace_sizes = NULL;
2666 lace_size = NULL;
2667 /* lacing flags */
2668 flags = *buffer++;
2669 (*size)--;
2671 switch ((flags & 0x06) >> 1)
2673 case 0: /* no lacing */
2674 *laces = 1;
2675 lace_size = calloc(*laces, sizeof(uint32_t));
2676 lace_size[0] = *size;
2677 break;
2679 case 1: /* xiph lacing */
2680 case 2: /* fixed-size lacing */
2681 case 3: /* EBML lacing */
2682 *laces = *buffer++;
2683 (*size)--;
2684 (*laces)++;
2685 lace_size = calloc(*laces, sizeof(uint32_t));
2687 switch ((flags & 0x06) >> 1)
2689 case 1: /* xiph lacing */
2690 for (i=0; i < *laces-1; i++)
2692 lace_size[i] = 0;
2695 lace_size[i] += *buffer;
2696 (*size)--;
2697 } while (*buffer++ == 0xFF);
2698 total += lace_size[i];
2700 lace_size[i] = *size - total;
2701 break;
2703 case 2: /* fixed-size lacing */
2704 for (i=0; i < *laces; i++)
2705 lace_size[i] = *size / *laces;
2706 break;
2708 case 3: /* EBML lacing */
2710 int l;
2711 uint64_t num = ebml_read_vlen_uint (buffer, &l);
2712 if (num == EBML_UINT_INVALID) {
2713 free(lace_size);
2714 return 1;
2716 buffer += l;
2717 *size -= l;
2719 total = lace_size[0] = num;
2720 for (i=1; i < *laces-1; i++)
2722 int64_t snum;
2723 snum = ebml_read_vlen_int (buffer, &l);
2724 if (snum == EBML_INT_INVALID) {
2725 free(lace_size);
2726 return 1;
2728 buffer += l;
2729 *size -= l;
2730 lace_size[i] = lace_size[i-1] + snum;
2731 total += lace_size[i];
2733 lace_size[i] = *size - total;
2734 break;
2737 break;
2739 *all_lace_sizes = lace_size;
2740 return 0;
2743 static void
2744 handle_subtitles(demuxer_t *demuxer, mkv_track_t *track, char *block,
2745 int64_t size, uint64_t block_duration, uint64_t timecode)
2747 demux_packet_t *dp;
2748 char *ptr1;
2749 int i;
2751 if (block_duration == 0)
2753 mp_msg (MSGT_DEMUX, MSGL_WARN,
2754 MSGTR_MPDEMUX_MKV_NoBlockDurationForSubtitleTrackFound);
2755 return;
2758 #ifdef USE_ASS
2759 if (ass_enabled && track->subtitle_type == MATROSKA_SUBTYPE_SSA) {
2760 ass_process_chunk(track->sh_sub->ass_track, block, size, (long long)timecode, (long long)block_duration);
2761 return;
2763 #endif
2765 ptr1 = block;
2766 if (track->subtitle_type == MATROSKA_SUBTYPE_SSA)
2768 /* Find text section. */
2769 for (i=0; i < 8 && *ptr1 != '\0'; ptr1++)
2770 if (*ptr1 == ',')
2771 i++;
2772 if (*ptr1 == '\0') /* Broken line? */
2773 return;
2776 sub_utf8 = 1;
2777 size -= ptr1 - block;
2778 dp = new_demux_packet(size);
2779 memcpy(dp->buffer, ptr1, size);
2780 dp->pts = timecode / 1000.0f;
2781 dp->endpts = (timecode + block_duration) / 1000.0f;
2782 ds_add_packet(demuxer->sub, dp);
2785 // Taken from demux_real.c. Thanks to the original developpers :)
2786 #define SKIP_BITS(n) buffer <<= n
2787 #define SHOW_BITS(n) ((buffer) >> (32 - (n)))
2789 static float real_fix_timestamp(mkv_track_t *track, unsigned char *s,
2790 int timestamp) {
2791 float v_pts;
2792 uint32_t buffer = (s[0] << 24) + (s[1] << 16) + (s[2] << 8) + s[3];
2793 int kf = timestamp;
2794 int pict_type;
2795 int orig_kf;
2797 if (!strcmp(track->codec_id, MKV_V_REALV30) ||
2798 !strcmp(track->codec_id, MKV_V_REALV40)) {
2800 if (!strcmp(track->codec_id, MKV_V_REALV30)) {
2801 SKIP_BITS(3);
2802 pict_type = SHOW_BITS(2);
2803 SKIP_BITS(2 + 7);
2804 }else{
2805 SKIP_BITS(1);
2806 pict_type = SHOW_BITS(2);
2807 SKIP_BITS(2 + 7 + 3);
2809 kf = SHOW_BITS(13); // kf= 2*SHOW_BITS(12);
2810 orig_kf = kf;
2811 if (pict_type <= 1) {
2812 // I frame, sync timestamps:
2813 track->rv_kf_base = timestamp - kf;
2814 mp_msg(MSGT_DEMUX, MSGL_DBG2, "\nTS: base=%08X\n", track->rv_kf_base);
2815 kf = timestamp;
2816 } else {
2817 // P/B frame, merge timestamps:
2818 int tmp = timestamp - track->rv_kf_base;
2819 kf |= tmp & (~0x1fff); // combine with packet timestamp
2820 if (kf < (tmp - 4096)) // workaround wrap-around problems
2821 kf += 8192;
2822 else if (kf > (tmp + 4096))
2823 kf -= 8192;
2824 kf += track->rv_kf_base;
2826 if (pict_type != 3) { // P || I frame -> swap timestamps
2827 int tmp = kf;
2828 kf = track->rv_kf_pts;
2829 track->rv_kf_pts = tmp;
2831 mp_msg(MSGT_DEMUX, MSGL_DBG2, "\nTS: %08X -> %08X (%04X) %d %02X %02X %02X "
2832 "%02X %5d\n", timestamp, kf, orig_kf, pict_type, s[0], s[1], s[2],
2833 s[3], kf - (int)(1000.0 * track->rv_pts));
2835 v_pts = kf * 0.001f;
2836 track->rv_pts = v_pts;
2838 return v_pts;
2841 static void
2842 handle_realvideo (demuxer_t *demuxer, mkv_track_t *track, uint8_t *buffer,
2843 uint32_t size, int block_bref)
2845 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2846 demux_packet_t *dp;
2847 uint32_t timestamp = mkv_d->last_pts * 1000;
2848 uint32_t *hdr;
2849 uint8_t chunks;
2850 int isize;
2851 #ifdef WORDS_BIGENDIAN
2852 uint8_t *p;
2853 int i;
2854 #endif
2856 chunks = *buffer++;
2857 isize = --size - (chunks+1)*8;
2858 dp = new_demux_packet (REALHEADER_SIZE + size);
2859 memcpy (dp->buffer + REALHEADER_SIZE, buffer + (chunks+1)*8, isize);
2860 #ifdef WORDS_BIGENDIAN
2861 p = (uint8_t *)(dp->buffer + REALHEADER_SIZE + isize);
2862 for (i = 0; i<(chunks+1)*8; i+=4) {
2863 p[i] = *((uint8_t *)buffer+i+3);
2864 p[i+1] = *((uint8_t *)buffer+i+2);
2865 p[i+2] = *((uint8_t *)buffer+i+1);
2866 p[i+3] = *((uint8_t *)buffer+i);
2868 #else
2869 memcpy (dp->buffer + REALHEADER_SIZE + isize, buffer, (chunks+1)*8);
2870 #endif
2872 hdr = dp->buffer;
2873 *hdr++ = chunks; // number of chunks
2874 *hdr++ = timestamp; // timestamp from packet header
2875 *hdr++ = isize; // length of actual data
2876 *hdr++ = REALHEADER_SIZE + isize; // offset to chunk offset array
2878 if (mkv_d->v_skip_to_keyframe)
2880 dp->pts = mkv_d->last_pts;
2881 track->rv_kf_base = 0;
2882 track->rv_kf_pts = timestamp;
2884 else
2885 dp->pts = real_fix_timestamp (track, dp->buffer + REALHEADER_SIZE,
2886 timestamp);
2887 dp->pos = demuxer->filepos;
2888 dp->flags = block_bref ? 0 : 0x10;
2890 ds_add_packet(demuxer->video, dp);
2893 static void
2894 handle_realaudio (demuxer_t *demuxer, mkv_track_t *track, uint8_t *buffer,
2895 uint32_t size, int block_bref)
2897 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
2898 int sps = track->sub_packet_size;
2899 int sph = track->sub_packet_h;
2900 int cfs = track->coded_framesize;
2901 int w = track->audiopk_size;
2902 int spc = track->sub_packet_cnt;
2903 demux_packet_t *dp;
2904 int x;
2906 if ((track->a_formattag == mmioFOURCC('2', '8', '_', '8')) ||
2907 (track->a_formattag == mmioFOURCC('c', 'o', 'o', 'k')) ||
2908 (track->a_formattag == mmioFOURCC('a', 't', 'r', 'c')) ||
2909 (track->a_formattag == mmioFOURCC('s', 'i', 'p', 'r')))
2911 // if(!block_bref)
2912 // spc = track->sub_packet_cnt = 0;
2913 switch (track->a_formattag) {
2914 case mmioFOURCC('2', '8', '_', '8'):
2915 for (x = 0; x < sph / 2; x++)
2916 memcpy(track->audio_buf + x * 2 * w + spc * cfs, buffer + cfs * x, cfs);
2917 break;
2918 case mmioFOURCC('c', 'o', 'o', 'k'):
2919 case mmioFOURCC('a', 't', 'r', 'c'):
2920 for (x = 0; x < w / sps; x++)
2921 memcpy(track->audio_buf + sps * (sph * x + ((sph + 1) / 2) * (spc & 1) + (spc >> 1)), buffer + sps * x, sps);
2922 break;
2923 case mmioFOURCC('s', 'i', 'p', 'r'):
2924 memcpy(track->audio_buf + spc * w, buffer, w);
2925 if (spc == sph - 1)
2927 int n;
2928 int bs = sph * w * 2 / 96; // nibbles per subpacket
2929 // Perform reordering
2930 for(n=0; n < 38; n++)
2932 int j;
2933 int i = bs * sipr_swaps[n][0];
2934 int o = bs * sipr_swaps[n][1];
2935 // swap nibbles of block 'i' with 'o' TODO: optimize
2936 for(j = 0;j < bs; j++)
2938 int x = (i & 1) ? (track->audio_buf[i >> 1] >> 4) : (track->audio_buf[i >> 1] & 0x0F);
2939 int y = (o & 1) ? (track->audio_buf[o >> 1] >> 4) : (track->audio_buf[o >> 1] & 0x0F);
2940 if(o & 1)
2941 track->audio_buf[o >> 1] = (track->audio_buf[o >> 1] & 0x0F) | (x << 4);
2942 else
2943 track->audio_buf[o >> 1] = (track->audio_buf[o >> 1] & 0xF0) | x;
2944 if(i & 1)
2945 track->audio_buf[i >> 1] = (track->audio_buf[i >> 1] & 0x0F) | (y << 4);
2946 else
2947 track->audio_buf[i >> 1] = (track->audio_buf[i >> 1] & 0xF0) | y;
2948 ++i; ++o;
2952 break;
2954 track->audio_timestamp[track->sub_packet_cnt] = (track->ra_pts == mkv_d->last_pts) ? 0 : (mkv_d->last_pts);
2955 track->ra_pts = mkv_d->last_pts;
2956 if (track->sub_packet_cnt == 0)
2957 track->audio_filepos = demuxer->filepos;
2958 if (++(track->sub_packet_cnt) == sph)
2960 int apk_usize = ((WAVEFORMATEX*)((sh_audio_t*)demuxer->audio->sh)->wf)->nBlockAlign;
2961 track->sub_packet_cnt = 0;
2962 // Release all the audio packets
2963 for (x = 0; x < sph*w/apk_usize; x++)
2965 dp = new_demux_packet(apk_usize);
2966 memcpy(dp->buffer, track->audio_buf + x * apk_usize, apk_usize);
2967 /* Put timestamp only on packets that correspond to original audio packets in file */
2968 dp->pts = (x * apk_usize % w) ? 0 : track->audio_timestamp[x * apk_usize / w];
2969 dp->pos = track->audio_filepos; // all equal
2970 dp->flags = x ? 0 : 0x10; // Mark first packet as keyframe
2971 ds_add_packet(demuxer->audio, dp);
2974 } else { // Not a codec that require reordering
2975 dp = new_demux_packet (size);
2976 memcpy(dp->buffer, buffer, size);
2977 if (track->ra_pts == mkv_d->last_pts && !mkv_d->a_skip_to_keyframe)
2978 dp->pts = 0;
2979 else
2980 dp->pts = mkv_d->last_pts;
2981 track->ra_pts = mkv_d->last_pts;
2983 dp->pos = demuxer->filepos;
2984 dp->flags = block_bref ? 0 : 0x10;
2985 ds_add_packet (demuxer->audio, dp);
2989 /** Reorder timecodes and add cached demux packets to the queues.
2991 * Timecode reordering is needed if a video track contains B frames that
2992 * are timestamped in display order (e.g. MPEG-1, MPEG-2 or "native" MPEG-4).
2993 * MPlayer doesn't like timestamps in display order. This function adjusts
2994 * the timestamp of cached frames (which are exactly one I/P frame followed
2995 * by one or more B frames) so that they are in coding order again.
2997 * Example: The track with 25 FPS contains four frames with the timecodes
2998 * I at 0ms, P at 120ms, B at 40ms and B at 80ms. As soon as the next I
2999 * or P frame arrives these timecodes can be changed to I at 0ms, P at 40ms,
3000 * B at 80ms and B at 120ms.
3002 * This works for simple H.264 B-frame pyramids, but not for arbitrary orders.
3004 * \param demuxer The Matroska demuxer struct for this instance.
3005 * \param track The track structure whose cache should be handled.
3007 static void
3008 flush_cached_dps (demuxer_t *demuxer, mkv_track_t *track)
3010 int i, ok;
3012 if (track->num_cached_dps == 0)
3013 return;
3015 do {
3016 ok = 1;
3017 for (i = 1; i < track->num_cached_dps; i++)
3018 if (track->cached_dps[i - 1]->pts > track->cached_dps[i]->pts) {
3019 float tmp_pts = track->cached_dps[i - 1]->pts;
3020 track->cached_dps[i - 1]->pts = track->cached_dps[i]->pts;
3021 track->cached_dps[i]->pts = tmp_pts;
3022 ok = 0;
3024 } while (!ok);
3026 for (i = 0; i < track->num_cached_dps; i++)
3027 ds_add_packet (demuxer->video, track->cached_dps[i]);
3028 track->num_cached_dps = 0;
3031 /** Cache video frames if timecodes have to be reordered.
3033 * Timecode reordering is needed if a video track contains B frames that
3034 * are timestamped in display order (e.g. MPEG-1, MPEG-2 or "native" MPEG-4).
3035 * This function takes in a Matroska block read from the file, allocates a
3036 * demux packet for it, fills in its values, allocates space for storing
3037 * pointers to the cached demux packets and adds the packet to it. If
3038 * the packet contains an I or a P frame then ::flush_cached_dps is called
3039 * in order to send the old cached frames downstream.
3041 * \param demuxer The Matroska demuxer struct for this instance.
3042 * \param track The packet is meant for this track.
3043 * \param buffer The actual frame contents.
3044 * \param size The frame size in bytes.
3045 * \param block_bref A relative timecode (backward reference). If it is \c 0
3046 * then the frame is an I frame.
3047 * \param block_fref A relative timecode (forward reference). If it is \c 0
3048 * then the frame is either an I frame or a P frame depending on the value
3049 * of \a block_bref. Otherwise it's a B frame.
3051 static void
3052 handle_video_bframes (demuxer_t *demuxer, mkv_track_t *track, uint8_t *buffer,
3053 uint32_t size, int block_bref, int block_fref)
3055 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
3056 demux_packet_t *dp;
3058 dp = new_demux_packet (size);
3059 memcpy(dp->buffer, buffer, size);
3060 dp->pos = demuxer->filepos;
3061 dp->pts = mkv_d->last_pts;
3062 if ((track->num_cached_dps > 0) && (dp->pts < track->max_pts))
3063 block_fref = 1;
3064 if (block_fref == 0) /* I or P frame */
3065 flush_cached_dps (demuxer, track);
3066 if (block_bref != 0) /* I frame, don't cache it */
3067 dp->flags = 0x10;
3068 if ((track->num_cached_dps + 1) > track->num_allocated_dps)
3070 track->cached_dps = (demux_packet_t **)
3071 realloc(track->cached_dps, (track->num_cached_dps + 10) *
3072 sizeof(demux_packet_t *));
3073 track->num_allocated_dps += 10;
3075 track->cached_dps[track->num_cached_dps] = dp;
3076 track->num_cached_dps++;
3077 if (dp->pts > track->max_pts)
3078 track->max_pts = dp->pts;
3081 static int
3082 handle_block (demuxer_t *demuxer, uint8_t *block, uint64_t length,
3083 uint64_t block_duration, int64_t block_bref, int64_t block_fref, uint8_t simpleblock)
3085 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
3086 mkv_track_t *track = NULL;
3087 demux_stream_t *ds = NULL;
3088 uint64_t old_length;
3089 int64_t tc;
3090 uint32_t *lace_size;
3091 uint8_t laces, flags;
3092 int i, num, tmp, use_this_block = 1;
3093 float current_pts;
3094 int16_t time;
3096 /* first byte(s): track num */
3097 num = ebml_read_vlen_uint (block, &tmp);
3098 block += tmp;
3099 /* time (relative to cluster time) */
3100 time = block[0] << 8 | block[1];
3101 block += 2;
3102 length -= tmp + 2;
3103 old_length = length;
3104 flags = block[0];
3105 if (demux_mkv_read_block_lacing (block, &length, &laces, &lace_size))
3106 return 0;
3107 block += old_length - length;
3109 tc = ((time*mkv_d->tc_scale+mkv_d->cluster_tc) /1000000.0 - mkv_d->first_tc);
3110 if (tc < 0)
3111 tc = 0;
3112 if (mkv_d->stop_timecode > 0 && tc > mkv_d->stop_timecode) {
3113 free(lace_size);
3114 return -1;
3116 current_pts = tc / 1000.0;
3118 for (i=0; i<mkv_d->num_tracks; i++)
3119 if (mkv_d->tracks[i]->tnum == num) {
3120 track = mkv_d->tracks[i];
3121 break;
3123 if (track == NULL)
3125 free(lace_size);
3126 return 1;
3128 if (num == demuxer->audio->id)
3130 ds = demuxer->audio;
3132 if (mkv_d->a_skip_to_keyframe)
3134 if (simpleblock)
3136 if (!(flags&0x80)) /*current frame isn't a keyframe*/
3137 use_this_block = 0;
3139 else if (block_bref != 0)
3140 use_this_block = 0;
3142 else if (mkv_d->v_skip_to_keyframe)
3143 use_this_block = 0;
3145 if (track->fix_i_bps && use_this_block)
3147 sh_audio_t *sh = (sh_audio_t *) ds->sh;
3149 if (block_duration != 0)
3151 sh->i_bps = length * 1000 / block_duration;
3152 track->fix_i_bps = 0;
3154 else if (track->qt_last_a_pts == 0.0)
3155 track->qt_last_a_pts = current_pts;
3156 else if(track->qt_last_a_pts != current_pts)
3158 sh->i_bps = length / (current_pts - track->qt_last_a_pts);
3159 track->fix_i_bps = 0;
3163 else if (tc < mkv_d->skip_to_timecode)
3164 use_this_block = 0;
3165 else if (num == demuxer->video->id)
3167 ds = demuxer->video;
3168 if (mkv_d->v_skip_to_keyframe)
3170 if (simpleblock)
3172 if (!(flags&0x80)) /*current frame isn't a keyframe*/
3173 use_this_block = 0;
3175 else if (block_bref != 0 || block_fref != 0)
3176 use_this_block = 0;
3179 else if (num == demuxer->sub->id)
3181 ds = demuxer->sub;
3182 if (track->subtitle_type != MATROSKA_SUBTYPE_VOBSUB)
3184 if (!mkv_d->v_skip_to_keyframe)
3185 handle_subtitles (demuxer, track, block, length,
3186 block_duration, tc);
3187 use_this_block = 0;
3190 else
3191 use_this_block = 0;
3193 if (use_this_block)
3195 mkv_d->last_pts = current_pts;
3196 mkv_d->last_filepos = demuxer->filepos;
3198 for (i=0; i < laces; i++)
3200 if (ds == demuxer->video && track->realmedia)
3201 handle_realvideo (demuxer, track, block, lace_size[i], block_bref);
3202 else if (ds == demuxer->audio && track->realmedia)
3203 handle_realaudio (demuxer, track, block, lace_size[i], block_bref);
3204 else if (ds == demuxer->video && track->reorder_timecodes)
3205 handle_video_bframes (demuxer, track, block, lace_size[i],
3206 block_bref, block_fref);
3207 else
3209 int modified, size = lace_size[i];
3210 demux_packet_t *dp;
3211 uint8_t *buffer;
3212 modified = demux_mkv_decode (track, block, &buffer, &size, 1);
3213 if (buffer)
3215 dp = new_demux_packet (size);
3216 memcpy (dp->buffer, buffer, size);
3217 if (modified)
3218 free (buffer);
3219 dp->flags = (block_bref == 0 && block_fref == 0) ? 0x10 : 0;
3220 /* If default_duration is 0, assume no pts value is known
3221 * for packets after the first one (rather than all pts
3222 * values being the same) */
3223 if (i == 0 || track->default_duration)
3224 dp->pts = mkv_d->last_pts + i * track->default_duration;
3225 ds_add_packet (ds, dp);
3228 block += lace_size[i];
3231 if (ds == demuxer->video)
3233 mkv_d->v_skip_to_keyframe = 0;
3234 mkv_d->skip_to_timecode = 0;
3236 else if (ds == demuxer->audio)
3237 mkv_d->a_skip_to_keyframe = 0;
3239 free(lace_size);
3240 return 1;
3243 free(lace_size);
3244 return 0;
3247 static int
3248 demux_mkv_fill_buffer (demuxer_t *demuxer, demux_stream_t *ds)
3250 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
3251 stream_t *s = demuxer->stream;
3252 uint64_t l;
3253 int il, tmp;
3255 while (1)
3257 while (mkv_d->cluster_size > 0)
3259 uint64_t block_duration = 0, block_length = 0;
3260 int64_t block_bref = 0, block_fref = 0;
3261 uint8_t *block = NULL;
3263 while (mkv_d->blockgroup_size > 0)
3265 switch (ebml_read_id (s, &il))
3267 case MATROSKA_ID_BLOCKDURATION:
3269 block_duration = ebml_read_uint (s, &l);
3270 if (block_duration == EBML_UINT_INVALID) {
3271 free(block);
3272 return 0;
3274 block_duration *= mkv_d->tc_scale / 1000000.0;
3275 break;
3278 case MATROSKA_ID_BLOCK:
3279 block_length = ebml_read_length (s, &tmp);
3280 free(block);
3281 if (block_length > SIZE_MAX - LZO_INPUT_PADDING) return 0;
3282 block = malloc (block_length + LZO_INPUT_PADDING);
3283 demuxer->filepos = stream_tell (s);
3284 if (stream_read (s,block,block_length) != (int) block_length)
3286 free(block);
3287 return 0;
3289 l = tmp + block_length;
3290 break;
3292 case MATROSKA_ID_REFERENCEBLOCK:
3294 int64_t num = ebml_read_int (s, &l);
3295 if (num == EBML_INT_INVALID) {
3296 free(block);
3297 return 0;
3299 if (num <= 0)
3300 block_bref = num;
3301 else
3302 block_fref = num;
3303 break;
3306 case EBML_ID_INVALID:
3307 free(block);
3308 return 0;
3310 default:
3311 ebml_read_skip (s, &l);
3312 break;
3314 mkv_d->blockgroup_size -= l + il;
3315 mkv_d->cluster_size -= l + il;
3318 if (block)
3320 int res = handle_block (demuxer, block, block_length,
3321 block_duration, block_bref, block_fref, 0);
3322 free (block);
3323 if (res < 0)
3324 return 0;
3325 if (res)
3326 return 1;
3329 if (mkv_d->cluster_size > 0)
3331 switch (ebml_read_id (s, &il))
3333 case MATROSKA_ID_CLUSTERTIMECODE:
3335 uint64_t num = ebml_read_uint (s, &l);
3336 if (num == EBML_UINT_INVALID)
3337 return 0;
3338 if (!mkv_d->has_first_tc)
3340 mkv_d->first_tc = num * mkv_d->tc_scale / 1000000.0;
3341 mkv_d->has_first_tc = 1;
3343 mkv_d->cluster_tc = num * mkv_d->tc_scale;
3344 break;
3347 case MATROSKA_ID_BLOCKGROUP:
3348 mkv_d->blockgroup_size = ebml_read_length (s, &tmp);
3349 l = tmp;
3350 break;
3352 case MATROSKA_ID_SIMPLEBLOCK:
3354 int res;
3355 block_length = ebml_read_length (s, &tmp);
3356 block = malloc (block_length);
3357 demuxer->filepos = stream_tell (s);
3358 if (stream_read (s,block,block_length) != (int) block_length)
3360 free(block);
3361 return 0;
3363 l = tmp + block_length;
3364 res = handle_block (demuxer, block, block_length,
3365 block_duration, block_bref, block_fref, 1);
3366 free (block);
3367 mkv_d->cluster_size -= l + il;
3368 if (res < 0)
3369 return 0;
3370 else if (res)
3371 return 1;
3372 else mkv_d->cluster_size += l + il;
3373 break;
3375 case EBML_ID_INVALID:
3376 return 0;
3378 default:
3379 ebml_read_skip (s, &l);
3380 break;
3382 mkv_d->cluster_size -= l + il;
3386 if (ebml_read_id (s, &il) != MATROSKA_ID_CLUSTER)
3387 return 0;
3388 add_cluster_position(mkv_d, stream_tell(s)-il);
3389 mkv_d->cluster_size = ebml_read_length (s, NULL);
3392 return 0;
3395 static void
3396 demux_mkv_seek (demuxer_t *demuxer, float rel_seek_secs, float audio_delay, int flags)
3398 free_cached_dps (demuxer);
3399 if (!(flags & 2)) /* time in secs */
3401 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
3402 stream_t *s = demuxer->stream;
3403 int64_t target_timecode = 0, diff, min_diff=0xFFFFFFFFFFFFFFFLL;
3404 int i;
3406 if (!(flags & 1)) /* relative seek */
3407 target_timecode = (int64_t) (mkv_d->last_pts * 1000.0);
3408 target_timecode += (int64_t)(rel_seek_secs * 1000.0);
3409 if (target_timecode < 0)
3410 target_timecode = 0;
3412 if (mkv_d->indexes == NULL) /* no index was found */
3414 uint64_t target_filepos, cluster_pos, max_pos;
3416 target_filepos = (uint64_t) (target_timecode * mkv_d->last_filepos
3417 / (mkv_d->last_pts * 1000.0));
3419 max_pos = mkv_d->cluster_positions[mkv_d->num_cluster_pos-1];
3420 if (target_filepos > max_pos)
3422 if ((off_t) max_pos > stream_tell (s))
3423 stream_seek (s, max_pos);
3424 else
3425 stream_seek (s, stream_tell (s) + mkv_d->cluster_size);
3426 /* parse all the clusters upto target_filepos */
3427 while (!s->eof && stream_tell(s) < (off_t) target_filepos)
3429 switch (ebml_read_id (s, &i))
3431 case MATROSKA_ID_CLUSTER:
3432 add_cluster_position(mkv_d, (uint64_t) stream_tell(s)-i);
3433 break;
3435 case MATROSKA_ID_CUES:
3436 demux_mkv_read_cues (demuxer);
3437 break;
3439 ebml_read_skip (s, NULL);
3441 if (s->eof)
3442 stream_reset(s);
3445 if (mkv_d->indexes == NULL)
3447 cluster_pos = mkv_d->cluster_positions[0];
3448 /* Let's find the nearest cluster */
3449 for (i=0; i < mkv_d->num_cluster_pos; i++)
3451 diff = mkv_d->cluster_positions[i] - target_filepos;
3452 if (rel_seek_secs < 0 && diff < 0 && -diff < min_diff)
3454 cluster_pos = mkv_d->cluster_positions[i];
3455 min_diff = -diff;
3457 else if (rel_seek_secs > 0
3458 && (diff < 0 ? -1 * diff : diff) < min_diff)
3460 cluster_pos = mkv_d->cluster_positions[i];
3461 min_diff = diff < 0 ? -1 * diff : diff;
3464 mkv_d->cluster_size = mkv_d->blockgroup_size = 0;
3465 stream_seek (s, cluster_pos);
3468 else
3470 mkv_index_t *index = NULL;
3471 int seek_id = (demuxer->video->id < 0) ? demuxer->audio->id : demuxer->video->id;
3473 /* let's find the entry in the indexes with the smallest */
3474 /* difference to the wanted timecode. */
3475 for (i=0; i < mkv_d->num_indexes; i++)
3476 if (mkv_d->indexes[i].tnum == seek_id)
3478 diff = target_timecode + mkv_d->first_tc -
3479 (int64_t) mkv_d->indexes[i].timecode * mkv_d->tc_scale / 1000000.0;
3481 if ((flags & 1 || target_timecode <= mkv_d->last_pts*1000)) {
3482 // Absolute seek or seek backward: find the last index
3483 // position before target time
3484 if (diff < 0 || diff >= min_diff)
3485 continue;
3487 else {
3488 // Relative seek forward: find the first index position
3489 // after target time. If no such index exists, find last
3490 // position between current position and target time.
3491 if (diff <= 0) {
3492 if (min_diff <= 0 && diff <= min_diff)
3493 continue;
3495 else if (diff >= FFMIN(target_timecode - mkv_d->last_pts,
3496 min_diff))
3497 continue;
3499 min_diff = diff;
3500 index = mkv_d->indexes + i;
3503 if (index) /* We've found an entry. */
3505 mkv_d->cluster_size = mkv_d->blockgroup_size = 0;
3506 stream_seek (s, index->filepos);
3510 if (demuxer->video->id >= 0)
3511 mkv_d->v_skip_to_keyframe = 1;
3512 if (rel_seek_secs > 0.0)
3513 mkv_d->skip_to_timecode = target_timecode;
3514 mkv_d->a_skip_to_keyframe = 1;
3516 demux_mkv_fill_buffer(demuxer, NULL);
3518 else if ((demuxer->movi_end <= 0) || !(flags & 1))
3519 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] seek unsupported flags\n");
3520 else
3522 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
3523 stream_t *s = demuxer->stream;
3524 uint64_t target_filepos;
3525 mkv_index_t *index = NULL;
3526 int i;
3528 if (mkv_d->indexes == NULL) /* no index was found */
3529 { /* I'm lazy... */
3530 mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] seek unsupported flags\n");
3531 return;
3534 target_filepos = (uint64_t)(demuxer->movi_end * rel_seek_secs);
3535 for (i=0; i < mkv_d->num_indexes; i++)
3536 if (mkv_d->indexes[i].tnum == demuxer->video->id)
3537 if ((index == NULL) ||
3538 ((mkv_d->indexes[i].filepos >= target_filepos) &&
3539 ((index->filepos < target_filepos) ||
3540 (mkv_d->indexes[i].filepos < index->filepos))))
3541 index = &mkv_d->indexes[i];
3543 if (!index)
3544 return;
3546 mkv_d->cluster_size = mkv_d->blockgroup_size = 0;
3547 stream_seek (s, index->filepos);
3549 if (demuxer->video->id >= 0)
3550 mkv_d->v_skip_to_keyframe = 1;
3551 mkv_d->skip_to_timecode = index->timecode;
3552 mkv_d->a_skip_to_keyframe = 1;
3554 demux_mkv_fill_buffer(demuxer, NULL);
3558 static int
3559 demux_mkv_control (demuxer_t *demuxer, int cmd, void *arg)
3561 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
3563 switch (cmd)
3565 case DEMUXER_CTRL_GET_TIME_LENGTH:
3566 if (mkv_d->duration == 0)
3567 return DEMUXER_CTRL_DONTKNOW;
3569 *((double *)arg) = (double)mkv_d->duration;
3570 return DEMUXER_CTRL_OK;
3572 case DEMUXER_CTRL_GET_PERCENT_POS:
3573 if (mkv_d->duration == 0)
3575 return DEMUXER_CTRL_DONTKNOW;
3578 *((int *) arg) = (int) (100 * mkv_d->last_pts / mkv_d->duration);
3579 return DEMUXER_CTRL_OK;
3581 case DEMUXER_CTRL_SWITCH_AUDIO:
3582 if (demuxer->audio && demuxer->audio->sh) {
3583 sh_audio_t *sh = demuxer->a_streams[demuxer->audio->id];
3584 int aid = *(int*)arg;
3585 if (aid < 0)
3586 aid = (sh->aid + 1) % mkv_d->last_aid;
3587 if (aid != sh->aid) {
3588 mkv_track_t *track = demux_mkv_find_track_by_num (mkv_d, aid, MATROSKA_TRACK_AUDIO);
3589 if (track) {
3590 demuxer->audio->id = track->tnum;
3591 sh = demuxer->a_streams[demuxer->audio->id];
3592 ds_free_packs(demuxer->audio);
3595 *(int*)arg = sh->aid;
3596 } else
3597 *(int*)arg = -2;
3598 return DEMUXER_CTRL_OK;
3600 default:
3601 return DEMUXER_CTRL_NOTIMPL;
3605 /** \brief Get the language code for a subtitle track.
3607 Retrieves the language code for a subtitle track if it is known.
3608 If the language code is "und" then do not copy it ("und" = "undefined").
3610 \param demuxer The demuxer to work on
3611 \param track_num The subtitle track number to get the language from
3612 \param lang Store the language here
3613 \param maxlen The maximum number of characters to copy into lang
3615 void
3616 demux_mkv_get_sub_lang(demuxer_t *demuxer, int track_num, char *lang,
3617 int maxlen)
3619 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
3620 mkv_track_t *track = demux_mkv_find_track_by_num (mkv_d, track_num, MATROSKA_TRACK_SUBTITLE);
3621 if (track && track->language && strcmp(track->language, "und"))
3622 av_strlcpy(lang, track->language, maxlen);
3625 /** \brief Get the language code for an audio track.
3627 Retrieves the language code for an audio track if it is known.
3628 If the language code is "und" then do not copy it ("und" = "undefined").
3630 \param demuxer The demuxer to work on
3631 \param track_num The n'th audio track to get the language from
3632 \param lang Store the language here
3633 \param maxlen The maximum number of characters to copy into lang
3635 void
3636 demux_mkv_get_audio_lang(demuxer_t *demuxer, int track_num, char *lang,
3637 int maxlen)
3639 mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
3640 mkv_track_t *track = demux_mkv_find_track_by_num (mkv_d, track_num, MATROSKA_TRACK_AUDIO);
3641 if (track && track->language && strcmp(track->language, "und"))
3642 av_strlcpy(lang, track->language, maxlen);
3646 demuxer_desc_t demuxer_desc_matroska = {
3647 "Matroska demuxer",
3648 "mkv",
3649 "Matroska",
3650 "Aurelien Jacobs",
3652 DEMUXER_TYPE_MATROSKA,
3653 1, // safe autodetect
3654 demux_mkv_open,
3655 demux_mkv_fill_buffer,
3656 NULL,
3657 demux_close_mkv,
3658 demux_mkv_seek,
3659 demux_mkv_control