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