matroskaenc: set the stream timebase earlier
[libav.git] / libavformat / matroskaenc.c
CommitLineData
67143c0f 1/*
8cf3bb26 2 * Matroska muxer
67143c0f
DC
3 * Copyright (c) 2007 David Conrad
4 *
2912e87a 5 * This file is part of Libav.
67143c0f 6 *
2912e87a 7 * Libav is free software; you can redistribute it and/or
67143c0f
DC
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.
11 *
2912e87a 12 * Libav is distributed in the hope that it will be useful,
67143c0f
DC
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.
16 *
17 * You should have received a copy of the GNU Lesser General Public
2912e87a 18 * License along with Libav; if not, write to the Free Software
67143c0f
DC
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
8f8bc923
DB
22#include <stdint.h>
23
0574bc06 24#include "avc.h"
a823d094 25#include "hevc.h"
67143c0f 26#include "avformat.h"
0574bc06
AK
27#include "avlanguage.h"
28#include "flacenc.h"
c3f9ebf7 29#include "internal.h"
f009e36f 30#include "isom.h"
67143c0f 31#include "matroska.h"
0574bc06 32#include "riff.h"
106b62f4 33#include "vorbiscomment.h"
01656fd4 34#include "wv.h"
0574bc06
AK
35
36#include "libavutil/avstring.h"
106b62f4 37#include "libavutil/channel_layout.h"
0574bc06 38#include "libavutil/dict.h"
3383a53e 39#include "libavutil/intfloat.h"
0574bc06
AK
40#include "libavutil/intreadwrite.h"
41#include "libavutil/lfg.h"
0ebcdf5c 42#include "libavutil/mathematics.h"
e3b225a4 43#include "libavutil/opt.h"
1f4280e7 44#include "libavutil/random_seed.h"
0574bc06
AK
45#include "libavutil/samplefmt.h"
46
245976da 47#include "libavcodec/xiph.h"
7bfacd4e 48#include "libavcodec/mpeg4audio.h"
67143c0f 49
baf71dca 50typedef struct ebml_master {
bc5c918e 51 int64_t pos; ///< absolute offset in the file where the master's elements start
baf71dca
DC
52 int sizebytes; ///< how many bytes were reserved for the size
53} ebml_master;
54
967d815a
DC
55typedef struct mkv_seekhead_entry {
56 unsigned int elementid;
57 uint64_t segmentpos;
58} mkv_seekhead_entry;
59
60typedef struct mkv_seekhead {
bc5c918e
DB
61 int64_t filepos;
62 int64_t segment_offset; ///< the file offset to the beginning of the segment
1b66d314 63 int reserved_size; ///< -1 if appending to file
967d815a
DC
64 int max_entries;
65 mkv_seekhead_entry *entries;
66 int num_entries;
67} mkv_seekhead;
68
6364d534
DC
69typedef struct {
70 uint64_t pts;
71 int tracknum;
bc5c918e 72 int64_t cluster_pos; ///< file offset of the cluster containing the block
6364d534
DC
73} mkv_cuepoint;
74
75typedef struct {
bc5c918e 76 int64_t segment_offset;
6364d534
DC
77 mkv_cuepoint *entries;
78 int num_entries;
79} mkv_cues;
80
84d4e599
DC
81typedef struct {
82 int write_dts;
a1aa37dd 83 int64_t ts_offset;
84d4e599
DC
84} mkv_track;
85
316d6c15
JZ
86#define MODE_MATROSKAv2 0x01
87#define MODE_WEBM 0x02
88
67143c0f 89typedef struct MatroskaMuxContext {
e3b225a4 90 const AVClass *class;
316d6c15 91 int mode;
ae628ec1 92 AVIOContext *dyn_bc;
baf71dca 93 ebml_master segment;
bc5c918e 94 int64_t segment_offset;
baf71dca 95 ebml_master cluster;
bc5c918e 96 int64_t cluster_pos; ///< file offset of the current cluster
f9ff7179 97 int64_t cluster_pts;
bc5c918e 98 int64_t duration_offset;
f9ff7179 99 int64_t duration;
967d815a 100 mkv_seekhead *main_seekhead;
6364d534 101 mkv_cues *cues;
84d4e599 102 mkv_track *tracks;
541d443c 103
ac9baa71 104 AVPacket cur_audio_pkt;
c7a63a52
AK
105
106 int have_attachments;
e3b225a4
AK
107
108 int reserve_cues_space;
98308bd4 109 int cluster_size_limit;
e3b225a4 110 int64_t cues_pos;
98308bd4 111 int64_t cluster_time_limit;
26b241c0 112 int wrote_chapters;
67143c0f
DC
113} MatroskaMuxContext;
114
baf71dca 115
e3cd80cd
DC
116/** 2 bytes * 3 for EBML IDs, 3 1-byte EBML lengths, 8 bytes for 64 bit
117 * offset, 4 bytes for target EBML ID */
baf71dca
DC
118#define MAX_SEEKENTRY_SIZE 21
119
e3cd80cd
DC
120/** per-cuepoint-track - 3 1-byte EBML IDs, 3 1-byte EBML sizes, 2
121 * 8-byte uint max */
baf71dca
DC
122#define MAX_CUETRACKPOS_SIZE 22
123
e3cd80cd 124/** per-cuepoint - 2 1-byte EBML IDs, 2 1-byte EBML sizes, 8-byte uint max */
baf71dca
DC
125#define MAX_CUEPOINT_SIZE(num_tracks) 12 + MAX_CUETRACKPOS_SIZE*num_tracks
126
127
22ccb69a
DC
128static int ebml_id_size(unsigned int id)
129{
130 return (av_log2(id+1)-1)/7+1;
131}
132
ae628ec1 133static void put_ebml_id(AVIOContext *pb, unsigned int id)
67143c0f 134{
432adc13
DC
135 int i = ebml_id_size(id);
136 while (i--)
77eb5504 137 avio_w8(pb, id >> (i*8));
67143c0f
DC
138}
139
ec8f4ad9 140/**
bf898960 141 * Write an EBML size meaning "unknown size".
ec8f4ad9 142 *
bf898960 143 * @param bytes The number of bytes the size should occupy (maximum: 8).
ec8f4ad9 144 */
ae628ec1 145static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
ec8f4ad9 146{
0580a122 147 assert(bytes <= 8);
77eb5504 148 avio_w8(pb, 0x1ff >> bytes);
203cce9a 149 while (--bytes)
77eb5504 150 avio_w8(pb, 0xff);
ec8f4ad9
DC
151}
152
1c73478c 153/**
0f651e8c 154 * Calculate how many bytes are needed to represent a given number in EBML.
1c73478c 155 */
0f651e8c 156static int ebml_num_size(uint64_t num)
1c73478c
DC
157{
158 int bytes = 1;
0f651e8c 159 while ((num+1) >> bytes*7) bytes++;
1c73478c
DC
160 return bytes;
161}
162
f0e9f442 163/**
0f651e8c 164 * Write a number in EBML variable length format.
f0e9f442 165 *
0f651e8c 166 * @param bytes The number of bytes that need to be used to write the number.
f0e9f442
DC
167 * If zero, any number of bytes can be used.
168 */
ae628ec1 169static void put_ebml_num(AVIOContext *pb, uint64_t num, int bytes)
67143c0f 170{
0f651e8c 171 int i, needed_bytes = ebml_num_size(num);
67143c0f
DC
172
173 // sizes larger than this are currently undefined in EBML
0f651e8c 174 assert(num < (1ULL<<56)-1);
ffb880c2 175
f0e9f442
DC
176 if (bytes == 0)
177 // don't care how many bytes are used, so use the min
178 bytes = needed_bytes;
47e08c58
DC
179 // the bytes needed to write the given size would exceed the bytes
180 // that we need to use, so write unknown size. This shouldn't happen.
0580a122 181 assert(bytes >= needed_bytes);
f0e9f442 182
0f651e8c 183 num |= 1ULL << bytes*7;
ddf16467 184 for (i = bytes - 1; i >= 0; i--)
77eb5504 185 avio_w8(pb, num >> i*8);
67143c0f
DC
186}
187
ae628ec1 188static void put_ebml_uint(AVIOContext *pb, unsigned int elementid, uint64_t val)
67143c0f 189{
9f38fd7e 190 int i, bytes = 1;
73260a11
AJ
191 uint64_t tmp = val;
192 while (tmp>>=8) bytes++;
67143c0f
DC
193
194 put_ebml_id(pb, elementid);
0f651e8c 195 put_ebml_num(pb, bytes, 0);
9f38fd7e 196 for (i = bytes - 1; i >= 0; i--)
77eb5504 197 avio_w8(pb, val >> i*8);
67143c0f
DC
198}
199
ae628ec1 200static void put_ebml_float(AVIOContext *pb, unsigned int elementid, double val)
9b6b0c79 201{
9b6b0c79 202 put_ebml_id(pb, elementid);
0f651e8c 203 put_ebml_num(pb, 8, 0);
3383a53e 204 avio_wb64(pb, av_double2int(val));
9b6b0c79
DC
205}
206
ae628ec1 207static void put_ebml_binary(AVIOContext *pb, unsigned int elementid,
4a6bef1f 208 const void *buf, int size)
67143c0f
DC
209{
210 put_ebml_id(pb, elementid);
0f651e8c 211 put_ebml_num(pb, size, 0);
77eb5504 212 avio_write(pb, buf, size);
67143c0f
DC
213}
214
ae628ec1 215static void put_ebml_string(AVIOContext *pb, unsigned int elementid, const char *str)
67143c0f
DC
216{
217 put_ebml_binary(pb, elementid, str, strlen(str));
218}
219
57848e9a 220/**
49bd8e4b 221 * Write a void element of a given size. Useful for reserving space in
cfde5d18 222 * the file to be written to later.
57848e9a 223 *
5045da83 224 * @param size The number of bytes to reserve, which must be at least 2.
57848e9a 225 */
ae628ec1 226static void put_ebml_void(AVIOContext *pb, uint64_t size)
f57b85a5 227{
a2704c97 228 int64_t currentpos = avio_tell(pb);
f57b85a5 229
0580a122 230 assert(size >= 2);
f57b85a5
DC
231
232 put_ebml_id(pb, EBML_ID_VOID);
cfde5d18
DC
233 // we need to subtract the length needed to store the size from the
234 // size we need to reserve so 2 cases, we use 8 bytes to store the
235 // size if possible, 1 byte otherwise
f57b85a5 236 if (size < 10)
0f651e8c 237 put_ebml_num(pb, size-1, 0);
f57b85a5 238 else
0f651e8c 239 put_ebml_num(pb, size-9, 8);
a2704c97 240 while(avio_tell(pb) < currentpos + size)
77eb5504 241 avio_w8(pb, 0);
f57b85a5
DC
242}
243
ae628ec1 244static ebml_master start_ebml_master(AVIOContext *pb, unsigned int elementid, uint64_t expectedsize)
67143c0f 245{
0f651e8c 246 int bytes = expectedsize ? ebml_num_size(expectedsize) : 8;
67143c0f 247 put_ebml_id(pb, elementid);
baf71dca 248 put_ebml_size_unknown(pb, bytes);
a2704c97 249 return (ebml_master){ avio_tell(pb), bytes };
67143c0f
DC
250}
251
ae628ec1 252static void end_ebml_master(AVIOContext *pb, ebml_master master)
67143c0f 253{
a2704c97 254 int64_t pos = avio_tell(pb);
67143c0f 255
6b4aa5da 256 if (avio_seek(pb, master.pos - master.sizebytes, SEEK_SET) < 0)
ac9e1177 257 return;
0f651e8c 258 put_ebml_num(pb, pos - master.pos, master.sizebytes);
6b4aa5da 259 avio_seek(pb, pos, SEEK_SET);
67143c0f
DC
260}
261
ae628ec1 262static void put_xiph_size(AVIOContext *pb, int size)
86be6637
DC
263{
264 int i;
265 for (i = 0; i < size / 255; i++)
77eb5504
AK
266 avio_w8(pb, 255);
267 avio_w8(pb, size % 255);
86be6637
DC
268}
269
57848e9a 270/**
cfde5d18
DC
271 * Initialize a mkv_seekhead element to be ready to index level 1 Matroska
272 * elements. If a maximum number of elements is specified, enough space
273 * will be reserved at the current file location to write a seek head of
274 * that size.
57848e9a 275 *
cfde5d18 276 * @param segment_offset The absolute offset to the position in the file
ab332d01
DC
277 * where the segment begins.
278 * @param numelements The maximum number of elements that will be indexed
cfde5d18 279 * by this seek head, 0 if unlimited.
57848e9a 280 */
ae628ec1 281static mkv_seekhead * mkv_start_seekhead(AVIOContext *pb, int64_t segment_offset, int numelements)
967d815a
DC
282{
283 mkv_seekhead *new_seekhead = av_mallocz(sizeof(mkv_seekhead));
284 if (new_seekhead == NULL)
285 return NULL;
286
287 new_seekhead->segment_offset = segment_offset;
288
289 if (numelements > 0) {
a2704c97 290 new_seekhead->filepos = avio_tell(pb);
cfde5d18
DC
291 // 21 bytes max for a seek entry, 10 bytes max for the SeekHead ID
292 // and size, and 3 bytes to guarantee that an EBML void element
293 // will fit afterwards
baf71dca 294 new_seekhead->reserved_size = numelements * MAX_SEEKENTRY_SIZE + 13;
967d815a
DC
295 new_seekhead->max_entries = numelements;
296 put_ebml_void(pb, new_seekhead->reserved_size);
297 }
298 return new_seekhead;
299}
300
301static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
302{
f369b935 303 int err;
967d815a
DC
304
305 // don't store more elements than we reserved space for
306 if (seekhead->max_entries > 0 && seekhead->max_entries <= seekhead->num_entries)
307 return -1;
308
00a63bfb
AK
309 if ((err = av_reallocp_array(&seekhead->entries, seekhead->num_entries + 1,
310 sizeof(*seekhead->entries))) < 0) {
f369b935
AK
311 seekhead->num_entries = 0;
312 return err;
313 }
967d815a 314
00a63bfb
AK
315 seekhead->entries[seekhead->num_entries].elementid = elementid;
316 seekhead->entries[seekhead->num_entries++].segmentpos = filepos - seekhead->segment_offset;
967d815a 317
967d815a
DC
318 return 0;
319}
320
57848e9a 321/**
cfde5d18
DC
322 * Write the seek head to the file and free it. If a maximum number of
323 * elements was specified to mkv_start_seekhead(), the seek head will
324 * be written at the location reserved for it. Otherwise, it is written
325 * at the current location in the file.
57848e9a 326 *
7a2a4840
DC
327 * @return The file offset where the seekhead was written,
328 * -1 if an error occurred.
57848e9a 329 */
ae628ec1 330static int64_t mkv_write_seekhead(AVIOContext *pb, mkv_seekhead *seekhead)
967d815a 331{
baf71dca 332 ebml_master metaseek, seekentry;
bc5c918e 333 int64_t currentpos;
967d815a
DC
334 int i;
335
a2704c97 336 currentpos = avio_tell(pb);
967d815a 337
44729bc0
MS
338 if (seekhead->reserved_size > 0) {
339 if (avio_seek(pb, seekhead->filepos, SEEK_SET) < 0) {
340 currentpos = -1;
341 goto fail;
342 }
343 }
967d815a 344
baf71dca 345 metaseek = start_ebml_master(pb, MATROSKA_ID_SEEKHEAD, seekhead->reserved_size);
967d815a
DC
346 for (i = 0; i < seekhead->num_entries; i++) {
347 mkv_seekhead_entry *entry = &seekhead->entries[i];
348
baf71dca 349 seekentry = start_ebml_master(pb, MATROSKA_ID_SEEKENTRY, MAX_SEEKENTRY_SIZE);
967d815a
DC
350
351 put_ebml_id(pb, MATROSKA_ID_SEEKID);
0f651e8c 352 put_ebml_num(pb, ebml_id_size(entry->elementid), 0);
967d815a
DC
353 put_ebml_id(pb, entry->elementid);
354
355 put_ebml_uint(pb, MATROSKA_ID_SEEKPOSITION, entry->segmentpos);
356 end_ebml_master(pb, seekentry);
357 }
358 end_ebml_master(pb, metaseek);
359
360 if (seekhead->reserved_size > 0) {
a2704c97 361 uint64_t remaining = seekhead->filepos + seekhead->reserved_size - avio_tell(pb);
967d815a 362 put_ebml_void(pb, remaining);
6b4aa5da 363 avio_seek(pb, currentpos, SEEK_SET);
967d815a
DC
364
365 currentpos = seekhead->filepos;
366 }
44729bc0 367fail:
967d815a
DC
368 av_free(seekhead->entries);
369 av_free(seekhead);
370
371 return currentpos;
372}
373
bc5c918e 374static mkv_cues * mkv_start_cues(int64_t segment_offset)
6364d534
DC
375{
376 mkv_cues *cues = av_mallocz(sizeof(mkv_cues));
377 if (cues == NULL)
378 return NULL;
379
380 cues->segment_offset = segment_offset;
381 return cues;
382}
383
84d4e599 384static int mkv_add_cuepoint(mkv_cues *cues, int stream, int64_t ts, int64_t cluster_pos)
6364d534 385{
f369b935 386 int err;
6364d534 387
4ffbe3f3
JG
388 if (ts < 0)
389 return 0;
390
00a63bfb
AK
391 if ((err = av_reallocp_array(&cues->entries, cues->num_entries + 1,
392 sizeof(*cues->entries))) < 0) {
f369b935
AK
393 cues->num_entries = 0;
394 return err;
395 }
6364d534 396
00a63bfb
AK
397 cues->entries[cues->num_entries].pts = ts;
398 cues->entries[cues->num_entries].tracknum = stream + 1;
399 cues->entries[cues->num_entries++].cluster_pos = cluster_pos - cues->segment_offset;
6364d534 400
6364d534
DC
401 return 0;
402}
403
ae628ec1 404static int64_t mkv_write_cues(AVIOContext *pb, mkv_cues *cues, int num_tracks)
6364d534 405{
baf71dca 406 ebml_master cues_element;
bc5c918e 407 int64_t currentpos;
6364d534
DC
408 int i, j;
409
a2704c97 410 currentpos = avio_tell(pb);
baf71dca 411 cues_element = start_ebml_master(pb, MATROSKA_ID_CUES, 0);
6364d534
DC
412
413 for (i = 0; i < cues->num_entries; i++) {
baf71dca 414 ebml_master cuepoint, track_positions;
6364d534
DC
415 mkv_cuepoint *entry = &cues->entries[i];
416 uint64_t pts = entry->pts;
417
baf71dca 418 cuepoint = start_ebml_master(pb, MATROSKA_ID_POINTENTRY, MAX_CUEPOINT_SIZE(num_tracks));
6364d534
DC
419 put_ebml_uint(pb, MATROSKA_ID_CUETIME, pts);
420
421 // put all the entries from different tracks that have the exact same
422 // timestamp into the same CuePoint
423 for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
baf71dca 424 track_positions = start_ebml_master(pb, MATROSKA_ID_CUETRACKPOSITION, MAX_CUETRACKPOS_SIZE);
6364d534
DC
425 put_ebml_uint(pb, MATROSKA_ID_CUETRACK , entry[j].tracknum );
426 put_ebml_uint(pb, MATROSKA_ID_CUECLUSTERPOSITION, entry[j].cluster_pos);
427 end_ebml_master(pb, track_positions);
428 }
429 i += j - 1;
430 end_ebml_master(pb, cuepoint);
431 }
432 end_ebml_master(pb, cues_element);
433
6364d534
DC
434 return currentpos;
435}
436
ae628ec1 437static int put_xiph_codecpriv(AVFormatContext *s, AVIOContext *pb, AVCodecContext *codec)
56d55a3b 438{
56d55a3b
DC
439 uint8_t *header_start[3];
440 int header_len[3];
441 int first_header_size;
86be6637 442 int j;
56d55a3b 443
36ef5369 444 if (codec->codec_id == AV_CODEC_ID_VORBIS)
56d55a3b
DC
445 first_header_size = 30;
446 else
447 first_header_size = 42;
448
357db4c2 449 if (avpriv_split_xiph_headers(codec->extradata, codec->extradata_size,
56d55a3b 450 first_header_size, header_start, header_len) < 0) {
b62a33d0 451 av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
56d55a3b
DC
452 return -1;
453 }
454
77eb5504 455 avio_w8(pb, 2); // number packets - 1
56d55a3b 456 for (j = 0; j < 2; j++) {
86be6637 457 put_xiph_size(pb, header_len[j]);
56d55a3b
DC
458 }
459 for (j = 0; j < 3; j++)
77eb5504 460 avio_write(pb, header_start[j], header_len[j]);
801edb42
DC
461
462 return 0;
56d55a3b 463}
67143c0f 464
01656fd4
AK
465static int put_wv_codecpriv(AVIOContext *pb, AVCodecContext *codec)
466{
467 if (codec->extradata && codec->extradata_size == 2)
468 avio_write(pb, codec->extradata, 2);
469 else
470 avio_wl16(pb, 0x403); // fallback to the version mentioned in matroska specs
471 return 0;
472}
473
106b62f4
AK
474static int put_flac_codecpriv(AVFormatContext *s,
475 AVIOContext *pb, AVCodecContext *codec)
476{
477 int write_comment = (codec->channel_layout &&
478 !(codec->channel_layout & ~0x3ffffULL) &&
479 !ff_flac_is_native_layout(codec->channel_layout));
480 int ret = ff_flac_write_header(pb, codec, !write_comment);
481
482 if (ret < 0)
483 return ret;
484
485 if (write_comment) {
486 const char *vendor = (s->flags & AVFMT_FLAG_BITEXACT) ?
487 "Libav" : LIBAVFORMAT_IDENT;
488 AVDictionary *dict = NULL;
489 uint8_t buf[32], *data, *p;
490 int len;
491
492 snprintf(buf, sizeof(buf), "0x%"PRIx64, codec->channel_layout);
493 av_dict_set(&dict, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", buf, 0);
494
495 len = ff_vorbiscomment_length(dict, vendor);
496 data = av_malloc(len + 4);
497 if (!data) {
498 av_dict_free(&dict);
499 return AVERROR(ENOMEM);
500 }
501
502 data[0] = 0x84;
503 AV_WB24(data + 1, len);
504
505 p = data + 4;
506 ff_vorbiscomment_write(&p, &dict, vendor);
507
508 avio_write(pb, data, len + 4);
509
510 av_freep(&data);
511 av_dict_free(&dict);
512 }
513
514 return 0;
515}
516
b62a33d0 517static void get_aac_sample_rates(AVFormatContext *s, AVCodecContext *codec, int *sample_rate, int *output_sample_rate)
07918a22 518{
bc17bd90 519 MPEG4AudioConfig mp4ac;
07918a22 520
fd095539
JG
521 if (avpriv_mpeg4audio_get_config(&mp4ac, codec->extradata,
522 codec->extradata_size * 8, 1) < 0) {
bc17bd90 523 av_log(s, AV_LOG_WARNING, "Error parsing AAC extradata, unable to determine samplerate.\n");
07918a22
DC
524 return;
525 }
526
bc17bd90
AK
527 *sample_rate = mp4ac.sample_rate;
528 *output_sample_rate = mp4ac.ext_sample_rate;
07918a22
DC
529}
530
ae628ec1 531static int mkv_write_codecprivate(AVFormatContext *s, AVIOContext *pb, AVCodecContext *codec, int native_id, int qt_id)
5c559894 532{
ae628ec1 533 AVIOContext *dyn_cp;
46d18a88 534 uint8_t *codecpriv;
899681cd 535 int ret, codecpriv_size;
46d18a88 536
b92c5452 537 ret = avio_open_dyn_buf(&dyn_cp);
899681cd
BA
538 if(ret < 0)
539 return ret;
5c559894
DC
540
541 if (native_id) {
36ef5369 542 if (codec->codec_id == AV_CODEC_ID_VORBIS || codec->codec_id == AV_CODEC_ID_THEORA)
899681cd 543 ret = put_xiph_codecpriv(s, dyn_cp, codec);
36ef5369 544 else if (codec->codec_id == AV_CODEC_ID_FLAC)
106b62f4 545 ret = put_flac_codecpriv(s, dyn_cp, codec);
01656fd4
AK
546 else if (codec->codec_id == AV_CODEC_ID_WAVPACK)
547 ret = put_wv_codecpriv(dyn_cp, codec);
36ef5369 548 else if (codec->codec_id == AV_CODEC_ID_H264)
9ab3f71b 549 ret = ff_isom_write_avcc(dyn_cp, codec->extradata, codec->extradata_size);
a823d094
TW
550 else if (codec->codec_id == AV_CODEC_ID_HEVC)
551 ret = ff_isom_write_hvcc(dyn_cp, codec->extradata, codec->extradata_size, 0);
8071dca3
MB
552 else if (codec->codec_id == AV_CODEC_ID_ALAC) {
553 if (codec->extradata_size < 36) {
554 av_log(s, AV_LOG_ERROR,
555 "Invalid extradata found, ALAC expects a 36-byte "
556 "QuickTime atom.");
557 ret = AVERROR_INVALIDDATA;
558 } else
559 avio_write(dyn_cp, codec->extradata + 12,
560 codec->extradata_size - 12);
561 }
c301d5ae 562 else if (codec->extradata_size)
77eb5504 563 avio_write(dyn_cp, codec->extradata, codec->extradata_size);
72415b2a 564 } else if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
f009e36f
AJ
565 if (qt_id) {
566 if (!codec->codec_tag)
167f3b8d 567 codec->codec_tag = ff_codec_get_tag(ff_codec_movvideo_tags, codec->codec_id);
f009e36f 568 if (codec->extradata_size)
77eb5504 569 avio_write(dyn_cp, codec->extradata, codec->extradata_size);
f009e36f 570 } else {
434a70b8
DC
571 if (!codec->codec_tag)
572 codec->codec_tag = ff_codec_get_tag(ff_codec_bmp_tags, codec->codec_id);
573 if (!codec->codec_tag) {
f75ab7a6 574 av_log(s, AV_LOG_ERROR, "No bmp codec ID found.\n");
434a70b8
DC
575 ret = -1;
576 }
5c559894 577
434a70b8 578 ff_put_bmp_header(dyn_cp, codec, ff_codec_bmp_tags, 0);
f009e36f 579 }
5c559894 580
72415b2a 581 } else if (codec->codec_type == AVMEDIA_TYPE_AUDIO) {
4896dd57
JM
582 unsigned int tag;
583 tag = ff_codec_get_tag(ff_codec_wav_tags, codec->codec_id);
584 if (!tag) {
f75ab7a6 585 av_log(s, AV_LOG_ERROR, "No wav codec ID found.\n");
46d18a88 586 ret = -1;
5c559894 587 }
4896dd57
JM
588 if (!codec->codec_tag)
589 codec->codec_tag = tag;
5c559894 590
1a40491e 591 ff_put_wav_header(dyn_cp, codec);
5c559894 592 }
46d18a88 593
6dc7d80d 594 codecpriv_size = avio_close_dyn_buf(dyn_cp, &codecpriv);
46d18a88
DC
595 if (codecpriv_size)
596 put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codecpriv, codecpriv_size);
597 av_free(codecpriv);
598 return ret;
5c559894
DC
599}
600
5034ab90 601static int mkv_write_tracks(AVFormatContext *s)
67143c0f
DC
602{
603 MatroskaMuxContext *mkv = s->priv_data;
ae628ec1 604 AVIOContext *pb = s->pb;
baf71dca 605 ebml_master tracks;
6d588ecd 606 int i, j, ret;
67143c0f 607
a2704c97 608 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TRACKS, avio_tell(pb));
6d588ecd 609 if (ret < 0) return ret;
967d815a 610
baf71dca 611 tracks = start_ebml_master(pb, MATROSKA_ID_TRACKS, 0);
67143c0f
DC
612 for (i = 0; i < s->nb_streams; i++) {
613 AVStream *st = s->streams[i];
f622c4f4 614 AVCodecContext *codec = st->codec;
baf71dca 615 ebml_master subinfo, track;
f622c4f4 616 int native_id = 0;
f009e36f 617 int qt_id = 0;
d22f88cb 618 int bit_depth = av_get_bits_per_sample(codec->codec_id);
07918a22
DC
619 int sample_rate = codec->sample_rate;
620 int output_sample_rate = 0;
d2d67e42 621 AVDictionaryEntry *tag;
07918a22 622
962d6315
AK
623 // ms precision is the de-facto standard timescale for mkv files
624 avpriv_set_pts_info(st, 64, 1, 1000);
625
c7a63a52
AK
626 if (codec->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
627 mkv->have_attachments = 1;
628 continue;
629 }
630
a6da1aa0 631 if (!bit_depth)
e6c52cee 632 bit_depth = av_get_bytes_per_sample(codec->sample_fmt) << 3;
a6da1aa0 633
36ef5369 634 if (codec->codec_id == AV_CODEC_ID_AAC)
b62a33d0 635 get_aac_sample_rates(s, codec, &sample_rate, &output_sample_rate);
f622c4f4 636
baf71dca 637 track = start_ebml_master(pb, MATROSKA_ID_TRACKENTRY, 0);
815eb6a2
DC
638 put_ebml_uint (pb, MATROSKA_ID_TRACKNUMBER , i + 1);
639 put_ebml_uint (pb, MATROSKA_ID_TRACKUID , i + 1);
f622c4f4
DC
640 put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0); // no lacing (yet)
641
d2d67e42 642 if ((tag = av_dict_get(st->metadata, "title", NULL, 0)))
5e565998 643 put_ebml_string(pb, MATROSKA_ID_TRACKNAME, tag->value);
d2d67e42 644 tag = av_dict_get(st->metadata, "language", NULL, 0);
5e565998 645 put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag ? tag->value:"und");
f622c4f4 646
f812eeda
JS
647 // The default value for TRACKFLAGDEFAULT is 1, so add element
648 // if we need to clear it.
649 if (!(st->disposition & AV_DISPOSITION_DEFAULT))
3194b004 650 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGDEFAULT, !!(st->disposition & AV_DISPOSITION_DEFAULT));
90c2295b 651
a1aa37dd
AK
652 if (codec->codec_type == AVMEDIA_TYPE_AUDIO && codec->delay) {
653 mkv->tracks[i].ts_offset = av_rescale_q(codec->delay,
654 (AVRational){ 1, codec->sample_rate },
655 st->time_base);
656
657 put_ebml_uint(pb, MATROSKA_ID_CODECDELAY,
658 av_rescale_q(codec->delay, (AVRational){ 1, codec->sample_rate },
659 (AVRational){ 1, 1000000000 }));
660 }
661
ab332d01 662 // look for a codec ID string specific to mkv to use,
cfde5d18 663 // if none are found, use AVI codes
36ef5369 664 for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
f622c4f4
DC
665 if (ff_mkv_codec_tags[j].id == codec->codec_id) {
666 put_ebml_string(pb, MATROSKA_ID_CODECID, ff_mkv_codec_tags[j].str);
667 native_id = 1;
668 break;
669 }
670 }
671
36ef5369
AK
672 if (mkv->mode == MODE_WEBM && !(codec->codec_id == AV_CODEC_ID_VP8 ||
673 codec->codec_id == AV_CODEC_ID_VORBIS)) {
316d6c15
JZ
674 av_log(s, AV_LOG_ERROR,
675 "Only VP8 video and Vorbis audio are supported for WebM.\n");
676 return AVERROR(EINVAL);
677 }
678
f622c4f4 679 switch (codec->codec_type) {
72415b2a 680 case AVMEDIA_TYPE_VIDEO:
f622c4f4 681 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_VIDEO);
81eec081
AK
682 if (st->avg_frame_rate.num > 0 && st->avg_frame_rate.den > 0)
683 put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, 1E9 / av_q2d(st->avg_frame_rate));
f622c4f4 684
f009e36f 685 if (!native_id &&
167f3b8d 686 ff_codec_get_tag(ff_codec_movvideo_tags, codec->codec_id) &&
1a40491e 687 (!ff_codec_get_tag(ff_codec_bmp_tags, codec->codec_id)
36ef5369
AK
688 || codec->codec_id == AV_CODEC_ID_SVQ1
689 || codec->codec_id == AV_CODEC_ID_SVQ3
690 || codec->codec_id == AV_CODEC_ID_CINEPAK))
f009e36f
AJ
691 qt_id = 1;
692
693 if (qt_id)
694 put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");
84d4e599 695 else if (!native_id) {
ab332d01 696 // if there is no mkv-specific codec ID, use VFW mode
cc8be506 697 put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");
84d4e599
DC
698 mkv->tracks[i].write_dts = 1;
699 }
c301d5ae 700
baf71dca 701 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
f622c4f4
DC
702 // XXX: interlace flag?
703 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , codec->width);
704 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, codec->height);
d2d67e42 705 if ((tag = av_dict_get(s->metadata, "stereo_mode", NULL, 0))) {
945dda41
AA
706 uint8_t stereo_fmt = atoi(tag->value);
707 int valid_fmt = 0;
708
709 switch (mkv->mode) {
710 case MODE_WEBM:
711 if (stereo_fmt <= MATROSKA_VIDEO_STEREOMODE_TYPE_TOP_BOTTOM
712 || stereo_fmt == MATROSKA_VIDEO_STEREOMODE_TYPE_RIGHT_LEFT)
713 valid_fmt = 1;
714 break;
715 case MODE_MATROSKAv2:
716 if (stereo_fmt <= MATROSKA_VIDEO_STEREOMODE_TYPE_BOTH_EYES_BLOCK_RL)
717 valid_fmt = 1;
718 break;
719 }
720
721 if (valid_fmt)
722 put_ebml_uint (pb, MATROSKA_ID_VIDEOSTEREOMODE, stereo_fmt);
723 }
59729451
AJ
724 if (st->sample_aspect_ratio.num) {
725 int d_width = codec->width*av_q2d(st->sample_aspect_ratio);
726 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , d_width);
727 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, codec->height);
d00a3516 728 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYUNIT, 3);
7332addd 729 }
f622c4f4
DC
730 end_ebml_master(pb, subinfo);
731 break;
732
72415b2a 733 case AVMEDIA_TYPE_AUDIO:
f622c4f4
DC
734 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_AUDIO);
735
c301d5ae 736 if (!native_id)
1a302a5c 737 // no mkv-specific ID, use ACM mode
cc8be506 738 put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");
c301d5ae 739
baf71dca 740 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);
f622c4f4 741 put_ebml_uint (pb, MATROSKA_ID_AUDIOCHANNELS , codec->channels);
07918a22
DC
742 put_ebml_float (pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, sample_rate);
743 if (output_sample_rate)
744 put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
44008871
DC
745 if (bit_depth)
746 put_ebml_uint(pb, MATROSKA_ID_AUDIOBITDEPTH, bit_depth);
f622c4f4
DC
747 end_ebml_master(pb, subinfo);
748 break;
749
72415b2a 750 case AVMEDIA_TYPE_SUBTITLE:
47e08c58 751 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_SUBTITLE);
89d4c130
AJ
752 if (!native_id) {
753 av_log(s, AV_LOG_ERROR, "Subtitle codec %d is not supported.\n", codec->codec_id);
754 return AVERROR(ENOSYS);
755 }
47e08c58 756 break;
f622c4f4 757 default:
2501d2f3 758 av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.\n");
f622c4f4
DC
759 break;
760 }
f009e36f 761 ret = mkv_write_codecprivate(s, pb, codec, native_id, qt_id);
5c559894
DC
762 if (ret < 0) return ret;
763
67143c0f
DC
764 end_ebml_master(pb, track);
765 }
766 end_ebml_master(pb, tracks);
801edb42 767 return 0;
5034ab90
DC
768}
769
2bd0758e
AK
770static int mkv_write_chapters(AVFormatContext *s)
771{
772 MatroskaMuxContext *mkv = s->priv_data;
ae628ec1 773 AVIOContext *pb = s->pb;
2bd0758e
AK
774 ebml_master chapters, editionentry;
775 AVRational scale = {1, 1E9};
776 int i, ret;
777
26b241c0 778 if (!s->nb_chapters || mkv->wrote_chapters)
2bd0758e
AK
779 return 0;
780
a2704c97 781 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CHAPTERS, avio_tell(pb));
2bd0758e
AK
782 if (ret < 0) return ret;
783
784 chapters = start_ebml_master(pb, MATROSKA_ID_CHAPTERS , 0);
785 editionentry = start_ebml_master(pb, MATROSKA_ID_EDITIONENTRY, 0);
786 put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGDEFAULT, 1);
787 put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGHIDDEN , 0);
788 for (i = 0; i < s->nb_chapters; i++) {
789 ebml_master chapteratom, chapterdisplay;
790 AVChapter *c = s->chapters[i];
d2d67e42 791 AVDictionaryEntry *t = NULL;
2bd0758e
AK
792
793 chapteratom = start_ebml_master(pb, MATROSKA_ID_CHAPTERATOM, 0);
794 put_ebml_uint(pb, MATROSKA_ID_CHAPTERUID, c->id);
795 put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMESTART,
796 av_rescale_q(c->start, c->time_base, scale));
797 put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMEEND,
798 av_rescale_q(c->end, c->time_base, scale));
799 put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGHIDDEN , 0);
800 put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGENABLED, 1);
d2d67e42 801 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
2bd0758e
AK
802 chapterdisplay = start_ebml_master(pb, MATROSKA_ID_CHAPTERDISPLAY, 0);
803 put_ebml_string(pb, MATROSKA_ID_CHAPSTRING, t->value);
804 put_ebml_string(pb, MATROSKA_ID_CHAPLANG , "und");
805 end_ebml_master(pb, chapterdisplay);
806 }
807 end_ebml_master(pb, chapteratom);
808 }
809 end_ebml_master(pb, editionentry);
810 end_ebml_master(pb, chapters);
26b241c0
JS
811
812 mkv->wrote_chapters = 1;
2bd0758e
AK
813 return 0;
814}
815
d2d67e42 816static void mkv_write_simpletag(AVIOContext *pb, AVDictionaryEntry *t)
9b75309c
AK
817{
818 uint8_t *key = av_strdup(t->key);
819 uint8_t *p = key;
820 const uint8_t *lang = NULL;
821 ebml_master tag;
822
823 if ((p = strrchr(p, '-')) &&
824 (lang = av_convert_lang_to(p + 1, AV_LANG_ISO639_2_BIBL)))
825 *p = 0;
826
827 p = key;
828 while (*p) {
829 if (*p == ' ')
830 *p = '_';
831 else if (*p >= 'a' && *p <= 'z')
832 *p -= 'a' - 'A';
833 p++;
834 }
835
836 tag = start_ebml_master(pb, MATROSKA_ID_SIMPLETAG, 0);
837 put_ebml_string(pb, MATROSKA_ID_TAGNAME, key);
838 if (lang)
839 put_ebml_string(pb, MATROSKA_ID_TAGLANG, lang);
840 put_ebml_string(pb, MATROSKA_ID_TAGSTRING, t->value);
841 end_ebml_master(pb, tag);
842
843 av_freep(&key);
844}
845
d2d67e42 846static int mkv_write_tag(AVFormatContext *s, AVDictionary *m, unsigned int elementid,
9b75309c
AK
847 unsigned int uid, ebml_master *tags)
848{
849 MatroskaMuxContext *mkv = s->priv_data;
850 ebml_master tag, targets;
d2d67e42 851 AVDictionaryEntry *t = NULL;
9b75309c
AK
852 int ret;
853
854 if (!tags->pos) {
a2704c97 855 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TAGS, avio_tell(s->pb));
9b75309c
AK
856 if (ret < 0) return ret;
857
858 *tags = start_ebml_master(s->pb, MATROSKA_ID_TAGS, 0);
859 }
860
861 tag = start_ebml_master(s->pb, MATROSKA_ID_TAG, 0);
862 targets = start_ebml_master(s->pb, MATROSKA_ID_TAGTARGETS, 0);
863 if (elementid)
864 put_ebml_uint(s->pb, elementid, uid);
865 end_ebml_master(s->pb, targets);
866
d2d67e42 867 while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX)))
0092c1dd
JS
868 if (av_strcasecmp(t->key, "title") &&
869 av_strcasecmp(t->key, "encoding_tool"))
eaa4542b 870 mkv_write_simpletag(s->pb, t);
9b75309c
AK
871
872 end_ebml_master(s->pb, tag);
873 return 0;
874}
875
876static int mkv_write_tags(AVFormatContext *s)
877{
878 ebml_master tags = {0};
879 int i, ret;
880
03700d39
AK
881 ff_metadata_conv_ctx(s, ff_mkv_metadata_conv, NULL);
882
d2d67e42 883 if (av_dict_get(s->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX)) {
9b75309c
AK
884 ret = mkv_write_tag(s, s->metadata, 0, 0, &tags);
885 if (ret < 0) return ret;
886 }
887
888 for (i = 0; i < s->nb_streams; i++) {
889 AVStream *st = s->streams[i];
890
d2d67e42 891 if (!av_dict_get(st->metadata, "", 0, AV_DICT_IGNORE_SUFFIX))
9b75309c
AK
892 continue;
893
894 ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &tags);
895 if (ret < 0) return ret;
896 }
897
898 for (i = 0; i < s->nb_chapters; i++) {
899 AVChapter *ch = s->chapters[i];
900
d2d67e42 901 if (!av_dict_get(ch->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX))
9b75309c
AK
902 continue;
903
904 ret = mkv_write_tag(s, ch->metadata, MATROSKA_ID_TAGTARGETS_CHAPTERUID, ch->id, &tags);
905 if (ret < 0) return ret;
906 }
907
908 if (tags.pos)
909 end_ebml_master(s->pb, tags);
910 return 0;
911}
912
c7a63a52
AK
913static int mkv_write_attachments(AVFormatContext *s)
914{
915 MatroskaMuxContext *mkv = s->priv_data;
916 AVIOContext *pb = s->pb;
917 ebml_master attachments;
918 AVLFG c;
919 int i, ret;
920
921 if (!mkv->have_attachments)
922 return 0;
923
924 av_lfg_init(&c, av_get_random_seed());
925
926 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_ATTACHMENTS, avio_tell(pb));
927 if (ret < 0) return ret;
928
929 attachments = start_ebml_master(pb, MATROSKA_ID_ATTACHMENTS, 0);
930
931 for (i = 0; i < s->nb_streams; i++) {
932 AVStream *st = s->streams[i];
933 ebml_master attached_file;
934 AVDictionaryEntry *t;
935 const char *mimetype = NULL;
936
937 if (st->codec->codec_type != AVMEDIA_TYPE_ATTACHMENT)
938 continue;
939
940 attached_file = start_ebml_master(pb, MATROSKA_ID_ATTACHEDFILE, 0);
941
942 if (t = av_dict_get(st->metadata, "title", NULL, 0))
943 put_ebml_string(pb, MATROSKA_ID_FILEDESC, t->value);
944 if (!(t = av_dict_get(st->metadata, "filename", NULL, 0))) {
945 av_log(s, AV_LOG_ERROR, "Attachment stream %d has no filename tag.\n", i);
946 return AVERROR(EINVAL);
947 }
948 put_ebml_string(pb, MATROSKA_ID_FILENAME, t->value);
949 if (t = av_dict_get(st->metadata, "mimetype", NULL, 0))
950 mimetype = t->value;
36ef5369 951 else if (st->codec->codec_id != AV_CODEC_ID_NONE ) {
c7a63a52 952 int i;
36ef5369 953 for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
c7a63a52
AK
954 if (ff_mkv_mime_tags[i].id == st->codec->codec_id) {
955 mimetype = ff_mkv_mime_tags[i].str;
956 break;
957 }
958 }
959 if (!mimetype) {
960 av_log(s, AV_LOG_ERROR, "Attachment stream %d has no mimetype tag and "
961 "it cannot be deduced from the codec id.\n", i);
962 return AVERROR(EINVAL);
963 }
964
965 put_ebml_string(pb, MATROSKA_ID_FILEMIMETYPE, mimetype);
966 put_ebml_binary(pb, MATROSKA_ID_FILEDATA, st->codec->extradata, st->codec->extradata_size);
967 put_ebml_uint(pb, MATROSKA_ID_FILEUID, av_lfg_get(&c));
968 end_ebml_master(pb, attached_file);
969 }
970 end_ebml_master(pb, attachments);
971
972 return 0;
973}
974
5034ab90
DC
975static int mkv_write_header(AVFormatContext *s)
976{
977 MatroskaMuxContext *mkv = s->priv_data;
ae628ec1 978 AVIOContext *pb = s->pb;
baf71dca 979 ebml_master ebml_header, segment_info;
d2d67e42 980 AVDictionaryEntry *tag;
1f4280e7 981 int ret, i;
5034ab90 982
316d6c15
JZ
983 if (!strcmp(s->oformat->name, "webm")) mkv->mode = MODE_WEBM;
984 else mkv->mode = MODE_MATROSKAv2;
985
84d4e599 986 mkv->tracks = av_mallocz(s->nb_streams * sizeof(*mkv->tracks));
d06735a3
DC
987 if (!mkv->tracks)
988 return AVERROR(ENOMEM);
541d443c 989
baf71dca 990 ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
5034ab90
DC
991 put_ebml_uint (pb, EBML_ID_EBMLVERSION , 1);
992 put_ebml_uint (pb, EBML_ID_EBMLREADVERSION , 1);
993 put_ebml_uint (pb, EBML_ID_EBMLMAXIDLENGTH , 4);
994 put_ebml_uint (pb, EBML_ID_EBMLMAXSIZELENGTH , 8);
316d6c15 995 put_ebml_string (pb, EBML_ID_DOCTYPE , s->oformat->name);
5034ab90
DC
996 put_ebml_uint (pb, EBML_ID_DOCTYPEVERSION , 2);
997 put_ebml_uint (pb, EBML_ID_DOCTYPEREADVERSION , 2);
998 end_ebml_master(pb, ebml_header);
999
baf71dca 1000 mkv->segment = start_ebml_master(pb, MATROSKA_ID_SEGMENT, 0);
a2704c97 1001 mkv->segment_offset = avio_tell(pb);
967d815a 1002
cfde5d18
DC
1003 // we write 2 seek heads - one at the end of the file to point to each
1004 // cluster, and one at the beginning to point to all other level one
1005 // elements (including the seek head at the end of the file), which
1006 // isn't more than 10 elements if we only write one of each other
1007 // currently defined level 1 element
967d815a 1008 mkv->main_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 10);
e7ddafd5 1009 if (!mkv->main_seekhead)
c35de1a1 1010 return AVERROR(ENOMEM);
967d815a 1011
a2704c97 1012 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_INFO, avio_tell(pb));
6d588ecd 1013 if (ret < 0) return ret;
5034ab90 1014
baf71dca 1015 segment_info = start_ebml_master(pb, MATROSKA_ID_INFO, 0);
5034ab90 1016 put_ebml_uint(pb, MATROSKA_ID_TIMECODESCALE, 1000000);
d2d67e42 1017 if ((tag = av_dict_get(s->metadata, "title", NULL, 0)))
5e565998 1018 put_ebml_string(pb, MATROSKA_ID_TITLE, tag->value);
0c1959b0 1019 if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
1f4280e7 1020 uint32_t segment_uid[4];
5150dd53
MR
1021 AVLFG lfg;
1022
1023 av_lfg_init(&lfg, av_get_random_seed());
1024
1f4280e7 1025 for (i = 0; i < 4; i++)
5150dd53 1026 segment_uid[i] = av_lfg_get(&lfg);
1f4280e7 1027
5fd35c6e 1028 put_ebml_string(pb, MATROSKA_ID_MUXINGAPP , LIBAVFORMAT_IDENT);
0092c1dd
JS
1029 if ((tag = av_dict_get(s->metadata, "encoding_tool", NULL, 0)))
1030 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, tag->value);
1031 else
1032 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, LIBAVFORMAT_IDENT);
1f4280e7 1033 put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
5034ab90 1034 }
4b8f58ee 1035
5034ab90
DC
1036 // reserve space for the duration
1037 mkv->duration = 0;
a2704c97 1038 mkv->duration_offset = avio_tell(pb);
5034ab90
DC
1039 put_ebml_void(pb, 11); // assumes double-precision float to be written
1040 end_ebml_master(pb, segment_info);
1041
6d588ecd
DC
1042 ret = mkv_write_tracks(s);
1043 if (ret < 0) return ret;
67143c0f 1044
316d6c15
JZ
1045 if (mkv->mode != MODE_WEBM) {
1046 ret = mkv_write_chapters(s);
1047 if (ret < 0) return ret;
9b75309c
AK
1048
1049 ret = mkv_write_tags(s);
1050 if (ret < 0) return ret;
c7a63a52
AK
1051
1052 ret = mkv_write_attachments(s);
1053 if (ret < 0) return ret;
316d6c15 1054 }
2bd0758e 1055
8978feda 1056 if (!s->pb->seekable)
7a2a4840
DC
1057 mkv_write_seekhead(pb, mkv->main_seekhead);
1058
6364d534
DC
1059 mkv->cues = mkv_start_cues(mkv->segment_offset);
1060 if (mkv->cues == NULL)
0b38843a 1061 return AVERROR(ENOMEM);
6364d534 1062
e3b225a4
AK
1063 if (pb->seekable && mkv->reserve_cues_space) {
1064 mkv->cues_pos = avio_tell(pb);
1065 put_ebml_void(pb, mkv->reserve_cues_space);
1066 }
1067
ac9baa71
JZ
1068 av_init_packet(&mkv->cur_audio_pkt);
1069 mkv->cur_audio_pkt.size = 0;
ac9baa71 1070
b7f2fdde 1071 avio_flush(pb);
98308bd4
LB
1072
1073 // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1074 // after 4k and on a keyframe
1075 if (pb->seekable) {
1076 if (mkv->cluster_time_limit < 0)
1077 mkv->cluster_time_limit = 5000;
1078 if (mkv->cluster_size_limit < 0)
1079 mkv->cluster_size_limit = 5 * 1024 * 1024;
1080 } else {
1081 if (mkv->cluster_time_limit < 0)
1082 mkv->cluster_time_limit = 1000;
1083 if (mkv->cluster_size_limit < 0)
1084 mkv->cluster_size_limit = 32 * 1024;
1085 }
1086
67143c0f
DC
1087 return 0;
1088}
1089
1bfbe8ff 1090static int mkv_blockgroup_size(int pkt_size)
baf71dca 1091{
1bfbe8ff 1092 int size = pkt_size + 4;
0f651e8c 1093 size += ebml_num_size(size);
baf71dca
DC
1094 size += 2; // EBML ID for block and block duration
1095 size += 8; // max size of block duration
0f651e8c 1096 size += ebml_num_size(size);
baf71dca
DC
1097 size += 1; // blockgroup EBML ID
1098 return size;
1099}
1100
b7f4e76d
AJ
1101static int ass_get_duration(const uint8_t *p)
1102{
1103 int sh, sm, ss, sc, eh, em, es, ec;
1104 uint64_t start, end;
1105
1106 if (sscanf(p, "%*[^,],%d:%d:%d%*c%d,%d:%d:%d%*c%d",
1107 &sh, &sm, &ss, &sc, &eh, &em, &es, &ec) != 8)
1108 return 0;
1109 start = 3600000*sh + 60000*sm + 1000*ss + 10*sc;
1110 end = 3600000*eh + 60000*em + 1000*es + 10*ec;
1111 return end - start;
1112}
1113
ae628ec1 1114static int mkv_write_ass_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
b7f4e76d
AJ
1115{
1116 MatroskaMuxContext *mkv = s->priv_data;
b7f4e76d
AJ
1117 int i, layer = 0, max_duration = 0, size, line_size, data_size = pkt->size;
1118 uint8_t *start, *end, *data = pkt->data;
1119 ebml_master blockgroup;
1120 char buffer[2048];
1121
1122 while (data_size) {
1123 int duration = ass_get_duration(data);
1124 max_duration = FFMAX(duration, max_duration);
1125 end = memchr(data, '\n', data_size);
1126 size = line_size = end ? end-data+1 : data_size;
1127 size -= end ? (end[-1]=='\r')+1 : 0;
1128 start = data;
1129 for (i=0; i<3; i++, start++)
1130 if (!(start = memchr(start, ',', size-(start-data))))
1131 return max_duration;
1132 size -= start - data;
1133 sscanf(data, "Dialogue: %d,", &layer);
1134 i = snprintf(buffer, sizeof(buffer), "%"PRId64",%d,",
1c6d2b7d 1135 s->streams[pkt->stream_index]->nb_frames, layer);
b7f4e76d
AJ
1136 size = FFMIN(i+size, sizeof(buffer));
1137 memcpy(buffer+i, start, size-i);
1138
1139 av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
1140 "pts %" PRId64 ", duration %d\n",
a2704c97 1141 avio_tell(pb), size, pkt->pts, duration);
b7f4e76d
AJ
1142 blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(size));
1143 put_ebml_id(pb, MATROSKA_ID_BLOCK);
1144 put_ebml_num(pb, size+4, 0);
77eb5504
AK
1145 avio_w8(pb, 0x80 | (pkt->stream_index + 1)); // this assumes stream_index is less than 126
1146 avio_wb16(pb, pkt->pts - mkv->cluster_pts);
1147 avio_w8(pb, 0);
1148 avio_write(pb, buffer, size);
b7f4e76d
AJ
1149 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
1150 end_ebml_master(pb, blockgroup);
1151
1152 data += line_size;
1153 data_size -= line_size;
1154 }
1155
1156 return max_duration;
1157}
1158
01656fd4
AK
1159static int mkv_strip_wavpack(const uint8_t *src, uint8_t **pdst, int *size)
1160{
1161 uint8_t *dst;
1162 int srclen = *size;
1163 int offset = 0;
1164 int ret;
1165
1166 dst = av_malloc(srclen);
1167 if (!dst)
1168 return AVERROR(ENOMEM);
1169
1170 while (srclen >= WV_HEADER_SIZE) {
1171 WvHeader header;
1172
1173 ret = ff_wv_parse_header(&header, src);
1174 if (ret < 0)
1175 goto fail;
1176 src += WV_HEADER_SIZE;
1177 srclen -= WV_HEADER_SIZE;
1178
1179 if (srclen < header.blocksize) {
1180 ret = AVERROR_INVALIDDATA;
1181 goto fail;
1182 }
1183
1184 if (header.initial) {
1185 AV_WL32(dst + offset, header.samples);
1186 offset += 4;
1187 }
1188 AV_WL32(dst + offset, header.flags);
1189 AV_WL32(dst + offset + 4, header.crc);
1190 offset += 8;
1191
1192 if (!(header.initial && header.final)) {
1193 AV_WL32(dst + offset, header.blocksize);
1194 offset += 4;
1195 }
1196
1197 memcpy(dst + offset, src, header.blocksize);
1198 src += header.blocksize;
1199 srclen -= header.blocksize;
1200 offset += header.blocksize;
1201 }
1202
1203 *pdst = dst;
1204 *size = offset;
1205
1206 return 0;
1207fail:
1208 av_freep(&dst);
1209 return ret;
1210}
1211
ae628ec1 1212static void mkv_write_block(AVFormatContext *s, AVIOContext *pb,
871b641b 1213 unsigned int blockid, AVPacket *pkt, int flags)
95527e06
DC
1214{
1215 MatroskaMuxContext *mkv = s->priv_data;
0a63a676 1216 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
5f8bae8d 1217 uint8_t *data = NULL;
117d8c6d 1218 int offset = 0, size = pkt->size;
84d4e599 1219 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
95527e06 1220
8ffc5f9e
DC
1221 av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
1222 "pts %" PRId64 ", dts %" PRId64 ", duration %d, flags %d\n",
a2704c97 1223 avio_tell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration, flags);
36ef5369 1224 if (codec->codec_id == AV_CODEC_ID_H264 && codec->extradata_size > 0 &&
5f8bae8d
AJ
1225 (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
1226 ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
558b20d7
TW
1227 else if (codec->codec_id == AV_CODEC_ID_HEVC && codec->extradata_size > 6 &&
1228 (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
1229 /* extradata is Annex B, assume the bitstream is too and convert it */
1230 ff_hevc_annexb2mp4_buf(pkt->data, &data, &size, 0, NULL);
01656fd4
AK
1231 else if (codec->codec_id == AV_CODEC_ID_WAVPACK) {
1232 int ret = mkv_strip_wavpack(pkt->data, &data, &size);
1233 if (ret < 0) {
1234 av_log(s, AV_LOG_ERROR, "Error stripping a WavPack packet.\n");
1235 return;
1236 }
1237 } else
5f8bae8d 1238 data = pkt->data;
117d8c6d
LB
1239
1240 if (codec->codec_id == AV_CODEC_ID_PRORES) {
1241 /* Matroska specification requires to remove the first QuickTime atom
1242 */
1243 size -= 8;
1244 offset = 8;
1245 }
1246
95527e06 1247 put_ebml_id(pb, blockid);
5f8bae8d 1248 put_ebml_num(pb, size+4, 0);
77eb5504
AK
1249 avio_w8(pb, 0x80 | (pkt->stream_index + 1)); // this assumes stream_index is less than 126
1250 avio_wb16(pb, ts - mkv->cluster_pts);
1251 avio_w8(pb, flags);
117d8c6d 1252 avio_write(pb, data + offset, size);
5f8bae8d
AJ
1253 if (data != pkt->data)
1254 av_free(data);
95527e06
DC
1255}
1256
2701fd40
AJ
1257static int srt_get_duration(uint8_t **buf)
1258{
1259 int i, duration = 0;
1260
1261 for (i=0; i<2 && !duration; i++) {
1262 int s_hour, s_min, s_sec, s_hsec, e_hour, e_min, e_sec, e_hsec;
1263 if (sscanf(*buf, "%d:%2d:%2d%*1[,.]%3d --> %d:%2d:%2d%*1[,.]%3d",
1264 &s_hour, &s_min, &s_sec, &s_hsec,
1265 &e_hour, &e_min, &e_sec, &e_hsec) == 8) {
1266 s_min += 60*s_hour; e_min += 60*e_hour;
1267 s_sec += 60*s_min; e_sec += 60*e_min;
1268 s_hsec += 1000*s_sec; e_hsec += 1000*e_sec;
1269 duration = e_hsec - s_hsec;
1270 }
1271 *buf += strcspn(*buf, "\n") + 1;
1272 }
1273 return duration;
1274}
1275
ae628ec1 1276static int mkv_write_srt_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
2701fd40
AJ
1277{
1278 ebml_master blockgroup;
1279 AVPacket pkt2 = *pkt;
1280 int64_t duration = srt_get_duration(&pkt2.data);
1281 pkt2.size -= pkt2.data - pkt->data;
1282
1283 blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
1284 mkv_blockgroup_size(pkt2.size));
1285 mkv_write_block(s, pb, MATROSKA_ID_BLOCK, &pkt2, 0);
1286 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
1287 end_ebml_master(pb, blockgroup);
1288
1289 return duration;
1290}
1291
871b641b
DC
1292static void mkv_flush_dynbuf(AVFormatContext *s)
1293{
1294 MatroskaMuxContext *mkv = s->priv_data;
1295 int bufsize;
1296 uint8_t *dyn_buf;
1297
1298 if (!mkv->dyn_bc)
1299 return;
1300
6dc7d80d 1301 bufsize = avio_close_dyn_buf(mkv->dyn_bc, &dyn_buf);
77eb5504 1302 avio_write(s->pb, dyn_buf, bufsize);
871b641b
DC
1303 av_free(dyn_buf);
1304 mkv->dyn_bc = NULL;
1305}
1306
ac9baa71 1307static int mkv_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
67143c0f 1308{
98186e41 1309 MatroskaMuxContext *mkv = s->priv_data;
ae628ec1 1310 AVIOContext *pb = s->pb;
9245c5ca 1311 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
cc947f04 1312 int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
62c24705 1313 int duration = pkt->duration;
6d588ecd 1314 int ret;
84d4e599 1315 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
b1adb69c 1316
654b65d0
DC
1317 if (ts == AV_NOPTS_VALUE) {
1318 av_log(s, AV_LOG_ERROR, "Can't write packet with unknown timestamp\n");
1319 return AVERROR(EINVAL);
1320 }
a1aa37dd 1321 ts += mkv->tracks[pkt->stream_index].ts_offset;
654b65d0 1322
8978feda 1323 if (!s->pb->seekable) {
871b641b 1324 if (!mkv->dyn_bc)
b92c5452 1325 avio_open_dyn_buf(&mkv->dyn_bc);
871b641b
DC
1326 pb = mkv->dyn_bc;
1327 }
1328
30f06a58 1329 if (!mkv->cluster_pos) {
a2704c97 1330 mkv->cluster_pos = avio_tell(s->pb);
baf71dca 1331 mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER, 0);
f9ff7179
DC
1332 put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, FFMAX(0, ts));
1333 mkv->cluster_pts = FFMAX(0, ts);
98186e41
DC
1334 }
1335
72415b2a 1336 if (codec->codec_type != AVMEDIA_TYPE_SUBTITLE) {
871b641b 1337 mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
36ef5369 1338 } else if (codec->codec_id == AV_CODEC_ID_SSA) {
871b641b 1339 duration = mkv_write_ass_blocks(s, pb, pkt);
36ef5369 1340 } else if (codec->codec_id == AV_CODEC_ID_SRT) {
2701fd40 1341 duration = mkv_write_srt_blocks(s, pb, pkt);
663a5d9d 1342 } else {
1bfbe8ff 1343 ebml_master blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(pkt->size));
62c24705 1344 duration = pkt->convergence_duration;
871b641b 1345 mkv_write_block(s, pb, MATROSKA_ID_BLOCK, pkt, 0);
291902c2 1346 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
663a5d9d
DC
1347 end_ebml_master(pb, blockgroup);
1348 }
02f487fc 1349
72415b2a 1350 if (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe) {
84d4e599 1351 ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, ts, mkv->cluster_pos);
6d588ecd 1352 if (ret < 0) return ret;
6364d534
DC
1353 }
1354
ac9baa71
JZ
1355 mkv->duration = FFMAX(mkv->duration, ts + duration);
1356 return 0;
1357}
1358
ac9baa71
JZ
1359static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
1360{
1361 MatroskaMuxContext *mkv = s->priv_data;
148fbdd1
LB
1362 int codec_type = s->streams[pkt->stream_index]->codec->codec_type;
1363 int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1364 int cluster_size;
148fbdd1 1365 int64_t cluster_time;
148fbdd1
LB
1366 AVIOContext *pb;
1367 int ret;
1368
1369 if (mkv->tracks[pkt->stream_index].write_dts)
1370 cluster_time = pkt->dts - mkv->cluster_pts;
1371 else
1372 cluster_time = pkt->pts - mkv->cluster_pts;
a1aa37dd 1373 cluster_time += mkv->tracks[pkt->stream_index].ts_offset;
ac9baa71
JZ
1374
1375 // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1376 // after 4k and on a keyframe
148fbdd1
LB
1377 if (s->pb->seekable) {
1378 pb = s->pb;
1379 cluster_size = avio_tell(pb) - mkv->cluster_pos;
148fbdd1
LB
1380 } else {
1381 pb = mkv->dyn_bc;
1382 cluster_size = avio_tell(pb);
148fbdd1
LB
1383 }
1384
ac9baa71 1385 if (mkv->cluster_pos &&
98308bd4
LB
1386 (cluster_size > mkv->cluster_size_limit ||
1387 cluster_time > mkv->cluster_time_limit ||
148fbdd1
LB
1388 (codec_type == AVMEDIA_TYPE_VIDEO && keyframe &&
1389 cluster_size > 4 * 1024))) {
30f06a58 1390 av_log(s, AV_LOG_DEBUG, "Starting new cluster at offset %" PRIu64
148fbdd1
LB
1391 " bytes, pts %" PRIu64 "dts %" PRIu64 "\n",
1392 avio_tell(pb), pkt->pts, pkt->dts);
30f06a58
DC
1393 end_ebml_master(pb, mkv->cluster);
1394 mkv->cluster_pos = 0;
871b641b
DC
1395 if (mkv->dyn_bc)
1396 mkv_flush_dynbuf(s);
59f59592 1397 avio_flush(s->pb);
30f06a58
DC
1398 }
1399
ac9baa71
JZ
1400 // check if we have an audio packet cached
1401 if (mkv->cur_audio_pkt.size > 0) {
1402 ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
1afddbe5 1403 av_free_packet(&mkv->cur_audio_pkt);
ac9baa71
JZ
1404 if (ret < 0) {
1405 av_log(s, AV_LOG_ERROR, "Could not write cached audio packet ret:%d\n", ret);
1406 return ret;
1407 }
1408 }
1409
1410 // buffer an audio packet to ensure the packet containing the video
1411 // keyframe's timecode is contained in the same cluster for WebM
148fbdd1 1412 if (codec_type == AVMEDIA_TYPE_AUDIO) {
1afddbe5 1413 mkv->cur_audio_pkt = *pkt;
c3e58f8f
RC
1414 if (pkt->buf) {
1415 mkv->cur_audio_pkt.buf = av_buffer_ref(pkt->buf);
1416 ret = mkv->cur_audio_pkt.buf ? 0 : AVERROR(ENOMEM);
1417 } else
1418 ret = av_dup_packet(&mkv->cur_audio_pkt);
1afddbe5 1419 } else
ac9baa71
JZ
1420 ret = mkv_write_packet_internal(s, pkt);
1421 return ret;
67143c0f
DC
1422}
1423
b886f5c2
MS
1424static int mkv_write_flush_packet(AVFormatContext *s, AVPacket *pkt)
1425{
1426 MatroskaMuxContext *mkv = s->priv_data;
1427 AVIOContext *pb;
1428 if (s->pb->seekable)
1429 pb = s->pb;
1430 else
1431 pb = mkv->dyn_bc;
1432 if (!pkt) {
1433 if (mkv->cluster_pos) {
1434 av_log(s, AV_LOG_DEBUG, "Flushing cluster at offset %" PRIu64
1435 " bytes\n", avio_tell(pb));
1436 end_ebml_master(pb, mkv->cluster);
1437 mkv->cluster_pos = 0;
1438 if (mkv->dyn_bc)
1439 mkv_flush_dynbuf(s);
1440 avio_flush(s->pb);
1441 }
1442 return 0;
1443 }
1444 return mkv_write_packet(s, pkt);
1445}
1446
67143c0f
DC
1447static int mkv_write_trailer(AVFormatContext *s)
1448{
1449 MatroskaMuxContext *mkv = s->priv_data;
ae628ec1 1450 AVIOContext *pb = s->pb;
e7ddafd5 1451 int64_t currentpos, cuespos;
9e2a3e22 1452 int ret;
02f487fc 1453
ac9baa71
JZ
1454 // check if we have an audio packet cached
1455 if (mkv->cur_audio_pkt.size > 0) {
1456 ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
1afddbe5 1457 av_free_packet(&mkv->cur_audio_pkt);
ac9baa71
JZ
1458 if (ret < 0) {
1459 av_log(s, AV_LOG_ERROR, "Could not write cached audio packet ret:%d\n", ret);
1460 return ret;
1461 }
1462 }
1463
871b641b
DC
1464 if (mkv->dyn_bc) {
1465 end_ebml_master(mkv->dyn_bc, mkv->cluster);
1466 mkv_flush_dynbuf(s);
1467 } else if (mkv->cluster_pos) {
1468 end_ebml_master(pb, mkv->cluster);
1469 }
02f487fc 1470
26b241c0
JS
1471 if (mkv->mode != MODE_WEBM) {
1472 ret = mkv_write_chapters(s);
1473 if (ret < 0) return ret;
1474 }
1475
8978feda 1476 if (pb->seekable) {
91819763 1477 if (mkv->cues->num_entries) {
e3b225a4
AK
1478 if (mkv->reserve_cues_space) {
1479 int64_t cues_end;
1480
1481 currentpos = avio_tell(pb);
1482 avio_seek(pb, mkv->cues_pos, SEEK_SET);
1483
1484 cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
1485 cues_end = avio_tell(pb);
1486 if (cues_end > cuespos + mkv->reserve_cues_space) {
1487 av_log(s, AV_LOG_ERROR, "Insufficient space reserved for cues: %d "
1488 "(needed: %"PRId64").\n", mkv->reserve_cues_space,
1489 cues_end - cuespos);
1490 return AVERROR(EINVAL);
1491 }
1492
1493 if (cues_end < cuespos + mkv->reserve_cues_space)
1494 put_ebml_void(pb, mkv->reserve_cues_space - (cues_end - cuespos));
1495
1496 avio_seek(pb, currentpos, SEEK_SET);
1497 } else {
1498 cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
1499 }
91819763
AK
1500
1501 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CUES, cuespos);
1502 if (ret < 0) return ret;
1503 }
6364d534 1504
e5c29287
DC
1505 mkv_write_seekhead(pb, mkv->main_seekhead);
1506
1507 // update the duration
1508 av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
a2704c97 1509 currentpos = avio_tell(pb);
6b4aa5da 1510 avio_seek(pb, mkv->duration_offset, SEEK_SET);
e5c29287
DC
1511 put_ebml_float(pb, MATROSKA_ID_DURATION, mkv->duration);
1512
6b4aa5da 1513 avio_seek(pb, currentpos, SEEK_SET);
ac9e1177 1514 }
02f487fc 1515
67143c0f 1516 end_ebml_master(pb, mkv->segment);
84d4e599 1517 av_free(mkv->tracks);
eddd580b
MR
1518 av_freep(&mkv->cues->entries);
1519 av_freep(&mkv->cues);
3b4bb19e 1520
67143c0f
DC
1521 return 0;
1522}
1523
36ef5369 1524static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
15c14ce6
AK
1525{
1526 int i;
36ef5369 1527 for (i = 0; ff_mkv_codec_tags[i].id != AV_CODEC_ID_NONE; i++)
15c14ce6
AK
1528 if (ff_mkv_codec_tags[i].id == codec_id)
1529 return 1;
1530
1531 if (std_compliance < FF_COMPLIANCE_NORMAL) { // mkv theoretically supports any
1532 enum AVMediaType type = avcodec_get_type(codec_id); // video/audio through VFW/ACM
1533 if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)
1534 return 1;
1535 }
1536
1537 return 0;
1538}
1539
e3b225a4
AK
1540#define OFFSET(x) offsetof(MatroskaMuxContext, x)
1541#define FLAGS AV_OPT_FLAG_ENCODING_PARAM
1542static const AVOption options[] = {
98308bd4
LB
1543 { "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 },
1544 { "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 },
1545 { "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 },
e3b225a4
AK
1546 { NULL },
1547};
1548
316d6c15 1549#if CONFIG_MATROSKA_MUXER
e3b225a4
AK
1550static const AVClass matroska_class = {
1551 .class_name = "matroska muxer",
1552 .item_name = av_default_item_name,
1553 .option = options,
1554 .version = LIBAVUTIL_VERSION_INT,
1555};
1556
c6610a21 1557AVOutputFormat ff_matroska_muxer = {
dfc2c4d9 1558 .name = "matroska",
6774247a 1559 .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
dfc2c4d9
AK
1560 .mime_type = "video/x-matroska",
1561 .extensions = "mkv",
1562 .priv_data_size = sizeof(MatroskaMuxContext),
fd487218 1563 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
36ef5369 1564 AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
fd487218 1565 .video_codec = CONFIG_LIBX264_ENCODER ?
36ef5369 1566 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
dfc2c4d9 1567 .write_header = mkv_write_header,
b886f5c2 1568 .write_packet = mkv_write_flush_packet,
dfc2c4d9 1569 .write_trailer = mkv_write_trailer,
e9cef897 1570 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
b886f5c2 1571 AVFMT_TS_NONSTRICT | AVFMT_ALLOW_FLUSH,
20234a4b
MS
1572 .codec_tag = (const AVCodecTag* const []){
1573 ff_codec_bmp_tags, ff_codec_wav_tags, 0
1574 },
36ef5369 1575 .subtitle_codec = AV_CODEC_ID_SSA,
15c14ce6 1576 .query_codec = mkv_query_codec,
e3b225a4 1577 .priv_class = &matroska_class,
67143c0f 1578};
316d6c15
JZ
1579#endif
1580
1581#if CONFIG_WEBM_MUXER
e3b225a4
AK
1582static const AVClass webm_class = {
1583 .class_name = "webm muxer",
1584 .item_name = av_default_item_name,
1585 .option = options,
1586 .version = LIBAVUTIL_VERSION_INT,
1587};
1588
c6610a21 1589AVOutputFormat ff_webm_muxer = {
dfc2c4d9 1590 .name = "webm",
6774247a 1591 .long_name = NULL_IF_CONFIG_SMALL("WebM"),
dfc2c4d9
AK
1592 .mime_type = "video/webm",
1593 .extensions = "webm",
1594 .priv_data_size = sizeof(MatroskaMuxContext),
36ef5369
AK
1595 .audio_codec = AV_CODEC_ID_VORBIS,
1596 .video_codec = AV_CODEC_ID_VP8,
dfc2c4d9 1597 .write_header = mkv_write_header,
b886f5c2 1598 .write_packet = mkv_write_flush_packet,
dfc2c4d9 1599 .write_trailer = mkv_write_trailer,
e9cef897 1600 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
b886f5c2 1601 AVFMT_TS_NONSTRICT | AVFMT_ALLOW_FLUSH,
e3b225a4 1602 .priv_class = &webm_class,
316d6c15
JZ
1603};
1604#endif
55c151ef 1605
316d6c15 1606#if CONFIG_MATROSKA_AUDIO_MUXER
e3b225a4
AK
1607static const AVClass mka_class = {
1608 .class_name = "matroska audio muxer",
1609 .item_name = av_default_item_name,
1610 .option = options,
1611 .version = LIBAVUTIL_VERSION_INT,
1612};
c6610a21 1613AVOutputFormat ff_matroska_audio_muxer = {
dfc2c4d9 1614 .name = "matroska",
6774247a 1615 .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
dfc2c4d9
AK
1616 .mime_type = "audio/x-matroska",
1617 .extensions = "mka",
1618 .priv_data_size = sizeof(MatroskaMuxContext),
fd487218 1619 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
36ef5369
AK
1620 AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
1621 .video_codec = AV_CODEC_ID_NONE,
dfc2c4d9 1622 .write_header = mkv_write_header,
b886f5c2 1623 .write_packet = mkv_write_flush_packet,
dfc2c4d9 1624 .write_trailer = mkv_write_trailer,
b886f5c2
MS
1625 .flags = AVFMT_GLOBALHEADER | AVFMT_TS_NONSTRICT |
1626 AVFMT_ALLOW_FLUSH,
20234a4b 1627 .codec_tag = (const AVCodecTag* const []){ ff_codec_wav_tags, 0 },
e3b225a4 1628 .priv_class = &mka_class,
55c151ef 1629};
316d6c15 1630#endif