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 * @author Ronald Bultje <rbultje@ronald.bitfreak.net>
26 * @author with a little help from Moritz Bunkus <moritz@bunkus.org>
27 * @author totally reworked by Aurelien Jacobs <aurel@gnuage.org>
28 * @see specs available on the Matroska project page: http://www.matroska.org/
34 #include "avio_internal.h"
35 /* For ff_codec_get_id(). */
40 #include "libavcodec/mpeg4audio.h"
41 #include "libavutil/intfloat.h"
42 #include "libavutil/intreadwrite.h"
43 #include "libavutil/avstring.h"
44 #include "libavutil/lzo.h"
45 #include "libavutil/dict.h"
66 typedef const struct EbmlSyntax {
75 const struct EbmlSyntax *n;
95 uint64_t doctype_version;
101 } MatroskaTrackCompression;
106 MatroskaTrackCompression compression;
107 } MatroskaTrackEncoding;
111 uint64_t display_width;
112 uint64_t display_height;
113 uint64_t pixel_width;
114 uint64_t pixel_height;
116 uint64_t stereo_mode;
117 } MatroskaTrackVideo;
121 double out_samplerate;
125 /* real audio header (extracted from extradata) */
132 uint64_t buf_timecode;
134 } MatroskaTrackAudio;
139 } MatroskaTrackPlane;
142 EbmlList combine_planes;
143 } MatroskaTrackOperation;
154 uint64_t default_duration;
155 uint64_t flag_default;
156 uint64_t flag_forced;
157 MatroskaTrackVideo video;
158 MatroskaTrackAudio audio;
159 MatroskaTrackOperation operation;
163 int64_t end_timecode;
174 } MatroskaAttachement;
212 MatroskaTagTarget target;
232 AVFormatContext *ctx;
236 MatroskaLevel levels[EBML_MAX_DEPTH];
245 EbmlList attachments;
251 /* byte position of the segment inside the stream */
252 int64_t segment_start;
254 /* the packet queue */
261 /* What to skip before effectively reading a packet. */
262 int skip_to_keyframe;
263 uint64_t skip_to_timecode;
265 /* File has a CUES element, but we defer parsing until it is needed. */
266 int cues_parsing_deferred;
268 int current_cluster_num_blocks;
269 int64_t current_cluster_pos;
270 MatroskaCluster current_cluster;
272 /* File has SSA subtitles which prevent incremental cluster parsing. */
274 } MatroskaDemuxContext;
283 static EbmlSyntax ebml_header[] = {
284 { EBML_ID_EBMLREADVERSION, EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
285 { EBML_ID_EBMLMAXSIZELENGTH, EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
286 { EBML_ID_EBMLMAXIDLENGTH, EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
287 { EBML_ID_DOCTYPE, EBML_STR, 0, offsetof(Ebml,doctype), {.s="(none)"} },
288 { EBML_ID_DOCTYPEREADVERSION, EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
289 { EBML_ID_EBMLVERSION, EBML_NONE },
290 { EBML_ID_DOCTYPEVERSION, EBML_NONE },
294 static EbmlSyntax ebml_syntax[] = {
295 { EBML_ID_HEADER, EBML_NEST, 0, 0, {.n=ebml_header} },
299 static EbmlSyntax matroska_info[] = {
300 { MATROSKA_ID_TIMECODESCALE, EBML_UINT, 0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
301 { MATROSKA_ID_DURATION, EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
302 { MATROSKA_ID_TITLE, EBML_UTF8, 0, offsetof(MatroskaDemuxContext,title) },
303 { MATROSKA_ID_WRITINGAPP, EBML_NONE },
304 { MATROSKA_ID_MUXINGAPP, EBML_NONE },
305 { MATROSKA_ID_DATEUTC, EBML_BIN, 0, offsetof(MatroskaDemuxContext,date_utc) },
306 { MATROSKA_ID_SEGMENTUID, EBML_NONE },
310 static EbmlSyntax matroska_track_video[] = {
311 { MATROSKA_ID_VIDEOFRAMERATE, EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
312 { MATROSKA_ID_VIDEODISPLAYWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
313 { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
314 { MATROSKA_ID_VIDEOPIXELWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
315 { MATROSKA_ID_VIDEOPIXELHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
316 { MATROSKA_ID_VIDEOCOLORSPACE, EBML_BIN, 0, offsetof(MatroskaTrackVideo,color_space) },
317 { MATROSKA_ID_VIDEOSTEREOMODE, EBML_UINT, 0, offsetof(MatroskaTrackVideo,stereo_mode) },
318 { MATROSKA_ID_VIDEOPIXELCROPB, EBML_NONE },
319 { MATROSKA_ID_VIDEOPIXELCROPT, EBML_NONE },
320 { MATROSKA_ID_VIDEOPIXELCROPL, EBML_NONE },
321 { MATROSKA_ID_VIDEOPIXELCROPR, EBML_NONE },
322 { MATROSKA_ID_VIDEODISPLAYUNIT, EBML_NONE },
323 { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
324 { MATROSKA_ID_VIDEOASPECTRATIO, EBML_NONE },
328 static EbmlSyntax matroska_track_audio[] = {
329 { MATROSKA_ID_AUDIOSAMPLINGFREQ, EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
330 { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
331 { MATROSKA_ID_AUDIOBITDEPTH, EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
332 { MATROSKA_ID_AUDIOCHANNELS, EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
336 static EbmlSyntax matroska_track_encoding_compression[] = {
337 { MATROSKA_ID_ENCODINGCOMPALGO, EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
338 { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
342 static EbmlSyntax matroska_track_encoding[] = {
343 { MATROSKA_ID_ENCODINGSCOPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
344 { MATROSKA_ID_ENCODINGTYPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
345 { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
346 { MATROSKA_ID_ENCODINGORDER, EBML_NONE },
350 static EbmlSyntax matroska_track_encodings[] = {
351 { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
355 static EbmlSyntax matroska_track_plane[] = {
356 { MATROSKA_ID_TRACKPLANEUID, EBML_UINT, 0, offsetof(MatroskaTrackPlane,uid) },
357 { MATROSKA_ID_TRACKPLANETYPE, EBML_UINT, 0, offsetof(MatroskaTrackPlane,type) },
361 static EbmlSyntax matroska_track_combine_planes[] = {
362 { MATROSKA_ID_TRACKPLANE, EBML_NEST, sizeof(MatroskaTrackPlane), offsetof(MatroskaTrackOperation,combine_planes), {.n=matroska_track_plane} },
366 static EbmlSyntax matroska_track_operation[] = {
367 { MATROSKA_ID_TRACKCOMBINEPLANES, EBML_NEST, 0, 0, {.n=matroska_track_combine_planes} },
371 static EbmlSyntax matroska_track[] = {
372 { MATROSKA_ID_TRACKNUMBER, EBML_UINT, 0, offsetof(MatroskaTrack,num) },
373 { MATROSKA_ID_TRACKNAME, EBML_UTF8, 0, offsetof(MatroskaTrack,name) },
374 { MATROSKA_ID_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTrack,uid) },
375 { MATROSKA_ID_TRACKTYPE, EBML_UINT, 0, offsetof(MatroskaTrack,type) },
376 { MATROSKA_ID_CODECID, EBML_STR, 0, offsetof(MatroskaTrack,codec_id) },
377 { MATROSKA_ID_CODECPRIVATE, EBML_BIN, 0, offsetof(MatroskaTrack,codec_priv) },
378 { MATROSKA_ID_TRACKLANGUAGE, EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
379 { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
380 { MATROSKA_ID_TRACKTIMECODESCALE, EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
381 { MATROSKA_ID_TRACKFLAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
382 { MATROSKA_ID_TRACKFLAGFORCED, EBML_UINT, 0, offsetof(MatroskaTrack,flag_forced), {.u=0} },
383 { MATROSKA_ID_TRACKVIDEO, EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
384 { MATROSKA_ID_TRACKAUDIO, EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
385 { MATROSKA_ID_TRACKOPERATION, EBML_NEST, 0, offsetof(MatroskaTrack,operation), {.n=matroska_track_operation} },
386 { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
387 { MATROSKA_ID_TRACKFLAGENABLED, EBML_NONE },
388 { MATROSKA_ID_TRACKFLAGLACING, EBML_NONE },
389 { MATROSKA_ID_CODECNAME, EBML_NONE },
390 { MATROSKA_ID_CODECDECODEALL, EBML_NONE },
391 { MATROSKA_ID_CODECINFOURL, EBML_NONE },
392 { MATROSKA_ID_CODECDOWNLOADURL, EBML_NONE },
393 { MATROSKA_ID_TRACKMINCACHE, EBML_NONE },
394 { MATROSKA_ID_TRACKMAXCACHE, EBML_NONE },
395 { MATROSKA_ID_TRACKMAXBLKADDID, EBML_NONE },
399 static EbmlSyntax matroska_tracks[] = {
400 { MATROSKA_ID_TRACKENTRY, EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
404 static EbmlSyntax matroska_attachment[] = {
405 { MATROSKA_ID_FILEUID, EBML_UINT, 0, offsetof(MatroskaAttachement,uid) },
406 { MATROSKA_ID_FILENAME, EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
407 { MATROSKA_ID_FILEMIMETYPE, EBML_STR, 0, offsetof(MatroskaAttachement,mime) },
408 { MATROSKA_ID_FILEDATA, EBML_BIN, 0, offsetof(MatroskaAttachement,bin) },
409 { MATROSKA_ID_FILEDESC, EBML_NONE },
413 static EbmlSyntax matroska_attachments[] = {
414 { MATROSKA_ID_ATTACHEDFILE, EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
418 static EbmlSyntax matroska_chapter_display[] = {
419 { MATROSKA_ID_CHAPSTRING, EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
420 { MATROSKA_ID_CHAPLANG, EBML_NONE },
424 static EbmlSyntax matroska_chapter_entry[] = {
425 { MATROSKA_ID_CHAPTERTIMESTART, EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
426 { MATROSKA_ID_CHAPTERTIMEEND, EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
427 { MATROSKA_ID_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
428 { MATROSKA_ID_CHAPTERDISPLAY, EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
429 { MATROSKA_ID_CHAPTERFLAGHIDDEN, EBML_NONE },
430 { MATROSKA_ID_CHAPTERFLAGENABLED, EBML_NONE },
431 { MATROSKA_ID_CHAPTERPHYSEQUIV, EBML_NONE },
432 { MATROSKA_ID_CHAPTERATOM, EBML_NONE },
436 static EbmlSyntax matroska_chapter[] = {
437 { MATROSKA_ID_CHAPTERATOM, EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
438 { MATROSKA_ID_EDITIONUID, EBML_NONE },
439 { MATROSKA_ID_EDITIONFLAGHIDDEN, EBML_NONE },
440 { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
441 { MATROSKA_ID_EDITIONFLAGORDERED, EBML_NONE },
445 static EbmlSyntax matroska_chapters[] = {
446 { MATROSKA_ID_EDITIONENTRY, EBML_NEST, 0, 0, {.n=matroska_chapter} },
450 static EbmlSyntax matroska_index_pos[] = {
451 { MATROSKA_ID_CUETRACK, EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
452 { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos) },
453 { MATROSKA_ID_CUEBLOCKNUMBER, EBML_NONE },
457 static EbmlSyntax matroska_index_entry[] = {
458 { MATROSKA_ID_CUETIME, EBML_UINT, 0, offsetof(MatroskaIndex,time) },
459 { MATROSKA_ID_CUETRACKPOSITION, EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
463 static EbmlSyntax matroska_index[] = {
464 { MATROSKA_ID_POINTENTRY, EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
468 static EbmlSyntax matroska_simpletag[] = {
469 { MATROSKA_ID_TAGNAME, EBML_UTF8, 0, offsetof(MatroskaTag,name) },
470 { MATROSKA_ID_TAGSTRING, EBML_UTF8, 0, offsetof(MatroskaTag,string) },
471 { MATROSKA_ID_TAGLANG, EBML_STR, 0, offsetof(MatroskaTag,lang), {.s="und"} },
472 { MATROSKA_ID_TAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTag,def) },
473 { MATROSKA_ID_TAGDEFAULT_BUG, EBML_UINT, 0, offsetof(MatroskaTag,def) },
474 { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag,sub), {.n=matroska_simpletag} },
478 static EbmlSyntax matroska_tagtargets[] = {
479 { MATROSKA_ID_TAGTARGETS_TYPE, EBML_STR, 0, offsetof(MatroskaTagTarget,type) },
480 { MATROSKA_ID_TAGTARGETS_TYPEVALUE, EBML_UINT, 0, offsetof(MatroskaTagTarget,typevalue), {.u=50} },
481 { MATROSKA_ID_TAGTARGETS_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,trackuid) },
482 { MATROSKA_ID_TAGTARGETS_CHAPTERUID,EBML_UINT, 0, offsetof(MatroskaTagTarget,chapteruid) },
483 { MATROSKA_ID_TAGTARGETS_ATTACHUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,attachuid) },
487 static EbmlSyntax matroska_tag[] = {
488 { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTags,tag), {.n=matroska_simpletag} },
489 { MATROSKA_ID_TAGTARGETS, EBML_NEST, 0, offsetof(MatroskaTags,target), {.n=matroska_tagtargets} },
493 static EbmlSyntax matroska_tags[] = {
494 { MATROSKA_ID_TAG, EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext,tags), {.n=matroska_tag} },
498 static EbmlSyntax matroska_seekhead_entry[] = {
499 { MATROSKA_ID_SEEKID, EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
500 { MATROSKA_ID_SEEKPOSITION, EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
504 static EbmlSyntax matroska_seekhead[] = {
505 { MATROSKA_ID_SEEKENTRY, EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
509 static EbmlSyntax matroska_segment[] = {
510 { MATROSKA_ID_INFO, EBML_NEST, 0, 0, {.n=matroska_info } },
511 { MATROSKA_ID_TRACKS, EBML_NEST, 0, 0, {.n=matroska_tracks } },
512 { MATROSKA_ID_ATTACHMENTS, EBML_NEST, 0, 0, {.n=matroska_attachments} },
513 { MATROSKA_ID_CHAPTERS, EBML_NEST, 0, 0, {.n=matroska_chapters } },
514 { MATROSKA_ID_CUES, EBML_NEST, 0, 0, {.n=matroska_index } },
515 { MATROSKA_ID_TAGS, EBML_NEST, 0, 0, {.n=matroska_tags } },
516 { MATROSKA_ID_SEEKHEAD, EBML_NEST, 0, 0, {.n=matroska_seekhead } },
517 { MATROSKA_ID_CLUSTER, EBML_STOP },
521 static EbmlSyntax matroska_segments[] = {
522 { MATROSKA_ID_SEGMENT, EBML_NEST, 0, 0, {.n=matroska_segment } },
526 static EbmlSyntax matroska_blockgroup[] = {
527 { MATROSKA_ID_BLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
528 { MATROSKA_ID_SIMPLEBLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
529 { MATROSKA_ID_BLOCKDURATION, EBML_UINT, 0, offsetof(MatroskaBlock,duration) },
530 { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
531 { 1, EBML_UINT, 0, offsetof(MatroskaBlock,non_simple), {.u=1} },
535 static EbmlSyntax matroska_cluster[] = {
536 { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
537 { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
538 { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
539 { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
540 { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
544 static EbmlSyntax matroska_clusters[] = {
545 { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, {.n=matroska_cluster} },
546 { MATROSKA_ID_INFO, EBML_NONE },
547 { MATROSKA_ID_CUES, EBML_NONE },
548 { MATROSKA_ID_TAGS, EBML_NONE },
549 { MATROSKA_ID_SEEKHEAD, EBML_NONE },
553 static EbmlSyntax matroska_cluster_incremental_parsing[] = {
554 { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
555 { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
556 { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
557 { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
558 { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
559 { MATROSKA_ID_INFO, EBML_NONE },
560 { MATROSKA_ID_CUES, EBML_NONE },
561 { MATROSKA_ID_TAGS, EBML_NONE },
562 { MATROSKA_ID_SEEKHEAD, EBML_NONE },
563 { MATROSKA_ID_CLUSTER, EBML_STOP },
567 static EbmlSyntax matroska_cluster_incremental[] = {
568 { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
569 { MATROSKA_ID_BLOCKGROUP, EBML_STOP },
570 { MATROSKA_ID_SIMPLEBLOCK, EBML_STOP },
571 { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
572 { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
576 static EbmlSyntax matroska_clusters_incremental[] = {
577 { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, {.n=matroska_cluster_incremental} },
578 { MATROSKA_ID_INFO, EBML_NONE },
579 { MATROSKA_ID_CUES, EBML_NONE },
580 { MATROSKA_ID_TAGS, EBML_NONE },
581 { MATROSKA_ID_SEEKHEAD, EBML_NONE },
585 static const char *const matroska_doctypes[] = { "matroska", "webm" };
587 static int matroska_resync(MatroskaDemuxContext *matroska, int64_t last_pos)
589 AVIOContext *pb = matroska->ctx->pb;
591 matroska->current_id = 0;
592 matroska->num_levels = 0;
594 // seek to next position to resync from
595 if (avio_seek(pb, last_pos + 1, SEEK_SET) < 0 || avio_tell(pb) <= last_pos)
600 // try to find a toplevel element
601 while (!url_feof(pb)) {
602 if (id == MATROSKA_ID_INFO || id == MATROSKA_ID_TRACKS ||
603 id == MATROSKA_ID_CUES || id == MATROSKA_ID_TAGS ||
604 id == MATROSKA_ID_SEEKHEAD || id == MATROSKA_ID_ATTACHMENTS ||
605 id == MATROSKA_ID_CLUSTER || id == MATROSKA_ID_CHAPTERS)
607 matroska->current_id = id;
610 id = (id << 8) | avio_r8(pb);
618 * Return: Whether we reached the end of a level in the hierarchy or not.
620 static int ebml_level_end(MatroskaDemuxContext *matroska)
622 AVIOContext *pb = matroska->ctx->pb;
623 int64_t pos = avio_tell(pb);
625 if (matroska->num_levels > 0) {
626 MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
627 if (pos - level->start >= level->length || matroska->current_id) {
628 matroska->num_levels--;
636 * Read: an "EBML number", which is defined as a variable-length
637 * array of bytes. The first byte indicates the length by giving a
638 * number of 0-bits followed by a one. The position of the first
639 * "one" bit inside the first byte indicates the length of this
641 * Returns: number of bytes read, < 0 on error
643 static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb,
644 int max_size, uint64_t *number)
649 /* The first byte tells us the length in bytes - avio_r8() can normally
650 * return 0, but since that's not a valid first ebmlID byte, we can
651 * use it safely here to catch EOS. */
652 if (!(total = avio_r8(pb))) {
653 /* we might encounter EOS here */
655 int64_t pos = avio_tell(pb);
656 av_log(matroska->ctx, AV_LOG_ERROR,
657 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
660 return AVERROR(EIO); /* EOS or actual I/O error */
663 /* get the length of the EBML number */
664 read = 8 - ff_log2_tab[total];
665 if (read > max_size) {
666 int64_t pos = avio_tell(pb) - 1;
667 av_log(matroska->ctx, AV_LOG_ERROR,
668 "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
669 (uint8_t) total, pos, pos);
670 return AVERROR_INVALIDDATA;
673 /* read out length */
674 total ^= 1 << ff_log2_tab[total];
676 total = (total << 8) | avio_r8(pb);
684 * Read a EBML length value.
685 * This needs special handling for the "unknown length" case which has multiple
688 static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb,
691 int res = ebml_read_num(matroska, pb, 8, number);
692 if (res > 0 && *number + 1 == 1ULL << (7 * res))
693 *number = 0xffffffffffffffULL;
698 * Read the next element as an unsigned int.
699 * 0 is success, < 0 is failure.
701 static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
706 return AVERROR_INVALIDDATA;
708 /* big-endian ordering; build up number */
711 *num = (*num << 8) | avio_r8(pb);
717 * Read the next element as a float.
718 * 0 is success, < 0 is failure.
720 static int ebml_read_float(AVIOContext *pb, int size, double *num)
724 } else if (size == 4) {
725 *num = av_int2float(avio_rb32(pb));
726 } else if (size == 8){
727 *num = av_int2double(avio_rb64(pb));
729 return AVERROR_INVALIDDATA;
735 * Read the next element as an ASCII string.
736 * 0 is success, < 0 is failure.
738 static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
742 /* EBML strings are usually not 0-terminated, so we allocate one
743 * byte more, read the string and NULL-terminate it ourselves. */
744 if (!(res = av_malloc(size + 1)))
745 return AVERROR(ENOMEM);
746 if (avio_read(pb, (uint8_t *) res, size) != size) {
758 * Read the next element as binary data.
759 * 0 is success, < 0 is failure.
761 static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
764 if (!(bin->data = av_malloc(length)))
765 return AVERROR(ENOMEM);
768 bin->pos = avio_tell(pb);
769 if (avio_read(pb, bin->data, length) != length) {
770 av_freep(&bin->data);
778 * Read the next element, but only the header. The contents
779 * are supposed to be sub-elements which can be read separately.
780 * 0 is success, < 0 is failure.
782 static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
784 AVIOContext *pb = matroska->ctx->pb;
785 MatroskaLevel *level;
787 if (matroska->num_levels >= EBML_MAX_DEPTH) {
788 av_log(matroska->ctx, AV_LOG_ERROR,
789 "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
790 return AVERROR(ENOSYS);
793 level = &matroska->levels[matroska->num_levels++];
794 level->start = avio_tell(pb);
795 level->length = length;
801 * Read signed/unsigned "EBML" numbers.
802 * Return: number of bytes processed, < 0 on error
804 static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
805 uint8_t *data, uint32_t size, uint64_t *num)
808 ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
809 return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
813 * Same as above, but signed.
815 static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
816 uint8_t *data, uint32_t size, int64_t *num)
821 /* read as unsigned number first */
822 if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
825 /* make signed (weird way) */
826 *num = unum - ((1LL << (7*res - 1)) - 1);
831 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
832 EbmlSyntax *syntax, void *data);
834 static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
835 uint32_t id, void *data)
838 for (i=0; syntax[i].id; i++)
839 if (id == syntax[i].id)
841 if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
842 matroska->num_levels > 0 &&
843 matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
844 return 0; // we reached the end of an unknown size cluster
845 if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32)
846 av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
847 return ebml_parse_elem(matroska, &syntax[i], data);
850 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
853 if (!matroska->current_id) {
855 int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
858 matroska->current_id = id | 1 << 7*res;
860 return ebml_parse_id(matroska, syntax, matroska->current_id, data);
863 static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
868 for (i=0; syntax[i].id; i++)
869 switch (syntax[i].type) {
871 *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
874 *(double *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
878 *(char **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
882 while (!res && !ebml_level_end(matroska))
883 res = ebml_parse(matroska, syntax, data);
888 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
889 EbmlSyntax *syntax, void *data)
891 static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
894 // max. 16 MB for strings
895 [EBML_STR] = 0x1000000,
896 [EBML_UTF8] = 0x1000000,
897 // max. 256 MB for binary data
898 [EBML_BIN] = 0x10000000,
899 // no limits for anything else
901 AVIOContext *pb = matroska->ctx->pb;
902 uint32_t id = syntax->id;
907 data = (char *)data + syntax->data_offset;
908 if (syntax->list_elem_size) {
909 EbmlList *list = data;
910 newelem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
912 return AVERROR(ENOMEM);
913 list->elem = newelem;
914 data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
915 memset(data, 0, syntax->list_elem_size);
919 if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
920 matroska->current_id = 0;
921 if ((res = ebml_read_length(matroska, pb, &length)) < 0)
923 if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
924 av_log(matroska->ctx, AV_LOG_ERROR,
925 "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
926 length, max_lengths[syntax->type], syntax->type);
927 return AVERROR_INVALIDDATA;
931 switch (syntax->type) {
932 case EBML_UINT: res = ebml_read_uint (pb, length, data); break;
933 case EBML_FLOAT: res = ebml_read_float (pb, length, data); break;
935 case EBML_UTF8: res = ebml_read_ascii (pb, length, data); break;
936 case EBML_BIN: res = ebml_read_binary(pb, length, data); break;
937 case EBML_NEST: if ((res=ebml_read_master(matroska, length)) < 0)
939 if (id == MATROSKA_ID_SEGMENT)
940 matroska->segment_start = avio_tell(matroska->ctx->pb);
941 return ebml_parse_nest(matroska, syntax->def.n, data);
942 case EBML_PASS: return ebml_parse_id(matroska, syntax->def.n, id, data);
943 case EBML_STOP: return 1;
944 default: return avio_skip(pb,length)<0 ? AVERROR(EIO) : 0;
946 if (res == AVERROR_INVALIDDATA)
947 av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
948 else if (res == AVERROR(EIO))
949 av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
953 static void ebml_free(EbmlSyntax *syntax, void *data)
956 for (i=0; syntax[i].id; i++) {
957 void *data_off = (char *)data + syntax[i].data_offset;
958 switch (syntax[i].type) {
960 case EBML_UTF8: av_freep(data_off); break;
961 case EBML_BIN: av_freep(&((EbmlBin *)data_off)->data); break;
963 if (syntax[i].list_elem_size) {
964 EbmlList *list = data_off;
965 char *ptr = list->elem;
966 for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
967 ebml_free(syntax[i].def.n, ptr);
970 ebml_free(syntax[i].def.n, data_off);
980 static int matroska_probe(AVProbeData *p)
983 int len_mask = 0x80, size = 1, n = 1, i;
986 if (AV_RB32(p->buf) != EBML_ID_HEADER)
989 /* length of header */
991 while (size <= 8 && !(total & len_mask)) {
997 total &= (len_mask - 1);
999 total = (total << 8) | p->buf[4 + n++];
1001 /* Does the probe data contain the whole header? */
1002 if (p->buf_size < 4 + size + total)
1005 /* The header should contain a known document type. For now,
1006 * we don't parse the whole header but simply check for the
1007 * availability of that array of characters inside the header.
1008 * Not fully fool-proof, but good enough. */
1009 for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
1010 int probelen = strlen(matroska_doctypes[i]);
1011 if (total < probelen)
1013 for (n = 4+size; n <= 4+size+total-probelen; n++)
1014 if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
1015 return AVPROBE_SCORE_MAX;
1018 // probably valid EBML header but no recognized doctype
1019 return AVPROBE_SCORE_MAX/2;
1022 static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
1025 MatroskaTrack *tracks = matroska->tracks.elem;
1028 for (i=0; i < matroska->tracks.nb_elem; i++)
1029 if (tracks[i].num == num)
1032 av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
1036 static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
1037 MatroskaTrack *track)
1039 MatroskaTrackEncoding *encodings = track->encodings.elem;
1040 uint8_t* data = *buf;
1041 int isize = *buf_size;
1042 uint8_t* pkt_data = NULL;
1043 uint8_t av_unused *newpktdata;
1044 int pkt_size = isize;
1048 if (pkt_size >= 10000000)
1051 switch (encodings[0].compression.algo) {
1052 case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
1053 if (encodings[0].compression.settings.size && !encodings[0].compression.settings.data) {
1054 av_log(0, AV_LOG_ERROR, "Compression size but no data in headerstrip\n");
1057 return encodings[0].compression.settings.size;
1058 case MATROSKA_TRACK_ENCODING_COMP_LZO:
1060 olen = pkt_size *= 3;
1061 pkt_data = av_realloc(pkt_data, pkt_size+AV_LZO_OUTPUT_PADDING);
1062 result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
1063 } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
1069 case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
1070 z_stream zstream = {0};
1071 if (inflateInit(&zstream) != Z_OK)
1073 zstream.next_in = data;
1074 zstream.avail_in = isize;
1077 newpktdata = av_realloc(pkt_data, pkt_size);
1079 inflateEnd(&zstream);
1082 pkt_data = newpktdata;
1083 zstream.avail_out = pkt_size - zstream.total_out;
1084 zstream.next_out = pkt_data + zstream.total_out;
1086 result = inflate(&zstream, Z_NO_FLUSH);
1088 result = Z_MEM_ERROR;
1089 } while (result==Z_OK && pkt_size<10000000);
1090 pkt_size = zstream.total_out;
1091 inflateEnd(&zstream);
1092 if (result != Z_STREAM_END)
1098 case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
1099 bz_stream bzstream = {0};
1100 if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1102 bzstream.next_in = data;
1103 bzstream.avail_in = isize;
1106 newpktdata = av_realloc(pkt_data, pkt_size);
1108 BZ2_bzDecompressEnd(&bzstream);
1111 pkt_data = newpktdata;
1112 bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1113 bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1115 result = BZ2_bzDecompress(&bzstream);
1117 result = BZ_MEM_ERROR;
1118 } while (result==BZ_OK && pkt_size<10000000);
1119 pkt_size = bzstream.total_out_lo32;
1120 BZ2_bzDecompressEnd(&bzstream);
1121 if (result != BZ_STREAM_END)
1131 *buf_size = pkt_size;
1138 static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
1139 AVPacket *pkt, uint64_t display_duration)
1141 char *line, *layer, *ptr = pkt->data, *end = ptr+pkt->size;
1142 for (; *ptr!=',' && ptr<end-1; ptr++);
1146 for (; *ptr!=',' && ptr<end-1; ptr++);
1148 int64_t end_pts = pkt->pts + display_duration;
1149 int sc = matroska->time_scale * pkt->pts / 10000000;
1150 int ec = matroska->time_scale * end_pts / 10000000;
1151 int sh, sm, ss, eh, em, es, len;
1152 sh = sc/360000; sc -= 360000*sh;
1153 sm = sc/ 6000; sc -= 6000*sm;
1154 ss = sc/ 100; sc -= 100*ss;
1155 eh = ec/360000; ec -= 360000*eh;
1156 em = ec/ 6000; ec -= 6000*em;
1157 es = ec/ 100; ec -= 100*es;
1159 len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
1160 if (!(line = av_malloc(len)))
1162 snprintf(line,len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
1163 layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
1166 pkt->size = strlen(line);
1170 static int matroska_merge_packets(AVPacket *out, AVPacket *in)
1172 int ret = av_grow_packet(out, in->size);
1175 memcpy(out->data + out->size - in->size, in->data, in->size);
1176 av_destruct_packet(in);
1181 static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
1182 AVDictionary **metadata, char *prefix)
1184 MatroskaTag *tags = list->elem;
1188 for (i=0; i < list->nb_elem; i++) {
1189 const char *lang= (tags[i].lang && strcmp(tags[i].lang, "und")) ? tags[i].lang : NULL;
1191 if (!tags[i].name) {
1192 av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
1195 if (prefix) snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
1196 else av_strlcpy(key, tags[i].name, sizeof(key));
1197 if (tags[i].def || !lang) {
1198 av_dict_set(metadata, key, tags[i].string, 0);
1199 if (tags[i].sub.nb_elem)
1200 matroska_convert_tag(s, &tags[i].sub, metadata, key);
1203 av_strlcat(key, "-", sizeof(key));
1204 av_strlcat(key, lang, sizeof(key));
1205 av_dict_set(metadata, key, tags[i].string, 0);
1206 if (tags[i].sub.nb_elem)
1207 matroska_convert_tag(s, &tags[i].sub, metadata, key);
1210 ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
1213 static void matroska_convert_tags(AVFormatContext *s)
1215 MatroskaDemuxContext *matroska = s->priv_data;
1216 MatroskaTags *tags = matroska->tags.elem;
1219 for (i=0; i < matroska->tags.nb_elem; i++) {
1220 if (tags[i].target.attachuid) {
1221 MatroskaAttachement *attachment = matroska->attachments.elem;
1222 for (j=0; j<matroska->attachments.nb_elem; j++)
1223 if (attachment[j].uid == tags[i].target.attachuid
1224 && attachment[j].stream)
1225 matroska_convert_tag(s, &tags[i].tag,
1226 &attachment[j].stream->metadata, NULL);
1227 } else if (tags[i].target.chapteruid) {
1228 MatroskaChapter *chapter = matroska->chapters.elem;
1229 for (j=0; j<matroska->chapters.nb_elem; j++)
1230 if (chapter[j].uid == tags[i].target.chapteruid
1231 && chapter[j].chapter)
1232 matroska_convert_tag(s, &tags[i].tag,
1233 &chapter[j].chapter->metadata, NULL);
1234 } else if (tags[i].target.trackuid) {
1235 MatroskaTrack *track = matroska->tracks.elem;
1236 for (j=0; j<matroska->tracks.nb_elem; j++)
1237 if (track[j].uid == tags[i].target.trackuid && track[j].stream)
1238 matroska_convert_tag(s, &tags[i].tag,
1239 &track[j].stream->metadata, NULL);
1241 matroska_convert_tag(s, &tags[i].tag, &s->metadata,
1242 tags[i].target.type);
1247 static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska, int idx)
1249 EbmlList *seekhead_list = &matroska->seekhead;
1250 MatroskaSeekhead *seekhead = seekhead_list->elem;
1251 uint32_t level_up = matroska->level_up;
1252 int64_t before_pos = avio_tell(matroska->ctx->pb);
1253 uint32_t saved_id = matroska->current_id;
1254 MatroskaLevel level;
1258 if (idx >= seekhead_list->nb_elem
1259 || seekhead[idx].id == MATROSKA_ID_SEEKHEAD
1260 || seekhead[idx].id == MATROSKA_ID_CLUSTER)
1264 offset = seekhead[idx].pos + matroska->segment_start;
1265 if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
1266 /* We don't want to lose our seekhead level, so we add
1267 * a dummy. This is a crude hack. */
1268 if (matroska->num_levels == EBML_MAX_DEPTH) {
1269 av_log(matroska->ctx, AV_LOG_INFO,
1270 "Max EBML element depth (%d) reached, "
1271 "cannot parse further.\n", EBML_MAX_DEPTH);
1272 ret = AVERROR_INVALIDDATA;
1275 level.length = (uint64_t)-1;
1276 matroska->levels[matroska->num_levels] = level;
1277 matroska->num_levels++;
1278 matroska->current_id = 0;
1280 ret = ebml_parse(matroska, matroska_segment, matroska);
1282 /* remove dummy level */
1283 while (matroska->num_levels) {
1284 uint64_t length = matroska->levels[--matroska->num_levels].length;
1285 if (length == (uint64_t)-1)
1291 avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
1292 matroska->level_up = level_up;
1293 matroska->current_id = saved_id;
1298 static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1300 EbmlList *seekhead_list = &matroska->seekhead;
1301 int64_t before_pos = avio_tell(matroska->ctx->pb);
1304 // we should not do any seeking in the streaming case
1305 if (!matroska->ctx->pb->seekable ||
1306 (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
1309 for (i = 0; i < seekhead_list->nb_elem; i++) {
1310 MatroskaSeekhead *seekhead = seekhead_list->elem;
1311 if (seekhead[i].pos <= before_pos)
1314 // defer cues parsing until we actually need cue data.
1315 if (seekhead[i].id == MATROSKA_ID_CUES) {
1316 matroska->cues_parsing_deferred = 1;
1320 if (matroska_parse_seekhead_entry(matroska, i) < 0) {
1321 // mark index as broken
1322 matroska->cues_parsing_deferred = -1;
1328 static void matroska_add_index_entries(MatroskaDemuxContext *matroska) {
1329 EbmlList *index_list;
1330 MatroskaIndex *index;
1331 int index_scale = 1;
1334 index_list = &matroska->index;
1335 index = index_list->elem;
1336 if (index_list->nb_elem
1337 && index[0].time > 1E14/matroska->time_scale) {
1338 av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
1339 index_scale = matroska->time_scale;
1341 for (i = 0; i < index_list->nb_elem; i++) {
1342 EbmlList *pos_list = &index[i].pos;
1343 MatroskaIndexPos *pos = pos_list->elem;
1344 for (j = 0; j < pos_list->nb_elem; j++) {
1345 MatroskaTrack *track = matroska_find_track_by_num(matroska, pos[j].track);
1346 if (track && track->stream)
1347 av_add_index_entry(track->stream,
1348 pos[j].pos + matroska->segment_start,
1349 index[i].time/index_scale, 0, 0,
1355 static void matroska_parse_cues(MatroskaDemuxContext *matroska) {
1356 EbmlList *seekhead_list = &matroska->seekhead;
1357 MatroskaSeekhead *seekhead = seekhead_list->elem;
1360 for (i = 0; i < seekhead_list->nb_elem; i++)
1361 if (seekhead[i].id == MATROSKA_ID_CUES)
1363 assert(i <= seekhead_list->nb_elem);
1365 if (matroska_parse_seekhead_entry(matroska, i) < 0)
1366 matroska->cues_parsing_deferred = -1;
1367 matroska_add_index_entries(matroska);
1370 static int matroska_aac_profile(char *codec_id)
1372 static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
1375 for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
1376 if (strstr(codec_id, aac_profiles[profile]))
1381 static int matroska_aac_sri(int samplerate)
1385 for (sri=0; sri<FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
1386 if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
1391 static void matroska_metadata_creation_time(AVDictionary **metadata, int64_t date_utc)
1394 /* Convert to seconds and adjust by number of seconds between 2001-01-01 and Epoch */
1395 time_t creation_time = date_utc / 1000000000 + 978307200;
1396 struct tm *ptm = gmtime(&creation_time);
1398 strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
1399 av_dict_set(metadata, "creation_time", buffer, 0);
1402 static int matroska_read_header(AVFormatContext *s)
1404 MatroskaDemuxContext *matroska = s->priv_data;
1405 EbmlList *attachements_list = &matroska->attachments;
1406 MatroskaAttachement *attachements;
1407 EbmlList *chapters_list = &matroska->chapters;
1408 MatroskaChapter *chapters;
1409 MatroskaTrack *tracks;
1410 uint64_t max_start = 0;
1418 /* First read the EBML header. */
1419 if (ebml_parse(matroska, ebml_syntax, &ebml)
1420 || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
1421 || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 3 || !ebml.doctype) {
1422 av_log(matroska->ctx, AV_LOG_ERROR,
1423 "EBML header using unsupported features\n"
1424 "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1425 ebml.version, ebml.doctype, ebml.doctype_version);
1426 ebml_free(ebml_syntax, &ebml);
1427 return AVERROR_PATCHWELCOME;
1428 } else if (ebml.doctype_version == 3) {
1429 av_log(matroska->ctx, AV_LOG_WARNING,
1430 "EBML header using unsupported features\n"
1431 "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1432 ebml.version, ebml.doctype, ebml.doctype_version);
1434 for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
1435 if (!strcmp(ebml.doctype, matroska_doctypes[i]))
1437 if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
1438 av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
1440 ebml_free(ebml_syntax, &ebml);
1442 /* The next thing is a segment. */
1443 pos = avio_tell(matroska->ctx->pb);
1444 res = ebml_parse(matroska, matroska_segments, matroska);
1445 // try resyncing until we find a EBML_STOP type element.
1447 res = matroska_resync(matroska, pos);
1450 pos = avio_tell(matroska->ctx->pb);
1451 res = ebml_parse(matroska, matroska_segment, matroska);
1453 matroska_execute_seekhead(matroska);
1455 if (!matroska->time_scale)
1456 matroska->time_scale = 1000000;
1457 if (matroska->duration)
1458 matroska->ctx->duration = matroska->duration * matroska->time_scale
1459 * 1000 / AV_TIME_BASE;
1460 av_dict_set(&s->metadata, "title", matroska->title, 0);
1462 if (matroska->date_utc.size == 8)
1463 matroska_metadata_creation_time(&s->metadata, AV_RB64(matroska->date_utc.data));
1465 tracks = matroska->tracks.elem;
1466 for (i=0; i < matroska->tracks.nb_elem; i++) {
1467 MatroskaTrack *track = &tracks[i];
1468 enum CodecID codec_id = CODEC_ID_NONE;
1469 EbmlList *encodings_list = &track->encodings;
1470 MatroskaTrackEncoding *encodings = encodings_list->elem;
1471 uint8_t *extradata = NULL;
1472 int extradata_size = 0;
1473 int extradata_offset = 0;
1474 uint32_t fourcc = 0;
1477 /* Apply some sanity checks. */
1478 if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1479 track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1480 track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1481 av_log(matroska->ctx, AV_LOG_INFO,
1482 "Unknown or unsupported track type %"PRIu64"\n",
1486 if (track->codec_id == NULL)
1489 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1490 if (!track->default_duration && track->video.frame_rate > 0)
1491 track->default_duration = 1000000000/track->video.frame_rate;
1492 if (!track->video.display_width)
1493 track->video.display_width = track->video.pixel_width;
1494 if (!track->video.display_height)
1495 track->video.display_height = track->video.pixel_height;
1496 if (track->video.color_space.size == 4)
1497 fourcc = AV_RL32(track->video.color_space.data);
1498 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1499 if (!track->audio.out_samplerate)
1500 track->audio.out_samplerate = track->audio.samplerate;
1502 if (encodings_list->nb_elem > 1) {
1503 av_log(matroska->ctx, AV_LOG_ERROR,
1504 "Multiple combined encodings not supported");
1505 } else if (encodings_list->nb_elem == 1) {
1506 if (encodings[0].type ||
1507 (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1509 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1512 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1514 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
1515 encodings[0].scope = 0;
1516 av_log(matroska->ctx, AV_LOG_ERROR,
1517 "Unsupported encoding type");
1518 } else if (track->codec_priv.size && encodings[0].scope&2) {
1519 uint8_t *codec_priv = track->codec_priv.data;
1520 int offset = matroska_decode_buffer(&track->codec_priv.data,
1521 &track->codec_priv.size,
1524 track->codec_priv.data = NULL;
1525 track->codec_priv.size = 0;
1526 av_log(matroska->ctx, AV_LOG_ERROR,
1527 "Failed to decode codec private data\n");
1528 } else if (offset > 0) {
1529 track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
1530 memcpy(track->codec_priv.data,
1531 encodings[0].compression.settings.data, offset);
1532 memcpy(track->codec_priv.data+offset, codec_priv,
1533 track->codec_priv.size);
1534 track->codec_priv.size += offset;
1536 if (codec_priv != track->codec_priv.data)
1537 av_free(codec_priv);
1541 for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1542 if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1543 strlen(ff_mkv_codec_tags[j].str))){
1544 codec_id= ff_mkv_codec_tags[j].id;
1549 st = track->stream = avformat_new_stream(s, NULL);
1551 return AVERROR(ENOMEM);
1553 if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
1554 && track->codec_priv.size >= 40
1555 && track->codec_priv.data != NULL) {
1556 track->ms_compat = 1;
1557 fourcc = AV_RL32(track->codec_priv.data + 16);
1558 codec_id = ff_codec_get_id(ff_codec_bmp_tags, fourcc);
1559 extradata_offset = 40;
1560 } else if (!strcmp(track->codec_id, "A_MS/ACM")
1561 && track->codec_priv.size >= 14
1562 && track->codec_priv.data != NULL) {
1564 ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
1565 AVIO_FLAG_READ, NULL, NULL, NULL, NULL);
1566 ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
1569 codec_id = st->codec->codec_id;
1570 extradata_offset = FFMIN(track->codec_priv.size, 18);
1571 } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1572 && (track->codec_priv.size >= 86)
1573 && (track->codec_priv.data != NULL)) {
1574 fourcc = AV_RL32(track->codec_priv.data);
1575 codec_id = ff_codec_get_id(ff_codec_movvideo_tags, fourcc);
1576 } else if (codec_id == CODEC_ID_PCM_S16BE) {
1577 switch (track->audio.bitdepth) {
1578 case 8: codec_id = CODEC_ID_PCM_U8; break;
1579 case 24: codec_id = CODEC_ID_PCM_S24BE; break;
1580 case 32: codec_id = CODEC_ID_PCM_S32BE; break;
1582 } else if (codec_id == CODEC_ID_PCM_S16LE) {
1583 switch (track->audio.bitdepth) {
1584 case 8: codec_id = CODEC_ID_PCM_U8; break;
1585 case 24: codec_id = CODEC_ID_PCM_S24LE; break;
1586 case 32: codec_id = CODEC_ID_PCM_S32LE; break;
1588 } else if (codec_id==CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
1589 codec_id = CODEC_ID_PCM_F64LE;
1590 } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
1591 int profile = matroska_aac_profile(track->codec_id);
1592 int sri = matroska_aac_sri(track->audio.samplerate);
1593 extradata = av_mallocz(5 + FF_INPUT_BUFFER_PADDING_SIZE);
1594 if (extradata == NULL)
1595 return AVERROR(ENOMEM);
1596 extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1597 extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1598 if (strstr(track->codec_id, "SBR")) {
1599 sri = matroska_aac_sri(track->audio.out_samplerate);
1600 extradata[2] = 0x56;
1601 extradata[3] = 0xE5;
1602 extradata[4] = 0x80 | (sri<<3);
1606 } else if (codec_id == CODEC_ID_TTA) {
1607 extradata_size = 30;
1608 extradata = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
1609 if (extradata == NULL)
1610 return AVERROR(ENOMEM);
1611 ffio_init_context(&b, extradata, extradata_size, 1,
1612 NULL, NULL, NULL, NULL);
1613 avio_write(&b, "TTA1", 4);
1615 avio_wl16(&b, track->audio.channels);
1616 avio_wl16(&b, track->audio.bitdepth);
1617 avio_wl32(&b, track->audio.out_samplerate);
1618 avio_wl32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1619 } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
1620 codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
1621 extradata_offset = 26;
1622 } else if (codec_id == CODEC_ID_RA_144) {
1623 track->audio.out_samplerate = 8000;
1624 track->audio.channels = 1;
1625 } else if ((codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
1626 codec_id == CODEC_ID_ATRAC3 || codec_id == CODEC_ID_SIPR)
1627 && track->codec_priv.data) {
1630 ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
1631 0, NULL, NULL, NULL, NULL);
1633 flavor = avio_rb16(&b);
1634 track->audio.coded_framesize = avio_rb32(&b);
1636 track->audio.sub_packet_h = avio_rb16(&b);
1637 track->audio.frame_size = avio_rb16(&b);
1638 track->audio.sub_packet_size = avio_rb16(&b);
1639 track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1640 if (codec_id == CODEC_ID_RA_288) {
1641 st->codec->block_align = track->audio.coded_framesize;
1642 track->codec_priv.size = 0;
1644 if (codec_id == CODEC_ID_SIPR && flavor < 4) {
1645 const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
1646 track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
1647 st->codec->bit_rate = sipr_bit_rate[flavor];
1649 st->codec->block_align = track->audio.sub_packet_size;
1650 extradata_offset = 78;
1653 track->codec_priv.size -= extradata_offset;
1655 if (codec_id == CODEC_ID_NONE)
1656 av_log(matroska->ctx, AV_LOG_INFO,
1657 "Unknown/unsupported CodecID %s.\n", track->codec_id);
1659 if (track->time_scale < 0.01)
1660 track->time_scale = 1.0;
1661 avpriv_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1663 st->codec->codec_id = codec_id;
1665 if (strcmp(track->language, "und"))
1666 av_dict_set(&st->metadata, "language", track->language, 0);
1667 av_dict_set(&st->metadata, "title", track->name, 0);
1669 if (track->flag_default)
1670 st->disposition |= AV_DISPOSITION_DEFAULT;
1671 if (track->flag_forced)
1672 st->disposition |= AV_DISPOSITION_FORCED;
1674 if (!st->codec->extradata) {
1676 st->codec->extradata = extradata;
1677 st->codec->extradata_size = extradata_size;
1678 } else if(track->codec_priv.data && track->codec_priv.size > 0){
1679 st->codec->extradata = av_mallocz(track->codec_priv.size +
1680 FF_INPUT_BUFFER_PADDING_SIZE);
1681 if(st->codec->extradata == NULL)
1682 return AVERROR(ENOMEM);
1683 st->codec->extradata_size = track->codec_priv.size;
1684 memcpy(st->codec->extradata,
1685 track->codec_priv.data + extradata_offset,
1686 track->codec_priv.size);
1690 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1691 MatroskaTrackPlane *planes = track->operation.combine_planes.elem;
1693 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1694 st->codec->codec_tag = fourcc;
1695 st->codec->width = track->video.pixel_width;
1696 st->codec->height = track->video.pixel_height;
1697 av_reduce(&st->sample_aspect_ratio.num,
1698 &st->sample_aspect_ratio.den,
1699 st->codec->height * track->video.display_width,
1700 st->codec-> width * track->video.display_height,
1702 st->need_parsing = AVSTREAM_PARSE_HEADERS;
1703 if (track->default_duration) {
1704 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
1705 1000000000, track->default_duration, 30000);
1706 st->avg_frame_rate = st->r_frame_rate;
1709 /* export stereo mode flag as metadata tag */
1710 if (track->video.stereo_mode && track->video.stereo_mode < MATROSKA_VIDEO_STEREO_MODE_COUNT)
1711 av_dict_set(&st->metadata, "stereo_mode", matroska_video_stereo_mode[track->video.stereo_mode], 0);
1713 /* if we have virtual track, mark the real tracks */
1714 for (j=0; j < track->operation.combine_planes.nb_elem; j++) {
1716 if (planes[j].type >= MATROSKA_VIDEO_STEREO_PLANE_COUNT)
1718 snprintf(buf, sizeof(buf), "%s_%d",
1719 matroska_video_stereo_plane[planes[j].type], i);
1720 for (k=0; k < matroska->tracks.nb_elem; k++)
1721 if (planes[j].uid == tracks[k].uid) {
1722 av_dict_set(&s->streams[k]->metadata,
1723 "stereo_mode", buf, 0);
1727 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1728 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1729 st->codec->sample_rate = track->audio.out_samplerate;
1730 st->codec->channels = track->audio.channels;
1731 if (st->codec->codec_id != CODEC_ID_AAC)
1732 st->need_parsing = AVSTREAM_PARSE_HEADERS;
1733 } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1734 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1735 if (st->codec->codec_id == CODEC_ID_SSA)
1736 matroska->contains_ssa = 1;
1740 attachements = attachements_list->elem;
1741 for (j=0; j<attachements_list->nb_elem; j++) {
1742 if (!(attachements[j].filename && attachements[j].mime &&
1743 attachements[j].bin.data && attachements[j].bin.size > 0)) {
1744 av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1746 AVStream *st = avformat_new_stream(s, NULL);
1749 av_dict_set(&st->metadata, "filename",attachements[j].filename, 0);
1750 av_dict_set(&st->metadata, "mimetype", attachements[j].mime, 0);
1751 st->codec->codec_id = CODEC_ID_NONE;
1752 st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
1753 st->codec->extradata = av_malloc(attachements[j].bin.size + FF_INPUT_BUFFER_PADDING_SIZE);
1754 if(st->codec->extradata == NULL)
1756 st->codec->extradata_size = attachements[j].bin.size;
1757 memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1759 for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1760 if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1761 strlen(ff_mkv_mime_tags[i].str))) {
1762 st->codec->codec_id = ff_mkv_mime_tags[i].id;
1766 attachements[j].stream = st;
1770 chapters = chapters_list->elem;
1771 for (i=0; i<chapters_list->nb_elem; i++)
1772 if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
1773 && (max_start==0 || chapters[i].start > max_start)) {
1774 chapters[i].chapter =
1775 avpriv_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1776 chapters[i].start, chapters[i].end,
1778 av_dict_set(&chapters[i].chapter->metadata,
1779 "title", chapters[i].title, 0);
1780 max_start = chapters[i].start;
1783 matroska_add_index_entries(matroska);
1785 matroska_convert_tags(s);
1791 * Put one packet in an application-supplied AVPacket struct.
1792 * Returns 0 on success or -1 on failure.
1794 static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
1797 if (matroska->num_packets > 0) {
1798 memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
1799 av_free(matroska->packets[0]);
1800 if (matroska->num_packets > 1) {
1802 memmove(&matroska->packets[0], &matroska->packets[1],
1803 (matroska->num_packets - 1) * sizeof(AVPacket *));
1804 newpackets = av_realloc(matroska->packets,
1805 (matroska->num_packets - 1) * sizeof(AVPacket *));
1807 matroska->packets = newpackets;
1809 av_freep(&matroska->packets);
1810 matroska->prev_pkt = NULL;
1812 matroska->num_packets--;
1820 * Free all packets in our internal queue.
1822 static void matroska_clear_queue(MatroskaDemuxContext *matroska)
1824 if (matroska->packets) {
1826 for (n = 0; n < matroska->num_packets; n++) {
1827 av_free_packet(matroska->packets[n]);
1828 av_free(matroska->packets[n]);
1830 av_freep(&matroska->packets);
1831 matroska->num_packets = 0;
1835 static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
1836 int size, int64_t pos, uint64_t cluster_time,
1837 uint64_t duration, int is_keyframe,
1838 int64_t cluster_pos)
1840 uint64_t timecode = AV_NOPTS_VALUE;
1841 MatroskaTrack *track;
1846 uint32_t *lace_size = NULL;
1847 int n, flags, laces = 0;
1850 if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
1851 av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
1857 track = matroska_find_track_by_num(matroska, num);
1858 if (!track || !track->stream) {
1859 av_log(matroska->ctx, AV_LOG_INFO,
1860 "Invalid stream %"PRIu64" or size %u\n", num, size);
1861 return AVERROR_INVALIDDATA;
1862 } else if (size <= 3)
1865 if (st->discard >= AVDISCARD_ALL)
1867 av_assert1(duration != AV_NOPTS_VALUE);
1869 duration = track->default_duration / matroska->time_scale;
1871 block_time = AV_RB16(data);
1875 if (is_keyframe == -1)
1876 is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
1878 if (cluster_time != (uint64_t)-1
1879 && (block_time >= 0 || cluster_time >= -block_time)) {
1880 timecode = cluster_time + block_time;
1881 if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
1882 && timecode < track->end_timecode)
1883 is_keyframe = 0; /* overlapping subtitles are not key frame */
1885 av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
1886 track->end_timecode = FFMAX(track->end_timecode, timecode+duration);
1889 if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1890 if (timecode < matroska->skip_to_timecode)
1892 if (!st->skip_to_keyframe) {
1893 av_log(matroska->ctx, AV_LOG_ERROR, "File is broken, keyframes not correctly marked!\n");
1894 matroska->skip_to_keyframe = 0;
1897 matroska->skip_to_keyframe = 0;
1900 switch ((flags & 0x06) >> 1) {
1901 case 0x0: /* no lacing */
1903 lace_size = av_mallocz(sizeof(int));
1904 lace_size[0] = size;
1907 case 0x1: /* Xiph lacing */
1908 case 0x2: /* fixed-size lacing */
1909 case 0x3: /* EBML lacing */
1910 assert(size>0); // size <=3 is checked before size-=3 above
1911 laces = (*data) + 1;
1914 lace_size = av_mallocz(laces * sizeof(int));
1916 switch ((flags & 0x06) >> 1) {
1917 case 0x1: /* Xiph lacing */ {
1920 for (n = 0; res == 0 && n < laces - 1; n++) {
1927 lace_size[n] += temp;
1933 total += lace_size[n];
1935 lace_size[n] = size - total;
1939 case 0x2: /* fixed-size lacing */
1940 for (n = 0; n < laces; n++)
1941 lace_size[n] = size / laces;
1944 case 0x3: /* EBML lacing */ {
1946 n = matroska_ebmlnum_uint(matroska, data, size, &num);
1948 av_log(matroska->ctx, AV_LOG_INFO,
1949 "EBML block data error\n");
1954 total = lace_size[0] = num;
1955 for (n = 1; res == 0 && n < laces - 1; n++) {
1958 r = matroska_ebmlnum_sint(matroska, data, size, &snum);
1960 av_log(matroska->ctx, AV_LOG_INFO,
1961 "EBML block data error\n");
1966 lace_size[n] = lace_size[n - 1] + snum;
1967 total += lace_size[n];
1969 lace_size[laces - 1] = size - total;
1977 for (n = 0; n < laces; n++) {
1978 if ((st->codec->codec_id == CODEC_ID_RA_288 ||
1979 st->codec->codec_id == CODEC_ID_COOK ||
1980 st->codec->codec_id == CODEC_ID_SIPR ||
1981 st->codec->codec_id == CODEC_ID_ATRAC3) &&
1982 st->codec->block_align && track->audio.sub_packet_size) {
1983 int a = st->codec->block_align;
1984 int sps = track->audio.sub_packet_size;
1985 int cfs = track->audio.coded_framesize;
1986 int h = track->audio.sub_packet_h;
1987 int y = track->audio.sub_packet_cnt;
1988 int w = track->audio.frame_size;
1991 if (!track->audio.pkt_cnt) {
1992 if (track->audio.sub_packet_cnt == 0)
1993 track->audio.buf_timecode = timecode;
1994 if (st->codec->codec_id == CODEC_ID_RA_288) {
1995 if (size < cfs * h / 2) {
1996 av_log(matroska->ctx, AV_LOG_ERROR,
1997 "Corrupt int4 RM-style audio packet size\n");
1998 res = AVERROR_INVALIDDATA;
2001 for (x=0; x<h/2; x++)
2002 memcpy(track->audio.buf+x*2*w+y*cfs,
2004 } else if (st->codec->codec_id == CODEC_ID_SIPR) {
2006 av_log(matroska->ctx, AV_LOG_ERROR,
2007 "Corrupt sipr RM-style audio packet size\n");
2008 res = AVERROR_INVALIDDATA;
2011 memcpy(track->audio.buf + y*w, data, w);
2013 if (size < sps * w / sps) {
2014 av_log(matroska->ctx, AV_LOG_ERROR,
2015 "Corrupt generic RM-style audio packet size\n");
2016 res = AVERROR_INVALIDDATA;
2019 for (x=0; x<w/sps; x++)
2020 memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
2023 if (++track->audio.sub_packet_cnt >= h) {
2024 if (st->codec->codec_id == CODEC_ID_SIPR)
2025 ff_rm_reorder_sipr_data(track->audio.buf, h, w);
2026 track->audio.sub_packet_cnt = 0;
2027 track->audio.pkt_cnt = h*w / a;
2030 while (track->audio.pkt_cnt) {
2031 pkt = av_mallocz(sizeof(AVPacket));
2032 av_new_packet(pkt, a);
2033 memcpy(pkt->data, track->audio.buf
2034 + a * (h*w / a - track->audio.pkt_cnt--), a);
2035 pkt->pts = track->audio.buf_timecode;
2036 track->audio.buf_timecode = AV_NOPTS_VALUE;
2038 pkt->stream_index = st->index;
2039 dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
2042 MatroskaTrackEncoding *encodings = track->encodings.elem;
2043 int offset = 0, pkt_size = lace_size[n];
2044 uint8_t *pkt_data = data;
2046 if (pkt_size > size) {
2047 av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
2051 if (encodings && encodings->scope & 1) {
2052 offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
2057 pkt = av_mallocz(sizeof(AVPacket));
2058 /* XXX: prevent data copy... */
2059 if (av_new_packet(pkt, pkt_size+offset) < 0) {
2061 res = AVERROR(ENOMEM);
2065 memcpy (pkt->data, encodings->compression.settings.data, offset);
2066 memcpy (pkt->data+offset, pkt_data, pkt_size);
2068 if (pkt_data != data)
2072 pkt->flags = is_keyframe;
2073 pkt->stream_index = st->index;
2075 if (track->ms_compat)
2076 pkt->dts = timecode;
2078 pkt->pts = timecode;
2080 if (st->codec->codec_id == CODEC_ID_TEXT)
2081 pkt->convergence_duration = duration;
2082 else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
2083 pkt->duration = duration;
2085 if (st->codec->codec_id == CODEC_ID_SSA)
2086 matroska_fix_ass_packet(matroska, pkt, duration);
2088 if (matroska->prev_pkt &&
2089 timecode != AV_NOPTS_VALUE &&
2090 matroska->prev_pkt->pts == timecode &&
2091 matroska->prev_pkt->stream_index == st->index &&
2092 st->codec->codec_id == CODEC_ID_SSA)
2093 matroska_merge_packets(matroska->prev_pkt, pkt);
2095 dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
2096 matroska->prev_pkt = pkt;
2100 if (timecode != AV_NOPTS_VALUE)
2101 timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
2102 data += lace_size[n];
2103 size -= lace_size[n];
2112 static int matroska_parse_cluster_incremental(MatroskaDemuxContext *matroska)
2114 EbmlList *blocks_list;
2115 MatroskaBlock *blocks;
2117 res = ebml_parse(matroska,
2118 matroska_cluster_incremental_parsing,
2119 &matroska->current_cluster);
2122 if (matroska->current_cluster_pos)
2123 ebml_level_end(matroska);
2124 ebml_free(matroska_cluster, &matroska->current_cluster);
2125 memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster));
2126 matroska->current_cluster_num_blocks = 0;
2127 matroska->current_cluster_pos = avio_tell(matroska->ctx->pb);
2128 matroska->prev_pkt = NULL;
2129 /* sizeof the ID which was already read */
2130 if (matroska->current_id)
2131 matroska->current_cluster_pos -= 4;
2132 res = ebml_parse(matroska,
2133 matroska_clusters_incremental,
2134 &matroska->current_cluster);
2135 /* Try parsing the block again. */
2137 res = ebml_parse(matroska,
2138 matroska_cluster_incremental_parsing,
2139 &matroska->current_cluster);
2143 matroska->current_cluster_num_blocks <
2144 matroska->current_cluster.blocks.nb_elem) {
2145 blocks_list = &matroska->current_cluster.blocks;
2146 blocks = blocks_list->elem;
2148 matroska->current_cluster_num_blocks = blocks_list->nb_elem;
2149 i = blocks_list->nb_elem - 1;
2150 if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
2151 int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
2152 if (!blocks[i].non_simple)
2153 blocks[i].duration = 0;
2154 res = matroska_parse_block(matroska,
2155 blocks[i].bin.data, blocks[i].bin.size,
2157 matroska->current_cluster.timecode,
2158 blocks[i].duration, is_keyframe,
2159 matroska->current_cluster_pos);
2163 if (res < 0) matroska->done = 1;
2167 static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
2169 MatroskaCluster cluster = { 0 };
2170 EbmlList *blocks_list;
2171 MatroskaBlock *blocks;
2174 if (!matroska->contains_ssa)
2175 return matroska_parse_cluster_incremental(matroska);
2176 pos = avio_tell(matroska->ctx->pb);
2177 matroska->prev_pkt = NULL;
2178 if (matroska->current_id)
2179 pos -= 4; /* sizeof the ID which was already read */
2180 res = ebml_parse(matroska, matroska_clusters, &cluster);
2181 blocks_list = &cluster.blocks;
2182 blocks = blocks_list->elem;
2183 for (i=0; i<blocks_list->nb_elem; i++)
2184 if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
2185 int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
2186 res=matroska_parse_block(matroska,
2187 blocks[i].bin.data, blocks[i].bin.size,
2188 blocks[i].bin.pos, cluster.timecode,
2189 blocks[i].duration, is_keyframe,
2192 ebml_free(matroska_cluster, &cluster);
2196 static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
2198 MatroskaDemuxContext *matroska = s->priv_data;
2200 while (matroska_deliver_packet(matroska, pkt)) {
2201 int64_t pos = avio_tell(matroska->ctx->pb);
2204 if (matroska_parse_cluster(matroska) < 0)
2205 matroska_resync(matroska, pos);
2211 static int matroska_read_seek(AVFormatContext *s, int stream_index,
2212 int64_t timestamp, int flags)
2214 MatroskaDemuxContext *matroska = s->priv_data;
2215 MatroskaTrack *tracks = matroska->tracks.elem;
2216 AVStream *st = s->streams[stream_index];
2217 int i, index, index_sub, index_min;
2219 /* Parse the CUES now since we need the index data to seek. */
2220 if (matroska->cues_parsing_deferred > 0) {
2221 matroska->cues_parsing_deferred = 0;
2222 matroska_parse_cues(matroska);
2225 if (!st->nb_index_entries)
2227 timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
2229 if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2230 avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
2231 matroska->current_id = 0;
2232 while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2233 matroska->prev_pkt = NULL;
2234 matroska_clear_queue(matroska);
2235 if (matroska_parse_cluster(matroska) < 0)
2240 matroska_clear_queue(matroska);
2241 if (index < 0 || (matroska->cues_parsing_deferred < 0 && index == st->nb_index_entries - 1))
2245 for (i=0; i < matroska->tracks.nb_elem; i++) {
2246 tracks[i].audio.pkt_cnt = 0;
2247 tracks[i].audio.sub_packet_cnt = 0;
2248 tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
2249 tracks[i].end_timecode = 0;
2250 if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
2251 && !tracks[i].stream->discard != AVDISCARD_ALL) {
2252 index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
2254 && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
2255 && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
2256 index_min = index_sub;
2260 avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
2261 matroska->current_id = 0;
2262 st->skip_to_keyframe =
2263 matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
2264 matroska->skip_to_timecode = st->index_entries[index].timestamp;
2266 matroska->num_levels = 0;
2267 ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
2270 // slightly hackish but allows proper fallback to
2271 // the generic seeking code.
2272 matroska_clear_queue(matroska);
2273 matroska->current_id = 0;
2274 st->skip_to_keyframe =
2275 matroska->skip_to_keyframe = 0;
2277 matroska->num_levels = 0;
2281 static int matroska_read_close(AVFormatContext *s)
2283 MatroskaDemuxContext *matroska = s->priv_data;
2284 MatroskaTrack *tracks = matroska->tracks.elem;
2287 matroska_clear_queue(matroska);
2289 for (n=0; n < matroska->tracks.nb_elem; n++)
2290 if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
2291 av_free(tracks[n].audio.buf);
2292 ebml_free(matroska_cluster, &matroska->current_cluster);
2293 ebml_free(matroska_segment, matroska);
2298 AVInputFormat ff_matroska_demuxer = {
2299 .name = "matroska,webm",
2300 .long_name = NULL_IF_CONFIG_SMALL("Matroska/WebM file format"),
2301 .priv_data_size = sizeof(MatroskaDemuxContext),
2302 .read_probe = matroska_probe,
2303 .read_header = matroska_read_header,
2304 .read_packet = matroska_read_packet,
2305 .read_close = matroska_read_close,
2306 .read_seek = matroska_read_seek,