2 * Matroska file demuxer (no muxer yet)
3 * Copyright (c) 2003-2004 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 * Specs available on the matroska project page:
28 * http://www.matroska.org/.
32 /* For codec_get_id(). */
36 #include "libavcodec/mpeg4audio.h"
37 #include "libavutil/intfloat_readwrite.h"
38 #include "libavutil/avstring.h"
39 #include "libavutil/lzo.h"
59 typedef const struct EbmlSyntax {
68 const struct EbmlSyntax *n;
88 uint64_t doctype_version;
94 } MatroskaTrackCompression;
99 MatroskaTrackCompression compression;
100 } MatroskaTrackEncoding;
104 uint64_t display_width;
105 uint64_t display_height;
106 uint64_t pixel_width;
107 uint64_t pixel_height;
109 } MatroskaTrackVideo;
113 double out_samplerate;
117 /* real audio header (extracted from extradata) */
125 } MatroskaTrackAudio;
134 uint64_t default_duration;
135 uint64_t flag_default;
136 MatroskaTrackVideo video;
137 MatroskaTrackAudio audio;
147 } MatroskaAttachement;
177 AVFormatContext *ctx;
181 MatroskaLevel levels[EBML_MAX_DEPTH];
188 EbmlList attachments;
193 /* num_streams is the number of streams that av_new_stream() was called
194 * for ( = that are available to the calling program). */
197 /* cache for ID peeking */
200 /* byte position of the segment inside the stream */
201 offset_t segment_start;
203 /* The packet queue. */
210 /* What to skip before effectively reading a packet. */
211 int skip_to_keyframe;
212 AVStream *skip_to_stream;
213 } MatroskaDemuxContext;
226 #define ARRAY_SIZE(x) (sizeof(x)/sizeof(*x))
228 static EbmlSyntax ebml_header[] = {
229 { EBML_ID_EBMLREADVERSION, EBML_UINT, 0, offsetof(Ebml,version), {.u=EBML_VERSION} },
230 { EBML_ID_EBMLMAXSIZELENGTH, EBML_UINT, 0, offsetof(Ebml,max_size), {.u=8} },
231 { EBML_ID_EBMLMAXIDLENGTH, EBML_UINT, 0, offsetof(Ebml,id_length), {.u=4} },
232 { EBML_ID_DOCTYPE, EBML_STR, 0, offsetof(Ebml,doctype), {.s="(none)"} },
233 { EBML_ID_DOCTYPEREADVERSION, EBML_UINT, 0, offsetof(Ebml,doctype_version), {.u=1} },
234 { EBML_ID_EBMLVERSION, EBML_NONE },
235 { EBML_ID_DOCTYPEVERSION, EBML_NONE },
236 { EBML_ID_VOID, EBML_NONE },
240 static EbmlSyntax ebml_syntax[] = {
241 { EBML_ID_HEADER, EBML_NEST, 0, 0, {.n=ebml_header} },
245 static EbmlSyntax matroska_info[] = {
246 { MATROSKA_ID_TIMECODESCALE, EBML_UINT, 0, offsetof(MatroskaDemuxContext,time_scale), {.u=1000000} },
247 { MATROSKA_ID_DURATION, EBML_FLOAT, 0, offsetof(MatroskaDemuxContext,duration) },
248 { MATROSKA_ID_TITLE, EBML_UTF8, 0, offsetof(MatroskaDemuxContext,title) },
249 { MATROSKA_ID_WRITINGAPP, EBML_NONE },
250 { MATROSKA_ID_MUXINGAPP, EBML_NONE },
251 { MATROSKA_ID_DATEUTC, EBML_NONE },
252 { MATROSKA_ID_SEGMENTUID, EBML_NONE },
253 { EBML_ID_VOID, EBML_NONE },
257 static EbmlSyntax matroska_track_video[] = {
258 { MATROSKA_ID_VIDEOFRAMERATE, EBML_FLOAT,0, offsetof(MatroskaTrackVideo,frame_rate) },
259 { MATROSKA_ID_VIDEODISPLAYWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_width) },
260 { MATROSKA_ID_VIDEODISPLAYHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,display_height) },
261 { MATROSKA_ID_VIDEOPIXELWIDTH, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_width) },
262 { MATROSKA_ID_VIDEOPIXELHEIGHT, EBML_UINT, 0, offsetof(MatroskaTrackVideo,pixel_height) },
263 { MATROSKA_ID_VIDEOCOLORSPACE, EBML_UINT, 0, offsetof(MatroskaTrackVideo,fourcc) },
264 { MATROSKA_ID_VIDEOFLAGINTERLACED,EBML_NONE },
265 { MATROSKA_ID_VIDEOSTEREOMODE, EBML_NONE },
266 { MATROSKA_ID_VIDEOASPECTRATIO, EBML_NONE },
267 { EBML_ID_VOID, EBML_NONE },
271 static EbmlSyntax matroska_track_audio[] = {
272 { MATROSKA_ID_AUDIOSAMPLINGFREQ, EBML_FLOAT,0, offsetof(MatroskaTrackAudio,samplerate), {.f=8000.0} },
273 { MATROSKA_ID_AUDIOOUTSAMPLINGFREQ,EBML_FLOAT,0,offsetof(MatroskaTrackAudio,out_samplerate) },
274 { MATROSKA_ID_AUDIOBITDEPTH, EBML_UINT, 0, offsetof(MatroskaTrackAudio,bitdepth) },
275 { MATROSKA_ID_AUDIOCHANNELS, EBML_UINT, 0, offsetof(MatroskaTrackAudio,channels), {.u=1} },
276 { EBML_ID_VOID, EBML_NONE },
280 static EbmlSyntax matroska_track_encoding_compression[] = {
281 { MATROSKA_ID_ENCODINGCOMPALGO, EBML_UINT, 0, offsetof(MatroskaTrackCompression,algo), {.u=0} },
282 { MATROSKA_ID_ENCODINGCOMPSETTINGS,EBML_BIN, 0, offsetof(MatroskaTrackCompression,settings) },
283 { EBML_ID_VOID, EBML_NONE },
287 static EbmlSyntax matroska_track_encoding[] = {
288 { MATROSKA_ID_ENCODINGSCOPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,scope), {.u=1} },
289 { MATROSKA_ID_ENCODINGTYPE, EBML_UINT, 0, offsetof(MatroskaTrackEncoding,type), {.u=0} },
290 { MATROSKA_ID_ENCODINGCOMPRESSION,EBML_NEST, 0, offsetof(MatroskaTrackEncoding,compression), {.n=matroska_track_encoding_compression} },
291 { EBML_ID_VOID, EBML_NONE },
295 static EbmlSyntax matroska_track_encodings[] = {
296 { MATROSKA_ID_TRACKCONTENTENCODING, EBML_NEST, sizeof(MatroskaTrackEncoding), offsetof(MatroskaTrack,encodings), {.n=matroska_track_encoding} },
297 { EBML_ID_VOID, EBML_NONE },
301 static EbmlSyntax matroska_track[] = {
302 { MATROSKA_ID_TRACKNUMBER, EBML_UINT, 0, offsetof(MatroskaTrack,num) },
303 { MATROSKA_ID_TRACKTYPE, EBML_UINT, 0, offsetof(MatroskaTrack,type) },
304 { MATROSKA_ID_CODECID, EBML_STR, 0, offsetof(MatroskaTrack,codec_id) },
305 { MATROSKA_ID_CODECPRIVATE, EBML_BIN, 0, offsetof(MatroskaTrack,codec_priv) },
306 { MATROSKA_ID_TRACKLANGUAGE, EBML_UTF8, 0, offsetof(MatroskaTrack,language), {.s="eng"} },
307 { MATROSKA_ID_TRACKDEFAULTDURATION, EBML_UINT, 0, offsetof(MatroskaTrack,default_duration) },
308 { MATROSKA_ID_TRACKTIMECODESCALE, EBML_FLOAT,0, offsetof(MatroskaTrack,time_scale), {.f=1.0} },
309 { MATROSKA_ID_TRACKFLAGDEFAULT, EBML_UINT, 0, offsetof(MatroskaTrack,flag_default), {.u=1} },
310 { MATROSKA_ID_TRACKVIDEO, EBML_NEST, 0, offsetof(MatroskaTrack,video), {.n=matroska_track_video} },
311 { MATROSKA_ID_TRACKAUDIO, EBML_NEST, 0, offsetof(MatroskaTrack,audio), {.n=matroska_track_audio} },
312 { MATROSKA_ID_TRACKCONTENTENCODINGS,EBML_NEST, 0, 0, {.n=matroska_track_encodings} },
313 { MATROSKA_ID_TRACKUID, EBML_NONE },
314 { MATROSKA_ID_TRACKNAME, EBML_NONE },
315 { MATROSKA_ID_TRACKFLAGENABLED, EBML_NONE },
316 { MATROSKA_ID_TRACKFLAGFORCED, EBML_NONE },
317 { MATROSKA_ID_TRACKFLAGLACING, EBML_NONE },
318 { MATROSKA_ID_CODECNAME, EBML_NONE },
319 { MATROSKA_ID_CODECDECODEALL, EBML_NONE },
320 { MATROSKA_ID_CODECINFOURL, EBML_NONE },
321 { MATROSKA_ID_CODECDOWNLOADURL, EBML_NONE },
322 { MATROSKA_ID_TRACKMINCACHE, EBML_NONE },
323 { MATROSKA_ID_TRACKMAXCACHE, EBML_NONE },
324 { EBML_ID_VOID, EBML_NONE },
328 static EbmlSyntax matroska_tracks[] = {
329 { MATROSKA_ID_TRACKENTRY, EBML_NEST, sizeof(MatroskaTrack), offsetof(MatroskaDemuxContext,tracks), {.n=matroska_track} },
330 { EBML_ID_VOID, EBML_NONE },
334 static EbmlSyntax matroska_attachment[] = {
335 { MATROSKA_ID_FILENAME, EBML_UTF8, 0, offsetof(MatroskaAttachement,filename) },
336 { MATROSKA_ID_FILEMIMETYPE, EBML_STR, 0, offsetof(MatroskaAttachement,mime) },
337 { MATROSKA_ID_FILEDATA, EBML_BIN, 0, offsetof(MatroskaAttachement,bin) },
338 { MATROSKA_ID_FILEUID, EBML_NONE },
339 { EBML_ID_VOID, EBML_NONE },
343 static EbmlSyntax matroska_attachments[] = {
344 { MATROSKA_ID_ATTACHEDFILE, EBML_NEST, sizeof(MatroskaAttachement), offsetof(MatroskaDemuxContext,attachments), {.n=matroska_attachment} },
345 { EBML_ID_VOID, EBML_NONE },
349 static EbmlSyntax matroska_chapter_display[] = {
350 { MATROSKA_ID_CHAPSTRING, EBML_UTF8, 0, offsetof(MatroskaChapter,title) },
351 { EBML_ID_VOID, EBML_NONE },
355 static EbmlSyntax matroska_chapter_entry[] = {
356 { MATROSKA_ID_CHAPTERTIMESTART, EBML_UINT, 0, offsetof(MatroskaChapter,start), {.u=AV_NOPTS_VALUE} },
357 { MATROSKA_ID_CHAPTERTIMEEND, EBML_UINT, 0, offsetof(MatroskaChapter,end), {.u=AV_NOPTS_VALUE} },
358 { MATROSKA_ID_CHAPTERUID, EBML_UINT, 0, offsetof(MatroskaChapter,uid) },
359 { MATROSKA_ID_CHAPTERDISPLAY, EBML_NEST, 0, 0, {.n=matroska_chapter_display} },
360 { MATROSKA_ID_CHAPTERFLAGHIDDEN, EBML_NONE },
361 { EBML_ID_VOID, EBML_NONE },
365 static EbmlSyntax matroska_chapter[] = {
366 { MATROSKA_ID_CHAPTERATOM, EBML_NEST, sizeof(MatroskaChapter), offsetof(MatroskaDemuxContext,chapters), {.n=matroska_chapter_entry} },
367 { MATROSKA_ID_EDITIONUID, EBML_NONE },
368 { MATROSKA_ID_EDITIONFLAGHIDDEN, EBML_NONE },
369 { MATROSKA_ID_EDITIONFLAGDEFAULT, EBML_NONE },
370 { EBML_ID_VOID, EBML_NONE },
374 static EbmlSyntax matroska_chapters[] = {
375 { MATROSKA_ID_EDITIONENTRY, EBML_NEST, 0, 0, {.n=matroska_chapter} },
376 { EBML_ID_VOID, EBML_NONE },
380 static EbmlSyntax matroska_index_pos[] = {
381 { MATROSKA_ID_CUETRACK, EBML_UINT, 0, offsetof(MatroskaIndexPos,track) },
382 { MATROSKA_ID_CUECLUSTERPOSITION, EBML_UINT, 0, offsetof(MatroskaIndexPos,pos) },
383 { EBML_ID_VOID, EBML_NONE },
387 static EbmlSyntax matroska_index_entry[] = {
388 { MATROSKA_ID_CUETIME, EBML_UINT, 0, offsetof(MatroskaIndex,time) },
389 { MATROSKA_ID_CUETRACKPOSITION, EBML_NEST, sizeof(MatroskaIndexPos), offsetof(MatroskaIndex,pos), {.n=matroska_index_pos} },
390 { EBML_ID_VOID, EBML_NONE },
394 static EbmlSyntax matroska_index[] = {
395 { MATROSKA_ID_POINTENTRY, EBML_NEST, sizeof(MatroskaIndex), offsetof(MatroskaDemuxContext,index), {.n=matroska_index_entry} },
396 { EBML_ID_VOID, EBML_NONE },
400 static EbmlSyntax matroska_tags[] = {
401 { EBML_ID_VOID, EBML_NONE },
405 static EbmlSyntax matroska_seekhead_entry[] = {
406 { MATROSKA_ID_SEEKID, EBML_UINT, 0, offsetof(MatroskaSeekhead,id) },
407 { MATROSKA_ID_SEEKPOSITION, EBML_UINT, 0, offsetof(MatroskaSeekhead,pos), {.u=-1} },
408 { EBML_ID_VOID, EBML_NONE },
412 static EbmlSyntax matroska_seekhead[] = {
413 { MATROSKA_ID_SEEKENTRY, EBML_NEST, sizeof(MatroskaSeekhead), offsetof(MatroskaDemuxContext,seekhead), {.n=matroska_seekhead_entry} },
414 { EBML_ID_VOID, EBML_NONE },
418 static EbmlSyntax matroska_segment[] = {
419 { MATROSKA_ID_INFO, EBML_NEST, 0, 0, {.n=matroska_info } },
420 { MATROSKA_ID_TRACKS, EBML_NEST, 0, 0, {.n=matroska_tracks } },
421 { MATROSKA_ID_ATTACHMENTS, EBML_NEST, 0, 0, {.n=matroska_attachments} },
422 { MATROSKA_ID_CHAPTERS, EBML_NEST, 0, 0, {.n=matroska_chapters } },
423 { MATROSKA_ID_CUES, EBML_NEST, 0, 0, {.n=matroska_index } },
424 { MATROSKA_ID_TAGS, EBML_NEST, 0, 0, {.n=matroska_tags } },
425 { MATROSKA_ID_SEEKHEAD, EBML_NEST, 0, 0, {.n=matroska_seekhead } },
426 { MATROSKA_ID_CLUSTER, EBML_STOP, 0, offsetof(MatroskaDemuxContext,has_cluster_id) },
427 { EBML_ID_VOID, EBML_NONE },
431 static EbmlSyntax matroska_segments[] = {
432 { MATROSKA_ID_SEGMENT, EBML_NEST, 0, 0, {.n=matroska_segment } },
436 static EbmlSyntax matroska_blockgroup[] = {
437 { MATROSKA_ID_BLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
438 { MATROSKA_ID_SIMPLEBLOCK, EBML_BIN, 0, offsetof(MatroskaBlock,bin) },
439 { MATROSKA_ID_BLOCKDURATION, EBML_UINT, 0, offsetof(MatroskaBlock,duration), {.u=AV_NOPTS_VALUE} },
440 { MATROSKA_ID_BLOCKREFERENCE, EBML_UINT, 0, offsetof(MatroskaBlock,reference) },
441 { EBML_ID_VOID, EBML_NONE },
445 static EbmlSyntax matroska_cluster[] = {
446 { MATROSKA_ID_CLUSTERTIMECODE,EBML_UINT,0, offsetof(MatroskaCluster,timecode) },
447 { MATROSKA_ID_BLOCKGROUP, EBML_NEST, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
448 { MATROSKA_ID_SIMPLEBLOCK, EBML_PASS, sizeof(MatroskaBlock), offsetof(MatroskaCluster,blocks), {.n=matroska_blockgroup} },
449 { EBML_ID_VOID, EBML_NONE },
453 static EbmlSyntax matroska_clusters[] = {
454 { MATROSKA_ID_CLUSTER, EBML_NEST, 0, 0, {.n=matroska_cluster} },
459 * Return: the amount of levels in the hierarchy that the
460 * current element lies higher than the previous one.
461 * The opposite isn't done - that's auto-done using master
465 ebml_read_element_level_up (MatroskaDemuxContext *matroska)
467 ByteIOContext *pb = matroska->ctx->pb;
468 offset_t pos = url_ftell(pb);
471 while (matroska->num_levels > 0) {
472 MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
474 if (pos >= level->start + level->length) {
475 matroska->num_levels--;
486 * Read: an "EBML number", which is defined as a variable-length
487 * array of bytes. The first byte indicates the length by giving a
488 * number of 0-bits followed by a one. The position of the first
489 * "one" bit inside the first byte indicates the length of this
491 * Returns: num. of bytes read. < 0 on error.
494 ebml_read_num (MatroskaDemuxContext *matroska,
498 ByteIOContext *pb = matroska->ctx->pb;
499 int len_mask = 0x80, read = 1, n = 1;
502 /* the first byte tells us the length in bytes - get_byte() can normally
503 * return 0, but since that's not a valid first ebmlID byte, we can
504 * use it safely here to catch EOS. */
505 if (!(total = get_byte(pb))) {
506 /* we might encounter EOS here */
508 offset_t pos = url_ftell(pb);
509 av_log(matroska->ctx, AV_LOG_ERROR,
510 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
513 return AVERROR(EIO); /* EOS or actual I/O error */
516 /* get the length of the EBML number */
517 while (read <= max_size && !(total & len_mask)) {
521 if (read > max_size) {
522 offset_t pos = url_ftell(pb) - 1;
523 av_log(matroska->ctx, AV_LOG_ERROR,
524 "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
525 (uint8_t) total, pos, pos);
526 return AVERROR_INVALIDDATA;
529 /* read out length */
532 total = (total << 8) | get_byte(pb);
540 * Read: the element content data ID.
541 * Return: the number of bytes read or < 0 on error.
544 ebml_read_element_id (MatroskaDemuxContext *matroska,
550 /* if we re-call this, use our cached ID */
551 if (matroska->peek_id != 0) {
552 *id = matroska->peek_id;
556 /* read out the "EBML number", include tag in ID */
557 if ((read = ebml_read_num(matroska, 4, &total)) < 0)
559 *id = matroska->peek_id = total | (1 << (read * 7));
565 * Read: element content length.
566 * Return: the number of bytes read or < 0 on error.
569 ebml_read_element_length (MatroskaDemuxContext *matroska,
572 /* clear cache since we're now beyond that data point */
573 matroska->peek_id = 0;
575 /* read out the "EBML number", include tag in ID */
576 return ebml_read_num(matroska, 8, length);
580 * Seek to a given offset.
581 * 0 is success, -1 is failure.
584 ebml_read_seek (MatroskaDemuxContext *matroska,
587 ByteIOContext *pb = matroska->ctx->pb;
589 /* clear ID cache, if any */
590 matroska->peek_id = 0;
592 return (url_fseek(pb, offset, SEEK_SET) == offset) ? 0 : -1;
596 * Skip the next element.
597 * 0 is success, -1 is failure.
600 ebml_read_skip (MatroskaDemuxContext *matroska)
602 ByteIOContext *pb = matroska->ctx->pb;
607 if ((res = ebml_read_element_id(matroska, &id)) < 0 ||
608 (res = ebml_read_element_length(matroska, &length)) < 0)
611 url_fskip(pb, length);
617 * Read the next element as an unsigned int.
618 * 0 is success, < 0 is failure.
621 ebml_read_uint (MatroskaDemuxContext *matroska,
625 ByteIOContext *pb = matroska->ctx->pb;
626 int n = 0, size, res;
629 if ((res = ebml_read_element_id(matroska, id)) < 0 ||
630 (res = ebml_read_element_length(matroska, &rlength)) < 0)
633 if (size < 1 || size > 8) {
634 offset_t pos = url_ftell(pb);
635 av_log(matroska->ctx, AV_LOG_ERROR,
636 "Invalid uint element size %d at position %"PRId64" (0x%"PRIx64")\n",
638 return AVERROR_INVALIDDATA;
641 /* big-endian ordening; build up number */
644 *num = (*num << 8) | get_byte(pb);
650 * Read the next element as a float.
651 * 0 is success, < 0 is failure.
654 ebml_read_float (MatroskaDemuxContext *matroska,
658 ByteIOContext *pb = matroska->ctx->pb;
662 if ((res = ebml_read_element_id(matroska, id)) < 0 ||
663 (res = ebml_read_element_length(matroska, &rlength)) < 0)
668 *num= av_int2flt(get_be32(pb));
670 *num= av_int2dbl(get_be64(pb));
672 offset_t pos = url_ftell(pb);
673 av_log(matroska->ctx, AV_LOG_ERROR,
674 "Invalid float element size %d at position %"PRIu64" (0x%"PRIx64")\n",
676 return AVERROR_INVALIDDATA;
683 * Read the next element as an ASCII string.
684 * 0 is success, < 0 is failure.
687 ebml_read_ascii (MatroskaDemuxContext *matroska,
691 ByteIOContext *pb = matroska->ctx->pb;
695 if ((res = ebml_read_element_id(matroska, id)) < 0 ||
696 (res = ebml_read_element_length(matroska, &rlength)) < 0)
700 /* ebml strings are usually not 0-terminated, so we allocate one
701 * byte more, read the string and NULL-terminate it ourselves. */
702 if (size < 0 || !(*str = av_malloc(size + 1))) {
703 av_log(matroska->ctx, AV_LOG_ERROR, "Memory allocation failed\n");
704 return AVERROR(ENOMEM);
706 if (get_buffer(pb, (uint8_t *) *str, size) != size) {
707 offset_t pos = url_ftell(pb);
708 av_log(matroska->ctx, AV_LOG_ERROR,
709 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
719 * Read the next element, but only the header. The contents
720 * are supposed to be sub-elements which can be read separately.
721 * 0 is success, < 0 is failure.
724 ebml_read_master (MatroskaDemuxContext *matroska,
727 ByteIOContext *pb = matroska->ctx->pb;
729 MatroskaLevel *level;
732 if ((res = ebml_read_element_id(matroska, id)) < 0 ||
733 (res = ebml_read_element_length(matroska, &length)) < 0)
736 if (matroska->num_levels >= EBML_MAX_DEPTH) {
737 av_log(matroska->ctx, AV_LOG_ERROR,
738 "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
739 return AVERROR(ENOSYS);
742 level = &matroska->levels[matroska->num_levels++];
743 level->start = url_ftell(pb);
744 level->length = length;
750 * Read the next element as binary data.
751 * 0 is success, < 0 is failure.
754 ebml_read_binary (MatroskaDemuxContext *matroska,
759 ByteIOContext *pb = matroska->ctx->pb;
763 if ((res = ebml_read_element_id(matroska, id)) < 0 ||
764 (res = ebml_read_element_length(matroska, &rlength)) < 0)
768 if (!(*binary = av_malloc(*size))) {
769 av_log(matroska->ctx, AV_LOG_ERROR,
770 "Memory allocation error\n");
771 return AVERROR(ENOMEM);
774 if (get_buffer(pb, *binary, *size) != *size) {
775 offset_t pos = url_ftell(pb);
776 av_log(matroska->ctx, AV_LOG_ERROR,
777 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
785 * Read signed/unsigned "EBML" numbers.
786 * Return: number of bytes processed, < 0 on error.
787 * XXX: use ebml_read_num().
790 matroska_ebmlnum_uint (uint8_t *data,
794 int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
798 return AVERROR_INVALIDDATA;
801 while (read <= 8 && !(total & len_mask)) {
806 return AVERROR_INVALIDDATA;
808 if ((total &= (len_mask - 1)) == len_mask - 1)
811 return AVERROR_INVALIDDATA;
815 total = (total << 8) | data[n];
828 * Same as above, but signed.
831 matroska_ebmlnum_sint (uint8_t *data,
838 /* read as unsigned number first */
839 if ((res = matroska_ebmlnum_uint(data, size, &unum)) < 0)
842 /* make signed (weird way) */
843 if (unum == (uint64_t)-1)
846 *num = unum - ((1LL << ((7 * res) - 1)) - 1);
852 static MatroskaTrack *
853 matroska_find_track_by_num (MatroskaDemuxContext *matroska,
856 MatroskaTrack *tracks = matroska->tracks.elem;
859 for (i=0; i < matroska->tracks.nb_elem; i++)
860 if (tracks[i].num == num)
863 av_log(matroska->ctx, AV_LOG_ERROR, "Invalid track number %d\n", num);
869 * Put one packet in an application-supplied AVPacket struct.
870 * Returns 0 on success or -1 on failure.
873 matroska_deliver_packet (MatroskaDemuxContext *matroska,
876 if (matroska->num_packets > 0) {
877 memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
878 av_free(matroska->packets[0]);
879 if (matroska->num_packets > 1) {
880 memmove(&matroska->packets[0], &matroska->packets[1],
881 (matroska->num_packets - 1) * sizeof(AVPacket *));
883 av_realloc(matroska->packets, (matroska->num_packets - 1) *
886 av_freep(&matroska->packets);
888 matroska->num_packets--;
896 * Put a packet into our internal queue. Will be delivered to the
897 * user/application during the next get_packet() call.
900 matroska_queue_packet (MatroskaDemuxContext *matroska,
904 av_realloc(matroska->packets, (matroska->num_packets + 1) *
906 matroska->packets[matroska->num_packets] = pkt;
907 matroska->num_packets++;
911 * Free all packets in our internal queue.
914 matroska_clear_queue (MatroskaDemuxContext *matroska)
916 if (matroska->packets) {
918 for (n = 0; n < matroska->num_packets; n++) {
919 av_free_packet(matroska->packets[n]);
920 av_free(matroska->packets[n]);
922 av_free(matroska->packets);
923 matroska->packets = NULL;
924 matroska->num_packets = 0;
933 matroska_probe (AVProbeData *p)
936 int len_mask = 0x80, size = 1, n = 1;
937 uint8_t probe_data[] = { 'm', 'a', 't', 'r', 'o', 's', 'k', 'a' };
940 if (AV_RB32(p->buf) != EBML_ID_HEADER)
943 /* length of header */
945 while (size <= 8 && !(total & len_mask)) {
951 total &= (len_mask - 1);
953 total = (total << 8) | p->buf[4 + n++];
955 /* does the probe data contain the whole header? */
956 if (p->buf_size < 4 + size + total)
959 /* the header must contain the document type 'matroska'. For now,
960 * we don't parse the whole header but simply check for the
961 * availability of that array of characters inside the header.
962 * Not fully fool-proof, but good enough. */
963 for (n = 4 + size; n <= 4 + size + total - sizeof(probe_data); n++)
964 if (!memcmp (&p->buf[n], probe_data, sizeof(probe_data)))
965 return AVPROBE_SCORE_MAX;
970 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
971 void *data, uint32_t expected_id, int once);
973 static int ebml_parse_elem(MatroskaDemuxContext *matroska,
974 EbmlSyntax *syntax, void *data)
976 uint32_t id = syntax->id;
980 data = (char *)data + syntax->data_offset;
981 if (syntax->list_elem_size) {
982 EbmlList *list = data;
983 list->elem = av_realloc(list->elem, (list->nb_elem+1)*syntax->list_elem_size);
984 data = (char*)list->elem + list->nb_elem*syntax->list_elem_size;
985 memset(data, 0, syntax->list_elem_size);
990 switch (syntax->type) {
991 case EBML_UINT: return ebml_read_uint (matroska, &id, data);
992 case EBML_FLOAT: return ebml_read_float(matroska, &id, data);
994 case EBML_UTF8: av_free(*(char **)data);
995 return ebml_read_ascii(matroska, &id, data);
996 case EBML_BIN: av_free(bin->data);
997 bin->pos = url_ftell(matroska->ctx->pb);
998 return ebml_read_binary(matroska, &id, &bin->data,
1000 case EBML_NEST: if ((res=ebml_read_master(matroska, &id)) < 0)
1002 if (id == MATROSKA_ID_SEGMENT)
1003 matroska->segment_start = url_ftell(matroska->ctx->pb);
1004 return ebml_parse(matroska, syntax->def.n, data, 0, 0);
1005 case EBML_PASS: return ebml_parse(matroska, syntax->def.n, data, 0, 1);
1006 case EBML_STOP: *(int *)data = 1; return 1;
1007 default: return ebml_read_skip(matroska);
1011 static int ebml_parse_id(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
1012 uint32_t id, void *data)
1015 for (i=0; syntax[i].id; i++)
1016 if (id == syntax[i].id)
1019 av_log(matroska->ctx, AV_LOG_INFO, "Unknown entry 0x%X\n", id);
1020 return ebml_parse_elem(matroska, &syntax[i], data);
1023 static int ebml_parse(MatroskaDemuxContext *matroska, EbmlSyntax *syntax,
1024 void *data, uint32_t expected_id, int once)
1026 int i, res = 0, res2;
1029 for (i=0; syntax[i].id; i++)
1030 switch (syntax[i].type) {
1032 *(uint64_t *)((char *)data+syntax[i].data_offset) = syntax[i].def.u;
1035 *(double *)((char *)data+syntax[i].data_offset) = syntax[i].def.f;
1039 *(char **)((char *)data+syntax[i].data_offset) = av_strdup(syntax[i].def.s);
1044 res = ebml_read_master(matroska, &id);
1045 if (id != expected_id)
1046 return AVERROR_INVALIDDATA;
1047 if (id == MATROSKA_ID_SEGMENT)
1048 matroska->segment_start = url_ftell(matroska->ctx->pb);
1052 res2 = ebml_read_element_id(matroska, &id);
1056 matroska->level_up = ebml_read_element_level_up(matroska);
1057 if (matroska->level_up) {
1058 matroska->level_up--;
1062 res = ebml_parse_id(matroska, syntax, id, data);
1070 static void ebml_free(EbmlSyntax *syntax, void *data)
1073 for (i=0; syntax[i].id; i++) {
1074 void *data_off = (char *)data + syntax[i].data_offset;
1075 switch (syntax[i].type) {
1077 case EBML_UTF8: av_freep(data_off); break;
1078 case EBML_BIN: av_freep(&((EbmlBin *)data_off)->data); break;
1080 if (syntax[i].list_elem_size) {
1081 EbmlList *list = data_off;
1082 char *ptr = list->elem;
1083 for (j=0; j<list->nb_elem; j++, ptr+=syntax[i].list_elem_size)
1084 ebml_free(syntax[i].def.n, ptr);
1085 av_free(list->elem);
1087 ebml_free(syntax[i].def.n, data_off);
1094 matroska_decode_buffer(uint8_t** buf, int* buf_size, MatroskaTrack *track)
1096 MatroskaTrackEncoding *encodings = track->encodings.elem;
1097 uint8_t* data = *buf;
1098 int isize = *buf_size;
1099 uint8_t* pkt_data = NULL;
1100 int pkt_size = isize;
1104 switch (encodings[0].compression.algo) {
1105 case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
1106 return encodings[0].compression.settings.size;
1107 case MATROSKA_TRACK_ENCODING_COMP_LZO:
1109 olen = pkt_size *= 3;
1110 pkt_data = av_realloc(pkt_data,
1111 pkt_size+LZO_OUTPUT_PADDING);
1112 result = lzo1x_decode(pkt_data, &olen, data, &isize);
1113 } while (result==LZO_OUTPUT_FULL && pkt_size<10000000);
1119 case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
1120 z_stream zstream = {0};
1121 if (inflateInit(&zstream) != Z_OK)
1123 zstream.next_in = data;
1124 zstream.avail_in = isize;
1127 pkt_data = av_realloc(pkt_data, pkt_size);
1128 zstream.avail_out = pkt_size - zstream.total_out;
1129 zstream.next_out = pkt_data + zstream.total_out;
1130 result = inflate(&zstream, Z_NO_FLUSH);
1131 } while (result==Z_OK && pkt_size<10000000);
1132 pkt_size = zstream.total_out;
1133 inflateEnd(&zstream);
1134 if (result != Z_STREAM_END)
1140 case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
1141 bz_stream bzstream = {0};
1142 if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
1144 bzstream.next_in = data;
1145 bzstream.avail_in = isize;
1148 pkt_data = av_realloc(pkt_data, pkt_size);
1149 bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
1150 bzstream.next_out = pkt_data + bzstream.total_out_lo32;
1151 result = BZ2_bzDecompress(&bzstream);
1152 } while (result==BZ_OK && pkt_size<10000000);
1153 pkt_size = bzstream.total_out_lo32;
1154 BZ2_bzDecompressEnd(&bzstream);
1155 if (result != BZ_STREAM_END)
1163 *buf_size = pkt_size;
1171 matroska_execute_seekhead(MatroskaDemuxContext *matroska)
1173 EbmlList *seekhead_list = &matroska->seekhead;
1174 MatroskaSeekhead *seekhead = seekhead_list->elem;
1175 uint32_t peek_id_cache = matroska->peek_id;
1176 uint32_t level_up = matroska->level_up;
1177 offset_t before_pos = url_ftell(matroska->ctx->pb);
1178 MatroskaLevel level;
1181 for (i=0; i<seekhead_list->nb_elem; i++) {
1182 if (seekhead[i].pos <= before_pos
1183 || seekhead[i].id == MATROSKA_ID_SEEKHEAD
1184 || seekhead[i].id == MATROSKA_ID_CLUSTER)
1188 if (ebml_read_seek(matroska,
1189 seekhead[i].pos+matroska->segment_start) < 0)
1192 /* we don't want to lose our seekhead level, so we add
1193 * a dummy. This is a crude hack. */
1194 if (matroska->num_levels == EBML_MAX_DEPTH) {
1195 av_log(matroska->ctx, AV_LOG_INFO,
1196 "Max EBML element depth (%d) reached, "
1197 "cannot parse further.\n", EBML_MAX_DEPTH);
1202 level.length = (uint64_t)-1;
1203 matroska->levels[matroska->num_levels] = level;
1204 matroska->num_levels++;
1206 ebml_parse_id(matroska, matroska_segment, seekhead[i].id, matroska);
1208 /* remove dummy level */
1209 while (matroska->num_levels) {
1210 uint64_t length = matroska->levels[--matroska->num_levels].length;
1211 if (length == (uint64_t)-1)
1217 ebml_read_seek(matroska, before_pos);
1218 matroska->peek_id = peek_id_cache;
1219 matroska->level_up = level_up;
1223 matroska_aac_profile (char *codec_id)
1225 static const char *aac_profiles[] = { "MAIN", "LC", "SSR" };
1228 for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
1229 if (strstr(codec_id, aac_profiles[profile]))
1235 matroska_aac_sri (int samplerate)
1239 for (sri=0; sri<ARRAY_SIZE(ff_mpeg4audio_sample_rates); sri++)
1240 if (ff_mpeg4audio_sample_rates[sri] == samplerate)
1246 matroska_read_header (AVFormatContext *s,
1247 AVFormatParameters *ap)
1249 MatroskaDemuxContext *matroska = s->priv_data;
1250 EbmlList *attachements_list = &matroska->attachments;
1251 MatroskaAttachement *attachements;
1252 EbmlList *chapters_list = &matroska->chapters;
1253 MatroskaChapter *chapters;
1254 MatroskaTrack *tracks;
1255 EbmlList *index_list;
1256 MatroskaIndex *index;
1263 /* First read the EBML header. */
1264 if (ebml_parse(matroska, ebml_syntax, &ebml, 0, 1)
1265 || ebml.version > EBML_VERSION || ebml.max_size > sizeof(uint64_t)
1266 || ebml.id_length > sizeof(uint32_t) || strcmp(ebml.doctype, "matroska")
1267 || ebml.doctype_version > 2) {
1268 av_log(matroska->ctx, AV_LOG_ERROR,
1269 "EBML header using unsupported features\n"
1270 "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",
1271 ebml.version, ebml.doctype, ebml.doctype_version);
1272 return AVERROR_NOFMT;
1274 ebml_free(ebml_syntax, &ebml);
1276 /* The next thing is a segment. */
1277 if (ebml_parse(matroska, matroska_segments, matroska, 0, 1) < 0)
1279 matroska_execute_seekhead(matroska);
1281 if (matroska->duration)
1282 matroska->ctx->duration = matroska->duration * matroska->time_scale
1283 * 1000 / AV_TIME_BASE;
1284 if (matroska->title)
1285 strncpy(matroska->ctx->title, matroska->title,
1286 sizeof(matroska->ctx->title)-1);
1288 tracks = matroska->tracks.elem;
1289 for (i=0; i < matroska->tracks.nb_elem; i++) {
1290 MatroskaTrack *track = &tracks[i];
1291 enum CodecID codec_id = CODEC_ID_NONE;
1292 EbmlList *encodings_list = &tracks->encodings;
1293 MatroskaTrackEncoding *encodings = encodings_list->elem;
1294 uint8_t *extradata = NULL;
1295 int extradata_size = 0;
1296 int extradata_offset = 0;
1298 /* Apply some sanity checks. */
1299 if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&
1300 track->type != MATROSKA_TRACK_TYPE_AUDIO &&
1301 track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {
1302 av_log(matroska->ctx, AV_LOG_INFO,
1303 "Unknown or unsupported track type %"PRIu64"\n",
1307 if (track->codec_id == NULL)
1310 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1311 if (!track->default_duration)
1312 track->default_duration = 1000000000/track->video.frame_rate;
1313 if (!track->video.display_width)
1314 track->video.display_width = track->video.pixel_width;
1315 if (!track->video.display_height)
1316 track->video.display_height = track->video.pixel_height;
1317 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1318 if (!track->audio.out_samplerate)
1319 track->audio.out_samplerate = track->audio.samplerate;
1321 if (encodings_list->nb_elem > 1) {
1322 av_log(matroska->ctx, AV_LOG_ERROR,
1323 "Multiple combined encodings no supported");
1324 } else if (encodings_list->nb_elem == 1) {
1325 if (encodings[0].type ||
1326 (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1328 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&
1331 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&
1333 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {
1334 encodings[0].scope = 0;
1335 av_log(matroska->ctx, AV_LOG_ERROR,
1336 "Unsupported encoding type");
1337 } else if (track->codec_priv.size && encodings[0].scope&2) {
1338 uint8_t *codec_priv = track->codec_priv.data;
1339 int offset = matroska_decode_buffer(&track->codec_priv.data,
1340 &track->codec_priv.size,
1343 track->codec_priv.data = NULL;
1344 track->codec_priv.size = 0;
1345 av_log(matroska->ctx, AV_LOG_ERROR,
1346 "Failed to decode codec private data\n");
1347 } else if (offset > 0) {
1348 track->codec_priv.data = av_malloc(track->codec_priv.size + offset);
1349 memcpy(track->codec_priv.data,
1350 encodings[0].compression.settings.data, offset);
1351 memcpy(track->codec_priv.data+offset, codec_priv,
1352 track->codec_priv.size);
1353 track->codec_priv.size += offset;
1355 if (codec_priv != track->codec_priv.data)
1356 av_free(codec_priv);
1360 for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
1361 if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
1362 strlen(ff_mkv_codec_tags[j].str))){
1363 codec_id= ff_mkv_codec_tags[j].id;
1368 st = track->stream = av_new_stream(s, matroska->num_streams++);
1370 return AVERROR(ENOMEM);
1372 if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC)
1373 && track->codec_priv.size >= 40
1374 && track->codec_priv.data != NULL) {
1375 track->video.fourcc = AV_RL32(track->codec_priv.data + 16);
1376 codec_id = codec_get_id(codec_bmp_tags, track->video.fourcc);
1377 } else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_AUDIO_ACM)
1378 && track->codec_priv.size >= 18
1379 && track->codec_priv.data != NULL) {
1380 uint16_t tag = AV_RL16(track->codec_priv.data);
1381 codec_id = codec_get_id(codec_wav_tags, tag);
1382 } else if (!strcmp(track->codec_id, "V_QUICKTIME")
1383 && (track->codec_priv.size >= 86)
1384 && (track->codec_priv.data != NULL)) {
1385 track->video.fourcc = AV_RL32(track->codec_priv.data);
1386 codec_id=codec_get_id(codec_movvideo_tags, track->video.fourcc);
1387 } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {
1388 int profile = matroska_aac_profile(track->codec_id);
1389 int sri = matroska_aac_sri(track->audio.samplerate);
1390 extradata = av_malloc(5);
1391 if (extradata == NULL)
1392 return AVERROR(ENOMEM);
1393 extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
1394 extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);
1395 if (strstr(track->codec_id, "SBR")) {
1396 sri = matroska_aac_sri(track->audio.out_samplerate);
1397 extradata[2] = 0x56;
1398 extradata[3] = 0xE5;
1399 extradata[4] = 0x80 | (sri<<3);
1403 } else if (codec_id == CODEC_ID_TTA) {
1405 extradata_size = 30;
1406 extradata = av_mallocz(extradata_size);
1407 if (extradata == NULL)
1408 return AVERROR(ENOMEM);
1409 init_put_byte(&b, extradata, extradata_size, 1,
1410 NULL, NULL, NULL, NULL);
1411 put_buffer(&b, "TTA1", 4);
1413 put_le16(&b, track->audio.channels);
1414 put_le16(&b, track->audio.bitdepth);
1415 put_le32(&b, track->audio.out_samplerate);
1416 put_le32(&b, matroska->ctx->duration * track->audio.out_samplerate);
1417 } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
1418 codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
1419 extradata_offset = 26;
1420 track->codec_priv.size -= extradata_offset;
1421 } else if (codec_id == CODEC_ID_RA_144) {
1422 track->audio.out_samplerate = 8000;
1423 track->audio.channels = 1;
1424 } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||
1425 codec_id == CODEC_ID_ATRAC3) {
1428 init_put_byte(&b, track->codec_priv.data,track->codec_priv.size,
1429 0, NULL, NULL, NULL, NULL);
1431 track->audio.coded_framesize = get_be32(&b);
1433 track->audio.sub_packet_h = get_be16(&b);
1434 track->audio.frame_size = get_be16(&b);
1435 track->audio.sub_packet_size = get_be16(&b);
1436 track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);
1437 if (codec_id == CODEC_ID_RA_288) {
1438 st->codec->block_align = track->audio.coded_framesize;
1439 track->codec_priv.size = 0;
1441 st->codec->block_align = track->audio.sub_packet_size;
1442 extradata_offset = 78;
1443 track->codec_priv.size -= extradata_offset;
1447 if (codec_id == CODEC_ID_NONE)
1448 av_log(matroska->ctx, AV_LOG_INFO,
1449 "Unknown/unsupported CodecID %s.\n", track->codec_id);
1451 av_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
1453 st->codec->codec_id = codec_id;
1455 if (strcmp(track->language, "und"))
1456 av_strlcpy(st->language, track->language, 4);
1458 if (track->flag_default)
1459 st->disposition |= AV_DISPOSITION_DEFAULT;
1461 if (track->default_duration)
1462 av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
1463 track->default_duration, 1000000000, 30000);
1466 st->codec->extradata = extradata;
1467 st->codec->extradata_size = extradata_size;
1468 } else if(track->codec_priv.data && track->codec_priv.size > 0){
1469 st->codec->extradata = av_malloc(track->codec_priv.size);
1470 if(st->codec->extradata == NULL)
1471 return AVERROR(ENOMEM);
1472 st->codec->extradata_size = track->codec_priv.size;
1473 memcpy(st->codec->extradata,
1474 track->codec_priv.data + extradata_offset,
1475 track->codec_priv.size);
1478 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
1479 st->codec->codec_type = CODEC_TYPE_VIDEO;
1480 st->codec->codec_tag = track->video.fourcc;
1481 st->codec->width = track->video.pixel_width;
1482 st->codec->height = track->video.pixel_height;
1483 av_reduce(&st->codec->sample_aspect_ratio.num,
1484 &st->codec->sample_aspect_ratio.den,
1485 st->codec->height * track->video.display_width,
1486 st->codec-> width * track->video.display_height,
1488 st->need_parsing = AVSTREAM_PARSE_HEADERS;
1489 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
1490 st->codec->codec_type = CODEC_TYPE_AUDIO;
1491 st->codec->sample_rate = track->audio.out_samplerate;
1492 st->codec->channels = track->audio.channels;
1493 } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
1494 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
1498 attachements = attachements_list->elem;
1499 for (j=0; j<attachements_list->nb_elem; j++) {
1500 if (!(attachements[j].filename && attachements[j].mime &&
1501 attachements[j].bin.data && attachements[j].bin.size > 0)) {
1502 av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1504 AVStream *st = av_new_stream(s, matroska->num_streams++);
1507 st->filename = av_strdup(attachements[j].filename);
1508 st->codec->codec_id = CODEC_ID_NONE;
1509 st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
1510 st->codec->extradata = av_malloc(attachements[j].bin.size);
1511 if(st->codec->extradata == NULL)
1513 st->codec->extradata_size = attachements[j].bin.size;
1514 memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);
1516 for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1517 if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,
1518 strlen(ff_mkv_mime_tags[i].str))) {
1519 st->codec->codec_id = ff_mkv_mime_tags[i].id;
1526 chapters = chapters_list->elem;
1527 for (i=0; i<chapters_list->nb_elem; i++)
1528 if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid)
1529 ff_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},
1530 chapters[i].start, chapters[i].end,
1533 index_list = &matroska->index;
1534 index = index_list->elem;
1535 for (i=0; i<index_list->nb_elem; i++) {
1536 EbmlList *pos_list = &index[i].pos;
1537 MatroskaIndexPos *pos = pos_list->elem;
1538 for (j=0; j<pos_list->nb_elem; j++) {
1539 MatroskaTrack *track = matroska_find_track_by_num(matroska,
1541 if (track && track->stream)
1542 av_add_index_entry(track->stream,
1543 pos[j].pos + matroska->segment_start,
1544 index[i].time*matroska->time_scale/AV_TIME_BASE,
1545 0, 0, AVINDEX_KEYFRAME);
1553 matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
1554 int64_t pos, uint64_t cluster_time, uint64_t duration,
1557 MatroskaTrack *track;
1562 uint32_t *lace_size = NULL;
1563 int n, flags, laces = 0;
1566 if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
1567 av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
1573 track = matroska_find_track_by_num(matroska, num);
1574 if (size <= 3 || !track || !track->stream) {
1575 av_log(matroska->ctx, AV_LOG_INFO,
1576 "Invalid stream %"PRIu64" or size %u\n", num, size);
1580 if (st->discard >= AVDISCARD_ALL)
1582 if (duration == AV_NOPTS_VALUE)
1583 duration = track->default_duration / matroska->time_scale;
1585 block_time = AV_RB16(data);
1589 if (is_keyframe == -1)
1590 is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
1592 if (matroska->skip_to_keyframe) {
1593 if (!is_keyframe || st != matroska->skip_to_stream)
1595 matroska->skip_to_keyframe = 0;
1598 switch ((flags & 0x06) >> 1) {
1599 case 0x0: /* no lacing */
1601 lace_size = av_mallocz(sizeof(int));
1602 lace_size[0] = size;
1605 case 0x1: /* xiph lacing */
1606 case 0x2: /* fixed-size lacing */
1607 case 0x3: /* EBML lacing */
1608 assert(size>0); // size <=3 is checked before size-=3 above
1609 laces = (*data) + 1;
1612 lace_size = av_mallocz(laces * sizeof(int));
1614 switch ((flags & 0x06) >> 1) {
1615 case 0x1: /* xiph lacing */ {
1618 for (n = 0; res == 0 && n < laces - 1; n++) {
1625 lace_size[n] += temp;
1631 total += lace_size[n];
1633 lace_size[n] = size - total;
1637 case 0x2: /* fixed-size lacing */
1638 for (n = 0; n < laces; n++)
1639 lace_size[n] = size / laces;
1642 case 0x3: /* EBML lacing */ {
1644 n = matroska_ebmlnum_uint(data, size, &num);
1646 av_log(matroska->ctx, AV_LOG_INFO,
1647 "EBML block data error\n");
1652 total = lace_size[0] = num;
1653 for (n = 1; res == 0 && n < laces - 1; n++) {
1656 r = matroska_ebmlnum_sint (data, size, &snum);
1658 av_log(matroska->ctx, AV_LOG_INFO,
1659 "EBML block data error\n");
1664 lace_size[n] = lace_size[n - 1] + snum;
1665 total += lace_size[n];
1667 lace_size[n] = size - total;
1675 uint64_t timecode = AV_NOPTS_VALUE;
1677 if (cluster_time != (uint64_t)-1
1678 && (block_time >= 0 || cluster_time >= -block_time))
1679 timecode = cluster_time + block_time;
1681 for (n = 0; n < laces; n++) {
1682 if (st->codec->codec_id == CODEC_ID_RA_288 ||
1683 st->codec->codec_id == CODEC_ID_COOK ||
1684 st->codec->codec_id == CODEC_ID_ATRAC3) {
1685 int a = st->codec->block_align;
1686 int sps = track->audio.sub_packet_size;
1687 int cfs = track->audio.coded_framesize;
1688 int h = track->audio.sub_packet_h;
1689 int y = track->audio.sub_packet_cnt;
1690 int w = track->audio.frame_size;
1693 if (!track->audio.pkt_cnt) {
1694 if (st->codec->codec_id == CODEC_ID_RA_288)
1695 for (x=0; x<h/2; x++)
1696 memcpy(track->audio.buf+x*2*w+y*cfs,
1699 for (x=0; x<w/sps; x++)
1700 memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
1702 if (++track->audio.sub_packet_cnt >= h) {
1703 track->audio.sub_packet_cnt = 0;
1704 track->audio.pkt_cnt = h*w / a;
1707 while (track->audio.pkt_cnt) {
1708 pkt = av_mallocz(sizeof(AVPacket));
1709 av_new_packet(pkt, a);
1710 memcpy(pkt->data, track->audio.buf
1711 + a * (h*w / a - track->audio.pkt_cnt--), a);
1713 pkt->stream_index = st->index;
1714 matroska_queue_packet(matroska, pkt);
1717 MatroskaTrackEncoding *encodings = track->encodings.elem;
1718 int offset = 0, pkt_size = lace_size[n];
1719 uint8_t *pkt_data = data;
1721 if (encodings && encodings->scope & 1) {
1722 offset = matroska_decode_buffer(&pkt_data,&pkt_size, track);
1727 pkt = av_mallocz(sizeof(AVPacket));
1728 /* XXX: prevent data copy... */
1729 if (av_new_packet(pkt, pkt_size+offset) < 0) {
1731 res = AVERROR(ENOMEM);
1736 memcpy (pkt->data, encodings->compression.settings.data, offset);
1737 memcpy (pkt->data+offset, pkt_data, pkt_size);
1739 if (pkt_data != data)
1743 pkt->flags = is_keyframe;
1744 pkt->stream_index = st->index;
1746 pkt->pts = timecode;
1748 pkt->duration = duration;
1750 matroska_queue_packet(matroska, pkt);
1753 if (timecode != AV_NOPTS_VALUE)
1754 timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
1755 data += lace_size[n];
1764 matroska_parse_cluster (MatroskaDemuxContext *matroska)
1766 MatroskaCluster cluster = { 0 };
1767 EbmlList *blocks_list;
1768 MatroskaBlock *blocks;
1769 int i, res = ebml_parse(matroska, matroska_clusters, &cluster, 0, 1);
1770 blocks_list = &cluster.blocks;
1771 blocks = blocks_list->elem;
1772 for (i=0; !res && i<blocks_list->nb_elem; i++)
1773 if (blocks[i].bin.size > 0)
1774 res=matroska_parse_block(matroska,
1775 blocks[i].bin.data, blocks[i].bin.size,
1776 blocks[i].bin.pos, cluster.timecode,
1777 blocks[i].duration, !blocks[i].reference);
1778 ebml_free(matroska_cluster, &cluster);
1783 matroska_read_packet (AVFormatContext *s,
1786 MatroskaDemuxContext *matroska = s->priv_data;
1788 while (matroska_deliver_packet(matroska, pkt)) {
1790 return AVERROR(EIO);
1791 if (matroska_parse_cluster(matroska) < 0)
1799 matroska_read_seek (AVFormatContext *s, int stream_index, int64_t timestamp,
1802 MatroskaDemuxContext *matroska = s->priv_data;
1803 AVStream *st = s->streams[stream_index];
1806 index = av_index_search_timestamp(st, timestamp, flags);
1810 matroska_clear_queue(matroska);
1812 url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
1813 matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
1814 matroska->skip_to_stream = st;
1815 matroska->peek_id = 0;
1816 av_update_cur_dts(s, st, st->index_entries[index].timestamp);
1821 matroska_read_close (AVFormatContext *s)
1823 MatroskaDemuxContext *matroska = s->priv_data;
1824 MatroskaTrack *tracks = matroska->tracks.elem;
1827 matroska_clear_queue(matroska);
1829 for (n=0; n < matroska->tracks.nb_elem; n++)
1830 if (tracks[n].type == MATROSKA_TRACK_TYPE_AUDIO)
1831 av_free(tracks[n].audio.buf);
1832 ebml_free(matroska_segment, matroska);
1837 AVInputFormat matroska_demuxer = {
1839 NULL_IF_CONFIG_SMALL("Matroska file format"),
1840 sizeof(MatroskaDemuxContext),
1842 matroska_read_header,
1843 matroska_read_packet,
1844 matroska_read_close,