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.

Add Nota Chamber, a hybrid convolution + algorithmic reverb

Egor Khindikaynencc7fe9234c2f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5d82ef1e..1e12178b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,29 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
## [Unreleased]
### Added
+- **Nota Chamber — a hybrid reverb.** A new built-in audio effect (kind 20) that runs a
+ convolution reverb and an algorithmic reverb side by side, as in Ableton's Hybrid Reverb.
+ **Blend** mixes the two — in parallel, or in **Serial** with the convolution feeding the
+ algorithm. The convolution engine comes with 16 impulse responses (concert hall, stone
+ vault, cathedral, scoring stage, wood chamber, live and drum rooms, tiled bathroom, two
+ plates, a spring tank, car park, stairwell, forest, gated room, metal tank), and loads your
+ own WAV / FLAC / MP3 file — mono, stereo or 4-channel true stereo — with **Load…** or by
+ dropping it on the waveform. Drag the waveform's brass lines to trim the IR (Start / Decay),
+ and shape it with Attack, Size (stretch 50–200 %), Reverse and True Stereo; a *Result* lane
+ under it shows the IR exactly as it is convolved, after the pre-delay. The engine has
+ no latency, and changing the IR re-renders the whole tail without a click. The algorithm
+ has four modes — **Dark Hall**, **Plate**, **Quartz** and **Shimmer** — with Decay, Size,
+ Diffusion, Damping and separate low / high decay times you drag on the *Decay per band*
+ graph — drawn over the algorithm's real, rendered impulse response — plus modulation, **Freeze** (the tail holds forever), **Hold in** (keep layering the
+ input into a frozen tail), a **Vintage** colour and a pitch shifter (−12 / +7 / +12, fed
+ back into the tail or on top). Each engine has its own pre-delay, free or tempo-synced.
+ Around them: a four-band EQ you can place at the input, on the tail or at the output (with
+ a drag-handle curve), ducking of the wet while you play, width and bass mono, Dry/Wet with
+ a dry level, a **Wet only** switch for send tracks, output gain and meters. The card follows
+ the design mockup (Blend column, Convolution / Algorithm / EQ · Mod and Levels / Output
+ tabs, a status line with CPU). 22 factory presets; every control can be automated, MIDI
+ learned and A/B compared, and a loaded IR is saved inside the project. MCP can add it,
+ load an IR file and read the IR names.
- **Nota Pentad — a 5-voice polyphonic synth (Prophet-5).** A new built-in instrument
(kind 14) modelled on the Prophet-5 Rev 3: Osc A (saw and pulse together, hard sync to
B) and Osc B (saw, triangle, pulse; Lo-Freq mode; keyboard tracking off), white/pink
@@ -64,6 +87,8 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
always jumps to the source, where the notes and devices live.
### Fixed
+- Applying a built-in effect's factory preset now resets the parameters the preset doesn't
+ name to their defaults, so switching presets no longer keeps leftovers from the last one.
- **Preferences: the end of long sections can be scrolled into view.** The last rows of
the Shortcuts list sat below the window's edge.
- **Deleting one half of a live-freeze pair no longer leaves the other half stuck.** If the
diff --git a/FEATURES.md b/FEATURES.md
index d2c33462..745d2332 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -269,6 +269,14 @@ and user presets, automation, persistence and cloning.
- **Nota Shutter** (19) — noise gate and ducker: Threshold/Return (hysteresis),
Attack/Hold/Release, Floor, Lookahead, Flip (ducker), band-pass sidechain with Listen; a
signal graph, IN/GR meters, LED.
+- **Nota Chamber** (20) — hybrid reverb: a zero-latency convolution engine (16 synthesised
+ IRs — halls, rooms, plates, spring, spaces, FX — or your own WAV/FLAC/MP3, mono / stereo /
+ 4-ch true stereo, dropped on the IR view) with Start/Decay trims, Attack, Size, Reverse,
+ True Stereo, and an algorithmic engine (Dark Hall / Plate / Quartz / Shimmer) with
+ per-band decay, diffusion, damping, modulation, Freeze + Hold in, Vintage and a pitch
+ shifter; Blend (parallel or serial), separate free/synced pre-delays, a 4-band EQ at the
+ input / tail / output, ducking, width + bass mono, Dry/Wet, wet-only send mode. IR edits
+ morph the tail without clicks; user IRs persist in the project.
- **Nota Chorus** — modulation (chorus) effect.
- **Forge**, **Valve** and **Vintage** each carry an **OVERSAMPLE** selector
(Off/2×/4×/8×) to suppress aliasing under heavy drive.
@@ -405,7 +413,8 @@ Coverage:
- **Project**: `get_overview` (a full snapshot).
- **Tracks**: add and remove, volume/pan/mute/solo, groups, sends.
- **Instruments**: add by kind, read and write parameters (by index or by stable id).
-- **Audio effects**: add, remove, reorder, bypass, parameters.
+- **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
and split.
- **Automation**: create a lane, read and write points.
diff --git a/src/managed/Nota.App/ArrangementView.Automation.cs b/src/managed/Nota.App/ArrangementView.Automation.cs
index f265433d..4406b73d 100644
--- a/src/managed/Nota.App/ArrangementView.Automation.cs
+++ b/src/managed/Nota.App/ArrangementView.Automation.cs
@@ -398,11 +398,23 @@ public sealed partial class ArrangementView
{
if (!sepAdded) { flyout.Items.Add(new Separator()); sepAdded = true; }
var devMenu = new MenuItem { Header = dn };
+ // Nota Chamber (45 params) groups by its section prefix ("IR", "Algo", "EQ" …):
+ // a word shared by two or more params becomes a submenu.
+ bool grouped = e.TrackDeviceBuiltinKind(t.Id, d) == 20;
+ var names = new string[builtinPc];
+ for (int p = 0; p < builtinPc; p++) names[p] = e.DeviceParamName(t.Id, d, p);
+ static string Head(string n) { int sp = n.IndexOf(' '); return sp > 0 ? n[..sp] : ""; }
+ var groups = new System.Collections.Generic.Dictionary<string, MenuItem>();
for (int p = 0; p < builtinPc; p++)
{
int dd = d, pp = p;
- devMenu.Items.Add(Leaf(e.DeviceParamName(t.Id, d, p), $"D:{dd}:{pp}",
- () => SetAutoTarget(t, AutomationTarget.DeviceParam, dd, pp), automated));
+ string head = grouped ? Head(names[p]) : "";
+ bool sub = head.Length > 0 && names.Count(n => Head(n) == head) >= 2;
+ var leaf = Leaf(sub ? names[p][(head.Length + 1)..] : names[p], $"D:{dd}:{pp}",
+ () => SetAutoTarget(t, AutomationTarget.DeviceParam, dd, pp), automated);
+ if (!sub) { devMenu.Items.Add(leaf); continue; }
+ if (!groups.TryGetValue(head, out var g)) { g = new MenuItem { Header = head }; groups[head] = g; devMenu.Items.Add(g); }
+ g.Items.Add(leaf);
}
flyout.Items.Add(devMenu);
}
diff --git a/src/managed/Nota.App/Controls/ChamberViews.cs b/src/managed/Nota.App/Controls/ChamberViews.cs
new file mode 100644
index 00000000..f4884c0c
--- /dev/null
+++ b/src/managed/Nota.App/Controls/ChamberViews.cs
@@ -0,0 +1,616 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Custom-drawn views for the Nota Chamber card: the two BLEND-column faders (the two-tone
+// convolution / algorithm split and the wet level), the IR waveform with draggable Start /
+// Decay trims (also a file drop target), the three-band decay graph, the tail-EQ response
+// with its two handles and the modulation LFO trace. Values are pushed in by the card's
+// refresh tick; the interactive views raise Changed / DragStarted / DragEnded so the card
+// writes the params and records automation gestures.
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Input;
+using Avalonia.Media;
+
+namespace Nota.App;
+
+internal static class ChamberInk
+{
+ public static readonly Color SlateColor = Color.Parse("#6D8FB5"); // convolution
+ public static readonly Color MauveColor = Color.Parse("#B57286"); // shimmer / pitch, low band
+ public static readonly IBrush Slate = new SolidColorBrush(SlateColor);
+ public static readonly IBrush Mauve = new SolidColorBrush(MauveColor);
+ public static readonly IBrush Veil = new SolidColorBrush(Color.FromArgb(0xB8, 0x0B, 0x0A, 0x09));
+ public static readonly IBrush GridLine = NotaPalette.SurfaceCard;
+ private static readonly Typeface Mono = new("ui-monospace, Menlo, monospace");
+ private static readonly Typeface Sans = new("Inter, system-ui, sans-serif", FontStyle.Normal, FontWeight.Bold);
+
+ public static FormattedText Text(string s, double size, IBrush b) => new(s, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, size, b);
+ public static FormattedText Caps(string s, double size, IBrush b) => new(s, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Sans, size, b);
+ public static IBrush Alpha(Color c, byte a) => new SolidColorBrush(Color.FromArgb(a, c.R, c.G, c.B));
+
+ // A time axis that stays put while the content moves inside it (so turning a knob visibly
+ // moves the curve instead of rescaling it away), and steps to the next range only when the
+ // content no longer fits or shrinks well below it.
+ private static readonly double[] Ranges = { 0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4, 5, 6, 8, 10, 12, 16, 20, 30, 45, 60, 90 };
+ public static double Axis(double current, double content)
+ {
+ double need = Math.Max(0.1, content) * 1.08;
+ if (current > 0 && need <= current && need >= current * 0.4) return current;
+ foreach (double r in Ranges) if (r >= need) return r;
+ return Ranges[^1];
+ }
+ public static string AxisLabel(double s) => s >= 1 ? FormattableString.Invariant($"{s:0.##} s") : FormattableString.Invariant($"{s * 1000:0} ms");
+ // Normalised amplitude → 0..1 height on a −60 dB floor.
+ public static double DbHeight(double v, double floorDb = 60) => Math.Clamp((20 * Math.Log10(Math.Max(v, 1e-9)) + floorDb) / floorDb, 0, 1);
+}
+
+// A vertical fader. Split = the BLEND C/A fader: slate (convolution) above the handle, brass
+// (algorithm) below, value = the algorithm share. Otherwise a brass fill from the bottom.
+internal sealed class ChamberFader : Control
+{
+ private double _v;
+ private bool _drag;
+ public bool Split { get; init; }
+ public double Default { get; set; } = double.NaN;
+ public bool Dragging => _drag;
+ public event Action<double>? Changed;
+ public event Action? DragStarted;
+ public event Action? DragEnded;
+
+ public ChamberFader() { Width = 16; Cursor = new Cursor(StandardCursorType.SizeNorthSouth); }
+
+ public void Set(double v) { if (_drag) return; _v = Math.Clamp(v, 0, 1); InvalidateVisual(); }
+
+ private void Apply(PointerEventArgs e)
+ {
+ double h = Bounds.Height; if (h <= 2) return;
+ _v = Math.Clamp(1 - e.GetPosition(this).Y / h, 0, 1);
+ Changed?.Invoke(_v); InvalidateVisual();
+ }
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ base.OnPointerPressed(e);
+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
+ if (e.ClickCount == 2 && !double.IsNaN(Default))
+ {
+ DragStarted?.Invoke(); _v = Default; Changed?.Invoke(_v); DragEnded?.Invoke(); InvalidateVisual(); e.Handled = true; return;
+ }
+ _drag = true; DragStarted?.Invoke(); e.Pointer.Capture(this); Apply(e); e.Handled = true;
+ }
+ protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); if (_drag) Apply(e); }
+ protected override void OnPointerReleased(PointerReleasedEventArgs e)
+ { base.OnPointerReleased(e); if (_drag) { _drag = false; e.Pointer.Capture(null); DragEnded?.Invoke(); } }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w < 2 || h < 4) return;
+ var rect = new Rect(0.5, 0.5, w - 1, h - 1);
+ double r = Math.Min(8, w / 2);
+ ctx.DrawRectangle(NotaPalette.BgSunken, null, rect, r, r);
+ double y = (1 - _v) * h;
+ using (ctx.PushClip(new RoundedRect(rect, r)))
+ {
+ if (Split) ctx.FillRectangle(ChamberInk.Alpha(ChamberInk.SlateColor, 0x59), new Rect(0, 0, w, y));
+ ctx.FillRectangle(ChamberInk.Alpha(NotaPalette.AccentColor, 0x48), new Rect(0, y, w, h - y));
+ }
+ ctx.DrawRectangle(null, new Pen(NotaPalette.BorderDefault, 1), rect, r, r);
+ double hy = Math.Clamp(y, 1.5, h - 2.5);
+ ctx.DrawRectangle(Split ? NotaPalette.AccentBright : NotaPalette.Accent, null, new Rect(1.5, hy - 1, w - 3, 2), 1, 1);
+ }
+}
+
+// The IR: a peak envelope of the source (left / LL above the centre line in brass, right / RR
+// below in mauve), veiled outside the Start … Decay window. Drag a trim line to move it,
+// double-click to reset both. Drop an audio file (Finder or the browser) to load it.
+internal sealed class ChamberIrView : Control
+{
+ private float[] _l = Array.Empty<float>(), _r = Array.Empty<float>();
+ private double _sec, _start, _end = 1, _attackSec;
+ private bool _reverse, _building, _hover;
+ private string? _empty;
+ private int _drag; // 0 none, 1 start, 2 end
+ private float[] _res = Array.Empty<float>();
+ private double _resSec, _preSec, _axis;
+ private const double SourceShare = 0.56; // top lane = the source + trims, bottom = the result
+
+ public event Action<double, double>? TrimChanged; // (start, end) fractions
+ public event Action<int>? DragStarted; // 1 start / 2 end
+ public event Action<int>? DragEnded;
+ public event Action<string>? FileDropped;
+ public event Action? DropHover; // a file drag is over the view
+ public int DraggingHandle => _drag;
+
+ public ChamberIrView()
+ {
+ ClipToBounds = true;
+ Cursor = new Cursor(StandardCursorType.SizeWestEast);
+ DragDrop.SetAllowDrop(this, true);
+ DragDrop.AddDragOverHandler(this, (_, e) => { if (BrowserView.IsAcceptableDrag(e)) { e.DragEffects = DragDropEffects.Copy; _hover = true; DropHover?.Invoke(); InvalidateVisual(); e.Handled = true; } });
+ DragDrop.AddDragLeaveHandler(this, (_, _) => { _hover = false; InvalidateVisual(); });
+ DragDrop.AddDropHandler(this, (_, e) =>
+ {
+ _hover = false; InvalidateVisual();
+ foreach (var it in BrowserView.DroppedItems(e))
+ if (it.Path is { Length: > 0 } p) { FileDropped?.Invoke(p); break; }
+ e.Handled = true;
+ });
+ }
+
+ public void SetWave(float[] l, float[] r) { _l = l; _r = r; InvalidateVisual(); }
+ // The processed IR as convolved (normalised envelope over `seconds`), after `preSec`.
+ public void SetResult(float[] env, double seconds, double preSec)
+ {
+ _res = env; _resSec = seconds; _preSec = preSec;
+ _axis = ChamberInk.Axis(_axis, preSec + seconds);
+ InvalidateVisual();
+ }
+ public void Set(double seconds, double start, double end, double attackSec, bool reverse, bool building, string? emptyText)
+ {
+ _sec = seconds; _attackSec = attackSec; _reverse = reverse; _building = building; _empty = emptyText;
+ if (_drag == 0) { _start = start; _end = end; }
+ InvalidateVisual();
+ }
+
+ private double X(double f) => f * Bounds.Width;
+ private void Apply(PointerEventArgs e)
+ {
+ double w = Bounds.Width; if (w <= 2) return;
+ double f = Math.Clamp(e.GetPosition(this).X / w, 0, 1);
+ if (_drag == 1) _start = Math.Min(f, Math.Min(0.9, _end - 0.02));
+ else _end = Math.Max(f, Math.Max(0.05, _start + 0.02));
+ TrimChanged?.Invoke(_start, _end); InvalidateVisual();
+ }
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ base.OnPointerPressed(e);
+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed || _empty != null) return;
+ if (e.GetPosition(this).Y > Bounds.Height * SourceShare) return; // the RESULT lane is read-only
+ if (e.ClickCount == 2)
+ {
+ DragStarted?.Invoke(1); DragStarted?.Invoke(2);
+ _start = 0; _end = 1; TrimChanged?.Invoke(_start, _end);
+ DragEnded?.Invoke(1); DragEnded?.Invoke(2);
+ InvalidateVisual(); e.Handled = true; return;
+ }
+ double x = e.GetPosition(this).X;
+ _drag = Math.Abs(x - X(_start)) <= Math.Abs(x - X(_end)) ? 1 : 2;
+ DragStarted?.Invoke(_drag); e.Pointer.Capture(this); Apply(e); e.Handled = true;
+ }
+ protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); if (_drag != 0) Apply(e); }
+ protected override void OnPointerReleased(PointerReleasedEventArgs e)
+ { base.OnPointerReleased(e); if (_drag != 0) { int d = _drag; _drag = 0; e.Pointer.Capture(null); DragEnded?.Invoke(d); } }
+
+ private static string Sec(double s) => s >= 1 ? FormattableString.Invariant($"{s:0.00} s") : FormattableString.Invariant($"{s * 1000:0} ms");
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w < 4 || h < 8) return;
+ ctx.FillRectangle(Brushes.Transparent, new Rect(0, 0, w, h));
+ if (_empty != null)
+ {
+ var t = ChamberInk.Text(_empty, 8, NotaPalette.TextTertiary);
+ ctx.DrawText(t, new Point((w - t.Width) / 2, (h - t.Height) / 2));
+ if (_hover) ctx.DrawRectangle(null, new Pen(NotaPalette.AccentBright, 1.5), new Rect(1, 1, w - 2, h - 2), 3, 3);
+ return;
+ }
+ double full = h;
+ h = Math.Floor(full * SourceShare); // ---- SOURCE lane (top) ----
+ double mid = h / 2, amp = mid - 3;
+ ctx.DrawLine(new Pen(ChamberInk.GridLine, 1), new Point(0, mid), new Point(w, mid));
+ var clip = ctx.PushClip(new Rect(0, 0, w, h));
+ void Env(float[] a, bool up, Color c, double alphaLine)
+ {
+ int n = a.Length; if (n < 2) return;
+ var fill = new StreamGeometry(); var line = new StreamGeometry();
+ using (var f = fill.Open())
+ using (var l = line.Open())
+ {
+ f.BeginFigure(new Point(0, mid), true);
+ for (int i = 0; i < n; i++)
+ {
+ double x = i * w / (n - 1), v = Math.Sqrt(Math.Clamp(a[i], 0f, 1f)); // √ lifts the tail into view
+ var p = new Point(x, up ? mid - v * amp : mid + v * amp);
+ f.LineTo(p);
+ if (i == 0) l.BeginFigure(p, false); else l.LineTo(p);
+ }
+ f.LineTo(new Point(w, mid));
+ }
+ ctx.DrawGeometry(ChamberInk.Alpha(c, 0x30), null, fill);
+ ctx.DrawGeometry(null, new Pen(ChamberInk.Alpha(c, (byte)(255 * alphaLine)), 1.1), line);
+ }
+ Env(_l, true, NotaPalette.AccentColor, 1.0);
+ Env(_r.Length > 0 ? _r : _l, false, ChamberInk.MauveColor, 0.7);
+
+ double xs = X(_start), xe = X(_end);
+ // Attack: the fade-in shape across the head of the kept window.
+ if (_attackSec > 0.0005 && _sec > 0)
+ {
+ double xa = xs + (_attackSec / _sec) * w;
+ var g = new StreamGeometry();
+ using (var c = g.Open())
+ {
+ c.BeginFigure(new Point(xs, h - 2), false);
+ for (int i = 1; i <= 16; i++) { double t = i / 16.0; c.LineTo(new Point(xs + (xa - xs) * t, h - 2 - (h - 4) * t * t)); }
+ }
+ ctx.DrawGeometry(null, new Pen(ChamberInk.Alpha(NotaPalette.AccentBrightColor, 0x90), 1, new DashStyle(new double[] { 2, 2 }, 0)), g);
+ }
+ ctx.FillRectangle(ChamberInk.Veil, new Rect(0, 0, xs, h));
+ ctx.FillRectangle(ChamberInk.Veil, new Rect(xe, 0, w - xe, h));
+ var brass = new Pen(NotaPalette.Accent, 1);
+ ctx.DrawLine(brass, new Point(xs + 0.5, 0), new Point(xs + 0.5, h));
+ ctx.DrawLine(brass, new Point(xe - 0.5, 0), new Point(xe - 0.5, h));
+ ctx.DrawRectangle(_drag == 1 ? NotaPalette.AccentBright : NotaPalette.Accent, null, new Rect(xs - 1.5, mid - 7, 3, 14), 1.5, 1.5);
+ ctx.DrawRectangle(_drag == 2 ? NotaPalette.AccentBright : NotaPalette.Accent, null, new Rect(xe - 1.5, mid - 7, 3, 14), 1.5, 1.5);
+
+ var st = ChamberInk.Text(FormattableString.Invariant($"start {Sec(_start * _sec)}"), 7, NotaPalette.AccentBright);
+ ctx.DrawText(st, new Point(Math.Min(xs + 4, w - st.Width - 2), 2));
+ var en = ChamberInk.Text(FormattableString.Invariant($"end {Sec(_end * _sec)}"), 7, NotaPalette.AccentBright);
+ ctx.DrawText(en, new Point(Math.Max(2, xe - en.Width - 4), h - en.Height - 2));
+ if (_reverse)
+ {
+ var rv = ChamberInk.Text("◀ REVERSED", 7, ChamberInk.Mauve);
+ ctx.DrawText(rv, new Point((xs + xe - rv.Width) / 2, 2));
+ }
+ clip.Dispose();
+ RenderResult(ctx, w, h, full);
+ if (_building)
+ {
+ var b = ChamberInk.Text("building…", 7, NotaPalette.TextTertiary);
+ ctx.DrawText(b, new Point(w - b.Width - 4, h + 2));
+ }
+ if (_hover) ctx.DrawRectangle(null, new Pen(NotaPalette.AccentBright, 1.5), new Rect(1, 1, w - 2, full - 2), 3, 3);
+ }
+
+ // ---- RESULT lane (bottom): the IR as it is convolved — pre-delay gap, stretched by Size,
+ // faded by Attack / Decay, reversed — on a steady time axis, in dB (−60 dB floor).
+ private void RenderResult(DrawingContext ctx, double w, double top, double full)
+ {
+ double lh = full - top;
+ if (lh < 10) return;
+ ctx.FillRectangle(ChamberInk.Alpha(Color.Parse("#0B0A09"), 0xFF), new Rect(0, top, w, lh));
+ ctx.DrawLine(new Pen(NotaPalette.BorderDefault, 1), new Point(0, top + 0.5), new Point(w, top + 0.5));
+ double axis = _axis > 0 ? _axis : 1, bot = full - 2, peakY = top + 9;
+ double X(double t) => Math.Clamp(t / axis, 0, 1) * w;
+ var gp = new Pen(ChamberInk.GridLine, 1);
+ for (int i = 1; i < 4; i++) ctx.DrawLine(gp, new Point(w * i / 4, top + 1), new Point(w * i / 4, full));
+ int n = _res.Length;
+ if (n >= 2 && _resSec > 0)
+ {
+ var fill = new StreamGeometry(); var line = new StreamGeometry();
+ double x0 = X(_preSec);
+ using (var f = fill.Open())
+ using (var l = line.Open())
+ {
+ f.BeginFigure(new Point(x0, bot), true);
+ for (int i = 0; i < n; i++)
+ {
+ double x = X(_preSec + (i + 0.5) / n * _resSec);
+ var p = new Point(x, bot - (bot - peakY) * ChamberInk.DbHeight(_res[i]));
+ f.LineTo(p);
+ if (i == 0) l.BeginFigure(p, false); else l.LineTo(p);
+ if (x >= w) break;
+ }
+ f.LineTo(new Point(Math.Min(w, X(_preSec + _resSec)), bot));
+ }
+ ctx.DrawGeometry(ChamberInk.Alpha(NotaPalette.AccentColor, 0x3A), null, fill);
+ ctx.DrawGeometry(null, new Pen(NotaPalette.Accent, 1), line);
+ if (_preSec > 0.0005)
+ {
+ ctx.DrawLine(new Pen(NotaPalette.Teal, 1, new DashStyle(new double[] { 2, 2 }, 0)), new Point(x0, top + 2), new Point(x0, full));
+ var pt = ChamberInk.Text(FormattableString.Invariant($"pre {_preSec * 1000:0} ms"), 7, NotaPalette.Teal);
+ ctx.DrawText(pt, new Point(Math.Min(x0 + 3, w - pt.Width - 2), bot - pt.Height));
+ }
+ if (_preSec + _resSec > axis * 1.001)
+ {
+ var more = ChamberInk.Text("▸", 8, NotaPalette.AccentBright);
+ ctx.DrawText(more, new Point(w - more.Width - 2, peakY - 2));
+ }
+ }
+ var len = ChamberInk.Text(FormattableString.Invariant($"as heard · {_resSec:0.00} s · axis {ChamberInk.AxisLabel(axis)}"), 7, NotaPalette.TextDisabled);
+ ctx.DrawText(len, new Point(w - len.Width - 4, top + 2));
+ }
+}
+
+// DECAY PER BAND: the energy decay (dB, straight lines) of the low / mid / high bands after the
+// pre-delay, each ending at its RT60 on the time axis. Drag a band's end marker to set its RT60
+// (mid = Decay; low / high are stored relative to it).
+internal sealed class ChamberDecayGraph : Control
+{
+ private double _pre, _tmax = 4;
+ private readonly double[] _rt = { 3, 3, 1.5 };
+ private bool _freeze;
+ private int _drag = -1;
+ private float[] _echo = Array.Empty<float>();
+ private double _echoSec;
+ private string _info = "";
+ private static readonly IBrush[] Ink = { ChamberInk.Mauve, NotaPalette.Accent, NotaPalette.Teal };
+ private static readonly string[] Names = { "low", "mid", "high" };
+
+ public event Action<int, double>? Changed; // band, RT60 seconds
+ public event Action<int>? DragStarted;
+ public event Action<int>? DragEnded;
+ public int DraggingBand => _drag;
+
+ public ChamberDecayGraph() { ClipToBounds = true; Cursor = new Cursor(StandardCursorType.SizeWestEast); }
+
+ public void Set(double preSec, double rtLow, double rtMid, double rtHigh, bool freeze, string info)
+ {
+ _pre = preSec; _freeze = freeze; _info = info;
+ if (_drag < 0)
+ {
+ _rt[0] = rtLow; _rt[1] = rtMid; _rt[2] = rtHigh;
+ double content = _freeze ? Math.Max(_pre + 2, _tmax / 1.08) : _pre + Math.Max(_rt[0], Math.Max(_rt[1], _rt[2]));
+ _tmax = ChamberInk.Axis(_tmax, content); // steady axis: the curves move, not the scale
+ }
+ InvalidateVisual();
+ }
+ // The algorithm's rendered impulse response (normalised envelope over `seconds`).
+ public void SetEchogram(float[] env, double seconds) { _echo = env; _echoSec = seconds; InvalidateVisual(); }
+
+ private const double Pad = 6, Top = 16;
+ private double X(double t) => Pad + t / _tmax * (Bounds.Width - 2 * Pad);
+ private double T(double x) => (x - Pad) / Math.Max(1, Bounds.Width - 2 * Pad) * _tmax;
+
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ base.OnPointerPressed(e);
+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed || _freeze) return;
+ double x = e.GetPosition(this).X, best = double.MaxValue;
+ for (int b = 0; b < 3; b++) { double d = Math.Abs(x - X(_pre + _rt[b])); if (d < best) { best = d; _drag = b; } }
+ DragStarted?.Invoke(_drag); e.Pointer.Capture(this); OnPointerMoved(e); e.Handled = true;
+ }
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ base.OnPointerMoved(e);
+ if (_drag < 0) return;
+ _rt[_drag] = Math.Clamp(T(e.GetPosition(this).X) - _pre, 0.05, 70);
+ Changed?.Invoke(_drag, _rt[_drag]); InvalidateVisual();
+ }
+ protected override void OnPointerReleased(PointerReleasedEventArgs e)
+ { base.OnPointerReleased(e); if (_drag >= 0) { int b = _drag; _drag = -1; e.Pointer.Capture(null); DragEnded?.Invoke(b); } }
+
+ private static string S(double s) => s >= 10 ? FormattableString.Invariant($"{s:0} s") : FormattableString.Invariant($"{s:0.0} s");
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w < 20 || h < 24) return;
+ ctx.FillRectangle(Brushes.Transparent, new Rect(0, 0, w, h));
+ var gp = new Pen(ChamberInk.GridLine, 1);
+ double bot = h - 4;
+ ctx.DrawLine(gp, new Point(0, (Top + bot) / 2), new Point(w, (Top + bot) / 2));
+ ctx.DrawLine(gp, new Point(w / 3, Top - 4), new Point(w / 3, h));
+ ctx.DrawLine(gp, new Point(2 * w / 3, Top - 4), new Point(2 * w / 3, h));
+ var cap = ChamberInk.Caps("DECAY PER BAND", 7, NotaPalette.TextTertiary);
+ ctx.DrawText(cap, new Point(5, 3));
+ if (_info.Length > 0) ctx.DrawText(ChamberInk.Text(_info, 7, NotaPalette.TextDisabled), new Point(5 + cap.Width + 6, 3));
+
+ // The real echogram (dB, −60 dB floor) behind the RT60 lines — Size, Diffusion, the
+ // mode, modulation and Freeze all show up here.
+ int en = _echo.Length;
+ if (en >= 2 && _echoSec > 0)
+ {
+ var fill = new StreamGeometry(); var line = new StreamGeometry();
+ using (var f = fill.Open())
+ using (var l = line.Open())
+ {
+ f.BeginFigure(new Point(X(_pre), bot), true);
+ for (int i = 0; i < en; i++)
+ {
+ double x = X(_pre + (i + 0.5) / en * _echoSec);
+ var p = new Point(x, bot - (bot - Top) * ChamberInk.DbHeight(_echo[i]));
+ f.LineTo(p);
+ if (i == 0) l.BeginFigure(p, false); else l.LineTo(p);
+ if (x >= w) break;
+ }
+ f.LineTo(new Point(Math.Min(w, X(_pre + _echoSec)), bot));
+ }
+ ctx.DrawGeometry(ChamberInk.Alpha(NotaPalette.AccentColor, 0x22), null, fill);
+ ctx.DrawGeometry(null, new Pen(ChamberInk.Alpha(NotaPalette.AccentColor, 0x60), 0.8), line);
+ }
+
+ // legend (right-aligned): swatch + "low 6.1 s"
+ double lx = w - 5;
+ for (int b = 2; b >= 0; b--)
+ {
+ var t = ChamberInk.Text(FormattableString.Invariant($"{Names[b]} {(_freeze ? "∞" : S(_rt[b]))}"), 7, b == 1 ? NotaPalette.AccentBright : NotaPalette.TextSecondary);
+ lx -= t.Width; ctx.DrawText(t, new Point(lx, 3));
+ lx -= 11; ctx.FillRectangle(Ink[b], new Rect(lx, 7, 8, 2));
+ lx -= 8;
+ }
+
+ double x0 = X(0), xp = X(_pre);
+ for (int b = 0; b < 3; b++)
+ {
+ var g = new StreamGeometry();
+ using (var c = g.Open())
+ {
+ c.BeginFigure(new Point(x0, Top), false);
+ c.LineTo(new Point(xp, Top));
+ if (_freeze) c.LineTo(new Point(w, Top));
+ else
+ {
+ // −60 dB at pre + RT on the same dB scale as the echogram (a straight decay).
+ c.LineTo(new Point(X(_pre + _rt[b]), bot));
+ }
+ }
+ ctx.DrawGeometry(null, new Pen(Ink[b], b == 1 ? 1.8 : 1.5), g);
+ if (!_freeze)
+ {
+ double hx = Math.Clamp(X(_pre + _rt[b]), 4, w - 4);
+ ctx.DrawEllipse(Ink[b], new Pen(NotaPalette.BgSunken, 2), new Point(hx, bot - 1), _drag == b ? 4.5 : 3.5, _drag == b ? 4.5 : 3.5);
+ }
+ }
+ var tm = ChamberInk.Text(ChamberInk.AxisLabel(_tmax), 7, NotaPalette.TextDisabled);
+ ctx.DrawText(tm, new Point(w - tm.Width - 4, bot - tm.Height - 3));
+ }
+}
+
+// TAIL EQ response (log 30 Hz … 18 kHz, ±20 dB): low cut + low shelf, high shelf + high cut
+// (the same RBJ biquads the engine runs). Handle 0 (brass) = low cut (X) + low shelf gain (Y);
+// handle 1 = high cut (X) + high shelf gain (Y).
+internal sealed class ChamberEqCurve : Control
+{
+ private double _lc, _lg = 0.5, _hs = 0.5, _hc = 1;
+ private int _drag = -1;
+ private const double FLo = 30, FHi = 18000, DbSpan = 20, Sr = 48000;
+
+ public event Action<int, double, double>? Changed; // handle, cut (norm), gain (norm)
+ public event Action<int>? DragStarted;
+ public event Action<int>? DragEnded;
+ public int DraggingHandle => _drag;
+
+ public ChamberEqCurve() { ClipToBounds = true; Cursor = new Cursor(StandardCursorType.Hand); }
+
+ public void Set(double lowCut, double lowGain, double highShelf, double highCut)
+ { if (_drag >= 0) return; _lc = lowCut; _lg = lowGain; _hs = highShelf; _hc = highCut; InvalidateVisual(); }
+
+ public static double LowCutHz(double v) => 20 * Math.Pow(100, Math.Clamp(v, 0, 1));
+ public static double HighCutHz(double v) => 1000 * Math.Pow(20, Math.Clamp(v, 0, 1));
+ private double X(double hz) => Math.Log(Math.Clamp(hz, FLo, FHi) / FLo) / Math.Log(FHi / FLo) * Bounds.Width;
+ private double Hz(double x) => FLo * Math.Pow(FHi / FLo, Math.Clamp(x / Math.Max(1, Bounds.Width), 0, 1));
+ private double Y(double db) => Bounds.Height / 2 - db / DbSpan * (Bounds.Height / 2 - 3);
+
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ base.OnPointerPressed(e);
+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
+ var p = e.GetPosition(this);
+ double d0 = Dist(p, X(LowCutHz(_lc)), Y((_lg - 0.5) * 36)), d1 = Dist(p, X(HighCutHz(_hc)), Y((_hs - 0.5) * 36));
+ _drag = d0 <= d1 ? 0 : 1;
+ DragStarted?.Invoke(_drag); e.Pointer.Capture(this); OnPointerMoved(e); e.Handled = true;
+ }
+ private static double Dist(Point p, double x, double y) => Math.Sqrt((p.X - x) * (p.X - x) + (p.Y - y) * (p.Y - y));
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ base.OnPointerMoved(e);
+ if (_drag < 0) return;
+ var p = e.GetPosition(this);
+ double hz = Hz(p.X);
+ double db = Math.Clamp(-(p.Y - Bounds.Height / 2) / (Bounds.Height / 2 - 3) * DbSpan, -18, 18);
+ double gn = Math.Clamp(0.5 + db / 36, 0, 1);
+ if (_drag == 0) { _lc = p.X <= 2 ? 0 : Math.Clamp(Math.Log(hz / 20) / Math.Log(100), 0, 1); _lg = gn; Changed?.Invoke(0, _lc, _lg); }
+ else { _hc = p.X >= Bounds.Width - 2 ? 1 : Math.Clamp(Math.Log(hz / 1000) / Math.Log(20), 0, 1); _hs = gn; Changed?.Invoke(1, _hc, _hs); }
+ InvalidateVisual();
+ }
+ protected override void OnPointerReleased(PointerReleasedEventArgs e)
+ { base.OnPointerReleased(e); if (_drag >= 0) { int d = _drag; _drag = -1; e.Pointer.Capture(null); DragEnded?.Invoke(d); } }
+
+ // |H| (dB) of the four stages at f.
+ private double Db(double f)
+ {
+ double lc = LowCutHz(_lc), hc = HighCutHz(_hc), lg = (_lg - 0.5) * 36, hg = (_hs - 0.5) * 36;
+ double db = 0;
+ if (_lc > 0.001) db += Mag(Biquad.Hp(lc), f);
+ if (Math.Abs(lg) > 0.05) db += Mag(Biquad.LowShelf(Math.Max(250, lc * 2), lg), f);
+ if (Math.Abs(hg) > 0.05) db += Mag(Biquad.HighShelf(Math.Min(4000, hc * 0.5), hg), f);
+ if (_hc < 0.999) db += Mag(Biquad.Lp(hc), f);
+ return db;
+ }
+ private static double Mag((double b0, double b1, double b2, double a0, double a1, double a2) c, double f)
+ {
+ double w = 2 * Math.PI * f / Sr, cw = Math.Cos(w), sw = Math.Sin(w), c2 = Math.Cos(2 * w), s2 = Math.Sin(2 * w);
+ double nr = c.b0 + c.b1 * cw + c.b2 * c2, ni = -(c.b1 * sw + c.b2 * s2);
+ double dr = c.a0 + c.a1 * cw + c.a2 * c2, di = -(c.a1 * sw + c.a2 * s2);
+ return 10 * Math.Log10((nr * nr + ni * ni) / Math.Max(1e-30, dr * dr + di * di));
+ }
+ private static class Biquad
+ {
+ public static (double, double, double, double, double, double) Hp(double f) { double w = 2 * Math.PI * f / Sr, c = Math.Cos(w), al = Math.Sin(w) / (2 * 0.7071); return ((1 + c) / 2, -(1 + c), (1 + c) / 2, 1 + al, -2 * c, 1 - al); }
+ public static (double, double, double, double, double, double) Lp(double f) { double w = 2 * Math.PI * f / Sr, c = Math.Cos(w), al = Math.Sin(w) / (2 * 0.7071); return ((1 - c) / 2, 1 - c, (1 - c) / 2, 1 + al, -2 * c, 1 - al); }
+ public static (double, double, double, double, double, double) LowShelf(double f, double db)
+ {
+ double A = Math.Pow(10, db / 40), w = 2 * Math.PI * f / Sr, c = Math.Cos(w), al = Math.Sin(w) / 2 * Math.Sqrt(2), sa = 2 * Math.Sqrt(A) * al;
+ return (A * ((A + 1) - (A - 1) * c + sa), 2 * A * ((A - 1) - (A + 1) * c), A * ((A + 1) - (A - 1) * c - sa), (A + 1) + (A - 1) * c + sa, -2 * ((A - 1) + (A + 1) * c), (A + 1) + (A - 1) * c - sa);
+ }
+ public static (double, double, double, double, double, double) HighShelf(double f, double db)
+ {
+ double A = Math.Pow(10, db / 40), w = 2 * Math.PI * f / Sr, c = Math.Cos(w), al = Math.Sin(w) / 2 * Math.Sqrt(2), sa = 2 * Math.Sqrt(A) * al;
+ return (A * ((A + 1) + (A - 1) * c + sa), -2 * A * ((A - 1) + (A + 1) * c), A * ((A + 1) + (A - 1) * c - sa), (A + 1) - (A - 1) * c + sa, 2 * ((A - 1) - (A + 1) * c), (A + 1) - (A - 1) * c - sa);
+ }
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w < 20 || h < 16) return;
+ ctx.FillRectangle(Brushes.Transparent, new Rect(0, 0, w, h));
+ var gp = new Pen(ChamberInk.GridLine, 1);
+ ctx.DrawLine(gp, new Point(0, h / 2), new Point(w, h / 2));
+ foreach (double hz in new[] { 100.0, 1000.0, 10000.0 }) { double gx = X(hz); ctx.DrawLine(gp, new Point(gx, 0), new Point(gx, h)); }
+
+ var line = new StreamGeometry(); var fill = new StreamGeometry();
+ using (var lc = line.Open())
+ using (var fc = fill.Open())
+ {
+ double y0 = Math.Clamp(Y(Db(FLo)), 1, h - 1);
+ lc.BeginFigure(new Point(0, y0), false);
+ fc.BeginFigure(new Point(0, h / 2), true); fc.LineTo(new Point(0, y0));
+ for (double x = 1.5; x <= w; x += 1.5)
+ {
+ var p = new Point(x, Math.Clamp(Y(Db(Hz(x))), 1, h - 1));
+ lc.LineTo(p); fc.LineTo(p);
+ }
+ fc.LineTo(new Point(w, h / 2));
+ }
+ ctx.DrawGeometry(ChamberInk.Alpha(NotaPalette.AccentColor, 0x1C), null, fill);
+ ctx.DrawGeometry(null, new Pen(NotaPalette.Accent, 1.6), line);
+
+ var t0 = ChamberInk.Text("30", 7, NotaPalette.TextDisabled);
+ ctx.DrawText(t0, new Point(4, h - t0.Height - 2));
+ var t1 = ChamberInk.Text("18k Hz", 7, NotaPalette.TextDisabled);
+ ctx.DrawText(t1, new Point(w - t1.Width - 4, h - t1.Height - 2));
+
+ var ring = new Pen(NotaPalette.BgSunken, 2);
+ double hx0 = Math.Clamp(X(LowCutHz(_lc)), 4, w - 4), hy0 = Math.Clamp(Y((_lg - 0.5) * 36), 4, h - 4);
+ double hx1 = Math.Clamp(X(HighCutHz(_hc)), 4, w - 4), hy1 = Math.Clamp(Y((_hs - 0.5) * 36), 4, h - 4);
+ ctx.DrawEllipse(NotaPalette.AccentBright, ring, new Point(hx0, hy0), _drag == 0 ? 4.5 : 3.8, _drag == 0 ? 4.5 : 3.8);
+ ctx.DrawEllipse(NotaPalette.TextSecondary, ring, new Point(hx1, hy1), _drag == 1 ? 4.5 : 3.8, _drag == 1 ? 4.5 : 3.8);
+ }
+}
+
+// The modulation LFO: a teal sine scrolling at the Rate, its swing following the Depth.
+internal sealed class ChamberLfoView : Control
+{
+ private double _rate = 0.4, _depth = 0.3, _phase;
+ private DateTime _last = DateTime.UtcNow;
+ public ChamberLfoView() { ClipToBounds = true; }
+
+ public void Tick(double rateHz, double depth)
+ {
+ var now = DateTime.UtcNow;
+ double dt = Math.Clamp((now - _last).TotalSeconds, 0, 0.1);
+ _last = now; _rate = rateHz; _depth = depth;
+ _phase = (_phase + dt * rateHz) % 1.0;
+ InvalidateVisual();
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w < 8 || h < 8) return;
+ ctx.DrawLine(new Pen(ChamberInk.GridLine, 1), new Point(0, h / 2), new Point(w, h / 2));
+ double amp = (h / 2 - 3) * (0.12 + 0.88 * Math.Clamp(_depth, 0, 1));
+ const double cycles = 3;
+ var g = new StreamGeometry();
+ using (var c = g.Open())
+ {
+ for (double x = 0; x <= w; x += 1)
+ {
+ double ph = (x / w * cycles - _phase) * 2 * Math.PI;
+ var p = new Point(x, h / 2 - Math.Sin(ph) * amp);
+ if (x == 0) c.BeginFigure(p, false); else c.LineTo(p);
+ }
+ }
+ ctx.DrawGeometry(null, new Pen(NotaPalette.Teal, 1.5), g);
+ var t = ChamberInk.Text(_rate >= 1 ? FormattableString.Invariant($"{_rate:0.0} Hz") : FormattableString.Invariant($"{_rate:0.00} Hz"), 7, NotaPalette.TextTertiary);
+ ctx.DrawText(t, new Point(w - t.Width - 3, 1));
+ }
+}
diff --git a/src/managed/Nota.App/DeviceCards/Bodies/ChamberDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/ChamberDeviceBody.cs
new file mode 100644
index 00000000..182ce5b5
--- /dev/null
+++ b/src/managed/Nota.App/DeviceCards/Bodies/ChamberDeviceBody.cs
@@ -0,0 +1,761 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Detail · Devices — built-in Nota Chamber body (device kind 20), a build of the "Nota Chamber"
+// mockup (700 × 260) on the Monolith / Pentad frame: an always-visible BLEND column (the
+// convolution ⇄ algorithm split and Dry/Wet), a centre tabbed panel (Convolution / Algorithm /
+// EQ · Mod), a right tabbed panel (Levels / Output) and a status strip. The IR view, the
+// decay-per-band graph and the tail-EQ curve are controls (drag trims, RT60 markers, EQ
+// handles); an audio file dropped on the IR view (or picked with Load…) becomes the user IR.
+// Every control is a device param, so automation / MIDI learn / presets / A-B / persistence
+// come for free. FullBleed — the shared shell draws the header (name · preset · A/B · meter).
+
+using System;
+using System.Collections.Generic;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Controls.Primitives;
+using Avalonia.Input;
+using Avalonia.Layout;
+using Avalonia.Media;
+using Avalonia.Platform.Storage;
+using Nota.Application;
+using static Nota.App.DeviceCardKit;
+
+namespace Nota.App;
+
+internal sealed class ChamberDeviceBody : IDeviceBody
+{
+ // ── Parameter indices (must match Chamber.h) ─────────────────────────────
+ private const int Blend = 0, DryWet = 1, ConvOn = 2, AlgoOn = 3, DryLevel = 4, Routing = 5,
+ IrSelect = 6, IrStart = 7, IrDecay = 8, IrAttack = 9, IrSize = 10, ConvPredelay = 11, ConvSync = 12, IrReverse = 13, IrTrueStereo = 14,
+ AlgoMode = 15, AlgoDecay = 16, AlgoSize = 17, AlgoDiffusion = 18, AlgoDamping = 19, AlgoPredelay = 20, AlgoSync = 21, AlgoLowDecay = 22, AlgoHighDecay = 23,
+ Freeze = 24, FreezeIn = 25, AlgoVintage = 26, ModRate = 27, ModDepth = 28, ShimmerAmount = 29, ShimmerPitch = 30, ShimmerFeedback = 31,
+ EqLowCut = 32, EqLowGain = 33, EqHighShelf = 34, EqHighCut = 35, EqPosition = 36,
+ DuckAmount = 37, DuckRelease = 38, Output = 39, WidthP = 40, BassMono = 41, Quality = 42, WetOnly = 43, ZeroLatency = 44;
+ // Scope telemetry layout (Chamber::S_*).
+ private const int S_WetL = 0, S_OutL = 2, S_OutR = 3, S_DuckDb = 4, S_Cpu = 5, S_Latency = 6, S_SampleRate = 7, S_Building = 8,
+ S_IrSeconds = 9, S_IrRate = 10, S_IrChannels = 11, S_KernelSeconds = 12, S_UserIr = 16,
+ S_ResultSeconds = 19, S_PreviewSeconds = 20, S_PreviewGen = 21, kScope = 22;
+ private const int IrCount = 17; // 16 built-ins + the user slot (normalized 1.0)
+
+ private static readonly string[] Modes = { "Dark Hall", "Plate", "Quartz", "Shimmer" };
+ private static readonly string[] SyncNames = { "1/64", "1/32T", "1/32", "1/16T", "1/16", "1/8T", "1/16.", "1/8", "1/4T", "1/8.", "1/4", "1/4.", "1/2" };
+ // Fallback for the built-in IR catalogue when the engine can't be asked (a rack chain's
+ // proxy); mirrors chamber::irSpec in Chamber.h — the engine list wins when present.
+ private static readonly (string Name, string Cat, string Len)[] IrFallback =
+ {
+ ("Concert Hall · Wide", "HALL", "2.6"), ("Stone Vault", "HALL", "4.4"), ("Cathedral", "HALL", "7.5"), ("Scoring Stage", "HALL", "2.3"),
+ ("Wood Chamber", "ROOM", "1.6"), ("Live Room", "ROOM", "1.0"), ("Drum Room", "ROOM", "0.8"), ("Tiled Bathroom", "ROOM", "1.3"),
+ ("Vocal Plate", "PLATE", "2.8"), ("Bright Plate", "PLATE", "2.0"), ("Spring Tank", "SPRING", "2.6"), ("Car Park", "SPACE", "3.6"),
+ ("Stairwell", "SPACE", "3.2"), ("Forest Clearing", "OUTDOOR", "2.0"), ("Gated Room", "FX", "0.7"), ("Metal Tank", "FX", "3.4"),
+ };
+
+ private static readonly IBrush RailBg = new SolidColorBrush(Color.Parse("#1B1916"));
+ private static readonly IBrush Panel = NotaPalette.BgApp;
+ private static readonly IBrush Border2 = NotaPalette.BorderDefault;
+ private static readonly IBrush BorderIn = new SolidColorBrush(Color.Parse("#221F1A"));
+ private static readonly IBrush Inset = NotaPalette.BgSunken;
+ private static readonly IBrush TabBg = NotaPalette.SurfaceCard;
+ private static readonly IBrush Amber = NotaPalette.Accent;
+ private static readonly IBrush AmberLit = NotaPalette.AccentBright;
+ private static readonly IBrush AmberSubtle = NotaPalette.AccentSubtle;
+ private static readonly IBrush TealC = NotaPalette.Teal;
+ private static readonly IBrush TxtC = NotaPalette.TextPrimary;
+ private static readonly IBrush Txt2 = NotaPalette.TextSecondary;
+ private static readonly IBrush MutedC = NotaPalette.TextTertiary;
+ private static readonly IBrush DimC = NotaPalette.TextDisabled;
+ private static readonly IBrush OffPill = NotaPalette.SurfaceRaised;
+
+ public double Width => 700;
+ public bool FullBleed => true;
+ public string? Subtitle => "HYBRID";
+
+ public Control Build(DeviceCardContext ctx, int index)
+ {
+ var engine = ctx.Engine;
+ int track = ctx.TrackId, di = index;
+ float P(int p) => engine.DeviceGetParam(track, di, p);
+ void Begin(int p) => engine.BeginAutomationWrite(track, AutomationTarget.DeviceParam, di, p, "");
+ void End(int p) => engine.EndAutomationWrite(track, AutomationTarget.DeviceParam, di, p, "");
+ void Raw(int p, float v) => engine.DeviceSetParam(track, di, p, Math.Clamp(v, 0f, 1f));
+ // A discrete edit (click) is one automation gesture, so Touch / Latch / Write record it.
+ void SetP(int p, float v) { Begin(p); Raw(p, v); End(p); }
+ bool On(int p) => P(p) >= 0.5f;
+ int Sel(int p, int n) => Math.Clamp((int)Math.Round(P(p) * (n - 1)), 0, n - 1);
+
+ var readouts = new List<Action>();
+ var scope = new float[kScope];
+ int scN = 0;
+ double Sc(int i) => scN > i ? scope[i] : 0;
+
+ // IR catalogue (engine first, fallback table in a rack chain).
+ var irList = new List<(string Name, string Cat, string Len)>();
+ foreach (var line in engine.DeviceText(track, di, 10).Split('\n', StringSplitOptions.RemoveEmptyEntries))
+ {
+ var f = line.Split('\t');
+ if (f.Length >= 3) irList.Add((f[0], f[1], f[2]));
+ }
+ if (irList.Count == 0) irList.AddRange(IrFallback);
+
+ // ---- formatters -------------------------------------------------------------
+ static double Exp(double v, double lo, double hi) => lo * Math.Pow(hi / lo, Math.Clamp(v, 0, 1));
+ static string Secs(double s) => s >= 10 ? FormattableString.Invariant($"{s:0.0} s") : s >= 1 ? FormattableString.Invariant($"{s:0.00} s") : FormattableString.Invariant($"{s * 1000:0} ms");
+ static string Ms(double ms) => ms >= 100 ? FormattableString.Invariant($"{ms:0} ms") : ms >= 10 ? FormattableString.Invariant($"{ms:0.0} ms") : FormattableString.Invariant($"{ms:0.0} ms");
+ static string Hz(double hz) => hz >= 1000 ? FormattableString.Invariant($"{hz / 1000:0.0} kHz") : FormattableString.Invariant($"{hz:0} Hz");
+ static string Pct(double v) => FormattableString.Invariant($"{v * 100:0} %");
+ static string Db(double db) => db <= -99 ? "−∞" : FormattableString.Invariant($"{db:+0.0;−0.0;0.0} dB");
+ static string ShortDb(double db) => db <= -99 ? "−∞" : FormattableString.Invariant($"{db:0.0;−0.0;0.0}");
+ string Pre(int timeP, int syncP) => On(syncP) ? SyncNames[Sel(timeP, SyncNames.Length)] : Ms(500 * P(timeP) * P(timeP));
+ double IrSecs() => Sc(S_IrSeconds);
+ double RtMid() => Exp(P(AlgoDecay), 0.2, 20);
+ double RtLow() => RtMid() * Exp(P(AlgoLowDecay), 0.25, 4);
+ double RtHigh() => RtMid() * Exp(P(AlgoHighDecay), 0.25, 4);
+ double PreSec(int timeP, int syncP)
+ {
+ if (!On(syncP)) return 0.5 * P(timeP) * P(timeP);
+ double[] beats = { 1.0 / 16, 1.0 / 12, 1.0 / 8, 1.0 / 6, 1.0 / 4, 1.0 / 3, 3.0 / 8, 1.0 / 2, 2.0 / 3, 3.0 / 4, 1, 1.5, 2 };
+ double bpm = scN > 13 && scope[13] > 1 ? scope[13] : 120;
+ return beats[Sel(timeP, beats.Length)] * 60.0 / bpm;
+ }
+ string LowCutF(double v) => v <= 0.001 ? "off" : Hz(Exp(v, 20, 2000));
+ string HighCutF(double v) => v >= 0.999 ? "off" : Hz(Exp(v, 1000, 20000));
+ static string GainF(double v) { double db = (v - 0.5) * 36; return Math.Abs(db) < 0.05 ? "0 dB" : FormattableString.Invariant($"{db:+0.0;−0.0} dB"); }
+ static double ShareDb(double share) => share <= 1e-4 ? -100 : 10 * Math.Log10(share); // equal-power blend gain
+ static double DryDb(double v) { double g = 2 * v * v; return g <= 1e-5 ? -100 : 20 * Math.Log10(g); }
+ string Interval() => Sel(ShimmerPitch, 3) switch { 0 => "−12 st", 1 => "+7 st", _ => "+12 st" };
+
+ // ---- small builders ---------------------------------------------------------
+ static TextBlock Caps(string t, IBrush? c = null, double fs = 7) => new() { Text = t, FontSize = fs, FontWeight = FontWeight.Bold, Foreground = c ?? MutedC, LetterSpacing = 0.8, VerticalAlignment = VerticalAlignment.Center };
+ static TextBlock Mono(string t, double fs, IBrush c)
+ { var tb = new TextBlock { Text = t, FontSize = fs, Foreground = c, VerticalAlignment = VerticalAlignment.Center }; tb.BindResource(TextBlock.FontFamilyProperty, "Font.Mono"); return tb; }
+ static StackPanel Row(double sp, params Control[] cs)
+ { var s = new StackPanel { Orientation = Orientation.Horizontal, Spacing = sp, VerticalAlignment = VerticalAlignment.Center }; foreach (var c in cs) s.Children.Add(c); return s; }
+ static Control Docked(Control c, Dock d) { DockPanel.SetDock(c, d); return c; }
+ static Control Col(Control c, int col) { Grid.SetColumn(c, col); return c; }
+ static Control GRow(Control c, int row) { Grid.SetRow(c, row); return c; }
+ static Border Divider(Control child, double top = 5) => new() { BorderBrush = BorderIn, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(0, top, 0, 0), Child = child };
+ static Border InsetBox(Control child) => new() { Background = Inset, BorderBrush = BorderIn, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(4), ClipToBounds = true, Child = child };
+
+ // Gauge knob bound to a device param (automation gesture + MIDI learn + live follow).
+ Control K(int p, string name, Func<double, string> fmt, double size = 34, double cellW = 48, IBrush? arc = null, Action? onChange = null)
+ {
+ var val = Mono(fmt(P(p)), 7, TxtC);
+ var knob = new Knob(P(p), 1.0) { Accent = true, ArcColor = arc, Default = engine.DeviceParamDefault(track, di, p), Width = size, Height = size };
+ knob.ValueChanged += v => { Raw(p, (float)v); val.Text = fmt(v); onChange?.Invoke(); };
+ knob.GestureBegin += () => Begin(p);
+ knob.GestureEnd += () => End(p);
+ MidiLearn.Bind(knob, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));
+ readouts.Add(() => { if (knob.Dragging) return; float c = P(p); if (Math.Abs(c - knob.Value) > 1e-4) knob.Value = c; val.Text = fmt(c); });
+ return KnobCell(name, knob, val, cellW);
+ }
+
+ // On/off pill bound to a param (> 0.5 = on).
+ Control Toggle(int p, string label, Func<bool>? dim = null)
+ {
+ var pill = new Border { Width = 18, Height = 10, CornerRadius = new CornerRadius(5), VerticalAlignment = VerticalAlignment.Center };
+ var dot = new Border { Width = 7, Height = 7, CornerRadius = new CornerRadius(4) };
+ var host = new Canvas { Width = 18, Height = 10 }; Canvas.SetTop(dot, 1.5); host.Children.Add(dot); pill.Child = host;
+ var txt = new TextBlock { Text = label, FontSize = 8, VerticalAlignment = VerticalAlignment.Center };
+ void Hi()
+ {
+ bool on = On(p), d = dim?.Invoke() ?? false;
+ pill.Background = on ? (d ? NotaPalette.BorderStrong : Amber) : OffPill; dot.Background = on ? Panel : MutedC;
+ Canvas.SetLeft(dot, on ? 9.5 : 1.5); txt.Foreground = on && !d ? TxtC : Txt2;
+ }
+ var wrap = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand), Children = { pill } };
+ if (label.Length > 0) wrap.Children.Add(txt);
+ wrap.PointerPressed += (_, e) => { if (!e.GetCurrentPoint(wrap).Properties.IsLeftButtonPressed) return; SetP(p, On(p) ? 0f : 1f); Hi(); e.Handled = true; };
+ readouts.Add(Hi); Hi();
+ MidiLearn.Bind(wrap, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));
+ return wrap;
+ }
+
+ // Segmented chips over a discrete param (n options spread over 0..1).
+ Control Seg(int p, string[] names, double fs = 7, IBrush? accent = null)
+ {
+ int n = names.Length; var cells = new Border[n];
+ var acc = accent ?? Amber;
+ void Hi()
+ {
+ int cur = Sel(p, n);
+ for (int i = 0; i < n; i++)
+ {
+ bool on = i == cur;
+ cells[i].Background = on ? acc : Brushes.Transparent;
+ var tb = (TextBlock)cells[i].Child!; tb.Foreground = on ? Panel : MutedC; tb.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;
+ }
+ }
+ var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 1 };
+ for (int i = 0; i < n; i++)
+ {
+ int iv = i;
+ var c = new Border { CornerRadius = new CornerRadius(2), Padding = new Thickness(4, 0), Cursor = new Cursor(StandardCursorType.Hand), Child = new TextBlock { Text = names[i], FontSize = fs, Foreground = MutedC } };
+ c.PointerPressed += (_, e) => { SetP(p, n > 1 ? iv / (float)(n - 1) : 0f); Hi(); e.Handled = true; };
+ cells[i] = c; row.Children.Add(c);
+ }
+ readouts.Add(Hi); Hi();
+ var seg = new Border { Background = Inset, BorderBrush = Border2, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(3), Padding = new Thickness(1), VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Child = row };
+ MidiLearn.Bind(seg, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));
+ return seg;
+ }
+
+ // Horizontal bar slider. get/set map the bar position (0..1) onto the param `p`
+ // (CONV / ALGO both drive Blend, from opposite ends).
+ Control HBar(int p, Func<double> get, Action<double> set, Func<double, string> fmt, IBrush fillC, Func<bool>? dim = null, double valW = 26)
+ {
+ var fill = new Border { Height = 3, Background = fillC, CornerRadius = new CornerRadius(2), HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center };
+ var handle = new Border { Width = 6, Height = 7, Background = Txt2, CornerRadius = new CornerRadius(2) };
+ var lay = new Canvas { Height = 9 };
+ lay.Children.Add(handle); Canvas.SetTop(handle, 1);
+ var canvas = new Panel { Height = 11, MinWidth = 24, Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand), Children = {
+ new Border { Height = 3, Background = Inset, CornerRadius = new CornerRadius(2), VerticalAlignment = VerticalAlignment.Center }, fill, lay } };
+ var val = Mono("", 8, TxtC); val.MinWidth = valW; val.TextAlignment = TextAlignment.Right;
+ bool drag = false;
+ void Vis()
+ {
+ double v = Math.Clamp(get(), 0, 1), w = canvas.Bounds.Width; if (w <= 0) w = 80;
+ fill.Width = Math.Max(0, v * w); Canvas.SetLeft(handle, v * w - 3); val.Text = fmt(v);
+ bool d = dim?.Invoke() ?? false;
+ fill.Background = d ? NotaPalette.BorderStrong : fillC; handle.Background = d ? MutedC : Txt2; val.Foreground = d ? Txt2 : TxtC;
+ }
+ void From(PointerEventArgs e) { double w = canvas.Bounds.Width; set(w > 0 ? Math.Clamp(e.GetPosition(canvas).X / w, 0, 1) : 0); Vis(); }
+ canvas.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(canvas).Properties.IsLeftButtonPressed) return;
+ if (e.ClickCount == 2) { Begin(p); Raw(p, engine.DeviceParamDefault(track, di, p)); End(p); Vis(); e.Handled = true; return; }
+ drag = true; Begin(p); e.Pointer.Capture(canvas); From(e); e.Handled = true;
+ };
+ canvas.PointerMoved += (_, e) => { if (drag) From(e); };
+ canvas.PointerReleased += (_, e) => { if (drag) { drag = false; End(p); e.Pointer.Capture(null); } };
+ canvas.SizeChanged += (_, _) => Vis();
+ readouts.Add(() => { if (!drag) Vis(); });
+ var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 5, VerticalAlignment = VerticalAlignment.Center };
+ grid.Children.Add(canvas); grid.Children.Add(Col(val, 1));
+ MidiLearn.Bind(grid, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));
+ return grid;
+ }
+ Control Bar(int p, Func<double, string> fmt, Func<bool>? dim = null, double valW = 26)
+ => HBar(p, () => P(p), v => Raw(p, (float)v), fmt, Amber, dim, valW);
+ Control SliderRow(string label, int p, Func<double, string> fmt, double labW = 48, Func<bool>? dim = null, double valW = 26)
+ {
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions(FormattableString.Invariant($"{labW},*")), VerticalAlignment = VerticalAlignment.Center };
+ g.Children.Add(Caps(label)); g.Children.Add(Col(Bar(p, fmt, dim, valW), 1));
+ return g;
+ }
+ // A small text button.
+ Border Btn(string text, Action click, string? tip = null)
+ {
+ var b = new Border { Height = 16, Padding = new Thickness(6, 0), CornerRadius = new CornerRadius(3), Background = OffPill, Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center,
+ Child = new TextBlock { Text = text, FontSize = 8, Foreground = TxtC, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center } };
+ b.PointerPressed += (_, e) => { if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return; click(); e.Handled = true; };
+ if (tip != null) ToolTip.SetTip(b, tip);
+ return b;
+ }
+ // A latching button over a toggle param (Freeze / Hold in).
+ Border Latch(int p, string text, string tip)
+ {
+ var tb = new TextBlock { Text = text, FontSize = 8, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center };
+ var b = new Border { Height = 16, CornerRadius = new CornerRadius(3), BorderThickness = new Thickness(1), Cursor = new Cursor(StandardCursorType.Hand), Child = tb };
+ void Hi() { bool on = On(p); b.Background = on ? AmberSubtle : OffPill; b.BorderBrush = on ? Amber : Brushes.Transparent; tb.Foreground = on ? AmberLit : TxtC; tb.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal; }
+ b.PointerPressed += (_, e) => { if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return; SetP(p, On(p) ? 0f : 1f); Hi(); e.Handled = true; };
+ ToolTip.SetTip(b, tip);
+ MidiLearn.Bind(b, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));
+ readouts.Add(Hi); Hi();
+ return b;
+ }
+
+ // ---- user IR loading ------------------------------------------------------------
+ var irView = new ChamberIrView();
+ var waveL = new float[320]; var waveR = new float[320];
+ string waveSig = "";
+ // Rendered previews (processed IR, algorithm echogram), refetched when the engine bumps its generation.
+ float[] resEnv = Array.Empty<float>(), echoEnv = Array.Empty<float>();
+ double previewGen = -1;
+ void FetchPreviews()
+ {
+ if (Sc(S_PreviewGen) == previewGen) return;
+ previewGen = Sc(S_PreviewGen);
+ var a = new float[360]; var b = new float[360];
+ resEnv = engine.DeviceLayerWave(track, di, 2, a, a.Length) > 0 ? a : Array.Empty<float>();
+ echoEnv = engine.DeviceLayerWave(track, di, 3, b, b.Length) > 0 ? b : Array.Empty<float>();
+ }
+ void FetchWave()
+ {
+ int n0 = engine.DeviceLayerWave(track, di, 0, waveL, waveL.Length);
+ int n1 = engine.DeviceLayerWave(track, di, 1, waveR, waveR.Length);
+ irView.SetWave(n0 > 0 ? (float[])waveL.Clone() : Array.Empty<float>(), n1 > 0 ? (float[])waveR.Clone() : Array.Empty<float>());
+ }
+ void LoadIr(string path)
+ {
+ if (!engine.DeviceLoadFile(track, di, path)) return;
+ waveSig = ""; ctx.NotifyChanged();
+ foreach (var a in readouts) a();
+ }
+ async void PickIr(Control anchor)
+ {
+ var top = TopLevel.GetTopLevel(anchor);
+ if (top is null) return;
+ var files = await top.StorageProvider.OpenFilePickerAsync(new Avalonia.Platform.Storage.FilePickerOpenOptions
+ {
+ Title = "Load impulse response", AllowMultiple = false,
+ FileTypeFilter = new[] { new Avalonia.Platform.Storage.FilePickerFileType("Impulse response") { Patterns = new[] { "*.wav", "*.wave", "*.flac", "*.mp3" } } },
+ });
+ if (files.Count > 0 && files[0].TryGetLocalPath() is { } p) LoadIr(p);
+ }
+ irView.FileDropped += p => { ctx.HideDropGlow(); LoadIr(p); };
+ irView.DropHover += ctx.HideDropGlow; // the IR view owns the highlight, not the panel
+
+ // ======================================================================
+ // LEFT — BLEND column (C/A split + Dry/Wet)
+ // ======================================================================
+ Control Fader(int p, bool split, string label)
+ {
+ var f = new ChamberFader { Split = split, VerticalAlignment = VerticalAlignment.Stretch, Default = engine.DeviceParamDefault(track, di, p) };
+ f.Changed += v => Raw(p, (float)v);
+ f.DragStarted += () => Begin(p);
+ f.DragEnded += () => End(p);
+ readouts.Add(() => f.Set(P(p)));
+ MidiLearn.Bind(f, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));
+ ToolTip.SetTip(f, split ? "Blend — convolution (slate, top) ⇄ algorithm (brass, bottom). Double-click: 50 / 50" : "Dry/Wet — double-click resets");
+ var lb = Caps(label); lb.HorizontalAlignment = HorizontalAlignment.Center;
+ if (!split) readouts.Add(() => lb.Foreground = P(DryWet) > 0.995f || On(WetOnly) ? AmberLit : MutedC);
+ return new DockPanel { Children = { Docked(lb, Dock.Bottom), f } };
+ }
+ var blendTxt = Mono("", 7, AmberLit); blendTxt.HorizontalAlignment = HorizontalAlignment.Center;
+ var wetTxt = Mono("", 7, TxtC); wetTxt.HorizontalAlignment = HorizontalAlignment.Center;
+ readouts.Add(() =>
+ {
+ float b = P(Blend);
+ blendTxt.Text = FormattableString.Invariant($"{(1 - b) * 100:0} / {b * 100:0}");
+ bool wo = On(WetOnly);
+ wetTxt.Text = wo ? "SEND" : FormattableString.Invariant($"{P(DryWet) * 100:0} %");
+ wetTxt.Foreground = wo || P(DryWet) > 0.995f ? AmberLit : TxtC;
+ });
+ var blendTitle = Caps("BLEND"); blendTitle.HorizontalAlignment = HorizontalAlignment.Center;
+ var faders = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto"), ColumnSpacing = 9, HorizontalAlignment = HorizontalAlignment.Center, Margin = new Thickness(0, 4, 0, 3) };
+ faders.Children.Add(Fader(Blend, true, "C/A")); faders.Children.Add(Col(Fader(DryWet, false, "WET"), 1));
+ var blendCol = new Border { Width = 56, Background = Panel, BorderBrush = Border2, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(5), Padding = new Thickness(0, 5, 0, 4),
+ Child = new DockPanel { Children = { Docked(blendTitle, Dock.Top), Docked(wetTxt, Dock.Bottom), Docked(blendTxt, Dock.Bottom), faders } } };
+ DockPanel.SetDock(blendCol, Dock.Left);
+
+ // ======================================================================
+ // CENTRE — Convolution
+ // ======================================================================
+ Control ConvTab()
+ {
+ // IR selector: ‹ [name · length · rate ▾] › + Load…
+ var irName = new TextBlock { FontSize = 9, Foreground = TxtC, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };
+ var irInfo = Mono("", 7, MutedC);
+ var irBox = new Border { Height = 16, Background = Inset, BorderBrush = Border2, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(3), Padding = new Thickness(6, 0), Cursor = new Cursor(StandardCursorType.Hand),
+ Child = new DockPanel { Children = { Docked(new TextBlock { Text = "▾", FontSize = 8, Foreground = MutedC, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(6, 0, 0, 0) }, Dock.Right), Docked(irInfo, Dock.Right), irName } } };
+ ToolTip.SetTip(irBox, "Impulse response — built-in rooms, or your own file (drop it on the waveform)");
+ MidiLearn.Bind(irBox, MidiTarget.DeviceParam(track, di, IrSelect), "IR");
+ readouts.Add(() =>
+ {
+ int ir = Sel(IrSelect, IrCount);
+ string user = ir == IrCount - 1 ? engine.DeviceText(track, di, 2) : "";
+ irName.Text = ir < irList.Count ? irList[ir].Name : user.Length > 0 ? user : "User IR — none loaded";
+ double s = IrSecs(), sr = Sc(S_IrRate); int ch = (int)Sc(S_IrChannels);
+ irInfo.Text = s > 0 ? FormattableString.Invariant($"{s:0.0} s · {sr / 1000:0.#} kHz · {(ch >= 4 ? "4-ch" : ch == 2 ? "stereo" : "mono")} ") : "";
+ });
+ void StepIr(int d) { int ir = Sel(IrSelect, IrCount); int max = engine.DeviceText(track, di, 2).Length > 0 ? IrCount - 1 : IrCount - 2; SetP(IrSelect, Math.Clamp(ir + d, 0, max) / (float)(IrCount - 1)); }
+ irBox.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(irBox).Properties.IsLeftButtonPressed) return;
+ var fly = new MenuFlyout();
+ int cur = Sel(IrSelect, IrCount);
+ string lastCat = "";
+ for (int i = 0; i < irList.Count; i++)
+ {
+ if (irList[i].Cat != lastCat)
+ {
+ if (lastCat.Length > 0) fly.Items.Add(new Separator());
+ fly.Items.Add(new MenuItem { Header = irList[i].Cat, IsEnabled = false, FontSize = 9 });
+ lastCat = irList[i].Cat;
+ }
+ int iv = i;
+ var mi = new MenuItem { Header = FormattableString.Invariant($"{irList[i].Name} {irList[i].Len} s") };
+ if (i == cur) mi.Icon = new Avalonia.Controls.Shapes.Ellipse { Width = 6, Height = 6, Fill = Amber };
+ mi.Click += (_, _) => SetP(IrSelect, iv / (float)(IrCount - 1));
+ fly.Items.Add(mi);
+ }
+ fly.Items.Add(new Separator());
+ string userName = engine.DeviceText(track, di, 2);
+ var um = new MenuItem { Header = userName.Length > 0 ? FormattableString.Invariant($"User · {userName}") : "User IR (none loaded)", IsEnabled = userName.Length > 0 };
+ if (cur == IrCount - 1) um.Icon = new Avalonia.Controls.Shapes.Ellipse { Width = 6, Height = 6, Fill = Amber };
+ um.Click += (_, _) => SetP(IrSelect, 1f);
+ fly.Items.Add(um);
+ var load = new MenuItem { Header = "Load impulse response…" };
+ load.Click += (_, _) => PickIr(irBox);
+ fly.Items.Add(load);
+ fly.ShowAt(irBox);
+ e.Handled = true;
+ };
+ var irRow = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*,Auto,Auto"), ColumnSpacing = 4, Height = 18 };
+ irRow.Children.Add(Caps("IR"));
+ irRow.Children.Add(Col(Btn("‹", () => StepIr(-1), "Previous IR"), 1));
+ irRow.Children.Add(Col(irBox, 2));
+ irRow.Children.Add(Col(Btn("›", () => StepIr(1), "Next IR"), 3));
+ irRow.Children.Add(Col(Btn("Load…", () => PickIr(irRow), "Load an impulse response (WAV / FLAC / MP3 — mono, stereo or 4-ch true stereo)"), 4));
+
+ // IR view: trims drive IR Start / IR Decay.
+ irView.TrimChanged += (s, e) => { Raw(IrStart, (float)s); Raw(IrDecay, (float)e); };
+ irView.DragStarted += h => Begin(h == 1 ? IrStart : IrDecay);
+ irView.DragEnded += h => End(h == 1 ? IrStart : IrDecay);
+ ToolTip.SetTip(irView, "Drag the brass lines to trim the IR (Start · Decay); double-click resets. Drop an audio file here to load it.");
+ readouts.Add(() =>
+ {
+ string sig = FormattableString.Invariant($"{Sel(IrSelect, IrCount)}|{Sc(S_IrSeconds):0.000}|{Sc(S_IrChannels)}|{Sc(S_UserIr)}");
+ if (sig != waveSig) { waveSig = sig; FetchWave(); }
+ int ir = Sel(IrSelect, IrCount);
+ bool noUser = ir == IrCount - 1 && Sc(S_UserIr) < 0.5;
+ irView.Set(IrSecs(), P(IrStart), P(IrDecay), 0.5 * P(IrAttack) * P(IrAttack), On(IrReverse), Sc(S_Building) > 0.5,
+ noUser ? "Drop an impulse response here (WAV / FLAC / MP3) or click Load…" : null);
+ FetchPreviews();
+ irView.SetResult(resEnv, Sc(S_ResultSeconds), PreSec(ConvPredelay, ConvSync));
+ });
+
+ var knobs = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*,*,*,Auto"), Height = 54 };
+ knobs.Children.Add(K(ConvPredelay, "PREDELAY", _ => Pre(ConvPredelay, ConvSync)));
+ knobs.Children.Add(Col(K(IrSize, "SIZE", v => FormattableString.Invariant($"{Exp(v, 0.5, 2) * 100:0} %")), 1));
+ knobs.Children.Add(Col(K(IrAttack, "ATTACK", v => Ms(500 * v * v)), 2));
+ knobs.Children.Add(Col(K(IrDecay, "DECAY", v => IrSecs() > 0 ? Secs(v * IrSecs()) : Pct(v)), 3));
+ var toggles = new StackPanel { Spacing = 3, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(6, 0, 0, 0), Children = {
+ Toggle(IrTrueStereo, "True stereo"), Toggle(IrReverse, "Reverse IR"), Toggle(ConvSync, "Sync predelay") } };
+ knobs.Children.Add(Col(toggles, 4));
+
+ return new DockPanel { LastChildFill = true, Margin = new Thickness(8, 5, 8, 2), Children = {
+ Docked(irRow, Dock.Top),
+ Docked(knobs, Dock.Bottom),
+ new Border { Margin = new Thickness(0, 4, 0, 2), Child = InsetBox(irView) } } };
+ }
+
+ // ======================================================================
+ // CENTRE — Algorithm
+ // ======================================================================
+ Control AlgoTab()
+ {
+ // MODE chips + tail readout
+ var chips = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center };
+ var chipB = new Border[Modes.Length];
+ void HiModes()
+ {
+ int cur = Sel(AlgoMode, Modes.Length);
+ for (int i = 0; i < Modes.Length; i++)
+ {
+ bool on = i == cur;
+ chipB[i].BorderBrush = on ? Amber : NotaPalette.BorderStrong; chipB[i].Background = on ? AmberSubtle : Brushes.Transparent;
+ var t = (TextBlock)chipB[i].Child!; t.Foreground = on ? AmberLit : Txt2; t.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;
+ }
+ }
+ for (int i = 0; i < Modes.Length; i++)
+ {
+ int iv = i;
+ var c = new Border { Height = 18, Padding = new Thickness(8, 0), CornerRadius = new CornerRadius(3), BorderThickness = new Thickness(1), Cursor = new Cursor(StandardCursorType.Hand),
+ Child = new TextBlock { Text = Modes[i], FontSize = 9, VerticalAlignment = VerticalAlignment.Center } };
+ c.PointerPressed += (_, e) => { SetP(AlgoMode, iv / 3f); HiModes(); e.Handled = true; };
+ chipB[i] = c; chips.Children.Add(c);
+ }
+ MidiLearn.Bind(chips, MidiTarget.DeviceParam(track, di, AlgoMode), "Algo Mode");
+ readouts.Add(HiModes); HiModes();
+ var tail = Mono("", 7, MutedC);
+ readouts.Add(() => tail.Text = On(Freeze) ? "tail ∞ (frozen)" : FormattableString.Invariant($"tail {Secs(RtMid())}"));
+ var modeRow = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*"), ColumnSpacing = 5, Height = 20 };
+ modeRow.Children.Add(Caps("MODE")); modeRow.Children.Add(Col(chips, 1));
+ tail.HorizontalAlignment = HorizontalAlignment.Right; modeRow.Children.Add(Col(tail, 2));
+
+ // DECAY PER BAND graph
+ var graph = new ChamberDecayGraph();
+ graph.Changed += (band, rt) =>
+ {
+ if (band == 1) Raw(AlgoDecay, (float)Math.Clamp(Math.Log(Math.Clamp(rt, 0.2, 20) / 0.2) / Math.Log(100), 0, 1));
+ else
+ {
+ double mul = Math.Clamp(rt / RtMid(), 0.25, 4);
+ Raw(band == 0 ? AlgoLowDecay : AlgoHighDecay, (float)(0.5 + Math.Log(mul) / Math.Log(16)));
+ }
+ };
+ graph.DragStarted += b => Begin(b == 0 ? AlgoLowDecay : b == 1 ? AlgoDecay : AlgoHighDecay);
+ graph.DragEnded += b => End(b == 0 ? AlgoLowDecay : b == 1 ? AlgoDecay : AlgoHighDecay);
+ ToolTip.SetTip(graph, "Drag a marker to set that band's RT60 (mid = Decay; low / high follow it as ratios). The Damping knob sets the high crossover.");
+ readouts.Add(() =>
+ {
+ FetchPreviews();
+ graph.SetEchogram(echoEnv, Sc(S_PreviewSeconds));
+ graph.Set(PreSec(AlgoPredelay, AlgoSync), RtLow(), RtMid(), RtHigh(), On(Freeze), FormattableString.Invariant($"· hf ≥ {Hz(Exp(P(AlgoDamping), 500, 18000))}"));
+ });
+
+ var knobs = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*,*,*,*,Auto"), Height = 56 };
+ knobs.Children.Add(K(AlgoDecay, "DECAY", v => Secs(Exp(v, 0.2, 20)), 36, 50));
+ knobs.Children.Add(Col(K(AlgoSize, "SIZE", v => FormattableString.Invariant($"{Exp(v, 0.4, 2.5) * 100:0} %"), 36, 50), 1));
+ knobs.Children.Add(Col(K(AlgoDiffusion, "DIFFUSE", v => Pct(v), 36, 50), 2));
+ knobs.Children.Add(Col(K(AlgoDamping, "DAMPING", v => Hz(Exp(v, 500, 18000)), 36, 50), 3));
+ knobs.Children.Add(Col(K(AlgoPredelay, "PREDELAY", _ => Pre(AlgoPredelay, AlgoSync), 36, 50), 4));
+ var toggles = new StackPanel { Spacing = 3, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(6, 0, 0, 0), Children = {
+ Toggle(Freeze, "Freeze"), Toggle(AlgoVintage, "Vintage"), Toggle(AlgoSync, "Sync") } };
+ knobs.Children.Add(Col(toggles, 5));
+
+ return new DockPanel { LastChildFill = true, Margin = new Thickness(8, 5, 8, 2), Children = {
+ Docked(modeRow, Dock.Top),
+ Docked(knobs, Dock.Bottom),
+ new Border { Margin = new Thickness(0, 4, 0, 2), Child = InsetBox(graph) } } };
+ }
+
+ // ======================================================================
+ // CENTRE — EQ · Mod
+ // ======================================================================
+ Control EqModTab()
+ {
+ var eq = new ChamberEqCurve();
+ eq.Changed += (h, cut, gain) =>
+ {
+ if (h == 0) { Raw(EqLowCut, (float)cut); Raw(EqLowGain, (float)gain); }
+ else { Raw(EqHighCut, (float)cut); Raw(EqHighShelf, (float)gain); }
+ };
+ eq.DragStarted += h => { if (h == 0) { Begin(EqLowCut); Begin(EqLowGain); } else { Begin(EqHighCut); Begin(EqHighShelf); } };
+ eq.DragEnded += h => { if (h == 0) { End(EqLowCut); End(EqLowGain); } else { End(EqHighCut); End(EqHighShelf); } };
+ ToolTip.SetTip(eq, "Brass handle: low cut (X) + low shelf (Y) · grey handle: high cut (X) + high shelf (Y)");
+ readouts.Add(() => eq.Set(P(EqLowCut), P(EqLowGain), P(EqHighShelf), P(EqHighCut)));
+ var eqKnobs = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*,*,*"), Height = 50 };
+ eqKnobs.Children.Add(K(EqLowCut, "LOW CUT", LowCutF, 30, 48));
+ eqKnobs.Children.Add(Col(K(EqLowGain, "LOW GAIN", GainF, 30, 48), 1));
+ eqKnobs.Children.Add(Col(K(EqHighShelf, "HI SHELF", GainF, 30, 48), 2));
+ eqKnobs.Children.Add(Col(K(EqHighCut, "HI CUT", HighCutF, 30, 48), 3));
+ var eqCap = Caps("TAIL EQ"); eqCap.Margin = new Thickness(0, 0, 0, 3);
+ var left = new Border { Width = 214, BorderBrush = BorderIn, BorderThickness = new Thickness(0, 0, 1, 0), Padding = new Thickness(7, 5),
+ Child = new DockPanel { Children = { Docked(eqCap, Dock.Top), Docked(eqKnobs, Dock.Bottom), new Border { Margin = new Thickness(0, 0, 0, 2), Child = InsetBox(eq) } } } };
+
+ // Modulation
+ var lfo = new ChamberLfoView { Height = 34 };
+ readouts.Add(() => lfo.Tick(Exp(P(ModRate), 0.05, 8), P(ModDepth)));
+ var modGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*"), ColumnSpacing = 4 };
+ modGrid.Children.Add(K(ModRate, "RATE", v => { double hz = Exp(v, 0.05, 8); return hz >= 1 ? FormattableString.Invariant($"{hz:0.0} Hz") : FormattableString.Invariant($"{hz:0.00} Hz"); }, 28, 42, TealC));
+ modGrid.Children.Add(Col(K(ModDepth, "DEPTH", v => Pct(v), 28, 42, TealC), 1));
+ modGrid.Children.Add(Col(new Border { VerticalAlignment = VerticalAlignment.Top, Margin = new Thickness(2, 1, 0, 0), Child = InsetBox(lfo) }, 2));
+ var mod = new StackPanel { Spacing = 2, Children = { Caps("MODULATION"), modGrid } };
+
+ // Shimmer
+ bool ShimDim() => Sel(AlgoMode, 4) != 3;
+ var shimCap = Caps("SHIMMER · PITCH SHIFT");
+ readouts.Add(() => { shimCap.Text = ShimDim() ? "SHIMMER · SHIMMER MODE ONLY" : "SHIMMER · PITCH SHIFT"; shimCap.Foreground = ShimDim() ? DimC : MutedC; });
+ var interval = Row(5, Caps("INTERVAL"), Seg(ShimmerPitch, new[] { "−12", "+7", "+12" }));
+ var shimGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), ColumnSpacing = 6 };
+ shimGrid.Children.Add(K(ShimmerAmount, "AMOUNT", v => Pct(v), 28, 44, ChamberInk.Mauve));
+ shimGrid.Children.Add(Col(new StackPanel { Spacing = 4, VerticalAlignment = VerticalAlignment.Center, Children = { interval, Toggle(ShimmerFeedback, "Feed shimmer back", ShimDim) } }, 1));
+ var shim = Divider(new StackPanel { Spacing = 2, Children = { shimCap, shimGrid } }, 4);
+ shim.Margin = new Thickness(0, 3, 0, 0);
+
+ // EQ position
+ var posHint = Mono("", 7, MutedC); posHint.HorizontalAlignment = HorizontalAlignment.Right;
+ readouts.Add(() => posHint.Text = Sel(EqPosition, 3) switch { 0 => "engine input", 2 => "dry + wet", _ => "wet only" });
+ var posRow = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*"), ColumnSpacing = 6 };
+ posRow.Children.Add(Caps("EQ POSITION")); posRow.Children.Add(Col(Seg(EqPosition, new[] { "Input", "Tail", "Output" }), 1)); posRow.Children.Add(Col(posHint, 2));
+ var pos = Divider(posRow, 4); pos.Margin = new Thickness(0, 3, 0, 0);
+
+ var right = new DockPanel { LastChildFill = false, Margin = new Thickness(7, 5, 7, 3), Children = { Docked(mod, Dock.Top), Docked(shim, Dock.Top), Docked(pos, Dock.Bottom) } };
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*") };
+ g.Children.Add(left); g.Children.Add(Col(right, 1));
+ return g;
+ }
+
+ // ======================================================================
+ // RIGHT — Levels / Output
+ // ======================================================================
+ Control LevelsTab()
+ {
+ Control EngineRow(int onP, string name, bool conv)
+ {
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,30,*"), ColumnSpacing = 6, VerticalAlignment = VerticalAlignment.Center };
+ g.Children.Add(Toggle(onP, ""));
+ g.Children.Add(Col(Caps(name), 1));
+ var bar = HBar(Blend, () => conv ? 1 - P(Blend) : P(Blend), v => Raw(Blend, (float)(conv ? 1 - v : v)),
+ v => ShortDb(ShareDb(v)), conv ? ChamberInk.Slate : Amber, () => !On(onP), 26);
+ ToolTip.SetTip(bar, conv ? "Convolution share of the blend (drags Blend)" : "Algorithm share of the blend (drags Blend)");
+ g.Children.Add(Col(bar, 2));
+ return g;
+ }
+ var route = new Grid { ColumnDefinitions = new ColumnDefinitions("48,*"), VerticalAlignment = VerticalAlignment.Center };
+ route.Children.Add(Caps("ROUTE"));
+ var rseg = Seg(Routing, new[] { "Parallel", "Serial" });
+ ToolTip.SetTip(rseg, "Parallel: both engines hear the input · Serial: the convolution feeds the algorithm");
+ route.Children.Add(Col(rseg, 1));
+ var dry = new Grid { ColumnDefinitions = new ColumnDefinitions("48,*"), VerticalAlignment = VerticalAlignment.Center };
+ dry.Children.Add(Caps("DRY"));
+ dry.Children.Add(Col(HBar(DryLevel, () => P(DryLevel), v => Raw(DryLevel, (float)v), v => ShortDb(DryDb(v)), NotaPalette.BorderStrong, () => On(WetOnly), 26), 1));
+ var duck = SliderRow("DUCKING", DuckAmount, v => FormattableString.Invariant($"{v * 24:0.0}"));
+ var rel = SliderRow("RELEASE", DuckRelease, v => FormattableString.Invariant($"{Exp(v, 20, 2000):0}"));
+ ToolTip.SetTip(duck, "Ducking — the wet dips (up to 24 dB) while the input plays");
+ var btns = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*"), ColumnSpacing = 6, VerticalAlignment = VerticalAlignment.Center };
+ btns.Children.Add(Latch(Freeze, "Freeze", "Freeze — hold the algorithm tail forever; the input is muted"));
+ btns.Children.Add(Col(Latch(FreezeIn, "Hold in", "Hold in — keep feeding the input into the frozen tail (layering)"), 1));
+ var wetBar = new PentadLevelBar { Height = 4, VerticalAlignment = VerticalAlignment.Center };
+ var wetDb = Mono("", 8, TxtC);
+ readouts.Add(() =>
+ {
+ double pk = Sc(S_WetL);
+ wetBar.SetLinear(pk);
+ double db = pk > 1e-5 ? 20 * Math.Log10(pk) : -100;
+ wetDb.Text = ShortDb(db); wetDb.Foreground = db > -6 ? NotaPalette.Warning : TxtC;
+ });
+ var wet = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), ColumnSpacing = 6, VerticalAlignment = VerticalAlignment.Center };
+ wet.Children.Add(Caps("WET")); wet.Children.Add(Col(wetBar, 1)); wet.Children.Add(Col(wetDb, 2));
+ var duckGr = Mono("", 7, MutedC);
+ readouts.Add(() => { double gr = Sc(S_DuckDb); duckGr.Text = gr > 0.05 ? FormattableString.Invariant($"−{gr:0.0}") : ""; });
+
+ var g = new Grid { RowDefinitions = new RowDefinitions("*,*,*,*,Auto,*,*,Auto,*,*") };
+ Control[] rows = { EngineRow(ConvOn, "CONV", true), EngineRow(AlgoOn, "ALGO", false), route, dry,
+ new Border { Height = 1, Background = BorderIn, Margin = new Thickness(0, 2) }, duck, rel,
+ new Border { Height = 1, Background = BorderIn, Margin = new Thickness(0, 2) }, btns, wet };
+ for (int r = 0; r < rows.Length; r++) g.Children.Add(GRow(rows[r], r));
+ return new Border { Padding = new Thickness(8, 4), Child = g };
+ }
+ Control OutputTab()
+ {
+ var meterL = new PentadLevelBar { Vertical = true, Width = 11, Height = 56 };
+ var meterR = new PentadLevelBar { Vertical = true, Width = 11, Height = 56 };
+ readouts.Add(() => { meterL.SetLinear(Sc(S_OutL)); meterR.SetLinear(Sc(S_OutR)); });
+ static Control Center(Control c) { c.HorizontalAlignment = HorizontalAlignment.Center; return c; }
+ var scale = new Grid { RowDefinitions = new RowDefinitions("*,*,*"), Height = 56, Children = { Mono("0", 7, DimC), GRow(Mono("−12", 7, DimC), 1), GRow(Mono("−48", 7, DimC), 2) } };
+ var meters = Row(4, new StackPanel { Spacing = 2, Children = { meterL, Center(Caps("L", MutedC)) } },
+ new StackPanel { Spacing = 2, Children = { meterR, Center(Caps("R", MutedC)) } }, scale);
+ meters.VerticalAlignment = VerticalAlignment.Top;
+ var top = Row(8, K(Output, "OUTPUT", v => Db(-24 + 36 * v), 40, 54), meters);
+ var qual = new Grid { ColumnDefinitions = new ColumnDefinitions("48,*"), VerticalAlignment = VerticalAlignment.Center };
+ qual.Children.Add(Caps("QUALITY"));
+ var qseg = Seg(Quality, new[] { "Eco", "Mid", "High" });
+ ToolTip.SetTip(qseg, "Eco: IR up to 3 s · Mid: 6 s · High: 10 s + cubic-interpolated algorithm modulation");
+ qual.Children.Add(Col(qseg, 1));
+ var mid = new StackPanel { Spacing = 6, Children = {
+ SliderRow("WIDTH", WidthP, v => FormattableString.Invariant($"{v * 200:0}"), 48),
+ SliderRow("MONO f", BassMono, v => v <= 0.001 ? "off" : FormattableString.Invariant($"{Exp(v, 30, 500):0}"), 48),
+ qual } };
+ var wetOnly = Toggle(WetOnly, "Wet only (send)");
+ ToolTip.SetTip(wetOnly, "Wet only — 100 % wet, no dry: for a return / send track");
+ var zl = Toggle(ZeroLatency, "Zero latency");
+ ToolTip.SetTip(zl, "On: exact convolution timing at 0 ms predelay (FIR head, more CPU). Off: lighter — the first block arrives late and is absorbed into the predelay.");
+ var bottom = new StackPanel { Spacing = 5, Children = { wetOnly, zl } };
+ var body = new DockPanel { LastChildFill = false, Children = {
+ Docked(top, Dock.Top),
+ Docked(Divider(mid), Dock.Top),
+ Docked(Divider(bottom), Dock.Bottom) } };
+ ((Control)body.Children[1]).Margin = new Thickness(0, 5, 0, 0);
+ return new Border { Padding = new Thickness(8, 5), Child = body };
+ }
+
+ // ======================================================================
+ // Tab frames
+ // ======================================================================
+ var centreHost = new ContentControl(); var rightHost = new ContentControl();
+ var centreBodies = new Control?[3]; var rightBodies = new Control?[2];
+ int centreTab = 0;
+ var extras = Mono("", 7, MutedC);
+ readouts.Add(() =>
+ {
+ switch (centreTab)
+ {
+ case 0:
+ int ch = (int)Sc(S_IrChannels);
+ string ts = !On(IrTrueStereo) || ch <= 1 ? "stereo" : ch >= 4 ? "true stereo" : "mono-in stereo";
+ extras.Text = Sc(S_KernelSeconds) > 0 ? FormattableString.Invariant($"{ts} · {Sc(S_KernelSeconds):0.0} s IR") : ts;
+ extras.Foreground = MutedC; break;
+ case 1:
+ extras.Text = On(Freeze) ? "FREEZE active" : On(Routing) && On(ConvOn) ? "fed by convolution" : "";
+ extras.Foreground = On(Freeze) ? AmberLit : MutedC; break;
+ default:
+ extras.Text = Sel(EqPosition, 3) switch { 0 => "at the input, before both engines", 2 => "at the output, dry + wet", _ => "on the tail, before Dry/Wet" };
+ extras.Foreground = MutedC; break;
+ }
+ });
+ Control CentreBody(int t) => centreBodies[t] ??= t switch { 1 => AlgoTab(), 2 => EqModTab(), _ => ConvTab() };
+ Control RightBody(int t) => rightBodies[t] ??= t == 1 ? OutputTab() : LevelsTab();
+ var centre = TabFrame(new[] { "Convolution", "Algorithm", "EQ · Mod" }, centreHost, CentreBody, false, t => { centreTab = t; foreach (var a in readouts) a(); }, extras);
+ var rightFrame = TabFrame(new[] { "Levels", "Output" }, rightHost, RightBody, true, _ => { foreach (var a in readouts) a(); }, null);
+ var right = new Border { Width = 186, Background = Panel, BorderBrush = Border2, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(5), ClipToBounds = true, Child = rightFrame };
+ DockPanel.SetDock(right, Dock.Right);
+ var centreBox = new Border { Background = Panel, BorderBrush = Border2, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(5), Margin = new Thickness(5, 0), ClipToBounds = true, Child = centre };
+
+ // ======================================================================
+ // Status strip
+ // ======================================================================
+ var statusLeft = new TextBlock { FontSize = 8, Foreground = Txt2, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };
+ var statusRight = Mono("", 8, Txt2);
+ string StatusText()
+ {
+ float b = P(Blend);
+ string blend = FormattableString.Invariant($"blend {(1 - b) * 100:0} / {b * 100:0}");
+ switch (centreTab)
+ {
+ case 1:
+ string mode = Modes[Sel(AlgoMode, 4)];
+ if (On(Freeze)) return On(FreezeIn) ? FormattableString.Invariant($"Freeze + hold in: the tail layers the input · {mode}") : FormattableString.Invariant($"Freeze: tail held, input muted · {mode} {Secs(RtMid())}");
+ return FormattableString.Invariant($"{mode} · decay {Secs(RtMid())} · size {Exp(P(AlgoSize), 0.4, 2.5) * 100:0} % · predelay {Pre(AlgoPredelay, AlgoSync)}{(On(Routing) ? " · serial" : "")}");
+ case 2:
+ string eqS = FormattableString.Invariant($"tail EQ {LowCutF(P(EqLowCut))} — {HighCutF(P(EqHighCut))}");
+ string shimS = Sel(AlgoMode, 4) == 3 ? FormattableString.Invariant($" · shimmer {Interval()}, {P(ShimmerAmount) * 100:0} %") : "";
+ return FormattableString.Invariant($"{(On(WetOnly) ? "Wet only · " : "")}{eqS}{shimS}");
+ default:
+ int ir = Sel(IrSelect, IrCount);
+ string name = ir < irList.Count ? irList[ir].Name : engine.DeviceText(track, di, 2) is { Length: > 0 } u ? u : "no user IR";
+ return FormattableString.Invariant($"{name} · {blend} · predelay {Pre(ConvPredelay, ConvSync)}");
+ }
+ }
+ readouts.Add(() =>
+ {
+ statusLeft.Text = StatusText();
+ statusLeft.Foreground = centreTab == 1 && On(Freeze) ? AmberLit : Txt2;
+ double sr = Sc(S_SampleRate), lat = Sc(S_Latency);
+ string latS = lat > 0 ? FormattableString.Invariant($"conv +{lat:0} smp (in predelay)") : "latency 0 smp";
+ statusRight.Text = sr > 0 ? FormattableString.Invariant($"{sr / 1000:0.#} kHz · {latS} · CPU {Sc(S_Cpu) * 100:0.0} %") : "";
+ });
+ var statusGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 8 };
+ statusGrid.Children.Add(statusLeft); statusGrid.Children.Add(Col(statusRight, 1));
+ var status = new Border { Height = 18, Background = Inset, BorderBrush = Border2, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(8, 0), Child = statusGrid };
+ DockPanel.SetDock(status, Dock.Bottom);
+
+ // ---- assemble ---------------------------------------------------------------
+ var bodyRow = new DockPanel { LastChildFill = true, Margin = new Thickness(5), Children = { blendCol, right, centreBox } };
+ var root = new DockPanel { LastChildFill = true, Background = RailBg, Children = { status, bodyRow } };
+
+ void Refresh()
+ {
+ scN = engine.DeviceScope(track, di, scope, kScope);
+ foreach (var a in readouts) a();
+ }
+ ctx.AddDeviceRefresher(Refresh);
+ Refresh();
+ return root;
+
+ // local: a tab frame (bar + swapping body), optional extras on the right of the bar.
+ Control TabFrame(string[] tabs, ContentControl host, Func<int, Control> body, bool centered, Action<int>? changed, Control? extrasCtl)
+ {
+ int sel = 0; var btns = new Border[tabs.Length];
+ void Hi()
+ {
+ for (int i = 0; i < tabs.Length; i++)
+ {
+ bool on = i == sel;
+ btns[i].Background = on ? TabBg : Brushes.Transparent; btns[i].BorderBrush = on ? Amber : Brushes.Transparent;
+ var tb = (TextBlock)btns[i].Child!; tb.Foreground = on ? AmberLit : MutedC; tb.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;
+ }
+ }
+ var bar = centered ? (Avalonia.Controls.Panel)new UniformGrid { Rows = 1 } : new StackPanel { Orientation = Orientation.Horizontal };
+ for (int i = 0; i < tabs.Length; i++)
+ {
+ int iv = i;
+ var b = new Border { Padding = new Thickness(9, 0), BorderThickness = new Thickness(0, 0, 0, 2), BorderBrush = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand),
+ Child = new TextBlock { Text = tabs[i], FontSize = 9, Foreground = MutedC, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center } };
+ b.PointerPressed += (_, _) => { sel = iv; Hi(); host.Content = body(iv); changed?.Invoke(iv); };
+ btns[i] = b; bar.Children.Add(b);
+ }
+ var barDock = new DockPanel { Height = 20, LastChildFill = centered };
+ if (extrasCtl != null) { var ex = new Border { Padding = new Thickness(0, 0, 8, 0), Child = extrasCtl }; DockPanel.SetDock(ex, Dock.Right); barDock.Children.Add(ex); }
+ if (!centered) DockPanel.SetDock(bar, Dock.Left);
+ barDock.Children.Add(bar);
+ var barBorder = new Border { BorderBrush = Border2, BorderThickness = new Thickness(0, 0, 0, 1), Child = barDock };
+ DockPanel.SetDock(barBorder, Dock.Top);
+ Hi(); host.Content = body(sel);
+ return new DockPanel { LastChildFill = true, Children = { barBorder, host } };
+ }
+ }
+}
diff --git a/src/managed/Nota.App/DeviceCards/DeviceCardFactory.cs b/src/managed/Nota.App/DeviceCards/DeviceCardFactory.cs
index b773fbeb..ed70401b 100644
--- a/src/managed/Nota.App/DeviceCards/DeviceCardFactory.cs
+++ b/src/managed/Nota.App/DeviceCards/DeviceCardFactory.cs
@@ -38,6 +38,7 @@ internal sealed class DeviceCardFactory
[17] = new ForgeDeviceBody(),
[18] = new AutoGainDeviceBody(),
[19] = new ShutterDeviceBody(),
+ [20] = new ChamberDeviceBody(),
};
/// <summary>Resolve the body for a device: -1 = hosted plugin, a mapped built-in kind,
diff --git a/src/managed/Nota.App/DeviceCards/IDeviceBody.cs b/src/managed/Nota.App/DeviceCards/IDeviceBody.cs
index dd4b583e..9bda3741 100644
--- a/src/managed/Nota.App/DeviceCards/IDeviceBody.cs
+++ b/src/managed/Nota.App/DeviceCards/IDeviceBody.cs
@@ -24,5 +24,9 @@ internal interface IDeviceBody
/// and the shell wraps it with no inset. Default false = the shell pads the body 8px.</summary>
bool FullBleed => false;
+ /// <summary>Tag shown after the device name in the shared header (e.g. "HYBRID");
+ /// null = the default "BUILT-IN".</summary>
+ string? Subtitle => null;
+
Control Build(DeviceCardContext ctx, int deviceIndex);
}
diff --git a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs
index 81c1347b..66bc327c 100644
--- a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs
+++ b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs
@@ -25,8 +25,8 @@ namespace Nota.App;
internal sealed class RackCardView(DeviceCardContext ctx)
{
- private static readonly string[] RackDeviceNames = { "Nota EQ-3", "Nota EQ-8", "Nota Dynamic EQ-8", "Nota Compressor", "Nota Reverb", "Nota Delay", "Nota Utility", "Nota Level", "Nota Ceiling", "Nota Shutter", "Nota Valve", "Nota Auto Filter", "Nota Vintage", "Nota Forge", "Nota Crush", "Nota Orbit", "Nota Auto Shift", "Nota Beat Repeat", "Nota Strata" };
- private static readonly int[] RackDeviceKinds = { 16, 0, 13, 1, 2, 3, 4, 18, 14, 19, 6, 7, 8, 17, 12, 9, 10, 11, 15 };
+ private static readonly string[] RackDeviceNames = { "Nota EQ-3", "Nota EQ-8", "Nota Dynamic EQ-8", "Nota Compressor", "Nota Reverb", "Nota Chamber", "Nota Delay", "Nota Utility", "Nota Level", "Nota Ceiling", "Nota Shutter", "Nota Valve", "Nota Auto Filter", "Nota Vintage", "Nota Forge", "Nota Crush", "Nota Orbit", "Nota Auto Shift", "Nota Beat Repeat", "Nota Strata" };
+ private static readonly int[] RackDeviceKinds = { 16, 0, 13, 1, 2, 20, 3, 4, 18, 14, 19, 6, 7, 8, 17, 12, 9, 10, 11, 15 };
private static readonly IBrush RowSel = new SolidColorBrush(Color.FromArgb(0x22, 0xD8, 0xA0, 0x3D)); // selected chain wash
private readonly DeviceCardContext _ctx = ctx;
@@ -2088,6 +2088,8 @@ internal class RackChainDeviceEngineProxy : System.Reflection.DispatchProxy
case nameof(Nota.Application.IAudioEngine.DeviceBypassed): return Access.ChainDeviceBypassed(Chain, Dev);
case nameof(Nota.Application.IAudioEngine.SetDeviceBypassed): Access.SetChainDeviceBypassed(Chain, Dev, (bool)args![2]!); return null;
case nameof(Nota.Application.IAudioEngine.DeviceGainReduction): return 0f;
+ case nameof(Nota.Application.IAudioEngine.DeviceLoadFile): return false; // chain devices keep params only
+ case nameof(Nota.Application.IAudioEngine.DeviceText): return "";
case nameof(Nota.Application.IAudioEngine.DeviceAcceptsSidechain): return false;
case nameof(Nota.Application.IAudioEngine.DeviceSidechainSource): return -1;
case nameof(Nota.Application.IAudioEngine.DeviceSidechainGain): return 0f;
diff --git a/src/managed/Nota.App/DeviceChainView.cs b/src/managed/Nota.App/DeviceChainView.cs
index 117fb45c..3d42cb09 100644
--- a/src/managed/Nota.App/DeviceChainView.cs
+++ b/src/managed/Nota.App/DeviceChainView.cs
@@ -155,11 +155,11 @@ public sealed partial class DeviceChainView : UserControl
int kind = _engine.TrackDeviceBuiltinKind(_trackId, index);
bool bypassed = _engine.DeviceBypassed(_trackId, index);
string name = _engine.DeviceName(_trackId, index);
- string tag = kind >= 0 ? "BUILT-IN" : "PLUGIN";
Control body;
double width;
bool fullBleed = false;
+ string tag = kind >= 0 ? "BUILT-IN" : "PLUGIN";
if (kind == 5) // Audio Effect Rack — full-bleed body (fills the shell; no 8px inset
{ // that would overflow its fixed width and skew hit-testing).
body = new RackCardView(NewCardContext()).BuildEffectRackBody(index); width = 700; fullBleed = true;
@@ -170,6 +170,7 @@ public sealed partial class DeviceChainView : UserControl
body = strategy.Build(NewCardContext(), index);
width = strategy.AutoWidth ? double.NaN : strategy.Width; // NaN → card sizes to content
fullBleed = strategy.FullBleed;
+ if (strategy.Subtitle is { } sub) tag = sub;
}
// Effects share the same shell as instruments (bypass + reorder + remove + preset,
// and the rich chrome when wide enough). Non-full-bleed bodies get an 8px inset.
diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.cs
index 86764179..9785e591 100644
--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs
+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs
@@ -366,6 +366,12 @@ public interface IAudioEngine : IDisposable
/// empty for param-only devices.</summary>
byte[] DeviceGetState(int trackId, int deviceIndex);
void DeviceSetState(int trackId, int deviceIndex, byte[] data);
+ /// <summary>Load an auxiliary audio file into a device (Nota Chamber: a user impulse
+ /// response — WAV / FLAC / MP3, mono, stereo or 4-channel true stereo). False if unsupported.</summary>
+ bool DeviceLoadFile(int trackId, int deviceIndex, string path);
+ /// <summary>A device's resource text (Nota Chamber: 0 IR name, 1 IR category, 2 user IR
+ /// name, 10 the built-in IR list as "name\tcategory\tseconds" lines); "" when none.</summary>
+ string DeviceText(int trackId, int deviceIndex, int id);
/// <summary>Sidechain routing: point a device's detector at another track's signal (-1 clears).</summary>
void SetDeviceSidechainSource(int trackId, int deviceIndex, int sourceTrackId);
int DeviceSidechainSource(int trackId, int deviceIndex);
diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs
index fe477cd6..b0423b8c 100644
--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs
@@ -79,6 +79,10 @@ internal static partial class NativeMethods
internal static partial int DeviceGetState(IntPtr engine, int trackId, int deviceIndex, [Out] byte[]? outBytes, int cap);
[LibraryImport(Lib, EntryPoint = "nota_device_set_state")]
internal static partial void DeviceSetState(IntPtr engine, int trackId, int deviceIndex, [In] byte[] data, int size);
+ [LibraryImport(Lib, EntryPoint = "nota_device_load_file", StringMarshalling = StringMarshalling.Utf8)]
+ internal static partial NotaResult DeviceLoadFile(IntPtr engine, int trackId, int deviceIndex, string path);
+ [LibraryImport(Lib, EntryPoint = "nota_device_text")]
+ internal static partial int DeviceText(IntPtr engine, int trackId, int deviceIndex, int id, [Out] byte[]? outBytes, int cap);
// --- MIDI effects ---
[LibraryImport(Lib, EntryPoint = "nota_track_add_midi_effect")]
diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs
index a95bbd3c..d931e97c 100644
--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs
@@ -119,6 +119,17 @@ public sealed partial class NotaEngine
}
public void DeviceSetState(int trackId, int deviceIndex, byte[] data)
{ ThrowIfDisposed(); if (data is { Length: > 0 }) NativeMethods.DeviceSetState(_handle, trackId, deviceIndex, data, data.Length); }
+ public bool DeviceLoadFile(int trackId, int deviceIndex, string path)
+ { ThrowIfDisposed(); return NativeMethods.DeviceLoadFile(_handle, trackId, deviceIndex, path) == NativeMethods.NotaResult.Ok; }
+ public string DeviceText(int trackId, int deviceIndex, int id)
+ {
+ ThrowIfDisposed();
+ int n = NativeMethods.DeviceText(_handle, trackId, deviceIndex, id, null, 0);
+ if (n <= 0) return "";
+ var buf = new byte[n + 1];
+ NativeMethods.DeviceText(_handle, trackId, deviceIndex, id, buf, buf.Length);
+ return System.Text.Encoding.UTF8.GetString(buf, 0, n);
+ }
// --- MIDI effects ---
public int AddMidiEffect(int trackId, int kind) { ThrowIfDisposed(); return NativeMethods.AddMidiEffect(_handle, trackId, kind); }
diff --git a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
index 72c84ff2..cec68d05 100644
--- a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
@@ -307,6 +307,46 @@ public sealed class FactoryPresetCatalog : IFactoryPresets
Fx("shutter", 19, "Kick Duck", ("Threshold", 0.42f), ("Flip", 1f), ("Attack", 0.2f), ("Hold", 0.5f), ("Release", 0.55f), ("Floor", 0.55f));
Fx("shutter", 19, "Trance Gate", ("Threshold", 0.55f), ("Return", 0.08f), ("Attack", 0.15f), ("Hold", 0.45f), ("Release", 0.4f), ("Floor", 0f), ("Lookahead", 1f));
+ // ---- Nota Chamber (kind 20) — hybrid reverb, all params normalized 0..1 (unnamed params
+ // reset to their defaults). IR = index/16 (0 Concert Hall · .0625 Stone Vault · .125
+ // Cathedral · .1875 Scoring Stage · .25 Wood Chamber · .3125 Live Room · .375 Drum Room ·
+ // .4375 Tiled Bathroom · .5 Vocal Plate · .5625 Bright Plate · .625 Spring Tank · .6875
+ // Car Park · .75 Stairwell · .8125 Forest · .875 Gated Room · .9375 Metal Tank · 1 user).
+ // Blend = algorithm share; Algo Mode 0 Dark Hall/.333 Plate/.667 Quartz/1 Shimmer;
+ // Algo Decay 0.2·100^v s; predelays 500·v² ms; IR Size 0.5·4^v; Algo Size 0.4·6.25^v;
+ // Damping 500·36^v Hz; Low/High Decay ×0.25·16^v; EQ Low Cut 20·100^v, High Cut 1k·20^v,
+ // gains (v−.5)·36 dB; Duck Amount v·24 dB; Output −24+36·v dB; Width v·200 %.
+ Fx("chamber", 20, "Stone Vault", ("IR", 0.0625f), ("Blend", 0.62f), ("Dry/Wet", 0.42f), ("Conv Predelay", 0.219f), ("IR Size", 0.619f), ("IR Attack", 0.19f), ("IR Decay", 0.74f),
+ ("Algo Decay", 0.681f), ("Algo Size", 0.405f), ("Algo Diffusion", 0.62f), ("Algo Damping", 0.518f), ("Algo Predelay", 0.268f), ("Algo Low Decay", 0.595f), ("Algo High Decay", 0.235f),
+ ("Duck Amount", 0.142f), ("Duck Release", 0.602f), ("EQ Low Cut", 0.389f), ("EQ High Cut", 0.8f));
+ Fx("chamber", 20, "Concert Hall", ("IR", 0f), ("Blend", 0.45f), ("Dry/Wet", 0.3f), ("Conv Predelay", 0.2f), ("Algo Decay", 0.6f), ("Algo Size", 0.6f), ("Algo Damping", 0.65f), ("EQ Low Cut", 0.301f));
+ Fx("chamber", 20, "Cathedral Wash", ("IR", 0.125f), ("Blend", 0.35f), ("Dry/Wet", 0.45f), ("Conv Predelay", 0.3f), ("IR Size", 0.6f), ("Algo Decay", 0.8f), ("Algo Size", 0.878f),
+ ("Algo Diffusion", 0.85f), ("Algo Damping", 0.45f), ("Algo Low Decay", 0.646f), ("Mod Depth", 0.45f), ("Width", 0.7f));
+ Fx("chamber", 20, "Scoring Stage", ("IR", 0.1875f), ("Blend", 0.3f), ("Dry/Wet", 0.25f), ("Conv Predelay", 0.141f), ("Algo Decay", 0.5f), ("Algo Size", 0.55f));
+ Fx("chamber", 20, "Wood Chamber", ("IR", 0.25f), ("Blend", 0.25f), ("Dry/Wet", 0.25f), ("Conv Predelay", 0.1f), ("Algo Mode", 0.667f), ("Algo Decay", 0.4f), ("Algo Size", 0.3f));
+ Fx("chamber", 20, "Drum Room", ("IR", 0.375f), ("Blend", 0.1f), ("Dry/Wet", 0.22f), ("Conv Predelay", 0f), ("Algo Decay", 0.3f), ("EQ Low Cut", 0.437f), ("Duck Amount", 0.2f), ("Duck Release", 0.4f));
+ Fx("chamber", 20, "Live Room", ("IR", 0.3125f), ("Blend", 0.2f), ("Dry/Wet", 0.2f), ("Algo Decay", 0.35f), ("EQ Low Cut", 0.5f), ("EQ High Cut", 0.8f));
+ Fx("chamber", 20, "Vocal Plate", ("IR", 0.5f), ("Blend", 0.5f), ("Dry/Wet", 0.28f), ("Conv Predelay", 0.245f), ("Algo Mode", 0.333f), ("Algo Decay", 0.5f), ("Algo Size", 0.45f),
+ ("Algo Diffusion", 0.8f), ("Algo Damping", 0.8f), ("Algo High Decay", 0.45f), ("Algo Predelay", 0.245f), ("EQ Low Cut", 0.5f), ("Duck Amount", 0.25f), ("Duck Release", 0.477f));
+ Fx("chamber", 20, "Snare Plate", ("IR", 0.5625f), ("Blend", 0.55f), ("Dry/Wet", 0.3f), ("Algo Mode", 0.333f), ("Algo Decay", 0.42f), ("Algo Damping", 0.85f), ("EQ Low Cut", 0.588f));
+ Fx("chamber", 20, "Spring Box", ("IR", 0.625f), ("Blend", 0f), ("Algo On", 0f), ("Dry/Wet", 0.3f), ("EQ Low Cut", 0.5f), ("EQ High Cut", 0.6f));
+ Fx("chamber", 20, "Wide Shimmer", ("IR", 0.125f), ("Blend", 0.48f), ("Dry/Wet", 0.55f), ("Algo Mode", 1f), ("Algo Decay", 0.8f), ("Algo Diffusion", 0.9f),
+ ("Mod Rate", 0.419f), ("Mod Depth", 0.38f), ("Shimmer Amount", 0.52f), ("Shimmer Pitch", 1f), ("Shimmer Feedback", 1f),
+ ("EQ Low Cut", 0.389f), ("EQ Low Gain", 0.389f), ("EQ High Shelf", 0.589f), ("EQ High Cut", 0.8f), ("Width", 0.64f), ("Bass Mono", 0.548f), ("Output", 0.611f));
+ Fx("chamber", 20, "Octave Down Bloom", ("Blend", 1f), ("Conv On", 0f), ("Dry/Wet", 0.45f), ("Algo Mode", 1f), ("Algo Decay", 0.75f), ("Shimmer Amount", 0.45f), ("Shimmer Pitch", 0f),
+ ("Shimmer Feedback", 0f), ("Algo Damping", 0.45f), ("Mod Depth", 0.4f));
+ Fx("chamber", 20, "Endless Pad", ("Blend", 1f), ("Conv On", 0f), ("Dry/Wet", 0.5f), ("Algo Mode", 1f), ("Algo Decay", 1f), ("Algo Size", 0.8f), ("Algo Diffusion", 0.9f),
+ ("Shimmer Amount", 0.6f), ("Mod Depth", 0.5f), ("Width", 0.75f), ("EQ Low Cut", 0.5f));
+ Fx("chamber", 20, "Reverse Swell", ("IR", 0.0625f), ("IR Reverse", 1f), ("IR Decay", 0.55f), ("Blend", 0.15f), ("Dry/Wet", 0.4f), ("Conv Predelay", 0f), ("Algo Decay", 0.5f));
+ Fx("chamber", 20, "Car Park", ("IR", 0.6875f), ("Blend", 0.3f), ("Dry/Wet", 0.3f), ("Algo Mode", 0.667f), ("Algo Decay", 0.62f));
+ Fx("chamber", 20, "Forest Echoes", ("IR", 0.8125f), ("Blend", 0.2f), ("Dry/Wet", 0.3f), ("Algo Mode", 0.667f), ("Algo Decay", 0.45f), ("Algo Diffusion", 0.3f));
+ Fx("chamber", 20, "Gated Snare", ("IR", 0.875f), ("Blend", 0f), ("Algo On", 0f), ("Dry/Wet", 0.35f), ("EQ Low Cut", 0.5f));
+ Fx("chamber", 20, "Metal Tank", ("IR", 0.9375f), ("Blend", 0.2f), ("Dry/Wet", 0.3f), ("IR Size", 0.4f));
+ Fx("chamber", 20, "Vintage Hall", ("Blend", 0.85f), ("Dry/Wet", 0.3f), ("Algo Vintage", 1f), ("Algo Decay", 0.65f), ("Mod Rate", 0.55f), ("Mod Depth", 0.5f), ("EQ High Cut", 0.694f));
+ Fx("chamber", 20, "Ducked Vocal Hall", ("IR", 0.1875f), ("Blend", 0.55f), ("Dry/Wet", 0.35f), ("Conv Predelay", 0.3f), ("Algo Decay", 0.62f), ("Duck Amount", 0.375f), ("Duck Release", 0.548f));
+ Fx("chamber", 20, "Send · Big Hall", ("IR", 0f), ("Blend", 0.5f), ("Wet Only", 1f), ("Conv Predelay", 0.2f), ("Algo Decay", 0.65f), ("EQ Low Cut", 0.437f), ("EQ High Cut", 0.8f), ("Bass Mono", 0.548f));
+ Fx("chamber", 20, "Send · Plate", ("IR", 0.5f), ("Blend", 0.5f), ("Wet Only", 1f), ("Algo Mode", 0.333f), ("Algo Decay", 0.5f), ("Conv Predelay", 0.2f), ("Algo Predelay", 0.2f), ("EQ Low Cut", 0.5f));
+
// ---- Compressor (kind 1) — Thresh -60..0, Ratio 1..20, Attack .1..100 ms, Release 5..1000 ms, Makeup 0..24 dB
// Character: Clean 0 / Glue 1 / Punch 2 / Opto 3 / FET 4.
Fx("comp", 1, "Drum Glue", ("Character", 1f), ("Thresh", -18f), ("Ratio", 3f), ("Attack", 30f), ("Release", 200f), ("Knee", 8f), ("AutoGain", 1f), ("Mix", 100f));
diff --git a/src/managed/Nota.Infrastructure/Persistence/PresetService.cs b/src/managed/Nota.Infrastructure/Persistence/PresetService.cs
index b3f78e64..25042124 100644
--- a/src/managed/Nota.Infrastructure/Persistence/PresetService.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/PresetService.cs
@@ -234,9 +234,12 @@ public static class PresetService
int pc = engine.DeviceParamCount(trackId, deviceIndex);
if (doc.NamedParams is { Count: > 0 })
{
+ // A param the preset doesn't name goes back to its default (like instruments),
+ // so switching presets never inherits leftovers from the previous one.
for (int i = 0; i < pc; i++)
- if (doc.NamedParams.TryGetValue(engine.DeviceParamName(trackId, deviceIndex, i), out var v))
- engine.DeviceSetParam(trackId, deviceIndex, i, v);
+ engine.DeviceSetParam(trackId, deviceIndex, i,
+ doc.NamedParams.TryGetValue(engine.DeviceParamName(trackId, deviceIndex, i), out var v)
+ ? v : engine.DeviceParamDefault(trackId, deviceIndex, i));
}
else
{
diff --git a/src/managed/Nota.Mcp/Tools/DeviceTools.cs b/src/managed/Nota.Mcp/Tools/DeviceTools.cs
index aad3ed34..8bc74294 100644
--- a/src/managed/Nota.Mcp/Tools/DeviceTools.cs
+++ b/src/managed/Nota.Mcp/Tools/DeviceTools.cs
@@ -19,7 +19,7 @@ public sealed class DeviceTools(IAudioEngine engine, IEngineDispatch dispatch, I
(0, "EQ-8"), (1, "Compressor"), (2, "Reverb"), (3, "Delay"), (4, "Utility"), (5, "Effect Rack"),
(6, "Nota Valve"), (7, "Auto Filter"), (8, "Nota Vintage"), (9, "Nota Orbit"), (10, "Auto Shift"),
(11, "Beat Repeat"), (12, "Crush"), (13, "Dynamic EQ-8"), (14, "Ceiling"), (15, "Strata"),
- (16, "EQ-3"), (17, "Forge"), (18, "Nota Level"), (19, "Nota Shutter"),
+ (16, "EQ-3"), (17, "Forge"), (18, "Nota Level"), (19, "Nota Shutter"), (20, "Nota Chamber"),
};
public sealed record DeviceKind(int Kind, string Name);
@@ -62,4 +62,10 @@ public sealed class DeviceTools(IAudioEngine engine, IEngineDispatch dispatch, I
[McpServerTool(Name = "set_device_param"), Description("Set a device parameter by index (value is in the param's own min..max range from get_device_params).")]
public Task SetDeviceParam(int trackId, int deviceIndex, int paramIndex, float value) => Mutate(() => E.DeviceSetParam(trackId, deviceIndex, paramIndex, value));
+
+ [McpServerTool(Name = "load_device_file"), Description("Load an audio file into a device that takes one — Nota Chamber: a user impulse response (WAV / FLAC / MP3; mono, stereo or 4-channel true stereo), which also selects it. Returns true on success.")]
+ public Task<bool> LoadDeviceFile(int trackId, int deviceIndex, [Description("Absolute path to the audio file")] string path) => Mutate(() => E.DeviceLoadFile(trackId, deviceIndex, path));
+
+ [McpServerTool(Name = "get_device_text"), Description("Read a device's resource text. Nota Chamber: id 0 = current IR name, 1 = its category, 2 = the loaded user IR's name, 10 = the built-in IR list (name, category, seconds per line; the IR param selects entry round(v × 16), 1.0 = the user IR).")]
+ public Task<string> GetDeviceText(int trackId, int deviceIndex, int id) => Read(() => E.DeviceText(trackId, deviceIndex, id));
}
diff --git a/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs b/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs
index 8e425a02..9b380bae 100644
--- a/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs
+++ b/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs
@@ -202,6 +202,7 @@ public sealed partial class BrowserViewModel : ObservableObject
new() { Name = "Nota EQ-8", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 0, Sub = "8-band EQ" },
new() { Name = "Nota Compressor", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 1, Sub = "built-in" },
new() { Name = "Nota Reverb", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 2, Sub = "built-in" },
+ new() { Name = "Nota Chamber", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 20, Sub = "hybrid reverb" },
new() { Name = "Nota Delay", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 3, Sub = "built-in" },
new() { Name = "Nota Utility", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 4, Sub = "built-in" },
new() { Name = "Nota Level", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 18, Sub = "gain" },
diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.h
index ea448fa6..f59b5bec 100644
--- a/src/native/nota.engine/include/nota/nota_engine.h
+++ b/src/native/nota.engine/include/nota/nota_engine.h
@@ -827,6 +827,11 @@ NOTA_API int32_t nota_device_layer_wave(const NotaEngine* engine, int32_t tr
* probe the size first); set restores from data. Empty for param-only devices. */
NOTA_API int32_t nota_device_get_state(const NotaEngine* engine, int32_t track_id, int32_t device_index, uint8_t* out, int32_t cap);
NOTA_API void nota_device_set_state(NotaEngine* engine, int32_t track_id, int32_t device_index, const uint8_t* data, int32_t size);
+/* Load an auxiliary audio file into a device (Nota Chamber: a user impulse response). */
+NOTA_API NotaResult nota_device_load_file(NotaEngine* engine, int32_t track_id, int32_t device_index, const char* path);
+/* A device's resource text (Chamber: 0 IR name, 1 category, 2 user IR name, 10 built-in IR list).
+ Returns the full UTF-8 length; copies up to cap-1 bytes + NUL when out is non-null. */
+NOTA_API int32_t nota_device_text(const NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t id, char* out, int32_t cap);
/* Sidechain routing (Phase B): point a device's detector at another track's signal.
* source_track_id -1 clears it; get returns the current source (-1 = none). */
NOTA_API void nota_device_set_sidechain_source(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t source_track_id);
diff --git a/src/native/nota.engine/src/Chamber.h b/src/native/nota.engine/src/Chamber.h
new file mode 100644
index 00000000..565b6d0b
--- /dev/null
+++ b/src/native/nota.engine/src/Chamber.h
@@ -0,0 +1,1618 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Chamber (device kind 20, mockup "Nota Chamber") — a hybrid reverb: a convolution
+// engine and an algorithmic engine side by side, crossfaded by Blend (in parallel, or with
+// the convolution feeding the algorithm in Serial).
+//
+// · Convolution — sixteen procedurally synthesised impulse responses (halls, rooms,
+// plates, a spring, spaces, FX) or a user file (WAV / FLAC / MP3; mono, stereo or 4-ch
+// true stereo), shaped by Start / Decay trims, an Attack fade-in, Size (time-stretch),
+// Reverse and True Stereo. The engine is zero-latency: a 64-tap direct FIR head, a
+// 64-sample uniformly partitioned stage up to one big block, then big-block partitions
+// for the rest (overlap-add over a frequency-domain delay line). Shaping an IR rebuilds
+// its partitions on a worker thread; on the audio thread the new kernel inherits the
+// input history (which doesn't depend on the IR) and crossfades in, so the whole tail
+// morphs without a click. With Zero Latency off the head stages are skipped (less CPU)
+// and the big block's delay is absorbed into the convolution pre-delay.
+// · Algorithm — Dark Hall / Plate / Quartz / Shimmer: an 8-line feedback delay network
+// (Householder feedback) behind a 4-stage Hadamard diffuser, with per-line three-band
+// decay (low / mid / high RT60 around a 250 Hz and a Damping crossover), modulated
+// fractional delays, Freeze (a lossless loop, input muted unless Freeze In), a Vintage
+// colour and a two-grain pitch shifter (Shimmer — fed back into the loop or on top).
+// · Around them: separate pre-delays (free or tempo-synced), a 4-band EQ placed at the
+// input / on the tail / at the output, width + bass mono, input-keyed ducking of the
+// wet signal, Dry/Wet with a dry level, a wet-only (send) switch and output gain.
+//
+// Params are normalized 0..1 (denormalized in process()); persistence / automation / clone
+// flow generically through the base Device, and a user IR's PCM travels in the state blob.
+// process() never allocates or locks: kernels arrive through an atomic hand-off and go back
+// to the worker thread through a lock-free ring to be freed there.
+
+#pragma once
+
+#include "AudioFile.h"
+#include "Device.h"
+
+#include "signalsmith-linear/fft.h"
+
+#include <algorithm>
+#include <array>
+#include <atomic>
+#include <chrono>
+#include <cmath>
+#include <condition_variable>
+#include <cstdint>
+#include <cstdio>
+#include <cstring>
+#include <memory>
+#include <mutex>
+#include <string>
+#include <thread>
+#include <vector>
+
+namespace nota {
+namespace chamber {
+
+constexpr double kPi = 3.14159265358979323846;
+
+struct Rng {
+ uint32_t s;
+ explicit Rng(uint32_t seed) : s(seed ? seed : 0x9E3779B9u) {}
+ uint32_t next() { s ^= s << 13; s ^= s >> 17; s ^= s << 5; return s; }
+ float uni() { return static_cast<float>(next() >> 8) * (1.0f / 16777216.0f); } // [0, 1)
+ float bi() { return uni() * 2.0f - 1.0f; } // [-1, 1)
+};
+
+inline double expMap(double v, double lo, double hi) { return lo * std::pow(hi / lo, std::clamp(v, 0.0, 1.0)); }
+inline float onePole(double hz, double sr) { return static_cast<float>(1.0 - std::exp(-2.0 * kPi * std::clamp(hz, 1.0, sr * 0.49) / sr)); }
+inline float flush(float x) { return std::fabs(x) < 1e-20f ? 0.0f : x; }
+// Transparent below |1|, a tanh knee above (the wet safety net).
+inline float softClip(float x) {
+ const float a = std::fabs(x);
+ if (a <= 1.0f) return x;
+ const float y = 1.0f + 0.6f * std::tanh((a - 1.0f) / 0.6f);
+ return x < 0.0f ? -y : y;
+}
+// Loop guard: identity in the normal range, bounded when shimmer / freeze-in overdrives it.
+inline float loopLimit(float x) {
+ const float a = std::fabs(x);
+ if (a <= 2.0f) return x;
+ const float y = 2.0f + std::tanh(a - 2.0f);
+ return x < 0.0f ? -y : y;
+}
+
+// ============================================================================
+// Impulse responses
+// ============================================================================
+
+struct SourceIr {
+ std::vector<float> data; // interleaved, `channels` per frame
+ int channels = 0;
+ int64_t frames = 0;
+ double sampleRate = 48000.0;
+ std::string name, category;
+ float seconds() const { return sampleRate > 0.0 ? static_cast<float>(frames / sampleRate) : 0.0f; }
+};
+
+enum IrType { IrRoom = 0, IrPlate, IrSpring, IrGated, IrMetal, IrOutdoor };
+
+struct IrSpec {
+ const char* name; const char* category;
+ float length; // generated length (s)
+ float rtLow, rtMid, rtHigh; // RT60 (s) around 125 Hz / 1 kHz / 8 kHz
+ float erSpan; int erCount; // early reflections: window (ms), count
+ float buildup; // echo-density build-up (ms)
+ float bright; // overall high cut (Hz)
+ float cross; // true-stereo cross-feed gain (LR / RL)
+ float flutter; // flutter-echo period (ms), 0 = none
+ int type; uint32_t seed;
+};
+
+constexpr int kNumBuiltinIrs = 16;
+
+inline const IrSpec& irSpec(int i) {
+ static const IrSpec specs[kNumBuiltinIrs] = {
+ { "Concert Hall · Wide", "HALL", 2.6f, 2.9f, 2.4f, 1.3f, 90.f, 18, 70.f, 12000.f, 0.55f, 0.f, IrRoom, 11 },
+ { "Stone Vault", "HALL", 4.4f, 4.8f, 3.8f, 1.5f, 120.f, 14, 110.f, 7000.f, 0.60f, 0.f, IrRoom, 23 },
+ { "Cathedral", "HALL", 7.5f, 7.8f, 6.4f, 2.6f, 170.f, 12, 170.f, 9000.f, 0.65f, 0.f, IrRoom, 37 },
+ { "Scoring Stage", "HALL", 2.3f, 2.1f, 1.8f, 1.1f, 70.f, 20, 50.f, 14000.f, 0.50f, 0.f, IrRoom, 41 },
+ { "Wood Chamber", "ROOM", 1.6f, 1.5f, 1.2f, 0.7f, 40.f, 16, 25.f, 11000.f, 0.45f, 0.f, IrRoom, 53 },
+ { "Live Room", "ROOM", 1.0f, 0.8f, 0.7f, 0.45f, 30.f, 14, 18.f, 13000.f, 0.40f, 0.f, IrRoom, 61 },
+ { "Drum Room", "ROOM", 0.8f, 0.6f, 0.5f, 0.35f, 22.f, 18, 10.f, 15000.f, 0.40f, 0.f, IrRoom, 67 },
+ { "Tiled Bathroom", "ROOM", 1.3f, 1.0f, 1.1f, 0.9f, 12.f, 20, 6.f, 16000.f, 0.35f, 7.f, IrRoom, 71 },
+ { "Vocal Plate", "PLATE", 2.8f, 2.2f, 2.4f, 1.8f, 0.f, 0, 3.f, 16000.f, 0.70f, 0.f, IrPlate, 79 },
+ { "Bright Plate", "PLATE", 2.0f, 1.3f, 1.6f, 1.5f, 0.f, 0, 2.f, 18000.f, 0.70f, 0.f, IrPlate, 83 },
+ { "Spring Tank", "SPRING", 2.6f, 2.0f, 2.2f, 1.2f, 0.f, 0, 0.f, 5200.f, 0.30f, 0.f, IrSpring, 89 },
+ { "Car Park", "SPACE", 3.6f, 3.2f, 2.9f, 1.5f, 80.f, 10, 60.f, 9000.f, 0.50f, 21.f, IrRoom, 97 },
+ { "Stairwell", "SPACE", 3.2f, 2.6f, 2.7f, 1.9f, 60.f, 24, 40.f, 12000.f, 0.45f, 13.f, IrRoom, 101 },
+ { "Forest Clearing", "OUTDOOR", 2.0f, 1.0f, 1.2f, 0.5f, 400.f, 14, 200.f, 8000.f, 0.50f, 0.f, IrOutdoor,103 },
+ { "Gated Room", "FX", 0.7f, 0.35f,0.35f,0.3f, 20.f, 12, 5.f, 14000.f, 0.50f, 0.f, IrGated, 107 },
+ { "Metal Tank", "FX", 3.4f, 2.2f, 3.0f, 2.0f, 30.f, 8, 15.f, 12000.f, 0.50f, 0.f, IrMetal, 109 },
+ };
+ return specs[std::clamp(i, 0, kNumBuiltinIrs - 1)];
+}
+
+// Rooms / halls / plates / gated / outdoor: sparse-to-dense noise (echo density growing with
+// t²) split into four bands that each decay at their own RT60, plus discrete early taps.
+inline void synthRoom(std::vector<float>& out, const IrSpec& s, double sr, Rng& rng) {
+ const int64_t n = static_cast<int64_t>(out.size());
+ const float rt[4] = { s.rtLow, s.rtMid, std::sqrt(s.rtMid * s.rtHigh), s.rtHigh };
+ float k[4], env[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
+ for (int b = 0; b < 4; ++b) k[b] = static_cast<float>(std::exp(-6.907755 / (std::max(0.05f, rt[b]) * sr)));
+ const float c1 = onePole(300.0, sr), c2 = onePole(2000.0, sr), c3 = onePole(6000.0, sr);
+ float l1 = 0.0f, l2 = 0.0f, l3 = 0.0f;
+ const double build = std::max(0.5, static_cast<double>(s.buildup)) * 0.001;
+ const double tStart = s.type == IrPlate ? 0.0 : s.erSpan * 0.001 * 0.3;
+ const double pMax = s.type == IrOutdoor ? 0.035 : 1.0;
+ const double gateT = s.type == IrGated ? s.length * 0.72 : 1e9;
+ std::vector<float> fl;
+ int flLen = 0, flPos = 0;
+ if (s.flutter > 0.0f) { flLen = std::max(1, static_cast<int>(s.flutter * 0.001 * sr)); fl.assign(static_cast<size_t>(flLen), 0.0f); }
+ for (int64_t i = 0; i < n; ++i) {
+ const double t = static_cast<double>(i) / sr;
+ float x = 0.0f;
+ if (t >= tStart) {
+ const double tt = t - tStart;
+ const double p = std::min(pMax, 0.004 + (tt / build) * (tt / build));
+ if (rng.uni() < p) x = rng.bi() * 1.7320508f / static_cast<float>(std::sqrt(p));
+ x *= static_cast<float>(1.0 - std::exp(-tt / (build * 0.5 + 1e-4)));
+ }
+ if (flLen > 0) { // parallel walls: a feedback comb over the noise
+ const float y = x + 0.55f * fl[static_cast<size_t>(flPos)];
+ fl[static_cast<size_t>(flPos)] = y;
+ if (++flPos >= flLen) flPos = 0;
+ x = y * 0.6f;
+ }
+ float y;
+ if (s.type == IrGated) {
+ const double body = std::exp(-t / (s.rtMid * 2.0));
+ y = x * static_cast<float>(t < gateT ? body : std::exp(-gateT / (s.rtMid * 2.0)) * std::exp(-(t - gateT) / 0.012));
+ } else {
+ l1 += c1 * (x - l1); l2 += c2 * (x - l2); l3 += c3 * (x - l3);
+ y = l1 * env[0] + (l2 - l1) * env[1] + (l3 - l2) * env[2] + (x - l3) * env[3];
+ for (int b = 0; b < 4; ++b) env[b] *= k[b];
+ }
+ out[static_cast<size_t>(i)] = y;
+ }
+ for (int e = 0; e < s.erCount; ++e) { // early reflections: soft (air-absorbed) taps
+ const float frac = (static_cast<float>(e) + rng.uni() * 0.9f) / static_cast<float>(s.erCount);
+ const double tk = 0.0015 + s.erSpan * 0.001 * std::pow(static_cast<double>(frac), 1.25);
+ const int64_t pos = static_cast<int64_t>(tk * sr);
+ if (pos + 2 >= n) continue;
+ const float amp = 9.0f * (1.0f - 0.55f * frac) * (0.55f + 0.45f * rng.uni()) * (rng.uni() < 0.5f ? -1.0f : 1.0f);
+ out[static_cast<size_t>(pos)] += amp * 0.5f;
+ out[static_cast<size_t>(pos + 1)] += amp * 0.3f;
+ out[static_cast<size_t>(pos + 2)] += amp * 0.2f;
+ }
+}
+
+// A spring tank: one recirculating delay per channel with a long first-order allpass chain
+// in the loop (the dispersive "boing" chirp), band-limited like the real thing.
+inline void synthSpring(std::vector<float>& out, const IrSpec& s, double sr, int c, Rng& rng) {
+ const int64_t n = static_cast<int64_t>(out.size());
+ const int d = std::max(8, static_cast<int>((31.0 + 4.3 * c) * 0.001 * sr));
+ const float g = static_cast<float>(std::pow(10.0, -3.0 * (d / sr) / s.rtMid));
+ std::vector<float> line(static_cast<size_t>(d), 0.0f);
+ int w = 0;
+ constexpr int kAp = 48;
+ float apX[kAp] = {}, apY[kAp] = {};
+ const float a = 0.72f;
+ float lp = 0.0f, hp = 0.0f, hpPrev = 0.0f;
+ const float lpC = onePole(4200.0, sr), hpC = static_cast<float>(std::exp(-2.0 * kPi * 140.0 / sr));
+ const int64_t splash = static_cast<int64_t>(0.02 * sr);
+ for (int64_t i = 0; i < n; ++i) {
+ const float x = (i == 0 ? 1.0f : 0.0f) + (i < splash ? rng.bi() * 0.03f : 0.0f);
+ const float dv = line[static_cast<size_t>(w)];
+ float v = dv;
+ for (int k = 0; k < kAp; ++k) { const float y = flush(-a * v + apX[k] + a * apY[k]); apX[k] = v; apY[k] = y; v = y; }
+ lp += lpC * (v - lp);
+ hp = flush(hpC * (hp + lp - hpPrev)); hpPrev = lp;
+ line[static_cast<size_t>(w)] = x + g * hp;
+ if (++w >= d) w = 0;
+ out[static_cast<size_t>(i)] = dv;
+ }
+}
+
+// A metal tank: inharmonic decaying modes (recursive phasors) — resonant and clangy.
+inline void synthMetal(std::vector<float>& out, const IrSpec& s, double sr, Rng& rng) {
+ const int64_t n = static_cast<int64_t>(out.size());
+ constexpr int kModes = 56;
+ const double attack = 0.002 * sr;
+ for (int m = 0; m < kModes; ++m) {
+ const double f = 160.0 * std::pow(45.0, static_cast<double>(rng.uni()));
+ const double tn = std::clamp((std::log10(f) - 2.1) / 1.8, 0.0, 1.0);
+ const double rtm = (s.rtLow + (s.rtHigh - s.rtLow) * tn) * (0.6 + 0.8 * rng.uni());
+ const double k = std::exp(-6.907755 / (rtm * sr));
+ const double amp = (0.3 + 0.7 * rng.uni()) * 0.27;
+ const double ph = rng.uni() * 2.0 * kPi, w0 = 2.0 * kPi * f / sr;
+ const double cr = std::cos(w0) * k, ci = std::sin(w0) * k;
+ double zr = std::cos(ph) * amp, zi = std::sin(ph) * amp;
+ for (int64_t i = 0; i < n; ++i) {
+ const double nr = zr * cr - zi * ci; zi = zr * ci + zi * cr; zr = nr;
+ out[static_cast<size_t>(i)] += static_cast<float>(zi * (i < attack ? i / attack : 1.0));
+ if (std::fabs(zr) + std::fabs(zi) < 1e-7) break;
+ }
+ }
+}
+
+// The 4-channel (LL, LR, RL, RR) true-stereo response of a built-in IR at 48 kHz.
+inline std::shared_ptr<SourceIr> synthesizeIr(int idx) {
+ const IrSpec& s = irSpec(idx);
+ const double sr = 48000.0;
+ const int64_t n = static_cast<int64_t>(s.length * sr);
+ auto ir = std::make_shared<SourceIr>();
+ ir->channels = 4; ir->frames = n; ir->sampleRate = sr; ir->name = s.name; ir->category = s.category;
+ ir->data.assign(static_cast<size_t>(n) * 4, 0.0f);
+ std::vector<float> ch(static_cast<size_t>(n));
+ const float hc = onePole(s.bright, sr);
+ for (int c = 0; c < 4; ++c) {
+ std::fill(ch.begin(), ch.end(), 0.0f);
+ Rng rng(s.seed * 7919u + static_cast<uint32_t>(c) * 104729u + 1u);
+ if (s.type == IrSpring) synthSpring(ch, s, sr, c, rng);
+ else if (s.type == IrMetal) synthMetal(ch, s, sr, rng);
+ else synthRoom(ch, s, sr, rng);
+ float a = 0.0f, b = 0.0f;
+ const float g = (c == 0 || c == 3) ? 1.0f : s.cross;
+ for (int64_t i = 0; i < n; ++i) {
+ a += hc * (ch[static_cast<size_t>(i)] - a); b += hc * (a - b);
+ ir->data[static_cast<size_t>(i) * 4 + c] = b * g;
+ }
+ }
+ return ir;
+}
+
+// Built-in IRs are synthesised once per process and shared by every Chamber instance.
+inline std::shared_ptr<const SourceIr> builtinIr(int idx) {
+ static std::mutex mu;
+ static std::shared_ptr<const SourceIr> cache[kNumBuiltinIrs];
+ idx = std::clamp(idx, 0, kNumBuiltinIrs - 1);
+ std::lock_guard<std::mutex> lk(mu);
+ if (!cache[idx]) cache[idx] = synthesizeIr(idx);
+ return cache[idx];
+}
+
+// ============================================================================
+// Zero-latency partitioned convolution
+// ============================================================================
+
+inline void cmac(float* __restrict ar, float* __restrict ai, const float* __restrict xr, const float* __restrict xi,
+ const float* __restrict hr, const float* __restrict hi, int b) {
+ ar[0] += xr[0] * hr[0]; // bin 0 packs DC (re) and Nyquist (im): two real products
+ ai[0] += xi[0] * hi[0];
+ for (int i = 1; i < b; ++i) {
+ ar[i] += xr[i] * hr[i] - xi[i] * hi[i];
+ ai[i] += xr[i] * hi[i] + xi[i] * hr[i];
+ }
+}
+
+class ConvKernel {
+public:
+ struct Path { int in, out, k; };
+
+ double sampleRate = 0.0;
+ int latency = 0; // samples this kernel adds (0 = zero-latency head)
+ int block = 0; // big partition size
+ float seconds = 0.0f; // processed IR length
+
+ // h: processed responses at the engine rate (equal lengths); paths route input → output.
+ static std::unique_ptr<ConvKernel> build(const std::vector<std::vector<float>>& h, const std::vector<Path>& paths,
+ int nIn, bool monoIn, bool zeroLatency, int bigB, double sr) {
+ auto k = std::unique_ptr<ConvKernel>(new ConvKernel());
+ k->sampleRate = sr; k->block = bigB; k->nIn_ = nIn; k->monoIn_ = monoIn;
+ k->nPaths_ = std::min(static_cast<int>(paths.size()), 4);
+ for (int p = 0; p < k->nPaths_; ++p) { k->paths_[p] = paths[static_cast<size_t>(p)]; k->used_[paths[static_cast<size_t>(p)].out] = true; }
+ const int nK = static_cast<int>(h.size());
+ const int len = nK > 0 ? static_cast<int>(h[0].size()) : 0;
+ k->seconds = static_cast<float>(len / sr);
+ k->scratch_.assign(static_cast<size_t>(kScratch) * 2, 0.0f);
+ if (len == 0) return k;
+ if (zeroLatency) {
+ const int f = std::min(kFir, len);
+ k->fir_.init(f, nIn, nK);
+ for (int c = 0; c < nK; ++c) k->fir_.setKernel(c, h[static_cast<size_t>(c)].data(), f);
+ if (len > kFir) {
+ const int segLen = std::min(len, bigB) - kFir;
+ k->stages_[k->nStages_++].init(kFir, (segLen + kFir - 1) / kFir, nIn, nK, h, kFir, segLen);
+ }
+ if (len > bigB)
+ k->stages_[k->nStages_++].init(bigB, (len - bigB + bigB - 1) / bigB, nIn, nK, h, bigB, len - bigB);
+ k->latency = 0;
+ } else {
+ k->stages_[k->nStages_++].init(bigB, (len + bigB - 1) / bigB, nIn, nK, h, 0, len);
+ k->latency = bigB;
+ }
+ return k;
+ }
+
+ // Convolve n frames, ADDING into outL/outR. A null input means silence (a fading kernel).
+ void process(const float* inL, const float* inR, float* outL, float* outR, int n) {
+ for (int off = 0; off < n; off += kScratch) {
+ const int m = std::min(kScratch, n - off);
+ const float* a;
+ const float* b;
+ if (!inL) { std::fill(scratch_.begin(), scratch_.begin() + m, 0.0f); a = b = scratch_.data(); }
+ else if (monoIn_) {
+ float* s = scratch_.data();
+ for (int i = 0; i < m; ++i) s[i] = (inL[off + i] + inR[off + i]) * 0.70710678f;
+ a = b = s;
+ } else { a = inL + off; b = inR + off; }
+ if (fir_.f > 0) fir_.run(a, b, outL + off, outR + off, m, paths_, nPaths_);
+ for (int s = 0; s < nStages_; ++s) stages_[s].run(a, b, outL + off, outR + off, m, paths_, nPaths_, used_);
+ }
+ }
+
+ void clear() { fir_.clear(); for (int s = 0; s < nStages_; ++s) stages_[s].clear(); }
+
+ // Same partition layout → the input history (FIR ring + frequency-domain delay lines,
+ // which depend only on the input, never on the IR) can be handed from one kernel to the
+ // next, so a re-shaped IR re-renders the whole tail instead of starting from silence.
+ bool compatible(const ConvKernel& o) const {
+ if (nIn_ != o.nIn_ || monoIn_ != o.monoIn_ || fir_.f != o.fir_.f || nStages_ != o.nStages_) return false;
+ for (int s = 0; s < nStages_; ++s) if (stages_[s].B != o.stages_[s].B) return false;
+ return true;
+ }
+ void transplant(const ConvKernel& o) {
+ if (fir_.f > 0) { fir_.hist = o.fir_.hist; fir_.pos = o.fir_.pos; fir_.quiet = o.fir_.quiet; }
+ for (int s = 0; s < nStages_; ++s) stages_[s].transplant(o.stages_[s]);
+ }
+ // Samples until every stage's output is exact after a transplant (partial block + one
+ // block for the overlap to be rebuilt with the new IR).
+ int warmup() const { int w = 0; for (int s = 0; s < nStages_; ++s) w = std::max(w, 2 * stages_[s].B); return w; }
+ bool silent() const {
+ if (fir_.f > 0 && fir_.quiet < fir_.f + 1) return false;
+ for (int s = 0; s < nStages_; ++s) if (!stages_[s].silent()) return false;
+ return true;
+ }
+
+private:
+ static constexpr int kFir = 64, kScratch = 256;
+
+ struct Fir {
+ int f = 0, nIn = 0, nK = 0, pos = 0, quiet = 1 << 30;
+ std::vector<float> taps; // [nK][f], time-reversed
+ std::vector<float> hist; // [nIn][2f] mirrored ring
+ void init(int f_, int nIn_, int nK_) {
+ f = f_; nIn = nIn_; nK = nK_; pos = 0;
+ taps.assign(static_cast<size_t>(nK) * f, 0.0f);
+ hist.assign(static_cast<size_t>(nIn) * 2 * f, 0.0f);
+ }
+ void setKernel(int k, const float* h, int len) {
+ for (int t = 0; t < len; ++t) taps[static_cast<size_t>(k) * f + (f - 1 - t)] = h[t];
+ }
+ void clear() { std::fill(hist.begin(), hist.end(), 0.0f); pos = 0; quiet = 1 << 30; }
+ void run(const float* a, const float* b, float* oL, float* oR, int n, const Path* paths, int nPaths) {
+ for (int i = 0; i < n; ++i) {
+ const float x0 = a[i], x1 = b[i];
+ const bool nz = x0 != 0.0f || (nIn > 1 && x1 != 0.0f);
+ if (nz) quiet = 0; else if (quiet < (1 << 30)) ++quiet;
+ float* h0 = &hist[0];
+ h0[pos] = x0; h0[pos + f] = x0;
+ if (nIn > 1) { float* h1 = &hist[static_cast<size_t>(2 * f)]; h1[pos] = x1; h1[pos + f] = x1; }
+ if (quiet <= f) {
+ for (int p = 0; p < nPaths; ++p) {
+ const float* win = &hist[static_cast<size_t>(paths[p].in) * 2 * f + pos + 1];
+ const float* tp = &taps[static_cast<size_t>(paths[p].k) * f];
+ float acc = 0.0f;
+ for (int t = 0; t < f; ++t) acc += tp[t] * win[t];
+ (paths[p].out == 0 ? oL : oR)[i] += acc;
+ }
+ }
+ if (++pos >= f) pos = 0;
+ }
+ }
+ };
+
+ // One uniformly partitioned overlap-add stage over IR[offset, offset + P·B); its block
+ // latency equals `offset` in the zero-latency layout, so the stages line up exactly.
+ struct Stage {
+ int B = 0, P = 0, nIn = 0, nK = 0;
+ signalsmith::linear::RealFFT<float> fft;
+ std::vector<float> Hr, Hi; // [nK][P][B], pre-scaled by 1/2B
+ std::vector<float> Xr, Xi; // [nIn][P][B] frequency-domain delay line
+ std::vector<uint8_t> live; // [nIn][P] slot holds non-zero input
+ std::vector<float> in, out, ovl; // [nIn][B] · [2][B] · [2][B]
+ std::vector<float> time, ar, ai; // [2B] · [2][B] · [2][B]
+ int pos = 0, fill = 0, liveSlots = 0, quietBlocks = 2;
+
+ void init(int b, int p, int nIn_, int nK_, const std::vector<std::vector<float>>& h, int offset, int len) {
+ B = b; P = std::max(1, p); nIn = nIn_; nK = nK_;
+ fft.resize(static_cast<size_t>(2 * B));
+ const size_t spec = static_cast<size_t>(P) * B;
+ Hr.assign(spec * nK, 0.0f); Hi.assign(spec * nK, 0.0f);
+ Xr.assign(spec * nIn, 0.0f); Xi.assign(spec * nIn, 0.0f);
+ live.assign(static_cast<size_t>(P) * nIn, 0);
+ in.assign(static_cast<size_t>(nIn) * B, 0.0f);
+ out.assign(static_cast<size_t>(2) * B, 0.0f); ovl.assign(static_cast<size_t>(2) * B, 0.0f);
+ time.assign(static_cast<size_t>(2) * B, 0.0f);
+ ar.assign(static_cast<size_t>(2) * B, 0.0f); ai.assign(static_cast<size_t>(2) * B, 0.0f);
+ const float sc = 1.0f / (2.0f * B);
+ for (int k = 0; k < nK; ++k) {
+ const float* src = h[static_cast<size_t>(k)].data() + offset;
+ for (int j = 0; j < P; ++j) {
+ std::fill(time.begin(), time.end(), 0.0f);
+ const int a = j * B, m = std::min(B, len - a);
+ if (m > 0) std::copy(src + a, src + a + m, time.begin());
+ float* hr = &Hr[(static_cast<size_t>(k) * P + j) * B];
+ float* hi = &Hi[(static_cast<size_t>(k) * P + j) * B];
+ fft.fft(time.data(), hr, hi);
+ for (int i = 0; i < B; ++i) { hr[i] *= sc; hi[i] *= sc; }
+ }
+ }
+ }
+ void clear() {
+ std::fill(live.begin(), live.end(), 0); liveSlots = 0;
+ std::fill(in.begin(), in.end(), 0.0f); std::fill(out.begin(), out.end(), 0.0f); std::fill(ovl.begin(), ovl.end(), 0.0f);
+ pos = 0; fill = 0; quietBlocks = 2;
+ }
+ bool silent() const { return liveSlots == 0 && quietBlocks >= 2; }
+ void transplant(const Stage& o) {
+ fill = o.fill;
+ std::copy(o.in.begin(), o.in.end(), in.begin());
+ std::fill(out.begin(), out.end(), 0.0f); std::fill(ovl.begin(), ovl.end(), 0.0f);
+ std::fill(live.begin(), live.end(), 0);
+ pos = 0; liveSlots = 0; quietBlocks = 0;
+ const int n = std::min(P, o.P);
+ for (int c = 0; c < nIn; ++c)
+ for (int j = 0; j < n; ++j) {
+ const int so = ((o.pos - j) % o.P + o.P) % o.P, sn = ((pos - j) % P + P) % P;
+ const uint8_t lv = o.live[static_cast<size_t>(c) * o.P + so];
+ live[static_cast<size_t>(c) * P + sn] = lv;
+ if (!lv) continue;
+ ++liveSlots;
+ const size_t xo = (static_cast<size_t>(c) * o.P + so) * B, xn = (static_cast<size_t>(c) * P + sn) * B;
+ std::copy(o.Xr.begin() + xo, o.Xr.begin() + xo + B, Xr.begin() + xn);
+ std::copy(o.Xi.begin() + xo, o.Xi.begin() + xo + B, Xi.begin() + xn);
+ }
+ }
+
+ void run(const float* a, const float* b, float* oL, float* oR, int n, const Path* paths, int nPaths, const bool* used) {
+ int i = 0;
+ while (i < n) {
+ const int m = std::min(n - i, B - fill);
+ std::copy(a + i, a + i + m, &in[static_cast<size_t>(fill)]);
+ if (nIn > 1) std::copy(b + i, b + i + m, &in[static_cast<size_t>(B + fill)]);
+ if (used[0]) { const float* s = &out[static_cast<size_t>(fill)]; for (int k = 0; k < m; ++k) oL[i + k] += s[k]; }
+ if (used[1]) { const float* s = &out[static_cast<size_t>(B + fill)]; for (int k = 0; k < m; ++k) oR[i + k] += s[k]; }
+ fill += m; i += m;
+ if (fill == B) { compute(paths, nPaths, used); fill = 0; }
+ }
+ }
+
+ void compute(const Path* paths, int nPaths, const bool* used) {
+ pos = pos + 1 >= P ? 0 : pos + 1;
+ for (int c = 0; c < nIn; ++c) {
+ const float* ic = &in[static_cast<size_t>(c) * B];
+ bool nz = false;
+ for (int k = 0; k < B; ++k) if (ic[k] != 0.0f) { nz = true; break; }
+ uint8_t& lv = live[static_cast<size_t>(c) * P + pos];
+ if (lv) --liveSlots;
+ lv = nz ? 1 : 0;
+ if (!nz) continue;
+ ++liveSlots;
+ std::copy(ic, ic + B, time.begin());
+ std::fill(time.begin() + B, time.end(), 0.0f);
+ const size_t o = (static_cast<size_t>(c) * P + pos) * B;
+ fft.fft(time.data(), &Xr[o], &Xi[o]);
+ }
+ bool any[2] = { false, false };
+ if (liveSlots > 0) {
+ for (int o = 0; o < 2; ++o) if (used[o]) {
+ std::fill(ar.begin() + o * B, ar.begin() + (o + 1) * B, 0.0f);
+ std::fill(ai.begin() + o * B, ai.begin() + (o + 1) * B, 0.0f);
+ }
+ for (int p = 0; p < nPaths; ++p) {
+ const Path& ph = paths[p];
+ float* accR = &ar[static_cast<size_t>(ph.out) * B];
+ float* accI = &ai[static_cast<size_t>(ph.out) * B];
+ for (int j = 0; j < P; ++j) {
+ int s = pos - j; if (s < 0) s += P;
+ if (!live[static_cast<size_t>(ph.in) * P + s]) continue;
+ const size_t xo = (static_cast<size_t>(ph.in) * P + s) * B;
+ const size_t ho = (static_cast<size_t>(ph.k) * P + j) * B;
+ cmac(accR, accI, &Xr[xo], &Xi[xo], &Hr[ho], &Hi[ho], B);
+ any[ph.out] = true;
+ }
+ }
+ }
+ for (int o = 0; o < 2; ++o) {
+ if (!used[o]) continue;
+ float* ob = &out[static_cast<size_t>(o) * B];
+ float* ov = &ovl[static_cast<size_t>(o) * B];
+ if (any[o]) {
+ fft.ifft(&ar[static_cast<size_t>(o) * B], &ai[static_cast<size_t>(o) * B], time.data());
+ for (int k = 0; k < B; ++k) { ob[k] = time[static_cast<size_t>(k)] + ov[k]; ov[k] = time[static_cast<size_t>(B + k)]; }
+ } else {
+ for (int k = 0; k < B; ++k) { ob[k] = ov[k]; ov[k] = 0.0f; }
+ }
+ }
+ if (any[0] || any[1]) quietBlocks = 0; else if (quietBlocks < 2) ++quietBlocks;
+ }
+ };
+
+ ConvKernel() = default;
+
+ int nIn_ = 2, nPaths_ = 0, nStages_ = 0;
+ bool monoIn_ = false;
+ bool used_[2] = { false, false };
+ Path paths_[4] = {};
+ Fir fir_;
+ Stage stages_[2];
+ std::vector<float> scratch_;
+};
+
+struct Shape { float start = 0.0f, end = 1.0f, attackMs = 0.0f, size = 1.0f; bool reverse = false; };
+
+// Trim [start, end] of the source, time-stretch by Size while resampling to the engine rate
+// (cubic Hermite), fade the truncated end, optionally reverse, then fade in over Attack.
+// Loudness is normalised on the whole source so trims read as trims, not as level jumps.
+inline std::vector<std::vector<float>> shapeIr(const SourceIr& src, const std::vector<int>& chans, const Shape& sh,
+ double sr, double maxSec) {
+ std::vector<std::vector<float>> out;
+ if (src.frames < 4 || src.channels <= 0) return out;
+ const int64_t F = src.frames;
+ const double s0 = std::clamp(static_cast<double>(sh.start), 0.0, 0.98) * F;
+ const double s1 = std::max(s0 + 0.004 * src.sampleRate, std::clamp(static_cast<double>(sh.end), 0.0, 1.0) * F);
+ const double step = (src.sampleRate / sr) / std::clamp(static_cast<double>(sh.size), 0.25, 4.0);
+ int64_t m = static_cast<int64_t>((s1 - s0) / step);
+ m = std::clamp<int64_t>(m, 1, static_cast<int64_t>(maxSec * sr));
+ const bool capped = static_cast<double>(m) * step < (s1 - s0) - 1.0;
+
+ // Normalisation: mean energy of the main (direct) channels over the whole source.
+ const int nc = src.channels;
+ double e = 0.0; int mains = 0;
+ for (int c = 0; c < nc; ++c) {
+ if (nc == 4 && (c == 1 || c == 2)) continue;
+ double ec = 0.0;
+ for (int64_t i = 0; i < F; ++i) { const double v = src.data[static_cast<size_t>(i * nc + c)]; ec += v * v; }
+ e += ec; ++mains;
+ }
+ e /= std::max(1, mains);
+ const float norm = e > 1e-12 ? static_cast<float>(0.5 / std::sqrt(e * (sr / src.sampleRate) * sh.size)) : 0.0f;
+
+ auto at = [&](int c, int64_t f) { return (f >= 0 && f < F) ? src.data[static_cast<size_t>(f * nc + c)] : 0.0f; };
+ const int64_t fadeOut = (sh.end < 0.999f || capped) ? std::min<int64_t>(m * 3 / 10, static_cast<int64_t>(0.35 * sr))
+ : std::min<int64_t>(m / 4, static_cast<int64_t>(0.01 * sr));
+ const int64_t fadeIn = std::max<int64_t>(static_cast<int64_t>(sh.attackMs * 0.001 * sr),
+ (sh.start > 0.0005f || sh.reverse) ? static_cast<int64_t>(0.002 * sr) : 0);
+ for (int c : chans) {
+ std::vector<float> v(static_cast<size_t>(m));
+ for (int64_t i = 0; i < m; ++i) {
+ const double pos = s0 + static_cast<double>(i) * step;
+ const int64_t k = static_cast<int64_t>(pos);
+ const float f = static_cast<float>(pos - static_cast<double>(k));
+ const float xm1 = at(c, k - 1), x0 = at(c, k), x1 = at(c, k + 1), x2 = at(c, k + 2);
+ const float c1 = 0.5f * (x1 - xm1), c2 = xm1 - 2.5f * x0 + 2.0f * x1 - 0.5f * x2, c3 = 0.5f * (x2 - xm1) + 1.5f * (x0 - x1);
+ v[static_cast<size_t>(i)] = (((c3 * f + c2) * f + c1) * f + x0) * norm;
+ }
+ for (int64_t i = 0; i < fadeOut; ++i) {
+ const float g = 0.5f - 0.5f * std::cos(static_cast<float>(kPi) * static_cast<float>(i) / static_cast<float>(fadeOut));
+ v[static_cast<size_t>(m - 1 - i)] *= g;
+ }
+ if (sh.reverse) std::reverse(v.begin(), v.end());
+ for (int64_t i = 0; i < fadeIn && i < m; ++i) {
+ const float g = static_cast<float>(i) / static_cast<float>(fadeIn);
+ v[static_cast<size_t>(i)] *= g * g;
+ }
+ out.push_back(std::move(v));
+ }
+ return out;
+}
+
+// ============================================================================
+// Algorithmic engine
+// ============================================================================
+
+struct DLine {
+ std::vector<float> b;
+ int mask = 0, w = 0;
+ void init(int maxLen) { int sz = 16; while (sz < maxLen + 8) sz <<= 1; b.assign(static_cast<size_t>(sz), 0.0f); mask = sz - 1; w = 0; }
+ void clear() { std::fill(b.begin(), b.end(), 0.0f); w = 0; }
+ void push(float x) { b[static_cast<size_t>(w)] = x; w = (w + 1) & mask; }
+ float tap(int d) const { return b[static_cast<size_t>((w - 1 - d) & mask)]; } // d = 0 → newest
+ float lin(float d) const { const int i = static_cast<int>(d); const float f = d - static_cast<float>(i); const float a = tap(i); return a + f * (tap(i + 1) - a); }
+ float cubic(float d) const {
+ const int i = static_cast<int>(d); const float f = d - static_cast<float>(i);
+ const float xm1 = tap(i - 1), x0 = tap(i), x1 = tap(i + 1), x2 = tap(i + 2);
+ const float c1 = 0.5f * (x1 - xm1), c2 = xm1 - 2.5f * x0 + 2.0f * x1 - 0.5f * x2, c3 = 0.5f * (x2 - xm1) + 1.5f * (x0 - x1);
+ return ((c3 * f + c2) * f + c1) * f + x0;
+ }
+};
+
+inline void hadamard8(float* x) {
+ for (int h = 1; h < 8; h <<= 1)
+ for (int i = 0; i < 8; i += h * 2)
+ for (int j = i; j < i + h; ++j) { const float a = x[j], b = x[j + h]; x[j] = a + b; x[j + h] = a - b; }
+ for (int i = 0; i < 8; ++i) x[i] *= 0.35355339f;
+}
+
+// Two crossfaded read heads sweeping a 60 ms window (sin² windows sum to one).
+struct PitchShift {
+ DLine d; float phase = 0.0f; int W = 2048;
+ void init(double sr) { W = std::max(64, static_cast<int>(0.06 * sr)); d.init(W + 8); phase = 0.0f; }
+ void clear() { d.clear(); phase = 0.0f; }
+ float process(float x, float ratio) {
+ d.push(x);
+ phase += (1.0f - ratio) / static_cast<float>(W);
+ phase -= std::floor(phase);
+ float p2 = phase + 0.5f; if (p2 >= 1.0f) p2 -= 1.0f;
+ float w1 = std::sin(static_cast<float>(kPi) * phase); w1 *= w1;
+ return d.lin(1.0f + phase * (W - 4)) * w1 + d.lin(1.0f + p2 * (W - 4)) * (1.0f - w1);
+ }
+};
+
+class Algo {
+public:
+ static constexpr int N = 8;
+ struct Params {
+ int mode = 0;
+ float decay = 3.0f, size = 1.0f, diffuse = 0.7f, damp = 4500.0f, lowMul = 1.0f, highMul = 0.5f;
+ float rate = 0.4f, depth = 0.3f, shimAmt = 0.0f, shimRatio = 2.0f;
+ bool freeze = false, vintage = false, cubic = false, shimFb = true;
+ };
+
+ void prepare(double sr) {
+ sr_ = sr;
+ for (auto& l : line_) l.init(static_cast<int>(0.5 * sr) + 64);
+ for (int s = 0; s < 4; ++s) for (int i = 0; i < N; ++i) diff_[s][i].init(static_cast<int>(0.085 * sr) + 8);
+ for (int i = 0; i < N; ++i) ap_[i].init(static_cast<int>(0.012 * sr) + 8);
+ shL_.init(sr); shR_.init(sr);
+ Rng r(0xC4A3B1u);
+ for (int s = 0; s < 4; ++s)
+ for (int i = 0; i < N; ++i) { frac_[s][i] = (static_cast<float>(i) + 0.15f + 0.7f * r.uni()) / static_cast<float>(N); flip_[s][i] = r.uni() < 0.5f ? -1.0f : 1.0f; }
+ for (int i = 0; i < N; ++i) { const double ph = 2.0 * kPi * i / N; lfoC_[i] = static_cast<float>(std::cos(ph)); lfoS_[i] = static_cast<float>(std::sin(ph)); }
+ primed_ = false;
+ reset();
+ }
+
+ void reset() {
+ for (auto& l : line_) l.clear();
+ for (int s = 0; s < 4; ++s) for (auto& d : diff_[s]) d.clear();
+ for (auto& a : ap_) a.clear();
+ shL_.clear(); shR_.clear();
+ for (int i = 0; i < N; ++i) { bl1_[i] = bl2_[i] = 0.0f; inj_[i] = 0.0f; }
+ vinL_[0] = vinL_[1] = vinR_[0] = vinR_[1] = 0.0f; hcL_ = hcR_ = 0.0f;
+ shHpL_ = shHpR_ = shLpL_ = shLpR_ = 0.0f;
+ }
+
+ // A clean start (delays re-primed at their targets) — for the offline preview render.
+ void restart() { primed_ = false; lfoCos_ = 1.0f; lfoSin_ = 0.0f; reset(); }
+
+ // Tail length the engine is set to (mid band, seconds) — for the UI readout.
+ static float modeScale(int mode) { return mode == 1 ? 0.3f : mode == 2 ? 1.6f : mode == 3 ? 1.1f : 1.0f; }
+
+ void process(const float* inL, const float* inR, float* outL, float* outR, int n, const Params& p) {
+ const Mode& mc = mode(p.mode);
+ const double sr = sr_;
+ const float size = std::clamp(p.size, 0.3f, 2.6f);
+ float dT[N], ddT[4][N];
+ for (int i = 0; i < N; ++i) dT[i] = std::max(4.0f, static_cast<float>(mc.dly[i] * 0.001 * sr * size));
+ static const float kStage[4] = { 5.3f, 10.9f, 21.7f, 41.3f };
+ const float sScale = mc.diff * std::sqrt(size);
+ for (int s = 0; s < 4; ++s)
+ for (int i = 0; i < N; ++i) ddT[s][i] = static_cast<float>(kStage[s] * sScale * 0.001 * sr) * frac_[s][i];
+ if (!primed_) { // first block: start at the targets instead of gliding from zero
+ for (int i = 0; i < N; ++i) dCur_[i] = dT[i];
+ for (int s = 0; s < 4; ++s) for (int i = 0; i < N; ++i) ddCur_[s][i] = ddT[s][i];
+ primed_ = true;
+ }
+ // Three-band loop gains from the RT60s (per line, at its current length).
+ const float a1 = onePole(250.0, sr), a2 = onePole(std::max(600.0f, p.damp), sr);
+ // RT60s, with an empirical allowance for the loop's interpolation / modulation loss
+ // (without it long tails measure ~20 % short).
+ auto comp = [](float rt) { return rt * (1.0f + 0.028f * std::min(rt, 20.0f)); };
+ const float rtM = comp(std::max(0.1f, p.decay)), rtL = comp(std::max(0.1f, p.decay * p.lowMul)), rtH = comp(std::max(0.05f, p.decay * p.highMul));
+ float gL[N], gM[N], gH[N];
+ for (int i = 0; i < N; ++i) {
+ const double d = (dCur_[i] + kApMs[i] * 0.001 * sr) / sr;
+ gL[i] = p.freeze ? 1.0f : std::min(0.9999f, static_cast<float>(std::pow(10.0, -3.0 * d / rtL)));
+ gM[i] = p.freeze ? 1.0f : std::min(0.9999f, static_cast<float>(std::pow(10.0, -3.0 * d / rtM)));
+ gH[i] = p.freeze ? 1.0f : std::min(0.9999f, static_cast<float>(std::pow(10.0, -3.0 * d / rtH)));
+ }
+ const float apG = mc.ap * (0.35f + 0.65f * p.diffuse);
+ const float dmix = std::clamp(p.diffuse * (p.mode == 2 ? 0.6f : 1.0f), 0.0f, 1.0f);
+ const float glide = static_cast<float>(1.0 - std::exp(-1.0 / (0.12 * sr)));
+ const float md = p.depth * static_cast<float>(0.0011 * sr) * (p.vintage ? 2.0f : 1.0f);
+ const double w0 = 2.0 * kPi * std::clamp(static_cast<double>(p.rate), 0.01, 20.0) / sr;
+ const float rc = static_cast<float>(std::cos(w0)), rs = static_cast<float>(std::sin(w0));
+ const float hc = onePole(p.vintage ? std::min(mc.hiCut, 8500.0f) : mc.hiCut, sr);
+ const float vin = onePole(6500.0, sr);
+ const bool shim = p.mode == 3 && p.shimAmt > 0.001f;
+ // Shimmer fed back into the loop: keep the pitched loop gain below one — longer tails
+ // ring more, so the injection shrinks with √RT; a frozen (lossless) loop takes none.
+ const bool shimFb = p.shimFb && !p.freeze;
+ const float shimLoop = 0.5f * std::min(1.0f, std::sqrt(2.5f / std::max(0.1f, p.decay)));
+ const float shHp = onePole(250.0, sr), shLp = onePole(7000.0, sr);
+ static const float sL[N] = { 1, -1, 1, -1, 1, -1, 1, -1 }, sR[N] = { 1, 1, -1, -1, 1, 1, -1, -1 };
+ static const float inSign[N] = { 1, 1, -1, 1, -1, -1, 1, -1 };
+ const float inG = 0.42f, outG = 0.30f * mc.gain; // per-mode gain: ~level-matched to the convolution
+ const float erG = mc.er * 0.55f;
+ int apLen[N];
+ for (int i = 0; i < N; ++i) apLen[i] = std::max(1, static_cast<int>(kApMs[i] * 0.001 * sr));
+
+ for (int t = 0; t < n; ++t) {
+ float xL = inL[t], xR = inR[t];
+ if (p.vintage) {
+ vinL_[0] += vin * (xL - vinL_[0]); vinL_[1] += vin * (vinL_[0] - vinL_[1]); xL = vinL_[1];
+ vinR_[0] += vin * (xR - vinR_[0]); vinR_[1] += vin * (vinR_[0] - vinR_[1]); xR = vinR_[1];
+ }
+ float ch[N], direct[N];
+ for (int i = 0; i < N; ++i) { ch[i] = ((i & 1) ? xR : xL) * inSign[i]; direct[i] = ch[i]; }
+ float eL = 0.0f, eR = 0.0f;
+ for (int s = 0; s < 4; ++s) {
+ for (int i = 0; i < N; ++i) {
+ ddCur_[s][i] += glide * (ddT[s][i] - ddCur_[s][i]);
+ diff_[s][i].push(ch[i]);
+ ch[i] = diff_[s][i].lin(ddCur_[s][i]);
+ }
+ hadamard8(ch);
+ for (int i = 0; i < N; ++i) ch[i] *= flip_[s][i];
+ if (s == 1) { eL = ch[0] + ch[2] + ch[4] + ch[6]; eR = ch[1] + ch[3] + ch[5] + ch[7]; }
+ }
+ // LFO: one quadrature oscillator, eight phase-offset taps.
+ const float nc = lfoCos_ * rc - lfoSin_ * rs; lfoSin_ = lfoSin_ * rc + lfoCos_ * rs; lfoCos_ = nc;
+ float y[N], sum = 0.0f;
+ for (int i = 0; i < N; ++i) {
+ dCur_[i] += glide * (dT[i] - dCur_[i]);
+ const float dd = std::max(2.0f, dCur_[i] + md * (lfoSin_ * lfoC_[i] + lfoCos_ * lfoS_[i]));
+ float v = p.cubic ? line_[i].cubic(dd - 1.0f) : line_[i].lin(dd - 1.0f);
+ // in-loop allpass (g = 0 → a plain short delay, so switching is seamless)
+ const float z = ap_[i].tap(apLen[i] - 1);
+ const float wv = v + apG * z;
+ ap_[i].push(flush(wv));
+ v = z - apG * wv;
+ // three-band decay
+ bl1_[i] += a1 * (v - bl1_[i]); bl2_[i] += a2 * (v - bl2_[i]);
+ v = gL[i] * bl1_[i] + gM[i] * (bl2_[i] - bl1_[i]) + gH[i] * (v - bl2_[i]);
+ y[i] = v; sum += v;
+ }
+ sum *= 2.0f / N;
+ for (int i = 0; i < N; ++i) {
+ float v = y[i] - sum + (direct[i] + (ch[i] - direct[i]) * dmix) * inG + inj_[i];
+ if (p.vintage) v = std::floor(v * 8192.0f + 0.5f) * (1.0f / 8192.0f);
+ line_[i].push(flush(loopLimit(v)));
+ }
+ float oL = 0.0f, oR = 0.0f;
+ for (int i = 0; i < N; ++i) { oL += y[i] * sL[i]; oR += y[i] * sR[i]; }
+ oL *= outG; oR *= outG;
+ if (shim) {
+ float a = shL_.process(oL, p.shimRatio), b = shR_.process(oR, p.shimRatio);
+ shLpL_ += shLp * (a - shLpL_); shHpL_ += shHp * (shLpL_ - shHpL_); a = shLpL_ - shHpL_;
+ shLpR_ += shLp * (b - shLpR_); shHpR_ += shHp * (shLpR_ - shHpR_); b = shLpR_ - shHpR_;
+ if (shimFb) {
+ const float g = p.shimAmt * shimLoop;
+ for (int i = 0; i < N; ++i) inj_[i] = ((i & 1) ? b : a) * g * inSign[i];
+ oL += a * p.shimAmt * 0.35f; oR += b * p.shimAmt * 0.35f;
+ } else {
+ for (int i = 0; i < N; ++i) inj_[i] = 0.0f;
+ oL += a * p.shimAmt; oR += b * p.shimAmt;
+ }
+ } else {
+ for (int i = 0; i < N; ++i) inj_[i] = 0.0f;
+ }
+ oL += eL * erG; oR += eR * erG;
+ hcL_ += hc * (oL - hcL_); hcR_ += hc * (oR - hcR_);
+ outL[t] = hcL_; outR[t] = hcR_;
+ }
+ const float mag = std::sqrt(lfoCos_ * lfoCos_ + lfoSin_ * lfoSin_); // keep the phasor on the unit circle
+ if (mag > 1e-6f) { lfoCos_ /= mag; lfoSin_ /= mag; } else { lfoCos_ = 1.0f; lfoSin_ = 0.0f; }
+ }
+
+private:
+ struct Mode { float dly[N]; float diff, ap, er, hiCut, gain; };
+ static const Mode& mode(int m) {
+ static const Mode cfg[4] = {
+ { { 43.1f, 49.7f, 55.3f, 62.9f, 69.4f, 77.9f, 85.1f, 93.7f }, 1.00f, 0.50f, 0.20f, 9000.0f, 2.40f }, // Dark Hall
+ { { 9.7f, 12.1f, 14.9f, 17.3f, 20.3f, 23.9f, 27.1f, 31.3f }, 0.40f, 0.62f, 0.00f, 18000.0f, 1.60f }, // Plate
+ { { 57.1f, 68.3f, 79.9f, 91.7f,107.3f,121.9f,139.1f,157.7f }, 0.55f, 0.00f, 0.50f, 15000.0f, 1.45f }, // Quartz
+ { { 47.3f, 56.1f, 63.7f, 71.9f, 81.3f, 89.9f, 98.3f,109.1f }, 1.15f, 0.55f, 0.12f, 14000.0f, 2.20f }, // Shimmer
+ };
+ return cfg[std::clamp(m, 0, 3)];
+ }
+ static constexpr float kApMs[N] = { 3.1f, 4.7f, 6.3f, 7.9f, 3.9f, 5.5f, 7.1f, 8.7f };
+
+ double sr_ = 48000.0;
+ bool primed_ = false;
+ DLine line_[N], diff_[4][N], ap_[N];
+ PitchShift shL_, shR_;
+ float dCur_[N] = {}, ddCur_[4][N] = {}, frac_[4][N] = {}, flip_[4][N] = {};
+ float bl1_[N] = {}, bl2_[N] = {}, inj_[N] = {};
+ float lfoC_[N] = {}, lfoS_[N] = {}, lfoCos_ = 1.0f, lfoSin_ = 0.0f;
+ float vinL_[2] = {}, vinR_[2] = {}, hcL_ = 0.0f, hcR_ = 0.0f;
+ float shHpL_ = 0.0f, shHpR_ = 0.0f, shLpL_ = 0.0f, shLpR_ = 0.0f;
+};
+
+// ============================================================================
+// Small helpers: biquad EQ
+// ============================================================================
+
+struct Biquad {
+ float b0 = 1, b1 = 0, b2 = 0, a1 = 0, a2 = 0;
+ float z1[2] = {}, z2[2] = {};
+ void clear() { z1[0] = z1[1] = z2[0] = z2[1] = 0.0f; }
+ float run(int c, float x) {
+ const float y = b0 * x + z1[c];
+ z1[c] = flush(b1 * x - a1 * y + z2[c]);
+ z2[c] = flush(b2 * x - a2 * y);
+ return y;
+ }
+ void set(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 hp(double f, double sr) { const double w = 2 * kPi * f / sr, c = std::cos(w), al = std::sin(w) / (2 * 0.7071); set((1 + c) / 2, -(1 + c), (1 + c) / 2, 1 + al, -2 * c, 1 - al); }
+ void lp(double f, double sr) { const double w = 2 * kPi * f / sr, c = std::cos(w), al = std::sin(w) / (2 * 0.7071); set((1 - c) / 2, 1 - c, (1 - c) / 2, 1 + al, -2 * c, 1 - al); }
+ void lowShelf(double f, double db, double sr) {
+ const double A = std::pow(10.0, db / 40.0), w = 2 * kPi * f / sr, c = std::cos(w), al = std::sin(w) / 2 * std::sqrt(2.0), sa = 2 * std::sqrt(A) * al;
+ set(A * ((A + 1) - (A - 1) * c + sa), 2 * A * ((A - 1) - (A + 1) * c), A * ((A + 1) - (A - 1) * c - sa),
+ (A + 1) + (A - 1) * c + sa, -2 * ((A - 1) + (A + 1) * c), (A + 1) + (A - 1) * c - sa);
+ }
+ void highShelf(double f, double db, double sr) {
+ const double A = std::pow(10.0, db / 40.0), w = 2 * kPi * f / sr, c = std::cos(w), al = std::sin(w) / 2 * std::sqrt(2.0), sa = 2 * std::sqrt(A) * al;
+ set(A * ((A + 1) + (A - 1) * c + sa), -2 * A * ((A - 1) + (A + 1) * c), A * ((A + 1) + (A - 1) * c - sa),
+ (A + 1) - (A - 1) * c + sa, 2 * ((A - 1) - (A + 1) * c), (A + 1) - (A - 1) * c - sa);
+ }
+};
+
+} // namespace chamber
+
+// ============================================================================
+// The device
+// ============================================================================
+
+class Chamber final : public Device {
+public:
+ enum {
+ Blend = 0, DryWet, ConvOn, AlgoOn, DryLevel, Routing,
+ IrSelect, IrStart, IrDecay, IrAttack, IrSize, ConvPredelay, ConvSync, IrReverse, IrTrueStereo,
+ AlgoMode, AlgoDecay, AlgoSize, AlgoDiffusion, AlgoDamping, AlgoPredelay, AlgoSync, AlgoLowDecay, AlgoHighDecay,
+ Freeze, FreezeIn, AlgoVintage, ModRate, ModDepth, ShimmerAmount, ShimmerPitch, ShimmerFeedback,
+ EqLowCut, EqLowGain, EqHighShelf, EqHighCut, EqPosition,
+ DuckAmount, DuckRelease, Output, Width, BassMono, Quality, WetOnly, ZeroLatency,
+ kNumParams
+ };
+ // Packed scope telemetry (lock-free, UI-polled).
+ enum { S_WetL = 0, S_WetR, S_OutL, S_OutR, S_DuckDb, S_Cpu, S_Latency, S_SampleRate, S_Building,
+ S_IrSeconds, S_IrRate, S_IrChannels, S_KernelSeconds, S_Bpm, S_Frozen, S_Block, S_UserIr, S_InPeak, S_Kernels,
+ S_ResultSeconds, S_PreviewSeconds, S_PreviewGen, kScope };
+ // deviceText ids.
+ enum { T_IrName = 0, T_IrCategory = 1, T_UserName = 2, T_IrList = 10 };
+
+ static constexpr int kIrCount = chamber::kNumBuiltinIrs + 1; // the last slot = the user IR
+ static constexpr int kSyncDivs = 13;
+
+ Chamber() {
+ static const float def[kNumParams] = {
+ 0.5f, 0.35f, 1.0f, 1.0f, 0.70710678f, 0.0f, // blend · dry/wet · conv · algo · dry level · routing
+ 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.2f, 0.0f, 0.0f, 1.0f, // IR · start · decay · attack · size · predelay · sync · reverse · true stereo
+ 0.0f, 0.588f, 0.5f, 0.7f, 0.613f, 0.2f, 0.0f, 0.6f, 0.25f, // mode · decay · size · diffusion · damping · predelay · sync · low · high
+ 0.0f, 0.0f, 0.0f, 0.41f, 0.3f, 0.5f, 1.0f, 1.0f, // freeze · freeze in · vintage · rate · depth · shimmer · pitch · feedback
+ 0.0f, 0.5f, 0.5f, 1.0f, 0.5f, // EQ low cut · low gain · high shelf · high cut · position
+ 0.0f, 0.548f, 0.6666667f, 0.5f, 0.0f, 0.5f, 0.0f, 1.0f // duck · release · output · width · bass mono · quality · wet only · zero latency
+ };
+ for (int i = 0; i < kNumParams; ++i) p_[i].store(def[i], std::memory_order_relaxed);
+ }
+ ~Chamber() override {
+ stopWorker();
+ delete ready_.exchange(nullptr, std::memory_order_acq_rel);
+ delete cur_; delete fade_; delete ramp_; delete xfOld_;
+ cur_ = fade_ = ramp_ = xfOld_ = nullptr;
+ for (auto*& k : spill_) { delete k; k = nullptr; }
+ drainRetired();
+ }
+ Chamber(const Chamber&) = delete;
+ Chamber& operator=(const Chamber&) = delete;
+
+ // ---- lifecycle ---------------------------------------------------------------
+ void setSampleRate(double sr, int32_t /*maxBlock*/) override {
+ const double nsr = sr > 0 ? sr : 44100.0;
+ if (prepared_ && nsr == sr_) return; // re-prepare at the same rate keeps tails + kernels
+ sr_ = nsr; srA_.store(nsr, std::memory_order_relaxed);
+ algo_.prepare(sr_);
+ for (auto* d : { &convPre_[0], &convPre_[1], &algoPre_[0], &algoPre_[1] }) d->init(static_cast<int>(2.6 * sr_) + 8);
+ convPreCur_ = algoPreCur_ = -1.0f;
+ for (auto& b : eq_) b.clear();
+ duckEnv_ = 0.0f; duckGain_ = 1.0f; msLp1_[0] = msLp1_[1] = 0.0f;
+ // Not concurrent with process(): install a kernel for the current params directly.
+ delete ready_.exchange(nullptr, std::memory_order_acq_rel);
+ delete cur_; delete fade_; delete ramp_; delete xfOld_;
+ cur_ = fade_ = ramp_ = xfOld_ = nullptr;
+ prepared_ = true;
+ rebuild(true);
+ startWorker();
+ }
+
+ void setTransport(double /*beatStart*/, double spb, bool /*playing*/) override { if (spb > 1.0) spb_ = spb; }
+
+ // ---- DSP ---------------------------------------------------------------------
+ void process(float* buf, int32_t frames) override {
+ if (!prepared_ || frames <= 0) return;
+ const auto t0 = std::chrono::steady_clock::now();
+ flushSpill();
+ if (!xfOld_) if (auto* k = ready_.exchange(nullptr, std::memory_order_acq_rel)) install(k);
+
+ const double sr = sr_;
+ // ---- block parameters ----
+ const float blend = get(Blend);
+ const float mix = get(DryWet);
+ const bool convOn = get(ConvOn) >= 0.5f, algoOn = get(AlgoOn) >= 0.5f;
+ const float dryLvl = 2.0f * get(DryLevel) * get(DryLevel);
+ const bool serial = get(Routing) >= 0.5f;
+ const bool freeze = get(Freeze) >= 0.5f, freezeIn = get(FreezeIn) >= 0.5f;
+ const bool wetOnly = get(WetOnly) >= 0.5f;
+ const int eqPos = std::clamp(static_cast<int>(std::lround(get(EqPosition) * 2.0f)), 0, 2);
+ const float outGain = std::pow(10.0f, (-24.0f + 36.0f * get(Output)) / 20.0f);
+ const float width = get(Width) * 2.0f;
+ const float monoV = get(BassMono);
+ const float monoC = monoV > 0.001f ? chamber::onePole(chamber::expMap(monoV, 30.0, 500.0), sr) : 0.0f;
+ const float duckDb = get(DuckAmount) * 24.0f;
+ const float duckRel = static_cast<float>(std::exp(-1.0 / (chamber::expMap(get(DuckRelease), 20.0, 2000.0) * 0.001 * sr)));
+ const float duckAtk = static_cast<float>(std::exp(-1.0 / (0.003 * sr)));
+ const float gc = std::sqrt(1.0f - blend), ga = std::sqrt(blend);
+ const float wetMix = wetOnly ? 1.0f : std::sin(mix * static_cast<float>(chamber::kPi) * 0.5f);
+ const float dryMix = wetOnly ? 0.0f : std::cos(mix * static_cast<float>(chamber::kPi) * 0.5f) * dryLvl;
+ const float sm = static_cast<float>(1.0 - std::exp(-1.0 / (0.015 * sr)));
+ const float preGlide = static_cast<float>(1.0 - std::exp(-1.0 / (0.03 * sr)));
+ const int lat = cur_ ? cur_->latency : 0;
+ const float convPreT = std::max(0.0f, predelaySamples(ConvPredelay, ConvSync) - static_cast<float>(lat));
+ const float algoPreT = predelaySamples(AlgoPredelay, AlgoSync);
+ if (convPreCur_ < 0.0f) convPreCur_ = convPreT;
+ if (algoPreCur_ < 0.0f) algoPreCur_ = algoPreT;
+ updateEq();
+
+ const chamber::Algo::Params ap = algoParams();
+
+ // Engines on/off ramp their contribution; a fully-off engine stops and forgets its tail.
+ if (convOn && !convActive_) { convActive_ = true; clearConv(); }
+ if (algoOn && !algoActive_) { algoActive_ = true; algo_.reset(); }
+
+ float wetPk = 0.0f, outPk[2] = { 0.0f, 0.0f }, inPk = 0.0f;
+ for (int32_t off = 0; off < frames; off += kChunk) {
+ const int n = std::min<int>(kChunk, frames - off);
+ float* b = buf + static_cast<size_t>(off) * 2;
+ // dry + ducking detector + the (freeze-gated) engine feed
+ for (int i = 0; i < n; ++i) {
+ const float l = b[i * 2], r = b[i * 2 + 1];
+ dL_[i] = l; dR_[i] = r;
+ const float a = std::max(std::fabs(l), std::fabs(r));
+ inPk = std::max(inPk, a);
+ duckEnv_ = a > duckEnv_ ? a + duckAtk * (duckEnv_ - a) : a + duckRel * (duckEnv_ - a);
+ feedG_ += sm * (((freeze && !freezeIn) ? 0.0f : 1.0f) - feedG_);
+ fL_[i] = l * feedG_; fR_[i] = r * feedG_;
+ }
+ if (eqPos == 0) runEq(fL_, fR_, n);
+
+ // ---- convolution ----
+ std::fill(cL_, cL_ + n, 0.0f); std::fill(cR_, cR_ + n, 0.0f);
+ if (convActive_) {
+ for (int i = 0; i < n; ++i) {
+ convPreCur_ += preGlide * (convPreT - convPreCur_);
+ convPre_[0].push(fL_[i]); convPre_[1].push(fR_[i]);
+ tL_[i] = convPre_[0].lin(convPreCur_); tR_[i] = convPre_[1].lin(convPreCur_);
+ }
+ if (xfOld_) { // re-shaped IR: both kernels hear the input; hold the old until
+ // the new one's output is exact, then an equal-power crossfade
+ std::fill(xL_, xL_ + n, 0.0f); std::fill(xR_, xR_ + n, 0.0f);
+ xfOld_->process(tL_, tR_, xL_, xR_, n);
+ if (cur_) cur_->process(tL_, tR_, cL_, cR_, n);
+ for (int i = 0; i < n; ++i) {
+ const float a = std::clamp(static_cast<float>(xfPos_++ - xfWarm_) / kXfLen, 0.0f, 1.0f);
+ const float gn = std::sin(a * 1.5707963f), go = std::cos(a * 1.5707963f);
+ cL_[i] = cL_[i] * gn + xL_[i] * go; cR_[i] = cR_[i] * gn + xR_[i] * go;
+ }
+ if (xfPos_ >= xfWarm_ + kXfLen) { retire(xfOld_); xfOld_ = nullptr; }
+ } else if (cur_) cur_->process(tL_, tR_, cL_, cR_, n);
+ if (fade_) { fade_->process(nullptr, nullptr, cL_, cR_, n); if (fade_->silent()) { retire(fade_); fade_ = nullptr; } }
+ if (ramp_) {
+ std::fill(tL_, tL_ + n, 0.0f); std::fill(tR_, tR_ + n, 0.0f);
+ ramp_->process(nullptr, nullptr, tL_, tR_, n);
+ for (int i = 0; i < n; ++i) {
+ const float g = std::max(0.0f, 1.0f - static_cast<float>(rampPos_++) / kRampLen);
+ cL_[i] += tL_[i] * g; cR_[i] += tR_[i] * g;
+ }
+ if (rampPos_ >= kRampLen) { retire(ramp_); ramp_ = nullptr; }
+ }
+ }
+
+ // ---- algorithm ----
+ std::fill(aL_, aL_ + n, 0.0f); std::fill(aR_, aR_ + n, 0.0f);
+ if (algoActive_) {
+ const bool fromConv = serial && convActive_;
+ for (int i = 0; i < n; ++i) {
+ algoPreCur_ += preGlide * (algoPreT - algoPreCur_);
+ algoPre_[0].push(fromConv ? cL_[i] : fL_[i]); algoPre_[1].push(fromConv ? cR_[i] : fR_[i]);
+ tL_[i] = algoPre_[0].lin(algoPreCur_); tR_[i] = algoPre_[1].lin(algoPreCur_);
+ }
+ // Idle gate: silent input + a tail below −140 dB → skip the tank until sound returns.
+ float inPkA = 0.0f;
+ for (int i = 0; i < n; ++i) inPkA = std::max(inPkA, std::max(std::fabs(tL_[i]), std::fabs(tR_[i])));
+ if (inPkA > 0.0f || freeze || algoQuiet_ < kQuietSamples) {
+ algo_.process(tL_, tR_, aL_, aR_, n, ap);
+ float outPkA = 0.0f;
+ for (int i = 0; i < n; ++i) outPkA = std::max(outPkA, std::max(std::fabs(aL_[i]), std::fabs(aR_[i])));
+ algoQuiet_ = (inPkA == 0.0f && outPkA < 1e-7f) ? algoQuiet_ + n : 0;
+ if (algoQuiet_ >= kQuietSamples) algo_.reset(); // drop sub-audible residue
+ }
+ }
+
+ // ---- wet: blend → tail EQ → width / bass mono → ducking ----
+ for (int i = 0; i < n; ++i) {
+ convG_ += sm * ((convOn ? gc : 0.0f) - convG_);
+ algoG_ += sm * ((algoOn ? ga : 0.0f) - algoG_);
+ wL_[i] = cL_[i] * convG_ + aL_[i] * algoG_;
+ wR_[i] = cR_[i] * convG_ + aR_[i] * algoG_;
+ }
+ if (eqPos == 1) runEq(wL_, wR_, n);
+ for (int i = 0; i < n; ++i) {
+ const float mid = 0.5f * (wL_[i] + wR_[i]);
+ widthS_ += sm * (width - widthS_);
+ float side = 0.5f * (wL_[i] - wR_[i]) * widthS_;
+ if (monoC > 0.0f) { msLp1_[0] += monoC * (side - msLp1_[0]); msLp1_[1] += monoC * (msLp1_[0] - msLp1_[1]); side -= msLp1_[1]; }
+ float target = 1.0f;
+ if (duckDb > 0.01f) { // wet dips by up to Duck Amount as the input rises −42 → −12 dBFS
+ const float envDb = 20.0f * std::log10(std::max(1e-6f, duckEnv_));
+ target = std::pow(10.0f, -duckDb * std::clamp((envDb + 42.0f) / 30.0f, 0.0f, 1.0f) / 20.0f);
+ }
+ duckGain_ += sm * (target - duckGain_);
+ wetS_ += sm * (wetMix - wetS_);
+ dryS_ += sm * (dryMix - dryS_);
+ outS_ += sm * (outGain - outS_);
+ const float wl = chamber::softClip((mid + side) * duckGain_) * wetS_;
+ const float wr = chamber::softClip((mid - side) * duckGain_) * wetS_;
+ wetPk = std::max(wetPk, std::max(std::fabs(wl), std::fabs(wr)));
+ wL_[i] = wl + dL_[i] * dryS_;
+ wR_[i] = wr + dR_[i] * dryS_;
+ }
+ if (eqPos == 2) runEq(wL_, wR_, n);
+ for (int i = 0; i < n; ++i) {
+ const float l = wL_[i] * outS_, r = wR_[i] * outS_;
+ b[i * 2] = l; b[i * 2 + 1] = r;
+ outPk[0] = std::max(outPk[0], std::fabs(l)); outPk[1] = std::max(outPk[1], std::fabs(r));
+ }
+ }
+
+ // Engines that finished ramping out stop (and drop their tails).
+ if (!convOn && convActive_ && convG_ < 1e-4f) { convActive_ = false; convG_ = 0.0f; clearConv(); }
+ if (!algoOn && algoActive_ && algoG_ < 1e-4f) { algoActive_ = false; algoG_ = 0.0f; algo_.reset(); }
+
+ // ---- meters + CPU ----
+ const float dec = static_cast<float>(std::exp(-frames / (0.3 * sr)));
+ auto hold = [&](std::atomic<float>& a, float v) { a.store(std::max(v, a.load(std::memory_order_relaxed) * dec), std::memory_order_relaxed); };
+ hold(mWet_, wetPk); hold(mOutL_, outPk[0]); hold(mOutR_, outPk[1]); hold(mIn_, inPk);
+ mDuck_.store(-20.0f * std::log10(std::max(1e-6f, duckGain_)), std::memory_order_relaxed);
+ latA_.store(cur_ ? cur_->latency : 0, std::memory_order_relaxed);
+ kernA_.store((cur_ ? 1 : 0) + (fade_ ? 1 : 0) + (ramp_ ? 1 : 0) + (xfOld_ ? 1 : 0), std::memory_order_relaxed);
+ kernSecA_.store(cur_ ? cur_->seconds : 0.0f, std::memory_order_relaxed);
+ bpmA_.store(static_cast<float>(60.0 * sr / spb_), std::memory_order_relaxed);
+ const double el = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
+ cpuS_ = cpuS_ * 0.9 + (el / (frames / sr)) * 0.1;
+ cpuA_.store(static_cast<float>(cpuS_), std::memory_order_relaxed);
+ }
+
+ // ---- identity / params ---------------------------------------------------------
+ const char* displayName() const override { return "Nota Chamber"; }
+ int32_t builtinKind() const override { return 20; }
+ int32_t paramCount() const override { return kNumParams; }
+ const char* paramName(int32_t i) const override {
+ static const char* nm[kNumParams] = {
+ "Blend", "Dry/Wet", "Conv On", "Algo On", "Dry Level", "Routing",
+ "IR", "IR Start", "IR Decay", "IR Attack", "IR Size", "Conv Predelay", "Conv Sync", "IR Reverse", "IR True Stereo",
+ "Algo Mode", "Algo Decay", "Algo Size", "Algo Diffusion", "Algo Damping", "Algo Predelay", "Algo Sync", "Algo Low Decay", "Algo High Decay",
+ "Freeze", "Freeze In", "Algo Vintage", "Mod Rate", "Mod Depth", "Shimmer Amount", "Shimmer Pitch", "Shimmer Feedback",
+ "EQ Low Cut", "EQ Low Gain", "EQ High Shelf", "EQ High Cut", "EQ Position",
+ "Duck Amount", "Duck Release", "Output", "Width", "Bass Mono", "Quality", "Wet Only", "Zero Latency" };
+ return (i >= 0 && i < kNumParams) ? nm[i] : "";
+ }
+ float paramMin(int32_t) const override { return 0.0f; }
+ float paramMax(int32_t) const override { return 1.0f; }
+ float getParam(int32_t i) const override { return (i >= 0 && i < kNumParams) ? p_[i].load(std::memory_order_relaxed) : 0.0f; }
+ void setParam(int32_t i, float v) override {
+ if (i < 0 || i >= kNumParams) return;
+ p_[i].store(std::clamp(v, 0.0f, 1.0f), std::memory_order_relaxed);
+ }
+
+ // ---- telemetry ---------------------------------------------------------------
+ int32_t scopeRead(float* out, int32_t maxSamples) const override {
+ if (!out || maxSamples < kScope) return 0;
+ std::shared_ptr<const chamber::SourceIr> src;
+ { std::lock_guard<std::mutex> lk(srcMu_); src = shownSrc_; }
+ out[S_WetL] = mWet_.load(std::memory_order_relaxed);
+ out[S_WetR] = out[S_WetL];
+ out[S_OutL] = mOutL_.load(std::memory_order_relaxed);
+ out[S_OutR] = mOutR_.load(std::memory_order_relaxed);
+ out[S_DuckDb] = mDuck_.load(std::memory_order_relaxed);
+ out[S_Cpu] = cpuA_.load(std::memory_order_relaxed);
+ out[S_Latency] = static_cast<float>(latA_.load(std::memory_order_relaxed));
+ out[S_SampleRate] = static_cast<float>(srA_.load(std::memory_order_relaxed));
+ out[S_Building] = (pending_.load(std::memory_order_relaxed) || ready_.load(std::memory_order_relaxed)) ? 1.0f : 0.0f;
+ out[S_IrSeconds] = src ? src->seconds() : 0.0f;
+ out[S_IrRate] = src ? static_cast<float>(src->sampleRate) : 0.0f;
+ out[S_IrChannels] = src ? static_cast<float>(src->channels) : 0.0f;
+ out[S_KernelSeconds] = kernSecA_.load(std::memory_order_relaxed);
+ out[S_Bpm] = bpmA_.load(std::memory_order_relaxed);
+ out[S_Frozen] = get(Freeze) >= 0.5f ? 1.0f : 0.0f;
+ out[S_Block] = static_cast<float>(bigBlock(srA_.load(std::memory_order_relaxed)));
+ { std::lock_guard<std::mutex> lk(srcMu_); out[S_UserIr] = userIr_ ? 1.0f : 0.0f; }
+ out[S_InPeak] = mIn_.load(std::memory_order_relaxed);
+ out[S_Kernels] = static_cast<float>(kernA_.load(std::memory_order_relaxed));
+ { std::lock_guard<std::mutex> lk(srcMu_); out[S_ResultSeconds] = convEnvSec_; out[S_PreviewSeconds] = algoEnvSec_; }
+ out[S_PreviewGen] = static_cast<float>(previewGen_.load(std::memory_order_relaxed) % 1000000u);
+ return kScope;
+ }
+
+ // Peak envelopes for the card: layer 0 / 1 = the source IR left (LL) / right (RR) over its
+ // full length; layer 2 = the processed IR as convolved (S_ResultSeconds long); layer 3 = the
+ // algorithm's rendered impulse response (S_PreviewSeconds long). All normalised to 1.
+ int32_t layerWave(int32_t layer, float* out, int32_t maxSamples) const override {
+ if (!out || maxSamples <= 0) return 0;
+ if (layer == 2 || layer == 3) {
+ std::lock_guard<std::mutex> lk(srcMu_);
+ const auto& e = layer == 2 ? convEnv_ : algoEnv_;
+ if (e.empty()) return 0;
+ const size_t n = e.size();
+ for (int32_t k = 0; k < maxSamples; ++k) {
+ const size_t a = n * static_cast<size_t>(k) / static_cast<size_t>(maxSamples);
+ const size_t z = std::max(a + 1, n * static_cast<size_t>(k + 1) / static_cast<size_t>(maxSamples));
+ float pk = 0.0f;
+ for (size_t i = a; i < z && i < n; ++i) pk = std::max(pk, e[i]);
+ out[k] = pk;
+ }
+ return maxSamples;
+ }
+ std::shared_ptr<const chamber::SourceIr> src;
+ { std::lock_guard<std::mutex> lk(srcMu_); src = shownSrc_; }
+ if (!src || src->frames <= 0) return 0;
+ const int nc = src->channels;
+ const int c = layer <= 0 ? 0 : (nc >= 4 ? 3 : nc >= 2 ? 1 : 0);
+ const int64_t F = src->frames;
+ float peak = 1e-9f;
+ for (int64_t i = 0; i < F; ++i) peak = std::max(peak, std::fabs(src->data[static_cast<size_t>(i * nc + c)]));
+ for (int32_t k = 0; k < maxSamples; ++k) {
+ const int64_t a = F * k / maxSamples, z = std::max(a + 1, F * (k + 1) / maxSamples);
+ float pk = 0.0f;
+ for (int64_t i = a; i < z && i < F; ++i) pk = std::max(pk, std::fabs(src->data[static_cast<size_t>(i * nc + c)]));
+ out[k] = pk / peak;
+ }
+ return maxSamples;
+ }
+
+ std::string deviceText(int32_t id) const override {
+ if (id == T_IrList) {
+ std::string s;
+ for (int i = 0; i < chamber::kNumBuiltinIrs; ++i) {
+ const auto& sp = chamber::irSpec(i);
+ char len[32]; std::snprintf(len, sizeof(len), "%.1f", static_cast<double>(sp.length));
+ s += sp.name; s += '\t'; s += sp.category; s += '\t'; s += len; s += '\n';
+ }
+ return s;
+ }
+ std::lock_guard<std::mutex> lk(srcMu_);
+ if (id == T_UserName) return userIr_ ? userIr_->name : std::string{};
+ const int ir = irIndex();
+ if (id == T_IrName) {
+ if (ir < chamber::kNumBuiltinIrs) return chamber::irSpec(ir).name;
+ return userIr_ ? userIr_->name : std::string("User IR — none loaded");
+ }
+ if (id == T_IrCategory) return ir < chamber::kNumBuiltinIrs ? chamber::irSpec(ir).category : "USER";
+ return {};
+ }
+
+ // ---- user impulse response -------------------------------------------------------
+ bool loadFile(const std::string& path) override {
+ auto sb = decodeAudioFile(path);
+ if (!sb || sb->empty()) return false;
+ const int inCh = sb->channels;
+ const int ch = inCh >= 4 ? 4 : inCh >= 2 ? 2 : 1;
+ float peak = 0.0f;
+ for (float v : sb->samples) peak = std::max(peak, std::fabs(v));
+ if (peak <= 1e-9f) return false;
+ int64_t first = 0; // skip leading silence (below −60 dB of the peak)
+ while (first < sb->frames) {
+ bool hit = false;
+ for (int c = 0; c < inCh; ++c) if (std::fabs(sb->samples[static_cast<size_t>(first * inCh + c)]) > peak * 1e-3f) { hit = true; break; }
+ if (hit) break;
+ ++first;
+ }
+ first = std::max<int64_t>(0, first - 8);
+ const double srcSr = sb->sourceSampleRate > 0 ? sb->sourceSampleRate : 44100.0;
+ const int64_t frames = std::min<int64_t>(sb->frames - first, static_cast<int64_t>(kMaxUserSec * srcSr));
+ if (frames < 8) return false;
+ auto ir = std::make_shared<chamber::SourceIr>();
+ ir->channels = ch; ir->frames = frames; ir->sampleRate = srcSr; ir->category = "USER";
+ std::string nm = path;
+ if (auto sl = nm.find_last_of("/\\"); sl != std::string::npos) nm = nm.substr(sl + 1);
+ if (auto dot = nm.find_last_of('.'); dot != std::string::npos && dot > 0) nm = nm.substr(0, dot);
+ ir->name = nm;
+ ir->data.resize(static_cast<size_t>(frames) * ch);
+ for (int64_t i = 0; i < frames; ++i)
+ for (int c = 0; c < ch; ++c) ir->data[static_cast<size_t>(i * ch + c)] = sb->samples[static_cast<size_t>((first + i) * inCh + c)];
+ { std::lock_guard<std::mutex> lk(srcMu_); userIr_ = std::move(ir); }
+ userGen_.fetch_add(1, std::memory_order_relaxed);
+ p_[IrSelect].store(1.0f, std::memory_order_relaxed);
+ if (prepared_) rebuild(false);
+ return true;
+ }
+
+ // State blob: the user IR (if any). Always non-empty so a restore re-syncs the kernel.
+ std::vector<uint8_t> getState() const override {
+ std::shared_ptr<const chamber::SourceIr> u;
+ { std::lock_guard<std::mutex> lk(srcMu_); u = userIr_; }
+ std::vector<uint8_t> s;
+ auto pU = [&](uint32_t v) { for (int b = 0; b < 4; ++b) s.push_back(static_cast<uint8_t>(v >> (8 * b))); };
+ auto pF = [&](float f) { uint32_t v; std::memcpy(&v, &f, 4); pU(v); };
+ pU(kMagic); pU(1u); pU(u ? 1u : 0u);
+ if (u) {
+ pU(static_cast<uint32_t>(u->name.size()));
+ s.insert(s.end(), u->name.begin(), u->name.end());
+ pF(static_cast<float>(u->sampleRate));
+ pU(static_cast<uint32_t>(u->channels));
+ pU(static_cast<uint32_t>(u->frames));
+ s.reserve(s.size() + u->data.size() * 4);
+ for (float v : u->data) pF(v);
+ }
+ return s;
+ }
+ void setState(const uint8_t* data, int32_t size) override {
+ if (!data || size < 12) return;
+ size_t off = 0;
+ const size_t n = static_cast<size_t>(size);
+ auto gU = [&](uint32_t& v) { if (off + 4 > n) return false; v = 0; for (int b = 0; b < 4; ++b) v |= static_cast<uint32_t>(data[off++]) << (8 * b); return true; };
+ auto gF = [&](float& f) { uint32_t v; if (!gU(v)) return false; std::memcpy(&f, &v, 4); return true; };
+ uint32_t magic = 0, ver = 0, has = 0;
+ if (!gU(magic) || magic != kMagic || !gU(ver) || !gU(has)) return;
+ std::shared_ptr<chamber::SourceIr> ir;
+ if (has) {
+ uint32_t nl = 0, ch = 0, frames = 0; float sr = 0.0f;
+ if (!gU(nl) || off + nl > n) return;
+ std::string name(reinterpret_cast<const char*>(data + off), nl); off += nl;
+ if (!gF(sr) || !gU(ch) || !gU(frames)) return;
+ if (ch < 1 || ch > 4 || sr <= 0.0f || frames == 0 || off + static_cast<size_t>(frames) * ch * 4 > n) return;
+ ir = std::make_shared<chamber::SourceIr>();
+ ir->name = name; ir->category = "USER"; ir->sampleRate = sr; ir->channels = static_cast<int>(ch); ir->frames = frames;
+ ir->data.resize(static_cast<size_t>(frames) * ch);
+ for (auto& v : ir->data) gF(v);
+ }
+ { std::lock_guard<std::mutex> lk(srcMu_); userIr_ = std::move(ir); }
+ userGen_.fetch_add(1, std::memory_order_relaxed);
+ if (prepared_) rebuild(false); // synchronous: the restored params + IR are live on return
+ }
+
+private:
+ static constexpr int kChunk = 64;
+ static constexpr int kRampLen = 1024;
+ static constexpr int kXfLen = 1536;
+ static constexpr int kQuietSamples = 4096;
+ static constexpr double kMaxUserSec = 20.0;
+ static constexpr uint32_t kMagic = 0x424D4843u; // "CHMB"
+
+ float get(int i) const { return p_[i].load(std::memory_order_relaxed); }
+ int irIndex() const { return std::clamp(static_cast<int>(std::lround(get(IrSelect) * (kIrCount - 1))), 0, kIrCount - 1); }
+ int qualityIndex() const { return std::clamp(static_cast<int>(std::lround(get(Quality) * 2.0f)), 0, 2); }
+ float shimRatio() const {
+ static const float r[3] = { 0.5f, 1.4983071f, 2.0f }; // −12 · +7 · +12 semitones
+ return r[std::clamp(static_cast<int>(std::lround(get(ShimmerPitch) * 2.0f)), 0, 2)];
+ }
+ static int bigBlock(double sr) { return sr <= 50000.0 ? 1024 : sr <= 100000.0 ? 2048 : 4096; }
+
+ float predelaySamples(int timeParam, int syncParam) const {
+ static const double beats[kSyncDivs] = { 1.0 / 16, 1.0 / 12, 1.0 / 8, 1.0 / 6, 1.0 / 4, 1.0 / 3, 3.0 / 8, 1.0 / 2, 2.0 / 3, 3.0 / 4, 1.0, 1.5, 2.0 };
+ const float v = get(timeParam);
+ double s;
+ if (get(syncParam) >= 0.5f) s = beats[std::clamp(static_cast<int>(std::lround(v * (kSyncDivs - 1))), 0, kSyncDivs - 1)] * spb_;
+ else s = 0.5 * v * v * sr_; // 0..500 ms, quadratic
+ return static_cast<float>(std::clamp(s, 0.0, 2.5 * sr_));
+ }
+
+ // ---- EQ ----
+ void updateEq() {
+ const float v[4] = { get(EqLowCut), get(EqLowGain), get(EqHighShelf), get(EqHighCut) };
+ if (v[0] == eqV_[0] && v[1] == eqV_[1] && v[2] == eqV_[2] && v[3] == eqV_[3] && eqSr_ == sr_) return;
+ const bool wasOn[4] = { eqOn_[0], eqOn_[1], eqOn_[2], eqOn_[3] };
+ const double lc = chamber::expMap(v[0], 20.0, 2000.0), hc = chamber::expMap(v[3], 1000.0, 20000.0);
+ const double lg = (v[1] - 0.5) * 36.0, hg = (v[2] - 0.5) * 36.0;
+ eqOn_[0] = v[0] > 0.001f; eqOn_[1] = std::fabs(lg) > 0.05; eqOn_[2] = std::fabs(hg) > 0.05; eqOn_[3] = v[3] < 0.999f && hc < sr_ * 0.45;
+ eq_[0].hp(lc, sr_);
+ eq_[1].lowShelf(std::max(250.0, lc * 2.0), lg, sr_);
+ eq_[2].highShelf(std::min(4000.0, hc * 0.5), hg, sr_);
+ eq_[3].lp(std::min(hc, sr_ * 0.45), sr_);
+ for (int i = 0; i < 4; ++i) if (eqOn_[i] && !wasOn[i]) eq_[i].clear();
+ for (int i = 0; i < 4; ++i) eqV_[i] = v[i];
+ eqSr_ = sr_;
+ }
+ void runEq(float* l, float* r, int n) {
+ for (int s = 0; s < 4; ++s) {
+ if (!eqOn_[s]) continue;
+ auto& b = eq_[s];
+ for (int i = 0; i < n; ++i) { l[i] = b.run(0, l[i]); r[i] = b.run(1, r[i]); }
+ }
+ }
+
+ // ---- kernels (audio thread side) ----
+ void install(chamber::ConvKernel* k) {
+ if (k->sampleRate != sr_) { retire(k); return; } // built for a rate we left
+ if (!cur_ || !convActive_) { // nothing sounding: just swap
+ retire(cur_); cur_ = k;
+ retire(fade_); fade_ = nullptr; retire(ramp_); ramp_ = nullptr;
+ return;
+ }
+ if (k->compatible(*cur_)) { // same layout: morph the whole tail
+ k->transplant(*cur_);
+ xfOld_ = cur_; cur_ = k; xfPos_ = 0; xfWarm_ = k->warmup();
+ return;
+ }
+ // Structural change (zero latency / true stereo / length class): the old kernel rings
+ // out what it already heard while the new one starts clean; a third ramps away.
+ if (ramp_) retire(ramp_);
+ ramp_ = fade_; rampPos_ = 0;
+ fade_ = cur_;
+ cur_ = k;
+ }
+ void clearConv() {
+ if (cur_) cur_->clear();
+ retire(fade_); fade_ = nullptr;
+ retire(ramp_); ramp_ = nullptr;
+ retire(xfOld_); xfOld_ = nullptr;
+ }
+ void retire(chamber::ConvKernel* k) {
+ if (!k) return;
+ const uint32_t h = rHead_.load(std::memory_order_relaxed);
+ if (h - rTail_.load(std::memory_order_acquire) < kRing) {
+ ring_[h % kRing] = k;
+ rHead_.store(h + 1, std::memory_order_release);
+ return;
+ }
+ for (auto*& s : spill_) if (!s) { s = k; return; }
+ // Ring and spill both full: the worker hasn't run for 40 retirements. Unreachable in
+ // practice (it drains every 10 ms); leaking one kernel beats freeing on the audio thread.
+ }
+ void flushSpill() {
+ for (auto*& s : spill_) {
+ if (!s) continue;
+ const uint32_t h = rHead_.load(std::memory_order_relaxed);
+ if (h - rTail_.load(std::memory_order_acquire) >= kRing) return;
+ ring_[h % kRing] = s; s = nullptr;
+ rHead_.store(h + 1, std::memory_order_release);
+ }
+ }
+
+ // ---- kernels (worker / message thread side) ----
+ struct Sig {
+ int ir = -1, start = 0, end = 0, attack = 0, size = 0, rev = 0, ts = 0, zl = 0, q = 0, sr = 0;
+ uint32_t gen = 0;
+ bool operator==(const Sig& o) const {
+ return ir == o.ir && start == o.start && end == o.end && attack == o.attack && size == o.size && rev == o.rev
+ && ts == o.ts && zl == o.zl && q == o.q && sr == o.sr && gen == o.gen;
+ }
+ bool operator!=(const Sig& o) const { return !(*this == o); }
+ };
+ chamber::Algo::Params algoParams() const {
+ chamber::Algo::Params ap;
+ ap.mode = std::clamp(static_cast<int>(std::lround(get(AlgoMode) * 3.0f)), 0, 3);
+ ap.decay = static_cast<float>(chamber::expMap(get(AlgoDecay), 0.2, 20.0));
+ ap.size = static_cast<float>(chamber::expMap(get(AlgoSize), 0.4, 2.5));
+ ap.diffuse = get(AlgoDiffusion);
+ ap.damp = static_cast<float>(chamber::expMap(get(AlgoDamping), 500.0, 18000.0));
+ ap.lowMul = static_cast<float>(chamber::expMap(get(AlgoLowDecay), 0.25, 4.0));
+ ap.highMul = static_cast<float>(chamber::expMap(get(AlgoHighDecay), 0.25, 4.0));
+ ap.rate = static_cast<float>(chamber::expMap(get(ModRate), 0.05, 8.0));
+ ap.depth = get(ModDepth);
+ ap.freeze = get(Freeze) >= 0.5f;
+ ap.vintage = get(AlgoVintage) >= 0.5f;
+ ap.cubic = qualityIndex() == 2;
+ ap.shimAmt = get(ShimmerAmount);
+ ap.shimRatio = shimRatio();
+ ap.shimFb = get(ShimmerFeedback) >= 0.5f;
+ return ap;
+ }
+
+ // ---- previews for the card (worker thread): what the engines actually sound like ----
+ static constexpr int kEnvBins = 512;
+ static constexpr double kPreviewSr = 16000.0;
+ // Peak envelope of `chans` over kEnvBins, normalised to its maximum.
+ static std::vector<float> envelope(const std::vector<std::vector<float>>& chans, const std::vector<int>& use) {
+ std::vector<float> env(kEnvBins, 0.0f);
+ if (chans.empty() || chans[0].empty()) return env;
+ const size_t n = chans[0].size();
+ float peak = 1e-12f;
+ for (int k = 0; k < kEnvBins; ++k) {
+ const size_t a = n * static_cast<size_t>(k) / kEnvBins, z = std::max(a + 1, n * static_cast<size_t>(k + 1) / kEnvBins);
+ float pk = 0.0f;
+ for (int c : use) { const auto& v = chans[static_cast<size_t>(c)]; for (size_t i = a; i < z && i < n; ++i) pk = std::max(pk, std::fabs(v[i])); }
+ env[static_cast<size_t>(k)] = pk; peak = std::max(peak, pk);
+ }
+ for (auto& v : env) v /= peak;
+ return env;
+ }
+ std::vector<int> previewSignature() const {
+ static const int ids[] = { AlgoMode, AlgoDecay, AlgoSize, AlgoDiffusion, AlgoDamping, AlgoLowDecay, AlgoHighDecay, Freeze,
+ AlgoVintage, ModRate, ModDepth, ShimmerAmount, ShimmerPitch, ShimmerFeedback };
+ std::vector<int> v;
+ for (int id : ids) v.push_back(static_cast<int>(std::lround(get(id) * 2000.0f)));
+ return v;
+ }
+ // Render the algorithm's impulse response offline (a private tank at 16 kHz) and keep its
+ // envelope — the card's decay graph draws the real echogram, not a model of it.
+ void renderAlgoPreview() {
+ const auto p = algoParams();
+ if (!preview_) { preview_ = std::make_unique<chamber::Algo>(); preview_->prepare(kPreviewSr); }
+ preview_->restart();
+ const double rt = p.freeze ? 3.0 : p.decay * std::max(1.0f, std::max(p.lowMul, p.highMul));
+ const double secs = std::clamp(rt * 1.15 + 0.1, 0.4, 12.0);
+ const size_t frames = static_cast<size_t>(secs * kPreviewSr);
+ std::vector<std::vector<float>> out(2, std::vector<float>(frames, 0.0f));
+ float inL[256] = {}, inR[256] = {};
+ for (size_t off = 0; off < frames; off += 256) {
+ const int n = static_cast<int>(std::min<size_t>(256, frames - off));
+ inL[0] = inR[0] = off == 0 ? 1.0f : 0.0f;
+ preview_->process(inL, inR, &out[0][off], &out[1][off], n, p);
+ }
+ auto env = envelope(out, { 0, 1 });
+ std::lock_guard<std::mutex> lk(srcMu_);
+ algoEnv_ = std::move(env); algoEnvSec_ = static_cast<float>(secs);
+ previewGen_.fetch_add(1, std::memory_order_relaxed);
+ }
+
+ Sig signature() const {
+ auto q = [](float v) { return static_cast<int>(std::lround(v * 4000.0f)); };
+ Sig s;
+ s.ir = irIndex(); s.start = q(get(IrStart)); s.end = q(get(IrDecay)); s.attack = q(get(IrAttack)); s.size = q(get(IrSize));
+ s.rev = get(IrReverse) >= 0.5f; s.ts = get(IrTrueStereo) >= 0.5f; s.zl = get(ZeroLatency) >= 0.5f; s.q = qualityIndex();
+ s.sr = static_cast<int>(std::lround(srA_.load(std::memory_order_relaxed)));
+ s.gen = userGen_.load(std::memory_order_relaxed);
+ return s;
+ }
+
+ std::unique_ptr<chamber::ConvKernel> makeKernel(const Sig& s) {
+ using chamber::ConvKernel;
+ const double sr = static_cast<double>(s.sr);
+ std::shared_ptr<const chamber::SourceIr> src;
+ if (s.ir < chamber::kNumBuiltinIrs) src = chamber::builtinIr(s.ir);
+ else { std::lock_guard<std::mutex> lk(srcMu_); src = userIr_; }
+ { std::lock_guard<std::mutex> lk(srcMu_); shownSrc_ = src; }
+ std::vector<int> chans;
+ std::vector<ConvKernel::Path> paths;
+ int nIn = 2; bool mono = false;
+ const int nc = src ? src->channels : 0;
+ if (nc == 1) { chans = { 0 }; paths = { { 0, 0, 0 }, { 1, 1, 0 } }; }
+ else if (nc == 2) {
+ chans = { 0, 1 };
+ if (s.ts) { nIn = 1; mono = true; paths = { { 0, 0, 0 }, { 0, 1, 1 } }; }
+ else paths = { { 0, 0, 0 }, { 1, 1, 1 } };
+ } else if (nc >= 4) {
+ if (s.ts) { chans = { 0, 1, 2, 3 }; paths = { { 0, 0, 0 }, { 0, 1, 1 }, { 1, 0, 2 }, { 1, 1, 3 } }; }
+ else { chans = { 0, 3 }; paths = { { 0, 0, 0 }, { 1, 1, 1 } }; }
+ }
+ chamber::Shape sh;
+ sh.start = s.start / 4000.0f; sh.end = s.end / 4000.0f;
+ sh.attackMs = 500.0f * (s.attack / 4000.0f) * (s.attack / 4000.0f);
+ sh.size = static_cast<float>(chamber::expMap(s.size / 4000.0, 0.5, 2.0));
+ sh.reverse = s.rev != 0;
+ static const double maxSec[3] = { 3.0, 6.0, 10.0 };
+ std::vector<std::vector<float>> h;
+ if (src && nc > 0) h = chamber::shapeIr(*src, chans, sh, sr, maxSec[std::clamp(s.q, 0, 2)]);
+ { // the processed response, as the card's RESULT lane (direct paths only)
+ std::vector<int> use;
+ if (!h.empty()) { use.push_back(0); if (h.size() > 1) use.push_back(h.size() == 4 ? 3 : 1); }
+ auto env = envelope(h, use);
+ std::lock_guard<std::mutex> lk(srcMu_);
+ convEnv_ = h.empty() ? std::vector<float>{} : std::move(env);
+ convEnvSec_ = h.empty() ? 0.0f : static_cast<float>(h[0].size() / sr);
+ previewGen_.fetch_add(1, std::memory_order_relaxed);
+ }
+ return ConvKernel::build(h, paths, nIn, mono, s.zl != 0, bigBlock(sr), sr);
+ }
+
+ // Build a kernel for the current params when they changed. `direct` installs it as the
+ // current kernel (only while process() can't run); otherwise it's handed to the audio thread.
+ bool rebuild(bool direct) {
+ std::lock_guard<std::mutex> lk(buildMu_);
+ const Sig s = signature();
+ if (!direct && built_ && s == builtSig_) { pending_.store(false, std::memory_order_relaxed); return false; }
+ pending_.store(true, std::memory_order_relaxed);
+ auto k = makeKernel(s);
+ builtSig_ = s; built_ = true;
+ if (direct) { delete cur_; cur_ = k.release(); }
+ else delete ready_.exchange(k.release(), std::memory_order_acq_rel); // an unclaimed older one is ours to free
+ pending_.store(false, std::memory_order_relaxed);
+ return true;
+ }
+
+ void startWorker() {
+ if (worker_.joinable()) return;
+ stop_.store(false);
+ worker_ = std::thread([this] { workerLoop(); });
+ }
+ void stopWorker() {
+ if (!worker_.joinable()) return;
+ { std::lock_guard<std::mutex> lk(wMu_); stop_.store(true); }
+ wCv_.notify_all();
+ worker_.join();
+ }
+ void workerLoop() {
+ using clock = std::chrono::steady_clock;
+ auto last = clock::now() - std::chrono::seconds(1), lastPreview = last;
+ while (!stop_.load()) {
+ {
+ std::unique_lock<std::mutex> lk(wMu_);
+ wCv_.wait_for(lk, std::chrono::milliseconds(10), [this] { return stop_.load(); });
+ }
+ if (stop_.load()) break;
+ drainRetired();
+ if (clock::now() - lastPreview >= std::chrono::milliseconds(40)) {
+ auto ps = previewSignature();
+ if (ps != previewSig_) { previewSig_ = std::move(ps); renderAlgoPreview(); lastPreview = clock::now(); }
+ }
+ if (clock::now() - last < std::chrono::milliseconds(25)) continue; // coalesce drags
+ bool changed;
+ { std::lock_guard<std::mutex> lk(buildMu_); changed = !built_ || signature() != builtSig_; }
+ if (changed && rebuild(false)) last = clock::now();
+ }
+ }
+ void drainRetired() {
+ uint32_t t = rTail_.load(std::memory_order_relaxed);
+ const uint32_t h = rHead_.load(std::memory_order_acquire);
+ while (t != h) { delete ring_[t % kRing]; ring_[t % kRing] = nullptr; ++t; }
+ rTail_.store(t, std::memory_order_release);
+ }
+
+ // ---- state ----
+ std::atomic<float> p_[kNumParams] = {};
+ double sr_ = 44100.0, spb_ = 22050.0;
+ bool prepared_ = false;
+ std::atomic<double> srA_{44100.0};
+
+ chamber::Algo algo_;
+ chamber::DLine convPre_[2], algoPre_[2];
+ float convPreCur_ = -1.0f, algoPreCur_ = -1.0f;
+ chamber::Biquad eq_[4];
+ bool eqOn_[4] = {};
+ float eqV_[4] = { -1.0f, -1.0f, -1.0f, -1.0f };
+ double eqSr_ = 0.0;
+ bool convActive_ = true, algoActive_ = true;
+ float convG_ = 0.0f, algoG_ = 0.0f, feedG_ = 1.0f, wetS_ = 0.0f, dryS_ = 1.0f, outS_ = 1.0f, widthS_ = 1.0f;
+ float duckEnv_ = 0.0f, duckGain_ = 1.0f, msLp1_[2] = {};
+ double cpuS_ = 0.0;
+ int algoQuiet_ = 0;
+ float dL_[kChunk] = {}, dR_[kChunk] = {}, fL_[kChunk] = {}, fR_[kChunk] = {}, cL_[kChunk] = {}, cR_[kChunk] = {};
+ float aL_[kChunk] = {}, aR_[kChunk] = {}, tL_[kChunk] = {}, tR_[kChunk] = {}, wL_[kChunk] = {}, wR_[kChunk] = {};
+ float xL_[kChunk] = {}, xR_[kChunk] = {};
+
+ // kernels: audio-thread owned (cur_ / fade_ / ramp_), handed over through ready_,
+ // returned through the SPSC ring (audio → worker) for deletion.
+ chamber::ConvKernel* cur_ = nullptr;
+ chamber::ConvKernel* fade_ = nullptr;
+ chamber::ConvKernel* ramp_ = nullptr;
+ chamber::ConvKernel* xfOld_ = nullptr;
+ int rampPos_ = 0, xfPos_ = 0, xfWarm_ = 0;
+ std::atomic<chamber::ConvKernel*> ready_{nullptr};
+ static constexpr uint32_t kRing = 32;
+ chamber::ConvKernel* ring_[kRing] = {};
+ std::atomic<uint32_t> rHead_{0}, rTail_{0};
+ chamber::ConvKernel* spill_[8] = {};
+
+ // worker
+ std::thread worker_;
+ std::atomic<bool> stop_{false};
+ std::mutex wMu_;
+ std::condition_variable wCv_;
+ std::mutex buildMu_;
+ Sig builtSig_;
+ bool built_ = false;
+ std::atomic<bool> pending_{false};
+
+ // IR sources (message / worker threads; never touched by process()).
+ mutable std::mutex srcMu_;
+ std::shared_ptr<const chamber::SourceIr> userIr_, shownSrc_;
+ std::vector<float> convEnv_, algoEnv_; // RESULT lane + algorithm echogram (srcMu_)
+ float convEnvSec_ = 0.0f, algoEnvSec_ = 0.0f;
+ std::atomic<uint32_t> previewGen_{0};
+ std::unique_ptr<chamber::Algo> preview_; // worker-only offline tank
+ std::vector<int> previewSig_; // worker-only
+ std::atomic<uint32_t> userGen_{0};
+
+ // meters
+ std::atomic<float> mWet_{0.0f}, mOutL_{0.0f}, mOutR_{0.0f}, mIn_{0.0f}, mDuck_{0.0f}, cpuA_{0.0f}, kernSecA_{0.0f}, bpmA_{120.0f};
+ std::atomic<int> latA_{0}, kernA_{0};
+};
+
+} // namespace nota
diff --git a/src/native/nota.engine/src/Device.h b/src/native/nota.engine/src/Device.h
index ec5a7e5d..c79c591a 100644
--- a/src/native/nota.engine/src/Device.h
+++ b/src/native/nota.engine/src/Device.h
@@ -107,6 +107,14 @@ public:
// maxSamples peak bins of layer's buffer, oldest→newest, returning the count.
virtual int32_t layerWave(int32_t /*layer*/, float* /*out*/, int32_t /*maxSamples*/) const { return 0; }
+ // Devices that carry a named resource (the Chamber's impulse response): an id-specific
+ // text (resource name, category, a catalogue listing …); empty by default. Message thread.
+ virtual std::string deviceText(int32_t /*id*/) const { return {}; }
+
+ // Load an auxiliary audio file into the device (the Chamber's user impulse response).
+ // Returns false when the device takes no file or it can't be decoded. Message thread.
+ virtual bool loadFile(const std::string& /*path*/) { return false; }
+
// Sidechain / signal routing (Phase B). A device may key its processing off
// another track's signal. sidechainSourceTrackId() reports the chosen source
// track (-1 = none); the engine assigns a routing slot and, right before each
diff --git a/src/native/nota.engine/src/Engine.h b/src/native/nota.engine/src/Engine.h
index 94b9d587..b8c566c9 100644
--- a/src/native/nota.engine/src/Engine.h
+++ b/src/native/nota.engine/src/Engine.h
@@ -540,6 +540,9 @@ public:
// Opaque device state blob (looper PCM etc.) for project save/restore.
int32_t deviceGetState(int32_t trackId, int32_t deviceIndex, uint8_t* out, int32_t cap) const;
void deviceSetState(int32_t trackId, int32_t deviceIndex, const uint8_t* data, int32_t size);
+ // Load an auxiliary file into a device (the Chamber's user IR) / read its resource text.
+ bool deviceLoadFile(int32_t trackId, int32_t deviceIndex, const std::string& path);
+ std::string deviceText(int32_t trackId, int32_t deviceIndex, int32_t id) const;
int32_t deviceParamCount(int32_t trackId, int32_t deviceIndex) const;
const char* deviceParamName(int32_t trackId, int32_t deviceIndex, int32_t paramIndex) const;
float deviceParamMin(int32_t trackId, int32_t deviceIndex, int32_t paramIndex) const;
diff --git a/src/native/nota.engine/src/Engine_Devices.cpp b/src/native/nota.engine/src/Engine_Devices.cpp
index a6ab80a9..c94c79aa 100644
--- a/src/native/nota.engine/src/Engine_Devices.cpp
+++ b/src/native/nota.engine/src/Engine_Devices.cpp
@@ -20,6 +20,7 @@
#include "Forge.h"
#include "AutoGain.h"
#include "Shutter.h"
+#include "Chamber.h"
#include "Ceiling.h"
#include "Strata.h"
#include "Vintage.h"
@@ -427,6 +428,7 @@ int32_t Engine::addTrackBuiltinDevice(int32_t trackId, int32_t kind) {
else if (kind == 17) dev = std::make_shared<Forge>();
else if (kind == 18) dev = std::make_shared<AutoGain>();
else if (kind == 19) dev = std::make_shared<Shutter>();
+ else if (kind == 20) dev = std::make_shared<Chamber>();
else return -1;
dev->setSampleRate(transport_.sampleRate() > 0 ? transport_.sampleRate() : 44100.0, kMaxBlock);
if (kind == 5) if (auto* rk = dynamic_cast<RackDevice*>(dev.get())) rk->addChain(-1); // one pass-through chain
@@ -488,6 +490,7 @@ std::shared_ptr<Device> Engine::cloneDevice(const Device& src) const {
case 17: d = std::make_shared<Forge>(); break;
case 18: d = std::make_shared<AutoGain>(); break;
case 19: d = std::make_shared<Shutter>(); break;
+ case 20: d = std::make_shared<Chamber>(); break;
default: d = src.clone(); break; // hosted plugin
}
if (!d) return nullptr;
@@ -562,6 +565,7 @@ static std::shared_ptr<Device> makeBuiltinDevice(int32_t kind) {
case 17: return std::make_shared<Forge>();
case 18: return std::make_shared<AutoGain>();
case 19: return std::make_shared<Shutter>();
+ case 20: return std::make_shared<Chamber>();
default: return nullptr; // Rack / plugin: no simple per-param default
}
}
@@ -782,6 +786,16 @@ void Engine::deviceSetState(int32_t trackId, int32_t deviceIndex, const uint8_t*
if (auto* d = deviceAt(trackId, deviceIndex)) d->setState(data, size);
}
+bool Engine::deviceLoadFile(int32_t trackId, int32_t deviceIndex, const std::string& path) {
+ auto* d = deviceAt(trackId, deviceIndex);
+ return d && d->loadFile(path);
+}
+
+std::string Engine::deviceText(int32_t trackId, int32_t deviceIndex, int32_t id) const {
+ auto* d = deviceAt(trackId, deviceIndex);
+ return d ? d->deviceText(id) : std::string{};
+}
+
void Engine::setDeviceSidechainSource(int32_t trackId, int32_t deviceIndex, int32_t sourceTrackId) {
if (auto* d = deviceAt(trackId, deviceIndex)) d->setSidechainSourceTrackId(sourceTrackId);
recomputeRouting();
diff --git a/src/native/nota.engine/src/RackCore.h b/src/native/nota.engine/src/RackCore.h
index d1ffc25c..282baf74 100644
--- a/src/native/nota.engine/src/RackCore.h
+++ b/src/native/nota.engine/src/RackCore.h
@@ -53,6 +53,7 @@
#include "Forge.h"
#include "AutoGain.h"
#include "Shutter.h"
+#include "Chamber.h"
#include <algorithm>
#include <atomic>
@@ -672,6 +673,7 @@ protected:
case 17: return std::make_shared<Forge>();
case 18: return std::make_shared<AutoGain>();
case 19: return std::make_shared<Shutter>();
+ case 20: return std::make_shared<Chamber>();
default: return nullptr; // 5 = Effect Rack (nesting) / plugin: not via this factory
}
}
diff --git a/src/native/nota.engine/src/nota_engine_device.cpp b/src/native/nota.engine/src/nota_engine_device.cpp
index d995c2a5..355aafa6 100644
--- a/src/native/nota.engine/src/nota_engine_device.cpp
+++ b/src/native/nota.engine/src/nota_engine_device.cpp
@@ -16,8 +16,10 @@
#include "Reverb.h"
#include "Utility.h"
+#include <algorithm>
#include <cmath>
#include <cstdio>
+#include <cstring>
#include <string>
#include <vector>
@@ -101,6 +103,21 @@ int32_t nota_device_get_state(const NotaEngine* e, int32_t track_id, int32_t dev
void nota_device_set_state(NotaEngine* e, int32_t track_id, int32_t device_index, const uint8_t* data, int32_t size) {
if (e) ENG(e)->deviceSetState(track_id, device_index, data, size);
}
+NotaResult nota_device_load_file(NotaEngine* e, int32_t track_id, int32_t device_index, const char* path) {
+ if (!e || !path) return NOTA_ERR_INVALID_ARG;
+ return ENG(e)->deviceLoadFile(track_id, device_index, path) ? NOTA_OK : NOTA_ERR_UNKNOWN;
+}
+int32_t nota_device_text(const NotaEngine* e, int32_t track_id, int32_t device_index, int32_t id, char* out, int32_t cap) {
+ if (!e) return 0;
+ const std::string s = CENG(e)->deviceText(track_id, device_index, id);
+ const int32_t n = static_cast<int32_t>(s.size());
+ if (out && cap > 0) {
+ const int32_t m = std::min(n, cap - 1);
+ std::memcpy(out, s.data(), static_cast<size_t>(m));
+ out[m] = '\0';
+ }
+ return n; // full length (probe with a null buffer, then fetch)
+}
// --- MIDI effects ---
int32_t nota_track_add_midi_effect(NotaEngine* e, int32_t t, int32_t kind) { return e ? ENG(e)->addTrackMidiEffect(t, kind) : -1; }
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index eed561e6..8a4f12c0 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -2466,6 +2466,213 @@ Console.WriteLine("-- Nota Shutter --");
Check(ge.DeviceGetParam(gt, gd, 0) > 0.7f, $"automation drives Shutter Threshold ({ge.DeviceGetParam(gt, gd, 0):F2})");
}
+// ============================ Nota Chamber =================================
+Console.WriteLine("-- Nota Chamber --");
+{
+ // Chamber = hybrid reverb (kind 20). Own engine. IR shaping rebuilds kernels on a worker
+ // thread, so the test waits a moment after IR-shaping edits before rendering.
+ const int Blend = 0, DryWet = 1, ConvOn = 2, AlgoOn = 3, Routing = 5, IrSelect = 6, IrSize = 10, AlgoMode = 15,
+ AlgoDecay = 16, Freeze = 24, ShimmerAmount = 29, EqPosition = 36, DuckAmount = 37, WetOnly = 43, ZeroLatency = 44;
+ using var ce = new NotaEngine();
+ ce.SetBpm(120); ce.SetTimeSignature(4, 4);
+ int ct = ce.AddInstrumentTrack();
+ ce.AddMidiClip(ct, 0.0, 8.0);
+ ce.SetClipNotes(ct, 0, new[] { new NotaNote(60, 0.0, 0.5, 0.8f) }); // a short note, then the tail
+ int cd = ce.AddBuiltinDevice(ct, 20);
+ Check(cd >= 0, "add built-in Nota Chamber");
+ Check(ce.DeviceName(ct, cd) == "Nota Chamber", $"name is Nota Chamber (got '{ce.DeviceName(ct, cd)}')");
+ Check(ce.TrackDeviceBuiltinKind(ct, cd) == 20, $"builtin kind is 20 (got {ce.TrackDeviceBuiltinKind(ct, cd)})");
+ int cpc = ce.DeviceParamCount(ct, cd);
+ Check(cpc == 45, $"Nota Chamber exposes 45 params (got {cpc})");
+ var cnames = Enumerable.Range(0, cpc).Select(i => ce.DeviceParamName(ct, cd, i)).ToList();
+ Check(cnames.Distinct().Count() == cpc && cnames.All(n => n.Length > 0), "Chamber param names are unique and non-empty");
+ ce.DeviceSetParam(ct, cd, AlgoDecay, 0.42f);
+ Check(Math.Abs(ce.DeviceGetParam(ct, cd, AlgoDecay) - 0.42f) < 1e-4, "Chamber param set/get round-trips");
+ ce.DeviceSetParam(ct, cd, AlgoDecay, ce.DeviceParamDefault(ct, cd, AlgoDecay));
+ var irs = ce.DeviceText(ct, cd, 10).Split('\n', StringSplitOptions.RemoveEmptyEntries);
+ Check(irs.Length == 16, $"Chamber lists 16 built-in IRs (got {irs.Length})");
+ Check(ce.DeviceText(ct, cd, 0) == "Concert Hall · Wide", $"default IR is Concert Hall · Wide (got '{ce.DeviceText(ct, cd, 0)}')");
+
+ const int N = 8192;
+ var cb = new float[N * 2];
+ var csc = new float[32];
+ // Render 6 blocks (~1.1 s at 44.1 k): the note ends at 0.25 s, so the last block is pure tail.
+ (bool fin, float tail, float all) RenderTail()
+ {
+ ce.Seek(0); ce.Play();
+ bool f = true; float t = 0, a = 0;
+ for (int k = 0; k < 6; k++)
+ {
+ ce.RenderOffline(cb, N);
+ foreach (var s in cb) if (!float.IsFinite(s)) { f = false; break; }
+ float r = Rms(cb, N); a = Math.Max(a, r); if (k == 5) t = r;
+ }
+ ce.StopTransport();
+ return (f, t, a);
+ }
+ void Settle() => System.Threading.Thread.Sleep(150); // let the IR worker publish a new kernel
+ ce.DeviceSetParam(ct, cd, WetOnly, 1f);
+ Settle();
+ var r0 = RenderTail();
+ Check(r0.fin && r0.tail > 1e-4f, $"Chamber renders a finite reverb tail (tail rms {r0.tail:F4})");
+ int cn = ce.DeviceScope(ct, cd, csc, csc.Length);
+ Check(cn == 22, $"Chamber scope returns 22 values (got {cn})");
+ Check(csc[6] == 0f && csc[9] > 2f && csc[11] == 4f, $"zero-latency kernel of a 4-ch built-in IR (lat {csc[6]}, {csc[9]:F1} s, {csc[11]} ch)");
+
+ // Card previews: the processed IR (layer 2) and the algorithm's rendered impulse response
+ // (layer 3) follow the params — Size stretches the result, Decay lengthens the echogram.
+ {
+ var pv = new float[128];
+ Check(ce.DeviceLayerWave(ct, cd, 2, pv, pv.Length) == 128 && ce.DeviceLayerWave(ct, cd, 3, pv, pv.Length) == 128, "Chamber exposes result + echogram previews");
+ ce.DeviceScope(ct, cd, csc, csc.Length);
+ float res0 = csc[19], echo0 = csc[20];
+ ce.DeviceSetParam(ct, cd, IrSize, 1f); ce.DeviceSetParam(ct, cd, AlgoDecay, 0.9f); Settle();
+ ce.DeviceScope(ct, cd, csc, csc.Length);
+ Check(csc[19] > res0 * 1.8f && csc[20] > echo0 * 2f, $"previews follow Size + Decay (result {res0:F2}→{csc[19]:F2} s, echogram {echo0:F2}→{csc[20]:F2} s)");
+ ce.DeviceSetParam(ct, cd, IrSize, 0.5f); ce.DeviceSetParam(ct, cd, AlgoDecay, ce.DeviceParamDefault(ct, cd, AlgoDecay)); Settle();
+ }
+
+ // Engines on their own, and each algorithm.
+ ce.DeviceSetParam(ct, cd, AlgoOn, 0f); ce.DeviceSetParam(ct, cd, Blend, 0f);
+ var rc = RenderTail();
+ Check(rc.fin && rc.tail > 1e-4f, $"convolution alone renders a tail ({rc.tail:F4})");
+ ce.DeviceSetParam(ct, cd, AlgoOn, 1f); ce.DeviceSetParam(ct, cd, ConvOn, 0f); ce.DeviceSetParam(ct, cd, Blend, 1f);
+ string[] modes = { "Dark Hall", "Plate", "Quartz", "Shimmer" };
+ for (int m = 0; m < 4; m++)
+ {
+ ce.DeviceSetParam(ct, cd, AlgoMode, m / 3f);
+ var ra = RenderTail();
+ Check(ra.fin && ra.tail > 1e-4f && ra.all < 4f, $"algorithm {modes[m]} renders a bounded tail ({ra.tail:F4}, peak rms {ra.all:F3})");
+ }
+ ce.DeviceSetParam(ct, cd, ShimmerAmount, 1f); ce.DeviceSetParam(ct, cd, AlgoDecay, 1f);
+ var rs = RenderTail();
+ Check(rs.fin && rs.all < 4f, $"max shimmer + max decay stays bounded (peak rms {rs.all:F3})");
+ ce.DeviceSetParam(ct, cd, ShimmerAmount, 0.5f); ce.DeviceSetParam(ct, cd, AlgoDecay, ce.DeviceParamDefault(ct, cd, AlgoDecay));
+ ce.DeviceSetParam(ct, cd, AlgoMode, 0f);
+
+ // Freeze holds the tail: with a short decay the free tail dies, the frozen one doesn't.
+ ce.DeviceSetParam(ct, cd, AlgoDecay, 0.2f);
+ var rFree = RenderTail();
+ ce.Seek(0); ce.Play();
+ ce.RenderOffline(cb, N); // the note plays into the tank
+ ce.DeviceSetParam(ct, cd, Freeze, 1f);
+ for (int k = 0; k < 5; k++) ce.RenderOffline(cb, N);
+ ce.StopTransport();
+ float frozen = Rms(cb, N);
+ Check(frozen > rFree.tail * 4 && frozen > 1e-4f, $"Freeze holds the algorithm tail (frozen {frozen:F4} vs free {rFree.tail:F5})");
+ ce.DeviceSetParam(ct, cd, Freeze, 0f);
+ ce.DeviceSetParam(ct, cd, AlgoDecay, ce.DeviceParamDefault(ct, cd, AlgoDecay));
+
+ // Serial routing, EQ positions, ducking, dry/wet mix.
+ ce.DeviceSetParam(ct, cd, ConvOn, 1f); ce.DeviceSetParam(ct, cd, Blend, 0.5f); ce.DeviceSetParam(ct, cd, Routing, 1f);
+ var rser = RenderTail();
+ Check(rser.fin && rser.tail > 1e-4f, $"serial routing (conv → algo) renders ({rser.tail:F4})");
+ ce.DeviceSetParam(ct, cd, Routing, 0f);
+ bool eqOk = true;
+ foreach (float pos in new[] { 0f, 0.5f, 1f })
+ {
+ ce.DeviceSetParam(ct, cd, EqPosition, pos); ce.DeviceSetParam(ct, cd, 32, 0.5f); ce.DeviceSetParam(ct, cd, 35, 0.4f);
+ var re = RenderTail(); eqOk &= re.fin && re.all > 1e-4f;
+ }
+ Check(eqOk, "tail EQ renders at input / tail / output");
+ ce.DeviceSetParam(ct, cd, 32, 0f); ce.DeviceSetParam(ct, cd, 35, 1f); ce.DeviceSetParam(ct, cd, EqPosition, 0.5f);
+ ce.DeviceSetParam(ct, cd, DuckAmount, 1f);
+ ce.Seek(0); ce.Play(); ce.RenderOffline(cb, N); ce.StopTransport();
+ ce.DeviceScope(ct, cd, csc, csc.Length);
+ Check(csc[4] > 1f, $"ducking pulls the wet down while the input plays (GR {csc[4]:F1} dB)");
+ ce.DeviceSetParam(ct, cd, DuckAmount, 0f);
+ ce.DeviceSetParam(ct, cd, WetOnly, 0f); ce.DeviceSetParam(ct, cd, DryWet, 0f);
+ var rdry = RenderTail();
+ Check(rdry.tail < 1e-4f && rdry.all > 1e-3f, $"Dry/Wet 0 passes only the dry signal (tail {rdry.tail:F5})");
+ ce.DeviceSetParam(ct, cd, DryWet, 0.35f); ce.DeviceSetParam(ct, cd, WetOnly, 1f);
+
+ // Zero latency off: the big block's delay is reported (absorbed in the predelay).
+ ce.DeviceSetParam(ct, cd, ZeroLatency, 0f); Settle();
+ ce.Seek(0); ce.Play(); ce.RenderOffline(cb, N); ce.StopTransport();
+ ce.DeviceScope(ct, cd, csc, csc.Length);
+ Check(csc[6] >= 1024f, $"Zero latency off uses the big-block kernel (conv +{csc[6]} smp)");
+ ce.DeviceSetParam(ct, cd, ZeroLatency, 1f);
+ // IR size changes swap kernels live (worker) without breaking the render.
+ ce.DeviceSetParam(ct, cd, IrSize, 0.9f); Settle();
+ ce.DeviceSetParam(ct, cd, IrSelect, 2f / 16f); Settle();
+ var rsz = RenderTail();
+ Check(rsz.fin && rsz.tail > 1e-4f && ce.DeviceText(ct, cd, 0) == "Cathedral", $"IR switch + stretch re-renders ({ce.DeviceText(ct, cd, 0)}, tail {rsz.tail:F4})");
+
+ // User IR: load a stereo WAV (with leading silence, auto-trimmed), it becomes the IR.
+ string irPath = Path.Combine(Path.GetTempPath(), "nota_chamber_ir_" + Guid.NewGuid().ToString("N") + ".wav");
+ Nota.SmokeTest.WavWriter.WriteNoiseIr(irPath, seconds: 1.2, lead: 0.05, sampleRate: 44100);
+ Check(ce.DeviceLoadFile(ct, cd, irPath), "Chamber loads a user IR file");
+ Check(!ce.DeviceLoadFile(ct, cd, irPath + ".missing"), "a missing IR file is rejected");
+ Check(ce.DeviceGetParam(ct, cd, IrSelect) > 0.999f, "loading selects the user IR slot");
+ string irName = Path.GetFileNameWithoutExtension(irPath);
+ Check(ce.DeviceText(ct, cd, 2) == irName && ce.DeviceText(ct, cd, 0) == irName, $"user IR is named after the file ({ce.DeviceText(ct, cd, 2)})");
+ var ublob = ce.DeviceGetState(ct, cd);
+ Check(ublob.Length > 100_000, $"state blob carries the user IR PCM ({ublob.Length} bytes)");
+ var cw = new float[64];
+ Check(ce.DeviceLayerWave(ct, cd, 0, cw, cw.Length) == 64 && cw.Max() > 0.5f, "IR waveform envelope is readable");
+ var ru = RenderTail();
+ Check(ru.fin && ru.all > 1e-3f, $"user IR renders ({ru.all:F4})");
+ ce.DeviceScope(ct, cd, csc, csc.Length);
+ Check(csc[11] == 2f && csc[9] > 1.0f && csc[9] < 1.2f, $"user IR: stereo, leading silence trimmed ({csc[9]:F3} s)");
+
+ // Clone: duplicating the track carries params + the user IR.
+ int ctD = ce.DuplicateTrack(ct); int cdD = ce.TrackDeviceCount(ctD) - 1;
+ Check(ctD > 0 && ce.DeviceText(ctD, cdD, 2) == irName && Math.Abs(ce.DeviceGetParam(ctD, cdD, IrSize) - 0.9f) < 1e-3,
+ "duplicate track clones Chamber params + user IR");
+
+ // Project round-trip keeps the user IR.
+ string cproj = Path.Combine(Path.GetTempPath(), "nota-chamber-" + Guid.NewGuid().ToString("N"));
+ try
+ {
+ var cwarn = new System.Collections.Generic.List<string>();
+ var cdoc = ProjectService.Capture(ce, new TransportState(120, 1, false, false), cwarn);
+ ProjectService.Save(cdoc, cproj, ce);
+ using var ce2 = new NotaEngine();
+ ProjectService.Apply(ProjectService.Load(cproj), ce2, cproj);
+ int rt = -1;
+ for (int i = 0; i < ce2.TrackCount; i++) if (ce2.TryGetTrackInfo(i, out var ti) && ce2.TrackDeviceCount(ti.Id) > 0) { rt = ti.Id; break; }
+ Check(rt > 0 && ce2.DeviceText(rt, 0, 2) == irName && ce2.DeviceGetParam(rt, 0, IrSelect) > 0.999f, "project round-trip restores the user IR");
+ }
+ finally { try { Directory.Delete(cproj, true); } catch { } try { File.Delete(irPath); } catch { } }
+
+ // Automation drives Blend.
+ int clane = ce.AddAutomationLane(ct, AutomationTarget.DeviceParam, cd, Blend);
+ Check(clane >= 0, "add Chamber Blend automation lane");
+ ce.SetAutomationPoints(ct, clane, new[] { new AutomationPoint(0.0, 0.1f), new AutomationPoint(2.0, 0.9f) });
+ ce.Seek(1.99); ce.Play(); ce.RenderOffline(cb, 4096); ce.StopTransport();
+ Check(ce.DeviceGetParam(ct, cd, Blend) > 0.7f, $"automation drives Chamber Blend ({ce.DeviceGetParam(ct, cd, Blend):F2})");
+ ce.RemoveAutomationLane(ct, clane);
+
+ // Factory presets: every named param exists and each applies in place + renders.
+ {
+ var cat = new FactoryPresetCatalog();
+ var mine = cat.All().Where(p => !p.IsInstrument && !p.IsMidiEffect && p.BuiltinKind == 20).ToList();
+ Check(mine.Count >= 16, $"Nota Chamber ships factory presets ({mine.Count})");
+ var bad = mine.SelectMany(p => cat.Document(p.Id)!.NamedParams!.Keys.Where(k => !cnames.Contains(k)).Select(k => $"{p.DisplayName}:{k}")).ToList();
+ Check(bad.Count == 0, $"every Chamber preset param name exists{(bad.Count > 0 ? " — bad: " + string.Join(", ", bad) : "")}");
+ int pf = 0;
+ foreach (var p in mine)
+ {
+ if (cat.ApplyInPlace(ce, p.Id, ct, cd).Length != 0) { pf++; continue; }
+ Settle();
+ var rp = RenderTail();
+ if (!rp.fin || rp.all < 1e-4f || rp.all > 4f) pf++;
+ }
+ Check(pf == 0, $"every Chamber preset applies and renders ({pf} failed)");
+ cat.ApplyInPlace(ce, "chamber/Wide Shimmer", ct, cd);
+ Check(Math.Abs(ce.DeviceGetParam(ct, cd, AlgoMode) - 1f) < 1e-3 && ce.DeviceGetParam(ct, cd, IrSelect) < 0.2f, "Wide Shimmer preset selects Shimmer + Cathedral");
+ cat.ApplyInPlace(ce, "chamber/Spring Box", ct, cd);
+ Check(ce.DeviceGetParam(ct, cd, AlgoMode) < 1e-3, "unnamed params reset to defaults between presets");
+ }
+
+ // MCP: kind listed, IR text + file load through the tools.
+ {
+ var dt = new Nota.Mcp.Tools.DeviceTools(ce, new Nota.SmokeTest.SyncDispatch(), new Nota.SmokeTest.NoRefresh());
+ Check(dt.ListDeviceKinds().Any(k => k.Kind == 20 && k.Name == "Nota Chamber"), "MCP lists Nota Chamber (kind 20)");
+ Check(dt.GetDeviceText(ct, cd, 0).Result.Length > 0, "MCP reads the Chamber IR name");
+ }
+}
+
// ============================ Nota Level ===================================
Console.WriteLine("-- Nota Level (AutoGain) --");
{
diff --git a/tests/Nota.SmokeTest/WavWriter.cs b/tests/Nota.SmokeTest/WavWriter.cs
index 8d642a16..bd5420b0 100644
--- a/tests/Nota.SmokeTest/WavWriter.cs
+++ b/tests/Nota.SmokeTest/WavWriter.cs
@@ -88,4 +88,26 @@ internal static class WavWriter
w.Write((short)(s * short.MaxValue));
}
}
+
+ // A stereo impulse response: `lead` seconds of silence, then decaying noise (independent
+ // L / R, deterministic LCG) — a stand-in for a user IR file.
+ public static void WriteNoiseIr(string path, double seconds, double lead, int sampleRate)
+ {
+ int frames = (int)(seconds * sampleRate), leadF = (int)(lead * sampleRate);
+ using var fs = new FileStream(path, FileMode.Create, FileAccess.Write);
+ using var w = new BinaryWriter(fs);
+ int dataBytes = frames * 4; // 16-bit stereo
+ w.Write("RIFF"u8.ToArray()); w.Write(36 + dataBytes); w.Write("WAVE"u8.ToArray());
+ w.Write("fmt "u8.ToArray()); w.Write(16); w.Write((short)1); w.Write((short)2);
+ w.Write(sampleRate); w.Write(sampleRate * 4); w.Write((short)4); w.Write((short)16);
+ w.Write("data"u8.ToArray()); w.Write(dataBytes);
+ uint seed = 12345;
+ double Next() { seed = seed * 1664525u + 1013904223u; return (seed >> 8) / 8388608.0 - 1.0; }
+ for (int i = 0; i < frames; i++)
+ {
+ double env = i < leadF ? 0.0 : Math.Exp(-(i - leadF) / (0.25 * sampleRate)) * 0.7;
+ w.Write((short)(Next() * env * short.MaxValue));
+ w.Write((short)(Next() * env * short.MaxValue));
+ }
+ }
}