-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
muxer.js
1261 lines (1254 loc) · 45.1 KB
/
muxer.js
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
"use strict";
var Mp4Muxer = (() => {
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __accessCheck = (obj, member, msg) => {
if (!member.has(obj))
throw TypeError("Cannot " + msg);
};
var __privateGet = (obj, member, getter) => {
__accessCheck(obj, member, "read from private field");
return getter ? getter.call(obj) : member.get(obj);
};
var __privateAdd = (obj, member, value) => {
if (member.has(obj))
throw TypeError("Cannot add the same private member more than once");
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
};
var __privateSet = (obj, member, value, setter) => {
__accessCheck(obj, member, "write to private field");
setter ? setter.call(obj, value) : member.set(obj, value);
return value;
};
var __privateMethod = (obj, member, method) => {
__accessCheck(obj, member, "access private method");
return method;
};
// src/index.ts
var src_exports = {};
__export(src_exports, {
ArrayBufferTarget: () => ArrayBufferTarget,
FileSystemWritableFileStreamTarget: () => FileSystemWritableFileStreamTarget,
Muxer: () => Muxer,
StreamTarget: () => StreamTarget
});
// src/misc.ts
var bytes = new Uint8Array(8);
var view = new DataView(bytes.buffer);
var u8 = (value) => {
return [(value % 256 + 256) % 256];
};
var u16 = (value) => {
view.setUint16(0, value, false);
return [bytes[0], bytes[1]];
};
var i16 = (value) => {
view.setInt16(0, value, false);
return [bytes[0], bytes[1]];
};
var u24 = (value) => {
view.setUint32(0, value, false);
return [bytes[1], bytes[2], bytes[3]];
};
var u32 = (value) => {
view.setUint32(0, value, false);
return [bytes[0], bytes[1], bytes[2], bytes[3]];
};
var u64 = (value) => {
view.setUint32(0, Math.floor(value / 2 ** 32), false);
view.setUint32(4, value, false);
return [bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]];
};
var fixed_8_8 = (value) => {
view.setInt16(0, 2 ** 8 * value, false);
return [bytes[0], bytes[1]];
};
var fixed_16_16 = (value) => {
view.setInt32(0, 2 ** 16 * value, false);
return [bytes[0], bytes[1], bytes[2], bytes[3]];
};
var fixed_2_30 = (value) => {
view.setInt32(0, 2 ** 30 * value, false);
return [bytes[0], bytes[1], bytes[2], bytes[3]];
};
var ascii = (text, nullTerminated = false) => {
let bytes2 = Array(text.length).fill(null).map((_, i) => text.charCodeAt(i));
if (nullTerminated)
bytes2.push(0);
return bytes2;
};
var last = (arr) => {
return arr && arr[arr.length - 1];
};
var intoTimescale = (timeInSeconds, timescale, round = true) => {
let value = timeInSeconds * timescale;
return round ? Math.round(value) : value;
};
var rotationMatrix = (rotationInDegrees) => {
let theta = rotationInDegrees * (Math.PI / 180);
let cosTheta = Math.cos(theta);
let sinTheta = Math.sin(theta);
return [
cosTheta,
sinTheta,
0,
-sinTheta,
cosTheta,
0,
0,
0,
1
];
};
var IDENTITY_MATRIX = rotationMatrix(0);
var matrixToBytes = (matrix) => {
return [
fixed_16_16(matrix[0]),
fixed_16_16(matrix[1]),
fixed_2_30(matrix[2]),
fixed_16_16(matrix[3]),
fixed_16_16(matrix[4]),
fixed_2_30(matrix[5]),
fixed_16_16(matrix[6]),
fixed_16_16(matrix[7]),
fixed_2_30(matrix[8])
];
};
var deepClone = (x) => {
if (!x)
return x;
if (typeof x !== "object")
return x;
if (Array.isArray(x))
return x.map(deepClone);
return Object.fromEntries(Object.entries(x).map(([key, value]) => [key, deepClone(value)]));
};
// src/box.ts
var box = (type, contents, children) => ({
type,
contents: contents && new Uint8Array(contents.flat(10)),
children
});
var fullBox = (type, version, flags, contents, children) => box(
type,
[u8(version), u24(flags), contents ?? []],
children
);
var ftyp = (holdsHevc) => {
if (holdsHevc)
return box("ftyp", [
ascii("isom"),
// Major brand
u32(0),
// Minor version
ascii("iso4"),
// Compatible brand 1
ascii("hvc1")
// Compatible brand 2
]);
return box("ftyp", [
ascii("isom"),
// Major brand
u32(0),
// Minor version
ascii("isom"),
// Compatible brand 1
ascii("avc1"),
// Compatible brand 2
ascii("mp41")
// Compatible brand 3
]);
};
var mdat = (reserveLargeSize) => ({ type: "mdat", largeSize: reserveLargeSize });
var free = (size) => ({ type: "free", size });
var moov = (tracks, creationTime) => box("moov", null, [
mvhd(creationTime, tracks),
...tracks.map((x) => trak(x, creationTime))
]);
var mvhd = (creationTime, tracks) => {
let duration = intoTimescale(Math.max(
0,
...tracks.filter((x) => x.samples.length > 0).map((x) => last(x.samples).timestamp + last(x.samples).duration)
), GLOBAL_TIMESCALE);
let nextTrackId = Math.max(...tracks.map((x) => x.id)) + 1;
return fullBox("mvhd", 0, 0, [
u32(creationTime),
// Creation time
u32(creationTime),
// Modification time
u32(GLOBAL_TIMESCALE),
// Timescale
u32(duration),
// Duration
fixed_16_16(1),
// Preferred rate
fixed_8_8(1),
// Preferred volume
Array(10).fill(0),
// Reserved
matrixToBytes(IDENTITY_MATRIX),
// Matrix
Array(24).fill(0),
// Pre-defined
u32(nextTrackId)
// Next track ID
]);
};
var trak = (track, creationTime) => box("trak", null, [
tkhd(track, creationTime),
mdia(track, creationTime)
]);
var tkhd = (track, creationTime) => {
let lastSample = last(track.samples);
let durationInGlobalTimescale = intoTimescale(
lastSample ? lastSample.timestamp + lastSample.duration : 0,
GLOBAL_TIMESCALE
);
return fullBox("tkhd", 0, 3, [
u32(creationTime),
// Creation time
u32(creationTime),
// Modification time
u32(track.id),
// Track ID
u32(0),
// Reserved
u32(durationInGlobalTimescale),
// Duration
Array(8).fill(0),
// Reserved
u16(0),
// Layer
u16(0),
// Alternate group
fixed_8_8(track.info.type === "audio" ? 1 : 0),
// Volume
u16(0),
// Reserved
matrixToBytes(rotationMatrix(track.info.type === "video" ? track.info.rotation : 0)),
// Matrix
fixed_16_16(track.info.type === "video" ? track.info.width : 0),
// Track width
fixed_16_16(track.info.type === "video" ? track.info.height : 0)
// Track height
]);
};
var mdia = (track, creationTime) => box("mdia", null, [
mdhd(track, creationTime),
hdlr(track.info.type === "video" ? "vide" : "soun"),
minf(track)
]);
var mdhd = (track, creationTime) => {
let lastSample = last(track.samples);
let localDuration = intoTimescale(
lastSample ? lastSample.timestamp + lastSample.duration : 0,
track.timescale
);
return fullBox("mdhd", 0, 0, [
u32(creationTime),
// Creation time
u32(creationTime),
// Modification time
u32(track.timescale),
// Timescale
u32(localDuration),
// Duration
u16(21956),
// Language ("und", undetermined)
u16(0)
// Quality
]);
};
var hdlr = (componentSubtype) => fullBox("hdlr", 0, 0, [
ascii("mhlr"),
// Component type
ascii(componentSubtype),
// Component subtype
u32(0),
// Component manufacturer
u32(0),
// Component flags
u32(0),
// Component flags mask
ascii("mp4-muxer-hdlr")
// Component name
]);
var minf = (track) => box("minf", null, [
track.info.type === "video" ? vmhd() : smhd(),
dinf(),
stbl(track)
]);
var vmhd = () => fullBox("vmhd", 0, 1, [
u16(0),
// Graphics mode
u16(0),
// Opcolor R
u16(0),
// Opcolor G
u16(0)
// Opcolor B
]);
var smhd = () => fullBox("smhd", 0, 0, [
u16(0),
// Balance
u16(0)
// Reserved
]);
var dinf = () => box("dinf", null, [
dref()
]);
var dref = () => fullBox("dref", 0, 0, [
u32(1)
// Entry count
], [
url()
]);
var url = () => fullBox("url ", 0, 1);
var stbl = (track) => box("stbl", null, [
stsd(track),
stts(track),
stss(track),
stsc(track),
stsz(track),
stco(track)
]);
var stsd = (track) => fullBox("stsd", 0, 0, [
u32(1)
// Entry count
], [
track.info.type === "video" ? videoSampleDescription(
VIDEO_CODEC_TO_BOX_NAME[track.info.codec],
track
) : soundSampleDescription(
AUDIO_CODEC_TO_BOX_NAME[track.info.codec],
track
)
]);
var videoSampleDescription = (compressionType, track) => box(compressionType, [
Array(6).fill(0),
// Reserved
u16(1),
// Data reference index
u16(0),
// Pre-defined
u16(0),
// Reserved
Array(12).fill(0),
// Pre-defined
u16(track.info.width),
// Width
u16(track.info.height),
// Height
u32(4718592),
// Horizontal resolution
u32(4718592),
// Vertical resolution
u32(0),
// Reserved
u16(1),
// Frame count
Array(32).fill(0),
// Compressor name
u16(24),
// Depth
i16(65535)
// Pre-defined
], [
VIDEO_CODEC_TO_CONFIGURATION_BOX[track.info.codec](track)
]);
var avcC = (track) => track.codecPrivate && box("avcC", [...track.codecPrivate]);
var hvcC = (track) => track.codecPrivate && box("hvcC", [...track.codecPrivate]);
var vpcC = (track) => track.codecPrivate && box("vpcC", [...track.codecPrivate]);
var av1C = (track) => track.codecPrivate && box("av1C", [...track.codecPrivate]);
var soundSampleDescription = (compressionType, track) => box(compressionType, [
Array(6).fill(0),
// Reserved
u16(1),
// Data reference index
u16(0),
// Version
u16(0),
// Revision level
u32(0),
// Vendor
u16(track.info.numberOfChannels),
// Number of channels
u16(16),
// Sample size (bits)
u16(0),
// Compression ID
u16(0),
// Packet size
fixed_16_16(track.info.sampleRate)
// Sample rate
], [
AUDIO_CODEC_TO_CONFIGURATION_BOX[track.info.codec](track)
]);
var esds = (track) => fullBox("esds", 0, 0, [
// https://stackoverflow.com/a/54803118
u32(58753152),
// TAG(3) = Object Descriptor ([2])
u8(32 + track.codecPrivate.byteLength),
// length of this OD (which includes the next 2 tags)
u16(1),
// ES_ID = 1
u8(0),
// flags etc = 0
u32(75530368),
// TAG(4) = ES Descriptor ([2]) embedded in above OD
u8(18 + track.codecPrivate.byteLength),
// length of this ESD
u8(64),
// MPEG-4 Audio
u8(21),
// stream type(6bits)=5 audio, flags(2bits)=1
u24(0),
// 24bit buffer size
u32(130071),
// max bitrate
u32(130071),
// avg bitrate
u32(92307584),
// TAG(5) = ASC ([2],[3]) embedded in above OD
u8(track.codecPrivate.byteLength),
// length
...track.codecPrivate,
u32(109084800),
// TAG(6)
u8(1),
// length
u8(2)
// data
]);
var dOps = (track) => box("dOps", [
u8(0),
// Version
u8(track.info.numberOfChannels),
// OutputChannelCount
u16(3840),
// PreSkip, should be at least 80 milliseconds worth of playback, measured in 48000 Hz samples
u32(track.info.sampleRate),
// InputSampleRate
fixed_8_8(0),
// OutputGain
u8(0)
// ChannelMappingFamily
]);
var stts = (track) => {
return fullBox("stts", 0, 0, [
u32(track.timeToSampleTable.length),
// Number of entries
track.timeToSampleTable.map((x) => [
// Time-to-sample table
u32(x.sampleCount),
// Sample count
u32(x.sampleDelta)
// Sample duration
])
]);
};
var stss = (track) => {
if (track.samples.every((x) => x.type === "key"))
return null;
let keySamples = [...track.samples.entries()].filter(([, sample]) => sample.type === "key");
return fullBox("stss", 0, 0, [
u32(keySamples.length),
// Number of entries
keySamples.map(([index]) => u32(index + 1))
// Sync sample table
]);
};
var stsc = (track) => {
return fullBox("stsc", 0, 0, [
u32(track.compactlyCodedChunkTable.length),
// Number of entries
track.compactlyCodedChunkTable.map((x) => [
// Sample-to-chunk table
u32(x.firstChunk),
// First chunk
u32(x.samplesPerChunk),
// Samples per chunk
u32(1)
// Sample description index
])
]);
};
var stsz = (track) => fullBox("stsz", 0, 0, [
u32(0),
// Sample size (0 means non-constant size)
u32(track.samples.length),
// Number of entries
track.samples.map((x) => u32(x.size))
// Sample size table
]);
var stco = (track) => {
if (track.finalizedChunks.length > 0 && last(track.finalizedChunks).offset >= 2 ** 32) {
return fullBox("co64", 0, 0, [
u32(track.finalizedChunks.length),
// Number of entries
track.finalizedChunks.map((x) => u64(x.offset))
// Chunk offset table
]);
}
return fullBox("stco", 0, 0, [
u32(track.finalizedChunks.length),
// Number of entries
track.finalizedChunks.map((x) => u32(x.offset))
// Chunk offset table
]);
};
var VIDEO_CODEC_TO_BOX_NAME = {
"avc": "avc1",
"hevc": "hvc1",
"vp9": "vp09",
"av1": "av01"
};
var VIDEO_CODEC_TO_CONFIGURATION_BOX = {
"avc": avcC,
"hevc": hvcC,
"vp9": vpcC,
"av1": av1C
};
var AUDIO_CODEC_TO_BOX_NAME = {
"aac": "mp4a",
"opus": "opus"
};
var AUDIO_CODEC_TO_CONFIGURATION_BOX = {
"aac": esds,
"opus": dOps
};
// src/target.ts
var ArrayBufferTarget = class {
constructor() {
this.buffer = null;
}
};
var StreamTarget = class {
constructor(onData, onDone, options) {
this.onData = onData;
this.onDone = onDone;
this.options = options;
}
};
var FileSystemWritableFileStreamTarget = class {
constructor(stream, options) {
this.stream = stream;
this.options = options;
}
};
// src/writer.ts
var _helper, _helperView;
var Writer = class {
constructor() {
this.pos = 0;
__privateAdd(this, _helper, new Uint8Array(8));
__privateAdd(this, _helperView, new DataView(__privateGet(this, _helper).buffer));
/**
* Stores the position from the start of the file to where boxes elements have been written. This is used to
* rewrite/edit elements that were already added before, and to measure sizes of things.
*/
this.offsets = /* @__PURE__ */ new WeakMap();
}
/** Sets the current position for future writes to a new one. */
seek(newPos) {
this.pos = newPos;
}
writeU32(value) {
__privateGet(this, _helperView).setUint32(0, value, false);
this.write(__privateGet(this, _helper).subarray(0, 4));
}
writeU64(value) {
__privateGet(this, _helperView).setUint32(0, Math.floor(value / 2 ** 32), false);
__privateGet(this, _helperView).setUint32(4, value, false);
this.write(__privateGet(this, _helper).subarray(0, 8));
}
writeAscii(text) {
for (let i = 0; i < text.length; i++) {
__privateGet(this, _helperView).setUint8(i % 8, text.charCodeAt(i));
if (i % 8 === 7)
this.write(__privateGet(this, _helper));
}
if (text.length % 8 !== 0) {
this.write(__privateGet(this, _helper).subarray(0, text.length % 8));
}
}
writeBox(box2) {
this.offsets.set(box2, this.pos);
if (box2.contents && !box2.children) {
this.writeBoxHeader(box2, box2.size ?? box2.contents.byteLength + 8);
this.write(box2.contents);
} else {
let startPos = this.pos;
this.writeBoxHeader(box2, 0);
if (box2.contents)
this.write(box2.contents);
if (box2.children) {
for (let child of box2.children)
if (child)
this.writeBox(child);
}
let endPos = this.pos;
let size = box2.size ?? endPos - startPos;
this.seek(startPos);
this.writeBoxHeader(box2, size);
this.seek(endPos);
}
}
writeBoxHeader(box2, size) {
this.writeU32(box2.largeSize ? 1 : size);
this.writeAscii(box2.type);
if (box2.largeSize)
this.writeU64(size);
}
measureBoxHeader(box2) {
return 8 + (box2.largeSize ? 8 : 0);
}
patchBox(box2) {
let endPos = this.pos;
this.seek(this.offsets.get(box2));
this.writeBox(box2);
this.seek(endPos);
}
measureBox(box2) {
if (box2.contents && !box2.children) {
let headerSize = this.measureBoxHeader(box2);
return headerSize + box2.contents.byteLength;
} else {
let result = this.measureBoxHeader(box2);
if (box2.contents)
result += box2.contents.byteLength;
if (box2.children) {
for (let child of box2.children)
if (child)
result += this.measureBox(child);
}
return result;
}
}
};
_helper = new WeakMap();
_helperView = new WeakMap();
var _target, _buffer, _bytes, _maxPos, _ensureSize, ensureSize_fn;
var ArrayBufferTargetWriter = class extends Writer {
constructor(target) {
super();
__privateAdd(this, _ensureSize);
__privateAdd(this, _target, void 0);
__privateAdd(this, _buffer, new ArrayBuffer(2 ** 16));
__privateAdd(this, _bytes, new Uint8Array(__privateGet(this, _buffer)));
__privateAdd(this, _maxPos, 0);
__privateSet(this, _target, target);
}
write(data) {
__privateMethod(this, _ensureSize, ensureSize_fn).call(this, this.pos + data.byteLength);
__privateGet(this, _bytes).set(data, this.pos);
this.pos += data.byteLength;
__privateSet(this, _maxPos, Math.max(__privateGet(this, _maxPos), this.pos));
}
finalize() {
__privateMethod(this, _ensureSize, ensureSize_fn).call(this, this.pos);
__privateGet(this, _target).buffer = __privateGet(this, _buffer).slice(0, Math.max(__privateGet(this, _maxPos), this.pos));
}
};
_target = new WeakMap();
_buffer = new WeakMap();
_bytes = new WeakMap();
_maxPos = new WeakMap();
_ensureSize = new WeakSet();
ensureSize_fn = function(size) {
let newLength = __privateGet(this, _buffer).byteLength;
while (newLength < size)
newLength *= 2;
if (newLength === __privateGet(this, _buffer).byteLength)
return;
let newBuffer = new ArrayBuffer(newLength);
let newBytes = new Uint8Array(newBuffer);
newBytes.set(__privateGet(this, _bytes), 0);
__privateSet(this, _buffer, newBuffer);
__privateSet(this, _bytes, newBytes);
};
var _target2, _sections;
var StreamTargetWriter = class extends Writer {
constructor(target) {
super();
__privateAdd(this, _target2, void 0);
__privateAdd(this, _sections, []);
__privateSet(this, _target2, target);
}
write(data) {
__privateGet(this, _sections).push({
data: data.slice(),
start: this.pos
});
this.pos += data.byteLength;
}
flush() {
if (__privateGet(this, _sections).length === 0)
return;
let chunks = [];
let sorted = [...__privateGet(this, _sections)].sort((a, b) => a.start - b.start);
chunks.push({
start: sorted[0].start,
size: sorted[0].data.byteLength
});
for (let i = 1; i < sorted.length; i++) {
let lastChunk = chunks[chunks.length - 1];
let section = sorted[i];
if (section.start <= lastChunk.start + lastChunk.size) {
lastChunk.size = Math.max(lastChunk.size, section.start + section.data.byteLength - lastChunk.start);
} else {
chunks.push({
start: section.start,
size: section.data.byteLength
});
}
}
for (let chunk of chunks) {
chunk.data = new Uint8Array(chunk.size);
for (let section of __privateGet(this, _sections)) {
if (chunk.start <= section.start && section.start < chunk.start + chunk.size) {
chunk.data.set(section.data, section.start - chunk.start);
}
}
__privateGet(this, _target2).onData(chunk.data, chunk.start);
}
__privateGet(this, _sections).length = 0;
}
finalize() {
__privateGet(this, _target2).onDone?.();
}
};
_target2 = new WeakMap();
_sections = new WeakMap();
var DEFAULT_CHUNK_SIZE = 2 ** 24;
var MAX_CHUNKS_AT_ONCE = 2;
var _target3, _chunkSize, _chunks, _writeDataIntoChunks, writeDataIntoChunks_fn, _insertSectionIntoChunk, insertSectionIntoChunk_fn, _createChunk, createChunk_fn, _flushChunks, flushChunks_fn;
var ChunkedStreamTargetWriter = class extends Writer {
constructor(target) {
super();
__privateAdd(this, _writeDataIntoChunks);
__privateAdd(this, _insertSectionIntoChunk);
__privateAdd(this, _createChunk);
__privateAdd(this, _flushChunks);
__privateAdd(this, _target3, void 0);
__privateAdd(this, _chunkSize, void 0);
/**
* The data is divided up into fixed-size chunks, whose contents are first filled in RAM and then flushed out.
* A chunk is flushed if all of its contents have been written.
*/
__privateAdd(this, _chunks, []);
__privateSet(this, _target3, target);
__privateSet(this, _chunkSize, target.options?.chunkSize ?? DEFAULT_CHUNK_SIZE);
if (!Number.isInteger(__privateGet(this, _chunkSize)) || __privateGet(this, _chunkSize) < 2 ** 10) {
throw new Error("Invalid StreamTarget options: chunkSize must be an integer not smaller than 1024.");
}
}
write(data) {
__privateMethod(this, _writeDataIntoChunks, writeDataIntoChunks_fn).call(this, data, this.pos);
__privateMethod(this, _flushChunks, flushChunks_fn).call(this);
this.pos += data.byteLength;
}
finalize() {
__privateMethod(this, _flushChunks, flushChunks_fn).call(this, true);
__privateGet(this, _target3).onDone?.();
}
};
_target3 = new WeakMap();
_chunkSize = new WeakMap();
_chunks = new WeakMap();
_writeDataIntoChunks = new WeakSet();
writeDataIntoChunks_fn = function(data, position) {
let chunkIndex = __privateGet(this, _chunks).findIndex((x) => x.start <= position && position < x.start + __privateGet(this, _chunkSize));
if (chunkIndex === -1)
chunkIndex = __privateMethod(this, _createChunk, createChunk_fn).call(this, position);
let chunk = __privateGet(this, _chunks)[chunkIndex];
let relativePosition = position - chunk.start;
let toWrite = data.subarray(0, Math.min(__privateGet(this, _chunkSize) - relativePosition, data.byteLength));
chunk.data.set(toWrite, relativePosition);
let section = {
start: relativePosition,
end: relativePosition + toWrite.byteLength
};
__privateMethod(this, _insertSectionIntoChunk, insertSectionIntoChunk_fn).call(this, chunk, section);
if (chunk.written[0].start === 0 && chunk.written[0].end === __privateGet(this, _chunkSize)) {
chunk.shouldFlush = true;
}
if (__privateGet(this, _chunks).length > MAX_CHUNKS_AT_ONCE) {
for (let i = 0; i < __privateGet(this, _chunks).length - 1; i++) {
__privateGet(this, _chunks)[i].shouldFlush = true;
}
__privateMethod(this, _flushChunks, flushChunks_fn).call(this);
}
if (toWrite.byteLength < data.byteLength) {
__privateMethod(this, _writeDataIntoChunks, writeDataIntoChunks_fn).call(this, data.subarray(toWrite.byteLength), position + toWrite.byteLength);
}
};
_insertSectionIntoChunk = new WeakSet();
insertSectionIntoChunk_fn = function(chunk, section) {
let low = 0;
let high = chunk.written.length - 1;
let index = -1;
while (low <= high) {
let mid = Math.floor(low + (high - low + 1) / 2);
if (chunk.written[mid].start <= section.start) {
low = mid + 1;
index = mid;
} else {
high = mid - 1;
}
}
chunk.written.splice(index + 1, 0, section);
if (index === -1 || chunk.written[index].end < section.start)
index++;
while (index < chunk.written.length - 1 && chunk.written[index].end >= chunk.written[index + 1].start) {
chunk.written[index].end = Math.max(chunk.written[index].end, chunk.written[index + 1].end);
chunk.written.splice(index + 1, 1);
}
};
_createChunk = new WeakSet();
createChunk_fn = function(includesPosition) {
let start = Math.floor(includesPosition / __privateGet(this, _chunkSize)) * __privateGet(this, _chunkSize);
let chunk = {
start,
data: new Uint8Array(__privateGet(this, _chunkSize)),
written: [],
shouldFlush: false
};
__privateGet(this, _chunks).push(chunk);
__privateGet(this, _chunks).sort((a, b) => a.start - b.start);
return __privateGet(this, _chunks).indexOf(chunk);
};
_flushChunks = new WeakSet();
flushChunks_fn = function(force = false) {
for (let i = 0; i < __privateGet(this, _chunks).length; i++) {
let chunk = __privateGet(this, _chunks)[i];
if (!chunk.shouldFlush && !force)
continue;
for (let section of chunk.written) {
__privateGet(this, _target3).onData(
chunk.data.subarray(section.start, section.end),
chunk.start + section.start
);
}
__privateGet(this, _chunks).splice(i--, 1);
}
};
var FileSystemWritableFileStreamTargetWriter = class extends ChunkedStreamTargetWriter {
constructor(target) {
super(new StreamTarget(
(data, position) => target.stream.write({
type: "write",
data,
position
}),
void 0,
{ chunkSize: target.options?.chunkSize }
));
}
};
// src/muxer.ts
var GLOBAL_TIMESCALE = 1e3;
var SUPPORTED_VIDEO_CODECS2 = ["avc", "hevc", "vp9", "av1"];
var SUPPORTED_AUDIO_CODECS2 = ["aac", "opus"];
var TIMESTAMP_OFFSET = 2082844800;
var MAX_CHUNK_DURATION = 0.5;
var FIRST_TIMESTAMP_BEHAVIORS = ["strict", "offset"];
var _options, _writer, _ftypSize, _mdat, _videoTrack, _audioTrack, _creationTime, _finalizedChunks, _finalized, _validateOptions, validateOptions_fn, _writeHeader, writeHeader_fn, _computeMoovSizeUpperBound, computeMoovSizeUpperBound_fn, _prepareTracks, prepareTracks_fn, _generateMpeg4AudioSpecificConfig, generateMpeg4AudioSpecificConfig_fn, _addSampleToTrack, addSampleToTrack_fn, _validateTimestamp, validateTimestamp_fn, _finalizeCurrentChunk, finalizeCurrentChunk_fn, _maybeFlushStreamingTargetWriter, maybeFlushStreamingTargetWriter_fn, _ensureNotFinalized, ensureNotFinalized_fn;
var Muxer = class {
constructor(options) {
__privateAdd(this, _validateOptions);
__privateAdd(this, _writeHeader);
__privateAdd(this, _computeMoovSizeUpperBound);
__privateAdd(this, _prepareTracks);
// https://wiki.multimedia.cx/index.php/MPEG-4_Audio
__privateAdd(this, _generateMpeg4AudioSpecificConfig);
__privateAdd(this, _addSampleToTrack);
__privateAdd(this, _validateTimestamp);
__privateAdd(this, _finalizeCurrentChunk);
__privateAdd(this, _maybeFlushStreamingTargetWriter);
__privateAdd(this, _ensureNotFinalized);
__privateAdd(this, _options, void 0);
__privateAdd(this, _writer, void 0);
__privateAdd(this, _ftypSize, void 0);
__privateAdd(this, _mdat, void 0);
__privateAdd(this, _videoTrack, null);
__privateAdd(this, _audioTrack, null);
__privateAdd(this, _creationTime, Math.floor(Date.now() / 1e3) + TIMESTAMP_OFFSET);
__privateAdd(this, _finalizedChunks, []);
__privateAdd(this, _finalized, false);
__privateMethod(this, _validateOptions, validateOptions_fn).call(this, options);
options.video = deepClone(options.video);
options.audio = deepClone(options.audio);
options.fastStart = deepClone(options.fastStart);
this.target = options.target;
__privateSet(this, _options, {
firstTimestampBehavior: "strict",
...options
});
if (options.target instanceof ArrayBufferTarget) {
__privateSet(this, _writer, new ArrayBufferTargetWriter(options.target));
} else if (options.target instanceof StreamTarget) {
__privateSet(this, _writer, options.target.options?.chunked ? new ChunkedStreamTargetWriter(options.target) : new StreamTargetWriter(options.target));
} else if (options.target instanceof FileSystemWritableFileStreamTarget) {
__privateSet(this, _writer, new FileSystemWritableFileStreamTargetWriter(options.target));
} else {
throw new Error(`Invalid target: ${options.target}`);
}
__privateMethod(this, _writeHeader, writeHeader_fn).call(this);
__privateMethod(this, _prepareTracks, prepareTracks_fn).call(this);
}
addVideoChunk(sample, meta, timestamp) {
let data = new Uint8Array(sample.byteLength);
sample.copyTo(data);
this.addVideoChunkRaw(data, sample.type, timestamp ?? sample.timestamp, sample.duration, meta);
}
addVideoChunkRaw(data, type, timestamp, duration, meta) {
__privateMethod(this, _ensureNotFinalized, ensureNotFinalized_fn).call(this);
if (!__privateGet(this, _options).video)
throw new Error("No video track declared.");
if (typeof __privateGet(this, _options).fastStart === "object" && __privateGet(this, _videoTrack).samples.length === __privateGet(this, _options).fastStart.expectedVideoChunks) {
throw new Error(`Cannot add more video chunks than specified in 'fastStart' (${__privateGet(this, _options).fastStart.expectedVideoChunks}).`);
}
__privateMethod(this, _addSampleToTrack, addSampleToTrack_fn).call(this, __privateGet(this, _videoTrack), data, type, timestamp, duration, meta);
}
addAudioChunk(sample, meta, timestamp) {
let data = new Uint8Array(sample.byteLength);
sample.copyTo(data);
this.addAudioChunkRaw(data, sample.type, timestamp ?? sample.timestamp, sample.duration, meta);
}
addAudioChunkRaw(data, type, timestamp, duration, meta) {
__privateMethod(this, _ensureNotFinalized, ensureNotFinalized_fn).call(this);
if (!__privateGet(this, _options).audio)
throw new Error("No audio track declared.");
if (typeof __privateGet(this, _options).fastStart === "object" && __privateGet(this, _audioTrack).samples.length === __privateGet(this, _options).fastStart.expectedAudioChunks) {
throw new Error(`Cannot add more audio chunks than specified in 'fastStart' (${__privateGet(this, _options).fastStart.expectedAudioChunks}).`);
}
__privateMethod(this, _addSampleToTrack, addSampleToTrack_fn).call(this, __privateGet(this, _audioTrack), data, type, timestamp, duration, meta);
}
/** Finalizes the file, making it ready for use. Must be called after all video and audio chunks have been added. */
finalize() {
if (__privateGet(this, _videoTrack))
__privateMethod(this, _finalizeCurrentChunk, finalizeCurrentChunk_fn).call(this, __privateGet(this, _videoTrack));
if (__privateGet(this, _audioTrack))
__privateMethod(this, _finalizeCurrentChunk, finalizeCurrentChunk_fn).call(this, __privateGet(this, _audioTrack));
let tracks = [__privateGet(this, _videoTrack), __privateGet(this, _audioTrack)].filter(Boolean);
if (__privateGet(this, _options).fastStart === "in-memory") {
let mdatSize;
for (let i = 0; i < 2; i++) {
let movieBox2 = moov(tracks, __privateGet(this, _creationTime));
let movieBoxSize = __privateGet(this, _writer).measureBox(movieBox2);
mdatSize = __privateGet(this, _writer).measureBox(__privateGet(this, _mdat));
let currentChunkPos = __privateGet(this, _writer).pos + movieBoxSize + mdatSize;
for (let chunk of __privateGet(this, _finalizedChunks)) {
chunk.offset = currentChunkPos;
for (let bytes2 of chunk.sampleData) {
currentChunkPos += bytes2.byteLength;
mdatSize += bytes2.byteLength;
}
}
if (currentChunkPos < 2 ** 32)
break;
if (mdatSize >= 2 ** 32)
__privateGet(this, _mdat).largeSize = true;
}
let movieBox = moov(tracks, __privateGet(this, _creationTime));
__privateGet(this, _writer).writeBox(movieBox);
__privateGet(this, _mdat).size = mdatSize;
__privateGet(this, _writer).writeBox(__privateGet(this, _mdat));
for (let chunk of __privateGet(this, _finalizedChunks)) {
for (let bytes2 of chunk.sampleData)
__privateGet(this, _writer).write(bytes2);
chunk.sampleData = null;
}
} else {
let mdatPos = __privateGet(this, _writer).offsets.get(__privateGet(this, _mdat));
let mdatSize = __privateGet(this, _writer).pos - mdatPos;
__privateGet(this, _mdat).size = mdatSize;
__privateGet(this, _mdat).largeSize = mdatSize >= 2 ** 32;
__privateGet(this, _writer).patchBox(__privateGet(this, _mdat));
let movieBox = moov(tracks, __privateGet(this, _creationTime));
if (typeof __privateGet(this, _options).fastStart === "object") {
__privateGet(this, _writer).seek(__privateGet(this, _ftypSize));
__privateGet(this, _writer).writeBox(movieBox);
let remainingBytes = mdatPos - __privateGet(this, _writer).pos;
__privateGet(this, _writer).writeBox(free(remainingBytes));
} else {
__privateGet(this, _writer).writeBox(movieBox);
}
}
__privateMethod(this, _maybeFlushStreamingTargetWriter, maybeFlushStreamingTargetWriter_fn).call(this);