@meframe/core 0.6.6 → 0.6.8

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 (95) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/Meframe.d.ts +30 -0
  3. package/dist/Meframe.d.ts.map +1 -1
  4. package/dist/Meframe.js +78 -29
  5. package/dist/Meframe.js.map +1 -1
  6. package/dist/cache/AudioMixBlockCache.d.ts +13 -10
  7. package/dist/cache/AudioMixBlockCache.d.ts.map +1 -1
  8. package/dist/cache/AudioMixBlockCache.js +39 -26
  9. package/dist/cache/AudioMixBlockCache.js.map +1 -1
  10. package/dist/cache/CacheManager.d.ts +26 -2
  11. package/dist/cache/CacheManager.d.ts.map +1 -1
  12. package/dist/cache/CacheManager.js +32 -8
  13. package/dist/cache/CacheManager.js.map +1 -1
  14. package/dist/cache/l1/AudioL1Cache.d.ts +29 -8
  15. package/dist/cache/l1/AudioL1Cache.d.ts.map +1 -1
  16. package/dist/cache/l1/AudioL1Cache.js +133 -83
  17. package/dist/cache/l1/AudioL1Cache.js.map +1 -1
  18. package/dist/cache/resource/AudioSampleCache.d.ts +1 -0
  19. package/dist/cache/resource/AudioSampleCache.d.ts.map +1 -1
  20. package/dist/cache/resource/AudioSampleCache.js +3 -0
  21. package/dist/cache/resource/AudioSampleCache.js.map +1 -1
  22. package/dist/cache/resource/MP4IndexCache.d.ts +1 -0
  23. package/dist/cache/resource/MP4IndexCache.d.ts.map +1 -1
  24. package/dist/cache/resource/MP4IndexCache.js +3 -0
  25. package/dist/cache/resource/MP4IndexCache.js.map +1 -1
  26. package/dist/config/defaults.d.ts.map +1 -1
  27. package/dist/config/defaults.js +1 -0
  28. package/dist/config/defaults.js.map +1 -1
  29. package/dist/config/types.d.ts +9 -0
  30. package/dist/config/types.d.ts.map +1 -1
  31. package/dist/config/validation.d.ts.map +1 -1
  32. package/dist/config/validation.js +5 -0
  33. package/dist/config/validation.js.map +1 -1
  34. package/dist/controllers/PlaybackController.d.ts +1 -1
  35. package/dist/controllers/PlaybackController.d.ts.map +1 -1
  36. package/dist/controllers/PlaybackController.js +20 -2
  37. package/dist/controllers/PlaybackController.js.map +1 -1
  38. package/dist/controllers/PlaybackStateMachine.d.ts.map +1 -1
  39. package/dist/controllers/PlaybackStateMachine.js +4 -1
  40. package/dist/controllers/PlaybackStateMachine.js.map +1 -1
  41. package/dist/controllers/types.d.ts +1 -0
  42. package/dist/controllers/types.d.ts.map +1 -1
  43. package/dist/controllers/types.js.map +1 -1
  44. package/dist/model/patch.d.ts.map +1 -1
  45. package/dist/model/patch.js +28 -9
  46. package/dist/model/patch.js.map +1 -1
  47. package/dist/model/validation.d.ts.map +1 -1
  48. package/dist/model/validation.js +4 -0
  49. package/dist/model/validation.js.map +1 -1
  50. package/dist/orchestrator/AudioExportSession.d.ts +0 -5
  51. package/dist/orchestrator/AudioExportSession.d.ts.map +1 -1
  52. package/dist/orchestrator/AudioExportSession.js +8 -16
  53. package/dist/orchestrator/AudioExportSession.js.map +1 -1
  54. package/dist/orchestrator/AudioPreviewSession.d.ts +13 -0
  55. package/dist/orchestrator/AudioPreviewSession.d.ts.map +1 -1
  56. package/dist/orchestrator/AudioPreviewSession.js +151 -75
  57. package/dist/orchestrator/AudioPreviewSession.js.map +1 -1
  58. package/dist/orchestrator/AudioWindowPreparer.d.ts +38 -9
  59. package/dist/orchestrator/AudioWindowPreparer.d.ts.map +1 -1
  60. package/dist/orchestrator/AudioWindowPreparer.js +207 -55
  61. package/dist/orchestrator/AudioWindowPreparer.js.map +1 -1
  62. package/dist/orchestrator/ExportScheduler.d.ts.map +1 -1
  63. package/dist/orchestrator/ExportScheduler.js +4 -2
  64. package/dist/orchestrator/ExportScheduler.js.map +1 -1
  65. package/dist/orchestrator/Orchestrator.d.ts +26 -0
  66. package/dist/orchestrator/Orchestrator.d.ts.map +1 -1
  67. package/dist/orchestrator/Orchestrator.js +149 -8
  68. package/dist/orchestrator/Orchestrator.js.map +1 -1
  69. package/dist/orchestrator/PreviewFrameScheduler.d.ts.map +1 -1
  70. package/dist/orchestrator/PreviewFrameScheduler.js +18 -1
  71. package/dist/orchestrator/PreviewFrameScheduler.js.map +1 -1
  72. package/dist/orchestrator/types.d.ts +4 -0
  73. package/dist/orchestrator/types.d.ts.map +1 -1
  74. package/dist/stages/compose/OfflineAudioMixer.d.ts +7 -2
  75. package/dist/stages/compose/OfflineAudioMixer.d.ts.map +1 -1
  76. package/dist/stages/compose/OfflineAudioMixer.js +86 -70
  77. package/dist/stages/compose/OfflineAudioMixer.js.map +1 -1
  78. package/dist/stages/decode/preview-video-decoder.d.ts.map +1 -1
  79. package/dist/stages/decode/preview-video-decoder.js +12 -0
  80. package/dist/stages/decode/preview-video-decoder.js.map +1 -1
  81. package/dist/stages/load/ResourceLoader.d.ts +8 -0
  82. package/dist/stages/load/ResourceLoader.d.ts.map +1 -1
  83. package/dist/stages/load/ResourceLoader.js +117 -20
  84. package/dist/stages/load/ResourceLoader.js.map +1 -1
  85. package/dist/stages/load/TaskManager.d.ts +2 -2
  86. package/dist/stages/load/TaskManager.d.ts.map +1 -1
  87. package/dist/stages/load/TaskManager.js +11 -6
  88. package/dist/stages/load/TaskManager.js.map +1 -1
  89. package/dist/stages/load/types.d.ts +2 -0
  90. package/dist/stages/load/types.d.ts.map +1 -1
  91. package/dist/utils/playback-diagnostics.d.ts +4 -0
  92. package/dist/utils/playback-diagnostics.d.ts.map +1 -0
  93. package/dist/utils/playback-diagnostics.js +15 -0
  94. package/dist/utils/playback-diagnostics.js.map +1 -0
  95. package/package.json +1 -1
@@ -3,7 +3,20 @@ import { AudioMixBlockCache } from "../cache/AudioMixBlockCache.js";
3
3
  class AudioPreviewSession {
4
4
  constructor(deps) {
5
5
  this.deps = deps;
6
- this.mixer = new OfflineAudioMixer(deps.cacheManager, () => deps.preparer.getModel());
6
+ this.PREVIEW_BLOCK_DURATION_US = Math.min(
7
+ 5e6,
8
+ Math.floor(deps.cacheManager.audioMixMaxBytes / 8 - 1920) / 48e3 * 1e6
9
+ );
10
+ this.PREVIEW_BUFFER_GUARD_US = Math.min(25e5, this.PREVIEW_BLOCK_DURATION_US / 2);
11
+ this.mixer = new OfflineAudioMixer(
12
+ deps.cacheManager,
13
+ () => deps.preparer.getModel(),
14
+ deps.preparer
15
+ );
16
+ this.previewBlockCache = new AudioMixBlockCache(
17
+ this.PREVIEW_BLOCK_CACHE_SIZE,
18
+ deps.cacheManager.audioMixMaxBytes
19
+ );
7
20
  }
8
21
  mixer;
9
22
  audioContext = null;
@@ -11,18 +24,16 @@ class AudioPreviewSession {
11
24
  playbackRate = 1;
12
25
  isPlaying = false;
13
26
  // Preview strategy (unified):
14
- // - Schedule audio in medium mix blocks (10s). Block size balances main-thread
15
- // cost of one mix (~50ms for rate-shifted content at 10s, vs ~150ms at 30s)
16
- // against mix frequency (was 5s blocks historically -> jitter, see 2c4f4da).
27
+ // - Schedule audio in 5s mix blocks, shortened when the byte budget is smaller.
17
28
  // OfflineAudioMixer.mix() yields between clips; the video frame hoard absorbs
18
29
  // the remaining per-clip synchronous stretch/copy bursts.
19
- // - Startup/seek never waits for a whole block: a short startup segment (5s, xfade-tailed)
20
- // is mixed first and scheduled immediately; the containing block is mixed in the
21
- // background and picks up mid-block via previewFirstBlockOffsetUs.
30
+ // - A cold play schedules a short startup segment first. Explicit buffering
31
+ // waits for the required mixed block (and the next block near a boundary),
32
+ // so recovery satisfies the same readiness condition as the playback guard.
22
33
  // - Cache recently mixed AudioBuffer blocks (LRU) to accelerate seek & avoid re-mixing.
23
34
  // - Adjacent blocks are mixed with a small overlap and crossfaded (equal-power) to hide seams.
24
35
  // - Mix ahead (idle preheat + playback water-marks) so playback rarely waits on a block.
25
- PREVIEW_BLOCK_DURATION_US = 5 * 1e6;
36
+ PREVIEW_BLOCK_DURATION_US;
26
37
  // 5s light blocks: half the per-mix main-thread cost; the 20s video hoard absorbs the (small) periodic bursts
27
38
  PREVIEW_XFADE_SEC = 0.04;
28
39
  // equal-power crossfade between adjacent blocks
@@ -38,11 +49,10 @@ class AudioPreviewSession {
38
49
  // mix ahead up to this far during playback
39
50
  PREVIEW_COLD_MIX_MIN_SCHEDULE_MARGIN_SEC = 8;
40
51
  // skip eager next-block mix while margin is healthy
41
- PREVIEW_BUFFER_GUARD_US = 25e5;
42
- // 5s blocks mix fast; guard scales down
52
+ PREVIEW_BUFFER_GUARD_US;
43
53
  PREVIEW_STARTUP_SEC = 5;
44
- // startup/seek short-segment duration before the containing block takes over
45
- previewBlockCache = new AudioMixBlockCache(this.PREVIEW_BLOCK_CACHE_SIZE);
54
+ // short startup segment before block scheduling takes over
55
+ previewBlockCache;
46
56
  previewScheduleTask = null;
47
57
  previewScheduleToken = 0;
48
58
  previewMixToken = 0;
@@ -61,14 +71,44 @@ class AudioPreviewSession {
61
71
  previewPlaybackPreheatToken = 0;
62
72
  previewScheduledSources = /* @__PURE__ */ new Set();
63
73
  previewMixQueue = Promise.resolve();
74
+ getStats() {
75
+ const buffers = new Set(
76
+ [...this.previewScheduledSources].map((entry) => entry.source.buffer).filter((buffer) => buffer !== null)
77
+ );
78
+ let scheduledBytes = 0;
79
+ for (const buffer of buffers) scheduledBytes += buffer.length * buffer.numberOfChannels * 4;
80
+ return {
81
+ ...this.previewBlockCache.getStats(),
82
+ scheduledBytes,
83
+ scheduledSources: this.previewScheduledSources.size,
84
+ audioContextState: this.audioContext?.state ?? "none"
85
+ };
86
+ }
87
+ async drain() {
88
+ await this.previewMixQueue;
89
+ }
64
90
  invalidatePreviewMixCache() {
65
91
  this.previewBlockCache.clear();
66
- this.previewMixToken += 1;
67
- this.previewIdlePreheatToken += 1;
68
- this.previewPlaybackPreheatToken += 1;
92
+ this.cancelPendingMixes();
93
+ }
94
+ cancelPendingMixes() {
95
+ this.previewBlockCache.cancelPending();
96
+ this.previewMixToken++;
97
+ this.previewIdlePreheatToken++;
98
+ this.previewIdlePreheatTask = null;
99
+ this.previewPlaybackPreheatToken++;
100
+ this.previewPlaybackPreheatTask = null;
69
101
  }
70
102
  enqueuePreviewMix(work, token) {
71
- const run = () => work();
103
+ const run = async () => {
104
+ try {
105
+ const result = await work();
106
+ return this.previewMixToken === token ? result : null;
107
+ } catch (error) {
108
+ if (this.previewMixToken !== token) return null;
109
+ throw error;
110
+ }
111
+ };
72
112
  const next = this.previewMixQueue.then(
73
113
  () => {
74
114
  if (this.previewMixToken !== token) {
@@ -93,34 +133,30 @@ class AudioPreviewSession {
93
133
  if (this.deps.cacheManager.isExporting) return;
94
134
  const model = this.deps.preparer.getModel();
95
135
  if (!model) return;
136
+ const token = this.previewMixToken;
96
137
  const mode = options?.mode ?? "blocking";
97
138
  const blockIndex = Math.floor(Math.max(0, timeUs) / this.PREVIEW_BLOCK_DURATION_US);
98
139
  if (mode === "probe") {
99
- void this.getOrCreateMixedBlock(blockIndex);
100
- const blockEndUs2 = (blockIndex + 1) * this.PREVIEW_BLOCK_DURATION_US;
101
- const remainingToBoundaryUs2 = blockEndUs2 - Math.max(0, timeUs);
140
+ void this.preheatBlock(blockIndex);
141
+ const blockEndUs = (blockIndex + 1) * this.PREVIEW_BLOCK_DURATION_US;
142
+ const remainingToBoundaryUs = blockEndUs - Math.max(0, timeUs);
102
143
  const lookaheadUs = Math.floor(this.PREVIEW_SCHEDULE_AHEAD_SEC * 1e6);
103
- if (remainingToBoundaryUs2 > 0 && remainingToBoundaryUs2 <= lookaheadUs) {
104
- void this.getOrCreateMixedBlock(blockIndex + 1);
144
+ if (remainingToBoundaryUs > 0 && remainingToBoundaryUs <= lookaheadUs) {
145
+ void this.preheatBlock(blockIndex + 1);
105
146
  }
106
147
  this.startIdlePreviewPreheat(timeUs);
107
148
  return;
108
149
  }
109
- const clampedUs = Math.max(0, timeUs);
110
- const xfadeUs = Math.floor(this.PREVIEW_XFADE_SEC * 1e6);
111
- const segmentEndUs = Math.min(
112
- clampedUs + this.PREVIEW_STARTUP_SEC * 1e6 + xfadeUs,
113
- model.durationUs
114
- );
115
- await this.deps.preparer.ensureAudioForTimeRange(clampedUs, segmentEndUs, {
116
- mode: "blocking",
117
- loadResource: true
118
- });
119
- void this.getOrCreateMixedBlock(blockIndex);
120
- const blockEndUs = (blockIndex + 1) * this.PREVIEW_BLOCK_DURATION_US;
121
- const remainingToBoundaryUs = blockEndUs - clampedUs;
122
- if (remainingToBoundaryUs > 0 && remainingToBoundaryUs <= this.PREVIEW_BUFFER_GUARD_US) {
123
- void this.getOrCreateMixedBlock(blockIndex + 1);
150
+ const requiredIndex = blockIndex + (options?.upcoming ? 1 : 0);
151
+ if (requiredIndex * this.PREVIEW_BLOCK_DURATION_US >= model.durationUs) return;
152
+ const mixed = await this.getOrCreateMixedBlock(requiredIndex);
153
+ if (token !== this.previewMixToken) return;
154
+ if (!mixed) throw new Error(`Preview audio block ${requiredIndex} unavailable after mixing`);
155
+ const nextStartUs = (blockIndex + 1) * this.PREVIEW_BLOCK_DURATION_US;
156
+ if (!options?.upcoming && nextStartUs < model.durationUs && nextStartUs - Math.max(0, timeUs) <= this.PREVIEW_BUFFER_GUARD_US) {
157
+ const next = await this.getOrCreateMixedBlock(blockIndex + 1);
158
+ if (token === this.previewMixToken && !next)
159
+ throw new Error(`Preview audio block ${blockIndex + 1} unavailable after mixing`);
124
160
  }
125
161
  }
126
162
  isPreviewMixBlockCached(timeUs) {
@@ -136,64 +172,68 @@ class AudioPreviewSession {
136
172
  if (nextBlockStartUs >= model.durationUs) return false;
137
173
  const remainingToBoundaryUs = nextBlockStartUs - clampedUs;
138
174
  if (remainingToBoundaryUs > this.PREVIEW_BUFFER_GUARD_US) return false;
175
+ const requiredEndUs = Math.min(
176
+ nextBlockStartUs + this.PREVIEW_BUFFER_GUARD_US,
177
+ model.durationUs
178
+ );
179
+ let coveredEndUs = clampedUs;
180
+ for (const entry of this.previewScheduledSources) {
181
+ if (entry.startUs > coveredEndUs + 1e6 / 48e3) break;
182
+ coveredEndUs = Math.max(coveredEndUs, entry.endUs);
183
+ if (coveredEndUs >= requiredEndUs) return false;
184
+ }
139
185
  return !this.isPreviewMixBlockCached(nextBlockStartUs);
140
186
  }
141
187
  async startPlayback(timeUs, audioContext) {
142
188
  this.audioContext = audioContext;
143
189
  this.isPlaying = true;
144
- this.previewIdlePreheatToken += 1;
145
- this.previewMixToken += 1;
190
+ this.previewIdlePreheatToken++;
191
+ this.previewIdlePreheatTask = null;
192
+ const mixToken = this.previewMixToken;
193
+ const current = () => this.isPlaying && mixToken === this.previewMixToken;
146
194
  if (audioContext.state === "suspended") {
147
195
  await audioContext.resume();
148
196
  }
149
197
  const model = this.deps.preparer.getModel();
150
- if (!model || !this.isPlaying) return;
198
+ if (!model || !current()) return;
151
199
  const startUs = Math.max(0, timeUs);
152
200
  const hotBlockIndex = Math.floor(startUs / this.PREVIEW_BLOCK_DURATION_US);
153
201
  const hotBlock = this.previewBlockCache.get(hotBlockIndex);
154
202
  if (hotBlock && this.isPlaying) {
155
203
  this.startPreviewBlockScheduling(startUs, audioContext);
156
204
  await this.scheduleNextPreviewBlock(audioContext, this.previewScheduleToken);
157
- if (!this.isPlaying) return;
205
+ if (!current()) return;
158
206
  void this.scheduleAudio(timeUs, audioContext);
159
207
  return;
160
208
  }
161
209
  const xfadeUs = Math.floor(this.PREVIEW_XFADE_SEC * 1e6);
162
210
  const startupBodyEndUs = Math.min(
163
- startUs + this.PREVIEW_STARTUP_SEC * 1e6,
211
+ startUs + Math.min(this.PREVIEW_STARTUP_SEC * 1e6, this.PREVIEW_BLOCK_DURATION_US),
164
212
  model.durationUs
165
213
  );
166
214
  const startupMixEndUs = Math.min(startupBodyEndUs + xfadeUs, model.durationUs);
167
- await this.deps.preparer.ensureAudioForTimeRange(startUs, startupMixEndUs, {
168
- mode: "blocking",
169
- loadResource: true
170
- });
171
- if (!this.isPlaying) return;
172
- const mixToken = this.previewMixToken;
173
215
  const startupBuffer = await this.enqueuePreviewMix(
174
- () => this.mixer.mix(startUs, startupMixEndUs),
216
+ () => this.mixer.mix(startUs, startupMixEndUs, { isCurrent: current }),
175
217
  mixToken
176
218
  );
177
- if (!this.isPlaying) return;
219
+ if (!current()) return;
178
220
  if (!startupBuffer) {
179
221
  await this.getOrCreateMixedBlock(Math.floor(startUs / this.PREVIEW_BLOCK_DURATION_US));
180
- if (!this.isPlaying) return;
222
+ if (!current()) return;
181
223
  this.startPreviewBlockScheduling(startUs, audioContext);
182
224
  await this.scheduleNextPreviewBlock(audioContext, this.previewScheduleToken);
183
- if (!this.isPlaying) return;
225
+ if (!current()) return;
184
226
  void this.scheduleAudio(timeUs, audioContext);
185
227
  return;
186
228
  }
187
229
  this.scheduleStartupSegment(startupBuffer, startUs, startupBodyEndUs, audioContext);
188
- void this.getOrCreateMixedBlock(Math.floor(startUs / this.PREVIEW_BLOCK_DURATION_US));
189
230
  void this.scheduleAudio(timeUs, audioContext);
190
231
  }
191
232
  stopPlayback() {
192
233
  this.isPlaying = false;
193
234
  this.stopAllPreviewSources();
194
235
  this.cancelPreviewBlockScheduling();
195
- this.previewMixToken += 1;
196
- this.previewPlaybackPreheatToken += 1;
236
+ this.cancelPendingMixes();
197
237
  }
198
238
  /**
199
239
  * Schedule audio chunks ahead of playback cursor.
@@ -209,13 +249,11 @@ class AudioPreviewSession {
209
249
  this.startPreviewBlockScheduling(currentTimelineUs, audioContext);
210
250
  }
211
251
  const token = this.previewScheduleToken;
212
- this.previewScheduleTask = this.runPreviewBlockSchedulingLoop(audioContext, token).finally(
213
- () => {
214
- if (this.previewScheduleToken === token) {
215
- this.previewScheduleTask = null;
216
- }
252
+ this.previewScheduleTask = this.runPreviewBlockSchedulingLoop(audioContext, token).catch((error) => console.error("[AudioPreviewSession] scheduling failed", error)).finally(() => {
253
+ if (this.previewScheduleToken === token) {
254
+ this.previewScheduleTask = null;
217
255
  }
218
- );
256
+ });
219
257
  }
220
258
  /**
221
259
  * Reset playback states (called on seek)
@@ -223,7 +261,7 @@ class AudioPreviewSession {
223
261
  resetPlaybackStates() {
224
262
  this.stopAllPreviewSources();
225
263
  this.cancelPreviewBlockScheduling();
226
- this.previewMixToken += 1;
264
+ this.cancelPendingMixes();
227
265
  }
228
266
  reset() {
229
267
  this.stopPlayback();
@@ -293,8 +331,11 @@ class AudioPreviewSession {
293
331
  if (!model) return;
294
332
  const token = ++this.previewIdlePreheatToken;
295
333
  const startBlockIndex = Math.floor(Math.max(0, startTimeUs) / this.PREVIEW_BLOCK_DURATION_US);
296
- const blockCount = Math.ceil(
297
- this.PREVIEW_IDLE_PREHEAT_AHEAD_SEC * 1e6 / this.PREVIEW_BLOCK_DURATION_US
334
+ const blockBytes = (this.PREVIEW_BLOCK_DURATION_US / 1e6 + this.PREVIEW_XFADE_SEC) * 48e3 * 8;
335
+ const blockCount = Math.min(
336
+ this.PREVIEW_BLOCK_CACHE_SIZE,
337
+ Math.max(1, Math.floor(this.deps.cacheManager.audioMixMaxBytes / blockBytes)),
338
+ Math.ceil(this.PREVIEW_IDLE_PREHEAT_AHEAD_SEC * 1e6 / this.PREVIEW_BLOCK_DURATION_US)
298
339
  );
299
340
  this.previewIdlePreheatTask = (async () => {
300
341
  for (let i = 0; i < blockCount; i++) {
@@ -307,7 +348,7 @@ class AudioPreviewSession {
307
348
  }
308
349
  await new Promise((resolve) => setTimeout(resolve, 0));
309
350
  }
310
- })().finally(() => {
351
+ })().catch((error) => console.error("[AudioPreviewSession] idle preheat failed", error)).finally(() => {
311
352
  if (this.previewIdlePreheatToken === token) {
312
353
  this.previewIdlePreheatTask = null;
313
354
  }
@@ -330,9 +371,23 @@ class AudioPreviewSession {
330
371
  await new Promise((resolve) => setTimeout(resolve, 500));
331
372
  continue;
332
373
  }
333
- const startBlockIndex = Math.floor(latestTimelineUs / this.PREVIEW_BLOCK_DURATION_US);
334
- const targetBlockIndex = Math.floor(
335
- (latestTimelineUs + this.PREVIEW_PLAYING_MIX_HIGH_WATER_SEC * 1e6) / this.PREVIEW_BLOCK_DURATION_US
374
+ const startBlockIndex = Math.max(
375
+ this.previewNextBlockIndex,
376
+ Math.floor(latestTimelineUs / this.PREVIEW_BLOCK_DURATION_US)
377
+ );
378
+ const blockBytes = (this.PREVIEW_BLOCK_DURATION_US / 1e6 + this.PREVIEW_XFADE_SEC) * 48e3 * 8;
379
+ const residentBlocks = Math.max(
380
+ 1,
381
+ Math.min(
382
+ this.PREVIEW_BLOCK_CACHE_SIZE,
383
+ Math.floor(this.deps.cacheManager.audioMixMaxBytes / blockBytes)
384
+ )
385
+ );
386
+ const targetBlockIndex = Math.min(
387
+ startBlockIndex + residentBlocks - 1,
388
+ Math.floor(
389
+ (latestTimelineUs + this.PREVIEW_PLAYING_MIX_HIGH_WATER_SEC * 1e6) / this.PREVIEW_BLOCK_DURATION_US
390
+ )
336
391
  );
337
392
  for (let blockIndex = startBlockIndex; blockIndex <= targetBlockIndex; blockIndex++) {
338
393
  if (!this.isPlaying || this.previewPlaybackPreheatToken !== token) return;
@@ -345,7 +400,7 @@ class AudioPreviewSession {
345
400
  }
346
401
  await new Promise((resolve) => setTimeout(resolve, 250));
347
402
  }
348
- })().finally(() => {
403
+ })().catch((error) => console.error("[AudioPreviewSession] playback preheat failed", error)).finally(() => {
349
404
  if (this.previewPlaybackPreheatToken === token) {
350
405
  this.previewPlaybackPreheatTask = null;
351
406
  }
@@ -360,7 +415,11 @@ class AudioPreviewSession {
360
415
  this.previewNextScheduleTime = audioContext.currentTime + this.PREVIEW_SCHEDULE_AHEAD_SEC;
361
416
  return;
362
417
  }
363
- const scheduleAheadTime = audioContext.currentTime + this.PREVIEW_SCHEDULE_AHEAD_SEC;
418
+ const scheduleAheadSec = Math.min(
419
+ this.PREVIEW_SCHEDULE_AHEAD_SEC,
420
+ this.deps.cacheManager.audioMixMaxBytes / (48e3 * 8 * this.playbackRate)
421
+ );
422
+ const scheduleAheadTime = audioContext.currentTime + scheduleAheadSec;
364
423
  if (this.previewNextScheduleTime >= scheduleAheadTime) return;
365
424
  const prevBlockIndex = this.previewNextBlockIndex;
366
425
  const prevScheduleTime = this.previewNextScheduleTime;
@@ -385,6 +444,11 @@ class AudioPreviewSession {
385
444
  }
386
445
  }
387
446
  }
447
+ async preheatBlock(index) {
448
+ await this.getOrCreateMixedBlock(index).catch(
449
+ (error) => console.error("[AudioPreviewSession] preheat failed", error)
450
+ );
451
+ }
388
452
  async getOrCreateMixedBlock(blockIndex) {
389
453
  const model = this.deps.preparer.getModel();
390
454
  if (!model) return null;
@@ -398,13 +462,15 @@ class AudioPreviewSession {
398
462
  startUs + this.PREVIEW_BLOCK_DURATION_US + overlapUs,
399
463
  model.durationUs
400
464
  );
401
- await this.deps.preparer.ensureAudioForTimeRange(startUs, endUs, {
402
- mode: "blocking",
403
- loadResource: true
465
+ const mixed = await this.mixer.mix(startUs, endUs, {
466
+ isCurrent: () => token === this.previewMixToken && !this.deps.cacheManager.isExporting
404
467
  });
405
- const mixed = await this.mixer.mix(startUs, endUs);
468
+ if (token !== this.previewMixToken) return null;
406
469
  return mixed;
407
470
  }, token);
471
+ }).catch((error) => {
472
+ if (error instanceof DOMException && error.name === "AbortError") return null;
473
+ throw error;
408
474
  });
409
475
  }
410
476
  /**
@@ -438,7 +504,7 @@ class AudioPreviewSession {
438
504
  source.connect(gainNode);
439
505
  gainNode.connect(audioContext.destination);
440
506
  source.start(startTime, 0);
441
- const entry = { source, gain: gainNode };
507
+ const entry = { source, gain: gainNode, startUs, endUs: bodyEndUs };
442
508
  this.previewScheduledSources.add(entry);
443
509
  source.onended = () => {
444
510
  try {
@@ -446,6 +512,7 @@ class AudioPreviewSession {
446
512
  gainNode.disconnect();
447
513
  } catch {
448
514
  }
515
+ source.buffer = null;
449
516
  this.previewScheduledSources.delete(entry);
450
517
  };
451
518
  const blockIndex = Math.floor(bodyEndUs / this.PREVIEW_BLOCK_DURATION_US);
@@ -471,6 +538,7 @@ class AudioPreviewSession {
471
538
  return;
472
539
  }
473
540
  const buffer = await this.getOrCreateMixedBlock(blockIndex);
541
+ if (this.previewScheduleToken !== token || !this.isPlaying) return;
474
542
  if (!buffer) {
475
543
  this.previewFirstBlockOffsetUs = 0;
476
544
  this.previewNextBlockIndex = blockIndex + 1;
@@ -525,7 +593,12 @@ class AudioPreviewSession {
525
593
  source.connect(gainNode);
526
594
  gainNode.connect(audioContext.destination);
527
595
  source.start(startTime, offsetSec);
528
- const entry = { source, gain: gainNode };
596
+ const entry = {
597
+ source,
598
+ gain: gainNode,
599
+ startUs: blockStartUs + offsetSec * 1e6,
600
+ endUs: blockStartUs + Math.max(0, buffer.duration - xfadeSec) * 1e6
601
+ };
529
602
  this.previewScheduledSources.add(entry);
530
603
  source.onended = () => {
531
604
  try {
@@ -533,6 +606,7 @@ class AudioPreviewSession {
533
606
  gainNode.disconnect();
534
607
  } catch {
535
608
  }
609
+ source.buffer = null;
536
610
  this.previewScheduledSources.delete(entry);
537
611
  };
538
612
  this.previewFirstBlockOffsetUs = 0;
@@ -541,6 +615,8 @@ class AudioPreviewSession {
541
615
  }
542
616
  stopAllPreviewSources() {
543
617
  for (const { source, gain } of this.previewScheduledSources) {
618
+ source.onended = null;
619
+ source.buffer = null;
544
620
  try {
545
621
  source.disconnect();
546
622
  } catch {