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/crc.h"
41 #include "libavutil/dict.h"
42 #include "libavutil/intfloat.h"
43 #include "libavutil/intreadwrite.h"
44 #include "libavutil/lfg.h"
45 #include "libavutil/mastering_display_metadata.h"
46 #include "libavutil/mathematics.h"
47 #include "libavutil/opt.h"
48 #include "libavutil/parseutils.h"
49 #include "libavutil/random_seed.h"
50 #include "libavutil/rational.h"
51 #include "libavutil/samplefmt.h"
52 #include "libavutil/sha.h"
53 #include "libavutil/stereo3d.h"
55 #include "libavcodec/xiph.h"
56 #include "libavcodec/mpeg4audio.h"
57 #include "libavcodec/internal.h"
59 typedef struct ebml_master {
60 int64_t pos; ///< absolute offset in the file where the master's elements start
61 int sizebytes; ///< how many bytes were reserved for the size
64 typedef struct mkv_seekhead_entry {
65 unsigned int elementid;
69 typedef struct mkv_seekhead {
71 int64_t segment_offset; ///< the file offset to the beginning of the segment
72 int reserved_size; ///< -1 if appending to file
74 mkv_seekhead_entry *entries;
78 typedef struct mkv_cuepoint {
82 int64_t cluster_pos; ///< file offset of the cluster containing the block
83 int64_t relative_pos; ///< relative offset from the position of the cluster containing the block
84 int64_t duration; ///< duration of the block according to time base
87 typedef struct mkv_cues {
88 int64_t segment_offset;
89 mkv_cuepoint *entries;
93 typedef struct mkv_track {
96 int64_t codecpriv_offset;
100 typedef struct mkv_attachment {
105 typedef struct mkv_attachments {
106 mkv_attachment *entries;
110 #define MODE_MATROSKAv2 0x01
111 #define MODE_WEBM 0x02
113 /** Maximum number of tracks allowed in a Matroska file (with track numbers in
114 * range 1 to 126 (inclusive) */
115 #define MAX_TRACKS 126
117 typedef struct MatroskaMuxContext {
118 const AVClass *class;
121 AVIOContext *tags_bc;
123 AVIOContext *info_bc;
125 AVIOContext *tracks_bc;
126 ebml_master tracks_master;
128 int64_t segment_offset;
130 int64_t cluster_pos; ///< file offset of the current cluster
132 int64_t duration_offset;
134 mkv_seekhead *main_seekhead;
137 mkv_attachments *attachments;
139 AVPacket cur_audio_pkt;
141 int have_attachments;
144 int reserve_cues_space;
145 int cluster_size_limit;
147 int64_t cluster_time_limit;
149 int dash_track_number;
153 uint32_t chapter_id_offset;
156 int64_t last_track_timestamp[MAX_TRACKS];
158 int64_t* stream_durations;
159 int64_t* stream_duration_offsets;
162 } MatroskaMuxContext;
165 /** 2 bytes * 3 for EBML IDs, 3 1-byte EBML lengths, 8 bytes for 64 bit
166 * offset, 4 bytes for target EBML ID */
167 #define MAX_SEEKENTRY_SIZE 21
169 /** per-cuepoint-track - 5 1-byte EBML IDs, 5 1-byte EBML sizes, 4
171 #define MAX_CUETRACKPOS_SIZE 42
173 /** per-cuepoint - 2 1-byte EBML IDs, 2 1-byte EBML sizes, 8-byte uint max */
174 #define MAX_CUEPOINT_SIZE(num_tracks) 12 + MAX_CUETRACKPOS_SIZE * num_tracks
176 /** Seek preroll value for opus */
177 #define OPUS_SEEK_PREROLL 80000000
179 static int ebml_id_size(unsigned int id)
181 return (av_log2(id + 1) - 1) / 7 + 1;
184 static void put_ebml_id(AVIOContext *pb, unsigned int id)
186 int i = ebml_id_size(id);
188 avio_w8(pb, (uint8_t)(id >> (i * 8)));
192 * Write an EBML size meaning "unknown size".
194 * @param bytes The number of bytes the size should occupy (maximum: 8).
196 static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
198 av_assert0(bytes <= 8);
199 avio_w8(pb, 0x1ff >> bytes);
200 ffio_fill(pb, 0xff, bytes - 1);
204 * Calculate how many bytes are needed to represent a given number in EBML.
206 static int ebml_num_size(uint64_t num)
209 while ((num + 1) >> bytes * 7)
215 * Write a number in EBML variable length format.
217 * @param bytes The number of bytes that need to be used to write the number.
218 * If zero, any number of bytes can be used.
220 static void put_ebml_num(AVIOContext *pb, uint64_t num, int bytes)
222 int i, needed_bytes = ebml_num_size(num);
224 // sizes larger than this are currently undefined in EBML
225 av_assert0(num < (1ULL << 56) - 1);
228 // don't care how many bytes are used, so use the min
229 bytes = needed_bytes;
230 // the bytes needed to write the given size would exceed the bytes
231 // that we need to use, so write unknown size. This shouldn't happen.
232 av_assert0(bytes >= needed_bytes);
234 num |= 1ULL << bytes * 7;
235 for (i = bytes - 1; i >= 0; i--)
236 avio_w8(pb, (uint8_t)(num >> i * 8));
239 static void put_ebml_uint(AVIOContext *pb, unsigned int elementid, uint64_t val)
246 put_ebml_id(pb, elementid);
247 put_ebml_num(pb, bytes, 0);
248 for (i = bytes - 1; i >= 0; i--)
249 avio_w8(pb, (uint8_t)(val >> i * 8));
252 static void put_ebml_sint(AVIOContext *pb, unsigned int elementid, int64_t val)
255 uint64_t tmp = 2*(val < 0 ? val^-1 : val);
257 while (tmp>>=8) bytes++;
259 put_ebml_id(pb, elementid);
260 put_ebml_num(pb, bytes, 0);
261 for (i = bytes - 1; i >= 0; i--)
262 avio_w8(pb, (uint8_t)(val >> i * 8));
265 static void put_ebml_float(AVIOContext *pb, unsigned int elementid, double val)
267 put_ebml_id(pb, elementid);
268 put_ebml_num(pb, 8, 0);
269 avio_wb64(pb, av_double2int(val));
272 static void put_ebml_binary(AVIOContext *pb, unsigned int elementid,
273 const void *buf, int size)
275 put_ebml_id(pb, elementid);
276 put_ebml_num(pb, size, 0);
277 avio_write(pb, buf, size);
280 static void put_ebml_string(AVIOContext *pb, unsigned int elementid,
283 put_ebml_binary(pb, elementid, str, strlen(str));
287 * Write a void element of a given size. Useful for reserving space in
288 * the file to be written to later.
290 * @param size The number of bytes to reserve, which must be at least 2.
292 static void put_ebml_void(AVIOContext *pb, uint64_t size)
294 int64_t currentpos = avio_tell(pb);
296 av_assert0(size >= 2);
298 put_ebml_id(pb, EBML_ID_VOID);
299 // we need to subtract the length needed to store the size from the
300 // size we need to reserve so 2 cases, we use 8 bytes to store the
301 // size if possible, 1 byte otherwise
303 put_ebml_num(pb, size - 2, 0);
305 put_ebml_num(pb, size - 9, 8);
306 ffio_fill(pb, 0, currentpos + size - avio_tell(pb));
309 static ebml_master start_ebml_master(AVIOContext *pb, unsigned int elementid,
310 uint64_t expectedsize)
312 int bytes = expectedsize ? ebml_num_size(expectedsize) : 8;
313 put_ebml_id(pb, elementid);
314 put_ebml_size_unknown(pb, bytes);
315 return (ebml_master) {avio_tell(pb), bytes };
318 static void end_ebml_master(AVIOContext *pb, ebml_master master)
320 int64_t pos = avio_tell(pb);
322 if (avio_seek(pb, master.pos - master.sizebytes, SEEK_SET) < 0)
324 put_ebml_num(pb, pos - master.pos, master.sizebytes);
325 avio_seek(pb, pos, SEEK_SET);
328 static int start_ebml_master_crc32(AVIOContext *pb, AVIOContext **dyn_cp, MatroskaMuxContext *mkv,
329 ebml_master *master, unsigned int elementid, uint64_t expectedsize)
333 if ((ret = avio_open_dyn_buf(dyn_cp)) < 0)
336 if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
337 *master = start_ebml_master(pb, elementid, expectedsize);
338 if (mkv->write_crc && mkv->mode != MODE_WEBM)
339 put_ebml_void(*dyn_cp, 6); /* Reserve space for CRC32 so position/size calculations using avio_tell() take it into account */
341 *master = start_ebml_master(*dyn_cp, elementid, expectedsize);
346 static void end_ebml_master_crc32(AVIOContext *pb, AVIOContext **dyn_cp, MatroskaMuxContext *mkv,
349 uint8_t *buf, crc[4];
352 if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
353 size = avio_close_dyn_buf(*dyn_cp, &buf);
354 if (mkv->write_crc && mkv->mode != MODE_WEBM) {
355 skip = 6; /* Skip reserved 6-byte long void element from the dynamic buffer. */
356 AV_WL32(crc, av_crc(av_crc_get_table(AV_CRC_32_IEEE_LE), UINT32_MAX, buf + skip, size - skip) ^ UINT32_MAX);
357 put_ebml_binary(pb, EBML_ID_CRC32, crc, sizeof(crc));
359 avio_write(pb, buf + skip, size - skip);
360 end_ebml_master(pb, master);
362 end_ebml_master(*dyn_cp, master);
363 size = avio_close_dyn_buf(*dyn_cp, &buf);
364 avio_write(pb, buf, size);
371 * Complete ebml master whithout destroying the buffer, allowing for later updates
373 static void end_ebml_master_crc32_preliminary(AVIOContext *pb, AVIOContext **dyn_cp, MatroskaMuxContext *mkv,
376 if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
379 int size = avio_get_dyn_buf(*dyn_cp, &buf);
381 avio_write(pb, buf, size);
382 end_ebml_master(pb, master);
386 static void put_xiph_size(AVIOContext *pb, int size)
388 ffio_fill(pb, 255, size / 255);
389 avio_w8(pb, size % 255);
393 * Free the members allocated in the mux context.
395 static void mkv_free(MatroskaMuxContext *mkv) {
398 avio_close_dyn_buf(mkv->dyn_bc, &buf);
402 avio_close_dyn_buf(mkv->info_bc, &buf);
405 if (mkv->tracks_bc) {
406 avio_close_dyn_buf(mkv->tracks_bc, &buf);
410 avio_close_dyn_buf(mkv->tags_bc, &buf);
413 if (mkv->main_seekhead) {
414 av_freep(&mkv->main_seekhead->entries);
415 av_freep(&mkv->main_seekhead);
418 av_freep(&mkv->cues->entries);
419 av_freep(&mkv->cues);
421 if (mkv->attachments) {
422 av_freep(&mkv->attachments->entries);
423 av_freep(&mkv->attachments);
425 av_freep(&mkv->tracks);
426 av_freep(&mkv->stream_durations);
427 av_freep(&mkv->stream_duration_offsets);
431 * Initialize a mkv_seekhead element to be ready to index level 1 Matroska
432 * elements. If a maximum number of elements is specified, enough space
433 * will be reserved at the current file location to write a seek head of
436 * @param segment_offset The absolute offset to the position in the file
437 * where the segment begins.
438 * @param numelements The maximum number of elements that will be indexed
439 * by this seek head, 0 if unlimited.
441 static mkv_seekhead *mkv_start_seekhead(AVIOContext *pb, int64_t segment_offset,
444 mkv_seekhead *new_seekhead = av_mallocz(sizeof(mkv_seekhead));
448 new_seekhead->segment_offset = segment_offset;
450 if (numelements > 0) {
451 new_seekhead->filepos = avio_tell(pb);
452 // 21 bytes max for a seek entry, 10 bytes max for the SeekHead ID
453 // and size, 6 bytes for a CRC32 element, and 3 bytes to guarantee
454 // that an EBML void element will fit afterwards
455 new_seekhead->reserved_size = numelements * MAX_SEEKENTRY_SIZE + 19;
456 new_seekhead->max_entries = numelements;
457 put_ebml_void(pb, new_seekhead->reserved_size);
462 static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
464 mkv_seekhead_entry *entries = seekhead->entries;
466 // don't store more elements than we reserved space for
467 if (seekhead->max_entries > 0 && seekhead->max_entries <= seekhead->num_entries)
470 entries = av_realloc_array(entries, seekhead->num_entries + 1, sizeof(mkv_seekhead_entry));
472 return AVERROR(ENOMEM);
473 seekhead->entries = entries;
475 seekhead->entries[seekhead->num_entries].elementid = elementid;
476 seekhead->entries[seekhead->num_entries++].segmentpos = filepos - seekhead->segment_offset;
482 * Write the seek head to the file and free it. If a maximum number of
483 * elements was specified to mkv_start_seekhead(), the seek head will
484 * be written at the location reserved for it. Otherwise, it is written
485 * at the current location in the file.
487 * @return The file offset where the seekhead was written,
488 * -1 if an error occurred.
490 static int64_t mkv_write_seekhead(AVIOContext *pb, MatroskaMuxContext *mkv)
493 mkv_seekhead *seekhead = mkv->main_seekhead;
494 ebml_master metaseek, seekentry;
498 currentpos = avio_tell(pb);
500 if (seekhead->reserved_size > 0) {
501 if (avio_seek(pb, seekhead->filepos, SEEK_SET) < 0) {
507 if (start_ebml_master_crc32(pb, &dyn_cp, mkv, &metaseek, MATROSKA_ID_SEEKHEAD,
508 seekhead->reserved_size) < 0) {
513 for (i = 0; i < seekhead->num_entries; i++) {
514 mkv_seekhead_entry *entry = &seekhead->entries[i];
516 seekentry = start_ebml_master(dyn_cp, MATROSKA_ID_SEEKENTRY, MAX_SEEKENTRY_SIZE);
518 put_ebml_id(dyn_cp, MATROSKA_ID_SEEKID);
519 put_ebml_num(dyn_cp, ebml_id_size(entry->elementid), 0);
520 put_ebml_id(dyn_cp, entry->elementid);
522 put_ebml_uint(dyn_cp, MATROSKA_ID_SEEKPOSITION, entry->segmentpos);
523 end_ebml_master(dyn_cp, seekentry);
525 end_ebml_master_crc32(pb, &dyn_cp, mkv, metaseek);
527 if (seekhead->reserved_size > 0) {
528 uint64_t remaining = seekhead->filepos + seekhead->reserved_size - avio_tell(pb);
529 put_ebml_void(pb, remaining);
530 avio_seek(pb, currentpos, SEEK_SET);
532 currentpos = seekhead->filepos;
535 av_freep(&mkv->main_seekhead->entries);
536 av_freep(&mkv->main_seekhead);
541 static mkv_cues *mkv_start_cues(int64_t segment_offset)
543 mkv_cues *cues = av_mallocz(sizeof(mkv_cues));
547 cues->segment_offset = segment_offset;
551 static int mkv_add_cuepoint(mkv_cues *cues, int stream, int tracknum, int64_t ts,
552 int64_t cluster_pos, int64_t relative_pos, int64_t duration)
554 mkv_cuepoint *entries = cues->entries;
559 entries = av_realloc_array(entries, cues->num_entries + 1, sizeof(mkv_cuepoint));
561 return AVERROR(ENOMEM);
562 cues->entries = entries;
564 cues->entries[cues->num_entries].pts = ts;
565 cues->entries[cues->num_entries].stream_idx = stream;
566 cues->entries[cues->num_entries].tracknum = tracknum;
567 cues->entries[cues->num_entries].cluster_pos = cluster_pos - cues->segment_offset;
568 cues->entries[cues->num_entries].relative_pos = relative_pos;
569 cues->entries[cues->num_entries++].duration = duration;
574 static int64_t mkv_write_cues(AVFormatContext *s, mkv_cues *cues, mkv_track *tracks, int num_tracks)
576 MatroskaMuxContext *mkv = s->priv_data;
577 AVIOContext *dyn_cp, *pb = s->pb;
578 ebml_master cues_element;
582 currentpos = avio_tell(pb);
583 ret = start_ebml_master_crc32(pb, &dyn_cp, mkv, &cues_element, MATROSKA_ID_CUES, 0);
587 for (i = 0; i < cues->num_entries; i++) {
588 ebml_master cuepoint, track_positions;
589 mkv_cuepoint *entry = &cues->entries[i];
590 uint64_t pts = entry->pts;
593 // Calculate the number of entries, so we know the element size
594 for (j = 0; j < num_tracks; j++)
595 tracks[j].has_cue = 0;
596 for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
597 int tracknum = entry[j].stream_idx;
598 av_assert0(tracknum>=0 && tracknum<num_tracks);
599 if (tracks[tracknum].has_cue && s->streams[tracknum]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE)
601 tracks[tracknum].has_cue = 1;
605 cuepoint = start_ebml_master(dyn_cp, MATROSKA_ID_POINTENTRY, MAX_CUEPOINT_SIZE(ctp_nb));
606 put_ebml_uint(dyn_cp, MATROSKA_ID_CUETIME, pts);
608 // put all the entries from different tracks that have the exact same
609 // timestamp into the same CuePoint
610 for (j = 0; j < num_tracks; j++)
611 tracks[j].has_cue = 0;
612 for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
613 int tracknum = entry[j].stream_idx;
614 av_assert0(tracknum>=0 && tracknum<num_tracks);
615 if (tracks[tracknum].has_cue && s->streams[tracknum]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE)
617 tracks[tracknum].has_cue = 1;
618 track_positions = start_ebml_master(dyn_cp, MATROSKA_ID_CUETRACKPOSITION, MAX_CUETRACKPOS_SIZE);
619 put_ebml_uint(dyn_cp, MATROSKA_ID_CUETRACK , entry[j].tracknum );
620 put_ebml_uint(dyn_cp, MATROSKA_ID_CUECLUSTERPOSITION , entry[j].cluster_pos);
621 put_ebml_uint(dyn_cp, MATROSKA_ID_CUERELATIVEPOSITION, entry[j].relative_pos);
622 if (entry[j].duration != -1)
623 put_ebml_uint(dyn_cp, MATROSKA_ID_CUEDURATION , entry[j].duration);
624 end_ebml_master(dyn_cp, track_positions);
627 end_ebml_master(dyn_cp, cuepoint);
629 end_ebml_master_crc32(pb, &dyn_cp, mkv, cues_element);
634 static int put_xiph_codecpriv(AVFormatContext *s, AVIOContext *pb, AVCodecParameters *par)
636 const uint8_t *header_start[3];
638 int first_header_size;
641 if (par->codec_id == AV_CODEC_ID_VORBIS)
642 first_header_size = 30;
644 first_header_size = 42;
646 if (avpriv_split_xiph_headers(par->extradata, par->extradata_size,
647 first_header_size, header_start, header_len) < 0) {
648 av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
652 avio_w8(pb, 2); // number packets - 1
653 for (j = 0; j < 2; j++) {
654 put_xiph_size(pb, header_len[j]);
656 for (j = 0; j < 3; j++)
657 avio_write(pb, header_start[j], header_len[j]);
662 static int put_wv_codecpriv(AVIOContext *pb, AVCodecParameters *par)
664 if (par->extradata && par->extradata_size == 2)
665 avio_write(pb, par->extradata, 2);
667 avio_wl16(pb, 0x403); // fallback to the version mentioned in matroska specs
671 static int put_flac_codecpriv(AVFormatContext *s,
672 AVIOContext *pb, AVCodecParameters *par)
674 int write_comment = (par->channel_layout &&
675 !(par->channel_layout & ~0x3ffffULL) &&
676 !ff_flac_is_native_layout(par->channel_layout));
677 int ret = ff_flac_write_header(pb, par->extradata, par->extradata_size,
684 const char *vendor = (s->flags & AVFMT_FLAG_BITEXACT) ?
685 "Lavf" : LIBAVFORMAT_IDENT;
686 AVDictionary *dict = NULL;
687 uint8_t buf[32], *data, *p;
690 snprintf(buf, sizeof(buf), "0x%"PRIx64, par->channel_layout);
691 av_dict_set(&dict, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", buf, 0);
693 len = ff_vorbiscomment_length(dict, vendor);
694 if (len >= ((1<<24) - 4))
695 return AVERROR(EINVAL);
697 data = av_malloc(len + 4);
700 return AVERROR(ENOMEM);
704 AV_WB24(data + 1, len);
707 ff_vorbiscomment_write(&p, &dict, vendor);
709 avio_write(pb, data, len + 4);
718 static int get_aac_sample_rates(AVFormatContext *s, AVCodecParameters *par,
719 int *sample_rate, int *output_sample_rate)
721 MPEG4AudioConfig mp4ac;
723 if (avpriv_mpeg4audio_get_config(&mp4ac, par->extradata,
724 par->extradata_size * 8, 1) < 0) {
725 av_log(s, AV_LOG_ERROR,
726 "Error parsing AAC extradata, unable to determine samplerate.\n");
727 return AVERROR(EINVAL);
730 *sample_rate = mp4ac.sample_rate;
731 *output_sample_rate = mp4ac.ext_sample_rate;
735 static int mkv_write_native_codecprivate(AVFormatContext *s,
736 AVCodecParameters *par,
739 switch (par->codec_id) {
740 case AV_CODEC_ID_VORBIS:
741 case AV_CODEC_ID_THEORA:
742 return put_xiph_codecpriv(s, dyn_cp, par);
743 case AV_CODEC_ID_FLAC:
744 return put_flac_codecpriv(s, dyn_cp, par);
745 case AV_CODEC_ID_WAVPACK:
746 return put_wv_codecpriv(dyn_cp, par);
747 case AV_CODEC_ID_H264:
748 return ff_isom_write_avcc(dyn_cp, par->extradata,
749 par->extradata_size);
750 case AV_CODEC_ID_HEVC:
751 ff_isom_write_hvcc(dyn_cp, par->extradata,
752 par->extradata_size, 0);
754 case AV_CODEC_ID_ALAC:
755 if (par->extradata_size < 36) {
756 av_log(s, AV_LOG_ERROR,
757 "Invalid extradata found, ALAC expects a 36-byte "
759 return AVERROR_INVALIDDATA;
761 avio_write(dyn_cp, par->extradata + 12,
762 par->extradata_size - 12);
765 if (par->codec_id == AV_CODEC_ID_PRORES &&
766 ff_codec_get_id(ff_codec_movvideo_tags, par->codec_tag) == AV_CODEC_ID_PRORES) {
767 avio_wl32(dyn_cp, par->codec_tag);
768 } else if (par->extradata_size && par->codec_id != AV_CODEC_ID_TTA)
769 avio_write(dyn_cp, par->extradata, par->extradata_size);
775 static int mkv_write_codecprivate(AVFormatContext *s, AVIOContext *pb,
776 AVCodecParameters *par,
777 int native_id, int qt_id)
781 int ret, codecpriv_size;
783 ret = avio_open_dyn_buf(&dyn_cp);
788 ret = mkv_write_native_codecprivate(s, par, dyn_cp);
789 } else if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
792 par->codec_tag = ff_codec_get_tag(ff_codec_movvideo_tags,
794 if ( ff_codec_get_id(ff_codec_movvideo_tags, par->codec_tag) == par->codec_id
795 && (!par->extradata_size || ff_codec_get_id(ff_codec_movvideo_tags, AV_RL32(par->extradata + 4)) != par->codec_id)
798 avio_wb32(dyn_cp, 0x5a + par->extradata_size);
799 avio_wl32(dyn_cp, par->codec_tag);
800 for(i = 0; i < 0x5a - 8; i++)
803 avio_write(dyn_cp, par->extradata, par->extradata_size);
805 if (!ff_codec_get_tag(ff_codec_bmp_tags, par->codec_id))
806 av_log(s, AV_LOG_WARNING, "codec %s is not supported by this format\n",
807 avcodec_get_name(par->codec_id));
810 par->codec_tag = ff_codec_get_tag(ff_codec_bmp_tags,
812 if (!par->codec_tag && par->codec_id != AV_CODEC_ID_RAWVIDEO) {
813 av_log(s, AV_LOG_ERROR, "No bmp codec tag found for codec %s\n",
814 avcodec_get_name(par->codec_id));
815 ret = AVERROR(EINVAL);
818 ff_put_bmp_header(dyn_cp, par, ff_codec_bmp_tags, 0, 0);
820 } else if (par->codec_type == AVMEDIA_TYPE_AUDIO) {
822 tag = ff_codec_get_tag(ff_codec_wav_tags, par->codec_id);
824 av_log(s, AV_LOG_ERROR, "No wav codec tag found for codec %s\n",
825 avcodec_get_name(par->codec_id));
826 ret = AVERROR(EINVAL);
829 par->codec_tag = tag;
831 ff_put_wav_header(s, dyn_cp, par, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX);
834 codecpriv_size = avio_close_dyn_buf(dyn_cp, &codecpriv);
836 put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codecpriv,
842 static int mkv_write_video_color(AVIOContext *pb, AVCodecParameters *par, AVStream *st) {
844 uint8_t *colorinfo_ptr;
845 int side_data_size = 0;
846 int ret, colorinfo_size;
847 const uint8_t *side_data = av_stream_get_side_data(
848 st, AV_PKT_DATA_MASTERING_DISPLAY_METADATA, &side_data_size);
850 ret = avio_open_dyn_buf(&dyn_cp);
854 if (par->color_trc != AVCOL_TRC_UNSPECIFIED &&
855 par->color_trc < AVCOL_TRC_NB) {
856 put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORTRANSFERCHARACTERISTICS,
859 if (par->color_space != AVCOL_SPC_UNSPECIFIED &&
860 par->color_space < AVCOL_SPC_NB) {
861 put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORMATRIXCOEFF, par->color_space);
863 if (par->color_primaries != AVCOL_PRI_UNSPECIFIED &&
864 par->color_primaries < AVCOL_PRI_NB) {
865 put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORPRIMARIES, par->color_primaries);
867 if (par->color_range != AVCOL_RANGE_UNSPECIFIED &&
868 par->color_range < AVCOL_RANGE_NB) {
869 put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORRANGE, par->color_range);
871 if (par->chroma_location != AVCHROMA_LOC_UNSPECIFIED &&
872 par->chroma_location <= AVCHROMA_LOC_TOP) {
875 avcodec_enum_to_chroma_pos(&xpos, &ypos, par->chroma_location);
876 put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORCHROMASITINGHORZ, (xpos >> 7) + 1);
877 put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORCHROMASITINGVERT, (ypos >> 7) + 1);
879 if (side_data_size == sizeof(AVMasteringDisplayMetadata)) {
880 ebml_master meta_element = start_ebml_master(
881 dyn_cp, MATROSKA_ID_VIDEOCOLORMASTERINGMETA, 0);
882 const AVMasteringDisplayMetadata *metadata =
883 (const AVMasteringDisplayMetadata*)side_data;
884 if (metadata->has_primaries) {
885 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_RX,
886 av_q2d(metadata->display_primaries[0][0]));
887 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_RY,
888 av_q2d(metadata->display_primaries[0][1]));
889 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_GX,
890 av_q2d(metadata->display_primaries[1][0]));
891 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_GY,
892 av_q2d(metadata->display_primaries[1][1]));
893 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_BX,
894 av_q2d(metadata->display_primaries[2][0]));
895 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_BY,
896 av_q2d(metadata->display_primaries[2][1]));
897 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_WHITEX,
898 av_q2d(metadata->white_point[0]));
899 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_WHITEY,
900 av_q2d(metadata->white_point[1]));
902 if (metadata->has_luminance) {
903 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_LUMINANCEMAX,
904 av_q2d(metadata->max_luminance));
905 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_LUMINANCEMIN,
906 av_q2d(metadata->min_luminance));
908 end_ebml_master(dyn_cp, meta_element);
911 colorinfo_size = avio_close_dyn_buf(dyn_cp, &colorinfo_ptr);
912 if (colorinfo_size) {
913 ebml_master colorinfo = start_ebml_master(pb, MATROSKA_ID_VIDEOCOLOR, colorinfo_size);
914 avio_write(pb, colorinfo_ptr, colorinfo_size);
915 end_ebml_master(pb, colorinfo);
917 av_free(colorinfo_ptr);
921 static int mkv_write_video_projection(AVFormatContext *s, AVIOContext *pb, AVStream *st)
923 int side_data_size = 0;
924 const AVSphericalMapping *spherical =
925 (const AVSphericalMapping*) av_stream_get_side_data(st, AV_PKT_DATA_SPHERICAL,
928 if (side_data_size) {
930 uint8_t *projection_ptr;
931 int ret, projection_size;
933 ret = avio_open_dyn_buf(&dyn_cp);
937 switch (spherical->projection) {
938 case AV_SPHERICAL_EQUIRECTANGULAR:
939 put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONTYPE,
940 MATROSKA_VIDEO_PROJECTION_TYPE_EQUIRECTANGULAR);
942 case AV_SPHERICAL_EQUIRECTANGULAR_TILE:
946 ffio_init_context(&b, private, sizeof(private),
947 1, NULL, NULL, NULL, NULL);
948 put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONTYPE,
949 MATROSKA_VIDEO_PROJECTION_TYPE_EQUIRECTANGULAR);
950 avio_wb32(&b, 0); // version + flags
951 avio_wb32(&b, spherical->bound_top);
952 avio_wb32(&b, spherical->bound_bottom);
953 avio_wb32(&b, spherical->bound_left);
954 avio_wb32(&b, spherical->bound_right);
955 put_ebml_binary(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONPRIVATE, private, sizeof(private));
958 case AV_SPHERICAL_CUBEMAP:
962 ffio_init_context(&b, private, sizeof(private),
963 1, NULL, NULL, NULL, NULL);
964 put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONTYPE,
965 MATROSKA_VIDEO_PROJECTION_TYPE_CUBEMAP);
966 avio_wb32(&b, 0); // version + flags
967 avio_wb32(&b, 0); // layout
968 avio_wb32(&b, spherical->padding);
969 put_ebml_binary(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONPRIVATE, private, sizeof(private));
973 av_log(s, AV_LOG_WARNING, "Unknown projection type\n");
978 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONPOSEYAW, (double)spherical->yaw / (1 << 16));
979 if (spherical->pitch)
980 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONPOSEPITCH, (double)spherical->pitch / (1 << 16));
982 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONPOSEROLL, (double)spherical->roll / (1 << 16));
985 projection_size = avio_close_dyn_buf(dyn_cp, &projection_ptr);
986 if (projection_size) {
987 ebml_master projection = start_ebml_master(pb, MATROSKA_ID_VIDEOPROJECTION, projection_size);
988 avio_write(pb, projection_ptr, projection_size);
989 end_ebml_master(pb, projection);
991 av_freep(&projection_ptr);
997 static void mkv_write_field_order(AVIOContext *pb, int mode,
998 enum AVFieldOrder field_order)
1000 switch (field_order) {
1001 case AV_FIELD_UNKNOWN:
1003 case AV_FIELD_PROGRESSIVE:
1004 put_ebml_uint(pb, MATROSKA_ID_VIDEOFLAGINTERLACED,
1005 MATROSKA_VIDEO_INTERLACE_FLAG_PROGRESSIVE);
1011 put_ebml_uint(pb, MATROSKA_ID_VIDEOFLAGINTERLACED,
1012 MATROSKA_VIDEO_INTERLACE_FLAG_INTERLACED);
1013 if (mode != MODE_WEBM) {
1014 switch (field_order) {
1016 put_ebml_uint(pb, MATROSKA_ID_VIDEOFIELDORDER,
1017 MATROSKA_VIDEO_FIELDORDER_TT);
1020 put_ebml_uint(pb, MATROSKA_ID_VIDEOFIELDORDER,
1021 MATROSKA_VIDEO_FIELDORDER_BB);
1024 put_ebml_uint(pb, MATROSKA_ID_VIDEOFIELDORDER,
1025 MATROSKA_VIDEO_FIELDORDER_TB);
1028 put_ebml_uint(pb, MATROSKA_ID_VIDEOFIELDORDER,
1029 MATROSKA_VIDEO_FIELDORDER_BT);
1036 static int mkv_write_stereo_mode(AVFormatContext *s, AVIOContext *pb,
1037 AVStream *st, int mode, int *h_width, int *h_height)
1041 AVDictionaryEntry *tag;
1042 MatroskaVideoStereoModeType format = MATROSKA_VIDEO_STEREOMODE_TYPE_NB;
1046 // convert metadata into proper side data and add it to the stream
1047 if ((tag = av_dict_get(st->metadata, "stereo_mode", NULL, 0)) ||
1048 (tag = av_dict_get( s->metadata, "stereo_mode", NULL, 0))) {
1049 int stereo_mode = atoi(tag->value);
1051 for (i=0; i<MATROSKA_VIDEO_STEREOMODE_TYPE_NB; i++)
1052 if (!strcmp(tag->value, ff_matroska_video_stereo_mode[i])){
1057 if (stereo_mode < MATROSKA_VIDEO_STEREOMODE_TYPE_NB &&
1058 stereo_mode != 10 && stereo_mode != 12) {
1059 int ret = ff_mkv_stereo3d_conv(st, stereo_mode);
1065 // iterate to find the stereo3d side data
1066 for (i = 0; i < st->nb_side_data; i++) {
1067 AVPacketSideData sd = st->side_data[i];
1068 if (sd.type == AV_PKT_DATA_STEREO3D) {
1069 AVStereo3D *stereo = (AVStereo3D *)sd.data;
1071 switch (stereo->type) {
1072 case AV_STEREO3D_2D:
1073 format = MATROSKA_VIDEO_STEREOMODE_TYPE_MONO;
1075 case AV_STEREO3D_SIDEBYSIDE:
1076 format = (stereo->flags & AV_STEREO3D_FLAG_INVERT)
1077 ? MATROSKA_VIDEO_STEREOMODE_TYPE_RIGHT_LEFT
1078 : MATROSKA_VIDEO_STEREOMODE_TYPE_LEFT_RIGHT;
1081 case AV_STEREO3D_TOPBOTTOM:
1082 format = MATROSKA_VIDEO_STEREOMODE_TYPE_TOP_BOTTOM;
1083 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
1087 case AV_STEREO3D_CHECKERBOARD:
1088 format = MATROSKA_VIDEO_STEREOMODE_TYPE_CHECKERBOARD_LR;
1089 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
1092 case AV_STEREO3D_LINES:
1093 format = MATROSKA_VIDEO_STEREOMODE_TYPE_ROW_INTERLEAVED_LR;
1094 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
1098 case AV_STEREO3D_COLUMNS:
1099 format = MATROSKA_VIDEO_STEREOMODE_TYPE_COL_INTERLEAVED_LR;
1100 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
1104 case AV_STEREO3D_FRAMESEQUENCE:
1105 format = MATROSKA_VIDEO_STEREOMODE_TYPE_BOTH_EYES_BLOCK_LR;
1106 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
1114 if (format == MATROSKA_VIDEO_STEREOMODE_TYPE_NB)
1117 // if webm, do not write unsupported modes
1118 if ((mode == MODE_WEBM &&
1119 format > MATROSKA_VIDEO_STEREOMODE_TYPE_TOP_BOTTOM &&
1120 format != MATROSKA_VIDEO_STEREOMODE_TYPE_RIGHT_LEFT)
1121 || format >= MATROSKA_VIDEO_STEREOMODE_TYPE_NB) {
1122 av_log(s, AV_LOG_ERROR,
1123 "The specified stereo mode is not valid.\n");
1124 format = MATROSKA_VIDEO_STEREOMODE_TYPE_NB;
1125 return AVERROR(EINVAL);
1128 // write StereoMode if format is valid
1129 put_ebml_uint(pb, MATROSKA_ID_VIDEOSTEREOMODE, format);
1134 static int mkv_write_track(AVFormatContext *s, MatroskaMuxContext *mkv,
1135 int i, AVIOContext *pb, int default_stream_exists)
1137 AVStream *st = s->streams[i];
1138 AVCodecParameters *par = st->codecpar;
1139 ebml_master subinfo, track;
1142 int bit_depth = av_get_bits_per_sample(par->codec_id);
1143 int sample_rate = par->sample_rate;
1144 int output_sample_rate = 0;
1145 int display_width_div = 1;
1146 int display_height_div = 1;
1148 AVDictionaryEntry *tag;
1150 if (par->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
1151 mkv->have_attachments = 1;
1155 if (par->codec_type == AVMEDIA_TYPE_AUDIO) {
1156 if (!bit_depth && par->codec_id != AV_CODEC_ID_ADPCM_G726) {
1157 if (par->bits_per_raw_sample)
1158 bit_depth = par->bits_per_raw_sample;
1160 bit_depth = av_get_bytes_per_sample(par->format) << 3;
1163 bit_depth = par->bits_per_coded_sample;
1166 if (par->codec_id == AV_CODEC_ID_AAC) {
1167 ret = get_aac_sample_rates(s, par, &sample_rate, &output_sample_rate);
1172 track = start_ebml_master(pb, MATROSKA_ID_TRACKENTRY, 0);
1173 put_ebml_uint (pb, MATROSKA_ID_TRACKNUMBER,
1174 mkv->is_dash ? mkv->dash_track_number : i + 1);
1175 put_ebml_uint (pb, MATROSKA_ID_TRACKUID,
1176 mkv->is_dash ? mkv->dash_track_number : i + 1);
1177 put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0); // no lacing (yet)
1179 if ((tag = av_dict_get(st->metadata, "title", NULL, 0)))
1180 put_ebml_string(pb, MATROSKA_ID_TRACKNAME, tag->value);
1181 tag = av_dict_get(st->metadata, "language", NULL, 0);
1182 if (mkv->mode != MODE_WEBM || par->codec_id != AV_CODEC_ID_WEBVTT) {
1183 put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag && tag->value ? tag->value:"und");
1184 } else if (tag && tag->value) {
1185 put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag->value);
1188 // The default value for TRACKFLAGDEFAULT is 1, so add element
1189 // if we need to clear it.
1190 if (default_stream_exists && !(st->disposition & AV_DISPOSITION_DEFAULT))
1191 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGDEFAULT, !!(st->disposition & AV_DISPOSITION_DEFAULT));
1193 if (st->disposition & AV_DISPOSITION_FORCED)
1194 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGFORCED, 1);
1196 if (mkv->mode == MODE_WEBM && par->codec_id == AV_CODEC_ID_WEBVTT) {
1197 const char *codec_id;
1198 if (st->disposition & AV_DISPOSITION_CAPTIONS) {
1199 codec_id = "D_WEBVTT/CAPTIONS";
1200 native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
1201 } else if (st->disposition & AV_DISPOSITION_DESCRIPTIONS) {
1202 codec_id = "D_WEBVTT/DESCRIPTIONS";
1203 native_id = MATROSKA_TRACK_TYPE_METADATA;
1204 } else if (st->disposition & AV_DISPOSITION_METADATA) {
1205 codec_id = "D_WEBVTT/METADATA";
1206 native_id = MATROSKA_TRACK_TYPE_METADATA;
1208 codec_id = "D_WEBVTT/SUBTITLES";
1209 native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
1211 put_ebml_string(pb, MATROSKA_ID_CODECID, codec_id);
1213 // look for a codec ID string specific to mkv to use,
1214 // if none are found, use AVI codes
1215 if (par->codec_id != AV_CODEC_ID_RAWVIDEO || par->codec_tag) {
1216 for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
1217 if (ff_mkv_codec_tags[j].id == par->codec_id && par->codec_id != AV_CODEC_ID_FFV1) {
1218 put_ebml_string(pb, MATROSKA_ID_CODECID, ff_mkv_codec_tags[j].str);
1224 if (mkv->allow_raw_vfw) {
1227 av_log(s, AV_LOG_ERROR, "Raw RGB is not supported Natively in Matroska, you can use AVI or NUT or\n"
1228 "If you would like to store it anyway using VFW mode, enable allow_raw_vfw (-allow_raw_vfw 1)\n");
1229 return AVERROR(EINVAL);
1234 if (par->codec_type == AVMEDIA_TYPE_AUDIO && par->initial_padding && par->codec_id == AV_CODEC_ID_OPUS) {
1235 int64_t codecdelay = av_rescale_q(par->initial_padding,
1236 (AVRational){ 1, 48000 },
1237 (AVRational){ 1, 1000000000 });
1238 if (codecdelay < 0) {
1239 av_log(s, AV_LOG_ERROR, "Initial padding is invalid\n");
1240 return AVERROR(EINVAL);
1242 // mkv->tracks[i].ts_offset = av_rescale_q(par->initial_padding,
1243 // (AVRational){ 1, par->sample_rate },
1246 put_ebml_uint(pb, MATROSKA_ID_CODECDELAY, codecdelay);
1248 if (par->codec_id == AV_CODEC_ID_OPUS) {
1249 put_ebml_uint(pb, MATROSKA_ID_SEEKPREROLL, OPUS_SEEK_PREROLL);
1252 if (mkv->mode == MODE_WEBM && !(par->codec_id == AV_CODEC_ID_VP8 ||
1253 par->codec_id == AV_CODEC_ID_VP9 ||
1254 par->codec_id == AV_CODEC_ID_OPUS ||
1255 par->codec_id == AV_CODEC_ID_VORBIS ||
1256 par->codec_id == AV_CODEC_ID_WEBVTT)) {
1257 av_log(s, AV_LOG_ERROR,
1258 "Only VP8 or VP9 video and Vorbis or Opus audio and WebVTT subtitles are supported for WebM.\n");
1259 return AVERROR(EINVAL);
1262 switch (par->codec_type) {
1263 case AVMEDIA_TYPE_VIDEO:
1264 mkv->have_video = 1;
1265 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_VIDEO);
1267 if( st->avg_frame_rate.num > 0 && st->avg_frame_rate.den > 0
1268 && av_cmp_q(av_inv_q(st->avg_frame_rate), st->time_base) > 0)
1269 put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, 1000000000LL * st->avg_frame_rate.den / st->avg_frame_rate.num);
1271 put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, 1000000000LL * st->time_base.num / st->time_base.den);
1274 ff_codec_get_tag(ff_codec_movvideo_tags, par->codec_id) &&
1275 ((!ff_codec_get_tag(ff_codec_bmp_tags, par->codec_id) && par->codec_id != AV_CODEC_ID_RAWVIDEO) ||
1276 par->codec_id == AV_CODEC_ID_SVQ1 ||
1277 par->codec_id == AV_CODEC_ID_SVQ3 ||
1278 par->codec_id == AV_CODEC_ID_CINEPAK))
1282 put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");
1283 else if (!native_id) {
1284 // if there is no mkv-specific codec ID, use VFW mode
1285 put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");
1286 mkv->tracks[i].write_dts = 1;
1287 s->internal->avoid_negative_ts_use_pts = 0;
1290 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
1292 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , par->width);
1293 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, par->height);
1295 mkv_write_field_order(pb, mkv->mode, par->field_order);
1297 // check both side data and metadata for stereo information,
1298 // write the result to the bitstream if any is found
1299 ret = mkv_write_stereo_mode(s, pb, st, mkv->mode,
1301 &display_height_div);
1305 if (((tag = av_dict_get(st->metadata, "alpha_mode", NULL, 0)) && atoi(tag->value)) ||
1306 ((tag = av_dict_get( s->metadata, "alpha_mode", NULL, 0)) && atoi(tag->value)) ||
1307 (par->format == AV_PIX_FMT_YUVA420P)) {
1308 put_ebml_uint(pb, MATROSKA_ID_VIDEOALPHAMODE, 1);
1311 // write DisplayWidth and DisplayHeight, they contain the size of
1312 // a single source view and/or the display aspect ratio
1313 if (st->sample_aspect_ratio.num) {
1314 int64_t d_width = av_rescale(par->width, st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
1315 if (d_width > INT_MAX) {
1316 av_log(s, AV_LOG_ERROR, "Overflow in display width\n");
1317 return AVERROR(EINVAL);
1319 if (d_width != par->width || display_width_div != 1 || display_height_div != 1) {
1320 if (mkv->mode == MODE_WEBM || display_width_div != 1 || display_height_div != 1) {
1321 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , d_width / display_width_div);
1322 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, par->height / display_height_div);
1324 AVRational display_aspect_ratio;
1325 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
1326 par->width * (int64_t)st->sample_aspect_ratio.num,
1327 par->height * (int64_t)st->sample_aspect_ratio.den,
1329 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH, display_aspect_ratio.num);
1330 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, display_aspect_ratio.den);
1331 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYUNIT, MATROSKA_VIDEO_DISPLAYUNIT_DAR);
1334 } else if (display_width_div != 1 || display_height_div != 1) {
1335 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , par->width / display_width_div);
1336 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, par->height / display_height_div);
1337 } else if (mkv->mode != MODE_WEBM)
1338 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYUNIT, MATROSKA_VIDEO_DISPLAYUNIT_UNKNOWN);
1340 if (par->codec_id == AV_CODEC_ID_RAWVIDEO) {
1341 uint32_t color_space = av_le2ne32(par->codec_tag);
1342 put_ebml_binary(pb, MATROSKA_ID_VIDEOCOLORSPACE, &color_space, sizeof(color_space));
1344 ret = mkv_write_video_color(pb, par, st);
1347 ret = mkv_write_video_projection(s, pb, st);
1350 end_ebml_master(pb, subinfo);
1353 case AVMEDIA_TYPE_AUDIO:
1354 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_AUDIO);
1357 // no mkv-specific ID, use ACM mode
1358 put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");
1360 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);
1361 put_ebml_uint (pb, MATROSKA_ID_AUDIOCHANNELS , par->channels);
1362 put_ebml_float (pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, sample_rate);
1363 if (output_sample_rate)
1364 put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
1366 put_ebml_uint(pb, MATROSKA_ID_AUDIOBITDEPTH, bit_depth);
1367 end_ebml_master(pb, subinfo);
1370 case AVMEDIA_TYPE_SUBTITLE:
1372 av_log(s, AV_LOG_ERROR, "Subtitle codec %d is not supported.\n", par->codec_id);
1373 return AVERROR(ENOSYS);
1376 if (mkv->mode != MODE_WEBM || par->codec_id != AV_CODEC_ID_WEBVTT)
1377 native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
1379 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, native_id);
1382 av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.\n");
1383 return AVERROR(EINVAL);
1386 if (mkv->mode != MODE_WEBM || par->codec_id != AV_CODEC_ID_WEBVTT) {
1387 mkv->tracks[i].codecpriv_offset = avio_tell(pb);
1388 ret = mkv_write_codecprivate(s, pb, par, native_id, qt_id);
1393 end_ebml_master(pb, track);
1398 static int mkv_write_tracks(AVFormatContext *s)
1400 MatroskaMuxContext *mkv = s->priv_data;
1401 AVIOContext *pb = s->pb;
1402 int i, ret, default_stream_exists = 0;
1404 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TRACKS, avio_tell(pb));
1408 ret = start_ebml_master_crc32(pb, &mkv->tracks_bc, mkv, &mkv->tracks_master, MATROSKA_ID_TRACKS, 0);
1412 for (i = 0; i < s->nb_streams; i++) {
1413 AVStream *st = s->streams[i];
1414 default_stream_exists |= st->disposition & AV_DISPOSITION_DEFAULT;
1416 for (i = 0; i < s->nb_streams; i++) {
1417 ret = mkv_write_track(s, mkv, i, mkv->tracks_bc, default_stream_exists);
1422 if ((pb->seekable & AVIO_SEEKABLE_NORMAL) && !mkv->is_live)
1423 end_ebml_master_crc32_preliminary(pb, &mkv->tracks_bc, mkv, mkv->tracks_master);
1425 end_ebml_master_crc32(pb, &mkv->tracks_bc, mkv, mkv->tracks_master);
1430 static int mkv_write_chapters(AVFormatContext *s)
1432 MatroskaMuxContext *mkv = s->priv_data;
1433 AVIOContext *dyn_cp, *pb = s->pb;
1434 ebml_master chapters, editionentry;
1435 AVRational scale = {1, 1E9};
1438 if (!s->nb_chapters || mkv->wrote_chapters)
1441 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CHAPTERS, avio_tell(pb));
1442 if (ret < 0) return ret;
1444 ret = start_ebml_master_crc32(pb, &dyn_cp, mkv, &chapters, MATROSKA_ID_CHAPTERS, 0);
1445 if (ret < 0) return ret;
1447 editionentry = start_ebml_master(dyn_cp, MATROSKA_ID_EDITIONENTRY, 0);
1448 put_ebml_uint(dyn_cp, MATROSKA_ID_EDITIONFLAGDEFAULT, 1);
1449 put_ebml_uint(dyn_cp, MATROSKA_ID_EDITIONFLAGHIDDEN , 0);
1450 for (i = 0; i < s->nb_chapters; i++) {
1451 ebml_master chapteratom, chapterdisplay;
1452 AVChapter *c = s->chapters[i];
1453 int64_t chapterstart = av_rescale_q(c->start, c->time_base, scale);
1454 int64_t chapterend = av_rescale_q(c->end, c->time_base, scale);
1455 AVDictionaryEntry *t = NULL;
1456 if (chapterstart < 0 || chapterstart > chapterend || chapterend < 0) {
1457 av_log(s, AV_LOG_ERROR,
1458 "Invalid chapter start (%"PRId64") or end (%"PRId64").\n",
1459 chapterstart, chapterend);
1460 return AVERROR_INVALIDDATA;
1463 chapteratom = start_ebml_master(dyn_cp, MATROSKA_ID_CHAPTERATOM, 0);
1464 put_ebml_uint(dyn_cp, MATROSKA_ID_CHAPTERUID, c->id + mkv->chapter_id_offset);
1465 put_ebml_uint(dyn_cp, MATROSKA_ID_CHAPTERTIMESTART, chapterstart);
1466 put_ebml_uint(dyn_cp, MATROSKA_ID_CHAPTERTIMEEND, chapterend);
1467 put_ebml_uint(dyn_cp, MATROSKA_ID_CHAPTERFLAGHIDDEN , 0);
1468 put_ebml_uint(dyn_cp, MATROSKA_ID_CHAPTERFLAGENABLED, 1);
1469 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
1470 chapterdisplay = start_ebml_master(dyn_cp, MATROSKA_ID_CHAPTERDISPLAY, 0);
1471 put_ebml_string(dyn_cp, MATROSKA_ID_CHAPSTRING, t->value);
1472 put_ebml_string(dyn_cp, MATROSKA_ID_CHAPLANG , "und");
1473 end_ebml_master(dyn_cp, chapterdisplay);
1475 end_ebml_master(dyn_cp, chapteratom);
1477 end_ebml_master(dyn_cp, editionentry);
1478 end_ebml_master_crc32(pb, &dyn_cp, mkv, chapters);
1480 mkv->wrote_chapters = 1;
1484 static int mkv_write_simpletag(AVIOContext *pb, AVDictionaryEntry *t)
1486 uint8_t *key = av_strdup(t->key);
1488 const uint8_t *lang = NULL;
1492 return AVERROR(ENOMEM);
1494 if ((p = strrchr(p, '-')) &&
1495 (lang = ff_convert_lang_to(p + 1, AV_LANG_ISO639_2_BIBL)))
1502 else if (*p >= 'a' && *p <= 'z')
1507 tag = start_ebml_master(pb, MATROSKA_ID_SIMPLETAG, 0);
1508 put_ebml_string(pb, MATROSKA_ID_TAGNAME, key);
1510 put_ebml_string(pb, MATROSKA_ID_TAGLANG, lang);
1511 put_ebml_string(pb, MATROSKA_ID_TAGSTRING, t->value);
1512 end_ebml_master(pb, tag);
1518 static int mkv_write_tag_targets(AVFormatContext *s,
1519 unsigned int elementid, unsigned int uid,
1520 ebml_master *tags, ebml_master* tag)
1523 MatroskaMuxContext *mkv = s->priv_data;
1524 ebml_master targets;
1528 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TAGS, avio_tell(s->pb));
1529 if (ret < 0) return ret;
1531 start_ebml_master_crc32(s->pb, &mkv->tags_bc, mkv, tags, MATROSKA_ID_TAGS, 0);
1535 *tag = start_ebml_master(pb, MATROSKA_ID_TAG, 0);
1536 targets = start_ebml_master(pb, MATROSKA_ID_TAGTARGETS, 0);
1538 put_ebml_uint(pb, elementid, uid);
1539 end_ebml_master(pb, targets);
1543 static int mkv_check_tag_name(const char *name, unsigned int elementid)
1545 return av_strcasecmp(name, "title") &&
1546 av_strcasecmp(name, "stereo_mode") &&
1547 av_strcasecmp(name, "creation_time") &&
1548 av_strcasecmp(name, "encoding_tool") &&
1549 av_strcasecmp(name, "duration") &&
1550 (elementid != MATROSKA_ID_TAGTARGETS_TRACKUID ||
1551 av_strcasecmp(name, "language")) &&
1552 (elementid != MATROSKA_ID_TAGTARGETS_ATTACHUID ||
1553 (av_strcasecmp(name, "filename") &&
1554 av_strcasecmp(name, "mimetype")));
1557 static int mkv_write_tag(AVFormatContext *s, AVDictionary *m, unsigned int elementid,
1558 unsigned int uid, ebml_master *tags)
1560 MatroskaMuxContext *mkv = s->priv_data;
1563 AVDictionaryEntry *t = NULL;
1565 ret = mkv_write_tag_targets(s, elementid, uid, tags, &tag);
1569 while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX))) {
1570 if (mkv_check_tag_name(t->key, elementid)) {
1571 ret = mkv_write_simpletag(mkv->tags_bc, t);
1577 end_ebml_master(mkv->tags_bc, tag);
1581 static int mkv_check_tag(AVDictionary *m, unsigned int elementid)
1583 AVDictionaryEntry *t = NULL;
1585 while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX)))
1586 if (mkv_check_tag_name(t->key, elementid))
1592 static int mkv_write_tags(AVFormatContext *s)
1594 MatroskaMuxContext *mkv = s->priv_data;
1597 ff_metadata_conv_ctx(s, ff_mkv_metadata_conv, NULL);
1599 if (mkv_check_tag(s->metadata, 0)) {
1600 ret = mkv_write_tag(s, s->metadata, 0, 0, &mkv->tags);
1601 if (ret < 0) return ret;
1604 for (i = 0; i < s->nb_streams; i++) {
1605 AVStream *st = s->streams[i];
1607 if (st->codecpar->codec_type == AVMEDIA_TYPE_ATTACHMENT)
1610 if (!mkv_check_tag(st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID))
1613 ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &mkv->tags);
1614 if (ret < 0) return ret;
1617 if ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) && !mkv->is_live) {
1618 for (i = 0; i < s->nb_streams; i++) {
1620 AVStream *st = s->streams[i];
1621 ebml_master tag_target;
1624 if (st->codecpar->codec_type == AVMEDIA_TYPE_ATTACHMENT)
1627 mkv_write_tag_targets(s, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &mkv->tags, &tag_target);
1630 tag = start_ebml_master(pb, MATROSKA_ID_SIMPLETAG, 0);
1631 put_ebml_string(pb, MATROSKA_ID_TAGNAME, "DURATION");
1632 mkv->stream_duration_offsets[i] = avio_tell(pb);
1634 // Reserve space to write duration as a 20-byte string.
1635 // 2 (ebml id) + 1 (data size) + 20 (data)
1636 put_ebml_void(pb, 23);
1637 end_ebml_master(pb, tag);
1638 end_ebml_master(pb, tag_target);
1642 for (i = 0; i < s->nb_chapters; i++) {
1643 AVChapter *ch = s->chapters[i];
1645 if (!mkv_check_tag(ch->metadata, MATROSKA_ID_TAGTARGETS_CHAPTERUID))
1648 ret = mkv_write_tag(s, ch->metadata, MATROSKA_ID_TAGTARGETS_CHAPTERUID, ch->id + mkv->chapter_id_offset, &mkv->tags);
1649 if (ret < 0) return ret;
1652 if (mkv->have_attachments) {
1653 for (i = 0; i < mkv->attachments->num_entries; i++) {
1654 mkv_attachment *attachment = &mkv->attachments->entries[i];
1655 AVStream *st = s->streams[attachment->stream_idx];
1657 if (!mkv_check_tag(st->metadata, MATROSKA_ID_TAGTARGETS_ATTACHUID))
1660 ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_ATTACHUID, attachment->fileuid, &mkv->tags);
1666 if (mkv->tags.pos) {
1667 if ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) && !mkv->is_live)
1668 end_ebml_master_crc32_preliminary(s->pb, &mkv->tags_bc, mkv, mkv->tags);
1670 end_ebml_master_crc32(s->pb, &mkv->tags_bc, mkv, mkv->tags);
1675 static int mkv_write_attachments(AVFormatContext *s)
1677 MatroskaMuxContext *mkv = s->priv_data;
1678 AVIOContext *dyn_cp, *pb = s->pb;
1679 ebml_master attachments;
1683 if (!mkv->have_attachments)
1686 mkv->attachments = av_mallocz(sizeof(*mkv->attachments));
1687 if (!mkv->attachments)
1688 return AVERROR(ENOMEM);
1690 av_lfg_init(&c, av_get_random_seed());
1692 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_ATTACHMENTS, avio_tell(pb));
1693 if (ret < 0) return ret;
1695 ret = start_ebml_master_crc32(pb, &dyn_cp, mkv, &attachments, MATROSKA_ID_ATTACHMENTS, 0);
1696 if (ret < 0) return ret;
1698 for (i = 0; i < s->nb_streams; i++) {
1699 AVStream *st = s->streams[i];
1700 ebml_master attached_file;
1701 mkv_attachment *attachment = mkv->attachments->entries;
1702 AVDictionaryEntry *t;
1703 const char *mimetype = NULL;
1706 if (st->codecpar->codec_type != AVMEDIA_TYPE_ATTACHMENT)
1709 attachment = av_realloc_array(attachment, mkv->attachments->num_entries + 1, sizeof(mkv_attachment));
1711 return AVERROR(ENOMEM);
1712 mkv->attachments->entries = attachment;
1714 attached_file = start_ebml_master(dyn_cp, MATROSKA_ID_ATTACHEDFILE, 0);
1716 if (t = av_dict_get(st->metadata, "title", NULL, 0))
1717 put_ebml_string(dyn_cp, MATROSKA_ID_FILEDESC, t->value);
1718 if (!(t = av_dict_get(st->metadata, "filename", NULL, 0))) {
1719 av_log(s, AV_LOG_ERROR, "Attachment stream %d has no filename tag.\n", i);
1720 return AVERROR(EINVAL);
1722 put_ebml_string(dyn_cp, MATROSKA_ID_FILENAME, t->value);
1723 if (t = av_dict_get(st->metadata, "mimetype", NULL, 0))
1724 mimetype = t->value;
1725 else if (st->codecpar->codec_id != AV_CODEC_ID_NONE ) {
1727 for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
1728 if (ff_mkv_mime_tags[i].id == st->codecpar->codec_id) {
1729 mimetype = ff_mkv_mime_tags[i].str;
1732 for (i = 0; ff_mkv_image_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
1733 if (ff_mkv_image_mime_tags[i].id == st->codecpar->codec_id) {
1734 mimetype = ff_mkv_image_mime_tags[i].str;
1739 av_log(s, AV_LOG_ERROR, "Attachment stream %d has no mimetype tag and "
1740 "it cannot be deduced from the codec id.\n", i);
1741 return AVERROR(EINVAL);
1744 if (s->flags & AVFMT_FLAG_BITEXACT) {
1745 struct AVSHA *sha = av_sha_alloc();
1748 return AVERROR(ENOMEM);
1749 av_sha_init(sha, 160);
1750 av_sha_update(sha, st->codecpar->extradata, st->codecpar->extradata_size);
1751 av_sha_final(sha, digest);
1753 fileuid = AV_RL32(digest);
1755 fileuid = av_lfg_get(&c);
1757 av_log(s, AV_LOG_VERBOSE, "Using %.8"PRIx32" for attachment %d\n",
1758 fileuid, mkv->attachments->num_entries);
1760 put_ebml_string(dyn_cp, MATROSKA_ID_FILEMIMETYPE, mimetype);
1761 put_ebml_binary(dyn_cp, MATROSKA_ID_FILEDATA, st->codecpar->extradata, st->codecpar->extradata_size);
1762 put_ebml_uint(dyn_cp, MATROSKA_ID_FILEUID, fileuid);
1763 end_ebml_master(dyn_cp, attached_file);
1765 mkv->attachments->entries[mkv->attachments->num_entries].stream_idx = i;
1766 mkv->attachments->entries[mkv->attachments->num_entries++].fileuid = fileuid;
1768 end_ebml_master_crc32(pb, &dyn_cp, mkv, attachments);
1773 static int64_t get_metadata_duration(AVFormatContext *s)
1779 AVDictionaryEntry *explicitDuration = av_dict_get(s->metadata, "DURATION", NULL, 0);
1780 if (explicitDuration && (av_parse_time(&us, explicitDuration->value, 1) == 0) && us > 0) {
1781 av_log(s, AV_LOG_DEBUG, "get_metadata_duration found duration in context metadata: %" PRId64 "\n", us);
1785 for (i = 0; i < s->nb_streams; i++) {
1787 AVDictionaryEntry *duration = av_dict_get(s->streams[i]->metadata, "DURATION", NULL, 0);
1789 if (duration && (av_parse_time(&us, duration->value, 1) == 0))
1790 max = FFMAX(max, us);
1793 av_log(s, AV_LOG_DEBUG, "get_metadata_duration returned: %" PRId64 "\n", max);
1797 static int mkv_write_header(AVFormatContext *s)
1799 MatroskaMuxContext *mkv = s->priv_data;
1800 AVIOContext *pb = s->pb;
1801 ebml_master ebml_header;
1802 AVDictionaryEntry *tag;
1803 int ret, i, version = 2;
1804 int64_t creation_time;
1806 if (!strcmp(s->oformat->name, "webm"))
1807 mkv->mode = MODE_WEBM;
1809 mkv->mode = MODE_MATROSKAv2;
1811 if (mkv->mode != MODE_WEBM ||
1812 av_dict_get(s->metadata, "stereo_mode", NULL, 0) ||
1813 av_dict_get(s->metadata, "alpha_mode", NULL, 0))
1816 for (i = 0; i < s->nb_streams; i++) {
1817 if (s->streams[i]->codecpar->codec_id == AV_CODEC_ID_ATRAC3 ||
1818 s->streams[i]->codecpar->codec_id == AV_CODEC_ID_COOK ||
1819 s->streams[i]->codecpar->codec_id == AV_CODEC_ID_RA_288 ||
1820 s->streams[i]->codecpar->codec_id == AV_CODEC_ID_SIPR ||
1821 s->streams[i]->codecpar->codec_id == AV_CODEC_ID_RV10 ||
1822 s->streams[i]->codecpar->codec_id == AV_CODEC_ID_RV20) {
1823 av_log(s, AV_LOG_ERROR,
1824 "The Matroska muxer does not yet support muxing %s\n",
1825 avcodec_get_name(s->streams[i]->codecpar->codec_id));
1826 return AVERROR_PATCHWELCOME;
1828 if (s->streams[i]->codecpar->codec_id == AV_CODEC_ID_OPUS ||
1829 av_dict_get(s->streams[i]->metadata, "stereo_mode", NULL, 0) ||
1830 av_dict_get(s->streams[i]->metadata, "alpha_mode", NULL, 0))
1834 mkv->tracks = av_mallocz_array(s->nb_streams, sizeof(*mkv->tracks));
1836 ret = AVERROR(ENOMEM);
1839 ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
1840 put_ebml_uint (pb, EBML_ID_EBMLVERSION , 1);
1841 put_ebml_uint (pb, EBML_ID_EBMLREADVERSION , 1);
1842 put_ebml_uint (pb, EBML_ID_EBMLMAXIDLENGTH , 4);
1843 put_ebml_uint (pb, EBML_ID_EBMLMAXSIZELENGTH , 8);
1844 put_ebml_string (pb, EBML_ID_DOCTYPE , s->oformat->name);
1845 put_ebml_uint (pb, EBML_ID_DOCTYPEVERSION , version);
1846 put_ebml_uint (pb, EBML_ID_DOCTYPEREADVERSION , 2);
1847 end_ebml_master(pb, ebml_header);
1849 mkv->segment = start_ebml_master(pb, MATROSKA_ID_SEGMENT, 0);
1850 mkv->segment_offset = avio_tell(pb);
1852 // we write 2 seek heads - one at the end of the file to point to each
1853 // cluster, and one at the beginning to point to all other level one
1854 // elements (including the seek head at the end of the file), which
1855 // isn't more than 10 elements if we only write one of each other
1856 // currently defined level 1 element
1857 mkv->main_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 10);
1858 if (!mkv->main_seekhead) {
1859 ret = AVERROR(ENOMEM);
1863 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_INFO, avio_tell(pb));
1864 if (ret < 0) goto fail;
1866 ret = start_ebml_master_crc32(pb, &mkv->info_bc, mkv, &mkv->info, MATROSKA_ID_INFO, 0);
1871 put_ebml_uint(pb, MATROSKA_ID_TIMECODESCALE, 1000000);
1872 if ((tag = av_dict_get(s->metadata, "title", NULL, 0)))
1873 put_ebml_string(pb, MATROSKA_ID_TITLE, tag->value);
1874 if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
1875 put_ebml_string(pb, MATROSKA_ID_MUXINGAPP, LIBAVFORMAT_IDENT);
1876 if ((tag = av_dict_get(s->metadata, "encoding_tool", NULL, 0)))
1877 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, tag->value);
1879 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, LIBAVFORMAT_IDENT);
1881 if (mkv->mode != MODE_WEBM) {
1882 uint32_t segment_uid[4];
1885 av_lfg_init(&lfg, av_get_random_seed());
1887 for (i = 0; i < 4; i++)
1888 segment_uid[i] = av_lfg_get(&lfg);
1890 put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
1893 const char *ident = "Lavf";
1894 put_ebml_string(pb, MATROSKA_ID_MUXINGAPP , ident);
1895 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, ident);
1898 if (ff_parse_creation_time_metadata(s, &creation_time, 0) > 0) {
1899 // Adjust time so it's relative to 2001-01-01 and convert to nanoseconds.
1900 int64_t date_utc = (creation_time - 978307200000000LL) * 1000;
1901 uint8_t date_utc_buf[8];
1902 AV_WB64(date_utc_buf, date_utc);
1903 put_ebml_binary(pb, MATROSKA_ID_DATEUTC, date_utc_buf, 8);
1906 // reserve space for the duration
1908 mkv->duration_offset = avio_tell(pb);
1909 if (!mkv->is_live) {
1910 int64_t metadata_duration = get_metadata_duration(s);
1912 if (s->duration > 0) {
1913 int64_t scaledDuration = av_rescale(s->duration, 1000, AV_TIME_BASE);
1914 put_ebml_float(pb, MATROSKA_ID_DURATION, scaledDuration);
1915 av_log(s, AV_LOG_DEBUG, "Write early duration from recording time = %" PRIu64 "\n", scaledDuration);
1916 } else if (metadata_duration > 0) {
1917 int64_t scaledDuration = av_rescale(metadata_duration, 1000, AV_TIME_BASE);
1918 put_ebml_float(pb, MATROSKA_ID_DURATION, scaledDuration);
1919 av_log(s, AV_LOG_DEBUG, "Write early duration from metadata = %" PRIu64 "\n", scaledDuration);
1921 put_ebml_void(pb, 11); // assumes double-precision float to be written
1924 if ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) && !mkv->is_live)
1925 end_ebml_master_crc32_preliminary(s->pb, &mkv->info_bc, mkv, mkv->info);
1927 end_ebml_master_crc32(s->pb, &mkv->info_bc, mkv, mkv->info);
1930 // initialize stream_duration fields
1931 mkv->stream_durations = av_mallocz(s->nb_streams * sizeof(int64_t));
1932 mkv->stream_duration_offsets = av_mallocz(s->nb_streams * sizeof(int64_t));
1934 ret = mkv_write_tracks(s);
1938 for (i = 0; i < s->nb_chapters; i++)
1939 mkv->chapter_id_offset = FFMAX(mkv->chapter_id_offset, 1LL - s->chapters[i]->id);
1941 if (mkv->mode != MODE_WEBM) {
1942 ret = mkv_write_chapters(s);
1946 ret = mkv_write_attachments(s);
1950 ret = mkv_write_tags(s);
1955 if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) && !mkv->is_live)
1956 mkv_write_seekhead(pb, mkv);
1958 mkv->cues = mkv_start_cues(mkv->segment_offset);
1960 ret = AVERROR(ENOMEM);
1963 if ((pb->seekable & AVIO_SEEKABLE_NORMAL) && mkv->reserve_cues_space) {
1964 mkv->cues_pos = avio_tell(pb);
1965 put_ebml_void(pb, mkv->reserve_cues_space);
1968 av_init_packet(&mkv->cur_audio_pkt);
1969 mkv->cur_audio_pkt.size = 0;
1970 mkv->cluster_pos = -1;
1974 // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1975 // after 4k and on a keyframe
1976 if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
1977 if (mkv->cluster_time_limit < 0)
1978 mkv->cluster_time_limit = 5000;
1979 if (mkv->cluster_size_limit < 0)
1980 mkv->cluster_size_limit = 5 * 1024 * 1024;
1982 if (mkv->cluster_time_limit < 0)
1983 mkv->cluster_time_limit = 1000;
1984 if (mkv->cluster_size_limit < 0)
1985 mkv->cluster_size_limit = 32 * 1024;
1994 static int mkv_blockgroup_size(int pkt_size)
1996 int size = pkt_size + 4;
1997 size += ebml_num_size(size);
1998 size += 2; // EBML ID for block and block duration
1999 size += 8; // max size of block duration
2000 size += ebml_num_size(size);
2001 size += 1; // blockgroup EBML ID
2005 static int mkv_strip_wavpack(const uint8_t *src, uint8_t **pdst, int *size)
2012 dst = av_malloc(srclen);
2014 return AVERROR(ENOMEM);
2016 while (srclen >= WV_HEADER_SIZE) {
2019 ret = ff_wv_parse_header(&header, src);
2022 src += WV_HEADER_SIZE;
2023 srclen -= WV_HEADER_SIZE;
2025 if (srclen < header.blocksize) {
2026 ret = AVERROR_INVALIDDATA;
2030 if (header.initial) {
2031 AV_WL32(dst + offset, header.samples);
2034 AV_WL32(dst + offset, header.flags);
2035 AV_WL32(dst + offset + 4, header.crc);
2038 if (!(header.initial && header.final)) {
2039 AV_WL32(dst + offset, header.blocksize);
2043 memcpy(dst + offset, src, header.blocksize);
2044 src += header.blocksize;
2045 srclen -= header.blocksize;
2046 offset += header.blocksize;
2058 static void mkv_write_block(AVFormatContext *s, AVIOContext *pb,
2059 unsigned int blockid, AVPacket *pkt, int keyframe)
2061 MatroskaMuxContext *mkv = s->priv_data;
2062 AVCodecParameters *par = s->streams[pkt->stream_index]->codecpar;
2063 uint8_t *data = NULL, *side_data = NULL;
2064 int offset = 0, size = pkt->size, side_data_size = 0;
2065 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
2066 uint64_t additional_id = 0;
2067 int64_t discard_padding = 0;
2068 uint8_t track_number = (mkv->is_dash ? mkv->dash_track_number : (pkt->stream_index + 1));
2069 ebml_master block_group, block_additions, block_more;
2071 av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
2072 "pts %" PRId64 ", dts %" PRId64 ", duration %" PRId64 ", keyframe %d\n",
2073 avio_tell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration,
2075 if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 0 &&
2076 (AV_RB24(par->extradata) == 1 || AV_RB32(par->extradata) == 1))
2077 ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
2078 else if (par->codec_id == AV_CODEC_ID_HEVC && par->extradata_size > 6 &&
2079 (AV_RB24(par->extradata) == 1 || AV_RB32(par->extradata) == 1))
2080 /* extradata is Annex B, assume the bitstream is too and convert it */
2081 ff_hevc_annexb2mp4_buf(pkt->data, &data, &size, 0, NULL);
2082 else if (par->codec_id == AV_CODEC_ID_WAVPACK) {
2083 int ret = mkv_strip_wavpack(pkt->data, &data, &size);
2085 av_log(s, AV_LOG_ERROR, "Error stripping a WavPack packet.\n");
2091 if (par->codec_id == AV_CODEC_ID_PRORES && size >= 8) {
2092 /* Matroska specification requires to remove the first QuickTime atom
2098 side_data = av_packet_get_side_data(pkt,
2099 AV_PKT_DATA_SKIP_SAMPLES,
2102 if (side_data && side_data_size >= 10) {
2103 discard_padding = av_rescale_q(AV_RL32(side_data + 4),
2104 (AVRational){1, par->sample_rate},
2105 (AVRational){1, 1000000000});
2108 side_data = av_packet_get_side_data(pkt,
2109 AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,
2112 additional_id = AV_RB64(side_data);
2114 side_data_size -= 8;
2117 if ((side_data_size && additional_id == 1) || discard_padding) {
2118 block_group = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, 0);
2119 blockid = MATROSKA_ID_BLOCK;
2122 put_ebml_id(pb, blockid);
2123 put_ebml_num(pb, size + 4, 0);
2124 // this assumes stream_index is less than 126
2125 avio_w8(pb, 0x80 | track_number);
2126 avio_wb16(pb, ts - mkv->cluster_pts);
2127 avio_w8(pb, (blockid == MATROSKA_ID_SIMPLEBLOCK && keyframe) ? (1 << 7) : 0);
2128 avio_write(pb, data + offset, size);
2129 if (data != pkt->data)
2132 if (blockid == MATROSKA_ID_BLOCK && !keyframe) {
2133 put_ebml_sint(pb, MATROSKA_ID_BLOCKREFERENCE,
2134 mkv->last_track_timestamp[track_number - 1]);
2136 mkv->last_track_timestamp[track_number - 1] = ts - mkv->cluster_pts;
2138 if (discard_padding) {
2139 put_ebml_sint(pb, MATROSKA_ID_DISCARDPADDING, discard_padding);
2142 if (side_data_size && additional_id == 1) {
2143 block_additions = start_ebml_master(pb, MATROSKA_ID_BLOCKADDITIONS, 0);
2144 block_more = start_ebml_master(pb, MATROSKA_ID_BLOCKMORE, 0);
2145 put_ebml_uint(pb, MATROSKA_ID_BLOCKADDID, 1);
2146 put_ebml_id(pb, MATROSKA_ID_BLOCKADDITIONAL);
2147 put_ebml_num(pb, side_data_size, 0);
2148 avio_write(pb, side_data, side_data_size);
2149 end_ebml_master(pb, block_more);
2150 end_ebml_master(pb, block_additions);
2152 if ((side_data_size && additional_id == 1) || discard_padding) {
2153 end_ebml_master(pb, block_group);
2157 static int mkv_write_vtt_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
2159 MatroskaMuxContext *mkv = s->priv_data;
2160 ebml_master blockgroup;
2161 int id_size, settings_size, size;
2162 uint8_t *id, *settings;
2163 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
2164 const int flags = 0;
2167 id = av_packet_get_side_data(pkt, AV_PKT_DATA_WEBVTT_IDENTIFIER,
2171 settings = av_packet_get_side_data(pkt, AV_PKT_DATA_WEBVTT_SETTINGS,
2174 size = id_size + 1 + settings_size + 1 + pkt->size;
2176 av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
2177 "pts %" PRId64 ", dts %" PRId64 ", duration %" PRId64 ", flags %d\n",
2178 avio_tell(pb), size, pkt->pts, pkt->dts, pkt->duration, flags);
2180 blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(size));
2182 put_ebml_id(pb, MATROSKA_ID_BLOCK);
2183 put_ebml_num(pb, size + 4, 0);
2184 avio_w8(pb, 0x80 | (pkt->stream_index + 1)); // this assumes stream_index is less than 126
2185 avio_wb16(pb, ts - mkv->cluster_pts);
2187 avio_printf(pb, "%.*s\n%.*s\n%.*s", id_size, id, settings_size, settings, pkt->size, pkt->data);
2189 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, pkt->duration);
2190 end_ebml_master(pb, blockgroup);
2192 return pkt->duration;
2195 static void mkv_start_new_cluster(AVFormatContext *s, AVPacket *pkt)
2197 MatroskaMuxContext *mkv = s->priv_data;
2199 end_ebml_master_crc32(s->pb, &mkv->dyn_bc, mkv, mkv->cluster);
2200 mkv->cluster_pos = -1;
2201 if (s->pb->seekable & AVIO_SEEKABLE_NORMAL)
2202 av_log(s, AV_LOG_DEBUG,
2203 "Starting new cluster at offset %" PRIu64 " bytes, "
2204 "pts %" PRIu64 "dts %" PRIu64 "\n",
2205 avio_tell(s->pb), pkt->pts, pkt->dts);
2207 av_log(s, AV_LOG_DEBUG, "Starting new cluster, "
2208 "pts %" PRIu64 "dts %" PRIu64 "\n",
2209 pkt->pts, pkt->dts);
2213 static int mkv_check_new_extra_data(AVFormatContext *s, AVPacket *pkt)
2215 MatroskaMuxContext *mkv = s->priv_data;
2216 mkv_track *track = &mkv->tracks[pkt->stream_index];
2217 AVCodecParameters *par = s->streams[pkt->stream_index]->codecpar;
2219 int side_data_size = 0, ret;
2221 side_data = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
2224 switch (par->codec_id) {
2225 case AV_CODEC_ID_FLAC:
2226 if (side_data_size && (s->pb->seekable & AVIO_SEEKABLE_NORMAL) && !mkv->is_live) {
2227 AVCodecParameters *codecpriv_par;
2229 if (side_data_size != par->extradata_size) {
2230 av_log(s, AV_LOG_ERROR, "Invalid FLAC STREAMINFO metadata for output stream %d\n",
2232 return AVERROR(EINVAL);
2234 codecpriv_par = avcodec_parameters_alloc();
2236 return AVERROR(ENOMEM);
2237 ret = avcodec_parameters_copy(codecpriv_par, par);
2239 avcodec_parameters_free(&codecpriv_par);
2242 memcpy(codecpriv_par->extradata, side_data, side_data_size);
2243 curpos = avio_tell(mkv->tracks_bc);
2244 avio_seek(mkv->tracks_bc, track->codecpriv_offset, SEEK_SET);
2245 mkv_write_codecprivate(s, mkv->tracks_bc, codecpriv_par, 1, 0);
2246 avio_seek(mkv->tracks_bc, curpos, SEEK_SET);
2247 avcodec_parameters_free(&codecpriv_par);
2252 av_log(s, AV_LOG_DEBUG, "Ignoring new extradata in a packet for stream %d.\n", pkt->stream_index);
2259 static int mkv_write_packet_internal(AVFormatContext *s, AVPacket *pkt, int add_cue)
2261 MatroskaMuxContext *mkv = s->priv_data;
2262 AVIOContext *pb = s->pb;
2263 AVCodecParameters *par = s->streams[pkt->stream_index]->codecpar;
2264 int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
2265 int duration = pkt->duration;
2267 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
2268 int64_t relative_packet_pos;
2269 int dash_tracknum = mkv->is_dash ? mkv->dash_track_number : pkt->stream_index + 1;
2271 if (ts == AV_NOPTS_VALUE) {
2272 av_log(s, AV_LOG_ERROR, "Can't write packet with unknown timestamp\n");
2273 return AVERROR(EINVAL);
2275 ts += mkv->tracks[pkt->stream_index].ts_offset;
2277 if (mkv->cluster_pos != -1) {
2278 int64_t cluster_time = ts - mkv->cluster_pts + mkv->tracks[pkt->stream_index].ts_offset;
2279 if ((int16_t)cluster_time != cluster_time) {
2280 av_log(s, AV_LOG_WARNING, "Starting new cluster due to timestamp\n");
2281 mkv_start_new_cluster(s, pkt);
2285 if (mkv->cluster_pos == -1) {
2286 mkv->cluster_pos = avio_tell(s->pb);
2287 ret = start_ebml_master_crc32(s->pb, &mkv->dyn_bc, mkv, &mkv->cluster, MATROSKA_ID_CLUSTER, 0);
2290 put_ebml_uint(mkv->dyn_bc, MATROSKA_ID_CLUSTERTIMECODE, FFMAX(0, ts));
2291 mkv->cluster_pts = FFMAX(0, ts);
2295 relative_packet_pos = avio_tell(pb);
2297 if (par->codec_type != AVMEDIA_TYPE_SUBTITLE) {
2298 mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe);
2299 if ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) && (par->codec_type == AVMEDIA_TYPE_VIDEO && keyframe || add_cue)) {
2300 ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, dash_tracknum, ts, mkv->cluster_pos, relative_packet_pos, -1);
2301 if (ret < 0) return ret;
2304 if (par->codec_id == AV_CODEC_ID_WEBVTT) {
2305 duration = mkv_write_vtt_blocks(s, pb, pkt);
2307 ebml_master blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
2308 mkv_blockgroup_size(pkt->size));
2310 #if FF_API_CONVERGENCE_DURATION
2311 FF_DISABLE_DEPRECATION_WARNINGS
2312 /* For backward compatibility, prefer convergence_duration. */
2313 if (pkt->convergence_duration > 0) {
2314 duration = pkt->convergence_duration;
2316 FF_ENABLE_DEPRECATION_WARNINGS
2318 /* All subtitle blocks are considered to be keyframes. */
2319 mkv_write_block(s, pb, MATROSKA_ID_BLOCK, pkt, 1);
2320 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
2321 end_ebml_master(pb, blockgroup);
2324 if (s->pb->seekable & AVIO_SEEKABLE_NORMAL) {
2325 ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, dash_tracknum, ts,
2326 mkv->cluster_pos, relative_packet_pos, duration);
2332 mkv->duration = FFMAX(mkv->duration, ts + duration);
2334 if (mkv->stream_durations)
2335 mkv->stream_durations[pkt->stream_index] =
2336 FFMAX(mkv->stream_durations[pkt->stream_index], ts + duration);
2341 static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
2343 MatroskaMuxContext *mkv = s->priv_data;
2344 int codec_type = s->streams[pkt->stream_index]->codecpar->codec_type;
2345 int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
2347 int64_t cluster_time;
2349 int start_new_cluster;
2351 ret = mkv_check_new_extra_data(s, pkt);
2355 if (mkv->tracks[pkt->stream_index].write_dts)
2356 cluster_time = pkt->dts - mkv->cluster_pts;
2358 cluster_time = pkt->pts - mkv->cluster_pts;
2359 cluster_time += mkv->tracks[pkt->stream_index].ts_offset;
2361 // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
2362 // after 4k and on a keyframe
2363 cluster_size = avio_tell(mkv->dyn_bc);
2365 if (mkv->is_dash && codec_type == AVMEDIA_TYPE_VIDEO) {
2366 // WebM DASH specification states that the first block of every cluster
2367 // has to be a key frame. So for DASH video, we only create a cluster
2368 // on seeing key frames.
2369 start_new_cluster = keyframe;
2370 } else if (mkv->is_dash && codec_type == AVMEDIA_TYPE_AUDIO &&
2371 (mkv->cluster_pos == -1 ||
2372 cluster_time > mkv->cluster_time_limit)) {
2373 // For DASH audio, we create a Cluster based on cluster_time_limit
2374 start_new_cluster = 1;
2375 } else if (!mkv->is_dash &&
2376 (cluster_size > mkv->cluster_size_limit ||
2377 cluster_time > mkv->cluster_time_limit ||
2378 (codec_type == AVMEDIA_TYPE_VIDEO && keyframe &&
2379 cluster_size > 4 * 1024))) {
2380 start_new_cluster = 1;
2382 start_new_cluster = 0;
2385 if (mkv->cluster_pos != -1 && start_new_cluster) {
2386 mkv_start_new_cluster(s, pkt);
2389 if (!mkv->cluster_pos)
2390 avio_write_marker(s->pb,
2391 av_rescale_q(pkt->dts, s->streams[pkt->stream_index]->time_base, AV_TIME_BASE_Q),
2392 keyframe && (mkv->have_video ? codec_type == AVMEDIA_TYPE_VIDEO : 1) ? AVIO_DATA_MARKER_SYNC_POINT : AVIO_DATA_MARKER_BOUNDARY_POINT);
2394 // check if we have an audio packet cached
2395 if (mkv->cur_audio_pkt.size > 0) {
2396 // for DASH audio, a CuePoint has to be added when there is a new cluster.
2397 ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt,
2398 mkv->is_dash ? start_new_cluster : 0);
2399 av_packet_unref(&mkv->cur_audio_pkt);
2401 av_log(s, AV_LOG_ERROR,
2402 "Could not write cached audio packet ret:%d\n", ret);
2407 // buffer an audio packet to ensure the packet containing the video
2408 // keyframe's timecode is contained in the same cluster for WebM
2409 if (codec_type == AVMEDIA_TYPE_AUDIO) {
2410 ret = av_packet_ref(&mkv->cur_audio_pkt, pkt);
2412 ret = mkv_write_packet_internal(s, pkt, 0);
2416 static int mkv_write_flush_packet(AVFormatContext *s, AVPacket *pkt)
2418 MatroskaMuxContext *mkv = s->priv_data;
2421 if (mkv->cluster_pos != -1) {
2422 end_ebml_master_crc32(s->pb, &mkv->dyn_bc, mkv, mkv->cluster);
2423 mkv->cluster_pos = -1;
2424 if (s->pb->seekable & AVIO_SEEKABLE_NORMAL)
2425 av_log(s, AV_LOG_DEBUG,
2426 "Flushing cluster at offset %" PRIu64 " bytes\n",
2429 av_log(s, AV_LOG_DEBUG, "Flushing cluster\n");
2434 return mkv_write_packet(s, pkt);
2437 static int mkv_write_trailer(AVFormatContext *s)
2439 MatroskaMuxContext *mkv = s->priv_data;
2440 AVIOContext *pb = s->pb;
2441 int64_t currentpos, cuespos;
2444 // check if we have an audio packet cached
2445 if (mkv->cur_audio_pkt.size > 0) {
2446 ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt, 0);
2447 av_packet_unref(&mkv->cur_audio_pkt);
2449 av_log(s, AV_LOG_ERROR,
2450 "Could not write cached audio packet ret:%d\n", ret);
2456 end_ebml_master_crc32(pb, &mkv->dyn_bc, mkv, mkv->cluster);
2459 if (mkv->mode != MODE_WEBM) {
2460 ret = mkv_write_chapters(s);
2465 if ((pb->seekable & AVIO_SEEKABLE_NORMAL) && !mkv->is_live) {
2466 if (mkv->cues->num_entries) {
2467 if (mkv->reserve_cues_space) {
2470 currentpos = avio_tell(pb);
2471 avio_seek(pb, mkv->cues_pos, SEEK_SET);
2473 cuespos = mkv_write_cues(s, mkv->cues, mkv->tracks, s->nb_streams);
2474 cues_end = avio_tell(pb);
2475 if (cues_end > cuespos + mkv->reserve_cues_space) {
2476 av_log(s, AV_LOG_ERROR,
2477 "Insufficient space reserved for cues: %d "
2478 "(needed: %" PRId64 ").\n",
2479 mkv->reserve_cues_space, cues_end - cuespos);
2480 return AVERROR(EINVAL);
2483 if (cues_end < cuespos + mkv->reserve_cues_space)
2484 put_ebml_void(pb, mkv->reserve_cues_space -
2485 (cues_end - cuespos));
2487 avio_seek(pb, currentpos, SEEK_SET);
2489 cuespos = mkv_write_cues(s, mkv->cues, mkv->tracks, s->nb_streams);
2492 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CUES,
2498 mkv_write_seekhead(pb, mkv);
2500 // update the duration
2501 av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
2502 currentpos = avio_tell(pb);
2503 avio_seek(mkv->info_bc, mkv->duration_offset, SEEK_SET);
2504 put_ebml_float(mkv->info_bc, MATROSKA_ID_DURATION, mkv->duration);
2505 avio_seek(pb, mkv->info.pos, SEEK_SET);
2506 end_ebml_master_crc32(pb, &mkv->info_bc, mkv, mkv->info);
2508 // write tracks master
2509 avio_seek(pb, mkv->tracks_master.pos, SEEK_SET);
2510 end_ebml_master_crc32(pb, &mkv->tracks_bc, mkv, mkv->tracks_master);
2512 // update stream durations
2513 if (!mkv->is_live && mkv->stream_durations) {
2515 int64_t curr = avio_tell(mkv->tags_bc);
2516 for (i = 0; i < s->nb_streams; ++i) {
2517 AVStream *st = s->streams[i];
2519 if (mkv->stream_duration_offsets[i] > 0) {
2520 double duration_sec = mkv->stream_durations[i] * av_q2d(st->time_base);
2521 char duration_string[20] = "";
2523 av_log(s, AV_LOG_DEBUG, "stream %d end duration = %" PRIu64 "\n", i,
2524 mkv->stream_durations[i]);
2526 avio_seek(mkv->tags_bc, mkv->stream_duration_offsets[i], SEEK_SET);
2528 snprintf(duration_string, 20, "%02d:%02d:%012.9f",
2529 (int) duration_sec / 3600, ((int) duration_sec / 60) % 60,
2530 fmod(duration_sec, 60));
2532 put_ebml_binary(mkv->tags_bc, MATROSKA_ID_TAGSTRING, duration_string, 20);
2535 avio_seek(mkv->tags_bc, curr, SEEK_SET);
2537 if (mkv->tags.pos && !mkv->is_live) {
2538 avio_seek(pb, mkv->tags.pos, SEEK_SET);
2539 end_ebml_master_crc32(pb, &mkv->tags_bc, mkv, mkv->tags);
2542 avio_seek(pb, currentpos, SEEK_SET);
2545 if (!mkv->is_live) {
2546 end_ebml_master(pb, mkv->segment);
2553 static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
2556 for (i = 0; ff_mkv_codec_tags[i].id != AV_CODEC_ID_NONE; i++)
2557 if (ff_mkv_codec_tags[i].id == codec_id)
2560 if (std_compliance < FF_COMPLIANCE_NORMAL) {
2561 enum AVMediaType type = avcodec_get_type(codec_id);
2562 // mkv theoretically supports any video/audio through VFW/ACM
2563 if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)
2570 static int mkv_init(struct AVFormatContext *s)
2574 if (s->avoid_negative_ts < 0) {
2575 s->avoid_negative_ts = 1;
2576 s->internal->avoid_negative_ts_use_pts = 1;
2579 for (i = 0; i < s->nb_streams; i++) {
2580 // ms precision is the de-facto standard timescale for mkv files
2581 avpriv_set_pts_info(s->streams[i], 64, 1, 1000);
2587 static int mkv_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
2590 AVStream *st = s->streams[pkt->stream_index];
2592 if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
2593 if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
2594 ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
2595 } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) {
2596 ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL);
2602 static const AVCodecTag additional_audio_tags[] = {
2603 { AV_CODEC_ID_ALAC, 0XFFFFFFFF },
2604 { AV_CODEC_ID_EAC3, 0XFFFFFFFF },
2605 { AV_CODEC_ID_MLP, 0xFFFFFFFF },
2606 { AV_CODEC_ID_OPUS, 0xFFFFFFFF },
2607 { AV_CODEC_ID_PCM_S16BE, 0xFFFFFFFF },
2608 { AV_CODEC_ID_PCM_S24BE, 0xFFFFFFFF },
2609 { AV_CODEC_ID_PCM_S32BE, 0xFFFFFFFF },
2610 { AV_CODEC_ID_QDMC, 0xFFFFFFFF },
2611 { AV_CODEC_ID_QDM2, 0xFFFFFFFF },
2612 { AV_CODEC_ID_RA_144, 0xFFFFFFFF },
2613 { AV_CODEC_ID_RA_288, 0xFFFFFFFF },
2614 { AV_CODEC_ID_COOK, 0xFFFFFFFF },
2615 { AV_CODEC_ID_TRUEHD, 0xFFFFFFFF },
2616 { AV_CODEC_ID_NONE, 0xFFFFFFFF }
2619 static const AVCodecTag additional_video_tags[] = {
2620 { AV_CODEC_ID_RV10, 0xFFFFFFFF },
2621 { AV_CODEC_ID_RV20, 0xFFFFFFFF },
2622 { AV_CODEC_ID_RV30, 0xFFFFFFFF },
2623 { AV_CODEC_ID_RV40, 0xFFFFFFFF },
2624 { AV_CODEC_ID_VP9, 0xFFFFFFFF },
2625 { AV_CODEC_ID_NONE, 0xFFFFFFFF }
2628 static const AVCodecTag additional_subtitle_tags[] = {
2629 { AV_CODEC_ID_DVB_SUBTITLE, 0xFFFFFFFF },
2630 { AV_CODEC_ID_HDMV_PGS_SUBTITLE, 0xFFFFFFFF },
2631 { AV_CODEC_ID_NONE, 0xFFFFFFFF }
2634 #define OFFSET(x) offsetof(MatroskaMuxContext, x)
2635 #define FLAGS AV_OPT_FLAG_ENCODING_PARAM
2636 static const AVOption options[] = {
2637 { "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 },
2638 { "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 },
2639 { "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 },
2640 { "dash", "Create a WebM file conforming to WebM DASH specification", OFFSET(is_dash), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
2641 { "dash_track_number", "Track number for the DASH stream", OFFSET(dash_track_number), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 127, FLAGS },
2642 { "live", "Write files assuming it is a live stream.", OFFSET(is_live), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
2643 { "allow_raw_vfw", "allow RAW VFW mode", OFFSET(allow_raw_vfw), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
2644 { "write_crc32", "write a CRC32 element inside every Level 1 element", OFFSET(write_crc), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, FLAGS },
2648 #if CONFIG_MATROSKA_MUXER
2649 static const AVClass matroska_class = {
2650 .class_name = "matroska muxer",
2651 .item_name = av_default_item_name,
2653 .version = LIBAVUTIL_VERSION_INT,
2656 AVOutputFormat ff_matroska_muxer = {
2658 .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
2659 .mime_type = "video/x-matroska",
2660 .extensions = "mkv",
2661 .priv_data_size = sizeof(MatroskaMuxContext),
2662 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
2663 AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
2664 .video_codec = CONFIG_LIBX264_ENCODER ?
2665 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
2667 .write_header = mkv_write_header,
2668 .write_packet = mkv_write_flush_packet,
2669 .write_trailer = mkv_write_trailer,
2670 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
2671 AVFMT_TS_NONSTRICT | AVFMT_ALLOW_FLUSH,
2672 .codec_tag = (const AVCodecTag* const []){
2673 ff_codec_bmp_tags, ff_codec_wav_tags,
2674 additional_audio_tags, additional_video_tags, additional_subtitle_tags, 0
2676 .subtitle_codec = AV_CODEC_ID_ASS,
2677 .query_codec = mkv_query_codec,
2678 .check_bitstream = mkv_check_bitstream,
2679 .priv_class = &matroska_class,
2683 #if CONFIG_WEBM_MUXER
2684 static const AVClass webm_class = {
2685 .class_name = "webm muxer",
2686 .item_name = av_default_item_name,
2688 .version = LIBAVUTIL_VERSION_INT,
2691 AVOutputFormat ff_webm_muxer = {
2693 .long_name = NULL_IF_CONFIG_SMALL("WebM"),
2694 .mime_type = "video/webm",
2695 .extensions = "webm",
2696 .priv_data_size = sizeof(MatroskaMuxContext),
2697 .audio_codec = CONFIG_LIBOPUS_ENCODER ? AV_CODEC_ID_OPUS : AV_CODEC_ID_VORBIS,
2698 .video_codec = CONFIG_LIBVPX_VP9_ENCODER? AV_CODEC_ID_VP9 : AV_CODEC_ID_VP8,
2699 .subtitle_codec = AV_CODEC_ID_WEBVTT,
2701 .write_header = mkv_write_header,
2702 .write_packet = mkv_write_flush_packet,
2703 .write_trailer = mkv_write_trailer,
2704 .check_bitstream = mkv_check_bitstream,
2705 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
2706 AVFMT_TS_NONSTRICT | AVFMT_ALLOW_FLUSH,
2707 .priv_class = &webm_class,
2711 #if CONFIG_MATROSKA_AUDIO_MUXER
2712 static const AVClass mka_class = {
2713 .class_name = "matroska audio muxer",
2714 .item_name = av_default_item_name,
2716 .version = LIBAVUTIL_VERSION_INT,
2718 AVOutputFormat ff_matroska_audio_muxer = {
2720 .long_name = NULL_IF_CONFIG_SMALL("Matroska Audio"),
2721 .mime_type = "audio/x-matroska",
2722 .extensions = "mka",
2723 .priv_data_size = sizeof(MatroskaMuxContext),
2724 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
2725 AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
2726 .video_codec = AV_CODEC_ID_NONE,
2728 .write_header = mkv_write_header,
2729 .write_packet = mkv_write_flush_packet,
2730 .write_trailer = mkv_write_trailer,
2731 .check_bitstream = mkv_check_bitstream,
2732 .flags = AVFMT_GLOBALHEADER | AVFMT_TS_NONSTRICT |
2734 .codec_tag = (const AVCodecTag* const []){
2735 ff_codec_wav_tags, additional_audio_tags, 0
2737 .priv_class = &mka_class,