@audio/effect-pingpong 1.1.4 → 1.2.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/README.md CHANGED
@@ -12,15 +12,19 @@ import pingPong from '@audio/effect-pingpong'
12
12
 
13
13
  Cross-fed stereo delay — left echo bounces to right, right to left.
14
14
 
15
- **`time`** delay time in seconds (default 0.25) · **`feedback`** 0–1 (default 0.3) · **`mix`** wet/dry 0–1 (default 0.5) · **`fs`** sample rate
15
+ **`time`** non-negative seconds (default 0.25) · **`feedback`** gain per repeat (default 0.4) · **`mix`** wet/dry 0–1 (default 0.5) · **`fs`** positive sample rate in Hz (default 44100)
16
16
 
17
17
  ```js
18
- import { pingPong } from '@audio/effect'
18
+ import pingPong from '@audio/effect-pingpong'
19
19
 
20
20
  let p = { time: 0.15, feedback: 0.5, mix: 0.5, fs: 44100 }
21
21
  for (let [L, R] of stereoStream) pingPong(L, R, p)
22
22
  ```
23
23
 
24
+ Both channels must have equal lengths; a mismatch throws before processing. The delay is read as the mono delay reads it, between frames where it falls between them, and a new time moves both reads across the call from the time the last call ended on, as fast as the mono delay's read at most. Rings too short for a longer time are made anew, empty (give `_bufL` and `_bufR` long enough to keep them); empty channels do not advance or reset them. Reuse one params object for successive stereo chunks, or create a fresh one to reset. Time and sample-rate validation match the mono delay. Keep `abs(feedback) < 1` for decay; the direct function does not clamp it.
25
+
26
+ The `/audio` factory limits feedback to 0–0.9 and time to 0.01–2 seconds and makes both rings for 2 seconds, so `time` is live, smoothed over 20 ms; a far move bends the echoes an octave at most, as the mono delay's does. `sync` sets the time to a note at the host's tempo, as the mono delay's does, held to 2 seconds. Each block calls the in-place form. Its tail estimate describes 60 dB decay at the supplied settings (with sync on, at the note at the tempo the host hands it, or at the longest time where it hands none; a value not known yet reserves its range's longest), not a hard silence boundary; disconnected inputs drain through silent blocks.
27
+
24
28
  **Use when**: stereo width from delays, spatial depth, rhythmic bounce effects<br>
25
29
  **Not for**: mono output
26
30
 
package/audio.d.ts CHANGED
@@ -16,6 +16,8 @@ export interface PingpongOptions {
16
16
  "feedback"?: Auto
17
17
  /** 0..1 (default 0.5) */
18
18
  "mix"?: Auto
19
+ /** default "off" */
20
+ "sync"?: "off" | "1/2" | "1/4" | "1/4t" | "1/8d" | "1/8" | "1/8t" | "1/16"
19
21
  at?: number | string
20
22
  duration?: number | string
21
23
  }
@@ -23,13 +25,15 @@ export interface PingpongOptions {
23
25
  export declare const pingpong: {
24
26
  (ctx: Ctx): Process
25
27
  channels: 2
26
- tail: (ctx: { sampleRate: number, params: Live }) => number
28
+ tail: (at: { sampleRate: number, params: Live, buffers: {} }) => number
27
29
  params: {
28
- /** 0.01..2 s (default 0.25) [restart] */
30
+ /** 0.01..2 s (default 0.25) */
29
31
  "time": { type: "number", default: 0.25 }
30
32
  /** 0..0.9 (default 0.4) */
31
33
  "feedback": { type: "number", default: 0.4 }
32
34
  /** 0..1 (default 0.5) */
33
35
  "mix": { type: "number", default: 0.5 }
36
+ /** default "off" */
37
+ "sync": { type: "enum", values: ["off","1/2","1/4","1/4t","1/8d","1/8","1/8t","1/16"], default: "off" }
34
38
  }
35
39
  }
package/audio.js CHANGED
@@ -1,26 +1,115 @@
1
1
  // atom manifest — wraps the ping-pong atom. Inherently stereo: the kernel
2
2
  // cross-feeds left/right delay lines, so this declares a fixed 2-channel bus and holds
3
- // one shared state object (not per-channel). `time` sizes both delay lines at
4
- // construction (flags: restart); feedback/mix are live.
3
+ // one shared state object (not per-channel), made here with both rings for the longest
4
+ // time (time.max, as the host hands it, a Float32), so `time` is live: a new time glides
5
+ // across the call from where the last call ended, and the reads run no slower than half
6
+ // speed and no faster than double until they are there, the bend of a tape delay: a far
7
+ // move bends the echoes by an octave at most, down for twice the increase, up for as long
8
+ // as the decrease, and one that reverses under way turns from an octave down to an octave
9
+ // up in a frame. `time.smoothing` is the host's ramp for a new time: the reads follow it as
10
+ // asked while each call's step asks at most half a frame a frame farther or a frame nearer
11
+ // (10 ms longer or 20 ms shorter over 20 ms where every call of the ramp is 32 frames; less
12
+ // where a host cuts a call of the ramp shorter), and a farther move takes as long as the
13
+ // bound needs. `sync` sets the time to a note at the host's tempo (ctx.transport.bpm),
14
+ // held to the rings; a new tempo or note is handed to the kernel as it comes, glided across
15
+ // the call after it, or at the bound's speed where that is slower. 'off' (default) leaves
16
+ // `time` in charge, as without it. feedback/mix are live: mix scales the signal, so a new mix
17
+ // is glided sample by sample (glide, below) along the host's ramp.
18
+ // Each block calls the in-place form, which returns no pair.
5
19
 
6
- import pingPongFn from './ping-pong.js'
20
+ import { pingPongInPlace, delaySamples } from './ping-pong.js'
21
+
22
+ // A value that scales the signal, glided sample by sample so that a host's steps of it join into one line. A host hands
23
+ // each call the value at its first frame and, while a value moves (a `smoothing` ramp), calls with 32 frames at most
24
+ // (contract 1.0: Parameters, Time; What a host owes, 3). So the line through the values the calls bring, each at its
25
+ // call's first frame, is known 32 frames behind any call's first frame, however the host cut the calls; the glide plays
26
+ // it 32 frames late. Straight from the value of one call to the next's, it is the host's ramp itself, in the value's
27
+ // own unit, the same whether the host calls with 1, 32 or a mix of frames; drawn between each call's end and the next
28
+ // (a glide across each call), a ramp cut 32, 4, 32 would put 32 frames of it into 4. A value that follows a call of
29
+ // more than 32 frames came with no ramp: it is reached in a straight line over 32 frames. The first call of an
30
+ // instance starts on its value, and a value held 32 frames is the value itself, so a value that does not move is bit
31
+ // for bit what the kernel makes of it alone.
32
+ // `g`: the memory, GLIDE slots a value from j·GLIDE (made NaN): the value the last call brought, where in the ring its
33
+ // first frame is, its frames, the frames the line had been at that value before it (64 once held and the ring all of
34
+ // it; counted to 63 at most, so that a long call after a move cannot reach 64 before the ring is made all of it), how
35
+ // many of `row`'s hold it, then the line, a frame a slot, in a ring of 64. `src`: the param's array. The line's values
36
+ // for this call's `n` frames go to `row` from `at`: as they are, or with `lin` 1 the gain e^(v·ln10/20) of a value in
37
+ // dB, per sample, so the gain follows the host's ramp of the dB value. Returns 1 while they move, 0 when every one is
38
+ // the value (then `row` holds it, filled once, and a caller may run its kernel on the value alone). Only arrays and
39
+ // whole numbers cross the call.
40
+ const GLIDE = 69
41
+ function glide (g, j, src, row, at, n, lin) {
42
+ let o = j * GLIDE, r = o + 5, v = src[0], was = g[o]
43
+ if (!(was === was)) { g[o] = v; g[o + 1] = 0; g[o + 2] = n; g[o + 3] = 0; g[o + 4] = 0 }
44
+ else if (v !== was || g[o + 3] < 64) {
45
+ let len = g[o + 2], L = len < 32 ? len : 32, w = (g[o + 1] + len) & 63, d = v - was, held = v === was ? Math.min(g[o + 3] + len, 63) : 0
46
+ for (let q = 0; q < L; q++) g[r + ((w - L + q) & 63)] = was + d * q / L
47
+ g[r + w] = v
48
+ g[o] = v; g[o + 1] = w; g[o + 2] = n; g[o + 3] = held; g[o + 4] = 0
49
+ if (held < 32) {
50
+ for (let i = 0; i < n; i++) {
51
+ let u = i < 32 ? g[r + ((w + i - 32) & 63)] : v
52
+ row[at + i] = lin ? Math.exp(u * (Math.LN10 / 20)) : u
53
+ }
54
+ return 1
55
+ }
56
+ } else { g[o + 1] = (g[o + 1] + g[o + 2]) & 63; g[o + 2] = n }
57
+ // held 32 frames: the ring made all of the value once (a move from it reads the line from there), the row filled
58
+ // with it as far as no call since it was held has filled it; from then on a call only moves the ring's position
59
+ if (g[o + 3] < 64) { for (let q = 0; q < 64; q++) g[r + q] = v; g[o + 3] = 64 }
60
+ if (g[o + 4] < n) {
61
+ let u = lin ? Math.exp(v * (Math.LN10 / 20)) : v
62
+ for (let i = 0; i < n; i++) row[at + i] = u
63
+ g[o + 4] = n
64
+ }
65
+ return 0
66
+ }
67
+
68
+ // quarter notes in each of sync's values, in their order ('off' 0): d is dotted (half as long again), t a triplet (two
69
+ // thirds). Looked up by position: a keyed load by the value's name had V8 box the number it read once two instances
70
+ // had asked for different names
71
+ const QUARTERS = Float64Array.of(0, 2, 1, 2 / 3, 0.75, 0.5, 1 / 3, 0.25)
72
+ // the seconds sync's k-th value lasts at `bpm` quarter notes a minute, held to the rings
73
+ const noted = (k, bpm) => Math.min(pingpong.params.time.max, Math.max(pingpong.params.time.min, QUARTERS[k] * 60 / bpm))
7
74
 
8
75
  export const pingpong = (ctx) => {
9
- const p = { fs: ctx.sampleRate, time: ctx.params.time[0] }
76
+ const { time, sync } = pingpong.params, fs = ctx.sampleRate
77
+ const ring = Math.floor(delaySamples(Math.fround(time.max), fs)) + 2 // as ping-pong.js sizes it for a time
78
+ const p = { fs, time: ctx.params.time[0], feedback: ctx.params.feedback[0], mix: ctx.params.mix[0], _bufL: new Float64Array(ring), _bufR: new Float64Array(ring), _ptr: 0, _glide: new Float64Array(2).fill(NaN) }
79
+ const g = new Float64Array(GLIDE).fill(NaN), mixes = new Float64Array(ctx.maxBlockSize)
10
80
  return (inputs, outputs, params) => {
11
- const inp = inputs[0], out = outputs[0]
12
- if (!inp || inp.length < 2) return
81
+ // `noted` written out: called here, V8 did not always inline it, and boxed the time it returned
82
+ const inp = inputs[0], out = outputs[0], bpm = ctx.transport?.bpm, k = sync.values.indexOf(params.sync)
83
+ p.time = k > 0 ? Math.min(time.max, Math.max(time.min, QUARTERS[k] * 60 / (bpm > 0 ? bpm : 120))) : params.time[0]
13
84
  p.feedback = params.feedback[0]
14
85
  p.mix = params.mix[0]
15
- out[0].set(inp[0])
16
- out[1].set(inp[1])
17
- pingPongFn(out[0], out[1], p)
86
+ for (let c = 0; c < 2; c++) {
87
+ if (inp?.[c]?.length) out[c].set(inp[c])
88
+ else out[c].fill(0)
89
+ }
90
+ pingPongInPlace(out[0], out[1], p, glide(g, 0, params.mix, mixes, 0, out[0].length, 0) ? mixes : undefined)
18
91
  }
19
92
  }
20
93
  pingpong.channels = 2
21
- pingpong.tail = ({ params }) => { let fb = params.feedback[0]; let reps = fb > 0 ? Math.log(1e-3) / Math.log(fb) : 1; return (reps + 1) * params.time[0] } // RT60 from live feedback × live time
94
+ // The echoes a loop of feedback fb leaves, the m-th back at gain · fb^(m − 1), until the rest of them is under 1e-3 (the
95
+ // tail, CONTRACT 1.0: 60 dB under the input's level): after n the rest of Σ|h| is gain · fb^n / (1 − fb), which a held
96
+ // DC meets, its echoes piled up to gain / (1 − fb) times it. None where they start under 1e-3; one where nothing feeds back
97
+ const echoes = (fb, gain) => gain / (1 - fb) <= 1e-3 ? 0 : fb > 0 ? Math.max(1, Math.ceil(Math.log(1e-3 * (1 - fb) / gain) / Math.log(fb))) : 1
98
+ pingpong.tail = ({ sampleRate, params, transport }) => {
99
+ // with sync on the time is a note at the host's tempo: at transport.bpm where the host hands over a finite one, else
100
+ // the longest it may be (an infinite tempo read as known gave the shortest). A planning snapshot's NaN (automation
101
+ // whose values are not known yet) reserves the maximum, as effect-delay's tail does: through the logarithm below it
102
+ // gave a NaN tail, which a host takes as none. An echo comes back each `time`, on the other channel, at
103
+ // mix · fb^(m − 1), a read between frames spreading it over the next frame; a ring of 128 frames or less needs no
104
+ // tail (CONTRACT 1.0)
105
+ const { feedback: f, time: t, sync } = pingpong.params, k = sync.values.indexOf(params.sync), bpm = transport?.bpm
106
+ const fb = Number.isFinite(params.feedback[0]) ? Math.abs(params.feedback[0]) : f.max, mix = Number.isFinite(params.mix?.[0]) ? Math.min(1, Math.abs(params.mix[0])) : 1
107
+ const frames = Math.ceil(delaySamples(k > 0 ? (Number.isFinite(bpm) && bpm > 0 ? noted(k, bpm) : t.max) : Number.isFinite(params.time[0]) ? params.time[0] : t.max, sampleRate)) * echoes(fb, mix)
108
+ return frames > 128 ? frames / sampleRate : 0
109
+ } // Time to decay by 60 dB at the supplied settings; not a hard silence boundary.
22
110
  pingpong.params = {
23
- time: { type: 'number', min: 0.01, max: 2, default: 0.25, unit: 's', flags: ['restart'] },
111
+ time: { type: 'number', min: 0.01, max: 2, default: 0.25, unit: 's', smoothing: 0.02 },
24
112
  feedback: { type: 'number', min: 0, max: 0.9, default: 0.4 },
25
113
  mix: { type: 'number', min: 0, max: 1, default: 0.5, smoothing: 0.02 },
114
+ sync: { type: 'enum', values: ['off', '1/2', '1/4', '1/4t', '1/8d', '1/8', '1/8t', '1/16'], default: 'off' },
26
115
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@audio/effect-pingpong",
3
- "version": "1.1.4",
3
+ "version": "1.2.0",
4
4
  "description": "Ping-pong delay — stereo: left and right delays alternate",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -13,6 +13,9 @@
13
13
  "default": "./audio.js"
14
14
  }
15
15
  },
16
+ "scripts": {
17
+ "prepublishOnly": "node ../../../compile/tools/tested.js"
18
+ },
16
19
  "files": [
17
20
  "ping-pong.js",
18
21
  "audio.js",
package/ping-pong.d.ts CHANGED
@@ -1,22 +1,40 @@
1
1
  /** Ping-pong delay — stereo cross-fed delay; left echo bounces to right, right to left. */
2
2
  export interface PingPongOptions {
3
- /** delay time, seconds, default 0.25. Changing this reallocates both delay buffers, dropping buffered history. */
3
+ /** Non-negative seconds, default 0.25. Reads delaySamples(time, fs) samples back, between two samples where that is not a whole frame. A new time glides across the call from the one the last call ended on, the reads moving at most half a frame a frame farther back and a frame a frame nearer (half speed to double, an octave down or up at most); a farther move goes on across the calls after, until the reads are on the time. Rings too short for it are made anew, empty; empty buffers leave state unchanged. */
4
4
  time?: number
5
- /** feedback, 0–0.9, default 0.4 */
5
+ /** Gain per repeat, default 0.4. abs(feedback) < 1 decays; direct calls do not clamp. */
6
6
  feedback?: number
7
7
  /** wet/dry, 0–1, default 0.5 */
8
8
  mix?: number
9
- /** sample rate, default 44100 */
9
+ /** Finite positive sample rate in Hz, default 44100 */
10
10
  fs?: number
11
11
  }
12
12
 
13
13
  /**
14
+ * Omitted options use fresh defaults; use a fresh options object to reset.
15
+ * Invalid time/sample rate throws RangeError before input/state changes.
16
+ * Channel lengths must match; otherwise throws RangeError before processing.
14
17
  * Mutates `left` and `right` in place and returns `[left, right]` (the same two
15
18
  * references). Pass the same params object across calls — the two delay ring
16
- * buffers and shared write pointer persist on it (`_bufL`, `_bufR`, `_ptr`).
19
+ * buffers, shared write pointer, and the time the last call ended on and where its reads
20
+ * were persist on it (`_bufL`, `_bufR`, `_ptr`, `_glide`). Rings made for a longer time (the `/audio`
21
+ * factory makes them for 2 s) keep their history as the time changes.
17
22
  */
18
- export default function pingPong(
19
- left: Float32Array,
20
- right: Float32Array,
23
+ export default function pingPong<L extends Float32Array | Float64Array, R extends Float32Array | Float64Array>(
24
+ left: L,
25
+ right: R,
21
26
  params?: PingPongOptions
22
- ): [Float32Array, Float32Array]
27
+ ): [L, R]
28
+
29
+ /**
30
+ * The same as the default, without the pair it returns: what a host's block loop calls, as it
31
+ * may allocate nothing. Throws as the default does on channel lengths that do not match. `mixes`, when given, holds the
32
+ * mix for each frame, in place of `params.mix`: the `/audio` factory's glide of a moving mix.
33
+ */
34
+ export function pingPongInPlace(left: Float32Array | Float64Array, right: Float32Array | Float64Array, params?: PingPongOptions, mixes?: Float64Array): void
35
+
36
+ /**
37
+ * The delay in samples a time asks for: max(1, time * fs), or the whole frame it is
38
+ * within a Float32 step (2^-23 of it) of, as a host passes a time as a Float32.
39
+ */
40
+ export function delaySamples(time: number, fs: number): number
package/ping-pong.js CHANGED
@@ -3,36 +3,84 @@
3
3
  * Takes two channel buffers, modifies both in-place.
4
4
  */
5
5
 
6
- export default function pingPong (left, right, params) {
6
+ // The delay in samples a time asks for, at least one so the feedback loop stays causal. A host passes a time as a
7
+ // Float32: 10 ms arrives as 0.009999999776, 479.99999 frames at 48 kHz. Within a Float32 step (2^-23 of it) of a whole
8
+ // frame it is that frame, so such a time reads one sample, bit for bit as a line of whole frames read it; any other
9
+ // time reads between two samples
10
+ export function delaySamples (time, fs) {
11
+ let d = time * fs, r = Math.round(d)
12
+ if (Math.abs(d - r) <= r * 2 ** -23) d = r
13
+ return Math.max(1, d)
14
+ }
15
+
16
+ // How far the reads may move in a frame, as a tape delay's head runs no slower than half speed and no faster than
17
+ // double while its time moves: the echoes bend an octave at most, down while the time grows (by at most half a frame a
18
+ // frame, so a move takes twice the increase) and up while it shrinks (a frame a frame, as long as the decrease)
19
+ const GROW = 0.5, SHRINK = 1
20
+
21
+ export default function pingPong (left, right, params = {}) {
22
+ pingPongInPlace(left, right, params)
23
+ return [left, right]
24
+ }
25
+
26
+ // ping-pong without the pair it returns: what a host's block loop calls, as it may allocate nothing. `mixes`, when
27
+ // given, holds the mix for each frame (the /audio manifest's glide of a moving mix), in place of params.mix
28
+ export function pingPongInPlace (left, right, params = {}, mixes) {
29
+ if (left.length !== right.length) throw new RangeError('channel lengths must match')
7
30
  let time = params.time ?? 0.25
8
31
  let feedback = params.feedback ?? 0.4
9
32
  let mix = params.mix ?? 0.5
10
- let fs = params.fs || 44100
33
+ let fs = params.fs ?? 44100
11
34
 
12
- let delaySamples = (time * fs) | 0
35
+ if (!Number.isFinite(time) || time < 0) throw new RangeError('time must be a finite non-negative number of seconds')
36
+ if (!Number.isFinite(fs) || fs <= 0) throw new RangeError('fs must be a finite positive sample rate')
37
+ let d = delaySamples(time, fs)
38
+ if (!(Math.floor(d) + 2 <= Number.MAX_SAFE_INTEGER)) throw new RangeError('delay length must be a safe integer')
39
+ if (!left.length) return
13
40
 
14
- if (!params._bufL || params._bufL.length < delaySamples) {
15
- params._bufL = new Float64Array(delaySamples)
16
- params._bufR = new Float64Array(delaySamples)
41
+ // a read d samples back takes the samples floor(d) and floor(d) + 1 back. Rings made for a longer time hold this
42
+ // one, so a shorter time keeps every sample at its age; rings too short for it are made anew, empty. Where the last
43
+ // call ended: the time it asked for, and where its reads were (NaN before the first call)
44
+ let ended = params._glide ??= new Float64Array(2).fill(NaN)
45
+ if (!params._bufL || params._bufL.length < Math.floor(d) + 2) {
46
+ params._bufL = new Float64Array(Math.floor(d) + 2)
47
+ params._bufR = new Float64Array(Math.floor(d) + 2)
17
48
  params._ptr = 0
49
+ ended[0] = ended[1] = NaN
18
50
  }
19
- let bufL = params._bufL, bufR = params._bufR, ptr = params._ptr
51
+ let bufL = params._bufL, bufR = params._bufR, N = bufL.length, ptr = params._ptr
52
+ // a new time is reached across this call from the one the last call ended on, so the reads glide (a tape delay's
53
+ // bend) instead of jumping; a host ramps a smoothed `time` in short calls, and this joins its steps into one line.
54
+ // The reads follow that line at the speed it asks, up to GROW and SHRINK; a farther move goes on at that speed
55
+ // across the calls that follow, until the reads are on the time
56
+ let from = ended[0] === ended[0] ? ended[0] : d, glide = d - from, at = ended[1] >= 1 ? ended[1] : from
20
57
 
21
58
  for (let i = 0, l = left.length; i < l; i++) {
22
- let dL = bufL[ptr]
23
- let dR = bufR[ptr]
59
+ let want = from + glide * (i + 1) / l
60
+ at = want > at + GROW ? at + GROW : want < at - SHRINK ? at - SHRINK : want
61
+ let D = Math.floor(at), f = at - D
62
+ let r = ptr - D
63
+ if (r < 0) r += N
64
+ let dL = bufL[r]
65
+ let dR = bufR[r]
66
+ if (f) {
67
+ let s = r ? r - 1 : N - 1
68
+ dL += f * (bufL[s] - dL)
69
+ dR += f * (bufR[s] - dR)
70
+ }
24
71
 
25
72
  // Cross-feed: left delay feeds right, right feeds left
26
73
  bufL[ptr] = left[i] + feedback * dR
27
74
  bufR[ptr] = right[i] + feedback * dL
28
75
 
29
- left[i] = left[i] * (1 - mix) + dL * mix
30
- right[i] = right[i] * (1 - mix) + dR * mix
76
+ let m = mixes ? mixes[i] : mix
77
+ left[i] = left[i] * (1 - m) + dL * m
78
+ right[i] = right[i] * (1 - m) + dR * m
31
79
 
32
- ptr = (ptr + 1) % delaySamples
80
+ if (++ptr === N) ptr = 0
33
81
  }
34
82
 
35
83
  params._ptr = ptr
36
-
37
- return [left, right]
84
+ ended[0] = d
85
+ ended[1] = at
38
86
  }