3 * Copyright (c) 2007 David Conrad
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
29 #include "avlanguage.h"
30 #include "libavutil/samplefmt.h"
31 #include "libavutil/sha.h"
32 #include "libavutil/intreadwrite.h"
33 #include "libavutil/intfloat.h"
34 #include "libavutil/mathematics.h"
35 #include "libavutil/random_seed.h"
36 #include "libavutil/lfg.h"
37 #include "libavutil/dict.h"
38 #include "libavutil/avstring.h"
39 #include "libavcodec/xiph.h"
40 #include "libavcodec/mpeg4audio.h"
42 typedef struct ebml_master {
43 int64_t pos; ///< absolute offset in the file where the master's elements start
44 int sizebytes; ///< how many bytes were reserved for the size
47 typedef struct mkv_seekhead_entry {
48 unsigned int elementid;
52 typedef struct mkv_seekhead {
54 int64_t segment_offset; ///< the file offset to the beginning of the segment
55 int reserved_size; ///< -1 if appending to file
57 mkv_seekhead_entry *entries;
64 int64_t cluster_pos; ///< file offset of the cluster containing the block
68 int64_t segment_offset;
69 mkv_cuepoint *entries;
78 #define MODE_MATROSKAv2 0x01
79 #define MODE_WEBM 0x02
81 typedef struct MatroskaMuxContext {
85 int64_t segment_offset;
87 int64_t cluster_pos; ///< file offset of the current cluster
89 int64_t duration_offset;
91 mkv_seekhead *main_seekhead;
95 AVPacket cur_audio_pkt;
101 /** 2 bytes * 3 for EBML IDs, 3 1-byte EBML lengths, 8 bytes for 64 bit
102 * offset, 4 bytes for target EBML ID */
103 #define MAX_SEEKENTRY_SIZE 21
105 /** per-cuepoint-track - 3 1-byte EBML IDs, 3 1-byte EBML sizes, 2
107 #define MAX_CUETRACKPOS_SIZE 22
109 /** per-cuepoint - 2 1-byte EBML IDs, 2 1-byte EBML sizes, 8-byte uint max */
110 #define MAX_CUEPOINT_SIZE(num_tracks) 12 + MAX_CUETRACKPOS_SIZE*num_tracks
113 static int ebml_id_size(unsigned int id)
115 return (av_log2(id+1)-1)/7+1;
118 static void put_ebml_id(AVIOContext *pb, unsigned int id)
120 int i = ebml_id_size(id);
122 avio_w8(pb, (uint8_t)(id >> (i*8)));
126 * Write an EBML size meaning "unknown size".
128 * @param bytes The number of bytes the size should occupy (maximum: 8).
130 static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
132 av_assert0(bytes <= 8);
133 avio_w8(pb, 0x1ff >> bytes);
139 * Calculate how many bytes are needed to represent a given number in EBML.
141 static int ebml_num_size(uint64_t num)
144 while ((num+1) >> bytes*7) bytes++;
149 * Write a number in EBML variable length format.
151 * @param bytes The number of bytes that need to be used to write the number.
152 * If zero, any number of bytes can be used.
154 static void put_ebml_num(AVIOContext *pb, uint64_t num, int bytes)
156 int i, needed_bytes = ebml_num_size(num);
158 // sizes larger than this are currently undefined in EBML
159 av_assert0(num < (1ULL<<56)-1);
162 // don't care how many bytes are used, so use the min
163 bytes = needed_bytes;
164 // the bytes needed to write the given size would exceed the bytes
165 // that we need to use, so write unknown size. This shouldn't happen.
166 av_assert0(bytes >= needed_bytes);
168 num |= 1ULL << bytes*7;
169 for (i = bytes - 1; i >= 0; i--)
170 avio_w8(pb, (uint8_t)(num >> i*8));
173 static void put_ebml_uint(AVIOContext *pb, unsigned int elementid, uint64_t val)
177 while (tmp>>=8) bytes++;
179 put_ebml_id(pb, elementid);
180 put_ebml_num(pb, bytes, 0);
181 for (i = bytes - 1; i >= 0; i--)
182 avio_w8(pb, (uint8_t)(val >> i*8));
185 static void put_ebml_float(AVIOContext *pb, unsigned int elementid, double val)
187 put_ebml_id(pb, elementid);
188 put_ebml_num(pb, 8, 0);
189 avio_wb64(pb, av_double2int(val));
192 static void put_ebml_binary(AVIOContext *pb, unsigned int elementid,
193 const void *buf, int size)
195 put_ebml_id(pb, elementid);
196 put_ebml_num(pb, size, 0);
197 avio_write(pb, buf, size);
200 static void put_ebml_string(AVIOContext *pb, unsigned int elementid, const char *str)
202 put_ebml_binary(pb, elementid, str, strlen(str));
206 * Write a void element of a given size. Useful for reserving space in
207 * the file to be written to later.
209 * @param size The number of bytes to reserve, which must be at least 2.
211 static void put_ebml_void(AVIOContext *pb, uint64_t size)
213 int64_t currentpos = avio_tell(pb);
215 av_assert0(size >= 2);
217 put_ebml_id(pb, EBML_ID_VOID);
218 // we need to subtract the length needed to store the size from the
219 // size we need to reserve so 2 cases, we use 8 bytes to store the
220 // size if possible, 1 byte otherwise
222 put_ebml_num(pb, size-1, 0);
224 put_ebml_num(pb, size-9, 8);
225 while(avio_tell(pb) < currentpos + size)
229 static ebml_master start_ebml_master(AVIOContext *pb, unsigned int elementid, uint64_t expectedsize)
231 int bytes = expectedsize ? ebml_num_size(expectedsize) : 8;
232 put_ebml_id(pb, elementid);
233 put_ebml_size_unknown(pb, bytes);
234 return (ebml_master){ avio_tell(pb), bytes };
237 static void end_ebml_master(AVIOContext *pb, ebml_master master)
239 int64_t pos = avio_tell(pb);
241 if (avio_seek(pb, master.pos - master.sizebytes, SEEK_SET) < 0)
243 put_ebml_num(pb, pos - master.pos, master.sizebytes);
244 avio_seek(pb, pos, SEEK_SET);
247 static void put_xiph_size(AVIOContext *pb, int size)
250 for (i = 0; i < size / 255; i++)
252 avio_w8(pb, size % 255);
256 * Initialize a mkv_seekhead element to be ready to index level 1 Matroska
257 * elements. If a maximum number of elements is specified, enough space
258 * will be reserved at the current file location to write a seek head of
261 * @param segment_offset The absolute offset to the position in the file
262 * where the segment begins.
263 * @param numelements The maximum number of elements that will be indexed
264 * by this seek head, 0 if unlimited.
266 static mkv_seekhead * mkv_start_seekhead(AVIOContext *pb, int64_t segment_offset, int numelements)
268 mkv_seekhead *new_seekhead = av_mallocz(sizeof(mkv_seekhead));
269 if (new_seekhead == NULL)
272 new_seekhead->segment_offset = segment_offset;
274 if (numelements > 0) {
275 new_seekhead->filepos = avio_tell(pb);
276 // 21 bytes max for a seek entry, 10 bytes max for the SeekHead ID
277 // and size, and 3 bytes to guarantee that an EBML void element
278 // will fit afterwards
279 new_seekhead->reserved_size = numelements * MAX_SEEKENTRY_SIZE + 13;
280 new_seekhead->max_entries = numelements;
281 put_ebml_void(pb, new_seekhead->reserved_size);
286 static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
288 mkv_seekhead_entry *entries = seekhead->entries;
290 // don't store more elements than we reserved space for
291 if (seekhead->max_entries > 0 && seekhead->max_entries <= seekhead->num_entries)
294 entries = av_realloc(entries, (seekhead->num_entries + 1) * sizeof(mkv_seekhead_entry));
296 return AVERROR(ENOMEM);
298 entries[seekhead->num_entries ].elementid = elementid;
299 entries[seekhead->num_entries++].segmentpos = filepos - seekhead->segment_offset;
301 seekhead->entries = entries;
306 * Write the seek head to the file and free it. If a maximum number of
307 * elements was specified to mkv_start_seekhead(), the seek head will
308 * be written at the location reserved for it. Otherwise, it is written
309 * at the current location in the file.
311 * @return The file offset where the seekhead was written,
312 * -1 if an error occurred.
314 static int64_t mkv_write_seekhead(AVIOContext *pb, mkv_seekhead *seekhead)
316 ebml_master metaseek, seekentry;
320 currentpos = avio_tell(pb);
322 if (seekhead->reserved_size > 0) {
323 if (avio_seek(pb, seekhead->filepos, SEEK_SET) < 0) {
329 metaseek = start_ebml_master(pb, MATROSKA_ID_SEEKHEAD, seekhead->reserved_size);
330 for (i = 0; i < seekhead->num_entries; i++) {
331 mkv_seekhead_entry *entry = &seekhead->entries[i];
333 seekentry = start_ebml_master(pb, MATROSKA_ID_SEEKENTRY, MAX_SEEKENTRY_SIZE);
335 put_ebml_id(pb, MATROSKA_ID_SEEKID);
336 put_ebml_num(pb, ebml_id_size(entry->elementid), 0);
337 put_ebml_id(pb, entry->elementid);
339 put_ebml_uint(pb, MATROSKA_ID_SEEKPOSITION, entry->segmentpos);
340 end_ebml_master(pb, seekentry);
342 end_ebml_master(pb, metaseek);
344 if (seekhead->reserved_size > 0) {
345 uint64_t remaining = seekhead->filepos + seekhead->reserved_size - avio_tell(pb);
346 put_ebml_void(pb, remaining);
347 avio_seek(pb, currentpos, SEEK_SET);
349 currentpos = seekhead->filepos;
352 av_free(seekhead->entries);
358 static mkv_cues * mkv_start_cues(int64_t segment_offset)
360 mkv_cues *cues = av_mallocz(sizeof(mkv_cues));
364 cues->segment_offset = segment_offset;
368 static int mkv_add_cuepoint(mkv_cues *cues, int stream, int64_t ts, int64_t cluster_pos)
370 mkv_cuepoint *entries = cues->entries;
375 entries = av_realloc(entries, (cues->num_entries + 1) * sizeof(mkv_cuepoint));
377 return AVERROR(ENOMEM);
379 entries[cues->num_entries ].pts = ts;
380 entries[cues->num_entries ].tracknum = stream + 1;
381 entries[cues->num_entries++].cluster_pos = cluster_pos - cues->segment_offset;
383 cues->entries = entries;
387 static int64_t mkv_write_cues(AVIOContext *pb, mkv_cues *cues, mkv_track *tracks, int num_tracks)
389 ebml_master cues_element;
393 currentpos = avio_tell(pb);
394 cues_element = start_ebml_master(pb, MATROSKA_ID_CUES, 0);
396 for (i = 0; i < cues->num_entries; i++) {
397 ebml_master cuepoint, track_positions;
398 mkv_cuepoint *entry = &cues->entries[i];
399 uint64_t pts = entry->pts;
401 cuepoint = start_ebml_master(pb, MATROSKA_ID_POINTENTRY, MAX_CUEPOINT_SIZE(num_tracks));
402 put_ebml_uint(pb, MATROSKA_ID_CUETIME, pts);
404 // put all the entries from different tracks that have the exact same
405 // timestamp into the same CuePoint
406 for (j = 0; j < num_tracks; j++)
407 tracks[j].has_cue = 0;
408 for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
409 int tracknum = entry[j].tracknum - 1;
410 av_assert0(tracknum>=0 && tracknum<num_tracks);
411 if (tracks[tracknum].has_cue)
413 tracks[tracknum].has_cue = 1;
414 track_positions = start_ebml_master(pb, MATROSKA_ID_CUETRACKPOSITION, MAX_CUETRACKPOS_SIZE);
415 put_ebml_uint(pb, MATROSKA_ID_CUETRACK , entry[j].tracknum );
416 put_ebml_uint(pb, MATROSKA_ID_CUECLUSTERPOSITION, entry[j].cluster_pos);
417 end_ebml_master(pb, track_positions);
420 end_ebml_master(pb, cuepoint);
422 end_ebml_master(pb, cues_element);
427 static int put_xiph_codecpriv(AVFormatContext *s, AVIOContext *pb, AVCodecContext *codec)
429 uint8_t *header_start[3];
431 int first_header_size;
434 if (codec->codec_id == AV_CODEC_ID_VORBIS)
435 first_header_size = 30;
437 first_header_size = 42;
439 if (avpriv_split_xiph_headers(codec->extradata, codec->extradata_size,
440 first_header_size, header_start, header_len) < 0) {
441 av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
445 avio_w8(pb, 2); // number packets - 1
446 for (j = 0; j < 2; j++) {
447 put_xiph_size(pb, header_len[j]);
449 for (j = 0; j < 3; j++)
450 avio_write(pb, header_start[j], header_len[j]);
455 static void get_aac_sample_rates(AVFormatContext *s, AVCodecContext *codec, int *sample_rate, int *output_sample_rate)
457 MPEG4AudioConfig mp4ac;
459 if (avpriv_mpeg4audio_get_config(&mp4ac, codec->extradata,
460 codec->extradata_size * 8, 1) < 0) {
461 av_log(s, AV_LOG_WARNING, "Error parsing AAC extradata, unable to determine samplerate.\n");
465 *sample_rate = mp4ac.sample_rate;
466 *output_sample_rate = mp4ac.ext_sample_rate;
469 static int mkv_write_codecprivate(AVFormatContext *s, AVIOContext *pb, AVCodecContext *codec, int native_id, int qt_id)
473 int ret, codecpriv_size;
475 ret = avio_open_dyn_buf(&dyn_cp);
480 if (codec->codec_id == AV_CODEC_ID_VORBIS || codec->codec_id == AV_CODEC_ID_THEORA)
481 ret = put_xiph_codecpriv(s, dyn_cp, codec);
482 else if (codec->codec_id == AV_CODEC_ID_FLAC)
483 ret = ff_flac_write_header(dyn_cp, codec, 1);
484 else if (codec->codec_id == AV_CODEC_ID_H264)
485 ret = ff_isom_write_avcc(dyn_cp, codec->extradata, codec->extradata_size);
486 else if (codec->codec_id == AV_CODEC_ID_ALAC) {
487 if (codec->extradata_size < 36) {
488 av_log(s, AV_LOG_ERROR,
489 "Invalid extradata found, ALAC expects a 36-byte "
491 ret = AVERROR_INVALIDDATA;
493 avio_write(dyn_cp, codec->extradata + 12,
494 codec->extradata_size - 12);
496 else if (codec->extradata_size && codec->codec_id != AV_CODEC_ID_TTA)
497 avio_write(dyn_cp, codec->extradata, codec->extradata_size);
498 } else if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
500 if (!codec->codec_tag)
501 codec->codec_tag = ff_codec_get_tag(ff_codec_movvideo_tags, codec->codec_id);
502 if (codec->extradata_size)
503 avio_write(dyn_cp, codec->extradata, codec->extradata_size);
505 if (!codec->codec_tag)
506 codec->codec_tag = ff_codec_get_tag(ff_codec_bmp_tags, codec->codec_id);
507 if (!codec->codec_tag) {
508 av_log(s, AV_LOG_ERROR, "No bmp codec tag found for codec %s\n",
509 avcodec_get_name(codec->codec_id));
510 ret = AVERROR(EINVAL);
513 ff_put_bmp_header(dyn_cp, codec, ff_codec_bmp_tags, 0);
516 } else if (codec->codec_type == AVMEDIA_TYPE_AUDIO) {
518 tag = ff_codec_get_tag(ff_codec_wav_tags, codec->codec_id);
520 av_log(s, AV_LOG_ERROR, "No wav codec tag found for codec %s\n",
521 avcodec_get_name(codec->codec_id));
522 ret = AVERROR(EINVAL);
524 if (!codec->codec_tag)
525 codec->codec_tag = tag;
527 ff_put_wav_header(dyn_cp, codec);
530 codecpriv_size = avio_close_dyn_buf(dyn_cp, &codecpriv);
532 put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codecpriv, codecpriv_size);
537 static int mkv_write_tracks(AVFormatContext *s)
539 MatroskaMuxContext *mkv = s->priv_data;
540 AVIOContext *pb = s->pb;
542 int i, j, ret, default_stream_exists = 0;
544 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TRACKS, avio_tell(pb));
545 if (ret < 0) return ret;
547 tracks = start_ebml_master(pb, MATROSKA_ID_TRACKS, 0);
548 for (i = 0; i < s->nb_streams; i++) {
549 AVStream *st = s->streams[i];
550 default_stream_exists |= st->disposition & AV_DISPOSITION_DEFAULT;
552 for (i = 0; i < s->nb_streams; i++) {
553 AVStream *st = s->streams[i];
554 AVCodecContext *codec = st->codec;
555 ebml_master subinfo, track;
558 int bit_depth = av_get_bits_per_sample(codec->codec_id);
559 int sample_rate = codec->sample_rate;
560 int output_sample_rate = 0;
561 AVDictionaryEntry *tag;
563 if (codec->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
564 mkv->have_attachments = 1;
569 bit_depth = av_get_bytes_per_sample(codec->sample_fmt) << 3;
571 bit_depth = codec->bits_per_coded_sample;
573 if (codec->codec_id == AV_CODEC_ID_AAC)
574 get_aac_sample_rates(s, codec, &sample_rate, &output_sample_rate);
576 track = start_ebml_master(pb, MATROSKA_ID_TRACKENTRY, 0);
577 put_ebml_uint (pb, MATROSKA_ID_TRACKNUMBER , i + 1);
578 put_ebml_uint (pb, MATROSKA_ID_TRACKUID , i + 1);
579 put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0); // no lacing (yet)
581 if ((tag = av_dict_get(st->metadata, "title", NULL, 0)))
582 put_ebml_string(pb, MATROSKA_ID_TRACKNAME, tag->value);
583 tag = av_dict_get(st->metadata, "language", NULL, 0);
584 put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag ? tag->value:"und");
586 if (default_stream_exists) {
587 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGDEFAULT, !!(st->disposition & AV_DISPOSITION_DEFAULT));
589 if (st->disposition & AV_DISPOSITION_FORCED)
590 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGFORCED, 1);
592 // look for a codec ID string specific to mkv to use,
593 // if none are found, use AVI codes
594 for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
595 if (ff_mkv_codec_tags[j].id == codec->codec_id) {
596 put_ebml_string(pb, MATROSKA_ID_CODECID, ff_mkv_codec_tags[j].str);
602 if (mkv->mode == MODE_WEBM && !(codec->codec_id == AV_CODEC_ID_VP8 ||
603 codec->codec_id == AV_CODEC_ID_VORBIS)) {
604 av_log(s, AV_LOG_ERROR,
605 "Only VP8 video and Vorbis audio are supported for WebM.\n");
606 return AVERROR(EINVAL);
609 switch (codec->codec_type) {
610 case AVMEDIA_TYPE_VIDEO:
611 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_VIDEO);
612 if(st->avg_frame_rate.num && st->avg_frame_rate.den && 1.0/av_q2d(st->avg_frame_rate) > av_q2d(codec->time_base))
613 put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, 1E9/av_q2d(st->avg_frame_rate));
615 put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, av_q2d(codec->time_base)*1E9);
618 ff_codec_get_tag(ff_codec_movvideo_tags, codec->codec_id) &&
619 (!ff_codec_get_tag(ff_codec_bmp_tags, codec->codec_id)
620 || codec->codec_id == AV_CODEC_ID_SVQ1
621 || codec->codec_id == AV_CODEC_ID_SVQ3
622 || codec->codec_id == AV_CODEC_ID_CINEPAK))
626 put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");
627 else if (!native_id) {
628 // if there is no mkv-specific codec ID, use VFW mode
629 put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");
630 mkv->tracks[i].write_dts = 1;
633 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
634 // XXX: interlace flag?
635 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , codec->width);
636 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, codec->height);
638 if ((tag = av_dict_get(st->metadata, "stereo_mode", NULL, 0)) ||
639 (tag = av_dict_get( s->metadata, "stereo_mode", NULL, 0))) {
640 // save stereo mode flag
641 uint64_t st_mode = MATROSKA_VIDEO_STEREO_MODE_COUNT;
643 for (j=0; j<MATROSKA_VIDEO_STEREO_MODE_COUNT; j++)
644 if (!strcmp(tag->value, ff_matroska_video_stereo_mode[j])){
649 if ((mkv->mode == MODE_WEBM && st_mode > 3 && st_mode != 11)
650 || st_mode >= MATROSKA_VIDEO_STEREO_MODE_COUNT) {
651 av_log(s, AV_LOG_ERROR,
652 "The specified stereo mode is not valid.\n");
653 return AVERROR(EINVAL);
655 put_ebml_uint(pb, MATROSKA_ID_VIDEOSTEREOMODE, st_mode);
658 if (st->sample_aspect_ratio.num) {
659 int64_t d_width = av_rescale(codec->width, st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
660 if (d_width > INT_MAX) {
661 av_log(s, AV_LOG_ERROR, "Overflow in display width\n");
662 return AVERROR(EINVAL);
664 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , d_width);
665 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, codec->height);
668 if (codec->codec_id == AV_CODEC_ID_RAWVIDEO) {
669 uint32_t color_space = av_le2ne32(codec->codec_tag);
670 put_ebml_binary(pb, MATROSKA_ID_VIDEOCOLORSPACE, &color_space, sizeof(color_space));
672 end_ebml_master(pb, subinfo);
675 case AVMEDIA_TYPE_AUDIO:
676 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_AUDIO);
679 // no mkv-specific ID, use ACM mode
680 put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");
682 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);
683 put_ebml_uint (pb, MATROSKA_ID_AUDIOCHANNELS , codec->channels);
684 put_ebml_float (pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, sample_rate);
685 if (output_sample_rate)
686 put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
688 put_ebml_uint(pb, MATROSKA_ID_AUDIOBITDEPTH, bit_depth);
689 end_ebml_master(pb, subinfo);
692 case AVMEDIA_TYPE_SUBTITLE:
693 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_SUBTITLE);
695 av_log(s, AV_LOG_ERROR, "Subtitle codec %d is not supported.\n", codec->codec_id);
696 return AVERROR(ENOSYS);
700 av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.\n");
703 ret = mkv_write_codecprivate(s, pb, codec, native_id, qt_id);
704 if (ret < 0) return ret;
706 end_ebml_master(pb, track);
708 // ms precision is the de-facto standard timescale for mkv files
709 avpriv_set_pts_info(st, 64, 1, 1000);
711 end_ebml_master(pb, tracks);
715 static int mkv_write_chapters(AVFormatContext *s)
717 MatroskaMuxContext *mkv = s->priv_data;
718 AVIOContext *pb = s->pb;
719 ebml_master chapters, editionentry;
720 AVRational scale = {1, 1E9};
726 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CHAPTERS, avio_tell(pb));
727 if (ret < 0) return ret;
729 chapters = start_ebml_master(pb, MATROSKA_ID_CHAPTERS , 0);
730 editionentry = start_ebml_master(pb, MATROSKA_ID_EDITIONENTRY, 0);
731 put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGDEFAULT, 1);
732 put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGHIDDEN , 0);
733 for (i = 0; i < s->nb_chapters; i++) {
734 ebml_master chapteratom, chapterdisplay;
735 AVChapter *c = s->chapters[i];
736 AVDictionaryEntry *t = NULL;
738 chapteratom = start_ebml_master(pb, MATROSKA_ID_CHAPTERATOM, 0);
739 put_ebml_uint(pb, MATROSKA_ID_CHAPTERUID, c->id);
740 put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMESTART,
741 av_rescale_q(c->start, c->time_base, scale));
742 put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMEEND,
743 av_rescale_q(c->end, c->time_base, scale));
744 put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGHIDDEN , 0);
745 put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGENABLED, 1);
746 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
747 chapterdisplay = start_ebml_master(pb, MATROSKA_ID_CHAPTERDISPLAY, 0);
748 put_ebml_string(pb, MATROSKA_ID_CHAPSTRING, t->value);
749 put_ebml_string(pb, MATROSKA_ID_CHAPLANG , "und");
750 end_ebml_master(pb, chapterdisplay);
752 end_ebml_master(pb, chapteratom);
754 end_ebml_master(pb, editionentry);
755 end_ebml_master(pb, chapters);
759 static void mkv_write_simpletag(AVIOContext *pb, AVDictionaryEntry *t)
761 uint8_t *key = av_strdup(t->key);
763 const uint8_t *lang = NULL;
766 if ((p = strrchr(p, '-')) &&
767 (lang = av_convert_lang_to(p + 1, AV_LANG_ISO639_2_BIBL)))
774 else if (*p >= 'a' && *p <= 'z')
779 tag = start_ebml_master(pb, MATROSKA_ID_SIMPLETAG, 0);
780 put_ebml_string(pb, MATROSKA_ID_TAGNAME, key);
782 put_ebml_string(pb, MATROSKA_ID_TAGLANG, lang);
783 put_ebml_string(pb, MATROSKA_ID_TAGSTRING, t->value);
784 end_ebml_master(pb, tag);
789 static int mkv_write_tag(AVFormatContext *s, AVDictionary *m, unsigned int elementid,
790 unsigned int uid, ebml_master *tags)
792 MatroskaMuxContext *mkv = s->priv_data;
793 ebml_master tag, targets;
794 AVDictionaryEntry *t = NULL;
798 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TAGS, avio_tell(s->pb));
799 if (ret < 0) return ret;
801 *tags = start_ebml_master(s->pb, MATROSKA_ID_TAGS, 0);
804 tag = start_ebml_master(s->pb, MATROSKA_ID_TAG, 0);
805 targets = start_ebml_master(s->pb, MATROSKA_ID_TAGTARGETS, 0);
807 put_ebml_uint(s->pb, elementid, uid);
808 end_ebml_master(s->pb, targets);
810 while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX)))
811 if (av_strcasecmp(t->key, "title") && av_strcasecmp(t->key, "stereo_mode"))
812 mkv_write_simpletag(s->pb, t);
814 end_ebml_master(s->pb, tag);
818 static int mkv_write_tags(AVFormatContext *s)
820 ebml_master tags = {0};
823 ff_metadata_conv_ctx(s, ff_mkv_metadata_conv, NULL);
825 if (av_dict_get(s->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX)) {
826 ret = mkv_write_tag(s, s->metadata, 0, 0, &tags);
827 if (ret < 0) return ret;
830 for (i = 0; i < s->nb_streams; i++) {
831 AVStream *st = s->streams[i];
833 if (!av_dict_get(st->metadata, "", 0, AV_DICT_IGNORE_SUFFIX))
836 ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &tags);
837 if (ret < 0) return ret;
840 for (i = 0; i < s->nb_chapters; i++) {
841 AVChapter *ch = s->chapters[i];
843 if (!av_dict_get(ch->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX))
846 ret = mkv_write_tag(s, ch->metadata, MATROSKA_ID_TAGTARGETS_CHAPTERUID, ch->id, &tags);
847 if (ret < 0) return ret;
851 end_ebml_master(s->pb, tags);
855 static int mkv_write_attachments(AVFormatContext *s)
857 MatroskaMuxContext *mkv = s->priv_data;
858 AVIOContext *pb = s->pb;
859 ebml_master attachments;
863 if (!mkv->have_attachments)
866 av_lfg_init(&c, av_get_random_seed());
868 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_ATTACHMENTS, avio_tell(pb));
869 if (ret < 0) return ret;
871 attachments = start_ebml_master(pb, MATROSKA_ID_ATTACHMENTS, 0);
873 for (i = 0; i < s->nb_streams; i++) {
874 AVStream *st = s->streams[i];
875 ebml_master attached_file;
876 AVDictionaryEntry *t;
877 const char *mimetype = NULL;
880 if (st->codec->codec_type != AVMEDIA_TYPE_ATTACHMENT)
883 attached_file = start_ebml_master(pb, MATROSKA_ID_ATTACHEDFILE, 0);
885 if (t = av_dict_get(st->metadata, "title", NULL, 0))
886 put_ebml_string(pb, MATROSKA_ID_FILEDESC, t->value);
887 if (!(t = av_dict_get(st->metadata, "filename", NULL, 0))) {
888 av_log(s, AV_LOG_ERROR, "Attachment stream %d has no filename tag.\n", i);
889 return AVERROR(EINVAL);
891 put_ebml_string(pb, MATROSKA_ID_FILENAME, t->value);
892 if (t = av_dict_get(st->metadata, "mimetype", NULL, 0))
894 else if (st->codec->codec_id != AV_CODEC_ID_NONE ) {
896 for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
897 if (ff_mkv_mime_tags[i].id == st->codec->codec_id) {
898 mimetype = ff_mkv_mime_tags[i].str;
903 av_log(s, AV_LOG_ERROR, "Attachment stream %d has no mimetype tag and "
904 "it cannot be deduced from the codec id.\n", i);
905 return AVERROR(EINVAL);
908 if (st->codec->flags & CODEC_FLAG_BITEXACT) {
909 struct AVSHA *sha = av_sha_alloc();
912 return AVERROR(ENOMEM);
913 av_sha_init(sha, 160);
914 av_sha_update(sha, st->codec->extradata, st->codec->extradata_size);
915 av_sha_final(sha, digest);
917 fileuid = AV_RL64(digest);
919 fileuid = av_lfg_get(&c);
921 av_log(s, AV_LOG_VERBOSE, "Using %.16"PRIx64" for attachment %d\n",
924 put_ebml_string(pb, MATROSKA_ID_FILEMIMETYPE, mimetype);
925 put_ebml_binary(pb, MATROSKA_ID_FILEDATA, st->codec->extradata, st->codec->extradata_size);
926 put_ebml_uint(pb, MATROSKA_ID_FILEUID, fileuid);
927 end_ebml_master(pb, attached_file);
929 end_ebml_master(pb, attachments);
934 static int mkv_write_header(AVFormatContext *s)
936 MatroskaMuxContext *mkv = s->priv_data;
937 AVIOContext *pb = s->pb;
938 ebml_master ebml_header, segment_info;
939 AVDictionaryEntry *tag;
942 if (!strcmp(s->oformat->name, "webm")) mkv->mode = MODE_WEBM;
943 else mkv->mode = MODE_MATROSKAv2;
945 if (s->avoid_negative_ts < 0)
946 s->avoid_negative_ts = 1;
948 for (i = 0; i < s->nb_streams; i++)
949 if (s->streams[i]->codec->codec_id == AV_CODEC_ID_ATRAC3 ||
950 s->streams[i]->codec->codec_id == AV_CODEC_ID_COOK ||
951 s->streams[i]->codec->codec_id == AV_CODEC_ID_RA_288 ||
952 s->streams[i]->codec->codec_id == AV_CODEC_ID_SIPR ||
953 s->streams[i]->codec->codec_id == AV_CODEC_ID_RV10 ||
954 s->streams[i]->codec->codec_id == AV_CODEC_ID_RV20) {
955 av_log(s, AV_LOG_ERROR,
956 "The Matroska muxer does not yet support muxing %s\n",
957 avcodec_get_name(s->streams[i]->codec->codec_id));
958 return AVERROR_PATCHWELCOME;
961 mkv->tracks = av_mallocz(s->nb_streams * sizeof(*mkv->tracks));
963 return AVERROR(ENOMEM);
965 ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
966 put_ebml_uint (pb, EBML_ID_EBMLVERSION , 1);
967 put_ebml_uint (pb, EBML_ID_EBMLREADVERSION , 1);
968 put_ebml_uint (pb, EBML_ID_EBMLMAXIDLENGTH , 4);
969 put_ebml_uint (pb, EBML_ID_EBMLMAXSIZELENGTH , 8);
970 put_ebml_string (pb, EBML_ID_DOCTYPE , s->oformat->name);
971 put_ebml_uint (pb, EBML_ID_DOCTYPEVERSION , 2);
972 put_ebml_uint (pb, EBML_ID_DOCTYPEREADVERSION , 2);
973 end_ebml_master(pb, ebml_header);
975 mkv->segment = start_ebml_master(pb, MATROSKA_ID_SEGMENT, 0);
976 mkv->segment_offset = avio_tell(pb);
978 // we write 2 seek heads - one at the end of the file to point to each
979 // cluster, and one at the beginning to point to all other level one
980 // elements (including the seek head at the end of the file), which
981 // isn't more than 10 elements if we only write one of each other
982 // currently defined level 1 element
983 mkv->main_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 10);
984 if (!mkv->main_seekhead)
985 return AVERROR(ENOMEM);
987 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_INFO, avio_tell(pb));
988 if (ret < 0) return ret;
990 segment_info = start_ebml_master(pb, MATROSKA_ID_INFO, 0);
991 put_ebml_uint(pb, MATROSKA_ID_TIMECODESCALE, 1000000);
992 if ((tag = av_dict_get(s->metadata, "title", NULL, 0)))
993 put_ebml_string(pb, MATROSKA_ID_TITLE, tag->value);
994 if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
995 uint32_t segment_uid[4];
998 av_lfg_init(&lfg, av_get_random_seed());
1000 for (i = 0; i < 4; i++)
1001 segment_uid[i] = av_lfg_get(&lfg);
1003 put_ebml_string(pb, MATROSKA_ID_MUXINGAPP , LIBAVFORMAT_IDENT);
1004 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, LIBAVFORMAT_IDENT);
1005 put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
1008 if (tag = av_dict_get(s->metadata, "creation_time", NULL, 0)) {
1009 // Adjust time so it's relative to 2001-01-01 and convert to nanoseconds.
1010 int64_t date_utc = (ff_iso8601_to_unix_time(tag->value) - 978307200) * 1000000000;
1011 uint8_t date_utc_buf[8];
1012 AV_WB64(date_utc_buf, date_utc);
1013 put_ebml_binary(pb, MATROSKA_ID_DATEUTC, date_utc_buf, 8);
1016 // reserve space for the duration
1018 mkv->duration_offset = avio_tell(pb);
1019 put_ebml_void(pb, 11); // assumes double-precision float to be written
1020 end_ebml_master(pb, segment_info);
1022 ret = mkv_write_tracks(s);
1023 if (ret < 0) return ret;
1025 if (mkv->mode != MODE_WEBM) {
1026 ret = mkv_write_chapters(s);
1027 if (ret < 0) return ret;
1029 ret = mkv_write_tags(s);
1030 if (ret < 0) return ret;
1032 ret = mkv_write_attachments(s);
1033 if (ret < 0) return ret;
1036 if (!s->pb->seekable)
1037 mkv_write_seekhead(pb, mkv->main_seekhead);
1039 mkv->cues = mkv_start_cues(mkv->segment_offset);
1040 if (mkv->cues == NULL)
1041 return AVERROR(ENOMEM);
1043 av_init_packet(&mkv->cur_audio_pkt);
1044 mkv->cur_audio_pkt.size = 0;
1045 mkv->cluster_pos = -1;
1051 static int mkv_blockgroup_size(int pkt_size)
1053 int size = pkt_size + 4;
1054 size += ebml_num_size(size);
1055 size += 2; // EBML ID for block and block duration
1056 size += 8; // max size of block duration
1057 size += ebml_num_size(size);
1058 size += 1; // blockgroup EBML ID
1062 static int ass_get_duration(const uint8_t *p)
1064 int sh, sm, ss, sc, eh, em, es, ec;
1065 uint64_t start, end;
1067 if (sscanf(p, "%*[^,],%d:%d:%d%*c%d,%d:%d:%d%*c%d",
1068 &sh, &sm, &ss, &sc, &eh, &em, &es, &ec) != 8)
1070 start = 3600000LL*sh + 60000LL*sm + 1000LL*ss + 10LL*sc;
1071 end = 3600000LL*eh + 60000LL*em + 1000LL*es + 10LL*ec;
1075 static int mkv_write_ass_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
1077 MatroskaMuxContext *mkv = s->priv_data;
1078 int i, layer = 0, max_duration = 0, size, line_size, data_size = pkt->size;
1079 uint8_t *start, *end, *data = pkt->data;
1080 ebml_master blockgroup;
1084 int duration = ass_get_duration(data);
1085 max_duration = FFMAX(duration, max_duration);
1086 end = memchr(data, '\n', data_size);
1087 size = line_size = end ? end-data+1 : data_size;
1088 size -= end ? (end[-1]=='\r')+1 : 0;
1090 for (i=0; i<3; i++, start++)
1091 if (!(start = memchr(start, ',', size-(start-data))))
1092 return max_duration;
1093 size -= start - data;
1094 sscanf(data, "Dialogue: %d,", &layer);
1095 i = snprintf(buffer, sizeof(buffer), "%"PRId64",%d,",
1096 s->streams[pkt->stream_index]->nb_frames, layer);
1097 size = FFMIN(i+size, sizeof(buffer));
1098 memcpy(buffer+i, start, size-i);
1100 av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
1101 "pts %" PRId64 ", duration %d\n",
1102 avio_tell(pb), size, pkt->pts, duration);
1103 blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(size));
1104 put_ebml_id(pb, MATROSKA_ID_BLOCK);
1105 put_ebml_num(pb, size+4, 0);
1106 avio_w8(pb, 0x80 | (pkt->stream_index + 1)); // this assumes stream_index is less than 126
1107 avio_wb16(pb, pkt->pts - mkv->cluster_pts);
1109 avio_write(pb, buffer, size);
1110 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
1111 end_ebml_master(pb, blockgroup);
1114 data_size -= line_size;
1117 return max_duration;
1120 static void mkv_write_block(AVFormatContext *s, AVIOContext *pb,
1121 unsigned int blockid, AVPacket *pkt, int flags)
1123 MatroskaMuxContext *mkv = s->priv_data;
1124 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1125 uint8_t *data = NULL;
1126 int offset = 0, size = pkt->size;
1127 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1129 av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
1130 "pts %" PRId64 ", dts %" PRId64 ", duration %d, flags %d\n",
1131 avio_tell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration, flags);
1132 if (codec->codec_id == AV_CODEC_ID_H264 && codec->extradata_size > 0 &&
1133 (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
1134 ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
1138 if (codec->codec_id == AV_CODEC_ID_PRORES) {
1139 /* Matroska specification requires to remove the first QuickTime atom
1145 put_ebml_id(pb, blockid);
1146 put_ebml_num(pb, size+4, 0);
1147 avio_w8(pb, 0x80 | (pkt->stream_index + 1)); // this assumes stream_index is less than 126
1148 avio_wb16(pb, ts - mkv->cluster_pts);
1150 avio_write(pb, data + offset, size);
1151 if (data != pkt->data)
1155 static int srt_get_duration(uint8_t **buf)
1157 int i, duration = 0;
1159 for (i=0; i<2 && !duration; i++) {
1160 int s_hour, s_min, s_sec, s_hsec, e_hour, e_min, e_sec, e_hsec;
1161 if (sscanf(*buf, "%d:%2d:%2d%*1[,.]%3d --> %d:%2d:%2d%*1[,.]%3d",
1162 &s_hour, &s_min, &s_sec, &s_hsec,
1163 &e_hour, &e_min, &e_sec, &e_hsec) == 8) {
1164 s_min += 60*s_hour; e_min += 60*e_hour;
1165 s_sec += 60*s_min; e_sec += 60*e_min;
1166 s_hsec += 1000*s_sec; e_hsec += 1000*e_sec;
1167 duration = e_hsec - s_hsec;
1169 *buf += strcspn(*buf, "\n") + 1;
1174 static int mkv_write_srt_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
1176 ebml_master blockgroup;
1177 AVPacket pkt2 = *pkt;
1178 int64_t duration = srt_get_duration(&pkt2.data);
1179 pkt2.size -= pkt2.data - pkt->data;
1181 blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
1182 mkv_blockgroup_size(pkt2.size));
1183 mkv_write_block(s, pb, MATROSKA_ID_BLOCK, &pkt2, 0);
1184 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
1185 end_ebml_master(pb, blockgroup);
1190 static void mkv_flush_dynbuf(AVFormatContext *s)
1192 MatroskaMuxContext *mkv = s->priv_data;
1199 bufsize = avio_close_dyn_buf(mkv->dyn_bc, &dyn_buf);
1200 avio_write(s->pb, dyn_buf, bufsize);
1205 static int mkv_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
1207 MatroskaMuxContext *mkv = s->priv_data;
1208 AVIOContext *pb = s->pb;
1209 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1210 int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1211 int duration = pkt->duration;
1213 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1215 if (ts == AV_NOPTS_VALUE) {
1216 av_log(s, AV_LOG_ERROR, "Can't write packet with unknown timestamp\n");
1217 return AVERROR(EINVAL);
1220 if (!s->pb->seekable) {
1222 if ((ret = avio_open_dyn_buf(&mkv->dyn_bc)) < 0) {
1223 av_log(s, AV_LOG_ERROR, "Failed to open dynamic buffer\n");
1230 if (mkv->cluster_pos == -1) {
1231 mkv->cluster_pos = avio_tell(s->pb);
1232 mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER, 0);
1233 put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, FFMAX(0, ts));
1234 mkv->cluster_pts = FFMAX(0, ts);
1237 if (codec->codec_type != AVMEDIA_TYPE_SUBTITLE) {
1238 mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
1239 } else if (codec->codec_id == AV_CODEC_ID_SSA) {
1240 duration = mkv_write_ass_blocks(s, pb, pkt);
1241 } else if (codec->codec_id == AV_CODEC_ID_SRT) {
1242 duration = mkv_write_srt_blocks(s, pb, pkt);
1244 ebml_master blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(pkt->size));
1245 /* For backward compatibility, prefer convergence_duration. */
1246 if (pkt->convergence_duration > 0) {
1247 duration = pkt->convergence_duration;
1249 mkv_write_block(s, pb, MATROSKA_ID_BLOCK, pkt, 0);
1250 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
1251 end_ebml_master(pb, blockgroup);
1254 if (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe) {
1255 ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, ts, mkv->cluster_pos);
1256 if (ret < 0) return ret;
1259 mkv->duration = FFMAX(mkv->duration, ts + duration);
1263 static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
1265 MatroskaMuxContext *mkv = s->priv_data;
1266 AVIOContext *pb = s->pb->seekable ? s->pb : mkv->dyn_bc;
1267 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1268 int ret, keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1269 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1270 int cluster_size = avio_tell(pb) - (s->pb->seekable ? mkv->cluster_pos : 0);
1272 // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1273 // after 4k and on a keyframe
1274 if (mkv->cluster_pos != -1 &&
1275 ((!s->pb->seekable && (cluster_size > 32*1024 || ts > mkv->cluster_pts + 1000))
1276 || cluster_size > 5*1024*1024 || ts > mkv->cluster_pts + 5000
1277 || (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe && cluster_size > 4*1024))) {
1278 av_log(s, AV_LOG_DEBUG, "Starting new cluster at offset %" PRIu64
1279 " bytes, pts %" PRIu64 "\n", avio_tell(pb), ts);
1280 end_ebml_master(pb, mkv->cluster);
1281 mkv->cluster_pos = -1;
1283 mkv_flush_dynbuf(s);
1286 // check if we have an audio packet cached
1287 if (mkv->cur_audio_pkt.size > 0) {
1288 ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
1289 av_free_packet(&mkv->cur_audio_pkt);
1291 av_log(s, AV_LOG_ERROR, "Could not write cached audio packet ret:%d\n", ret);
1296 // buffer an audio packet to ensure the packet containing the video
1297 // keyframe's timecode is contained in the same cluster for WebM
1298 if (codec->codec_type == AVMEDIA_TYPE_AUDIO) {
1299 mkv->cur_audio_pkt = *pkt;
1300 mkv->cur_audio_pkt.buf = av_buffer_ref(pkt->buf);
1301 ret = mkv->cur_audio_pkt.buf ? 0 : AVERROR(ENOMEM);
1303 ret = mkv_write_packet_internal(s, pkt);
1307 static int mkv_write_trailer(AVFormatContext *s)
1309 MatroskaMuxContext *mkv = s->priv_data;
1310 AVIOContext *pb = s->pb;
1311 int64_t currentpos, cuespos;
1314 // check if we have an audio packet cached
1315 if (mkv->cur_audio_pkt.size > 0) {
1316 ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
1317 av_free_packet(&mkv->cur_audio_pkt);
1319 av_log(s, AV_LOG_ERROR, "Could not write cached audio packet ret:%d\n", ret);
1325 end_ebml_master(mkv->dyn_bc, mkv->cluster);
1326 mkv_flush_dynbuf(s);
1327 } else if (mkv->cluster_pos != -1) {
1328 end_ebml_master(pb, mkv->cluster);
1332 if (mkv->cues->num_entries) {
1333 cuespos = mkv_write_cues(pb, mkv->cues, mkv->tracks, s->nb_streams);
1335 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CUES, cuespos);
1336 if (ret < 0) return ret;
1339 mkv_write_seekhead(pb, mkv->main_seekhead);
1341 // update the duration
1342 av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
1343 currentpos = avio_tell(pb);
1344 avio_seek(pb, mkv->duration_offset, SEEK_SET);
1345 put_ebml_float(pb, MATROSKA_ID_DURATION, mkv->duration);
1347 avio_seek(pb, currentpos, SEEK_SET);
1350 end_ebml_master(pb, mkv->segment);
1351 av_free(mkv->tracks);
1352 av_freep(&mkv->cues->entries);
1353 av_freep(&mkv->cues);
1358 static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
1361 for (i = 0; ff_mkv_codec_tags[i].id != AV_CODEC_ID_NONE; i++)
1362 if (ff_mkv_codec_tags[i].id == codec_id)
1365 if (std_compliance < FF_COMPLIANCE_NORMAL) { // mkv theoretically supports any
1366 enum AVMediaType type = avcodec_get_type(codec_id); // video/audio through VFW/ACM
1367 if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)
1374 const AVCodecTag additional_audio_tags[] = {
1375 { AV_CODEC_ID_ALAC, 0XFFFFFFFF },
1376 { AV_CODEC_ID_EAC3, 0XFFFFFFFF },
1377 { AV_CODEC_ID_MLP, 0xFFFFFFFF },
1378 { AV_CODEC_ID_OPUS, 0xFFFFFFFF },
1379 { AV_CODEC_ID_PCM_S16BE, 0xFFFFFFFF },
1380 { AV_CODEC_ID_PCM_S24BE, 0xFFFFFFFF },
1381 { AV_CODEC_ID_PCM_S32BE, 0xFFFFFFFF },
1382 { AV_CODEC_ID_QDM2, 0xFFFFFFFF },
1383 { AV_CODEC_ID_RA_144, 0xFFFFFFFF },
1384 { AV_CODEC_ID_RA_288, 0xFFFFFFFF },
1385 { AV_CODEC_ID_COOK, 0xFFFFFFFF },
1386 { AV_CODEC_ID_TRUEHD, 0xFFFFFFFF },
1387 { AV_CODEC_ID_WAVPACK, 0xFFFFFFFF },
1388 { AV_CODEC_ID_NONE, 0xFFFFFFFF }
1391 const AVCodecTag additional_video_tags[] = {
1392 { AV_CODEC_ID_PRORES, 0xFFFFFFFF },
1393 { AV_CODEC_ID_RV10, 0xFFFFFFFF },
1394 { AV_CODEC_ID_RV20, 0xFFFFFFFF },
1395 { AV_CODEC_ID_RV30, 0xFFFFFFFF },
1396 { AV_CODEC_ID_RV40, 0xFFFFFFFF },
1397 { AV_CODEC_ID_VP9, 0xFFFFFFFF },
1398 { AV_CODEC_ID_NONE, 0xFFFFFFFF }
1401 #if CONFIG_MATROSKA_MUXER
1402 AVOutputFormat ff_matroska_muxer = {
1404 .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
1405 .mime_type = "video/x-matroska",
1406 .extensions = "mkv",
1407 .priv_data_size = sizeof(MatroskaMuxContext),
1408 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
1409 AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
1410 .video_codec = CONFIG_LIBX264_ENCODER ?
1411 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
1412 .write_header = mkv_write_header,
1413 .write_packet = mkv_write_packet,
1414 .write_trailer = mkv_write_trailer,
1415 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
1417 .codec_tag = (const AVCodecTag* const []){
1418 ff_codec_bmp_tags, ff_codec_wav_tags,
1419 additional_audio_tags, additional_video_tags, 0
1421 .subtitle_codec = AV_CODEC_ID_SSA,
1422 .query_codec = mkv_query_codec,
1426 #if CONFIG_WEBM_MUXER
1427 AVOutputFormat ff_webm_muxer = {
1429 .long_name = NULL_IF_CONFIG_SMALL("WebM"),
1430 .mime_type = "video/webm",
1431 .extensions = "webm",
1432 .priv_data_size = sizeof(MatroskaMuxContext),
1433 .audio_codec = AV_CODEC_ID_VORBIS,
1434 .video_codec = AV_CODEC_ID_VP8,
1435 .write_header = mkv_write_header,
1436 .write_packet = mkv_write_packet,
1437 .write_trailer = mkv_write_trailer,
1438 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
1443 #if CONFIG_MATROSKA_AUDIO_MUXER
1444 AVOutputFormat ff_matroska_audio_muxer = {
1446 .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
1447 .mime_type = "audio/x-matroska",
1448 .extensions = "mka",
1449 .priv_data_size = sizeof(MatroskaMuxContext),
1450 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
1451 AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
1452 .video_codec = AV_CODEC_ID_NONE,
1453 .write_header = mkv_write_header,
1454 .write_packet = mkv_write_packet,
1455 .write_trailer = mkv_write_trailer,
1456 .flags = AVFMT_GLOBALHEADER | AVFMT_TS_NONSTRICT,
1457 .codec_tag = (const AVCodecTag* const []){
1458 ff_codec_wav_tags, additional_audio_tags, 0