Skip to content

Latest commit

 

History

History
1307 lines (1201 loc) · 84.4 KB

javascript.md

File metadata and controls

1307 lines (1201 loc) · 84.4 KB

JavaScript Strudel and native audio

Tompouce now embeds QuickJS and the upstream Strudel 1.2.6 core, mini, tonal, and transpiler packages. JavaScript builds and queries patterns; the native audio callback synthesizes and processes sound in C. Node.js is a build tool for updating the bundled libraries, not a runtime dependency.

Writing code

setcpm(128 / 4)
const melody = n("0 2 4 <6 7>").scale('D:minor')
const brighten = p => p.hpf(180).lpf(sine.range(500, 5000).slow(4))
$: brighten(melody.s('supersaw')).fm(1.5).room(.3).pianoroll()
$: s("bd sd, hh*8").sometimes(x => x.ply(2)).crush("<16 8>")

The upstream implementation supplies pattern constructors, time transforms, conditionals, arithmetic, alignment, scales, voicings, and signals. Integer fraction arithmetic on the pattern clock runs in the host. tri, itri, and their bipolar forms, with numeric fast, slow, early, late, and range, are sampled in the host too. Saw, sine, square, and noise stay in JavaScript. JavaScript-only reference runners leave these signal objects and pattern prototypes untouched when native signal hooks are absent; no native-hook mock is needed to import the runtime or query its live controls. Ordinary fraction clones, cycle bounds, span intersections/splitting and hap value/span transformations also have native paths. Custom objects, accessors and values beyond the native integer range retain the JavaScript paths. Fractional numbers and fraction strings still use the pinned fraction.js parser. Ordinary pure() queries also have a bounded host path that creates fresh cycle spans, haps and contexts. Common keys in ordinary control records are computed without repeatedly enumerating the right record. These build-time hooks require the exact pinned source; JavaScript-only hosts keep the original queries. Custom prototypes/builtins and unsupported spans retain the JS paths. Variables, closures, functions, arrays, loops, and async functions execute as JavaScript. Double quoted strings and backticks use Strudel mini-notation; single quoted strings remain ordinary strings. $: plays concurrent patterns. Named labels also work; a leading or trailing underscore mutes a label. Prefix a label with S to solo it (S$: or Sdrums:); multiple solo labels play together and exclude ordinary branches. A label consisting only of S does not solo. Registered labels are available through pattern-state id. all transforms the combined pattern; each transforms each collected branch, or the final pattern when there are no registered branches. Several statements can share a line, and statements and strings can span editor lines.

slider(value,min,max,step) supplies a live control pattern. Register it with F5 once, then use Ctrl+Left/Right or drag its chip. Changes update upcoming note parameters without reevaluating source, resetting cycle phase, retriggering held notes or applying unrelated editor changes. The first numeric argument updates in the editor, so saving the song saves the performed value too. Parsed source locations keep the controls attached after edits; comments and strings cannot register controls. New controls require F5 before they are live. Each successfully loaded program owns its bindings, so a failed evaluation cannot replace the playing program's controls. F5 reads the source values again, as in the web REPL. Direct calls create live widgets. Aliases such as const control=slider; control(.5) and member calls return a fixed pure() pattern and emit the web fallback warning. For live arithmetic, use pattern operations such as slider(700,200,3000,100).mul(2); ordinary JavaScript numeric coercion of a control Pattern is not supported. Top-level setcpm/setcps read numeric or Pattern arguments once at evaluation; moving a slider inside setcpm(slider(30)) requires F5 to change tempo. Use .cps(slider(...)) for query-time global tempo changes. A Pattern-valued .cpm(...) transform uses current scheduler CPS; numeric .cpm(...) keeps evaluation-time scaling, matching the web helper.

midin(input?) opens an ALSA sender for MIDI controller input and returns a per-CC live reader, mirroring the upstream input package: cc(0) reads the most recently received value normalized 0..1 (optionally restricted with a 1..16 channel), defaulting to 0 with no input. midikeys(input?) returns live keyboard notes with fixed durations like the web helper (kb() defaults to 0.5, pattern arguments scale durations; note, velocity and 1..16 midichan travel with each hap). Values merge across senders into one store; Pattern input is rejected, and midikeys rejects a missing device while midin keeps default readers. Held notes sound on the next scheduled window after arrival, like live slider moves, and fire once: audio queries consume, visual queries peek without consuming pending notes. A missing explicit device does not fall back to an unrelated connected sender. Input names accept client:port, numeric client ids and device-name substrings (a bare call tries the first sender); without a sender, connect one with aconnect. CC values persist per string sender name across restarts and load as reader defaults on open (numeric opens never persist); on (re)connect the stored values are addressed only to the device's writable port, restoring motorized controls like the web input, and replugged devices are resubscribed by client name. Native readers handle CC and note-on messages. cmake --build build --target test-midi-input-reference-web compares the input path against the deployed REPL through fake ports (scripts/midi-input-reference-qa.mjs plus a --midi-input-reference driver mode): CC values, channels, normalization and defaults, keyboard note values/counts/tags, seeded and corrupt persistence round-trips, drop/resume across disconnect/reconnect and error paths all hold. Two divergences are locked explicitly rather than matched: the web isolates stores per device while native merges senders (correction would break the merged semantics native gates depend on), and the web files every message byte into its CC store (notes zero it on noteoff) while native keeps CC/notes/bend paths separate. Native ALSA tests cover these features alongside the web gates.

JavaScript playback uses the web scheduler's 50 ms query windows, 100 ms timer and overlap, and 100 ms output latency. Already submitted notes keep their values; the next query reads the new control. This applies equally to native audio, MIDI, OSC and Csound. External tempo changes pivot at the next unqueried fractional cycle, and evaluation while playing preserves that clock and the pending notes. Held native voices and effect tails continue. Csound evaluations share one Csound renderer, preserving sounding instances and loaded definitions across changed or omitted orchestra loads. Inline loads execute again on each evaluation; URL loads are cached after compilation, including github: aliases. Orchestra calls apply in order. Like the browser, an orchestra syntax error is reported in the console without rejecting an otherwise valid musical pattern. JavaScript exceptions, failed fetches and host failures still reject evaluation.

Event .cps() follows the current live web scheduler: tempo controls are sorted before simultaneous notes, the change takes effect at its onset, and the rest of the query window is recomputed at the new tempo. Zero tempo pauses cycle advancement while sounding notes continue. As in the web REPL, a slider cannot resume its own zero-tempo pattern because there are no advancing queries; use an external BPM change or evaluate a positive setcps/setcpm value. There is no hidden 20–400 BPM clamp. Negative or non-finite tempos are rejected.

Shared delay uses the web limit of one second and default feedback of .5. Zero delay time or feedback suspends new sends and parameter updates while existing shared tails continue. Parameter decisions use the web's current Float32 AudioParam value at preparation time; a future return value can be skipped when it already matches that current value. Accepted delay automation survives source removal or voice stealing, including zero-gain events. JavaScript delay taps interpolate fractional samples, including sub-sample times. Feedback repeats include the web graph's additional 128-frame cycle delay. Legacy direct-event delay keeps its original timing.

Stop ends new scheduling and resets the next start to cycle zero. Already submitted notes and sounding envelopes/effect tails finish, as in the web REPL. F5, Ctrl+Enter, Alt+Enter, Ctrl+R in insert mode and :eval evaluate the current editor source and start a stopped transport only when evaluation succeeds. Ctrl+P and /play from stopped also evaluate pending editor text before starting, matching web Play. Committed notes survive Stop/evaluate/start; failed evaluation retains the prior pattern and transport state. Companion Apply, Evaluate and Play from stopped use the companion's current source with the same success-only activation. MCP music_set_code and music_evaluate expose optional autostart: true; their default remains false. Cold sound preparation that misses its onset starts the note immediately if gate time remains, shortening its duration to retain the original note-off deadline. Notes whose gate has already ended are skipped.

The terminal editor accepts the Strudel REPL shortcuts: Ctrl+Enter or Alt+Enter evaluates and starts playback; Ctrl+. or Alt+. stops without restarting an already stopped transport. Alt+W and Alt+Q jump to the next/previous literal $, wrapping at either end, just like the web editor (including $ inside strings and comments). Evaluation and stop work in vi normal mode too. Prompts and pickers keep their own input handling. Ctrl+Enter and Ctrl+. require a terminal that reports modified keys distinctly; Alt+Enter and Alt+. also accept traditional Escape-prefixed encoding. Plain Enter continues to insert a newline. F5 and Ctrl+P remain available.

The source editor automatically pairs parentheses, square brackets, braces, single/double quotes and backticks while typing, including in vi insert mode. Typing a closer the editor inserted moves over it; manually loaded or pasted closers remain ordinary text. Backspace between an empty matching pair removes both characters. Typing an opener around a selection wraps it and keeps its contents selected. Quote handling respects escapes and avoids adding pairs inside words or when closing the same kind of string. Brackets pair at the end of a line or before whitespace or )]}:;>; angle brackets retain their JavaScript comparison meaning. Paste, completion snippets, prompts and reference searches remain literal. Pair edits use the normal undo history and never evaluate the musical source.

Enter preserves the current indentation and adds a two-space level inside JavaScript blocks, arrays and calls. Between empty matching brackets it opens an indented line and puts the closing bracket on a separate line. Typing a closer on a whitespace-only line aligns it with its opener; a generated closer on the following line is reused. Vi o and O also open indented lines. Indentation reads bounded Tree-sitter syntax, ignoring brackets in strings, comments and regular expressions; very large or deep input falls back to the current line's indentation. Pasted text retains its original indentation.

Alt+H or Shift+F1 opens the offline Strudel reference in the right pane. /reference slow in the F2 prompt (or :reference slow in vi mode) opens a search directly. Type to filter function names, aliases and descriptions; exact names and aliases come first. Up/Down selects a result, PgUp/PgDn or the mouse wheel scrolls its description, parameters and examples, Backspace edits the query and Ctrl+U clears it. Click a result to select it. Tab or Escape returns to editing while leaving the reference visible; click the reference pane to resume searching. Alt+H/Shift+F1 closes it, and F1 switches to the existing keyboard help. Searching and viewing examples never change or evaluate the editor source.

Reference prose comes from the installed, lockfile-pinned Strudel 1.2.6 source documentation and JSDoc alongside Tompouce's embedded runtime implementations (444 documented entries, including 39 runtime entries). Runtime documentation covers sliders, visualizations and their underscored aliases, pattern branches, MIDI/OSC routing, sample maps, tempo helpers, Csound and native synthesis. It includes parameters, return values and examples. Native descriptions take precedence over upstream descriptions of the same API, including aliases. The K/S source transforms and sFreq/sGate graph symbols are searchable too. Case-matching exact names rank first, so s and S select their own entries. Names without authored documentation remain listed and say so explicitly. The compiled catalog works offline; it does not fetch documentation while performing. It describes upstream APIs, rather than certifying native audio parity for every control. Regenerate it with node js/reference.mjs after installing the pinned JavaScript dependencies; --check verifies the committed catalog. npm --prefix js run build also refreshes it. New public helpers in js/runtime.mjs and js/native-synth.mjs can supply @name, @synonyms, @param, @returns and @example JSDoc for the same generator.

Native voices are prepared ahead of playback and wait for their scheduled timestamp. Their source position and envelope remain frozen until onset; cut groups, ducking and orbit delay settings take effect at that timestamp. Offline callback tests check the exact first sample and chronological cut ordering independently of voice-slot order.

The live pattern uses upstream ref(), matching the web REPL's slider implementation. live_controls_reference compares 135 queries against the pinned upstream implementation, including gain, pan, filter, arithmetic, masks, speed, effects and long notes. It also compares the native scheduler's event times, durations, pitches and gains against upstream Cyclist through live slider, tempo and pattern changes. A test-only snapshot of the current web scheduler additionally compares 30 finite native note schedules and 11 clock states through simultaneous tempo controls, pause/resume and stop/start. cmake --build build --target test-controls-reference-web verifies the snapshot against the deployed strudel.cc scheduler in a disposable browser, including failed evaluation and source lifetime on Stop. It never produces real audio. The pattern library and its historical event baselines stay pinned. cmake --build build --target test-csound-reference-web checks Csound lifecycle against the deployed loaders and actual Csound WASM in private offline contexts, including held PCM, redefined instruments, globals, syntax errors and URL caching. Native tests also check exact note onset, idle-session retention and confinement of the compiler thread. No orchestra compilation runs in the native audio callback. The default step matches the web widget's range divided by 1,000. These gates establish the tested control behavior; they do not establish complete browser audio, device or synthesis parity. Ordinary sliders do not continuously modulate already sounding voices in the web REPL; adding that behavior here would require a separate feature. F4's output Volume slider is a separate final-bus control: it scales held voices, Csound and effect tails immediately without changing source or running JavaScript. F2 /volume .5 sets half amplitude; /volume 1 restores unity. The level persists across evaluations and song changes for the current process. Alt+Up/Down raises/lowers output volume by 1% from any pane, including prompts and the fullscreen visualizer, even when F4 is closed. See prebake support for the Switch Angel Volume widget mapping.

Imports resolve the bundled modules:

import { note as tone } from '@strudel/core'
const { scale } = await import('@strudel/tonal')
tone("c4 e4 g4").slow(2)

@strudel/transpiler is also available as a bundled module. Arbitrary npm packages and remote module URLs are not resolved. Local ES modules can live in $XDG_CONFIG_HOME/tompouce/modules (default ~/.config/tompouce/modules):

import { melody } from './melody.mjs'
const { rhythm } = await import('local:rhythm.mjs')
stack(melody(), rhythm())

Local modules use ordinary JavaScript module syntax and can import bundled packages or sibling ./ modules. Parent traversal, absolute paths, symlinks, and files over 256 KiB are refused. Load modules during top-level evaluation; new local module loading is disabled during pattern queries. Modules are isolated to each compiled program and refreshed on reevaluation. This is an embedded ECMAScript host, not Node.js or a browser: there is no filesystem/process API, DOM, WebAudio, Hydra, or browser input-device API. Additional JavaScript modules require an explicit addition to the bundle.

Prebake setup files can register reusable helpers before song evaluation. Load named files with await loadPrebake('helpers.strudel'), or use ~/.config/tompouce/prebake.strudel for automatic setup. An opt-in pinned Switch Angel starter is available with tompouce --install-prebake switchangel.

JavaScript Strudel is the only source language. The historical C mini/statement parser and bpm / drum / notes / | transform line dialect have been removed. Use setcpm(BPM / 4), s("bd sd"), note("c4 e4") and JavaScript method chains. Retired syntax reports an evaluation error and retains the last playable program. Quoted mini-notation remains supported by the upstream Strudel runtime.

Native audio coverage

The following resolved Strudel controls are consumed by the C backend; their arguments can be patterns or signals because Strudel resolves them per event. Aliases registered by upstream Strudel map to the same controls.

Area Implemented in C
Sources sine, triangle, sawtooth, square, pulse, supersaw/unison/stereo spread, white/pink/brown noise, procedural wt: tables, local and remote samples, ZzFX, bytebeat, bounded Kabelsalat graphs
Harmonics numeric n (up to 2,047 represented harmonics); partials and phases (32 explicit entries), normalized and bandlimited
Amplitude gain, velocity (multiplied through 16, same ceiling as gain), amp, busgain, overgain, ADSR, clip/legato, duration, postgain, pan, dry
Filters low/high/band-pass, their Q values and ADSR/depth envelopes, fanchor, 12 dB / 24 dB filters and nonlinear low-pass ladder, vowel/formant filtering
Filter LFOs lp/hp/bp rate, sync, depth, depthfrequency, shape, dc, skew
Modulation pitch ADSR/anchor/curve, vibrato, pulse-width rate/sweep, tremolo/sync/depth/skew/phase/shape
FM eight operators with index, harmonicity, ADSR, envelope type, waveform, and operator-to-operator routing
Color/dynamics coarse, crush, shape/shapevol, distortion/type/volume, compressor threshold/ratio/knee/attack/release
Spatial chorus, phaser rate/depth/center/sweep, delay/send/time/sync/feedback, reverb/send/roomsize
Samples sound/bank/index selection, pitch matching, forward/reverse speed, begin/end, looping/loop bounds, cut groups, unit c, upstream chop/slice/fit/loopAt transforms
MIDI note events and midichan through the existing ALSA output
OSC timestamped UDP /dirt/play through .osc()

Generic Strudel .lfo() modulation is implemented for gain, filter cutoff, source frequency (s), pan, tremolo rate/depth/skew/sync, coarse, crush, shape/shapevol, distort/distortvol/distorttype, vib/vibmod, pw/pwrate/pwsweep, vowel, detune, wavetable position/warp rate/depth/skew, delay send, room send, phaser rate/center/sweep/depth and postgain. All follow the deployed lfo-processor semantics: defaults rate=1 depth=1 dcoffset=-0.5 triangle skew=.5 curve=1, depth scaling by the target value (1 when the target is 0), sync as cycles-per-second multiples, shapes triangle/sine/ramp/saw/square, and output clamping ([20-base, 24000-base] for audio-rate frequency targets at or above 30 Hz). Non-finite pow(curve) output reads the target AudioParam default instead of adding (gain 1.0, frequency 440, detune/pan 0), matching the deployed node sample-for-sample. Like the filter path, voice LFOs hold their static values for the render quantum containing the voice start (the deployed worklet leaves its first block unwritten while the absolute phase stays frozen); this closes the FM phase gap outright. A bare .lfo() targets the control immediately before it, so s("saw").lfo().lpf(800) is a source-frequency LFO and s("saw").lpf(800).lfo() is a cutoff LFO. Gain uses the same additive worklet math against the voice gain, on synth and sample voices alike. Sample voices use the deployed detune fallback: a source LFO bends transport in cents (base 1, inaudible at the default depth, exact at 1.0/1.0002). Pan requires an explicit .pan() (as upstream requires the pan node) and recomputes the equal-power StereoPanner split every sample; it gates at 0.99977 correlation. Cutoff maps onto the sample-rate scalar filter path. The steady cutoff response is gated at 0.99977 correlation; only the first ~50 ms graph onset remains a comparison limit. Source-frequency LFO renders the tutorial vibrato shape (zero-crossing contour matches the deployed player); exact PCM under deep frequency modulation is still limited by onset/envelope modeling plus the naive native saw versus the browser's bandlimited oscillator (RMS ratios sit near 1.0, so this is not gain staging). Voices with active voice LFO slots bypass the SoA batch lanes and render per sample, since the lanes have no slot support. Remaining targets (delaytime/delayfeedback, compressor params, busgain, stretch, bus modulators, FM indices/ratios, djf/transient and controls with no upstream routing such as overgain) keep their static value and log one warning naming the unsupported target per program. Nested LFO controls (lfo, lfo_rate, …) warn on both sides: generic LFO nodes register as lfo_<id>, so the plain lfo node upstream routing names does not exist. Generic tremolophase, wtdc/warpdc and dry match the deployed no-ops: phase and dc have no worklet params, and the dry gain node is wired but never registered, so both sides render static (lfo-tremolophase-inert, lfo-wtdc-inert, lfo-warpdc-inert, lfo-dry-inert); generic tremoloshape and wt/warp shape are recorded supersets (a float shape index crashes the deployed worklet to silence, while native steps the integer wave). Filter-specific lp/hp/bp LFO controls, pitch envelope/vibrato and pulse-width LFO are separate supported controls. Static tremolo and the phaser (single notch at center+282 Hz, Q from depth, detune in cents from its own triangle LFO) render natively; generic tremolo rate/depth/skew and every phaser param modulate them per sample. Voice targets take one slot per entry in encounter order (up to 8) and repeats sum in the renderer; each filter LFO type keeps the first entry. subControl and non-main fxi routings warn instead of misrendering. Short aliases (r sh sk cu s dep dr da dc rt) and retrig phase restart match the core sub-control table.

Generic .env() modulation is recognized, validated and logged, but never applied: the deployed connectEnvelope omits begin/end, so its worklet stays in the initial state forever and outputs zeros (verified flat against strudel.cc with and without explicit begin: 0, end: 2; the trigger needs begin to differ from the initial zero). Native matches the deployed silence exactly (env-inert-gain gates static PCM at 1.0/1.0002) and warns once per program. If the site ever wires begin/end through, the envelope-processor state machine (attack/decay/sustain hold/release with _warp curves and [min, max] clamp) can be evaluated per sample against the voice gate.

Reference: .reference/strudel (gitignored Codeberg checkout) packages/superdough/modulators.mjs (connectLFO), helpers.mjs (getLfo), worklets.mjs (LFOProcessor), superdoughdata.mjs (CONTROL_TARGETS), packages/webaudio/webaudio.mjs (render cycle argument) and packages/core/controls.mjs (aliases, bare-.lfo() targets the preceding control).

Native WAV, MP3 and FLAC sampling preserves stereo channels and recorded levels. Pitch-keyed maps accept arrays within each region; sample indices round and wrap with JavaScript semantics, including negative indices. Region selection preserves fractional pitches. Imported manifest banks (strudel.json folder imports) use the same nearest-region selection, with each recording played at its own pitch. Arrays allow up to 1,024 slots per name, with an overall 8,192-slot map guard. Decoded samples have a 120-second duration guard and a 256 MiB/256-sample cache guard; exceeding a decode/cache guard reports an error rather than silently truncating audio. MP3 decoding honors Xing/Info encoder delay and end padding before resampling, keeping note attacks aligned when samples are repitched. Files without gapless metadata retain their decoded duration.

Sample starts preserve fractional source position and envelope time at the first render frame, including fractional playback rates. Reverse stereo follows the deployed web REPL's buffer-copy behavior: the right channel has a leading zero and is displaced by one source frame. This applies before stretching too.

Native oscillators now use direct ADSR automation without the legacy envelope smoothing stage. Explicit panning follows equal-power mono and stereo folding conventions; omitted panning preserves unity upmix. Stock saw/square levels match the browser periodic-wave normalization. Stock saw and square discontinuities use polyBLEP corrections, and triangle starts at the sine phase. The maintained browser comparison covers representative waveforms and effects; broader parameter and full-song parity remains unverified.

pulse uses the REPL's feedback oscillator, including its startup smoothing, 128-frame render-quantum behavior, stereo panning and pulse-width triangle LFO. Setting only pwrate supplies the web's .3 sweep default; setting only pwsweep supplies a 1 Hz rate. Pulse is distinct from square.

Pitch envelopes support linear .pcurve(0) and exponential .pcurve(1) ramps in detune cents, including anchors, negative depths, short gates and release. Exponential ramps follow WebAudio's zero/sign-crossing behavior; they are not a squared linear envelope. Nineteen browser audio gates cover selected oscillator pitch/vibrato cases. Eight additional shared-PCM sample gates cover linear/exponential pitch, vibrato, release, fractional starts, stereo and reverse playback. Sample detune updates once per 128-frame quantum; its first automation evaluation clamps past events to that boundary, matching Chromium. The computed ratio is cached per quantum. Twelve full-player worklet cases cover selected pulse/supersaw pitch/vibrato/release and a Kabelsalat source. Pulse and supersaw start in the first quantum whose head is later than their Float32 begin parameter; supersaw phases stay still before then. Kabelsalat graph sources retain their own frequency/gate logic: pattern pitch controls on the replaced source do not automatically modulate sFreq. Five FM/frequency gates cover harmonicity-scaled depth, carrier pitch envelopes/vibrato, static detune and fractional onset. FM modulators retain their base frequency when carrier pitch automation changes, and have no amplitude envelope unless FM ADSR controls are supplied. Their first render quantum follows the carrier's a-rate array alignment. Nine further browser gates cover explicit FM ADSR defaults, linear and exponential ramps, zero-length segments and gates ending during attack or decay. FM defaults to exponential ramps with the REPL's segment minima and decay-dependent sustain default. Thirteen matrix gates additionally cover selected sine-modulator chains, parallel/cross sends, operator 8, signed indices/harmonicity, numbered envelopes and feedback. .fm2(x) sends operator 2 into operator 1; .fm20(x) sends it directly into the carrier. .fm13(x) sends operator 1 into operator 3. An operator disconnected from the carrier has no audible effect. Matrix sends modulate frequency, not phase. Fixed per-voice 128-frame buffers preserve dependency order and feedback history without callback allocation. Eight waveform gates cover triangle, square, sawtooth and white/pink/brown modulators (correlations 0.99074–0.9999996, RMS ratios 0.94389–1.00847). Triangle, square and sawtooth follow the polyBLEP oscillator; noise loops the shared two-second buffers and has no frequency input. Six onset gates combine envelopes with late starts (0.99015–0.9999996, RMS ratios 1.00108–1.01167). An enveloped operator that feeds another operator advances through the silent head of the onset quantum at gain 1. Four cyclic graphs exceed 0.9999996 correlation, and five frequency-boundary gates exceed 0.999992, all on the same 0.99/RMS gates. A sine at ±Nyquist is silent. From Nyquist/2^(1/3) up to that rail its level is 3·log2(Nyquist/|f|), and phase keeps advancing at the clamped frequency.

Static detune controls unison spread where supported; it does not transpose basic oscillators or samples. Five further browser gates cover sine, triangle, sawtooth, square and a shared-PCM sample. Use note, freq or sample speed for transposition; penv and vib still automate pitch.

On basic waveforms, numeric n selects the number of harmonic coefficients; zero retains the stock oscillator. partials overrides n. Custom waves use the web's coefficient signs, phase rotation, peak normalization and frequency bands. The existing 32-entry bound for explicit arrays is enforced with a diagnostic rather than silently truncating a waveform. Invalid counts and preparation failures reject the affected source, retaining accepted voices. Prepared waves share a process-lifetime cache bounded to 256 entries / 64 MiB; the callback only reads those immutable tables.

.noise(amount) blends pink noise into basic oscillators using the REPL's dry/wet curve, before amplitude envelopes and effects. Standalone white, pink and brown sources and oscillator noise share prepared two-second looping buffers, including fractional starts. Noise buffers use a deterministic random stream; the REPL chooses its buffer randomly on first use. Comparisons seed the web buffer to isolate algorithm, gain and timing differences.

Zero-gain events remain silent but still prepare their sources and apply shared effect controls. Sample cut groups fade the previous sampled sources over 10 ms before their effects, retaining their original graph lifetimes. As in the web REPL, oscillator sources ignore cut.

This is not complete WebAudio/SuperDirt sound parity. ZzFX, bytebeat and a bounded Kabelsalat graph host are implemented natively (see below). Sample pitch compensation and custom convolution impulses are now native (see below). Separate orbits and ducking are implemented. The native DSP algorithms are not promised to produce bit-identical WebAudio output. tests/test_dsp.c compares the bandlimited saw with its Fourier series and checks ADSR breakpoints. tests/test_audio.c checks orbit delay time and duck depth. It also checks sample release tails, explicit duration gating, reverse slices, looping through release, and effects on both stereo channels.

ZzFX, bytebeat and Kabelsalat

Like the REPL, ZzFX and bytebeat use their source frequency without applying detune, penv or vib controls. Six independent browser comparisons cover these controls on z_sine and a custom bytebeat expression; this does not establish equivalence for every ZzFX preset or frequency combination.

note("c3 e3 g3").s('z_sawtooth').zrand(0).slide(.1).zdelay(.05)
note("c3 e3").s('bytebeat').bbexpr('t*(t>>15^t>>66)').bbst(0)
note("c3 e3 g3").K(sine(sFreq).mul(sGate.adsr(.001,.1,.5,.1)).out())
note(60).s('saw').K(audioin().fold(.5).out())

ZzFX supports zzfx, z_sine, z_triangle, z_sawtooth, z_square, z_tan and z_noise, the 20-value .zzfx([...]) parameter array and the corresponding named controls. Its internal envelope is applied once; ordinary native effects remain available. Random frequency variation is chosen during voice preparation. Sounds are limited to 30 seconds, with at most two seconds of internal delay.

Bytebeat provides the 15 upstream presets (s('bytebeat:N') or .n(N)), custom bbexpr/byteBeatExpression and bbst/byteBeatStartTime. Arithmetic, bitwise operators, comparisons, logical/conditional expressions and standard numeric Math functions compile to native operations with JavaScript 32-bit bitwise semantics. Its startup follows the reference worklet's 128-frame quantum. Assignments, loops, arrays, object access and arbitrary JavaScript functions inside a bytebeat expression are rejected; expressions are at most 4,096 bytes.

K(...) uses the pinned Kabelsalat graph constructors, including Strudel S(...) inputs and mini-notation placeholders. sFreq resolves per event and sGate tracks its gate. Like the web worklet, audioin() reads the first input channel into one graph; .out() supplies both output channels by default. Use explicit .out(0)/.out(1) calls for separate graph outputs. Sources and effects support stereo output channels 0/1, arithmetic/math, ranges, oscillator/noise nodes, ADSR, filters, lag/slide/slew, fold/distortion, clocks, triggers, sequences, hold and delay. Feedback requires a delay; device input, MIDI/mouse nodes, custom UGens and raw JavaScript nodes are unavailable. Unsupported nodes are rejected during compilation. This is a native adaptation rather than a complete browser host. K(...) graph sources replace the oscillator or sample. Pattern ADSR stays on those replaced sources and is not applied again to the graph. Use sGate ADSR inside the graph. Startup follows the browser generic processor: a 128-frame quantum whose start is still before the onset stays silent and does not advance the graph, then the whole next quantum plays. sGate stays high for the quantum that contains the hap end and drops for the following quantum. Bytebeat keeps its own currentTime <= begin guard. audioin() effects run after the source envelope and before event gain, native filters and waveshaping. Both graph output channels receive the downstream effects independently, including when the input source is mono. .fxr(seconds) sets the cleanup deadline to the hap end plus the longer of the pattern release and that time, bounded to 0..60 seconds. Values at or below the pattern release add no fade. audioin() effects then feed silence through the graph. Graph sources keep running, with the gate low, and a linear fade runs from the pattern-release deadline to the effects deadline. Delay length does not extend either deadline. Accepted graphs retain their state across program changes and voice retirement. The cleanup and fade use the original hap end and the raw release control; natural sample endings do not move them. The source ADSR's minimum release is separate: .release(0).fxr(.005) still fades over five milliseconds after the hap end, while a naturally ending sample can leave a much later delay tail. Pattern-form FX(...) controls replay shared room/delay, filter, pan, coarse, shape, distort, postgain, phaser, tremolo, compressor, FM operator/envelope/matrix, IR/room and canonical numeric DSP controls; chorus is a no-op because the deployed player exposes no chorus control. Pattern filters and pan are post-source stages before source pan, so source controls and multiple FX arguments compose; each FX argument applies its own default 0.8 gain. Callable FX arguments are ignored by the current site and retain only that default gain, so native ignores their recorded steps. Pattern partials arrays flatten to a numeric control and FX loop windows are ignored by the site; parity gates cover both. Pattern shape and distort are post-source stages; pattern delay/IR sends are ignored, leaving source sends in force. FX room presence feeds a mono-left room send with the source R/L ratio held through the tail, with measured pan feed gains of 1.423 center, 1.86 half pan and 2.012 full pan; fx-overlap-source-room and the panned gate pass at 0.9999994/0.9938 and 0.9999991/1.00056. Source distortion follows the deployed expm1(distort) processor; source chorus is a no-op. Pattern ADSR and speed controls are ignored, leaving source values in force. Pattern note, n, s, bank and string ftype are ignored too, leaving source frequency, token and filter type unchanged. FX distorttype('fold') carries a post-source algorithm variant and passes at 0.99999999/1.00065. The graph/effect boundary is covered: a K() source does not receive the chain's default gain, while audioin() worklet effects and ordinary sources do.

Programs have at most 256 operations and 16 inputs per operation. The cache holds 256 programs and evicts unreferenced entries; queued events and sounding voices keep their programs alive. Graph delay lines allow at most two seconds per node and 262,144 total samples per voice. Native voice state is allocated before taking the voice lock and has a shared 64 MiB budget. Neither preparation, allocation, cache eviction nor JavaScript execution occurs in the callback.

Live LV2 instruments

s('lv2:<uri>') uses a scheduler-owned live instance when the plugin reports MIDI input and no audio input; effects keep the offline path. The instance runs in a confined worker with a bounded render thread, stereo ring and note/CC queue. Pattern.lv2param(name, value) sets an input control port by its display name (case-insensitive, clamped to the declared range) and accepts a number, slider or pattern. Pattern.lv2preset(name) loads an installed preset by URI or display label and applies its declared control-port values without retriggering. Pattern.lv2state(name) loads an LV2 state file from $XDG_CONFIG_HOME/tompouce/lv2-state (or $TOMPOUCE_LV2_STATE), restores its plugin properties and maps declared control-port values to the same sliders. Without a note these methods only change parameters, so a separate long note keeps sounding. Control, preset and state changes are applied between 256-frame blocks. test_live_lv2 and test_lv2_worker cover the metadata, timing, queue bounds, preset/state loading and sanitized worker.

Managed Carla projects

Pattern.carla(project, target) manages a bounded Carla project from a pattern. The project is resolved under $XDG_CONFIG_HOME/tompouce/carla (or $TOMPOUCE_CARLA_ROOT) and the engine starts one owned process without loading plugin code itself. A background thread links the normal ALSA MIDI output, exposed by PipeWire as Midi-Bridge:<client>:out (capture), to <target>:events-in; target defaults to the first plugin name in the project. Combine it with .midi():

note("c4 e4 g4").ccn(7).ccv(0.8).midi().carla('sf2.carxp', 'sf2synth')

Stopping transport or shutting down the engine terminates and reaps the owned processes. Startup/link retries never run in the audio callback; the first cycle may begin before Carla is ready. test_carla_host and the real tests/test_managed_carla.py cover bounds, process lifecycle, the MIDI link and non-silent project output.

OSC output

note("c4 e4 g4").s('superpiano').osc()
s("bd sd").oschost('127.0.0.1').oscport(57120).osc()

.osc() routes a pattern exclusively to native UDP OSC, defaulting to 127.0.0.1:57120. Each hap becomes a timestamped OSC bundle containing a /dirt/play message with alternating control names and values, plus cps, cycle and delta. Note-name strings become midinote; numeric note values retain upstream OSC semantics. Bank names, room size and cycle-unit speed use the upstream conversions. No browser/WebSocket bridge or Node process is needed. Use another unmodified pattern branch if local audio is wanted too.

oschost accepts localhost or literal IPv4/IPv6 addresses; DNS names are unavailable. Packets are bounded to 2,048 bytes, 64 primitive key/value pairs, 48-byte keys and 512-byte string values. Invalid addresses, complex values and oversize packets are rejected with a console warning. Preparation runs on the generator; nonblocking sends run on the consumer and follow transport stop/start. With no local audio backend, a monotonic clock keeps external scheduling moving.

Unimplemented event controls are reported once per program in the console, rather than silently claiming that the sound effect exists.

samples(...) arguments are evaluated by JavaScript, including variables and computed maps, then handed to the existing C sample loader. Its URL checks, cache, decoder limits, and lazy audio downloads still apply. Default sounds use the installed Dirt-Samples strudel.json when available, overlaid with the bundled uzu-drumkit manifest used by the current web player. Missing uzu audio downloads lazily on first use; installed Dirt samples work offline. Installed dough-samples/piano.json and tidal-drum-machines.json register the default pitch-keyed piano and drum-machine banks too. Bare .s('piano') selects the nearest recorded pitch, and .bank('RolandTR909') uses manifest sample order. The pinned web drum-machine aliases resolve compact names such as tr505–tr909, Linn, DMX, MPC60, SP12, HR16 and 9000 to the installed machine directories; an explicitly installed directory with the compact name still wins. Explicit samples() maps take precedence. Without those installed manifests, load the catalogs explicitly with samples() (the .piano() helper also loads its map). VCSL and mridangam use the installed dough-samples/vcsl.json and mridangam.json, with recordings under VCSL/ and mrid/ at the bank root. Installed catalogs register by default. The installer includes them by default, along with the uzu-wavetables catalog and all valid pinned GM font variants. --core-banks opts into the smaller set. Supplemental local manifests preserve the REPL's mridangam_* and individual wt_digital_* names without renaming historical entries. Absent installed manifests still require explicit maps. Sample recordings are downloaded during installation rather than bundled in Git.

await initHydra(...) is accepted as an audio-only compatibility placeholder by the terminal runtime. It enables inert Hydra source/texture chains, s0–s3/o0–o3 buffers and H(), while musical branches continue to evaluate. Options such as feedStrudel and detectAudio are ignored by the terminal; there is no visual rendering, audio/video capture, resource fetching or execution of visual callbacks, and its a.fft is an inert zero buffer. analyze(id) and fft(exponent) on musical patterns are independent of the terminal placeholder: native events attach to up to 32 generation-tagged taps. fftSize follows Superdough's 2 ** (exponent + 5) mapping (default 8) and is capped by the 4096-sample analysis ring. music_audio_spectrum takes id 0 (master) or 1..32 and runs the Hann FFT in the MCP thread; taps never change the rendered PCM. The console points to /hydra once per evaluation. The placeholder does not open a browser; the separate /hydra browser visualizer renders a bounded Hydra-style graph through WebGL (all built-in generators and effects, camera/screen/image sources, and previous-frame feedback) and falls back to the 2D audio scope when no graph is set. The page reads the current source through the read-only music_get_code bridge when the source generation changes, evaluates its visual calls in the browser with inert stubs for musical calls, and overlays the source on the output. web/dist/patterns.js bundles the same pinned Strudel core and mini-notation packages so H(pattern) returns live numeric pattern values at the engine's cycle position. Function-valued Hydra parameters, including arrow functions over a.fft, are resolved every frame; o0–o3 outputs sample the previous rendered frame.

With detectAudio:true, the page fills a.fft from music_audio_spectrum: a 4096-sample Hann FFT of the master mix, reduced to 64 logarithmic bands outside the audio callback in the MCP thread. setBins, setSmooth, setCutoff and setScale follow Hydra's analyser settings; the engine's own audio is used instead of requesting microphone permission. With feedStrudel:1, s0 is a live Strudel-style scope canvas drawn from the same bounded waveform feed. hydra_webgl exercises generators, the full effect set, prev feedback, owned canvas-backed camera/screen stubs, image sources, resolution changes, source-driven graph switching, the code overlay, H(), detectAudio, feedStrudel and the four https://strudel.cc/learn/hydra/ examples in headless Chromium. Custom setFunction GLSL and patchbay stream names are not accepted by this bounded backend.

Pitch compensation and convolution

stretch follows the current upstream worklet's shift mapping: positive x uses pitch factor 1+x, negative x uses max(0,1+x/4). For example, .speed(.5).stretch(1) plays a sample at half speed while compensating its pitch upward by an octave. Duration still follows sample transport and the event envelope. Native samples now use the reference's 2048-frame phase vocoder, 128-frame hop, peak regions, phase correction and Float32 Hann overlap-add. The sample envelope precedes the vocoder, and ordinary effects follow it. Preparation accounts for the reference's 40 ms source anticipation and quantum disconnect at the end; the musical event and highlight times stay unchanged. Output begins at the musical onset, so earlier low-level precursors are omitted.

The generator prepares immutable stereo PCM with a 90-second input-lifetime limit, a 128 MiB/128-buffer cache and eviction of unreferenced entries. Queued events and voices retain their buffers. Preparation-limit failures report a console error. New source/pitch variants require preparation; gain and ordinary effect changes reuse the same PCM. No FFT, allocation, decoding or JavaScript runs in the callback. Stretch overlap-add runs outside the cache lock, so independent variants can prepare concurrently. Lookup, slot reservation and publication keep their locks short; in-flight reservations count toward the byte bound. Concurrent jobs for the same key converge on one published buffer and discard the losing copy. A repeated source and pitch reuses the cached PCM after a short lookup. A new pitch or stretch variant misses and prepares again without decoding the sample a second time. Sample decoding runs outside the sample cache lock. Reverse playback, slices, looping, envelopes and source pitch modulation are included in preparation. Oscillators retain their direct pitch-factor implementation rather than passing through a vocoder. The preparation profile in audio comparison records cold-cache, live-edit and burst timings for this path.

Source preparation for a scheduling window is submitted to a bounded worker pool. The generator classifies haps first, submits sample/native/stretch jobs, then waits for and publishes each hap in order through its own event-queue staging transaction. An earlier ready note is therefore visible before a later slow source finishes; it is not held until the whole window completes. This keeps shared delay and room changes, duck decisions, equal-time notes and generation checks in scheduling order. For normal publication, accepted duck controls commit before waiting for their source, matching Superdough's timer creation before its asynchronous source trigger. A slow or rejected source does not hold those callbacks, and already accepted callbacks survive program replacement. Refresh still stages future replacements until its final cutoff. If the program changes while jobs are running, completed results are discarded before publication; audio that was already committed is not withdrawn. Immediate OSC, Csound, rest/eviction and control-only work uses the same transaction. The pool budget comes from process affinity and visible ancestor cgroup v1/v2 quotas, capped at four general workers; membership and mount roots are resolved from /proc/self/cgroup and /proc/self/mountinfo. Limits above an inaccessible cgroup namespace root cannot be inspected. The serial room lane adds one thread. Set TOMPOUCE_PREP_WORKERS=1..8 to benchmark another count. Its general queue is workers*32, capped at 512. Failed worker startup falls back to inline source/kernel preparation and reports a console message; room requests report a room failure instead.

Maintained browser comparisons pass for half/fractional-speed compensation, upward shifting, reverse playback, loops and envelope/filter ordering. Downward shifting passes for shared PCM and eight independently decoded MP3 piano cases, including three downward factors, C4/Fs3/Ds4 recordings, fractional speed and fractional onsets. MP3 decoding retains float precision rather than rounding to PCM16 before stretching. Prepared output begins on the first playback frame, avoiding a one-frame delay at fractional onsets. The downward peak regions still amplify small decoder differences; these selected gates establish neither full decoder equivalence nor full-song waveform parity. See audio comparison for evidence and limits.

ir selects a registered sample as the orbit's convolution impulse:

note(60).s('piano').ir("RolandTR909_sd").set({i:0}).room(.5).roomsize(.2)

irbegin sets the source offset and irspeed selects its signed playback rate. Fractional positive rates play forward; negative rates play backward. This correct signed-rate behavior differs from the current browser's adjustLength bug for positive rates below one. roomsize limits the active IR duration; the original buffer length participates in WebAudio-style RMS normalization. The IR is prepared by the generator using existing sample maps, URL policy and decoders. Kernel construction and its FFTs run outside the sample-impulse cache lock; lookup and publication are short, and concurrent requests for the same key share one published kernel. After inherited room controls are resolved in hap order, the kernel FFT is submitted to the same preparation pool as other source work. The callback uses an immediate 128-tap head plus 128-frame FFT partitions for its tail, preserving zero onset latency. Stereo IR channels remain separate. With a mono IR, the web convolver switches to mono output when its stereo source connections expire: only the left history advances, and its output is duplicated. The right history stays paused until a later stereo connection resumes it. Native convolution follows that behavior without callback allocations. Five shared-PCM IR checks cover clipped source cleanup, room-send toggles, silent sends, orbit switching and combined delay/reverb. Nine further checks cover natural endings, fast/reverse playback, short buffers, pitch envelopes, vibrato, slices, loops and fxr for stereo samples without a pan stage. Preparation derives when the buffer actually ends instead of keeping stereo input alive for the whole hap. Constant-rate sources use direct arithmetic; pitch modulation is integrated per quantum outside the callback. Work is bounded to 32,768 quanta (about 95 seconds), falling back to the conservative scheduled source-stop deadline for unusually long modulation. Panned/stretched/graph connections, eviction and live reconnection timing still need separate comparisons. Prepared impulse changes select the shared convolver immediately and reset that orbit's tail on the next audio frame; an earlier accepted note does not restore its old impulse at onset.

Sample IR limits: roomsize up to 10 seconds (441,000 active frames at 44.1 kHz) and 16 cached IR/size/speed/offset combinations per process. The convolver's 15-second capacity additionally accommodates generated-room tails. Excess limits or failed IR resolution reject the event and report a console warning; audio is not silently truncated or replaced by another reverb. Kernels are immutable and retained for the process lifetime.

The initial roomsize defaults to two seconds, matching the web REPL. Omitted roomsize, roomfade, roomlp and roomdim controls retain the last accepted settings while the orbit reuses its room, including across evaluation and Stop/Play. Changing an explicit room parameter rebuilds the impulse and restores defaults for omitted parameters, matching the web REPL. Unchanged generated room settings reuse the impulse and preserve its tail. Custom IRs also retain omitted speed and offset while reusing the same resolved sample. Changing the sample, or an explicit room control, restores defaults for omitted controls before preparing the replacement kernel. An explicitly supplied IR speed or offset differs from an omitted one even when its numeric value equals the default. Such rebuilds reset convolution history even if the prepared PCM is already cached.

room without ir prepares a stereo convolution impulse on the serial FIFO lane of the shared preparation pool, with a bounded 32-request queue. Live scheduling does not wait for generation. Noise synthesis, the low-pass and the kernel FFTs run outside the generated-IR cache lock. That lock is separate from the stretch lock, so stretch and IR preparation can overlap. The lane still completes one generated request at a time, so several rooms do not overlap with each other; concurrent requests for the same generated IR share one published kernel. The old convolver and its sounding tail remain active until a completed kernel is published; that publication resets the old convolution history on the next audio frame. An initial pending room has no wet output. Accepted requests survive evaluation and Stop/Play while their scheduling generation remains current. The completion checks the generation and publishes the kernel under the same generation guard, so a program transition cannot interleave between the check and publication; an obsolete completion is discarded. Kernel publication remains on this serial lane rather than the note-queue transaction. As on the web, an older generated completion can replace an intervening custom IR. Multiple generated requests complete in FIFO order; arbitrary browser worker completion races are not reproduced.

The generated impulse follows the upstream exponential decay, fade-in and gradual low-pass. roomfade defaults to .1, roomlp to 15000 and roomdim to 1000. A fixed random seed makes native rooms reproducible. Generated rooms support roomsize / size up to 10 seconds, matching the web REPL's documented maximum. The IR lasts 1.5 times the decay, so size 10 prepares a 15-second, 661,500-frame stereo IR at 44.1 kHz. Coastline's final .size(4) now works directly, preparing a six-second IR. Zero size, exhausted caches, a full request queue or worker startup failure retain the previous room and report the orbit, requested size/fade/filter settings and specific failure reason. Duration failures also print the native size limit; queue and cache exhaustion are distinguished. These generated impulses retain a separate 16-entry cache. Convolution history has a fixed bound of 5,168 slots per channel, but a short kernel uses only its own ring slots rather than touching the full history. Kernel building, allocation and generation stay outside the callback; switching kernels retains the existing publication and failure rules. Failed initial generation leaves the wet output silent. Parameter equality guards retain the requested settings even after failure; change a parameter to request another generation. Explicit ir failures still reject the event rather than silently substituting another impulse.

The browser capture harness checks dry piano, synths, envelopes, filters, panning, ZzFX, bytebeat and seeded generated/custom IRs through the real callback; see audio comparison. No-pan mono sources upmix at unity, while explicit panning uses equal-power mono or stereo folding. Stock saw/square levels follow the full-partial periodic-table normalization used by Chromium.

Chromium companion

From the terminal UI, press F2, type /companion, and press Enter. This starts the bridge, opens Chromium, and logs its URL. It reuses this engine's TCP MCP port, or enables a private ephemeral loopback port for an ordinary UI launch. Repeated commands reuse the running helper. /companion stop stops it, and the helper also exits when the engine exits. A UI attached to stdio MCP needs to be launched in a terminal TCP session instead.

The standalone bridge remains available:

python3 scripts/companion.py --open
# Optional fixed port or alternate MCP endpoint:
python3 scripts/companion.py --port 18990 --mcp-port 18789

Standalone TCP engines and bridges must share TOMPOUCE_MCP_TOKEN, a secret of 64 lowercase hexadecimal characters (see README). The bridge authenticates each MCP request; this capability is separate from its browser request token. The terminal's /companion launch generates or uses the engine capability and passes it to the helper over a private stdin pipe, without putting it in the browser or helper command line. Stdio MCP is unchanged.

Open the loopback URL printed by the command in Chromium. The companion shows sounding voices, pitch, level and sample progress, the console and engine health. It provides play/stop, tempo, reevaluation and a source editor. The source editor uses locally bundled CodeMirror 6 with JavaScript syntax highlighting, multiline paste, line numbers, bracket matching and undo. Unchanged source polling preserves selection and history; in-flight polling also preserves unapplied edits and their conflict-detection baseline. Strings containing mini-notation are highlighted as JavaScript strings. Voice telemetry targets 30 snapshots per second independently of the slower status/console/source refresh. Canvas rendering uses animation frames and extrapolates sample progress between snapshots; data older than 250 ms is cleared. Hidden tabs reduce polling. The terminal's idle wait wakes directly on MCP traffic, so telemetry does not wait for a 50 ms UI sleep per connection. Edits stay in the tab until Apply; terminal-side changes prompt before replacement, and polling never overwrites unapplied tab edits. Audio remains in the native engine. This provides native session controls and activity visuals, not Hydra or browser audio/input-device emulation.

The bridge binds only to 127.0.0.1, checks Host/Origin and a per-process token, and exposes a fixed tool allowlist. It sends no data to external services. Stop the bridge with Ctrl+C. It does not restart the engine. The source replacement check detects changes observed before applying; it is not an atomic compare-and-swap against simultaneous terminal edits.

The committed web/dist/editor.js and web/dist/licenses.txt let the companion run without npm or CDN access. Rebuild them with cmake --build build --target companion-bundle after editing web/editor.mjs; web/package-lock.json pins the editor/build dependencies independently of the Strudel runtime. Editor DOM regression checks run with node tests/test_companion_editor.mjs after installing those development dependencies. Companion asset/CSP changes require restarting only the bridge (/companion stop, then /companion).

Live coding and visual feedback

Upstream event source locations feed the existing TUI sounding-token highlighting, including locations in patterned control arguments. UTF-16 locations are converted to UTF-8 byte offsets before rendering. Highlight spans are cached during scheduling, so drawing the editor does not execute user JavaScript again. Adding, moving or changing a visualization preserves moving note highlights: the generator maps the original literal offsets to the edited source after checking that the musical syntax still matches. Comments and whitespace can move those offsets; unapplied musical changes still suppress highlighting. Patterned .color() changes active-token colors; .markcss() supports underline, bold and italic terminal attributes (arbitrary browser CSS is unavailable). Colors accept common names, hex, RGB(A) and HSL(A).

The native inline views are scope (also tscope), pianoroll, punchcard, spiral, pitchwheel, spectrum and wordfall. Both ._name() and .name() render beneath the source line in the terminal. Kitty-capable terminals receive pixel graphics; others receive the same geometry in braille, or ASCII without UTF-8. Global transforms such as all(punchcard) also work.

Piano rolls, punchcard, wordfall, spiral and pitchwheel follow subsequent transformations, including time changes after the visual call. Each view stays isolated to its tagged branch. This intentionally adapts the browser's capture-at-call piano roll to match terminal playback. Note views query held, recent and upcoming logical haps, including silent patterns, rather than relying on the audio-trigger history. The default window is four cycles with a centered playhead. cycles, playhead, vertical, labels, flipTime, flipValues, fold, minMidi, maxMidi, autorange, fill/stroke controls and colors are supported. Wordfall defaults to vertical labelled notes. Drum sounds occupy separate categorical rows. Overlapping same-pitch notes retain lanes and onset markers where resolution permits. Mixed pitched/percussion rolls use a single uniform lane layout; drum sample indices do not affect the melodic auto-range. Horizontal rolls have note guides on the left; vertical rolls have a keyboard/label rail across the top, with low pitches on the left by default. Quiet notes keep their geometry in braille. These orientation options apply to piano roll, punchcard and wordfall; scope, spectrum, spiral and pitchwheel currently keep their fixed native geometry.

Spiral supports stretch, steady, inset, padding, fade, logSpiral, size/thickness and playhead/color options. Pitchwheel preserves fractional pitches and supports edo, root (frequency or note name), circle, hapcircles, hapRadius, margin and mode: 'flake'|'polygon'. Spectrum is a scrolling logarithmic-frequency spectrogram with native Hann FFT analysis, 20 Hz–20 kHz guides, min/max dB range and speed (zero freezes). At speed 1 its time span is four seconds. History fills continuously between foreground frames; narrow low-frequency bands interpolate FFT magnitudes instead of leaving empty stripes. Its default intensity gradient runs from the terminal's blue through cyan, green and yellow to foreground, with quiet energy translucent and silence transparent. Explicit color, active/activeColor or patterned note colors retain a single hue. thickness sets a minimum history column width. Scope uses the web renderer's fixed amplitude scale and thickness (3). Inline ._scope() defaults to scale: 1 and pos: 0.5; .scope() defaults to scale: 0.25 and pos: 0.75, matching the web's distinct entry points. Samples map to (pos - sample * scale) * height; there is no automatic normalization. scale: 0 draws a flat line and negative scale inverts the trace. Alignment starts at the first falling crossing of -trigger, preserving sample spacing rather than stretching the remaining waveform. The default window is 4,096 samples (about 93 ms at 44.1 kHz). Color and explicit scale, position, trigger and thickness options are supported. The separate master/F12 and bottom status scopes retain their terminal layouts. node scripts/scope-reference-qa.mjs checks coordinates captured from the deployed web renderer in a disposable browser without opening audio devices. Native raster checks cover the same trigger, scaling and spacing cases in test_terminal_graphics; terminal rasterization remains an adaptation.

Browser page-background placement, custom canvas contexts, font families, spiral cap styles and pitchwheel degree/int-label options are unavailable; unknown options are reported once in the console. Native typography and low-resolution braille are adaptations, not browser-pixel replicas. Each scope now shows only the native voices from its attached pattern, after voice effects, envelope, gain and pan. The tap precedes shared orbit reverb/delay, ducking and master effects; these shared tails are not attributed to a pattern. Csound's combined orchestra output has no isolated tap yet. Spectrum uses the same isolated tap.

Assessment of the remaining browser options. The styling/layout features that have no terminal equivalent are deliberate ceilings, not pending work: page-background placement, custom canvas contexts, font families, spiral cap styles and pitchwheel degree/int-label options. Unknown options are reported once and ignored; native typography and low-resolution braille are documented adaptations rather than browser-pixel replicas. Coordinate checks against the deployed renderer (node scripts/scope-reference-qa.mjs) and native raster checks (test_terminal_graphics) cover the geometry that does have a counterpart. Shared delay, reverb and duck tails stay on their orbits and are intentionally not attributed to an individual pattern: the web shares those effects too, so per-pattern tap attribution would require duplicating shared state and would misrepresent what is sounding. Csound output is a single combined orchestra stream with no isolated per-pattern tap for the same reason. No browser-pixel parity is claimed for any of these cases. Up to 32 visualization call sites are supported per program, with one visible widget of each kind per source line and eight simultaneous Kitty placements (additional widgets use braille). Drawing queries run on the generator at up to 8 Hz, with a 50 ms budget and 4,096 total cached events; the UI interpolates time at its display frame rate and runs FFT outside audio. Drawing queries fill a bounded tile cache incrementally, starting near the playhead, rather than querying an entire complex score within one budget. Views fill outward during startup; cached tiles refresh as playback continues. The cache holds at most 256 tiles/8,192 events, deduplicating held notes across tile boundaries while retaining simultaneous identical notes. Waveform scopes use only the audio tap and do not consume pattern-query time. Excessive queries report a console error and retain the previous view. Adding, moving, removing or changing a visual call on a running branch takes effect without F5. Loading a song activates its views automatically. The generator parses display requests and binds them to the existing program; it does not rerun the song, change tempo, clear queued notes or reset playback. Comments, whitespace and edits elsewhere in the buffer do not detach an unchanged branch. Literal visual options update immediately; options that execute JavaScript still require F5. Musical edits also require F5. A new or changed musical branch that cannot be matched to the playing program shows “waiting for playing pattern”. Branches carry bounded observation tags from compilation, so scopes can read already sounding voices as soon as they are attached. Existing visual sites and these automatic branch feeds share 32 tap slots; reaching the limit can require F5 to attach another branch explicitly. Generation tags reject stale waveform data. These are live views, not static sample-file previews. Comments and strings do not create widgets. Widgets scroll with code but are skipped by editing, selection, mouse placement and keyboard movement. UTF-8 terminals use 2×4 braille dots per cell, with an ASCII fallback. /inline off hides them and /inline on restores them; the preference persists. F12 opens a fullscreen piano roll and master waveform. F12 or Esc returns to the editor; F1 returns and opens keyboard help. Ctrl+P controls playback. Other editor input is ignored while fullscreen, including pasted text. Supported terminals use Kitty images; other terminals use colored braille (ASCII when Unicode is unavailable). Both renderers use the syntax theme's cyan and magenta roles and fill the terminal below a single navigation line.

A failed JavaScript evaluation retains the last playable program and reports the error. The editor keeps the failed source for correction; it does not highlight the old program against the new source. MCP evaluation tools return an error result for the failed evaluation. Empty or comment-only JavaScript buffers evaluate successfully as silent patterns.

Compilation and sample-map loading happen outside the track lock. JavaScript queries and sample resolution also run outside that lock, in the generator. Program references protect an in-flight query during reloads; queue generation numbers reject events produced by an obsolete program. The audio callback executes neither JavaScript nor file/network operations.

Limits remain: the editor source and each line grow until malloc fails (byte offsets stop near 2 GiB), 128 current source slots plus up to 128 retiring graphs, 12 effect orbits, 128 MiB per JS runtime, two seconds per compilation, 200 ms per pattern query, 4,096 haps/events per query, 4 MiB query JSON, and 8,192 queued audio events. Long lines wrap on JavaScript tokens; /wrap off scrolls sideways. The audio callback does not allocate. orbit / o selects the delay and reverb bus (default 1). duckorbit / duck selects target buses by number or array. Canonical numeric strings and singleton nested arrays follow the web's target-key conversion; colon lists and leading-zero strings do not select numeric orbits. Targets that do not yet exist are skipped at preparation time. duckattack is the return time, defaulting to 0.1 seconds with a 0.002-second minimum; duckdepth sets the minimum gain to max(0.01, 1-sqrt(depth)). Exponential ramps begin 10 ms before the note, reach their minimum at the note plus duckonset, then return to unity. Arrays of onset, attack and depth values map to the target array, reusing the first value for omitted entries. Depth zero still cancels the previous ramp. Replacement callbacks anchor to the last rendered sample's gain, as returned by WebAudio's AudioParam.value, before cancelling and replacing automation. That anchor is retained if the first replacement ramp fails; failure of the return ramp retains the accepted downward ramp and its target. Empty arrays and arrays whose first entry is undefined use onset zero and depth one, but their attack becomes NaN before the orbit defaults apply: the downward ramp is retained and the return ramp is rejected. Nested arrays retain JavaScript string/number conversion, including null, booleans and empty arrays. Numeric NaN and infinities retain their duck conversion behavior across the native bridge: invalid ramp endpoints reject, positive infinite depth reaches the minimum gain, and negative infinite attack uses the 0.002-second minimum. Repeated targets retain their order and per-entry controls; each target entry queues its own callback, including repeats of the same orbit. Timer creation validates the note time minus 10 ms before accepting controls, preparing shared effects or allocating a source. A negative/non-finite stop time rejects the event at the first existing target and reports a distinct timer diagnostic. The source orbit remains registered, missing targets are skipped, and a stop time of exactly zero is accepted. Rejection leaves existing gain automation, accepted callbacks and voices intact; later haps still run. String and singleton nested-array onsets follow JavaScript concatenation when forming ramp times. Invalid depth holds the cancellation gain; an invalid return time holds the target of an accepted downward ramp. Rejected ramps record their orbit, failing ramp and callback execution time. The scheduler reports these to the console outside the audio callback, including while stopped. Bursts retain the first 64 errors between drains and report overflow. Long normalized onset strings use immutable numeric summaries prepared outside the callback, without increasing the size of queued controls. The callback combines bounded significant digits with the actual (possibly late) callback time and attack, preserving concatenation and binary64 rounding. A separate 256-entry process-lived summary cache bounds memory; exhaustion rejects the new control with a console diagnostic and retains existing references. Malformed syntax uses a shared invalid summary. Embedded NULs in duck numeric strings are encoded as NaN before JSON serialization, avoiding native string truncation. Accepted duck callbacks use an independent bounded timeline, so voice stealing, source preparation failure, Stop and program replacement retain them. Rest and missing-source events can still duck another bus. Missing sounds stay silent and report an error. As in Superdough, clip(0) falls back to full duration. Csound and OSC output bypass local orbit creation and ducking. Csound also bypasses ALSA note output even when midichan is present. Native midichan without either output keeps its existing local-audio-plus-ALSA behavior. .midi() (port name, number or options object; Pattern input is rejected like the web) selects dominant MIDI instead: the ALSA note goes out with no local voice, and the channel follows midichan (defaulting to 1) with pitch from the resolved voice frequency. An options midichannel applies only when the hap sets no midichan. Each external output fires independently, so .midi() combines with .osc() and .csound() while local synthesis stays off; a failing Csound schedule still warns while the MIDI note goes out. Rests and pitch-less drum patterns carry no MIDI note, and haps without a note key send extras without a note, matching the web scheduler. Velocity follows gain times velocity, defaulting to 1 times .9 for dominant MIDI, with seven-bit rounding including zero. Local audio gain stages do not affect it; an out-of-range note velocity aborts that MIDI hap. The legacy midichan path keeps its local gain rules. Options can supply gain, velocity, midichannel, noteOffsetMs and isController; the second options argument overrides the first object, and explicit hap controls override defaults. Channel options also accept ordered arrays, for example note("c4 e4").midi({midichannel:[1,3]}), or 'all' for channels 1–16. Duplicates remain duplicate sends; an empty list suppresses channel messages while transport and SysEx still send once per hap. WebMidi's parseInt conversion and invalid-channel filtering apply to these options. Explicitly null or undefined midichannel selects all channels, as in the REPL; omitting the option retains channel 1. At most 16 raw destinations are accepted per hap, including duplicates; larger lists warn and suppress that MIDI hap. Mapped CCs precede the note fan-out, followed by each extra's channel fan-out in REPL order. NRPN remains a complete transaction for each channel. Every fan-out reserves all its note-off slots before sending any note-on; if the bounded queue cannot hold them all, none of those note-ons is sent. Controller mode suppresses notes while retaining controls and transport. CC (ccn number 0..127 or a WebMidi controller name such as brightness, with ccv 0..1, also via control([ccn, ccv])), program change (progNum 0..127, truncated), pitch bend (midibend -1..1), channel aftertouch (miditouch 0..1), sysex (integer sysexid/sysexdata bytes 0..255, up to 3 id and 256 data bytes framed F0..F7) and transport midicmd (clock/midiClock/start/stop/continue, plus progNum/sysex array forms) all send through ALSA. midiport selects a native ALSA client or port by case-sensitive name substring, or a zero-based index into the writable MIDI-generic output list. .midi('name') sets the same default for the pattern. Omitting it prefers the first IAC-named writable output, otherwise the first writable output, and only when no output exists the first subscriber, matching the web's default choice. Explicit string names prefer a subscribed destination such as PipeWire's Midi-Bridge before writable outputs, which is how native aconnect/Carla routes are selected. "*" is a native-only broadcast opt-in, and an unmatched selector drops the message like the web's missing-device branch. Named and numeric selectors use the writable MIDI-generic output ordering of a WebMIDI output list, including outputs that are not ALSA subscribers. A hap at cycle zero additionally sends transport start, as on the web. Sends run in web order (note, program, sysex, CC, NRPN, bend, touch, cycle-zero start, transport/command); a rejected extra drops itself and every later extra for that hap with a console warning, matching the web throw-abort behavior. Numeric CCs truncate like WebMidi; unknown controller names and out-of-range values reject. nrpnn([msb,lsb]) and nrpv(value) or nrpv([coarse,fine]) send a bounded NRPN CC transaction, including the reference's RPN-null deselection. Both parameter and data bytes must fit 0..127. Scalar extras and equivalent midicmd array forms both send, with command forms following cycle-zero start rather than replacing earlier messages. Scalar extras and equivalent midicmd array forms both send, with command forms following cycle-zero start rather than replacing earlier messages. Sysex byte values also accept the documented string form: sysexid("0x77") and sysexdata("0x01:0x02:0x03:0x04"), where a 0x prefix means hex and a bare token is decimal, separated by :. A space is not a separator because control strings are mini-notation and would split into a sequence first. Malformed tokens, values above 255 and byte counts beyond the id/data bounds are rejected with the usual warning, and the note still commits. The deployed REPL throws on these documented strings, so this string form is a deliberate superset; numeric bytes, arrays and midicmd framing are unchanged.

defaultmidimap({lpf:74}) registers the current program's default map; await midimaps({synth:{lpf:{ccn:74,min:100,max:1100,exp:2}}}) registers named maps selected with .midimap('synth') or MIDI options. Mapped CCs send before notes, in hap control order, with clamping and exponential scaling. Maps are bounded to 32 names including the default, 128 control entries per map and 32 mapped sends per hap. await midimaps('synth') now loads a named manifest from the user's confined tompouce/midimaps/<name>.json config file instead of an inline object. Names are bounded to 128 safe characters, files to 64 KiB, traversal and non-JSON content are rejected, and the same manifest can be reloaded on later evaluations, so persistence is explicit rather than implicit. Query workers do not read these files; a program using a manifest falls back to the QuickJS evaluation. Inline definitions remain supported.

MIDI note gates use the hap duration in cycles, including .duration() and .clip(), converted at scheduling tempo. The default note-off offset is 1 ms, capped at half the gate, and noteOffsetMs:0 disables that offset. Nonnegative offsets and gates up to 24 hours are supported. Dominant MIDI keeps fractional milliseconds and short gates; the legacy local-plus-ALSA path retains its 50 ms floor. A full note-off queue rejects the new note-on instead of sending a note without a scheduled off. test_midi measures the direct and scheduler-generated 20 ms note-off paths through an owned ALSA receiver while two CPU-load threads run; real USB/DIN transport and device response are not measured.

cmake --build build --target test-midi-reference-web gates 180 cases, including all 128 controller names, hap values, native commits, actual send bytes/order and note-on/off timestamp differences against the deployed REPL. Only MIDI transport and clock mapping are mocked; scheduling and WebMidi conversion/validation run normally. These gates establish note duration, not physical device delivery latency. Open gaps include channel-array options, remote/persistent maps and numeric-string control coercion drift (pinned 1.2.6 coerces ccn("74") to 74 while the deployed REPL preserves the string and rejects the send).

Building and testing

.piano() follows the upstream REPL helper: it selects the default piano sample map, preserves explicit clipping, sets release to 0.1 seconds, and pans by pitch. loadCsound (also loadCSound / loadcsound) accepts orchestra strings and template literals; loadOrc accepts public HTTP(S) or github: URLs. .csound('Instrument') and .csound(1.25) route named and numeric instrument instances to the native Csound renderer. .csoundm(...) uses MIDI key/velocity pfields and preserves fractional keys. These functions can also be imported from @strudel/csound.

Csound rendering runs in an isolated Linux process with bounded memory and execution time. After trusted engine initialization it cannot open files, create processes, or access the network; loadOrc fetching happens in the parent using the existing URL policy. The audio callback consumes buffered stereo PCM without IPC, allocation, or Csound calls. Failed fetching or host initialization keeps the previous playable program unless source catches the loader rejection and returns a valid pattern; orchestra syntax diagnostics retain existing definitions while allowing the new musical pattern, as above. Engine runtime messages (for example an unknown instrument at note time) travel back over a dedicated socket into the console ring through the render pump thread, bounded with an omission summary under floods; compile diagnostics keep their existing reply path. The compiler thread has the same confinement as the renderer. Up to 16 loads per evaluation, 2 MiB of combined source per update and 64 cached orchestra URLs per Csound session are accepted. Failed orchestra fetches stay rejected without refetching, matching the deployed loader's session promise cache; oversize content is not cached, so shrunken upstream text loads normally. Live loaders apply in source order at their call sites during evaluation. Loads that succeed before a later JavaScript throw or loader failure stay available to the next evaluation through a parked session engine, matching the deployed page engine. Failed evaluation retains the previous musical pattern; it does not roll back successful orchestra loads. A caught fetch failure can therefore select an alternative pattern. Loads are never replayed after evaluation, and query-time loader calls are rejected. The existing evaluation and worker budgets remain in force. Named instruments receive frequency, gain, and the slash-separated Strudel control map as p4/p5/p6, matching the upstream bridge.

Current livecode.orc uses Csound 7 syntax. Install the pinned native engine on Linux x86_64 with bash scripts/install-csound7.sh, then rebuild. It lives under ~/.local/opt/tompouce-csound7; pass -DCSOUND_PREFIX=/path when configuring to use another installation. Csound 6 headers/libraries are also supported for older orchestras. Without either dependency, ordinary Strudel playback still builds and Csound evaluation reports the missing dependency.

ctest --preset default includes all 31 published examples, comparing 1,207 events across three cycles with committed Node/V8 reference results. It also renders the two Csound examples using the native backend. See fixture provenance and update instructions.

Plain sample arrays use MIDI 36 as their playback root, matching Superdough; explicit note-keyed maps retain their declared roots. Decoding preserves the recorded levels rather than peak-normalizing each file. Sample amplitude ADSR defaults differ from oscillator defaults, and note duration gates a sample only when clip, loop, or release is specified. Lowpass/highpass resonance uses WebAudio's decibel Q convention; bandpass Q is linear. For ordinary samples, begin sets the playback offset and end sets the default envelope gate. Playback continues through the release tail until the envelope or buffer ends. Explicit clipping, looping, or release uses the pattern event's duration for that gate.

Normal builds use the committed bundle and vendored QuickJS sources:

cmake --preset default
cmake --build --preset default
ctest --preset default
python3 tests/test_tui_pty.py

Updating the JavaScript bundle requires Node.js/npm and package downloads:

cmake --build build --target js-bundle
cmake --preset default
cmake --build --preset default

js/package-lock.json pins dependencies. js/runtime.mjs contains the native host adapter and js/build.mjs produces the bundle and third-party notices. QuickJS 2026-06-04 is vendored under its MIT license. The upstream Strudel packages use AGPL-3.0-or-later; see thirdparty/STRUDEL-LICENSE and js/dist/licenses.txt for the bundled dependency notices and licenses.

References: Strudel REPL pipeline, audio effects, time modifiers, and QuickJS. Audio implementation references: upstream pitch-shift worklet, upstream custom IR handling, and WebAudio convolution normalization.