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