matroskaenc: don't warn about unknown spherical metadata when there isn't any
[libav.git] / libavformat / matroskaenc.c
1 /*
2 * Matroska muxer
3 * Copyright (c) 2007 David Conrad
4 *
5 * This file is part of Libav.
6 *
7 * Libav 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 * Libav 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 Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22 #include <stdint.h>
23
24 #include "avc.h"
25 #include "hevc.h"
26 #include "avformat.h"
27 #include "avio_internal.h"
28 #include "avlanguage.h"
29 #include "flacenc.h"
30 #include "internal.h"
31 #include "isom.h"
32 #include "matroska.h"
33 #include "riff.h"
34 #include "vorbiscomment.h"
35 #include "wv.h"
36
37 #include "libavutil/avstring.h"
38 #include "libavutil/channel_layout.h"
39 #include "libavutil/dict.h"
40 #include "libavutil/intfloat.h"
41 #include "libavutil/intreadwrite.h"
42 #include "libavutil/lfg.h"
43 #include "libavutil/mathematics.h"
44 #include "libavutil/opt.h"
45 #include "libavutil/random_seed.h"
46 #include "libavutil/samplefmt.h"
47 #include "libavutil/stereo3d.h"
48 #include "libavutil/spherical.h"
49
50 #include "libavcodec/xiph.h"
51 #include "libavcodec/mpeg4audio.h"
52
53 typedef struct ebml_master {
54 int64_t pos; ///< absolute offset in the file where the master's elements start
55 int sizebytes; ///< how many bytes were reserved for the size
56 } ebml_master;
57
58 typedef struct mkv_seekhead_entry {
59 unsigned int elementid;
60 uint64_t segmentpos;
61 } mkv_seekhead_entry;
62
63 typedef struct mkv_seekhead {
64 int64_t filepos;
65 int64_t segment_offset; ///< the file offset to the beginning of the segment
66 int reserved_size; ///< -1 if appending to file
67 int max_entries;
68 mkv_seekhead_entry *entries;
69 int num_entries;
70 } mkv_seekhead;
71
72 typedef struct mkv_cuepoint {
73 uint64_t pts;
74 int tracknum;
75 int64_t cluster_pos; ///< file offset of the cluster containing the block
76 } mkv_cuepoint;
77
78 typedef struct mkv_cues {
79 int64_t segment_offset;
80 mkv_cuepoint *entries;
81 int num_entries;
82 } mkv_cues;
83
84 typedef struct mkv_track {
85 int write_dts;
86 int sample_rate;
87 int64_t sample_rate_offset;
88 int64_t codecpriv_offset;
89 int64_t ts_offset;
90 } mkv_track;
91
92 #define MODE_MATROSKAv2 0x01
93 #define MODE_WEBM 0x02
94
95 typedef struct MatroskaMuxContext {
96 const AVClass *class;
97 int mode;
98 AVIOContext *dyn_bc;
99 ebml_master segment;
100 int64_t segment_offset;
101 ebml_master cluster;
102 int64_t cluster_pos; ///< file offset of the current cluster
103 int64_t cluster_pts;
104 int64_t duration_offset;
105 int64_t duration;
106 mkv_seekhead *main_seekhead;
107 mkv_cues *cues;
108 mkv_track *tracks;
109
110 AVPacket cur_audio_pkt;
111
112 int have_attachments;
113 int have_video;
114
115 int reserve_cues_space;
116 int cluster_size_limit;
117 int64_t cues_pos;
118 int64_t cluster_time_limit;
119 int wrote_chapters;
120 } MatroskaMuxContext;
121
122
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 */
125 #define MAX_SEEKENTRY_SIZE 21
126
127 /** per-cuepoint-track - 3 1-byte EBML IDs, 3 1-byte EBML sizes, 2
128 * 8-byte uint max */
129 #define MAX_CUETRACKPOS_SIZE 22
130
131 /** per-cuepoint - 2 1-byte EBML IDs, 2 1-byte EBML sizes, 8-byte uint max */
132 #define MAX_CUEPOINT_SIZE(num_tracks) 12 + MAX_CUETRACKPOS_SIZE * num_tracks
133
134 static int ebml_id_size(unsigned int id)
135 {
136 return (av_log2(id + 1) - 1) / 7 + 1;
137 }
138
139 static void put_ebml_id(AVIOContext *pb, unsigned int id)
140 {
141 int i = ebml_id_size(id);
142 while (i--)
143 avio_w8(pb, id >> (i * 8));
144 }
145
146 /**
147 * Write an EBML size meaning "unknown size".
148 *
149 * @param bytes The number of bytes the size should occupy (maximum: 8).
150 */
151 static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
152 {
153 assert(bytes <= 8);
154 avio_w8(pb, 0x1ff >> bytes);
155 while (--bytes)
156 avio_w8(pb, 0xff);
157 }
158
159 /**
160 * Calculate how many bytes are needed to represent a given number in EBML.
161 */
162 static int ebml_num_size(uint64_t num)
163 {
164 int bytes = 1;
165 while ((num + 1) >> bytes * 7)
166 bytes++;
167 return bytes;
168 }
169
170 /**
171 * Write a number in EBML variable length format.
172 *
173 * @param bytes The number of bytes that need to be used to write the number.
174 * If zero, any number of bytes can be used.
175 */
176 static void put_ebml_num(AVIOContext *pb, uint64_t num, int bytes)
177 {
178 int i, needed_bytes = ebml_num_size(num);
179
180 // sizes larger than this are currently undefined in EBML
181 assert(num < (1ULL << 56) - 1);
182
183 if (bytes == 0)
184 // don't care how many bytes are used, so use the min
185 bytes = needed_bytes;
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.
188 assert(bytes >= needed_bytes);
189
190 num |= 1ULL << bytes * 7;
191 for (i = bytes - 1; i >= 0; i--)
192 avio_w8(pb, num >> i * 8);
193 }
194
195 static void put_ebml_uint(AVIOContext *pb, unsigned int elementid, uint64_t val)
196 {
197 int i, bytes = 1;
198 uint64_t tmp = val;
199 while (tmp >>= 8)
200 bytes++;
201
202 put_ebml_id(pb, elementid);
203 put_ebml_num(pb, bytes, 0);
204 for (i = bytes - 1; i >= 0; i--)
205 avio_w8(pb, val >> i * 8);
206 }
207
208 static void put_ebml_float(AVIOContext *pb, unsigned int elementid, double val)
209 {
210 put_ebml_id(pb, elementid);
211 put_ebml_num(pb, 8, 0);
212 avio_wb64(pb, av_double2int(val));
213 }
214
215 static void put_ebml_binary(AVIOContext *pb, unsigned int elementid,
216 const void *buf, int size)
217 {
218 put_ebml_id(pb, elementid);
219 put_ebml_num(pb, size, 0);
220 avio_write(pb, buf, size);
221 }
222
223 static void put_ebml_string(AVIOContext *pb, unsigned int elementid,
224 const char *str)
225 {
226 put_ebml_binary(pb, elementid, str, strlen(str));
227 }
228
229 /**
230 * Write a void element of a given size. Useful for reserving space in
231 * the file to be written to later.
232 *
233 * @param size The number of bytes to reserve, which must be at least 2.
234 */
235 static void put_ebml_void(AVIOContext *pb, uint64_t size)
236 {
237 int64_t currentpos = avio_tell(pb);
238
239 assert(size >= 2);
240
241 put_ebml_id(pb, EBML_ID_VOID);
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
245 if (size < 10)
246 put_ebml_num(pb, size - 1, 0);
247 else
248 put_ebml_num(pb, size - 9, 8);
249 while (avio_tell(pb) < currentpos + size)
250 avio_w8(pb, 0);
251 }
252
253 static ebml_master start_ebml_master(AVIOContext *pb, unsigned int elementid,
254 uint64_t expectedsize)
255 {
256 int bytes = expectedsize ? ebml_num_size(expectedsize) : 8;
257 put_ebml_id(pb, elementid);
258 put_ebml_size_unknown(pb, bytes);
259 return (ebml_master) {avio_tell(pb), bytes };
260 }
261
262 static void end_ebml_master(AVIOContext *pb, ebml_master master)
263 {
264 int64_t pos = avio_tell(pb);
265
266 if (avio_seek(pb, master.pos - master.sizebytes, SEEK_SET) < 0)
267 return;
268 put_ebml_num(pb, pos - master.pos, master.sizebytes);
269 avio_seek(pb, pos, SEEK_SET);
270 }
271
272 static void put_xiph_size(AVIOContext *pb, int size)
273 {
274 int i;
275 for (i = 0; i < size / 255; i++)
276 avio_w8(pb, 255);
277 avio_w8(pb, size % 255);
278 }
279
280 /**
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.
285 *
286 * @param segment_offset The absolute offset to the position in the file
287 * where the segment begins.
288 * @param numelements The maximum number of elements that will be indexed
289 * by this seek head, 0 if unlimited.
290 */
291 static mkv_seekhead *mkv_start_seekhead(AVIOContext *pb, int64_t segment_offset,
292 int numelements)
293 {
294 mkv_seekhead *new_seekhead = av_mallocz(sizeof(mkv_seekhead));
295 if (!new_seekhead)
296 return NULL;
297
298 new_seekhead->segment_offset = segment_offset;
299
300 if (numelements > 0) {
301 new_seekhead->filepos = avio_tell(pb);
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
305 new_seekhead->reserved_size = numelements * MAX_SEEKENTRY_SIZE + 13;
306 new_seekhead->max_entries = numelements;
307 put_ebml_void(pb, new_seekhead->reserved_size);
308 }
309 return new_seekhead;
310 }
311
312 static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
313 {
314 int err;
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
320 if ((err = av_reallocp_array(&seekhead->entries, seekhead->num_entries + 1,
321 sizeof(*seekhead->entries))) < 0) {
322 seekhead->num_entries = 0;
323 return err;
324 }
325
326 seekhead->entries[seekhead->num_entries].elementid = elementid;
327 seekhead->entries[seekhead->num_entries++].segmentpos = filepos - seekhead->segment_offset;
328
329 return 0;
330 }
331
332 /**
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.
337 *
338 * @return The file offset where the seekhead was written,
339 * -1 if an error occurred.
340 */
341 static int64_t mkv_write_seekhead(AVIOContext *pb, mkv_seekhead *seekhead)
342 {
343 ebml_master metaseek, seekentry;
344 int64_t currentpos;
345 int i;
346
347 currentpos = avio_tell(pb);
348
349 if (seekhead->reserved_size > 0) {
350 if (avio_seek(pb, seekhead->filepos, SEEK_SET) < 0) {
351 currentpos = -1;
352 goto fail;
353 }
354 }
355
356 metaseek = start_ebml_master(pb, MATROSKA_ID_SEEKHEAD, seekhead->reserved_size);
357 for (i = 0; i < seekhead->num_entries; i++) {
358 mkv_seekhead_entry *entry = &seekhead->entries[i];
359
360 seekentry = start_ebml_master(pb, MATROSKA_ID_SEEKENTRY, MAX_SEEKENTRY_SIZE);
361
362 put_ebml_id(pb, MATROSKA_ID_SEEKID);
363 put_ebml_num(pb, ebml_id_size(entry->elementid), 0);
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) {
372 uint64_t remaining = seekhead->filepos + seekhead->reserved_size - avio_tell(pb);
373 put_ebml_void(pb, remaining);
374 avio_seek(pb, currentpos, SEEK_SET);
375
376 currentpos = seekhead->filepos;
377 }
378 fail:
379 av_free(seekhead->entries);
380 av_free(seekhead);
381
382 return currentpos;
383 }
384
385 static mkv_cues *mkv_start_cues(int64_t segment_offset)
386 {
387 mkv_cues *cues = av_mallocz(sizeof(mkv_cues));
388 if (!cues)
389 return NULL;
390
391 cues->segment_offset = segment_offset;
392 return cues;
393 }
394
395 static int mkv_add_cuepoint(mkv_cues *cues, int stream, int64_t ts, int64_t cluster_pos)
396 {
397 int err;
398
399 if (ts < 0)
400 return 0;
401
402 if ((err = av_reallocp_array(&cues->entries, cues->num_entries + 1,
403 sizeof(*cues->entries))) < 0) {
404 cues->num_entries = 0;
405 return err;
406 }
407
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;
411
412 return 0;
413 }
414
415 static int64_t mkv_write_cues(AVIOContext *pb, mkv_cues *cues, int num_tracks)
416 {
417 ebml_master cues_element;
418 int64_t currentpos;
419 int i, j;
420
421 currentpos = avio_tell(pb);
422 cues_element = start_ebml_master(pb, MATROSKA_ID_CUES, 0);
423
424 for (i = 0; i < cues->num_entries; i++) {
425 ebml_master cuepoint, track_positions;
426 mkv_cuepoint *entry = &cues->entries[i];
427 uint64_t pts = entry->pts;
428
429 cuepoint = start_ebml_master(pb, MATROSKA_ID_POINTENTRY, MAX_CUEPOINT_SIZE(num_tracks));
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++) {
435 track_positions = start_ebml_master(pb, MATROSKA_ID_CUETRACKPOSITION, MAX_CUETRACKPOS_SIZE);
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
445 return currentpos;
446 }
447
448 static int put_xiph_codecpriv(AVFormatContext *s, AVIOContext *pb, AVCodecParameters *par)
449 {
450 uint8_t *header_start[3];
451 int header_len[3];
452 int first_header_size;
453 int j;
454
455 if (par->codec_id == AV_CODEC_ID_VORBIS)
456 first_header_size = 30;
457 else
458 first_header_size = 42;
459
460 if (avpriv_split_xiph_headers(par->extradata, par->extradata_size,
461 first_header_size, header_start, header_len) < 0) {
462 av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
463 return -1;
464 }
465
466 avio_w8(pb, 2); // number packets - 1
467 for (j = 0; j < 2; j++) {
468 put_xiph_size(pb, header_len[j]);
469 }
470 for (j = 0; j < 3; j++)
471 avio_write(pb, header_start[j], header_len[j]);
472
473 return 0;
474 }
475
476 static int put_wv_codecpriv(AVIOContext *pb, AVCodecParameters *par)
477 {
478 if (par->extradata && par->extradata_size == 2)
479 avio_write(pb, par->extradata, 2);
480 else
481 avio_wl16(pb, 0x403); // fallback to the version mentioned in matroska specs
482 return 0;
483 }
484
485 static int put_flac_codecpriv(AVFormatContext *s,
486 AVIOContext *pb, AVCodecParameters *par)
487 {
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,
492 !write_comment);
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
504 snprintf(buf, sizeof(buf), "0x%"PRIx64, par->channel_layout);
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
529 static int get_aac_sample_rates(AVFormatContext *s, uint8_t *extradata, int extradata_size,
530 int *sample_rate, int *output_sample_rate)
531 {
532 MPEG4AudioConfig mp4ac;
533 int ret;
534
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))) {
543 av_log(s, AV_LOG_ERROR,
544 "Error parsing AAC extradata, unable to determine samplerate.\n");
545 return AVERROR(EINVAL);
546 }
547
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 }
559 return 0;
560 }
561
562 static int mkv_write_native_codecprivate(AVFormatContext *s,
563 AVCodecParameters *par,
564 AVIOContext *dyn_cp)
565 {
566 switch (par->codec_id) {
567 case AV_CODEC_ID_VORBIS:
568 case AV_CODEC_ID_THEORA:
569 return put_xiph_codecpriv(s, dyn_cp, par);
570 case AV_CODEC_ID_FLAC:
571 return put_flac_codecpriv(s, dyn_cp, par);
572 case AV_CODEC_ID_WAVPACK:
573 return put_wv_codecpriv(dyn_cp, par);
574 case AV_CODEC_ID_H264:
575 return ff_isom_write_avcc(dyn_cp, par->extradata,
576 par->extradata_size);
577 case AV_CODEC_ID_HEVC:
578 return ff_isom_write_hvcc(dyn_cp, par->extradata,
579 par->extradata_size, 0);
580 case AV_CODEC_ID_ALAC:
581 if (par->extradata_size < 36) {
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
587 avio_write(dyn_cp, par->extradata + 12,
588 par->extradata_size - 12);
589 break;
590 default:
591 if (par->extradata_size)
592 avio_write(dyn_cp, par->extradata, par->extradata_size);
593 }
594
595 return 0;
596 }
597
598 static int mkv_write_codecprivate(AVFormatContext *s, AVIOContext *pb,
599 AVCodecParameters *par,
600 int native_id, int qt_id)
601 {
602 AVIOContext *dyn_cp;
603 uint8_t *codecpriv;
604 int ret, codecpriv_size;
605
606 ret = avio_open_dyn_buf(&dyn_cp);
607 if (ret < 0)
608 return ret;
609
610 if (native_id) {
611 ret = mkv_write_native_codecprivate(s, par, dyn_cp);
612 } else if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
613 if (qt_id) {
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);
619 } else {
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) {
624 av_log(s, AV_LOG_ERROR, "No bmp codec ID found.\n");
625 ret = -1;
626 }
627
628 ff_put_bmp_header(dyn_cp, par, ff_codec_bmp_tags, 0);
629 }
630 } else if (par->codec_type == AVMEDIA_TYPE_AUDIO) {
631 unsigned int tag;
632 tag = ff_codec_get_tag(ff_codec_wav_tags, par->codec_id);
633 if (!tag) {
634 av_log(s, AV_LOG_ERROR, "No wav codec ID found.\n");
635 ret = -1;
636 }
637 if (!par->codec_tag)
638 par->codec_tag = tag;
639
640 ff_put_wav_header(s, dyn_cp, par);
641 }
642
643 codecpriv_size = avio_close_dyn_buf(dyn_cp, &codecpriv);
644 if (codecpriv_size)
645 put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codecpriv,
646 codecpriv_size);
647 av_free(codecpriv);
648 return ret;
649 }
650
651 static 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
665 if (!side_data_size)
666 return 0;
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,
687 private, avio_tell(&b));
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,
697 private, avio_tell(&b));
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
714 end:
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
728 static 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
767 static int mkv_write_stereo_mode(AVFormatContext *s, AVIOContext *pb,
768 AVStream *st, int mode)
769 {
770 int i;
771 int display_width, display_height;
772 int h_width = 1, h_height = 1;
773 AVCodecParameters *par = st->codecpar;
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 }
787
788 // iterate to find the stereo3d side data
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;
802 h_width = 2;
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--;
808 h_height = 2;
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--;
819 h_height = 2;
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--;
825 h_width = 2;
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 }
836 }
837
838 // if webm, do not write unsupported modes
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
844 // write StereoMode if format is valid
845 if (format < MATROSKA_VIDEO_STEREOMODE_TYPE_NB)
846 put_ebml_uint(pb, MATROSKA_ID_VIDEOSTEREOMODE, format);
847
848 // write DisplayWidth and DisplayHeight, they contain the size of
849 // a single source view and/or the display aspect ratio
850 display_width = par->width / h_width;
851 display_height = par->height / h_height;
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
862 return 0;
863 }
864
865 static int mkv_write_track(AVFormatContext *s, MatroskaMuxContext *mkv,
866 int i, AVIOContext *pb)
867 {
868 AVStream *st = s->streams[i];
869 AVCodecParameters *par = st->codecpar;
870 ebml_master subinfo, track;
871 int native_id = 0;
872 int qt_id = 0;
873 int bit_depth = av_get_bits_per_sample(par->codec_id);
874 int sample_rate = par->sample_rate;
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
882 if (par->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
883 mkv->have_attachments = 1;
884 return 0;
885 }
886
887 if (!bit_depth)
888 bit_depth = av_get_bytes_per_sample(par->format) << 3;
889
890 if (par->codec_id == AV_CODEC_ID_AAC) {
891 ret = get_aac_sample_rates(s, par->extradata, par->extradata_size, &sample_rate,
892 &output_sample_rate);
893 if (ret < 0)
894 return ret;
895 }
896
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)
901
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");
906
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));
911 if (st->disposition & AV_DISPOSITION_FORCED)
912 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGFORCED, !!(st->disposition & AV_DISPOSITION_FORCED));
913
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 },
917 st->time_base);
918
919 put_ebml_uint(pb, MATROSKA_ID_CODECDELAY,
920 av_rescale_q(par->initial_padding,
921 (AVRational){ 1, par->sample_rate },
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++) {
928 if (ff_mkv_codec_tags[j].id == par->codec_id) {
929 put_ebml_string(pb, MATROSKA_ID_CODECID, ff_mkv_codec_tags[j].str);
930 native_id = 1;
931 break;
932 }
933 }
934
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)) {
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 }
943
944 switch (par->codec_type) {
945 case AVMEDIA_TYPE_VIDEO:
946 mkv->have_video = 1;
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 &&
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))
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;
965 }
966
967 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
968
969 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , par->width);
970 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, par->height);
971
972 mkv_write_field_order(pb, par->field_order);
973
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;
979 ret = mkv_write_video_projection(s, pb, st);
980 if (ret < 0)
981 return ret;
982
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);
994 put_ebml_uint (pb, MATROSKA_ID_AUDIOCHANNELS , par->channels);
995
996 mkv->tracks[i].sample_rate_offset = avio_tell(pb);
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) {
1008 av_log(s, AV_LOG_ERROR, "Subtitle codec %d is not supported.\n", par->codec_id);
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 }
1016
1017 mkv->tracks[i].codecpriv_offset = avio_tell(pb);
1018 ret = mkv_write_codecprivate(s, pb, par, native_id, qt_id);
1019 if (ret < 0)
1020 return ret;
1021
1022 end_ebml_master(pb, track);
1023
1024 return 0;
1025 }
1026
1027 static 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;
1033
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);
1041 if (ret < 0)
1042 return ret;
1043 }
1044 end_ebml_master(pb, tracks);
1045 return 0;
1046 }
1047
1048 static int mkv_write_chapters(AVFormatContext *s)
1049 {
1050 MatroskaMuxContext *mkv = s->priv_data;
1051 AVIOContext *pb = s->pb;
1052 ebml_master chapters, editionentry;
1053 AVRational scale = {1, 1E9};
1054 int i, ret;
1055
1056 if (!s->nb_chapters || mkv->wrote_chapters)
1057 return 0;
1058
1059 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CHAPTERS, avio_tell(pb));
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];
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);
1071 AVDictionaryEntry *t = NULL;
1072 if (chapterstart < 0 || chapterstart > chapterend || chapterend < 0) {
1073 av_log(s, AV_LOG_ERROR,
1074 "Invalid chapter start (%"PRId64") or end (%"PRId64").\n",
1075 chapterstart, chapterend);
1076 return AVERROR_INVALIDDATA;
1077 }
1078
1079 chapteratom = start_ebml_master(pb, MATROSKA_ID_CHAPTERATOM, 0);
1080 put_ebml_uint(pb, MATROSKA_ID_CHAPTERUID, c->id);
1081 put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMESTART, chapterstart);
1082 put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMEEND, chapterend);
1083 put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGHIDDEN , 0);
1084 put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGENABLED, 1);
1085 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
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);
1095
1096 mkv->wrote_chapters = 1;
1097 return 0;
1098 }
1099
1100 static int mkv_write_simpletag(AVIOContext *pb, AVDictionaryEntry *t)
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
1107 if (!key)
1108 return AVERROR(ENOMEM);
1109
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);
1131 return 0;
1132 }
1133
1134 static int mkv_write_tag(AVFormatContext *s, AVDictionary *m, unsigned int elementid,
1135 unsigned int uid, ebml_master *tags)
1136 {
1137 MatroskaMuxContext *mkv = s->priv_data;
1138 ebml_master tag, targets;
1139 AVDictionaryEntry *t = NULL;
1140 int ret;
1141
1142 if (!tags->pos) {
1143 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TAGS, avio_tell(s->pb));
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
1155 while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX))) {
1156 if (av_strcasecmp(t->key, "title") &&
1157 av_strcasecmp(t->key, "encoding_tool") &&
1158 (elementid != MATROSKA_ID_TAGTARGETS_TRACKUID ||
1159 av_strcasecmp(t->key, "language"))) {
1160 ret = mkv_write_simpletag(s->pb, t);
1161 if (ret < 0)
1162 return ret;
1163 }
1164 }
1165
1166 end_ebml_master(s->pb, tag);
1167 return 0;
1168 }
1169
1170 static int mkv_write_tags(AVFormatContext *s)
1171 {
1172 ebml_master tags = {0};
1173 int i, ret;
1174
1175 ff_metadata_conv_ctx(s, ff_mkv_metadata_conv, NULL);
1176
1177 if (av_dict_get(s->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX)) {
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
1185 if (!av_dict_get(st->metadata, "", 0, AV_DICT_IGNORE_SUFFIX))
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
1195 if (!av_dict_get(ch->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX))
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
1207 static 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
1231 if (st->codecpar->codec_type != AVMEDIA_TYPE_ATTACHMENT)
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;
1245 else if (st->codecpar->codec_id != AV_CODEC_ID_NONE ) {
1246 int i;
1247 for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
1248 if (ff_mkv_mime_tags[i].id == st->codecpar->codec_id) {
1249 mimetype = ff_mkv_mime_tags[i].str;
1250 break;
1251 }
1252 for (i = 0; ff_mkv_image_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
1253 if (ff_mkv_image_mime_tags[i].id == st->codecpar->codec_id) {
1254 mimetype = ff_mkv_image_mime_tags[i].str;
1255 break;
1256 }
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);
1265 put_ebml_binary(pb, MATROSKA_ID_FILEDATA, st->codecpar->extradata, st->codecpar->extradata_size);
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
1274 static int mkv_write_header(AVFormatContext *s)
1275 {
1276 MatroskaMuxContext *mkv = s->priv_data;
1277 AVIOContext *pb = s->pb;
1278 ebml_master ebml_header, segment_info;
1279 AVDictionaryEntry *tag;
1280 int ret, i;
1281
1282 if (!strcmp(s->oformat->name, "webm"))
1283 mkv->mode = MODE_WEBM;
1284 else
1285 mkv->mode = MODE_MATROSKAv2;
1286
1287 mkv->tracks = av_mallocz(s->nb_streams * sizeof(*mkv->tracks));
1288 if (!mkv->tracks)
1289 return AVERROR(ENOMEM);
1290
1291 ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
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);
1296 put_ebml_string (pb, EBML_ID_DOCTYPE , s->oformat->name);
1297 put_ebml_uint (pb, EBML_ID_DOCTYPEVERSION , 4);
1298 put_ebml_uint (pb, EBML_ID_DOCTYPEREADVERSION , 2);
1299 end_ebml_master(pb, ebml_header);
1300
1301 mkv->segment = start_ebml_master(pb, MATROSKA_ID_SEGMENT, 0);
1302 mkv->segment_offset = avio_tell(pb);
1303
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
1309 mkv->main_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 10);
1310 if (!mkv->main_seekhead)
1311 return AVERROR(ENOMEM);
1312
1313 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_INFO, avio_tell(pb));
1314 if (ret < 0) return ret;
1315
1316 segment_info = start_ebml_master(pb, MATROSKA_ID_INFO, 0);
1317 put_ebml_uint(pb, MATROSKA_ID_TIMECODESCALE, 1000000);
1318 if ((tag = av_dict_get(s->metadata, "title", NULL, 0)))
1319 put_ebml_string(pb, MATROSKA_ID_TITLE, tag->value);
1320 if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
1321 uint32_t segment_uid[4];
1322 AVLFG lfg;
1323
1324 av_lfg_init(&lfg, av_get_random_seed());
1325
1326 for (i = 0; i < 4; i++)
1327 segment_uid[i] = av_lfg_get(&lfg);
1328
1329 put_ebml_string(pb, MATROSKA_ID_MUXINGAPP, LIBAVFORMAT_IDENT);
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);
1334 put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
1335 }
1336
1337 // reserve space for the duration
1338 mkv->duration = 0;
1339 mkv->duration_offset = avio_tell(pb);
1340 put_ebml_void(pb, 11); // assumes double-precision float to be written
1341 end_ebml_master(pb, segment_info);
1342
1343 ret = mkv_write_tracks(s);
1344 if (ret < 0)
1345 return ret;
1346
1347 if (mkv->mode != MODE_WEBM) {
1348 ret = mkv_write_chapters(s);
1349 if (ret < 0)
1350 return ret;
1351
1352 ret = mkv_write_tags(s);
1353 if (ret < 0)
1354 return ret;
1355
1356 ret = mkv_write_attachments(s);
1357 if (ret < 0)
1358 return ret;
1359 }
1360
1361 if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL))
1362 mkv_write_seekhead(pb, mkv->main_seekhead);
1363
1364 mkv->cues = mkv_start_cues(mkv->segment_offset);
1365 if (!mkv->cues)
1366 return AVERROR(ENOMEM);
1367
1368 if ((pb->seekable & AVIO_SEEKABLE_NORMAL) && mkv->reserve_cues_space) {
1369 mkv->cues_pos = avio_tell(pb);
1370 put_ebml_void(pb, mkv->reserve_cues_space);
1371 }
1372
1373 av_init_packet(&mkv->cur_audio_pkt);
1374 mkv->cur_audio_pkt.size = 0;
1375
1376 avio_flush(pb);
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
1380 if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
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
1392 return 0;
1393 }
1394
1395 static int mkv_blockgroup_size(int pkt_size)
1396 {
1397 int size = pkt_size + 4;
1398 size += ebml_num_size(size);
1399 size += 2; // EBML ID for block and block duration
1400 size += 8; // max size of block duration
1401 size += ebml_num_size(size);
1402 size += 1; // blockgroup EBML ID
1403 return size;
1404 }
1405
1406 static int ass_get_duration(AVFormatContext *s, const uint8_t *p)
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;
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
1423 start = 3600000 * sh + 60000 * sm + 1000 * ss + 10 * sc;
1424 end = 3600000 * eh + 60000 * em + 1000 * es + 10 * ec;
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
1433 return end - start;
1434 }
1435
1436 static int mkv_write_ass_blocks(AVFormatContext *s, AVIOContext *pb,
1437 AVPacket *pkt)
1438 {
1439 MatroskaMuxContext *mkv = s->priv_data;
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) {
1446 int duration = ass_get_duration(s, data);
1447 max_duration = FFMAX(duration, max_duration);
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))))
1454 return max_duration;
1455 size -= start - data;
1456 sscanf(data, "Dialogue: %d,", &layer);
1457 i = snprintf(buffer, sizeof(buffer), "%" PRId64 ",%d,",
1458 s->streams[pkt->stream_index]->nb_frames, layer);
1459 size = FFMIN(i + size, sizeof(buffer));
1460 memcpy(buffer + i, start, size - i);
1461
1462 av_log(s, AV_LOG_DEBUG,
1463 "Writing block at offset %" PRIu64 ", size %d, "
1464 "pts %" PRId64 ", duration %d\n",
1465 avio_tell(pb), size, pkt->pts, duration);
1466 blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
1467 mkv_blockgroup_size(size));
1468 put_ebml_id(pb, MATROSKA_ID_BLOCK);
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));
1472 avio_wb16(pb, pkt->pts - mkv->cluster_pts);
1473 avio_w8(pb, 0);
1474 avio_write(pb, buffer, size);
1475 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
1476 end_ebml_master(pb, blockgroup);
1477
1478 data += line_size;
1479 data_size -= line_size;
1480 }
1481
1482 return max_duration;
1483 }
1484
1485 static 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;
1533 fail:
1534 av_freep(&dst);
1535 return ret;
1536 }
1537
1538 static void mkv_write_block(AVFormatContext *s, AVIOContext *pb,
1539 unsigned int blockid, AVPacket *pkt, int flags)
1540 {
1541 MatroskaMuxContext *mkv = s->priv_data;
1542 AVCodecParameters *par = s->streams[pkt->stream_index]->codecpar;
1543 uint8_t *data = NULL;
1544 int offset = 0, size = pkt->size;
1545 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1546 ts += mkv->tracks[pkt->stream_index].ts_offset;
1547
1548 av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
1549 "pts %" PRId64 ", dts %" PRId64 ", duration %" PRId64 ", flags %d\n",
1550 avio_tell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration, flags);
1551 if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 0 &&
1552 (AV_RB24(par->extradata) == 1 || AV_RB32(par->extradata) == 1))
1553 ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
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))
1556 /* extradata is Annex B, assume the bitstream is too and convert it */
1557 ff_hevc_annexb2mp4_buf(pkt->data, &data, &size, 0, NULL);
1558 else if (par->codec_id == AV_CODEC_ID_WAVPACK) {
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
1565 data = pkt->data;
1566
1567 if (par->codec_id == AV_CODEC_ID_PRORES) {
1568 /* Matroska specification requires to remove the first QuickTime atom
1569 */
1570 size -= 8;
1571 offset = 8;
1572 }
1573
1574 put_ebml_id(pb, blockid);
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));
1578 avio_wb16(pb, ts - mkv->cluster_pts);
1579 avio_w8(pb, flags);
1580 avio_write(pb, data + offset, size);
1581 if (data != pkt->data)
1582 av_free(data);
1583 }
1584
1585 static int srt_get_duration(uint8_t **buf)
1586 {
1587 int i, duration = 0;
1588
1589 for (i = 0; i < 2 && !duration; i++) {
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) {
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
1602 duration = e_hsec - s_hsec;
1603 }
1604 *buf += strcspn(*buf, "\n") + 1;
1605 }
1606 return duration;
1607 }
1608
1609 static int mkv_write_srt_blocks(AVFormatContext *s, AVIOContext *pb,
1610 AVPacket *pkt)
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
1626 static 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
1635 bufsize = avio_close_dyn_buf(mkv->dyn_bc, &dyn_buf);
1636 avio_write(s->pb, dyn_buf, bufsize);
1637 av_free(dyn_buf);
1638 mkv->dyn_bc = NULL;
1639 }
1640
1641 static 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;
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;
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
1708 static int mkv_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
1709 {
1710 MatroskaMuxContext *mkv = s->priv_data;
1711 AVIOContext *pb = s->pb;
1712 AVCodecParameters *par = s->streams[pkt->stream_index]->codecpar;
1713 int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1714 int duration = pkt->duration;
1715 int ret;
1716 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1717
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 }
1722 ts += mkv->tracks[pkt->stream_index].ts_offset;
1723
1724 if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL)) {
1725 if (!mkv->dyn_bc) {
1726 ret = avio_open_dyn_buf(&mkv->dyn_bc);
1727 if (ret < 0)
1728 return ret;
1729 }
1730 pb = mkv->dyn_bc;
1731 }
1732
1733 if (!mkv->cluster_pos) {
1734 mkv->cluster_pos = avio_tell(s->pb);
1735 mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER, 0);
1736 put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, FFMAX(0, ts));
1737 mkv->cluster_pts = FFMAX(0, ts);
1738 }
1739
1740 if (par->codec_type != AVMEDIA_TYPE_SUBTITLE) {
1741 mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
1742 } else if (par->codec_id == AV_CODEC_ID_SSA) {
1743 duration = mkv_write_ass_blocks(s, pb, pkt);
1744 } else if (par->codec_id == AV_CODEC_ID_SRT) {
1745 duration = mkv_write_srt_blocks(s, pb, pkt);
1746 } else {
1747 ebml_master blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
1748 mkv_blockgroup_size(pkt->size));
1749 duration = pkt->duration;
1750 #if FF_API_CONVERGENCE_DURATION
1751 FF_DISABLE_DEPRECATION_WARNINGS
1752 if (pkt->convergence_duration)
1753 duration = pkt->convergence_duration;
1754 FF_ENABLE_DEPRECATION_WARNINGS
1755 #endif
1756 mkv_write_block(s, pb, MATROSKA_ID_BLOCK, pkt, 0);
1757 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
1758 end_ebml_master(pb, blockgroup);
1759 }
1760
1761 if (par->codec_type == AVMEDIA_TYPE_VIDEO && keyframe) {
1762 ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, ts,
1763 mkv->cluster_pos);
1764 if (ret < 0)
1765 return ret;
1766 }
1767
1768 mkv->duration = FFMAX(mkv->duration, ts + duration);
1769 return 0;
1770 }
1771
1772 static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
1773 {
1774 MatroskaMuxContext *mkv = s->priv_data;
1775 int codec_type = s->streams[pkt->stream_index]->codecpar->codec_type;
1776 int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1777 int cluster_size;
1778 int64_t cluster_time;
1779 AVIOContext *pb;
1780 int ret;
1781
1782 ret = mkv_check_new_extra_data(s, pkt);
1783 if (ret < 0)
1784 return ret;
1785
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;
1790 cluster_time += mkv->tracks[pkt->stream_index].ts_offset;
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
1794 if (s->pb->seekable & AVIO_SEEKABLE_NORMAL) {
1795 pb = s->pb;
1796 cluster_size = avio_tell(pb) - mkv->cluster_pos;
1797 } else {
1798 pb = mkv->dyn_bc;
1799 cluster_size = avio_tell(pb);
1800 }
1801
1802 if (mkv->cluster_pos &&
1803 (cluster_size > mkv->cluster_size_limit ||
1804 cluster_time > mkv->cluster_time_limit ||
1805 (codec_type == AVMEDIA_TYPE_VIDEO && keyframe &&
1806 cluster_size > 4 * 1024))) {
1807 av_log(s, AV_LOG_DEBUG,
1808 "Starting new cluster at offset %" PRIu64 " bytes, "
1809 "pts %" PRIu64 "dts %" PRIu64 "\n",
1810 avio_tell(pb), pkt->pts, pkt->dts);
1811 end_ebml_master(pb, mkv->cluster);
1812 mkv->cluster_pos = 0;
1813 if (mkv->dyn_bc)
1814 mkv_flush_dynbuf(s);
1815 avio_flush(s->pb);
1816 }
1817
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
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);
1826 av_packet_unref(&mkv->cur_audio_pkt);
1827 if (ret < 0) {
1828 av_log(s, AV_LOG_ERROR,
1829 "Could not write cached audio packet ret:%d\n", ret);
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
1836 if (codec_type == AVMEDIA_TYPE_AUDIO) {
1837 ret = av_packet_ref(&mkv->cur_audio_pkt, pkt);
1838 } else
1839 ret = mkv_write_packet_internal(s, pkt);
1840 return ret;
1841 }
1842
1843 static int mkv_write_flush_packet(AVFormatContext *s, AVPacket *pkt)
1844 {
1845 MatroskaMuxContext *mkv = s->priv_data;
1846 AVIOContext *pb;
1847 if (s->pb->seekable & AVIO_SEEKABLE_NORMAL)
1848 pb = s->pb;
1849 else
1850 pb = mkv->dyn_bc;
1851 if (!pkt) {
1852 if (mkv->cluster_pos) {
1853 av_log(s, AV_LOG_DEBUG,
1854 "Flushing cluster at offset %" PRIu64 " bytes\n",
1855 avio_tell(pb));
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 }
1862 return 1;
1863 }
1864 return mkv_write_packet(s, pkt);
1865 }
1866
1867 static int mkv_write_trailer(AVFormatContext *s)
1868 {
1869 MatroskaMuxContext *mkv = s->priv_data;
1870 AVIOContext *pb = s->pb;
1871 int64_t currentpos, cuespos;
1872 int ret;
1873
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);
1877 av_packet_unref(&mkv->cur_audio_pkt);
1878 if (ret < 0) {
1879 av_log(s, AV_LOG_ERROR,
1880 "Could not write cached audio packet ret:%d\n", ret);
1881 return ret;
1882 }
1883 }
1884
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 }
1891
1892 if (mkv->mode != MODE_WEBM) {
1893 ret = mkv_write_chapters(s);
1894 if (ret < 0)
1895 return ret;
1896 }
1897
1898 if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
1899 if (mkv->cues->num_entries) {
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
1906 cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
1907 cues_end = avio_tell(pb);
1908 if (cues_end > cuespos + mkv->reserve_cues_space) {
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);
1913 return AVERROR(EINVAL);
1914 }
1915
1916 if (cues_end < cuespos + mkv->reserve_cues_space)
1917 put_ebml_void(pb, mkv->reserve_cues_space -
1918 (cues_end - cuespos));
1919
1920 avio_seek(pb, currentpos, SEEK_SET);
1921 } else {
1922 cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
1923 }
1924
1925 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CUES,
1926 cuespos);
1927 if (ret < 0)
1928 return ret;
1929 }
1930
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);
1935 currentpos = avio_tell(pb);
1936 avio_seek(pb, mkv->duration_offset, SEEK_SET);
1937 put_ebml_float(pb, MATROSKA_ID_DURATION, mkv->duration);
1938
1939 avio_seek(pb, currentpos, SEEK_SET);
1940 }
1941
1942 end_ebml_master(pb, mkv->segment);
1943 av_free(mkv->tracks);
1944 av_freep(&mkv->cues->entries);
1945 av_freep(&mkv->cues);
1946
1947 return 0;
1948 }
1949
1950 static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
1951 {
1952 int i;
1953 for (i = 0; ff_mkv_codec_tags[i].id != AV_CODEC_ID_NONE; i++)
1954 if (ff_mkv_codec_tags[i].id == codec_id)
1955 return 1;
1956
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
1960 if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)
1961 return 1;
1962 }
1963
1964 return 0;
1965 }
1966
1967 #define OFFSET(x) offsetof(MatroskaMuxContext, x)
1968 #define FLAGS AV_OPT_FLAG_ENCODING_PARAM
1969 static const AVOption options[] = {
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 },
1973 { NULL },
1974 };
1975
1976 #if CONFIG_MATROSKA_MUXER
1977 static 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
1984 AVOutputFormat ff_matroska_muxer = {
1985 .name = "matroska",
1986 .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
1987 .mime_type = "video/x-matroska",
1988 .extensions = "mkv",
1989 .priv_data_size = sizeof(MatroskaMuxContext),
1990 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
1991 AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
1992 .video_codec = CONFIG_LIBX264_ENCODER ?
1993 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
1994 .write_header = mkv_write_header,
1995 .write_packet = mkv_write_flush_packet,
1996 .write_trailer = mkv_write_trailer,
1997 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
1998 AVFMT_TS_NONSTRICT | AVFMT_ALLOW_FLUSH,
1999 .codec_tag = (const AVCodecTag* const []){
2000 ff_codec_bmp_tags, ff_codec_wav_tags, 0
2001 },
2002 .subtitle_codec = AV_CODEC_ID_SSA,
2003 .query_codec = mkv_query_codec,
2004 .priv_class = &matroska_class,
2005 };
2006 #endif
2007
2008 #if CONFIG_WEBM_MUXER
2009 static 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
2016 AVOutputFormat ff_webm_muxer = {
2017 .name = "webm",
2018 .long_name = NULL_IF_CONFIG_SMALL("WebM"),
2019 .mime_type = "video/webm",
2020 .extensions = "webm",
2021 .priv_data_size = sizeof(MatroskaMuxContext),
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,
2024 .write_header = mkv_write_header,
2025 .write_packet = mkv_write_flush_packet,
2026 .write_trailer = mkv_write_trailer,
2027 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
2028 AVFMT_TS_NONSTRICT | AVFMT_ALLOW_FLUSH,
2029 .priv_class = &webm_class,
2030 };
2031 #endif
2032
2033 #if CONFIG_MATROSKA_AUDIO_MUXER
2034 static 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 };
2040 AVOutputFormat ff_matroska_audio_muxer = {
2041 .name = "matroska",
2042 .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
2043 .mime_type = "audio/x-matroska",
2044 .extensions = "mka",
2045 .priv_data_size = sizeof(MatroskaMuxContext),
2046 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
2047 AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
2048 .video_codec = AV_CODEC_ID_NONE,
2049 .write_header = mkv_write_header,
2050 .write_packet = mkv_write_flush_packet,
2051 .write_trailer = mkv_write_trailer,
2052 .flags = AVFMT_GLOBALHEADER | AVFMT_TS_NONSTRICT |
2053 AVFMT_ALLOW_FLUSH,
2054 .codec_tag = (const AVCodecTag* const []){ ff_codec_wav_tags, 0 },
2055 .priv_class = &mka_class,
2056 };
2057 #endif