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
27 #include "avio_internal.h"
28 #include "avlanguage.h"
34 #include "subtitles.h"
35 #include "vorbiscomment.h"
38 #include "libavutil/avstring.h"
39 #include "libavutil/channel_layout.h"
40 #include "libavutil/dict.h"
41 #include "libavutil/intfloat.h"
42 #include "libavutil/intreadwrite.h"
43 #include "libavutil/lfg.h"
44 #include "libavutil/mathematics.h"
45 #include "libavutil/opt.h"
46 #include "libavutil/random_seed.h"
47 #include "libavutil/samplefmt.h"
48 #include "libavutil/sha.h"
50 #include "libavcodec/xiph.h"
51 #include "libavcodec/mpeg4audio.h"
52 #include "libavcodec/internal.h"
54 typedef struct ebml_master {
55 int64_t pos; ///< absolute offset in the file where the master's elements start
56 int sizebytes; ///< how many bytes were reserved for the size
59 typedef struct mkv_seekhead_entry {
60 unsigned int elementid;
64 typedef struct mkv_seekhead {
66 int64_t segment_offset; ///< the file offset to the beginning of the segment
67 int reserved_size; ///< -1 if appending to file
69 mkv_seekhead_entry *entries;
77 int64_t cluster_pos; ///< file offset of the cluster containing the block
78 int64_t relative_pos; ///< relative offset from the position of the cluster containing the block
79 int64_t duration; ///< duration of the block according to time base
83 int64_t segment_offset;
84 mkv_cuepoint *entries;
94 #define MODE_MATROSKAv2 0x01
95 #define MODE_WEBM 0x02
97 typedef struct MatroskaMuxContext {
102 int64_t segment_offset;
104 int64_t cluster_pos; ///< file offset of the current cluster
106 int64_t duration_offset;
108 mkv_seekhead *main_seekhead;
112 AVPacket cur_audio_pkt;
114 int have_attachments;
116 int reserve_cues_space;
117 int cluster_size_limit;
119 int64_t cluster_time_limit;
121 int dash_track_number;
123 uint32_t chapter_id_offset;
125 } MatroskaMuxContext;
128 /** 2 bytes * 3 for EBML IDs, 3 1-byte EBML lengths, 8 bytes for 64 bit
129 * offset, 4 bytes for target EBML ID */
130 #define MAX_SEEKENTRY_SIZE 21
132 /** per-cuepoint-track - 5 1-byte EBML IDs, 5 1-byte EBML sizes, 4
134 #define MAX_CUETRACKPOS_SIZE 42
136 /** per-cuepoint - 2 1-byte EBML IDs, 2 1-byte EBML sizes, 8-byte uint max */
137 #define MAX_CUEPOINT_SIZE(num_tracks) 12 + MAX_CUETRACKPOS_SIZE * num_tracks
139 /** Seek preroll value for opus */
140 #define OPUS_SEEK_PREROLL 80000000
142 static int ebml_id_size(unsigned int id)
144 return (av_log2(id + 1) - 1) / 7 + 1;
147 static void put_ebml_id(AVIOContext *pb, unsigned int id)
149 int i = ebml_id_size(id);
151 avio_w8(pb, (uint8_t)(id >> (i * 8)));
155 * Write an EBML size meaning "unknown size".
157 * @param bytes The number of bytes the size should occupy (maximum: 8).
159 static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
161 av_assert0(bytes <= 8);
162 avio_w8(pb, 0x1ff >> bytes);
163 ffio_fill(pb, 0xff, bytes - 1);
167 * Calculate how many bytes are needed to represent a given number in EBML.
169 static int ebml_num_size(uint64_t num)
172 while ((num + 1) >> bytes * 7)
178 * Write a number in EBML variable length format.
180 * @param bytes The number of bytes that need to be used to write the number.
181 * If zero, any number of bytes can be used.
183 static void put_ebml_num(AVIOContext *pb, uint64_t num, int bytes)
185 int i, needed_bytes = ebml_num_size(num);
187 // sizes larger than this are currently undefined in EBML
188 av_assert0(num < (1ULL << 56) - 1);
191 // don't care how many bytes are used, so use the min
192 bytes = needed_bytes;
193 // the bytes needed to write the given size would exceed the bytes
194 // that we need to use, so write unknown size. This shouldn't happen.
195 av_assert0(bytes >= needed_bytes);
197 num |= 1ULL << bytes * 7;
198 for (i = bytes - 1; i >= 0; i--)
199 avio_w8(pb, (uint8_t)(num >> i * 8));
202 static void put_ebml_uint(AVIOContext *pb, unsigned int elementid, uint64_t val)
209 put_ebml_id(pb, elementid);
210 put_ebml_num(pb, bytes, 0);
211 for (i = bytes - 1; i >= 0; i--)
212 avio_w8(pb, (uint8_t)(val >> i * 8));
215 static void put_ebml_sint(AVIOContext *pb, unsigned int elementid, int64_t val)
218 uint64_t tmp = 2*(val < 0 ? val^-1 : val);
220 while (tmp>>=8) bytes++;
222 put_ebml_id(pb, elementid);
223 put_ebml_num(pb, bytes, 0);
224 for (i = bytes - 1; i >= 0; i--)
225 avio_w8(pb, (uint8_t)(val >> i * 8));
228 static void put_ebml_float(AVIOContext *pb, unsigned int elementid, double val)
230 put_ebml_id(pb, elementid);
231 put_ebml_num(pb, 8, 0);
232 avio_wb64(pb, av_double2int(val));
235 static void put_ebml_binary(AVIOContext *pb, unsigned int elementid,
236 const void *buf, int size)
238 put_ebml_id(pb, elementid);
239 put_ebml_num(pb, size, 0);
240 avio_write(pb, buf, size);
243 static void put_ebml_string(AVIOContext *pb, unsigned int elementid,
246 put_ebml_binary(pb, elementid, str, strlen(str));
250 * Write a void element of a given size. Useful for reserving space in
251 * the file to be written to later.
253 * @param size The number of bytes to reserve, which must be at least 2.
255 static void put_ebml_void(AVIOContext *pb, uint64_t size)
257 int64_t currentpos = avio_tell(pb);
259 av_assert0(size >= 2);
261 put_ebml_id(pb, EBML_ID_VOID);
262 // we need to subtract the length needed to store the size from the
263 // size we need to reserve so 2 cases, we use 8 bytes to store the
264 // size if possible, 1 byte otherwise
266 put_ebml_num(pb, size - 1, 0);
268 put_ebml_num(pb, size - 9, 8);
269 ffio_fill(pb, 0, currentpos + size - avio_tell(pb));
272 static ebml_master start_ebml_master(AVIOContext *pb, unsigned int elementid,
273 uint64_t expectedsize)
275 int bytes = expectedsize ? ebml_num_size(expectedsize) : 8;
276 put_ebml_id(pb, elementid);
277 put_ebml_size_unknown(pb, bytes);
278 return (ebml_master) {avio_tell(pb), bytes };
281 static void end_ebml_master(AVIOContext *pb, ebml_master master)
283 int64_t pos = avio_tell(pb);
285 if (avio_seek(pb, master.pos - master.sizebytes, SEEK_SET) < 0)
287 put_ebml_num(pb, pos - master.pos, master.sizebytes);
288 avio_seek(pb, pos, SEEK_SET);
291 static void put_xiph_size(AVIOContext *pb, int size)
293 ffio_fill(pb, 255, size / 255);
294 avio_w8(pb, size % 255);
298 * Initialize a mkv_seekhead element to be ready to index level 1 Matroska
299 * elements. If a maximum number of elements is specified, enough space
300 * will be reserved at the current file location to write a seek head of
303 * @param segment_offset The absolute offset to the position in the file
304 * where the segment begins.
305 * @param numelements The maximum number of elements that will be indexed
306 * by this seek head, 0 if unlimited.
308 static mkv_seekhead *mkv_start_seekhead(AVIOContext *pb, int64_t segment_offset,
311 mkv_seekhead *new_seekhead = av_mallocz(sizeof(mkv_seekhead));
312 if (new_seekhead == NULL)
315 new_seekhead->segment_offset = segment_offset;
317 if (numelements > 0) {
318 new_seekhead->filepos = avio_tell(pb);
319 // 21 bytes max for a seek entry, 10 bytes max for the SeekHead ID
320 // and size, and 3 bytes to guarantee that an EBML void element
321 // will fit afterwards
322 new_seekhead->reserved_size = numelements * MAX_SEEKENTRY_SIZE + 13;
323 new_seekhead->max_entries = numelements;
324 put_ebml_void(pb, new_seekhead->reserved_size);
329 static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
331 mkv_seekhead_entry *entries = seekhead->entries;
333 // don't store more elements than we reserved space for
334 if (seekhead->max_entries > 0 && seekhead->max_entries <= seekhead->num_entries)
337 entries = av_realloc_array(entries, seekhead->num_entries + 1, sizeof(mkv_seekhead_entry));
339 return AVERROR(ENOMEM);
340 seekhead->entries = entries;
342 seekhead->entries[seekhead->num_entries].elementid = elementid;
343 seekhead->entries[seekhead->num_entries++].segmentpos = filepos - seekhead->segment_offset;
349 * Write the seek head to the file and free it. If a maximum number of
350 * elements was specified to mkv_start_seekhead(), the seek head will
351 * be written at the location reserved for it. Otherwise, it is written
352 * at the current location in the file.
354 * @return The file offset where the seekhead was written,
355 * -1 if an error occurred.
357 static int64_t mkv_write_seekhead(AVIOContext *pb, mkv_seekhead *seekhead)
359 ebml_master metaseek, seekentry;
363 currentpos = avio_tell(pb);
365 if (seekhead->reserved_size > 0) {
366 if (avio_seek(pb, seekhead->filepos, SEEK_SET) < 0) {
372 metaseek = start_ebml_master(pb, MATROSKA_ID_SEEKHEAD, seekhead->reserved_size);
373 for (i = 0; i < seekhead->num_entries; i++) {
374 mkv_seekhead_entry *entry = &seekhead->entries[i];
376 seekentry = start_ebml_master(pb, MATROSKA_ID_SEEKENTRY, MAX_SEEKENTRY_SIZE);
378 put_ebml_id(pb, MATROSKA_ID_SEEKID);
379 put_ebml_num(pb, ebml_id_size(entry->elementid), 0);
380 put_ebml_id(pb, entry->elementid);
382 put_ebml_uint(pb, MATROSKA_ID_SEEKPOSITION, entry->segmentpos);
383 end_ebml_master(pb, seekentry);
385 end_ebml_master(pb, metaseek);
387 if (seekhead->reserved_size > 0) {
388 uint64_t remaining = seekhead->filepos + seekhead->reserved_size - avio_tell(pb);
389 put_ebml_void(pb, remaining);
390 avio_seek(pb, currentpos, SEEK_SET);
392 currentpos = seekhead->filepos;
395 av_freep(&seekhead->entries);
401 static mkv_cues *mkv_start_cues(int64_t segment_offset)
403 mkv_cues *cues = av_mallocz(sizeof(mkv_cues));
407 cues->segment_offset = segment_offset;
411 static int mkv_add_cuepoint(mkv_cues *cues, int stream, int tracknum, int64_t ts,
412 int64_t cluster_pos, int64_t relative_pos, int64_t duration)
414 mkv_cuepoint *entries = cues->entries;
419 entries = av_realloc_array(entries, cues->num_entries + 1, sizeof(mkv_cuepoint));
421 return AVERROR(ENOMEM);
422 cues->entries = entries;
424 cues->entries[cues->num_entries].pts = ts;
425 cues->entries[cues->num_entries].stream_idx = stream;
426 cues->entries[cues->num_entries].tracknum = tracknum;
427 cues->entries[cues->num_entries].cluster_pos = cluster_pos - cues->segment_offset;
428 cues->entries[cues->num_entries].relative_pos = relative_pos;
429 cues->entries[cues->num_entries++].duration = duration;
434 static int64_t mkv_write_cues(AVFormatContext *s, mkv_cues *cues, mkv_track *tracks, int num_tracks)
436 AVIOContext *pb = s->pb;
437 ebml_master cues_element;
441 currentpos = avio_tell(pb);
442 cues_element = start_ebml_master(pb, MATROSKA_ID_CUES, 0);
444 for (i = 0; i < cues->num_entries; i++) {
445 ebml_master cuepoint, track_positions;
446 mkv_cuepoint *entry = &cues->entries[i];
447 uint64_t pts = entry->pts;
450 // Calculate the number of entries, so we know the element size
451 for (j = 0; j < num_tracks; j++)
452 tracks[j].has_cue = 0;
453 for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
454 int tracknum = entry[j].stream_idx;
455 av_assert0(tracknum>=0 && tracknum<num_tracks);
456 if (tracks[tracknum].has_cue && s->streams[tracknum]->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
458 tracks[tracknum].has_cue = 1;
462 cuepoint = start_ebml_master(pb, MATROSKA_ID_POINTENTRY, MAX_CUEPOINT_SIZE(ctp_nb));
463 put_ebml_uint(pb, MATROSKA_ID_CUETIME, pts);
465 // put all the entries from different tracks that have the exact same
466 // timestamp into the same CuePoint
467 for (j = 0; j < num_tracks; j++)
468 tracks[j].has_cue = 0;
469 for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
470 int tracknum = entry[j].stream_idx;
471 av_assert0(tracknum>=0 && tracknum<num_tracks);
472 if (tracks[tracknum].has_cue && s->streams[tracknum]->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
474 tracks[tracknum].has_cue = 1;
475 track_positions = start_ebml_master(pb, MATROSKA_ID_CUETRACKPOSITION, MAX_CUETRACKPOS_SIZE);
476 put_ebml_uint(pb, MATROSKA_ID_CUETRACK , entry[j].tracknum );
477 put_ebml_uint(pb, MATROSKA_ID_CUECLUSTERPOSITION , entry[j].cluster_pos);
478 put_ebml_uint(pb, MATROSKA_ID_CUERELATIVEPOSITION, entry[j].relative_pos);
479 if (entry[j].duration != -1)
480 put_ebml_uint(pb, MATROSKA_ID_CUEDURATION , entry[j].duration);
481 end_ebml_master(pb, track_positions);
484 end_ebml_master(pb, cuepoint);
486 end_ebml_master(pb, cues_element);
491 static int put_xiph_codecpriv(AVFormatContext *s, AVIOContext *pb, AVCodecContext *codec)
493 uint8_t *header_start[3];
495 int first_header_size;
498 if (codec->codec_id == AV_CODEC_ID_VORBIS)
499 first_header_size = 30;
501 first_header_size = 42;
503 if (avpriv_split_xiph_headers(codec->extradata, codec->extradata_size,
504 first_header_size, header_start, header_len) < 0) {
505 av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
509 avio_w8(pb, 2); // number packets - 1
510 for (j = 0; j < 2; j++) {
511 put_xiph_size(pb, header_len[j]);
513 for (j = 0; j < 3; j++)
514 avio_write(pb, header_start[j], header_len[j]);
519 static int put_wv_codecpriv(AVIOContext *pb, AVCodecContext *codec)
521 if (codec->extradata && codec->extradata_size == 2)
522 avio_write(pb, codec->extradata, 2);
524 avio_wl16(pb, 0x403); // fallback to the version mentioned in matroska specs
528 static int put_flac_codecpriv(AVFormatContext *s,
529 AVIOContext *pb, AVCodecContext *codec)
531 int write_comment = (codec->channel_layout &&
532 !(codec->channel_layout & ~0x3ffffULL) &&
533 !ff_flac_is_native_layout(codec->channel_layout));
534 int ret = ff_flac_write_header(pb, codec->extradata, codec->extradata_size,
541 const char *vendor = (s->flags & AVFMT_FLAG_BITEXACT) ?
542 "Lavf" : LIBAVFORMAT_IDENT;
543 AVDictionary *dict = NULL;
544 uint8_t buf[32], *data, *p;
547 snprintf(buf, sizeof(buf), "0x%"PRIx64, codec->channel_layout);
548 av_dict_set(&dict, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", buf, 0);
550 len = ff_vorbiscomment_length(dict, vendor);
551 data = av_malloc(len + 4);
554 return AVERROR(ENOMEM);
558 AV_WB24(data + 1, len);
561 ff_vorbiscomment_write(&p, &dict, vendor);
563 avio_write(pb, data, len + 4);
572 static void get_aac_sample_rates(AVFormatContext *s, AVCodecContext *codec,
573 int *sample_rate, int *output_sample_rate)
575 MPEG4AudioConfig mp4ac;
577 if (avpriv_mpeg4audio_get_config(&mp4ac, codec->extradata,
578 codec->extradata_size * 8, 1) < 0) {
579 av_log(s, AV_LOG_WARNING,
580 "Error parsing AAC extradata, unable to determine samplerate.\n");
584 *sample_rate = mp4ac.sample_rate;
585 *output_sample_rate = mp4ac.ext_sample_rate;
588 static int mkv_write_native_codecprivate(AVFormatContext *s,
589 AVCodecContext *codec,
592 switch (codec->codec_id) {
593 case AV_CODEC_ID_VORBIS:
594 case AV_CODEC_ID_THEORA:
595 return put_xiph_codecpriv(s, dyn_cp, codec);
596 case AV_CODEC_ID_FLAC:
597 return put_flac_codecpriv(s, dyn_cp, codec);
598 case AV_CODEC_ID_WAVPACK:
599 return put_wv_codecpriv(dyn_cp, codec);
600 case AV_CODEC_ID_H264:
601 return ff_isom_write_avcc(dyn_cp, codec->extradata,
602 codec->extradata_size);
603 case AV_CODEC_ID_HEVC:
604 return ff_isom_write_hvcc(dyn_cp, codec->extradata,
605 codec->extradata_size, 0);
606 case AV_CODEC_ID_ALAC:
607 if (codec->extradata_size < 36) {
608 av_log(s, AV_LOG_ERROR,
609 "Invalid extradata found, ALAC expects a 36-byte "
611 return AVERROR_INVALIDDATA;
613 avio_write(dyn_cp, codec->extradata + 12,
614 codec->extradata_size - 12);
617 if (codec->codec_id == AV_CODEC_ID_PRORES &&
618 ff_codec_get_id(ff_codec_movvideo_tags, codec->codec_tag) == AV_CODEC_ID_PRORES) {
619 avio_wl32(dyn_cp, codec->codec_tag);
620 } else if (codec->extradata_size && codec->codec_id != AV_CODEC_ID_TTA)
621 avio_write(dyn_cp, codec->extradata, codec->extradata_size);
627 static int mkv_write_codecprivate(AVFormatContext *s, AVIOContext *pb,
628 AVCodecContext *codec, int native_id,
633 int ret, codecpriv_size;
635 ret = avio_open_dyn_buf(&dyn_cp);
640 ret = mkv_write_native_codecprivate(s, codec, dyn_cp);
641 } else if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
643 if (!codec->codec_tag)
644 codec->codec_tag = ff_codec_get_tag(ff_codec_movvideo_tags,
646 if (codec->extradata_size) {
647 if ( ff_codec_get_id(ff_codec_movvideo_tags, codec->codec_tag) == codec->codec_id
648 && ff_codec_get_id(ff_codec_movvideo_tags, AV_RL32(codec->extradata + 4)) != codec->codec_id
651 avio_wb32(dyn_cp, 0x5a + codec->extradata_size);
652 avio_wl32(dyn_cp, codec->codec_tag);
653 for(i = 0; i < 0x5a - 8; i++)
656 avio_write(dyn_cp, codec->extradata, codec->extradata_size);
659 if (!ff_codec_get_tag(ff_codec_bmp_tags, codec->codec_id))
660 av_log(s, AV_LOG_WARNING, "codec %s is not supported by this format\n",
661 avcodec_get_name(codec->codec_id));
663 if (!codec->codec_tag)
664 codec->codec_tag = ff_codec_get_tag(ff_codec_bmp_tags,
666 if (!codec->codec_tag) {
667 av_log(s, AV_LOG_ERROR, "No bmp codec tag found for codec %s\n",
668 avcodec_get_name(codec->codec_id));
669 ret = AVERROR(EINVAL);
672 ff_put_bmp_header(dyn_cp, codec, ff_codec_bmp_tags, 0, 0);
674 } else if (codec->codec_type == AVMEDIA_TYPE_AUDIO) {
676 tag = ff_codec_get_tag(ff_codec_wav_tags, codec->codec_id);
678 av_log(s, AV_LOG_ERROR, "No wav codec tag found for codec %s\n",
679 avcodec_get_name(codec->codec_id));
680 ret = AVERROR(EINVAL);
682 if (!codec->codec_tag)
683 codec->codec_tag = tag;
685 ff_put_wav_header(dyn_cp, codec, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX);
688 codecpriv_size = avio_close_dyn_buf(dyn_cp, &codecpriv);
690 put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codecpriv,
696 static int mkv_write_stereo_mode(AVFormatContext *s, AVIOContext *pb, int st_mode,
699 if ((mode == MODE_WEBM && st_mode > 3 && st_mode != 11)
700 || st_mode >= MATROSKA_VIDEO_STEREO_MODE_COUNT) {
701 av_log(s, AV_LOG_ERROR,
702 "The specified stereo mode is not valid.\n");
703 return AVERROR(EINVAL);
705 put_ebml_uint(pb, MATROSKA_ID_VIDEOSTEREOMODE, st_mode);
710 static int mkv_write_track(AVFormatContext *s, MatroskaMuxContext *mkv,
711 int i, AVIOContext *pb, int default_stream_exists)
713 AVStream *st = s->streams[i];
714 AVCodecContext *codec = st->codec;
715 ebml_master subinfo, track;
718 int bit_depth = av_get_bits_per_sample(codec->codec_id);
719 int sample_rate = codec->sample_rate;
720 int output_sample_rate = 0;
721 int display_width_div = 1;
722 int display_height_div = 1;
724 AVDictionaryEntry *tag;
726 // ms precision is the de-facto standard timescale for mkv files
727 avpriv_set_pts_info(st, 64, 1, 1000);
729 if (codec->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
730 mkv->have_attachments = 1;
734 if (!bit_depth && codec->codec_id != AV_CODEC_ID_ADPCM_G726)
735 bit_depth = av_get_bytes_per_sample(codec->sample_fmt) << 3;
737 bit_depth = codec->bits_per_coded_sample;
739 if (codec->codec_id == AV_CODEC_ID_AAC)
740 get_aac_sample_rates(s, codec, &sample_rate, &output_sample_rate);
742 track = start_ebml_master(pb, MATROSKA_ID_TRACKENTRY, 0);
743 put_ebml_uint (pb, MATROSKA_ID_TRACKNUMBER,
744 mkv->is_dash ? mkv->dash_track_number : i + 1);
745 put_ebml_uint (pb, MATROSKA_ID_TRACKUID,
746 mkv->is_dash ? mkv->dash_track_number : i + 1);
747 put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0); // no lacing (yet)
749 if ((tag = av_dict_get(st->metadata, "title", NULL, 0)))
750 put_ebml_string(pb, MATROSKA_ID_TRACKNAME, tag->value);
751 tag = av_dict_get(st->metadata, "language", NULL, 0);
752 if (mkv->mode != MODE_WEBM || codec->codec_id != AV_CODEC_ID_WEBVTT) {
753 put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag && tag->value ? tag->value:"und");
754 } else if (tag && tag->value) {
755 put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag->value);
758 // The default value for TRACKFLAGDEFAULT is 1, so add element
759 // if we need to clear it.
760 if (default_stream_exists && !(st->disposition & AV_DISPOSITION_DEFAULT))
761 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGDEFAULT, !!(st->disposition & AV_DISPOSITION_DEFAULT));
763 if (st->disposition & AV_DISPOSITION_FORCED)
764 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGFORCED, 1);
766 if (mkv->mode == MODE_WEBM && codec->codec_id == AV_CODEC_ID_WEBVTT) {
767 const char *codec_id;
768 if (st->disposition & AV_DISPOSITION_CAPTIONS) {
769 codec_id = "D_WEBVTT/CAPTIONS";
770 native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
771 } else if (st->disposition & AV_DISPOSITION_DESCRIPTIONS) {
772 codec_id = "D_WEBVTT/DESCRIPTIONS";
773 native_id = MATROSKA_TRACK_TYPE_METADATA;
774 } else if (st->disposition & AV_DISPOSITION_METADATA) {
775 codec_id = "D_WEBVTT/METADATA";
776 native_id = MATROSKA_TRACK_TYPE_METADATA;
778 codec_id = "D_WEBVTT/SUBTITLES";
779 native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
781 put_ebml_string(pb, MATROSKA_ID_CODECID, codec_id);
783 // look for a codec ID string specific to mkv to use,
784 // if none are found, use AVI codes
785 for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
786 if (ff_mkv_codec_tags[j].id == codec->codec_id) {
787 put_ebml_string(pb, MATROSKA_ID_CODECID, ff_mkv_codec_tags[j].str);
794 if (codec->codec_type == AVMEDIA_TYPE_AUDIO && codec->delay && codec->codec_id == AV_CODEC_ID_OPUS) {
795 // mkv->tracks[i].ts_offset = av_rescale_q(codec->delay,
796 // (AVRational){ 1, codec->sample_rate },
799 put_ebml_uint(pb, MATROSKA_ID_CODECDELAY,
800 av_rescale_q(codec->delay, (AVRational){ 1, codec->sample_rate },
801 (AVRational){ 1, 1000000000 }));
803 if (codec->codec_id == AV_CODEC_ID_OPUS) {
804 put_ebml_uint(pb, MATROSKA_ID_SEEKPREROLL, OPUS_SEEK_PREROLL);
807 if (mkv->mode == MODE_WEBM && !(codec->codec_id == AV_CODEC_ID_VP8 ||
808 codec->codec_id == AV_CODEC_ID_VP9 ||
809 codec->codec_id == AV_CODEC_ID_OPUS ||
810 codec->codec_id == AV_CODEC_ID_VORBIS ||
811 codec->codec_id == AV_CODEC_ID_WEBVTT)) {
812 av_log(s, AV_LOG_ERROR,
813 "Only VP8 or VP9 video and Vorbis or Opus audio and WebVTT subtitles are supported for WebM.\n");
814 return AVERROR(EINVAL);
817 switch (codec->codec_type) {
818 case AVMEDIA_TYPE_VIDEO:
819 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_VIDEO);
821 if( st->avg_frame_rate.num > 0 && st->avg_frame_rate.den > 0
822 && 1.0/av_q2d(st->avg_frame_rate) > av_q2d(codec->time_base))
823 put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, 1E9 / av_q2d(st->avg_frame_rate));
825 put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, av_q2d(codec->time_base)*1E9);
828 ff_codec_get_tag(ff_codec_movvideo_tags, codec->codec_id) &&
829 (!ff_codec_get_tag(ff_codec_bmp_tags, codec->codec_id) ||
830 codec->codec_id == AV_CODEC_ID_SVQ1 ||
831 codec->codec_id == AV_CODEC_ID_SVQ3 ||
832 codec->codec_id == AV_CODEC_ID_CINEPAK))
836 put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");
837 else if (!native_id) {
838 // if there is no mkv-specific codec ID, use VFW mode
839 put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");
840 mkv->tracks[i].write_dts = 1;
843 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
844 // XXX: interlace flag?
845 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , codec->width);
846 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, codec->height);
848 if ((tag = av_dict_get(st->metadata, "stereo_mode", NULL, 0)) ||
849 (tag = av_dict_get( s->metadata, "stereo_mode", NULL, 0))) {
850 int st_mode = MATROSKA_VIDEO_STEREO_MODE_COUNT;
852 for (j=0; j<MATROSKA_VIDEO_STEREO_MODE_COUNT; j++)
853 if (!strcmp(tag->value, ff_matroska_video_stereo_mode[j])){
858 if (mkv_write_stereo_mode(s, pb, st_mode, mkv->mode) < 0)
859 return AVERROR(EINVAL);
866 display_width_div = 2;
872 display_height_div = 2;
877 if ((tag = av_dict_get(st->metadata, "alpha_mode", NULL, 0)) ||
878 (tag = av_dict_get( s->metadata, "alpha_mode", NULL, 0)) ||
879 (codec->pix_fmt == AV_PIX_FMT_YUVA420P)) {
880 put_ebml_uint(pb, MATROSKA_ID_VIDEOALPHAMODE, 1);
883 if (st->sample_aspect_ratio.num) {
884 int64_t d_width = av_rescale(codec->width, st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
885 if (d_width > INT_MAX) {
886 av_log(s, AV_LOG_ERROR, "Overflow in display width\n");
887 return AVERROR(EINVAL);
889 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , d_width / display_width_div);
890 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, codec->height / display_height_div);
891 } else if (display_width_div != 1 || display_height_div != 1) {
892 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , codec->width / display_width_div);
893 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, codec->height / display_height_div);
896 if (codec->codec_id == AV_CODEC_ID_RAWVIDEO) {
897 uint32_t color_space = av_le2ne32(codec->codec_tag);
898 put_ebml_binary(pb, MATROSKA_ID_VIDEOCOLORSPACE, &color_space, sizeof(color_space));
900 end_ebml_master(pb, subinfo);
903 case AVMEDIA_TYPE_AUDIO:
904 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_AUDIO);
907 // no mkv-specific ID, use ACM mode
908 put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");
910 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);
911 put_ebml_uint (pb, MATROSKA_ID_AUDIOCHANNELS , codec->channels);
912 put_ebml_float (pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, sample_rate);
913 if (output_sample_rate)
914 put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
916 put_ebml_uint(pb, MATROSKA_ID_AUDIOBITDEPTH, bit_depth);
917 end_ebml_master(pb, subinfo);
920 case AVMEDIA_TYPE_SUBTITLE:
922 av_log(s, AV_LOG_ERROR, "Subtitle codec %d is not supported.\n", codec->codec_id);
923 return AVERROR(ENOSYS);
926 if (mkv->mode != MODE_WEBM || codec->codec_id != AV_CODEC_ID_WEBVTT)
927 native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
929 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, native_id);
932 av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.\n");
933 return AVERROR(EINVAL);
936 if (mkv->mode != MODE_WEBM || codec->codec_id != AV_CODEC_ID_WEBVTT) {
937 ret = mkv_write_codecprivate(s, pb, codec, native_id, qt_id);
942 end_ebml_master(pb, track);
947 static int mkv_write_tracks(AVFormatContext *s)
949 MatroskaMuxContext *mkv = s->priv_data;
950 AVIOContext *pb = s->pb;
952 int i, ret, default_stream_exists = 0;
954 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TRACKS, avio_tell(pb));
958 tracks = start_ebml_master(pb, MATROSKA_ID_TRACKS, 0);
959 for (i = 0; i < s->nb_streams; i++) {
960 AVStream *st = s->streams[i];
961 default_stream_exists |= st->disposition & AV_DISPOSITION_DEFAULT;
963 for (i = 0; i < s->nb_streams; i++) {
964 ret = mkv_write_track(s, mkv, i, pb, default_stream_exists);
968 end_ebml_master(pb, tracks);
972 static int mkv_write_chapters(AVFormatContext *s)
974 MatroskaMuxContext *mkv = s->priv_data;
975 AVIOContext *pb = s->pb;
976 ebml_master chapters, editionentry;
977 AVRational scale = {1, 1E9};
980 if (!s->nb_chapters || mkv->wrote_chapters)
983 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CHAPTERS, avio_tell(pb));
984 if (ret < 0) return ret;
986 chapters = start_ebml_master(pb, MATROSKA_ID_CHAPTERS , 0);
987 editionentry = start_ebml_master(pb, MATROSKA_ID_EDITIONENTRY, 0);
988 put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGDEFAULT, 1);
989 put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGHIDDEN , 0);
990 for (i = 0; i < s->nb_chapters; i++) {
991 ebml_master chapteratom, chapterdisplay;
992 AVChapter *c = s->chapters[i];
993 AVDictionaryEntry *t = NULL;
995 chapteratom = start_ebml_master(pb, MATROSKA_ID_CHAPTERATOM, 0);
996 put_ebml_uint(pb, MATROSKA_ID_CHAPTERUID, c->id + mkv->chapter_id_offset);
997 put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMESTART,
998 av_rescale_q(c->start, c->time_base, scale));
999 put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMEEND,
1000 av_rescale_q(c->end, c->time_base, scale));
1001 put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGHIDDEN , 0);
1002 put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGENABLED, 1);
1003 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
1004 chapterdisplay = start_ebml_master(pb, MATROSKA_ID_CHAPTERDISPLAY, 0);
1005 put_ebml_string(pb, MATROSKA_ID_CHAPSTRING, t->value);
1006 put_ebml_string(pb, MATROSKA_ID_CHAPLANG , "und");
1007 end_ebml_master(pb, chapterdisplay);
1009 end_ebml_master(pb, chapteratom);
1011 end_ebml_master(pb, editionentry);
1012 end_ebml_master(pb, chapters);
1014 mkv->wrote_chapters = 1;
1018 static void mkv_write_simpletag(AVIOContext *pb, AVDictionaryEntry *t)
1020 uint8_t *key = av_strdup(t->key);
1022 const uint8_t *lang = NULL;
1025 if ((p = strrchr(p, '-')) &&
1026 (lang = av_convert_lang_to(p + 1, AV_LANG_ISO639_2_BIBL)))
1033 else if (*p >= 'a' && *p <= 'z')
1038 tag = start_ebml_master(pb, MATROSKA_ID_SIMPLETAG, 0);
1039 put_ebml_string(pb, MATROSKA_ID_TAGNAME, key);
1041 put_ebml_string(pb, MATROSKA_ID_TAGLANG, lang);
1042 put_ebml_string(pb, MATROSKA_ID_TAGSTRING, t->value);
1043 end_ebml_master(pb, tag);
1048 static int mkv_write_tag(AVFormatContext *s, AVDictionary *m, unsigned int elementid,
1049 unsigned int uid, ebml_master *tags)
1051 MatroskaMuxContext *mkv = s->priv_data;
1052 ebml_master tag, targets;
1053 AVDictionaryEntry *t = NULL;
1057 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TAGS, avio_tell(s->pb));
1058 if (ret < 0) return ret;
1060 *tags = start_ebml_master(s->pb, MATROSKA_ID_TAGS, 0);
1063 tag = start_ebml_master(s->pb, MATROSKA_ID_TAG, 0);
1064 targets = start_ebml_master(s->pb, MATROSKA_ID_TAGTARGETS, 0);
1066 put_ebml_uint(s->pb, elementid, uid);
1067 end_ebml_master(s->pb, targets);
1069 while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX)))
1070 if (av_strcasecmp(t->key, "title") &&
1071 av_strcasecmp(t->key, "stereo_mode") &&
1072 av_strcasecmp(t->key, "encoding_tool"))
1073 mkv_write_simpletag(s->pb, t);
1075 end_ebml_master(s->pb, tag);
1079 static int mkv_check_tag(AVDictionary *m)
1081 AVDictionaryEntry *t = NULL;
1083 while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX)))
1084 if (av_strcasecmp(t->key, "title") && av_strcasecmp(t->key, "stereo_mode"))
1090 static int mkv_write_tags(AVFormatContext *s)
1092 MatroskaMuxContext *mkv = s->priv_data;
1093 ebml_master tags = {0};
1096 ff_metadata_conv_ctx(s, ff_mkv_metadata_conv, NULL);
1098 if (mkv_check_tag(s->metadata)) {
1099 ret = mkv_write_tag(s, s->metadata, 0, 0, &tags);
1100 if (ret < 0) return ret;
1103 for (i = 0; i < s->nb_streams; i++) {
1104 AVStream *st = s->streams[i];
1106 if (!mkv_check_tag(st->metadata))
1109 ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &tags);
1110 if (ret < 0) return ret;
1113 for (i = 0; i < s->nb_chapters; i++) {
1114 AVChapter *ch = s->chapters[i];
1116 if (!mkv_check_tag(ch->metadata))
1119 ret = mkv_write_tag(s, ch->metadata, MATROSKA_ID_TAGTARGETS_CHAPTERUID, ch->id + mkv->chapter_id_offset, &tags);
1120 if (ret < 0) return ret;
1124 end_ebml_master(s->pb, tags);
1128 static int mkv_write_attachments(AVFormatContext *s)
1130 MatroskaMuxContext *mkv = s->priv_data;
1131 AVIOContext *pb = s->pb;
1132 ebml_master attachments;
1136 if (!mkv->have_attachments)
1139 av_lfg_init(&c, av_get_random_seed());
1141 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_ATTACHMENTS, avio_tell(pb));
1142 if (ret < 0) return ret;
1144 attachments = start_ebml_master(pb, MATROSKA_ID_ATTACHMENTS, 0);
1146 for (i = 0; i < s->nb_streams; i++) {
1147 AVStream *st = s->streams[i];
1148 ebml_master attached_file;
1149 AVDictionaryEntry *t;
1150 const char *mimetype = NULL;
1153 if (st->codec->codec_type != AVMEDIA_TYPE_ATTACHMENT)
1156 attached_file = start_ebml_master(pb, MATROSKA_ID_ATTACHEDFILE, 0);
1158 if (t = av_dict_get(st->metadata, "title", NULL, 0))
1159 put_ebml_string(pb, MATROSKA_ID_FILEDESC, t->value);
1160 if (!(t = av_dict_get(st->metadata, "filename", NULL, 0))) {
1161 av_log(s, AV_LOG_ERROR, "Attachment stream %d has no filename tag.\n", i);
1162 return AVERROR(EINVAL);
1164 put_ebml_string(pb, MATROSKA_ID_FILENAME, t->value);
1165 if (t = av_dict_get(st->metadata, "mimetype", NULL, 0))
1166 mimetype = t->value;
1167 else if (st->codec->codec_id != AV_CODEC_ID_NONE ) {
1169 for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
1170 if (ff_mkv_mime_tags[i].id == st->codec->codec_id) {
1171 mimetype = ff_mkv_mime_tags[i].str;
1176 av_log(s, AV_LOG_ERROR, "Attachment stream %d has no mimetype tag and "
1177 "it cannot be deduced from the codec id.\n", i);
1178 return AVERROR(EINVAL);
1181 if (s->flags & AVFMT_FLAG_BITEXACT) {
1182 struct AVSHA *sha = av_sha_alloc();
1185 return AVERROR(ENOMEM);
1186 av_sha_init(sha, 160);
1187 av_sha_update(sha, st->codec->extradata, st->codec->extradata_size);
1188 av_sha_final(sha, digest);
1190 fileuid = AV_RL64(digest);
1192 fileuid = av_lfg_get(&c);
1194 av_log(s, AV_LOG_VERBOSE, "Using %.16"PRIx64" for attachment %d\n",
1197 put_ebml_string(pb, MATROSKA_ID_FILEMIMETYPE, mimetype);
1198 put_ebml_binary(pb, MATROSKA_ID_FILEDATA, st->codec->extradata, st->codec->extradata_size);
1199 put_ebml_uint(pb, MATROSKA_ID_FILEUID, fileuid);
1200 end_ebml_master(pb, attached_file);
1202 end_ebml_master(pb, attachments);
1207 static int mkv_write_header(AVFormatContext *s)
1209 MatroskaMuxContext *mkv = s->priv_data;
1210 AVIOContext *pb = s->pb;
1211 ebml_master ebml_header, segment_info;
1212 AVDictionaryEntry *tag;
1213 int ret, i, version = 2;
1215 if (!strcmp(s->oformat->name, "webm"))
1216 mkv->mode = MODE_WEBM;
1218 mkv->mode = MODE_MATROSKAv2;
1220 if (s->avoid_negative_ts < 0)
1221 s->avoid_negative_ts = 1;
1223 if (mkv->mode != MODE_WEBM ||
1224 av_dict_get(s->metadata, "stereo_mode", NULL, 0) ||
1225 av_dict_get(s->metadata, "alpha_mode", NULL, 0))
1228 for (i = 0; i < s->nb_streams; i++) {
1229 if (s->streams[i]->codec->codec_id == AV_CODEC_ID_ATRAC3 ||
1230 s->streams[i]->codec->codec_id == AV_CODEC_ID_COOK ||
1231 s->streams[i]->codec->codec_id == AV_CODEC_ID_RA_288 ||
1232 s->streams[i]->codec->codec_id == AV_CODEC_ID_SIPR ||
1233 s->streams[i]->codec->codec_id == AV_CODEC_ID_RV10 ||
1234 s->streams[i]->codec->codec_id == AV_CODEC_ID_RV20) {
1235 av_log(s, AV_LOG_ERROR,
1236 "The Matroska muxer does not yet support muxing %s\n",
1237 avcodec_get_name(s->streams[i]->codec->codec_id));
1238 return AVERROR_PATCHWELCOME;
1240 if (s->streams[i]->codec->codec_id == AV_CODEC_ID_OPUS ||
1241 av_dict_get(s->streams[i]->metadata, "stereo_mode", NULL, 0) ||
1242 av_dict_get(s->streams[i]->metadata, "alpha_mode", NULL, 0))
1246 mkv->tracks = av_mallocz_array(s->nb_streams, sizeof(*mkv->tracks));
1248 return AVERROR(ENOMEM);
1250 ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
1251 put_ebml_uint (pb, EBML_ID_EBMLVERSION , 1);
1252 put_ebml_uint (pb, EBML_ID_EBMLREADVERSION , 1);
1253 put_ebml_uint (pb, EBML_ID_EBMLMAXIDLENGTH , 4);
1254 put_ebml_uint (pb, EBML_ID_EBMLMAXSIZELENGTH , 8);
1255 put_ebml_string (pb, EBML_ID_DOCTYPE , s->oformat->name);
1256 put_ebml_uint (pb, EBML_ID_DOCTYPEVERSION , version);
1257 put_ebml_uint (pb, EBML_ID_DOCTYPEREADVERSION , 2);
1258 end_ebml_master(pb, ebml_header);
1260 mkv->segment = start_ebml_master(pb, MATROSKA_ID_SEGMENT, 0);
1261 mkv->segment_offset = avio_tell(pb);
1263 // we write 2 seek heads - one at the end of the file to point to each
1264 // cluster, and one at the beginning to point to all other level one
1265 // elements (including the seek head at the end of the file), which
1266 // isn't more than 10 elements if we only write one of each other
1267 // currently defined level 1 element
1268 mkv->main_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 10);
1269 if (!mkv->main_seekhead)
1270 return AVERROR(ENOMEM);
1272 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_INFO, avio_tell(pb));
1273 if (ret < 0) return ret;
1275 segment_info = start_ebml_master(pb, MATROSKA_ID_INFO, 0);
1276 put_ebml_uint(pb, MATROSKA_ID_TIMECODESCALE, 1000000);
1277 if ((tag = av_dict_get(s->metadata, "title", NULL, 0)))
1278 put_ebml_string(pb, MATROSKA_ID_TITLE, tag->value);
1279 if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
1280 uint32_t segment_uid[4];
1283 av_lfg_init(&lfg, av_get_random_seed());
1285 for (i = 0; i < 4; i++)
1286 segment_uid[i] = av_lfg_get(&lfg);
1288 put_ebml_string(pb, MATROSKA_ID_MUXINGAPP, LIBAVFORMAT_IDENT);
1289 if ((tag = av_dict_get(s->metadata, "encoding_tool", NULL, 0)))
1290 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, tag->value);
1292 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, LIBAVFORMAT_IDENT);
1293 put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
1295 const char *ident = "Lavf";
1296 put_ebml_string(pb, MATROSKA_ID_MUXINGAPP , ident);
1297 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, ident);
1300 if (tag = av_dict_get(s->metadata, "creation_time", NULL, 0)) {
1301 // Adjust time so it's relative to 2001-01-01 and convert to nanoseconds.
1302 int64_t date_utc = (ff_iso8601_to_unix_time(tag->value) - 978307200) * 1000000000;
1303 uint8_t date_utc_buf[8];
1304 AV_WB64(date_utc_buf, date_utc);
1305 put_ebml_binary(pb, MATROSKA_ID_DATEUTC, date_utc_buf, 8);
1308 // reserve space for the duration
1310 mkv->duration_offset = avio_tell(pb);
1311 put_ebml_void(pb, 11); // assumes double-precision float to be written
1312 end_ebml_master(pb, segment_info);
1314 ret = mkv_write_tracks(s);
1318 for (i = 0; i < s->nb_chapters; i++)
1319 mkv->chapter_id_offset = FFMAX(mkv->chapter_id_offset, 1LL - s->chapters[i]->id);
1321 if (mkv->mode != MODE_WEBM) {
1322 ret = mkv_write_chapters(s);
1326 ret = mkv_write_tags(s);
1330 ret = mkv_write_attachments(s);
1335 if (!s->pb->seekable)
1336 mkv_write_seekhead(pb, mkv->main_seekhead);
1338 mkv->cues = mkv_start_cues(mkv->segment_offset);
1339 if (mkv->cues == NULL)
1340 return AVERROR(ENOMEM);
1342 if (pb->seekable && mkv->reserve_cues_space) {
1343 mkv->cues_pos = avio_tell(pb);
1344 put_ebml_void(pb, mkv->reserve_cues_space);
1347 av_init_packet(&mkv->cur_audio_pkt);
1348 mkv->cur_audio_pkt.size = 0;
1349 mkv->cluster_pos = -1;
1353 // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1354 // after 4k and on a keyframe
1356 if (mkv->cluster_time_limit < 0)
1357 mkv->cluster_time_limit = 5000;
1358 if (mkv->cluster_size_limit < 0)
1359 mkv->cluster_size_limit = 5 * 1024 * 1024;
1361 if (mkv->cluster_time_limit < 0)
1362 mkv->cluster_time_limit = 1000;
1363 if (mkv->cluster_size_limit < 0)
1364 mkv->cluster_size_limit = 32 * 1024;
1370 static int mkv_blockgroup_size(int pkt_size)
1372 int size = pkt_size + 4;
1373 size += ebml_num_size(size);
1374 size += 2; // EBML ID for block and block duration
1375 size += 8; // max size of block duration
1376 size += ebml_num_size(size);
1377 size += 1; // blockgroup EBML ID
1381 static int ass_get_duration(const uint8_t *p)
1383 int sh, sm, ss, sc, eh, em, es, ec;
1384 uint64_t start, end;
1386 if (sscanf(p, "%*[^,],%d:%d:%d%*c%d,%d:%d:%d%*c%d",
1387 &sh, &sm, &ss, &sc, &eh, &em, &es, &ec) != 8)
1389 start = 3600000LL * sh + 60000LL * sm + 1000LL * ss + 10LL * sc;
1390 end = 3600000LL * eh + 60000LL * em + 1000LL * es + 10LL * ec;
1395 /* Writes the contents of pkt to a block, using the data starting at *datap.
1396 * If pkt corresponds to more than one block, this writes the contents of the first block
1397 * (starting from *datap) and updates *datap so it points to the beginning of the data
1398 * corresponding to the next block.
1400 static int mkv_write_ass_block(AVFormatContext *s, AVIOContext *pb,
1401 AVPacket *pkt, uint8_t **datap)
1403 MatroskaMuxContext *mkv = s->priv_data;
1404 int i, layer = 0, size, line_size, data_size = pkt->size - (*datap - pkt->data);
1405 uint8_t *start, *end, *data = *datap;
1406 ebml_master blockgroup;
1409 int duration = ass_get_duration(data);
1410 end = memchr(data, '\n', data_size);
1411 size = line_size = end ? end - data + 1 : data_size;
1412 size -= end ? (end[-1] == '\r') + 1 : 0;
1414 for (i = 0; i < 3; i++, start++)
1415 if (!(start = memchr(start, ',', size - (start - data))))
1417 size -= start - data;
1418 sscanf(data, "Dialogue: %d,", &layer);
1419 i = snprintf(buffer, sizeof(buffer), "%" PRId64 ",%d,",
1420 s->streams[pkt->stream_index]->nb_frames, layer);
1421 size = FFMIN(i + size, sizeof(buffer));
1422 memcpy(buffer + i, start, size - i);
1424 av_log(s, AV_LOG_DEBUG,
1425 "Writing block at offset %" PRIu64 ", size %d, "
1426 "pts %" PRId64 ", duration %d\n",
1427 avio_tell(pb), size, pkt->pts, duration);
1428 blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
1429 mkv_blockgroup_size(size));
1430 put_ebml_id(pb, MATROSKA_ID_BLOCK);
1431 put_ebml_num(pb, size + 4, 0);
1432 // this assumes stream_index is less than 126
1433 avio_w8(pb, 0x80 | (pkt->stream_index + 1));
1434 avio_wb16(pb, pkt->pts - mkv->cluster_pts);
1436 avio_write(pb, buffer, size);
1437 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
1438 end_ebml_master(pb, blockgroup);
1440 *datap += line_size;
1446 static int mkv_strip_wavpack(const uint8_t *src, uint8_t **pdst, int *size)
1453 dst = av_malloc(srclen);
1455 return AVERROR(ENOMEM);
1457 while (srclen >= WV_HEADER_SIZE) {
1460 ret = ff_wv_parse_header(&header, src);
1463 src += WV_HEADER_SIZE;
1464 srclen -= WV_HEADER_SIZE;
1466 if (srclen < header.blocksize) {
1467 ret = AVERROR_INVALIDDATA;
1471 if (header.initial) {
1472 AV_WL32(dst + offset, header.samples);
1475 AV_WL32(dst + offset, header.flags);
1476 AV_WL32(dst + offset + 4, header.crc);
1479 if (!(header.initial && header.final)) {
1480 AV_WL32(dst + offset, header.blocksize);
1484 memcpy(dst + offset, src, header.blocksize);
1485 src += header.blocksize;
1486 srclen -= header.blocksize;
1487 offset += header.blocksize;
1499 static void mkv_write_block(AVFormatContext *s, AVIOContext *pb,
1500 unsigned int blockid, AVPacket *pkt, int flags)
1502 MatroskaMuxContext *mkv = s->priv_data;
1503 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1504 uint8_t *data = NULL, *side_data = NULL;
1505 int offset = 0, size = pkt->size, side_data_size = 0;
1506 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1507 uint64_t additional_id = 0;
1508 int64_t discard_padding = 0;
1509 ebml_master block_group, block_additions, block_more;
1511 av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
1512 "pts %" PRId64 ", dts %" PRId64 ", duration %d, flags %d\n",
1513 avio_tell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration, flags);
1514 if (codec->codec_id == AV_CODEC_ID_H264 && codec->extradata_size > 0 &&
1515 (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
1516 ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
1517 else if (codec->codec_id == AV_CODEC_ID_HEVC && codec->extradata_size > 6 &&
1518 (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
1519 /* extradata is Annex B, assume the bitstream is too and convert it */
1520 ff_hevc_annexb2mp4_buf(pkt->data, &data, &size, 0, NULL);
1521 else if (codec->codec_id == AV_CODEC_ID_WAVPACK) {
1522 int ret = mkv_strip_wavpack(pkt->data, &data, &size);
1524 av_log(s, AV_LOG_ERROR, "Error stripping a WavPack packet.\n");
1530 if (codec->codec_id == AV_CODEC_ID_PRORES) {
1531 /* Matroska specification requires to remove the first QuickTime atom
1537 side_data = av_packet_get_side_data(pkt,
1538 AV_PKT_DATA_SKIP_SAMPLES,
1541 if (side_data && side_data_size >= 10) {
1542 discard_padding = av_rescale_q(AV_RL32(side_data + 4),
1543 (AVRational){1, codec->sample_rate},
1544 (AVRational){1, 1000000000});
1547 side_data = av_packet_get_side_data(pkt,
1548 AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,
1551 additional_id = AV_RB64(side_data);
1553 side_data_size -= 8;
1556 if ((side_data_size && additional_id == 1) || discard_padding) {
1557 block_group = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, 0);
1558 blockid = MATROSKA_ID_BLOCK;
1561 put_ebml_id(pb, blockid);
1562 put_ebml_num(pb, size + 4, 0);
1563 // this assumes stream_index is less than 126
1564 avio_w8(pb, 0x80 | (mkv->is_dash ? mkv->dash_track_number : (pkt->stream_index + 1)));
1565 avio_wb16(pb, ts - mkv->cluster_pts);
1567 avio_write(pb, data + offset, size);
1568 if (data != pkt->data)
1571 if (discard_padding) {
1572 put_ebml_sint(pb, MATROSKA_ID_DISCARDPADDING, discard_padding);
1575 if (side_data_size && additional_id == 1) {
1576 block_additions = start_ebml_master(pb, MATROSKA_ID_BLOCKADDITIONS, 0);
1577 block_more = start_ebml_master(pb, MATROSKA_ID_BLOCKMORE, 0);
1578 put_ebml_uint(pb, MATROSKA_ID_BLOCKADDID, 1);
1579 put_ebml_id(pb, MATROSKA_ID_BLOCKADDITIONAL);
1580 put_ebml_num(pb, side_data_size, 0);
1581 avio_write(pb, side_data, side_data_size);
1582 end_ebml_master(pb, block_more);
1583 end_ebml_master(pb, block_additions);
1585 if ((side_data_size && additional_id == 1) || discard_padding) {
1586 end_ebml_master(pb, block_group);
1590 static int srt_get_duration(uint8_t **buf)
1592 int i, duration = 0;
1594 for (i = 0; i < 2 && !duration; i++) {
1595 int s_hour, s_min, s_sec, s_hsec, e_hour, e_min, e_sec, e_hsec;
1596 if (sscanf(*buf, "%d:%2d:%2d%*1[,.]%3d --> %d:%2d:%2d%*1[,.]%3d",
1597 &s_hour, &s_min, &s_sec, &s_hsec,
1598 &e_hour, &e_min, &e_sec, &e_hsec) == 8) {
1599 s_min += 60 * s_hour;
1600 e_min += 60 * e_hour;
1601 s_sec += 60 * s_min;
1603 e_sec += 60 * e_min;
1604 s_hsec += 1000 * s_sec;
1605 e_hsec += 1000 * e_sec;
1607 duration = e_hsec - s_hsec;
1609 *buf += ff_subtitles_next_line(*buf);
1614 static int mkv_write_srt_blocks(AVFormatContext *s, AVIOContext *pb,
1617 ebml_master blockgroup;
1618 AVPacket pkt2 = *pkt;
1619 int64_t duration = srt_get_duration(&pkt2.data);
1620 pkt2.size -= pkt2.data - pkt->data;
1622 blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
1623 mkv_blockgroup_size(pkt2.size));
1624 mkv_write_block(s, pb, MATROSKA_ID_BLOCK, &pkt2, 0);
1625 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
1626 end_ebml_master(pb, blockgroup);
1631 static int mkv_write_vtt_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
1633 MatroskaMuxContext *mkv = s->priv_data;
1634 ebml_master blockgroup;
1635 int id_size, settings_size, size;
1636 uint8_t *id, *settings;
1637 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1638 const int flags = 0;
1641 id = av_packet_get_side_data(pkt, AV_PKT_DATA_WEBVTT_IDENTIFIER,
1645 settings = av_packet_get_side_data(pkt, AV_PKT_DATA_WEBVTT_SETTINGS,
1648 size = id_size + 1 + settings_size + 1 + pkt->size;
1650 av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
1651 "pts %" PRId64 ", dts %" PRId64 ", duration %d, flags %d\n",
1652 avio_tell(pb), size, pkt->pts, pkt->dts, pkt->duration, flags);
1654 blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(size));
1656 put_ebml_id(pb, MATROSKA_ID_BLOCK);
1657 put_ebml_num(pb, size + 4, 0);
1658 avio_w8(pb, 0x80 | (pkt->stream_index + 1)); // this assumes stream_index is less than 126
1659 avio_wb16(pb, ts - mkv->cluster_pts);
1661 avio_printf(pb, "%.*s\n%.*s\n%.*s", id_size, id, settings_size, settings, pkt->size, pkt->data);
1663 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, pkt->duration);
1664 end_ebml_master(pb, blockgroup);
1666 return pkt->duration;
1669 static void mkv_flush_dynbuf(AVFormatContext *s)
1671 MatroskaMuxContext *mkv = s->priv_data;
1678 bufsize = avio_close_dyn_buf(mkv->dyn_bc, &dyn_buf);
1679 avio_write(s->pb, dyn_buf, bufsize);
1684 static void mkv_start_new_cluster(AVFormatContext *s, AVPacket *pkt)
1686 MatroskaMuxContext *mkv = s->priv_data;
1689 if (s->pb->seekable) {
1695 av_log(s, AV_LOG_DEBUG,
1696 "Starting new cluster at offset %" PRIu64 " bytes, "
1697 "pts %" PRIu64 "dts %" PRIu64 "\n",
1698 avio_tell(pb), pkt->pts, pkt->dts);
1699 end_ebml_master(pb, mkv->cluster);
1700 mkv->cluster_pos = -1;
1702 mkv_flush_dynbuf(s);
1706 static int mkv_write_packet_internal(AVFormatContext *s, AVPacket *pkt, int add_cue)
1708 MatroskaMuxContext *mkv = s->priv_data;
1709 AVIOContext *pb = s->pb;
1710 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1711 int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1712 int duration = pkt->duration;
1714 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1715 int64_t relative_packet_pos;
1716 uint8_t *data_offset = pkt->data;
1717 int dash_tracknum = mkv->is_dash ? mkv->dash_track_number : pkt->stream_index + 1;
1719 if (ts == AV_NOPTS_VALUE) {
1720 av_log(s, AV_LOG_ERROR, "Can't write packet with unknown timestamp\n");
1721 return AVERROR(EINVAL);
1723 ts += mkv->tracks[pkt->stream_index].ts_offset;
1725 if (mkv->cluster_pos != -1) {
1726 int64_t cluster_time = ts - mkv->cluster_pts + mkv->tracks[pkt->stream_index].ts_offset;
1727 if ((int16_t)cluster_time != cluster_time) {
1728 av_log(s, AV_LOG_WARNING, "Starting new cluster due to timestamp\n");
1729 mkv_start_new_cluster(s, pkt);
1733 if (!s->pb->seekable) {
1735 if ((ret = avio_open_dyn_buf(&mkv->dyn_bc)) < 0) {
1736 av_log(s, AV_LOG_ERROR, "Failed to open dynamic buffer\n");
1743 if (mkv->cluster_pos == -1) {
1744 mkv->cluster_pos = avio_tell(s->pb);
1745 mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER, 0);
1746 put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, FFMAX(0, ts));
1747 mkv->cluster_pts = FFMAX(0, ts);
1750 relative_packet_pos = avio_tell(s->pb) - mkv->cluster.pos;
1752 if (codec->codec_type != AVMEDIA_TYPE_SUBTITLE) {
1753 mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
1754 if (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe || add_cue) {
1755 ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, dash_tracknum, ts, mkv->cluster_pos, relative_packet_pos, -1);
1756 if (ret < 0) return ret;
1759 } else if (codec->codec_id == AV_CODEC_ID_SSA) {
1760 while (data_offset < pkt->data + pkt->size) {
1761 duration = mkv_write_ass_block(s, pb, pkt, &data_offset);
1762 ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, dash_tracknum, ts, mkv->cluster_pos, relative_packet_pos, duration);
1763 if (ret < 0) return ret;
1764 relative_packet_pos = avio_tell(s->pb) - mkv->cluster.pos;
1768 if (codec->codec_id == AV_CODEC_ID_SRT) {
1769 duration = mkv_write_srt_blocks(s, pb, pkt);
1770 } else if (codec->codec_id == AV_CODEC_ID_WEBVTT) {
1771 duration = mkv_write_vtt_blocks(s, pb, pkt);
1773 ebml_master blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
1774 mkv_blockgroup_size(pkt->size));
1775 /* For backward compatibility, prefer convergence_duration. */
1776 if (pkt->convergence_duration > 0) {
1777 duration = pkt->convergence_duration;
1779 mkv_write_block(s, pb, MATROSKA_ID_BLOCK, pkt, 0);
1780 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
1781 end_ebml_master(pb, blockgroup);
1784 ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, dash_tracknum, ts,
1785 mkv->cluster_pos, relative_packet_pos, duration);
1790 mkv->duration = FFMAX(mkv->duration, ts + duration);
1794 static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
1796 MatroskaMuxContext *mkv = s->priv_data;
1797 int codec_type = s->streams[pkt->stream_index]->codec->codec_type;
1798 int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1800 int64_t cluster_time;
1802 int start_new_cluster;
1804 if (mkv->tracks[pkt->stream_index].write_dts)
1805 cluster_time = pkt->dts - mkv->cluster_pts;
1807 cluster_time = pkt->pts - mkv->cluster_pts;
1808 cluster_time += mkv->tracks[pkt->stream_index].ts_offset;
1810 // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1811 // after 4k and on a keyframe
1812 if (s->pb->seekable) {
1813 cluster_size = avio_tell(s->pb) - mkv->cluster_pos;
1815 cluster_size = avio_tell(mkv->dyn_bc);
1818 if (mkv->is_dash && codec_type == AVMEDIA_TYPE_VIDEO) {
1819 // WebM DASH specification states that the first block of every cluster
1820 // has to be a key frame. So for DASH video, we only create a cluster
1821 // on seeing key frames.
1822 start_new_cluster = keyframe;
1823 } else if (mkv->is_dash && codec_type == AVMEDIA_TYPE_AUDIO &&
1824 cluster_time > mkv->cluster_time_limit) {
1825 // For DASH audio, we create a Cluster based on cluster_time_limit
1826 start_new_cluster = 1;
1827 } else if (!mkv->is_dash &&
1828 (cluster_size > mkv->cluster_size_limit ||
1829 cluster_time > mkv->cluster_time_limit ||
1830 (codec_type == AVMEDIA_TYPE_VIDEO && keyframe &&
1831 cluster_size > 4 * 1024))) {
1832 start_new_cluster = 1;
1834 start_new_cluster = 0;
1837 if (mkv->cluster_pos != -1 && start_new_cluster) {
1838 mkv_start_new_cluster(s, pkt);
1841 // check if we have an audio packet cached
1842 if (mkv->cur_audio_pkt.size > 0) {
1843 // for DASH audio, a CuePoint has to be added when there is a new cluster.
1844 ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt,
1845 mkv->is_dash ? start_new_cluster : 0);
1846 av_free_packet(&mkv->cur_audio_pkt);
1848 av_log(s, AV_LOG_ERROR,
1849 "Could not write cached audio packet ret:%d\n", ret);
1854 // buffer an audio packet to ensure the packet containing the video
1855 // keyframe's timecode is contained in the same cluster for WebM
1856 if (codec_type == AVMEDIA_TYPE_AUDIO) {
1857 mkv->cur_audio_pkt = *pkt;
1859 mkv->cur_audio_pkt.buf = av_buffer_ref(pkt->buf);
1860 ret = mkv->cur_audio_pkt.buf ? 0 : AVERROR(ENOMEM);
1862 ret = av_dup_packet(&mkv->cur_audio_pkt);
1863 if (mkv->cur_audio_pkt.side_data_elems > 0) {
1864 ret = av_copy_packet_side_data(&mkv->cur_audio_pkt, &mkv->cur_audio_pkt);
1867 ret = mkv_write_packet_internal(s, pkt, 0);
1871 static int mkv_write_flush_packet(AVFormatContext *s, AVPacket *pkt)
1873 MatroskaMuxContext *mkv = s->priv_data;
1875 if (s->pb->seekable)
1880 if (mkv->cluster_pos != -1) {
1881 av_log(s, AV_LOG_DEBUG,
1882 "Flushing cluster at offset %" PRIu64 " bytes\n",
1884 end_ebml_master(pb, mkv->cluster);
1885 mkv->cluster_pos = -1;
1887 mkv_flush_dynbuf(s);
1892 return mkv_write_packet(s, pkt);
1895 static int mkv_write_trailer(AVFormatContext *s)
1897 MatroskaMuxContext *mkv = s->priv_data;
1898 AVIOContext *pb = s->pb;
1899 int64_t currentpos, cuespos;
1902 // check if we have an audio packet cached
1903 if (mkv->cur_audio_pkt.size > 0) {
1904 ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt, 0);
1905 av_free_packet(&mkv->cur_audio_pkt);
1907 av_log(s, AV_LOG_ERROR,
1908 "Could not write cached audio packet ret:%d\n", ret);
1914 end_ebml_master(mkv->dyn_bc, mkv->cluster);
1915 mkv_flush_dynbuf(s);
1916 } else if (mkv->cluster_pos != -1) {
1917 end_ebml_master(pb, mkv->cluster);
1920 if (mkv->mode != MODE_WEBM) {
1921 ret = mkv_write_chapters(s);
1927 if (mkv->cues->num_entries) {
1928 if (mkv->reserve_cues_space) {
1931 currentpos = avio_tell(pb);
1932 avio_seek(pb, mkv->cues_pos, SEEK_SET);
1934 cuespos = mkv_write_cues(s, mkv->cues, mkv->tracks, s->nb_streams);
1935 cues_end = avio_tell(pb);
1936 if (cues_end > cuespos + mkv->reserve_cues_space) {
1937 av_log(s, AV_LOG_ERROR,
1938 "Insufficient space reserved for cues: %d "
1939 "(needed: %" PRId64 ").\n",
1940 mkv->reserve_cues_space, cues_end - cuespos);
1941 return AVERROR(EINVAL);
1944 if (cues_end < cuespos + mkv->reserve_cues_space)
1945 put_ebml_void(pb, mkv->reserve_cues_space -
1946 (cues_end - cuespos));
1948 avio_seek(pb, currentpos, SEEK_SET);
1950 cuespos = mkv_write_cues(s, mkv->cues, mkv->tracks, s->nb_streams);
1953 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CUES,
1959 mkv_write_seekhead(pb, mkv->main_seekhead);
1961 // update the duration
1962 av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
1963 currentpos = avio_tell(pb);
1964 avio_seek(pb, mkv->duration_offset, SEEK_SET);
1965 put_ebml_float(pb, MATROSKA_ID_DURATION, mkv->duration);
1967 avio_seek(pb, currentpos, SEEK_SET);
1970 end_ebml_master(pb, mkv->segment);
1971 av_freep(&mkv->tracks);
1972 av_freep(&mkv->cues->entries);
1973 av_freep(&mkv->cues);
1978 static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
1981 for (i = 0; ff_mkv_codec_tags[i].id != AV_CODEC_ID_NONE; i++)
1982 if (ff_mkv_codec_tags[i].id == codec_id)
1985 if (std_compliance < FF_COMPLIANCE_NORMAL) {
1986 enum AVMediaType type = avcodec_get_type(codec_id);
1987 // mkv theoretically supports any video/audio through VFW/ACM
1988 if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)
1995 static const AVCodecTag additional_audio_tags[] = {
1996 { AV_CODEC_ID_ALAC, 0XFFFFFFFF },
1997 { AV_CODEC_ID_EAC3, 0XFFFFFFFF },
1998 { AV_CODEC_ID_MLP, 0xFFFFFFFF },
1999 { AV_CODEC_ID_OPUS, 0xFFFFFFFF },
2000 { AV_CODEC_ID_PCM_S16BE, 0xFFFFFFFF },
2001 { AV_CODEC_ID_PCM_S24BE, 0xFFFFFFFF },
2002 { AV_CODEC_ID_PCM_S32BE, 0xFFFFFFFF },
2003 { AV_CODEC_ID_QDM2, 0xFFFFFFFF },
2004 { AV_CODEC_ID_RA_144, 0xFFFFFFFF },
2005 { AV_CODEC_ID_RA_288, 0xFFFFFFFF },
2006 { AV_CODEC_ID_COOK, 0xFFFFFFFF },
2007 { AV_CODEC_ID_TRUEHD, 0xFFFFFFFF },
2008 { AV_CODEC_ID_NONE, 0xFFFFFFFF }
2011 static const AVCodecTag additional_video_tags[] = {
2012 { AV_CODEC_ID_RV10, 0xFFFFFFFF },
2013 { AV_CODEC_ID_RV20, 0xFFFFFFFF },
2014 { AV_CODEC_ID_RV30, 0xFFFFFFFF },
2015 { AV_CODEC_ID_RV40, 0xFFFFFFFF },
2016 { AV_CODEC_ID_VP9, 0xFFFFFFFF },
2017 { AV_CODEC_ID_NONE, 0xFFFFFFFF }
2020 #define OFFSET(x) offsetof(MatroskaMuxContext, x)
2021 #define FLAGS AV_OPT_FLAG_ENCODING_PARAM
2022 static const AVOption options[] = {
2023 { "reserve_index_space", "Reserve a given amount of space (in bytes) at the beginning of the file for the index (cues).", OFFSET(reserve_cues_space), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, FLAGS },
2024 { "cluster_size_limit", "Store at most the provided amount of bytes in a cluster. ", OFFSET(cluster_size_limit), AV_OPT_TYPE_INT , { .i64 = -1 }, -1, INT_MAX, FLAGS },
2025 { "cluster_time_limit", "Store at most the provided number of milliseconds in a cluster.", OFFSET(cluster_time_limit), AV_OPT_TYPE_INT64, { .i64 = -1 }, -1, INT64_MAX, FLAGS },
2026 { "dash", "Create a WebM file conforming to WebM DASH specification", OFFSET(is_dash), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
2027 { "dash_track_number", "Track number for the DASH stream", OFFSET(dash_track_number), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 127, FLAGS },
2031 #if CONFIG_MATROSKA_MUXER
2032 static const AVClass matroska_class = {
2033 .class_name = "matroska muxer",
2034 .item_name = av_default_item_name,
2036 .version = LIBAVUTIL_VERSION_INT,
2039 AVOutputFormat ff_matroska_muxer = {
2041 .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
2042 .mime_type = "video/x-matroska",
2043 .extensions = "mkv",
2044 .priv_data_size = sizeof(MatroskaMuxContext),
2045 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
2046 AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
2047 .video_codec = CONFIG_LIBX264_ENCODER ?
2048 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
2049 .write_header = mkv_write_header,
2050 .write_packet = mkv_write_flush_packet,
2051 .write_trailer = mkv_write_trailer,
2052 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
2053 AVFMT_TS_NONSTRICT | AVFMT_ALLOW_FLUSH,
2054 .codec_tag = (const AVCodecTag* const []){
2055 ff_codec_bmp_tags, ff_codec_wav_tags,
2056 additional_audio_tags, additional_video_tags, 0
2059 .subtitle_codec = AV_CODEC_ID_SSA,
2061 .subtitle_codec = AV_CODEC_ID_ASS,
2063 .query_codec = mkv_query_codec,
2064 .priv_class = &matroska_class,
2068 #if CONFIG_WEBM_MUXER
2069 static const AVClass webm_class = {
2070 .class_name = "webm muxer",
2071 .item_name = av_default_item_name,
2073 .version = LIBAVUTIL_VERSION_INT,
2076 AVOutputFormat ff_webm_muxer = {
2078 .long_name = NULL_IF_CONFIG_SMALL("WebM"),
2079 .mime_type = "video/webm",
2080 .extensions = "webm",
2081 .priv_data_size = sizeof(MatroskaMuxContext),
2082 .audio_codec = AV_CODEC_ID_VORBIS,
2083 .video_codec = AV_CODEC_ID_VP8,
2084 .subtitle_codec = AV_CODEC_ID_WEBVTT,
2085 .write_header = mkv_write_header,
2086 .write_packet = mkv_write_flush_packet,
2087 .write_trailer = mkv_write_trailer,
2088 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
2089 AVFMT_TS_NONSTRICT | AVFMT_ALLOW_FLUSH,
2090 .priv_class = &webm_class,
2094 #if CONFIG_MATROSKA_AUDIO_MUXER
2095 static const AVClass mka_class = {
2096 .class_name = "matroska audio muxer",
2097 .item_name = av_default_item_name,
2099 .version = LIBAVUTIL_VERSION_INT,
2101 AVOutputFormat ff_matroska_audio_muxer = {
2103 .long_name = NULL_IF_CONFIG_SMALL("Matroska Audio"),
2104 .mime_type = "audio/x-matroska",
2105 .extensions = "mka",
2106 .priv_data_size = sizeof(MatroskaMuxContext),
2107 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
2108 AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
2109 .video_codec = AV_CODEC_ID_NONE,
2110 .write_header = mkv_write_header,
2111 .write_packet = mkv_write_flush_packet,
2112 .write_trailer = mkv_write_trailer,
2113 .flags = AVFMT_GLOBALHEADER | AVFMT_TS_NONSTRICT |
2115 .codec_tag = (const AVCodecTag* const []){
2116 ff_codec_wav_tags, additional_audio_tags, 0
2118 .priv_class = &mka_class,