@dawcore/spectrogram 0.0.3 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -36,6 +36,12 @@ interface SpectrogramWorkerApi {
36
36
  cacheKey: string;
37
37
  }>;
38
38
  renderChunks(params: SpectrogramWorkerRenderChunksParams, generation?: number): Promise<void>;
39
+ /**
40
+ * Cancel in-flight work from generations OLDER than `generation`.
41
+ * Pass the NEW (current) generation after bumping — the worker treats work
42
+ * as stale iff `workGeneration < latestAbortedGeneration`, so passing the
43
+ * previous generation cancels nothing (#555).
44
+ */
39
45
  abortGeneration(generation: number): void;
40
46
  registerCanvas(canvasId: string, canvas: OffscreenCanvas): void;
41
47
  unregisterCanvas(canvasId: string): void;
@@ -100,6 +106,13 @@ interface CanvasRegistration {
100
106
  readonly trackId: string;
101
107
  readonly channelIndex: number;
102
108
  readonly chunkIndex: number;
109
+ /**
110
+ * TIMELINE-absolute pixel where this chunk starts. Layout contract: every
111
+ * canvas of a clip must satisfy
112
+ * `globalPixelOffset === clipOriginPx + chunkIndex * MAX_CANVAS_WIDTH` —
113
+ * renderGroup's clip-relative sample math depends on it (#554), and
114
+ * registerCanvas warns when a registration violates it.
115
+ */
103
116
  readonly globalPixelOffset: number;
104
117
  readonly widthPx: number;
105
118
  readonly heightPx: number;
@@ -133,6 +146,11 @@ declare class SpectrogramOrchestrator extends EventTarget {
133
146
  protected colorLUT: ColorLUTCache;
134
147
  protected disposed: boolean;
135
148
  protected renderInFlight: boolean;
149
+ protected renderQueued: boolean;
150
+ protected clipOrigins: Map<string, {
151
+ originPx: number;
152
+ canvasCount: number;
153
+ }>;
136
154
  protected readyDispatched: Set<string>;
137
155
  constructor(opts: SpectrogramOrchestratorOptions);
138
156
  registerClip(reg: ClipRegistration): void;
@@ -143,11 +161,27 @@ declare class SpectrogramOrchestrator extends EventTarget {
143
161
  setConfig(config: SpectrogramConfig): void;
144
162
  setColorMap(colorMap: ColorMapValue): void;
145
163
  setDevicePixelRatio(dpr: number): void;
164
+ /**
165
+ * Start a new render generation and cancel in-flight work from older ones.
166
+ *
167
+ * The worker treats work as stale iff `generation < latestGeneration`, so
168
+ * the abort message must carry the NEW generation — passing the previous
169
+ * one leaves its in-flight FFTs running to completion (#555).
170
+ */
171
+ protected bumpGenerationAndAbortStale(): void;
146
172
  dispose(): void;
173
+ /**
174
+ * Coalesce render requests: `renderInFlight` is held for the WHOLE async
175
+ * render, not just until the microtask fires — a request arriving
176
+ * mid-render (e.g. a late registerCanvas) queues one follow-up run instead
177
+ * of starting a concurrent runRender for the same generation (#558).
178
+ */
147
179
  protected scheduleRender(): void;
180
+ protected runRenderLoop(): Promise<void>;
148
181
  protected runRender(generation: number): Promise<void>;
149
182
  protected renderTier(canvases: CanvasEntry[], generation: number, viewport: ViewportState): Promise<void>;
150
183
  protected renderGroup(group: CanvasEntry[], generation: number, viewport: ViewportState): Promise<void>;
184
+ protected renderGroupOnce(group: CanvasEntry[], generation: number, viewport: ViewportState, clip: ClipEntry): Promise<void>;
151
185
  protected renderRemainingViaIdle(canvases: CanvasEntry[], generation: number, viewport: ViewportState): Promise<void>;
152
186
  protected yieldUntilIdle(): Promise<void>;
153
187
  }
@@ -167,6 +201,10 @@ interface ViewportReadyDetail {
167
201
  interface ChunkLike {
168
202
  chunkIndex: number;
169
203
  }
204
+ interface RenderableChunkLike extends ChunkLike {
205
+ clipId: string;
206
+ channelIndex: number;
207
+ }
170
208
  /**
171
209
  * Group a list of chunks into runs of contiguous chunk indices.
172
210
  *
@@ -178,5 +216,17 @@ interface ChunkLike {
178
216
  * two smaller FFTs (10–11, 14–15) totaling ~32K frames.
179
217
  */
180
218
  declare function groupContiguousChunks<T extends ChunkLike>(chunks: T[]): T[][];
219
+ /**
220
+ * Group render canvases into runs of contiguous chunk indices, partitioned by
221
+ * `(clipId, channelIndex)` first.
222
+ *
223
+ * A track's canvases span multiple channels (one <daw-spectrogram> per channel,
224
+ * chunk indices shared) and multiple clips (chunk indices restart at 0 per
225
+ * clip). Grouping by chunk index alone interleaves them — e.g. stereo
226
+ * [ch0k0, ch1k0, ch0k1, ch1k1] yields the mixed group [ch1k0, ch0k1], which
227
+ * renderGroup then routes to a single channel's worker with a single clip's
228
+ * FFT data (issue #553).
229
+ */
230
+ declare function groupRenderableChunks<T extends RenderableChunkLike>(chunks: T[]): T[][];
181
231
 
182
- export { type CanvasMeta, type CanvasRegistration, type ChunkLike, type ClassifiedTiers, type ClipRegistration, ColorLUTCache, SpectrogramOrchestrator, type SpectrogramOrchestratorOptions, type ViewportBounds, type ViewportReadyDetail, type ViewportState, classifyViewport, groupContiguousChunks };
232
+ export { type CanvasMeta, type CanvasRegistration, type ChunkLike, type ClassifiedTiers, type ClipRegistration, ColorLUTCache, type RenderableChunkLike, SpectrogramOrchestrator, type SpectrogramOrchestratorOptions, type ViewportBounds, type ViewportReadyDetail, type ViewportState, classifyViewport, groupContiguousChunks, groupRenderableChunks };
@@ -1,5 +1,9 @@
1
1
  // src/orchestrator/SpectrogramOrchestrator.ts
2
- import { SPECTROGRAM_DEFAULTS, DEFAULT_SPECTROGRAM_COLOR_MAP } from "@waveform-playlist/core";
2
+ import {
3
+ SPECTROGRAM_DEFAULTS,
4
+ DEFAULT_SPECTROGRAM_COLOR_MAP,
5
+ MAX_CANVAS_WIDTH as MAX_CANVAS_WIDTH2
6
+ } from "@waveform-playlist/core";
3
7
 
4
8
  // src/worker/createSpectrogramWorker.ts
5
9
  var SpectrogramAbortError = class extends Error {
@@ -40,7 +44,6 @@ function createSpectrogramWorker(worker) {
40
44
  }
41
45
  };
42
46
  worker.onerror = (e) => {
43
- terminated = true;
44
47
  console.error(
45
48
  "[dawcore-spectrogram] worker crashed with " + pending.size + " pending operations: " + (e.message || "unknown error")
46
49
  );
@@ -143,21 +146,31 @@ function createSpectrogramWorker(worker) {
143
146
  }
144
147
 
145
148
  // src/worker/createSpectrogramWorkerPool.ts
149
+ import { parseSpectrogramCanvasId } from "@waveform-playlist/core";
146
150
  function parseChannelFromCanvasId(canvasId) {
147
- const match = canvasId.match(/-ch(\d+)-/);
148
- if (!match) {
151
+ const parsed = parseSpectrogramCanvasId(canvasId);
152
+ if (!parsed) {
149
153
  console.warn(
150
- "[dawcore-spectrogram] canvas ID missing -ch{N}- segment, routing to worker 0: " + canvasId
154
+ "[dawcore-spectrogram] canvas ID missing -ch{N}-chunk{M} suffix, routing to worker 0: " + canvasId
151
155
  );
152
156
  return 0;
153
157
  }
154
- return parseInt(match[1], 10);
158
+ return parsed.channelIndex;
155
159
  }
156
160
  function defaultPoolSize() {
157
161
  return 2;
158
162
  }
163
+ var MAX_POOL_CHANNELS = 32;
159
164
  function createSpectrogramWorkerPool(createWorker, poolSize = defaultPoolSize()) {
165
+ if (poolSize > MAX_POOL_CHANNELS) {
166
+ console.warn(
167
+ "[dawcore-spectrogram] workerPoolSize " + poolSize + " exceeds the channel cap (" + MAX_POOL_CHANNELS + ") \u2014 clamping; channels beyond the cap are not servable"
168
+ );
169
+ poolSize = MAX_POOL_CHANNELS;
170
+ }
160
171
  const workers = [];
172
+ let terminated = false;
173
+ const registeredAudio = /* @__PURE__ */ new Map();
161
174
  let failedAt = -1;
162
175
  try {
163
176
  for (let i = 0; i < poolSize; i++) {
@@ -179,59 +192,111 @@ function createSpectrogramWorkerPool(createWorker, poolSize = defaultPoolSize())
179
192
  "Failed to create spectrogram worker pool (size=" + poolSize + ") at worker " + failedAt + ": " + (err instanceof Error ? err.message : String(err))
180
193
  );
181
194
  }
182
- function getWorkerForChannel(channelIndex) {
183
- return workers[channelIndex % workers.length];
195
+ function assertValidChannelIndex(channelIndex) {
196
+ if (!Number.isInteger(channelIndex) || channelIndex < 0 || channelIndex >= MAX_POOL_CHANNELS) {
197
+ throw new Error(
198
+ "[dawcore-spectrogram] invalid channel index " + channelIndex + " (expected an integer in 0.." + (MAX_POOL_CHANNELS - 1) + ")"
199
+ );
200
+ }
201
+ }
202
+ function ensureWorkerForChannel(channelIndex) {
203
+ assertValidChannelIndex(channelIndex);
204
+ if (terminated) {
205
+ throw new Error("[dawcore-spectrogram] worker pool is terminated");
206
+ }
207
+ while (workers.length <= channelIndex) {
208
+ const w = createSpectrogramWorker(createWorker());
209
+ const workerIndex = workers.length;
210
+ for (const [clipId, entry] of registeredAudio) {
211
+ if (entry.channelDataArrays.length > workerIndex) {
212
+ w.registerAudioData(clipId, entry.channelDataArrays, entry.sampleRate);
213
+ }
214
+ }
215
+ workers.push(w);
216
+ }
217
+ return workers[channelIndex];
184
218
  }
185
219
  return {
186
220
  async computeFFT(params, generation = 0) {
221
+ if (terminated) {
222
+ throw new Error("[dawcore-spectrogram] worker pool is terminated");
223
+ }
224
+ const channelCount = params.channelDataArrays.length || registeredAudio.get(params.clipId)?.channelDataArrays.length || 0;
225
+ if (channelCount === 0) {
226
+ throw new Error(
227
+ "[dawcore-spectrogram] computeFFT called with no channel data \u2014 pass channelDataArrays or registerAudioData the clip first"
228
+ );
229
+ }
187
230
  if (params.mono) {
188
231
  return workers[0].computeFFT(params, generation);
189
232
  }
190
- const channelCount = params.channelDataArrays.length;
191
- const activeWorkers = workers.slice(0, channelCount);
192
- const promises = activeWorkers.map(
193
- (w, i) => w.computeFFT({ ...params, channelFilter: i }, generation)
233
+ if (channelCount > MAX_POOL_CHANNELS) {
234
+ throw new Error(
235
+ "[dawcore-spectrogram] computeFFT: " + channelCount + " channels exceeds the pool channel cap (" + MAX_POOL_CHANNELS + ")"
236
+ );
237
+ }
238
+ const promises = Array.from(
239
+ { length: channelCount },
240
+ (_, i) => ensureWorkerForChannel(i).computeFFT({ ...params, channelFilter: i }, generation)
194
241
  );
195
242
  const settled = await Promise.allSettled(promises);
196
243
  const failures = settled.filter((s) => s.status === "rejected");
197
244
  if (failures.length > 0) {
198
- for (let i = 1; i < failures.length; i++) {
245
+ const realErrors = failures.filter((f) => !(f.reason instanceof SpectrogramAbortError));
246
+ for (let i = 1; i < realErrors.length; i++) {
199
247
  console.warn(
200
- "[dawcore-spectrogram] additional channel FFT failure (" + i + "): " + (failures[i].reason instanceof Error ? failures[i].reason.message : String(failures[i].reason))
248
+ "[dawcore-spectrogram] additional channel FFT failure (" + i + "): " + (realErrors[i].reason instanceof Error ? realErrors[i].reason.message : String(realErrors[i].reason))
201
249
  );
202
250
  }
203
- throw failures[0].reason;
251
+ throw (realErrors[0] ?? failures[0]).reason;
204
252
  }
205
253
  return settled[0].value;
206
254
  },
207
- renderChunks(params, generation = 0) {
208
- const worker = getWorkerForChannel(params.channelIndex);
255
+ // async so ensureWorkerForChannel's policy throws surface as rejections,
256
+ // matching computeFFT, instead of escaping synchronously.
257
+ async renderChunks(params, generation = 0) {
258
+ const worker = ensureWorkerForChannel(params.channelIndex);
209
259
  return worker.renderChunks({ ...params, channelIndex: 0 }, generation);
210
260
  },
211
261
  abortGeneration(generation) {
262
+ if (terminated) return;
212
263
  for (const w of workers) {
213
264
  w.abortGeneration(generation);
214
265
  }
215
266
  },
216
267
  registerCanvas(canvasId, canvas) {
217
- const ch = parseChannelFromCanvasId(canvasId);
218
- getWorkerForChannel(ch).registerCanvas(canvasId, canvas);
268
+ try {
269
+ ensureWorkerForChannel(parseChannelFromCanvasId(canvasId)).registerCanvas(canvasId, canvas);
270
+ } catch (err) {
271
+ console.warn(
272
+ '[dawcore-spectrogram] registerCanvas("' + canvasId + '") rejected \u2014 canvas not registered: ' + (err instanceof Error ? err.message : String(err))
273
+ );
274
+ }
219
275
  },
220
276
  unregisterCanvas(canvasId) {
221
- const ch = parseChannelFromCanvasId(canvasId);
222
- getWorkerForChannel(ch).unregisterCanvas(canvasId);
277
+ if (terminated) return;
278
+ const worker = workers[parseChannelFromCanvasId(canvasId)];
279
+ if (!worker) return;
280
+ worker.unregisterCanvas(canvasId);
223
281
  },
224
282
  registerAudioData(clipId, channelDataArrays, sampleRate) {
225
- for (const w of workers) {
226
- w.registerAudioData(clipId, channelDataArrays, sampleRate);
283
+ if (terminated) return;
284
+ registeredAudio.set(clipId, { channelDataArrays, sampleRate });
285
+ const relevantWorkers = Math.min(channelDataArrays.length, workers.length);
286
+ for (let i = 0; i < relevantWorkers; i++) {
287
+ workers[i].registerAudioData(clipId, channelDataArrays, sampleRate);
227
288
  }
228
289
  },
229
290
  unregisterAudioData(clipId) {
291
+ if (terminated) return;
292
+ registeredAudio.delete(clipId);
230
293
  for (const w of workers) {
231
294
  w.unregisterAudioData(clipId);
232
295
  }
233
296
  },
234
297
  terminate() {
298
+ terminated = true;
299
+ registeredAudio.clear();
235
300
  for (const w of workers) {
236
301
  w.terminate();
237
302
  }
@@ -239,8 +304,32 @@ function createSpectrogramWorkerPool(createWorker, poolSize = defaultPoolSize())
239
304
  };
240
305
  }
241
306
 
307
+ // src/computation/fftSampleRange.ts
308
+ import { MAX_CANVAS_WIDTH } from "@waveform-playlist/core";
309
+ function computePaddedFftRange({
310
+ chunks,
311
+ fftSize,
312
+ offsetSamples,
313
+ durationSamples,
314
+ samplesPerPixel
315
+ }) {
316
+ const startPx = Math.min(...chunks.map((c) => c.chunkIndex * MAX_CANVAS_WIDTH));
317
+ const endPx = Math.max(...chunks.map((c) => c.chunkIndex * MAX_CANVAS_WIDTH + c.widthPx));
318
+ const startSample = offsetSamples + Math.floor(startPx * samplesPerPixel);
319
+ const endSample = Math.min(
320
+ offsetSamples + durationSamples,
321
+ offsetSamples + Math.ceil(endPx * samplesPerPixel)
322
+ );
323
+ const paddedStart = Math.max(offsetSamples, startSample - fftSize);
324
+ const paddedEnd = Math.min(offsetSamples + durationSamples, endSample + fftSize);
325
+ return { paddedStart, paddedEnd };
326
+ }
327
+
242
328
  // src/computation/colorMaps.ts
243
329
  function interpolateLUT(stops) {
330
+ if (stops.length === 0) {
331
+ throw new Error("[spectrogram] custom color map requires at least one color stop");
332
+ }
244
333
  const lut = new Uint8Array(256 * 3);
245
334
  const n = stops.length;
246
335
  for (let i = 0; i < 256; i++) {
@@ -3444,6 +3533,20 @@ function groupContiguousChunks(chunks) {
3444
3533
  groups.push(current);
3445
3534
  return groups;
3446
3535
  }
3536
+ function groupRenderableChunks(chunks) {
3537
+ const partitions = /* @__PURE__ */ new Map();
3538
+ for (const chunk of chunks) {
3539
+ const key = chunk.clipId + " " + chunk.channelIndex;
3540
+ const list = partitions.get(key) ?? [];
3541
+ list.push(chunk);
3542
+ partitions.set(key, list);
3543
+ }
3544
+ const groups = [];
3545
+ for (const partition of partitions.values()) {
3546
+ groups.push(...groupContiguousChunks(partition));
3547
+ }
3548
+ return groups;
3549
+ }
3447
3550
 
3448
3551
  // src/orchestrator/SpectrogramOrchestrator.ts
3449
3552
  var SpectrogramOrchestrator = class extends EventTarget {
@@ -3456,6 +3559,12 @@ var SpectrogramOrchestrator = class extends EventTarget {
3456
3559
  this.colorLUT = new ColorLUTCache();
3457
3560
  this.disposed = false;
3458
3561
  this.renderInFlight = false;
3562
+ this.renderQueued = false;
3563
+ // Per-clip timeline origin (globalPixelOffset - chunkIndex * MAX_CANVAS_WIDTH)
3564
+ // with a live canvas count — used to detect layout-contract violations.
3565
+ // The origin resets once all of a clip's canvases unregister, so a moved
3566
+ // clip re-registering at a new position doesn't false-positive.
3567
+ this.clipOrigins = /* @__PURE__ */ new Map();
3459
3568
  // Tracks which trackIds have already emitted `viewport-ready` for the
3460
3569
  // current generation. Cleared on every generation bump (setViewport with a
3461
3570
  // real change, setConfig, setColorMap, setDevicePixelRatio) AND in dispose().
@@ -3516,16 +3625,34 @@ var SpectrogramOrchestrator = class extends EventTarget {
3516
3625
  channelIndex: reg.channelIndex,
3517
3626
  chunkIndex: reg.chunkIndex
3518
3627
  });
3628
+ const originPx = reg.globalPixelOffset - reg.chunkIndex * MAX_CANVAS_WIDTH2;
3629
+ const origin = this.clipOrigins.get(reg.clipId);
3630
+ if (!origin) {
3631
+ this.clipOrigins.set(reg.clipId, { originPx, canvasCount: 1 });
3632
+ } else {
3633
+ origin.canvasCount += 1;
3634
+ if (origin.originPx !== originPx) {
3635
+ console.warn(
3636
+ "[dawcore-spectrogram] registerCanvas: " + reg.canvasId + " violates the chunk layout contract (chunk " + reg.chunkIndex + " at " + reg.globalPixelOffset + "px implies clip origin " + originPx + "px, but other canvases imply " + origin.originPx + "px) \u2014 sample math assumes chunkIndex * " + MAX_CANVAS_WIDTH2 + "px and this clip will render shifted audio"
3637
+ );
3638
+ }
3639
+ }
3519
3640
  this.pool.registerCanvas(reg.canvasId, reg.canvas);
3520
3641
  if (this.viewport) this.scheduleRender();
3521
3642
  }
3522
3643
  unregisterCanvas(canvasId) {
3523
3644
  if (this.disposed) return;
3524
- if (!this.canvases.has(canvasId)) {
3645
+ const entry = this.canvases.get(canvasId);
3646
+ if (!entry) {
3525
3647
  console.warn("[dawcore-spectrogram] unregisterCanvas: unknown canvas " + canvasId);
3526
3648
  return;
3527
3649
  }
3528
3650
  this.canvases.delete(canvasId);
3651
+ const origin = this.clipOrigins.get(entry.clipId);
3652
+ if (origin) {
3653
+ origin.canvasCount -= 1;
3654
+ if (origin.canvasCount <= 0) this.clipOrigins.delete(entry.clipId);
3655
+ }
3529
3656
  this.pool.unregisterCanvas(canvasId);
3530
3657
  }
3531
3658
  setViewport(state) {
@@ -3537,30 +3664,21 @@ var SpectrogramOrchestrator = class extends EventTarget {
3537
3664
  return;
3538
3665
  }
3539
3666
  if (this.viewport && viewportsEqual(this.viewport, state)) return;
3540
- const prevGeneration = this.generation;
3541
- this.generation += 1;
3542
- this.readyDispatched.clear();
3543
- this.pool.abortGeneration(prevGeneration);
3667
+ this.bumpGenerationAndAbortStale();
3544
3668
  this.viewport = state;
3545
3669
  this.scheduleRender();
3546
3670
  }
3547
3671
  setConfig(config) {
3548
3672
  if (this.disposed) return;
3549
3673
  this.config = config;
3550
- const prevGeneration = this.generation;
3551
- this.generation += 1;
3552
- this.readyDispatched.clear();
3553
- this.pool.abortGeneration(prevGeneration);
3674
+ this.bumpGenerationAndAbortStale();
3554
3675
  this.colorLUT.clear();
3555
3676
  this.scheduleRender();
3556
3677
  }
3557
3678
  setColorMap(colorMap) {
3558
3679
  if (this.disposed) return;
3559
3680
  this.colorMap = colorMap;
3560
- const prevGeneration = this.generation;
3561
- this.generation += 1;
3562
- this.readyDispatched.clear();
3563
- this.pool.abortGeneration(prevGeneration);
3681
+ this.bumpGenerationAndAbortStale();
3564
3682
  this.scheduleRender();
3565
3683
  }
3566
3684
  setDevicePixelRatio(dpr) {
@@ -3573,36 +3691,64 @@ var SpectrogramOrchestrator = class extends EventTarget {
3573
3691
  }
3574
3692
  if (this.devicePixelRatio === dpr) return;
3575
3693
  this.devicePixelRatio = dpr;
3576
- const prevGeneration = this.generation;
3694
+ this.bumpGenerationAndAbortStale();
3695
+ this.scheduleRender();
3696
+ }
3697
+ /**
3698
+ * Start a new render generation and cancel in-flight work from older ones.
3699
+ *
3700
+ * The worker treats work as stale iff `generation < latestGeneration`, so
3701
+ * the abort message must carry the NEW generation — passing the previous
3702
+ * one leaves its in-flight FFTs running to completion (#555).
3703
+ */
3704
+ bumpGenerationAndAbortStale() {
3577
3705
  this.generation += 1;
3578
3706
  this.readyDispatched.clear();
3579
- this.pool.abortGeneration(prevGeneration);
3580
- this.scheduleRender();
3707
+ this.pool.abortGeneration(this.generation);
3581
3708
  }
3582
3709
  dispose() {
3583
3710
  if (this.disposed) return;
3584
3711
  this.disposed = true;
3585
3712
  this.clips.clear();
3586
3713
  this.canvases.clear();
3714
+ this.clipOrigins.clear();
3587
3715
  this.viewport = null;
3588
3716
  this.colorLUT.clear();
3589
3717
  this.readyDispatched.clear();
3590
3718
  this.pool.terminate();
3591
3719
  }
3720
+ /**
3721
+ * Coalesce render requests: `renderInFlight` is held for the WHOLE async
3722
+ * render, not just until the microtask fires — a request arriving
3723
+ * mid-render (e.g. a late registerCanvas) queues one follow-up run instead
3724
+ * of starting a concurrent runRender for the same generation (#558).
3725
+ */
3592
3726
  scheduleRender() {
3593
- if (this.renderInFlight) return;
3594
3727
  if (!this.viewport) return;
3728
+ if (this.renderInFlight) {
3729
+ this.renderQueued = true;
3730
+ return;
3731
+ }
3595
3732
  this.renderInFlight = true;
3596
3733
  queueMicrotask(() => {
3597
- this.renderInFlight = false;
3598
- this.runRender(this.generation).catch((err) => {
3599
- if (err instanceof SpectrogramAbortError) return;
3600
- console.warn(
3601
- "[dawcore-spectrogram] runRender unhandled rejection (generation " + this.generation + "): " + (err instanceof Error ? err.message : String(err))
3602
- );
3603
- });
3734
+ void this.runRenderLoop();
3604
3735
  });
3605
3736
  }
3737
+ async runRenderLoop() {
3738
+ try {
3739
+ do {
3740
+ this.renderQueued = false;
3741
+ await this.runRender(this.generation).catch((err) => {
3742
+ if (err instanceof SpectrogramAbortError) return;
3743
+ console.warn(
3744
+ "[dawcore-spectrogram] runRender unhandled rejection (generation " + this.generation + "): " + (err instanceof Error ? err.message : String(err))
3745
+ );
3746
+ });
3747
+ } while (this.renderQueued && !this.disposed);
3748
+ } finally {
3749
+ this.renderInFlight = false;
3750
+ }
3751
+ }
3606
3752
  async runRender(generation) {
3607
3753
  if (this.disposed) return;
3608
3754
  const viewport = this.viewport;
@@ -3646,7 +3792,7 @@ var SpectrogramOrchestrator = class extends EventTarget {
3646
3792
  }
3647
3793
  async renderTier(canvases, generation, viewport) {
3648
3794
  if (canvases.length === 0) return;
3649
- const groups = groupContiguousChunks(canvases);
3795
+ const groups = groupRenderableChunks(canvases);
3650
3796
  for (const group of groups) {
3651
3797
  if (this.generation !== generation || this.disposed) return;
3652
3798
  await this.renderGroup(group, generation, viewport);
@@ -3662,16 +3808,31 @@ var SpectrogramOrchestrator = class extends EventTarget {
3662
3808
  );
3663
3809
  return;
3664
3810
  }
3811
+ try {
3812
+ await this.renderGroupOnce(group, generation, viewport, clip);
3813
+ } catch (err) {
3814
+ if (this.generation !== generation || this.disposed) throw err;
3815
+ if (err instanceof Error && err.message.includes("cache-miss")) {
3816
+ console.warn(
3817
+ "[dawcore-spectrogram] FFT cache entry evicted between compute and render \u2014 retrying group once"
3818
+ );
3819
+ await this.renderGroupOnce(group, generation, viewport, clip);
3820
+ return;
3821
+ }
3822
+ throw err;
3823
+ }
3824
+ }
3825
+ async renderGroupOnce(group, generation, viewport, clip) {
3826
+ const first = group[0];
3665
3827
  const fftSize = this.config.fftSize ?? SPECTROGRAM_DEFAULTS.fftSize;
3666
- const startPx = Math.min(...group.map((c) => c.globalPixelOffset));
3667
- const endPx = Math.max(...group.map((c) => c.globalPixelOffset + c.widthPx));
3668
- const startSample = clip.offsetSamples + Math.floor(startPx * viewport.samplesPerPixel);
3669
- const endSample = Math.min(
3670
- clip.offsetSamples + clip.durationSamples,
3671
- clip.offsetSamples + Math.ceil(endPx * viewport.samplesPerPixel)
3672
- );
3673
- const paddedStart = Math.max(clip.offsetSamples, startSample - fftSize);
3674
- const paddedEnd = Math.min(clip.offsetSamples + clip.durationSamples, endSample + fftSize);
3828
+ const clipRelativeOffsets = group.map((c) => c.chunkIndex * MAX_CANVAS_WIDTH2);
3829
+ const { paddedStart, paddedEnd } = computePaddedFftRange({
3830
+ chunks: group.map((c) => ({ chunkIndex: c.chunkIndex, widthPx: c.widthPx })),
3831
+ fftSize,
3832
+ offsetSamples: clip.offsetSamples,
3833
+ durationSamples: clip.durationSamples,
3834
+ samplesPerPixel: viewport.samplesPerPixel
3835
+ });
3675
3836
  const { cacheKey: cacheKey2 } = await this.pool.computeFFT(
3676
3837
  {
3677
3838
  clipId: first.clipId,
@@ -3692,7 +3853,7 @@ var SpectrogramOrchestrator = class extends EventTarget {
3692
3853
  cacheKey: cacheKey2,
3693
3854
  canvasIds: group.map((c) => c.canvasId),
3694
3855
  canvasWidths: group.map((c) => c.widthPx),
3695
- globalPixelOffsets: group.map((c) => c.globalPixelOffset),
3856
+ globalPixelOffsets: clipRelativeOffsets,
3696
3857
  canvasHeight: first.heightPx,
3697
3858
  devicePixelRatio: this.devicePixelRatio,
3698
3859
  samplesPerPixel: viewport.samplesPerPixel,
@@ -3709,7 +3870,7 @@ var SpectrogramOrchestrator = class extends EventTarget {
3709
3870
  }
3710
3871
  async renderRemainingViaIdle(canvases, generation, viewport) {
3711
3872
  if (canvases.length === 0) return;
3712
- const groups = groupContiguousChunks(canvases);
3873
+ const groups = groupRenderableChunks(canvases);
3713
3874
  for (const group of groups) {
3714
3875
  if (this.generation !== generation || this.disposed) return;
3715
3876
  await this.yieldUntilIdle();
@@ -3743,6 +3904,7 @@ export {
3743
3904
  ColorLUTCache,
3744
3905
  SpectrogramOrchestrator,
3745
3906
  classifyViewport,
3746
- groupContiguousChunks
3907
+ groupContiguousChunks,
3908
+ groupRenderableChunks
3747
3909
  };
3748
3910
  //# sourceMappingURL=index.mjs.map