/
matroskaenc.c
2855 lines (2464 loc) · 103 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 "subtitles.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/sha.h"
#include "libavutil/stereo3d.h"
#include "libavcodec/xiph.h"
#include "libavcodec/mpeg4audio.h"
#include "libavcodec/internal.h"
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 mkv_seekhead_entry {
uint32_t elementid;
uint64_t segmentpos;
} mkv_seekhead_entry;
typedef struct mkv_seekhead {
int64_t filepos;
int64_t segment_offset; ///< the file offset to the beginning of the segment
int reserved_size; ///< -1 if appending to file
int max_entries;
mkv_seekhead_entry *entries;
int num_entries;
} mkv_seekhead;
typedef struct mkv_cuepoint {
uint64_t pts;
int stream_idx;
int tracknum;
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 {
int64_t segment_offset;
mkv_cuepoint *entries;
int num_entries;
} mkv_cues;
typedef struct mkv_track {
int write_dts;
int has_cue;
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;
typedef struct mkv_attachment {
int stream_idx;
uint32_t fileuid;
} mkv_attachment;
typedef struct mkv_attachments {
mkv_attachment *entries;
int num_entries;
} mkv_attachments;
#define MODE_MATROSKAv2 0x01
#define MODE_WEBM 0x02
/** Maximum number of tracks allowed in a Matroska file (with track numbers in
* range 1 to 126 (inclusive) */
#define MAX_TRACKS 126
typedef struct MatroskaMuxContext {
const AVClass *class;
int mode;
AVIOContext *tags_bc;
int64_t tags_pos;
AVIOContext *info_bc;
int64_t info_pos;
AVIOContext *tracks_bc;
int64_t tracks_pos;
ebml_master segment;
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_seekhead *seekhead;
mkv_cues *cues;
mkv_track *tracks;
mkv_attachments *attachments;
AVPacket cur_audio_pkt;
int have_attachments;
int have_video;
int reserve_cues_space;
int cluster_size_limit;
int64_t cues_pos;
int64_t cluster_time_limit;
int is_dash;
int dash_track_number;
int is_live;
int write_crc;
uint32_t chapter_id_offset;
int wrote_chapters;
int allow_raw_vfw;
} 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
/** per-cuepoint-track - 5 1-byte EBML IDs, 5 1-byte EBML sizes, 3 8-byte uint max
* and one 1-byte uint for the track number (this assumes MAX_TRACKS to be <= 255) */
#define MAX_CUETRACKPOS_SIZE 35
/** per-cuepoint - 1 1-byte EBML ID, 1 1-byte EBML size, 8-byte uint max */
#define MAX_CUEPOINT_CONTENT_SIZE(num_tracks) 10 + MAX_CUETRACKPOS_SIZE * num_tracks
/** Seek preroll value for opus */
#define OPUS_SEEK_PREROLL 80000000
static int ebml_id_size(uint32_t id)
{
return (av_log2(id + 1) - 1) / 7 + 1;
}
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);
ffio_fill(pb, 0xff, bytes - 1);
}
/**
* Calculate how many bytes are needed to represent a given number in EBML.
*/
static int ebml_num_size(uint64_t num)
{
int bytes = 1;
while ((num + 1) >> bytes * 7)
bytes++;
return bytes;
}
/**
* Write a number in EBML variable length format.
*
* @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_num(AVIOContext *pb, uint64_t num, int bytes)
{
int i, needed_bytes = ebml_num_size(num);
// sizes larger than this are currently undefined in EBML
av_assert0(num < (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);
num |= 1ULL << bytes * 7;
for (i = bytes - 1; i >= 0; i--)
avio_w8(pb, (uint8_t)(num >> i * 8));
}
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_num(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_num(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_num(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_num(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, uint64_t size)
{
int64_t currentpos = avio_tell(pb);
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)
put_ebml_num(pb, size - 2, 0);
else
put_ebml_num(pb, size - 9, 8);
ffio_fill(pb, 0, currentpos + size - avio_tell(pb));
}
static ebml_master start_ebml_master(AVIOContext *pb, uint32_t elementid,
uint64_t expectedsize)
{
int bytes = expectedsize ? ebml_num_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_num(pb, pos - master.pos, master.sizebytes);
avio_seek(pb, pos, SEEK_SET);
}
static int start_ebml_master_crc32(AVIOContext *pb, AVIOContext **dyn_cp, MatroskaMuxContext *mkv,
uint32_t elementid)
{
int ret;
if ((ret = avio_open_dyn_buf(dyn_cp)) < 0)
return ret;
put_ebml_id(pb, elementid);
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 void end_ebml_master_crc32(AVIOContext *pb, AVIOContext **dyn_cp, MatroskaMuxContext *mkv)
{
uint8_t *buf, crc[4];
int size, skip = 0;
size = avio_close_dyn_buf(*dyn_cp, &buf);
put_ebml_num(pb, size, 0);
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);
av_free(buf);
*dyn_cp = NULL;
}
/**
* Complete ebml master without destroying the buffer, allowing for later updates
*/
static void end_ebml_master_crc32_preliminary(AVIOContext *pb, AVIOContext **dyn_cp, MatroskaMuxContext *mkv,
int64_t *pos)
{
uint8_t *buf;
int size = avio_get_dyn_buf(*dyn_cp, &buf);
*pos = avio_tell(pb);
put_ebml_num(pb, size, 0);
avio_write(pb, buf, size);
}
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;
av_packet_unref(&mkv->cur_audio_pkt);
ffio_free_dyn_buf(&mkv->cluster_bc);
ffio_free_dyn_buf(&mkv->info_bc);
ffio_free_dyn_buf(&mkv->tracks_bc);
ffio_free_dyn_buf(&mkv->tags_bc);
if (mkv->seekhead) {
av_freep(&mkv->seekhead->entries);
av_freep(&mkv->seekhead);
}
if (mkv->cues) {
av_freep(&mkv->cues->entries);
av_freep(&mkv->cues);
}
if (mkv->attachments) {
av_freep(&mkv->attachments->entries);
av_freep(&mkv->attachments);
}
av_freep(&mkv->tracks);
}
/**
* Initialize a mkv_seekhead element to be ready to index level 1 Matroska
* elements. If a maximum number of elements is specified, enough space
* will be reserved at the current file location to write a seek head of
* that size.
*
* @param segment_offset The absolute offset to the position in the file
* where the segment begins.
* @param numelements The maximum number of elements that will be indexed
* by this seek head, 0 if unlimited.
*/
static mkv_seekhead *mkv_start_seekhead(AVIOContext *pb, int64_t segment_offset,
int numelements)
{
mkv_seekhead *new_seekhead = av_mallocz(sizeof(mkv_seekhead));
if (!new_seekhead)
return NULL;
new_seekhead->segment_offset = segment_offset;
if (numelements > 0) {
new_seekhead->filepos = avio_tell(pb);
// 21 bytes max for a seek entry, 10 bytes max for the SeekHead ID
// and size, 6 bytes for a CRC32 element, and 3 bytes to guarantee
// that an EBML void element will fit afterwards
new_seekhead->reserved_size = numelements * MAX_SEEKENTRY_SIZE + 19;
new_seekhead->max_entries = numelements;
put_ebml_void(pb, new_seekhead->reserved_size);
}
return new_seekhead;
}
static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, uint32_t elementid, uint64_t filepos)
{
mkv_seekhead_entry *entries = seekhead->entries;
// don't store more elements than we reserved space for
if (seekhead->max_entries > 0 && seekhead->max_entries <= seekhead->num_entries)
return -1;
entries = av_realloc_array(entries, seekhead->num_entries + 1, sizeof(mkv_seekhead_entry));
if (!entries)
return AVERROR(ENOMEM);
seekhead->entries = entries;
seekhead->entries[seekhead->num_entries].elementid = elementid;
seekhead->entries[seekhead->num_entries++].segmentpos = filepos - seekhead->segment_offset;
return 0;
}
/**
* Write the seek head to the file and free it. If a maximum number of
* elements was specified to mkv_start_seekhead(), the seek head will
* be written at the location reserved for it. Otherwise, it is written
* at the current location in the file.
*
* @return The file offset where the seekhead was written,
* -1 if an error occurred.
*/
static int64_t mkv_write_seekhead(AVIOContext *pb, MatroskaMuxContext *mkv)
{
AVIOContext *dyn_cp;
mkv_seekhead *seekhead = mkv->seekhead;
ebml_master seekentry;
int64_t currentpos;
int i;
currentpos = avio_tell(pb);
if (seekhead->reserved_size > 0) {
if (avio_seek(pb, seekhead->filepos, SEEK_SET) < 0) {
currentpos = -1;
goto fail;
}
}
if (start_ebml_master_crc32(pb, &dyn_cp, mkv, MATROSKA_ID_SEEKHEAD) < 0) {
currentpos = -1;
goto fail;
}
for (i = 0; i < seekhead->num_entries; i++) {
mkv_seekhead_entry *entry = &seekhead->entries[i];
seekentry = start_ebml_master(dyn_cp, MATROSKA_ID_SEEKENTRY, MAX_SEEKENTRY_SIZE);
put_ebml_id(dyn_cp, MATROSKA_ID_SEEKID);
put_ebml_num(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);
}
end_ebml_master_crc32(pb, &dyn_cp, mkv);
if (seekhead->reserved_size > 0) {
uint64_t remaining = seekhead->filepos + seekhead->reserved_size - avio_tell(pb);
put_ebml_void(pb, remaining);
avio_seek(pb, currentpos, SEEK_SET);
currentpos = seekhead->filepos;
}
fail:
av_freep(&mkv->seekhead->entries);
av_freep(&mkv->seekhead);
return currentpos;
}
static mkv_cues *mkv_start_cues(int64_t segment_offset)
{
mkv_cues *cues = av_mallocz(sizeof(mkv_cues));
if (!cues)
return NULL;
cues->segment_offset = segment_offset;
return cues;
}
static int mkv_add_cuepoint(mkv_cues *cues, int stream, int tracknum, int64_t ts,
int64_t cluster_pos, int64_t relative_pos, int64_t duration)
{
mkv_cuepoint *entries = cues->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;
cues->entries[cues->num_entries].pts = ts;
cues->entries[cues->num_entries].stream_idx = stream;
cues->entries[cues->num_entries].tracknum = tracknum;
cues->entries[cues->num_entries].cluster_pos = cluster_pos - cues->segment_offset;
cues->entries[cues->num_entries].relative_pos = relative_pos;
cues->entries[cues->num_entries++].duration = duration;
return 0;
}
static int64_t mkv_write_cues(AVFormatContext *s, mkv_cues *cues, mkv_track *tracks, int num_tracks)
{
MatroskaMuxContext *mkv = s->priv_data;
AVIOContext *dyn_cp, *pb = s->pb;
int64_t currentpos;
int i, j, ret;
currentpos = avio_tell(pb);
ret = start_ebml_master_crc32(pb, &dyn_cp, mkv, MATROSKA_ID_CUES);
if (ret < 0)
return ret;
for (i = 0; i < cues->num_entries; i++) {
ebml_master cuepoint, track_positions;
mkv_cuepoint *entry = &cues->entries[i];
uint64_t pts = entry->pts;
int ctp_nb = 0;
// Calculate the number of entries, so we know the element size
for (j = 0; j < num_tracks; j++)
tracks[j].has_cue = 0;
for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
int idx = entry[j].stream_idx;
av_assert0(idx >= 0 && idx < num_tracks);
if (tracks[idx].has_cue && s->streams[idx]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE)
continue;
tracks[idx].has_cue = 1;
ctp_nb ++;
}
cuepoint = start_ebml_master(dyn_cp, MATROSKA_ID_POINTENTRY, MAX_CUEPOINT_CONTENT_SIZE(ctp_nb));
put_ebml_uint(dyn_cp, MATROSKA_ID_CUETIME, pts);
// put all the entries from different tracks that have the exact same
// timestamp into the same CuePoint
for (j = 0; j < num_tracks; j++)
tracks[j].has_cue = 0;
for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
int idx = entry[j].stream_idx;
if (tracks[idx].has_cue && s->streams[idx]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE)
continue;
tracks[idx].has_cue = 1;
track_positions = start_ebml_master(dyn_cp, MATROSKA_ID_CUETRACKPOSITION, MAX_CUETRACKPOS_SIZE);
put_ebml_uint(dyn_cp, MATROSKA_ID_CUETRACK , entry[j].tracknum );
put_ebml_uint(dyn_cp, MATROSKA_ID_CUECLUSTERPOSITION , entry[j].cluster_pos);
put_ebml_uint(dyn_cp, MATROSKA_ID_CUERELATIVEPOSITION, entry[j].relative_pos);
if (entry[j].duration != -1)
put_ebml_uint(dyn_cp, MATROSKA_ID_CUEDURATION , entry[j].duration);
end_ebml_master(dyn_cp, track_positions);
}
i += j - 1;
end_ebml_master(dyn_cp, cuepoint);
}
end_ebml_master_crc32(pb, &dyn_cp, mkv);
return currentpos;
}
static int put_xiph_codecpriv(AVFormatContext *s, AVIOContext *pb, AVCodecParameters *par)
{
const uint8_t *header_start[3];
int header_len[3];
int first_header_size;
int j;
if (par->codec_id == AV_CODEC_ID_VORBIS)
first_header_size = 30;
else
first_header_size = 42;
if (avpriv_split_xiph_headers(par->extradata, par->extradata_size,
first_header_size, header_start, header_len) < 0) {
av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
return -1;
}
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, AVCodecParameters *par)
{
if (par->extradata && par->extradata_size == 2)
avio_write(pb, par->extradata, 2);
else
avio_wl16(pb, 0x403); // fallback to the version mentioned in matroska specs
return 0;
}
static int put_flac_codecpriv(AVFormatContext *s,
AVIOContext *pb, 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], *data, *p;
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);
if (len >= ((1<<24) - 4)) {
av_dict_free(&dict);
return AVERROR(EINVAL);
}
data = av_malloc(len + 4);
if (!data) {
av_dict_free(&dict);
return AVERROR(ENOMEM);
}
data[0] = 0x84;
AV_WB24(data + 1, len);
p = data + 4;
ff_vorbiscomment_write(&p, &dict, vendor, NULL, 0);
avio_write(pb, data, len + 4);
av_freep(&data);
av_dict_free(&dict);
}
return 0;
}
static int get_aac_sample_rates(AVFormatContext *s, 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 || !(s->pb->seekable & AVIO_SEEKABLE_NORMAL))) {
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,
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;
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)
) {
int i;
avio_wb32(dyn_cp, 0x5a + par->extradata_size);
avio_wl32(dyn_cp, par->codec_tag);
for(i = 0; i < 0x5a - 8; i++)
avio_w8(dyn_cp, 0);
}
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);
}
} 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);
}
codecpriv_size = avio_get_dyn_buf(dyn_cp, &codecpriv);
if (codecpriv_size)
put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codecpriv,
codecpriv_size);
ffio_free_dyn_buf(&dyn_cp);
return ret;
}
static int mkv_write_video_color(AVIOContext *pb, AVCodecParameters *par, AVStream *st) {
AVIOContext *dyn_cp;
uint8_t *colorinfo_ptr;
int side_data_size = 0;
int ret, colorinfo_size;
const uint8_t *side_data;
ret = avio_open_dyn_buf(&dyn_cp);
if (ret < 0)
return ret;
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,
&side_data_size);
if (side_data_size) {
const AVContentLightMetadata *metadata =
(const AVContentLightMetadata*)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,
&side_data_size);
if (side_data_size == sizeof(AVMasteringDisplayMetadata)) {
ebml_master meta_element = start_ebml_master(
dyn_cp, MATROSKA_ID_VIDEOCOLORMASTERINGMETA, 0);
const AVMasteringDisplayMetadata *metadata =
(const AVMasteringDisplayMetadata*)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_get_dyn_buf(dyn_cp, &colorinfo_ptr);
if (colorinfo_size) {
ebml_master colorinfo = start_ebml_master(pb, MATROSKA_ID_VIDEOCOLOR, colorinfo_size);
avio_write(pb, colorinfo_ptr, colorinfo_size);
end_ebml_master(pb, colorinfo);
}
ffio_free_dyn_buf(&dyn_cp);
return 0;
}
static int mkv_write_video_projection(AVFormatContext *s, AVIOContext *pb,
AVStream *st)
{
AVIOContext b;
AVIOContext *dyn_cp;
int side_data_size = 0;
int ret, projection_size;
uint8_t *projection_ptr;
uint8_t private[20];
const AVSphericalMapping *spherical =
(const AVSphericalMapping *)av_stream_get_side_data(st, AV_PKT_DATA_SPHERICAL,
&side_data_size);
if (!side_data_size)
return 0;
ret = avio_open_dyn_buf(&dyn_cp);
if (ret < 0)
return ret;
switch (spherical->projection) {
case AV_SPHERICAL_EQUIRECTANGULAR:
put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONTYPE,
MATROSKA_VIDEO_PROJECTION_TYPE_EQUIRECTANGULAR);
break;
case AV_SPHERICAL_EQUIRECTANGULAR_TILE:
ffio_init_context(&b, private, 20, 1, NULL, NULL, NULL, NULL);
put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONTYPE,
MATROSKA_VIDEO_PROJECTION_TYPE_EQUIRECTANGULAR);
avio_wb32(&b, 0); // version + flags
avio_wb32(&b, spherical->bound_top);
avio_wb32(&b, spherical->bound_bottom);
avio_wb32(&b, spherical->bound_left);
avio_wb32(&b, spherical->bound_right);
put_ebml_binary(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONPRIVATE,
private, avio_tell(&b));
break;
case AV_SPHERICAL_CUBEMAP:
ffio_init_context(&b, private, 12, 1, NULL, NULL, NULL, NULL);
put_ebml_uint(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONTYPE,
MATROSKA_VIDEO_PROJECTION_TYPE_CUBEMAP);
avio_wb32(&b, 0); // version + flags
avio_wb32(&b, 0); // layout
avio_wb32(&b, spherical->padding);
put_ebml_binary(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONPRIVATE,
private, avio_tell(&b));
break;
default:
av_log(s, AV_LOG_WARNING, "Unknown projection type\n");
goto end;
}
if (spherical->yaw)
put_ebml_float(dyn_cp, MATROSKA_ID_VIDEOPROJECTIONPOSEYAW,
(double) spherical->yaw / (1 << 16));
if (spherical->pitch)