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