@meframe/core 0.0.4 → 0.0.5

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