forked from FFmpeg/FFmpeg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatroskaenc.c
2914 lines (2521 loc) · 105 KB
/
matroskaenc.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Matroska muxer
* Copyright (c) 2007 David Conrad
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdint.h>
#include "av1.h"
#include "avc.h"
#include "hevc.h"
#include "avformat.h"
#include "avio_internal.h"
#include "avlanguage.h"
#include "flacenc.h"
#include "internal.h"
#include "isom.h"
#include "matroska.h"
#include "riff.h"
#include "vorbiscomment.h"
#include "wv.h"
#include "libavutil/avstring.h"
#include "libavutil/channel_layout.h"
#include "libavutil/crc.h"
#include "libavutil/dict.h"
#include "libavutil/intfloat.h"
#include "libavutil/intreadwrite.h"
#include "libavutil/lfg.h"
#include "libavutil/mastering_display_metadata.h"
#include "libavutil/mathematics.h"
#include "libavutil/opt.h"
#include "libavutil/parseutils.h"
#include "libavutil/random_seed.h"
#include "libavutil/rational.h"
#include "libavutil/samplefmt.h"
#include "libavutil/stereo3d.h"
#include "libavcodec/xiph.h"
#include "libavcodec/mpeg4audio.h"
/* Level 1 elements we create a SeekHead entry for:
* Info, Tracks, Chapters, Attachments, Tags (potentially twice) and Cues */
#define MAX_SEEKHEAD_ENTRIES 7
#define IS_SEEKABLE(pb, mkv) (((pb)->seekable & AVIO_SEEKABLE_NORMAL) && \
!(mkv)->is_live)
enum {
DEFAULT_MODE_INFER,
DEFAULT_MODE_INFER_NO_SUBS,
DEFAULT_MODE_PASSTHROUGH,
};
typedef struct ebml_master {
int64_t pos; ///< absolute offset in the containing AVIOContext where the master's elements start
int sizebytes; ///< how many bytes were reserved for the size
} ebml_master;
typedef struct ebml_stored_master {
AVIOContext *bc;
int64_t pos;
} ebml_stored_master;
typedef struct mkv_seekhead_entry {
uint32_t elementid;
uint64_t segmentpos;
} mkv_seekhead_entry;
typedef struct mkv_seekhead {
int64_t filepos;
mkv_seekhead_entry entries[MAX_SEEKHEAD_ENTRIES];
int num_entries;
int reserved_size;
} mkv_seekhead;
typedef struct mkv_cuepoint {
uint64_t pts;
int stream_idx;
int64_t cluster_pos; ///< offset of the cluster containing the block relative to the segment
int64_t relative_pos; ///< relative offset from the position of the cluster containing the block
int64_t duration; ///< duration of the block according to time base
} mkv_cuepoint;
typedef struct mkv_cues {
mkv_cuepoint *entries;
int num_entries;
} mkv_cues;
typedef struct mkv_track {
int write_dts;
int has_cue;
uint64_t uid;
unsigned track_num;
int track_num_size;
int sample_rate;
int64_t sample_rate_offset;
int64_t last_timestamp;
int64_t duration;
int64_t duration_offset;
int64_t codecpriv_offset;
int64_t ts_offset;
} mkv_track;
#define MODE_MATROSKAv2 0x01
#define MODE_WEBM 0x02
typedef struct MatroskaMuxContext {
const AVClass *class;
int mode;
ebml_stored_master info;
ebml_stored_master track;
ebml_stored_master tags;
int64_t segment_offset;
AVIOContext *cluster_bc;
int64_t cluster_pos; ///< file offset of the current Cluster
int64_t cluster_pts;
int64_t duration_offset;
int64_t duration;
mkv_track *tracks;
mkv_seekhead seekhead;
mkv_cues cues;
int64_t cues_pos;
AVPacket *cur_audio_pkt;
unsigned nb_attachments;
int have_video;
int wrote_chapters;
int wrote_tags;
int reserve_cues_space;
int cluster_size_limit;
int64_t cluster_time_limit;
int write_crc;
int is_live;
int is_dash;
int dash_track_number;
int allow_raw_vfw;
int flipped_raw_rgb;
int default_mode;
uint32_t segment_uid[4];
} MatroskaMuxContext;
/** 2 bytes * 7 for EBML IDs, 7 1-byte EBML lengths, 6 1-byte uint,
* 8 byte for "matroska" doctype string */
#define MAX_EBML_HEADER_SIZE 35
/** 2 bytes * 3 for EBML IDs, 3 1-byte EBML lengths, 8 bytes for 64 bit
* offset, 4 bytes for target EBML ID */
#define MAX_SEEKENTRY_SIZE 21
/** 4 * (1-byte EBML ID, 1-byte EBML size, 8-byte uint max) */
#define MAX_CUETRACKPOS_SIZE 40
/** Seek preroll value for opus */
#define OPUS_SEEK_PREROLL 80000000
static int ebml_id_size(uint32_t id)
{
return (av_log2(id) + 7U) / 8;
}
static void put_ebml_id(AVIOContext *pb, uint32_t id)
{
int i = ebml_id_size(id);
while (i--)
avio_w8(pb, (uint8_t)(id >> (i * 8)));
}
/**
* Write an EBML size meaning "unknown size".
*
* @param bytes The number of bytes the size should occupy (maximum: 8).
*/
static void put_ebml_size_unknown(AVIOContext *pb, int bytes)
{
av_assert0(bytes <= 8);
avio_w8(pb, 0x1ff >> bytes);
if (av_builtin_constant_p(bytes) && bytes == 1)
return;
ffio_fill(pb, 0xff, bytes - 1);
}
/**
* Returns how many bytes are needed to represent a number
* as EBML variable length integer.
*/
static int ebml_num_size(uint64_t num)
{
int bytes = 0;
do {
bytes++;
} while (num >>= 7);
return bytes;
}
/**
* Calculate how many bytes are needed to represent the length field
* of an EBML element whose payload has a given length.
*/
static int ebml_length_size(uint64_t length)
{
return ebml_num_size(length + 1);
}
/**
* Write a number as EBML variable length integer on `bytes` bytes.
* `bytes` is taken literally without checking.
*/
static void put_ebml_num(AVIOContext *pb, uint64_t num, int bytes)
{
num |= 1ULL << bytes * 7;
for (int i = bytes - 1; i >= 0; i--)
avio_w8(pb, (uint8_t)(num >> i * 8));
}
/**
* Write a length as EBML variable length integer.
*
* @param bytes The number of bytes that need to be used to write the number.
* If zero, the minimal number of bytes will be used.
*/
static void put_ebml_length(AVIOContext *pb, uint64_t length, int bytes)
{
int needed_bytes = ebml_length_size(length);
// sizes larger than this are currently undefined in EBML
av_assert0(length < (1ULL << 56) - 1);
if (bytes == 0)
bytes = needed_bytes;
// The bytes needed to write the given size must not exceed
// the bytes that we ought to use.
av_assert0(bytes >= needed_bytes);
put_ebml_num(pb, length, bytes);
}
/**
* Write a (random) UID with fixed size to make the output more deterministic
*/
static void put_ebml_uid(AVIOContext *pb, uint32_t elementid, uint64_t uid)
{
put_ebml_id(pb, elementid);
put_ebml_length(pb, 8, 0);
avio_wb64(pb, uid);
}
static void put_ebml_uint(AVIOContext *pb, uint32_t elementid, uint64_t val)
{
int i, bytes = 1;
uint64_t tmp = val;
while (tmp >>= 8)
bytes++;
put_ebml_id(pb, elementid);
put_ebml_length(pb, bytes, 0);
for (i = bytes - 1; i >= 0; i--)
avio_w8(pb, (uint8_t)(val >> i * 8));
}
static void put_ebml_sint(AVIOContext *pb, uint32_t elementid, int64_t val)
{
int i, bytes = 1;
uint64_t tmp = 2*(val < 0 ? val^-1 : val);
while (tmp >>= 8)
bytes++;
put_ebml_id(pb, elementid);
put_ebml_length(pb, bytes, 0);
for (i = bytes - 1; i >= 0; i--)
avio_w8(pb, (uint8_t)(val >> i * 8));
}
static void put_ebml_float(AVIOContext *pb, uint32_t elementid, double val)
{
put_ebml_id(pb, elementid);
put_ebml_length(pb, 8, 0);
avio_wb64(pb, av_double2int(val));
}
static void put_ebml_binary(AVIOContext *pb, uint32_t elementid,
const void *buf, int size)
{
put_ebml_id(pb, elementid);
put_ebml_length(pb, size, 0);
avio_write(pb, buf, size);
}
static void put_ebml_string(AVIOContext *pb, uint32_t elementid,
const char *str)
{
put_ebml_binary(pb, elementid, str, strlen(str));
}
/**
* Write a void element of a given size. Useful for reserving space in
* the file to be written to later.
*
* @param size The number of bytes to reserve, which must be at least 2.
*/
static void put_ebml_void(AVIOContext *pb, int size)
{
av_assert0(size >= 2);
put_ebml_id(pb, EBML_ID_VOID);
// we need to subtract the length needed to store the size from the
// size we need to reserve so 2 cases, we use 8 bytes to store the
// size if possible, 1 byte otherwise
if (size < 10) {
size -= 2;
put_ebml_length(pb, size, 0);
} else {
size -= 9;
put_ebml_length(pb, size, 8);
}
ffio_fill(pb, 0, size);
}
static ebml_master start_ebml_master(AVIOContext *pb, uint32_t elementid,
uint64_t expectedsize)
{
int bytes = expectedsize ? ebml_length_size(expectedsize) : 8;
put_ebml_id(pb, elementid);
put_ebml_size_unknown(pb, bytes);
return (ebml_master) { avio_tell(pb), bytes };
}
static void end_ebml_master(AVIOContext *pb, ebml_master master)
{
int64_t pos = avio_tell(pb);
if (avio_seek(pb, master.pos - master.sizebytes, SEEK_SET) < 0)
return;
put_ebml_length(pb, pos - master.pos, master.sizebytes);
avio_seek(pb, pos, SEEK_SET);
}
static void mkv_add_seekhead_entry(MatroskaMuxContext *mkv, uint32_t elementid,
uint64_t filepos)
{
mkv_seekhead *seekhead = &mkv->seekhead;
av_assert1(seekhead->num_entries < MAX_SEEKHEAD_ENTRIES);
seekhead->entries[seekhead->num_entries].elementid = elementid;
seekhead->entries[seekhead->num_entries++].segmentpos = filepos - mkv->segment_offset;
}
static int start_ebml_master_crc32(AVIOContext **dyn_cp, MatroskaMuxContext *mkv)
{
int ret;
if (!*dyn_cp && (ret = avio_open_dyn_buf(dyn_cp)) < 0)
return ret;
if (mkv->write_crc)
put_ebml_void(*dyn_cp, 6); /* Reserve space for CRC32 so position/size calculations using avio_tell() take it into account */
return 0;
}
static int end_ebml_master_crc32(AVIOContext *pb, AVIOContext **dyn_cp,
MatroskaMuxContext *mkv, uint32_t id,
int length_size, int keep_buffer,
int add_seekentry)
{
uint8_t *buf, crc[4];
int ret, size, skip = 0;
size = avio_get_dyn_buf(*dyn_cp, &buf);
if ((ret = (*dyn_cp)->error) < 0)
goto fail;
if (add_seekentry)
mkv_add_seekhead_entry(mkv, id, avio_tell(pb));
put_ebml_id(pb, id);
put_ebml_length(pb, size, length_size);
if (mkv->write_crc) {
skip = 6; /* Skip reserved 6-byte long void element from the dynamic buffer. */
AV_WL32(crc, av_crc(av_crc_get_table(AV_CRC_32_IEEE_LE), UINT32_MAX, buf + skip, size - skip) ^ UINT32_MAX);
put_ebml_binary(pb, EBML_ID_CRC32, crc, sizeof(crc));
}
avio_write(pb, buf + skip, size - skip);
fail:
if (keep_buffer) {
ffio_reset_dyn_buf(*dyn_cp);
} else {
ffio_free_dyn_buf(dyn_cp);
}
return ret;
}
/**
* Output EBML master. Keep the buffer if seekable, allowing for later updates.
* Furthermore always add a SeekHead Entry for this element.
*/
static int end_ebml_master_crc32_tentatively(AVIOContext *pb,
ebml_stored_master *elem,
MatroskaMuxContext *mkv, uint32_t id)
{
if (IS_SEEKABLE(pb, mkv)) {
uint8_t *buf;
int size = avio_get_dyn_buf(elem->bc, &buf);
if (elem->bc->error < 0)
return elem->bc->error;
elem->pos = avio_tell(pb);
mkv_add_seekhead_entry(mkv, id, elem->pos);
put_ebml_id(pb, id);
put_ebml_length(pb, size, 0);
avio_write(pb, buf, size);
return 0;
} else
return end_ebml_master_crc32(pb, &elem->bc, mkv, id, 0, 0, 1);
}
static void put_xiph_size(AVIOContext *pb, int size)
{
ffio_fill(pb, 255, size / 255);
avio_w8(pb, size % 255);
}
/**
* Free the members allocated in the mux context.
*/
static void mkv_deinit(AVFormatContext *s)
{
MatroskaMuxContext *mkv = s->priv_data;
ffio_free_dyn_buf(&mkv->cluster_bc);
ffio_free_dyn_buf(&mkv->info.bc);
ffio_free_dyn_buf(&mkv->track.bc);
ffio_free_dyn_buf(&mkv->tags.bc);
av_freep(&mkv->cues.entries);
av_freep(&mkv->tracks);
}
/**
* Initialize the SeekHead element to be ready to index level 1 Matroska
* elements. Enough space to write MAX_SEEKHEAD_ENTRIES SeekHead entries
* will be reserved at the current file location.
*/
static void mkv_start_seekhead(MatroskaMuxContext *mkv, AVIOContext *pb)
{
mkv->seekhead.filepos = avio_tell(pb);
// 21 bytes max for a Seek entry, 6 bytes max for the SeekHead ID
// and size, 6 bytes for a CRC32 element, and 2 bytes to guarantee
// that an EBML void element will fit afterwards
mkv->seekhead.reserved_size = MAX_SEEKHEAD_ENTRIES * MAX_SEEKENTRY_SIZE + 14;
put_ebml_void(pb, mkv->seekhead.reserved_size);
}
/**
* Write the SeekHead to the file at the location reserved for it
* and seek to destpos afterwards. When error_on_seek_failure
* is not set, failure to seek to the position designated for the
* SeekHead is not considered an error and it is presumed that
* destpos is the current position; failure to seek to destpos
* afterwards is always an error.
*
* @return 0 on success, < 0 on error.
*/
static int mkv_write_seekhead(AVIOContext *pb, MatroskaMuxContext *mkv,
int error_on_seek_failure, int64_t destpos)
{
AVIOContext *dyn_cp = NULL;
mkv_seekhead *seekhead = &mkv->seekhead;
int64_t remaining, ret64;
int i, ret;
if ((ret64 = avio_seek(pb, seekhead->filepos, SEEK_SET)) < 0)
return error_on_seek_failure ? ret64 : 0;
ret = start_ebml_master_crc32(&dyn_cp, mkv);
if (ret < 0)
return ret;
for (i = 0; i < seekhead->num_entries; i++) {
mkv_seekhead_entry *entry = &seekhead->entries[i];
ebml_master seekentry = start_ebml_master(dyn_cp, MATROSKA_ID_SEEKENTRY,
MAX_SEEKENTRY_SIZE);
put_ebml_id(dyn_cp, MATROSKA_ID_SEEKID);
put_ebml_length(dyn_cp, ebml_id_size(entry->elementid), 0);
put_ebml_id(dyn_cp, entry->elementid);
put_ebml_uint(dyn_cp, MATROSKA_ID_SEEKPOSITION, entry->segmentpos);
end_ebml_master(dyn_cp, seekentry);
}
ret = end_ebml_master_crc32(pb, &dyn_cp, mkv,
MATROSKA_ID_SEEKHEAD, 0, 0, 0);
if (ret < 0)
return ret;
remaining = seekhead->filepos + seekhead->reserved_size - avio_tell(pb);
put_ebml_void(pb, remaining);
if ((ret64 = avio_seek(pb, destpos, SEEK_SET)) < 0)
return ret64;
return 0;
}
static int mkv_add_cuepoint(MatroskaMuxContext *mkv, int stream, int64_t ts,
int64_t cluster_pos, int64_t relative_pos, int64_t duration)
{
mkv_cues *cues = &mkv->cues;
mkv_cuepoint *entries = cues->entries;
unsigned idx = cues->num_entries;
if (ts < 0)
return 0;
entries = av_realloc_array(entries, cues->num_entries + 1, sizeof(mkv_cuepoint));
if (!entries)
return AVERROR(ENOMEM);
cues->entries = entries;
/* Make sure the cues entries are sorted by pts. */
while (idx > 0 && entries[idx - 1].pts > ts)
idx--;
memmove(&entries[idx + 1], &entries[idx],
(cues->num_entries - idx) * sizeof(entries[0]));
entries[idx].pts = ts;
entries[idx].stream_idx = stream;
entries[idx].cluster_pos = cluster_pos - mkv->segment_offset;
entries[idx].relative_pos = relative_pos;
entries[idx].duration = duration;
cues->num_entries++;
return 0;
}
static int mkv_assemble_cues(AVStream **streams, AVIOContext *dyn_cp,
mkv_cues *cues, mkv_track *tracks, int num_tracks)
{
AVIOContext *cuepoint;
int ret;
ret = avio_open_dyn_buf(&cuepoint);
if (ret < 0)
return ret;
for (mkv_cuepoint *entry = cues->entries, *end = entry + cues->num_entries;
entry < end;) {
uint64_t pts = entry->pts;
uint8_t *buf;
int size;
put_ebml_uint(cuepoint, MATROSKA_ID_CUETIME, pts);
// put all the entries from different tracks that have the exact same
// timestamp into the same CuePoint
for (int j = 0; j < num_tracks; j++)
tracks[j].has_cue = 0;
do {
ebml_master track_positions;
int idx = entry->stream_idx;
av_assert0(idx >= 0 && idx < num_tracks);
if (tracks[idx].has_cue && streams[idx]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE)
continue;
tracks[idx].has_cue = 1;
track_positions = start_ebml_master(cuepoint, MATROSKA_ID_CUETRACKPOSITION, MAX_CUETRACKPOS_SIZE);
put_ebml_uint(cuepoint, MATROSKA_ID_CUETRACK , tracks[idx].track_num);
put_ebml_uint(cuepoint, MATROSKA_ID_CUECLUSTERPOSITION , entry->cluster_pos);
put_ebml_uint(cuepoint, MATROSKA_ID_CUERELATIVEPOSITION, entry->relative_pos);
if (entry->duration > 0)
put_ebml_uint(cuepoint, MATROSKA_ID_CUEDURATION , entry->duration);
end_ebml_master(cuepoint, track_positions);
} while (++entry < end && entry->pts == pts);
size = avio_get_dyn_buf(cuepoint, &buf);
if ((ret = cuepoint->error) < 0)
break;
put_ebml_binary(dyn_cp, MATROSKA_ID_POINTENTRY, buf, size);
ffio_reset_dyn_buf(cuepoint);
}
ffio_free_dyn_buf(&cuepoint);
return ret;
}
static int put_xiph_codecpriv(AVFormatContext *s, AVIOContext *pb,
const AVCodecParameters *par)
{
const uint8_t *header_start[3];
int header_len[3];
int first_header_size;
int err, j;
if (par->codec_id == AV_CODEC_ID_VORBIS)
first_header_size = 30;
else
first_header_size = 42;
err = avpriv_split_xiph_headers(par->extradata, par->extradata_size,
first_header_size, header_start, header_len);
if (err < 0) {
av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
return err;
}
avio_w8(pb, 2); // number packets - 1
for (j = 0; j < 2; j++) {
put_xiph_size(pb, header_len[j]);
}
for (j = 0; j < 3; j++)
avio_write(pb, header_start[j], header_len[j]);
return 0;
}
static int put_wv_codecpriv(AVIOContext *pb, const AVCodecParameters *par)
{
if (par->extradata && par->extradata_size == 2)
avio_write(pb, par->extradata, 2);
else
avio_wl16(pb, 0x410); // fallback to the most recent version
return 0;
}
static int put_flac_codecpriv(AVFormatContext *s, AVIOContext *pb,
const AVCodecParameters *par)
{
int write_comment = (par->channel_layout &&
!(par->channel_layout & ~0x3ffffULL) &&
!ff_flac_is_native_layout(par->channel_layout));
int ret = ff_flac_write_header(pb, par->extradata, par->extradata_size,
!write_comment);
if (ret < 0)
return ret;
if (write_comment) {
const char *vendor = (s->flags & AVFMT_FLAG_BITEXACT) ?
"Lavf" : LIBAVFORMAT_IDENT;
AVDictionary *dict = NULL;
uint8_t buf[32];
int64_t len;
snprintf(buf, sizeof(buf), "0x%"PRIx64, par->channel_layout);
av_dict_set(&dict, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", buf, 0);
len = ff_vorbiscomment_length(dict, vendor, NULL, 0);
av_assert1(len < (1 << 24) - 4);
avio_w8(pb, 0x84);
avio_wb24(pb, len);
ff_vorbiscomment_write(pb, dict, vendor, NULL, 0);
av_dict_free(&dict);
}
return 0;
}
static int get_aac_sample_rates(AVFormatContext *s, MatroskaMuxContext *mkv,
const uint8_t *extradata, int extradata_size,
int *sample_rate, int *output_sample_rate)
{
MPEG4AudioConfig mp4ac;
int ret;
ret = avpriv_mpeg4audio_get_config2(&mp4ac, extradata, extradata_size, 1, s);
/* Don't abort if the failure is because of missing extradata. Assume in that
* case a bitstream filter will provide the muxer with the extradata in the
* first packet.
* Abort however if s->pb is not seekable, as we would not be able to seek back
* to write the sample rate elements once the extradata shows up, anyway. */
if (ret < 0 && (extradata_size || !IS_SEEKABLE(s->pb, mkv))) {
av_log(s, AV_LOG_ERROR,
"Error parsing AAC extradata, unable to determine samplerate.\n");
return AVERROR(EINVAL);
}
if (ret < 0) {
/* This will only happen when this function is called while writing the
* header and no extradata is available. The space for this element has
* to be reserved for when this function is called again after the
* extradata shows up in the first packet, as there's no way to know if
* output_sample_rate will be different than sample_rate or not. */
*output_sample_rate = *sample_rate;
} else {
*sample_rate = mp4ac.sample_rate;
*output_sample_rate = mp4ac.ext_sample_rate;
}
return 0;
}
static int mkv_write_native_codecprivate(AVFormatContext *s, AVIOContext *pb,
const AVCodecParameters *par,
AVIOContext *dyn_cp)
{
switch (par->codec_id) {
case AV_CODEC_ID_VORBIS:
case AV_CODEC_ID_THEORA:
return put_xiph_codecpriv(s, dyn_cp, par);
case AV_CODEC_ID_FLAC:
return put_flac_codecpriv(s, dyn_cp, par);
case AV_CODEC_ID_WAVPACK:
return put_wv_codecpriv(dyn_cp, par);
case AV_CODEC_ID_H264:
return ff_isom_write_avcc(dyn_cp, par->extradata,
par->extradata_size);
case AV_CODEC_ID_HEVC:
return ff_isom_write_hvcc(dyn_cp, par->extradata,
par->extradata_size, 0);
case AV_CODEC_ID_AV1:
if (par->extradata_size)
return ff_isom_write_av1c(dyn_cp, par->extradata,
par->extradata_size);
else
put_ebml_void(pb, 4 + 3);
break;
case AV_CODEC_ID_ALAC:
if (par->extradata_size < 36) {
av_log(s, AV_LOG_ERROR,
"Invalid extradata found, ALAC expects a 36-byte "
"QuickTime atom.");
return AVERROR_INVALIDDATA;
} else
avio_write(dyn_cp, par->extradata + 12,
par->extradata_size - 12);
break;
case AV_CODEC_ID_AAC:
if (par->extradata_size)
avio_write(dyn_cp, par->extradata, par->extradata_size);
else
put_ebml_void(pb, MAX_PCE_SIZE + 2 + 4);
break;
default:
if (par->codec_id == AV_CODEC_ID_PRORES &&
ff_codec_get_id(ff_codec_movvideo_tags, par->codec_tag) == AV_CODEC_ID_PRORES) {
avio_wl32(dyn_cp, par->codec_tag);
} else if (par->extradata_size && par->codec_id != AV_CODEC_ID_TTA)
avio_write(dyn_cp, par->extradata, par->extradata_size);
}
return 0;
}
static int mkv_write_codecprivate(AVFormatContext *s, AVIOContext *pb,
AVCodecParameters *par,
int native_id, int qt_id)
{
AVIOContext *dyn_cp;
MatroskaMuxContext *mkv = s->priv_data;
uint8_t *codecpriv;
int ret, codecpriv_size;
ret = avio_open_dyn_buf(&dyn_cp);
if (ret < 0)
return ret;
if (native_id) {
ret = mkv_write_native_codecprivate(s, pb, par, dyn_cp);
} else if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
if (qt_id) {
if (!par->codec_tag)
par->codec_tag = ff_codec_get_tag(ff_codec_movvideo_tags,
par->codec_id);
if ( ff_codec_get_id(ff_codec_movvideo_tags, par->codec_tag) == par->codec_id
&& (!par->extradata_size || ff_codec_get_id(ff_codec_movvideo_tags, AV_RL32(par->extradata + 4)) != par->codec_id)
) {
avio_wb32(dyn_cp, 0x5a + par->extradata_size);
avio_wl32(dyn_cp, par->codec_tag);
ffio_fill(dyn_cp, 0, 0x5a - 8);
}
avio_write(dyn_cp, par->extradata, par->extradata_size);
} else {
if (!ff_codec_get_tag(ff_codec_bmp_tags, par->codec_id))
av_log(s, AV_LOG_WARNING, "codec %s is not supported by this format\n",
avcodec_get_name(par->codec_id));
if (!par->codec_tag)
par->codec_tag = ff_codec_get_tag(ff_codec_bmp_tags,
par->codec_id);
if (!par->codec_tag && par->codec_id != AV_CODEC_ID_RAWVIDEO) {
av_log(s, AV_LOG_ERROR, "No bmp codec tag found for codec %s\n",
avcodec_get_name(par->codec_id));
ret = AVERROR(EINVAL);
}
ff_put_bmp_header(dyn_cp, par, 0, 0, mkv->flipped_raw_rgb);
}
} else if (par->codec_type == AVMEDIA_TYPE_AUDIO) {
unsigned int tag;
tag = ff_codec_get_tag(ff_codec_wav_tags, par->codec_id);
if (!tag) {
av_log(s, AV_LOG_ERROR, "No wav codec tag found for codec %s\n",
avcodec_get_name(par->codec_id));
ret = AVERROR(EINVAL);
}
if (!par->codec_tag)
par->codec_tag = tag;
ff_put_wav_header(s, dyn_cp, par, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX);
}
if (ret >= 0) {
codecpriv_size = avio_get_dyn_buf(dyn_cp, &codecpriv);
if ((ret = dyn_cp->error) >= 0 && codecpriv_size)
put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codecpriv,
codecpriv_size);
}
ffio_free_dyn_buf(&dyn_cp);
return ret;
}
static void mkv_write_video_color(AVIOContext *pb, const AVStream *st,
const AVCodecParameters *par)
{
/* 18 Elements with two bytes ID, one byte length field, 8 bytes payload
* a master element with two bytes ID and one byte length field
* plus another byte to stay clear of the end. */
uint8_t colour[(2 + 1 + 8) * 18 + (2 + 1) + 1];
FFIOContext buf;
AVIOContext *const dyn_cp = &buf.pub;
int colorinfo_size;
const void *side_data;
ffio_init_context(&buf, colour, sizeof(colour), 1, NULL, NULL, NULL, NULL);
if (par->color_trc != AVCOL_TRC_UNSPECIFIED &&
par->color_trc < AVCOL_TRC_NB) {
put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORTRANSFERCHARACTERISTICS,
par->color_trc);
}
if (par->color_space != AVCOL_SPC_UNSPECIFIED &&
par->color_space < AVCOL_SPC_NB) {
put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORMATRIXCOEFF, par->color_space);
}
if (par->color_primaries != AVCOL_PRI_UNSPECIFIED &&
par->color_primaries < AVCOL_PRI_NB) {
put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORPRIMARIES, par->color_primaries);
}
if (par->color_range != AVCOL_RANGE_UNSPECIFIED &&
par->color_range < AVCOL_RANGE_NB) {
put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORRANGE, par->color_range);
}
if (par->chroma_location != AVCHROMA_LOC_UNSPECIFIED &&
par->chroma_location <= AVCHROMA_LOC_TOP) {
int xpos, ypos;
avcodec_enum_to_chroma_pos(&xpos, &ypos, par->chroma_location);
put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORCHROMASITINGHORZ, (xpos >> 7) + 1);
put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORCHROMASITINGVERT, (ypos >> 7) + 1);
}
side_data = av_stream_get_side_data(st, AV_PKT_DATA_CONTENT_LIGHT_LEVEL,
NULL);
if (side_data) {
const AVContentLightMetadata *metadata = side_data;
put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORMAXCLL, metadata->MaxCLL);
put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOCOLORMAXFALL, metadata->MaxFALL);
}
side_data = av_stream_get_side_data(st, AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
NULL);
if (side_data) {
ebml_master meta_element = start_ebml_master(
dyn_cp, MATROSKA_ID_VIDEOCOLORMASTERINGMETA, 10 * (2 + 1 + 8));
const AVMasteringDisplayMetadata *metadata = side_data;
if (metadata->has_primaries) {
put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_RX,
av_q2d(metadata->display_primaries[0][0]));
put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_RY,
av_q2d(metadata->display_primaries[0][1]));
put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_GX,
av_q2d(metadata->display_primaries[1][0]));
put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_GY,
av_q2d(metadata->display_primaries[1][1]));
put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_BX,
av_q2d(metadata->display_primaries[2][0]));
put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_BY,
av_q2d(metadata->display_primaries[2][1]));
put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_WHITEX,
av_q2d(metadata->white_point[0]));
put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_WHITEY,
av_q2d(metadata->white_point[1]));
}
if (metadata->has_luminance) {
put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_LUMINANCEMAX,
av_q2d(metadata->max_luminance));
put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOCOLOR_LUMINANCEMIN,
av_q2d(metadata->min_luminance));
}
end_ebml_master(dyn_cp, meta_element);
}
colorinfo_size = avio_tell(dyn_cp);
if (colorinfo_size)
put_ebml_binary(pb, MATROSKA_ID_VIDEOCOLOR, colour, colorinfo_size);
}
static void mkv_write_video_projection(AVFormatContext *s, AVIOContext *pb,
const AVStream *st)
{
ebml_master projection;
uint8_t private[20];
const AVSphericalMapping *spherical =
(const AVSphericalMapping *)av_stream_get_side_data(st, AV_PKT_DATA_SPHERICAL,
NULL);
if (!spherical)
return;
if (spherical->projection != AV_SPHERICAL_EQUIRECTANGULAR &&
spherical->projection != AV_SPHERICAL_EQUIRECTANGULAR_TILE &&
spherical->projection != AV_SPHERICAL_CUBEMAP) {
av_log(s, AV_LOG_WARNING, "Unknown projection type\n");
return;
}
// Maximally 4 8-byte elements with id-length 2 + 1 byte length field
// and the private data of the AV_SPHERICAL_EQUIRECTANGULAR_TILE case
projection = start_ebml_master(pb, MATROSKA_ID_VIDEOPROJECTION,
4 * (2 + 1 + 8) + (2 + 1 + 20));
switch (spherical->projection) {
case AV_SPHERICAL_EQUIRECTANGULAR:
put_ebml_uint(pb, MATROSKA_ID_VIDEOPROJECTIONTYPE,
MATROSKA_VIDEO_PROJECTION_TYPE_EQUIRECTANGULAR);
break;
case AV_SPHERICAL_EQUIRECTANGULAR_TILE:
put_ebml_uint(pb, MATROSKA_ID_VIDEOPROJECTIONTYPE,
MATROSKA_VIDEO_PROJECTION_TYPE_EQUIRECTANGULAR);
AV_WB32(private, 0); // version + flags
AV_WB32(private + 4, spherical->bound_top);
AV_WB32(private + 8, spherical->bound_bottom);
AV_WB32(private + 12, spherical->bound_left);
AV_WB32(private + 16, spherical->bound_right);
put_ebml_binary(pb, MATROSKA_ID_VIDEOPROJECTIONPRIVATE,
private, 20);
break;
case AV_SPHERICAL_CUBEMAP:
put_ebml_uint(pb, MATROSKA_ID_VIDEOPROJECTIONTYPE,
MATROSKA_VIDEO_PROJECTION_TYPE_CUBEMAP);
AV_WB32(private, 0); // version + flags
AV_WB32(private + 4, 0); // layout
AV_WB32(private + 8, spherical->padding);
put_ebml_binary(pb, MATROSKA_ID_VIDEOPROJECTIONPRIVATE,
private, 12);
break;
default:
av_assert0(0);
}
if (spherical->yaw)
put_ebml_float(pb, MATROSKA_ID_VIDEOPROJECTIONPOSEYAW,
(double) spherical->yaw / (1 << 16));
if (spherical->pitch)
put_ebml_float(pb, MATROSKA_ID_VIDEOPROJECTIONPOSEPITCH,
(double) spherical->pitch / (1 << 16));
if (spherical->roll)
put_ebml_float(pb, MATROSKA_ID_VIDEOPROJECTIONPOSEROLL,
(double) spherical->roll / (1 << 16));
end_ebml_master(pb, projection);
}
static void mkv_write_field_order(AVIOContext *pb, int mode,
enum AVFieldOrder field_order)
{
switch (field_order) {
case AV_FIELD_UNKNOWN:
break;
case AV_FIELD_PROGRESSIVE:
put_ebml_uint(pb, MATROSKA_ID_VIDEOFLAGINTERLACED,