0a3775daea37a88b1c43e8d9622476bca9531a4c
[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 if (st->avg_frame_rate.num > 0 && st->avg_frame_rate.den > 0)
680 put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, 1E9 / av_q2d(st->avg_frame_rate));
681
682 if (!native_id &&
683 ff_codec_get_tag(ff_codec_movvideo_tags, codec->codec_id) &&
684 (!ff_codec_get_tag(ff_codec_bmp_tags, codec->codec_id)
685 || codec->codec_id == AV_CODEC_ID_SVQ1
686 || codec->codec_id == AV_CODEC_ID_SVQ3
687 || codec->codec_id == AV_CODEC_ID_CINEPAK))
688 qt_id = 1;
689
690 if (qt_id)
691 put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");
692 else if (!native_id) {
693 // if there is no mkv-specific codec ID, use VFW mode
694 put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");
695 mkv->tracks[i].write_dts = 1;
696 }
697
698 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
699 // XXX: interlace flag?
700 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , codec->width);
701 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, codec->height);
702 if ((tag = av_dict_get(s->metadata, "stereo_mode", NULL, 0))) {
703 uint8_t stereo_fmt = atoi(tag->value);
704 int valid_fmt = 0;
705
706 switch (mkv->mode) {
707 case MODE_WEBM:
708 if (stereo_fmt <= MATROSKA_VIDEO_STEREOMODE_TYPE_TOP_BOTTOM
709 || stereo_fmt == MATROSKA_VIDEO_STEREOMODE_TYPE_RIGHT_LEFT)
710 valid_fmt = 1;
711 break;
712 case MODE_MATROSKAv2:
713 if (stereo_fmt <= MATROSKA_VIDEO_STEREOMODE_TYPE_BOTH_EYES_BLOCK_RL)
714 valid_fmt = 1;
715 break;
716 }
717
718 if (valid_fmt)
719 put_ebml_uint (pb, MATROSKA_ID_VIDEOSTEREOMODE, stereo_fmt);
720 }
721 if (st->sample_aspect_ratio.num) {
722 int d_width = codec->width*av_q2d(st->sample_aspect_ratio);
723 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , d_width);
724 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, codec->height);
725 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYUNIT, 3);
726 }
727 end_ebml_master(pb, subinfo);
728 break;
729
730 case AVMEDIA_TYPE_AUDIO:
731 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_AUDIO);
732
733 if (!native_id)
734 // no mkv-specific ID, use ACM mode
735 put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");
736
737 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);
738 put_ebml_uint (pb, MATROSKA_ID_AUDIOCHANNELS , codec->channels);
739 put_ebml_float (pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, sample_rate);
740 if (output_sample_rate)
741 put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
742 if (bit_depth)
743 put_ebml_uint(pb, MATROSKA_ID_AUDIOBITDEPTH, bit_depth);
744 end_ebml_master(pb, subinfo);
745 break;
746
747 case AVMEDIA_TYPE_SUBTITLE:
748 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_SUBTITLE);
749 if (!native_id) {
750 av_log(s, AV_LOG_ERROR, "Subtitle codec %d is not supported.\n", codec->codec_id);
751 return AVERROR(ENOSYS);
752 }
753 break;
754 default:
755 av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.\n");
756 break;
757 }
758 ret = mkv_write_codecprivate(s, pb, codec, native_id, qt_id);
759 if (ret < 0) return ret;
760
761 end_ebml_master(pb, track);
762
763 // ms precision is the de-facto standard timescale for mkv files
764 avpriv_set_pts_info(st, 64, 1, 1000);
765 }
766 end_ebml_master(pb, tracks);
767 return 0;
768 }
769
770 static int mkv_write_chapters(AVFormatContext *s)
771 {
772 MatroskaMuxContext *mkv = s->priv_data;
773 AVIOContext *pb = s->pb;
774 ebml_master chapters, editionentry;
775 AVRational scale = {1, 1E9};
776 int i, ret;
777
778 if (!s->nb_chapters || mkv->wrote_chapters)
779 return 0;
780
781 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CHAPTERS, avio_tell(pb));
782 if (ret < 0) return ret;
783
784 chapters = start_ebml_master(pb, MATROSKA_ID_CHAPTERS , 0);
785 editionentry = start_ebml_master(pb, MATROSKA_ID_EDITIONENTRY, 0);
786 put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGDEFAULT, 1);
787 put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGHIDDEN , 0);
788 for (i = 0; i < s->nb_chapters; i++) {
789 ebml_master chapteratom, chapterdisplay;
790 AVChapter *c = s->chapters[i];
791 AVDictionaryEntry *t = NULL;
792
793 chapteratom = start_ebml_master(pb, MATROSKA_ID_CHAPTERATOM, 0);
794 put_ebml_uint(pb, MATROSKA_ID_CHAPTERUID, c->id);
795 put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMESTART,
796 av_rescale_q(c->start, c->time_base, scale));
797 put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMEEND,
798 av_rescale_q(c->end, c->time_base, scale));
799 put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGHIDDEN , 0);
800 put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGENABLED, 1);
801 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
802 chapterdisplay = start_ebml_master(pb, MATROSKA_ID_CHAPTERDISPLAY, 0);
803 put_ebml_string(pb, MATROSKA_ID_CHAPSTRING, t->value);
804 put_ebml_string(pb, MATROSKA_ID_CHAPLANG , "und");
805 end_ebml_master(pb, chapterdisplay);
806 }
807 end_ebml_master(pb, chapteratom);
808 }
809 end_ebml_master(pb, editionentry);
810 end_ebml_master(pb, chapters);
811
812 mkv->wrote_chapters = 1;
813 return 0;
814 }
815
816 static void mkv_write_simpletag(AVIOContext *pb, AVDictionaryEntry *t)
817 {
818 uint8_t *key = av_strdup(t->key);
819 uint8_t *p = key;
820 const uint8_t *lang = NULL;
821 ebml_master tag;
822
823 if ((p = strrchr(p, '-')) &&
824 (lang = av_convert_lang_to(p + 1, AV_LANG_ISO639_2_BIBL)))
825 *p = 0;
826
827 p = key;
828 while (*p) {
829 if (*p == ' ')
830 *p = '_';
831 else if (*p >= 'a' && *p <= 'z')
832 *p -= 'a' - 'A';
833 p++;
834 }
835
836 tag = start_ebml_master(pb, MATROSKA_ID_SIMPLETAG, 0);
837 put_ebml_string(pb, MATROSKA_ID_TAGNAME, key);
838 if (lang)
839 put_ebml_string(pb, MATROSKA_ID_TAGLANG, lang);
840 put_ebml_string(pb, MATROSKA_ID_TAGSTRING, t->value);
841 end_ebml_master(pb, tag);
842
843 av_freep(&key);
844 }
845
846 static int mkv_write_tag(AVFormatContext *s, AVDictionary *m, unsigned int elementid,
847 unsigned int uid, ebml_master *tags)
848 {
849 MatroskaMuxContext *mkv = s->priv_data;
850 ebml_master tag, targets;
851 AVDictionaryEntry *t = NULL;
852 int ret;
853
854 if (!tags->pos) {
855 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TAGS, avio_tell(s->pb));
856 if (ret < 0) return ret;
857
858 *tags = start_ebml_master(s->pb, MATROSKA_ID_TAGS, 0);
859 }
860
861 tag = start_ebml_master(s->pb, MATROSKA_ID_TAG, 0);
862 targets = start_ebml_master(s->pb, MATROSKA_ID_TAGTARGETS, 0);
863 if (elementid)
864 put_ebml_uint(s->pb, elementid, uid);
865 end_ebml_master(s->pb, targets);
866
867 while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX)))
868 if (av_strcasecmp(t->key, "title") &&
869 av_strcasecmp(t->key, "encoding_tool"))
870 mkv_write_simpletag(s->pb, t);
871
872 end_ebml_master(s->pb, tag);
873 return 0;
874 }
875
876 static int mkv_write_tags(AVFormatContext *s)
877 {
878 ebml_master tags = {0};
879 int i, ret;
880
881 ff_metadata_conv_ctx(s, ff_mkv_metadata_conv, NULL);
882
883 if (av_dict_get(s->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX)) {
884 ret = mkv_write_tag(s, s->metadata, 0, 0, &tags);
885 if (ret < 0) return ret;
886 }
887
888 for (i = 0; i < s->nb_streams; i++) {
889 AVStream *st = s->streams[i];
890
891 if (!av_dict_get(st->metadata, "", 0, AV_DICT_IGNORE_SUFFIX))
892 continue;
893
894 ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &tags);
895 if (ret < 0) return ret;
896 }
897
898 for (i = 0; i < s->nb_chapters; i++) {
899 AVChapter *ch = s->chapters[i];
900
901 if (!av_dict_get(ch->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX))
902 continue;
903
904 ret = mkv_write_tag(s, ch->metadata, MATROSKA_ID_TAGTARGETS_CHAPTERUID, ch->id, &tags);
905 if (ret < 0) return ret;
906 }
907
908 if (tags.pos)
909 end_ebml_master(s->pb, tags);
910 return 0;
911 }
912
913 static int mkv_write_attachments(AVFormatContext *s)
914 {
915 MatroskaMuxContext *mkv = s->priv_data;
916 AVIOContext *pb = s->pb;
917 ebml_master attachments;
918 AVLFG c;
919 int i, ret;
920
921 if (!mkv->have_attachments)
922 return 0;
923
924 av_lfg_init(&c, av_get_random_seed());
925
926 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_ATTACHMENTS, avio_tell(pb));
927 if (ret < 0) return ret;
928
929 attachments = start_ebml_master(pb, MATROSKA_ID_ATTACHMENTS, 0);
930
931 for (i = 0; i < s->nb_streams; i++) {
932 AVStream *st = s->streams[i];
933 ebml_master attached_file;
934 AVDictionaryEntry *t;
935 const char *mimetype = NULL;
936
937 if (st->codec->codec_type != AVMEDIA_TYPE_ATTACHMENT)
938 continue;
939
940 attached_file = start_ebml_master(pb, MATROSKA_ID_ATTACHEDFILE, 0);
941
942 if (t = av_dict_get(st->metadata, "title", NULL, 0))
943 put_ebml_string(pb, MATROSKA_ID_FILEDESC, t->value);
944 if (!(t = av_dict_get(st->metadata, "filename", NULL, 0))) {
945 av_log(s, AV_LOG_ERROR, "Attachment stream %d has no filename tag.\n", i);
946 return AVERROR(EINVAL);
947 }
948 put_ebml_string(pb, MATROSKA_ID_FILENAME, t->value);
949 if (t = av_dict_get(st->metadata, "mimetype", NULL, 0))
950 mimetype = t->value;
951 else if (st->codec->codec_id != AV_CODEC_ID_NONE ) {
952 int i;
953 for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++)
954 if (ff_mkv_mime_tags[i].id == st->codec->codec_id) {
955 mimetype = ff_mkv_mime_tags[i].str;
956 break;
957 }
958 }
959 if (!mimetype) {
960 av_log(s, AV_LOG_ERROR, "Attachment stream %d has no mimetype tag and "
961 "it cannot be deduced from the codec id.\n", i);
962 return AVERROR(EINVAL);
963 }
964
965 put_ebml_string(pb, MATROSKA_ID_FILEMIMETYPE, mimetype);
966 put_ebml_binary(pb, MATROSKA_ID_FILEDATA, st->codec->extradata, st->codec->extradata_size);
967 put_ebml_uint(pb, MATROSKA_ID_FILEUID, av_lfg_get(&c));
968 end_ebml_master(pb, attached_file);
969 }
970 end_ebml_master(pb, attachments);
971
972 return 0;
973 }
974
975 static int mkv_write_header(AVFormatContext *s)
976 {
977 MatroskaMuxContext *mkv = s->priv_data;
978 AVIOContext *pb = s->pb;
979 ebml_master ebml_header, segment_info;
980 AVDictionaryEntry *tag;
981 int ret, i;
982
983 if (!strcmp(s->oformat->name, "webm")) mkv->mode = MODE_WEBM;
984 else mkv->mode = MODE_MATROSKAv2;
985
986 mkv->tracks = av_mallocz(s->nb_streams * sizeof(*mkv->tracks));
987 if (!mkv->tracks)
988 return AVERROR(ENOMEM);
989
990 ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
991 put_ebml_uint (pb, EBML_ID_EBMLVERSION , 1);
992 put_ebml_uint (pb, EBML_ID_EBMLREADVERSION , 1);
993 put_ebml_uint (pb, EBML_ID_EBMLMAXIDLENGTH , 4);
994 put_ebml_uint (pb, EBML_ID_EBMLMAXSIZELENGTH , 8);
995 put_ebml_string (pb, EBML_ID_DOCTYPE , s->oformat->name);
996 put_ebml_uint (pb, EBML_ID_DOCTYPEVERSION , 2);
997 put_ebml_uint (pb, EBML_ID_DOCTYPEREADVERSION , 2);
998 end_ebml_master(pb, ebml_header);
999
1000 mkv->segment = start_ebml_master(pb, MATROSKA_ID_SEGMENT, 0);
1001 mkv->segment_offset = avio_tell(pb);
1002
1003 // we write 2 seek heads - one at the end of the file to point to each
1004 // cluster, and one at the beginning to point to all other level one
1005 // elements (including the seek head at the end of the file), which
1006 // isn't more than 10 elements if we only write one of each other
1007 // currently defined level 1 element
1008 mkv->main_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 10);
1009 if (!mkv->main_seekhead)
1010 return AVERROR(ENOMEM);
1011
1012 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_INFO, avio_tell(pb));
1013 if (ret < 0) return ret;
1014
1015 segment_info = start_ebml_master(pb, MATROSKA_ID_INFO, 0);
1016 put_ebml_uint(pb, MATROSKA_ID_TIMECODESCALE, 1000000);
1017 if ((tag = av_dict_get(s->metadata, "title", NULL, 0)))
1018 put_ebml_string(pb, MATROSKA_ID_TITLE, tag->value);
1019 if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
1020 uint32_t segment_uid[4];
1021 AVLFG lfg;
1022
1023 av_lfg_init(&lfg, av_get_random_seed());
1024
1025 for (i = 0; i < 4; i++)
1026 segment_uid[i] = av_lfg_get(&lfg);
1027
1028 put_ebml_string(pb, MATROSKA_ID_MUXINGAPP , LIBAVFORMAT_IDENT);
1029 if ((tag = av_dict_get(s->metadata, "encoding_tool", NULL, 0)))
1030 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, tag->value);
1031 else
1032 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, LIBAVFORMAT_IDENT);
1033 put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
1034 }
1035
1036 // reserve space for the duration
1037 mkv->duration = 0;
1038 mkv->duration_offset = avio_tell(pb);
1039 put_ebml_void(pb, 11); // assumes double-precision float to be written
1040 end_ebml_master(pb, segment_info);
1041
1042 ret = mkv_write_tracks(s);
1043 if (ret < 0) return ret;
1044
1045 if (mkv->mode != MODE_WEBM) {
1046 ret = mkv_write_chapters(s);
1047 if (ret < 0) return ret;
1048
1049 ret = mkv_write_tags(s);
1050 if (ret < 0) return ret;
1051
1052 ret = mkv_write_attachments(s);
1053 if (ret < 0) return ret;
1054 }
1055
1056 if (!s->pb->seekable)
1057 mkv_write_seekhead(pb, mkv->main_seekhead);
1058
1059 mkv->cues = mkv_start_cues(mkv->segment_offset);
1060 if (mkv->cues == NULL)
1061 return AVERROR(ENOMEM);
1062
1063 if (pb->seekable && mkv->reserve_cues_space) {
1064 mkv->cues_pos = avio_tell(pb);
1065 put_ebml_void(pb, mkv->reserve_cues_space);
1066 }
1067
1068 av_init_packet(&mkv->cur_audio_pkt);
1069 mkv->cur_audio_pkt.size = 0;
1070
1071 avio_flush(pb);
1072
1073 // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1074 // after 4k and on a keyframe
1075 if (pb->seekable) {
1076 if (mkv->cluster_time_limit < 0)
1077 mkv->cluster_time_limit = 5000;
1078 if (mkv->cluster_size_limit < 0)
1079 mkv->cluster_size_limit = 5 * 1024 * 1024;
1080 } else {
1081 if (mkv->cluster_time_limit < 0)
1082 mkv->cluster_time_limit = 1000;
1083 if (mkv->cluster_size_limit < 0)
1084 mkv->cluster_size_limit = 32 * 1024;
1085 }
1086
1087 return 0;
1088 }
1089
1090 static int mkv_blockgroup_size(int pkt_size)
1091 {
1092 int size = pkt_size + 4;
1093 size += ebml_num_size(size);
1094 size += 2; // EBML ID for block and block duration
1095 size += 8; // max size of block duration
1096 size += ebml_num_size(size);
1097 size += 1; // blockgroup EBML ID
1098 return size;
1099 }
1100
1101 static int ass_get_duration(const uint8_t *p)
1102 {
1103 int sh, sm, ss, sc, eh, em, es, ec;
1104 uint64_t start, end;
1105
1106 if (sscanf(p, "%*[^,],%d:%d:%d%*c%d,%d:%d:%d%*c%d",
1107 &sh, &sm, &ss, &sc, &eh, &em, &es, &ec) != 8)
1108 return 0;
1109 start = 3600000*sh + 60000*sm + 1000*ss + 10*sc;
1110 end = 3600000*eh + 60000*em + 1000*es + 10*ec;
1111 return end - start;
1112 }
1113
1114 static int mkv_write_ass_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
1115 {
1116 MatroskaMuxContext *mkv = s->priv_data;
1117 int i, layer = 0, max_duration = 0, size, line_size, data_size = pkt->size;
1118 uint8_t *start, *end, *data = pkt->data;
1119 ebml_master blockgroup;
1120 char buffer[2048];
1121
1122 while (data_size) {
1123 int duration = ass_get_duration(data);
1124 max_duration = FFMAX(duration, max_duration);
1125 end = memchr(data, '\n', data_size);
1126 size = line_size = end ? end-data+1 : data_size;
1127 size -= end ? (end[-1]=='\r')+1 : 0;
1128 start = data;
1129 for (i=0; i<3; i++, start++)
1130 if (!(start = memchr(start, ',', size-(start-data))))
1131 return max_duration;
1132 size -= start - data;
1133 sscanf(data, "Dialogue: %d,", &layer);
1134 i = snprintf(buffer, sizeof(buffer), "%"PRId64",%d,",
1135 s->streams[pkt->stream_index]->nb_frames, layer);
1136 size = FFMIN(i+size, sizeof(buffer));
1137 memcpy(buffer+i, start, size-i);
1138
1139 av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
1140 "pts %" PRId64 ", duration %d\n",
1141 avio_tell(pb), size, pkt->pts, duration);
1142 blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(size));
1143 put_ebml_id(pb, MATROSKA_ID_BLOCK);
1144 put_ebml_num(pb, size+4, 0);
1145 avio_w8(pb, 0x80 | (pkt->stream_index + 1)); // this assumes stream_index is less than 126
1146 avio_wb16(pb, pkt->pts - mkv->cluster_pts);
1147 avio_w8(pb, 0);
1148 avio_write(pb, buffer, size);
1149 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
1150 end_ebml_master(pb, blockgroup);
1151
1152 data += line_size;
1153 data_size -= line_size;
1154 }
1155
1156 return max_duration;
1157 }
1158
1159 static int mkv_strip_wavpack(const uint8_t *src, uint8_t **pdst, int *size)
1160 {
1161 uint8_t *dst;
1162 int srclen = *size;
1163 int offset = 0;
1164 int ret;
1165
1166 dst = av_malloc(srclen);
1167 if (!dst)
1168 return AVERROR(ENOMEM);
1169
1170 while (srclen >= WV_HEADER_SIZE) {
1171 WvHeader header;
1172
1173 ret = ff_wv_parse_header(&header, src);
1174 if (ret < 0)
1175 goto fail;
1176 src += WV_HEADER_SIZE;
1177 srclen -= WV_HEADER_SIZE;
1178
1179 if (srclen < header.blocksize) {
1180 ret = AVERROR_INVALIDDATA;
1181 goto fail;
1182 }
1183
1184 if (header.initial) {
1185 AV_WL32(dst + offset, header.samples);
1186 offset += 4;
1187 }
1188 AV_WL32(dst + offset, header.flags);
1189 AV_WL32(dst + offset + 4, header.crc);
1190 offset += 8;
1191
1192 if (!(header.initial && header.final)) {
1193 AV_WL32(dst + offset, header.blocksize);
1194 offset += 4;
1195 }
1196
1197 memcpy(dst + offset, src, header.blocksize);
1198 src += header.blocksize;
1199 srclen -= header.blocksize;
1200 offset += header.blocksize;
1201 }
1202
1203 *pdst = dst;
1204 *size = offset;
1205
1206 return 0;
1207 fail:
1208 av_freep(&dst);
1209 return ret;
1210 }
1211
1212 static void mkv_write_block(AVFormatContext *s, AVIOContext *pb,
1213 unsigned int blockid, AVPacket *pkt, int flags)
1214 {
1215 MatroskaMuxContext *mkv = s->priv_data;
1216 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1217 uint8_t *data = NULL;
1218 int offset = 0, size = pkt->size;
1219 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1220
1221 av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
1222 "pts %" PRId64 ", dts %" PRId64 ", duration %d, flags %d\n",
1223 avio_tell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration, flags);
1224 if (codec->codec_id == AV_CODEC_ID_H264 && codec->extradata_size > 0 &&
1225 (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
1226 ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
1227 else if (codec->codec_id == AV_CODEC_ID_HEVC && codec->extradata_size > 6 &&
1228 (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
1229 /* extradata is Annex B, assume the bitstream is too and convert it */
1230 ff_hevc_annexb2mp4_buf(pkt->data, &data, &size, 0, NULL);
1231 else if (codec->codec_id == AV_CODEC_ID_WAVPACK) {
1232 int ret = mkv_strip_wavpack(pkt->data, &data, &size);
1233 if (ret < 0) {
1234 av_log(s, AV_LOG_ERROR, "Error stripping a WavPack packet.\n");
1235 return;
1236 }
1237 } else
1238 data = pkt->data;
1239
1240 if (codec->codec_id == AV_CODEC_ID_PRORES) {
1241 /* Matroska specification requires to remove the first QuickTime atom
1242 */
1243 size -= 8;
1244 offset = 8;
1245 }
1246
1247 put_ebml_id(pb, blockid);
1248 put_ebml_num(pb, size+4, 0);
1249 avio_w8(pb, 0x80 | (pkt->stream_index + 1)); // this assumes stream_index is less than 126
1250 avio_wb16(pb, ts - mkv->cluster_pts);
1251 avio_w8(pb, flags);
1252 avio_write(pb, data + offset, size);
1253 if (data != pkt->data)
1254 av_free(data);
1255 }
1256
1257 static int srt_get_duration(uint8_t **buf)
1258 {
1259 int i, duration = 0;
1260
1261 for (i=0; i<2 && !duration; i++) {
1262 int s_hour, s_min, s_sec, s_hsec, e_hour, e_min, e_sec, e_hsec;
1263 if (sscanf(*buf, "%d:%2d:%2d%*1[,.]%3d --> %d:%2d:%2d%*1[,.]%3d",
1264 &s_hour, &s_min, &s_sec, &s_hsec,
1265 &e_hour, &e_min, &e_sec, &e_hsec) == 8) {
1266 s_min += 60*s_hour; e_min += 60*e_hour;
1267 s_sec += 60*s_min; e_sec += 60*e_min;
1268 s_hsec += 1000*s_sec; e_hsec += 1000*e_sec;
1269 duration = e_hsec - s_hsec;
1270 }
1271 *buf += strcspn(*buf, "\n") + 1;
1272 }
1273 return duration;
1274 }
1275
1276 static int mkv_write_srt_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
1277 {
1278 ebml_master blockgroup;
1279 AVPacket pkt2 = *pkt;
1280 int64_t duration = srt_get_duration(&pkt2.data);
1281 pkt2.size -= pkt2.data - pkt->data;
1282
1283 blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
1284 mkv_blockgroup_size(pkt2.size));
1285 mkv_write_block(s, pb, MATROSKA_ID_BLOCK, &pkt2, 0);
1286 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
1287 end_ebml_master(pb, blockgroup);
1288
1289 return duration;
1290 }
1291
1292 static void mkv_flush_dynbuf(AVFormatContext *s)
1293 {
1294 MatroskaMuxContext *mkv = s->priv_data;
1295 int bufsize;
1296 uint8_t *dyn_buf;
1297
1298 if (!mkv->dyn_bc)
1299 return;
1300
1301 bufsize = avio_close_dyn_buf(mkv->dyn_bc, &dyn_buf);
1302 avio_write(s->pb, dyn_buf, bufsize);
1303 av_free(dyn_buf);
1304 mkv->dyn_bc = NULL;
1305 }
1306
1307 static int mkv_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
1308 {
1309 MatroskaMuxContext *mkv = s->priv_data;
1310 AVIOContext *pb = s->pb;
1311 AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1312 int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1313 int duration = pkt->duration;
1314 int ret;
1315 int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1316
1317 if (ts == AV_NOPTS_VALUE) {
1318 av_log(s, AV_LOG_ERROR, "Can't write packet with unknown timestamp\n");
1319 return AVERROR(EINVAL);
1320 }
1321 ts += mkv->tracks[pkt->stream_index].ts_offset;
1322
1323 if (!s->pb->seekable) {
1324 if (!mkv->dyn_bc)
1325 avio_open_dyn_buf(&mkv->dyn_bc);
1326 pb = mkv->dyn_bc;
1327 }
1328
1329 if (!mkv->cluster_pos) {
1330 mkv->cluster_pos = avio_tell(s->pb);
1331 mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER, 0);
1332 put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, FFMAX(0, ts));
1333 mkv->cluster_pts = FFMAX(0, ts);
1334 }
1335
1336 if (codec->codec_type != AVMEDIA_TYPE_SUBTITLE) {
1337 mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
1338 } else if (codec->codec_id == AV_CODEC_ID_SSA) {
1339 duration = mkv_write_ass_blocks(s, pb, pkt);
1340 } else if (codec->codec_id == AV_CODEC_ID_SRT) {
1341 duration = mkv_write_srt_blocks(s, pb, pkt);
1342 } else {
1343 ebml_master blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(pkt->size));
1344 duration = pkt->convergence_duration;
1345 mkv_write_block(s, pb, MATROSKA_ID_BLOCK, pkt, 0);
1346 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
1347 end_ebml_master(pb, blockgroup);
1348 }
1349
1350 if (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe) {
1351 ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, ts, mkv->cluster_pos);
1352 if (ret < 0) return ret;
1353 }
1354
1355 mkv->duration = FFMAX(mkv->duration, ts + duration);
1356 return 0;
1357 }
1358
1359 static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
1360 {
1361 MatroskaMuxContext *mkv = s->priv_data;
1362 int codec_type = s->streams[pkt->stream_index]->codec->codec_type;
1363 int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1364 int cluster_size;
1365 int64_t cluster_time;
1366 AVIOContext *pb;
1367 int ret;
1368
1369 if (mkv->tracks[pkt->stream_index].write_dts)
1370 cluster_time = pkt->dts - mkv->cluster_pts;
1371 else
1372 cluster_time = pkt->pts - mkv->cluster_pts;
1373 cluster_time += mkv->tracks[pkt->stream_index].ts_offset;
1374
1375 // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1376 // after 4k and on a keyframe
1377 if (s->pb->seekable) {
1378 pb = s->pb;
1379 cluster_size = avio_tell(pb) - mkv->cluster_pos;
1380 } else {
1381 pb = mkv->dyn_bc;
1382 cluster_size = avio_tell(pb);
1383 }
1384
1385 if (mkv->cluster_pos &&
1386 (cluster_size > mkv->cluster_size_limit ||
1387 cluster_time > mkv->cluster_time_limit ||
1388 (codec_type == AVMEDIA_TYPE_VIDEO && keyframe &&
1389 cluster_size > 4 * 1024))) {
1390 av_log(s, AV_LOG_DEBUG, "Starting new cluster at offset %" PRIu64
1391 " bytes, pts %" PRIu64 "dts %" PRIu64 "\n",
1392 avio_tell(pb), pkt->pts, pkt->dts);
1393 end_ebml_master(pb, mkv->cluster);
1394 mkv->cluster_pos = 0;
1395 if (mkv->dyn_bc)
1396 mkv_flush_dynbuf(s);
1397 avio_flush(s->pb);
1398 }
1399
1400 // check if we have an audio packet cached
1401 if (mkv->cur_audio_pkt.size > 0) {
1402 ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
1403 av_free_packet(&mkv->cur_audio_pkt);
1404 if (ret < 0) {
1405 av_log(s, AV_LOG_ERROR, "Could not write cached audio packet ret:%d\n", ret);
1406 return ret;
1407 }
1408 }
1409
1410 // buffer an audio packet to ensure the packet containing the video
1411 // keyframe's timecode is contained in the same cluster for WebM
1412 if (codec_type == AVMEDIA_TYPE_AUDIO) {
1413 mkv->cur_audio_pkt = *pkt;
1414 if (pkt->buf) {
1415 mkv->cur_audio_pkt.buf = av_buffer_ref(pkt->buf);
1416 ret = mkv->cur_audio_pkt.buf ? 0 : AVERROR(ENOMEM);
1417 } else
1418 ret = av_dup_packet(&mkv->cur_audio_pkt);
1419 } else
1420 ret = mkv_write_packet_internal(s, pkt);
1421 return ret;
1422 }
1423
1424 static int mkv_write_flush_packet(AVFormatContext *s, AVPacket *pkt)
1425 {
1426 MatroskaMuxContext *mkv = s->priv_data;
1427 AVIOContext *pb;
1428 if (s->pb->seekable)
1429 pb = s->pb;
1430 else
1431 pb = mkv->dyn_bc;
1432 if (!pkt) {
1433 if (mkv->cluster_pos) {
1434 av_log(s, AV_LOG_DEBUG, "Flushing cluster at offset %" PRIu64
1435 " bytes\n", avio_tell(pb));
1436 end_ebml_master(pb, mkv->cluster);
1437 mkv->cluster_pos = 0;
1438 if (mkv->dyn_bc)
1439 mkv_flush_dynbuf(s);
1440 avio_flush(s->pb);
1441 }
1442 return 0;
1443 }
1444 return mkv_write_packet(s, pkt);
1445 }
1446
1447 static int mkv_write_trailer(AVFormatContext *s)
1448 {
1449 MatroskaMuxContext *mkv = s->priv_data;
1450 AVIOContext *pb = s->pb;
1451 int64_t currentpos, cuespos;
1452 int ret;
1453
1454 // check if we have an audio packet cached
1455 if (mkv->cur_audio_pkt.size > 0) {
1456 ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
1457 av_free_packet(&mkv->cur_audio_pkt);
1458 if (ret < 0) {
1459 av_log(s, AV_LOG_ERROR, "Could not write cached audio packet ret:%d\n", ret);
1460 return ret;
1461 }
1462 }
1463
1464 if (mkv->dyn_bc) {
1465 end_ebml_master(mkv->dyn_bc, mkv->cluster);
1466 mkv_flush_dynbuf(s);
1467 } else if (mkv->cluster_pos) {
1468 end_ebml_master(pb, mkv->cluster);
1469 }
1470
1471 if (mkv->mode != MODE_WEBM) {
1472 ret = mkv_write_chapters(s);
1473 if (ret < 0) return ret;
1474 }
1475
1476 if (pb->seekable) {
1477 if (mkv->cues->num_entries) {
1478 if (mkv->reserve_cues_space) {
1479 int64_t cues_end;
1480
1481 currentpos = avio_tell(pb);
1482 avio_seek(pb, mkv->cues_pos, SEEK_SET);
1483
1484 cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
1485 cues_end = avio_tell(pb);
1486 if (cues_end > cuespos + mkv->reserve_cues_space) {
1487 av_log(s, AV_LOG_ERROR, "Insufficient space reserved for cues: %d "
1488 "(needed: %"PRId64").\n", mkv->reserve_cues_space,
1489 cues_end - cuespos);
1490 return AVERROR(EINVAL);
1491 }
1492
1493 if (cues_end < cuespos + mkv->reserve_cues_space)
1494 put_ebml_void(pb, mkv->reserve_cues_space - (cues_end - cuespos));
1495
1496 avio_seek(pb, currentpos, SEEK_SET);
1497 } else {
1498 cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
1499 }
1500
1501 ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CUES, cuespos);
1502 if (ret < 0) return ret;
1503 }
1504
1505 mkv_write_seekhead(pb, mkv->main_seekhead);
1506
1507 // update the duration
1508 av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
1509 currentpos = avio_tell(pb);
1510 avio_seek(pb, mkv->duration_offset, SEEK_SET);
1511 put_ebml_float(pb, MATROSKA_ID_DURATION, mkv->duration);
1512
1513 avio_seek(pb, currentpos, SEEK_SET);
1514 }
1515
1516 end_ebml_master(pb, mkv->segment);
1517 av_free(mkv->tracks);
1518 av_freep(&mkv->cues->entries);
1519 av_freep(&mkv->cues);
1520
1521 return 0;
1522 }
1523
1524 static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
1525 {
1526 int i;
1527 for (i = 0; ff_mkv_codec_tags[i].id != AV_CODEC_ID_NONE; i++)
1528 if (ff_mkv_codec_tags[i].id == codec_id)
1529 return 1;
1530
1531 if (std_compliance < FF_COMPLIANCE_NORMAL) { // mkv theoretically supports any
1532 enum AVMediaType type = avcodec_get_type(codec_id); // video/audio through VFW/ACM
1533 if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)
1534 return 1;
1535 }
1536
1537 return 0;
1538 }
1539
1540 #define OFFSET(x) offsetof(MatroskaMuxContext, x)
1541 #define FLAGS AV_OPT_FLAG_ENCODING_PARAM
1542 static const AVOption options[] = {
1543 { "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 },
1544 { "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 },
1545 { "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 },
1546 { NULL },
1547 };
1548
1549 #if CONFIG_MATROSKA_MUXER
1550 static const AVClass matroska_class = {
1551 .class_name = "matroska muxer",
1552 .item_name = av_default_item_name,
1553 .option = options,
1554 .version = LIBAVUTIL_VERSION_INT,
1555 };
1556
1557 AVOutputFormat ff_matroska_muxer = {
1558 .name = "matroska",
1559 .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
1560 .mime_type = "video/x-matroska",
1561 .extensions = "mkv",
1562 .priv_data_size = sizeof(MatroskaMuxContext),
1563 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
1564 AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
1565 .video_codec = CONFIG_LIBX264_ENCODER ?
1566 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
1567 .write_header = mkv_write_header,
1568 .write_packet = mkv_write_flush_packet,
1569 .write_trailer = mkv_write_trailer,
1570 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
1571 AVFMT_TS_NONSTRICT | AVFMT_ALLOW_FLUSH,
1572 .codec_tag = (const AVCodecTag* const []){
1573 ff_codec_bmp_tags, ff_codec_wav_tags, 0
1574 },
1575 .subtitle_codec = AV_CODEC_ID_SSA,
1576 .query_codec = mkv_query_codec,
1577 .priv_class = &matroska_class,
1578 };
1579 #endif
1580
1581 #if CONFIG_WEBM_MUXER
1582 static const AVClass webm_class = {
1583 .class_name = "webm muxer",
1584 .item_name = av_default_item_name,
1585 .option = options,
1586 .version = LIBAVUTIL_VERSION_INT,
1587 };
1588
1589 AVOutputFormat ff_webm_muxer = {
1590 .name = "webm",
1591 .long_name = NULL_IF_CONFIG_SMALL("WebM"),
1592 .mime_type = "video/webm",
1593 .extensions = "webm",
1594 .priv_data_size = sizeof(MatroskaMuxContext),
1595 .audio_codec = AV_CODEC_ID_VORBIS,
1596 .video_codec = AV_CODEC_ID_VP8,
1597 .write_header = mkv_write_header,
1598 .write_packet = mkv_write_flush_packet,
1599 .write_trailer = mkv_write_trailer,
1600 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
1601 AVFMT_TS_NONSTRICT | AVFMT_ALLOW_FLUSH,
1602 .priv_class = &webm_class,
1603 };
1604 #endif
1605
1606 #if CONFIG_MATROSKA_AUDIO_MUXER
1607 static const AVClass mka_class = {
1608 .class_name = "matroska audio muxer",
1609 .item_name = av_default_item_name,
1610 .option = options,
1611 .version = LIBAVUTIL_VERSION_INT,
1612 };
1613 AVOutputFormat ff_matroska_audio_muxer = {
1614 .name = "matroska",
1615 .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
1616 .mime_type = "audio/x-matroska",
1617 .extensions = "mka",
1618 .priv_data_size = sizeof(MatroskaMuxContext),
1619 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
1620 AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
1621 .video_codec = AV_CODEC_ID_NONE,
1622 .write_header = mkv_write_header,
1623 .write_packet = mkv_write_flush_packet,
1624 .write_trailer = mkv_write_trailer,
1625 .flags = AVFMT_GLOBALHEADER | AVFMT_TS_NONSTRICT |
1626 AVFMT_ALLOW_FLUSH,
1627 .codec_tag = (const AVCodecTag* const []){ ff_codec_wav_tags, 0 },
1628 .priv_class = &mka_class,
1629 };
1630 #endif