@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.
package/dist/index.js CHANGED
@@ -34,13 +34,17 @@ __export(src_exports, {
34
34
  SpectrogramAbortError: () => SpectrogramAbortError,
35
35
  SpectrogramOrchestrator: () => SpectrogramOrchestrator,
36
36
  classifyViewport: () => classifyViewport,
37
+ computePaddedFftRange: () => computePaddedFftRange,
37
38
  computeSpectrogram: () => computeSpectrogram,
38
39
  computeSpectrogramMono: () => computeSpectrogramMono,
39
40
  createSpectrogramWorker: () => createSpectrogramWorker,
40
41
  createSpectrogramWorkerPool: () => createSpectrogramWorkerPool,
41
42
  getColorMap: () => getColorMap,
42
43
  getFrequencyScale: () => getFrequencyScale,
43
- groupContiguousChunks: () => groupContiguousChunks
44
+ groupContiguousChunks: () => groupContiguousChunks,
45
+ groupRenderableChunks: () => groupRenderableChunks,
46
+ pixelColumnToFrame: () => pixelColumnToFrame,
47
+ pixelRowToBin: () => pixelRowToBin
44
48
  });
45
49
  module.exports = __toCommonJS(src_exports);
46
50
 
@@ -237,6 +241,9 @@ function computeSpectrogramMono(audioBuffer, config = {}, offsetSamples = 0, dur
237
241
 
238
242
  // src/computation/colorMaps.ts
239
243
  function interpolateLUT(stops) {
244
+ if (stops.length === 0) {
245
+ throw new Error("[spectrogram] custom color map requires at least one color stop");
246
+ }
240
247
  const lut = new Uint8Array(256 * 3);
241
248
  const n = stops.length;
242
249
  for (let i = 0; i < 256; i++) {
@@ -3433,6 +3440,56 @@ function getFrequencyScale(name) {
3433
3440
  }
3434
3441
  }
3435
3442
 
3443
+ // src/computation/renderGeometry.ts
3444
+ function pixelColumnToFrame(params) {
3445
+ const fileSample = params.clipOffsetSamples + params.pixelX * params.samplesPerPixel;
3446
+ return Math.floor((fileSample - params.fftStartSample) / params.hopSize);
3447
+ }
3448
+ function pixelRowToBin(params) {
3449
+ const { normalizedY, frequencyBinCount, sampleRate, minFrequency, maxFrequency } = params;
3450
+ const nyquist = sampleRate / 2;
3451
+ let bin;
3452
+ if (params.isLinear) {
3453
+ const freq = minFrequency + normalizedY * (maxFrequency - minFrequency);
3454
+ bin = Math.floor(freq / nyquist * frequencyBinCount);
3455
+ } else {
3456
+ let lo = 0;
3457
+ let hi = frequencyBinCount - 1;
3458
+ while (lo < hi) {
3459
+ const mid = lo + hi >> 1;
3460
+ const freq = mid / frequencyBinCount * nyquist;
3461
+ if (params.scaleFn(freq, minFrequency, maxFrequency) < normalizedY) {
3462
+ lo = mid + 1;
3463
+ } else {
3464
+ hi = mid;
3465
+ }
3466
+ }
3467
+ bin = lo;
3468
+ }
3469
+ return Math.min(bin, frequencyBinCount - 1);
3470
+ }
3471
+
3472
+ // src/computation/fftSampleRange.ts
3473
+ var import_core = require("@waveform-playlist/core");
3474
+ function computePaddedFftRange({
3475
+ chunks,
3476
+ fftSize,
3477
+ offsetSamples,
3478
+ durationSamples,
3479
+ samplesPerPixel
3480
+ }) {
3481
+ const startPx = Math.min(...chunks.map((c) => c.chunkIndex * import_core.MAX_CANVAS_WIDTH));
3482
+ const endPx = Math.max(...chunks.map((c) => c.chunkIndex * import_core.MAX_CANVAS_WIDTH + c.widthPx));
3483
+ const startSample = offsetSamples + Math.floor(startPx * samplesPerPixel);
3484
+ const endSample = Math.min(
3485
+ offsetSamples + durationSamples,
3486
+ offsetSamples + Math.ceil(endPx * samplesPerPixel)
3487
+ );
3488
+ const paddedStart = Math.max(offsetSamples, startSample - fftSize);
3489
+ const paddedEnd = Math.min(offsetSamples + durationSamples, endSample + fftSize);
3490
+ return { paddedStart, paddedEnd };
3491
+ }
3492
+
3436
3493
  // src/worker/createSpectrogramWorker.ts
3437
3494
  var SpectrogramAbortError = class extends Error {
3438
3495
  constructor() {
@@ -3472,7 +3529,6 @@ function createSpectrogramWorker(worker) {
3472
3529
  }
3473
3530
  };
3474
3531
  worker.onerror = (e) => {
3475
- terminated = true;
3476
3532
  console.error(
3477
3533
  "[dawcore-spectrogram] worker crashed with " + pending.size + " pending operations: " + (e.message || "unknown error")
3478
3534
  );
@@ -3575,21 +3631,31 @@ function createSpectrogramWorker(worker) {
3575
3631
  }
3576
3632
 
3577
3633
  // src/worker/createSpectrogramWorkerPool.ts
3634
+ var import_core2 = require("@waveform-playlist/core");
3578
3635
  function parseChannelFromCanvasId(canvasId) {
3579
- const match = canvasId.match(/-ch(\d+)-/);
3580
- if (!match) {
3636
+ const parsed = (0, import_core2.parseSpectrogramCanvasId)(canvasId);
3637
+ if (!parsed) {
3581
3638
  console.warn(
3582
- "[dawcore-spectrogram] canvas ID missing -ch{N}- segment, routing to worker 0: " + canvasId
3639
+ "[dawcore-spectrogram] canvas ID missing -ch{N}-chunk{M} suffix, routing to worker 0: " + canvasId
3583
3640
  );
3584
3641
  return 0;
3585
3642
  }
3586
- return parseInt(match[1], 10);
3643
+ return parsed.channelIndex;
3587
3644
  }
3588
3645
  function defaultPoolSize() {
3589
3646
  return 2;
3590
3647
  }
3648
+ var MAX_POOL_CHANNELS = 32;
3591
3649
  function createSpectrogramWorkerPool(createWorker, poolSize = defaultPoolSize()) {
3650
+ if (poolSize > MAX_POOL_CHANNELS) {
3651
+ console.warn(
3652
+ "[dawcore-spectrogram] workerPoolSize " + poolSize + " exceeds the channel cap (" + MAX_POOL_CHANNELS + ") \u2014 clamping; channels beyond the cap are not servable"
3653
+ );
3654
+ poolSize = MAX_POOL_CHANNELS;
3655
+ }
3592
3656
  const workers = [];
3657
+ let terminated = false;
3658
+ const registeredAudio = /* @__PURE__ */ new Map();
3593
3659
  let failedAt = -1;
3594
3660
  try {
3595
3661
  for (let i = 0; i < poolSize; i++) {
@@ -3611,59 +3677,111 @@ function createSpectrogramWorkerPool(createWorker, poolSize = defaultPoolSize())
3611
3677
  "Failed to create spectrogram worker pool (size=" + poolSize + ") at worker " + failedAt + ": " + (err instanceof Error ? err.message : String(err))
3612
3678
  );
3613
3679
  }
3614
- function getWorkerForChannel(channelIndex) {
3615
- return workers[channelIndex % workers.length];
3680
+ function assertValidChannelIndex(channelIndex) {
3681
+ if (!Number.isInteger(channelIndex) || channelIndex < 0 || channelIndex >= MAX_POOL_CHANNELS) {
3682
+ throw new Error(
3683
+ "[dawcore-spectrogram] invalid channel index " + channelIndex + " (expected an integer in 0.." + (MAX_POOL_CHANNELS - 1) + ")"
3684
+ );
3685
+ }
3686
+ }
3687
+ function ensureWorkerForChannel(channelIndex) {
3688
+ assertValidChannelIndex(channelIndex);
3689
+ if (terminated) {
3690
+ throw new Error("[dawcore-spectrogram] worker pool is terminated");
3691
+ }
3692
+ while (workers.length <= channelIndex) {
3693
+ const w = createSpectrogramWorker(createWorker());
3694
+ const workerIndex = workers.length;
3695
+ for (const [clipId, entry] of registeredAudio) {
3696
+ if (entry.channelDataArrays.length > workerIndex) {
3697
+ w.registerAudioData(clipId, entry.channelDataArrays, entry.sampleRate);
3698
+ }
3699
+ }
3700
+ workers.push(w);
3701
+ }
3702
+ return workers[channelIndex];
3616
3703
  }
3617
3704
  return {
3618
3705
  async computeFFT(params, generation = 0) {
3706
+ if (terminated) {
3707
+ throw new Error("[dawcore-spectrogram] worker pool is terminated");
3708
+ }
3709
+ const channelCount = params.channelDataArrays.length || registeredAudio.get(params.clipId)?.channelDataArrays.length || 0;
3710
+ if (channelCount === 0) {
3711
+ throw new Error(
3712
+ "[dawcore-spectrogram] computeFFT called with no channel data \u2014 pass channelDataArrays or registerAudioData the clip first"
3713
+ );
3714
+ }
3619
3715
  if (params.mono) {
3620
3716
  return workers[0].computeFFT(params, generation);
3621
3717
  }
3622
- const channelCount = params.channelDataArrays.length;
3623
- const activeWorkers = workers.slice(0, channelCount);
3624
- const promises = activeWorkers.map(
3625
- (w, i) => w.computeFFT({ ...params, channelFilter: i }, generation)
3718
+ if (channelCount > MAX_POOL_CHANNELS) {
3719
+ throw new Error(
3720
+ "[dawcore-spectrogram] computeFFT: " + channelCount + " channels exceeds the pool channel cap (" + MAX_POOL_CHANNELS + ")"
3721
+ );
3722
+ }
3723
+ const promises = Array.from(
3724
+ { length: channelCount },
3725
+ (_, i) => ensureWorkerForChannel(i).computeFFT({ ...params, channelFilter: i }, generation)
3626
3726
  );
3627
3727
  const settled = await Promise.allSettled(promises);
3628
3728
  const failures = settled.filter((s) => s.status === "rejected");
3629
3729
  if (failures.length > 0) {
3630
- for (let i = 1; i < failures.length; i++) {
3730
+ const realErrors = failures.filter((f) => !(f.reason instanceof SpectrogramAbortError));
3731
+ for (let i = 1; i < realErrors.length; i++) {
3631
3732
  console.warn(
3632
- "[dawcore-spectrogram] additional channel FFT failure (" + i + "): " + (failures[i].reason instanceof Error ? failures[i].reason.message : String(failures[i].reason))
3733
+ "[dawcore-spectrogram] additional channel FFT failure (" + i + "): " + (realErrors[i].reason instanceof Error ? realErrors[i].reason.message : String(realErrors[i].reason))
3633
3734
  );
3634
3735
  }
3635
- throw failures[0].reason;
3736
+ throw (realErrors[0] ?? failures[0]).reason;
3636
3737
  }
3637
3738
  return settled[0].value;
3638
3739
  },
3639
- renderChunks(params, generation = 0) {
3640
- const worker = getWorkerForChannel(params.channelIndex);
3740
+ // async so ensureWorkerForChannel's policy throws surface as rejections,
3741
+ // matching computeFFT, instead of escaping synchronously.
3742
+ async renderChunks(params, generation = 0) {
3743
+ const worker = ensureWorkerForChannel(params.channelIndex);
3641
3744
  return worker.renderChunks({ ...params, channelIndex: 0 }, generation);
3642
3745
  },
3643
3746
  abortGeneration(generation) {
3747
+ if (terminated) return;
3644
3748
  for (const w of workers) {
3645
3749
  w.abortGeneration(generation);
3646
3750
  }
3647
3751
  },
3648
3752
  registerCanvas(canvasId, canvas) {
3649
- const ch = parseChannelFromCanvasId(canvasId);
3650
- getWorkerForChannel(ch).registerCanvas(canvasId, canvas);
3753
+ try {
3754
+ ensureWorkerForChannel(parseChannelFromCanvasId(canvasId)).registerCanvas(canvasId, canvas);
3755
+ } catch (err) {
3756
+ console.warn(
3757
+ '[dawcore-spectrogram] registerCanvas("' + canvasId + '") rejected \u2014 canvas not registered: ' + (err instanceof Error ? err.message : String(err))
3758
+ );
3759
+ }
3651
3760
  },
3652
3761
  unregisterCanvas(canvasId) {
3653
- const ch = parseChannelFromCanvasId(canvasId);
3654
- getWorkerForChannel(ch).unregisterCanvas(canvasId);
3762
+ if (terminated) return;
3763
+ const worker = workers[parseChannelFromCanvasId(canvasId)];
3764
+ if (!worker) return;
3765
+ worker.unregisterCanvas(canvasId);
3655
3766
  },
3656
3767
  registerAudioData(clipId, channelDataArrays, sampleRate) {
3657
- for (const w of workers) {
3658
- w.registerAudioData(clipId, channelDataArrays, sampleRate);
3768
+ if (terminated) return;
3769
+ registeredAudio.set(clipId, { channelDataArrays, sampleRate });
3770
+ const relevantWorkers = Math.min(channelDataArrays.length, workers.length);
3771
+ for (let i = 0; i < relevantWorkers; i++) {
3772
+ workers[i].registerAudioData(clipId, channelDataArrays, sampleRate);
3659
3773
  }
3660
3774
  },
3661
3775
  unregisterAudioData(clipId) {
3776
+ if (terminated) return;
3777
+ registeredAudio.delete(clipId);
3662
3778
  for (const w of workers) {
3663
3779
  w.unregisterAudioData(clipId);
3664
3780
  }
3665
3781
  },
3666
3782
  terminate() {
3783
+ terminated = true;
3784
+ registeredAudio.clear();
3667
3785
  for (const w of workers) {
3668
3786
  w.terminate();
3669
3787
  }
@@ -3672,7 +3790,7 @@ function createSpectrogramWorkerPool(createWorker, poolSize = defaultPoolSize())
3672
3790
  }
3673
3791
 
3674
3792
  // src/orchestrator/SpectrogramOrchestrator.ts
3675
- var import_core = require("@waveform-playlist/core");
3793
+ var import_core3 = require("@waveform-playlist/core");
3676
3794
 
3677
3795
  // src/orchestrator/color-lut-cache.ts
3678
3796
  var ColorLUTCache = class {
@@ -3737,6 +3855,20 @@ function groupContiguousChunks(chunks) {
3737
3855
  groups.push(current);
3738
3856
  return groups;
3739
3857
  }
3858
+ function groupRenderableChunks(chunks) {
3859
+ const partitions = /* @__PURE__ */ new Map();
3860
+ for (const chunk of chunks) {
3861
+ const key = chunk.clipId + " " + chunk.channelIndex;
3862
+ const list = partitions.get(key) ?? [];
3863
+ list.push(chunk);
3864
+ partitions.set(key, list);
3865
+ }
3866
+ const groups = [];
3867
+ for (const partition of partitions.values()) {
3868
+ groups.push(...groupContiguousChunks(partition));
3869
+ }
3870
+ return groups;
3871
+ }
3740
3872
 
3741
3873
  // src/orchestrator/SpectrogramOrchestrator.ts
3742
3874
  var SpectrogramOrchestrator = class extends EventTarget {
@@ -3749,6 +3881,12 @@ var SpectrogramOrchestrator = class extends EventTarget {
3749
3881
  this.colorLUT = new ColorLUTCache();
3750
3882
  this.disposed = false;
3751
3883
  this.renderInFlight = false;
3884
+ this.renderQueued = false;
3885
+ // Per-clip timeline origin (globalPixelOffset - chunkIndex * MAX_CANVAS_WIDTH)
3886
+ // with a live canvas count — used to detect layout-contract violations.
3887
+ // The origin resets once all of a clip's canvases unregister, so a moved
3888
+ // clip re-registering at a new position doesn't false-positive.
3889
+ this.clipOrigins = /* @__PURE__ */ new Map();
3752
3890
  // Tracks which trackIds have already emitted `viewport-ready` for the
3753
3891
  // current generation. Cleared on every generation bump (setViewport with a
3754
3892
  // real change, setConfig, setColorMap, setDevicePixelRatio) AND in dispose().
@@ -3760,7 +3898,7 @@ var SpectrogramOrchestrator = class extends EventTarget {
3760
3898
  const poolSize = opts.workerPoolSize ?? 2;
3761
3899
  this.pool = createSpectrogramWorkerPool(opts.workerFactory, poolSize);
3762
3900
  this.config = opts.config;
3763
- this.colorMap = opts.colorMap ?? import_core.DEFAULT_SPECTROGRAM_COLOR_MAP;
3901
+ this.colorMap = opts.colorMap ?? import_core3.DEFAULT_SPECTROGRAM_COLOR_MAP;
3764
3902
  this.devicePixelRatio = opts.devicePixelRatio ?? (typeof window !== "undefined" ? window.devicePixelRatio : 1);
3765
3903
  }
3766
3904
  registerClip(reg) {
@@ -3809,16 +3947,34 @@ var SpectrogramOrchestrator = class extends EventTarget {
3809
3947
  channelIndex: reg.channelIndex,
3810
3948
  chunkIndex: reg.chunkIndex
3811
3949
  });
3950
+ const originPx = reg.globalPixelOffset - reg.chunkIndex * import_core3.MAX_CANVAS_WIDTH;
3951
+ const origin = this.clipOrigins.get(reg.clipId);
3952
+ if (!origin) {
3953
+ this.clipOrigins.set(reg.clipId, { originPx, canvasCount: 1 });
3954
+ } else {
3955
+ origin.canvasCount += 1;
3956
+ if (origin.originPx !== originPx) {
3957
+ console.warn(
3958
+ "[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 * " + import_core3.MAX_CANVAS_WIDTH + "px and this clip will render shifted audio"
3959
+ );
3960
+ }
3961
+ }
3812
3962
  this.pool.registerCanvas(reg.canvasId, reg.canvas);
3813
3963
  if (this.viewport) this.scheduleRender();
3814
3964
  }
3815
3965
  unregisterCanvas(canvasId) {
3816
3966
  if (this.disposed) return;
3817
- if (!this.canvases.has(canvasId)) {
3967
+ const entry = this.canvases.get(canvasId);
3968
+ if (!entry) {
3818
3969
  console.warn("[dawcore-spectrogram] unregisterCanvas: unknown canvas " + canvasId);
3819
3970
  return;
3820
3971
  }
3821
3972
  this.canvases.delete(canvasId);
3973
+ const origin = this.clipOrigins.get(entry.clipId);
3974
+ if (origin) {
3975
+ origin.canvasCount -= 1;
3976
+ if (origin.canvasCount <= 0) this.clipOrigins.delete(entry.clipId);
3977
+ }
3822
3978
  this.pool.unregisterCanvas(canvasId);
3823
3979
  }
3824
3980
  setViewport(state) {
@@ -3830,30 +3986,21 @@ var SpectrogramOrchestrator = class extends EventTarget {
3830
3986
  return;
3831
3987
  }
3832
3988
  if (this.viewport && viewportsEqual(this.viewport, state)) return;
3833
- const prevGeneration = this.generation;
3834
- this.generation += 1;
3835
- this.readyDispatched.clear();
3836
- this.pool.abortGeneration(prevGeneration);
3989
+ this.bumpGenerationAndAbortStale();
3837
3990
  this.viewport = state;
3838
3991
  this.scheduleRender();
3839
3992
  }
3840
3993
  setConfig(config) {
3841
3994
  if (this.disposed) return;
3842
3995
  this.config = config;
3843
- const prevGeneration = this.generation;
3844
- this.generation += 1;
3845
- this.readyDispatched.clear();
3846
- this.pool.abortGeneration(prevGeneration);
3996
+ this.bumpGenerationAndAbortStale();
3847
3997
  this.colorLUT.clear();
3848
3998
  this.scheduleRender();
3849
3999
  }
3850
4000
  setColorMap(colorMap) {
3851
4001
  if (this.disposed) return;
3852
4002
  this.colorMap = colorMap;
3853
- const prevGeneration = this.generation;
3854
- this.generation += 1;
3855
- this.readyDispatched.clear();
3856
- this.pool.abortGeneration(prevGeneration);
4003
+ this.bumpGenerationAndAbortStale();
3857
4004
  this.scheduleRender();
3858
4005
  }
3859
4006
  setDevicePixelRatio(dpr) {
@@ -3866,36 +4013,64 @@ var SpectrogramOrchestrator = class extends EventTarget {
3866
4013
  }
3867
4014
  if (this.devicePixelRatio === dpr) return;
3868
4015
  this.devicePixelRatio = dpr;
3869
- const prevGeneration = this.generation;
4016
+ this.bumpGenerationAndAbortStale();
4017
+ this.scheduleRender();
4018
+ }
4019
+ /**
4020
+ * Start a new render generation and cancel in-flight work from older ones.
4021
+ *
4022
+ * The worker treats work as stale iff `generation < latestGeneration`, so
4023
+ * the abort message must carry the NEW generation — passing the previous
4024
+ * one leaves its in-flight FFTs running to completion (#555).
4025
+ */
4026
+ bumpGenerationAndAbortStale() {
3870
4027
  this.generation += 1;
3871
4028
  this.readyDispatched.clear();
3872
- this.pool.abortGeneration(prevGeneration);
3873
- this.scheduleRender();
4029
+ this.pool.abortGeneration(this.generation);
3874
4030
  }
3875
4031
  dispose() {
3876
4032
  if (this.disposed) return;
3877
4033
  this.disposed = true;
3878
4034
  this.clips.clear();
3879
4035
  this.canvases.clear();
4036
+ this.clipOrigins.clear();
3880
4037
  this.viewport = null;
3881
4038
  this.colorLUT.clear();
3882
4039
  this.readyDispatched.clear();
3883
4040
  this.pool.terminate();
3884
4041
  }
4042
+ /**
4043
+ * Coalesce render requests: `renderInFlight` is held for the WHOLE async
4044
+ * render, not just until the microtask fires — a request arriving
4045
+ * mid-render (e.g. a late registerCanvas) queues one follow-up run instead
4046
+ * of starting a concurrent runRender for the same generation (#558).
4047
+ */
3885
4048
  scheduleRender() {
3886
- if (this.renderInFlight) return;
3887
4049
  if (!this.viewport) return;
4050
+ if (this.renderInFlight) {
4051
+ this.renderQueued = true;
4052
+ return;
4053
+ }
3888
4054
  this.renderInFlight = true;
3889
4055
  queueMicrotask(() => {
3890
- this.renderInFlight = false;
3891
- this.runRender(this.generation).catch((err) => {
3892
- if (err instanceof SpectrogramAbortError) return;
3893
- console.warn(
3894
- "[dawcore-spectrogram] runRender unhandled rejection (generation " + this.generation + "): " + (err instanceof Error ? err.message : String(err))
3895
- );
3896
- });
4056
+ void this.runRenderLoop();
3897
4057
  });
3898
4058
  }
4059
+ async runRenderLoop() {
4060
+ try {
4061
+ do {
4062
+ this.renderQueued = false;
4063
+ await this.runRender(this.generation).catch((err) => {
4064
+ if (err instanceof SpectrogramAbortError) return;
4065
+ console.warn(
4066
+ "[dawcore-spectrogram] runRender unhandled rejection (generation " + this.generation + "): " + (err instanceof Error ? err.message : String(err))
4067
+ );
4068
+ });
4069
+ } while (this.renderQueued && !this.disposed);
4070
+ } finally {
4071
+ this.renderInFlight = false;
4072
+ }
4073
+ }
3899
4074
  async runRender(generation) {
3900
4075
  if (this.disposed) return;
3901
4076
  const viewport = this.viewport;
@@ -3939,7 +4114,7 @@ var SpectrogramOrchestrator = class extends EventTarget {
3939
4114
  }
3940
4115
  async renderTier(canvases, generation, viewport) {
3941
4116
  if (canvases.length === 0) return;
3942
- const groups = groupContiguousChunks(canvases);
4117
+ const groups = groupRenderableChunks(canvases);
3943
4118
  for (const group of groups) {
3944
4119
  if (this.generation !== generation || this.disposed) return;
3945
4120
  await this.renderGroup(group, generation, viewport);
@@ -3955,16 +4130,31 @@ var SpectrogramOrchestrator = class extends EventTarget {
3955
4130
  );
3956
4131
  return;
3957
4132
  }
3958
- const fftSize = this.config.fftSize ?? import_core.SPECTROGRAM_DEFAULTS.fftSize;
3959
- const startPx = Math.min(...group.map((c) => c.globalPixelOffset));
3960
- const endPx = Math.max(...group.map((c) => c.globalPixelOffset + c.widthPx));
3961
- const startSample = clip.offsetSamples + Math.floor(startPx * viewport.samplesPerPixel);
3962
- const endSample = Math.min(
3963
- clip.offsetSamples + clip.durationSamples,
3964
- clip.offsetSamples + Math.ceil(endPx * viewport.samplesPerPixel)
3965
- );
3966
- const paddedStart = Math.max(clip.offsetSamples, startSample - fftSize);
3967
- const paddedEnd = Math.min(clip.offsetSamples + clip.durationSamples, endSample + fftSize);
4133
+ try {
4134
+ await this.renderGroupOnce(group, generation, viewport, clip);
4135
+ } catch (err) {
4136
+ if (this.generation !== generation || this.disposed) throw err;
4137
+ if (err instanceof Error && err.message.includes("cache-miss")) {
4138
+ console.warn(
4139
+ "[dawcore-spectrogram] FFT cache entry evicted between compute and render \u2014 retrying group once"
4140
+ );
4141
+ await this.renderGroupOnce(group, generation, viewport, clip);
4142
+ return;
4143
+ }
4144
+ throw err;
4145
+ }
4146
+ }
4147
+ async renderGroupOnce(group, generation, viewport, clip) {
4148
+ const first = group[0];
4149
+ const fftSize = this.config.fftSize ?? import_core3.SPECTROGRAM_DEFAULTS.fftSize;
4150
+ const clipRelativeOffsets = group.map((c) => c.chunkIndex * import_core3.MAX_CANVAS_WIDTH);
4151
+ const { paddedStart, paddedEnd } = computePaddedFftRange({
4152
+ chunks: group.map((c) => ({ chunkIndex: c.chunkIndex, widthPx: c.widthPx })),
4153
+ fftSize,
4154
+ offsetSamples: clip.offsetSamples,
4155
+ durationSamples: clip.durationSamples,
4156
+ samplesPerPixel: viewport.samplesPerPixel
4157
+ });
3968
4158
  const { cacheKey: cacheKey2 } = await this.pool.computeFFT(
3969
4159
  {
3970
4160
  clipId: first.clipId,
@@ -3985,16 +4175,16 @@ var SpectrogramOrchestrator = class extends EventTarget {
3985
4175
  cacheKey: cacheKey2,
3986
4176
  canvasIds: group.map((c) => c.canvasId),
3987
4177
  canvasWidths: group.map((c) => c.widthPx),
3988
- globalPixelOffsets: group.map((c) => c.globalPixelOffset),
4178
+ globalPixelOffsets: clipRelativeOffsets,
3989
4179
  canvasHeight: first.heightPx,
3990
4180
  devicePixelRatio: this.devicePixelRatio,
3991
4181
  samplesPerPixel: viewport.samplesPerPixel,
3992
4182
  colorLUT,
3993
- frequencyScale: String(this.config.frequencyScale ?? import_core.SPECTROGRAM_DEFAULTS.frequencyScale),
3994
- minFrequency: this.config.minFrequency ?? import_core.SPECTROGRAM_DEFAULTS.minFrequency,
4183
+ frequencyScale: String(this.config.frequencyScale ?? import_core3.SPECTROGRAM_DEFAULTS.frequencyScale),
4184
+ minFrequency: this.config.minFrequency ?? import_core3.SPECTROGRAM_DEFAULTS.minFrequency,
3995
4185
  maxFrequency: this.config.maxFrequency ?? clip.sampleRate / 2,
3996
- gainDb: this.config.gainDb ?? import_core.SPECTROGRAM_DEFAULTS.gainDb,
3997
- rangeDb: this.config.rangeDb ?? import_core.SPECTROGRAM_DEFAULTS.rangeDb,
4186
+ gainDb: this.config.gainDb ?? import_core3.SPECTROGRAM_DEFAULTS.gainDb,
4187
+ rangeDb: this.config.rangeDb ?? import_core3.SPECTROGRAM_DEFAULTS.rangeDb,
3998
4188
  channelIndex: first.channelIndex
3999
4189
  },
4000
4190
  generation
@@ -4002,7 +4192,7 @@ var SpectrogramOrchestrator = class extends EventTarget {
4002
4192
  }
4003
4193
  async renderRemainingViaIdle(canvases, generation, viewport) {
4004
4194
  if (canvases.length === 0) return;
4005
- const groups = groupContiguousChunks(canvases);
4195
+ const groups = groupRenderableChunks(canvases);
4006
4196
  for (const group of groups) {
4007
4197
  if (this.generation !== generation || this.disposed) return;
4008
4198
  await this.yieldUntilIdle();
@@ -4038,12 +4228,16 @@ function viewportsEqual(a, b) {
4038
4228
  SpectrogramAbortError,
4039
4229
  SpectrogramOrchestrator,
4040
4230
  classifyViewport,
4231
+ computePaddedFftRange,
4041
4232
  computeSpectrogram,
4042
4233
  computeSpectrogramMono,
4043
4234
  createSpectrogramWorker,
4044
4235
  createSpectrogramWorkerPool,
4045
4236
  getColorMap,
4046
4237
  getFrequencyScale,
4047
- groupContiguousChunks
4238
+ groupContiguousChunks,
4239
+ groupRenderableChunks,
4240
+ pixelColumnToFrame,
4241
+ pixelRowToBin
4048
4242
  });
4049
4243
  //# sourceMappingURL=index.js.map