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 #include "avio_internal.h"
35 /* For ff_codec_get_id(). */
40 #include "libavcodec/mpeg4audio.h"
41 #include "libavutil/intfloat_readwrite.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;
227 AVFormatContext *ctx;
231 MatroskaLevel levels[EBML_MAX_DEPTH];
239 EbmlList attachments;
245 /* byte position of the segment inside the stream */
246 int64_t segment_start;
248 /* the packet queue */
255 /* What to skip before effectively reading a packet. */
256 int skip_to_keyframe;
257 uint64_t skip_to_timecode;
259 /* File has a CUES element, but we defer parsing until it is needed. */
260 int cues_parsing_deferred;
261 } MatroskaDemuxContext;
275 static EbmlSyntax ebml_header[] = {
276 { EBML_ID_EBMLREADVERSION, EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
277 { EBML_ID_EBMLMAXSIZELENGTH, EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
278 { EBML_ID_EBMLMAXIDLENGTH, EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
279 { EBML_ID_DOCTYPE, EBML_STR, 0, offsetof(Ebml,doctype), {.s="(none)"} },
280 { EBML_ID_DOCTYPEREADVERSION, EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
281 { EBML_ID_EBMLVERSION, EBML_NONE },
282 { EBML_ID_DOCTYPEVERSION, EBML_NONE },
286 static EbmlSyntax ebml_syntax[] = {
287 { EBML_ID_HEADER, EBML_NEST, 0, 0, {.n=ebml_header} },
291 static EbmlSyntax matroska_info[] = {
292 { MATROSKA_ID_TIMECODESCALE, EBML_UINT, 0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
293 { MATROSKA_ID_DURATION, EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
294 { MATROSKA_ID_TITLE, EBML_UTF8, 0, offsetof(MatroskaDemuxContext,title) },
295 { MATROSKA_ID_WRITINGAPP, EBML_NONE },
296 { MATROSKA_ID_MUXINGAPP, EBML_NONE },
297 { MATROSKA_ID_DATEUTC, EBML_NONE },
298 { MATROSKA_ID_SEGMENTUID, EBML_NONE },
302 static EbmlSyntax matroska_track_video[] = {
303 { MATROSKA_ID_VIDEOFRAMERATE, EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
304 { MATROSKA_ID_VIDEODISPLAYWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
305 { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
306 { MATROSKA_ID_VIDEOPIXELWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
307 { MATROSKA_ID_VIDEOPIXELHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
308 { MATROSKA_ID_VIDEOCOLORSPACE, EBML_BIN, 0, offsetof(MatroskaTrackVideo,color_space) },
309 { MATROSKA_ID_VIDEOSTEREOMODE, EBML_UINT, 0, offsetof(MatroskaTrackVideo,stereo_mode) },
310 { MATROSKA_ID_VIDEOPIXELCROPB, EBML_NONE },
311 { MATROSKA_ID_VIDEOPIXELCROPT, EBML_NONE },
312 { MATROSKA_ID_VIDEOPIXELCROPL, EBML_NONE },
313 { MATROSKA_ID_VIDEOPIXELCROPR, EBML_NONE },
314 { MATROSKA_ID_VIDEODISPLAYUNIT, EBML_NONE },
315 { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
316 { MATROSKA_ID_VIDEOASPECTRATIO, EBML_NONE },
320 static EbmlSyntax matroska_track_audio[] = {
321 { MATROSKA_ID_AUDIOSAMPLINGFREQ, EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
322 { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
323 { MATROSKA_ID_AUDIOBITDEPTH, EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
324 { MATROSKA_ID_AUDIOCHANNELS, EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
328 static EbmlSyntax matroska_track_encoding_compression[] = {
329 { MATROSKA_ID_ENCODINGCOMPALGO, EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
330 { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
334 static EbmlSyntax matroska_track_encoding[] = {
335 { MATROSKA_ID_ENCODINGSCOPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
336 { MATROSKA_ID_ENCODINGTYPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
337 { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
338 { MATROSKA_ID_ENCODINGORDER, EBML_NONE },
342 static EbmlSyntax matroska_track_encodings[] = {
343 { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
347 static EbmlSyntax matroska_track_plane[] = {
348 { MATROSKA_ID_TRACKPLANEUID, EBML_UINT, 0, offsetof(MatroskaTrackPlane,uid) },
349 { MATROSKA_ID_TRACKPLANETYPE, EBML_UINT, 0, offsetof(MatroskaTrackPlane,type) },
353 static EbmlSyntax matroska_track_combine_planes[] = {
354 { MATROSKA_ID_TRACKPLANE, EBML_NEST, sizeof(MatroskaTrackPlane), offsetof(MatroskaTrackOperation,combine_planes), {.n=matroska_track_plane} },
358 static EbmlSyntax matroska_track_operation[] = {
359 { MATROSKA_ID_TRACKCOMBINEPLANES, EBML_NEST, 0, 0, {.n=matroska_track_combine_planes} },
363 static EbmlSyntax matroska_track[] = {
364 { MATROSKA_ID_TRACKNUMBER, EBML_UINT, 0, offsetof(MatroskaTrack,num) },
365 { MATROSKA_ID_TRACKNAME, EBML_UTF8, 0, offsetof(MatroskaTrack,name) },
366 { MATROSKA_ID_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTrack,uid) },
367 { MATROSKA_ID_TRACKTYPE, EBML_UINT, 0, offsetof(MatroskaTrack,type) },
368 { MATROSKA_ID_CODECID, EBML_STR, 0, offsetof(MatroskaTrack,codec_id) },
369 { MATROSKA_ID_CODECPRIVATE, EBML_BIN, 0, offsetof(MatroskaTrack,codec_priv) },
370 { MATROSKA_ID_TRACKLANGUAGE, EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
371 { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
372 { MATROSKA_ID_TRACKTIMECODESCALE, EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
373 { MATROSKA_ID_TRACKFLAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
374 { MATROSKA_ID_TRACKFLAGFORCED, EBML_UINT, 0, offsetof(MatroskaTrack,flag_forced), {.u=0} },
375 { MATROSKA_ID_TRACKVIDEO, EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
376 { MATROSKA_ID_TRACKAUDIO, EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
377 { MATROSKA_ID_TRACKOPERATION, EBML_NEST, 0, offsetof(MatroskaTrack,operation), {.n=matroska_track_operation} },
378 { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
379 { MATROSKA_ID_TRACKFLAGENABLED, EBML_NONE },
380 { MATROSKA_ID_TRACKFLAGLACING, EBML_NONE },
381 { MATROSKA_ID_CODECNAME, EBML_NONE },
382 { MATROSKA_ID_CODECDECODEALL, EBML_NONE },
383 { MATROSKA_ID_CODECINFOURL, EBML_NONE },
384 { MATROSKA_ID_CODECDOWNLOADURL, EBML_NONE },
385 { MATROSKA_ID_TRACKMINCACHE, EBML_NONE },
386 { MATROSKA_ID_TRACKMAXCACHE, EBML_NONE },
387 { MATROSKA_ID_TRACKMAXBLKADDID, EBML_NONE },
391 static EbmlSyntax matroska_tracks[] = {
392 { MATROSKA_ID_TRACKENTRY, EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
396 static EbmlSyntax matroska_attachment[] = {
397 { MATROSKA_ID_FILEUID, EBML_UINT, 0, offsetof(MatroskaAttachement,uid) },
398 { MATROSKA_ID_FILENAME, EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
399 { MATROSKA_ID_FILEMIMETYPE, EBML_STR, 0, offsetof(MatroskaAttachement,mime) },
400 { MATROSKA_ID_FILEDATA, EBML_BIN, 0, offsetof(MatroskaAttachement,bin) },
401 { MATROSKA_ID_FILEDESC, EBML_NONE },
405 static EbmlSyntax matroska_attachments[] = {
406 { MATROSKA_ID_ATTACHEDFILE, EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
410 static EbmlSyntax matroska_chapter_display[] = {
411 { MATROSKA_ID_CHAPSTRING, EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
412 { MATROSKA_ID_CHAPLANG, EBML_NONE },
416 static EbmlSyntax matroska_chapter_entry[] = {
417 { MATROSKA_ID_CHAPTERTIMESTART, EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
418 { MATROSKA_ID_CHAPTERTIMEEND, EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
419 { MATROSKA_ID_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
420 { MATROSKA_ID_CHAPTERDISPLAY, EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
421 { MATROSKA_ID_CHAPTERFLAGHIDDEN, EBML_NONE },
422 { MATROSKA_ID_CHAPTERFLAGENABLED, EBML_NONE },
423 { MATROSKA_ID_CHAPTERPHYSEQUIV, EBML_NONE },
424 { MATROSKA_ID_CHAPTERATOM, EBML_NONE },
428 static EbmlSyntax matroska_chapter[] = {
429 { MATROSKA_ID_CHAPTERATOM, EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
430 { MATROSKA_ID_EDITIONUID, EBML_NONE },
431 { MATROSKA_ID_EDITIONFLAGHIDDEN, EBML_NONE },
432 { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
433 { MATROSKA_ID_EDITIONFLAGORDERED, EBML_NONE },
437 static EbmlSyntax matroska_chapters[] = {
438 { MATROSKA_ID_EDITIONENTRY, EBML_NEST, 0, 0, {.n=matroska_chapter} },
442 static EbmlSyntax matroska_index_pos[] = {
443 { MATROSKA_ID_CUETRACK, EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
444 { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos) },
445 { MATROSKA_ID_CUEBLOCKNUMBER, EBML_NONE },
449 static EbmlSyntax matroska_index_entry[] = {
450 { MATROSKA_ID_CUETIME, EBML_UINT, 0, offsetof(MatroskaIndex,time) },
451 { MATROSKA_ID_CUETRACKPOSITION, EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
455 static EbmlSyntax matroska_index[] = {
456 { MATROSKA_ID_POINTENTRY, EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
460 static EbmlSyntax matroska_simpletag[] = {
461 { MATROSKA_ID_TAGNAME, EBML_UTF8, 0, offsetof(MatroskaTag,name) },
462 { MATROSKA_ID_TAGSTRING, EBML_UTF8, 0, offsetof(MatroskaTag,string) },
463 { MATROSKA_ID_TAGLANG, EBML_STR, 0, offsetof(MatroskaTag,lang), {.s="und"} },
464 { MATROSKA_ID_TAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTag,def) },
465 { MATROSKA_ID_TAGDEFAULT_BUG, EBML_UINT, 0, offsetof(MatroskaTag,def) },
466 { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTag,sub), {.n=matroska_simpletag} },
470 static EbmlSyntax matroska_tagtargets[] = {
471 { MATROSKA_ID_TAGTARGETS_TYPE, EBML_STR, 0, offsetof(MatroskaTagTarget,type) },
472 { MATROSKA_ID_TAGTARGETS_TYPEVALUE, EBML_UINT, 0, offsetof(MatroskaTagTarget,typevalue), {.u=50} },
473 { MATROSKA_ID_TAGTARGETS_TRACKUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,trackuid) },
474 { MATROSKA_ID_TAGTARGETS_CHAPTERUID,EBML_UINT, 0, offsetof(MatroskaTagTarget,chapteruid) },
475 { MATROSKA_ID_TAGTARGETS_ATTACHUID, EBML_UINT, 0, offsetof(MatroskaTagTarget,attachuid) },
479 static EbmlSyntax matroska_tag[] = {
480 { MATROSKA_ID_SIMPLETAG, EBML_NEST, sizeof(MatroskaTag), offsetof(MatroskaTags,tag), {.n=matroska_simpletag} },
481 { MATROSKA_ID_TAGTARGETS, EBML_NEST, 0, offsetof(MatroskaTags,target), {.n=matroska_tagtargets} },
485 static EbmlSyntax matroska_tags[] = {
486 { MATROSKA_ID_TAG, EBML_NEST, sizeof(MatroskaTags), offsetof(MatroskaDemuxContext,tags), {.n=matroska_tag} },
490 static EbmlSyntax matroska_seekhead_entry[] = {
491 { MATROSKA_ID_SEEKID, EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
492 { MATROSKA_ID_SEEKPOSITION, EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
496 static EbmlSyntax matroska_seekhead[] = {
497 { MATROSKA_ID_SEEKENTRY, EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
501 static EbmlSyntax matroska_segment[] = {
502 { MATROSKA_ID_INFO, EBML_NEST, 0, 0, {.n=matroska_info } },
503 { MATROSKA_ID_TRACKS, EBML_NEST, 0, 0, {.n=matroska_tracks } },
504 { MATROSKA_ID_ATTACHMENTS, EBML_NEST, 0, 0, {.n=matroska_attachments} },
505 { MATROSKA_ID_CHAPTERS, EBML_NEST, 0, 0, {.n=matroska_chapters } },
506 { MATROSKA_ID_CUES, EBML_NEST, 0, 0, {.n=matroska_index } },
507 { MATROSKA_ID_TAGS, EBML_NEST, 0, 0, {.n=matroska_tags } },
508 { MATROSKA_ID_SEEKHEAD, EBML_NEST, 0, 0, {.n=matroska_seekhead } },
509 { MATROSKA_ID_CLUSTER, EBML_STOP },
513 static EbmlSyntax matroska_segments[] = {
514 { MATROSKA_ID_SEGMENT, EBML_NEST, 0, 0, {.n=matroska_segment } },
518 static EbmlSyntax matroska_blockgroup[] = {
519 { MATROSKA_ID_BLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
520 { MATROSKA_ID_SIMPLEBLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
521 { MATROSKA_ID_BLOCKDURATION, EBML_UINT, 0, offsetof(MatroskaBlock,duration) },
522 { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
523 { 1, EBML_UINT, 0, offsetof(MatroskaBlock,non_simple), {.u=1} },
527 static EbmlSyntax matroska_cluster[] = {
528 { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
529 { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
530 { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
531 { MATROSKA_ID_CLUSTERPOSITION,EBML_NONE },
532 { MATROSKA_ID_CLUSTERPREVSIZE,EBML_NONE },
536 static EbmlSyntax matroska_clusters[] = {
537 { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, {.n=matroska_cluster} },
538 { MATROSKA_ID_INFO, EBML_NONE },
539 { MATROSKA_ID_CUES, EBML_NONE },
540 { MATROSKA_ID_TAGS, EBML_NONE },
541 { MATROSKA_ID_SEEKHEAD, EBML_NONE },
545 static const char *matroska_doctypes[] = { "matroska", "webm" };
548 * Return: Whether we reached the end of a level in the hierarchy or not.
550 static int ebml_level_end(MatroskaDemuxContext *matroska)
552 AVIOContext *pb = matroska->ctx->pb;
553 int64_t pos = avio_tell(pb);
555 if (matroska->num_levels > 0) {
556 MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
557 if (pos - level->start >= level->length || matroska->current_id) {
558 matroska->num_levels--;
566 * Read: an "EBML number", which is defined as a variable-length
567 * array of bytes. The first byte indicates the length by giving a
568 * number of 0-bits followed by a one. The position of the first
569 * "one" bit inside the first byte indicates the length of this
571 * Returns: number of bytes read, < 0 on error
573 static int ebml_read_num(MatroskaDemuxContext *matroska, AVIOContext *pb,
574 int max_size, uint64_t *number)
579 /* The first byte tells us the length in bytes - avio_r8() can normally
580 * return 0, but since that's not a valid first ebmlID byte, we can
581 * use it safely here to catch EOS. */
582 if (!(total = avio_r8(pb))) {
583 /* we might encounter EOS here */
585 int64_t pos = avio_tell(pb);
586 av_log(matroska->ctx, AV_LOG_ERROR,
587 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
590 return AVERROR(EIO); /* EOS or actual I/O error */
593 /* get the length of the EBML number */
594 read = 8 - ff_log2_tab[total];
595 if (read > max_size) {
596 int64_t pos = avio_tell(pb) - 1;
597 av_log(matroska->ctx, AV_LOG_ERROR,
598 "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
599 (uint8_t) total, pos, pos);
600 return AVERROR_INVALIDDATA;
603 /* read out length */
604 total ^= 1 << ff_log2_tab[total];
606 total = (total << 8) | avio_r8(pb);
614 * Read a EBML length value.
615 * This needs special handling for the "unknown length" case which has multiple
618 static int ebml_read_length(MatroskaDemuxContext *matroska, AVIOContext *pb,
621 int res = ebml_read_num(matroska, pb, 8, number);
622 if (res > 0 && *number + 1 == 1ULL << (7 * res))
623 *number = 0xffffffffffffffULL;
628 * Read the next element as an unsigned int.
629 * 0 is success, < 0 is failure.
631 static int ebml_read_uint(AVIOContext *pb, int size, uint64_t *num)
636 return AVERROR_INVALIDDATA;
638 /* big-endian ordering; build up number */
641 *num = (*num << 8) | avio_r8(pb);
647 * Read the next element as a float.
648 * 0 is success, < 0 is failure.
650 static int ebml_read_float(AVIOContext *pb, int size, double *num)
654 } else if (size == 4) {
655 *num= av_int2flt(avio_rb32(pb));
657 *num= av_int2dbl(avio_rb64(pb));
659 return AVERROR_INVALIDDATA;
665 * Read the next element as an ASCII string.
666 * 0 is success, < 0 is failure.
668 static int ebml_read_ascii(AVIOContext *pb, int size, char **str)
671 /* EBML strings are usually not 0-terminated, so we allocate one
672 * byte more, read the string and NULL-terminate it ourselves. */
673 if (!(*str = av_malloc(size + 1)))
674 return AVERROR(ENOMEM);
675 if (avio_read(pb, (uint8_t *) *str, size) != size) {
685 * Read the next element as binary data.
686 * 0 is success, < 0 is failure.
688 static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)
691 if (!(bin->data = av_malloc(length)))
692 return AVERROR(ENOMEM);
695 bin->pos = avio_tell(pb);
696 if (avio_read(pb, bin->data, length) != length) {
697 av_freep(&bin->data);
705 * Read the next element, but only the header. The contents
706 * are supposed to be sub-elements which can be read separately.
707 * 0 is success, < 0 is failure.
709 static int ebml_read_master(MatroskaDemuxContext *matroska, uint64_t length)
711 AVIOContext *pb = matroska->ctx->pb;
712 MatroskaLevel *level;
714 if (matroska->num_levels >= EBML_MAX_DEPTH) {
715 av_log(matroska->ctx, AV_LOG_ERROR,
716 "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
717 return AVERROR(ENOSYS);
720 level = &matroska->levels[matroska->num_levels++];
721 level->start = avio_tell(pb);
722 level->length = length;
728 * Read signed/unsigned "EBML" numbers.
729 * Return: number of bytes processed, < 0 on error
731 static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,
732 uint8_t *data, uint32_t size, uint64_t *num)
735 ffio_init_context(&pb, data, size, 0, NULL, NULL, NULL, NULL);
736 return ebml_read_num(matroska, &pb, FFMIN(size, 8), num);
740 * Same as above, but signed.
742 static int matroska_ebmlnum_sint(MatroskaDemuxContext *matroska,
743 uint8_t *data, uint32_t size, int64_t *num)
748 /* read as unsigned number first */
749 if ((res = matroska_ebmlnum_uint(matroska, data, size, &unum)) < 0)
752 /* make signed (weird way) */
753 *num = unum - ((1LL << (7*res - 1)) - 1);
758 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
759 EbmlSyntax *syntax, void *data);
761 static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
762 uint32_t id, void *data)
765 for (i=0; syntax[i].id; i++)
766 if (id == syntax[i].id)
768 if (!syntax[i].id && id == MATROSKA_ID_CLUSTER &&
769 matroska->num_levels > 0 &&
770 matroska->levels[matroska->num_levels-1].length == 0xffffffffffffff)
771 return 0; // we reached the end of an unknown size cluster
772 if (!syntax[i].id && id != EBML_ID_VOID && id != EBML_ID_CRC32)
773 av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
774 return ebml_parse_elem(matroska, &syntax[i], data);
777 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
780 if (!matroska->current_id) {
782 int res = ebml_read_num(matroska, matroska->ctx->pb, 4, &id);
785 matroska->current_id = id | 1 << 7*res;
787 return ebml_parse_id(matroska, syntax, matroska->current_id, data);
790 static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
795 for (i=0; syntax[i].id; i++)
796 switch (syntax[i].type) {
798 *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
801 *(double *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
805 *(char **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
809 while (!res && !ebml_level_end(matroska))
810 res = ebml_parse(matroska, syntax, data);
815 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
816 EbmlSyntax *syntax, void *data)
818 static const uint64_t max_lengths[EBML_TYPE_COUNT] = {
821 // max. 16 MB for strings
822 [EBML_STR] = 0x1000000,
823 [EBML_UTF8] = 0x1000000,
824 // max. 256 MB for binary data
825 [EBML_BIN] = 0x10000000,
826 // no limits for anything else
828 AVIOContext *pb = matroska->ctx->pb;
829 uint32_t id = syntax->id;
834 data = (char *)data + syntax->data_offset;
835 if (syntax->list_elem_size) {
836 EbmlList *list = data;
837 newelem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
839 return AVERROR(ENOMEM);
840 list->elem = newelem;
841 data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
842 memset(data, 0, syntax->list_elem_size);
846 if (syntax->type != EBML_PASS && syntax->type != EBML_STOP) {
847 matroska->current_id = 0;
848 if ((res = ebml_read_length(matroska, pb, &length)) < 0)
850 if (max_lengths[syntax->type] && length > max_lengths[syntax->type]) {
851 av_log(matroska->ctx, AV_LOG_ERROR,
852 "Invalid length 0x%"PRIx64" > 0x%"PRIx64" for syntax element %i\n",
853 length, max_lengths[syntax->type], syntax->type);
854 return AVERROR_INVALIDDATA;
858 switch (syntax->type) {
859 case EBML_UINT: res = ebml_read_uint (pb, length, data); break;
860 case EBML_FLOAT: res = ebml_read_float (pb, length, data); break;
862 case EBML_UTF8: res = ebml_read_ascii (pb, length, data); break;
863 case EBML_BIN: res = ebml_read_binary(pb, length, data); break;
864 case EBML_NEST: if ((res=ebml_read_master(matroska, length)) < 0)
866 if (id == MATROSKA_ID_SEGMENT)
867 matroska->segment_start = avio_tell(matroska->ctx->pb);
868 return ebml_parse_nest(matroska, syntax->def.n, data);
869 case EBML_PASS: return ebml_parse_id(matroska, syntax->def.n, id, data);
870 case EBML_STOP: return 1;
871 default: return avio_skip(pb,length)<0 ? AVERROR(EIO) : 0;
873 if (res == AVERROR_INVALIDDATA)
874 av_log(matroska->ctx, AV_LOG_ERROR, "Invalid element\n");
875 else if (res == AVERROR(EIO))
876 av_log(matroska->ctx, AV_LOG_ERROR, "Read error\n");
880 static void ebml_free(EbmlSyntax *syntax, void *data)
883 for (i=0; syntax[i].id; i++) {
884 void *data_off = (char *)data + syntax[i].data_offset;
885 switch (syntax[i].type) {
887 case EBML_UTF8: av_freep(data_off); break;
888 case EBML_BIN: av_freep(&((EbmlBin *)data_off)->data); break;
890 if (syntax[i].list_elem_size) {
891 EbmlList *list = data_off;
892 char *ptr = list->elem;
893 for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
894 ebml_free(syntax[i].def.n, ptr);
897 ebml_free(syntax[i].def.n, data_off);
907 static int matroska_probe(AVProbeData *p)
910 int len_mask = 0x80, size = 1, n = 1, i;
913 if (AV_RB32(p->buf) != EBML_ID_HEADER)
916 /* length of header */
918 while (size <= 8 && !(total & len_mask)) {
924 total &= (len_mask - 1);
926 total = (total << 8) | p->buf[4 + n++];
928 /* Does the probe data contain the whole header? */
929 if (p->buf_size < 4 + size + total)
932 /* The header should contain a known document type. For now,
933 * we don't parse the whole header but simply check for the
934 * availability of that array of characters inside the header.
935 * Not fully fool-proof, but good enough. */
936 for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++) {
937 int probelen = strlen(matroska_doctypes[i]);
938 if (total < probelen)
940 for (n = 4+size; n <= 4+size+total-probelen; n++)
941 if (!memcmp(p->buf+n, matroska_doctypes[i], probelen))
942 return AVPROBE_SCORE_MAX;
945 // probably valid EBML header but no recognized doctype
946 return AVPROBE_SCORE_MAX/2;
949 static MatroskaTrack *matroska_find_track_by_num(MatroskaDemuxContext *matroska,
952 MatroskaTrack *tracks = matroska->tracks.elem;
955 for (i=0; i < matroska->tracks.nb_elem; i++)
956 if (tracks[i].num == num)
959 av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
963 static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
964 MatroskaTrack *track)
966 MatroskaTrackEncoding *encodings = track->encodings.elem;
967 uint8_t* data = *buf;
968 int isize = *buf_size;
969 uint8_t* pkt_data = NULL;
971 int pkt_size = isize;
975 if (pkt_size >= 10000000)
978 switch (encodings[0].compression.algo) {
979 case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
980 return encodings[0].compression.settings.size;
981 case MATROSKA_TRACK_ENCODING_COMP_LZO:
983 olen = pkt_size *= 3;
984 pkt_data = av_realloc(pkt_data, pkt_size+AV_LZO_OUTPUT_PADDING);
985 result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
986 } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
992 case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
993 z_stream zstream = {0};
994 if (inflateInit(&zstream) != Z_OK)
996 zstream.next_in = data;
997 zstream.avail_in = isize;
1000 newpktdata = av_realloc(pkt_data, pkt_size);
1002 inflateEnd(&zstream);
1005 pkt_data = newpktdata;
1006 zstream.avail_out = pkt_size - zstream.total_out;
1007 zstream.next_out = pkt_data + zstream.total_out;
1009 result = inflate(&zstream, Z_NO_FLUSH);
1011 result = Z_MEM_ERROR;
1012 } while (result==Z_OK && pkt_size<10000000);
1013 pkt_size = zstream.total_out;
1014 inflateEnd(&zstream);
1015 if (result != Z_STREAM_END)
1021 case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
1022 bz_stream bzstream = {0};
1023 if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1025 bzstream.next_in = data;
1026 bzstream.avail_in = isize;
1029 newpktdata = av_realloc(pkt_data, pkt_size);
1031 BZ2_bzDecompressEnd(&bzstream);
1034 pkt_data = newpktdata;
1035 bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1036 bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1038 result = BZ2_bzDecompress(&bzstream);
1040 result = BZ_MEM_ERROR;
1041 } while (result==BZ_OK && pkt_size<10000000);
1042 pkt_size = bzstream.total_out_lo32;
1043 BZ2_bzDecompressEnd(&bzstream);
1044 if (result != BZ_STREAM_END)
1054 *buf_size = pkt_size;
1061 static void matroska_fix_ass_packet(MatroskaDemuxContext *matroska,
1062 AVPacket *pkt, uint64_t display_duration)
1064 char *line, *layer, *ptr = pkt->data, *end = ptr+pkt->size;
1065 for (; *ptr!=',' && ptr<end-1; ptr++);
1069 for (; *ptr!=',' && ptr<end-1; ptr++);
1071 int64_t end_pts = pkt->pts + display_duration;
1072 int sc = matroska->time_scale * pkt->pts / 10000000;
1073 int ec = matroska->time_scale * end_pts / 10000000;
1074 int sh, sm, ss, eh, em, es, len;
1075 sh = sc/360000; sc -= 360000*sh;
1076 sm = sc/ 6000; sc -= 6000*sm;
1077 ss = sc/ 100; sc -= 100*ss;
1078 eh = ec/360000; ec -= 360000*eh;
1079 em = ec/ 6000; ec -= 6000*em;
1080 es = ec/ 100; ec -= 100*es;
1082 len = 50 + end-ptr + FF_INPUT_BUFFER_PADDING_SIZE;
1083 if (!(line = av_malloc(len)))
1085 snprintf(line,len,"Dialogue: %s,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s\r\n",
1086 layer, sh, sm, ss, sc, eh, em, es, ec, ptr);
1089 pkt->size = strlen(line);
1093 static int matroska_merge_packets(AVPacket *out, AVPacket *in)
1095 void *newdata = av_realloc(out->data, out->size+in->size);
1097 return AVERROR(ENOMEM);
1098 out->data = newdata;
1099 memcpy(out->data+out->size, in->data, in->size);
1100 out->size += in->size;
1101 av_destruct_packet(in);
1106 static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
1107 AVDictionary **metadata, char *prefix)
1109 MatroskaTag *tags = list->elem;
1113 for (i=0; i < list->nb_elem; i++) {
1114 const char *lang = strcmp(tags[i].lang, "und") ? tags[i].lang : NULL;
1116 if (!tags[i].name) {
1117 av_log(s, AV_LOG_WARNING, "Skipping invalid tag with no TagName.\n");
1120 if (prefix) snprintf(key, sizeof(key), "%s/%s", prefix, tags[i].name);
1121 else av_strlcpy(key, tags[i].name, sizeof(key));
1122 if (tags[i].def || !lang) {
1123 av_dict_set(metadata, key, tags[i].string, 0);
1124 if (tags[i].sub.nb_elem)
1125 matroska_convert_tag(s, &tags[i].sub, metadata, key);
1128 av_strlcat(key, "-", sizeof(key));
1129 av_strlcat(key, lang, sizeof(key));
1130 av_dict_set(metadata, key, tags[i].string, 0);
1131 if (tags[i].sub.nb_elem)
1132 matroska_convert_tag(s, &tags[i].sub, metadata, key);
1135 ff_metadata_conv(metadata, NULL, ff_mkv_metadata_conv);
1138 static void matroska_convert_tags(AVFormatContext *s)
1140 MatroskaDemuxContext *matroska = s->priv_data;
1141 MatroskaTags *tags = matroska->tags.elem;
1144 for (i=0; i < matroska->tags.nb_elem; i++) {
1145 if (tags[i].target.attachuid) {
1146 MatroskaAttachement *attachment = matroska->attachments.elem;
1147 for (j=0; j<matroska->attachments.nb_elem; j++)
1148 if (attachment[j].uid == tags[i].target.attachuid
1149 && attachment[j].stream)
1150 matroska_convert_tag(s, &tags[i].tag,
1151 &attachment[j].stream->metadata, NULL);
1152 } else if (tags[i].target.chapteruid) {
1153 MatroskaChapter *chapter = matroska->chapters.elem;
1154 for (j=0; j<matroska->chapters.nb_elem; j++)
1155 if (chapter[j].uid == tags[i].target.chapteruid
1156 && chapter[j].chapter)
1157 matroska_convert_tag(s, &tags[i].tag,
1158 &chapter[j].chapter->metadata, NULL);
1159 } else if (tags[i].target.trackuid) {
1160 MatroskaTrack *track = matroska->tracks.elem;
1161 for (j=0; j<matroska->tracks.nb_elem; j++)
1162 if (track[j].uid == tags[i].target.trackuid && track[j].stream)
1163 matroska_convert_tag(s, &tags[i].tag,
1164 &track[j].stream->metadata, NULL);
1166 matroska_convert_tag(s, &tags[i].tag, &s->metadata,
1167 tags[i].target.type);
1172 static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska, int idx)
1174 EbmlList *seekhead_list = &matroska->seekhead;
1175 MatroskaSeekhead *seekhead = seekhead_list->elem;
1176 uint32_t level_up = matroska->level_up;
1177 int64_t before_pos = avio_tell(matroska->ctx->pb);
1178 uint32_t saved_id = matroska->current_id;
1179 MatroskaLevel level;
1183 if (idx >= seekhead_list->nb_elem
1184 || seekhead[idx].id == MATROSKA_ID_SEEKHEAD
1185 || seekhead[idx].id == MATROSKA_ID_CLUSTER)
1189 offset = seekhead[idx].pos + matroska->segment_start;
1190 if (avio_seek(matroska->ctx->pb, offset, SEEK_SET) == offset) {
1191 /* We don't want to lose our seekhead level, so we add
1192 * a dummy. This is a crude hack. */
1193 if (matroska->num_levels == EBML_MAX_DEPTH) {
1194 av_log(matroska->ctx, AV_LOG_INFO,
1195 "Max EBML element depth (%d) reached, "
1196 "cannot parse further.\n", EBML_MAX_DEPTH);
1197 ret = AVERROR_INVALIDDATA;
1200 level.length = (uint64_t)-1;
1201 matroska->levels[matroska->num_levels] = level;
1202 matroska->num_levels++;
1203 matroska->current_id = 0;
1205 ret = ebml_parse(matroska, matroska_segment, matroska);
1207 /* remove dummy level */
1208 while (matroska->num_levels) {
1209 uint64_t length = matroska->levels[--matroska->num_levels].length;
1210 if (length == (uint64_t)-1)
1216 avio_seek(matroska->ctx->pb, before_pos, SEEK_SET);
1217 matroska->level_up = level_up;
1218 matroska->current_id = saved_id;
1223 static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1225 EbmlList *seekhead_list = &matroska->seekhead;
1226 MatroskaSeekhead *seekhead = seekhead_list->elem;
1227 int64_t before_pos = avio_tell(matroska->ctx->pb);
1230 // we should not do any seeking in the streaming case
1231 if (!matroska->ctx->pb->seekable ||
1232 (matroska->ctx->flags & AVFMT_FLAG_IGNIDX))
1235 for (i = 0; i < seekhead_list->nb_elem; i++) {
1236 if (seekhead[i].pos <= before_pos)
1239 // defer cues parsing until we actually need cue data.
1240 if (seekhead[i].id == MATROSKA_ID_CUES) {
1241 matroska->cues_parsing_deferred = 1;
1245 if (matroska_parse_seekhead_entry(matroska, i) < 0)
1250 static void matroska_add_index_entries(MatroskaDemuxContext *matroska) {
1251 EbmlList *index_list;
1252 MatroskaIndex *index;
1253 int index_scale = 1;
1256 index_list = &matroska->index;
1257 index = index_list->elem;
1258 if (index_list->nb_elem
1259 && index[0].time > 1E14/matroska->time_scale) {
1260 av_log(matroska->ctx, AV_LOG_WARNING, "Working around broken index.\n");
1261 index_scale = matroska->time_scale;
1263 for (i = 0; i < index_list->nb_elem; i++) {
1264 EbmlList *pos_list = &index[i].pos;
1265 MatroskaIndexPos *pos = pos_list->elem;
1266 for (j = 0; j < pos_list->nb_elem; j++) {
1267 MatroskaTrack *track = matroska_find_track_by_num(matroska, pos[j].track);
1268 if (track && track->stream)
1269 av_add_index_entry(track->stream,
1270 pos[j].pos + matroska->segment_start,
1271 index[i].time/index_scale, 0, 0,
1277 static void matroska_parse_cues(MatroskaDemuxContext *matroska) {
1278 EbmlList *seekhead_list = &matroska->seekhead;
1279 MatroskaSeekhead *seekhead = seekhead_list->elem;
1282 for (i = 0; i < seekhead_list->nb_elem; i++)
1283 if (seekhead[i].id == MATROSKA_ID_CUES)
1285 assert(i <= seekhead_list->nb_elem);
1287 matroska_parse_seekhead_entry(matroska, i);
1288 matroska_add_index_entries(matroska);
1291 static int matroska_aac_profile(char *codec_id)
1293 static const char * const aac_profiles[] = { "MAIN", "LC", "SSR" };
1296 for (profile=0; profile<FF_ARRAY_ELEMS(aac_profiles); profile++)
1297 if (strstr(codec_id, aac_profiles[profile]))
1302 static int matroska_aac_sri(int samplerate)
1306 for (sri=0; sri<FF_ARRAY_ELEMS(avpriv_mpeg4audio_sample_rates); sri++)
1307 if (avpriv_mpeg4audio_sample_rates[sri] == samplerate)
1312 static int matroska_read_header(AVFormatContext *s, AVFormatParameters *ap)
1314 MatroskaDemuxContext *matroska = s->priv_data;
1315 EbmlList *attachements_list = &matroska->attachments;
1316 MatroskaAttachement *attachements;
1317 EbmlList *chapters_list = &matroska->chapters;
1318 MatroskaChapter *chapters;
1319 MatroskaTrack *tracks;
1320 uint64_t max_start = 0;
1327 /* First read the EBML header. */
1328 if (ebml_parse(matroska, ebml_syntax, &ebml)
1329 || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
1330 || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 3) {
1331 av_log(matroska->ctx, AV_LOG_ERROR,
1332 "EBML header using unsupported features\n"
1333 "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1334 ebml.version, ebml.doctype, ebml.doctype_version);
1335 ebml_free(ebml_syntax, &ebml);
1336 return AVERROR_PATCHWELCOME;
1337 } else if (ebml.doctype_version == 3) {
1338 av_log(matroska->ctx, AV_LOG_WARNING,
1339 "EBML header using unsupported features\n"
1340 "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1341 ebml.version, ebml.doctype, ebml.doctype_version);
1343 for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)
1344 if (!strcmp(ebml.doctype, matroska_doctypes[i]))
1346 if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {
1347 av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);
1349 ebml_free(ebml_syntax, &ebml);
1351 /* The next thing is a segment. */
1352 if ((res = ebml_parse(matroska, matroska_segments, matroska)) < 0)
1354 matroska_execute_seekhead(matroska);
1356 if (!matroska->time_scale)
1357 matroska->time_scale = 1000000;
1358 if (matroska->duration)
1359 matroska->ctx->duration = matroska->duration * matroska->time_scale
1360 * 1000 / AV_TIME_BASE;
1361 av_dict_set(&s->metadata, "title", matroska->title, 0);
1363 tracks = matroska->tracks.elem;
1364 for (i=0; i < matroska->tracks.nb_elem; i++) {
1365 MatroskaTrack *track = &tracks[i];
1366 enum CodecID codec_id = CODEC_ID_NONE;
1367 EbmlList *encodings_list = &track->encodings;
1368 MatroskaTrackEncoding *encodings = encodings_list->elem;
1369 uint8_t *extradata = NULL;
1370 int extradata_size = 0;
1371 int extradata_offset = 0;
1372 uint32_t fourcc = 0;
1375 /* Apply some sanity checks. */
1376 if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1377 track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1378 track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1379 av_log(matroska->ctx, AV_LOG_INFO,
1380 "Unknown or unsupported track type %"PRIu64"\n",
1384 if (track->codec_id == NULL)
1387 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1388 if (!track->default_duration)
1389 track->default_duration = 1000000000/track->video.frame_rate;
1390 if (!track->video.display_width)
1391 track->video.display_width = track->video.pixel_width;
1392 if (!track->video.display_height)
1393 track->video.display_height = track->video.pixel_height;
1394 if (track->video.color_space.size == 4)
1395 fourcc = AV_RL32(track->video.color_space.data);
1396 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1397 if (!track->audio.out_samplerate)
1398 track->audio.out_samplerate = track->audio.samplerate;
1400 if (encodings_list->nb_elem > 1) {
1401 av_log(matroska->ctx, AV_LOG_ERROR,
1402 "Multiple combined encodings not supported");
1403 } else if (encodings_list->nb_elem == 1) {
1404 if (encodings[0].type ||
1405 (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1407 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1410 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1412 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
1413 encodings[0].scope = 0;
1414 av_log(matroska->ctx, AV_LOG_ERROR,
1415 "Unsupported encoding type");
1416 } else if (track->codec_priv.size && encodings[0].scope&2) {
1417 uint8_t *codec_priv = track->codec_priv.data;
1418 int offset = matroska_decode_buffer(&track->codec_priv.data,
1419 &track->codec_priv.size,
1422 track->codec_priv.data = NULL;
1423 track->codec_priv.size = 0;
1424 av_log(matroska->ctx, AV_LOG_ERROR,
1425 "Failed to decode codec private data\n");
1426 } else if (offset > 0) {
1427 track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
1428 memcpy(track->codec_priv.data,
1429 encodings[0].compression.settings.data, offset);
1430 memcpy(track->codec_priv.data+offset, codec_priv,
1431 track->codec_priv.size);
1432 track->codec_priv.size += offset;
1434 if (codec_priv != track->codec_priv.data)
1435 av_free(codec_priv);
1439 for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1440 if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1441 strlen(ff_mkv_codec_tags[j].str))){
1442 codec_id= ff_mkv_codec_tags[j].id;
1447 st = track->stream = avformat_new_stream(s, NULL);
1449 return AVERROR(ENOMEM);
1451 if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")
1452 && track->codec_priv.size >= 40
1453 && track->codec_priv.data != NULL) {
1454 track->ms_compat = 1;
1455 fourcc = AV_RL32(track->codec_priv.data + 16);
1456 codec_id = ff_codec_get_id(ff_codec_bmp_tags, fourcc);
1457 extradata_offset = 40;
1458 } else if (!strcmp(track->codec_id, "A_MS/ACM")
1459 && track->codec_priv.size >= 14
1460 && track->codec_priv.data != NULL) {
1462 ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,
1463 AVIO_FLAG_READ, NULL, NULL, NULL, NULL);
1464 ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);
1467 codec_id = st->codec->codec_id;
1468 extradata_offset = FFMIN(track->codec_priv.size, 18);
1469 } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1470 && (track->codec_priv.size >= 86)
1471 && (track->codec_priv.data != NULL)) {
1472 fourcc = AV_RL32(track->codec_priv.data);
1473 codec_id = ff_codec_get_id(codec_movvideo_tags, fourcc);
1474 } else if (codec_id == CODEC_ID_PCM_S16BE) {
1475 switch (track->audio.bitdepth) {
1476 case 8: codec_id = CODEC_ID_PCM_U8; break;
1477 case 24: codec_id = CODEC_ID_PCM_S24BE; break;
1478 case 32: codec_id = CODEC_ID_PCM_S32BE; break;
1480 } else if (codec_id == CODEC_ID_PCM_S16LE) {
1481 switch (track->audio.bitdepth) {
1482 case 8: codec_id = CODEC_ID_PCM_U8; break;
1483 case 24: codec_id = CODEC_ID_PCM_S24LE; break;
1484 case 32: codec_id = CODEC_ID_PCM_S32LE; break;
1486 } else if (codec_id==CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {
1487 codec_id = CODEC_ID_PCM_F64LE;
1488 } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
1489 int profile = matroska_aac_profile(track->codec_id);
1490 int sri = matroska_aac_sri(track->audio.samplerate);
1491 extradata = av_malloc(5);
1492 if (extradata == NULL)
1493 return AVERROR(ENOMEM);
1494 extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1495 extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1496 if (strstr(track->codec_id, "SBR")) {
1497 sri = matroska_aac_sri(track->audio.out_samplerate);
1498 extradata[2] = 0x56;
1499 extradata[3] = 0xE5;
1500 extradata[4] = 0x80 | (sri<<3);
1504 } else if (codec_id == CODEC_ID_TTA) {
1505 extradata_size = 30;
1506 extradata = av_mallocz(extradata_size);
1507 if (extradata == NULL)
1508 return AVERROR(ENOMEM);
1509 ffio_init_context(&b, extradata, extradata_size, 1,
1510 NULL, NULL, NULL, NULL);
1511 avio_write(&b, "TTA1", 4);
1513 avio_wl16(&b, track->audio.channels);
1514 avio_wl16(&b, track->audio.bitdepth);
1515 avio_wl32(&b, track->audio.out_samplerate);
1516 avio_wl32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1517 } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
1518 codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
1519 extradata_offset = 26;
1520 } else if (codec_id == CODEC_ID_RA_144) {
1521 track->audio.out_samplerate = 8000;
1522 track->audio.channels = 1;
1523 } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
1524 codec_id == CODEC_ID_ATRAC3 || codec_id == CODEC_ID_SIPR) {
1526 ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,
1527 0, NULL, NULL, NULL, NULL);
1529 flavor = avio_rb16(&b);
1530 track->audio.coded_framesize = avio_rb32(&b);
1532 track->audio.sub_packet_h = avio_rb16(&b);
1533 track->audio.frame_size = avio_rb16(&b);
1534 track->audio.sub_packet_size = avio_rb16(&b);
1535 track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1536 if (codec_id == CODEC_ID_RA_288) {
1537 st->codec->block_align = track->audio.coded_framesize;
1538 track->codec_priv.size = 0;
1540 if (codec_id == CODEC_ID_SIPR && flavor < 4) {
1541 const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };
1542 track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];
1543 st->codec->bit_rate = sipr_bit_rate[flavor];
1545 st->codec->block_align = track->audio.sub_packet_size;
1546 extradata_offset = 78;
1549 track->codec_priv.size -= extradata_offset;
1551 if (codec_id == CODEC_ID_NONE)
1552 av_log(matroska->ctx, AV_LOG_INFO,
1553 "Unknown/unsupported CodecID %s.\n", track->codec_id);
1555 if (track->time_scale < 0.01)
1556 track->time_scale = 1.0;
1557 av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1559 st->codec->codec_id = codec_id;
1561 if (strcmp(track->language, "und"))
1562 av_dict_set(&st->metadata, "language", track->language, 0);
1563 av_dict_set(&st->metadata, "title", track->name, 0);
1565 if (track->flag_default)
1566 st->disposition |= AV_DISPOSITION_DEFAULT;
1567 if (track->flag_forced)
1568 st->disposition |= AV_DISPOSITION_FORCED;
1570 if (track->default_duration)
1571 av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
1572 track->default_duration, 1000000000, 30000);
1574 if (!st->codec->extradata) {
1576 st->codec->extradata = extradata;
1577 st->codec->extradata_size = extradata_size;
1578 } else if(track->codec_priv.data && track->codec_priv.size > 0){
1579 st->codec->extradata = av_mallocz(track->codec_priv.size +
1580 FF_INPUT_BUFFER_PADDING_SIZE);
1581 if(st->codec->extradata == NULL)
1582 return AVERROR(ENOMEM);
1583 st->codec->extradata_size = track->codec_priv.size;
1584 memcpy(st->codec->extradata,
1585 track->codec_priv.data + extradata_offset,
1586 track->codec_priv.size);
1590 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1591 MatroskaTrackPlane *planes = track->operation.combine_planes.elem;
1593 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1594 st->codec->codec_tag = fourcc;
1595 st->codec->width = track->video.pixel_width;
1596 st->codec->height = track->video.pixel_height;
1597 av_reduce(&st->sample_aspect_ratio.num,
1598 &st->sample_aspect_ratio.den,
1599 st->codec->height * track->video.display_width,
1600 st->codec-> width * track->video.display_height,
1602 if (st->codec->codec_id != CODEC_ID_H264)
1603 st->need_parsing = AVSTREAM_PARSE_HEADERS;
1604 if (track->default_duration)
1605 st->avg_frame_rate = av_d2q(1000000000.0/track->default_duration, INT_MAX);
1607 /* export stereo mode flag as metadata tag */
1608 if (track->video.stereo_mode && track->video.stereo_mode < MATROSKA_VIDEO_STEREO_MODE_COUNT)
1609 av_dict_set(&st->metadata, "stereo_mode", matroska_video_stereo_mode[track->video.stereo_mode], 0);
1611 /* if we have virtual track, mark the real tracks */
1612 for (j=0; j < track->operation.combine_planes.nb_elem; j++) {
1614 if (planes[j].type >= MATROSKA_VIDEO_STEREO_PLANE_COUNT)
1616 snprintf(buf, sizeof(buf), "%s_%d",
1617 matroska_video_stereo_plane[planes[j].type], i);
1618 for (k=0; k < matroska->tracks.nb_elem; k++)
1619 if (planes[j].uid == tracks[k].uid) {
1620 av_dict_set(&s->streams[k]->metadata,
1621 "stereo_mode", buf, 0);
1625 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1626 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1627 st->codec->sample_rate = track->audio.out_samplerate;
1628 st->codec->channels = track->audio.channels;
1629 if (st->codec->codec_id != CODEC_ID_AAC)
1630 st->need_parsing = AVSTREAM_PARSE_HEADERS;
1631 } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1632 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1636 attachements = attachements_list->elem;
1637 for (j=0; j<attachements_list->nb_elem; j++) {
1638 if (!(attachements[j].filename && attachements[j].mime &&
1639 attachements[j].bin.data && attachements[j].bin.size > 0)) {
1640 av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1642 AVStream *st = avformat_new_stream(s, NULL);
1645 av_dict_set(&st->metadata, "filename",attachements[j].filename, 0);
1646 av_dict_set(&st->metadata, "mimetype", attachements[j].mime, 0);
1647 st->codec->codec_id = CODEC_ID_NONE;
1648 st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;
1649 st->codec->extradata = av_malloc(attachements[j].bin.size);
1650 if(st->codec->extradata == NULL)
1652 st->codec->extradata_size = attachements[j].bin.size;
1653 memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1655 for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1656 if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1657 strlen(ff_mkv_mime_tags[i].str))) {
1658 st->codec->codec_id = ff_mkv_mime_tags[i].id;
1662 attachements[j].stream = st;
1666 chapters = chapters_list->elem;
1667 for (i=0; i<chapters_list->nb_elem; i++)
1668 if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid
1669 && (max_start==0 || chapters[i].start > max_start)) {
1670 chapters[i].chapter =
1671 avpriv_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1672 chapters[i].start, chapters[i].end,
1674 av_dict_set(&chapters[i].chapter->metadata,
1675 "title", chapters[i].title, 0);
1676 max_start = chapters[i].start;
1679 matroska_add_index_entries(matroska);
1681 matroska_convert_tags(s);
1687 * Put one packet in an application-supplied AVPacket struct.
1688 * Returns 0 on success or -1 on failure.
1690 static int matroska_deliver_packet(MatroskaDemuxContext *matroska,
1693 if (matroska->num_packets > 0) {
1694 memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
1695 av_free(matroska->packets[0]);
1696 if (matroska->num_packets > 1) {
1698 memmove(&matroska->packets[0], &matroska->packets[1],
1699 (matroska->num_packets - 1) * sizeof(AVPacket *));
1700 newpackets = av_realloc(matroska->packets,
1701 (matroska->num_packets - 1) * sizeof(AVPacket *));
1703 matroska->packets = newpackets;
1705 av_freep(&matroska->packets);
1707 matroska->num_packets--;
1715 * Free all packets in our internal queue.
1717 static void matroska_clear_queue(MatroskaDemuxContext *matroska)
1719 if (matroska->packets) {
1721 for (n = 0; n < matroska->num_packets; n++) {
1722 av_free_packet(matroska->packets[n]);
1723 av_free(matroska->packets[n]);
1725 av_freep(&matroska->packets);
1726 matroska->num_packets = 0;
1730 static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,
1731 int size, int64_t pos, uint64_t cluster_time,
1732 uint64_t duration, int is_keyframe,
1733 int64_t cluster_pos)
1735 uint64_t timecode = AV_NOPTS_VALUE;
1736 MatroskaTrack *track;
1741 uint32_t *lace_size = NULL;
1742 int n, flags, laces = 0;
1745 if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {
1746 av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
1752 track = matroska_find_track_by_num(matroska, num);
1753 if (size <= 3 || !track || !track->stream) {
1754 av_log(matroska->ctx, AV_LOG_INFO,
1755 "Invalid stream %"PRIu64" or size %u\n", num, size);
1756 return AVERROR_INVALIDDATA;
1759 if (st->discard >= AVDISCARD_ALL)
1762 duration = track->default_duration / matroska->time_scale;
1764 block_time = AV_RB16(data);
1768 if (is_keyframe == -1)
1769 is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;
1771 if (cluster_time != (uint64_t)-1
1772 && (block_time >= 0 || cluster_time >= -block_time)) {
1773 timecode = cluster_time + block_time;
1774 if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE
1775 && timecode < track->end_timecode)
1776 is_keyframe = 0; /* overlapping subtitles are not key frame */
1778 av_add_index_entry(st, cluster_pos, timecode, 0,0,AVINDEX_KEYFRAME);
1779 track->end_timecode = FFMAX(track->end_timecode, timecode+duration);
1782 if (matroska->skip_to_keyframe && track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1783 if (!is_keyframe || timecode < matroska->skip_to_timecode)
1785 matroska->skip_to_keyframe = 0;
1788 switch ((flags & 0x06) >> 1) {
1789 case 0x0: /* no lacing */
1791 lace_size = av_mallocz(sizeof(int));
1792 lace_size[0] = size;
1795 case 0x1: /* Xiph lacing */
1796 case 0x2: /* fixed-size lacing */
1797 case 0x3: /* EBML lacing */
1798 assert(size>0); // size <=3 is checked before size-=3 above
1799 laces = (*data) + 1;
1802 lace_size = av_mallocz(laces * sizeof(int));
1804 switch ((flags & 0x06) >> 1) {
1805 case 0x1: /* Xiph lacing */ {
1808 for (n = 0; res == 0 && n < laces - 1; n++) {
1815 lace_size[n] += temp;
1821 total += lace_size[n];
1823 lace_size[n] = size - total;
1827 case 0x2: /* fixed-size lacing */
1828 for (n = 0; n < laces; n++)
1829 lace_size[n] = size / laces;
1832 case 0x3: /* EBML lacing */ {
1834 n = matroska_ebmlnum_uint(matroska, data, size, &num);
1836 av_log(matroska->ctx, AV_LOG_INFO,
1837 "EBML block data error\n");
1842 total = lace_size[0] = num;
1843 for (n = 1; res == 0 && n < laces - 1; n++) {
1846 r = matroska_ebmlnum_sint(matroska, data, size, &snum);
1848 av_log(matroska->ctx, AV_LOG_INFO,
1849 "EBML block data error\n");
1854 lace_size[n] = lace_size[n - 1] + snum;
1855 total += lace_size[n];
1857 lace_size[laces - 1] = size - total;
1865 for (n = 0; n < laces; n++) {
1866 if ((st->codec->codec_id == CODEC_ID_RA_288 ||
1867 st->codec->codec_id == CODEC_ID_COOK ||
1868 st->codec->codec_id == CODEC_ID_SIPR ||
1869 st->codec->codec_id == CODEC_ID_ATRAC3) &&
1870 st->codec->block_align && track->audio.sub_packet_size) {
1871 int a = st->codec->block_align;
1872 int sps = track->audio.sub_packet_size;
1873 int cfs = track->audio.coded_framesize;
1874 int h = track->audio.sub_packet_h;
1875 int y = track->audio.sub_packet_cnt;
1876 int w = track->audio.frame_size;
1879 if (!track->audio.pkt_cnt) {
1880 if (track->audio.sub_packet_cnt == 0)
1881 track->audio.buf_timecode = timecode;
1882 if (st->codec->codec_id == CODEC_ID_RA_288)
1883 for (x=0; x<h/2; x++)
1884 memcpy(track->audio.buf+x*2*w+y*cfs,
1886 else if (st->codec->codec_id == CODEC_ID_SIPR)
1887 memcpy(track->audio.buf + y*w, data, w);
1889 for (x=0; x<w/sps; x++)
1890 memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1892 if (++track->audio.sub_packet_cnt >= h) {
1893 if (st->codec->codec_id == CODEC_ID_SIPR)
1894 ff_rm_reorder_sipr_data(track->audio.buf, h, w);
1895 track->audio.sub_packet_cnt = 0;
1896 track->audio.pkt_cnt = h*w / a;
1899 while (track->audio.pkt_cnt) {
1900 pkt = av_mallocz(sizeof(AVPacket));
1901 av_new_packet(pkt, a);
1902 memcpy(pkt->data, track->audio.buf
1903 + a * (h*w / a - track->audio.pkt_cnt--), a);
1904 pkt->pts = track->audio.buf_timecode;
1905 track->audio.buf_timecode = AV_NOPTS_VALUE;
1907 pkt->stream_index = st->index;
1908 dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1911 MatroskaTrackEncoding *encodings = track->encodings.elem;
1912 int offset = 0, pkt_size = lace_size[n];
1913 uint8_t *pkt_data = data;
1915 if (pkt_size > size) {
1916 av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");
1920 if (encodings && encodings->scope & 1) {
1921 offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
1926 pkt = av_mallocz(sizeof(AVPacket));
1927 /* XXX: prevent data copy... */
1928 if (av_new_packet(pkt, pkt_size+offset) < 0) {
1930 res = AVERROR(ENOMEM);
1934 memcpy (pkt->data, encodings->compression.settings.data, offset);
1935 memcpy (pkt->data+offset, pkt_data, pkt_size);
1937 if (pkt_data != data)
1941 pkt->flags = is_keyframe;
1942 pkt->stream_index = st->index;
1944 if (track->ms_compat)
1945 pkt->dts = timecode;
1947 pkt->pts = timecode;
1949 if (st->codec->codec_id == CODEC_ID_TEXT)
1950 pkt->convergence_duration = duration;
1951 else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)
1952 pkt->duration = duration;
1954 if (st->codec->codec_id == CODEC_ID_SSA)
1955 matroska_fix_ass_packet(matroska, pkt, duration);
1957 if (matroska->prev_pkt &&
1958 timecode != AV_NOPTS_VALUE &&
1959 matroska->prev_pkt->pts == timecode &&
1960 matroska->prev_pkt->stream_index == st->index &&
1961 st->codec->codec_id == CODEC_ID_SSA)
1962 matroska_merge_packets(matroska->prev_pkt, pkt);
1964 dynarray_add(&matroska->packets,&matroska->num_packets,pkt);
1965 matroska->prev_pkt = pkt;
1969 if (timecode != AV_NOPTS_VALUE)
1970 timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
1971 data += lace_size[n];
1972 size -= lace_size[n];
1980 static int matroska_parse_cluster(MatroskaDemuxContext *matroska)
1982 MatroskaCluster cluster = { 0 };
1983 EbmlList *blocks_list;
1984 MatroskaBlock *blocks;
1986 int64_t pos = avio_tell(matroska->ctx->pb);
1987 matroska->prev_pkt = NULL;
1988 if (matroska->current_id)
1989 pos -= 4; /* sizeof the ID which was already read */
1990 res = ebml_parse(matroska, matroska_clusters, &cluster);
1991 blocks_list = &cluster.blocks;
1992 blocks = blocks_list->elem;
1993 for (i=0; i<blocks_list->nb_elem && !res; i++)
1994 if (blocks[i].bin.size > 0 && blocks[i].bin.data) {
1995 int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;
1996 res=matroska_parse_block(matroska,
1997 blocks[i].bin.data, blocks[i].bin.size,
1998 blocks[i].bin.pos, cluster.timecode,
1999 blocks[i].duration, is_keyframe,
2002 ebml_free(matroska_cluster, &cluster);
2003 if (res < 0) matroska->done = 1;
2007 static int matroska_read_packet(AVFormatContext *s, AVPacket *pkt)
2009 MatroskaDemuxContext *matroska = s->priv_data;
2012 while (!ret && matroska_deliver_packet(matroska, pkt)) {
2015 ret = matroska_parse_cluster(matroska);
2021 static int matroska_read_seek(AVFormatContext *s, int stream_index,
2022 int64_t timestamp, int flags)
2024 MatroskaDemuxContext *matroska = s->priv_data;
2025 MatroskaTrack *tracks = matroska->tracks.elem;
2026 AVStream *st = s->streams[stream_index];
2027 int i, index, index_sub, index_min;
2029 /* Parse the CUES now since we need the index data to seek. */
2030 if (matroska->cues_parsing_deferred) {
2031 matroska_parse_cues(matroska);
2032 matroska->cues_parsing_deferred = 0;
2035 if (!st->nb_index_entries)
2037 timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);
2039 if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2040 avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);
2041 matroska->current_id = 0;
2042 while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {
2043 matroska_clear_queue(matroska);
2044 if (matroska_parse_cluster(matroska) < 0)
2049 matroska_clear_queue(matroska);
2054 for (i=0; i < matroska->tracks.nb_elem; i++) {
2055 tracks[i].audio.pkt_cnt = 0;
2056 tracks[i].audio.sub_packet_cnt = 0;
2057 tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;
2058 tracks[i].end_timecode = 0;
2059 if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE
2060 && !tracks[i].stream->discard != AVDISCARD_ALL) {
2061 index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);
2063 && st->index_entries[index_sub].pos < st->index_entries[index_min].pos
2064 && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)
2065 index_min = index_sub;
2069 avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);
2070 matroska->current_id = 0;
2071 matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
2072 matroska->skip_to_timecode = st->index_entries[index].timestamp;
2074 ff_update_cur_dts(s, st, st->index_entries[index].timestamp);
2078 static int matroska_read_close(AVFormatContext *s)
2080 MatroskaDemuxContext *matroska = s->priv_data;
2081 MatroskaTrack *tracks = matroska->tracks.elem;
2084 matroska_clear_queue(matroska);
2086 for (n=0; n < matroska->tracks.nb_elem; n++)
2087 if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
2088 av_free(tracks[n].audio.buf);
2089 ebml_free(matroska_segment, matroska);
2094 AVInputFormat ff_matroska_demuxer = {
2095 .name = "matroska,webm",
2096 .long_name = NULL_IF_CONFIG_SMALL("Matroska/WebM file format"),
2097 .priv_data_size = sizeof(MatroskaDemuxContext),
2098 .read_probe = matroska_probe,
2099 .read_header = matroska_read_header,
2100 .read_packet = matroska_read_packet,
2101 .read_close = matroska_read_close,
2102 .read_seek = matroska_read_seek,