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 {
100 } MatroskaSubtitleTrack;
102 #define MAX_TRACK_SIZE (FFMAX(FFMAX(sizeof(MatroskaVideoTrack), \
103 sizeof(MatroskaAudioTrack)), \
104 sizeof(MatroskaSubtitleTrack)))
106 typedef struct MatroskaLevel {
111 typedef struct MatroskaDemuxIndex {
112 uint64_t pos; /* of the corresponding *cluster*! */
113 uint16_t track; /* reference to 'num' */
114 uint64_t time; /* in nanoseconds */
115 } MatroskaDemuxIndex;
117 typedef struct MatroskaDemuxContext {
118 AVFormatContext *ctx;
122 MatroskaLevel levels[EBML_MAX_DEPTH];
130 /* timescale in the file */
133 /* num_streams is the number of streams that av_new_stream() was called
134 * for ( = that are available to the calling program). */
137 MatroskaTrack *tracks[MAX_STREAMS];
139 /* cache for ID peeking */
142 /* byte position of the segment inside the stream */
143 offset_t segment_start;
145 /* The packet queue. */
149 /* have we already parse metadata/cues/clusters? */
154 /* The index for seeking. */
156 MatroskaDemuxIndex *index;
158 /* What to skip before effectively reading a packet. */
159 int skip_to_keyframe;
160 AVStream *skip_to_stream;
161 } MatroskaDemuxContext;
164 * The first few functions handle EBML file parsing. The rest
165 * is the document interpretation. Matroska really just is a
170 * Return: the amount of levels in the hierarchy that the
171 * current element lies higher than the previous one.
172 * The opposite isn't done - that's auto-done using master
177 ebml_read_element_level_up (MatroskaDemuxContext *matroska)
179 ByteIOContext *pb = &matroska->ctx->pb;
180 offset_t pos = url_ftell(pb);
183 while (matroska->num_levels > 0) {
184 MatroskaLevel *level = &matroska->levels[matroska->num_levels - 1];
186 if (pos >= level->start + level->length) {
187 matroska->num_levels--;
198 * Read: an "EBML number", which is defined as a variable-length
199 * array of bytes. The first byte indicates the length by giving a
200 * number of 0-bits followed by a one. The position of the first
201 * "one" bit inside the first byte indicates the length of this
203 * Returns: num. of bytes read. < 0 on error.
207 ebml_read_num (MatroskaDemuxContext *matroska,
211 ByteIOContext *pb = &matroska->ctx->pb;
212 int len_mask = 0x80, read = 1, n = 1;
215 /* the first byte tells us the length in bytes - get_byte() can normally
216 * return 0, but since that's not a valid first ebmlID byte, we can
217 * use it safely here to catch EOS. */
218 if (!(total = get_byte(pb))) {
219 /* we might encounter EOS here */
221 offset_t pos = url_ftell(pb);
222 av_log(matroska->ctx, AV_LOG_ERROR,
223 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n",
226 return AVERROR_IO; /* EOS or actual I/O error */
229 /* get the length of the EBML number */
230 while (read <= max_size && !(total & len_mask)) {
234 if (read > max_size) {
235 offset_t pos = url_ftell(pb) - 1;
236 av_log(matroska->ctx, AV_LOG_ERROR,
237 "Invalid EBML number size tag 0x%02x at pos %"PRIu64" (0x%"PRIx64")\n",
238 (uint8_t) total, pos, pos);
239 return AVERROR_INVALIDDATA;
242 /* read out length */
245 total = (total << 8) | get_byte(pb);
253 * Read: the element content data ID.
254 * Return: the number of bytes read or < 0 on error.
258 ebml_read_element_id (MatroskaDemuxContext *matroska,
265 /* if we re-call this, use our cached ID */
266 if (matroska->peek_id != 0) {
269 *id = matroska->peek_id;
273 /* read out the "EBML number", include tag in ID */
274 if ((read = ebml_read_num(matroska, 4, &total)) < 0)
276 *id = matroska->peek_id = total | (1 << (read * 7));
280 *level_up = ebml_read_element_level_up(matroska);
286 * Read: element content length.
287 * Return: the number of bytes read or < 0 on error.
291 ebml_read_element_length (MatroskaDemuxContext *matroska,
294 /* clear cache since we're now beyond that data point */
295 matroska->peek_id = 0;
297 /* read out the "EBML number", include tag in ID */
298 return ebml_read_num(matroska, 8, length);
302 * Return: the ID of the next element, or 0 on error.
303 * Level_up contains the amount of levels that this
304 * next element lies higher than the previous one.
308 ebml_peek_id (MatroskaDemuxContext *matroska,
313 assert(level_up != NULL);
315 if (ebml_read_element_id(matroska, &id, level_up) < 0)
322 * Seek to a given offset.
323 * 0 is success, -1 is failure.
327 ebml_read_seek (MatroskaDemuxContext *matroska,
330 ByteIOContext *pb = &matroska->ctx->pb;
332 /* clear ID cache, if any */
333 matroska->peek_id = 0;
335 return (url_fseek(pb, offset, SEEK_SET) == offset) ? 0 : -1;
339 * Skip the next element.
340 * 0 is success, -1 is failure.
344 ebml_read_skip (MatroskaDemuxContext *matroska)
346 ByteIOContext *pb = &matroska->ctx->pb;
351 if ((res = ebml_read_element_id(matroska, &id, NULL)) < 0 ||
352 (res = ebml_read_element_length(matroska, &length)) < 0)
355 url_fskip(pb, length);
361 * Read the next element as an unsigned int.
362 * 0 is success, < 0 is failure.
366 ebml_read_uint (MatroskaDemuxContext *matroska,
370 ByteIOContext *pb = &matroska->ctx->pb;
371 int n = 0, size, res;
374 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
375 (res = ebml_read_element_length(matroska, &rlength)) < 0)
378 if (size < 1 || size > 8) {
379 offset_t pos = url_ftell(pb);
380 av_log(matroska->ctx, AV_LOG_ERROR,
381 "Invalid uint element size %d at position %"PRId64" (0x%"PRIx64")\n",
383 return AVERROR_INVALIDDATA;
386 /* big-endian ordening; build up number */
389 *num = (*num << 8) | get_byte(pb);
395 * Read the next element as a signed int.
396 * 0 is success, < 0 is failure.
400 ebml_read_sint (MatroskaDemuxContext *matroska,
404 ByteIOContext *pb = &matroska->ctx->pb;
405 int size, n = 1, negative = 0, res;
408 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
409 (res = ebml_read_element_length(matroska, &rlength)) < 0)
412 if (size < 1 || size > 8) {
413 offset_t pos = url_ftell(pb);
414 av_log(matroska->ctx, AV_LOG_ERROR,
415 "Invalid sint element size %d at position %"PRId64" (0x%"PRIx64")\n",
417 return AVERROR_INVALIDDATA;
419 if ((*num = get_byte(pb)) & 0x80) {
424 *num = (*num << 8) | get_byte(pb);
428 *num = *num - (1LL << ((8 * size) - 1));
434 * Read the next element as a float.
435 * 0 is success, < 0 is failure.
439 ebml_read_float (MatroskaDemuxContext *matroska,
443 ByteIOContext *pb = &matroska->ctx->pb;
447 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
448 (res = ebml_read_element_length(matroska, &rlength)) < 0)
453 *num= av_int2flt(get_be32(pb));
455 *num= av_int2dbl(get_be64(pb));
457 offset_t pos = url_ftell(pb);
458 av_log(matroska->ctx, AV_LOG_ERROR,
459 "Invalid float element size %d at position %"PRIu64" (0x%"PRIx64")\n",
461 return AVERROR_INVALIDDATA;
468 * Read the next element as an ASCII string.
469 * 0 is success, < 0 is failure.
473 ebml_read_ascii (MatroskaDemuxContext *matroska,
477 ByteIOContext *pb = &matroska->ctx->pb;
481 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
482 (res = ebml_read_element_length(matroska, &rlength)) < 0)
486 /* ebml strings are usually not 0-terminated, so we allocate one
487 * byte more, read the string and NULL-terminate it ourselves. */
488 if (size < 0 || !(*str = av_malloc(size + 1))) {
489 av_log(matroska->ctx, AV_LOG_ERROR, "Memory allocation failed\n");
490 return AVERROR_NOMEM;
492 if (get_buffer(pb, (uint8_t *) *str, size) != size) {
493 offset_t pos = url_ftell(pb);
494 av_log(matroska->ctx, AV_LOG_ERROR,
495 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
504 * Read the next element as a UTF-8 string.
505 * 0 is success, < 0 is failure.
509 ebml_read_utf8 (MatroskaDemuxContext *matroska,
513 return ebml_read_ascii(matroska, id, str);
517 * Read the next element as a date (nanoseconds since 1/1/2000).
518 * 0 is success, < 0 is failure.
522 ebml_read_date (MatroskaDemuxContext *matroska,
526 return ebml_read_sint(matroska, id, date);
530 * Read the next element, but only the header. The contents
531 * are supposed to be sub-elements which can be read separately.
532 * 0 is success, < 0 is failure.
536 ebml_read_master (MatroskaDemuxContext *matroska,
539 ByteIOContext *pb = &matroska->ctx->pb;
541 MatroskaLevel *level;
544 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
545 (res = ebml_read_element_length(matroska, &length)) < 0)
548 /* protect... (Heaven forbids that the '>' is true) */
549 if (matroska->num_levels >= EBML_MAX_DEPTH) {
550 av_log(matroska->ctx, AV_LOG_ERROR,
551 "File moves beyond max. allowed depth (%d)\n", EBML_MAX_DEPTH);
552 return AVERROR_NOTSUPP;
556 level = &matroska->levels[matroska->num_levels++];
557 level->start = url_ftell(pb);
558 level->length = length;
564 * Read the next element as binary data.
565 * 0 is success, < 0 is failure.
569 ebml_read_binary (MatroskaDemuxContext *matroska,
574 ByteIOContext *pb = &matroska->ctx->pb;
578 if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||
579 (res = ebml_read_element_length(matroska, &rlength)) < 0)
583 if (!(*binary = av_malloc(*size))) {
584 av_log(matroska->ctx, AV_LOG_ERROR,
585 "Memory allocation error\n");
586 return AVERROR_NOMEM;
589 if (get_buffer(pb, *binary, *size) != *size) {
590 offset_t pos = url_ftell(pb);
591 av_log(matroska->ctx, AV_LOG_ERROR,
592 "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);
600 * Read signed/unsigned "EBML" numbers.
601 * Return: number of bytes processed, < 0 on error.
602 * XXX: use ebml_read_num().
606 matroska_ebmlnum_uint (uint8_t *data,
610 int len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
614 return AVERROR_INVALIDDATA;
617 while (read <= 8 && !(total & len_mask)) {
622 return AVERROR_INVALIDDATA;
624 if ((total &= (len_mask - 1)) == len_mask - 1)
627 return AVERROR_INVALIDDATA;
631 total = (total << 8) | data[n];
644 * Same as above, but signed.
648 matroska_ebmlnum_sint (uint8_t *data,
655 /* read as unsigned number first */
656 if ((res = matroska_ebmlnum_uint(data, size, &unum)) < 0)
659 /* make signed (weird way) */
660 if (unum == (uint64_t)-1)
663 *num = unum - ((1LL << ((7 * res) - 1)) - 1);
669 * Read an EBML header.
670 * 0 is success, < 0 is failure.
674 ebml_read_header (MatroskaDemuxContext *matroska,
679 int level_up, res = 0;
687 if (!(id = ebml_peek_id(matroska, &level_up)) ||
688 level_up != 0 || id != EBML_ID_HEADER) {
689 av_log(matroska->ctx, AV_LOG_ERROR,
690 "This is not an EBML file (id=0x%x/0x%x)\n", id, EBML_ID_HEADER);
691 return AVERROR_INVALIDDATA;
693 if ((res = ebml_read_master(matroska, &id)) < 0)
697 if (!(id = ebml_peek_id(matroska, &level_up)))
705 /* is our read version uptodate? */
706 case EBML_ID_EBMLREADVERSION: {
709 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
711 if (num > EBML_VERSION) {
712 av_log(matroska->ctx, AV_LOG_ERROR,
713 "EBML version %"PRIu64" (> %d) is not supported\n",
715 return AVERROR_INVALIDDATA;
720 /* we only handle 8 byte lengths at max */
721 case EBML_ID_EBMLMAXSIZELENGTH: {
724 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
726 if (num > sizeof(uint64_t)) {
727 av_log(matroska->ctx, AV_LOG_ERROR,
728 "Integers of size %"PRIu64" (> %zd) not supported\n",
729 num, sizeof(uint64_t));
730 return AVERROR_INVALIDDATA;
735 /* we handle 4 byte IDs at max */
736 case EBML_ID_EBMLMAXIDLENGTH: {
739 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
741 if (num > sizeof(uint32_t)) {
742 av_log(matroska->ctx, AV_LOG_ERROR,
743 "IDs of size %"PRIu64" (> %zu) not supported\n",
744 num, sizeof(uint32_t));
745 return AVERROR_INVALIDDATA;
750 case EBML_ID_DOCTYPE: {
753 if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
764 case EBML_ID_DOCTYPEREADVERSION: {
767 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
775 av_log(matroska->ctx, AV_LOG_INFO,
776 "Unknown data type 0x%x in EBML header", id);
780 /* we ignore these two, as they don't tell us anything we
782 case EBML_ID_EBMLVERSION:
783 case EBML_ID_DOCTYPEVERSION:
784 res = ebml_read_skip (matroska);
794 matroska_find_track_by_num (MatroskaDemuxContext *matroska,
799 for (i = 0; i < matroska->num_tracks; i++)
800 if (matroska->tracks[i]->num == num)
808 * Put one packet in an application-supplied AVPacket struct.
809 * Returns 0 on success or -1 on failure.
813 matroska_deliver_packet (MatroskaDemuxContext *matroska,
816 if (matroska->num_packets > 0) {
817 memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
818 av_free(matroska->packets[0]);
819 if (matroska->num_packets > 1) {
820 memmove(&matroska->packets[0], &matroska->packets[1],
821 (matroska->num_packets - 1) * sizeof(AVPacket *));
823 av_realloc(matroska->packets, (matroska->num_packets - 1) *
826 av_freep(&matroska->packets);
828 matroska->num_packets--;
836 * Put a packet into our internal queue. Will be delivered to the
837 * user/application during the next get_packet() call.
841 matroska_queue_packet (MatroskaDemuxContext *matroska,
845 av_realloc(matroska->packets, (matroska->num_packets + 1) *
847 matroska->packets[matroska->num_packets] = pkt;
848 matroska->num_packets++;
857 matroska_probe (AVProbeData *p)
860 int len_mask = 0x80, size = 1, n = 1;
861 uint8_t probe_data[] = { 'm', 'a', 't', 'r', 'o', 's', 'k', 'a' };
864 if (AV_RB32(p->buf) != EBML_ID_HEADER)
867 /* length of header */
869 while (size <= 8 && !(total & len_mask)) {
875 total &= (len_mask - 1);
877 total = (total << 8) | p->buf[4 + n++];
879 /* does the probe data contain the whole header? */
880 if (p->buf_size < 4 + size + total)
883 /* the header must contain the document type 'matroska'. For now,
884 * we don't parse the whole header but simply check for the
885 * availability of that array of characters inside the header.
886 * Not fully fool-proof, but good enough. */
887 for (n = 4 + size; n <= 4 + size + total - sizeof(probe_data); n++)
888 if (!memcmp (&p->buf[n], probe_data, sizeof(probe_data)))
889 return AVPROBE_SCORE_MAX;
895 * From here on, it's all XML-style DTD stuff... Needs no comments.
899 matroska_parse_info (MatroskaDemuxContext *matroska)
904 av_log(matroska->ctx, AV_LOG_DEBUG, "Parsing info...\n");
907 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
910 } else if (matroska->level_up) {
911 matroska->level_up--;
916 /* cluster timecode */
917 case MATROSKA_ID_TIMECODESCALE: {
919 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
921 matroska->time_scale = num;
925 case MATROSKA_ID_DURATION: {
927 if ((res = ebml_read_float(matroska, &id, &num)) < 0)
929 matroska->ctx->duration = num * matroska->time_scale * 1000 / AV_TIME_BASE;
933 case MATROSKA_ID_TITLE: {
935 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
937 strncpy(matroska->ctx->title, text,
938 sizeof(matroska->ctx->title)-1);
943 case MATROSKA_ID_WRITINGAPP: {
945 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
947 matroska->writing_app = text;
951 case MATROSKA_ID_MUXINGAPP: {
953 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
955 matroska->muxing_app = text;
959 case MATROSKA_ID_DATEUTC: {
961 if ((res = ebml_read_date(matroska, &id, &time)) < 0)
963 matroska->created = time;
968 av_log(matroska->ctx, AV_LOG_INFO,
969 "Unknown entry 0x%x in info header\n", id);
973 res = ebml_read_skip(matroska);
977 if (matroska->level_up) {
978 matroska->level_up--;
987 matroska_add_stream (MatroskaDemuxContext *matroska)
991 MatroskaTrack *track;
993 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing track, adding stream..,\n");
995 /* Allocate a generic track. As soon as we know its type we'll realloc. */
996 track = av_mallocz(MAX_TRACK_SIZE);
997 matroska->num_tracks++;
998 strcpy(track->language, "eng");
1000 /* start with the master */
1001 if ((res = ebml_read_master(matroska, &id)) < 0)
1004 /* try reading the trackentry headers */
1006 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1009 } else if (matroska->level_up > 0) {
1010 matroska->level_up--;
1015 /* track number (unique stream ID) */
1016 case MATROSKA_ID_TRACKNUMBER: {
1018 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1024 /* track UID (unique identifier) */
1025 case MATROSKA_ID_TRACKUID: {
1027 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1033 /* track type (video, audio, combined, subtitle, etc.) */
1034 case MATROSKA_ID_TRACKTYPE: {
1036 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1038 if (track->type && track->type != num) {
1039 av_log(matroska->ctx, AV_LOG_INFO,
1040 "More than one tracktype in an entry - skip\n");
1045 switch (track->type) {
1046 case MATROSKA_TRACK_TYPE_VIDEO:
1047 case MATROSKA_TRACK_TYPE_AUDIO:
1048 case MATROSKA_TRACK_TYPE_SUBTITLE:
1050 case MATROSKA_TRACK_TYPE_COMPLEX:
1051 case MATROSKA_TRACK_TYPE_LOGO:
1052 case MATROSKA_TRACK_TYPE_CONTROL:
1054 av_log(matroska->ctx, AV_LOG_INFO,
1055 "Unknown or unsupported track type 0x%x\n",
1060 matroska->tracks[matroska->num_tracks - 1] = track;
1064 /* tracktype specific stuff for video */
1065 case MATROSKA_ID_TRACKVIDEO: {
1066 MatroskaVideoTrack *videotrack;
1068 track->type = MATROSKA_TRACK_TYPE_VIDEO;
1069 if (track->type != MATROSKA_TRACK_TYPE_VIDEO) {
1070 av_log(matroska->ctx, AV_LOG_INFO,
1071 "video data in non-video track - ignoring\n");
1072 res = AVERROR_INVALIDDATA;
1074 } else if ((res = ebml_read_master(matroska, &id)) < 0)
1076 videotrack = (MatroskaVideoTrack *)track;
1079 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1082 } else if (matroska->level_up > 0) {
1083 matroska->level_up--;
1088 /* fixme, this should be one-up, but I get it here */
1089 case MATROSKA_ID_TRACKDEFAULTDURATION: {
1091 if ((res = ebml_read_uint (matroska, &id,
1094 track->default_duration = num/matroska->time_scale;
1098 /* video framerate */
1099 case MATROSKA_ID_VIDEOFRAMERATE: {
1101 if ((res = ebml_read_float(matroska, &id,
1104 track->default_duration = 1000000000/(matroska->time_scale*num);
1108 /* width of the size to display the video at */
1109 case MATROSKA_ID_VIDEODISPLAYWIDTH: {
1111 if ((res = ebml_read_uint(matroska, &id,
1114 videotrack->display_width = num;
1118 /* height of the size to display the video at */
1119 case MATROSKA_ID_VIDEODISPLAYHEIGHT: {
1121 if ((res = ebml_read_uint(matroska, &id,
1124 videotrack->display_height = num;
1128 /* width of the video in the file */
1129 case MATROSKA_ID_VIDEOPIXELWIDTH: {
1131 if ((res = ebml_read_uint(matroska, &id,
1134 videotrack->pixel_width = num;
1138 /* height of the video in the file */
1139 case MATROSKA_ID_VIDEOPIXELHEIGHT: {
1141 if ((res = ebml_read_uint(matroska, &id,
1144 videotrack->pixel_height = num;
1148 /* whether the video is interlaced */
1149 case MATROSKA_ID_VIDEOFLAGINTERLACED: {
1151 if ((res = ebml_read_uint(matroska, &id,
1156 MATROSKA_VIDEOTRACK_INTERLACED;
1159 ~MATROSKA_VIDEOTRACK_INTERLACED;
1163 /* stereo mode (whether the video has two streams,
1164 * where one is for the left eye and the other for
1165 * the right eye, which creates a 3D-like
1167 case MATROSKA_ID_VIDEOSTEREOMODE: {
1169 if ((res = ebml_read_uint(matroska, &id,
1172 if (num != MATROSKA_EYE_MODE_MONO &&
1173 num != MATROSKA_EYE_MODE_LEFT &&
1174 num != MATROSKA_EYE_MODE_RIGHT &&
1175 num != MATROSKA_EYE_MODE_BOTH) {
1176 av_log(matroska->ctx, AV_LOG_INFO,
1177 "Ignoring unknown eye mode 0x%x\n",
1181 videotrack->eye_mode = num;
1185 /* aspect ratio behaviour */
1186 case MATROSKA_ID_VIDEOASPECTRATIO: {
1188 if ((res = ebml_read_uint(matroska, &id,
1191 if (num != MATROSKA_ASPECT_RATIO_MODE_FREE &&
1192 num != MATROSKA_ASPECT_RATIO_MODE_KEEP &&
1193 num != MATROSKA_ASPECT_RATIO_MODE_FIXED) {
1194 av_log(matroska->ctx, AV_LOG_INFO,
1195 "Ignoring unknown aspect ratio 0x%x\n",
1199 videotrack->ar_mode = num;
1203 /* colourspace (only matters for raw video)
1205 case MATROSKA_ID_VIDEOCOLOURSPACE: {
1207 if ((res = ebml_read_uint(matroska, &id,
1210 videotrack->fourcc = num;
1215 av_log(matroska->ctx, AV_LOG_INFO,
1216 "Unknown video track header entry "
1217 "0x%x - ignoring\n", id);
1221 res = ebml_read_skip(matroska);
1225 if (matroska->level_up) {
1226 matroska->level_up--;
1233 /* tracktype specific stuff for audio */
1234 case MATROSKA_ID_TRACKAUDIO: {
1235 MatroskaAudioTrack *audiotrack;
1237 track->type = MATROSKA_TRACK_TYPE_AUDIO;
1238 if (track->type != MATROSKA_TRACK_TYPE_AUDIO) {
1239 av_log(matroska->ctx, AV_LOG_INFO,
1240 "audio data in non-audio track - ignoring\n");
1241 res = AVERROR_INVALIDDATA;
1243 } else if ((res = ebml_read_master(matroska, &id)) < 0)
1245 audiotrack = (MatroskaAudioTrack *)track;
1246 audiotrack->channels = 1;
1247 audiotrack->samplerate = 8000;
1250 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1253 } else if (matroska->level_up > 0) {
1254 matroska->level_up--;
1260 case MATROSKA_ID_AUDIOSAMPLINGFREQ: {
1262 if ((res = ebml_read_float(matroska, &id,
1265 audiotrack->internal_samplerate =
1266 audiotrack->samplerate = num;
1270 case MATROSKA_ID_AUDIOOUTSAMPLINGFREQ: {
1272 if ((res = ebml_read_float(matroska, &id,
1275 audiotrack->samplerate = num;
1280 case MATROSKA_ID_AUDIOBITDEPTH: {
1282 if ((res = ebml_read_uint(matroska, &id,
1285 audiotrack->bitdepth = num;
1290 case MATROSKA_ID_AUDIOCHANNELS: {
1292 if ((res = ebml_read_uint(matroska, &id,
1295 audiotrack->channels = num;
1300 av_log(matroska->ctx, AV_LOG_INFO,
1301 "Unknown audio track header entry "
1302 "0x%x - ignoring\n", id);
1306 res = ebml_read_skip(matroska);
1310 if (matroska->level_up) {
1311 matroska->level_up--;
1318 /* codec identifier */
1319 case MATROSKA_ID_CODECID: {
1321 if ((res = ebml_read_ascii(matroska, &id, &text)) < 0)
1323 track->codec_id = text;
1327 /* codec private data */
1328 case MATROSKA_ID_CODECPRIVATE: {
1331 if ((res = ebml_read_binary(matroska, &id, &data, &size) < 0))
1333 track->codec_priv = data;
1334 track->codec_priv_size = size;
1338 /* name of the codec */
1339 case MATROSKA_ID_CODECNAME: {
1341 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1343 track->codec_name = text;
1347 /* name of this track */
1348 case MATROSKA_ID_TRACKNAME: {
1350 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1356 /* language (matters for audio/subtitles, mostly) */
1357 case MATROSKA_ID_TRACKLANGUAGE: {
1359 if ((res = ebml_read_utf8(matroska, &id, &text)) < 0)
1361 if ((end = strchr(text, '-')))
1363 if (strlen(text) == 3)
1364 strcpy(track->language, text);
1369 /* whether this is actually used */
1370 case MATROSKA_ID_TRACKFLAGENABLED: {
1372 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1375 track->flags |= MATROSKA_TRACK_ENABLED;
1377 track->flags &= ~MATROSKA_TRACK_ENABLED;
1381 /* whether it's the default for this track type */
1382 case MATROSKA_ID_TRACKFLAGDEFAULT: {
1384 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1387 track->flags |= MATROSKA_TRACK_DEFAULT;
1389 track->flags &= ~MATROSKA_TRACK_DEFAULT;
1393 /* lacing (like MPEG, where blocks don't end/start on frame
1395 case MATROSKA_ID_TRACKFLAGLACING: {
1397 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1400 track->flags |= MATROSKA_TRACK_LACING;
1402 track->flags &= ~MATROSKA_TRACK_LACING;
1406 /* default length (in time) of one data block in this track */
1407 case MATROSKA_ID_TRACKDEFAULTDURATION: {
1409 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
1411 track->default_duration = num / matroska->time_scale;
1416 av_log(matroska->ctx, AV_LOG_INFO,
1417 "Unknown track header entry 0x%x - ignoring\n", id);
1421 /* we ignore these because they're nothing useful. */
1422 case MATROSKA_ID_CODECINFOURL:
1423 case MATROSKA_ID_CODECDOWNLOADURL:
1424 case MATROSKA_ID_TRACKMINCACHE:
1425 case MATROSKA_ID_TRACKMAXCACHE:
1426 res = ebml_read_skip(matroska);
1430 if (matroska->level_up) {
1431 matroska->level_up--;
1440 matroska_parse_tracks (MatroskaDemuxContext *matroska)
1445 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing tracks...\n");
1448 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1451 } else if (matroska->level_up) {
1452 matroska->level_up--;
1457 /* one track within the "all-tracks" header */
1458 case MATROSKA_ID_TRACKENTRY:
1459 res = matroska_add_stream(matroska);
1463 av_log(matroska->ctx, AV_LOG_INFO,
1464 "Unknown entry 0x%x in track header\n", id);
1468 res = ebml_read_skip(matroska);
1472 if (matroska->level_up) {
1473 matroska->level_up--;
1482 matroska_parse_index (MatroskaDemuxContext *matroska)
1486 MatroskaDemuxIndex idx;
1488 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing index...\n");
1491 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1494 } else if (matroska->level_up) {
1495 matroska->level_up--;
1500 /* one single index entry ('point') */
1501 case MATROSKA_ID_POINTENTRY:
1502 if ((res = ebml_read_master(matroska, &id)) < 0)
1505 /* in the end, we hope to fill one entry with a
1506 * timestamp, a file position and a tracknum */
1507 idx.pos = (uint64_t) -1;
1508 idx.time = (uint64_t) -1;
1509 idx.track = (uint16_t) -1;
1512 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1515 } else if (matroska->level_up) {
1516 matroska->level_up--;
1521 /* one single index entry ('point') */
1522 case MATROSKA_ID_CUETIME: {
1524 if ((res = ebml_read_uint(matroska, &id,
1527 idx.time = time * matroska->time_scale;
1531 /* position in the file + track to which it
1533 case MATROSKA_ID_CUETRACKPOSITION:
1534 if ((res = ebml_read_master(matroska, &id)) < 0)
1538 if (!(id = ebml_peek_id (matroska,
1539 &matroska->level_up))) {
1542 } else if (matroska->level_up) {
1543 matroska->level_up--;
1549 case MATROSKA_ID_CUETRACK: {
1551 if ((res = ebml_read_uint(matroska,
1558 /* position in file */
1559 case MATROSKA_ID_CUECLUSTERPOSITION: {
1561 if ((res = ebml_read_uint(matroska,
1564 idx.pos = num+matroska->segment_start;
1569 av_log(matroska->ctx, AV_LOG_INFO,
1570 "Unknown entry 0x%x in "
1571 "CuesTrackPositions\n", id);
1575 res = ebml_read_skip(matroska);
1579 if (matroska->level_up) {
1580 matroska->level_up--;
1588 av_log(matroska->ctx, AV_LOG_INFO,
1589 "Unknown entry 0x%x in cuespoint "
1594 res = ebml_read_skip(matroska);
1598 if (matroska->level_up) {
1599 matroska->level_up--;
1604 /* so let's see if we got what we wanted */
1605 if (idx.pos != (uint64_t) -1 &&
1606 idx.time != (uint64_t) -1 &&
1607 idx.track != (uint16_t) -1) {
1608 if (matroska->num_indexes % 32 == 0) {
1609 /* re-allocate bigger index */
1611 av_realloc(matroska->index,
1612 (matroska->num_indexes + 32) *
1613 sizeof(MatroskaDemuxIndex));
1615 matroska->index[matroska->num_indexes] = idx;
1616 matroska->num_indexes++;
1621 av_log(matroska->ctx, AV_LOG_INFO,
1622 "Unknown entry 0x%x in cues header\n", id);
1626 res = ebml_read_skip(matroska);
1630 if (matroska->level_up) {
1631 matroska->level_up--;
1640 matroska_parse_metadata (MatroskaDemuxContext *matroska)
1646 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1649 } else if (matroska->level_up) {
1650 matroska->level_up--;
1655 /* Hm, this is unsupported... */
1657 av_log(matroska->ctx, AV_LOG_INFO,
1658 "Unknown entry 0x%x in metadata header\n", id);
1662 res = ebml_read_skip(matroska);
1666 if (matroska->level_up) {
1667 matroska->level_up--;
1676 matroska_parse_seekhead (MatroskaDemuxContext *matroska)
1681 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing seekhead...\n");
1684 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1687 } else if (matroska->level_up) {
1688 matroska->level_up--;
1693 case MATROSKA_ID_SEEKENTRY: {
1694 uint32_t seek_id = 0, peek_id_cache = 0;
1695 uint64_t seek_pos = (uint64_t) -1, t;
1697 if ((res = ebml_read_master(matroska, &id)) < 0)
1701 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1704 } else if (matroska->level_up) {
1705 matroska->level_up--;
1710 case MATROSKA_ID_SEEKID:
1711 res = ebml_read_uint(matroska, &id, &t);
1715 case MATROSKA_ID_SEEKPOSITION:
1716 res = ebml_read_uint(matroska, &id, &seek_pos);
1720 av_log(matroska->ctx, AV_LOG_INFO,
1721 "Unknown seekhead ID 0x%x\n", id);
1725 res = ebml_read_skip(matroska);
1729 if (matroska->level_up) {
1730 matroska->level_up--;
1735 if (!seek_id || seek_pos == (uint64_t) -1) {
1736 av_log(matroska->ctx, AV_LOG_INFO,
1737 "Incomplete seekhead entry (0x%x/%"PRIu64")\n",
1743 case MATROSKA_ID_CUES:
1744 case MATROSKA_ID_TAGS: {
1745 uint32_t level_up = matroska->level_up;
1746 offset_t before_pos;
1748 MatroskaLevel level;
1750 /* remember the peeked ID and the current position */
1751 peek_id_cache = matroska->peek_id;
1752 before_pos = url_ftell(&matroska->ctx->pb);
1755 if ((res = ebml_read_seek(matroska, seek_pos +
1756 matroska->segment_start)) < 0)
1759 /* we don't want to lose our seekhead level, so we add
1760 * a dummy. This is a crude hack. */
1761 if (matroska->num_levels == EBML_MAX_DEPTH) {
1762 av_log(matroska->ctx, AV_LOG_INFO,
1763 "Max EBML element depth (%d) reached, "
1764 "cannot parse further.\n", EBML_MAX_DEPTH);
1765 return AVERROR_UNKNOWN;
1769 level.length = (uint64_t)-1;
1770 matroska->levels[matroska->num_levels] = level;
1771 matroska->num_levels++;
1774 if (!(id = ebml_peek_id (matroska,
1775 &matroska->level_up)))
1777 if (id != seek_id) {
1778 av_log(matroska->ctx, AV_LOG_INFO,
1779 "We looked for ID=0x%x but got "
1780 "ID=0x%x (pos=%"PRIu64")",
1781 seek_id, id, seek_pos +
1782 matroska->segment_start);
1786 /* read master + parse */
1787 if ((res = ebml_read_master(matroska, &id)) < 0)
1790 case MATROSKA_ID_CUES:
1791 if (!(res = matroska_parse_index(matroska)) ||
1792 url_feof(&matroska->ctx->pb)) {
1793 matroska->index_parsed = 1;
1797 case MATROSKA_ID_TAGS:
1798 if (!(res = matroska_parse_metadata(matroska)) ||
1799 url_feof(&matroska->ctx->pb)) {
1800 matroska->metadata_parsed = 1;
1807 /* remove dummy level */
1808 while (matroska->num_levels) {
1809 matroska->num_levels--;
1811 matroska->levels[matroska->num_levels].length;
1812 if (length == (uint64_t)-1)
1817 if ((res = ebml_read_seek(matroska, before_pos)) < 0)
1819 matroska->peek_id = peek_id_cache;
1820 matroska->level_up = level_up;
1825 av_log(matroska->ctx, AV_LOG_INFO,
1826 "Ignoring seekhead entry for ID=0x%x\n",
1835 av_log(matroska->ctx, AV_LOG_INFO,
1836 "Unknown seekhead ID 0x%x\n", id);
1840 res = ebml_read_skip(matroska);
1844 if (matroska->level_up) {
1845 matroska->level_up--;
1853 #define ARRAY_SIZE(x) (sizeof(x)/sizeof(*x))
1856 matroska_aac_profile (char *codec_id)
1858 static const char *aac_profiles[] = {
1863 for (profile=0; profile<ARRAY_SIZE(aac_profiles); profile++)
1864 if (strstr(codec_id, aac_profiles[profile]))
1870 matroska_aac_sri (int samplerate)
1872 static const int aac_sample_rates[] = {
1873 96000, 88200, 64000, 48000, 44100, 32000,
1874 24000, 22050, 16000, 12000, 11025, 8000,
1878 for (sri=0; sri<ARRAY_SIZE(aac_sample_rates); sri++)
1879 if (aac_sample_rates[sri] == samplerate)
1885 matroska_read_header (AVFormatContext *s,
1886 AVFormatParameters *ap)
1888 MatroskaDemuxContext *matroska = s->priv_data;
1890 int version, last_level, res = 0;
1895 /* First read the EBML header. */
1897 if ((res = ebml_read_header(matroska, &doctype, &version)) < 0)
1899 if ((doctype == NULL) || strcmp(doctype, "matroska")) {
1900 av_log(matroska->ctx, AV_LOG_ERROR,
1901 "Wrong EBML doctype ('%s' != 'matroska').\n",
1902 doctype ? doctype : "(none)");
1905 return AVERROR_NOFMT;
1909 av_log(matroska->ctx, AV_LOG_ERROR,
1910 "Matroska demuxer version 2 too old for file version %d\n",
1912 return AVERROR_NOFMT;
1915 /* The next thing is a segment. */
1917 if (!(id = ebml_peek_id(matroska, &last_level)))
1919 if (id == MATROSKA_ID_SEGMENT)
1923 av_log(matroska->ctx, AV_LOG_INFO,
1924 "Expected a Segment ID (0x%x), but received 0x%x!\n",
1925 MATROSKA_ID_SEGMENT, id);
1926 if ((res = ebml_read_skip(matroska)) < 0)
1930 /* We now have a Matroska segment.
1931 * Seeks are from the beginning of the segment,
1932 * after the segment ID/length. */
1933 if ((res = ebml_read_master(matroska, &id)) < 0)
1935 matroska->segment_start = url_ftell(&s->pb);
1937 matroska->time_scale = 1000000;
1938 /* we've found our segment, start reading the different contents in here */
1940 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
1943 } else if (matroska->level_up) {
1944 matroska->level_up--;
1950 case MATROSKA_ID_INFO: {
1951 if ((res = ebml_read_master(matroska, &id)) < 0)
1953 res = matroska_parse_info(matroska);
1957 /* track info headers */
1958 case MATROSKA_ID_TRACKS: {
1959 if ((res = ebml_read_master(matroska, &id)) < 0)
1961 res = matroska_parse_tracks(matroska);
1966 case MATROSKA_ID_CUES: {
1967 if (!matroska->index_parsed) {
1968 if ((res = ebml_read_master(matroska, &id)) < 0)
1970 res = matroska_parse_index(matroska);
1972 res = ebml_read_skip(matroska);
1977 case MATROSKA_ID_TAGS: {
1978 if (!matroska->metadata_parsed) {
1979 if ((res = ebml_read_master(matroska, &id)) < 0)
1981 res = matroska_parse_metadata(matroska);
1983 res = ebml_read_skip(matroska);
1987 /* file index (if seekable, seek to Cues/Tags to parse it) */
1988 case MATROSKA_ID_SEEKHEAD: {
1989 if ((res = ebml_read_master(matroska, &id)) < 0)
1991 res = matroska_parse_seekhead(matroska);
1995 case MATROSKA_ID_CLUSTER: {
1996 /* Do not read the master - this will be done in the next
1997 * call to matroska_read_packet. */
2003 av_log(matroska->ctx, AV_LOG_INFO,
2004 "Unknown matroska file header ID 0x%x\n", id);
2008 res = ebml_read_skip(matroska);
2012 if (matroska->level_up) {
2013 matroska->level_up--;
2018 /* Have we found a cluster? */
2019 if (ebml_peek_id(matroska, NULL) == MATROSKA_ID_CLUSTER) {
2021 MatroskaTrack *track;
2024 for (i = 0; i < matroska->num_tracks; i++) {
2025 enum CodecID codec_id = CODEC_ID_NONE;
2026 uint8_t *extradata = NULL;
2027 int extradata_size = 0;
2028 int extradata_offset = 0;
2029 track = matroska->tracks[i];
2030 track->stream_index = -1;
2032 /* Apply some sanity checks. */
2033 if (track->codec_id == NULL)
2036 for(j=0; ff_mkv_codec_tags[j].str; j++){
2037 if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,
2038 strlen(ff_mkv_codec_tags[j].str))){
2039 codec_id= ff_mkv_codec_tags[j].id;
2044 /* Set the FourCC from the CodecID. */
2045 /* This is the MS compatibility mode which stores a
2046 * BITMAPINFOHEADER in the CodecPrivate. */
2047 if (!strcmp(track->codec_id,
2048 MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&
2049 (track->codec_priv_size >= 40) &&
2050 (track->codec_priv != NULL)) {
2051 MatroskaVideoTrack *vtrack = (MatroskaVideoTrack *) track;
2053 /* Offset of biCompression. Stored in LE. */
2054 vtrack->fourcc = AV_RL32(track->codec_priv + 16);
2055 codec_id = codec_get_id(codec_bmp_tags, vtrack->fourcc);
2059 /* This is the MS compatibility mode which stores a
2060 * WAVEFORMATEX in the CodecPrivate. */
2061 else if (!strcmp(track->codec_id,
2062 MATROSKA_CODEC_ID_AUDIO_ACM) &&
2063 (track->codec_priv_size >= 18) &&
2064 (track->codec_priv != NULL)) {
2067 /* Offset of wFormatTag. Stored in LE. */
2068 tag = AV_RL16(track->codec_priv);
2069 codec_id = codec_get_id(codec_wav_tags, tag);
2073 else if (codec_id == CODEC_ID_AAC && !track->codec_priv_size) {
2074 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2075 int profile = matroska_aac_profile(track->codec_id);
2076 int sri = matroska_aac_sri(audiotrack->internal_samplerate);
2077 extradata = av_malloc(5);
2078 if (extradata == NULL)
2079 return AVERROR_NOMEM;
2080 extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);
2081 extradata[1] = ((sri&0x01) << 7) | (audiotrack->channels<<3);
2082 if (strstr(track->codec_id, "SBR")) {
2083 sri = matroska_aac_sri(audiotrack->samplerate);
2084 extradata[2] = 0x56;
2085 extradata[3] = 0xE5;
2086 extradata[4] = 0x80 | (sri<<3);
2091 track->default_duration = 1024*1000 / audiotrack->internal_samplerate;
2094 else if (codec_id == CODEC_ID_TTA) {
2095 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;
2097 extradata_size = 30;
2098 extradata = av_mallocz(extradata_size);
2099 if (extradata == NULL)
2100 return AVERROR_NOMEM;
2101 init_put_byte(&b, extradata, extradata_size, 1,
2102 NULL, NULL, NULL, NULL);
2103 put_buffer(&b, (uint8_t *) "TTA1", 4);
2105 put_le16(&b, audiotrack->channels);
2106 put_le16(&b, audiotrack->bitdepth);
2107 put_le32(&b, audiotrack->samplerate);
2108 put_le32(&b, matroska->ctx->duration * audiotrack->samplerate);
2111 else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||
2112 codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {
2113 extradata_offset = 26;
2114 track->codec_priv_size -= extradata_offset;
2115 track->flags |= MATROSKA_TRACK_REAL_V;
2118 else if (codec_id == CODEC_ID_RA_144) {
2119 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2120 audiotrack->samplerate = 8000;
2121 audiotrack->channels = 1;
2124 else if (codec_id == CODEC_ID_RA_288 ||
2125 codec_id == CODEC_ID_COOK ||
2126 codec_id == CODEC_ID_ATRAC3) {
2127 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2130 init_put_byte(&b, track->codec_priv, track->codec_priv_size, 0,
2131 NULL, NULL, NULL, NULL);
2133 audiotrack->coded_framesize = get_be32(&b);
2135 audiotrack->sub_packet_h = get_be16(&b);
2136 audiotrack->frame_size = get_be16(&b);
2137 audiotrack->sub_packet_size = get_be16(&b);
2138 audiotrack->buf = av_malloc(audiotrack->frame_size * audiotrack->sub_packet_h);
2139 if (codec_id == CODEC_ID_RA_288) {
2140 audiotrack->block_align = audiotrack->coded_framesize;
2141 track->codec_priv_size = 0;
2143 audiotrack->block_align = audiotrack->sub_packet_size;
2144 extradata_offset = 78;
2145 track->codec_priv_size -= extradata_offset;
2149 else if (codec_id == CODEC_ID_TEXT) {
2150 MatroskaSubtitleTrack *subtrack=(MatroskaSubtitleTrack *)track;
2151 if (!strcmp(track->codec_id, "S_TEXT/ASS") ||
2152 !strcmp(track->codec_id, "S_TEXT/SSA"))
2156 if (codec_id == CODEC_ID_NONE) {
2157 av_log(matroska->ctx, AV_LOG_INFO,
2158 "Unknown/unsupported CodecID %s.\n",
2162 track->stream_index = matroska->num_streams;
2164 matroska->num_streams++;
2165 st = av_new_stream(s, track->stream_index);
2167 return AVERROR_NOMEM;
2168 av_set_pts_info(st, 64, matroska->time_scale, 1000*1000*1000); /* 64 bit pts in ns */
2170 st->codec->codec_id = codec_id;
2172 if (strcmp(track->language, "und"))
2173 strcpy(st->language, track->language);
2175 if (track->default_duration)
2176 av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,
2177 track->default_duration, 1000, 30000);
2180 st->codec->extradata = extradata;
2181 st->codec->extradata_size = extradata_size;
2182 } else if(track->codec_priv && track->codec_priv_size > 0){
2183 st->codec->extradata = av_malloc(track->codec_priv_size);
2184 if(st->codec->extradata == NULL)
2185 return AVERROR_NOMEM;
2186 st->codec->extradata_size = track->codec_priv_size;
2187 memcpy(st->codec->extradata,track->codec_priv+extradata_offset,
2188 track->codec_priv_size);
2191 if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {
2192 MatroskaVideoTrack *videotrack = (MatroskaVideoTrack *)track;
2194 st->codec->codec_type = CODEC_TYPE_VIDEO;
2195 st->codec->codec_tag = videotrack->fourcc;
2196 st->codec->width = videotrack->pixel_width;
2197 st->codec->height = videotrack->pixel_height;
2198 if (videotrack->display_width == 0)
2199 videotrack->display_width= videotrack->pixel_width;
2200 if (videotrack->display_height == 0)
2201 videotrack->display_height= videotrack->pixel_height;
2202 av_reduce(&st->codec->sample_aspect_ratio.num,
2203 &st->codec->sample_aspect_ratio.den,
2204 st->codec->height * videotrack->display_width,
2205 st->codec-> width * videotrack->display_height,
2207 st->need_parsing = AVSTREAM_PARSE_HEADERS;
2208 } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2209 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2211 st->codec->codec_type = CODEC_TYPE_AUDIO;
2212 st->codec->sample_rate = audiotrack->samplerate;
2213 st->codec->channels = audiotrack->channels;
2214 st->codec->block_align = audiotrack->block_align;
2215 } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {
2216 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
2219 /* What do we do with private data? E.g. for Vorbis. */
2224 if (matroska->index_parsed) {
2225 int i, track, stream;
2226 for (i=0; i<matroska->num_indexes; i++) {
2227 MatroskaDemuxIndex *idx = &matroska->index[i];
2228 track = matroska_find_track_by_num(matroska, idx->track);
2229 stream = matroska->tracks[track]->stream_index;
2231 av_add_index_entry(matroska->ctx->streams[stream],
2232 idx->pos, idx->time/matroska->time_scale,
2233 0, 0, AVINDEX_KEYFRAME);
2241 rv_offset(uint8_t *data, int slice, int slices)
2243 return AV_RL32(data+8*slice+4) + 8*slices;
2247 matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data, int size,
2248 int64_t pos, uint64_t cluster_time, uint64_t duration,
2249 int is_keyframe, int is_bframe)
2255 uint8_t *origdata = data;
2257 uint32_t *lace_size = NULL;
2258 int n, flags, laces = 0;
2261 /* first byte(s): tracknum */
2262 if ((n = matroska_ebmlnum_uint(data, size, &num)) < 0) {
2263 av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");
2270 /* fetch track from num */
2271 track = matroska_find_track_by_num(matroska, num);
2272 if (size <= 3 || track < 0 || track >= matroska->num_tracks) {
2273 av_log(matroska->ctx, AV_LOG_INFO,
2274 "Invalid stream %d or size %u\n", track, size);
2278 if (matroska->tracks[track]->stream_index < 0)
2280 st = matroska->ctx->streams[matroska->tracks[track]->stream_index];
2281 if (st->discard >= AVDISCARD_ALL) {
2285 if (duration == AV_NOPTS_VALUE)
2286 duration = matroska->tracks[track]->default_duration;
2288 /* block_time (relative to cluster time) */
2289 block_time = AV_RB16(data);
2293 if (is_keyframe == -1)
2294 is_keyframe = flags & 1 ? PKT_FLAG_KEY : 0;
2296 if (matroska->skip_to_keyframe) {
2297 if (!is_keyframe || st != matroska->skip_to_stream)
2299 matroska->skip_to_keyframe = 0;
2302 switch ((flags & 0x06) >> 1) {
2303 case 0x0: /* no lacing */
2305 lace_size = av_mallocz(sizeof(int));
2306 lace_size[0] = size;
2309 case 0x1: /* xiph lacing */
2310 case 0x2: /* fixed-size lacing */
2311 case 0x3: /* EBML lacing */
2316 laces = (*data) + 1;
2319 lace_size = av_mallocz(laces * sizeof(int));
2321 switch ((flags & 0x06) >> 1) {
2322 case 0x1: /* xiph lacing */ {
2325 for (n = 0; res == 0 && n < laces - 1; n++) {
2332 lace_size[n] += temp;
2338 total += lace_size[n];
2340 lace_size[n] = size - total;
2344 case 0x2: /* fixed-size lacing */
2345 for (n = 0; n < laces; n++)
2346 lace_size[n] = size / laces;
2349 case 0x3: /* EBML lacing */ {
2351 n = matroska_ebmlnum_uint(data, size, &num);
2353 av_log(matroska->ctx, AV_LOG_INFO,
2354 "EBML block data error\n");
2359 total = lace_size[0] = num;
2360 for (n = 1; res == 0 && n < laces - 1; n++) {
2363 r = matroska_ebmlnum_sint (data, size, &snum);
2365 av_log(matroska->ctx, AV_LOG_INFO,
2366 "EBML block data error\n");
2371 lace_size[n] = lace_size[n - 1] + snum;
2372 total += lace_size[n];
2374 lace_size[n] = size - total;
2382 int real_v = matroska->tracks[track]->flags & MATROSKA_TRACK_REAL_V;
2383 uint64_t timecode = AV_NOPTS_VALUE;
2385 if (cluster_time != (uint64_t)-1 && cluster_time + block_time >= 0)
2386 timecode = cluster_time + block_time;
2388 for (n = 0; n < laces; n++) {
2389 int slice, slices = 1;
2392 slices = *data++ + 1;
2396 for (slice=0; slice<slices; slice++) {
2397 int slice_size, slice_offset = 0;
2399 slice_offset = rv_offset(data, slice, slices);
2400 if (slice+1 == slices)
2401 slice_size = lace_size[n] - slice_offset;
2403 slice_size = rv_offset(data, slice+1, slices) - slice_offset;
2405 if (st->codec->codec_id == CODEC_ID_RA_288 ||
2406 st->codec->codec_id == CODEC_ID_COOK ||
2407 st->codec->codec_id == CODEC_ID_ATRAC3) {
2408 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)matroska->tracks[track];
2409 int a = st->codec->block_align;
2410 int sps = audiotrack->sub_packet_size;
2411 int cfs = audiotrack->coded_framesize;
2412 int h = audiotrack->sub_packet_h;
2413 int y = audiotrack->sub_packet_cnt;
2414 int w = audiotrack->frame_size;
2417 if (!audiotrack->pkt_cnt) {
2418 if (st->codec->codec_id == CODEC_ID_RA_288)
2419 for (x=0; x<h/2; x++)
2420 memcpy(audiotrack->buf+x*2*w+y*cfs,
2423 for (x=0; x<w/sps; x++)
2424 memcpy(audiotrack->buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);
2426 if (++audiotrack->sub_packet_cnt >= h) {
2427 audiotrack->sub_packet_cnt = 0;
2428 audiotrack->pkt_cnt = h*w / a;
2431 while (audiotrack->pkt_cnt) {
2432 pkt = av_mallocz(sizeof(AVPacket));
2433 av_new_packet(pkt, a);
2434 memcpy(pkt->data, audiotrack->buf
2435 + a * (h*w / a - audiotrack->pkt_cnt--), a);
2437 pkt->stream_index = matroska->tracks[track]->stream_index;
2438 matroska_queue_packet(matroska, pkt);
2443 if (st->codec->codec_id == CODEC_ID_TEXT
2444 && ((MatroskaSubtitleTrack *)(matroska->tracks[track]))->ass) {
2446 for (i=0; i<8 && data[slice_offset+offset]; offset++)
2447 if (data[slice_offset+offset] == ',')
2451 pkt = av_mallocz(sizeof(AVPacket));
2452 /* XXX: prevent data copy... */
2453 if (av_new_packet(pkt, slice_size-offset) < 0) {
2454 res = AVERROR_NOMEM;
2458 memcpy (pkt->data, data+slice_offset+offset, slice_size-offset);
2461 pkt->flags = is_keyframe;
2462 pkt->stream_index = matroska->tracks[track]->stream_index;
2464 pkt->pts = timecode;
2466 pkt->duration = duration;
2468 matroska_queue_packet(matroska, pkt);
2471 if (timecode != AV_NOPTS_VALUE)
2472 timecode = duration ? timecode + duration : AV_NOPTS_VALUE;
2474 data += lace_size[n];
2484 matroska_parse_blockgroup (MatroskaDemuxContext *matroska,
2485 uint64_t cluster_time)
2490 int is_keyframe = PKT_FLAG_KEY, last_num_packets = matroska->num_packets;
2491 uint64_t duration = AV_NOPTS_VALUE;
2496 av_log(matroska->ctx, AV_LOG_DEBUG, "parsing blockgroup...\n");
2499 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2502 } else if (matroska->level_up) {
2503 matroska->level_up--;
2508 /* one block inside the group. Note, block parsing is one
2509 * of the harder things, so this code is a bit complicated.
2510 * See http://www.matroska.org/ for documentation. */
2511 case MATROSKA_ID_BLOCK: {
2512 pos = url_ftell(&matroska->ctx->pb);
2513 res = ebml_read_binary(matroska, &id, &data, &size);
2517 case MATROSKA_ID_BLOCKDURATION: {
2518 if ((res = ebml_read_uint(matroska, &id, &duration)) < 0)
2523 case MATROSKA_ID_BLOCKREFERENCE: {
2525 /* We've found a reference, so not even the first frame in
2526 * the lace is a key frame. */
2528 if (last_num_packets != matroska->num_packets)
2529 matroska->packets[last_num_packets]->flags = 0;
2530 if ((res = ebml_read_sint(matroska, &id, &num)) < 0)
2538 av_log(matroska->ctx, AV_LOG_INFO,
2539 "Unknown entry 0x%x in blockgroup data\n", id);
2543 res = ebml_read_skip(matroska);
2547 if (matroska->level_up) {
2548 matroska->level_up--;
2557 res = matroska_parse_block(matroska, data, size, pos, cluster_time,
2558 duration, is_keyframe, is_bframe);
2564 matroska_parse_cluster (MatroskaDemuxContext *matroska)
2568 uint64_t cluster_time = 0;
2573 av_log(matroska->ctx, AV_LOG_DEBUG,
2574 "parsing cluster at %"PRId64"\n", url_ftell(&matroska->ctx->pb));
2577 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2580 } else if (matroska->level_up) {
2581 matroska->level_up--;
2586 /* cluster timecode */
2587 case MATROSKA_ID_CLUSTERTIMECODE: {
2589 if ((res = ebml_read_uint(matroska, &id, &num)) < 0)
2595 /* a group of blocks inside a cluster */
2596 case MATROSKA_ID_BLOCKGROUP:
2597 if ((res = ebml_read_master(matroska, &id)) < 0)
2599 res = matroska_parse_blockgroup(matroska, cluster_time);
2602 case MATROSKA_ID_SIMPLEBLOCK:
2603 pos = url_ftell(&matroska->ctx->pb);
2604 res = ebml_read_binary(matroska, &id, &data, &size);
2606 res = matroska_parse_block(matroska, data, size, pos,
2607 cluster_time, AV_NOPTS_VALUE,
2612 av_log(matroska->ctx, AV_LOG_INFO,
2613 "Unknown entry 0x%x in cluster data\n", id);
2617 res = ebml_read_skip(matroska);
2621 if (matroska->level_up) {
2622 matroska->level_up--;
2631 matroska_read_packet (AVFormatContext *s,
2634 MatroskaDemuxContext *matroska = s->priv_data;
2638 /* Read stream until we have a packet queued. */
2639 while (matroska_deliver_packet(matroska, pkt)) {
2641 /* Have we already reached the end? */
2647 if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {
2649 } else if (matroska->level_up) {
2650 matroska->level_up--;
2655 case MATROSKA_ID_CLUSTER:
2656 if ((res = ebml_read_master(matroska, &id)) < 0)
2658 if ((res = matroska_parse_cluster(matroska)) == 0)
2659 res = 1; /* Parsed one cluster, let's get out. */
2664 res = ebml_read_skip(matroska);
2668 if (matroska->level_up) {
2669 matroska->level_up--;
2682 matroska_read_seek (AVFormatContext *s, int stream_index, int64_t timestamp,
2685 MatroskaDemuxContext *matroska = s->priv_data;
2686 AVStream *st = s->streams[stream_index];
2689 /* find index entry */
2690 index = av_index_search_timestamp(st, timestamp, flags);
2695 url_fseek(&s->pb, st->index_entries[index].pos, SEEK_SET);
2696 matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);
2697 matroska->skip_to_stream = st;
2698 matroska->num_packets = 0;
2699 matroska->peek_id = 0;
2704 matroska_read_close (AVFormatContext *s)
2706 MatroskaDemuxContext *matroska = s->priv_data;
2709 av_free(matroska->writing_app);
2710 av_free(matroska->muxing_app);
2711 av_free(matroska->index);
2713 if (matroska->packets != NULL) {
2714 for (n = 0; n < matroska->num_packets; n++) {
2715 av_free_packet(matroska->packets[n]);
2716 av_free(matroska->packets[n]);
2718 av_free(matroska->packets);
2721 for (n = 0; n < matroska->num_tracks; n++) {
2722 MatroskaTrack *track = matroska->tracks[n];
2723 av_free(track->codec_id);
2724 av_free(track->codec_name);
2725 av_free(track->codec_priv);
2726 av_free(track->name);
2728 if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {
2729 MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;
2730 av_free(audiotrack->buf);
2739 AVInputFormat matroska_demuxer = {
2741 "Matroska file format",
2742 sizeof(MatroskaDemuxContext),
2744 matroska_read_header,
2745 matroska_read_packet,
2746 matroska_read_close,