Skip to content

armgit / nota

Public Imported from GitHub
0

Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.

Redesign on Utility and Physical

Egor Khindikaynen7772e70000f3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7f4442a8..1da7bd14 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,10 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
## [Unreleased]
### Added
+- **MCP: `read_physical`.** Ask a Nota Physical track what it is: a one-line summary of the
+ patch, a guide to every parameter's values, the sounding voices, the last struck pitch, the
+ output peak and both resonators' 16 partials as the engine tunes them (Hz, level, ring
+ time, whether each one sounds).
- **Nota Lens — analyzer and oscilloscope.** A new built-in audio effect (kind 22) that shows
you what a track is actually doing. Drop it anywhere in a chain; it passes the audio through
untouched and adds no latency. One card, three views behind tabs:
@@ -51,6 +55,63 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
level, the effective attack and release, look-ahead latency and how often it kicked in.
### Changed
+- **Nota Physical's editor is now the almanac's card, with a voice mode, a resonator mix and
+ the partials it actually rings.** The card moves onto the 700 × 260 frame the other
+ instruments use — an **Exciter** / **Resonator** tab panel with a one-line reading of the
+ chain beside the tabs, a fixed **Output** rail and a status strip:
+ - **Exciter** — the mallet's four knobs › the noise burst: LP / BP / HP, a draggable ADSR
+ with its stage times written under it, and level, envelope → filter (in octaves), freq
+ and reso.
+ - **Resonator** — pick bank 1 or 2, switch bank 2 on, choose its material and the
+ structure. The partial window now comes from the engine itself: every partial where the
+ last struck note puts it, how loud it is struck and how long it rings, the ones past
+ Nyquist left out, the other bank drawn faintly behind, and a count of what sounds. Drag
+ it sideways to spread the series (Ratio) and up / down to tilt the highs (Bright). Knobs
+ read in real units — decay in seconds, tune in semitones, ratio as its exponent.
+ - **Output** — **Poly / Mono**, tune (semitones), fine (cents), note-off, volume, pan and
+ the track's meter. The header shows the sounding voices (x/8) or MONO.
+- **Nota Physical: Mono and Res Mix.** Two new parameters: **Mono** plays one note at a time
+ — a new strike chokes the sounding one with a 4 ms fade, so repeated hits don't smear —
+ and **Res Mix** balances resonator 1 against resonator 2 (both at full level in the
+ middle, which is how every project saved before sounds). Both automate, save and clone.
+- **Nota Physical ships 32 factory presets** (was 6) — mallets (xylophone, glockenspiel,
+ bass marimba, soft vibes, balafon), bells (church bell, music box, crystal chime, gamelan,
+ singing bowl, wind chimes), percussion (hand drum, steel drum, log drum, cowbell, clave,
+ kalimba), plucked, blown and bowed (harp, koto, tine keys, pan flute, blown bottle, bowed
+ glass) and textures (metal plate, mono kalimba, sub thump).
+- **Instrument automation menus flatten single entries.** A built-in instrument's parameter
+ whose name shares its first word with no other one is listed under its full name
+ ("Note Off"), not as a one-item submenu.
+
+- **Nota Utility shows where the stereo field and the level go, not just its knobs.** The card
+ moves onto the Valve / Vintage / Auto Filter frame — a LEVEL column (input and output meters
+ with their level), a centre panel with **Field**, **Mono** and **Levels** tabs, a
+ **Routing / Output** panel and a status strip. The goniometer gives way to pictures that say
+ which part of the signal does what:
+ - **Field** — the output's stereo field by frequency over the last second, lows at the bottom:
+ where each band sits between L and R, how far it spreads, and how far the width setting
+ spreads an uncorrelated band. Drag sideways for the balance, up and down for the width.
+ - **Mono** — the width over frequency as the settings make it, the mono region shaded, against
+ the output's measured width. Drag sideways for the mono cutoff, up and down for the width.
+ - **Levels** — input and output over the last 8 s in LUFS-S, sample peak or RMS, with the
+ target, the delta and the true peak. Drag up and down for the target.
+ - **New in the engine:** an **M/S width law** (mid and side are traded, so widening does not get
+ louder; 200 % = side only), a **mono-below slope** of 6, 12 or 24 dB/oct with 60 / 120 / 240 Hz
+ quick picks, **level matching** — a one-shot **Gain match** and a continuous **Level match**,
+ to the input's level or to a **Target**, in the meter's unit, measured before Gain so a
+ second press does not chase the first — a zero-latency **true-peak limiter** with its
+ ceiling, and LUFS-S, peak, RMS and true-peak metering of both sides. Gain, width and balance
+ are now smoothed, so automating them no longer clicks.
+ - **30 factory presets**, up from six — width, bass mono, routing and level targets (streaming
+ −14, podcast −16, broadcast −23 LUFS …); the six old ones keep their names. The first nine
+ parameters keep their order, units and defaults and the eight new ones are appended and
+ default to the old sound, so older projects open unchanged. Every one of them automates
+ (mono, phase and true-peak params grouped in the lane menu), MIDI-learns, saves in a preset
+ and is reachable over MCP. `get_device_text` returns the status line, the live reading and a
+ guide to the parameter values, `device_action` 0 gain-matches and 1 resets the meters, and
+ the new `read_utility` returns the levels in every unit, the delta, true peak, correlation,
+ width, energy balance, the auto-match gain, the limiter's reduction and eight bands of the
+ stereo field.
- **Nota Valve shows the amp it runs, not just its knobs.** The card moves onto the Vintage /
Auto Filter / Lens frame — a STAGE column (gain and output faders), a centre panel with
**Amp**, **Cab** and **Harmonics** tabs, a **Cabinet / Output** panel and a status strip.
@@ -152,6 +213,12 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
lane menu), MIDI-learns, saves in a preset and is reachable over MCP; `get_device_text`
returns the compressor's status line.
+### Fixed
+- **Nota Physical's 1→2 structure no longer blows up.** Resonator 1 fed resonator 2 at full
+ gain, so a partial landing on one of resonator 2's rang it up by thousands of times and the
+ track clipped. Resonator 2 now works as a set of resonant band-passes at the level of its
+ partials, and Res Mix sets how much of resonator 1's own sound comes through with it.
+
## [0.40.0] — 2026-09-18
### Highlights
diff --git a/FEATURES.md b/FEATURES.md
index 1499a521..9bc88ed6 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -293,7 +293,13 @@ and user presets, automation, persistence and cloning.
cutoff and pitch, unison, output drive and pan, glide, Legato, pitch-bend (±2/±5/±12)
and mod wheels (the wheel opens the LFO onto the cutoff), VEL→AMP, VEL→FILTER,
Mono/Poly. 25 factory presets.
-- **Nota Physical** — physical modelling.
+- **Nota Physical** — modal percussion: a mallet (stiffness, strike noise, colour) and a
+ filtered noise burst with its own ADSR and envelope → filter strike one or two tuned
+ resonator banks (Beam / Marimba / String / Membrane / Plate / Pipe partial series with
+ decay, material, brightness, inharmonicity, ratio, hit position and tune), in series
+ (1→2) or parallel (1+2) with a Res 1 / Res 2 mix; the partials drawn as the engine tunes
+ them (drag for ratio and brightness), Poly (8 voices) / Mono, tune, fine, note-off
+ damping, volume, pan and a meter. 32 factory presets. MCP: `read_physical`.
- **Nota Flux** — vector-morphing analog synth: an XY pad with four "timbre worlds"
(WARM/GLASS/MOOG/GRAIN) whose resonance, drive and unison the vector blends, **React**
(sidechain modulation from another track: Filter/Pitch/Space/Vector, with a live scope of
@@ -344,9 +350,13 @@ and user presets, automation, persistence and cloning.
bending the pitch tape-style; output stage with dry level, width, bass mono, wet only and
latency compensation for the diffuser. Tabs: Time / Loop · Wow and Levels / Output, over a
live repeat window that lights the repeat sounding now. Tap tempo. 29 factory presets.
-- **Nota Utility** (4) — gain, L/R balance, stereo width (mid/side 0–400%), channel mode
- (Stereo/Left/Right/Swap), bass mono, mute, phase invert; goniometer/vectorscope,
- correlation meter, meters, Gain match.
+- **Nota Utility** (4) — gain, L/R balance, stereo width 0–400 % with an L/R or M/S law, channel
+ mode (Stereo / Left / Right / Swap), mono below a cutoff at 6 / 12 / 24 dB/oct, mute, phase
+ invert per side; Gain match and continuous Level match to the input or a Target (LUFS-S / peak /
+ RMS), a zero-latency true-peak limiter. Tabs: Field (the stereo field by frequency, drag balance /
+ width) / Mono (width over frequency, drag the cutoff) / Levels (in and out over 8 s against the
+ target) and Routing / Output, with a LEVEL column, correlation and a status strip. 30 factory
+ presets. MCP: `read_utility`.
- **Nota Valve** (6, formerly Amplifier) — guitar amp: 7 models (Clean / Boost / Blues /
Rock / Lead / Heavy / Bass), gain, a Bass / Middle / Treble / Presence tone stack with a
sweepable middle, Bright and Deep, an even-harmonics-only preamp; a cabinet (Match / 1×12 /
diff --git a/src/managed/Nota.App/ArrangementView.Automation.cs b/src/managed/Nota.App/ArrangementView.Automation.cs
index ec799776..4c98f14f 100644
--- a/src/managed/Nota.App/ArrangementView.Automation.cs
+++ b/src/managed/Nota.App/ArrangementView.Automation.cs
@@ -390,9 +390,10 @@ public sealed partial class ArrangementView
// Nota Prism (52) by band ("Low", "Mid", "High", "Crossover") and Nota Lens (37) by
// view ("Spectrum", "Scope", "Waterfall", "Cursor"), the Compressor its key
// ("SC HP", "SC Gain" …), the Auto Filter its sources ("Env", "LFO", "Mod"), Nota
- // Vintage its tone and wow ("Tone Low", "Wow Rate" …) and Nota Valve its mic ("Mic Distance" …):
+ // Vintage its tone and wow ("Tone Low", "Wow Rate" …), Nota Valve its mic ("Mic Distance" …) and
+ // Nota Utility its mono, phase and true-peak params ("Mono Freq", "Invert L", "TP Ceiling" …):
// a word shared by two or more params becomes a submenu.
- bool grouped = e.TrackDeviceBuiltinKind(t.Id, d) is 1 or 6 or 7 or 8 or 20 or 21 or 22;
+ bool grouped = e.TrackDeviceBuiltinKind(t.Id, d) is 1 or 4 or 6 or 7 or 8 or 20 or 21 or 22;
var names = new string[builtinPc];
for (int p = 0; p < builtinPc; p++) names[p] = e.DeviceParamName(t.Id, d, p);
static string Head(string n) { int sp = n.IndexOf(' '); return sp > 0 ? n[..sp] : ""; }
@@ -480,14 +481,23 @@ public sealed partial class ArrangementView
var root = new MenuItem { Header = e.DeviceName(t.Id, -1) };
var groups = new System.Collections.Generic.Dictionary<string, MenuItem>();
int n = e.PluginParamCount(t.Id, -1);
+ // Group by the name's head ("Res1 Decay" → Res1 › Decay); a head only one param has
+ // stays a plain entry under its full name ("Note Off", not Note › Off).
+ static string Head(string nm) { int sp = nm.LastIndexOf(' '); return sp >= 0 ? nm[..sp] : ""; }
+ var sizes = new System.Collections.Generic.Dictionary<string, int>();
+ for (int i = 0; i < n; i++)
+ {
+ string h = Head(e.PluginParamName(t.Id, -1, i));
+ sizes[h] = sizes.TryGetValue(h, out var c) ? c + 1 : 1;
+ }
for (int i = 0; i < n; i++)
{
string id = e.PluginParamId(t.Id, -1, i);
string nm = e.PluginParamName(t.Id, -1, i);
if (id.Length == 0) continue;
- int sp = nm.LastIndexOf(' ');
- string leaf = sp >= 0 ? nm[(sp + 1)..] : nm;
- string grp = sp >= 0 ? nm[..sp] : "";
+ string grp = Head(nm);
+ if (grp.Length > 0 && sizes[grp] < 2) grp = "";
+ string leaf = grp.Length > 0 ? nm[(grp.Length + 1)..] : nm;
string pid = id;
var item = Leaf(leaf, $"P:-1:{pid}", () => SetAutoPluginTarget(t, -1, pid), automated);
if (grp.Length == 0) root.Items.Add(item);
diff --git a/src/managed/Nota.App/Controls/CollisionViz.cs b/src/managed/Nota.App/Controls/CollisionViz.cs
deleted file mode 100644
index 27c92e0a..00000000
--- a/src/managed/Nota.App/Controls/CollisionViz.cs
+++ /dev/null
@@ -1,110 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-only
-// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
-//
-// Modal partial spectrum for Nota Physical's resonator: draws the tuned mode series
-// (frequency on a log axis, bar height = struck amplitude) exactly as the DSP freezes
-// it from Type / Decay / Material / Bright / Inharm / Ratio / Hit — so the picture the
-// user sees is the resonator they hear. Non-interactive readout, app-styled.
-
-using System;
-using System.Globalization;
-using Avalonia;
-using Avalonia.Controls;
-using Avalonia.Media;
-
-namespace Nota.App;
-
-internal sealed class CollisionViz : Control
-{
- private static readonly IBrush Sunken = NotaPalette.BgSunken;
- private static readonly IBrush BorderDef = NotaPalette.BorderDefault;
- private static readonly IBrush AccentBright = NotaPalette.AccentBright;
- private static readonly IBrush TextTertiary = NotaPalette.TextTertiary;
- private static readonly IBrush Grid = NotaGraph.Grid;
- private static readonly Typeface Face = NotaFonts.Mono;
- private static readonly string[] TypeNames = { "BEAM", "MARIMBA", "STRING", "MEMBRANE", "PLATE", "PIPE" };
-
- private const int Modes = 16;
- private int _type;
- private double _decay, _material, _bright, _inharm, _ratio, _hit;
-
- public CollisionViz() { MinWidth = 150; MinHeight = 60; }
-
- public void Set(int type, double decay, double material, double bright, double inharm, double ratio, double hit)
- {
- _type = Math.Clamp(type, 0, 5); _decay = decay; _material = material;
- _bright = bright; _inharm = inharm; _ratio = ratio; _hit = hit;
- InvalidateVisual();
- }
-
- private static double ExpMap(double v, double lo, double hi) => lo * Math.Pow(hi / lo, Math.Clamp(v, 0.0, 1.0));
-
- // Partial ratios per material Type (mode 0 = fundamental = 1.0). Mirrors PhysicalSynth::ratioOf.
- private static double RatioOf(int type, int m)
- {
- double[] beam = { 1.0, 2.7565, 5.4039, 8.9330, 13.3443, 18.6379, 24.8137, 31.8718, 39.8122, 48.6349, 58.3399, 68.9272, 80.3968, 92.7487, 105.983, 120.099 };
- double[] marimba = { 1.0, 3.984, 9.531, 17.65, 28.10, 41.0, 56.4, 74.3, 94.7, 117.6, 143.0, 170.9, 201.3, 234.2, 269.6, 307.5 };
- double[] membrane = { 1.0, 1.5933, 2.1355, 2.2954, 2.6531, 2.9173, 3.1555, 3.5001, 3.5985, 3.6521, 3.8452, 4.0602, 4.1057, 4.2323, 4.6018, 4.8321 };
- return type switch
- {
- 0 => beam[m],
- 1 => marimba[m],
- 2 => m + 1,
- 3 => membrane[m],
- 4 => Math.Sqrt(m + 1),
- _ => 2 * m + 1,
- };
- }
-
- private void Label(DrawingContext ctx, string text, double x, double y, IBrush brush, double size = 8)
- => ctx.DrawText(new FormattedText(text, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Face, size, brush), new Point(x, y));
-
- public override void Render(DrawingContext ctx)
- {
- double w = Bounds.Width, h = Bounds.Height;
- if (w <= 0) return;
- NotaGraph.Window(ctx, new Rect(0, 0, w, h));
- Label(ctx, "PARTIALS · " + TypeNames[_type], 6, 3, TextTertiary);
-
- double pad = 6, x0 = pad, x1 = w - pad, top = pad + 12, bot = h - pad - 8;
-
- // Compute mode frequencies (as octave offsets from the fundamental) and amplitudes,
- // exactly as buildBank does: inharmonic stretch, ratio exponent, bright tilt, hit comb.
- double ratioExp = 0.5 + _ratio;
- double stretch = _inharm * 0.04;
- double brightRoll = ExpMap(_bright, 0.55, 1.0);
- var oct = new double[Modes];
- var amp = new double[Modes];
- double maxOct = 0.001, maxAmp = 1e-6;
- for (int m = 0; m < Modes; m++)
- {
- double r = RatioOf(_type, m) * (1.0 + stretch * m);
- r = Math.Pow(r, ratioExp);
- oct[m] = Math.Log2(Math.Max(r, 1e-6));
- amp[m] = Math.Pow(brightRoll, m) * (0.3 + 0.7 * Math.Abs(Math.Sin((m + 1) * Math.PI * (0.02 + 0.96 * _hit))));
- if (oct[m] > maxOct) maxOct = oct[m];
- if (amp[m] > maxAmp) maxAmp = amp[m];
- }
- double span = Math.Max(maxOct, 3.0);
-
- // Faint horizontal grid.
- var gridPen = new Pen(Grid, 1);
- for (int i = 1; i <= 3; i++) { double gy = top + (bot - top) * i / 4.0; ctx.DrawLine(gridPen, new Point(x0, gy), new Point(x1, gy)); }
- ctx.DrawLine(new Pen(BorderDef, 1), new Point(x0, bot), new Point(x1, bot));
-
- // Higher modes ring out faster (material), so fade the bars toward the top of the series.
- double matRoll = ExpMap(_material, 1.0, 0.45);
- for (int m = 0; m < Modes; m++)
- {
- if (amp[m] < maxAmp * 0.02) continue;
- double x = x0 + (oct[m] / span) * (x1 - x0);
- if (x < x0 || x > x1) continue;
- double barH = (amp[m] / maxAmp) * (bot - top);
- byte a = (byte)Math.Clamp(90 + 165 * Math.Pow(matRoll, m), 40, 255);
- var ab = NotaPalette.AccentBright.Color;
- var brush = new SolidColorBrush(Color.FromArgb(a, ab.R, ab.G, ab.B));
- ctx.DrawRectangle(brush, null, new Rect(x - 1.4, bot - barH, 2.8, barH), 1, 1);
- if (m == 0) ctx.DrawEllipse(AccentBright, null, new Point(x, bot - barH - 2.5), 1.6, 1.6);
- }
- }
-}
diff --git a/src/managed/Nota.App/Controls/PhysViz.cs b/src/managed/Nota.App/Controls/PhysViz.cs
deleted file mode 100644
index 6745f4fb..00000000
--- a/src/managed/Nota.App/Controls/PhysViz.cs
+++ /dev/null
@@ -1,139 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-only
-// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
-
-using System;
-using System.Globalization;
-using Avalonia;
-using Avalonia.Controls;
-using Avalonia.Media;
-
-namespace Nota.App;
-
- // Stylized resonator glyph + exponential decay curve for Nota Physical, drawn from
- // normalized param values in the app style (faint grid + labels).
- internal sealed class PhysViz : Control
- {
- private static readonly IBrush Sunken = NotaPalette.BgSunken;
- private static readonly IBrush BorderDef = NotaPalette.BorderDefault;
- private static readonly IBrush AccentBright = NotaPalette.AccentBright;
- private static readonly IBrush TextTertiary = NotaPalette.TextTertiary;
- public enum K { Glyph, Decay }
- private static readonly IBrush Grid = NotaGraph.Grid;
- private static readonly Typeface Face = NotaFonts.Mono;
- private readonly K _k;
- private int _st;
- private double _exc, _pos, _damp, _tone, _inh, _body;
- public PhysViz(K k) { _k = k; MinWidth = 180; MinHeight = 40; }
- public void Set(int st, double exc, double pos, double damp, double tone, double inh, double body)
- { _st = st; _exc = exc; _pos = pos; _damp = damp; _tone = tone; _inh = inh; _body = body; InvalidateVisual(); }
-
- private void Label(DrawingContext ctx, string text, double x, double y, IBrush brush, double size = 8)
- => ctx.DrawText(new FormattedText(text, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Face, size, brush), new Point(x, y));
-
- public override void Render(DrawingContext ctx)
- {
- double w = Bounds.Width, h = Bounds.Height;
- if (w <= 0) return;
- NotaGraph.Window(ctx, new Rect(0, 0, w, h));
- double pad = 6, x0 = pad, x1 = w - pad, top = pad + 11, bot = h - pad - 9;
- var pen = new Pen(AccentBright, 1.6, lineCap: PenLineCap.Round, lineJoin: PenLineJoin.Round);
-
- if (_k == K.Glyph)
- {
- string[] names = { "STRING", "MEMBRANE", "TUBE", "BODY" };
- Label(ctx, names[Math.Clamp(_st, 0, 3)], x0, pad - 1, TextTertiary);
- double cx = (x0 + x1) / 2, cy = (top + bot) / 2, rw = (x1 - x0) / 2, rh = (bot - top) / 2;
- var faint = new Pen(NotaPalette.Wash(NotaPalette.AccentBright, 0x66), 1.2, lineCap: PenLineCap.Round);
- switch (Math.Clamp(_st, 0, 3))
- {
- case 0: // String: a plucked line pulled aside at the pluck position.
- {
- double px = x0 + _pos * (x1 - x0);
- double amp = (bot - top) * 0.34 * (0.4 + 0.6 * _exc);
- var fig = new StreamGeometry();
- using (var g = fig.Open())
- {
- g.BeginFigure(new Point(x0, cy), false);
- g.LineTo(new Point(px, cy - amp));
- g.LineTo(new Point(x1, cy), false);
- }
- ctx.DrawGeometry(null, pen, fig);
- ctx.DrawEllipse(AccentBright, null, new Point(px, cy - amp), 2.2, 2.2);
- break;
- }
- case 1: // Membrane: concentric ripples.
- {
- for (int i = 1; i <= 4; i++)
- ctx.DrawEllipse(null, i == 1 ? pen : faint, new Point(cx, cy), rw * i / 4.4, rh * i / 4.4);
- break;
- }
- case 2: // Tube: a pipe with a standing wave inside.
- {
- double ty = top + (bot - top) * 0.18, by = bot - (bot - top) * 0.18;
- ctx.DrawLine(faint, new Point(x0, ty), new Point(x1, ty));
- ctx.DrawLine(faint, new Point(x0, by), new Point(x1, by));
- var wave = new StreamGeometry();
- using (var g = wave.Open())
- {
- g.BeginFigure(new Point(x0, cy), false);
- int n = 48;
- double amp = (by - ty) * 0.42;
- for (int i = 1; i <= n; i++)
- {
- double t = (double)i / n, x = x0 + t * (x1 - x0);
- double env = Math.Sin(Math.PI * t); // node at both ends
- double y = cy - env * amp * Math.Sin(t * Math.PI * 3);
- g.LineTo(new Point(x, y));
- }
- }
- ctx.DrawGeometry(null, pen, wave);
- break;
- }
- default: // Body: a rounded resonator box with rings.
- {
- var box = new Rect(x0 + rw * 0.18, top + rh * 0.28, (x1 - x0) * 0.64, (bot - top) * 0.62);
- ctx.DrawRectangle(null, pen, box, 8, 8);
- ctx.DrawEllipse(null, faint, new Point(cx, cy + rh * 0.28), rw * 0.16, rw * 0.16);
- ctx.DrawEllipse(null, faint, new Point(cx, cy + rh * 0.28), rw * 0.28, rw * 0.28);
- break;
- }
- }
- }
- else
- {
- Label(ctx, "DECAY", x0, pad - 1, TextTertiary);
- var gridPen = new Pen(Grid, 1);
- for (int i = 1; i <= 3; i++)
- {
- double gy = top + (bot - top) * i / 4.0;
- ctx.DrawLine(gridPen, new Point(x0, gy), new Point(x1, gy));
- double gx = x0 + (x1 - x0) * i / 4.0;
- ctx.DrawLine(gridPen, new Point(gx, top), new Point(gx, bot));
- }
- // Exponential amplitude decay: higher Damping → faster fall. A brighter
- // Tone shows as a faint denser oscillation under the envelope.
- double k = 2.0 + 7.0 * _damp; // decay rate
- var env = new StreamGeometry();
- var osc = new StreamGeometry();
- int n = 96;
- using var ge = env.Open();
- using var go = osc.Open();
- ge.BeginFigure(new Point(x0, bot), false);
- go.BeginFigure(new Point(x0, cyMid(top, bot)), false);
- for (int i = 0; i <= n; i++)
- {
- double t = (double)i / n, x = x0 + t * (x1 - x0);
- double a = Math.Exp(-k * t);
- double y = bot - a * (bot - top);
- ge.LineTo(new Point(x, y));
- double f = 6 + 40 * _tone;
- double oy = cyMid(top, bot) - a * (bot - top) * 0.42 * Math.Sin(t * f);
- go.LineTo(new Point(x, oy));
- }
- ctx.DrawGeometry(null, new Pen(NotaPalette.Wash(NotaPalette.AccentBright, 0x55), 1), osc);
- ctx.DrawGeometry(null, pen, env);
- }
- }
-
- private static double cyMid(double top, double bot) => (top + bot) / 2;
- }
diff --git a/src/managed/Nota.App/Controls/PhysicalViews.cs b/src/managed/Nota.App/Controls/PhysicalViews.cs
new file mode 100644
index 00000000..5bc7748e
--- /dev/null
+++ b/src/managed/Nota.App/Controls/PhysicalViews.cs
@@ -0,0 +1,107 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Physical's resonator window — the modal partials of the selected bank exactly as
+// the engine tunes them (its scope telemetry: ratio to the note, struck amplitude, ring
+// time). Frequency runs on a log axis from the fundamental, bar height is the struck
+// amplitude and a bar's ink fades with how much sooner that partial dies than the
+// fundamental. Partials above Nyquist for the reference note are left out. The other
+// bank, when it sounds, is drawn as faint hairlines behind. A drag is a control: sideways
+// spreads or squeezes the series (Ratio), up / down tilts the highs (Bright).
+
+using System;
+using Avalonia;
+using Avalonia.Media;
+
+namespace Nota.App;
+
+internal sealed class PhysPartialsView : VtWindowBase
+{
+ private (double Ratio, double Amp, double Tau)[] _modes = Array.Empty<(double, double, double)>();
+ private (double Ratio, double Amp, double Tau)[] _ghost = Array.Empty<(double, double, double)>();
+ private string _title = "PARTIALS", _footer = "";
+ private double _maxRatio = double.PositiveInfinity;
+ private bool _dim;
+
+ /// <summary>Show a bank. <paramref name="maxRatio"/> = the highest ratio still under
+ /// Nyquist for the reference note; <paramref name="ghost"/> = the other bank, or empty.</summary>
+ public void Set(string title, (double, double, double)[] modes, (double, double, double)[] ghost,
+ double maxRatio, string footer, bool dim)
+ {
+ if (title == _title && footer == _footer && dim == _dim && maxRatio == _maxRatio
+ && Same(modes, _modes) && Same(ghost, _ghost)) return;
+ _title = title; _modes = modes; _ghost = ghost; _maxRatio = maxRatio; _footer = footer; _dim = dim;
+ InvalidateVisual();
+ }
+
+ private static bool Same((double, double, double)[] a, (double, double, double)[] b)
+ {
+ if (a.Length != b.Length) return false;
+ for (int i = 0; i < a.Length; i++) if (a[i] != b[i]) return false;
+ return true;
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 0 || h <= 0) return;
+ NotaGraph.Window(ctx, new Rect(0, 0, w, h));
+ double x0 = 8, x1 = w - 8, top = 16, bot = h - 12;
+ for (int i = 1; i <= 3; i++)
+ {
+ double gy = top + (bot - top) * i / 4.0;
+ ctx.DrawLine(NotaGraph.GridPen, new Point(0, gy), new Point(w, gy));
+ }
+
+ // The axis spans both banks' audible series (at least three octaves), from the
+ // lower of the two fundamentals, so the ghost lines up with what it'd sound against.
+ double lo = double.MaxValue, hi = 0, maxAmp = 1e-9;
+ void Scan((double Ratio, double Amp, double Tau)[] ms, bool amp)
+ {
+ foreach (var m in ms)
+ {
+ if (m.Ratio <= 0 || m.Ratio > _maxRatio) continue;
+ lo = Math.Min(lo, m.Ratio); hi = Math.Max(hi, m.Ratio);
+ if (amp) maxAmp = Math.Max(maxAmp, m.Amp);
+ }
+ }
+ Scan(_modes, true); Scan(_ghost, false);
+ if (hi > 0)
+ {
+ double oLo = Math.Log2(lo), span = Math.Max(3.0, Math.Log2(hi) - oLo);
+ double X(double r) => x0 + (Math.Log2(r) - oLo) / span * (x1 - x0);
+
+ double ghostMax = 1e-9;
+ foreach (var m in _ghost) ghostMax = Math.Max(ghostMax, m.Amp);
+ var ghostPen = new Pen(NotaPalette.Wash(NotaPalette.TextTertiary, 0x66), 1);
+ foreach (var m in _ghost)
+ {
+ if (m.Ratio <= 0 || m.Ratio > _maxRatio || m.Amp < ghostMax * 0.02) continue;
+ double x = X(m.Ratio);
+ ctx.DrawLine(ghostPen, new Point(x, bot), new Point(x, bot - m.Amp / ghostMax * (bot - top)));
+ }
+
+ var ink = _dim ? NotaPalette.TextDisabled : NotaPalette.Accent;
+ double tau0 = _modes.Length > 0 ? Math.Max(1e-3, _modes[0].Tau) : 1;
+ for (int i = 0; i < _modes.Length; i++)
+ {
+ var m = _modes[i];
+ if (m.Ratio <= 0 || m.Ratio > _maxRatio || m.Amp < maxAmp * 0.02) continue;
+ double x = X(m.Ratio), bh = m.Amp / maxAmp * (bot - top);
+ // A partial that dies at once is drawn at ~35 % ink; one that rings as long
+ // as the fundamental at full.
+ byte a = (byte)Math.Clamp(90 + 165 * Math.Min(1, m.Tau / tau0), 60, 255);
+ var c = ((ISolidColorBrush)ink).Color;
+ ctx.DrawRectangle(new SolidColorBrush(Color.FromArgb(a, c.R, c.G, c.B)), null, new Rect(x - 1.5, bot - bh, 3, bh), 1, 1);
+ if (i == 0) ctx.DrawEllipse(_dim ? NotaPalette.TextDisabled : NotaPalette.AccentBright, null, new Point(x, bot - bh - 3), 1.8, 1.8);
+ }
+ }
+
+ ctx.DrawText(NotaGraph.AxisText(_title, NotaGraph.TitleInk), new Point(6, 3));
+ if (_footer.Length > 0)
+ {
+ var ft = NotaGraph.AxisText(_footer, NotaGraph.AxisInk);
+ ctx.DrawText(ft, new Point(w - ft.Width - 6, h - ft.Height - 1));
+ }
+ }
+}
diff --git a/src/managed/Nota.App/Controls/UtilityViews.cs b/src/managed/Nota.App/Controls/UtilityViews.cs
new file mode 100644
index 00000000..61b45907
--- /dev/null
+++ b/src/managed/Nota.App/Controls/UtilityViews.cs
@@ -0,0 +1,348 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Utility card windows (the centre panel's three tabs), all read from the engine
+// (Utility.h scopeRead), so the picture is what the device measures and runs:
+// • UtFieldView — Field: the stereo field by frequency — lows at the bottom, highs at the
+// top; where each band's energy sits (brass trace), how wide it is (teal
+// dots either side) and, dashed, how wide the width setting makes an
+// uncorrelated signal. Drag sideways for the balance, up / down for the width;
+// • UtWidthView — Mono: the configured width over frequency (brass) — the mono region
+// shaded — against the output's measured width (teal, dashed). Drag
+// sideways for the mono cutoff, up / down for the width;
+// • UtLevelView — Levels: input (teal) and output (brass) over the last 8 s in the
+// meter's unit, the target dashed. Drag up / down for the target.
+// UtCorrBar is the −1 … +1 correlation bar of the Routing panel.
+
+using System;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Media;
+
+namespace Nota.App;
+
+internal sealed class UtFieldView : VtWindowBase
+{
+ private float[] _pan = Array.Empty<float>(), _wid = Array.Empty<float>(), _lvl = Array.Empty<float>(), _set = Array.Empty<float>();
+ private int _n;
+ private bool _valid;
+ private double _lo = 30, _hi = 16000;
+ private string _legend = "";
+
+ /// <summary>The per-band pan / width share / level / configured width (%), the band span and the legend.</summary>
+ public void Set(float[] src, int panAt, int widAt, int lvlAt, int setAt, int n, bool valid, double lo, double hi, string legend)
+ {
+ if (_pan.Length != n) { _pan = new float[n]; _wid = new float[n]; _lvl = new float[n]; _set = new float[n]; }
+ if (n > 0 && Math.Max(Math.Max(panAt, widAt), Math.Max(lvlAt, setAt)) + n <= src.Length)
+ {
+ Array.Copy(src, panAt, _pan, 0, n); Array.Copy(src, widAt, _wid, 0, n);
+ Array.Copy(src, lvlAt, _lvl, 0, n); Array.Copy(src, setAt, _set, 0, n);
+ }
+ _n = n; _valid = valid; _lo = lo > 0 ? lo : 30; _hi = hi > _lo ? hi : 16000; _legend = legend;
+ InvalidateVisual();
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 0 || h <= 0) return;
+ var frame = new Rect(0, 0, w, h);
+ NotaGraph.Window(ctx, frame);
+ double top = 16, bot = h - 13, cx = w / 2, half = w / 2 - 10;
+ for (int i = 1; i < 4; i++) ctx.DrawLine(NotaGraph.GridPen, new Point(0, h * i / 4), new Point(w, h * i / 4));
+ ctx.DrawLine(NotaGraph.GridPen, new Point(cx - half / 2, 0), new Point(cx - half / 2, h));
+ ctx.DrawLine(NotaGraph.GridPen, new Point(cx + half / 2, 0), new Point(cx + half / 2, h));
+ ctx.DrawLine(new Pen(NotaPalette.BorderDefault, 1.2), new Point(cx, 0), new Point(cx, h));
+
+ double Yb(int b) => bot - (b + 0.5) / Math.Max(1, _n) * (bot - top);
+ if (_n > 1)
+ {
+ // The width setting: how far an uncorrelated band would spread.
+ var env = new Pen(NotaPalette.BorderStrong, 1, new DashStyle(new double[] { 3, 5 }, 0));
+ var gl = new StreamGeometry(); var gr = new StreamGeometry();
+ using (var cl = gl.Open())
+ using (var cr = gr.Open())
+ {
+ for (int b = 0; b < _n; b++)
+ {
+ double r = Math.Max(0, _set[b]) / 100.0, e = r / Math.Sqrt(1 + r * r);
+ var pl = new Point(cx - e * half, Yb(b)); var pr = new Point(cx + e * half, Yb(b));
+ if (b == 0) { cl.BeginFigure(pl, false); cr.BeginFigure(pr, false); } else { cl.LineTo(pl); cr.LineTo(pr); }
+ }
+ cl.EndFigure(false); cr.EndFigure(false);
+ }
+ ctx.DrawGeometry(null, env, gl); ctx.DrawGeometry(null, env, gr);
+
+ if (_valid)
+ {
+ double loudest = -120;
+ for (int b = 0; b < _n; b++) loudest = Math.Max(loudest, _lvl[b]);
+ const double gate = 42; // bands this far under the loudest are left out
+ bool Quiet(int b) => _lvl[b] < loudest - gate || _lvl[b] < -100;
+ // Teal dots: each band's spread either side of where it sits.
+ for (int b = 0; b < _n; b++)
+ {
+ if (Quiet(b)) continue;
+ double a = Math.Clamp((_lvl[b] - (loudest - gate)) / gate, 0.15, 1);
+ var dot = NotaPalette.Wash(NotaPalette.Teal, (byte)(40 + a * 190));
+ double x0 = cx + _pan[b] * half, y = Yb(b), s = Math.Clamp(_wid[b], 0, 1) * half;
+ ctx.DrawEllipse(dot, null, new Point(Math.Clamp(x0 - s, 2, w - 2), y), 1.7, 1.7);
+ ctx.DrawEllipse(dot, null, new Point(Math.Clamp(x0 + s, 2, w - 2), y), 1.7, 1.7);
+ }
+ // Brass trace: where each band's energy sits.
+ var g = new StreamGeometry();
+ using (var c = g.Open())
+ {
+ bool open = false;
+ for (int b = 0; b < _n; b++)
+ {
+ if (Quiet(b)) continue; // joined across: a lone tone still reads as a kink
+ // Power-weighted over the neighbours, so a quiet band between two loud
+ // ones does not throw the trace across the field.
+ double sw = 0, sp = 0;
+ for (int j = Math.Max(0, b - 1); j <= Math.Min(_n - 1, b + 1); j++)
+ {
+ if (Quiet(j)) continue;
+ double wgt = Math.Pow(10, (_lvl[j] - loudest) / 10) * (j == b ? 2 : 1);
+ sw += wgt; sp += wgt * _pan[j];
+ }
+ var p = new Point(cx + Math.Clamp(sw > 0 ? sp / sw : _pan[b], -1, 1) * half, Yb(b));
+ if (!open) { c.BeginFigure(p, false); open = true; } else c.LineTo(p);
+ }
+ if (open) c.EndFigure(false);
+ }
+ ctx.DrawGeometry(null, NotaGraph.PrimaryPen, g);
+ }
+ }
+
+ NotaGraph.Title(ctx, frame, "Stereo field");
+ NotaGraph.Axis(ctx, frame, NotaGraph.Corner.TopRight, _legend, NotaPalette.AccentBright);
+ NotaGraph.Axis(ctx, frame, NotaGraph.Corner.BottomLeft, "L");
+ NotaGraph.Axis(ctx, frame, NotaGraph.Corner.BottomRight, "R");
+ var c0 = NotaGraph.AxisText("C");
+ ctx.DrawText(c0, new Point(cx - c0.Width / 2, h - c0.Height - 3));
+ // Frequency marks up the left edge.
+ foreach (double hz in new double[] { 100, 1000, 10000 })
+ {
+ if (hz < _lo || hz > _hi || _n < 2) continue;
+ double t = Math.Log(hz / _lo) / Math.Log(_hi / _lo);
+ double y = bot - t * (bot - top);
+ var ft = NotaGraph.AxisText(hz >= 1000 ? NotaNum.F($"{hz / 1000:0} k") : NotaNum.F($"{hz:0}"));
+ ctx.DrawText(ft, new Point(4, y - ft.Height / 2));
+ }
+ if (!_valid)
+ {
+ var ns = NotaGraph.AxisText("no signal");
+ ctx.DrawText(ns, new Point(cx + 6, (top + bot) / 2 - ns.Height / 2));
+ }
+ else
+ {
+ var hint = NotaGraph.AxisText("lows at the bottom · highs at the top", NotaPalette.TealBright);
+ ctx.DrawText(hint, new Point(w - hint.Width - 5, h - hint.Height - 14));
+ }
+ }
+}
+
+internal sealed class UtWidthView : VtWindowBase
+{
+ private float[] _resp = Array.Empty<float>(), _meas = Array.Empty<float>(), _lvl = Array.Empty<float>();
+ private int _nr, _nb;
+ private double _rLo = 20, _rHi = 20000, _bLo = 30, _bHi = 16000, _monoHz = double.NaN;
+ private bool _valid;
+ private string _legend = "";
+
+ public const double LoHz = 20, HiHz = 18000;
+
+ /// <summary>The configured width (%, nr points on a log grid rLo…rHi), the output's width share and
+ /// level per band (nb bands, bLo…bHi), the mono cutoff (NaN = off) and the legend.</summary>
+ public void Set(float[] src, int respAt, int nr, double rLo, double rHi, int measAt, int lvlAt, int nb, double bLo, double bHi, bool valid, double monoHz, string legend)
+ {
+ if (_resp.Length != nr) _resp = new float[nr];
+ if (_meas.Length != nb) { _meas = new float[nb]; _lvl = new float[nb]; }
+ if (nr > 0 && respAt + nr <= src.Length) Array.Copy(src, respAt, _resp, 0, nr);
+ if (nb > 0 && Math.Max(measAt, lvlAt) + nb <= src.Length) { Array.Copy(src, measAt, _meas, 0, nb); Array.Copy(src, lvlAt, _lvl, 0, nb); }
+ _nr = nr; _nb = nb; _rLo = rLo > 0 ? rLo : 20; _rHi = rHi > _rLo ? rHi : 20000; _bLo = bLo > 0 ? bLo : 30; _bHi = bHi > _bLo ? bHi : 16000;
+ _valid = valid; _monoHz = monoHz; _legend = legend;
+ InvalidateVisual();
+ }
+
+ /// <summary>0 % at the bottom, 100 % in the middle, 400 % at the top (octaves above 100 %).</summary>
+ private static double Norm(double pct) => pct <= 100 ? Math.Max(0, pct) / 200 : 0.5 + Math.Min(2, Math.Log2(pct / 100)) / 4;
+
+ private double At(float[] a, int n, double lo, double hi, double hz)
+ {
+ if (n < 2) return 100;
+ double t = Math.Clamp(Math.Log(hz / lo) / Math.Log(hi / lo) * (n - 1), 0, n - 1);
+ int i = (int)Math.Floor(t), j = Math.Min(n - 1, i + 1);
+ return a[i] + (a[j] - a[i]) * (t - i);
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 0 || h <= 0) return;
+ var frame = new Rect(0, 0, w, h);
+ NotaGraph.Window(ctx, frame);
+ double top = 14, bot = h - 12;
+ double X(double hz) => Math.Log(hz / LoHz) / Math.Log(HiHz / LoHz) * w;
+ double Y(double pct) => bot - Norm(pct) * (bot - top);
+ foreach (double t in new double[] { 100, 1000, 10000 }) ctx.DrawLine(NotaGraph.GridPen, new Point(X(t), 0), new Point(X(t), h));
+ foreach (double p in new double[] { 50, 200 }) ctx.DrawLine(NotaGraph.GridPen, new Point(0, Y(p)), new Point(w, Y(p)));
+ ctx.DrawLine(new Pen(NotaPalette.BorderDefault, 1), new Point(0, Y(100)), new Point(w, Y(100)));
+
+ if (!double.IsNaN(_monoHz))
+ {
+ double mx = X(_monoHz);
+ ctx.FillRectangle(NotaPalette.Wash(NotaPalette.Teal, 0x1A), new Rect(0, 0, Math.Max(0, mx), h));
+ ctx.DrawLine(new Pen(NotaPalette.Wash(NotaPalette.Teal, 0xB0), 1, new DashStyle(new double[] { 3, 4 }, 0)), new Point(mx, 0), new Point(mx, h));
+ var mono = NotaGraph.AxisText("mono", NotaPalette.TealBright);
+ if (mx > mono.Width + 10) ctx.DrawText(mono, new Point(6, bot - mono.Height - 2));
+ }
+
+ // Measured: the output's side / mid ratio per band (dashed teal; gaps where it is quiet).
+ if (_valid && _nb > 1)
+ {
+ double loudest = -120;
+ for (int b = 0; b < _nb; b++) loudest = Math.Max(loudest, _lvl[b]);
+ var g = new StreamGeometry();
+ using (var c = g.Open())
+ {
+ bool open = false;
+ for (int b = 0; b < _nb; b++)
+ {
+ double hz = _bLo * Math.Pow(_bHi / _bLo, (b + 0.5) / _nb);
+ if (hz < LoHz || hz > HiHz || _lvl[b] < loudest - 50 || _lvl[b] < -100) { if (open) { c.EndFigure(false); open = false; } continue; }
+ double s = Math.Clamp(_meas[b], 0, 0.9999), pct = Math.Min(400, 100 * s / Math.Sqrt(1 - s * s));
+ var p = new Point(X(hz), Y(pct));
+ if (!open) { c.BeginFigure(p, false); open = true; } else c.LineTo(p);
+ }
+ if (open) c.EndFigure(false);
+ }
+ ctx.DrawGeometry(null, new Pen(NotaPalette.Wash(NotaPalette.Teal, 0x90), 1.1, new DashStyle(new double[] { 4, 4 }, 0)), g);
+ }
+ // Configured.
+ if (_nr > 1)
+ {
+ var g = new StreamGeometry();
+ using (var c = g.Open())
+ {
+ int px = Math.Max(2, (int)(w / 2));
+ for (int x = 0; x <= px; x++)
+ {
+ double hz = LoHz * Math.Pow(HiHz / LoHz, (double)x / px);
+ var p = new Point(x * w / px, Y(At(_resp, _nr, _rLo, _rHi, hz)));
+ if (x == 0) c.BeginFigure(p, false); else c.LineTo(p);
+ }
+ c.EndFigure(false);
+ }
+ ctx.DrawGeometry(null, NotaGraph.PrimaryPen, g);
+ if (!double.IsNaN(_monoHz)) NotaGraph.Node(ctx, new Point(X(_monoHz), Y(At(_resp, _nr, _rLo, _rHi, _monoHz))), true);
+ }
+
+ NotaGraph.Title(ctx, frame, "Width by frequency");
+ NotaGraph.Axis(ctx, frame, NotaGraph.Corner.TopRight, _legend, NotaPalette.AccentBright);
+ NotaGraph.Axis(ctx, frame, NotaGraph.Corner.BottomLeft, "20");
+ NotaGraph.Axis(ctx, frame, NotaGraph.Corner.BottomRight, "18 k");
+ foreach (double t in new double[] { 2000 })
+ {
+ var ft = NotaGraph.AxisText("2 k");
+ ctx.DrawText(ft, new Point(X(t) - ft.Width / 2, h - ft.Height - 2));
+ }
+ if (!double.IsNaN(_monoHz))
+ {
+ var ft = NotaGraph.AxisText(_monoHz >= 1000 ? NotaNum.F($"{_monoHz / 1000:0.#} k") : NotaNum.F($"{_monoHz:0}"), NotaPalette.AccentBright);
+ ctx.DrawText(ft, new Point(Math.Clamp(X(_monoHz) - ft.Width / 2, 22, Math.Max(22, w - ft.Width - 30)), h - ft.Height - 2));
+ }
+ var scale = NotaGraph.AxisText("100 %");
+ ctx.DrawText(scale, new Point(w - scale.Width - 5, Y(100) - scale.Height - 1));
+ }
+}
+
+internal sealed class UtLevelView : VtWindowBase
+{
+ private float[] _in = Array.Empty<float>(), _out = Array.Empty<float>();
+ private int _n;
+ private double _target = double.NaN, _sec = 8;
+ private string _legend = "", _targetText = "";
+
+ public const double RangeDb = 48; // 0 … −48 in the meter's unit
+
+ /// <summary>The histories (dB, oldest first; −120 = silence), the target line (NaN = none),
+ /// the window length and the texts.</summary>
+ public void Set(float[] src, int inAt, int outAt, int n, double target, double seconds, string legend, string targetText)
+ {
+ if (_in.Length != n) { _in = new float[n]; _out = new float[n]; }
+ if (n > 0 && Math.Max(inAt, outAt) + n <= src.Length) { Array.Copy(src, inAt, _in, 0, n); Array.Copy(src, outAt, _out, 0, n); }
+ _n = n; _target = target; _sec = seconds; _legend = legend; _targetText = targetText;
+ InvalidateVisual();
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 0 || h <= 0) return;
+ var frame = new Rect(0, 0, w, h);
+ NotaGraph.Window(ctx, frame);
+ Grid(ctx, w, h, 4);
+ double top = 14, bot = h - 12;
+ double Y(double db) => top + Math.Clamp(-db / RangeDb, 0, 1) * (bot - top);
+ if (!double.IsNaN(_target))
+ ctx.DrawLine(new Pen(NotaPalette.TextTertiary, 1, new DashStyle(new double[] { 2, 4 }, 0)), new Point(0, Y(_target)), new Point(w, Y(_target)));
+
+ StreamGeometry Line(float[] a)
+ {
+ var g = new StreamGeometry();
+ using var c = g.Open();
+ bool open = false;
+ for (int k = 0; k < _n; k++)
+ {
+ if (a[k] <= -100) { if (open) { c.EndFigure(false); open = false; } continue; }
+ var p = new Point(_n > 1 ? k * w / (_n - 1) : 0, Y(a[k]));
+ if (!open) { c.BeginFigure(p, false); open = true; } else c.LineTo(p);
+ }
+ if (open) c.EndFigure(false);
+ return g;
+ }
+ if (_n > 1)
+ {
+ ctx.DrawGeometry(null, new Pen(NotaPalette.Wash(NotaPalette.Teal, 0xA0), 1.1), Line(_in));
+ ctx.DrawGeometry(null, NotaGraph.PrimaryPen, Line(_out));
+ if (_in[_n - 1] > -100)
+ {
+ var lab = NotaGraph.AxisText("in", NotaPalette.TealBright);
+ ctx.DrawText(lab, new Point(w - lab.Width - 5, Math.Clamp(Y(_in[_n - 1]) + 2, top, bot - lab.Height)));
+ }
+ }
+
+ NotaGraph.Title(ctx, frame, "Input and output");
+ NotaGraph.Axis(ctx, frame, NotaGraph.Corner.TopRight, _legend, NotaPalette.AccentBright);
+ NotaGraph.Axis(ctx, frame, NotaGraph.Corner.BottomLeft, NotaNum.F($"−{_sec:0} s"));
+ NotaGraph.Axis(ctx, frame, NotaGraph.Corner.BottomRight, "now");
+ var tt = NotaGraph.AxisText(_targetText);
+ ctx.DrawText(tt, new Point((w - tt.Width) / 2, h - tt.Height - 3));
+ foreach (double db in new double[] { -12, -24, -36 })
+ {
+ var ft = NotaGraph.AxisText(NotaNum.F($"{db:0}"));
+ ctx.DrawText(ft, new Point(4, Y(db) - ft.Height / 2));
+ }
+ }
+}
+
+/// <summary>Correlation −1 … +1: the negative half tinted red, a needle at the value.</summary>
+internal sealed class UtCorrBar : Control
+{
+ private double _c = 1;
+ public UtCorrBar() { Height = 6; }
+ public void Set(double c) { _c = Math.Clamp(c, -1, 1); InvalidateVisual(); }
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 2 || h <= 1) return;
+ var rr = new RoundedRect(new Rect(0.5, 0.5, w - 1, h - 1), 2);
+ ctx.DrawRectangle(NotaPalette.BgSunken, new Pen(NotaPalette.GraphBorder, 1), rr);
+ using (ctx.PushClip(rr)) ctx.FillRectangle(NotaPalette.Wash(NotaPalette.Danger, 0x55), new Rect(0, 0, w / 2, h));
+ double x = (_c + 1) / 2 * w;
+ var ink = _c < 0 ? NotaPalette.Danger : _c < 0.3 ? NotaPalette.Accent : NotaPalette.Success;
+ ctx.FillRectangle(ink, new Rect(Math.Clamp(x - 1.5, 0, w - 3), -1, 3, h + 2));
+ }
+}
diff --git a/src/managed/Nota.App/DeviceCards/Bodies/UtilityDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/UtilityDeviceBody.cs
index bc55fca7..c3aca6a8 100644
--- a/src/managed/Nota.App/DeviceCards/Bodies/UtilityDeviceBody.cs
+++ b/src/managed/Nota.App/DeviceCards/Bodies/UtilityDeviceBody.cs
@@ -1,17 +1,22 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
-// Detail · Devices — built-in Nota Utility (kind 4) body, mockup 3j "show the thing
-// you can't hear". Three islands: ROUTING (channel mode · mono-below · mute · phase
-// invert · reset / gain match) | STEREO FIELD (a goniometer/vectorscope + a
-// correlation meter with the mono-risk zone in red) | LEVELS (Gain / Balance / Width
-// knobs + IN/OUT peak meters). The scope (peaks · correlation · a decimated ring of
-// output L/R pairs) comes from the packed device scope; params drive the knobs.
+// Detail · Devices — built-in Nota Utility body (device kind 4), a build of the "Nota Utility"
+// mockup (700 × 260) on the Valve / Vintage / Auto Filter frame: an always-visible LEVEL
+// column (input and output meters with their level in the meter's unit), a centre panel with
+// Field / Mono / Levels tabs — the stereo field by frequency, the width over frequency with the
+// mono region, input and output over the last 8 s against the target — a right panel with
+// Routing / Output tabs, and a status strip. Every picture comes from the engine (Utility.h
+// scopeRead); every control is a device param, so automation / MIDI learn / presets / A-B /
+// persistence come for free. Params are in real units (Gain dB, Width %, Mono Freq Hz …);
+// the controls work on 0..1 and map.
+// FullBleed — the shared shell draws the header (name · preset · badge · bypass).
using System;
using System.Collections.Generic;
using Avalonia;
using Avalonia.Controls;
+using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
@@ -22,249 +27,680 @@ namespace Nota.App;
internal sealed class UtilityDeviceBody : IDeviceBody
{
- // Param indices — must match Utility.h.
- private const int Gain = 0, Balance = 1, Width_ = 2, ChannelMode = 3, MonoFreq = 4, MonoBelow = 5, Mute = 6, InvertL = 7, InvertR = 8;
- // Packed scope layout (Utility::scopeRead): meters then kScopePairs (L,R) pairs.
- private const int S_InL = 0, S_InR = 1, S_OutL = 2, S_OutR = 3, S_Corr = 4, kMeters = 5, kPairs = 48, kScope = kMeters + kPairs * 2;
+ // ── Parameter indices (must match Utility.h) ─────────────────────────────
+ private const int Gain = 0, Balance = 1, Width_ = 2, ChannelMode = 3, MonoFreq = 4, MonoBelow = 5, Mute = 6, InvertL = 7, InvertR = 8,
+ WidthMode = 9, MonoSlope = 10, AutoMatch = 11, MatchTo = 12, Target = 13, Meter = 14, TpLimit = 15, TpCeiling = 16, kParams = 17;
+ // Scope layout (Utility::S_* / kTele / kHist / kBands / kResp).
+ private const int S_InPk = 0, S_OutPk = 1, S_Cpu = 2, S_SampleRate = 3, S_Corr = 4, S_InLufs = 5, S_OutLufs = 6,
+ S_TruePeak = 11, S_AutoDb = 14, S_LimDb = 15, S_InLevel = 16, S_OutLevel = 17, S_InMatch = 18,
+ S_EnergyBal = 20, S_WidthNow = 21, S_EffWidth = 22, S_MonoHz = 23, S_HistSec = 26, S_BandLo = 28, S_BandHi = 29,
+ S_RespLo = 31, S_RespHi = 32, S_Analysed = 33, S_InTruePeak = 34, S_OutPreMatch = 35;
+ private const int kTele = 48, kHist = 80, kBands = 32, kResp = 96;
+ private const int kHistAt = kTele, kBandAt = kHistAt + 6 * kHist, kRespAt = kBandAt + 5 * kBands, kScope = kRespAt + kResp;
+ private const int H_InLufs = 0, H_OutLufs = 1, H_InPeak = 2, H_OutPeak = 3, H_InRms = 4, H_OutRms = 5;
+ private const int B_Pan = 0, B_Width = 1, B_Corr = 2, B_Level = 3, B_Set = 4;
- public double Width => 700; // the almanac device format: 700 × 260
+ private static readonly string[] Modes = { "Stereo", "Left", "Right", "Swap" };
+ private static readonly string[] Meters = { "LUFS-S", "Peak", "RMS" };
+ private static readonly string[] Units = { "LUFS", "dB", "dB" };
+ private static readonly int[] Slopes = { 6, 12, 24 };
- public string? Subtitle => "UTILITY"; // the processing type, shown as the header badge
+ public double Width => 700;
+ public bool FullBleed => true;
+ public string? Subtitle => "UTILITY";
public Control Build(DeviceCardContext ctx, int index)
{
- var engine = ctx.Engine; int track = ctx.TrackId, di = index;
+ var engine = ctx.Engine;
+ int track = ctx.TrackId, di = index;
+ var mn = new float[kParams];
+ var mx = new float[kParams];
+ for (int p = 0; p < kParams; p++) { mn[p] = engine.DeviceParamMin(track, di, p); mx[p] = engine.DeviceParamMax(track, di, p); if (mx[p] <= mn[p]) mx[p] = mn[p] + 1; }
float P(int p) => engine.DeviceGetParam(track, di, p);
- void SetR(int p, float v) => engine.DeviceSetParam(track, di, p, v);
+ void Begin(int p) => engine.BeginAutomationWrite(track, AutomationTarget.DeviceParam, di, p, "");
+ void End(int p) => engine.EndAutomationWrite(track, AutomationTarget.DeviceParam, di, p, "");
+ void Raw(int p, float v) => engine.DeviceSetParam(track, di, p, Math.Clamp(v, mn[p], mx[p]));
+ // A discrete edit (a click) is one automation gesture, so it records while the transport does.
+ void SetP(int p, float v) { Begin(p); Raw(p, v); End(p); }
+ void Reset(int p) { Begin(p); Raw(p, engine.DeviceParamDefault(track, di, p)); End(p); }
+ bool On(int p) => P(p) >= 0.5f;
+ int Idx(int p) => Math.Clamp((int)Math.Round(P(p)), (int)mn[p], (int)mx[p]);
+
+ // ---- 0..1 mappings per param (the width puts 100 % in the middle, the cutoff is log) ----
+ const double FLo = 20, FHi = 2000;
+ double ToN(int p, double v) => p switch
+ {
+ Width_ => v <= 100 ? v / 200 : 0.5 + (v - 100) / 600,
+ MonoFreq => Math.Log(Math.Clamp(v, FLo, FHi) / FLo) / Math.Log(FHi / FLo),
+ _ => (v - mn[p]) / (mx[p] - mn[p]),
+ };
+ double FromN(int p, double n)
+ {
+ n = Math.Clamp(n, 0, 1);
+ return p switch
+ {
+ Width_ => n <= 0.5 ? n * 200 : 100 + (n - 0.5) * 600,
+ MonoFreq => FLo * Math.Pow(FHi / FLo, n),
+ _ => mn[p] + n * (mx[p] - mn[p]),
+ };
+ }
+ double N(int p) => ToN(p, P(p));
+ void SetN(int p, double n) => Raw(p, (float)FromN(p, n));
+ double DefN(int p) => ToN(p, engine.DeviceParamDefault(track, di, p));
var readouts = new List<Action>();
+ void RefreshAll() { for (int i = 0; i < readouts.Count; i++) readouts[i](); }
var scope = new float[kScope];
- var pairs = new float[kPairs * 2];
+ int scN = 0;
+ double Sc(int i) => scN > i ? scope[i] : 0;
+ double ScDb(int i) => scN > i ? scope[i] : -120;
+
+ // ---- units ----------------------------------------------------------------
+ static string Db1(double v) => NotaNum.F($"{v:+0.0;−0.0;0.0}");
+ static string GainF(double v) => NotaNum.F($"{v:+0.0;−0.0;0.0} dB");
+ static string BalF(double v) => Math.Abs(v) < 0.005 ? "C" : NotaNum.F($"{(v < 0 ? "L" : "R")} {Math.Abs(v) * 100:0}");
+ static string WidthF(double v) => NotaNum.F($"{v:0} %");
+ static string HzF(double hz) => hz >= 1000 ? NotaNum.F($"{hz / 1000:0.0#} k") : NotaNum.F($"{hz:0} Hz");
+ static string CeilF(double v) => NotaNum.F($"{v:0.0} dBTP");
+ static string CorrF(double c) => NotaNum.F($"{c:+0.00;−0.00;0.00}");
+ static string LvlF(double db) => db <= -119 ? "−∞" : NotaNum.F($"{db:0.0}");
+ int MeterI() => Idx(Meter);
+ string Unit() => Units[MeterI()];
+ string MonoF(double v) => On(MonoBelow) ? HzF(v) : "off";
+ string PhaseText() => On(InvertL) && On(InvertR) ? "both phases inverted" : On(InvertL) ? "phase L inverted" : On(InvertR) ? "phase R inverted" : "phase normal";
+ string MonoText() => On(MonoBelow) ? NotaNum.F($"mono below {HzF(P(MonoFreq))}") : "bass mono off";
+ string BalanceText()
+ {
+ double b = Sc(S_EnergyBal);
+ return Math.Abs(b) < 0.25 ? "energy L=R" : NotaNum.F($"energy {(b > 0 ? "L" : "R")} +{Math.Abs(b):0.0} dB");
+ }
+ string CorrWords()
+ {
+ double c = Sc(S_Corr);
+ if (Sc(S_OutPk) < 1e-4) return "no signal";
+ if (c < 0) return "out of phase — mono risk";
+ if (c < 0.3) return "wide — check in mono";
+ return P(Width_) > 100.5 ? "wider, still in phase" : "in phase";
+ }
+ double Delta() => ScDb(S_OutLevel) > -119 && ScDb(S_InLevel) > -119 ? Sc(S_OutLevel) - Sc(S_InLevel) : 0;
+ string DeltaText() => ScDb(S_OutLevel) > -119 && ScDb(S_InLevel) > -119 ? NotaNum.F($"Δ {Delta():+0.0;−0.0;0.0} dB") : "Δ —";
- // ---- shared small controls (mirroring the Ceiling body) --------------
- Control Toggle(int p, string label, IBrush tint)
+ // ---- small builders ---------------------------------------------------------
+ static TextBlock Caps(string t, IBrush? c = null, double fs = 7) => new()
+ { Text = t, FontSize = fs, FontWeight = FontWeight.Bold, Foreground = c ?? TextTertiary, LetterSpacing = 0.8, VerticalAlignment = VerticalAlignment.Center };
+ static TextBlock Mono(string t, double fs, IBrush c)
+ { var tb = new TextBlock { Text = t, FontSize = fs, Foreground = c, VerticalAlignment = VerticalAlignment.Center }; tb.BindResource(TextBlock.FontFamilyProperty, "Font.Mono"); return tb; }
+ static StackPanel Row(double sp, params Control[] cs)
+ { var s = new StackPanel { Orientation = Orientation.Horizontal, Spacing = sp, VerticalAlignment = VerticalAlignment.Center }; foreach (var c in cs) s.Children.Add(c); return s; }
+ static T Docked<T>(T c, Dock d) where T : Control { DockPanel.SetDock(c, d); return c; }
+ static T Col<T>(T c, int col) where T : Control { Grid.SetColumn(c, col); return c; }
+ static T GRow<T>(T c, int row) where T : Control { Grid.SetRow(c, row); return c; }
+ void Learn(Control c, int p) => MidiLearn.Bind(c, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));
+
+ // Gauge knob bound to a device param (automation gesture + MIDI learn + live follow).
+ Control K(int p, string name, Func<double, string> fmt, IBrush? arc = null, Func<bool>? dim = null, double cellW = 44)
{
- var b = new Border { CornerRadius = NotaRadius.Control, BorderThickness = new Thickness(1), Padding = new Thickness(7, 2), Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center,
- Child = new TextBlock { Text = label, FontSize = 8, FontWeight = FontWeight.Bold } };
- void Hi() { bool on = P(p) > 0.5f; b.Background = on ? NotaPalette.AccentSubtle : Sunken; b.BorderBrush = on ? NotaPalette.BorderBrass : BorderDef; ((TextBlock)b.Child!).Foreground = on ? NotaPalette.AccentHover : TextTertiary; }
- b.PointerPressed += (_, _) => { SetR(p, P(p) > 0.5f ? 0f : 1f); Hi(); };
- MidiLearn.Bind(b, MidiTarget.DeviceParam(track, di, p), label);
- readouts.Add(Hi); Hi(); return b;
+ var val = Mono(fmt(P(p)), 7, TextPrimary);
+ var knob = new Knob(N(p), 1.0) { Accent = true, ArcColor = arc, Default = DefN(p), Width = 34, Height = 34 };
+ knob.ValueChanged += v => { SetN(p, v); val.Text = fmt(P(p)); };
+ knob.GestureBegin += () => Begin(p);
+ knob.GestureEnd += () => End(p);
+ Learn(knob, p);
+ readouts.Add(() =>
+ {
+ if (dim is not null) knob.IsDim = dim();
+ if (knob.Dragging) return;
+ double c = N(p); if (Math.Abs(c - knob.Value) > 1e-4) knob.Value = c;
+ val.Text = fmt(P(p));
+ });
+ return KnobCell(name, knob, val, cellW);
}
- // Horizontal log slider for the mono-below cutoff.
- Control FreqSlider(double tw)
- {
- double mn = 20, mx = 2000, lmn = Math.Log(mn), lspan = Math.Log(mx) - lmn;
- double Norm(double v) => (Math.Log(Math.Clamp(v, mn, mx)) - lmn) / lspan;
- double Val(double n) => Math.Exp(lmn + Math.Clamp(n, 0, 1) * lspan);
- var row = DeviceCardKit.SliderRow("", () => Norm(P(MonoFreq)), n => SetR(MonoFreq, (float)Val(n)), () => $"{P(MonoFreq):0}\u2009Hz", out var sync,
- begin: () => engine.BeginAutomationWrite(track, AutomationTarget.DeviceParam, di, MonoFreq, ""),
- end: () => engine.EndAutomationWrite(track, AutomationTarget.DeviceParam, di, MonoFreq, ""),
- trackWidth: tw, valueWidth: 44);
- MidiLearn.Bind(row, MidiTarget.DeviceParam(track, di, MonoFreq), engine.DeviceParamName(track, di, MonoFreq));
+
+ // On/off switch bound to a param (> 0.5 = on).
+ Control Toggle(int p, string label, Func<string>? live = null)
+ {
+ var wrap = Switch(label, () => On(p), () => { SetP(p, On(p) ? 0f : 1f); RefreshAll(); }, out var sync, null, live);
readouts.Add(sync);
+ Learn(wrap, p);
+ return wrap;
+ }
+
+ // Segmented pill over an index param (0 … n−1 in raw units).
+ Control Seg(int p, string[] names, string tip)
+ {
+ var seg = Segments(names, () => Idx(p), iv => { SetP(p, iv); RefreshAll(); }, out var sync, padX: 6);
+ readouts.Add(sync);
+ ToolTip.SetTip(seg, tip);
+ Learn(seg, p);
+ return seg;
+ }
+
+ // Outlined chips: lit = brass edge + wash.
+ Control Chips(string[] names, Func<int, bool> lit, Action<int> pick, int learnParam, string tip, double h = 16, double padX = 7)
+ {
+ var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 3, VerticalAlignment = VerticalAlignment.Center };
+ var cells = new Border[names.Length];
+ var texts = new TextBlock[names.Length];
+ for (int i = 0; i < names.Length; i++)
+ {
+ int iv = i;
+ var tb = new TextBlock { Text = names[i], FontSize = 8, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center };
+ var b = new Border { Height = h, Padding = new Thickness(padX, 0), CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), Cursor = new Cursor(StandardCursorType.Hand), Child = tb };
+ b.PointerPressed += (_, e) => { if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return; pick(iv); RefreshAll(); e.Handled = true; };
+ cells[i] = b; texts[i] = tb; row.Children.Add(b);
+ }
+ readouts.Add(() =>
+ {
+ for (int i = 0; i < names.Length; i++)
+ {
+ bool on = lit(i);
+ cells[i].BorderBrush = on ? Brass : NotaPalette.BorderStrong;
+ cells[i].Background = on ? NotaPalette.AccentSubtle : Brushes.Transparent;
+ texts[i].Foreground = on ? AccentBright : TextSecondary;
+ texts[i].FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;
+ }
+ });
+ ToolTip.SetTip(row, tip);
+ if (learnParam >= 0) Learn(row, learnParam);
return row;
}
- static TextBlock Cap(string t) => new() { Text = t, FontSize = 8, FontWeight = FontWeight.Bold, Foreground = TextTertiary };
- Border Button(string text, Action onClick)
+ Control IndexChips(int p, string[] names, string tip, double h = 16, double padX = 7)
+ => Chips(names, i => Idx(p) == i, i => SetP(p, i), p, tip, h, padX);
+
+ // A latching chip: lit when `lit()`, a click runs `click`; its text can follow the value.
+ Border Latch(int p, Func<bool> lit, Action click, Func<string> text, string tip, bool fill = false, double h = 16, double padX = 7)
{
- var b = new Border { CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), BorderBrush = BorderStrong, Background = Card2, Padding = new Thickness(8, 3), Cursor = new Cursor(StandardCursorType.Hand),
- Child = new TextBlock { Text = text, FontSize = 9, Foreground = TextSecondary } };
- b.PointerPressed += (_, _) => onClick();
+ var tb = new TextBlock { FontSize = 8, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center };
+ var b = new Border { Height = h, Padding = new Thickness(padX, 0), CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center, Child = tb };
+ if (fill) b.HorizontalAlignment = HorizontalAlignment.Stretch;
+ void Hi()
+ {
+ bool on = lit();
+ b.Background = on ? NotaPalette.AccentSubtle : fill ? Raised : Brushes.Transparent;
+ b.BorderBrush = on ? Brass : fill ? Brushes.Transparent : NotaPalette.BorderStrong;
+ tb.Foreground = on ? AccentBright : fill ? TextPrimary : TextSecondary;
+ tb.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;
+ tb.Text = text();
+ }
+ b.PointerPressed += (_, e) => { if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return; click(); RefreshAll(); e.Handled = true; };
+ ToolTip.SetTip(b, tip);
+ if (p >= 0) Learn(b, p);
+ readouts.Add(Hi); Hi();
return b;
}
+ Border ToggleLatch(int p, Func<string> text, string tip, bool fill = false, double h = 16, double padX = 7)
+ => Latch(p, () => On(p), () => SetP(p, On(p) ? 0f : 1f), text, tip, fill, h, padX);
- // ---------- ROUTING island -------------------------------------------
- var modeChips = ChipRow(new[] { "Stereo", "Left", "Right", "Swap" },
- () => (int)Math.Round(P(ChannelMode)), v => SetR(ChannelMode, v));
- MidiLearn.Bind(modeChips, MidiTarget.DeviceParam(track, di, ChannelMode), engine.DeviceParamName(track, di, ChannelMode));
- var monoRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center,
- Children = { Toggle(MonoBelow, "MONO", Teal), FreqSlider(76) } };
- var phaseRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5,
- Children = { Toggle(Mute, "MUTE", Danger), Toggle(InvertL, "Ø L", Brass), Toggle(InvertR, "Ø R", Brass) } };
- var btnRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, Children = {
- Button("Reset", () => { for (int p = 0; p < engine.DeviceParamCount(track, di); p++) SetR(p, engine.DeviceParamDefault(track, di, p)); ctx.RequestRebuild(); }),
- Button("Gain match", GainMatch) } };
- var routing = Island("ROUTING", 206, new StackPanel { Spacing = 7, Children = {
- Cap("CHANNEL MODE"), modeChips,
- Cap("MONO BELOW"), monoRow,
- Cap("PHASE"), phaseRow,
- new Border { Height = 1, Background = Div(), Margin = new Thickness(0, 2) },
- btnRow } });
-
- // ---------- STEREO FIELD island (the hero visual) --------------------
- var gonio = new Goniometer { VerticalAlignment = VerticalAlignment.Stretch };
- var corr = new CorrMeter { Height = 12 };
- var corrVal = new TextBlock { FontSize = 9, Foreground = TextPrimary, MinWidth = 34, TextAlignment = TextAlignment.Right };
- corrVal.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");
- var widthVal = new TextBlock { FontSize = 8, Foreground = TextSecondary, HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center };
- widthVal.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");
- var fieldHead = new DockPanel { LastChildFill = false, Children = { Cap("STEREO FIELD") } };
- DockPanel.SetDock(widthVal, Dock.Right); fieldHead.Children.Add(widthVal);
- var corrRow = new DockPanel { LastChildFill = true, Margin = new Thickness(0, 6, 0, 0),
- Children = { } };
- var corrLbl = new TextBlock { Text = "CORR", FontSize = 8, FontWeight = FontWeight.Bold, Foreground = TextTertiary, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 6, 0) };
- DockPanel.SetDock(corrLbl, Dock.Left); corrRow.Children.Add(corrLbl);
- DockPanel.SetDock(corrVal, Dock.Right); corrRow.Children.Add(corrVal);
- corrRow.Children.Add(new Border { Child = corr, Margin = new Thickness(0, 0, 6, 0), VerticalAlignment = VerticalAlignment.Center });
- var fieldStack = new DockPanel { LastChildFill = true };
- DockPanel.SetDock(fieldHead, Dock.Top); fieldStack.Children.Add(fieldHead);
- DockPanel.SetDock(corrRow, Dock.Bottom); fieldStack.Children.Add(corrRow);
- fieldStack.Children.Add(new Border { Child = gonio, Margin = new Thickness(0, 6, 0, 0) });
- var field = Island("", double.NaN, fieldStack, headerless: true, custom: fieldStack); // the work column takes the rest
-
- // ---------- LEVELS island --------------------------------------------
- Action<float> inL, inR, outL, outR;
- var inMeter = MeterPair("IN", out inL, out inR);
- var outMeter = MeterPair("OUT", out outL, out outR);
- var knobRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 2, HorizontalAlignment = HorizontalAlignment.Center, Children = {
- DeviceParamControls.ParamRow(ctx, di, Gain),
- DeviceParamControls.ParamRow(ctx, di, Balance),
- DeviceParamControls.ParamRow(ctx, di, Width_) } };
- foreach (var c in knobRow.Children) if (c is StackPanel sp) sp.Width = 52;
- var metersRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 14, HorizontalAlignment = HorizontalAlignment.Center, Margin = new Thickness(0, 8, 0, 0),
- Children = { inMeter, outMeter } };
- var levels = Island("LEVELS", 172, new StackPanel { Spacing = 2, Children = { knobRow, metersRow } });
-
- // ---------- assemble + live refresh ----------------------------------
- // Three columns, the almanac order: choice (routing) → work (stereo field) → output (levels).
- var row = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), ColumnSpacing = 8 };
- row.Children.Add(routing);
- Grid.SetColumn(field, 1); row.Children.Add(field);
- Grid.SetColumn(levels, 2); row.Children.Add(levels);
- var rootBody = new Border { Padding = new Thickness(8), Child = row };
+ // A push button (an action, not a param).
+ Border Button(string text, Action click, string tip, bool primary)
+ {
+ var tb = new TextBlock { Text = text, FontSize = 8, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center,
+ FontWeight = primary ? FontWeight.SemiBold : FontWeight.Normal, Foreground = primary ? OnAccent : TextPrimary };
+ var b = new Border { Height = 16, Padding = new Thickness(7, 0), CornerRadius = NotaRadius.Badge, Background = primary ? Brass : Raised,
+ BorderBrush = primary ? Brass : NotaPalette.BorderStrong, BorderThickness = new Thickness(1),
+ Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center, Child = tb };
+ b.PointerPressed += (_, e) => { if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return; click(); RefreshAll(); e.Handled = true; };
+ ToolTip.SetTip(b, tip);
+ return b;
+ }
+
+ // Slider row: caps label · track · mono value (the track works on 0..1).
+ Control SliderRow(string label, int p, Func<double, string> fmt, bool bipolar = false, bool modulation = false, Func<bool>? dim = null, double labW = 40)
+ {
+ var bar = DeviceCardKit.SliderRow("", () => N(p), v => SetN(p, v), () => fmt(P(p)), out var sync,
+ begin: () => Begin(p), end: () => End(p), reset: () => Reset(p), bipolar: bipolar, dim: dim, valueWidth: 40, modulation: modulation);
+ readouts.Add(sync);
+ Learn(bar, p);
+ var lb = Caps(label);
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions(NotaNum.F($"{labW},*")), VerticalAlignment = VerticalAlignment.Center };
+ g.Children.Add(lb);
+ g.Children.Add(Col(bar, 1));
+ if (dim is not null) readouts.Add(() => lb.Foreground = dim() ? TextDisabled : TextTertiary);
+ return g;
+ }
+
+ static Grid HeadRow(Control left, Control right)
+ {
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), Height = 18, ColumnSpacing = 6 };
+ g.Children.Add(left); g.Children.Add(Col(right, 1));
+ return g;
+ }
+ Control KnobRow(Control[] knobs, Func<string> info1, Func<string> info2)
+ {
+ var i1 = Mono("", 7, TextTertiary); i1.HorizontalAlignment = HorizontalAlignment.Right;
+ var i2 = Mono("", 7, TextTertiary); i2.HorizontalAlignment = HorizontalAlignment.Right;
+ i1.TextTrimming = i2.TextTrimming = TextTrimming.CharacterEllipsis;
+ readouts.Add(() => { i1.Text = info1(); i2.Text = info2(); });
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), Height = 52, ColumnSpacing = 6 };
+ g.Children.Add(Row(4, knobs));
+ g.Children.Add(Col(new StackPanel { Spacing = 3, VerticalAlignment = VerticalAlignment.Center, Children = { i1, i2 } }, 1));
+ return g;
+ }
+ static Control TabBody(Control head, Control window, Control knobs) => new DockPanel
+ {
+ LastChildFill = true, Margin = new Thickness(8, 5, 8, 0),
+ Children = { Docked(head, Dock.Top), Docked(knobs, Dock.Bottom), new Border { Margin = new Thickness(0, 5, 0, 0), Child = window } },
+ };
+ // ---- actions -----------------------------------------------------------------
+ // Gain match: Gain is set so the output — metered before Gain and the auto-match ride —
+ // meets the reference (the input's level or Target) over the last 3 s, in the meter's unit.
void GainMatch()
{
- engine.DeviceScope(track, di, scope, scope.Length);
- float ip = Math.Max(scope[S_InL], scope[S_InR]), op = Math.Max(scope[S_OutL], scope[S_OutR]);
- if (ip <= 1e-5f || op <= 1e-5f) return;
- double delta = 20.0 * Math.Log10(ip / op);
- float g = (float)Math.Clamp(P(Gain) + delta, -24.0, 24.0);
- engine.BeginAutomationWrite(track, AutomationTarget.DeviceParam, di, Gain, "");
- SetR(Gain, g);
- engine.EndAutomationWrite(track, AutomationTarget.DeviceParam, di, Gain, "");
+ scN = engine.DeviceScope(track, di, scope, kBandAt);
+ double pre = ScDb(S_OutPreMatch), refL = On(MatchTo) ? P(Target) : ScDb(S_InMatch);
+ if (pre <= -70 || refL <= -70) return;
+ SetP(Gain, (float)Math.Clamp(refL - pre, -24, 24));
+ }
+ void ResetLevels()
+ {
+ SetP(Gain, 0f);
+ engine.DeviceAction(track, di, 1, 0, 0);
}
+ const string GainMatchTip = "Gain match — moves Gain once so the output meets the reference (the input's level, or Target) over the last 3 s, in the meter's unit";
+ const string ResetTip = "Reset — Gain back to 0 dB, and the meters, holds and the level history start over";
- void Refresh()
+ // ======================================================================
+ // LEFT — LEVEL column (input · output)
+ // ======================================================================
+ static AfFader MeterBar(IBrush ink) => new() { Ink = ink, Width = 16, VerticalAlignment = VerticalAlignment.Stretch, IsHitTestVisible = false };
+ var levelTitle = Caps("LEVEL"); levelTitle.HorizontalAlignment = HorizontalAlignment.Center;
+ var inMeter = MeterBar(Brass);
+ var outMeter = MeterBar(Teal);
+ var levelIn = Mono("", 7, AccentBright); levelIn.HorizontalAlignment = HorizontalAlignment.Center;
+ var levelOut = Mono("", 7, TextPrimary); levelOut.HorizontalAlignment = HorizontalAlignment.Center;
+ ToolTip.SetTip(levelIn, "The input's level in the meter's unit (LUFS-S, 1 s peak or 300 ms RMS)");
+ ToolTip.SetTip(levelOut, "The output's level in the meter's unit");
+ static double MeterN(double lin) => lin > 1e-6 ? Math.Clamp((20 * Math.Log10(lin) + 60) / 60, 0, 1) : 0;
+ readouts.Add(() =>
+ {
+ inMeter.Set(MeterN(Sc(S_InPk)), double.NaN);
+ outMeter.Set(MeterN(Sc(S_OutPk)), double.NaN);
+ levelIn.Text = LvlF(ScDb(S_InLevel));
+ levelOut.Text = NotaNum.F($"{LvlF(ScDb(S_OutLevel))} {Unit()}");
+ levelTitle.Foreground = Sc(S_InPk) > 0.01 ? AccentBright : TextTertiary; // lit while signal passes
+ });
+ Control MeterCell(AfFader m, string label, string tip)
+ {
+ var lb = Caps(label); lb.HorizontalAlignment = HorizontalAlignment.Center;
+ var d = new DockPanel { Children = { Docked(lb, Dock.Bottom), new Border { Margin = new Thickness(0, 0, 0, 3), Child = m } } };
+ ToolTip.SetTip(d, tip);
+ return d;
+ }
+ var meters = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto"), ColumnSpacing = 9, HorizontalAlignment = HorizontalAlignment.Center, Margin = new Thickness(0, 4, 0, 4) };
+ meters.Children.Add(MeterCell(inMeter, "IN", "Input peak, −60 … 0 dBFS"));
+ meters.Children.Add(Col(MeterCell(outMeter, "OUT", "Output peak, −60 … 0 dBFS"), 1));
+ var levelCol = new Border
{
- int cnt = engine.DeviceScope(track, di, scope, scope.Length);
- if (cnt >= kScope)
+ Width = 56, Background = Card2, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile, Padding = new Thickness(0, 5, 0, 4),
+ Child = new DockPanel { Children = { Docked(levelTitle, Dock.Top), Docked(levelOut, Dock.Bottom), Docked(levelIn, Dock.Bottom), meters } },
+ };
+ DockPanel.SetDock(levelCol, Dock.Left);
+
+ Control WidthModeSeg() => Seg(WidthMode, new[] { "L/R", "M/S" },
+ "Width law — L/R: the side is scaled, so wider is louder; M/S: mid and side are traded, so the level holds (200 % = side only)");
+
+ // ======================================================================
+ // CENTRE — Field
+ // ======================================================================
+ UtFieldView? field = null;
+ Control FieldTab()
+ {
+ field = new UtFieldView();
+ field.StartH = () => N(Balance);
+ field.StartV = () => N(Width_);
+ field.DragH += v => SetN(Balance, v);
+ field.DragV += v => SetN(Width_, v);
+ field.GestureBegin += () => { Begin(Balance); Begin(Width_); };
+ field.GestureEnd += () => { End(Balance); End(Width_); };
+ ToolTip.SetTip(field, "The output's stereo field by frequency over the last second — lows at the bottom, highs at the top. Brass: where each band sits between L and R; teal: how far it spreads; dashed: how far the width setting spreads an uncorrelated band. Drag sideways for the balance, up or down for the width.");
+ Learn(field, Width_);
+
+ var corr = Mono("", 7, TextTertiary);
+ readouts.Add(() => corr.Text = "corr " + CorrF(Sc(S_Corr)));
+ var chips = IndexChips(ChannelMode, Modes, "Channel — Stereo; Left or Right on both sides; Swap the sides");
+ var head = HeadRow(Row(6, Caps("CHANNEL"), chips, WidthModeSeg()), corr);
+ var knobs = KnobRow(new[]
{
- Array.Copy(scope, kMeters, pairs, 0, kPairs * 2);
- gonio.Set(pairs, kPairs);
- float c = scope[S_Corr];
- corr.Set(c);
- corrVal.Text = $"{c:+0.00;−0.00;0.00}";
- corrVal.Foreground = c < 0 ? Danger : c < 0.3f ? Brass : TextPrimary;
- inL(scope[S_InL]); inR(scope[S_InR]); outL(scope[S_OutL]); outR(scope[S_OutR]);
- }
- widthVal.Text = $"width {P(Width_):0}\u2009%";
- foreach (var a in readouts) a();
+ K(Gain, "GAIN", GainF),
+ K(Balance, "BALANCE", BalF),
+ K(Width_, "WIDTH", WidthF),
+ K(MonoFreq, "MONO", MonoF, dim: () => !On(MonoBelow)),
+ },
+ () => NotaNum.F($"correlation {CorrF(Sc(S_Corr))} · {BalanceText()}"),
+ () => NotaNum.F($"{PhaseText()} · {MonoText()}"));
+ return TabBody(head, field, knobs);
}
- ctx.AddDeviceRefresher(Refresh);
- Refresh();
- return rootBody;
- }
- private static IBrush Div() => NotaPalette.SurfaceRaised;
+ // ======================================================================
+ // CENTRE — Mono
+ // ======================================================================
+ UtWidthView? widthView = null;
+ Control MonoTab()
+ {
+ widthView = new UtWidthView();
+ widthView.StartH = () => N(MonoFreq);
+ widthView.StartV = () => N(Width_);
+ widthView.DragH += v => SetN(MonoFreq, v);
+ widthView.DragV += v => SetN(Width_, v);
+ widthView.GestureBegin += () => { Begin(MonoFreq); Begin(Width_); };
+ widthView.GestureEnd += () => { End(MonoFreq); End(Width_); };
+ ToolTip.SetTip(widthView, "The width over frequency — brass: what the settings do (0 % = mono, 100 % = unchanged), the mono region shaded; teal dashed: the output's measured width (side against mid). Drag sideways for the mono cutoff, up or down for the width.");
+ Learn(widthView, MonoFreq);
- // A titled bordered island panel (fixed width). headerless/custom lets the
- // stereo-field island supply its own dock layout that fills the height.
- private static Control Island(string title, double width, Control body, bool headerless = false, Control? custom = null)
- {
- Control inner = headerless ? custom! : new StackPanel { Spacing = 6, Children = {
- new TextBlock { Text = title, FontSize = 9, FontWeight = FontWeight.Bold, Foreground = TextSecondary }, body } };
- return new Border { Width = width, Background = Card2, BorderBrush = BorderDef, BorderThickness = new Thickness(1),
- CornerRadius = NotaRadius.Panel, Padding = new Thickness(9, 8), Child = inner };
- }
+ var wv = Mono("", 7, AccentBright);
+ readouts.Add(() => wv.Text = NotaNum.F($"width {Sc(S_EffWidth):0}"));
+ var onOff = ToggleLatch(MonoBelow, () => On(MonoBelow) ? "On" : "Off", "Mono below — removes the side below the cutoff, so the low end is mono");
+ float[] quick = { 60, 120, 240 };
+ var quickSeg = Segments(new[] { "60", "120", "240" }, () => NearestHz(P(MonoFreq), quick), iv => { SetP(MonoFreq, quick[iv]); if (!On(MonoBelow)) SetP(MonoBelow, 1f); RefreshAll(); }, out var qSync, padX: 6);
+ readouts.Add(qSync);
+ ToolTip.SetTip(quickSeg, "The usual cutoffs — 60, 120 or 240 Hz (turns Mono below on)");
+ Learn(quickSeg, MonoFreq);
+ var slope = Latch(MonoSlope, () => Idx(MonoSlope) > 0, () => SetP(MonoSlope, (Idx(MonoSlope) + 1) % 3),
+ () => NotaNum.F($"Slope {Slopes[Idx(MonoSlope)]}"), "Slope of the mono cutoff — 6, 12 or 24 dB/oct; click to step");
+ var head = HeadRow(Row(6, Caps("MONO"), onOff, quickSeg, WidthModeSeg(), slope), wv);
+ var knobs = KnobRow(new[]
+ {
+ K(MonoFreq, "MONO", MonoF, dim: () => !On(MonoBelow)),
+ K(Width_, "WIDTH", WidthF),
+ K(Balance, "BALANCE", BalF, Teal),
+ K(Gain, "GAIN", GainF, Teal),
+ },
+ () => On(MonoBelow) ? NotaNum.F($"below {HzF(P(MonoFreq))} width 0 · slope {Slopes[Idx(MonoSlope)]} dB/oct") : NotaNum.F($"full range · width {Sc(S_EffWidth):0} %"),
+ () => NotaNum.F($"correlation {CorrF(Sc(S_Corr))} · {(Sc(S_Corr) >= 0.3 || Sc(S_OutPk) < 1e-4 ? "mono-safe" : Sc(S_Corr) >= 0 ? "check in mono" : "mono risk")}"));
+ return TabBody(head, widthView, knobs);
+ }
- // IN/OUT peak meter: two vertical bars (L/R) with peak-hold + a caption. Returns
- // the control and per-channel setters (linear peak in, dB internally).
- private static Control MeterPair(string label, out Action<float> setL, out Action<float> setR)
- {
- Border Bar(out Action<float> set)
+ // ======================================================================
+ // CENTRE — Levels
+ // ======================================================================
+ UtLevelView? levelView = null;
+ Control LevelsTab()
{
- const double H = 96;
- var fill = new Border { Background = Success, CornerRadius = NotaRadius.Bar, VerticalAlignment = VerticalAlignment.Bottom, Height = 0 };
- var track = new Border { Width = 9, Height = H, Background = Sunken, CornerRadius = NotaRadius.Clip, ClipToBounds = true, Child = fill };
- float hold = -120;
- set = peak =>
+ levelView = new UtLevelView();
+ levelView.StartV = () => N(Target);
+ levelView.DragV += v => SetN(Target, v);
+ levelView.GestureBegin += () => Begin(Target);
+ levelView.GestureEnd += () => End(Target);
+ ToolTip.SetTip(levelView, "Input (teal) and output (brass) over the last 8 s in the meter's unit; dashed: the target. Drag up or down for the target.");
+ Learn(levelView, Target);
+
+ var delta = Mono("", 7, AccentBright);
+ readouts.Add(() => delta.Text = DeltaText());
+ var chips = IndexChips(Meter, Meters, "Meter — LUFS-S: short-term loudness (3 s, K-weighted); Peak: sample peak; RMS: 300 ms");
+ var head = HeadRow(Row(6, Caps("METER"), chips, Button("Gain match", GainMatch, GainMatchTip, true), Button("Reset", ResetLevels, ResetTip, false)), delta);
+ var knobs = KnobRow(new[]
{
- float db = peak > 1e-6f ? 20f * (float)Math.Log10(peak) : -120f;
- if (db > hold) hold = db; else hold -= 2.0f; // ~fast attack, slow decay per tick
- double n = Math.Clamp((hold + 60.0) / 60.0, 0, 1); // -60..0 dB
- fill.Height = n * H;
- fill.Background = hold > -0.2f ? Danger : hold > -6f ? Brass : Success;
+ K(Gain, "GAIN", GainF),
+ K(Balance, "BALANCE", BalF, Teal),
+ K(Width_, "WIDTH", WidthF, Teal),
+ K(Target, "TARGET", v => NotaNum.F($"{v:0.0}"), Teal),
+ },
+ () => NotaNum.F($"in {LvlF(ScDb(S_InLevel))} → out {LvlF(ScDb(S_OutLevel))} {Meters[MeterI()]}"),
+ () => ScDb(S_TruePeak) > -119 ? NotaNum.F($"true peak {Sc(S_TruePeak):0.0} dBTP · headroom {Math.Max(0, -Sc(S_TruePeak)):0.0} dB") : "true peak —");
+ return TabBody(head, levelView, knobs);
+ }
+
+ // ======================================================================
+ // RIGHT — Routing / Output
+ // ======================================================================
+ static Control Spread(params Control[] rows)
+ {
+ var defs = new List<string>();
+ for (int i = 0; i < rows.Length; i++) { if (i > 0) defs.Add("*"); defs.Add("Auto"); }
+ var g = new Grid { RowDefinitions = new RowDefinitions(string.Join(",", defs)) };
+ for (int i = 0; i < rows.Length; i++) g.Children.Add(GRow(rows[i], i * 2));
+ return new Border { Padding = new Thickness(8, 6), Child = g };
+ }
+ static Control LabelRow(string label, Control c, double labW = 40)
+ {
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions(NotaNum.F($"{labW},*")) };
+ g.Children.Add(new TextBlock { Text = label, FontSize = 7, FontWeight = FontWeight.Bold, Foreground = TextTertiary, LetterSpacing = 0.8, VerticalAlignment = VerticalAlignment.Center });
+ g.Children.Add(Col(c, 1));
+ return g;
+ }
+ Control Divided(Control c) => new Border { BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(0, 5, 0, 0), Child = c };
+
+ Control RoutingTab()
+ {
+ var phase = Row(3,
+ ToggleLatch(InvertL, () => "Ø L", "Invert the left channel's phase", h: 15, padX: 6),
+ ToggleLatch(InvertR, () => "Ø R", "Invert the right channel's phase", h: 15, padX: 6),
+ ToggleLatch(Mute, () => "Mute", "Mute the output", h: 15, padX: 6));
+ // Mono on: WIDTH · MONO f | BALANCE; off: WIDTH · BALANCE | GAIN — the mockup's two states.
+ var monoRow = SliderRow("MONO f", MonoFreq, HzF);
+ var balA = SliderRow("BALANCE", Balance, v => NotaNum.F($"{v:+0.00;−0.00;0.00}"), bipolar: true);
+ var balB = SliderRow("BALANCE", Balance, v => NotaNum.F($"{v:+0.00;−0.00;0.00}"), bipolar: true, modulation: true);
+ var gainRow = SliderRow("GAIN", Gain, Db1, bipolar: true);
+ var slot2 = new Panel { Children = { monoRow, balA } };
+ var slot3 = new Panel { Children = { balB, gainRow } };
+ readouts.Add(() => { bool m = On(MonoBelow); monoRow.IsVisible = m; balA.IsVisible = !m; balB.IsVisible = m; gainRow.IsVisible = !m; });
+
+ var corrBar = new UtCorrBar();
+ var corrTitle = Caps("CORRELATION");
+ var corrText = Mono("", 9, TextPrimary);
+ corrText.TextTrimming = TextTrimming.CharacterEllipsis;
+ var corrBox = new Border { Background = Sunken, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge, Padding = new Thickness(6, 4),
+ Child = new StackPanel { Spacing = 3, Children = { corrTitle, corrBar, corrText } } };
+ ToolTip.SetTip(corrBox, "Output correlation — +1 mono, 0 unrelated, below 0 out of phase (it cancels in mono)");
+ readouts.Add(() =>
+ {
+ double c = Sc(S_Corr);
+ corrBar.Set(c);
+ corrText.Text = NotaNum.F($"{CorrF(c)} · {CorrWords()}");
+ bool lit = Math.Abs(P(Width_) - 100) > 0.5 || On(MonoBelow);
+ corrBox.BorderBrush = lit ? NotaPalette.BorderBrass : NotaPalette.GraphBorder;
+ corrTitle.Foreground = lit ? AccentBright : TextTertiary;
+ corrText.Foreground = c < 0 && Sc(S_OutPk) > 1e-4 ? Danger : lit ? AccentBright : TextPrimary;
+ });
+ return Spread(
+ LabelRow("PHASE", phase, 40),
+ SliderRow("WIDTH", Width_, v => NotaNum.F($"{v:0}")),
+ slot2,
+ Divided(slot3),
+ corrBox,
+ new StackPanel { Spacing = 5, Children = {
+ Toggle(MonoBelow, "Mono below freq", () => On(MonoBelow) ? NotaNum.F($"Mono below {HzF(P(MonoFreq))}") : "Mono below freq"),
+ Toggle(AutoMatch, "Level match", () => On(AutoMatch) ? NotaNum.F($"Level match {Sc(S_AutoDb):+0.0;−0.0;0.0} dB") : "Level match") } });
+ }
+
+ Control OutputTab()
+ {
+ Control Line(string k, Func<string> v, IBrush? ink = null)
+ {
+ var val = Mono("", 8, ink ?? TextPrimary); val.HorizontalAlignment = HorizontalAlignment.Right;
+ readouts.Add(() => val.Text = v());
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
+ g.Children.Add(new TextBlock { Text = k, FontSize = 8, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center });
+ g.Children.Add(Col(val, 1));
+ return g;
+ }
+ var box = new Border
+ {
+ Background = Sunken, BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge, Padding = new Thickness(6, 3),
+ Child = new StackPanel { Spacing = 1, Children = {
+ Caps("MEASUREMENTS"),
+ Line("in", () => NotaNum.F($"{LvlF(ScDb(S_InLevel))} {Unit()}")),
+ Line("out", () => NotaNum.F($"{LvlF(ScDb(S_OutLevel))} {Unit()}")),
+ Line("true peak", () => NotaNum.F($"{LvlF(ScDb(S_TruePeak))} dBTP"), AccentBright) } },
};
- return track;
+ var matchTo = Seg(MatchTo, new[] { "Input", "Target" }, "What Gain match and Level match aim for — the input's level, or Target");
+ var btns = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*"), ColumnSpacing = 6 };
+ var gm = Button("Gain match", GainMatch, GainMatchTip, false);
+ gm.Background = NotaPalette.AccentSubtle; gm.BorderBrush = Brass; gm.BorderThickness = new Thickness(1);
+ ((TextBlock)gm.Child!).Foreground = AccentBright; ((TextBlock)gm.Child!).FontWeight = FontWeight.SemiBold;
+ btns.Children.Add(gm);
+ btns.Children.Add(Col(Button("Reset", ResetLevels, ResetTip, false), 1));
+ return Spread(
+ box,
+ SliderRow("GAIN", Gain, Db1, bipolar: true),
+ SliderRow("TARGET", Target, v => NotaNum.F($"{v:0.0}"), modulation: true),
+ SliderRow("CEILING", TpCeiling, v => NotaNum.F($"{v:0.0}"), dim: () => !On(TpLimit)),
+ LabelRow("MATCH", matchTo, 40),
+ Divided(btns),
+ new StackPanel { Spacing = 5, Children = {
+ Toggle(AutoMatch, "Level match", () => On(AutoMatch) ? NotaNum.F($"Level match {Sc(S_AutoDb):+0.0;−0.0;0.0} dB") : "Level match"),
+ Toggle(TpLimit, "True-peak limiter", () => On(TpLimit) ? NotaNum.F($"TP limit {CeilF(P(TpCeiling))}{(Sc(S_LimDb) > 0.05 ? NotaNum.F($" · −{Sc(S_LimDb):0.0}") : "")}") : "True-peak limiter") } });
}
- var l = Bar(out setL); var r = Bar(out setR);
- var bars = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 3, HorizontalAlignment = HorizontalAlignment.Center, Children = { l, r } };
- var cap = new TextBlock { Text = label, FontSize = 8, FontWeight = FontWeight.Bold, Foreground = TextTertiary, HorizontalAlignment = HorizontalAlignment.Center, Margin = new Thickness(0, 3, 0, 0) };
- return new StackPanel { Spacing = 0, Children = { bars, cap } };
- }
- // Goniometer / vectorscope: plots recent output (L,R) pairs in mid/side
- // coordinates (mono = vertical, anti-phase = horizontal), over L/R diagonal axes.
- private sealed class Goniometer : Control
- {
- private static readonly IBrush Bg = NotaPalette.BgSunken;
- private static readonly IBrush Grid = NotaPalette.SurfaceCard;
- private static readonly IBrush Diag = NotaPalette.SurfaceRaised;
- private static readonly IBrush Dot = NotaPalette.Wash(NotaPalette.Marker, 0xCC);
- private float[]? _p; private int _n;
-
- public void Set(float[] p, int n) { _p = p; _n = n; InvalidateVisual(); }
-
- public override void Render(DrawingContext ctx)
- {
- double w = Bounds.Width, h = Bounds.Height;
- if (w <= 2 || h <= 2) return;
- ctx.DrawRectangle(Bg, null, new RoundedRect(new Rect(0, 0, w, h), 4));
- double cx = w / 2, cy = h / 2;
- ctx.DrawLine(new Pen(Grid, 1), new Point(cx, 0), new Point(cx, h));
- ctx.DrawLine(new Pen(Grid, 1), new Point(0, cy), new Point(w, cy));
- var dash = new Pen(Diag, 1) { DashStyle = new DashStyle(new double[] { 3, 3 }, 0) };
- ctx.DrawLine(dash, new Point(0, h), new Point(w, 0));
- ctx.DrawLine(dash, new Point(0, 0), new Point(w, h));
- if (_p is null || _n <= 0) return;
- // Instantaneous samples sit well below the peak the meters show, so a raw plot
- // collapses to a dot near the centre. Boost so program material fills the scope
- // (loud peaks clip at the edges, which is the expected goniometer behaviour).
- const double gain = 2.4;
- double scale = Math.Min(w, h) * 0.5 * gain;
- using var clip = ctx.PushClip(new Rect(0, 0, w, h));
- for (int k = 0; k < _n; k++)
+ // ======================================================================
+ // Tab frames
+ // ======================================================================
+ int centreTab = 0;
+ var centreHost = new ContentControl();
+ var rightHost = new ContentControl();
+ var centreBodies = new Control?[3];
+ var rightBodies = new Control?[2];
+ var extras = Mono("", 7, TextTertiary);
+ readouts.Add(() =>
+ {
+ extras.Text = centreTab switch
{
- float l = _p[k * 2], r = _p[k * 2 + 1];
- double x = cx + (l - r) * 0.5 * scale; // side → horizontal
- double y = cy - (l + r) * 0.5 * scale; // mid → vertical
- ctx.FillRectangle(Dot, new Rect(x - 0.9, y - 0.9, 1.8, 1.8));
+ 1 => NotaNum.F($"width by frequency · {(On(WidthMode) ? "M/S" : "L/R")}"),
+ 2 => NotaNum.F($"{Sc(S_HistSec):0} s window · {Meters[MeterI()]}"),
+ _ => "pan by frequency · 1 s window",
+ };
+ });
+ Control CentreBody(int t) => centreBodies[t] ??= t switch { 1 => MonoTab(), 2 => LevelsTab(), _ => FieldTab() };
+ Control RightBody(int t) => rightBodies[t] ??= t == 1 ? OutputTab() : RoutingTab();
+
+ var centre = TabFrame(new[] { "Field", "Mono", "Levels" }, centreHost, CentreBody, false, t => { centreTab = t; Refresh(); }, extras);
+ var rightFrame = TabFrame(new[] { "Routing", "Output" }, rightHost, RightBody, true, _ => RefreshAll(), null);
+ var right = new Border { Width = 186, Background = Card2, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile, ClipToBounds = true, Child = rightFrame };
+ DockPanel.SetDock(right, Dock.Right);
+ var centreBox = new Border { Background = Card2, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile, Margin = new Thickness(5, 0), ClipToBounds = true, Child = centre };
+
+ // ======================================================================
+ // Status strip
+ // ======================================================================
+ var statusLeft = new TextBlock { FontSize = 8, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };
+ var statusRight = Mono("", 8, TextSecondary);
+ string StatusText()
+ {
+ var parts = new List<string>();
+ switch (centreTab)
+ {
+ case 1:
+ parts.Add(On(WidthMode) ? "M/S" : "L/R");
+ parts.Add(On(MonoBelow) ? NotaNum.F($"mono ↓ {HzF(P(MonoFreq))} · {Slopes[Idx(MonoSlope)]} dB/oct") : "mono off");
+ parts.Add(NotaNum.F($"width {P(Width_):0}"));
+ parts.Add(NotaNum.F($"balance {BalF(P(Balance))}"));
+ if (On(InvertL)) parts.Add("Ø L");
+ if (On(InvertR)) parts.Add("Ø R");
+ parts.Add("gain " + GainF(P(Gain)));
+ break;
+ case 2:
+ parts.Add(Meters[MeterI()]);
+ parts.Add("in " + LvlF(ScDb(S_InLevel)));
+ parts.Add("out " + LvlF(ScDb(S_OutLevel)));
+ parts.Add(On(MatchTo) ? NotaNum.F($"target {P(Target):0.0}") : "match to input");
+ parts.Add("gain " + GainF(P(Gain)));
+ if (On(AutoMatch)) parts.Add(NotaNum.F($"auto {Sc(S_AutoDb):+0.0;−0.0;0.0} dB"));
+ if (On(TpLimit)) parts.Add("TP " + CeilF(P(TpCeiling)));
+ parts.Add(NotaNum.F($"width {P(Width_):0}"));
+ break;
+ default:
+ parts.Add(Modes[Idx(ChannelMode)]);
+ parts.Add("gain " + Db1(P(Gain)));
+ parts.Add(NotaNum.F($"balance {BalF(P(Balance))}"));
+ parts.Add(NotaNum.F($"width {P(Width_):0}{(On(WidthMode) ? " M/S" : "")}"));
+ parts.Add(On(MonoBelow) ? NotaNum.F($"mono ↓ {HzF(P(MonoFreq))}") : "mono off");
+ parts.Add(PhaseText());
+ if (On(Mute)) parts.Add("muted");
+ break;
}
+ return string.Join(" · ", parts);
}
- }
+ readouts.Add(() =>
+ {
+ statusLeft.Text = StatusText();
+ double sr = Sc(S_SampleRate);
+ statusRight.Text = sr > 0 ? NotaNum.F($"{sr / 1000:0.#} kHz · latency 0 smp · CPU {Sc(S_Cpu) * 100:0.0} %") : "";
+ });
+ var statusGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 8 };
+ statusGrid.Children.Add(statusLeft);
+ statusGrid.Children.Add(Col(statusRight, 1));
+ var status = new Border { Height = 18, Background = Sunken, BorderBrush = BorderDef, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(8, 0), Child = statusGrid };
+ DockPanel.SetDock(status, Dock.Bottom);
- // Correlation meter: −1 (left) … +1 (right); the negative "mono-risk" half is
- // tinted red, a needle marks the current value (red when out of phase).
- private sealed class CorrMeter : Control
- {
- private static readonly IBrush Bg = NotaPalette.BgSunken;
- private static readonly IBrush Risk = NotaPalette.Wash(NotaPalette.Danger, 0x33);
- private static readonly IBrush Tick = NotaPalette.BorderStrong;
- private float _c = 1;
- public void Set(float c) { _c = Math.Clamp(c, -1, 1); InvalidateVisual(); }
- public override void Render(DrawingContext ctx)
- {
- double w = Bounds.Width, h = Bounds.Height;
- if (w <= 2 || h <= 2) return;
- var rr = new RoundedRect(new Rect(0, 0, w, h), 3);
- ctx.DrawRectangle(Bg, null, rr);
- using (ctx.PushClip(rr)) ctx.FillRectangle(Risk, new Rect(0, 0, w / 2, h)); // corr < 0 zone
- ctx.DrawLine(new Pen(Tick, 1), new Point(w / 2, 0), new Point(w / 2, h));
- double pos = (_c + 1) / 2 * w;
- var needle = _c < 0 ? NotaPalette.Danger : _c < 0.3f ? NotaPalette.Accent : NotaPalette.Success;
- ctx.FillRectangle(needle, new Rect(Math.Clamp(pos - 1.5, 0, w - 3), 0, 3, h));
+ // ---- assemble ---------------------------------------------------------------
+ var bodyRow = new DockPanel { LastChildFill = true, Margin = new Thickness(5), Children = { levelCol, right, centreBox } };
+ var root = new DockPanel { LastChildFill = true, Background = NotaPalette.SurfaceInset, Children = { status, bodyRow } };
+
+ void Refresh()
+ {
+ // The band analysis (an FFT) runs only while a tab that draws it is showing.
+ bool bands = centreTab != 2;
+ scN = engine.DeviceScope(track, di, scope, bands ? kScope : kBandAt);
+ bool haveBands = bands && scN >= kScope && Sc(S_Analysed) > 0.5;
+ bool loud = false;
+ if (haveBands) for (int b = 0; b < kBands; b++) if (scope[kBandAt + B_Level * kBands + b] > -100) { loud = true; break; }
+ if (centreTab == 0 && field is not null && !field.Dragging)
+ field.Set(scope, kBandAt + B_Pan * kBands, kBandAt + B_Width * kBands, kBandAt + B_Level * kBands, kBandAt + B_Set * kBands, haveBands ? kBands : 0,
+ haveBands && loud, Sc(S_BandLo), Sc(S_BandHi), NotaNum.F($"width {P(Width_):0} %"));
+ if (centreTab == 1 && widthView is not null && !widthView.Dragging)
+ widthView.Set(scope, kRespAt, haveBands ? kResp : 0, Sc(S_RespLo), Sc(S_RespHi), kBandAt + B_Width * kBands, kBandAt + B_Level * kBands, haveBands ? kBands : 0,
+ Sc(S_BandLo), Sc(S_BandHi), haveBands && loud, On(MonoBelow) ? P(MonoFreq) : double.NaN, NotaNum.F($"{Sc(S_EffWidth):0} %"));
+ if (centreTab == 2 && levelView is not null && !levelView.Dragging)
+ {
+ int m = MeterI();
+ int hin = m == 0 ? H_InLufs : m == 1 ? H_InPeak : H_InRms, hout = m == 0 ? H_OutLufs : m == 1 ? H_OutPeak : H_OutRms;
+ levelView.Set(scope, kHistAt + hin * kHist, kHistAt + hout * kHist, scN >= kBandAt ? kHist : 0,
+ On(MatchTo) ? P(Target) : double.NaN, Sc(S_HistSec) > 0 ? Sc(S_HistSec) : 8,
+ NotaNum.F($"{LvlF(ScDb(S_OutLevel))} {Unit()}"),
+ On(MatchTo) ? NotaNum.F($"target {P(Target):0.0}") : "target = input");
+ }
+ RefreshAll();
+ }
+ ctx.AddDeviceRefresher(Refresh);
+ Refresh();
+ return root;
+
+ static int NearestHz(float v, float[] hz)
+ {
+ for (int i = 0; i < hz.Length; i++) if (Math.Abs(v - hz[i]) < 0.5f) return i;
+ return -1;
+ }
+
+ // local: a tab frame (bar + swapping body), optional extras on the right of the bar.
+ Control TabFrame(string[] tabs, ContentControl host, Func<int, Control> body, bool centered, Action<int>? changed, Control? extrasCtl)
+ {
+ int sel = 0;
+ var btns = new Border[tabs.Length];
+ void Hi()
+ {
+ for (int i = 0; i < tabs.Length; i++)
+ {
+ bool on = i == sel;
+ btns[i].Background = on ? Card2 : Brushes.Transparent;
+ btns[i].BorderBrush = on ? Brass : Brushes.Transparent;
+ var tb = (TextBlock)btns[i].Child!;
+ tb.Foreground = on ? AccentBright : TextTertiary;
+ tb.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;
+ }
+ }
+ var bar = centered ? (Avalonia.Controls.Panel)new UniformGrid { Rows = 1 } : new StackPanel { Orientation = Orientation.Horizontal };
+ for (int i = 0; i < tabs.Length; i++)
+ {
+ int iv = i;
+ var b = new Border
+ {
+ Padding = new Thickness(9, 0), BorderThickness = new Thickness(0, 0, 0, 2), BorderBrush = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand),
+ Child = new TextBlock { Text = tabs[i], FontSize = 9, Foreground = TextTertiary, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center },
+ };
+ b.PointerPressed += (_, _) => { sel = iv; Hi(); host.Content = body(iv); changed?.Invoke(iv); };
+ btns[i] = b;
+ bar.Children.Add(b);
+ }
+ var barDock = new DockPanel { Height = 20, LastChildFill = centered };
+ if (extrasCtl != null) { var ex = new Border { Padding = new Thickness(0, 0, 8, 0), Child = extrasCtl }; DockPanel.SetDock(ex, Dock.Right); barDock.Children.Add(ex); }
+ if (!centered) DockPanel.SetDock(bar, Dock.Left);
+ barDock.Children.Add(bar);
+ var barBorder = new Border { BorderBrush = BorderDef, BorderThickness = new Thickness(0, 0, 0, 1), Child = barDock };
+ DockPanel.SetDock(barBorder, Dock.Top);
+ Hi();
+ host.Content = body(sel);
+ return new DockPanel { LastChildFill = true, Children = { barBorder, host } };
}
}
}
diff --git a/src/managed/Nota.App/DeviceCards/Instruments/PhysicalInstrumentCard.cs b/src/managed/Nota.App/DeviceCards/Instruments/PhysicalInstrumentCard.cs
index f104b8c3..f460e493 100644
--- a/src/managed/Nota.App/DeviceCards/Instruments/PhysicalInstrumentCard.cs
+++ b/src/managed/Nota.App/DeviceCards/Instruments/PhysicalInstrumentCard.cs
@@ -1,12 +1,23 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
-// Detail · Devices — built-in Nota Physical editor (instrument kind 2): a modal
-// physical-modeling voice laid out as its signal chain across two tabs — EXCITER
-// (Mallet → Noise, the noise burst carrying an interactive ADSR graph) and RESONATOR
-// (Res 1 / Res 2 banks with a material Type chip row, a live modal-partial spectrum,
-// and the tuning/damping knobs) plus a global OUTPUT panel. Follows automation live
-// via RefreshSynthLive. Uses the shared gauge Knob and the DeviceCardKit tokens.
+// Detail · Devices — built-in Nota Physical editor (instrument kind 2): a modal voice in
+// the 700 × 260 card the almanac draws for it. The chain reads left to right — what
+// strikes, what rings, what comes out; the tabs pick what the centre shows.
+//
+// Centre two tabs:
+// Exciter — the mallet (level, stiffness, strike noise, colour) › the
+// noise burst: its filter type, a draggable ADSR with the
+// stage times under it, level, envelope → filter, freq, reso.
+// Resonator — bank 1 / 2, on / off, the material type and the structure
+// (1→2 serial, 1+2 parallel); the bank's partials as the engine
+// tunes them (drag: ↔ ratio, ↕ bright) beside its seven knobs
+// and the 1+2 mix.
+// Rail 186 Output: Poly / Mono, tune, fine and note-off rows, volume, pan and the
+// track's meter.
+//
+// Brass is the parameter itself; teal is modulation. Everything is a plugin param →
+// automation / persist / clone, and the card follows automation live.
using System;
using System.Collections.Generic;
@@ -15,6 +26,7 @@ using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
+using Nota.Application;
using static Nota.App.DeviceCardKit;
namespace Nota.App;
@@ -23,7 +35,30 @@ internal sealed class PhysicalInstrumentCard : IInstrumentCard
{
public bool BodyOnly => true;
public string Subtitle => "MODAL";
- public double CardWidth => 720;
+ public double CardWidth => 700;
+
+ public string? VoiceLabel(IAudioEngine engine, int trackId, int active)
+ {
+ int mi = -1;
+ for (int i = 0, n = engine.PluginParamCount(trackId, -1); i < n; i++)
+ if (engine.PluginParamId(trackId, -1, i) == "mono") { mi = i; break; }
+ return mi >= 0 && engine.PluginParamGet(trackId, -1, mi) >= 0.5f ? "MONO" : $"{Math.Max(0, active)}/{PhysicalModel.Voices}";
+ }
+
+ private const double RailW = 186, TabH = 20, StatusH = 18, KnobS = 30;
+
+ private static readonly string[] TabNames = { "Exciter", "Resonator" };
+ private static readonly string[] TypeNames = PhysicalModel.TypeNames;
+
+ private static string Pct(float v) => NotaNum.Pct(v);
+ private static string Bip(float v) => NotaNum.Unit((v - 0.5f) * 200, "+0;−0;0", "%");
+ private static string Secs(double s) => NotaNum.Time(s);
+ private static string Semis(double st, string f = "+0;−0;0") => NotaNum.Unit(st, f, "st");
+ private static string PanText(float v)
+ {
+ double p = (v - 0.5) * 200;
+ return Math.Abs(p) < 0.5 ? "C" : (p < 0 ? "L" : "R") + NotaNum.Str(Math.Abs(p), "0");
+ }
public Control Build(DeviceCardContext ctx)
{
@@ -32,160 +67,486 @@ internal sealed class PhysicalInstrumentCard : IInstrumentCard
int pc = engine.PluginParamCount(track, -1);
var idx = new Dictionary<string, int>();
for (int i = 0; i < pc; i++) idx[engine.PluginParamId(track, -1, i)] = i;
- float G(string id) => idx.TryGetValue(id, out var i) ? engine.PluginParamGet(track, -1, i) : 0f;
int I(string id) => idx.TryGetValue(id, out var i) ? i : -1;
+ float G(string id) => I(id) is var i and >= 0 ? engine.PluginParamGet(track, -1, i) : 0f;
+ void SetP(string id, float v) { if (I(id) is var i and >= 0) engine.PluginParamSet(track, -1, i, Math.Clamp(v, 0f, 1f)); }
+ void Begin(string id) { if (I(id) >= 0) engine.BeginAutomationWrite(track, AutomationTarget.PluginParam, -1, -1, id); }
+ void End(string id) { if (I(id) >= 0) engine.EndAutomationWrite(track, AutomationTarget.PluginParam, -1, -1, id); }
+ void Write(string id, float v) { Begin(id); SetP(id, v); End(id); }
+ int Sel(string id, int n) => Math.Clamp((int)Math.Round(G(id) * (n - 1)), 0, n - 1);
(int, string) P(string id) => (I(id), id);
+ bool IsMono() => G("mono") >= 0.5f;
+ bool R2On() => G("r2on") >= 0.5f;
+ bool Serial() => G("structure") < 0.5f;
+ string TypeWord(string pre) => TypeNames[PhysicalModel.TypeIndex(G(pre + "type"))].ToLowerInvariant();
- int rsel = 0; // which resonator bank the Type/knobs edit
var readouts = new List<Action>();
- var viz = new CollisionViz();
- var noiseEnv = new VoltEnv(engine, track);
+ int tab = 0, bank = 0;
+ var scope = new float[PhysicalModel.ScopeLength];
+
+ var noiseEnv = new VoltEnv(engine, track) { VerticalAlignment = VerticalAlignment.Stretch, MinWidth = 90, MinHeight = 50 };
noiseEnv.Target("NOISE ENV", P("noisea"), P("noised"), P("noises"), P("noiser"));
+ var partials = new PhysPartialsView { VerticalAlignment = VerticalAlignment.Stretch };
+ ToolTip.SetTip(partials, "Partials as the engine tunes them — drag ↔ to spread the series (Ratio), ↕ to tilt the highs (Bright)");
+
+ static TextBlock Cap(string t, IBrush? c = null) => new()
+ {
+ Text = t, FontSize = NotaType.KnobLabel, FontWeight = FontWeight.Bold,
+ LetterSpacing = NotaType.KnobLabelTracking, Foreground = c ?? TextTertiary,
+ VerticalAlignment = VerticalAlignment.Center,
+ };
+ static TextBlock Mono(string t, IBrush? c = null, double fs = 8) => new()
+ {
+ Text = t, FontSize = fs, Foreground = c ?? TextSecondary,
+ VerticalAlignment = VerticalAlignment.Center, FontFamily = NotaFonts.MonoFamily,
+ };
+
+ var hint = Mono("", TextTertiary, NotaType.Axis);
+ hint.HorizontalAlignment = HorizontalAlignment.Right; hint.Margin = new Thickness(0, 0, 8, 0);
+ hint.TextTrimming = TextTrimming.CharacterEllipsis;
+ var status = new TextBlock { FontSize = 8, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };
+ var meta = Mono("", TextSecondary);
+ Action showTab = () => { };
+
+ // The partial window: the selected bank's modes from the engine's scope, the other
+ // bank behind when it sounds, and how many of them the reference note can hold.
+ void RefreshPartials()
+ {
+ int n = engine.InstrumentScope(track, scope);
+ var s = scope.AsSpan(0, Math.Max(0, n));
+ var mine = PhysicalModel.Bank(s, bank);
+ var other = PhysicalModel.Bank(s, 1 - bank);
+ bool r2 = R2On();
+ double sr = engine.SampleRate > 0 ? engine.SampleRate : 48000;
+ double f0 = n > 2 && scope[2] > 0 ? scope[2] : 261.63;
+ string pre = bank == 0 ? "r1" : "r2";
+ int audible = PhysicalModel.AudiblePartials(mine, f0, sr);
+ partials.Set($"PARTIALS · {TypeWord(pre).ToUpperInvariant()}", mine, r2 ? other : Array.Empty<(double, double, double)>(),
+ sr * 0.49 / f0, $"{audible} partials · inharm {NotaNum.Pct(G(pre + "inharm"))}", bank == 1 && !r2);
+ }
void Refresh()
{
- string pre = rsel == 0 ? "r1" : "r2";
- int rtype = Math.Clamp((int)Math.Round(G(pre + "type") * 5), 0, 5);
- viz.Set(rtype, G(pre + "decay"), G(pre + "material"), G(pre + "bright"), G(pre + "inharm"), G(pre + "ratio"), G(pre + "hit"));
noiseEnv.Refresh();
- foreach (var a in readouts) a();
+ foreach (var r in readouts) r();
+ RefreshPartials();
+ hint.Text = Hint();
+ status.Text = Summary();
}
- // ---- shared builders (mirror the Volt card's vocabulary) --------------
- Control K(string id, string name, bool mod = false) => InstrumentControls.InstKnob(ctx, idx, id, name, Refresh, 40, 52, mod ? Teal : null);
- Control KnobGrid(int cols, params Control[] ks)
+ // ---- shared builders --------------------------------------------------
+ Control PKnob(string id, string label, Func<float, string> fmt, double size = KnobS, double cellW = 48,
+ IBrush? arc = null, Func<bool>? dim = null)
{
- var col = new StackPanel { Spacing = 2, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };
- for (int i = 0; i < ks.Length; i += cols)
+ if (!idx.TryGetValue(id, out var pi)) return new Panel();
+ var value = new TextBlock
{
- var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 2, HorizontalAlignment = HorizontalAlignment.Center };
- for (int j = i; j < Math.Min(i + cols, ks.Length); j++) row.Children.Add(ks[j]);
- col.Children.Add(row);
- }
- return col;
+ Text = fmt(G(id)), FontSize = NotaType.KnobValue, FontFamily = NotaFonts.MonoFamily,
+ Foreground = TextPrimary, HorizontalAlignment = HorizontalAlignment.Center,
+ TextAlignment = TextAlignment.Center, LineHeight = 10,
+ };
+ var knob = new Knob(G(id), 1.0)
+ {
+ Accent = true, ArcColor = arc, Default = engine.InstrumentParamDefault(track, pi),
+ Width = size, Height = size, HorizontalAlignment = HorizontalAlignment.Center,
+ };
+ knob.ValueChanged += v => { engine.PluginParamSet(track, -1, pi, (float)v); value.Text = fmt((float)v); Refresh(); };
+ knob.GestureBegin += () => Begin(id);
+ knob.GestureEnd += () => End(id);
+ ctx.AddInstFader(pi, knob, value, fmt);
+ MidiLearn.Bind(knob, MidiTarget.PluginParam(track, -1, pi), engine.PluginParamName(track, -1, pi));
+ if (dim is not null) readouts.Add(() => knob.IsDim = dim());
+ var cell = KnobCell(label, knob, value, cellW);
+ cell.HorizontalAlignment = HorizontalAlignment.Center;
+ cell.VerticalAlignment = VerticalAlignment.Center;
+ return cell;
}
- Control Arrow() => new Glyph(GlyphKind.ChevronRight, 9) { Foreground = NotaPalette.BorderStrong, Margin = new Thickness(1, 0) };
- Control Cap(string t, IBrush? c = null) => new TextBlock { Text = t, FontSize = 9, Foreground = c ?? TextTertiary, VerticalAlignment = VerticalAlignment.Center };
- Control Head(string title, params Control[] extras)
+
+ Border Chips(string id, string[] names, Func<int>? current = null, Action<int>? pick = null,
+ Func<bool>? dim = null, double padX = 5)
{
- var sp = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center };
- sp.Children.Add(new TextBlock { Text = title, FontSize = 9, FontWeight = FontWeight.Bold, Foreground = TextPrimary, VerticalAlignment = VerticalAlignment.Center });
- foreach (var e in extras) sp.Children.Add(e);
- return sp;
+ int n = names.Length;
+ var seg = Segments(names, current ?? (() => Sel(id, n)),
+ pick ?? (iv => { Write(id, iv / (float)(n - 1)); Refresh(); }), out var sync, dim: dim, padX: padX);
+ readouts.Add(sync);
+ if (I(id) is var pi and >= 0) MidiLearn.Bind(seg, MidiTarget.PluginParam(track, -1, pi), engine.PluginParamName(track, -1, pi));
+ return seg;
}
- Border Panel(double width, Control header, Control body)
- => new Border { Width = width, Background = Card2, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Panel, Padding = new Thickness(9, 8),
- Child = new StackPanel { Spacing = 8, VerticalAlignment = VerticalAlignment.Center, Children = { header, body } } };
- // A panel whose body fills the remaining height (for graphs / viz).
- Border GraphPanel(double width, Control header, Control body)
+
+ Grid Slider(string label, string id, Func<string> text, bool bipolar = false, Func<bool>? dim = null)
{
- DockPanel.SetDock(header, Dock.Top);
- header.Margin = new Thickness(0, 0, 0, 8);
- return new Border { Width = width, Background = Card2, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Panel, Padding = new Thickness(9, 8),
- Child = new DockPanel { LastChildFill = true, Children = { header, body } } };
+ int pi = I(id);
+ var row = SliderRow(label, () => G(id), v => { SetP(id, (float)v); Refresh(); }, text, out var sync,
+ begin: pi >= 0 ? () => Begin(id) : null,
+ end: pi >= 0 ? () => End(id) : null,
+ reset: pi >= 0 ? () => { SetP(id, engine.InstrumentParamDefault(track, pi)); Refresh(); } : null,
+ bipolar: bipolar, dim: dim, labelWidth: 46, valueWidth: 30);
+ readouts.Add(sync);
+ if (pi >= 0) MidiLearn.Bind(row, MidiTarget.PluginParam(track, -1, pi), engine.PluginParamName(track, -1, pi));
+ return row;
}
- // Text chips writing a normalized selector param.
- Control TextChips(string id, string[] names)
+ // Knobs packed into a grid of equal cells, rows spread over the height.
+ static Grid KnobGrid(int cols, params Control[] ks)
{
- int n = names.Length; var arr = new Border[n];
- void Hi() { int cur = Math.Clamp((int)Math.Round(G(id) * (n - 1)), 0, n - 1); for (int i = 0; i < n; i++) { bool on = i == cur; arr[i].Background = on ? NotaPalette.Accent : Brushes.Transparent; ((TextBlock)arr[i].Child!).Foreground = on ? NotaPalette.TextOnAccent : TextSecondary; } }
- var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 2 };
- for (int i = 0; i < n; i++)
+ int rows = (ks.Length + cols - 1) / cols;
+ var g = new Grid { VerticalAlignment = VerticalAlignment.Stretch };
+ for (int c = 0; c < cols; c++) g.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
+ for (int r = 0; r < rows; r++) g.RowDefinitions.Add(new RowDefinition(1, GridUnitType.Star));
+ for (int i = 0; i < ks.Length; i++) { Grid.SetColumn(ks[i], i % cols); Grid.SetRow(ks[i], i / cols); g.Children.Add(ks[i]); }
+ return g;
+ }
+
+ // ---- Exciter tab ------------------------------------------------------
+ var malletGrid = new Grid { RowDefinitions = new RowDefinitions("Auto,*"), RowSpacing = 3 };
+ {
+ var knobs = KnobGrid(2,
+ PKnob("malletvol", "VOLUME", Pct),
+ PKnob("malletstiff", "STIFF", Pct),
+ PKnob("malletnoise", "NOISE", Pct),
+ PKnob("malletcolor", "COLOR", Pct));
+ ToolTip.SetTip(knobs, "Stiffness sets the contact time: soft = long and dark, hard = short and bright");
+ malletGrid.Children.Add(Cap("MALLET"));
+ Grid.SetRow(knobs, 1); malletGrid.Children.Add(knobs);
+ }
+
+ var noiseGrid = new Grid { RowDefinitions = new RowDefinitions("Auto,*"), RowSpacing = 3 };
+ {
+ var envCap = Mono("", Teal, NotaType.Axis);
+ envCap.HorizontalAlignment = HorizontalAlignment.Right;
+ readouts.Add(() =>
+ {
+ double oct = PhysicalModel.NoiseEnvOct(G("noiseenv"));
+ envCap.Text = Math.Abs(oct) < 0.05 ? "env → freq off" : "env → freq " + NotaNum.Unit(oct, "+0.0;−0.0;0", "oct");
+ });
+ var head = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*"), ColumnSpacing = 5 };
+ var typeChips = Chips("noisetype", PhysicalModel.NoiseTypes);
+ head.Children.Add(Cap("NOISE"));
+ Grid.SetColumn(typeChips, 1); head.Children.Add(typeChips);
+ Grid.SetColumn(envCap, 2); head.Children.Add(envCap);
+
+ // The ADSR editor with its stage times along the bottom edge.
+ var envTimes = Mono("", NotaPalette.TextAxis, NotaType.Axis);
+ envTimes.HorizontalAlignment = HorizontalAlignment.Right; envTimes.VerticalAlignment = VerticalAlignment.Bottom;
+ envTimes.Margin = new Thickness(0, 0, 6, 1); envTimes.IsHitTestVisible = false;
+ readouts.Add(() => envTimes.Text =
+ $"{Secs(PhysicalModel.NoiseAttack(G("noisea")))} · {Secs(PhysicalModel.NoiseDecay(G("noised")))} · "
+ + $"{Pct(G("noises"))} · {Secs(PhysicalModel.NoiseRelease(G("noiser")))}");
+ var envHost = new Panel { Children = { noiseEnv, envTimes } };
+
+ var knobs = KnobGrid(2,
+ PKnob("noisevol", "VOLUME", Pct, cellW: 46),
+ PKnob("noiseenv", "ENV", Bip, cellW: 46, arc: Teal),
+ PKnob("noisefreq", "FREQ", v => NotaNum.Hz(PhysicalModel.NoiseFreqHz(v)), cellW: 46),
+ PKnob("noisereso", "RESO", Pct, cellW: 46));
+ knobs.Width = 96;
+ var noiseBody = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 5 };
+ noiseBody.Children.Add(envHost);
+ Grid.SetColumn(knobs, 1); noiseBody.Children.Add(knobs);
+
+ noiseGrid.Children.Add(head);
+ Grid.SetRow(noiseBody, 1); noiseGrid.Children.Add(noiseBody);
+ }
+
+ var exciterGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("104,10,*"), ColumnSpacing = 5 };
+ exciterGrid.Children.Add(malletGrid);
+ var arrow = new Glyph(GlyphKind.ChevronRight, 9) { Foreground = NotaPalette.BorderStrong, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };
+ Grid.SetColumn(arrow, 1); exciterGrid.Children.Add(arrow);
+ Grid.SetColumn(noiseGrid, 2); exciterGrid.Children.Add(noiseGrid);
+ var exciterBody = new Border { Padding = new Thickness(6, 5), Child = exciterGrid };
+
+ // ---- Resonator tab ----------------------------------------------------
+ // Both banks' controls are built once; the 1 / 2 segment shows one set.
+ Control MixCell(Func<bool> dim)
+ {
+ int pi = I("resmix");
+ var trackC = new SliderTrack
{
- int iv = i;
- var chip = new Border { CornerRadius = NotaRadius.Badge, Padding = new Thickness(7, 1), Cursor = new Cursor(StandardCursorType.Hand), Child = new TextBlock { Text = names[i], FontSize = 9, Foreground = TextSecondary } };
- chip.PointerPressed += (_, _) => { if (I(id) is var ci and >= 0 && n > 1) { engine.PluginParamSet(track, -1, ci, iv / (float)(n - 1)); Hi(); Refresh(); } };
- arr[i] = chip; row.Children.Add(chip);
+ Width = 44, HorizontalAlignment = HorizontalAlignment.Center,
+ Reset = pi >= 0 ? () => { Write("resmix", engine.InstrumentParamDefault(track, pi)); Refresh(); } : null,
+ };
+ var val = Mono("", TextPrimary, NotaType.KnobValue);
+ val.HorizontalAlignment = HorizontalAlignment.Center;
+ var cap = Cap("MIX 1+2"); cap.HorizontalAlignment = HorizontalAlignment.Center;
+ trackC.Changed += v => { SetP("resmix", (float)v); Refresh(); };
+ trackC.GestureBegin += () => Begin("resmix");
+ trackC.GestureEnd += () => End("resmix");
+ readouts.Add(() =>
+ {
+ bool d = dim();
+ if (!trackC.Dragging) trackC.Norm = G("resmix");
+ trackC.IsDim = d;
+ var (g1, g2) = PhysicalModel.MixGains(G("resmix"));
+ val.Text = $"{NotaNum.Str(g1 * 100, "0")} / {NotaNum.Str(g2 * 100, "0")}";
+ val.Foreground = d ? TextDisabled : TextPrimary;
+ cap.Foreground = d ? TextDisabled : TextTertiary;
+ });
+ var cell = new StackPanel { Spacing = 3, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center, Children = { cap, trackC, val } };
+ ToolTip.SetTip(cell, "Res 1 against Res 2 — both at full level in the middle; in 1→2, res 1's own sound against the body it rings");
+ if (pi >= 0) MidiLearn.Bind(cell, MidiTarget.PluginParam(track, -1, pi), "Res Mix");
+ return cell;
+ }
+
+ var typeHosts = new Control[2];
+ var knobHosts = new Control[2];
+ for (int b = 0; b < 2; b++)
+ {
+ string pre = b == 0 ? "r1" : "r2";
+ Func<bool>? off = b == 1 ? () => !R2On() : null;
+ typeHosts[b] = Chips(pre + "type", TypeNames, dim: off, padX: 4);
+ knobHosts[b] = KnobGrid(4,
+ PKnob(pre + "decay", "DECAY", v => Secs(PhysicalModel.DecaySeconds(v)), dim: off),
+ PKnob(pre + "material", "MATERIAL", Pct, dim: off),
+ PKnob(pre + "bright", "BRIGHT", Pct, dim: off),
+ PKnob(pre + "inharm", "INHARM", Pct, dim: off),
+ PKnob(pre + "ratio", "RATIO", v => NotaNum.Str(PhysicalModel.RatioExponent(v), "0.00"), dim: off),
+ PKnob(pre + "hit", "HIT", Pct, dim: off),
+ PKnob(pre + "tune", "TUNE", v => Semis(PhysicalModel.BankSemis(v), "+0.0;−0.0;0"), dim: off),
+ MixCell(() => !R2On()));
+ }
+
+ partials.StartH = () => G(bank == 0 ? "r1ratio" : "r2ratio");
+ partials.StartV = () => G(bank == 0 ? "r1bright" : "r2bright");
+ partials.GestureBegin += () => { string pre = bank == 0 ? "r1" : "r2"; Begin(pre + "ratio"); Begin(pre + "bright"); };
+ partials.GestureEnd += () => { string pre = bank == 0 ? "r1" : "r2"; End(pre + "ratio"); End(pre + "bright"); };
+ partials.DragH += v => { SetP(bank == 0 ? "r1ratio" : "r2ratio", (float)v); Refresh(); };
+ partials.DragV += v => { SetP(bank == 0 ? "r1bright" : "r2bright", (float)v); Refresh(); };
+
+ var bankSeg = Segments(new[] { "1", "2" }, () => bank, iv => { bank = iv; showTab(); }, out var bankSync, padX: 5);
+ readouts.Add(bankSync);
+ ToolTip.SetTip(bankSeg, "Which resonator the controls below edit");
+ // On / Off belongs to the bank on screen: bank 1 always rings, bank 2 is switchable.
+ var onSeg = Chips("r2on", new[] { "Off", "On" }, () => bank == 0 || R2On() ? 1 : 0,
+ iv => { if (bank == 1) { Write("r2on", iv); Refresh(); } }, dim: () => bank == 0);
+ ToolTip.SetTip(onSeg, "Resonator 2 on / off — resonator 1 always rings");
+ var structSeg = Chips("structure", new[] { "1→2", "1+2" }, dim: () => !R2On(), padX: 4);
+ ToolTip.SetTip(structSeg, "1→2: resonator 1 rings into resonator 2 · 1+2: both struck, mixed");
+ var typeHost = new Panel { Children = { typeHosts[0], typeHosts[1] } };
+
+ var resHead = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,Auto,*,Auto,Auto"), ColumnSpacing = 5, Margin = new Thickness(6, 0) };
+ {
+ var structCap = Cap("STRUCT"); structCap.HorizontalAlignment = HorizontalAlignment.Right;
+ var cs = new Control[] { bankSeg, onSeg, typeHost, new Panel(), structCap, structSeg };
+ for (int i = 0; i < cs.Length; i++) { Grid.SetColumn(cs[i], i); resHead.Children.Add(cs[i]); }
+ }
+ var resHeadHost = new Border { Height = TabH, BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 0, 0, 1), Child = resHead };
+
+ var knobHost = new Panel { Children = { knobHosts[0], knobHosts[1] } };
+ var resBody = new Grid { ColumnDefinitions = new ColumnDefinitions("150,*"), ColumnSpacing = 6, Margin = new Thickness(6, 5) };
+ resBody.Children.Add(partials);
+ Grid.SetColumn(knobHost, 1); resBody.Children.Add(knobHost);
+
+ var resonatorGrid = new Grid { RowDefinitions = new RowDefinitions("Auto,*") };
+ resonatorGrid.Children.Add(resHeadHost);
+ Grid.SetRow(resBody, 1); resonatorGrid.Children.Add(resBody);
+
+ // ---- the tab strip ----------------------------------------------------
+ var bodies = new Control[] { exciterBody, resonatorGrid };
+ var tabCells = new Border[TabNames.Length];
+ var tabTexts = new TextBlock[TabNames.Length];
+ var tabRow = new StackPanel { Orientation = Orientation.Horizontal };
+ for (int i = 0; i < TabNames.Length; i++)
+ {
+ int iv = i;
+ var tb = new TextBlock { Text = TabNames[i], FontSize = NotaType.DeviceSection, VerticalAlignment = VerticalAlignment.Center };
+ var cell = new Border
+ {
+ Padding = new Thickness(8, 0), BorderThickness = new Thickness(0, 0, 0, 2),
+ Cursor = new Cursor(StandardCursorType.Hand), Child = tb,
+ };
+ cell.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(cell).Properties.IsLeftButtonPressed) return;
+ tab = iv; showTab(); e.Handled = true;
+ };
+ tabCells[i] = cell; tabTexts[i] = tb; tabRow.Children.Add(cell);
+ }
+ var tabStrip = new Grid { Height = TabH, ColumnDefinitions = new ColumnDefinitions("Auto,*") };
+ tabStrip.Children.Add(tabRow);
+ Grid.SetColumn(hint, 1); tabStrip.Children.Add(hint);
+
+ showTab = () =>
+ {
+ for (int i = 0; i < TabNames.Length; i++)
+ {
+ bool on = i == tab;
+ tabCells[i].Background = on ? NotaPalette.SurfaceRaised : Brushes.Transparent;
+ tabCells[i].BorderBrush = on ? Brass : Brushes.Transparent;
+ tabTexts[i].Foreground = on ? AccentBright : TextTertiary;
+ tabTexts[i].FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;
+ bodies[i].IsVisible = on;
}
- var container = new Border { Background = Sunken, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile, Padding = new Thickness(2), Child = row };
- Hi(); readouts.Add(Hi);
- if (I(id) is var pi and >= 0) MidiLearn.Bind(container, MidiTarget.PluginParam(track, -1, pi), id);
- return container;
- }
-
- // Local (non-param) segmented toggle.
- Control Seg(string[] names, int initial, Action<int> onPick, double fs = 10)
- {
- int cur = initial;
- return DeviceCardKit.Segments(names, () => cur, iv => { cur = iv; onPick(iv); }, out _);
- }
-
- // ===== EXCITER tab: Mallet → Noise ==================================
- var malletBox = Panel(132, Head("MALLET"),
- KnobGrid(2, K("malletvol", "VOLUME"), K("malletstiff", "STIFF"), K("malletnoise", "NOISE"), K("malletcolor", "COLOR")));
-
- noiseEnv.VerticalAlignment = VerticalAlignment.Stretch; noiseEnv.MinHeight = 96;
- var noiseCap = new TextBlock { FontSize = 9, Foreground = Teal, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Right };
- noiseCap.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");
- readouts.Add(() => { int en = (int)Math.Round((G("noiseenv") - 0.5) * 200); noiseCap.Text = "env " + en.ToString("+0;−0;0"); });
- var noiseHeadLeft = Head("NOISE", TextChips("noisetype", new[] { "LP", "BP", "HP" }));
- DockPanel.SetDock(noiseCap, Dock.Right);
- var noiseHeader = new DockPanel { Children = { noiseCap, noiseHeadLeft } };
- var noiseBody = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 8, VerticalAlignment = VerticalAlignment.Stretch };
- noiseBody.Children.Add(noiseEnv);
- var noiseKnobs = KnobGrid(2, K("noisevol", "VOLUME"), K("noiseenv", "ENV", true), K("noisefreq", "FREQ"), K("noisereso", "RESO"));
- Grid.SetColumn(noiseKnobs, 1); noiseBody.Children.Add(noiseKnobs);
- var noiseBox = GraphPanel(356, noiseHeader, noiseBody);
-
- var exciterTab = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Stretch, HorizontalAlignment = HorizontalAlignment.Left,
- Children = { malletBox, Arrow(), noiseBox } };
-
- // ===== RESONATOR tab: Res 1 / Res 2 + spectrum + OUTPUT =============
- var typeHost = new ContentControl { VerticalAlignment = VerticalAlignment.Center };
- var knobHost = new ContentControl { VerticalAlignment = VerticalAlignment.Center };
- void ApplyResSel()
- {
- string pre = rsel == 0 ? "r1" : "r2";
- typeHost.Content = TextChips(pre + "type", new[] { "Beam", "Marimba", "String", "Membrane", "Plate", "Pipe" });
- knobHost.Content = KnobGrid(4,
- K(pre + "decay", "DECAY"), K(pre + "material", "MATERIAL"), K(pre + "bright", "BRIGHT"), K(pre + "inharm", "INHARM"),
- K(pre + "ratio", "RATIO"), K(pre + "hit", "HIT"), K(pre + "tune", "TUNE"));
+ for (int b = 0; b < 2; b++) { typeHosts[b].IsVisible = b == bank; knobHosts[b].IsVisible = b == bank; }
Refresh();
+ };
+
+ var tabHost = new Panel();
+ foreach (var b in bodies) tabHost.Children.Add(b);
+ var tabGrid = new Grid { RowDefinitions = new RowDefinitions("Auto,*") };
+ tabGrid.Children.Add(HeaderStrip(tabStrip));
+ Grid.SetRow(tabHost, 1); tabGrid.Children.Add(tabHost);
+ var tabPanel = SectionBox(tabGrid);
+
+ // ---- rail · Output ----------------------------------------------------
+ var monoChips = Chips("mono", new[] { "Poly", "Mono" }, () => IsMono() ? 1 : 0, iv => { Write("mono", iv); Refresh(); });
+ monoChips.HorizontalAlignment = HorizontalAlignment.Right;
+ monoChips.Margin = new Thickness(0, 0, 6, 0);
+ ToolTip.SetTip(monoChips, "Poly: 8 voices ring over each other · Mono: a new strike chokes the sounding note");
+ var outCap = Cap("OUTPUT"); outCap.Margin = new Thickness(8, 0, 0, 0);
+ var outHead = new Grid { Height = TabH, ColumnDefinitions = new ColumnDefinitions("Auto,*") };
+ outHead.Children.Add(outCap);
+ Grid.SetColumn(monoChips, 1); outHead.Children.Add(monoChips);
+
+ var noteOffRow = Slider("NOTE OFF", "noteoff", () => Pct(G("noteoff")));
+ ToolTip.SetTip(noteOffRow, "How hard a released key damps the body — at 0 it rings on, fully up it stops at once");
+ var outTop = new StackPanel
+ {
+ Spacing = 6, Margin = new Thickness(8, 6, 8, 0),
+ Children =
+ {
+ Slider("TUNE", "tune", () => Semis(Math.Round(PhysicalModel.TuneSemis(G("tune")))), bipolar: true),
+ Slider("FINE", "fine", () => NotaNum.Unit(Math.Round(PhysicalModel.FineCents(G("fine"))), "+0;−0;0", "c"), bipolar: true),
+ noteOffRow,
+ },
+ };
+
+ var meter = new MeterBar { VerticalAlignment = VerticalAlignment.Stretch, Width = MeterScale.StereoWidth };
+ ctx.AddDeviceRefresher(() => { if (engine.TryGetTrackMeter(track, out var m)) meter.Push(m); });
+ var meterScale = new Grid { VerticalAlignment = VerticalAlignment.Stretch, RowDefinitions = new RowDefinitions(string.Join(",", ScaleRows(0, -12, -48))) };
+ for (int i = 0; i < 3; i++)
+ {
+ var c = Mono(i == 0 ? "0" : i == 1 ? "−12" : "−48", NotaPalette.TextAxis, NotaType.Axis);
+ Grid.SetRow(c, i * 2 + 1); meterScale.Children.Add(c);
+ }
+ var meterBlock = new Grid
+ {
+ ColumnDefinitions = new ColumnDefinitions("Auto,Auto"), ColumnSpacing = 4,
+ HorizontalAlignment = HorizontalAlignment.Right, Margin = new Thickness(0, 0, 0, 9),
+ };
+ meterBlock.Children.Add(meter);
+ Grid.SetColumn(meterScale, 1); meterBlock.Children.Add(meterScale);
+
+ var outBottom = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*"), VerticalAlignment = VerticalAlignment.Stretch };
+ var volCell = PKnob("volume", "VOLUME", Pct, NotaSize.KnobMain, 48);
+ var panCell = PKnob("pan", "PAN", PanText, NotaSize.KnobSecondary, 42);
+ outBottom.Children.Add(volCell);
+ Grid.SetColumn(panCell, 1); outBottom.Children.Add(panCell);
+ Grid.SetColumn(meterBlock, 2); outBottom.Children.Add(meterBlock);
+
+ var outGrid = new Grid { RowDefinitions = new RowDefinitions("Auto,*") };
+ outGrid.Children.Add(outTop);
+ var outBottomFrame = new Border
+ {
+ BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 1, 0, 0),
+ Margin = new Thickness(8, 6, 8, 5), Padding = new Thickness(0, 5, 0, 0), Child = outBottom,
+ };
+ Grid.SetRow(outBottomFrame, 1); outGrid.Children.Add(outBottomFrame);
+
+ var railGrid = new Grid { RowDefinitions = new RowDefinitions("Auto,*") };
+ railGrid.Children.Add(HeaderStrip(outHead));
+ Grid.SetRow(outGrid, 1); railGrid.Children.Add(outGrid);
+ var rail = SectionBox(railGrid);
+ rail.Width = RailW;
+
+ // ---- status strip -----------------------------------------------------
+ string Exciters()
+ {
+ var parts = new List<string>();
+ if (G("malletvol") > 0.001f) parts.Add($"mallet {Pct(G("malletvol"))}");
+ if (G("noisevol") > 0.001f) parts.Add($"noise {Pct(G("noisevol"))}");
+ return parts.Count == 0 ? "no exciter" : string.Join(" → ", parts);
+ }
+ string StructWord() => !R2On() ? "res 1 only" : Serial() ? "1→2" : "1+2";
+ string BankOf() => bank == 0 ? "r1" : "r2";
+
+ // The line at the right of the tab strip: what this tab holds, in a few words.
+ string Hint() => tab switch
+ {
+ 0 => $"{Exciters()} → {TypeWord("r1")}",
+ _ => $"{StructWord()} · {TypeWord(BankOf())} · decay {Secs(PhysicalModel.DecaySeconds(G(BankOf() + "decay")))}",
+ };
+ string Summary()
+ {
+ if (tab == 0)
+ {
+ var s = G("malletvol") > 0.001f
+ ? $"Mallet {Pct(G("malletvol"))} · stiff {Pct(G("malletstiff"))} ({NotaNum.Unit(PhysicalModel.ContactMs(G("malletstiff")), "0.0", "ms")})"
+ : "Mallet off";
+ s += G("noisevol") > 0.001f
+ ? $" · noise {Pct(G("noisevol"))} {PhysicalModel.NoiseTypes[Sel("noisetype", 3)]} {NotaNum.Hz(PhysicalModel.NoiseFreqHz(G("noisefreq")))} · env → freq {NotaNum.Unit(PhysicalModel.NoiseEnvOct(G("noiseenv")), "+0.0;−0.0;0", "oct")}"
+ : " · noise off";
+ return s + $" → resonator {TypeWord("r1")}";
+ }
+ string pre = BankOf();
+ bool on = bank == 0 || R2On();
+ var line = $"Resonator {bank + 1} {TypeWord(pre)} {(on ? "on" : "off")} · decay {Secs(PhysicalModel.DecaySeconds(G(pre + "decay")))} · "
+ + $"bright {Pct(G(pre + "bright"))} · inharm {Pct(G(pre + "inharm"))} · structure {StructWord()}";
+ if (R2On())
+ {
+ var (g1, g2) = PhysicalModel.MixGains(G("resmix"));
+ line += $" · mix {NotaNum.Str(g1 * 100, "0")} / {NotaNum.Str(g2 * 100, "0")}";
+ }
+ return line;
}
- viz.VerticalAlignment = VerticalAlignment.Stretch; viz.MinHeight = 96; viz.Width = 190;
- var resTypeRow = new DockPanel { Margin = new Thickness(0, 0, 0, 6) };
- DockPanel.SetDock(typeHost, Dock.Left);
- resTypeRow.Children.Add(typeHost);
- var resInner = new DockPanel { LastChildFill = true };
- DockPanel.SetDock(resTypeRow, Dock.Top);
- var resGraphRow = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), ColumnSpacing = 10, VerticalAlignment = VerticalAlignment.Stretch };
- resGraphRow.Children.Add(viz);
- Grid.SetColumn(knobHost, 1); resGraphRow.Children.Add(knobHost);
- resInner.Children.Add(resTypeRow);
- resInner.Children.Add(resGraphRow);
-
- var onChips = TextChips("r2on", new[] { "Off", "On" });
- var resHeadLeft = Head("RESONATOR", Seg(new[] { "1", "2" }, 0, i => { rsel = i; ApplyResSel(); }), onChips);
- var structChips = TextChips("structure", new[] { "1→2", "1+2" });
- var structWrap = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Right,
- Children = { Cap("STRUCTURE"), structChips } };
- DockPanel.SetDock(structWrap, Dock.Right);
- var resHeader = new DockPanel { Children = { structWrap, resHeadLeft } };
- var resBox = GraphPanel(500, resHeader, resInner);
-
- var resonatorTab = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Stretch, HorizontalAlignment = HorizontalAlignment.Left,
- Children = { resBox } };
-
- // Global OUTPUT panel — always visible on the right, both tabs.
- var outputBox = Panel(178, Head("OUTPUT"),
- KnobGrid(2, K("tune", "TUNE"), K("fine", "FINE"), K("noteoff", "NOTE OFF"), K("pan", "PAN"), K("volume", "VOLUME")));
-
- // ===== tabs + body (shared shell provides the header + frame) ======
- var tabHost = new ContentControl { VerticalAlignment = VerticalAlignment.Stretch, Content = exciterTab };
- var tabs = Seg(new[] { "Exciter", "Resonator" }, 0, i => tabHost.Content = i == 0 ? exciterTab : resonatorTab, 11);
- var tabStrip = new Border { Height = 26, Background = Card2, BorderBrush = BorderDef, BorderThickness = new Thickness(0, 0, 0, 1), Padding = new Thickness(10, 0),
- Child = new StackPanel { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Center, Children = { tabs } } };
- DockPanel.SetDock(tabStrip, Dock.Top);
- DockPanel.SetDock(outputBox, Dock.Right);
- outputBox.Margin = new Thickness(6, 0, 0, 0);
- var contentBody = new DockPanel { LastChildFill = true, Children = { outputBox, tabHost } };
- var contentHost = new Border { Padding = new Thickness(10, 8), Child = contentBody };
- var dockRoot = new DockPanel { LastChildFill = true, Background = Raised, Children = { tabStrip, contentHost } };
+ ctx.AddDeviceRefresher(() =>
+ {
+ int v = Math.Max(0, engine.InstrumentVoiceCount(track));
+ string mode = IsMono() ? "MONO" : $"POLY {v}/{PhysicalModel.Voices}";
+ double sr = engine.SampleRate > 0 ? engine.SampleRate : 48000;
+ meta.Text = $"{mode} · NOTE OFF {Secs(PhysicalModel.NoteOffSeconds(G("noteoff")))} · {NotaNum.Unit(sr / 1000, "0.#", "kHz")}";
+ RefreshPartials(); // follows the struck note (the partials' reach under Nyquist)
+ });
+ var statusBar = new Grid { Height = StatusH, ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 10 };
+ statusBar.Children.Add(status);
+ Grid.SetColumn(meta, 1); statusBar.Children.Add(meta);
+ var statusHost = new Border
+ {
+ Height = StatusH, BorderBrush = BorderDef, BorderThickness = new Thickness(0, 1, 0, 0),
+ Background = NotaPalette.SurfaceAbyss, Padding = new Thickness(8, 0), Child = statusBar,
+ };
+
+ // ---- assembly ---------------------------------------------------------
+ var body = new Grid
+ {
+ ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = NotaSpace.DeviceGap,
+ Margin = new Thickness(NotaSpace.DeviceGap),
+ };
+ body.Children.Add(tabPanel);
+ Grid.SetColumn(rail, 1); body.Children.Add(rail);
+
+ DockPanel.SetDock(statusHost, Dock.Bottom);
+ var root = new DockPanel { LastChildFill = true, Background = NotaPalette.Gutter, Children = { statusHost, body } };
ctx.SetInstLiveViz(Refresh);
- ApplyResSel();
- Refresh();
- return dockRoot;
+ showTab();
+ return root;
+ }
+
+ // A device section: card ground, hairline, radius 6 — the almanac's section box.
+ private static Border SectionBox(Control child) => new()
+ {
+ Background = NotaPalette.SurfaceCard, BorderBrush = BorderDef, BorderThickness = new Thickness(1),
+ CornerRadius = NotaRadius.Tile, ClipToBounds = true, Child = child,
+ };
+
+ // A section's own header strip: a hairline under it, nothing else.
+ private static Border HeaderStrip(Control child) => new()
+ {
+ BorderBrush = BorderDef, BorderThickness = new Thickness(0, 0, 0, 1), Child = child,
+ };
+
+ /// <summary>Row definitions that put a caption for each dB mark at its place on the
+ /// meter's scale: a star gap, the caption (Auto), … and a star gap for the remainder.</summary>
+ private static IEnumerable<string> ScaleRows(params double[] dbs)
+ {
+ double prev = 0;
+ foreach (var db in dbs)
+ {
+ double fromTop = 1.0 - MeterScale.NormDb(db);
+ yield return Math.Max(0, fromTop - prev).ToString("0.000", NotaNum.Culture) + "*";
+ yield return "Auto";
+ prev = fromTop;
+ }
+ yield return Math.Max(0, 1.0 - prev).ToString("0.000", NotaNum.Culture) + "*";
}
}
diff --git a/src/managed/Nota.Application/Instruments/PhysicalModel.cs b/src/managed/Nota.Application/Instruments/PhysicalModel.cs
new file mode 100644
index 00000000..581f0fb9
--- /dev/null
+++ b/src/managed/Nota.Application/Instruments/PhysicalModel.cs
@@ -0,0 +1,122 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Physical (built-in instrument kind 2) — the engine's own value maps, in one place
+// for the editor card and the MCP server: what a normalized 0..1 parameter means in
+// seconds / semitones / cents, how the engine's scope telemetry is laid out, a one-line
+// summary of the patch and a guide to every parameter. Mirrors PhysicalSynth.h.
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Text;
+
+namespace Nota.Application;
+
+public static class PhysicalModel
+{
+ public const int Kind = 2;
+ public const int Voices = 8;
+ public const int Modes = 16;
+
+ // scopeRead layout: 4 head floats, then per bank 3 rows of Modes (ratio, amp, ring s).
+ public const int ScopeHead = 4;
+ public const int ScopeLength = ScopeHead + 2 * 3 * Modes;
+
+ public static readonly string[] TypeNames = { "Beam", "Marimba", "String", "Membrane", "Plate", "Pipe" };
+ public static readonly string[] NoiseTypes = { "LP", "BP", "HP" };
+
+ public static double ExpMap(double v, double lo, double hi) => lo * Math.Pow(hi / lo, Math.Clamp(v, 0.0, 1.0));
+
+ public static int TypeIndex(float v) => Math.Clamp((int)Math.Round(v * 5), 0, 5);
+ public static int NoiseTypeIndex(float v) => Math.Clamp((int)Math.Round(v * 2), 0, 2);
+
+ /// <summary>Resonator Decay → the fundamental's ring time (s, e-folding).</summary>
+ public static double DecaySeconds(float v) => ExpMap(v, 0.04, 18.0);
+ /// <summary>Resonator Tune → semitones (±24).</summary>
+ public static double BankSemis(float v) => (v - 0.5) * 48.0;
+ /// <summary>Resonator Ratio → the partial-spacing exponent (0.5 squeezed … 1 natural … 1.5 spread).</summary>
+ public static double RatioExponent(float v) => 0.5 + v;
+ /// <summary>Global Tune → semitones (±24).</summary>
+ public static double TuneSemis(float v) => (v - 0.5) * 48.0;
+ /// <summary>Global Fine → cents (±100).</summary>
+ public static double FineCents(float v) => (v - 0.5) * 200.0;
+ /// <summary>Note Off → how long a released note takes to die (s): 0 = rings on, 1 = damped at once.</summary>
+ public static double NoteOffSeconds(float v) => ExpMap(1.0 - v, 0.006, 4.0);
+ /// <summary>Mallet Stiffness → contact time (ms): soft = long and dark, hard = short and bright.</summary>
+ public static double ContactMs(float v) => ExpMap(1.0 - v, 0.0004, 0.010) * 1000.0;
+ public static double NoiseFreqHz(float v) => ExpMap(v, 60.0, 12000.0);
+ public static double NoiseAttack(float v) => ExpMap(v, 0.001, 2.0);
+ public static double NoiseDecay(float v) => ExpMap(v, 0.002, 4.0);
+ public static double NoiseRelease(float v) => ExpMap(v, 0.002, 5.0);
+ /// <summary>Noise Env → how far the envelope sweeps the noise filter (±3 octaves).</summary>
+ public static double NoiseEnvOct(float v) => (v - 0.5) * 6.0;
+ /// <summary>Res Mix → (Res 1 gain, Res 2 gain): equal-gain, both 1 in the middle.</summary>
+ public static (double G1, double G2) MixGains(float v) => (Math.Min(1.0, 2.0 * (1.0 - v)), Math.Min(1.0, 2.0 * v));
+
+ /// <summary>One bank's modes from the engine scope: frequency ratio (bank Tune included),
+ /// struck amplitude and ring time in seconds. Empty when the scope is too short.</summary>
+ public static (double Ratio, double Amp, double Tau)[] Bank(ReadOnlySpan<float> scope, int bank)
+ {
+ int at = ScopeHead + bank * 3 * Modes;
+ if (scope.Length < at + 3 * Modes) return Array.Empty<(double, double, double)>();
+ var r = new (double, double, double)[Modes];
+ for (int m = 0; m < Modes; m++) r[m] = (scope[at + m], scope[at + Modes + m], scope[at + 2 * Modes + m]);
+ return r;
+ }
+
+ /// <summary>How many of a bank's partials actually sound for a fundamental f0 at the
+ /// sample rate: below Nyquist and at least 2 % of the loudest.</summary>
+ public static int AudiblePartials((double Ratio, double Amp, double Tau)[] bank, double f0, double sampleRate)
+ {
+ double max = 1e-9;
+ foreach (var p in bank) max = Math.Max(max, p.Amp);
+ int n = 0;
+ foreach (var p in bank) if (f0 * p.Ratio < sampleRate * 0.49 && p.Amp >= max * 0.02) n++;
+ return n;
+ }
+
+ private static string S(double v, string f) => v.ToString(f, CultureInfo.InvariantCulture);
+ private static string Secs(double s) => s < 1 ? S(s * 1000, "0") + " ms" : S(s, "0.00") + " s";
+ private static string Pct(float v) => S(v * 100, "0") + " %";
+ private static string Signed(double v, string f) => (v > 0 ? "+" : "") + S(v, f);
+
+ /// <summary>A one-line summary of the patch, from a param-id getter.</summary>
+ public static string Summary(Func<string, float> g)
+ {
+ var sb = new StringBuilder();
+ sb.Append(g("mono") >= 0.5f ? "Mono" : "Poly " + Voices).Append(" · ");
+ var ex = new List<string>();
+ if (g("malletvol") > 0.001f) ex.Add($"mallet {Pct(g("malletvol"))} (stiff {Pct(g("malletstiff"))}, contact {S(ContactMs(g("malletstiff")), "0.0")} ms)");
+ if (g("noisevol") > 0.001f) ex.Add($"noise {Pct(g("noisevol"))} {NoiseTypes[NoiseTypeIndex(g("noisetype"))]} {S(NoiseFreqHz(g("noisefreq")), "0")} Hz");
+ sb.Append(ex.Count == 0 ? "no exciter (silent)" : string.Join(" + ", ex)).Append(" → ");
+ string Bank(string p) => $"{TypeNames[TypeIndex(g(p + "type"))].ToLowerInvariant()} ring {Secs(DecaySeconds(g(p + "decay")))}"
+ + (Math.Abs(BankSemis(g(p + "tune"))) >= 0.05 ? $" {Signed(BankSemis(g(p + "tune")), "0.0")} st" : "");
+ sb.Append("res 1 ").Append(Bank("r1"));
+ if (g("r2on") >= 0.5f)
+ {
+ bool serial = g("structure") < 0.5f;
+ sb.Append(serial ? " → res 2 " : " + res 2 ").Append(Bank("r2"));
+ var (g1, g2) = MixGains(g("resmix"));
+ sb.Append($" (mix {S(g1 * 100, "0")}/{S(g2 * 100, "0")})");
+ }
+ sb.Append($" · tune {Signed(TuneSemis(g("tune")), "0")} st {Signed(FineCents(g("fine")), "0")} c");
+ sb.Append($" · note off {Secs(NoteOffSeconds(g("noteoff")))} · vol {Pct(g("volume"))}");
+ return sb.ToString();
+ }
+
+ /// <summary>What each 0..1 parameter value means, one line per id.</summary>
+ public const string Guide =
+ "All params are normalized 0..1 (set_instrument_param_by_id).\n"
+ + "malletvol / malletnoise / malletcolor: level, strike noise, dark (0) … raw bright (1). malletstiff: soft 10 ms contact (0) … hard 0.4 ms (1), exp.\n"
+ + "noisevol: noise-burst exciter level (0 = off). noisetype: LP 0 / BP 0.5 / HP 1. noisefreq: 60 Hz … 12 kHz, exp. noisereso: 0 … high Q. "
+ + "noiseenv: envelope → filter, 0.5 = none, ±3 oct at the ends. noisea 1 ms … 2 s, noised 2 ms … 4 s, noiser 2 ms … 5 s (exp), noises sustain level.\n"
+ + "r1type / r2type: Beam 0 / Marimba 0.2 / String 0.4 / Membrane 0.6 / Plate 0.8 / Pipe 1 — the partial series. "
+ + "r*decay: fundamental ring 40 ms … 18 s, exp. r*material: how much faster high partials die (0 metal = all ring, 1 wood = highs damped). "
+ + "r*bright: high-partial level tilt. r*inharm: stretches the series (bell-like). r*ratio: partial-spacing exponent 0.5 + v (0.5 = natural). "
+ + "r*hit: strike position along the body (comb over the partials). r*tune: ±24 st, 0.5 = 0.\n"
+ + "r2on: second resonator off (<0.5) / on. structure: 1→2 serial (<0.5, res 1 feeds res 2) / 1+2 parallel. "
+ + "resmix: balance of res 1 against res 2, 0 = res 1 only, 0.5 = both full, 1 = res 2 only (in 1→2: res 1's own sound against the body it rings, res 2 +12 dB).\n"
+ + "tune: ±24 st (0.5 = 0). fine: ±100 cents. noteoff: 0 = released notes ring on (4 s), 1 = damped at once (6 ms). "
+ + "pan: 0 L … 0.5 C … 1 R. volume: output level. mono: 0 poly (8 voices) / 1 mono (a new strike chokes the sounding note).";
+}
diff --git a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
index 05241337..818c9599 100644
--- a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
@@ -57,14 +57,67 @@ public sealed class FactoryPresetCatalog : IFactoryPresets
Inst("synth", 0, "Filter Sweep", ("wave", 0f), ("attack", 0.35f), ("decay", 0.70f), ("sustain", 0.75f), ("release", 0.70f), ("cutoff", 0.30f), ("resonance", 0.45f), ("filenv", 0.92f), ("unison", 0.333f), ("detune", 0.57f), ("gain", 0.74f));
Inst("synth", 0, "Band Motion", ("wave", 0.333f), ("pulsewidth", 0.44f), ("attack", 0.28f), ("decay", 0.62f), ("sustain", 0.70f), ("release", 0.62f), ("filtype", 1f), ("cutoff", 0.58f), ("resonance", 0.50f), ("filenv", 0.74f), ("unison", 0.333f), ("detune", 0.60f), ("spread", 0.65f), ("gain", 0.74f));
- // ---- Nota Physical (kind 2) — modal percussion. Res1 Type: Beam 0 / Marimba .2 /
- // String .4 / Membrane .6 / Plate .8 / Pipe 1. Tune/Ratio are neutral at 0.5.
- Inst("physical", 2, "Marimba", ("malletvol", 0.85f), ("malletstiff", 0.45f), ("r1type", 0.2f), ("r1decay", 0.38f), ("r1material", 0.62f), ("r1bright", 0.55f), ("r1hit", 0.25f), ("volume", 0.8f));
- Inst("physical", 2, "Vibraphone", ("malletvol", 0.8f), ("malletstiff", 0.5f), ("r1type", 0.2f), ("r1decay", 0.78f), ("r1material", 0.22f), ("r1bright", 0.6f), ("r1hit", 0.3f), ("volume", 0.78f));
- Inst("physical", 2, "Glass Bell", ("malletvol", 0.8f), ("malletstiff", 0.62f), ("r1type", 0.0f), ("r1decay", 0.82f), ("r1material", 0.2f), ("r1bright", 0.72f), ("r1inharm", 0.22f), ("r1hit", 0.5f), ("volume", 0.75f));
- Inst("physical", 2, "Tubular", ("malletvol", 0.8f), ("malletstiff", 0.55f), ("r1type", 1.0f), ("r1decay", 0.8f), ("r1material", 0.3f), ("r1bright", 0.55f), ("r1hit", 0.2f), ("volume", 0.72f));
- Inst("physical", 2, "Wood Block", ("malletvol", 0.9f), ("malletstiff", 0.7f), ("r1type", 0.0f), ("r1decay", 0.14f), ("r1material", 0.82f), ("r1bright", 0.5f), ("r1hit", 0.3f), ("volume", 0.82f));
- Inst("physical", 2, "Membrane", ("malletvol", 0.85f), ("malletstiff", 0.5f), ("r1type", 0.6f), ("r1decay", 0.32f), ("r1material", 0.62f), ("r1bright", 0.5f), ("r1inharm", 0.1f), ("r1hit", 0.4f), ("volume", 0.8f));
+ // ---- Nota Physical (kind 2) — 32 modal patches: mallets, bells, percussion, plucked
+ // and blown, textures. Type (r1type / r2type): Beam 0 / Marimba .2 / String .4 /
+ // Membrane .6 / Plate .8 / Pipe 1 · noisetype LP 0 / BP .5 / HP 1 · structure
+ // 1→2 serial 0 / 1+2 parallel 1 · mono Poly 0 / Mono 1. Tune, bank tune, ratio,
+ // noise env, pan and resmix are neutral at .5; tune and bank tune span ±24 st
+ // (.75 = +12, .25 = −12, n st = .5 + n/48). Decay: .5 ≈ 0.85 s, .7 ≈ 2.9 s,
+ // .9 ≈ 10 s. A struck body rings on noise (mallet 0 + sustained noise) = bowed / blown.
+ // Mallets
+ Inst("physical", 2, "Marimba", ("malletvol", 0.85f), ("malletstiff", 0.45f), ("r1type", 0.2f), ("r1decay", 0.38f), ("r1material", 0.62f), ("r1bright", 0.55f), ("r1hit", 0.25f), ("volume", 0.8f));
+ Inst("physical", 2, "Vibraphone", ("malletvol", 0.8f), ("malletstiff", 0.5f), ("r1type", 0.2f), ("r1decay", 0.78f), ("r1material", 0.22f), ("r1bright", 0.6f), ("r1hit", 0.3f), ("volume", 0.78f));
+ Inst("physical", 2, "Xylophone", ("malletvol", 0.85f), ("malletstiff", 0.78f), ("malletcolor", 0.6f), ("r1type", 0.2f), ("r1decay", 0.3f), ("r1material", 0.7f), ("r1bright", 0.72f), ("r1hit", 0.22f), ("tune", 0.75f), ("volume", 0.78f));
+ Inst("physical", 2, "Glockenspiel", ("malletvol", 0.8f), ("malletstiff", 0.88f), ("malletnoise", 0.05f), ("malletcolor", 0.7f), ("r1type", 0f), ("r1decay", 0.72f), ("r1material", 0.18f), ("r1bright", 0.78f), ("r1hit", 0.3f), ("tune", 0.75f), ("volume", 0.7f));
+ Inst("physical", 2, "Bass Marimba", ("malletvol", 0.9f), ("malletstiff", 0.25f), ("malletcolor", 0.2f), ("r1type", 0.2f), ("r1decay", 0.52f), ("r1material", 0.6f), ("r1bright", 0.42f), ("r1hit", 0.2f), ("tune", 0.25f), ("volume", 0.85f));
+ Inst("physical", 2, "Soft Vibes", ("malletvol", 0.8f), ("malletstiff", 0.2f), ("malletcolor", 0.25f), ("r1type", 0.2f), ("r1decay", 0.7f), ("r1material", 0.28f), ("r1bright", 0.45f), ("r1hit", 0.3f),
+ ("r2on", 1f), ("r2type", 0.2f), ("r2decay", 0.72f), ("r2material", 0.28f), ("r2bright", 0.45f), ("r2hit", 0.3f), ("r2tune", 0.50208f), ("volume", 0.72f));
+ Inst("physical", 2, "Balafon", ("malletvol", 0.85f), ("malletstiff", 0.6f), ("malletnoise", 0.3f), ("malletcolor", 0.55f), ("r1type", 0.2f), ("r1decay", 0.26f), ("r1material", 0.78f), ("r1bright", 0.55f), ("r1inharm", 0.06f), ("r1hit", 0.35f),
+ ("noisevol", 0.25f), ("noisetype", 0.5f), ("noisefreq", 0.55f), ("noised", 0.15f), ("noises", 0f), ("noiser", 0.1f), ("volume", 0.8f));
+ // Bells
+ Inst("physical", 2, "Glass Bell", ("malletvol", 0.8f), ("malletstiff", 0.62f), ("r1type", 0.0f), ("r1decay", 0.82f), ("r1material", 0.2f), ("r1bright", 0.72f), ("r1inharm", 0.22f), ("r1hit", 0.5f), ("volume", 0.75f));
+ Inst("physical", 2, "Tubular", ("malletvol", 0.8f), ("malletstiff", 0.55f), ("r1type", 1.0f), ("r1decay", 0.8f), ("r1material", 0.3f), ("r1bright", 0.55f), ("r1hit", 0.2f), ("volume", 0.72f));
+ Inst("physical", 2, "Church Bell", ("malletvol", 0.85f), ("malletstiff", 0.7f), ("r1type", 0.8f), ("r1decay", 0.9f), ("r1material", 0.22f), ("r1bright", 0.62f), ("r1inharm", 0.35f), ("r1hit", 0.4f),
+ ("r2on", 1f), ("r2type", 0f), ("r2decay", 0.85f), ("r2material", 0.25f), ("r2inharm", 0.2f), ("r2tune", 0.25f), ("resmix", 0.4f), ("noteoff", 0.05f), ("volume", 0.7f));
+ Inst("physical", 2, "Music Box", ("malletvol", 0.8f), ("malletstiff", 0.85f), ("malletcolor", 0.7f), ("r1type", 0f), ("r1decay", 0.62f), ("r1material", 0.35f), ("r1bright", 0.7f), ("r1hit", 0.15f), ("tune", 0.75f), ("noteoff", 0.1f), ("volume", 0.72f));
+ Inst("physical", 2, "Crystal Chime", ("malletvol", 0.8f), ("malletstiff", 0.9f), ("r1type", 0f), ("r1decay", 0.85f), ("r1material", 0.15f), ("r1bright", 0.85f), ("r1inharm", 0.12f), ("r1ratio", 0.55f), ("r1hit", 0.45f),
+ ("r2on", 1f), ("r2type", 0f), ("r2decay", 0.8f), ("r2material", 0.15f), ("r2bright", 0.8f), ("r2tune", 0.8958f), ("resmix", 0.35f), ("tune", 0.75f), ("volume", 0.66f));
+ Inst("physical", 2, "Gamelan", ("malletvol", 0.85f), ("malletstiff", 0.6f), ("r1type", 0f), ("r1decay", 0.78f), ("r1material", 0.3f), ("r1bright", 0.55f), ("r1inharm", 0.25f), ("r1ratio", 0.45f), ("r1hit", 0.3f),
+ ("r2on", 1f), ("r2type", 0f), ("r2decay", 0.78f), ("r2material", 0.3f), ("r2bright", 0.55f), ("r2inharm", 0.25f), ("r2ratio", 0.45f), ("r2hit", 0.3f), ("r2tune", 0.50417f),
+ ("noteoff", 0.1f), ("volume", 0.72f));
+ Inst("physical", 2, "Singing Bowl", ("malletvol", 0.6f), ("malletstiff", 0.3f), ("malletcolor", 0.3f), ("r1type", 0f), ("r1decay", 0.95f), ("r1material", 0.1f), ("r1bright", 0.5f), ("r1inharm", 0.15f), ("r1ratio", 0.42f), ("r1hit", 0.5f),
+ ("noisevol", 0.15f), ("noisetype", 0.5f), ("noisefreq", 0.45f), ("noisea", 0.5f), ("noises", 0.5f), ("noiser", 0.5f), ("noteoff", 0.02f), ("tune", 0.25f), ("volume", 0.7f));
+ Inst("physical", 2, "Wind Chimes", ("malletvol", 0.8f), ("malletstiff", 0.85f), ("r1type", 0.8f), ("r1decay", 0.8f), ("r1material", 0.2f), ("r1bright", 0.8f), ("r1inharm", 0.4f), ("r1hit", 0.5f), ("tune", 0.75f), ("noteoff", 0.05f), ("volume", 0.66f));
+ // Percussion
+ Inst("physical", 2, "Wood Block", ("malletvol", 0.9f), ("malletstiff", 0.7f), ("r1type", 0.0f), ("r1decay", 0.14f), ("r1material", 0.82f), ("r1bright", 0.5f), ("r1hit", 0.3f), ("volume", 0.82f));
+ Inst("physical", 2, "Membrane", ("malletvol", 0.85f), ("malletstiff", 0.5f), ("r1type", 0.6f), ("r1decay", 0.32f), ("r1material", 0.62f), ("r1bright", 0.5f), ("r1inharm", 0.1f), ("r1hit", 0.4f), ("volume", 0.8f));
+ Inst("physical", 2, "Hand Drum", ("malletvol", 0.85f), ("malletstiff", 0.35f), ("malletnoise", 0.35f), ("malletcolor", 0.35f), ("r1type", 0.6f), ("r1decay", 0.28f), ("r1material", 0.7f), ("r1bright", 0.45f), ("r1inharm", 0.05f), ("r1hit", 0.15f),
+ ("noisevol", 0.3f), ("noisefreq", 0.45f), ("noised", 0.12f), ("noises", 0f), ("noiser", 0.1f), ("tune", 0.25f), ("volume", 0.85f));
+ Inst("physical", 2, "Steel Drum", ("malletvol", 0.85f), ("malletstiff", 0.5f), ("r1type", 0.4f), ("r1decay", 0.55f), ("r1material", 0.45f), ("r1bright", 0.6f), ("r1hit", 0.3f),
+ ("r2on", 1f), ("r2type", 0.6f), ("r2decay", 0.45f), ("r2material", 0.5f), ("r2tune", 0.75f), ("resmix", 0.35f), ("volume", 0.76f));
+ Inst("physical", 2, "Log Drum", ("malletvol", 0.9f), ("malletstiff", 0.35f), ("malletcolor", 0.3f), ("r1type", 0f), ("r1decay", 0.3f), ("r1material", 0.75f), ("r1bright", 0.4f), ("r1ratio", 0.45f), ("r1hit", 0.2f), ("tune", 0.25f), ("volume", 0.85f));
+ Inst("physical", 2, "Cowbell", ("malletvol", 0.85f), ("malletstiff", 0.8f), ("malletnoise", 0.2f), ("r1type", 0.8f), ("r1decay", 0.28f), ("r1material", 0.55f), ("r1bright", 0.65f), ("r1inharm", 0.3f), ("r1ratio", 0.6f), ("r1hit", 0.35f), ("tune", 0.75f), ("volume", 0.72f));
+ Inst("physical", 2, "Clave", ("malletvol", 0.9f), ("malletstiff", 0.9f), ("r1type", 0f), ("r1decay", 0.18f), ("r1material", 0.7f), ("r1bright", 0.6f), ("r1hit", 0.4f), ("tune", 0.75f), ("volume", 0.8f));
+ Inst("physical", 2, "Kalimba", ("malletvol", 0.85f), ("malletstiff", 0.62f), ("malletcolor", 0.5f), ("r1type", 0f), ("r1decay", 0.5f), ("r1material", 0.45f), ("r1bright", 0.55f), ("r1hit", 0.1f),
+ ("r2on", 1f), ("r2type", 0.6f), ("r2decay", 0.2f), ("r2material", 0.6f), ("structure", 0f), ("volume", 0.8f));
+ // Plucked, blown and bowed
+ Inst("physical", 2, "Harp Pluck", ("malletvol", 0.9f), ("malletstiff", 0.55f), ("malletcolor", 0.5f), ("r1type", 0.4f), ("r1decay", 0.62f), ("r1material", 0.55f), ("r1bright", 0.6f), ("r1hit", 0.12f), ("noteoff", 0.2f), ("volume", 0.78f));
+ Inst("physical", 2, "Koto", ("malletvol", 0.85f), ("malletstiff", 0.75f), ("malletnoise", 0.2f), ("r1type", 0.4f), ("r1decay", 0.55f), ("r1material", 0.6f), ("r1bright", 0.7f), ("r1inharm", 0.04f), ("r1hit", 0.08f), ("volume", 0.76f));
+ Inst("physical", 2, "Tine Keys", ("malletvol", 0.85f), ("malletstiff", 0.55f), ("r1type", 0f), ("r1decay", 0.7f), ("r1material", 0.5f), ("r1bright", 0.5f), ("r1hit", 0.12f),
+ ("r2on", 1f), ("structure", 0f), ("r2type", 0.4f), ("r2decay", 0.45f), ("r2bright", 0.5f), ("r2hit", 0.2f), ("noteoff", 0.45f), ("volume", 0.8f));
+ Inst("physical", 2, "Pan Flute", ("malletvol", 0f), ("noisevol", 0.3f), ("noisetype", 0.5f), ("noisefreq", 0.62f), ("noisereso", 0.3f), ("noisea", 0.35f), ("noised", 0.4f), ("noises", 0.8f), ("noiser", 0.35f),
+ ("r1type", 1f), ("r1decay", 0.32f), ("r1material", 0.6f), ("r1bright", 0.5f), ("r1hit", 0.5f), ("noteoff", 0.6f), ("volume", 0.8f));
+ Inst("physical", 2, "Blown Bottle", ("malletvol", 0f), ("noisevol", 0.2f), ("noisetype", 0.5f), ("noisefreq", 0.5f), ("noisereso", 0.4f), ("noisea", 0.3f), ("noises", 0.7f), ("noiser", 0.3f),
+ ("r1type", 1f), ("r1decay", 0.6f), ("r1material", 0.75f), ("r1bright", 0.35f), ("r1hit", 0.5f), ("volume", 0.55f));
+ Inst("physical", 2, "Bowed Glass", ("malletvol", 0f), ("noisevol", 0.14f), ("noisetype", 0.5f), ("noisefreq", 0.7f), ("noisereso", 0.5f), ("noisea", 0.55f), ("noised", 0.5f), ("noises", 0.85f), ("noiser", 0.5f),
+ ("r1type", 0f), ("r1decay", 0.85f), ("r1material", 0.2f), ("r1bright", 0.7f), ("r1inharm", 0.12f), ("r1hit", 0.45f), ("noteoff", 0.35f), ("volume", 0.55f));
+ // Textures and mono
+ Inst("physical", 2, "Metal Plate", ("malletvol", 0.85f), ("malletstiff", 0.7f), ("malletnoise", 0.25f), ("r1type", 0.8f), ("r1decay", 0.82f), ("r1material", 0.25f), ("r1bright", 0.7f), ("r1inharm", 0.2f), ("r1hit", 0.6f),
+ ("r2on", 1f), ("r2type", 0.8f), ("r2decay", 0.75f), ("r2material", 0.25f), ("r2inharm", 0.35f), ("r2tune", 0.6458f), ("noteoff", 0.1f), ("volume", 0.66f));
+ Inst("physical", 2, "Mono Kalimba", ("mono", 1f), ("malletvol", 0.85f), ("malletstiff", 0.62f), ("r1type", 0f), ("r1decay", 0.5f), ("r1material", 0.45f), ("r1bright", 0.6f), ("r1hit", 0.1f),
+ ("r2on", 1f), ("r2type", 0.6f), ("r2decay", 0.2f), ("r2material", 0.6f), ("structure", 0f), ("tune", 0.75f), ("volume", 0.8f));
+ Inst("physical", 2, "Sub Thump", ("mono", 1f), ("malletvol", 0.9f), ("malletstiff", 0.2f), ("malletcolor", 0.15f), ("r1type", 0.6f), ("r1decay", 0.3f), ("r1material", 0.8f), ("r1bright", 0.3f), ("r1hit", 0.1f),
+ ("noisevol", 0.2f), ("noisefreq", 0.2f), ("noised", 0.1f), ("noises", 0f), ("tune", 0.25f), ("volume", 0.9f));
// ---- Nota Aurora (kind 5) — 25 patches: pads, keys, leads, basses, plucks and
// motion. Table: Analog 0 / Pulse .333 / Formant .667 / Chroma 1 · warp mode
@@ -1192,14 +1245,45 @@ public sealed class FactoryPresetCatalog : IFactoryPresets
Fx("delay", 3, "Send · Eighth", ("Wet Only", 1f), ("Sync", 1f), ("Div L", 0.286f), ("Div R", 0.286f), ("Ping-Pong", 1f), ("Feedback", 0.40f), ("Low Cut", 0.42f), ("High Cut", 0.78f), ("Bass Mono", 0.49f), ("Dry/Wet", 1f));
Fx("delay", 3, "Send · Quarter", ("Wet Only", 1f), ("Sync", 1f), ("Div L", 0.714f), ("Div R", 0.714f), ("Ping-Pong", 1f), ("Feedback", 0.45f), ("Spread", 0.55f), ("Width", 0.80f), ("Low Cut", 0.45f), ("Dry/Wet", 1f));
- // ---- Utility (kind 4) — Gain -24..24 dB · Balance -1..1 · Width 0..400% ·
- // Channel Mode 0..3 (Stereo/Left/Right/Swap) · Mono Freq 20..2000 Hz · toggles 0/1
- Fx("util", 4, "Stereo Widener", ("Gain", 0f), ("Width", 175f), ("Balance", 0f));
- Fx("util", 4, "Bass Mono", ("Width", 130f), ("Mono Below", 1f), ("Mono Freq", 140f));
- Fx("util", 4, "Mono Maker", ("Width", 100f), ("Mono Below", 1f), ("Mono Freq", 500f));
- Fx("util", 4, "Narrow", ("Width", 55f));
- Fx("util", 4, "Trim −6 dB", ("Gain", -6f));
- Fx("util", 4, "Swap L/R", ("Channel Mode", 3f));
+ // ---- Nota Utility (kind 4) — real units: Gain −24..24 dB · Balance −1..1 · Width 0..400 % ·
+ // Channel Mode 0 Stereo/1 Left/2 Right/3 Swap · Mono Freq 20..2000 Hz · Mono Slope 0 = 6 /
+ // 1 = 12 / 2 = 24 dB/oct · Width Mode 0 L/R / 1 M/S (mid ↔ side, 200 % = side only) ·
+ // Match To 0 input / 1 Target · Target −36..0 in the Meter's unit · Meter 0 LUFS-S / 1 Peak /
+ // 2 RMS · TP Ceiling −6..0 dBTP · toggles 1 = on. Unnamed → default (the device as added).
+ Fx("util", 4, "Init", ("Width", 100f));
+ // Width
+ Fx("util", 4, "Stereo Widener", ("Width", 175f));
+ Fx("util", 4, "Wide, Level Held",("Width", 150f), ("Width Mode", 1f));
+ Fx("util", 4, "Wide Master", ("Width", 125f), ("Mono Below", 1f), ("Mono Freq", 120f), ("Mono Slope", 1f));
+ Fx("util", 4, "Wide Pad", ("Width", 160f), ("Width Mode", 1f), ("Mono Below", 1f), ("Mono Freq", 200f), ("Mono Slope", 1f));
+ Fx("util", 4, "Bus Glue", ("Width", 115f), ("Mono Below", 1f), ("Mono Freq", 120f), ("Mono Slope", 1f));
+ Fx("util", 4, "Narrow", ("Width", 55f));
+ Fx("util", 4, "Mono", ("Width", 0f));
+ Fx("util", 4, "Side Only", ("Width", 200f), ("Width Mode", 1f));
+ // Bass mono
+ Fx("util", 4, "Bass Mono", ("Width", 130f), ("Mono Below", 1f), ("Mono Freq", 140f));
+ Fx("util", 4, "Mono Maker", ("Width", 100f), ("Mono Below", 1f), ("Mono Freq", 500f));
+ Fx("util", 4, "Club Low End", ("Mono Below", 1f), ("Mono Freq", 100f), ("Mono Slope", 2f));
+ Fx("util", 4, "Sub Mono 60", ("Mono Below", 1f), ("Mono Freq", 60f), ("Mono Slope", 2f));
+ Fx("util", 4, "Vinyl Safe", ("Mono Below", 1f), ("Mono Freq", 250f), ("Mono Slope", 1f), ("Width", 90f), ("TP Limit", 1f), ("TP Ceiling", -1f));
+ // Routing
+ Fx("util", 4, "Swap L/R", ("Channel Mode", 3f));
+ Fx("util", 4, "Left Only", ("Channel Mode", 1f));
+ Fx("util", 4, "Right Only", ("Channel Mode", 2f));
+ Fx("util", 4, "Polarity Flip", ("Invert L", 1f), ("Invert R", 1f));
+ Fx("util", 4, "Fix Left Polarity", ("Invert L", 1f));
+ Fx("util", 4, "Mute", ("Mute", 1f));
+ // Levels
+ Fx("util", 4, "Trim −6 dB", ("Gain", -6f));
+ Fx("util", 4, "Boost +6 dB", ("Gain", 6f));
+ Fx("util", 4, "Level Match", ("Auto Match", 1f));
+ Fx("util", 4, "RMS Match", ("Auto Match", 1f), ("Meter", 2f));
+ Fx("util", 4, "Gain Match −9", ("Match To", 1f), ("Target", -9f), ("TP Limit", 1f), ("TP Ceiling", -1f));
+ Fx("util", 4, "Streaming −14 LUFS", ("Auto Match", 1f), ("Match To", 1f), ("Target", -14f), ("TP Limit", 1f), ("TP Ceiling", -1f));
+ Fx("util", 4, "Podcast −16 LUFS", ("Auto Match", 1f), ("Match To", 1f), ("Target", -16f), ("TP Limit", 1f), ("TP Ceiling", -1f));
+ Fx("util", 4, "Broadcast −23 LUFS", ("Auto Match", 1f), ("Match To", 1f), ("Target", -23f), ("TP Limit", 1f), ("TP Ceiling", -1f));
+ Fx("util", 4, "Peak Target −3 dB", ("Meter", 1f), ("Match To", 1f), ("Target", -3f));
+ Fx("util", 4, "True-Peak Safety", ("TP Limit", 1f), ("TP Ceiling", -1f));
// ---- Nota Valve (kind 6) — the first 14 params keep their raw units: Model 0 Clean/1 Boost/
// 2 Blues/3 Rock/4 Lead/5 Heavy/6 Bass; Gain / Bass / Middle / Treble / Presence / Output
diff --git a/src/managed/Nota.Mcp/Tools/DeviceTools.cs b/src/managed/Nota.Mcp/Tools/DeviceTools.cs
index 33cd2d5e..9f2c5b4c 100644
--- a/src/managed/Nota.Mcp/Tools/DeviceTools.cs
+++ b/src/managed/Nota.Mcp/Tools/DeviceTools.cs
@@ -67,10 +67,10 @@ public sealed class DeviceTools(IAudioEngine engine, IEngineDispatch dispatch, I
[McpServerTool(Name = "load_device_file"), Description("Load an audio file into a device that takes one — Nota Chamber: a user impulse response (WAV / FLAC / MP3; mono, stereo or 4-channel true stereo), which also selects it. Returns true on success.")]
public Task<bool> LoadDeviceFile(int trackId, int deviceIndex, [Description("Absolute path to the audio file")] string path) => Mutate(() => E.DeviceLoadFile(trackId, deviceIndex, path));
- [McpServerTool(Name = "get_device_text"), Description("Read a device's resource text. Nota Chamber: id 0 = current IR name, 1 = its category, 2 = the loaded user IR's name, 10 = the built-in IR list (name, category, seconds per line; the IR param selects entry round(v × 16), 1.0 = the user IR). Nota Lens: id 0 = the analysis summary, 1 = the third-octave band table, 2 = the scope measurements, 3 = the strongest spectral peaks, 4 = the A/B cursor measurements — or use read_analyzer, which returns all of it parsed. Delay (kind 3): id 0 = a one-line summary of what it is doing now (sync division or free times, ping-pong, feedback, mix, or that it is frozen). Reverb (kind 2): id 0 = a one-line summary (algorithm, RT60, pre-delay, diffusion, mix, early reflections / vintage, or that the tail is frozen). Compressor (kind 1): id 0 = a one-line summary (character, threshold, ratio, knee, attack / release, detector, range, mix, the reduction right now, external key / unlinked / Listen) — or use read_dynamics for the numbers. Auto Filter (kind 7): id 0 = a one-line summary (type, slope, cutoff, Q, what the envelope and LFO drive and by how much, drive, mix, sidechain key), 1 = the live reading (modulated cutoff with its note, resonance, envelope level, LFO value and phase, onsets counted), 2 = a guide to what each 0..1 parameter value means — or use read_filter_motion for the numbers. Nota Vintage (kind 8): id 0 = a one-line summary (character, drive, tone model and shelves, wow / flutter with their rates, noise, crackle, wear, stage, mix, output, oversampling, auto-comp), 1 = the live reading (in / out peaks, THD with the 2nd and 3rd harmonics, asymmetry, wow and flutter in cents, band-limit, hiss level, auto-comp gain), 2 = a guide to what each 0..1 parameter value means — or use read_vintage for the numbers. Nota Valve (kind 6): id 0 = a one-line summary (model, gain, the tone stack with the middle's frequency, bright / deep, even-only, cabinet with mic, distance, axis and position, low / high cut, gate, mix, output, oversampling, auto-comp), 1 = the live reading (in / out peaks, THD with the 2nd and 3rd harmonics, estimated aliasing, drive, gate open / closed, auto-comp gain, the cab's loss at 4 kHz vs on-axis), 2 = a guide to the parameter values and units — or use read_valve for the numbers.")]
+ [McpServerTool(Name = "get_device_text"), Description("Read a device's resource text. Nota Chamber: id 0 = current IR name, 1 = its category, 2 = the loaded user IR's name, 10 = the built-in IR list (name, category, seconds per line; the IR param selects entry round(v × 16), 1.0 = the user IR). Nota Lens: id 0 = the analysis summary, 1 = the third-octave band table, 2 = the scope measurements, 3 = the strongest spectral peaks, 4 = the A/B cursor measurements — or use read_analyzer, which returns all of it parsed. Delay (kind 3): id 0 = a one-line summary of what it is doing now (sync division or free times, ping-pong, feedback, mix, or that it is frozen). Reverb (kind 2): id 0 = a one-line summary (algorithm, RT60, pre-delay, diffusion, mix, early reflections / vintage, or that the tail is frozen). Compressor (kind 1): id 0 = a one-line summary (character, threshold, ratio, knee, attack / release, detector, range, mix, the reduction right now, external key / unlinked / Listen) — or use read_dynamics for the numbers. Auto Filter (kind 7): id 0 = a one-line summary (type, slope, cutoff, Q, what the envelope and LFO drive and by how much, drive, mix, sidechain key), 1 = the live reading (modulated cutoff with its note, resonance, envelope level, LFO value and phase, onsets counted), 2 = a guide to what each 0..1 parameter value means — or use read_filter_motion for the numbers. Nota Vintage (kind 8): id 0 = a one-line summary (character, drive, tone model and shelves, wow / flutter with their rates, noise, crackle, wear, stage, mix, output, oversampling, auto-comp), 1 = the live reading (in / out peaks, THD with the 2nd and 3rd harmonics, asymmetry, wow and flutter in cents, band-limit, hiss level, auto-comp gain), 2 = a guide to what each 0..1 parameter value means — or use read_vintage for the numbers. Nota Valve (kind 6): id 0 = a one-line summary (model, gain, the tone stack with the middle's frequency, bright / deep, even-only, cabinet with mic, distance, axis and position, low / high cut, gate, mix, output, oversampling, auto-comp), 1 = the live reading (in / out peaks, THD with the 2nd and 3rd harmonics, estimated aliasing, drive, gate open / closed, auto-comp gain, the cab's loss at 4 kHz vs on-axis), 2 = a guide to the parameter values and units — or use read_valve for the numbers. Nota Utility (kind 4): id 0 = a one-line summary (channel mode, width and its L/R or M/S law, mono below with its slope, balance, phase, mute, gain, auto match and its reference, true-peak limit), 1 = the live reading (in / out LUFS-S, peak and RMS, true peak, the delta in the meter's unit, correlation, width, energy balance, auto-match gain, limiter reduction), 2 = a guide to the parameter values and units — or use read_utility for the numbers.")]
public Task<string> GetDeviceText(int trackId, int deviceIndex, int id) => Read(() => E.DeviceText(trackId, deviceIndex, id));
- [McpServerTool(Name = "device_action"), Description("Run a device's own command — the few things that are actions rather than parameters. Delay (kind 3): id 0 clears the loop (empties the delay buffer, so whatever is still circulating stops; useful after Freeze). Reverb (kind 2): id 0 kills the tail (empties the reverb's buffers, so whatever is still ringing — or frozen — stops). Auto Filter (kind 7): id 0 restarts the LFO (from its start phase; in Sync the cycle is re-anchored to the current beat), id 1 resets the envelope follower (drops a held peak). Nota Vintage (kind 8): id 0 resets the wear (restarts the wow and flutter at their zero phase and silences a ringing crackle). Nota Valve (kind 6): id 0 resets the amp (clears the filters, the gate and the auto-comp). Devices without a command ignore the call.")]
+ [McpServerTool(Name = "device_action"), Description("Run a device's own command — the few things that are actions rather than parameters. Delay (kind 3): id 0 clears the loop (empties the delay buffer, so whatever is still circulating stops; useful after Freeze). Reverb (kind 2): id 0 kills the tail (empties the reverb's buffers, so whatever is still ringing — or frozen — stops). Auto Filter (kind 7): id 0 restarts the LFO (from its start phase; in Sync the cycle is re-anchored to the current beat), id 1 resets the envelope follower (drops a held peak). Nota Vintage (kind 8): id 0 resets the wear (restarts the wow and flutter at their zero phase and silences a ringing crackle). Nota Valve (kind 6): id 0 resets the amp (clears the filters, the gate and the auto-comp). Nota Utility (kind 4): id 0 gain match — moves Gain once so the output meets the reference (the input's level, or Target when Match To = 1) over the last 3 s in the Meter's unit; id 1 resets the meters (level history, holds and the auto-match ride). Devices without a command ignore the call.")]
public Task DeviceAction(int trackId, int deviceIndex, [Description("Command id — see the device's list in this description")] int id,
int intArg = 0, float floatArg = 0) => Mutate(() => E.DeviceAction(trackId, deviceIndex, id, intArg, floatArg));
@@ -238,6 +238,52 @@ public sealed class DeviceTools(IAudioEngine engine, IEngineDispatch dispatch, I
Math.Round(V(19), 1), Math.Round(V(27), 1), Curve(tele), Curve(tele + 2 * resp), V(3));
});
+ public sealed record UtilityBand(double Hz, double Pan, double Width, double Correlation, double LevelDb, double SetWidthPercent);
+ public sealed record UtilityReading(string Summary, string Live, string Meter, double InLevel, double OutLevel, double DeltaDb,
+ double InLufsShort, double OutLufsShort, double InPeakDb, double OutPeakDb, double InRmsDb, double OutRmsDb, double TruePeakDb,
+ double Correlation, double WidthPercent, double ConfiguredWidthPercent, double EnergyBalanceDb, double AutoMatchDb, double LimiterDb,
+ double MonoHz, UtilityBand[] Bands, double SampleRate);
+
+ [McpServerTool(Name = "read_utility"), Description(
+ "Read what a Nota Utility (built-in effect kind 4 — routing, stereo field and levels) is measuring right now: the input and "
+ + "output level in the Meter's unit (LUFS-S / Peak / RMS) and their delta, short-term loudness (LUFS, 3 s), sample peak "
+ + "(dBFS, 1 s hold) and RMS (dBFS, 300 ms) of both, the output true peak (dBTP, 3 s hold), the output correlation (−1..+1), "
+ + "its width (side against mid, %; 100 = uncorrelated), the configured width above the mono cutoff, the L/R energy balance "
+ + "(dB, + = left louder), the auto-match gain, the true-peak limiter's reduction, the mono cutoff (0 = off) and eight bands "
+ + "of the output's stereo field over the last second (pan −1 L … +1 R, width share 0 mono … 0.71 uncorrelated … 1 "
+ + "anti-phase, correlation, level dB, and the width the settings give that band in %). Levels move only while audio plays "
+ + "through the track (−120 = silence). Use get_device_text id 2 for what each parameter value means, device_action 0 to "
+ + "gain match.")]
+ public Task<UtilityReading> ReadUtility(int trackId, int deviceIndex) => Read(() =>
+ {
+ const int tele = 48, hist = 80, bands = 32, resp = 96;
+ const int bandAt = tele + 6 * hist;
+ var sc = new float[bandAt + 5 * bands + resp];
+ int n = E.DeviceScope(trackId, deviceIndex, sc, sc.Length);
+ float V(int i) => n > i ? sc[i] : 0f;
+ float L(int i) => n > i ? sc[i] : -120f;
+ static double R1(double v) => Math.Round(v, 1);
+ string[] meters = { "LUFS-S", "Peak", "RMS" };
+ double inL = L(16), outL = L(17);
+ // Eight bands: every fourth analysis band, their centres ~ 45 Hz … 11 kHz.
+ var outBands = new List<UtilityBand>();
+ if (n >= bandAt + 5 * bands)
+ {
+ double lo = V(28) > 0 ? V(28) : 30, hi = V(29) > lo ? V(29) : 16000;
+ for (int b = 1; b < bands; b += 4)
+ {
+ double hz = lo * Math.Pow(hi / lo, (b + 0.5) / bands);
+ outBands.Add(new UtilityBand(Math.Round(hz), Math.Round(sc[bandAt + b], 2), Math.Round(sc[bandAt + bands + b], 2),
+ Math.Round(sc[bandAt + 2 * bands + b], 2), R1(sc[bandAt + 3 * bands + b]), Math.Round(sc[bandAt + 4 * bands + b])));
+ }
+ }
+ return new UtilityReading(E.DeviceText(trackId, deviceIndex, 0), E.DeviceText(trackId, deviceIndex, 1),
+ meters[Math.Clamp((int)V(24), 0, 2)], R1(inL), R1(outL), inL > -119 && outL > -119 ? R1(outL - inL) : 0,
+ R1(L(5)), R1(L(6)), R1(L(9)), R1(L(10)), R1(L(7)), R1(L(8)), R1(L(11)),
+ Math.Round(V(4), 2), Math.Round(V(21)), Math.Round(V(22)), R1(V(20)), R1(V(14)), R1(V(15)), Math.Round(V(23)),
+ outBands.ToArray(), V(3));
+ });
+
public sealed record AnalyzerBand(double Hz, double Db);
public sealed record AnalyzerPeak(double Hz, double Db, string Note);
public sealed record AnalyzerReading(string Summary, string Scope, string Cursors, AnalyzerBand[] Bands, AnalyzerPeak[] Peaks);
diff --git a/src/managed/Nota.Mcp/Tools/InstrumentTools.cs b/src/managed/Nota.Mcp/Tools/InstrumentTools.cs
index 723e6443..2cf54464 100644
--- a/src/managed/Nota.Mcp/Tools/InstrumentTools.cs
+++ b/src/managed/Nota.Mcp/Tools/InstrumentTools.cs
@@ -62,6 +62,57 @@ public sealed class InstrumentTools(IAudioEngine engine, IEngineDispatch dispatc
public Task SetInstrumentParam(int trackId, int paramIndex, [Description("Normalized 0..1")] float value)
=> Mutate(() => E.PluginParamSet(trackId, -1, paramIndex, Math.Clamp(value, 0f, 1f)));
+ public sealed record PhysicalPartial(int Index, double Ratio, double Hz, double Amp, double RingSeconds, bool Audible);
+ public sealed record PhysicalReading(string Summary, string Guide, int ActiveVoices, int MaxVoices, bool Mono,
+ double LastNoteHz, double OutputPeakDb, string Res1Type, string Res2Type, bool Res2On, string Structure,
+ int Res1Audible, int Res2Audible, PhysicalPartial[] Res1, PhysicalPartial[] Res2);
+
+ [McpServerTool(Name = "read_physical"), Description(
+ "Read a Nota Physical track (built-in instrument kind 2 — modal percussion: a mallet and/or filtered noise burst "
+ + "strikes one or two tuned resonator banks). Returns a one-line summary of the patch, a guide to what each 0..1 "
+ + "parameter value means (ids for set_instrument_param_by_id), the sounding voices (8 in Poly, 1 in Mono), the last "
+ + "struck fundamental (Hz, 0 = none yet), the output peak (dBFS, ~300 ms hold; -120 = silence) and both resonators' "
+ + "16 partials exactly as the engine tunes them: ratio to the note, Hz at the last note (or middle C before the first), "
+ + "struck amplitude, ring time in seconds, and whether it sounds (below Nyquist, >= 2 % of the loudest). Res 2 only "
+ + "sounds when Res2On; Structure 1>2 feeds res 1 into res 2, 1+2 strikes both; resmix balances res 1 against res 2 in either.")]
+ public Task<PhysicalReading?> ReadPhysical(int trackId) => Read<PhysicalReading?>(() =>
+ {
+ if (E.TrackInstrumentKind(trackId) != PhysicalModel.Kind) return null;
+ int pc = E.PluginParamCount(trackId, -1);
+ var vals = new Dictionary<string, float>();
+ for (int i = 0; i < pc; i++) vals[E.PluginParamId(trackId, -1, i)] = E.PluginParamGet(trackId, -1, i);
+ float G(string id) => vals.TryGetValue(id, out var v) ? v : 0f;
+ var sc = new float[PhysicalModel.ScopeLength];
+ int n = E.InstrumentScope(trackId, sc);
+ var scope = sc[..Math.Max(0, n)];
+ double sr = E.SampleRate > 0 ? E.SampleRate : 48000;
+ double f0 = n > 2 && sc[2] > 0 ? sc[2] : 261.63;
+ PhysicalPartial[] Bank(int b, out int audible)
+ {
+ var modes = PhysicalModel.Bank(scope, b);
+ double max = 1e-9;
+ foreach (var m in modes) max = Math.Max(max, m.Amp);
+ var list = new PhysicalPartial[modes.Length];
+ audible = 0;
+ for (int i = 0; i < modes.Length; i++)
+ {
+ var (r, a, tau) = modes[i];
+ bool on = f0 * r < sr * 0.49 && a >= max * 0.02;
+ if (on) audible++;
+ list[i] = new PhysicalPartial(i, Math.Round(r, 4), Math.Round(f0 * r, 1), Math.Round(a, 3), Math.Round(tau, 3), on);
+ }
+ return list;
+ }
+ var r1 = Bank(0, out int a1);
+ var r2 = Bank(1, out int a2);
+ double peak = n > 3 ? sc[3] : 0;
+ return new PhysicalReading(PhysicalModel.Summary(G), PhysicalModel.Guide,
+ n > 0 ? (int)sc[0] : 0, PhysicalModel.Voices, G("mono") >= 0.5f,
+ n > 2 ? Math.Round(sc[2], 2) : 0, peak > 1e-6 ? Math.Round(20 * Math.Log10(peak), 1) : -120,
+ PhysicalModel.TypeNames[PhysicalModel.TypeIndex(G("r1type"))], PhysicalModel.TypeNames[PhysicalModel.TypeIndex(G("r2type"))],
+ G("r2on") >= 0.5f, G("structure") < 0.5f ? "1>2 serial" : "1+2 parallel", a1, a2, r1, r2);
+ });
+
[McpServerTool(Name = "set_instrument_param_by_id"), Description(
"Set a track instrument parameter by its stable id (e.g. \"cutoff\", \"pmoscb\") to a normalized value (0..1). "
+ "Ids never change between versions, unlike indices. Returns false if the instrument has no such parameter.")]
diff --git a/src/native/nota.engine/src/PhysicalSynth.h b/src/native/nota.engine/src/PhysicalSynth.h
index 86a5b2e2..f40e8a87 100644
--- a/src/native/nota.engine/src/PhysicalSynth.h
+++ b/src/native/nota.engine/src/PhysicalSynth.h
@@ -9,11 +9,19 @@
//
// Mallet ┐ ┌─ Resonator 1 ─┐ (1>2 serial: 1 → 2)
// ┼─ exciter ───────────┤ ├─→ out
-// Noise ┘ └─ Resonator 2 ─┘ (1+2 parallel: 1 + 2)
+// Noise ┘ └─ Resonator 2 ─┘ (1+2 parallel: 1 and 2 both struck)
+//
+// Res Mix balances what comes out: resonator 1 against resonator 2 — in 1>2, resonator 1's
+// own sound against the body it rings (+12 dB make-up, as only its partials that meet
+// resonator 2's pass through).
//
// Mode coefficients (frequency / decay / amplitude, per Type + Decay/Material/Bright/
// Inharm/Ratio/Hit/Tune) are computed at note-on per voice; the exciter and global
-// params (Volume/Pan/NoteOff/Tune) apply live. All params ride the Instrument plugin-
+// params (Volume/Pan/NoteOff/Tune/Res Mix) apply live. Poly plays 8 voices; Mono chokes
+// the sounding note (a ~4 ms fade) whenever a new one strikes. scopeRead() exposes the
+// live voice count, the last struck pitch, the output peak and both banks' mode tables
+// (ratio / amplitude / ring time) exactly as buildBank freezes them — the editor's
+// partial spectrum and the MCP read_physical tool draw on it. All params ride the Instrument plugin-
// param interface (normalized 0..1, stable ids) → automation / persist / clone for free.
// Header-only, allocation-free after construction. Name & DSP are Nota's own.
@@ -34,6 +42,9 @@ namespace nota {
class PhysicalSynth final : public Instrument {
public:
+ static constexpr int kVoices = 8;
+ static constexpr int kModes = 16;
+
// Parameter layout (normalized 0..1). Order == persisted state layout — APPEND ONLY.
enum Param {
MalletVol = 0, MalletStiff, MalletNoise, MalletColor,
@@ -41,6 +52,7 @@ public:
R1Type, R1Decay, R1Material, R1Bright, R1Inharm, R1Ratio, R1Hit, R1Tune,
R2On, R2Type, R2Decay, R2Material, R2Bright, R2Inharm, R2Ratio, R2Hit, R2Tune,
Structure, Tune, Fine, NoteOff, Pan, Volume,
+ Mono, ResMix, // v2 (redesign): voice mode, Res 1 / Res 2 balance in 1+2
kNumParams
};
@@ -55,6 +67,9 @@ public:
set(R2Inharm, 0.0f); set(R2Ratio, 0.5f); set(R2Hit, 0.3f); set(R2Tune, 0.5f);
set(Structure, 1.0f); // 1+2 parallel
set(Tune, 0.5f); set(Fine, 0.5f); set(NoteOff, 0.3f); set(Pan, 0.5f); set(Volume, 0.8f);
+ // Poly, and an even balance — both banks at full level, the pre-v2 "1 + 2" sum, so a
+ // project saved before these two params existed sounds the same.
+ set(Mono, 0.0f); set(ResMix, 0.5f);
}
int32_t kind() const override { return 2; }
@@ -70,7 +85,8 @@ public:
"noisevol", "noiseenv", "noisetype", "noisefreq", "noisereso", "noisea", "noised", "noises", "noiser",
"r1type", "r1decay", "r1material", "r1bright", "r1inharm", "r1ratio", "r1hit", "r1tune",
"r2on", "r2type", "r2decay", "r2material", "r2bright", "r2inharm", "r2ratio", "r2hit", "r2tune",
- "structure", "tune", "fine", "noteoff", "pan", "volume" };
+ "structure", "tune", "fine", "noteoff", "pan", "volume",
+ "mono", "resmix" };
return (i >= 0 && i < kNumParams) ? std::string(ids[i]) : std::string{};
}
std::string pluginParamName(int32_t i) const override {
@@ -79,7 +95,8 @@ public:
"Noise Volume", "Noise Env", "Noise Type", "Noise Freq", "Noise Reso", "Noise Attack", "Noise Decay", "Noise Sustain", "Noise Release",
"Res1 Type", "Res1 Decay", "Res1 Material", "Res1 Bright", "Res1 Inharm", "Res1 Ratio", "Res1 Hit", "Res1 Tune",
"Res2 On", "Res2 Type", "Res2 Decay", "Res2 Material", "Res2 Bright", "Res2 Inharm", "Res2 Ratio", "Res2 Hit", "Res2 Tune",
- "Structure", "Tune", "Fine", "Note Off", "Pan", "Volume" };
+ "Res Structure", "Tune", "Fine", "Note Off", "Pan", "Volume",
+ "Mono", "Res Mix" };
return (i >= 0 && i < kNumParams) ? std::string(nm[i]) : std::string{};
}
float pluginParamGet(int32_t i) const override {
@@ -117,12 +134,52 @@ public:
return s;
}
+ int32_t activeVoiceCount() const override { return activeVoices_.load(std::memory_order_relaxed); }
+
+ // Telemetry for the editor + MCP (message thread). Layout:
+ // [0] sounding voices · [1] mono (0/1) · [2] last struck fundamental in Hz (0 = none
+ // yet) · [3] output peak (linear, held ~300 ms) · then per bank (1, 2) three rows of
+ // kModes: the partial's frequency ratio to the note (bank Tune included), its struck
+ // amplitude, and its ring time in seconds (e-folding) — what buildBank freezes.
+ static constexpr int kScopeHead = 4;
+ static constexpr int kScopeLen = kScopeHead + 2 * 3 * kModes;
+ int32_t scopeRead(float* out, int32_t maxN) const override {
+ if (!out || maxN <= 0) return 0;
+ float buf[kScopeLen];
+ buf[0] = static_cast<float>(activeVoices_.load(std::memory_order_relaxed));
+ buf[1] = get(Mono) >= 0.5f ? 1.0f : 0.0f;
+ buf[2] = lastF0_.load(std::memory_order_relaxed);
+ buf[3] = outPeak_.load(std::memory_order_relaxed);
+ for (int b = 0; b < 2; ++b) {
+ const Param base = b == 0 ? R1Type : R2Type;
+ const Param tune = b == 0 ? R1Tune : R2Tune;
+ const double tr = std::exp2((get(tune) - 0.5) * 4.0);
+ const int type = typeOf(base);
+ float* row = buf + kScopeHead + b * 3 * kModes;
+ for (int m = 0; m < kModes; ++m) {
+ const Mode md = modeOf(type, m, get(Param(base + 1)), get(Param(base + 2)), get(Param(base + 3)),
+ get(Param(base + 4)), get(Param(base + 5)), get(Param(base + 6)));
+ row[m] = static_cast<float>(md.ratio * tr);
+ row[kModes + m] = static_cast<float>(md.amp);
+ row[2 * kModes + m] = static_cast<float>(md.tau);
+ }
+ }
+ const int n = std::min<int>(maxN, kScopeLen);
+ std::memcpy(out, buf, n * sizeof(float));
+ return n;
+ }
+
// ---- note events ------------------------------------------------------
void noteOn(int32_t pitch, float velocity) override {
+ // Mono: whatever is sounding is choked (a short fade, so the cut doesn't click)
+ // and the new strike takes a fresh voice — a struck body can't glide.
+ if (get(Mono) >= 0.5f)
+ for (auto& o : voices_) if (o.active) o.choke = true;
Voice* v = findFreeVoice();
const double tuneSemis = (get(Tune) - 0.5f) * 48.0 + (get(Fine) - 0.5f) * 2.0; // ±24 st + ±1 st fine
const double f0 = 440.0 * std::pow(2.0, (pitch - 69 + tuneSemis) / 12.0);
- v->active = true; v->released = false;
+ lastF0_.store(static_cast<float>(f0), std::memory_order_relaxed);
+ v->active = true; v->released = false; v->choke = false;
v->pitch = pitch; v->vel = std::clamp(velocity, 0.0f, 1.0f);
v->peak = v->vel;
v->relEnv = 1.0f;
@@ -161,6 +218,12 @@ public:
const float nS = get(NoiseS);
const bool r2on = get(R2On) >= 0.5f;
const bool serial = get(Structure) < 0.5f; // 0 = 1>2 (serial), 1 = 1+2 (parallel)
+ // Res Mix: an equal-gain balance — both banks at full level in the middle (the plain
+ // sum), one fading out toward either end. In 1>2 bank 2 carries a make-up gain.
+ const float mix = get(ResMix);
+ const float g1 = std::min(1.0f, 2.0f * (1.0f - mix)), g2 = std::min(1.0f, 2.0f * mix);
+ const float chokeCoef = static_cast<float>(std::exp(-1.0 / (0.004 * sampleRate_)));
+ float peak = 0.0f;
const float relCoef = static_cast<float>(std::exp(-1.0 / (expMap(1.0 - get(NoteOff), 0.006, 4.0) * sampleRate_)));
const float volume = get(Volume);
const float pan = (get(Pan) - 0.5f) * 2.0f;
@@ -194,12 +257,13 @@ public:
float o1 = bank(v.r1, exc);
float wet;
if (r2on) {
- float o2 = bank(v.r2, serial ? o1 : exc);
- wet = serial ? o2 : (o1 + o2);
+ float o2 = serial ? bankSerial(v.r2, o1) : bank(v.r2, exc);
+ wet = g1 * o1 + g2 * (serial ? kSerialMakeup : 1.0f) * o2;
} else {
wet = o1;
}
- if (v.released) { wet *= v.relEnv; v.relEnv *= relCoef; }
+ if (v.choke) { wet *= v.relEnv; v.relEnv *= chokeCoef; if (v.relEnv < 1.0e-4f) { v.active = false; continue; } }
+ else if (v.released) { wet *= v.relEnv; v.relEnv *= relCoef; }
const float s = wet * v.vel;
mono += s;
@@ -209,25 +273,35 @@ public:
const float o = mono * volume * 0.4f;
out[i * 2] += o * gl;
out[i * 2 + 1] += o * gr;
+ peak = std::max(peak, std::fabs(o));
}
+ int n = 0;
+ for (const auto& v : voices_) if (v.active && !v.choke) ++n;
+ activeVoices_.store(n, std::memory_order_relaxed);
+ // Peak hold for the telemetry: ~300 ms fall.
+ const float fall = static_cast<float>(std::exp(-static_cast<double>(frames) / (0.3 * sampleRate_)));
+ outPeak_.store(std::max(peak, outPeak_.load(std::memory_order_relaxed) * fall), std::memory_order_relaxed);
}
private:
static constexpr double kPi = 3.14159265358979323846;
static constexpr double kTwoPi = 6.283185307179586;
- static constexpr int kVoices = 8;
- static constexpr int kModes = 16;
+ static constexpr float kSerialMakeup = 4.0f; // +12 dB on bank 2 in 1>2
enum class Stage { Attack, Decay, Sustain, Release, Off };
// One modal resonator bank: kModes tuned 2-pole resonators (frozen coefficients).
+ // bs = the input gain when the bank is fed by resonator 1 (1→2): a struck resonator's
+ // gain is ~amp for an impulse, but a sustained sine on its resonance rings it up by
+ // ~τ·sr — so in series each mode is normalised to a peak gain of ~amp (a resonant
+ // band-pass), and bank 2 colours bank 1 instead of exploding.
struct Bank {
- double a1[kModes] = {}, a2[kModes] = {}, b0[kModes] = {}; // 2R cos w, R², input gain
+ double a1[kModes] = {}, a2[kModes] = {}, b0[kModes] = {}, bs[kModes] = {}; // 2R cos w, R², input gains
double y1[kModes] = {}, y2[kModes] = {};
};
struct Voice {
- bool active = false, released = false;
+ bool active = false, released = false, choke = false;
int32_t pitch = 0;
float vel = 0.0f, peak = 0.0f, relEnv = 1.0f;
// Mallet.
@@ -283,6 +357,16 @@ private:
return static_cast<float>(acc);
}
+ static float bankSerial(Bank& b, float x) {
+ double acc = 0.0;
+ for (int m = 0; m < kModes; ++m) {
+ const double y = b.bs[m] * x + b.a1[m] * b.y1[m] - b.a2[m] * b.y2[m];
+ b.y2[m] = b.y1[m]; b.y1[m] = y;
+ acc += y;
+ }
+ return static_cast<float>(acc);
+ }
+
// Partial ratios for a material Type (mode 0 = the fundamental = 1.0).
static double ratioOf(int type, int m) {
// Free-free beam (bar): (β_m/β_0)², β ≈ (m+0.5)π with exact low modes.
@@ -307,30 +391,41 @@ private:
}
}
- // Freeze a bank's coefficients from a fundamental + Type/Decay/Material/Bright/Inharm/Ratio/Hit.
- void buildBank(Bank& b, double f0, int type, float decay, float material, float bright,
- float inharm, float ratioP, float hit) const {
+ // One mode of a bank from Type + Decay/Material/Bright/Inharm/Ratio/Hit: its frequency
+ // ratio to the fundamental (before the bank's Tune), struck amplitude and ring time.
+ struct Mode { double ratio, amp, tau; };
+ static Mode modeOf(int type, int m, float decay, float material, float bright,
+ float inharm, float ratioP, float hit) {
const double baseDecay = expMap(decay, 0.04, 18.0); // ring time (s)
const double matRoll = expMap(material, 1.0, 0.45); // high-mode decay scaling (metal .. damped)
const double brightRoll = expMap(bright, 0.55, 1.0); // high-mode amplitude tilt
const double ratioExp = 0.5 + ratioP; // partial-spacing exponent (0.5 .. 1.5)
const double stretch = inharm * 0.04; // inharmonic stretch per mode
+ Mode md;
+ md.ratio = std::pow(ratioOf(type, m) * (1.0 + stretch * m), ratioExp);
+ md.tau = std::max(0.01, baseDecay * std::pow(matRoll, m));
+ // Amplitude: bright tilt × strike-position comb (mode excited ∝ |sin|).
+ md.amp = std::pow(brightRoll, m) * (0.3 + 0.7 * std::fabs(std::sin((m + 1) * kPi * (0.02 + 0.96 * hit))));
+ return md;
+ }
+
+ // Freeze a bank's coefficients from a fundamental + Type/Decay/Material/Bright/Inharm/Ratio/Hit.
+ void buildBank(Bank& b, double f0, int type, float decay, float material, float bright,
+ float inharm, float ratioP, float hit) const {
const double nyq = sampleRate_ * 0.49;
for (int m = 0; m < kModes; ++m) {
- double r = ratioOf(type, m) * (1.0 + stretch * m);
- r = std::pow(r, ratioExp);
- const double f = f0 * r;
- if (f >= nyq || f <= 0.0) { b.a1[m] = b.a2[m] = b.b0[m] = 0.0; b.y1[m] = b.y2[m] = 0.0; continue; }
- const double tau = std::max(0.01, baseDecay * std::pow(matRoll, m));
- const double R = std::exp(-1.0 / (tau * sampleRate_));
+ const Mode md = modeOf(type, m, decay, material, bright, inharm, ratioP, hit);
+ const double f = f0 * md.ratio;
+ if (f >= nyq || f <= 0.0) { b.a1[m] = b.a2[m] = b.b0[m] = b.bs[m] = 0.0; b.y1[m] = b.y2[m] = 0.0; continue; }
+ const double R = std::exp(-1.0 / (md.tau * sampleRate_));
const double w = kTwoPi * f / sampleRate_;
b.a1[m] = 2.0 * R * std::cos(w);
b.a2[m] = R * R;
- // Amplitude: bright tilt × strike-position comb (mode excited ∝ |sin|). The
- // sin(w) input gain normalises the resonator so its struck peak ≈ amp,
+ // The sin(w) input gain normalises the resonator so its struck peak ≈ amp,
// independent of the (near-1) decay radius.
- const double amp = std::pow(brightRoll, m) * (0.3 + 0.7 * std::fabs(std::sin((m + 1) * kPi * (0.02 + 0.96 * hit))));
- b.b0[m] = amp * std::sin(w);
+ b.b0[m] = md.amp * std::sin(w);
+ // Peak gain on resonance ≈ b / ((1 − R)·2 sin w) → normalise to amp.
+ b.bs[m] = md.amp * (1.0 - R) * 2.0 * std::sin(w);
b.y1[m] = b.y2[m] = 0.0;
}
}
@@ -345,6 +440,8 @@ private:
double sampleRate_ = 44100.0;
uint32_t rng_ = 0x2545F491u;
std::atomic<float> pn_[kNumParams];
+ std::atomic<int32_t> activeVoices_{0};
+ std::atomic<float> lastF0_{0.0f}, outPeak_{0.0f};
};
} // namespace nota
diff --git a/src/native/nota.engine/src/Utility.h b/src/native/nota.engine/src/Utility.h
index 01217655..b1e3aaad 100644
--- a/src/native/nota.engine/src/Utility.h
+++ b/src/native/nota.engine/src/Utility.h
@@ -1,68 +1,217 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
-// Built-in Utility (device kind 4) — reworked to the "show the thing you can't
-// hear" mockup (design 3j). A stereo utility: output gain, L/R balance, mid/side
-// stereo width, channel mode (Stereo/Left/Right/Swap), mono-below (bass mono up
-// to a cutoff), mute and per-channel phase invert. It also packs live telemetry
-// through scopeRead — IN/OUT peaks, an inter-channel correlation coefficient and
-// a decimated ring of output L/R pairs for a vectorscope — so width and phase,
-// whose effect is hard to hear on headphones, become visible.
+// Built-in Nota Utility (device kind 4) — routing, stereo field and levels (the "Nota
+// Utility" mockup, 700 × 260). A stereo utility: channel mode (Stereo / Left / Right /
+// Swap), mid/side width with two laws (L/R: the side is scaled, wider gets louder; M/S:
+// mid and side are traded, 200 % = side only), mono below a cutoff at 6 / 12 / 24 dB/oct,
+// L/R balance, per-channel phase invert, mute, output gain; level matching (a one-shot
+// Gain match and a continuous Auto Match, to the input's level or to a Target in the
+// meter's unit — LUFS-S, sample peak or RMS) and a zero-latency true-peak safety limiter.
//
-// A core Device (JUCE-free); params are atomic / lock-free. Allocation-free after
-// construction.
+// in ─▶ meters ─▶ channel mode ─▶ M/S ─▶ mono below (side HP) ─▶ width ─▶ L/R
+// ─▶ balance ─▶ phase ─▶ gain · auto match · mute ─▶ TP limiter ─▶ meters ─▶ out
+//
+// Header-only, allocation-free after setSampleRate. Params keep real units (Gain dB,
+// Balance −1..1, Width %, Mono Freq Hz, choices as indices, Target / TP Ceiling dB); the
+// first nine are the original layout with their original defaults, the rest are appended
+// and default to the old sound, so older projects and presets load unchanged.
+//
+// Telemetry (scopeRead): kTele live values; kHist-point level histories (in / out ×
+// LUFS-S / peak / RMS, 100 ms apart, oldest first); kBands per-band readings of the output
+// (pan, width share, correlation, level, the configured width) from an FFT over the last
+// second; the configured width over frequency on a kResp-point log grid. A read shorter
+// than kBandAt skips the FFT. deviceText: 0 status line, 1 live reading, 2 parameter guide.
+// deviceAction: 0 gain match, 1 reset the meters (histories, holds, the auto-match ride).
#pragma once
#include "Device.h"
+#include "signalsmith-linear/fft.h"
+
#include <algorithm>
#include <array>
#include <atomic>
+#include <chrono>
#include <cmath>
+#include <complex>
#include <cstdint>
+#include <cstdio>
+#include <mutex>
+#include <string>
+#include <vector>
namespace nota {
class Utility : public Device {
public:
- enum { Gain = 0, Balance, Width, ChannelMode, MonoFreq, MonoBelow, Mute, InvertL, InvertR, kNumParams };
+ // Param layout — order is the persisted/automation layout. APPEND ONLY.
+ enum { Gain = 0, Balance, Width, ChannelMode, MonoFreq, MonoBelow, Mute, InvertL, InvertR,
+ WidthMode, // 0 L/R (side × width), 1 M/S (mid ↔ side balance; 200 % = side only)
+ MonoSlope, // 0 6 dB/oct (the original one-pole), 1 12, 2 24
+ AutoMatch, // the output rides to the reference (the input's level or Target)
+ MatchTo, // 0 input, 1 Target
+ Target, // −36..0, in the Meter's unit (LUFS / dBFS peak / dBFS RMS)
+ Meter, // 0 LUFS-S, 1 Peak, 2 RMS
+ TpLimit, // true-peak safety limiter at TP Ceiling
+ TpCeiling, // −6..0 dBTP
+ kNumParams };
- // Packed scope telemetry (scopeRead): IN/OUT linear peaks (L/R), the output
- // correlation (-1..+1), then kScopePairs decimated output (L,R) pairs.
- enum { S_InL = 0, S_InR, S_OutL, S_OutR, S_Corr, kMeters };
- static constexpr int kScopePairs = 48;
- static constexpr int kScope = kMeters + kScopePairs * 2;
+ // Telemetry slots (scopeRead). Levels in dB (−120 = silence).
+ enum {
+ S_InPk = 0, // input peak (decaying ~300 ms), linear
+ S_OutPk, // output peak (decaying), linear
+ S_Cpu, // share of real time spent in process()
+ S_SampleRate,
+ S_Corr, // output L/R correlation −1..+1
+ S_InLufs, // short-term loudness (3 s), LUFS
+ S_OutLufs,
+ S_InRms, // RMS over 300 ms, dBFS
+ S_OutRms,
+ S_InPeak, // sample peak held over 1 s, dBFS
+ S_OutPeak,
+ S_TruePeak, // output true peak held over 3 s, dBTP
+ S_InMom, // momentary loudness (400 ms), LUFS
+ S_OutMom,
+ S_AutoDb, // the auto-match gain now, dB
+ S_LimDb, // limiter gain reduction in the last 100 ms, dB (≥ 0)
+ S_InLevel, // input / output in the Meter's unit (LUFS-S / 1 s peak / 300 ms RMS)
+ S_OutLevel,
+ S_InMatch, // input / output over 3 s in the Meter's unit (what Gain match uses)
+ S_OutMatch,
+ S_EnergyBal, // output L vs R energy, dB (+ = left louder)
+ S_WidthNow, // measured output width: side / mid amplitude, %
+ S_EffWidth, // configured width above the mono cutoff, % (the width law applied)
+ S_MonoHz, // the mono cutoff (0 when Mono Below is off)
+ S_Meter,
+ S_HistN,
+ S_HistSec,
+ S_Bands,
+ S_BandLo,
+ S_BandHi,
+ S_RespN,
+ S_RespLo,
+ S_RespHi,
+ S_Analysed, // 1 when the band block below is filled
+ S_InTruePeak, // input sample peak over 3 s, dBFS (the headroom reference)
+ S_OutPreMatch, // the output over 3 s before Gain and the auto-match ride, in the Meter's unit
+ S_Reserved1, S_Reserved2, S_Reserved3, S_Reserved4,
+ kTele = 48
+ };
+ static constexpr int kHist = 80; // 8 s of 100 ms blocks
+ static constexpr int kHistSeries = 6;
+ enum { H_InLufs = 0, H_OutLufs, H_InPeak, H_OutPeak, H_InRms, H_OutRms };
+ static constexpr int kBands = 32;
+ static constexpr int kBandSeries = 5;
+ enum { B_Pan = 0, // −1 left … +1 right: where the band's energy sits
+ B_Width, // side share sqrt(S² / (M² + S²)): 0 mono, .71 uncorrelated, 1 anti-phase
+ B_Corr, // L/R correlation in the band
+ B_Level, // band level, dB re full scale
+ B_Set }; // the configured width at the band centre, %
+ static constexpr int kResp = 96;
+ static constexpr double kBandLo = 30.0, kBandHi = 16000.0, kRespLo = 20.0, kRespHi = 20000.0;
+ static constexpr int kHistAt = kTele;
+ static constexpr int kBandAt = kHistAt + kHistSeries * kHist;
+ static constexpr int kRespAt = kBandAt + kBandSeries * kBands;
+ static constexpr int kScopeTotal = kRespAt + kResp;
+ enum { A_GainMatch = 0, A_ResetMeters = 1 }; // deviceAction ids
+
+ Utility() {
+ p_[Gain].store(0.0f); // 0 dB
+ p_[Balance].store(0.0f); // centre
+ p_[Width].store(100.0f); // 100 %
+ p_[ChannelMode].store(0.0f); // Stereo
+ p_[MonoFreq].store(120.0f); // 120 Hz
+ p_[MonoBelow].store(0.0f); // off
+ p_[Mute].store(0.0f);
+ p_[InvertL].store(0.0f);
+ p_[InvertR].store(0.0f);
+ p_[WidthMode].store(0.0f); // L/R — the original width law
+ p_[MonoSlope].store(0.0f); // 6 dB/oct — the original one-pole
+ p_[AutoMatch].store(0.0f);
+ p_[MatchTo].store(0.0f); // the input
+ p_[Target].store(-14.0f);
+ p_[Meter].store(0.0f); // LUFS-S
+ p_[TpLimit].store(0.0f);
+ p_[TpCeiling].store(-1.0f);
+ clearHistory();
+ }
void setSampleRate(double sr, int32_t /*maxBlock*/) override {
+ std::lock_guard<std::mutex> lock(mx_);
sr_ = sr > 0 ? sr : 44100.0;
- decim_ = std::max(1, (int)std::lround(sr_ / 6000.0)); // ~48 pts over ~8 ms
- lpSide_ = 0.0f;
+ computeKWeighting();
+ blockLen_ = std::max(1, (int)std::lround(sr_ * 0.1));
+ fftN_ = sr_ > 50000.0 ? 8192 : 4096;
+ size_t ring = 1;
+ while (ring < (size_t)(sr_ * 1.1) + (size_t)fftN_) ring <<= 1;
+ ringL_.assign(ring, 0.0f); ringR_.assign(ring, 0.0f);
+ ringMask_ = (uint32_t)(ring - 1);
+ fft_.resize((size_t)fftN_);
+ win_.assign((size_t)fftN_, 0.0f);
+ tl_.assign((size_t)fftN_, 0.0f); tr_.assign((size_t)fftN_, 0.0f);
+ fl_.assign((size_t)fftN_ / 2, {}); fr_.assign((size_t)fftN_ / 2, {});
+ winSum_ = 0.0;
+ for (int i = 0; i < fftN_; ++i) {
+ win_[(size_t)i] = (float)(0.5 - 0.5 * std::cos(2.0 * kPi * i / fftN_));
+ winSum_ += win_[(size_t)i];
+ }
+ lastAnaS_ = -1.0;
+ srA_.store((float)sr_, std::memory_order_relaxed);
+ curMonoHz_ = -1.0f;
+ first_ = true;
+ resetDsp();
+ resetMeters();
+ }
+
+ void deviceAction(int32_t id, int32_t, float) override {
+ if (id == A_GainMatch) gainMatch();
+ else if (id == A_ResetMeters) resetReq_.store(true, std::memory_order_relaxed);
}
void process(float* buf, int32_t frames) override {
- const int mode = std::clamp((int)std::lround(p_[ChannelMode].load(std::memory_order_relaxed)), 0, 3);
- const bool mute = p_[Mute].load(std::memory_order_relaxed) >= 0.5f;
- const bool invL = p_[InvertL].load(std::memory_order_relaxed) >= 0.5f;
- const bool invR = p_[InvertR].load(std::memory_order_relaxed) >= 0.5f;
- const float widthF = std::clamp(p_[Width].load(std::memory_order_relaxed) / 100.0f, 0.0f, 4.0f);
- const float bal = std::clamp(p_[Balance].load(std::memory_order_relaxed), -1.0f, 1.0f);
- const float gain = mute ? 0.0f : std::pow(10.0f, p_[Gain].load(std::memory_order_relaxed) / 20.0f);
- const bool monoOn = p_[MonoBelow].load(std::memory_order_relaxed) >= 0.5f;
- const float monoHz = std::clamp(p_[MonoFreq].load(std::memory_order_relaxed), 20.0f, 2000.0f);
- const float lpCoef = 1.0f - std::exp(-2.0f * kPi * monoHz / (float)sr_);
+ const auto t0 = std::chrono::steady_clock::now();
+ if (resetReq_.exchange(false, std::memory_order_relaxed)) resetMeters();
+
+ const int mode = std::clamp((int)std::lround(get(ChannelMode)), 0, 3);
+ const bool mute = get(Mute) >= 0.5f;
+ const bool invL = get(InvertL) >= 0.5f;
+ const bool invR = get(InvertR) >= 0.5f;
+ const bool monoOn = get(MonoBelow) >= 0.5f;
+ const bool tpOn = get(TpLimit) >= 0.5f;
+ const float bal = std::clamp(get(Balance), -1.0f, 1.0f);
+ const float gainT = mute ? 0.0f : std::pow(10.0f, std::clamp(get(Gain), -24.0f, 24.0f) / 20.0f);
+ const float ceil = std::pow(10.0f, std::clamp(get(TpCeiling), -6.0f, 0.0f) / 20.0f);
+ float gm, gs;
+ widthGains(gm, gs);
// Constant-power-ish linear balance: attenuate the opposite side.
- const float gL = bal <= 0.0f ? 1.0f : 1.0f - bal;
- const float gR = bal >= 0.0f ? 1.0f : 1.0f + bal;
+ const float gLT = bal <= 0.0f ? 1.0f : 1.0f - bal;
+ const float gRT = bal >= 0.0f ? 1.0f : 1.0f + bal;
+ const float autoT = autoOn() ? std::pow(10.0f, autoDb_ / 20.0f) : 1.0f;
+ if (!autoOn()) autoDb_ = 0.0f;
+
+ const float monoHz = std::clamp(get(MonoFreq), 20.0f, 2000.0f);
+ const int slope = std::clamp((int)std::lround(get(MonoSlope)), 0, 2);
+ if (monoHz != curMonoHz_ || slope != curSlope_) setCrossover(monoHz, slope);
+
+ if (first_) { sGain_ = gainT; sGL_ = gLT; sGR_ = gRT; sGm_ = gm; sGs_ = gs; sAuto_ = autoT; first_ = false; }
+ const float sm = smCoef_, sa = autoCoef_;
+ const float rel = relCoef_;
- float inL = 0, inR = 0, outL = 0, outR = 0;
- double sLL = 0, sRR = 0, sLR = 0;
- int w = ringW_;
+ float inPk = 0, outPk = 0;
+ double sLL = 0, sRR = 0, sLR = 0, sMM = 0, sSS = 0;
+ const bool ringOk = !ringL_.empty();
+ uint32_t w = ringW_.load(std::memory_order_relaxed);
for (int32_t i = 0; i < frames; ++i) {
float l = buf[i * 2], r = buf[i * 2 + 1];
- inL = std::max(inL, std::fabs(l));
- inR = std::max(inR, std::fabs(r));
+ const float al = std::fabs(l), ar = std::fabs(r);
+ inPk = std::max(inPk, std::max(al, ar));
+ { const float kl = kweight(kIn_[0], l), kr = kweight(kIn_[1], r);
+ blkInK_ += (double)kl * kl + (double)kr * kr; }
+ blkInSq_ += (double)l * l + (double)r * r;
+ blkInPk_ = std::max(blkInPk_, std::max(al, ar));
switch (mode) { // channel mode
case 1: r = l; break; // Left → both
@@ -71,51 +220,143 @@ public:
default: break; // Stereo
}
+ sGm_ += (gm - sGm_) * sm; sGs_ += (gs - sGs_) * sm;
+ sGL_ += (gLT - sGL_) * sm; sGR_ += (gRT - sGR_) * sm;
+ sGain_ += (gainT - sGain_) * sm;
+ sAuto_ += (autoT - sAuto_) * sa;
+
float mid = 0.5f * (l + r), side = 0.5f * (l - r);
- if (monoOn) { lpSide_ += lpCoef * (side - lpSide_); side -= lpSide_; } // bass → mono
- side *= widthF;
+ if (monoOn) side = crossover(side); // bass → mono
+ mid *= sGm_; side *= sGs_;
l = mid + side; r = mid - side;
- l *= gL; r *= gR; // balance
+ l *= sGL_; r *= sGR_; // balance
if (invL) l = -l;
if (invR) r = -r;
- l *= gain; r *= gain; // output gain / mute
+ const float g = sGain_ * sAuto_;
+ l *= g; r *= g; // output gain / auto match / mute
+ blkG2_ += (double)g * g;
+
+ if (tpOn) { // zero-latency true-peak safety limiter
+ const float est = std::max(isp(limH_[0], l), isp(limH_[1], r));
+ limEnv_ += (1.0f - limEnv_) * rel;
+ if (est * limEnv_ > ceil) limEnv_ = ceil / est;
+ l *= limEnv_; r *= limEnv_;
+ l = std::clamp(l, -ceil, ceil); r = std::clamp(r, -ceil, ceil);
+ blkLimMin_ = std::min(blkLimMin_, limEnv_);
+ } else {
+ limEnv_ = 1.0f;
+ }
buf[i * 2] = l; buf[i * 2 + 1] = r;
- outL = std::max(outL, std::fabs(l));
- outR = std::max(outR, std::fabs(r));
+ const float ol = std::fabs(l), orr = std::fabs(r);
+ outPk = std::max(outPk, std::max(ol, orr));
sLL += (double)l * l; sRR += (double)r * r; sLR += (double)l * r;
+ const double m = 0.5 * ((double)l + r), s = 0.5 * ((double)l - r);
+ sMM += m * m; sSS += s * s;
+ { const float kl = kweight(kOut_[0], l), kr = kweight(kOut_[1], r);
+ blkOutK_ += (double)kl * kl + (double)kr * kr; }
+ blkOutSq_ += (double)l * l + (double)r * r;
+ blkOutPk_ = std::max(blkOutPk_, std::max(ol, orr));
+ blkOutTp_ = std::max(blkOutTp_, std::max(truePeak(tpM_[0], l), truePeak(tpM_[1], r)));
- if (--decimCnt_ <= 0) { // vectorscope capture (decimated)
- decimCnt_ = decim_;
- ring_[w * 2] = l; ring_[w * 2 + 1] = r;
- w = (w + 1) % kScopePairs;
- }
+ if (ringOk) { ringL_[w & ringMask_] = l; ringR_[w & ringMask_] = r; }
+ ++w;
+ if (++blkCount_ >= blockLen_) endBlock();
}
- ringW_ = w; ringWA_.store(w, std::memory_order_release);
+ ringW_.store(w, std::memory_order_release);
- // Correlation of the output; hold the last value while silent.
+ // Correlation, balance and width of the output; hold the last values while silent.
if (sLL > 1e-9 && sRR > 1e-9) {
- float c = std::clamp((float)(sLR / std::sqrt(sLL * sRR)), -1.0f, 1.0f);
+ const float c = std::clamp((float)(sLR / std::sqrt(sLL * sRR)), -1.0f, 1.0f);
corr_.store(corr_.load(std::memory_order_relaxed) * 0.8f + c * 0.2f, std::memory_order_relaxed);
}
- inL_.store(inL, std::memory_order_relaxed); inR_.store(inR, std::memory_order_relaxed);
- outL_.store(outL, std::memory_order_relaxed); outR_.store(outR, std::memory_order_relaxed);
+ if (sLL + sRR > 1e-9) {
+ const float a = frames > 0 ? 1.0f - std::exp(-(float)frames / (float)(0.5 * sr_)) : 0.0f;
+ emaL_ += a * ((float)sLL / std::max(1, frames) - emaL_);
+ emaR_ += a * ((float)sRR / std::max(1, frames) - emaR_);
+ emaM_ += a * ((float)sMM / std::max(1, frames) - emaM_);
+ emaS_ += a * ((float)sSS / std::max(1, frames) - emaS_);
+ balDbA_.store(emaL_ > 1e-12f && emaR_ > 1e-12f ? 10.0f * std::log10(emaL_ / emaR_) : 0.0f, std::memory_order_relaxed);
+ widthA_.store(emaM_ > 1e-12f ? 100.0f * std::sqrt(emaS_ / emaM_) : (emaS_ > 1e-12f ? 400.0f : 0.0f), std::memory_order_relaxed);
+ }
+ const float fall = std::exp(-(float)frames / (float)(0.3 * sr_)); // ~300 ms peak fall
+ inPkA_.store(std::max(inPk, inPkA_.load(std::memory_order_relaxed) * fall), std::memory_order_relaxed);
+ outPkA_.store(std::max(outPk, outPkA_.load(std::memory_order_relaxed) * fall), std::memory_order_relaxed);
+ if (frames > 0) {
+ const double el = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
+ cpuS_ = cpuS_ * 0.9 + (el / (frames / sr_)) * 0.1;
+ cpuA_.store((float)cpuS_, std::memory_order_relaxed);
+ }
}
+ // Telemetry, the histories, the bands and the configured width (see the header note).
+ // Writes as much of that layout as fits in maxSamples. Torn reads are fine.
int32_t scopeRead(float* out, int32_t maxSamples) const override {
- if (!out || maxSamples < kScope) return 0;
- out[S_InL] = inL_.load(std::memory_order_relaxed);
- out[S_InR] = inR_.load(std::memory_order_relaxed);
- out[S_OutL] = outL_.load(std::memory_order_relaxed);
- out[S_OutR] = outR_.load(std::memory_order_relaxed);
- out[S_Corr] = corr_.load(std::memory_order_relaxed);
- int w = ringWA_.load(std::memory_order_acquire); // oldest sample
- for (int k = 0; k < kScopePairs; ++k) {
- int idx = (w + k) % kScopePairs;
- out[kMeters + k * 2] = ring_[idx * 2];
- out[kMeters + k * 2 + 1] = ring_[idx * 2 + 1];
+ if (!out || maxSamples <= 0) return 0;
+ float t[kTele] = {};
+ t[S_InPk] = inPkA_.load(std::memory_order_relaxed);
+ t[S_OutPk] = outPkA_.load(std::memory_order_relaxed);
+ t[S_Cpu] = cpuA_.load(std::memory_order_relaxed);
+ t[S_SampleRate] = srA_.load(std::memory_order_relaxed);
+ t[S_Corr] = corr_.load(std::memory_order_relaxed);
+ t[S_InLufs] = inLufsA_.load(std::memory_order_relaxed);
+ t[S_OutLufs] = outLufsA_.load(std::memory_order_relaxed);
+ t[S_InRms] = inRmsA_.load(std::memory_order_relaxed);
+ t[S_OutRms] = outRmsA_.load(std::memory_order_relaxed);
+ t[S_InPeak] = inPeak1A_.load(std::memory_order_relaxed);
+ t[S_OutPeak] = outPeak1A_.load(std::memory_order_relaxed);
+ t[S_TruePeak] = truePk3A_.load(std::memory_order_relaxed);
+ t[S_InMom] = inMomA_.load(std::memory_order_relaxed);
+ t[S_OutMom] = outMomA_.load(std::memory_order_relaxed);
+ t[S_AutoDb] = autoOn() ? autoDbA_.load(std::memory_order_relaxed) : 0.0f;
+ t[S_LimDb] = get(TpLimit) >= 0.5f ? limDbA_.load(std::memory_order_relaxed) : 0.0f;
+ const int meter = meterIdx();
+ t[S_InLevel] = levelIn(meter);
+ t[S_OutLevel] = levelOut(meter);
+ t[S_InMatch] = matchIn(meter);
+ t[S_OutMatch] = matchOut(meter);
+ t[S_EnergyBal] = balDbA_.load(std::memory_order_relaxed);
+ t[S_WidthNow] = widthA_.load(std::memory_order_relaxed);
+ t[S_EffWidth] = (float)effWidth(1e9);
+ t[S_MonoHz] = get(MonoBelow) >= 0.5f ? std::clamp(get(MonoFreq), 20.0f, 2000.0f) : 0.0f;
+ t[S_Meter] = (float)meter;
+ t[S_HistN] = (float)kHist;
+ t[S_HistSec] = kHist * 0.1f;
+ t[S_Bands] = (float)kBands;
+ t[S_BandLo] = (float)kBandLo;
+ t[S_BandHi] = (float)kBandHi;
+ t[S_RespN] = (float)kResp;
+ t[S_RespLo] = (float)kRespLo;
+ t[S_RespHi] = (float)kRespHi;
+ t[S_InTruePeak] = inPeak3A_.load(std::memory_order_relaxed);
+ t[S_OutPreMatch] = matchPre(meter);
+
+ const bool bands = maxSamples >= kBandAt + kBandSeries * kBands;
+ if (bands) t[S_Analysed] = analyse() ? 1.0f : 0.0f;
+
+ int32_t n = 0;
+ for (int k = 0; k < kTele && n < maxSamples; ++k) out[n++] = t[k];
+ const int hw = histW_.load(std::memory_order_acquire);
+ for (int s = 0; s < kHistSeries; ++s)
+ for (int k = 0; k < kHist && n < maxSamples; ++k) out[n++] = hist_[s][(size_t)((hw + k) % kHist)];
+ if (!bands) return n;
+ {
+ std::lock_guard<std::mutex> lock(mx_);
+ for (int s = 0; s < kBandSeries; ++s)
+ for (int b = 0; b < kBands && n < maxSamples; ++b) {
+ float v = 0.0f;
+ switch (s) {
+ case B_Pan: v = bandPan_[b]; break;
+ case B_Width: v = bandWidth_[b]; break;
+ case B_Corr: v = bandCorr_[b]; break;
+ case B_Level: v = bandLevel_[b]; break;
+ default: v = (float)effWidth(bandHz(b)); break;
+ }
+ out[n++] = v;
+ }
}
- return kScope;
+ for (int k = 0; k < kResp && n < maxSamples; ++k) out[n++] = (float)effWidth(respHz(k));
+ return n;
}
const char* displayName() const override { return "Nota Utility"; }
@@ -123,51 +364,453 @@ public:
int32_t paramCount() const override { return kNumParams; }
const char* paramName(int32_t i) const override {
- static const char* nm[] = { "Gain", "Balance", "Width", "Channel Mode",
- "Mono Freq", "Mono Below", "Mute", "Invert L", "Invert R" };
+ static const char* nm[kNumParams] = { "Gain", "Balance", "Width", "Channel Mode",
+ "Mono Freq", "Mono Below", "Mute", "Invert L", "Invert R",
+ "Width Mode", "Mono Slope", "Auto Match", "Match To", "Target", "Meter",
+ "TP Limit", "TP Ceiling" };
return (i >= 0 && i < kNumParams) ? nm[i] : "";
}
float paramMin(int32_t i) const override {
- switch (i) { case Gain: return -24.0f; case Balance: return -1.0f; case MonoFreq: return 20.0f; default: return 0.0f; }
+ switch (i) {
+ case Gain: return -24.0f; case Balance: return -1.0f; case MonoFreq: return 20.0f;
+ case Target: return -36.0f; case TpCeiling: return -6.0f;
+ default: return 0.0f;
+ }
}
float paramMax(int32_t i) const override {
switch (i) {
case Gain: return 24.0f; case Balance: return 1.0f; case Width: return 400.0f;
- case ChannelMode: return 3.0f; case MonoFreq: return 2000.0f; default: return 1.0f;
+ case ChannelMode: return 3.0f; case MonoFreq: return 2000.0f;
+ case MonoSlope: case Meter: return 2.0f;
+ case Target: case TpCeiling: return 0.0f;
+ default: return 1.0f;
}
}
float getParam(int32_t i) const override {
return (i >= 0 && i < kNumParams) ? p_[i].load(std::memory_order_relaxed) : 0.0f;
}
void setParam(int32_t i, float v) override {
- if (i >= 0 && i < kNumParams) p_[i].store(v, std::memory_order_relaxed);
+ if (i >= 0 && i < kNumParams && std::isfinite(v)) p_[i].store(std::clamp(v, paramMin(i), paramMax(i)), std::memory_order_relaxed);
}
- Utility() {
- p_[Gain].store(0.0f); // 0 dB
- p_[Balance].store(0.0f); // centre
- p_[Width].store(100.0f); // 100 %
- p_[ChannelMode].store(0.0f); // Stereo
- p_[MonoFreq].store(120.0f); // 120 Hz
- p_[MonoBelow].store(0.0f); // off
- p_[Mute].store(0.0f);
- p_[InvertL].store(0.0f);
- p_[InvertR].store(0.0f);
+ // 0 — a one-line status; 1 — the live reading; 2 — a guide to the parameter values.
+ std::string deviceText(int32_t id) const override {
+ char b[768];
+ static const char* kMode[4] = { "Stereo", "Left", "Right", "Swap" };
+ static const char* kMeterName[3] = { "LUFS-S", "Peak", "RMS" };
+ static const char* kUnit[3] = { "LUFS", "dBFS", "dBFS" };
+ const int meter = meterIdx();
+ if (id == 0) {
+ std::string s = kMode[std::clamp((int)std::lround(get(ChannelMode)), 0, 3)];
+ std::snprintf(b, sizeof b, " - %s width %.0f %%", get(WidthMode) >= 0.5f ? "M/S" : "L/R", get(Width));
+ s += b;
+ if (get(MonoBelow) >= 0.5f) {
+ static const int kSl[3] = { 6, 12, 24 };
+ std::snprintf(b, sizeof b, " - mono below %.0f Hz (%d dB/oct)", get(MonoFreq), kSl[std::clamp((int)std::lround(get(MonoSlope)), 0, 2)]);
+ s += b;
+ }
+ const float bal = get(Balance);
+ if (std::fabs(bal) > 0.005f) { std::snprintf(b, sizeof b, " - balance %s %.0f %%", bal < 0 ? "L" : "R", std::fabs(bal) * 100.0f); s += b; }
+ if (get(InvertL) >= 0.5f) s += " - phase L inverted";
+ if (get(InvertR) >= 0.5f) s += " - phase R inverted";
+ if (get(Mute) >= 0.5f) s += " - muted";
+ std::snprintf(b, sizeof b, " - gain %+.1f dB", get(Gain)); s += b;
+ if (autoOn()) {
+ if (get(MatchTo) >= 0.5f) std::snprintf(b, sizeof b, " - auto match to %.1f %s (%s)", get(Target), kUnit[meter], kMeterName[meter]);
+ else std::snprintf(b, sizeof b, " - auto match to the input (%s)", kMeterName[meter]);
+ s += b;
+ }
+ if (get(TpLimit) >= 0.5f) { std::snprintf(b, sizeof b, " - true-peak limit %.1f dBTP", get(TpCeiling)); s += b; }
+ return s;
+ }
+ if (id == 1) {
+ float sc[kTele];
+ scopeRead(sc, kTele);
+ char balText[32];
+ if (std::fabs(sc[S_EnergyBal]) < 0.25f) std::snprintf(balText, sizeof balText, "L=R");
+ else std::snprintf(balText, sizeof balText, "%s +%.1f dB", sc[S_EnergyBal] > 0 ? "L" : "R", std::fabs(sc[S_EnergyBal]));
+ std::snprintf(b, sizeof b,
+ "in %.1f LUFS-S / %.1f dBFS peak / %.1f dBFS RMS - out %.1f LUFS-S / %.1f dBFS peak / %.1f dBFS RMS - "
+ "true peak %.1f dBTP - %s delta %+.1f dB - correlation %+.2f - width %.0f %% - balance %s - "
+ "auto match %+.1f dB - limiter %.1f dB",
+ sc[S_InLufs], sc[S_InPeak], sc[S_InRms], sc[S_OutLufs], sc[S_OutPeak], sc[S_OutRms], sc[S_TruePeak],
+ kMeterName[meter], sc[S_OutLevel] > -119.0f && sc[S_InLevel] > -119.0f ? sc[S_OutLevel] - sc[S_InLevel] : 0.0f,
+ sc[S_Corr], sc[S_WidthNow],
+ balText, sc[S_AutoDb], sc[S_LimDb]);
+ return b;
+ }
+ if (id == 2) {
+ return "Gain -24..24 dB. Balance -1 (left) .. 1 (right). Width 0..400 %, 100 = unchanged. Channel Mode: 0 Stereo, 1 Left "
+ "(left on both), 2 Right, 3 Swap. Mono Freq 20..2000 Hz, Mono Below 0/1 (the side below it is removed). Mute, "
+ "Invert L, Invert R: 0/1. Width Mode: 0 L/R (the side is scaled by Width, wider gets louder), 1 M/S (mid and side "
+ "are traded: below 100 % the side drops, above it the mid drops, 200 % = side only). Mono Slope: 0 = 6, 1 = 12, "
+ "2 = 24 dB/oct. Auto Match 0/1: the output level rides to the reference. Match To: 0 the input's level, 1 Target. "
+ "Target -36..0 in the Meter's unit. Meter: 0 LUFS-S (short-term loudness), 1 Peak (sample peak, dBFS), 2 RMS "
+ "(dBFS). TP Limit 0/1: a zero-latency true-peak safety limiter at TP Ceiling (-6..0 dBTP). Toggles: >= 0.5 = on. "
+ "device_action 0 = gain match once (Gain moves so the output matches the reference over the last 3 s), "
+ "1 = reset the meters.";
+ }
+ return {};
}
private:
- static constexpr float kPi = 3.14159265358979323846f;
+ static constexpr double kPi = 3.14159265358979323846;
+
+ float get(int i) const { return p_[i].load(std::memory_order_relaxed); }
+ bool autoOn() const { return get(AutoMatch) >= 0.5f; }
+ int meterIdx() const { return std::clamp((int)std::lround(get(Meter)), 0, 2); }
+ static float lufs(double ms) { return ms > 1e-12 ? (float)std::max(-120.0, -0.691 + 10.0 * std::log10(ms)) : -120.0f; }
+ static float dbPow(double ms) { return ms > 1e-12 ? (float)std::max(-120.0, 10.0 * std::log10(ms)) : -120.0f; }
+ static float dbLin(float lin) { return lin > 1e-6f ? std::max(-120.0f, 20.0f * std::log10(lin)) : -120.0f; }
+ static double bandHz(int b) { return kBandLo * std::pow(kBandHi / kBandLo, (b + 0.5) / kBands); }
+ static double respHz(int k) { return kRespLo * std::pow(kRespHi / kRespLo, (double)k / (kResp - 1)); }
+
+ // Mid / side gains of the width law. L/R: the side is scaled (the original law). M/S:
+ // mid and side are traded — the side drops below 100 %, the mid above it; 200 % = side only.
+ void widthGains(float& gm, float& gs) const {
+ const float w = std::clamp(get(Width) / 100.0f, 0.0f, 4.0f);
+ if (get(WidthMode) >= 0.5f) { gm = std::clamp(2.0f - w, 0.0f, 1.0f); gs = std::min(w, 1.0f); }
+ else { gm = 1.0f; gs = w; }
+ }
+ // The configured width at hz: side / mid gain ratio × the mono high-pass, in % (≤ 400).
+ double effWidth(double hz) const {
+ float gm, gs;
+ widthGains(gm, gs);
+ double ratio = gm > 1e-4f ? (double)gs / gm : (gs > 1e-4f ? 4.0 : 0.0);
+ ratio = std::min(ratio, 4.0);
+ if (get(MonoBelow) >= 0.5f) {
+ const double fc = std::clamp(get(MonoFreq), 20.0f, 2000.0f), x = hz / fc;
+ const int slope = std::clamp((int)std::lround(get(MonoSlope)), 0, 2);
+ const double h1 = x / std::sqrt(1.0 + x * x), h2 = x * x / std::sqrt(1.0 + x * x * x * x);
+ ratio *= slope == 0 ? h1 : slope == 1 ? h2 : h2 * h2;
+ }
+ return ratio * 100.0;
+ }
+
+ // Level readouts in the Meter's unit.
+ float levelIn(int m) const { return m == 0 ? inLufsA_.load(std::memory_order_relaxed) : m == 1 ? inPeak1A_.load(std::memory_order_relaxed) : inRmsA_.load(std::memory_order_relaxed); }
+ float levelOut(int m) const { return m == 0 ? outLufsA_.load(std::memory_order_relaxed) : m == 1 ? outPeak1A_.load(std::memory_order_relaxed) : outRmsA_.load(std::memory_order_relaxed); }
+ float matchIn(int m) const { return m == 0 ? inLufsA_.load(std::memory_order_relaxed) : m == 1 ? inPeak3A_.load(std::memory_order_relaxed) : inRms3A_.load(std::memory_order_relaxed); }
+ float matchOut(int m) const { return m == 0 ? outLufsA_.load(std::memory_order_relaxed) : m == 1 ? outPeak3A_.load(std::memory_order_relaxed) : outRms3A_.load(std::memory_order_relaxed); }
+ float matchPre(int m) const { return m == 0 ? preLufsA_.load(std::memory_order_relaxed) : m == 1 ? prePeak3A_.load(std::memory_order_relaxed) : preRms3A_.load(std::memory_order_relaxed); }
+
+ // One-shot gain match (message thread): Gain is set so the output — measured before Gain
+ // and the auto-match ride, so whatever Gain was over the window does not matter — meets
+ // the reference over the last 3 s. Silence (or a muted window) leaves Gain alone.
+ void gainMatch() {
+ const int m = meterIdx();
+ const float pre = matchPre(m);
+ const float ref = get(MatchTo) >= 0.5f ? get(Target) : matchIn(m);
+ if (pre <= -70.0f || ref <= -70.0f) return;
+ setParam(Gain, std::clamp(ref - pre, -24.0f, 24.0f));
+ }
+
+ // ---- mono-below crossover on the side ---------------------------------------------
+ struct Biquad {
+ float b0 = 1, b1 = 0, b2 = 0, a1 = 0, a2 = 0, z1 = 0, z2 = 0;
+ float run(float x) { const float y = b0 * x + z1; z1 = b1 * x - a1 * y + z2; z2 = b2 * x - a2 * y; return y; }
+ void clear() { z1 = z2 = 0; }
+ };
+ void setCrossover(float hz, int slope) {
+ const bool reset = slope != curSlope_;
+ curMonoHz_ = hz; curSlope_ = slope;
+ lpCoef_ = 1.0f - std::exp(-2.0f * (float)kPi * hz / (float)sr_);
+ const double w0 = 2.0 * kPi * hz / sr_, cw = std::cos(w0), al = std::sin(w0) / (2.0 * 0.70710678);
+ const double a0 = 1.0 + al;
+ for (auto* q : { &hp1_, &hp2_ }) {
+ q->b0 = (float)((1.0 + cw) / 2.0 / a0); q->b1 = (float)(-(1.0 + cw) / a0); q->b2 = q->b0;
+ q->a1 = (float)(-2.0 * cw / a0); q->a2 = (float)((1.0 - al) / a0);
+ if (reset) q->clear();
+ }
+ if (reset) lpSide_ = 0.0f;
+ }
+ float crossover(float side) {
+ switch (curSlope_) {
+ case 1: return hp1_.run(side);
+ case 2: return hp2_.run(hp1_.run(side));
+ default: lpSide_ += lpCoef_ * (side - lpSide_); return side - lpSide_;
+ }
+ }
+
+ // ---- K-weighting (BS.1770): high shelf then the 38 Hz high-pass ----------------------
+ struct KW { float z1a = 0, z1b = 0, z2a = 0, z2b = 0; };
+ float kweight(KW& s, float x) const {
+ const float y1 = kb0_[0] * x + s.z1a;
+ s.z1a = kb1_[0] * x - ka1_[0] * y1 + s.z1b;
+ s.z1b = kb2_[0] * x - ka2_[0] * y1;
+ const float y2 = kb0_[1] * y1 + s.z2a;
+ s.z2a = kb1_[1] * y1 - ka1_[1] * y2 + s.z2b;
+ s.z2b = kb2_[1] * y1 - ka2_[1] * y2;
+ return y2;
+ }
+ void computeKWeighting() {
+ { const double f0 = 1681.974450955533, G = 3.999843853973347, Q = 0.7071752369554196;
+ const double K = std::tan(kPi * f0 / sr_);
+ const double Vh = std::pow(10.0, G / 20.0), Vb = std::pow(Vh, 0.4996667741545416);
+ const double a0 = 1.0 + K / Q + K * K;
+ kb0_[0] = (float)((Vh + Vb * K / Q + K * K) / a0);
+ kb1_[0] = (float)(2.0 * (K * K - Vh) / a0);
+ kb2_[0] = (float)((Vh - Vb * K / Q + K * K) / a0);
+ ka1_[0] = (float)(2.0 * (K * K - 1.0) / a0);
+ ka2_[0] = (float)((1.0 - K / Q + K * K) / a0); }
+ { const double f0 = 38.13547087602444, Q = 0.5003270373238773;
+ const double K = std::tan(kPi * f0 / sr_);
+ const double a0 = 1.0 + K / Q + K * K;
+ ka1_[1] = (float)(2.0 * (K * K - 1.0) / a0);
+ ka2_[1] = (float)((1.0 - K / Q + K * K) / a0);
+ kb0_[1] = (float)(1.0 / a0); kb1_[1] = (float)(-2.0 / a0); kb2_[1] = (float)(1.0 / a0); }
+ }
+
+ // ---- true peak --------------------------------------------------------------------
+ // Meter: 4× Catmull-Rom between the last two samples (one sample late, fine for a meter).
+ struct Tp { float y0 = 0, y1 = 0, y2 = 0; };
+ static float catmull(float y0, float y1, float y2, float y3, float t) {
+ const float a = y1, b = 0.5f * (y2 - y0), d = 0.5f * (y3 - y1), c = y2;
+ return a + t * (b + t * ((3 * (c - a) - 2 * b - d) + t * (2 * (a - c) + b + d)));
+ }
+ static float truePeak(Tp& s, float x) {
+ float pk = std::fabs(s.y2);
+ for (int k = 1; k < 4; ++k) pk = std::max(pk, std::fabs(catmull(s.y0, s.y1, s.y2, x, k * 0.25f)));
+ s.y0 = s.y1; s.y1 = s.y2; s.y2 = x;
+ return pk;
+ }
+ // Limiter: the inter-sample peak between the previous sample and this one, with the next
+ // sample extrapolated — no look-ahead, so no latency.
+ static float isp(Tp& s, float x) {
+ const float y3 = 2.0f * x - s.y2;
+ float pk = std::fabs(x);
+ for (int k = 1; k < 4; ++k) pk = std::max(pk, std::fabs(catmull(s.y1, s.y2, x, y3, k * 0.25f)));
+ s.y0 = s.y1; s.y1 = s.y2; s.y2 = x;
+ return pk;
+ }
+
+ // ---- 100 ms blocks: loudness windows, histories and the auto-match ride --------------
+ static constexpr int kWin = 30; // 3 s of blocks
+ void endBlock() {
+ const int n = blkCount_;
+ const int at = winW_;
+ wInK_[at] = blkInK_ / n; wOutK_[at] = blkOutK_ / n;
+ wInSq_[at] = blkInSq_ / (2.0 * n); wOutSq_[at] = blkOutSq_ / (2.0 * n);
+ wInPk_[at] = blkInPk_; wOutPk_[at] = blkOutPk_; wOutTp_[at] = blkOutTp_;
+ // The output with the block's gain divided out (0 = muted: no reading).
+ const double g2 = blkG2_ / n;
+ wPreK_[at] = g2 > 1e-10 ? wOutK_[at] / g2 : 0.0;
+ wPreSq_[at] = g2 > 1e-10 ? wOutSq_[at] / g2 : 0.0;
+ wPrePk_[at] = g2 > 1e-10 ? (float)(blkOutPk_ / std::sqrt(g2)) : 0.0f;
+ winW_ = (winW_ + 1) % kWin;
+ winFill_ = std::min(winFill_ + 1, kWin);
+ const float limDb = blkLimMin_ < 1.0f ? -20.0f * std::log10(std::max(1e-6f, blkLimMin_)) : 0.0f;
+ blkInK_ = blkOutK_ = blkInSq_ = blkOutSq_ = blkG2_ = 0.0;
+ blkInPk_ = blkOutPk_ = blkOutTp_ = 0.0f;
+ blkLimMin_ = 1.0f;
+ blkCount_ = 0;
+
+ // Mean / max over the last `k` blocks.
+ auto mean = [&](const double* a, int k) { k = std::min(k, winFill_); double s = 0; for (int j = 0; j < k; ++j) s += a[(at - j + kWin) % kWin]; return k > 0 ? s / k : 0.0; };
+ auto peak = [&](const float* a, int k) { k = std::min(k, winFill_); float s = 0; for (int j = 0; j < k; ++j) s = std::max(s, a[(at - j + kWin) % kWin]); return s; };
+ const float inL = lufs(mean(wInK_, kWin)), outL = lufs(mean(wOutK_, kWin));
+ const float inM = lufs(mean(wInK_, 4)), outM = lufs(mean(wOutK_, 4));
+ const float inR = dbPow(mean(wInSq_, 3)), outR = dbPow(mean(wOutSq_, 3));
+ const float inR3 = dbPow(mean(wInSq_, kWin)), outR3 = dbPow(mean(wOutSq_, kWin));
+ const float inP1 = dbLin(peak(wInPk_, 10)), outP1 = dbLin(peak(wOutPk_, 10));
+ const float inP3 = dbLin(peak(wInPk_, kWin)), outP3 = dbLin(peak(wOutPk_, kWin));
+ inLufsA_.store(inL, std::memory_order_relaxed); outLufsA_.store(outL, std::memory_order_relaxed);
+ inMomA_.store(inM, std::memory_order_relaxed); outMomA_.store(outM, std::memory_order_relaxed);
+ inRmsA_.store(inR, std::memory_order_relaxed); outRmsA_.store(outR, std::memory_order_relaxed);
+ inRms3A_.store(inR3, std::memory_order_relaxed); outRms3A_.store(outR3, std::memory_order_relaxed);
+ inPeak1A_.store(inP1, std::memory_order_relaxed); outPeak1A_.store(outP1, std::memory_order_relaxed);
+ inPeak3A_.store(inP3, std::memory_order_relaxed); outPeak3A_.store(outP3, std::memory_order_relaxed);
+ truePk3A_.store(dbLin(peak(wOutTp_, kWin)), std::memory_order_relaxed);
+ preLufsA_.store(lufs(mean(wPreK_, kWin)), std::memory_order_relaxed);
+ preRms3A_.store(dbPow(mean(wPreSq_, kWin)), std::memory_order_relaxed);
+ prePeak3A_.store(dbLin(peak(wPrePk_, kWin)), std::memory_order_relaxed);
+ limDbA_.store(limDb, std::memory_order_relaxed);
+
+ const int hw = histW_.load(std::memory_order_relaxed);
+ hist_[H_InLufs][(size_t)hw] = inL; hist_[H_OutLufs][(size_t)hw] = outL;
+ hist_[H_InPeak][(size_t)hw] = dbLin(wInPk_[at]); hist_[H_OutPeak][(size_t)hw] = dbLin(wOutPk_[at]);
+ hist_[H_InRms][(size_t)hw] = inR; hist_[H_OutRms][(size_t)hw] = outR;
+ histW_.store((hw + 1) % kHist, std::memory_order_release);
+
+ // Auto match: ride toward the reference, measured fast (momentary / 1 s peak / 300 ms
+ // RMS) on the output before Gain and the ride, so the loop does not chase itself;
+ // silence holds; the limiter working stops it from pushing up.
+ if (autoOn()) {
+ const int m = meterIdx();
+ const float ref = get(MatchTo) >= 0.5f ? get(Target) : (m == 0 ? inM : m == 1 ? inP1 : inR);
+ const float pre = m == 0 ? lufs(mean(wPreK_, 4)) : m == 1 ? dbLin(peak(wPrePk_, 10)) : dbPow(mean(wPreSq_, 3));
+ if (ref > -70.0f && pre > -70.0f && get(Mute) < 0.5f) {
+ float want = std::clamp(ref - (pre + std::clamp(get(Gain), -24.0f, 24.0f)), -24.0f, 24.0f);
+ if (limDb > 0.5f && want > autoDb_) want = autoDb_;
+ autoDb_ += (want - autoDb_) * (1.0f - std::exp(-0.1f / 1.5f));
+ }
+ } else {
+ autoDb_ = 0.0f;
+ }
+ autoDbA_.store(autoDb_, std::memory_order_relaxed);
+ }
+
+ void clearHistory() {
+ for (auto& s : hist_) s.fill(-120.0f);
+ histW_.store(0, std::memory_order_relaxed);
+ }
+ // Audio thread (or before the device runs): meters, holds, histories, the auto-match ride.
+ void resetMeters() {
+ for (int k = 0; k < kWin; ++k) {
+ wInK_[k] = wOutK_[k] = wInSq_[k] = wOutSq_[k] = wPreK_[k] = wPreSq_[k] = 0.0;
+ wInPk_[k] = wOutPk_[k] = wOutTp_[k] = wPrePk_[k] = 0.0f;
+ }
+ winW_ = 0; winFill_ = 0;
+ blkInK_ = blkOutK_ = blkInSq_ = blkOutSq_ = blkG2_ = 0.0;
+ blkInPk_ = blkOutPk_ = blkOutTp_ = 0.0f; blkLimMin_ = 1.0f; blkCount_ = 0;
+ clearHistory();
+ for (auto* a : { &inLufsA_, &outLufsA_, &inMomA_, &outMomA_, &inRmsA_, &outRmsA_, &inRms3A_, &outRms3A_,
+ &inPeak1A_, &outPeak1A_, &inPeak3A_, &outPeak3A_, &truePk3A_, &preLufsA_, &preRms3A_, &prePeak3A_ })
+ a->store(-120.0f, std::memory_order_relaxed);
+ inPkA_.store(0.0f, std::memory_order_relaxed); outPkA_.store(0.0f, std::memory_order_relaxed);
+ limDbA_.store(0.0f, std::memory_order_relaxed);
+ autoDb_ = 0.0f; autoDbA_.store(0.0f, std::memory_order_relaxed);
+ }
+ void resetDsp() {
+ for (int c = 0; c < 2; ++c) { kIn_[c] = KW{}; kOut_[c] = KW{}; tpM_[c] = Tp{}; limH_[c] = Tp{}; }
+ hp1_.clear(); hp2_.clear(); lpSide_ = 0.0f; limEnv_ = 1.0f;
+ smCoef_ = (float)(1.0 - std::exp(-1.0 / (0.005 * sr_)));
+ autoCoef_ = (float)(1.0 - std::exp(-1.0 / (0.03 * sr_)));
+ relCoef_ = (float)(1.0 - std::exp(-1.0 / (0.08 * sr_)));
+ emaL_ = emaR_ = emaM_ = emaS_ = 0.0f;
+ }
+
+ // ---- band analysis (message thread, rate-limited) -----------------------------------
+ static double nowSeconds() {
+ return std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count();
+ }
+ // Powers of one FFT frame ending at `end` (frames written) into per-band sums.
+ void frame(uint32_t end, double (&pl)[kBands], double (&pr)[kBands], double (&pm)[kBands], double (&ps)[kBands], double (&px)[kBands]) const {
+ const int n = fftN_;
+ const uint32_t start = end - (uint32_t)n;
+ for (int i = 0; i < n; ++i) {
+ const uint32_t k = (start + (uint32_t)i) & ringMask_;
+ tl_[(size_t)i] = ringL_[k] * win_[(size_t)i];
+ tr_[(size_t)i] = ringR_[k] * win_[(size_t)i];
+ }
+ fft_.fft(tl_.data(), fl_.data());
+ fft_.fft(tr_.data(), fr_.data());
+ const double binHz = sr_ / n;
+ for (int b = 0; b < kBands; ++b) {
+ const double lo = kBandLo * std::pow(kBandHi / kBandLo, (double)b / kBands);
+ const double hi = kBandLo * std::pow(kBandHi / kBandLo, (double)(b + 1) / kBands);
+ int k0 = std::max(1, (int)std::ceil(lo / binHz)), k1 = std::min(n / 2 - 1, (int)std::ceil(hi / binHz) - 1);
+ if (k1 < k0) k0 = k1 = std::clamp((int)std::lround(bandHz(b) / binHz), 1, n / 2 - 1);
+ double sl = 0, sr = 0, smm = 0, sss = 0, sx = 0;
+ for (int k = k0; k <= k1; ++k) {
+ const std::complex<float> L = fl_[(size_t)k], R = fr_[(size_t)k];
+ sl += std::norm(L); sr += std::norm(R);
+ smm += 0.25 * std::norm(L + R); sss += 0.25 * std::norm(L - R);
+ sx += (double)L.real() * R.real() + (double)L.imag() * R.imag();
+ }
+ pl[b] += sl; pr[b] += sr; pm[b] += smm; ps[b] += sss; px[b] += sx;
+ }
+ }
+ // Refresh the band readings: a fresh average of six frames over the last second when the
+ // last analysis is stale, else a one-second EMA on the newest frame. Returns whether the
+ // readings are valid.
+ bool analyse() const {
+ std::lock_guard<std::mutex> lock(mx_);
+ if (ringL_.empty() || fftN_ <= 0) return false;
+ const double now = nowSeconds();
+ const uint32_t w = ringW_.load(std::memory_order_acquire);
+ if (lastAnaS_ >= 0 && (now - lastAnaS_ < 1.0 / 30.0 || w == lastAnaW_)) return anaValid_;
+ const bool stale = lastAnaS_ < 0 || now - lastAnaS_ > 1.2;
+ double pl[kBands] = {}, pr[kBands] = {}, pm[kBands] = {}, ps[kBands] = {}, px[kBands] = {};
+ int frames = 0;
+ if (stale) {
+ const uint32_t hop = (uint32_t)std::max(1.0, sr_ / 6.0);
+ for (int j = 0; j < 6; ++j) {
+ const uint32_t back = (uint32_t)j * hop;
+ if ((uint64_t)w < (uint64_t)back + (uint64_t)fftN_ && j > 0) break;
+ frame(w - back, pl, pr, pm, ps, px);
+ ++frames;
+ }
+ } else {
+ frame(w, pl, pr, pm, ps, px);
+ frames = 1;
+ }
+ const double inv = 1.0 / std::max(1, frames);
+ const double a = stale ? 1.0 : 1.0 - std::exp(-(now - lastAnaS_) / 1.0);
+ for (int b = 0; b < kBands; ++b) {
+ aPL_[b] += a * (pl[b] * inv - aPL_[b]); aPR_[b] += a * (pr[b] * inv - aPR_[b]);
+ aPM_[b] += a * (pm[b] * inv - aPM_[b]); aPS_[b] += a * (ps[b] * inv - aPS_[b]);
+ aPX_[b] += a * (px[b] * inv - aPX_[b]);
+ }
+ lastAnaS_ = now; lastAnaW_ = w;
+ const double ref = (winSum_ * 0.5) * (winSum_ * 0.5); // a full-scale sine → 0 dB
+ for (int b = 0; b < kBands; ++b) {
+ const double l = aPL_[b], r = aPR_[b], tot = l + r;
+ if (tot < ref * 1e-12) { bandPan_[b] = 0; bandWidth_[b] = 0; bandCorr_[b] = 1; bandLevel_[b] = -120; continue; }
+ const double al = std::sqrt(l), ar = std::sqrt(r);
+ bandPan_[b] = (float)((ar - al) / (ar + al));
+ bandWidth_[b] = (float)std::sqrt(aPS_[b] / std::max(1e-30, aPM_[b] + aPS_[b]));
+ bandCorr_[b] = l > 1e-30 && r > 1e-30 ? (float)std::clamp(aPX_[b] / std::sqrt(l * r), -1.0, 1.0) : 0.0f;
+ bandLevel_[b] = (float)std::max(-120.0, 10.0 * std::log10(0.5 * tot / ref));
+ }
+ anaValid_ = true;
+ return true;
+ }
std::atomic<float> p_[kNumParams] = {};
double sr_ = 44100.0;
- float lpSide_ = 0.0f; // mono-below one-pole state (audio thread)
- int decim_ = 8, decimCnt_ = 0;
-
- // Scope telemetry (audio thread writes, UI reads lock-free; torn reads OK).
- std::atomic<float> inL_{0}, inR_{0}, outL_{0}, outR_{0}, corr_{1.0f};
- std::array<float, kScopePairs * 2> ring_{};
- int ringW_ = 0; // audio-thread write cursor
- std::atomic<int> ringWA_{0}; // published cursor for the UI
+
+ // Audio-thread state.
+ bool first_ = true;
+ float sGain_ = 1, sGL_ = 1, sGR_ = 1, sGm_ = 1, sGs_ = 1, sAuto_ = 1;
+ float smCoef_ = 0.004f, autoCoef_ = 0.0008f, relCoef_ = 0.0003f;
+ float curMonoHz_ = -1.0f; int curSlope_ = -1;
+ float lpSide_ = 0.0f, lpCoef_ = 0.0f;
+ Biquad hp1_, hp2_;
+ float kb0_[2] = {}, kb1_[2] = {}, kb2_[2] = {}, ka1_[2] = {}, ka2_[2] = {};
+ KW kIn_[2], kOut_[2];
+ Tp tpM_[2], limH_[2];
+ float limEnv_ = 1.0f;
+ float autoDb_ = 0.0f;
+ float emaL_ = 0, emaR_ = 0, emaM_ = 0, emaS_ = 0;
+ int blockLen_ = 4410, blkCount_ = 0;
+ double blkInK_ = 0, blkOutK_ = 0, blkInSq_ = 0, blkOutSq_ = 0, blkG2_ = 0;
+ float blkInPk_ = 0, blkOutPk_ = 0, blkOutTp_ = 0, blkLimMin_ = 1.0f;
+ double wInK_[kWin] = {}, wOutK_[kWin] = {}, wInSq_[kWin] = {}, wOutSq_[kWin] = {};
+ float wInPk_[kWin] = {}, wOutPk_[kWin] = {}, wOutTp_[kWin] = {};
+ double wPreK_[kWin] = {}, wPreSq_[kWin] = {}; // the output before Gain and the ride
+ float wPrePk_[kWin] = {};
+ int winW_ = 0, winFill_ = 0;
+ double cpuS_ = 0.0;
+ std::atomic<bool> resetReq_{false};
+
+ // Published telemetry (audio thread writes, UI reads lock-free; torn reads OK).
+ std::atomic<float> inPkA_{0}, outPkA_{0}, cpuA_{0}, srA_{44100.0f}, corr_{1.0f};
+ std::atomic<float> inLufsA_{-120}, outLufsA_{-120}, inMomA_{-120}, outMomA_{-120}, inRmsA_{-120}, outRmsA_{-120},
+ inRms3A_{-120}, outRms3A_{-120}, inPeak1A_{-120}, outPeak1A_{-120}, inPeak3A_{-120}, outPeak3A_{-120},
+ truePk3A_{-120}, preLufsA_{-120}, preRms3A_{-120}, prePeak3A_{-120},
+ limDbA_{0}, autoDbA_{0}, balDbA_{0}, widthA_{0};
+ std::array<std::array<float, kHist>, kHistSeries> hist_{};
+ std::atomic<int> histW_{0};
+
+ // Output ring for the band analysis (sized in setSampleRate).
+ std::vector<float> ringL_, ringR_;
+ uint32_t ringMask_ = 0;
+ std::atomic<uint32_t> ringW_{0};
+
+ // Band analysis (message thread; guarded by mx_).
+ mutable std::mutex mx_;
+ int fftN_ = 0;
+ double winSum_ = 0.0;
+ mutable signalsmith::linear::RealFFT<float> fft_;
+ std::vector<float> win_;
+ mutable std::vector<float> tl_, tr_;
+ mutable std::vector<std::complex<float>> fl_, fr_;
+ mutable double aPL_[kBands] = {}, aPR_[kBands] = {}, aPM_[kBands] = {}, aPS_[kBands] = {}, aPX_[kBands] = {};
+ mutable float bandPan_[kBands] = {}, bandWidth_[kBands] = {}, bandCorr_[kBands] = {}, bandLevel_[kBands] = {};
+ mutable double lastAnaS_ = -1.0;
+ mutable uint32_t lastAnaW_ = 0;
+ mutable bool anaValid_ = false;
};
} // namespace nota
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index cc5f6c09..484fa1b8 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -1103,7 +1103,7 @@ Console.WriteLine("-- Nota Physical --");
Check(pe.DeviceName(t, -1) == "Nota Physical", $"instrument is Nota Physical (got '{pe.DeviceName(t, -1)}')");
int pc = pe.PluginParamCount(t, -1);
- Check(pc == 36, $"Nota Physical exposes 36 params (got {pc})");
+ Check(pc == 38, $"Nota Physical exposes 38 params (got {pc})");
int dec = -1; bool idsOk = true;
for (int i = 0; i < pc; i++)
{
@@ -1115,7 +1115,7 @@ Console.WriteLine("-- Nota Physical --");
// State round-trips to another track (project save/load path).
pe.PluginParamSet(t, -1, dec, 0.77f);
var state = pe.GetPluginState(t, -1);
- Check(state.Length >= 36 * 4, $"collision state serialized ({state.Length} bytes)");
+ Check(state.Length >= 38 * 4, $"physical state serialized ({state.Length} bytes)");
int t2 = pe.AddPhysicalSynthTrack();
pe.SetPluginState(t2, -1, state);
Check(Math.Abs(pe.PluginParamGet(t2, -1, dec) - 0.77f) < 1e-4, "collision state restores params on another track");
@@ -1157,6 +1157,150 @@ Console.WriteLine("-- Nota Physical --");
pe.Seek(0.0); pe.Play(); pe.RenderOffline(nbuf, 8192); pe.StopTransport();
Check(Rms(nbuf, 8192) > 0.001f, $"noise exciter (mallet off) is audible ({Rms(nbuf, 8192):F3})");
}
+
+ // ---- v2 (redesign): Mono, Res Mix, telemetry, presets ----------------
+ double physSpb = (pe.SampleRate > 0 ? pe.SampleRate : 48000.0) * 60.0 / 120.0; // 120 BPM
+ int BF(double beats) => (int)Math.Round(beats * physSpb);
+ int PI(int tr, string id)
+ {
+ for (int i = 0; i < pe.PluginParamCount(tr, -1); i++) if (pe.PluginParamId(tr, -1, i) == id) return i;
+ return -1;
+ }
+ float[] PhysRender((string id, float v)[] ps, NotaNote[] notes, int frames)
+ {
+ using var e = new NotaEngine();
+ e.SetBpm(120); e.SetTimeSignature(4, 4);
+ int tr = e.AddPhysicalSynthTrack();
+ foreach (var (id, v) in ps)
+ for (int i = 0; i < e.PluginParamCount(tr, -1); i++) if (e.PluginParamId(tr, -1, i) == id) e.PluginParamSet(tr, -1, i, v);
+ e.AddMidiClip(tr, 0.0, 8.0);
+ e.SetClipNotes(tr, 0, notes);
+ var b = new float[frames * 2];
+ e.Seek(0.0); e.Play(); e.RenderOffline(b, frames); e.StopTransport();
+ return b;
+ }
+
+ // A project saved before v2 (36 floats) loads: old values kept, Mono off, Res Mix even.
+ {
+ int told = pe.AddPhysicalSynthTrack();
+ pe.PluginParamSet(t, -1, PI(t, "mono"), 1f); pe.PluginParamSet(t, -1, PI(t, "resmix"), 0.1f);
+ var full = pe.GetPluginState(t, -1);
+ pe.SetPluginState(told, -1, full.AsSpan(0, 36 * 4).ToArray());
+ Check(Math.Abs(pe.PluginParamGet(told, -1, dec) - 0.15f) < 1e-4, "a 36-param (pre-v2) state keeps its values");
+ Check(pe.PluginParamGet(told, -1, PI(told, "mono")) < 0.5f && Math.Abs(pe.PluginParamGet(told, -1, PI(told, "resmix")) - 0.5f) < 1e-4,
+ "a pre-v2 state loads Poly with an even Res Mix");
+ int tc = pe.DuplicateTrack(t);
+ Check(pe.PluginParamGet(tc, -1, PI(tc, "mono")) > 0.5f && Math.Abs(pe.PluginParamGet(tc, -1, PI(tc, "resmix")) - 0.1f) < 1e-4,
+ "duplicate track clones Mono and Res Mix");
+ pe.PluginParamSet(t, -1, PI(t, "mono"), 0f); pe.PluginParamSet(t, -1, PI(t, "resmix"), 0.5f);
+ }
+
+ // Res Mix in 1+2: 0 = resonator 1 alone (bit-identical to Res 2 off), 1 = resonator 2 alone.
+ {
+ var note = new[] { new NotaNote(60, 0.0, 1.0, 0.9f) };
+ var r2 = new (string, float)[] { ("r2on", 1f), ("r2type", 0.8f), ("structure", 1f) };
+ var off = PhysRender(new[] { ("r2on", 0f) }, note, 8192);
+ var only1 = PhysRender(r2.Append(("resmix", 0f)).ToArray(), note, 8192);
+ var sum = PhysRender(r2.Append(("resmix", 0.5f)).ToArray(), note, 8192);
+ var only2 = PhysRender(r2.Append(("resmix", 1f)).ToArray(), note, 8192);
+ double diff = 0; for (int i = 0; i < off.Length; i++) diff = Math.Max(diff, Math.Abs(off[i] - only1[i]));
+ Check(diff < 1e-5, $"Res Mix 0 = resonator 1 alone (max diff {diff:E1})");
+ double d12 = 0; for (int i = 0; i < off.Length; i++) d12 = Math.Max(d12, Math.Abs(only2[i] - only1[i]));
+ Check(Rms(only2, 8192) > 0.001f && d12 > 1e-3, $"Res Mix 1 = resonator 2 alone, a different sound (RMS {Rms(only2, 8192):F3})");
+ double dSum = 0; for (int i = 0; i < off.Length; i++) dSum = Math.Max(dSum, Math.Abs(sum[i] - (only1[i] + only2[i])));
+ Check(dSum < 1e-4, $"Res Mix 0.5 = both at full level, the pre-v2 sum (max diff {dSum:E1})");
+ // 1→2: resonator 1 rings resonator 2 — bounded (it used to ring up by τ·sr), and Res
+ // Mix 0 leaves resonator 1's own sound alone.
+ var ser = new (string, float)[] { ("r2on", 1f), ("r2type", 0.4f), ("r2decay", 0.9f), ("structure", 0f) };
+ var serial = PhysRender(ser.Append(("resmix", 0.5f)).ToArray(), note, 8192);
+ float serRms = Rms(serial, 8192), peak = 0; foreach (var x in serial) peak = Math.Max(peak, Math.Abs(x));
+ Check(serRms > 0.01f && peak < 1.5f, $"1→2 with a long-ringing resonator 2 stays bounded (RMS {serRms:F3}, peak {peak:F2})");
+ var serial0 = PhysRender(ser.Append(("resmix", 0f)).ToArray(), note, 8192);
+ double dSer = 0; for (int i = 0; i < off.Length; i++) dSer = Math.Max(dSer, Math.Abs(serial0[i] - off[i]));
+ Check(dSer < 1e-5, $"1→2 with Res Mix 0 = resonator 1 alone (max diff {dSer:E1})");
+ }
+
+ // Mono chokes the sounding note when a new one strikes; Poly lets both ring.
+ for (int m = 0; m < 2; m++)
+ {
+ using var e = new NotaEngine();
+ e.SetBpm(120); e.SetTimeSignature(4, 4);
+ int tr = e.AddPhysicalSynthTrack();
+ for (int i = 0; i < e.PluginParamCount(tr, -1); i++)
+ {
+ string id = e.PluginParamId(tr, -1, i);
+ if (id == "mono") e.PluginParamSet(tr, -1, i, m);
+ else if (id == "r1decay") e.PluginParamSet(tr, -1, i, 0.9f);
+ else if (id == "noteoff") e.PluginParamSet(tr, -1, i, 0f);
+ }
+ e.AddMidiClip(tr, 0.0, 4.0);
+ e.SetClipNotes(tr, 0, new[] { new NotaNote(60, 0.0, 2.0, 0.9f), new NotaNote(67, 0.5, 2.0, 0.9f) });
+ var b = new float[BF(0.5) * 2];
+ e.Seek(0.0); e.Play(); e.RenderOffline(b, BF(0.5)); e.StopTransport();
+ int voices = e.InstrumentVoiceCount(tr);
+ Check(voices == (m == 1 ? 1 : 2), $"Physical {(m == 1 ? "mono" : "poly")}: {voices} voice(s) sound after two overlapping strikes");
+ Check(Rms(b, BF(0.5)) > 0.001f, $"Physical {(m == 1 ? "mono" : "poly")} is audible");
+ }
+
+ // Telemetry: the last struck pitch and bank 1's partial table as the engine tunes it.
+ {
+ int ts = pe.AddPhysicalSynthTrack();
+ pe.AddMidiClip(ts, 0.0, 4.0);
+ pe.SetClipNotes(ts, 0, new[] { new NotaNote(60, 0.0, 1.0, 0.9f) });
+ var b = new float[4096 * 2];
+ pe.Seek(0.0); pe.Play(); pe.RenderOffline(b, 4096); pe.StopTransport();
+ var sc = new float[Nota.Application.PhysicalModel.ScopeLength];
+ int n = pe.InstrumentScope(ts, sc);
+ Check(n == Nota.Application.PhysicalModel.ScopeLength, $"Physical scope returns {Nota.Application.PhysicalModel.ScopeLength} floats (got {n})");
+ Check(Math.Abs(sc[2] - 261.63f) < 0.5f, $"scope reports the struck fundamental (C4 = {sc[2]:F2} Hz)");
+ Check(sc[3] > 1e-4f, $"scope reports an output peak ({sc[3]:F4})");
+ var bank1 = Nota.Application.PhysicalModel.Bank(sc, 0);
+ Check(Math.Abs(bank1[0].Ratio - 1) < 1e-4 && Math.Abs(bank1[1].Ratio - 3.984) < 0.01, $"bank 1 = marimba partials (1, {bank1[1].Ratio:F3} …)");
+ Check(bank1[0].Tau > bank1[8].Tau, "high partials die sooner than the fundamental");
+ pe.PluginParamSet(ts, -1, PI(ts, "r1tune"), 0.75f);
+ pe.InstrumentScope(ts, sc);
+ Check(Math.Abs(Nota.Application.PhysicalModel.Bank(sc, 0)[0].Ratio - 2) < 1e-3, "bank tune +12 st doubles the partial ratios");
+ string sum = Nota.Application.PhysicalModel.Summary(id => pe.PluginParamGet(ts, -1, PI(ts, id)));
+ Check(sum.Contains("marimba") && sum.StartsWith("Poly 8"), $"summary reads the patch ('{sum}')");
+ }
+
+ // Automation: a plugin-param lane on Res Mix drives it during playback.
+ {
+ int ta = pe.AddPhysicalSynthTrack();
+ int mi = PI(ta, "resmix");
+ int lane = pe.AddPluginAutomationLane(ta, -1, "resmix");
+ Check(lane >= 0, "add plugin automation lane on resmix");
+ pe.SetAutomationPoints(ta, lane, new[] { new AutomationPoint(0.0, 0.0f, 0f), new AutomationPoint(2.0, 1.0f, 0f) });
+ var ab = new float[4096 * 2];
+ pe.Seek(1.99); pe.Play(); pe.RenderOffline(ab, 4096); pe.StopTransport();
+ Check(pe.PluginParamGet(ta, -1, mi) > 0.9f, $"automation drives Res Mix ({pe.PluginParamGet(ta, -1, mi):F2})");
+ }
+
+ // Factory presets: 32 ship, every named param is a real Physical id, each applies in
+ // place and renders audible + finite.
+ {
+ var ids = new System.Collections.Generic.HashSet<string>();
+ for (int i = 0; i < pc; i++) ids.Add(pe.PluginParamId(t, -1, i));
+ var cat = new FactoryPresetCatalog();
+ var mine = cat.All().Where(p => p.IsInstrument && p.BuiltinKind == 2).ToList();
+ Check(mine.Count == 32, $"Nota Physical ships 32 factory presets (got {mine.Count})");
+ var bad = mine.SelectMany(p => cat.Document(p.Id)!.NamedParams!.Keys.Where(k => !ids.Contains(k)).Select(k => $"{p.DisplayName}:{k}")).ToList();
+ Check(bad.Count == 0, $"every Physical preset param id exists{(bad.Count > 0 ? " — bad: " + string.Join(", ", bad) : "")}");
+ int tp = pe.AddPhysicalSynthTrack();
+ int fails = mine.Count(p => cat.ApplyInPlace(pe, p.Id, tp, -1).Length != 0);
+ Check(fails == 0, $"every Physical preset applies in place ({fails} failed)");
+ var off = new System.Collections.Generic.List<string>();
+ foreach (var p in mine)
+ {
+ var doc = cat.Document(p.Id)!;
+ var b = PhysRender(doc.NamedParams!.Select(kv => (kv.Key, kv.Value)).ToArray(),
+ new[] { new NotaNote(60, 0.0, 0.5, 0.9f), new NotaNote(64, 0.5, 0.5, 0.9f), new NotaNote(67, 1.0, 0.5, 0.9f) }, BF(1.6));
+ bool ok = true; foreach (var x in b) if (!float.IsFinite(x) || Math.Abs(x) > 4f) { ok = false; break; }
+ float rms = Rms(b, BF(1.6));
+ if (!ok || rms < 0.005f || rms > 0.9f) off.Add($"{p.DisplayName} ({rms:F3})");
+ }
+ Check(off.Count == 0, $"every Physical preset renders audible and finite{(off.Count > 0 ? " — off: " + string.Join(", ", off) : "")}");
+ }
}
// ============================ Nota Aurora ==================================
@@ -3071,7 +3215,7 @@ Check(revDev >= 0 && engine.DeviceName(fxT, revDev) == "Nota Reverb" && engine.D
int delDev = engine.AddBuiltinDevice(fxT, 3);
Check(delDev >= 0 && engine.DeviceName(fxT, delDev) == "Nota Delay" && engine.DeviceParamCount(fxT, delDev) == 24, "add built-in Delay (24 params)");
int utilDev = engine.AddBuiltinDevice(fxT, 4);
-Check(utilDev >= 0 && engine.DeviceName(fxT, utilDev) == "Nota Utility" && engine.DeviceParamCount(fxT, utilDev) == 9, "add built-in Utility (9 params)");
+Check(utilDev >= 0 && engine.DeviceName(fxT, utilDev) == "Nota Utility" && engine.DeviceParamCount(fxT, utilDev) == 17, "add built-in Utility (17 params)");
engine.DeviceSetParam(fxT, delDev, 12, 0.5f); // Delay Dry/Wet (index 12)
Check(Math.Abs(engine.DeviceGetParam(fxT, delDev, 12) - 0.5f) < 0.001f, "Delay param round-trips");
int ampDev = engine.AddBuiltinDevice(fxT, 6);
@@ -7083,6 +7227,225 @@ Console.WriteLine("-- Nota Valve (effect kind 6) --");
}
}
+// ===================== Nota Utility (effect kind 4) ========================
+Console.WriteLine("-- Nota Utility (effect kind 4) --");
+{
+ // 8 s of stereo: a 60 Hz tone in anti-phase (pure side) under a 2 kHz tone in phase (pure mid).
+ string uwav = Path.Combine(Path.GetTempPath(), "nota_smoke_utility.wav");
+ Nota.SmokeTest.WavWriter.WriteStereo(uwav, 8.0, 44100, i =>
+ {
+ double lo = 0.3 * Math.Sin(2 * Math.PI * 60 * i / 44100.0), hi = 0.3 * Math.Sin(2 * Math.PI * 2000 * i / 44100.0);
+ return (hi + lo, hi - lo);
+ });
+ using var ueng = new NotaEngine();
+ int ut = ueng.AddAudioTrack();
+ ueng.AddAudioClip(ut, uwav, 0.0);
+ int ud = ueng.AddBuiltinDevice(ut, 4);
+ Check(ud >= 0 && ueng.DeviceName(ut, ud) == "Nota Utility" && ueng.TrackDeviceBuiltinKind(ut, ud) == 4, "add Nota Utility (kind 4)");
+ int upc = ueng.DeviceParamCount(ut, ud);
+ Check(upc == 17, $"Nota Utility exposes 17 params ({upc})");
+ const int UGain = 0, UBal = 1, UWidth = 2, UMode = 3, UMonoF = 4, UMono = 5, UMute = 6, UInvL = 7, UWMode = 9, USlope = 10,
+ UAuto = 11, UMatchTo = 12, UTarget = 13, UMeter = 14, UTp = 15, UCeil = 16;
+ string[] uNames = { "Gain", "Balance", "Width", "Channel Mode", "Mono Freq", "Mono Below", "Mute", "Invert L", "Invert R",
+ "Width Mode", "Mono Slope", "Auto Match", "Match To", "Target", "Meter", "TP Limit", "TP Ceiling" };
+ bool namesOk = true;
+ for (int k = 0; k < upc && k < uNames.Length; k++) namesOk &= ueng.DeviceParamName(ut, ud, k) == uNames[k];
+ Check(namesOk, "the original nine params keep their order; Width Mode … TP Ceiling are appended");
+ Check(Math.Abs(ueng.DeviceParamMax(ut, ud, UWidth) - 400f) < 1e-3f && Math.Abs(ueng.DeviceParamMin(ut, ud, UGain) + 24f) < 1e-3f
+ && Math.Abs(ueng.DeviceParamMin(ut, ud, UTarget) + 36f) < 1e-3f && Math.Abs(ueng.DeviceParamMax(ut, ud, UMeter) - 2f) < 1e-3f,
+ "params keep real units (Gain ±24 dB, Width 0..400 %, Target −36..0, Meter 0..2)");
+ Check(Math.Abs(ueng.DeviceParamDefault(ut, ud, UWidth) - 100f) < 1e-3f && Math.Abs(ueng.DeviceParamDefault(ut, ud, UMonoF) - 120f) < 1e-3f
+ && ueng.DeviceParamDefault(ut, ud, UWMode) < 0.5f && ueng.DeviceParamDefault(ut, ud, USlope) < 0.5f && ueng.DeviceParamDefault(ut, ud, UAuto) < 0.5f
+ && ueng.DeviceParamDefault(ut, ud, UTp) < 0.5f && Math.Abs(ueng.DeviceParamDefault(ut, ud, UCeil) + 1f) < 1e-3f,
+ "appended params default to the old sound (L/R width, 6 dB/oct mono, no auto match, no limiter)");
+ ueng.DeviceSetParam(ut, ud, UWidth, 250f);
+ Check(Math.Abs(ueng.DeviceGetParam(ut, ud, UWidth) - 250f) < 1e-3f, "device param set/get round-trips (raw units)");
+ ueng.DeviceSetParam(ut, ud, UWidth, 900f);
+ Check(Math.Abs(ueng.DeviceGetParam(ut, ud, UWidth) - 400f) < 1e-3f, "out-of-range values clamp to the param's range");
+ ueng.DeviceSetParam(ut, ud, UWidth, 100f);
+
+ var ubuf = new float[4096 * 2];
+ int uFrames = 0;
+ // Render n frames from `from` seconds; keep the last 4096 in ubuf.
+ void URender(int n = 8192, double from = 0.5)
+ {
+ ueng.SetBpm(120); ueng.Seek(from * 2); ueng.Play();
+ for (int k = 0; k < n; k += 4096) ueng.RenderOffline(ubuf, 4096);
+ ueng.StopTransport(); uFrames = n;
+ }
+ double Side() { double s = 0; for (int i = 0; i < 4096; i++) { double d = 0.5 * (ubuf[i * 2] - ubuf[i * 2 + 1]); s += d * d; } return Math.Sqrt(s / 4096); }
+ double Mid() { double s = 0; for (int i = 0; i < 4096; i++) { double d = 0.5 * (ubuf[i * 2] + ubuf[i * 2 + 1]); s += d * d; } return Math.Sqrt(s / 4096); }
+ double ChRms(int c) { double s = 0; for (int i = 0; i < 4096; i++) s += ubuf[i * 2 + c] * (double)ubuf[i * 2 + c]; return Math.Sqrt(s / 4096); }
+ bool UFinite() { foreach (var x in ubuf) if (!float.IsFinite(x) || Math.Abs(x) > 8f) return false; return true; }
+
+ URender(); double side0 = Side(), mid0 = Mid();
+ Check(side0 > 0.1 && mid0 > 0.1, $"the test signal carries mid and side ({mid0:0.000} / {side0:0.000})");
+ // Width: 0 → mono; 200 L/R → twice the side; M/S 200 → side only; M/S 150 keeps the side and halves the mid.
+ ueng.DeviceSetParam(ut, ud, UWidth, 0f); URender();
+ Check(Side() < 0.002 && Math.Abs(Mid() - mid0) < 0.01, $"Width 0 is mono ({Side():0.0000})");
+ ueng.DeviceSetParam(ut, ud, UWidth, 200f); URender();
+ Check(Math.Abs(Side() / side0 - 2) < 0.05 && Math.Abs(Mid() - mid0) < 0.01, $"L/R Width 200 doubles the side ({Side() / side0:0.00}×)");
+ ueng.DeviceSetParam(ut, ud, UWMode, 1f); URender();
+ Check(Mid() < 0.002 && Math.Abs(Side() - side0) < 0.01, $"M/S Width 200 is side only (mid {Mid():0.0000})");
+ ueng.DeviceSetParam(ut, ud, UWidth, 150f); URender();
+ Check(Math.Abs(Mid() / mid0 - 0.5) < 0.03 && Math.Abs(Side() - side0) < 0.01, $"M/S Width 150 trades the mid for width, the side holds ({Mid() / mid0:0.00}× mid)");
+ ueng.DeviceSetParam(ut, ud, UWMode, 0f); ueng.DeviceSetParam(ut, ud, UWidth, 100f);
+
+ // Mono below 120 Hz removes the 60 Hz side, steeper slopes more of it; the mid is untouched.
+ ueng.DeviceSetParam(ut, ud, UMono, 1f);
+ var sideBySlope = new double[3];
+ for (int sl = 0; sl < 3; sl++) { ueng.DeviceSetParam(ut, ud, USlope, sl); URender(16384); sideBySlope[sl] = Side(); }
+ Check(sideBySlope[0] < side0 * 0.6 && sideBySlope[1] < sideBySlope[0] * 0.7 && sideBySlope[2] < sideBySlope[1] * 0.6 && Math.Abs(Mid() - mid0) < 0.01,
+ $"Mono below 120 Hz takes out the 60 Hz side, more with each slope (6 / 12 / 24: {sideBySlope[0] / side0:0.00} / {sideBySlope[1] / side0:0.00} / {sideBySlope[2] / side0:0.00})");
+ ueng.DeviceSetParam(ut, ud, UMono, 0f); ueng.DeviceSetParam(ut, ud, USlope, 0f);
+
+ // Channel modes, phase, balance, mute.
+ ueng.DeviceSetParam(ut, ud, UMode, 1f); URender();
+ bool same = true; for (int i = 0; i < 4096; i++) same &= Math.Abs(ubuf[i * 2] - ubuf[i * 2 + 1]) < 1e-5f;
+ Check(same, "Channel Mode Left puts the left on both sides");
+ ueng.DeviceSetParam(ut, ud, UMode, 0f); URender(); var stereo = (float[])ubuf.Clone();
+ ueng.DeviceSetParam(ut, ud, UMode, 3f); URender();
+ bool swapped = true; for (int i = 0; i < 4096; i++) swapped &= Math.Abs(ubuf[i * 2] - stereo[i * 2 + 1]) < 1e-4f;
+ Check(swapped, "Channel Mode Swap swaps the sides");
+ ueng.DeviceSetParam(ut, ud, UMode, 0f);
+ ueng.DeviceSetParam(ut, ud, UInvL, 1f); URender();
+ bool inv = true; for (int i = 0; i < 4096; i++) inv &= Math.Abs(ubuf[i * 2] + stereo[i * 2]) < 1e-4f;
+ Check(inv, "Invert L flips the left channel");
+ ueng.DeviceSetParam(ut, ud, UInvL, 0f);
+ ueng.DeviceSetParam(ut, ud, UBal, -1f); URender();
+ Check(ChRms(1) < 1e-4 && ChRms(0) > 0.1, "Balance −1 leaves the left only");
+ ueng.DeviceSetParam(ut, ud, UBal, 0f);
+ ueng.DeviceSetParam(ut, ud, UMute, 1f); URender();
+ Check(ChRms(0) + ChRms(1) < 1e-5, "Mute silences the output");
+ ueng.DeviceSetParam(ut, ud, UMute, 0f);
+ ueng.DeviceSetParam(ut, ud, UGain, 6f); URender();
+ Check(Math.Abs(20 * Math.Log10(Mid() / mid0) - 6) < 0.2, $"Gain +6 dB raises the level ({20 * Math.Log10(Mid() / mid0):+0.0;-0.0} dB)");
+ ueng.DeviceSetParam(ut, ud, UGain, 0f);
+
+ // Scope: telemetry, the level history and the band analysis.
+ const int uTele = 48, uHist = 80, uBands = 32, uResp = 96, uBandAt = uTele + 6 * uHist;
+ var usc = new float[uBandAt + 5 * uBands + uResp];
+ ueng.DeviceAction(ut, ud, 1, 0, 0);
+ URender(44100 * 4);
+ int un = ueng.DeviceScope(ut, ud, usc, usc.Length);
+ Check(un == usc.Length && usc[3] > 1000 && usc[33] > 0.5f, $"Utility scope carries telemetry, histories and bands ({un} values, sr {usc[3]:0})");
+ Check(usc[5] > -30 && usc[5] < 0 && Math.Abs(usc[6] - usc[5]) < 0.3 && usc[11] > -12 && usc[11] < 0.5,
+ $"loudness and true peak are metered (in {usc[5]:0.0} LUFS, out {usc[6]:0.0} LUFS, TP {usc[11]:0.0} dBTP)");
+ int filled = 0; for (int k = 0; k < uHist; k++) if (usc[uTele + 1 * uHist + k] > -100) filled++;
+ Check(filled >= 30 && filled <= uHist, $"the output loudness history fills as audio plays ({filled} of {uHist} points)");
+ int bLow = -1, bHigh = -1;
+ for (int b = 0; b < uBands; b++)
+ {
+ double hz = 30 * Math.Pow(16000 / 30.0, (b + 0.5) / uBands);
+ if (bLow < 0 && hz > 55) bLow = b;
+ if (bHigh < 0 && hz > 1900) bHigh = b;
+ }
+ float wLow = usc[uBandAt + uBands + bLow], wHigh = usc[uBandAt + uBands + bHigh], cLow = usc[uBandAt + 2 * uBands + bLow];
+ Check(wLow > 0.9f && cLow < -0.8f && wHigh < 0.1f, $"bands: the 60 Hz tone reads anti-phase, the 2 kHz tone mono (width {wLow:0.00} / {wHigh:0.00}, corr {cLow:+0.00;-0.00})");
+ ueng.DeviceSetParam(ut, ud, UMono, 1f); ueng.DeviceSetParam(ut, ud, UMonoF, 200f); ueng.DeviceSetParam(ut, ud, UWidth, 200f); ueng.DeviceSetParam(ut, ud, USlope, 2f);
+ ueng.DeviceScope(ut, ud, usc, usc.Length);
+ float setLow = usc[uBandAt + 4 * uBands + bLow], setHigh = usc[uBandAt + 4 * uBands + bHigh], effW = usc[22];
+ Check(setLow < 50 && Math.Abs(setHigh - 200) < 5 && Math.Abs(effW - 200) < 0.5, $"the configured width drops below the mono cutoff ({setLow:0} % at 60 Hz, {setHigh:0} % at 2 kHz)");
+ ueng.DeviceSetParam(ut, ud, UMono, 0f); ueng.DeviceSetParam(ut, ud, UMonoF, 120f); ueng.DeviceSetParam(ut, ud, UWidth, 100f); ueng.DeviceSetParam(ut, ud, USlope, 0f);
+
+ // Gain match (action 0): to the input, then to a Target.
+ ueng.DeviceSetParam(ut, ud, UGain, 8f); URender(44100 * 4);
+ ueng.DeviceAction(ut, ud, 0, 0, 0);
+ Check(Math.Abs(ueng.DeviceGetParam(ut, ud, UGain)) < 0.5f, $"Gain match brings a +8 dB output back to the input level (Gain {ueng.DeviceGetParam(ut, ud, UGain):+0.0;-0.0})");
+ ueng.DeviceSetParam(ut, ud, UMatchTo, 1f); ueng.DeviceSetParam(ut, ud, UTarget, -20f);
+ ueng.DeviceAction(ut, ud, 0, 0, 0);
+ URender(44100 * 4); ueng.DeviceScope(ut, ud, usc, uBandAt);
+ Check(Math.Abs(usc[6] + 20) < 0.7, $"Gain match to Target −20 LUFS lands there ({usc[6]:0.0} LUFS)");
+ ueng.DeviceSetParam(ut, ud, UMeter, 2f);
+ ueng.DeviceAction(ut, ud, 0, 0, 0);
+ URender(44100 * 4); ueng.DeviceScope(ut, ud, usc, uBandAt);
+ Check(Math.Abs(usc[8] + 20) < 0.7 && (int)usc[24] == 2, $"… and in RMS, to −20 dBFS RMS ({usc[8]:0.0} dBFS)");
+ ueng.DeviceSetParam(ut, ud, UMeter, 0f); ueng.DeviceSetParam(ut, ud, UMatchTo, 0f); ueng.DeviceSetParam(ut, ud, UGain, 0f);
+
+ // Auto match: a +10 dB output rides back to the input's loudness.
+ ueng.DeviceSetParam(ut, ud, UGain, 10f); ueng.DeviceSetParam(ut, ud, UAuto, 1f);
+ URender(44100 * 7);
+ ueng.DeviceScope(ut, ud, usc, uBandAt);
+ Check(Math.Abs(usc[13] - usc[12]) < 1.0 && usc[14] < -8, $"Auto Match rides a hot output to the input (out {usc[13]:0.0} vs in {usc[12]:0.0} LUFS, ride {usc[14]:+0.0;-0.0} dB)");
+ ueng.DeviceSetParam(ut, ud, UAuto, 0f); ueng.DeviceSetParam(ut, ud, UGain, 0f);
+
+ // True-peak limiter: +14 dB would clip; with the limiter no sample passes the ceiling.
+ ueng.DeviceSetParam(ut, ud, UGain, 14f); ueng.DeviceSetParam(ut, ud, UTp, 1f); ueng.DeviceSetParam(ut, ud, UCeil, -1f);
+ URender(44100);
+ float upk = 0; foreach (var x in ubuf) upk = Math.Max(upk, Math.Abs(x));
+ ueng.DeviceScope(ut, ud, usc, uBandAt);
+ Check(upk <= 0.8913f + 1e-4f && usc[15] > 3 && UFinite(), $"the true-peak limiter holds −1 dBTP (peak {20 * Math.Log10(upk):0.00} dBFS, reduction {usc[15]:0.0} dB)");
+ ueng.DeviceSetParam(ut, ud, UTp, 0f); ueng.DeviceSetParam(ut, ud, UGain, 0f);
+
+ // Texts, the reset action.
+ ueng.DeviceSetParam(ut, ud, UMono, 1f); ueng.DeviceSetParam(ut, ud, UWMode, 1f);
+ string utext = ueng.DeviceText(ut, ud, 0);
+ Check(utext.StartsWith("Stereo") && utext.Contains("M/S") && utext.Contains("mono below 120 Hz"), $"status text names the mode, width law and mono (got '{utext}')");
+ Check(ueng.DeviceText(ut, ud, 1).Contains("LUFS-S") && ueng.DeviceText(ut, ud, 2).Contains("Mono Slope"), "live reading and parameter guide texts");
+ ueng.DeviceAction(ut, ud, 1, 0, 0);
+ URender(4096);
+ ueng.DeviceScope(ut, ud, usc, uBandAt);
+ int after = 0; for (int k = 0; k < uHist; k++) if (usc[uTele + uHist + k] > -100) after++;
+ Check(after <= 1, $"reset clears the level history ({after} points left)");
+ ueng.DeviceSetParam(ut, ud, UMono, 0f); ueng.DeviceSetParam(ut, ud, UWMode, 0f);
+
+ // MCP: the utility reading.
+ var utools = new Nota.Mcp.Tools.DeviceTools(ueng, new Nota.SmokeTest.SyncDispatch(), new Nota.SmokeTest.NoRefresh());
+ URender(44100 * 4);
+ var ur = utools.ReadUtility(ut, ud).Result;
+ Check(ur.Meter == "LUFS-S" && ur.SampleRate > 1000 && ur.Bands.Length == 8 && ur.Summary.StartsWith("Stereo") && ur.OutLufsShort > -30
+ && Math.Abs(ur.DeltaDb) < 0.5 && ur.Bands[0].Width > 0.8,
+ $"MCP read_utility reports levels, delta and bands (out {ur.OutLufsShort:0.0} LUFS, Δ {ur.DeltaDb:+0.0;-0.0}, low band width {ur.Bands[0].Width:0.00})");
+
+ // Duplicate the track → cloneDevice(kind 4) carries the params, appended ones too.
+ ueng.DeviceSetParam(ut, ud, UWidth, 140f); ueng.DeviceSetParam(ut, ud, USlope, 2f); ueng.DeviceSetParam(ut, ud, UTarget, -9f);
+ int ucopy = ueng.DuplicateTrack(ut);
+ Check(ucopy > 0 && Math.Abs(ueng.DeviceGetParam(ucopy, ud, UWidth) - 140f) < 1e-3f && Math.Abs(ueng.DeviceGetParam(ucopy, ud, USlope) - 2f) < 1e-3f
+ && Math.Abs(ueng.DeviceGetParam(ucopy, ud, UTarget) + 9f) < 1e-3f, "duplicate track clones Utility params (appended ones too)");
+ ueng.RemoveTrack(ucopy);
+ ueng.DeviceSetParam(ut, ud, UWidth, 100f); ueng.DeviceSetParam(ut, ud, USlope, 0f); ueng.DeviceSetParam(ut, ud, UTarget, -14f);
+
+ // Automation drives an original and an appended param.
+ int ulane = ueng.AddAutomationLane(ut, AutomationTarget.DeviceParam, ud, UWidth);
+ ueng.SetAutomationPoints(ut, ulane, new[] { new AutomationPoint(0, 200f), new AutomationPoint(16, 200f) });
+ int ulane2 = ueng.AddAutomationLane(ut, AutomationTarget.DeviceParam, ud, UTarget);
+ ueng.SetAutomationPoints(ut, ulane2, new[] { new AutomationPoint(0, -27f), new AutomationPoint(16, -27f) });
+ URender();
+ Check(Math.Abs(ueng.DeviceGetParam(ut, ud, UWidth) - 200f) < 2f, $"automation drives Width ({ueng.DeviceGetParam(ut, ud, UWidth):0} %)");
+ Check(Math.Abs(ueng.DeviceGetParam(ut, ud, UTarget) + 27f) < 0.5f, $"automation drives Target ({ueng.DeviceGetParam(ut, ud, UTarget):0.0})");
+ ueng.RemoveAutomationLane(ut, ulane2);
+ ueng.RemoveAutomationLane(ut, ulane);
+
+ // Factory presets: ≥ 25, every named param exists, each applies in place and renders finite; the old names stay.
+ {
+ var names = new HashSet<string>();
+ for (int k = 0; k < upc; k++) names.Add(ueng.DeviceParamName(ut, ud, k));
+ var cat = new FactoryPresetCatalog();
+ var mine = cat.All().Where(p => !p.IsInstrument && !p.IsMidiEffect && p.BuiltinKind == 4).ToList();
+ Check(mine.Count >= 25, $"Nota Utility ships ≥ 25 factory presets ({mine.Count})");
+ var bad = mine.SelectMany(p => cat.Document(p.Id)!.NamedParams!.Keys.Where(k => !names.Contains(k)).Select(k => $"{p.DisplayName}:{k}")).ToList();
+ Check(bad.Count == 0, $"every Utility preset param name exists{(bad.Count > 0 ? " — bad: " + string.Join(", ", bad) : "")}");
+ Check(new[] { "Stereo Widener", "Bass Mono", "Mono Maker", "Narrow", "Trim −6 dB", "Swap L/R" }.All(n => mine.Any(p => p.DisplayName == n)),
+ "the original six Utility presets keep their names");
+ int pf = 0;
+ foreach (var p in mine)
+ {
+ if (cat.ApplyInPlace(ueng, p.Id, ut, ud).Length != 0) { pf++; continue; }
+ URender();
+ if (!UFinite()) pf++;
+ if (p.DisplayName != "Mute" && p.DisplayName != "Side Only" && Rms(ubuf, 4096) < 1e-4f) pf++;
+ }
+ Check(pf == 0, $"every Utility preset applies and renders ({pf} failed)");
+ cat.ApplyInPlace(ueng, "util/Club Low End", ut, ud);
+ Check(ueng.DeviceGetParam(ut, ud, UMono) > 0.5f && Math.Abs(ueng.DeviceGetParam(ut, ud, USlope) - 2f) < 1e-3f && Math.Abs(ueng.DeviceGetParam(ut, ud, UMonoF) - 100f) < 1e-3f,
+ "Club Low End preset: mono below 100 Hz at 24 dB/oct");
+ cat.ApplyInPlace(ueng, "util/Init", ut, ud);
+ Check(ueng.DeviceGetParam(ut, ud, UMono) < 0.5f && Math.Abs(ueng.DeviceGetParam(ut, ud, UWidth) - 100f) < 1e-3f && ueng.DeviceGetParam(ut, ud, USlope) < 0.5f,
+ "unnamed params reset to defaults between presets");
+ }
+ try { File.Delete(uwav); } catch { }
+}
+
// ===================== Nota Vintage (effect kind 8) ========================
Console.WriteLine("-- Nota Vintage (effect kind 8) --");
{
diff --git a/tests/Nota.SmokeTest/WavWriter.cs b/tests/Nota.SmokeTest/WavWriter.cs
index 41e04c33..d82d8849 100644
--- a/tests/Nota.SmokeTest/WavWriter.cs
+++ b/tests/Nota.SmokeTest/WavWriter.cs
@@ -41,6 +41,25 @@ internal static class WavWriter
}
}
+ // 16-bit stereo PCM from a per-frame generator (left, right), for the stereo devices.
+ public static void WriteStereo(string path, double seconds, int sampleRate, Func<int, (double L, double R)> gen)
+ {
+ int frames = (int)(seconds * sampleRate);
+ using var fs = new FileStream(path, FileMode.Create, FileAccess.Write);
+ using var w = new BinaryWriter(fs);
+ int dataBytes = frames * 4;
+ w.Write("RIFF"u8.ToArray()); w.Write(36 + dataBytes); w.Write("WAVE"u8.ToArray());
+ w.Write("fmt "u8.ToArray()); w.Write(16); w.Write((short)1); w.Write((short)2);
+ w.Write(sampleRate); w.Write(sampleRate * 4); w.Write((short)4); w.Write((short)16);
+ w.Write("data"u8.ToArray()); w.Write(dataBytes);
+ for (int i = 0; i < frames; i++)
+ {
+ var (l, r) = gen(i);
+ w.Write((short)(Math.Clamp(l, -1, 1) * short.MaxValue));
+ w.Write((short)(Math.Clamp(r, -1, 1) * short.MaxValue));
+ }
+ }
+
// First half silence, second half a steady tone. Used to prove source-region
// editing: sliding the Start marker to the midpoint should reveal the tone.
public static void WriteSilenceThenTone(string path, double seconds, double freq, int sampleRate)