vp9: add superframe merging bitstream filter.
[libav.git] / libavformat / matroskaenc.c
CommitLineData
67143c0f 1/*
8cf3bb26 2 * Matroska muxer
67143c0f
DC
3 * Copyright (c) 2007 David Conrad
4 *
5 * This file is part of FFmpeg.
6 *
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
8f8bc923
DB
22#include <stdint.h>
23
0574bc06 24#include "avc.h"
a823d094 25#include "hevc.h"
67143c0f 26#include "avformat.h"
5ceffb1b 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"
90fc00a6 34#include "subtitles.h"
106b62f4 35#include "vorbiscomment.h"
01656fd4 36#include "wv.h"
0574bc06
AK
37
38#include "libavutil/avstring.h"
106b62f4 39#include "libavutil/channel_layout.h"
0574bc06 40#include "libavutil/dict.h"
3383a53e 41#include "libavutil/intfloat.h"
0574bc06
AK
42#include "libavutil/intreadwrite.h"
43#include "libavutil/lfg.h"
0ebcdf5c 44#include "libavutil/mathematics.h"
e3b225a4 45#include "libavutil/opt.h"
1f4280e7 46#include "libavutil/random_seed.h"
31852540 47#include "libavutil/rational.h"
0574bc06 48#include "libavutil/samplefmt.h"
2e0cc342 49#include "libavutil/sha.h"
4d686fb7 50#include "libavutil/stereo3d.h"
0574bc06 51
245976da 52#include "libavcodec/xiph.h"
7bfacd4e 53#include "libavcodec/mpeg4audio.h"
bb47aa58 54#include "libavcodec/internal.h"
67143c0f 55
baf71dca 56typedef struct ebml_master {
bc5c918e 57 int64_t pos; ///< absolute offset in the file where the master's elements start
baf71dca
DC
58 int sizebytes; ///< how many bytes were reserved for the size
59} ebml_master;
60
967d815a
DC
61typedef struct mkv_seekhead_entry {
62 unsigned int elementid;
63 uint64_t segmentpos;
64} mkv_seekhead_entry;
65
66typedef struct mkv_seekhead {
bc5c918e
DB
67 int64_t filepos;
68 int64_t segment_offset; ///< the file offset to the beginning of the segment
1b66d314 69 int reserved_size; ///< -1 if appending to file
967d815a
DC
70 int max_entries;
71 mkv_seekhead_entry *entries;
72 int num_entries;
73} mkv_seekhead;
74
daf8cf35 75typedef struct mkv_cuepoint {
6364d534 76 uint64_t pts;
37cef8c7 77 int stream_idx;
6364d534 78 int tracknum;
bc5c918e 79 int64_t cluster_pos; ///< file offset of the cluster containing the block
c5f3cc40 80 int64_t relative_pos; ///< relative offset from the position of the cluster containing the block
56f17407 81 int64_t duration; ///< duration of the block according to time base
6364d534
DC
82} mkv_cuepoint;
83
daf8cf35 84typedef struct mkv_cues {
bc5c918e 85 int64_t segment_offset;
6364d534
DC
86 mkv_cuepoint *entries;
87 int num_entries;
88} mkv_cues;
89
daf8cf35 90typedef struct mkv_track {
84d4e599 91 int write_dts;
271f4112 92 int has_cue;
a1aa37dd 93 int64_t ts_offset;
84d4e599
DC
94} mkv_track;
95
316d6c15
JZ
96#define MODE_MATROSKAv2 0x01
97#define MODE_WEBM 0x02
98
7be0f48a
VV
99/** Maximum number of tracks allowed in a Matroska file (with track numbers in
100 * range 1 to 126 (inclusive) */
101#define MAX_TRACKS 126
102
67143c0f 103typedef struct MatroskaMuxContext {
e3b225a4 104 const AVClass *class;
316d6c15 105 int mode;
ae628ec1 106 AVIOContext *dyn_bc;
baf71dca 107 ebml_master segment;
bc5c918e 108 int64_t segment_offset;
baf71dca 109 ebml_master cluster;
bc5c918e 110 int64_t cluster_pos; ///< file offset of the current cluster
f9ff7179 111 int64_t cluster_pts;
bc5c918e 112 int64_t duration_offset;
f9ff7179 113 int64_t duration;
967d815a 114 mkv_seekhead *main_seekhead;
6364d534 115 mkv_cues *cues;
84d4e599 116 mkv_track *tracks;
541d443c 117
ac9baa71 118 AVPacket cur_audio_pkt;
c7a63a52
AK
119
120 int have_attachments;
e3b225a4
AK
121
122 int reserve_cues_space;
98308bd4 123 int cluster_size_limit;
e3b225a4 124 int64_t cues_pos;
98308bd4 125 int64_t cluster_time_limit;
37cef8c7
VV
126 int is_dash;
127 int dash_track_number;
6fd300ac 128 int is_live;
07704c61
MN
129
130 uint32_t chapter_id_offset;
26b241c0 131 int wrote_chapters;
7d60baa8 132
7be0f48a
VV
133 int64_t last_track_timestamp[MAX_TRACKS];
134
31852540
SI
135 int64_t* stream_durations;
136 int64_t* stream_duration_offsets;
137
7d60baa8 138 int allow_raw_vfw;
67143c0f
DC
139} MatroskaMuxContext;
140
baf71dca 141
e3cd80cd
DC
142/** 2 bytes * 3 for EBML IDs, 3 1-byte EBML lengths, 8 bytes for 64 bit
143 * offset, 4 bytes for target EBML ID */
baf71dca
DC
144#define MAX_SEEKENTRY_SIZE 21
145
56f17407 146/** per-cuepoint-track - 5 1-byte EBML IDs, 5 1-byte EBML sizes, 4
e3cd80cd 147 * 8-byte uint max */
56f17407 148#define MAX_CUETRACKPOS_SIZE 42
baf71dca 149
e3cd80cd 150/** per-cuepoint - 2 1-byte EBML IDs, 2 1-byte EBML sizes, 8-byte uint max */
f1f6156b 151#define MAX_CUEPOINT_SIZE(num_tracks) 12 + MAX_CUETRACKPOS_SIZE * num_tracks
baf71dca 152
571efd97
VV
153/** Seek preroll value for opus */
154#define OPUS_SEEK_PREROLL 80000000
155
22ccb69a
DC
156static int ebml_id_size(unsigned int id)
157{
f1f6156b 158 return (av_log2(id + 1) - 1) / 7 + 1;
22ccb69a
DC
159}
160
ae628ec1 161static void put_ebml_id(AVIOContext *pb, unsigned int id)
67143c0f 162{
432adc13
DC
163 int i = ebml_id_size(id);
164 while (i--)
8365287e 165 avio_w8(pb, (uint8_t)(id >> (i * 8)));
67143c0f
DC
166}
167
ec8f4ad9 168/**
bf898960 169 * Write an EBML size meaning "unknown size".
ec8f4ad9 170 *
bf898960 171 * @param bytes The number of bytes the size should occupy (maximum: 8).
ec8f4ad9 172 */
ae628ec1 173static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
ec8f4ad9 174{
c5cc9498 175 av_assert0(bytes <= 8);
77eb5504 176 avio_w8(pb, 0x1ff >> bytes);
5ceffb1b 177 ffio_fill(pb, 0xff, bytes - 1);
ec8f4ad9
DC
178}
179
1c73478c 180/**
0f651e8c 181 * Calculate how many bytes are needed to represent a given number in EBML.
1c73478c 182 */
0f651e8c 183static int ebml_num_size(uint64_t num)
1c73478c
DC
184{
185 int bytes = 1;
f1f6156b
LB
186 while ((num + 1) >> bytes * 7)
187 bytes++;
1c73478c
DC
188 return bytes;
189}
190
f0e9f442 191/**
0f651e8c 192 * Write a number in EBML variable length format.
f0e9f442 193 *
0f651e8c 194 * @param bytes The number of bytes that need to be used to write the number.
f0e9f442
DC
195 * If zero, any number of bytes can be used.
196 */
ae628ec1 197static void put_ebml_num(AVIOContext *pb, uint64_t num, int bytes)
67143c0f 198{
0f651e8c 199 int i, needed_bytes = ebml_num_size(num);
67143c0f
DC
200
201 // sizes larger than this are currently undefined in EBML
8365287e 202 av_assert0(num < (1ULL << 56) - 1);
ffb880c2 203
f0e9f442
DC
204 if (bytes == 0)
205 // don't care how many bytes are used, so use the min
206 bytes = needed_bytes;
47e08c58
DC
207 // the bytes needed to write the given size would exceed the bytes
208 // that we need to use, so write unknown size. This shouldn't happen.
c5cc9498 209 av_assert0(bytes >= needed_bytes);
f0e9f442 210
f1f6156b 211 num |= 1ULL << bytes * 7;
ddf16467 212 for (i = bytes - 1; i >= 0; i--)
8365287e 213 avio_w8(pb, (uint8_t)(num >> i * 8));
67143c0f
DC
214}
215
ae628ec1 216static void put_ebml_uint(AVIOContext *pb, unsigned int elementid, uint64_t val)
67143c0f 217{
9f38fd7e 218 int i, bytes = 1;
73260a11 219 uint64_t tmp = val;
f1f6156b
LB
220 while (tmp >>= 8)
221 bytes++;
67143c0f
DC
222
223 put_ebml_id(pb, elementid);
0f651e8c 224 put_ebml_num(pb, bytes, 0);
9f38fd7e 225 for (i = bytes - 1; i >= 0; i--)
8365287e 226 avio_w8(pb, (uint8_t)(val >> i * 8));
67143c0f
DC
227}
228
d03eea36
JG
229static void put_ebml_sint(AVIOContext *pb, unsigned int elementid, int64_t val)
230{
231 int i, bytes = 1;
cddd15ba
MN
232 uint64_t tmp = 2*(val < 0 ? val^-1 : val);
233
234 while (tmp>>=8) bytes++;
d03eea36
JG
235
236 put_ebml_id(pb, elementid);
237 put_ebml_num(pb, bytes, 0);
238 for (i = bytes - 1; i >= 0; i--)
8365287e 239 avio_w8(pb, (uint8_t)(val >> i * 8));
d03eea36
JG
240}
241
ae628ec1 242static void put_ebml_float(AVIOContext *pb, unsigned int elementid, double val)
9b6b0c79 243{
9b6b0c79 244 put_ebml_id(pb, elementid);
0f651e8c 245 put_ebml_num(pb, 8, 0);
3383a53e 246 avio_wb64(pb, av_double2int(val));
9b6b0c79
DC
247}
248
ae628ec1 249static void put_ebml_binary(AVIOContext *pb, unsigned int elementid,
4a6bef1f 250 const void *buf, int size)
67143c0f
DC
251{
252 put_ebml_id(pb, elementid);
0f651e8c 253 put_ebml_num(pb, size, 0);
77eb5504 254 avio_write(pb, buf, size);
67143c0f
DC
255}
256
f1f6156b
LB
257static void put_ebml_string(AVIOContext *pb, unsigned int elementid,
258 const char *str)
67143c0f
DC
259{
260 put_ebml_binary(pb, elementid, str, strlen(str));
261}
262
57848e9a 263/**
49bd8e4b 264 * Write a void element of a given size. Useful for reserving space in
cfde5d18 265 * the file to be written to later.
57848e9a 266 *
5045da83 267 * @param size The number of bytes to reserve, which must be at least 2.
57848e9a 268 */
ae628ec1 269static void put_ebml_void(AVIOContext *pb, uint64_t size)
f57b85a5 270{
a2704c97 271 int64_t currentpos = avio_tell(pb);
f57b85a5 272
c5cc9498 273 av_assert0(size >= 2);
f57b85a5
DC
274
275 put_ebml_id(pb, EBML_ID_VOID);
cfde5d18
DC
276 // we need to subtract the length needed to store the size from the
277 // size we need to reserve so 2 cases, we use 8 bytes to store the
278 // size if possible, 1 byte otherwise
f57b85a5 279 if (size < 10)
f1f6156b 280 put_ebml_num(pb, size - 1, 0);
f57b85a5 281 else
f1f6156b 282 put_ebml_num(pb, size - 9, 8);
5ceffb1b 283 ffio_fill(pb, 0, currentpos + size - avio_tell(pb));
f57b85a5
DC
284}
285
f1f6156b
LB
286static ebml_master start_ebml_master(AVIOContext *pb, unsigned int elementid,
287 uint64_t expectedsize)
67143c0f 288{
0f651e8c 289 int bytes = expectedsize ? ebml_num_size(expectedsize) : 8;
67143c0f 290 put_ebml_id(pb, elementid);
baf71dca 291 put_ebml_size_unknown(pb, bytes);
f1f6156b 292 return (ebml_master) {avio_tell(pb), bytes };
67143c0f
DC
293}
294
ae628ec1 295static void end_ebml_master(AVIOContext *pb, ebml_master master)
67143c0f 296{
a2704c97 297 int64_t pos = avio_tell(pb);
67143c0f 298
6b4aa5da 299 if (avio_seek(pb, master.pos - master.sizebytes, SEEK_SET) < 0)
ac9e1177 300 return;
0f651e8c 301 put_ebml_num(pb, pos - master.pos, master.sizebytes);
6b4aa5da 302 avio_seek(pb, pos, SEEK_SET);
67143c0f
DC
303}
304
ae628ec1 305static void put_xiph_size(AVIOContext *pb, int size)
86be6637 306{
5ceffb1b 307 ffio_fill(pb, 255, size / 255);
77eb5504 308 avio_w8(pb, size % 255);
86be6637
DC
309}
310
57848e9a 311/**
3dabebc2
NB
312 * Free the members allocated in the mux context.
313 */
314static void mkv_free(MatroskaMuxContext *mkv) {
315 if (mkv->main_seekhead) {
316 av_freep(&mkv->main_seekhead->entries);
317 av_freep(&mkv->main_seekhead);
318 }
319 if (mkv->cues) {
320 av_freep(&mkv->cues->entries);
321 av_freep(&mkv->cues);
322 }
323 av_freep(&mkv->tracks);
324 av_freep(&mkv->stream_durations);
325 av_freep(&mkv->stream_duration_offsets);
326}
327
328/**
cfde5d18
DC
329 * Initialize a mkv_seekhead element to be ready to index level 1 Matroska
330 * elements. If a maximum number of elements is specified, enough space
331 * will be reserved at the current file location to write a seek head of
332 * that size.
57848e9a 333 *
cfde5d18 334 * @param segment_offset The absolute offset to the position in the file
ab332d01
DC
335 * where the segment begins.
336 * @param numelements The maximum number of elements that will be indexed
cfde5d18 337 * by this seek head, 0 if unlimited.
57848e9a 338 */
f1f6156b
LB
339static mkv_seekhead *mkv_start_seekhead(AVIOContext *pb, int64_t segment_offset,
340 int numelements)
967d815a
DC
341{
342 mkv_seekhead *new_seekhead = av_mallocz(sizeof(mkv_seekhead));
f929ab05 343 if (!new_seekhead)
967d815a
DC
344 return NULL;
345
346 new_seekhead->segment_offset = segment_offset;
347
348 if (numelements > 0) {
a2704c97 349 new_seekhead->filepos = avio_tell(pb);
cfde5d18
DC
350 // 21 bytes max for a seek entry, 10 bytes max for the SeekHead ID
351 // and size, and 3 bytes to guarantee that an EBML void element
352 // will fit afterwards
baf71dca 353 new_seekhead->reserved_size = numelements * MAX_SEEKENTRY_SIZE + 13;
f1f6156b 354 new_seekhead->max_entries = numelements;
967d815a
DC
355 put_ebml_void(pb, new_seekhead->reserved_size);
356 }
357 return new_seekhead;
358}
359
360static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
361{
362 mkv_seekhead_entry *entries = seekhead->entries;
967d815a
DC
363
364 // don't store more elements than we reserved space for
365 if (seekhead->max_entries > 0 && seekhead->max_entries <= seekhead->num_entries)
366 return -1;
367
9bca8e53 368 entries = av_realloc_array(entries, seekhead->num_entries + 1, sizeof(mkv_seekhead_entry));
fb33bff9 369 if (!entries)
c9367c07 370 return AVERROR(ENOMEM);
ba5e7781 371 seekhead->entries = entries;
967d815a 372
00a63bfb
AK
373 seekhead->entries[seekhead->num_entries].elementid = elementid;
374 seekhead->entries[seekhead->num_entries++].segmentpos = filepos - seekhead->segment_offset;
967d815a 375
967d815a
DC
376 return 0;
377}
378
57848e9a 379/**
cfde5d18
DC
380 * Write the seek head to the file and free it. If a maximum number of
381 * elements was specified to mkv_start_seekhead(), the seek head will
382 * be written at the location reserved for it. Otherwise, it is written
383 * at the current location in the file.
57848e9a 384 *
7a2a4840
DC
385 * @return The file offset where the seekhead was written,
386 * -1 if an error occurred.
57848e9a 387 */
3dabebc2 388static int64_t mkv_write_seekhead(AVIOContext *pb, MatroskaMuxContext *mkv)
967d815a 389{
3dabebc2 390 mkv_seekhead *seekhead = mkv->main_seekhead;
baf71dca 391 ebml_master metaseek, seekentry;
bc5c918e 392 int64_t currentpos;
967d815a
DC
393 int i;
394
a2704c97 395 currentpos = avio_tell(pb);
967d815a 396
44729bc0
MS
397 if (seekhead->reserved_size > 0) {
398 if (avio_seek(pb, seekhead->filepos, SEEK_SET) < 0) {
399 currentpos = -1;
400 goto fail;
401 }
402 }
967d815a 403
baf71dca 404 metaseek = start_ebml_master(pb, MATROSKA_ID_SEEKHEAD, seekhead->reserved_size);
967d815a
DC
405 for (i = 0; i < seekhead->num_entries; i++) {
406 mkv_seekhead_entry *entry = &seekhead->entries[i];
407
baf71dca 408 seekentry = start_ebml_master(pb, MATROSKA_ID_SEEKENTRY, MAX_SEEKENTRY_SIZE);
967d815a
DC
409
410 put_ebml_id(pb, MATROSKA_ID_SEEKID);
0f651e8c 411 put_ebml_num(pb, ebml_id_size(entry->elementid), 0);
967d815a
DC
412 put_ebml_id(pb, entry->elementid);
413
414 put_ebml_uint(pb, MATROSKA_ID_SEEKPOSITION, entry->segmentpos);
415 end_ebml_master(pb, seekentry);
416 }
417 end_ebml_master(pb, metaseek);
418
419 if (seekhead->reserved_size > 0) {
a2704c97 420 uint64_t remaining = seekhead->filepos + seekhead->reserved_size - avio_tell(pb);
967d815a 421 put_ebml_void(pb, remaining);
6b4aa5da 422 avio_seek(pb, currentpos, SEEK_SET);
967d815a
DC
423
424 currentpos = seekhead->filepos;
425 }
44729bc0 426fail:
3dabebc2
NB
427 av_freep(&mkv->main_seekhead->entries);
428 av_freep(&mkv->main_seekhead);
967d815a
DC
429
430 return currentpos;
431}
432
f1f6156b 433static mkv_cues *mkv_start_cues(int64_t segment_offset)
6364d534
DC
434{
435 mkv_cues *cues = av_mallocz(sizeof(mkv_cues));
f929ab05 436 if (!cues)
6364d534
DC
437 return NULL;
438
439 cues->segment_offset = segment_offset;
440 return cues;
441}
442
37cef8c7
VV
443static int mkv_add_cuepoint(mkv_cues *cues, int stream, int tracknum, int64_t ts,
444 int64_t cluster_pos, int64_t relative_pos, int64_t duration)
6364d534
DC
445{
446 mkv_cuepoint *entries = cues->entries;
6364d534 447
4ffbe3f3
JG
448 if (ts < 0)
449 return 0;
450
9bca8e53 451 entries = av_realloc_array(entries, cues->num_entries + 1, sizeof(mkv_cuepoint));
fb33bff9 452 if (!entries)
c9367c07 453 return AVERROR(ENOMEM);
ba5e7781 454 cues->entries = entries;
6364d534 455
00a63bfb 456 cues->entries[cues->num_entries].pts = ts;
37cef8c7
VV
457 cues->entries[cues->num_entries].stream_idx = stream;
458 cues->entries[cues->num_entries].tracknum = tracknum;
ba5e7781 459 cues->entries[cues->num_entries].cluster_pos = cluster_pos - cues->segment_offset;
56f17407
JA
460 cues->entries[cues->num_entries].relative_pos = relative_pos;
461 cues->entries[cues->num_entries++].duration = duration;
6364d534 462
6364d534
DC
463 return 0;
464}
465
925f7980 466static int64_t mkv_write_cues(AVFormatContext *s, mkv_cues *cues, mkv_track *tracks, int num_tracks)
6364d534 467{
925f7980 468 AVIOContext *pb = s->pb;
baf71dca 469 ebml_master cues_element;
bc5c918e 470 int64_t currentpos;
6364d534
DC
471 int i, j;
472
a2704c97 473 currentpos = avio_tell(pb);
baf71dca 474 cues_element = start_ebml_master(pb, MATROSKA_ID_CUES, 0);
6364d534
DC
475
476 for (i = 0; i < cues->num_entries; i++) {
baf71dca 477 ebml_master cuepoint, track_positions;
6364d534
DC
478 mkv_cuepoint *entry = &cues->entries[i];
479 uint64_t pts = entry->pts;
64d029de 480 int ctp_nb = 0;
6364d534 481
64d029de
MN
482 // Calculate the number of entries, so we know the element size
483 for (j = 0; j < num_tracks; j++)
484 tracks[j].has_cue = 0;
485 for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
486 int tracknum = entry[j].stream_idx;
487 av_assert0(tracknum>=0 && tracknum<num_tracks);
488 if (tracks[tracknum].has_cue && s->streams[tracknum]->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
489 continue;
490 tracks[tracknum].has_cue = 1;
491 ctp_nb ++;
492 }
493
494 cuepoint = start_ebml_master(pb, MATROSKA_ID_POINTENTRY, MAX_CUEPOINT_SIZE(ctp_nb));
6364d534
DC
495 put_ebml_uint(pb, MATROSKA_ID_CUETIME, pts);
496
497 // put all the entries from different tracks that have the exact same
498 // timestamp into the same CuePoint
271f4112
SS
499 for (j = 0; j < num_tracks; j++)
500 tracks[j].has_cue = 0;
6364d534 501 for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
37cef8c7 502 int tracknum = entry[j].stream_idx;
285485ac 503 av_assert0(tracknum>=0 && tracknum<num_tracks);
925f7980 504 if (tracks[tracknum].has_cue && s->streams[tracknum]->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
271f4112 505 continue;
285485ac 506 tracks[tracknum].has_cue = 1;
baf71dca 507 track_positions = start_ebml_master(pb, MATROSKA_ID_CUETRACKPOSITION, MAX_CUETRACKPOS_SIZE);
c5f3cc40
BH
508 put_ebml_uint(pb, MATROSKA_ID_CUETRACK , entry[j].tracknum );
509 put_ebml_uint(pb, MATROSKA_ID_CUECLUSTERPOSITION , entry[j].cluster_pos);
510 put_ebml_uint(pb, MATROSKA_ID_CUERELATIVEPOSITION, entry[j].relative_pos);
56f17407
JA
511 if (entry[j].duration != -1)
512 put_ebml_uint(pb, MATROSKA_ID_CUEDURATION , entry[j].duration);
6364d534
DC
513 end_ebml_master(pb, track_positions);
514 }
515 i += j - 1;
516 end_ebml_master(pb, cuepoint);
517 }
518 end_ebml_master(pb, cues_element);
519
6364d534
DC
520 return currentpos;
521}
522
ae628ec1 523static int put_xiph_codecpriv(AVFormatContext *s, AVIOContext *pb, AVCodecContext *codec)
56d55a3b 524{
ad2deb02 525 const uint8_t *header_start[3];
56d55a3b
DC
526 int header_len[3];
527 int first_header_size;
86be6637 528 int j;
56d55a3b 529
36ef5369 530 if (codec->codec_id == AV_CODEC_ID_VORBIS)
56d55a3b
DC
531 first_header_size = 30;
532 else
533 first_header_size = 42;
534
357db4c2 535 if (avpriv_split_xiph_headers(codec->extradata, codec->extradata_size,
56d55a3b 536 first_header_size, header_start, header_len) < 0) {
b62a33d0 537 av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
56d55a3b
DC
538 return -1;
539 }
540
77eb5504 541 avio_w8(pb, 2); // number packets - 1
56d55a3b 542 for (j = 0; j < 2; j++) {
86be6637 543 put_xiph_size(pb, header_len[j]);
56d55a3b
DC
544 }
545 for (j = 0; j < 3; j++)
77eb5504 546 avio_write(pb, header_start[j], header_len[j]);
801edb42
DC
547
548 return 0;
56d55a3b 549}
67143c0f 550
01656fd4
AK
551static int put_wv_codecpriv(AVIOContext *pb, AVCodecContext *codec)
552{
553 if (codec->extradata && codec->extradata_size == 2)
554 avio_write(pb, codec->extradata, 2);
555 else
556 avio_wl16(pb, 0x403); // fallback to the version mentioned in matroska specs
557 return 0;
558}
559
106b62f4
AK
560static int put_flac_codecpriv(AVFormatContext *s,
561 AVIOContext *pb, AVCodecContext *codec)
562{
563 int write_comment = (codec->channel_layout &&
564 !(codec->channel_layout & ~0x3ffffULL) &&
565 !ff_flac_is_native_layout(codec->channel_layout));
e19d48df
AK
566 int ret = ff_flac_write_header(pb, codec->extradata, codec->extradata_size,
567 !write_comment);
106b62f4
AK
568
569 if (ret < 0)
570 return ret;
571
572 if (write_comment) {
573 const char *vendor = (s->flags & AVFMT_FLAG_BITEXACT) ?
cf3a038f 574 "Lavf" : LIBAVFORMAT_IDENT;
106b62f4
AK
575 AVDictionary *dict = NULL;
576 uint8_t buf[32], *data, *p;
66f26b3e 577 int64_t len;
106b62f4
AK
578
579 snprintf(buf, sizeof(buf), "0x%"PRIx64, codec->channel_layout);
580 av_dict_set(&dict, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", buf, 0);
581
582 len = ff_vorbiscomment_length(dict, vendor);
66f26b3e
MN
583 if (len >= ((1<<24) - 4))
584 return AVERROR(EINVAL);
585
106b62f4
AK
586 data = av_malloc(len + 4);
587 if (!data) {
588 av_dict_free(&dict);
589 return AVERROR(ENOMEM);
590 }
591
592 data[0] = 0x84;
593 AV_WB24(data + 1, len);
594
595 p = data + 4;
596 ff_vorbiscomment_write(&p, &dict, vendor);
597
598 avio_write(pb, data, len + 4);
599
600 av_freep(&data);
601 av_dict_free(&dict);
602 }
603
604 return 0;
605}
606
51da7d02
AK
607static int get_aac_sample_rates(AVFormatContext *s, AVCodecContext *codec,
608 int *sample_rate, int *output_sample_rate)
07918a22 609{
bc17bd90 610 MPEG4AudioConfig mp4ac;
07918a22 611
fd095539
JG
612 if (avpriv_mpeg4audio_get_config(&mp4ac, codec->extradata,
613 codec->extradata_size * 8, 1) < 0) {
51da7d02 614 av_log(s, AV_LOG_ERROR,
f1f6156b 615 "Error parsing AAC extradata, unable to determine samplerate.\n");
51da7d02 616 return AVERROR(EINVAL);
07918a22
DC
617 }
618
bc17bd90
AK
619 *sample_rate = mp4ac.sample_rate;
620 *output_sample_rate = mp4ac.ext_sample_rate;
51da7d02 621 return 0;
07918a22
DC
622}
623
b75a1f98
LB
624static int mkv_write_native_codecprivate(AVFormatContext *s,
625 AVCodecContext *codec,
626 AVIOContext *dyn_cp)
627{
628 switch (codec->codec_id) {
629 case AV_CODEC_ID_VORBIS:
630 case AV_CODEC_ID_THEORA:
631 return put_xiph_codecpriv(s, dyn_cp, codec);
632 case AV_CODEC_ID_FLAC:
633 return put_flac_codecpriv(s, dyn_cp, codec);
634 case AV_CODEC_ID_WAVPACK:
635 return put_wv_codecpriv(dyn_cp, codec);
636 case AV_CODEC_ID_H264:
637 return ff_isom_write_avcc(dyn_cp, codec->extradata,
638 codec->extradata_size);
639 case AV_CODEC_ID_HEVC:
7a5356c7
CEH
640 ff_isom_write_hvcc(dyn_cp, codec->extradata,
641 codec->extradata_size, 0);
642 return 0;
b75a1f98
LB
643 case AV_CODEC_ID_ALAC:
644 if (codec->extradata_size < 36) {
645 av_log(s, AV_LOG_ERROR,
646 "Invalid extradata found, ALAC expects a 36-byte "
647 "QuickTime atom.");
648 return AVERROR_INVALIDDATA;
649 } else
650 avio_write(dyn_cp, codec->extradata + 12,
651 codec->extradata_size - 12);
652 break;
653 default:
ee78b0c2
MN
654 if (codec->codec_id == AV_CODEC_ID_PRORES &&
655 ff_codec_get_id(ff_codec_movvideo_tags, codec->codec_tag) == AV_CODEC_ID_PRORES) {
656 avio_wl32(dyn_cp, codec->codec_tag);
657 } else if (codec->extradata_size && codec->codec_id != AV_CODEC_ID_TTA)
658 avio_write(dyn_cp, codec->extradata, codec->extradata_size);
b75a1f98
LB
659 }
660
661 return 0;
662}
663
f1f6156b
LB
664static int mkv_write_codecprivate(AVFormatContext *s, AVIOContext *pb,
665 AVCodecContext *codec, int native_id,
666 int qt_id)
5c559894 667{
ae628ec1 668 AVIOContext *dyn_cp;
46d18a88 669 uint8_t *codecpriv;
899681cd 670 int ret, codecpriv_size;
46d18a88 671
b92c5452 672 ret = avio_open_dyn_buf(&dyn_cp);
f1f6156b 673 if (ret < 0)
899681cd 674 return ret;
5c559894
DC
675
676 if (native_id) {
b75a1f98 677 ret = mkv_write_native_codecprivate(s, codec, dyn_cp);
72415b2a 678 } else if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
f009e36f
AJ
679 if (qt_id) {
680 if (!codec->codec_tag)
f1f6156b
LB
681 codec->codec_tag = ff_codec_get_tag(ff_codec_movvideo_tags,
682 codec->codec_id);
8456bd2c
MN
683 if (codec->extradata_size) {
684 if ( ff_codec_get_id(ff_codec_movvideo_tags, codec->codec_tag) == codec->codec_id
8365287e 685 && ff_codec_get_id(ff_codec_movvideo_tags, AV_RL32(codec->extradata + 4)) != codec->codec_id
8456bd2c
MN
686 ) {
687 int i;
688 avio_wb32(dyn_cp, 0x5a + codec->extradata_size);
689 avio_wl32(dyn_cp, codec->codec_tag);
8365287e 690 for(i = 0; i < 0x5a - 8; i++)
8456bd2c
MN
691 avio_w8(dyn_cp, 0);
692 }
77eb5504 693 avio_write(dyn_cp, codec->extradata, codec->extradata_size);
8456bd2c 694 }
f009e36f 695 } else {
f5f6e594
PR
696 if (!ff_codec_get_tag(ff_codec_bmp_tags, codec->codec_id))
697 av_log(s, AV_LOG_WARNING, "codec %s is not supported by this format\n",
698 avcodec_get_name(codec->codec_id));
699
434a70b8 700 if (!codec->codec_tag)
f1f6156b
LB
701 codec->codec_tag = ff_codec_get_tag(ff_codec_bmp_tags,
702 codec->codec_id);
e2fb12b6 703 if (!codec->codec_tag && codec->codec_id != AV_CODEC_ID_RAWVIDEO) {
6b171f04
SS
704 av_log(s, AV_LOG_ERROR, "No bmp codec tag found for codec %s\n",
705 avcodec_get_name(codec->codec_id));
706 ret = AVERROR(EINVAL);
434a70b8 707 }
5c559894 708
fcbb9471 709 ff_put_bmp_header(dyn_cp, codec, ff_codec_bmp_tags, 0, 0);
f009e36f 710 }
72415b2a 711 } else if (codec->codec_type == AVMEDIA_TYPE_AUDIO) {
4896dd57
JM
712 unsigned int tag;
713 tag = ff_codec_get_tag(ff_codec_wav_tags, codec->codec_id);
714 if (!tag) {
6b171f04
SS
715 av_log(s, AV_LOG_ERROR, "No wav codec tag found for codec %s\n",
716 avcodec_get_name(codec->codec_id));
717 ret = AVERROR(EINVAL);
5c559894 718 }
4896dd57
JM
719 if (!codec->codec_tag)
720 codec->codec_tag = tag;
5c559894 721
5e7d21c7 722 ff_put_wav_header(dyn_cp, codec, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX);
5c559894 723 }
46d18a88 724
6dc7d80d 725 codecpriv_size = avio_close_dyn_buf(dyn_cp, &codecpriv);
46d18a88 726 if (codecpriv_size)
f1f6156b
LB
727 put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codecpriv,
728 codecpriv_size);
46d18a88
DC
729 av_free(codecpriv);
730 return ret;
5c559894
DC
731}
732
39cd9fdb 733
4d686fb7 734static int mkv_write_stereo_mode(AVFormatContext *s, AVIOContext *pb,
f769671f 735 AVStream *st, int mode, int *h_width, int *h_height)
48e64324 736{
4d686fb7 737 int i;
39cd9fdb 738 int ret = 0;
4d686fb7
VG
739 AVDictionaryEntry *tag;
740 MatroskaVideoStereoModeType format = MATROSKA_VIDEO_STEREOMODE_TYPE_NB;
741
f769671f
MN
742 *h_width = 1;
743 *h_height = 1;
4d686fb7 744 // convert metadata into proper side data and add it to the stream
39cd9fdb
MN
745 if ((tag = av_dict_get(st->metadata, "stereo_mode", NULL, 0)) ||
746 (tag = av_dict_get( s->metadata, "stereo_mode", NULL, 0))) {
4d686fb7 747 int stereo_mode = atoi(tag->value);
39cd9fdb 748
37520a91 749 for (i=0; i<MATROSKA_VIDEO_STEREOMODE_TYPE_NB; i++)
39cd9fdb
MN
750 if (!strcmp(tag->value, ff_matroska_video_stereo_mode[i])){
751 stereo_mode = i;
752 break;
753 }
754
4d686fb7
VG
755 if (stereo_mode < MATROSKA_VIDEO_STEREOMODE_TYPE_NB &&
756 stereo_mode != 10 && stereo_mode != 12) {
757 int ret = ff_mkv_stereo3d_conv(st, stereo_mode);
758 if (ret < 0)
759 return ret;
760 }
761 }
48e64324 762
090c67d5 763 // iterate to find the stereo3d side data
4d686fb7
VG
764 for (i = 0; i < st->nb_side_data; i++) {
765 AVPacketSideData sd = st->side_data[i];
766 if (sd.type == AV_PKT_DATA_STEREO3D) {
767 AVStereo3D *stereo = (AVStereo3D *)sd.data;
768
769 switch (stereo->type) {
770 case AV_STEREO3D_2D:
771 format = MATROSKA_VIDEO_STEREOMODE_TYPE_MONO;
772 break;
773 case AV_STEREO3D_SIDEBYSIDE:
774 format = (stereo->flags & AV_STEREO3D_FLAG_INVERT)
775 ? MATROSKA_VIDEO_STEREOMODE_TYPE_RIGHT_LEFT
776 : MATROSKA_VIDEO_STEREOMODE_TYPE_LEFT_RIGHT;
f769671f 777 *h_width = 2;
4d686fb7
VG
778 break;
779 case AV_STEREO3D_TOPBOTTOM:
780 format = MATROSKA_VIDEO_STEREOMODE_TYPE_TOP_BOTTOM;
781 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
782 format--;
f769671f 783 *h_height = 2;
4d686fb7
VG
784 break;
785 case AV_STEREO3D_CHECKERBOARD:
786 format = MATROSKA_VIDEO_STEREOMODE_TYPE_CHECKERBOARD_LR;
787 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
788 format--;
789 break;
790 case AV_STEREO3D_LINES:
791 format = MATROSKA_VIDEO_STEREOMODE_TYPE_ROW_INTERLEAVED_LR;
792 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
793 format--;
f769671f 794 *h_height = 2;
4d686fb7
VG
795 break;
796 case AV_STEREO3D_COLUMNS:
797 format = MATROSKA_VIDEO_STEREOMODE_TYPE_COL_INTERLEAVED_LR;
798 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
799 format--;
f769671f 800 *h_width = 2;
4d686fb7
VG
801 break;
802 case AV_STEREO3D_FRAMESEQUENCE:
803 format = MATROSKA_VIDEO_STEREOMODE_TYPE_BOTH_EYES_BLOCK_LR;
804 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
805 format++;
806 break;
807 }
4d686fb7
VG
808 break;
809 }
48e64324
LB
810 }
811
39cd9fdb
MN
812 if (format == MATROSKA_VIDEO_STEREOMODE_TYPE_NB)
813 return ret;
814
090c67d5 815 // if webm, do not write unsupported modes
39cd9fdb
MN
816 if ((mode == MODE_WEBM &&
817 format > MATROSKA_VIDEO_STEREOMODE_TYPE_TOP_BOTTOM &&
818 format != MATROSKA_VIDEO_STEREOMODE_TYPE_RIGHT_LEFT)
37520a91 819 || format >= MATROSKA_VIDEO_STEREOMODE_TYPE_NB) {
141ee109
MN
820 av_log(s, AV_LOG_ERROR,
821 "The specified stereo mode is not valid.\n");
4d686fb7 822 format = MATROSKA_VIDEO_STEREOMODE_TYPE_NB;
141ee109 823 return AVERROR(EINVAL);
39cd9fdb 824 }
48e64324 825
090c67d5 826 // write StereoMode if format is valid
39cd9fdb 827 put_ebml_uint(pb, MATROSKA_ID_VIDEOSTEREOMODE, format);
4d686fb7 828
39cd9fdb 829 return ret;
48e64324
LB
830}
831
b75a1f98 832static int mkv_write_track(AVFormatContext *s, MatroskaMuxContext *mkv,
ee78b0c2 833 int i, AVIOContext *pb, int default_stream_exists)
67143c0f 834{
b75a1f98
LB
835 AVStream *st = s->streams[i];
836 AVCodecContext *codec = st->codec;
837 ebml_master subinfo, track;
838 int native_id = 0;
839 int qt_id = 0;
840 int bit_depth = av_get_bits_per_sample(codec->codec_id);
841 int sample_rate = codec->sample_rate;
842 int output_sample_rate = 0;
ee78b0c2
MN
843 int display_width_div = 1;
844 int display_height_div = 1;
b75a1f98
LB
845 int j, ret;
846 AVDictionaryEntry *tag;
847
b75a1f98
LB
848 if (codec->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
849 mkv->have_attachments = 1;
850 return 0;
91f35929 851 }
c7a63a52 852
ee78b0c2 853 if (!bit_depth && codec->codec_id != AV_CODEC_ID_ADPCM_G726)
b75a1f98 854 bit_depth = av_get_bytes_per_sample(codec->sample_fmt) << 3;
ee78b0c2
MN
855 if (!bit_depth)
856 bit_depth = codec->bits_per_coded_sample;
967d815a 857
51da7d02
AK
858 if (codec->codec_id == AV_CODEC_ID_AAC) {
859 ret = get_aac_sample_rates(s, codec, &sample_rate, &output_sample_rate);
860 if (ret < 0)
861 return ret;
862 }
c7a63a52 863
b75a1f98 864 track = start_ebml_master(pb, MATROSKA_ID_TRACKENTRY, 0);
ee78b0c2
MN
865 put_ebml_uint (pb, MATROSKA_ID_TRACKNUMBER,
866 mkv->is_dash ? mkv->dash_track_number : i + 1);
867 put_ebml_uint (pb, MATROSKA_ID_TRACKUID,
868 mkv->is_dash ? mkv->dash_track_number : i + 1);
b75a1f98 869 put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0); // no lacing (yet)
a6da1aa0 870
b75a1f98
LB
871 if ((tag = av_dict_get(st->metadata, "title", NULL, 0)))
872 put_ebml_string(pb, MATROSKA_ID_TRACKNAME, tag->value);
873 tag = av_dict_get(st->metadata, "language", NULL, 0);
ee78b0c2 874 if (mkv->mode != MODE_WEBM || codec->codec_id != AV_CODEC_ID_WEBVTT) {
73b7a360 875 put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag && tag->value ? tag->value:"und");
ee78b0c2
MN
876 } else if (tag && tag->value) {
877 put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag->value);
878 }
f622c4f4 879
b75a1f98
LB
880 // The default value for TRACKFLAGDEFAULT is 1, so add element
881 // if we need to clear it.
ee78b0c2 882 if (default_stream_exists && !(st->disposition & AV_DISPOSITION_DEFAULT))
b75a1f98 883 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGDEFAULT, !!(st->disposition & AV_DISPOSITION_DEFAULT));
f622c4f4 884
ee78b0c2
MN
885 if (st->disposition & AV_DISPOSITION_FORCED)
886 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGFORCED, 1);
887
888 if (mkv->mode == MODE_WEBM && codec->codec_id == AV_CODEC_ID_WEBVTT) {
889 const char *codec_id;
890 if (st->disposition & AV_DISPOSITION_CAPTIONS) {
891 codec_id = "D_WEBVTT/CAPTIONS";
892 native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
893 } else if (st->disposition & AV_DISPOSITION_DESCRIPTIONS) {
894 codec_id = "D_WEBVTT/DESCRIPTIONS";
895 native_id = MATROSKA_TRACK_TYPE_METADATA;
896 } else if (st->disposition & AV_DISPOSITION_METADATA) {
897 codec_id = "D_WEBVTT/METADATA";
898 native_id = MATROSKA_TRACK_TYPE_METADATA;
509642b4 899 } else {
ee78b0c2
MN
900 codec_id = "D_WEBVTT/SUBTITLES";
901 native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
902 }
903 put_ebml_string(pb, MATROSKA_ID_CODECID, codec_id);
904 } else {
905 // look for a codec ID string specific to mkv to use,
906 // if none are found, use AVI codes
907 for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
908 if (ff_mkv_codec_tags[j].id == codec->codec_id) {
909 put_ebml_string(pb, MATROSKA_ID_CODECID, ff_mkv_codec_tags[j].str);
910 native_id = 1;
911 break;
f622c4f4
DC
912 }
913 }
7d60baa8
MN
914 if (codec->codec_id == AV_CODEC_ID_RAWVIDEO && !codec->codec_tag) {
915 if (mkv->allow_raw_vfw) {
916 native_id = 0;
917 } else {
918 av_log(s, AV_LOG_ERROR, "Raw RGB is not supported Natively in Matroska, you can use AVI or NUT or\n"
919 "If you would like to store it anyway using VFW mode, enable allow_raw_vfw (-allow_raw_vfw 1)\n");
920 return AVERROR(EINVAL);
921 }
922 }
ee78b0c2 923 }
f622c4f4 924
4694c0bb 925 if (codec->codec_type == AVMEDIA_TYPE_AUDIO && codec->initial_padding && codec->codec_id == AV_CODEC_ID_OPUS) {
e6971db1 926 int64_t codecdelay = av_rescale_q(codec->initial_padding,
c3c22bee 927 (AVRational){ 1, 48000 },
e6971db1
MN
928 (AVRational){ 1, 1000000000 });
929 if (codecdelay < 0) {
930 av_log(s, AV_LOG_ERROR, "Initial padding is invalid\n");
931 return AVERROR(EINVAL);
932 }
4694c0bb 933// mkv->tracks[i].ts_offset = av_rescale_q(codec->initial_padding,
ee78b0c2
MN
934// (AVRational){ 1, codec->sample_rate },
935// st->time_base);
a1aa37dd 936
e6971db1 937 put_ebml_uint(pb, MATROSKA_ID_CODECDELAY, codecdelay);
b75a1f98 938 }
ee78b0c2
MN
939 if (codec->codec_id == AV_CODEC_ID_OPUS) {
940 put_ebml_uint(pb, MATROSKA_ID_SEEKPREROLL, OPUS_SEEK_PREROLL);
b75a1f98 941 }
571efd97 942
b75a1f98
LB
943 if (mkv->mode == MODE_WEBM && !(codec->codec_id == AV_CODEC_ID_VP8 ||
944 codec->codec_id == AV_CODEC_ID_VP9 ||
945 codec->codec_id == AV_CODEC_ID_OPUS ||
ee78b0c2
MN
946 codec->codec_id == AV_CODEC_ID_VORBIS ||
947 codec->codec_id == AV_CODEC_ID_WEBVTT)) {
b75a1f98 948 av_log(s, AV_LOG_ERROR,
ee78b0c2 949 "Only VP8 or VP9 video and Vorbis or Opus audio and WebVTT subtitles are supported for WebM.\n");
b75a1f98
LB
950 return AVERROR(EINVAL);
951 }
a1aa37dd 952
b75a1f98
LB
953 switch (codec->codec_type) {
954 case AVMEDIA_TYPE_VIDEO:
955 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_VIDEO);
ee78b0c2
MN
956
957 if( st->avg_frame_rate.num > 0 && st->avg_frame_rate.den > 0
cf86fd00
MN
958 && av_cmp_q(av_inv_q(st->avg_frame_rate), codec->time_base) > 0)
959 put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, 1000000000LL * st->avg_frame_rate.den / st->avg_frame_rate.num);
ee78b0c2 960 else
cf86fd00 961 put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, 1000000000LL * codec->time_base.num / codec->time_base.den);
b75a1f98
LB
962
963 if (!native_id &&
964 ff_codec_get_tag(ff_codec_movvideo_tags, codec->codec_id) &&
e2fb12b6 965 ((!ff_codec_get_tag(ff_codec_bmp_tags, codec->codec_id) && codec->codec_id != AV_CODEC_ID_RAWVIDEO) ||
b75a1f98
LB
966 codec->codec_id == AV_CODEC_ID_SVQ1 ||
967 codec->codec_id == AV_CODEC_ID_SVQ3 ||
968 codec->codec_id == AV_CODEC_ID_CINEPAK))
969 qt_id = 1;
970
971 if (qt_id)
972 put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");
973 else if (!native_id) {
974 // if there is no mkv-specific codec ID, use VFW mode
975 put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");
976 mkv->tracks[i].write_dts = 1;
9d4fdfe2 977 s->internal->avoid_negative_ts_use_pts = 0;
316d6c15
JZ
978 }
979
b75a1f98
LB
980 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
981 // XXX: interlace flag?
982 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , codec->width);
983 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, codec->height);
c301d5ae 984
4d686fb7
VG
985 // check both side data and metadata for stereo information,
986 // write the result to the bitstream if any is found
f769671f
MN
987 ret = mkv_write_stereo_mode(s, pb, st, mkv->mode,
988 &display_width_div,
989 &display_height_div);
4d686fb7
VG
990 if (ret < 0)
991 return ret;
992
c2c4cee8
MN
993 if (((tag = av_dict_get(st->metadata, "alpha_mode", NULL, 0)) && atoi(tag->value)) ||
994 ((tag = av_dict_get( s->metadata, "alpha_mode", NULL, 0)) && atoi(tag->value)) ||
ee78b0c2
MN
995 (codec->pix_fmt == AV_PIX_FMT_YUVA420P)) {
996 put_ebml_uint(pb, MATROSKA_ID_VIDEOALPHAMODE, 1);
b75a1f98 997 }
509642b4 998
f769671f
MN
999 // write DisplayWidth and DisplayHeight, they contain the size of
1000 // a single source view and/or the display aspect ratio
b75a1f98 1001 if (st->sample_aspect_ratio.num) {
ee78b0c2
MN
1002 int64_t d_width = av_rescale(codec->width, st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
1003 if (d_width > INT_MAX) {
1004 av_log(s, AV_LOG_ERROR, "Overflow in display width\n");
1005 return AVERROR(EINVAL);
f1f6156b 1006 }
ee78b0c2
MN
1007 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , d_width / display_width_div);
1008 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, codec->height / display_height_div);
1009 } else if (display_width_div != 1 || display_height_div != 1) {
1010 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , codec->width / display_width_div);
1011 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, codec->height / display_height_div);
f622c4f4 1012 }
509642b4 1013
ee78b0c2
MN
1014 if (codec->codec_id == AV_CODEC_ID_RAWVIDEO) {
1015 uint32_t color_space = av_le2ne32(codec->codec_tag);
1016 put_ebml_binary(pb, MATROSKA_ID_VIDEOCOLORSPACE, &color_space, sizeof(color_space));
509642b4 1017 }
f769671f 1018
b75a1f98
LB
1019 end_ebml_master(pb, subinfo);
1020 break;
1021
1022 case AVMEDIA_TYPE_AUDIO:
1023 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_AUDIO);
1024
1025 if (!native_id)
1026 // no mkv-specific ID, use ACM mode
1027 put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");
1028
1029 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);
1030 put_ebml_uint (pb, MATROSKA_ID_AUDIOCHANNELS , codec->channels);
1031 put_ebml_float (pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, sample_rate);
1032 if (output_sample_rate)
1033 put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
1034 if (bit_depth)
1035 put_ebml_uint(pb, MATROSKA_ID_AUDIOBITDEPTH, bit_depth);
1036 end_ebml_master(pb, subinfo);
1037 break;
1038
1039 case AVMEDIA_TYPE_SUBTITLE:
b75a1f98
LB
1040 if (!native_id) {
1041 av_log(s, AV_LOG_ERROR, "Subtitle codec %d is not supported.\n", codec->codec_id);
1042 return AVERROR(ENOSYS);
1043 }
ee78b0c2
MN
1044
1045 if (mkv->mode != MODE_WEBM || codec->codec_id != AV_CODEC_ID_WEBVTT)
1046 native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
1047
1048 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, native_id);
b75a1f98
LB
1049 break;
1050 default:
1051 av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.\n");
ee78b0c2
MN
1052 return AVERROR(EINVAL);
1053 }
1054
1055 if (mkv->mode != MODE_WEBM || codec->codec_id != AV_CODEC_ID_WEBVTT) {
1056 ret = mkv_write_codecprivate(s, pb, codec, native_id, qt_id);
1057 if (ret < 0)
1058 return ret;
b75a1f98 1059 }
316d6c15 1060
b75a1f98 1061 end_ebml_master(pb, track);
c301d5ae 1062
b75a1f98
LB
1063 return 0;
1064}
f1f6156b 1065
b75a1f98
LB
1066static int mkv_write_tracks(AVFormatContext *s)
1067{
1068 MatroskaMuxContext *mkv = s->priv_data;
1069 AVIOContext *pb = s->pb;
1070 ebml_master tracks;
ee78b0c2 1071 int i, ret, default_stream_exists = 0;
5c559894 1072
b75a1f98
LB
1073 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TRACKS, avio_tell(pb));
1074 if (ret < 0)
1075 return ret;
1076
1077 tracks = start_ebml_master(pb, MATROSKA_ID_TRACKS, 0);
1078 for (i = 0; i < s->nb_streams; i++) {
ee78b0c2
MN
1079 AVStream *st = s->streams[i];
1080 default_stream_exists |= st->disposition & AV_DISPOSITION_DEFAULT;
1081 }
1082 for (i = 0; i < s->nb_streams; i++) {
1083 ret = mkv_write_track(s, mkv, i, pb, default_stream_exists);
f1f6156b
LB
1084 if (ret < 0)
1085 return ret;
67143c0f
DC
1086 }
1087 end_ebml_master(pb, tracks);
801edb42 1088 return 0;
5034ab90
DC
1089}
1090
2bd0758e
AK
1091static int mkv_write_chapters(AVFormatContext *s)
1092{
1093 MatroskaMuxContext *mkv = s->priv_data;
ae628ec1 1094 AVIOContext *pb = s->pb;
2bd0758e
AK
1095 ebml_master chapters, editionentry;
1096 AVRational scale = {1, 1E9};
1097 int i, ret;
1098
26b241c0 1099 if (!s->nb_chapters || mkv->wrote_chapters)
2bd0758e
AK
1100 return 0;
1101
a2704c97 1102 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CHAPTERS, avio_tell(pb));
2bd0758e
AK
1103 if (ret < 0) return ret;
1104
1105 chapters = start_ebml_master(pb, MATROSKA_ID_CHAPTERS , 0);
1106 editionentry = start_ebml_master(pb, MATROSKA_ID_EDITIONENTRY, 0);
1107 put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGDEFAULT, 1);
1108 put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGHIDDEN , 0);
1109 for (i = 0; i < s->nb_chapters; i++) {
1110 ebml_master chapteratom, chapterdisplay;
1111 AVChapter *c = s->chapters[i];
a4cd057b
MN
1112 int64_t chapterstart = av_rescale_q(c->start, c->time_base, scale);
1113 int64_t chapterend = av_rescale_q(c->end, c->time_base, scale);
d2d67e42 1114 AVDictionaryEntry *t = NULL;
9f25a109 1115 if (chapterstart < 0 || chapterstart > chapterend || chapterend < 0) {
9272c965
VG
1116 av_log(s, AV_LOG_ERROR,
1117 "Invalid chapter start (%"PRId64") or end (%"PRId64").\n",
9f25a109 1118 chapterstart, chapterend);
5dc47a2b 1119 return AVERROR_INVALIDDATA;
9f25a109 1120 }
2bd0758e
AK
1121
1122 chapteratom = start_ebml_master(pb, MATROSKA_ID_CHAPTERATOM, 0);
07704c61 1123 put_ebml_uint(pb, MATROSKA_ID_CHAPTERUID, c->id + mkv->chapter_id_offset);
5dc47a2b
VG
1124 put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMESTART, chapterstart);
1125 put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMEEND, chapterend);
2bd0758e
AK
1126 put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGHIDDEN , 0);
1127 put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGENABLED, 1);
d2d67e42 1128 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
2bd0758e
AK
1129 chapterdisplay = start_ebml_master(pb, MATROSKA_ID_CHAPTERDISPLAY, 0);
1130 put_ebml_string(pb, MATROSKA_ID_CHAPSTRING, t->value);
1131 put_ebml_string(pb, MATROSKA_ID_CHAPLANG , "und");
1132 end_ebml_master(pb, chapterdisplay);
1133 }
1134 end_ebml_master(pb, chapteratom);
1135 }
1136 end_ebml_master(pb, editionentry);
1137 end_ebml_master(pb, chapters);
26b241c0
JS
1138
1139 mkv->wrote_chapters = 1;
2bd0758e
AK
1140 return 0;
1141}
1142
b1306823 1143static int mkv_write_simpletag(AVIOContext *pb, AVDictionaryEntry *t)
9b75309c
AK
1144{
1145 uint8_t *key = av_strdup(t->key);
1146 uint8_t *p = key;
1147 const uint8_t *lang = NULL;
1148 ebml_master tag;
1149
b1306823
VG
1150 if (!key)
1151 return AVERROR(ENOMEM);
1152
9b75309c
AK
1153 if ((p = strrchr(p, '-')) &&
1154 (lang = av_convert_lang_to(p + 1, AV_LANG_ISO639_2_BIBL)))
1155 *p = 0;
1156
1157 p = key;
1158 while (*p) {
1159 if (*p == ' ')
1160 *p = '_';
1161 else if (*p >= 'a' && *p <= 'z')
1162 *p -= 'a' - 'A';
1163 p++;
1164 }
1165
1166 tag = start_ebml_master(pb, MATROSKA_ID_SIMPLETAG, 0);
1167 put_ebml_string(pb, MATROSKA_ID_TAGNAME, key);
1168 if (lang)
1169 put_ebml_string(pb, MATROSKA_ID_TAGLANG, lang);
1170 put_ebml_string(pb, MATROSKA_ID_TAGSTRING, t->value);
1171 end_ebml_master(pb, tag);
1172
1173 av_freep(&key);
b1306823 1174 return 0;
9b75309c
AK
1175}
1176
31852540
SI
1177static int mkv_write_tag_targets(AVFormatContext *s,
1178 unsigned int elementid, unsigned int uid,
1179 ebml_master *tags, ebml_master* tag)
9b75309c
AK
1180{
1181 MatroskaMuxContext *mkv = s->priv_data;
31852540 1182 ebml_master targets;
9b75309c
AK
1183 int ret;
1184
1185 if (!tags->pos) {
a2704c97 1186 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TAGS, avio_tell(s->pb));
9b75309c
AK
1187 if (ret < 0) return ret;
1188
1189 *tags = start_ebml_master(s->pb, MATROSKA_ID_TAGS, 0);
1190 }
1191
31852540 1192 *tag = start_ebml_master(s->pb, MATROSKA_ID_TAG, 0);
9b75309c
AK
1193 targets = start_ebml_master(s->pb, MATROSKA_ID_TAGTARGETS, 0);
1194 if (elementid)
1195 put_ebml_uint(s->pb, elementid, uid);
1196 end_ebml_master(s->pb, targets);
31852540
SI
1197 return 0;
1198}
1199
1200static int mkv_write_tag(AVFormatContext *s, AVDictionary *m, unsigned int elementid,
1201 unsigned int uid, ebml_master *tags)
1202{
1203 ebml_master tag;
1204 int ret;
1205 AVDictionaryEntry *t = NULL;
1206
1207 ret = mkv_write_tag_targets(s, elementid, uid, tags, &tag);
1208 if (ret < 0)
1209 return ret;
9b75309c 1210
b1306823 1211 while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX))) {
0092c1dd 1212 if (av_strcasecmp(t->key, "title") &&
4cb68141 1213 av_strcasecmp(t->key, "stereo_mode") &&
66e85a18 1214 av_strcasecmp(t->key, "creation_time") &&
f56a0855
JS
1215 av_strcasecmp(t->key, "encoding_tool") &&
1216 (elementid != MATROSKA_ID_TAGTARGETS_TRACKUID ||
1217 av_strcasecmp(t->key, "language"))) {
b1306823
VG
1218 ret = mkv_write_simpletag(s->pb, t);
1219 if (ret < 0)
1220 return ret;
1221 }
1222 }
9b75309c
AK
1223
1224 end_ebml_master(s->pb, tag);
1225 return 0;
1226}
1227
088ed531
JA
1228static int mkv_check_tag(AVDictionary *m)
1229{
1230 AVDictionaryEntry *t = NULL;
088ed531
JA
1231
1232 while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX)))
1233 if (av_strcasecmp(t->key, "title") && av_strcasecmp(t->key, "stereo_mode"))
066111bf 1234 return 1;
088ed531 1235
066111bf 1236 return 0;
088ed531
JA
1237}
1238
9b75309c
AK
1239static int mkv_write_tags(AVFormatContext *s)
1240{
07704c61 1241 MatroskaMuxContext *mkv = s->priv_data;
9b75309c
AK
1242 ebml_master tags = {0};
1243 int i, ret;
1244
03700d39
AK
1245 ff_metadata_conv_ctx(s, ff_mkv_metadata_conv, NULL);
1246
088ed531 1247 if (mkv_check_tag(s->metadata)) {
9b75309c
AK
1248 ret = mkv_write_tag(s, s->metadata, 0, 0, &tags);
1249 if (ret < 0) return ret;
1250 }
1251
1252 for (i = 0; i < s->nb_streams; i++) {
1253 AVStream *st = s->streams[i];
1254
088ed531 1255 if (!mkv_check_tag(st->metadata))
9b75309c
AK
1256 continue;
1257
1258 ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &tags);
1259 if (ret < 0) return ret;
1260 }
1261
31852540
SI
1262 if (!mkv->is_live) {
1263 for (i = 0; i < s->nb_streams; i++) {
1264 ebml_master tag_target;
1265 ebml_master tag;
1266
1267 mkv_write_tag_targets(s, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &tags, &tag_target);
1268
1269 tag = start_ebml_master(s->pb, MATROSKA_ID_SIMPLETAG, 0);
1270 put_ebml_string(s->pb, MATROSKA_ID_TAGNAME, "DURATION");
1271 mkv->stream_duration_offsets[i] = avio_tell(s->pb);
1272
1273 // Reserve space to write duration as a 20-byte string.
1274 // 2 (ebml id) + 1 (data size) + 20 (data)
1275 put_ebml_void(s->pb, 23);
1276 end_ebml_master(s->pb, tag);
1277 end_ebml_master(s->pb, tag_target);
1278 }
1279 }
1280
9b75309c
AK
1281 for (i = 0; i < s->nb_chapters; i++) {
1282 AVChapter *ch = s->chapters[i];
1283
088ed531 1284 if (!mkv_check_tag(ch->metadata))
9b75309c
AK
1285 continue;
1286
07704c61 1287 ret = mkv_write_tag(s, ch->metadata, MATROSKA_ID_TAGTARGETS_CHAPTERUID, ch->id + mkv->chapter_id_offset, &tags);
9b75309c
AK
1288 if (ret < 0) return ret;
1289 }
1290
1291 if (tags.pos)
1292 end_ebml_master(s->pb, tags);
1293 return 0;
1294}
1295
c7a63a52
AK
1296static int mkv_write_attachments(AVFormatContext *s)
1297{
1298 MatroskaMuxContext *mkv = s->priv_data;
1299 AVIOContext *pb = s->pb;
1300 ebml_master attachments;
1301 AVLFG c;
1302 int i, ret;
1303
1304 if (!mkv->have_attachments)
1305 return 0;
1306
1307 av_lfg_init(&c, av_get_random_seed());
1308
1309 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_ATTACHMENTS, avio_tell(pb));
1310 if (ret < 0) return ret;
1311
1312 attachments = start_ebml_master(pb, MATROSKA_ID_ATTACHMENTS, 0);
1313
1314 for (i = 0; i < s->nb_streams; i++) {
1315 AVStream *st = s->streams[i];
1316 ebml_master attached_file;
1317 AVDictionaryEntry *t;
1318 const char *mimetype = NULL;
8dbbaf56 1319 uint64_t fileuid;
c7a63a52
AK
1320
1321 if (st->codec->codec_type != AVMEDIA_TYPE_ATTACHMENT)
1322 continue;
1323
1324 attached_file = start_ebml_master(pb, MATROSKA_ID_ATTACHEDFILE, 0);
1325
1326 if (t = av_dict_get(st->metadata, "title", NULL, 0))
1327 put_ebml_string(pb, MATROSKA_ID_FILEDESC, t->value);
1328 if (!(t = av_dict_get(st->metadata, "filename", NULL, 0))) {
1329 av_log(s, AV_LOG_ERROR, "Attachment stream %d has no filename tag.\n", i);
1330 return AVERROR(EINVAL);
1331 }
1332 put_ebml_string(pb, MATROSKA_ID_FILENAME, t->value);
1333 if (t = av_dict_get(st->metadata, "mimetype", NULL, 0))
1334 mimetype = t->value;
36ef5369 1335 else if (st->codec->codec_id != AV_CODEC_ID_NONE ) {
c7a63a52 1336 int i;
36ef5369 1337 for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
c7a63a52
AK
1338 if (ff_mkv_mime_tags[i].id == st->codec->codec_id) {
1339 mimetype = ff_mkv_mime_tags[i].str;
1340 break;
1341 }
511585ce 1342 for (i = 0; ff_mkv_image_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
1343 if (ff_mkv_image_mime_tags[i].id == st->codec->codec_id) {
1344 mimetype = ff_mkv_image_mime_tags[i].str;
1345 break;
1346 }
c7a63a52
AK
1347 }
1348 if (!mimetype) {
1349 av_log(s, AV_LOG_ERROR, "Attachment stream %d has no mimetype tag and "
1350 "it cannot be deduced from the codec id.\n", i);
1351 return AVERROR(EINVAL);
1352 }
1353
0421409c 1354 if (s->flags & AVFMT_FLAG_BITEXACT) {
8dbbaf56
NG
1355 struct AVSHA *sha = av_sha_alloc();
1356 uint8_t digest[20];
1357 if (!sha)
1358 return AVERROR(ENOMEM);
1359 av_sha_init(sha, 160);
1360 av_sha_update(sha, st->codec->extradata, st->codec->extradata_size);
1361 av_sha_final(sha, digest);
1362 av_free(sha);
1363 fileuid = AV_RL64(digest);
1364 } else {
1365 fileuid = av_lfg_get(&c);
1366 }
1367 av_log(s, AV_LOG_VERBOSE, "Using %.16"PRIx64" for attachment %d\n",
1368 fileuid, i);
1369
c7a63a52
AK
1370 put_ebml_string(pb, MATROSKA_ID_FILEMIMETYPE, mimetype);
1371 put_ebml_binary(pb, MATROSKA_ID_FILEDATA, st->codec->extradata, st->codec->extradata_size);
8dbbaf56 1372 put_ebml_uint(pb, MATROSKA_ID_FILEUID, fileuid);
c7a63a52
AK
1373 end_ebml_master(pb, attached_file);
1374 }
1375 end_ebml_master(pb, attachments);
1376
1377 return 0;
1378}
1379
5034ab90
DC
1380static int mkv_write_header(AVFormatContext *s)
1381{
1382 MatroskaMuxContext *mkv = s->priv_data;
ae628ec1 1383 AVIOContext *pb = s->pb;
baf71dca 1384 ebml_master ebml_header, segment_info;
d2d67e42 1385 AVDictionaryEntry *tag;
ab21acec 1386 int ret, i, version = 2;
66e85a18 1387 int64_t creation_time;
5034ab90 1388
f1f6156b
LB
1389 if (!strcmp(s->oformat->name, "webm"))
1390 mkv->mode = MODE_WEBM;
1391 else
1392 mkv->mode = MODE_MATROSKAv2;
316d6c15 1393
ab21acec
CEH
1394 if (mkv->mode != MODE_WEBM ||
1395 av_dict_get(s->metadata, "stereo_mode", NULL, 0) ||
1396 av_dict_get(s->metadata, "alpha_mode", NULL, 0))
1397 version = 4;
1398
1399 for (i = 0; i < s->nb_streams; i++) {
f02f231e
CEH
1400 if (s->streams[i]->codec->codec_id == AV_CODEC_ID_ATRAC3 ||
1401 s->streams[i]->codec->codec_id == AV_CODEC_ID_COOK ||
1402 s->streams[i]->codec->codec_id == AV_CODEC_ID_RA_288 ||
1403 s->streams[i]->codec->codec_id == AV_CODEC_ID_SIPR ||
1404 s->streams[i]->codec->codec_id == AV_CODEC_ID_RV10 ||
1405 s->streams[i]->codec->codec_id == AV_CODEC_ID_RV20) {
1406 av_log(s, AV_LOG_ERROR,
1407 "The Matroska muxer does not yet support muxing %s\n",
1408 avcodec_get_name(s->streams[i]->codec->codec_id));
1409 return AVERROR_PATCHWELCOME;
1410 }
ab21acec
CEH
1411 if (s->streams[i]->codec->codec_id == AV_CODEC_ID_OPUS ||
1412 av_dict_get(s->streams[i]->metadata, "stereo_mode", NULL, 0) ||
1413 av_dict_get(s->streams[i]->metadata, "alpha_mode", NULL, 0))
1414 version = 4;
1415 }
f02f231e 1416
f6d17d2a 1417 mkv->tracks = av_mallocz_array(s->nb_streams, sizeof(*mkv->tracks));
3dabebc2
NB
1418 if (!mkv->tracks) {
1419 ret = AVERROR(ENOMEM);
1420 goto fail;
1421 }
baf71dca 1422 ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
5034ab90
DC
1423 put_ebml_uint (pb, EBML_ID_EBMLVERSION , 1);
1424 put_ebml_uint (pb, EBML_ID_EBMLREADVERSION , 1);
1425 put_ebml_uint (pb, EBML_ID_EBMLMAXIDLENGTH , 4);
1426 put_ebml_uint (pb, EBML_ID_EBMLMAXSIZELENGTH , 8);
316d6c15 1427 put_ebml_string (pb, EBML_ID_DOCTYPE , s->oformat->name);
ab21acec 1428 put_ebml_uint (pb, EBML_ID_DOCTYPEVERSION , version);
5034ab90
DC
1429 put_ebml_uint (pb, EBML_ID_DOCTYPEREADVERSION , 2);
1430 end_ebml_master(pb, ebml_header);
1431
baf71dca 1432 mkv->segment = start_ebml_master(pb, MATROSKA_ID_SEGMENT, 0);
a2704c97 1433 mkv->segment_offset = avio_tell(pb);
967d815a 1434
cfde5d18
DC
1435 // we write 2 seek heads - one at the end of the file to point to each
1436 // cluster, and one at the beginning to point to all other level one
1437 // elements (including the seek head at the end of the file), which
1438 // isn't more than 10 elements if we only write one of each other
1439 // currently defined level 1 element
967d815a 1440 mkv->main_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 10);
3dabebc2
NB
1441 if (!mkv->main_seekhead) {
1442 ret = AVERROR(ENOMEM);
1443 goto fail;
1444 }
967d815a 1445
a2704c97 1446 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_INFO, avio_tell(pb));
3dabebc2 1447 if (ret < 0) goto fail;
5034ab90 1448
baf71dca 1449 segment_info = start_ebml_master(pb, MATROSKA_ID_INFO, 0);
5034ab90 1450 put_ebml_uint(pb, MATROSKA_ID_TIMECODESCALE, 1000000);
d2d67e42 1451 if ((tag = av_dict_get(s->metadata, "title", NULL, 0)))
5e565998 1452 put_ebml_string(pb, MATROSKA_ID_TITLE, tag->value);
0c1959b0 1453 if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
1f4280e7 1454 uint32_t segment_uid[4];
5150dd53
MR
1455 AVLFG lfg;
1456
1457 av_lfg_init(&lfg, av_get_random_seed());
1458
1f4280e7 1459 for (i = 0; i < 4; i++)
5150dd53 1460 segment_uid[i] = av_lfg_get(&lfg);
1f4280e7 1461
f1f6156b 1462 put_ebml_string(pb, MATROSKA_ID_MUXINGAPP, LIBAVFORMAT_IDENT);
0092c1dd
JS
1463 if ((tag = av_dict_get(s->metadata, "encoding_tool", NULL, 0)))
1464 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, tag->value);
1465 else
1466 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, LIBAVFORMAT_IDENT);
1f4280e7 1467 put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
ea70e2f2
JA
1468 } else {
1469 const char *ident = "Lavf";
1470 put_ebml_string(pb, MATROSKA_ID_MUXINGAPP , ident);
1471 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, ident);
5034ab90 1472 }
4b8f58ee 1473
66e85a18 1474 if (ff_parse_creation_time_metadata(s, &creation_time, 0) > 0) {
2e061130 1475 // Adjust time so it's relative to 2001-01-01 and convert to nanoseconds.
66e85a18 1476 int64_t date_utc = (creation_time - 978307200000000LL) * 1000;
2e061130
AC
1477 uint8_t date_utc_buf[8];
1478 AV_WB64(date_utc_buf, date_utc);
1479 put_ebml_binary(pb, MATROSKA_ID_DATEUTC, date_utc_buf, 8);
1480 }
1481
5034ab90
DC
1482 // reserve space for the duration
1483 mkv->duration = 0;
a2704c97 1484 mkv->duration_offset = avio_tell(pb);
6fd300ac
VV
1485 if (!mkv->is_live) {
1486 put_ebml_void(pb, 11); // assumes double-precision float to be written
1487 }
5034ab90
DC
1488 end_ebml_master(pb, segment_info);
1489
31852540
SI
1490 // initialize stream_duration fields
1491 mkv->stream_durations = av_mallocz(s->nb_streams * sizeof(int64_t));
1492 mkv->stream_duration_offsets = av_mallocz(s->nb_streams * sizeof(int64_t));
1493
6d588ecd 1494 ret = mkv_write_tracks(s);
f1f6156b 1495 if (ret < 0)
3dabebc2 1496 goto fail;
67143c0f 1497
07704c61
MN
1498 for (i = 0; i < s->nb_chapters; i++)
1499 mkv->chapter_id_offset = FFMAX(mkv->chapter_id_offset, 1LL - s->chapters[i]->id);
1500
316d6c15
JZ
1501 if (mkv->mode != MODE_WEBM) {
1502 ret = mkv_write_chapters(s);
f1f6156b 1503 if (ret < 0)
3dabebc2 1504 goto fail;
9b75309c
AK
1505
1506 ret = mkv_write_tags(s);
f1f6156b 1507 if (ret < 0)
3dabebc2 1508 goto fail;
c7a63a52
AK
1509
1510 ret = mkv_write_attachments(s);
f1f6156b 1511 if (ret < 0)
3dabebc2 1512 goto fail;
316d6c15 1513 }
2bd0758e 1514
6fd300ac 1515 if (!s->pb->seekable && !mkv->is_live)
3dabebc2 1516 mkv_write_seekhead(pb, mkv);
7a2a4840 1517
6364d534 1518 mkv->cues = mkv_start_cues(mkv->segment_offset);
3dabebc2
NB
1519 if (!mkv->cues) {
1520 ret = AVERROR(ENOMEM);
1521 goto fail;
1522 }
e3b225a4
AK
1523 if (pb->seekable && mkv->reserve_cues_space) {
1524 mkv->cues_pos = avio_tell(pb);
1525 put_ebml_void(pb, mkv->reserve_cues_space);
1526 }
1527
ac9baa71
JZ
1528 av_init_packet(&mkv->cur_audio_pkt);
1529 mkv->cur_audio_pkt.size = 0;
bda5b662 1530 mkv->cluster_pos = -1;
ac9baa71 1531
b7f2fdde 1532 avio_flush(pb);
98308bd4
LB
1533
1534 // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1535 // after 4k and on a keyframe
1536 if (pb->seekable) {
1537 if (mkv->cluster_time_limit < 0)
1538 mkv->cluster_time_limit = 5000;
1539 if (mkv->cluster_size_limit < 0)
1540 mkv->cluster_size_limit = 5 * 1024 * 1024;
1541 } else {
1542 if (mkv->cluster_time_limit < 0)
1543 mkv->cluster_time_limit = 1000;
1544 if (mkv->cluster_size_limit < 0)
1545 mkv->cluster_size_limit = 32 * 1024;
1546 }
1547
67143c0f 1548 return 0;
3dabebc2
NB
1549fail:
1550 mkv_free(mkv);
1551 return ret;
67143c0f
DC
1552}
1553
1bfbe8ff 1554static int mkv_blockgroup_size(int pkt_size)
baf71dca 1555{
1bfbe8ff 1556 int size = pkt_size + 4;
0f651e8c 1557 size += ebml_num_size(size);
baf71dca
DC
1558 size += 2; // EBML ID for block and block duration
1559 size += 8; // max size of block duration
0f651e8c 1560 size += ebml_num_size(size);
baf71dca
DC
1561 size += 1; // blockgroup EBML ID
1562 return size;
1563}
1564
01656fd4
AK
1565static int mkv_strip_wavpack(const uint8_t *src, uint8_t **pdst, int *size)
1566{
1567 uint8_t *dst;
1568 int srclen = *size;
1569 int offset = 0;
1570 int ret;
1571
1572 dst = av_malloc(srclen);
1573 if (!dst)
1574 return AVERROR(ENOMEM);
1575
1576 while (srclen >= WV_HEADER_SIZE) {
1577 WvHeader header;
1578
1579 ret = ff_wv_parse_header(&header, src);
1580 if (ret < 0)
1581 goto fail;
1582 src += WV_HEADER_SIZE;
1583 srclen -= WV_HEADER_SIZE;
1584
1585 if (srclen < header.blocksize) {
1586 ret = AVERROR_INVALIDDATA;
1587 goto fail;
1588 }
1589
1590 if (header.initial) {
1591 AV_WL32(dst + offset, header.samples);
1592 offset += 4;
1593 }
1594 AV_WL32(dst + offset, header.flags);
1595 AV_WL32(dst + offset + 4, header.crc);
1596 offset += 8;
1597
1598 if (!(header.initial && header.final)) {
1599 AV_WL32(dst + offset, header.blocksize);
1600 offset += 4;
1601 }
1602
1603 memcpy(dst + offset, src, header.blocksize);
1604 src += header.blocksize;
1605 srclen -= header.blocksize;
1606 offset += header.blocksize;
1607 }
1608
1609 *pdst = dst;
1610 *size = offset;
1611
1612 return 0;
1613fail:
1614 av_freep(&dst);
1615 return ret;
1616}
1617
ae628ec1 1618static void mkv_write_block(AVFormatContext *s, AVIOContext *pb,
7be0f48a 1619 unsigned int blockid, AVPacket *pkt, int keyframe)
95527e06
DC
1620{
1621 MatroskaMuxContext *mkv = s->priv_data;
0a63a676 1622 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
8ffcc826
VV
1623 uint8_t *data = NULL, *side_data = NULL;
1624 int offset = 0, size = pkt->size, side_data_size = 0;
84d4e599 1625 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
f4b1ca99
JG
1626 uint64_t additional_id = 0;
1627 int64_t discard_padding = 0;
7be0f48a 1628 uint8_t track_number = (mkv->is_dash ? mkv->dash_track_number : (pkt->stream_index + 1));
2fb193b1 1629 ebml_master block_group, block_additions, block_more;
95527e06 1630
8ffc5f9e 1631 av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
b01891a9 1632 "pts %" PRId64 ", dts %" PRId64 ", duration %" PRId64 ", keyframe %d\n",
7be0f48a
VV
1633 avio_tell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration,
1634 keyframe != 0);
36ef5369 1635 if (codec->codec_id == AV_CODEC_ID_H264 && codec->extradata_size > 0 &&
5f8bae8d
AJ
1636 (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
1637 ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
558b20d7
TW
1638 else if (codec->codec_id == AV_CODEC_ID_HEVC && codec->extradata_size > 6 &&
1639 (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
1640 /* extradata is Annex B, assume the bitstream is too and convert it */
1641 ff_hevc_annexb2mp4_buf(pkt->data, &data, &size, 0, NULL);
01656fd4
AK
1642 else if (codec->codec_id == AV_CODEC_ID_WAVPACK) {
1643 int ret = mkv_strip_wavpack(pkt->data, &data, &size);
1644 if (ret < 0) {
1645 av_log(s, AV_LOG_ERROR, "Error stripping a WavPack packet.\n");
1646 return;
1647 }
1648 } else
5f8bae8d 1649 data = pkt->data;
117d8c6d 1650
8f6b919d 1651 if (codec->codec_id == AV_CODEC_ID_PRORES && size >= 8) {
117d8c6d
LB
1652 /* Matroska specification requires to remove the first QuickTime atom
1653 */
f1f6156b 1654 size -= 8;
117d8c6d
LB
1655 offset = 8;
1656 }
1657
8ffcc826 1658 side_data = av_packet_get_side_data(pkt,
bb47aa58
VV
1659 AV_PKT_DATA_SKIP_SAMPLES,
1660 &side_data_size);
1661
1662 if (side_data && side_data_size >= 10) {
1663 discard_padding = av_rescale_q(AV_RL32(side_data + 4),
1664 (AVRational){1, codec->sample_rate},
1665 (AVRational){1, 1000000000});
1666 }
1667
1668 side_data = av_packet_get_side_data(pkt,
8ffcc826
VV
1669 AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,
1670 &side_data_size);
1671 if (side_data) {
1672 additional_id = AV_RB64(side_data);
1673 side_data += 8;
1674 side_data_size -= 8;
1675 }
1676
bb47aa58 1677 if ((side_data_size && additional_id == 1) || discard_padding) {
8ffcc826 1678 block_group = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, 0);
2fb193b1
MN
1679 blockid = MATROSKA_ID_BLOCK;
1680 }
1681
1682 put_ebml_id(pb, blockid);
f1f6156b 1683 put_ebml_num(pb, size + 4, 0);
37cef8c7 1684 // this assumes stream_index is less than 126
7be0f48a 1685 avio_w8(pb, 0x80 | track_number);
2fb193b1 1686 avio_wb16(pb, ts - mkv->cluster_pts);
7be0f48a 1687 avio_w8(pb, (blockid == MATROSKA_ID_SIMPLEBLOCK && keyframe) ? (1 << 7) : 0);
2fb193b1
MN
1688 avio_write(pb, data + offset, size);
1689 if (data != pkt->data)
1690 av_free(data);
1691
7be0f48a
VV
1692 if (blockid == MATROSKA_ID_BLOCK && !keyframe) {
1693 put_ebml_sint(pb, MATROSKA_ID_BLOCKREFERENCE,
1694 mkv->last_track_timestamp[track_number - 1]);
1695 }
1696 mkv->last_track_timestamp[track_number - 1] = ts - mkv->cluster_pts;
1697
bb47aa58 1698 if (discard_padding) {
f4b1ca99 1699 put_ebml_sint(pb, MATROSKA_ID_DISCARDPADDING, discard_padding);
bb47aa58
VV
1700 }
1701
2fb193b1 1702 if (side_data_size && additional_id == 1) {
8ffcc826
VV
1703 block_additions = start_ebml_master(pb, MATROSKA_ID_BLOCKADDITIONS, 0);
1704 block_more = start_ebml_master(pb, MATROSKA_ID_BLOCKMORE, 0);
1705 put_ebml_uint(pb, MATROSKA_ID_BLOCKADDID, 1);
1706 put_ebml_id(pb, MATROSKA_ID_BLOCKADDITIONAL);
1707 put_ebml_num(pb, side_data_size, 0);
1708 avio_write(pb, side_data, side_data_size);
1709 end_ebml_master(pb, block_more);
1710 end_ebml_master(pb, block_additions);
bb47aa58
VV
1711 }
1712 if ((side_data_size && additional_id == 1) || discard_padding) {
8ffcc826
VV
1713 end_ebml_master(pb, block_group);
1714 }
95527e06
DC
1715}
1716
509642b4
MH
1717static int mkv_write_vtt_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
1718{
1719 MatroskaMuxContext *mkv = s->priv_data;
1720 ebml_master blockgroup;
1721 int id_size, settings_size, size;
1722 uint8_t *id, *settings;
1723 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1724 const int flags = 0;
1725
1726 id_size = 0;
1727 id = av_packet_get_side_data(pkt, AV_PKT_DATA_WEBVTT_IDENTIFIER,
1728 &id_size);
1729
1730 settings_size = 0;
1731 settings = av_packet_get_side_data(pkt, AV_PKT_DATA_WEBVTT_SETTINGS,
1732 &settings_size);
1733
1734 size = id_size + 1 + settings_size + 1 + pkt->size;
1735
1736 av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
b01891a9 1737 "pts %" PRId64 ", dts %" PRId64 ", duration %" PRId64 ", flags %d\n",
509642b4
MH
1738 avio_tell(pb), size, pkt->pts, pkt->dts, pkt->duration, flags);
1739
1740 blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(size));
1741
1742 put_ebml_id(pb, MATROSKA_ID_BLOCK);
8365287e 1743 put_ebml_num(pb, size + 4, 0);
509642b4
MH
1744 avio_w8(pb, 0x80 | (pkt->stream_index + 1)); // this assumes stream_index is less than 126
1745 avio_wb16(pb, ts - mkv->cluster_pts);
1746 avio_w8(pb, flags);
1747 avio_printf(pb, "%.*s\n%.*s\n%.*s", id_size, id, settings_size, settings, pkt->size, pkt->data);
1748
1749 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, pkt->duration);
1750 end_ebml_master(pb, blockgroup);
1751
1752 return pkt->duration;
1753}
1754
871b641b
DC
1755static void mkv_flush_dynbuf(AVFormatContext *s)
1756{
1757 MatroskaMuxContext *mkv = s->priv_data;
1758 int bufsize;
1759 uint8_t *dyn_buf;
1760
1761 if (!mkv->dyn_bc)
1762 return;
1763
6dc7d80d 1764 bufsize = avio_close_dyn_buf(mkv->dyn_bc, &dyn_buf);
77eb5504 1765 avio_write(s->pb, dyn_buf, bufsize);
871b641b
DC
1766 av_free(dyn_buf);
1767 mkv->dyn_bc = NULL;
1768}
1769
3c6e220a
MN
1770static void mkv_start_new_cluster(AVFormatContext *s, AVPacket *pkt)
1771{
1772 MatroskaMuxContext *mkv = s->priv_data;
1773 AVIOContext *pb;
1774
1775 if (s->pb->seekable) {
1776 pb = s->pb;
1777 } else {
1778 pb = mkv->dyn_bc;
1779 }
1780
1781 av_log(s, AV_LOG_DEBUG,
1782 "Starting new cluster at offset %" PRIu64 " bytes, "
1783 "pts %" PRIu64 "dts %" PRIu64 "\n",
1784 avio_tell(pb), pkt->pts, pkt->dts);
1785 end_ebml_master(pb, mkv->cluster);
1786 mkv->cluster_pos = -1;
1787 if (mkv->dyn_bc)
1788 mkv_flush_dynbuf(s);
1789 avio_flush(s->pb);
1790}
1791
37cef8c7 1792static int mkv_write_packet_internal(AVFormatContext *s, AVPacket *pkt, int add_cue)
67143c0f 1793{
98186e41 1794 MatroskaMuxContext *mkv = s->priv_data;
f1f6156b
LB
1795 AVIOContext *pb = s->pb;
1796 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1797 int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1798 int duration = pkt->duration;
6d588ecd 1799 int ret;
84d4e599 1800 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
c5f3cc40 1801 int64_t relative_packet_pos;
925f7980 1802 int dash_tracknum = mkv->is_dash ? mkv->dash_track_number : pkt->stream_index + 1;
b1adb69c 1803
654b65d0
DC
1804 if (ts == AV_NOPTS_VALUE) {
1805 av_log(s, AV_LOG_ERROR, "Can't write packet with unknown timestamp\n");
1806 return AVERROR(EINVAL);
1807 }
a1aa37dd 1808 ts += mkv->tracks[pkt->stream_index].ts_offset;
654b65d0 1809
7923aa0f
MN
1810 if (mkv->cluster_pos != -1) {
1811 int64_t cluster_time = ts - mkv->cluster_pts + mkv->tracks[pkt->stream_index].ts_offset;
1812 if ((int16_t)cluster_time != cluster_time) {
d44b8f0a 1813 av_log(s, AV_LOG_WARNING, "Starting new cluster due to timestamp\n");
7923aa0f
MN
1814 mkv_start_new_cluster(s, pkt);
1815 }
1816 }
1817
8978feda 1818 if (!s->pb->seekable) {
b1f517f5 1819 if (!mkv->dyn_bc) {
28c020d4 1820 ret = avio_open_dyn_buf(&mkv->dyn_bc);
8be93ba0 1821 if (ret < 0) {
b1f517f5
MN
1822 av_log(s, AV_LOG_ERROR, "Failed to open dynamic buffer\n");
1823 return ret;
1824 }
1825 }
871b641b
DC
1826 pb = mkv->dyn_bc;
1827 }
1828
bda5b662 1829 if (mkv->cluster_pos == -1) {
a2704c97 1830 mkv->cluster_pos = avio_tell(s->pb);
f1f6156b 1831 mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER, 0);
f9ff7179
DC
1832 put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, FFMAX(0, ts));
1833 mkv->cluster_pts = FFMAX(0, ts);
98186e41
DC
1834 }
1835
c5f3cc40
BH
1836 relative_packet_pos = avio_tell(s->pb) - mkv->cluster.pos;
1837
72415b2a 1838 if (codec->codec_type != AVMEDIA_TYPE_SUBTITLE) {
7be0f48a 1839 mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe);
da46370e 1840 if (s->pb->seekable && (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe || add_cue)) {
925f7980
JP
1841 ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, dash_tracknum, ts, mkv->cluster_pos, relative_packet_pos, -1);
1842 if (ret < 0) return ret;
1843 }
925f7980 1844 } else {
0c6a92a4
TG
1845 if (codec->codec_id == AV_CODEC_ID_WEBVTT) {
1846 duration = mkv_write_vtt_blocks(s, pb, pkt);
1847 } else {
1848 ebml_master blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
1849 mkv_blockgroup_size(pkt->size));
b01891a9 1850
948f3c19 1851#if FF_API_CONVERGENCE_DURATION
1852FF_DISABLE_DEPRECATION_WARNINGS
0c6a92a4
TG
1853 /* For backward compatibility, prefer convergence_duration. */
1854 if (pkt->convergence_duration > 0) {
1855 duration = pkt->convergence_duration;
1856 }
948f3c19 1857FF_ENABLE_DEPRECATION_WARNINGS
1858#endif
0c6a92a4
TG
1859 /* All subtitle blocks are considered to be keyframes. */
1860 mkv_write_block(s, pb, MATROSKA_ID_BLOCK, pkt, 1);
1861 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
1862 end_ebml_master(pb, blockgroup);
9d89c8b3 1863 }
02f487fc 1864
0c6a92a4
TG
1865 if (s->pb->seekable) {
1866 ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, dash_tracknum, ts,
1867 mkv->cluster_pos, relative_packet_pos, duration);
1868 if (ret < 0)
1869 return ret;
6253f511 1870 }
da46370e 1871 }
6364d534 1872
ac9baa71 1873 mkv->duration = FFMAX(mkv->duration, ts + duration);
31852540
SI
1874
1875 if (mkv->stream_durations)
1876 mkv->stream_durations[pkt->stream_index] =
1877 FFMAX(mkv->stream_durations[pkt->stream_index], ts + duration);
1878
ac9baa71
JZ
1879 return 0;
1880}
1881
ac9baa71
JZ
1882static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
1883{
1884 MatroskaMuxContext *mkv = s->priv_data;
148fbdd1
LB
1885 int codec_type = s->streams[pkt->stream_index]->codec->codec_type;
1886 int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1887 int cluster_size;
148fbdd1 1888 int64_t cluster_time;
148fbdd1 1889 int ret;
37cef8c7 1890 int start_new_cluster;
148fbdd1
LB
1891
1892 if (mkv->tracks[pkt->stream_index].write_dts)
1893 cluster_time = pkt->dts - mkv->cluster_pts;
1894 else
1895 cluster_time = pkt->pts - mkv->cluster_pts;
a1aa37dd 1896 cluster_time += mkv->tracks[pkt->stream_index].ts_offset;
ac9baa71
JZ
1897
1898 // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1899 // after 4k and on a keyframe
148fbdd1 1900 if (s->pb->seekable) {
3c6e220a 1901 cluster_size = avio_tell(s->pb) - mkv->cluster_pos;
148fbdd1 1902 } else {
3c6e220a 1903 cluster_size = avio_tell(mkv->dyn_bc);
148fbdd1
LB
1904 }
1905
37cef8c7
VV
1906 if (mkv->is_dash && codec_type == AVMEDIA_TYPE_VIDEO) {
1907 // WebM DASH specification states that the first block of every cluster
1908 // has to be a key frame. So for DASH video, we only create a cluster
1909 // on seeing key frames.
1910 start_new_cluster = keyframe;
1911 } else if (mkv->is_dash && codec_type == AVMEDIA_TYPE_AUDIO &&
241b306b
FG
1912 (mkv->cluster_pos == -1 ||
1913 cluster_time > mkv->cluster_time_limit)) {
37cef8c7
VV
1914 // For DASH audio, we create a Cluster based on cluster_time_limit
1915 start_new_cluster = 1;
1916 } else if (!mkv->is_dash &&
1917 (cluster_size > mkv->cluster_size_limit ||
1918 cluster_time > mkv->cluster_time_limit ||
1919 (codec_type == AVMEDIA_TYPE_VIDEO && keyframe &&
1920 cluster_size > 4 * 1024))) {
1921 start_new_cluster = 1;
1922 } else {
1923 start_new_cluster = 0;
1924 }
1925
1926 if (mkv->cluster_pos != -1 && start_new_cluster) {
3c6e220a 1927 mkv_start_new_cluster(s, pkt);
30f06a58
DC
1928 }
1929
ac9baa71
JZ
1930 // check if we have an audio packet cached
1931 if (mkv->cur_audio_pkt.size > 0) {
37cef8c7
VV
1932 // for DASH audio, a CuePoint has to be added when there is a new cluster.
1933 ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt,
1934 mkv->is_dash ? start_new_cluster : 0);
ce70f28a 1935 av_packet_unref(&mkv->cur_audio_pkt);
ac9baa71 1936 if (ret < 0) {
f1f6156b
LB
1937 av_log(s, AV_LOG_ERROR,
1938 "Could not write cached audio packet ret:%d\n", ret);
ac9baa71
JZ
1939 return ret;
1940 }
1941 }
1942
1943 // buffer an audio packet to ensure the packet containing the video
1944 // keyframe's timecode is contained in the same cluster for WebM
148fbdd1 1945 if (codec_type == AVMEDIA_TYPE_AUDIO) {
9b56d5c1 1946 ret = av_packet_ref(&mkv->cur_audio_pkt, pkt);
1afddbe5 1947 } else
37cef8c7 1948 ret = mkv_write_packet_internal(s, pkt, 0);
ac9baa71 1949 return ret;
67143c0f
DC
1950}
1951
b886f5c2
MS
1952static int mkv_write_flush_packet(AVFormatContext *s, AVPacket *pkt)
1953{
1954 MatroskaMuxContext *mkv = s->priv_data;
1955 AVIOContext *pb;
1956 if (s->pb->seekable)
1957 pb = s->pb;
1958 else
1959 pb = mkv->dyn_bc;
1960 if (!pkt) {
e1acfd3c 1961 if (mkv->cluster_pos != -1) {
f1f6156b
LB
1962 av_log(s, AV_LOG_DEBUG,
1963 "Flushing cluster at offset %" PRIu64 " bytes\n",
1964 avio_tell(pb));
b886f5c2 1965 end_ebml_master(pb, mkv->cluster);
e1acfd3c 1966 mkv->cluster_pos = -1;
b886f5c2
MS
1967 if (mkv->dyn_bc)
1968 mkv_flush_dynbuf(s);
1969 avio_flush(s->pb);
1970 }
b14086ca 1971 return 1;
b886f5c2
MS
1972 }
1973 return mkv_write_packet(s, pkt);
1974}
1975
67143c0f
DC
1976static int mkv_write_trailer(AVFormatContext *s)
1977{
1978 MatroskaMuxContext *mkv = s->priv_data;
ae628ec1 1979 AVIOContext *pb = s->pb;
e7ddafd5 1980 int64_t currentpos, cuespos;
9e2a3e22 1981 int ret;
02f487fc 1982
ac9baa71
JZ
1983 // check if we have an audio packet cached
1984 if (mkv->cur_audio_pkt.size > 0) {
37cef8c7 1985 ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt, 0);
ce70f28a 1986 av_packet_unref(&mkv->cur_audio_pkt);
ac9baa71 1987 if (ret < 0) {
f1f6156b
LB
1988 av_log(s, AV_LOG_ERROR,
1989 "Could not write cached audio packet ret:%d\n", ret);
ac9baa71
JZ
1990 return ret;
1991 }
1992 }
1993
871b641b
DC
1994 if (mkv->dyn_bc) {
1995 end_ebml_master(mkv->dyn_bc, mkv->cluster);
1996 mkv_flush_dynbuf(s);
bda5b662 1997 } else if (mkv->cluster_pos != -1) {
871b641b
DC
1998 end_ebml_master(pb, mkv->cluster);
1999 }
02f487fc 2000
26b241c0
JS
2001 if (mkv->mode != MODE_WEBM) {
2002 ret = mkv_write_chapters(s);
f1f6156b
LB
2003 if (ret < 0)
2004 return ret;
26b241c0
JS
2005 }
2006
8978feda 2007 if (pb->seekable) {
91819763 2008 if (mkv->cues->num_entries) {
e3b225a4
AK
2009 if (mkv->reserve_cues_space) {
2010 int64_t cues_end;
2011
2012 currentpos = avio_tell(pb);
2013 avio_seek(pb, mkv->cues_pos, SEEK_SET);
2014
8365287e 2015 cuespos = mkv_write_cues(s, mkv->cues, mkv->tracks, s->nb_streams);
e3b225a4
AK
2016 cues_end = avio_tell(pb);
2017 if (cues_end > cuespos + mkv->reserve_cues_space) {
f1f6156b
LB
2018 av_log(s, AV_LOG_ERROR,
2019 "Insufficient space reserved for cues: %d "
2020 "(needed: %" PRId64 ").\n",
2021 mkv->reserve_cues_space, cues_end - cuespos);
e3b225a4
AK
2022 return AVERROR(EINVAL);
2023 }
2024
2025 if (cues_end < cuespos + mkv->reserve_cues_space)
f1f6156b
LB
2026 put_ebml_void(pb, mkv->reserve_cues_space -
2027 (cues_end - cuespos));
e3b225a4
AK
2028
2029 avio_seek(pb, currentpos, SEEK_SET);
2030 } else {
925f7980 2031 cuespos = mkv_write_cues(s, mkv->cues, mkv->tracks, s->nb_streams);
e3b225a4 2032 }
91819763 2033
f1f6156b
LB
2034 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CUES,
2035 cuespos);
2036 if (ret < 0)
2037 return ret;
91819763 2038 }
6364d534 2039
3dabebc2 2040 mkv_write_seekhead(pb, mkv);
e5c29287
DC
2041
2042 // update the duration
2043 av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
a2704c97 2044 currentpos = avio_tell(pb);
6b4aa5da 2045 avio_seek(pb, mkv->duration_offset, SEEK_SET);
e5c29287
DC
2046 put_ebml_float(pb, MATROSKA_ID_DURATION, mkv->duration);
2047
31852540
SI
2048 // update stream durations
2049 if (mkv->stream_durations) {
ace83766
MN
2050 int i;
2051 for (i = 0; i < s->nb_streams; ++i) {
31852540
SI
2052 AVStream *st = s->streams[i];
2053 double duration_sec = mkv->stream_durations[i] * av_q2d(st->time_base);
2054 char duration_string[20] = "";
2055
2056 av_log(s, AV_LOG_DEBUG, "stream %d end duration = %" PRIu64 "\n", i,
2057 mkv->stream_durations[i]);
2058
2059 if (!mkv->is_live && mkv->stream_duration_offsets[i] > 0) {
2060 avio_seek(pb, mkv->stream_duration_offsets[i], SEEK_SET);
2061
2062 snprintf(duration_string, 20, "%02d:%02d:%012.9f",
2063 (int) duration_sec / 3600, ((int) duration_sec / 60) % 60,
2064 fmod(duration_sec, 60));
2065
2066 put_ebml_binary(pb, MATROSKA_ID_TAGSTRING, duration_string, 20);
2067 }
2068 }
2069 }
2070
6b4aa5da 2071 avio_seek(pb, currentpos, SEEK_SET);
ac9e1177 2072 }
02f487fc 2073
6fd300ac
VV
2074 if (!mkv->is_live) {
2075 end_ebml_master(pb, mkv->segment);
2076 }
3b4bb19e 2077
3dabebc2 2078 mkv_free(mkv);
67143c0f
DC
2079 return 0;
2080}
2081
36ef5369 2082static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
15c14ce6
AK
2083{
2084 int i;
36ef5369 2085 for (i = 0; ff_mkv_codec_tags[i].id != AV_CODEC_ID_NONE; i++)
15c14ce6
AK
2086 if (ff_mkv_codec_tags[i].id == codec_id)
2087 return 1;
2088
f1f6156b
LB
2089 if (std_compliance < FF_COMPLIANCE_NORMAL) {
2090 enum AVMediaType type = avcodec_get_type(codec_id);
2091 // mkv theoretically supports any video/audio through VFW/ACM
15c14ce6
AK
2092 if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)
2093 return 1;
2094 }
2095
2096 return 0;
2097}
2098
b287d7ea
RC
2099static int mkv_init(struct AVFormatContext *s)
2100{
2101 int i;
2102
2103 if (s->avoid_negative_ts < 0) {
2104 s->avoid_negative_ts = 1;
2105 s->internal->avoid_negative_ts_use_pts = 1;
2106 }
2107
2108 for (i = 0; i < s->nb_streams; i++) {
2109 // ms precision is the de-facto standard timescale for mkv files
2110 avpriv_set_pts_info(s->streams[i], 64, 1, 1000);
2111 }
2112
2113 return 0;
2114}
2115
2116static int mkv_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
2117{
2118 int ret = 1;
2119 AVStream *st = s->streams[pkt->stream_index];
2120
2e6636aa 2121 if (st->codec->codec_id == AV_CODEC_ID_AAC) {
b287d7ea
RC
2122 if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
2123 ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
2e6636aa
RB
2124 } else if (st->codec->codec_id == AV_CODEC_ID_VP9) {
2125 ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL);
2126 }
b287d7ea
RC
2127
2128 return ret;
2129}
2130
0553f2c6 2131static const AVCodecTag additional_audio_tags[] = {
df39c3ce
CEH
2132 { AV_CODEC_ID_ALAC, 0XFFFFFFFF },
2133 { AV_CODEC_ID_EAC3, 0XFFFFFFFF },
2134 { AV_CODEC_ID_MLP, 0xFFFFFFFF },
2135 { AV_CODEC_ID_OPUS, 0xFFFFFFFF },
2136 { AV_CODEC_ID_PCM_S16BE, 0xFFFFFFFF },
2137 { AV_CODEC_ID_PCM_S24BE, 0xFFFFFFFF },
2138 { AV_CODEC_ID_PCM_S32BE, 0xFFFFFFFF },
2139 { AV_CODEC_ID_QDM2, 0xFFFFFFFF },
2140 { AV_CODEC_ID_RA_144, 0xFFFFFFFF },
2141 { AV_CODEC_ID_RA_288, 0xFFFFFFFF },
2142 { AV_CODEC_ID_COOK, 0xFFFFFFFF },
2143 { AV_CODEC_ID_TRUEHD, 0xFFFFFFFF },
df39c3ce
CEH
2144 { AV_CODEC_ID_NONE, 0xFFFFFFFF }
2145};
2146
0553f2c6 2147static const AVCodecTag additional_video_tags[] = {
df39c3ce
CEH
2148 { AV_CODEC_ID_RV10, 0xFFFFFFFF },
2149 { AV_CODEC_ID_RV20, 0xFFFFFFFF },
2150 { AV_CODEC_ID_RV30, 0xFFFFFFFF },
2151 { AV_CODEC_ID_RV40, 0xFFFFFFFF },
2152 { AV_CODEC_ID_VP9, 0xFFFFFFFF },
2153 { AV_CODEC_ID_NONE, 0xFFFFFFFF }
2154};
2155
b76df6ef
CEH
2156static const AVCodecTag additional_subtitle_tags[] = {
2157 { AV_CODEC_ID_DVB_SUBTITLE, 0xFFFFFFFF },
2158 { AV_CODEC_ID_HDMV_PGS_SUBTITLE, 0xFFFFFFFF },
2159 { AV_CODEC_ID_NONE, 0xFFFFFFFF }
2160};
2161
e3b225a4
AK
2162#define OFFSET(x) offsetof(MatroskaMuxContext, x)
2163#define FLAGS AV_OPT_FLAG_ENCODING_PARAM
2164static const AVOption options[] = {
98308bd4
LB
2165 { "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 },
2166 { "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 },
2167 { "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 },
43ecec0f 2168 { "dash", "Create a WebM file conforming to WebM DASH specification", OFFSET(is_dash), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
37cef8c7 2169 { "dash_track_number", "Track number for the DASH stream", OFFSET(dash_track_number), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 127, FLAGS },
43ecec0f
CB
2170 { "live", "Write files assuming it is a live stream.", OFFSET(is_live), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
2171 { "allow_raw_vfw", "allow RAW VFW mode", OFFSET(allow_raw_vfw), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
e3b225a4
AK
2172 { NULL },
2173};
2174
316d6c15 2175#if CONFIG_MATROSKA_MUXER
e3b225a4
AK
2176static const AVClass matroska_class = {
2177 .class_name = "matroska muxer",
2178 .item_name = av_default_item_name,
2179 .option = options,
2180 .version = LIBAVUTIL_VERSION_INT,
2181};
2182
c6610a21 2183AVOutputFormat ff_matroska_muxer = {
dfc2c4d9 2184 .name = "matroska",
6774247a 2185 .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
dfc2c4d9
AK
2186 .mime_type = "video/x-matroska",
2187 .extensions = "mkv",
2188 .priv_data_size = sizeof(MatroskaMuxContext),
fd487218 2189 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
36ef5369 2190 AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
fd487218 2191 .video_codec = CONFIG_LIBX264_ENCODER ?
36ef5369 2192 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
b287d7ea 2193 .init = mkv_init,
dfc2c4d9 2194 .write_header = mkv_write_header,
b886f5c2 2195 .write_packet = mkv_write_flush_packet,
dfc2c4d9 2196 .write_trailer = mkv_write_trailer,
e9cef897 2197 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
b886f5c2 2198 AVFMT_TS_NONSTRICT | AVFMT_ALLOW_FLUSH,
df39c3ce
CEH
2199 .codec_tag = (const AVCodecTag* const []){
2200 ff_codec_bmp_tags, ff_codec_wav_tags,
b76df6ef 2201 additional_audio_tags, additional_video_tags, additional_subtitle_tags, 0
df39c3ce 2202 },
7c1a002c 2203 .subtitle_codec = AV_CODEC_ID_ASS,
15c14ce6 2204 .query_codec = mkv_query_codec,
b287d7ea 2205 .check_bitstream = mkv_check_bitstream,
e3b225a4 2206 .priv_class = &matroska_class,
67143c0f 2207};
316d6c15
JZ
2208#endif
2209
2210#if CONFIG_WEBM_MUXER
e3b225a4
AK
2211static const AVClass webm_class = {
2212 .class_name = "webm muxer",
2213 .item_name = av_default_item_name,
2214 .option = options,
2215 .version = LIBAVUTIL_VERSION_INT,
2216};
2217
c6610a21 2218AVOutputFormat ff_webm_muxer = {
dfc2c4d9 2219 .name = "webm",
6774247a 2220 .long_name = NULL_IF_CONFIG_SMALL("WebM"),
dfc2c4d9
AK
2221 .mime_type = "video/webm",
2222 .extensions = "webm",
2223 .priv_data_size = sizeof(MatroskaMuxContext),
e176639b
LB
2224 .audio_codec = CONFIG_LIBOPUS_ENCODER ? AV_CODEC_ID_OPUS : AV_CODEC_ID_VORBIS,
2225 .video_codec = CONFIG_LIBVPX_VP9_ENCODER? AV_CODEC_ID_VP9 : AV_CODEC_ID_VP8,
509642b4 2226 .subtitle_codec = AV_CODEC_ID_WEBVTT,
b287d7ea 2227 .init = mkv_init,
dfc2c4d9 2228 .write_header = mkv_write_header,
b886f5c2 2229 .write_packet = mkv_write_flush_packet,
dfc2c4d9 2230 .write_trailer = mkv_write_trailer,
b287d7ea 2231 .check_bitstream = mkv_check_bitstream,
e9cef897 2232 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
b886f5c2 2233 AVFMT_TS_NONSTRICT | AVFMT_ALLOW_FLUSH,
e3b225a4 2234 .priv_class = &webm_class,
316d6c15
JZ
2235};
2236#endif
55c151ef 2237
316d6c15 2238#if CONFIG_MATROSKA_AUDIO_MUXER
e3b225a4
AK
2239static const AVClass mka_class = {
2240 .class_name = "matroska audio muxer",
2241 .item_name = av_default_item_name,
2242 .option = options,
2243 .version = LIBAVUTIL_VERSION_INT,
2244};
c6610a21 2245AVOutputFormat ff_matroska_audio_muxer = {
dfc2c4d9 2246 .name = "matroska",
8d9c1b32 2247 .long_name = NULL_IF_CONFIG_SMALL("Matroska Audio"),
dfc2c4d9
AK
2248 .mime_type = "audio/x-matroska",
2249 .extensions = "mka",
2250 .priv_data_size = sizeof(MatroskaMuxContext),
fd487218 2251 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
36ef5369
AK
2252 AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
2253 .video_codec = AV_CODEC_ID_NONE,
b287d7ea 2254 .init = mkv_init,
dfc2c4d9 2255 .write_header = mkv_write_header,
b886f5c2 2256 .write_packet = mkv_write_flush_packet,
dfc2c4d9 2257 .write_trailer = mkv_write_trailer,
b287d7ea 2258 .check_bitstream = mkv_check_bitstream,
b886f5c2
MS
2259 .flags = AVFMT_GLOBALHEADER | AVFMT_TS_NONSTRICT |
2260 AVFMT_ALLOW_FLUSH,
df39c3ce
CEH
2261 .codec_tag = (const AVCodecTag* const []){
2262 ff_codec_wav_tags, additional_audio_tags, 0
2263 },
e3b225a4 2264 .priv_class = &mka_class,
55c151ef 2265};
316d6c15 2266#endif