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.

(feat) Add Nota Keys

Egor Khindikaynen4ab6bd1c2a39
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d46cb642..0a77469d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -44,6 +44,19 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
- **Nota Remote: Expressive keys.** On a track that takes MPE, the Keys screen's Keyboard and
Scale modes get an **Expressive** switch: a finger keeps its note, sliding sideways bends it,
the height on the key changes its timbre, and a phone that senses touch force sends pressure.
+- **Nota Keys — a modelled electric piano.** Four instruments in one: Tine, Suitcase, Reed and
+ Clav. A hammer strikes a tine (with its tone bar), a reed or a string, and the PICKUP graph is
+ the very curve the sound passes — drag the point to set symmetry and distance: close and
+ off-centre growls (the bark), far and centred stays round; play harder and it barks more. The
+ Clav shows its string and two pickups (Upper / Both / Lower). Hammer hardness, velocity →
+ hardness and thump, decay, body, brightness and key tracking, damper and release noise, a
+ sustain pedal (click it, automate it, or press a keyboard's CC64), age, stretch tuning and 8–64
+ voices. The FX tab chains a preamp, a mono or stereo-pan tremolo (free or synced to the
+ tempo), a phaser, a chorus and a Suitcase / Combo / DI cabinet. Two sizes: L with Sound and FX
+ tabs, S with the model, the pickup and four knobs. MPE: bend, pressure drives the tine harder
+ into the pickup, slide shifts its symmetry. 40 factory presets; MCP `read_keys` / `set_keys`.
+- **The sustain pedal (CC64) reaches instruments.** A keyboard's pedal now holds Nota Keys' notes
+ and reaches hosted plug-ins as CC64.
### Changed
- **The menu, the keyboard shortcuts and the command palette run the same commands**, so a
diff --git a/FEATURES.md b/FEATURES.md
index d4b23dc1..5c8dc18a 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -202,13 +202,14 @@ the mixer opens as a separate floating window (**View → Mixer**, ⌘M).
bend, pressure and slide (CC74): channels 2–16 are per-note (lower zone, ±48 semitones by
default; the controller's MPE Configuration and bend-range messages are honoured), channel 1
is an ordinary keyboard whose pitch wheel, channel aftertouch and CC74 move the whole
- instrument. **Nota Synth, Volt, Aurora, Operator, Pentad and Physical** play it: bend moves
+ instrument. **Nota Synth, Volt, Aurora, Operator, Pentad, Physical and Keys** play it: bend moves
the note's pitch; pressure raises its level and opens its filter (Operator: deepens the FM,
Pentad: poly aftertouch through *Aftertouch Cutoff*, Physical: bows the struck body so a held
note sustains); slide sweeps the filter (Aurora: the wavetable position, Operator: the FM
- index, Physical: how long the body rings). Instrument Racks pass it to their chains; hosted
- plug-ins get the wheel, channel pressure and polyphonic aftertouch. Expression is played
- live — it is not recorded into clips.
+ index, Physical: how long the body rings, Keys: drives the tine into the pickup / shifts its
+ symmetry). Instrument Racks pass it to their chains; hosted plug-ins get the wheel, channel
+ pressure, polyphonic aftertouch and the sustain pedal (CC64), which also holds Nota Keys'
+ notes. Expression is played live — it is not recorded into clips.
- **Nota Remote Keys — Expressive**: on a track whose instrument takes MPE, the phone's
Keyboard and Scale modes can keep each finger on the note it struck: sliding sideways bends
it (a key's width is its pitch step), the height on the key is its slide, and a screen that
@@ -423,6 +424,15 @@ and user presets, automation, persistence and cloning.
a six-shape LFO, a stereo bucket-brigade delay, a 16-step sequencer / arpeggiator with
ratchets and ties, and a 12-cable patch bay over 42 points (matrix, jack strip or full-card
overlay). Cables are parameters: saved, preset-able and automatable. 28 factory presets.
+- **Nota Keys** — modelled electric piano: Tine, Suitcase, Reed and Clav models (a hammer
+ pulse into tine + tone bar, reed or string modes). The PICKUP graph is the transfer curve the
+ sound passes — drag for symmetry (X) and distance (Y), with H1–H8 bars and the bark readout;
+ Clav shows its string and Upper / Both / Lower pickups. Hammer (hardness, vel → hardness,
+ noise), resonator (decay, body, bright, key → bright), damper with release noise and a sustain
+ pedal (button, automation or CC64), tune / age / stretch, 8 / 16 / 32 / 64 voices. FX tab:
+ preamp (drive, bass, treble), mono or stereo-pan tremolo (free or tempo-synced), phaser,
+ chorus, Suitcase / Combo / DI cabinet, volume and pan. Two sizes: L (Sound / FX tabs) and S
+ (model, pickup, four knobs). 40 factory presets; MCP `read_keys` / `set_keys`.
### Audio effects
- **Nota EQ-8** (kind 0) — 8-band parametric: each band on / off, Low cut / Low shelf / Bell /
@@ -903,7 +913,8 @@ Coverage:
each changed), `save_version` with a note, `switch_version`, `annotate_version` (name, note,
star). Deleting versions stays with the user.
- **Tracks**: add and remove, volume/pan/mute/solo, groups, sends.
-- **Instruments**: add by kind, read and write parameters (by index or by stable id).
+- **Instruments**: add by kind, read and write parameters (by index or by stable id); read /
+ shape Nota Keys in musical terms (`read_keys`, `set_keys`).
- **Audio effects**: add, remove, reorder, bypass, parameters; load an audio file into a
device (a Nota Chamber impulse response) and read its resource text (IR names).
- **MIDI clips and notes**: piano roll — add a clip, read/write/append/clear notes, move
diff --git a/src/managed/Nota.App/Controls/KeysViews.cs b/src/managed/Nota.App/Controls/KeysViews.cs
new file mode 100644
index 00000000..793bdb4b
--- /dev/null
+++ b/src/managed/Nota.App/Controls/KeysViews.cs
@@ -0,0 +1,307 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Detail · Devices — the Nota Keys graphs (instrument kind 16):
+//
+// KeysPickupView the PICKUP transfer curve — the exact function the engine runs
+// (KeysModel.PickupRaw) — with the tine's travel drawn over it, a dashed
+// linear reference and the handle: drag X = Symmetry, Y = Distance. L adds
+// the H1–H8 bars of what the curve does to a sine. For Clav it draws the
+// string instead, with its two pickups lit by Pickup Position.
+// KeysTremView the tremolo: the left (brass) and right (teal) gains scrolling with the
+// engine's LFO, a playhead and the pan dot it puts the sound at.
+// KeysVoiceGrid the voice pool: held notes in brass, pedal / release tails dim, free
+// slots dark, the cells past the voice limit darker still.
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Input;
+using Avalonia.Media;
+using Nota.Application;
+
+namespace Nota.App;
+
+internal sealed class KeysPickupView : Control, IMidiLearnRegions
+{
+ private readonly IAudioEngine _e;
+ private readonly int _t;
+ private readonly Dictionary<string, int> _idx;
+ private bool _drag;
+
+ /// <summary>The mini (S) card's window: no harmonics inset, the readout top-right.</summary>
+ public bool Mini { get; init; }
+
+ public event Action? Changed;
+
+ public KeysPickupView(IAudioEngine engine, int track, Dictionary<string, int> idx)
+ {
+ _e = engine; _t = track; _idx = idx;
+ MinWidth = 120; MinHeight = 60;
+ Cursor = new Cursor(StandardCursorType.Hand);
+ }
+
+ public void Refresh() => InvalidateVisual();
+
+ private int I(string id) => _idx.TryGetValue(id, out var i) ? i : -1;
+ private float G(string id) { int i = I(id); return i >= 0 ? _e.PluginParamGet(_t, -1, i) : 0f; }
+ private void Set(string id, double v) { int i = I(id); if (i >= 0) _e.PluginParamSet(_t, -1, i, (float)Math.Clamp(v, 0, 1)); }
+ private int Model => KeysModel.Index(G("model"), 4);
+
+ // The plot box: X spans −1..1 of displacement, the handle's Y spans Distance 0..1.
+ private Rect Plot() => new(8, 8, Math.Max(10, Bounds.Width - 16), Math.Max(10, Bounds.Height - 16));
+
+ public IReadOnlyList<(Rect rect, MidiTarget target, string name)> GetMidiLearnRegions()
+ {
+ var list = new List<(Rect, MidiTarget, string)>(2);
+ var r = Plot();
+ if (Model == 3) return list;
+ if (I("sym") is var s and >= 0) list.Add((new Rect(r.X, r.Y, r.Width / 2, r.Height), MidiTarget.PluginParam(_t, -1, s), "Pickup Symmetry"));
+ if (I("dist") is var d and >= 0) list.Add((new Rect(r.X + r.Width / 2, r.Y, r.Width / 2, r.Height), MidiTarget.PluginParam(_t, -1, d), "Pickup Distance"));
+ return list;
+ }
+
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ if (Model == 3 || !e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
+ _drag = true;
+ _e.BeginAutomationWrite(_t, AutomationTarget.PluginParam, -1, -1, "sym");
+ _e.BeginAutomationWrite(_t, AutomationTarget.PluginParam, -1, -1, "dist");
+ e.Pointer.Capture(this); Apply(e.GetPosition(this)); e.Handled = true;
+ }
+ protected override void OnPointerMoved(PointerEventArgs e) { if (_drag) Apply(e.GetPosition(this)); }
+ protected override void OnPointerReleased(PointerReleasedEventArgs e)
+ {
+ if (!_drag) return;
+ _drag = false;
+ _e.EndAutomationWrite(_t, AutomationTarget.PluginParam, -1, -1, "sym");
+ _e.EndAutomationWrite(_t, AutomationTarget.PluginParam, -1, -1, "dist");
+ e.Pointer.Capture(null);
+ }
+
+ private void Apply(Point p)
+ {
+ var r = Plot();
+ double sym = Math.Clamp((p.X - (r.X + r.Width / 2)) / (r.Width / 2), -1, 1);
+ double dist = Math.Clamp((p.Y - r.Y) / r.Height, 0, 1);
+ Set("sym", (sym + 1) / 2);
+ Set("dist", dist);
+ InvalidateVisual();
+ Changed?.Invoke();
+ }
+
+ private static FormattedText Mono(string t, IBrush ink, double size = 8)
+ => new(t, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, NotaFonts.Mono, size, ink);
+
+ 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);
+ int model = Model;
+ using (ctx.PushClip(new RoundedRect(frame.Deflate(1), NotaGraph.Radius)))
+ {
+ if (model == 3) RenderString(ctx, frame);
+ else RenderCurve(ctx, frame, model);
+ }
+ }
+
+ private void RenderCurve(DrawingContext ctx, Rect frame, int model)
+ {
+ var r = Plot();
+ double sym = KeysModel.Bipolar(G("sym")), dist = G("dist");
+ double norm = KeysModel.PickupNorm(sym, dist, model);
+ double cx = r.X + r.Width / 2, cy = r.Y + r.Height / 2, sx = r.Width / 2, sy = r.Height / 2 * 0.8;
+ Point Pt(double x) => new(cx + x * sx, cy - KeysModel.PickupRaw(x, sym, dist, model) / norm * sy);
+
+ // Grid: quarters + the centre cross.
+ for (int i = 1; i < 4; i++)
+ {
+ double x = r.X + r.Width * i / 4;
+ ctx.DrawLine(NotaGraph.GridPen, new Point(x, frame.Y + 1), new Point(x, frame.Bottom - 1));
+ }
+ ctx.DrawLine(NotaGraph.GridPen, new Point(frame.X + 1, cy), new Point(frame.Right - 1, cy));
+ // Linear reference.
+ ctx.DrawLine(new Pen(NotaPalette.TextAxis, 1) { DashStyle = new DashStyle(new double[] { 3, 3 }, 0) },
+ new Point(cx - sx, cy + sy), new Point(cx + sx, cy - sy));
+
+ // The curve, and the tine's travel at a full-velocity note over it.
+ var curve = new StreamGeometry();
+ using (var g = curve.Open())
+ {
+ for (int i = 0; i <= 80; i++) { var p = Pt(-1 + i / 40.0); if (i == 0) g.BeginFigure(p, false); else g.LineTo(p); }
+ g.EndFigure(false);
+ }
+ var travel = new StreamGeometry();
+ using (var g = travel.Open())
+ {
+ for (int i = 0; i <= 40; i++) { var p = Pt(-0.72 + 1.44 * i / 40.0); if (i == 0) g.BeginFigure(p, false); else g.LineTo(p); }
+ g.EndFigure(false);
+ }
+ ctx.DrawGeometry(null, new Pen(NotaPalette.Accent, NotaGraph.PrimaryWidth, lineCap: PenLineCap.Round, lineJoin: PenLineJoin.Round), curve);
+ ctx.DrawGeometry(null, new Pen(NotaPalette.Wash(NotaPalette.TealBright, 0x80), 4.5, lineCap: PenLineCap.Round, lineJoin: PenLineJoin.Round), travel);
+
+ // The handle: X = symmetry, Y = distance, with its crosshair.
+ double hx = cx + sym * sx, hy = r.Y + dist * r.Height;
+ var dash = new Pen(NotaPalette.Wash(NotaPalette.Accent, 0xA0), 1) { DashStyle = new DashStyle(new double[] { 3, 3 }, 0) };
+ ctx.DrawLine(dash, new Point(hx, frame.Y + 1), new Point(hx, frame.Bottom - 1));
+ ctx.DrawLine(dash, new Point(frame.X + 1, hy), new Point(frame.Right - 1, hy));
+ NotaGraph.Node(ctx, new Point(hx, hy), true);
+
+ // Captions.
+ string read = $"sym {(sym >= 0 ? "+" : "−")}{Math.Round(Math.Abs(sym) * 100)}\u2009% · dist {Math.Round(dist * 100)}\u2009%";
+ var title = Mono($"PICKUP · {KeysModel.ModelNames[model].ToUpperInvariant()}", NotaPalette.TextTertiary);
+ var readout = Mono(read, NotaPalette.AccentBright);
+ if (Mini)
+ {
+ ctx.DrawText(title, new Point(6, 4));
+ ctx.DrawText(readout, new Point(frame.Right - 6 - readout.Width, 4));
+ return;
+ }
+ ctx.DrawText(title, new Point(6, 4));
+ ctx.DrawText(readout, new Point(6, 15));
+
+ // H1–H8 of the curve driven by a sine (brass even, teal odd, the fundamental neutral).
+ var mags = KeysModel.Harmonics(sym, dist, model);
+ double bw = 6, gap = 3, ih = 34, iw = 8 * bw + 7 * gap + 10;
+ var inset = new Rect(frame.Right - iw - 8, frame.Bottom - ih - 6, iw, ih);
+ ctx.DrawRectangle(NotaGraph.Ground, NotaGraph.FramePen, new RoundedRect(inset, 3));
+ ctx.DrawText(Mono("H1–H8", NotaPalette.TextAxis, 7), new Point(inset.X + 4, inset.Y + 2));
+ for (int k = 0; k < 8; k++)
+ {
+ double db = 20 * Math.Log10(mags[k] / Math.Max(1e-9, mags[0]) + 1e-9);
+ double bh = Math.Max(1, (1 + db / 60) * (ih - 14));
+ IBrush ink = k == 0 ? NotaPalette.TextSecondary : k % 2 == 1 ? NotaPalette.TealBright : NotaPalette.Accent;
+ double x = inset.X + 5 + k * (bw + gap);
+ ctx.DrawRectangle(ink, null, new Rect(x, inset.Bottom - 3 - bh, bw, bh));
+ }
+ }
+
+ private void RenderString(DrawingContext ctx, Rect frame)
+ {
+ double x0 = frame.X + 24, x1 = frame.Right - 24, cy = frame.Y + frame.Height * 0.55;
+ double amp = frame.Height * 0.2;
+ double X(double t) => x0 + t * (x1 - x0);
+ ctx.DrawLine(NotaGraph.GridPen, new Point(frame.X + 1, cy), new Point(frame.Right - 1, cy));
+ StreamGeometry Shape(double sign)
+ {
+ var geo = new StreamGeometry();
+ using var g = geo.Open();
+ for (int i = 0; i <= 48; i++)
+ {
+ double t = i / 48.0, env = Math.Sin(Math.PI * t) * (1 - 0.65 * Math.Exp(-t * 6));
+ var p = new Point(X(t), cy - sign * amp * env * (sign > 0 ? 1 : 0.7));
+ if (i == 0) g.BeginFigure(p, false); else g.LineTo(p);
+ }
+ g.EndFigure(false);
+ return geo;
+ }
+ ctx.DrawGeometry(null, new Pen(NotaPalette.Accent, NotaGraph.PrimaryWidth, lineJoin: PenLineJoin.Round), Shape(1));
+ ctx.DrawGeometry(null, new Pen(NotaPalette.Wash(NotaPalette.TealBright, 0xB0), 1.2, lineJoin: PenLineJoin.Round), Shape(-1));
+ // Bridge / nut.
+ ctx.DrawRectangle(NotaPalette.TextSecondary, null, new Rect(x0 - 3, cy - 8, 3, 16));
+ ctx.DrawRectangle(NotaPalette.TextSecondary, null, new Rect(x1, cy - 8, 3, 16));
+ // The two pickups.
+ int pos = KeysModel.Index(G("pupos"), 3);
+ void Pickup(double t, string label, bool lit)
+ {
+ var rr = new Rect(X(t) - 8, cy + amp + 6, 16, 9);
+ ctx.DrawRectangle(lit ? NotaPalette.Accent : NotaPalette.BorderStrong, null, new RoundedRect(rr, 2));
+ var ft = Mono(label, lit ? NotaPalette.AccentBright : NotaPalette.TextAxis, 7);
+ ctx.DrawText(ft, new Point(X(t) - ft.Width / 2, rr.Bottom + 2));
+ }
+ Pickup(0.2, "UP", pos != 2);
+ Pickup(0.34, "LO", pos != 0);
+ ctx.DrawText(Mono("STRING · 2 PICKUPS", NotaPalette.TextTertiary), new Point(6, 4));
+ var read = Mono(KeysModel.PickupPositions[pos], NotaPalette.AccentBright);
+ if (Mini) ctx.DrawText(read, new Point(frame.Right - 6 - read.Width, 4));
+ else ctx.DrawText(read, new Point(6, 15));
+ }
+}
+
+internal sealed class KeysTremView : Control
+{
+ private readonly Func<string, float> _get; // a Keys param by id
+ private double _phase;
+
+ public KeysTremView(Func<string, float> get) { _get = get; MinHeight = 40; MinWidth = 100; }
+
+ /// <summary>The engine's tremolo LFO phase (0..1), from the scope.</summary>
+ public void SetPhase(double ph) { if (Math.Abs(ph - _phase) > 1e-4) { _phase = ph; InvalidateVisual(); } }
+
+ private static double Shape(double p) => Math.Tanh(2.2 * Math.Sin(p)) / Math.Tanh(2.2);
+
+ 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);
+ bool on = _get("tremon") >= 0.5f, stereo = _get("tremmode") >= 0.5f;
+ double depth = _get("tremdepth") * (on ? 1 : 0.15);
+ double barH = 12, cy = (h - barH) / 2 + 2, a = (h - barH) / 2 - 8;
+ using (ctx.PushClip(new RoundedRect(frame.Deflate(1), NotaGraph.Radius)))
+ {
+ ctx.DrawLine(NotaGraph.GridPen, new Point(1, cy), new Point(w - 1, cy));
+ StreamGeometry Line(double sign)
+ {
+ var geo = new StreamGeometry();
+ using var g = geo.Open();
+ for (int i = 0; i <= 96; i++)
+ {
+ double t = i / 96.0, p = 2 * Math.PI * (t * 2.25 + _phase);
+ var pt = new Point(4 + t * (w - 8), cy - sign * Shape(p) * a * depth);
+ if (i == 0) g.BeginFigure(pt, false); else g.LineTo(pt);
+ }
+ g.EndFigure(false);
+ return geo;
+ }
+ var ink = on ? NotaPalette.Accent : NotaPalette.BorderStrong;
+ if (stereo) ctx.DrawGeometry(null, new Pen(on ? NotaPalette.Teal : NotaPalette.BorderStrong, NotaGraph.SecondaryWidth, lineJoin: PenLineJoin.Round), Line(-1));
+ ctx.DrawGeometry(null, new Pen(ink, NotaGraph.PrimaryWidth, lineJoin: PenLineJoin.Round), Line(1));
+ ctx.DrawLine(new Pen(NotaPalette.TextAxis, 1), new Point(w * 0.33, 2), new Point(w * 0.33, h - barH - 2));
+ ctx.DrawText(NotaGraph.AxisText(stereo ? "L R" : "MONO"), new Point(6, 3));
+
+ // Where the sound sits: the pan dot (stereo) or the level (mono) at the playhead.
+ double s = Shape(2 * Math.PI * (0.33 * 2.25 + _phase)) * _get("tremdepth");
+ var bar = new Rect(8, h - barH + 1, w - 16, 6);
+ ctx.DrawRectangle(NotaPalette.BgSunken, NotaGraph.FramePen, new RoundedRect(bar, 3));
+ double pos = stereo && on ? 0.5 + s * 0.5 : 0.5;
+ double px = bar.X + pos * bar.Width;
+ ctx.DrawEllipse(on ? NotaPalette.AccentBright : NotaPalette.TextAxis, null, new Point(px, bar.Y + bar.Height / 2), 3, 3);
+ }
+ }
+}
+
+internal sealed class KeysVoiceGrid : Control
+{
+ private int _limit = 32, _held, _tail;
+ private const int Cols = 16, Rows = 4;
+
+ public KeysVoiceGrid() { Height = Rows * 6 - 1; }
+
+ public void Set(int limit, int held, int tail)
+ {
+ if (limit == _limit && held == _held && tail == _tail) return;
+ _limit = limit; _held = held; _tail = tail;
+ InvalidateVisual();
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double cw = Math.Floor((Bounds.Width + 1) / Cols) - 1;
+ if (cw <= 0) return;
+ for (int i = 0; i < Cols * Rows; i++)
+ {
+ int c = i % Cols, r = i / Cols;
+ IBrush ink = i >= _limit ? NotaPalette.BgSunken
+ : i < _held ? NotaPalette.Accent
+ : i < _held + _tail ? NotaPalette.AccentDeep
+ : NotaPalette.BorderDefault;
+ ctx.DrawRectangle(ink, null, new RoundedRect(new Rect(c * (cw + 1), r * 6, cw, 5), 1));
+ }
+ }
+}
diff --git a/src/managed/Nota.App/DeviceCards/InstrumentCardFactory.cs b/src/managed/Nota.App/DeviceCards/InstrumentCardFactory.cs
index 5c6c72d9..0553f2a6 100644
--- a/src/managed/Nota.App/DeviceCards/InstrumentCardFactory.cs
+++ b/src/managed/Nota.App/DeviceCards/InstrumentCardFactory.cs
@@ -28,6 +28,7 @@ internal sealed class InstrumentCardFactory
[13] = new MonolithInstrumentCard(),
[14] = new PentadInstrumentCard(),
[15] = new ConsortInstrumentCard(),
+ [16] = new KeysInstrumentCard(),
};
/// <summary>Resolve the editor for a built-in instrument kind. The Sampler (1) always
diff --git a/src/managed/Nota.App/DeviceCards/Instruments/KeysInstrumentCard.cs b/src/managed/Nota.App/DeviceCards/Instruments/KeysInstrumentCard.cs
new file mode 100644
index 00000000..7f207904
--- /dev/null
+++ b/src/managed/Nota.App/DeviceCards/Instruments/KeysInstrumentCard.cs
@@ -0,0 +1,576 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Detail · Devices — built-in Nota Keys editor (instrument kind 16), a build of the
+// "Nota Keys" mockup. Two sizes of one device; the S / L toggle in the shell header flips
+// them (the instrument's "view" param — see InstrumentView — a new Keys opens as L):
+//
+// • L 700 × 260, two tabs:
+// Sound HAMMER ▸ RESONATOR ▸ PICKUP (the curve — drag X = symmetry, Y = distance,
+// H1–H8 of what it does to a sine; Clav shows its string and two pickups) ▸
+// DAMPER (+ the pedal, lit by the Pedal param or a keyboard's CC64), with the
+// model chips in the tab strip and a PLAY rail (tune / age / stretch, the voice
+// pool and the meter) on the right.
+// FX PREAMP ▸ TREMOLO (its L / R gains scrolling with the engine's LFO) ▸ PHASER
+// ▸ CHORUS ▸ CABINET ▸ OUTPUT — each with its power dot; the chain in words
+// sits in the tab strip.
+// • S 260 × 260 — the model chips, the pickup window, HARD · PICKUP · DRIVE · TREM.
+//
+// Brass is the parameter itself; teal is modulation depth (vel → hardness, key → bright,
+// tremolo depth). BodyOnly — the shared shell draws the header (name / preset / A-B / MPE).
+
+using System;
+using System.Collections.Generic;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Controls.Shapes;
+using Avalonia.Input;
+using Avalonia.Layout;
+using Avalonia.Media;
+using Nota.Application;
+using static Nota.App.DeviceCardKit;
+
+namespace Nota.App;
+
+internal sealed class KeysInstrumentCard : IInstrumentCard
+{
+ public bool BodyOnly => true;
+ public string Subtitle => "ELECTRIC PIANO";
+
+ public double WidthFor(IAudioEngine engine, int trackId) => InstrumentView.IsMini(engine, trackId) ? 260 : 700;
+
+ public Control? HeaderAccessory(DeviceCardContext ctx)
+ {
+ var e = ctx.Engine; int t = ctx.TrackId;
+ if (InstrumentView.Index(e, t) < 0) return null;
+ var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center };
+ if (!InstrumentView.IsMini(e, t)) row.Children.Add(MidiCardHeader.LearnButton(ctx));
+ row.Children.Add(MidiCardHeader.SizeToggle(ctx, () => InstrumentView.IsMini(e, t), m => InstrumentView.SetMini(e, t, m)));
+ return row;
+ }
+
+ public string? VoiceLabel(IAudioEngine engine, int trackId, int active)
+ {
+ int pc = engine.PluginParamCount(trackId, -1);
+ for (int i = 0; i < pc; i++)
+ if (engine.PluginParamId(trackId, -1, i) == "voices")
+ return $"{Math.Max(0, active)}/{KeysModel.VoiceCounts[KeysModel.Index(engine.PluginParamGet(trackId, -1, i), 4)]}";
+ return null;
+ }
+
+ private const double TabH = 20, StatusH = 18, RailW = 142;
+ private static readonly string[] TabNames = { "Sound", "FX" };
+ private static readonly Dictionary<int, int> OpenTab = new(); // per track, survives a rebuild
+
+ private static string Signed(double v, string unit) => $"{(v >= 0.5 ? "+" : v <= -0.5 ? "−" : "")}{Math.Round(Math.Abs(v))}\u2009{unit}";
+ private static string PanText(float v)
+ {
+ int p = (int)Math.Round((v - 0.5f) * 200);
+ return p == 0 ? "C" : p < 0 ? $"{-p} L" : $"{p} R";
+ }
+ private static string NoiseText(float v) => KeysModel.NoiseDb(v) is { } db ? NotaNum.Db(db) : "off";
+ private static string VolText(float v) => KeysModel.VolumeDb(v) is { } db ? NotaNum.Db(db) : "−∞\u2009dB";
+
+ public Control Build(DeviceCardContext ctx)
+ {
+ var engine = ctx.Engine;
+ int track = ctx.TrackId;
+ 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;
+ void SetP(string id, float v) { if (I(id) is var i and >= 0) engine.PluginParamSet(track, -1, i, Math.Clamp(v, 0f, 1f)); }
+ int Sel(string id, int n) => KeysModel.Index(G(id), n);
+ bool On(string id) => G(id) >= 0.5f;
+
+ bool mini = InstrumentView.IsMini(engine, track);
+ var readouts = new List<Action>();
+ var scope = new float[KeysModel.ScopeLength];
+ int Sc(int k) => (int)Math.Round(scope[k]);
+ void ReadScope() { Array.Clear(scope); engine.InstrumentScope(track, scope); }
+
+ var pickup = new KeysPickupView(engine, track, idx) { Mini = mini };
+ var status = new TextBlock { FontSize = 8, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };
+ var meta = new TextBlock { FontSize = 8, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center };
+ meta.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");
+ int tab = OpenTab.TryGetValue(track, out var ot) ? ot : 0;
+
+ void Refresh()
+ {
+ pickup.Refresh();
+ foreach (var a in readouts) a();
+ }
+ ctx.SetInstLiveViz(Refresh);
+ pickup.Changed += Refresh;
+
+ // ---- shared builders --------------------------------------------------
+ Control Knob(string id, string name, Func<float, string> fmt, double size = 28, double cellW = 46, IBrush? arc = null)
+ => InstrumentControls.InstKnob(ctx, idx, id, name, Refresh, fmt, size, cellW, arc);
+
+ Border Chips(string id, string[] names, bool fill = false, Action<int>? after = null, Func<bool>? dim = null, double padX = 6)
+ {
+ int n = names.Length;
+ var seg = Segments(names, () => Sel(id, n), iv => { SetP(id, iv / (float)(n - 1)); after?.Invoke(iv); Refresh(); }, out var sync, fill: fill, dim: dim, padX: padX);
+ readouts.Add(sync);
+ if (I(id) is var pi and >= 0) MidiLearn.Bind(seg, MidiTarget.PluginParam(track, -1, pi), id);
+ return seg;
+ }
+
+ // Picking a model resets the pickup it was voiced with and its usual cabinet.
+ void ModelPicked(int m)
+ {
+ var (sym, dist, cab) = KeysModel.ModelDefaults(m);
+ SetP("sym", (float)((sym + 1) / 2)); SetP("dist", (float)dist); SetP("cab", cab / 3f);
+ }
+ Border ModelChips(bool fill) => Chips("model", fill ? KeysModel.ModelShort : KeysModel.ModelNames, fill, ModelPicked, padX: fill ? 6 : 5);
+
+ static TextBlock Caps(string text, IBrush? ink = null) => new()
+ {
+ Text = text.ToUpperInvariant(), FontSize = NotaType.KnobLabel, FontWeight = FontWeight.Bold,
+ LetterSpacing = NotaType.KnobLabelTracking, Foreground = ink ?? TextTertiary, VerticalAlignment = VerticalAlignment.Center,
+ };
+
+ // A section's power dot: brass and glowing when on. Click toggles the param.
+ Control PowerDot(string id)
+ {
+ var dot = new Ellipse { Width = 7, Height = 7, VerticalAlignment = VerticalAlignment.Center };
+ var host = new Border { Background = Brushes.Transparent, Padding = new Thickness(2), Cursor = new Cursor(StandardCursorType.Hand), Child = dot, VerticalAlignment = VerticalAlignment.Center };
+ void Paint()
+ {
+ bool on = On(id);
+ dot.Fill = on ? NotaPalette.Accent : NotaPalette.BorderStrong;
+ host.Effect = on ? new DropShadowEffect { Color = NotaPalette.AccentColor, BlurRadius = 5, OffsetX = 0, OffsetY = 0 } : null;
+ }
+ host.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(host).Properties.IsLeftButtonPressed) return;
+ SetP(id, On(id) ? 0f : 1f); Paint(); Refresh(); e.Handled = true;
+ };
+ if (I(id) is var pi and >= 0) MidiLearn.Bind(host, MidiTarget.PluginParam(track, -1, pi), id);
+ readouts.Add(Paint);
+ Paint();
+ return host;
+ }
+
+ // Dim every knob in a cell list while its section is off (they stay editable).
+ void DimWhen(Func<bool> off, params Control[] cells)
+ {
+ var knobs = new List<Knob>();
+ foreach (var c in cells) if (FindKnob(c) is { } k) knobs.Add(k);
+ readouts.Add(() => { bool d = off(); foreach (var k in knobs) k.IsDim = d; });
+ }
+
+ Grid Slider(string label, string id, Func<string> text, bool bipolar = false)
+ {
+ int pi = I(id);
+ var row = SliderRow(label, () => G(id), v => { SetP(id, (float)v); Refresh(); }, text, out var sync,
+ begin: pi >= 0 ? () => engine.BeginAutomationWrite(track, AutomationTarget.PluginParam, -1, -1, id) : null,
+ end: pi >= 0 ? () => engine.EndAutomationWrite(track, AutomationTarget.PluginParam, -1, -1, id) : null,
+ reset: pi >= 0 ? () => { SetP(id, engine.InstrumentParamDefault(track, pi)); Refresh(); } : null,
+ bipolar: bipolar, labelWidth: 46, valueWidth: 28);
+ readouts.Add(sync);
+ if (pi >= 0) MidiLearn.Bind(row, MidiTarget.PluginParam(track, -1, pi), id);
+ return row;
+ }
+
+ // ---- status strip ------------------------------------------------------
+ string PedalWord() => Sc(KeysModel.ScPedal) > 0 ? "pedal ↓" : "pedal —";
+ string SoundLine()
+ {
+ int m = Sel("model", 4);
+ string pu = m == 3 ? KeysModel.PickupPositions[Sel("pupos", 3)]
+ : $"pickup {NotaNum.Pct(G("dist"))} / {Signed(KeysModel.Bipolar(G("sym")) * 100, "%")}";
+ return $"{KeysModel.ModelNames[m]} · hard {NotaNum.Pct(G("hard"))} · {pu} · damper {NotaNum.Pct(G("damper"))} · {PedalWord()}";
+ }
+ string FxLine()
+ {
+ string pre = On("preon") ? $"preamp {NotaNum.Pct(G("drive"))}" : "preamp off";
+ string trem = On("tremon") ? $"trem {KeysModel.TremModes[Sel("tremmode", 2)].ToLowerInvariant()} {KeysModel.TremRateText(G)} {NotaNum.Pct(G("tremdepth"))}" : "trem off";
+ string ph = On("phaseron") ? $"phaser {KeysModel.PhaserHz(G("phaserrate")):0.0#}\u2009Hz" : "phaser off";
+ string ch = On("choruson") ? $"chorus {NotaNum.Pct(G("chorusmix"))}" : "chorus off";
+ return $"{pre} · {trem} · {ph} · {ch} · cab {KeysModel.CabNames[Sel("cab", 4)]}";
+ }
+ string VoicesText() => $"{Sc(KeysModel.ScActive)} / {KeysModel.VoiceCounts[Sel("voices", 4)]}";
+ double sr = engine.SampleRate > 0 ? engine.SampleRate : 48000;
+ string Rate() => $"{sr / 1000:0.#}\u2009kHz";
+
+ var meterOut = new TextBlock { FontSize = 8, Foreground = TextSecondary };
+ ctx.AddDeviceRefresher(() =>
+ {
+ ReadScope();
+ status.Text = mini ? $"{KeysModel.ModelNames[Sel("model", 4)]} · {VoicesText()} · {PedalWord()}"
+ : tab == 0 ? SoundLine() : FxLine();
+ if (engine.TryGetTrackMeter(track, out var mt))
+ {
+ double pk = Math.Max(mt.PeakL, mt.PeakR);
+ meterOut.Text = pk > 1e-6 ? $"out {NotaNum.Db(AudioMath.LinToDb((float)pk))}" : "out −∞\u2009dB";
+ }
+ meta.Text = mini ? meterOut.Text : $"{Rate()} · {VoicesText()} voices";
+ });
+
+ if (mini) return BuildMini(ctx, pickup, ModelChips(true), Knob, status, meta, Refresh);
+
+ // ======================= SOUND tab ======================================
+ Control Col(string title, Control body, double width, Control? accessory = null)
+ {
+ var head = new DockPanel { Height = 14, Margin = new Thickness(0, 0, 0, 3) };
+ if (accessory is not null) { DockPanel.SetDock(accessory, Dock.Right); head.Children.Add(accessory); }
+ head.Children.Add(Caps(title));
+ var dp = new DockPanel { Width = width };
+ DockPanel.SetDock(head, Dock.Top);
+ dp.Children.Add(head); dp.Children.Add(body);
+ return dp;
+ }
+ static Control Arrow() => new Glyph(GlyphKind.ChevronRight, 8)
+ {
+ Foreground = NotaPalette.BorderStrong, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(2, 0),
+ };
+ static StackPanel VStack(params Control[] cs)
+ {
+ var sp = new StackPanel { Spacing = 1, VerticalAlignment = VerticalAlignment.Center };
+ foreach (var c in cs) { c.HorizontalAlignment = HorizontalAlignment.Center; sp.Children.Add(c); }
+ return sp;
+ }
+ static Grid Grid2(params Control[] cs)
+ {
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*"), RowDefinitions = new RowDefinitions("Auto,Auto"), RowSpacing = 10, VerticalAlignment = VerticalAlignment.Center };
+ for (int i = 0; i < cs.Length; i++) { cs[i].HorizontalAlignment = HorizontalAlignment.Center; Grid.SetColumn(cs[i], i % 2); Grid.SetRow(cs[i], i / 2); g.Children.Add(cs[i]); }
+ return g;
+ }
+
+ var hammer = Col("Hammer", VStack(
+ Knob("hard", "Hard", v => NotaNum.Pct(v), size: 24),
+ Knob("velhard", "Vel→H", v => NotaNum.Pct(v), size: 24, arc: Teal),
+ Knob("noise", "Noise", NoiseText, size: 24)), 46);
+
+ var reso = Col("Resonator", Grid2(
+ Knob("decay", "Decay", v => NotaNum.Pct(KeysModel.DecayPct(v) / 100)),
+ Knob("body", "Body", v => NotaNum.Pct(v)),
+ Knob("bright", "Bright", v => NotaNum.Pct(v)),
+ Knob("keybright", "Key→Br", v => Signed(KeysModel.Bipolar(v) * 100, "%"), arc: Teal)), 94);
+
+ // PICKUP: the graph, with the bark readout (or, for Clav, the pickup chips) on its header.
+ var bark = new TextBlock { FontSize = 8, Foreground = NotaPalette.TealBright, VerticalAlignment = VerticalAlignment.Center };
+ bark.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");
+ var puChips = Chips("pupos", KeysModel.PickupPositions, padX: 4);
+ var puAcc = new Panel { Children = { bark, puChips } };
+ readouts.Add(() =>
+ {
+ int m = Sel("model", 4);
+ bool clav = m == 3;
+ puChips.IsVisible = clav; bark.IsVisible = !clav;
+ if (!clav) bark.Text = $"bark H2 {KeysModel.BarkDb(KeysModel.Bipolar(G("sym")), G("dist"), m):0}\u2009dB";
+ });
+ var pickupCol = new DockPanel();
+ {
+ var head = new DockPanel { Height = 14, Margin = new Thickness(0, 0, 0, 3) };
+ DockPanel.SetDock(puAcc, Dock.Right); head.Children.Add(puAcc);
+ head.Children.Add(Caps("Pickup"));
+ DockPanel.SetDock(head, Dock.Top);
+ pickupCol.Children.Add(head); pickupCol.Children.Add(pickup);
+ }
+
+ // DAMPER + the pedal.
+ var pedalDot = new Ellipse { Width = 6, Height = 6, VerticalAlignment = VerticalAlignment.Center };
+ var pedalTxt = new TextBlock { Text = "CC64", FontSize = 8, VerticalAlignment = VerticalAlignment.Center };
+ pedalTxt.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");
+ var pedalPill = new Border
+ {
+ CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), Padding = new Thickness(5, 1),
+ Cursor = new Cursor(StandardCursorType.Hand), Background = Brushes.Transparent, HorizontalAlignment = HorizontalAlignment.Center,
+ Child = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, Children = { pedalDot, pedalTxt } },
+ };
+ var pedalLbl = Caps("Pedal");
+ pedalLbl.HorizontalAlignment = HorizontalAlignment.Center;
+ pedalPill.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(pedalPill).Properties.IsLeftButtonPressed) return;
+ SetP("pedal", On("pedal") ? 0f : 1f); Refresh(); e.Handled = true;
+ };
+ if (I("pedal") is var pedI and >= 0) MidiLearn.Bind(pedalPill, MidiTarget.PluginParam(track, -1, pedI), "Damper Pedal");
+ ToolTip.SetTip(pedalPill, "Sustain pedal — click to hold it down; a keyboard's CC64 works too");
+ ctx.AddDeviceRefresher(() =>
+ {
+ bool down = Sc(KeysModel.ScPedal) > 0 || On("pedal");
+ pedalDot.Fill = down ? NotaPalette.Success : NotaPalette.BorderStrong;
+ pedalPill.BorderBrush = down ? NotaPalette.Success : BorderDef;
+ pedalTxt.Foreground = down ? TextPrimary : TextTertiary;
+ pedalLbl.Text = down ? "PEDAL ↓" : "PEDAL";
+ pedalLbl.Foreground = down ? TextPrimary : TextTertiary;
+ });
+ var damper = Col("Damper", VStack(
+ Knob("damper", "Damper", v => NotaNum.Pct(v), size: 26),
+ Knob("relnoise", "Rel N", NoiseText, size: 24),
+ new StackPanel { Spacing = 3, Children = { pedalPill, pedalLbl } }), 52);
+
+ var soundRow = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,Auto,Auto,*,Auto,Auto"), Margin = new Thickness(7, 5, 7, 6) };
+ Control[] soundCells = { hammer, Arrow(), reso, Arrow(), pickupCol, Arrow(), damper };
+ for (int i = 0; i < soundCells.Length; i++) { Grid.SetColumn(soundCells[i], i); soundRow.Children.Add(soundCells[i]); }
+
+ // ======================= FX tab =========================================
+ Border Island(string title, Control body, string? power = null, Control? accessory = null, double width = double.NaN)
+ {
+ var head = new DockPanel { Height = 18, Margin = new Thickness(6, 0) };
+ if (accessory is not null) { DockPanel.SetDock(accessory, Dock.Right); head.Children.Add(accessory); }
+ var left = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, VerticalAlignment = VerticalAlignment.Center };
+ if (power is not null) left.Children.Add(PowerDot(power));
+ var tl = Caps(title, power is null ? TextTertiary : TextPrimary);
+ if (power is not null) readouts.Add(() => tl.Foreground = On(power) ? TextPrimary : TextTertiary);
+ left.Children.Add(tl);
+ head.Children.Add(left);
+ var grid = new Grid { RowDefinitions = new RowDefinitions("Auto,*") };
+ grid.Children.Add(new Border { BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 0, 0, 1), Child = head });
+ body.Margin = new Thickness(5, 5, 5, 5);
+ Grid.SetRow(body, 1); grid.Children.Add(body);
+ var b = new Border
+ {
+ Background = NotaPalette.SurfaceCard, BorderBrush = BorderDef, BorderThickness = new Thickness(1),
+ CornerRadius = NotaRadius.Tile, ClipToBounds = true, Child = grid,
+ };
+ if (!double.IsNaN(width)) b.Width = width;
+ return b;
+ }
+
+ var driveK = Knob("drive", "Drive", v => NotaNum.Pct(v), size: 34, cellW: 50);
+ var bassK = Knob("bass", "Bass", v => Signed(KeysModel.ShelfDb(v), "dB"), size: 24, cellW: 34);
+ var trebK = Knob("treble", "Treble", v => Signed(KeysModel.ShelfDb(v), "dB"), size: 24, cellW: 34);
+ DimWhen(() => !On("preon"), driveK, bassK, trebK);
+ var preamp = Island("Preamp", new StackPanel
+ {
+ Spacing = 4, VerticalAlignment = VerticalAlignment.Center,
+ Children = { Center(driveK), new StackPanel { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Center, Children = { bassK, trebK } } },
+ }, "preon", width: 80);
+
+ var tremView = new KeysTremView(G);
+ ctx.AddDeviceRefresher(() => tremView.SetPhase(scope[KeysModel.ScLfo]));
+ var rateK = Knob("tremrate", "Rate", _ => KeysModel.TremRateText(G));
+ var depthK = Knob("tremdepth", "Depth", v => NotaNum.Pct(v), arc: Teal);
+ DimWhen(() => !On("tremon"), rateK, depthK);
+ var syncSeg = Chips("tremsync", KeysModel.TremSyncs, padX: 4);
+ var syncCell = new StackPanel { Spacing = 3, VerticalAlignment = VerticalAlignment.Center, Children = { syncSeg, Center(Caps("Sync")) } };
+ readouts.Add(() => tremView.InvalidateVisual());
+ var tremBody = new Grid { RowDefinitions = new RowDefinitions("*,Auto"), RowSpacing = 4 };
+ tremBody.Children.Add(tremView);
+ var tremKnobs = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, HorizontalAlignment = HorizontalAlignment.Center, Children = { rateK, depthK, syncCell } };
+ Grid.SetRow(tremKnobs, 1); tremBody.Children.Add(tremKnobs);
+ var trem = Island("Tremolo", tremBody, "tremon", Chips("tremmode", KeysModel.TremModes, padX: 4));
+
+ var phRate = Knob("phaserrate", "Rate", v => $"{KeysModel.PhaserHz(v):0.0#}\u2009Hz");
+ var phDepth = Knob("phaserdepth", "Depth", v => NotaNum.Pct(v));
+ DimWhen(() => !On("phaseron"), phRate, phDepth);
+ var phaser = Island("Phaser", VStack(phRate, phDepth), "phaseron", width: 62);
+
+ var chMix = Knob("chorusmix", "Mix", v => NotaNum.Pct(v));
+ DimWhen(() => !On("choruson"), chMix);
+ var chNote = new TextBlock { Text = "2 lines · BBD", FontSize = 7, Foreground = NotaPalette.TextAxis, HorizontalAlignment = HorizontalAlignment.Center };
+ var chorus = Island("Chorus", VStack(chMix, chNote), "choruson", width: 62);
+
+ var cabList = new StackPanel { Spacing = 3, VerticalAlignment = VerticalAlignment.Center };
+ var cabCells = new List<(Border B, TextBlock T)>();
+ for (int c = 0; c < KeysModel.CabNames.Length; c++)
+ {
+ int cv = c;
+ var tb = new TextBlock { Text = KeysModel.CabNames[c], FontSize = 8, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };
+ var cell = new Border { Height = 15, CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), Cursor = new Cursor(StandardCursorType.Hand), Child = tb };
+ cell.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(cell).Properties.IsLeftButtonPressed) return;
+ SetP("cab", cv / 3f); Refresh(); e.Handled = true;
+ };
+ cabCells.Add((cell, tb)); cabList.Children.Add(cell);
+ }
+ if (I("cab") is var cabI and >= 0) MidiLearn.Bind(cabList, MidiTarget.PluginParam(track, -1, cabI), "Cabinet Type");
+ var cabNote = new TextBlock { FontSize = 7, Foreground = NotaPalette.TextAxis, HorizontalAlignment = HorizontalAlignment.Center, Margin = new Thickness(0, 3, 0, 0) };
+ cabList.Children.Add(cabNote);
+ readouts.Add(() =>
+ {
+ int cur = Sel("cab", 4);
+ for (int c = 0; c < cabCells.Count; c++)
+ {
+ bool on = c == cur;
+ cabCells[c].B.Background = on ? Brass : NotaPalette.BgSunken;
+ cabCells[c].B.BorderBrush = on ? Brass : BorderDef;
+ cabCells[c].T.Foreground = on ? OnAccent : TextTertiary;
+ cabCells[c].T.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;
+ }
+ cabNote.Text = KeysModel.CabNotes[cur];
+ });
+ var cabinet = Island("Cabinet", cabList, width: 72);
+
+ var outMeter = new MeterBar { VerticalAlignment = VerticalAlignment.Stretch, Width = MeterScale.StereoWidth };
+ ctx.AddDeviceRefresher(() => { if (engine.TryGetTrackMeter(track, out var m)) outMeter.Push(m); });
+ var outKnobs = VStack(Knob("volume", "Volume", VolText, size: 30), Knob("pan", "Pan", PanText, size: 24));
+ var outBody = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 6 };
+ outBody.Children.Add(outKnobs);
+ Grid.SetColumn(outMeter, 1); outBody.Children.Add(outMeter);
+ var output = Island("Output", outBody, width: 92);
+
+ var fxRow = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*,Auto,Auto,Auto,Auto,Auto,Auto,Auto,Auto"), Margin = new Thickness(6, 5, 6, 6) };
+ Control[] fxCells = { preamp, Arrow(), trem, Arrow(), phaser, Arrow(), chorus, Arrow(), cabinet, Arrow(), output };
+ for (int i = 0; i < fxCells.Length; i++) { Grid.SetColumn(fxCells[i], i); fxRow.Children.Add(fxCells[i]); }
+
+ // ======================= PLAY rail (Sound tab) ==========================
+ var voicesChips = Chips("voices", KeysModel.VoiceNames, padX: 3);
+ var grid = new KeysVoiceGrid { Margin = new Thickness(0, 2, 0, 0) };
+ var voicesLine = new TextBlock { FontSize = 8, Foreground = TextPrimary };
+ voicesLine.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");
+ var pedalLine = new TextBlock { FontSize = 7, Foreground = NotaPalette.TextAxis };
+ ctx.AddDeviceRefresher(() =>
+ {
+ int limit = KeysModel.VoiceCounts[Sel("voices", 4)];
+ int held = Sc(KeysModel.ScHeld), sus = Sc(KeysModel.ScSustained), act = Sc(KeysModel.ScActive);
+ grid.Set(limit, held, Math.Max(0, act - held));
+ voicesLine.Text = $"{act} / {limit} voices";
+ pedalLine.Text = sus > 0 ? $"{sus} held by the pedal" : act > held ? $"{act - held} ringing out" : "";
+ });
+ var railMeter = new MeterBar { VerticalAlignment = VerticalAlignment.Stretch, Width = MeterScale.StereoWidth };
+ ctx.AddDeviceRefresher(() => { if (engine.TryGetTrackMeter(track, out var m)) railMeter.Push(m); });
+ var voiceInfo = new StackPanel { Spacing = 2, VerticalAlignment = VerticalAlignment.Bottom, Children = { voicesLine, pedalLine } };
+ var railBottom = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 6 };
+ railBottom.Children.Add(voiceInfo);
+ Grid.SetColumn(railMeter, 1); railBottom.Children.Add(railMeter);
+ var voicesRow = new DockPanel();
+ var vLbl = new TextBlock { Text = "VOICES", FontSize = NotaType.RowLabel, FontWeight = FontWeight.Bold, LetterSpacing = NotaType.RowLabelTracking, Foreground = TextTertiary, VerticalAlignment = VerticalAlignment.Center };
+ DockPanel.SetDock(vLbl, Dock.Left); voicesRow.Children.Add(vLbl);
+ voicesChips.HorizontalAlignment = HorizontalAlignment.Right; voicesRow.Children.Add(voicesChips);
+ var railTop = new StackPanel
+ {
+ Spacing = 5,
+ Children =
+ {
+ Slider("Tune", "tune", () => $"{Math.Round(KeysModel.TuneCents(G("tune"))):+0;−0;0}\u2009c", bipolar: true),
+ Slider("Age", "age", () => NotaNum.Pct(G("age"))),
+ Slider("Stretch", "stretch", () => NotaNum.Pct(G("stretch"))),
+ voicesRow, grid,
+ },
+ };
+ var railBody = new Grid { RowDefinitions = new RowDefinitions("Auto,*"), RowSpacing = 4, Margin = new Thickness(7, 5, 7, 6) };
+ railBody.Children.Add(railTop);
+ Grid.SetRow(railBottom, 1); railBody.Children.Add(railBottom);
+ var railHead = new DockPanel { Height = TabH, Margin = new Thickness(8, 0) };
+ var railHeadTxt = Caps("Play");
+ railHead.Children.Add(railHeadTxt);
+ var railGrid = new Grid { RowDefinitions = new RowDefinitions("Auto,*") };
+ railGrid.Children.Add(new Border { BorderBrush = BorderDef, BorderThickness = new Thickness(0, 0, 0, 1), Child = railHead });
+ Grid.SetRow(railBody, 1); railGrid.Children.Add(railBody);
+ var rail = SectionBox(railGrid);
+ rail.Width = RailW;
+
+ // ======================= tabs ===========================================
+ var tabCells = new Border[TabNames.Length];
+ var tabTexts = new TextBlock[TabNames.Length];
+ var tabRow = new StackPanel { Orientation = Orientation.Horizontal };
+ var modelChips = ModelChips(false);
+ var chain = new TextBlock { FontSize = NotaType.Axis, Foreground = TextTertiary, VerticalAlignment = VerticalAlignment.Center };
+ chain.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");
+ readouts.Add(() =>
+ chain.Text = $"{(On("preon") ? "preamp" : "—")} → {(On("tremon") ? "trem" : "—")} → {(On("phaseron") ? "phaser" : "—")} → "
+ + $"{(On("choruson") ? "chorus" : "—")} → {KeysModel.CabNames[Sel("cab", 4)]}");
+ var tabRight = new Panel { HorizontalAlignment = HorizontalAlignment.Right, Margin = new Thickness(0, 0, 6, 0), Children = { modelChips, chain } };
+ var tabStrip = new Grid { Height = TabH, ColumnDefinitions = new ColumnDefinitions("Auto,*"), Background = Brushes.Transparent };
+ tabStrip.Children.Add(tabRow);
+ Grid.SetColumn(tabRight, 1); tabStrip.Children.Add(tabRight);
+ var bodyHost = new Panel { Children = { soundRow, fxRow } };
+
+ void ShowTab()
+ {
+ OpenTab[track] = tab;
+ 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;
+ }
+ soundRow.IsVisible = tab == 0; fxRow.IsVisible = tab == 1;
+ modelChips.IsVisible = tab == 0; chain.IsVisible = tab == 1;
+ rail.IsVisible = tab == 0;
+ Refresh();
+ }
+ 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(9, 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 tabPanel = SectionBox(new Grid { RowDefinitions = new RowDefinitions("Auto,*") });
+ var tg = (Grid)tabPanel.Child!;
+ tg.Children.Add(new Border { BorderBrush = BorderDef, BorderThickness = new Thickness(0, 0, 0, 1), Child = tabStrip });
+ Grid.SetRow(bodyHost, 1); tg.Children.Add(bodyHost);
+
+ 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);
+
+ var statusHost = StatusStrip(status, meta);
+ DockPanel.SetDock(statusHost, Dock.Bottom);
+ var root = new DockPanel { LastChildFill = true, Background = NotaPalette.Gutter, Children = { statusHost, body } };
+ ShowTab();
+ return root;
+ }
+
+ private static Control Center(Control c) { c.HorizontalAlignment = HorizontalAlignment.Center; return c; }
+
+ // ---- S: the mini card -------------------------------------------------------
+ private static Control BuildMini(DeviceCardContext ctx, KeysPickupView pickup, Border modelChips,
+ Func<string, string, Func<float, string>, double, double, IBrush?, Control> knob,
+ TextBlock status, TextBlock meta, Action refresh)
+ {
+ var cells = new[]
+ {
+ knob("hard", "Hard", v => NotaNum.Pct(v), 30, 54, null),
+ knob("dist", "Pickup", v => NotaNum.Pct(v), 30, 54, null),
+ knob("drive", "Drive", v => NotaNum.Pct(v), 30, 54, null),
+ knob("tremdepth", "Trem", v => NotaNum.Pct(v), 30, 54, Teal),
+ };
+ var knobRow = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*,*,*") };
+ for (int i = 0; i < cells.Length; i++)
+ {
+ cells[i].HorizontalAlignment = HorizontalAlignment.Center;
+ Grid.SetColumn(cells[i], i); knobRow.Children.Add(cells[i]);
+ }
+ modelChips.HorizontalAlignment = HorizontalAlignment.Stretch;
+ var inner = new Grid { RowDefinitions = new RowDefinitions("Auto,*,Auto"), RowSpacing = 5, Margin = new Thickness(6, 6, 6, 4) };
+ inner.Children.Add(modelChips);
+ Grid.SetRow(pickup, 1); inner.Children.Add(pickup);
+ Grid.SetRow(knobRow, 2); inner.Children.Add(knobRow);
+ var island = SectionBox(inner);
+ island.Margin = new Thickness(NotaSpace.DeviceGap);
+
+ var statusHost = StatusStrip(status, meta);
+ DockPanel.SetDock(statusHost, Dock.Bottom);
+ var root = new DockPanel { LastChildFill = true, Background = NotaPalette.Gutter, Children = { statusHost, island } };
+ refresh();
+ return root;
+ }
+
+ private static Border StatusStrip(TextBlock status, TextBlock meta)
+ {
+ var bar = new Grid { Height = StatusH, ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 10, Background = NotaPalette.SurfaceAbyss };
+ bar.Children.Add(status);
+ Grid.SetColumn(meta, 1); bar.Children.Add(meta);
+ return new Border
+ {
+ Height = StatusH, BorderBrush = BorderDef, BorderThickness = new Thickness(0, 1, 0, 0),
+ Background = NotaPalette.SurfaceAbyss, Padding = new Thickness(8, 0), Child = bar,
+ };
+ }
+
+ private static Border SectionBox(Control child) => new()
+ {
+ Background = NotaPalette.SurfaceCard, BorderBrush = BorderDef, BorderThickness = new Thickness(1),
+ CornerRadius = NotaRadius.Tile, ClipToBounds = true, Child = child,
+ };
+
+ private static Knob? FindKnob(Control cell)
+ => cell is Panel p ? System.Linq.Enumerable.FirstOrDefault(System.Linq.Enumerable.OfType<Knob>(p.Children)) : null;
+}
diff --git a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.Drum.cs b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.Drum.cs
index fd933205..0da706df 100644
--- a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.Drum.cs
+++ b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.Drum.cs
@@ -812,6 +812,7 @@ internal sealed partial class RackCardView
Add("Nota Monolith", 13);
Add("Nota Pentad", 14);
Add("Nota Consort", 15);
+ Add("Nota Keys", 16);
f.ShowAt(anchor, showAtPointer: true);
}
diff --git a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs
index 081e48fd..91414c08 100644
--- a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs
+++ b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs
@@ -623,7 +623,7 @@ internal sealed partial class RackCardView(DeviceCardContext ctx)
var f = new MenuFlyout();
void Add(string h, int k) { var mi = new MenuItem { Header = h }; mi.Click += (_, _) => { int c = a.AddChain(k); if (c >= 0) Sel = c; _ctx.RequestRebuild(); }; f.Items.Add(mi); }
Add("Nota Synth", 0); Add("Nota Sampler", 1); Add("Nota Physical", 2); Add("Nota Aurora", 5);
- Add("Nota Volt", 6); Add("Nota Bass", 7); Add("Nota Pendulum", 8); Add("Nota Operator", 9); Add("Nota Grain", 10); Add("Nota Flux", 11); Add("Nota Monolith", 13); Add("Nota Pentad", 14); Add("Nota Consort", 15);
+ Add("Nota Volt", 6); Add("Nota Bass", 7); Add("Nota Pendulum", 8); Add("Nota Operator", 9); Add("Nota Grain", 10); Add("Nota Flux", 11); Add("Nota Monolith", 13); Add("Nota Pentad", 14); Add("Nota Consort", 15); Add("Nota Keys", 16);
f.ShowAt(anchor, showAtPointer: true);
}
@@ -1495,7 +1495,9 @@ internal sealed partial class RackCardView(DeviceCardContext ctx)
pd.Click += (_, _) => { a.AddChain(14); _ctx.RequestRebuild(); };
var co = new MenuItem { Header = "Nota Consort" };
co.Click += (_, _) => { a.AddChain(15); _ctx.RequestRebuild(); };
- f.Items.Add(s); f.Items.Add(p); f.Items.Add(w); f.Items.Add(vo); f.Items.Add(ba); f.Items.Add(pe); f.Items.Add(op); f.Items.Add(gr); f.Items.Add(fl); f.Items.Add(mo); f.Items.Add(pd); f.Items.Add(co);
+ var ke = new MenuItem { Header = "Nota Keys" };
+ ke.Click += (_, _) => { a.AddChain(16); _ctx.RequestRebuild(); };
+ f.Items.Add(s); f.Items.Add(p); f.Items.Add(w); f.Items.Add(vo); f.Items.Add(ba); f.Items.Add(pe); f.Items.Add(op); f.Items.Add(gr); f.Items.Add(fl); f.Items.Add(mo); f.Items.Add(pd); f.Items.Add(co); f.Items.Add(ke);
f.ShowAt(b, showAtPointer: true);
};
return b;
diff --git a/src/managed/Nota.App/NotaDocs.cs b/src/managed/Nota.App/NotaDocs.cs
index d2c19797..76b5dd53 100644
--- a/src/managed/Nota.App/NotaDocs.cs
+++ b/src/managed/Nota.App/NotaDocs.cs
@@ -23,6 +23,7 @@ internal static class NotaDocs
"racks/drum-rack", "instruments/aurora", "instruments/volt", "instruments/bass",
"instruments/pendulum", "instruments/operator", "instruments/grain", "instruments/flux",
"instruments/rhythm", "instruments/monolith", "instruments/pentad", "instruments/consort",
+ "instruments/keys",
};
private static readonly string[] AudioEffects =
{
diff --git a/src/managed/Nota.Application/Engine/EngineContracts.cs b/src/managed/Nota.Application/Engine/EngineContracts.cs
index ffe3f321..ed1fdac8 100644
--- a/src/managed/Nota.Application/Engine/EngineContracts.cs
+++ b/src/managed/Nota.Application/Engine/EngineContracts.cs
@@ -216,7 +216,8 @@ public enum MidiClipEnvelope { Velocity = 0, Volume = 1 }
/// <summary>A per-note expression dimension (MPE). Matches native ExprDim: Bend in semitones
/// (the whole-instrument wheel −1..+1), Pressure 0..1, Slide (CC74 timbre) 0..1 with 0.5 neutral.</summary>
-public enum NoteExpressionDim { Bend = 0, Pressure = 1, Slide = 2 }
+/// <remarks>Sustain (the CC64 pedal, 0/1) is instrument-wide only — send it with pitch −1.</remarks>
+public enum NoteExpressionDim { Bend = 0, Pressure = 1, Slide = 2, Sustain = 3 }
/// <summary>An automation breakpoint, blittable and laid out to match native
/// NotaAutomationPoint (M9). Value is in the target's native units; Curve (M9-D)
diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.cs
index c4dfc571..8a3ff379 100644
--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs
+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs
@@ -374,6 +374,8 @@ public interface IAudioEngine : IDisposable
int AddPentadTrack();
/// <summary>Adds an instrument track with the built-in Nota Consort paraphonic semi-modular synth (kind 15).</summary>
int AddConsortTrack();
+ /// <summary>Adds an instrument track with the built-in Nota Keys modelled electric piano (kind 16).</summary>
+ int AddKeysTrack();
/// <summary>UI editing channel for the track's instrument (e.g. Rhythm step patterns).</summary>
void InstrumentAction(int trackId, int id, int iarg, float farg);
/// <summary>Loads a sample file into a Nota Grain track (kind 10). True on success.</summary>
diff --git a/src/managed/Nota.Application/Instruments/KeysModel.cs b/src/managed/Nota.Application/Instruments/KeysModel.cs
new file mode 100644
index 00000000..57fc6637
--- /dev/null
+++ b/src/managed/Nota.Application/Instruments/KeysModel.cs
@@ -0,0 +1,156 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Keys (built-in instrument kind 16) — 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 dB / Hz / %,
+// the PICKUP transfer curve (the same function the engine runs, so the graph is the sound),
+// the harmonics it makes, the scope telemetry layout, a one-line summary and a parameter
+// guide. Mirrors Keys.h.
+
+using System;
+using System.Globalization;
+using System.Text;
+
+namespace Nota.Application;
+
+public static class KeysModel
+{
+ public const int Kind = 16;
+
+ // scopeRead layout (Keys::Scope).
+ public const int ScActive = 0, ScLimit = 1, ScHeld = 2, ScSustained = 3, ScPedal = 4, ScLfo = 5,
+ ScPeakL = 6, ScPeakR = 7, ScLastNote = 8, ScopeLength = 9;
+
+ public static readonly string[] ModelNames = { "Tine", "Suitcase", "Reed", "Clav" };
+ public static readonly string[] ModelShort = { "Tine", "Case", "Reed", "Clav" };
+ public static readonly string[] PickupPositions = { "Upper", "Both", "Lower" };
+ public static readonly int[] VoiceCounts = { 8, 16, 32, 64 };
+ public static readonly string[] VoiceNames = { "8", "16", "32", "64" };
+ public static readonly string[] TremModes = { "Mono", "Stereo" };
+ public static readonly string[] TremSyncs = { "Free", "Tempo" };
+ public static readonly string[] TremDivisions = { "1/1", "1/2", "1/4", "1/8", "1/8T", "1/16", "1/16T", "1/32" };
+ public static readonly string[] CabNames = { "Off", "Suitcase", "Combo", "DI" };
+ public static readonly string[] CabNotes = { "bypass", "2×12″ wood", "Wurli speaker", "line" };
+
+ /// <summary>What picking a model chip resets: the pickup it was voiced with and its usual cabinet.</summary>
+ public static (double Sym, double Dist, int Cab) ModelDefaults(int model) => model switch
+ {
+ 1 => (0.28, 0.46, 1),
+ 2 => (0.0, 0.28, 2),
+ 3 => (0.0, 0.5, 3),
+ _ => (0.2, 0.4, 3),
+ };
+
+ 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 Index(float v, int n) => Math.Clamp((int)Math.Round(v * (n - 1)), 0, n - 1);
+ public static double Bipolar(float v) => (v - 0.5) * 2.0;
+
+ // ---- value maps ---------------------------------------------------------------------
+ /// <summary>Hammer Noise / Damper Release-Noise → dB (null = off).</summary>
+ public static double? NoiseDb(float v) => v <= 1e-3f ? null : -60.0 + 48.0 * Math.Sqrt(v);
+ /// <summary>Resonator Decay → % of the model's natural ring time.</summary>
+ public static double DecayPct(float v) => ExpMap(v, 0.25, 4.0) * 100.0;
+ /// <summary>Damper Amount → how long a released note takes to die (s, e-folding).</summary>
+ public static double DamperSeconds(float v) => ExpMap(1.0 - v, 0.025, 3.0);
+ public static double TuneCents(float v) => (v - 0.5) * 100.0;
+ /// <summary>Preamp Bass / Treble → shelf gain (dB, ±12).</summary>
+ public static double ShelfDb(float v) => (v - 0.5) * 24.0;
+ public static double TremHz(float v) => ExpMap(v, 0.5, 15.0);
+ public static double PhaserHz(float v) => ExpMap(v, 0.05, 5.0);
+ /// <summary>Output Volume → dB: 0.8 = 0 dB, 1 = +6, log taper below; null = silent.</summary>
+ public static double? VolumeDb(float v) => v <= 1e-3f ? null : v >= 0.8f ? (v - 0.8) * 30.0 : 60.0 * Math.Log10(v / 0.8);
+
+ // ---- the PICKUP curve (Keys.h keys::pickupRaw) ---------------------------------------
+ public static double PickupRaw(double x, double sym, double dist, int model)
+ {
+ double a = 0.3 + (1.0 - dist) * 3.2;
+ if (model == 2)
+ {
+ double k = (1.0 - dist) * 0.8;
+ return x / (1.0 + a * 0.6 * Math.Abs(x)) * (1.0 + k * x * x) / (1.0 + k) + sym * 0.35 * (2.0 - dist) * x * x;
+ }
+ double aa = model == 3 ? a * 0.5 : a;
+ return x / (1.0 + aa * Math.Abs(x)) + sym * 0.55 * (2.0 - dist) * x * x;
+ }
+
+ public static double PickupNorm(double sym, double dist, int model)
+ {
+ double mx = 0;
+ for (int i = 0; i <= 60; i++) mx = Math.Max(mx, Math.Abs(PickupRaw(-1.0 + i / 30.0, sym, dist, model)));
+ return mx > 1e-6 ? mx : 1.0;
+ }
+
+ /// <summary>Magnitudes of harmonics 1..count of the curve driven by a sine of amplitude
+ /// <paramref name="amp"/> (DFT, 128 points) — the editor's H1–H8 bars and the bark readout.</summary>
+ public static double[] Harmonics(double sym, double dist, int model, double amp = 0.72, int count = 8)
+ {
+ const int N = 128;
+ double norm = PickupNorm(sym, dist, model);
+ var sig = new double[N];
+ for (int n = 0; n < N; n++) sig[n] = PickupRaw(amp * Math.Sin(2 * Math.PI * n / N), sym, dist, model) / norm;
+ var mags = new double[count];
+ for (int k = 1; k <= count; k++)
+ {
+ double re = 0, im = 0;
+ for (int n = 0; n < N; n++) { double ph = 2 * Math.PI * k * n / N; re += sig[n] * Math.Cos(ph); im += sig[n] * Math.Sin(ph); }
+ mags[k - 1] = Math.Sqrt(re * re + im * im);
+ }
+ return mags;
+ }
+
+ /// <summary>The second harmonic against the fundamental, dB — the "bark".</summary>
+ public static double BarkDb(double sym, double dist, int model)
+ {
+ var h = Harmonics(sym, dist, model, count: 2);
+ return 20 * Math.Log10(h[1] / Math.Max(1e-9, h[0]) + 1e-6);
+ }
+
+ // ---- text ---------------------------------------------------------------------------
+ private static readonly CultureInfo Inv = CultureInfo.InvariantCulture;
+ private static string Pct(double v) => Math.Round(v * 100).ToString(Inv) + "\u2009%";
+ private static string SignedPct(double v) => (v >= 0 ? "+" : "−") + Math.Round(Math.Abs(v) * 100).ToString(Inv) + "\u2009%";
+
+ public static string TremRateText(Func<string, float> g)
+ => g("tremsync") >= 0.5f ? TremDivisions[Index(g("tremrate"), TremDivisions.Length)]
+ : TremHz(g("tremrate")).ToString("0.0", Inv) + "\u2009Hz";
+
+ /// <summary>One line: the model, the hammer, the pickup and the effects that are on.</summary>
+ public static string Summary(Func<string, float> g)
+ {
+ int model = Index(g("model"), 4);
+ var sb = new StringBuilder();
+ sb.Append(ModelNames[model]);
+ if (model == 3) sb.Append(" · ").Append(PickupPositions[Index(g("pupos"), 3)]).Append(" pickup");
+ sb.Append(" · hard ").Append(Pct(g("hard")));
+ sb.Append(" · pickup ").Append(Pct(g("dist"))).Append(" / ").Append(SignedPct(Bipolar(g("sym"))));
+ sb.Append(" · damper ").Append(Pct(g("damper")));
+ sb.Append(" · ").Append(VoiceCounts[Index(g("voices"), 4)]).Append(" voices");
+ if (g("preon") >= 0.5f) sb.Append(" · drive ").Append(Pct(g("drive")));
+ if (g("tremon") >= 0.5f) sb.Append(" · trem ").Append(TremModes[Index(g("tremmode"), 2)].ToLowerInvariant()).Append(' ').Append(TremRateText(g)).Append(' ').Append(Pct(g("tremdepth")));
+ if (g("phaseron") >= 0.5f) sb.Append(" · phaser ").Append(PhaserHz(g("phaserrate")).ToString("0.00", Inv)).Append("\u2009Hz");
+ if (g("choruson") >= 0.5f) sb.Append(" · chorus ").Append(Pct(g("chorusmix")));
+ sb.Append(" · cab ").Append(CabNames[Index(g("cab"), 4)]);
+ if (g("pedal") >= 0.5f) sb.Append(" · pedal down");
+ return sb.ToString();
+ }
+
+ public const string Guide =
+ "All values are normalized 0..1 (set_instrument_param_by_id, or set_keys in musical terms). "
+ + "model: 0 Tine, 1/3 Suitcase, 2/3 Reed, 1 Clav. "
+ + "hammer — hard: contact time 6.5 ms (0, soft, dark) .. 0.35 ms (1, hard, bright); velhard: how much velocity hardens the hammer; "
+ + "noise: hammer thump, 0 off else -60..-12 dB (sqrt taper). "
+ + "resonator — decay: ring time 25 %..400 % of the model's natural (0.5 = 100 %); body: tone-bar / fundamental weight (0.5 = natural); "
+ + "bright: the bell partials (6.27x, 17.55x for tine/reed, the string's upper harmonics for clav), 0.5 = natural; "
+ + "keybright: bipolar, 0.5 = flat, >0.5 brighter up the keyboard. "
+ + "pickup — sym: bipolar offset of the tine against the pickup (0.5 = centred; off-centre = even harmonics, the bark); "
+ + "dist: 0 = pickup close (strong saturation, growl) .. 1 = far (clean, linear); pupos (clav only): 0 Upper, 0.5 Both, 1 Lower. "
+ + "damper — damper: how fast a released key dies, 0 = rings ~3 s .. 1 = stops in ~25 ms; relnoise: damper felt thump (as noise); "
+ + "pedal: >= 0.5 holds released notes (OR'd with a keyboard's CC64). "
+ + "play — tune: +-50 cents (0.5 = 0); age: per-key detune / decay / level spread; stretch: octave stretch (0..30 cents at the ends); "
+ + "voices: 0 = 8, 1/3 = 16, 2/3 = 32, 1 = 64. "
+ + "preamp — preon on/off, drive 1x..14x into a soft clipper, bass / treble: shelves +-12 dB (0.5 = flat). "
+ + "tremolo — tremon, tremmode 0 mono amplitude / 1 stereo auto-pan, tremsync 0 free (tremrate 0.5..15 Hz) / 1 tempo (tremrate picks 1/1,1/2,1/4,1/8,1/8T,1/16,1/16T,1/32), tremdepth 0..1. "
+ + "phaser — phaseron, phaserrate 0.05..5 Hz, phaserdepth. chorus — choruson, chorusmix. "
+ + "cab: 0 Off, 1/3 Suitcase, 2/3 Combo, 1 DI. volume: 0.8 = 0 dB, 1 = +6 dB; pan: 0.5 = centre. "
+ + "MPE: bend retunes, pressure drives the tine harder into the pickup, slide shifts the pickup symmetry.";
+}
diff --git a/src/managed/Nota.Application/Palette/BuiltinDeviceCatalog.cs b/src/managed/Nota.Application/Palette/BuiltinDeviceCatalog.cs
index 98840881..1e4cb9af 100644
--- a/src/managed/Nota.Application/Palette/BuiltinDeviceCatalog.cs
+++ b/src/managed/Nota.Application/Palette/BuiltinDeviceCatalog.cs
@@ -82,6 +82,9 @@ public static class BuiltinDeviceCatalog
new("Nota Consort", I, 15, "paraphonic synth", D("synth.subtractive", "paraphonic string-machine",
"lush vintage warm", "strings pad choir", "", "", "synthwave",
"Paraphonic ensemble synth — string machines and choirs.")),
+ new("Nota Keys", I, 16, "electric piano", D("synth.physical", "epiano e-piano rhodes wurlitzer wurli clavinet clav tine reed suitcase",
+ "warm vintage", "keys", "", "", "jazz funk",
+ "Modelled electric piano — tine, suitcase, reed and clav with tremolo, phaser and cabinet.")),
new("Nota Sampler", I, 1, "built-in", D("sampler", "simpler multisample",
"", "keys perc", "", "", "",
"Plays a sample across the keyboard.")),
diff --git a/src/managed/Nota.Application/Palette/PresetDescriptors.cs b/src/managed/Nota.Application/Palette/PresetDescriptors.cs
index d17d603e..6f173d5e 100644
--- a/src/managed/Nota.Application/Palette/PresetDescriptors.cs
+++ b/src/managed/Nota.Application/Palette/PresetDescriptors.cs
@@ -83,6 +83,11 @@ public static class PresetDescriptors
["humanize"] = new() { Character = ["subtle"] },
["ratchets & rolls"] = new() { Source = ["drums"] },
["melodic"] = new() { Sound = ["seq"] },
+ ["tine"] = new() { Sound = ["keys"], Character = ["bright"] },
+ ["suitcase"] = new() { Sound = ["keys"], Character = ["warm", "wide"] },
+ ["reed"] = new() { Sound = ["keys"], Character = ["gritty", "vintage"] },
+ ["clav"] = new() { Sound = ["keys"], Character = ["punchy"], Genre = ["funk"] },
+ ["character"] = new() { Character = ["lofi", "vintage"] },
};
/// <summary>A factory or user preset's descriptor (CP-13.2/13.3): the device's role,
diff --git a/src/managed/Nota.Infrastructure/Audition/PresetAudition.cs b/src/managed/Nota.Infrastructure/Audition/PresetAudition.cs
index 4babe17c..e5c039df 100644
--- a/src/managed/Nota.Infrastructure/Audition/PresetAudition.cs
+++ b/src/managed/Nota.Infrastructure/Audition/PresetAudition.cs
@@ -171,7 +171,7 @@ public sealed partial class PresetAudition : IPresetAudition
{
[0] = "Nota Synth", [1] = "Nota Sampler", [2] = "Nota Physical", [5] = "Nota Aurora", [6] = "Nota Volt",
[7] = "Nota Bass", [8] = "Nota Pendulum", [9] = "Nota Operator", [10] = "Nota Grain", [11] = "Nota Flux",
- [12] = "Nota Rhythm", [13] = "Nota Monolith", [14] = "Nota Pentad", [15] = "Nota Consort",
+ [12] = "Nota Rhythm", [13] = "Nota Monolith", [14] = "Nota Pentad", [15] = "Nota Consort", [16] = "Nota Keys",
};
private static readonly Dictionary<int, string> MidiNames = new()
{
diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs
index 71c9c699..b4836cf6 100644
--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs
@@ -362,6 +362,9 @@ internal static partial class NativeMethods
[LibraryImport(Lib, EntryPoint = "nota_engine_add_consort_track")]
internal static partial int AddConsortTrack(IntPtr engine);
+ [LibraryImport(Lib, EntryPoint = "nota_engine_add_keys_track")]
+ internal static partial int AddKeysTrack(IntPtr engine);
+
[LibraryImport(Lib, EntryPoint = "nota_track_instrument_action")]
internal static partial void InstrumentAction(IntPtr engine, int trackId, int id, int iarg, float farg);
diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs
index c7976ad9..ab047960 100644
--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs
@@ -779,6 +779,15 @@ public sealed partial class NotaEngine
return id;
}
+ /// <summary>Adds an instrument track with the built-in Nota Keys electric piano. Returns its id.</summary>
+ public int AddKeysTrack()
+ {
+ ThrowIfDisposed();
+ var id = NativeMethods.AddKeysTrack(_handle);
+ if (id <= 0) throw new NotaEngineException("Failed to add Keys track.");
+ return id;
+ }
+
/// <summary>UI editing channel for the track's instrument (e.g. Nota Rhythm step patterns).</summary>
public void InstrumentAction(int trackId, int id, int iarg, float farg)
{ ThrowIfDisposed(); NativeMethods.InstrumentAction(_handle, trackId, id, iarg, farg); }
diff --git a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
index f681e037..728cbc05 100644
--- a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
@@ -993,6 +993,59 @@ public sealed class FactoryPresetCatalog : IFactoryPresets
("fdecay", 0.5f), ("fsustain", 0.15f), ("adecay", 0.55f), ("asustain", 0.3f)),
Cab(1, 1, 16, 0.4f)));
+ // ---- Nota Keys (kind 16) — modelled electric piano. Model Tine/Suitcase/Reed/Clav =
+ // 0/.333/.667/1; sym .5 = centred (bipolar); dist 0 = close (bark) .. 1 = far (clean);
+ // pupos (Clav) Upper/Both/Lower = 0/.5/1; cab Off/Suitcase/Combo/DI = 0/.333/.667/1;
+ // tremmode Mono/Stereo = 0/1; tremrate free v = ln(Hz/0.5)/ln 30 (4.5 Hz = .646),
+ // tempo (tremsync 1) = division/7 over 1/1,1/2,1/4,1/8,1/8T,1/16,1/16T,1/32;
+ // phaserrate v = ln(Hz/0.05)/ln 100. Unnamed params keep the Init ("Mk I Stage").
+ Section("Basics");
+ Inst("keys", 16, "Mk I Stage", ("model", 0f));
+ Inst("keys", 16, "Suitcase Init", ("model", 0.333f), ("sym", 0.64f), ("dist", 0.46f), ("cab", 0.333f), ("tremon", 1f), ("tremmode", 1f));
+ Inst("keys", 16, "200A Classic", ("model", 0.667f), ("sym", 0.5f), ("dist", 0.28f), ("cab", 0.667f), ("bass", 0.55f), ("treble", 0.5f));
+ Inst("keys", 16, "D6 Funk", ("model", 1f), ("sym", 0.5f), ("dist", 0.5f), ("pupos", 0.5f), ("damper", 0.85f), ("drive", 0.3f));
+ Section("Tine");
+ Inst("keys", 16, "Ballad Tine", ("hard", 0.35f), ("velhard", 0.7f), ("bright", 0.4f), ("decay", 0.65f), ("dist", 0.55f), ("sym", 0.56f), ("choruson", 1f), ("chorusmix", 0.25f), ("age", 0.1f));
+ Inst("keys", 16, "Bark Lead", ("hard", 0.75f), ("velhard", 0.8f), ("dist", 0.12f), ("sym", 0.72f), ("drive", 0.55f), ("bright", 0.6f), ("treble", 0.56f));
+ Inst("keys", 16, "Glass Tine", ("hard", 0.8f), ("bright", 0.85f), ("keybright", 0.7f), ("body", 0.35f), ("dist", 0.7f), ("sym", 0.52f), ("choruson", 1f), ("chorusmix", 0.4f), ("treble", 0.58f));
+ Inst("keys", 16, "Mellow Mk II", ("hard", 0.3f), ("bright", 0.3f), ("body", 0.7f), ("dist", 0.6f), ("sym", 0.55f), ("drive", 0.2f), ("treble", 0.4f), ("decay", 0.6f));
+ Inst("keys", 16, "Neo-Soul Tine", ("hard", 0.45f), ("velhard", 0.75f), ("dist", 0.35f), ("sym", 0.64f), ("phaseron", 1f), ("phaserrate", 0.3f), ("phaserdepth", 0.5f), ("age", 0.25f), ("bass", 0.66f));
+ Inst("keys", 16, "Phase Ninety", ("phaseron", 1f), ("phaserrate", 0.4515f), ("phaserdepth", 0.7f), ("dist", 0.38f));
+ Inst("keys", 16, "Chorus Tine", ("choruson", 1f), ("chorusmix", 0.55f), ("bright", 0.55f), ("dist", 0.45f));
+ Inst("keys", 16, "Dry & Close", ("hard", 0.55f), ("dist", 0.2f), ("sym", 0.66f), ("preon", 0f), ("noise", 0.35f), ("relnoise", 0.4f));
+ Inst("keys", 16, "Worn Tines", ("age", 0.7f), ("stretch", 0.5f), ("decay", 0.4f), ("noise", 0.4f), ("relnoise", 0.45f), ("dist", 0.32f), ("sym", 0.7f), ("tune", 0.47f));
+ Inst("keys", 16, "Tine Bells", ("hard", 0.9f), ("bright", 1f), ("keybright", 0.8f), ("body", 0.25f), ("decay", 0.75f), ("dist", 0.8f), ("sym", 0.5f), ("choruson", 1f), ("chorusmix", 0.35f));
+ Section("Suitcase");
+ Inst("keys", 16, "Suitcase Stereo", ("model", 0.333f), ("sym", 0.64f), ("dist", 0.46f), ("cab", 0.333f), ("tremon", 1f), ("tremrate", 0.646f), ("choruson", 1f), ("chorusmix", 0.35f));
+ Inst("keys", 16, "Slow Pan", ("model", 0.333f), ("cab", 0.333f), ("tremon", 1f), ("tremrate", 0.408f), ("tremdepth", 0.7f), ("sym", 0.62f), ("dist", 0.5f));
+ Inst("keys", 16, "Fast Pan", ("model", 0.333f), ("cab", 0.333f), ("tremon", 1f), ("tremrate", 0.776f), ("tremdepth", 0.55f), ("sym", 0.64f), ("dist", 0.46f));
+ Inst("keys", 16, "Synced Eighths", ("model", 0.333f), ("cab", 0.333f), ("tremon", 1f), ("tremsync", 1f), ("tremrate", 0.4286f), ("tremdepth", 0.65f), ("sym", 0.64f), ("dist", 0.46f));
+ Inst("keys", 16, "Late Night Case", ("model", 0.333f), ("cab", 0.333f), ("hard", 0.3f), ("bright", 0.35f), ("body", 0.7f), ("dist", 0.58f), ("tremon", 1f), ("tremrate", 0.527f), ("tremdepth", 0.35f), ("drive", 0.25f), ("treble", 0.4f));
+ Inst("keys", 16, "Growl Case", ("model", 0.333f), ("cab", 0.333f), ("hard", 0.7f), ("velhard", 0.85f), ("dist", 0.15f), ("sym", 0.74f), ("drive", 0.6f), ("tremon", 1f), ("tremdepth", 0.4f));
+ Inst("keys", 16, "Mono Trem Case", ("model", 0.333f), ("cab", 0.333f), ("tremon", 1f), ("tremmode", 0f), ("tremrate", 0.62f), ("tremdepth", 0.55f), ("sym", 0.64f), ("dist", 0.46f));
+ Inst("keys", 16, "Dream Case", ("model", 0.333f), ("cab", 0.333f), ("tremon", 1f), ("tremrate", 0.45f), ("tremdepth", 0.5f), ("choruson", 1f), ("chorusmix", 0.6f), ("phaseron", 1f), ("phaserrate", 0.25f), ("phaserdepth", 0.5f), ("decay", 0.7f), ("damper", 0.5f));
+ Section("Reed");
+ Inst("keys", 16, "Reed Bark", ("model", 0.667f), ("cab", 0.667f), ("dist", 0.12f), ("sym", 0.55f), ("hard", 0.7f), ("velhard", 0.85f), ("drive", 0.5f));
+ Inst("keys", 16, "School Reed", ("model", 0.667f), ("cab", 0.667f), ("dist", 0.35f), ("sym", 0.5f), ("hard", 0.45f), ("age", 0.35f), ("noise", 0.35f));
+ Inst("keys", 16, "Reed Tremolo", ("model", 0.667f), ("cab", 0.667f), ("dist", 0.28f), ("sym", 0.5f), ("tremon", 1f), ("tremmode", 0f), ("tremrate", 0.62f), ("tremdepth", 0.5f));
+ Inst("keys", 16, "Soft Reed", ("model", 0.667f), ("cab", 0.667f), ("hard", 0.25f), ("bright", 0.35f), ("dist", 0.5f), ("sym", 0.5f), ("drive", 0.2f), ("treble", 0.42f));
+ Inst("keys", 16, "Reed Phaser", ("model", 0.667f), ("cab", 0.667f), ("dist", 0.25f), ("sym", 0.5f), ("phaseron", 1f), ("phaserrate", 0.35f), ("phaserdepth", 0.65f));
+ Inst("keys", 16, "Bright Reed", ("model", 0.667f), ("bright", 0.75f), ("keybright", 0.7f), ("dist", 0.3f), ("sym", 0.5f), ("treble", 0.6f));
+ Inst("keys", 16, "Overdriven Reed", ("model", 0.667f), ("cab", 0.667f), ("dist", 0.1f), ("sym", 0.6f), ("drive", 0.85f), ("bass", 0.58f), ("treble", 0.55f));
+ Inst("keys", 16, "Reed Chorus", ("model", 0.667f), ("cab", 0.667f), ("dist", 0.32f), ("sym", 0.5f), ("choruson", 1f), ("chorusmix", 0.5f));
+ Section("Clav");
+ Inst("keys", 16, "D6 Bright", ("model", 1f), ("pupos", 0f), ("bright", 0.7f), ("sym", 0.5f), ("dist", 0.45f), ("damper", 0.9f));
+ Inst("keys", 16, "Clav Lower", ("model", 1f), ("pupos", 1f), ("body", 0.65f), ("bright", 0.4f), ("sym", 0.5f), ("dist", 0.5f));
+ Inst("keys", 16, "Funk Drive", ("model", 1f), ("pupos", 0.5f), ("hard", 0.8f), ("velhard", 0.8f), ("drive", 0.55f), ("sym", 0.5f), ("dist", 0.5f), ("phaseron", 1f), ("phaserrate", 0.5f), ("phaserdepth", 0.5f));
+ Inst("keys", 16, "Muted Clav", ("model", 1f), ("damper", 1f), ("decay", 0.25f), ("bright", 0.35f), ("hard", 0.4f), ("sym", 0.5f), ("dist", 0.5f));
+ Inst("keys", 16, "Clav Phaser", ("model", 1f), ("pupos", 0f), ("phaseron", 1f), ("phaserrate", 0.4f), ("phaserdepth", 0.7f), ("sym", 0.5f), ("dist", 0.5f));
+ Inst("keys", 16, "Clav Combo", ("model", 1f), ("cab", 0.667f), ("drive", 0.5f), ("sym", 0.5f), ("dist", 0.35f));
+ Section("Character");
+ Inst("keys", 16, "Lo-Fi Keys", ("age", 0.8f), ("tune", 0.46f), ("drive", 0.5f), ("cab", 0.667f), ("treble", 0.3f), ("bass", 0.58f), ("noise", 0.45f), ("tremon", 1f), ("tremmode", 0f), ("tremrate", 0.35f), ("tremdepth", 0.2f));
+ Inst("keys", 16, "Detuned Tape", ("age", 1f), ("stretch", 0.8f), ("choruson", 1f), ("chorusmix", 0.7f), ("tremon", 1f), ("tremmode", 0f), ("tremrate", 0.2f), ("tremdepth", 0.15f), ("cab", 0.333f));
+ Inst("keys", 16, "Toy Box", ("model", 0.667f), ("hard", 1f), ("bright", 1f), ("decay", 0.3f), ("body", 0.2f), ("keybright", 0.9f), ("cab", 0.667f), ("dist", 0.4f), ("sym", 0.5f));
+ Inst("keys", 16, "Ambient Tine", ("hard", 0.2f), ("velhard", 0.5f), ("decay", 1f), ("damper", 0.2f), ("choruson", 1f), ("chorusmix", 0.65f), ("phaseron", 1f), ("phaserrate", 0.2f), ("phaserdepth", 0.4f), ("tremon", 1f), ("tremrate", 0.4f), ("tremdepth", 0.35f));
+
// ---- Nota EQ-8 (kind 0) — raw units. Eq8(…) spells out every band it uses with B(band, type,
// Hz, dB, Q, slope, channel); a band it does not name is switched off. Type: 0 Low cut,
// 1 Low shelf, 2 Bell, 3 Notch, 4 High shelf, 5 High cut. Slope (cuts): 0 = 12, 1 = 24,
diff --git a/src/managed/Nota.Infrastructure/Persistence/PresetService.cs b/src/managed/Nota.Infrastructure/Persistence/PresetService.cs
index eabeb97d..be60ddcd 100644
--- a/src/managed/Nota.Infrastructure/Persistence/PresetService.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/PresetService.cs
@@ -223,6 +223,7 @@ public static class PresetService
13 => engine.AddMonolithTrack(),
14 => engine.AddPentadTrack(),
15 => engine.AddConsortTrack(),
+ 16 => engine.AddKeysTrack(),
_ => engine.AddInstrumentTrack(),
};
if (t <= 0) return "Failed to add instrument.";
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
index 7224f511..e411ba6a 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
@@ -534,6 +534,7 @@ public sealed class ProjectService
{ Kind: 13 } => engine.AddMonolithTrack(), // Nota Monolith
{ Kind: 14 } => engine.AddPentadTrack(), // Nota Pentad
{ Kind: 15 } => engine.AddConsortTrack(), // Nota Consort
+ { Kind: 16 } => engine.AddKeysTrack(), // Nota Keys
_ => engine.AddInstrumentTrack(), // Nota Synth
};
if (t.Instrument?.State is { } synthState)
diff --git a/src/managed/Nota.Mcp/Tools/InstrumentTools.cs b/src/managed/Nota.Mcp/Tools/InstrumentTools.cs
index 5ca591ea..bcc5e6cd 100644
--- a/src/managed/Nota.Mcp/Tools/InstrumentTools.cs
+++ b/src/managed/Nota.Mcp/Tools/InstrumentTools.cs
@@ -20,6 +20,7 @@ public sealed class InstrumentTools(IAudioEngine engine, IEngineDispatch dispatc
(4, "Drum Rack"), (5, "Nota Aurora"), (6, "Nota Volt"), (7, "Nota Bass"),
(8, "Nota Pendulum"), (9, "Nota Operator"), (10, "Nota Grain"), (11, "Nota Flux"),
(12, "Nota Rhythm"), (13, "Nota Monolith"), (14, "Nota Pentad"), (15, "Nota Consort"),
+ (16, "Nota Keys"),
};
public sealed record InstrumentKind(int Kind, string Name);
@@ -29,7 +30,7 @@ public sealed class InstrumentTools(IAudioEngine engine, IEngineDispatch dispatc
public InstrumentKind[] ListInstrumentKinds() => Array.ConvertAll(Kinds, k => new InstrumentKind(k.Kind, k.Name));
[McpServerTool(Name = "add_instrument_track"), Description("Add an instrument track with the given built-in kind (see list_instrument_kinds). Returns the track id.")]
- public Task<int> AddInstrumentTrack([Description("Instrument kind id (0..15)")] int kind) => Mutate(() => kind switch
+ public Task<int> AddInstrumentTrack([Description("Instrument kind id (0..16)")] int kind) => Mutate(() => kind switch
{
1 => E.AddSamplerInstrumentTrack(),
2 => E.AddPhysicalSynthTrack(),
@@ -46,6 +47,7 @@ public sealed class InstrumentTools(IAudioEngine engine, IEngineDispatch dispatc
13 => E.AddMonolithTrack(),
14 => E.AddPentadTrack(),
15 => E.AddConsortTrack(),
+ 16 => E.AddKeysTrack(),
_ => E.AddInstrumentTrack(), // 0 = Nota Synth
});
@@ -219,6 +221,122 @@ public sealed class InstrumentTools(IAudioEngine engine, IEngineDispatch dispatc
return id => vals.TryGetValue(id, out var v) ? v : 0f;
}
+ public sealed record KeysReading(string Summary, string Guide, string Model, int ActiveVoices, int VoiceLimit,
+ int HeldNotes, int PedalHeld, bool PedalDown, string LastNote, double OutputPeakDb, double BarkDb, double[] HarmonicsDb);
+
+ [McpServerTool(Name = "read_keys"), Description(
+ "Read a Nota Keys track (built-in instrument kind 16 — a modelled electric piano: Tine, Suitcase, Reed or Clav; a hammer "
+ + "strikes a tine / reed / string whose motion passes a PICKUP transfer curve, then preamp → tremolo → phaser → chorus → "
+ + "cabinet). Returns a one-line summary, a guide to every 0..1 parameter (ids for set_instrument_param_by_id, or use "
+ + "set_keys), the voices sounding / the voice limit, how many are held by keys and by the sustain pedal, whether the pedal "
+ + "is down (the Pedal param or a keyboard's CC64), the last note struck, the output peak (dBFS, -120 = silence), the bark "
+ + "(2nd harmonic against the fundamental, dB) and the curve's harmonics H1..H8 in dB relative to H1 for a full-velocity "
+ + "note — what the PICKUP graph shows.")]
+ public Task<KeysReading?> ReadKeys(int trackId) => Read<KeysReading?>(() =>
+ {
+ if (E.TrackInstrumentKind(trackId) != KeysModel.Kind) return null;
+ var g = PendulumGetter(trackId);
+ var sc = new float[KeysModel.ScopeLength];
+ int n = E.InstrumentScope(trackId, sc);
+ int model = KeysModel.Index(g("model"), 4);
+ double sym = KeysModel.Bipolar(g("sym")), dist = g("dist");
+ var mags = KeysModel.Harmonics(sym, dist, model);
+ var hdb = new double[mags.Length];
+ for (int i = 0; i < mags.Length; i++) hdb[i] = Math.Round(20 * Math.Log10(mags[i] / Math.Max(1e-9, mags[0]) + 1e-9), 1);
+ double peak = n > KeysModel.ScPeakR ? Math.Max(sc[KeysModel.ScPeakL], sc[KeysModel.ScPeakR]) : 0;
+ int last = n > KeysModel.ScLastNote ? (int)Math.Round(sc[KeysModel.ScLastNote]) : -1;
+ return new KeysReading(KeysModel.Summary(g), KeysModel.Guide, KeysModel.ModelNames[model],
+ n > 0 ? (int)sc[KeysModel.ScActive] : 0, KeysModel.VoiceCounts[KeysModel.Index(g("voices"), 4)],
+ n > KeysModel.ScHeld ? (int)sc[KeysModel.ScHeld] : 0, n > KeysModel.ScSustained ? (int)sc[KeysModel.ScSustained] : 0,
+ n > KeysModel.ScPedal && sc[KeysModel.ScPedal] > 0.5f, last >= 0 ? PendulumModel.NoteName(last) : "",
+ peak > 1e-6 ? Math.Round(20 * Math.Log10(peak), 1) : -120,
+ Math.Round(KeysModel.BarkDb(sym, dist, model), 1), hdb);
+ });
+
+ [McpServerTool(Name = "set_keys"), Description(
+ "Shape a Nota Keys track (kind 16) in musical terms; every argument is optional and only the given ones change. "
+ + "model Tine | Suitcase | Reed | Clav (also resets the pickup and cabinet that model is voiced with unless you pass them); "
+ + "hardnessPercent / velocityHardnessPercent 0..100; decayPercent 25..400 (100 = the model's natural ring); "
+ + "brightPercent / bodyPercent 0..100 (50 = natural); symmetryPercent -100..100 (0 = centred; off-centre adds even "
+ + "harmonics, the bark); distancePercent 0..100 (0 = pickup close: growl, 100 = far: clean); pickup Upper | Both | Lower "
+ + "(Clav); damperPercent 0..100 (how fast a released key stops); pedal down/up; voices 8 | 16 | 32 | 64; "
+ + "tuneCents -50..50; agePercent 0..100; drivePercent 0..100 (turns the preamp on); tremolo off | mono | stereo; "
+ + "tremoloRate \"4.5\" (Hz, free) or a division 1/1, 1/2, 1/4, 1/8, 1/8T, 1/16, 1/16T, 1/32 (tempo); tremoloDepthPercent; "
+ + "phaser on/off with phaserRateHz 0.05..5; chorusMixPercent (0 = chorus off); cabinet Off | Suitcase | Combo | DI; "
+ + "volumeDb -40..6. Returns the new summary, or an error line naming what it could not use.")]
+ public Task<string> SetKeys(int trackId, string? model = null, double? hardnessPercent = null, double? velocityHardnessPercent = null,
+ double? decayPercent = null, double? brightPercent = null, double? bodyPercent = null, double? symmetryPercent = null,
+ double? distancePercent = null, string? pickup = null, double? damperPercent = null, bool? pedal = null, int? voices = null,
+ double? tuneCents = null, double? agePercent = null, double? drivePercent = null, string? tremolo = null, string? tremoloRate = null,
+ double? tremoloDepthPercent = null, bool? phaser = null, double? phaserRateHz = null, double? chorusMixPercent = null,
+ string? cabinet = null, double? volumeDb = null) => Mutate(() =>
+ {
+ if (E.TrackInstrumentKind(trackId) != KeysModel.Kind) return $"error: track {trackId} is not a Nota Keys";
+ int pc = E.PluginParamCount(trackId, -1);
+ var ids = new Dictionary<string, int>();
+ for (int i = 0; i < pc; i++) ids[E.PluginParamId(trackId, -1, i)] = i;
+ void Set(string id, double v) { if (ids.TryGetValue(id, out var i)) E.PluginParamSet(trackId, -1, i, (float)Math.Clamp(v, 0, 1)); }
+ static int Find(string[] names, string? v) => v is null ? -1 : Array.FindIndex(names, n => string.Equals(n, v.Trim(), StringComparison.OrdinalIgnoreCase));
+ static double Pct(double p) => Math.Clamp(p, 0, 100) / 100.0;
+ var errors = new List<string>();
+
+ if (model is not null)
+ {
+ int m = Find(KeysModel.ModelNames, model);
+ if (m < 0) errors.Add($"model '{model}'");
+ else
+ {
+ Set("model", m / 3.0);
+ var (ds, dd, dc) = KeysModel.ModelDefaults(m);
+ if (symmetryPercent is null) Set("sym", (ds + 1) / 2);
+ if (distancePercent is null) Set("dist", dd);
+ if (cabinet is null) Set("cab", dc / 3.0);
+ }
+ }
+ if (hardnessPercent is { } h) Set("hard", Pct(h));
+ if (velocityHardnessPercent is { } vh) Set("velhard", Pct(vh));
+ if (decayPercent is { } dp) Set("decay", Math.Log(Math.Clamp(dp, 25, 400) / 25.0) / Math.Log(16.0));
+ if (brightPercent is { } br) Set("bright", Pct(br));
+ if (bodyPercent is { } bo) Set("body", Pct(bo));
+ if (symmetryPercent is { } sy) Set("sym", (Math.Clamp(sy, -100, 100) / 100.0 + 1) / 2);
+ if (distancePercent is { } di) Set("dist", Pct(di));
+ if (pickup is not null) { int p = Find(KeysModel.PickupPositions, pickup); if (p < 0) errors.Add($"pickup '{pickup}'"); else Set("pupos", p / 2.0); }
+ if (damperPercent is { } da) Set("damper", Pct(da));
+ if (pedal is { } pd) Set("pedal", pd ? 1 : 0);
+ if (voices is { } vc) { int v = Array.IndexOf(KeysModel.VoiceCounts, vc); if (v < 0) errors.Add($"voices {vc}"); else Set("voices", v / 3.0); }
+ if (tuneCents is { } tc) Set("tune", 0.5 + Math.Clamp(tc, -50, 50) / 100.0);
+ if (agePercent is { } ag) Set("age", Pct(ag));
+ if (drivePercent is { } dr) { Set("drive", Pct(dr)); Set("preon", 1); }
+ if (tremolo is not null)
+ {
+ var t = tremolo.Trim().ToLowerInvariant();
+ if (t == "off") Set("tremon", 0);
+ else if (t is "mono" or "stereo") { Set("tremon", 1); Set("tremmode", t == "stereo" ? 1 : 0); }
+ else errors.Add($"tremolo '{tremolo}'");
+ }
+ if (tremoloRate is not null)
+ {
+ int d = Find(KeysModel.TremDivisions, tremoloRate);
+ if (d >= 0) { Set("tremsync", 1); Set("tremrate", d / 7.0); }
+ else if (double.TryParse(tremoloRate.Replace("Hz", "", StringComparison.OrdinalIgnoreCase).Trim(), System.Globalization.NumberStyles.Float,
+ System.Globalization.CultureInfo.InvariantCulture, out var hz) && hz > 0)
+ { Set("tremsync", 0); Set("tremrate", Math.Log(Math.Clamp(hz, 0.5, 15) / 0.5) / Math.Log(30.0)); }
+ else errors.Add($"tremoloRate '{tremoloRate}'");
+ }
+ if (tremoloDepthPercent is { } td) Set("tremdepth", Pct(td));
+ if (phaser is { } ph) Set("phaseron", ph ? 1 : 0);
+ if (phaserRateHz is { } pr) { Set("phaserrate", Math.Log(Math.Clamp(pr, 0.05, 5) / 0.05) / Math.Log(100.0)); if (phaser is null) Set("phaseron", 1); }
+ if (chorusMixPercent is { } cm) { Set("chorusmix", Pct(cm)); Set("choruson", cm > 0 ? 1 : 0); }
+ if (cabinet is not null) { int c = Find(KeysModel.CabNames, cabinet); if (c < 0) errors.Add($"cabinet '{cabinet}'"); else Set("cab", c / 3.0); }
+ if (volumeDb is { } vd)
+ {
+ double db = Math.Clamp(vd, -40, 6);
+ Set("volume", db >= 0 ? 0.8 + db / 30.0 : 0.8 * Math.Pow(10, db / 60.0));
+ }
+ string summary = KeysModel.Summary(PendulumGetter(trackId));
+ return errors.Count == 0 ? summary : $"error: could not use {string.Join(", ", errors)} · {summary}";
+ });
+
[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/managed/Nota.Presentation/DeviceInsertService.cs b/src/managed/Nota.Presentation/DeviceInsertService.cs
index 8d5eb2a3..2c2b11a2 100644
--- a/src/managed/Nota.Presentation/DeviceInsertService.cs
+++ b/src/managed/Nota.Presentation/DeviceInsertService.cs
@@ -133,6 +133,7 @@ public sealed class DeviceInsertService
13 => _engine.AddMonolithTrack(),
14 => _engine.AddPentadTrack(),
15 => _engine.AddConsortTrack(),
+ 16 => _engine.AddKeysTrack(),
1 => _engine.AddSamplerInstrumentTrack(),
_ => _engine.AddInstrumentTrack(),
};
diff --git a/src/managed/Nota.Remote/RemoteParams.cs b/src/managed/Nota.Remote/RemoteParams.cs
index 59d2d10f..e4941223 100644
--- a/src/managed/Nota.Remote/RemoteParams.cs
+++ b/src/managed/Nota.Remote/RemoteParams.cs
@@ -44,7 +44,7 @@ public static class RemoteParams
0 => "Nota Synth", 1 => "Sampler", 2 => "Nota Physical", 3 => "Instrument Rack", 4 => "Drum Rack",
5 => "Nota Aurora", 6 => "Nota Volt", 7 => "Nota Bass", 8 => "Nota Pendulum", 9 => "Nota Operator",
10 => "Nota Grain", 11 => "Nota Flux", 12 => "Nota Rhythm", 13 => "Nota Monolith", 14 => "Nota Pentad",
- 15 => "Nota Consort", _ => "",
+ 15 => "Nota Consort", 16 => "Nota Keys", _ => "",
};
if (name.Length > 0) return name;
string id = e.TrackInstrumentPluginId(trackId);
diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.h
index d8a19fe8..6e798313 100644
--- a/src/native/nota.engine/include/nota/nota_engine.h
+++ b/src/native/nota.engine/include/nota/nota_engine.h
@@ -593,6 +593,8 @@ NOTA_API int32_t nota_engine_add_monolith_track(NotaEngine* engine);
NOTA_API int32_t nota_engine_add_pentad_track(NotaEngine* engine);
/* Adds an instrument track with the built-in Nota Consort (paraphonic semi-modular synth, kind 15). id (>0). */
NOTA_API int32_t nota_engine_add_consort_track(NotaEngine* engine);
+/* Adds an instrument track with the built-in Nota Keys (modelled electric piano, kind 16). id (>0). */
+NOTA_API int32_t nota_engine_add_keys_track(NotaEngine* engine);
/* UI editing channel for the track's instrument (e.g. Nota Rhythm step patterns):
* id/iarg/farg are instrument-specific (see the instrument's action()). */
NOTA_API void nota_track_instrument_action(NotaEngine* engine, int32_t track_id, int32_t id, int32_t iarg, float farg);
@@ -685,8 +687,9 @@ NOTA_API NotaResult nota_engine_note_off(NotaEngine* engine, int32_t pitch);
NOTA_API NotaResult nota_track_note_on(NotaEngine* engine, int32_t track_id, int32_t pitch, float velocity);
NOTA_API NotaResult nota_track_note_off(NotaEngine* engine, int32_t track_id, int32_t pitch);
/* Per-note expression (MPE) for live notes: dim 0 = pitch bend in semitones, 1 = pressure
- * 0..1, 2 = slide (CC74 timbre) 0..1 with 0.5 neutral. pitch -1 addresses the whole
- * instrument; its bend is the wheel normalized -1..+1 (the synth applies its own range).
+ * 0..1, 2 = slide (CC74 timbre) 0..1 with 0.5 neutral, 3 = sustain pedal (CC64) 0/1 —
+ * instrument-wide only (pitch -1). pitch -1 addresses the whole instrument; its bend is
+ * the wheel normalized -1..+1 (the synth applies its own range).
* A note-on resets the note's expression; send it after the note-on. The engine_ form
* reaches the tracks live notes reach; the track_ form one track (Nota Remote). */
NOTA_API NotaResult nota_engine_note_expression(NotaEngine* engine, int32_t pitch, int32_t dim, float value);
diff --git a/src/native/nota.engine/pluginhost/PluginHost.cpp b/src/native/nota.engine/pluginhost/PluginHost.cpp
index 42978949..562c6a51 100644
--- a/src/native/nota.engine/pluginhost/PluginHost.cpp
+++ b/src/native/nota.engine/pluginhost/PluginHost.cpp
@@ -637,6 +637,7 @@ public:
if (dim == 0) pending_.addEvent(juce::MidiMessage::pitchWheel(1, juce::jlimit(0, 16383, (int)std::lround((value + 1.0f) * 8191.5f))), 0);
else if (dim == 1) pending_.addEvent(juce::MidiMessage::channelPressureChange(1, u7(value)), 0);
else if (dim == 2) pending_.addEvent(juce::MidiMessage::controllerEvent(1, 74, u7(value)), 0);
+ else if (dim == 3) pending_.addEvent(juce::MidiMessage::controllerEvent(1, 64, value >= 0.5f ? 127 : 0), 0);
} else if (dim == 1) {
pending_.addEvent(juce::MidiMessage::aftertouchChange(1, pitch, u7(value)), 0);
}
diff --git a/src/native/nota.engine/src/Engine.h b/src/native/nota.engine/src/Engine.h
index 60cc67a2..c9a27299 100644
--- a/src/native/nota.engine/src/Engine.h
+++ b/src/native/nota.engine/src/Engine.h
@@ -635,6 +635,7 @@ public:
int32_t addMonolithTrack(); // built-in Nota Monolith (mono Model-D synth, kind 13)
int32_t addPentadTrack(); // built-in Nota Pentad (5-voice Prophet-5 poly, kind 14)
int32_t addConsortTrack(); // built-in Nota Consort (paraphonic semi-modular, kind 15)
+ int32_t addKeysTrack(); // built-in Nota Keys (modelled electric piano, kind 16)
void instrumentAction(int32_t trackId, int32_t id, int32_t iarg, float farg); // UI editing channel
bool setRhythmVoiceSample(int32_t trackId, int32_t voice, const std::string& path); // Phase 2
bool rhythmVoiceInfo(int32_t trackId, int32_t voice, NotaSamplerInfo* out) const; // sample id per voice
diff --git a/src/native/nota.engine/src/Engine_Devices.cpp b/src/native/nota.engine/src/Engine_Devices.cpp
index 9d1d5e7d..4776d94d 100644
--- a/src/native/nota.engine/src/Engine_Devices.cpp
+++ b/src/native/nota.engine/src/Engine_Devices.cpp
@@ -41,6 +41,7 @@
#include "Monolith.h"
#include "Pentad.h"
#include "Consort.h"
+#include "Keys.h"
#include "GrainSynth.h"
#include "Arpeggiator.h"
#include "MidiChord.h"
@@ -247,6 +248,18 @@ int32_t Engine::addConsortTrack() {
return id;
}
+int32_t Engine::addKeysTrack() {
+ auto g = std::make_shared<Graph>(*authoring_);
+ const int32_t id = nextTrackId_++;
+ auto track = std::make_shared<Track>(id, TrackType::Instrument);
+ auto inst = std::make_shared<Keys>();
+ inst->setSampleRate(transport_.sampleRate());
+ track->instrument = inst;
+ g->tracks.push_back(track);
+ publish(g);
+ return id;
+}
+
// UI editing channel for the track's instrument (e.g. Nota Rhythm step patterns). The
// instrument object is stable across snapshots, so this mutates it in place (message thread).
void Engine::instrumentAction(int32_t trackId, int32_t id, int32_t iarg, float farg) {
@@ -501,6 +514,7 @@ std::shared_ptr<Instrument> Engine::cloneInstrument(const Track& src) const {
case 13: { auto mo = std::make_shared<Monolith>(); mo->setSampleRate(sr); return mo; }
case 14: { auto pe = std::make_shared<Pentad>(); pe->setSampleRate(sr); return pe; }
case 15: { auto co = std::make_shared<Consort>(); co->setSampleRate(sr); return co; }
+ case 16: { auto ke = std::make_shared<Keys>(); ke->setSampleRate(sr); return ke; }
default: return nullptr;
}
}
@@ -635,6 +649,7 @@ std::shared_ptr<Instrument> makeBuiltinInstrument(int32_t kind) {
case 13: return std::make_shared<Monolith>();
case 14: return std::make_shared<Pentad>();
case 15: return std::make_shared<Consort>();
+ case 16: return std::make_shared<Keys>();
default: return nullptr; // Racks (3/4) / unknown: no simple swap
}
}
diff --git a/src/native/nota.engine/src/Engine_Recording.cpp b/src/native/nota.engine/src/Engine_Recording.cpp
index 17137fb4..fa68dd60 100644
--- a/src/native/nota.engine/src/Engine_Recording.cpp
+++ b/src/native/nota.engine/src/Engine_Recording.cpp
@@ -162,13 +162,15 @@ void Engine::noteOff(int32_t pitch) {
}
void Engine::noteExpression(int32_t pitch, int32_t dim, float value) {
- if (pitch < -1 || pitch > 127 || dim < 0 || dim >= kExprDims || !std::isfinite(value)) return;
+ if (pitch < -1 || pitch > 127 || dim < 0 || dim >= kExprWireDims || (dim >= kExprDims && pitch >= 0)
+ || !std::isfinite(value)) return;
std::lock_guard<std::mutex> lk(liveMidiMx_);
liveMidi_.push(MidiEvent{false, pitch, value, -1, dim});
}
void Engine::trackNoteExpression(int32_t trackId, int32_t pitch, int32_t dim, float value) {
- if (pitch < -1 || pitch > 127 || dim < 0 || dim >= kExprDims || !std::isfinite(value)) return;
+ if (pitch < -1 || pitch > 127 || dim < 0 || dim >= kExprWireDims || (dim >= kExprDims && pitch >= 0)
+ || !std::isfinite(value)) return;
std::lock_guard<std::mutex> lk(remoteMidiMx_);
remoteMidi_.push(MidiEvent{false, pitch, value, trackId, dim});
}
diff --git a/src/native/nota.engine/src/Keys.h b/src/native/nota.engine/src/Keys.h
new file mode 100644
index 00000000..c81d9ede
--- /dev/null
+++ b/src/native/nota.engine/src/Keys.h
@@ -0,0 +1,797 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Keys — the built-in physically modelled electric piano (kind 16). Nota's own DSP.
+//
+// hammer ─→ resonator (tine + tone bar | reed | string) ─→ PICKUP curve ─→ Σ voices
+// ↑ hardness, vel→hardness, noise ↑ decay, body, bright, key→bright
+// ─→ preamp (drive, bass, treble) ─→ tremolo (mono / stereo pan) ─→ phaser ─→ chorus
+// ─→ cabinet (Suitcase / Combo / DI) ─→ volume · pan
+//
+// Models. Tine and Suitcase: a cantilever tine (modes 1 : 6.27 : 17.55) coupled to a tone
+// bar a hair sharper that rings longer (the beat and the long sustain). Reed: a struck reed
+// with the same beam modes, shorter, into an electrostatic pickup (odd-heavy curve). Clav:
+// a string struck by a tangent (24 near-harmonic partials) read by two pickups — Upper,
+// Lower or Both — whose positions comb the spectrum.
+//
+// The hammer is a half-sine force pulse whose contact time comes from Hardness (+ velocity
+// × Vel→H), fed into two-pole mode resonators, so a soft hammer excites the upper modes
+// less on its own. The summed displacement (×velocity, ×MPE pressure) passes the PICKUP
+// transfer curve — the very curve the editor draws: Symmetry offsets the tine against the
+// pickup (even harmonics), Distance sets how hard it saturates (close = bark). Quiet notes
+// stay on the linear middle of the curve, loud ones reach its knees — the e-piano growl.
+//
+// The damper. Key up drops a damper on the modes (Damper sets how fast, upper modes damp
+// faster) with a felt thump (Rel N). The pedal — the Pedal param or a keyboard's CC64,
+// whichever is down — holds released notes; re-striking a ringing key re-excites the same
+// voice (the tine is still moving). Voices: 8 / 16 / 32 / 64, the quietest is stolen with
+// a 5 ms fade. Age detunes / re-voices every key by its own fixed amount (deterministic,
+// so a freeze equals the live render); Stretch is a piano-style octave stretch.
+//
+// MPE: bend retunes the modes, pressure pushes the tine into the pickup (more bark), slide
+// shifts the pickup symmetry (timbre); a keyboard's wheel bends ±2 semitones.
+//
+// All parameters ride the Instrument plugin-param interface (normalized 0..1, stable ids).
+// Header-only; allocation-free after construction.
+
+#pragma once
+
+#include "Instrument.h"
+#include "NoteExpression.h"
+
+#include <algorithm>
+#include <atomic>
+#include <cmath>
+#include <cstdint>
+#include <cstring>
+#include <memory>
+#include <string>
+#include <vector>
+
+#if defined(__SSE2__) || defined(_M_X64) || (defined(_M_IX86_FP) && _M_IX86_FP >= 2)
+#include <xmmintrin.h>
+#define NOTA_KEYS_FTZ_X86 1
+#elif defined(__aarch64__) && !defined(_MSC_VER)
+#define NOTA_KEYS_FTZ_ARM 1
+#endif
+
+namespace nota {
+
+namespace keys {
+
+constexpr float kPi = 3.14159265358979f;
+
+// The PICKUP transfer curve, shared with the editor's graph (KeysModel.cs mirrors it):
+// x = tine displacement (−1..1 at full scale), sym −1..1, dist 0..1, model 0..3.
+inline float pickupRaw(float x, float sym, float dist, int model) {
+ const float a = 0.3f + (1.0f - dist) * 3.2f;
+ if (model == 2) { // Reed — electrostatic: odd-heavy, a little symmetry
+ const float k = (1.0f - dist) * 0.8f;
+ return x / (1.0f + a * 0.6f * std::fabs(x)) * (1.0f + k * x * x) / (1.0f + k)
+ + sym * 0.35f * (2.0f - dist) * x * x;
+ }
+ const float aa = model == 3 ? a * 0.5f : a; // Clav — a gentler magnetic pickup
+ return x / (1.0f + aa * std::fabs(x)) + sym * 0.55f * (2.0f - dist) * x * x;
+}
+// The curve's peak magnitude on −1..1 (the editor scales its graph by the same number).
+inline float pickupNorm(float sym, float dist, int model) {
+ float mx = 0.0f;
+ for (int i = 0; i <= 60; ++i) mx = std::max(mx, std::fabs(pickupRaw(-1.0f + i / 30.0f, sym, dist, model)));
+ return mx > 1e-6f ? mx : 1.0f;
+}
+
+inline uint32_t hash32(uint32_t x) {
+ x ^= x >> 16; x *= 0x7feb352dU; x ^= x >> 15; x *= 0x846ca68bU; x ^= x >> 16;
+ return x;
+}
+// −1..1, fixed per (key, slot) — the Age offsets.
+inline float keyRand(int pitch, int slot) {
+ return static_cast<float>(hash32(static_cast<uint32_t>(pitch * 131 + slot * 7919 + 17)) & 0xFFFFFF) / 8388607.5f - 1.0f;
+}
+
+// RBJ biquad (transposed direct form II).
+struct Biquad {
+ float b0 = 1, b1 = 0, b2 = 0, a1 = 0, a2 = 0, z1 = 0, z2 = 0;
+ float tick(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.0f; }
+ void bypass() { b0 = 1; b1 = b2 = a1 = a2 = 0; }
+ void norm(double B0, double B1, double B2, double A0, double A1, double A2) {
+ b0 = static_cast<float>(B0 / A0); b1 = static_cast<float>(B1 / A0); b2 = static_cast<float>(B2 / A0);
+ a1 = static_cast<float>(A1 / A0); a2 = static_cast<float>(A2 / A0);
+ }
+ void lowpass(double fc, double q, double sr) {
+ const double w = 2.0 * 3.141592653589793 * std::min(fc, sr * 0.45) / sr, c = std::cos(w), al = std::sin(w) / (2.0 * q);
+ norm((1 - c) / 2, 1 - c, (1 - c) / 2, 1 + al, -2 * c, 1 - al);
+ }
+ void highpass(double fc, double q, double sr) {
+ const double w = 2.0 * 3.141592653589793 * std::min(fc, sr * 0.45) / sr, c = std::cos(w), al = std::sin(w) / (2.0 * q);
+ norm((1 + c) / 2, -(1 + c), (1 + c) / 2, 1 + al, -2 * c, 1 - al);
+ }
+ void peak(double fc, double q, double db, double sr) {
+ const double A = std::pow(10.0, db / 40.0), w = 2.0 * 3.141592653589793 * std::min(fc, sr * 0.45) / sr;
+ const double c = std::cos(w), al = std::sin(w) / (2.0 * q);
+ norm(1 + al * A, -2 * c, 1 - al * A, 1 + al / A, -2 * c, 1 - al / A);
+ }
+ void shelf(double fc, double db, double sr, bool high) {
+ const double A = std::pow(10.0, db / 40.0), w = 2.0 * 3.141592653589793 * std::min(fc, sr * 0.45) / sr;
+ const double c = std::cos(w), s = std::sin(w), al = s / 2.0 * std::sqrt(2.0), sq = 2.0 * std::sqrt(A) * al;
+ if (high) norm(A * ((A + 1) + (A - 1) * c + sq), -2 * A * ((A - 1) + (A + 1) * c), A * ((A + 1) + (A - 1) * c - sq),
+ (A + 1) - (A - 1) * c + sq, 2 * ((A - 1) - (A + 1) * c), (A + 1) - (A - 1) * c - sq);
+ else norm(A * ((A + 1) - (A - 1) * c + sq), 2 * A * ((A - 1) - (A + 1) * c), A * ((A + 1) - (A - 1) * c - sq),
+ (A + 1) + (A - 1) * c + sq, -2 * ((A - 1) + (A + 1) * c), (A + 1) + (A - 1) * c - sq);
+ }
+};
+
+} // namespace keys
+
+class Keys final : public Instrument {
+public:
+ static constexpr int kMaxVoices = 64, kMaxModes = 24;
+
+ // Parameter layout (normalized 0..1). Order == persisted state layout — APPEND ONLY.
+ enum Param {
+ Model = 0,
+ Hard, VelHard, Noise, // hammer
+ Decay, Body, Bright, KeyBright, // resonator
+ Sym, Dist, PuPos, // pickup
+ Damper, RelNoise, Pedal, // damper
+ Tune, Age, Stretch, Voices, // play
+ PreOn, Drive, Bass, Treble, // preamp
+ TremOn, TremMode, TremSync, TremRate, TremDepth,
+ PhaserOn, PhaserRate, PhaserDepth,
+ ChorusOn, ChorusMix,
+ Cab, Volume, Pan,
+ View, // editor state, not sound: card size (0 = L, 1 = S)
+ kNumParams
+ };
+
+ // scopeRead layout.
+ enum Scope { ScActive = 0, ScLimit, ScHeld, ScSustained, ScPedal, ScLfo, ScPeakL, ScPeakR, ScLastNote, kScopeN };
+
+ Keys() {
+ // "Mk I Stage": a Tine through a DI, the preamp warm, no modulation effects.
+ for (int i = 0; i < kNumParams; ++i) pn_[i].store(0.0f, std::memory_order_relaxed);
+ set(Model, 0.0f);
+ set(Hard, 0.5f); set(VelHard, 0.6f); set(Noise, 0.25f);
+ set(Decay, 0.5f); set(Body, 0.5f); set(Bright, 0.5f); set(KeyBright, 0.65f);
+ set(Sym, 0.6f); set(Dist, 0.4f); set(PuPos, 0.5f);
+ set(Damper, 0.7f); set(RelNoise, 0.3f); set(Pedal, 0.0f);
+ set(Tune, 0.5f); set(Age, 0.15f); set(Stretch, 0.3f); set(Voices, 2.0f / 3.0f);
+ set(PreOn, 1.0f); set(Drive, 0.35f); set(Bass, 0.62f); set(Treble, 0.46f);
+ set(TremOn, 0.0f); set(TremMode, 1.0f); set(TremSync, 0.0f); set(TremRate, 0.65f); set(TremDepth, 0.5f);
+ set(PhaserOn, 0.0f); set(PhaserRate, 0.3f); set(PhaserDepth, 0.6f);
+ set(ChorusOn, 0.0f); set(ChorusMix, 0.35f);
+ set(Cab, 1.0f); set(Volume, 0.8f); set(Pan, 0.5f);
+ set(View, 0.0f);
+ std::memset(chBuf_, 0, sizeof(chBuf_));
+ for (auto& t : tele_) t.store(0.0f, std::memory_order_relaxed);
+ }
+
+ int32_t kind() const override { return 16; }
+ const char* displayName() const override { return "Nota Keys"; }
+
+ void setSampleRate(double sr) override { pendingRate_.store(sr > 0 ? sr : 44100.0, std::memory_order_relaxed); }
+
+ int32_t activeVoiceCount() const override { return static_cast<int32_t>(tele_[ScActive].load(std::memory_order_relaxed)); }
+ int32_t scopeRead(float* out, int32_t maxN) const override {
+ const int n = std::min<int>(maxN, kScopeN);
+ for (int i = 0; i < n; ++i) out[i] = tele_[i].load(std::memory_order_relaxed);
+ return n;
+ }
+
+ // MPE: bend → pitch, pressure → drive into the pickup (+ a little level), slide → pickup symmetry.
+ bool supportsMpe() const override { return true; }
+ void noteExpression(int32_t pitch, int32_t dim, float value) override {
+ if (pitch < 0) {
+ if (dim == ExprSustain) cc64_ = value >= 0.5f;
+ else gexpr_.set(dim, value);
+ return;
+ }
+ if (dim < 0 || dim >= kExprDims) return;
+ float add[kExprDims]; gexpr_.offsets(kWheelRange, add);
+ for (auto& v : voices_)
+ if (v.active && v.pitch == pitch && v.held) v.ex.set(dim, value, add);
+ }
+
+ void setTransportInfo(const TransportInfo& ti) override {
+ looping_ = ti.isLooping; loopStart_ = ti.ppqLoopStart;
+ }
+
+ void setTransport(double beatStart, double samplesPerBeat, bool playing) override {
+ // A jump while rolling (a seek, a fresh play from elsewhere — not a loop wrap) restarts
+ // like a play edge, and the notes from before it stop: the engine re-chases held clip notes.
+ if (playing && playing_ && samplesPerBeat > 0.0) {
+ const double expect = beat_ + sinceBlock_ / std::max(1.0, spb_);
+ const bool wrap = looping_ && std::fabs(beatStart - loopStart_) < 1e-6;
+ if (std::fabs(beatStart - expect) * samplesPerBeat > 2.0 && !wrap) {
+ fxRestart_ = true;
+ for (auto& v : voices_) v.active = false;
+ }
+ }
+ if (samplesPerBeat > 0.0) spb_ = samplesPerBeat;
+ // A play edge restarts the effects (tails, LFOs, smoothing) from a fixed state, so a
+ // freeze or a bounce equals what a fresh play of the same bars sounds like.
+ // Released tails from before the edge stop with it; keys still held keep sounding.
+ if (playing && !playing_) {
+ fxRestart_ = true;
+ for (auto& v : voices_) if (v.active && !v.held) v.active = false;
+ }
+ beat_ = beatStart; playing_ = playing; sinceBlock_ = 0;
+ }
+
+ // ---- parameters -----------------------------------------------------------
+ // Display names group by the part before the last space (the automation menu nests on it).
+ int32_t pluginParamCount() const override { return kNumParams; }
+ std::string pluginParamId(int32_t i) const override {
+ static const char* ids[kNumParams] = {
+ "model", "hard", "velhard", "noise", "decay", "body", "bright", "keybright",
+ "sym", "dist", "pupos", "damper", "relnoise", "pedal",
+ "tune", "age", "stretch", "voices",
+ "preon", "drive", "bass", "treble",
+ "tremon", "tremmode", "tremsync", "tremrate", "tremdepth",
+ "phaseron", "phaserrate", "phaserdepth", "choruson", "chorusmix",
+ "cab", "volume", "pan", "view" };
+ return (i >= 0 && i < kNumParams) ? std::string(ids[i]) : std::string{};
+ }
+ std::string pluginParamName(int32_t i) const override {
+ static const char* nm[kNumParams] = {
+ "Model", "Hammer Hardness", "Hammer Vel-Hardness", "Hammer Noise",
+ "Resonator Decay", "Resonator Body", "Resonator Bright", "Resonator Key-Bright",
+ "Pickup Symmetry", "Pickup Distance", "Pickup Position",
+ "Damper Amount", "Damper Release-Noise", "Damper Pedal",
+ "Play Tune", "Play Age", "Play Stretch", "Play Voices",
+ "Preamp On", "Preamp Drive", "Preamp Bass", "Preamp Treble",
+ "Tremolo On", "Tremolo Mode", "Tremolo Sync", "Tremolo Rate", "Tremolo Depth",
+ "Phaser On", "Phaser Rate", "Phaser Depth", "Chorus On", "Chorus Mix",
+ "Cabinet Type", "Output Volume", "Output Pan", "View" };
+ return (i >= 0 && i < kNumParams) ? std::string(nm[i]) : std::string{};
+ }
+ float pluginParamGet(int32_t i) const override {
+ return (i >= 0 && i < kNumParams) ? pn_[i].load(std::memory_order_relaxed) : 0.0f;
+ }
+ void pluginParamSet(int32_t i, float v) override {
+ if (i >= 0 && i < kNumParams && std::isfinite(v)) pn_[i].store(std::clamp(v, 0.0f, 1.0f), std::memory_order_relaxed);
+ }
+ int32_t pluginParamIndexOfId(const std::string& id) const override {
+ for (int32_t i = 0; i < kNumParams; ++i) if (pluginParamId(i) == id) return i;
+ return -1;
+ }
+
+ std::vector<uint8_t> getState() const override {
+ std::vector<uint8_t> b(kNumParams * sizeof(float));
+ for (int i = 0; i < kNumParams; ++i) {
+ const float v = pn_[i].load(std::memory_order_relaxed);
+ std::memcpy(b.data() + i * sizeof(float), &v, sizeof(float));
+ }
+ return b;
+ }
+ void setState(const uint8_t* data, int32_t size) override {
+ if (!data || size <= 0) return;
+ const int n = std::min<int>(kNumParams, size / static_cast<int>(sizeof(float)));
+ for (int i = 0; i < n; ++i) {
+ float v; std::memcpy(&v, data + i * sizeof(float), sizeof(float));
+ if (std::isfinite(v)) pn_[i].store(std::clamp(v, 0.0f, 1.0f), std::memory_order_relaxed);
+ }
+ }
+ std::shared_ptr<Instrument> clone() const override {
+ auto k = std::make_shared<Keys>();
+ for (int i = 0; i < kNumParams; ++i) k->pn_[i].store(pn_[i].load(std::memory_order_relaxed), std::memory_order_relaxed);
+ k->setSampleRate(pendingRate_.load(std::memory_order_relaxed));
+ return k;
+ }
+
+ // ---- notes ----------------------------------------------------------------
+ void noteOn(int32_t pitch, float velocity) override {
+ if (pitch < 0 || pitch > 127) return;
+ applyRate();
+ const float vel = std::clamp(velocity, 0.0f, 1.0f);
+ lastNote_ = pitch;
+ // Re-striking a ringing key hits the same tine again.
+ for (auto& v : voices_)
+ if (v.active && v.pitch == pitch && v.kill <= 0) { strike(v, vel, false); return; }
+
+ int active = 0;
+ for (auto& v : voices_) if (v.active && v.kill <= 0) ++active;
+ if (active >= voiceLimit()) {
+ Voice* q = nullptr; // steal the quietest, released ones first
+ for (auto& v : voices_) {
+ if (!v.active || v.kill > 0) continue;
+ if (!q || (v.held < q->held) || (v.held == q->held && v.peak < q->peak)) q = &v;
+ }
+ if (q) q->kill = killLen();
+ }
+ Voice* slot = nullptr;
+ for (auto& v : voices_) if (!v.active) { slot = &v; break; }
+ if (!slot) { // all 64 busy: take the quietest outright
+ slot = &voices_[0];
+ for (auto& v : voices_) if (v.peak < slot->peak) slot = &v;
+ }
+ slot->pitch = pitch;
+ strike(*slot, vel, true);
+ }
+
+ void noteOff(int32_t pitch) override {
+ for (auto& v : voices_) {
+ if (!v.active || v.pitch != pitch || !v.held) continue;
+ v.held = false;
+ if (pedalDown_) v.sustained = true;
+ else damp(v);
+ }
+ }
+
+ void allNotesOff() override {
+ for (auto& v : voices_) v.active = false;
+ gexpr_.reset(); cc64_ = false; pedalDown_ = false;
+ dcL_ = 0.0f; dcPrev_ = 0.0f;
+ }
+
+ // ---- render ---------------------------------------------------------------
+ void render(float* out, int32_t frames) override {
+ FtzGuard ftz;
+ applyRate();
+ const double sr = sr_;
+
+ // Block snapshot.
+ const int model = modelIndex();
+ const float sym = (get(Sym) - 0.5f) * 2.0f, dist = get(Dist);
+ const float pnorm = keys::pickupNorm(sym, dist, model);
+ const float noiseLin = dbMap(get(Noise)) * 0.5f, relLin = dbMap(get(RelNoise)) * 0.5f;
+
+ // The pedal: param or CC64. Lifting it drops the dampers on every held-over note.
+ const bool pedal = get(Pedal) >= 0.5f || cc64_;
+ if (pedalDown_ && !pedal)
+ for (auto& v : voices_) if (v.active && v.sustained) { v.sustained = false; damp(v); }
+ pedalDown_ = pedal;
+
+ float exAdd[kExprDims]; gexpr_.offsets(kWheelRange, exAdd);
+ const float exprCoef = exprSmoothCoef(sr);
+
+ float mono[kChunk];
+ int done = 0;
+ while (done < frames) {
+ const int n = std::min<int>(kChunk, frames - done);
+ std::fill(mono, mono + n, 0.0f);
+ for (auto& v : voices_) if (v.active) renderVoice(v, mono, n, model, sym, dist, pnorm, noiseLin, relLin, exAdd, exprCoef);
+ renderFx(mono, out + done * 2, n);
+ done += n;
+ }
+ publishTelemetry();
+ }
+
+private:
+ static constexpr int kChunk = 64;
+ static constexpr int kCtl = 32; // control-rate interval (bend / damper retune)
+ static constexpr float kWheelRange = 2.0f;
+ static constexpr int kChLen = 8192; // chorus delay line (≥ 25 ms at 192 kHz)
+
+ struct Voice {
+ bool active = false, held = false, sustained = false, damped = false;
+ int32_t pitch = 60, model = 0;
+ float vel = 0.0f, peak = 0.0f, level = 1.0f, symOff = 0.0f;
+ int nModes = 0;
+ float a1[kMaxModes] = {}, a2[kMaxModes] = {}, b[kMaxModes] = {}, y1[kMaxModes] = {}, y2[kMaxModes] = {};
+ float w[kMaxModes] = {}, R[kMaxModes] = {}, Rd[kMaxModes] = {}, amp[kMaxModes] = {};
+ // hammer pulse
+ int pulseN = 0, pulsePos = 0; float pulseK = 0.0f;
+ float drive = 0.75f;
+ // hammer noise / release thump
+ float hnEnv = 0.0f, hnDec = 0.0f, hnG = 0.0f, hnF = 0.1f, hnIc1 = 0.0f, hnIc2 = 0.0f;
+ float rnEnv = 0.0f, rnDec = 0.0f, rnLp = 0.0f;
+ uint32_t rng = 1;
+ int kill = 0; // >0: stolen, fading out over killLen()
+ int ctl = 0;
+ float exBend = 0.0f;
+ VoiceExpr ex;
+ };
+
+ // ---- helpers ----------------------------------------------------------------
+ struct FtzGuard {
+#if defined(NOTA_KEYS_FTZ_X86)
+ unsigned int old; FtzGuard() : old(_mm_getcsr()) { _mm_setcsr(old | 0x8040u); } ~FtzGuard() { _mm_setcsr(old); }
+#elif defined(NOTA_KEYS_FTZ_ARM)
+ uint64_t old = 0;
+ FtzGuard() { asm volatile("mrs %0, fpcr" : "=r"(old)); const uint64_t n = old | (1ull << 24); asm volatile("msr fpcr, %0" : : "r"(n)); }
+ ~FtzGuard() { asm volatile("msr fpcr, %0" : : "r"(old)); }
+#endif
+ };
+
+ void set(Param p, float v) { pn_[p].store(v, std::memory_order_relaxed); }
+ float get(Param p) const { return pn_[p].load(std::memory_order_relaxed); }
+ static double expMap(double v, double lo, double hi) { return lo * std::pow(hi / lo, std::clamp(v, 0.0, 1.0)); }
+ int modelIndex() const { return std::clamp(static_cast<int>(std::lround(get(Model) * 3.0f)), 0, 3); }
+ int voiceLimit() const { static const int n[4] = { 8, 16, 32, 64 }; return n[std::clamp(static_cast<int>(std::lround(get(Voices) * 3.0f)), 0, 3)]; }
+ int killLen() const { return std::max(8, static_cast<int>(0.005 * sr_)); }
+ // Noise levels: 0 = off, else −60 … −12 dB (√-shaped so the low end is finely graded).
+ static float dbMap(float v) { return v <= 1e-3f ? 0.0f : std::pow(10.0f, (-60.0f + 48.0f * std::sqrt(v)) / 20.0f); }
+ float rnd(Voice& v) { v.rng = v.rng * 1664525u + 1013904223u; return static_cast<float>(v.rng >> 8) / 8388608.0f - 1.0f; }
+
+ void applyRate() {
+ const double r = pendingRate_.load(std::memory_order_relaxed);
+ if (r != sr_) { sr_ = r; for (auto& v : voices_) v.active = false; fxDirty_ = true; }
+ }
+
+ // ---- the strike: build the modes for this key + model, start the hammer pulse ----
+ void strike(Voice& v, float vel, bool fresh) {
+ const int p = v.pitch;
+ const int model = modelIndex();
+ const float age = get(Age);
+ const double stretchC = get(Stretch) * 30.0 * (p >= 60 ? 1.0 : -1.0) * std::pow(std::fabs(p - 60.0) / 48.0, 2.0);
+ const double cents = (get(Tune) - 0.5) * 100.0 + stretchC + age * 12.0 * keys::keyRand(p, 0);
+ const double f0 = 440.0 * std::pow(2.0, (p - 69) / 12.0 + cents / 1200.0);
+ const double nyq = sr_ * 0.45;
+
+ // Hammer: hardness (+ velocity) → contact time.
+ const float hard = std::clamp(get(Hard) + get(VelHard) * (vel - 0.55f) * 1.2f, 0.0f, 1.0f);
+ const double contact = expMap(1.0 - hard, 0.00035, 0.0065) * (model == 3 ? 0.5 : 1.0);
+ const int pulseN = std::max(2, static_cast<int>(contact * sr_));
+
+ // Resonator character.
+ const double bodyF = get(Body) * 2.0;
+ const double kb = (get(KeyBright) - 0.5) * 3.0; // ±1.5 octaves of brightness per 2 octaves of key
+ const double brightF = expMap(get(Bright), 0.15, 4.0) * std::pow(2.0, kb * (p - 60) / 24.0);
+ const double decMul = expMap(get(Decay), 0.25, 4.0) * (1.0 + age * 0.35 * keys::keyRand(p, 1));
+ double T = 6.5 * std::pow(2.0, -(p - 36) / 18.0); // fundamental ring time (s) at Decay 100 %
+ T = std::clamp(T, 0.3, 14.0) * decMul;
+
+ struct M { double ratio, amp, tau; };
+ M ms[kMaxModes]; int nm = 0;
+ auto add = [&](double r, double a, double tauMul) { if (nm < kMaxModes) ms[nm++] = { r, a, T * tauMul }; };
+ if (model <= 1) {
+ const bool suit = model == 1;
+ add(1.0, 1.0, 1.0);
+ add(1.0 + (suit ? 0.45 : 0.35) / f0, (suit ? 0.55 : 0.4) * bodyF, 1.7); // tone bar
+ add(suit ? 5.9 : 6.27, (suit ? 0.16 : 0.22) * brightF, 0.16); // tine bell
+ add(17.55, 0.06 * brightF, 0.05);
+ add(2.0, 0.04 * bodyF, 0.4);
+ } else if (model == 2) {
+ T *= 0.6;
+ add(1.0, 0.6 + 0.4 * bodyF, 1.0);
+ add(6.27, 0.3 * brightF, 0.2);
+ add(17.55, 0.1 * brightF, 0.07);
+ add(3.0, 0.03 * brightF, 0.25);
+ } else {
+ T *= 0.45;
+ const int pos = std::clamp(static_cast<int>(std::lround(get(PuPos) * 2.0f)), 0, 2);
+ const double B = 0.00012;
+ for (int k = 1; k <= kMaxModes; ++k) {
+ const double r = k * std::sqrt(1.0 + B * k * k);
+ if (f0 * r >= nyq) break;
+ const double wu = std::sin(k * keys::kPi * 0.2), wl = std::sin(k * keys::kPi * 0.34);
+ const double pw = pos == 0 ? wu : pos == 2 ? wl : 0.6 * (wu + wl);
+ double a = std::sin(k * keys::kPi * 0.12) / k * pw * 3.0 * std::pow(brightF, 0.5 * std::log2((double)k));
+ if (k <= 2) a *= 0.5 + 0.5 * bodyF;
+ add(r, a, 1.0 / (1.0 + 0.012 * k * k * (1.6 - get(Bright))));
+ }
+ }
+
+ // Damper time for a released note (s); upper modes go faster.
+ const double damp = expMap(1.0 - get(Damper), 0.025, 3.0) * (model == 3 ? 0.5 : 1.0);
+ v.nModes = 0;
+ for (int i = 0; i < nm; ++i) {
+ const double f = f0 * ms[i].ratio;
+ if (f >= nyq || f <= 0.0 || std::fabs(ms[i].amp) < 1e-5) continue;
+ const int m = v.nModes++;
+ const double w = 2.0 * 3.141592653589793 * f / sr_;
+ const double R = std::exp(-1.0 / (ms[i].tau * sr_));
+ const double tauD = std::min(ms[i].tau, damp / std::sqrt(ms[i].ratio));
+ v.w[m] = static_cast<float>(w);
+ v.R[m] = static_cast<float>(R);
+ v.Rd[m] = static_cast<float>(std::exp(-1.0 / (tauD * sr_)));
+ v.amp[m] = static_cast<float>(ms[i].amp);
+ v.a1[m] = static_cast<float>(2.0 * R * std::cos(w));
+ v.a2[m] = static_cast<float>(R * R);
+ v.b[m] = static_cast<float>(ms[i].amp * std::sin(w));
+ if (fresh) { v.y1[m] = 0.0f; v.y2[m] = 0.0f; }
+ }
+ if (!fresh) // a re-strike rebuilt the table — clear the modes it no longer has
+ for (int m = v.nModes; m < kMaxModes; ++m) { v.y1[m] = v.y2[m] = 0.0f; }
+
+ v.model = model;
+ v.vel = vel;
+ v.pulseN = pulseN; v.pulsePos = 0;
+ v.pulseK = static_cast<float>(3.141592653589793 / (2.0 * pulseN)); // Σ pulse = 1
+ v.drive = 0.75f * std::pow(std::max(vel, 0.02f), 0.9f);
+ v.level = static_cast<float>(1.0 + age * 0.25 * keys::keyRand(p, 2));
+ v.symOff = age * 0.15f * keys::keyRand(p, 3);
+ v.rng = keys::hash32(static_cast<uint32_t>(p * 977 + static_cast<int>(vel * 127.0f) * 31 + 5));
+ // Hammer noise: a short band-passed burst near the strike.
+ v.hnEnv = 1.0f;
+ v.hnDec = static_cast<float>(std::exp(-1.0 / ((0.004 + 0.006 * (1.0 - hard)) * sr_)));
+ v.hnG = vel * (1.0f + age);
+ v.hnF = static_cast<float>(std::tan(3.141592653589793 * std::min(1500.0 * std::pow(2.0, (p - 60) / 24.0) * (0.5 + hard), sr_ * 0.4) / sr_));
+ if (fresh) { v.hnIc1 = v.hnIc2 = 0.0f; v.rnEnv = 0.0f; v.rnLp = 0.0f; v.peak = vel; }
+ v.held = true; v.sustained = false; v.damped = false; v.kill = 0;
+ v.active = true;
+ float add2[kExprDims]; gexpr_.offsets(kWheelRange, add2);
+ v.ex.reset(add2);
+ v.exBend = 1e9f; v.ctl = 0; // the coefficients follow the (reset) bend on the first tick
+ }
+
+ void damp(Voice& v) {
+ if (v.damped) return;
+ v.damped = true;
+ v.ctl = 0; v.exBend = 1e9f; // re-derive coefficients with the damper R on the next tick
+ v.rnEnv = std::max(v.rnEnv, std::min(1.0f, v.vel * 1.2f));
+ v.rnDec = static_cast<float>(std::exp(-1.0 / (0.03 * sr_)));
+ }
+
+ void retune(Voice& v, float bend) {
+ const float mul = std::exp2(bend / 12.0f);
+ const float wMax = keys::kPi * 0.98f;
+ for (int m = 0; m < v.nModes; ++m) {
+ const float w = v.w[m] * mul;
+ const float R = v.damped ? v.Rd[m] : v.R[m];
+ if (w >= wMax) { v.a1[m] = 0.0f; v.a2[m] = 0.0f; v.b[m] = 0.0f; continue; }
+ v.a1[m] = 2.0f * R * std::cos(w);
+ v.a2[m] = R * R;
+ v.b[m] = v.amp[m] * std::sin(w);
+ }
+ }
+
+ void renderVoice(Voice& v, float* mono, int n, int /*model*/, float sym, float dist, float pnorm,
+ float noiseLin, float relLin, const float exAdd[kExprDims], float exprCoef) {
+ const float killStep = 1.0f / static_cast<float>(killLen());
+ const float invNorm = 1.0f / pnorm;
+ const float relLp = 1.0f - std::exp(-2.0f * keys::kPi * 700.0f / static_cast<float>(sr_));
+ for (int i = 0; i < n; ++i) {
+ v.ex.tick(exAdd, exprCoef);
+ if (--v.ctl <= 0) {
+ v.ctl = kCtl;
+ const float b = v.ex.bend();
+ if (std::fabs(b - v.exBend) > 0.002f) { v.exBend = b; retune(v, b); }
+ }
+ // Hammer force pulse.
+ float exc = 0.0f;
+ if (v.pulsePos < v.pulseN) { exc = std::sin((v.pulsePos + 0.5f) * 2.0f * v.pulseK) * v.pulseK; ++v.pulsePos; }
+ // Modes → displacement.
+ float x = 0.0f;
+ for (int m = 0; m < v.nModes; ++m) {
+ const float y = v.a1[m] * v.y1[m] - v.a2[m] * v.y2[m] + v.b[m] * exc;
+ v.y2[m] = v.y1[m]; v.y1[m] = y;
+ x += y;
+ }
+ // Pickup.
+ const float xd = std::clamp(x * v.drive * (1.0f + 0.6f * v.ex.pressure()), -1.6f, 1.6f);
+ const float s = std::clamp(sym + v.symOff + 0.4f * v.ex.slide(), -1.5f, 1.5f);
+ float o = keys::pickupRaw(xd, s, dist, v.model) * invNorm * v.level * (1.0f + 0.3f * v.ex.pressure());
+ // Hammer + damper noise.
+ if (v.hnEnv > 1e-4f && noiseLin > 0.0f) {
+ const float nz = rnd(v);
+ const float g = v.hnF, k = 1.2f;
+ const float a1 = 1.0f / (1.0f + g * (g + k)), a2 = g * a1;
+ const float v1 = a1 * v.hnIc1 + a2 * (nz - v.hnIc2);
+ const float v2 = v.hnIc2 + g * v1;
+ v.hnIc1 = 2.0f * v1 - v.hnIc1; v.hnIc2 = 2.0f * v2 - v.hnIc2;
+ o += v1 * v.hnEnv * v.hnG * noiseLin * 4.0f;
+ v.hnEnv *= v.hnDec;
+ }
+ if (v.rnEnv > 1e-4f) {
+ v.rnLp += relLp * (rnd(v) - v.rnLp);
+ o += v.rnLp * v.rnEnv * relLin * 6.0f;
+ v.rnEnv *= v.rnDec;
+ }
+ if (v.kill > 0) {
+ o *= static_cast<float>(v.kill) * killStep;
+ if (--v.kill <= 0) { v.active = false; return; }
+ }
+ mono[i] += o * 0.22f;
+ v.peak = std::max(v.peak * 0.9995f, std::fabs(o));
+ }
+ if (v.peak < 3e-5f && v.pulsePos >= v.pulseN && v.rnEnv < 1e-4f) v.active = false; // rang out
+ }
+
+ // ---- the effects chain (mono voices in, stereo out, added into out) ----------
+ void updateFx() {
+ const double sr = sr_;
+ const int cab = std::clamp(static_cast<int>(std::lround(get(Cab) * 3.0f)), 0, 3);
+ const float bass = (get(Bass) - 0.5f) * 24.0f, treble = (get(Treble) - 0.5f) * 24.0f;
+ if (fxDirty_ || cab != cabCache_ || bass != bassCache_ || treble != trebleCache_) {
+ loShelf_.shelf(200.0, bass, sr, false);
+ hiShelf_.shelf(2500.0, treble, sr, true);
+ for (int c = 0; c < 2; ++c) {
+ auto* q = cabF_[c];
+ switch (cab) {
+ case 1: q[0].highpass(45, 0.7, sr); q[1].peak(110, 1.0, 3.0, sr); q[2].peak(900, 0.8, -2.0, sr); q[3].lowpass(6000, 0.7, sr); break;
+ case 2: q[0].highpass(120, 0.7, sr); q[1].peak(1600, 0.9, 4.0, sr); q[2].peak(300, 1.0, 1.5, sr); q[3].lowpass(4500, 0.8, sr); break;
+ case 3: q[0].highpass(25, 0.7, sr); q[1].bypass(); q[2].bypass(); q[3].lowpass(16000, 0.7, sr); break;
+ default: for (int k = 0; k < 4; ++k) q[k].bypass(); break;
+ }
+ }
+ if (fxDirty_ || cab != cabCache_) for (int c = 0; c < 2; ++c) for (int k = 0; k < 4; ++k) cabF_[c][k].clear();
+ cabCache_ = cab; bassCache_ = bass; trebleCache_ = treble; fxDirty_ = false;
+ }
+ }
+
+ double tremHz() const {
+ if (get(TremSync) >= 0.5f) {
+ static const double cpb[8] = { 0.25, 0.5, 1.0, 2.0, 3.0, 4.0, 6.0, 8.0 }; // 1/1 … 1/32
+ const int d = std::clamp(static_cast<int>(std::lround(get(TremRate) * 7.0f)), 0, 7);
+ return cpb[d] * sr_ / std::max(1.0, spb_);
+ }
+ return expMap(get(TremRate), 0.5, 15.0);
+ }
+ double tremCyclesPerBeat() const {
+ static const double cpb[8] = { 0.25, 0.5, 1.0, 2.0, 3.0, 4.0, 6.0, 8.0 };
+ return cpb[std::clamp(static_cast<int>(std::lround(get(TremRate) * 7.0f)), 0, 7)];
+ }
+
+ void renderFx(const float* mono, float* out, int n) {
+ if (fxRestart_) {
+ fxRestart_ = false;
+ resetFx();
+ lfo_ = 0.0; phLfo_ = 0.0; chL1_ = 0.0; chL2_ = 0.37; chW_ = 0;
+ sDepth_ = sPh_ = sCh_ = sVol_ = 0.0f;
+ }
+ updateFx();
+ const double sr = sr_;
+ const bool preOn = get(PreOn) >= 0.5f;
+ const float driveG = static_cast<float>(expMap(get(Drive), 1.0, 14.0));
+ const float driveComp = 1.0f / std::pow(driveG, 0.6f);
+ const bool tremOn = get(TremOn) >= 0.5f, stereo = get(TremMode) >= 0.5f;
+ const float tremDepth = tremOn ? get(TremDepth) : 0.0f;
+ const double tremInc = tremHz() / sr;
+ // Tempo-synced tremolo locks to the grid while the transport rolls (a freeze matches).
+ // (render() runs in segments between note events; sinceBlock_ counts the block's frames so far.)
+ if (tremOn && get(TremSync) >= 0.5f && playing_) {
+ const double ph = (beat_ + sinceBlock_ / std::max(1.0, spb_)) * tremCyclesPerBeat();
+ lfo_ = ph - std::floor(ph);
+ }
+ sinceBlock_ += n;
+ const bool phOn = get(PhaserOn) >= 0.5f;
+ const double phInc = expMap(get(PhaserRate), 0.05, 5.0) / sr;
+ const float phDepth = get(PhaserDepth);
+ const bool chOn = get(ChorusOn) >= 0.5f;
+ const float chMixT = chOn ? get(ChorusMix) : 0.0f;
+ const float vol = volumeGain(get(Volume));
+ const float pan = (get(Pan) - 0.5f) * 2.0f;
+ const float panL = std::cos((pan + 1.0f) * 0.25f * keys::kPi) * 1.41421356f;
+ const float panR = std::sin((pan + 1.0f) * 0.25f * keys::kPi) * 1.41421356f;
+ const float sm = 1.0f - std::exp(-1.0f / (0.01f * static_cast<float>(sr)));
+ const float dcR = 1.0f - static_cast<float>(2.0 * 3.141592653589793 * 12.0 / sr);
+ const float chBase = static_cast<float>(0.007 * sr), chDepth = static_cast<float>(0.0025 * sr);
+ const double chInc1 = 0.52 / sr, chInc2 = 0.63 / sr;
+
+ for (int i = 0; i < n; ++i) {
+ // DC blocker (the pickup's even term carries DC with the note's envelope).
+ float x = mono[i];
+ const float dc = x - dcPrev_ + dcR * dcL_;
+ dcPrev_ = x; dcL_ = dc; x = dc;
+
+ // Preamp.
+ if (preOn) {
+ const float d = x * driveG;
+ x = (d / (1.0f + std::fabs(d)) + 0.08f * d / (1.0f + d * d)) * driveComp * 1.6f;
+ x = hiShelf_.tick(loShelf_.tick(x));
+ }
+
+ // Tremolo (mono amplitude, or the stereo pan of a Suitcase).
+ sDepth_ += (tremDepth - sDepth_) * sm;
+ float l = x, r = x;
+ if (sDepth_ > 1e-4f) {
+ const float sh = std::tanh(2.2f * std::sin(static_cast<float>(lfo_) * 2.0f * keys::kPi)) / std::tanh(2.2f);
+ if (stereo) { l *= 1.0f - sDepth_ * (1.0f + sh) * 0.5f; r *= 1.0f - sDepth_ * (1.0f - sh) * 0.5f; }
+ else { const float g = 1.0f - sDepth_ * (1.0f + sh) * 0.5f; l *= g; r *= g; }
+ }
+ lfo_ += tremInc; if (lfo_ >= 1.0) lfo_ -= 1.0;
+
+ // Phaser: four first-order all-passes per side, the sweep a quarter-turn apart.
+ sPh_ += ((phOn ? 1.0f : 0.0f) - sPh_) * sm;
+ if (sPh_ > 1e-4f) {
+ phLfo_ += phInc; if (phLfo_ >= 1.0) phLfo_ -= 1.0;
+ for (int c = 0; c < 2; ++c) {
+ const float ph = static_cast<float>(phLfo_) + c * 0.25f;
+ const float tri = 1.0f - 2.0f * std::fabs(ph - std::floor(ph) - 0.5f) * 2.0f; // −1..1
+ const float fc = 700.0f * std::exp2(tri * 1.7f * phDepth);
+ const float t = std::tan(keys::kPi * std::min(fc, static_cast<float>(sr) * 0.4f) / static_cast<float>(sr));
+ const float a = (t - 1.0f) / (t + 1.0f);
+ float in = (c ? r : l) + phFb_[c] * 0.35f;
+ for (int s = 0; s < 4; ++s) {
+ const float y = a * in + phZ_[c][s];
+ phZ_[c][s] = in - a * y;
+ in = y;
+ }
+ phFb_[c] = in;
+ float& ch = c ? r : l;
+ ch += (0.5f * (ch + in) - ch) * sPh_;
+ }
+ }
+
+ // Chorus: a modulated delay per side.
+ sCh_ += (chMixT - sCh_) * sm;
+ chBuf_[0][chW_] = l; chBuf_[1][chW_] = r;
+ if (sCh_ > 1e-4f) {
+ chL1_ += chInc1; if (chL1_ >= 1.0) chL1_ -= 1.0;
+ chL2_ += chInc2; if (chL2_ >= 1.0) chL2_ -= 1.0;
+ const float dL = chBase + chDepth * std::sin(static_cast<float>(chL1_) * 2.0f * keys::kPi);
+ const float dR = chBase + chDepth * std::sin(static_cast<float>(chL2_) * 2.0f * keys::kPi + 1.7f);
+ const float wl = readCh(0, dL), wr = readCh(1, dR);
+ l = l * (1.0f - 0.5f * sCh_) + wl * 0.7f * sCh_;
+ r = r * (1.0f - 0.5f * sCh_) + wr * 0.7f * sCh_;
+ }
+ chW_ = (chW_ + 1) & (kChLen - 1);
+
+ // Cabinet.
+ for (int k = 0; k < 4; ++k) { l = cabF_[0][k].tick(l); r = cabF_[1][k].tick(r); }
+
+ // Output.
+ sVol_ += (vol - sVol_) * sm;
+ l *= sVol_ * panL; r *= sVol_ * panR;
+ if (!std::isfinite(l) || !std::isfinite(r)) { resetFx(); l = r = 0.0f; }
+ out[i * 2] += l; out[i * 2 + 1] += r;
+ pkL_ = std::max(pkL_ * 0.9997f, std::fabs(l));
+ pkR_ = std::max(pkR_ * 0.9997f, std::fabs(r));
+ }
+ }
+
+ float readCh(int c, float delay) const {
+ float rp = static_cast<float>(chW_) - delay;
+ while (rp < 0.0f) rp += kChLen;
+ const int i0 = static_cast<int>(rp);
+ const float fr = rp - i0;
+ return chBuf_[c][i0 & (kChLen - 1)] * (1.0f - fr) + chBuf_[c][(i0 + 1) & (kChLen - 1)] * fr;
+ }
+
+ void resetFx() {
+ loShelf_.clear(); hiShelf_.clear();
+ for (auto& q : cabF_) for (auto& f : q) f.clear();
+ for (auto& z : phZ_) for (auto& s : z) s = 0.0f;
+ phFb_[0] = phFb_[1] = 0.0f; dcL_ = dcPrev_ = 0.0f;
+ std::memset(chBuf_, 0, sizeof(chBuf_));
+ }
+
+ // Volume: 0.8 = 0 dB, 1 = +6 dB, a log taper below (0.4 ≈ −18 dB), 0 = silent.
+ static float volumeGain(float v) {
+ if (v <= 1e-3f) return 0.0f;
+ const float db = v >= 0.8f ? (v - 0.8f) * 30.0f : 60.0f * std::log10(v / 0.8f);
+ return std::pow(10.0f, db / 20.0f);
+ }
+
+ void publishTelemetry() {
+ int active = 0, held = 0, sus = 0;
+ for (const auto& v : voices_) {
+ if (!v.active || v.kill > 0) continue;
+ ++active;
+ if (v.held) ++held; else if (v.sustained) ++sus;
+ }
+ tele_[ScActive].store(static_cast<float>(active), std::memory_order_relaxed);
+ tele_[ScLimit].store(static_cast<float>(voiceLimit()), std::memory_order_relaxed);
+ tele_[ScHeld].store(static_cast<float>(held), std::memory_order_relaxed);
+ tele_[ScSustained].store(static_cast<float>(sus), std::memory_order_relaxed);
+ tele_[ScPedal].store(pedalDown_ ? 1.0f : 0.0f, std::memory_order_relaxed);
+ tele_[ScLfo].store(static_cast<float>(lfo_), std::memory_order_relaxed);
+ tele_[ScPeakL].store(pkL_, std::memory_order_relaxed);
+ tele_[ScPeakR].store(pkR_, std::memory_order_relaxed);
+ tele_[ScLastNote].store(static_cast<float>(lastNote_), std::memory_order_relaxed);
+ }
+
+ std::atomic<float> pn_[kNumParams];
+ std::atomic<float> tele_[kScopeN];
+ std::atomic<double> pendingRate_{44100.0};
+ double sr_ = 0.0; // 0 → the first applyRate() adopts the pending rate
+ Voice voices_[kMaxVoices];
+ GlobalExpr gexpr_;
+ bool cc64_ = false, pedalDown_ = false;
+ int32_t lastNote_ = -1;
+ double spb_ = 22050.0, beat_ = 0.0; bool playing_ = false;
+ int64_t sinceBlock_ = 0;
+ bool looping_ = false; double loopStart_ = 0.0;
+
+ // FX state
+ bool fxDirty_ = true, fxRestart_ = false;
+ int cabCache_ = -1; float bassCache_ = 1e9f, trebleCache_ = 1e9f;
+ keys::Biquad loShelf_, hiShelf_, cabF_[2][4];
+ double lfo_ = 0.0, phLfo_ = 0.0, chL1_ = 0.0, chL2_ = 0.37;
+ float phZ_[2][4] = {}, phFb_[2] = {};
+ float chBuf_[2][kChLen];
+ int chW_ = 0;
+ float sDepth_ = 0.0f, sPh_ = 0.0f, sCh_ = 0.0f, sVol_ = 0.0f;
+ float dcL_ = 0.0f, dcPrev_ = 0.0f;
+ float pkL_ = 0.0f, pkR_ = 0.0f;
+};
+
+} // namespace nota
diff --git a/src/native/nota.engine/src/MpeInput.h b/src/native/nota.engine/src/MpeInput.h
index b5ffa63b..edb741e0 100644
--- a/src/native/nota.engine/src/MpeInput.h
+++ b/src/native/nota.engine/src/MpeInput.h
@@ -135,6 +135,9 @@ private:
if (isMember(channel)) forHeld(c, [&](int32_t p) { out.mpeExpression(p, ExprSlide, c.slide); });
else out.mpeExpression(-1, ExprSlide, c.slide);
break;
+ case 64: // sustain pedal: instrument-wide on any channel (an MPE master or member)
+ out.mpeExpression(-1, ExprSustain, v >= 64 ? 1.0f : 0.0f);
+ break;
case 101: c.rpnMsb = v; break;
case 100: c.rpnLsb = v; break;
case 6: dataEntry(channel, v); break;
diff --git a/src/native/nota.engine/src/NoteExpression.h b/src/native/nota.engine/src/NoteExpression.h
index 9514b9f1..a5f47dd9 100644
--- a/src/native/nota.engine/src/NoteExpression.h
+++ b/src/native/nota.engine/src/NoteExpression.h
@@ -23,6 +23,12 @@ namespace nota {
enum ExprDim : int32_t { ExprBend = 0, ExprPressure = 1, ExprSlide = 2, kExprDims = 3 };
+// The sustain pedal (CC64, 0 = up, 1 = down) rides the same channel, instrument-wide only
+// (pitch −1) and outside the per-note set above, so a VoiceExpr never sees it. Instruments
+// that don't model a damper ignore it (GlobalExpr::set drops unknown dims).
+inline constexpr int32_t ExprSustain = 3;
+inline constexpr int32_t kExprWireDims = 4; // every dim the engine accepts
+
inline constexpr float kExprNeutral[kExprDims] = { 0.0f, 0.0f, 0.5f };
// One-pole smoothing coefficient for a ~3 ms time constant.
diff --git a/src/native/nota.engine/src/RackCore.h b/src/native/nota.engine/src/RackCore.h
index bb56fe90..dd5ac499 100644
--- a/src/native/nota.engine/src/RackCore.h
+++ b/src/native/nota.engine/src/RackCore.h
@@ -32,6 +32,7 @@
#include "Monolith.h"
#include "Pentad.h"
#include "Consort.h"
+#include "Keys.h"
#include "GrainSynth.h"
#include "Sampler.h"
#include "SampleBuffer.h"
@@ -686,6 +687,7 @@ public:
case 13: return std::make_shared<Monolith>();
case 14: return std::make_shared<Pentad>();
case 15: return std::make_shared<Consort>();
+ case 16: return std::make_shared<Keys>();
default: return nullptr; // -1 = no instrument (effect rack); plugins are a follow-up
}
}
diff --git a/src/native/nota.engine/src/nota_engine_core.cpp b/src/native/nota.engine/src/nota_engine_core.cpp
index fc04df58..39b7adbf 100644
--- a/src/native/nota.engine/src/nota_engine_core.cpp
+++ b/src/native/nota.engine/src/nota_engine_core.cpp
@@ -183,11 +183,11 @@ NotaResult nota_track_note_off(NotaEngine* e, int32_t track_id, int32_t pitch) {
ENG(e)->trackNoteOff(track_id, pitch); return NOTA_OK;
}
NotaResult nota_engine_note_expression(NotaEngine* e, int32_t pitch, int32_t dim, float value) {
- if (!e || pitch < -1 || pitch > 127 || dim < 0 || dim > 2) return NOTA_ERR_INVALID_ARG;
+ if (!e || pitch < -1 || pitch > 127 || dim < 0 || dim > 3 || (dim == 3 && pitch >= 0)) return NOTA_ERR_INVALID_ARG;
ENG(e)->noteExpression(pitch, dim, value); return NOTA_OK;
}
NotaResult nota_track_note_expression(NotaEngine* e, int32_t track_id, int32_t pitch, int32_t dim, float value) {
- if (!e || pitch < -1 || pitch > 127 || dim < 0 || dim > 2) return NOTA_ERR_INVALID_ARG;
+ if (!e || pitch < -1 || pitch > 127 || dim < 0 || dim > 3 || (dim == 3 && pitch >= 0)) return NOTA_ERR_INVALID_ARG;
ENG(e)->trackNoteExpression(track_id, pitch, dim, value); return NOTA_OK;
}
void nota_engine_set_audition_track(NotaEngine* e, int32_t track_id) {
diff --git a/src/native/nota.engine/src/nota_engine_track.cpp b/src/native/nota.engine/src/nota_engine_track.cpp
index c6994e08..43a44ef7 100644
--- a/src/native/nota.engine/src/nota_engine_track.cpp
+++ b/src/native/nota.engine/src/nota_engine_track.cpp
@@ -145,6 +145,9 @@ int32_t nota_engine_add_pentad_track(NotaEngine* e) {
int32_t nota_engine_add_consort_track(NotaEngine* e) {
return e ? ENG(e)->addConsortTrack() : 0;
}
+int32_t nota_engine_add_keys_track(NotaEngine* e) {
+ return e ? ENG(e)->addKeysTrack() : 0;
+}
void nota_track_instrument_action(NotaEngine* e, int32_t track_id, int32_t id, int32_t iarg, float farg) {
if (e) ENG(e)->instrumentAction(track_id, id, iarg, farg);
}
diff --git a/tests/Nota.SmokeTest/KeysTests.cs b/tests/Nota.SmokeTest/KeysTests.cs
new file mode 100644
index 00000000..7c391470
--- /dev/null
+++ b/tests/Nota.SmokeTest/KeysTests.cs
@@ -0,0 +1,348 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Keys (instrument kind 16): identity, params, state / clone, every model sounding, the
+// pickup curve's bark growing with velocity, damper / pedal (the param and a keyboard's CC64),
+// re-strikes reusing the ringing voice, the voice limit, the tremolo's stereo pan, every effect
+// and cabinet finite, block-size null test, freeze == live, automation, a 64-voice stress run,
+// the 40 factory presets and the MCP tools.
+
+using Nota.Application;
+using Nota.Infrastructure;
+
+namespace Nota.SmokeTest;
+
+internal static class KeysTests
+{
+ private const int Sr = 48000;
+
+ private static int Pi(NotaEngine e, int t, string id)
+ {
+ int n = e.PluginParamCount(t, -1);
+ for (int i = 0; i < n; i++) if (e.PluginParamId(t, -1, i) == id) return i;
+ return -1;
+ }
+ private static void P(NotaEngine e, int t, string id, float v) => e.PluginParamSet(t, -1, Pi(e, t, id), v);
+
+ // Interleaved stereo, `frames` long, live notes only (no transport).
+ private static float[] Render(NotaEngine e, int frames, int block = 512)
+ {
+ var all = new float[frames * 2];
+ var b = new float[block * 2];
+ for (int done = 0; done < frames;)
+ {
+ int m = Math.Min(block, frames - done);
+ e.RenderOffline(b, m, Sr);
+ Array.Copy(b, 0, all, done * 2, m * 2);
+ done += m;
+ }
+ return all;
+ }
+
+ private static double Rms(float[] st, int from = 0, int to = -1)
+ {
+ if (to < 0) to = st.Length / 2;
+ double s = 0;
+ for (int i = from * 2; i < to * 2; i++) s += st[i] * (double)st[i];
+ return Math.Sqrt(s / Math.Max(1, (to - from) * 2));
+ }
+ private static double RmsCh(float[] st, int ch, int from, int to)
+ {
+ double s = 0;
+ for (int i = from; i < to; i++) s += st[i * 2 + ch] * (double)st[i * 2 + ch];
+ return Math.Sqrt(s / Math.Max(1, to - from));
+ }
+ // Energy at one frequency (Goertzel), mono sum.
+ private static double At(float[] st, double hz, int from = 0)
+ {
+ double w = 2 * Math.PI * hz / Sr, c = 2 * Math.Cos(w), s1 = 0, s2 = 0;
+ for (int i = from * 2; i < st.Length; i += 2) { double s0 = (st[i] + st[i + 1]) * 0.5 + c * s1 - s2; s2 = s1; s1 = s0; }
+ return s1 * s1 + s2 * s2 - c * s1 * s2;
+ }
+ private static double MaxDiff(float[] a, float[] b) { double d = 0; for (int i = 0; i < Math.Min(a.Length, b.Length); i++) d = Math.Max(d, Math.Abs(a[i] - b[i])); return d; }
+
+ private static (NotaEngine E, int T) Fresh(Action<NotaEngine, int>? setup = null)
+ {
+ var e = new NotaEngine();
+ int t = e.AddKeysTrack();
+ setup?.Invoke(e, t);
+ Render(e, 1024);
+ return (e, t);
+ }
+
+ // A clip-driven render (transport rolling), for the null and freeze tests.
+ private static float[] Play(Action<NotaEngine, int> setup, NotaNote[] notes, int frames, int block)
+ {
+ using var e = new NotaEngine();
+ e.SetBpm(120);
+ int t = e.AddKeysTrack();
+ setup(e, t);
+ e.AddMidiClip(t, 0.0, 16.0);
+ e.SetClipNotes(t, 0, notes);
+ var outv = new float[frames * 2]; var tmp = new float[block * 2];
+ e.Seek(0); e.Play();
+ for (int done = 0; done < frames;) { int m = Math.Min(block, frames - done); e.RenderOffline(tmp, m); Array.Copy(tmp, 0, outv, done * 2, m * 2); done += m; }
+ e.StopTransport();
+ return outv;
+ }
+
+ public static IEnumerable<(bool, string)> Run()
+ {
+ // ---- identity, params, state ------------------------------------------------
+ var (ke, t) = Fresh();
+ using (ke)
+ {
+ yield return (t > 0 && ke.TrackInstrumentKind(t) == KeysModel.Kind, $"AddKeysTrack adds kind 16 (got {ke.TrackInstrumentKind(t)})");
+ yield return (ke.DeviceName(t, -1) == "Nota Keys", $"instrument is Nota Keys (got '{ke.DeviceName(t, -1)}')");
+ int pc = ke.PluginParamCount(t, -1);
+ var ids = new HashSet<string>();
+ bool names = true;
+ for (int i = 0; i < pc; i++) { ids.Add(ke.PluginParamId(t, -1, i)); if (ke.PluginParamName(t, -1, i).Length == 0) names = false; }
+ yield return (pc == 36 && ids.Count == pc && !ids.Contains("") && names, $"Nota Keys exposes 36 params with unique ids and names (got {pc})");
+ yield return (ke.TrackInstrumentSupportsMpe(t), "Nota Keys reports MPE support");
+ yield return (InstrumentView.Index(ke, t) >= 0 && !InstrumentView.IsMini(ke, t), "Nota Keys has an S / L view param and opens as L");
+
+ P(ke, t, "dist", 0.17f); P(ke, t, "model", 1f); P(ke, t, "tremon", 1f);
+ var state = ke.GetPluginState(t, -1);
+ int t2 = ke.AddKeysTrack();
+ ke.SetPluginState(t2, -1, state);
+ yield return (Math.Abs(ke.PluginParamGet(t2, -1, Pi(ke, t2, "dist")) - 0.17f) < 1e-4 && ke.PluginParamGet(t2, -1, Pi(ke, t2, "model")) > 0.99f,
+ "keys state restores on another track");
+ int t3 = ke.DuplicateTrack(t);
+ yield return (t3 > 0 && Math.Abs(ke.PluginParamGet(t3, -1, Pi(ke, t3, "dist")) - 0.17f) < 1e-4 && ke.TrackInstrumentKind(t3) == 16,
+ "duplicating the track clones the keys patch");
+ yield return (ke.SetTrackBuiltinInstrument(ke.AddInstrumentTrack(), 16), "a track's instrument can be swapped to Nota Keys");
+ }
+
+ // ---- every model sounds -----------------------------------------------------
+ foreach (var (model, name) in new[] { (0f, "Tine"), (1 / 3f, "Suitcase"), (2 / 3f, "Reed"), (1f, "Clav") })
+ {
+ var (e, tr) = Fresh((e, tr) => P(e, tr, "model", model));
+ using (e)
+ {
+ foreach (var n in new[] { 48, 55, 60, 64 }) e.TrackNoteOn(tr, n, 0.8f);
+ var b = Render(e, Sr / 2);
+ int voices = e.InstrumentVoiceCount(tr);
+ yield return (b.All(float.IsFinite) && Rms(b) > 0.01 && b.Max(Math.Abs) < 1.5f && voices == 4,
+ $"Nota Keys {name}: a 4-note chord is audible, finite, not clipping, 4 voices (rms {Rms(b):F3}, peak {b.Max(Math.Abs):F2}, {voices})");
+ }
+ }
+
+ // ---- velocity drives the pickup harder: louder and more bark (H2 / H1) -------
+ {
+ double Bark(float vel, out double rms)
+ {
+ var (e, tr) = Fresh((e, tr) => { P(e, tr, "preon", 0f); P(e, tr, "cab", 0f); P(e, tr, "noise", 0f); P(e, tr, "dist", 0.2f); });
+ using (e)
+ {
+ e.TrackNoteOn(tr, 45, vel);
+ var b = Render(e, Sr / 2);
+ rms = Rms(b, 2400);
+ return At(b, 220, 2400) / Math.Max(1e-12, At(b, 110, 2400));
+ }
+ }
+ double soft = Bark(0.25f, out var rSoft), hard = Bark(1f, out var rHard);
+ yield return (rHard > rSoft * 1.5 && hard > soft * 2, $"harder notes are louder and bark more (rms {rSoft:F3} → {rHard:F3}, H2/H1 energy {soft:G2} → {hard:G2})");
+ }
+
+ // ---- damper and pedal -------------------------------------------------------
+ double TailAfterRelease(Action<NotaEngine, int> setup, Action<NotaEngine, int>? beforeOff = null, Action<NotaEngine, int>? afterOff = null)
+ {
+ var (e, tr) = Fresh(setup);
+ using (e)
+ {
+ beforeOff?.Invoke(e, tr);
+ e.TrackNoteOn(tr, 60, 0.8f);
+ Render(e, Sr / 4);
+ e.TrackNoteOff(tr, 60);
+ Render(e, Sr / 4);
+ afterOff?.Invoke(e, tr);
+ return Rms(Render(e, Sr / 4));
+ }
+ }
+ double damped = TailAfterRelease((e, tr) => P(e, tr, "damper", 0.9f));
+ double free = TailAfterRelease((e, tr) => P(e, tr, "damper", 0.9f), (e, tr) => P(e, tr, "pedal", 1f));
+ double cc64 = TailAfterRelease((e, tr) => P(e, tr, "damper", 0.9f), (e, tr) => { e.TrackNoteExpression(tr, -1, NoteExpressionDim.Sustain, 1f); Render(e, 512); });
+ double lifted = TailAfterRelease((e, tr) => P(e, tr, "damper", 0.9f), (e, tr) => P(e, tr, "pedal", 1f), (e, tr) => { P(e, tr, "pedal", 0f); Render(e, Sr / 4); });
+ yield return (free > damped * 20, $"the pedal (param) holds a released note (tail rms {damped:G2} damped → {free:G2} held)");
+ yield return (cc64 > damped * 20, $"a keyboard's CC64 holds a released note (tail rms {damped:G2} → {cc64:G2})");
+ yield return (lifted < free * 0.1, $"lifting the pedal drops the dampers (tail rms {free:G2} → {lifted:G2})");
+ {
+ bool threw = false;
+ using var e = new NotaEngine();
+ int tr = e.AddKeysTrack();
+ try { e.TrackNoteExpression(tr, 60, NoteExpressionDim.Sustain, 1f); } catch (NotaEngineException) { threw = true; }
+ yield return (threw, "the sustain dimension is instrument-wide only (a per-note one is refused)");
+ }
+
+ // ---- voices: re-strike reuses, the limit holds --------------------------------
+ {
+ var (e, tr) = Fresh();
+ using (e)
+ {
+ e.TrackNoteOn(tr, 57, 0.8f); Render(e, 2048); e.TrackNoteOff(tr, 57); Render(e, 512);
+ e.TrackNoteOn(tr, 57, 0.8f); Render(e, 2048);
+ yield return (e.InstrumentVoiceCount(tr) == 1, $"re-striking a ringing key reuses its voice ({e.InstrumentVoiceCount(tr)} voice)");
+ }
+ }
+ {
+ var (e, tr) = Fresh((e, tr) => P(e, tr, "voices", 0f));
+ using (e)
+ {
+ for (int n = 0; n < 12; n++) { e.TrackNoteOn(tr, 48 + n, 0.8f); Render(e, 256); }
+ Render(e, 2048);
+ var sc = new float[KeysModel.ScopeLength]; e.InstrumentScope(tr, sc);
+ yield return (e.InstrumentVoiceCount(tr) == 8 && (int)sc[KeysModel.ScLimit] == 8,
+ $"the voice limit holds at 8 with 12 keys down ({e.InstrumentVoiceCount(tr)} voices, scope limit {sc[KeysModel.ScLimit]})");
+ }
+ }
+
+ // ---- tremolo: stereo pans, mono pumps -------------------------------------------
+ {
+ var (e, tr) = Fresh((e, tr) => { P(e, tr, "tremon", 1f); P(e, tr, "tremmode", 1f); P(e, tr, "tremdepth", 1f); P(e, tr, "tremrate", 0.2f); P(e, tr, "decay", 1f); });
+ using (e)
+ {
+ e.TrackNoteOn(tr, 60, 0.9f);
+ var b = Render(e, Sr);
+ // Over ~1.6 Hz the left and right gains swap; count windows where one side clearly leads.
+ int lLead = 0, rLead = 0;
+ for (int w = 4; w < 40; w++)
+ {
+ double l = RmsCh(b, 0, w * 1200, (w + 1) * 1200), r = RmsCh(b, 1, w * 1200, (w + 1) * 1200);
+ if (l > r * 1.5) lLead++; else if (r > l * 1.5) rLead++;
+ }
+ yield return (lLead >= 3 && rLead >= 3, $"stereo tremolo pans between the sides (left leads {lLead}, right leads {rLead} windows)");
+ }
+ }
+
+ // ---- every effect and cabinet stays finite and audible --------------------------
+ foreach (var (label, set) in new (string, Action<NotaEngine, int>)[]
+ {
+ ("phaser", (e, tr) => { P(e, tr, "phaseron", 1f); P(e, tr, "phaserdepth", 1f); }),
+ ("chorus", (e, tr) => { P(e, tr, "choruson", 1f); P(e, tr, "chorusmix", 1f); }),
+ ("mono trem", (e, tr) => { P(e, tr, "tremon", 1f); P(e, tr, "tremmode", 0f); }),
+ ("max drive", (e, tr) => { P(e, tr, "drive", 1f); P(e, tr, "bass", 1f); P(e, tr, "treble", 1f); }),
+ ("cab off", (e, tr) => P(e, tr, "cab", 0f)),
+ ("cab suitcase", (e, tr) => P(e, tr, "cab", 1 / 3f)),
+ ("cab combo", (e, tr) => P(e, tr, "cab", 2 / 3f)),
+ ("everything at max", (e, tr) => { for (int i = 0; i < e.PluginParamCount(tr, -1) - 1; i++) e.PluginParamSet(tr, -1, i, 1f); }),
+ })
+ {
+ var (e, tr) = Fresh(set);
+ using (e)
+ {
+ foreach (var n in new[] { 36, 60, 72, 96 }) e.TrackNoteOn(tr, n, 1f);
+ var b = Render(e, Sr / 2);
+ yield return (b.All(float.IsFinite) && Rms(b) > 0.005 && b.Max(Math.Abs) < 4f, $"Nota Keys {label}: finite and audible (rms {Rms(b):F3}, peak {b.Max(Math.Abs):F2})");
+ }
+ }
+
+ // ---- determinism: block-size null test, freeze == live ------------------------------
+ {
+ void Setup(NotaEngine e, int tr) { P(e, tr, "age", 0.6f); P(e, tr, "tremon", 1f); P(e, tr, "tremsync", 1f); P(e, tr, "choruson", 1f); P(e, tr, "phaseron", 1f); }
+ NotaNote[] notes = { new(57, 0, 1.5, 0.8f), new(64, 0.25, 1, 0.6f), new(69, 0.5, 1.5, 1f), new(57, 1.0, 0.5, 0.9f) };
+ var a = Play(Setup, notes, 44100, 4096); var b = Play(Setup, notes, 44100, 128); var c = Play(Setup, notes, 44100, 777);
+ yield return (Rms(a) > 0.001 && MaxDiff(a, b) < 1e-6 && MaxDiff(a, c) < 1e-6,
+ $"Nota Keys null test: identical at blocks 4096/128/777 (maxdiff {Math.Max(MaxDiff(a, b), MaxDiff(a, c)):G3})");
+ }
+ {
+ using var fe = new NotaEngine(); fe.SetBpm(120);
+ int ft = fe.AddKeysTrack();
+ P(fe, ft, "tremon", 1f); P(fe, ft, "tremsync", 1f); P(fe, ft, "age", 0.5f);
+ fe.AddMidiClip(ft, 0.0, 4.0);
+ fe.SetClipNotes(ft, 0, new[] { new NotaNote(57, 0.0, 3.0, 0.9f), new NotaNote(64, 0.5, 2.0, 0.7f) });
+ const int N = 8192 * 4;
+ fe.Seek(0); fe.Play(); var live = new float[N * 2]; fe.RenderOffline(live, N); fe.StopTransport();
+ fe.Stop(); fe.SetLoop(false, 0, 0); fe.SetMetronome(false); fe.StopTransport();
+ long total = fe.BeginFreeze(ft, 4.0);
+ fe.StopTransport(); fe.Seek(0); fe.Play();
+ var chunk = new float[4096 * 2];
+ for (long rem = total; rem > 0;) { int m = (int)Math.Min(4096, rem); fe.RenderOffline(chunk, m); rem -= m; }
+ fe.StopTransport(); fe.EndFreeze(ft);
+ fe.Seek(0); fe.Play(); var frozen = new float[N * 2]; fe.RenderOffline(frozen, N); fe.StopTransport();
+ double md = MaxDiff(live, frozen);
+ yield return (fe.IsTrackFrozen(ft) && Rms(live) > 1e-3 && md < 1e-4, $"Nota Keys freeze == live render (maxdiff {md:G3})");
+ }
+
+ // ---- automation -----------------------------------------------------------------
+ {
+ using var e = new NotaEngine(); e.SetBpm(120);
+ int ta = e.AddKeysTrack();
+ foreach (var id in new[] { "dist", "tremdepth", "pedal" })
+ {
+ int fi = Pi(e, ta, id);
+ e.PluginParamSet(ta, -1, fi, 0.1f);
+ int lane = e.AddPluginAutomationLane(ta, -1, id);
+ e.SetAutomationPoints(ta, lane, new[] { new AutomationPoint(0.0, 0.1f, 0f), new AutomationPoint(2.0, 0.9f, 0f) });
+ var abuf = new float[4096 * 2];
+ e.Seek(1.99); e.Play(); e.RenderOffline(abuf, 4096); e.StopTransport();
+ yield return (lane >= 0 && e.PluginParamGet(ta, -1, fi) > 0.7f, $"automation drives Keys {id} ({e.PluginParamGet(ta, -1, fi):F2})");
+ }
+ }
+
+ // ---- stress: 64 Clav voices (24 partials each) + every effect in real time ------------
+ {
+ var (e, tr) = Fresh((e, tr) =>
+ {
+ P(e, tr, "model", 1f); P(e, tr, "voices", 1f); P(e, tr, "decay", 1f); P(e, tr, "damper", 0f);
+ P(e, tr, "tremon", 1f); P(e, tr, "phaseron", 1f); P(e, tr, "choruson", 1f);
+ });
+ using (e)
+ {
+ for (int n = 0; n < 64; n++) e.TrackNoteOn(tr, 28 + n, 0.9f);
+ var blk = new float[128 * 2];
+ for (int i = 0; i < 20; i++) e.RenderOffline(blk, 128, Sr);
+ var sw = System.Diagnostics.Stopwatch.StartNew(); const int blocks = 400;
+ for (int i = 0; i < blocks; i++) e.RenderOffline(blk, 128, Sr);
+ sw.Stop();
+ double budget = 128 * 1000.0 / Sr, avg = sw.Elapsed.TotalMilliseconds / blocks;
+ yield return (e.InstrumentVoiceCount(tr) == 64 && avg < budget * 0.5,
+ $"Nota Keys stress: 64 Clav voices + FX avg {avg:0.000} ms per 128-frame block (budget {budget:0.00} ms, {e.InstrumentVoiceCount(tr)} voices)");
+ }
+ }
+
+ // ---- factory presets -------------------------------------------------------------
+ {
+ var cat = new FactoryPresetCatalog();
+ var mine = cat.All().Where(p => p.IsInstrument && p.BuiltinKind == KeysModel.Kind).ToList();
+ yield return (mine.Count == 40, $"Nota Keys ships 40 factory presets (got {mine.Count})");
+ using var pe = new NotaEngine();
+ int pt = pe.AddKeysTrack();
+ var ids = new HashSet<string>();
+ for (int i = 0; i < pe.PluginParamCount(pt, -1); i++) ids.Add(pe.PluginParamId(pt, -1, i));
+ var bad = mine.SelectMany(p => cat.Document(p.Id)!.NamedParams!.Keys.Where(k => !ids.Contains(k)).Select(k => $"{p.DisplayName}:{k}")).ToList();
+ yield return (bad.Count == 0, $"every Keys preset param id exists{(bad.Count > 0 ? " — bad: " + string.Join(", ", bad) : "")}");
+ int fails = mine.Count(p => cat.ApplyInPlace(pe, p.Id, pt, -1).Length != 0);
+ yield return (fails == 0, $"every Keys preset applies in place ({fails} failed)");
+ var quiet = new List<string>();
+ foreach (var p in mine)
+ {
+ var b = Play((e, tr) => cat.ApplyInPlace(e, p.Id, tr, -1),
+ new[] { new NotaNote(48, 0, 1.5, 0.8f), new NotaNote(55, 0, 1.5, 0.8f), new NotaNote(64, 0, 1.5, 0.8f) }, 44100, 1024);
+ double r = Rms(b); float pk = b.Max(Math.Abs);
+ if (!b.All(float.IsFinite) || r < 0.005 || pk > 1.5f) quiet.Add($"{p.DisplayName} ({r:F3}/{pk:F2})");
+ }
+ yield return (quiet.Count == 0, $"every Keys preset sounds a chord, finite and not clipping{(quiet.Count > 0 ? " — " + string.Join(", ", quiet) : "")}");
+ var folders = mine.Select(p => p.Category).Distinct().ToList();
+ yield return (folders.Count == 6, $"Keys presets sit in 6 folders ({string.Join(", ", folders)})");
+ }
+
+ // ---- MCP --------------------------------------------------------------------------
+ {
+ using var me = new NotaEngine();
+ var mcp = new Nota.Mcp.Tools.InstrumentTools(me, new SyncDispatch(), new NoRefresh());
+ int mt = mcp.AddInstrumentTrack(16).Result;
+ yield return (mt > 0 && me.TrackInstrumentKind(mt) == 16, "MCP add_instrument_track(16) adds a Nota Keys");
+ yield return (mcp.ListInstrumentKinds().Any(k => k.Kind == 16 && k.Name == "Nota Keys"), "MCP list_instrument_kinds includes Nota Keys");
+ var r0 = mcp.ReadKeys(mt).Result;
+ yield return (r0 is not null && r0.Model == "Tine" && r0.VoiceLimit == 32 && r0.HarmonicsDb.Length == 8 && r0.Guide.Contains("tremrate"),
+ $"read_keys reads a fresh Keys ({r0?.Summary})");
+ string s = mcp.SetKeys(mt, model: "Reed", tremolo: "stereo", tremoloRate: "1/8", voices: 16, pedal: true, chorusMixPercent: 40).Result;
+ var r1 = mcp.ReadKeys(mt).Result;
+ yield return (!s.StartsWith("error") && r1!.Model == "Reed" && r1.VoiceLimit == 16 && s.Contains("trem stereo 1/8") && s.Contains("cab Combo") && s.Contains("pedal down"),
+ $"set_keys shapes the patch in musical terms ({s})");
+ yield return (mcp.SetKeys(mt, cabinet: "Marshall").Result.StartsWith("error"), "set_keys names a value it cannot use");
+ yield return (mcp.ReadKeys(me.AddInstrumentTrack()).Result is null, "read_keys returns null for another instrument");
+ }
+ }
+}
diff --git a/tests/Nota.SmokeTest/MpeTests.cs b/tests/Nota.SmokeTest/MpeTests.cs
index da13170c..150f4f6b 100644
--- a/tests/Nota.SmokeTest/MpeTests.cs
+++ b/tests/Nota.SmokeTest/MpeTests.cs
@@ -17,6 +17,7 @@ internal static class MpeTests
private static readonly (int Kind, string Name)[] Synths =
{
(0, "Nota Synth"), (6, "Nota Volt"), (5, "Nota Aurora"), (9, "Nota Operator"), (14, "Nota Pentad"), (2, "Nota Physical"),
+ (16, "Nota Keys"),
};
private const int NotMpeKind = 13; // Nota Monolith (mono)
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index b8083474..e0d7ae35 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -199,6 +199,14 @@ if (args.Length >= 1 && args[0] == "--bundle")
return failures == 0 ? 0 : 1;
}
+// Nota Keys alone (fast iteration): `--keys`. Also part of the full run.
+if (args.Length >= 1 && args[0] == "--keys")
+{
+ Console.WriteLine("-- nota keys --");
+ foreach (var (ok, label) in KeysTests.Run()) Check(ok, label);
+ Console.WriteLine(failures == 0 ? "KEYS PASSED" : $"KEYS FAILED ({failures})");
+ return failures == 0 ? 0 : 1;
+}
// MPE alone (fast iteration): `--mpe`. Also part of the full run.
if (args.Length >= 1 && args[0] == "--mpe")
{
@@ -14209,6 +14217,8 @@ Console.WriteLine("-- nota remote --");
foreach (var (ok, label) in RemoteTests.Run()) Check(ok, label);
Console.WriteLine("-- mpe: per-note expression --");
foreach (var (ok, label) in MpeTests.Run()) Check(ok, label);
+Console.WriteLine("-- nota keys --");
+foreach (var (ok, label) in KeysTests.Run()) Check(ok, label);
// --- command palette: descriptors, golden queries, context table, undo, speed ---
Console.WriteLine("-- command palette --");