@dawcore/spectrogram 0.0.3 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
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
  );
@@ -144,10 +147,10 @@ function createSpectrogramWorker(worker) {
144
147
 
145
148
  // src/worker/createSpectrogramWorkerPool.ts
146
149
  function parseChannelFromCanvasId(canvasId) {
147
- const match = canvasId.match(/-ch(\d+)-/);
150
+ const match = canvasId.match(/-ch(\d+)-chunk\d+$/);
148
151
  if (!match) {
149
152
  console.warn(
150
- "[dawcore-spectrogram] canvas ID missing -ch{N}- segment, routing to worker 0: " + canvasId
153
+ "[dawcore-spectrogram] canvas ID missing -ch{N}-chunk{M} suffix, routing to worker 0: " + canvasId
151
154
  );
152
155
  return 0;
153
156
  }
@@ -156,8 +159,17 @@ function parseChannelFromCanvasId(canvasId) {
156
159
  function defaultPoolSize() {
157
160
  return 2;
158
161
  }
162
+ var MAX_POOL_CHANNELS = 32;
159
163
  function createSpectrogramWorkerPool(createWorker, poolSize = defaultPoolSize()) {
164
+ if (poolSize > MAX_POOL_CHANNELS) {
165
+ console.warn(
166
+ "[dawcore-spectrogram] workerPoolSize " + poolSize + " exceeds the channel cap (" + MAX_POOL_CHANNELS + ") \u2014 clamping; channels beyond the cap are not servable"
167
+ );
168
+ poolSize = MAX_POOL_CHANNELS;
169
+ }
160
170
  const workers = [];
171
+ let terminated = false;
172
+ const registeredAudio = /* @__PURE__ */ new Map();
161
173
  let failedAt = -1;
162
174
  try {
163
175
  for (let i = 0; i < poolSize; i++) {
@@ -179,59 +191,111 @@ function createSpectrogramWorkerPool(createWorker, poolSize = defaultPoolSize())
179
191
  "Failed to create spectrogram worker pool (size=" + poolSize + ") at worker " + failedAt + ": " + (err instanceof Error ? err.message : String(err))
180
192
  );
181
193
  }
182
- function getWorkerForChannel(channelIndex) {
183
- return workers[channelIndex % workers.length];
194
+ function assertValidChannelIndex(channelIndex) {
195
+ if (!Number.isInteger(channelIndex) || channelIndex < 0 || channelIndex >= MAX_POOL_CHANNELS) {
196
+ throw new Error(
197
+ "[dawcore-spectrogram] invalid channel index " + channelIndex + " (expected an integer in 0.." + (MAX_POOL_CHANNELS - 1) + ")"
198
+ );
199
+ }
200
+ }
201
+ function ensureWorkerForChannel(channelIndex) {
202
+ assertValidChannelIndex(channelIndex);
203
+ if (terminated) {
204
+ throw new Error("[dawcore-spectrogram] worker pool is terminated");
205
+ }
206
+ while (workers.length <= channelIndex) {
207
+ const w = createSpectrogramWorker(createWorker());
208
+ const workerIndex = workers.length;
209
+ for (const [clipId, entry] of registeredAudio) {
210
+ if (entry.channelDataArrays.length > workerIndex) {
211
+ w.registerAudioData(clipId, entry.channelDataArrays, entry.sampleRate);
212
+ }
213
+ }
214
+ workers.push(w);
215
+ }
216
+ return workers[channelIndex];
184
217
  }
185
218
  return {
186
219
  async computeFFT(params, generation = 0) {
220
+ if (terminated) {
221
+ throw new Error("[dawcore-spectrogram] worker pool is terminated");
222
+ }
223
+ const channelCount = params.channelDataArrays.length || registeredAudio.get(params.clipId)?.channelDataArrays.length || 0;
224
+ if (channelCount === 0) {
225
+ throw new Error(
226
+ "[dawcore-spectrogram] computeFFT called with no channel data \u2014 pass channelDataArrays or registerAudioData the clip first"
227
+ );
228
+ }
187
229
  if (params.mono) {
188
230
  return workers[0].computeFFT(params, generation);
189
231
  }
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)
232
+ if (channelCount > MAX_POOL_CHANNELS) {
233
+ throw new Error(
234
+ "[dawcore-spectrogram] computeFFT: " + channelCount + " channels exceeds the pool channel cap (" + MAX_POOL_CHANNELS + ")"
235
+ );
236
+ }
237
+ const promises = Array.from(
238
+ { length: channelCount },
239
+ (_, i) => ensureWorkerForChannel(i).computeFFT({ ...params, channelFilter: i }, generation)
194
240
  );
195
241
  const settled = await Promise.allSettled(promises);
196
242
  const failures = settled.filter((s) => s.status === "rejected");
197
243
  if (failures.length > 0) {
198
- for (let i = 1; i < failures.length; i++) {
244
+ const realErrors = failures.filter((f) => !(f.reason instanceof SpectrogramAbortError));
245
+ for (let i = 1; i < realErrors.length; i++) {
199
246
  console.warn(
200
- "[dawcore-spectrogram] additional channel FFT failure (" + i + "): " + (failures[i].reason instanceof Error ? failures[i].reason.message : String(failures[i].reason))
247
+ "[dawcore-spectrogram] additional channel FFT failure (" + i + "): " + (realErrors[i].reason instanceof Error ? realErrors[i].reason.message : String(realErrors[i].reason))
201
248
  );
202
249
  }
203
- throw failures[0].reason;
250
+ throw (realErrors[0] ?? failures[0]).reason;
204
251
  }
205
252
  return settled[0].value;
206
253
  },
207
- renderChunks(params, generation = 0) {
208
- const worker = getWorkerForChannel(params.channelIndex);
254
+ // async so ensureWorkerForChannel's policy throws surface as rejections,
255
+ // matching computeFFT, instead of escaping synchronously.
256
+ async renderChunks(params, generation = 0) {
257
+ const worker = ensureWorkerForChannel(params.channelIndex);
209
258
  return worker.renderChunks({ ...params, channelIndex: 0 }, generation);
210
259
  },
211
260
  abortGeneration(generation) {
261
+ if (terminated) return;
212
262
  for (const w of workers) {
213
263
  w.abortGeneration(generation);
214
264
  }
215
265
  },
216
266
  registerCanvas(canvasId, canvas) {
217
- const ch = parseChannelFromCanvasId(canvasId);
218
- getWorkerForChannel(ch).registerCanvas(canvasId, canvas);
267
+ try {
268
+ ensureWorkerForChannel(parseChannelFromCanvasId(canvasId)).registerCanvas(canvasId, canvas);
269
+ } catch (err) {
270
+ console.warn(
271
+ '[dawcore-spectrogram] registerCanvas("' + canvasId + '") rejected \u2014 canvas not registered: ' + (err instanceof Error ? err.message : String(err))
272
+ );
273
+ }
219
274
  },
220
275
  unregisterCanvas(canvasId) {
221
- const ch = parseChannelFromCanvasId(canvasId);
222
- getWorkerForChannel(ch).unregisterCanvas(canvasId);
276
+ if (terminated) return;
277
+ const worker = workers[parseChannelFromCanvasId(canvasId)];
278
+ if (!worker) return;
279
+ worker.unregisterCanvas(canvasId);
223
280
  },
224
281
  registerAudioData(clipId, channelDataArrays, sampleRate) {
225
- for (const w of workers) {
226
- w.registerAudioData(clipId, channelDataArrays, sampleRate);
282
+ if (terminated) return;
283
+ registeredAudio.set(clipId, { channelDataArrays, sampleRate });
284
+ const relevantWorkers = Math.min(channelDataArrays.length, workers.length);
285
+ for (let i = 0; i < relevantWorkers; i++) {
286
+ workers[i].registerAudioData(clipId, channelDataArrays, sampleRate);
227
287
  }
228
288
  },
229
289
  unregisterAudioData(clipId) {
290
+ if (terminated) return;
291
+ registeredAudio.delete(clipId);
230
292
  for (const w of workers) {
231
293
  w.unregisterAudioData(clipId);
232
294
  }
233
295
  },
234
296
  terminate() {
297
+ terminated = true;
298
+ registeredAudio.clear();
235
299
  for (const w of workers) {
236
300
  w.terminate();
237
301
  }
@@ -241,6 +305,9 @@ function createSpectrogramWorkerPool(createWorker, poolSize = defaultPoolSize())
241
305
 
242
306
  // src/computation/colorMaps.ts
243
307
  function interpolateLUT(stops) {
308
+ if (stops.length === 0) {
309
+ throw new Error("[spectrogram] custom color map requires at least one color stop");
310
+ }
244
311
  const lut = new Uint8Array(256 * 3);
245
312
  const n = stops.length;
246
313
  for (let i = 0; i < 256; i++) {
@@ -3444,6 +3511,20 @@ function groupContiguousChunks(chunks) {
3444
3511
  groups.push(current);
3445
3512
  return groups;
3446
3513
  }
3514
+ function groupRenderableChunks(chunks) {
3515
+ const partitions = /* @__PURE__ */ new Map();
3516
+ for (const chunk of chunks) {
3517
+ const key = chunk.clipId + " " + chunk.channelIndex;
3518
+ const list = partitions.get(key) ?? [];
3519
+ list.push(chunk);
3520
+ partitions.set(key, list);
3521
+ }
3522
+ const groups = [];
3523
+ for (const partition of partitions.values()) {
3524
+ groups.push(...groupContiguousChunks(partition));
3525
+ }
3526
+ return groups;
3527
+ }
3447
3528
 
3448
3529
  // src/orchestrator/SpectrogramOrchestrator.ts
3449
3530
  var SpectrogramOrchestrator = class extends EventTarget {
@@ -3456,6 +3537,12 @@ var SpectrogramOrchestrator = class extends EventTarget {
3456
3537
  this.colorLUT = new ColorLUTCache();
3457
3538
  this.disposed = false;
3458
3539
  this.renderInFlight = false;
3540
+ this.renderQueued = false;
3541
+ // Per-clip timeline origin (globalPixelOffset - chunkIndex * MAX_CANVAS_WIDTH)
3542
+ // with a live canvas count — used to detect layout-contract violations.
3543
+ // The origin resets once all of a clip's canvases unregister, so a moved
3544
+ // clip re-registering at a new position doesn't false-positive.
3545
+ this.clipOrigins = /* @__PURE__ */ new Map();
3459
3546
  // Tracks which trackIds have already emitted `viewport-ready` for the
3460
3547
  // current generation. Cleared on every generation bump (setViewport with a
3461
3548
  // real change, setConfig, setColorMap, setDevicePixelRatio) AND in dispose().
@@ -3516,16 +3603,34 @@ var SpectrogramOrchestrator = class extends EventTarget {
3516
3603
  channelIndex: reg.channelIndex,
3517
3604
  chunkIndex: reg.chunkIndex
3518
3605
  });
3606
+ const originPx = reg.globalPixelOffset - reg.chunkIndex * MAX_CANVAS_WIDTH;
3607
+ const origin = this.clipOrigins.get(reg.clipId);
3608
+ if (!origin) {
3609
+ this.clipOrigins.set(reg.clipId, { originPx, canvasCount: 1 });
3610
+ } else {
3611
+ origin.canvasCount += 1;
3612
+ if (origin.originPx !== originPx) {
3613
+ console.warn(
3614
+ "[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_WIDTH + "px and this clip will render shifted audio"
3615
+ );
3616
+ }
3617
+ }
3519
3618
  this.pool.registerCanvas(reg.canvasId, reg.canvas);
3520
3619
  if (this.viewport) this.scheduleRender();
3521
3620
  }
3522
3621
  unregisterCanvas(canvasId) {
3523
3622
  if (this.disposed) return;
3524
- if (!this.canvases.has(canvasId)) {
3623
+ const entry = this.canvases.get(canvasId);
3624
+ if (!entry) {
3525
3625
  console.warn("[dawcore-spectrogram] unregisterCanvas: unknown canvas " + canvasId);
3526
3626
  return;
3527
3627
  }
3528
3628
  this.canvases.delete(canvasId);
3629
+ const origin = this.clipOrigins.get(entry.clipId);
3630
+ if (origin) {
3631
+ origin.canvasCount -= 1;
3632
+ if (origin.canvasCount <= 0) this.clipOrigins.delete(entry.clipId);
3633
+ }
3529
3634
  this.pool.unregisterCanvas(canvasId);
3530
3635
  }
3531
3636
  setViewport(state) {
@@ -3537,30 +3642,21 @@ var SpectrogramOrchestrator = class extends EventTarget {
3537
3642
  return;
3538
3643
  }
3539
3644
  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);
3645
+ this.bumpGenerationAndAbortStale();
3544
3646
  this.viewport = state;
3545
3647
  this.scheduleRender();
3546
3648
  }
3547
3649
  setConfig(config) {
3548
3650
  if (this.disposed) return;
3549
3651
  this.config = config;
3550
- const prevGeneration = this.generation;
3551
- this.generation += 1;
3552
- this.readyDispatched.clear();
3553
- this.pool.abortGeneration(prevGeneration);
3652
+ this.bumpGenerationAndAbortStale();
3554
3653
  this.colorLUT.clear();
3555
3654
  this.scheduleRender();
3556
3655
  }
3557
3656
  setColorMap(colorMap) {
3558
3657
  if (this.disposed) return;
3559
3658
  this.colorMap = colorMap;
3560
- const prevGeneration = this.generation;
3561
- this.generation += 1;
3562
- this.readyDispatched.clear();
3563
- this.pool.abortGeneration(prevGeneration);
3659
+ this.bumpGenerationAndAbortStale();
3564
3660
  this.scheduleRender();
3565
3661
  }
3566
3662
  setDevicePixelRatio(dpr) {
@@ -3573,36 +3669,64 @@ var SpectrogramOrchestrator = class extends EventTarget {
3573
3669
  }
3574
3670
  if (this.devicePixelRatio === dpr) return;
3575
3671
  this.devicePixelRatio = dpr;
3576
- const prevGeneration = this.generation;
3672
+ this.bumpGenerationAndAbortStale();
3673
+ this.scheduleRender();
3674
+ }
3675
+ /**
3676
+ * Start a new render generation and cancel in-flight work from older ones.
3677
+ *
3678
+ * The worker treats work as stale iff `generation < latestGeneration`, so
3679
+ * the abort message must carry the NEW generation — passing the previous
3680
+ * one leaves its in-flight FFTs running to completion (#555).
3681
+ */
3682
+ bumpGenerationAndAbortStale() {
3577
3683
  this.generation += 1;
3578
3684
  this.readyDispatched.clear();
3579
- this.pool.abortGeneration(prevGeneration);
3580
- this.scheduleRender();
3685
+ this.pool.abortGeneration(this.generation);
3581
3686
  }
3582
3687
  dispose() {
3583
3688
  if (this.disposed) return;
3584
3689
  this.disposed = true;
3585
3690
  this.clips.clear();
3586
3691
  this.canvases.clear();
3692
+ this.clipOrigins.clear();
3587
3693
  this.viewport = null;
3588
3694
  this.colorLUT.clear();
3589
3695
  this.readyDispatched.clear();
3590
3696
  this.pool.terminate();
3591
3697
  }
3698
+ /**
3699
+ * Coalesce render requests: `renderInFlight` is held for the WHOLE async
3700
+ * render, not just until the microtask fires — a request arriving
3701
+ * mid-render (e.g. a late registerCanvas) queues one follow-up run instead
3702
+ * of starting a concurrent runRender for the same generation (#558).
3703
+ */
3592
3704
  scheduleRender() {
3593
- if (this.renderInFlight) return;
3594
3705
  if (!this.viewport) return;
3706
+ if (this.renderInFlight) {
3707
+ this.renderQueued = true;
3708
+ return;
3709
+ }
3595
3710
  this.renderInFlight = true;
3596
3711
  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
- });
3712
+ void this.runRenderLoop();
3604
3713
  });
3605
3714
  }
3715
+ async runRenderLoop() {
3716
+ try {
3717
+ do {
3718
+ this.renderQueued = false;
3719
+ await this.runRender(this.generation).catch((err) => {
3720
+ if (err instanceof SpectrogramAbortError) return;
3721
+ console.warn(
3722
+ "[dawcore-spectrogram] runRender unhandled rejection (generation " + this.generation + "): " + (err instanceof Error ? err.message : String(err))
3723
+ );
3724
+ });
3725
+ } while (this.renderQueued && !this.disposed);
3726
+ } finally {
3727
+ this.renderInFlight = false;
3728
+ }
3729
+ }
3606
3730
  async runRender(generation) {
3607
3731
  if (this.disposed) return;
3608
3732
  const viewport = this.viewport;
@@ -3646,7 +3770,7 @@ var SpectrogramOrchestrator = class extends EventTarget {
3646
3770
  }
3647
3771
  async renderTier(canvases, generation, viewport) {
3648
3772
  if (canvases.length === 0) return;
3649
- const groups = groupContiguousChunks(canvases);
3773
+ const groups = groupRenderableChunks(canvases);
3650
3774
  for (const group of groups) {
3651
3775
  if (this.generation !== generation || this.disposed) return;
3652
3776
  await this.renderGroup(group, generation, viewport);
@@ -3662,9 +3786,26 @@ var SpectrogramOrchestrator = class extends EventTarget {
3662
3786
  );
3663
3787
  return;
3664
3788
  }
3789
+ try {
3790
+ await this.renderGroupOnce(group, generation, viewport, clip);
3791
+ } catch (err) {
3792
+ if (this.generation !== generation || this.disposed) throw err;
3793
+ if (err instanceof Error && err.message.includes("cache-miss")) {
3794
+ console.warn(
3795
+ "[dawcore-spectrogram] FFT cache entry evicted between compute and render \u2014 retrying group once"
3796
+ );
3797
+ await this.renderGroupOnce(group, generation, viewport, clip);
3798
+ return;
3799
+ }
3800
+ throw err;
3801
+ }
3802
+ }
3803
+ async renderGroupOnce(group, generation, viewport, clip) {
3804
+ const first = group[0];
3665
3805
  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));
3806
+ const clipRelativeOffsets = group.map((c) => c.chunkIndex * MAX_CANVAS_WIDTH);
3807
+ const startPx = Math.min(...clipRelativeOffsets);
3808
+ const endPx = Math.max(...group.map((c, i) => clipRelativeOffsets[i] + c.widthPx));
3668
3809
  const startSample = clip.offsetSamples + Math.floor(startPx * viewport.samplesPerPixel);
3669
3810
  const endSample = Math.min(
3670
3811
  clip.offsetSamples + clip.durationSamples,
@@ -3692,7 +3833,7 @@ var SpectrogramOrchestrator = class extends EventTarget {
3692
3833
  cacheKey: cacheKey2,
3693
3834
  canvasIds: group.map((c) => c.canvasId),
3694
3835
  canvasWidths: group.map((c) => c.widthPx),
3695
- globalPixelOffsets: group.map((c) => c.globalPixelOffset),
3836
+ globalPixelOffsets: clipRelativeOffsets,
3696
3837
  canvasHeight: first.heightPx,
3697
3838
  devicePixelRatio: this.devicePixelRatio,
3698
3839
  samplesPerPixel: viewport.samplesPerPixel,
@@ -3709,7 +3850,7 @@ var SpectrogramOrchestrator = class extends EventTarget {
3709
3850
  }
3710
3851
  async renderRemainingViaIdle(canvases, generation, viewport) {
3711
3852
  if (canvases.length === 0) return;
3712
- const groups = groupContiguousChunks(canvases);
3853
+ const groups = groupRenderableChunks(canvases);
3713
3854
  for (const group of groups) {
3714
3855
  if (this.generation !== generation || this.disposed) return;
3715
3856
  await this.yieldUntilIdle();
@@ -3743,6 +3884,7 @@ export {
3743
3884
  ColorLUTCache,
3744
3885
  SpectrogramOrchestrator,
3745
3886
  classifyViewport,
3746
- groupContiguousChunks
3887
+ groupContiguousChunks,
3888
+ groupRenderableChunks
3747
3889
  };
3748
3890
  //# sourceMappingURL=index.mjs.map