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
24 #include "avio_internal.h"
25 #include "avlanguage.h"
33 #include "libavutil/avstring.h"
34 #include "libavutil/dict.h"
35 #include "libavutil/intfloat.h"
36 #include "libavutil/intreadwrite.h"
37 #include "libavutil/lfg.h"
38 #include "libavutil/mathematics.h"
39 #include "libavutil/opt.h"
40 #include "libavutil/random_seed.h"
41 #include "libavutil/samplefmt.h"
42 #include "libavutil/sha.h"
44 #include "libavcodec/xiph.h"
45 #include "libavcodec/mpeg4audio.h"
47 typedef struct ebml_master {
48 int64_t pos; ///< absolute offset in the file where the master's elements start
49 int sizebytes; ///< how many bytes were reserved for the size
52 typedef struct mkv_seekhead_entry {
53 unsigned int elementid;
57 typedef struct mkv_seekhead {
59 int64_t segment_offset; ///< the file offset to the beginning of the segment
60 int reserved_size; ///< -1 if appending to file
62 mkv_seekhead_entry *entries;
69 int64_t cluster_pos; ///< file offset of the cluster containing the block
70 int64_t relative_pos; ///< relative offset from the position of the cluster containing the block
74 int64_t segment_offset;
75 mkv_cuepoint *entries;
84 #define MODE_MATROSKAv2 0x01
85 #define MODE_WEBM 0x02
87 typedef struct MatroskaMuxContext {
92 int64_t segment_offset;
94 int64_t cluster_pos; ///< file offset of the current cluster
96 int64_t duration_offset;
98 mkv_seekhead *main_seekhead;
102 AVPacket cur_audio_pkt;
104 int have_attachments;
106 int reserve_cues_space;
107 int cluster_size_limit;
109 int64_t cluster_time_limit;
111 uint32_t chapter_id_offset;
112 } MatroskaMuxContext;
115 /** 2 bytes * 3 for EBML IDs, 3 1-byte EBML lengths, 8 bytes for 64 bit
116 * offset, 4 bytes for target EBML ID */
117 #define MAX_SEEKENTRY_SIZE 21
119 /** per-cuepoint-track - 4 1-byte EBML IDs, 4 1-byte EBML sizes, 3
121 #define MAX_CUETRACKPOS_SIZE 32
123 /** per-cuepoint - 2 1-byte EBML IDs, 2 1-byte EBML sizes, 8-byte uint max */
124 #define MAX_CUEPOINT_SIZE(num_tracks) 12 + MAX_CUETRACKPOS_SIZE*num_tracks
126 /** Seek preroll value for opus */
127 #define OPUS_SEEK_PREROLL 80000000
130 static int ebml_id_size(unsigned int id)
132 return (av_log2(id+1)-1)/7+1;
135 static void put_ebml_id(AVIOContext *pb, unsigned int id)
137 int i = ebml_id_size(id);
139 avio_w8(pb, (uint8_t)(id >> (i*8)));
143 * Write an EBML size meaning "unknown size".
145 * @param bytes The number of bytes the size should occupy (maximum: 8).
147 static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
149 av_assert0(bytes <= 8);
150 avio_w8(pb, 0x1ff >> bytes);
151 ffio_fill(pb, 0xff, bytes - 1);
155 * Calculate how many bytes are needed to represent a given number in EBML.
157 static int ebml_num_size(uint64_t num)
160 while ((num+1) >> bytes*7) bytes++;
165 * Write a number in EBML variable length format.
167 * @param bytes The number of bytes that need to be used to write the number.
168 * If zero, any number of bytes can be used.
170 static void put_ebml_num(AVIOContext *pb, uint64_t num, int bytes)
172 int i, needed_bytes = ebml_num_size(num);
174 // sizes larger than this are currently undefined in EBML
175 av_assert0(num < (1ULL<<56)-1);
178 // don't care how many bytes are used, so use the min
179 bytes = needed_bytes;
180 // the bytes needed to write the given size would exceed the bytes
181 // that we need to use, so write unknown size. This shouldn't happen.
182 av_assert0(bytes >= needed_bytes);
184 num |= 1ULL << bytes*7;
185 for (i = bytes - 1; i >= 0; i--)
186 avio_w8(pb, (uint8_t)(num >> i*8));
189 static void put_ebml_uint(AVIOContext *pb, unsigned int elementid, uint64_t val)
193 while (tmp>>=8) bytes++;
195 put_ebml_id(pb, elementid);
196 put_ebml_num(pb, bytes, 0);
197 for (i = bytes - 1; i >= 0; i--)
198 avio_w8(pb, (uint8_t)(val >> i*8));
201 static void put_ebml_float(AVIOContext *pb, unsigned int elementid, double val)
203 put_ebml_id(pb, elementid);
204 put_ebml_num(pb, 8, 0);
205 avio_wb64(pb, av_double2int(val));
208 static void put_ebml_binary(AVIOContext *pb, unsigned int elementid,
209 const void *buf, int size)
211 put_ebml_id(pb, elementid);
212 put_ebml_num(pb, size, 0);
213 avio_write(pb, buf, size);
216 static void put_ebml_string(AVIOContext *pb, unsigned int elementid, const char *str)
218 put_ebml_binary(pb, elementid, str, strlen(str));
222 * Write a void element of a given size. Useful for reserving space in
223 * the file to be written to later.
225 * @param size The number of bytes to reserve, which must be at least 2.
227 static void put_ebml_void(AVIOContext *pb, uint64_t size)
229 int64_t currentpos = avio_tell(pb);
231 av_assert0(size >= 2);
233 put_ebml_id(pb, EBML_ID_VOID);
234 // we need to subtract the length needed to store the size from the
235 // size we need to reserve so 2 cases, we use 8 bytes to store the
236 // size if possible, 1 byte otherwise
238 put_ebml_num(pb, size-1, 0);
240 put_ebml_num(pb, size-9, 8);
241 ffio_fill(pb, 0, currentpos + size - avio_tell(pb));
244 static ebml_master start_ebml_master(AVIOContext *pb, unsigned int elementid, uint64_t expectedsize)
246 int bytes = expectedsize ? ebml_num_size(expectedsize) : 8;
247 put_ebml_id(pb, elementid);
248 put_ebml_size_unknown(pb, bytes);
249 return (ebml_master){ avio_tell(pb), bytes };
252 static void end_ebml_master(AVIOContext *pb, ebml_master master)
254 int64_t pos = avio_tell(pb);
256 if (avio_seek(pb, master.pos - master.sizebytes, SEEK_SET) < 0)
258 put_ebml_num(pb, pos - master.pos, master.sizebytes);
259 avio_seek(pb, pos, SEEK_SET);
262 static void put_xiph_size(AVIOContext *pb, int size)
264 ffio_fill(pb, 255, size / 255);
265 avio_w8(pb, size % 255);
269 * Initialize a mkv_seekhead element to be ready to index level 1 Matroska
270 * elements. If a maximum number of elements is specified, enough space
271 * will be reserved at the current file location to write a seek head of
274 * @param segment_offset The absolute offset to the position in the file
275 * where the segment begins.
276 * @param numelements The maximum number of elements that will be indexed
277 * by this seek head, 0 if unlimited.
279 static mkv_seekhead * mkv_start_seekhead(AVIOContext *pb, int64_t segment_offset, int numelements)
281 mkv_seekhead *new_seekhead = av_mallocz(sizeof(mkv_seekhead));
282 if (new_seekhead == NULL)
285 new_seekhead->segment_offset = segment_offset;
287 if (numelements > 0) {
288 new_seekhead->filepos = avio_tell(pb);
289 // 21 bytes max for a seek entry, 10 bytes max for the SeekHead ID
290 // and size, and 3 bytes to guarantee that an EBML void element
291 // will fit afterwards
292 new_seekhead->reserved_size = numelements * MAX_SEEKENTRY_SIZE + 13;
293 new_seekhead->max_entries = numelements;
294 put_ebml_void(pb, new_seekhead->reserved_size);
299 static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
301 mkv_seekhead_entry *entries = seekhead->entries;
303 // don't store more elements than we reserved space for
304 if (seekhead->max_entries > 0 && seekhead->max_entries <= seekhead->num_entries)
307 entries = av_realloc(entries, (seekhead->num_entries + 1) * sizeof(mkv_seekhead_entry));
309 return AVERROR(ENOMEM);
311 entries[seekhead->num_entries ].elementid = elementid;
312 entries[seekhead->num_entries++].segmentpos = filepos - seekhead->segment_offset;
314 seekhead->entries = entries;
319 * Write the seek head to the file and free it. If a maximum number of
320 * elements was specified to mkv_start_seekhead(), the seek head will
321 * be written at the location reserved for it. Otherwise, it is written
322 * at the current location in the file.
324 * @return The file offset where the seekhead was written,
325 * -1 if an error occurred.
327 static int64_t mkv_write_seekhead(AVIOContext *pb, mkv_seekhead *seekhead)
329 ebml_master metaseek, seekentry;
333 currentpos = avio_tell(pb);
335 if (seekhead->reserved_size > 0) {
336 if (avio_seek(pb, seekhead->filepos, SEEK_SET) < 0) {
342 metaseek = start_ebml_master(pb, MATROSKA_ID_SEEKHEAD, seekhead->reserved_size);
343 for (i = 0; i < seekhead->num_entries; i++) {
344 mkv_seekhead_entry *entry = &seekhead->entries[i];
346 seekentry = start_ebml_master(pb, MATROSKA_ID_SEEKENTRY, MAX_SEEKENTRY_SIZE);
348 put_ebml_id(pb, MATROSKA_ID_SEEKID);
349 put_ebml_num(pb, ebml_id_size(entry->elementid), 0);
350 put_ebml_id(pb, entry->elementid);
352 put_ebml_uint(pb, MATROSKA_ID_SEEKPOSITION, entry->segmentpos);
353 end_ebml_master(pb, seekentry);
355 end_ebml_master(pb, metaseek);
357 if (seekhead->reserved_size > 0) {
358 uint64_t remaining = seekhead->filepos + seekhead->reserved_size - avio_tell(pb);
359 put_ebml_void(pb, remaining);
360 avio_seek(pb, currentpos, SEEK_SET);
362 currentpos = seekhead->filepos;
365 av_free(seekhead->entries);
371 static mkv_cues * mkv_start_cues(int64_t segment_offset)
373 mkv_cues *cues = av_mallocz(sizeof(mkv_cues));
377 cues->segment_offset = segment_offset;
381 static int mkv_add_cuepoint(mkv_cues *cues, int stream, int64_t ts, int64_t cluster_pos, int64_t relative_pos)
383 mkv_cuepoint *entries = cues->entries;
388 entries = av_realloc(entries, (cues->num_entries + 1) * sizeof(mkv_cuepoint));
390 return AVERROR(ENOMEM);
392 entries[cues->num_entries ].pts = ts;
393 entries[cues->num_entries ].tracknum = stream + 1;
394 entries[cues->num_entries ].cluster_pos = cluster_pos - cues->segment_offset;
395 entries[cues->num_entries++].relative_pos = relative_pos;
397 cues->entries = entries;
401 static int64_t mkv_write_cues(AVIOContext *pb, mkv_cues *cues, mkv_track *tracks, int num_tracks)
403 ebml_master cues_element;
407 currentpos = avio_tell(pb);
408 cues_element = start_ebml_master(pb, MATROSKA_ID_CUES, 0);
410 for (i = 0; i < cues->num_entries; i++) {
411 ebml_master cuepoint, track_positions;
412 mkv_cuepoint *entry = &cues->entries[i];
413 uint64_t pts = entry->pts;
415 cuepoint = start_ebml_master(pb, MATROSKA_ID_POINTENTRY, MAX_CUEPOINT_SIZE(num_tracks));
416 put_ebml_uint(pb, MATROSKA_ID_CUETIME, pts);
418 // put all the entries from different tracks that have the exact same
419 // timestamp into the same CuePoint
420 for (j = 0; j < num_tracks; j++)
421 tracks[j].has_cue = 0;
422 for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
423 int tracknum = entry[j].tracknum - 1;
424 av_assert0(tracknum>=0 && tracknum<num_tracks);
425 if (tracks[tracknum].has_cue)
427 tracks[tracknum].has_cue = 1;
428 track_positions = start_ebml_master(pb, MATROSKA_ID_CUETRACKPOSITION, MAX_CUETRACKPOS_SIZE);
429 put_ebml_uint(pb, MATROSKA_ID_CUETRACK , entry[j].tracknum );
430 put_ebml_uint(pb, MATROSKA_ID_CUECLUSTERPOSITION , entry[j].cluster_pos);
431 put_ebml_uint(pb, MATROSKA_ID_CUERELATIVEPOSITION, entry[j].relative_pos);
432 end_ebml_master(pb, track_positions);
435 end_ebml_master(pb, cuepoint);
437 end_ebml_master(pb, cues_element);
442 static int put_xiph_codecpriv(AVFormatContext *s, AVIOContext *pb, AVCodecContext *codec)
444 uint8_t *header_start[3];
446 int first_header_size;
449 if (codec->codec_id == AV_CODEC_ID_VORBIS)
450 first_header_size = 30;
452 first_header_size = 42;
454 if (avpriv_split_xiph_headers(codec->extradata, codec->extradata_size,
455 first_header_size, header_start, header_len) < 0) {
456 av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
460 avio_w8(pb, 2); // number packets - 1
461 for (j = 0; j < 2; j++) {
462 put_xiph_size(pb, header_len[j]);
464 for (j = 0; j < 3; j++)
465 avio_write(pb, header_start[j], header_len[j]);
470 static int put_wv_codecpriv(AVIOContext *pb, AVCodecContext *codec)
472 if (codec->extradata && codec->extradata_size == 2)
473 avio_write(pb, codec->extradata, 2);
475 avio_wl16(pb, 0x403); // fallback to the version mentioned in matroska specs
479 static void get_aac_sample_rates(AVFormatContext *s, AVCodecContext *codec, int *sample_rate, int *output_sample_rate)
481 MPEG4AudioConfig mp4ac;
483 if (avpriv_mpeg4audio_get_config(&mp4ac, codec->extradata,
484 codec->extradata_size * 8, 1) < 0) {
485 av_log(s, AV_LOG_WARNING, "Error parsing AAC extradata, unable to determine samplerate.\n");
489 *sample_rate = mp4ac.sample_rate;
490 *output_sample_rate = mp4ac.ext_sample_rate;
493 static int mkv_write_codecprivate(AVFormatContext *s, AVIOContext *pb, AVCodecContext *codec, int native_id, int qt_id)
497 int ret, codecpriv_size;
499 ret = avio_open_dyn_buf(&dyn_cp);
504 if (codec->codec_id == AV_CODEC_ID_VORBIS || codec->codec_id == AV_CODEC_ID_THEORA)
505 ret = put_xiph_codecpriv(s, dyn_cp, codec);
506 else if (codec->codec_id == AV_CODEC_ID_FLAC)
507 ret = ff_flac_write_header(dyn_cp, codec, 1);
508 else if (codec->codec_id == AV_CODEC_ID_WAVPACK)
509 ret = put_wv_codecpriv(dyn_cp, codec);
510 else if (codec->codec_id == AV_CODEC_ID_H264)
511 ret = ff_isom_write_avcc(dyn_cp, codec->extradata, codec->extradata_size);
512 else if (codec->codec_id == AV_CODEC_ID_ALAC) {
513 if (codec->extradata_size < 36) {
514 av_log(s, AV_LOG_ERROR,
515 "Invalid extradata found, ALAC expects a 36-byte "
517 ret = AVERROR_INVALIDDATA;
519 avio_write(dyn_cp, codec->extradata + 12,
520 codec->extradata_size - 12);
522 else if (codec->extradata_size && codec->codec_id != AV_CODEC_ID_TTA)
523 avio_write(dyn_cp, codec->extradata, codec->extradata_size);
524 } else if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
526 if (!codec->codec_tag)
527 codec->codec_tag = ff_codec_get_tag(ff_codec_movvideo_tags, codec->codec_id);
528 if (codec->extradata_size)
529 avio_write(dyn_cp, codec->extradata, codec->extradata_size);
531 if (!codec->codec_tag)
532 codec->codec_tag = ff_codec_get_tag(ff_codec_bmp_tags, codec->codec_id);
533 if (!codec->codec_tag) {
534 av_log(s, AV_LOG_ERROR, "No bmp codec tag found for codec %s\n",
535 avcodec_get_name(codec->codec_id));
536 ret = AVERROR(EINVAL);
539 ff_put_bmp_header(dyn_cp, codec, ff_codec_bmp_tags, 0);
542 } else if (codec->codec_type == AVMEDIA_TYPE_AUDIO) {
544 tag = ff_codec_get_tag(ff_codec_wav_tags, codec->codec_id);
546 av_log(s, AV_LOG_ERROR, "No wav codec tag found for codec %s\n",
547 avcodec_get_name(codec->codec_id));
548 ret = AVERROR(EINVAL);
550 if (!codec->codec_tag)
551 codec->codec_tag = tag;
553 ff_put_wav_header(dyn_cp, codec);
556 codecpriv_size = avio_close_dyn_buf(dyn_cp, &codecpriv);
558 put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codecpriv, codecpriv_size);
563 static int mkv_write_tracks(AVFormatContext *s)
565 MatroskaMuxContext *mkv = s->priv_data;
566 AVIOContext *pb = s->pb;
568 int i, j, ret, default_stream_exists = 0;
570 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TRACKS, avio_tell(pb));
571 if (ret < 0) return ret;
573 tracks = start_ebml_master(pb, MATROSKA_ID_TRACKS, 0);
574 for (i = 0; i < s->nb_streams; i++) {
575 AVStream *st = s->streams[i];
576 default_stream_exists |= st->disposition & AV_DISPOSITION_DEFAULT;
578 for (i = 0; i < s->nb_streams; i++) {
579 AVStream *st = s->streams[i];
580 AVCodecContext *codec = st->codec;
581 ebml_master subinfo, track;
584 int bit_depth = av_get_bits_per_sample(codec->codec_id);
585 int sample_rate = codec->sample_rate;
586 int output_sample_rate = 0;
587 AVDictionaryEntry *tag;
589 if (codec->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
590 mkv->have_attachments = 1;
595 bit_depth = av_get_bytes_per_sample(codec->sample_fmt) << 3;
597 bit_depth = codec->bits_per_coded_sample;
599 if (codec->codec_id == AV_CODEC_ID_AAC)
600 get_aac_sample_rates(s, codec, &sample_rate, &output_sample_rate);
602 track = start_ebml_master(pb, MATROSKA_ID_TRACKENTRY, 0);
603 put_ebml_uint (pb, MATROSKA_ID_TRACKNUMBER , i + 1);
604 put_ebml_uint (pb, MATROSKA_ID_TRACKUID , i + 1);
605 put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0); // no lacing (yet)
607 if ((tag = av_dict_get(st->metadata, "title", NULL, 0)))
608 put_ebml_string(pb, MATROSKA_ID_TRACKNAME, tag->value);
609 tag = av_dict_get(st->metadata, "language", NULL, 0);
610 if (mkv->mode != MODE_WEBM || codec->codec_id != AV_CODEC_ID_WEBVTT) {
611 put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag ? tag->value:"und");
612 } else if (tag && tag->value) {
613 put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag->value);
616 if (default_stream_exists) {
617 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGDEFAULT, !!(st->disposition & AV_DISPOSITION_DEFAULT));
619 if (st->disposition & AV_DISPOSITION_FORCED)
620 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGFORCED, 1);
622 if (mkv->mode == MODE_WEBM && codec->codec_id == AV_CODEC_ID_WEBVTT) {
623 const char *codec_id;
624 if (st->disposition & AV_DISPOSITION_CAPTIONS) {
625 codec_id = "D_WEBVTT/CAPTIONS";
626 native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
627 } else if (st->disposition & AV_DISPOSITION_DESCRIPTIONS) {
628 codec_id = "D_WEBVTT/DESCRIPTIONS";
629 native_id = MATROSKA_TRACK_TYPE_METADATA;
630 } else if (st->disposition & AV_DISPOSITION_METADATA) {
631 codec_id = "D_WEBVTT/METADATA";
632 native_id = MATROSKA_TRACK_TYPE_METADATA;
634 codec_id = "D_WEBVTT/SUBTITLES";
635 native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
637 put_ebml_string(pb, MATROSKA_ID_CODECID, codec_id);
639 // look for a codec ID string specific to mkv to use,
640 // if none are found, use AVI codes
641 for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
642 if (ff_mkv_codec_tags[j].id == codec->codec_id) {
643 put_ebml_string(pb, MATROSKA_ID_CODECID, ff_mkv_codec_tags[j].str);
650 if (codec->codec_id == AV_CODEC_ID_OPUS) {
651 put_ebml_uint(pb, MATROSKA_ID_SEEKPREROLL, OPUS_SEEK_PREROLL);
654 if (mkv->mode == MODE_WEBM && !(codec->codec_id == AV_CODEC_ID_VP8 ||
655 codec->codec_id == AV_CODEC_ID_VP9 ||
656 ((codec->codec_id == AV_CODEC_ID_OPUS)&&(codec->strict_std_compliance <= FF_COMPLIANCE_EXPERIMENTAL)) ||
657 codec->codec_id == AV_CODEC_ID_VORBIS ||
658 codec->codec_id == AV_CODEC_ID_WEBVTT)) {
659 av_log(s, AV_LOG_ERROR,
660 "Only VP8,VP9 video and Vorbis,Opus(experimental, use -strict -2) audio and WebVTT subtitles are supported for WebM.\n");
661 return AVERROR(EINVAL);
664 switch (codec->codec_type) {
665 case AVMEDIA_TYPE_VIDEO:
666 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_VIDEO);
667 if(st->avg_frame_rate.num && st->avg_frame_rate.den && 1.0/av_q2d(st->avg_frame_rate) > av_q2d(codec->time_base))
668 put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, 1E9/av_q2d(st->avg_frame_rate));
670 put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, av_q2d(codec->time_base)*1E9);
673 ff_codec_get_tag(ff_codec_movvideo_tags, codec->codec_id) &&
674 (!ff_codec_get_tag(ff_codec_bmp_tags, codec->codec_id)
675 || codec->codec_id == AV_CODEC_ID_SVQ1
676 || codec->codec_id == AV_CODEC_ID_SVQ3
677 || codec->codec_id == AV_CODEC_ID_CINEPAK))
681 put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");
682 else if (!native_id) {
683 // if there is no mkv-specific codec ID, use VFW mode
684 put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");
685 mkv->tracks[i].write_dts = 1;
688 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
689 // XXX: interlace flag?
690 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , codec->width);
691 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, codec->height);
693 if ((tag = av_dict_get(st->metadata, "stereo_mode", NULL, 0)) ||
694 (tag = av_dict_get( s->metadata, "stereo_mode", NULL, 0))) {
695 // save stereo mode flag
696 uint64_t st_mode = MATROSKA_VIDEO_STEREO_MODE_COUNT;
698 for (j=0; j<MATROSKA_VIDEO_STEREO_MODE_COUNT; j++)
699 if (!strcmp(tag->value, ff_matroska_video_stereo_mode[j])){
704 if ((mkv->mode == MODE_WEBM && st_mode > 3 && st_mode != 11)
705 || st_mode >= MATROSKA_VIDEO_STEREO_MODE_COUNT) {
706 av_log(s, AV_LOG_ERROR,
707 "The specified stereo mode is not valid.\n");
708 return AVERROR(EINVAL);
710 put_ebml_uint(pb, MATROSKA_ID_VIDEOSTEREOMODE, st_mode);
713 if ((tag = av_dict_get(st->metadata, "alpha_mode", NULL, 0)) ||
714 (tag = av_dict_get( s->metadata, "alpha_mode", NULL, 0)) ||
715 (codec->pix_fmt == AV_PIX_FMT_YUVA420P)) {
716 put_ebml_uint(pb, MATROSKA_ID_VIDEOALPHAMODE, 1);
719 if (st->sample_aspect_ratio.num) {
720 int64_t d_width = av_rescale(codec->width, st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
721 if (d_width > INT_MAX) {
722 av_log(s, AV_LOG_ERROR, "Overflow in display width\n");
723 return AVERROR(EINVAL);
725 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , d_width);
726 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, codec->height);
729 if (codec->codec_id == AV_CODEC_ID_RAWVIDEO) {
730 uint32_t color_space = av_le2ne32(codec->codec_tag);
731 put_ebml_binary(pb, MATROSKA_ID_VIDEOCOLORSPACE, &color_space, sizeof(color_space));
733 end_ebml_master(pb, subinfo);
736 case AVMEDIA_TYPE_AUDIO:
737 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_AUDIO);
740 // no mkv-specific ID, use ACM mode
741 put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");
743 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);
744 put_ebml_uint (pb, MATROSKA_ID_AUDIOCHANNELS , codec->channels);
745 put_ebml_float (pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, sample_rate);
746 if (output_sample_rate)
747 put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
749 put_ebml_uint(pb, MATROSKA_ID_AUDIOBITDEPTH, bit_depth);
750 end_ebml_master(pb, subinfo);
753 case AVMEDIA_TYPE_SUBTITLE:
755 av_log(s, AV_LOG_ERROR, "Subtitle codec %d is not supported.\n", codec->codec_id);
756 return AVERROR(ENOSYS);
759 if (mkv->mode != MODE_WEBM || codec->codec_id != AV_CODEC_ID_WEBVTT)
760 native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
762 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, native_id);
765 av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.\n");
766 return AVERROR(EINVAL);
769 if (mkv->mode != MODE_WEBM || codec->codec_id != AV_CODEC_ID_WEBVTT) {
770 ret = mkv_write_codecprivate(s, pb, codec, native_id, qt_id);
771 if (ret < 0) return ret;
774 end_ebml_master(pb, track);
776 // ms precision is the de-facto standard timescale for mkv files
777 avpriv_set_pts_info(st, 64, 1, 1000);
779 end_ebml_master(pb, tracks);
783 static int mkv_write_chapters(AVFormatContext *s)
785 MatroskaMuxContext *mkv = s->priv_data;
786 AVIOContext *pb = s->pb;
787 ebml_master chapters, editionentry;
788 AVRational scale = {1, 1E9};
794 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CHAPTERS, avio_tell(pb));
795 if (ret < 0) return ret;
797 chapters = start_ebml_master(pb, MATROSKA_ID_CHAPTERS , 0);
798 editionentry = start_ebml_master(pb, MATROSKA_ID_EDITIONENTRY, 0);
799 put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGDEFAULT, 1);
800 put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGHIDDEN , 0);
801 for (i = 0; i < s->nb_chapters; i++) {
802 ebml_master chapteratom, chapterdisplay;
803 AVChapter *c = s->chapters[i];
804 AVDictionaryEntry *t = NULL;
806 chapteratom = start_ebml_master(pb, MATROSKA_ID_CHAPTERATOM, 0);
807 put_ebml_uint(pb, MATROSKA_ID_CHAPTERUID, c->id + mkv->chapter_id_offset);
808 put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMESTART,
809 av_rescale_q(c->start, c->time_base, scale));
810 put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMEEND,
811 av_rescale_q(c->end, c->time_base, scale));
812 put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGHIDDEN , 0);
813 put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGENABLED, 1);
814 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
815 chapterdisplay = start_ebml_master(pb, MATROSKA_ID_CHAPTERDISPLAY, 0);
816 put_ebml_string(pb, MATROSKA_ID_CHAPSTRING, t->value);
817 put_ebml_string(pb, MATROSKA_ID_CHAPLANG , "und");
818 end_ebml_master(pb, chapterdisplay);
820 end_ebml_master(pb, chapteratom);
822 end_ebml_master(pb, editionentry);
823 end_ebml_master(pb, chapters);
827 static void mkv_write_simpletag(AVIOContext *pb, AVDictionaryEntry *t)
829 uint8_t *key = av_strdup(t->key);
831 const uint8_t *lang = NULL;
834 if ((p = strrchr(p, '-')) &&
835 (lang = av_convert_lang_to(p + 1, AV_LANG_ISO639_2_BIBL)))
842 else if (*p >= 'a' && *p <= 'z')
847 tag = start_ebml_master(pb, MATROSKA_ID_SIMPLETAG, 0);
848 put_ebml_string(pb, MATROSKA_ID_TAGNAME, key);
850 put_ebml_string(pb, MATROSKA_ID_TAGLANG, lang);
851 put_ebml_string(pb, MATROSKA_ID_TAGSTRING, t->value);
852 end_ebml_master(pb, tag);
857 static int mkv_write_tag(AVFormatContext *s, AVDictionary *m, unsigned int elementid,
858 unsigned int uid, ebml_master *tags)
860 MatroskaMuxContext *mkv = s->priv_data;
861 ebml_master tag, targets;
862 AVDictionaryEntry *t = NULL;
866 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TAGS, avio_tell(s->pb));
867 if (ret < 0) return ret;
869 *tags = start_ebml_master(s->pb, MATROSKA_ID_TAGS, 0);
872 tag = start_ebml_master(s->pb, MATROSKA_ID_TAG, 0);
873 targets = start_ebml_master(s->pb, MATROSKA_ID_TAGTARGETS, 0);
875 put_ebml_uint(s->pb, elementid, uid);
876 end_ebml_master(s->pb, targets);
878 while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX)))
879 if (av_strcasecmp(t->key, "title") && av_strcasecmp(t->key, "stereo_mode"))
880 mkv_write_simpletag(s->pb, t);
882 end_ebml_master(s->pb, tag);
886 static int mkv_check_tag(AVDictionary *m)
888 AVDictionaryEntry *t = NULL;
890 while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX)))
891 if (av_strcasecmp(t->key, "title") && av_strcasecmp(t->key, "stereo_mode"))
897 static int mkv_write_tags(AVFormatContext *s)
899 MatroskaMuxContext *mkv = s->priv_data;
900 ebml_master tags = {0};
903 ff_metadata_conv_ctx(s, ff_mkv_metadata_conv, NULL);
905 if (mkv_check_tag(s->metadata)) {
906 ret = mkv_write_tag(s, s->metadata, 0, 0, &tags);
907 if (ret < 0) return ret;
910 for (i = 0; i < s->nb_streams; i++) {
911 AVStream *st = s->streams[i];
913 if (!mkv_check_tag(st->metadata))
916 ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &tags);
917 if (ret < 0) return ret;
920 for (i = 0; i < s->nb_chapters; i++) {
921 AVChapter *ch = s->chapters[i];
923 if (!mkv_check_tag(ch->metadata))
926 ret = mkv_write_tag(s, ch->metadata, MATROSKA_ID_TAGTARGETS_CHAPTERUID, ch->id + mkv->chapter_id_offset, &tags);
927 if (ret < 0) return ret;
931 end_ebml_master(s->pb, tags);
935 static int mkv_write_attachments(AVFormatContext *s)
937 MatroskaMuxContext *mkv = s->priv_data;
938 AVIOContext *pb = s->pb;
939 ebml_master attachments;
943 if (!mkv->have_attachments)
946 av_lfg_init(&c, av_get_random_seed());
948 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_ATTACHMENTS, avio_tell(pb));
949 if (ret < 0) return ret;
951 attachments = start_ebml_master(pb, MATROSKA_ID_ATTACHMENTS, 0);
953 for (i = 0; i < s->nb_streams; i++) {
954 AVStream *st = s->streams[i];
955 ebml_master attached_file;
956 AVDictionaryEntry *t;
957 const char *mimetype = NULL;
960 if (st->codec->codec_type != AVMEDIA_TYPE_ATTACHMENT)
963 attached_file = start_ebml_master(pb, MATROSKA_ID_ATTACHEDFILE, 0);
965 if (t = av_dict_get(st->metadata, "title", NULL, 0))
966 put_ebml_string(pb, MATROSKA_ID_FILEDESC, t->value);
967 if (!(t = av_dict_get(st->metadata, "filename", NULL, 0))) {
968 av_log(s, AV_LOG_ERROR, "Attachment stream %d has no filename tag.\n", i);
969 return AVERROR(EINVAL);
971 put_ebml_string(pb, MATROSKA_ID_FILENAME, t->value);
972 if (t = av_dict_get(st->metadata, "mimetype", NULL, 0))
974 else if (st->codec->codec_id != AV_CODEC_ID_NONE ) {
976 for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
977 if (ff_mkv_mime_tags[i].id == st->codec->codec_id) {
978 mimetype = ff_mkv_mime_tags[i].str;
983 av_log(s, AV_LOG_ERROR, "Attachment stream %d has no mimetype tag and "
984 "it cannot be deduced from the codec id.\n", i);
985 return AVERROR(EINVAL);
988 if (st->codec->flags & CODEC_FLAG_BITEXACT) {
989 struct AVSHA *sha = av_sha_alloc();
992 return AVERROR(ENOMEM);
993 av_sha_init(sha, 160);
994 av_sha_update(sha, st->codec->extradata, st->codec->extradata_size);
995 av_sha_final(sha, digest);
997 fileuid = AV_RL64(digest);
999 fileuid = av_lfg_get(&c);
1001 av_log(s, AV_LOG_VERBOSE, "Using %.16"PRIx64" for attachment %d\n",
1004 put_ebml_string(pb, MATROSKA_ID_FILEMIMETYPE, mimetype);
1005 put_ebml_binary(pb, MATROSKA_ID_FILEDATA, st->codec->extradata, st->codec->extradata_size);
1006 put_ebml_uint(pb, MATROSKA_ID_FILEUID, fileuid);
1007 end_ebml_master(pb, attached_file);
1009 end_ebml_master(pb, attachments);
1014 static int mkv_write_header(AVFormatContext *s)
1016 MatroskaMuxContext *mkv = s->priv_data;
1017 AVIOContext *pb = s->pb;
1018 ebml_master ebml_header, segment_info;
1019 AVDictionaryEntry *tag;
1022 if (!strcmp(s->oformat->name, "webm")) mkv->mode = MODE_WEBM;
1023 else mkv->mode = MODE_MATROSKAv2;
1025 if (s->avoid_negative_ts < 0)
1026 s->avoid_negative_ts = 1;
1028 for (i = 0; i < s->nb_streams; i++)
1029 if (s->streams[i]->codec->codec_id == AV_CODEC_ID_ATRAC3 ||
1030 s->streams[i]->codec->codec_id == AV_CODEC_ID_COOK ||
1031 s->streams[i]->codec->codec_id == AV_CODEC_ID_RA_288 ||
1032 s->streams[i]->codec->codec_id == AV_CODEC_ID_SIPR ||
1033 s->streams[i]->codec->codec_id == AV_CODEC_ID_RV10 ||
1034 s->streams[i]->codec->codec_id == AV_CODEC_ID_RV20) {
1035 av_log(s, AV_LOG_ERROR,
1036 "The Matroska muxer does not yet support muxing %s\n",
1037 avcodec_get_name(s->streams[i]->codec->codec_id));
1038 return AVERROR_PATCHWELCOME;
1041 mkv->tracks = av_mallocz(s->nb_streams * sizeof(*mkv->tracks));
1043 return AVERROR(ENOMEM);
1045 ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
1046 put_ebml_uint (pb, EBML_ID_EBMLVERSION , 1);
1047 put_ebml_uint (pb, EBML_ID_EBMLREADVERSION , 1);
1048 put_ebml_uint (pb, EBML_ID_EBMLMAXIDLENGTH , 4);
1049 put_ebml_uint (pb, EBML_ID_EBMLMAXSIZELENGTH , 8);
1050 put_ebml_string (pb, EBML_ID_DOCTYPE , s->oformat->name);
1051 put_ebml_uint (pb, EBML_ID_DOCTYPEVERSION , 2);
1052 put_ebml_uint (pb, EBML_ID_DOCTYPEREADVERSION , 2);
1053 end_ebml_master(pb, ebml_header);
1055 mkv->segment = start_ebml_master(pb, MATROSKA_ID_SEGMENT, 0);
1056 mkv->segment_offset = avio_tell(pb);
1058 // we write 2 seek heads - one at the end of the file to point to each
1059 // cluster, and one at the beginning to point to all other level one
1060 // elements (including the seek head at the end of the file), which
1061 // isn't more than 10 elements if we only write one of each other
1062 // currently defined level 1 element
1063 mkv->main_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 10);
1064 if (!mkv->main_seekhead)
1065 return AVERROR(ENOMEM);
1067 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_INFO, avio_tell(pb));
1068 if (ret < 0) return ret;
1070 segment_info = start_ebml_master(pb, MATROSKA_ID_INFO, 0);
1071 put_ebml_uint(pb, MATROSKA_ID_TIMECODESCALE, 1000000);
1072 if ((tag = av_dict_get(s->metadata, "title", NULL, 0)))
1073 put_ebml_string(pb, MATROSKA_ID_TITLE, tag->value);
1074 if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
1075 uint32_t segment_uid[4];
1078 av_lfg_init(&lfg, av_get_random_seed());
1080 for (i = 0; i < 4; i++)
1081 segment_uid[i] = av_lfg_get(&lfg);
1083 put_ebml_string(pb, MATROSKA_ID_MUXINGAPP , LIBAVFORMAT_IDENT);
1084 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, LIBAVFORMAT_IDENT);
1085 put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
1088 if (tag = av_dict_get(s->metadata, "creation_time", NULL, 0)) {
1089 // Adjust time so it's relative to 2001-01-01 and convert to nanoseconds.
1090 int64_t date_utc = (ff_iso8601_to_unix_time(tag->value) - 978307200) * 1000000000;
1091 uint8_t date_utc_buf[8];
1092 AV_WB64(date_utc_buf, date_utc);
1093 put_ebml_binary(pb, MATROSKA_ID_DATEUTC, date_utc_buf, 8);
1096 // reserve space for the duration
1098 mkv->duration_offset = avio_tell(pb);
1099 put_ebml_void(pb, 11); // assumes double-precision float to be written
1100 end_ebml_master(pb, segment_info);
1102 ret = mkv_write_tracks(s);
1103 if (ret < 0) return ret;
1105 for (i = 0; i < s->nb_chapters; i++)
1106 mkv->chapter_id_offset = FFMAX(mkv->chapter_id_offset, 1LL - s->chapters[i]->id);
1108 if (mkv->mode != MODE_WEBM) {
1109 ret = mkv_write_chapters(s);
1110 if (ret < 0) return ret;
1112 ret = mkv_write_tags(s);
1113 if (ret < 0) return ret;
1115 ret = mkv_write_attachments(s);
1116 if (ret < 0) return ret;
1119 if (!s->pb->seekable)
1120 mkv_write_seekhead(pb, mkv->main_seekhead);
1122 mkv->cues = mkv_start_cues(mkv->segment_offset);
1123 if (mkv->cues == NULL)
1124 return AVERROR(ENOMEM);
1126 if (pb->seekable && mkv->reserve_cues_space) {
1127 mkv->cues_pos = avio_tell(pb);
1128 put_ebml_void(pb, mkv->reserve_cues_space);
1131 av_init_packet(&mkv->cur_audio_pkt);
1132 mkv->cur_audio_pkt.size = 0;
1133 mkv->cluster_pos = -1;
1137 // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1138 // after 4k and on a keyframe
1140 if (mkv->cluster_time_limit < 0)
1141 mkv->cluster_time_limit = 5000;
1142 if (mkv->cluster_size_limit < 0)
1143 mkv->cluster_size_limit = 5 * 1024 * 1024;
1145 if (mkv->cluster_time_limit < 0)
1146 mkv->cluster_time_limit = 1000;
1147 if (mkv->cluster_size_limit < 0)
1148 mkv->cluster_size_limit = 32 * 1024;
1154 static int mkv_blockgroup_size(int pkt_size)
1156 int size = pkt_size + 4;
1157 size += ebml_num_size(size);
1158 size += 2; // EBML ID for block and block duration
1159 size += 8; // max size of block duration
1160 size += ebml_num_size(size);
1161 size += 1; // blockgroup EBML ID
1165 static int ass_get_duration(const uint8_t *p)
1167 int sh, sm, ss, sc, eh, em, es, ec;
1168 uint64_t start, end;
1170 if (sscanf(p, "%*[^,],%d:%d:%d%*c%d,%d:%d:%d%*c%d",
1171 &sh, &sm, &ss, &sc, &eh, &em, &es, &ec) != 8)
1173 start = 3600000LL*sh + 60000LL*sm + 1000LL*ss + 10LL*sc;
1174 end = 3600000LL*eh + 60000LL*em + 1000LL*es + 10LL*ec;
1179 static int mkv_write_ass_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
1181 MatroskaMuxContext *mkv = s->priv_data;
1182 int i, layer = 0, max_duration = 0, size, line_size, data_size = pkt->size;
1183 uint8_t *start, *end, *data = pkt->data;
1184 ebml_master blockgroup;
1188 int duration = ass_get_duration(data);
1189 max_duration = FFMAX(duration, max_duration);
1190 end = memchr(data, '\n', data_size);
1191 size = line_size = end ? end-data+1 : data_size;
1192 size -= end ? (end[-1]=='\r')+1 : 0;
1194 for (i=0; i<3; i++, start++)
1195 if (!(start = memchr(start, ',', size-(start-data))))
1196 return max_duration;
1197 size -= start - data;
1198 sscanf(data, "Dialogue: %d,", &layer);
1199 i = snprintf(buffer, sizeof(buffer), "%"PRId64",%d,",
1200 s->streams[pkt->stream_index]->nb_frames, layer);
1201 size = FFMIN(i+size, sizeof(buffer));
1202 memcpy(buffer+i, start, size-i);
1204 av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
1205 "pts %" PRId64 ", duration %d\n",
1206 avio_tell(pb), size, pkt->pts, duration);
1207 blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(size));
1208 put_ebml_id(pb, MATROSKA_ID_BLOCK);
1209 put_ebml_num(pb, size+4, 0);
1210 avio_w8(pb, 0x80 | (pkt->stream_index + 1)); // this assumes stream_index is less than 126
1211 avio_wb16(pb, pkt->pts - mkv->cluster_pts);
1213 avio_write(pb, buffer, size);
1214 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
1215 end_ebml_master(pb, blockgroup);
1218 data_size -= line_size;
1221 return max_duration;
1225 static int mkv_strip_wavpack(const uint8_t *src, uint8_t **pdst, int *size)
1232 dst = av_malloc(srclen);
1234 return AVERROR(ENOMEM);
1236 while (srclen >= WV_HEADER_SIZE) {
1239 ret = ff_wv_parse_header(&header, src);
1242 src += WV_HEADER_SIZE;
1243 srclen -= WV_HEADER_SIZE;
1245 if (srclen < header.blocksize) {
1246 ret = AVERROR_INVALIDDATA;
1250 if (header.initial) {
1251 AV_WL32(dst + offset, header.samples);
1254 AV_WL32(dst + offset, header.flags);
1255 AV_WL32(dst + offset + 4, header.crc);
1258 if (!(header.initial && header.final)) {
1259 AV_WL32(dst + offset, header.blocksize);
1263 memcpy(dst + offset, src, header.blocksize);
1264 src += header.blocksize;
1265 srclen -= header.blocksize;
1266 offset += header.blocksize;
1278 static void mkv_write_block(AVFormatContext *s, AVIOContext *pb,
1279 unsigned int blockid, AVPacket *pkt, int flags)
1281 MatroskaMuxContext *mkv = s->priv_data;
1282 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1283 uint8_t *data = NULL, *side_data = NULL;
1284 int offset = 0, size = pkt->size, side_data_size = 0;
1285 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1286 uint64_t additional_id = 0;
1287 ebml_master block_group, block_additions, block_more;
1289 av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
1290 "pts %" PRId64 ", dts %" PRId64 ", duration %d, flags %d\n",
1291 avio_tell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration, flags);
1292 if (codec->codec_id == AV_CODEC_ID_H264 && codec->extradata_size > 0 &&
1293 (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
1294 ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
1295 else if (codec->codec_id == AV_CODEC_ID_WAVPACK) {
1296 int ret = mkv_strip_wavpack(pkt->data, &data, &size);
1298 av_log(s, AV_LOG_ERROR, "Error stripping a WavPack packet.\n");
1304 if (codec->codec_id == AV_CODEC_ID_PRORES) {
1305 /* Matroska specification requires to remove the first QuickTime atom
1311 side_data = av_packet_get_side_data(pkt,
1312 AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,
1315 additional_id = AV_RB64(side_data);
1317 side_data_size -= 8;
1320 if (side_data_size && additional_id == 1) {
1321 block_group = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, 0);
1322 blockid = MATROSKA_ID_BLOCK;
1325 put_ebml_id(pb, blockid);
1326 put_ebml_num(pb, size+4, 0);
1327 avio_w8(pb, 0x80 | (pkt->stream_index + 1)); // this assumes stream_index is less than 126
1328 avio_wb16(pb, ts - mkv->cluster_pts);
1330 avio_write(pb, data + offset, size);
1331 if (data != pkt->data)
1334 if (side_data_size && additional_id == 1) {
1335 block_additions = start_ebml_master(pb, MATROSKA_ID_BLOCKADDITIONS, 0);
1336 block_more = start_ebml_master(pb, MATROSKA_ID_BLOCKMORE, 0);
1337 put_ebml_uint(pb, MATROSKA_ID_BLOCKADDID, 1);
1338 put_ebml_id(pb, MATROSKA_ID_BLOCKADDITIONAL);
1339 put_ebml_num(pb, side_data_size, 0);
1340 avio_write(pb, side_data, side_data_size);
1341 end_ebml_master(pb, block_more);
1342 end_ebml_master(pb, block_additions);
1343 end_ebml_master(pb, block_group);
1347 static int srt_get_duration(uint8_t **buf)
1349 int i, duration = 0;
1351 for (i=0; i<2 && !duration; i++) {
1352 int s_hour, s_min, s_sec, s_hsec, e_hour, e_min, e_sec, e_hsec;
1353 if (sscanf(*buf, "%d:%2d:%2d%*1[,.]%3d --> %d:%2d:%2d%*1[,.]%3d",
1354 &s_hour, &s_min, &s_sec, &s_hsec,
1355 &e_hour, &e_min, &e_sec, &e_hsec) == 8) {
1356 s_min += 60*s_hour; e_min += 60*e_hour;
1357 s_sec += 60*s_min; e_sec += 60*e_min;
1358 s_hsec += 1000*s_sec; e_hsec += 1000*e_sec;
1359 duration = e_hsec - s_hsec;
1361 *buf += strcspn(*buf, "\n") + 1;
1366 static int mkv_write_srt_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
1368 ebml_master blockgroup;
1369 AVPacket pkt2 = *pkt;
1370 int64_t duration = srt_get_duration(&pkt2.data);
1371 pkt2.size -= pkt2.data - pkt->data;
1373 blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
1374 mkv_blockgroup_size(pkt2.size));
1375 mkv_write_block(s, pb, MATROSKA_ID_BLOCK, &pkt2, 0);
1376 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
1377 end_ebml_master(pb, blockgroup);
1382 static int mkv_write_vtt_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
1384 MatroskaMuxContext *mkv = s->priv_data;
1385 ebml_master blockgroup;
1386 int id_size, settings_size, size;
1387 uint8_t *id, *settings;
1388 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1389 const int flags = 0;
1392 id = av_packet_get_side_data(pkt, AV_PKT_DATA_WEBVTT_IDENTIFIER,
1396 settings = av_packet_get_side_data(pkt, AV_PKT_DATA_WEBVTT_SETTINGS,
1399 size = id_size + 1 + settings_size + 1 + pkt->size;
1401 av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
1402 "pts %" PRId64 ", dts %" PRId64 ", duration %d, flags %d\n",
1403 avio_tell(pb), size, pkt->pts, pkt->dts, pkt->duration, flags);
1405 blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(size));
1407 put_ebml_id(pb, MATROSKA_ID_BLOCK);
1408 put_ebml_num(pb, size+4, 0);
1409 avio_w8(pb, 0x80 | (pkt->stream_index + 1)); // this assumes stream_index is less than 126
1410 avio_wb16(pb, ts - mkv->cluster_pts);
1412 avio_printf(pb, "%.*s\n%.*s\n%.*s", id_size, id, settings_size, settings, pkt->size, pkt->data);
1414 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, pkt->duration);
1415 end_ebml_master(pb, blockgroup);
1417 return pkt->duration;
1420 static void mkv_flush_dynbuf(AVFormatContext *s)
1422 MatroskaMuxContext *mkv = s->priv_data;
1429 bufsize = avio_close_dyn_buf(mkv->dyn_bc, &dyn_buf);
1430 avio_write(s->pb, dyn_buf, bufsize);
1435 static int mkv_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
1437 MatroskaMuxContext *mkv = s->priv_data;
1438 AVIOContext *pb = s->pb;
1439 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1440 int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1441 int duration = pkt->duration;
1443 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1444 int64_t relative_packet_pos;
1446 if (ts == AV_NOPTS_VALUE) {
1447 av_log(s, AV_LOG_ERROR, "Can't write packet with unknown timestamp\n");
1448 return AVERROR(EINVAL);
1451 if (!s->pb->seekable) {
1453 if ((ret = avio_open_dyn_buf(&mkv->dyn_bc)) < 0) {
1454 av_log(s, AV_LOG_ERROR, "Failed to open dynamic buffer\n");
1461 if (mkv->cluster_pos == -1) {
1462 mkv->cluster_pos = avio_tell(s->pb);
1463 mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER, 0);
1464 put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, FFMAX(0, ts));
1465 mkv->cluster_pts = FFMAX(0, ts);
1468 relative_packet_pos = avio_tell(s->pb) - mkv->cluster.pos;
1470 if (codec->codec_type != AVMEDIA_TYPE_SUBTITLE) {
1471 mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
1473 } else if (codec->codec_id == AV_CODEC_ID_SSA) {
1474 duration = mkv_write_ass_blocks(s, pb, pkt);
1476 } else if (codec->codec_id == AV_CODEC_ID_SRT) {
1477 duration = mkv_write_srt_blocks(s, pb, pkt);
1478 } else if (codec->codec_id == AV_CODEC_ID_WEBVTT) {
1479 duration = mkv_write_vtt_blocks(s, pb, pkt);
1481 ebml_master blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(pkt->size));
1482 /* For backward compatibility, prefer convergence_duration. */
1483 if (pkt->convergence_duration > 0) {
1484 duration = pkt->convergence_duration;
1486 mkv_write_block(s, pb, MATROSKA_ID_BLOCK, pkt, 0);
1487 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
1488 end_ebml_master(pb, blockgroup);
1491 if (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe) {
1492 ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, ts, mkv->cluster_pos, relative_packet_pos);
1493 if (ret < 0) return ret;
1496 mkv->duration = FFMAX(mkv->duration, ts + duration);
1500 static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
1502 MatroskaMuxContext *mkv = s->priv_data;
1503 int codec_type = s->streams[pkt->stream_index]->codec->codec_type;
1504 int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1506 int64_t cluster_time;
1510 if (mkv->tracks[pkt->stream_index].write_dts)
1511 cluster_time = pkt->dts - mkv->cluster_pts;
1513 cluster_time = pkt->pts - mkv->cluster_pts;
1515 // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1516 // after 4k and on a keyframe
1517 if (s->pb->seekable) {
1519 cluster_size = avio_tell(pb) - mkv->cluster_pos;
1522 cluster_size = avio_tell(pb);
1525 if (mkv->cluster_pos != -1 &&
1526 (cluster_size > mkv->cluster_size_limit ||
1527 cluster_time > mkv->cluster_time_limit ||
1528 (codec_type == AVMEDIA_TYPE_VIDEO && keyframe &&
1529 cluster_size > 4 * 1024))) {
1530 av_log(s, AV_LOG_DEBUG, "Starting new cluster at offset %" PRIu64
1531 " bytes, pts %" PRIu64 "dts %" PRIu64 "\n",
1532 avio_tell(pb), pkt->pts, pkt->dts);
1533 end_ebml_master(pb, mkv->cluster);
1534 mkv->cluster_pos = -1;
1536 mkv_flush_dynbuf(s);
1540 // check if we have an audio packet cached
1541 if (mkv->cur_audio_pkt.size > 0) {
1542 ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
1543 av_free_packet(&mkv->cur_audio_pkt);
1545 av_log(s, AV_LOG_ERROR, "Could not write cached audio packet ret:%d\n", ret);
1550 // buffer an audio packet to ensure the packet containing the video
1551 // keyframe's timecode is contained in the same cluster for WebM
1552 if (codec_type == AVMEDIA_TYPE_AUDIO) {
1553 mkv->cur_audio_pkt = *pkt;
1555 mkv->cur_audio_pkt.buf = av_buffer_ref(pkt->buf);
1556 ret = mkv->cur_audio_pkt.buf ? 0 : AVERROR(ENOMEM);
1558 ret = av_dup_packet(&mkv->cur_audio_pkt);
1560 ret = mkv_write_packet_internal(s, pkt);
1564 static int mkv_write_flush_packet(AVFormatContext *s, AVPacket *pkt)
1566 MatroskaMuxContext *mkv = s->priv_data;
1568 if (s->pb->seekable)
1573 if (mkv->cluster_pos != -1) {
1574 av_log(s, AV_LOG_DEBUG, "Flushing cluster at offset %" PRIu64
1575 " bytes\n", avio_tell(pb));
1576 end_ebml_master(pb, mkv->cluster);
1577 mkv->cluster_pos = -1;
1579 mkv_flush_dynbuf(s);
1584 return mkv_write_packet(s, pkt);
1587 static int mkv_write_trailer(AVFormatContext *s)
1589 MatroskaMuxContext *mkv = s->priv_data;
1590 AVIOContext *pb = s->pb;
1591 int64_t currentpos, cuespos;
1594 // check if we have an audio packet cached
1595 if (mkv->cur_audio_pkt.size > 0) {
1596 ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
1597 av_free_packet(&mkv->cur_audio_pkt);
1599 av_log(s, AV_LOG_ERROR, "Could not write cached audio packet ret:%d\n", ret);
1605 end_ebml_master(mkv->dyn_bc, mkv->cluster);
1606 mkv_flush_dynbuf(s);
1607 } else if (mkv->cluster_pos != -1) {
1608 end_ebml_master(pb, mkv->cluster);
1612 if (mkv->cues->num_entries) {
1613 if (mkv->reserve_cues_space) {
1616 currentpos = avio_tell(pb);
1617 avio_seek(pb, mkv->cues_pos, SEEK_SET);
1619 cuespos = mkv_write_cues(pb, mkv->cues, mkv->tracks, s->nb_streams);
1620 cues_end = avio_tell(pb);
1621 if (cues_end > cuespos + mkv->reserve_cues_space) {
1622 av_log(s, AV_LOG_ERROR, "Insufficient space reserved for cues: %d "
1623 "(needed: %"PRId64").\n", mkv->reserve_cues_space,
1624 cues_end - cuespos);
1625 return AVERROR(EINVAL);
1628 if (cues_end < cuespos + mkv->reserve_cues_space)
1629 put_ebml_void(pb, mkv->reserve_cues_space - (cues_end - cuespos));
1631 avio_seek(pb, currentpos, SEEK_SET);
1633 cuespos = mkv_write_cues(pb, mkv->cues, mkv->tracks, s->nb_streams);
1636 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CUES, cuespos);
1637 if (ret < 0) return ret;
1640 mkv_write_seekhead(pb, mkv->main_seekhead);
1642 // update the duration
1643 av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
1644 currentpos = avio_tell(pb);
1645 avio_seek(pb, mkv->duration_offset, SEEK_SET);
1646 put_ebml_float(pb, MATROSKA_ID_DURATION, mkv->duration);
1648 avio_seek(pb, currentpos, SEEK_SET);
1651 end_ebml_master(pb, mkv->segment);
1652 av_free(mkv->tracks);
1653 av_freep(&mkv->cues->entries);
1654 av_freep(&mkv->cues);
1659 static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
1662 for (i = 0; ff_mkv_codec_tags[i].id != AV_CODEC_ID_NONE; i++)
1663 if (ff_mkv_codec_tags[i].id == codec_id)
1666 if (std_compliance < FF_COMPLIANCE_NORMAL) { // mkv theoretically supports any
1667 enum AVMediaType type = avcodec_get_type(codec_id); // video/audio through VFW/ACM
1668 if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)
1675 static const AVCodecTag additional_audio_tags[] = {
1676 { AV_CODEC_ID_ALAC, 0XFFFFFFFF },
1677 { AV_CODEC_ID_EAC3, 0XFFFFFFFF },
1678 { AV_CODEC_ID_MLP, 0xFFFFFFFF },
1679 { AV_CODEC_ID_OPUS, 0xFFFFFFFF },
1680 { AV_CODEC_ID_PCM_S16BE, 0xFFFFFFFF },
1681 { AV_CODEC_ID_PCM_S24BE, 0xFFFFFFFF },
1682 { AV_CODEC_ID_PCM_S32BE, 0xFFFFFFFF },
1683 { AV_CODEC_ID_QDM2, 0xFFFFFFFF },
1684 { AV_CODEC_ID_RA_144, 0xFFFFFFFF },
1685 { AV_CODEC_ID_RA_288, 0xFFFFFFFF },
1686 { AV_CODEC_ID_COOK, 0xFFFFFFFF },
1687 { AV_CODEC_ID_TRUEHD, 0xFFFFFFFF },
1688 { AV_CODEC_ID_NONE, 0xFFFFFFFF }
1691 static const AVCodecTag additional_video_tags[] = {
1692 { AV_CODEC_ID_PRORES, 0xFFFFFFFF },
1693 { AV_CODEC_ID_RV10, 0xFFFFFFFF },
1694 { AV_CODEC_ID_RV20, 0xFFFFFFFF },
1695 { AV_CODEC_ID_RV30, 0xFFFFFFFF },
1696 { AV_CODEC_ID_RV40, 0xFFFFFFFF },
1697 { AV_CODEC_ID_VP9, 0xFFFFFFFF },
1698 { AV_CODEC_ID_NONE, 0xFFFFFFFF }
1701 #define OFFSET(x) offsetof(MatroskaMuxContext, x)
1702 #define FLAGS AV_OPT_FLAG_ENCODING_PARAM
1703 static const AVOption options[] = {
1704 { "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 },
1705 { "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 },
1706 { "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 },
1710 #if CONFIG_MATROSKA_MUXER
1711 static const AVClass matroska_class = {
1712 .class_name = "matroska muxer",
1713 .item_name = av_default_item_name,
1715 .version = LIBAVUTIL_VERSION_INT,
1718 AVOutputFormat ff_matroska_muxer = {
1720 .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
1721 .mime_type = "video/x-matroska",
1722 .extensions = "mkv",
1723 .priv_data_size = sizeof(MatroskaMuxContext),
1724 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
1725 AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
1726 .video_codec = CONFIG_LIBX264_ENCODER ?
1727 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
1728 .write_header = mkv_write_header,
1729 .write_packet = mkv_write_flush_packet,
1730 .write_trailer = mkv_write_trailer,
1731 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
1732 AVFMT_TS_NONSTRICT | AVFMT_ALLOW_FLUSH,
1733 .codec_tag = (const AVCodecTag* const []){
1734 ff_codec_bmp_tags, ff_codec_wav_tags,
1735 additional_audio_tags, additional_video_tags, 0
1738 .subtitle_codec = AV_CODEC_ID_SSA,
1740 .subtitle_codec = AV_CODEC_ID_ASS,
1742 .query_codec = mkv_query_codec,
1743 .priv_class = &matroska_class,
1747 #if CONFIG_WEBM_MUXER
1748 static const AVClass webm_class = {
1749 .class_name = "webm muxer",
1750 .item_name = av_default_item_name,
1752 .version = LIBAVUTIL_VERSION_INT,
1755 AVOutputFormat ff_webm_muxer = {
1757 .long_name = NULL_IF_CONFIG_SMALL("WebM"),
1758 .mime_type = "video/webm",
1759 .extensions = "webm",
1760 .priv_data_size = sizeof(MatroskaMuxContext),
1761 .audio_codec = AV_CODEC_ID_VORBIS,
1762 .video_codec = AV_CODEC_ID_VP8,
1763 .subtitle_codec = AV_CODEC_ID_WEBVTT,
1764 .write_header = mkv_write_header,
1765 .write_packet = mkv_write_flush_packet,
1766 .write_trailer = mkv_write_trailer,
1767 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
1768 AVFMT_TS_NONSTRICT | AVFMT_ALLOW_FLUSH,
1769 .priv_class = &webm_class,
1773 #if CONFIG_MATROSKA_AUDIO_MUXER
1774 static const AVClass mka_class = {
1775 .class_name = "matroska audio muxer",
1776 .item_name = av_default_item_name,
1778 .version = LIBAVUTIL_VERSION_INT,
1780 AVOutputFormat ff_matroska_audio_muxer = {
1782 .long_name = NULL_IF_CONFIG_SMALL("Matroska Audio"),
1783 .mime_type = "audio/x-matroska",
1784 .extensions = "mka",
1785 .priv_data_size = sizeof(MatroskaMuxContext),
1786 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
1787 AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
1788 .video_codec = AV_CODEC_ID_NONE,
1789 .write_header = mkv_write_header,
1790 .write_packet = mkv_write_flush_packet,
1791 .write_trailer = mkv_write_trailer,
1792 .flags = AVFMT_GLOBALHEADER | AVFMT_TS_NONSTRICT |
1794 .codec_tag = (const AVCodecTag* const []){
1795 ff_codec_wav_tags, additional_audio_tags, 0
1797 .priv_class = &mka_class,