@schmooky/zvuk 1.5.0 → 1.7.0

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.ts CHANGED
@@ -17,6 +17,20 @@ interface DecodeAttempt {
17
17
  readonly url: string;
18
18
  readonly cause: unknown;
19
19
  }
20
+ interface PreloadFailure {
21
+ readonly name: string;
22
+ readonly cause: unknown;
23
+ }
24
+ /**
25
+ * Thrown by `engine.preload(...)` when one or more items in the batch fail.
26
+ * Other items in the batch still complete; this only fires after every item
27
+ * has settled, so a single broken asset doesn't short-circuit the rest of a
28
+ * loading screen.
29
+ */
30
+ declare class PreloadError extends ZvukError {
31
+ readonly failures: readonly PreloadFailure[];
32
+ constructor(failures: readonly PreloadFailure[]);
33
+ }
20
34
  /**
21
35
  * Thrown when every URL in a fallback list fails to load. Subclass of
22
36
  * DecodeError so existing `catch (e instanceof DecodeError)` paths still
@@ -77,6 +91,23 @@ declare class Compressor implements FxInsert {
77
91
  }
78
92
 
79
93
  type FadeCurve = 'linear' | 'equal-power' | 'easeIn' | 'easeOut' | 'easeInOut';
94
+ /**
95
+ * Live amplitude readout, returned by `voice.level()` and `bus.meter()`.
96
+ * Values are linear (0..1). Convert to dB with `20 * log10(value)`.
97
+ *
98
+ * - `rms` — root-mean-square over the most recent ~10 ms window. Smooth,
99
+ * matches what a VU meter shows.
100
+ * - `peak` — maximum absolute sample in the same window. Fast-moving,
101
+ * matches what a peak meter / clip indicator shows.
102
+ *
103
+ * Both numbers come from a single AnalyserNode read; calling `level()` more
104
+ * than ~60 Hz is wasted work because the underlying time-domain buffer
105
+ * doesn't refresh faster than the audio thread fills it.
106
+ */
107
+ interface AudioLevel {
108
+ rms: number;
109
+ peak: number;
110
+ }
80
111
  interface ConcurrencyConfig {
81
112
  /** Max simultaneous voices on this bus. */
82
113
  max: number;
@@ -317,6 +348,50 @@ interface LoadSoundOptions {
317
348
  */
318
349
  normalize?: boolean | LoudnessOptions$1;
319
350
  }
351
+ /**
352
+ * One entry in a `engine.preload(...)` batch. Mirrors `engine.loadSound`'s
353
+ * signature so callers can hand the same data to either path.
354
+ */
355
+ interface PreloadItem {
356
+ /** Sound name, registered on `engine.sound(name)` after preload completes. */
357
+ name: string;
358
+ /** URL or codec ladder — same shape as `engine.loadSound`. */
359
+ url: string | readonly string[];
360
+ /** Per-item options (bus, normalize, etc.). Forwarded to `loadSound`. */
361
+ options?: LoadSoundOptions;
362
+ }
363
+ interface PreloadProgressEvent {
364
+ /** Name of the item that just completed (success or failure). */
365
+ readonly name: string;
366
+ /** Outcome — `'loaded'` on decode success, `'failed'` otherwise. */
367
+ readonly status: 'loaded' | 'failed';
368
+ /** Error attached when `status === 'failed'`. */
369
+ readonly error?: unknown;
370
+ /** Items settled so far (loaded + failed). */
371
+ readonly completed: number;
372
+ /** Total items in the batch. */
373
+ readonly total: number;
374
+ }
375
+ interface PreloadOptions {
376
+ /**
377
+ * Cancels the whole preload. In-flight fetches receive the abort; pending
378
+ * items aren't started. The promise rejects with the signal's abort reason.
379
+ */
380
+ signal?: AbortSignal;
381
+ /**
382
+ * Maximum concurrent loads. Default 4 — chosen for balance with browser
383
+ * connection limits (typically 6 per host) so the rest of the page's
384
+ * fetches don't starve. Lower for cheap mobile data plans, higher when
385
+ * you control the host and want to saturate.
386
+ */
387
+ concurrency?: number;
388
+ /**
389
+ * Fires once per item as it settles. Use this to drive a loading-screen
390
+ * progress bar. The event is cumulative — `event.completed / event.total`
391
+ * is a fraction in [0..1].
392
+ */
393
+ onProgress?: (event: PreloadProgressEvent) => void;
394
+ }
320
395
 
321
396
  /**
322
397
  * PannerNode wrapper. Inserted between a Voice and its Bus when a play call
@@ -390,6 +465,8 @@ declare class Voice {
390
465
  private crossfadeRegionLen;
391
466
  private crossfadeChain;
392
467
  private crossfadeArmTimer;
468
+ private levelAnalyser;
469
+ private levelBuf;
393
470
  static nextId: number;
394
471
  constructor(deps: VoiceDeps);
395
472
  private shouldUseLoopCrossfade;
@@ -428,6 +505,13 @@ declare class Voice {
428
505
  get playbackRate(): number;
429
506
  /** The Spatializer attached to this voice (if any). Use for live setPan/setPosition. */
430
507
  get spatializer(): Spatializer | undefined;
508
+ /**
509
+ * Live amplitude readout. Returns `{ rms, peak }` as linear values in
510
+ * [0..1]. The first call lazily attaches an AnalyserNode to the voice's
511
+ * gain stage; subsequent calls reuse it. Returns zeros once the voice has
512
+ * finished.
513
+ */
514
+ level(): AudioLevel;
431
515
  /** Async iterator of lifecycle cues — yields started, optional paused, ended. */
432
516
  cues(): AsyncIterableIterator<VoiceCue>;
433
517
  private finish;
@@ -477,6 +561,8 @@ declare class Bus {
477
561
  private _concurrency;
478
562
  private _voices;
479
563
  private _fxChain;
564
+ private _meterAnalyser;
565
+ private _meterBuf;
480
566
  constructor(ctx: AudioContext, name: string, config?: BusConfig);
481
567
  get level(): number;
482
568
  set level(v: number);
@@ -506,6 +592,16 @@ declare class Bus {
506
592
  addFx(fx: FxInsert): void;
507
593
  removeFx(fx: FxInsert): void;
508
594
  fx(): readonly FxInsert[];
595
+ /**
596
+ * Live amplitude readout on the bus output. Returns `{ rms, peak }` as
597
+ * linear values in [0..1]. The first call lazily attaches an AnalyserNode
598
+ * as a passive sibling of `bus.output → master.input`; subsequent calls
599
+ * reuse it.
600
+ *
601
+ * Use this to drive a mixer-dashboard VU meter, drive automation that
602
+ * reacts to overall bus level, or implement custom voice-stealing rules.
603
+ */
604
+ meter(): AudioLevel;
509
605
  private rewireFxChain;
510
606
  private rampOutput;
511
607
  private ramp;
@@ -870,6 +966,22 @@ interface Engine {
870
966
  * `string` URL, or `undefined`/`null` to fall through to the URL list.
871
967
  */
872
968
  loadSound(name: string, url: string | readonly string[], options?: LoadSoundOptions): Promise<Sound>;
969
+ /**
970
+ * Bulk-load a batch of sounds with a shared progress reporter. Use this
971
+ * to drive a loading screen — the `onProgress` callback fires once per
972
+ * item as it settles, and the returned promise resolves when every item
973
+ * has either succeeded or failed.
974
+ *
975
+ * If any items fail, the promise rejects with `PreloadError` after every
976
+ * item has settled (a single broken asset doesn't short-circuit the rest
977
+ * of the screen). On success the items are registered as if you'd called
978
+ * `engine.loadSound(...)` for each.
979
+ *
980
+ * Concurrency is capped (default 4) so the rest of the page's fetches
981
+ * aren't starved by a 100-asset preload competing for the browser's
982
+ * per-host connection budget.
983
+ */
984
+ preload(items: readonly PreloadItem[], options?: PreloadOptions): Promise<void>;
873
985
  /** Register a Sound from an AudioBuffer you constructed yourself (procedural, custom-decoded, time-stretched). */
874
986
  createSound(name: string, buffer: AudioBuffer, options?: {
875
987
  bus?: string;
@@ -1019,4 +1131,4 @@ type NormalizeFlag = boolean | LoudnessOptions;
1019
1131
  declare function applyLoudnessNormalization(buffer: AudioBuffer, flag: NormalizeFlag): AudioBuffer;
1020
1132
  declare function computeNormalizationGain(buffer: AudioBuffer, opts: Required<LoudnessOptions>): number;
1021
1133
 
1022
- export { AggregateDecodeError, type ApplyOptions, type AssetResolver, type AudioMimeType, Bus, type BusConfig, BusNotFoundError, Compressor, type CompressorConfig, type ConcurrencyConfig, type CrossfadeOptions, type DecodeAttempt, DecodeError, Ducker, type DuckerConfig, type Engine, EngineClosedError, type EngineConfig, type EngineState, type FadeCurve, type FadeOptions, Filter, type FilterConfig, type FilterKind, type FxInsert, type LoadSoundOptions, type LoudnessOptions, Master, type MasterConfig, type MasterLimiterConfig, type NormalizeFlag, Parameter, type ParameterCurve, type PlayOptions, type ResolveAssetContext, type ResolvedAsset, Reverb, type ReverbConfig, type SidechainConfig, Snapshot, type SnapshotState, Sound, SoundNotFoundError, type SpatialOptions, Spatializer, Sprite, type SpriteMap, type SpriteRegion, type SpriteRegionPlayOptions, type StopOptions, StreamSound, StretchProcessor, type StretchWorkletNode, type StretchWorkletOptions, type TickSource, Voice, type VoiceDefaults, type VoiceJitter, ZvukError, applyLoudnessNormalization, canPlay, computeNormalizationGain, createEngine, createStretchWorkletNode, ensureStretchWorklet, mimeForUrl, pickSource, pickSourceOrder };
1134
+ export { AggregateDecodeError, type ApplyOptions, type AssetResolver, type AudioLevel, type AudioMimeType, Bus, type BusConfig, BusNotFoundError, Compressor, type CompressorConfig, type ConcurrencyConfig, type CrossfadeOptions, type DecodeAttempt, DecodeError, Ducker, type DuckerConfig, type Engine, EngineClosedError, type EngineConfig, type EngineState, type FadeCurve, type FadeOptions, Filter, type FilterConfig, type FilterKind, type FxInsert, type LoadSoundOptions, type LoudnessOptions, Master, type MasterConfig, type MasterLimiterConfig, type NormalizeFlag, Parameter, type ParameterCurve, type PlayOptions, PreloadError, type PreloadFailure, type PreloadItem, type PreloadOptions, type PreloadProgressEvent, type ResolveAssetContext, type ResolvedAsset, Reverb, type ReverbConfig, type SidechainConfig, Snapshot, type SnapshotState, Sound, SoundNotFoundError, type SpatialOptions, Spatializer, Sprite, type SpriteMap, type SpriteRegion, type SpriteRegionPlayOptions, type StopOptions, StreamSound, StretchProcessor, type StretchWorkletNode, type StretchWorkletOptions, type TickSource, Voice, type VoiceDefaults, type VoiceJitter, ZvukError, applyLoudnessNormalization, canPlay, computeNormalizationGain, createEngine, createStretchWorkletNode, ensureStretchWorklet, mimeForUrl, pickSource, pickSourceOrder };
package/dist/index.js CHANGED
@@ -29,6 +29,16 @@ var DecodeError = class extends ZvukError {
29
29
  this.name = "DecodeError";
30
30
  }
31
31
  };
32
+ var PreloadError = class extends ZvukError {
33
+ failures;
34
+ constructor(failures) {
35
+ const summary = failures.map((f) => ` - ${f.name}: ${f.cause instanceof Error ? f.cause.message : String(f.cause)}`).join("\n");
36
+ super(`Failed to preload ${failures.length} item(s):
37
+ ${summary}`);
38
+ this.name = "PreloadError";
39
+ this.failures = failures;
40
+ }
41
+ };
32
42
  var AggregateDecodeError = class extends DecodeError {
33
43
  attempts;
34
44
  constructor(urls, attempts) {
@@ -612,6 +622,10 @@ var Bus = class {
612
622
  _concurrency;
613
623
  _voices = /* @__PURE__ */ new Set();
614
624
  _fxChain = [];
625
+ // Lazy meter tap. Connected as a passive sibling of bus.output → master.input
626
+ // so the audio path is unchanged.
627
+ _meterAnalyser = null;
628
+ _meterBuf = null;
615
629
  constructor(ctx, name, config = {}) {
616
630
  this.ctx = ctx;
617
631
  this.name = name;
@@ -708,6 +722,35 @@ var Bus = class {
708
722
  fx() {
709
723
  return this._fxChain;
710
724
  }
725
+ /**
726
+ * Live amplitude readout on the bus output. Returns `{ rms, peak }` as
727
+ * linear values in [0..1]. The first call lazily attaches an AnalyserNode
728
+ * as a passive sibling of `bus.output → master.input`; subsequent calls
729
+ * reuse it.
730
+ *
731
+ * Use this to drive a mixer-dashboard VU meter, drive automation that
732
+ * reacts to overall bus level, or implement custom voice-stealing rules.
733
+ */
734
+ meter() {
735
+ if (!this._meterAnalyser) {
736
+ const a = this.ctx.createAnalyser();
737
+ a.fftSize = 1024;
738
+ this.output.connect(a);
739
+ this._meterAnalyser = a;
740
+ this._meterBuf = new Float32Array(a.fftSize);
741
+ }
742
+ const buf = this._meterBuf;
743
+ this._meterAnalyser.getFloatTimeDomainData(buf);
744
+ let sumSq = 0;
745
+ let peak = 0;
746
+ for (let i = 0; i < buf.length; i++) {
747
+ const s = buf[i] ?? 0;
748
+ sumSq += s * s;
749
+ const a = Math.abs(s);
750
+ if (a > peak) peak = a;
751
+ }
752
+ return { rms: Math.sqrt(sumSq / buf.length), peak };
753
+ }
711
754
  rewireFxChain() {
712
755
  try {
713
756
  this.fxInput.disconnect();
@@ -735,8 +778,11 @@ var Bus = class {
735
778
  this.input.disconnect();
736
779
  this.fxInput.disconnect();
737
780
  this.output.disconnect();
781
+ this._meterAnalyser?.disconnect();
738
782
  } catch {
739
783
  }
784
+ this._meterAnalyser = null;
785
+ this._meterBuf = null;
740
786
  }
741
787
  };
742
788
  function clamp01(v) {
@@ -747,17 +793,10 @@ function wait(seconds) {
747
793
  if (seconds <= 0) return Promise.resolve();
748
794
  return new Promise((res) => setTimeout(res, seconds * 1e3));
749
795
  }
750
- var warnedQuietest = false;
751
796
  function pickVictim(voices, strategy, newVoice) {
752
- let effective = strategy;
753
- if (effective === "quietest") {
754
- if (!warnedQuietest) {
755
- warnedQuietest = true;
756
- console.warn(
757
- "[zvuk] concurrency.steal: 'quietest' currently falls back to 'oldest' \u2014 per-voice level metering ships in a follow-up release. Use 'lowest-priority' if you need explicit control today."
758
- );
759
- }
760
- effective = "oldest";
797
+ const rmsCache = strategy === "quietest" ? /* @__PURE__ */ new Map() : null;
798
+ if (rmsCache) {
799
+ for (const v of voices) if (v !== newVoice) rmsCache.set(v, v.level().rms);
761
800
  }
762
801
  let victim = null;
763
802
  for (const v of voices) {
@@ -766,13 +805,19 @@ function pickVictim(voices, strategy, newVoice) {
766
805
  victim = v;
767
806
  continue;
768
807
  }
769
- switch (effective) {
808
+ switch (strategy) {
770
809
  case "oldest":
771
810
  if (v.startedAt < victim.startedAt) victim = v;
772
811
  break;
773
812
  case "lowest-priority":
774
813
  if (v.priority < victim.priority) victim = v;
775
814
  break;
815
+ case "quietest": {
816
+ const a = rmsCache?.get(v) ?? 0;
817
+ const b = rmsCache?.get(victim) ?? 0;
818
+ if (a < b) victim = v;
819
+ break;
820
+ }
776
821
  }
777
822
  }
778
823
  return victim;
@@ -1273,6 +1318,12 @@ var Voice = class _Voice {
1273
1318
  crossfadeRegionLen = 0;
1274
1319
  crossfadeChain = [];
1275
1320
  crossfadeArmTimer = null;
1321
+ // Lazily-allocated meter tap. Created on first level() read; kept alive
1322
+ // until finish(). The tap connects voice gain → analyser as a sibling of
1323
+ // gain → destination, so the audio path is unchanged and the analyser is
1324
+ // a passive read-only observer.
1325
+ levelAnalyser = null;
1326
+ levelBuf = null;
1276
1327
  static nextId = 1;
1277
1328
  constructor(deps) {
1278
1329
  const { ctx, buffer, destination, options } = deps;
@@ -1486,6 +1537,33 @@ var Voice = class _Voice {
1486
1537
  get spatializer() {
1487
1538
  return this._spatializer;
1488
1539
  }
1540
+ /**
1541
+ * Live amplitude readout. Returns `{ rms, peak }` as linear values in
1542
+ * [0..1]. The first call lazily attaches an AnalyserNode to the voice's
1543
+ * gain stage; subsequent calls reuse it. Returns zeros once the voice has
1544
+ * finished.
1545
+ */
1546
+ level() {
1547
+ if (this.done) return { rms: 0, peak: 0 };
1548
+ if (!this.levelAnalyser) {
1549
+ const a = this.ctx.createAnalyser();
1550
+ a.fftSize = 512;
1551
+ this.gain.connect(a);
1552
+ this.levelAnalyser = a;
1553
+ this.levelBuf = new Float32Array(a.fftSize);
1554
+ }
1555
+ const buf = this.levelBuf;
1556
+ this.levelAnalyser.getFloatTimeDomainData(buf);
1557
+ let sumSq = 0;
1558
+ let peak = 0;
1559
+ for (let i = 0; i < buf.length; i++) {
1560
+ const s = buf[i] ?? 0;
1561
+ sumSq += s * s;
1562
+ const a = Math.abs(s);
1563
+ if (a > peak) peak = a;
1564
+ }
1565
+ return { rms: Math.sqrt(sumSq / buf.length), peak };
1566
+ }
1489
1567
  /** Async iterator of lifecycle cues — yields started, optional paused, ended. */
1490
1568
  async *cues() {
1491
1569
  const queue = [];
@@ -1535,9 +1613,12 @@ var Voice = class _Voice {
1535
1613
  try {
1536
1614
  for (const src of this.activeSources()) src.disconnect();
1537
1615
  for (const e of this.crossfadeChain) e.gain.disconnect();
1616
+ this.levelAnalyser?.disconnect();
1538
1617
  this.gain.disconnect();
1539
1618
  } catch {
1540
1619
  }
1620
+ this.levelAnalyser = null;
1621
+ this.levelBuf = null;
1541
1622
  this.crossfadeChain = [];
1542
1623
  this.emit(reason);
1543
1624
  this.resolveEnded();
@@ -2107,6 +2188,47 @@ var EngineImpl = class {
2107
2188
  const urls = typeof url === "string" ? [url] : pickSourceOrder(url);
2108
2189
  return await this.decoder.loadFirst(urls, decodeOpts);
2109
2190
  }
2191
+ async preload(items, options = {}) {
2192
+ if (this.host.state === "closed") throw new EngineClosedError();
2193
+ if (items.length === 0) return;
2194
+ const concurrency = Math.max(1, options.concurrency ?? 4);
2195
+ const onProgress = options.onProgress;
2196
+ const batchSignal = options.signal;
2197
+ const total = items.length;
2198
+ let completed = 0;
2199
+ const failures = [];
2200
+ let nextIdx = 0;
2201
+ const workerCount = Math.min(concurrency, total);
2202
+ const workers = [];
2203
+ for (let w = 0; w < workerCount; w++) {
2204
+ workers.push(
2205
+ (async () => {
2206
+ while (true) {
2207
+ const idx = nextIdx++;
2208
+ if (idx >= total) return;
2209
+ if (batchSignal?.aborted) {
2210
+ throw batchSignal.reason ?? new DOMException("preload aborted", "AbortError");
2211
+ }
2212
+ const item = items[idx];
2213
+ const itemSignal = combineSignals(batchSignal, item.options?.signal);
2214
+ const opts = { ...item.options ?? {}, signal: itemSignal };
2215
+ try {
2216
+ await this.loadSound(item.name, item.url, opts);
2217
+ completed++;
2218
+ onProgress?.({ name: item.name, status: "loaded", completed, total });
2219
+ } catch (e) {
2220
+ if (e.name === "AbortError") throw e;
2221
+ completed++;
2222
+ failures.push({ name: item.name, cause: e });
2223
+ onProgress?.({ name: item.name, status: "failed", error: e, completed, total });
2224
+ }
2225
+ }
2226
+ })()
2227
+ );
2228
+ }
2229
+ await Promise.all(workers);
2230
+ if (failures.length > 0) throw new PreloadError(failures);
2231
+ }
2110
2232
  async loadSprite(name, url, regions, options = {}) {
2111
2233
  const sound = await this.loadSound(`__sprite:${name}`, url, options);
2112
2234
  const sprite = new Sprite(name, sound, regions);
@@ -2296,6 +2418,18 @@ function suggest(missing, candidates) {
2296
2418
  }
2297
2419
  return missing;
2298
2420
  }
2421
+ function combineSignals(a, b) {
2422
+ if (!a) return b;
2423
+ if (!b) return a;
2424
+ if (a.aborted) return a;
2425
+ if (b.aborted) return b;
2426
+ const ac = new AbortController();
2427
+ const onAbortA = () => ac.abort(a.reason);
2428
+ const onAbortB = () => ac.abort(b.reason);
2429
+ a.addEventListener("abort", onAbortA, { once: true });
2430
+ b.addEventListener("abort", onAbortB, { once: true });
2431
+ return ac.signal;
2432
+ }
2299
2433
  function levenshtein(a, b) {
2300
2434
  if (a === b) return 0;
2301
2435
  if (a.length === 0) return b.length;
@@ -2314,6 +2448,6 @@ function levenshtein(a, b) {
2314
2448
  return prev[b.length];
2315
2449
  }
2316
2450
 
2317
- export { AggregateDecodeError, Bus, BusNotFoundError, Compressor, DecodeError, Ducker, EngineClosedError, Filter, Master, Parameter, Reverb, Snapshot, Sound, SoundNotFoundError, Spatializer, Sprite, StreamSound, StretchProcessor, Voice, ZvukError, applyLoudnessNormalization, canPlay, computeNormalizationGain, createEngine, createStretchWorkletNode, ensureStretchWorklet, mimeForUrl, pickSource, pickSourceOrder };
2451
+ export { AggregateDecodeError, Bus, BusNotFoundError, Compressor, DecodeError, Ducker, EngineClosedError, Filter, Master, Parameter, PreloadError, Reverb, Snapshot, Sound, SoundNotFoundError, Spatializer, Sprite, StreamSound, StretchProcessor, Voice, ZvukError, applyLoudnessNormalization, canPlay, computeNormalizationGain, createEngine, createStretchWorkletNode, ensureStretchWorklet, mimeForUrl, pickSource, pickSourceOrder };
2318
2452
  //# sourceMappingURL=index.js.map
2319
2453
  //# sourceMappingURL=index.js.map