@audio/synth-osc 1.0.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
@@ -1,6 +1,6 @@
1
1
  # @audio/synth-osc [![npm](https://img.shields.io/npm/v/@audio/synth-osc)](https://www.npmjs.com/package/@audio/synth-osc) [![MIT](https://img.shields.io/badge/MIT-%E0%A5%90-white)](https://github.com/krishnized/license)
2
2
 
3
- Oscillator — periodic-function waveforms (sine/square/saw/triangle), detune, custom wave fn
3
+ Oscillator — band-limited sine/square/saw/triangle, detune, custom wave fn
4
4
 
5
5
  ```
6
6
  npm install @audio/synth-osc
@@ -10,7 +10,18 @@ npm install @audio/synth-osc
10
10
  import osc from '@audio/synth-osc'
11
11
  ```
12
12
 
13
- Classic waveform oscillator rendered from [`periodic-function`](https://www.npmjs.com/package/periodic-function), with cents detune and phase offset. Pitched — `(freq, opts)`, the family generator contract.
13
+ Classic waveform oscillator with cents detune and phase offset, in [`periodic-function`](https://www.npmjs.com/package/periodic-function)'s phase conventions (saw falling, square high on the first half, triangle falling from its peak). Pitched — `(freq, opts)`, the family generator contract.
14
+
15
+ Square, saw and triangle are band-limited: at each jump in value (saw, square) or slope (triangle) within ±32 samples, the waveform takes the residual of a band-limited step (BLEP; Brandt 2001, Välimäki & Huovilainen 2007) or its integral (BLAMP; Esqueda et al. 2016), a 64-tap Kaiser-windowed sinc (β 10, cutoff 0.47·fs), linear phase, no latency. Measured from 55 Hz to 10 kHz at 44.1 and 48 kHz (2¹⁸-point Blackman-Harris spectra):
16
+
17
+ | | naive (1.0.x) | band-limited |
18
+ |---|---|---|
19
+ | strongest alias below 16 kHz, dB re fundamental (saw) | −54 (55 Hz) to −10 (10 kHz) | under −94 (the analysis floor) |
20
+ | strongest alias anywhere | −52 to −9 | under −75 |
21
+ | all aliased power re harmonics | −29 to −5 | −76 to −109 |
22
+ | harmonics vs the ideal, to 16 kHz | exact, plus aliases | within 0.01 dB; −0.8 dB at 0.45·fs |
23
+
24
+ `wave(type, t, dt)` gives one sample of it at phase `t` advancing `dt = f/fs` per sample, for oscillators of your own (synth-sfx sweeps its pitch through it).
14
25
 
15
26
  ```js
16
27
  osc(440, { type: 'sawtooth', detune: -5 }) // → Float32Array
@@ -27,6 +38,8 @@ osc(440, { type: 'sawtooth', detune: -5 }) // → Float32Array
27
38
  | `wave` | — | Custom waveform fn `t => v`, overrides `type` |
28
39
  | `fs` | `44100` | Sample rate |
29
40
 
41
+ **Live oscillator.** `import { osc } from '@audio/synth-osc/audio'` is a processor of the audio.js contract 1.0: a generator (no input bus), with `freq`, `detune`, `gain` and `type` live. A moving `gain` follows the host's ramp sample by sample, 32 frames behind it, so it does not step at the host's calls; a held one is the value itself. The two 64 KB tables the band-limited waves read are built with the first instance, once for the module, so no block allocates whatever wave it switches to; `osc()` and `wave()` build them at their first band-limited sample.
42
+
30
43
  **Use when:** the base oscillator under [`synth-voice`](https://github.com/audiojs/synth/tree/main/packages/synth-voice) and [`synth-poly`](https://github.com/audiojs/synth/tree/main/packages/synth-poly), or any test tone with a classic waveform.
31
44
 
32
45
  ---
package/audio.js CHANGED
@@ -1,23 +1,81 @@
1
- // atom manifest — oscillator as a generator: no input bus, phase in closure.
1
+ // atom manifest — oscillator as a generator: no input bus, band-limited (blep.js). The phase is kept from call to call
2
+ // in a Float64Array with the call's increment: blep.js's `fill` runs the sample loop on it, so no number is boxed (a
3
+ // number written to a closure variable, or passed to a call V8 did not inline, is a new object). The tables the
4
+ // band-limited waves read are built with the instance (blep.js `tables`, once for the module): `type` is live, so any
5
+ // block may be the first of a square, and process makes nothing.
2
6
 
3
- import { sine, square, sawtooth, triangle } from 'periodic-function'
7
+ import { fill, tables } from './blep.js'
4
8
 
5
- const WAVES = { sine, square, sawtooth, triangle }
9
+ // 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
10
+ // each call the value at its first frame and, while a value moves (a `smoothing` ramp), calls with 32 frames at most
11
+ // (contract 1.0: Parameters, Time; What a host owes, 3). So the line through the values the calls bring, each at its
12
+ // call's first frame, is known 32 frames behind any call's first frame, however the host cut the calls; the glide plays
13
+ // 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
14
+ // 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
15
+ // (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
16
+ // more than 32 frames came with no ramp: it is reached in a straight line over 32 frames. The first call of an
17
+ // instance starts on its value, and a value held 32 frames is the value itself, so a value that does not move is bit
18
+ // for bit what the kernel makes of it alone.
19
+ // `g`: the memory, GLIDE slots a value from j·GLIDE (made NaN): the value the last call brought, where in the ring its
20
+ // first frame is, its frames, the frames the line had been at that value before it (64 once held and the ring all of
21
+ // 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
22
+ // 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
23
+ // 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
24
+ // 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
25
+ // the value (then `row` holds it, filled once, and a caller may run its kernel on the value alone). Only arrays and
26
+ // whole numbers cross the call.
27
+ const GLIDE = 69
28
+ function glide (g, j, src, row, at, n, lin) {
29
+ let o = j * GLIDE, r = o + 5, v = src[0], was = g[o]
30
+ if (!(was === was)) { g[o] = v; g[o + 1] = 0; g[o + 2] = n; g[o + 3] = 0; g[o + 4] = 0 }
31
+ else if (v !== was || g[o + 3] < 64) {
32
+ 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
33
+ for (let q = 0; q < L; q++) g[r + ((w - L + q) & 63)] = was + d * q / L
34
+ g[r + w] = v
35
+ g[o] = v; g[o + 1] = w; g[o + 2] = n; g[o + 3] = held; g[o + 4] = 0
36
+ if (held < 32) {
37
+ for (let i = 0; i < n; i++) {
38
+ let u = i < 32 ? g[r + ((w + i - 32) & 63)] : v
39
+ row[at + i] = lin ? Math.exp(u * (Math.LN10 / 20)) : u
40
+ }
41
+ return 1
42
+ }
43
+ } else { g[o + 1] = (g[o + 1] + g[o + 2]) & 63; g[o + 2] = n }
44
+ // held 32 frames: the ring made all of the value once (a move from it reads the line from there), the row filled
45
+ // 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
46
+ if (g[o + 3] < 64) { for (let q = 0; q < 64; q++) g[r + q] = v; g[o + 3] = 64 }
47
+ if (g[o + 4] < n) {
48
+ let u = lin ? Math.exp(v * (Math.LN10 / 20)) : v
49
+ for (let i = 0; i < n; i++) row[at + i] = u
50
+ g[o + 4] = n
51
+ }
52
+ return 0
53
+ }
6
54
 
7
55
  export const osc = (ctx) => {
8
- let t = 0
56
+ tables()
57
+ const st = new Float64Array(2) // phase, increment
58
+ // gain scales the signal: glided (above), each sample's gain in `gains`, the value itself while it holds. The glide
59
+ // runs its paths on its memory three times over (a first value, a move to another, held until it is the value, held
60
+ // on), which is then made as built: V8 keeps no record of a function's first calls, and has then seen each path
61
+ // before it optimizes process, so the first move of the gain seconds into a stream does not deoptimize it. The
62
+ // values are fractions, as a gain is: V8 takes a whole number it has seen alone for a small integer, and a fraction
63
+ // after it deoptimizes the code made on that
64
+ const g = new Float64Array(GLIDE), gains = new Float64Array(ctx.maxBlockSize), v = new Float32Array(1)
65
+ for (let k = 0, n = Math.min(32, ctx.maxBlockSize), m = 3 + Math.ceil(32 / n); k < 3 * m; k++) {
66
+ if (k % m === 0) g.fill(NaN)
67
+ v[0] = k % m ? 0.75 : 0.25
68
+ glide(g, 0, v, gains, 0, n, 0)
69
+ }
70
+ g.fill(NaN)
9
71
  return (inputs, outputs, params) => {
10
72
  const out = outputs[0]
11
73
  if (!out || !out.length) return
12
74
  const f = params.freq[0] * 2 ** (params.detune[0] / 1200)
13
- const dt = f / ctx.sampleRate
14
- const fn = WAVES[params.type]
15
- const g = params.gain[0]
75
+ st[1] = f / ctx.sampleRate
16
76
  const o0 = out[0]
17
- for (let i = 0; i < o0.length; i++) {
18
- o0[i] = g * fn(t % 1)
19
- t += dt
20
- }
77
+ glide(g, 0, params.gain, gains, 0, o0.length, 0)
78
+ fill(params.type, st, o0, gains)
21
79
  for (let c = 1; c < out.length; c++) out[c].set(o0)
22
80
  }
23
81
  }
package/blep.js ADDED
@@ -0,0 +1,91 @@
1
+ // Band-limited classic waveforms. Each is the naive shape (periodic-function's phase conventions: saw falling
2
+ // 1 → −1, square high on [0, ½), triangle falling from 1 at t = 0) plus, at every discontinuity within ±32
3
+ // samples, the band-limited step's residual (BLEP, Brandt 2001, "Hard sync without aliasing"; Välimäki &
4
+ // Huovilainen 2007, "Antialiasing oscillators in subtractive synthesis") for a jump in value, or its integral
5
+ // (BLAMP, Esqueda, Välimäki & Bilbao 2016) for a jump in slope. The step is a 64-tap Kaiser-windowed sinc
6
+ // (β = 10, cutoff 0.47·fs), linear phase; the discontinuities' positions follow from the phase and its
7
+ // increment, so no state is kept and nothing is delayed. Measured (2^18-point Blackman-Harris spectra, 55 Hz to
8
+ // 10 kHz, 44.1 and 48 kHz): aliases below 16 kHz under −94 dB re the fundamental, the analysis floor, and under
9
+ // −75 dB anywhere; harmonics within 0.01 dB of the ideal to 16 kHz, 0.8 dB low at 0.45·fs.
10
+
11
+ const K = 32, O = 128, FC = 0.47, BETA = 10, TYPES = ['sine', 'square', 'sawtooth', 'triangle']
12
+
13
+ let H, R // ∫h and ∫(∫h − step), tabulated O per sample over (−K, K)
14
+ // Built once for the module: where an instance is built (osc's factory: `type` is live, so any block of a stream may
15
+ // be its first of a band-limited wave, and process makes nothing), else at the first band-limited `wave`. Two tables of
16
+ // 64 KB: h is written over by R, which is made from H alone. Then each wave a few times, so that V8 has seen every
17
+ // path of `value` before it optimizes a stream's loop: a path first taken seconds into a stream (a square after a
18
+ // minute of sine) would deoptimize the loop, and the code it falls back to boxes numbers until V8 optimizes it again
19
+ export function tables () {
20
+ if (H) return
21
+ let L = 2 * K * O + 1, h = new Float64Array(L)
22
+ let I0 = x => { let s = 1, t = 1; for (let k = 1; k < 60; k++) { t *= (x / 2 / k) ** 2; s += t } return s }
23
+ for (let i = 0; i < L; i++) {
24
+ let x = i / O - K, u = x / K
25
+ h[i] = (x ? Math.sin(2 * Math.PI * FC * x) / (Math.PI * x) : 2 * FC) * I0(BETA * Math.sqrt(Math.max(0, 1 - u * u))) / I0(BETA)
26
+ }
27
+ let sum = 0
28
+ for (let i = 1; i < L; i++) sum += (h[i - 1] + h[i]) / 2
29
+ H = new Float64Array(L)
30
+ for (let i = 1; i < L; i++) H[i] = H[i - 1] + (h[i - 1] + h[i]) / 2 / sum
31
+ // R integrates r = H − step; the cell ending on the step takes r's left limit there
32
+ R = h; R[0] = 0
33
+ for (let i = 1, c = K * O; i < L; i++) {
34
+ let r0 = H[i - 1] - (i - 1 >= c ? 1 : 0), r1 = H[i] - (i > c ? 1 : 0)
35
+ R[i] = R[i - 1] + (r0 + r1) / 2 / O
36
+ }
37
+ // the waves in turn, 16 times each: V8 keeps no record of a function's first calls (some 8 on Node 22 and 25; it
38
+ // makes the record lazily), and from then on sees each path many times. At dt 0.1 a discontinuity sums 3 samples
39
+ // on either side, so both loops of `residuals` run
40
+ for (let i = 0; i < 64; i++) { io[0] = i / 64; io[1] = 0.1; value(TYPES[i & 3]) }
41
+ }
42
+
43
+ // The waveform at the phase io[0] advancing io[1] a sample, into io[2], and the residuals it sums, into io[2] as well:
44
+ // no number crosses a call, because V8 boxes a double passed to or returned from a function it did not inline (square
45
+ // and triangle sum two discontinuities a sample, and V8 then inlined neither these nor `wave` into a block's loop)
46
+ const io = new Float64Array(3)
47
+
48
+ // sum of the step's (H) or the ramp's (R) residual over the discontinuities at phase `at`, past and coming, within K
49
+ // samples: a step x samples after the jump (x < 0: before it) leaves ∫h − 1 (∫h before it), a unit change of slope per
50
+ // sample ∫(∫h − step); `after` is that 1, or 0 for the ramp. Each read from its table by linear interpolation
51
+ function residuals (T, after, at) {
52
+ let dt = io[1], p = io[0] - at, s = 0, last = T.length - 1
53
+ if (p < 0) p += 1
54
+ for (let x = p / dt; x < K; x += 1 / dt) { let q = (x + K) * O, i = q | 0; s += (i >= last ? T[last] : T[i] + (T[i + 1] - T[i]) * (q - i)) - after }
55
+ for (let x = (p - 1) / dt; x > -K; x -= 1 / dt) { let q = (x + K) * O, i = q | 0; s += i >= last ? T[last] : T[i] + (T[i + 1] - T[i]) * (q - i) }
56
+ io[2] = s
57
+ }
58
+
59
+ function value (type) {
60
+ let t = io[0], dt = io[1], bl = dt > 0, s = 0
61
+ if (type === 'sine') { io[2] = Math.sin(2 * Math.PI * t); return }
62
+ if (type === 'sawtooth') { if (bl) { residuals(H, 1, 0); s = 2 * io[2] } io[2] = 1 - 2 * t + s; return }
63
+ if (type === 'square') { if (bl) { residuals(H, 1, 0); s = io[2]; residuals(H, 1, 0.5); s = 2 * (s - io[2]) } io[2] = (t < 0.5 ? 1 : -1) + s; return }
64
+ if (type === 'triangle') { if (bl) { residuals(R, 0, 0.5); s = io[2]; residuals(R, 0, 0); s = 8 * dt * (s - io[2]) } io[2] = (t < 0.5 ? 1 - 4 * t : 4 * t - 3) + s; return }
65
+ throw new RangeError(`wave: unknown type "${type}"`)
66
+ }
67
+
68
+ /**
69
+ * Band-limited waveform value at phase t ∈ [0, 1) advancing dt = f/fs per sample.
70
+ * @param {'sine'|'sawtooth'|'square'|'triangle'} type
71
+ */
72
+ export function wave (type, t, dt) {
73
+ if (!H && type !== 'sine') tables()
74
+ io[0] = t; io[1] = dt
75
+ value(type)
76
+ return io[2]
77
+ }
78
+
79
+ /** One block of the waveform into `out`, `st` = [phase, increment], the phase advanced past it, each sample scaled by
80
+ * its gain in `gains` (the manifest's loop: nothing in it is boxed; `tables` has run, in the manifest's factory) */
81
+ export function fill (type, st, out, gains) {
82
+ let t = st[0], dt = st[1]
83
+ for (let i = 0; i < out.length; i++) {
84
+ io[0] = t; io[1] = dt
85
+ value(type)
86
+ out[i] = gains[i] * io[2]
87
+ t += dt
88
+ t -= Math.floor(t)
89
+ }
90
+ st[0] = t
91
+ }
package/osc.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- /** Classic waveform oscillator (periodic-function), with detune + phase offset. */
1
+ /** Classic waveform oscillator, band-limited, with detune + phase offset. */
2
2
  export interface OscOptions {
3
3
  /** seconds, default 1 */
4
4
  duration?: number
@@ -12,9 +12,12 @@ export interface OscOptions {
12
12
  detune?: number
13
13
  /** starting phase 0..1, default 0 */
14
14
  phase?: number
15
- /** custom waveform fn, overrides type */
15
+ /** custom waveform fn, overrides type (rendered as given, not band-limited) */
16
16
  wave?: (t: number) => number
17
17
  }
18
18
 
19
19
  /** freq: Hz (positional) */
20
20
  export default function osc(freq: number, options?: OscOptions): Float32Array
21
+
22
+ /** One sample of a band-limited waveform at phase t ∈ [0, 1) advancing dt = f/fs per sample (BLEP / BLAMP). */
23
+ export function wave(type: 'sine' | 'square' | 'sawtooth' | 'triangle', t: number, dt: number): number
package/osc.js CHANGED
@@ -1,26 +1,27 @@
1
- // Oscillator — classic waveforms rendered from periodic-function (scijs), with detune.
1
+ // Oscillator — classic waveforms, band-limited (blep.js), with detune.
2
2
 
3
- import { sine, square, sawtooth, triangle } from 'periodic-function'
3
+ import { wave } from './blep.js'
4
4
 
5
- const WAVES = { sine, square, sawtooth, triangle }
5
+ export { wave }
6
+
7
+ const TYPES = ['sine', 'square', 'sawtooth', 'triangle']
6
8
 
7
9
  /**
8
10
  * @param {number} freq — Hz
9
11
  * @param {object} opts — { duration=1 (s), fs=44100, type='sine'|'square'|'sawtooth'|'triangle',
10
- * amp=0.8, detune=0 (cents), phase=0 (0..1), wave: custom t=>v }
12
+ * amp=0.8, detune=0 (cents), phase=0 (0..1), wave: custom t=>v (rendered as given, not band-limited) }
11
13
  * @returns {Float32Array}
12
14
  */
13
- export default function osc (freq, { duration = 1, fs = 44100, type = 'sine', amp = 0.8, detune = 0, phase = 0, wave } = {}) {
14
- let fn = wave || WAVES[type]
15
- if (!fn) throw new RangeError(`osc: unknown type "${type}"`)
15
+ export default function osc (freq, { duration = 1, fs = 44100, type = 'sine', amp = 0.8, detune = 0, phase = 0, wave: fn } = {}) {
16
+ if (!fn && !TYPES.includes(type)) throw new RangeError(`osc: unknown type "${type}"`)
16
17
  let f = freq * 2 ** (detune / 1200)
17
18
  let n = Math.round(duration * fs)
18
19
  let d = new Float32Array(n)
19
- let t = phase
20
20
  let dt = f / fs
21
21
  for (let i = 0; i < n; i++) {
22
- d[i] = amp * fn(t % 1)
23
- t += dt
22
+ let t = (phase + i * dt) % 1
23
+ if (t < 0) t += 1
24
+ d[i] = amp * (fn ? fn(t) : wave(type, t, dt))
24
25
  }
25
26
  return d
26
27
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@audio/synth-osc",
3
- "version": "1.0.4",
4
- "description": "Oscillator — sine/square/sawtooth/triangle with detune (wraps periodic-function)",
3
+ "version": "1.2.0",
4
+ "description": "Oscillator — band-limited sine/square/sawtooth/triangle with detune",
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
7
  "main": "osc.js",
@@ -13,16 +13,17 @@
13
13
  "default": "./audio.js"
14
14
  }
15
15
  },
16
+ "scripts": {
17
+ "prepublishOnly": "node ../../../compile/tools/tested.js"
18
+ },
16
19
  "files": [
17
20
  "osc.js",
21
+ "blep.js",
18
22
  "osc.d.ts",
19
23
  "audio.js",
20
24
  "audio.d.ts"
21
25
  ],
22
26
  "types": "osc.d.ts",
23
- "dependencies": {
24
- "periodic-function": "^2.1.0"
25
- },
26
27
  "keywords": [
27
28
  "audio",
28
29
  "dsp",