@audio/synth-osc 1.1.0 → 1.2.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/README.md CHANGED
@@ -38,6 +38,8 @@ osc(440, { type: 'sawtooth', detune: -5 }) // → Float32Array
38
38
  | `wave` | — | Custom waveform fn `t => v`, overrides `type` |
39
39
  | `fs` | `44100` | Sample rate |
40
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
+
41
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.
42
44
 
43
45
  ---
package/audio.d.ts CHANGED
@@ -1,11 +1,13 @@
1
1
  // Generated from the audio.js manifest (params metadata is the source of truth).
2
- // Regenerate: node tools/dts.js in @audio/compile. Do not edit by hand.
2
+ // Regenerate: node tools/dts.js in @audio/plugin. Do not edit by hand.
3
3
 
4
4
  /** Automatable number — scalar, `t => value` fn, or breakpoint curve {t, v} */
5
5
  type Auto = number | ((t: number) => number) | { t: number[], v: number[] }
6
6
  /** Per-block param values as delivered by hosts (numbers arrive as 1-length Float32Array) */
7
7
  type Live = Record<string, Float32Array | string | boolean>
8
- type Ctx = { sampleRate: number, maxBlockSize: number, maxChannels: number, currentTime: number, duration?: number, events?: readonly any[], emit?: (name: string, ...args: any[]) => void, [k: string]: unknown }
8
+ type Transport = Readonly<{ playing: boolean, bpm: number, beat: number, barStart: number, timeSig: [number, number] }>
9
+ /** What a host hands a processor it builds: the contract's Context (CONTRACT.d.ts, 1.0) */
10
+ type Ctx = { readonly sampleRate: number, readonly maxBlockSize: number, readonly maxChannels: number, readonly layouts?: { readonly inputs: readonly (string | undefined)[], readonly outputs: readonly (string | undefined)[] }, readonly params: Live, readonly buffers: Readonly<Record<string, Float32Array[] | undefined>>, readonly events?: readonly { time: number, kind: 'on' | 'off', midi: number, velocity: number, id: number }[], emit(name: string, value: number): void, readonly transport: Transport }
9
11
  type Process = (inputs: Float32Array[][], outputs: Float32Array[][], params: Live) => void
10
12
 
11
13
  /** Chainable-host options for 'osc' */
@@ -27,11 +29,11 @@ export declare const osc: {
27
29
  channels: {"inputs":[],"outputs":1}
28
30
  params: {
29
31
  /** 20..20000 Hz (default 440) */
30
- "freq": { type: "number", default: 440 }
32
+ "freq": { type: "number", min: 20, max: 20000, default: 440, unit: "Hz", curve: "log" }
31
33
  /** -1200..1200 cents (default 0) */
32
- "detune": { type: "number", default: 0 }
34
+ "detune": { type: "number", min: -1200, max: 1200, default: 0, unit: "cents" }
33
35
  /** 0..1 (default 0.8) */
34
- "gain": { type: "number", default: 0.8 }
36
+ "gain": { type: "number", min: 0, max: 1, default: 0.8, smoothing: 0.01 }
35
37
  /** default "sine" */
36
38
  "type": { type: "enum", values: ["sine","square","sawtooth","triangle"], default: "sine" }
37
39
  }
package/audio.js CHANGED
@@ -1,22 +1,81 @@
1
- // atom manifest — oscillator as a generator: no input bus, phase in closure, band-limited (blep.js).
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 { wave } from './blep.js'
7
+ import { fill, tables } from './blep.js'
8
+
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
+ }
4
54
 
5
55
  export const osc = (ctx) => {
6
- 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)
7
71
  return (inputs, outputs, params) => {
8
72
  const out = outputs[0]
9
73
  if (!out || !out.length) return
10
74
  const f = params.freq[0] * 2 ** (params.detune[0] / 1200)
11
- const dt = f / ctx.sampleRate
12
- const type = params.type
13
- const g = params.gain[0]
75
+ st[1] = f / ctx.sampleRate
14
76
  const o0 = out[0]
15
- for (let i = 0; i < o0.length; i++) {
16
- o0[i] = g * wave(type, t, dt)
17
- t += dt
18
- t -= Math.floor(t)
19
- }
77
+ glide(g, 0, params.gain, gains, 0, o0.length, 0)
78
+ fill(params.type, st, o0, gains)
20
79
  for (let c = 1; c < out.length; c++) out[c].set(o0)
21
80
  }
22
81
  }
package/blep.js CHANGED
@@ -8,10 +8,16 @@
8
8
  // 10 kHz, 44.1 and 48 kHz): aliases below 16 kHz under −94 dB re the fundamental, the analysis floor, and under
9
9
  // −75 dB anywhere; harmonics within 0.01 dB of the ideal to 16 kHz, 0.8 dB low at 0.45·fs.
10
10
 
11
- const K = 32, O = 128, FC = 0.47, BETA = 10
11
+ const K = 32, O = 128, FC = 0.47, BETA = 10, TYPES = ['sine', 'square', 'sawtooth', 'triangle']
12
12
 
13
13
  let H, R // ∫h and ∫(∫h − step), tabulated O per sample over (−K, K)
14
- function tables () {
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
15
21
  let L = 2 * K * O + 1, h = new Float64Array(L)
16
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 }
17
23
  for (let i = 0; i < L; i++) {
@@ -20,28 +26,43 @@ function tables () {
20
26
  }
21
27
  let sum = 0
22
28
  for (let i = 1; i < L; i++) sum += (h[i - 1] + h[i]) / 2
23
- H = new Float64Array(L); R = new Float64Array(L)
29
+ H = new Float64Array(L)
24
30
  for (let i = 1; i < L; i++) H[i] = H[i - 1] + (h[i - 1] + h[i]) / 2 / sum
25
31
  // R integrates r = H − step; the cell ending on the step takes r's left limit there
32
+ R = h; R[0] = 0
26
33
  for (let i = 1, c = K * O; i < L; i++) {
27
34
  let r0 = H[i - 1] - (i - 1 >= c ? 1 : 0), r1 = H[i] - (i > c ? 1 : 0)
28
35
  R[i] = R[i - 1] + (r0 + r1) / 2 / O
29
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]) }
30
41
  }
31
42
 
32
- const lookup = (T, x) => { let p = (x + K) * O, i = p | 0; return i >= T.length - 1 ? T[T.length - 1] : T[i] + (T[i + 1] - T[i]) * (p - i) }
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)
33
47
 
34
- // residuals x samples after a unit step (x < 0: before it) and after a unit change of slope per sample
35
- const step = x => x <= -K || x >= K ? 0 : lookup(H, x) - (x >= 0 ? 1 : 0)
36
- const ramp = x => x <= -K || x >= K ? 0 : lookup(R, x)
37
-
38
- // sum of f over the discontinuities at phase `at`, past and coming, within K samples of phase t
39
- function around (t, dt, at, f) {
40
- let p = t - at, s = 0
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
41
53
  if (p < 0) p += 1
42
- for (let x = p / dt; x < K; x += 1 / dt) s += f(x)
43
- for (let x = (p - 1) / dt; x > -K; x -= 1 / dt) s += f(x)
44
- return s
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}"`)
45
66
  }
46
67
 
47
68
  /**
@@ -49,11 +70,22 @@ function around (t, dt, at, f) {
49
70
  * @param {'sine'|'sawtooth'|'square'|'triangle'} type
50
71
  */
51
72
  export function wave (type, t, dt) {
52
- if (type === 'sine') return Math.sin(2 * Math.PI * t)
53
- if (!H) tables()
54
- let bl = dt > 0
55
- if (type === 'sawtooth') return 1 - 2 * t + (bl ? 2 * around(t, dt, 0, step) : 0)
56
- if (type === 'square') return (t < 0.5 ? 1 : -1) + (bl ? 2 * (around(t, dt, 0, step) - around(t, dt, 0.5, step)) : 0)
57
- if (type === 'triangle') return (t < 0.5 ? 1 - 4 * t : 4 * t - 3) + (bl ? 8 * dt * (around(t, dt, 0.5, ramp) - around(t, dt, 0, ramp)) : 0)
58
- throw new RangeError(`wave: unknown type "${type}"`)
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
59
91
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@audio/synth-osc",
3
- "version": "1.1.0",
3
+ "version": "1.2.1",
4
4
  "description": "Oscillator — band-limited sine/square/sawtooth/triangle with detune",
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
  "osc.js",
18
21
  "blep.js",