@schmooky/zvuk 1.13.0 → 1.14.1

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
@@ -1,17 +1,22 @@
1
1
  declare class ZvukError extends Error {
2
- constructor(message: string);
2
+ constructor(message: string, options?: ErrorOptions);
3
3
  }
4
4
  declare class EngineClosedError extends ZvukError {
5
5
  constructor();
6
6
  }
7
7
  declare class BusNotFoundError extends ZvukError {
8
- constructor(name: string);
8
+ constructor(name: string, hint?: string | null);
9
9
  }
10
10
  declare class SoundNotFoundError extends ZvukError {
11
- constructor(name: string);
11
+ constructor(name: string, hint?: string | null);
12
12
  }
13
+ /**
14
+ * A fetch or decode failure for one URL. The underlying failure is kept on
15
+ * `cause` as well as summarised into the message, so a logger that walks
16
+ * the cause chain gets the original stack.
17
+ */
13
18
  declare class DecodeError extends ZvukError {
14
- constructor(url: string, cause: unknown);
19
+ constructor(url: string, cause: unknown, message?: string);
15
20
  }
16
21
  interface DecodeAttempt {
17
22
  readonly url: string;
@@ -135,7 +140,7 @@ interface SendOptions {
135
140
  amount?: number;
136
141
  /**
137
142
  * Tap the source bus's output (post-fader, post-FX) when `true`,
138
- * or input (pre-fader, pre-FX) when `false`. Default `true` — almost
143
+ * or input (pre-fader, pre-FX) when `false`. Default `true`, which is almost
139
144
  * always what you want. Pre-fader sends are mainly useful for
140
145
  * monitoring buses that should hear the dry signal regardless of how
141
146
  * the user has faded the source bus down.
@@ -145,9 +150,9 @@ interface SendOptions {
145
150
  interface MasterLimiterConfig {
146
151
  /** Threshold in dB. Default -1 (just below 0 dBFS). */
147
152
  threshold?: number;
148
- /** Compression ratio. Default 20 (high — limiter-like, but not a true brick wall). */
153
+ /** Compression ratio. Default 20, high enough to be limiter-like without being a brick wall. */
149
154
  ratio?: number;
150
- /** Attack in seconds. Default 0.001 (fast — catches the transient). */
155
+ /** Attack in seconds. Default 0.001, fast enough to catch the transient. */
151
156
  attack?: number;
152
157
  /** Release in seconds. Default 0.05. */
153
158
  release?: number;
@@ -164,7 +169,7 @@ interface MasterConfig {
164
169
  * - `ArrayBuffer` — encoded bytes; zvuk decodes via the engine's AudioContext.
165
170
  * - `string` — a URL; zvuk fetches and decodes via its normal loader (and
166
171
  * the cache).
167
- * - `undefined` / `null` — explicit "I don't have this" — falls through to
172
+ * - `undefined` / `null` — explicit "I don't have this". Falls through to
168
173
  * the URL list passed to `loadSound` (or throws if none was given).
169
174
  */
170
175
  type ResolvedAsset = AudioBuffer | ArrayBuffer | string;
@@ -183,19 +188,19 @@ interface ResolveAssetContext {
183
188
  * so resolvers can mix cached and uncached sounds without branching at the
184
189
  * call site.
185
190
  *
186
- * The resolver runs before any fetch — if it returns a buffer or URL, the
191
+ * The resolver runs before any fetch. If it returns a buffer or URL, the
187
192
  * URL list passed to `loadSound` is only used as the resolution key.
188
193
  */
189
194
  type AssetResolver = (ctx: ResolveAssetContext) => ResolvedAsset | undefined | null | Promise<ResolvedAsset | undefined | null>;
190
195
  /**
191
- * External ticker for driving the scheduler's task dispatch — typically
196
+ * External ticker for driving the scheduler's task dispatch. Typically
192
197
  * a host's existing render loop (Pixi `app.ticker`, GSAP `gsap.ticker`).
193
198
  *
194
199
  * The scheduler subscribes lazily: only while there are pending tasks. When
195
200
  * the queue drains, it unsubscribes so a 60 Hz host loop isn't waking the
196
201
  * scheduler 60 times per second to do nothing.
197
202
  *
198
- * Without a `TickSource`, the scheduler dispatches via `setTimeout` — see
203
+ * Without a `TickSource`, the scheduler dispatches via `setTimeout`. See
199
204
  * the "Runtime timing" guide for trade-offs around browser timer
200
205
  * throttling and tab visibility.
201
206
  *
@@ -228,7 +233,7 @@ interface VoiceDefaults {
228
233
  /**
229
234
  * Default click-free fade-out duration applied by `voice.stop()`, in
230
235
  * seconds. Web Audio cuts source nodes mid-waveform, which produces a
231
- * digital click on non-zero crossings — a tiny linear ramp on the gain
236
+ * digital click on non-zero crossings. A tiny linear ramp on the gain
232
237
  * stage before the source actually stops eliminates that. Default 0.008
233
238
  * (8 ms): inaudible as fade, sufficient as click suppressor.
234
239
  *
@@ -261,7 +266,7 @@ interface EngineConfig<TBusName extends string = string> {
261
266
  latencyHint?: AudioContextLatencyCategory | number;
262
267
  /**
263
268
  * External ticker (e.g. Pixi `app.ticker`, GSAP `gsap.ticker`) that drives
264
- * scheduler dispatch. Without one, the scheduler uses `setTimeout` —
269
+ * scheduler dispatch. Without one, the scheduler uses `setTimeout`,
265
270
  * which browsers throttle to ~1 Hz on hidden tabs. Inject a host ticker
266
271
  * to align dispatch to your render loop and avoid spawning a parallel rAF
267
272
  * loop. See the "Runtime timing" guide for the full trade-off.
@@ -290,12 +295,26 @@ interface EngineConfig<TBusName extends string = string> {
290
295
  * automatically on return. This is also the iOS Safari workaround for
291
296
  * suspension-on-blur.
292
297
  *
293
- * Set to `false` if you want music to keep playing across tab switches —
298
+ * Set to `false` if you want music to keep playing across tab switches:
294
299
  * e.g. background music players where a brief navigation away from the
295
300
  * page shouldn't pause playback. Audio continues running on the Web Audio
296
301
  * thread regardless of tab visibility.
297
302
  */
298
303
  autoPauseOnHidden?: boolean;
304
+ /**
305
+ * Decoded-buffer cache limits. Decoded audio costs 4 bytes per sample per
306
+ * channel, so a few minutes of stereo 48 kHz is tens of megabytes and an
307
+ * entry count says nothing useful about memory.
308
+ *
309
+ * Defaults: 64 MiB, 128 entries. The cache is LRU on both.
310
+ */
311
+ cache?: CacheConfig;
312
+ }
313
+ interface CacheConfig {
314
+ /** Ceiling on decoded bytes held in the cache. Default 64 MiB. */
315
+ maxBytes?: number;
316
+ /** Ceiling on cached entries, applied alongside `maxBytes`. Default 128. */
317
+ maxEntries?: number;
299
318
  }
300
319
  interface FadeOptions {
301
320
  to: number;
@@ -357,7 +376,7 @@ interface SpatialOptions {
357
376
  /**
358
377
  * Occlusion amount (0..1). Drives an internal low-pass filter that
359
378
  * sweeps cutoff from 22050 Hz (transparent) down to ~500 Hz (heavily
360
- * muffled), plus a small gain dip — the standard "behind a wall"
379
+ * muffled), plus a small gain dip. That is the standard "behind a wall"
361
380
  * effect. Independent of distance attenuation; combine via a
362
381
  * `Parameter` if you want one knob to drive both.
363
382
  * 3D only; ignored when `pan` is used.
@@ -369,7 +388,7 @@ interface PlayOptions {
369
388
  volume?: number | VoiceJitter;
370
389
  /**
371
390
  * Fade-in duration (seconds) applied to the voice's gain at start.
372
- * Default 0 (instant). Convenience for "drop in smoothly" — the dual
391
+ * Default 0 (instant). Convenience for "drop in smoothly", the mirror
373
392
  * of the click-free stop fade. Equivalent to playing at `volume: 0`
374
393
  * and immediately calling `voice.fade({ to: volume, duration: fadeIn })`.
375
394
  */
@@ -380,9 +399,9 @@ interface PlayOptions {
380
399
  loop?: boolean;
381
400
  /** Override the default bus for this voice. */
382
401
  bus?: string;
383
- /** Voice priority — higher = more likely to survive stealing. Default 0. */
402
+ /** Voice priority. Higher survives stealing for longer. Default 0. */
384
403
  priority?: number;
385
- /** AbortSignal — voice stops when aborted. */
404
+ /** AbortSignal. The voice stops when it aborts. */
386
405
  signal?: AbortSignal;
387
406
  /** 2D pan or 3D position. Inserts a Spatializer between the voice and its bus. */
388
407
  spatializer?: SpatialOptions;
@@ -397,11 +416,11 @@ interface PlayOptions {
397
416
  /**
398
417
  * Equal-power crossfade duration (seconds) at the loop boundary. When
399
418
  * `loop` is true and this is non-zero, zvuk spawns a parallel buffer
400
- * source at every loop point and ramps between them — masking the click
419
+ * source at every loop point and ramps between them, masking the click
401
420
  * that AudioBufferSourceNode's native loop produces when the region
402
421
  * doesn't end on a zero crossing.
403
422
  *
404
- * Default `0` (off — native hard-cut loop). Cost is one extra
423
+ * Default `0`, meaning off, which leaves the native hard-cut loop. Cost is one extra
405
424
  * AudioBufferSourceNode + GainNode per loop iteration; with default
406
425
  * Web Audio dispatch this is well under 1% CPU per voice.
407
426
  *
@@ -434,7 +453,7 @@ interface LoadSoundOptions {
434
453
  * optional outro tail. Modelled on the Wwise / FMOD pattern every casino
435
454
  * slot, action game, and rhythm game uses for combat/win/menu music.
436
455
  *
437
- * Each part accepts a single URL or a codec ladder — the same shape as
456
+ * Each part accepts a single URL or a codec ladder, the same shape as
438
457
  * `engine.loadSound`'s second argument.
439
458
  */
440
459
  interface MusicParts {
@@ -445,7 +464,7 @@ interface MusicParts {
445
464
  interface MusicLoadOptions extends LoadSoundOptions {
446
465
  /**
447
466
  * Equal-power crossfade (seconds) at the loop boundary. Mirrors
448
- * `PlayOptions.loopCrossfade` — masks the click that would otherwise
467
+ * `PlayOptions.loopCrossfade`. Masks the click that would otherwise
449
468
  * fire if the loop region doesn't end on a zero crossing. Default `0`.
450
469
  */
451
470
  loopCrossfade?: number;
@@ -477,7 +496,7 @@ type MusicState = 'intro' | 'loop' | 'outro' | 'ended';
477
496
  interface PreloadItem {
478
497
  /** Sound name, registered on `engine.sound(name)` after preload completes. */
479
498
  name: string;
480
- /** URL or codec ladder — same shape as `engine.loadSound`. */
499
+ /** URL or codec ladder, the same shape as `engine.loadSound`. */
481
500
  url: string | readonly string[];
482
501
  /** Per-item options (bus, normalize, etc.). Forwarded to `loadSound`. */
483
502
  options?: LoadSoundOptions;
@@ -485,7 +504,7 @@ interface PreloadItem {
485
504
  interface PreloadProgressEvent {
486
505
  /** Name of the item that just completed (success or failure). */
487
506
  readonly name: string;
488
- /** Outcome — `'loaded'` on decode success, `'failed'` otherwise. */
507
+ /** Outcome. `'loaded'` on decode success, `'failed'` otherwise. */
489
508
  readonly status: 'loaded' | 'failed';
490
509
  /** Error attached when `status === 'failed'`. */
491
510
  readonly error?: unknown;
@@ -501,7 +520,7 @@ interface PreloadOptions {
501
520
  */
502
521
  signal?: AbortSignal;
503
522
  /**
504
- * Maximum concurrent loads. Default 4 — chosen for balance with browser
523
+ * Maximum concurrent loads. Default 4, which balances against browser
505
524
  * connection limits (typically 6 per host) so the rest of the page's
506
525
  * fetches don't starve. Lower for cheap mobile data plans, higher when
507
526
  * you control the host and want to saturate.
@@ -509,7 +528,7 @@ interface PreloadOptions {
509
528
  concurrency?: number;
510
529
  /**
511
530
  * Fires once per item as it settles. Use this to drive a loading-screen
512
- * progress bar. The event is cumulative — `event.completed / event.total`
531
+ * progress bar. The event is cumulative, so `event.completed / event.total`
513
532
  * is a fraction in [0..1].
514
533
  */
515
534
  onProgress?: (event: PreloadProgressEvent) => void;
@@ -659,6 +678,18 @@ declare class Voice {
659
678
  * finished.
660
679
  */
661
680
  level(): AudioLevel;
681
+ /**
682
+ * Cheap loudness proxy for voice stealing, in [0..1].
683
+ *
684
+ * `level()` allocates an AnalyserNode and keeps it for the voice's
685
+ * lifetime, so using it to rank 64 candidates left 64 permanent analysers
686
+ * on the graph — and a freshly created analyser reads silence anyway,
687
+ * because its buffer hasn't filled yet. Reuse a tap that already exists;
688
+ * otherwise read the voice's own gain, which costs nothing.
689
+ *
690
+ * @internal
691
+ */
692
+ levelHint(): number;
662
693
  /** Async iterator of lifecycle cues — yields started, optional paused, ended. */
663
694
  cues(): AsyncIterableIterator<VoiceCue>;
664
695
  private finish;
@@ -857,6 +888,11 @@ declare class Ducker implements FxInsert {
857
888
  private rafId;
858
889
  /** Timestamp of the previous tick (ms), for measuring the real frame delta. */
859
890
  private lastTickMs;
891
+ /**
892
+ * Envelope-follower state, 1 = not ducking. It starts at unity: starting
893
+ * at 0 made every freshly-inserted ducker drop its target bus to silence
894
+ * and swell it back over the release time.
895
+ */
860
896
  private envelope;
861
897
  private targetGain;
862
898
  private ctx;
@@ -870,6 +906,17 @@ declare class Ducker implements FxInsert {
870
906
  set bypassed(v: boolean);
871
907
  dispose(): void;
872
908
  private tick;
909
+ /**
910
+ * A hidden tab stops firing rAF, so the envelope freezes wherever it was.
911
+ * Come back to a ducker that was mid-duck and the music stays quiet with
912
+ * nothing driving it back up. Reset to unity on return and let the next
913
+ * few frames re-duck if the source really is still loud.
914
+ */
915
+ private handleVisibility;
916
+ private resetEnvelope;
917
+ private releaseToUnity;
918
+ private startLoop;
919
+ private stopLoop;
873
920
  }
874
921
 
875
922
  type FilterKind = 'lowpass' | 'highpass' | 'bandpass' | 'notch' | 'peaking' | 'allpass';
@@ -1071,7 +1118,19 @@ declare class Parameter {
1071
1118
  }): () => void;
1072
1119
  }
1073
1120
 
1074
- type EngineState = 'cold' | 'unlocking' | 'live' | 'interrupted' | 'closed';
1121
+ /**
1122
+ * Engine lifecycle, mirroring the underlying AudioContext:
1123
+ *
1124
+ * - `cold` — no context yet, or a failed unlock.
1125
+ * - `unlocking` — a resume() is in flight.
1126
+ * - `live` — the context is running.
1127
+ * - `suspended` — the context was paused, normally by `autoPauseOnHidden`
1128
+ * on tab hide. Recoverable with `unlock()`.
1129
+ * - `interrupted` — iOS took the audio session (phone call, Siri).
1130
+ * `resume()` does not recover from this; the OS has to hand it back.
1131
+ * - `closed` — terminal.
1132
+ */
1133
+ type EngineState = 'cold' | 'unlocking' | 'live' | 'suspended' | 'interrupted' | 'closed';
1075
1134
 
1076
1135
  interface MusicBuffers {
1077
1136
  intro?: AudioBuffer;
@@ -1099,11 +1158,20 @@ interface MusicDeps {
1099
1158
  declare class Music {
1100
1159
  readonly name: string;
1101
1160
  private deps;
1161
+ private live;
1102
1162
  constructor(name: string, deps: MusicDeps);
1103
1163
  get loopDuration(): number;
1104
1164
  get hasIntro(): boolean;
1105
1165
  get hasOutro(): boolean;
1106
1166
  play(options?: MusicPlayOptions): MusicVoice;
1167
+ /** Live playback instances spawned from this asset. */
1168
+ voices(): readonly MusicVoice[];
1169
+ /**
1170
+ * Stop every live instance. `engine.close()` uses this — without it a
1171
+ * music voice kept its source nodes running past the engine that owned
1172
+ * them, the way streams used to.
1173
+ */
1174
+ stopAll(opts?: StopOptions): void;
1107
1175
  }
1108
1176
  interface MusicVoiceDeps {
1109
1177
  ctx: AudioContext;
@@ -1143,6 +1211,8 @@ declare class MusicVoice {
1143
1211
  private loopArmTimer;
1144
1212
  private outroTimer;
1145
1213
  private nextLoopBoundaryAt;
1214
+ private loopAnchorAt;
1215
+ private introEndsAt;
1146
1216
  constructor(deps: MusicVoiceDeps);
1147
1217
  /** Currently-sounding part. Transitions automatically as parts hand off. */
1148
1218
  get currentPart(): MusicState;
@@ -1172,6 +1242,19 @@ declare class MusicVoice {
1172
1242
  private armNextLoopSegment;
1173
1243
  private crossfadeViable;
1174
1244
  private releaseLoopSegment;
1245
+ /**
1246
+ * Audio time of the next natural loop boundary.
1247
+ *
1248
+ * Under crossfade the chain re-anchors `nextLoopBoundaryAt` every time it
1249
+ * spawns a segment, so that marker is current by construction. The
1250
+ * native-loop path has no chain — one source loops itself for the whole
1251
+ * playback — so its boundaries are a grid off the loop's start, and the
1252
+ * answer has to be computed against the clock each time it's asked for.
1253
+ * Reading a marker that was written once, at the first boundary, is how
1254
+ * `skipToOutro({ at: 'loop-end' })` came to fire instantly on every
1255
+ * iteration but the first.
1256
+ */
1257
+ private nextLoopBoundary;
1175
1258
  private skipToOutroAtLoopEnd;
1176
1259
  private skipToOutroNow;
1177
1260
  private cancelLoopArm;
@@ -1193,6 +1276,13 @@ interface SoundDeps {
1193
1276
  applyConcurrency?: (v: Voice, bus: string) => boolean;
1194
1277
  /** Engine-level default click-free fade for voice.stop() (seconds). */
1195
1278
  defaultStopFade?: number;
1279
+ /**
1280
+ * Name reported on spawned voices, when it differs from the registry key.
1281
+ * Sprites and variant bundles register under internal keys; their voices
1282
+ * should still say which public asset they came from so `engine.crossfade`
1283
+ * can find them.
1284
+ */
1285
+ sourceName?: string;
1196
1286
  }
1197
1287
  /**
1198
1288
  * A loaded sample — owns one decoded AudioBuffer, spawns Voices on play().
@@ -1318,6 +1408,13 @@ declare class Variants {
1318
1408
  private lastIndex;
1319
1409
  private bag;
1320
1410
  constructor(name: string, sounds: Sound[], options?: VariantsOptions);
1411
+ /**
1412
+ * Index of the variant the most recent `play()` picked, or `-1` before the
1413
+ * first one. Read it when something outside the mix has to follow the
1414
+ * pick: a subtitle for the line that actually fired, a telemetry event, an
1415
+ * animation keyed to which take you got.
1416
+ */
1417
+ get lastPick(): number;
1321
1418
  /** Spawn a Voice on a randomly-picked variant. */
1322
1419
  play(options?: PlayOptions): Voice;
1323
1420
  /** Force the next pick to use a specific variant index. Useful for tests. */
@@ -1518,6 +1615,18 @@ interface Engine<TBusName extends string = string> {
1518
1615
  * left untouched.
1519
1616
  */
1520
1617
  crossfade(from: string, to: string, options?: CrossfadeOptions): Voice;
1618
+ /**
1619
+ * Run `fn` when the audio clock reaches `audioTime`. Returns a cancel
1620
+ * function.
1621
+ *
1622
+ * Dispatch is a JS callback, so it is not sample-accurate and can run late —
1623
+ * by a tick when the main thread is keeping up, by however long it was
1624
+ * wedged when it isn't. Stamp Web Audio parameters with the `audioTime` you
1625
+ * scheduled against for sample accuracy, but clamp it to the clock first:
1626
+ * `Math.max(audioTime, ctx.currentTime)`. Engines pull a past-dated event up
1627
+ * to the current time rather than refusing it, so two of them land on the
1628
+ * same instant and the second is refused with NotSupportedError.
1629
+ */
1521
1630
  scheduleAt(audioTime: number, fn: () => void): () => void;
1522
1631
  /** All currently active voices (across all buses). */
1523
1632
  activeVoices(): readonly Voice[];