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"
49 #include "libavutil/stereo3d.h"
51 #include "libavcodec/xiph.h"
52 #include "libavcodec/mpeg4audio.h"
53 #include "libavcodec/internal.h"
55 typedef struct ebml_master {
56 int64_t pos; ///< absolute offset in the file where the master's elements start
57 int sizebytes; ///< how many bytes were reserved for the size
60 typedef struct mkv_seekhead_entry {
61 unsigned int elementid;
65 typedef struct mkv_seekhead {
67 int64_t segment_offset; ///< the file offset to the beginning of the segment
68 int reserved_size; ///< -1 if appending to file
70 mkv_seekhead_entry *entries;
74 typedef struct mkv_cuepoint {
78 int64_t cluster_pos; ///< file offset of the cluster containing the block
79 int64_t relative_pos; ///< relative offset from the position of the cluster containing the block
80 int64_t duration; ///< duration of the block according to time base
83 typedef struct mkv_cues {
84 int64_t segment_offset;
85 mkv_cuepoint *entries;
89 typedef struct mkv_track {
95 #define MODE_MATROSKAv2 0x01
96 #define MODE_WEBM 0x02
98 /** Maximum number of tracks allowed in a Matroska file (with track numbers in
99 * range 1 to 126 (inclusive) */
100 #define MAX_TRACKS 126
102 typedef struct MatroskaMuxContext {
103 const AVClass *class;
107 int64_t segment_offset;
109 int64_t cluster_pos; ///< file offset of the current cluster
111 int64_t duration_offset;
113 mkv_seekhead *main_seekhead;
117 AVPacket cur_audio_pkt;
119 int have_attachments;
121 int reserve_cues_space;
122 int cluster_size_limit;
124 int64_t cluster_time_limit;
126 int dash_track_number;
129 uint32_t chapter_id_offset;
132 int64_t last_track_timestamp[MAX_TRACKS];
135 } MatroskaMuxContext;
138 /** 2 bytes * 3 for EBML IDs, 3 1-byte EBML lengths, 8 bytes for 64 bit
139 * offset, 4 bytes for target EBML ID */
140 #define MAX_SEEKENTRY_SIZE 21
142 /** per-cuepoint-track - 5 1-byte EBML IDs, 5 1-byte EBML sizes, 4
144 #define MAX_CUETRACKPOS_SIZE 42
146 /** per-cuepoint - 2 1-byte EBML IDs, 2 1-byte EBML sizes, 8-byte uint max */
147 #define MAX_CUEPOINT_SIZE(num_tracks) 12 + MAX_CUETRACKPOS_SIZE * num_tracks
149 /** Seek preroll value for opus */
150 #define OPUS_SEEK_PREROLL 80000000
152 static int ebml_id_size(unsigned int id)
154 return (av_log2(id + 1) - 1) / 7 + 1;
157 static void put_ebml_id(AVIOContext *pb, unsigned int id)
159 int i = ebml_id_size(id);
161 avio_w8(pb, (uint8_t)(id >> (i * 8)));
165 * Write an EBML size meaning "unknown size".
167 * @param bytes The number of bytes the size should occupy (maximum: 8).
169 static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
171 av_assert0(bytes <= 8);
172 avio_w8(pb, 0x1ff >> bytes);
173 ffio_fill(pb, 0xff, bytes - 1);
177 * Calculate how many bytes are needed to represent a given number in EBML.
179 static int ebml_num_size(uint64_t num)
182 while ((num + 1) >> bytes * 7)
188 * Write a number in EBML variable length format.
190 * @param bytes The number of bytes that need to be used to write the number.
191 * If zero, any number of bytes can be used.
193 static void put_ebml_num(AVIOContext *pb, uint64_t num, int bytes)
195 int i, needed_bytes = ebml_num_size(num);
197 // sizes larger than this are currently undefined in EBML
198 av_assert0(num < (1ULL << 56) - 1);
201 // don't care how many bytes are used, so use the min
202 bytes = needed_bytes;
203 // the bytes needed to write the given size would exceed the bytes
204 // that we need to use, so write unknown size. This shouldn't happen.
205 av_assert0(bytes >= needed_bytes);
207 num |= 1ULL << bytes * 7;
208 for (i = bytes - 1; i >= 0; i--)
209 avio_w8(pb, (uint8_t)(num >> i * 8));
212 static void put_ebml_uint(AVIOContext *pb, unsigned int elementid, uint64_t val)
219 put_ebml_id(pb, elementid);
220 put_ebml_num(pb, bytes, 0);
221 for (i = bytes - 1; i >= 0; i--)
222 avio_w8(pb, (uint8_t)(val >> i * 8));
225 static void put_ebml_sint(AVIOContext *pb, unsigned int elementid, int64_t val)
228 uint64_t tmp = 2*(val < 0 ? val^-1 : val);
230 while (tmp>>=8) bytes++;
232 put_ebml_id(pb, elementid);
233 put_ebml_num(pb, bytes, 0);
234 for (i = bytes - 1; i >= 0; i--)
235 avio_w8(pb, (uint8_t)(val >> i * 8));
238 static void put_ebml_float(AVIOContext *pb, unsigned int elementid, double val)
240 put_ebml_id(pb, elementid);
241 put_ebml_num(pb, 8, 0);
242 avio_wb64(pb, av_double2int(val));
245 static void put_ebml_binary(AVIOContext *pb, unsigned int elementid,
246 const void *buf, int size)
248 put_ebml_id(pb, elementid);
249 put_ebml_num(pb, size, 0);
250 avio_write(pb, buf, size);
253 static void put_ebml_string(AVIOContext *pb, unsigned int elementid,
256 put_ebml_binary(pb, elementid, str, strlen(str));
260 * Write a void element of a given size. Useful for reserving space in
261 * the file to be written to later.
263 * @param size The number of bytes to reserve, which must be at least 2.
265 static void put_ebml_void(AVIOContext *pb, uint64_t size)
267 int64_t currentpos = avio_tell(pb);
269 av_assert0(size >= 2);
271 put_ebml_id(pb, EBML_ID_VOID);
272 // we need to subtract the length needed to store the size from the
273 // size we need to reserve so 2 cases, we use 8 bytes to store the
274 // size if possible, 1 byte otherwise
276 put_ebml_num(pb, size - 1, 0);
278 put_ebml_num(pb, size - 9, 8);
279 ffio_fill(pb, 0, currentpos + size - avio_tell(pb));
282 static ebml_master start_ebml_master(AVIOContext *pb, unsigned int elementid,
283 uint64_t expectedsize)
285 int bytes = expectedsize ? ebml_num_size(expectedsize) : 8;
286 put_ebml_id(pb, elementid);
287 put_ebml_size_unknown(pb, bytes);
288 return (ebml_master) {avio_tell(pb), bytes };
291 static void end_ebml_master(AVIOContext *pb, ebml_master master)
293 int64_t pos = avio_tell(pb);
295 if (avio_seek(pb, master.pos - master.sizebytes, SEEK_SET) < 0)
297 put_ebml_num(pb, pos - master.pos, master.sizebytes);
298 avio_seek(pb, pos, SEEK_SET);
301 static void put_xiph_size(AVIOContext *pb, int size)
303 ffio_fill(pb, 255, size / 255);
304 avio_w8(pb, size % 255);
308 * Initialize a mkv_seekhead element to be ready to index level 1 Matroska
309 * elements. If a maximum number of elements is specified, enough space
310 * will be reserved at the current file location to write a seek head of
313 * @param segment_offset The absolute offset to the position in the file
314 * where the segment begins.
315 * @param numelements The maximum number of elements that will be indexed
316 * by this seek head, 0 if unlimited.
318 static mkv_seekhead *mkv_start_seekhead(AVIOContext *pb, int64_t segment_offset,
321 mkv_seekhead *new_seekhead = av_mallocz(sizeof(mkv_seekhead));
325 new_seekhead->segment_offset = segment_offset;
327 if (numelements > 0) {
328 new_seekhead->filepos = avio_tell(pb);
329 // 21 bytes max for a seek entry, 10 bytes max for the SeekHead ID
330 // and size, and 3 bytes to guarantee that an EBML void element
331 // will fit afterwards
332 new_seekhead->reserved_size = numelements * MAX_SEEKENTRY_SIZE + 13;
333 new_seekhead->max_entries = numelements;
334 put_ebml_void(pb, new_seekhead->reserved_size);
339 static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
341 mkv_seekhead_entry *entries = seekhead->entries;
343 // don't store more elements than we reserved space for
344 if (seekhead->max_entries > 0 && seekhead->max_entries <= seekhead->num_entries)
347 entries = av_realloc_array(entries, seekhead->num_entries + 1, sizeof(mkv_seekhead_entry));
349 return AVERROR(ENOMEM);
350 seekhead->entries = entries;
352 seekhead->entries[seekhead->num_entries].elementid = elementid;
353 seekhead->entries[seekhead->num_entries++].segmentpos = filepos - seekhead->segment_offset;
359 * Write the seek head to the file and free it. If a maximum number of
360 * elements was specified to mkv_start_seekhead(), the seek head will
361 * be written at the location reserved for it. Otherwise, it is written
362 * at the current location in the file.
364 * @return The file offset where the seekhead was written,
365 * -1 if an error occurred.
367 static int64_t mkv_write_seekhead(AVIOContext *pb, mkv_seekhead *seekhead)
369 ebml_master metaseek, seekentry;
373 currentpos = avio_tell(pb);
375 if (seekhead->reserved_size > 0) {
376 if (avio_seek(pb, seekhead->filepos, SEEK_SET) < 0) {
382 metaseek = start_ebml_master(pb, MATROSKA_ID_SEEKHEAD, seekhead->reserved_size);
383 for (i = 0; i < seekhead->num_entries; i++) {
384 mkv_seekhead_entry *entry = &seekhead->entries[i];
386 seekentry = start_ebml_master(pb, MATROSKA_ID_SEEKENTRY, MAX_SEEKENTRY_SIZE);
388 put_ebml_id(pb, MATROSKA_ID_SEEKID);
389 put_ebml_num(pb, ebml_id_size(entry->elementid), 0);
390 put_ebml_id(pb, entry->elementid);
392 put_ebml_uint(pb, MATROSKA_ID_SEEKPOSITION, entry->segmentpos);
393 end_ebml_master(pb, seekentry);
395 end_ebml_master(pb, metaseek);
397 if (seekhead->reserved_size > 0) {
398 uint64_t remaining = seekhead->filepos + seekhead->reserved_size - avio_tell(pb);
399 put_ebml_void(pb, remaining);
400 avio_seek(pb, currentpos, SEEK_SET);
402 currentpos = seekhead->filepos;
405 av_freep(&seekhead->entries);
411 static mkv_cues *mkv_start_cues(int64_t segment_offset)
413 mkv_cues *cues = av_mallocz(sizeof(mkv_cues));
417 cues->segment_offset = segment_offset;
421 static int mkv_add_cuepoint(mkv_cues *cues, int stream, int tracknum, int64_t ts,
422 int64_t cluster_pos, int64_t relative_pos, int64_t duration)
424 mkv_cuepoint *entries = cues->entries;
429 entries = av_realloc_array(entries, cues->num_entries + 1, sizeof(mkv_cuepoint));
431 return AVERROR(ENOMEM);
432 cues->entries = entries;
434 cues->entries[cues->num_entries].pts = ts;
435 cues->entries[cues->num_entries].stream_idx = stream;
436 cues->entries[cues->num_entries].tracknum = tracknum;
437 cues->entries[cues->num_entries].cluster_pos = cluster_pos - cues->segment_offset;
438 cues->entries[cues->num_entries].relative_pos = relative_pos;
439 cues->entries[cues->num_entries++].duration = duration;
444 static int64_t mkv_write_cues(AVFormatContext *s, mkv_cues *cues, mkv_track *tracks, int num_tracks)
446 AVIOContext *pb = s->pb;
447 ebml_master cues_element;
451 currentpos = avio_tell(pb);
452 cues_element = start_ebml_master(pb, MATROSKA_ID_CUES, 0);
454 for (i = 0; i < cues->num_entries; i++) {
455 ebml_master cuepoint, track_positions;
456 mkv_cuepoint *entry = &cues->entries[i];
457 uint64_t pts = entry->pts;
460 // Calculate the number of entries, so we know the element size
461 for (j = 0; j < num_tracks; j++)
462 tracks[j].has_cue = 0;
463 for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
464 int tracknum = entry[j].stream_idx;
465 av_assert0(tracknum>=0 && tracknum<num_tracks);
466 if (tracks[tracknum].has_cue && s->streams[tracknum]->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
468 tracks[tracknum].has_cue = 1;
472 cuepoint = start_ebml_master(pb, MATROSKA_ID_POINTENTRY, MAX_CUEPOINT_SIZE(ctp_nb));
473 put_ebml_uint(pb, MATROSKA_ID_CUETIME, pts);
475 // put all the entries from different tracks that have the exact same
476 // timestamp into the same CuePoint
477 for (j = 0; j < num_tracks; j++)
478 tracks[j].has_cue = 0;
479 for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
480 int tracknum = entry[j].stream_idx;
481 av_assert0(tracknum>=0 && tracknum<num_tracks);
482 if (tracks[tracknum].has_cue && s->streams[tracknum]->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
484 tracks[tracknum].has_cue = 1;
485 track_positions = start_ebml_master(pb, MATROSKA_ID_CUETRACKPOSITION, MAX_CUETRACKPOS_SIZE);
486 put_ebml_uint(pb, MATROSKA_ID_CUETRACK , entry[j].tracknum );
487 put_ebml_uint(pb, MATROSKA_ID_CUECLUSTERPOSITION , entry[j].cluster_pos);
488 put_ebml_uint(pb, MATROSKA_ID_CUERELATIVEPOSITION, entry[j].relative_pos);
489 if (entry[j].duration != -1)
490 put_ebml_uint(pb, MATROSKA_ID_CUEDURATION , entry[j].duration);
491 end_ebml_master(pb, track_positions);
494 end_ebml_master(pb, cuepoint);
496 end_ebml_master(pb, cues_element);
501 static int put_xiph_codecpriv(AVFormatContext *s, AVIOContext *pb, AVCodecContext *codec)
503 const uint8_t *header_start[3];
505 int first_header_size;
508 if (codec->codec_id == AV_CODEC_ID_VORBIS)
509 first_header_size = 30;
511 first_header_size = 42;
513 if (avpriv_split_xiph_headers(codec->extradata, codec->extradata_size,
514 first_header_size, header_start, header_len) < 0) {
515 av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
519 avio_w8(pb, 2); // number packets - 1
520 for (j = 0; j < 2; j++) {
521 put_xiph_size(pb, header_len[j]);
523 for (j = 0; j < 3; j++)
524 avio_write(pb, header_start[j], header_len[j]);
529 static int put_wv_codecpriv(AVIOContext *pb, AVCodecContext *codec)
531 if (codec->extradata && codec->extradata_size == 2)
532 avio_write(pb, codec->extradata, 2);
534 avio_wl16(pb, 0x403); // fallback to the version mentioned in matroska specs
538 static int put_flac_codecpriv(AVFormatContext *s,
539 AVIOContext *pb, AVCodecContext *codec)
541 int write_comment = (codec->channel_layout &&
542 !(codec->channel_layout & ~0x3ffffULL) &&
543 !ff_flac_is_native_layout(codec->channel_layout));
544 int ret = ff_flac_write_header(pb, codec->extradata, codec->extradata_size,
551 const char *vendor = (s->flags & AVFMT_FLAG_BITEXACT) ?
552 "Lavf" : LIBAVFORMAT_IDENT;
553 AVDictionary *dict = NULL;
554 uint8_t buf[32], *data, *p;
557 snprintf(buf, sizeof(buf), "0x%"PRIx64, codec->channel_layout);
558 av_dict_set(&dict, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", buf, 0);
560 len = ff_vorbiscomment_length(dict, vendor);
561 if (len >= ((1<<24) - 4))
562 return AVERROR(EINVAL);
564 data = av_malloc(len + 4);
567 return AVERROR(ENOMEM);
571 AV_WB24(data + 1, len);
574 ff_vorbiscomment_write(&p, &dict, vendor);
576 avio_write(pb, data, len + 4);
585 static int get_aac_sample_rates(AVFormatContext *s, AVCodecContext *codec,
586 int *sample_rate, int *output_sample_rate)
588 MPEG4AudioConfig mp4ac;
590 if (avpriv_mpeg4audio_get_config(&mp4ac, codec->extradata,
591 codec->extradata_size * 8, 1) < 0) {
592 av_log(s, AV_LOG_ERROR,
593 "Error parsing AAC extradata, unable to determine samplerate.\n");
594 return AVERROR(EINVAL);
597 *sample_rate = mp4ac.sample_rate;
598 *output_sample_rate = mp4ac.ext_sample_rate;
602 static int mkv_write_native_codecprivate(AVFormatContext *s,
603 AVCodecContext *codec,
606 switch (codec->codec_id) {
607 case AV_CODEC_ID_VORBIS:
608 case AV_CODEC_ID_THEORA:
609 return put_xiph_codecpriv(s, dyn_cp, codec);
610 case AV_CODEC_ID_FLAC:
611 return put_flac_codecpriv(s, dyn_cp, codec);
612 case AV_CODEC_ID_WAVPACK:
613 return put_wv_codecpriv(dyn_cp, codec);
614 case AV_CODEC_ID_H264:
615 return ff_isom_write_avcc(dyn_cp, codec->extradata,
616 codec->extradata_size);
617 case AV_CODEC_ID_HEVC:
618 ff_isom_write_hvcc(dyn_cp, codec->extradata,
619 codec->extradata_size, 0);
621 case AV_CODEC_ID_ALAC:
622 if (codec->extradata_size < 36) {
623 av_log(s, AV_LOG_ERROR,
624 "Invalid extradata found, ALAC expects a 36-byte "
626 return AVERROR_INVALIDDATA;
628 avio_write(dyn_cp, codec->extradata + 12,
629 codec->extradata_size - 12);
632 if (codec->codec_id == AV_CODEC_ID_PRORES &&
633 ff_codec_get_id(ff_codec_movvideo_tags, codec->codec_tag) == AV_CODEC_ID_PRORES) {
634 avio_wl32(dyn_cp, codec->codec_tag);
635 } else if (codec->extradata_size && codec->codec_id != AV_CODEC_ID_TTA)
636 avio_write(dyn_cp, codec->extradata, codec->extradata_size);
642 static int mkv_write_codecprivate(AVFormatContext *s, AVIOContext *pb,
643 AVCodecContext *codec, int native_id,
648 int ret, codecpriv_size;
650 ret = avio_open_dyn_buf(&dyn_cp);
655 ret = mkv_write_native_codecprivate(s, codec, dyn_cp);
656 } else if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
658 if (!codec->codec_tag)
659 codec->codec_tag = ff_codec_get_tag(ff_codec_movvideo_tags,
661 if (codec->extradata_size) {
662 if ( ff_codec_get_id(ff_codec_movvideo_tags, codec->codec_tag) == codec->codec_id
663 && ff_codec_get_id(ff_codec_movvideo_tags, AV_RL32(codec->extradata + 4)) != codec->codec_id
666 avio_wb32(dyn_cp, 0x5a + codec->extradata_size);
667 avio_wl32(dyn_cp, codec->codec_tag);
668 for(i = 0; i < 0x5a - 8; i++)
671 avio_write(dyn_cp, codec->extradata, codec->extradata_size);
674 if (!ff_codec_get_tag(ff_codec_bmp_tags, codec->codec_id))
675 av_log(s, AV_LOG_WARNING, "codec %s is not supported by this format\n",
676 avcodec_get_name(codec->codec_id));
678 if (!codec->codec_tag)
679 codec->codec_tag = ff_codec_get_tag(ff_codec_bmp_tags,
681 if (!codec->codec_tag && codec->codec_id != AV_CODEC_ID_RAWVIDEO) {
682 av_log(s, AV_LOG_ERROR, "No bmp codec tag found for codec %s\n",
683 avcodec_get_name(codec->codec_id));
684 ret = AVERROR(EINVAL);
687 ff_put_bmp_header(dyn_cp, codec, ff_codec_bmp_tags, 0, 0);
689 } else if (codec->codec_type == AVMEDIA_TYPE_AUDIO) {
691 tag = ff_codec_get_tag(ff_codec_wav_tags, codec->codec_id);
693 av_log(s, AV_LOG_ERROR, "No wav codec tag found for codec %s\n",
694 avcodec_get_name(codec->codec_id));
695 ret = AVERROR(EINVAL);
697 if (!codec->codec_tag)
698 codec->codec_tag = tag;
700 ff_put_wav_header(dyn_cp, codec, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX);
703 codecpriv_size = avio_close_dyn_buf(dyn_cp, &codecpriv);
705 put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codecpriv,
712 static int mkv_write_stereo_mode(AVFormatContext *s, AVIOContext *pb,
713 AVStream *st, int mode, int *h_width, int *h_height)
717 AVDictionaryEntry *tag;
718 MatroskaVideoStereoModeType format = MATROSKA_VIDEO_STEREOMODE_TYPE_NB;
722 // convert metadata into proper side data and add it to the stream
723 if ((tag = av_dict_get(st->metadata, "stereo_mode", NULL, 0)) ||
724 (tag = av_dict_get( s->metadata, "stereo_mode", NULL, 0))) {
725 int stereo_mode = atoi(tag->value);
727 for (i=0; i<MATROSKA_VIDEO_STEREOMODE_TYPE_NB; i++)
728 if (!strcmp(tag->value, ff_matroska_video_stereo_mode[i])){
733 if (stereo_mode < MATROSKA_VIDEO_STEREOMODE_TYPE_NB &&
734 stereo_mode != 10 && stereo_mode != 12) {
735 int ret = ff_mkv_stereo3d_conv(st, stereo_mode);
741 // iterate to find the stereo3d side data
742 for (i = 0; i < st->nb_side_data; i++) {
743 AVPacketSideData sd = st->side_data[i];
744 if (sd.type == AV_PKT_DATA_STEREO3D) {
745 AVStereo3D *stereo = (AVStereo3D *)sd.data;
747 switch (stereo->type) {
749 format = MATROSKA_VIDEO_STEREOMODE_TYPE_MONO;
751 case AV_STEREO3D_SIDEBYSIDE:
752 format = (stereo->flags & AV_STEREO3D_FLAG_INVERT)
753 ? MATROSKA_VIDEO_STEREOMODE_TYPE_RIGHT_LEFT
754 : MATROSKA_VIDEO_STEREOMODE_TYPE_LEFT_RIGHT;
757 case AV_STEREO3D_TOPBOTTOM:
758 format = MATROSKA_VIDEO_STEREOMODE_TYPE_TOP_BOTTOM;
759 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
763 case AV_STEREO3D_CHECKERBOARD:
764 format = MATROSKA_VIDEO_STEREOMODE_TYPE_CHECKERBOARD_LR;
765 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
768 case AV_STEREO3D_LINES:
769 format = MATROSKA_VIDEO_STEREOMODE_TYPE_ROW_INTERLEAVED_LR;
770 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
774 case AV_STEREO3D_COLUMNS:
775 format = MATROSKA_VIDEO_STEREOMODE_TYPE_COL_INTERLEAVED_LR;
776 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
780 case AV_STEREO3D_FRAMESEQUENCE:
781 format = MATROSKA_VIDEO_STEREOMODE_TYPE_BOTH_EYES_BLOCK_LR;
782 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
790 if (format == MATROSKA_VIDEO_STEREOMODE_TYPE_NB)
793 // if webm, do not write unsupported modes
794 if ((mode == MODE_WEBM &&
795 format > MATROSKA_VIDEO_STEREOMODE_TYPE_TOP_BOTTOM &&
796 format != MATROSKA_VIDEO_STEREOMODE_TYPE_RIGHT_LEFT)
797 || format >= MATROSKA_VIDEO_STEREOMODE_TYPE_NB) {
798 av_log(s, AV_LOG_ERROR,
799 "The specified stereo mode is not valid.\n");
800 format = MATROSKA_VIDEO_STEREOMODE_TYPE_NB;
801 return AVERROR(EINVAL);
804 // write StereoMode if format is valid
805 put_ebml_uint(pb, MATROSKA_ID_VIDEOSTEREOMODE, format);
810 static int mkv_write_track(AVFormatContext *s, MatroskaMuxContext *mkv,
811 int i, AVIOContext *pb, int default_stream_exists)
813 AVStream *st = s->streams[i];
814 AVCodecContext *codec = st->codec;
815 ebml_master subinfo, track;
818 int bit_depth = av_get_bits_per_sample(codec->codec_id);
819 int sample_rate = codec->sample_rate;
820 int output_sample_rate = 0;
821 int display_width_div = 1;
822 int display_height_div = 1;
824 AVDictionaryEntry *tag;
826 // ms precision is the de-facto standard timescale for mkv files
827 avpriv_set_pts_info(st, 64, 1, 1000);
829 if (codec->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
830 mkv->have_attachments = 1;
834 if (!bit_depth && codec->codec_id != AV_CODEC_ID_ADPCM_G726)
835 bit_depth = av_get_bytes_per_sample(codec->sample_fmt) << 3;
837 bit_depth = codec->bits_per_coded_sample;
839 if (codec->codec_id == AV_CODEC_ID_AAC) {
840 ret = get_aac_sample_rates(s, codec, &sample_rate, &output_sample_rate);
845 track = start_ebml_master(pb, MATROSKA_ID_TRACKENTRY, 0);
846 put_ebml_uint (pb, MATROSKA_ID_TRACKNUMBER,
847 mkv->is_dash ? mkv->dash_track_number : i + 1);
848 put_ebml_uint (pb, MATROSKA_ID_TRACKUID,
849 mkv->is_dash ? mkv->dash_track_number : i + 1);
850 put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0); // no lacing (yet)
852 if ((tag = av_dict_get(st->metadata, "title", NULL, 0)))
853 put_ebml_string(pb, MATROSKA_ID_TRACKNAME, tag->value);
854 tag = av_dict_get(st->metadata, "language", NULL, 0);
855 if (mkv->mode != MODE_WEBM || codec->codec_id != AV_CODEC_ID_WEBVTT) {
856 put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag && tag->value ? tag->value:"und");
857 } else if (tag && tag->value) {
858 put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag->value);
861 // The default value for TRACKFLAGDEFAULT is 1, so add element
862 // if we need to clear it.
863 if (default_stream_exists && !(st->disposition & AV_DISPOSITION_DEFAULT))
864 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGDEFAULT, !!(st->disposition & AV_DISPOSITION_DEFAULT));
866 if (st->disposition & AV_DISPOSITION_FORCED)
867 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGFORCED, 1);
869 if (mkv->mode == MODE_WEBM && codec->codec_id == AV_CODEC_ID_WEBVTT) {
870 const char *codec_id;
871 if (st->disposition & AV_DISPOSITION_CAPTIONS) {
872 codec_id = "D_WEBVTT/CAPTIONS";
873 native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
874 } else if (st->disposition & AV_DISPOSITION_DESCRIPTIONS) {
875 codec_id = "D_WEBVTT/DESCRIPTIONS";
876 native_id = MATROSKA_TRACK_TYPE_METADATA;
877 } else if (st->disposition & AV_DISPOSITION_METADATA) {
878 codec_id = "D_WEBVTT/METADATA";
879 native_id = MATROSKA_TRACK_TYPE_METADATA;
881 codec_id = "D_WEBVTT/SUBTITLES";
882 native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
884 put_ebml_string(pb, MATROSKA_ID_CODECID, codec_id);
886 // look for a codec ID string specific to mkv to use,
887 // if none are found, use AVI codes
888 for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
889 if (ff_mkv_codec_tags[j].id == codec->codec_id) {
890 put_ebml_string(pb, MATROSKA_ID_CODECID, ff_mkv_codec_tags[j].str);
895 if (codec->codec_id == AV_CODEC_ID_RAWVIDEO && !codec->codec_tag) {
896 if (mkv->allow_raw_vfw) {
899 av_log(s, AV_LOG_ERROR, "Raw RGB is not supported Natively in Matroska, you can use AVI or NUT or\n"
900 "If you would like to store it anyway using VFW mode, enable allow_raw_vfw (-allow_raw_vfw 1)\n");
901 return AVERROR(EINVAL);
906 if (codec->codec_type == AVMEDIA_TYPE_AUDIO && codec->initial_padding && codec->codec_id == AV_CODEC_ID_OPUS) {
907 // mkv->tracks[i].ts_offset = av_rescale_q(codec->initial_padding,
908 // (AVRational){ 1, codec->sample_rate },
911 put_ebml_uint(pb, MATROSKA_ID_CODECDELAY,
912 av_rescale_q(codec->initial_padding,
913 (AVRational){ 1, codec->sample_rate },
914 (AVRational){ 1, 1000000000 }));
916 if (codec->codec_id == AV_CODEC_ID_OPUS) {
917 put_ebml_uint(pb, MATROSKA_ID_SEEKPREROLL, OPUS_SEEK_PREROLL);
920 if (mkv->mode == MODE_WEBM && !(codec->codec_id == AV_CODEC_ID_VP8 ||
921 codec->codec_id == AV_CODEC_ID_VP9 ||
922 codec->codec_id == AV_CODEC_ID_OPUS ||
923 codec->codec_id == AV_CODEC_ID_VORBIS ||
924 codec->codec_id == AV_CODEC_ID_WEBVTT)) {
925 av_log(s, AV_LOG_ERROR,
926 "Only VP8 or VP9 video and Vorbis or Opus audio and WebVTT subtitles are supported for WebM.\n");
927 return AVERROR(EINVAL);
930 switch (codec->codec_type) {
931 case AVMEDIA_TYPE_VIDEO:
932 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_VIDEO);
934 if( st->avg_frame_rate.num > 0 && st->avg_frame_rate.den > 0
935 && av_cmp_q(av_inv_q(st->avg_frame_rate), codec->time_base) > 0)
936 put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, 1000000000LL * st->avg_frame_rate.den / st->avg_frame_rate.num);
938 put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, 1000000000LL * codec->time_base.num / codec->time_base.den);
941 ff_codec_get_tag(ff_codec_movvideo_tags, codec->codec_id) &&
942 ((!ff_codec_get_tag(ff_codec_bmp_tags, codec->codec_id) && codec->codec_id != AV_CODEC_ID_RAWVIDEO) ||
943 codec->codec_id == AV_CODEC_ID_SVQ1 ||
944 codec->codec_id == AV_CODEC_ID_SVQ3 ||
945 codec->codec_id == AV_CODEC_ID_CINEPAK))
949 put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");
950 else if (!native_id) {
951 // if there is no mkv-specific codec ID, use VFW mode
952 put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");
953 mkv->tracks[i].write_dts = 1;
954 s->internal->avoid_negative_ts_use_pts = 0;
957 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
958 // XXX: interlace flag?
959 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , codec->width);
960 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, codec->height);
962 // check both side data and metadata for stereo information,
963 // write the result to the bitstream if any is found
964 ret = mkv_write_stereo_mode(s, pb, st, mkv->mode,
966 &display_height_div);
970 if (((tag = av_dict_get(st->metadata, "alpha_mode", NULL, 0)) && atoi(tag->value)) ||
971 ((tag = av_dict_get( s->metadata, "alpha_mode", NULL, 0)) && atoi(tag->value)) ||
972 (codec->pix_fmt == AV_PIX_FMT_YUVA420P)) {
973 put_ebml_uint(pb, MATROSKA_ID_VIDEOALPHAMODE, 1);
976 // write DisplayWidth and DisplayHeight, they contain the size of
977 // a single source view and/or the display aspect ratio
978 if (st->sample_aspect_ratio.num) {
979 int64_t d_width = av_rescale(codec->width, st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
980 if (d_width > INT_MAX) {
981 av_log(s, AV_LOG_ERROR, "Overflow in display width\n");
982 return AVERROR(EINVAL);
984 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , d_width / display_width_div);
985 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, codec->height / display_height_div);
986 } else if (display_width_div != 1 || display_height_div != 1) {
987 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , codec->width / display_width_div);
988 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, codec->height / display_height_div);
991 if (codec->codec_id == AV_CODEC_ID_RAWVIDEO) {
992 uint32_t color_space = av_le2ne32(codec->codec_tag);
993 put_ebml_binary(pb, MATROSKA_ID_VIDEOCOLORSPACE, &color_space, sizeof(color_space));
996 end_ebml_master(pb, subinfo);
999 case AVMEDIA_TYPE_AUDIO:
1000 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_AUDIO);
1003 // no mkv-specific ID, use ACM mode
1004 put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");
1006 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);
1007 put_ebml_uint (pb, MATROSKA_ID_AUDIOCHANNELS , codec->channels);
1008 put_ebml_float (pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, sample_rate);
1009 if (output_sample_rate)
1010 put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
1012 put_ebml_uint(pb, MATROSKA_ID_AUDIOBITDEPTH, bit_depth);
1013 end_ebml_master(pb, subinfo);
1016 case AVMEDIA_TYPE_SUBTITLE:
1018 av_log(s, AV_LOG_ERROR, "Subtitle codec %d is not supported.\n", codec->codec_id);
1019 return AVERROR(ENOSYS);
1022 if (mkv->mode != MODE_WEBM || codec->codec_id != AV_CODEC_ID_WEBVTT)
1023 native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
1025 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, native_id);
1028 av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.\n");
1029 return AVERROR(EINVAL);
1032 if (mkv->mode != MODE_WEBM || codec->codec_id != AV_CODEC_ID_WEBVTT) {
1033 ret = mkv_write_codecprivate(s, pb, codec, native_id, qt_id);
1038 end_ebml_master(pb, track);
1043 static int mkv_write_tracks(AVFormatContext *s)
1045 MatroskaMuxContext *mkv = s->priv_data;
1046 AVIOContext *pb = s->pb;
1048 int i, ret, default_stream_exists = 0;
1050 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TRACKS, avio_tell(pb));
1054 tracks = start_ebml_master(pb, MATROSKA_ID_TRACKS, 0);
1055 for (i = 0; i < s->nb_streams; i++) {
1056 AVStream *st = s->streams[i];
1057 default_stream_exists |= st->disposition & AV_DISPOSITION_DEFAULT;
1059 for (i = 0; i < s->nb_streams; i++) {
1060 ret = mkv_write_track(s, mkv, i, pb, default_stream_exists);
1064 end_ebml_master(pb, tracks);
1068 static int mkv_write_chapters(AVFormatContext *s)
1070 MatroskaMuxContext *mkv = s->priv_data;
1071 AVIOContext *pb = s->pb;
1072 ebml_master chapters, editionentry;
1073 AVRational scale = {1, 1E9};
1076 if (!s->nb_chapters || mkv->wrote_chapters)
1079 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CHAPTERS, avio_tell(pb));
1080 if (ret < 0) return ret;
1082 chapters = start_ebml_master(pb, MATROSKA_ID_CHAPTERS , 0);
1083 editionentry = start_ebml_master(pb, MATROSKA_ID_EDITIONENTRY, 0);
1084 put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGDEFAULT, 1);
1085 put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGHIDDEN , 0);
1086 for (i = 0; i < s->nb_chapters; i++) {
1087 ebml_master chapteratom, chapterdisplay;
1088 AVChapter *c = s->chapters[i];
1089 int64_t chapterstart = av_rescale_q(c->start, c->time_base, scale);
1090 int64_t chapterend = av_rescale_q(c->end, c->time_base, scale);
1091 AVDictionaryEntry *t = NULL;
1092 if (chapterstart < 0 || chapterstart > chapterend || chapterend < 0) {
1093 av_log(s, AV_LOG_ERROR,
1094 "Invalid chapter start (%"PRId64") or end (%"PRId64").\n",
1095 chapterstart, chapterend);
1096 return AVERROR_INVALIDDATA;
1099 chapteratom = start_ebml_master(pb, MATROSKA_ID_CHAPTERATOM, 0);
1100 put_ebml_uint(pb, MATROSKA_ID_CHAPTERUID, c->id + mkv->chapter_id_offset);
1101 put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMESTART, chapterstart);
1102 put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMEEND, chapterend);
1103 put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGHIDDEN , 0);
1104 put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGENABLED, 1);
1105 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
1106 chapterdisplay = start_ebml_master(pb, MATROSKA_ID_CHAPTERDISPLAY, 0);
1107 put_ebml_string(pb, MATROSKA_ID_CHAPSTRING, t->value);
1108 put_ebml_string(pb, MATROSKA_ID_CHAPLANG , "und");
1109 end_ebml_master(pb, chapterdisplay);
1111 end_ebml_master(pb, chapteratom);
1113 end_ebml_master(pb, editionentry);
1114 end_ebml_master(pb, chapters);
1116 mkv->wrote_chapters = 1;
1120 static int mkv_write_simpletag(AVIOContext *pb, AVDictionaryEntry *t)
1122 uint8_t *key = av_strdup(t->key);
1124 const uint8_t *lang = NULL;
1128 return AVERROR(ENOMEM);
1130 if ((p = strrchr(p, '-')) &&
1131 (lang = av_convert_lang_to(p + 1, AV_LANG_ISO639_2_BIBL)))
1138 else if (*p >= 'a' && *p <= 'z')
1143 tag = start_ebml_master(pb, MATROSKA_ID_SIMPLETAG, 0);
1144 put_ebml_string(pb, MATROSKA_ID_TAGNAME, key);
1146 put_ebml_string(pb, MATROSKA_ID_TAGLANG, lang);
1147 put_ebml_string(pb, MATROSKA_ID_TAGSTRING, t->value);
1148 end_ebml_master(pb, tag);
1154 static int mkv_write_tag(AVFormatContext *s, AVDictionary *m, unsigned int elementid,
1155 unsigned int uid, ebml_master *tags)
1157 MatroskaMuxContext *mkv = s->priv_data;
1158 ebml_master tag, targets;
1159 AVDictionaryEntry *t = NULL;
1163 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TAGS, avio_tell(s->pb));
1164 if (ret < 0) return ret;
1166 *tags = start_ebml_master(s->pb, MATROSKA_ID_TAGS, 0);
1169 tag = start_ebml_master(s->pb, MATROSKA_ID_TAG, 0);
1170 targets = start_ebml_master(s->pb, MATROSKA_ID_TAGTARGETS, 0);
1172 put_ebml_uint(s->pb, elementid, uid);
1173 end_ebml_master(s->pb, targets);
1175 while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX))) {
1176 if (av_strcasecmp(t->key, "title") &&
1177 av_strcasecmp(t->key, "stereo_mode") &&
1178 av_strcasecmp(t->key, "encoding_tool")) {
1179 ret = mkv_write_simpletag(s->pb, t);
1185 end_ebml_master(s->pb, tag);
1189 static int mkv_check_tag(AVDictionary *m)
1191 AVDictionaryEntry *t = NULL;
1193 while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX)))
1194 if (av_strcasecmp(t->key, "title") && av_strcasecmp(t->key, "stereo_mode"))
1200 static int mkv_write_tags(AVFormatContext *s)
1202 MatroskaMuxContext *mkv = s->priv_data;
1203 ebml_master tags = {0};
1206 ff_metadata_conv_ctx(s, ff_mkv_metadata_conv, NULL);
1208 if (mkv_check_tag(s->metadata)) {
1209 ret = mkv_write_tag(s, s->metadata, 0, 0, &tags);
1210 if (ret < 0) return ret;
1213 for (i = 0; i < s->nb_streams; i++) {
1214 AVStream *st = s->streams[i];
1216 if (!mkv_check_tag(st->metadata))
1219 ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &tags);
1220 if (ret < 0) return ret;
1223 for (i = 0; i < s->nb_chapters; i++) {
1224 AVChapter *ch = s->chapters[i];
1226 if (!mkv_check_tag(ch->metadata))
1229 ret = mkv_write_tag(s, ch->metadata, MATROSKA_ID_TAGTARGETS_CHAPTERUID, ch->id + mkv->chapter_id_offset, &tags);
1230 if (ret < 0) return ret;
1234 end_ebml_master(s->pb, tags);
1238 static int mkv_write_attachments(AVFormatContext *s)
1240 MatroskaMuxContext *mkv = s->priv_data;
1241 AVIOContext *pb = s->pb;
1242 ebml_master attachments;
1246 if (!mkv->have_attachments)
1249 av_lfg_init(&c, av_get_random_seed());
1251 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_ATTACHMENTS, avio_tell(pb));
1252 if (ret < 0) return ret;
1254 attachments = start_ebml_master(pb, MATROSKA_ID_ATTACHMENTS, 0);
1256 for (i = 0; i < s->nb_streams; i++) {
1257 AVStream *st = s->streams[i];
1258 ebml_master attached_file;
1259 AVDictionaryEntry *t;
1260 const char *mimetype = NULL;
1263 if (st->codec->codec_type != AVMEDIA_TYPE_ATTACHMENT)
1266 attached_file = start_ebml_master(pb, MATROSKA_ID_ATTACHEDFILE, 0);
1268 if (t = av_dict_get(st->metadata, "title", NULL, 0))
1269 put_ebml_string(pb, MATROSKA_ID_FILEDESC, t->value);
1270 if (!(t = av_dict_get(st->metadata, "filename", NULL, 0))) {
1271 av_log(s, AV_LOG_ERROR, "Attachment stream %d has no filename tag.\n", i);
1272 return AVERROR(EINVAL);
1274 put_ebml_string(pb, MATROSKA_ID_FILENAME, t->value);
1275 if (t = av_dict_get(st->metadata, "mimetype", NULL, 0))
1276 mimetype = t->value;
1277 else if (st->codec->codec_id != AV_CODEC_ID_NONE ) {
1279 for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
1280 if (ff_mkv_mime_tags[i].id == st->codec->codec_id) {
1281 mimetype = ff_mkv_mime_tags[i].str;
1284 for (i = 0; ff_mkv_image_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
1285 if (ff_mkv_image_mime_tags[i].id == st->codec->codec_id) {
1286 mimetype = ff_mkv_image_mime_tags[i].str;
1291 av_log(s, AV_LOG_ERROR, "Attachment stream %d has no mimetype tag and "
1292 "it cannot be deduced from the codec id.\n", i);
1293 return AVERROR(EINVAL);
1296 if (s->flags & AVFMT_FLAG_BITEXACT) {
1297 struct AVSHA *sha = av_sha_alloc();
1300 return AVERROR(ENOMEM);
1301 av_sha_init(sha, 160);
1302 av_sha_update(sha, st->codec->extradata, st->codec->extradata_size);
1303 av_sha_final(sha, digest);
1305 fileuid = AV_RL64(digest);
1307 fileuid = av_lfg_get(&c);
1309 av_log(s, AV_LOG_VERBOSE, "Using %.16"PRIx64" for attachment %d\n",
1312 put_ebml_string(pb, MATROSKA_ID_FILEMIMETYPE, mimetype);
1313 put_ebml_binary(pb, MATROSKA_ID_FILEDATA, st->codec->extradata, st->codec->extradata_size);
1314 put_ebml_uint(pb, MATROSKA_ID_FILEUID, fileuid);
1315 end_ebml_master(pb, attached_file);
1317 end_ebml_master(pb, attachments);
1322 static int mkv_write_header(AVFormatContext *s)
1324 MatroskaMuxContext *mkv = s->priv_data;
1325 AVIOContext *pb = s->pb;
1326 ebml_master ebml_header, segment_info;
1327 AVDictionaryEntry *tag;
1328 int ret, i, version = 2;
1330 if (!strcmp(s->oformat->name, "webm"))
1331 mkv->mode = MODE_WEBM;
1333 mkv->mode = MODE_MATROSKAv2;
1335 if (s->avoid_negative_ts < 0) {
1336 s->avoid_negative_ts = 1;
1337 s->internal->avoid_negative_ts_use_pts = 1;
1340 if (mkv->mode != MODE_WEBM ||
1341 av_dict_get(s->metadata, "stereo_mode", NULL, 0) ||
1342 av_dict_get(s->metadata, "alpha_mode", NULL, 0))
1345 for (i = 0; i < s->nb_streams; i++) {
1346 if (s->streams[i]->codec->codec_id == AV_CODEC_ID_ATRAC3 ||
1347 s->streams[i]->codec->codec_id == AV_CODEC_ID_COOK ||
1348 s->streams[i]->codec->codec_id == AV_CODEC_ID_RA_288 ||
1349 s->streams[i]->codec->codec_id == AV_CODEC_ID_SIPR ||
1350 s->streams[i]->codec->codec_id == AV_CODEC_ID_RV10 ||
1351 s->streams[i]->codec->codec_id == AV_CODEC_ID_RV20) {
1352 av_log(s, AV_LOG_ERROR,
1353 "The Matroska muxer does not yet support muxing %s\n",
1354 avcodec_get_name(s->streams[i]->codec->codec_id));
1355 return AVERROR_PATCHWELCOME;
1357 if (s->streams[i]->codec->codec_id == AV_CODEC_ID_OPUS ||
1358 av_dict_get(s->streams[i]->metadata, "stereo_mode", NULL, 0) ||
1359 av_dict_get(s->streams[i]->metadata, "alpha_mode", NULL, 0))
1363 mkv->tracks = av_mallocz_array(s->nb_streams, sizeof(*mkv->tracks));
1365 return AVERROR(ENOMEM);
1367 ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
1368 put_ebml_uint (pb, EBML_ID_EBMLVERSION , 1);
1369 put_ebml_uint (pb, EBML_ID_EBMLREADVERSION , 1);
1370 put_ebml_uint (pb, EBML_ID_EBMLMAXIDLENGTH , 4);
1371 put_ebml_uint (pb, EBML_ID_EBMLMAXSIZELENGTH , 8);
1372 put_ebml_string (pb, EBML_ID_DOCTYPE , s->oformat->name);
1373 put_ebml_uint (pb, EBML_ID_DOCTYPEVERSION , version);
1374 put_ebml_uint (pb, EBML_ID_DOCTYPEREADVERSION , 2);
1375 end_ebml_master(pb, ebml_header);
1377 mkv->segment = start_ebml_master(pb, MATROSKA_ID_SEGMENT, 0);
1378 mkv->segment_offset = avio_tell(pb);
1380 // we write 2 seek heads - one at the end of the file to point to each
1381 // cluster, and one at the beginning to point to all other level one
1382 // elements (including the seek head at the end of the file), which
1383 // isn't more than 10 elements if we only write one of each other
1384 // currently defined level 1 element
1385 mkv->main_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 10);
1386 if (!mkv->main_seekhead)
1387 return AVERROR(ENOMEM);
1389 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_INFO, avio_tell(pb));
1390 if (ret < 0) return ret;
1392 segment_info = start_ebml_master(pb, MATROSKA_ID_INFO, 0);
1393 put_ebml_uint(pb, MATROSKA_ID_TIMECODESCALE, 1000000);
1394 if ((tag = av_dict_get(s->metadata, "title", NULL, 0)))
1395 put_ebml_string(pb, MATROSKA_ID_TITLE, tag->value);
1396 if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
1397 uint32_t segment_uid[4];
1400 av_lfg_init(&lfg, av_get_random_seed());
1402 for (i = 0; i < 4; i++)
1403 segment_uid[i] = av_lfg_get(&lfg);
1405 put_ebml_string(pb, MATROSKA_ID_MUXINGAPP, LIBAVFORMAT_IDENT);
1406 if ((tag = av_dict_get(s->metadata, "encoding_tool", NULL, 0)))
1407 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, tag->value);
1409 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, LIBAVFORMAT_IDENT);
1410 put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
1412 const char *ident = "Lavf";
1413 put_ebml_string(pb, MATROSKA_ID_MUXINGAPP , ident);
1414 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, ident);
1417 if (tag = av_dict_get(s->metadata, "creation_time", NULL, 0)) {
1418 // Adjust time so it's relative to 2001-01-01 and convert to nanoseconds.
1419 int64_t date_utc = (ff_iso8601_to_unix_time(tag->value) - 978307200) * 1000000000;
1420 uint8_t date_utc_buf[8];
1421 AV_WB64(date_utc_buf, date_utc);
1422 put_ebml_binary(pb, MATROSKA_ID_DATEUTC, date_utc_buf, 8);
1425 // reserve space for the duration
1427 mkv->duration_offset = avio_tell(pb);
1428 if (!mkv->is_live) {
1429 put_ebml_void(pb, 11); // assumes double-precision float to be written
1431 end_ebml_master(pb, segment_info);
1433 ret = mkv_write_tracks(s);
1437 for (i = 0; i < s->nb_chapters; i++)
1438 mkv->chapter_id_offset = FFMAX(mkv->chapter_id_offset, 1LL - s->chapters[i]->id);
1440 if (mkv->mode != MODE_WEBM) {
1441 ret = mkv_write_chapters(s);
1445 ret = mkv_write_tags(s);
1449 ret = mkv_write_attachments(s);
1454 if (!s->pb->seekable && !mkv->is_live)
1455 mkv_write_seekhead(pb, mkv->main_seekhead);
1457 mkv->cues = mkv_start_cues(mkv->segment_offset);
1459 return AVERROR(ENOMEM);
1461 if (pb->seekable && mkv->reserve_cues_space) {
1462 mkv->cues_pos = avio_tell(pb);
1463 put_ebml_void(pb, mkv->reserve_cues_space);
1466 av_init_packet(&mkv->cur_audio_pkt);
1467 mkv->cur_audio_pkt.size = 0;
1468 mkv->cluster_pos = -1;
1472 // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1473 // after 4k and on a keyframe
1475 if (mkv->cluster_time_limit < 0)
1476 mkv->cluster_time_limit = 5000;
1477 if (mkv->cluster_size_limit < 0)
1478 mkv->cluster_size_limit = 5 * 1024 * 1024;
1480 if (mkv->cluster_time_limit < 0)
1481 mkv->cluster_time_limit = 1000;
1482 if (mkv->cluster_size_limit < 0)
1483 mkv->cluster_size_limit = 32 * 1024;
1489 static int mkv_blockgroup_size(int pkt_size)
1491 int size = pkt_size + 4;
1492 size += ebml_num_size(size);
1493 size += 2; // EBML ID for block and block duration
1494 size += 8; // max size of block duration
1495 size += ebml_num_size(size);
1496 size += 1; // blockgroup EBML ID
1500 static int mkv_strip_wavpack(const uint8_t *src, uint8_t **pdst, int *size)
1507 dst = av_malloc(srclen);
1509 return AVERROR(ENOMEM);
1511 while (srclen >= WV_HEADER_SIZE) {
1514 ret = ff_wv_parse_header(&header, src);
1517 src += WV_HEADER_SIZE;
1518 srclen -= WV_HEADER_SIZE;
1520 if (srclen < header.blocksize) {
1521 ret = AVERROR_INVALIDDATA;
1525 if (header.initial) {
1526 AV_WL32(dst + offset, header.samples);
1529 AV_WL32(dst + offset, header.flags);
1530 AV_WL32(dst + offset + 4, header.crc);
1533 if (!(header.initial && header.final)) {
1534 AV_WL32(dst + offset, header.blocksize);
1538 memcpy(dst + offset, src, header.blocksize);
1539 src += header.blocksize;
1540 srclen -= header.blocksize;
1541 offset += header.blocksize;
1553 static void mkv_write_block(AVFormatContext *s, AVIOContext *pb,
1554 unsigned int blockid, AVPacket *pkt, int keyframe)
1556 MatroskaMuxContext *mkv = s->priv_data;
1557 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1558 uint8_t *data = NULL, *side_data = NULL;
1559 int offset = 0, size = pkt->size, side_data_size = 0;
1560 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1561 uint64_t additional_id = 0;
1562 int64_t discard_padding = 0;
1563 uint8_t track_number = (mkv->is_dash ? mkv->dash_track_number : (pkt->stream_index + 1));
1564 ebml_master block_group, block_additions, block_more;
1566 av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
1567 "pts %" PRId64 ", dts %" PRId64 ", duration %d, keyframe %d\n",
1568 avio_tell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration,
1570 if (codec->codec_id == AV_CODEC_ID_H264 && codec->extradata_size > 0 &&
1571 (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
1572 ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
1573 else if (codec->codec_id == AV_CODEC_ID_HEVC && codec->extradata_size > 6 &&
1574 (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
1575 /* extradata is Annex B, assume the bitstream is too and convert it */
1576 ff_hevc_annexb2mp4_buf(pkt->data, &data, &size, 0, NULL);
1577 else if (codec->codec_id == AV_CODEC_ID_WAVPACK) {
1578 int ret = mkv_strip_wavpack(pkt->data, &data, &size);
1580 av_log(s, AV_LOG_ERROR, "Error stripping a WavPack packet.\n");
1586 if (codec->codec_id == AV_CODEC_ID_PRORES && size >= 8) {
1587 /* Matroska specification requires to remove the first QuickTime atom
1593 side_data = av_packet_get_side_data(pkt,
1594 AV_PKT_DATA_SKIP_SAMPLES,
1597 if (side_data && side_data_size >= 10) {
1598 discard_padding = av_rescale_q(AV_RL32(side_data + 4),
1599 (AVRational){1, codec->sample_rate},
1600 (AVRational){1, 1000000000});
1603 side_data = av_packet_get_side_data(pkt,
1604 AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,
1607 additional_id = AV_RB64(side_data);
1609 side_data_size -= 8;
1612 if ((side_data_size && additional_id == 1) || discard_padding) {
1613 block_group = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, 0);
1614 blockid = MATROSKA_ID_BLOCK;
1617 put_ebml_id(pb, blockid);
1618 put_ebml_num(pb, size + 4, 0);
1619 // this assumes stream_index is less than 126
1620 avio_w8(pb, 0x80 | track_number);
1621 avio_wb16(pb, ts - mkv->cluster_pts);
1622 avio_w8(pb, (blockid == MATROSKA_ID_SIMPLEBLOCK && keyframe) ? (1 << 7) : 0);
1623 avio_write(pb, data + offset, size);
1624 if (data != pkt->data)
1627 if (blockid == MATROSKA_ID_BLOCK && !keyframe) {
1628 put_ebml_sint(pb, MATROSKA_ID_BLOCKREFERENCE,
1629 mkv->last_track_timestamp[track_number - 1]);
1631 mkv->last_track_timestamp[track_number - 1] = ts - mkv->cluster_pts;
1633 if (discard_padding) {
1634 put_ebml_sint(pb, MATROSKA_ID_DISCARDPADDING, discard_padding);
1637 if (side_data_size && additional_id == 1) {
1638 block_additions = start_ebml_master(pb, MATROSKA_ID_BLOCKADDITIONS, 0);
1639 block_more = start_ebml_master(pb, MATROSKA_ID_BLOCKMORE, 0);
1640 put_ebml_uint(pb, MATROSKA_ID_BLOCKADDID, 1);
1641 put_ebml_id(pb, MATROSKA_ID_BLOCKADDITIONAL);
1642 put_ebml_num(pb, side_data_size, 0);
1643 avio_write(pb, side_data, side_data_size);
1644 end_ebml_master(pb, block_more);
1645 end_ebml_master(pb, block_additions);
1647 if ((side_data_size && additional_id == 1) || discard_padding) {
1648 end_ebml_master(pb, block_group);
1652 static int mkv_write_vtt_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
1654 MatroskaMuxContext *mkv = s->priv_data;
1655 ebml_master blockgroup;
1656 int id_size, settings_size, size;
1657 uint8_t *id, *settings;
1658 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1659 const int flags = 0;
1662 id = av_packet_get_side_data(pkt, AV_PKT_DATA_WEBVTT_IDENTIFIER,
1666 settings = av_packet_get_side_data(pkt, AV_PKT_DATA_WEBVTT_SETTINGS,
1669 size = id_size + 1 + settings_size + 1 + pkt->size;
1671 av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
1672 "pts %" PRId64 ", dts %" PRId64 ", duration %d, flags %d\n",
1673 avio_tell(pb), size, pkt->pts, pkt->dts, pkt->duration, flags);
1675 blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(size));
1677 put_ebml_id(pb, MATROSKA_ID_BLOCK);
1678 put_ebml_num(pb, size + 4, 0);
1679 avio_w8(pb, 0x80 | (pkt->stream_index + 1)); // this assumes stream_index is less than 126
1680 avio_wb16(pb, ts - mkv->cluster_pts);
1682 avio_printf(pb, "%.*s\n%.*s\n%.*s", id_size, id, settings_size, settings, pkt->size, pkt->data);
1684 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, pkt->duration);
1685 end_ebml_master(pb, blockgroup);
1687 return pkt->duration;
1690 static void mkv_flush_dynbuf(AVFormatContext *s)
1692 MatroskaMuxContext *mkv = s->priv_data;
1699 bufsize = avio_close_dyn_buf(mkv->dyn_bc, &dyn_buf);
1700 avio_write(s->pb, dyn_buf, bufsize);
1705 static void mkv_start_new_cluster(AVFormatContext *s, AVPacket *pkt)
1707 MatroskaMuxContext *mkv = s->priv_data;
1710 if (s->pb->seekable) {
1716 av_log(s, AV_LOG_DEBUG,
1717 "Starting new cluster at offset %" PRIu64 " bytes, "
1718 "pts %" PRIu64 "dts %" PRIu64 "\n",
1719 avio_tell(pb), pkt->pts, pkt->dts);
1720 end_ebml_master(pb, mkv->cluster);
1721 mkv->cluster_pos = -1;
1723 mkv_flush_dynbuf(s);
1727 static int mkv_write_packet_internal(AVFormatContext *s, AVPacket *pkt, int add_cue)
1729 MatroskaMuxContext *mkv = s->priv_data;
1730 AVIOContext *pb = s->pb;
1731 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1732 int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1733 int duration = pkt->duration;
1735 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1736 int64_t relative_packet_pos;
1737 int dash_tracknum = mkv->is_dash ? mkv->dash_track_number : pkt->stream_index + 1;
1739 if (ts == AV_NOPTS_VALUE) {
1740 av_log(s, AV_LOG_ERROR, "Can't write packet with unknown timestamp\n");
1741 return AVERROR(EINVAL);
1743 ts += mkv->tracks[pkt->stream_index].ts_offset;
1745 if (mkv->cluster_pos != -1) {
1746 int64_t cluster_time = ts - mkv->cluster_pts + mkv->tracks[pkt->stream_index].ts_offset;
1747 if ((int16_t)cluster_time != cluster_time) {
1748 av_log(s, AV_LOG_WARNING, "Starting new cluster due to timestamp\n");
1749 mkv_start_new_cluster(s, pkt);
1753 if (!s->pb->seekable) {
1755 ret = avio_open_dyn_buf(&mkv->dyn_bc);
1757 av_log(s, AV_LOG_ERROR, "Failed to open dynamic buffer\n");
1764 if (mkv->cluster_pos == -1) {
1765 mkv->cluster_pos = avio_tell(s->pb);
1766 mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER, 0);
1767 put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, FFMAX(0, ts));
1768 mkv->cluster_pts = FFMAX(0, ts);
1771 relative_packet_pos = avio_tell(s->pb) - mkv->cluster.pos;
1773 if (codec->codec_type != AVMEDIA_TYPE_SUBTITLE) {
1774 mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe);
1775 if (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe || add_cue) {
1776 ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, dash_tracknum, ts, mkv->cluster_pos, relative_packet_pos, -1);
1777 if (ret < 0) return ret;
1780 if (codec->codec_id == AV_CODEC_ID_WEBVTT) {
1781 duration = mkv_write_vtt_blocks(s, pb, pkt);
1783 ebml_master blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
1784 mkv_blockgroup_size(pkt->size));
1785 /* For backward compatibility, prefer convergence_duration. */
1786 if (pkt->convergence_duration > 0) {
1787 duration = pkt->convergence_duration;
1789 /* All subtitle blocks are considered to be keyframes. */
1790 mkv_write_block(s, pb, MATROSKA_ID_BLOCK, pkt, 1);
1791 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
1792 end_ebml_master(pb, blockgroup);
1795 ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, dash_tracknum, ts,
1796 mkv->cluster_pos, relative_packet_pos, duration);
1801 mkv->duration = FFMAX(mkv->duration, ts + duration);
1805 static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
1807 MatroskaMuxContext *mkv = s->priv_data;
1808 int codec_type = s->streams[pkt->stream_index]->codec->codec_type;
1809 int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1811 int64_t cluster_time;
1813 int start_new_cluster;
1815 if (mkv->tracks[pkt->stream_index].write_dts)
1816 cluster_time = pkt->dts - mkv->cluster_pts;
1818 cluster_time = pkt->pts - mkv->cluster_pts;
1819 cluster_time += mkv->tracks[pkt->stream_index].ts_offset;
1821 // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1822 // after 4k and on a keyframe
1823 if (s->pb->seekable) {
1824 cluster_size = avio_tell(s->pb) - mkv->cluster_pos;
1826 cluster_size = avio_tell(mkv->dyn_bc);
1829 if (mkv->is_dash && codec_type == AVMEDIA_TYPE_VIDEO) {
1830 // WebM DASH specification states that the first block of every cluster
1831 // has to be a key frame. So for DASH video, we only create a cluster
1832 // on seeing key frames.
1833 start_new_cluster = keyframe;
1834 } else if (mkv->is_dash && codec_type == AVMEDIA_TYPE_AUDIO &&
1835 (mkv->cluster_pos == -1 ||
1836 cluster_time > mkv->cluster_time_limit)) {
1837 // For DASH audio, we create a Cluster based on cluster_time_limit
1838 start_new_cluster = 1;
1839 } else if (!mkv->is_dash &&
1840 (cluster_size > mkv->cluster_size_limit ||
1841 cluster_time > mkv->cluster_time_limit ||
1842 (codec_type == AVMEDIA_TYPE_VIDEO && keyframe &&
1843 cluster_size > 4 * 1024))) {
1844 start_new_cluster = 1;
1846 start_new_cluster = 0;
1849 if (mkv->cluster_pos != -1 && start_new_cluster) {
1850 mkv_start_new_cluster(s, pkt);
1853 // check if we have an audio packet cached
1854 if (mkv->cur_audio_pkt.size > 0) {
1855 // for DASH audio, a CuePoint has to be added when there is a new cluster.
1856 ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt,
1857 mkv->is_dash ? start_new_cluster : 0);
1858 av_free_packet(&mkv->cur_audio_pkt);
1860 av_log(s, AV_LOG_ERROR,
1861 "Could not write cached audio packet ret:%d\n", ret);
1866 // buffer an audio packet to ensure the packet containing the video
1867 // keyframe's timecode is contained in the same cluster for WebM
1868 if (codec_type == AVMEDIA_TYPE_AUDIO) {
1869 mkv->cur_audio_pkt = *pkt;
1871 mkv->cur_audio_pkt.buf = av_buffer_ref(pkt->buf);
1872 ret = mkv->cur_audio_pkt.buf ? 0 : AVERROR(ENOMEM);
1874 ret = av_dup_packet(&mkv->cur_audio_pkt);
1875 if (mkv->cur_audio_pkt.side_data_elems > 0) {
1876 ret = av_copy_packet_side_data(&mkv->cur_audio_pkt, &mkv->cur_audio_pkt);
1879 ret = mkv_write_packet_internal(s, pkt, 0);
1883 static int mkv_write_flush_packet(AVFormatContext *s, AVPacket *pkt)
1885 MatroskaMuxContext *mkv = s->priv_data;
1887 if (s->pb->seekable)
1892 if (mkv->cluster_pos != -1) {
1893 av_log(s, AV_LOG_DEBUG,
1894 "Flushing cluster at offset %" PRIu64 " bytes\n",
1896 end_ebml_master(pb, mkv->cluster);
1897 mkv->cluster_pos = -1;
1899 mkv_flush_dynbuf(s);
1904 return mkv_write_packet(s, pkt);
1907 static int mkv_write_trailer(AVFormatContext *s)
1909 MatroskaMuxContext *mkv = s->priv_data;
1910 AVIOContext *pb = s->pb;
1911 int64_t currentpos, cuespos;
1914 // check if we have an audio packet cached
1915 if (mkv->cur_audio_pkt.size > 0) {
1916 ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt, 0);
1917 av_free_packet(&mkv->cur_audio_pkt);
1919 av_log(s, AV_LOG_ERROR,
1920 "Could not write cached audio packet ret:%d\n", ret);
1926 end_ebml_master(mkv->dyn_bc, mkv->cluster);
1927 mkv_flush_dynbuf(s);
1928 } else if (mkv->cluster_pos != -1) {
1929 end_ebml_master(pb, mkv->cluster);
1932 if (mkv->mode != MODE_WEBM) {
1933 ret = mkv_write_chapters(s);
1939 if (mkv->cues->num_entries) {
1940 if (mkv->reserve_cues_space) {
1943 currentpos = avio_tell(pb);
1944 avio_seek(pb, mkv->cues_pos, SEEK_SET);
1946 cuespos = mkv_write_cues(s, mkv->cues, mkv->tracks, s->nb_streams);
1947 cues_end = avio_tell(pb);
1948 if (cues_end > cuespos + mkv->reserve_cues_space) {
1949 av_log(s, AV_LOG_ERROR,
1950 "Insufficient space reserved for cues: %d "
1951 "(needed: %" PRId64 ").\n",
1952 mkv->reserve_cues_space, cues_end - cuespos);
1953 return AVERROR(EINVAL);
1956 if (cues_end < cuespos + mkv->reserve_cues_space)
1957 put_ebml_void(pb, mkv->reserve_cues_space -
1958 (cues_end - cuespos));
1960 avio_seek(pb, currentpos, SEEK_SET);
1962 cuespos = mkv_write_cues(s, mkv->cues, mkv->tracks, s->nb_streams);
1965 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CUES,
1971 mkv_write_seekhead(pb, mkv->main_seekhead);
1973 // update the duration
1974 av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
1975 currentpos = avio_tell(pb);
1976 avio_seek(pb, mkv->duration_offset, SEEK_SET);
1977 put_ebml_float(pb, MATROSKA_ID_DURATION, mkv->duration);
1979 avio_seek(pb, currentpos, SEEK_SET);
1982 if (!mkv->is_live) {
1983 end_ebml_master(pb, mkv->segment);
1985 av_freep(&mkv->tracks);
1986 av_freep(&mkv->cues->entries);
1987 av_freep(&mkv->cues);
1992 static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
1995 for (i = 0; ff_mkv_codec_tags[i].id != AV_CODEC_ID_NONE; i++)
1996 if (ff_mkv_codec_tags[i].id == codec_id)
1999 if (std_compliance < FF_COMPLIANCE_NORMAL) {
2000 enum AVMediaType type = avcodec_get_type(codec_id);
2001 // mkv theoretically supports any video/audio through VFW/ACM
2002 if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)
2009 static const AVCodecTag additional_audio_tags[] = {
2010 { AV_CODEC_ID_ALAC, 0XFFFFFFFF },
2011 { AV_CODEC_ID_EAC3, 0XFFFFFFFF },
2012 { AV_CODEC_ID_MLP, 0xFFFFFFFF },
2013 { AV_CODEC_ID_OPUS, 0xFFFFFFFF },
2014 { AV_CODEC_ID_PCM_S16BE, 0xFFFFFFFF },
2015 { AV_CODEC_ID_PCM_S24BE, 0xFFFFFFFF },
2016 { AV_CODEC_ID_PCM_S32BE, 0xFFFFFFFF },
2017 { AV_CODEC_ID_QDM2, 0xFFFFFFFF },
2018 { AV_CODEC_ID_RA_144, 0xFFFFFFFF },
2019 { AV_CODEC_ID_RA_288, 0xFFFFFFFF },
2020 { AV_CODEC_ID_COOK, 0xFFFFFFFF },
2021 { AV_CODEC_ID_TRUEHD, 0xFFFFFFFF },
2022 { AV_CODEC_ID_NONE, 0xFFFFFFFF }
2025 static const AVCodecTag additional_video_tags[] = {
2026 { AV_CODEC_ID_RV10, 0xFFFFFFFF },
2027 { AV_CODEC_ID_RV20, 0xFFFFFFFF },
2028 { AV_CODEC_ID_RV30, 0xFFFFFFFF },
2029 { AV_CODEC_ID_RV40, 0xFFFFFFFF },
2030 { AV_CODEC_ID_VP9, 0xFFFFFFFF },
2031 { AV_CODEC_ID_NONE, 0xFFFFFFFF }
2034 static const AVCodecTag additional_subtitle_tags[] = {
2035 { AV_CODEC_ID_DVB_SUBTITLE, 0xFFFFFFFF },
2036 { AV_CODEC_ID_HDMV_PGS_SUBTITLE, 0xFFFFFFFF },
2037 { AV_CODEC_ID_NONE, 0xFFFFFFFF }
2040 #define OFFSET(x) offsetof(MatroskaMuxContext, x)
2041 #define FLAGS AV_OPT_FLAG_ENCODING_PARAM
2042 static const AVOption options[] = {
2043 { "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 },
2044 { "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 },
2045 { "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 },
2046 { "dash", "Create a WebM file conforming to WebM DASH specification", OFFSET(is_dash), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
2047 { "dash_track_number", "Track number for the DASH stream", OFFSET(dash_track_number), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 127, FLAGS },
2048 { "live", "Write files assuming it is a live stream.", OFFSET(is_live), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
2049 { "allow_raw_vfw", "allow RAW VFW mode", OFFSET(allow_raw_vfw), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
2053 #if CONFIG_MATROSKA_MUXER
2054 static const AVClass matroska_class = {
2055 .class_name = "matroska muxer",
2056 .item_name = av_default_item_name,
2058 .version = LIBAVUTIL_VERSION_INT,
2061 AVOutputFormat ff_matroska_muxer = {
2063 .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
2064 .mime_type = "video/x-matroska",
2065 .extensions = "mkv",
2066 .priv_data_size = sizeof(MatroskaMuxContext),
2067 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
2068 AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
2069 .video_codec = CONFIG_LIBX264_ENCODER ?
2070 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
2071 .write_header = mkv_write_header,
2072 .write_packet = mkv_write_flush_packet,
2073 .write_trailer = mkv_write_trailer,
2074 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
2075 AVFMT_TS_NONSTRICT | AVFMT_ALLOW_FLUSH,
2076 .codec_tag = (const AVCodecTag* const []){
2077 ff_codec_bmp_tags, ff_codec_wav_tags,
2078 additional_audio_tags, additional_video_tags, additional_subtitle_tags, 0
2080 .subtitle_codec = AV_CODEC_ID_ASS,
2081 .query_codec = mkv_query_codec,
2082 .priv_class = &matroska_class,
2086 #if CONFIG_WEBM_MUXER
2087 static const AVClass webm_class = {
2088 .class_name = "webm muxer",
2089 .item_name = av_default_item_name,
2091 .version = LIBAVUTIL_VERSION_INT,
2094 AVOutputFormat ff_webm_muxer = {
2096 .long_name = NULL_IF_CONFIG_SMALL("WebM"),
2097 .mime_type = "video/webm",
2098 .extensions = "webm",
2099 .priv_data_size = sizeof(MatroskaMuxContext),
2100 .audio_codec = AV_CODEC_ID_VORBIS,
2101 .video_codec = AV_CODEC_ID_VP8,
2102 .subtitle_codec = AV_CODEC_ID_WEBVTT,
2103 .write_header = mkv_write_header,
2104 .write_packet = mkv_write_flush_packet,
2105 .write_trailer = mkv_write_trailer,
2106 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
2107 AVFMT_TS_NONSTRICT | AVFMT_ALLOW_FLUSH,
2108 .priv_class = &webm_class,
2112 #if CONFIG_MATROSKA_AUDIO_MUXER
2113 static const AVClass mka_class = {
2114 .class_name = "matroska audio muxer",
2115 .item_name = av_default_item_name,
2117 .version = LIBAVUTIL_VERSION_INT,
2119 AVOutputFormat ff_matroska_audio_muxer = {
2121 .long_name = NULL_IF_CONFIG_SMALL("Matroska Audio"),
2122 .mime_type = "audio/x-matroska",
2123 .extensions = "mka",
2124 .priv_data_size = sizeof(MatroskaMuxContext),
2125 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
2126 AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
2127 .video_codec = AV_CODEC_ID_NONE,
2128 .write_header = mkv_write_header,
2129 .write_packet = mkv_write_flush_packet,
2130 .write_trailer = mkv_write_trailer,
2131 .flags = AVFMT_GLOBALHEADER | AVFMT_TS_NONSTRICT |
2133 .codec_tag = (const AVCodecTag* const []){
2134 ff_codec_wav_tags, additional_audio_tags, 0
2136 .priv_class = &mka_class,