mediabunny 1.0.2 → 1.0.4

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 (188) hide show
  1. package/README.md +4 -4
  2. package/dist/mediabunny.d.ts +4 -2
  3. package/dist/modules/codec-data.d.ts +95 -0
  4. package/dist/modules/codec-data.d.ts.map +1 -0
  5. package/dist/modules/codec-data.js +1103 -0
  6. package/dist/modules/codec.d.ts +250 -0
  7. package/dist/modules/codec.d.ts.map +1 -0
  8. package/dist/modules/codec.js +1100 -0
  9. package/dist/modules/conversion.d.ts +158 -0
  10. package/dist/modules/conversion.d.ts.map +1 -0
  11. package/dist/modules/conversion.js +866 -0
  12. package/dist/modules/custom-coder.d.ts +119 -0
  13. package/dist/modules/custom-coder.d.ts.map +1 -0
  14. package/dist/modules/custom-coder.js +91 -0
  15. package/dist/modules/demuxer.d.ts +17 -0
  16. package/dist/modules/demuxer.d.ts.map +1 -0
  17. package/dist/modules/demuxer.js +12 -0
  18. package/dist/modules/index.d.ts +25 -0
  19. package/dist/modules/index.d.ts.map +1 -0
  20. package/dist/modules/index.js +24 -0
  21. package/dist/modules/input-format.d.ts +121 -0
  22. package/dist/modules/input-format.d.ts.map +1 -0
  23. package/dist/modules/input-format.js +333 -0
  24. package/dist/modules/input-track.d.ts +138 -0
  25. package/dist/modules/input-track.d.ts.map +1 -0
  26. package/dist/modules/input-track.js +230 -0
  27. package/dist/modules/input.d.ts +55 -0
  28. package/dist/modules/input.d.ts.map +1 -0
  29. package/dist/modules/input.js +104 -0
  30. package/dist/modules/isobmff/isobmff-boxes.d.ts +202 -0
  31. package/dist/modules/isobmff/isobmff-boxes.d.ts.map +1 -0
  32. package/dist/modules/isobmff/isobmff-boxes.js +1111 -0
  33. package/dist/modules/isobmff/isobmff-demuxer.d.ts +163 -0
  34. package/dist/modules/isobmff/isobmff-demuxer.d.ts.map +1 -0
  35. package/dist/modules/isobmff/isobmff-demuxer.js +2080 -0
  36. package/dist/modules/isobmff/isobmff-misc.d.ts +14 -0
  37. package/dist/modules/isobmff/isobmff-misc.d.ts.map +1 -0
  38. package/dist/modules/isobmff/isobmff-misc.js +20 -0
  39. package/dist/modules/isobmff/isobmff-muxer.d.ts +142 -0
  40. package/dist/modules/isobmff/isobmff-muxer.d.ts.map +1 -0
  41. package/dist/modules/isobmff/isobmff-muxer.js +858 -0
  42. package/dist/modules/isobmff/isobmff-reader.d.ts +36 -0
  43. package/dist/modules/isobmff/isobmff-reader.d.ts.map +1 -0
  44. package/dist/modules/isobmff/isobmff-reader.js +105 -0
  45. package/dist/modules/matroska/ebml.d.ts +156 -0
  46. package/dist/modules/matroska/ebml.d.ts.map +1 -0
  47. package/dist/modules/matroska/ebml.js +529 -0
  48. package/dist/modules/matroska/matroska-demuxer.d.ts +119 -0
  49. package/dist/modules/matroska/matroska-demuxer.d.ts.map +1 -0
  50. package/dist/modules/matroska/matroska-demuxer.js +1330 -0
  51. package/dist/modules/matroska/matroska-misc.d.ts +14 -0
  52. package/dist/modules/matroska/matroska-misc.d.ts.map +1 -0
  53. package/dist/modules/matroska/matroska-misc.js +20 -0
  54. package/dist/modules/matroska/matroska-muxer.d.ts +71 -0
  55. package/dist/modules/matroska/matroska-muxer.d.ts.map +1 -0
  56. package/dist/modules/matroska/matroska-muxer.js +729 -0
  57. package/dist/modules/media-sink.d.ts +272 -0
  58. package/dist/modules/media-sink.d.ts.map +1 -0
  59. package/dist/modules/media-sink.js +1264 -0
  60. package/dist/modules/media-source.d.ts +230 -0
  61. package/dist/modules/media-source.d.ts.map +1 -0
  62. package/dist/modules/media-source.js +1095 -0
  63. package/dist/modules/misc.d.ts +127 -0
  64. package/dist/modules/misc.d.ts.map +1 -0
  65. package/dist/modules/misc.js +462 -0
  66. package/dist/modules/mp3/mp3-demuxer.d.ts +32 -0
  67. package/dist/modules/mp3/mp3-demuxer.d.ts.map +1 -0
  68. package/dist/modules/mp3/mp3-demuxer.js +160 -0
  69. package/dist/modules/mp3/mp3-misc.d.ts +37 -0
  70. package/dist/modules/mp3/mp3-misc.d.ts.map +1 -0
  71. package/dist/modules/mp3/mp3-misc.js +122 -0
  72. package/dist/modules/mp3/mp3-muxer.d.ts +27 -0
  73. package/dist/modules/mp3/mp3-muxer.d.ts.map +1 -0
  74. package/dist/modules/mp3/mp3-muxer.js +112 -0
  75. package/dist/modules/mp3/mp3-reader.d.ts +25 -0
  76. package/dist/modules/mp3/mp3-reader.d.ts.map +1 -0
  77. package/dist/modules/mp3/mp3-reader.js +73 -0
  78. package/dist/modules/mp3/mp3-writer.d.ts +30 -0
  79. package/dist/modules/mp3/mp3-writer.d.ts.map +1 -0
  80. package/dist/modules/mp3/mp3-writer.js +72 -0
  81. package/dist/modules/muxer.d.ts +32 -0
  82. package/dist/modules/muxer.d.ts.map +1 -0
  83. package/dist/modules/muxer.js +50 -0
  84. package/dist/modules/ogg/ogg-demuxer.d.ts +53 -0
  85. package/dist/modules/ogg/ogg-demuxer.d.ts.map +1 -0
  86. package/dist/modules/ogg/ogg-demuxer.js +701 -0
  87. package/dist/modules/ogg/ogg-misc.d.ts +27 -0
  88. package/dist/modules/ogg/ogg-misc.d.ts.map +1 -0
  89. package/dist/modules/ogg/ogg-misc.js +78 -0
  90. package/dist/modules/ogg/ogg-muxer.d.ts +58 -0
  91. package/dist/modules/ogg/ogg-muxer.d.ts.map +1 -0
  92. package/dist/modules/ogg/ogg-muxer.js +345 -0
  93. package/dist/modules/ogg/ogg-reader.d.ts +37 -0
  94. package/dist/modules/ogg/ogg-reader.d.ts.map +1 -0
  95. package/dist/modules/ogg/ogg-reader.js +104 -0
  96. package/dist/modules/output-format.d.ts +285 -0
  97. package/dist/modules/output-format.d.ts.map +1 -0
  98. package/dist/modules/output-format.js +385 -0
  99. package/dist/modules/output.d.ts +134 -0
  100. package/dist/modules/output.d.ts.map +1 -0
  101. package/dist/modules/output.js +269 -0
  102. package/dist/modules/packet.d.ts +86 -0
  103. package/dist/modules/packet.d.ts.map +1 -0
  104. package/dist/modules/packet.js +133 -0
  105. package/dist/modules/pcm.d.ts +12 -0
  106. package/dist/modules/pcm.d.ts.map +1 -0
  107. package/dist/modules/pcm.js +85 -0
  108. package/dist/modules/reader.d.ts +40 -0
  109. package/dist/modules/reader.d.ts.map +1 -0
  110. package/dist/modules/reader.js +153 -0
  111. package/dist/modules/sample.d.ts +186 -0
  112. package/dist/modules/sample.d.ts.map +1 -0
  113. package/dist/modules/sample.js +798 -0
  114. package/dist/modules/source.d.ts +76 -0
  115. package/dist/modules/source.d.ts.map +1 -0
  116. package/dist/modules/source.js +183 -0
  117. package/dist/modules/subtitles.d.ts +37 -0
  118. package/dist/modules/subtitles.d.ts.map +1 -0
  119. package/dist/modules/subtitles.js +89 -0
  120. package/dist/modules/target.d.ts +58 -0
  121. package/dist/modules/target.d.ts.map +1 -0
  122. package/dist/modules/target.js +63 -0
  123. package/dist/modules/wave/riff-reader.d.ts +19 -0
  124. package/dist/modules/wave/riff-reader.d.ts.map +1 -0
  125. package/dist/modules/wave/riff-reader.js +38 -0
  126. package/dist/modules/wave/riff-writer.d.ts +18 -0
  127. package/dist/modules/wave/riff-writer.d.ts.map +1 -0
  128. package/dist/modules/wave/riff-writer.js +25 -0
  129. package/dist/modules/wave/wave-demuxer.d.ts +42 -0
  130. package/dist/modules/wave/wave-demuxer.d.ts.map +1 -0
  131. package/dist/modules/wave/wave-demuxer.js +239 -0
  132. package/dist/modules/wave/wave-muxer.d.ts +27 -0
  133. package/dist/modules/wave/wave-muxer.d.ts.map +1 -0
  134. package/dist/modules/wave/wave-muxer.js +108 -0
  135. package/dist/modules/writer.d.ts +85 -0
  136. package/dist/modules/writer.d.ts.map +1 -0
  137. package/dist/modules/writer.js +347 -0
  138. package/package.json +14 -10
  139. package/src/codec-data.ts +1394 -0
  140. package/src/codec.ts +1392 -0
  141. package/src/conversion.ts +1199 -0
  142. package/src/custom-coder.ts +162 -0
  143. package/src/demuxer.ts +22 -0
  144. package/src/index.ts +148 -0
  145. package/src/input-format.ts +386 -0
  146. package/src/input-track.ts +341 -0
  147. package/src/input.ts +138 -0
  148. package/src/isobmff/isobmff-boxes.ts +1365 -0
  149. package/src/isobmff/isobmff-demuxer.ts +2646 -0
  150. package/src/isobmff/isobmff-misc.ts +29 -0
  151. package/src/isobmff/isobmff-muxer.ts +1210 -0
  152. package/src/isobmff/isobmff-reader.ts +137 -0
  153. package/src/matroska/ebml.ts +595 -0
  154. package/src/matroska/matroska-demuxer.ts +1677 -0
  155. package/src/matroska/matroska-misc.ts +29 -0
  156. package/src/matroska/matroska-muxer.ts +999 -0
  157. package/src/media-sink.ts +1577 -0
  158. package/src/media-source.ts +1406 -0
  159. package/src/misc.ts +584 -0
  160. package/src/mp3/mp3-demuxer.ts +228 -0
  161. package/src/mp3/mp3-misc.ts +154 -0
  162. package/src/mp3/mp3-muxer.ts +153 -0
  163. package/src/mp3/mp3-reader.ts +93 -0
  164. package/src/mp3/mp3-writer.ts +112 -0
  165. package/src/muxer.ts +88 -0
  166. package/src/ogg/ogg-demuxer.ts +985 -0
  167. package/src/ogg/ogg-misc.ts +116 -0
  168. package/src/ogg/ogg-muxer.ts +480 -0
  169. package/src/ogg/ogg-reader.ts +143 -0
  170. package/src/output-format.ts +689 -0
  171. package/src/output.ts +427 -0
  172. package/src/packet.ts +180 -0
  173. package/src/pcm.ts +112 -0
  174. package/src/reader.ts +205 -0
  175. package/src/sample.ts +1029 -0
  176. package/src/source.ts +279 -0
  177. package/src/subtitles.ts +131 -0
  178. package/src/target.ts +106 -0
  179. package/src/tsconfig.json +13 -0
  180. package/src/wave/riff-reader.ts +48 -0
  181. package/src/wave/riff-writer.ts +30 -0
  182. package/src/wave/wave-demuxer.ts +317 -0
  183. package/src/wave/wave-muxer.ts +145 -0
  184. package/src/writer.ts +461 -0
  185. /package/dist/{mediabunny.js → bundles/mediabunny.cjs} +0 -0
  186. /package/dist/{mediabunny.min.js → bundles/mediabunny.min.cjs} +0 -0
  187. /package/dist/{mediabunny.min.mjs → bundles/mediabunny.min.mjs} +0 -0
  188. /package/dist/{mediabunny.mjs → bundles/mediabunny.mjs} +0 -0
package/src/writer.ts ADDED
@@ -0,0 +1,461 @@
1
+ /*!
2
+ * Copyright (c) 2025-present, Vanilagy and contributors
3
+ *
4
+ * This Source Code Form is subject to the terms of the Mozilla Public
5
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
6
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
7
+ */
8
+
9
+ import { BufferTarget, StreamTarget, StreamTargetChunk } from './target';
10
+ import { assert } from './misc';
11
+
12
+ export abstract class Writer {
13
+ /** Setting this to true will cause the writer to ensure data is written in a strictly monotonic, streamable way. */
14
+ ensureMonotonicity = false;
15
+
16
+ start() {}
17
+
18
+ /** Writes the given data to the target, at the current position. */
19
+ abstract write(data: Uint8Array): void;
20
+ /** Sets the current position for future writes to a new one. */
21
+ abstract seek(newPos: number): void;
22
+ /** Returns the current position. */
23
+ abstract getPos(): number;
24
+ /** Signals to the writer that it may be time to flush. */
25
+ abstract flush(): Promise<void>;
26
+ /** Called after muxing has finished. */
27
+ abstract finalize(): Promise<void>;
28
+ /** Closes the writer. */
29
+ abstract close(): Promise<void>;
30
+
31
+ private trackedWrites: Uint8Array | null = null;
32
+ private trackedStart = -1;
33
+ private trackedEnd = -1;
34
+
35
+ protected maybeTrackWrites(data: Uint8Array) {
36
+ if (!this.trackedWrites) {
37
+ return;
38
+ }
39
+
40
+ // Handle negative relative write positions
41
+ let pos = this.getPos();
42
+ if (pos < this.trackedStart) {
43
+ if (pos + data.byteLength <= this.trackedStart) {
44
+ return;
45
+ }
46
+
47
+ data = data.subarray(this.trackedStart - pos);
48
+ pos = 0;
49
+ }
50
+
51
+ const neededSize = pos + data.byteLength - this.trackedStart;
52
+ let newLength = this.trackedWrites.byteLength;
53
+ while (newLength < neededSize) {
54
+ newLength *= 2;
55
+ }
56
+
57
+ // Check if we need to resize the buffer
58
+ if (newLength !== this.trackedWrites.byteLength) {
59
+ const copy = new Uint8Array(newLength);
60
+ copy.set(this.trackedWrites, 0);
61
+ this.trackedWrites = copy;
62
+ }
63
+
64
+ this.trackedWrites.set(data, pos - this.trackedStart);
65
+ this.trackedEnd = Math.max(this.trackedEnd, pos + data.byteLength);
66
+ }
67
+
68
+ startTrackingWrites() {
69
+ this.trackedWrites = new Uint8Array(2 ** 10);
70
+ this.trackedStart = this.getPos();
71
+ this.trackedEnd = this.trackedStart;
72
+ }
73
+
74
+ stopTrackingWrites() {
75
+ if (!this.trackedWrites) {
76
+ throw new Error('Internal error: Can\'t get tracked writes since nothing was tracked.');
77
+ }
78
+
79
+ const slice = this.trackedWrites.subarray(0, this.trackedEnd - this.trackedStart);
80
+ const result = {
81
+ data: slice,
82
+ start: this.trackedStart,
83
+ end: this.trackedEnd,
84
+ };
85
+
86
+ this.trackedWrites = null;
87
+
88
+ return result;
89
+ }
90
+ }
91
+
92
+ const ARRAY_BUFFER_INITIAL_SIZE = 2 ** 16;
93
+ const ARRAY_BUFFER_MAX_SIZE = 2 ** 32;
94
+
95
+ export class BufferTargetWriter extends Writer {
96
+ private pos = 0;
97
+ private target: BufferTarget;
98
+ private buffer: ArrayBuffer;
99
+ private bytes: Uint8Array;
100
+ private maxPos = 0;
101
+ private supportsResize: boolean;
102
+
103
+ constructor(target: BufferTarget) {
104
+ super();
105
+
106
+ this.target = target;
107
+
108
+ this.supportsResize = 'resize' in new ArrayBuffer(0);
109
+ if (this.supportsResize) {
110
+ try {
111
+ // @ts-expect-error Don't want to bump "lib" in tsconfig
112
+ this.buffer = new ArrayBuffer(ARRAY_BUFFER_INITIAL_SIZE, { maxByteLength: ARRAY_BUFFER_MAX_SIZE });
113
+ } catch {
114
+ this.buffer = new ArrayBuffer(ARRAY_BUFFER_INITIAL_SIZE);
115
+ this.supportsResize = false;
116
+ }
117
+ } else {
118
+ this.buffer = new ArrayBuffer(ARRAY_BUFFER_INITIAL_SIZE);
119
+ }
120
+
121
+ this.bytes = new Uint8Array(this.buffer);
122
+ }
123
+
124
+ private ensureSize(size: number) {
125
+ let newLength = this.buffer.byteLength;
126
+ while (newLength < size) newLength *= 2;
127
+
128
+ if (newLength === this.buffer.byteLength) return;
129
+
130
+ if (newLength > ARRAY_BUFFER_MAX_SIZE) {
131
+ throw new Error(
132
+ `ArrayBuffer exceeded maximum size of ${ARRAY_BUFFER_MAX_SIZE} bytes. Please consider using another`
133
+ + ` target.`,
134
+ );
135
+ }
136
+
137
+ if (this.supportsResize) {
138
+ // Use resize if it exists
139
+ // @ts-expect-error Don't want to bump "lib" in tsconfig
140
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-call
141
+ this.buffer.resize(newLength);
142
+ // The Uint8Array scales automatically
143
+ } else {
144
+ const newBuffer = new ArrayBuffer(newLength);
145
+ const newBytes = new Uint8Array(newBuffer);
146
+ newBytes.set(this.bytes, 0);
147
+
148
+ this.buffer = newBuffer;
149
+ this.bytes = newBytes;
150
+ }
151
+ }
152
+
153
+ write(data: Uint8Array) {
154
+ this.maybeTrackWrites(data);
155
+
156
+ this.ensureSize(this.pos + data.byteLength);
157
+
158
+ this.bytes.set(data, this.pos);
159
+ this.pos += data.byteLength;
160
+
161
+ this.maxPos = Math.max(this.maxPos, this.pos);
162
+ }
163
+
164
+ seek(newPos: number) {
165
+ this.pos = newPos;
166
+ }
167
+
168
+ getPos() {
169
+ return this.pos;
170
+ }
171
+
172
+ async flush() {}
173
+
174
+ async finalize() {
175
+ this.ensureSize(this.pos);
176
+ this.target.buffer = this.buffer.slice(0, Math.max(this.maxPos, this.pos));
177
+ }
178
+
179
+ async close() {}
180
+
181
+ getSlice(start: number, end: number) {
182
+ return this.bytes.slice(start, end);
183
+ }
184
+ }
185
+
186
+ const DEFAULT_CHUNK_SIZE = 2 ** 24;
187
+ const MAX_CHUNKS_AT_ONCE = 2;
188
+
189
+ interface Chunk {
190
+ start: number;
191
+ written: ChunkSection[];
192
+ data: Uint8Array;
193
+ shouldFlush: boolean;
194
+ }
195
+
196
+ interface ChunkSection {
197
+ start: number;
198
+ end: number;
199
+ }
200
+
201
+ /**
202
+ * Writes to a StreamTarget every time it is flushed, sending out all of the new data written since the
203
+ * last flush. This is useful for streaming applications, like piping the output to disk. When using the chunked mode,
204
+ * data will first be accumulated in larger chunks, and then the entire chunk will be flushed out at once when ready.
205
+ */
206
+ export class StreamTargetWriter extends Writer {
207
+ private pos = 0;
208
+ private target: StreamTarget;
209
+ private sections: {
210
+ data: Uint8Array;
211
+ start: number;
212
+ }[] = [];
213
+
214
+ private lastWriteEnd = 0;
215
+ private lastFlushEnd = 0;
216
+ private writer: WritableStreamDefaultWriter<StreamTargetChunk> | null = null;
217
+
218
+ // These variables regard chunked mode:
219
+ private chunked: boolean;
220
+ private chunkSize: number;
221
+ /**
222
+ * The data is divided up into fixed-size chunks, whose contents are first filled in RAM and then flushed out.
223
+ * A chunk is flushed if all of its contents have been written.
224
+ */
225
+ private chunks: Chunk[] = [];
226
+
227
+ constructor(target: StreamTarget) {
228
+ super();
229
+
230
+ this.target = target;
231
+
232
+ this.chunked = target._options.chunked ?? false;
233
+ this.chunkSize = target._options.chunkSize ?? DEFAULT_CHUNK_SIZE;
234
+ }
235
+
236
+ override start() {
237
+ this.writer = this.target._writable.getWriter();
238
+ }
239
+
240
+ write(data: Uint8Array) {
241
+ if (this.pos > this.lastWriteEnd) {
242
+ const paddingBytesNeeded = this.pos - this.lastWriteEnd;
243
+ this.pos = this.lastWriteEnd;
244
+ this.write(new Uint8Array(paddingBytesNeeded));
245
+ }
246
+
247
+ this.maybeTrackWrites(data);
248
+
249
+ this.sections.push({
250
+ data: data.slice(),
251
+ start: this.pos,
252
+ });
253
+ this.pos += data.byteLength;
254
+
255
+ this.lastWriteEnd = Math.max(this.lastWriteEnd, this.pos);
256
+ }
257
+
258
+ seek(newPos: number) {
259
+ this.pos = newPos;
260
+ }
261
+
262
+ getPos() {
263
+ return this.pos;
264
+ }
265
+
266
+ async flush() {
267
+ if (this.pos > this.lastWriteEnd) {
268
+ // There's a "void" between the last written byte and the next byte we're about to write. Let's pad that
269
+ // void with zeroes explicitly.
270
+ const paddingBytesNeeded = this.pos - this.lastWriteEnd;
271
+ this.pos = this.lastWriteEnd;
272
+ this.write(new Uint8Array(paddingBytesNeeded));
273
+ }
274
+
275
+ assert(this.writer);
276
+ if (this.sections.length === 0) return;
277
+
278
+ const chunks: {
279
+ start: number;
280
+ size: number;
281
+ data?: Uint8Array;
282
+ }[] = [];
283
+ const sorted = [...this.sections].sort((a, b) => a.start - b.start);
284
+
285
+ chunks.push({
286
+ start: sorted[0]!.start,
287
+ size: sorted[0]!.data.byteLength,
288
+ });
289
+
290
+ // Figure out how many contiguous chunks we have
291
+ for (let i = 1; i < sorted.length; i++) {
292
+ const lastChunk = chunks[chunks.length - 1]!;
293
+ const section = sorted[i]!;
294
+
295
+ if (section.start <= lastChunk.start + lastChunk.size) {
296
+ lastChunk.size = Math.max(lastChunk.size, section.start + section.data.byteLength - lastChunk.start);
297
+ } else {
298
+ chunks.push({
299
+ start: section.start,
300
+ size: section.data.byteLength,
301
+ });
302
+ }
303
+ }
304
+
305
+ for (const chunk of chunks) {
306
+ chunk.data = new Uint8Array(chunk.size);
307
+
308
+ // Make sure to write the data in the correct order for correct overwriting
309
+ for (const section of this.sections) {
310
+ // Check if the section is in the chunk
311
+ if (chunk.start <= section.start && section.start < chunk.start + chunk.size) {
312
+ chunk.data.set(section.data, section.start - chunk.start);
313
+ }
314
+ }
315
+
316
+ if (this.writer.desiredSize !== null && this.writer.desiredSize <= 0) {
317
+ await this.writer.ready; // Allow the writer to apply backpressure
318
+ }
319
+
320
+ if (this.chunked) {
321
+ // Let's first gather the data into bigger chunks before writing it
322
+ this.writeDataIntoChunks(chunk.data, chunk.start);
323
+ this.tryToFlushChunks();
324
+ } else {
325
+ if (this.ensureMonotonicity && chunk.start !== this.lastFlushEnd) {
326
+ throw new Error('Internal error: Monotonicity violation.');
327
+ }
328
+
329
+ // Write out the data immediately
330
+ void this.writer.write({
331
+ type: 'write',
332
+ data: chunk.data,
333
+ position: chunk.start,
334
+ });
335
+
336
+ this.lastFlushEnd = chunk.start + chunk.data.byteLength;
337
+ }
338
+ }
339
+
340
+ this.sections.length = 0;
341
+ }
342
+
343
+ private writeDataIntoChunks(data: Uint8Array, position: number) {
344
+ // First, find the chunk to write the data into, or create one if none exists
345
+ let chunkIndex = this.chunks.findIndex(x => x.start <= position && position < x.start + this.chunkSize);
346
+ if (chunkIndex === -1) chunkIndex = this.createChunk(position);
347
+ const chunk = this.chunks[chunkIndex]!;
348
+
349
+ // Figure out how much to write to the chunk, and then write to the chunk
350
+ const relativePosition = position - chunk.start;
351
+ const toWrite = data.subarray(0, Math.min(this.chunkSize - relativePosition, data.byteLength));
352
+ chunk.data.set(toWrite, relativePosition);
353
+
354
+ // Create a section describing the region of data that was just written to
355
+ const section: ChunkSection = {
356
+ start: relativePosition,
357
+ end: relativePosition + toWrite.byteLength,
358
+ };
359
+ this.insertSectionIntoChunk(chunk, section);
360
+
361
+ // Queue chunk for flushing to target if it has been fully written to
362
+ if (chunk.written[0]!.start === 0 && chunk.written[0]!.end === this.chunkSize) {
363
+ chunk.shouldFlush = true;
364
+ }
365
+
366
+ // Make sure we don't hold too many chunks in memory at once to keep memory usage down
367
+ if (this.chunks.length > MAX_CHUNKS_AT_ONCE) {
368
+ // Flush all but the last chunk
369
+ for (let i = 0; i < this.chunks.length - 1; i++) {
370
+ this.chunks[i]!.shouldFlush = true;
371
+ }
372
+ this.tryToFlushChunks();
373
+ }
374
+
375
+ // If the data didn't fit in one chunk, recurse with the remaining data
376
+ if (toWrite.byteLength < data.byteLength) {
377
+ this.writeDataIntoChunks(data.subarray(toWrite.byteLength), position + toWrite.byteLength);
378
+ }
379
+ }
380
+
381
+ private insertSectionIntoChunk(chunk: Chunk, section: ChunkSection) {
382
+ let low = 0;
383
+ let high = chunk.written.length - 1;
384
+ let index = -1;
385
+
386
+ // Do a binary search to find the last section with a start not larger than `section`'s start
387
+ while (low <= high) {
388
+ const mid = Math.floor(low + (high - low + 1) / 2);
389
+
390
+ if (chunk.written[mid]!.start <= section.start) {
391
+ low = mid + 1;
392
+ index = mid;
393
+ } else {
394
+ high = mid - 1;
395
+ }
396
+ }
397
+
398
+ // Insert the new section
399
+ chunk.written.splice(index + 1, 0, section);
400
+ if (index === -1 || chunk.written[index]!.end < section.start) index++;
401
+
402
+ // Merge overlapping sections
403
+ while (index < chunk.written.length - 1 && chunk.written[index]!.end >= chunk.written[index + 1]!.start) {
404
+ chunk.written[index]!.end = Math.max(chunk.written[index]!.end, chunk.written[index + 1]!.end);
405
+ chunk.written.splice(index + 1, 1);
406
+ }
407
+ }
408
+
409
+ private createChunk(includesPosition: number) {
410
+ const start = Math.floor(includesPosition / this.chunkSize) * this.chunkSize;
411
+ const chunk: Chunk = {
412
+ start,
413
+ data: new Uint8Array(this.chunkSize),
414
+ written: [],
415
+ shouldFlush: false,
416
+ };
417
+ this.chunks.push(chunk);
418
+ this.chunks.sort((a, b) => a.start - b.start);
419
+
420
+ return this.chunks.indexOf(chunk);
421
+ }
422
+
423
+ private tryToFlushChunks(force = false) {
424
+ assert(this.writer);
425
+
426
+ for (let i = 0; i < this.chunks.length; i++) {
427
+ const chunk = this.chunks[i]!;
428
+ if (!chunk.shouldFlush && !force) continue;
429
+
430
+ for (const section of chunk.written) {
431
+ const position = chunk.start + section.start;
432
+ if (this.ensureMonotonicity && position !== this.lastFlushEnd) {
433
+ throw new Error('Internal error: Monotonicity violation.');
434
+ }
435
+
436
+ void this.writer.write({
437
+ type: 'write',
438
+ data: chunk.data.subarray(section.start, section.end),
439
+ position,
440
+ });
441
+
442
+ this.lastFlushEnd = chunk.start + section.end;
443
+ }
444
+
445
+ this.chunks.splice(i--, 1);
446
+ }
447
+ }
448
+
449
+ finalize() {
450
+ if (this.chunked) {
451
+ this.tryToFlushChunks(true);
452
+ }
453
+
454
+ assert(this.writer);
455
+ return this.writer.close();
456
+ }
457
+
458
+ async close() {
459
+ return this.writer?.close();
460
+ }
461
+ }
File without changes
File without changes