privateboard 0.1.31 → 0.1.32

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