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