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(). */
34 #include "intfloat_readwrite.h"
36 #include "libavcodec/mpeg4audio.h"
37 #include "libavutil/lzo.h"
39 typedef struct Track {
40 MatroskaTrackType type;
42 /* Unique track number and track ID. stream_index is the index that
43 * the calling app uses for this track. */
54 unsigned char *codec_priv;
57 uint64_t default_duration;
58 MatroskaTrackFlags flags;
62 uint8_t *encoding_settings;
63 int encoding_settings_len;
66 typedef struct MatroskaVideoTrack {
76 MatroskaAspectRatioMode ar_mode;
77 MatroskaEyeMode eye_mode;
82 typedef struct MatroskaAudioTrack {
87 int internal_samplerate;
91 /* real audio header */
100 } MatroskaAudioTrack;
102 typedef struct MatroskaSubtitleTrack {
105 } MatroskaSubtitleTrack;
107 #define MAX_TRACK_SIZE (FFMAX3(sizeof(MatroskaVideoTrack), \
108 sizeof(MatroskaAudioTrack), \
109 sizeof(MatroskaSubtitleTrack)))
111 typedef struct MatroskaLevel {
116 typedef struct MatroskaDemuxIndex {
117 uint64_t pos; /* of the corresponding *cluster*! */
118 uint16_t track; /* reference to 'num' */
119 uint64_t time; /* in nanoseconds */
120 } MatroskaDemuxIndex;
122 typedef struct MatroskaDemuxContext {
123 AVFormatContext *ctx;
127 MatroskaLevel levels[EBML_MAX_DEPTH];
135 /* timescale in the file */
138 /* num_streams is the number of streams that av_new_stream() was called
139 * for ( = that are available to the calling program). */
142 MatroskaTrack *tracks[MAX_STREAMS];
144 /* cache for ID peeking */
147 /* byte position of the segment inside the stream */
148 offset_t segment_start;
150 /* The packet queue. */
154 /* have we already parse metadata/cues/clusters? */
159 /* The index for seeking. */
161 MatroskaDemuxIndex *index;
163 /* What to skip before effectively reading a packet. */
164 int skip_to_keyframe;
165 AVStream *skip_to_stream;
166 } MatroskaDemuxContext;
169 * The first few functions handle EBML file parsing. The rest
170 * is the document interpretation. Matroska really just is a
175 * Return: the amount of levels in the hierarchy that the
176 * current element lies higher than the previous one.
177 * The opposite isn't done - that's auto-done using master
182 ebml_read_element_level_up (MatroskaDemuxContext *matroska)
184 ByteIOContext *pb = matroska->ctx->pb;
185 offset_t pos = url_ftell(pb);
188 while (matroska->num_levels > 0) {
189 MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
191 if (pos >= level->start + level->length) {
192 matroska->num_levels--;
203 * Read: an "EBML number", which is defined as a variable-length
204 * array of bytes. The first byte indicates the length by giving a
205 * number of 0-bits followed by a one. The position of the first
206 * "one" bit inside the first byte indicates the length of this
208 * Returns: num. of bytes read. < 0 on error.
212 ebml_read_num (MatroskaDemuxContext *matroska,
216 ByteIOContext *pb = matroska->ctx->pb;
217 int len_mask = 0x80, read = 1, n = 1;
220 /* the first byte tells us the length in bytes - get_byte() can normally
221 * return 0, but since that's not a valid first ebmlID byte, we can
222 * use it safely here to catch EOS. */
223 if (!(total = get_byte(pb))) {
224 /* we might encounter EOS here */
226 offset_t pos = url_ftell(pb);
227 av_log(matroska->ctx, AV_LOG_ERROR,
228 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
231 return AVERROR(EIO); /* EOS or actual I/O error */
234 /* get the length of the EBML number */
235 while (read <= max_size && !(total & len_mask)) {
239 if (read > max_size) {
240 offset_t pos = url_ftell(pb) - 1;
241 av_log(matroska->ctx, AV_LOG_ERROR,
242 "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
243 (uint8_t) total, pos, pos);
244 return AVERROR_INVALIDDATA;
247 /* read out length */
250 total = (total << 8) | get_byte(pb);
258 * Read: the element content data ID.
259 * Return: the number of bytes read or < 0 on error.
263 ebml_read_element_id (MatroskaDemuxContext *matroska,
270 /* if we re-call this, use our cached ID */
271 if (matroska->peek_id != 0) {
274 *id = matroska->peek_id;
278 /* read out the "EBML number", include tag in ID */
279 if ((read = ebml_read_num(matroska, 4, &total)) < 0)
281 *id = matroska->peek_id = total | (1 << (read * 7));
285 *level_up = ebml_read_element_level_up(matroska);
291 * Read: element content length.
292 * Return: the number of bytes read or < 0 on error.
296 ebml_read_element_length (MatroskaDemuxContext *matroska,
299 /* clear cache since we're now beyond that data point */
300 matroska->peek_id = 0;
302 /* read out the "EBML number", include tag in ID */
303 return ebml_read_num(matroska, 8, length);
307 * Return: the ID of the next element, or 0 on error.
308 * Level_up contains the amount of levels that this
309 * next element lies higher than the previous one.
313 ebml_peek_id (MatroskaDemuxContext *matroska,
318 if (ebml_read_element_id(matroska, &id, level_up) < 0)
325 * Seek to a given offset.
326 * 0 is success, -1 is failure.
330 ebml_read_seek (MatroskaDemuxContext *matroska,
333 ByteIOContext *pb = matroska->ctx->pb;
335 /* clear ID cache, if any */
336 matroska->peek_id = 0;
338 return (url_fseek(pb, offset, SEEK_SET) == offset) ? 0 : -1;
342 * Skip the next element.
343 * 0 is success, -1 is failure.
347 ebml_read_skip (MatroskaDemuxContext *matroska)
349 ByteIOContext *pb = matroska->ctx->pb;
354 if ((res = ebml_read_element_id(matroska, &id, NULL)) < 0 ||
355 (res = ebml_read_element_length(matroska, &length)) < 0)
358 url_fskip(pb, length);
364 * Read the next element as an unsigned int.
365 * 0 is success, < 0 is failure.
369 ebml_read_uint (MatroskaDemuxContext *matroska,
373 ByteIOContext *pb = matroska->ctx->pb;
374 int n = 0, size, res;
377 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
378 (res = ebml_read_element_length(matroska, &rlength)) < 0)
381 if (size < 1 || size > 8) {
382 offset_t pos = url_ftell(pb);
383 av_log(matroska->ctx, AV_LOG_ERROR,
384 "Invalid uint element size %d at position %"PRId64" (0x%"PRIx64")\n",
386 return AVERROR_INVALIDDATA;
389 /* big-endian ordening; build up number */
392 *num = (*num << 8) | get_byte(pb);
398 * Read the next element as a signed int.
399 * 0 is success, < 0 is failure.
403 ebml_read_sint (MatroskaDemuxContext *matroska,
407 ByteIOContext *pb = matroska->ctx->pb;
408 int size, n = 1, negative = 0, res;
411 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
412 (res = ebml_read_element_length(matroska, &rlength)) < 0)
415 if (size < 1 || size > 8) {
416 offset_t pos = url_ftell(pb);
417 av_log(matroska->ctx, AV_LOG_ERROR,
418 "Invalid sint element size %d at position %"PRId64" (0x%"PRIx64")\n",
420 return AVERROR_INVALIDDATA;
422 if ((*num = get_byte(pb)) & 0x80) {
427 *num = (*num << 8) | get_byte(pb);
431 *num = *num - (1LL << ((8 * size) - 1));
437 * Read the next element as a float.
438 * 0 is success, < 0 is failure.
442 ebml_read_float (MatroskaDemuxContext *matroska,
446 ByteIOContext *pb = matroska->ctx->pb;
450 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
451 (res = ebml_read_element_length(matroska, &rlength)) < 0)
456 *num= av_int2flt(get_be32(pb));
458 *num= av_int2dbl(get_be64(pb));
460 offset_t pos = url_ftell(pb);
461 av_log(matroska->ctx, AV_LOG_ERROR,
462 "Invalid float element size %d at position %"PRIu64" (0x%"PRIx64")\n",
464 return AVERROR_INVALIDDATA;
471 * Read the next element as an ASCII string.
472 * 0 is success, < 0 is failure.
476 ebml_read_ascii (MatroskaDemuxContext *matroska,
480 ByteIOContext *pb = matroska->ctx->pb;
484 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
485 (res = ebml_read_element_length(matroska, &rlength)) < 0)
489 /* ebml strings are usually not 0-terminated, so we allocate one
490 * byte more, read the string and NULL-terminate it ourselves. */
491 if (size < 0 || !(*str = av_malloc(size + 1))) {
492 av_log(matroska->ctx, AV_LOG_ERROR, "Memory allocation failed\n");
493 return AVERROR(ENOMEM);
495 if (get_buffer(pb, (uint8_t *) *str, size) != size) {
496 offset_t pos = url_ftell(pb);
497 av_log(matroska->ctx, AV_LOG_ERROR,
498 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
507 * Read the next element as a UTF-8 string.
508 * 0 is success, < 0 is failure.
512 ebml_read_utf8 (MatroskaDemuxContext *matroska,
516 return ebml_read_ascii(matroska, id, str);
520 * Read the next element as a date (nanoseconds since 1/1/2000).
521 * 0 is success, < 0 is failure.
525 ebml_read_date (MatroskaDemuxContext *matroska,
529 return ebml_read_sint(matroska, id, date);
533 * Read the next element, but only the header. The contents
534 * are supposed to be sub-elements which can be read separately.
535 * 0 is success, < 0 is failure.
539 ebml_read_master (MatroskaDemuxContext *matroska,
542 ByteIOContext *pb = matroska->ctx->pb;
544 MatroskaLevel *level;
547 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
548 (res = ebml_read_element_length(matroska, &length)) < 0)
551 /* protect... (Heaven forbids that the '>' is true) */
552 if (matroska->num_levels >= EBML_MAX_DEPTH) {
553 av_log(matroska->ctx, AV_LOG_ERROR,
554 "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
555 return AVERROR(ENOSYS);
559 level = &matroska->levels[matroska->num_levels++];
560 level->start = url_ftell(pb);
561 level->length = length;
567 * Read the next element as binary data.
568 * 0 is success, < 0 is failure.
572 ebml_read_binary (MatroskaDemuxContext *matroska,
577 ByteIOContext *pb = matroska->ctx->pb;
581 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
582 (res = ebml_read_element_length(matroska, &rlength)) < 0)
586 if (!(*binary = av_malloc(*size))) {
587 av_log(matroska->ctx, AV_LOG_ERROR,
588 "Memory allocation error\n");
589 return AVERROR(ENOMEM);
592 if (get_buffer(pb, *binary, *size) != *size) {
593 offset_t pos = url_ftell(pb);
594 av_log(matroska->ctx, AV_LOG_ERROR,
595 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
603 * Read signed/unsigned "EBML" numbers.
604 * Return: number of bytes processed, < 0 on error.
605 * XXX: use ebml_read_num().
609 matroska_ebmlnum_uint (uint8_t *data,
613 int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
617 return AVERROR_INVALIDDATA;
620 while (read <= 8 && !(total & len_mask)) {
625 return AVERROR_INVALIDDATA;
627 if ((total &= (len_mask - 1)) == len_mask - 1)
630 return AVERROR_INVALIDDATA;
634 total = (total << 8) | data[n];
647 * Same as above, but signed.
651 matroska_ebmlnum_sint (uint8_t *data,
658 /* read as unsigned number first */
659 if ((res = matroska_ebmlnum_uint(data, size, &unum)) < 0)
662 /* make signed (weird way) */
663 if (unum == (uint64_t)-1)
666 *num = unum - ((1LL << ((7 * res) - 1)) - 1);
672 * Read an EBML header.
673 * 0 is success, < 0 is failure.
677 ebml_read_header (MatroskaDemuxContext *matroska,
682 int level_up, res = 0;
690 if (!(id = ebml_peek_id(matroska, &level_up)) ||
691 level_up != 0 || id != EBML_ID_HEADER) {
692 av_log(matroska->ctx, AV_LOG_ERROR,
693 "This is not an EBML file (id=0x%x/0x%x)\n", id, EBML_ID_HEADER);
694 return AVERROR_INVALIDDATA;
696 if ((res = ebml_read_master(matroska, &id)) < 0)
700 if (!(id = ebml_peek_id(matroska, &level_up)))
708 /* is our read version uptodate? */
709 case EBML_ID_EBMLREADVERSION: {
712 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
714 if (num > EBML_VERSION) {
715 av_log(matroska->ctx, AV_LOG_ERROR,
716 "EBML version %"PRIu64" (> %d) is not supported\n",
718 return AVERROR_INVALIDDATA;
723 /* we only handle 8 byte lengths at max */
724 case EBML_ID_EBMLMAXSIZELENGTH: {
727 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
729 if (num > sizeof(uint64_t)) {
730 av_log(matroska->ctx, AV_LOG_ERROR,
731 "Integers of size %"PRIu64" (> %zd) not supported\n",
732 num, sizeof(uint64_t));
733 return AVERROR_INVALIDDATA;
738 /* we handle 4 byte IDs at max */
739 case EBML_ID_EBMLMAXIDLENGTH: {
742 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
744 if (num > sizeof(uint32_t)) {
745 av_log(matroska->ctx, AV_LOG_ERROR,
746 "IDs of size %"PRIu64" (> %zu) not supported\n",
747 num, sizeof(uint32_t));
748 return AVERROR_INVALIDDATA;
753 case EBML_ID_DOCTYPE: {
756 if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
767 case EBML_ID_DOCTYPEREADVERSION: {
770 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
778 av_log(matroska->ctx, AV_LOG_INFO,
779 "Unknown data type 0x%x in EBML header", id);
783 /* we ignore these two, as they don't tell us anything we
785 case EBML_ID_EBMLVERSION:
786 case EBML_ID_DOCTYPEVERSION:
787 res = ebml_read_skip (matroska);
797 matroska_find_track_by_num (MatroskaDemuxContext *matroska,
802 for (i = 0; i < matroska->num_tracks; i++)
803 if (matroska->tracks[i]->num == num)
811 * Put one packet in an application-supplied AVPacket struct.
812 * Returns 0 on success or -1 on failure.
816 matroska_deliver_packet (MatroskaDemuxContext *matroska,
819 if (matroska->num_packets > 0) {
820 memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
821 av_free(matroska->packets[0]);
822 if (matroska->num_packets > 1) {
823 memmove(&matroska->packets[0], &matroska->packets[1],
824 (matroska->num_packets - 1) * sizeof(AVPacket *));
826 av_realloc(matroska->packets, (matroska->num_packets - 1) *
829 av_freep(&matroska->packets);
831 matroska->num_packets--;
839 * Put a packet into our internal queue. Will be delivered to the
840 * user/application during the next get_packet() call.
844 matroska_queue_packet (MatroskaDemuxContext *matroska,
848 av_realloc(matroska->packets, (matroska->num_packets + 1) *
850 matroska->packets[matroska->num_packets] = pkt;
851 matroska->num_packets++;
855 * Free all packets in our internal queue.
858 matroska_clear_queue (MatroskaDemuxContext *matroska)
860 if (matroska->packets) {
862 for (n = 0; n < matroska->num_packets; n++) {
863 av_free_packet(matroska->packets[n]);
864 av_free(matroska->packets[n]);
866 av_free(matroska->packets);
867 matroska->packets = NULL;
868 matroska->num_packets = 0;
878 matroska_probe (AVProbeData *p)
881 int len_mask = 0x80, size = 1, n = 1;
882 uint8_t probe_data[] = { 'm', 'a', 't', 'r', 'o', 's', 'k', 'a' };
885 if (AV_RB32(p->buf) != EBML_ID_HEADER)
888 /* length of header */
890 while (size <= 8 && !(total & len_mask)) {
896 total &= (len_mask - 1);
898 total = (total << 8) | p->buf[4 + n++];
900 /* does the probe data contain the whole header? */
901 if (p->buf_size < 4 + size + total)
904 /* the header must contain the document type 'matroska'. For now,
905 * we don't parse the whole header but simply check for the
906 * availability of that array of characters inside the header.
907 * Not fully fool-proof, but good enough. */
908 for (n = 4 + size; n <= 4 + size + total - sizeof(probe_data); n++)
909 if (!memcmp (&p->buf[n], probe_data, sizeof(probe_data)))
910 return AVPROBE_SCORE_MAX;
916 * From here on, it's all XML-style DTD stuff... Needs no comments.
920 matroska_parse_info (MatroskaDemuxContext *matroska)
925 av_log(matroska->ctx, AV_LOG_DEBUG, "Parsing info...\n");
928 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
931 } else if (matroska->level_up) {
932 matroska->level_up--;
937 /* cluster timecode */
938 case MATROSKA_ID_TIMECODESCALE: {
940 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
942 matroska->time_scale = num;
946 case MATROSKA_ID_DURATION: {
948 if ((res = ebml_read_float(matroska, &id, &num)) < 0)
950 matroska->ctx->duration = num * matroska->time_scale * 1000 / AV_TIME_BASE;
954 case MATROSKA_ID_TITLE: {
956 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
958 strncpy(matroska->ctx->title, text,
959 sizeof(matroska->ctx->title)-1);
964 case MATROSKA_ID_WRITINGAPP: {
966 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
968 matroska->writing_app = text;
972 case MATROSKA_ID_MUXINGAPP: {
974 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
976 matroska->muxing_app = text;
980 case MATROSKA_ID_DATEUTC: {
982 if ((res = ebml_read_date(matroska, &id, &time)) < 0)
984 matroska->created = time;
989 av_log(matroska->ctx, AV_LOG_INFO,
990 "Unknown entry 0x%x in info header\n", id);
994 res = ebml_read_skip(matroska);
998 if (matroska->level_up) {
999 matroska->level_up--;
1008 matroska_add_stream (MatroskaDemuxContext *matroska)
1012 MatroskaTrack *track;
1014 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing track, adding stream..,\n");
1016 /* Allocate a generic track. As soon as we know its type we'll realloc. */
1017 track = av_mallocz(MAX_TRACK_SIZE);
1018 matroska->num_tracks++;
1019 strcpy(track->language, "eng");
1021 /* start with the master */
1022 if ((res = ebml_read_master(matroska, &id)) < 0)
1025 /* try reading the trackentry headers */
1027 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1030 } else if (matroska->level_up > 0) {
1031 matroska->level_up--;
1036 /* track number (unique stream ID) */
1037 case MATROSKA_ID_TRACKNUMBER: {
1039 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1045 /* track UID (unique identifier) */
1046 case MATROSKA_ID_TRACKUID: {
1048 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1054 /* track type (video, audio, combined, subtitle, etc.) */
1055 case MATROSKA_ID_TRACKTYPE: {
1057 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1059 if (track->type && track->type != num) {
1060 av_log(matroska->ctx, AV_LOG_INFO,
1061 "More than one tracktype in an entry - skip\n");
1066 switch (track->type) {
1067 case MATROSKA_TRACK_TYPE_VIDEO:
1068 case MATROSKA_TRACK_TYPE_AUDIO:
1069 case MATROSKA_TRACK_TYPE_SUBTITLE:
1071 case MATROSKA_TRACK_TYPE_COMPLEX:
1072 case MATROSKA_TRACK_TYPE_LOGO:
1073 case MATROSKA_TRACK_TYPE_CONTROL:
1075 av_log(matroska->ctx, AV_LOG_INFO,
1076 "Unknown or unsupported track type 0x%x\n",
1081 matroska->tracks[matroska->num_tracks - 1] = track;
1085 /* tracktype specific stuff for video */
1086 case MATROSKA_ID_TRACKVIDEO: {
1087 MatroskaVideoTrack *videotrack;
1089 track->type = MATROSKA_TRACK_TYPE_VIDEO;
1090 if (track->type != MATROSKA_TRACK_TYPE_VIDEO) {
1091 av_log(matroska->ctx, AV_LOG_INFO,
1092 "video data in non-video track - ignoring\n");
1093 res = AVERROR_INVALIDDATA;
1095 } else if ((res = ebml_read_master(matroska, &id)) < 0)
1097 videotrack = (MatroskaVideoTrack *)track;
1100 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1103 } else if (matroska->level_up > 0) {
1104 matroska->level_up--;
1109 /* fixme, this should be one-up, but I get it here */
1110 case MATROSKA_ID_TRACKDEFAULTDURATION: {
1112 if ((res = ebml_read_uint (matroska, &id,
1115 track->default_duration = num;
1119 /* video framerate */
1120 case MATROSKA_ID_VIDEOFRAMERATE: {
1122 if ((res = ebml_read_float(matroska, &id,
1125 if (!track->default_duration)
1126 track->default_duration = 1000000000/num;
1130 /* width of the size to display the video at */
1131 case MATROSKA_ID_VIDEODISPLAYWIDTH: {
1133 if ((res = ebml_read_uint(matroska, &id,
1136 videotrack->display_width = num;
1140 /* height of the size to display the video at */
1141 case MATROSKA_ID_VIDEODISPLAYHEIGHT: {
1143 if ((res = ebml_read_uint(matroska, &id,
1146 videotrack->display_height = num;
1150 /* width of the video in the file */
1151 case MATROSKA_ID_VIDEOPIXELWIDTH: {
1153 if ((res = ebml_read_uint(matroska, &id,
1156 videotrack->pixel_width = num;
1160 /* height of the video in the file */
1161 case MATROSKA_ID_VIDEOPIXELHEIGHT: {
1163 if ((res = ebml_read_uint(matroska, &id,
1166 videotrack->pixel_height = num;
1170 /* whether the video is interlaced */
1171 case MATROSKA_ID_VIDEOFLAGINTERLACED: {
1173 if ((res = ebml_read_uint(matroska, &id,
1178 MATROSKA_VIDEOTRACK_INTERLACED;
1181 ~MATROSKA_VIDEOTRACK_INTERLACED;
1185 /* stereo mode (whether the video has two streams,
1186 * where one is for the left eye and the other for
1187 * the right eye, which creates a 3D-like
1189 case MATROSKA_ID_VIDEOSTEREOMODE: {
1191 if ((res = ebml_read_uint(matroska, &id,
1194 if (num != MATROSKA_EYE_MODE_MONO &&
1195 num != MATROSKA_EYE_MODE_LEFT &&
1196 num != MATROSKA_EYE_MODE_RIGHT &&
1197 num != MATROSKA_EYE_MODE_BOTH) {
1198 av_log(matroska->ctx, AV_LOG_INFO,
1199 "Ignoring unknown eye mode 0x%x\n",
1203 videotrack->eye_mode = num;
1207 /* aspect ratio behaviour */
1208 case MATROSKA_ID_VIDEOASPECTRATIO: {
1210 if ((res = ebml_read_uint(matroska, &id,
1213 if (num != MATROSKA_ASPECT_RATIO_MODE_FREE &&
1214 num != MATROSKA_ASPECT_RATIO_MODE_KEEP &&
1215 num != MATROSKA_ASPECT_RATIO_MODE_FIXED) {
1216 av_log(matroska->ctx, AV_LOG_INFO,
1217 "Ignoring unknown aspect ratio 0x%x\n",
1221 videotrack->ar_mode = num;
1225 /* colorspace (only matters for raw video)
1227 case MATROSKA_ID_VIDEOCOLORSPACE: {
1229 if ((res = ebml_read_uint(matroska, &id,
1232 videotrack->fourcc = num;
1237 av_log(matroska->ctx, AV_LOG_INFO,
1238 "Unknown video track header entry "
1239 "0x%x - ignoring\n", id);
1243 res = ebml_read_skip(matroska);
1247 if (matroska->level_up) {
1248 matroska->level_up--;
1255 /* tracktype specific stuff for audio */
1256 case MATROSKA_ID_TRACKAUDIO: {
1257 MatroskaAudioTrack *audiotrack;
1259 track->type = MATROSKA_TRACK_TYPE_AUDIO;
1260 if (track->type != MATROSKA_TRACK_TYPE_AUDIO) {
1261 av_log(matroska->ctx, AV_LOG_INFO,
1262 "audio data in non-audio track - ignoring\n");
1263 res = AVERROR_INVALIDDATA;
1265 } else if ((res = ebml_read_master(matroska, &id)) < 0)
1267 audiotrack = (MatroskaAudioTrack *)track;
1268 audiotrack->channels = 1;
1269 audiotrack->samplerate = 8000;
1272 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1275 } else if (matroska->level_up > 0) {
1276 matroska->level_up--;
1282 case MATROSKA_ID_AUDIOSAMPLINGFREQ: {
1284 if ((res = ebml_read_float(matroska, &id,
1287 audiotrack->internal_samplerate =
1288 audiotrack->samplerate = num;
1292 case MATROSKA_ID_AUDIOOUTSAMPLINGFREQ: {
1294 if ((res = ebml_read_float(matroska, &id,
1297 audiotrack->samplerate = num;
1302 case MATROSKA_ID_AUDIOBITDEPTH: {
1304 if ((res = ebml_read_uint(matroska, &id,
1307 audiotrack->bitdepth = num;
1312 case MATROSKA_ID_AUDIOCHANNELS: {
1314 if ((res = ebml_read_uint(matroska, &id,
1317 audiotrack->channels = num;
1322 av_log(matroska->ctx, AV_LOG_INFO,
1323 "Unknown audio track header entry "
1324 "0x%x - ignoring\n", id);
1328 res = ebml_read_skip(matroska);
1332 if (matroska->level_up) {
1333 matroska->level_up--;
1340 /* codec identifier */
1341 case MATROSKA_ID_CODECID: {
1343 if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
1345 track->codec_id = text;
1349 /* codec private data */
1350 case MATROSKA_ID_CODECPRIVATE: {
1353 if ((res = ebml_read_binary(matroska, &id, &data, &size) < 0))
1355 track->codec_priv = data;
1356 track->codec_priv_size = size;
1360 /* name of the codec */
1361 case MATROSKA_ID_CODECNAME: {
1363 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1365 track->codec_name = text;
1369 /* name of this track */
1370 case MATROSKA_ID_TRACKNAME: {
1372 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1378 /* language (matters for audio/subtitles, mostly) */
1379 case MATROSKA_ID_TRACKLANGUAGE: {
1381 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1383 if ((end = strchr(text, '-')))
1385 if (strlen(text) == 3)
1386 strcpy(track->language, text);
1391 /* whether this is actually used */
1392 case MATROSKA_ID_TRACKFLAGENABLED: {
1394 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1397 track->flags |= MATROSKA_TRACK_ENABLED;
1399 track->flags &= ~MATROSKA_TRACK_ENABLED;
1403 /* whether it's the default for this track type */
1404 case MATROSKA_ID_TRACKFLAGDEFAULT: {
1406 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1409 track->flags |= MATROSKA_TRACK_DEFAULT;
1411 track->flags &= ~MATROSKA_TRACK_DEFAULT;
1415 /* lacing (like MPEG, where blocks don't end/start on frame
1417 case MATROSKA_ID_TRACKFLAGLACING: {
1419 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1422 track->flags |= MATROSKA_TRACK_LACING;
1424 track->flags &= ~MATROSKA_TRACK_LACING;
1428 /* default length (in time) of one data block in this track */
1429 case MATROSKA_ID_TRACKDEFAULTDURATION: {
1431 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1433 track->default_duration = num;
1437 case MATROSKA_ID_TRACKCONTENTENCODINGS: {
1438 if ((res = ebml_read_master(matroska, &id)) < 0)
1442 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1445 } else if (matroska->level_up > 0) {
1446 matroska->level_up--;
1451 case MATROSKA_ID_TRACKCONTENTENCODING: {
1452 int encoding_scope = 1;
1453 if ((res = ebml_read_master(matroska, &id)) < 0)
1457 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1460 } else if (matroska->level_up > 0) {
1461 matroska->level_up--;
1466 case MATROSKA_ID_ENCODINGSCOPE: {
1468 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1470 encoding_scope = num;
1474 case MATROSKA_ID_ENCODINGTYPE: {
1476 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1479 av_log(matroska->ctx, AV_LOG_ERROR,
1480 "Unsupported encoding type");
1484 case MATROSKA_ID_ENCODINGCOMPRESSION: {
1485 if ((res = ebml_read_master(matroska, &id)) < 0)
1489 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1492 } else if (matroska->level_up > 0) {
1493 matroska->level_up--;
1498 case MATROSKA_ID_ENCODINGCOMPALGO: {
1500 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1502 if (num != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&
1503 num != MATROSKA_TRACK_ENCODING_COMP_LZO)
1504 av_log(matroska->ctx, AV_LOG_ERROR,
1505 "Unsupported compression algo");
1506 track->encoding_algo = num;
1510 case MATROSKA_ID_ENCODINGCOMPSETTINGS: {
1513 if ((res = ebml_read_binary(matroska, &id, &data, &size) < 0))
1515 track->encoding_settings = data;
1516 track->encoding_settings_len = size;
1521 av_log(matroska->ctx, AV_LOG_INFO,
1522 "Unknown compression header entry "
1523 "0x%x - ignoring\n", id);
1527 res = ebml_read_skip(matroska);
1531 if (matroska->level_up) {
1532 matroska->level_up--;
1540 av_log(matroska->ctx, AV_LOG_INFO,
1541 "Unknown content encoding header entry "
1542 "0x%x - ignoring\n", id);
1546 res = ebml_read_skip(matroska);
1550 if (matroska->level_up) {
1551 matroska->level_up--;
1556 track->encoding_scope = encoding_scope;
1561 av_log(matroska->ctx, AV_LOG_INFO,
1562 "Unknown content encodings header entry "
1563 "0x%x - ignoring\n", id);
1567 res = ebml_read_skip(matroska);
1571 if (matroska->level_up) {
1572 matroska->level_up--;
1580 av_log(matroska->ctx, AV_LOG_INFO,
1581 "Unknown track header entry 0x%x - ignoring\n", id);
1585 /* we ignore these because they're nothing useful. */
1586 case MATROSKA_ID_CODECINFOURL:
1587 case MATROSKA_ID_CODECDOWNLOADURL:
1588 case MATROSKA_ID_TRACKMINCACHE:
1589 case MATROSKA_ID_TRACKMAXCACHE:
1590 res = ebml_read_skip(matroska);
1594 if (matroska->level_up) {
1595 matroska->level_up--;
1604 matroska_parse_tracks (MatroskaDemuxContext *matroska)
1609 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing tracks...\n");
1612 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1615 } else if (matroska->level_up) {
1616 matroska->level_up--;
1621 /* one track within the "all-tracks" header */
1622 case MATROSKA_ID_TRACKENTRY:
1623 res = matroska_add_stream(matroska);
1627 av_log(matroska->ctx, AV_LOG_INFO,
1628 "Unknown entry 0x%x in track header\n", id);
1632 res = ebml_read_skip(matroska);
1636 if (matroska->level_up) {
1637 matroska->level_up--;
1646 matroska_parse_index (MatroskaDemuxContext *matroska)
1650 MatroskaDemuxIndex idx;
1652 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing index...\n");
1655 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1658 } else if (matroska->level_up) {
1659 matroska->level_up--;
1664 /* one single index entry ('point') */
1665 case MATROSKA_ID_POINTENTRY:
1666 if ((res = ebml_read_master(matroska, &id)) < 0)
1669 /* in the end, we hope to fill one entry with a
1670 * timestamp, a file position and a tracknum */
1671 idx.pos = (uint64_t) -1;
1672 idx.time = (uint64_t) -1;
1673 idx.track = (uint16_t) -1;
1676 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1679 } else if (matroska->level_up) {
1680 matroska->level_up--;
1685 /* one single index entry ('point') */
1686 case MATROSKA_ID_CUETIME: {
1688 if ((res = ebml_read_uint(matroska, &id,
1691 idx.time = time * matroska->time_scale;
1695 /* position in the file + track to which it
1697 case MATROSKA_ID_CUETRACKPOSITION:
1698 if ((res = ebml_read_master(matroska, &id)) < 0)
1702 if (!(id = ebml_peek_id (matroska,
1703 &matroska->level_up))) {
1706 } else if (matroska->level_up) {
1707 matroska->level_up--;
1713 case MATROSKA_ID_CUETRACK: {
1715 if ((res = ebml_read_uint(matroska,
1722 /* position in file */
1723 case MATROSKA_ID_CUECLUSTERPOSITION: {
1725 if ((res = ebml_read_uint(matroska,
1728 idx.pos = num+matroska->segment_start;
1733 av_log(matroska->ctx, AV_LOG_INFO,
1734 "Unknown entry 0x%x in "
1735 "CuesTrackPositions\n", id);
1739 res = ebml_read_skip(matroska);
1743 if (matroska->level_up) {
1744 matroska->level_up--;
1752 av_log(matroska->ctx, AV_LOG_INFO,
1753 "Unknown entry 0x%x in cuespoint "
1758 res = ebml_read_skip(matroska);
1762 if (matroska->level_up) {
1763 matroska->level_up--;
1768 /* so let's see if we got what we wanted */
1769 if (idx.pos != (uint64_t) -1 &&
1770 idx.time != (uint64_t) -1 &&
1771 idx.track != (uint16_t) -1) {
1772 if (matroska->num_indexes % 32 == 0) {
1773 /* re-allocate bigger index */
1775 av_realloc(matroska->index,
1776 (matroska->num_indexes + 32) *
1777 sizeof(MatroskaDemuxIndex));
1779 matroska->index[matroska->num_indexes] = idx;
1780 matroska->num_indexes++;
1785 av_log(matroska->ctx, AV_LOG_INFO,
1786 "Unknown entry 0x%x in cues header\n", id);
1790 res = ebml_read_skip(matroska);
1794 if (matroska->level_up) {
1795 matroska->level_up--;
1804 matroska_parse_metadata (MatroskaDemuxContext *matroska)
1810 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1813 } else if (matroska->level_up) {
1814 matroska->level_up--;
1819 /* Hm, this is unsupported... */
1821 av_log(matroska->ctx, AV_LOG_INFO,
1822 "Unknown entry 0x%x in metadata header\n", id);
1826 res = ebml_read_skip(matroska);
1830 if (matroska->level_up) {
1831 matroska->level_up--;
1840 matroska_parse_seekhead (MatroskaDemuxContext *matroska)
1845 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing seekhead...\n");
1848 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1851 } else if (matroska->level_up) {
1852 matroska->level_up--;
1857 case MATROSKA_ID_SEEKENTRY: {
1858 uint32_t seek_id = 0, peek_id_cache = 0;
1859 uint64_t seek_pos = (uint64_t) -1, t;
1861 if ((res = ebml_read_master(matroska, &id)) < 0)
1865 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1868 } else if (matroska->level_up) {
1869 matroska->level_up--;
1874 case MATROSKA_ID_SEEKID:
1875 res = ebml_read_uint(matroska, &id, &t);
1879 case MATROSKA_ID_SEEKPOSITION:
1880 res = ebml_read_uint(matroska, &id, &seek_pos);
1884 av_log(matroska->ctx, AV_LOG_INFO,
1885 "Unknown seekhead ID 0x%x\n", id);
1889 res = ebml_read_skip(matroska);
1893 if (matroska->level_up) {
1894 matroska->level_up--;
1899 if (!seek_id || seek_pos == (uint64_t) -1) {
1900 av_log(matroska->ctx, AV_LOG_INFO,
1901 "Incomplete seekhead entry (0x%x/%"PRIu64")\n",
1907 case MATROSKA_ID_CUES:
1908 case MATROSKA_ID_TAGS: {
1909 uint32_t level_up = matroska->level_up;
1910 offset_t before_pos;
1912 MatroskaLevel level;
1914 /* remember the peeked ID and the current position */
1915 peek_id_cache = matroska->peek_id;
1916 before_pos = url_ftell(matroska->ctx->pb);
1919 if ((res = ebml_read_seek(matroska, seek_pos +
1920 matroska->segment_start)) < 0)
1923 /* we don't want to lose our seekhead level, so we add
1924 * a dummy. This is a crude hack. */
1925 if (matroska->num_levels == EBML_MAX_DEPTH) {
1926 av_log(matroska->ctx, AV_LOG_INFO,
1927 "Max EBML element depth (%d) reached, "
1928 "cannot parse further.\n", EBML_MAX_DEPTH);
1929 return AVERROR_UNKNOWN;
1933 level.length = (uint64_t)-1;
1934 matroska->levels[matroska->num_levels] = level;
1935 matroska->num_levels++;
1938 if (!(id = ebml_peek_id (matroska,
1939 &matroska->level_up)))
1941 if (id != seek_id) {
1942 av_log(matroska->ctx, AV_LOG_INFO,
1943 "We looked for ID=0x%x but got "
1944 "ID=0x%x (pos=%"PRIu64")",
1945 seek_id, id, seek_pos +
1946 matroska->segment_start);
1950 /* read master + parse */
1951 if ((res = ebml_read_master(matroska, &id)) < 0)
1954 case MATROSKA_ID_CUES:
1955 if (!(res = matroska_parse_index(matroska)) ||
1956 url_feof(matroska->ctx->pb)) {
1957 matroska->index_parsed = 1;
1961 case MATROSKA_ID_TAGS:
1962 if (!(res = matroska_parse_metadata(matroska)) ||
1963 url_feof(matroska->ctx->pb)) {
1964 matroska->metadata_parsed = 1;
1971 /* remove dummy level */
1972 while (matroska->num_levels) {
1973 matroska->num_levels--;
1975 matroska->levels[matroska->num_levels].length;
1976 if (length == (uint64_t)-1)
1981 if ((res = ebml_read_seek(matroska, before_pos)) < 0)
1983 matroska->peek_id = peek_id_cache;
1984 matroska->level_up = level_up;
1989 av_log(matroska->ctx, AV_LOG_INFO,
1990 "Ignoring seekhead entry for ID=0x%x\n",
1999 av_log(matroska->ctx, AV_LOG_INFO,
2000 "Unknown seekhead ID 0x%x\n", id);
2004 res = ebml_read_skip(matroska);
2008 if (matroska->level_up) {
2009 matroska->level_up--;
2018 matroska_parse_attachments(AVFormatContext *s)
2020 MatroskaDemuxContext *matroska = s->priv_data;
2024 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing attachments...\n");
2027 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2030 } else if (matroska->level_up) {
2031 matroska->level_up--;
2036 case MATROSKA_ID_ATTACHEDFILE: {
2039 uint8_t* data = NULL;
2040 int i, data_size = 0;
2043 if ((res = ebml_read_master(matroska, &id)) < 0)
2047 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2050 } else if (matroska->level_up) {
2051 matroska->level_up--;
2056 case MATROSKA_ID_FILENAME:
2057 res = ebml_read_utf8 (matroska, &id, &name);
2060 case MATROSKA_ID_FILEMIMETYPE:
2061 res = ebml_read_ascii (matroska, &id, &mime);
2064 case MATROSKA_ID_FILEDATA:
2065 res = ebml_read_binary(matroska, &id, &data, &data_size);
2069 av_log(matroska->ctx, AV_LOG_INFO,
2070 "Unknown attachedfile ID 0x%x\n", id);
2072 res = ebml_read_skip(matroska);
2076 if (matroska->level_up) {
2077 matroska->level_up--;
2082 if (!(name && mime && data && data_size > 0)) {
2083 av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
2087 st = av_new_stream(s, matroska->num_streams++);
2089 return AVERROR(ENOMEM);
2090 st->filename = av_strdup(name);
2091 st->codec->codec_id = CODEC_ID_NONE;
2092 st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
2093 st->codec->extradata = av_malloc(data_size);
2094 if(st->codec->extradata == NULL)
2095 return AVERROR(ENOMEM);
2096 st->codec->extradata_size = data_size;
2097 memcpy(st->codec->extradata, data, data_size);
2099 for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
2100 if (!strncmp(ff_mkv_mime_tags[i].str, mime,
2101 strlen(ff_mkv_mime_tags[i].str))) {
2102 st->codec->codec_id = ff_mkv_mime_tags[i].id;
2107 av_log(matroska->ctx, AV_LOG_DEBUG, "new attachment: %s, %s, size %d \n", name, mime, data_size);
2112 av_log(matroska->ctx, AV_LOG_INFO,
2113 "Unknown attachments ID 0x%x\n", id);
2117 res = ebml_read_skip(matroska);
2121 if (matroska->level_up) {
2122 matroska->level_up--;
2130 #define ARRAY_SIZE(x) (sizeof(x)/sizeof(*x))
2133 matroska_aac_profile (char *codec_id)
2135 static const char *aac_profiles[] = {
2140 for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
2141 if (strstr(codec_id, aac_profiles[profile]))
2147 matroska_aac_sri (int samplerate)
2151 for (sri=0; sri<ARRAY_SIZE(ff_mpeg4audio_sample_rates); sri++)
2152 if (ff_mpeg4audio_sample_rates[sri] == samplerate)
2158 matroska_read_header (AVFormatContext *s,
2159 AVFormatParameters *ap)
2161 MatroskaDemuxContext *matroska = s->priv_data;
2163 int version, last_level, res = 0;
2168 /* First read the EBML header. */
2170 if ((res = ebml_read_header(matroska, &doctype, &version)) < 0)
2172 if ((doctype == NULL) || strcmp(doctype, "matroska")) {
2173 av_log(matroska->ctx, AV_LOG_ERROR,
2174 "Wrong EBML doctype ('%s' != 'matroska').\n",
2175 doctype ? doctype : "(none)");
2178 return AVERROR_NOFMT;
2182 av_log(matroska->ctx, AV_LOG_ERROR,
2183 "Matroska demuxer version 2 too old for file version %d\n",
2185 return AVERROR_NOFMT;
2188 /* The next thing is a segment. */
2190 if (!(id = ebml_peek_id(matroska, &last_level)))
2191 return AVERROR(EIO);
2192 if (id == MATROSKA_ID_SEGMENT)
2196 av_log(matroska->ctx, AV_LOG_INFO,
2197 "Expected a Segment ID (0x%x), but received 0x%x!\n",
2198 MATROSKA_ID_SEGMENT, id);
2199 if ((res = ebml_read_skip(matroska)) < 0)
2203 /* We now have a Matroska segment.
2204 * Seeks are from the beginning of the segment,
2205 * after the segment ID/length. */
2206 if ((res = ebml_read_master(matroska, &id)) < 0)
2208 matroska->segment_start = url_ftell(s->pb);
2210 matroska->time_scale = 1000000;
2211 /* we've found our segment, start reading the different contents in here */
2213 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2216 } else if (matroska->level_up) {
2217 matroska->level_up--;
2223 case MATROSKA_ID_INFO: {
2224 if ((res = ebml_read_master(matroska, &id)) < 0)
2226 res = matroska_parse_info(matroska);
2230 /* track info headers */
2231 case MATROSKA_ID_TRACKS: {
2232 if ((res = ebml_read_master(matroska, &id)) < 0)
2234 res = matroska_parse_tracks(matroska);
2239 case MATROSKA_ID_CUES: {
2240 if (!matroska->index_parsed) {
2241 if ((res = ebml_read_master(matroska, &id)) < 0)
2243 res = matroska_parse_index(matroska);
2245 res = ebml_read_skip(matroska);
2250 case MATROSKA_ID_TAGS: {
2251 if (!matroska->metadata_parsed) {
2252 if ((res = ebml_read_master(matroska, &id)) < 0)
2254 res = matroska_parse_metadata(matroska);
2256 res = ebml_read_skip(matroska);
2260 /* file index (if seekable, seek to Cues/Tags to parse it) */
2261 case MATROSKA_ID_SEEKHEAD: {
2262 if ((res = ebml_read_master(matroska, &id)) < 0)
2264 res = matroska_parse_seekhead(matroska);
2268 case MATROSKA_ID_ATTACHMENTS: {
2269 if ((res = ebml_read_master(matroska, &id)) < 0)
2271 res = matroska_parse_attachments(s);
2275 case MATROSKA_ID_CLUSTER: {
2276 /* Do not read the master - this will be done in the next
2277 * call to matroska_read_packet. */
2283 av_log(matroska->ctx, AV_LOG_INFO,
2284 "Unknown matroska file header ID 0x%x\n", id);
2288 res = ebml_read_skip(matroska);
2292 if (matroska->level_up) {
2293 matroska->level_up--;
2298 /* Have we found a cluster? */
2299 if (ebml_peek_id(matroska, NULL) == MATROSKA_ID_CLUSTER) {
2301 MatroskaTrack *track;
2304 for (i = 0; i < matroska->num_tracks; i++) {
2305 enum CodecID codec_id = CODEC_ID_NONE;
2306 uint8_t *extradata = NULL;
2307 int extradata_size = 0;
2308 int extradata_offset = 0;
2309 track = matroska->tracks[i];
2310 track->stream_index = -1;
2312 /* Apply some sanity checks. */
2313 if (track->codec_id == NULL)
2316 for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
2317 if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
2318 strlen(ff_mkv_codec_tags[j].str))){
2319 codec_id= ff_mkv_codec_tags[j].id;
2324 /* Set the FourCC from the CodecID. */
2325 /* This is the MS compatibility mode which stores a
2326 * BITMAPINFOHEADER in the CodecPrivate. */
2327 if (!strcmp(track->codec_id,
2328 MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
2329 (track->codec_priv_size >= 40) &&
2330 (track->codec_priv != NULL)) {
2331 MatroskaVideoTrack *vtrack = (MatroskaVideoTrack *) track;
2333 /* Offset of biCompression. Stored in LE. */
2334 vtrack->fourcc = AV_RL32(track->codec_priv + 16);
2335 codec_id = codec_get_id(codec_bmp_tags, vtrack->fourcc);
2339 /* This is the MS compatibility mode which stores a
2340 * WAVEFORMATEX in the CodecPrivate. */
2341 else if (!strcmp(track->codec_id,
2342 MATROSKA_CODEC_ID_AUDIO_ACM) &&
2343 (track->codec_priv_size >= 18) &&
2344 (track->codec_priv != NULL)) {
2347 /* Offset of wFormatTag. Stored in LE. */
2348 tag = AV_RL16(track->codec_priv);
2349 codec_id = codec_get_id(codec_wav_tags, tag);
2353 else if (codec_id == CODEC_ID_AAC && !track->codec_priv_size) {
2354 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2355 int profile = matroska_aac_profile(track->codec_id);
2356 int sri = matroska_aac_sri(audiotrack->internal_samplerate);
2357 extradata = av_malloc(5);
2358 if (extradata == NULL)
2359 return AVERROR(ENOMEM);
2360 extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
2361 extradata[1] = ((sri&0x01) << 7) | (audiotrack->channels<<3);
2362 if (strstr(track->codec_id, "SBR")) {
2363 sri = matroska_aac_sri(audiotrack->samplerate);
2364 extradata[2] = 0x56;
2365 extradata[3] = 0xE5;
2366 extradata[4] = 0x80 | (sri<<3);
2373 else if (codec_id == CODEC_ID_TTA) {
2374 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2376 extradata_size = 30;
2377 extradata = av_mallocz(extradata_size);
2378 if (extradata == NULL)
2379 return AVERROR(ENOMEM);
2380 init_put_byte(&b, extradata, extradata_size, 1,
2381 NULL, NULL, NULL, NULL);
2382 put_buffer(&b, "TTA1", 4);
2384 put_le16(&b, audiotrack->channels);
2385 put_le16(&b, audiotrack->bitdepth);
2386 put_le32(&b, audiotrack->samplerate);
2387 put_le32(&b, matroska->ctx->duration * audiotrack->samplerate);
2390 else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
2391 codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
2392 extradata_offset = 26;
2393 track->codec_priv_size -= extradata_offset;
2396 else if (codec_id == CODEC_ID_RA_144) {
2397 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2398 audiotrack->samplerate = 8000;
2399 audiotrack->channels = 1;
2402 else if (codec_id == CODEC_ID_RA_288 ||
2403 codec_id == CODEC_ID_COOK ||
2404 codec_id == CODEC_ID_ATRAC3) {
2405 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2408 init_put_byte(&b, track->codec_priv, track->codec_priv_size, 0,
2409 NULL, NULL, NULL, NULL);
2411 audiotrack->coded_framesize = get_be32(&b);
2413 audiotrack->sub_packet_h = get_be16(&b);
2414 audiotrack->frame_size = get_be16(&b);
2415 audiotrack->sub_packet_size = get_be16(&b);
2416 audiotrack->buf = av_malloc(audiotrack->frame_size * audiotrack->sub_packet_h);
2417 if (codec_id == CODEC_ID_RA_288) {
2418 audiotrack->block_align = audiotrack->coded_framesize;
2419 track->codec_priv_size = 0;
2421 audiotrack->block_align = audiotrack->sub_packet_size;
2422 extradata_offset = 78;
2423 track->codec_priv_size -= extradata_offset;
2427 if (codec_id == CODEC_ID_NONE) {
2428 av_log(matroska->ctx, AV_LOG_INFO,
2429 "Unknown/unsupported CodecID %s.\n",
2433 track->stream_index = matroska->num_streams;
2435 matroska->num_streams++;
2436 st = av_new_stream(s, track->stream_index);
2438 return AVERROR(ENOMEM);
2439 av_set_pts_info(st, 64, matroska->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
2441 st->codec->codec_id = codec_id;
2443 if (strcmp(track->language, "und"))
2444 strcpy(st->language, track->language);
2446 if (track->flags & MATROSKA_TRACK_DEFAULT)
2447 st->disposition |= AV_DISPOSITION_DEFAULT;
2449 if (track->default_duration)
2450 av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
2451 track->default_duration, 1000000000, 30000);
2454 st->codec->extradata = extradata;
2455 st->codec->extradata_size = extradata_size;
2456 } else if(track->codec_priv && track->codec_priv_size > 0){
2457 st->codec->extradata = av_malloc(track->codec_priv_size);
2458 if(st->codec->extradata == NULL)
2459 return AVERROR(ENOMEM);
2460 st->codec->extradata_size = track->codec_priv_size;
2461 memcpy(st->codec->extradata,track->codec_priv+extradata_offset,
2462 track->codec_priv_size);
2465 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
2466 MatroskaVideoTrack *videotrack = (MatroskaVideoTrack *)track;
2468 st->codec->codec_type = CODEC_TYPE_VIDEO;
2469 st->codec->codec_tag = videotrack->fourcc;
2470 st->codec->width = videotrack->pixel_width;
2471 st->codec->height = videotrack->pixel_height;
2472 if (videotrack->display_width == 0)
2473 videotrack->display_width= videotrack->pixel_width;
2474 if (videotrack->display_height == 0)
2475 videotrack->display_height= videotrack->pixel_height;
2476 av_reduce(&st->codec->sample_aspect_ratio.num,
2477 &st->codec->sample_aspect_ratio.den,
2478 st->codec->height * videotrack->display_width,
2479 st->codec-> width * videotrack->display_height,
2481 st->need_parsing = AVSTREAM_PARSE_HEADERS;
2482 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2483 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2485 st->codec->codec_type = CODEC_TYPE_AUDIO;
2486 st->codec->sample_rate = audiotrack->samplerate;
2487 st->codec->channels = audiotrack->channels;
2488 st->codec->block_align = audiotrack->block_align;
2489 } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
2490 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
2493 /* What do we do with private data? E.g. for Vorbis. */
2498 if (matroska->index_parsed) {
2499 int i, track, stream;
2500 for (i=0; i<matroska->num_indexes; i++) {
2501 MatroskaDemuxIndex *idx = &matroska->index[i];
2502 track = matroska_find_track_by_num(matroska, idx->track);
2503 if (track < 0) continue;
2504 stream = matroska->tracks[track]->stream_index;
2505 if (stream >= 0 && stream < matroska->ctx->nb_streams)
2506 av_add_index_entry(matroska->ctx->streams[stream],
2507 idx->pos, idx->time/matroska->time_scale,
2508 0, 0, AVINDEX_KEYFRAME);
2516 matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
2517 int64_t pos, uint64_t cluster_time, uint64_t duration,
2518 int is_keyframe, int is_bframe)
2524 uint8_t *origdata = data;
2526 uint32_t *lace_size = NULL;
2527 int n, flags, laces = 0;
2531 /* first byte(s): tracknum */
2532 if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
2533 av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
2540 /* fetch track from num */
2541 track = matroska_find_track_by_num(matroska, num);
2542 if (size <= 3 || track < 0 || track >= matroska->num_tracks) {
2543 av_log(matroska->ctx, AV_LOG_INFO,
2544 "Invalid stream %d or size %u\n", track, size);
2548 stream_index = matroska->tracks[track]->stream_index;
2549 if (stream_index < 0 || stream_index >= matroska->ctx->nb_streams) {
2553 st = matroska->ctx->streams[stream_index];
2554 if (st->discard >= AVDISCARD_ALL) {
2558 if (duration == AV_NOPTS_VALUE)
2559 duration = matroska->tracks[track]->default_duration / matroska->time_scale;
2561 /* block_time (relative to cluster time) */
2562 block_time = AV_RB16(data);
2566 if (is_keyframe == -1)
2567 is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
2569 if (matroska->skip_to_keyframe) {
2570 if (!is_keyframe || st != matroska->skip_to_stream) {
2574 matroska->skip_to_keyframe = 0;
2577 switch ((flags & 0x06) >> 1) {
2578 case 0x0: /* no lacing */
2580 lace_size = av_mallocz(sizeof(int));
2581 lace_size[0] = size;
2584 case 0x1: /* xiph lacing */
2585 case 0x2: /* fixed-size lacing */
2586 case 0x3: /* EBML lacing */
2591 laces = (*data) + 1;
2594 lace_size = av_mallocz(laces * sizeof(int));
2596 switch ((flags & 0x06) >> 1) {
2597 case 0x1: /* xiph lacing */ {
2600 for (n = 0; res == 0 && n < laces - 1; n++) {
2607 lace_size[n] += temp;
2613 total += lace_size[n];
2615 lace_size[n] = size - total;
2619 case 0x2: /* fixed-size lacing */
2620 for (n = 0; n < laces; n++)
2621 lace_size[n] = size / laces;
2624 case 0x3: /* EBML lacing */ {
2626 n = matroska_ebmlnum_uint(data, size, &num);
2628 av_log(matroska->ctx, AV_LOG_INFO,
2629 "EBML block data error\n");
2634 total = lace_size[0] = num;
2635 for (n = 1; res == 0 && n < laces - 1; n++) {
2638 r = matroska_ebmlnum_sint (data, size, &snum);
2640 av_log(matroska->ctx, AV_LOG_INFO,
2641 "EBML block data error\n");
2646 lace_size[n] = lace_size[n - 1] + snum;
2647 total += lace_size[n];
2649 lace_size[n] = size - total;
2657 uint64_t timecode = AV_NOPTS_VALUE;
2659 if (cluster_time != (uint64_t)-1
2660 && (block_time >= 0 || cluster_time >= -block_time))
2661 timecode = cluster_time + block_time;
2663 for (n = 0; n < laces; n++) {
2664 if (st->codec->codec_id == CODEC_ID_RA_288 ||
2665 st->codec->codec_id == CODEC_ID_COOK ||
2666 st->codec->codec_id == CODEC_ID_ATRAC3) {
2667 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)matroska->tracks[track];
2668 int a = st->codec->block_align;
2669 int sps = audiotrack->sub_packet_size;
2670 int cfs = audiotrack->coded_framesize;
2671 int h = audiotrack->sub_packet_h;
2672 int y = audiotrack->sub_packet_cnt;
2673 int w = audiotrack->frame_size;
2676 if (!audiotrack->pkt_cnt) {
2677 if (st->codec->codec_id == CODEC_ID_RA_288)
2678 for (x=0; x<h/2; x++)
2679 memcpy(audiotrack->buf+x*2*w+y*cfs,
2682 for (x=0; x<w/sps; x++)
2683 memcpy(audiotrack->buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
2685 if (++audiotrack->sub_packet_cnt >= h) {
2686 audiotrack->sub_packet_cnt = 0;
2687 audiotrack->pkt_cnt = h*w / a;
2690 while (audiotrack->pkt_cnt) {
2691 pkt = av_mallocz(sizeof(AVPacket));
2692 av_new_packet(pkt, a);
2693 memcpy(pkt->data, audiotrack->buf
2694 + a * (h*w / a - audiotrack->pkt_cnt--), a);
2696 pkt->stream_index = stream_index;
2697 matroska_queue_packet(matroska, pkt);
2700 int result, offset = 0, ilen, olen, pkt_size = lace_size[n];
2701 uint8_t *pkt_data = data;
2703 if (matroska->tracks[track]->encoding_scope & 1) {
2704 switch (matroska->tracks[track]->encoding_algo) {
2705 case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
2706 offset = matroska->tracks[track]->encoding_settings_len;
2708 case MATROSKA_TRACK_ENCODING_COMP_LZO:
2711 ilen = lace_size[n];
2712 olen = pkt_size *= 3;
2713 pkt_data = av_realloc(pkt_data,
2714 pkt_size+LZO_OUTPUT_PADDING);
2715 result = lzo1x_decode(pkt_data, &olen, data, &ilen);
2716 } while (result==LZO_OUTPUT_FULL && pkt_size<10000000);
2726 pkt = av_mallocz(sizeof(AVPacket));
2727 /* XXX: prevent data copy... */
2728 if (av_new_packet(pkt, pkt_size+offset) < 0) {
2729 res = AVERROR(ENOMEM);
2734 memcpy (pkt->data, matroska->tracks[track]->encoding_settings, offset);
2735 memcpy (pkt->data+offset, pkt_data, pkt_size);
2738 pkt->flags = is_keyframe;
2739 pkt->stream_index = stream_index;
2741 pkt->pts = timecode;
2743 pkt->duration = duration;
2745 matroska_queue_packet(matroska, pkt);
2748 if (timecode != AV_NOPTS_VALUE)
2749 timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
2750 data += lace_size[n];
2760 matroska_parse_blockgroup (MatroskaDemuxContext *matroska,
2761 uint64_t cluster_time)
2766 int is_keyframe = PKT_FLAG_KEY, last_num_packets = matroska->num_packets;
2767 uint64_t duration = AV_NOPTS_VALUE;
2772 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing blockgroup...\n");
2775 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2778 } else if (matroska->level_up) {
2779 matroska->level_up--;
2784 /* one block inside the group. Note, block parsing is one
2785 * of the harder things, so this code is a bit complicated.
2786 * See http://www.matroska.org/ for documentation. */
2787 case MATROSKA_ID_BLOCK: {
2788 pos = url_ftell(matroska->ctx->pb);
2789 res = ebml_read_binary(matroska, &id, &data, &size);
2793 case MATROSKA_ID_BLOCKDURATION: {
2794 if ((res = ebml_read_uint(matroska, &id, &duration)) < 0)
2799 case MATROSKA_ID_BLOCKREFERENCE: {
2801 /* We've found a reference, so not even the first frame in
2802 * the lace is a key frame. */
2804 if (last_num_packets != matroska->num_packets)
2805 matroska->packets[last_num_packets]->flags = 0;
2806 if ((res = ebml_read_sint(matroska, &id, &num)) < 0)
2814 av_log(matroska->ctx, AV_LOG_INFO,
2815 "Unknown entry 0x%x in blockgroup data\n", id);
2819 res = ebml_read_skip(matroska);
2823 if (matroska->level_up) {
2824 matroska->level_up--;
2833 res = matroska_parse_block(matroska, data, size, pos, cluster_time,
2834 duration, is_keyframe, is_bframe);
2840 matroska_parse_cluster (MatroskaDemuxContext *matroska)
2844 uint64_t cluster_time = 0;
2849 av_log(matroska->ctx, AV_LOG_DEBUG,
2850 "parsing cluster at %"PRId64"\n", url_ftell(matroska->ctx->pb));
2853 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2856 } else if (matroska->level_up) {
2857 matroska->level_up--;
2862 /* cluster timecode */
2863 case MATROSKA_ID_CLUSTERTIMECODE: {
2865 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
2871 /* a group of blocks inside a cluster */
2872 case MATROSKA_ID_BLOCKGROUP:
2873 if ((res = ebml_read_master(matroska, &id)) < 0)
2875 res = matroska_parse_blockgroup(matroska, cluster_time);
2878 case MATROSKA_ID_SIMPLEBLOCK:
2879 pos = url_ftell(matroska->ctx->pb);
2880 res = ebml_read_binary(matroska, &id, &data, &size);
2882 res = matroska_parse_block(matroska, data, size, pos,
2883 cluster_time, AV_NOPTS_VALUE,
2888 av_log(matroska->ctx, AV_LOG_INFO,
2889 "Unknown entry 0x%x in cluster data\n", id);
2893 res = ebml_read_skip(matroska);
2897 if (matroska->level_up) {
2898 matroska->level_up--;
2907 matroska_read_packet (AVFormatContext *s,
2910 MatroskaDemuxContext *matroska = s->priv_data;
2914 /* Read stream until we have a packet queued. */
2915 while (matroska_deliver_packet(matroska, pkt)) {
2917 /* Have we already reached the end? */
2919 return AVERROR(EIO);
2923 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2924 return AVERROR(EIO);
2925 } else if (matroska->level_up) {
2926 matroska->level_up--;
2931 case MATROSKA_ID_CLUSTER:
2932 if ((res = ebml_read_master(matroska, &id)) < 0)
2934 if ((res = matroska_parse_cluster(matroska)) == 0)
2935 res = 1; /* Parsed one cluster, let's get out. */
2940 res = ebml_read_skip(matroska);
2944 if (matroska->level_up) {
2945 matroska->level_up--;
2958 matroska_read_seek (AVFormatContext *s, int stream_index, int64_t timestamp,
2961 MatroskaDemuxContext *matroska = s->priv_data;
2962 AVStream *st = s->streams[stream_index];
2965 /* find index entry */
2966 index = av_index_search_timestamp(st, timestamp, flags);
2970 matroska_clear_queue(matroska);
2973 url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
2974 matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
2975 matroska->skip_to_stream = st;
2976 matroska->peek_id = 0;
2981 matroska_read_close (AVFormatContext *s)
2983 MatroskaDemuxContext *matroska = s->priv_data;
2986 av_free(matroska->writing_app);
2987 av_free(matroska->muxing_app);
2988 av_free(matroska->index);
2990 matroska_clear_queue(matroska);
2992 for (n = 0; n < matroska->num_tracks; n++) {
2993 MatroskaTrack *track = matroska->tracks[n];
2994 av_free(track->codec_id);
2995 av_free(track->codec_name);
2996 av_free(track->codec_priv);
2997 av_free(track->name);
2999 if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
3000 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
3001 av_free(audiotrack->buf);
3010 AVInputFormat matroska_demuxer = {
3012 "Matroska file format",
3013 sizeof(MatroskaDemuxContext),
3015 matroska_read_header,
3016 matroska_read_packet,
3017 matroska_read_close,