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"
37 typedef struct Track {
38 MatroskaTrackType type;
40 /* Unique track number and track ID. stream_index is the index that
41 * the calling app uses for this track. */
52 unsigned char *codec_priv;
55 uint64_t default_duration;
56 MatroskaTrackFlags flags;
59 typedef struct MatroskaVideoTrack {
69 MatroskaAspectRatioMode ar_mode;
70 MatroskaEyeMode eye_mode;
75 typedef struct MatroskaAudioTrack {
80 int internal_samplerate;
84 /* real audio header */
95 typedef struct MatroskaSubtitleTrack {
98 } MatroskaSubtitleTrack;
100 #define MAX_TRACK_SIZE (FFMAX(FFMAX(sizeof(MatroskaVideoTrack), \
101 sizeof(MatroskaAudioTrack)), \
102 sizeof(MatroskaSubtitleTrack)))
104 typedef struct MatroskaLevel {
109 typedef struct MatroskaDemuxIndex {
110 uint64_t pos; /* of the corresponding *cluster*! */
111 uint16_t track; /* reference to 'num' */
112 uint64_t time; /* in nanoseconds */
113 } MatroskaDemuxIndex;
115 typedef struct MatroskaDemuxContext {
116 AVFormatContext *ctx;
120 MatroskaLevel levels[EBML_MAX_DEPTH];
128 /* timescale in the file */
131 /* num_streams is the number of streams that av_new_stream() was called
132 * for ( = that are available to the calling program). */
135 MatroskaTrack *tracks[MAX_STREAMS];
137 /* cache for ID peeking */
140 /* byte position of the segment inside the stream */
141 offset_t segment_start;
143 /* The packet queue. */
147 /* have we already parse metadata/cues/clusters? */
152 /* The index for seeking. */
154 MatroskaDemuxIndex *index;
156 /* What to skip before effectively reading a packet. */
157 int skip_to_keyframe;
158 AVStream *skip_to_stream;
159 } MatroskaDemuxContext;
162 * The first few functions handle EBML file parsing. The rest
163 * is the document interpretation. Matroska really just is a
168 * Return: the amount of levels in the hierarchy that the
169 * current element lies higher than the previous one.
170 * The opposite isn't done - that's auto-done using master
175 ebml_read_element_level_up (MatroskaDemuxContext *matroska)
177 ByteIOContext *pb = matroska->ctx->pb;
178 offset_t pos = url_ftell(pb);
181 while (matroska->num_levels > 0) {
182 MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
184 if (pos >= level->start + level->length) {
185 matroska->num_levels--;
196 * Read: an "EBML number", which is defined as a variable-length
197 * array of bytes. The first byte indicates the length by giving a
198 * number of 0-bits followed by a one. The position of the first
199 * "one" bit inside the first byte indicates the length of this
201 * Returns: num. of bytes read. < 0 on error.
205 ebml_read_num (MatroskaDemuxContext *matroska,
209 ByteIOContext *pb = matroska->ctx->pb;
210 int len_mask = 0x80, read = 1, n = 1;
213 /* the first byte tells us the length in bytes - get_byte() can normally
214 * return 0, but since that's not a valid first ebmlID byte, we can
215 * use it safely here to catch EOS. */
216 if (!(total = get_byte(pb))) {
217 /* we might encounter EOS here */
219 offset_t pos = url_ftell(pb);
220 av_log(matroska->ctx, AV_LOG_ERROR,
221 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
224 return AVERROR(EIO); /* EOS or actual I/O error */
227 /* get the length of the EBML number */
228 while (read <= max_size && !(total & len_mask)) {
232 if (read > max_size) {
233 offset_t pos = url_ftell(pb) - 1;
234 av_log(matroska->ctx, AV_LOG_ERROR,
235 "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
236 (uint8_t) total, pos, pos);
237 return AVERROR_INVALIDDATA;
240 /* read out length */
243 total = (total << 8) | get_byte(pb);
251 * Read: the element content data ID.
252 * Return: the number of bytes read or < 0 on error.
256 ebml_read_element_id (MatroskaDemuxContext *matroska,
263 /* if we re-call this, use our cached ID */
264 if (matroska->peek_id != 0) {
267 *id = matroska->peek_id;
271 /* read out the "EBML number", include tag in ID */
272 if ((read = ebml_read_num(matroska, 4, &total)) < 0)
274 *id = matroska->peek_id = total | (1 << (read * 7));
278 *level_up = ebml_read_element_level_up(matroska);
284 * Read: element content length.
285 * Return: the number of bytes read or < 0 on error.
289 ebml_read_element_length (MatroskaDemuxContext *matroska,
292 /* clear cache since we're now beyond that data point */
293 matroska->peek_id = 0;
295 /* read out the "EBML number", include tag in ID */
296 return ebml_read_num(matroska, 8, length);
300 * Return: the ID of the next element, or 0 on error.
301 * Level_up contains the amount of levels that this
302 * next element lies higher than the previous one.
306 ebml_peek_id (MatroskaDemuxContext *matroska,
311 if (ebml_read_element_id(matroska, &id, level_up) < 0)
318 * Seek to a given offset.
319 * 0 is success, -1 is failure.
323 ebml_read_seek (MatroskaDemuxContext *matroska,
326 ByteIOContext *pb = matroska->ctx->pb;
328 /* clear ID cache, if any */
329 matroska->peek_id = 0;
331 return (url_fseek(pb, offset, SEEK_SET) == offset) ? 0 : -1;
335 * Skip the next element.
336 * 0 is success, -1 is failure.
340 ebml_read_skip (MatroskaDemuxContext *matroska)
342 ByteIOContext *pb = matroska->ctx->pb;
347 if ((res = ebml_read_element_id(matroska, &id, NULL)) < 0 ||
348 (res = ebml_read_element_length(matroska, &length)) < 0)
351 url_fskip(pb, length);
357 * Read the next element as an unsigned int.
358 * 0 is success, < 0 is failure.
362 ebml_read_uint (MatroskaDemuxContext *matroska,
366 ByteIOContext *pb = matroska->ctx->pb;
367 int n = 0, size, res;
370 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
371 (res = ebml_read_element_length(matroska, &rlength)) < 0)
374 if (size < 1 || size > 8) {
375 offset_t pos = url_ftell(pb);
376 av_log(matroska->ctx, AV_LOG_ERROR,
377 "Invalid uint element size %d at position %"PRId64" (0x%"PRIx64")\n",
379 return AVERROR_INVALIDDATA;
382 /* big-endian ordening; build up number */
385 *num = (*num << 8) | get_byte(pb);
391 * Read the next element as a signed int.
392 * 0 is success, < 0 is failure.
396 ebml_read_sint (MatroskaDemuxContext *matroska,
400 ByteIOContext *pb = matroska->ctx->pb;
401 int size, n = 1, negative = 0, res;
404 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
405 (res = ebml_read_element_length(matroska, &rlength)) < 0)
408 if (size < 1 || size > 8) {
409 offset_t pos = url_ftell(pb);
410 av_log(matroska->ctx, AV_LOG_ERROR,
411 "Invalid sint element size %d at position %"PRId64" (0x%"PRIx64")\n",
413 return AVERROR_INVALIDDATA;
415 if ((*num = get_byte(pb)) & 0x80) {
420 *num = (*num << 8) | get_byte(pb);
424 *num = *num - (1LL << ((8 * size) - 1));
430 * Read the next element as a float.
431 * 0 is success, < 0 is failure.
435 ebml_read_float (MatroskaDemuxContext *matroska,
439 ByteIOContext *pb = matroska->ctx->pb;
443 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
444 (res = ebml_read_element_length(matroska, &rlength)) < 0)
449 *num= av_int2flt(get_be32(pb));
451 *num= av_int2dbl(get_be64(pb));
453 offset_t pos = url_ftell(pb);
454 av_log(matroska->ctx, AV_LOG_ERROR,
455 "Invalid float element size %d at position %"PRIu64" (0x%"PRIx64")\n",
457 return AVERROR_INVALIDDATA;
464 * Read the next element as an ASCII string.
465 * 0 is success, < 0 is failure.
469 ebml_read_ascii (MatroskaDemuxContext *matroska,
473 ByteIOContext *pb = matroska->ctx->pb;
477 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
478 (res = ebml_read_element_length(matroska, &rlength)) < 0)
482 /* ebml strings are usually not 0-terminated, so we allocate one
483 * byte more, read the string and NULL-terminate it ourselves. */
484 if (size < 0 || !(*str = av_malloc(size + 1))) {
485 av_log(matroska->ctx, AV_LOG_ERROR, "Memory allocation failed\n");
486 return AVERROR(ENOMEM);
488 if (get_buffer(pb, (uint8_t *) *str, size) != size) {
489 offset_t pos = url_ftell(pb);
490 av_log(matroska->ctx, AV_LOG_ERROR,
491 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
500 * Read the next element as a UTF-8 string.
501 * 0 is success, < 0 is failure.
505 ebml_read_utf8 (MatroskaDemuxContext *matroska,
509 return ebml_read_ascii(matroska, id, str);
513 * Read the next element as a date (nanoseconds since 1/1/2000).
514 * 0 is success, < 0 is failure.
518 ebml_read_date (MatroskaDemuxContext *matroska,
522 return ebml_read_sint(matroska, id, date);
526 * Read the next element, but only the header. The contents
527 * are supposed to be sub-elements which can be read separately.
528 * 0 is success, < 0 is failure.
532 ebml_read_master (MatroskaDemuxContext *matroska,
535 ByteIOContext *pb = matroska->ctx->pb;
537 MatroskaLevel *level;
540 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
541 (res = ebml_read_element_length(matroska, &length)) < 0)
544 /* protect... (Heaven forbids that the '>' is true) */
545 if (matroska->num_levels >= EBML_MAX_DEPTH) {
546 av_log(matroska->ctx, AV_LOG_ERROR,
547 "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
548 return AVERROR(ENOSYS);
552 level = &matroska->levels[matroska->num_levels++];
553 level->start = url_ftell(pb);
554 level->length = length;
560 * Read the next element as binary data.
561 * 0 is success, < 0 is failure.
565 ebml_read_binary (MatroskaDemuxContext *matroska,
570 ByteIOContext *pb = matroska->ctx->pb;
574 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
575 (res = ebml_read_element_length(matroska, &rlength)) < 0)
579 if (!(*binary = av_malloc(*size))) {
580 av_log(matroska->ctx, AV_LOG_ERROR,
581 "Memory allocation error\n");
582 return AVERROR(ENOMEM);
585 if (get_buffer(pb, *binary, *size) != *size) {
586 offset_t pos = url_ftell(pb);
587 av_log(matroska->ctx, AV_LOG_ERROR,
588 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
596 * Read signed/unsigned "EBML" numbers.
597 * Return: number of bytes processed, < 0 on error.
598 * XXX: use ebml_read_num().
602 matroska_ebmlnum_uint (uint8_t *data,
606 int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
610 return AVERROR_INVALIDDATA;
613 while (read <= 8 && !(total & len_mask)) {
618 return AVERROR_INVALIDDATA;
620 if ((total &= (len_mask - 1)) == len_mask - 1)
623 return AVERROR_INVALIDDATA;
627 total = (total << 8) | data[n];
640 * Same as above, but signed.
644 matroska_ebmlnum_sint (uint8_t *data,
651 /* read as unsigned number first */
652 if ((res = matroska_ebmlnum_uint(data, size, &unum)) < 0)
655 /* make signed (weird way) */
656 if (unum == (uint64_t)-1)
659 *num = unum - ((1LL << ((7 * res) - 1)) - 1);
665 * Read an EBML header.
666 * 0 is success, < 0 is failure.
670 ebml_read_header (MatroskaDemuxContext *matroska,
675 int level_up, res = 0;
683 if (!(id = ebml_peek_id(matroska, &level_up)) ||
684 level_up != 0 || id != EBML_ID_HEADER) {
685 av_log(matroska->ctx, AV_LOG_ERROR,
686 "This is not an EBML file (id=0x%x/0x%x)\n", id, EBML_ID_HEADER);
687 return AVERROR_INVALIDDATA;
689 if ((res = ebml_read_master(matroska, &id)) < 0)
693 if (!(id = ebml_peek_id(matroska, &level_up)))
701 /* is our read version uptodate? */
702 case EBML_ID_EBMLREADVERSION: {
705 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
707 if (num > EBML_VERSION) {
708 av_log(matroska->ctx, AV_LOG_ERROR,
709 "EBML version %"PRIu64" (> %d) is not supported\n",
711 return AVERROR_INVALIDDATA;
716 /* we only handle 8 byte lengths at max */
717 case EBML_ID_EBMLMAXSIZELENGTH: {
720 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
722 if (num > sizeof(uint64_t)) {
723 av_log(matroska->ctx, AV_LOG_ERROR,
724 "Integers of size %"PRIu64" (> %zd) not supported\n",
725 num, sizeof(uint64_t));
726 return AVERROR_INVALIDDATA;
731 /* we handle 4 byte IDs at max */
732 case EBML_ID_EBMLMAXIDLENGTH: {
735 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
737 if (num > sizeof(uint32_t)) {
738 av_log(matroska->ctx, AV_LOG_ERROR,
739 "IDs of size %"PRIu64" (> %zu) not supported\n",
740 num, sizeof(uint32_t));
741 return AVERROR_INVALIDDATA;
746 case EBML_ID_DOCTYPE: {
749 if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
760 case EBML_ID_DOCTYPEREADVERSION: {
763 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
771 av_log(matroska->ctx, AV_LOG_INFO,
772 "Unknown data type 0x%x in EBML header", id);
776 /* we ignore these two, as they don't tell us anything we
778 case EBML_ID_EBMLVERSION:
779 case EBML_ID_DOCTYPEVERSION:
780 res = ebml_read_skip (matroska);
790 matroska_find_track_by_num (MatroskaDemuxContext *matroska,
795 for (i = 0; i < matroska->num_tracks; i++)
796 if (matroska->tracks[i]->num == num)
804 * Put one packet in an application-supplied AVPacket struct.
805 * Returns 0 on success or -1 on failure.
809 matroska_deliver_packet (MatroskaDemuxContext *matroska,
812 if (matroska->num_packets > 0) {
813 memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
814 av_free(matroska->packets[0]);
815 if (matroska->num_packets > 1) {
816 memmove(&matroska->packets[0], &matroska->packets[1],
817 (matroska->num_packets - 1) * sizeof(AVPacket *));
819 av_realloc(matroska->packets, (matroska->num_packets - 1) *
822 av_freep(&matroska->packets);
824 matroska->num_packets--;
832 * Put a packet into our internal queue. Will be delivered to the
833 * user/application during the next get_packet() call.
837 matroska_queue_packet (MatroskaDemuxContext *matroska,
841 av_realloc(matroska->packets, (matroska->num_packets + 1) *
843 matroska->packets[matroska->num_packets] = pkt;
844 matroska->num_packets++;
848 * Free all packets in our internal queue.
851 matroska_clear_queue (MatroskaDemuxContext *matroska)
853 if (matroska->packets) {
855 for (n = 0; n < matroska->num_packets; n++) {
856 av_free_packet(matroska->packets[n]);
857 av_free(matroska->packets[n]);
859 av_free(matroska->packets);
860 matroska->packets = NULL;
861 matroska->num_packets = 0;
871 matroska_probe (AVProbeData *p)
874 int len_mask = 0x80, size = 1, n = 1;
875 uint8_t probe_data[] = { 'm', 'a', 't', 'r', 'o', 's', 'k', 'a' };
878 if (AV_RB32(p->buf) != EBML_ID_HEADER)
881 /* length of header */
883 while (size <= 8 && !(total & len_mask)) {
889 total &= (len_mask - 1);
891 total = (total << 8) | p->buf[4 + n++];
893 /* does the probe data contain the whole header? */
894 if (p->buf_size < 4 + size + total)
897 /* the header must contain the document type 'matroska'. For now,
898 * we don't parse the whole header but simply check for the
899 * availability of that array of characters inside the header.
900 * Not fully fool-proof, but good enough. */
901 for (n = 4 + size; n <= 4 + size + total - sizeof(probe_data); n++)
902 if (!memcmp (&p->buf[n], probe_data, sizeof(probe_data)))
903 return AVPROBE_SCORE_MAX;
909 * From here on, it's all XML-style DTD stuff... Needs no comments.
913 matroska_parse_info (MatroskaDemuxContext *matroska)
918 av_log(matroska->ctx, AV_LOG_DEBUG, "Parsing info...\n");
921 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
924 } else if (matroska->level_up) {
925 matroska->level_up--;
930 /* cluster timecode */
931 case MATROSKA_ID_TIMECODESCALE: {
933 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
935 matroska->time_scale = num;
939 case MATROSKA_ID_DURATION: {
941 if ((res = ebml_read_float(matroska, &id, &num)) < 0)
943 matroska->ctx->duration = num * matroska->time_scale * 1000 / AV_TIME_BASE;
947 case MATROSKA_ID_TITLE: {
949 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
951 strncpy(matroska->ctx->title, text,
952 sizeof(matroska->ctx->title)-1);
957 case MATROSKA_ID_WRITINGAPP: {
959 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
961 matroska->writing_app = text;
965 case MATROSKA_ID_MUXINGAPP: {
967 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
969 matroska->muxing_app = text;
973 case MATROSKA_ID_DATEUTC: {
975 if ((res = ebml_read_date(matroska, &id, &time)) < 0)
977 matroska->created = time;
982 av_log(matroska->ctx, AV_LOG_INFO,
983 "Unknown entry 0x%x in info header\n", id);
987 res = ebml_read_skip(matroska);
991 if (matroska->level_up) {
992 matroska->level_up--;
1001 matroska_add_stream (MatroskaDemuxContext *matroska)
1005 MatroskaTrack *track;
1007 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing track, adding stream..,\n");
1009 /* Allocate a generic track. As soon as we know its type we'll realloc. */
1010 track = av_mallocz(MAX_TRACK_SIZE);
1011 matroska->num_tracks++;
1012 strcpy(track->language, "eng");
1014 /* start with the master */
1015 if ((res = ebml_read_master(matroska, &id)) < 0)
1018 /* try reading the trackentry headers */
1020 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1023 } else if (matroska->level_up > 0) {
1024 matroska->level_up--;
1029 /* track number (unique stream ID) */
1030 case MATROSKA_ID_TRACKNUMBER: {
1032 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1038 /* track UID (unique identifier) */
1039 case MATROSKA_ID_TRACKUID: {
1041 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1047 /* track type (video, audio, combined, subtitle, etc.) */
1048 case MATROSKA_ID_TRACKTYPE: {
1050 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1052 if (track->type && track->type != num) {
1053 av_log(matroska->ctx, AV_LOG_INFO,
1054 "More than one tracktype in an entry - skip\n");
1059 switch (track->type) {
1060 case MATROSKA_TRACK_TYPE_VIDEO:
1061 case MATROSKA_TRACK_TYPE_AUDIO:
1062 case MATROSKA_TRACK_TYPE_SUBTITLE:
1064 case MATROSKA_TRACK_TYPE_COMPLEX:
1065 case MATROSKA_TRACK_TYPE_LOGO:
1066 case MATROSKA_TRACK_TYPE_CONTROL:
1068 av_log(matroska->ctx, AV_LOG_INFO,
1069 "Unknown or unsupported track type 0x%x\n",
1074 matroska->tracks[matroska->num_tracks - 1] = track;
1078 /* tracktype specific stuff for video */
1079 case MATROSKA_ID_TRACKVIDEO: {
1080 MatroskaVideoTrack *videotrack;
1082 track->type = MATROSKA_TRACK_TYPE_VIDEO;
1083 if (track->type != MATROSKA_TRACK_TYPE_VIDEO) {
1084 av_log(matroska->ctx, AV_LOG_INFO,
1085 "video data in non-video track - ignoring\n");
1086 res = AVERROR_INVALIDDATA;
1088 } else if ((res = ebml_read_master(matroska, &id)) < 0)
1090 videotrack = (MatroskaVideoTrack *)track;
1093 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1096 } else if (matroska->level_up > 0) {
1097 matroska->level_up--;
1102 /* fixme, this should be one-up, but I get it here */
1103 case MATROSKA_ID_TRACKDEFAULTDURATION: {
1105 if ((res = ebml_read_uint (matroska, &id,
1108 track->default_duration = num;
1112 /* video framerate */
1113 case MATROSKA_ID_VIDEOFRAMERATE: {
1115 if ((res = ebml_read_float(matroska, &id,
1118 if (!track->default_duration)
1119 track->default_duration = 1000000000/num;
1123 /* width of the size to display the video at */
1124 case MATROSKA_ID_VIDEODISPLAYWIDTH: {
1126 if ((res = ebml_read_uint(matroska, &id,
1129 videotrack->display_width = num;
1133 /* height of the size to display the video at */
1134 case MATROSKA_ID_VIDEODISPLAYHEIGHT: {
1136 if ((res = ebml_read_uint(matroska, &id,
1139 videotrack->display_height = num;
1143 /* width of the video in the file */
1144 case MATROSKA_ID_VIDEOPIXELWIDTH: {
1146 if ((res = ebml_read_uint(matroska, &id,
1149 videotrack->pixel_width = num;
1153 /* height of the video in the file */
1154 case MATROSKA_ID_VIDEOPIXELHEIGHT: {
1156 if ((res = ebml_read_uint(matroska, &id,
1159 videotrack->pixel_height = num;
1163 /* whether the video is interlaced */
1164 case MATROSKA_ID_VIDEOFLAGINTERLACED: {
1166 if ((res = ebml_read_uint(matroska, &id,
1171 MATROSKA_VIDEOTRACK_INTERLACED;
1174 ~MATROSKA_VIDEOTRACK_INTERLACED;
1178 /* stereo mode (whether the video has two streams,
1179 * where one is for the left eye and the other for
1180 * the right eye, which creates a 3D-like
1182 case MATROSKA_ID_VIDEOSTEREOMODE: {
1184 if ((res = ebml_read_uint(matroska, &id,
1187 if (num != MATROSKA_EYE_MODE_MONO &&
1188 num != MATROSKA_EYE_MODE_LEFT &&
1189 num != MATROSKA_EYE_MODE_RIGHT &&
1190 num != MATROSKA_EYE_MODE_BOTH) {
1191 av_log(matroska->ctx, AV_LOG_INFO,
1192 "Ignoring unknown eye mode 0x%x\n",
1196 videotrack->eye_mode = num;
1200 /* aspect ratio behaviour */
1201 case MATROSKA_ID_VIDEOASPECTRATIO: {
1203 if ((res = ebml_read_uint(matroska, &id,
1206 if (num != MATROSKA_ASPECT_RATIO_MODE_FREE &&
1207 num != MATROSKA_ASPECT_RATIO_MODE_KEEP &&
1208 num != MATROSKA_ASPECT_RATIO_MODE_FIXED) {
1209 av_log(matroska->ctx, AV_LOG_INFO,
1210 "Ignoring unknown aspect ratio 0x%x\n",
1214 videotrack->ar_mode = num;
1218 /* colorspace (only matters for raw video)
1220 case MATROSKA_ID_VIDEOCOLORSPACE: {
1222 if ((res = ebml_read_uint(matroska, &id,
1225 videotrack->fourcc = num;
1230 av_log(matroska->ctx, AV_LOG_INFO,
1231 "Unknown video track header entry "
1232 "0x%x - ignoring\n", id);
1236 res = ebml_read_skip(matroska);
1240 if (matroska->level_up) {
1241 matroska->level_up--;
1248 /* tracktype specific stuff for audio */
1249 case MATROSKA_ID_TRACKAUDIO: {
1250 MatroskaAudioTrack *audiotrack;
1252 track->type = MATROSKA_TRACK_TYPE_AUDIO;
1253 if (track->type != MATROSKA_TRACK_TYPE_AUDIO) {
1254 av_log(matroska->ctx, AV_LOG_INFO,
1255 "audio data in non-audio track - ignoring\n");
1256 res = AVERROR_INVALIDDATA;
1258 } else if ((res = ebml_read_master(matroska, &id)) < 0)
1260 audiotrack = (MatroskaAudioTrack *)track;
1261 audiotrack->channels = 1;
1262 audiotrack->samplerate = 8000;
1265 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1268 } else if (matroska->level_up > 0) {
1269 matroska->level_up--;
1275 case MATROSKA_ID_AUDIOSAMPLINGFREQ: {
1277 if ((res = ebml_read_float(matroska, &id,
1280 audiotrack->internal_samplerate =
1281 audiotrack->samplerate = num;
1285 case MATROSKA_ID_AUDIOOUTSAMPLINGFREQ: {
1287 if ((res = ebml_read_float(matroska, &id,
1290 audiotrack->samplerate = num;
1295 case MATROSKA_ID_AUDIOBITDEPTH: {
1297 if ((res = ebml_read_uint(matroska, &id,
1300 audiotrack->bitdepth = num;
1305 case MATROSKA_ID_AUDIOCHANNELS: {
1307 if ((res = ebml_read_uint(matroska, &id,
1310 audiotrack->channels = num;
1315 av_log(matroska->ctx, AV_LOG_INFO,
1316 "Unknown audio track header entry "
1317 "0x%x - ignoring\n", id);
1321 res = ebml_read_skip(matroska);
1325 if (matroska->level_up) {
1326 matroska->level_up--;
1333 /* codec identifier */
1334 case MATROSKA_ID_CODECID: {
1336 if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
1338 track->codec_id = text;
1342 /* codec private data */
1343 case MATROSKA_ID_CODECPRIVATE: {
1346 if ((res = ebml_read_binary(matroska, &id, &data, &size) < 0))
1348 track->codec_priv = data;
1349 track->codec_priv_size = size;
1353 /* name of the codec */
1354 case MATROSKA_ID_CODECNAME: {
1356 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1358 track->codec_name = text;
1362 /* name of this track */
1363 case MATROSKA_ID_TRACKNAME: {
1365 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1371 /* language (matters for audio/subtitles, mostly) */
1372 case MATROSKA_ID_TRACKLANGUAGE: {
1374 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1376 if ((end = strchr(text, '-')))
1378 if (strlen(text) == 3)
1379 strcpy(track->language, text);
1384 /* whether this is actually used */
1385 case MATROSKA_ID_TRACKFLAGENABLED: {
1387 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1390 track->flags |= MATROSKA_TRACK_ENABLED;
1392 track->flags &= ~MATROSKA_TRACK_ENABLED;
1396 /* whether it's the default for this track type */
1397 case MATROSKA_ID_TRACKFLAGDEFAULT: {
1399 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1402 track->flags |= MATROSKA_TRACK_DEFAULT;
1404 track->flags &= ~MATROSKA_TRACK_DEFAULT;
1408 /* lacing (like MPEG, where blocks don't end/start on frame
1410 case MATROSKA_ID_TRACKFLAGLACING: {
1412 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1415 track->flags |= MATROSKA_TRACK_LACING;
1417 track->flags &= ~MATROSKA_TRACK_LACING;
1421 /* default length (in time) of one data block in this track */
1422 case MATROSKA_ID_TRACKDEFAULTDURATION: {
1424 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1426 track->default_duration = num;
1431 av_log(matroska->ctx, AV_LOG_INFO,
1432 "Unknown track header entry 0x%x - ignoring\n", id);
1436 /* we ignore these because they're nothing useful. */
1437 case MATROSKA_ID_CODECINFOURL:
1438 case MATROSKA_ID_CODECDOWNLOADURL:
1439 case MATROSKA_ID_TRACKMINCACHE:
1440 case MATROSKA_ID_TRACKMAXCACHE:
1441 res = ebml_read_skip(matroska);
1445 if (matroska->level_up) {
1446 matroska->level_up--;
1455 matroska_parse_tracks (MatroskaDemuxContext *matroska)
1460 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing tracks...\n");
1463 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1466 } else if (matroska->level_up) {
1467 matroska->level_up--;
1472 /* one track within the "all-tracks" header */
1473 case MATROSKA_ID_TRACKENTRY:
1474 res = matroska_add_stream(matroska);
1478 av_log(matroska->ctx, AV_LOG_INFO,
1479 "Unknown entry 0x%x in track header\n", id);
1483 res = ebml_read_skip(matroska);
1487 if (matroska->level_up) {
1488 matroska->level_up--;
1497 matroska_parse_index (MatroskaDemuxContext *matroska)
1501 MatroskaDemuxIndex idx;
1503 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing index...\n");
1506 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1509 } else if (matroska->level_up) {
1510 matroska->level_up--;
1515 /* one single index entry ('point') */
1516 case MATROSKA_ID_POINTENTRY:
1517 if ((res = ebml_read_master(matroska, &id)) < 0)
1520 /* in the end, we hope to fill one entry with a
1521 * timestamp, a file position and a tracknum */
1522 idx.pos = (uint64_t) -1;
1523 idx.time = (uint64_t) -1;
1524 idx.track = (uint16_t) -1;
1527 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1530 } else if (matroska->level_up) {
1531 matroska->level_up--;
1536 /* one single index entry ('point') */
1537 case MATROSKA_ID_CUETIME: {
1539 if ((res = ebml_read_uint(matroska, &id,
1542 idx.time = time * matroska->time_scale;
1546 /* position in the file + track to which it
1548 case MATROSKA_ID_CUETRACKPOSITION:
1549 if ((res = ebml_read_master(matroska, &id)) < 0)
1553 if (!(id = ebml_peek_id (matroska,
1554 &matroska->level_up))) {
1557 } else if (matroska->level_up) {
1558 matroska->level_up--;
1564 case MATROSKA_ID_CUETRACK: {
1566 if ((res = ebml_read_uint(matroska,
1573 /* position in file */
1574 case MATROSKA_ID_CUECLUSTERPOSITION: {
1576 if ((res = ebml_read_uint(matroska,
1579 idx.pos = num+matroska->segment_start;
1584 av_log(matroska->ctx, AV_LOG_INFO,
1585 "Unknown entry 0x%x in "
1586 "CuesTrackPositions\n", id);
1590 res = ebml_read_skip(matroska);
1594 if (matroska->level_up) {
1595 matroska->level_up--;
1603 av_log(matroska->ctx, AV_LOG_INFO,
1604 "Unknown entry 0x%x in cuespoint "
1609 res = ebml_read_skip(matroska);
1613 if (matroska->level_up) {
1614 matroska->level_up--;
1619 /* so let's see if we got what we wanted */
1620 if (idx.pos != (uint64_t) -1 &&
1621 idx.time != (uint64_t) -1 &&
1622 idx.track != (uint16_t) -1) {
1623 if (matroska->num_indexes % 32 == 0) {
1624 /* re-allocate bigger index */
1626 av_realloc(matroska->index,
1627 (matroska->num_indexes + 32) *
1628 sizeof(MatroskaDemuxIndex));
1630 matroska->index[matroska->num_indexes] = idx;
1631 matroska->num_indexes++;
1636 av_log(matroska->ctx, AV_LOG_INFO,
1637 "Unknown entry 0x%x in cues header\n", id);
1641 res = ebml_read_skip(matroska);
1645 if (matroska->level_up) {
1646 matroska->level_up--;
1655 matroska_parse_metadata (MatroskaDemuxContext *matroska)
1661 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1664 } else if (matroska->level_up) {
1665 matroska->level_up--;
1670 /* Hm, this is unsupported... */
1672 av_log(matroska->ctx, AV_LOG_INFO,
1673 "Unknown entry 0x%x in metadata header\n", id);
1677 res = ebml_read_skip(matroska);
1681 if (matroska->level_up) {
1682 matroska->level_up--;
1691 matroska_parse_seekhead (MatroskaDemuxContext *matroska)
1696 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing seekhead...\n");
1699 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1702 } else if (matroska->level_up) {
1703 matroska->level_up--;
1708 case MATROSKA_ID_SEEKENTRY: {
1709 uint32_t seek_id = 0, peek_id_cache = 0;
1710 uint64_t seek_pos = (uint64_t) -1, t;
1712 if ((res = ebml_read_master(matroska, &id)) < 0)
1716 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1719 } else if (matroska->level_up) {
1720 matroska->level_up--;
1725 case MATROSKA_ID_SEEKID:
1726 res = ebml_read_uint(matroska, &id, &t);
1730 case MATROSKA_ID_SEEKPOSITION:
1731 res = ebml_read_uint(matroska, &id, &seek_pos);
1735 av_log(matroska->ctx, AV_LOG_INFO,
1736 "Unknown seekhead ID 0x%x\n", id);
1740 res = ebml_read_skip(matroska);
1744 if (matroska->level_up) {
1745 matroska->level_up--;
1750 if (!seek_id || seek_pos == (uint64_t) -1) {
1751 av_log(matroska->ctx, AV_LOG_INFO,
1752 "Incomplete seekhead entry (0x%x/%"PRIu64")\n",
1758 case MATROSKA_ID_CUES:
1759 case MATROSKA_ID_TAGS: {
1760 uint32_t level_up = matroska->level_up;
1761 offset_t before_pos;
1763 MatroskaLevel level;
1765 /* remember the peeked ID and the current position */
1766 peek_id_cache = matroska->peek_id;
1767 before_pos = url_ftell(matroska->ctx->pb);
1770 if ((res = ebml_read_seek(matroska, seek_pos +
1771 matroska->segment_start)) < 0)
1774 /* we don't want to lose our seekhead level, so we add
1775 * a dummy. This is a crude hack. */
1776 if (matroska->num_levels == EBML_MAX_DEPTH) {
1777 av_log(matroska->ctx, AV_LOG_INFO,
1778 "Max EBML element depth (%d) reached, "
1779 "cannot parse further.\n", EBML_MAX_DEPTH);
1780 return AVERROR_UNKNOWN;
1784 level.length = (uint64_t)-1;
1785 matroska->levels[matroska->num_levels] = level;
1786 matroska->num_levels++;
1789 if (!(id = ebml_peek_id (matroska,
1790 &matroska->level_up)))
1792 if (id != seek_id) {
1793 av_log(matroska->ctx, AV_LOG_INFO,
1794 "We looked for ID=0x%x but got "
1795 "ID=0x%x (pos=%"PRIu64")",
1796 seek_id, id, seek_pos +
1797 matroska->segment_start);
1801 /* read master + parse */
1802 if ((res = ebml_read_master(matroska, &id)) < 0)
1805 case MATROSKA_ID_CUES:
1806 if (!(res = matroska_parse_index(matroska)) ||
1807 url_feof(matroska->ctx->pb)) {
1808 matroska->index_parsed = 1;
1812 case MATROSKA_ID_TAGS:
1813 if (!(res = matroska_parse_metadata(matroska)) ||
1814 url_feof(matroska->ctx->pb)) {
1815 matroska->metadata_parsed = 1;
1822 /* remove dummy level */
1823 while (matroska->num_levels) {
1824 matroska->num_levels--;
1826 matroska->levels[matroska->num_levels].length;
1827 if (length == (uint64_t)-1)
1832 if ((res = ebml_read_seek(matroska, before_pos)) < 0)
1834 matroska->peek_id = peek_id_cache;
1835 matroska->level_up = level_up;
1840 av_log(matroska->ctx, AV_LOG_INFO,
1841 "Ignoring seekhead entry for ID=0x%x\n",
1850 av_log(matroska->ctx, AV_LOG_INFO,
1851 "Unknown seekhead ID 0x%x\n", id);
1855 res = ebml_read_skip(matroska);
1859 if (matroska->level_up) {
1860 matroska->level_up--;
1869 matroska_parse_attachments(AVFormatContext *s)
1871 MatroskaDemuxContext *matroska = s->priv_data;
1875 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing attachments...\n");
1878 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1881 } else if (matroska->level_up) {
1882 matroska->level_up--;
1887 case MATROSKA_ID_ATTACHEDFILE: {
1890 uint8_t* data = NULL;
1891 int i, data_size = 0;
1894 if ((res = ebml_read_master(matroska, &id)) < 0)
1898 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1901 } else if (matroska->level_up) {
1902 matroska->level_up--;
1907 case MATROSKA_ID_FILENAME:
1908 res = ebml_read_utf8 (matroska, &id, &name);
1911 case MATROSKA_ID_FILEMIMETYPE:
1912 res = ebml_read_ascii (matroska, &id, &mime);
1915 case MATROSKA_ID_FILEDATA:
1916 res = ebml_read_binary(matroska, &id, &data, &data_size);
1920 av_log(matroska->ctx, AV_LOG_INFO,
1921 "Unknown attachedfile ID 0x%x\n", id);
1923 res = ebml_read_skip(matroska);
1927 if (matroska->level_up) {
1928 matroska->level_up--;
1933 if (!(name && mime && data && data_size > 0)) {
1934 av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");
1938 st = av_new_stream(s, matroska->num_streams++);
1940 return AVERROR(ENOMEM);
1941 st->filename = av_strdup(name);
1942 st->codec->codec_id = CODEC_ID_NONE;
1943 st->codec->codec_type = CODEC_TYPE_ATTACHMENT;
1944 st->codec->extradata = av_malloc(data_size);
1945 if(st->codec->extradata == NULL)
1946 return AVERROR(ENOMEM);
1947 st->codec->extradata_size = data_size;
1948 memcpy(st->codec->extradata, data, data_size);
1950 for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {
1951 if (!strncmp(ff_mkv_mime_tags[i].str, mime,
1952 strlen(ff_mkv_mime_tags[i].str))) {
1953 st->codec->codec_id = ff_mkv_mime_tags[i].id;
1958 av_log(matroska->ctx, AV_LOG_DEBUG, "new attachment: %s, %s, size %d \n", name, mime, data_size);
1963 av_log(matroska->ctx, AV_LOG_INFO,
1964 "Unknown attachments ID 0x%x\n", id);
1968 res = ebml_read_skip(matroska);
1972 if (matroska->level_up) {
1973 matroska->level_up--;
1981 #define ARRAY_SIZE(x) (sizeof(x)/sizeof(*x))
1984 matroska_aac_profile (char *codec_id)
1986 static const char *aac_profiles[] = {
1991 for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
1992 if (strstr(codec_id, aac_profiles[profile]))
1998 matroska_aac_sri (int samplerate)
2000 static const int aac_sample_rates[] = {
2001 96000, 88200, 64000, 48000, 44100, 32000,
2002 24000, 22050, 16000, 12000, 11025, 8000,
2006 for (sri=0; sri<ARRAY_SIZE(aac_sample_rates); sri++)
2007 if (aac_sample_rates[sri] == samplerate)
2013 matroska_read_header (AVFormatContext *s,
2014 AVFormatParameters *ap)
2016 MatroskaDemuxContext *matroska = s->priv_data;
2018 int version, last_level, res = 0;
2023 /* First read the EBML header. */
2025 if ((res = ebml_read_header(matroska, &doctype, &version)) < 0)
2027 if ((doctype == NULL) || strcmp(doctype, "matroska")) {
2028 av_log(matroska->ctx, AV_LOG_ERROR,
2029 "Wrong EBML doctype ('%s' != 'matroska').\n",
2030 doctype ? doctype : "(none)");
2033 return AVERROR_NOFMT;
2037 av_log(matroska->ctx, AV_LOG_ERROR,
2038 "Matroska demuxer version 2 too old for file version %d\n",
2040 return AVERROR_NOFMT;
2043 /* The next thing is a segment. */
2045 if (!(id = ebml_peek_id(matroska, &last_level)))
2046 return AVERROR(EIO);
2047 if (id == MATROSKA_ID_SEGMENT)
2051 av_log(matroska->ctx, AV_LOG_INFO,
2052 "Expected a Segment ID (0x%x), but received 0x%x!\n",
2053 MATROSKA_ID_SEGMENT, id);
2054 if ((res = ebml_read_skip(matroska)) < 0)
2058 /* We now have a Matroska segment.
2059 * Seeks are from the beginning of the segment,
2060 * after the segment ID/length. */
2061 if ((res = ebml_read_master(matroska, &id)) < 0)
2063 matroska->segment_start = url_ftell(s->pb);
2065 matroska->time_scale = 1000000;
2066 /* we've found our segment, start reading the different contents in here */
2068 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2071 } else if (matroska->level_up) {
2072 matroska->level_up--;
2078 case MATROSKA_ID_INFO: {
2079 if ((res = ebml_read_master(matroska, &id)) < 0)
2081 res = matroska_parse_info(matroska);
2085 /* track info headers */
2086 case MATROSKA_ID_TRACKS: {
2087 if ((res = ebml_read_master(matroska, &id)) < 0)
2089 res = matroska_parse_tracks(matroska);
2094 case MATROSKA_ID_CUES: {
2095 if (!matroska->index_parsed) {
2096 if ((res = ebml_read_master(matroska, &id)) < 0)
2098 res = matroska_parse_index(matroska);
2100 res = ebml_read_skip(matroska);
2105 case MATROSKA_ID_TAGS: {
2106 if (!matroska->metadata_parsed) {
2107 if ((res = ebml_read_master(matroska, &id)) < 0)
2109 res = matroska_parse_metadata(matroska);
2111 res = ebml_read_skip(matroska);
2115 /* file index (if seekable, seek to Cues/Tags to parse it) */
2116 case MATROSKA_ID_SEEKHEAD: {
2117 if ((res = ebml_read_master(matroska, &id)) < 0)
2119 res = matroska_parse_seekhead(matroska);
2123 case MATROSKA_ID_ATTACHMENTS: {
2124 if ((res = ebml_read_master(matroska, &id)) < 0)
2126 res = matroska_parse_attachments(s);
2130 case MATROSKA_ID_CLUSTER: {
2131 /* Do not read the master - this will be done in the next
2132 * call to matroska_read_packet. */
2138 av_log(matroska->ctx, AV_LOG_INFO,
2139 "Unknown matroska file header ID 0x%x\n", id);
2143 res = ebml_read_skip(matroska);
2147 if (matroska->level_up) {
2148 matroska->level_up--;
2153 /* Have we found a cluster? */
2154 if (ebml_peek_id(matroska, NULL) == MATROSKA_ID_CLUSTER) {
2156 MatroskaTrack *track;
2159 for (i = 0; i < matroska->num_tracks; i++) {
2160 enum CodecID codec_id = CODEC_ID_NONE;
2161 uint8_t *extradata = NULL;
2162 int extradata_size = 0;
2163 int extradata_offset = 0;
2164 track = matroska->tracks[i];
2165 track->stream_index = -1;
2167 /* Apply some sanity checks. */
2168 if (track->codec_id == NULL)
2171 for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){
2172 if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
2173 strlen(ff_mkv_codec_tags[j].str))){
2174 codec_id= ff_mkv_codec_tags[j].id;
2179 /* Set the FourCC from the CodecID. */
2180 /* This is the MS compatibility mode which stores a
2181 * BITMAPINFOHEADER in the CodecPrivate. */
2182 if (!strcmp(track->codec_id,
2183 MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
2184 (track->codec_priv_size >= 40) &&
2185 (track->codec_priv != NULL)) {
2186 MatroskaVideoTrack *vtrack = (MatroskaVideoTrack *) track;
2188 /* Offset of biCompression. Stored in LE. */
2189 vtrack->fourcc = AV_RL32(track->codec_priv + 16);
2190 codec_id = codec_get_id(codec_bmp_tags, vtrack->fourcc);
2194 /* This is the MS compatibility mode which stores a
2195 * WAVEFORMATEX in the CodecPrivate. */
2196 else if (!strcmp(track->codec_id,
2197 MATROSKA_CODEC_ID_AUDIO_ACM) &&
2198 (track->codec_priv_size >= 18) &&
2199 (track->codec_priv != NULL)) {
2202 /* Offset of wFormatTag. Stored in LE. */
2203 tag = AV_RL16(track->codec_priv);
2204 codec_id = codec_get_id(codec_wav_tags, tag);
2208 else if (codec_id == CODEC_ID_AAC && !track->codec_priv_size) {
2209 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2210 int profile = matroska_aac_profile(track->codec_id);
2211 int sri = matroska_aac_sri(audiotrack->internal_samplerate);
2212 extradata = av_malloc(5);
2213 if (extradata == NULL)
2214 return AVERROR(ENOMEM);
2215 extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
2216 extradata[1] = ((sri&0x01) << 7) | (audiotrack->channels<<3);
2217 if (strstr(track->codec_id, "SBR")) {
2218 sri = matroska_aac_sri(audiotrack->samplerate);
2219 extradata[2] = 0x56;
2220 extradata[3] = 0xE5;
2221 extradata[4] = 0x80 | (sri<<3);
2228 else if (codec_id == CODEC_ID_TTA) {
2229 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2231 extradata_size = 30;
2232 extradata = av_mallocz(extradata_size);
2233 if (extradata == NULL)
2234 return AVERROR(ENOMEM);
2235 init_put_byte(&b, extradata, extradata_size, 1,
2236 NULL, NULL, NULL, NULL);
2237 put_buffer(&b, "TTA1", 4);
2239 put_le16(&b, audiotrack->channels);
2240 put_le16(&b, audiotrack->bitdepth);
2241 put_le32(&b, audiotrack->samplerate);
2242 put_le32(&b, matroska->ctx->duration * audiotrack->samplerate);
2245 else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
2246 codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
2247 extradata_offset = 26;
2248 track->codec_priv_size -= extradata_offset;
2251 else if (codec_id == CODEC_ID_RA_144) {
2252 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2253 audiotrack->samplerate = 8000;
2254 audiotrack->channels = 1;
2257 else if (codec_id == CODEC_ID_RA_288 ||
2258 codec_id == CODEC_ID_COOK ||
2259 codec_id == CODEC_ID_ATRAC3) {
2260 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2263 init_put_byte(&b, track->codec_priv, track->codec_priv_size, 0,
2264 NULL, NULL, NULL, NULL);
2266 audiotrack->coded_framesize = get_be32(&b);
2268 audiotrack->sub_packet_h = get_be16(&b);
2269 audiotrack->frame_size = get_be16(&b);
2270 audiotrack->sub_packet_size = get_be16(&b);
2271 audiotrack->buf = av_malloc(audiotrack->frame_size * audiotrack->sub_packet_h);
2272 if (codec_id == CODEC_ID_RA_288) {
2273 audiotrack->block_align = audiotrack->coded_framesize;
2274 track->codec_priv_size = 0;
2276 audiotrack->block_align = audiotrack->sub_packet_size;
2277 extradata_offset = 78;
2278 track->codec_priv_size -= extradata_offset;
2282 if (codec_id == CODEC_ID_NONE) {
2283 av_log(matroska->ctx, AV_LOG_INFO,
2284 "Unknown/unsupported CodecID %s.\n",
2288 track->stream_index = matroska->num_streams;
2290 matroska->num_streams++;
2291 st = av_new_stream(s, track->stream_index);
2293 return AVERROR(ENOMEM);
2294 av_set_pts_info(st, 64, matroska->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
2296 st->codec->codec_id = codec_id;
2298 if (strcmp(track->language, "und"))
2299 strcpy(st->language, track->language);
2301 if (track->flags & MATROSKA_TRACK_DEFAULT)
2302 st->disposition |= AV_DISPOSITION_DEFAULT;
2304 if (track->default_duration)
2305 av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
2306 track->default_duration, 1000000000, 30000);
2309 st->codec->extradata = extradata;
2310 st->codec->extradata_size = extradata_size;
2311 } else if(track->codec_priv && track->codec_priv_size > 0){
2312 st->codec->extradata = av_malloc(track->codec_priv_size);
2313 if(st->codec->extradata == NULL)
2314 return AVERROR(ENOMEM);
2315 st->codec->extradata_size = track->codec_priv_size;
2316 memcpy(st->codec->extradata,track->codec_priv+extradata_offset,
2317 track->codec_priv_size);
2320 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
2321 MatroskaVideoTrack *videotrack = (MatroskaVideoTrack *)track;
2323 st->codec->codec_type = CODEC_TYPE_VIDEO;
2324 st->codec->codec_tag = videotrack->fourcc;
2325 st->codec->width = videotrack->pixel_width;
2326 st->codec->height = videotrack->pixel_height;
2327 if (videotrack->display_width == 0)
2328 videotrack->display_width= videotrack->pixel_width;
2329 if (videotrack->display_height == 0)
2330 videotrack->display_height= videotrack->pixel_height;
2331 av_reduce(&st->codec->sample_aspect_ratio.num,
2332 &st->codec->sample_aspect_ratio.den,
2333 st->codec->height * videotrack->display_width,
2334 st->codec-> width * videotrack->display_height,
2336 st->need_parsing = AVSTREAM_PARSE_HEADERS;
2337 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2338 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2340 st->codec->codec_type = CODEC_TYPE_AUDIO;
2341 st->codec->sample_rate = audiotrack->samplerate;
2342 st->codec->channels = audiotrack->channels;
2343 st->codec->block_align = audiotrack->block_align;
2344 } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
2345 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
2348 /* What do we do with private data? E.g. for Vorbis. */
2353 if (matroska->index_parsed) {
2354 int i, track, stream;
2355 for (i=0; i<matroska->num_indexes; i++) {
2356 MatroskaDemuxIndex *idx = &matroska->index[i];
2357 track = matroska_find_track_by_num(matroska, idx->track);
2358 stream = matroska->tracks[track]->stream_index;
2360 av_add_index_entry(matroska->ctx->streams[stream],
2361 idx->pos, idx->time/matroska->time_scale,
2362 0, 0, AVINDEX_KEYFRAME);
2370 matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
2371 int64_t pos, uint64_t cluster_time, uint64_t duration,
2372 int is_keyframe, int is_bframe)
2378 uint8_t *origdata = data;
2380 uint32_t *lace_size = NULL;
2381 int n, flags, laces = 0;
2384 /* first byte(s): tracknum */
2385 if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
2386 av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
2393 /* fetch track from num */
2394 track = matroska_find_track_by_num(matroska, num);
2395 if (size <= 3 || track < 0 || track >= matroska->num_tracks) {
2396 av_log(matroska->ctx, AV_LOG_INFO,
2397 "Invalid stream %d or size %u\n", track, size);
2401 if (matroska->tracks[track]->stream_index < 0) {
2405 st = matroska->ctx->streams[matroska->tracks[track]->stream_index];
2406 if (st->discard >= AVDISCARD_ALL) {
2410 if (duration == AV_NOPTS_VALUE)
2411 duration = matroska->tracks[track]->default_duration / matroska->time_scale;
2413 /* block_time (relative to cluster time) */
2414 block_time = AV_RB16(data);
2418 if (is_keyframe == -1)
2419 is_keyframe = flags & 0x80 ? PKT_FLAG_KEY : 0;
2421 if (matroska->skip_to_keyframe) {
2422 if (!is_keyframe || st != matroska->skip_to_stream) {
2426 matroska->skip_to_keyframe = 0;
2429 switch ((flags & 0x06) >> 1) {
2430 case 0x0: /* no lacing */
2432 lace_size = av_mallocz(sizeof(int));
2433 lace_size[0] = size;
2436 case 0x1: /* xiph lacing */
2437 case 0x2: /* fixed-size lacing */
2438 case 0x3: /* EBML lacing */
2443 laces = (*data) + 1;
2446 lace_size = av_mallocz(laces * sizeof(int));
2448 switch ((flags & 0x06) >> 1) {
2449 case 0x1: /* xiph lacing */ {
2452 for (n = 0; res == 0 && n < laces - 1; n++) {
2459 lace_size[n] += temp;
2465 total += lace_size[n];
2467 lace_size[n] = size - total;
2471 case 0x2: /* fixed-size lacing */
2472 for (n = 0; n < laces; n++)
2473 lace_size[n] = size / laces;
2476 case 0x3: /* EBML lacing */ {
2478 n = matroska_ebmlnum_uint(data, size, &num);
2480 av_log(matroska->ctx, AV_LOG_INFO,
2481 "EBML block data error\n");
2486 total = lace_size[0] = num;
2487 for (n = 1; res == 0 && n < laces - 1; n++) {
2490 r = matroska_ebmlnum_sint (data, size, &snum);
2492 av_log(matroska->ctx, AV_LOG_INFO,
2493 "EBML block data error\n");
2498 lace_size[n] = lace_size[n - 1] + snum;
2499 total += lace_size[n];
2501 lace_size[n] = size - total;
2509 uint64_t timecode = AV_NOPTS_VALUE;
2511 if (cluster_time != (uint64_t)-1
2512 && (block_time >= 0 || cluster_time >= -block_time))
2513 timecode = cluster_time + block_time;
2515 for (n = 0; n < laces; n++) {
2516 if (st->codec->codec_id == CODEC_ID_RA_288 ||
2517 st->codec->codec_id == CODEC_ID_COOK ||
2518 st->codec->codec_id == CODEC_ID_ATRAC3) {
2519 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)matroska->tracks[track];
2520 int a = st->codec->block_align;
2521 int sps = audiotrack->sub_packet_size;
2522 int cfs = audiotrack->coded_framesize;
2523 int h = audiotrack->sub_packet_h;
2524 int y = audiotrack->sub_packet_cnt;
2525 int w = audiotrack->frame_size;
2528 if (!audiotrack->pkt_cnt) {
2529 if (st->codec->codec_id == CODEC_ID_RA_288)
2530 for (x=0; x<h/2; x++)
2531 memcpy(audiotrack->buf+x*2*w+y*cfs,
2534 for (x=0; x<w/sps; x++)
2535 memcpy(audiotrack->buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
2537 if (++audiotrack->sub_packet_cnt >= h) {
2538 audiotrack->sub_packet_cnt = 0;
2539 audiotrack->pkt_cnt = h*w / a;
2542 while (audiotrack->pkt_cnt) {
2543 pkt = av_mallocz(sizeof(AVPacket));
2544 av_new_packet(pkt, a);
2545 memcpy(pkt->data, audiotrack->buf
2546 + a * (h*w / a - audiotrack->pkt_cnt--), a);
2548 pkt->stream_index = matroska->tracks[track]->stream_index;
2549 matroska_queue_packet(matroska, pkt);
2554 pkt = av_mallocz(sizeof(AVPacket));
2555 /* XXX: prevent data copy... */
2556 if (av_new_packet(pkt, lace_size[n]-offset) < 0) {
2557 res = AVERROR(ENOMEM);
2561 memcpy (pkt->data, data+offset, lace_size[n]-offset);
2564 pkt->flags = is_keyframe;
2565 pkt->stream_index = matroska->tracks[track]->stream_index;
2567 pkt->pts = timecode;
2569 pkt->duration = duration;
2571 matroska_queue_packet(matroska, pkt);
2574 if (timecode != AV_NOPTS_VALUE)
2575 timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
2576 data += lace_size[n];
2586 matroska_parse_blockgroup (MatroskaDemuxContext *matroska,
2587 uint64_t cluster_time)
2592 int is_keyframe = PKT_FLAG_KEY, last_num_packets = matroska->num_packets;
2593 uint64_t duration = AV_NOPTS_VALUE;
2598 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing blockgroup...\n");
2601 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2604 } else if (matroska->level_up) {
2605 matroska->level_up--;
2610 /* one block inside the group. Note, block parsing is one
2611 * of the harder things, so this code is a bit complicated.
2612 * See http://www.matroska.org/ for documentation. */
2613 case MATROSKA_ID_BLOCK: {
2614 pos = url_ftell(matroska->ctx->pb);
2615 res = ebml_read_binary(matroska, &id, &data, &size);
2619 case MATROSKA_ID_BLOCKDURATION: {
2620 if ((res = ebml_read_uint(matroska, &id, &duration)) < 0)
2625 case MATROSKA_ID_BLOCKREFERENCE: {
2627 /* We've found a reference, so not even the first frame in
2628 * the lace is a key frame. */
2630 if (last_num_packets != matroska->num_packets)
2631 matroska->packets[last_num_packets]->flags = 0;
2632 if ((res = ebml_read_sint(matroska, &id, &num)) < 0)
2640 av_log(matroska->ctx, AV_LOG_INFO,
2641 "Unknown entry 0x%x in blockgroup data\n", id);
2645 res = ebml_read_skip(matroska);
2649 if (matroska->level_up) {
2650 matroska->level_up--;
2659 res = matroska_parse_block(matroska, data, size, pos, cluster_time,
2660 duration, is_keyframe, is_bframe);
2666 matroska_parse_cluster (MatroskaDemuxContext *matroska)
2670 uint64_t cluster_time = 0;
2675 av_log(matroska->ctx, AV_LOG_DEBUG,
2676 "parsing cluster at %"PRId64"\n", url_ftell(matroska->ctx->pb));
2679 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2682 } else if (matroska->level_up) {
2683 matroska->level_up--;
2688 /* cluster timecode */
2689 case MATROSKA_ID_CLUSTERTIMECODE: {
2691 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
2697 /* a group of blocks inside a cluster */
2698 case MATROSKA_ID_BLOCKGROUP:
2699 if ((res = ebml_read_master(matroska, &id)) < 0)
2701 res = matroska_parse_blockgroup(matroska, cluster_time);
2704 case MATROSKA_ID_SIMPLEBLOCK:
2705 pos = url_ftell(matroska->ctx->pb);
2706 res = ebml_read_binary(matroska, &id, &data, &size);
2708 res = matroska_parse_block(matroska, data, size, pos,
2709 cluster_time, AV_NOPTS_VALUE,
2714 av_log(matroska->ctx, AV_LOG_INFO,
2715 "Unknown entry 0x%x in cluster data\n", id);
2719 res = ebml_read_skip(matroska);
2723 if (matroska->level_up) {
2724 matroska->level_up--;
2733 matroska_read_packet (AVFormatContext *s,
2736 MatroskaDemuxContext *matroska = s->priv_data;
2740 /* Read stream until we have a packet queued. */
2741 while (matroska_deliver_packet(matroska, pkt)) {
2743 /* Have we already reached the end? */
2745 return AVERROR(EIO);
2749 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2750 return AVERROR(EIO);
2751 } else if (matroska->level_up) {
2752 matroska->level_up--;
2757 case MATROSKA_ID_CLUSTER:
2758 if ((res = ebml_read_master(matroska, &id)) < 0)
2760 if ((res = matroska_parse_cluster(matroska)) == 0)
2761 res = 1; /* Parsed one cluster, let's get out. */
2766 res = ebml_read_skip(matroska);
2770 if (matroska->level_up) {
2771 matroska->level_up--;
2784 matroska_read_seek (AVFormatContext *s, int stream_index, int64_t timestamp,
2787 MatroskaDemuxContext *matroska = s->priv_data;
2788 AVStream *st = s->streams[stream_index];
2791 /* find index entry */
2792 index = av_index_search_timestamp(st, timestamp, flags);
2796 matroska_clear_queue(matroska);
2799 url_fseek(s->pb, st->index_entries[index].pos, SEEK_SET);
2800 matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
2801 matroska->skip_to_stream = st;
2802 matroska->peek_id = 0;
2807 matroska_read_close (AVFormatContext *s)
2809 MatroskaDemuxContext *matroska = s->priv_data;
2812 av_free(matroska->writing_app);
2813 av_free(matroska->muxing_app);
2814 av_free(matroska->index);
2816 matroska_clear_queue(matroska);
2818 for (n = 0; n < matroska->num_tracks; n++) {
2819 MatroskaTrack *track = matroska->tracks[n];
2820 av_free(track->codec_id);
2821 av_free(track->codec_name);
2822 av_free(track->codec_priv);
2823 av_free(track->name);
2825 if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2826 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2827 av_free(audiotrack->buf);
2836 AVInputFormat matroska_demuxer = {
2838 "Matroska file format",
2839 sizeof(MatroskaDemuxContext),
2841 matroska_read_header,
2842 matroska_read_packet,
2843 matroska_read_close,