@meframe/core 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/dist/cache/index.d.ts +0 -3
  3. package/dist/cache/index.d.ts.map +1 -1
  4. package/dist/cache/resource/AudioSampleCache.d.ts +12 -0
  5. package/dist/cache/resource/AudioSampleCache.d.ts.map +1 -1
  6. package/dist/cache/resource/AudioSampleCache.js +40 -5
  7. package/dist/cache/resource/AudioSampleCache.js.map +1 -1
  8. package/dist/cache/resource/MP4IndexCache.d.ts.map +1 -1
  9. package/dist/cache/resource/MP4IndexCache.js +23 -13
  10. package/dist/cache/resource/MP4IndexCache.js.map +1 -1
  11. package/dist/cache/resource/ResourceCache.d.ts +4 -0
  12. package/dist/cache/resource/ResourceCache.d.ts.map +1 -1
  13. package/dist/cache/resource/ResourceCache.js +7 -0
  14. package/dist/cache/resource/ResourceCache.js.map +1 -1
  15. package/dist/index.d.ts +1 -1
  16. package/dist/index.js +1 -1
  17. package/dist/index.js.map +1 -1
  18. package/dist/orchestrator/AudioWindowPreparer.d.ts +5 -0
  19. package/dist/orchestrator/AudioWindowPreparer.d.ts.map +1 -1
  20. package/dist/orchestrator/AudioWindowPreparer.js +411 -26
  21. package/dist/orchestrator/AudioWindowPreparer.js.map +1 -1
  22. package/dist/orchestrator/Orchestrator.d.ts.map +1 -1
  23. package/dist/orchestrator/Orchestrator.js +20 -9
  24. package/dist/orchestrator/Orchestrator.js.map +1 -1
  25. package/dist/orchestrator/VideoWindowDecodeSession.d.ts.map +1 -1
  26. package/dist/orchestrator/VideoWindowDecodeSession.js +59 -47
  27. package/dist/orchestrator/VideoWindowDecodeSession.js.map +1 -1
  28. package/dist/orchestrator/aac-window-timeline.d.ts +11 -1
  29. package/dist/orchestrator/aac-window-timeline.d.ts.map +1 -1
  30. package/dist/orchestrator/aac-window-timeline.js +146 -17
  31. package/dist/orchestrator/aac-window-timeline.js.map +1 -1
  32. package/dist/stages/decode/preview-audio-decoder.d.ts +57 -0
  33. package/dist/stages/decode/preview-audio-decoder.d.ts.map +1 -0
  34. package/dist/stages/decode/preview-audio-decoder.js +281 -0
  35. package/dist/stages/decode/preview-audio-decoder.js.map +1 -0
  36. package/dist/stages/demux/MP3FrameParser.d.ts +18 -0
  37. package/dist/stages/demux/MP3FrameParser.d.ts.map +1 -1
  38. package/dist/stages/demux/MP3FrameParser.js +144 -11
  39. package/dist/stages/demux/MP3FrameParser.js.map +1 -1
  40. package/dist/stages/demux/MP4IndexParser.d.ts +34 -23
  41. package/dist/stages/demux/MP4IndexParser.d.ts.map +1 -1
  42. package/dist/stages/demux/MP4IndexParser.js +226 -326
  43. package/dist/stages/demux/MP4IndexParser.js.map +1 -1
  44. package/dist/stages/demux/MP4IndexWorkerClient.d.ts +15 -0
  45. package/dist/stages/demux/MP4IndexWorkerClient.d.ts.map +1 -0
  46. package/dist/stages/demux/MP4IndexWorkerClient.js +257 -0
  47. package/dist/stages/demux/MP4IndexWorkerClient.js.map +1 -0
  48. package/dist/stages/demux/SampleTable.d.ts +74 -0
  49. package/dist/stages/demux/SampleTable.d.ts.map +1 -0
  50. package/dist/stages/demux/SampleTable.js +259 -0
  51. package/dist/stages/demux/SampleTable.js.map +1 -0
  52. package/dist/stages/demux/mp4-index-protocol.d.ts +141 -0
  53. package/dist/stages/demux/mp4-index-protocol.d.ts.map +1 -0
  54. package/dist/stages/demux/mp4-index-protocol.js +108 -0
  55. package/dist/stages/demux/mp4-index-protocol.js.map +1 -0
  56. package/dist/stages/demux/sample-collector.d.ts +35 -0
  57. package/dist/stages/demux/sample-collector.d.ts.map +1 -0
  58. package/dist/stages/demux/sample-collector.js +105 -0
  59. package/dist/stages/demux/sample-collector.js.map +1 -0
  60. package/dist/stages/demux/types.d.ts +3 -2
  61. package/dist/stages/demux/types.d.ts.map +1 -1
  62. package/dist/stages/load/ResourceLoader.d.ts +6 -13
  63. package/dist/stages/load/ResourceLoader.d.ts.map +1 -1
  64. package/dist/stages/load/ResourceLoader.js +126 -80
  65. package/dist/stages/load/ResourceLoader.js.map +1 -1
  66. package/dist/stages/load/types.d.ts +2 -0
  67. package/dist/stages/load/types.d.ts.map +1 -1
  68. package/dist/worker/WorkerPool.d.ts +4 -0
  69. package/dist/worker/WorkerPool.d.ts.map +1 -1
  70. package/dist/worker/WorkerPool.js +10 -2
  71. package/dist/worker/WorkerPool.js.map +1 -1
  72. package/dist/worker/types.d.ts +1 -1
  73. package/dist/worker/types.d.ts.map +1 -1
  74. package/dist/worker/types.js.map +1 -1
  75. package/dist/worker/worker-event-whitelist.d.ts.map +1 -1
  76. package/dist/workers/stages/demux/mp4-index.worker.DaGeoDUz.js +8431 -0
  77. package/dist/workers/stages/demux/mp4-index.worker.DaGeoDUz.js.map +1 -0
  78. package/dist/workers/stages/export/export.worker.BG8HA7dY.js.map +1 -1
  79. package/dist/workers/worker-manifest.json +1 -0
  80. package/package.json +23 -22
  81. package/dist/cache/l2/IndexedDBStore.d.ts +0 -74
  82. package/dist/cache/l2/IndexedDBStore.d.ts.map +0 -1
  83. package/dist/cache/l2/L2Cache.d.ts +0 -78
  84. package/dist/cache/l2/L2Cache.d.ts.map +0 -1
  85. package/dist/cache/l2/L2OPFSStore.d.ts +0 -37
  86. package/dist/cache/l2/L2OPFSStore.d.ts.map +0 -1
  87. package/dist/cache/l2/OPFSStore.d.ts +0 -46
  88. package/dist/cache/l2/OPFSStore.d.ts.map +0 -1
  89. package/dist/cache/storage/indexeddb/ChunkRecordStore.d.ts +0 -75
  90. package/dist/cache/storage/indexeddb/ChunkRecordStore.d.ts.map +0 -1
@@ -1,305 +1,219 @@
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";
5
+ import { sampleByteLengthAt, sampleByteOffsetAt, SampleTable, sampleDurationAt, sampleTimestampAt, sampleIsKeyframeAt } from "./SampleTable.js";
4
6
  class MP4IndexParser {
5
7
  /**
6
- * Parse from streaming download
7
- * Returns video index + all audio samples
8
- * Can optionally extract first GOP for fast cover rendering
8
+ * Parse from a stream of the file from its first byte (download or cached file).
9
+ * Returns video index + all audio samples; can extract the first GOP for fast cover rendering.
9
10
  */
10
11
  async parseFromStream(stream, options) {
12
+ options?.signal?.throwIfAborted();
11
13
  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}`));
14
+ const mp4boxFile = MP4Box.createFile(false);
15
+ let info = null;
16
+ mp4boxFile.onReady = (readyInfo) => {
17
+ info = readyInfo;
38
18
  };
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);
19
+ let index = null;
20
+ let audioMeta = null;
21
+ let audio = null;
22
+ let cover = null;
23
+ let fileOffset = 0;
24
+ let nextParseOffset = 0;
25
+ let rangeJumpOffset;
26
+ for await (const value of readChunks(stream)) {
27
+ options?.signal?.throwIfAborted();
28
+ if (fileOffset === 0) this.assertLikelyMP4(value, resourceId);
29
+ if (!index || info.isFragmented) {
30
+ const chunkEnd = fileOffset + value.byteLength;
31
+ if (nextParseOffset !== void 0 && chunkEnd > nextParseOffset) {
32
+ const sliceFrom = Math.max(0, nextParseOffset - fileOffset);
33
+ const next = mp4boxFile.appendBuffer(
34
+ this.toFileBuffer(value.subarray(sliceFrom), fileOffset + sliceFrom)
35
+ );
36
+ nextParseOffset = next === void 0 ? void 0 : Math.max(next, chunkEnd);
75
37
  }
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
- }
38
+ if (info && !index) {
39
+ index = this.buildIndex(mp4boxFile, info);
40
+ audioMeta = this.extractAudioConfig(mp4boxFile, info);
41
+ if (audioMeta && (info.isFragmented || !options?.lazyAudio)) {
42
+ audio = this.createAudioExtraction(audioMeta);
96
43
  }
44
+ cover = this.startCoverExtraction(index, info, options?.onFirstFrameReady);
97
45
  }
98
- if (expectedAudioSamples !== Infinity && audioChunks.length >= expectedAudioSamples) {
99
- streamState.audioComplete = true;
100
- }
46
+ if (audio) this.registerNewAudioSamples(audio);
101
47
  }
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 });
48
+ audio?.collector.collect(value, fileOffset);
49
+ cover?.collect(value, fileOffset);
50
+ fileOffset += value.byteLength;
51
+ if (!index && options?.readRange && nextParseOffset !== void 0 && nextParseOffset - fileOffset >= READ_BUFFER_BYTES) {
52
+ rangeJumpOffset = nextParseOffset;
53
+ break;
54
+ }
55
+ if (index && !info.isFragmented && (audio?.collector.settled ?? true) && (cover?.settled ?? true)) {
56
+ break;
134
57
  }
135
58
  }
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;
59
+ if (fileOffset === 0) throw new EmptyStreamError(resourceId, 0);
60
+ if (!index && rangeJumpOffset !== void 0 && options?.readRange) {
61
+ let pos = rangeJumpOffset;
62
+ while (!index || info?.isFragmented) {
63
+ options?.signal?.throwIfAborted();
64
+ const buf = await options.readRange(pos, pos + READ_BUFFER_BYTES);
65
+ options?.signal?.throwIfAborted();
66
+ if (buf.byteLength === 0) break;
67
+ const chunk = new Uint8Array(buf);
68
+ const chunkEnd = pos + chunk.byteLength;
69
+ fileOffset = Math.max(fileOffset, chunkEnd);
70
+ const sliceFrom = Math.max(0, (nextParseOffset ?? pos) - pos);
71
+ if (sliceFrom < chunk.byteLength) {
72
+ const next = mp4boxFile.appendBuffer(
73
+ this.toFileBuffer(chunk.subarray(sliceFrom), pos + sliceFrom)
74
+ );
75
+ nextParseOffset = next === void 0 ? void 0 : Math.max(next, chunkEnd);
156
76
  }
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;
77
+ if (info && !index) {
78
+ index = this.buildIndex(mp4boxFile, info);
79
+ audioMeta = this.extractAudioConfig(mp4boxFile, info);
80
+ if (audioMeta && (info.isFragmented || !options.lazyAudio)) {
81
+ audio = this.createAudioExtraction(audioMeta);
169
82
  }
170
83
  }
84
+ if (audio) {
85
+ this.registerNewAudioSamples(audio);
86
+ audio.collector.collect(chunk, pos);
87
+ }
88
+ if (index && !info?.isFragmented) break;
89
+ pos = nextParseOffset !== void 0 && nextParseOffset > chunkEnd ? nextParseOffset : chunkEnd;
171
90
  }
172
- if (!hasData) {
173
- throw new EmptyStreamError(resourceId, streamState.fileOffset);
91
+ if (audio && !audio.collector.settled) {
92
+ audio.collector.collect(new Uint8Array(0), Number.MAX_SAFE_INTEGER);
174
93
  }
175
- } finally {
176
- reader.releaseLock();
177
94
  }
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)");
95
+ if (!index) throw new MP4MoovNotFoundError(resourceId, fileOffset);
96
+ if (info.isFragmented) {
97
+ const rebuilt = this.buildIndex(mp4boxFile, info);
98
+ index.durationUs = rebuilt.durationUs;
99
+ index.tracks = rebuilt.tracks;
182
100
  }
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
- );
101
+ if (!audioMeta) return { index };
102
+ if (!audio) return { index, audioMetadata: audioMeta.config };
103
+ if (audio.collector.missedCount > 0) {
104
+ if (!options?.readRange) return { index, audioMetadata: audio.config, audioBeforeMoov: true };
105
+ await audio.collector.readMissed(options.readRange, options?.signal);
193
106
  }
107
+ return { index, audioSamples: this.deliveredPrefix(audio), audioMetadata: audio.config };
108
+ }
109
+ /** mp4box keeps the buffers it is given until it has parsed them, so it gets a compact copy of the chunk slice. */
110
+ toFileBuffer(value, fileOffset) {
111
+ const buffer = new Uint8Array(value).buffer;
194
112
  buffer.fileStart = fileOffset;
195
113
  return buffer;
196
114
  }
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
- }
115
+ extractAudioConfig(mp4boxFile, info) {
116
+ const audioTrack = info.tracks.find((t) => t.type === "audio");
117
+ if (!audioTrack) return null;
118
+ const trackId = audioTrack.id;
119
+ const codec = normalizeAudioCodec(audioTrack.codec);
120
+ const config = {
121
+ codec,
122
+ sampleRate: audioTrack.audio.sample_rate || audioTrack.timescale,
123
+ numberOfChannels: audioTrack.audio.channel_count,
124
+ // MP4 contains raw AAC access units. Without AudioSpecificConfig the
125
+ // WebCodecs AAC decoder expects ADTS frames and can fail or emit silence.
126
+ // Opus decodes without a description; the dOps payload is not an OpusHead
127
+ // and Chrome rejects it as an unsupported configuration.
128
+ ...codec.startsWith("mp4a") && {
129
+ description: MP4Demuxer.extractAudioDescription(mp4boxFile, trackId)
228
130
  }
229
- }
131
+ };
132
+ const timescale = audioTrack.timescale || config.sampleRate;
133
+ const samples = mp4boxFile.getTrackById(trackId)?.samples ?? [];
134
+ return { config, timescale, samples };
230
135
  }
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
136
+ createAudioExtraction(details) {
137
+ const { config, timescale, samples } = details;
138
+ const chunks = [];
139
+ const collector = new SampleCollector((i, data) => {
140
+ const sample = samples[i];
141
+ chunks[i] = new EncodedAudioChunk({
142
+ type: sample.is_sync ? "key" : "delta",
143
+ timestamp: Math.round(sample.cts / timescale * 1e6),
144
+ duration: Math.round(sample.duration / timescale * 1e6),
145
+ data
251
146
  });
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 };
147
+ });
148
+ return { config, samples, chunks, collector };
149
+ }
150
+ registerNewAudioSamples(audio) {
151
+ const registered = audio.collector.registeredCount;
152
+ if (audio.samples.length > registered) audio.collector.add(audio.samples.slice(registered));
153
+ }
154
+ /** Samples are used up to the first one whose bytes never arrived (a truncated file). */
155
+ deliveredPrefix(audio) {
156
+ const { chunks } = audio;
157
+ let end = 0;
158
+ while (end < audio.samples.length && chunks[end]) end++;
159
+ chunks.length = end;
160
+ return chunks;
262
161
  }
263
162
  /**
264
- * Parse from file/ArrayBuffer (for already cached resources)
163
+ * Collects the first GOP of a fast-start file. A moov-at-end file has its first GOP before the moov; its cover is
164
+ * decoded from the cached file instead.
265
165
  */
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
- }
166
+ startCoverExtraction(index, info, onFirstFrameReady) {
167
+ const video = index.tracks.video;
168
+ const gop = video?.gopIndex[0];
169
+ if (!onFirstFrameReady || info.isProgressive !== true || !video || !gop) return null;
170
+ const first = gop.keyframeSampleIndex;
171
+ const count = gop.sampleCount;
172
+ const locations = new Array(count);
173
+ for (let i = 0; i < count; i++) {
174
+ const idx = first + i;
175
+ locations[i] = {
176
+ offset: sampleByteOffsetAt(video.samples, idx),
177
+ size: sampleByteLengthAt(video.samples, idx)
279
178
  };
179
+ }
180
+ const chunks = [];
181
+ let remaining = count;
182
+ const collector = new SampleCollector((i, data) => {
183
+ const idx = first + i;
184
+ chunks[i] = new EncodedVideoChunk({
185
+ type: sampleIsKeyframeAt(video.samples, idx) ? "key" : "delta",
186
+ timestamp: sampleTimestampAt(video.samples, idx),
187
+ duration: sampleDurationAt(video.samples, idx),
188
+ data
189
+ });
190
+ if (--remaining > 0) return;
191
+ try {
192
+ onFirstFrameReady(index, chunks);
193
+ } catch (error) {
194
+ console.warn("[MP4IndexParser] Failed to publish first GOP:", error);
195
+ }
280
196
  });
281
- let buffer;
282
- if (data instanceof File) {
283
- buffer = await data.arrayBuffer();
284
- } else {
285
- buffer = data;
197
+ collector.add(locations);
198
+ return collector;
199
+ }
200
+ assertLikelyMP4(firstChunk, resourceId) {
201
+ if (firstChunk.length >= 4 && firstChunk[0] === 26 && firstChunk[1] === 69 && firstChunk[2] === 223 && firstChunk[3] === 163) {
202
+ throw new NotMP4Error(resourceId, "matroska/webm (EBML)");
286
203
  }
287
- buffer.fileStart = 0;
288
- mp4boxFile.appendBuffer(buffer);
289
- mp4boxFile.flush();
290
- return indexPromise;
291
204
  }
292
205
  /**
293
206
  * Build MP4Index from mp4box.js parsed data
294
207
  */
295
208
  buildIndex(mp4boxFile, info) {
209
+ const rawDuration = info.duration || info.fragment_duration || 0;
296
210
  const index = {
297
211
  resourceId: "",
298
212
  // Will be set by caller
299
213
  moovOffset: 0,
300
214
  // mp4box doesn't expose this directly
301
215
  moovSize: 0,
302
- durationUs: info.duration / info.timescale * 1e6,
216
+ durationUs: info.timescale > 0 ? rawDuration / info.timescale * 1e6 : 0,
303
217
  tracks: {}
304
218
  };
305
219
  for (const trackInfo of info.tracks) {
@@ -309,6 +223,21 @@ class MP4IndexParser {
309
223
  index.tracks.audio = this.buildAudioTrackIndex(mp4boxFile, trackInfo);
310
224
  }
311
225
  }
226
+ if (index.durationUs <= 0) {
227
+ const maxEndUs = (samples) => {
228
+ if (!samples || samples.length === 0) return 0;
229
+ let max = 0;
230
+ for (let i = 0; i < samples.length; i++) {
231
+ const end = sampleTimestampAt(samples, i) + sampleDurationAt(samples, i);
232
+ if (end > max) max = end;
233
+ }
234
+ return max;
235
+ };
236
+ index.durationUs = Math.max(
237
+ maxEndUs(index.tracks.video?.samples),
238
+ maxEndUs(index.tracks.audio?.samples)
239
+ );
240
+ }
312
241
  return index;
313
242
  }
314
243
  /**
@@ -344,34 +273,36 @@ class MP4IndexParser {
344
273
  };
345
274
  }
346
275
  /**
347
- * Build sample table from mp4box track samples
276
+ * Build columnar SoA sample table directly from mp4box track samples without intermediate V8 objects.
348
277
  *
349
278
  * IMPORTANT: Keep samples in DTS (decode) order, not PTS (presentation) order!
350
279
  * VideoDecoder requires chunks in decode order. It will output frames in PTS order.
351
280
  */
352
281
  buildSampleTable(mp4boxFile, trackId, timescale) {
353
- const samples = [];
354
282
  const trak = mp4boxFile.getTrackById(trackId);
355
- if (!trak) return samples;
283
+ if (!trak) return new SampleTable(0);
356
284
  const sampleTable = trak.samples || [];
285
+ const n = sampleTable.length;
286
+ const table = new SampleTable(n);
357
287
  let timestampOffset = null;
358
- for (const sample of sampleTable) {
288
+ for (let i = 0; i < n; i++) {
289
+ const sample = sampleTable[i];
359
290
  const durationUs = (sample.duration || 0) / timescale * 1e6;
360
291
  const rawTimestampUs = (sample.cts || 0) / timescale * 1e6;
361
292
  if (timestampOffset === null) {
362
293
  timestampOffset = rawTimestampUs;
363
294
  }
364
295
  const timestampUs = rawTimestampUs - timestampOffset;
365
- samples.push({
366
- timestamp: timestampUs,
367
- // Normalized PTS (display timestamp)
368
- duration: durationUs,
369
- byteOffset: sample.offset || 0,
370
- byteLength: sample.size || 0,
371
- isKeyframe: sample.is_sync || false
372
- });
296
+ table.set(
297
+ i,
298
+ timestampUs,
299
+ durationUs,
300
+ sample.offset || 0,
301
+ sample.size || 0,
302
+ Boolean(sample.is_sync)
303
+ );
373
304
  }
374
- return samples;
305
+ return table;
375
306
  }
376
307
  /**
377
308
  * Extract video description (avcC/hvcC/etc) for VideoDecoder
@@ -381,21 +312,19 @@ class MP4IndexParser {
381
312
  return MP4Demuxer.extractVideoDescription(mp4boxFile, trackInfo.id);
382
313
  }
383
314
  /**
384
- * Build GOP index from samples
315
+ * Build GOP index from columnar sample table
385
316
  * GOP = Group of Pictures, starts with a keyframe
386
317
  */
387
318
  buildGOPIndex(samples) {
388
319
  const gopIndex = [];
389
320
  let currentGOP = null;
390
321
  for (let i = 0; i < samples.length; i++) {
391
- const sample = samples[i];
392
- if (!sample) continue;
393
- if (sample.isKeyframe) {
322
+ if (samples.isKeyframeAt(i)) {
394
323
  if (currentGOP) {
395
324
  gopIndex.push(currentGOP);
396
325
  }
397
326
  currentGOP = {
398
- startTimeUs: sample.timestamp,
327
+ startTimeUs: samples.timestampAt(i),
399
328
  keyframeSampleIndex: i,
400
329
  sampleCount: 1
401
330
  };
@@ -408,59 +337,30 @@ class MP4IndexParser {
408
337
  }
409
338
  return gopIndex;
410
339
  }
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);
340
+ }
341
+ const READ_BUFFER_BYTES = 1024 * 1024;
342
+ async function* readChunks(stream) {
343
+ let byob = null;
344
+ try {
345
+ byob = stream.getReader({ mode: "byob" });
346
+ } catch {
347
+ }
348
+ const reader = byob ?? stream.getReader();
349
+ let done = false;
350
+ try {
351
+ let buffer = new ArrayBuffer(READ_BUFFER_BYTES);
352
+ for (; ; ) {
353
+ const result = byob ? await byob.read(new Uint8Array(buffer)) : await reader.read();
354
+ if (result.done) {
355
+ done = true;
356
+ return;
457
357
  }
358
+ if (byob) buffer = result.value.buffer;
359
+ if (result.value.byteLength) yield result.value;
458
360
  }
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;
361
+ } finally {
362
+ if (!done) await reader.cancel().catch(() => void 0);
363
+ reader.releaseLock();
464
364
  }
465
365
  }
466
366
  export {