2 * Matroska file demuxer
3 * Copyright (c) 2003-2008 The FFmpeg Project
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 * Matroska file demuxer
25 * by Ronald Bultje <rbultje@ronald.bitfreak.net>
26 * with a little help from Moritz Bunkus <moritz@bunkus.org>
27 * totally reworked by Aurelien Jacobs <aurel@gnuage.org>
28 * Specs available on the Matroska project page: http://www.matroska.org/.
34 /* For ff_codec_get_id(). */
39 #include "libavcodec/mpeg4audio.h"
40 #include "libavutil/intfloat_readwrite.h"
41 #include "libavutil/intreadwrite.h"
42 #include "libavutil/avstring.h"
43 #include "libavutil/lzo.h"
63 typedef const struct EbmlSyntax {
72 const struct EbmlSyntax *n;
92 uint64_t doctype_version;
98 } MatroskaTrackCompression;
103 MatroskaTrackCompression compression;
104 } MatroskaTrackEncoding;
108 uint64_t display_width;
109 uint64_t display_height;
110 uint64_t pixel_width;
111 uint64_t pixel_height;
113 } MatroskaTrackVideo;
117 double out_samplerate;
121 /* real audio header (extracted from extradata) */
129 } MatroskaTrackAudio;
140 uint64_t default_duration;
141 uint64_t flag_default;
142 uint64_t flag_forced;
143 MatroskaTrackVideo video;
144 MatroskaTrackAudio audio;
148 int64_t end_timecode;
159 } MatroskaAttachement;
197 MatroskaTagTarget target;
212 AVFormatContext *ctx;
216 MatroskaLevel levels[EBML_MAX_DEPTH];
224 EbmlList attachments;
230 /* byte position of the segment inside the stream */
231 int64_t segment_start;
233 /* the packet queue */
240 /* What to skip before effectively reading a packet. */
241 int skip_to_keyframe;
242 uint64_t skip_to_timecode;
243 } MatroskaDemuxContext;
257 static EbmlSyntax ebml_header[] = {
258 { EBML_ID_EBMLREADVERSION, EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
259 { EBML_ID_EBMLMAXSIZELENGTH, EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
260 { EBML_ID_EBMLMAXIDLENGTH, EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
261 { EBML_ID_DOCTYPE, EBML_STR, 0, offsetof(Ebml,doctype), {.s="(none)"} },
262 { EBML_ID_DOCTYPEREADVERSION, EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
263 { EBML_ID_EBMLVERSION, EBML_NONE },
264 { EBML_ID_DOCTYPEVERSION, EBML_NONE },
268 static EbmlSyntax ebml_syntax[] = {
269 { EBML_ID_HEADER, EBML_NEST, 0, 0, {.n=ebml_header} },
273 static EbmlSyntax matroska_info[] = {
274 { MATROSKA_ID_TIMECODESCALE, EBML_UINT, 0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
275 { MATROSKA_ID_DURATION, EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
276 { MATROSKA_ID_TITLE, EBML_UTF8, 0, offsetof(MatroskaDemuxContext,title) },
277 { MATROSKA_ID_WRITINGAPP, EBML_NONE },
278 { MATROSKA_ID_MUXINGAPP, EBML_NONE },
279 { MATROSKA_ID_DATEUTC, EBML_NONE },
280 { MATROSKA_ID_SEGMENTUID, EBML_NONE },
284 static EbmlSyntax matroska_track_video[] = {
285 { MATROSKA_ID_VIDEOFRAMERATE, EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
286 { MATROSKA_ID_VIDEODISPLAYWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
287 { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
288 { MATROSKA_ID_VIDEOPIXELWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
289 { MATROSKA_ID_VIDEOPIXELHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
290 { MATROSKA_ID_VIDEOCOLORSPACE, EBML_UINT, 0, offsetof(MatroskaTrackVideo,fourcc) },
291 { MATROSKA_ID_VIDEOPIXELCROPB, EBML_NONE },
292 { MATROSKA_ID_VIDEOPIXELCROPT, EBML_NONE },
293 { MATROSKA_ID_VIDEOPIXELCROPL, EBML_NONE },
294 { MATROSKA_ID_VIDEOPIXELCROPR, EBML_NONE },
295 { MATROSKA_ID_VIDEODISPLAYUNIT, EBML_NONE },
296 { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
297 { MATROSKA_ID_VIDEOSTEREOMODE, EBML_NONE },
298 { MATROSKA_ID_VIDEOASPECTRATIO, EBML_NONE },
302 static EbmlSyntax matroska_track_audio[] = {
303 { MATROSKA_ID_AUDIOSAMPLINGFREQ, EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
304 { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
305 { MATROSKA_ID_AUDIOBITDEPTH, EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
306 { MATROSKA_ID_AUDIOCHANNELS, EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
310 static EbmlSyntax matroska_track_encoding_compression[] = {
311 { MATROSKA_ID_ENCODINGCOMPALGO, EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
312 { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
316 static EbmlSyntax matroska_track_encoding[] = {
317 { MATROSKA_ID_ENCODINGSCOPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
318 { MATROSKA_ID_ENCODINGTYPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
319 { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
320 { MATROSKA_ID_ENCODINGORDER, EBML_NONE },
324 static EbmlSyntax matroska_track_encodings[] = {
325 { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
329 static EbmlSyntax matroska_track[] = {
330 { MATROSKA_ID_TRACKNUMBER, EBML_UINT, 0, offsetof(MatroskaTrack,num) },
331 { MATROSKA_ID_TRACKNAME, EBML_UTF8, 0, offsetof(MatroskaTrack,name) },
332 { MATROSKA_ID_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTrack,uid) },
333 { MATROSKA_ID_TRACKTYPE, EBML_UINT, 0, offsetof(MatroskaTrack,type) },
334 { MATROSKA_ID_CODECID, EBML_STR, 0, offsetof(MatroskaTrack,codec_id) },
335 { MATROSKA_ID_CODECPRIVATE, EBML_BIN, 0, offsetof(MatroskaTrack,codec_priv) },
336 { MATROSKA_ID_TRACKLANGUAGE, EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
337 { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
338 { MATROSKA_ID_TRACKTIMECODESCALE, EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
339 { MATROSKA_ID_TRACKFLAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
340 { MATROSKA_ID_TRACKFLAGFORCED, EBML_UINT, 0, offsetof(MatroskaTrack,flag_forced), {.u=0} },
341 { MATROSKA_ID_TRACKVIDEO, EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
342 { MATROSKA_ID_TRACKAUDIO, EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
343 { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
344 { MATROSKA_ID_TRACKFLAGENABLED, EBML_NONE },
345 { MATROSKA_ID_TRACKFLAGLACING, EBML_NONE },
346 { MATROSKA_ID_CODECNAME, EBML_NONE },
347 { MATROSKA_ID_CODECDECODEALL, EBML_NONE },
348 { MATROSKA_ID_CODECINFOURL, EBML_NONE },
349 { MATROSKA_ID_CODECDOWNLOADURL, EBML_NONE },
350 { MATROSKA_ID_TRACKMINCACHE, EBML_NONE },
351 { MATROSKA_ID_TRACKMAXCACHE, EBML_NONE },
352 { MATROSKA_ID_TRACKMAXBLKADDID, EBML_NONE },
356 static EbmlSyntax matroska_tracks[] = {
357 { MATROSKA_ID_TRACKENTRY, EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
361 static EbmlSyntax matroska_attachment[] = {
362 { MATROSKA_ID_FILEUID, EBML_UINT, 0, offsetof(MatroskaAttachement,uid) },
363 { MATROSKA_ID_FILENAME, EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
364 { MATROSKA_ID_FILEMIMETYPE, EBML_STR, 0, offsetof(MatroskaAttachement,mime) },
365 { MATROSKA_ID_FILEDATA, EBML_BIN, 0, offsetof(MatroskaAttachement,bin) },
366 { MATROSKA_ID_FILEDESC, EBML_NONE },
370 static EbmlSyntax matroska_attachments[] = {
371 { MATROSKA_ID_ATTACHEDFILE, EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
375 static EbmlSyntax matroska_chapter_display[] = {
376 { MATROSKA_ID_CHAPSTRING, EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
377 { MATROSKA_ID_CHAPLANG, EBML_NONE },
381 static EbmlSyntax matroska_chapter_entry[] = {
382 { MATROSKA_ID_CHAPTERTIMESTART, EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
383 { MATROSKA_ID_CHAPTERTIMEEND, EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
384 { MATROSKA_ID_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
385 { MATROSKA_ID_CHAPTERDISPLAY, EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
386 { MATROSKA_ID_CHAPTERFLAGHIDDEN, EBML_NONE },
387 { MATROSKA_ID_CHAPTERFLAGENABLED, EBML_NONE },
388 { MATROSKA_ID_CHAPTERPHYSEQUIV, EBML_NONE },
389 { MATROSKA_ID_CHAPTERATOM, EBML_NONE },
393 static EbmlSyntax matroska_chapter[] = {
394 { MATROSKA_ID_CHAPTERATOM, EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
395 { MATROSKA_ID_EDITIONUID, EBML_NONE },
396 { MATROSKA_ID_EDITIONFLAGHIDDEN, EBML_NONE },
397 { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
398 { MATROSKA_ID_EDITIONFLAGORDERED, EBML_NONE },
402 static EbmlSyntax matroska_chapters[] = {
403 { MATROSKA_ID_EDITIONENTRY, EBML_NEST, 0, 0, {.n=matroska_chapter} },
407 static EbmlSyntax matroska_index_pos[] = {
408 { MATROSKA_ID_CUETRACK, EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
409 { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos) },
410 { MATROSKA_ID_CUEBLOCKNUMBER, EBML_NONE },
414 static EbmlSyntax matroska_index_entry[] = {
415 { MATROSKA_ID_CUETIME, EBML_UINT, 0, offsetof(MatroskaIndex,time) },
416 { MATROSKA_ID_CUETRACKPOSITION, EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
420 static EbmlSyntax matroska_index[] = {
421 { MATROSKA_ID_POINTENTRY, EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
425 static EbmlSyntax matroska_simpletag[] = {
426 { MATROSKA_ID_TAGNAME, EBML_UTF8, 0, offsetof(MatroskaTag,name) },
427 { MATROSKA_ID_TAGSTRING, EBML_UTF8, 0, offsetof(MatroskaTag,string) },
428 { MATROSKA_ID_TAGLANG, EBML_STR, 0, offsetof(MatroskaTag,lang), {.s="und"} },
429 { MATROSKA_ID_TAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTag,def) },
430 { MATROSKA_ID_TAGDEFAULT_BUG, EBML_UINT, 0, offsetof(MatroskaTag,def) },
431 { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag,sub), {.n=matroska_simpletag} },
435 static EbmlSyntax matroska_tagtargets[] = {
436 { MATROSKA_ID_TAGTARGETS_TYPE, EBML_STR, 0, offsetof(MatroskaTagTarget,type) },
437 { MATROSKA_ID_TAGTARGETS_TYPEVALUE, EBML_UINT, 0, offsetof(MatroskaTagTarget,typevalue), {.u=50} },
438 { MATROSKA_ID_TAGTARGETS_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,trackuid) },
439 { MATROSKA_ID_TAGTARGETS_CHAPTERUID,EBML_UINT, 0, offsetof(MatroskaTagTarget,chapteruid) },
440 { MATROSKA_ID_TAGTARGETS_ATTACHUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,attachuid) },
444 static EbmlSyntax matroska_tag[] = {
445 { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTags,tag), {.n=matroska_simpletag} },
446 { MATROSKA_ID_TAGTARGETS, EBML_NEST, 0, offsetof(MatroskaTags,target), {.n=matroska_tagtargets} },
450 static EbmlSyntax matroska_tags[] = {
451 { MATROSKA_ID_TAG, EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext,tags), {.n=matroska_tag} },
455 static EbmlSyntax matroska_seekhead_entry[] = {
456 { MATROSKA_ID_SEEKID, EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
457 { MATROSKA_ID_SEEKPOSITION, EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
461 static EbmlSyntax matroska_seekhead[] = {
462 { MATROSKA_ID_SEEKENTRY, EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
466 static EbmlSyntax matroska_segment[] = {
467 { MATROSKA_ID_INFO, EBML_NEST, 0, 0, {.n=matroska_info } },
468 { MATROSKA_ID_TRACKS, EBML_NEST, 0, 0, {.n=matroska_tracks } },
469 { MATROSKA_ID_ATTACHMENTS, EBML_NEST, 0, 0, {.n=matroska_attachments} },
470 { MATROSKA_ID_CHAPTERS, EBML_NEST, 0, 0, {.n=matroska_chapters } },
471 { MATROSKA_ID_CUES, EBML_NEST, 0, 0, {.n=matroska_index } },
472 { MATROSKA_ID_TAGS, EBML_NEST, 0, 0, {.n=matroska_tags } },
473 { MATROSKA_ID_SEEKHEAD, EBML_NEST, 0, 0, {.n=matroska_seekhead } },
474 { MATROSKA_ID_CLUSTER, EBML_STOP },
478 static EbmlSyntax matroska_segments[] = {
479 { MATROSKA_ID_SEGMENT, EBML_NEST, 0, 0, {.n=matroska_segment } },
483 static EbmlSyntax matroska_blockgroup[] = {
484 { MATROSKA_ID_BLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
485 { MATROSKA_ID_SIMPLEBLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
486 { MATROSKA_ID_BLOCKDURATION, EBML_UINT, 0, offsetof(MatroskaBlock,duration), {.u=AV_NOPTS_VALUE} },
487 { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
488 { 1, EBML_UINT, 0, offsetof(MatroskaBlock,non_simple), {.u=1} },
492 static EbmlSyntax matroska_cluster[] = {
493 { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
494 { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
495 { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
496 { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
497 { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
501 static EbmlSyntax matroska_clusters[] = {
502 { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, {.n=matroska_cluster} },
503 { MATROSKA_ID_INFO, EBML_NONE },
504 { MATROSKA_ID_CUES, EBML_NONE },
505 { MATROSKA_ID_TAGS, EBML_NONE },
506 { MATROSKA_ID_SEEKHEAD, EBML_NONE },
510 static const char *matroska_doctypes[] = { "matroska", "webm" };
513 * Return: Whether we reached the end of a level in the hierarchy or not.
515 static int ebml_level_end(MatroskaDemuxContext *matroska)
517 ByteIOContext *pb = matroska->ctx->pb;
518 int64_t pos = url_ftell(pb);
520 if (matroska->num_levels > 0) {
521 MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
522 if (pos - level->start >= level->length || matroska->current_id) {
523 matroska->num_levels--;
531 * Read: an "EBML number", which is defined as a variable-length
532 * array of bytes. The first byte indicates the length by giving a
533 * number of 0-bits followed by a one. The position of the first
534 * "one" bit inside the first byte indicates the length of this
536 * Returns: number of bytes read, < 0 on error
538 static int ebml_read_num(MatroskaDemuxContext *matroska, ByteIOContext *pb,
539 int max_size, uint64_t *number)
544 /* The first byte tells us the length in bytes - get_byte() can normally
545 * return 0, but since that's not a valid first ebmlID byte, we can
546 * use it safely here to catch EOS. */
547 if (!(total = get_byte(pb))) {
548 /* we might encounter EOS here */
550 int64_t pos = url_ftell(pb);
551 av_log(matroska->ctx, AV_LOG_ERROR,
552 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
555 return AVERROR(EIO); /* EOS or actual I/O error */
558 /* get the length of the EBML number */
559 read = 8 - ff_log2_tab[total];
560 if (read > max_size) {
561 int64_t pos = url_ftell(pb) - 1;
562 av_log(matroska->ctx, AV_LOG_ERROR,
563 "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
564 (uint8_t) total, pos, pos);
565 return AVERROR_INVALIDDATA;
568 /* read out length */
569 total ^= 1 << ff_log2_tab[total];
571 total = (total << 8) | get_byte(pb);
579 * Read a EBML length value.
580 * This needs special handling for the "unknown length" case which has multiple
583 static int ebml_read_length(MatroskaDemuxContext *matroska, ByteIOContext *pb,
586 int res = ebml_read_num(matroska, pb, 8, number);
587 if (res > 0 && *number + 1 == 1ULL << (7 * res))
588 *number = 0xffffffffffffffULL;
593 * Read the next element as an unsigned int.
594 * 0 is success, < 0 is failure.
596 static int ebml_read_uint(ByteIOContext *pb, int size, uint64_t *num)
601 return AVERROR_INVALIDDATA;
603 /* big-endian ordering; build up number */
606 *num = (*num << 8) | get_byte(pb);
612 * Read the next element as a float.
613 * 0 is success, < 0 is failure.
615 static int ebml_read_float(ByteIOContext *pb, int size, double *num)
619 } else if (size == 4) {
620 *num= av_int2flt(get_be32(pb));
622 *num= av_int2dbl(get_be64(pb));
624 return AVERROR_INVALIDDATA;
630 * Read the next element as an ASCII string.
631 * 0 is success, < 0 is failure.
633 static int ebml_read_ascii(ByteIOContext *pb, int size, char **str)
636 /* EBML strings are usually not 0-terminated, so we allocate one
637 * byte more, read the string and NULL-terminate it ourselves. */
638 if (!(*str = av_malloc(size + 1)))
639 return AVERROR(ENOMEM);
640 if (get_buffer(pb, (uint8_t *) *str, size) != size) {
650 * Read the next element as binary data.
651 * 0 is success, < 0 is failure.
653 static int ebml_read_binary(ByteIOContext *pb, int length, EbmlBin *bin)
656 if (!(bin->data = av_malloc(length)))
657 return AVERROR(ENOMEM);
660 bin->pos = url_ftell(pb);
661 if (get_buffer(pb, bin->data, length) != length) {
662 av_freep(&bin->data);
670 * Read the next element, but only the header. The contents
671 * are supposed to be sub-elements which can be read separately.
672 * 0 is success, < 0 is failure.
674 static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
676 ByteIOContext *pb = matroska->ctx->pb;
677 MatroskaLevel *level;
679 if (matroska->num_levels >= EBML_MAX_DEPTH) {
680 av_log(matroska->ctx, AV_LOG_ERROR,
681 "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
682 return AVERROR(ENOSYS);
685 level = &matroska->levels[matroska->num_levels++];
686 level->start = url_ftell(pb);
687 level->length = length;
693 * Read signed/unsigned "EBML" numbers.
694 * Return: number of bytes processed, < 0 on error
696 static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
697 uint8_t *data, uint32_t size, uint64_t *num)
700 init_put_byte(&pb, data, size, 0, NULL, NULL, NULL, NULL);
701 return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
705 * Same as above, but signed.
707 static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
708 uint8_t *data, uint32_t size, int64_t *num)
713 /* read as unsigned number first */
714 if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
717 /* make signed (weird way) */
718 *num = unum - ((1LL << (7*res - 1)) - 1);
723 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
724 EbmlSyntax *syntax, void *data);
726 static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
727 uint32_t id, void *data)
730 for (i=0; syntax[i].id; i++)
731 if (id == syntax[i].id)
733 if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
734 matroska->num_levels > 0 &&
735 matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
736 return 0; // we reached the end of an unknown size cluster
737 if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32)
738 av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
739 return ebml_parse_elem(matroska, &syntax[i], data);
742 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
745 if (!matroska->current_id) {
747 int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
750 matroska->current_id = id | 1 << 7*res;
752 return ebml_parse_id(matroska, syntax, matroska->current_id, data);
755 static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
760 for (i=0; syntax[i].id; i++)
761 switch (syntax[i].type) {
763 *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
766 *(double *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
770 *(char **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
774 while (!res && !ebml_level_end(matroska))
775 res = ebml_parse(matroska, syntax, data);
780 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
781 EbmlSyntax *syntax, void *data)
783 ByteIOContext *pb = matroska->ctx->pb;
784 uint32_t id = syntax->id;
788 data = (char *)data + syntax->data_offset;
789 if (syntax->list_elem_size) {
790 EbmlList *list = data;
791 list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
792 data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
793 memset(data, 0, syntax->list_elem_size);
797 if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
798 matroska->current_id = 0;
799 if ((res = ebml_read_length(matroska, pb, &length)) < 0)
803 switch (syntax->type) {
804 case EBML_UINT: res = ebml_read_uint (pb, length, data); break;
805 case EBML_FLOAT: res = ebml_read_float (pb, length, data); break;
807 case EBML_UTF8: res = ebml_read_ascii (pb, length, data); break;
808 case EBML_BIN: res = ebml_read_binary(pb, length, data); break;
809 case EBML_NEST: if ((res=ebml_read_master(matroska, length)) < 0)
811 if (id == MATROSKA_ID_SEGMENT)
812 matroska->segment_start = url_ftell(matroska->ctx->pb);
813 return ebml_parse_nest(matroska, syntax->def.n, data);
814 case EBML_PASS: return ebml_parse_id(matroska, syntax->def.n, id, data);
815 case EBML_STOP: return 1;
816 default: return url_fseek(pb,length,SEEK_CUR)<0 ? AVERROR(EIO) : 0;
818 if (res == AVERROR_INVALIDDATA)
819 av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
820 else if (res == AVERROR(EIO))
821 av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
825 static void ebml_free(EbmlSyntax *syntax, void *data)
828 for (i=0; syntax[i].id; i++) {
829 void *data_off = (char *)data + syntax[i].data_offset;
830 switch (syntax[i].type) {
832 case EBML_UTF8: av_freep(data_off); break;
833 case EBML_BIN: av_freep(&((EbmlBin *)data_off)->data); break;
835 if (syntax[i].list_elem_size) {
836 EbmlList *list = data_off;
837 char *ptr = list->elem;
838 for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
839 ebml_free(syntax[i].def.n, ptr);
842 ebml_free(syntax[i].def.n, data_off);
852 static int matroska_probe(AVProbeData *p)
855 int len_mask = 0x80, size = 1, n = 1, i;
858 if (AV_RB32(p->buf) != EBML_ID_HEADER)
861 /* length of header */
863 while (size <= 8 && !(total & len_mask)) {
869 total &= (len_mask - 1);
871 total = (total << 8) | p->buf[4 + n++];
873 /* Does the probe data contain the whole header? */
874 if (p->buf_size < 4 + size + total)
877 /* The header should contain a known document type. For now,
878 * we don't parse the whole header but simply check for the
879 * availability of that array of characters inside the header.
880 * Not fully fool-proof, but good enough. */
881 for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
882 int probelen = strlen(matroska_doctypes[i]);
883 for (n = 4+size; n <= 4+size+total-probelen; n++)
884 if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
885 return AVPROBE_SCORE_MAX;
888 // probably valid EBML header but no recognized doctype
889 return AVPROBE_SCORE_MAX/2;
892 static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
895 MatroskaTrack *tracks = matroska->tracks.elem;
898 for (i=0; i < matroska->tracks.nb_elem; i++)
899 if (tracks[i].num == num)
902 av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
906 static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
907 MatroskaTrack *track)
909 MatroskaTrackEncoding *encodings = track->encodings.elem;
910 uint8_t* data = *buf;
911 int isize = *buf_size;
912 uint8_t* pkt_data = NULL;
913 int pkt_size = isize;
917 if (pkt_size >= 10000000)
920 switch (encodings[0].compression.algo) {
921 case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
922 return encodings[0].compression.settings.size;
923 case MATROSKA_TRACK_ENCODING_COMP_LZO:
925 olen = pkt_size *= 3;
926 pkt_data = av_realloc(pkt_data, pkt_size+AV_LZO_OUTPUT_PADDING);
927 result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
928 } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
934 case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
935 z_stream zstream = {0};
936 if (inflateInit(&zstream) != Z_OK)
938 zstream.next_in = data;
939 zstream.avail_in = isize;
942 pkt_data = av_realloc(pkt_data, pkt_size);
943 zstream.avail_out = pkt_size - zstream.total_out;
944 zstream.next_out = pkt_data + zstream.total_out;
945 result = inflate(&zstream, Z_NO_FLUSH);
946 } while (result==Z_OK && pkt_size<10000000);
947 pkt_size = zstream.total_out;
948 inflateEnd(&zstream);
949 if (result != Z_STREAM_END)
955 case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
956 bz_stream bzstream = {0};
957 if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
959 bzstream.next_in = data;
960 bzstream.avail_in = isize;
963 pkt_data = av_realloc(pkt_data, pkt_size);
964 bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
965 bzstream.next_out = pkt_data + bzstream.total_out_lo32;
966 result = BZ2_bzDecompress(&bzstream);
967 } while (result==BZ_OK && pkt_size<10000000);
968 pkt_size = bzstream.total_out_lo32;
969 BZ2_bzDecompressEnd(&bzstream);
970 if (result != BZ_STREAM_END)
980 *buf_size = pkt_size;
987 static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
988 AVPacket *pkt, uint64_t display_duration)
990 char *line, *layer, *ptr = pkt->data, *end = ptr+pkt->size;
991 for (; *ptr!=',' && ptr<end-1; ptr++);
994 for (; *ptr!=',' && ptr<end-1; ptr++);
996 int64_t end_pts = pkt->pts + display_duration;
997 int sc = matroska->time_scale * pkt->pts / 10000000;
998 int ec = matroska->time_scale * end_pts / 10000000;
999 int sh, sm, ss, eh, em, es, len;
1000 sh = sc/360000; sc -= 360000*sh;
1001 sm = sc/ 6000; sc -= 6000*sm;
1002 ss = sc/ 100; sc -= 100*ss;
1003 eh = ec/360000; ec -= 360000*eh;
1004 em = ec/ 6000; ec -= 6000*em;
1005 es = ec/ 100; ec -= 100*es;
1007 len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
1008 if (!(line = av_malloc(len)))
1010 snprintf(line,len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
1011 layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
1014 pkt->size = strlen(line);
1018 static void matroska_merge_packets(AVPacket *out, AVPacket *in)
1020 out->data = av_realloc(out->data, out->size+in->size);
1021 memcpy(out->data+out->size, in->data, in->size);
1022 out->size += in->size;
1023 av_destruct_packet(in);
1027 static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
1028 AVMetadata **metadata, char *prefix)
1030 MatroskaTag *tags = list->elem;
1034 for (i=0; i < list->nb_elem; i++) {
1035 const char *lang = strcmp(tags[i].lang, "und") ? tags[i].lang : NULL;
1037 if (!tags[i].name) {
1038 av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
1041 if (prefix) snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
1042 else av_strlcpy(key, tags[i].name, sizeof(key));
1043 if (tags[i].def || !lang) {
1044 av_metadata_set2(metadata, key, tags[i].string, 0);
1045 if (tags[i].sub.nb_elem)
1046 matroska_convert_tag(s, &tags[i].sub, metadata, key);
1049 av_strlcat(key, "-", sizeof(key));
1050 av_strlcat(key, lang, sizeof(key));
1051 av_metadata_set2(metadata, key, tags[i].string, 0);
1052 if (tags[i].sub.nb_elem)
1053 matroska_convert_tag(s, &tags[i].sub, metadata, key);
1056 ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
1059 static void matroska_convert_tags(AVFormatContext *s)
1061 MatroskaDemuxContext *matroska = s->priv_data;
1062 MatroskaTags *tags = matroska->tags.elem;
1065 for (i=0; i < matroska->tags.nb_elem; i++) {
1066 if (tags[i].target.attachuid) {
1067 MatroskaAttachement *attachment = matroska->attachments.elem;
1068 for (j=0; j<matroska->attachments.nb_elem; j++)
1069 if (attachment[j].uid == tags[i].target.attachuid)
1070 matroska_convert_tag(s, &tags[i].tag,
1071 &attachment[j].stream->metadata, NULL);
1072 } else if (tags[i].target.chapteruid) {
1073 MatroskaChapter *chapter = matroska->chapters.elem;
1074 for (j=0; j<matroska->chapters.nb_elem; j++)
1075 if (chapter[j].uid == tags[i].target.chapteruid)
1076 matroska_convert_tag(s, &tags[i].tag,
1077 &chapter[j].chapter->metadata, NULL);
1078 } else if (tags[i].target.trackuid) {
1079 MatroskaTrack *track = matroska->tracks.elem;
1080 for (j=0; j<matroska->tracks.nb_elem; j++)
1081 if (track[j].uid == tags[i].target.trackuid)
1082 matroska_convert_tag(s, &tags[i].tag,
1083 &track[j].stream->metadata, NULL);
1085 matroska_convert_tag(s, &tags[i].tag, &s->metadata,
1086 tags[i].target.type);
1091 static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1093 EbmlList *seekhead_list = &matroska->seekhead;
1094 MatroskaSeekhead *seekhead = seekhead_list->elem;
1095 uint32_t level_up = matroska->level_up;
1096 int64_t before_pos = url_ftell(matroska->ctx->pb);
1097 uint32_t saved_id = matroska->current_id;
1098 MatroskaLevel level;
1101 // we should not do any seeking in the streaming case
1102 if (url_is_streamed(matroska->ctx->pb) ||
1103 (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
1106 for (i=0; i<seekhead_list->nb_elem; i++) {
1107 int64_t offset = seekhead[i].pos + matroska->segment_start;
1109 if (seekhead[i].pos <= before_pos
1110 || seekhead[i].id == MATROSKA_ID_SEEKHEAD
1111 || seekhead[i].id == MATROSKA_ID_CLUSTER)
1115 if (url_fseek(matroska->ctx->pb, offset, SEEK_SET) != offset)
1118 /* We don't want to lose our seekhead level, so we add
1119 * a dummy. This is a crude hack. */
1120 if (matroska->num_levels == EBML_MAX_DEPTH) {
1121 av_log(matroska->ctx, AV_LOG_INFO,
1122 "Max EBML element depth (%d) reached, "
1123 "cannot parse further.\n", EBML_MAX_DEPTH);
1128 level.length = (uint64_t)-1;
1129 matroska->levels[matroska->num_levels] = level;
1130 matroska->num_levels++;
1131 matroska->current_id = 0;
1133 ebml_parse(matroska, matroska_segment, matroska);
1135 /* remove dummy level */
1136 while (matroska->num_levels) {
1137 uint64_t length = matroska->levels[--matroska->num_levels].length;
1138 if (length == (uint64_t)-1)
1144 url_fseek(matroska->ctx->pb, before_pos, SEEK_SET);
1145 matroska->level_up = level_up;
1146 matroska->current_id = saved_id;
1149 static int matroska_aac_profile(char *codec_id)
1151 static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
1154 for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
1155 if (strstr(codec_id, aac_profiles[profile]))
1160 static int matroska_aac_sri(int samplerate)
1164 for (sri=0; sri<FF_ARRAY_ELEMS(ff_mpeg4audio_sample_rates); sri++)
1165 if (ff_mpeg4audio_sample_rates[sri] == samplerate)
1170 static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
1172 MatroskaDemuxContext *matroska = s->priv_data;
1173 EbmlList *attachements_list = &matroska->attachments;
1174 MatroskaAttachement *attachements;
1175 EbmlList *chapters_list = &matroska->chapters;
1176 MatroskaChapter *chapters;
1177 MatroskaTrack *tracks;
1178 EbmlList *index_list;
1179 MatroskaIndex *index;
1180 int index_scale = 1;
1181 uint64_t max_start = 0;
1188 /* First read the EBML header. */
1189 if (ebml_parse(matroska, ebml_syntax, &ebml)
1190 || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
1191 || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 2) {
1192 av_log(matroska->ctx, AV_LOG_ERROR,
1193 "EBML header using unsupported features\n"
1194 "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1195 ebml.version, ebml.doctype, ebml.doctype_version);
1196 ebml_free(ebml_syntax, &ebml);
1197 return AVERROR_PATCHWELCOME;
1199 for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
1200 if (!strcmp(ebml.doctype, matroska_doctypes[i]))
1202 if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
1203 av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
1205 ebml_free(ebml_syntax, &ebml);
1207 /* The next thing is a segment. */
1208 if ((res = ebml_parse(matroska, matroska_segments, matroska)) < 0)
1210 matroska_execute_seekhead(matroska);
1212 if (!matroska->time_scale)
1213 matroska->time_scale = 1000000;
1214 if (matroska->duration)
1215 matroska->ctx->duration = matroska->duration * matroska->time_scale
1216 * 1000 / AV_TIME_BASE;
1217 av_metadata_set2(&s->metadata, "title", matroska->title, 0);
1219 tracks = matroska->tracks.elem;
1220 for (i=0; i < matroska->tracks.nb_elem; i++) {
1221 MatroskaTrack *track = &tracks[i];
1222 enum CodecID codec_id = CODEC_ID_NONE;
1223 EbmlList *encodings_list = &tracks->encodings;
1224 MatroskaTrackEncoding *encodings = encodings_list->elem;
1225 uint8_t *extradata = NULL;
1226 int extradata_size = 0;
1227 int extradata_offset = 0;
1230 /* Apply some sanity checks. */
1231 if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1232 track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1233 track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1234 av_log(matroska->ctx, AV_LOG_INFO,
1235 "Unknown or unsupported track type %"PRIu64"\n",
1239 if (track->codec_id == NULL)
1242 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1243 if (!track->default_duration)
1244 track->default_duration = 1000000000/track->video.frame_rate;
1245 if (!track->video.display_width)
1246 track->video.display_width = track->video.pixel_width;
1247 if (!track->video.display_height)
1248 track->video.display_height = track->video.pixel_height;
1249 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1250 if (!track->audio.out_samplerate)
1251 track->audio.out_samplerate = track->audio.samplerate;
1253 if (encodings_list->nb_elem > 1) {
1254 av_log(matroska->ctx, AV_LOG_ERROR,
1255 "Multiple combined encodings no supported");
1256 } else if (encodings_list->nb_elem == 1) {
1257 if (encodings[0].type ||
1258 (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1260 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1263 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1265 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
1266 encodings[0].scope = 0;
1267 av_log(matroska->ctx, AV_LOG_ERROR,
1268 "Unsupported encoding type");
1269 } else if (track->codec_priv.size && encodings[0].scope&2) {
1270 uint8_t *codec_priv = track->codec_priv.data;
1271 int offset = matroska_decode_buffer(&track->codec_priv.data,
1272 &track->codec_priv.size,
1275 track->codec_priv.data = NULL;
1276 track->codec_priv.size = 0;
1277 av_log(matroska->ctx, AV_LOG_ERROR,
1278 "Failed to decode codec private data\n");
1279 } else if (offset > 0) {
1280 track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
1281 memcpy(track->codec_priv.data,
1282 encodings[0].compression.settings.data, offset);
1283 memcpy(track->codec_priv.data+offset, codec_priv,
1284 track->codec_priv.size);
1285 track->codec_priv.size += offset;
1287 if (codec_priv != track->codec_priv.data)
1288 av_free(codec_priv);
1292 for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1293 if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1294 strlen(ff_mkv_codec_tags[j].str))){
1295 codec_id= ff_mkv_codec_tags[j].id;
1300 st = track->stream = av_new_stream(s, 0);
1302 return AVERROR(ENOMEM);
1304 if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
1305 && track->codec_priv.size >= 40
1306 && track->codec_priv.data != NULL) {
1307 track->ms_compat = 1;
1308 track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1309 codec_id = ff_codec_get_id(ff_codec_bmp_tags, track->video.fourcc);
1310 extradata_offset = 40;
1311 } else if (!strcmp(track->codec_id, "A_MS/ACM")
1312 && track->codec_priv.size >= 14
1313 && track->codec_priv.data != NULL) {
1314 init_put_byte(&b, track->codec_priv.data, track->codec_priv.size,
1315 URL_RDONLY, NULL, NULL, NULL, NULL);
1316 ff_get_wav_header(&b, st->codec, track->codec_priv.size);
1317 codec_id = st->codec->codec_id;
1318 extradata_offset = FFMIN(track->codec_priv.size, 18);
1319 } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1320 && (track->codec_priv.size >= 86)
1321 && (track->codec_priv.data != NULL)) {
1322 track->video.fourcc = AV_RL32(track->codec_priv.data);
1323 codec_id=ff_codec_get_id(codec_movvideo_tags, track->video.fourcc);
1324 } else if (codec_id == CODEC_ID_PCM_S16BE) {
1325 switch (track->audio.bitdepth) {
1326 case 8: codec_id = CODEC_ID_PCM_U8; break;
1327 case 24: codec_id = CODEC_ID_PCM_S24BE; break;
1328 case 32: codec_id = CODEC_ID_PCM_S32BE; break;
1330 } else if (codec_id == CODEC_ID_PCM_S16LE) {
1331 switch (track->audio.bitdepth) {
1332 case 8: codec_id = CODEC_ID_PCM_U8; break;
1333 case 24: codec_id = CODEC_ID_PCM_S24LE; break;
1334 case 32: codec_id = CODEC_ID_PCM_S32LE; break;
1336 } else if (codec_id==CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
1337 codec_id = CODEC_ID_PCM_F64LE;
1338 } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
1339 int profile = matroska_aac_profile(track->codec_id);
1340 int sri = matroska_aac_sri(track->audio.samplerate);
1341 extradata = av_malloc(5);
1342 if (extradata == NULL)
1343 return AVERROR(ENOMEM);
1344 extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1345 extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1346 if (strstr(track->codec_id, "SBR")) {
1347 sri = matroska_aac_sri(track->audio.out_samplerate);
1348 extradata[2] = 0x56;
1349 extradata[3] = 0xE5;
1350 extradata[4] = 0x80 | (sri<<3);
1354 } else if (codec_id == CODEC_ID_TTA) {
1355 extradata_size = 30;
1356 extradata = av_mallocz(extradata_size);
1357 if (extradata == NULL)
1358 return AVERROR(ENOMEM);
1359 init_put_byte(&b, extradata, extradata_size, 1,
1360 NULL, NULL, NULL, NULL);
1361 put_buffer(&b, "TTA1", 4);
1363 put_le16(&b, track->audio.channels);
1364 put_le16(&b, track->audio.bitdepth);
1365 put_le32(&b, track->audio.out_samplerate);
1366 put_le32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1367 } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
1368 codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
1369 extradata_offset = 26;
1370 } else if (codec_id == CODEC_ID_RA_144) {
1371 track->audio.out_samplerate = 8000;
1372 track->audio.channels = 1;
1373 } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
1374 codec_id == CODEC_ID_ATRAC3 || codec_id == CODEC_ID_SIPR) {
1376 init_put_byte(&b, track->codec_priv.data,track->codec_priv.size,
1377 0, NULL, NULL, NULL, NULL);
1379 flavor = get_be16(&b);
1380 track->audio.coded_framesize = get_be32(&b);
1382 track->audio.sub_packet_h = get_be16(&b);
1383 track->audio.frame_size = get_be16(&b);
1384 track->audio.sub_packet_size = get_be16(&b);
1385 track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1386 if (codec_id == CODEC_ID_RA_288) {
1387 st->codec->block_align = track->audio.coded_framesize;
1388 track->codec_priv.size = 0;
1390 if (codec_id == CODEC_ID_SIPR && flavor < 4) {
1391 const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
1392 track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
1393 st->codec->bit_rate = sipr_bit_rate[flavor];
1395 st->codec->block_align = track->audio.sub_packet_size;
1396 extradata_offset = 78;
1399 track->codec_priv.size -= extradata_offset;
1401 if (codec_id == CODEC_ID_NONE)
1402 av_log(matroska->ctx, AV_LOG_INFO,
1403 "Unknown/unsupported CodecID %s.\n", track->codec_id);
1405 if (track->time_scale < 0.01)
1406 track->time_scale = 1.0;
1407 av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1409 st->codec->codec_id = codec_id;
1411 if (strcmp(track->language, "und"))
1412 av_metadata_set2(&st->metadata, "language", track->language, 0);
1413 av_metadata_set2(&st->metadata, "title", track->name, 0);
1415 if (track->flag_default)
1416 st->disposition |= AV_DISPOSITION_DEFAULT;
1417 if (track->flag_forced)
1418 st->disposition |= AV_DISPOSITION_FORCED;
1420 if (track->default_duration)
1421 av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
1422 track->default_duration, 1000000000, 30000);
1424 if (!st->codec->extradata) {
1426 st->codec->extradata = extradata;
1427 st->codec->extradata_size = extradata_size;
1428 } else if(track->codec_priv.data && track->codec_priv.size > 0){
1429 st->codec->extradata = av_mallocz(track->codec_priv.size +
1430 FF_INPUT_BUFFER_PADDING_SIZE);
1431 if(st->codec->extradata == NULL)
1432 return AVERROR(ENOMEM);
1433 st->codec->extradata_size = track->codec_priv.size;
1434 memcpy(st->codec->extradata,
1435 track->codec_priv.data + extradata_offset,
1436 track->codec_priv.size);
1440 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1441 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1442 st->codec->codec_tag = track->video.fourcc;
1443 st->codec->width = track->video.pixel_width;
1444 st->codec->height = track->video.pixel_height;
1445 av_reduce(&st->sample_aspect_ratio.num,
1446 &st->sample_aspect_ratio.den,
1447 st->codec->height * track->video.display_width,
1448 st->codec-> width * track->video.display_height,
1450 if (st->codec->codec_id != CODEC_ID_H264)
1451 st->need_parsing = AVSTREAM_PARSE_HEADERS;
1452 if (track->default_duration)
1453 st->avg_frame_rate = av_d2q(1000000000.0/track->default_duration, INT_MAX);
1454 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1455 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1456 st->codec->sample_rate = track->audio.out_samplerate;
1457 st->codec->channels = track->audio.channels;
1458 if (st->codec->codec_id != CODEC_ID_AAC)
1459 st->need_parsing = AVSTREAM_PARSE_HEADERS;
1460 } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1461 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1465 attachements = attachements_list->elem;
1466 for (j=0; j<attachements_list->nb_elem; j++) {
1467 if (!(attachements[j].filename && attachements[j].mime &&
1468 attachements[j].bin.data && attachements[j].bin.size > 0)) {
1469 av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1471 AVStream *st = av_new_stream(s, 0);
1474 av_metadata_set2(&st->metadata, "filename",attachements[j].filename, 0);
1475 st->codec->codec_id = CODEC_ID_NONE;
1476 st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
1477 st->codec->extradata = av_malloc(attachements[j].bin.size);
1478 if(st->codec->extradata == NULL)
1480 st->codec->extradata_size = attachements[j].bin.size;
1481 memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1483 for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1484 if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1485 strlen(ff_mkv_mime_tags[i].str))) {
1486 st->codec->codec_id = ff_mkv_mime_tags[i].id;
1490 attachements[j].stream = st;
1494 chapters = chapters_list->elem;
1495 for (i=0; i<chapters_list->nb_elem; i++)
1496 if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
1497 && (max_start==0 || chapters[i].start > max_start)) {
1498 chapters[i].chapter =
1499 ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1500 chapters[i].start, chapters[i].end,
1502 av_metadata_set2(&chapters[i].chapter->metadata,
1503 "title", chapters[i].title, 0);
1504 max_start = chapters[i].start;
1507 index_list = &matroska->index;
1508 index = index_list->elem;
1509 if (index_list->nb_elem
1510 && index[0].time > 100000000000000/matroska->time_scale) {
1511 av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
1512 index_scale = matroska->time_scale;
1514 for (i=0; i<index_list->nb_elem; i++) {
1515 EbmlList *pos_list = &index[i].pos;
1516 MatroskaIndexPos *pos = pos_list->elem;
1517 for (j=0; j<pos_list->nb_elem; j++) {
1518 MatroskaTrack *track = matroska_find_track_by_num(matroska,
1520 if (track && track->stream)
1521 av_add_index_entry(track->stream,
1522 pos[j].pos + matroska->segment_start,
1523 index[i].time/index_scale, 0, 0,
1528 matroska_convert_tags(s);
1534 * Put one packet in an application-supplied AVPacket struct.
1535 * Returns 0 on success or -1 on failure.
1537 static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
1540 if (matroska->num_packets > 0) {
1541 memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
1542 av_free(matroska->packets[0]);
1543 if (matroska->num_packets > 1) {
1544 memmove(&matroska->packets[0], &matroska->packets[1],
1545 (matroska->num_packets - 1) * sizeof(AVPacket *));
1547 av_realloc(matroska->packets, (matroska->num_packets - 1) *
1548 sizeof(AVPacket *));
1550 av_freep(&matroska->packets);
1552 matroska->num_packets--;
1560 * Free all packets in our internal queue.
1562 static void matroska_clear_queue(MatroskaDemuxContext *matroska)
1564 if (matroska->packets) {
1566 for (n = 0; n < matroska->num_packets; n++) {
1567 av_free_packet(matroska->packets[n]);
1568 av_free(matroska->packets[n]);
1570 av_freep(&matroska->packets);
1571 matroska->num_packets = 0;
1575 static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
1576 int size, int64_t pos, uint64_t cluster_time,
1577 uint64_t duration, int is_keyframe,
1578 int64_t cluster_pos)
1580 uint64_t timecode = AV_NOPTS_VALUE;
1581 MatroskaTrack *track;
1586 uint32_t *lace_size = NULL;
1587 int n, flags, laces = 0;
1590 if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
1591 av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
1597 track = matroska_find_track_by_num(matroska, num);
1598 if (size <= 3 || !track || !track->stream) {
1599 av_log(matroska->ctx, AV_LOG_INFO,
1600 "Invalid stream %"PRIu64" or size %u\n", num, size);
1604 if (st->discard >= AVDISCARD_ALL)
1606 if (duration == AV_NOPTS_VALUE)
1607 duration = track->default_duration / matroska->time_scale;
1609 block_time = AV_RB16(data);
1613 if (is_keyframe == -1)
1614 is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
1616 if (cluster_time != (uint64_t)-1
1617 && (block_time >= 0 || cluster_time >= -block_time)) {
1618 timecode = cluster_time + block_time;
1619 if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
1620 && timecode < track->end_timecode)
1621 is_keyframe = 0; /* overlapping subtitles are not key frame */
1623 av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
1624 track->end_timecode = FFMAX(track->end_timecode, timecode+duration);
1627 if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1628 if (!is_keyframe || timecode < matroska->skip_to_timecode)
1630 matroska->skip_to_keyframe = 0;
1633 switch ((flags & 0x06) >> 1) {
1634 case 0x0: /* no lacing */
1636 lace_size = av_mallocz(sizeof(int));
1637 lace_size[0] = size;
1640 case 0x1: /* Xiph lacing */
1641 case 0x2: /* fixed-size lacing */
1642 case 0x3: /* EBML lacing */
1643 assert(size>0); // size <=3 is checked before size-=3 above
1644 laces = (*data) + 1;
1647 lace_size = av_mallocz(laces * sizeof(int));
1649 switch ((flags & 0x06) >> 1) {
1650 case 0x1: /* Xiph lacing */ {
1653 for (n = 0; res == 0 && n < laces - 1; n++) {
1660 lace_size[n] += temp;
1666 total += lace_size[n];
1668 lace_size[n] = size - total;
1672 case 0x2: /* fixed-size lacing */
1673 for (n = 0; n < laces; n++)
1674 lace_size[n] = size / laces;
1677 case 0x3: /* EBML lacing */ {
1679 n = matroska_ebmlnum_uint(matroska, data, size, &num);
1681 av_log(matroska->ctx, AV_LOG_INFO,
1682 "EBML block data error\n");
1687 total = lace_size[0] = num;
1688 for (n = 1; res == 0 && n < laces - 1; n++) {
1691 r = matroska_ebmlnum_sint(matroska, data, size, &snum);
1693 av_log(matroska->ctx, AV_LOG_INFO,
1694 "EBML block data error\n");
1699 lace_size[n] = lace_size[n - 1] + snum;
1700 total += lace_size[n];
1702 lace_size[n] = size - total;
1710 for (n = 0; n < laces; n++) {
1711 if ((st->codec->codec_id == CODEC_ID_RA_288 ||
1712 st->codec->codec_id == CODEC_ID_COOK ||
1713 st->codec->codec_id == CODEC_ID_SIPR ||
1714 st->codec->codec_id == CODEC_ID_ATRAC3) &&
1715 st->codec->block_align && track->audio.sub_packet_size) {
1716 int a = st->codec->block_align;
1717 int sps = track->audio.sub_packet_size;
1718 int cfs = track->audio.coded_framesize;
1719 int h = track->audio.sub_packet_h;
1720 int y = track->audio.sub_packet_cnt;
1721 int w = track->audio.frame_size;
1724 if (!track->audio.pkt_cnt) {
1725 if (st->codec->codec_id == CODEC_ID_RA_288)
1726 for (x=0; x<h/2; x++)
1727 memcpy(track->audio.buf+x*2*w+y*cfs,
1729 else if (st->codec->codec_id == CODEC_ID_SIPR)
1730 memcpy(track->audio.buf + y*w, data, w);
1732 for (x=0; x<w/sps; x++)
1733 memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1735 if (++track->audio.sub_packet_cnt >= h) {
1736 if (st->codec->codec_id == CODEC_ID_SIPR)
1737 ff_rm_reorder_sipr_data(track->audio.buf, h, w);
1738 track->audio.sub_packet_cnt = 0;
1739 track->audio.pkt_cnt = h*w / a;
1742 while (track->audio.pkt_cnt) {
1743 pkt = av_mallocz(sizeof(AVPacket));
1744 av_new_packet(pkt, a);
1745 memcpy(pkt->data, track->audio.buf
1746 + a * (h*w / a - track->audio.pkt_cnt--), a);
1748 pkt->stream_index = st->index;
1749 dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1752 MatroskaTrackEncoding *encodings = track->encodings.elem;
1753 int offset = 0, pkt_size = lace_size[n];
1754 uint8_t *pkt_data = data;
1756 if (pkt_size > size) {
1757 av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
1761 if (encodings && encodings->scope & 1) {
1762 offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
1767 pkt = av_mallocz(sizeof(AVPacket));
1768 /* XXX: prevent data copy... */
1769 if (av_new_packet(pkt, pkt_size+offset) < 0) {
1771 res = AVERROR(ENOMEM);
1775 memcpy (pkt->data, encodings->compression.settings.data, offset);
1776 memcpy (pkt->data+offset, pkt_data, pkt_size);
1778 if (pkt_data != data)
1782 pkt->flags = is_keyframe;
1783 pkt->stream_index = st->index;
1785 if (track->ms_compat)
1786 pkt->dts = timecode;
1788 pkt->pts = timecode;
1790 if (st->codec->codec_id == CODEC_ID_TEXT)
1791 pkt->convergence_duration = duration;
1792 else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
1793 pkt->duration = duration;
1795 if (st->codec->codec_id == CODEC_ID_SSA)
1796 matroska_fix_ass_packet(matroska, pkt, duration);
1798 if (matroska->prev_pkt &&
1799 timecode != AV_NOPTS_VALUE &&
1800 matroska->prev_pkt->pts == timecode &&
1801 matroska->prev_pkt->stream_index == st->index &&
1802 st->codec->codec_id == CODEC_ID_SSA)
1803 matroska_merge_packets(matroska->prev_pkt, pkt);
1805 dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1806 matroska->prev_pkt = pkt;
1810 if (timecode != AV_NOPTS_VALUE)
1811 timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
1812 data += lace_size[n];
1813 size -= lace_size[n];
1821 static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
1823 MatroskaCluster cluster = { 0 };
1824 EbmlList *blocks_list;
1825 MatroskaBlock *blocks;
1827 int64_t pos = url_ftell(matroska->ctx->pb);
1828 matroska->prev_pkt = NULL;
1829 if (matroska->current_id)
1830 pos -= 4; /* sizeof the ID which was already read */
1831 res = ebml_parse(matroska, matroska_clusters, &cluster);
1832 blocks_list = &cluster.blocks;
1833 blocks = blocks_list->elem;
1834 for (i=0; i<blocks_list->nb_elem; i++)
1835 if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
1836 int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
1837 res=matroska_parse_block(matroska,
1838 blocks[i].bin.data, blocks[i].bin.size,
1839 blocks[i].bin.pos, cluster.timecode,
1840 blocks[i].duration, is_keyframe,
1843 ebml_free(matroska_cluster, &cluster);
1844 if (res < 0) matroska->done = 1;
1848 static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
1850 MatroskaDemuxContext *matroska = s->priv_data;
1852 while (matroska_deliver_packet(matroska, pkt)) {
1855 matroska_parse_cluster(matroska);
1861 static int matroska_read_seek(AVFormatContext *s, int stream_index,
1862 int64_t timestamp, int flags)
1864 MatroskaDemuxContext *matroska = s->priv_data;
1865 MatroskaTrack *tracks = matroska->tracks.elem;
1866 AVStream *st = s->streams[stream_index];
1867 int i, index, index_sub, index_min;
1869 if (!st->nb_index_entries)
1871 timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
1873 if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
1874 url_fseek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
1875 while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
1876 matroska_clear_queue(matroska);
1877 if (matroska_parse_cluster(matroska) < 0)
1882 matroska_clear_queue(matroska);
1887 for (i=0; i < matroska->tracks.nb_elem; i++) {
1888 tracks[i].end_timecode = 0;
1889 if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
1890 && !tracks[i].stream->discard != AVDISCARD_ALL) {
1891 index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
1893 && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
1894 && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
1895 index_min = index_sub;
1899 url_fseek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
1900 matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
1901 matroska->skip_to_timecode = st->index_entries[index].timestamp;
1903 av_update_cur_dts(s, st, st->index_entries[index].timestamp);
1907 static int matroska_read_close(AVFormatContext *s)
1909 MatroskaDemuxContext *matroska = s->priv_data;
1910 MatroskaTrack *tracks = matroska->tracks.elem;
1913 matroska_clear_queue(matroska);
1915 for (n=0; n < matroska->tracks.nb_elem; n++)
1916 if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
1917 av_free(tracks[n].audio.buf);
1918 ebml_free(matroska_segment, matroska);
1923 AVInputFormat matroska_demuxer = {
1925 NULL_IF_CONFIG_SMALL("Matroska/WebM file format"),
1926 sizeof(MatroskaDemuxContext),
1928 matroska_read_header,
1929 matroska_read_packet,
1930 matroska_read_close,