tui-cap 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1885 @@
1
+ /*
2
+ * mp4-muxer v5.2.2 — https://github.com/Vanilagy/mp4-muxer
3
+ * Vendored standalone ESM build. MIT License, Copyright (c) 2023 Vanilagy.
4
+ * Full license text in ./mp4-muxer.LICENSE. Bundled here (no build step) so the
5
+ * GUI can mux H.264 (WebCodecs) chunks into MP4 entirely in the browser.
6
+ */
7
+ var __accessCheck = (obj, member, msg) => {
8
+ if (!member.has(obj))
9
+ throw TypeError("Cannot " + msg);
10
+ };
11
+ var __privateGet = (obj, member, getter) => {
12
+ __accessCheck(obj, member, "read from private field");
13
+ return getter ? getter.call(obj) : member.get(obj);
14
+ };
15
+ var __privateAdd = (obj, member, value) => {
16
+ if (member.has(obj))
17
+ throw TypeError("Cannot add the same private member more than once");
18
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
19
+ };
20
+ var __privateSet = (obj, member, value, setter) => {
21
+ __accessCheck(obj, member, "write to private field");
22
+ setter ? setter.call(obj, value) : member.set(obj, value);
23
+ return value;
24
+ };
25
+ var __privateWrapper = (obj, member, setter, getter) => ({
26
+ set _(value) {
27
+ __privateSet(obj, member, value, setter);
28
+ },
29
+ get _() {
30
+ return __privateGet(obj, member, getter);
31
+ }
32
+ });
33
+ var __privateMethod = (obj, member, method) => {
34
+ __accessCheck(obj, member, "access private method");
35
+ return method;
36
+ };
37
+
38
+ // src/misc.ts
39
+ var bytes = new Uint8Array(8);
40
+ var view = new DataView(bytes.buffer);
41
+ var u8 = (value) => {
42
+ return [(value % 256 + 256) % 256];
43
+ };
44
+ var u16 = (value) => {
45
+ view.setUint16(0, value, false);
46
+ return [bytes[0], bytes[1]];
47
+ };
48
+ var i16 = (value) => {
49
+ view.setInt16(0, value, false);
50
+ return [bytes[0], bytes[1]];
51
+ };
52
+ var u24 = (value) => {
53
+ view.setUint32(0, value, false);
54
+ return [bytes[1], bytes[2], bytes[3]];
55
+ };
56
+ var u32 = (value) => {
57
+ view.setUint32(0, value, false);
58
+ return [bytes[0], bytes[1], bytes[2], bytes[3]];
59
+ };
60
+ var i32 = (value) => {
61
+ view.setInt32(0, value, false);
62
+ return [bytes[0], bytes[1], bytes[2], bytes[3]];
63
+ };
64
+ var u64 = (value) => {
65
+ view.setUint32(0, Math.floor(value / 2 ** 32), false);
66
+ view.setUint32(4, value, false);
67
+ return [bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]];
68
+ };
69
+ var fixed_8_8 = (value) => {
70
+ view.setInt16(0, 2 ** 8 * value, false);
71
+ return [bytes[0], bytes[1]];
72
+ };
73
+ var fixed_16_16 = (value) => {
74
+ view.setInt32(0, 2 ** 16 * value, false);
75
+ return [bytes[0], bytes[1], bytes[2], bytes[3]];
76
+ };
77
+ var fixed_2_30 = (value) => {
78
+ view.setInt32(0, 2 ** 30 * value, false);
79
+ return [bytes[0], bytes[1], bytes[2], bytes[3]];
80
+ };
81
+ var ascii = (text, nullTerminated = false) => {
82
+ let bytes2 = Array(text.length).fill(null).map((_, i) => text.charCodeAt(i));
83
+ if (nullTerminated)
84
+ bytes2.push(0);
85
+ return bytes2;
86
+ };
87
+ var last = (arr) => {
88
+ return arr && arr[arr.length - 1];
89
+ };
90
+ var lastPresentedSample = (samples) => {
91
+ let result = void 0;
92
+ for (let sample of samples) {
93
+ if (!result || sample.presentationTimestamp > result.presentationTimestamp) {
94
+ result = sample;
95
+ }
96
+ }
97
+ return result;
98
+ };
99
+ var intoTimescale = (timeInSeconds, timescale, round = true) => {
100
+ let value = timeInSeconds * timescale;
101
+ return round ? Math.round(value) : value;
102
+ };
103
+ var rotationMatrix = (rotationInDegrees) => {
104
+ let theta = rotationInDegrees * (Math.PI / 180);
105
+ let cosTheta = Math.cos(theta);
106
+ let sinTheta = Math.sin(theta);
107
+ return [
108
+ cosTheta,
109
+ sinTheta,
110
+ 0,
111
+ -sinTheta,
112
+ cosTheta,
113
+ 0,
114
+ 0,
115
+ 0,
116
+ 1
117
+ ];
118
+ };
119
+ var IDENTITY_MATRIX = rotationMatrix(0);
120
+ var matrixToBytes = (matrix) => {
121
+ return [
122
+ fixed_16_16(matrix[0]),
123
+ fixed_16_16(matrix[1]),
124
+ fixed_2_30(matrix[2]),
125
+ fixed_16_16(matrix[3]),
126
+ fixed_16_16(matrix[4]),
127
+ fixed_2_30(matrix[5]),
128
+ fixed_16_16(matrix[6]),
129
+ fixed_16_16(matrix[7]),
130
+ fixed_2_30(matrix[8])
131
+ ];
132
+ };
133
+ var deepClone = (x) => {
134
+ if (!x)
135
+ return x;
136
+ if (typeof x !== "object")
137
+ return x;
138
+ if (Array.isArray(x))
139
+ return x.map(deepClone);
140
+ return Object.fromEntries(Object.entries(x).map(([key, value]) => [key, deepClone(value)]));
141
+ };
142
+ var isU32 = (value) => {
143
+ return value >= 0 && value < 2 ** 32;
144
+ };
145
+
146
+ // src/box.ts
147
+ var box = (type, contents, children) => ({
148
+ type,
149
+ contents: contents && new Uint8Array(contents.flat(10)),
150
+ children
151
+ });
152
+ var fullBox = (type, version, flags, contents, children) => box(
153
+ type,
154
+ [u8(version), u24(flags), contents ?? []],
155
+ children
156
+ );
157
+ var ftyp = (details) => {
158
+ let minorVersion = 512;
159
+ if (details.fragmented)
160
+ return box("ftyp", [
161
+ ascii("iso5"),
162
+ // Major brand
163
+ u32(minorVersion),
164
+ // Minor version
165
+ // Compatible brands
166
+ ascii("iso5"),
167
+ ascii("iso6"),
168
+ ascii("mp41")
169
+ ]);
170
+ return box("ftyp", [
171
+ ascii("isom"),
172
+ // Major brand
173
+ u32(minorVersion),
174
+ // Minor version
175
+ // Compatible brands
176
+ ascii("isom"),
177
+ details.holdsAvc ? ascii("avc1") : [],
178
+ ascii("mp41")
179
+ ]);
180
+ };
181
+ var mdat = (reserveLargeSize) => ({ type: "mdat", largeSize: reserveLargeSize });
182
+ var free = (size) => ({ type: "free", size });
183
+ var moov = (tracks, creationTime, fragmented = false) => box("moov", null, [
184
+ mvhd(creationTime, tracks),
185
+ ...tracks.map((x) => trak(x, creationTime)),
186
+ fragmented ? mvex(tracks) : null
187
+ ]);
188
+ var mvhd = (creationTime, tracks) => {
189
+ let duration = intoTimescale(Math.max(
190
+ 0,
191
+ ...tracks.filter((x) => x.samples.length > 0).map((x) => {
192
+ const lastSample = lastPresentedSample(x.samples);
193
+ return lastSample.presentationTimestamp + lastSample.duration;
194
+ })
195
+ ), GLOBAL_TIMESCALE);
196
+ let nextTrackId = Math.max(...tracks.map((x) => x.id)) + 1;
197
+ let needsU64 = !isU32(creationTime) || !isU32(duration);
198
+ let u32OrU64 = needsU64 ? u64 : u32;
199
+ return fullBox("mvhd", +needsU64, 0, [
200
+ u32OrU64(creationTime),
201
+ // Creation time
202
+ u32OrU64(creationTime),
203
+ // Modification time
204
+ u32(GLOBAL_TIMESCALE),
205
+ // Timescale
206
+ u32OrU64(duration),
207
+ // Duration
208
+ fixed_16_16(1),
209
+ // Preferred rate
210
+ fixed_8_8(1),
211
+ // Preferred volume
212
+ Array(10).fill(0),
213
+ // Reserved
214
+ matrixToBytes(IDENTITY_MATRIX),
215
+ // Matrix
216
+ Array(24).fill(0),
217
+ // Pre-defined
218
+ u32(nextTrackId)
219
+ // Next track ID
220
+ ]);
221
+ };
222
+ var trak = (track, creationTime) => box("trak", null, [
223
+ tkhd(track, creationTime),
224
+ mdia(track, creationTime)
225
+ ]);
226
+ var tkhd = (track, creationTime) => {
227
+ let lastSample = lastPresentedSample(track.samples);
228
+ let durationInGlobalTimescale = intoTimescale(
229
+ lastSample ? lastSample.presentationTimestamp + lastSample.duration : 0,
230
+ GLOBAL_TIMESCALE
231
+ );
232
+ let needsU64 = !isU32(creationTime) || !isU32(durationInGlobalTimescale);
233
+ let u32OrU64 = needsU64 ? u64 : u32;
234
+ let matrix;
235
+ if (track.info.type === "video") {
236
+ matrix = typeof track.info.rotation === "number" ? rotationMatrix(track.info.rotation) : track.info.rotation;
237
+ } else {
238
+ matrix = IDENTITY_MATRIX;
239
+ }
240
+ return fullBox("tkhd", +needsU64, 3, [
241
+ u32OrU64(creationTime),
242
+ // Creation time
243
+ u32OrU64(creationTime),
244
+ // Modification time
245
+ u32(track.id),
246
+ // Track ID
247
+ u32(0),
248
+ // Reserved
249
+ u32OrU64(durationInGlobalTimescale),
250
+ // Duration
251
+ Array(8).fill(0),
252
+ // Reserved
253
+ u16(0),
254
+ // Layer
255
+ u16(0),
256
+ // Alternate group
257
+ fixed_8_8(track.info.type === "audio" ? 1 : 0),
258
+ // Volume
259
+ u16(0),
260
+ // Reserved
261
+ matrixToBytes(matrix),
262
+ // Matrix
263
+ fixed_16_16(track.info.type === "video" ? track.info.width : 0),
264
+ // Track width
265
+ fixed_16_16(track.info.type === "video" ? track.info.height : 0)
266
+ // Track height
267
+ ]);
268
+ };
269
+ var mdia = (track, creationTime) => box("mdia", null, [
270
+ mdhd(track, creationTime),
271
+ hdlr(track.info.type === "video" ? "vide" : "soun"),
272
+ minf(track)
273
+ ]);
274
+ var mdhd = (track, creationTime) => {
275
+ let lastSample = lastPresentedSample(track.samples);
276
+ let localDuration = intoTimescale(
277
+ lastSample ? lastSample.presentationTimestamp + lastSample.duration : 0,
278
+ track.timescale
279
+ );
280
+ let needsU64 = !isU32(creationTime) || !isU32(localDuration);
281
+ let u32OrU64 = needsU64 ? u64 : u32;
282
+ return fullBox("mdhd", +needsU64, 0, [
283
+ u32OrU64(creationTime),
284
+ // Creation time
285
+ u32OrU64(creationTime),
286
+ // Modification time
287
+ u32(track.timescale),
288
+ // Timescale
289
+ u32OrU64(localDuration),
290
+ // Duration
291
+ u16(21956),
292
+ // Language ("und", undetermined)
293
+ u16(0)
294
+ // Quality
295
+ ]);
296
+ };
297
+ var hdlr = (componentSubtype) => fullBox("hdlr", 0, 0, [
298
+ ascii("mhlr"),
299
+ // Component type
300
+ ascii(componentSubtype),
301
+ // Component subtype
302
+ u32(0),
303
+ // Component manufacturer
304
+ u32(0),
305
+ // Component flags
306
+ u32(0),
307
+ // Component flags mask
308
+ ascii("mp4-muxer-hdlr", true)
309
+ // Component name
310
+ ]);
311
+ var minf = (track) => box("minf", null, [
312
+ track.info.type === "video" ? vmhd() : smhd(),
313
+ dinf(),
314
+ stbl(track)
315
+ ]);
316
+ var vmhd = () => fullBox("vmhd", 0, 1, [
317
+ u16(0),
318
+ // Graphics mode
319
+ u16(0),
320
+ // Opcolor R
321
+ u16(0),
322
+ // Opcolor G
323
+ u16(0)
324
+ // Opcolor B
325
+ ]);
326
+ var smhd = () => fullBox("smhd", 0, 0, [
327
+ u16(0),
328
+ // Balance
329
+ u16(0)
330
+ // Reserved
331
+ ]);
332
+ var dinf = () => box("dinf", null, [
333
+ dref()
334
+ ]);
335
+ var dref = () => fullBox("dref", 0, 0, [
336
+ u32(1)
337
+ // Entry count
338
+ ], [
339
+ url()
340
+ ]);
341
+ var url = () => fullBox("url ", 0, 1);
342
+ var stbl = (track) => {
343
+ const needsCtts = track.compositionTimeOffsetTable.length > 1 || track.compositionTimeOffsetTable.some((x) => x.sampleCompositionTimeOffset !== 0);
344
+ return box("stbl", null, [
345
+ stsd(track),
346
+ stts(track),
347
+ stss(track),
348
+ stsc(track),
349
+ stsz(track),
350
+ stco(track),
351
+ needsCtts ? ctts(track) : null
352
+ ]);
353
+ };
354
+ var stsd = (track) => fullBox("stsd", 0, 0, [
355
+ u32(1)
356
+ // Entry count
357
+ ], [
358
+ track.info.type === "video" ? videoSampleDescription(
359
+ VIDEO_CODEC_TO_BOX_NAME[track.info.codec],
360
+ track
361
+ ) : soundSampleDescription(
362
+ AUDIO_CODEC_TO_BOX_NAME[track.info.codec],
363
+ track
364
+ )
365
+ ]);
366
+ var videoSampleDescription = (compressionType, track) => box(compressionType, [
367
+ Array(6).fill(0),
368
+ // Reserved
369
+ u16(1),
370
+ // Data reference index
371
+ u16(0),
372
+ // Pre-defined
373
+ u16(0),
374
+ // Reserved
375
+ Array(12).fill(0),
376
+ // Pre-defined
377
+ u16(track.info.width),
378
+ // Width
379
+ u16(track.info.height),
380
+ // Height
381
+ u32(4718592),
382
+ // Horizontal resolution
383
+ u32(4718592),
384
+ // Vertical resolution
385
+ u32(0),
386
+ // Reserved
387
+ u16(1),
388
+ // Frame count
389
+ Array(32).fill(0),
390
+ // Compressor name
391
+ u16(24),
392
+ // Depth
393
+ i16(65535)
394
+ // Pre-defined
395
+ ], [
396
+ VIDEO_CODEC_TO_CONFIGURATION_BOX[track.info.codec](track),
397
+ track.info.decoderConfig.colorSpace ? colr(track) : null
398
+ ]);
399
+ var COLOR_PRIMARIES_MAP = {
400
+ "bt709": 1,
401
+ // ITU-R BT.709
402
+ "bt470bg": 5,
403
+ // ITU-R BT.470BG
404
+ "smpte170m": 6
405
+ // ITU-R BT.601 525 - SMPTE 170M
406
+ };
407
+ var TRANSFER_CHARACTERISTICS_MAP = {
408
+ "bt709": 1,
409
+ // ITU-R BT.709
410
+ "smpte170m": 6,
411
+ // SMPTE 170M
412
+ "iec61966-2-1": 13
413
+ // IEC 61966-2-1
414
+ };
415
+ var MATRIX_COEFFICIENTS_MAP = {
416
+ "rgb": 0,
417
+ // Identity
418
+ "bt709": 1,
419
+ // ITU-R BT.709
420
+ "bt470bg": 5,
421
+ // ITU-R BT.470BG
422
+ "smpte170m": 6
423
+ // SMPTE 170M
424
+ };
425
+ var colr = (track) => box("colr", [
426
+ ascii("nclx"),
427
+ // Colour type
428
+ u16(COLOR_PRIMARIES_MAP[track.info.decoderConfig.colorSpace.primaries]),
429
+ // Colour primaries
430
+ u16(TRANSFER_CHARACTERISTICS_MAP[track.info.decoderConfig.colorSpace.transfer]),
431
+ // Transfer characteristics
432
+ u16(MATRIX_COEFFICIENTS_MAP[track.info.decoderConfig.colorSpace.matrix]),
433
+ // Matrix coefficients
434
+ u8((track.info.decoderConfig.colorSpace.fullRange ? 1 : 0) << 7)
435
+ // Full range flag
436
+ ]);
437
+ var avcC = (track) => track.info.decoderConfig && box("avcC", [
438
+ // For AVC, description is an AVCDecoderConfigurationRecord, so nothing else to do here
439
+ ...new Uint8Array(track.info.decoderConfig.description)
440
+ ]);
441
+ var hvcC = (track) => track.info.decoderConfig && box("hvcC", [
442
+ // For HEVC, description is a HEVCDecoderConfigurationRecord, so nothing else to do here
443
+ ...new Uint8Array(track.info.decoderConfig.description)
444
+ ]);
445
+ var vpcC = (track) => {
446
+ if (!track.info.decoderConfig) {
447
+ return null;
448
+ }
449
+ let decoderConfig = track.info.decoderConfig;
450
+ if (!decoderConfig.colorSpace) {
451
+ throw new Error(`'colorSpace' is required in the decoder config for VP9.`);
452
+ }
453
+ let parts = decoderConfig.codec.split(".");
454
+ let profile = Number(parts[1]);
455
+ let level = Number(parts[2]);
456
+ let bitDepth = Number(parts[3]);
457
+ let chromaSubsampling = 0;
458
+ let thirdByte = (bitDepth << 4) + (chromaSubsampling << 1) + Number(decoderConfig.colorSpace.fullRange);
459
+ let colourPrimaries = 2;
460
+ let transferCharacteristics = 2;
461
+ let matrixCoefficients = 2;
462
+ return fullBox("vpcC", 1, 0, [
463
+ u8(profile),
464
+ // Profile
465
+ u8(level),
466
+ // Level
467
+ u8(thirdByte),
468
+ // Bit depth, chroma subsampling, full range
469
+ u8(colourPrimaries),
470
+ // Colour primaries
471
+ u8(transferCharacteristics),
472
+ // Transfer characteristics
473
+ u8(matrixCoefficients),
474
+ // Matrix coefficients
475
+ u16(0)
476
+ // Codec initialization data size
477
+ ]);
478
+ };
479
+ var av1C = () => {
480
+ let marker = 1;
481
+ let version = 1;
482
+ let firstByte = (marker << 7) + version;
483
+ return box("av1C", [
484
+ firstByte,
485
+ 0,
486
+ 0,
487
+ 0
488
+ ]);
489
+ };
490
+ var soundSampleDescription = (compressionType, track) => box(compressionType, [
491
+ Array(6).fill(0),
492
+ // Reserved
493
+ u16(1),
494
+ // Data reference index
495
+ u16(0),
496
+ // Version
497
+ u16(0),
498
+ // Revision level
499
+ u32(0),
500
+ // Vendor
501
+ u16(track.info.numberOfChannels),
502
+ // Number of channels
503
+ u16(16),
504
+ // Sample size (bits)
505
+ u16(0),
506
+ // Compression ID
507
+ u16(0),
508
+ // Packet size
509
+ fixed_16_16(track.info.sampleRate)
510
+ // Sample rate
511
+ ], [
512
+ AUDIO_CODEC_TO_CONFIGURATION_BOX[track.info.codec](track)
513
+ ]);
514
+ var esds = (track) => {
515
+ let description = new Uint8Array(track.info.decoderConfig.description);
516
+ return fullBox("esds", 0, 0, [
517
+ // https://stackoverflow.com/a/54803118
518
+ u32(58753152),
519
+ // TAG(3) = Object Descriptor ([2])
520
+ u8(32 + description.byteLength),
521
+ // length of this OD (which includes the next 2 tags)
522
+ u16(1),
523
+ // ES_ID = 1
524
+ u8(0),
525
+ // flags etc = 0
526
+ u32(75530368),
527
+ // TAG(4) = ES Descriptor ([2]) embedded in above OD
528
+ u8(18 + description.byteLength),
529
+ // length of this ESD
530
+ u8(64),
531
+ // MPEG-4 Audio
532
+ u8(21),
533
+ // stream type(6bits)=5 audio, flags(2bits)=1
534
+ u24(0),
535
+ // 24bit buffer size
536
+ u32(130071),
537
+ // max bitrate
538
+ u32(130071),
539
+ // avg bitrate
540
+ u32(92307584),
541
+ // TAG(5) = ASC ([2],[3]) embedded in above OD
542
+ u8(description.byteLength),
543
+ // length
544
+ ...description,
545
+ u32(109084800),
546
+ // TAG(6)
547
+ u8(1),
548
+ // length
549
+ u8(2)
550
+ // data
551
+ ]);
552
+ };
553
+ var dOps = (track) => {
554
+ let preskip = 3840;
555
+ let gain = 0;
556
+ const description = track.info.decoderConfig?.description;
557
+ if (description) {
558
+ if (description.byteLength < 18) {
559
+ throw new TypeError("Invalid decoder description provided for Opus; must be at least 18 bytes long.");
560
+ }
561
+ const view2 = ArrayBuffer.isView(description) ? new DataView(description.buffer, description.byteOffset, description.byteLength) : new DataView(description);
562
+ preskip = view2.getUint16(10, true);
563
+ gain = view2.getInt16(14, true);
564
+ }
565
+ return box("dOps", [
566
+ u8(0),
567
+ // Version
568
+ u8(track.info.numberOfChannels),
569
+ // OutputChannelCount
570
+ u16(preskip),
571
+ u32(track.info.sampleRate),
572
+ // InputSampleRate
573
+ fixed_8_8(gain),
574
+ // OutputGain
575
+ u8(0)
576
+ // ChannelMappingFamily
577
+ ]);
578
+ };
579
+ var stts = (track) => {
580
+ return fullBox("stts", 0, 0, [
581
+ u32(track.timeToSampleTable.length),
582
+ // Number of entries
583
+ track.timeToSampleTable.map((x) => [
584
+ // Time-to-sample table
585
+ u32(x.sampleCount),
586
+ // Sample count
587
+ u32(x.sampleDelta)
588
+ // Sample duration
589
+ ])
590
+ ]);
591
+ };
592
+ var stss = (track) => {
593
+ if (track.samples.every((x) => x.type === "key"))
594
+ return null;
595
+ let keySamples = [...track.samples.entries()].filter(([, sample]) => sample.type === "key");
596
+ return fullBox("stss", 0, 0, [
597
+ u32(keySamples.length),
598
+ // Number of entries
599
+ keySamples.map(([index]) => u32(index + 1))
600
+ // Sync sample table
601
+ ]);
602
+ };
603
+ var stsc = (track) => {
604
+ return fullBox("stsc", 0, 0, [
605
+ u32(track.compactlyCodedChunkTable.length),
606
+ // Number of entries
607
+ track.compactlyCodedChunkTable.map((x) => [
608
+ // Sample-to-chunk table
609
+ u32(x.firstChunk),
610
+ // First chunk
611
+ u32(x.samplesPerChunk),
612
+ // Samples per chunk
613
+ u32(1)
614
+ // Sample description index
615
+ ])
616
+ ]);
617
+ };
618
+ var stsz = (track) => fullBox("stsz", 0, 0, [
619
+ u32(0),
620
+ // Sample size (0 means non-constant size)
621
+ u32(track.samples.length),
622
+ // Number of entries
623
+ track.samples.map((x) => u32(x.size))
624
+ // Sample size table
625
+ ]);
626
+ var stco = (track) => {
627
+ if (track.finalizedChunks.length > 0 && last(track.finalizedChunks).offset >= 2 ** 32) {
628
+ return fullBox("co64", 0, 0, [
629
+ u32(track.finalizedChunks.length),
630
+ // Number of entries
631
+ track.finalizedChunks.map((x) => u64(x.offset))
632
+ // Chunk offset table
633
+ ]);
634
+ }
635
+ return fullBox("stco", 0, 0, [
636
+ u32(track.finalizedChunks.length),
637
+ // Number of entries
638
+ track.finalizedChunks.map((x) => u32(x.offset))
639
+ // Chunk offset table
640
+ ]);
641
+ };
642
+ var ctts = (track) => {
643
+ return fullBox("ctts", 0, 0, [
644
+ u32(track.compositionTimeOffsetTable.length),
645
+ // Number of entries
646
+ track.compositionTimeOffsetTable.map((x) => [
647
+ // Time-to-sample table
648
+ u32(x.sampleCount),
649
+ // Sample count
650
+ u32(x.sampleCompositionTimeOffset)
651
+ // Sample offset
652
+ ])
653
+ ]);
654
+ };
655
+ var mvex = (tracks) => {
656
+ return box("mvex", null, tracks.map(trex));
657
+ };
658
+ var trex = (track) => {
659
+ return fullBox("trex", 0, 0, [
660
+ u32(track.id),
661
+ // Track ID
662
+ u32(1),
663
+ // Default sample description index
664
+ u32(0),
665
+ // Default sample duration
666
+ u32(0),
667
+ // Default sample size
668
+ u32(0)
669
+ // Default sample flags
670
+ ]);
671
+ };
672
+ var moof = (sequenceNumber, tracks) => {
673
+ return box("moof", null, [
674
+ mfhd(sequenceNumber),
675
+ ...tracks.map(traf)
676
+ ]);
677
+ };
678
+ var mfhd = (sequenceNumber) => {
679
+ return fullBox("mfhd", 0, 0, [
680
+ u32(sequenceNumber)
681
+ // Sequence number
682
+ ]);
683
+ };
684
+ var fragmentSampleFlags = (sample) => {
685
+ let byte1 = 0;
686
+ let byte2 = 0;
687
+ let byte3 = 0;
688
+ let byte4 = 0;
689
+ let sampleIsDifferenceSample = sample.type === "delta";
690
+ byte2 |= +sampleIsDifferenceSample;
691
+ if (sampleIsDifferenceSample) {
692
+ byte1 |= 1;
693
+ } else {
694
+ byte1 |= 2;
695
+ }
696
+ return byte1 << 24 | byte2 << 16 | byte3 << 8 | byte4;
697
+ };
698
+ var traf = (track) => {
699
+ return box("traf", null, [
700
+ tfhd(track),
701
+ tfdt(track),
702
+ trun(track)
703
+ ]);
704
+ };
705
+ var tfhd = (track) => {
706
+ let tfFlags = 0;
707
+ tfFlags |= 8;
708
+ tfFlags |= 16;
709
+ tfFlags |= 32;
710
+ tfFlags |= 131072;
711
+ let referenceSample = track.currentChunk.samples[1] ?? track.currentChunk.samples[0];
712
+ let referenceSampleInfo = {
713
+ duration: referenceSample.timescaleUnitsToNextSample,
714
+ size: referenceSample.size,
715
+ flags: fragmentSampleFlags(referenceSample)
716
+ };
717
+ return fullBox("tfhd", 0, tfFlags, [
718
+ u32(track.id),
719
+ // Track ID
720
+ u32(referenceSampleInfo.duration),
721
+ // Default sample duration
722
+ u32(referenceSampleInfo.size),
723
+ // Default sample size
724
+ u32(referenceSampleInfo.flags)
725
+ // Default sample flags
726
+ ]);
727
+ };
728
+ var tfdt = (track) => {
729
+ return fullBox("tfdt", 1, 0, [
730
+ u64(intoTimescale(track.currentChunk.startTimestamp, track.timescale))
731
+ // Base Media Decode Time
732
+ ]);
733
+ };
734
+ var trun = (track) => {
735
+ let allSampleDurations = track.currentChunk.samples.map((x) => x.timescaleUnitsToNextSample);
736
+ let allSampleSizes = track.currentChunk.samples.map((x) => x.size);
737
+ let allSampleFlags = track.currentChunk.samples.map(fragmentSampleFlags);
738
+ let allSampleCompositionTimeOffsets = track.currentChunk.samples.map((x) => intoTimescale(x.presentationTimestamp - x.decodeTimestamp, track.timescale));
739
+ let uniqueSampleDurations = new Set(allSampleDurations);
740
+ let uniqueSampleSizes = new Set(allSampleSizes);
741
+ let uniqueSampleFlags = new Set(allSampleFlags);
742
+ let uniqueSampleCompositionTimeOffsets = new Set(allSampleCompositionTimeOffsets);
743
+ let firstSampleFlagsPresent = uniqueSampleFlags.size === 2 && allSampleFlags[0] !== allSampleFlags[1];
744
+ let sampleDurationPresent = uniqueSampleDurations.size > 1;
745
+ let sampleSizePresent = uniqueSampleSizes.size > 1;
746
+ let sampleFlagsPresent = !firstSampleFlagsPresent && uniqueSampleFlags.size > 1;
747
+ let sampleCompositionTimeOffsetsPresent = uniqueSampleCompositionTimeOffsets.size > 1 || [...uniqueSampleCompositionTimeOffsets].some((x) => x !== 0);
748
+ let flags = 0;
749
+ flags |= 1;
750
+ flags |= 4 * +firstSampleFlagsPresent;
751
+ flags |= 256 * +sampleDurationPresent;
752
+ flags |= 512 * +sampleSizePresent;
753
+ flags |= 1024 * +sampleFlagsPresent;
754
+ flags |= 2048 * +sampleCompositionTimeOffsetsPresent;
755
+ return fullBox("trun", 1, flags, [
756
+ u32(track.currentChunk.samples.length),
757
+ // Sample count
758
+ u32(track.currentChunk.offset - track.currentChunk.moofOffset || 0),
759
+ // Data offset
760
+ firstSampleFlagsPresent ? u32(allSampleFlags[0]) : [],
761
+ track.currentChunk.samples.map((_, i) => [
762
+ sampleDurationPresent ? u32(allSampleDurations[i]) : [],
763
+ // Sample duration
764
+ sampleSizePresent ? u32(allSampleSizes[i]) : [],
765
+ // Sample size
766
+ sampleFlagsPresent ? u32(allSampleFlags[i]) : [],
767
+ // Sample flags
768
+ // Sample composition time offsets
769
+ sampleCompositionTimeOffsetsPresent ? i32(allSampleCompositionTimeOffsets[i]) : []
770
+ ])
771
+ ]);
772
+ };
773
+ var mfra = (tracks) => {
774
+ return box("mfra", null, [
775
+ ...tracks.map(tfra),
776
+ mfro()
777
+ ]);
778
+ };
779
+ var tfra = (track, trackIndex) => {
780
+ let version = 1;
781
+ return fullBox("tfra", version, 0, [
782
+ u32(track.id),
783
+ // Track ID
784
+ u32(63),
785
+ // This specifies that traf number, trun number and sample number are 32-bit ints
786
+ u32(track.finalizedChunks.length),
787
+ // Number of entries
788
+ track.finalizedChunks.map((chunk) => [
789
+ u64(intoTimescale(chunk.startTimestamp, track.timescale)),
790
+ // Time
791
+ u64(chunk.moofOffset),
792
+ // moof offset
793
+ u32(trackIndex + 1),
794
+ // traf number
795
+ u32(1),
796
+ // trun number
797
+ u32(1)
798
+ // Sample number
799
+ ])
800
+ ]);
801
+ };
802
+ var mfro = () => {
803
+ return fullBox("mfro", 0, 0, [
804
+ // This value needs to be overwritten manually from the outside, where the actual size of the enclosing mfra box
805
+ // is known
806
+ u32(0)
807
+ // Size
808
+ ]);
809
+ };
810
+ var VIDEO_CODEC_TO_BOX_NAME = {
811
+ "avc": "avc1",
812
+ "hevc": "hvc1",
813
+ "vp9": "vp09",
814
+ "av1": "av01"
815
+ };
816
+ var VIDEO_CODEC_TO_CONFIGURATION_BOX = {
817
+ "avc": avcC,
818
+ "hevc": hvcC,
819
+ "vp9": vpcC,
820
+ "av1": av1C
821
+ };
822
+ var AUDIO_CODEC_TO_BOX_NAME = {
823
+ "aac": "mp4a",
824
+ "opus": "Opus"
825
+ };
826
+ var AUDIO_CODEC_TO_CONFIGURATION_BOX = {
827
+ "aac": esds,
828
+ "opus": dOps
829
+ };
830
+
831
+ // src/target.ts
832
+ var isTarget = Symbol("isTarget");
833
+ var Target = class {
834
+ };
835
+ isTarget;
836
+ var ArrayBufferTarget = class extends Target {
837
+ constructor() {
838
+ super(...arguments);
839
+ this.buffer = null;
840
+ }
841
+ };
842
+ var StreamTarget = class extends Target {
843
+ constructor(options) {
844
+ super();
845
+ this.options = options;
846
+ if (typeof options !== "object") {
847
+ throw new TypeError("StreamTarget requires an options object to be passed to its constructor.");
848
+ }
849
+ if (options.onData) {
850
+ if (typeof options.onData !== "function") {
851
+ throw new TypeError("options.onData, when provided, must be a function.");
852
+ }
853
+ if (options.onData.length < 2) {
854
+ throw new TypeError(
855
+ "options.onData, when provided, must be a function that takes in at least two arguments (data and position). Ignoring the position argument, which specifies the byte offset at which the data is to be written, can lead to broken outputs."
856
+ );
857
+ }
858
+ }
859
+ if (options.chunked !== void 0 && typeof options.chunked !== "boolean") {
860
+ throw new TypeError("options.chunked, when provided, must be a boolean.");
861
+ }
862
+ if (options.chunkSize !== void 0 && (!Number.isInteger(options.chunkSize) || options.chunkSize < 1024)) {
863
+ throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");
864
+ }
865
+ }
866
+ };
867
+ var FileSystemWritableFileStreamTarget = class extends Target {
868
+ constructor(stream, options) {
869
+ super();
870
+ this.stream = stream;
871
+ this.options = options;
872
+ if (!(stream instanceof FileSystemWritableFileStream)) {
873
+ throw new TypeError("FileSystemWritableFileStreamTarget requires a FileSystemWritableFileStream instance.");
874
+ }
875
+ if (options !== void 0 && typeof options !== "object") {
876
+ throw new TypeError("FileSystemWritableFileStreamTarget's options, when provided, must be an object.");
877
+ }
878
+ if (options) {
879
+ if (options.chunkSize !== void 0 && (!Number.isInteger(options.chunkSize) || options.chunkSize <= 0)) {
880
+ throw new TypeError("options.chunkSize, when provided, must be a positive integer");
881
+ }
882
+ }
883
+ }
884
+ };
885
+
886
+ // src/writer.ts
887
+ var _helper, _helperView;
888
+ var Writer = class {
889
+ constructor() {
890
+ this.pos = 0;
891
+ __privateAdd(this, _helper, new Uint8Array(8));
892
+ __privateAdd(this, _helperView, new DataView(__privateGet(this, _helper).buffer));
893
+ /**
894
+ * Stores the position from the start of the file to where boxes elements have been written. This is used to
895
+ * rewrite/edit elements that were already added before, and to measure sizes of things.
896
+ */
897
+ this.offsets = /* @__PURE__ */ new WeakMap();
898
+ }
899
+ /** Sets the current position for future writes to a new one. */
900
+ seek(newPos) {
901
+ this.pos = newPos;
902
+ }
903
+ writeU32(value) {
904
+ __privateGet(this, _helperView).setUint32(0, value, false);
905
+ this.write(__privateGet(this, _helper).subarray(0, 4));
906
+ }
907
+ writeU64(value) {
908
+ __privateGet(this, _helperView).setUint32(0, Math.floor(value / 2 ** 32), false);
909
+ __privateGet(this, _helperView).setUint32(4, value, false);
910
+ this.write(__privateGet(this, _helper).subarray(0, 8));
911
+ }
912
+ writeAscii(text) {
913
+ for (let i = 0; i < text.length; i++) {
914
+ __privateGet(this, _helperView).setUint8(i % 8, text.charCodeAt(i));
915
+ if (i % 8 === 7)
916
+ this.write(__privateGet(this, _helper));
917
+ }
918
+ if (text.length % 8 !== 0) {
919
+ this.write(__privateGet(this, _helper).subarray(0, text.length % 8));
920
+ }
921
+ }
922
+ writeBox(box2) {
923
+ this.offsets.set(box2, this.pos);
924
+ if (box2.contents && !box2.children) {
925
+ this.writeBoxHeader(box2, box2.size ?? box2.contents.byteLength + 8);
926
+ this.write(box2.contents);
927
+ } else {
928
+ let startPos = this.pos;
929
+ this.writeBoxHeader(box2, 0);
930
+ if (box2.contents)
931
+ this.write(box2.contents);
932
+ if (box2.children) {
933
+ for (let child of box2.children)
934
+ if (child)
935
+ this.writeBox(child);
936
+ }
937
+ let endPos = this.pos;
938
+ let size = box2.size ?? endPos - startPos;
939
+ this.seek(startPos);
940
+ this.writeBoxHeader(box2, size);
941
+ this.seek(endPos);
942
+ }
943
+ }
944
+ writeBoxHeader(box2, size) {
945
+ this.writeU32(box2.largeSize ? 1 : size);
946
+ this.writeAscii(box2.type);
947
+ if (box2.largeSize)
948
+ this.writeU64(size);
949
+ }
950
+ measureBoxHeader(box2) {
951
+ return 8 + (box2.largeSize ? 8 : 0);
952
+ }
953
+ patchBox(box2) {
954
+ let endPos = this.pos;
955
+ this.seek(this.offsets.get(box2));
956
+ this.writeBox(box2);
957
+ this.seek(endPos);
958
+ }
959
+ measureBox(box2) {
960
+ if (box2.contents && !box2.children) {
961
+ let headerSize = this.measureBoxHeader(box2);
962
+ return headerSize + box2.contents.byteLength;
963
+ } else {
964
+ let result = this.measureBoxHeader(box2);
965
+ if (box2.contents)
966
+ result += box2.contents.byteLength;
967
+ if (box2.children) {
968
+ for (let child of box2.children)
969
+ if (child)
970
+ result += this.measureBox(child);
971
+ }
972
+ return result;
973
+ }
974
+ }
975
+ };
976
+ _helper = new WeakMap();
977
+ _helperView = new WeakMap();
978
+ var _target, _buffer, _bytes, _maxPos, _ensureSize, ensureSize_fn;
979
+ var ArrayBufferTargetWriter = class extends Writer {
980
+ constructor(target) {
981
+ super();
982
+ __privateAdd(this, _ensureSize);
983
+ __privateAdd(this, _target, void 0);
984
+ __privateAdd(this, _buffer, new ArrayBuffer(2 ** 16));
985
+ __privateAdd(this, _bytes, new Uint8Array(__privateGet(this, _buffer)));
986
+ __privateAdd(this, _maxPos, 0);
987
+ __privateSet(this, _target, target);
988
+ }
989
+ write(data) {
990
+ __privateMethod(this, _ensureSize, ensureSize_fn).call(this, this.pos + data.byteLength);
991
+ __privateGet(this, _bytes).set(data, this.pos);
992
+ this.pos += data.byteLength;
993
+ __privateSet(this, _maxPos, Math.max(__privateGet(this, _maxPos), this.pos));
994
+ }
995
+ finalize() {
996
+ __privateMethod(this, _ensureSize, ensureSize_fn).call(this, this.pos);
997
+ __privateGet(this, _target).buffer = __privateGet(this, _buffer).slice(0, Math.max(__privateGet(this, _maxPos), this.pos));
998
+ }
999
+ };
1000
+ _target = new WeakMap();
1001
+ _buffer = new WeakMap();
1002
+ _bytes = new WeakMap();
1003
+ _maxPos = new WeakMap();
1004
+ _ensureSize = new WeakSet();
1005
+ ensureSize_fn = function(size) {
1006
+ let newLength = __privateGet(this, _buffer).byteLength;
1007
+ while (newLength < size)
1008
+ newLength *= 2;
1009
+ if (newLength === __privateGet(this, _buffer).byteLength)
1010
+ return;
1011
+ let newBuffer = new ArrayBuffer(newLength);
1012
+ let newBytes = new Uint8Array(newBuffer);
1013
+ newBytes.set(__privateGet(this, _bytes), 0);
1014
+ __privateSet(this, _buffer, newBuffer);
1015
+ __privateSet(this, _bytes, newBytes);
1016
+ };
1017
+ var DEFAULT_CHUNK_SIZE = 2 ** 24;
1018
+ var MAX_CHUNKS_AT_ONCE = 2;
1019
+ var _target2, _sections, _chunked, _chunkSize, _chunks, _writeDataIntoChunks, writeDataIntoChunks_fn, _insertSectionIntoChunk, insertSectionIntoChunk_fn, _createChunk, createChunk_fn, _flushChunks, flushChunks_fn;
1020
+ var StreamTargetWriter = class extends Writer {
1021
+ constructor(target) {
1022
+ super();
1023
+ __privateAdd(this, _writeDataIntoChunks);
1024
+ __privateAdd(this, _insertSectionIntoChunk);
1025
+ __privateAdd(this, _createChunk);
1026
+ __privateAdd(this, _flushChunks);
1027
+ __privateAdd(this, _target2, void 0);
1028
+ __privateAdd(this, _sections, []);
1029
+ __privateAdd(this, _chunked, void 0);
1030
+ __privateAdd(this, _chunkSize, void 0);
1031
+ /**
1032
+ * The data is divided up into fixed-size chunks, whose contents are first filled in RAM and then flushed out.
1033
+ * A chunk is flushed if all of its contents have been written.
1034
+ */
1035
+ __privateAdd(this, _chunks, []);
1036
+ __privateSet(this, _target2, target);
1037
+ __privateSet(this, _chunked, target.options?.chunked ?? false);
1038
+ __privateSet(this, _chunkSize, target.options?.chunkSize ?? DEFAULT_CHUNK_SIZE);
1039
+ }
1040
+ write(data) {
1041
+ __privateGet(this, _sections).push({
1042
+ data: data.slice(),
1043
+ start: this.pos
1044
+ });
1045
+ this.pos += data.byteLength;
1046
+ }
1047
+ flush() {
1048
+ if (__privateGet(this, _sections).length === 0)
1049
+ return;
1050
+ let chunks = [];
1051
+ let sorted = [...__privateGet(this, _sections)].sort((a, b) => a.start - b.start);
1052
+ chunks.push({
1053
+ start: sorted[0].start,
1054
+ size: sorted[0].data.byteLength
1055
+ });
1056
+ for (let i = 1; i < sorted.length; i++) {
1057
+ let lastChunk = chunks[chunks.length - 1];
1058
+ let section = sorted[i];
1059
+ if (section.start <= lastChunk.start + lastChunk.size) {
1060
+ lastChunk.size = Math.max(lastChunk.size, section.start + section.data.byteLength - lastChunk.start);
1061
+ } else {
1062
+ chunks.push({
1063
+ start: section.start,
1064
+ size: section.data.byteLength
1065
+ });
1066
+ }
1067
+ }
1068
+ for (let chunk of chunks) {
1069
+ chunk.data = new Uint8Array(chunk.size);
1070
+ for (let section of __privateGet(this, _sections)) {
1071
+ if (chunk.start <= section.start && section.start < chunk.start + chunk.size) {
1072
+ chunk.data.set(section.data, section.start - chunk.start);
1073
+ }
1074
+ }
1075
+ if (__privateGet(this, _chunked)) {
1076
+ __privateMethod(this, _writeDataIntoChunks, writeDataIntoChunks_fn).call(this, chunk.data, chunk.start);
1077
+ __privateMethod(this, _flushChunks, flushChunks_fn).call(this);
1078
+ } else {
1079
+ __privateGet(this, _target2).options.onData?.(chunk.data, chunk.start);
1080
+ }
1081
+ }
1082
+ __privateGet(this, _sections).length = 0;
1083
+ }
1084
+ finalize() {
1085
+ if (__privateGet(this, _chunked)) {
1086
+ __privateMethod(this, _flushChunks, flushChunks_fn).call(this, true);
1087
+ }
1088
+ }
1089
+ };
1090
+ _target2 = new WeakMap();
1091
+ _sections = new WeakMap();
1092
+ _chunked = new WeakMap();
1093
+ _chunkSize = new WeakMap();
1094
+ _chunks = new WeakMap();
1095
+ _writeDataIntoChunks = new WeakSet();
1096
+ writeDataIntoChunks_fn = function(data, position) {
1097
+ let chunkIndex = __privateGet(this, _chunks).findIndex((x) => x.start <= position && position < x.start + __privateGet(this, _chunkSize));
1098
+ if (chunkIndex === -1)
1099
+ chunkIndex = __privateMethod(this, _createChunk, createChunk_fn).call(this, position);
1100
+ let chunk = __privateGet(this, _chunks)[chunkIndex];
1101
+ let relativePosition = position - chunk.start;
1102
+ let toWrite = data.subarray(0, Math.min(__privateGet(this, _chunkSize) - relativePosition, data.byteLength));
1103
+ chunk.data.set(toWrite, relativePosition);
1104
+ let section = {
1105
+ start: relativePosition,
1106
+ end: relativePosition + toWrite.byteLength
1107
+ };
1108
+ __privateMethod(this, _insertSectionIntoChunk, insertSectionIntoChunk_fn).call(this, chunk, section);
1109
+ if (chunk.written[0].start === 0 && chunk.written[0].end === __privateGet(this, _chunkSize)) {
1110
+ chunk.shouldFlush = true;
1111
+ }
1112
+ if (__privateGet(this, _chunks).length > MAX_CHUNKS_AT_ONCE) {
1113
+ for (let i = 0; i < __privateGet(this, _chunks).length - 1; i++) {
1114
+ __privateGet(this, _chunks)[i].shouldFlush = true;
1115
+ }
1116
+ __privateMethod(this, _flushChunks, flushChunks_fn).call(this);
1117
+ }
1118
+ if (toWrite.byteLength < data.byteLength) {
1119
+ __privateMethod(this, _writeDataIntoChunks, writeDataIntoChunks_fn).call(this, data.subarray(toWrite.byteLength), position + toWrite.byteLength);
1120
+ }
1121
+ };
1122
+ _insertSectionIntoChunk = new WeakSet();
1123
+ insertSectionIntoChunk_fn = function(chunk, section) {
1124
+ let low = 0;
1125
+ let high = chunk.written.length - 1;
1126
+ let index = -1;
1127
+ while (low <= high) {
1128
+ let mid = Math.floor(low + (high - low + 1) / 2);
1129
+ if (chunk.written[mid].start <= section.start) {
1130
+ low = mid + 1;
1131
+ index = mid;
1132
+ } else {
1133
+ high = mid - 1;
1134
+ }
1135
+ }
1136
+ chunk.written.splice(index + 1, 0, section);
1137
+ if (index === -1 || chunk.written[index].end < section.start)
1138
+ index++;
1139
+ while (index < chunk.written.length - 1 && chunk.written[index].end >= chunk.written[index + 1].start) {
1140
+ chunk.written[index].end = Math.max(chunk.written[index].end, chunk.written[index + 1].end);
1141
+ chunk.written.splice(index + 1, 1);
1142
+ }
1143
+ };
1144
+ _createChunk = new WeakSet();
1145
+ createChunk_fn = function(includesPosition) {
1146
+ let start = Math.floor(includesPosition / __privateGet(this, _chunkSize)) * __privateGet(this, _chunkSize);
1147
+ let chunk = {
1148
+ start,
1149
+ data: new Uint8Array(__privateGet(this, _chunkSize)),
1150
+ written: [],
1151
+ shouldFlush: false
1152
+ };
1153
+ __privateGet(this, _chunks).push(chunk);
1154
+ __privateGet(this, _chunks).sort((a, b) => a.start - b.start);
1155
+ return __privateGet(this, _chunks).indexOf(chunk);
1156
+ };
1157
+ _flushChunks = new WeakSet();
1158
+ flushChunks_fn = function(force = false) {
1159
+ for (let i = 0; i < __privateGet(this, _chunks).length; i++) {
1160
+ let chunk = __privateGet(this, _chunks)[i];
1161
+ if (!chunk.shouldFlush && !force)
1162
+ continue;
1163
+ for (let section of chunk.written) {
1164
+ __privateGet(this, _target2).options.onData?.(
1165
+ chunk.data.subarray(section.start, section.end),
1166
+ chunk.start + section.start
1167
+ );
1168
+ }
1169
+ __privateGet(this, _chunks).splice(i--, 1);
1170
+ }
1171
+ };
1172
+ var FileSystemWritableFileStreamTargetWriter = class extends StreamTargetWriter {
1173
+ constructor(target) {
1174
+ super(new StreamTarget({
1175
+ onData: (data, position) => target.stream.write({
1176
+ type: "write",
1177
+ data,
1178
+ position
1179
+ }),
1180
+ chunked: true,
1181
+ chunkSize: target.options?.chunkSize
1182
+ }));
1183
+ }
1184
+ };
1185
+
1186
+ // src/muxer.ts
1187
+ var GLOBAL_TIMESCALE = 1e3;
1188
+ var SUPPORTED_VIDEO_CODECS = ["avc", "hevc", "vp9", "av1"];
1189
+ var SUPPORTED_AUDIO_CODECS = ["aac", "opus"];
1190
+ var TIMESTAMP_OFFSET = 2082844800;
1191
+ var FIRST_TIMESTAMP_BEHAVIORS = ["strict", "offset", "cross-track-offset"];
1192
+ var _options, _writer, _ftypSize, _mdat, _videoTrack, _audioTrack, _creationTime, _finalizedChunks, _nextFragmentNumber, _videoSampleQueue, _audioSampleQueue, _finalized, _validateOptions, validateOptions_fn, _writeHeader, writeHeader_fn, _computeMoovSizeUpperBound, computeMoovSizeUpperBound_fn, _prepareTracks, prepareTracks_fn, _generateMpeg4AudioSpecificConfig, generateMpeg4AudioSpecificConfig_fn, _createSampleForTrack, createSampleForTrack_fn, _addSampleToTrack, addSampleToTrack_fn, _validateTimestamp, validateTimestamp_fn, _finalizeCurrentChunk, finalizeCurrentChunk_fn, _finalizeFragment, finalizeFragment_fn, _maybeFlushStreamingTargetWriter, maybeFlushStreamingTargetWriter_fn, _ensureNotFinalized, ensureNotFinalized_fn;
1193
+ var Muxer = class {
1194
+ constructor(options) {
1195
+ __privateAdd(this, _validateOptions);
1196
+ __privateAdd(this, _writeHeader);
1197
+ __privateAdd(this, _computeMoovSizeUpperBound);
1198
+ __privateAdd(this, _prepareTracks);
1199
+ // https://wiki.multimedia.cx/index.php/MPEG-4_Audio
1200
+ __privateAdd(this, _generateMpeg4AudioSpecificConfig);
1201
+ __privateAdd(this, _createSampleForTrack);
1202
+ __privateAdd(this, _addSampleToTrack);
1203
+ __privateAdd(this, _validateTimestamp);
1204
+ __privateAdd(this, _finalizeCurrentChunk);
1205
+ __privateAdd(this, _finalizeFragment);
1206
+ __privateAdd(this, _maybeFlushStreamingTargetWriter);
1207
+ __privateAdd(this, _ensureNotFinalized);
1208
+ __privateAdd(this, _options, void 0);
1209
+ __privateAdd(this, _writer, void 0);
1210
+ __privateAdd(this, _ftypSize, void 0);
1211
+ __privateAdd(this, _mdat, void 0);
1212
+ __privateAdd(this, _videoTrack, null);
1213
+ __privateAdd(this, _audioTrack, null);
1214
+ __privateAdd(this, _creationTime, Math.floor(Date.now() / 1e3) + TIMESTAMP_OFFSET);
1215
+ __privateAdd(this, _finalizedChunks, []);
1216
+ // Fields for fragmented MP4:
1217
+ __privateAdd(this, _nextFragmentNumber, 1);
1218
+ __privateAdd(this, _videoSampleQueue, []);
1219
+ __privateAdd(this, _audioSampleQueue, []);
1220
+ __privateAdd(this, _finalized, false);
1221
+ __privateMethod(this, _validateOptions, validateOptions_fn).call(this, options);
1222
+ options.video = deepClone(options.video);
1223
+ options.audio = deepClone(options.audio);
1224
+ options.fastStart = deepClone(options.fastStart);
1225
+ this.target = options.target;
1226
+ __privateSet(this, _options, {
1227
+ firstTimestampBehavior: "strict",
1228
+ ...options
1229
+ });
1230
+ if (options.target instanceof ArrayBufferTarget) {
1231
+ __privateSet(this, _writer, new ArrayBufferTargetWriter(options.target));
1232
+ } else if (options.target instanceof StreamTarget) {
1233
+ __privateSet(this, _writer, new StreamTargetWriter(options.target));
1234
+ } else if (options.target instanceof FileSystemWritableFileStreamTarget) {
1235
+ __privateSet(this, _writer, new FileSystemWritableFileStreamTargetWriter(options.target));
1236
+ } else {
1237
+ throw new Error(`Invalid target: ${options.target}`);
1238
+ }
1239
+ __privateMethod(this, _prepareTracks, prepareTracks_fn).call(this);
1240
+ __privateMethod(this, _writeHeader, writeHeader_fn).call(this);
1241
+ }
1242
+ addVideoChunk(sample, meta, timestamp, compositionTimeOffset) {
1243
+ if (!(sample instanceof EncodedVideoChunk)) {
1244
+ throw new TypeError("addVideoChunk's first argument (sample) must be of type EncodedVideoChunk.");
1245
+ }
1246
+ if (meta && typeof meta !== "object") {
1247
+ throw new TypeError("addVideoChunk's second argument (meta), when provided, must be an object.");
1248
+ }
1249
+ if (timestamp !== void 0 && (!Number.isFinite(timestamp) || timestamp < 0)) {
1250
+ throw new TypeError(
1251
+ "addVideoChunk's third argument (timestamp), when provided, must be a non-negative real number."
1252
+ );
1253
+ }
1254
+ if (compositionTimeOffset !== void 0 && !Number.isFinite(compositionTimeOffset)) {
1255
+ throw new TypeError(
1256
+ "addVideoChunk's fourth argument (compositionTimeOffset), when provided, must be a real number."
1257
+ );
1258
+ }
1259
+ let data = new Uint8Array(sample.byteLength);
1260
+ sample.copyTo(data);
1261
+ this.addVideoChunkRaw(
1262
+ data,
1263
+ sample.type,
1264
+ timestamp ?? sample.timestamp,
1265
+ sample.duration,
1266
+ meta,
1267
+ compositionTimeOffset
1268
+ );
1269
+ }
1270
+ addVideoChunkRaw(data, type, timestamp, duration, meta, compositionTimeOffset) {
1271
+ if (!(data instanceof Uint8Array)) {
1272
+ throw new TypeError("addVideoChunkRaw's first argument (data) must be an instance of Uint8Array.");
1273
+ }
1274
+ if (type !== "key" && type !== "delta") {
1275
+ throw new TypeError("addVideoChunkRaw's second argument (type) must be either 'key' or 'delta'.");
1276
+ }
1277
+ if (!Number.isFinite(timestamp) || timestamp < 0) {
1278
+ throw new TypeError("addVideoChunkRaw's third argument (timestamp) must be a non-negative real number.");
1279
+ }
1280
+ if (!Number.isFinite(duration) || duration < 0) {
1281
+ throw new TypeError("addVideoChunkRaw's fourth argument (duration) must be a non-negative real number.");
1282
+ }
1283
+ if (meta && typeof meta !== "object") {
1284
+ throw new TypeError("addVideoChunkRaw's fifth argument (meta), when provided, must be an object.");
1285
+ }
1286
+ if (compositionTimeOffset !== void 0 && !Number.isFinite(compositionTimeOffset)) {
1287
+ throw new TypeError(
1288
+ "addVideoChunkRaw's sixth argument (compositionTimeOffset), when provided, must be a real number."
1289
+ );
1290
+ }
1291
+ __privateMethod(this, _ensureNotFinalized, ensureNotFinalized_fn).call(this);
1292
+ if (!__privateGet(this, _options).video)
1293
+ throw new Error("No video track declared.");
1294
+ if (typeof __privateGet(this, _options).fastStart === "object" && __privateGet(this, _videoTrack).samples.length === __privateGet(this, _options).fastStart.expectedVideoChunks) {
1295
+ throw new Error(`Cannot add more video chunks than specified in 'fastStart' (${__privateGet(this, _options).fastStart.expectedVideoChunks}).`);
1296
+ }
1297
+ let videoSample = __privateMethod(this, _createSampleForTrack, createSampleForTrack_fn).call(this, __privateGet(this, _videoTrack), data, type, timestamp, duration, meta, compositionTimeOffset);
1298
+ if (__privateGet(this, _options).fastStart === "fragmented" && __privateGet(this, _audioTrack)) {
1299
+ while (__privateGet(this, _audioSampleQueue).length > 0 && __privateGet(this, _audioSampleQueue)[0].decodeTimestamp <= videoSample.decodeTimestamp) {
1300
+ let audioSample = __privateGet(this, _audioSampleQueue).shift();
1301
+ __privateMethod(this, _addSampleToTrack, addSampleToTrack_fn).call(this, __privateGet(this, _audioTrack), audioSample);
1302
+ }
1303
+ if (videoSample.decodeTimestamp <= __privateGet(this, _audioTrack).lastDecodeTimestamp) {
1304
+ __privateMethod(this, _addSampleToTrack, addSampleToTrack_fn).call(this, __privateGet(this, _videoTrack), videoSample);
1305
+ } else {
1306
+ __privateGet(this, _videoSampleQueue).push(videoSample);
1307
+ }
1308
+ } else {
1309
+ __privateMethod(this, _addSampleToTrack, addSampleToTrack_fn).call(this, __privateGet(this, _videoTrack), videoSample);
1310
+ }
1311
+ }
1312
+ addAudioChunk(sample, meta, timestamp) {
1313
+ if (!(sample instanceof EncodedAudioChunk)) {
1314
+ throw new TypeError("addAudioChunk's first argument (sample) must be of type EncodedAudioChunk.");
1315
+ }
1316
+ if (meta && typeof meta !== "object") {
1317
+ throw new TypeError("addAudioChunk's second argument (meta), when provided, must be an object.");
1318
+ }
1319
+ if (timestamp !== void 0 && (!Number.isFinite(timestamp) || timestamp < 0)) {
1320
+ throw new TypeError(
1321
+ "addAudioChunk's third argument (timestamp), when provided, must be a non-negative real number."
1322
+ );
1323
+ }
1324
+ let data = new Uint8Array(sample.byteLength);
1325
+ sample.copyTo(data);
1326
+ this.addAudioChunkRaw(data, sample.type, timestamp ?? sample.timestamp, sample.duration, meta);
1327
+ }
1328
+ addAudioChunkRaw(data, type, timestamp, duration, meta) {
1329
+ if (!(data instanceof Uint8Array)) {
1330
+ throw new TypeError("addAudioChunkRaw's first argument (data) must be an instance of Uint8Array.");
1331
+ }
1332
+ if (type !== "key" && type !== "delta") {
1333
+ throw new TypeError("addAudioChunkRaw's second argument (type) must be either 'key' or 'delta'.");
1334
+ }
1335
+ if (!Number.isFinite(timestamp) || timestamp < 0) {
1336
+ throw new TypeError("addAudioChunkRaw's third argument (timestamp) must be a non-negative real number.");
1337
+ }
1338
+ if (!Number.isFinite(duration) || duration < 0) {
1339
+ throw new TypeError("addAudioChunkRaw's fourth argument (duration) must be a non-negative real number.");
1340
+ }
1341
+ if (meta && typeof meta !== "object") {
1342
+ throw new TypeError("addAudioChunkRaw's fifth argument (meta), when provided, must be an object.");
1343
+ }
1344
+ __privateMethod(this, _ensureNotFinalized, ensureNotFinalized_fn).call(this);
1345
+ if (!__privateGet(this, _options).audio)
1346
+ throw new Error("No audio track declared.");
1347
+ if (typeof __privateGet(this, _options).fastStart === "object" && __privateGet(this, _audioTrack).samples.length === __privateGet(this, _options).fastStart.expectedAudioChunks) {
1348
+ throw new Error(`Cannot add more audio chunks than specified in 'fastStart' (${__privateGet(this, _options).fastStart.expectedAudioChunks}).`);
1349
+ }
1350
+ let audioSample = __privateMethod(this, _createSampleForTrack, createSampleForTrack_fn).call(this, __privateGet(this, _audioTrack), data, type, timestamp, duration, meta);
1351
+ if (__privateGet(this, _options).fastStart === "fragmented" && __privateGet(this, _videoTrack)) {
1352
+ while (__privateGet(this, _videoSampleQueue).length > 0 && __privateGet(this, _videoSampleQueue)[0].decodeTimestamp <= audioSample.decodeTimestamp) {
1353
+ let videoSample = __privateGet(this, _videoSampleQueue).shift();
1354
+ __privateMethod(this, _addSampleToTrack, addSampleToTrack_fn).call(this, __privateGet(this, _videoTrack), videoSample);
1355
+ }
1356
+ if (audioSample.decodeTimestamp <= __privateGet(this, _videoTrack).lastDecodeTimestamp) {
1357
+ __privateMethod(this, _addSampleToTrack, addSampleToTrack_fn).call(this, __privateGet(this, _audioTrack), audioSample);
1358
+ } else {
1359
+ __privateGet(this, _audioSampleQueue).push(audioSample);
1360
+ }
1361
+ } else {
1362
+ __privateMethod(this, _addSampleToTrack, addSampleToTrack_fn).call(this, __privateGet(this, _audioTrack), audioSample);
1363
+ }
1364
+ }
1365
+ /** Finalizes the file, making it ready for use. Must be called after all video and audio chunks have been added. */
1366
+ finalize() {
1367
+ if (__privateGet(this, _finalized)) {
1368
+ throw new Error("Cannot finalize a muxer more than once.");
1369
+ }
1370
+ if (__privateGet(this, _options).fastStart === "fragmented") {
1371
+ for (let videoSample of __privateGet(this, _videoSampleQueue))
1372
+ __privateMethod(this, _addSampleToTrack, addSampleToTrack_fn).call(this, __privateGet(this, _videoTrack), videoSample);
1373
+ for (let audioSample of __privateGet(this, _audioSampleQueue))
1374
+ __privateMethod(this, _addSampleToTrack, addSampleToTrack_fn).call(this, __privateGet(this, _audioTrack), audioSample);
1375
+ __privateMethod(this, _finalizeFragment, finalizeFragment_fn).call(this, false);
1376
+ } else {
1377
+ if (__privateGet(this, _videoTrack))
1378
+ __privateMethod(this, _finalizeCurrentChunk, finalizeCurrentChunk_fn).call(this, __privateGet(this, _videoTrack));
1379
+ if (__privateGet(this, _audioTrack))
1380
+ __privateMethod(this, _finalizeCurrentChunk, finalizeCurrentChunk_fn).call(this, __privateGet(this, _audioTrack));
1381
+ }
1382
+ let tracks = [__privateGet(this, _videoTrack), __privateGet(this, _audioTrack)].filter(Boolean);
1383
+ if (__privateGet(this, _options).fastStart === "in-memory") {
1384
+ let mdatSize;
1385
+ for (let i = 0; i < 2; i++) {
1386
+ let movieBox2 = moov(tracks, __privateGet(this, _creationTime));
1387
+ let movieBoxSize = __privateGet(this, _writer).measureBox(movieBox2);
1388
+ mdatSize = __privateGet(this, _writer).measureBox(__privateGet(this, _mdat));
1389
+ let currentChunkPos = __privateGet(this, _writer).pos + movieBoxSize + mdatSize;
1390
+ for (let chunk of __privateGet(this, _finalizedChunks)) {
1391
+ chunk.offset = currentChunkPos;
1392
+ for (let { data } of chunk.samples) {
1393
+ currentChunkPos += data.byteLength;
1394
+ mdatSize += data.byteLength;
1395
+ }
1396
+ }
1397
+ if (currentChunkPos < 2 ** 32)
1398
+ break;
1399
+ if (mdatSize >= 2 ** 32)
1400
+ __privateGet(this, _mdat).largeSize = true;
1401
+ }
1402
+ let movieBox = moov(tracks, __privateGet(this, _creationTime));
1403
+ __privateGet(this, _writer).writeBox(movieBox);
1404
+ __privateGet(this, _mdat).size = mdatSize;
1405
+ __privateGet(this, _writer).writeBox(__privateGet(this, _mdat));
1406
+ for (let chunk of __privateGet(this, _finalizedChunks)) {
1407
+ for (let sample of chunk.samples) {
1408
+ __privateGet(this, _writer).write(sample.data);
1409
+ sample.data = null;
1410
+ }
1411
+ }
1412
+ } else if (__privateGet(this, _options).fastStart === "fragmented") {
1413
+ let startPos = __privateGet(this, _writer).pos;
1414
+ let mfraBox = mfra(tracks);
1415
+ __privateGet(this, _writer).writeBox(mfraBox);
1416
+ let mfraBoxSize = __privateGet(this, _writer).pos - startPos;
1417
+ __privateGet(this, _writer).seek(__privateGet(this, _writer).pos - 4);
1418
+ __privateGet(this, _writer).writeU32(mfraBoxSize);
1419
+ } else {
1420
+ let mdatPos = __privateGet(this, _writer).offsets.get(__privateGet(this, _mdat));
1421
+ let mdatSize = __privateGet(this, _writer).pos - mdatPos;
1422
+ __privateGet(this, _mdat).size = mdatSize;
1423
+ __privateGet(this, _mdat).largeSize = mdatSize >= 2 ** 32;
1424
+ __privateGet(this, _writer).patchBox(__privateGet(this, _mdat));
1425
+ let movieBox = moov(tracks, __privateGet(this, _creationTime));
1426
+ if (typeof __privateGet(this, _options).fastStart === "object") {
1427
+ __privateGet(this, _writer).seek(__privateGet(this, _ftypSize));
1428
+ __privateGet(this, _writer).writeBox(movieBox);
1429
+ let remainingBytes = mdatPos - __privateGet(this, _writer).pos;
1430
+ __privateGet(this, _writer).writeBox(free(remainingBytes));
1431
+ } else {
1432
+ __privateGet(this, _writer).writeBox(movieBox);
1433
+ }
1434
+ }
1435
+ __privateMethod(this, _maybeFlushStreamingTargetWriter, maybeFlushStreamingTargetWriter_fn).call(this);
1436
+ __privateGet(this, _writer).finalize();
1437
+ __privateSet(this, _finalized, true);
1438
+ }
1439
+ };
1440
+ _options = new WeakMap();
1441
+ _writer = new WeakMap();
1442
+ _ftypSize = new WeakMap();
1443
+ _mdat = new WeakMap();
1444
+ _videoTrack = new WeakMap();
1445
+ _audioTrack = new WeakMap();
1446
+ _creationTime = new WeakMap();
1447
+ _finalizedChunks = new WeakMap();
1448
+ _nextFragmentNumber = new WeakMap();
1449
+ _videoSampleQueue = new WeakMap();
1450
+ _audioSampleQueue = new WeakMap();
1451
+ _finalized = new WeakMap();
1452
+ _validateOptions = new WeakSet();
1453
+ validateOptions_fn = function(options) {
1454
+ if (typeof options !== "object") {
1455
+ throw new TypeError("The muxer requires an options object to be passed to its constructor.");
1456
+ }
1457
+ if (!(options.target instanceof Target)) {
1458
+ throw new TypeError("The target must be provided and an instance of Target.");
1459
+ }
1460
+ if (options.video) {
1461
+ if (!SUPPORTED_VIDEO_CODECS.includes(options.video.codec)) {
1462
+ throw new TypeError(`Unsupported video codec: ${options.video.codec}`);
1463
+ }
1464
+ if (!Number.isInteger(options.video.width) || options.video.width <= 0) {
1465
+ throw new TypeError(`Invalid video width: ${options.video.width}. Must be a positive integer.`);
1466
+ }
1467
+ if (!Number.isInteger(options.video.height) || options.video.height <= 0) {
1468
+ throw new TypeError(`Invalid video height: ${options.video.height}. Must be a positive integer.`);
1469
+ }
1470
+ const videoRotation = options.video.rotation;
1471
+ if (typeof videoRotation === "number" && ![0, 90, 180, 270].includes(videoRotation)) {
1472
+ throw new TypeError(`Invalid video rotation: ${videoRotation}. Has to be 0, 90, 180 or 270.`);
1473
+ } else if (Array.isArray(videoRotation) && (videoRotation.length !== 9 || videoRotation.some((value) => typeof value !== "number"))) {
1474
+ throw new TypeError(`Invalid video transformation matrix: ${videoRotation.join()}`);
1475
+ }
1476
+ if (options.video.frameRate !== void 0 && (!Number.isInteger(options.video.frameRate) || options.video.frameRate <= 0)) {
1477
+ throw new TypeError(
1478
+ `Invalid video frame rate: ${options.video.frameRate}. Must be a positive integer.`
1479
+ );
1480
+ }
1481
+ }
1482
+ if (options.audio) {
1483
+ if (!SUPPORTED_AUDIO_CODECS.includes(options.audio.codec)) {
1484
+ throw new TypeError(`Unsupported audio codec: ${options.audio.codec}`);
1485
+ }
1486
+ if (!Number.isInteger(options.audio.numberOfChannels) || options.audio.numberOfChannels <= 0) {
1487
+ throw new TypeError(
1488
+ `Invalid number of audio channels: ${options.audio.numberOfChannels}. Must be a positive integer.`
1489
+ );
1490
+ }
1491
+ if (!Number.isInteger(options.audio.sampleRate) || options.audio.sampleRate <= 0) {
1492
+ throw new TypeError(
1493
+ `Invalid audio sample rate: ${options.audio.sampleRate}. Must be a positive integer.`
1494
+ );
1495
+ }
1496
+ }
1497
+ if (options.firstTimestampBehavior && !FIRST_TIMESTAMP_BEHAVIORS.includes(options.firstTimestampBehavior)) {
1498
+ throw new TypeError(`Invalid first timestamp behavior: ${options.firstTimestampBehavior}`);
1499
+ }
1500
+ if (typeof options.fastStart === "object") {
1501
+ if (options.video) {
1502
+ if (options.fastStart.expectedVideoChunks === void 0) {
1503
+ throw new TypeError(`'fastStart' is an object but is missing property 'expectedVideoChunks'.`);
1504
+ } else if (!Number.isInteger(options.fastStart.expectedVideoChunks) || options.fastStart.expectedVideoChunks < 0) {
1505
+ throw new TypeError(`'expectedVideoChunks' must be a non-negative integer.`);
1506
+ }
1507
+ }
1508
+ if (options.audio) {
1509
+ if (options.fastStart.expectedAudioChunks === void 0) {
1510
+ throw new TypeError(`'fastStart' is an object but is missing property 'expectedAudioChunks'.`);
1511
+ } else if (!Number.isInteger(options.fastStart.expectedAudioChunks) || options.fastStart.expectedAudioChunks < 0) {
1512
+ throw new TypeError(`'expectedAudioChunks' must be a non-negative integer.`);
1513
+ }
1514
+ }
1515
+ } else if (![false, "in-memory", "fragmented"].includes(options.fastStart)) {
1516
+ throw new TypeError(`'fastStart' option must be false, 'in-memory', 'fragmented' or an object.`);
1517
+ }
1518
+ if (options.minFragmentDuration !== void 0 && (!Number.isFinite(options.minFragmentDuration) || options.minFragmentDuration < 0)) {
1519
+ throw new TypeError(`'minFragmentDuration' must be a non-negative number.`);
1520
+ }
1521
+ };
1522
+ _writeHeader = new WeakSet();
1523
+ writeHeader_fn = function() {
1524
+ __privateGet(this, _writer).writeBox(ftyp({
1525
+ holdsAvc: __privateGet(this, _options).video?.codec === "avc",
1526
+ fragmented: __privateGet(this, _options).fastStart === "fragmented"
1527
+ }));
1528
+ __privateSet(this, _ftypSize, __privateGet(this, _writer).pos);
1529
+ if (__privateGet(this, _options).fastStart === "in-memory") {
1530
+ __privateSet(this, _mdat, mdat(false));
1531
+ } else if (__privateGet(this, _options).fastStart === "fragmented") {
1532
+ } else {
1533
+ if (typeof __privateGet(this, _options).fastStart === "object") {
1534
+ let moovSizeUpperBound = __privateMethod(this, _computeMoovSizeUpperBound, computeMoovSizeUpperBound_fn).call(this);
1535
+ __privateGet(this, _writer).seek(__privateGet(this, _writer).pos + moovSizeUpperBound);
1536
+ }
1537
+ __privateSet(this, _mdat, mdat(true));
1538
+ __privateGet(this, _writer).writeBox(__privateGet(this, _mdat));
1539
+ }
1540
+ __privateMethod(this, _maybeFlushStreamingTargetWriter, maybeFlushStreamingTargetWriter_fn).call(this);
1541
+ };
1542
+ _computeMoovSizeUpperBound = new WeakSet();
1543
+ computeMoovSizeUpperBound_fn = function() {
1544
+ if (typeof __privateGet(this, _options).fastStart !== "object")
1545
+ return;
1546
+ let upperBound = 0;
1547
+ let sampleCounts = [
1548
+ __privateGet(this, _options).fastStart.expectedVideoChunks,
1549
+ __privateGet(this, _options).fastStart.expectedAudioChunks
1550
+ ];
1551
+ for (let n of sampleCounts) {
1552
+ if (!n)
1553
+ continue;
1554
+ upperBound += (4 + 4) * Math.ceil(2 / 3 * n);
1555
+ upperBound += 4 * n;
1556
+ upperBound += (4 + 4 + 4) * Math.ceil(2 / 3 * n);
1557
+ upperBound += 4 * n;
1558
+ upperBound += 8 * n;
1559
+ }
1560
+ upperBound += 4096;
1561
+ return upperBound;
1562
+ };
1563
+ _prepareTracks = new WeakSet();
1564
+ prepareTracks_fn = function() {
1565
+ if (__privateGet(this, _options).video) {
1566
+ __privateSet(this, _videoTrack, {
1567
+ id: 1,
1568
+ info: {
1569
+ type: "video",
1570
+ codec: __privateGet(this, _options).video.codec,
1571
+ width: __privateGet(this, _options).video.width,
1572
+ height: __privateGet(this, _options).video.height,
1573
+ rotation: __privateGet(this, _options).video.rotation ?? 0,
1574
+ decoderConfig: null
1575
+ },
1576
+ // The fallback contains many common frame rates as factors
1577
+ timescale: __privateGet(this, _options).video.frameRate ?? 57600,
1578
+ samples: [],
1579
+ finalizedChunks: [],
1580
+ currentChunk: null,
1581
+ firstDecodeTimestamp: void 0,
1582
+ lastDecodeTimestamp: -1,
1583
+ timeToSampleTable: [],
1584
+ compositionTimeOffsetTable: [],
1585
+ lastTimescaleUnits: null,
1586
+ lastSample: null,
1587
+ compactlyCodedChunkTable: []
1588
+ });
1589
+ }
1590
+ if (__privateGet(this, _options).audio) {
1591
+ __privateSet(this, _audioTrack, {
1592
+ id: __privateGet(this, _options).video ? 2 : 1,
1593
+ info: {
1594
+ type: "audio",
1595
+ codec: __privateGet(this, _options).audio.codec,
1596
+ numberOfChannels: __privateGet(this, _options).audio.numberOfChannels,
1597
+ sampleRate: __privateGet(this, _options).audio.sampleRate,
1598
+ decoderConfig: null
1599
+ },
1600
+ timescale: __privateGet(this, _options).audio.sampleRate,
1601
+ samples: [],
1602
+ finalizedChunks: [],
1603
+ currentChunk: null,
1604
+ firstDecodeTimestamp: void 0,
1605
+ lastDecodeTimestamp: -1,
1606
+ timeToSampleTable: [],
1607
+ compositionTimeOffsetTable: [],
1608
+ lastTimescaleUnits: null,
1609
+ lastSample: null,
1610
+ compactlyCodedChunkTable: []
1611
+ });
1612
+ if (__privateGet(this, _options).audio.codec === "aac") {
1613
+ let guessedCodecPrivate = __privateMethod(this, _generateMpeg4AudioSpecificConfig, generateMpeg4AudioSpecificConfig_fn).call(
1614
+ this,
1615
+ 2,
1616
+ // Object type for AAC-LC, since it's the most common
1617
+ __privateGet(this, _options).audio.sampleRate,
1618
+ __privateGet(this, _options).audio.numberOfChannels
1619
+ );
1620
+ __privateGet(this, _audioTrack).info.decoderConfig = {
1621
+ codec: __privateGet(this, _options).audio.codec,
1622
+ description: guessedCodecPrivate,
1623
+ numberOfChannels: __privateGet(this, _options).audio.numberOfChannels,
1624
+ sampleRate: __privateGet(this, _options).audio.sampleRate
1625
+ };
1626
+ }
1627
+ }
1628
+ };
1629
+ _generateMpeg4AudioSpecificConfig = new WeakSet();
1630
+ generateMpeg4AudioSpecificConfig_fn = function(objectType, sampleRate, numberOfChannels) {
1631
+ let frequencyIndices = [96e3, 88200, 64e3, 48e3, 44100, 32e3, 24e3, 22050, 16e3, 12e3, 11025, 8e3, 7350];
1632
+ let frequencyIndex = frequencyIndices.indexOf(sampleRate);
1633
+ let channelConfig = numberOfChannels;
1634
+ let configBits = "";
1635
+ configBits += objectType.toString(2).padStart(5, "0");
1636
+ configBits += frequencyIndex.toString(2).padStart(4, "0");
1637
+ if (frequencyIndex === 15)
1638
+ configBits += sampleRate.toString(2).padStart(24, "0");
1639
+ configBits += channelConfig.toString(2).padStart(4, "0");
1640
+ let paddingLength = Math.ceil(configBits.length / 8) * 8;
1641
+ configBits = configBits.padEnd(paddingLength, "0");
1642
+ let configBytes = new Uint8Array(configBits.length / 8);
1643
+ for (let i = 0; i < configBits.length; i += 8) {
1644
+ configBytes[i / 8] = parseInt(configBits.slice(i, i + 8), 2);
1645
+ }
1646
+ return configBytes;
1647
+ };
1648
+ _createSampleForTrack = new WeakSet();
1649
+ createSampleForTrack_fn = function(track, data, type, timestamp, duration, meta, compositionTimeOffset) {
1650
+ let presentationTimestampInSeconds = timestamp / 1e6;
1651
+ let decodeTimestampInSeconds = (timestamp - (compositionTimeOffset ?? 0)) / 1e6;
1652
+ let durationInSeconds = duration / 1e6;
1653
+ let adjusted = __privateMethod(this, _validateTimestamp, validateTimestamp_fn).call(this, presentationTimestampInSeconds, decodeTimestampInSeconds, track);
1654
+ presentationTimestampInSeconds = adjusted.presentationTimestamp;
1655
+ decodeTimestampInSeconds = adjusted.decodeTimestamp;
1656
+ if (meta?.decoderConfig) {
1657
+ if (track.info.decoderConfig === null) {
1658
+ track.info.decoderConfig = meta.decoderConfig;
1659
+ } else {
1660
+ Object.assign(track.info.decoderConfig, meta.decoderConfig);
1661
+ }
1662
+ }
1663
+ let sample = {
1664
+ presentationTimestamp: presentationTimestampInSeconds,
1665
+ decodeTimestamp: decodeTimestampInSeconds,
1666
+ duration: durationInSeconds,
1667
+ data,
1668
+ size: data.byteLength,
1669
+ type,
1670
+ // Will be refined once the next sample comes in
1671
+ timescaleUnitsToNextSample: intoTimescale(durationInSeconds, track.timescale)
1672
+ };
1673
+ return sample;
1674
+ };
1675
+ _addSampleToTrack = new WeakSet();
1676
+ addSampleToTrack_fn = function(track, sample) {
1677
+ if (__privateGet(this, _options).fastStart !== "fragmented") {
1678
+ track.samples.push(sample);
1679
+ }
1680
+ const sampleCompositionTimeOffset = intoTimescale(sample.presentationTimestamp - sample.decodeTimestamp, track.timescale);
1681
+ if (track.lastTimescaleUnits !== null) {
1682
+ let timescaleUnits = intoTimescale(sample.decodeTimestamp, track.timescale, false);
1683
+ let delta = Math.round(timescaleUnits - track.lastTimescaleUnits);
1684
+ track.lastTimescaleUnits += delta;
1685
+ track.lastSample.timescaleUnitsToNextSample = delta;
1686
+ if (__privateGet(this, _options).fastStart !== "fragmented") {
1687
+ let lastTableEntry = last(track.timeToSampleTable);
1688
+ if (lastTableEntry.sampleCount === 1) {
1689
+ lastTableEntry.sampleDelta = delta;
1690
+ lastTableEntry.sampleCount++;
1691
+ } else if (lastTableEntry.sampleDelta === delta) {
1692
+ lastTableEntry.sampleCount++;
1693
+ } else {
1694
+ lastTableEntry.sampleCount--;
1695
+ track.timeToSampleTable.push({
1696
+ sampleCount: 2,
1697
+ sampleDelta: delta
1698
+ });
1699
+ }
1700
+ const lastCompositionTimeOffsetTableEntry = last(track.compositionTimeOffsetTable);
1701
+ if (lastCompositionTimeOffsetTableEntry.sampleCompositionTimeOffset === sampleCompositionTimeOffset) {
1702
+ lastCompositionTimeOffsetTableEntry.sampleCount++;
1703
+ } else {
1704
+ track.compositionTimeOffsetTable.push({
1705
+ sampleCount: 1,
1706
+ sampleCompositionTimeOffset
1707
+ });
1708
+ }
1709
+ }
1710
+ } else {
1711
+ track.lastTimescaleUnits = 0;
1712
+ if (__privateGet(this, _options).fastStart !== "fragmented") {
1713
+ track.timeToSampleTable.push({
1714
+ sampleCount: 1,
1715
+ sampleDelta: intoTimescale(sample.duration, track.timescale)
1716
+ });
1717
+ track.compositionTimeOffsetTable.push({
1718
+ sampleCount: 1,
1719
+ sampleCompositionTimeOffset
1720
+ });
1721
+ }
1722
+ }
1723
+ track.lastSample = sample;
1724
+ let beginNewChunk = false;
1725
+ if (!track.currentChunk) {
1726
+ beginNewChunk = true;
1727
+ } else {
1728
+ let currentChunkDuration = sample.presentationTimestamp - track.currentChunk.startTimestamp;
1729
+ if (__privateGet(this, _options).fastStart === "fragmented") {
1730
+ let mostImportantTrack = __privateGet(this, _videoTrack) ?? __privateGet(this, _audioTrack);
1731
+ const chunkDuration = __privateGet(this, _options).minFragmentDuration ?? 1;
1732
+ if (track === mostImportantTrack && sample.type === "key" && currentChunkDuration >= chunkDuration) {
1733
+ beginNewChunk = true;
1734
+ __privateMethod(this, _finalizeFragment, finalizeFragment_fn).call(this);
1735
+ }
1736
+ } else {
1737
+ beginNewChunk = currentChunkDuration >= 0.5;
1738
+ }
1739
+ }
1740
+ if (beginNewChunk) {
1741
+ if (track.currentChunk) {
1742
+ __privateMethod(this, _finalizeCurrentChunk, finalizeCurrentChunk_fn).call(this, track);
1743
+ }
1744
+ track.currentChunk = {
1745
+ startTimestamp: sample.presentationTimestamp,
1746
+ samples: []
1747
+ };
1748
+ }
1749
+ track.currentChunk.samples.push(sample);
1750
+ };
1751
+ _validateTimestamp = new WeakSet();
1752
+ validateTimestamp_fn = function(presentationTimestamp, decodeTimestamp, track) {
1753
+ const strictTimestampBehavior = __privateGet(this, _options).firstTimestampBehavior === "strict";
1754
+ const noLastDecodeTimestamp = track.lastDecodeTimestamp === -1;
1755
+ const timestampNonZero = decodeTimestamp !== 0;
1756
+ if (strictTimestampBehavior && noLastDecodeTimestamp && timestampNonZero) {
1757
+ throw new Error(
1758
+ `The first chunk for your media track must have a timestamp of 0 (received DTS=${decodeTimestamp}).Non-zero first timestamps are often caused by directly piping frames or audio data from a MediaStreamTrack into the encoder. Their timestamps are typically relative to the age of thedocument, which is probably what you want.
1759
+
1760
+ If you want to offset all timestamps of a track such that the first one is zero, set firstTimestampBehavior: 'offset' in the options.
1761
+ `
1762
+ );
1763
+ } else if (__privateGet(this, _options).firstTimestampBehavior === "offset" || __privateGet(this, _options).firstTimestampBehavior === "cross-track-offset") {
1764
+ if (track.firstDecodeTimestamp === void 0) {
1765
+ track.firstDecodeTimestamp = decodeTimestamp;
1766
+ }
1767
+ let baseDecodeTimestamp;
1768
+ if (__privateGet(this, _options).firstTimestampBehavior === "offset") {
1769
+ baseDecodeTimestamp = track.firstDecodeTimestamp;
1770
+ } else {
1771
+ baseDecodeTimestamp = Math.min(
1772
+ __privateGet(this, _videoTrack)?.firstDecodeTimestamp ?? Infinity,
1773
+ __privateGet(this, _audioTrack)?.firstDecodeTimestamp ?? Infinity
1774
+ );
1775
+ }
1776
+ decodeTimestamp -= baseDecodeTimestamp;
1777
+ presentationTimestamp -= baseDecodeTimestamp;
1778
+ }
1779
+ if (decodeTimestamp < track.lastDecodeTimestamp) {
1780
+ throw new Error(
1781
+ `Timestamps must be monotonically increasing (DTS went from ${track.lastDecodeTimestamp * 1e6} to ${decodeTimestamp * 1e6}).`
1782
+ );
1783
+ }
1784
+ track.lastDecodeTimestamp = decodeTimestamp;
1785
+ return { presentationTimestamp, decodeTimestamp };
1786
+ };
1787
+ _finalizeCurrentChunk = new WeakSet();
1788
+ finalizeCurrentChunk_fn = function(track) {
1789
+ if (__privateGet(this, _options).fastStart === "fragmented") {
1790
+ throw new Error("Can't finalize individual chunks if 'fastStart' is set to 'fragmented'.");
1791
+ }
1792
+ if (!track.currentChunk)
1793
+ return;
1794
+ track.finalizedChunks.push(track.currentChunk);
1795
+ __privateGet(this, _finalizedChunks).push(track.currentChunk);
1796
+ if (track.compactlyCodedChunkTable.length === 0 || last(track.compactlyCodedChunkTable).samplesPerChunk !== track.currentChunk.samples.length) {
1797
+ track.compactlyCodedChunkTable.push({
1798
+ firstChunk: track.finalizedChunks.length,
1799
+ // 1-indexed
1800
+ samplesPerChunk: track.currentChunk.samples.length
1801
+ });
1802
+ }
1803
+ if (__privateGet(this, _options).fastStart === "in-memory") {
1804
+ track.currentChunk.offset = 0;
1805
+ return;
1806
+ }
1807
+ track.currentChunk.offset = __privateGet(this, _writer).pos;
1808
+ for (let sample of track.currentChunk.samples) {
1809
+ __privateGet(this, _writer).write(sample.data);
1810
+ sample.data = null;
1811
+ }
1812
+ __privateMethod(this, _maybeFlushStreamingTargetWriter, maybeFlushStreamingTargetWriter_fn).call(this);
1813
+ };
1814
+ _finalizeFragment = new WeakSet();
1815
+ finalizeFragment_fn = function(flushStreamingWriter = true) {
1816
+ if (__privateGet(this, _options).fastStart !== "fragmented") {
1817
+ throw new Error("Can't finalize a fragment unless 'fastStart' is set to 'fragmented'.");
1818
+ }
1819
+ let tracks = [__privateGet(this, _videoTrack), __privateGet(this, _audioTrack)].filter((track) => track && track.currentChunk);
1820
+ if (tracks.length === 0)
1821
+ return;
1822
+ let fragmentNumber = __privateWrapper(this, _nextFragmentNumber)._++;
1823
+ if (fragmentNumber === 1) {
1824
+ let movieBox = moov(tracks, __privateGet(this, _creationTime), true);
1825
+ __privateGet(this, _writer).writeBox(movieBox);
1826
+ }
1827
+ let moofOffset = __privateGet(this, _writer).pos;
1828
+ let moofBox = moof(fragmentNumber, tracks);
1829
+ __privateGet(this, _writer).writeBox(moofBox);
1830
+ {
1831
+ let mdatBox = mdat(false);
1832
+ let totalTrackSampleSize = 0;
1833
+ for (let track of tracks) {
1834
+ for (let sample of track.currentChunk.samples) {
1835
+ totalTrackSampleSize += sample.size;
1836
+ }
1837
+ }
1838
+ let mdatSize = __privateGet(this, _writer).measureBox(mdatBox) + totalTrackSampleSize;
1839
+ if (mdatSize >= 2 ** 32) {
1840
+ mdatBox.largeSize = true;
1841
+ mdatSize = __privateGet(this, _writer).measureBox(mdatBox) + totalTrackSampleSize;
1842
+ }
1843
+ mdatBox.size = mdatSize;
1844
+ __privateGet(this, _writer).writeBox(mdatBox);
1845
+ }
1846
+ for (let track of tracks) {
1847
+ track.currentChunk.offset = __privateGet(this, _writer).pos;
1848
+ track.currentChunk.moofOffset = moofOffset;
1849
+ for (let sample of track.currentChunk.samples) {
1850
+ __privateGet(this, _writer).write(sample.data);
1851
+ sample.data = null;
1852
+ }
1853
+ }
1854
+ let endPos = __privateGet(this, _writer).pos;
1855
+ __privateGet(this, _writer).seek(__privateGet(this, _writer).offsets.get(moofBox));
1856
+ let newMoofBox = moof(fragmentNumber, tracks);
1857
+ __privateGet(this, _writer).writeBox(newMoofBox);
1858
+ __privateGet(this, _writer).seek(endPos);
1859
+ for (let track of tracks) {
1860
+ track.finalizedChunks.push(track.currentChunk);
1861
+ __privateGet(this, _finalizedChunks).push(track.currentChunk);
1862
+ track.currentChunk = null;
1863
+ }
1864
+ if (flushStreamingWriter) {
1865
+ __privateMethod(this, _maybeFlushStreamingTargetWriter, maybeFlushStreamingTargetWriter_fn).call(this);
1866
+ }
1867
+ };
1868
+ _maybeFlushStreamingTargetWriter = new WeakSet();
1869
+ maybeFlushStreamingTargetWriter_fn = function() {
1870
+ if (__privateGet(this, _writer) instanceof StreamTargetWriter) {
1871
+ __privateGet(this, _writer).flush();
1872
+ }
1873
+ };
1874
+ _ensureNotFinalized = new WeakSet();
1875
+ ensureNotFinalized_fn = function() {
1876
+ if (__privateGet(this, _finalized)) {
1877
+ throw new Error("Cannot add new video or audio chunks after the file has been finalized.");
1878
+ }
1879
+ };
1880
+ export {
1881
+ ArrayBufferTarget,
1882
+ FileSystemWritableFileStreamTarget,
1883
+ Muxer,
1884
+ StreamTarget
1885
+ };