@meframe/core 0.7.0 → 0.7.2

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 (46) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/dist/cache/l2/IndexedDBStore.d.ts +1 -2
  3. package/dist/cache/l2/IndexedDBStore.d.ts.map +1 -1
  4. package/dist/cache/l2/L2Cache.d.ts +3 -2
  5. package/dist/cache/l2/L2Cache.d.ts.map +1 -1
  6. package/dist/cache/l2/L2OPFSStore.d.ts +3 -3
  7. package/dist/cache/l2/L2OPFSStore.d.ts.map +1 -1
  8. package/dist/cache/l2/OPFSStore.d.ts +1 -2
  9. package/dist/cache/l2/OPFSStore.d.ts.map +1 -1
  10. package/dist/cache/resource/AudioSampleCache.d.ts +12 -0
  11. package/dist/cache/resource/AudioSampleCache.d.ts.map +1 -1
  12. package/dist/cache/resource/AudioSampleCache.js +39 -5
  13. package/dist/cache/resource/AudioSampleCache.js.map +1 -1
  14. package/dist/cache/resource/ResourceCache.d.ts +4 -0
  15. package/dist/cache/resource/ResourceCache.d.ts.map +1 -1
  16. package/dist/cache/resource/ResourceCache.js +7 -0
  17. package/dist/cache/resource/ResourceCache.js.map +1 -1
  18. package/dist/index.d.ts +1 -1
  19. package/dist/index.js +1 -1
  20. package/dist/index.js.map +1 -1
  21. package/dist/orchestrator/AudioWindowPreparer.d.ts +1 -0
  22. package/dist/orchestrator/AudioWindowPreparer.d.ts.map +1 -1
  23. package/dist/orchestrator/AudioWindowPreparer.js +171 -26
  24. package/dist/orchestrator/AudioWindowPreparer.js.map +1 -1
  25. package/dist/orchestrator/aac-window-timeline.d.ts +5 -1
  26. package/dist/orchestrator/aac-window-timeline.d.ts.map +1 -1
  27. package/dist/orchestrator/aac-window-timeline.js +146 -17
  28. package/dist/orchestrator/aac-window-timeline.js.map +1 -1
  29. package/dist/stages/demux/MP3FrameParser.d.ts +18 -0
  30. package/dist/stages/demux/MP3FrameParser.d.ts.map +1 -1
  31. package/dist/stages/demux/MP3FrameParser.js +143 -11
  32. package/dist/stages/demux/MP3FrameParser.js.map +1 -1
  33. package/dist/stages/demux/MP4IndexParser.d.ts +32 -21
  34. package/dist/stages/demux/MP4IndexParser.d.ts.map +1 -1
  35. package/dist/stages/demux/MP4IndexParser.js +202 -309
  36. package/dist/stages/demux/MP4IndexParser.js.map +1 -1
  37. package/dist/stages/demux/sample-collector.d.ts +35 -0
  38. package/dist/stages/demux/sample-collector.d.ts.map +1 -0
  39. package/dist/stages/demux/sample-collector.js +105 -0
  40. package/dist/stages/demux/sample-collector.js.map +1 -0
  41. package/dist/stages/load/ResourceLoader.d.ts +5 -13
  42. package/dist/stages/load/ResourceLoader.d.ts.map +1 -1
  43. package/dist/stages/load/ResourceLoader.js +122 -77
  44. package/dist/stages/load/ResourceLoader.js.map +1 -1
  45. package/dist/workers/stages/export/export.worker.BG8HA7dY.js.map +1 -1
  46. package/package.json +23 -22
@@ -1,305 +1,212 @@
1
1
  import { MP4Box } from "../../utils/mp4box.js";
2
2
  import { normalizeAudioCodec, MP4Demuxer, normalizeVideoCodec } from "./MP4Demuxer.js";
3
- import { MP4MoovNotFoundError, EmptyStreamError, NotMP4Error } from "../../utils/errors.js";
3
+ import { EmptyStreamError, MP4MoovNotFoundError, NotMP4Error } from "../../utils/errors.js";
4
+ import { SampleCollector } from "./sample-collector.js";
4
5
  class MP4IndexParser {
5
6
  /**
6
- * Parse from streaming download
7
- * Returns video index + all audio samples
8
- * Can optionally extract first GOP for fast cover rendering
7
+ * Parse from a stream of the file from its first byte (download or cached file).
8
+ * Returns video index + all audio samples; can extract the first GOP for fast cover rendering.
9
9
  */
10
10
  async parseFromStream(stream, options) {
11
+ options?.signal?.throwIfAborted();
11
12
  const resourceId = options?.resourceId || "unknown";
12
- const mp4boxFile = MP4Box.createFile();
13
- let resolveResult = null;
14
- let rejectResult = null;
15
- const audioChunks = [];
16
- let audioConfig;
17
- let audioTrackId;
18
- let audioTimescale;
19
- let expectedAudioSamples = 0;
20
- let savedInfo = null;
21
- const resultPromise = new Promise((resolve, reject) => {
22
- resolveResult = resolve;
23
- rejectResult = reject;
24
- });
25
- const firstGOPState = {
26
- byteEnd: 0,
27
- extracted: !options?.onFirstFrameReady,
28
- index: null,
29
- buffer: new Uint8Array(0)
30
- };
31
- const streamState = {
32
- fileOffset: 0,
33
- moovParsed: false,
34
- audioComplete: false
35
- };
36
- mp4boxFile.onError = (error) => {
37
- rejectResult?.(new Error(`MP4Box error: ${error}`));
13
+ const mp4boxFile = MP4Box.createFile(false);
14
+ let info = null;
15
+ mp4boxFile.onReady = (readyInfo) => {
16
+ info = readyInfo;
38
17
  };
39
- mp4boxFile.onReady = (info) => {
40
- try {
41
- streamState.moovParsed = true;
42
- savedInfo = info;
43
- const index = this.buildIndex(mp4boxFile, info);
44
- firstGOPState.index = index;
45
- const isFastStart = info.isProgressive === true;
46
- if (isFastStart && options?.onFirstFrameReady && index.tracks.video?.gopIndex[0]) {
47
- const firstGOP = index.tracks.video.gopIndex[0];
48
- const samples = index.tracks.video.samples;
49
- const startIdx = firstGOP.keyframeSampleIndex;
50
- const endIdx = startIdx + firstGOP.sampleCount;
51
- let byteEnd = 0;
52
- for (let i = startIdx; i < endIdx; i++) {
53
- const sample = samples[i];
54
- if (!sample) continue;
55
- const end = sample.byteOffset + sample.byteLength;
56
- if (end > byteEnd) byteEnd = end;
57
- }
58
- firstGOPState.byteEnd = byteEnd;
59
- }
60
- const { config, trackId, timescale, expectedSamples, isComplete } = this.setupAudioExtraction(mp4boxFile, info);
61
- audioConfig = config;
62
- audioTrackId = trackId;
63
- audioTimescale = timescale;
64
- expectedAudioSamples = expectedSamples;
65
- streamState.audioComplete = isComplete;
66
- if (!isComplete && audioTrackId && audioConfig) {
67
- mp4boxFile.start();
68
- }
69
- if (isComplete) {
70
- setTimeout(() => {
71
- if (streamState.moovParsed && streamState.audioComplete && firstGOPState.extracted) {
72
- resolveResult?.({ index });
73
- }
74
- }, 0);
18
+ let index = null;
19
+ let audioMeta = null;
20
+ let audio = null;
21
+ let cover = null;
22
+ let fileOffset = 0;
23
+ let nextParseOffset = 0;
24
+ let rangeJumpOffset;
25
+ for await (const value of readChunks(stream)) {
26
+ options?.signal?.throwIfAborted();
27
+ if (fileOffset === 0) this.assertLikelyMP4(value, resourceId);
28
+ if (!index || info.isFragmented) {
29
+ const chunkEnd = fileOffset + value.byteLength;
30
+ if (nextParseOffset !== void 0 && chunkEnd > nextParseOffset) {
31
+ const sliceFrom = Math.max(0, nextParseOffset - fileOffset);
32
+ const next = mp4boxFile.appendBuffer(
33
+ this.toFileBuffer(value.subarray(sliceFrom), fileOffset + sliceFrom)
34
+ );
35
+ nextParseOffset = next === void 0 ? void 0 : Math.max(next, chunkEnd);
75
36
  }
76
- } catch (error) {
77
- rejectResult?.(error);
78
- }
79
- };
80
- mp4boxFile.onSamples = (trackId, _user, samples) => {
81
- if (trackId === audioTrackId && audioConfig) {
82
- const timescale = audioTimescale || audioConfig.sampleRate;
83
- if (samples && samples.length > 0) {
84
- for (const sample of samples) {
85
- try {
86
- const chunk = new EncodedAudioChunk({
87
- type: sample.is_sync ? "key" : "delta",
88
- timestamp: Math.round(sample.cts / timescale * 1e6),
89
- duration: Math.round(sample.duration / timescale * 1e6),
90
- data: sample.data
91
- });
92
- audioChunks.push(chunk);
93
- } catch (error) {
94
- console.warn("[MP4IndexParser] Failed to create audio chunk:", error);
95
- }
37
+ if (info && !index) {
38
+ index = this.buildIndex(mp4boxFile, info);
39
+ audioMeta = this.extractAudioConfig(mp4boxFile, info);
40
+ if (audioMeta && (info.isFragmented || !options?.lazyAudio)) {
41
+ audio = this.createAudioExtraction(audioMeta);
96
42
  }
43
+ cover = this.startCoverExtraction(index, info, options?.onFirstFrameReady);
97
44
  }
98
- if (expectedAudioSamples !== Infinity && audioChunks.length >= expectedAudioSamples) {
99
- streamState.audioComplete = true;
100
- }
45
+ if (audio) this.registerNewAudioSamples(audio);
101
46
  }
102
- };
103
- await this.processStreamData(
104
- stream,
105
- mp4boxFile,
106
- options,
107
- firstGOPState,
108
- streamState,
109
- resourceId
110
- );
111
- mp4boxFile.flush();
112
- await new Promise((resolve) => setTimeout(resolve, 100));
113
- if (!streamState.moovParsed) {
114
- throw new MP4MoovNotFoundError(resourceId, streamState.fileOffset);
115
- }
116
- if (streamState.moovParsed && streamState.audioComplete) {
117
- const index = firstGOPState.index || this.buildIndex(mp4boxFile, savedInfo);
118
- resolveResult({
119
- index,
120
- audioSamples: audioChunks,
121
- audioMetadata: audioConfig
122
- });
123
- } else if (streamState.moovParsed && !streamState.audioComplete && savedInfo) {
124
- streamState.audioComplete = true;
125
- const index = firstGOPState.index || this.buildIndex(mp4boxFile, savedInfo);
126
- if (audioChunks.length > 0 && audioConfig) {
127
- resolveResult({
128
- index,
129
- audioSamples: audioChunks,
130
- audioMetadata: audioConfig
131
- });
132
- } else {
133
- resolveResult({ index });
47
+ audio?.collector.collect(value, fileOffset);
48
+ cover?.collect(value, fileOffset);
49
+ fileOffset += value.byteLength;
50
+ if (!index && options?.readRange && nextParseOffset !== void 0 && nextParseOffset - fileOffset >= READ_BUFFER_BYTES) {
51
+ rangeJumpOffset = nextParseOffset;
52
+ break;
53
+ }
54
+ if (index && !info.isFragmented && (audio?.collector.settled ?? true) && (cover?.settled ?? true)) {
55
+ break;
134
56
  }
135
57
  }
136
- const parseTimeout = new Promise((_, reject) => {
137
- setTimeout(() => {
138
- reject(
139
- new Error(
140
- `MP4Box parsing timeout after reading ${streamState.fileOffset} bytes. moovParsed=${streamState.moovParsed}, audioExtractionComplete=${streamState.audioComplete}`
141
- )
142
- );
143
- }, 5e3);
144
- });
145
- return await Promise.race([resultPromise, parseTimeout]);
146
- }
147
- async processStreamData(stream, mp4boxFile, options, firstGOPState, streamState, resourceId) {
148
- const reader = stream.getReader();
149
- try {
150
- let hasData = false;
151
- let containerValidated = false;
152
- while (true) {
153
- const { done, value } = await reader.read();
154
- if (done) {
155
- break;
58
+ if (fileOffset === 0) throw new EmptyStreamError(resourceId, 0);
59
+ if (!index && rangeJumpOffset !== void 0 && options?.readRange) {
60
+ let pos = rangeJumpOffset;
61
+ while (!index || info?.isFragmented) {
62
+ options?.signal?.throwIfAborted();
63
+ const buf = await options.readRange(pos, pos + READ_BUFFER_BYTES);
64
+ options?.signal?.throwIfAborted();
65
+ if (buf.byteLength === 0) break;
66
+ const chunk = new Uint8Array(buf);
67
+ const chunkEnd = pos + chunk.byteLength;
68
+ fileOffset = Math.max(fileOffset, chunkEnd);
69
+ const sliceFrom = Math.max(0, (nextParseOffset ?? pos) - pos);
70
+ if (sliceFrom < chunk.byteLength) {
71
+ const next = mp4boxFile.appendBuffer(
72
+ this.toFileBuffer(chunk.subarray(sliceFrom), pos + sliceFrom)
73
+ );
74
+ nextParseOffset = next === void 0 ? void 0 : Math.max(next, chunkEnd);
156
75
  }
157
- if (value) {
158
- hasData = true;
159
- if (!containerValidated) {
160
- this.assertLikelyMP4(value, resourceId);
161
- containerValidated = true;
162
- }
163
- const buffer = this.prepareBuffer(value, streamState.fileOffset);
164
- this.handleFirstGOPExtraction(value, options, firstGOPState, streamState);
165
- mp4boxFile.appendBuffer(buffer);
166
- streamState.fileOffset += buffer.byteLength;
167
- if (streamState.moovParsed && streamState.audioComplete && firstGOPState.extracted) {
168
- break;
76
+ if (info && !index) {
77
+ index = this.buildIndex(mp4boxFile, info);
78
+ audioMeta = this.extractAudioConfig(mp4boxFile, info);
79
+ if (audioMeta && (info.isFragmented || !options.lazyAudio)) {
80
+ audio = this.createAudioExtraction(audioMeta);
169
81
  }
170
82
  }
83
+ if (audio) {
84
+ this.registerNewAudioSamples(audio);
85
+ audio.collector.collect(chunk, pos);
86
+ }
87
+ if (index && !info?.isFragmented) break;
88
+ pos = nextParseOffset !== void 0 && nextParseOffset > chunkEnd ? nextParseOffset : chunkEnd;
171
89
  }
172
- if (!hasData) {
173
- throw new EmptyStreamError(resourceId, streamState.fileOffset);
90
+ if (audio && !audio.collector.settled) {
91
+ audio.collector.collect(new Uint8Array(0), Number.MAX_SAFE_INTEGER);
174
92
  }
175
- } finally {
176
- reader.releaseLock();
177
93
  }
178
- }
179
- assertLikelyMP4(firstChunk, resourceId) {
180
- if (firstChunk.length >= 4 && firstChunk[0] === 26 && firstChunk[1] === 69 && firstChunk[2] === 223 && firstChunk[3] === 163) {
181
- throw new NotMP4Error(resourceId, "matroska/webm (EBML)");
94
+ if (!index) throw new MP4MoovNotFoundError(resourceId, fileOffset);
95
+ if (info.isFragmented) {
96
+ const rebuilt = this.buildIndex(mp4boxFile, info);
97
+ index.durationUs = rebuilt.durationUs;
98
+ index.tracks = rebuilt.tracks;
182
99
  }
183
- }
184
- prepareBuffer(value, fileOffset) {
185
- let buffer;
186
- if (value.byteOffset === 0 && value.byteLength === value.buffer.byteLength) {
187
- buffer = value.buffer;
188
- } else {
189
- buffer = value.buffer.slice(
190
- value.byteOffset,
191
- value.byteOffset + value.byteLength
192
- );
100
+ if (!audioMeta) return { index };
101
+ if (!audio) return { index, audioMetadata: audioMeta.config };
102
+ if (audio.collector.missedCount > 0) {
103
+ if (!options?.readRange) return { index, audioMetadata: audio.config, audioBeforeMoov: true };
104
+ await audio.collector.readMissed(options.readRange, options?.signal);
193
105
  }
106
+ return { index, audioSamples: this.deliveredPrefix(audio), audioMetadata: audio.config };
107
+ }
108
+ /** mp4box keeps the buffers it is given until it has parsed them, so it gets a compact copy of the chunk slice. */
109
+ toFileBuffer(value, fileOffset) {
110
+ const buffer = new Uint8Array(value).buffer;
194
111
  buffer.fileStart = fileOffset;
195
112
  return buffer;
196
113
  }
197
- handleFirstGOPExtraction(value, options, firstGOPState, streamState) {
198
- if (!firstGOPState.extracted && options?.onFirstFrameReady) {
199
- if (firstGOPState.buffer.length + value.length < 10 * 1024 * 1024) {
200
- const newBuffer = new Uint8Array(firstGOPState.buffer.length + value.length);
201
- newBuffer.set(firstGOPState.buffer);
202
- newBuffer.set(value, firstGOPState.buffer.length);
203
- firstGOPState.buffer = newBuffer;
204
- } else if (!streamState.moovParsed) {
205
- firstGOPState.extracted = true;
206
- firstGOPState.buffer = new Uint8Array(0);
207
- }
208
- if (streamState.moovParsed && firstGOPState.byteEnd > 0 && firstGOPState.index && // Extraction buffer is accumulated with a safety cap (10MB).
209
- // Do NOT use download progress (fileOffset) as a signal here, otherwise we may trigger extraction
210
- // even when the accumulated buffer doesn't contain all referenced samples yet.
211
- firstGOPState.buffer.length >= firstGOPState.byteEnd) {
212
- try {
213
- const currentIndex = firstGOPState.index;
214
- const videoTrack = currentIndex.tracks.video;
215
- if (videoTrack && videoTrack.gopIndex[0]) {
216
- const chunks = this.extractFirstGOP(firstGOPState.buffer, videoTrack, 0);
217
- if (chunks.length > 0) {
218
- options.onFirstFrameReady?.(currentIndex, chunks);
219
- }
220
- }
221
- firstGOPState.extracted = true;
222
- firstGOPState.buffer = new Uint8Array(0);
223
- } catch (error) {
224
- console.warn("[MP4IndexParser] Failed to extract first GOP:", error);
225
- firstGOPState.extracted = true;
226
- firstGOPState.buffer = new Uint8Array(0);
227
- }
114
+ extractAudioConfig(mp4boxFile, info) {
115
+ const audioTrack = info.tracks.find((t) => t.type === "audio");
116
+ if (!audioTrack) return null;
117
+ const trackId = audioTrack.id;
118
+ const codec = normalizeAudioCodec(audioTrack.codec);
119
+ const config = {
120
+ codec,
121
+ sampleRate: audioTrack.audio.sample_rate || audioTrack.timescale,
122
+ numberOfChannels: audioTrack.audio.channel_count,
123
+ // MP4 contains raw AAC access units. Without AudioSpecificConfig the
124
+ // WebCodecs AAC decoder expects ADTS frames and can fail or emit silence.
125
+ // Opus decodes without a description; the dOps payload is not an OpusHead
126
+ // and Chrome rejects it as an unsupported configuration.
127
+ ...codec.startsWith("mp4a") && {
128
+ description: MP4Demuxer.extractAudioDescription(mp4boxFile, trackId)
228
129
  }
229
- }
130
+ };
131
+ const timescale = audioTrack.timescale || config.sampleRate;
132
+ const samples = mp4boxFile.getTrackById(trackId)?.samples ?? [];
133
+ return { config, timescale, samples };
230
134
  }
231
- setupAudioExtraction(mp4boxFile, info) {
232
- const audioTrack = info.tracks.find((t) => t.type === "audio");
233
- if (audioTrack) {
234
- const trackId = audioTrack.id;
235
- const codec = normalizeAudioCodec(audioTrack.codec);
236
- const config = {
237
- codec,
238
- sampleRate: audioTrack.audio.sample_rate || audioTrack.timescale,
239
- numberOfChannels: audioTrack.audio.channel_count,
240
- // MP4 contains raw AAC access units. Without AudioSpecificConfig the
241
- // WebCodecs AAC decoder expects ADTS frames and can fail or emit silence.
242
- // Opus decodes without a description; the dOps payload is not an OpusHead
243
- // and Chrome rejects it as an unsupported configuration.
244
- ...codec.startsWith("mp4a") && {
245
- description: MP4Demuxer.extractAudioDescription(mp4boxFile, trackId)
246
- }
247
- };
248
- mp4boxFile.setExtractionOptions(trackId, audioTrack, {
249
- nbSamples: Infinity
250
- // Extract all samples
135
+ createAudioExtraction(details) {
136
+ const { config, timescale, samples } = details;
137
+ const chunks = [];
138
+ const collector = new SampleCollector((i, data) => {
139
+ const sample = samples[i];
140
+ chunks[i] = new EncodedAudioChunk({
141
+ type: sample.is_sync ? "key" : "delta",
142
+ timestamp: Math.round(sample.cts / timescale * 1e6),
143
+ duration: Math.round(sample.duration / timescale * 1e6),
144
+ data
251
145
  });
252
- return {
253
- config,
254
- trackId,
255
- timescale: audioTrack.timescale,
256
- // Use track timescale for time calculations
257
- expectedSamples: audioTrack.nb_samples || Infinity,
258
- isComplete: false
259
- };
260
- }
261
- return { expectedSamples: 0, isComplete: true };
146
+ });
147
+ return { config, samples, chunks, collector };
148
+ }
149
+ registerNewAudioSamples(audio) {
150
+ const registered = audio.collector.registeredCount;
151
+ if (audio.samples.length > registered) audio.collector.add(audio.samples.slice(registered));
152
+ }
153
+ /** Samples are used up to the first one whose bytes never arrived (a truncated file). */
154
+ deliveredPrefix(audio) {
155
+ const { chunks } = audio;
156
+ let end = 0;
157
+ while (end < audio.samples.length && chunks[end]) end++;
158
+ chunks.length = end;
159
+ return chunks;
262
160
  }
263
161
  /**
264
- * Parse from file/ArrayBuffer (for already cached resources)
162
+ * Collects the first GOP of a fast-start file. A moov-at-end file has its first GOP before the moov; its cover is
163
+ * decoded from the cached file instead.
265
164
  */
266
- async parseFromFile(data) {
267
- const mp4boxFile = MP4Box.createFile();
268
- const indexPromise = new Promise((resolve, reject) => {
269
- mp4boxFile.onError = (error) => {
270
- reject(new Error(`MP4Box error: ${error}`));
271
- };
272
- mp4boxFile.onReady = (info) => {
273
- try {
274
- const index = this.buildIndex(mp4boxFile, info);
275
- resolve(index);
276
- } catch (error) {
277
- reject(error);
278
- }
279
- };
165
+ startCoverExtraction(index, info, onFirstFrameReady) {
166
+ const video = index.tracks.video;
167
+ const gop = video?.gopIndex[0];
168
+ if (!onFirstFrameReady || info.isProgressive !== true || !video || !gop) return null;
169
+ const samples = video.samples.slice(
170
+ gop.keyframeSampleIndex,
171
+ gop.keyframeSampleIndex + gop.sampleCount
172
+ );
173
+ const chunks = [];
174
+ let remaining = samples.length;
175
+ const collector = new SampleCollector((i, data) => {
176
+ const sample = samples[i];
177
+ chunks[i] = new EncodedVideoChunk({
178
+ type: sample.isKeyframe ? "key" : "delta",
179
+ timestamp: sample.timestamp,
180
+ duration: sample.duration,
181
+ data
182
+ });
183
+ if (--remaining > 0) return;
184
+ try {
185
+ onFirstFrameReady(index, chunks);
186
+ } catch (error) {
187
+ console.warn("[MP4IndexParser] Failed to publish first GOP:", error);
188
+ }
280
189
  });
281
- let buffer;
282
- if (data instanceof File) {
283
- buffer = await data.arrayBuffer();
284
- } else {
285
- buffer = data;
190
+ collector.add(samples.map((s) => ({ offset: s.byteOffset, size: s.byteLength })));
191
+ return collector;
192
+ }
193
+ assertLikelyMP4(firstChunk, resourceId) {
194
+ if (firstChunk.length >= 4 && firstChunk[0] === 26 && firstChunk[1] === 69 && firstChunk[2] === 223 && firstChunk[3] === 163) {
195
+ throw new NotMP4Error(resourceId, "matroska/webm (EBML)");
286
196
  }
287
- buffer.fileStart = 0;
288
- mp4boxFile.appendBuffer(buffer);
289
- mp4boxFile.flush();
290
- return indexPromise;
291
197
  }
292
198
  /**
293
199
  * Build MP4Index from mp4box.js parsed data
294
200
  */
295
201
  buildIndex(mp4boxFile, info) {
202
+ const rawDuration = info.duration || info.fragment_duration || 0;
296
203
  const index = {
297
204
  resourceId: "",
298
205
  // Will be set by caller
299
206
  moovOffset: 0,
300
207
  // mp4box doesn't expose this directly
301
208
  moovSize: 0,
302
- durationUs: info.duration / info.timescale * 1e6,
209
+ durationUs: info.timescale > 0 ? rawDuration / info.timescale * 1e6 : 0,
303
210
  tracks: {}
304
211
  };
305
212
  for (const trackInfo of info.tracks) {
@@ -309,6 +216,21 @@ class MP4IndexParser {
309
216
  index.tracks.audio = this.buildAudioTrackIndex(mp4boxFile, trackInfo);
310
217
  }
311
218
  }
219
+ if (index.durationUs <= 0) {
220
+ const maxEndUs = (samples) => {
221
+ if (!samples || samples.length === 0) return 0;
222
+ let max = 0;
223
+ for (const s of samples) {
224
+ const end = s.timestamp + s.duration;
225
+ if (end > max) max = end;
226
+ }
227
+ return max;
228
+ };
229
+ index.durationUs = Math.max(
230
+ maxEndUs(index.tracks.video?.samples),
231
+ maxEndUs(index.tracks.audio?.samples)
232
+ );
233
+ }
312
234
  return index;
313
235
  }
314
236
  /**
@@ -408,59 +330,30 @@ class MP4IndexParser {
408
330
  }
409
331
  return gopIndex;
410
332
  }
411
- /**
412
- * Extract first GOP chunks from accumulated buffer
413
- * Used for fast cover rendering during streaming download
414
- */
415
- extractFirstGOP(buffer, videoTrack, byteStart) {
416
- const chunks = [];
417
- const firstGOP = videoTrack.gopIndex[0];
418
- if (!firstGOP) {
419
- return chunks;
420
- }
421
- const samples = videoTrack.samples;
422
- for (let i = 0; i < firstGOP.sampleCount; i++) {
423
- const sampleIdx = firstGOP.keyframeSampleIndex + i;
424
- const sample = samples[sampleIdx];
425
- if (!sample) continue;
426
- const relativeOffset = sample.byteOffset - byteStart;
427
- if (relativeOffset < 0 || relativeOffset + sample.byteLength > buffer.length) {
428
- if (i === 0) {
429
- console.warn(
430
- "[MP4IndexParser] First GOP keyframe not fully downloaded, skipping cover decode"
431
- );
432
- return [];
433
- }
434
- console.warn("[MP4IndexParser] Sample outside buffer:", {
435
- sampleOffset: sample.byteOffset,
436
- sampleLength: sample.byteLength,
437
- byteStart,
438
- relativeOffset,
439
- bufferLength: buffer.length,
440
- isKeyframe: sample.isKeyframe,
441
- sampleIndex: i
442
- });
443
- continue;
444
- }
445
- const sampleData = buffer.slice(relativeOffset, relativeOffset + sample.byteLength);
446
- try {
447
- chunks.push(
448
- new EncodedVideoChunk({
449
- type: sample.isKeyframe ? "key" : "delta",
450
- timestamp: sample.timestamp,
451
- duration: sample.duration,
452
- data: sampleData
453
- })
454
- );
455
- } catch (error) {
456
- console.warn("[MP4IndexParser] Failed to create EncodedVideoChunk:", error);
333
+ }
334
+ const READ_BUFFER_BYTES = 1024 * 1024;
335
+ async function* readChunks(stream) {
336
+ let byob = null;
337
+ try {
338
+ byob = stream.getReader({ mode: "byob" });
339
+ } catch {
340
+ }
341
+ const reader = byob ?? stream.getReader();
342
+ let done = false;
343
+ try {
344
+ let buffer = new ArrayBuffer(READ_BUFFER_BYTES);
345
+ for (; ; ) {
346
+ const result = byob ? await byob.read(new Uint8Array(buffer)) : await reader.read();
347
+ if (result.done) {
348
+ done = true;
349
+ return;
457
350
  }
351
+ if (byob) buffer = result.value.buffer;
352
+ if (result.value.byteLength) yield result.value;
458
353
  }
459
- if (chunks.length > 0 && chunks[0]?.type !== "key") {
460
- console.error("[MP4IndexParser] First chunk is not a keyframe, discarding all chunks");
461
- return [];
462
- }
463
- return chunks;
354
+ } finally {
355
+ if (!done) await reader.cancel().catch(() => void 0);
356
+ reader.releaseLock();
464
357
  }
465
358
  }
466
359
  export {