matroskaenc: don't warn about unknown spherical metadata when there isn't any
[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"
827a05ea 27#include "avio_internal.h"
0574bc06
AK
28#include "avlanguage.h"
29#include "flacenc.h"
c3f9ebf7 30#include "internal.h"
f009e36f 31#include "isom.h"
67143c0f 32#include "matroska.h"
0574bc06 33#include "riff.h"
106b62f4 34#include "vorbiscomment.h"
01656fd4 35#include "wv.h"
0574bc06
AK
36
37#include "libavutil/avstring.h"
106b62f4 38#include "libavutil/channel_layout.h"
0574bc06 39#include "libavutil/dict.h"
3383a53e 40#include "libavutil/intfloat.h"
0574bc06
AK
41#include "libavutil/intreadwrite.h"
42#include "libavutil/lfg.h"
0ebcdf5c 43#include "libavutil/mathematics.h"
e3b225a4 44#include "libavutil/opt.h"
1f4280e7 45#include "libavutil/random_seed.h"
0574bc06 46#include "libavutil/samplefmt.h"
4d686fb7 47#include "libavutil/stereo3d.h"
827a05ea 48#include "libavutil/spherical.h"
0574bc06 49
245976da 50#include "libavcodec/xiph.h"
7bfacd4e 51#include "libavcodec/mpeg4audio.h"
67143c0f 52
baf71dca 53typedef struct ebml_master {
bc5c918e 54 int64_t pos; ///< absolute offset in the file where the master's elements start
baf71dca
DC
55 int sizebytes; ///< how many bytes were reserved for the size
56} ebml_master;
57
967d815a
DC
58typedef struct mkv_seekhead_entry {
59 unsigned int elementid;
60 uint64_t segmentpos;
61} mkv_seekhead_entry;
62
63typedef struct mkv_seekhead {
bc5c918e
DB
64 int64_t filepos;
65 int64_t segment_offset; ///< the file offset to the beginning of the segment
1b66d314 66 int reserved_size; ///< -1 if appending to file
967d815a
DC
67 int max_entries;
68 mkv_seekhead_entry *entries;
69 int num_entries;
70} mkv_seekhead;
71
daf8cf35 72typedef struct mkv_cuepoint {
6364d534
DC
73 uint64_t pts;
74 int tracknum;
bc5c918e 75 int64_t cluster_pos; ///< file offset of the cluster containing the block
6364d534
DC
76} mkv_cuepoint;
77
daf8cf35 78typedef struct mkv_cues {
bc5c918e 79 int64_t segment_offset;
6364d534
DC
80 mkv_cuepoint *entries;
81 int num_entries;
82} mkv_cues;
83
daf8cf35 84typedef struct mkv_track {
84d4e599 85 int write_dts;
f4bf2363
JA
86 int sample_rate;
87 int64_t sample_rate_offset;
98cae966 88 int64_t codecpriv_offset;
a1aa37dd 89 int64_t ts_offset;
84d4e599
DC
90} mkv_track;
91
316d6c15
JZ
92#define MODE_MATROSKAv2 0x01
93#define MODE_WEBM 0x02
94
67143c0f 95typedef struct MatroskaMuxContext {
e3b225a4 96 const AVClass *class;
316d6c15 97 int mode;
ae628ec1 98 AVIOContext *dyn_bc;
baf71dca 99 ebml_master segment;
bc5c918e 100 int64_t segment_offset;
baf71dca 101 ebml_master cluster;
bc5c918e 102 int64_t cluster_pos; ///< file offset of the current cluster
f9ff7179 103 int64_t cluster_pts;
bc5c918e 104 int64_t duration_offset;
f9ff7179 105 int64_t duration;
967d815a 106 mkv_seekhead *main_seekhead;
6364d534 107 mkv_cues *cues;
84d4e599 108 mkv_track *tracks;
541d443c 109
ac9baa71 110 AVPacket cur_audio_pkt;
c7a63a52
AK
111
112 int have_attachments;
71852a1b 113 int have_video;
e3b225a4
AK
114
115 int reserve_cues_space;
98308bd4 116 int cluster_size_limit;
e3b225a4 117 int64_t cues_pos;
98308bd4 118 int64_t cluster_time_limit;
26b241c0 119 int wrote_chapters;
67143c0f
DC
120} MatroskaMuxContext;
121
baf71dca 122
e3cd80cd
DC
123/** 2 bytes * 3 for EBML IDs, 3 1-byte EBML lengths, 8 bytes for 64 bit
124 * offset, 4 bytes for target EBML ID */
baf71dca
DC
125#define MAX_SEEKENTRY_SIZE 21
126
e3cd80cd
DC
127/** per-cuepoint-track - 3 1-byte EBML IDs, 3 1-byte EBML sizes, 2
128 * 8-byte uint max */
baf71dca
DC
129#define MAX_CUETRACKPOS_SIZE 22
130
e3cd80cd 131/** per-cuepoint - 2 1-byte EBML IDs, 2 1-byte EBML sizes, 8-byte uint max */
f1f6156b 132#define MAX_CUEPOINT_SIZE(num_tracks) 12 + MAX_CUETRACKPOS_SIZE * num_tracks
baf71dca 133
22ccb69a
DC
134static int ebml_id_size(unsigned int id)
135{
f1f6156b 136 return (av_log2(id + 1) - 1) / 7 + 1;
22ccb69a
DC
137}
138
ae628ec1 139static void put_ebml_id(AVIOContext *pb, unsigned int id)
67143c0f 140{
432adc13
DC
141 int i = ebml_id_size(id);
142 while (i--)
f1f6156b 143 avio_w8(pb, id >> (i * 8));
67143c0f
DC
144}
145
ec8f4ad9 146/**
bf898960 147 * Write an EBML size meaning "unknown size".
ec8f4ad9 148 *
bf898960 149 * @param bytes The number of bytes the size should occupy (maximum: 8).
ec8f4ad9 150 */
ae628ec1 151static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
ec8f4ad9 152{
0580a122 153 assert(bytes <= 8);
77eb5504 154 avio_w8(pb, 0x1ff >> bytes);
203cce9a 155 while (--bytes)
77eb5504 156 avio_w8(pb, 0xff);
ec8f4ad9
DC
157}
158
1c73478c 159/**
0f651e8c 160 * Calculate how many bytes are needed to represent a given number in EBML.
1c73478c 161 */
0f651e8c 162static int ebml_num_size(uint64_t num)
1c73478c
DC
163{
164 int bytes = 1;
f1f6156b
LB
165 while ((num + 1) >> bytes * 7)
166 bytes++;
1c73478c
DC
167 return bytes;
168}
169
f0e9f442 170/**
0f651e8c 171 * Write a number in EBML variable length format.
f0e9f442 172 *
0f651e8c 173 * @param bytes The number of bytes that need to be used to write the number.
f0e9f442
DC
174 * If zero, any number of bytes can be used.
175 */
ae628ec1 176static void put_ebml_num(AVIOContext *pb, uint64_t num, int bytes)
67143c0f 177{
0f651e8c 178 int i, needed_bytes = ebml_num_size(num);
67143c0f
DC
179
180 // sizes larger than this are currently undefined in EBML
f1f6156b 181 assert(num < (1ULL << 56) - 1);
ffb880c2 182
f0e9f442
DC
183 if (bytes == 0)
184 // don't care how many bytes are used, so use the min
185 bytes = needed_bytes;
47e08c58
DC
186 // the bytes needed to write the given size would exceed the bytes
187 // that we need to use, so write unknown size. This shouldn't happen.
0580a122 188 assert(bytes >= needed_bytes);
f0e9f442 189
f1f6156b 190 num |= 1ULL << bytes * 7;
ddf16467 191 for (i = bytes - 1; i >= 0; i--)
f1f6156b 192 avio_w8(pb, num >> i * 8);
67143c0f
DC
193}
194
ae628ec1 195static void put_ebml_uint(AVIOContext *pb, unsigned int elementid, uint64_t val)
67143c0f 196{
9f38fd7e 197 int i, bytes = 1;
73260a11 198 uint64_t tmp = val;
f1f6156b
LB
199 while (tmp >>= 8)
200 bytes++;
67143c0f
DC
201
202 put_ebml_id(pb, elementid);
0f651e8c 203 put_ebml_num(pb, bytes, 0);
9f38fd7e 204 for (i = bytes - 1; i >= 0; i--)
f1f6156b 205 avio_w8(pb, val >> i * 8);
67143c0f
DC
206}
207
ae628ec1 208static void put_ebml_float(AVIOContext *pb, unsigned int elementid, double val)
9b6b0c79 209{
9b6b0c79 210 put_ebml_id(pb, elementid);
0f651e8c 211 put_ebml_num(pb, 8, 0);
3383a53e 212 avio_wb64(pb, av_double2int(val));
9b6b0c79
DC
213}
214
ae628ec1 215static void put_ebml_binary(AVIOContext *pb, unsigned int elementid,
4a6bef1f 216 const void *buf, int size)
67143c0f
DC
217{
218 put_ebml_id(pb, elementid);
0f651e8c 219 put_ebml_num(pb, size, 0);
77eb5504 220 avio_write(pb, buf, size);
67143c0f
DC
221}
222
f1f6156b
LB
223static void put_ebml_string(AVIOContext *pb, unsigned int elementid,
224 const char *str)
67143c0f
DC
225{
226 put_ebml_binary(pb, elementid, str, strlen(str));
227}
228
57848e9a 229/**
49bd8e4b 230 * Write a void element of a given size. Useful for reserving space in
cfde5d18 231 * the file to be written to later.
57848e9a 232 *
5045da83 233 * @param size The number of bytes to reserve, which must be at least 2.
57848e9a 234 */
ae628ec1 235static void put_ebml_void(AVIOContext *pb, uint64_t size)
f57b85a5 236{
a2704c97 237 int64_t currentpos = avio_tell(pb);
f57b85a5 238
0580a122 239 assert(size >= 2);
f57b85a5
DC
240
241 put_ebml_id(pb, EBML_ID_VOID);
cfde5d18
DC
242 // we need to subtract the length needed to store the size from the
243 // size we need to reserve so 2 cases, we use 8 bytes to store the
244 // size if possible, 1 byte otherwise
f57b85a5 245 if (size < 10)
f1f6156b 246 put_ebml_num(pb, size - 1, 0);
f57b85a5 247 else
f1f6156b
LB
248 put_ebml_num(pb, size - 9, 8);
249 while (avio_tell(pb) < currentpos + size)
77eb5504 250 avio_w8(pb, 0);
f57b85a5
DC
251}
252
f1f6156b
LB
253static ebml_master start_ebml_master(AVIOContext *pb, unsigned int elementid,
254 uint64_t expectedsize)
67143c0f 255{
0f651e8c 256 int bytes = expectedsize ? ebml_num_size(expectedsize) : 8;
67143c0f 257 put_ebml_id(pb, elementid);
baf71dca 258 put_ebml_size_unknown(pb, bytes);
f1f6156b 259 return (ebml_master) {avio_tell(pb), bytes };
67143c0f
DC
260}
261
ae628ec1 262static void end_ebml_master(AVIOContext *pb, ebml_master master)
67143c0f 263{
a2704c97 264 int64_t pos = avio_tell(pb);
67143c0f 265
6b4aa5da 266 if (avio_seek(pb, master.pos - master.sizebytes, SEEK_SET) < 0)
ac9e1177 267 return;
0f651e8c 268 put_ebml_num(pb, pos - master.pos, master.sizebytes);
6b4aa5da 269 avio_seek(pb, pos, SEEK_SET);
67143c0f
DC
270}
271
ae628ec1 272static void put_xiph_size(AVIOContext *pb, int size)
86be6637
DC
273{
274 int i;
275 for (i = 0; i < size / 255; i++)
77eb5504
AK
276 avio_w8(pb, 255);
277 avio_w8(pb, size % 255);
86be6637
DC
278}
279
57848e9a 280/**
cfde5d18
DC
281 * Initialize a mkv_seekhead element to be ready to index level 1 Matroska
282 * elements. If a maximum number of elements is specified, enough space
283 * will be reserved at the current file location to write a seek head of
284 * that size.
57848e9a 285 *
cfde5d18 286 * @param segment_offset The absolute offset to the position in the file
ab332d01
DC
287 * where the segment begins.
288 * @param numelements The maximum number of elements that will be indexed
cfde5d18 289 * by this seek head, 0 if unlimited.
57848e9a 290 */
f1f6156b
LB
291static mkv_seekhead *mkv_start_seekhead(AVIOContext *pb, int64_t segment_offset,
292 int numelements)
967d815a
DC
293{
294 mkv_seekhead *new_seekhead = av_mallocz(sizeof(mkv_seekhead));
f929ab05 295 if (!new_seekhead)
967d815a
DC
296 return NULL;
297
298 new_seekhead->segment_offset = segment_offset;
299
300 if (numelements > 0) {
a2704c97 301 new_seekhead->filepos = avio_tell(pb);
cfde5d18
DC
302 // 21 bytes max for a seek entry, 10 bytes max for the SeekHead ID
303 // and size, and 3 bytes to guarantee that an EBML void element
304 // will fit afterwards
baf71dca 305 new_seekhead->reserved_size = numelements * MAX_SEEKENTRY_SIZE + 13;
f1f6156b 306 new_seekhead->max_entries = numelements;
967d815a
DC
307 put_ebml_void(pb, new_seekhead->reserved_size);
308 }
309 return new_seekhead;
310}
311
312static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
313{
f369b935 314 int err;
967d815a
DC
315
316 // don't store more elements than we reserved space for
317 if (seekhead->max_entries > 0 && seekhead->max_entries <= seekhead->num_entries)
318 return -1;
319
00a63bfb
AK
320 if ((err = av_reallocp_array(&seekhead->entries, seekhead->num_entries + 1,
321 sizeof(*seekhead->entries))) < 0) {
f369b935
AK
322 seekhead->num_entries = 0;
323 return err;
324 }
967d815a 325
00a63bfb
AK
326 seekhead->entries[seekhead->num_entries].elementid = elementid;
327 seekhead->entries[seekhead->num_entries++].segmentpos = filepos - seekhead->segment_offset;
967d815a 328
967d815a
DC
329 return 0;
330}
331
57848e9a 332/**
cfde5d18
DC
333 * Write the seek head to the file and free it. If a maximum number of
334 * elements was specified to mkv_start_seekhead(), the seek head will
335 * be written at the location reserved for it. Otherwise, it is written
336 * at the current location in the file.
57848e9a 337 *
7a2a4840
DC
338 * @return The file offset where the seekhead was written,
339 * -1 if an error occurred.
57848e9a 340 */
ae628ec1 341static int64_t mkv_write_seekhead(AVIOContext *pb, mkv_seekhead *seekhead)
967d815a 342{
baf71dca 343 ebml_master metaseek, seekentry;
bc5c918e 344 int64_t currentpos;
967d815a
DC
345 int i;
346
a2704c97 347 currentpos = avio_tell(pb);
967d815a 348
44729bc0
MS
349 if (seekhead->reserved_size > 0) {
350 if (avio_seek(pb, seekhead->filepos, SEEK_SET) < 0) {
351 currentpos = -1;
352 goto fail;
353 }
354 }
967d815a 355
baf71dca 356 metaseek = start_ebml_master(pb, MATROSKA_ID_SEEKHEAD, seekhead->reserved_size);
967d815a
DC
357 for (i = 0; i < seekhead->num_entries; i++) {
358 mkv_seekhead_entry *entry = &seekhead->entries[i];
359
baf71dca 360 seekentry = start_ebml_master(pb, MATROSKA_ID_SEEKENTRY, MAX_SEEKENTRY_SIZE);
967d815a
DC
361
362 put_ebml_id(pb, MATROSKA_ID_SEEKID);
0f651e8c 363 put_ebml_num(pb, ebml_id_size(entry->elementid), 0);
967d815a
DC
364 put_ebml_id(pb, entry->elementid);
365
366 put_ebml_uint(pb, MATROSKA_ID_SEEKPOSITION, entry->segmentpos);
367 end_ebml_master(pb, seekentry);
368 }
369 end_ebml_master(pb, metaseek);
370
371 if (seekhead->reserved_size > 0) {
a2704c97 372 uint64_t remaining = seekhead->filepos + seekhead->reserved_size - avio_tell(pb);
967d815a 373 put_ebml_void(pb, remaining);
6b4aa5da 374 avio_seek(pb, currentpos, SEEK_SET);
967d815a
DC
375
376 currentpos = seekhead->filepos;
377 }
44729bc0 378fail:
967d815a
DC
379 av_free(seekhead->entries);
380 av_free(seekhead);
381
382 return currentpos;
383}
384
f1f6156b 385static mkv_cues *mkv_start_cues(int64_t segment_offset)
6364d534
DC
386{
387 mkv_cues *cues = av_mallocz(sizeof(mkv_cues));
f929ab05 388 if (!cues)
6364d534
DC
389 return NULL;
390
391 cues->segment_offset = segment_offset;
392 return cues;
393}
394
84d4e599 395static int mkv_add_cuepoint(mkv_cues *cues, int stream, int64_t ts, int64_t cluster_pos)
6364d534 396{
f369b935 397 int err;
6364d534 398
4ffbe3f3
JG
399 if (ts < 0)
400 return 0;
401
00a63bfb
AK
402 if ((err = av_reallocp_array(&cues->entries, cues->num_entries + 1,
403 sizeof(*cues->entries))) < 0) {
f369b935
AK
404 cues->num_entries = 0;
405 return err;
406 }
6364d534 407
00a63bfb
AK
408 cues->entries[cues->num_entries].pts = ts;
409 cues->entries[cues->num_entries].tracknum = stream + 1;
410 cues->entries[cues->num_entries++].cluster_pos = cluster_pos - cues->segment_offset;
6364d534 411
6364d534
DC
412 return 0;
413}
414
ae628ec1 415static int64_t mkv_write_cues(AVIOContext *pb, mkv_cues *cues, int num_tracks)
6364d534 416{
baf71dca 417 ebml_master cues_element;
bc5c918e 418 int64_t currentpos;
6364d534
DC
419 int i, j;
420
a2704c97 421 currentpos = avio_tell(pb);
baf71dca 422 cues_element = start_ebml_master(pb, MATROSKA_ID_CUES, 0);
6364d534
DC
423
424 for (i = 0; i < cues->num_entries; i++) {
baf71dca 425 ebml_master cuepoint, track_positions;
6364d534
DC
426 mkv_cuepoint *entry = &cues->entries[i];
427 uint64_t pts = entry->pts;
428
baf71dca 429 cuepoint = start_ebml_master(pb, MATROSKA_ID_POINTENTRY, MAX_CUEPOINT_SIZE(num_tracks));
6364d534
DC
430 put_ebml_uint(pb, MATROSKA_ID_CUETIME, pts);
431
432 // put all the entries from different tracks that have the exact same
433 // timestamp into the same CuePoint
434 for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
baf71dca 435 track_positions = start_ebml_master(pb, MATROSKA_ID_CUETRACKPOSITION, MAX_CUETRACKPOS_SIZE);
6364d534
DC
436 put_ebml_uint(pb, MATROSKA_ID_CUETRACK , entry[j].tracknum );
437 put_ebml_uint(pb, MATROSKA_ID_CUECLUSTERPOSITION, entry[j].cluster_pos);
438 end_ebml_master(pb, track_positions);
439 }
440 i += j - 1;
441 end_ebml_master(pb, cuepoint);
442 }
443 end_ebml_master(pb, cues_element);
444
6364d534
DC
445 return currentpos;
446}
447
9200514a 448static int put_xiph_codecpriv(AVFormatContext *s, AVIOContext *pb, AVCodecParameters *par)
56d55a3b 449{
56d55a3b
DC
450 uint8_t *header_start[3];
451 int header_len[3];
452 int first_header_size;
86be6637 453 int j;
56d55a3b 454
9200514a 455 if (par->codec_id == AV_CODEC_ID_VORBIS)
56d55a3b
DC
456 first_header_size = 30;
457 else
458 first_header_size = 42;
459
9200514a 460 if (avpriv_split_xiph_headers(par->extradata, par->extradata_size,
56d55a3b 461 first_header_size, header_start, header_len) < 0) {
b62a33d0 462 av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
56d55a3b
DC
463 return -1;
464 }
465
77eb5504 466 avio_w8(pb, 2); // number packets - 1
56d55a3b 467 for (j = 0; j < 2; j++) {
86be6637 468 put_xiph_size(pb, header_len[j]);
56d55a3b
DC
469 }
470 for (j = 0; j < 3; j++)
77eb5504 471 avio_write(pb, header_start[j], header_len[j]);
801edb42
DC
472
473 return 0;
56d55a3b 474}
67143c0f 475
9200514a 476static int put_wv_codecpriv(AVIOContext *pb, AVCodecParameters *par)
01656fd4 477{
9200514a
AK
478 if (par->extradata && par->extradata_size == 2)
479 avio_write(pb, par->extradata, 2);
01656fd4
AK
480 else
481 avio_wl16(pb, 0x403); // fallback to the version mentioned in matroska specs
482 return 0;
483}
484
106b62f4 485static int put_flac_codecpriv(AVFormatContext *s,
9200514a 486 AVIOContext *pb, AVCodecParameters *par)
106b62f4 487{
9200514a
AK
488 int write_comment = (par->channel_layout &&
489 !(par->channel_layout & ~0x3ffffULL) &&
490 !ff_flac_is_native_layout(par->channel_layout));
491 int ret = ff_flac_write_header(pb, par->extradata, par->extradata_size,
e19d48df 492 !write_comment);
106b62f4
AK
493
494 if (ret < 0)
495 return ret;
496
497 if (write_comment) {
498 const char *vendor = (s->flags & AVFMT_FLAG_BITEXACT) ?
499 "Libav" : LIBAVFORMAT_IDENT;
500 AVDictionary *dict = NULL;
501 uint8_t buf[32], *data, *p;
502 int len;
503
9200514a 504 snprintf(buf, sizeof(buf), "0x%"PRIx64, par->channel_layout);
106b62f4
AK
505 av_dict_set(&dict, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", buf, 0);
506
507 len = ff_vorbiscomment_length(dict, vendor);
508 data = av_malloc(len + 4);
509 if (!data) {
510 av_dict_free(&dict);
511 return AVERROR(ENOMEM);
512 }
513
514 data[0] = 0x84;
515 AV_WB24(data + 1, len);
516
517 p = data + 4;
518 ff_vorbiscomment_write(&p, &dict, vendor);
519
520 avio_write(pb, data, len + 4);
521
522 av_freep(&data);
523 av_dict_free(&dict);
524 }
525
526 return 0;
527}
528
f4bf2363 529static int get_aac_sample_rates(AVFormatContext *s, uint8_t *extradata, int extradata_size,
51da7d02 530 int *sample_rate, int *output_sample_rate)
07918a22 531{
bc17bd90 532 MPEG4AudioConfig mp4ac;
f4bf2363 533 int ret;
07918a22 534
f4bf2363
JA
535 ret = avpriv_mpeg4audio_get_config(&mp4ac, extradata,
536 extradata_size * 8, 1);
537 /* Don't abort if the failure is because of missing extradata. Assume in that
538 * case a bitstream filter will provide the muxer with the extradata in the
539 * first packet.
540 * Abort however if s->pb is not seekable, as we would not be able to seek back
541 * to write the sample rate elements once the extradata shows up, anyway. */
542 if (ret < 0 && (extradata_size || !(s->pb->seekable & AVIO_SEEKABLE_NORMAL))) {
51da7d02 543 av_log(s, AV_LOG_ERROR,
f1f6156b 544 "Error parsing AAC extradata, unable to determine samplerate.\n");
51da7d02 545 return AVERROR(EINVAL);
07918a22
DC
546 }
547
f4bf2363
JA
548 if (ret < 0) {
549 /* This will only happen when this function is called while writing the
550 * header and no extradata is available. The space for this element has
551 * to be reserved for when this function is called again after the
552 * extradata shows up in the first packet, as there's no way to know if
553 * output_sample_rate will be different than sample_rate or not. */
554 *output_sample_rate = *sample_rate;
555 } else {
556 *sample_rate = mp4ac.sample_rate;
557 *output_sample_rate = mp4ac.ext_sample_rate;
558 }
51da7d02 559 return 0;
07918a22
DC
560}
561
b75a1f98 562static int mkv_write_native_codecprivate(AVFormatContext *s,
9200514a 563 AVCodecParameters *par,
b75a1f98
LB
564 AVIOContext *dyn_cp)
565{
9200514a 566 switch (par->codec_id) {
b75a1f98
LB
567 case AV_CODEC_ID_VORBIS:
568 case AV_CODEC_ID_THEORA:
9200514a 569 return put_xiph_codecpriv(s, dyn_cp, par);
b75a1f98 570 case AV_CODEC_ID_FLAC:
9200514a 571 return put_flac_codecpriv(s, dyn_cp, par);
b75a1f98 572 case AV_CODEC_ID_WAVPACK:
9200514a 573 return put_wv_codecpriv(dyn_cp, par);
b75a1f98 574 case AV_CODEC_ID_H264:
9200514a
AK
575 return ff_isom_write_avcc(dyn_cp, par->extradata,
576 par->extradata_size);
b75a1f98 577 case AV_CODEC_ID_HEVC:
9200514a
AK
578 return ff_isom_write_hvcc(dyn_cp, par->extradata,
579 par->extradata_size, 0);
b75a1f98 580 case AV_CODEC_ID_ALAC:
9200514a 581 if (par->extradata_size < 36) {
b75a1f98
LB
582 av_log(s, AV_LOG_ERROR,
583 "Invalid extradata found, ALAC expects a 36-byte "
584 "QuickTime atom.");
585 return AVERROR_INVALIDDATA;
586 } else
9200514a
AK
587 avio_write(dyn_cp, par->extradata + 12,
588 par->extradata_size - 12);
b75a1f98
LB
589 break;
590 default:
9200514a
AK
591 if (par->extradata_size)
592 avio_write(dyn_cp, par->extradata, par->extradata_size);
b75a1f98
LB
593 }
594
595 return 0;
596}
597
f1f6156b 598static int mkv_write_codecprivate(AVFormatContext *s, AVIOContext *pb,
9200514a
AK
599 AVCodecParameters *par,
600 int native_id, int qt_id)
5c559894 601{
ae628ec1 602 AVIOContext *dyn_cp;
46d18a88 603 uint8_t *codecpriv;
899681cd 604 int ret, codecpriv_size;
46d18a88 605
b92c5452 606 ret = avio_open_dyn_buf(&dyn_cp);
f1f6156b 607 if (ret < 0)
899681cd 608 return ret;
5c559894
DC
609
610 if (native_id) {
9200514a
AK
611 ret = mkv_write_native_codecprivate(s, par, dyn_cp);
612 } else if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
f009e36f 613 if (qt_id) {
9200514a
AK
614 if (!par->codec_tag)
615 par->codec_tag = ff_codec_get_tag(ff_codec_movvideo_tags,
616 par->codec_id);
617 if (par->extradata_size)
618 avio_write(dyn_cp, par->extradata, par->extradata_size);
f009e36f 619 } else {
9200514a
AK
620 if (!par->codec_tag)
621 par->codec_tag = ff_codec_get_tag(ff_codec_bmp_tags,
622 par->codec_id);
623 if (!par->codec_tag) {
f75ab7a6 624 av_log(s, AV_LOG_ERROR, "No bmp codec ID found.\n");
434a70b8
DC
625 ret = -1;
626 }
5c559894 627
9200514a 628 ff_put_bmp_header(dyn_cp, par, ff_codec_bmp_tags, 0);
f009e36f 629 }
9200514a 630 } else if (par->codec_type == AVMEDIA_TYPE_AUDIO) {
4896dd57 631 unsigned int tag;
9200514a 632 tag = ff_codec_get_tag(ff_codec_wav_tags, par->codec_id);
4896dd57 633 if (!tag) {
f75ab7a6 634 av_log(s, AV_LOG_ERROR, "No wav codec ID found.\n");
46d18a88 635 ret = -1;
5c559894 636 }
9200514a
AK
637 if (!par->codec_tag)
638 par->codec_tag = tag;
5c559894 639
9200514a 640 ff_put_wav_header(s, dyn_cp, par);
5c559894 641 }
46d18a88 642
6dc7d80d 643 codecpriv_size = avio_close_dyn_buf(dyn_cp, &codecpriv);
46d18a88 644 if (codecpriv_size)
f1f6156b
LB
645 put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codecpriv,
646 codecpriv_size);
46d18a88
DC
647 av_free(codecpriv);
648 return ret;
5c559894
DC
649}
650
827a05ea
JA
651static int mkv_write_video_projection(AVFormatContext *s, AVIOContext *pb,
652 AVStream *st)
653{
654 AVIOContext b;
655 AVIOContext *dyn_cp;
656 int side_data_size = 0;
657 int ret, projection_size;
658 uint8_t *projection_ptr;
659 uint8_t private[20];
660
661 const AVSphericalMapping *spherical =
662 (const AVSphericalMapping *)av_stream_get_side_data(st, AV_PKT_DATA_SPHERICAL,
663 &side_data_size);
664
bee89ed3 665 if (!side_data_size)
827a05ea 666 return 0;
827a05ea
JA
667
668 ret = avio_open_dyn_buf(&dyn_cp);
669 if (ret < 0)
670 return ret;
671
672 switch (spherical->projection) {
673 case AV_SPHERICAL_EQUIRECTANGULAR:
674 put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONTYPE,
675 MATROSKA_VIDEO_PROJECTION_TYPE_EQUIRECTANGULAR);
676 break;
677 case AV_SPHERICAL_EQUIRECTANGULAR_TILE:
678 ffio_init_context(&b, private, 20, 1, NULL, NULL, NULL, NULL);
679 put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONTYPE,
680 MATROSKA_VIDEO_PROJECTION_TYPE_EQUIRECTANGULAR);
681 avio_wb32(&b, 0); // version + flags
682 avio_wb32(&b, spherical->bound_top);
683 avio_wb32(&b, spherical->bound_bottom);
684 avio_wb32(&b, spherical->bound_left);
685 avio_wb32(&b, spherical->bound_right);
686 put_ebml_binary(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONPRIVATE,
d32d59bc 687 private, avio_tell(&b));
827a05ea
JA
688 break;
689 case AV_SPHERICAL_CUBEMAP:
690 ffio_init_context(&b, private, 12, 1, NULL, NULL, NULL, NULL);
691 put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONTYPE,
692 MATROSKA_VIDEO_PROJECTION_TYPE_CUBEMAP);
693 avio_wb32(&b, 0); // version + flags
694 avio_wb32(&b, 0); // layout
695 avio_wb32(&b, spherical->padding);
696 put_ebml_binary(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONPRIVATE,
d32d59bc 697 private, avio_tell(&b));
827a05ea
JA
698 break;
699 default:
700 av_log(s, AV_LOG_WARNING, "Unknown projection type\n");
701 goto end;
702 }
703
704 if (spherical->yaw)
705 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONPOSEYAW,
706 (double) spherical->yaw / (1 << 16));
707 if (spherical->pitch)
708 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONPOSEPITCH,
709 (double) spherical->pitch / (1 << 16));
710 if (spherical->roll)
711 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONPOSEROLL,
712 (double) spherical->roll / (1 << 16));
713
714end:
715 projection_size = avio_close_dyn_buf(dyn_cp, &projection_ptr);
716 if (projection_size) {
717 ebml_master projection = start_ebml_master(pb,
718 MATROSKA_ID_VIDEOPROJECTION,
719 projection_size);
720 avio_write(pb, projection_ptr, projection_size);
721 end_ebml_master(pb, projection);
722 }
723 av_freep(&projection_ptr);
724
725 return 0;
726}
727
e3453fd4
LB
728static void mkv_write_field_order(AVIOContext *pb,
729 enum AVFieldOrder field_order)
730{
731 switch (field_order) {
732 case AV_FIELD_UNKNOWN:
733 put_ebml_uint(pb, MATROSKA_ID_VIDEOFLAGINTERLACED,
734 MATROSKA_VIDEO_INTERLACE_FLAG_UNDETERMINED);
735 break;
736 case AV_FIELD_PROGRESSIVE:
737 put_ebml_uint(pb, MATROSKA_ID_VIDEOFLAGINTERLACED,
738 MATROSKA_VIDEO_INTERLACE_FLAG_PROGRESSIVE);
739 break;
740 case AV_FIELD_TT:
741 case AV_FIELD_BB:
742 case AV_FIELD_TB:
743 case AV_FIELD_BT:
744 put_ebml_uint(pb, MATROSKA_ID_VIDEOFLAGINTERLACED,
745 MATROSKA_VIDEO_INTERLACE_FLAG_INTERLACED);
746 switch (field_order) {
747 case AV_FIELD_TT:
748 put_ebml_uint(pb, MATROSKA_ID_VIDEOFIELDORDER,
749 MATROSKA_VIDEO_FIELDORDER_TT);
750 break;
751 case AV_FIELD_BB:
752 put_ebml_uint(pb, MATROSKA_ID_VIDEOFIELDORDER,
753 MATROSKA_VIDEO_FIELDORDER_BB);
754 break;
755 case AV_FIELD_TB:
756 put_ebml_uint(pb, MATROSKA_ID_VIDEOFIELDORDER,
757 MATROSKA_VIDEO_FIELDORDER_TB);
758 break;
759 case AV_FIELD_BT:
760 put_ebml_uint(pb, MATROSKA_ID_VIDEOFIELDORDER,
761 MATROSKA_VIDEO_FIELDORDER_BT);
762 break;
763 }
764 }
765}
766
4d686fb7
VG
767static int mkv_write_stereo_mode(AVFormatContext *s, AVIOContext *pb,
768 AVStream *st, int mode)
48e64324 769{
4d686fb7 770 int i;
090c67d5
VG
771 int display_width, display_height;
772 int h_width = 1, h_height = 1;
9200514a 773 AVCodecParameters *par = st->codecpar;
4d686fb7
VG
774 AVDictionaryEntry *tag;
775 MatroskaVideoStereoModeType format = MATROSKA_VIDEO_STEREOMODE_TYPE_NB;
776
777 // convert metadata into proper side data and add it to the stream
778 if ((tag = av_dict_get(s->metadata, "stereo_mode", NULL, 0))) {
779 int stereo_mode = atoi(tag->value);
780 if (stereo_mode < MATROSKA_VIDEO_STEREOMODE_TYPE_NB &&
781 stereo_mode != 10 && stereo_mode != 12) {
782 int ret = ff_mkv_stereo3d_conv(st, stereo_mode);
783 if (ret < 0)
784 return ret;
785 }
786 }
48e64324 787
090c67d5 788 // iterate to find the stereo3d side data
4d686fb7
VG
789 for (i = 0; i < st->nb_side_data; i++) {
790 AVPacketSideData sd = st->side_data[i];
791 if (sd.type == AV_PKT_DATA_STEREO3D) {
792 AVStereo3D *stereo = (AVStereo3D *)sd.data;
793
794 switch (stereo->type) {
795 case AV_STEREO3D_2D:
796 format = MATROSKA_VIDEO_STEREOMODE_TYPE_MONO;
797 break;
798 case AV_STEREO3D_SIDEBYSIDE:
799 format = (stereo->flags & AV_STEREO3D_FLAG_INVERT)
800 ? MATROSKA_VIDEO_STEREOMODE_TYPE_RIGHT_LEFT
801 : MATROSKA_VIDEO_STEREOMODE_TYPE_LEFT_RIGHT;
090c67d5 802 h_width = 2;
4d686fb7
VG
803 break;
804 case AV_STEREO3D_TOPBOTTOM:
805 format = MATROSKA_VIDEO_STEREOMODE_TYPE_TOP_BOTTOM;
806 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
807 format--;
090c67d5 808 h_height = 2;
4d686fb7
VG
809 break;
810 case AV_STEREO3D_CHECKERBOARD:
811 format = MATROSKA_VIDEO_STEREOMODE_TYPE_CHECKERBOARD_LR;
812 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
813 format--;
814 break;
815 case AV_STEREO3D_LINES:
816 format = MATROSKA_VIDEO_STEREOMODE_TYPE_ROW_INTERLEAVED_LR;
817 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
818 format--;
090c67d5 819 h_height = 2;
4d686fb7
VG
820 break;
821 case AV_STEREO3D_COLUMNS:
822 format = MATROSKA_VIDEO_STEREOMODE_TYPE_COL_INTERLEAVED_LR;
823 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
824 format--;
090c67d5 825 h_width = 2;
4d686fb7
VG
826 break;
827 case AV_STEREO3D_FRAMESEQUENCE:
828 format = MATROSKA_VIDEO_STEREOMODE_TYPE_BOTH_EYES_BLOCK_LR;
829 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
830 format++;
831 break;
832 }
833
834 break;
835 }
48e64324
LB
836 }
837
090c67d5 838 // if webm, do not write unsupported modes
4d686fb7
VG
839 if (mode == MODE_WEBM &&
840 (format > MATROSKA_VIDEO_STEREOMODE_TYPE_TOP_BOTTOM &&
841 format != MATROSKA_VIDEO_STEREOMODE_TYPE_RIGHT_LEFT))
842 format = MATROSKA_VIDEO_STEREOMODE_TYPE_NB;
843
090c67d5 844 // write StereoMode if format is valid
4d686fb7
VG
845 if (format < MATROSKA_VIDEO_STEREOMODE_TYPE_NB)
846 put_ebml_uint(pb, MATROSKA_ID_VIDEOSTEREOMODE, format);
847
090c67d5
VG
848 // write DisplayWidth and DisplayHeight, they contain the size of
849 // a single source view and/or the display aspect ratio
9200514a
AK
850 display_width = par->width / h_width;
851 display_height = par->height / h_height;
090c67d5
VG
852 if (st->sample_aspect_ratio.num) {
853 display_width *= av_q2d(st->sample_aspect_ratio);
854 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYUNIT, 3); // DAR
855 }
856 if (st->sample_aspect_ratio.num ||
857 format < MATROSKA_VIDEO_STEREOMODE_TYPE_NB) {
858 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH, display_width);
859 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, display_height);
860 }
861
4d686fb7 862 return 0;
48e64324
LB
863}
864
b75a1f98
LB
865static int mkv_write_track(AVFormatContext *s, MatroskaMuxContext *mkv,
866 int i, AVIOContext *pb)
67143c0f 867{
b75a1f98 868 AVStream *st = s->streams[i];
9200514a 869 AVCodecParameters *par = st->codecpar;
b75a1f98
LB
870 ebml_master subinfo, track;
871 int native_id = 0;
872 int qt_id = 0;
9200514a
AK
873 int bit_depth = av_get_bits_per_sample(par->codec_id);
874 int sample_rate = par->sample_rate;
b75a1f98
LB
875 int output_sample_rate = 0;
876 int j, ret;
877 AVDictionaryEntry *tag;
878
879 // ms precision is the de-facto standard timescale for mkv files
880 avpriv_set_pts_info(st, 64, 1, 1000);
881
9200514a 882 if (par->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
b75a1f98
LB
883 mkv->have_attachments = 1;
884 return 0;
885 }
67143c0f 886
b75a1f98 887 if (!bit_depth)
9200514a 888 bit_depth = av_get_bytes_per_sample(par->format) << 3;
967d815a 889
9200514a 890 if (par->codec_id == AV_CODEC_ID_AAC) {
f4bf2363
JA
891 ret = get_aac_sample_rates(s, par->extradata, par->extradata_size, &sample_rate,
892 &output_sample_rate);
51da7d02
AK
893 if (ret < 0)
894 return ret;
895 }
c7a63a52 896
b75a1f98
LB
897 track = start_ebml_master(pb, MATROSKA_ID_TRACKENTRY, 0);
898 put_ebml_uint (pb, MATROSKA_ID_TRACKNUMBER , i + 1);
899 put_ebml_uint (pb, MATROSKA_ID_TRACKUID , i + 1);
900 put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0); // no lacing (yet)
a6da1aa0 901
b75a1f98
LB
902 if ((tag = av_dict_get(st->metadata, "title", NULL, 0)))
903 put_ebml_string(pb, MATROSKA_ID_TRACKNAME, tag->value);
904 tag = av_dict_get(st->metadata, "language", NULL, 0);
905 put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag ? tag->value:"und");
f622c4f4 906
b75a1f98
LB
907 // The default value for TRACKFLAGDEFAULT is 1, so add element
908 // if we need to clear it.
909 if (!(st->disposition & AV_DISPOSITION_DEFAULT))
910 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGDEFAULT, !!(st->disposition & AV_DISPOSITION_DEFAULT));
da7e5619
JS
911 if (st->disposition & AV_DISPOSITION_FORCED)
912 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGFORCED, !!(st->disposition & AV_DISPOSITION_FORCED));
f622c4f4 913
9200514a
AK
914 if (par->codec_type == AVMEDIA_TYPE_AUDIO && par->initial_padding) {
915 mkv->tracks[i].ts_offset = av_rescale_q(par->initial_padding,
916 (AVRational){ 1, par->sample_rate },
b75a1f98 917 st->time_base);
f622c4f4 918
b75a1f98 919 put_ebml_uint(pb, MATROSKA_ID_CODECDELAY,
9200514a
AK
920 av_rescale_q(par->initial_padding,
921 (AVRational){ 1, par->sample_rate },
b75a1f98
LB
922 (AVRational){ 1, 1000000000 }));
923 }
924
925 // look for a codec ID string specific to mkv to use,
926 // if none are found, use AVI codes
927 for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
9200514a 928 if (ff_mkv_codec_tags[j].id == par->codec_id) {
b75a1f98
LB
929 put_ebml_string(pb, MATROSKA_ID_CODECID, ff_mkv_codec_tags[j].str);
930 native_id = 1;
931 break;
932 }
933 }
90c2295b 934
9200514a
AK
935 if (mkv->mode == MODE_WEBM && !(par->codec_id == AV_CODEC_ID_VP8 ||
936 par->codec_id == AV_CODEC_ID_VP9 ||
937 par->codec_id == AV_CODEC_ID_OPUS ||
938 par->codec_id == AV_CODEC_ID_VORBIS)) {
b75a1f98
LB
939 av_log(s, AV_LOG_ERROR,
940 "Only VP8 or VP9 video and Vorbis or Opus audio are supported for WebM.\n");
941 return AVERROR(EINVAL);
942 }
a1aa37dd 943
9200514a 944 switch (par->codec_type) {
b75a1f98 945 case AVMEDIA_TYPE_VIDEO:
71852a1b 946 mkv->have_video = 1;
b75a1f98
LB
947 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_VIDEO);
948 if (st->avg_frame_rate.num > 0 && st->avg_frame_rate.den > 0)
949 put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, 1E9 / av_q2d(st->avg_frame_rate));
950
951 if (!native_id &&
9200514a
AK
952 ff_codec_get_tag(ff_codec_movvideo_tags, par->codec_id) &&
953 (!ff_codec_get_tag(ff_codec_bmp_tags, par->codec_id) ||
954 par->codec_id == AV_CODEC_ID_SVQ1 ||
955 par->codec_id == AV_CODEC_ID_SVQ3 ||
956 par->codec_id == AV_CODEC_ID_CINEPAK))
b75a1f98
LB
957 qt_id = 1;
958
959 if (qt_id)
960 put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");
961 else if (!native_id) {
962 // if there is no mkv-specific codec ID, use VFW mode
963 put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");
964 mkv->tracks[i].write_dts = 1;
a1aa37dd
AK
965 }
966
b75a1f98 967 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
e3453fd4 968
9200514a
AK
969 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , par->width);
970 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, par->height);
4d686fb7 971
e3453fd4
LB
972 mkv_write_field_order(pb, par->field_order);
973
4d686fb7
VG
974 // check both side data and metadata for stereo information,
975 // write the result to the bitstream if any is found
976 ret = mkv_write_stereo_mode(s, pb, st, mkv->mode);
977 if (ret < 0)
978 return ret;
827a05ea
JA
979 ret = mkv_write_video_projection(s, pb, st);
980 if (ret < 0)
981 return ret;
4d686fb7 982
b75a1f98
LB
983 end_ebml_master(pb, subinfo);
984 break;
985
986 case AVMEDIA_TYPE_AUDIO:
987 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_AUDIO);
988
989 if (!native_id)
990 // no mkv-specific ID, use ACM mode
991 put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");
992
993 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);
9200514a 994 put_ebml_uint (pb, MATROSKA_ID_AUDIOCHANNELS , par->channels);
f4bf2363
JA
995
996 mkv->tracks[i].sample_rate_offset = avio_tell(pb);
b75a1f98
LB
997 put_ebml_float (pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, sample_rate);
998 if (output_sample_rate)
999 put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
1000 if (bit_depth)
1001 put_ebml_uint(pb, MATROSKA_ID_AUDIOBITDEPTH, bit_depth);
1002 end_ebml_master(pb, subinfo);
1003 break;
1004
1005 case AVMEDIA_TYPE_SUBTITLE:
1006 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_SUBTITLE);
1007 if (!native_id) {
9200514a 1008 av_log(s, AV_LOG_ERROR, "Subtitle codec %d is not supported.\n", par->codec_id);
b75a1f98
LB
1009 return AVERROR(ENOSYS);
1010 }
1011 break;
1012 default:
1013 av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.\n");
1014 break;
1015 }
f4bf2363 1016
98cae966 1017 mkv->tracks[i].codecpriv_offset = avio_tell(pb);
9200514a 1018 ret = mkv_write_codecprivate(s, pb, par, native_id, qt_id);
b75a1f98
LB
1019 if (ret < 0)
1020 return ret;
316d6c15 1021
b75a1f98 1022 end_ebml_master(pb, track);
c301d5ae 1023
b75a1f98
LB
1024 return 0;
1025}
f1f6156b 1026
b75a1f98
LB
1027static int mkv_write_tracks(AVFormatContext *s)
1028{
1029 MatroskaMuxContext *mkv = s->priv_data;
1030 AVIOContext *pb = s->pb;
1031 ebml_master tracks;
1032 int i, ret;
f1f6156b 1033
b75a1f98
LB
1034 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TRACKS, avio_tell(pb));
1035 if (ret < 0)
1036 return ret;
1037
1038 tracks = start_ebml_master(pb, MATROSKA_ID_TRACKS, 0);
1039 for (i = 0; i < s->nb_streams; i++) {
1040 ret = mkv_write_track(s, mkv, i, pb);
f1f6156b
LB
1041 if (ret < 0)
1042 return ret;
67143c0f
DC
1043 }
1044 end_ebml_master(pb, tracks);
801edb42 1045 return 0;
5034ab90
DC
1046}
1047
2bd0758e
AK
1048static int mkv_write_chapters(AVFormatContext *s)
1049{
1050 MatroskaMuxContext *mkv = s->priv_data;
ae628ec1 1051 AVIOContext *pb = s->pb;
2bd0758e
AK
1052 ebml_master chapters, editionentry;
1053 AVRational scale = {1, 1E9};
1054 int i, ret;
1055
26b241c0 1056 if (!s->nb_chapters || mkv->wrote_chapters)
2bd0758e
AK
1057 return 0;
1058
a2704c97 1059 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CHAPTERS, avio_tell(pb));
2bd0758e
AK
1060 if (ret < 0) return ret;
1061
1062 chapters = start_ebml_master(pb, MATROSKA_ID_CHAPTERS , 0);
1063 editionentry = start_ebml_master(pb, MATROSKA_ID_EDITIONENTRY, 0);
1064 put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGDEFAULT, 1);
1065 put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGHIDDEN , 0);
1066 for (i = 0; i < s->nb_chapters; i++) {
1067 ebml_master chapteratom, chapterdisplay;
1068 AVChapter *c = s->chapters[i];
9272c965
VG
1069 int64_t chapterstart = av_rescale_q(c->start, c->time_base, scale);
1070 int64_t chapterend = av_rescale_q(c->end, c->time_base, scale);
d2d67e42 1071 AVDictionaryEntry *t = NULL;
9f25a109 1072 if (chapterstart < 0 || chapterstart > chapterend || chapterend < 0) {
9272c965
VG
1073 av_log(s, AV_LOG_ERROR,
1074 "Invalid chapter start (%"PRId64") or end (%"PRId64").\n",
9f25a109 1075 chapterstart, chapterend);
5dc47a2b 1076 return AVERROR_INVALIDDATA;
9f25a109 1077 }
2bd0758e
AK
1078
1079 chapteratom = start_ebml_master(pb, MATROSKA_ID_CHAPTERATOM, 0);
1080 put_ebml_uint(pb, MATROSKA_ID_CHAPTERUID, c->id);
5dc47a2b
VG
1081 put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMESTART, chapterstart);
1082 put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMEEND, chapterend);
2bd0758e
AK
1083 put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGHIDDEN , 0);
1084 put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGENABLED, 1);
d2d67e42 1085 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
2bd0758e
AK
1086 chapterdisplay = start_ebml_master(pb, MATROSKA_ID_CHAPTERDISPLAY, 0);
1087 put_ebml_string(pb, MATROSKA_ID_CHAPSTRING, t->value);
1088 put_ebml_string(pb, MATROSKA_ID_CHAPLANG , "und");
1089 end_ebml_master(pb, chapterdisplay);
1090 }
1091 end_ebml_master(pb, chapteratom);
1092 }
1093 end_ebml_master(pb, editionentry);
1094 end_ebml_master(pb, chapters);
26b241c0
JS
1095
1096 mkv->wrote_chapters = 1;
2bd0758e
AK
1097 return 0;
1098}
1099
b1306823 1100static int mkv_write_simpletag(AVIOContext *pb, AVDictionaryEntry *t)
9b75309c
AK
1101{
1102 uint8_t *key = av_strdup(t->key);
1103 uint8_t *p = key;
1104 const uint8_t *lang = NULL;
1105 ebml_master tag;
1106
b1306823
VG
1107 if (!key)
1108 return AVERROR(ENOMEM);
1109
9b75309c
AK
1110 if ((p = strrchr(p, '-')) &&
1111 (lang = av_convert_lang_to(p + 1, AV_LANG_ISO639_2_BIBL)))
1112 *p = 0;
1113
1114 p = key;
1115 while (*p) {
1116 if (*p == ' ')
1117 *p = '_';
1118 else if (*p >= 'a' && *p <= 'z')
1119 *p -= 'a' - 'A';
1120 p++;
1121 }
1122
1123 tag = start_ebml_master(pb, MATROSKA_ID_SIMPLETAG, 0);
1124 put_ebml_string(pb, MATROSKA_ID_TAGNAME, key);
1125 if (lang)
1126 put_ebml_string(pb, MATROSKA_ID_TAGLANG, lang);
1127 put_ebml_string(pb, MATROSKA_ID_TAGSTRING, t->value);
1128 end_ebml_master(pb, tag);
1129
1130 av_freep(&key);
b1306823 1131 return 0;
9b75309c
AK
1132}
1133
d2d67e42 1134static int mkv_write_tag(AVFormatContext *s, AVDictionary *m, unsigned int elementid,
9b75309c
AK
1135 unsigned int uid, ebml_master *tags)
1136{
1137 MatroskaMuxContext *mkv = s->priv_data;
1138 ebml_master tag, targets;
d2d67e42 1139 AVDictionaryEntry *t = NULL;
9b75309c
AK
1140 int ret;
1141
1142 if (!tags->pos) {
a2704c97 1143 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TAGS, avio_tell(s->pb));
9b75309c
AK
1144 if (ret < 0) return ret;
1145
1146 *tags = start_ebml_master(s->pb, MATROSKA_ID_TAGS, 0);
1147 }
1148
1149 tag = start_ebml_master(s->pb, MATROSKA_ID_TAG, 0);
1150 targets = start_ebml_master(s->pb, MATROSKA_ID_TAGTARGETS, 0);
1151 if (elementid)
1152 put_ebml_uint(s->pb, elementid, uid);
1153 end_ebml_master(s->pb, targets);
1154
b1306823 1155 while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX))) {
0092c1dd 1156 if (av_strcasecmp(t->key, "title") &&
f56a0855
JS
1157 av_strcasecmp(t->key, "encoding_tool") &&
1158 (elementid != MATROSKA_ID_TAGTARGETS_TRACKUID ||
1159 av_strcasecmp(t->key, "language"))) {
b1306823
VG
1160 ret = mkv_write_simpletag(s->pb, t);
1161 if (ret < 0)
1162 return ret;
1163 }
1164 }
9b75309c
AK
1165
1166 end_ebml_master(s->pb, tag);
1167 return 0;
1168}
1169
1170static int mkv_write_tags(AVFormatContext *s)
1171{
1172 ebml_master tags = {0};
1173 int i, ret;
1174
03700d39
AK
1175 ff_metadata_conv_ctx(s, ff_mkv_metadata_conv, NULL);
1176
d2d67e42 1177 if (av_dict_get(s->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX)) {
9b75309c
AK
1178 ret = mkv_write_tag(s, s->metadata, 0, 0, &tags);
1179 if (ret < 0) return ret;
1180 }
1181
1182 for (i = 0; i < s->nb_streams; i++) {
1183 AVStream *st = s->streams[i];
1184
d2d67e42 1185 if (!av_dict_get(st->metadata, "", 0, AV_DICT_IGNORE_SUFFIX))
9b75309c
AK
1186 continue;
1187
1188 ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &tags);
1189 if (ret < 0) return ret;
1190 }
1191
1192 for (i = 0; i < s->nb_chapters; i++) {
1193 AVChapter *ch = s->chapters[i];
1194
d2d67e42 1195 if (!av_dict_get(ch->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX))
9b75309c
AK
1196 continue;
1197
1198 ret = mkv_write_tag(s, ch->metadata, MATROSKA_ID_TAGTARGETS_CHAPTERUID, ch->id, &tags);
1199 if (ret < 0) return ret;
1200 }
1201
1202 if (tags.pos)
1203 end_ebml_master(s->pb, tags);
1204 return 0;
1205}
1206
c7a63a52
AK
1207static int mkv_write_attachments(AVFormatContext *s)
1208{
1209 MatroskaMuxContext *mkv = s->priv_data;
1210 AVIOContext *pb = s->pb;
1211 ebml_master attachments;
1212 AVLFG c;
1213 int i, ret;
1214
1215 if (!mkv->have_attachments)
1216 return 0;
1217
1218 av_lfg_init(&c, av_get_random_seed());
1219
1220 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_ATTACHMENTS, avio_tell(pb));
1221 if (ret < 0) return ret;
1222
1223 attachments = start_ebml_master(pb, MATROSKA_ID_ATTACHMENTS, 0);
1224
1225 for (i = 0; i < s->nb_streams; i++) {
1226 AVStream *st = s->streams[i];
1227 ebml_master attached_file;
1228 AVDictionaryEntry *t;
1229 const char *mimetype = NULL;
1230
9200514a 1231 if (st->codecpar->codec_type != AVMEDIA_TYPE_ATTACHMENT)
c7a63a52
AK
1232 continue;
1233
1234 attached_file = start_ebml_master(pb, MATROSKA_ID_ATTACHEDFILE, 0);
1235
1236 if (t = av_dict_get(st->metadata, "title", NULL, 0))
1237 put_ebml_string(pb, MATROSKA_ID_FILEDESC, t->value);
1238 if (!(t = av_dict_get(st->metadata, "filename", NULL, 0))) {
1239 av_log(s, AV_LOG_ERROR, "Attachment stream %d has no filename tag.\n", i);
1240 return AVERROR(EINVAL);
1241 }
1242 put_ebml_string(pb, MATROSKA_ID_FILENAME, t->value);
1243 if (t = av_dict_get(st->metadata, "mimetype", NULL, 0))
1244 mimetype = t->value;
9200514a 1245 else if (st->codecpar->codec_id != AV_CODEC_ID_NONE ) {
c7a63a52 1246 int i;
36ef5369 1247 for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
9200514a 1248 if (ff_mkv_mime_tags[i].id == st->codecpar->codec_id) {
c7a63a52
AK
1249 mimetype = ff_mkv_mime_tags[i].str;
1250 break;
1251 }
c4d37cd9 1252 for (i = 0; ff_mkv_image_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
9200514a 1253 if (ff_mkv_image_mime_tags[i].id == st->codecpar->codec_id) {
c4d37cd9 1254 mimetype = ff_mkv_image_mime_tags[i].str;
1255 break;
1256 }
c7a63a52
AK
1257 }
1258 if (!mimetype) {
1259 av_log(s, AV_LOG_ERROR, "Attachment stream %d has no mimetype tag and "
1260 "it cannot be deduced from the codec id.\n", i);
1261 return AVERROR(EINVAL);
1262 }
1263
1264 put_ebml_string(pb, MATROSKA_ID_FILEMIMETYPE, mimetype);
9200514a 1265 put_ebml_binary(pb, MATROSKA_ID_FILEDATA, st->codecpar->extradata, st->codecpar->extradata_size);
c7a63a52
AK
1266 put_ebml_uint(pb, MATROSKA_ID_FILEUID, av_lfg_get(&c));
1267 end_ebml_master(pb, attached_file);
1268 }
1269 end_ebml_master(pb, attachments);
1270
1271 return 0;
1272}
1273
5034ab90
DC
1274static int mkv_write_header(AVFormatContext *s)
1275{
1276 MatroskaMuxContext *mkv = s->priv_data;
ae628ec1 1277 AVIOContext *pb = s->pb;
baf71dca 1278 ebml_master ebml_header, segment_info;
d2d67e42 1279 AVDictionaryEntry *tag;
1f4280e7 1280 int ret, i;
5034ab90 1281
f1f6156b
LB
1282 if (!strcmp(s->oformat->name, "webm"))
1283 mkv->mode = MODE_WEBM;
1284 else
1285 mkv->mode = MODE_MATROSKAv2;
316d6c15 1286
84d4e599 1287 mkv->tracks = av_mallocz(s->nb_streams * sizeof(*mkv->tracks));
d06735a3
DC
1288 if (!mkv->tracks)
1289 return AVERROR(ENOMEM);
541d443c 1290
baf71dca 1291 ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
5034ab90
DC
1292 put_ebml_uint (pb, EBML_ID_EBMLVERSION , 1);
1293 put_ebml_uint (pb, EBML_ID_EBMLREADVERSION , 1);
1294 put_ebml_uint (pb, EBML_ID_EBMLMAXIDLENGTH , 4);
1295 put_ebml_uint (pb, EBML_ID_EBMLMAXSIZELENGTH , 8);
316d6c15 1296 put_ebml_string (pb, EBML_ID_DOCTYPE , s->oformat->name);
e3453fd4 1297 put_ebml_uint (pb, EBML_ID_DOCTYPEVERSION , 4);
5034ab90
DC
1298 put_ebml_uint (pb, EBML_ID_DOCTYPEREADVERSION , 2);
1299 end_ebml_master(pb, ebml_header);
1300
baf71dca 1301 mkv->segment = start_ebml_master(pb, MATROSKA_ID_SEGMENT, 0);
a2704c97 1302 mkv->segment_offset = avio_tell(pb);
967d815a 1303
cfde5d18
DC
1304 // we write 2 seek heads - one at the end of the file to point to each
1305 // cluster, and one at the beginning to point to all other level one
1306 // elements (including the seek head at the end of the file), which
1307 // isn't more than 10 elements if we only write one of each other
1308 // currently defined level 1 element
967d815a 1309 mkv->main_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 10);
e7ddafd5 1310 if (!mkv->main_seekhead)
c35de1a1 1311 return AVERROR(ENOMEM);
967d815a 1312
a2704c97 1313 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_INFO, avio_tell(pb));
6d588ecd 1314 if (ret < 0) return ret;
5034ab90 1315
baf71dca 1316 segment_info = start_ebml_master(pb, MATROSKA_ID_INFO, 0);
5034ab90 1317 put_ebml_uint(pb, MATROSKA_ID_TIMECODESCALE, 1000000);
d2d67e42 1318 if ((tag = av_dict_get(s->metadata, "title", NULL, 0)))
5e565998 1319 put_ebml_string(pb, MATROSKA_ID_TITLE, tag->value);
0c1959b0 1320 if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
1f4280e7 1321 uint32_t segment_uid[4];
5150dd53
MR
1322 AVLFG lfg;
1323
1324 av_lfg_init(&lfg, av_get_random_seed());
1325
1f4280e7 1326 for (i = 0; i < 4; i++)
5150dd53 1327 segment_uid[i] = av_lfg_get(&lfg);
1f4280e7 1328
f1f6156b 1329 put_ebml_string(pb, MATROSKA_ID_MUXINGAPP, LIBAVFORMAT_IDENT);
0092c1dd
JS
1330 if ((tag = av_dict_get(s->metadata, "encoding_tool", NULL, 0)))
1331 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, tag->value);
1332 else
1333 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, LIBAVFORMAT_IDENT);
1f4280e7 1334 put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
5034ab90 1335 }
4b8f58ee 1336
5034ab90
DC
1337 // reserve space for the duration
1338 mkv->duration = 0;
a2704c97 1339 mkv->duration_offset = avio_tell(pb);
5034ab90
DC
1340 put_ebml_void(pb, 11); // assumes double-precision float to be written
1341 end_ebml_master(pb, segment_info);
1342
6d588ecd 1343 ret = mkv_write_tracks(s);
f1f6156b
LB
1344 if (ret < 0)
1345 return ret;
67143c0f 1346
316d6c15
JZ
1347 if (mkv->mode != MODE_WEBM) {
1348 ret = mkv_write_chapters(s);
f1f6156b
LB
1349 if (ret < 0)
1350 return ret;
9b75309c
AK
1351
1352 ret = mkv_write_tags(s);
f1f6156b
LB
1353 if (ret < 0)
1354 return ret;
c7a63a52
AK
1355
1356 ret = mkv_write_attachments(s);
f1f6156b
LB
1357 if (ret < 0)
1358 return ret;
316d6c15 1359 }
2bd0758e 1360
83548fe8 1361 if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL))
7a2a4840
DC
1362 mkv_write_seekhead(pb, mkv->main_seekhead);
1363
6364d534 1364 mkv->cues = mkv_start_cues(mkv->segment_offset);
f929ab05 1365 if (!mkv->cues)
0b38843a 1366 return AVERROR(ENOMEM);
6364d534 1367
83548fe8 1368 if ((pb->seekable & AVIO_SEEKABLE_NORMAL) && mkv->reserve_cues_space) {
e3b225a4
AK
1369 mkv->cues_pos = avio_tell(pb);
1370 put_ebml_void(pb, mkv->reserve_cues_space);
1371 }
1372
ac9baa71
JZ
1373 av_init_packet(&mkv->cur_audio_pkt);
1374 mkv->cur_audio_pkt.size = 0;
ac9baa71 1375
b7f2fdde 1376 avio_flush(pb);
98308bd4
LB
1377
1378 // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1379 // after 4k and on a keyframe
83548fe8 1380 if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
98308bd4
LB
1381 if (mkv->cluster_time_limit < 0)
1382 mkv->cluster_time_limit = 5000;
1383 if (mkv->cluster_size_limit < 0)
1384 mkv->cluster_size_limit = 5 * 1024 * 1024;
1385 } else {
1386 if (mkv->cluster_time_limit < 0)
1387 mkv->cluster_time_limit = 1000;
1388 if (mkv->cluster_size_limit < 0)
1389 mkv->cluster_size_limit = 32 * 1024;
1390 }
1391
67143c0f
DC
1392 return 0;
1393}
1394
1bfbe8ff 1395static int mkv_blockgroup_size(int pkt_size)
baf71dca 1396{
1bfbe8ff 1397 int size = pkt_size + 4;
0f651e8c 1398 size += ebml_num_size(size);
baf71dca
DC
1399 size += 2; // EBML ID for block and block duration
1400 size += 8; // max size of block duration
0f651e8c 1401 size += ebml_num_size(size);
baf71dca
DC
1402 size += 1; // blockgroup EBML ID
1403 return size;
1404}
1405
69c1fe7c 1406static int ass_get_duration(AVFormatContext *s, const uint8_t *p)
b7f4e76d
AJ
1407{
1408 int sh, sm, ss, sc, eh, em, es, ec;
1409 uint64_t start, end;
1410
1411 if (sscanf(p, "%*[^,],%d:%d:%d%*c%d,%d:%d:%d%*c%d",
1412 &sh, &sm, &ss, &sc, &eh, &em, &es, &ec) != 8)
1413 return 0;
69c1fe7c
LB
1414
1415 if (sh > 9 || sm > 59 || ss > 59 || sc > 99 ||
1416 eh > 9 || em > 59 || es > 59 || ec > 99) {
1417 av_log(s, AV_LOG_WARNING,
1418 "Non-standard time reference %d:%d:%d.%d,%d:%d:%d.%d\n",
1419 sh, sm, ss, sc, eh, em, es, ec);
1420 return 0;
1421 }
1422
f1f6156b
LB
1423 start = 3600000 * sh + 60000 * sm + 1000 * ss + 10 * sc;
1424 end = 3600000 * eh + 60000 * em + 1000 * es + 10 * ec;
69c1fe7c
LB
1425
1426 if (start > end) {
1427 av_log(s, AV_LOG_WARNING,
1428 "Unexpected time reference %d:%d:%d.%d,%d:%d:%d.%d\n",
1429 sh, sm, ss, sc, eh, em, es, ec);
1430 return 0;
1431 }
1432
b7f4e76d
AJ
1433 return end - start;
1434}
1435
f1f6156b
LB
1436static int mkv_write_ass_blocks(AVFormatContext *s, AVIOContext *pb,
1437 AVPacket *pkt)
b7f4e76d
AJ
1438{
1439 MatroskaMuxContext *mkv = s->priv_data;
b7f4e76d
AJ
1440 int i, layer = 0, max_duration = 0, size, line_size, data_size = pkt->size;
1441 uint8_t *start, *end, *data = pkt->data;
1442 ebml_master blockgroup;
1443 char buffer[2048];
1444
1445 while (data_size) {
69c1fe7c 1446 int duration = ass_get_duration(s, data);
b7f4e76d 1447 max_duration = FFMAX(duration, max_duration);
f1f6156b
LB
1448 end = memchr(data, '\n', data_size);
1449 size = line_size = end ? end - data + 1 : data_size;
1450 size -= end ? (end[-1] == '\r') + 1 : 0;
1451 start = data;
1452 for (i = 0; i < 3; i++, start++)
1453 if (!(start = memchr(start, ',', size - (start - data))))
b7f4e76d
AJ
1454 return max_duration;
1455 size -= start - data;
1456 sscanf(data, "Dialogue: %d,", &layer);
f1f6156b 1457 i = snprintf(buffer, sizeof(buffer), "%" PRId64 ",%d,",
1c6d2b7d 1458 s->streams[pkt->stream_index]->nb_frames, layer);
f1f6156b
LB
1459 size = FFMIN(i + size, sizeof(buffer));
1460 memcpy(buffer + i, start, size - i);
b7f4e76d 1461
f1f6156b
LB
1462 av_log(s, AV_LOG_DEBUG,
1463 "Writing block at offset %" PRIu64 ", size %d, "
b7f4e76d 1464 "pts %" PRId64 ", duration %d\n",
a2704c97 1465 avio_tell(pb), size, pkt->pts, duration);
f1f6156b
LB
1466 blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
1467 mkv_blockgroup_size(size));
b7f4e76d 1468 put_ebml_id(pb, MATROSKA_ID_BLOCK);
f1f6156b
LB
1469 put_ebml_num(pb, size + 4, 0);
1470 // this assumes stream_index is less than 126
1471 avio_w8(pb, 0x80 | (pkt->stream_index + 1));
77eb5504
AK
1472 avio_wb16(pb, pkt->pts - mkv->cluster_pts);
1473 avio_w8(pb, 0);
1474 avio_write(pb, buffer, size);
b7f4e76d
AJ
1475 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
1476 end_ebml_master(pb, blockgroup);
1477
f1f6156b 1478 data += line_size;
b7f4e76d
AJ
1479 data_size -= line_size;
1480 }
1481
1482 return max_duration;
1483}
1484
01656fd4
AK
1485static int mkv_strip_wavpack(const uint8_t *src, uint8_t **pdst, int *size)
1486{
1487 uint8_t *dst;
1488 int srclen = *size;
1489 int offset = 0;
1490 int ret;
1491
1492 dst = av_malloc(srclen);
1493 if (!dst)
1494 return AVERROR(ENOMEM);
1495
1496 while (srclen >= WV_HEADER_SIZE) {
1497 WvHeader header;
1498
1499 ret = ff_wv_parse_header(&header, src);
1500 if (ret < 0)
1501 goto fail;
1502 src += WV_HEADER_SIZE;
1503 srclen -= WV_HEADER_SIZE;
1504
1505 if (srclen < header.blocksize) {
1506 ret = AVERROR_INVALIDDATA;
1507 goto fail;
1508 }
1509
1510 if (header.initial) {
1511 AV_WL32(dst + offset, header.samples);
1512 offset += 4;
1513 }
1514 AV_WL32(dst + offset, header.flags);
1515 AV_WL32(dst + offset + 4, header.crc);
1516 offset += 8;
1517
1518 if (!(header.initial && header.final)) {
1519 AV_WL32(dst + offset, header.blocksize);
1520 offset += 4;
1521 }
1522
1523 memcpy(dst + offset, src, header.blocksize);
1524 src += header.blocksize;
1525 srclen -= header.blocksize;
1526 offset += header.blocksize;
1527 }
1528
1529 *pdst = dst;
1530 *size = offset;
1531
1532 return 0;
1533fail:
1534 av_freep(&dst);
1535 return ret;
1536}
1537
ae628ec1 1538static void mkv_write_block(AVFormatContext *s, AVIOContext *pb,
871b641b 1539 unsigned int blockid, AVPacket *pkt, int flags)
95527e06
DC
1540{
1541 MatroskaMuxContext *mkv = s->priv_data;
9200514a 1542 AVCodecParameters *par = s->streams[pkt->stream_index]->codecpar;
5f8bae8d 1543 uint8_t *data = NULL;
117d8c6d 1544 int offset = 0, size = pkt->size;
84d4e599 1545 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
5d3953a5 1546 ts += mkv->tracks[pkt->stream_index].ts_offset;
95527e06 1547
8ffc5f9e 1548 av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
948f3c19 1549 "pts %" PRId64 ", dts %" PRId64 ", duration %" PRId64 ", flags %d\n",
a2704c97 1550 avio_tell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration, flags);
9200514a
AK
1551 if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 0 &&
1552 (AV_RB24(par->extradata) == 1 || AV_RB32(par->extradata) == 1))
5f8bae8d 1553 ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
9200514a
AK
1554 else if (par->codec_id == AV_CODEC_ID_HEVC && par->extradata_size > 6 &&
1555 (AV_RB24(par->extradata) == 1 || AV_RB32(par->extradata) == 1))
558b20d7
TW
1556 /* extradata is Annex B, assume the bitstream is too and convert it */
1557 ff_hevc_annexb2mp4_buf(pkt->data, &data, &size, 0, NULL);
9200514a 1558 else if (par->codec_id == AV_CODEC_ID_WAVPACK) {
01656fd4
AK
1559 int ret = mkv_strip_wavpack(pkt->data, &data, &size);
1560 if (ret < 0) {
1561 av_log(s, AV_LOG_ERROR, "Error stripping a WavPack packet.\n");
1562 return;
1563 }
1564 } else
5f8bae8d 1565 data = pkt->data;
117d8c6d 1566
9200514a 1567 if (par->codec_id == AV_CODEC_ID_PRORES) {
117d8c6d
LB
1568 /* Matroska specification requires to remove the first QuickTime atom
1569 */
f1f6156b 1570 size -= 8;
117d8c6d
LB
1571 offset = 8;
1572 }
1573
95527e06 1574 put_ebml_id(pb, blockid);
f1f6156b
LB
1575 put_ebml_num(pb, size + 4, 0);
1576 // this assumes stream_index is less than 126
1577 avio_w8(pb, 0x80 | (pkt->stream_index + 1));
77eb5504
AK
1578 avio_wb16(pb, ts - mkv->cluster_pts);
1579 avio_w8(pb, flags);
117d8c6d 1580 avio_write(pb, data + offset, size);
5f8bae8d
AJ
1581 if (data != pkt->data)
1582 av_free(data);
95527e06
DC
1583}
1584
2701fd40
AJ
1585static int srt_get_duration(uint8_t **buf)
1586{
1587 int i, duration = 0;
1588
f1f6156b 1589 for (i = 0; i < 2 && !duration; i++) {
2701fd40
AJ
1590 int s_hour, s_min, s_sec, s_hsec, e_hour, e_min, e_sec, e_hsec;
1591 if (sscanf(*buf, "%d:%2d:%2d%*1[,.]%3d --> %d:%2d:%2d%*1[,.]%3d",
1592 &s_hour, &s_min, &s_sec, &s_hsec,
1593 &e_hour, &e_min, &e_sec, &e_hsec) == 8) {
f1f6156b
LB
1594 s_min += 60 * s_hour;
1595 e_min += 60 * e_hour;
1596 s_sec += 60 * s_min;
1597
1598 e_sec += 60 * e_min;
1599 s_hsec += 1000 * s_sec;
1600 e_hsec += 1000 * e_sec;
1601
2701fd40
AJ
1602 duration = e_hsec - s_hsec;
1603 }
1604 *buf += strcspn(*buf, "\n") + 1;
1605 }
1606 return duration;
1607}
1608
f1f6156b
LB
1609static int mkv_write_srt_blocks(AVFormatContext *s, AVIOContext *pb,
1610 AVPacket *pkt)
2701fd40
AJ
1611{
1612 ebml_master blockgroup;
1613 AVPacket pkt2 = *pkt;
1614 int64_t duration = srt_get_duration(&pkt2.data);
1615 pkt2.size -= pkt2.data - pkt->data;
1616
1617 blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
1618 mkv_blockgroup_size(pkt2.size));
1619 mkv_write_block(s, pb, MATROSKA_ID_BLOCK, &pkt2, 0);
1620 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
1621 end_ebml_master(pb, blockgroup);
1622
1623 return duration;
1624}
1625
871b641b
DC
1626static void mkv_flush_dynbuf(AVFormatContext *s)
1627{
1628 MatroskaMuxContext *mkv = s->priv_data;
1629 int bufsize;
1630 uint8_t *dyn_buf;
1631
1632 if (!mkv->dyn_bc)
1633 return;
1634
6dc7d80d 1635 bufsize = avio_close_dyn_buf(mkv->dyn_bc, &dyn_buf);
77eb5504 1636 avio_write(s->pb, dyn_buf, bufsize);
871b641b
DC
1637 av_free(dyn_buf);
1638 mkv->dyn_bc = NULL;
1639}
1640
f4bf2363
JA
1641static int mkv_check_new_extra_data(AVFormatContext *s, AVPacket *pkt)
1642{
1643 MatroskaMuxContext *mkv = s->priv_data;
1644 AVCodecParameters *par = s->streams[pkt->stream_index]->codecpar;
1645 mkv_track *track = &mkv->tracks[pkt->stream_index];
1646 uint8_t *side_data;
1647 int side_data_size = 0, ret;
1648
1649 side_data = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
1650 &side_data_size);
1651
1652 switch (par->codec_id) {
1653 case AV_CODEC_ID_AAC:
1654 if (side_data_size && (s->pb->seekable & AVIO_SEEKABLE_NORMAL)) {
1655 int output_sample_rate = 0;
1656 int64_t curpos;
1657 ret = get_aac_sample_rates(s, side_data, side_data_size, &track->sample_rate,
1658 &output_sample_rate);
1659 if (ret < 0)
1660 return ret;
1661 if (!output_sample_rate)
1662 output_sample_rate = track->sample_rate; // Space is already reserved, so it's this or a void element.
1663 curpos = avio_tell(s->pb);
1664 avio_seek(s->pb, track->sample_rate_offset, SEEK_SET);
1665 put_ebml_float(s->pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, track->sample_rate);
1666 put_ebml_float(s->pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
1667 avio_seek(s->pb, curpos, SEEK_SET);
1668 } else if (!par->extradata_size && !track->sample_rate) {
1669 // No extradata (codecpar or packet side data).
1670 av_log(s, AV_LOG_ERROR, "Error parsing AAC extradata, unable to determine samplerate.\n");
1671 return AVERROR(EINVAL);
1672 }
1673 break;
98cae966
JA
1674 case AV_CODEC_ID_FLAC:
1675 if (side_data_size && (s->pb->seekable & AVIO_SEEKABLE_NORMAL)) {
1676 AVCodecParameters *codecpriv_par;
1677 int64_t curpos;
1678 if (side_data_size != par->extradata_size) {
1679 av_log(s, AV_LOG_ERROR, "Invalid FLAC STREAMINFO metadata for output stream %d\n",
1680 pkt->stream_index);
1681 return AVERROR(EINVAL);
1682 }
1683 codecpriv_par = avcodec_parameters_alloc();
1684 if (!codecpriv_par)
1685 return AVERROR(ENOMEM);
1686 ret = avcodec_parameters_copy(codecpriv_par, par);
1687 if (ret < 0) {
1688 avcodec_parameters_free(&codecpriv_par);
1689 return ret;
1690 }
1691 memcpy(codecpriv_par->extradata, side_data, side_data_size);
1692 curpos = avio_tell(s->pb);
1693 avio_seek(s->pb, track->codecpriv_offset, SEEK_SET);
1694 mkv_write_codecprivate(s, s->pb, codecpriv_par, 1, 0);
1695 avio_seek(s->pb, curpos, SEEK_SET);
1696 avcodec_parameters_free(&codecpriv_par);
1697 }
1698 break;
f4bf2363
JA
1699 default:
1700 if (side_data_size)
1701 av_log(s, AV_LOG_DEBUG, "Ignoring new extradata in a packet for stream %d.\n", pkt->stream_index);
1702 break;
1703 }
1704
1705 return 0;
1706}
1707
ac9baa71 1708static int mkv_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
67143c0f 1709{
98186e41 1710 MatroskaMuxContext *mkv = s->priv_data;
f1f6156b 1711 AVIOContext *pb = s->pb;
9200514a 1712 AVCodecParameters *par = s->streams[pkt->stream_index]->codecpar;
f1f6156b
LB
1713 int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1714 int duration = pkt->duration;
6d588ecd 1715 int ret;
84d4e599 1716 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
b1adb69c 1717
654b65d0
DC
1718 if (ts == AV_NOPTS_VALUE) {
1719 av_log(s, AV_LOG_ERROR, "Can't write packet with unknown timestamp\n");
1720 return AVERROR(EINVAL);
1721 }
a1aa37dd 1722 ts += mkv->tracks[pkt->stream_index].ts_offset;
654b65d0 1723
83548fe8 1724 if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL)) {
28c020d4
VG
1725 if (!mkv->dyn_bc) {
1726 ret = avio_open_dyn_buf(&mkv->dyn_bc);
1727 if (ret < 0)
1728 return ret;
1729 }
871b641b
DC
1730 pb = mkv->dyn_bc;
1731 }
1732
30f06a58 1733 if (!mkv->cluster_pos) {
a2704c97 1734 mkv->cluster_pos = avio_tell(s->pb);
f1f6156b 1735 mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER, 0);
f9ff7179
DC
1736 put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, FFMAX(0, ts));
1737 mkv->cluster_pts = FFMAX(0, ts);
98186e41
DC
1738 }
1739
9200514a 1740 if (par->codec_type != AVMEDIA_TYPE_SUBTITLE) {
871b641b 1741 mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
9200514a 1742 } else if (par->codec_id == AV_CODEC_ID_SSA) {
871b641b 1743 duration = mkv_write_ass_blocks(s, pb, pkt);
9200514a 1744 } else if (par->codec_id == AV_CODEC_ID_SRT) {
2701fd40 1745 duration = mkv_write_srt_blocks(s, pb, pkt);
663a5d9d 1746 } else {
f1f6156b
LB
1747 ebml_master blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
1748 mkv_blockgroup_size(pkt->size));
948f3c19 1749 duration = pkt->duration;
1750#if FF_API_CONVERGENCE_DURATION
1751FF_DISABLE_DEPRECATION_WARNINGS
1752 if (pkt->convergence_duration)
1753 duration = pkt->convergence_duration;
1754FF_ENABLE_DEPRECATION_WARNINGS
1755#endif
871b641b 1756 mkv_write_block(s, pb, MATROSKA_ID_BLOCK, pkt, 0);
291902c2 1757 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
663a5d9d
DC
1758 end_ebml_master(pb, blockgroup);
1759 }
02f487fc 1760
9200514a 1761 if (par->codec_type == AVMEDIA_TYPE_VIDEO && keyframe) {
f1f6156b
LB
1762 ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, ts,
1763 mkv->cluster_pos);
1764 if (ret < 0)
1765 return ret;
6364d534
DC
1766 }
1767
ac9baa71
JZ
1768 mkv->duration = FFMAX(mkv->duration, ts + duration);
1769 return 0;
1770}
1771
ac9baa71
JZ
1772static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
1773{
1774 MatroskaMuxContext *mkv = s->priv_data;
9200514a 1775 int codec_type = s->streams[pkt->stream_index]->codecpar->codec_type;
148fbdd1
LB
1776 int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1777 int cluster_size;
148fbdd1 1778 int64_t cluster_time;
148fbdd1
LB
1779 AVIOContext *pb;
1780 int ret;
1781
f4bf2363
JA
1782 ret = mkv_check_new_extra_data(s, pkt);
1783 if (ret < 0)
1784 return ret;
1785
148fbdd1
LB
1786 if (mkv->tracks[pkt->stream_index].write_dts)
1787 cluster_time = pkt->dts - mkv->cluster_pts;
1788 else
1789 cluster_time = pkt->pts - mkv->cluster_pts;
a1aa37dd 1790 cluster_time += mkv->tracks[pkt->stream_index].ts_offset;
ac9baa71
JZ
1791
1792 // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1793 // after 4k and on a keyframe
83548fe8 1794 if (s->pb->seekable & AVIO_SEEKABLE_NORMAL) {
148fbdd1
LB
1795 pb = s->pb;
1796 cluster_size = avio_tell(pb) - mkv->cluster_pos;
148fbdd1
LB
1797 } else {
1798 pb = mkv->dyn_bc;
1799 cluster_size = avio_tell(pb);
148fbdd1
LB
1800 }
1801
ac9baa71 1802 if (mkv->cluster_pos &&
98308bd4
LB
1803 (cluster_size > mkv->cluster_size_limit ||
1804 cluster_time > mkv->cluster_time_limit ||
148fbdd1
LB
1805 (codec_type == AVMEDIA_TYPE_VIDEO && keyframe &&
1806 cluster_size > 4 * 1024))) {
f1f6156b
LB
1807 av_log(s, AV_LOG_DEBUG,
1808 "Starting new cluster at offset %" PRIu64 " bytes, "
1809 "pts %" PRIu64 "dts %" PRIu64 "\n",
148fbdd1 1810 avio_tell(pb), pkt->pts, pkt->dts);
30f06a58
DC
1811 end_ebml_master(pb, mkv->cluster);
1812 mkv->cluster_pos = 0;
871b641b
DC
1813 if (mkv->dyn_bc)
1814 mkv_flush_dynbuf(s);
59f59592 1815 avio_flush(s->pb);
30f06a58
DC
1816 }
1817
71852a1b
MS
1818 if (!mkv->cluster_pos)
1819 avio_write_marker(s->pb,
1820 av_rescale_q(pkt->dts, s->streams[pkt->stream_index]->time_base, AV_TIME_BASE_Q),
1821 keyframe && (mkv->have_video ? codec_type == AVMEDIA_TYPE_VIDEO : 1) ? AVIO_DATA_MARKER_SYNC_POINT : AVIO_DATA_MARKER_BOUNDARY_POINT);
1822
ac9baa71
JZ
1823 // check if we have an audio packet cached
1824 if (mkv->cur_audio_pkt.size > 0) {
1825 ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
ce70f28a 1826 av_packet_unref(&mkv->cur_audio_pkt);
ac9baa71 1827 if (ret < 0) {
f1f6156b
LB
1828 av_log(s, AV_LOG_ERROR,
1829 "Could not write cached audio packet ret:%d\n", ret);
ac9baa71
JZ
1830 return ret;
1831 }
1832 }
1833
1834 // buffer an audio packet to ensure the packet containing the video
1835 // keyframe's timecode is contained in the same cluster for WebM
148fbdd1 1836 if (codec_type == AVMEDIA_TYPE_AUDIO) {
9b56d5c1 1837 ret = av_packet_ref(&mkv->cur_audio_pkt, pkt);
1afddbe5 1838 } else
ac9baa71
JZ
1839 ret = mkv_write_packet_internal(s, pkt);
1840 return ret;
67143c0f
DC
1841}
1842
b886f5c2
MS
1843static int mkv_write_flush_packet(AVFormatContext *s, AVPacket *pkt)
1844{
1845 MatroskaMuxContext *mkv = s->priv_data;
1846 AVIOContext *pb;
83548fe8 1847 if (s->pb->seekable & AVIO_SEEKABLE_NORMAL)
b886f5c2
MS
1848 pb = s->pb;
1849 else
1850 pb = mkv->dyn_bc;
1851 if (!pkt) {
1852 if (mkv->cluster_pos) {
f1f6156b
LB
1853 av_log(s, AV_LOG_DEBUG,
1854 "Flushing cluster at offset %" PRIu64 " bytes\n",
1855 avio_tell(pb));
b886f5c2
MS
1856 end_ebml_master(pb, mkv->cluster);
1857 mkv->cluster_pos = 0;
1858 if (mkv->dyn_bc)
1859 mkv_flush_dynbuf(s);
1860 avio_flush(s->pb);
1861 }
b14086ca 1862 return 1;
b886f5c2
MS
1863 }
1864 return mkv_write_packet(s, pkt);
1865}
1866
67143c0f
DC
1867static int mkv_write_trailer(AVFormatContext *s)
1868{
1869 MatroskaMuxContext *mkv = s->priv_data;
ae628ec1 1870 AVIOContext *pb = s->pb;
e7ddafd5 1871 int64_t currentpos, cuespos;
9e2a3e22 1872 int ret;
02f487fc 1873
ac9baa71
JZ
1874 // check if we have an audio packet cached
1875 if (mkv->cur_audio_pkt.size > 0) {
1876 ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
ce70f28a 1877 av_packet_unref(&mkv->cur_audio_pkt);
ac9baa71 1878 if (ret < 0) {
f1f6156b
LB
1879 av_log(s, AV_LOG_ERROR,
1880 "Could not write cached audio packet ret:%d\n", ret);
ac9baa71
JZ
1881 return ret;
1882 }
1883 }
1884
871b641b
DC
1885 if (mkv->dyn_bc) {
1886 end_ebml_master(mkv->dyn_bc, mkv->cluster);
1887 mkv_flush_dynbuf(s);
1888 } else if (mkv->cluster_pos) {
1889 end_ebml_master(pb, mkv->cluster);
1890 }
02f487fc 1891
26b241c0
JS
1892 if (mkv->mode != MODE_WEBM) {
1893 ret = mkv_write_chapters(s);
f1f6156b
LB
1894 if (ret < 0)
1895 return ret;
26b241c0
JS
1896 }
1897
83548fe8 1898 if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
91819763 1899 if (mkv->cues->num_entries) {
e3b225a4
AK
1900 if (mkv->reserve_cues_space) {
1901 int64_t cues_end;
1902
1903 currentpos = avio_tell(pb);
1904 avio_seek(pb, mkv->cues_pos, SEEK_SET);
1905
f1f6156b 1906 cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
e3b225a4
AK
1907 cues_end = avio_tell(pb);
1908 if (cues_end > cuespos + mkv->reserve_cues_space) {
f1f6156b
LB
1909 av_log(s, AV_LOG_ERROR,
1910 "Insufficient space reserved for cues: %d "
1911 "(needed: %" PRId64 ").\n",
1912 mkv->reserve_cues_space, cues_end - cuespos);
e3b225a4
AK
1913 return AVERROR(EINVAL);
1914 }
1915
1916 if (cues_end < cuespos + mkv->reserve_cues_space)
f1f6156b
LB
1917 put_ebml_void(pb, mkv->reserve_cues_space -
1918 (cues_end - cuespos));
e3b225a4
AK
1919
1920 avio_seek(pb, currentpos, SEEK_SET);
1921 } else {
1922 cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
1923 }
91819763 1924
f1f6156b
LB
1925 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CUES,
1926 cuespos);
1927 if (ret < 0)
1928 return ret;
91819763 1929 }
6364d534 1930
e5c29287
DC
1931 mkv_write_seekhead(pb, mkv->main_seekhead);
1932
1933 // update the duration
1934 av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
a2704c97 1935 currentpos = avio_tell(pb);
6b4aa5da 1936 avio_seek(pb, mkv->duration_offset, SEEK_SET);
e5c29287
DC
1937 put_ebml_float(pb, MATROSKA_ID_DURATION, mkv->duration);
1938
6b4aa5da 1939 avio_seek(pb, currentpos, SEEK_SET);
ac9e1177 1940 }
02f487fc 1941
67143c0f 1942 end_ebml_master(pb, mkv->segment);
84d4e599 1943 av_free(mkv->tracks);
eddd580b
MR
1944 av_freep(&mkv->cues->entries);
1945 av_freep(&mkv->cues);
3b4bb19e 1946
67143c0f
DC
1947 return 0;
1948}
1949
36ef5369 1950static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
15c14ce6
AK
1951{
1952 int i;
36ef5369 1953 for (i = 0; ff_mkv_codec_tags[i].id != AV_CODEC_ID_NONE; i++)
15c14ce6
AK
1954 if (ff_mkv_codec_tags[i].id == codec_id)
1955 return 1;
1956
f1f6156b
LB
1957 if (std_compliance < FF_COMPLIANCE_NORMAL) {
1958 enum AVMediaType type = avcodec_get_type(codec_id);
1959 // mkv theoretically supports any video/audio through VFW/ACM
15c14ce6
AK
1960 if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)
1961 return 1;
1962 }
1963
1964 return 0;
1965}
1966
e3b225a4
AK
1967#define OFFSET(x) offsetof(MatroskaMuxContext, x)
1968#define FLAGS AV_OPT_FLAG_ENCODING_PARAM
1969static const AVOption options[] = {
98308bd4
LB
1970 { "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 },
1971 { "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 },
1972 { "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
1973 { NULL },
1974};
1975
316d6c15 1976#if CONFIG_MATROSKA_MUXER
e3b225a4
AK
1977static const AVClass matroska_class = {
1978 .class_name = "matroska muxer",
1979 .item_name = av_default_item_name,
1980 .option = options,
1981 .version = LIBAVUTIL_VERSION_INT,
1982};
1983
c6610a21 1984AVOutputFormat ff_matroska_muxer = {
dfc2c4d9 1985 .name = "matroska",
6774247a 1986 .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
dfc2c4d9
AK
1987 .mime_type = "video/x-matroska",
1988 .extensions = "mkv",
1989 .priv_data_size = sizeof(MatroskaMuxContext),
fd487218 1990 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
36ef5369 1991 AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
fd487218 1992 .video_codec = CONFIG_LIBX264_ENCODER ?
36ef5369 1993 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
dfc2c4d9 1994 .write_header = mkv_write_header,
b886f5c2 1995 .write_packet = mkv_write_flush_packet,
dfc2c4d9 1996 .write_trailer = mkv_write_trailer,
e9cef897 1997 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
b886f5c2 1998 AVFMT_TS_NONSTRICT | AVFMT_ALLOW_FLUSH,
20234a4b
MS
1999 .codec_tag = (const AVCodecTag* const []){
2000 ff_codec_bmp_tags, ff_codec_wav_tags, 0
2001 },
36ef5369 2002 .subtitle_codec = AV_CODEC_ID_SSA,
15c14ce6 2003 .query_codec = mkv_query_codec,
e3b225a4 2004 .priv_class = &matroska_class,
67143c0f 2005};
316d6c15
JZ
2006#endif
2007
2008#if CONFIG_WEBM_MUXER
e3b225a4
AK
2009static const AVClass webm_class = {
2010 .class_name = "webm muxer",
2011 .item_name = av_default_item_name,
2012 .option = options,
2013 .version = LIBAVUTIL_VERSION_INT,
2014};
2015
c6610a21 2016AVOutputFormat ff_webm_muxer = {
dfc2c4d9 2017 .name = "webm",
6774247a 2018 .long_name = NULL_IF_CONFIG_SMALL("WebM"),
dfc2c4d9
AK
2019 .mime_type = "video/webm",
2020 .extensions = "webm",
2021 .priv_data_size = sizeof(MatroskaMuxContext),
e176639b
LB
2022 .audio_codec = CONFIG_LIBOPUS_ENCODER ? AV_CODEC_ID_OPUS : AV_CODEC_ID_VORBIS,
2023 .video_codec = CONFIG_LIBVPX_VP9_ENCODER? AV_CODEC_ID_VP9 : AV_CODEC_ID_VP8,
dfc2c4d9 2024 .write_header = mkv_write_header,
b886f5c2 2025 .write_packet = mkv_write_flush_packet,
dfc2c4d9 2026 .write_trailer = mkv_write_trailer,
e9cef897 2027 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
b886f5c2 2028 AVFMT_TS_NONSTRICT | AVFMT_ALLOW_FLUSH,
e3b225a4 2029 .priv_class = &webm_class,
316d6c15
JZ
2030};
2031#endif
55c151ef 2032
316d6c15 2033#if CONFIG_MATROSKA_AUDIO_MUXER
e3b225a4
AK
2034static const AVClass mka_class = {
2035 .class_name = "matroska audio muxer",
2036 .item_name = av_default_item_name,
2037 .option = options,
2038 .version = LIBAVUTIL_VERSION_INT,
2039};
c6610a21 2040AVOutputFormat ff_matroska_audio_muxer = {
dfc2c4d9 2041 .name = "matroska",
6774247a 2042 .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
dfc2c4d9
AK
2043 .mime_type = "audio/x-matroska",
2044 .extensions = "mka",
2045 .priv_data_size = sizeof(MatroskaMuxContext),
fd487218 2046 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
36ef5369
AK
2047 AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
2048 .video_codec = AV_CODEC_ID_NONE,
dfc2c4d9 2049 .write_header = mkv_write_header,
b886f5c2 2050 .write_packet = mkv_write_flush_packet,
dfc2c4d9 2051 .write_trailer = mkv_write_trailer,
b886f5c2
MS
2052 .flags = AVFMT_GLOBALHEADER | AVFMT_TS_NONSTRICT |
2053 AVFMT_ALLOW_FLUSH,
20234a4b 2054 .codec_tag = (const AVCodecTag* const []){ ff_codec_wav_tags, 0 },
e3b225a4 2055 .priv_class = &mka_class,
55c151ef 2056};
316d6c15 2057#endif