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