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
28 #include "avio_internal.h"
29 #include "avlanguage.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/stereo3d.h"
54 #include "libavcodec/xiph.h"
55 #include "libavcodec/mpeg4audio.h"
57 /* Level 1 elements we create a SeekHead entry for:
58 * Info, Tracks, Chapters, Attachments, Tags (potentially twice) and Cues */
59 #define MAX_SEEKHEAD_ENTRIES 7
61 #define IS_SEEKABLE(pb, mkv) (((pb)->seekable & AVIO_SEEKABLE_NORMAL) && \
66 DEFAULT_MODE_INFER_NO_SUBS,
67 DEFAULT_MODE_PASSTHROUGH,
70 typedef struct ebml_master {
71 int64_t pos; ///< absolute offset in the containing AVIOContext where the master's elements start
72 int sizebytes; ///< how many bytes were reserved for the size
75 typedef struct ebml_stored_master {
80 typedef struct mkv_seekhead_entry {
85 typedef struct mkv_seekhead {
87 mkv_seekhead_entry entries[MAX_SEEKHEAD_ENTRIES];
92 typedef struct mkv_cuepoint {
95 int64_t cluster_pos; ///< offset of the cluster containing the block relative to the segment
96 int64_t relative_pos; ///< relative offset from the position of the cluster containing the block
97 int64_t duration; ///< duration of the block according to time base
100 typedef struct mkv_cues {
101 mkv_cuepoint *entries;
105 typedef struct mkv_track {
112 int64_t sample_rate_offset;
113 int64_t last_timestamp;
115 int64_t duration_offset;
116 int64_t codecpriv_offset;
120 #define MODE_MATROSKAv2 0x01
121 #define MODE_WEBM 0x02
123 typedef struct MatroskaMuxContext {
124 const AVClass *class;
126 ebml_stored_master info;
127 ebml_stored_master track;
128 ebml_stored_master tags;
129 int64_t segment_offset;
130 AVIOContext *cluster_bc;
131 int64_t cluster_pos; ///< file offset of the current Cluster
133 int64_t duration_offset;
136 mkv_seekhead seekhead;
140 AVPacket *cur_audio_pkt;
142 unsigned nb_attachments;
148 int reserve_cues_space;
149 int cluster_size_limit;
150 int64_t cluster_time_limit;
155 int dash_track_number;
160 uint32_t segment_uid[4];
161 } MatroskaMuxContext;
163 /** 2 bytes * 7 for EBML IDs, 7 1-byte EBML lengths, 6 1-byte uint,
164 * 8 byte for "matroska" doctype string */
165 #define MAX_EBML_HEADER_SIZE 35
167 /** 2 bytes * 3 for EBML IDs, 3 1-byte EBML lengths, 8 bytes for 64 bit
168 * offset, 4 bytes for target EBML ID */
169 #define MAX_SEEKENTRY_SIZE 21
171 /** 4 * (1-byte EBML ID, 1-byte EBML size, 8-byte uint max) */
172 #define MAX_CUETRACKPOS_SIZE 40
174 /** Seek preroll value for opus */
175 #define OPUS_SEEK_PREROLL 80000000
177 static int ebml_id_size(uint32_t id)
179 return (av_log2(id) + 7U) / 8;
182 static void put_ebml_id(AVIOContext *pb, uint32_t id)
184 int i = ebml_id_size(id);
186 avio_w8(pb, (uint8_t)(id >> (i * 8)));
190 * Write an EBML size meaning "unknown size".
192 * @param bytes The number of bytes the size should occupy (maximum: 8).
194 static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
196 av_assert0(bytes <= 8);
197 avio_w8(pb, 0x1ff >> bytes);
198 if (av_builtin_constant_p(bytes) && bytes == 1)
200 ffio_fill(pb, 0xff, bytes - 1);
204 * Returns how many bytes are needed to represent a number
205 * as EBML variable length integer.
207 static int ebml_num_size(uint64_t num)
217 * Calculate how many bytes are needed to represent the length field
218 * of an EBML element whose payload has a given length.
220 static int ebml_length_size(uint64_t length)
222 return ebml_num_size(length + 1);
226 * Write a number as EBML variable length integer on `bytes` bytes.
227 * `bytes` is taken literally without checking.
229 static void put_ebml_num(AVIOContext *pb, uint64_t num, int bytes)
231 num |= 1ULL << bytes * 7;
232 for (int i = bytes - 1; i >= 0; i--)
233 avio_w8(pb, (uint8_t)(num >> i * 8));
237 * Write a length as EBML variable length integer.
239 * @param bytes The number of bytes that need to be used to write the number.
240 * If zero, the minimal number of bytes will be used.
242 static void put_ebml_length(AVIOContext *pb, uint64_t length, int bytes)
244 int needed_bytes = ebml_length_size(length);
246 // sizes larger than this are currently undefined in EBML
247 av_assert0(length < (1ULL << 56) - 1);
250 bytes = needed_bytes;
251 // The bytes needed to write the given size must not exceed
252 // the bytes that we ought to use.
253 av_assert0(bytes >= needed_bytes);
254 put_ebml_num(pb, length, bytes);
258 * Write a (random) UID with fixed size to make the output more deterministic
260 static void put_ebml_uid(AVIOContext *pb, uint32_t elementid, uint64_t uid)
262 put_ebml_id(pb, elementid);
263 put_ebml_length(pb, 8, 0);
267 static void put_ebml_uint(AVIOContext *pb, uint32_t elementid, uint64_t val)
274 put_ebml_id(pb, elementid);
275 put_ebml_length(pb, bytes, 0);
276 for (i = bytes - 1; i >= 0; i--)
277 avio_w8(pb, (uint8_t)(val >> i * 8));
280 static void put_ebml_sint(AVIOContext *pb, uint32_t elementid, int64_t val)
283 uint64_t tmp = 2*(val < 0 ? val^-1 : val);
288 put_ebml_id(pb, elementid);
289 put_ebml_length(pb, bytes, 0);
290 for (i = bytes - 1; i >= 0; i--)
291 avio_w8(pb, (uint8_t)(val >> i * 8));
294 static void put_ebml_float(AVIOContext *pb, uint32_t elementid, double val)
296 put_ebml_id(pb, elementid);
297 put_ebml_length(pb, 8, 0);
298 avio_wb64(pb, av_double2int(val));
301 static void put_ebml_binary(AVIOContext *pb, uint32_t elementid,
302 const void *buf, int size)
304 put_ebml_id(pb, elementid);
305 put_ebml_length(pb, size, 0);
306 avio_write(pb, buf, size);
309 static void put_ebml_string(AVIOContext *pb, uint32_t elementid,
312 put_ebml_binary(pb, elementid, str, strlen(str));
316 * Write a void element of a given size. Useful for reserving space in
317 * the file to be written to later.
319 * @param size The number of bytes to reserve, which must be at least 2.
321 static void put_ebml_void(AVIOContext *pb, int size)
323 av_assert0(size >= 2);
325 put_ebml_id(pb, EBML_ID_VOID);
326 // we need to subtract the length needed to store the size from the
327 // size we need to reserve so 2 cases, we use 8 bytes to store the
328 // size if possible, 1 byte otherwise
331 put_ebml_length(pb, size, 0);
334 put_ebml_length(pb, size, 8);
336 ffio_fill(pb, 0, size);
339 static ebml_master start_ebml_master(AVIOContext *pb, uint32_t elementid,
340 uint64_t expectedsize)
342 int bytes = expectedsize ? ebml_length_size(expectedsize) : 8;
344 put_ebml_id(pb, elementid);
345 put_ebml_size_unknown(pb, bytes);
346 return (ebml_master) { avio_tell(pb), bytes };
349 static void end_ebml_master(AVIOContext *pb, ebml_master master)
351 int64_t pos = avio_tell(pb);
353 if (avio_seek(pb, master.pos - master.sizebytes, SEEK_SET) < 0)
355 put_ebml_length(pb, pos - master.pos, master.sizebytes);
356 avio_seek(pb, pos, SEEK_SET);
359 static void mkv_add_seekhead_entry(MatroskaMuxContext *mkv, uint32_t elementid,
362 mkv_seekhead *seekhead = &mkv->seekhead;
364 av_assert1(seekhead->num_entries < MAX_SEEKHEAD_ENTRIES);
366 seekhead->entries[seekhead->num_entries].elementid = elementid;
367 seekhead->entries[seekhead->num_entries++].segmentpos = filepos - mkv->segment_offset;
370 static int start_ebml_master_crc32(AVIOContext **dyn_cp, MatroskaMuxContext *mkv)
374 if (!*dyn_cp && (ret = avio_open_dyn_buf(dyn_cp)) < 0)
378 put_ebml_void(*dyn_cp, 6); /* Reserve space for CRC32 so position/size calculations using avio_tell() take it into account */
383 static int end_ebml_master_crc32(AVIOContext *pb, AVIOContext **dyn_cp,
384 MatroskaMuxContext *mkv, uint32_t id,
385 int length_size, int keep_buffer,
388 uint8_t *buf, crc[4];
389 int ret, size, skip = 0;
391 size = avio_get_dyn_buf(*dyn_cp, &buf);
392 if ((ret = (*dyn_cp)->error) < 0)
396 mkv_add_seekhead_entry(mkv, id, avio_tell(pb));
399 put_ebml_length(pb, size, length_size);
400 if (mkv->write_crc) {
401 skip = 6; /* Skip reserved 6-byte long void element from the dynamic buffer. */
402 AV_WL32(crc, av_crc(av_crc_get_table(AV_CRC_32_IEEE_LE), UINT32_MAX, buf + skip, size - skip) ^ UINT32_MAX);
403 put_ebml_binary(pb, EBML_ID_CRC32, crc, sizeof(crc));
405 avio_write(pb, buf + skip, size - skip);
409 ffio_reset_dyn_buf(*dyn_cp);
411 ffio_free_dyn_buf(dyn_cp);
417 * Output EBML master. Keep the buffer if seekable, allowing for later updates.
418 * Furthermore always add a SeekHead Entry for this element.
420 static int end_ebml_master_crc32_tentatively(AVIOContext *pb,
421 ebml_stored_master *elem,
422 MatroskaMuxContext *mkv, uint32_t id)
424 if (IS_SEEKABLE(pb, mkv)) {
426 int size = avio_get_dyn_buf(elem->bc, &buf);
428 if (elem->bc->error < 0)
429 return elem->bc->error;
431 elem->pos = avio_tell(pb);
432 mkv_add_seekhead_entry(mkv, id, elem->pos);
435 put_ebml_length(pb, size, 0);
436 avio_write(pb, buf, size);
440 return end_ebml_master_crc32(pb, &elem->bc, mkv, id, 0, 0, 1);
443 static void put_xiph_size(AVIOContext *pb, int size)
445 ffio_fill(pb, 255, size / 255);
446 avio_w8(pb, size % 255);
450 * Free the members allocated in the mux context.
452 static void mkv_deinit(AVFormatContext *s)
454 MatroskaMuxContext *mkv = s->priv_data;
456 av_packet_free(&mkv->cur_audio_pkt);
458 ffio_free_dyn_buf(&mkv->cluster_bc);
459 ffio_free_dyn_buf(&mkv->info.bc);
460 ffio_free_dyn_buf(&mkv->track.bc);
461 ffio_free_dyn_buf(&mkv->tags.bc);
463 av_freep(&mkv->cues.entries);
464 av_freep(&mkv->tracks);
468 * Initialize the SeekHead element to be ready to index level 1 Matroska
469 * elements. Enough space to write MAX_SEEKHEAD_ENTRIES SeekHead entries
470 * will be reserved at the current file location.
472 static void mkv_start_seekhead(MatroskaMuxContext *mkv, AVIOContext *pb)
474 mkv->seekhead.filepos = avio_tell(pb);
475 // 21 bytes max for a Seek entry, 6 bytes max for the SeekHead ID
476 // and size, 6 bytes for a CRC32 element, and 2 bytes to guarantee
477 // that an EBML void element will fit afterwards
478 mkv->seekhead.reserved_size = MAX_SEEKHEAD_ENTRIES * MAX_SEEKENTRY_SIZE + 14;
479 put_ebml_void(pb, mkv->seekhead.reserved_size);
483 * Write the SeekHead to the file at the location reserved for it
484 * and seek to destpos afterwards. When error_on_seek_failure
485 * is not set, failure to seek to the position designated for the
486 * SeekHead is not considered an error and it is presumed that
487 * destpos is the current position; failure to seek to destpos
488 * afterwards is always an error.
490 * @return 0 on success, < 0 on error.
492 static int mkv_write_seekhead(AVIOContext *pb, MatroskaMuxContext *mkv,
493 int error_on_seek_failure, int64_t destpos)
495 AVIOContext *dyn_cp = NULL;
496 mkv_seekhead *seekhead = &mkv->seekhead;
497 int64_t remaining, ret64;
500 if ((ret64 = avio_seek(pb, seekhead->filepos, SEEK_SET)) < 0)
501 return error_on_seek_failure ? ret64 : 0;
503 ret = start_ebml_master_crc32(&dyn_cp, mkv);
507 for (i = 0; i < seekhead->num_entries; i++) {
508 mkv_seekhead_entry *entry = &seekhead->entries[i];
509 ebml_master seekentry = start_ebml_master(dyn_cp, MATROSKA_ID_SEEKENTRY,
512 put_ebml_id(dyn_cp, MATROSKA_ID_SEEKID);
513 put_ebml_length(dyn_cp, ebml_id_size(entry->elementid), 0);
514 put_ebml_id(dyn_cp, entry->elementid);
516 put_ebml_uint(dyn_cp, MATROSKA_ID_SEEKPOSITION, entry->segmentpos);
517 end_ebml_master(dyn_cp, seekentry);
519 ret = end_ebml_master_crc32(pb, &dyn_cp, mkv,
520 MATROSKA_ID_SEEKHEAD, 0, 0, 0);
524 remaining = seekhead->filepos + seekhead->reserved_size - avio_tell(pb);
525 put_ebml_void(pb, remaining);
527 if ((ret64 = avio_seek(pb, destpos, SEEK_SET)) < 0)
533 static int mkv_add_cuepoint(MatroskaMuxContext *mkv, int stream, int64_t ts,
534 int64_t cluster_pos, int64_t relative_pos, int64_t duration)
536 mkv_cues *cues = &mkv->cues;
537 mkv_cuepoint *entries = cues->entries;
542 entries = av_realloc_array(entries, cues->num_entries + 1, sizeof(mkv_cuepoint));
544 return AVERROR(ENOMEM);
545 cues->entries = entries;
547 cues->entries[cues->num_entries].pts = ts;
548 cues->entries[cues->num_entries].stream_idx = stream;
549 cues->entries[cues->num_entries].cluster_pos = cluster_pos - mkv->segment_offset;
550 cues->entries[cues->num_entries].relative_pos = relative_pos;
551 cues->entries[cues->num_entries++].duration = duration;
556 static int mkv_assemble_cues(AVStream **streams, AVIOContext *dyn_cp,
557 mkv_cues *cues, mkv_track *tracks, int num_tracks)
559 AVIOContext *cuepoint;
562 ret = avio_open_dyn_buf(&cuepoint);
566 for (mkv_cuepoint *entry = cues->entries, *end = entry + cues->num_entries;
568 uint64_t pts = entry->pts;
572 put_ebml_uint(cuepoint, MATROSKA_ID_CUETIME, pts);
574 // put all the entries from different tracks that have the exact same
575 // timestamp into the same CuePoint
576 for (int j = 0; j < num_tracks; j++)
577 tracks[j].has_cue = 0;
579 ebml_master track_positions;
580 int idx = entry->stream_idx;
582 av_assert0(idx >= 0 && idx < num_tracks);
583 if (tracks[idx].has_cue && streams[idx]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE)
585 tracks[idx].has_cue = 1;
586 track_positions = start_ebml_master(cuepoint, MATROSKA_ID_CUETRACKPOSITION, MAX_CUETRACKPOS_SIZE);
587 put_ebml_uint(cuepoint, MATROSKA_ID_CUETRACK , tracks[idx].track_num);
588 put_ebml_uint(cuepoint, MATROSKA_ID_CUECLUSTERPOSITION , entry->cluster_pos);
589 put_ebml_uint(cuepoint, MATROSKA_ID_CUERELATIVEPOSITION, entry->relative_pos);
590 if (entry->duration > 0)
591 put_ebml_uint(cuepoint, MATROSKA_ID_CUEDURATION , entry->duration);
592 end_ebml_master(cuepoint, track_positions);
593 } while (++entry < end && entry->pts == pts);
594 size = avio_get_dyn_buf(cuepoint, &buf);
595 if ((ret = cuepoint->error) < 0)
597 put_ebml_binary(dyn_cp, MATROSKA_ID_POINTENTRY, buf, size);
598 ffio_reset_dyn_buf(cuepoint);
600 ffio_free_dyn_buf(&cuepoint);
605 static int put_xiph_codecpriv(AVFormatContext *s, AVIOContext *pb,
606 const AVCodecParameters *par)
608 const uint8_t *header_start[3];
610 int first_header_size;
613 if (par->codec_id == AV_CODEC_ID_VORBIS)
614 first_header_size = 30;
616 first_header_size = 42;
618 err = avpriv_split_xiph_headers(par->extradata, par->extradata_size,
619 first_header_size, header_start, header_len);
621 av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
625 avio_w8(pb, 2); // number packets - 1
626 for (j = 0; j < 2; j++) {
627 put_xiph_size(pb, header_len[j]);
629 for (j = 0; j < 3; j++)
630 avio_write(pb, header_start[j], header_len[j]);
635 static int put_wv_codecpriv(AVIOContext *pb, const AVCodecParameters *par)
637 if (par->extradata && par->extradata_size == 2)
638 avio_write(pb, par->extradata, 2);
640 avio_wl16(pb, 0x410); // fallback to the most recent version
644 static int put_flac_codecpriv(AVFormatContext *s, AVIOContext *pb,
645 const AVCodecParameters *par)
647 int write_comment = (par->channel_layout &&
648 !(par->channel_layout & ~0x3ffffULL) &&
649 !ff_flac_is_native_layout(par->channel_layout));
650 int ret = ff_flac_write_header(pb, par->extradata, par->extradata_size,
657 const char *vendor = (s->flags & AVFMT_FLAG_BITEXACT) ?
658 "Lavf" : LIBAVFORMAT_IDENT;
659 AVDictionary *dict = NULL;
663 snprintf(buf, sizeof(buf), "0x%"PRIx64, par->channel_layout);
664 av_dict_set(&dict, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", buf, 0);
666 len = ff_vorbiscomment_length(dict, vendor, NULL, 0);
667 av_assert1(len < (1 << 24) - 4);
672 ff_vorbiscomment_write(pb, dict, vendor, NULL, 0);
680 static int get_aac_sample_rates(AVFormatContext *s, MatroskaMuxContext *mkv,
681 const uint8_t *extradata, int extradata_size,
682 int *sample_rate, int *output_sample_rate)
684 MPEG4AudioConfig mp4ac;
687 ret = avpriv_mpeg4audio_get_config2(&mp4ac, extradata, extradata_size, 1, s);
688 /* Don't abort if the failure is because of missing extradata. Assume in that
689 * case a bitstream filter will provide the muxer with the extradata in the
691 * Abort however if s->pb is not seekable, as we would not be able to seek back
692 * to write the sample rate elements once the extradata shows up, anyway. */
693 if (ret < 0 && (extradata_size || !IS_SEEKABLE(s->pb, mkv))) {
694 av_log(s, AV_LOG_ERROR,
695 "Error parsing AAC extradata, unable to determine samplerate.\n");
696 return AVERROR(EINVAL);
700 /* This will only happen when this function is called while writing the
701 * header and no extradata is available. The space for this element has
702 * to be reserved for when this function is called again after the
703 * extradata shows up in the first packet, as there's no way to know if
704 * output_sample_rate will be different than sample_rate or not. */
705 *output_sample_rate = *sample_rate;
707 *sample_rate = mp4ac.sample_rate;
708 *output_sample_rate = mp4ac.ext_sample_rate;
713 static int mkv_write_native_codecprivate(AVFormatContext *s, AVIOContext *pb,
714 const AVCodecParameters *par,
717 switch (par->codec_id) {
718 case AV_CODEC_ID_VORBIS:
719 case AV_CODEC_ID_THEORA:
720 return put_xiph_codecpriv(s, dyn_cp, par);
721 case AV_CODEC_ID_FLAC:
722 return put_flac_codecpriv(s, dyn_cp, par);
723 case AV_CODEC_ID_WAVPACK:
724 return put_wv_codecpriv(dyn_cp, par);
725 case AV_CODEC_ID_H264:
726 return ff_isom_write_avcc(dyn_cp, par->extradata,
727 par->extradata_size);
728 case AV_CODEC_ID_HEVC:
729 return ff_isom_write_hvcc(dyn_cp, par->extradata,
730 par->extradata_size, 0);
731 case AV_CODEC_ID_AV1:
732 if (par->extradata_size)
733 return ff_isom_write_av1c(dyn_cp, par->extradata,
734 par->extradata_size);
736 put_ebml_void(pb, 4 + 3);
738 case AV_CODEC_ID_ALAC:
739 if (par->extradata_size < 36) {
740 av_log(s, AV_LOG_ERROR,
741 "Invalid extradata found, ALAC expects a 36-byte "
743 return AVERROR_INVALIDDATA;
745 avio_write(dyn_cp, par->extradata + 12,
746 par->extradata_size - 12);
748 case AV_CODEC_ID_AAC:
749 if (par->extradata_size)
750 avio_write(dyn_cp, par->extradata, par->extradata_size);
752 put_ebml_void(pb, MAX_PCE_SIZE + 2 + 4);
755 if (par->codec_id == AV_CODEC_ID_PRORES &&
756 ff_codec_get_id(ff_codec_movvideo_tags, par->codec_tag) == AV_CODEC_ID_PRORES) {
757 avio_wl32(dyn_cp, par->codec_tag);
758 } else if (par->extradata_size && par->codec_id != AV_CODEC_ID_TTA)
759 avio_write(dyn_cp, par->extradata, par->extradata_size);
765 static int mkv_write_codecprivate(AVFormatContext *s, AVIOContext *pb,
766 AVCodecParameters *par,
767 int native_id, int qt_id)
770 MatroskaMuxContext *mkv = s->priv_data;
772 int ret, codecpriv_size;
774 ret = avio_open_dyn_buf(&dyn_cp);
779 ret = mkv_write_native_codecprivate(s, pb, par, dyn_cp);
780 } else if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
783 par->codec_tag = ff_codec_get_tag(ff_codec_movvideo_tags,
785 if ( ff_codec_get_id(ff_codec_movvideo_tags, par->codec_tag) == par->codec_id
786 && (!par->extradata_size || ff_codec_get_id(ff_codec_movvideo_tags, AV_RL32(par->extradata + 4)) != par->codec_id)
789 avio_wb32(dyn_cp, 0x5a + par->extradata_size);
790 avio_wl32(dyn_cp, par->codec_tag);
791 for(i = 0; i < 0x5a - 8; i++)
794 avio_write(dyn_cp, par->extradata, par->extradata_size);
796 if (!ff_codec_get_tag(ff_codec_bmp_tags, par->codec_id))
797 av_log(s, AV_LOG_WARNING, "codec %s is not supported by this format\n",
798 avcodec_get_name(par->codec_id));
801 par->codec_tag = ff_codec_get_tag(ff_codec_bmp_tags,
803 if (!par->codec_tag && par->codec_id != AV_CODEC_ID_RAWVIDEO) {
804 av_log(s, AV_LOG_ERROR, "No bmp codec tag found for codec %s\n",
805 avcodec_get_name(par->codec_id));
806 ret = AVERROR(EINVAL);
809 ff_put_bmp_header(dyn_cp, par, 0, 0, mkv->flipped_raw_rgb);
811 } else if (par->codec_type == AVMEDIA_TYPE_AUDIO) {
813 tag = ff_codec_get_tag(ff_codec_wav_tags, par->codec_id);
815 av_log(s, AV_LOG_ERROR, "No wav codec tag found for codec %s\n",
816 avcodec_get_name(par->codec_id));
817 ret = AVERROR(EINVAL);
820 par->codec_tag = tag;
822 ff_put_wav_header(s, dyn_cp, par, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX);
826 codecpriv_size = avio_get_dyn_buf(dyn_cp, &codecpriv);
827 if ((ret = dyn_cp->error) >= 0 && codecpriv_size)
828 put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codecpriv,
831 ffio_free_dyn_buf(&dyn_cp);
835 static void mkv_write_video_color(AVIOContext *pb, const AVStream *st,
836 const AVCodecParameters *par)
838 /* 18 Elements with two bytes ID, one byte length field, 8 bytes payload
839 * a master element with two bytes ID and one byte length field
840 * plus another byte to stay clear of the end. */
841 uint8_t colour[(2 + 1 + 8) * 18 + (2 + 1) + 1];
842 AVIOContext buf, *dyn_cp = &buf;
844 const void *side_data;
846 ffio_init_context(dyn_cp, colour, sizeof(colour), 1, NULL, NULL, NULL, NULL);
848 if (par->color_trc != AVCOL_TRC_UNSPECIFIED &&
849 par->color_trc < AVCOL_TRC_NB) {
850 put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORTRANSFERCHARACTERISTICS,
853 if (par->color_space != AVCOL_SPC_UNSPECIFIED &&
854 par->color_space < AVCOL_SPC_NB) {
855 put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORMATRIXCOEFF, par->color_space);
857 if (par->color_primaries != AVCOL_PRI_UNSPECIFIED &&
858 par->color_primaries < AVCOL_PRI_NB) {
859 put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORPRIMARIES, par->color_primaries);
861 if (par->color_range != AVCOL_RANGE_UNSPECIFIED &&
862 par->color_range < AVCOL_RANGE_NB) {
863 put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORRANGE, par->color_range);
865 if (par->chroma_location != AVCHROMA_LOC_UNSPECIFIED &&
866 par->chroma_location <= AVCHROMA_LOC_TOP) {
869 avcodec_enum_to_chroma_pos(&xpos, &ypos, par->chroma_location);
870 put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORCHROMASITINGHORZ, (xpos >> 7) + 1);
871 put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORCHROMASITINGVERT, (ypos >> 7) + 1);
874 side_data = av_stream_get_side_data(st, AV_PKT_DATA_CONTENT_LIGHT_LEVEL,
877 const AVContentLightMetadata *metadata = side_data;
878 put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORMAXCLL, metadata->MaxCLL);
879 put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORMAXFALL, metadata->MaxFALL);
882 side_data = av_stream_get_side_data(st, AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
885 ebml_master meta_element = start_ebml_master(
886 dyn_cp, MATROSKA_ID_VIDEOCOLORMASTERINGMETA, 10 * (2 + 1 + 8));
887 const AVMasteringDisplayMetadata *metadata = side_data;
888 if (metadata->has_primaries) {
889 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_RX,
890 av_q2d(metadata->display_primaries[0][0]));
891 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_RY,
892 av_q2d(metadata->display_primaries[0][1]));
893 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_GX,
894 av_q2d(metadata->display_primaries[1][0]));
895 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_GY,
896 av_q2d(metadata->display_primaries[1][1]));
897 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_BX,
898 av_q2d(metadata->display_primaries[2][0]));
899 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_BY,
900 av_q2d(metadata->display_primaries[2][1]));
901 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_WHITEX,
902 av_q2d(metadata->white_point[0]));
903 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_WHITEY,
904 av_q2d(metadata->white_point[1]));
906 if (metadata->has_luminance) {
907 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_LUMINANCEMAX,
908 av_q2d(metadata->max_luminance));
909 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_LUMINANCEMIN,
910 av_q2d(metadata->min_luminance));
912 end_ebml_master(dyn_cp, meta_element);
915 colorinfo_size = avio_tell(dyn_cp);
917 put_ebml_binary(pb, MATROSKA_ID_VIDEOCOLOR, colour, colorinfo_size);
920 static void mkv_write_video_projection(AVFormatContext *s, AVIOContext *pb,
923 ebml_master projection;
926 const AVSphericalMapping *spherical =
927 (const AVSphericalMapping *)av_stream_get_side_data(st, AV_PKT_DATA_SPHERICAL,
933 if (spherical->projection != AV_SPHERICAL_EQUIRECTANGULAR &&
934 spherical->projection != AV_SPHERICAL_EQUIRECTANGULAR_TILE &&
935 spherical->projection != AV_SPHERICAL_CUBEMAP) {
936 av_log(s, AV_LOG_WARNING, "Unknown projection type\n");
940 // Maximally 4 8-byte elements with id-length 2 + 1 byte length field
941 // and the private data of the AV_SPHERICAL_EQUIRECTANGULAR_TILE case
942 projection = start_ebml_master(pb, MATROSKA_ID_VIDEOPROJECTION,
943 4 * (2 + 1 + 8) + (2 + 1 + 20));
945 switch (spherical->projection) {
946 case AV_SPHERICAL_EQUIRECTANGULAR:
947 put_ebml_uint(pb, MATROSKA_ID_VIDEOPROJECTIONTYPE,
948 MATROSKA_VIDEO_PROJECTION_TYPE_EQUIRECTANGULAR);
950 case AV_SPHERICAL_EQUIRECTANGULAR_TILE:
951 put_ebml_uint(pb, MATROSKA_ID_VIDEOPROJECTIONTYPE,
952 MATROSKA_VIDEO_PROJECTION_TYPE_EQUIRECTANGULAR);
953 AV_WB32(private, 0); // version + flags
954 AV_WB32(private + 4, spherical->bound_top);
955 AV_WB32(private + 8, spherical->bound_bottom);
956 AV_WB32(private + 12, spherical->bound_left);
957 AV_WB32(private + 16, spherical->bound_right);
958 put_ebml_binary(pb, MATROSKA_ID_VIDEOPROJECTIONPRIVATE,
961 case AV_SPHERICAL_CUBEMAP:
962 put_ebml_uint(pb, MATROSKA_ID_VIDEOPROJECTIONTYPE,
963 MATROSKA_VIDEO_PROJECTION_TYPE_CUBEMAP);
964 AV_WB32(private, 0); // version + flags
965 AV_WB32(private + 4, 0); // layout
966 AV_WB32(private + 8, spherical->padding);
967 put_ebml_binary(pb, MATROSKA_ID_VIDEOPROJECTIONPRIVATE,
975 put_ebml_float(pb, MATROSKA_ID_VIDEOPROJECTIONPOSEYAW,
976 (double) spherical->yaw / (1 << 16));
977 if (spherical->pitch)
978 put_ebml_float(pb, MATROSKA_ID_VIDEOPROJECTIONPOSEPITCH,
979 (double) spherical->pitch / (1 << 16));
981 put_ebml_float(pb, MATROSKA_ID_VIDEOPROJECTIONPOSEROLL,
982 (double) spherical->roll / (1 << 16));
984 end_ebml_master(pb, projection);
987 static void mkv_write_field_order(AVIOContext *pb, int mode,
988 enum AVFieldOrder field_order)
990 switch (field_order) {
991 case AV_FIELD_UNKNOWN:
993 case AV_FIELD_PROGRESSIVE:
994 put_ebml_uint(pb, MATROSKA_ID_VIDEOFLAGINTERLACED,
995 MATROSKA_VIDEO_INTERLACE_FLAG_PROGRESSIVE);
1001 put_ebml_uint(pb, MATROSKA_ID_VIDEOFLAGINTERLACED,
1002 MATROSKA_VIDEO_INTERLACE_FLAG_INTERLACED);
1003 if (mode != MODE_WEBM) {
1004 switch (field_order) {
1006 put_ebml_uint(pb, MATROSKA_ID_VIDEOFIELDORDER,
1007 MATROSKA_VIDEO_FIELDORDER_TT);
1010 put_ebml_uint(pb, MATROSKA_ID_VIDEOFIELDORDER,
1011 MATROSKA_VIDEO_FIELDORDER_BB);
1014 put_ebml_uint(pb, MATROSKA_ID_VIDEOFIELDORDER,
1015 MATROSKA_VIDEO_FIELDORDER_TB);
1018 put_ebml_uint(pb, MATROSKA_ID_VIDEOFIELDORDER,
1019 MATROSKA_VIDEO_FIELDORDER_BT);
1026 static int mkv_write_stereo_mode(AVFormatContext *s, AVIOContext *pb,
1027 AVStream *st, int mode, int *h_width, int *h_height)
1029 const AVDictionaryEntry *tag;
1030 MatroskaVideoStereoModeType format = MATROSKA_VIDEO_STEREOMODE_TYPE_NB;
1031 const AVStereo3D *stereo;
1035 // convert metadata into proper side data and add it to the stream
1036 if ((tag = av_dict_get(st->metadata, "stereo_mode", NULL, 0)) ||
1037 (tag = av_dict_get( s->metadata, "stereo_mode", NULL, 0))) {
1038 int stereo_mode = atoi(tag->value);
1040 for (int i = 0; i < MATROSKA_VIDEO_STEREOMODE_TYPE_NB; i++)
1041 if (!strcmp(tag->value, ff_matroska_video_stereo_mode[i])){
1046 if (stereo_mode < MATROSKA_VIDEO_STEREOMODE_TYPE_NB &&
1047 stereo_mode != 10 && stereo_mode != 12) {
1048 int ret = ff_mkv_stereo3d_conv(st, stereo_mode);
1054 stereo = (const AVStereo3D*)av_stream_get_side_data(st, AV_PKT_DATA_STEREO3D,
1057 switch (stereo->type) {
1058 case AV_STEREO3D_2D:
1059 format = MATROSKA_VIDEO_STEREOMODE_TYPE_MONO;
1061 case AV_STEREO3D_SIDEBYSIDE:
1062 format = (stereo->flags & AV_STEREO3D_FLAG_INVERT)
1063 ? MATROSKA_VIDEO_STEREOMODE_TYPE_RIGHT_LEFT
1064 : MATROSKA_VIDEO_STEREOMODE_TYPE_LEFT_RIGHT;
1067 case AV_STEREO3D_TOPBOTTOM:
1068 format = MATROSKA_VIDEO_STEREOMODE_TYPE_TOP_BOTTOM;
1069 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
1073 case AV_STEREO3D_CHECKERBOARD:
1074 format = MATROSKA_VIDEO_STEREOMODE_TYPE_CHECKERBOARD_LR;
1075 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
1078 case AV_STEREO3D_LINES:
1079 format = MATROSKA_VIDEO_STEREOMODE_TYPE_ROW_INTERLEAVED_LR;
1080 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
1084 case AV_STEREO3D_COLUMNS:
1085 format = MATROSKA_VIDEO_STEREOMODE_TYPE_COL_INTERLEAVED_LR;
1086 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
1090 case AV_STEREO3D_FRAMESEQUENCE:
1091 format = MATROSKA_VIDEO_STEREOMODE_TYPE_BOTH_EYES_BLOCK_LR;
1092 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
1098 if (format == MATROSKA_VIDEO_STEREOMODE_TYPE_NB)
1101 // if webm, do not write unsupported modes
1102 if ((mode == MODE_WEBM &&
1103 format > MATROSKA_VIDEO_STEREOMODE_TYPE_TOP_BOTTOM &&
1104 format != MATROSKA_VIDEO_STEREOMODE_TYPE_RIGHT_LEFT)
1105 || format >= MATROSKA_VIDEO_STEREOMODE_TYPE_NB) {
1106 av_log(s, AV_LOG_ERROR,
1107 "The specified stereo mode is not valid.\n");
1108 return AVERROR(EINVAL);
1111 // write StereoMode if format is valid
1112 put_ebml_uint(pb, MATROSKA_ID_VIDEOSTEREOMODE, format);
1117 static int mkv_write_track(AVFormatContext *s, MatroskaMuxContext *mkv,
1118 AVStream *st, mkv_track *track, AVIOContext *pb,
1121 AVCodecParameters *par = st->codecpar;
1122 ebml_master subinfo, track_master;
1126 int sample_rate = par->sample_rate;
1127 int output_sample_rate = 0;
1128 int display_width_div = 1;
1129 int display_height_div = 1;
1131 const AVDictionaryEntry *tag;
1133 if (par->codec_type == AVMEDIA_TYPE_ATTACHMENT)
1136 if (par->codec_id == AV_CODEC_ID_AAC) {
1137 ret = get_aac_sample_rates(s, mkv, par->extradata, par->extradata_size,
1138 &sample_rate, &output_sample_rate);
1143 track_master = start_ebml_master(pb, MATROSKA_ID_TRACKENTRY, 0);
1144 put_ebml_uint(pb, MATROSKA_ID_TRACKNUMBER, track->track_num);
1145 put_ebml_uid (pb, MATROSKA_ID_TRACKUID, track->uid);
1146 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGLACING, 0); // no lacing (yet)
1148 if ((tag = av_dict_get(st->metadata, "title", NULL, 0)))
1149 put_ebml_string(pb, MATROSKA_ID_TRACKNAME, tag->value);
1150 tag = av_dict_get(st->metadata, "language", NULL, 0);
1151 put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE,
1152 tag && tag->value[0] ? tag->value : "und");
1154 // The default value for TRACKFLAGDEFAULT is 1, so add element
1155 // if we need to clear it.
1157 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGDEFAULT, 0);
1159 if (st->disposition & AV_DISPOSITION_FORCED)
1160 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGFORCED, 1);
1162 if (mkv->mode == MODE_WEBM) {
1163 const char *codec_id;
1164 if (par->codec_type != AVMEDIA_TYPE_SUBTITLE) {
1165 for (j = 0; ff_webm_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
1166 if (ff_webm_codec_tags[j].id == par->codec_id) {
1167 codec_id = ff_webm_codec_tags[j].str;
1172 } else if (par->codec_id == AV_CODEC_ID_WEBVTT) {
1173 if (st->disposition & AV_DISPOSITION_CAPTIONS) {
1174 codec_id = "D_WEBVTT/CAPTIONS";
1175 native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
1176 } else if (st->disposition & AV_DISPOSITION_DESCRIPTIONS) {
1177 codec_id = "D_WEBVTT/DESCRIPTIONS";
1178 native_id = MATROSKA_TRACK_TYPE_METADATA;
1179 } else if (st->disposition & AV_DISPOSITION_METADATA) {
1180 codec_id = "D_WEBVTT/METADATA";
1181 native_id = MATROSKA_TRACK_TYPE_METADATA;
1183 codec_id = "D_WEBVTT/SUBTITLES";
1184 native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
1189 av_log(s, AV_LOG_ERROR,
1190 "Only VP8 or VP9 or AV1 video and Vorbis or Opus audio and WebVTT subtitles are supported for WebM.\n");
1191 return AVERROR(EINVAL);
1194 put_ebml_string(pb, MATROSKA_ID_CODECID, codec_id);
1196 if (st->disposition & AV_DISPOSITION_COMMENT)
1197 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGCOMMENTARY, 1);
1198 if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
1199 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGHEARINGIMPAIRED, 1);
1200 if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
1201 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGVISUALIMPAIRED, 1);
1202 if (st->disposition & (AV_DISPOSITION_ORIGINAL | AV_DISPOSITION_DUB) &&
1203 (st->disposition & (AV_DISPOSITION_ORIGINAL | AV_DISPOSITION_DUB))
1204 != (AV_DISPOSITION_ORIGINAL | AV_DISPOSITION_DUB))
1205 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGORIGINAL,
1206 !!(st->disposition & AV_DISPOSITION_ORIGINAL));
1208 // look for a codec ID string specific to mkv to use,
1209 // if none are found, use AVI codes
1210 if (par->codec_id != AV_CODEC_ID_RAWVIDEO || par->codec_tag) {
1211 for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
1212 if (ff_mkv_codec_tags[j].id == par->codec_id && par->codec_id != AV_CODEC_ID_FFV1) {
1213 put_ebml_string(pb, MATROSKA_ID_CODECID, ff_mkv_codec_tags[j].str);
1219 if (mkv->allow_raw_vfw) {
1222 av_log(s, AV_LOG_ERROR, "Raw RGB is not supported Natively in Matroska, you can use AVI or NUT or\n"
1223 "If you would like to store it anyway using VFW mode, enable allow_raw_vfw (-allow_raw_vfw 1)\n");
1224 return AVERROR(EINVAL);
1229 switch (par->codec_type) {
1230 case AVMEDIA_TYPE_VIDEO:
1231 mkv->have_video = 1;
1232 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_VIDEO);
1234 if( st->avg_frame_rate.num > 0 && st->avg_frame_rate.den > 0
1235 && av_cmp_q(av_inv_q(st->avg_frame_rate), st->time_base) > 0)
1236 put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, 1000000000LL * st->avg_frame_rate.den / st->avg_frame_rate.num);
1237 else if( st->r_frame_rate.num > 0 && st->r_frame_rate.den > 0
1238 && av_cmp_q(av_inv_q(st->r_frame_rate), st->time_base) > 0)
1239 put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, 1000000000LL * st->r_frame_rate.den / st->r_frame_rate.num);
1242 ff_codec_get_tag(ff_codec_movvideo_tags, par->codec_id) &&
1243 ((!ff_codec_get_tag(ff_codec_bmp_tags, par->codec_id) && par->codec_id != AV_CODEC_ID_RAWVIDEO) ||
1244 par->codec_id == AV_CODEC_ID_SVQ1 ||
1245 par->codec_id == AV_CODEC_ID_SVQ3 ||
1246 par->codec_id == AV_CODEC_ID_CINEPAK))
1250 put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");
1251 else if (!native_id) {
1252 // if there is no mkv-specific codec ID, use VFW mode
1253 put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");
1254 track->write_dts = 1;
1255 s->internal->avoid_negative_ts_use_pts = 0;
1258 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
1260 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , par->width);
1261 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, par->height);
1263 mkv_write_field_order(pb, mkv->mode, par->field_order);
1265 // check both side data and metadata for stereo information,
1266 // write the result to the bitstream if any is found
1267 ret = mkv_write_stereo_mode(s, pb, st, mkv->mode,
1269 &display_height_div);
1273 if (((tag = av_dict_get(st->metadata, "alpha_mode", NULL, 0)) && atoi(tag->value)) ||
1274 ((tag = av_dict_get( s->metadata, "alpha_mode", NULL, 0)) && atoi(tag->value)) ||
1275 (par->format == AV_PIX_FMT_YUVA420P)) {
1276 put_ebml_uint(pb, MATROSKA_ID_VIDEOALPHAMODE, 1);
1279 // write DisplayWidth and DisplayHeight, they contain the size of
1280 // a single source view and/or the display aspect ratio
1281 if (st->sample_aspect_ratio.num) {
1282 int64_t d_width = av_rescale(par->width, st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
1283 if (d_width > INT_MAX) {
1284 av_log(s, AV_LOG_ERROR, "Overflow in display width\n");
1285 return AVERROR(EINVAL);
1287 if (d_width != par->width || display_width_div != 1 || display_height_div != 1) {
1288 if (mkv->mode == MODE_WEBM || display_width_div != 1 || display_height_div != 1) {
1289 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , d_width / display_width_div);
1290 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, par->height / display_height_div);
1292 AVRational display_aspect_ratio;
1293 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
1294 par->width * (int64_t)st->sample_aspect_ratio.num,
1295 par->height * (int64_t)st->sample_aspect_ratio.den,
1297 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH, display_aspect_ratio.num);
1298 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, display_aspect_ratio.den);
1299 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYUNIT, MATROSKA_VIDEO_DISPLAYUNIT_DAR);
1302 } else if (display_width_div != 1 || display_height_div != 1) {
1303 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , par->width / display_width_div);
1304 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, par->height / display_height_div);
1305 } else if (mkv->mode != MODE_WEBM)
1306 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYUNIT, MATROSKA_VIDEO_DISPLAYUNIT_UNKNOWN);
1308 if (par->codec_id == AV_CODEC_ID_RAWVIDEO) {
1309 uint32_t color_space = av_le2ne32(par->codec_tag);
1310 put_ebml_binary(pb, MATROSKA_ID_VIDEOCOLORSPACE, &color_space, sizeof(color_space));
1312 mkv_write_video_color(pb, st, par);
1313 mkv_write_video_projection(s, pb, st);
1315 end_ebml_master(pb, subinfo);
1318 case AVMEDIA_TYPE_AUDIO:
1319 if (par->initial_padding && par->codec_id == AV_CODEC_ID_OPUS) {
1320 int64_t codecdelay = av_rescale_q(par->initial_padding,
1321 (AVRational){ 1, 48000 },
1322 (AVRational){ 1, 1000000000 });
1323 if (codecdelay < 0) {
1324 av_log(s, AV_LOG_ERROR, "Initial padding is invalid\n");
1325 return AVERROR(EINVAL);
1327 // track->ts_offset = av_rescale_q(par->initial_padding,
1328 // (AVRational){ 1, par->sample_rate },
1331 put_ebml_uint(pb, MATROSKA_ID_CODECDELAY, codecdelay);
1333 if (par->codec_id == AV_CODEC_ID_OPUS)
1334 put_ebml_uint(pb, MATROSKA_ID_SEEKPREROLL, OPUS_SEEK_PREROLL);
1336 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_AUDIO);
1339 // no mkv-specific ID, use ACM mode
1340 put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");
1342 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 6 + 4 * 9);
1343 put_ebml_uint (pb, MATROSKA_ID_AUDIOCHANNELS , par->channels);
1345 track->sample_rate_offset = avio_tell(pb);
1346 put_ebml_float (pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, sample_rate);
1347 if (output_sample_rate)
1348 put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
1350 bit_depth = av_get_bits_per_sample(par->codec_id);
1351 if (!bit_depth && par->codec_id != AV_CODEC_ID_ADPCM_G726) {
1352 if (par->bits_per_raw_sample)
1353 bit_depth = par->bits_per_raw_sample;
1355 bit_depth = av_get_bytes_per_sample(par->format) << 3;
1358 bit_depth = par->bits_per_coded_sample;
1360 put_ebml_uint(pb, MATROSKA_ID_AUDIOBITDEPTH, bit_depth);
1361 end_ebml_master(pb, subinfo);
1364 case AVMEDIA_TYPE_SUBTITLE:
1366 av_log(s, AV_LOG_ERROR, "Subtitle codec %d is not supported.\n", par->codec_id);
1367 return AVERROR(ENOSYS);
1369 if (mkv->mode != MODE_WEBM && st->disposition & AV_DISPOSITION_DESCRIPTIONS)
1370 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGTEXTDESCRIPTIONS, 1);
1372 if (mkv->mode != MODE_WEBM || par->codec_id != AV_CODEC_ID_WEBVTT)
1373 native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
1375 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, native_id);
1378 av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.\n");
1379 return AVERROR(EINVAL);
1382 if (mkv->mode != MODE_WEBM || par->codec_id != AV_CODEC_ID_WEBVTT) {
1383 track->codecpriv_offset = avio_tell(pb);
1384 ret = mkv_write_codecprivate(s, pb, par, native_id, qt_id);
1389 end_ebml_master(pb, track_master);
1394 static int mkv_write_tracks(AVFormatContext *s)
1396 MatroskaMuxContext *mkv = s->priv_data;
1397 AVIOContext *pb = s->pb;
1398 int i, ret, video_default_idx, audio_default_idx, subtitle_default_idx;
1400 if (mkv->nb_attachments == s->nb_streams)
1403 ret = start_ebml_master_crc32(&mkv->track.bc, mkv);
1407 if (mkv->default_mode != DEFAULT_MODE_PASSTHROUGH) {
1408 int video_idx, audio_idx, subtitle_idx;
1410 video_idx = video_default_idx =
1411 audio_idx = audio_default_idx =
1412 subtitle_idx = subtitle_default_idx = -1;
1414 for (i = s->nb_streams - 1; i >= 0; i--) {
1415 AVStream *st = s->streams[i];
1417 switch (st->codecpar->codec_type) {
1418 #define CASE(type, variable) \
1419 case AVMEDIA_TYPE_ ## type: \
1420 variable ## _idx = i; \
1421 if (st->disposition & AV_DISPOSITION_DEFAULT) \
1422 variable ## _default_idx = i; \
1426 CASE(SUBTITLE, subtitle)
1431 video_default_idx = FFMAX(video_default_idx, video_idx);
1432 audio_default_idx = FFMAX(audio_default_idx, audio_idx);
1433 if (mkv->default_mode != DEFAULT_MODE_INFER_NO_SUBS)
1434 subtitle_default_idx = FFMAX(subtitle_default_idx, subtitle_idx);
1436 for (i = 0; i < s->nb_streams; i++) {
1437 AVStream *st = s->streams[i];
1438 int is_default = mkv->default_mode == DEFAULT_MODE_PASSTHROUGH ?
1439 st->disposition & AV_DISPOSITION_DEFAULT :
1440 i == video_default_idx || i == audio_default_idx ||
1441 i == subtitle_default_idx;
1442 ret = mkv_write_track(s, mkv, st, &mkv->tracks[i],
1443 mkv->track.bc, is_default);
1448 return end_ebml_master_crc32_tentatively(pb, &mkv->track, mkv,
1449 MATROSKA_ID_TRACKS);
1452 static int mkv_write_simpletag(AVIOContext *pb, const AVDictionaryEntry *t)
1454 uint8_t *key = av_strdup(t->key);
1456 const uint8_t *lang = NULL;
1460 return AVERROR(ENOMEM);
1462 if ((p = strrchr(p, '-')) &&
1463 (lang = ff_convert_lang_to(p + 1, AV_LANG_ISO639_2_BIBL)))
1470 else if (*p >= 'a' && *p <= 'z')
1475 tag = start_ebml_master(pb, MATROSKA_ID_SIMPLETAG, 0);
1476 put_ebml_string(pb, MATROSKA_ID_TAGNAME, key);
1478 put_ebml_string(pb, MATROSKA_ID_TAGLANG, lang);
1479 put_ebml_string(pb, MATROSKA_ID_TAGSTRING, t->value);
1480 end_ebml_master(pb, tag);
1486 static int mkv_write_tag_targets(MatroskaMuxContext *mkv, AVIOContext **pb,
1487 ebml_master *tag, uint32_t elementid, uint64_t uid)
1489 ebml_master targets;
1493 ret = start_ebml_master_crc32(pb, mkv);
1498 *tag = start_ebml_master(*pb, MATROSKA_ID_TAG, 0);
1499 targets = start_ebml_master(*pb, MATROSKA_ID_TAGTARGETS, 4 + 1 + 8);
1501 put_ebml_uid(*pb, elementid, uid);
1502 end_ebml_master(*pb, targets);
1506 static int mkv_check_tag_name(const char *name, uint32_t elementid)
1508 return av_strcasecmp(name, "title") &&
1509 av_strcasecmp(name, "stereo_mode") &&
1510 av_strcasecmp(name, "creation_time") &&
1511 av_strcasecmp(name, "encoding_tool") &&
1512 av_strcasecmp(name, "duration") &&
1513 (elementid != MATROSKA_ID_TAGTARGETS_TRACKUID ||
1514 av_strcasecmp(name, "language")) &&
1515 (elementid != MATROSKA_ID_TAGTARGETS_ATTACHUID ||
1516 (av_strcasecmp(name, "filename") &&
1517 av_strcasecmp(name, "mimetype")));
1520 static int mkv_write_tag(MatroskaMuxContext *mkv, const AVDictionary *m,
1521 AVIOContext **pb, ebml_master *tag,
1522 uint32_t elementid, uint64_t uid)
1524 const AVDictionaryEntry *t = NULL;
1528 ret = mkv_write_tag_targets(mkv, pb, tag ? tag : &tag2, elementid, uid);
1532 while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX))) {
1533 if (mkv_check_tag_name(t->key, elementid)) {
1534 ret = mkv_write_simpletag(*pb, t);
1541 end_ebml_master(*pb, tag2);
1546 static int mkv_check_tag(const AVDictionary *m, uint32_t elementid)
1548 const AVDictionaryEntry *t = NULL;
1550 while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX)))
1551 if (mkv_check_tag_name(t->key, elementid))
1557 static int mkv_write_tags(AVFormatContext *s)
1559 MatroskaMuxContext *mkv = s->priv_data;
1560 ebml_master tag, *tagp = IS_SEEKABLE(s->pb, mkv) ? &tag : NULL;
1563 mkv->wrote_tags = 1;
1565 ff_metadata_conv_ctx(s, ff_mkv_metadata_conv, NULL);
1567 if (mkv_check_tag(s->metadata, 0)) {
1568 ret = mkv_write_tag(mkv, s->metadata, &mkv->tags.bc, NULL, 0, 0);
1573 for (i = 0; i < s->nb_streams; i++) {
1574 const AVStream *st = s->streams[i];
1575 mkv_track *track = &mkv->tracks[i];
1577 if (st->codecpar->codec_type == AVMEDIA_TYPE_ATTACHMENT)
1580 if (!tagp && !mkv_check_tag(st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID))
1583 ret = mkv_write_tag(mkv, st->metadata, &mkv->tags.bc, tagp,
1584 MATROSKA_ID_TAGTARGETS_TRACKUID, track->uid);
1589 AVIOContext *pb = mkv->tags.bc;
1590 ebml_master simpletag;
1592 simpletag = start_ebml_master(pb, MATROSKA_ID_SIMPLETAG,
1594 put_ebml_string(pb, MATROSKA_ID_TAGNAME, "DURATION");
1595 track->duration_offset = avio_tell(pb);
1597 // Reserve space to write duration as a 20-byte string.
1598 // 2 (ebml id) + 1 (data size) + 20 (data)
1599 put_ebml_void(pb, 23);
1600 end_ebml_master(pb, simpletag);
1601 end_ebml_master(pb, tag);
1605 if (mkv->nb_attachments && mkv->mode != MODE_WEBM) {
1606 for (i = 0; i < s->nb_streams; i++) {
1607 const mkv_track *track = &mkv->tracks[i];
1608 const AVStream *st = s->streams[i];
1610 if (st->codecpar->codec_type != AVMEDIA_TYPE_ATTACHMENT)
1613 if (!mkv_check_tag(st->metadata, MATROSKA_ID_TAGTARGETS_ATTACHUID))
1616 ret = mkv_write_tag(mkv, st->metadata, &mkv->tags.bc, NULL,
1617 MATROSKA_ID_TAGTARGETS_ATTACHUID, track->uid);
1624 return end_ebml_master_crc32_tentatively(s->pb, &mkv->tags, mkv,
1630 static int mkv_new_chapter_ids_needed(const AVFormatContext *s)
1632 for (unsigned i = 0; i < s->nb_chapters; i++) {
1633 if (!s->chapters[i]->id)
1635 for (unsigned j = 0; j < i; j++)
1636 if (s->chapters[j]->id == s->chapters[i]->id)
1642 static int mkv_write_chapters(AVFormatContext *s)
1644 MatroskaMuxContext *mkv = s->priv_data;
1645 AVIOContext *dyn_cp = NULL, *dyn_tags = NULL, **tags, *pb = s->pb;
1646 ebml_master editionentry;
1647 AVRational scale = {1, 1E9};
1648 int ret, create_new_ids;
1650 if (!s->nb_chapters || mkv->wrote_chapters)
1653 ret = start_ebml_master_crc32(&dyn_cp, mkv);
1657 editionentry = start_ebml_master(dyn_cp, MATROSKA_ID_EDITIONENTRY, 0);
1658 if (mkv->mode != MODE_WEBM) {
1659 put_ebml_uint(dyn_cp, MATROSKA_ID_EDITIONFLAGDEFAULT, 1);
1660 /* If mkv_write_tags() has already been called, then any tags
1661 * corresponding to chapters will be put into a new Tags element. */
1662 tags = mkv->wrote_tags ? &dyn_tags : &mkv->tags.bc;
1666 create_new_ids = mkv_new_chapter_ids_needed(s);
1668 for (unsigned i = 0; i < s->nb_chapters; i++) {
1669 ebml_master chapteratom, chapterdisplay;
1670 const AVChapter *c = s->chapters[i];
1671 int64_t chapterstart = av_rescale_q(c->start, c->time_base, scale);
1672 int64_t chapterend = av_rescale_q(c->end, c->time_base, scale);
1673 const AVDictionaryEntry *t;
1674 uint64_t uid = create_new_ids ? i + 1ULL : c->id;
1675 if (chapterstart < 0 || chapterstart > chapterend || chapterend < 0) {
1676 av_log(s, AV_LOG_ERROR,
1677 "Invalid chapter start (%"PRId64") or end (%"PRId64").\n",
1678 chapterstart, chapterend);
1679 ret = AVERROR_INVALIDDATA;
1683 chapteratom = start_ebml_master(dyn_cp, MATROSKA_ID_CHAPTERATOM, 0);
1684 put_ebml_uint(dyn_cp, MATROSKA_ID_CHAPTERUID, uid);
1685 put_ebml_uint(dyn_cp, MATROSKA_ID_CHAPTERTIMESTART, chapterstart);
1686 put_ebml_uint(dyn_cp, MATROSKA_ID_CHAPTERTIMEEND, chapterend);
1687 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
1688 chapterdisplay = start_ebml_master(dyn_cp, MATROSKA_ID_CHAPTERDISPLAY, 0);
1689 put_ebml_string(dyn_cp, MATROSKA_ID_CHAPSTRING, t->value);
1690 put_ebml_string(dyn_cp, MATROSKA_ID_CHAPLANG , "und");
1691 end_ebml_master(dyn_cp, chapterdisplay);
1693 end_ebml_master(dyn_cp, chapteratom);
1695 if (tags && mkv_check_tag(c->metadata, MATROSKA_ID_TAGTARGETS_CHAPTERUID)) {
1696 ret = mkv_write_tag(mkv, c->metadata, tags, NULL,
1697 MATROSKA_ID_TAGTARGETS_CHAPTERUID, uid);
1702 end_ebml_master(dyn_cp, editionentry);
1703 mkv->wrote_chapters = 1;
1705 ret = end_ebml_master_crc32(pb, &dyn_cp, mkv, MATROSKA_ID_CHAPTERS, 0, 0, 1);
1709 return end_ebml_master_crc32(pb, &dyn_tags, mkv,
1710 MATROSKA_ID_TAGS, 0, 0, 1);
1715 /* tags == &mkv->tags.bc can only happen if mkv->tags.bc was
1716 * initially NULL, so we never free older tags. */
1717 ffio_free_dyn_buf(tags);
1719 ffio_free_dyn_buf(&dyn_cp);
1723 static const char *get_mimetype(const AVStream *st)
1725 const AVDictionaryEntry *t;
1727 if (t = av_dict_get(st->metadata, "mimetype", NULL, 0))
1729 if (st->codecpar->codec_id != AV_CODEC_ID_NONE) {
1730 const AVCodecDescriptor *desc = avcodec_descriptor_get(st->codecpar->codec_id);
1731 if (desc && desc->mime_types) {
1732 return desc->mime_types[0];
1733 } else if (st->codecpar->codec_id == AV_CODEC_ID_TEXT)
1734 return "text/plain";
1740 static int mkv_write_attachments(AVFormatContext *s)
1742 MatroskaMuxContext *mkv = s->priv_data;
1743 AVIOContext *dyn_cp = NULL, *pb = s->pb;
1746 if (!mkv->nb_attachments)
1749 ret = start_ebml_master_crc32(&dyn_cp, mkv);
1753 for (i = 0; i < s->nb_streams; i++) {
1754 const AVStream *st = s->streams[i];
1755 mkv_track *track = &mkv->tracks[i];
1756 ebml_master attached_file;
1757 const AVDictionaryEntry *t;
1758 const char *mimetype;
1760 if (st->codecpar->codec_type != AVMEDIA_TYPE_ATTACHMENT)
1763 attached_file = start_ebml_master(dyn_cp, MATROSKA_ID_ATTACHEDFILE, 0);
1765 if (t = av_dict_get(st->metadata, "title", NULL, 0))
1766 put_ebml_string(dyn_cp, MATROSKA_ID_FILEDESC, t->value);
1767 if (!(t = av_dict_get(st->metadata, "filename", NULL, 0))) {
1768 av_log(s, AV_LOG_ERROR, "Attachment stream %d has no filename tag.\n", i);
1769 ffio_free_dyn_buf(&dyn_cp);
1770 return AVERROR(EINVAL);
1772 put_ebml_string(dyn_cp, MATROSKA_ID_FILENAME, t->value);
1774 mimetype = get_mimetype(st);
1775 av_assert0(mimetype);
1776 put_ebml_string(dyn_cp, MATROSKA_ID_FILEMIMETYPE, mimetype);
1777 put_ebml_binary(dyn_cp, MATROSKA_ID_FILEDATA, st->codecpar->extradata, st->codecpar->extradata_size);
1778 put_ebml_uid(dyn_cp, MATROSKA_ID_FILEUID, track->uid);
1779 end_ebml_master(dyn_cp, attached_file);
1781 return end_ebml_master_crc32(pb, &dyn_cp, mkv,
1782 MATROSKA_ID_ATTACHMENTS, 0, 0, 1);
1785 static int64_t get_metadata_duration(AVFormatContext *s)
1787 const AVDictionaryEntry *duration = av_dict_get(s->metadata, "DURATION",
1792 if (duration && (av_parse_time(&us, duration->value, 1) == 0) && us > 0) {
1793 av_log(s, AV_LOG_DEBUG, "get_metadata_duration found duration in context metadata: %" PRId64 "\n", us);
1797 for (unsigned i = 0; i < s->nb_streams; i++) {
1799 duration = av_dict_get(s->streams[i]->metadata, "DURATION", NULL, 0);
1801 if (duration && (av_parse_time(&us, duration->value, 1) == 0))
1802 max = FFMAX(max, us);
1805 av_log(s, AV_LOG_DEBUG, "get_metadata_duration returned: %" PRId64 "\n", max);
1809 static int mkv_write_header(AVFormatContext *s)
1811 MatroskaMuxContext *mkv = s->priv_data;
1812 AVIOContext *pb = s->pb;
1813 ebml_master ebml_header;
1814 const AVDictionaryEntry *tag;
1815 int ret, i, version = 2;
1816 int64_t creation_time;
1818 if (mkv->mode != MODE_WEBM ||
1819 av_dict_get(s->metadata, "stereo_mode", NULL, 0) ||
1820 av_dict_get(s->metadata, "alpha_mode", NULL, 0))
1823 for (i = 0; i < s->nb_streams; i++) {
1824 if (s->streams[i]->codecpar->codec_id == AV_CODEC_ID_OPUS ||
1825 av_dict_get(s->streams[i]->metadata, "stereo_mode", NULL, 0) ||
1826 av_dict_get(s->streams[i]->metadata, "alpha_mode", NULL, 0))
1830 ebml_header = start_ebml_master(pb, EBML_ID_HEADER, MAX_EBML_HEADER_SIZE);
1831 put_ebml_uint (pb, EBML_ID_EBMLVERSION , 1);
1832 put_ebml_uint (pb, EBML_ID_EBMLREADVERSION , 1);
1833 put_ebml_uint (pb, EBML_ID_EBMLMAXIDLENGTH , 4);
1834 put_ebml_uint (pb, EBML_ID_EBMLMAXSIZELENGTH , 8);
1835 put_ebml_string(pb, EBML_ID_DOCTYPE , s->oformat->name);
1836 put_ebml_uint (pb, EBML_ID_DOCTYPEVERSION , version);
1837 put_ebml_uint (pb, EBML_ID_DOCTYPEREADVERSION, 2);
1838 end_ebml_master(pb, ebml_header);
1840 put_ebml_id(pb, MATROSKA_ID_SEGMENT);
1841 put_ebml_size_unknown(pb, 8);
1842 mkv->segment_offset = avio_tell(pb);
1844 // We write a SeekHead at the beginning to point to all other level
1845 // one elements (except Clusters).
1846 mkv_start_seekhead(mkv, pb);
1848 ret = start_ebml_master_crc32(&mkv->info.bc, mkv);
1853 put_ebml_uint(pb, MATROSKA_ID_TIMECODESCALE, 1000000);
1854 if ((tag = av_dict_get(s->metadata, "title", NULL, 0)))
1855 put_ebml_string(pb, MATROSKA_ID_TITLE, tag->value);
1856 if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
1857 put_ebml_string(pb, MATROSKA_ID_MUXINGAPP, LIBAVFORMAT_IDENT);
1858 if ((tag = av_dict_get(s->metadata, "encoding_tool", NULL, 0)))
1859 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, tag->value);
1861 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, LIBAVFORMAT_IDENT);
1863 if (mkv->mode != MODE_WEBM)
1864 put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, mkv->segment_uid, 16);
1866 const char *ident = "Lavf";
1867 put_ebml_string(pb, MATROSKA_ID_MUXINGAPP , ident);
1868 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, ident);
1871 if (ff_parse_creation_time_metadata(s, &creation_time, 0) > 0) {
1872 // Adjust time so it's relative to 2001-01-01 and convert to nanoseconds.
1873 int64_t date_utc = (creation_time - 978307200000000LL) * 1000;
1874 uint8_t date_utc_buf[8];
1875 AV_WB64(date_utc_buf, date_utc);
1876 put_ebml_binary(pb, MATROSKA_ID_DATEUTC, date_utc_buf, 8);
1879 // reserve space for the duration
1881 mkv->duration_offset = avio_tell(pb);
1882 if (!mkv->is_live) {
1883 int64_t metadata_duration = get_metadata_duration(s);
1885 if (s->duration > 0) {
1886 int64_t scaledDuration = av_rescale(s->duration, 1000, AV_TIME_BASE);
1887 put_ebml_float(pb, MATROSKA_ID_DURATION, scaledDuration);
1888 av_log(s, AV_LOG_DEBUG, "Write early duration from recording time = %" PRIu64 "\n", scaledDuration);
1889 } else if (metadata_duration > 0) {
1890 int64_t scaledDuration = av_rescale(metadata_duration, 1000, AV_TIME_BASE);
1891 put_ebml_float(pb, MATROSKA_ID_DURATION, scaledDuration);
1892 av_log(s, AV_LOG_DEBUG, "Write early duration from metadata = %" PRIu64 "\n", scaledDuration);
1893 } else if (s->pb->seekable & AVIO_SEEKABLE_NORMAL) {
1894 put_ebml_void(pb, 11); // assumes double-precision float to be written
1897 ret = end_ebml_master_crc32_tentatively(s->pb, &mkv->info,
1898 mkv, MATROSKA_ID_INFO);
1903 ret = mkv_write_tracks(s);
1907 ret = mkv_write_chapters(s);
1911 if (mkv->mode != MODE_WEBM) {
1912 ret = mkv_write_attachments(s);
1917 /* Must come after mkv_write_chapters() to write chapter tags
1918 * into the same Tags element as the other tags. */
1919 ret = mkv_write_tags(s);
1923 if (!IS_SEEKABLE(pb, mkv)) {
1924 ret = mkv_write_seekhead(pb, mkv, 0, avio_tell(pb));
1929 if (s->metadata_header_padding > 0) {
1930 if (s->metadata_header_padding == 1)
1931 s->metadata_header_padding++;
1932 put_ebml_void(pb, s->metadata_header_padding);
1935 if (mkv->reserve_cues_space) {
1936 if (IS_SEEKABLE(pb, mkv)) {
1937 mkv->cues_pos = avio_tell(pb);
1938 if (mkv->reserve_cues_space == 1)
1939 mkv->reserve_cues_space++;
1940 put_ebml_void(pb, mkv->reserve_cues_space);
1942 mkv->reserve_cues_space = -1;
1945 mkv->cluster_pos = -1;
1947 // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1948 // after 4k and on a keyframe
1949 if (IS_SEEKABLE(pb, mkv)) {
1950 if (mkv->cluster_time_limit < 0)
1951 mkv->cluster_time_limit = 5000;
1952 if (mkv->cluster_size_limit < 0)
1953 mkv->cluster_size_limit = 5 * 1024 * 1024;
1955 if (mkv->cluster_time_limit < 0)
1956 mkv->cluster_time_limit = 1000;
1957 if (mkv->cluster_size_limit < 0)
1958 mkv->cluster_size_limit = 32 * 1024;
1964 static int mkv_blockgroup_size(int pkt_size, int track_num_size)
1966 int size = pkt_size + track_num_size + 3;
1967 size += ebml_length_size(size);
1968 size += 2; // EBML ID for block and block duration
1969 size += 9; // max size of block duration incl. length field
1973 static int mkv_strip_wavpack(const uint8_t *src, uint8_t **pdst, int *size)
1980 dst = av_malloc(srclen);
1982 return AVERROR(ENOMEM);
1984 while (srclen >= WV_HEADER_SIZE) {
1987 ret = ff_wv_parse_header(&header, src);
1990 src += WV_HEADER_SIZE;
1991 srclen -= WV_HEADER_SIZE;
1993 if (srclen < header.blocksize) {
1994 ret = AVERROR_INVALIDDATA;
1998 if (header.initial) {
1999 AV_WL32(dst + offset, header.samples);
2002 AV_WL32(dst + offset, header.flags);
2003 AV_WL32(dst + offset + 4, header.crc);
2006 if (!(header.initial && header.final)) {
2007 AV_WL32(dst + offset, header.blocksize);
2011 memcpy(dst + offset, src, header.blocksize);
2012 src += header.blocksize;
2013 srclen -= header.blocksize;
2014 offset += header.blocksize;
2026 static int mkv_write_block(AVFormatContext *s, AVIOContext *pb,
2027 uint32_t blockid, const AVPacket *pkt, int keyframe)
2029 MatroskaMuxContext *mkv = s->priv_data;
2030 AVCodecParameters *par = s->streams[pkt->stream_index]->codecpar;
2031 mkv_track *track = &mkv->tracks[pkt->stream_index];
2032 uint8_t *data = NULL, *side_data = NULL;
2033 size_t side_data_size;
2034 int err = 0, offset = 0, size = pkt->size;
2035 int64_t ts = track->write_dts ? pkt->dts : pkt->pts;
2036 uint64_t additional_id;
2037 int64_t discard_padding = 0;
2038 unsigned track_number = track->track_num;
2039 ebml_master block_group, block_additions, block_more;
2041 ts += track->ts_offset;
2043 /* The following string is identical to the one in mkv_write_vtt_blocks
2044 * so that only one copy needs to exist in binaries. */
2045 av_log(s, AV_LOG_DEBUG,
2046 "Writing block of size %d with pts %" PRId64 ", dts %" PRId64 ", "
2047 "duration %" PRId64 " at relative offset %" PRId64 " in cluster "
2048 "at offset %" PRId64 ". TrackNumber %u, keyframe %d\n",
2049 pkt->size, pkt->pts, pkt->dts, pkt->duration, avio_tell(pb),
2050 mkv->cluster_pos, track_number, keyframe != 0);
2052 if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 0 &&
2053 (AV_RB24(par->extradata) == 1 || AV_RB32(par->extradata) == 1)) {
2054 err = ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
2055 } else if (par->codec_id == AV_CODEC_ID_HEVC && par->extradata_size > 6 &&
2056 (AV_RB24(par->extradata) == 1 || AV_RB32(par->extradata) == 1)) {
2057 /* extradata is Annex B, assume the bitstream is too and convert it */
2058 err = ff_hevc_annexb2mp4_buf(pkt->data, &data, &size, 0, NULL);
2059 } else if (par->codec_id == AV_CODEC_ID_AV1) {
2060 err = ff_av1_filter_obus_buf(pkt->data, &data, &size, &offset);
2061 } else if (par->codec_id == AV_CODEC_ID_WAVPACK) {
2062 err = mkv_strip_wavpack(pkt->data, &data, &size);
2067 av_log(s, AV_LOG_ERROR, "Error when reformatting data of "
2068 "a packet from stream %d.\n", pkt->stream_index);
2072 if (par->codec_id == AV_CODEC_ID_PRORES && size >= 8) {
2073 /* Matroska specification requires to remove the first QuickTime atom
2079 side_data = av_packet_get_side_data(pkt,
2080 AV_PKT_DATA_SKIP_SAMPLES,
2082 if (side_data && side_data_size >= 10) {
2083 discard_padding = av_rescale_q(AV_RL32(side_data + 4),
2084 (AVRational){1, par->sample_rate},
2085 (AVRational){1, 1000000000});
2088 side_data = av_packet_get_side_data(pkt,
2089 AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,
2092 // Only the Codec-specific BlockMore (id == 1) is currently supported.
2093 if (side_data_size < 8 || (additional_id = AV_RB64(side_data)) != 1) {
2097 side_data_size -= 8;
2101 if (side_data_size || discard_padding) {
2102 block_group = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, 0);
2103 blockid = MATROSKA_ID_BLOCK;
2106 put_ebml_id(pb, blockid);
2107 put_ebml_length(pb, size + track->track_num_size + 3, 0);
2108 put_ebml_num(pb, track_number, track->track_num_size);
2109 avio_wb16(pb, ts - mkv->cluster_pts);
2110 avio_w8(pb, (blockid == MATROSKA_ID_SIMPLEBLOCK && keyframe) ? (1 << 7) : 0);
2111 avio_write(pb, data + offset, size);
2112 if (data != pkt->data)
2115 if (blockid == MATROSKA_ID_BLOCK && !keyframe)
2116 put_ebml_sint(pb, MATROSKA_ID_BLOCKREFERENCE, track->last_timestamp - ts);
2117 track->last_timestamp = ts;
2119 if (discard_padding)
2120 put_ebml_sint(pb, MATROSKA_ID_DISCARDPADDING, discard_padding);
2122 if (side_data_size) {
2123 block_additions = start_ebml_master(pb, MATROSKA_ID_BLOCKADDITIONS, 0);
2124 block_more = start_ebml_master(pb, MATROSKA_ID_BLOCKMORE, 0);
2125 /* Until dbc50f8a our demuxer used a wrong default value
2126 * of BlockAddID, so we write it unconditionally. */
2127 put_ebml_uint (pb, MATROSKA_ID_BLOCKADDID, additional_id);
2128 put_ebml_binary(pb, MATROSKA_ID_BLOCKADDITIONAL,
2129 side_data, side_data_size);
2130 end_ebml_master(pb, block_more);
2131 end_ebml_master(pb, block_additions);
2133 if (side_data_size || discard_padding)
2134 end_ebml_master(pb, block_group);
2139 static int mkv_write_vtt_blocks(AVFormatContext *s, AVIOContext *pb, const AVPacket *pkt)
2141 MatroskaMuxContext *mkv = s->priv_data;
2142 mkv_track *track = &mkv->tracks[pkt->stream_index];
2143 ebml_master blockgroup;
2144 size_t id_size, settings_size;
2145 int size, id_size_int, settings_size_int;
2146 const char *id, *settings;
2147 int64_t ts = track->write_dts ? pkt->dts : pkt->pts;
2148 const int flags = 0;
2150 id = av_packet_get_side_data(pkt, AV_PKT_DATA_WEBVTT_IDENTIFIER,
2154 settings = av_packet_get_side_data(pkt, AV_PKT_DATA_WEBVTT_SETTINGS,
2156 settings = settings ? settings : "";
2158 if (id_size > INT_MAX - 2 || settings_size > INT_MAX - id_size - 2 ||
2159 pkt->size > INT_MAX - settings_size - id_size - 2)
2160 return AVERROR(EINVAL);
2162 size = id_size + 1 + settings_size + 1 + pkt->size;
2164 /* The following string is identical to the one in mkv_write_block so that
2165 * only one copy needs to exist in binaries. */
2166 av_log(s, AV_LOG_DEBUG,
2167 "Writing block of size %d with pts %" PRId64 ", dts %" PRId64 ", "
2168 "duration %" PRId64 " at relative offset %" PRId64 " in cluster "
2169 "at offset %" PRId64 ". TrackNumber %u, keyframe %d\n",
2170 size, pkt->pts, pkt->dts, pkt->duration, avio_tell(pb),
2171 mkv->cluster_pos, track->track_num, 1);
2173 blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
2174 mkv_blockgroup_size(size, track->track_num_size));
2176 put_ebml_id(pb, MATROSKA_ID_BLOCK);
2177 put_ebml_length(pb, size + track->track_num_size + 3, 0);
2178 put_ebml_num(pb, track->track_num, track->track_num_size);
2179 avio_wb16(pb, ts - mkv->cluster_pts);
2182 id_size_int = id_size;
2183 settings_size_int = settings_size;
2184 avio_printf(pb, "%.*s\n%.*s\n%.*s", id_size_int, id, settings_size_int, settings, pkt->size, pkt->data);
2186 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, pkt->duration);
2187 end_ebml_master(pb, blockgroup);
2192 static int mkv_end_cluster(AVFormatContext *s)
2194 MatroskaMuxContext *mkv = s->priv_data;
2197 if (!mkv->have_video) {
2198 for (unsigned i = 0; i < s->nb_streams; i++)
2199 mkv->tracks[i].has_cue = 0;
2201 mkv->cluster_pos = -1;
2202 ret = end_ebml_master_crc32(s->pb, &mkv->cluster_bc, mkv,
2203 MATROSKA_ID_CLUSTER, 0, 1, 0);
2207 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_FLUSH_POINT);
2211 static int mkv_check_new_extra_data(AVFormatContext *s, const AVPacket *pkt)
2213 MatroskaMuxContext *mkv = s->priv_data;
2214 mkv_track *track = &mkv->tracks[pkt->stream_index];
2215 AVCodecParameters *par = s->streams[pkt->stream_index]->codecpar;
2217 size_t side_data_size;
2220 side_data = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
2223 switch (par->codec_id) {
2224 case AV_CODEC_ID_AAC:
2225 if (side_data_size && mkv->track.bc) {
2226 int filler, output_sample_rate = 0;
2227 ret = get_aac_sample_rates(s, mkv, side_data, side_data_size,
2228 &track->sample_rate, &output_sample_rate);
2231 if (!output_sample_rate)
2232 output_sample_rate = track->sample_rate; // Space is already reserved, so it's this or a void element.
2233 ret = ff_alloc_extradata(par, side_data_size);
2236 memcpy(par->extradata, side_data, side_data_size);
2237 avio_seek(mkv->track.bc, track->codecpriv_offset, SEEK_SET);
2238 mkv_write_codecprivate(s, mkv->track.bc, par, 1, 0);
2239 filler = MAX_PCE_SIZE + 2 + 4 - (avio_tell(mkv->track.bc) - track->codecpriv_offset);
2241 put_ebml_void(mkv->track.bc, filler);
2242 avio_seek(mkv->track.bc, track->sample_rate_offset, SEEK_SET);
2243 put_ebml_float(mkv->track.bc, MATROSKA_ID_AUDIOSAMPLINGFREQ, track->sample_rate);
2244 put_ebml_float(mkv->track.bc, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
2245 } else if (!par->extradata_size && !track->sample_rate) {
2246 // No extradata (codecpar or packet side data).
2247 av_log(s, AV_LOG_ERROR, "Error parsing AAC extradata, unable to determine samplerate.\n");
2248 return AVERROR(EINVAL);
2251 case AV_CODEC_ID_FLAC:
2252 if (side_data_size && mkv->track.bc) {
2253 uint8_t *old_extradata = par->extradata;
2254 if (side_data_size != par->extradata_size) {
2255 av_log(s, AV_LOG_ERROR, "Invalid FLAC STREAMINFO metadata for output stream %d\n",
2257 return AVERROR(EINVAL);
2259 par->extradata = side_data;
2260 avio_seek(mkv->track.bc, track->codecpriv_offset, SEEK_SET);
2261 mkv_write_codecprivate(s, mkv->track.bc, par, 1, 0);
2262 par->extradata = old_extradata;
2265 // FIXME: Remove the following once libaom starts propagating extradata during init()
2266 // See https://bugs.chromium.org/p/aomedia/issues/detail?id=2012
2267 case AV_CODEC_ID_AV1:
2268 if (side_data_size && mkv->track.bc && !par->extradata_size) {
2269 AVIOContext *dyn_cp;
2272 ret = avio_open_dyn_buf(&dyn_cp);
2275 ff_isom_write_av1c(dyn_cp, side_data, side_data_size);
2276 codecpriv_size = avio_get_dyn_buf(dyn_cp, &codecpriv);
2277 if ((ret = dyn_cp->error) < 0 ||
2278 !codecpriv_size && (ret = AVERROR_INVALIDDATA)) {
2279 ffio_free_dyn_buf(&dyn_cp);
2282 avio_seek(mkv->track.bc, track->codecpriv_offset, SEEK_SET);
2283 // Do not write the OBUs as we don't have space saved for them
2284 put_ebml_binary(mkv->track.bc, MATROSKA_ID_CODECPRIVATE, codecpriv, 4);
2285 ffio_free_dyn_buf(&dyn_cp);
2286 ret = ff_alloc_extradata(par, side_data_size);
2289 memcpy(par->extradata, side_data, side_data_size);
2290 } else if (!par->extradata_size)
2291 return AVERROR_INVALIDDATA;
2295 av_log(s, AV_LOG_DEBUG, "Ignoring new extradata in a packet for stream %d.\n", pkt->stream_index);
2302 static int mkv_write_packet_internal(AVFormatContext *s, const AVPacket *pkt)
2304 MatroskaMuxContext *mkv = s->priv_data;
2306 AVCodecParameters *par = s->streams[pkt->stream_index]->codecpar;
2307 mkv_track *track = &mkv->tracks[pkt->stream_index];
2308 int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
2309 int64_t duration = pkt->duration;
2311 int64_t ts = track->write_dts ? pkt->dts : pkt->pts;
2312 int64_t relative_packet_pos;
2314 if (ts == AV_NOPTS_VALUE) {
2315 av_log(s, AV_LOG_ERROR, "Can't write packet with unknown timestamp\n");
2316 return AVERROR(EINVAL);
2318 ts += track->ts_offset;
2320 if (mkv->cluster_pos != -1) {
2321 int64_t cluster_time = ts - mkv->cluster_pts;
2322 if ((int16_t)cluster_time != cluster_time) {
2323 ret = mkv_end_cluster(s);
2326 av_log(s, AV_LOG_WARNING, "Starting new cluster due to timestamp\n");
2330 if (mkv->cluster_pos == -1) {
2331 ret = start_ebml_master_crc32(&mkv->cluster_bc, mkv);
2334 mkv->cluster_pos = avio_tell(s->pb);
2335 put_ebml_uint(mkv->cluster_bc, MATROSKA_ID_CLUSTERTIMECODE, FFMAX(0, ts));
2336 mkv->cluster_pts = FFMAX(0, ts);
2337 av_log(s, AV_LOG_DEBUG,
2338 "Starting new cluster with timestamp "
2339 "%" PRId64 " at offset %" PRId64 " bytes\n",
2340 mkv->cluster_pts, mkv->cluster_pos);
2342 pb = mkv->cluster_bc;
2344 relative_packet_pos = avio_tell(pb);
2346 if (par->codec_type != AVMEDIA_TYPE_SUBTITLE ||
2347 (par->codec_id != AV_CODEC_ID_WEBVTT && duration <= 0)) {
2348 ret = mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe);
2351 if (keyframe && IS_SEEKABLE(s->pb, mkv) &&
2352 (par->codec_type == AVMEDIA_TYPE_VIDEO ||
2353 par->codec_type == AVMEDIA_TYPE_SUBTITLE ||
2354 !mkv->have_video && !track->has_cue)) {
2355 ret = mkv_add_cuepoint(mkv, pkt->stream_index, ts,
2356 mkv->cluster_pos, relative_packet_pos, 0);
2362 if (par->codec_id == AV_CODEC_ID_WEBVTT) {
2363 ret = mkv_write_vtt_blocks(s, pb, pkt);
2367 ebml_master blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
2368 mkv_blockgroup_size(pkt->size,
2369 track->track_num_size));
2371 /* All subtitle blocks are considered to be keyframes. */
2372 mkv_write_block(s, pb, MATROSKA_ID_BLOCK, pkt, 1);
2373 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
2374 end_ebml_master(pb, blockgroup);
2377 if (IS_SEEKABLE(s->pb, mkv)) {
2378 ret = mkv_add_cuepoint(mkv, pkt->stream_index, ts,
2379 mkv->cluster_pos, relative_packet_pos, duration);
2385 mkv->duration = FFMAX(mkv->duration, ts + duration);
2386 track->duration = FFMAX(track->duration, ts + duration);
2391 static int mkv_write_packet(AVFormatContext *s, const AVPacket *pkt)
2393 MatroskaMuxContext *mkv = s->priv_data;
2394 int codec_type = s->streams[pkt->stream_index]->codecpar->codec_type;
2395 int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
2397 int64_t cluster_time;
2399 int start_new_cluster;
2401 ret = mkv_check_new_extra_data(s, pkt);
2405 if (mkv->cluster_pos != -1) {
2406 if (mkv->tracks[pkt->stream_index].write_dts)
2407 cluster_time = pkt->dts - mkv->cluster_pts;
2409 cluster_time = pkt->pts - mkv->cluster_pts;
2410 cluster_time += mkv->tracks[pkt->stream_index].ts_offset;
2412 cluster_size = avio_tell(mkv->cluster_bc);
2414 if (mkv->is_dash && codec_type == AVMEDIA_TYPE_VIDEO) {
2415 // WebM DASH specification states that the first block of
2416 // every Cluster has to be a key frame. So for DASH video,
2417 // we only create a Cluster on seeing key frames.
2418 start_new_cluster = keyframe;
2419 } else if (mkv->is_dash && codec_type == AVMEDIA_TYPE_AUDIO &&
2420 cluster_time > mkv->cluster_time_limit) {
2421 // For DASH audio, we create a Cluster based on cluster_time_limit.
2422 start_new_cluster = 1;
2423 } else if (!mkv->is_dash &&
2424 (cluster_size > mkv->cluster_size_limit ||
2425 cluster_time > mkv->cluster_time_limit ||
2426 (codec_type == AVMEDIA_TYPE_VIDEO && keyframe &&
2427 cluster_size > 4 * 1024))) {
2428 start_new_cluster = 1;
2430 start_new_cluster = 0;
2432 if (start_new_cluster) {
2433 ret = mkv_end_cluster(s);
2439 if (!mkv->cluster_pos)
2440 avio_write_marker(s->pb,
2441 av_rescale_q(pkt->dts, s->streams[pkt->stream_index]->time_base, AV_TIME_BASE_Q),
2442 keyframe && (mkv->have_video ? codec_type == AVMEDIA_TYPE_VIDEO : 1) ? AVIO_DATA_MARKER_SYNC_POINT : AVIO_DATA_MARKER_BOUNDARY_POINT);
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);
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);
2455 // buffer an audio packet to ensure the packet containing the video
2456 // keyframe's timecode is contained in the same cluster for WebM
2457 if (codec_type == AVMEDIA_TYPE_AUDIO) {
2459 ret = av_packet_ref(mkv->cur_audio_pkt, pkt);
2461 ret = mkv_write_packet_internal(s, pkt);
2465 static int mkv_write_flush_packet(AVFormatContext *s, AVPacket *pkt)
2467 MatroskaMuxContext *mkv = s->priv_data;
2470 if (mkv->cluster_pos != -1) {
2471 int ret = mkv_end_cluster(s);
2474 av_log(s, AV_LOG_DEBUG,
2475 "Flushing cluster at offset %" PRIu64 " bytes\n",
2480 return mkv_write_packet(s, pkt);
2483 static int mkv_write_trailer(AVFormatContext *s)
2485 MatroskaMuxContext *mkv = s->priv_data;
2486 AVIOContext *pb = s->pb;
2487 int64_t endpos, ret64;
2490 // check if we have an audio packet cached
2491 if (mkv->cur_audio_pkt->size > 0) {
2492 ret = mkv_write_packet_internal(s, mkv->cur_audio_pkt);
2494 av_log(s, AV_LOG_ERROR,
2495 "Could not write cached audio packet ret:%d\n", ret);
2500 if (mkv->cluster_pos != -1) {
2501 ret = end_ebml_master_crc32(pb, &mkv->cluster_bc, mkv,
2502 MATROSKA_ID_CLUSTER, 0, 0, 0);
2507 ret = mkv_write_chapters(s);
2511 if (!IS_SEEKABLE(pb, mkv))
2514 endpos = avio_tell(pb);
2516 if (mkv->cues.num_entries && mkv->reserve_cues_space >= 0) {
2517 AVIOContext *cues = NULL;
2519 int length_size = 0;
2521 ret = start_ebml_master_crc32(&cues, mkv);
2525 ret = mkv_assemble_cues(s->streams, cues, &mkv->cues,
2526 mkv->tracks, s->nb_streams);
2528 ffio_free_dyn_buf(&cues);
2532 if (mkv->reserve_cues_space) {
2533 size = avio_tell(cues);
2534 length_size = ebml_length_size(size);
2535 size += 4 + length_size;
2536 if (mkv->reserve_cues_space < size) {
2537 av_log(s, AV_LOG_WARNING,
2538 "Insufficient space reserved for Cues: "
2539 "%d < %"PRIu64". No Cues will be output.\n",
2540 mkv->reserve_cues_space, size);
2541 ret2 = AVERROR(EINVAL);
2544 if ((ret64 = avio_seek(pb, mkv->cues_pos, SEEK_SET)) < 0) {
2545 ffio_free_dyn_buf(&cues);
2548 if (mkv->reserve_cues_space == size + 1) {
2549 /* There is no way to reserve a single byte because
2550 * the minimal size of an EBML Void element is 2
2551 * (1 byte ID, 1 byte length field). This problem
2552 * is solved by writing the Cues' length field on
2553 * one byte more than necessary. */
2559 ret = end_ebml_master_crc32(pb, &cues, mkv, MATROSKA_ID_CUES,
2563 if (mkv->reserve_cues_space) {
2564 if (size < mkv->reserve_cues_space)
2565 put_ebml_void(pb, mkv->reserve_cues_space - size);
2567 endpos = avio_tell(pb);
2571 /* Lengths greater than (1ULL << 56) - 1 can't be represented
2572 * via an EBML number, so leave the unknown length field. */
2573 if (endpos - mkv->segment_offset < (1ULL << 56) - 1) {
2574 if ((ret64 = avio_seek(pb, mkv->segment_offset - 8, SEEK_SET)) < 0)
2576 put_ebml_length(pb, endpos - mkv->segment_offset, 8);
2579 ret = mkv_write_seekhead(pb, mkv, 1, mkv->info.pos);
2584 // update the duration
2585 av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
2586 avio_seek(mkv->info.bc, mkv->duration_offset, SEEK_SET);
2587 put_ebml_float(mkv->info.bc, MATROSKA_ID_DURATION, mkv->duration);
2588 ret = end_ebml_master_crc32(pb, &mkv->info.bc, mkv,
2589 MATROSKA_ID_INFO, 0, 0, 0);
2594 if (mkv->track.bc) {
2595 // write Tracks master
2596 avio_seek(pb, mkv->track.pos, SEEK_SET);
2597 ret = end_ebml_master_crc32(pb, &mkv->track.bc, mkv,
2598 MATROSKA_ID_TRACKS, 0, 0, 0);
2603 // update stream durations
2606 for (i = 0; i < s->nb_streams; ++i) {
2607 const AVStream *st = s->streams[i];
2608 const mkv_track *track = &mkv->tracks[i];
2610 if (track->duration_offset > 0) {
2611 double duration_sec = track->duration * av_q2d(st->time_base);
2612 char duration_string[20] = "";
2614 av_log(s, AV_LOG_DEBUG, "stream %d end duration = %" PRIu64 "\n", i,
2617 avio_seek(mkv->tags.bc, track->duration_offset, SEEK_SET);
2619 snprintf(duration_string, 20, "%02d:%02d:%012.9f",
2620 (int) duration_sec / 3600, ((int) duration_sec / 60) % 60,
2621 fmod(duration_sec, 60));
2623 put_ebml_binary(mkv->tags.bc, MATROSKA_ID_TAGSTRING, duration_string, 20);
2627 avio_seek(pb, mkv->tags.pos, SEEK_SET);
2628 ret = end_ebml_master_crc32(pb, &mkv->tags.bc, mkv,
2629 MATROSKA_ID_TAGS, 0, 0, 0);
2634 avio_seek(pb, endpos, SEEK_SET);
2639 static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
2642 for (i = 0; ff_mkv_codec_tags[i].id != AV_CODEC_ID_NONE; i++)
2643 if (ff_mkv_codec_tags[i].id == codec_id)
2646 if (std_compliance < FF_COMPLIANCE_NORMAL) {
2647 enum AVMediaType type = avcodec_get_type(codec_id);
2648 // mkv theoretically supports any video/audio through VFW/ACM
2649 if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)
2656 static int webm_query_codec(enum AVCodecID codec_id, int std_compliance)
2659 for (i = 0; ff_webm_codec_tags[i].id != AV_CODEC_ID_NONE; i++)
2660 if (ff_webm_codec_tags[i].id == codec_id)
2666 static uint64_t mkv_get_uid(const mkv_track *tracks, int i, AVLFG *c)
2671 uid = (uint64_t)av_lfg_get(c) << 32;
2672 uid |= av_lfg_get(c);
2675 for (k = 0; k < i; k++) {
2676 if (tracks[k].uid == uid)
2684 static int mkv_init(struct AVFormatContext *s)
2686 MatroskaMuxContext *mkv = s->priv_data;
2688 unsigned nb_tracks = 0;
2691 for (i = 0; i < s->nb_streams; i++) {
2692 if (s->streams[i]->codecpar->codec_id == AV_CODEC_ID_ATRAC3 ||
2693 s->streams[i]->codecpar->codec_id == AV_CODEC_ID_COOK ||
2694 s->streams[i]->codecpar->codec_id == AV_CODEC_ID_RA_288 ||
2695 s->streams[i]->codecpar->codec_id == AV_CODEC_ID_SIPR ||
2696 s->streams[i]->codecpar->codec_id == AV_CODEC_ID_RV10 ||
2697 s->streams[i]->codecpar->codec_id == AV_CODEC_ID_RV20) {
2698 av_log(s, AV_LOG_ERROR,
2699 "The Matroska muxer does not yet support muxing %s\n",
2700 avcodec_get_name(s->streams[i]->codecpar->codec_id));
2701 return AVERROR_PATCHWELCOME;
2705 if (s->avoid_negative_ts < 0) {
2706 s->avoid_negative_ts = 1;
2707 s->internal->avoid_negative_ts_use_pts = 1;
2710 if (!strcmp(s->oformat->name, "webm")) {
2711 mkv->mode = MODE_WEBM;
2714 mkv->mode = MODE_MATROSKAv2;
2716 mkv->cur_audio_pkt = av_packet_alloc();
2717 if (!mkv->cur_audio_pkt)
2718 return AVERROR(ENOMEM);
2719 mkv->tracks = av_mallocz_array(s->nb_streams, sizeof(*mkv->tracks));
2721 return AVERROR(ENOMEM);
2723 if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
2724 av_lfg_init(&c, av_get_random_seed());
2726 // Calculate the SegmentUID now in order not to waste our random seed.
2727 for (i = 0; i < 4; i++)
2728 mkv->segment_uid[i] = av_lfg_get(&c);
2731 for (i = 0; i < s->nb_streams; i++) {
2732 AVStream *st = s->streams[i];
2733 mkv_track *track = &mkv->tracks[i];
2735 if (s->flags & AVFMT_FLAG_BITEXACT) {
2738 track->uid = mkv_get_uid(mkv->tracks, i, &c);
2741 // ms precision is the de-facto standard timescale for mkv files
2742 avpriv_set_pts_info(st, 64, 1, 1000);
2744 if (st->codecpar->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
2745 if (mkv->mode == MODE_WEBM) {
2746 av_log(s, AV_LOG_WARNING, "Stream %d will be ignored "
2747 "as WebM doesn't support attachments.\n", i);
2748 } else if (!get_mimetype(st)) {
2749 av_log(s, AV_LOG_ERROR, "Attachment stream %d has no mimetype "
2750 "tag and it cannot be deduced from the codec id.\n", i);
2751 return AVERROR(EINVAL);
2753 mkv->nb_attachments++;
2758 track->track_num = mkv->is_dash ? mkv->dash_track_number : nb_tracks;
2759 track->track_num_size = ebml_num_size(track->track_num);
2762 if (mkv->is_dash && nb_tracks != 1)
2763 return AVERROR(EINVAL);
2768 static int mkv_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
2771 AVStream *st = s->streams[pkt->stream_index];
2773 if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
2774 if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
2775 ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
2776 } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) {
2777 ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL);
2783 static const AVCodecTag additional_audio_tags[] = {
2784 { AV_CODEC_ID_ALAC, 0XFFFFFFFF },
2785 { AV_CODEC_ID_MLP, 0xFFFFFFFF },
2786 { AV_CODEC_ID_OPUS, 0xFFFFFFFF },
2787 { AV_CODEC_ID_PCM_S16BE, 0xFFFFFFFF },
2788 { AV_CODEC_ID_PCM_S24BE, 0xFFFFFFFF },
2789 { AV_CODEC_ID_PCM_S32BE, 0xFFFFFFFF },
2790 { AV_CODEC_ID_QDMC, 0xFFFFFFFF },
2791 { AV_CODEC_ID_QDM2, 0xFFFFFFFF },
2792 { AV_CODEC_ID_RA_144, 0xFFFFFFFF },
2793 { AV_CODEC_ID_RA_288, 0xFFFFFFFF },
2794 { AV_CODEC_ID_COOK, 0xFFFFFFFF },
2795 { AV_CODEC_ID_TRUEHD, 0xFFFFFFFF },
2796 { AV_CODEC_ID_NONE, 0xFFFFFFFF }
2799 static const AVCodecTag additional_video_tags[] = {
2800 { AV_CODEC_ID_RV10, 0xFFFFFFFF },
2801 { AV_CODEC_ID_RV20, 0xFFFFFFFF },
2802 { AV_CODEC_ID_RV30, 0xFFFFFFFF },
2803 { AV_CODEC_ID_NONE, 0xFFFFFFFF }
2806 static const AVCodecTag additional_subtitle_tags[] = {
2807 { AV_CODEC_ID_DVB_SUBTITLE, 0xFFFFFFFF },
2808 { AV_CODEC_ID_DVD_SUBTITLE, 0xFFFFFFFF },
2809 { AV_CODEC_ID_HDMV_PGS_SUBTITLE, 0xFFFFFFFF },
2810 { AV_CODEC_ID_NONE, 0xFFFFFFFF }
2813 #define OFFSET(x) offsetof(MatroskaMuxContext, x)
2814 #define FLAGS AV_OPT_FLAG_ENCODING_PARAM
2815 static const AVOption options[] = {
2816 { "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 },
2817 { "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 },
2818 { "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 },
2819 { "dash", "Create a WebM file conforming to WebM DASH specification", OFFSET(is_dash), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
2820 { "dash_track_number", "Track number for the DASH stream", OFFSET(dash_track_number), AV_OPT_TYPE_INT, { .i64 = 1 }, 1, INT_MAX, FLAGS },
2821 { "live", "Write files assuming it is a live stream.", OFFSET(is_live), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
2822 { "allow_raw_vfw", "allow RAW VFW mode", OFFSET(allow_raw_vfw), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
2823 { "flipped_raw_rgb", "Raw RGB bitmaps in VFW mode are stored bottom-up", OFFSET(flipped_raw_rgb), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
2824 { "write_crc32", "write a CRC32 element inside every Level 1 element", OFFSET(write_crc), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, FLAGS },
2825 { "default_mode", "Controls how a track's FlagDefault is inferred", OFFSET(default_mode), AV_OPT_TYPE_INT, { .i64 = DEFAULT_MODE_INFER }, DEFAULT_MODE_INFER, DEFAULT_MODE_PASSTHROUGH, FLAGS, "default_mode" },
2826 { "infer", "For each track type, mark the first track of disposition default as default; if none exists, mark the first track as default.", 0, AV_OPT_TYPE_CONST, { .i64 = DEFAULT_MODE_INFER }, 0, 0, FLAGS, "default_mode" },
2827 { "infer_no_subs", "For each track type, mark the first track of disposition default as default; for audio and video: if none exists, mark the first track as default.", 0, AV_OPT_TYPE_CONST, { .i64 = DEFAULT_MODE_INFER_NO_SUBS }, 0, 0, FLAGS, "default_mode" },
2828 { "passthrough", "Use the disposition flag as-is", 0, AV_OPT_TYPE_CONST, { .i64 = DEFAULT_MODE_PASSTHROUGH }, 0, 0, FLAGS, "default_mode" },
2832 #if CONFIG_MATROSKA_MUXER
2833 static const AVClass matroska_class = {
2834 .class_name = "matroska muxer",
2835 .item_name = av_default_item_name,
2837 .version = LIBAVUTIL_VERSION_INT,
2840 const AVOutputFormat ff_matroska_muxer = {
2842 .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
2843 .mime_type = "video/x-matroska",
2844 .extensions = "mkv",
2845 .priv_data_size = sizeof(MatroskaMuxContext),
2846 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
2847 AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
2848 .video_codec = CONFIG_LIBX264_ENCODER ?
2849 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
2851 .deinit = mkv_deinit,
2852 .write_header = mkv_write_header,
2853 .write_packet = mkv_write_flush_packet,
2854 .write_trailer = mkv_write_trailer,
2855 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
2856 AVFMT_TS_NONSTRICT | AVFMT_ALLOW_FLUSH,
2857 .codec_tag = (const AVCodecTag* const []){
2858 ff_codec_bmp_tags, ff_codec_wav_tags,
2859 additional_audio_tags, additional_video_tags, additional_subtitle_tags, 0
2861 .subtitle_codec = AV_CODEC_ID_ASS,
2862 .query_codec = mkv_query_codec,
2863 .check_bitstream = mkv_check_bitstream,
2864 .priv_class = &matroska_class,
2868 #if CONFIG_WEBM_MUXER
2869 static const AVClass webm_class = {
2870 .class_name = "webm muxer",
2871 .item_name = av_default_item_name,
2873 .version = LIBAVUTIL_VERSION_INT,
2876 const AVOutputFormat ff_webm_muxer = {
2878 .long_name = NULL_IF_CONFIG_SMALL("WebM"),
2879 .mime_type = "video/webm",
2880 .extensions = "webm",
2881 .priv_data_size = sizeof(MatroskaMuxContext),
2882 .audio_codec = CONFIG_LIBOPUS_ENCODER ? AV_CODEC_ID_OPUS : AV_CODEC_ID_VORBIS,
2883 .video_codec = CONFIG_LIBVPX_VP9_ENCODER? AV_CODEC_ID_VP9 : AV_CODEC_ID_VP8,
2884 .subtitle_codec = AV_CODEC_ID_WEBVTT,
2886 .deinit = mkv_deinit,
2887 .write_header = mkv_write_header,
2888 .write_packet = mkv_write_flush_packet,
2889 .write_trailer = mkv_write_trailer,
2890 .query_codec = webm_query_codec,
2891 .check_bitstream = mkv_check_bitstream,
2892 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
2893 AVFMT_TS_NONSTRICT | AVFMT_ALLOW_FLUSH,
2894 .priv_class = &webm_class,
2898 #if CONFIG_MATROSKA_AUDIO_MUXER
2899 static const AVClass mka_class = {
2900 .class_name = "matroska audio muxer",
2901 .item_name = av_default_item_name,
2903 .version = LIBAVUTIL_VERSION_INT,
2905 const AVOutputFormat ff_matroska_audio_muxer = {
2907 .long_name = NULL_IF_CONFIG_SMALL("Matroska Audio"),
2908 .mime_type = "audio/x-matroska",
2909 .extensions = "mka",
2910 .priv_data_size = sizeof(MatroskaMuxContext),
2911 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
2912 AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
2913 .video_codec = AV_CODEC_ID_NONE,
2915 .deinit = mkv_deinit,
2916 .write_header = mkv_write_header,
2917 .write_packet = mkv_write_flush_packet,
2918 .write_trailer = mkv_write_trailer,
2919 .check_bitstream = mkv_check_bitstream,
2920 .flags = AVFMT_GLOBALHEADER | AVFMT_TS_NONSTRICT |
2922 .codec_tag = (const AVCodecTag* const []){
2923 ff_codec_wav_tags, additional_audio_tags, 0
2925 .priv_class = &mka_class,