1 /*
2 * Matroska muxer
3 * Copyright (c) 2007 David Conrad
4 *
5 * This file is part of FFmpeg.
6 *
7 * FFmpeg 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 * FFmpeg 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 FFmpeg; 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 "av1.h"
25 #include "avc.h"
26 #include "hevc.h"
27 #include "avformat.h"
28 #include "avio_internal.h"
29 #include "avlanguage.h"
30 #include "flacenc.h"
31 #include "internal.h"
32 #include "isom.h"
33 #include "matroska.h"
34 #include "riff.h"
35 #include "vorbiscomment.h"
36 #include "wv.h"
37
38 #include "libavutil/avstring.h"
39 #include "libavutil/channel_layout.h"
40 #include "libavutil/crc.h"
41 #include "libavutil/dict.h"
42 #include "libavutil/intfloat.h"
43 #include "libavutil/intreadwrite.h"
44 #include "libavutil/lfg.h"
45 #include "libavutil/mastering_display_metadata.h"
46 #include "libavutil/mathematics.h"
47 #include "libavutil/opt.h"
48 #include "libavutil/parseutils.h"
49 #include "libavutil/random_seed.h"
50 #include "libavutil/rational.h"
51 #include "libavutil/samplefmt.h"
52 #include "libavutil/stereo3d.h"
53
54 #include "libavcodec/xiph.h"
55 #include "libavcodec/mpeg4audio.h"
56
57 /* Level 1 elements we create a SeekHead entry for:
58 * Info, Tracks, Chapters, Attachments, Tags (potentially twice) and Cues */
59 #define MAX_SEEKHEAD_ENTRIES 7
60
61 #define IS_SEEKABLE(pb, mkv) (((pb)->seekable & AVIO_SEEKABLE_NORMAL) && \
62 !(mkv)->is_live)
63
64 enum {
65 DEFAULT_MODE_INFER,
66 DEFAULT_MODE_INFER_NO_SUBS,
67 DEFAULT_MODE_PASSTHROUGH,
68 };
69
70 typedef struct ebml_master {
71 int64_t pos; ///< absolute offset in the containing AVIOContext where the master's elements start
72 int sizebytes; ///< how many bytes were reserved for the size
73 } ebml_master;
74
75 typedef struct ebml_stored_master {
76 AVIOContext *bc;
77 int64_t pos;
78 } ebml_stored_master;
79
80 typedef struct mkv_seekhead_entry {
81 uint32_t elementid;
82 uint64_t segmentpos;
83 } mkv_seekhead_entry;
84
85 typedef struct mkv_seekhead {
86 int64_t filepos;
87 mkv_seekhead_entry entries[MAX_SEEKHEAD_ENTRIES];
88 int num_entries;
89 int reserved_size;
90 } mkv_seekhead;
91
92 typedef struct mkv_cuepoint {
93 uint64_t pts;
94 int stream_idx;
95 int64_t cluster_pos; ///< offset of the cluster containing the block relative to the segment
96 int64_t relative_pos; ///< relative offset from the position of the cluster containing the block
97 int64_t duration; ///< duration of the block according to time base
98 } mkv_cuepoint;
99
100 typedef struct mkv_cues {
101 mkv_cuepoint *entries;
102 int num_entries;
103 } mkv_cues;
104
105 typedef struct mkv_track {
106 int write_dts;
107 int has_cue;
108 uint64_t uid;
109 unsigned track_num;
110 int track_num_size;
111 int sample_rate;
112 int64_t sample_rate_offset;
113 int64_t last_timestamp;
114 int64_t duration;
115 int64_t duration_offset;
116 int64_t codecpriv_offset;
117 int64_t ts_offset;
118 } mkv_track;
119
120 #define MODE_MATROSKAv2 0x01
121 #define MODE_WEBM 0x02
122
123 typedef struct MatroskaMuxContext {
124 const AVClass *class;
125 int mode;
126 ebml_stored_master info;
127 ebml_stored_master track;
128 ebml_stored_master tags;
129 int64_t segment_offset;
130 AVIOContext *cluster_bc;
131 int64_t cluster_pos; ///< file offset of the current Cluster
132 int64_t cluster_pts;
133 int64_t duration_offset;
134 int64_t duration;
135 mkv_track *tracks;
136 mkv_seekhead seekhead;
137 mkv_cues cues;
138 int64_t cues_pos;
139
140 AVPacket *cur_audio_pkt;
141
142 unsigned nb_attachments;
143 int have_video;
144
145 int wrote_chapters;
146 int wrote_tags;
147
148 int reserve_cues_space;
149 int cluster_size_limit;
150 int64_t cluster_time_limit;
151 int write_crc;
152 int is_live;
153
154 int is_dash;
155 int dash_track_number;
156 int allow_raw_vfw;
157 int flipped_raw_rgb;
158 int default_mode;
159
160 uint32_t segment_uid[4];
161 } MatroskaMuxContext;
162
163 /** 2 bytes * 7 for EBML IDs, 7 1-byte EBML lengths, 6 1-byte uint,
164 * 8 byte for "matroska" doctype string */
165 #define MAX_EBML_HEADER_SIZE 35
166
167 /** 2 bytes * 3 for EBML IDs, 3 1-byte EBML lengths, 8 bytes for 64 bit
168 * offset, 4 bytes for target EBML ID */
169 #define MAX_SEEKENTRY_SIZE 21
170
171 /** 4 * (1-byte EBML ID, 1-byte EBML size, 8-byte uint max) */
172 #define MAX_CUETRACKPOS_SIZE 40
173
174 /** Seek preroll value for opus */
175 #define OPUS_SEEK_PREROLL 80000000
176
ebml_id_size(uint32_t id)177 static int ebml_id_size(uint32_t id)
178 {
179 return (av_log2(id) + 7U) / 8;
180 }
181
put_ebml_id(AVIOContext * pb,uint32_t id)182 static void put_ebml_id(AVIOContext *pb, uint32_t id)
183 {
184 int i = ebml_id_size(id);
185 while (i--)
186 avio_w8(pb, (uint8_t)(id >> (i * 8)));
187 }
188
189 /**
190 * Write an EBML size meaning "unknown size".
191 *
192 * @param bytes The number of bytes the size should occupy (maximum: 8).
193 */
put_ebml_size_unknown(AVIOContext * pb,int bytes)194 static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
195 {
196 av_assert0(bytes <= 8);
197 avio_w8(pb, 0x1ff >> bytes);
198 ffio_fill(pb, 0xff, bytes - 1);
199 }
200
201 /**
202 * Returns how many bytes are needed to represent a number
203 * as EBML variable length integer.
204 */
ebml_num_size(uint64_t num)205 static int ebml_num_size(uint64_t num)
206 {
207 int bytes = 0;
208 do {
209 bytes++;
210 } while (num >>= 7);
211 return bytes;
212 }
213
214 /**
215 * Calculate how many bytes are needed to represent the length field
216 * of an EBML element whose payload has a given length.
217 */
ebml_length_size(uint64_t length)218 static int ebml_length_size(uint64_t length)
219 {
220 return ebml_num_size(length + 1);
221 }
222
223 /**
224 * Write a number as EBML variable length integer on `bytes` bytes.
225 * `bytes` is taken literally without checking.
226 */
put_ebml_num(AVIOContext * pb,uint64_t num,int bytes)227 static void put_ebml_num(AVIOContext *pb, uint64_t num, int bytes)
228 {
229 num |= 1ULL << bytes * 7;
230 for (int i = bytes - 1; i >= 0; i--)
231 avio_w8(pb, (uint8_t)(num >> i * 8));
232 }
233
234 /**
235 * Write a length as EBML variable length integer.
236 *
237 * @param bytes The number of bytes that need to be used to write the number.
238 * If zero, the minimal number of bytes will be used.
239 */
put_ebml_length(AVIOContext * pb,uint64_t length,int bytes)240 static void put_ebml_length(AVIOContext *pb, uint64_t length, int bytes)
241 {
242 int needed_bytes = ebml_length_size(length);
243
244 // sizes larger than this are currently undefined in EBML
245 av_assert0(length < (1ULL << 56) - 1);
246
247 if (bytes == 0)
248 bytes = needed_bytes;
249 // The bytes needed to write the given size must not exceed
250 // the bytes that we ought to use.
251 av_assert0(bytes >= needed_bytes);
252 put_ebml_num(pb, length, bytes);
253 }
254
255 /**
256 * Write a (random) UID with fixed size to make the output more deterministic
257 */
put_ebml_uid(AVIOContext * pb,uint32_t elementid,uint64_t uid)258 static void put_ebml_uid(AVIOContext *pb, uint32_t elementid, uint64_t uid)
259 {
260 put_ebml_id(pb, elementid);
261 put_ebml_length(pb, 8, 0);
262 avio_wb64(pb, uid);
263 }
264
put_ebml_uint(AVIOContext * pb,uint32_t elementid,uint64_t val)265 static void put_ebml_uint(AVIOContext *pb, uint32_t elementid, uint64_t val)
266 {
267 int i, bytes = 1;
268 uint64_t tmp = val;
269 while (tmp >>= 8)
270 bytes++;
271
272 put_ebml_id(pb, elementid);
273 put_ebml_length(pb, bytes, 0);
274 for (i = bytes - 1; i >= 0; i--)
275 avio_w8(pb, (uint8_t)(val >> i * 8));
276 }
277
put_ebml_sint(AVIOContext * pb,uint32_t elementid,int64_t val)278 static void put_ebml_sint(AVIOContext *pb, uint32_t elementid, int64_t val)
279 {
280 int i, bytes = 1;
281 uint64_t tmp = 2*(val < 0 ? val^-1 : val);
282
283 while (tmp >>= 8)
284 bytes++;
285
286 put_ebml_id(pb, elementid);
287 put_ebml_length(pb, bytes, 0);
288 for (i = bytes - 1; i >= 0; i--)
289 avio_w8(pb, (uint8_t)(val >> i * 8));
290 }
291
put_ebml_float(AVIOContext * pb,uint32_t elementid,double val)292 static void put_ebml_float(AVIOContext *pb, uint32_t elementid, double val)
293 {
294 put_ebml_id(pb, elementid);
295 put_ebml_length(pb, 8, 0);
296 avio_wb64(pb, av_double2int(val));
297 }
298
put_ebml_binary(AVIOContext * pb,uint32_t elementid,const void * buf,int size)299 static void put_ebml_binary(AVIOContext *pb, uint32_t elementid,
300 const void *buf, int size)
301 {
302 put_ebml_id(pb, elementid);
303 put_ebml_length(pb, size, 0);
304 avio_write(pb, buf, size);
305 }
306
put_ebml_string(AVIOContext * pb,uint32_t elementid,const char * str)307 static void put_ebml_string(AVIOContext *pb, uint32_t elementid,
308 const char *str)
309 {
310 put_ebml_binary(pb, elementid, str, strlen(str));
311 }
312
313 /**
314 * Write a void element of a given size. Useful for reserving space in
315 * the file to be written to later.
316 *
317 * @param size The number of bytes to reserve, which must be at least 2.
318 */
put_ebml_void(AVIOContext * pb,int size)319 static void put_ebml_void(AVIOContext *pb, int size)
320 {
321 av_assert0(size >= 2);
322
323 put_ebml_id(pb, EBML_ID_VOID);
324 // we need to subtract the length needed to store the size from the
325 // size we need to reserve so 2 cases, we use 8 bytes to store the
326 // size if possible, 1 byte otherwise
327 if (size < 10) {
328 size -= 2;
329 put_ebml_length(pb, size, 0);
330 } else {
331 size -= 9;
332 put_ebml_length(pb, size, 8);
333 }
334 ffio_fill(pb, 0, size);
335 }
336
start_ebml_master(AVIOContext * pb,uint32_t elementid,uint64_t expectedsize)337 static ebml_master start_ebml_master(AVIOContext *pb, uint32_t elementid,
338 uint64_t expectedsize)
339 {
340 int bytes = expectedsize ? ebml_length_size(expectedsize) : 8;
341
342 put_ebml_id(pb, elementid);
343 put_ebml_size_unknown(pb, bytes);
344 return (ebml_master) { avio_tell(pb), bytes };
345 }
346
end_ebml_master(AVIOContext * pb,ebml_master master)347 static void end_ebml_master(AVIOContext *pb, ebml_master master)
348 {
349 int64_t pos = avio_tell(pb);
350
351 if (avio_seek(pb, master.pos - master.sizebytes, SEEK_SET) < 0)
352 return;
353 put_ebml_length(pb, pos - master.pos, master.sizebytes);
354 avio_seek(pb, pos, SEEK_SET);
355 }
356
mkv_add_seekhead_entry(MatroskaMuxContext * mkv,uint32_t elementid,uint64_t filepos)357 static void mkv_add_seekhead_entry(MatroskaMuxContext *mkv, uint32_t elementid,
358 uint64_t filepos)
359 {
360 mkv_seekhead *seekhead = &mkv->seekhead;
361
362 av_assert1(seekhead->num_entries < MAX_SEEKHEAD_ENTRIES);
363
364 seekhead->entries[seekhead->num_entries].elementid = elementid;
365 seekhead->entries[seekhead->num_entries++].segmentpos = filepos - mkv->segment_offset;
366 }
367
start_ebml_master_crc32(AVIOContext ** dyn_cp,MatroskaMuxContext * mkv)368 static int start_ebml_master_crc32(AVIOContext **dyn_cp, MatroskaMuxContext *mkv)
369 {
370 int ret;
371
372 if (!*dyn_cp && (ret = avio_open_dyn_buf(dyn_cp)) < 0)
373 return ret;
374
375 if (mkv->write_crc)
376 put_ebml_void(*dyn_cp, 6); /* Reserve space for CRC32 so position/size calculations using avio_tell() take it into account */
377
378 return 0;
379 }
380
end_ebml_master_crc32(AVIOContext * pb,AVIOContext ** dyn_cp,MatroskaMuxContext * mkv,uint32_t id,int length_size,int keep_buffer,int add_seekentry)381 static int end_ebml_master_crc32(AVIOContext *pb, AVIOContext **dyn_cp,
382 MatroskaMuxContext *mkv, uint32_t id,
383 int length_size, int keep_buffer,
384 int add_seekentry)
385 {
386 uint8_t *buf, crc[4];
387 int ret, size, skip = 0;
388
389 size = avio_get_dyn_buf(*dyn_cp, &buf);
390 if ((ret = (*dyn_cp)->error) < 0)
391 goto fail;
392
393 if (add_seekentry)
394 mkv_add_seekhead_entry(mkv, id, avio_tell(pb));
395
396 put_ebml_id(pb, id);
397 put_ebml_length(pb, size, length_size);
398 if (mkv->write_crc) {
399 skip = 6; /* Skip reserved 6-byte long void element from the dynamic buffer. */
400 AV_WL32(crc, av_crc(av_crc_get_table(AV_CRC_32_IEEE_LE), UINT32_MAX, buf + skip, size - skip) ^ UINT32_MAX);
401 put_ebml_binary(pb, EBML_ID_CRC32, crc, sizeof(crc));
402 }
403 avio_write(pb, buf + skip, size - skip);
404
405 fail:
406 if (keep_buffer) {
407 ffio_reset_dyn_buf(*dyn_cp);
408 } else {
409 ffio_free_dyn_buf(dyn_cp);
410 }
411 return ret;
412 }
413
414 /**
415 * Output EBML master. Keep the buffer if seekable, allowing for later updates.
416 * Furthermore always add a SeekHead Entry for this element.
417 */
end_ebml_master_crc32_tentatively(AVIOContext * pb,ebml_stored_master * elem,MatroskaMuxContext * mkv,uint32_t id)418 static int end_ebml_master_crc32_tentatively(AVIOContext *pb,
419 ebml_stored_master *elem,
420 MatroskaMuxContext *mkv, uint32_t id)
421 {
422 if (IS_SEEKABLE(pb, mkv)) {
423 uint8_t *buf;
424 int size = avio_get_dyn_buf(elem->bc, &buf);
425
426 if (elem->bc->error < 0)
427 return elem->bc->error;
428
429 elem->pos = avio_tell(pb);
430 mkv_add_seekhead_entry(mkv, id, elem->pos);
431
432 put_ebml_id(pb, id);
433 put_ebml_length(pb, size, 0);
434 avio_write(pb, buf, size);
435
436 return 0;
437 } else
438 return end_ebml_master_crc32(pb, &elem->bc, mkv, id, 0, 0, 1);
439 }
440
put_xiph_size(AVIOContext * pb,int size)441 static void put_xiph_size(AVIOContext *pb, int size)
442 {
443 ffio_fill(pb, 255, size / 255);
444 avio_w8(pb, size % 255);
445 }
446
447 /**
448 * Free the members allocated in the mux context.
449 */
mkv_deinit(AVFormatContext * s)450 static void mkv_deinit(AVFormatContext *s)
451 {
452 MatroskaMuxContext *mkv = s->priv_data;
453
454 av_packet_free(&mkv->cur_audio_pkt);
455
456 ffio_free_dyn_buf(&mkv->cluster_bc);
457 ffio_free_dyn_buf(&mkv->info.bc);
458 ffio_free_dyn_buf(&mkv->track.bc);
459 ffio_free_dyn_buf(&mkv->tags.bc);
460
461 av_freep(&mkv->cues.entries);
462 av_freep(&mkv->tracks);
463 }
464
465 /**
466 * Initialize the SeekHead element to be ready to index level 1 Matroska
467 * elements. Enough space to write MAX_SEEKHEAD_ENTRIES SeekHead entries
468 * will be reserved at the current file location.
469 */
mkv_start_seekhead(MatroskaMuxContext * mkv,AVIOContext * pb)470 static void mkv_start_seekhead(MatroskaMuxContext *mkv, AVIOContext *pb)
471 {
472 mkv->seekhead.filepos = avio_tell(pb);
473 // 21 bytes max for a Seek entry, 6 bytes max for the SeekHead ID
474 // and size, 6 bytes for a CRC32 element, and 2 bytes to guarantee
475 // that an EBML void element will fit afterwards
476 mkv->seekhead.reserved_size = MAX_SEEKHEAD_ENTRIES * MAX_SEEKENTRY_SIZE + 14;
477 put_ebml_void(pb, mkv->seekhead.reserved_size);
478 }
479
480 /**
481 * Write the SeekHead to the file at the location reserved for it
482 * and seek to destpos afterwards. When error_on_seek_failure
483 * is not set, failure to seek to the position designated for the
484 * SeekHead is not considered an error and it is presumed that
485 * destpos is the current position; failure to seek to destpos
486 * afterwards is always an error.
487 *
488 * @return 0 on success, < 0 on error.
489 */
mkv_write_seekhead(AVIOContext * pb,MatroskaMuxContext * mkv,int error_on_seek_failure,int64_t destpos)490 static int mkv_write_seekhead(AVIOContext *pb, MatroskaMuxContext *mkv,
491 int error_on_seek_failure, int64_t destpos)
492 {
493 AVIOContext *dyn_cp = NULL;
494 mkv_seekhead *seekhead = &mkv->seekhead;
495 int64_t remaining, ret64;
496 int i, ret;
497
498 if ((ret64 = avio_seek(pb, seekhead->filepos, SEEK_SET)) < 0)
499 return error_on_seek_failure ? ret64 : 0;
500
501 ret = start_ebml_master_crc32(&dyn_cp, mkv);
502 if (ret < 0)
503 return ret;
504
505 for (i = 0; i < seekhead->num_entries; i++) {
506 mkv_seekhead_entry *entry = &seekhead->entries[i];
507 ebml_master seekentry = start_ebml_master(dyn_cp, MATROSKA_ID_SEEKENTRY,
508 MAX_SEEKENTRY_SIZE);
509
510 put_ebml_id(dyn_cp, MATROSKA_ID_SEEKID);
511 put_ebml_length(dyn_cp, ebml_id_size(entry->elementid), 0);
512 put_ebml_id(dyn_cp, entry->elementid);
513
514 put_ebml_uint(dyn_cp, MATROSKA_ID_SEEKPOSITION, entry->segmentpos);
515 end_ebml_master(dyn_cp, seekentry);
516 }
517 ret = end_ebml_master_crc32(pb, &dyn_cp, mkv,
518 MATROSKA_ID_SEEKHEAD, 0, 0, 0);
519 if (ret < 0)
520 return ret;
521
522 remaining = seekhead->filepos + seekhead->reserved_size - avio_tell(pb);
523 put_ebml_void(pb, remaining);
524
525 if ((ret64 = avio_seek(pb, destpos, SEEK_SET)) < 0)
526 return ret64;
527
528 return 0;
529 }
530
mkv_add_cuepoint(MatroskaMuxContext * mkv,int stream,int64_t ts,int64_t cluster_pos,int64_t relative_pos,int64_t duration)531 static int mkv_add_cuepoint(MatroskaMuxContext *mkv, int stream, int64_t ts,
532 int64_t cluster_pos, int64_t relative_pos, int64_t duration)
533 {
534 mkv_cues *cues = &mkv->cues;
535 mkv_cuepoint *entries = cues->entries;
536
537 if (ts < 0)
538 return 0;
539
540 entries = av_realloc_array(entries, cues->num_entries + 1, sizeof(mkv_cuepoint));
541 if (!entries)
542 return AVERROR(ENOMEM);
543 cues->entries = entries;
544
545 cues->entries[cues->num_entries].pts = ts;
546 cues->entries[cues->num_entries].stream_idx = stream;
547 cues->entries[cues->num_entries].cluster_pos = cluster_pos - mkv->segment_offset;
548 cues->entries[cues->num_entries].relative_pos = relative_pos;
549 cues->entries[cues->num_entries++].duration = duration;
550
551 return 0;
552 }
553
mkv_assemble_cues(AVStream ** streams,AVIOContext * dyn_cp,mkv_cues * cues,mkv_track * tracks,int num_tracks)554 static int mkv_assemble_cues(AVStream **streams, AVIOContext *dyn_cp,
555 mkv_cues *cues, mkv_track *tracks, int num_tracks)
556 {
557 AVIOContext *cuepoint;
558 int ret;
559
560 ret = avio_open_dyn_buf(&cuepoint);
561 if (ret < 0)
562 return ret;
563
564 for (mkv_cuepoint *entry = cues->entries, *end = entry + cues->num_entries;
565 entry < end;) {
566 uint64_t pts = entry->pts;
567 uint8_t *buf;
568 int size;
569
570 put_ebml_uint(cuepoint, MATROSKA_ID_CUETIME, pts);
571
572 // put all the entries from different tracks that have the exact same
573 // timestamp into the same CuePoint
574 for (int j = 0; j < num_tracks; j++)
575 tracks[j].has_cue = 0;
576 do {
577 ebml_master track_positions;
578 int idx = entry->stream_idx;
579
580 av_assert0(idx >= 0 && idx < num_tracks);
581 if (tracks[idx].has_cue && streams[idx]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE)
582 continue;
583 tracks[idx].has_cue = 1;
584 track_positions = start_ebml_master(cuepoint, MATROSKA_ID_CUETRACKPOSITION, MAX_CUETRACKPOS_SIZE);
585 put_ebml_uint(cuepoint, MATROSKA_ID_CUETRACK , tracks[idx].track_num);
586 put_ebml_uint(cuepoint, MATROSKA_ID_CUECLUSTERPOSITION , entry->cluster_pos);
587 put_ebml_uint(cuepoint, MATROSKA_ID_CUERELATIVEPOSITION, entry->relative_pos);
588 if (entry->duration != -1)
589 put_ebml_uint(cuepoint, MATROSKA_ID_CUEDURATION , entry->duration);
590 end_ebml_master(cuepoint, track_positions);
591 } while (++entry < end && entry->pts == pts);
592 size = avio_get_dyn_buf(cuepoint, &buf);
593 if ((ret = cuepoint->error) < 0)
594 break;
595 put_ebml_binary(dyn_cp, MATROSKA_ID_POINTENTRY, buf, size);
596 ffio_reset_dyn_buf(cuepoint);
597 }
598 ffio_free_dyn_buf(&cuepoint);
599
600 return ret;
601 }
602
put_xiph_codecpriv(AVFormatContext * s,AVIOContext * pb,const AVCodecParameters * par)603 static int put_xiph_codecpriv(AVFormatContext *s, AVIOContext *pb,
604 const AVCodecParameters *par)
605 {
606 const uint8_t *header_start[3];
607 int header_len[3];
608 int first_header_size;
609 int err, j;
610
611 if (par->codec_id == AV_CODEC_ID_VORBIS)
612 first_header_size = 30;
613 else
614 first_header_size = 42;
615
616 err = avpriv_split_xiph_headers(par->extradata, par->extradata_size,
617 first_header_size, header_start, header_len);
618 if (err < 0) {
619 av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
620 return err;
621 }
622
623 avio_w8(pb, 2); // number packets - 1
624 for (j = 0; j < 2; j++) {
625 put_xiph_size(pb, header_len[j]);
626 }
627 for (j = 0; j < 3; j++)
628 avio_write(pb, header_start[j], header_len[j]);
629
630 return 0;
631 }
632
put_wv_codecpriv(AVIOContext * pb,const AVCodecParameters * par)633 static int put_wv_codecpriv(AVIOContext *pb, const AVCodecParameters *par)
634 {
635 if (par->extradata && par->extradata_size == 2)
636 avio_write(pb, par->extradata, 2);
637 else
638 avio_wl16(pb, 0x410); // fallback to the most recent version
639 return 0;
640 }
641
put_flac_codecpriv(AVFormatContext * s,AVIOContext * pb,const AVCodecParameters * par)642 static int put_flac_codecpriv(AVFormatContext *s, AVIOContext *pb,
643 const AVCodecParameters *par)
644 {
645 int write_comment = (par->channel_layout &&
646 !(par->channel_layout & ~0x3ffffULL) &&
647 !ff_flac_is_native_layout(par->channel_layout));
648 int ret = ff_flac_write_header(pb, par->extradata, par->extradata_size,
649 !write_comment);
650
651 if (ret < 0)
652 return ret;
653
654 if (write_comment) {
655 const char *vendor = (s->flags & AVFMT_FLAG_BITEXACT) ?
656 "Lavf" : LIBAVFORMAT_IDENT;
657 AVDictionary *dict = NULL;
658 uint8_t buf[32];
659 int64_t len;
660
661 snprintf(buf, sizeof(buf), "0x%"PRIx64, par->channel_layout);
662 av_dict_set(&dict, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", buf, 0);
663
664 len = ff_vorbiscomment_length(dict, vendor, NULL, 0);
665 av_assert1(len < (1 << 24) - 4);
666
667 avio_w8(pb, 0x84);
668 avio_wb24(pb, len);
669
670 ff_vorbiscomment_write(pb, dict, vendor, NULL, 0);
671
672 av_dict_free(&dict);
673 }
674
675 return 0;
676 }
677
get_aac_sample_rates(AVFormatContext * s,MatroskaMuxContext * mkv,const uint8_t * extradata,int extradata_size,int * sample_rate,int * output_sample_rate)678 static int get_aac_sample_rates(AVFormatContext *s, MatroskaMuxContext *mkv,
679 const uint8_t *extradata, int extradata_size,
680 int *sample_rate, int *output_sample_rate)
681 {
682 MPEG4AudioConfig mp4ac;
683 int ret;
684
685 ret = avpriv_mpeg4audio_get_config2(&mp4ac, extradata, extradata_size, 1, s);
686 /* Don't abort if the failure is because of missing extradata. Assume in that
687 * case a bitstream filter will provide the muxer with the extradata in the
688 * first packet.
689 * Abort however if s->pb is not seekable, as we would not be able to seek back
690 * to write the sample rate elements once the extradata shows up, anyway. */
691 if (ret < 0 && (extradata_size || !IS_SEEKABLE(s->pb, mkv))) {
692 av_log(s, AV_LOG_ERROR,
693 "Error parsing AAC extradata, unable to determine samplerate.\n");
694 return AVERROR(EINVAL);
695 }
696
697 if (ret < 0) {
698 /* This will only happen when this function is called while writing the
699 * header and no extradata is available. The space for this element has
700 * to be reserved for when this function is called again after the
701 * extradata shows up in the first packet, as there's no way to know if
702 * output_sample_rate will be different than sample_rate or not. */
703 *output_sample_rate = *sample_rate;
704 } else {
705 *sample_rate = mp4ac.sample_rate;
706 *output_sample_rate = mp4ac.ext_sample_rate;
707 }
708 return 0;
709 }
710
mkv_write_native_codecprivate(AVFormatContext * s,AVIOContext * pb,const AVCodecParameters * par,AVIOContext * dyn_cp)711 static int mkv_write_native_codecprivate(AVFormatContext *s, AVIOContext *pb,
712 const AVCodecParameters *par,
713 AVIOContext *dyn_cp)
714 {
715 switch (par->codec_id) {
716 case AV_CODEC_ID_VORBIS:
717 case AV_CODEC_ID_THEORA:
718 return put_xiph_codecpriv(s, dyn_cp, par);
719 case AV_CODEC_ID_FLAC:
720 return put_flac_codecpriv(s, dyn_cp, par);
721 case AV_CODEC_ID_WAVPACK:
722 return put_wv_codecpriv(dyn_cp, par);
723 case AV_CODEC_ID_H264:
724 return ff_isom_write_avcc(dyn_cp, par->extradata,
725 par->extradata_size);
726 case AV_CODEC_ID_HEVC:
727 return ff_isom_write_hvcc(dyn_cp, par->extradata,
728 par->extradata_size, 0);
729 case AV_CODEC_ID_AV1:
730 if (par->extradata_size)
731 return ff_isom_write_av1c(dyn_cp, par->extradata,
732 par->extradata_size);
733 else
734 put_ebml_void(pb, 4 + 3);
735 break;
736 case AV_CODEC_ID_ALAC:
737 if (par->extradata_size < 36) {
738 av_log(s, AV_LOG_ERROR,
739 "Invalid extradata found, ALAC expects a 36-byte "
740 "QuickTime atom.");
741 return AVERROR_INVALIDDATA;
742 } else
743 avio_write(dyn_cp, par->extradata + 12,
744 par->extradata_size - 12);
745 break;
746 case AV_CODEC_ID_AAC:
747 if (par->extradata_size)
748 avio_write(dyn_cp, par->extradata, par->extradata_size);
749 else
750 put_ebml_void(pb, MAX_PCE_SIZE + 2 + 4);
751 break;
752 default:
753 if (par->codec_id == AV_CODEC_ID_PRORES &&
754 ff_codec_get_id(ff_codec_movvideo_tags, par->codec_tag) == AV_CODEC_ID_PRORES) {
755 avio_wl32(dyn_cp, par->codec_tag);
756 } else if (par->extradata_size && par->codec_id != AV_CODEC_ID_TTA)
757 avio_write(dyn_cp, par->extradata, par->extradata_size);
758 }
759
760 return 0;
761 }
762
mkv_write_codecprivate(AVFormatContext * s,AVIOContext * pb,AVCodecParameters * par,int native_id,int qt_id)763 static int mkv_write_codecprivate(AVFormatContext *s, AVIOContext *pb,
764 AVCodecParameters *par,
765 int native_id, int qt_id)
766 {
767 AVIOContext *dyn_cp;
768 MatroskaMuxContext *mkv = s->priv_data;
769 uint8_t *codecpriv;
770 int ret, codecpriv_size;
771
772 ret = avio_open_dyn_buf(&dyn_cp);
773 if (ret < 0)
774 return ret;
775
776 if (native_id) {
777 ret = mkv_write_native_codecprivate(s, pb, par, dyn_cp);
778 } else if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
779 if (qt_id) {
780 if (!par->codec_tag)
781 par->codec_tag = ff_codec_get_tag(ff_codec_movvideo_tags,
782 par->codec_id);
783 if ( ff_codec_get_id(ff_codec_movvideo_tags, par->codec_tag) == par->codec_id
784 && (!par->extradata_size || ff_codec_get_id(ff_codec_movvideo_tags, AV_RL32(par->extradata + 4)) != par->codec_id)
785 ) {
786 int i;
787 avio_wb32(dyn_cp, 0x5a + par->extradata_size);
788 avio_wl32(dyn_cp, par->codec_tag);
789 for(i = 0; i < 0x5a - 8; i++)
790 avio_w8(dyn_cp, 0);
791 }
792 avio_write(dyn_cp, par->extradata, par->extradata_size);
793 } else {
794 if (!ff_codec_get_tag(ff_codec_bmp_tags, par->codec_id))
795 av_log(s, AV_LOG_WARNING, "codec %s is not supported by this format\n",
796 avcodec_get_name(par->codec_id));
797
798 if (!par->codec_tag)
799 par->codec_tag = ff_codec_get_tag(ff_codec_bmp_tags,
800 par->codec_id);
801 if (!par->codec_tag && par->codec_id != AV_CODEC_ID_RAWVIDEO) {
802 av_log(s, AV_LOG_ERROR, "No bmp codec tag found for codec %s\n",
803 avcodec_get_name(par->codec_id));
804 ret = AVERROR(EINVAL);
805 }
806
807 ff_put_bmp_header(dyn_cp, par, 0, 0, mkv->flipped_raw_rgb);
808 }
809 } else if (par->codec_type == AVMEDIA_TYPE_AUDIO) {
810 unsigned int tag;
811 tag = ff_codec_get_tag(ff_codec_wav_tags, par->codec_id);
812 if (!tag) {
813 av_log(s, AV_LOG_ERROR, "No wav codec tag found for codec %s\n",
814 avcodec_get_name(par->codec_id));
815 ret = AVERROR(EINVAL);
816 }
817 if (!par->codec_tag)
818 par->codec_tag = tag;
819
820 ff_put_wav_header(s, dyn_cp, par, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX);
821 }
822
823 if (ret >= 0) {
824 codecpriv_size = avio_get_dyn_buf(dyn_cp, &codecpriv);
825 if ((ret = dyn_cp->error) >= 0 && codecpriv_size)
826 put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codecpriv,
827 codecpriv_size);
828 }
829 ffio_free_dyn_buf(&dyn_cp);
830 return ret;
831 }
832
mkv_write_video_color(AVIOContext * pb,const AVStream * st,const AVCodecParameters * par)833 static void mkv_write_video_color(AVIOContext *pb, const AVStream *st,
834 const AVCodecParameters *par)
835 {
836 /* 18 Elements with two bytes ID, one byte length field, 8 bytes payload
837 * a master element with two bytes ID and one byte length field
838 * plus another byte to stay clear of the end. */
839 uint8_t colour[(2 + 1 + 8) * 18 + (2 + 1) + 1];
840 AVIOContext buf, *dyn_cp = &buf;
841 int colorinfo_size;
842 const void *side_data;
843
844 ffio_init_context(dyn_cp, colour, sizeof(colour), 1, NULL, NULL, NULL, NULL);
845
846 if (par->color_trc != AVCOL_TRC_UNSPECIFIED &&
847 par->color_trc < AVCOL_TRC_NB) {
848 put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORTRANSFERCHARACTERISTICS,
849 par->color_trc);
850 }
851 if (par->color_space != AVCOL_SPC_UNSPECIFIED &&
852 par->color_space < AVCOL_SPC_NB) {
853 put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORMATRIXCOEFF, par->color_space);
854 }
855 if (par->color_primaries != AVCOL_PRI_UNSPECIFIED &&
856 par->color_primaries < AVCOL_PRI_NB) {
857 put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORPRIMARIES, par->color_primaries);
858 }
859 if (par->color_range != AVCOL_RANGE_UNSPECIFIED &&
860 par->color_range < AVCOL_RANGE_NB) {
861 put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORRANGE, par->color_range);
862 }
863 if (par->chroma_location != AVCHROMA_LOC_UNSPECIFIED &&
864 par->chroma_location <= AVCHROMA_LOC_TOP) {
865 int xpos, ypos;
866
867 avcodec_enum_to_chroma_pos(&xpos, &ypos, par->chroma_location);
868 put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORCHROMASITINGHORZ, (xpos >> 7) + 1);
869 put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORCHROMASITINGVERT, (ypos >> 7) + 1);
870 }
871
872 side_data = av_stream_get_side_data(st, AV_PKT_DATA_CONTENT_LIGHT_LEVEL,
873 NULL);
874 if (side_data) {
875 const AVContentLightMetadata *metadata = side_data;
876 put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORMAXCLL, metadata->MaxCLL);
877 put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORMAXFALL, metadata->MaxFALL);
878 }
879
880 side_data = av_stream_get_side_data(st, AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
881 NULL);
882 if (side_data) {
883 ebml_master meta_element = start_ebml_master(
884 dyn_cp, MATROSKA_ID_VIDEOCOLORMASTERINGMETA, 10 * (2 + 1 + 8));
885 const AVMasteringDisplayMetadata *metadata = side_data;
886 if (metadata->has_primaries) {
887 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_RX,
888 av_q2d(metadata->display_primaries[0][0]));
889 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_RY,
890 av_q2d(metadata->display_primaries[0][1]));
891 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_GX,
892 av_q2d(metadata->display_primaries[1][0]));
893 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_GY,
894 av_q2d(metadata->display_primaries[1][1]));
895 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_BX,
896 av_q2d(metadata->display_primaries[2][0]));
897 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_BY,
898 av_q2d(metadata->display_primaries[2][1]));
899 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_WHITEX,
900 av_q2d(metadata->white_point[0]));
901 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_WHITEY,
902 av_q2d(metadata->white_point[1]));
903 }
904 if (metadata->has_luminance) {
905 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_LUMINANCEMAX,
906 av_q2d(metadata->max_luminance));
907 put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_LUMINANCEMIN,
908 av_q2d(metadata->min_luminance));
909 }
910 end_ebml_master(dyn_cp, meta_element);
911 }
912
913 colorinfo_size = avio_tell(dyn_cp);
914 if (colorinfo_size)
915 put_ebml_binary(pb, MATROSKA_ID_VIDEOCOLOR, colour, colorinfo_size);
916 }
917
mkv_write_video_projection(AVFormatContext * s,AVIOContext * pb,const AVStream * st)918 static void mkv_write_video_projection(AVFormatContext *s, AVIOContext *pb,
919 const AVStream *st)
920 {
921 ebml_master projection;
922 uint8_t private[20];
923
924 const AVSphericalMapping *spherical =
925 (const AVSphericalMapping *)av_stream_get_side_data(st, AV_PKT_DATA_SPHERICAL,
926 NULL);
927
928 if (!spherical)
929 return;
930
931 if (spherical->projection != AV_SPHERICAL_EQUIRECTANGULAR &&
932 spherical->projection != AV_SPHERICAL_EQUIRECTANGULAR_TILE &&
933 spherical->projection != AV_SPHERICAL_CUBEMAP) {
934 av_log(s, AV_LOG_WARNING, "Unknown projection type\n");
935 return;
936 }
937
938 // Maximally 4 8-byte elements with id-length 2 + 1 byte length field
939 // and the private data of the AV_SPHERICAL_EQUIRECTANGULAR_TILE case
940 projection = start_ebml_master(pb, MATROSKA_ID_VIDEOPROJECTION,
941 4 * (2 + 1 + 8) + (2 + 1 + 20));
942
943 switch (spherical->projection) {
944 case AV_SPHERICAL_EQUIRECTANGULAR:
945 put_ebml_uint(pb, MATROSKA_ID_VIDEOPROJECTIONTYPE,
946 MATROSKA_VIDEO_PROJECTION_TYPE_EQUIRECTANGULAR);
947 break;
948 case AV_SPHERICAL_EQUIRECTANGULAR_TILE:
949 put_ebml_uint(pb, MATROSKA_ID_VIDEOPROJECTIONTYPE,
950 MATROSKA_VIDEO_PROJECTION_TYPE_EQUIRECTANGULAR);
951 AV_WB32(private, 0); // version + flags
952 AV_WB32(private + 4, spherical->bound_top);
953 AV_WB32(private + 8, spherical->bound_bottom);
954 AV_WB32(private + 12, spherical->bound_left);
955 AV_WB32(private + 16, spherical->bound_right);
956 put_ebml_binary(pb, MATROSKA_ID_VIDEOPROJECTIONPRIVATE,
957 private, 20);
958 break;
959 case AV_SPHERICAL_CUBEMAP:
960 put_ebml_uint(pb, MATROSKA_ID_VIDEOPROJECTIONTYPE,
961 MATROSKA_VIDEO_PROJECTION_TYPE_CUBEMAP);
962 AV_WB32(private, 0); // version + flags
963 AV_WB32(private + 4, 0); // layout
964 AV_WB32(private + 8, spherical->padding);
965 put_ebml_binary(pb, MATROSKA_ID_VIDEOPROJECTIONPRIVATE,
966 private, 12);
967 break;
968 default:
969 av_assert0(0);
970 }
971
972 if (spherical->yaw)
973 put_ebml_float(pb, MATROSKA_ID_VIDEOPROJECTIONPOSEYAW,
974 (double) spherical->yaw / (1 << 16));
975 if (spherical->pitch)
976 put_ebml_float(pb, MATROSKA_ID_VIDEOPROJECTIONPOSEPITCH,
977 (double) spherical->pitch / (1 << 16));
978 if (spherical->roll)
979 put_ebml_float(pb, MATROSKA_ID_VIDEOPROJECTIONPOSEROLL,
980 (double) spherical->roll / (1 << 16));
981
982 end_ebml_master(pb, projection);
983 }
984
mkv_write_field_order(AVIOContext * pb,int mode,enum AVFieldOrder field_order)985 static void mkv_write_field_order(AVIOContext *pb, int mode,
986 enum AVFieldOrder field_order)
987 {
988 switch (field_order) {
989 case AV_FIELD_UNKNOWN:
990 break;
991 case AV_FIELD_PROGRESSIVE:
992 put_ebml_uint(pb, MATROSKA_ID_VIDEOFLAGINTERLACED,
993 MATROSKA_VIDEO_INTERLACE_FLAG_PROGRESSIVE);
994 break;
995 case AV_FIELD_TT:
996 case AV_FIELD_BB:
997 case AV_FIELD_TB:
998 case AV_FIELD_BT:
999 put_ebml_uint(pb, MATROSKA_ID_VIDEOFLAGINTERLACED,
1000 MATROSKA_VIDEO_INTERLACE_FLAG_INTERLACED);
1001 if (mode != MODE_WEBM) {
1002 switch (field_order) {
1003 case AV_FIELD_TT:
1004 put_ebml_uint(pb, MATROSKA_ID_VIDEOFIELDORDER,
1005 MATROSKA_VIDEO_FIELDORDER_TT);
1006 break;
1007 case AV_FIELD_BB:
1008 put_ebml_uint(pb, MATROSKA_ID_VIDEOFIELDORDER,
1009 MATROSKA_VIDEO_FIELDORDER_BB);
1010 break;
1011 case AV_FIELD_TB:
1012 put_ebml_uint(pb, MATROSKA_ID_VIDEOFIELDORDER,
1013 MATROSKA_VIDEO_FIELDORDER_TB);
1014 break;
1015 case AV_FIELD_BT:
1016 put_ebml_uint(pb, MATROSKA_ID_VIDEOFIELDORDER,
1017 MATROSKA_VIDEO_FIELDORDER_BT);
1018 break;
1019 }
1020 }
1021 }
1022 }
1023
mkv_write_stereo_mode(AVFormatContext * s,AVIOContext * pb,AVStream * st,int mode,int * h_width,int * h_height)1024 static int mkv_write_stereo_mode(AVFormatContext *s, AVIOContext *pb,
1025 AVStream *st, int mode, int *h_width, int *h_height)
1026 {
1027 const AVDictionaryEntry *tag;
1028 MatroskaVideoStereoModeType format = MATROSKA_VIDEO_STEREOMODE_TYPE_NB;
1029 const AVStereo3D *stereo;
1030
1031 *h_width = 1;
1032 *h_height = 1;
1033 // convert metadata into proper side data and add it to the stream
1034 if ((tag = av_dict_get(st->metadata, "stereo_mode", NULL, 0)) ||
1035 (tag = av_dict_get( s->metadata, "stereo_mode", NULL, 0))) {
1036 int stereo_mode = atoi(tag->value);
1037
1038 for (int i = 0; i < MATROSKA_VIDEO_STEREOMODE_TYPE_NB; i++)
1039 if (!strcmp(tag->value, ff_matroska_video_stereo_mode[i])){
1040 stereo_mode = i;
1041 break;
1042 }
1043
1044 if (stereo_mode < MATROSKA_VIDEO_STEREOMODE_TYPE_NB &&
1045 stereo_mode != 10 && stereo_mode != 12) {
1046 int ret = ff_mkv_stereo3d_conv(st, stereo_mode);
1047 if (ret < 0)
1048 return ret;
1049 }
1050 }
1051
1052 stereo = (const AVStereo3D*)av_stream_get_side_data(st, AV_PKT_DATA_STEREO3D,
1053 NULL);
1054 if (stereo) {
1055 switch (stereo->type) {
1056 case AV_STEREO3D_2D:
1057 format = MATROSKA_VIDEO_STEREOMODE_TYPE_MONO;
1058 break;
1059 case AV_STEREO3D_SIDEBYSIDE:
1060 format = (stereo->flags & AV_STEREO3D_FLAG_INVERT)
1061 ? MATROSKA_VIDEO_STEREOMODE_TYPE_RIGHT_LEFT
1062 : MATROSKA_VIDEO_STEREOMODE_TYPE_LEFT_RIGHT;
1063 *h_width = 2;
1064 break;
1065 case AV_STEREO3D_TOPBOTTOM:
1066 format = MATROSKA_VIDEO_STEREOMODE_TYPE_TOP_BOTTOM;
1067 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
1068 format--;
1069 *h_height = 2;
1070 break;
1071 case AV_STEREO3D_CHECKERBOARD:
1072 format = MATROSKA_VIDEO_STEREOMODE_TYPE_CHECKERBOARD_LR;
1073 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
1074 format--;
1075 break;
1076 case AV_STEREO3D_LINES:
1077 format = MATROSKA_VIDEO_STEREOMODE_TYPE_ROW_INTERLEAVED_LR;
1078 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
1079 format--;
1080 *h_height = 2;
1081 break;
1082 case AV_STEREO3D_COLUMNS:
1083 format = MATROSKA_VIDEO_STEREOMODE_TYPE_COL_INTERLEAVED_LR;
1084 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
1085 format--;
1086 *h_width = 2;
1087 break;
1088 case AV_STEREO3D_FRAMESEQUENCE:
1089 format = MATROSKA_VIDEO_STEREOMODE_TYPE_BOTH_EYES_BLOCK_LR;
1090 if (stereo->flags & AV_STEREO3D_FLAG_INVERT)
1091 format++;
1092 break;
1093 }
1094 }
1095
1096 if (format == MATROSKA_VIDEO_STEREOMODE_TYPE_NB)
1097 return 0;
1098
1099 // if webm, do not write unsupported modes
1100 if ((mode == MODE_WEBM &&
1101 format > MATROSKA_VIDEO_STEREOMODE_TYPE_TOP_BOTTOM &&
1102 format != MATROSKA_VIDEO_STEREOMODE_TYPE_RIGHT_LEFT)
1103 || format >= MATROSKA_VIDEO_STEREOMODE_TYPE_NB) {
1104 av_log(s, AV_LOG_ERROR,
1105 "The specified stereo mode is not valid.\n");
1106 return AVERROR(EINVAL);
1107 }
1108
1109 // write StereoMode if format is valid
1110 put_ebml_uint(pb, MATROSKA_ID_VIDEOSTEREOMODE, format);
1111
1112 return 0;
1113 }
1114
mkv_write_track(AVFormatContext * s,MatroskaMuxContext * mkv,AVStream * st,mkv_track * track,AVIOContext * pb,int is_default)1115 static int mkv_write_track(AVFormatContext *s, MatroskaMuxContext *mkv,
1116 AVStream *st, mkv_track *track, AVIOContext *pb,
1117 int is_default)
1118 {
1119 AVCodecParameters *par = st->codecpar;
1120 ebml_master subinfo, track_master;
1121 int native_id = 0;
1122 int qt_id = 0;
1123 int bit_depth;
1124 int sample_rate = par->sample_rate;
1125 int output_sample_rate = 0;
1126 int display_width_div = 1;
1127 int display_height_div = 1;
1128 int j, ret;
1129 const AVDictionaryEntry *tag;
1130
1131 if (par->codec_type == AVMEDIA_TYPE_ATTACHMENT)
1132 return 0;
1133
1134 if (par->codec_id == AV_CODEC_ID_AAC) {
1135 ret = get_aac_sample_rates(s, mkv, par->extradata, par->extradata_size,
1136 &sample_rate, &output_sample_rate);
1137 if (ret < 0)
1138 return ret;
1139 }
1140
1141 track_master = start_ebml_master(pb, MATROSKA_ID_TRACKENTRY, 0);
1142 put_ebml_uint(pb, MATROSKA_ID_TRACKNUMBER, track->track_num);
1143 put_ebml_uid (pb, MATROSKA_ID_TRACKUID, track->uid);
1144 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGLACING, 0); // no lacing (yet)
1145
1146 if ((tag = av_dict_get(st->metadata, "title", NULL, 0)))
1147 put_ebml_string(pb, MATROSKA_ID_TRACKNAME, tag->value);
1148 tag = av_dict_get(st->metadata, "language", NULL, 0);
1149 put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE,
1150 tag && tag->value[0] ? tag->value : "und");
1151
1152 // The default value for TRACKFLAGDEFAULT is 1, so add element
1153 // if we need to clear it.
1154 if (!is_default)
1155 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGDEFAULT, 0);
1156
1157 if (st->disposition & AV_DISPOSITION_FORCED)
1158 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGFORCED, 1);
1159
1160 if (mkv->mode == MODE_WEBM) {
1161 const char *codec_id;
1162 if (par->codec_type != AVMEDIA_TYPE_SUBTITLE) {
1163 for (j = 0; ff_webm_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
1164 if (ff_webm_codec_tags[j].id == par->codec_id) {
1165 codec_id = ff_webm_codec_tags[j].str;
1166 native_id = 1;
1167 break;
1168 }
1169 }
1170 } else if (par->codec_id == AV_CODEC_ID_WEBVTT) {
1171 if (st->disposition & AV_DISPOSITION_CAPTIONS) {
1172 codec_id = "D_WEBVTT/CAPTIONS";
1173 native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
1174 } else if (st->disposition & AV_DISPOSITION_DESCRIPTIONS) {
1175 codec_id = "D_WEBVTT/DESCRIPTIONS";
1176 native_id = MATROSKA_TRACK_TYPE_METADATA;
1177 } else if (st->disposition & AV_DISPOSITION_METADATA) {
1178 codec_id = "D_WEBVTT/METADATA";
1179 native_id = MATROSKA_TRACK_TYPE_METADATA;
1180 } else {
1181 codec_id = "D_WEBVTT/SUBTITLES";
1182 native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
1183 }
1184 }
1185
1186 if (!native_id) {
1187 av_log(s, AV_LOG_ERROR,
1188 "Only VP8 or VP9 or AV1 video and Vorbis or Opus audio and WebVTT subtitles are supported for WebM.\n");
1189 return AVERROR(EINVAL);
1190 }
1191
1192 put_ebml_string(pb, MATROSKA_ID_CODECID, codec_id);
1193 } else {
1194 if (st->disposition & AV_DISPOSITION_COMMENT)
1195 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGCOMMENTARY, 1);
1196 if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
1197 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGHEARINGIMPAIRED, 1);
1198 if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
1199 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGVISUALIMPAIRED, 1);
1200 if (st->disposition & (AV_DISPOSITION_ORIGINAL | AV_DISPOSITION_DUB) &&
1201 (st->disposition & (AV_DISPOSITION_ORIGINAL | AV_DISPOSITION_DUB))
1202 != (AV_DISPOSITION_ORIGINAL | AV_DISPOSITION_DUB))
1203 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGORIGINAL,
1204 !!(st->disposition & AV_DISPOSITION_ORIGINAL));
1205
1206 // look for a codec ID string specific to mkv to use,
1207 // if none are found, use AVI codes
1208 if (par->codec_id != AV_CODEC_ID_RAWVIDEO || par->codec_tag) {
1209 for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {
1210 if (ff_mkv_codec_tags[j].id == par->codec_id && par->codec_id != AV_CODEC_ID_FFV1) {
1211 put_ebml_string(pb, MATROSKA_ID_CODECID, ff_mkv_codec_tags[j].str);
1212 native_id = 1;
1213 break;
1214 }
1215 }
1216 } else {
1217 if (mkv->allow_raw_vfw) {
1218 native_id = 0;
1219 } else {
1220 av_log(s, AV_LOG_ERROR, "Raw RGB is not supported Natively in Matroska, you can use AVI or NUT or\n"
1221 "If you would like to store it anyway using VFW mode, enable allow_raw_vfw (-allow_raw_vfw 1)\n");
1222 return AVERROR(EINVAL);
1223 }
1224 }
1225 }
1226
1227 switch (par->codec_type) {
1228 case AVMEDIA_TYPE_VIDEO:
1229 mkv->have_video = 1;
1230 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_VIDEO);
1231
1232 if( st->avg_frame_rate.num > 0 && st->avg_frame_rate.den > 0
1233 && av_cmp_q(av_inv_q(st->avg_frame_rate), st->time_base) > 0)
1234 put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, 1000000000LL * st->avg_frame_rate.den / st->avg_frame_rate.num);
1235 else if( st->r_frame_rate.num > 0 && st->r_frame_rate.den > 0
1236 && av_cmp_q(av_inv_q(st->r_frame_rate), st->time_base) > 0)
1237 put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, 1000000000LL * st->r_frame_rate.den / st->r_frame_rate.num);
1238
1239 if (!native_id &&
1240 ff_codec_get_tag(ff_codec_movvideo_tags, par->codec_id) &&
1241 ((!ff_codec_get_tag(ff_codec_bmp_tags, par->codec_id) && par->codec_id != AV_CODEC_ID_RAWVIDEO) ||
1242 par->codec_id == AV_CODEC_ID_SVQ1 ||
1243 par->codec_id == AV_CODEC_ID_SVQ3 ||
1244 par->codec_id == AV_CODEC_ID_CINEPAK))
1245 qt_id = 1;
1246
1247 if (qt_id)
1248 put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");
1249 else if (!native_id) {
1250 // if there is no mkv-specific codec ID, use VFW mode
1251 put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");
1252 track->write_dts = 1;
1253 s->internal->avoid_negative_ts_use_pts = 0;
1254 }
1255
1256 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
1257
1258 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , par->width);
1259 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, par->height);
1260
1261 mkv_write_field_order(pb, mkv->mode, par->field_order);
1262
1263 // check both side data and metadata for stereo information,
1264 // write the result to the bitstream if any is found
1265 ret = mkv_write_stereo_mode(s, pb, st, mkv->mode,
1266 &display_width_div,
1267 &display_height_div);
1268 if (ret < 0)
1269 return ret;
1270
1271 if (((tag = av_dict_get(st->metadata, "alpha_mode", NULL, 0)) && atoi(tag->value)) ||
1272 ((tag = av_dict_get( s->metadata, "alpha_mode", NULL, 0)) && atoi(tag->value)) ||
1273 (par->format == AV_PIX_FMT_YUVA420P)) {
1274 put_ebml_uint(pb, MATROSKA_ID_VIDEOALPHAMODE, 1);
1275 }
1276
1277 // write DisplayWidth and DisplayHeight, they contain the size of
1278 // a single source view and/or the display aspect ratio
1279 if (st->sample_aspect_ratio.num) {
1280 int64_t d_width = av_rescale(par->width, st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
1281 if (d_width > INT_MAX) {
1282 av_log(s, AV_LOG_ERROR, "Overflow in display width\n");
1283 return AVERROR(EINVAL);
1284 }
1285 if (d_width != par->width || display_width_div != 1 || display_height_div != 1) {
1286 if (mkv->mode == MODE_WEBM || display_width_div != 1 || display_height_div != 1) {
1287 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , d_width / display_width_div);
1288 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, par->height / display_height_div);
1289 } else {
1290 AVRational display_aspect_ratio;
1291 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
1292 par->width * (int64_t)st->sample_aspect_ratio.num,
1293 par->height * (int64_t)st->sample_aspect_ratio.den,
1294 1024 * 1024);
1295 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH, display_aspect_ratio.num);
1296 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, display_aspect_ratio.den);
1297 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYUNIT, MATROSKA_VIDEO_DISPLAYUNIT_DAR);
1298 }
1299 }
1300 } else if (display_width_div != 1 || display_height_div != 1) {
1301 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , par->width / display_width_div);
1302 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, par->height / display_height_div);
1303 } else if (mkv->mode != MODE_WEBM)
1304 put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYUNIT, MATROSKA_VIDEO_DISPLAYUNIT_UNKNOWN);
1305
1306 if (par->codec_id == AV_CODEC_ID_RAWVIDEO) {
1307 uint32_t color_space = av_le2ne32(par->codec_tag);
1308 put_ebml_binary(pb, MATROSKA_ID_VIDEOCOLORSPACE, &color_space, sizeof(color_space));
1309 }
1310 mkv_write_video_color(pb, st, par);
1311 mkv_write_video_projection(s, pb, st);
1312
1313 end_ebml_master(pb, subinfo);
1314 break;
1315
1316 case AVMEDIA_TYPE_AUDIO:
1317 if (par->initial_padding && par->codec_id == AV_CODEC_ID_OPUS) {
1318 int64_t codecdelay = av_rescale_q(par->initial_padding,
1319 (AVRational){ 1, 48000 },
1320 (AVRational){ 1, 1000000000 });
1321 if (codecdelay < 0) {
1322 av_log(s, AV_LOG_ERROR, "Initial padding is invalid\n");
1323 return AVERROR(EINVAL);
1324 }
1325 // track->ts_offset = av_rescale_q(par->initial_padding,
1326 // (AVRational){ 1, par->sample_rate },
1327 // st->time_base);
1328
1329 put_ebml_uint(pb, MATROSKA_ID_CODECDELAY, codecdelay);
1330 }
1331 if (par->codec_id == AV_CODEC_ID_OPUS)
1332 put_ebml_uint(pb, MATROSKA_ID_SEEKPREROLL, OPUS_SEEK_PREROLL);
1333
1334 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_AUDIO);
1335
1336 if (!native_id)
1337 // no mkv-specific ID, use ACM mode
1338 put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");
1339
1340 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 6 + 4 * 9);
1341 put_ebml_uint (pb, MATROSKA_ID_AUDIOCHANNELS , par->channels);
1342
1343 track->sample_rate_offset = avio_tell(pb);
1344 put_ebml_float (pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, sample_rate);
1345 if (output_sample_rate)
1346 put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
1347
1348 bit_depth = av_get_bits_per_sample(par->codec_id);
1349 if (!bit_depth && par->codec_id != AV_CODEC_ID_ADPCM_G726) {
1350 if (par->bits_per_raw_sample)
1351 bit_depth = par->bits_per_raw_sample;
1352 else
1353 bit_depth = av_get_bytes_per_sample(par->format) << 3;
1354 }
1355 if (!bit_depth)
1356 bit_depth = par->bits_per_coded_sample;
1357 if (bit_depth)
1358 put_ebml_uint(pb, MATROSKA_ID_AUDIOBITDEPTH, bit_depth);
1359 end_ebml_master(pb, subinfo);
1360 break;
1361
1362 case AVMEDIA_TYPE_SUBTITLE:
1363 if (!native_id) {
1364 av_log(s, AV_LOG_ERROR, "Subtitle codec %d is not supported.\n", par->codec_id);
1365 return AVERROR(ENOSYS);
1366 }
1367 if (mkv->mode != MODE_WEBM && st->disposition & AV_DISPOSITION_DESCRIPTIONS)
1368 put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGTEXTDESCRIPTIONS, 1);
1369
1370 if (mkv->mode != MODE_WEBM || par->codec_id != AV_CODEC_ID_WEBVTT)
1371 native_id = MATROSKA_TRACK_TYPE_SUBTITLE;
1372
1373 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, native_id);
1374 break;
1375 default:
1376 av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.\n");
1377 return AVERROR(EINVAL);
1378 }
1379
1380 if (mkv->mode != MODE_WEBM || par->codec_id != AV_CODEC_ID_WEBVTT) {
1381 track->codecpriv_offset = avio_tell(pb);
1382 ret = mkv_write_codecprivate(s, pb, par, native_id, qt_id);
1383 if (ret < 0)
1384 return ret;
1385 }
1386
1387 end_ebml_master(pb, track_master);
1388
1389 return 0;
1390 }
1391
mkv_write_tracks(AVFormatContext * s)1392 static int mkv_write_tracks(AVFormatContext *s)
1393 {
1394 MatroskaMuxContext *mkv = s->priv_data;
1395 AVIOContext *pb = s->pb;
1396 int i, ret, video_default_idx, audio_default_idx, subtitle_default_idx;
1397
1398 if (mkv->nb_attachments == s->nb_streams)
1399 return 0;
1400
1401 ret = start_ebml_master_crc32(&mkv->track.bc, mkv);
1402 if (ret < 0)
1403 return ret;
1404
1405 if (mkv->default_mode != DEFAULT_MODE_PASSTHROUGH) {
1406 int video_idx, audio_idx, subtitle_idx;
1407
1408 video_idx = video_default_idx =
1409 audio_idx = audio_default_idx =
1410 subtitle_idx = subtitle_default_idx = -1;
1411
1412 for (i = s->nb_streams - 1; i >= 0; i--) {
1413 AVStream *st = s->streams[i];
1414
1415 switch (st->codecpar->codec_type) {
1416 #define CASE(type, variable) \
1417 case AVMEDIA_TYPE_ ## type: \
1418 variable ## _idx = i; \
1419 if (st->disposition & AV_DISPOSITION_DEFAULT) \
1420 variable ## _default_idx = i; \
1421 break;
1422 CASE(VIDEO, video)
1423 CASE(AUDIO, audio)
1424 CASE(SUBTITLE, subtitle)
1425 #undef CASE
1426 }
1427 }
1428
1429 video_default_idx = FFMAX(video_default_idx, video_idx);
1430 audio_default_idx = FFMAX(audio_default_idx, audio_idx);
1431 if (mkv->default_mode != DEFAULT_MODE_INFER_NO_SUBS)
1432 subtitle_default_idx = FFMAX(subtitle_default_idx, subtitle_idx);
1433 }
1434 for (i = 0; i < s->nb_streams; i++) {
1435 AVStream *st = s->streams[i];
1436 int is_default = mkv->default_mode == DEFAULT_MODE_PASSTHROUGH ?
1437 st->disposition & AV_DISPOSITION_DEFAULT :
1438 i == video_default_idx || i == audio_default_idx ||
1439 i == subtitle_default_idx;
1440 ret = mkv_write_track(s, mkv, st, &mkv->tracks[i],
1441 mkv->track.bc, is_default);
1442 if (ret < 0)
1443 return ret;
1444 }
1445
1446 return end_ebml_master_crc32_tentatively(pb, &mkv->track, mkv,
1447 MATROSKA_ID_TRACKS);
1448 }
1449
mkv_write_simpletag(AVIOContext * pb,const AVDictionaryEntry * t)1450 static int mkv_write_simpletag(AVIOContext *pb, const AVDictionaryEntry *t)
1451 {
1452 uint8_t *key = av_strdup(t->key);
1453 uint8_t *p = key;
1454 const uint8_t *lang = NULL;
1455 ebml_master tag;
1456
1457 if (!key)
1458 return AVERROR(ENOMEM);
1459
1460 if ((p = strrchr(p, '-')) &&
1461 (lang = ff_convert_lang_to(p + 1, AV_LANG_ISO639_2_BIBL)))
1462 *p = 0;
1463
1464 p = key;
1465 while (*p) {
1466 if (*p == ' ')
1467 *p = '_';
1468 else if (*p >= 'a' && *p <= 'z')
1469 *p -= 'a' - 'A';
1470 p++;
1471 }
1472
1473 tag = start_ebml_master(pb, MATROSKA_ID_SIMPLETAG, 0);
1474 put_ebml_string(pb, MATROSKA_ID_TAGNAME, key);
1475 if (lang)
1476 put_ebml_string(pb, MATROSKA_ID_TAGLANG, lang);
1477 put_ebml_string(pb, MATROSKA_ID_TAGSTRING, t->value);
1478 end_ebml_master(pb, tag);
1479
1480 av_freep(&key);
1481 return 0;
1482 }
1483
mkv_write_tag_targets(MatroskaMuxContext * mkv,AVIOContext ** pb,ebml_master * tag,uint32_t elementid,uint64_t uid)1484 static int mkv_write_tag_targets(MatroskaMuxContext *mkv, AVIOContext **pb,
1485 ebml_master *tag, uint32_t elementid, uint64_t uid)
1486 {
1487 ebml_master targets;
1488 int ret;
1489
1490 if (!*pb) {
1491 ret = start_ebml_master_crc32(pb, mkv);
1492 if (ret < 0)
1493 return ret;
1494 }
1495
1496 *tag = start_ebml_master(*pb, MATROSKA_ID_TAG, 0);
1497 targets = start_ebml_master(*pb, MATROSKA_ID_TAGTARGETS, 4 + 1 + 8);
1498 if (elementid)
1499 put_ebml_uid(*pb, elementid, uid);
1500 end_ebml_master(*pb, targets);
1501 return 0;
1502 }
1503
mkv_check_tag_name(const char * name,uint32_t elementid)1504 static int mkv_check_tag_name(const char *name, uint32_t elementid)
1505 {
1506 return av_strcasecmp(name, "title") &&
1507 av_strcasecmp(name, "stereo_mode") &&
1508 av_strcasecmp(name, "creation_time") &&
1509 av_strcasecmp(name, "encoding_tool") &&
1510 av_strcasecmp(name, "duration") &&
1511 (elementid != MATROSKA_ID_TAGTARGETS_TRACKUID ||
1512 av_strcasecmp(name, "language")) &&
1513 (elementid != MATROSKA_ID_TAGTARGETS_ATTACHUID ||
1514 (av_strcasecmp(name, "filename") &&
1515 av_strcasecmp(name, "mimetype")));
1516 }
1517
mkv_write_tag(MatroskaMuxContext * mkv,const AVDictionary * m,AVIOContext ** pb,ebml_master * tag,uint32_t elementid,uint64_t uid)1518 static int mkv_write_tag(MatroskaMuxContext *mkv, const AVDictionary *m,
1519 AVIOContext **pb, ebml_master *tag,
1520 uint32_t elementid, uint64_t uid)
1521 {
1522 const AVDictionaryEntry *t = NULL;
1523 ebml_master tag2;
1524 int ret;
1525
1526 ret = mkv_write_tag_targets(mkv, pb, tag ? tag : &tag2, elementid, uid);
1527 if (ret < 0)
1528 return ret;
1529
1530 while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX))) {
1531 if (mkv_check_tag_name(t->key, elementid)) {
1532 ret = mkv_write_simpletag(*pb, t);
1533 if (ret < 0)
1534 return ret;
1535 }
1536 }
1537
1538 if (!tag)
1539 end_ebml_master(*pb, tag2);
1540
1541 return 0;
1542 }
1543
mkv_check_tag(const AVDictionary * m,uint32_t elementid)1544 static int mkv_check_tag(const AVDictionary *m, uint32_t elementid)
1545 {
1546 const AVDictionaryEntry *t = NULL;
1547
1548 while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX)))
1549 if (mkv_check_tag_name(t->key, elementid))
1550 return 1;
1551
1552 return 0;
1553 }
1554
mkv_write_tags(AVFormatContext * s)1555 static int mkv_write_tags(AVFormatContext *s)
1556 {
1557 MatroskaMuxContext *mkv = s->priv_data;
1558 ebml_master tag, *tagp = IS_SEEKABLE(s->pb, mkv) ? &tag : NULL;
1559 int i, ret;
1560
1561 mkv->wrote_tags = 1;
1562
1563 ff_metadata_conv_ctx(s, ff_mkv_metadata_conv, NULL);
1564
1565 if (mkv_check_tag(s->metadata, 0)) {
1566 ret = mkv_write_tag(mkv, s->metadata, &mkv->tags.bc, NULL, 0, 0);
1567 if (ret < 0)
1568 return ret;
1569 }
1570
1571 for (i = 0; i < s->nb_streams; i++) {
1572 const AVStream *st = s->streams[i];
1573 mkv_track *track = &mkv->tracks[i];
1574
1575 if (st->codecpar->codec_type == AVMEDIA_TYPE_ATTACHMENT)
1576 continue;
1577
1578 if (!tagp && !mkv_check_tag(st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID))
1579 continue;
1580
1581 ret = mkv_write_tag(mkv, st->metadata, &mkv->tags.bc, tagp,
1582 MATROSKA_ID_TAGTARGETS_TRACKUID, track->uid);
1583 if (ret < 0)
1584 return ret;
1585
1586 if (tagp) {
1587 AVIOContext *pb = mkv->tags.bc;
1588 ebml_master simpletag;
1589
1590 simpletag = start_ebml_master(pb, MATROSKA_ID_SIMPLETAG,
1591 2 + 1 + 8 + 23);
1592 put_ebml_string(pb, MATROSKA_ID_TAGNAME, "DURATION");
1593 track->duration_offset = avio_tell(pb);
1594
1595 // Reserve space to write duration as a 20-byte string.
1596 // 2 (ebml id) + 1 (data size) + 20 (data)
1597 put_ebml_void(pb, 23);
1598 end_ebml_master(pb, simpletag);
1599 end_ebml_master(pb, tag);
1600 }
1601 }
1602
1603 if (mkv->nb_attachments && mkv->mode != MODE_WEBM) {
1604 for (i = 0; i < s->nb_streams; i++) {
1605 const mkv_track *track = &mkv->tracks[i];
1606 const AVStream *st = s->streams[i];
1607
1608 if (st->codecpar->codec_type != AVMEDIA_TYPE_ATTACHMENT)
1609 continue;
1610
1611 if (!mkv_check_tag(st->metadata, MATROSKA_ID_TAGTARGETS_ATTACHUID))
1612 continue;
1613
1614 ret = mkv_write_tag(mkv, st->metadata, &mkv->tags.bc, NULL,
1615 MATROSKA_ID_TAGTARGETS_ATTACHUID, track->uid);
1616 if (ret < 0)
1617 return ret;
1618 }
1619 }
1620
1621 if (mkv->tags.bc) {
1622 return end_ebml_master_crc32_tentatively(s->pb, &mkv->tags, mkv,
1623 MATROSKA_ID_TAGS);
1624 }
1625 return 0;
1626 }
1627
mkv_new_chapter_ids_needed(const AVFormatContext * s)1628 static int mkv_new_chapter_ids_needed(const AVFormatContext *s)
1629 {
1630 for (unsigned i = 0; i < s->nb_chapters; i++) {
1631 if (!s->chapters[i]->id)
1632 return 1;
1633 for (unsigned j = 0; j < i; j++)
1634 if (s->chapters[j]->id == s->chapters[i]->id)
1635 return 1;
1636 }
1637 return 0;
1638 }
1639
mkv_write_chapters(AVFormatContext * s)1640 static int mkv_write_chapters(AVFormatContext *s)
1641 {
1642 MatroskaMuxContext *mkv = s->priv_data;
1643 AVIOContext *dyn_cp = NULL, *dyn_tags = NULL, **tags, *pb = s->pb;
1644 ebml_master editionentry;
1645 AVRational scale = {1, 1E9};
1646 int ret, create_new_ids;
1647
1648 if (!s->nb_chapters || mkv->wrote_chapters)
1649 return 0;
1650
1651 ret = start_ebml_master_crc32(&dyn_cp, mkv);
1652 if (ret < 0)
1653 return ret;
1654
1655 editionentry = start_ebml_master(dyn_cp, MATROSKA_ID_EDITIONENTRY, 0);
1656 if (mkv->mode != MODE_WEBM) {
1657 put_ebml_uint(dyn_cp, MATROSKA_ID_EDITIONFLAGDEFAULT, 1);
1658 /* If mkv_write_tags() has already been called, then any tags
1659 * corresponding to chapters will be put into a new Tags element. */
1660 tags = mkv->wrote_tags ? &dyn_tags : &mkv->tags.bc;
1661 } else
1662 tags = NULL;
1663
1664 create_new_ids = mkv_new_chapter_ids_needed(s);
1665
1666 for (unsigned i = 0; i < s->nb_chapters; i++) {
1667 ebml_master chapteratom, chapterdisplay;
1668 const AVChapter *c = s->chapters[i];
1669 int64_t chapterstart = av_rescale_q(c->start, c->time_base, scale);
1670 int64_t chapterend = av_rescale_q(c->end, c->time_base, scale);
1671 const AVDictionaryEntry *t;
1672 #if FF_API_CHAPTER_ID_INT
1673 uint64_t uid = create_new_ids ? i + 1ULL : (uint32_t)c->id;
1674 #else
1675 uint64_t uid = create_new_ids ? i + 1ULL : c->id;
1676 #endif
1677 if (chapterstart < 0 || chapterstart > chapterend || chapterend < 0) {
1678 av_log(s, AV_LOG_ERROR,
1679 "Invalid chapter start (%"PRId64") or end (%"PRId64").\n",
1680 chapterstart, chapterend);
1681 ret = AVERROR_INVALIDDATA;
1682 goto fail;
1683 }
1684
1685 chapteratom = start_ebml_master(dyn_cp, MATROSKA_ID_CHAPTERATOM, 0);
1686 put_ebml_uint(dyn_cp, MATROSKA_ID_CHAPTERUID, uid);
1687 put_ebml_uint(dyn_cp, MATROSKA_ID_CHAPTERTIMESTART, chapterstart);
1688 put_ebml_uint(dyn_cp, MATROSKA_ID_CHAPTERTIMEEND, chapterend);
1689 if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
1690 chapterdisplay = start_ebml_master(dyn_cp, MATROSKA_ID_CHAPTERDISPLAY, 0);
1691 put_ebml_string(dyn_cp, MATROSKA_ID_CHAPSTRING, t->value);
1692 put_ebml_string(dyn_cp, MATROSKA_ID_CHAPLANG , "und");
1693 end_ebml_master(dyn_cp, chapterdisplay);
1694 }
1695 end_ebml_master(dyn_cp, chapteratom);
1696
1697 if (tags && mkv_check_tag(c->metadata, MATROSKA_ID_TAGTARGETS_CHAPTERUID)) {
1698 ret = mkv_write_tag(mkv, c->metadata, tags, NULL,
1699 MATROSKA_ID_TAGTARGETS_CHAPTERUID, uid);
1700 if (ret < 0)
1701 goto fail;
1702 }
1703 }
1704 end_ebml_master(dyn_cp, editionentry);
1705 mkv->wrote_chapters = 1;
1706
1707 ret = end_ebml_master_crc32(pb, &dyn_cp, mkv, MATROSKA_ID_CHAPTERS, 0, 0, 1);
1708 if (ret < 0)
1709 goto fail;
1710 if (dyn_tags)
1711 return end_ebml_master_crc32(pb, &dyn_tags, mkv,
1712 MATROSKA_ID_TAGS, 0, 0, 1);
1713 return 0;
1714
1715 fail:
1716 if (tags) {
1717 /* tags == &mkv->tags.bc can only happen if mkv->tags.bc was
1718 * initially NULL, so we never free older tags. */
1719 ffio_free_dyn_buf(tags);
1720 }
1721 ffio_free_dyn_buf(&dyn_cp);
1722 return ret;
1723 }
1724
get_mimetype(const AVStream * st)1725 static const char *get_mimetype(const AVStream *st)
1726 {
1727 const AVDictionaryEntry *t;
1728
1729 if (t = av_dict_get(st->metadata, "mimetype", NULL, 0))
1730 return t->value;
1731 if (st->codecpar->codec_id != AV_CODEC_ID_NONE) {
1732 const AVCodecDescriptor *desc = avcodec_descriptor_get(st->codecpar->codec_id);
1733 if (desc && desc->mime_types) {
1734 return desc->mime_types[0];
1735 } else if (st->codecpar->codec_id == AV_CODEC_ID_TEXT)
1736 return "text/plain";
1737 }
1738
1739 return NULL;
1740 }
1741
mkv_write_attachments(AVFormatContext * s)1742 static int mkv_write_attachments(AVFormatContext *s)
1743 {
1744 MatroskaMuxContext *mkv = s->priv_data;
1745 AVIOContext *dyn_cp = NULL, *pb = s->pb;
1746 int i, ret;
1747
1748 if (!mkv->nb_attachments)
1749 return 0;
1750
1751 ret = start_ebml_master_crc32(&dyn_cp, mkv);
1752 if (ret < 0)
1753 return ret;
1754
1755 for (i = 0; i < s->nb_streams; i++) {
1756 const AVStream *st = s->streams[i];
1757 mkv_track *track = &mkv->tracks[i];
1758 ebml_master attached_file;
1759 const AVDictionaryEntry *t;
1760 const char *mimetype;
1761
1762 if (st->codecpar->codec_type != AVMEDIA_TYPE_ATTACHMENT)
1763 continue;
1764
1765 attached_file = start_ebml_master(dyn_cp, MATROSKA_ID_ATTACHEDFILE, 0);
1766
1767 if (t = av_dict_get(st->metadata, "title", NULL, 0))
1768 put_ebml_string(dyn_cp, MATROSKA_ID_FILEDESC, t->value);
1769 if (!(t = av_dict_get(st->metadata, "filename", NULL, 0))) {
1770 av_log(s, AV_LOG_ERROR, "Attachment stream %d has no filename tag.\n", i);
1771 ffio_free_dyn_buf(&dyn_cp);
1772 return AVERROR(EINVAL);
1773 }
1774 put_ebml_string(dyn_cp, MATROSKA_ID_FILENAME, t->value);
1775
1776 mimetype = get_mimetype(st);
1777 av_assert0(mimetype);
1778 put_ebml_string(dyn_cp, MATROSKA_ID_FILEMIMETYPE, mimetype);
1779 put_ebml_binary(dyn_cp, MATROSKA_ID_FILEDATA, st->codecpar->extradata, st->codecpar->extradata_size);
1780 put_ebml_uid(dyn_cp, MATROSKA_ID_FILEUID, track->uid);
1781 end_ebml_master(dyn_cp, attached_file);
1782 }
1783 return end_ebml_master_crc32(pb, &dyn_cp, mkv,
1784 MATROSKA_ID_ATTACHMENTS, 0, 0, 1);
1785 }
1786
get_metadata_duration(AVFormatContext * s)1787 static int64_t get_metadata_duration(AVFormatContext *s)
1788 {
1789 const AVDictionaryEntry *duration = av_dict_get(s->metadata, "DURATION",
1790 NULL, 0);
1791 int64_t max = 0;
1792 int64_t us;
1793
1794 if (duration && (av_parse_time(&us, duration->value, 1) == 0) && us > 0) {
1795 av_log(s, AV_LOG_DEBUG, "get_metadata_duration found duration in context metadata: %" PRId64 "\n", us);
1796 return us;
1797 }
1798
1799 for (unsigned i = 0; i < s->nb_streams; i++) {
1800 int64_t us;
1801 duration = av_dict_get(s->streams[i]->metadata, "DURATION", NULL, 0);
1802
1803 if (duration && (av_parse_time(&us, duration->value, 1) == 0))
1804 max = FFMAX(max, us);
1805 }
1806
1807 av_log(s, AV_LOG_DEBUG, "get_metadata_duration returned: %" PRId64 "\n", max);
1808 return max;
1809 }
1810
mkv_write_header(AVFormatContext * s)1811 static int mkv_write_header(AVFormatContext *s)
1812 {
1813 MatroskaMuxContext *mkv = s->priv_data;
1814 AVIOContext *pb = s->pb;
1815 ebml_master ebml_header;
1816 const AVDictionaryEntry *tag;
1817 int ret, i, version = 2;
1818 int64_t creation_time;
1819
1820 if (mkv->mode != MODE_WEBM ||
1821 av_dict_get(s->metadata, "stereo_mode", NULL, 0) ||
1822 av_dict_get(s->metadata, "alpha_mode", NULL, 0))
1823 version = 4;
1824
1825 for (i = 0; i < s->nb_streams; i++) {
1826 if (s->streams[i]->codecpar->codec_id == AV_CODEC_ID_OPUS ||
1827 av_dict_get(s->streams[i]->metadata, "stereo_mode", NULL, 0) ||
1828 av_dict_get(s->streams[i]->metadata, "alpha_mode", NULL, 0))
1829 version = 4;
1830 }
1831
1832 ebml_header = start_ebml_master(pb, EBML_ID_HEADER, MAX_EBML_HEADER_SIZE);
1833 put_ebml_uint (pb, EBML_ID_EBMLVERSION , 1);
1834 put_ebml_uint (pb, EBML_ID_EBMLREADVERSION , 1);
1835 put_ebml_uint (pb, EBML_ID_EBMLMAXIDLENGTH , 4);
1836 put_ebml_uint (pb, EBML_ID_EBMLMAXSIZELENGTH , 8);
1837 put_ebml_string(pb, EBML_ID_DOCTYPE , s->oformat->name);
1838 put_ebml_uint (pb, EBML_ID_DOCTYPEVERSION , version);
1839 put_ebml_uint (pb, EBML_ID_DOCTYPEREADVERSION, 2);
1840 end_ebml_master(pb, ebml_header);
1841
1842 put_ebml_id(pb, MATROSKA_ID_SEGMENT);
1843 put_ebml_size_unknown(pb, 8);
1844 mkv->segment_offset = avio_tell(pb);
1845
1846 // We write a SeekHead at the beginning to point to all other level
1847 // one elements (except Clusters).
1848 mkv_start_seekhead(mkv, pb);
1849
1850 ret = start_ebml_master_crc32(&mkv->info.bc, mkv);
1851 if (ret < 0)
1852 return ret;
1853 pb = mkv->info.bc;
1854
1855 put_ebml_uint(pb, MATROSKA_ID_TIMECODESCALE, 1000000);
1856 if ((tag = av_dict_get(s->metadata, "title", NULL, 0)))
1857 put_ebml_string(pb, MATROSKA_ID_TITLE, tag->value);
1858 if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
1859 put_ebml_string(pb, MATROSKA_ID_MUXINGAPP, LIBAVFORMAT_IDENT);
1860 if ((tag = av_dict_get(s->metadata, "encoding_tool", NULL, 0)))
1861 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, tag->value);
1862 else
1863 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, LIBAVFORMAT_IDENT);
1864
1865 if (mkv->mode != MODE_WEBM)
1866 put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, mkv->segment_uid, 16);
1867 } else {
1868 const char *ident = "Lavf";
1869 put_ebml_string(pb, MATROSKA_ID_MUXINGAPP , ident);
1870 put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, ident);
1871 }
1872
1873 if (ff_parse_creation_time_metadata(s, &creation_time, 0) > 0) {
1874 // Adjust time so it's relative to 2001-01-01 and convert to nanoseconds.
1875 int64_t date_utc = (creation_time - 978307200000000LL) * 1000;
1876 uint8_t date_utc_buf[8];
1877 AV_WB64(date_utc_buf, date_utc);
1878 put_ebml_binary(pb, MATROSKA_ID_DATEUTC, date_utc_buf, 8);
1879 }
1880
1881 // reserve space for the duration
1882 mkv->duration = 0;
1883 mkv->duration_offset = avio_tell(pb);
1884 if (!mkv->is_live) {
1885 int64_t metadata_duration = get_metadata_duration(s);
1886
1887 if (s->duration > 0) {
1888 int64_t scaledDuration = av_rescale(s->duration, 1000, AV_TIME_BASE);
1889 put_ebml_float(pb, MATROSKA_ID_DURATION, scaledDuration);
1890 av_log(s, AV_LOG_DEBUG, "Write early duration from recording time = %" PRIu64 "\n", scaledDuration);
1891 } else if (metadata_duration > 0) {
1892 int64_t scaledDuration = av_rescale(metadata_duration, 1000, AV_TIME_BASE);
1893 put_ebml_float(pb, MATROSKA_ID_DURATION, scaledDuration);
1894 av_log(s, AV_LOG_DEBUG, "Write early duration from metadata = %" PRIu64 "\n", scaledDuration);
1895 } else if (s->pb->seekable & AVIO_SEEKABLE_NORMAL) {
1896 put_ebml_void(pb, 11); // assumes double-precision float to be written
1897 }
1898 }
1899 ret = end_ebml_master_crc32_tentatively(s->pb, &mkv->info,
1900 mkv, MATROSKA_ID_INFO);
1901 if (ret < 0)
1902 return ret;
1903 pb = s->pb;
1904
1905 ret = mkv_write_tracks(s);
1906 if (ret < 0)
1907 return ret;
1908
1909 ret = mkv_write_chapters(s);
1910 if (ret < 0)
1911 return ret;
1912
1913 if (mkv->mode != MODE_WEBM) {
1914 ret = mkv_write_attachments(s);
1915 if (ret < 0)
1916 return ret;
1917 }
1918
1919 /* Must come after mkv_write_chapters() to write chapter tags
1920 * into the same Tags element as the other tags. */
1921 ret = mkv_write_tags(s);
1922 if (ret < 0)
1923 return ret;
1924
1925 if (!IS_SEEKABLE(pb, mkv)) {
1926 ret = mkv_write_seekhead(pb, mkv, 0, avio_tell(pb));
1927 if (ret < 0)
1928 return ret;
1929 }
1930
1931 if (s->metadata_header_padding > 0) {
1932 if (s->metadata_header_padding == 1)
1933 s->metadata_header_padding++;
1934 put_ebml_void(pb, s->metadata_header_padding);
1935 }
1936
1937 if (mkv->reserve_cues_space) {
1938 if (IS_SEEKABLE(pb, mkv)) {
1939 mkv->cues_pos = avio_tell(pb);
1940 if (mkv->reserve_cues_space == 1)
1941 mkv->reserve_cues_space++;
1942 put_ebml_void(pb, mkv->reserve_cues_space);
1943 } else
1944 mkv->reserve_cues_space = -1;
1945 }
1946
1947 mkv->cluster_pos = -1;
1948
1949 // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1950 // after 4k and on a keyframe
1951 if (IS_SEEKABLE(pb, mkv)) {
1952 if (mkv->cluster_time_limit < 0)
1953 mkv->cluster_time_limit = 5000;
1954 if (mkv->cluster_size_limit < 0)
1955 mkv->cluster_size_limit = 5 * 1024 * 1024;
1956 } else {
1957 if (mkv->cluster_time_limit < 0)
1958 mkv->cluster_time_limit = 1000;
1959 if (mkv->cluster_size_limit < 0)
1960 mkv->cluster_size_limit = 32 * 1024;
1961 }
1962
1963 return 0;
1964 }
1965
mkv_blockgroup_size(int pkt_size,int track_num_size)1966 static int mkv_blockgroup_size(int pkt_size, int track_num_size)
1967 {
1968 int size = pkt_size + track_num_size + 3;
1969 size += ebml_length_size(size);
1970 size += 2; // EBML ID for block and block duration
1971 size += 9; // max size of block duration incl. length field
1972 return size;
1973 }
1974
mkv_strip_wavpack(const uint8_t * src,uint8_t ** pdst,int * size)1975 static int mkv_strip_wavpack(const uint8_t *src, uint8_t **pdst, int *size)
1976 {
1977 uint8_t *dst;
1978 int srclen = *size;
1979 int offset = 0;
1980 int ret;
1981
1982 dst = av_malloc(srclen);
1983 if (!dst)
1984 return AVERROR(ENOMEM);
1985
1986 while (srclen >= WV_HEADER_SIZE) {
1987 WvHeader header;
1988
1989 ret = ff_wv_parse_header(&header, src);
1990 if (ret < 0)
1991 goto fail;
1992 src += WV_HEADER_SIZE;
1993 srclen -= WV_HEADER_SIZE;
1994
1995 if (srclen < header.blocksize) {
1996 ret = AVERROR_INVALIDDATA;
1997 goto fail;
1998 }
1999
2000 if (header.initial) {
2001 AV_WL32(dst + offset, header.samples);
2002 offset += 4;
2003 }
2004 AV_WL32(dst + offset, header.flags);
2005 AV_WL32(dst + offset + 4, header.crc);
2006 offset += 8;
2007
2008 if (!(header.initial && header.final)) {
2009 AV_WL32(dst + offset, header.blocksize);
2010 offset += 4;
2011 }
2012
2013 memcpy(dst + offset, src, header.blocksize);
2014 src += header.blocksize;
2015 srclen -= header.blocksize;
2016 offset += header.blocksize;
2017 }
2018
2019 *pdst = dst;
2020 *size = offset;
2021
2022 return 0;
2023 fail:
2024 av_freep(&dst);
2025 return ret;
2026 }
2027
mkv_write_block(AVFormatContext * s,AVIOContext * pb,uint32_t blockid,const AVPacket * pkt,int keyframe)2028 static int mkv_write_block(AVFormatContext *s, AVIOContext *pb,
2029 uint32_t blockid, const AVPacket *pkt, int keyframe)
2030 {
2031 MatroskaMuxContext *mkv = s->priv_data;
2032 AVCodecParameters *par = s->streams[pkt->stream_index]->codecpar;
2033 mkv_track *track = &mkv->tracks[pkt->stream_index];
2034 uint8_t *data = NULL, *side_data = NULL;
2035 buffer_size_t side_data_size;
2036 int err = 0, offset = 0, size = pkt->size;
2037 int64_t ts = track->write_dts ? pkt->dts : pkt->pts;
2038 uint64_t additional_id;
2039 int64_t discard_padding = 0;
2040 unsigned track_number = track->track_num;
2041 ebml_master block_group, block_additions, block_more;
2042
2043 ts += track->ts_offset;
2044
2045 /* The following string is identical to the one in mkv_write_vtt_blocks
2046 * so that only one copy needs to exist in binaries. */
2047 av_log(s, AV_LOG_DEBUG,
2048 "Writing block of size %d with pts %" PRId64 ", dts %" PRId64 ", "
2049 "duration %" PRId64 " at relative offset %" PRId64 " in cluster "
2050 "at offset %" PRId64 ". TrackNumber %u, keyframe %d\n",
2051 pkt->size, pkt->pts, pkt->dts, pkt->duration, avio_tell(pb),
2052 mkv->cluster_pos, track_number, keyframe != 0);
2053
2054 if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 0 &&
2055 (AV_RB24(par->extradata) == 1 || AV_RB32(par->extradata) == 1)) {
2056 err = ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
2057 } else if (par->codec_id == AV_CODEC_ID_HEVC && par->extradata_size > 6 &&
2058 (AV_RB24(par->extradata) == 1 || AV_RB32(par->extradata) == 1)) {
2059 /* extradata is Annex B, assume the bitstream is too and convert it */
2060 err = ff_hevc_annexb2mp4_buf(pkt->data, &data, &size, 0, NULL);
2061 } else if (par->codec_id == AV_CODEC_ID_AV1) {
2062 err = ff_av1_filter_obus_buf(pkt->data, &data, &size, &offset);
2063 } else if (par->codec_id == AV_CODEC_ID_WAVPACK) {
2064 err = mkv_strip_wavpack(pkt->data, &data, &size);
2065 } else
2066 data = pkt->data;
2067
2068 if (err < 0) {
2069 av_log(s, AV_LOG_ERROR, "Error when reformatting data of "
2070 "a packet from stream %d.\n", pkt->stream_index);
2071 return err;
2072 }
2073
2074 if (par->codec_id == AV_CODEC_ID_PRORES && size >= 8) {
2075 /* Matroska specification requires to remove the first QuickTime atom
2076 */
2077 size -= 8;
2078 offset = 8;
2079 }
2080
2081 side_data = av_packet_get_side_data(pkt,
2082 AV_PKT_DATA_SKIP_SAMPLES,
2083 &side_data_size);
2084 if (side_data && side_data_size >= 10) {
2085 discard_padding = av_rescale_q(AV_RL32(side_data + 4),
2086 (AVRational){1, par->sample_rate},
2087 (AVRational){1, 1000000000});
2088 }
2089
2090 side_data = av_packet_get_side_data(pkt,
2091 AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,
2092 &side_data_size);
2093 if (side_data) {
2094 // Only the Codec-specific BlockMore (id == 1) is currently supported.
2095 if (side_data_size < 8 || (additional_id = AV_RB64(side_data)) != 1) {
2096 side_data_size = 0;
2097 } else {
2098 side_data += 8;
2099 side_data_size -= 8;
2100 }
2101 }
2102
2103 if (side_data_size || discard_padding) {
2104 block_group = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, 0);
2105 blockid = MATROSKA_ID_BLOCK;
2106 }
2107
2108 put_ebml_id(pb, blockid);
2109 put_ebml_length(pb, size + track->track_num_size + 3, 0);
2110 put_ebml_num(pb, track_number, track->track_num_size);
2111 avio_wb16(pb, ts - mkv->cluster_pts);
2112 avio_w8(pb, (blockid == MATROSKA_ID_SIMPLEBLOCK && keyframe) ? (1 << 7) : 0);
2113 avio_write(pb, data + offset, size);
2114 if (data != pkt->data)
2115 av_free(data);
2116
2117 if (blockid == MATROSKA_ID_BLOCK && !keyframe)
2118 put_ebml_sint(pb, MATROSKA_ID_BLOCKREFERENCE, track->last_timestamp - ts);
2119 track->last_timestamp = ts;
2120
2121 if (discard_padding)
2122 put_ebml_sint(pb, MATROSKA_ID_DISCARDPADDING, discard_padding);
2123
2124 if (side_data_size) {
2125 block_additions = start_ebml_master(pb, MATROSKA_ID_BLOCKADDITIONS, 0);
2126 block_more = start_ebml_master(pb, MATROSKA_ID_BLOCKMORE, 0);
2127 /* Until dbc50f8a our demuxer used a wrong default value
2128 * of BlockAddID, so we write it unconditionally. */
2129 put_ebml_uint (pb, MATROSKA_ID_BLOCKADDID, additional_id);
2130 put_ebml_binary(pb, MATROSKA_ID_BLOCKADDITIONAL,
2131 side_data, side_data_size);
2132 end_ebml_master(pb, block_more);
2133 end_ebml_master(pb, block_additions);
2134 }
2135 if (side_data_size || discard_padding)
2136 end_ebml_master(pb, block_group);
2137
2138 return 0;
2139 }
2140
mkv_write_vtt_blocks(AVFormatContext * s,AVIOContext * pb,const AVPacket * pkt)2141 static int mkv_write_vtt_blocks(AVFormatContext *s, AVIOContext *pb, const AVPacket *pkt)
2142 {
2143 MatroskaMuxContext *mkv = s->priv_data;
2144 mkv_track *track = &mkv->tracks[pkt->stream_index];
2145 ebml_master blockgroup;
2146 buffer_size_t id_size, settings_size;
2147 int size;
2148 const char *id, *settings;
2149 int64_t ts = track->write_dts ? pkt->dts : pkt->pts;
2150 const int flags = 0;
2151
2152 id = av_packet_get_side_data(pkt, AV_PKT_DATA_WEBVTT_IDENTIFIER,
2153 &id_size);
2154 id = id ? id : "";
2155
2156 settings = av_packet_get_side_data(pkt, AV_PKT_DATA_WEBVTT_SETTINGS,
2157 &settings_size);
2158 settings = settings ? settings : "";
2159
2160 size = id_size + 1 + settings_size + 1 + pkt->size;
2161
2162 /* The following string is identical to the one in mkv_write_block so that
2163 * only one copy needs to exist in binaries. */
2164 av_log(s, AV_LOG_DEBUG,
2165 "Writing block of size %d with pts %" PRId64 ", dts %" PRId64 ", "
2166 "duration %" PRId64 " at relative offset %" PRId64 " in cluster "
2167 "at offset %" PRId64 ". TrackNumber %u, keyframe %d\n",
2168 size, pkt->pts, pkt->dts, pkt->duration, avio_tell(pb),
2169 mkv->cluster_pos, track->track_num, 1);
2170
2171 blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
2172 mkv_blockgroup_size(size, track->track_num_size));
2173
2174 put_ebml_id(pb, MATROSKA_ID_BLOCK);
2175 put_ebml_length(pb, size + track->track_num_size + 3, 0);
2176 put_ebml_num(pb, track->track_num, track->track_num_size);
2177 avio_wb16(pb, ts - mkv->cluster_pts);
2178 avio_w8(pb, flags);
2179 avio_printf(pb, "%.*s\n%.*s\n%.*s", id_size, id, settings_size, settings, pkt->size, pkt->data);
2180
2181 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, pkt->duration);
2182 end_ebml_master(pb, blockgroup);
2183
2184 return pkt->duration;
2185 }
2186
mkv_end_cluster(AVFormatContext * s)2187 static int mkv_end_cluster(AVFormatContext *s)
2188 {
2189 MatroskaMuxContext *mkv = s->priv_data;
2190 int ret;
2191
2192 if (!mkv->have_video) {
2193 for (unsigned i = 0; i < s->nb_streams; i++)
2194 mkv->tracks[i].has_cue = 0;
2195 }
2196 mkv->cluster_pos = -1;
2197 ret = end_ebml_master_crc32(s->pb, &mkv->cluster_bc, mkv,
2198 MATROSKA_ID_CLUSTER, 0, 1, 0);
2199 if (ret < 0)
2200 return ret;
2201
2202 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_FLUSH_POINT);
2203 return 0;
2204 }
2205
mkv_check_new_extra_data(AVFormatContext * s,const AVPacket * pkt)2206 static int mkv_check_new_extra_data(AVFormatContext *s, const AVPacket *pkt)
2207 {
2208 MatroskaMuxContext *mkv = s->priv_data;
2209 mkv_track *track = &mkv->tracks[pkt->stream_index];
2210 AVCodecParameters *par = s->streams[pkt->stream_index]->codecpar;
2211 uint8_t *side_data;
2212 buffer_size_t side_data_size;
2213 int ret;
2214
2215 side_data = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
2216 &side_data_size);
2217
2218 switch (par->codec_id) {
2219 case AV_CODEC_ID_AAC:
2220 if (side_data_size && mkv->track.bc) {
2221 int filler, output_sample_rate = 0;
2222 ret = get_aac_sample_rates(s, mkv, side_data, side_data_size,
2223 &track->sample_rate, &output_sample_rate);
2224 if (ret < 0)
2225 return ret;
2226 if (!output_sample_rate)
2227 output_sample_rate = track->sample_rate; // Space is already reserved, so it's this or a void element.
2228 ret = ff_alloc_extradata(par, side_data_size);
2229 if (ret < 0)
2230 return ret;
2231 memcpy(par->extradata, side_data, side_data_size);
2232 avio_seek(mkv->track.bc, track->codecpriv_offset, SEEK_SET);
2233 mkv_write_codecprivate(s, mkv->track.bc, par, 1, 0);
2234 filler = MAX_PCE_SIZE + 2 + 4 - (avio_tell(mkv->track.bc) - track->codecpriv_offset);
2235 if (filler)
2236 put_ebml_void(mkv->track.bc, filler);
2237 avio_seek(mkv->track.bc, track->sample_rate_offset, SEEK_SET);
2238 put_ebml_float(mkv->track.bc, MATROSKA_ID_AUDIOSAMPLINGFREQ, track->sample_rate);
2239 put_ebml_float(mkv->track.bc, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
2240 } else if (!par->extradata_size && !track->sample_rate) {
2241 // No extradata (codecpar or packet side data).
2242 av_log(s, AV_LOG_ERROR, "Error parsing AAC extradata, unable to determine samplerate.\n");
2243 return AVERROR(EINVAL);
2244 }
2245 break;
2246 case AV_CODEC_ID_FLAC:
2247 if (side_data_size && mkv->track.bc) {
2248 uint8_t *old_extradata = par->extradata;
2249 if (side_data_size != par->extradata_size) {
2250 av_log(s, AV_LOG_ERROR, "Invalid FLAC STREAMINFO metadata for output stream %d\n",
2251 pkt->stream_index);
2252 return AVERROR(EINVAL);
2253 }
2254 par->extradata = side_data;
2255 avio_seek(mkv->track.bc, track->codecpriv_offset, SEEK_SET);
2256 mkv_write_codecprivate(s, mkv->track.bc, par, 1, 0);
2257 par->extradata = old_extradata;
2258 }
2259 break;
2260 // FIXME: Remove the following once libaom starts propagating extradata during init()
2261 // See https://bugs.chromium.org/p/aomedia/issues/detail?id=2012
2262 case AV_CODEC_ID_AV1:
2263 if (side_data_size && mkv->track.bc && !par->extradata_size) {
2264 AVIOContext *dyn_cp;
2265 uint8_t *codecpriv;
2266 int codecpriv_size;
2267 ret = avio_open_dyn_buf(&dyn_cp);
2268 if (ret < 0)
2269 return ret;
2270 ff_isom_write_av1c(dyn_cp, side_data, side_data_size);
2271 codecpriv_size = avio_get_dyn_buf(dyn_cp, &codecpriv);
2272 if ((ret = dyn_cp->error) < 0 ||
2273 !codecpriv_size && (ret = AVERROR_INVALIDDATA)) {
2274 ffio_free_dyn_buf(&dyn_cp);
2275 return ret;
2276 }
2277 avio_seek(mkv->track.bc, track->codecpriv_offset, SEEK_SET);
2278 // Do not write the OBUs as we don't have space saved for them
2279 put_ebml_binary(mkv->track.bc, MATROSKA_ID_CODECPRIVATE, codecpriv, 4);
2280 ffio_free_dyn_buf(&dyn_cp);
2281 ret = ff_alloc_extradata(par, side_data_size);
2282 if (ret < 0)
2283 return ret;
2284 memcpy(par->extradata, side_data, side_data_size);
2285 } else if (!par->extradata_size)
2286 return AVERROR_INVALIDDATA;
2287 break;
2288 default:
2289 if (side_data_size)
2290 av_log(s, AV_LOG_DEBUG, "Ignoring new extradata in a packet for stream %d.\n", pkt->stream_index);
2291 break;
2292 }
2293
2294 return 0;
2295 }
2296
mkv_write_packet_internal(AVFormatContext * s,const AVPacket * pkt)2297 static int mkv_write_packet_internal(AVFormatContext *s, const AVPacket *pkt)
2298 {
2299 MatroskaMuxContext *mkv = s->priv_data;
2300 AVIOContext *pb;
2301 AVCodecParameters *par = s->streams[pkt->stream_index]->codecpar;
2302 mkv_track *track = &mkv->tracks[pkt->stream_index];
2303 int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
2304 int duration = pkt->duration;
2305 int ret;
2306 int64_t ts = track->write_dts ? pkt->dts : pkt->pts;
2307 int64_t relative_packet_pos;
2308
2309 if (ts == AV_NOPTS_VALUE) {
2310 av_log(s, AV_LOG_ERROR, "Can't write packet with unknown timestamp\n");
2311 return AVERROR(EINVAL);
2312 }
2313 ts += track->ts_offset;
2314
2315 if (mkv->cluster_pos != -1) {
2316 int64_t cluster_time = ts - mkv->cluster_pts;
2317 if ((int16_t)cluster_time != cluster_time) {
2318 ret = mkv_end_cluster(s);
2319 if (ret < 0)
2320 return ret;
2321 av_log(s, AV_LOG_WARNING, "Starting new cluster due to timestamp\n");
2322 }
2323 }
2324
2325 if (mkv->cluster_pos == -1) {
2326 ret = start_ebml_master_crc32(&mkv->cluster_bc, mkv);
2327 if (ret < 0)
2328 return ret;
2329 mkv->cluster_pos = avio_tell(s->pb);
2330 put_ebml_uint(mkv->cluster_bc, MATROSKA_ID_CLUSTERTIMECODE, FFMAX(0, ts));
2331 mkv->cluster_pts = FFMAX(0, ts);
2332 av_log(s, AV_LOG_DEBUG,
2333 "Starting new cluster with timestamp "
2334 "%" PRId64 " at offset %" PRId64 " bytes\n",
2335 mkv->cluster_pts, mkv->cluster_pos);
2336 }
2337 pb = mkv->cluster_bc;
2338
2339 relative_packet_pos = avio_tell(pb);
2340
2341 if (par->codec_type != AVMEDIA_TYPE_SUBTITLE) {
2342 ret = mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe);
2343 if (ret < 0)
2344 return ret;
2345 if (keyframe && IS_SEEKABLE(s->pb, mkv) &&
2346 (par->codec_type == AVMEDIA_TYPE_VIDEO || !mkv->have_video && !track->has_cue)) {
2347 ret = mkv_add_cuepoint(mkv, pkt->stream_index, ts,
2348 mkv->cluster_pos, relative_packet_pos, -1);
2349 if (ret < 0)
2350 return ret;
2351 track->has_cue = 1;
2352 }
2353 } else {
2354 if (par->codec_id == AV_CODEC_ID_WEBVTT) {
2355 duration = mkv_write_vtt_blocks(s, pb, pkt);
2356 } else {
2357 ebml_master blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
2358 mkv_blockgroup_size(pkt->size,
2359 track->track_num_size));
2360
2361 #if FF_API_CONVERGENCE_DURATION
2362 FF_DISABLE_DEPRECATION_WARNINGS
2363 /* For backward compatibility, prefer convergence_duration. */
2364 if (pkt->convergence_duration > 0) {
2365 duration = pkt->convergence_duration;
2366 }
2367 FF_ENABLE_DEPRECATION_WARNINGS
2368 #endif
2369 /* All subtitle blocks are considered to be keyframes. */
2370 mkv_write_block(s, pb, MATROSKA_ID_BLOCK, pkt, 1);
2371 put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
2372 end_ebml_master(pb, blockgroup);
2373 }
2374
2375 if (IS_SEEKABLE(s->pb, mkv)) {
2376 ret = mkv_add_cuepoint(mkv, pkt->stream_index, ts,
2377 mkv->cluster_pos, relative_packet_pos, duration);
2378 if (ret < 0)
2379 return ret;
2380 }
2381 }
2382
2383 mkv->duration = FFMAX(mkv->duration, ts + duration);
2384 track->duration = FFMAX(track->duration, ts + duration);
2385
2386 return 0;
2387 }
2388
mkv_write_packet(AVFormatContext * s,const AVPacket * pkt)2389 static int mkv_write_packet(AVFormatContext *s, const AVPacket *pkt)
2390 {
2391 MatroskaMuxContext *mkv = s->priv_data;
2392 int codec_type = s->streams[pkt->stream_index]->codecpar->codec_type;
2393 int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
2394 int cluster_size;
2395 int64_t cluster_time;
2396 int ret;
2397 int start_new_cluster;
2398
2399 ret = mkv_check_new_extra_data(s, pkt);
2400 if (ret < 0)
2401 return ret;
2402
2403 if (mkv->cluster_pos != -1) {
2404 if (mkv->tracks[pkt->stream_index].write_dts)
2405 cluster_time = pkt->dts - mkv->cluster_pts;
2406 else
2407 cluster_time = pkt->pts - mkv->cluster_pts;
2408 cluster_time += mkv->tracks[pkt->stream_index].ts_offset;
2409
2410 cluster_size = avio_tell(mkv->cluster_bc);
2411
2412 if (mkv->is_dash && codec_type == AVMEDIA_TYPE_VIDEO) {
2413 // WebM DASH specification states that the first block of
2414 // every Cluster has to be a key frame. So for DASH video,
2415 // we only create a Cluster on seeing key frames.
2416 start_new_cluster = keyframe;
2417 } else if (mkv->is_dash && codec_type == AVMEDIA_TYPE_AUDIO &&
2418 cluster_time > mkv->cluster_time_limit) {
2419 // For DASH audio, we create a Cluster based on cluster_time_limit.
2420 start_new_cluster = 1;
2421 } else if (!mkv->is_dash &&
2422 (cluster_size > mkv->cluster_size_limit ||
2423 cluster_time > mkv->cluster_time_limit ||
2424 (codec_type == AVMEDIA_TYPE_VIDEO && keyframe &&
2425 cluster_size > 4 * 1024))) {
2426 start_new_cluster = 1;
2427 } else
2428 start_new_cluster = 0;
2429
2430 if (start_new_cluster) {
2431 ret = mkv_end_cluster(s);
2432 if (ret < 0)
2433 return ret;
2434 }
2435 }
2436
2437 if (!mkv->cluster_pos)
2438 avio_write_marker(s->pb,
2439 av_rescale_q(pkt->dts, s->streams[pkt->stream_index]->time_base, AV_TIME_BASE_Q),
2440 keyframe && (mkv->have_video ? codec_type == AVMEDIA_TYPE_VIDEO : 1) ? AVIO_DATA_MARKER_SYNC_POINT : AVIO_DATA_MARKER_BOUNDARY_POINT);
2441
2442 // check if we have an audio packet cached
2443 if (mkv->cur_audio_pkt->size > 0) {
2444 ret = mkv_write_packet_internal(s, mkv->cur_audio_pkt);
2445 av_packet_unref(mkv->cur_audio_pkt);
2446 if (ret < 0) {
2447 av_log(s, AV_LOG_ERROR,
2448 "Could not write cached audio packet ret:%d\n", ret);
2449 return ret;
2450 }
2451 }
2452
2453 // buffer an audio packet to ensure the packet containing the video
2454 // keyframe's timecode is contained in the same cluster for WebM
2455 if (codec_type == AVMEDIA_TYPE_AUDIO) {
2456 if (pkt->size > 0)
2457 ret = av_packet_ref(mkv->cur_audio_pkt, pkt);
2458 } else
2459 ret = mkv_write_packet_internal(s, pkt);
2460 return ret;
2461 }
2462
mkv_write_flush_packet(AVFormatContext * s,AVPacket * pkt)2463 static int mkv_write_flush_packet(AVFormatContext *s, AVPacket *pkt)
2464 {
2465 MatroskaMuxContext *mkv = s->priv_data;
2466
2467 if (!pkt) {
2468 if (mkv->cluster_pos != -1) {
2469 int ret = mkv_end_cluster(s);
2470 if (ret < 0)
2471 return ret;
2472 av_log(s, AV_LOG_DEBUG,
2473 "Flushing cluster at offset %" PRIu64 " bytes\n",
2474 avio_tell(s->pb));
2475 }
2476 return 1;
2477 }
2478 return mkv_write_packet(s, pkt);
2479 }
2480
mkv_write_trailer(AVFormatContext * s)2481 static int mkv_write_trailer(AVFormatContext *s)
2482 {
2483 MatroskaMuxContext *mkv = s->priv_data;
2484 AVIOContext *pb = s->pb;
2485 int64_t endpos, ret64;
2486 int ret, ret2 = 0;
2487
2488 // check if we have an audio packet cached
2489 if (mkv->cur_audio_pkt->size > 0) {
2490 ret = mkv_write_packet_internal(s, mkv->cur_audio_pkt);
2491 if (ret < 0) {
2492 av_log(s, AV_LOG_ERROR,
2493 "Could not write cached audio packet ret:%d\n", ret);
2494 return ret;
2495 }
2496 }
2497
2498 if (mkv->cluster_pos != -1) {
2499 ret = end_ebml_master_crc32(pb, &mkv->cluster_bc, mkv,
2500 MATROSKA_ID_CLUSTER, 0, 0, 0);
2501 if (ret < 0)
2502 return ret;
2503 }
2504
2505 ret = mkv_write_chapters(s);
2506 if (ret < 0)
2507 return ret;
2508
2509 if (!IS_SEEKABLE(pb, mkv))
2510 return 0;
2511
2512 endpos = avio_tell(pb);
2513
2514 if (mkv->cues.num_entries && mkv->reserve_cues_space >= 0) {
2515 AVIOContext *cues = NULL;
2516 uint64_t size;
2517 int length_size = 0;
2518
2519 ret = start_ebml_master_crc32(&cues, mkv);
2520 if (ret < 0)
2521 return ret;
2522
2523 ret = mkv_assemble_cues(s->streams, cues, &mkv->cues,
2524 mkv->tracks, s->nb_streams);
2525 if (ret < 0) {
2526 ffio_free_dyn_buf(&cues);
2527 return ret;
2528 }
2529
2530 if (mkv->reserve_cues_space) {
2531 size = avio_tell(cues);
2532 length_size = ebml_length_size(size);
2533 size += 4 + length_size;
2534 if (mkv->reserve_cues_space < size) {
2535 av_log(s, AV_LOG_WARNING,
2536 "Insufficient space reserved for Cues: "
2537 "%d < %"PRIu64". No Cues will be output.\n",
2538 mkv->reserve_cues_space, size);
2539 ret2 = AVERROR(EINVAL);
2540 goto after_cues;
2541 } else {
2542 if ((ret64 = avio_seek(pb, mkv->cues_pos, SEEK_SET)) < 0) {
2543 ffio_free_dyn_buf(&cues);
2544 return ret64;
2545 }
2546 if (mkv->reserve_cues_space == size + 1) {
2547 /* There is no way to reserve a single byte because
2548 * the minimal size of an EBML Void element is 2
2549 * (1 byte ID, 1 byte length field). This problem
2550 * is solved by writing the Cues' length field on
2551 * one byte more than necessary. */
2552 length_size++;
2553 size++;
2554 }
2555 }
2556 }
2557 ret = end_ebml_master_crc32(pb, &cues, mkv, MATROSKA_ID_CUES,
2558 length_size, 0, 1);
2559 if (ret < 0)
2560 return ret;
2561 if (mkv->reserve_cues_space) {
2562 if (size < mkv->reserve_cues_space)
2563 put_ebml_void(pb, mkv->reserve_cues_space - size);
2564 } else
2565 endpos = avio_tell(pb);
2566 }
2567
2568 after_cues:
2569 /* Lengths greater than (1ULL << 56) - 1 can't be represented
2570 * via an EBML number, so leave the unknown length field. */
2571 if (endpos - mkv->segment_offset < (1ULL << 56) - 1) {
2572 if ((ret64 = avio_seek(pb, mkv->segment_offset - 8, SEEK_SET)) < 0)
2573 return ret64;
2574 put_ebml_length(pb, endpos - mkv->segment_offset, 8);
2575 }
2576
2577 ret = mkv_write_seekhead(pb, mkv, 1, mkv->info.pos);
2578 if (ret < 0)
2579 return ret;
2580
2581 if (mkv->info.bc) {
2582 // update the duration
2583 av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
2584 avio_seek(mkv->info.bc, mkv->duration_offset, SEEK_SET);
2585 put_ebml_float(mkv->info.bc, MATROSKA_ID_DURATION, mkv->duration);
2586 ret = end_ebml_master_crc32(pb, &mkv->info.bc, mkv,
2587 MATROSKA_ID_INFO, 0, 0, 0);
2588 if (ret < 0)
2589 return ret;
2590 }
2591
2592 if (mkv->track.bc) {
2593 // write Tracks master
2594 avio_seek(pb, mkv->track.pos, SEEK_SET);
2595 ret = end_ebml_master_crc32(pb, &mkv->track.bc, mkv,
2596 MATROSKA_ID_TRACKS, 0, 0, 0);
2597 if (ret < 0)
2598 return ret;
2599 }
2600
2601 // update stream durations
2602 if (mkv->tags.bc) {
2603 int i;
2604 for (i = 0; i < s->nb_streams; ++i) {
2605 const AVStream *st = s->streams[i];
2606 const mkv_track *track = &mkv->tracks[i];
2607
2608 if (track->duration_offset > 0) {
2609 double duration_sec = track->duration * av_q2d(st->time_base);
2610 char duration_string[20] = "";
2611
2612 av_log(s, AV_LOG_DEBUG, "stream %d end duration = %" PRIu64 "\n", i,
2613 track->duration);
2614
2615 avio_seek(mkv->tags.bc, track->duration_offset, SEEK_SET);
2616
2617 snprintf(duration_string, 20, "%02d:%02d:%012.9f",
2618 (int) duration_sec / 3600, ((int) duration_sec / 60) % 60,
2619 fmod(duration_sec, 60));
2620
2621 put_ebml_binary(mkv->tags.bc, MATROSKA_ID_TAGSTRING, duration_string, 20);
2622 }
2623 }
2624
2625 avio_seek(pb, mkv->tags.pos, SEEK_SET);
2626 ret = end_ebml_master_crc32(pb, &mkv->tags.bc, mkv,
2627 MATROSKA_ID_TAGS, 0, 0, 0);
2628 if (ret < 0)
2629 return ret;
2630 }
2631
2632 avio_seek(pb, endpos, SEEK_SET);
2633
2634 return ret2;
2635 }
2636
mkv_query_codec(enum AVCodecID codec_id,int std_compliance)2637 static int mkv_query_codec(enum AVCodecID codec_id, int std_compliance)
2638 {
2639 int i;
2640 for (i = 0; ff_mkv_codec_tags[i].id != AV_CODEC_ID_NONE; i++)
2641 if (ff_mkv_codec_tags[i].id == codec_id)
2642 return 1;
2643
2644 if (std_compliance < FF_COMPLIANCE_NORMAL) {
2645 enum AVMediaType type = avcodec_get_type(codec_id);
2646 // mkv theoretically supports any video/audio through VFW/ACM
2647 if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO)
2648 return 1;
2649 }
2650
2651 return 0;
2652 }
2653
webm_query_codec(enum AVCodecID codec_id,int std_compliance)2654 static int webm_query_codec(enum AVCodecID codec_id, int std_compliance)
2655 {
2656 int i;
2657 for (i = 0; ff_webm_codec_tags[i].id != AV_CODEC_ID_NONE; i++)
2658 if (ff_webm_codec_tags[i].id == codec_id)
2659 return 1;
2660
2661 return 0;
2662 }
2663
mkv_get_uid(const mkv_track * tracks,int i,AVLFG * c)2664 static uint64_t mkv_get_uid(const mkv_track *tracks, int i, AVLFG *c)
2665 {
2666 while (1) {
2667 uint64_t uid;
2668 int k;
2669 uid = (uint64_t)av_lfg_get(c) << 32;
2670 uid |= av_lfg_get(c);
2671 if (!uid)
2672 continue;
2673 for (k = 0; k < i; k++) {
2674 if (tracks[k].uid == uid)
2675 break;
2676 }
2677 if (k == i)
2678 return uid;
2679 }
2680 }
2681
mkv_init(struct AVFormatContext * s)2682 static int mkv_init(struct AVFormatContext *s)
2683 {
2684 MatroskaMuxContext *mkv = s->priv_data;
2685 AVLFG c;
2686 unsigned nb_tracks = 0;
2687 int i;
2688
2689 for (i = 0; i < s->nb_streams; i++) {
2690 if (s->streams[i]->codecpar->codec_id == AV_CODEC_ID_ATRAC3 ||
2691 s->streams[i]->codecpar->codec_id == AV_CODEC_ID_COOK ||
2692 s->streams[i]->codecpar->codec_id == AV_CODEC_ID_RA_288 ||
2693 s->streams[i]->codecpar->codec_id == AV_CODEC_ID_SIPR ||
2694 s->streams[i]->codecpar->codec_id == AV_CODEC_ID_RV10 ||
2695 s->streams[i]->codecpar->codec_id == AV_CODEC_ID_RV20) {
2696 av_log(s, AV_LOG_ERROR,
2697 "The Matroska muxer does not yet support muxing %s\n",
2698 avcodec_get_name(s->streams[i]->codecpar->codec_id));
2699 return AVERROR_PATCHWELCOME;
2700 }
2701 }
2702
2703 if (s->avoid_negative_ts < 0) {
2704 s->avoid_negative_ts = 1;
2705 s->internal->avoid_negative_ts_use_pts = 1;
2706 }
2707
2708 if (!strcmp(s->oformat->name, "webm")) {
2709 mkv->mode = MODE_WEBM;
2710 mkv->write_crc = 0;
2711 } else
2712 mkv->mode = MODE_MATROSKAv2;
2713
2714 mkv->cur_audio_pkt = av_packet_alloc();
2715 if (!mkv->cur_audio_pkt)
2716 return AVERROR(ENOMEM);
2717 mkv->tracks = av_mallocz_array(s->nb_streams, sizeof(*mkv->tracks));
2718 if (!mkv->tracks)
2719 return AVERROR(ENOMEM);
2720
2721 if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
2722 av_lfg_init(&c, av_get_random_seed());
2723
2724 // Calculate the SegmentUID now in order not to waste our random seed.
2725 for (i = 0; i < 4; i++)
2726 mkv->segment_uid[i] = av_lfg_get(&c);
2727 }
2728
2729 for (i = 0; i < s->nb_streams; i++) {
2730 AVStream *st = s->streams[i];
2731 mkv_track *track = &mkv->tracks[i];
2732
2733 if (s->flags & AVFMT_FLAG_BITEXACT) {
2734 track->uid = i + 1;
2735 } else {
2736 track->uid = mkv_get_uid(mkv->tracks, i, &c);
2737 }
2738
2739 // ms precision is the de-facto standard timescale for mkv files
2740 avpriv_set_pts_info(st, 64, 1, 1000);
2741
2742 if (st->codecpar->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
2743 if (mkv->mode == MODE_WEBM) {
2744 av_log(s, AV_LOG_WARNING, "Stream %d will be ignored "
2745 "as WebM doesn't support attachments.\n", i);
2746 } else if (!get_mimetype(st)) {
2747 av_log(s, AV_LOG_ERROR, "Attachment stream %d has no mimetype "
2748 "tag and it cannot be deduced from the codec id.\n", i);
2749 return AVERROR(EINVAL);
2750 }
2751 mkv->nb_attachments++;
2752 continue;
2753 }
2754
2755 nb_tracks++;
2756 track->track_num = mkv->is_dash ? mkv->dash_track_number : nb_tracks;
2757 track->track_num_size = ebml_num_size(track->track_num);
2758 }
2759
2760 if (mkv->is_dash && nb_tracks != 1)
2761 return AVERROR(EINVAL);
2762
2763 return 0;
2764 }
2765
mkv_check_bitstream(struct AVFormatContext * s,const AVPacket * pkt)2766 static int mkv_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
2767 {
2768 int ret = 1;
2769 AVStream *st = s->streams[pkt->stream_index];
2770
2771 if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
2772 if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
2773 ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
2774 } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) {
2775 ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL);
2776 }
2777
2778 return ret;
2779 }
2780
2781 static const AVCodecTag additional_audio_tags[] = {
2782 { AV_CODEC_ID_ALAC, 0XFFFFFFFF },
2783 { AV_CODEC_ID_MLP, 0xFFFFFFFF },
2784 { AV_CODEC_ID_OPUS, 0xFFFFFFFF },
2785 { AV_CODEC_ID_PCM_S16BE, 0xFFFFFFFF },
2786 { AV_CODEC_ID_PCM_S24BE, 0xFFFFFFFF },
2787 { AV_CODEC_ID_PCM_S32BE, 0xFFFFFFFF },
2788 { AV_CODEC_ID_QDMC, 0xFFFFFFFF },
2789 { AV_CODEC_ID_QDM2, 0xFFFFFFFF },
2790 { AV_CODEC_ID_RA_144, 0xFFFFFFFF },
2791 { AV_CODEC_ID_RA_288, 0xFFFFFFFF },
2792 { AV_CODEC_ID_COOK, 0xFFFFFFFF },
2793 { AV_CODEC_ID_TRUEHD, 0xFFFFFFFF },
2794 { AV_CODEC_ID_NONE, 0xFFFFFFFF }
2795 };
2796
2797 static const AVCodecTag additional_video_tags[] = {
2798 { AV_CODEC_ID_RV10, 0xFFFFFFFF },
2799 { AV_CODEC_ID_RV20, 0xFFFFFFFF },
2800 { AV_CODEC_ID_RV30, 0xFFFFFFFF },
2801 { AV_CODEC_ID_NONE, 0xFFFFFFFF }
2802 };
2803
2804 static const AVCodecTag additional_subtitle_tags[] = {
2805 { AV_CODEC_ID_DVB_SUBTITLE, 0xFFFFFFFF },
2806 { AV_CODEC_ID_DVD_SUBTITLE, 0xFFFFFFFF },
2807 { AV_CODEC_ID_HDMV_PGS_SUBTITLE, 0xFFFFFFFF },
2808 { AV_CODEC_ID_NONE, 0xFFFFFFFF }
2809 };
2810
2811 #define OFFSET(x) offsetof(MatroskaMuxContext, x)
2812 #define FLAGS AV_OPT_FLAG_ENCODING_PARAM
2813 static const AVOption options[] = {
2814 { "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 },
2815 { "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 },
2816 { "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 },
2817 { "dash", "Create a WebM file conforming to WebM DASH specification", OFFSET(is_dash), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
2818 { "dash_track_number", "Track number for the DASH stream", OFFSET(dash_track_number), AV_OPT_TYPE_INT, { .i64 = 1 }, 1, INT_MAX, FLAGS },
2819 { "live", "Write files assuming it is a live stream.", OFFSET(is_live), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
2820 { "allow_raw_vfw", "allow RAW VFW mode", OFFSET(allow_raw_vfw), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
2821 { "flipped_raw_rgb", "Raw RGB bitmaps in VFW mode are stored bottom-up", OFFSET(flipped_raw_rgb), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
2822 { "write_crc32", "write a CRC32 element inside every Level 1 element", OFFSET(write_crc), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, FLAGS },
2823 { "default_mode", "Controls how a track's FlagDefault is inferred", OFFSET(default_mode), AV_OPT_TYPE_INT, { .i64 = DEFAULT_MODE_INFER }, DEFAULT_MODE_INFER, DEFAULT_MODE_PASSTHROUGH, FLAGS, "default_mode" },
2824 { "infer", "For each track type, mark the first track of disposition default as default; if none exists, mark the first track as default.", 0, AV_OPT_TYPE_CONST, { .i64 = DEFAULT_MODE_INFER }, 0, 0, FLAGS, "default_mode" },
2825 { "infer_no_subs", "For each track type, mark the first track of disposition default as default; for audio and video: if none exists, mark the first track as default.", 0, AV_OPT_TYPE_CONST, { .i64 = DEFAULT_MODE_INFER_NO_SUBS }, 0, 0, FLAGS, "default_mode" },
2826 { "passthrough", "Use the disposition flag as-is", 0, AV_OPT_TYPE_CONST, { .i64 = DEFAULT_MODE_PASSTHROUGH }, 0, 0, FLAGS, "default_mode" },
2827 { NULL },
2828 };
2829
2830 #if CONFIG_MATROSKA_MUXER
2831 static const AVClass matroska_class = {
2832 .class_name = "matroska muxer",
2833 .item_name = av_default_item_name,
2834 .option = options,
2835 .version = LIBAVUTIL_VERSION_INT,
2836 };
2837
2838 AVOutputFormat ff_matroska_muxer = {
2839 .name = "matroska",
2840 .long_name = NULL_IF_CONFIG_SMALL("Matroska"),
2841 .mime_type = "video/x-matroska",
2842 .extensions = "mkv",
2843 .priv_data_size = sizeof(MatroskaMuxContext),
2844 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
2845 AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
2846 .video_codec = CONFIG_LIBX264_ENCODER ?
2847 AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
2848 .init = mkv_init,
2849 .deinit = mkv_deinit,
2850 .write_header = mkv_write_header,
2851 .write_packet = mkv_write_flush_packet,
2852 .write_trailer = mkv_write_trailer,
2853 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
2854 AVFMT_TS_NONSTRICT | AVFMT_ALLOW_FLUSH,
2855 .codec_tag = (const AVCodecTag* const []){
2856 ff_codec_bmp_tags, ff_codec_wav_tags,
2857 additional_audio_tags, additional_video_tags, additional_subtitle_tags, 0
2858 },
2859 .subtitle_codec = AV_CODEC_ID_ASS,
2860 .query_codec = mkv_query_codec,
2861 .check_bitstream = mkv_check_bitstream,
2862 .priv_class = &matroska_class,
2863 };
2864 #endif
2865
2866 #if CONFIG_WEBM_MUXER
2867 static const AVClass webm_class = {
2868 .class_name = "webm muxer",
2869 .item_name = av_default_item_name,
2870 .option = options,
2871 .version = LIBAVUTIL_VERSION_INT,
2872 };
2873
2874 AVOutputFormat ff_webm_muxer = {
2875 .name = "webm",
2876 .long_name = NULL_IF_CONFIG_SMALL("WebM"),
2877 .mime_type = "video/webm",
2878 .extensions = "webm",
2879 .priv_data_size = sizeof(MatroskaMuxContext),
2880 .audio_codec = CONFIG_LIBOPUS_ENCODER ? AV_CODEC_ID_OPUS : AV_CODEC_ID_VORBIS,
2881 .video_codec = CONFIG_LIBVPX_VP9_ENCODER? AV_CODEC_ID_VP9 : AV_CODEC_ID_VP8,
2882 .subtitle_codec = AV_CODEC_ID_WEBVTT,
2883 .init = mkv_init,
2884 .deinit = mkv_deinit,
2885 .write_header = mkv_write_header,
2886 .write_packet = mkv_write_flush_packet,
2887 .write_trailer = mkv_write_trailer,
2888 .query_codec = webm_query_codec,
2889 .check_bitstream = mkv_check_bitstream,
2890 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
2891 AVFMT_TS_NONSTRICT | AVFMT_ALLOW_FLUSH,
2892 .priv_class = &webm_class,
2893 };
2894 #endif
2895
2896 #if CONFIG_MATROSKA_AUDIO_MUXER
2897 static const AVClass mka_class = {
2898 .class_name = "matroska audio muxer",
2899 .item_name = av_default_item_name,
2900 .option = options,
2901 .version = LIBAVUTIL_VERSION_INT,
2902 };
2903 AVOutputFormat ff_matroska_audio_muxer = {
2904 .name = "matroska",
2905 .long_name = NULL_IF_CONFIG_SMALL("Matroska Audio"),
2906 .mime_type = "audio/x-matroska",
2907 .extensions = "mka",
2908 .priv_data_size = sizeof(MatroskaMuxContext),
2909 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
2910 AV_CODEC_ID_VORBIS : AV_CODEC_ID_AC3,
2911 .video_codec = AV_CODEC_ID_NONE,
2912 .init = mkv_init,
2913 .deinit = mkv_deinit,
2914 .write_header = mkv_write_header,
2915 .write_packet = mkv_write_flush_packet,
2916 .write_trailer = mkv_write_trailer,
2917 .check_bitstream = mkv_check_bitstream,
2918 .flags = AVFMT_GLOBALHEADER | AVFMT_TS_NONSTRICT |
2919 AVFMT_ALLOW_FLUSH,
2920 .codec_tag = (const AVCodecTag* const []){
2921 ff_codec_wav_tags, additional_audio_tags, 0
2922 },
2923 .priv_class = &mka_class,
2924 };
2925 #endif
2926