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/intreadwrite.h"
32 #include "libavutil/intfloat.h"
33 #include "libavutil/mathematics.h"
34 #include "libavutil/random_seed.h"
35 #include "libavutil/lfg.h"
36 #include "libavutil/dict.h"
37 #include "libavutil/avstring.h"
38 #include "libavcodec/xiph.h"
39 #include "libavcodec/mpeg4audio.h"
41 typedef struct ebml_master {
42 int64_t pos; ///< absolute offset in the file where the master's elements start
43 int sizebytes; ///< how many bytes were reserved for the size
46 typedef struct mkv_seekhead_entry {
47 unsigned int elementid;
51 typedef struct mkv_seekhead {
53 int64_t segment_offset; ///< the file offset to the beginning of the segment
54 int reserved_size; ///< -1 if appending to file
56 mkv_seekhead_entry *entries;
63 int64_t cluster_pos; ///< file offset of the cluster containing the block
67 int64_t segment_offset;
68 mkv_cuepoint *entries;
76 #define MODE_MATROSKAv2 0x01
77 #define MODE_WEBM 0x02
79 typedef struct MatroskaMuxContext {
83 int64_t segment_offset;
85 int64_t cluster_pos; ///< file offset of the current cluster
87 int64_t duration_offset;
89 mkv_seekhead *main_seekhead;
93 unsigned int audio_buffer_size;
94 AVPacket cur_audio_pkt;
100 /** 2 bytes * 3 for EBML IDs, 3 1-byte EBML lengths, 8 bytes for 64 bit
101 * offset, 4 bytes for target EBML ID */
102 #define MAX_SEEKENTRY_SIZE 21
104 /** per-cuepoint-track - 3 1-byte EBML IDs, 3 1-byte EBML sizes, 2
106 #define MAX_CUETRACKPOS_SIZE 22
108 /** per-cuepoint - 2 1-byte EBML IDs, 2 1-byte EBML sizes, 8-byte uint max */
109 #define MAX_CUEPOINT_SIZE(num_tracks) 12 + MAX_CUETRACKPOS_SIZE*num_tracks
112 static int ebml_id_size(unsigned int id)
114 return (av_log2(id+1)-1)/7+1;
117 static void put_ebml_id(AVIOContext *pb, unsigned int id)
119 int i = ebml_id_size(id);
121 avio_w8(pb, id >> (i*8));
125 * Write an EBML size meaning "unknown size".
127 * @param bytes The number of bytes the size should occupy (maximum: 8).
129 static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
131 av_assert0(bytes <= 8);
132 avio_w8(pb, 0x1ff >> bytes);
138 * Calculate how many bytes are needed to represent a given number in EBML.
140 static int ebml_num_size(uint64_t num)
143 while ((num+1) >> bytes*7) bytes++;
148 * Write a number in EBML variable length format.
150 * @param bytes The number of bytes that need to be used to write the number.
151 * If zero, any number of bytes can be used.
153 static void put_ebml_num(AVIOContext *pb, uint64_t num, int bytes)
155 int i, needed_bytes = ebml_num_size(num);
157 // sizes larger than this are currently undefined in EBML
158 av_assert0(num < (1ULL<<56)-1);
161 // don't care how many bytes are used, so use the min
162 bytes = needed_bytes;
163 // the bytes needed to write the given size would exceed the bytes
164 // that we need to use, so write unknown size. This shouldn't happen.
165 av_assert0(bytes >= needed_bytes);
167 num |= 1ULL << bytes*7;
168 for (i = bytes - 1; i >= 0; i--)
169 avio_w8(pb, num >> i*8);
172 static void put_ebml_uint(AVIOContext *pb, unsigned int elementid, uint64_t val)
176 while (tmp>>=8) bytes++;
178 put_ebml_id(pb, elementid);
179 put_ebml_num(pb, bytes, 0);
180 for (i = bytes - 1; i >= 0; i--)
181 avio_w8(pb, val >> i*8);
184 static void put_ebml_float(AVIOContext *pb, unsigned int elementid, double val)
186 put_ebml_id(pb, elementid);
187 put_ebml_num(pb, 8, 0);
188 avio_wb64(pb, av_double2int(val));
191 static void put_ebml_binary(AVIOContext *pb, unsigned int elementid,
192 const void *buf, int size)
194 put_ebml_id(pb, elementid);
195 put_ebml_num(pb, size, 0);
196 avio_write(pb, buf, size);
199 static void put_ebml_string(AVIOContext *pb, unsigned int elementid, const char *str)
201 put_ebml_binary(pb, elementid, str, strlen(str));
205 * Write a void element of a given size. Useful for reserving space in
206 * the file to be written to later.
208 * @param size The number of bytes to reserve, which must be at least 2.
210 static void put_ebml_void(AVIOContext *pb, uint64_t size)
212 int64_t currentpos = avio_tell(pb);
214 av_assert0(size >= 2);
216 put_ebml_id(pb, EBML_ID_VOID);
217 // we need to subtract the length needed to store the size from the
218 // size we need to reserve so 2 cases, we use 8 bytes to store the
219 // size if possible, 1 byte otherwise
221 put_ebml_num(pb, size-1, 0);
223 put_ebml_num(pb, size-9, 8);
224 while(avio_tell(pb) < currentpos + size)
228 static ebml_master start_ebml_master(AVIOContext *pb, unsigned int elementid, uint64_t expectedsize)
230 int bytes = expectedsize ? ebml_num_size(expectedsize) : 8;
231 put_ebml_id(pb, elementid);
232 put_ebml_size_unknown(pb, bytes);
233 return (ebml_master){ avio_tell(pb), bytes };
236 static void end_ebml_master(AVIOContext *pb, ebml_master master)
238 int64_t pos = avio_tell(pb);
240 if (avio_seek(pb, master.pos - master.sizebytes, SEEK_SET) < 0)
242 put_ebml_num(pb, pos - master.pos, master.sizebytes);
243 avio_seek(pb, pos, SEEK_SET);
246 static void put_xiph_size(AVIOContext *pb, int size)
249 for (i = 0; i < size / 255; i++)
251 avio_w8(pb, size % 255);
255 * Initialize a mkv_seekhead element to be ready to index level 1 Matroska
256 * elements. If a maximum number of elements is specified, enough space
257 * will be reserved at the current file location to write a seek head of
260 * @param segment_offset The absolute offset to the position in the file
261 * where the segment begins.
262 * @param numelements The maximum number of elements that will be indexed
263 * by this seek head, 0 if unlimited.
265 static mkv_seekhead * mkv_start_seekhead(AVIOContext *pb, int64_t segment_offset, int numelements)
267 mkv_seekhead *new_seekhead = av_mallocz(sizeof(mkv_seekhead));
268 if (new_seekhead == NULL)
271 new_seekhead->segment_offset = segment_offset;
273 if (numelements > 0) {
274 new_seekhead->filepos = avio_tell(pb);
275 // 21 bytes max for a seek entry, 10 bytes max for the SeekHead ID
276 // and size, and 3 bytes to guarantee that an EBML void element
277 // will fit afterwards
278 new_seekhead->reserved_size = numelements * MAX_SEEKENTRY_SIZE + 13;
279 new_seekhead->max_entries = numelements;
280 put_ebml_void(pb, new_seekhead->reserved_size);
285 static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
287 mkv_seekhead_entry *entries = seekhead->entries;
289 // don't store more elements than we reserved space for
290 if (seekhead->max_entries > 0 && seekhead->max_entries <= seekhead->num_entries)
293 entries = av_realloc(entries, (seekhead->num_entries + 1) * sizeof(mkv_seekhead_entry));
295 return AVERROR(ENOMEM);
297 entries[seekhead->num_entries ].elementid = elementid;
298 entries[seekhead->num_entries++].segmentpos = filepos - seekhead->segment_offset;
300 seekhead->entries = entries;
305 * Write the seek head to the file and free it. If a maximum number of
306 * elements was specified to mkv_start_seekhead(), the seek head will
307 * be written at the location reserved for it. Otherwise, it is written
308 * at the current location in the file.
310 * @return The file offset where the seekhead was written,
311 * -1 if an error occurred.
313 static int64_t mkv_write_seekhead(AVIOContext *pb, mkv_seekhead *seekhead)
315 ebml_master metaseek, seekentry;
319 currentpos = avio_tell(pb);
321 if (seekhead->reserved_size > 0) {
322 if (avio_seek(pb, seekhead->filepos, SEEK_SET) < 0) {
328 metaseek = start_ebml_master(pb, MATROSKA_ID_SEEKHEAD, seekhead->reserved_size);
329 for (i = 0; i < seekhead->num_entries; i++) {
330 mkv_seekhead_entry *entry = &seekhead->entries[i];
332 seekentry = start_ebml_master(pb, MATROSKA_ID_SEEKENTRY, MAX_SEEKENTRY_SIZE);
334 put_ebml_id(pb, MATROSKA_ID_SEEKID);
335 put_ebml_num(pb, ebml_id_size(entry->elementid), 0);
336 put_ebml_id(pb, entry->elementid);
338 put_ebml_uint(pb, MATROSKA_ID_SEEKPOSITION, entry->segmentpos);
339 end_ebml_master(pb, seekentry);
341 end_ebml_master(pb, metaseek);
343 if (seekhead->reserved_size > 0) {
344 uint64_t remaining = seekhead->filepos + seekhead->reserved_size - avio_tell(pb);
345 put_ebml_void(pb, remaining);
346 avio_seek(pb, currentpos, SEEK_SET);
348 currentpos = seekhead->filepos;
351 av_free(seekhead->entries);
357 static mkv_cues * mkv_start_cues(int64_t segment_offset)
359 mkv_cues *cues = av_mallocz(sizeof(mkv_cues));
363 cues->segment_offset = segment_offset;
367 static int mkv_add_cuepoint(mkv_cues *cues, int stream, int64_t ts, int64_t cluster_pos)
369 mkv_cuepoint *entries = cues->entries;
374 entries = av_realloc(entries, (cues->num_entries + 1) * sizeof(mkv_cuepoint));
376 return AVERROR(ENOMEM);
378 entries[cues->num_entries ].pts = ts;
379 entries[cues->num_entries ].tracknum = stream + 1;
380 entries[cues->num_entries++].cluster_pos = cluster_pos - cues->segment_offset;
382 cues->entries = entries;
386 static int64_t mkv_write_cues(AVIOContext *pb, mkv_cues *cues, int num_tracks)
388 ebml_master cues_element;
392 currentpos = avio_tell(pb);
393 cues_element = start_ebml_master(pb, MATROSKA_ID_CUES, 0);
395 for (i = 0; i < cues->num_entries; i++) {
396 ebml_master cuepoint, track_positions;
397 mkv_cuepoint *entry = &cues->entries[i];
398 uint64_t pts = entry->pts;
400 cuepoint = start_ebml_master(pb, MATROSKA_ID_POINTENTRY, MAX_CUEPOINT_SIZE(num_tracks));
401 put_ebml_uint(pb, MATROSKA_ID_CUETIME, pts);
403 // put all the entries from different tracks that have the exact same
404 // timestamp into the same CuePoint
405 for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
406 track_positions = start_ebml_master(pb, MATROSKA_ID_CUETRACKPOSITION, MAX_CUETRACKPOS_SIZE);
407 put_ebml_uint(pb, MATROSKA_ID_CUETRACK , entry[j].tracknum );
408 put_ebml_uint(pb, MATROSKA_ID_CUECLUSTERPOSITION, entry[j].cluster_pos);
409 end_ebml_master(pb, track_positions);
412 end_ebml_master(pb, cuepoint);
414 end_ebml_master(pb, cues_element);
419 static int put_xiph_codecpriv(AVFormatContext *s, AVIOContext *pb, AVCodecContext *codec)
421 uint8_t *header_start[3];
423 int first_header_size;
426 if (codec->codec_id == AV_CODEC_ID_VORBIS)
427 first_header_size = 30;
429 first_header_size = 42;
431 if (avpriv_split_xiph_headers(codec->extradata, codec->extradata_size,
432 first_header_size, header_start, header_len) < 0) {
433 av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
437 avio_w8(pb, 2); // number packets - 1
438 for (j = 0; j < 2; j++) {
439 put_xiph_size(pb, header_len[j]);
441 for (j = 0; j < 3; j++)
442 avio_write(pb, header_start[j], header_len[j]);
447 static void get_aac_sample_rates(AVFormatContext *s, AVCodecContext *codec, int *sample_rate, int *output_sample_rate)
449 MPEG4AudioConfig mp4ac;
451 if (avpriv_mpeg4audio_get_config(&mp4ac, codec->extradata,
452 codec->extradata_size * 8, 1) < 0) {
453 av_log(s, AV_LOG_WARNING, "Error parsing AAC extradata, unable to determine samplerate.\n");
457 *sample_rate = mp4ac.sample_rate;
458 *output_sample_rate = mp4ac.ext_sample_rate;
461 static int mkv_write_codecprivate(AVFormatContext *s, AVIOContext *pb, AVCodecContext *codec, int native_id, int qt_id)
465 int ret, codecpriv_size;
467 ret = avio_open_dyn_buf(&dyn_cp);
472 if (codec->codec_id == AV_CODEC_ID_VORBIS || codec->codec_id == AV_CODEC_ID_THEORA)
473 ret = put_xiph_codecpriv(s, dyn_cp, codec);
474 else if (codec->codec_id == AV_CODEC_ID_FLAC)
475 ret = ff_flac_write_header(dyn_cp, codec, 1);
476 else if (codec->codec_id == AV_CODEC_ID_H264)
477 ret = ff_isom_write_avcc(dyn_cp, codec->extradata, codec->extradata_size);
478 else if (codec->codec_id == AV_CODEC_ID_ALAC) {
479 if (codec->extradata_size < 36) {
480 av_log(s, AV_LOG_ERROR,
481 "Invalid extradata found, ALAC expects a 36-byte "
483 ret = AVERROR_INVALIDDATA;
485 avio_write(dyn_cp, codec->extradata + 12,
486 codec->extradata_size - 12);
488 else if (codec->extradata_size)
489 avio_write(dyn_cp, codec->extradata, codec->extradata_size);
490 } else if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
492 if (!codec->codec_tag)
493 codec->codec_tag = ff_codec_get_tag(ff_codec_movvideo_tags, codec->codec_id);
494 if (codec->extradata_size)
495 avio_write(dyn_cp, codec->extradata, codec->extradata_size);
497 if (!codec->codec_tag)
498 codec->codec_tag = ff_codec_get_tag(ff_codec_bmp_tags, codec->codec_id);
499 if (!codec->codec_tag) {
500 av_log(s, AV_LOG_ERROR, "No bmp codec ID found.\n");
504 ff_put_bmp_header(dyn_cp, codec, ff_codec_bmp_tags, 0);
507 } else if (codec->codec_type == AVMEDIA_TYPE_AUDIO) {
509 tag = ff_codec_get_tag(ff_codec_wav_tags, codec->codec_id);
511 av_log(s, AV_LOG_ERROR, "No wav codec ID found.\n");
514 if (!codec->codec_tag)
515 codec->codec_tag = tag;
517 ff_put_wav_header(dyn_cp, codec);
520 codecpriv_size = avio_close_dyn_buf(dyn_cp, &codecpriv);
522 put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codecpriv, codecpriv_size);
527 static int mkv_write_tracks(AVFormatContext *s)
529 MatroskaMuxContext *mkv = s->priv_data;
530 AVIOContext *pb = s->pb;
534 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TRACKS, avio_tell(pb));
535 if (ret < 0) return ret;
537 tracks = start_ebml_master(pb, MATROSKA_ID_TRACKS, 0);
538 for (i = 0; i < s->nb_streams; i++) {
539 AVStream *st = s->streams[i];
540 AVCodecContext *codec = st->codec;
541 ebml_master subinfo, track;
544 int bit_depth = av_get_bits_per_sample(codec->codec_id);
545 int sample_rate = codec->sample_rate;
546 int output_sample_rate = 0;
547 AVDictionaryEntry *tag;
549 if (codec->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
550 mkv->have_attachments = 1;
555 bit_depth = av_get_bytes_per_sample(codec->sample_fmt) << 3;
557 if (codec->codec_id == AV_CODEC_ID_AAC)
558 get_aac_sample_rates(s, codec, &sample_rate, &output_sample_rate);
560 track = start_ebml_master(pb, MATROSKA_ID_TRACKENTRY, 0);
561 put_ebml_uint (pb, MATROSKA_ID_TRACKNUMBER , i + 1);
562 put_ebml_uint (pb, MATROSKA_ID_TRACKUID , i + 1);
563 put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0); // no lacing (yet)
565 if ((tag = av_dict_get(st->metadata, "title", NULL, 0)))
566 put_ebml_string(pb, MATROSKA_ID_TRACKNAME, tag->value);
567 tag = av_dict_get(st->metadata, "language", NULL, 0);
568 put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag ? tag->value:"und");
571 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGDEFAULT, !!(st->disposition & AV_DISPOSITION_DEFAULT));
573 // look for a codec ID string specific to mkv to use,
574 // if none are found, use AVI codes
575 for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
576 if (ff_mkv_codec_tags[j].id == codec->codec_id) {
577 put_ebml_string(pb, MATROSKA_ID_CODECID, ff_mkv_codec_tags[j].str);
583 if (mkv->mode == MODE_WEBM && !(codec->codec_id == AV_CODEC_ID_VP8 ||
584 codec->codec_id == AV_CODEC_ID_VORBIS)) {
585 av_log(s, AV_LOG_ERROR,
586 "Only VP8 video and Vorbis audio are supported for WebM.\n");
587 return AVERROR(EINVAL);
590 switch (codec->codec_type) {
591 case AVMEDIA_TYPE_VIDEO:
592 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_VIDEO);
593 if(st->avg_frame_rate.num && st->avg_frame_rate.den && 1.0/av_q2d(st->avg_frame_rate) > av_q2d(codec->time_base))
594 put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, 1E9/av_q2d(st->avg_frame_rate));
596 put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, av_q2d(codec->time_base)*1E9);
599 ff_codec_get_tag(ff_codec_movvideo_tags, codec->codec_id) &&
600 (!ff_codec_get_tag(ff_codec_bmp_tags, codec->codec_id)
601 || codec->codec_id == AV_CODEC_ID_SVQ1
602 || codec->codec_id == AV_CODEC_ID_SVQ3
603 || codec->codec_id == AV_CODEC_ID_CINEPAK))
607 put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");
608 else if (!native_id) {
609 // if there is no mkv-specific codec ID, use VFW mode
610 put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");
611 mkv->tracks[i].write_dts = 1;
614 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
615 // XXX: interlace flag?
616 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , codec->width);
617 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, codec->height);
619 if ((tag = av_dict_get(st->metadata, "stereo_mode", NULL, 0)) ||
620 (tag = av_dict_get( s->metadata, "stereo_mode", NULL, 0))) {
621 // save stereo mode flag
622 uint64_t st_mode = MATROSKA_VIDEO_STEREO_MODE_COUNT;
624 for (j=0; j<MATROSKA_VIDEO_STEREO_MODE_COUNT; j++)
625 if (!strcmp(tag->value, ff_matroska_video_stereo_mode[j])){
630 if ((mkv->mode == MODE_WEBM && st_mode > 3 && st_mode != 11)
631 || st_mode >= MATROSKA_VIDEO_STEREO_MODE_COUNT) {
632 av_log(s, AV_LOG_ERROR,
633 "The specified stereo mode is not valid.\n");
634 return AVERROR(EINVAL);
636 put_ebml_uint(pb, MATROSKA_ID_VIDEOSTEREOMODE, st_mode);
639 if (st->sample_aspect_ratio.num) {
640 int d_width = codec->width*av_q2d(st->sample_aspect_ratio);
641 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , d_width);
642 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, codec->height);
645 if (codec->codec_id == AV_CODEC_ID_RAWVIDEO) {
646 uint32_t color_space = av_le2ne32(codec->codec_tag);
647 put_ebml_binary(pb, MATROSKA_ID_VIDEOCOLORSPACE, &color_space, sizeof(color_space));
649 end_ebml_master(pb, subinfo);
652 case AVMEDIA_TYPE_AUDIO:
653 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_AUDIO);
656 // no mkv-specific ID, use ACM mode
657 put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");
659 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);
660 put_ebml_uint (pb, MATROSKA_ID_AUDIOCHANNELS , codec->channels);
661 put_ebml_float (pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, sample_rate);
662 if (output_sample_rate)
663 put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
665 put_ebml_uint(pb, MATROSKA_ID_AUDIOBITDEPTH, bit_depth);
666 end_ebml_master(pb, subinfo);
669 case AVMEDIA_TYPE_SUBTITLE:
670 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_SUBTITLE);
672 av_log(s, AV_LOG_ERROR, "Subtitle codec %d is not supported.\n", codec->codec_id);
673 return AVERROR(ENOSYS);
677 av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.\n");
680 ret = mkv_write_codecprivate(s, pb, codec, native_id, qt_id);
681 if (ret < 0) return ret;
683 end_ebml_master(pb, track);
685 // ms precision is the de-facto standard timescale for mkv files
686 avpriv_set_pts_info(st, 64, 1, 1000);
688 end_ebml_master(pb, tracks);
692 static int mkv_write_chapters(AVFormatContext *s)
694 MatroskaMuxContext *mkv = s->priv_data;
695 AVIOContext *pb = s->pb;
696 ebml_master chapters, editionentry;
697 AVRational scale = {1, 1E9};
703 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CHAPTERS, avio_tell(pb));
704 if (ret < 0) return ret;
706 chapters = start_ebml_master(pb, MATROSKA_ID_CHAPTERS , 0);
707 editionentry = start_ebml_master(pb, MATROSKA_ID_EDITIONENTRY, 0);
708 put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGDEFAULT, 1);
709 put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGHIDDEN , 0);
710 for (i = 0; i < s->nb_chapters; i++) {
711 ebml_master chapteratom, chapterdisplay;
712 AVChapter *c = s->chapters[i];
713 AVDictionaryEntry *t = NULL;
715 chapteratom = start_ebml_master(pb, MATROSKA_ID_CHAPTERATOM, 0);
716 put_ebml_uint(pb, MATROSKA_ID_CHAPTERUID, c->id);
717 put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMESTART,
718 av_rescale_q(c->start, c->time_base, scale));
719 put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMEEND,
720 av_rescale_q(c->end, c->time_base, scale));
721 put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGHIDDEN , 0);
722 put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGENABLED, 1);
723 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
724 chapterdisplay = start_ebml_master(pb, MATROSKA_ID_CHAPTERDISPLAY, 0);
725 put_ebml_string(pb, MATROSKA_ID_CHAPSTRING, t->value);
726 put_ebml_string(pb, MATROSKA_ID_CHAPLANG , "und");
727 end_ebml_master(pb, chapterdisplay);
729 end_ebml_master(pb, chapteratom);
731 end_ebml_master(pb, editionentry);
732 end_ebml_master(pb, chapters);
736 static void mkv_write_simpletag(AVIOContext *pb, AVDictionaryEntry *t)
738 uint8_t *key = av_strdup(t->key);
740 const uint8_t *lang = NULL;
743 if ((p = strrchr(p, '-')) &&
744 (lang = av_convert_lang_to(p + 1, AV_LANG_ISO639_2_BIBL)))
751 else if (*p >= 'a' && *p <= 'z')
756 tag = start_ebml_master(pb, MATROSKA_ID_SIMPLETAG, 0);
757 put_ebml_string(pb, MATROSKA_ID_TAGNAME, key);
759 put_ebml_string(pb, MATROSKA_ID_TAGLANG, lang);
760 put_ebml_string(pb, MATROSKA_ID_TAGSTRING, t->value);
761 end_ebml_master(pb, tag);
766 static int mkv_write_tag(AVFormatContext *s, AVDictionary *m, unsigned int elementid,
767 unsigned int uid, ebml_master *tags)
769 MatroskaMuxContext *mkv = s->priv_data;
770 ebml_master tag, targets;
771 AVDictionaryEntry *t = NULL;
775 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TAGS, avio_tell(s->pb));
776 if (ret < 0) return ret;
778 *tags = start_ebml_master(s->pb, MATROSKA_ID_TAGS, 0);
781 tag = start_ebml_master(s->pb, MATROSKA_ID_TAG, 0);
782 targets = start_ebml_master(s->pb, MATROSKA_ID_TAGTARGETS, 0);
784 put_ebml_uint(s->pb, elementid, uid);
785 end_ebml_master(s->pb, targets);
787 while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX)))
788 if (av_strcasecmp(t->key, "title") && av_strcasecmp(t->key, "stereo_mode"))
789 mkv_write_simpletag(s->pb, t);
791 end_ebml_master(s->pb, tag);
795 static int mkv_write_tags(AVFormatContext *s)
797 ebml_master tags = {0};
800 ff_metadata_conv_ctx(s, ff_mkv_metadata_conv, NULL);
802 if (av_dict_get(s->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX)) {
803 ret = mkv_write_tag(s, s->metadata, 0, 0, &tags);
804 if (ret < 0) return ret;
807 for (i = 0; i < s->nb_streams; i++) {
808 AVStream *st = s->streams[i];
810 if (!av_dict_get(st->metadata, "", 0, AV_DICT_IGNORE_SUFFIX))
813 ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &tags);
814 if (ret < 0) return ret;
817 for (i = 0; i < s->nb_chapters; i++) {
818 AVChapter *ch = s->chapters[i];
820 if (!av_dict_get(ch->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX))
823 ret = mkv_write_tag(s, ch->metadata, MATROSKA_ID_TAGTARGETS_CHAPTERUID, ch->id, &tags);
824 if (ret < 0) return ret;
828 end_ebml_master(s->pb, tags);
832 static int mkv_write_attachments(AVFormatContext *s)
834 MatroskaMuxContext *mkv = s->priv_data;
835 AVIOContext *pb = s->pb;
836 ebml_master attachments;
840 if (!mkv->have_attachments)
843 av_lfg_init(&c, av_get_random_seed());
845 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_ATTACHMENTS, avio_tell(pb));
846 if (ret < 0) return ret;
848 attachments = start_ebml_master(pb, MATROSKA_ID_ATTACHMENTS, 0);
850 for (i = 0; i < s->nb_streams; i++) {
851 AVStream *st = s->streams[i];
852 ebml_master attached_file;
853 AVDictionaryEntry *t;
854 const char *mimetype = NULL;
856 if (st->codec->codec_type != AVMEDIA_TYPE_ATTACHMENT)
859 attached_file = start_ebml_master(pb, MATROSKA_ID_ATTACHEDFILE, 0);
861 if (t = av_dict_get(st->metadata, "title", NULL, 0))
862 put_ebml_string(pb, MATROSKA_ID_FILEDESC, t->value);
863 if (!(t = av_dict_get(st->metadata, "filename", NULL, 0))) {
864 av_log(s, AV_LOG_ERROR, "Attachment stream %d has no filename tag.\n", i);
865 return AVERROR(EINVAL);
867 put_ebml_string(pb, MATROSKA_ID_FILENAME, t->value);
868 if (t = av_dict_get(st->metadata, "mimetype", NULL, 0))
870 else if (st->codec->codec_id != AV_CODEC_ID_NONE ) {
872 for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
873 if (ff_mkv_mime_tags[i].id == st->codec->codec_id) {
874 mimetype = ff_mkv_mime_tags[i].str;
879 av_log(s, AV_LOG_ERROR, "Attachment stream %d has no mimetype tag and "
880 "it cannot be deduced from the codec id.\n", i);
881 return AVERROR(EINVAL);
884 put_ebml_string(pb, MATROSKA_ID_FILEMIMETYPE, mimetype);
885 put_ebml_binary(pb, MATROSKA_ID_FILEDATA, st->codec->extradata, st->codec->extradata_size);
886 put_ebml_uint(pb, MATROSKA_ID_FILEUID, av_lfg_get(&c));
887 end_ebml_master(pb, attached_file);
889 end_ebml_master(pb, attachments);
894 static int mkv_write_header(AVFormatContext *s)
896 MatroskaMuxContext *mkv = s->priv_data;
897 AVIOContext *pb = s->pb;
898 ebml_master ebml_header, segment_info;
899 AVDictionaryEntry *tag;
902 if (!strcmp(s->oformat->name, "webm")) mkv->mode = MODE_WEBM;
903 else mkv->mode = MODE_MATROSKAv2;
905 if (s->avoid_negative_ts < 0)
906 s->avoid_negative_ts = 1;
908 mkv->tracks = av_mallocz(s->nb_streams * sizeof(*mkv->tracks));
910 return AVERROR(ENOMEM);
912 ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
913 put_ebml_uint (pb, EBML_ID_EBMLVERSION , 1);
914 put_ebml_uint (pb, EBML_ID_EBMLREADVERSION , 1);
915 put_ebml_uint (pb, EBML_ID_EBMLMAXIDLENGTH , 4);
916 put_ebml_uint (pb, EBML_ID_EBMLMAXSIZELENGTH , 8);
917 put_ebml_string (pb, EBML_ID_DOCTYPE , s->oformat->name);
918 put_ebml_uint (pb, EBML_ID_DOCTYPEVERSION , 2);
919 put_ebml_uint (pb, EBML_ID_DOCTYPEREADVERSION , 2);
920 end_ebml_master(pb, ebml_header);
922 mkv->segment = start_ebml_master(pb, MATROSKA_ID_SEGMENT, 0);
923 mkv->segment_offset = avio_tell(pb);
925 // we write 2 seek heads - one at the end of the file to point to each
926 // cluster, and one at the beginning to point to all other level one
927 // elements (including the seek head at the end of the file), which
928 // isn't more than 10 elements if we only write one of each other
929 // currently defined level 1 element
930 mkv->main_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 10);
931 if (!mkv->main_seekhead)
932 return AVERROR(ENOMEM);
934 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_INFO, avio_tell(pb));
935 if (ret < 0) return ret;
937 segment_info = start_ebml_master(pb, MATROSKA_ID_INFO, 0);
938 put_ebml_uint(pb, MATROSKA_ID_TIMECODESCALE, 1000000);
939 if ((tag = av_dict_get(s->metadata, "title", NULL, 0)))
940 put_ebml_string(pb, MATROSKA_ID_TITLE, tag->value);
941 if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
942 uint32_t segment_uid[4];
945 av_lfg_init(&lfg, av_get_random_seed());
947 for (i = 0; i < 4; i++)
948 segment_uid[i] = av_lfg_get(&lfg);
950 put_ebml_string(pb, MATROSKA_ID_MUXINGAPP , LIBAVFORMAT_IDENT);
951 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, LIBAVFORMAT_IDENT);
952 put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
955 if (tag = av_dict_get(s->metadata, "creation_time", NULL, 0)) {
956 // Adjust time so it's relative to 2001-01-01 and convert to nanoseconds.
957 int64_t date_utc = (ff_iso8601_to_unix_time(tag->value) - 978307200) * 1000000000;
958 uint8_t date_utc_buf[8];
959 AV_WB64(date_utc_buf, date_utc);
960 put_ebml_binary(pb, MATROSKA_ID_DATEUTC, date_utc_buf, 8);
963 // reserve space for the duration
965 mkv->duration_offset = avio_tell(pb);
966 put_ebml_void(pb, 11); // assumes double-precision float to be written
967 end_ebml_master(pb, segment_info);
969 ret = mkv_write_tracks(s);
970 if (ret < 0) return ret;
972 if (mkv->mode != MODE_WEBM) {
973 ret = mkv_write_chapters(s);
974 if (ret < 0) return ret;
976 ret = mkv_write_tags(s);
977 if (ret < 0) return ret;
979 ret = mkv_write_attachments(s);
980 if (ret < 0) return ret;
983 if (!s->pb->seekable)
984 mkv_write_seekhead(pb, mkv->main_seekhead);
986 mkv->cues = mkv_start_cues(mkv->segment_offset);
987 if (mkv->cues == NULL)
988 return AVERROR(ENOMEM);
990 av_init_packet(&mkv->cur_audio_pkt);
991 mkv->cur_audio_pkt.size = 0;
992 mkv->audio_buffer_size = 0;
993 mkv->cluster_pos = -1;
999 static int mkv_blockgroup_size(int pkt_size)
1001 int size = pkt_size + 4;
1002 size += ebml_num_size(size);
1003 size += 2; // EBML ID for block and block duration
1004 size += 8; // max size of block duration
1005 size += ebml_num_size(size);
1006 size += 1; // blockgroup EBML ID
1010 static int ass_get_duration(const uint8_t *p)
1012 int sh, sm, ss, sc, eh, em, es, ec;
1013 uint64_t start, end;
1015 if (sscanf(p, "%*[^,],%d:%d:%d%*c%d,%d:%d:%d%*c%d",
1016 &sh, &sm, &ss, &sc, &eh, &em, &es, &ec) != 8)
1018 start = 3600000LL*sh + 60000LL*sm + 1000LL*ss + 10LL*sc;
1019 end = 3600000LL*eh + 60000LL*em + 1000LL*es + 10LL*ec;
1023 static int mkv_write_ass_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
1025 MatroskaMuxContext *mkv = s->priv_data;
1026 int i, layer = 0, max_duration = 0, size, line_size, data_size = pkt->size;
1027 uint8_t *start, *end, *data = pkt->data;
1028 ebml_master blockgroup;
1032 int duration = ass_get_duration(data);
1033 max_duration = FFMAX(duration, max_duration);
1034 end = memchr(data, '\n', data_size);
1035 size = line_size = end ? end-data+1 : data_size;
1036 size -= end ? (end[-1]=='\r')+1 : 0;
1038 for (i=0; i<3; i++, start++)
1039 if (!(start = memchr(start, ',', size-(start-data))))
1040 return max_duration;
1041 size -= start - data;
1042 sscanf(data, "Dialogue: %d,", &layer);
1043 i = snprintf(buffer, sizeof(buffer), "%"PRId64",%d,",
1044 s->streams[pkt->stream_index]->nb_frames, layer);
1045 size = FFMIN(i+size, sizeof(buffer));
1046 memcpy(buffer+i, start, size-i);
1048 av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
1049 "pts %" PRId64 ", duration %d\n",
1050 avio_tell(pb), size, pkt->pts, duration);
1051 blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(size));
1052 put_ebml_id(pb, MATROSKA_ID_BLOCK);
1053 put_ebml_num(pb, size+4, 0);
1054 avio_w8(pb, 0x80 | (pkt->stream_index + 1)); // this assumes stream_index is less than 126
1055 avio_wb16(pb, pkt->pts - mkv->cluster_pts);
1057 avio_write(pb, buffer, size);
1058 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
1059 end_ebml_master(pb, blockgroup);
1062 data_size -= line_size;
1065 return max_duration;
1068 static void mkv_write_block(AVFormatContext *s, AVIOContext *pb,
1069 unsigned int blockid, AVPacket *pkt, int flags)
1071 MatroskaMuxContext *mkv = s->priv_data;
1072 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1073 uint8_t *data = NULL;
1074 int offset = 0, size = pkt->size;
1075 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1077 av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
1078 "pts %" PRId64 ", dts %" PRId64 ", duration %d, flags %d\n",
1079 avio_tell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration, flags);
1080 if (codec->codec_id == AV_CODEC_ID_H264 && codec->extradata_size > 0 &&
1081 (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
1082 ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
1086 if (codec->codec_id == AV_CODEC_ID_PRORES) {
1087 /* Matroska specification requires to remove the first QuickTime atom
1093 put_ebml_id(pb, blockid);
1094 put_ebml_num(pb, size+4, 0);
1095 avio_w8(pb, 0x80 | (pkt->stream_index + 1)); // this assumes stream_index is less than 126
1096 avio_wb16(pb, ts - mkv->cluster_pts);
1098 avio_write(pb, data + offset, size);
1099 if (data != pkt->data)
1103 static int srt_get_duration(uint8_t **buf)
1105 int i, duration = 0;
1107 for (i=0; i<2 && !duration; i++) {
1108 int s_hour, s_min, s_sec, s_hsec, e_hour, e_min, e_sec, e_hsec;
1109 if (sscanf(*buf, "%d:%2d:%2d%*1[,.]%3d --> %d:%2d:%2d%*1[,.]%3d",
1110 &s_hour, &s_min, &s_sec, &s_hsec,
1111 &e_hour, &e_min, &e_sec, &e_hsec) == 8) {
1112 s_min += 60*s_hour; e_min += 60*e_hour;
1113 s_sec += 60*s_min; e_sec += 60*e_min;
1114 s_hsec += 1000*s_sec; e_hsec += 1000*e_sec;
1115 duration = e_hsec - s_hsec;
1117 *buf += strcspn(*buf, "\n") + 1;
1122 static int mkv_write_srt_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
1124 ebml_master blockgroup;
1125 AVPacket pkt2 = *pkt;
1126 int64_t duration = srt_get_duration(&pkt2.data);
1127 pkt2.size -= pkt2.data - pkt->data;
1129 blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
1130 mkv_blockgroup_size(pkt2.size));
1131 mkv_write_block(s, pb, MATROSKA_ID_BLOCK, &pkt2, 0);
1132 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
1133 end_ebml_master(pb, blockgroup);
1138 static void mkv_flush_dynbuf(AVFormatContext *s)
1140 MatroskaMuxContext *mkv = s->priv_data;
1147 bufsize = avio_close_dyn_buf(mkv->dyn_bc, &dyn_buf);
1148 avio_write(s->pb, dyn_buf, bufsize);
1153 static int mkv_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
1155 MatroskaMuxContext *mkv = s->priv_data;
1156 AVIOContext *pb = s->pb;
1157 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1158 int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1159 int duration = pkt->duration;
1161 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1163 if (ts == AV_NOPTS_VALUE) {
1164 av_log(s, AV_LOG_ERROR, "Can't write packet with unknown timestamp\n");
1165 return AVERROR(EINVAL);
1168 if (!s->pb->seekable) {
1170 if ((ret = avio_open_dyn_buf(&mkv->dyn_bc)) < 0) {
1171 av_log(s, AV_LOG_ERROR, "Failed to open dynamic buffer\n");
1178 if (mkv->cluster_pos == -1) {
1179 mkv->cluster_pos = avio_tell(s->pb);
1180 mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER, 0);
1181 put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, FFMAX(0, ts));
1182 mkv->cluster_pts = FFMAX(0, ts);
1185 if (codec->codec_type != AVMEDIA_TYPE_SUBTITLE) {
1186 mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
1187 } else if (codec->codec_id == AV_CODEC_ID_SSA) {
1188 duration = mkv_write_ass_blocks(s, pb, pkt);
1189 } else if (codec->codec_id == AV_CODEC_ID_SRT) {
1190 duration = mkv_write_srt_blocks(s, pb, pkt);
1192 ebml_master blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(pkt->size));
1193 /* For backward compatibility, prefer convergence_duration. */
1194 if (pkt->convergence_duration > 0) {
1195 duration = pkt->convergence_duration;
1197 mkv_write_block(s, pb, MATROSKA_ID_BLOCK, pkt, 0);
1198 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
1199 end_ebml_master(pb, blockgroup);
1202 if (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe) {
1203 ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, ts, mkv->cluster_pos);
1204 if (ret < 0) return ret;
1207 mkv->duration = FFMAX(mkv->duration, ts + duration);
1211 static int mkv_copy_packet(MatroskaMuxContext *mkv, const AVPacket *pkt)
1213 uint8_t *data = mkv->cur_audio_pkt.data;
1214 mkv->cur_audio_pkt = *pkt;
1215 mkv->cur_audio_pkt.data = av_fast_realloc(data, &mkv->audio_buffer_size, pkt->size);
1216 if (!mkv->cur_audio_pkt.data)
1217 return AVERROR(ENOMEM);
1219 memcpy(mkv->cur_audio_pkt.data, pkt->data, pkt->size);
1220 mkv->cur_audio_pkt.size = pkt->size;
1224 static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
1226 MatroskaMuxContext *mkv = s->priv_data;
1227 AVIOContext *pb = s->pb->seekable ? s->pb : mkv->dyn_bc;
1228 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1229 int ret, keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1230 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1231 int cluster_size = avio_tell(pb) - (s->pb->seekable ? mkv->cluster_pos : 0);
1233 // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1234 // after 4k and on a keyframe
1235 if (mkv->cluster_pos != -1 &&
1236 ((!s->pb->seekable && (cluster_size > 32*1024 || ts > mkv->cluster_pts + 1000))
1237 || cluster_size > 5*1024*1024 || ts > mkv->cluster_pts + 5000
1238 || (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe && cluster_size > 4*1024))) {
1239 av_log(s, AV_LOG_DEBUG, "Starting new cluster at offset %" PRIu64
1240 " bytes, pts %" PRIu64 "\n", avio_tell(pb), ts);
1241 end_ebml_master(pb, mkv->cluster);
1242 mkv->cluster_pos = -1;
1244 mkv_flush_dynbuf(s);
1247 // check if we have an audio packet cached
1248 if (mkv->cur_audio_pkt.size > 0) {
1249 ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
1250 mkv->cur_audio_pkt.size = 0;
1252 av_log(s, AV_LOG_ERROR, "Could not write cached audio packet ret:%d\n", ret);
1257 // buffer an audio packet to ensure the packet containing the video
1258 // keyframe's timecode is contained in the same cluster for WebM
1259 if (codec->codec_type == AVMEDIA_TYPE_AUDIO)
1260 ret = mkv_copy_packet(mkv, pkt);
1262 ret = mkv_write_packet_internal(s, pkt);
1266 static int mkv_write_trailer(AVFormatContext *s)
1268 MatroskaMuxContext *mkv = s->priv_data;
1269 AVIOContext *pb = s->pb;
1270 int64_t currentpos, cuespos;
1273 // check if we have an audio packet cached
1274 if (mkv->cur_audio_pkt.size > 0) {
1275 ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
1276 mkv->cur_audio_pkt.size = 0;
1278 av_log(s, AV_LOG_ERROR, "Could not write cached audio packet ret:%d\n", ret);
1284 end_ebml_master(mkv->dyn_bc, mkv->cluster);
1285 mkv_flush_dynbuf(s);
1286 } else if (mkv->cluster_pos != -1) {
1287 end_ebml_master(pb, mkv->cluster);
1291 if (mkv->cues->num_entries) {
1292 cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
1294 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CUES, cuespos);
1295 if (ret < 0) return ret;
1298 mkv_write_seekhead(pb, mkv->main_seekhead);
1300 // update the duration
1301 av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
1302 currentpos = avio_tell(pb);
1303 avio_seek(pb, mkv->duration_offset, SEEK_SET);
1304 put_ebml_float(pb, MATROSKA_ID_DURATION, mkv->duration);
1306 avio_seek(pb, currentpos, SEEK_SET);
1309 end_ebml_master(pb, mkv->segment);
1310 av_free(mkv->tracks);
1311 av_freep(&mkv->cues->entries);
1312 av_freep(&mkv->cues);
1313 av_destruct_packet(&mkv->cur_audio_pkt);
1318 static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
1321 for (i = 0; ff_mkv_codec_tags[i].id != AV_CODEC_ID_NONE; i++)
1322 if (ff_mkv_codec_tags[i].id == codec_id)
1325 if (std_compliance < FF_COMPLIANCE_NORMAL) { // mkv theoretically supports any
1326 enum AVMediaType type = avcodec_get_type(codec_id); // video/audio through VFW/ACM
1327 if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)
1334 #if CONFIG_MATROSKA_MUXER
1335 AVOutputFormat ff_matroska_muxer = {
1337 .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
1338 .mime_type = "video/x-matroska",
1339 .extensions = "mkv",
1340 .priv_data_size = sizeof(MatroskaMuxContext),
1341 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
1342 AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
1343 .video_codec = CONFIG_LIBX264_ENCODER ?
1344 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
1345 .write_header = mkv_write_header,
1346 .write_packet = mkv_write_packet,
1347 .write_trailer = mkv_write_trailer,
1348 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
1350 .subtitle_codec = AV_CODEC_ID_SSA,
1351 .query_codec = mkv_query_codec,
1355 #if CONFIG_WEBM_MUXER
1356 AVOutputFormat ff_webm_muxer = {
1358 .long_name = NULL_IF_CONFIG_SMALL("WebM"),
1359 .mime_type = "video/webm",
1360 .extensions = "webm",
1361 .priv_data_size = sizeof(MatroskaMuxContext),
1362 .audio_codec = AV_CODEC_ID_VORBIS,
1363 .video_codec = AV_CODEC_ID_VP8,
1364 .write_header = mkv_write_header,
1365 .write_packet = mkv_write_packet,
1366 .write_trailer = mkv_write_trailer,
1367 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
1372 #if CONFIG_MATROSKA_AUDIO_MUXER
1373 AVOutputFormat ff_matroska_audio_muxer = {
1375 .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
1376 .mime_type = "audio/x-matroska",
1377 .extensions = "mka",
1378 .priv_data_size = sizeof(MatroskaMuxContext),
1379 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
1380 AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
1381 .video_codec = AV_CODEC_ID_NONE,
1382 .write_header = mkv_write_header,
1383 .write_packet = mkv_write_packet,
1384 .write_trailer = mkv_write_trailer,
1385 .flags = AVFMT_GLOBALHEADER | AVFMT_TS_NONSTRICT,