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.

30.3 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
// Detail · Devices — built-in Compressor body (device kind 1), a build of the "Nota
// Compressor" mockup (700 × 260) on the Lens / Delay / Reverb frame: a centre tabbed graph
// that fills its panel — Curve (transfer curve + reduction history), Motion (the reduction
// envelope against the input, so attack and release are seen, not guessed) and Sidechain (the
// key's spectrum under its filters), each with its knobs beside it (Threshold · Ratio · Knee,
// Attack · Release · Hold, HP · LP · Q) and the character under the curve — and a right panel
// with no tabs of its own that follows them (Dynamics / Timing / Key) over Dry/wet · Makeup;
// laid out the #531 way (CardLayout). S is the curve over the character and Threshold, Ratio,
// Release, Dry/wet. The graphs are
// controls: drag the transfer curve for threshold / ratio, the key filter handles for HP / LP / Q. Every control is a device
// param (raw units), so automation / MIDI learn / presets / A-B / persistence come for free;
// the key source and its pre/post tap are the device's sidechain routing, not params.
// FullBleed — the shared shell draws the header (name · preset · badge · GR meter · bypass).

using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
using Nota.Application;
using Nota.Application.Localization;
using static Nota.App.DeviceCardKit;

namespace Nota.App;

internal sealed class CompressorDeviceBody : IDeviceBody
{
    // ── Parameter indices (must match Compressor.h) ─────────────────────────────
    private const int Threshold = 0, Ratio = 1, Attack = 2, Release = 3, Makeup = 4, Knee = 5, Mix = 6,
        Lookahead = 7, Detection = 8, AutoRelease = 9, AutoGain = 10, Range = 11, Character = 12,
        ScHP = 13, ScLP = 14, ScListen = 15, ScGain = 16, Hold = 17, ScQ = 18, External = 19, StereoLink = 20;
    // Scope telemetry layout (Compressor::S_*), then the envelope rings and the key samples.
    private const int S_InPk = 0, S_OutPk = 1, S_InRms = 2, S_OutRms = 3, S_Gr = 4, S_KeyPk = 5, S_AtkMs = 6,
        S_RelMs = 7, S_SampleRate = 8, S_Bpm = 9, S_Latency = 10, S_Cpu = 11, S_ExtKey = 12, kScope = 14;
    private const int EnvN = 2048, KeyN = 2048, ScopeLen = kScope + 2 * EnvN + KeyN;

    private static readonly string[] Chars = { "Clean", "Glue", "Punch", "Opto", "FET" };
    private static readonly string[] Detects = { "Peak", "RMS", "Auto" };
    private static readonly double[] Windows = { 300, 600, 1000, 1500, 2000 };

    public double Width => 700;
    public double WidthFor(IAudioEngine engine, int trackId, int deviceIndex) => CardLayout.WidthFor(engine, trackId, deviceIndex, Width);
    public Control? HeaderAccessory(DeviceCardContext ctx, int deviceIndex) => CardLayout.SizeToggle(ctx, deviceIndex);
    public bool FullBleed => true;
    public string? Subtitle => "Dynamics";

    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);
        float Mn(int p) => engine.DeviceParamMin(track, di, p);
        float Mx(int p) => engine.DeviceParamMax(track, di, p);
        float Def(int p) => engine.DeviceParamDefault(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, double v) => engine.DeviceSetParam(track, di, p, (float)Math.Clamp(v, Mn(p), Mx(p)));
        // A discrete edit (a click) is one automation gesture, so it records while the transport does.
        void SetP(int p, double v) { Begin(p); Raw(p, v); End(p); }
        void Reset(int p) => SetP(p, Def(p));
        bool On(int p) => P(p) >= 0.5f;
        int Sel(int p, int n) => Math.Clamp((int)Math.Round(P(p)), 0, n - 1);

        var readouts = new List<Action>();
        object AutoRow = new();
        var scope = new float[ScopeLen];
        int scN = 0;
        double Sc(int i) => scN > i ? scope[i] : 0;
        var envIn = new float[EnvN];
        var envGr = new float[EnvN];

        // ---- value maps (raw ↔ 0..1 for knobs and sliders) ------------------------------
        (Func<double, double> N, Func<double, double> V) Lin(int p)
        { double a = Mn(p), b = Mx(p); return (v => (v - a) / (b - a), n => a + Math.Clamp(n, 0, 1) * (b - a)); }
        (Func<double, double> N, Func<double, double> V) Log(int p)
        { double a = Mn(p), b = Mx(p); return (v => Math.Log(Math.Clamp(v, a, b) / a) / Math.Log(b / a), n => a * Math.Pow(b / a, Math.Clamp(n, 0, 1))); }
        (Func<double, double> N, Func<double, double> V) Sq(int p)
        { double b = Mx(p); return (v => Math.Sqrt(Math.Clamp(v, 0, b) / b), n => b * Math.Clamp(n, 0, 1) * Math.Clamp(n, 0, 1)); }
        // Range reads as the limit it puts on the reduction: empty = off (48 dB), full = 1 dB.
        (Func<double, double> N, Func<double, double> V) RangeMap() =>
            (v => v >= 47.5 ? 0 : Math.Clamp((48 - v) / 47, 0, 1), n => n <= 0.005 ? 48 : 48 - 47 * Math.Clamp(n, 0, 1));

        // A typeable value over a raw-unit parameter through its 0..1 map (⌥-click, specs/035).
        ValueField F(string name, Func<int> param, Func<int, (Func<double, double> N, Func<double, double> V)> map, Func<double, string> fmt, bool reset = true)
            => new(name, () => map(param()).N(P(param())), n => fmt(map(param()).V(n)), n => Raw(param(), map(param()).V(n)),
                () => Begin(param()), () => End(param()), reset ? map(param()).N(Def(param())) : null) { After = () => { foreach (var a in readouts) a(); } };

        // ---- formatters -------------------------------------------------------------------
        static string Ms(double ms) => ms >= 100 ? NotaNum.F($"{ms:0} ms") : NotaNum.F($"{ms:0.0} ms");
        static string MsShort(double ms) => ms >= 100 ? NotaNum.F($"{ms:0}") : NotaNum.F($"{ms:0.0}");
        static string Hz(double hz) => hz >= 1000 ? NotaNum.F($"{hz / 1000:0.0} k") : NotaNum.F($"{hz:0} Hz");
        static string Db(double db) => NotaNum.F($"{db:0.0} dB");
        static string SDb(double db) => NotaNum.F($"{db:+0.0;−0.0;0.0} dB");
        static string RatioF(double r) => r >= 9.95 ? NotaNum.F($"{r:0}:1") : NotaNum.F($"{r:0.#}:1");
        static string PctF(double v) => NotaNum.F($"{v:0} %");
        static string RangeF(double v) => v >= 47.5 ? "off" : NotaNum.F($"{v:0} dB");
        static string Gr(double g) => g > 0.05 ? NotaNum.F($"−{g:0.0}") : "0.0";
        static double LinDb(double lin) => lin > 1e-6 ? 20 * Math.Log10(lin) : -120;
        static string Lvl(double db) => db <= -99 ? "−∞" : NotaNum.F($"{db:0.0}");
        string HpF(double v) => v <= 20.5 ? "off" : Hz(v);
        string LpF(double v) => v >= 19999 ? "off" : Hz(v);

        // ---- small builders ---------------------------------------------------------------
        static TextBlock Caps(string t, IBrush? c = null, double fs = NotaType.KnobLabel) => new()
        { Text = NotaText.Label(t), FontSize = fs, FontWeight = FontWeight.Medium, Foreground = c ?? TextTertiary, 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.Measure"); return tb; }
        static T Col<T>(T c, int col) where T : Control { Grid.SetColumn(c, col); return c; }
        static T GRow<T>(T c, int row) where T : Control { Grid.SetRow(c, row); return c; }
        static Border Rule() => new() { Height = 1, Background = NotaPalette.GraphBorder, Margin = new Thickness(0, 1) };

        // On/off switch bound to a param (≥ 0.5 = on).
        Control Toggle(int p, string label, string tip)
        {
            var wrap = Switch(label, () => On(p), () => SetP(p, On(p) ? 0 : 1), out var sync);
            readouts.Add(sync);
            ToolTip.SetTip(wrap, tip);
            MidiLearn.Bind(wrap, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));
            return wrap;
        }

        // Segmented chips over a discrete raw param (0 … n−1).
        Control Seg(int p, string[] names, bool fill = false, double padX = 6)
        {
            int n = names.Length;
            var seg = Segments(names, () => Sel(p, n), iv => SetP(p, iv), out var sync, fill: fill, padX: padX);
            readouts.Add(sync);
            MidiLearn.Bind(seg, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));
            return seg;
        }

        // A latching chip over a toggle param (Listen · Auto gain).
        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, Padding = new Thickness(6, 0), CornerRadius = NotaRadius.Cell, BorderThickness = new Thickness(1), Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center, Child = tb };
            void Hi()
            {
                bool on = On(p);
                b.Background = on ? NotaPalette.AccentSubtle : Raised;
                b.BorderBrush = on ? NotaPalette.BorderBrass : Brushes.Transparent;
                tb.Foreground = on ? NotaPalette.AccentHover : TextPrimary;
                tb.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;
            }
            b.PointerPressed += (_, e) => { if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return; SetP(p, On(p) ? 0 : 1); 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;
        }

        // Gauge knob over a raw param through its 0..1 map (automation gesture, MIDI learn, live follow).
        Control KM(int p, string name, Func<double, string> fmt, (Func<double, double> N, Func<double, double> V) map, double cellW = 50, double size = 34, bool teal = false)
        {
            var val = Mono(fmt(P(p)), 7, TextPrimary);
            var knob = new Knob(map.N(P(p)), 1.0) { Accent = true, ArcColor = teal ? DeviceCardKit.ModInk : null, Default = map.N(Def(p)), Width = size, Height = size };
            knob.Format = n => fmt(map.V(n));
            knob.ValueChanged += n => { Raw(p, map.V(n)); val.Text = fmt(P(p)); };
            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) { double c = map.N(P(p)); if (Math.Abs(c - knob.Value) > 1e-4) knob.Value = c; } val.Text = fmt(P(p)); });
            return KnobCell(name, knob, val, cellW);
        }

        // A caps label + slider row over a raw param.
        Control SliderRow(string label, int p, Func<double, string> fmt, (Func<double, double> N, Func<double, double> V) map, bool teal = false, double valW = 34)
        {
            var row = DeviceCardKit.SliderRow("", () => map.N(P(p)), n => Raw(p, map.V(n)), () => fmt(P(p)), out var sync,
                begin: () => Begin(p), end: () => End(p), reset: () => Reset(p), valueWidth: valW, modulation: teal);
            readouts.Add(sync);
            MidiLearn.Bind(row, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));
            var g = new Grid { ColumnDefinitions = new ColumnDefinitions("40,*"), VerticalAlignment = VerticalAlignment.Center };
            g.Children.Add(Caps(label));
            g.Children.Add(Col(row, 1));
            return g;
        }

        // ---- live measurements ------------------------------------------------------------
        // Peaks held over ~300 ms of UI ticks, for the crest factors.
        var inPkHist = new double[18]; var outPkHist = new double[18]; int pkW = 0;
        double inPkHeld = 0, outPkHeld = 0;
        double KeyDb() => LinDb(Sc(S_KeyPk));
        double Bpm() => Sc(S_Bpm) > 1 ? Sc(S_Bpm) : 120;
        double WindowMs()
        {
            double want = 4 * (P(Attack) + P(Release) + P(Hold));
            foreach (double w in Windows) if (w >= want) return w;
            return Windows[^1];
        }
        // Hits: rises of the reduction through 1 dB (re-armed below 0.5 dB) over the last n ms.
        int Hits(int n)
        {
            int hits = 0; bool armed = true;
            for (int i = Math.Max(0, EnvN - n); i < EnvN; i++)
            {
                if (armed && envGr[i] > 1) { hits++; armed = false; }
                else if (!armed && envGr[i] < 0.5) armed = true;
            }
            return hits;
        }
        // The last hit in the window (the reduction rising through 1 dB from below 0.5 dB):
        // onset → 90 % of its first peak (the rise — timed to 90 % so a Hold plateau at the top
        // does not count) and that peak → 37 % of it (recovery), in ms;
        // NaN when there is nothing to measure.
        (double Transient, double Recovery) Timings(int n)
        {
            int start = Math.Max(1, EnvN - n), onset = -1;
            bool armed = false;
            for (int i = start; i < EnvN; i++)
            {
                if (envGr[i] < 0.5) armed = true;
                else if (armed && envGr[i] > 1) { onset = i; armed = false; }
            }
            if (onset < 0) return (double.NaN, double.NaN);
            while (onset > start && envGr[onset - 1] >= 0.5) onset--;     // back to where it left 0.5 dB
            int peak = onset;
            while (peak + 1 < EnvN && envGr[peak + 1] >= envGr[peak]) peak++;
            if (peak + 1 >= EnvN) return (Math.Max(peak - onset, 0.5), double.NaN);   // still attacking
            double pv = envGr[peak];
            int reach = onset;
            while (reach < peak && envGr[reach] < 0.9 * pv) reach++;
            int k = peak;
            while (k + 1 < EnvN && envGr[k] > 0.37 * pv && !(envGr[k + 1] > envGr[k] + 0.5)) k++;
            double recovery = envGr[k] <= 0.37 * pv ? k - peak : double.NaN;
            return (Math.Max(reach - onset, 0.5), recovery);
        }

        int centreTab = 0;
        // ======================================================================
        // CENTRE — Curve
        // ======================================================================
        var grHist = new CompGrHistoryView();
        ToolTip.SetTip(grHist, Loc.T("device.compressor.gain_reduction_over_the_last"));
        Control CurveTab()
        {
            var transfer = new CompTransferView();
            ToolTip.SetTip(transfer, Loc.T("device.compressor.drag_sideways_for_the_threshold"));
            transfer.GestureBegin += () => { Begin(Threshold); Begin(Ratio); };
            transfer.GestureEnd += () => { End(Threshold); End(Ratio); };
            transfer.Changed += (thr, ratio) => { Raw(Threshold, thr); Raw(Ratio, ratio); };
            transfer.Reset += () => { Reset(Threshold); Reset(Ratio); };
            ValueEntry.AttachAll(transfer, F("Threshold", () => Threshold, Lin, Db), F("Ratio", () => Ratio, Log, RatioF));
            MidiLearn.Bind(transfer, MidiTarget.DeviceParam(track, di, Threshold), "Thresh");
            readouts.Add(() => { if (!transfer.Dragging) transfer.Set(P(Threshold), P(Ratio), P(Knee), P(Range), KeyDb()); });

            var graphs = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), ColumnSpacing = 6 };
            graphs.Children.Add(transfer);
            graphs.Children.Add(Col(grHist, 1));
            return graphs;
        }
        Control CurveView() => CardLayout.View(CurveTab(),
            CardLayout.KnobColumn(KM(Threshold, "THRESH", Db, Lin(Threshold)), KM(Ratio, "RATIO", RatioF, Log(Ratio)), KM(Knee, "KNEE", Db, Lin(Knee))),
            CharSeg());

        // ======================================================================
        // CENTRE — Motion
        // ======================================================================
        Control MotionTab()
        {
            var motion = new CompMotionView();
            ToolTip.SetTip(motion, Loc.T("device.compressor.the_reduction_neutral_ink_hanging"));
            readouts.Add(() => motion.Set(envIn, envGr, scN >= kScope + 2 * EnvN ? EnvN : 0, P(Threshold), WindowMs()));
            return CardLayout.View(motion, CardLayout.KnobColumn(KM(Attack, "ATTACK", Ms, Log(Attack)), KM(Release, "RELEASE", Ms, Log(Release)),
                KM(Hold, "HOLD", v => v < 0.5 ? "off" : Ms(v), Sq(Hold), teal: true)));
        }

        // ======================================================================
        // CENTRE — Sidechain
        // ======================================================================
        // The key source: a track, or one pad / chain / voice of it (specs/050).
        var picker = new SidechainSourcePicker(engine, track, () => engine.DeviceSidechainKey(track, di),
            (src, part) => engine.SetDeviceSidechainKey(track, di, src, part));

        var key = new CompKeyView();
        Control SidechainTab()
        {
            ToolTip.SetTip(key, MenuKit.Keys(Loc.T("device.compressor.the_keys_spectrum_under_its")));
            int KParam(int h) => h == 0 ? ScHP : h == 1 ? ScLP : ScQ;
            key.GestureBegin += h => Begin(KParam(h));
            key.GestureEnd += h => End(KParam(h));
            key.FreqChanged += (h, hz) => Raw(h == 0 ? ScHP : ScLP, hz);
            key.QChanged += q => Raw(ScQ, q);
            key.Reset += h => Reset(h == 0 ? ScHP : ScLP);
            var keyQ = F("SC Q", () => ScQ, Log, v => NotaNum.F($"{v:0.00}"), reset: false);
            ValueEntry.AttachHandles(key, [F("SC HP", () => ScHP, Log, HpF), keyQ], [F("SC LP", () => ScLP, Log, LpF), keyQ]);
            MidiLearn.Bind(key, MidiTarget.DeviceParam(track, di, ScHP), "SC HP");
            readouts.Add(() =>
            {
                if (!key.Dragging) key.SetFilter(P(ScHP), P(ScLP), P(ScQ), On(ScListen));
                if (scN >= ScopeLen) key.SetKey(scope, kScope + 2 * EnvN, KeyN, Sc(S_SampleRate));
            });
            return CardLayout.View(key, CardLayout.KnobColumn(KM(ScHP, "HP", HpF, Log(ScHP)), KM(ScLP, "LP", LpF, Log(ScLP)),
                KM(ScQ, "Q", v => NotaNum.F($"{v:0.00}"), Log(ScQ))));
        }

        // ======================================================================
        // RIGHT — the controls of the centre tab (Curve · Motion · Sidechain)
        // ======================================================================
        // Rows spread evenly down the panel; Auto rows (rules, and the read-out boxes tagged
        // AutoRow) keep their own height, so a box's lines never spill over the next row.
        Control Rows(params Control[] rows)
        {
            var grid = new Grid { RowSpacing = 2 };
            for (int r = 0; r < rows.Length; r++)
            {
                bool auto = rows[r] is Border { Height: 1 } || ReferenceEquals(rows[r].Tag, AutoRow);
                grid.RowDefinitions.Add(new RowDefinition(auto ? GridLength.Auto : GridLength.Star));
                grid.Children.Add(GRow(rows[r], r));
            }
            return new Border { Padding = new Thickness(8, 4, 8, 5), Child = grid };
        }
        Control Labelled(string label, Control c)
        {
            var g = new Grid { ColumnDefinitions = new ColumnDefinitions("40,*"), VerticalAlignment = VerticalAlignment.Center };
            g.Children.Add(Caps(label));
            g.Children.Add(Col(c, 1));
            return g;
        }

        Border GrBox(bool levels)
        {
            var box = GrBoxCore(levels);
            box.Tag = AutoRow;
            return box;
        }
        Border GrBoxCore(bool levels)
        {
            var title = Caps(levels ? "OUTPUT" : "REDUCTION");
            var stack = new StackPanel { Spacing = 2, Children = { title } };
            var box = new Border { Background = Sunken, BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(NotaRadius.FieldValue), Padding = new Thickness(6, 4), Child = stack };
            if (levels)
            {
                Control Line(string name, Func<string> v, Func<IBrush> ink)
                {
                    var val = Mono("", 8, TextPrimary); val.HorizontalAlignment = HorizontalAlignment.Right;
                    readouts.Add(() => { val.Text = v(); val.Foreground = ink(); });
                    var gg = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
                    gg.Children.Add(new TextBlock { Text = name, FontSize = 8, Foreground = TextSecondary });
                    gg.Children.Add(Col(val, 1));
                    return gg;
                }
                stack.Children.Add(Line("in", () => NotaNum.F($"{Lvl(LinDb(Sc(S_InRms)))} dB"), () => TextPrimary));
                stack.Children.Add(Line("out", () => NotaNum.F($"{Lvl(LinDb(Sc(S_OutRms)))} dB"), () => Sc(S_OutPk) > 0.5 ? NotaPalette.Warning : TextPrimary));
                stack.Children.Add(Line("GR", () => NotaNum.F($"{Gr(Sc(S_Gr))} dB"), () => TextPrimary));
            }
            else
            {
                var now = Mono("", 9, TextPrimary);
                var set = Mono("", 8, TextSecondary);
                stack.Children.Add(now); stack.Children.Add(set);
                readouts.Add(() =>
                {
                    now.Text = NotaNum.F($"{Gr(Sc(S_Gr))} dB · peak {Gr(grHist.Peak)}");
                    set.Text = NotaNum.F($"thresh {P(Threshold):0.0} · {RatioF(P(Ratio))} · knee {P(Knee):0.#}");
                    bool hot = grHist.Peak >= 10;   // heavy reduction: a caution, not the accent
                    box.BorderBrush = hot ? NotaPalette.Warning : NotaPalette.GraphBorder;
                    title.Foreground = hot ? NotaPalette.Warning : TextTertiary;
                });
            }
            return box;
        }

        // Character chips — on the Curve and the Motion panels, so the voicing can be changed while
        // watching either graph.
        Control CharSeg()
        {
            var charSeg = Segments(Chars, () => Sel(Character, 5), iv => SetP(Character, iv), out var charSync, padX: 6);
            readouts.Add(charSync);
            MidiLearn.Bind(charSeg, MidiTarget.DeviceParam(track, di, Character), engine.DeviceParamName(track, di, Character));
            ToolTip.SetTip(charSeg, Loc.T("device.compressor.character_the_voicing_clean_as"));
            return charSeg;
        }

        (Control, Control) CurvePanel()
        {
            var detSeg = Seg(Detection, Detects);
            ToolTip.SetTip(detSeg, Loc.T("device.compressor.detector_peak_reacts_to_every"));
            return (CardLayout.Head(CardLayout.Title(Loc.T("device.compressor.dynamics")), detSeg), Rows(
                SliderRow("RANGE", Range, RangeF, RangeMap(), teal: true),
                Rule(),
                GrBox(true),
                Toggle(AutoGain, "Auto gain", Loc.T("device.compressor.auto_gain_make_up_that")),
                Toggle(StereoLink, "Stereo link", Loc.T("device.compressor.stereo_link_one_reduction_for"))));
        }

        // The Motion read-outs: the attack / release the detector really runs (after Character
        // and auto-release), the window the graph and the timings cover, and the GR peak.
        Border MotionBox()
        {
            var stack = new StackPanel { Spacing = 2, Children = { Caps(Loc.T("device.compressor.live_caps")) } };
            Control Line(string name, Func<string> v)
            {
                var val = Mono("", 8, TextPrimary); val.HorizontalAlignment = HorizontalAlignment.Right;
                readouts.Add(() => val.Text = v());
                var gg = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
                gg.Children.Add(new TextBlock { Text = name, FontSize = 8, Foreground = TextSecondary });
                gg.Children.Add(Col(val, 1));
                return gg;
            }
            stack.Children.Add(Line("attack · release", () => NotaNum.F($"{MsShort(Sc(S_AtkMs))} / {Ms(Sc(S_RelMs))}")));
            stack.Children.Add(Line("window", () => Ms(WindowMs())));
            stack.Children.Add(Line(Loc.T("device.compressor.gr_peak"), () => NotaNum.F($"{Gr(grHist.Peak)} dB")));
            var box = new Border { Background = Sunken, BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(NotaRadius.FieldValue), Padding = new Thickness(6, 4), Child = stack };
            box.Tag = AutoRow;
            ToolTip.SetTip(box, Loc.T("device.compressor.attack_and_release_as_the"));
            return box;
        }

        (Control, Control) MotionPanel() => (CardLayout.Head(Toggle(AutoRelease, "Auto-release", Loc.T("device.compressor.auto_release_a_slower_second"))), Rows(
            SliderRow("AHEAD", Lookahead, v => v < 0.05 ? "off" : Ms(v), Lin(Lookahead)),
            Rule(),
            MotionBox()));

        (Control, Control) KeyPanel()
        {
            var combo = picker.Combo;
            combo.HorizontalAlignment = HorizontalAlignment.Stretch;
            // The source can change elsewhere (MCP, undo): follow it while the list is closed.
            readouts.Add(picker.Sync);
            picker.Picked += k =>
            {
                // Picking a source means using it.
                if (k.Source >= 0 && !On(External)) SetP(External, 1);
                ctx.NotifyChanged();
            };
            ToolTip.SetTip(combo, Loc.T("device.compressor.key_source_internal_keys_off"));
            var tap = Segments(new[] { "Pre", "Post" }, () => engine.DeviceSidechainTapPre(track, di) ? 0 : 1,
                i => { engine.SetDeviceSidechainTapPre(track, di, i == 0); ctx.NotifyChanged(); }, out var tapSync, fill: true);
            readouts.Add(tapSync);
            ToolTip.SetTip(tap, Loc.T("device.compressor.where_the_source_is_tapped"));
            var listen = Latch(ScListen, "Listen", Loc.T("device.compressor.listen_hear_the_filtered_key"));
            var ext = Toggle(External, Loc.T("device.compressor.external"), Loc.T("device.compressor.external_key_key_off_the_source"));
            return (CardLayout.Head(ext, listen), Rows(
                Labelled("SOURCE", combo),
                Labelled("TAP", tap),
                Rule(),
                SliderRow(engine.DeviceParamName(track, di, ScGain), ScGain, SDb, Lin(ScGain))));
        }

        // ======================================================================
        // Tab frame + the panel that follows it
        // ======================================================================
        string Crest(double pk, double rms) => rms > 1e-5 && pk > 1e-5 ? NotaNum.F($"{LinDb(pk) - LinDb(rms):0.0}") : "–";
        var extras = Mono("", 7, TextTertiary);
        readouts.Add(() =>
        {
            switch (centreTab)
            {
                case 1:
                    var (tr, rec) = Timings((int)WindowMs());
                    int hits = Hits((int)WindowMs());
                    double held = 0;
                    for (int i = Math.Max(0, EnvN - (int)WindowMs()); i < EnvN; i++) held = Math.Max(held, envGr[i]);
                    extras.Text = !double.IsNaN(tr)
                        ? Loc.F("device.compressor.rise_recovery_hits", Ms(tr), double.IsNaN(rec) ? "–" : Ms(rec), Loc.Plural("device.compressor.hits", hits))
                        : held > 1 ? NotaNum.F($"reduction held near −{held:0.0}\u2009dB · no separate hits to time")
                        : Loc.F("device.compressor.attack_release_no_reduction", Ms(Sc(S_AtkMs)), Ms(Sc(S_RelMs)));
                    extras.Foreground = TextTertiary; break;
                case 2:
                    double kdb = KeyDb(), trig = Hits(EnvN) * (4 * 60000.0 / Bpm()) / EnvN;
                    extras.Text = On(ScListen) ? Loc.T("device.compressor.key_audible_output_muted")
                        : kdb <= -99 ? "key silent"
                        : NotaNum.F($"key {Lvl(kdb)} dB{(key.PeakHz > 0 ? NotaNum.F($" · peak {Hz(key.PeakHz)}") : "")} · {trig:0.#} {(Math.Abs(trig - 1) < 0.05 ? "trigger" : "triggers")} / bar");
                    extras.Foreground = On(ScListen) ? AccentBright : TextTertiary; break;
                default:
                    extras.Text = NotaNum.F($"GR avg {Gr(grHist.Average)} · peak {Gr(grHist.Peak)} dB · crest {Crest(inPkHeld, Sc(S_InRms))} → {Crest(outPkHeld, Sc(S_OutRms))}");
                    extras.Foreground = TextTertiary; break;
            }
        });
        Control root = CardLayout.IsMini(ctx, di)
            ? CardLayout.Mini(CurveTab(), CharSeg(),
                KM(Threshold, "THRESH", Db, Lin(Threshold), 56), KM(Ratio, "RATIO", RatioF, Log(Ratio), 56),
                KM(Release, "RELEASE", Ms, Log(Release), 56), KM(Mix, "DRY/WET", PctF, Lin(Mix), 56))
            : CardLayout.Large(new[] { "Curve", "Motion", "Sidechain" }, 0,
                t => t switch { 1 => MotionTab(), 2 => SidechainTab(), _ => CurveView() },
                t => t switch { 1 => MotionPanel(), 2 => KeyPanel(), _ => CurvePanel() },
                extras,
                CardLayout.Output(null, KM(Mix, "DRY/WET", PctF, Lin(Mix), 58, 44), KM(Makeup, "MAKEUP", v => NotaNum.F($"{v:+0.0;−0.0;0.0} dB"), Lin(Makeup), 54)),
                t => { centreTab = t; Refresh(); });

        void Refresh()
        {
            scN = engine.DeviceScope(track, di, scope, ScopeLen);
            if (scN >= kScope + 2 * EnvN)
            {
                Array.Copy(scope, kScope, envIn, 0, EnvN);
                Array.Copy(scope, kScope + EnvN, envGr, 0, EnvN);
            }
            inPkHist[pkW] = Sc(S_InPk); outPkHist[pkW] = Sc(S_OutPk); pkW = (pkW + 1) % inPkHist.Length;
            inPkHeld = 0; outPkHeld = 0;
            for (int i = 0; i < inPkHist.Length; i++) { inPkHeld = Math.Max(inPkHeld, inPkHist[i]); outPkHeld = Math.Max(outPkHeld, outPkHist[i]); }
            foreach (var a in readouts) a();
        }
        void Tick() { grHist.Push(Sc(S_Gr)); }
        ctx.AddDeviceRefresher(() => { Refresh(); Tick(); });
        Refresh();
        return root;

    }
}