@dawcore/spectrogram 0.0.9-next.1 → 0.0.9-next.11

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.d.mts CHANGED
@@ -125,7 +125,8 @@ declare function computePaddedFftRange({ chunks, fftSize, offsetSamples, duratio
125
125
  };
126
126
 
127
127
  /**
128
- * Error thrown when a spectrogram computation is aborted due to a generation change.
128
+ * Error thrown when a spectrogram computation is aborted: its generation was
129
+ * superseded, or its clip's audio was replaced or unregistered while it ran (#928).
129
130
  * Use `instanceof SpectrogramAbortError` instead of string matching on error messages.
130
131
  */
131
132
  declare class SpectrogramAbortError extends Error {
@@ -143,7 +144,13 @@ interface SpectrogramWorkerFFTParams {
143
144
  start: number;
144
145
  end: number;
145
146
  };
146
- /** If set, compute only this channel index (used by worker pool). */
147
+ /**
148
+ * If set, compute only the channel at this index of the arrays the worker
149
+ * has for the clip. A worker with one array computes that array whatever
150
+ * this says. The pool gives each worker its one channel at index 0, or
151
+ * (worker 0, registered audio) every channel, and its multi-channel fan-out
152
+ * asks for index 0 (a mono request sends no filter) (#925).
153
+ */
147
154
  channelFilter?: number;
148
155
  }
149
156
  interface SpectrogramWorkerRenderChunksParams {
@@ -178,6 +185,15 @@ interface SpectrogramWorkerApi {
178
185
  unregisterCanvas(canvasId: string): void;
179
186
  registerAudioData(clipId: string, channelDataArrays: Float32Array[], sampleRate: number): void;
180
187
  unregisterAudioData(clipId: string): void;
188
+ /**
189
+ * The ids whose audio is registered now: registered and not unregistered
190
+ * since. An id is whatever the caller registered the audio under (a clip id,
191
+ * or a key per AudioBuffer, as the React provider uses). Empty once
192
+ * terminated; a register after that is ignored. A new array on every call.
193
+ * A caller that pre-registers audio asks this instead of keeping its own
194
+ * list, which would outlive a terminated worker (#821).
195
+ */
196
+ registeredAudioClipIds(): string[];
181
197
  terminate(): void;
182
198
  }
183
199
  /**
@@ -325,8 +341,15 @@ declare class SpectrogramOrchestrator extends EventTarget {
325
341
  protected scheduleRender(): void;
326
342
  protected runRenderLoop(): Promise<void>;
327
343
  protected runRender(generation: number): Promise<void>;
328
- protected renderTier(canvases: CanvasEntry[], generation: number, viewport: ViewportState): Promise<void>;
329
- protected renderGroup(group: CanvasEntry[], generation: number, viewport: ViewportState): Promise<void>;
344
+ /** Renders the tier's groups; false when a group waits for a render already scheduled. */
345
+ protected renderTier(canvases: CanvasEntry[], generation: number, viewport: ViewportState): Promise<boolean>;
346
+ /**
347
+ * Renders one group. Returns false when its computation was dropped and
348
+ * another pass is queued (registerClip queues one for a clip registered again
349
+ * mid-computation that still has canvases, #928): that pass draws it. True
350
+ * otherwise, also when there is nothing to draw or nothing will draw it.
351
+ */
352
+ protected renderGroup(group: CanvasEntry[], generation: number, viewport: ViewportState): Promise<boolean>;
330
353
  protected renderGroupOnce(group: CanvasEntry[], generation: number, viewport: ViewportState, clip: ClipEntry): Promise<void>;
331
354
  protected renderRemainingViaIdle(canvases: CanvasEntry[], generation: number, viewport: ViewportState): Promise<void>;
332
355
  protected yieldUntilIdle(): Promise<void>;
package/dist/index.d.ts CHANGED
@@ -125,7 +125,8 @@ declare function computePaddedFftRange({ chunks, fftSize, offsetSamples, duratio
125
125
  };
126
126
 
127
127
  /**
128
- * Error thrown when a spectrogram computation is aborted due to a generation change.
128
+ * Error thrown when a spectrogram computation is aborted: its generation was
129
+ * superseded, or its clip's audio was replaced or unregistered while it ran (#928).
129
130
  * Use `instanceof SpectrogramAbortError` instead of string matching on error messages.
130
131
  */
131
132
  declare class SpectrogramAbortError extends Error {
@@ -143,7 +144,13 @@ interface SpectrogramWorkerFFTParams {
143
144
  start: number;
144
145
  end: number;
145
146
  };
146
- /** If set, compute only this channel index (used by worker pool). */
147
+ /**
148
+ * If set, compute only the channel at this index of the arrays the worker
149
+ * has for the clip. A worker with one array computes that array whatever
150
+ * this says. The pool gives each worker its one channel at index 0, or
151
+ * (worker 0, registered audio) every channel, and its multi-channel fan-out
152
+ * asks for index 0 (a mono request sends no filter) (#925).
153
+ */
147
154
  channelFilter?: number;
148
155
  }
149
156
  interface SpectrogramWorkerRenderChunksParams {
@@ -178,6 +185,15 @@ interface SpectrogramWorkerApi {
178
185
  unregisterCanvas(canvasId: string): void;
179
186
  registerAudioData(clipId: string, channelDataArrays: Float32Array[], sampleRate: number): void;
180
187
  unregisterAudioData(clipId: string): void;
188
+ /**
189
+ * The ids whose audio is registered now: registered and not unregistered
190
+ * since. An id is whatever the caller registered the audio under (a clip id,
191
+ * or a key per AudioBuffer, as the React provider uses). Empty once
192
+ * terminated; a register after that is ignored. A new array on every call.
193
+ * A caller that pre-registers audio asks this instead of keeping its own
194
+ * list, which would outlive a terminated worker (#821).
195
+ */
196
+ registeredAudioClipIds(): string[];
181
197
  terminate(): void;
182
198
  }
183
199
  /**
@@ -325,8 +341,15 @@ declare class SpectrogramOrchestrator extends EventTarget {
325
341
  protected scheduleRender(): void;
326
342
  protected runRenderLoop(): Promise<void>;
327
343
  protected runRender(generation: number): Promise<void>;
328
- protected renderTier(canvases: CanvasEntry[], generation: number, viewport: ViewportState): Promise<void>;
329
- protected renderGroup(group: CanvasEntry[], generation: number, viewport: ViewportState): Promise<void>;
344
+ /** Renders the tier's groups; false when a group waits for a render already scheduled. */
345
+ protected renderTier(canvases: CanvasEntry[], generation: number, viewport: ViewportState): Promise<boolean>;
346
+ /**
347
+ * Renders one group. Returns false when its computation was dropped and
348
+ * another pass is queued (registerClip queues one for a clip registered again
349
+ * mid-computation that still has canvases, #928): that pass draws it. True
350
+ * otherwise, also when there is nothing to draw or nothing will draw it.
351
+ */
352
+ protected renderGroup(group: CanvasEntry[], generation: number, viewport: ViewportState): Promise<boolean>;
330
353
  protected renderGroupOnce(group: CanvasEntry[], generation: number, viewport: ViewportState, clip: ClipEntry): Promise<void>;
331
354
  protected renderRemainingViaIdle(canvases: CanvasEntry[], generation: number, viewport: ViewportState): Promise<void>;
332
355
  protected yieldUntilIdle(): Promise<void>;
package/dist/index.js CHANGED
@@ -3607,6 +3607,7 @@ function createSpectrogramWorker(worker) {
3607
3607
  worker.postMessage({ type: "unregister-canvas", canvasId });
3608
3608
  },
3609
3609
  registerAudioData(clipId, channelDataArrays, sampleRate) {
3610
+ if (terminated) return;
3610
3611
  const transferableArrays = channelDataArrays.map((arr) => arr.slice());
3611
3612
  const transferables = transferableArrays.map((arr) => arr.buffer);
3612
3613
  worker.postMessage(
@@ -3616,11 +3617,16 @@ function createSpectrogramWorker(worker) {
3616
3617
  registeredClipIds.add(clipId);
3617
3618
  },
3618
3619
  unregisterAudioData(clipId) {
3620
+ if (terminated) return;
3619
3621
  worker.postMessage({ type: "unregister-audio-data", clipId });
3620
3622
  registeredClipIds.delete(clipId);
3621
3623
  },
3624
+ registeredAudioClipIds() {
3625
+ return [...registeredClipIds];
3626
+ },
3622
3627
  terminate() {
3623
3628
  terminated = true;
3629
+ registeredClipIds.clear();
3624
3630
  worker.terminate();
3625
3631
  for (const [, entry] of pending) {
3626
3632
  entry.reject(new Error("Worker terminated"));
@@ -3645,6 +3651,13 @@ function parseChannelFromCanvasId(canvasId) {
3645
3651
  function defaultPoolSize() {
3646
3652
  return 2;
3647
3653
  }
3654
+ function channelsForWorker(channelDataArrays, workerIndex) {
3655
+ if (workerIndex === 0 || channelDataArrays.length === 0) return channelDataArrays;
3656
+ return [channelDataArrays[workerIndex]];
3657
+ }
3658
+ function payloadForChannel(channelDataArrays, channelIndex) {
3659
+ return channelDataArrays.length === 0 ? [] : [channelDataArrays[channelIndex]];
3660
+ }
3648
3661
  var MAX_POOL_CHANNELS = 32;
3649
3662
  function createSpectrogramWorkerPool(createWorker, poolSize = defaultPoolSize()) {
3650
3663
  if (poolSize > MAX_POOL_CHANNELS) {
@@ -3694,7 +3707,11 @@ function createSpectrogramWorkerPool(createWorker, poolSize = defaultPoolSize())
3694
3707
  const workerIndex = workers.length;
3695
3708
  for (const [clipId, entry] of registeredAudio) {
3696
3709
  if (entry.channelDataArrays.length > workerIndex) {
3697
- w.registerAudioData(clipId, entry.channelDataArrays, entry.sampleRate);
3710
+ w.registerAudioData(
3711
+ clipId,
3712
+ channelsForWorker(entry.channelDataArrays, workerIndex),
3713
+ entry.sampleRate
3714
+ );
3698
3715
  }
3699
3716
  }
3700
3717
  workers.push(w);
@@ -3722,7 +3739,14 @@ function createSpectrogramWorkerPool(createWorker, poolSize = defaultPoolSize())
3722
3739
  }
3723
3740
  const promises = Array.from(
3724
3741
  { length: channelCount },
3725
- (_, i) => ensureWorkerForChannel(i).computeFFT({ ...params, channelFilter: i }, generation)
3742
+ (_, i) => ensureWorkerForChannel(i).computeFFT(
3743
+ {
3744
+ ...params,
3745
+ channelDataArrays: payloadForChannel(params.channelDataArrays, i),
3746
+ channelFilter: 0
3747
+ },
3748
+ generation
3749
+ )
3726
3750
  );
3727
3751
  const settled = await Promise.allSettled(promises);
3728
3752
  const failures = settled.filter((s) => s.status === "rejected");
@@ -3766,10 +3790,14 @@ function createSpectrogramWorkerPool(createWorker, poolSize = defaultPoolSize())
3766
3790
  },
3767
3791
  registerAudioData(clipId, channelDataArrays, sampleRate) {
3768
3792
  if (terminated) return;
3793
+ const previousCount = registeredAudio.get(clipId)?.channelDataArrays.length ?? 0;
3794
+ for (let i = channelDataArrays.length; i < Math.min(previousCount, workers.length); i++) {
3795
+ workers[i].unregisterAudioData(clipId);
3796
+ }
3769
3797
  registeredAudio.set(clipId, { channelDataArrays, sampleRate });
3770
3798
  const relevantWorkers = Math.min(channelDataArrays.length, workers.length);
3771
3799
  for (let i = 0; i < relevantWorkers; i++) {
3772
- workers[i].registerAudioData(clipId, channelDataArrays, sampleRate);
3800
+ workers[i].registerAudioData(clipId, channelsForWorker(channelDataArrays, i), sampleRate);
3773
3801
  }
3774
3802
  },
3775
3803
  unregisterAudioData(clipId) {
@@ -3779,6 +3807,9 @@ function createSpectrogramWorkerPool(createWorker, poolSize = defaultPoolSize())
3779
3807
  w.unregisterAudioData(clipId);
3780
3808
  }
3781
3809
  },
3810
+ registeredAudioClipIds() {
3811
+ return [...registeredAudio.keys()];
3812
+ },
3782
3813
  terminate() {
3783
3814
  terminated = true;
3784
3815
  registeredAudio.clear();
@@ -4084,9 +4115,9 @@ var SpectrogramOrchestrator = class extends EventTarget {
4084
4115
  for (const [trackId, trackCanvases] of canvasesByTrack) {
4085
4116
  try {
4086
4117
  const tiers = classifyViewport(trackCanvases, viewport);
4087
- await this.renderTier(tiers.viewport, generation, viewport);
4118
+ const viewportDrawn = await this.renderTier(tiers.viewport, generation, viewport);
4088
4119
  if (this.generation !== generation || this.disposed) return;
4089
- if (!this.readyDispatched.has(trackId)) {
4120
+ if (viewportDrawn && !this.readyDispatched.has(trackId)) {
4090
4121
  this.readyDispatched.add(trackId);
4091
4122
  this.dispatchEvent(
4092
4123
  new CustomEvent("viewport-ready", { detail: { trackId, generation } })
@@ -4098,7 +4129,7 @@ var SpectrogramOrchestrator = class extends EventTarget {
4098
4129
  } catch (err) {
4099
4130
  if (this.generation !== generation || this.disposed) return;
4100
4131
  if (err instanceof SpectrogramAbortError) {
4101
- return;
4132
+ continue;
4102
4133
  }
4103
4134
  const error = err instanceof Error ? err : new Error(String(err));
4104
4135
  console.warn(
@@ -4112,34 +4143,47 @@ var SpectrogramOrchestrator = class extends EventTarget {
4112
4143
  }
4113
4144
  }
4114
4145
  }
4146
+ /** Renders the tier's groups; false when a group waits for a render already scheduled. */
4115
4147
  async renderTier(canvases, generation, viewport) {
4116
- if (canvases.length === 0) return;
4148
+ let drawn = true;
4149
+ if (canvases.length === 0) return drawn;
4117
4150
  const groups = groupRenderableChunks(canvases);
4118
4151
  for (const group of groups) {
4119
- if (this.generation !== generation || this.disposed) return;
4120
- await this.renderGroup(group, generation, viewport);
4152
+ if (this.generation !== generation || this.disposed) return drawn;
4153
+ if (!await this.renderGroup(group, generation, viewport)) drawn = false;
4121
4154
  }
4155
+ return drawn;
4122
4156
  }
4157
+ /**
4158
+ * Renders one group. Returns false when its computation was dropped and
4159
+ * another pass is queued (registerClip queues one for a clip registered again
4160
+ * mid-computation that still has canvases, #928): that pass draws it. True
4161
+ * otherwise, also when there is nothing to draw or nothing will draw it.
4162
+ */
4123
4163
  async renderGroup(group, generation, viewport) {
4124
- if (group.length === 0) return;
4164
+ if (group.length === 0) return true;
4125
4165
  const first = group[0];
4126
4166
  const clip = this.clips.get(first.clipId);
4127
4167
  if (!clip) {
4128
4168
  console.warn(
4129
4169
  "[dawcore-spectrogram] renderGroup: no clip audio for " + first.clipId + " (canvas " + first.canvasId + ") \u2014 canvas will stay black until registerClip is called"
4130
4170
  );
4131
- return;
4171
+ return true;
4132
4172
  }
4133
4173
  try {
4134
4174
  await this.renderGroupOnce(group, generation, viewport, clip);
4175
+ return true;
4135
4176
  } catch (err) {
4136
4177
  if (this.generation !== generation || this.disposed) throw err;
4178
+ if (err instanceof SpectrogramAbortError) {
4179
+ return !this.renderQueued;
4180
+ }
4137
4181
  if (err instanceof Error && err.message.includes("cache-miss")) {
4138
4182
  console.warn(
4139
4183
  "[dawcore-spectrogram] FFT cache entry evicted between compute and render \u2014 retrying group once"
4140
4184
  );
4141
4185
  await this.renderGroupOnce(group, generation, viewport, clip);
4142
- return;
4186
+ return true;
4143
4187
  }
4144
4188
  throw err;
4145
4189
  }