From 1461779e23a18e5348795b94aa31fe6e60209f77 Mon Sep 17 00:00:00 2001 From: monkey-w1n5t0n Date: Sun, 28 Jun 2026 23:06:20 +0200 Subject: [PATCH] =?UTF-8?q?feat(manifold):=20gate=20sequences=20in=20the?= =?UTF-8?q?=20CV=20backend=20(RatioSeq)=20=E2=80=94=20SLP-Workshop?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implements the spec's rhythm stream for the uSEQ CV backend, on the existing slp_workshop/MEMLCelium engine (its outputs [0..13] are the 2 RatioSeq tracks). - ratio-seq.ts: faithful TS port of the engine's gate generator (decode 7 params/track, ratio_seq pulse test, 4/4 bar clock). Unit-tested (5 tests). - CV backend: gate channels run as a clock-driven Sequence (RatioSeq track from the rhythm output slice [track*7..]) or a continuous Threshold; BPM-synced to the app tempo; one eval per track per tick. - CvSpec gains gateSource ('sequence'|'threshold') + seqTrack; per-gate UI in the Outputs panel; bpm threaded through useBackendManager. Next (spec Build Deltas): MIDI note on/off from gate edges; gate-sequence count + shared/separate-net toggle + per-input-channel routing; engine 2nd MLP head. --- manifold/src/backends/cv-backend.ts | 44 ++++++- manifold/src/backends/ratio-seq.test.ts | 66 ++++++++++ manifold/src/backends/ratio-seq.ts | 136 +++++++++++++++++++++ manifold/src/backends/useBackendManager.ts | 7 +- manifold/src/console/ConsoleApp.tsx | 1 + manifold/src/console/model.ts | 4 +- manifold/src/dock/BackendAdvanced.tsx | 4 +- manifold/src/dock/OutputsBackendConfig.tsx | 78 +++++++++--- manifold/src/dock/output-state.ts | 15 ++- 9 files changed, 324 insertions(+), 31 deletions(-) create mode 100644 manifold/src/backends/ratio-seq.test.ts create mode 100644 manifold/src/backends/ratio-seq.ts diff --git a/manifold/src/backends/cv-backend.ts b/manifold/src/backends/cv-backend.ts index 3388ec3..68ac695 100644 --- a/manifold/src/backends/cv-backend.ts +++ b/manifold/src/backends/cv-backend.ts @@ -31,10 +31,12 @@ import { encodeOutput, FRAME_IDENTIFY_LEN, } from './useq-protocol'; +import { RatioSeqEngine, decodeTrack } from './ratio-seq'; const SEND_INTERVAL_MS = 1000 / STREAM_HZ; // ~10 ms const CV_DEAD_ZONE = 8; // on the 12-bit value (~0.2%) const IDENTIFY_TIMEOUT_MS = 5000; +const MAX_TRACKS = 16; // gate-sequence RatioSeq tracks (7 rhythm params each) // The firmware streams INPUT frames at 20 Hz, so a live module proves itself // within ~50 ms. Allow for a USB-CDC (DTR) reset on open before giving up. const HANDSHAKE_TIMEOUT_MS = 2500; @@ -75,6 +77,12 @@ export class UseqCvBackend implements OutputBackend { private lastSendMs = 0; private writing = false; // in-flight write guard (avoid serial backpressure) + // Gate sequencer (the rhythm stream): RatioSeq tracks decoded from the rhythm + // slice of the routed output vector. `trackDone` memoises one eval per tick. + private seq = new RatioSeqEngine(); + private trackGate = new Uint8Array(MAX_TRACKS); + private trackDone = new Uint8Array(MAX_TRACKS); + private pendingIdentify: (() => void) | null = null; private statusState: BackendStatus = { state: 'idle', message: 'CV idle' }; @@ -115,7 +123,7 @@ export class UseqCvBackend implements OutputBackend { this.ctx = ctx; } - /** Update the per-output CV specs (channel + gate threshold). */ + /** Update the per-output CV specs (channel, gate source/track/threshold). */ setCvConfig(specs: CvSpec[]): void { this.specs = specs; this.targets = specs.map((s) => resolveTarget(s.channel)); @@ -123,6 +131,11 @@ export class UseqCvBackend implements OutputBackend { this.lastGateBits = -1; } + /** Tempo for the gate sequencer (BPM, 4/4). */ + setBpm(bpm: number): void { + this.seq.setBpm(bpm); + } + /** User-gesture path: pick + open a serial port. Throws if the user cancels. */ async connect(): Promise { if (!this.isAvailable()) { @@ -251,11 +264,16 @@ export class UseqCvBackend implements OutputBackend { const now = typeof performance !== 'undefined' ? performance.now() : Date.now(); if (now - this.lastSendMs < SEND_INTERVAL_MS) return; + // Advance the gate-sequencer clock every tick (even if we end up not + // transmitting), clamping any backgrounded-tab jump. + const dt = Math.min(0.1, (now - this.lastSendMs) / 1000); this.lastSendMs = now; + this.seq.advance(dt); if (this.writing) return; // previous frame still draining — drop this one // Rebuild the 14-channel snapshot from the routed outputs. this.cvVals.fill(0); + this.trackDone.fill(0); let gates = 0; const n = Math.min(routed.length, ctx.mappings.length, this.targets.length); for (let i = 0; i < n; i++) { @@ -263,11 +281,15 @@ export class UseqCvBackend implements OutputBackend { if (!t) continue; const m = ctx.mappings[i]; if (isSilent(m)) continue; - const mapped = mapOutput(routed[i], m); // 0..1 in [min,max] if (t.kind === 'cv') { - if (t.idx >= 0 && t.idx < NUM_CV) this.cvVals[t.idx] = cvToWire(mapped); + if (t.idx >= 0 && t.idx < NUM_CV) this.cvVals[t.idx] = cvToWire(mapOutput(routed[i], m)); } else if (t.idx >= 0 && t.idx < 3) { - if (mapped >= (this.specs[i]?.gateThreshold ?? 0.5)) gates |= 1 << t.idx; + const spec = this.specs[i]; + const on = + spec?.gateSource === 'threshold' + ? mapOutput(routed[i], m) >= (spec.gateThreshold ?? 0.5) + : this.seqGate(spec?.seqTrack ?? 0, routed); + if (on) gates |= 1 << t.idx; } } @@ -294,6 +316,20 @@ export class UseqCvBackend implements OutputBackend { }); } + /** + * Gate level for RatioSeq `track`, evaluated at most once per tick. The track's + * 7 params are the rhythm slice of the routed vector at [track*7 .. +6] — which + * for the MEMLCelium / SLP-Workshop engine are outputs [0..13] (its 2 tracks). + */ + private seqGate(track: number, routed: Float32Array): boolean { + if (track < 0 || track >= MAX_TRACKS) return false; + if (!this.trackDone[track]) { + this.trackGate[track] = this.seq.evalTrack(track, decodeTrack(routed, track * 7)).gate ? 1 : 0; + this.trackDone[track] = 1; + } + return this.trackGate[track] === 1; + } + private handleDisconnect(): void { if (!this.port) return; this.clearHandshakeWatchdog(); diff --git a/manifold/src/backends/ratio-seq.test.ts b/manifold/src/backends/ratio-seq.test.ts new file mode 100644 index 0000000..e225ff4 --- /dev/null +++ b/manifold/src/backends/ratio-seq.test.ts @@ -0,0 +1,66 @@ +/** + * RatioSeqEngine tests (bun test) — pin the gate generator against the C++ + * engine's decode + ratio_seq semantics so the browser stays in parity. + */ +import { expect, test } from 'bun:test'; +import { RatioSeqEngine, decodeTrack, ratioSeq } from './ratio-seq'; + +test('decodeTrack matches the C++ set_params decode', () => { + // params all 0.5 → ratios int(1.5)=1 +1 = 2; phasorMul muls[int(1.999..)&3]=muls[1]=2; + // phaseOff int(2.0)*0.25 = 0.5; ampRatios int(1.5)+1 = 2. + const d = decodeTrack([0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5]); + expect(d.ratios).toEqual([2, 2, 2]); + expect(d.ratioSum).toBe(6); + expect(d.phasorMul).toBe(2); + expect(d.phaseOff).toBe(0.5); + expect(d.ampRatios).toEqual([2, 2]); + expect(d.ampRatioSum).toBe(4); +}); + +test('decodeTrack extremes: 0 → minimum 1, ~1 → maximum 4', () => { + const lo = decodeTrack([0, 0, 0, 0, 0, 0, 0]); + expect(lo.ratios).toEqual([1, 1, 1]); + expect(lo.phasorMul).toBe(1); // muls[0] + expect(lo.phaseOff).toBe(0); + const hi = decodeTrack([0.99, 0.99, 0.99, 0.99, 0.5, 0.99, 0.99]); + expect(hi.ratios).toEqual([3, 3, 3]); // int(2.97)+1 + expect(hi.phasorMul).toBe(8); // muls[int(3.95)&3=3] +}); + +test('ratioSeq: phasor 0 is on (start of first segment), pulse-width boundary', () => { + const ratios = [1, 1, 1]; + const sum = 3; + expect(ratioSeq(0, sum, ratios, 0.5)).toBe(true); // beatPhase 0 ≤ 0.5 + // Just inside segment 0: phaseAdj = 3*0.1 = 0.3, segment0 [0,1], beatPhase 0.3 ≤ 0.5 → on + expect(ratioSeq(0.1, sum, ratios, 0.5)).toBe(true); + // Late in segment 0: phaseAdj = 3*0.3 = 0.9, beatPhase 0.9 > 0.5 → off + expect(ratioSeq(0.3, sum, ratios, 0.5)).toBe(false); +}); + +test('clock advances a 4/4 bar at the set BPM and wraps', () => { + const seq = new RatioSeqEngine(); + seq.setBpm(120); // bar = (60/120)*4 = 2 s + expect(seq.phase()).toBe(0); + seq.advance(0.5); // quarter of a bar + expect(seq.phase()).toBeCloseTo(0.25, 6); + seq.advance(2.0); // a full bar later → wraps back to 0.25 + expect(seq.phase()).toBeCloseTo(0.25, 6); +}); + +test('evalTrack reports rising/falling edges across ticks', () => { + const seq = new RatioSeqEngine(); + seq.setBpm(120); + const d = decodeTrack([0, 0, 0, 0, 0, 0.99, 0.99]); // ratios 1,1,1; phasorMul 1; phaseOff 0 + // At phase 0 → gate on (rising on first eval). + const a = seq.evalTrack(0, d); + expect(a.gate).toBe(true); + expect(a.rising).toBe(true); + expect(a.falling).toBe(false); + expect(a.velocity).toBe(1); // ampRatios decode → high + // Advance past the pulse (into the off part of the cycle) → falling edge. + seq.advance(0.6); // 0.3 of the bar; phaseAdj = 3*0.3 = 0.9 > pw → off + const b = seq.evalTrack(0, d); + expect(b.gate).toBe(false); + expect(b.falling).toBe(true); + expect(b.rising).toBe(false); +}); diff --git a/manifold/src/backends/ratio-seq.ts b/manifold/src/backends/ratio-seq.ts new file mode 100644 index 0000000..cdcab0b --- /dev/null +++ b/manifold/src/backends/ratio-seq.ts @@ -0,0 +1,136 @@ +/** + * RatioSeqEngine — browser-side gate sequencer, a faithful TS port of the + * MEMLCelium / SLP-Workshop engine's internal ratio sequencer + * (`nisps/engines/memlcelium.hpp` + `ratio_seq` in `nisps/engines/breakor.hpp`). + * + * It turns the **rhythm** slice of the model output vector — 7 params per track, + * exactly as the C++ engine decodes outputs [0..13] into its 2 sequences — into + * clock-driven gate events. This is the gate generator the spec calls for so the + * CV and MIDI backends can emit gate sequences without running the audio engine + * (docs/slp-workshop/SPEC.md §2). Pure + framework-neutral; unit-tested. + * + * Per-track raw params (each 0..1, in this order): + * [0,1,2] ratios → int(p*3)+1 (1..4) + * [3] phasorMul→ {1,2,4,8}[int(p*3.999999) & 3] + * [4] phaseOff → int(p*4) * 0.25 ({0,.25,.5,.75}) + * [5,6] ampRatios→ int(p*3)+1 (1..4) + * + * Clock: a 4/4 bar phasor (matches `update_bpm`: bar = 4 beats); advance() moves + * it by dt/bar_seconds. Gate per track = `ratioSeq(seqPhasor, ratios, pw=0.5)`; + * a second ratio set picks a 2-level velocity (firmware parity: 127/64 → 1.0/0.5). + */ + +const PULSE_WIDTH = 0.5; // firmware parity (per-track pulse width is a deferred extension) +const VELOCITY_HIGH = 1.0; +const VELOCITY_LOW = 64 / 127; // ≈0.504, mirrors the engine's 64/127 +const PHASOR_MULS = [1, 2, 4, 8] as const; + +/** Decoded per-track sequence parameters. */ +export interface SeqParams { + ratios: [number, number, number]; + ratioSum: number; + phasorMul: number; + phaseOff: number; + ampRatios: [number, number]; + ampRatioSum: number; +} + +/** Per-track evaluation result for one tick. */ +export interface GateState { + /** Gate level — true while inside a pulse. */ + gate: boolean; + /** 2-level velocity / accent in [0,1] for the current pulse. */ + velocity: number; + /** Gate just went high this tick (note-on edge). */ + rising: boolean; + /** Gate just went low this tick (note-off edge). */ + falling: boolean; +} + +/** Decode 7 raw params (starting at `off`) into sequence params (matches set_params). */ +export function decodeTrack(p: ArrayLike, off = 0): SeqParams { + const q = (i: number) => p[off + i] ?? 0; + const r0 = ((q(0) * 3) | 0) + 1; + const r1 = ((q(1) * 3) | 0) + 1; + const r2 = ((q(2) * 3) | 0) + 1; + const a0 = ((q(5) * 3) | 0) + 1; + const a1 = ((q(6) * 3) | 0) + 1; + return { + ratios: [r0, r1, r2], + ratioSum: r0 + r1 + r2, + phasorMul: PHASOR_MULS[((q(3) * 3.999999) | 0) & 3], + phaseOff: ((q(4) * 4) | 0) * 0.25, + ampRatios: [a0, a1], + ampRatioSum: a0 + a1, + }; +} + +/** + * The ratio sequencer pulse test (port of `ratio_seq` in breakor.hpp): carve the + * cycle into segments proportional to `ratios`; the segment the phasor lands in + * is "on" for its first `pulseWidth` fraction. + */ +export function ratioSeq(phasor: number, ratioSum: number, ratios: ArrayLike, pulseWidth: number): boolean { + let offsetPhase = phasor; + if (offsetPhase >= 1) offsetPhase -= 1; + const phaseAdj = ratioSum * offsetPhase; + let accum = 0; + let last = 0; + for (let i = 0; i < ratios.length; i++) { + accum += ratios[i]; + if (phaseAdj <= accum) { + const beatPhase = (phaseAdj - last) / (accum - last); + return beatPhase <= pulseWidth; + } + last = accum; + } + return false; +} + +export class RatioSeqEngine { + private barPhasor = 0; + private bpm = 120; + private lastTrig: boolean[] = []; + + /** Set tempo (BPM, 4/4). */ + setBpm(bpm: number): void { + this.bpm = bpm > 0 ? bpm : 120; + } + + /** Reset the clock + per-track edge memory (e.g. on stop / reconfigure). */ + reset(): void { + this.barPhasor = 0; + this.lastTrig.length = 0; + } + + /** Advance the bar phasor by `dtSeconds` of wall-clock time. */ + advance(dtSeconds: number): void { + const barSeconds = (60 / this.bpm) * 4; // 4/4 + this.barPhasor += dtSeconds / barSeconds; + if (this.barPhasor >= 1) this.barPhasor -= Math.floor(this.barPhasor); + } + + /** Current bar phasor (0..1), for visualisation. */ + phase(): number { + return this.barPhasor; + } + + /** + * Evaluate one track. `idx` keys the rising/falling edge memory; `params` are + * already decoded (call {@link decodeTrack} on the rhythm output slice). + */ + evalTrack(idx: number, params: SeqParams): GateState { + let seqPhasor = this.barPhasor * params.phasorMul; + seqPhasor = (seqPhasor + params.phaseOff) % 1; + const trig = ratioSeq(seqPhasor, params.ratioSum, params.ratios, PULSE_WIDTH); + const highAmp = ratioSeq(seqPhasor, params.ampRatioSum, params.ampRatios, PULSE_WIDTH); + const prev = this.lastTrig[idx] ?? false; + this.lastTrig[idx] = trig; + return { + gate: trig, + velocity: highAmp ? VELOCITY_HIGH : VELOCITY_LOW, + rising: trig && !prev, + falling: !trig && prev, + }; + } +} diff --git a/manifold/src/backends/useBackendManager.ts b/manifold/src/backends/useBackendManager.ts index a8ab2f8..38076c1 100644 --- a/manifold/src/backends/useBackendManager.ts +++ b/manifold/src/backends/useBackendManager.ts @@ -72,6 +72,7 @@ export function useBackendManager( midiSettings: MidiSettings, oscSettings: OscSettings, vcvSettings: VcvSettings, + bpm: number, ): UseBackendManager { const managerRef = useRef(null); const [status, setStatus] = useState({ state: 'idle', message: 'idle' }); @@ -154,13 +155,15 @@ export function useBackendManager( vcv.setVcvConfig(specs, { url: vcvSettings.url, sendRaw: vcvSettings.sendRaw }); }, [manager, params, vcvSettings.url, vcvSettings.sendRaw]); - // Push per-output uSEQ CV config (channel + gate threshold) whenever it changes. + // Push per-output uSEQ CV config (channel + gate source/track/threshold) and + // the gate-sequencer tempo whenever they change. useEffect(() => { const cv = manager?.cv(); if (!cv) return; const specs: CvSpec[] = params.map((p, i) => (p.cv as CvSpec | undefined) ?? defaultCvSpec(i)); cv.setCvConfig(specs); - }, [manager, params]); + cv.setBpm(bpm); + }, [manager, params, bpm]); const cvConnect = () => void manager?.cv()?.connect(); const cvIdentify = () => manager?.cv()?.identify(); diff --git a/manifold/src/console/ConsoleApp.tsx b/manifold/src/console/ConsoleApp.tsx index aca34b7..da5d522 100644 --- a/manifold/src/console/ConsoleApp.tsx +++ b/manifold/src/console/ConsoleApp.tsx @@ -287,6 +287,7 @@ export function ConsoleApp({ focus: initialFocus = 'composite' }: ConsoleAppProp { outputId: midiOutputId, ccCount: midiCcCount }, { url: oscUrl, sendRaw: oscSendRaw }, { url: vcvUrl, sendRaw: vcvSendRaw }, + bpm, ); // VCV bridge: forward a verdict op to the module's embedded learner. No-op diff --git a/manifold/src/console/model.ts b/manifold/src/console/model.ts index f17196a..625044f 100644 --- a/manifold/src/console/model.ts +++ b/manifold/src/console/model.ts @@ -45,8 +45,8 @@ export interface MFParam { osc?: { path: string; rangeMin: number; rangeMax: number }; /** VCV backend spec ({ bipolar }). */ vcv?: { bipolar: boolean }; - /** uSEQ CV/gate backend spec ({ channel, gateThreshold }). */ - cv?: { channel: string; gateThreshold: number }; + /** uSEQ CV/gate backend spec ({ channel, gateSource, seqTrack, gateThreshold }). */ + cv?: { channel: string; gateSource: 'sequence' | 'threshold'; seqTrack: number; gateThreshold: number }; } export interface MFMode { diff --git a/manifold/src/dock/BackendAdvanced.tsx b/manifold/src/dock/BackendAdvanced.tsx index 269df47..29771c9 100644 --- a/manifold/src/dock/BackendAdvanced.tsx +++ b/manifold/src/dock/BackendAdvanced.tsx @@ -9,7 +9,7 @@ * inline config in OutputsBackendConfig; both write the same store. */ import type { MFParam } from '../console/model'; -import type { BackendId, CvChannelId } from './output-state'; +import type { BackendId, CvChannelId, CvSpec } from './output-state'; import { CV_CHANNELS, defaultCvSpec, defaultMidiSpec, defaultOscSpec } from './output-state'; function num(s: string, fallback: number): number { @@ -296,7 +296,7 @@ function CvChannelEditor({ {params.map((p, i) => { - const c = (p.cv as { channel: CvChannelId; gateThreshold: number } | undefined) ?? defaultCvSpec(i); + const c = (p.cv as CvSpec | undefined) ?? defaultCvSpec(i); const isGate = c.channel.startsWith('gate'); return ( diff --git a/manifold/src/dock/OutputsBackendConfig.tsx b/manifold/src/dock/OutputsBackendConfig.tsx index 2ad824d..10946ad 100644 --- a/manifold/src/dock/OutputsBackendConfig.tsx +++ b/manifold/src/dock/OutputsBackendConfig.tsx @@ -17,7 +17,7 @@ */ import { useEffect, useState } from 'react'; import type { ConsoleCtx } from '../console/types'; -import type { BackendId, CvChannelId } from './output-state'; +import type { BackendId, CvChannelId, CvSpec } from './output-state'; import { CV_CHANNELS, defaultCvSpec, defaultMidiSpec, defaultOscSpec, defaultVcvSpec } from './output-state'; import { applyPreset, @@ -648,19 +648,23 @@ function CvConfig({ ctx }: { ctx: ConsoleCtx }) { model output to a CV jack or gate. 11 CV (3 main + 8 expander) + 3 gates, streamed at 100 Hz.

- Per-output channel · gate threshold + Per-output channel · gate source +

+ Gate channels run a clock-driven Sequence (RatioSeq, tempo = app BPM) whose 7 params come from rhythm + outputs [track×7…]; or Threshold a continuous output. CV channels carry the mapped value. +

- + {ctx.params.map((p, i) => { - const c = (p.cv as { channel: CvChannelId; gateThreshold: number } | undefined) ?? defaultCvSpec(i); + const c = (p.cv as CvSpec | undefined) ?? defaultCvSpec(i); const isGate = c.channel.startsWith('gate'); return ( @@ -679,21 +683,57 @@ function CvConfig({ ctx }: { ctx: ConsoleCtx }) { ))} - ); diff --git a/manifold/src/dock/output-state.ts b/manifold/src/dock/output-state.ts index 74d66ed..bffb9ec 100644 --- a/manifold/src/dock/output-state.ts +++ b/manifold/src/dock/output-state.ts @@ -107,7 +107,16 @@ export const CV_CHANNELS: readonly CvChannelDesc[] = [ export interface CvSpec { /** Physical uSEQ channel this output drives, or 'none' to skip it. */ channel: CvChannelId; - /** For gate channels: gate goes HIGH when the mapped 0..1 value ≥ this. */ + /** + * For GATE channels: how the gate is produced. + * - 'sequence' → a clock-driven RatioSeq track (the rhythm stream; the + * track's 7 params come from outputs [seqTrack*7 .. +6]). + * - 'threshold' → the continuous stream: gate HIGH when mapped value ≥ gateThreshold. + */ + gateSource: 'sequence' | 'threshold'; + /** RatioSeq track index driving this gate when gateSource==='sequence'. */ + seqTrack: number; + /** Threshold on the mapped 0..1 value when gateSource==='threshold'. */ gateThreshold: number; } @@ -185,5 +194,7 @@ export function defaultVcvSpec(): VcvSpec { */ export function defaultCvSpec(index: number): CvSpec { const ch = CV_CHANNELS[index]?.id ?? 'none'; - return { channel: ch, gateThreshold: 0.5 }; + // Gate channels default to the rhythm stream (RatioSeq), one track per gate. + const gateNum = ch.startsWith('gate') ? parseInt(ch.slice(4), 10) - 1 : 0; + return { channel: ch, gateSource: 'sequence', seqTrack: gateNum, gateThreshold: 0.5 }; }
Output uSEQ channelGate ≥Gate source
- - ctx.setParam(i, { - cv: { ...c, gateThreshold: Math.max(0, Math.min(1, num(e.target.value, c.gateThreshold))) }, - }) - } - /> + + {isGate ? ( +
+ + {c.gateSource === 'sequence' ? ( + + ) : ( + + )} +
+ ) : ( + — CV — + )}