3 * Copyright (c) 2007 David Conrad
5 * This file is part of Libav.
7 * Libav 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 * Libav 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 Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27 #include "avlanguage.h"
33 #include "vorbiscomment.h"
36 #include "libavutil/avstring.h"
37 #include "libavutil/channel_layout.h"
38 #include "libavutil/dict.h"
39 #include "libavutil/intfloat.h"
40 #include "libavutil/intreadwrite.h"
41 #include "libavutil/lfg.h"
42 #include "libavutil/mathematics.h"
43 #include "libavutil/opt.h"
44 #include "libavutil/random_seed.h"
45 #include "libavutil/samplefmt.h"
46 #include "libavutil/stereo3d.h"
48 #include "libavcodec/xiph.h"
49 #include "libavcodec/mpeg4audio.h"
51 typedef struct ebml_master {
52 int64_t pos; ///< absolute offset in the file where the master's elements start
53 int sizebytes; ///< how many bytes were reserved for the size
56 typedef struct mkv_seekhead_entry {
57 unsigned int elementid;
61 typedef struct mkv_seekhead {
63 int64_t segment_offset; ///< the file offset to the beginning of the segment
64 int reserved_size; ///< -1 if appending to file
66 mkv_seekhead_entry *entries;
70 typedef struct mkv_cuepoint {
73 int64_t cluster_pos; ///< file offset of the cluster containing the block
76 typedef struct mkv_cues {
77 int64_t segment_offset;
78 mkv_cuepoint *entries;
82 typedef struct mkv_track {
87 #define MODE_MATROSKAv2 0x01
88 #define MODE_WEBM 0x02
90 typedef struct MatroskaMuxContext {
95 int64_t segment_offset;
97 int64_t cluster_pos; ///< file offset of the current cluster
99 int64_t duration_offset;
101 mkv_seekhead *main_seekhead;
105 AVPacket cur_audio_pkt;
107 int have_attachments;
109 int reserve_cues_space;
110 int cluster_size_limit;
112 int64_t cluster_time_limit;
114 } MatroskaMuxContext;
117 /** 2 bytes * 3 for EBML IDs, 3 1-byte EBML lengths, 8 bytes for 64 bit
118 * offset, 4 bytes for target EBML ID */
119 #define MAX_SEEKENTRY_SIZE 21
121 /** per-cuepoint-track - 3 1-byte EBML IDs, 3 1-byte EBML sizes, 2
123 #define MAX_CUETRACKPOS_SIZE 22
125 /** per-cuepoint - 2 1-byte EBML IDs, 2 1-byte EBML sizes, 8-byte uint max */
126 #define MAX_CUEPOINT_SIZE(num_tracks) 12 + MAX_CUETRACKPOS_SIZE * num_tracks
128 static int ebml_id_size(unsigned int id)
130 return (av_log2(id + 1) - 1) / 7 + 1;
133 static void put_ebml_id(AVIOContext *pb, unsigned int id)
135 int i = ebml_id_size(id);
137 avio_w8(pb, id >> (i * 8));
141 * Write an EBML size meaning "unknown size".
143 * @param bytes The number of bytes the size should occupy (maximum: 8).
145 static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
148 avio_w8(pb, 0x1ff >> bytes);
154 * Calculate how many bytes are needed to represent a given number in EBML.
156 static int ebml_num_size(uint64_t num)
159 while ((num + 1) >> bytes * 7)
165 * Write a number in EBML variable length format.
167 * @param bytes The number of bytes that need to be used to write the number.
168 * If zero, any number of bytes can be used.
170 static void put_ebml_num(AVIOContext *pb, uint64_t num, int bytes)
172 int i, needed_bytes = ebml_num_size(num);
174 // sizes larger than this are currently undefined in EBML
175 assert(num < (1ULL << 56) - 1);
178 // don't care how many bytes are used, so use the min
179 bytes = needed_bytes;
180 // the bytes needed to write the given size would exceed the bytes
181 // that we need to use, so write unknown size. This shouldn't happen.
182 assert(bytes >= needed_bytes);
184 num |= 1ULL << bytes * 7;
185 for (i = bytes - 1; i >= 0; i--)
186 avio_w8(pb, num >> i * 8);
189 static void put_ebml_uint(AVIOContext *pb, unsigned int elementid, uint64_t val)
196 put_ebml_id(pb, elementid);
197 put_ebml_num(pb, bytes, 0);
198 for (i = bytes - 1; i >= 0; i--)
199 avio_w8(pb, val >> i * 8);
202 static void put_ebml_float(AVIOContext *pb, unsigned int elementid, double val)
204 put_ebml_id(pb, elementid);
205 put_ebml_num(pb, 8, 0);
206 avio_wb64(pb, av_double2int(val));
209 static void put_ebml_binary(AVIOContext *pb, unsigned int elementid,
210 const void *buf, int size)
212 put_ebml_id(pb, elementid);
213 put_ebml_num(pb, size, 0);
214 avio_write(pb, buf, size);
217 static void put_ebml_string(AVIOContext *pb, unsigned int elementid,
220 put_ebml_binary(pb, elementid, str, strlen(str));
224 * Write a void element of a given size. Useful for reserving space in
225 * the file to be written to later.
227 * @param size The number of bytes to reserve, which must be at least 2.
229 static void put_ebml_void(AVIOContext *pb, uint64_t size)
231 int64_t currentpos = avio_tell(pb);
235 put_ebml_id(pb, EBML_ID_VOID);
236 // we need to subtract the length needed to store the size from the
237 // size we need to reserve so 2 cases, we use 8 bytes to store the
238 // size if possible, 1 byte otherwise
240 put_ebml_num(pb, size - 1, 0);
242 put_ebml_num(pb, size - 9, 8);
243 while (avio_tell(pb) < currentpos + size)
247 static ebml_master start_ebml_master(AVIOContext *pb, unsigned int elementid,
248 uint64_t expectedsize)
250 int bytes = expectedsize ? ebml_num_size(expectedsize) : 8;
251 put_ebml_id(pb, elementid);
252 put_ebml_size_unknown(pb, bytes);
253 return (ebml_master) {avio_tell(pb), bytes };
256 static void end_ebml_master(AVIOContext *pb, ebml_master master)
258 int64_t pos = avio_tell(pb);
260 if (avio_seek(pb, master.pos - master.sizebytes, SEEK_SET) < 0)
262 put_ebml_num(pb, pos - master.pos, master.sizebytes);
263 avio_seek(pb, pos, SEEK_SET);
266 static void put_xiph_size(AVIOContext *pb, int size)
269 for (i = 0; i < size / 255; i++)
271 avio_w8(pb, size % 255);
275 * Initialize a mkv_seekhead element to be ready to index level 1 Matroska
276 * elements. If a maximum number of elements is specified, enough space
277 * will be reserved at the current file location to write a seek head of
280 * @param segment_offset The absolute offset to the position in the file
281 * where the segment begins.
282 * @param numelements The maximum number of elements that will be indexed
283 * by this seek head, 0 if unlimited.
285 static mkv_seekhead *mkv_start_seekhead(AVIOContext *pb, int64_t segment_offset,
288 mkv_seekhead *new_seekhead = av_mallocz(sizeof(mkv_seekhead));
292 new_seekhead->segment_offset = segment_offset;
294 if (numelements > 0) {
295 new_seekhead->filepos = avio_tell(pb);
296 // 21 bytes max for a seek entry, 10 bytes max for the SeekHead ID
297 // and size, and 3 bytes to guarantee that an EBML void element
298 // will fit afterwards
299 new_seekhead->reserved_size = numelements * MAX_SEEKENTRY_SIZE + 13;
300 new_seekhead->max_entries = numelements;
301 put_ebml_void(pb, new_seekhead->reserved_size);
306 static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
310 // don't store more elements than we reserved space for
311 if (seekhead->max_entries > 0 && seekhead->max_entries <= seekhead->num_entries)
314 if ((err = av_reallocp_array(&seekhead->entries, seekhead->num_entries + 1,
315 sizeof(*seekhead->entries))) < 0) {
316 seekhead->num_entries = 0;
320 seekhead->entries[seekhead->num_entries].elementid = elementid;
321 seekhead->entries[seekhead->num_entries++].segmentpos = filepos - seekhead->segment_offset;
327 * Write the seek head to the file and free it. If a maximum number of
328 * elements was specified to mkv_start_seekhead(), the seek head will
329 * be written at the location reserved for it. Otherwise, it is written
330 * at the current location in the file.
332 * @return The file offset where the seekhead was written,
333 * -1 if an error occurred.
335 static int64_t mkv_write_seekhead(AVIOContext *pb, mkv_seekhead *seekhead)
337 ebml_master metaseek, seekentry;
341 currentpos = avio_tell(pb);
343 if (seekhead->reserved_size > 0) {
344 if (avio_seek(pb, seekhead->filepos, SEEK_SET) < 0) {
350 metaseek = start_ebml_master(pb, MATROSKA_ID_SEEKHEAD, seekhead->reserved_size);
351 for (i = 0; i < seekhead->num_entries; i++) {
352 mkv_seekhead_entry *entry = &seekhead->entries[i];
354 seekentry = start_ebml_master(pb, MATROSKA_ID_SEEKENTRY, MAX_SEEKENTRY_SIZE);
356 put_ebml_id(pb, MATROSKA_ID_SEEKID);
357 put_ebml_num(pb, ebml_id_size(entry->elementid), 0);
358 put_ebml_id(pb, entry->elementid);
360 put_ebml_uint(pb, MATROSKA_ID_SEEKPOSITION, entry->segmentpos);
361 end_ebml_master(pb, seekentry);
363 end_ebml_master(pb, metaseek);
365 if (seekhead->reserved_size > 0) {
366 uint64_t remaining = seekhead->filepos + seekhead->reserved_size - avio_tell(pb);
367 put_ebml_void(pb, remaining);
368 avio_seek(pb, currentpos, SEEK_SET);
370 currentpos = seekhead->filepos;
373 av_free(seekhead->entries);
379 static mkv_cues *mkv_start_cues(int64_t segment_offset)
381 mkv_cues *cues = av_mallocz(sizeof(mkv_cues));
385 cues->segment_offset = segment_offset;
389 static int mkv_add_cuepoint(mkv_cues *cues, int stream, int64_t ts, int64_t cluster_pos)
396 if ((err = av_reallocp_array(&cues->entries, cues->num_entries + 1,
397 sizeof(*cues->entries))) < 0) {
398 cues->num_entries = 0;
402 cues->entries[cues->num_entries].pts = ts;
403 cues->entries[cues->num_entries].tracknum = stream + 1;
404 cues->entries[cues->num_entries++].cluster_pos = cluster_pos - cues->segment_offset;
409 static int64_t mkv_write_cues(AVIOContext *pb, mkv_cues *cues, int num_tracks)
411 ebml_master cues_element;
415 currentpos = avio_tell(pb);
416 cues_element = start_ebml_master(pb, MATROSKA_ID_CUES, 0);
418 for (i = 0; i < cues->num_entries; i++) {
419 ebml_master cuepoint, track_positions;
420 mkv_cuepoint *entry = &cues->entries[i];
421 uint64_t pts = entry->pts;
423 cuepoint = start_ebml_master(pb, MATROSKA_ID_POINTENTRY, MAX_CUEPOINT_SIZE(num_tracks));
424 put_ebml_uint(pb, MATROSKA_ID_CUETIME, pts);
426 // put all the entries from different tracks that have the exact same
427 // timestamp into the same CuePoint
428 for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
429 track_positions = start_ebml_master(pb, MATROSKA_ID_CUETRACKPOSITION, MAX_CUETRACKPOS_SIZE);
430 put_ebml_uint(pb, MATROSKA_ID_CUETRACK , entry[j].tracknum );
431 put_ebml_uint(pb, MATROSKA_ID_CUECLUSTERPOSITION, entry[j].cluster_pos);
432 end_ebml_master(pb, track_positions);
435 end_ebml_master(pb, cuepoint);
437 end_ebml_master(pb, cues_element);
442 static int put_xiph_codecpriv(AVFormatContext *s, AVIOContext *pb, AVCodecContext *codec)
444 uint8_t *header_start[3];
446 int first_header_size;
449 if (codec->codec_id == AV_CODEC_ID_VORBIS)
450 first_header_size = 30;
452 first_header_size = 42;
454 if (avpriv_split_xiph_headers(codec->extradata, codec->extradata_size,
455 first_header_size, header_start, header_len) < 0) {
456 av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
460 avio_w8(pb, 2); // number packets - 1
461 for (j = 0; j < 2; j++) {
462 put_xiph_size(pb, header_len[j]);
464 for (j = 0; j < 3; j++)
465 avio_write(pb, header_start[j], header_len[j]);
470 static int put_wv_codecpriv(AVIOContext *pb, AVCodecContext *codec)
472 if (codec->extradata && codec->extradata_size == 2)
473 avio_write(pb, codec->extradata, 2);
475 avio_wl16(pb, 0x403); // fallback to the version mentioned in matroska specs
479 static int put_flac_codecpriv(AVFormatContext *s,
480 AVIOContext *pb, AVCodecContext *codec)
482 int write_comment = (codec->channel_layout &&
483 !(codec->channel_layout & ~0x3ffffULL) &&
484 !ff_flac_is_native_layout(codec->channel_layout));
485 int ret = ff_flac_write_header(pb, codec->extradata, codec->extradata_size,
492 const char *vendor = (s->flags & AVFMT_FLAG_BITEXACT) ?
493 "Libav" : LIBAVFORMAT_IDENT;
494 AVDictionary *dict = NULL;
495 uint8_t buf[32], *data, *p;
498 snprintf(buf, sizeof(buf), "0x%"PRIx64, codec->channel_layout);
499 av_dict_set(&dict, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", buf, 0);
501 len = ff_vorbiscomment_length(dict, vendor);
502 data = av_malloc(len + 4);
505 return AVERROR(ENOMEM);
509 AV_WB24(data + 1, len);
512 ff_vorbiscomment_write(&p, &dict, vendor);
514 avio_write(pb, data, len + 4);
523 static int get_aac_sample_rates(AVFormatContext *s, AVCodecContext *codec,
524 int *sample_rate, int *output_sample_rate)
526 MPEG4AudioConfig mp4ac;
528 if (avpriv_mpeg4audio_get_config(&mp4ac, codec->extradata,
529 codec->extradata_size * 8, 1) < 0) {
530 av_log(s, AV_LOG_ERROR,
531 "Error parsing AAC extradata, unable to determine samplerate.\n");
532 return AVERROR(EINVAL);
535 *sample_rate = mp4ac.sample_rate;
536 *output_sample_rate = mp4ac.ext_sample_rate;
540 static int mkv_write_native_codecprivate(AVFormatContext *s,
541 AVCodecContext *codec,
544 switch (codec->codec_id) {
545 case AV_CODEC_ID_VORBIS:
546 case AV_CODEC_ID_THEORA:
547 return put_xiph_codecpriv(s, dyn_cp, codec);
548 case AV_CODEC_ID_FLAC:
549 return put_flac_codecpriv(s, dyn_cp, codec);
550 case AV_CODEC_ID_WAVPACK:
551 return put_wv_codecpriv(dyn_cp, codec);
552 case AV_CODEC_ID_H264:
553 return ff_isom_write_avcc(dyn_cp, codec->extradata,
554 codec->extradata_size);
555 case AV_CODEC_ID_HEVC:
556 return ff_isom_write_hvcc(dyn_cp, codec->extradata,
557 codec->extradata_size, 0);
558 case AV_CODEC_ID_ALAC:
559 if (codec->extradata_size < 36) {
560 av_log(s, AV_LOG_ERROR,
561 "Invalid extradata found, ALAC expects a 36-byte "
563 return AVERROR_INVALIDDATA;
565 avio_write(dyn_cp, codec->extradata + 12,
566 codec->extradata_size - 12);
569 if (codec->extradata_size)
570 avio_write(dyn_cp, codec->extradata, codec->extradata_size);
576 static int mkv_write_codecprivate(AVFormatContext *s, AVIOContext *pb,
577 AVCodecContext *codec, int native_id,
582 int ret, codecpriv_size;
584 ret = avio_open_dyn_buf(&dyn_cp);
589 ret = mkv_write_native_codecprivate(s, codec, dyn_cp);
590 } else if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
592 if (!codec->codec_tag)
593 codec->codec_tag = ff_codec_get_tag(ff_codec_movvideo_tags,
595 if (codec->extradata_size)
596 avio_write(dyn_cp, codec->extradata, codec->extradata_size);
598 if (!codec->codec_tag)
599 codec->codec_tag = ff_codec_get_tag(ff_codec_bmp_tags,
601 if (!codec->codec_tag) {
602 av_log(s, AV_LOG_ERROR, "No bmp codec ID found.\n");
606 ff_put_bmp_header(dyn_cp, codec, ff_codec_bmp_tags, 0);
608 } else if (codec->codec_type == AVMEDIA_TYPE_AUDIO) {
610 tag = ff_codec_get_tag(ff_codec_wav_tags, codec->codec_id);
612 av_log(s, AV_LOG_ERROR, "No wav codec ID found.\n");
615 if (!codec->codec_tag)
616 codec->codec_tag = tag;
618 ff_put_wav_header(dyn_cp, codec);
621 codecpriv_size = avio_close_dyn_buf(dyn_cp, &codecpriv);
623 put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codecpriv,
629 static int mkv_write_stereo_mode(AVFormatContext *s, AVIOContext *pb,
630 AVStream *st, int mode)
633 int display_width, display_height;
634 int h_width = 1, h_height = 1;
635 AVCodecContext *codec = st->codec;
636 AVDictionaryEntry *tag;
637 MatroskaVideoStereoModeType format = MATROSKA_VIDEO_STEREOMODE_TYPE_NB;
639 // convert metadata into proper side data and add it to the stream
640 if ((tag = av_dict_get(s->metadata, "stereo_mode", NULL, 0))) {
641 int stereo_mode = atoi(tag->value);
642 if (stereo_mode < MATROSKA_VIDEO_STEREOMODE_TYPE_NB &&
643 stereo_mode != 10 && stereo_mode != 12) {
644 int ret = ff_mkv_stereo3d_conv(st, stereo_mode);
650 // iterate to find the stereo3d side data
651 for (i = 0; i < st->nb_side_data; i++) {
652 AVPacketSideData sd = st->side_data[i];
653 if (sd.type == AV_PKT_DATA_STEREO3D) {
654 AVStereo3D *stereo = (AVStereo3D *)sd.data;
656 switch (stereo->type) {
658 format = MATROSKA_VIDEO_STEREOMODE_TYPE_MONO;
660 case AV_STEREO3D_SIDEBYSIDE:
661 format = (stereo->flags & AV_STEREO3D_FLAG_INVERT)
662 ? MATROSKA_VIDEO_STEREOMODE_TYPE_RIGHT_LEFT
663 : MATROSKA_VIDEO_STEREOMODE_TYPE_LEFT_RIGHT;
666 case AV_STEREO3D_TOPBOTTOM:
667 format = MATROSKA_VIDEO_STEREOMODE_TYPE_TOP_BOTTOM;
668 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
672 case AV_STEREO3D_CHECKERBOARD:
673 format = MATROSKA_VIDEO_STEREOMODE_TYPE_CHECKERBOARD_LR;
674 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
677 case AV_STEREO3D_LINES:
678 format = MATROSKA_VIDEO_STEREOMODE_TYPE_ROW_INTERLEAVED_LR;
679 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
683 case AV_STEREO3D_COLUMNS:
684 format = MATROSKA_VIDEO_STEREOMODE_TYPE_COL_INTERLEAVED_LR;
685 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
689 case AV_STEREO3D_FRAMESEQUENCE:
690 format = MATROSKA_VIDEO_STEREOMODE_TYPE_BOTH_EYES_BLOCK_LR;
691 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
700 // if webm, do not write unsupported modes
701 if (mode == MODE_WEBM &&
702 (format > MATROSKA_VIDEO_STEREOMODE_TYPE_TOP_BOTTOM &&
703 format != MATROSKA_VIDEO_STEREOMODE_TYPE_RIGHT_LEFT))
704 format = MATROSKA_VIDEO_STEREOMODE_TYPE_NB;
706 // write StereoMode if format is valid
707 if (format < MATROSKA_VIDEO_STEREOMODE_TYPE_NB)
708 put_ebml_uint(pb, MATROSKA_ID_VIDEOSTEREOMODE, format);
710 // write DisplayWidth and DisplayHeight, they contain the size of
711 // a single source view and/or the display aspect ratio
712 display_width = codec->width / h_width;
713 display_height = codec->height / h_height;
714 if (st->sample_aspect_ratio.num) {
715 display_width *= av_q2d(st->sample_aspect_ratio);
716 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYUNIT, 3); // DAR
718 if (st->sample_aspect_ratio.num ||
719 format < MATROSKA_VIDEO_STEREOMODE_TYPE_NB) {
720 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH, display_width);
721 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, display_height);
727 static int mkv_write_track(AVFormatContext *s, MatroskaMuxContext *mkv,
728 int i, AVIOContext *pb)
730 AVStream *st = s->streams[i];
731 AVCodecContext *codec = st->codec;
732 ebml_master subinfo, track;
735 int bit_depth = av_get_bits_per_sample(codec->codec_id);
736 int sample_rate = codec->sample_rate;
737 int output_sample_rate = 0;
739 AVDictionaryEntry *tag;
741 // ms precision is the de-facto standard timescale for mkv files
742 avpriv_set_pts_info(st, 64, 1, 1000);
744 if (codec->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
745 mkv->have_attachments = 1;
750 bit_depth = av_get_bytes_per_sample(codec->sample_fmt) << 3;
752 if (codec->codec_id == AV_CODEC_ID_AAC) {
753 ret = get_aac_sample_rates(s, codec, &sample_rate, &output_sample_rate);
758 track = start_ebml_master(pb, MATROSKA_ID_TRACKENTRY, 0);
759 put_ebml_uint (pb, MATROSKA_ID_TRACKNUMBER , i + 1);
760 put_ebml_uint (pb, MATROSKA_ID_TRACKUID , i + 1);
761 put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0); // no lacing (yet)
763 if ((tag = av_dict_get(st->metadata, "title", NULL, 0)))
764 put_ebml_string(pb, MATROSKA_ID_TRACKNAME, tag->value);
765 tag = av_dict_get(st->metadata, "language", NULL, 0);
766 put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag ? tag->value:"und");
768 // The default value for TRACKFLAGDEFAULT is 1, so add element
769 // if we need to clear it.
770 if (!(st->disposition & AV_DISPOSITION_DEFAULT))
771 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGDEFAULT, !!(st->disposition & AV_DISPOSITION_DEFAULT));
772 if (st->disposition & AV_DISPOSITION_FORCED)
773 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGFORCED, !!(st->disposition & AV_DISPOSITION_FORCED));
775 if (codec->codec_type == AVMEDIA_TYPE_AUDIO && codec->initial_padding) {
776 mkv->tracks[i].ts_offset = av_rescale_q(codec->initial_padding,
777 (AVRational){ 1, codec->sample_rate },
780 put_ebml_uint(pb, MATROSKA_ID_CODECDELAY,
781 av_rescale_q(codec->initial_padding,
782 (AVRational){ 1, codec->sample_rate },
783 (AVRational){ 1, 1000000000 }));
786 // look for a codec ID string specific to mkv to use,
787 // if none are found, use AVI codes
788 for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
789 if (ff_mkv_codec_tags[j].id == codec->codec_id) {
790 put_ebml_string(pb, MATROSKA_ID_CODECID, ff_mkv_codec_tags[j].str);
796 if (mkv->mode == MODE_WEBM && !(codec->codec_id == AV_CODEC_ID_VP8 ||
797 codec->codec_id == AV_CODEC_ID_VP9 ||
798 codec->codec_id == AV_CODEC_ID_OPUS ||
799 codec->codec_id == AV_CODEC_ID_VORBIS)) {
800 av_log(s, AV_LOG_ERROR,
801 "Only VP8 or VP9 video and Vorbis or Opus audio are supported for WebM.\n");
802 return AVERROR(EINVAL);
805 switch (codec->codec_type) {
806 case AVMEDIA_TYPE_VIDEO:
807 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_VIDEO);
808 if (st->avg_frame_rate.num > 0 && st->avg_frame_rate.den > 0)
809 put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, 1E9 / av_q2d(st->avg_frame_rate));
812 ff_codec_get_tag(ff_codec_movvideo_tags, codec->codec_id) &&
813 (!ff_codec_get_tag(ff_codec_bmp_tags, codec->codec_id) ||
814 codec->codec_id == AV_CODEC_ID_SVQ1 ||
815 codec->codec_id == AV_CODEC_ID_SVQ3 ||
816 codec->codec_id == AV_CODEC_ID_CINEPAK))
820 put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");
821 else if (!native_id) {
822 // if there is no mkv-specific codec ID, use VFW mode
823 put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");
824 mkv->tracks[i].write_dts = 1;
827 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
828 // XXX: interlace flag?
829 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , codec->width);
830 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, codec->height);
832 // check both side data and metadata for stereo information,
833 // write the result to the bitstream if any is found
834 ret = mkv_write_stereo_mode(s, pb, st, mkv->mode);
838 end_ebml_master(pb, subinfo);
841 case AVMEDIA_TYPE_AUDIO:
842 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_AUDIO);
845 // no mkv-specific ID, use ACM mode
846 put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");
848 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);
849 put_ebml_uint (pb, MATROSKA_ID_AUDIOCHANNELS , codec->channels);
850 put_ebml_float (pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, sample_rate);
851 if (output_sample_rate)
852 put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
854 put_ebml_uint(pb, MATROSKA_ID_AUDIOBITDEPTH, bit_depth);
855 end_ebml_master(pb, subinfo);
858 case AVMEDIA_TYPE_SUBTITLE:
859 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_SUBTITLE);
861 av_log(s, AV_LOG_ERROR, "Subtitle codec %d is not supported.\n", codec->codec_id);
862 return AVERROR(ENOSYS);
866 av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.\n");
869 ret = mkv_write_codecprivate(s, pb, codec, native_id, qt_id);
873 end_ebml_master(pb, track);
878 static int mkv_write_tracks(AVFormatContext *s)
880 MatroskaMuxContext *mkv = s->priv_data;
881 AVIOContext *pb = s->pb;
885 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TRACKS, avio_tell(pb));
889 tracks = start_ebml_master(pb, MATROSKA_ID_TRACKS, 0);
890 for (i = 0; i < s->nb_streams; i++) {
891 ret = mkv_write_track(s, mkv, i, pb);
895 end_ebml_master(pb, tracks);
899 static int mkv_write_chapters(AVFormatContext *s)
901 MatroskaMuxContext *mkv = s->priv_data;
902 AVIOContext *pb = s->pb;
903 ebml_master chapters, editionentry;
904 AVRational scale = {1, 1E9};
907 if (!s->nb_chapters || mkv->wrote_chapters)
910 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CHAPTERS, avio_tell(pb));
911 if (ret < 0) return ret;
913 chapters = start_ebml_master(pb, MATROSKA_ID_CHAPTERS , 0);
914 editionentry = start_ebml_master(pb, MATROSKA_ID_EDITIONENTRY, 0);
915 put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGDEFAULT, 1);
916 put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGHIDDEN , 0);
917 for (i = 0; i < s->nb_chapters; i++) {
918 ebml_master chapteratom, chapterdisplay;
919 AVChapter *c = s->chapters[i];
920 int64_t chapterstart = av_rescale_q(c->start, c->time_base, scale);
921 int64_t chapterend = av_rescale_q(c->end, c->time_base, scale);
922 AVDictionaryEntry *t = NULL;
923 if (chapterstart < 0 || chapterstart > chapterend || chapterend < 0) {
924 av_log(s, AV_LOG_ERROR,
925 "Invalid chapter start (%"PRId64") or end (%"PRId64").\n",
926 chapterstart, chapterend);
927 return AVERROR_INVALIDDATA;
930 chapteratom = start_ebml_master(pb, MATROSKA_ID_CHAPTERATOM, 0);
931 put_ebml_uint(pb, MATROSKA_ID_CHAPTERUID, c->id);
932 put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMESTART, chapterstart);
933 put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMEEND, chapterend);
934 put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGHIDDEN , 0);
935 put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGENABLED, 1);
936 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
937 chapterdisplay = start_ebml_master(pb, MATROSKA_ID_CHAPTERDISPLAY, 0);
938 put_ebml_string(pb, MATROSKA_ID_CHAPSTRING, t->value);
939 put_ebml_string(pb, MATROSKA_ID_CHAPLANG , "und");
940 end_ebml_master(pb, chapterdisplay);
942 end_ebml_master(pb, chapteratom);
944 end_ebml_master(pb, editionentry);
945 end_ebml_master(pb, chapters);
947 mkv->wrote_chapters = 1;
951 static int mkv_write_simpletag(AVIOContext *pb, AVDictionaryEntry *t)
953 uint8_t *key = av_strdup(t->key);
955 const uint8_t *lang = NULL;
959 return AVERROR(ENOMEM);
961 if ((p = strrchr(p, '-')) &&
962 (lang = av_convert_lang_to(p + 1, AV_LANG_ISO639_2_BIBL)))
969 else if (*p >= 'a' && *p <= 'z')
974 tag = start_ebml_master(pb, MATROSKA_ID_SIMPLETAG, 0);
975 put_ebml_string(pb, MATROSKA_ID_TAGNAME, key);
977 put_ebml_string(pb, MATROSKA_ID_TAGLANG, lang);
978 put_ebml_string(pb, MATROSKA_ID_TAGSTRING, t->value);
979 end_ebml_master(pb, tag);
985 static int mkv_write_tag(AVFormatContext *s, AVDictionary *m, unsigned int elementid,
986 unsigned int uid, ebml_master *tags)
988 MatroskaMuxContext *mkv = s->priv_data;
989 ebml_master tag, targets;
990 AVDictionaryEntry *t = NULL;
994 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TAGS, avio_tell(s->pb));
995 if (ret < 0) return ret;
997 *tags = start_ebml_master(s->pb, MATROSKA_ID_TAGS, 0);
1000 tag = start_ebml_master(s->pb, MATROSKA_ID_TAG, 0);
1001 targets = start_ebml_master(s->pb, MATROSKA_ID_TAGTARGETS, 0);
1003 put_ebml_uint(s->pb, elementid, uid);
1004 end_ebml_master(s->pb, targets);
1006 while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX))) {
1007 if (av_strcasecmp(t->key, "title") &&
1008 av_strcasecmp(t->key, "encoding_tool") &&
1009 (elementid != MATROSKA_ID_TAGTARGETS_TRACKUID ||
1010 av_strcasecmp(t->key, "language"))) {
1011 ret = mkv_write_simpletag(s->pb, t);
1017 end_ebml_master(s->pb, tag);
1021 static int mkv_write_tags(AVFormatContext *s)
1023 ebml_master tags = {0};
1026 ff_metadata_conv_ctx(s, ff_mkv_metadata_conv, NULL);
1028 if (av_dict_get(s->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX)) {
1029 ret = mkv_write_tag(s, s->metadata, 0, 0, &tags);
1030 if (ret < 0) return ret;
1033 for (i = 0; i < s->nb_streams; i++) {
1034 AVStream *st = s->streams[i];
1036 if (!av_dict_get(st->metadata, "", 0, AV_DICT_IGNORE_SUFFIX))
1039 ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &tags);
1040 if (ret < 0) return ret;
1043 for (i = 0; i < s->nb_chapters; i++) {
1044 AVChapter *ch = s->chapters[i];
1046 if (!av_dict_get(ch->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX))
1049 ret = mkv_write_tag(s, ch->metadata, MATROSKA_ID_TAGTARGETS_CHAPTERUID, ch->id, &tags);
1050 if (ret < 0) return ret;
1054 end_ebml_master(s->pb, tags);
1058 static int mkv_write_attachments(AVFormatContext *s)
1060 MatroskaMuxContext *mkv = s->priv_data;
1061 AVIOContext *pb = s->pb;
1062 ebml_master attachments;
1066 if (!mkv->have_attachments)
1069 av_lfg_init(&c, av_get_random_seed());
1071 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_ATTACHMENTS, avio_tell(pb));
1072 if (ret < 0) return ret;
1074 attachments = start_ebml_master(pb, MATROSKA_ID_ATTACHMENTS, 0);
1076 for (i = 0; i < s->nb_streams; i++) {
1077 AVStream *st = s->streams[i];
1078 ebml_master attached_file;
1079 AVDictionaryEntry *t;
1080 const char *mimetype = NULL;
1082 if (st->codec->codec_type != AVMEDIA_TYPE_ATTACHMENT)
1085 attached_file = start_ebml_master(pb, MATROSKA_ID_ATTACHEDFILE, 0);
1087 if (t = av_dict_get(st->metadata, "title", NULL, 0))
1088 put_ebml_string(pb, MATROSKA_ID_FILEDESC, t->value);
1089 if (!(t = av_dict_get(st->metadata, "filename", NULL, 0))) {
1090 av_log(s, AV_LOG_ERROR, "Attachment stream %d has no filename tag.\n", i);
1091 return AVERROR(EINVAL);
1093 put_ebml_string(pb, MATROSKA_ID_FILENAME, t->value);
1094 if (t = av_dict_get(st->metadata, "mimetype", NULL, 0))
1095 mimetype = t->value;
1096 else if (st->codec->codec_id != AV_CODEC_ID_NONE ) {
1098 for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
1099 if (ff_mkv_mime_tags[i].id == st->codec->codec_id) {
1100 mimetype = ff_mkv_mime_tags[i].str;
1103 for (i = 0; ff_mkv_image_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
1104 if (ff_mkv_image_mime_tags[i].id == st->codec->codec_id) {
1105 mimetype = ff_mkv_image_mime_tags[i].str;
1110 av_log(s, AV_LOG_ERROR, "Attachment stream %d has no mimetype tag and "
1111 "it cannot be deduced from the codec id.\n", i);
1112 return AVERROR(EINVAL);
1115 put_ebml_string(pb, MATROSKA_ID_FILEMIMETYPE, mimetype);
1116 put_ebml_binary(pb, MATROSKA_ID_FILEDATA, st->codec->extradata, st->codec->extradata_size);
1117 put_ebml_uint(pb, MATROSKA_ID_FILEUID, av_lfg_get(&c));
1118 end_ebml_master(pb, attached_file);
1120 end_ebml_master(pb, attachments);
1125 static int mkv_write_header(AVFormatContext *s)
1127 MatroskaMuxContext *mkv = s->priv_data;
1128 AVIOContext *pb = s->pb;
1129 ebml_master ebml_header, segment_info;
1130 AVDictionaryEntry *tag;
1133 if (!strcmp(s->oformat->name, "webm"))
1134 mkv->mode = MODE_WEBM;
1136 mkv->mode = MODE_MATROSKAv2;
1138 mkv->tracks = av_mallocz(s->nb_streams * sizeof(*mkv->tracks));
1140 return AVERROR(ENOMEM);
1142 ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
1143 put_ebml_uint (pb, EBML_ID_EBMLVERSION , 1);
1144 put_ebml_uint (pb, EBML_ID_EBMLREADVERSION , 1);
1145 put_ebml_uint (pb, EBML_ID_EBMLMAXIDLENGTH , 4);
1146 put_ebml_uint (pb, EBML_ID_EBMLMAXSIZELENGTH , 8);
1147 put_ebml_string (pb, EBML_ID_DOCTYPE , s->oformat->name);
1148 put_ebml_uint (pb, EBML_ID_DOCTYPEVERSION , 2);
1149 put_ebml_uint (pb, EBML_ID_DOCTYPEREADVERSION , 2);
1150 end_ebml_master(pb, ebml_header);
1152 mkv->segment = start_ebml_master(pb, MATROSKA_ID_SEGMENT, 0);
1153 mkv->segment_offset = avio_tell(pb);
1155 // we write 2 seek heads - one at the end of the file to point to each
1156 // cluster, and one at the beginning to point to all other level one
1157 // elements (including the seek head at the end of the file), which
1158 // isn't more than 10 elements if we only write one of each other
1159 // currently defined level 1 element
1160 mkv->main_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 10);
1161 if (!mkv->main_seekhead)
1162 return AVERROR(ENOMEM);
1164 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_INFO, avio_tell(pb));
1165 if (ret < 0) return ret;
1167 segment_info = start_ebml_master(pb, MATROSKA_ID_INFO, 0);
1168 put_ebml_uint(pb, MATROSKA_ID_TIMECODESCALE, 1000000);
1169 if ((tag = av_dict_get(s->metadata, "title", NULL, 0)))
1170 put_ebml_string(pb, MATROSKA_ID_TITLE, tag->value);
1171 if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
1172 uint32_t segment_uid[4];
1175 av_lfg_init(&lfg, av_get_random_seed());
1177 for (i = 0; i < 4; i++)
1178 segment_uid[i] = av_lfg_get(&lfg);
1180 put_ebml_string(pb, MATROSKA_ID_MUXINGAPP, LIBAVFORMAT_IDENT);
1181 if ((tag = av_dict_get(s->metadata, "encoding_tool", NULL, 0)))
1182 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, tag->value);
1184 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, LIBAVFORMAT_IDENT);
1185 put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
1188 // reserve space for the duration
1190 mkv->duration_offset = avio_tell(pb);
1191 put_ebml_void(pb, 11); // assumes double-precision float to be written
1192 end_ebml_master(pb, segment_info);
1194 ret = mkv_write_tracks(s);
1198 if (mkv->mode != MODE_WEBM) {
1199 ret = mkv_write_chapters(s);
1203 ret = mkv_write_tags(s);
1207 ret = mkv_write_attachments(s);
1212 if (!s->pb->seekable)
1213 mkv_write_seekhead(pb, mkv->main_seekhead);
1215 mkv->cues = mkv_start_cues(mkv->segment_offset);
1217 return AVERROR(ENOMEM);
1219 if (pb->seekable && mkv->reserve_cues_space) {
1220 mkv->cues_pos = avio_tell(pb);
1221 put_ebml_void(pb, mkv->reserve_cues_space);
1224 av_init_packet(&mkv->cur_audio_pkt);
1225 mkv->cur_audio_pkt.size = 0;
1229 // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1230 // after 4k and on a keyframe
1232 if (mkv->cluster_time_limit < 0)
1233 mkv->cluster_time_limit = 5000;
1234 if (mkv->cluster_size_limit < 0)
1235 mkv->cluster_size_limit = 5 * 1024 * 1024;
1237 if (mkv->cluster_time_limit < 0)
1238 mkv->cluster_time_limit = 1000;
1239 if (mkv->cluster_size_limit < 0)
1240 mkv->cluster_size_limit = 32 * 1024;
1246 static int mkv_blockgroup_size(int pkt_size)
1248 int size = pkt_size + 4;
1249 size += ebml_num_size(size);
1250 size += 2; // EBML ID for block and block duration
1251 size += 8; // max size of block duration
1252 size += ebml_num_size(size);
1253 size += 1; // blockgroup EBML ID
1257 static int ass_get_duration(AVFormatContext *s, const uint8_t *p)
1259 int sh, sm, ss, sc, eh, em, es, ec;
1260 uint64_t start, end;
1262 if (sscanf(p, "%*[^,],%d:%d:%d%*c%d,%d:%d:%d%*c%d",
1263 &sh, &sm, &ss, &sc, &eh, &em, &es, &ec) != 8)
1266 if (sh > 9 || sm > 59 || ss > 59 || sc > 99 ||
1267 eh > 9 || em > 59 || es > 59 || ec > 99) {
1268 av_log(s, AV_LOG_WARNING,
1269 "Non-standard time reference %d:%d:%d.%d,%d:%d:%d.%d\n",
1270 sh, sm, ss, sc, eh, em, es, ec);
1274 start = 3600000 * sh + 60000 * sm + 1000 * ss + 10 * sc;
1275 end = 3600000 * eh + 60000 * em + 1000 * es + 10 * ec;
1278 av_log(s, AV_LOG_WARNING,
1279 "Unexpected time reference %d:%d:%d.%d,%d:%d:%d.%d\n",
1280 sh, sm, ss, sc, eh, em, es, ec);
1287 static int mkv_write_ass_blocks(AVFormatContext *s, AVIOContext *pb,
1290 MatroskaMuxContext *mkv = s->priv_data;
1291 int i, layer = 0, max_duration = 0, size, line_size, data_size = pkt->size;
1292 uint8_t *start, *end, *data = pkt->data;
1293 ebml_master blockgroup;
1297 int duration = ass_get_duration(s, data);
1298 max_duration = FFMAX(duration, max_duration);
1299 end = memchr(data, '\n', data_size);
1300 size = line_size = end ? end - data + 1 : data_size;
1301 size -= end ? (end[-1] == '\r') + 1 : 0;
1303 for (i = 0; i < 3; i++, start++)
1304 if (!(start = memchr(start, ',', size - (start - data))))
1305 return max_duration;
1306 size -= start - data;
1307 sscanf(data, "Dialogue: %d,", &layer);
1308 i = snprintf(buffer, sizeof(buffer), "%" PRId64 ",%d,",
1309 s->streams[pkt->stream_index]->nb_frames, layer);
1310 size = FFMIN(i + size, sizeof(buffer));
1311 memcpy(buffer + i, start, size - i);
1313 av_log(s, AV_LOG_DEBUG,
1314 "Writing block at offset %" PRIu64 ", size %d, "
1315 "pts %" PRId64 ", duration %d\n",
1316 avio_tell(pb), size, pkt->pts, duration);
1317 blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
1318 mkv_blockgroup_size(size));
1319 put_ebml_id(pb, MATROSKA_ID_BLOCK);
1320 put_ebml_num(pb, size + 4, 0);
1321 // this assumes stream_index is less than 126
1322 avio_w8(pb, 0x80 | (pkt->stream_index + 1));
1323 avio_wb16(pb, pkt->pts - mkv->cluster_pts);
1325 avio_write(pb, buffer, size);
1326 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
1327 end_ebml_master(pb, blockgroup);
1330 data_size -= line_size;
1333 return max_duration;
1336 static int mkv_strip_wavpack(const uint8_t *src, uint8_t **pdst, int *size)
1343 dst = av_malloc(srclen);
1345 return AVERROR(ENOMEM);
1347 while (srclen >= WV_HEADER_SIZE) {
1350 ret = ff_wv_parse_header(&header, src);
1353 src += WV_HEADER_SIZE;
1354 srclen -= WV_HEADER_SIZE;
1356 if (srclen < header.blocksize) {
1357 ret = AVERROR_INVALIDDATA;
1361 if (header.initial) {
1362 AV_WL32(dst + offset, header.samples);
1365 AV_WL32(dst + offset, header.flags);
1366 AV_WL32(dst + offset + 4, header.crc);
1369 if (!(header.initial && header.final)) {
1370 AV_WL32(dst + offset, header.blocksize);
1374 memcpy(dst + offset, src, header.blocksize);
1375 src += header.blocksize;
1376 srclen -= header.blocksize;
1377 offset += header.blocksize;
1389 static void mkv_write_block(AVFormatContext *s, AVIOContext *pb,
1390 unsigned int blockid, AVPacket *pkt, int flags)
1392 MatroskaMuxContext *mkv = s->priv_data;
1393 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1394 uint8_t *data = NULL;
1395 int offset = 0, size = pkt->size;
1396 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1398 av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
1399 "pts %" PRId64 ", dts %" PRId64 ", duration %" PRId64 ", flags %d\n",
1400 avio_tell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration, flags);
1401 if (codec->codec_id == AV_CODEC_ID_H264 && codec->extradata_size > 0 &&
1402 (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
1403 ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
1404 else if (codec->codec_id == AV_CODEC_ID_HEVC && codec->extradata_size > 6 &&
1405 (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
1406 /* extradata is Annex B, assume the bitstream is too and convert it */
1407 ff_hevc_annexb2mp4_buf(pkt->data, &data, &size, 0, NULL);
1408 else if (codec->codec_id == AV_CODEC_ID_WAVPACK) {
1409 int ret = mkv_strip_wavpack(pkt->data, &data, &size);
1411 av_log(s, AV_LOG_ERROR, "Error stripping a WavPack packet.\n");
1417 if (codec->codec_id == AV_CODEC_ID_PRORES) {
1418 /* Matroska specification requires to remove the first QuickTime atom
1424 put_ebml_id(pb, blockid);
1425 put_ebml_num(pb, size + 4, 0);
1426 // this assumes stream_index is less than 126
1427 avio_w8(pb, 0x80 | (pkt->stream_index + 1));
1428 avio_wb16(pb, ts - mkv->cluster_pts);
1430 avio_write(pb, data + offset, size);
1431 if (data != pkt->data)
1435 static int srt_get_duration(uint8_t **buf)
1437 int i, duration = 0;
1439 for (i = 0; i < 2 && !duration; i++) {
1440 int s_hour, s_min, s_sec, s_hsec, e_hour, e_min, e_sec, e_hsec;
1441 if (sscanf(*buf, "%d:%2d:%2d%*1[,.]%3d --> %d:%2d:%2d%*1[,.]%3d",
1442 &s_hour, &s_min, &s_sec, &s_hsec,
1443 &e_hour, &e_min, &e_sec, &e_hsec) == 8) {
1444 s_min += 60 * s_hour;
1445 e_min += 60 * e_hour;
1446 s_sec += 60 * s_min;
1448 e_sec += 60 * e_min;
1449 s_hsec += 1000 * s_sec;
1450 e_hsec += 1000 * e_sec;
1452 duration = e_hsec - s_hsec;
1454 *buf += strcspn(*buf, "\n") + 1;
1459 static int mkv_write_srt_blocks(AVFormatContext *s, AVIOContext *pb,
1462 ebml_master blockgroup;
1463 AVPacket pkt2 = *pkt;
1464 int64_t duration = srt_get_duration(&pkt2.data);
1465 pkt2.size -= pkt2.data - pkt->data;
1467 blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
1468 mkv_blockgroup_size(pkt2.size));
1469 mkv_write_block(s, pb, MATROSKA_ID_BLOCK, &pkt2, 0);
1470 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
1471 end_ebml_master(pb, blockgroup);
1476 static void mkv_flush_dynbuf(AVFormatContext *s)
1478 MatroskaMuxContext *mkv = s->priv_data;
1485 bufsize = avio_close_dyn_buf(mkv->dyn_bc, &dyn_buf);
1486 avio_write(s->pb, dyn_buf, bufsize);
1491 static int mkv_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
1493 MatroskaMuxContext *mkv = s->priv_data;
1494 AVIOContext *pb = s->pb;
1495 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1496 int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1497 int duration = pkt->duration;
1499 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1501 if (ts == AV_NOPTS_VALUE) {
1502 av_log(s, AV_LOG_ERROR, "Can't write packet with unknown timestamp\n");
1503 return AVERROR(EINVAL);
1505 ts += mkv->tracks[pkt->stream_index].ts_offset;
1507 if (!s->pb->seekable) {
1509 ret = avio_open_dyn_buf(&mkv->dyn_bc);
1516 if (!mkv->cluster_pos) {
1517 mkv->cluster_pos = avio_tell(s->pb);
1518 mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER, 0);
1519 put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, FFMAX(0, ts));
1520 mkv->cluster_pts = FFMAX(0, ts);
1523 if (codec->codec_type != AVMEDIA_TYPE_SUBTITLE) {
1524 mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
1525 } else if (codec->codec_id == AV_CODEC_ID_SSA) {
1526 duration = mkv_write_ass_blocks(s, pb, pkt);
1527 } else if (codec->codec_id == AV_CODEC_ID_SRT) {
1528 duration = mkv_write_srt_blocks(s, pb, pkt);
1530 ebml_master blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
1531 mkv_blockgroup_size(pkt->size));
1532 duration = pkt->duration;
1533 #if FF_API_CONVERGENCE_DURATION
1534 FF_DISABLE_DEPRECATION_WARNINGS
1535 if (pkt->convergence_duration)
1536 duration = pkt->convergence_duration;
1537 FF_ENABLE_DEPRECATION_WARNINGS
1539 mkv_write_block(s, pb, MATROSKA_ID_BLOCK, pkt, 0);
1540 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
1541 end_ebml_master(pb, blockgroup);
1544 if (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe) {
1545 ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, ts,
1551 mkv->duration = FFMAX(mkv->duration, ts + duration);
1555 static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
1557 MatroskaMuxContext *mkv = s->priv_data;
1558 int codec_type = s->streams[pkt->stream_index]->codec->codec_type;
1559 int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1561 int64_t cluster_time;
1565 if (mkv->tracks[pkt->stream_index].write_dts)
1566 cluster_time = pkt->dts - mkv->cluster_pts;
1568 cluster_time = pkt->pts - mkv->cluster_pts;
1569 cluster_time += mkv->tracks[pkt->stream_index].ts_offset;
1571 // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1572 // after 4k and on a keyframe
1573 if (s->pb->seekable) {
1575 cluster_size = avio_tell(pb) - mkv->cluster_pos;
1578 cluster_size = avio_tell(pb);
1581 if (mkv->cluster_pos &&
1582 (cluster_size > mkv->cluster_size_limit ||
1583 cluster_time > mkv->cluster_time_limit ||
1584 (codec_type == AVMEDIA_TYPE_VIDEO && keyframe &&
1585 cluster_size > 4 * 1024))) {
1586 av_log(s, AV_LOG_DEBUG,
1587 "Starting new cluster at offset %" PRIu64 " bytes, "
1588 "pts %" PRIu64 "dts %" PRIu64 "\n",
1589 avio_tell(pb), pkt->pts, pkt->dts);
1590 end_ebml_master(pb, mkv->cluster);
1591 mkv->cluster_pos = 0;
1593 mkv_flush_dynbuf(s);
1597 // check if we have an audio packet cached
1598 if (mkv->cur_audio_pkt.size > 0) {
1599 ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
1600 av_packet_unref(&mkv->cur_audio_pkt);
1602 av_log(s, AV_LOG_ERROR,
1603 "Could not write cached audio packet ret:%d\n", ret);
1608 // buffer an audio packet to ensure the packet containing the video
1609 // keyframe's timecode is contained in the same cluster for WebM
1610 if (codec_type == AVMEDIA_TYPE_AUDIO) {
1611 ret = av_packet_ref(&mkv->cur_audio_pkt, pkt);
1613 ret = mkv_write_packet_internal(s, pkt);
1617 static int mkv_write_flush_packet(AVFormatContext *s, AVPacket *pkt)
1619 MatroskaMuxContext *mkv = s->priv_data;
1621 if (s->pb->seekable)
1626 if (mkv->cluster_pos) {
1627 av_log(s, AV_LOG_DEBUG,
1628 "Flushing cluster at offset %" PRIu64 " bytes\n",
1630 end_ebml_master(pb, mkv->cluster);
1631 mkv->cluster_pos = 0;
1633 mkv_flush_dynbuf(s);
1638 return mkv_write_packet(s, pkt);
1641 static int mkv_write_trailer(AVFormatContext *s)
1643 MatroskaMuxContext *mkv = s->priv_data;
1644 AVIOContext *pb = s->pb;
1645 int64_t currentpos, cuespos;
1648 // check if we have an audio packet cached
1649 if (mkv->cur_audio_pkt.size > 0) {
1650 ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
1651 av_packet_unref(&mkv->cur_audio_pkt);
1653 av_log(s, AV_LOG_ERROR,
1654 "Could not write cached audio packet ret:%d\n", ret);
1660 end_ebml_master(mkv->dyn_bc, mkv->cluster);
1661 mkv_flush_dynbuf(s);
1662 } else if (mkv->cluster_pos) {
1663 end_ebml_master(pb, mkv->cluster);
1666 if (mkv->mode != MODE_WEBM) {
1667 ret = mkv_write_chapters(s);
1673 if (mkv->cues->num_entries) {
1674 if (mkv->reserve_cues_space) {
1677 currentpos = avio_tell(pb);
1678 avio_seek(pb, mkv->cues_pos, SEEK_SET);
1680 cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
1681 cues_end = avio_tell(pb);
1682 if (cues_end > cuespos + mkv->reserve_cues_space) {
1683 av_log(s, AV_LOG_ERROR,
1684 "Insufficient space reserved for cues: %d "
1685 "(needed: %" PRId64 ").\n",
1686 mkv->reserve_cues_space, cues_end - cuespos);
1687 return AVERROR(EINVAL);
1690 if (cues_end < cuespos + mkv->reserve_cues_space)
1691 put_ebml_void(pb, mkv->reserve_cues_space -
1692 (cues_end - cuespos));
1694 avio_seek(pb, currentpos, SEEK_SET);
1696 cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
1699 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CUES,
1705 mkv_write_seekhead(pb, mkv->main_seekhead);
1707 // update the duration
1708 av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
1709 currentpos = avio_tell(pb);
1710 avio_seek(pb, mkv->duration_offset, SEEK_SET);
1711 put_ebml_float(pb, MATROSKA_ID_DURATION, mkv->duration);
1713 avio_seek(pb, currentpos, SEEK_SET);
1716 end_ebml_master(pb, mkv->segment);
1717 av_free(mkv->tracks);
1718 av_freep(&mkv->cues->entries);
1719 av_freep(&mkv->cues);
1724 static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
1727 for (i = 0; ff_mkv_codec_tags[i].id != AV_CODEC_ID_NONE; i++)
1728 if (ff_mkv_codec_tags[i].id == codec_id)
1731 if (std_compliance < FF_COMPLIANCE_NORMAL) {
1732 enum AVMediaType type = avcodec_get_type(codec_id);
1733 // mkv theoretically supports any video/audio through VFW/ACM
1734 if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)
1741 #define OFFSET(x) offsetof(MatroskaMuxContext, x)
1742 #define FLAGS AV_OPT_FLAG_ENCODING_PARAM
1743 static const AVOption options[] = {
1744 { "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 },
1745 { "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 },
1746 { "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 },
1750 #if CONFIG_MATROSKA_MUXER
1751 static const AVClass matroska_class = {
1752 .class_name = "matroska muxer",
1753 .item_name = av_default_item_name,
1755 .version = LIBAVUTIL_VERSION_INT,
1758 AVOutputFormat ff_matroska_muxer = {
1760 .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
1761 .mime_type = "video/x-matroska",
1762 .extensions = "mkv",
1763 .priv_data_size = sizeof(MatroskaMuxContext),
1764 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
1765 AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
1766 .video_codec = CONFIG_LIBX264_ENCODER ?
1767 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
1768 .write_header = mkv_write_header,
1769 .write_packet = mkv_write_flush_packet,
1770 .write_trailer = mkv_write_trailer,
1771 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
1772 AVFMT_TS_NONSTRICT | AVFMT_ALLOW_FLUSH,
1773 .codec_tag = (const AVCodecTag* const []){
1774 ff_codec_bmp_tags, ff_codec_wav_tags, 0
1776 .subtitle_codec = AV_CODEC_ID_SSA,
1777 .query_codec = mkv_query_codec,
1778 .priv_class = &matroska_class,
1782 #if CONFIG_WEBM_MUXER
1783 static const AVClass webm_class = {
1784 .class_name = "webm muxer",
1785 .item_name = av_default_item_name,
1787 .version = LIBAVUTIL_VERSION_INT,
1790 AVOutputFormat ff_webm_muxer = {
1792 .long_name = NULL_IF_CONFIG_SMALL("WebM"),
1793 .mime_type = "video/webm",
1794 .extensions = "webm",
1795 .priv_data_size = sizeof(MatroskaMuxContext),
1796 .audio_codec = CONFIG_LIBOPUS_ENCODER ? AV_CODEC_ID_OPUS : AV_CODEC_ID_VORBIS,
1797 .video_codec = CONFIG_LIBVPX_VP9_ENCODER? AV_CODEC_ID_VP9 : AV_CODEC_ID_VP8,
1798 .write_header = mkv_write_header,
1799 .write_packet = mkv_write_flush_packet,
1800 .write_trailer = mkv_write_trailer,
1801 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
1802 AVFMT_TS_NONSTRICT | AVFMT_ALLOW_FLUSH,
1803 .priv_class = &webm_class,
1807 #if CONFIG_MATROSKA_AUDIO_MUXER
1808 static const AVClass mka_class = {
1809 .class_name = "matroska audio muxer",
1810 .item_name = av_default_item_name,
1812 .version = LIBAVUTIL_VERSION_INT,
1814 AVOutputFormat ff_matroska_audio_muxer = {
1816 .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
1817 .mime_type = "audio/x-matroska",
1818 .extensions = "mka",
1819 .priv_data_size = sizeof(MatroskaMuxContext),
1820 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
1821 AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
1822 .video_codec = AV_CODEC_ID_NONE,
1823 .write_header = mkv_write_header,
1824 .write_packet = mkv_write_flush_packet,
1825 .write_trailer = mkv_write_trailer,
1826 .flags = AVFMT_GLOBALHEADER | AVFMT_TS_NONSTRICT |
1828 .codec_tag = (const AVCodecTag* const []){ ff_codec_wav_tags, 0 },
1829 .priv_class = &mka_class,