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.

33.9 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.

using System.Runtime.InteropServices;

namespace Nota.Infrastructure;

public sealed partial class NotaEngine
{
    // --- Hosted plugins (M3-3) ---------------------------------------------

    /// <summary>Creates a new instrument track hosting catalog plugin <paramref name="catalogIndex"/>. Returns its id, or throws.</summary>
    public int AddPluginInstrumentTrack(int catalogIndex)
    {
        ThrowIfDisposed();
        int id = NativeMethods.AddPluginInstrumentTrack(_handle, catalogIndex);
        if (id <= 0) throw new NotaEngineException("Failed to load plugin instrument.");
        return id;
    }

    /// <summary>Replaces an instrument track's instrument with a hosted plugin.</summary>
    public void SetTrackInstrumentPlugin(int trackId, int catalogIndex)
    {
        ThrowIfDisposed();
        Check(NativeMethods.SetTrackInstrumentPlugin(_handle, trackId, catalogIndex));
    }

    /// <summary>Replaces an instrument track's instrument with a fresh built-in synth. Returns
    /// false for Racks / unknown kinds or non-instrument tracks (caller adds a new track instead).</summary>
    public bool SetTrackBuiltinInstrument(int trackId, int kind)
    {
        ThrowIfDisposed();
        return NativeMethods.SetTrackBuiltinInstrument(_handle, trackId, kind) == NativeMethods.NotaResult.Ok;
    }

    /// <summary>Copies an audio clip's played region down-mixed to mono (offline audio→MIDI
    /// analysis). Pass null to query the frame count; else fills up to <paramref name="outOrNull"/>.
    /// Returns the frame count. <paramref name="sr"/> receives the sample's source sample rate.</summary>
    public int GetClipAudioMono(int trackId, int clipIndex, float[]? outOrNull, out double sr)
    {
        ThrowIfDisposed();
        return NativeMethods.ClipAudioMono(_handle, trackId, clipIndex, outOrNull, outOrNull?.Length ?? 0, out sr);
    }

    /// <summary>Appends a hosted effect plugin to a track's device chain. Returns the device index, or -1.</summary>
    public int AddTrackEffectPlugin(int trackId, int catalogIndex)
    {
        ThrowIfDisposed();
        return NativeMethods.AddTrackEffectPlugin(_handle, trackId, catalogIndex);
    }

    /// <summary>Number of insert effects on a track's device chain.</summary>
    public int TrackDeviceCount(int trackId)
    {
        ThrowIfDisposed();
        return NativeMethods.TrackDeviceCount(_handle, trackId);
    }

    // --- Built-in devices + params (M4-4/5) --------------------------------

    /// <summary>Appends a built-in device (0=EQ, 1=Compressor, 2=Reverb, 3=Delay, 4=Utility, 5=Rack, 6=Amp). Returns device index, or -1.</summary>
    public int AddBuiltinDevice(int trackId, int kind)
    { ThrowIfDisposed(); return NativeMethods.AddBuiltinDevice(_handle, trackId, kind); }

    /// <summary>Reorders a device within the track chain.</summary>
    public void MoveDevice(int trackId, int fromIndex, int toIndex)
    { ThrowIfDisposed(); Check(NativeMethods.MoveDevice(_handle, trackId, fromIndex, toIndex)); }

    /// <summary>Removes a device from the track chain.</summary>
    public void RemoveDevice(int trackId, int deviceIndex)
    { ThrowIfDisposed(); Check(NativeMethods.RemoveDevice(_handle, trackId, deviceIndex)); }

    /// <summary>Copies a full clone of an audio effect to the engine's device clipboard (#238).</summary>
    public bool CopyDevice(int trackId, int deviceIndex)
    { ThrowIfDisposed(); return NativeMethods.CopyDevice(_handle, trackId, deviceIndex) == NativeMethods.NotaResult.Ok; }

    /// <summary>Copies a full clone of a MIDI effect to the engine's device clipboard.</summary>
    public bool CopyMidiEffect(int trackId, int index)
    { ThrowIfDisposed(); return NativeMethods.CopyMidiEffect(_handle, trackId, index) == NativeMethods.NotaResult.Ok; }

    /// <summary>0 = empty, 1 = an audio effect, 2 = a MIDI effect.</summary>
    public int DeviceClipboardKind() { ThrowIfDisposed(); return NativeMethods.DeviceClipboardKind(_handle); }

    /// <summary>True when the clipboard holds an audio effect keyed from another track.</summary>
    public bool DeviceClipboardSidechain() { ThrowIfDisposed(); return NativeMethods.DeviceClipboardSidechain(_handle) != 0; }

    /// <summary>Inserts a clone of the copied audio effect at atIndex (-1 = end), one undo step. New index or -1.</summary>
    public int PasteDevice(int trackId, int atIndex)
    { ThrowIfDisposed(); return NativeMethods.PasteDevice(_handle, trackId, atIndex); }

    /// <summary>Inserts a clone of the copied MIDI effect at atIndex (-1 = end), one undo step. New index or -1.</summary>
    public int PasteMidiEffect(int trackId, int atIndex)
    { ThrowIfDisposed(); return NativeMethods.PasteMidiEffect(_handle, trackId, atIndex); }
    public int DuplicateDevice(int trackId, int deviceIndex)
    { ThrowIfDisposed(); return NativeMethods.DuplicateDevice(_handle, trackId, deviceIndex); }
    public int DuplicateMidiEffect(int trackId, int index)
    { ThrowIfDisposed(); return NativeMethods.DuplicateMidiEffect(_handle, trackId, index); }

    /// <summary>The track's instrument on the device clipboard (specs/043), a full clone.</summary>
    public bool CopyInstrument(int trackId)
    { ThrowIfDisposed(); return NativeMethods.CopyInstrument(_handle, trackId) == 1; }
    /// <summary>Replaces the track's instrument with a clone of the copied one, one undo step.
    /// 0 done, -1 nothing to paste, -2 not an instrument track, -3 the clone failed.</summary>
    public int PasteInstrument(int trackId)
    { ThrowIfDisposed(); return NativeMethods.PasteInstrument(_handle, trackId); }
    /// <summary>Moves (or copies) a device to another track in one undo step (specs/043). The new
    /// index (0 for the instrument), -1 bad address, -2 the target can't take it, -3 the clone failed.</summary>
    public int TransferDevice(int srcTrackId, DeviceFamily family, int index, int dstTrackId, int atIndex, bool keepSource, out TransferFlags flags)
    {
        ThrowIfDisposed();
        int r = NativeMethods.TransferDevice(_handle, srcTrackId, (int)family, index, dstTrackId, atIndex, keepSource ? 1 : 0, out int f);
        flags = (TransferFlags)f;
        return r;
    }

    /// <summary>Wraps an audio effect in a new Audio Effect Rack in its place (#257). The rack's index, or -1.</summary>
    public int WrapDeviceInRack(int trackId, int deviceIndex)
    { ThrowIfDisposed(); return NativeMethods.WrapDeviceInRack(_handle, trackId, deviceIndex); }

    /// <summary>Replaces a one-chain Audio Effect Rack with its chain's devices. Their count, or -1.</summary>
    public int UnwrapRack(int trackId, int deviceIndex)
    { ThrowIfDisposed(); return NativeMethods.UnwrapRack(_handle, trackId, deviceIndex); }

    public int GroupDevices(int trackId, int midiFirst, int midiCount, bool withInstrument, int fxFirst, int fxCount)
    { ThrowIfDisposed(); return NativeMethods.GroupDevices(_handle, trackId, midiFirst, midiCount, withInstrument ? 1 : 0, fxFirst, fxCount); }

    public int UngroupRack(int trackId, DeviceFamily family, int index, out UngroupDropped dropped)
    {
        ThrowIfDisposed();
        int r = NativeMethods.UngroupRack(_handle, trackId, (int)family, index, out int d);
        dropped = (UngroupDropped)d;
        return r;
    }

    public int CopyDevices(int trackId, int[] midiIndices, bool withInstrument, int[] fxIndices)
    { ThrowIfDisposed(); return NativeMethods.CopyDevices(_handle, trackId, midiIndices, midiIndices.Length, withInstrument ? 1 : 0, fxIndices, fxIndices.Length); }

    public int DeviceClipboardCount() { ThrowIfDisposed(); return NativeMethods.DeviceClipboardCount(_handle); }

    public int PasteDevices(int trackId, int midiAt, int fxAt, out int skipped)
    { ThrowIfDisposed(); return NativeMethods.PasteDevices(_handle, trackId, midiAt, fxAt, out skipped); }

    public string DeviceName(int trackId, int deviceIndex)
    { ThrowIfDisposed(); return Marshal.PtrToStringUTF8(NativeMethods.DeviceName(_handle, trackId, deviceIndex)) ?? ""; }

    public int DeviceParamCount(int trackId, int deviceIndex)
    { ThrowIfDisposed(); return NativeMethods.DeviceParamCount(_handle, trackId, deviceIndex); }

    public string DeviceParamName(int trackId, int deviceIndex, int paramIndex)
    { ThrowIfDisposed(); return Marshal.PtrToStringUTF8(NativeMethods.DeviceParamName(_handle, trackId, deviceIndex, paramIndex)) ?? ""; }

    public float DeviceParamMin(int trackId, int deviceIndex, int paramIndex)
    { ThrowIfDisposed(); return NativeMethods.DeviceParamMin(_handle, trackId, deviceIndex, paramIndex); }

    public float DeviceParamMax(int trackId, int deviceIndex, int paramIndex)
    { ThrowIfDisposed(); return NativeMethods.DeviceParamMax(_handle, trackId, deviceIndex, paramIndex); }

    public float DeviceGetParam(int trackId, int deviceIndex, int paramIndex)
    { ThrowIfDisposed(); return NativeMethods.DeviceGetParam(_handle, trackId, deviceIndex, paramIndex); }

    public void DeviceSetParam(int trackId, int deviceIndex, int paramIndex, float value)
    { ThrowIfDisposed(); Check(NativeMethods.DeviceSetParam(_handle, trackId, deviceIndex, paramIndex, value)); }

    public float DeviceGainReduction(int trackId, int deviceIndex)
    { ThrowIfDisposed(); return NativeMethods.DeviceGainReduction(_handle, trackId, deviceIndex); }

    public float DeviceParamDefault(int trackId, int deviceIndex, int paramIndex)
    { ThrowIfDisposed(); return NativeMethods.DeviceParamDefault(_handle, trackId, deviceIndex, paramIndex); }

    public float BuiltinDeviceParamDefault(int kind, int paramIndex)
    { ThrowIfDisposed(); return NativeMethods.BuiltinDeviceParamDefault(_handle, kind, paramIndex); }
    public float InstrumentParamDefault(int trackId, int paramIndex)
    { ThrowIfDisposed(); return NativeMethods.InstrumentParamDefault(_handle, trackId, paramIndex); }
    public float MidiEffectParamDefault(int trackId, int index, int paramIndex)
    { ThrowIfDisposed(); return NativeMethods.MidiEffectParamDefault(_handle, trackId, index, paramIndex); }

    public int DeviceScope(int trackId, int deviceIndex, float[] outSamples, int maxSamples)
    { ThrowIfDisposed(); return NativeMethods.DeviceScope(_handle, trackId, deviceIndex, outSamples, maxSamples); }

    /// <summary>Device-free self-test: the Reverb comb read stays inside its delay line at the wrap edge.</summary>
    public bool ReverbWrapSelfTest()
    { ThrowIfDisposed(); return NativeMethods.ReverbWrapSelfTest(_handle) != 0; }

    public void DeviceAction(int trackId, int deviceIndex, int id, int iarg, float farg)
    { ThrowIfDisposed(); NativeMethods.DeviceAction(_handle, trackId, deviceIndex, id, iarg, farg); }
    public int DeviceLayerWave(int trackId, int deviceIndex, int layer, float[] outSamples, int maxSamples)
    { ThrowIfDisposed(); return NativeMethods.DeviceLayerWave(_handle, trackId, deviceIndex, layer, outSamples, maxSamples); }
    public byte[] DeviceGetState(int trackId, int deviceIndex)
    {
        ThrowIfDisposed();
        int n = NativeMethods.DeviceGetState(_handle, trackId, deviceIndex, null, 0);
        if (n <= 0) return System.Array.Empty<byte>();
        var buf = new byte[n];
        NativeMethods.DeviceGetState(_handle, trackId, deviceIndex, buf, n);
        return buf;
    }
    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);
    }
    public bool EqSetBandText(int trackId, int deviceIndex, int band, string label, string note)
    { ThrowIfDisposed(); return NativeMethods.EqSetBandText(_handle, trackId, deviceIndex, band, label ?? "", note ?? "") != 0; }
    public string EqBandText(int trackId, int deviceIndex, int band, int which)
    {
        ThrowIfDisposed();
        int n = NativeMethods.EqBandText(_handle, trackId, deviceIndex, band, which, null, 0);
        if (n <= 0) return "";
        var buf = new byte[n + 1];
        NativeMethods.EqBandText(_handle, trackId, deviceIndex, band, which, 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); }
    public int TrackMidiEffectCount(int trackId) { ThrowIfDisposed(); return NativeMethods.TrackMidiEffectCount(_handle, trackId); }
    public void MoveMidiEffect(int trackId, int fromIndex, int toIndex) { ThrowIfDisposed(); NativeMethods.MoveMidiEffect(_handle, trackId, fromIndex, toIndex); }
    public void RemoveMidiEffect(int trackId, int index) { ThrowIfDisposed(); NativeMethods.RemoveMidiEffect(_handle, trackId, index); }
    public int MidiEffectKind(int trackId, int index) { ThrowIfDisposed(); return NativeMethods.MidiEffectKind(_handle, trackId, index); }
    public int MidiEffectLastIn(int trackId, int index) { ThrowIfDisposed(); return NativeMethods.MidiEffectLastIn(_handle, trackId, index); }
    public int MidiEffectLastOut(int trackId, int index) { ThrowIfDisposed(); return NativeMethods.MidiEffectLastOut(_handle, trackId, index); }
    public int MidiEffectScope(int trackId, int index, float[] outv) { ThrowIfDisposed(); return NativeMethods.MidiEffectScope(_handle, trackId, index, outv, outv.Length); }
    public void MidiEffectCommand(int trackId, int index, int cmd) { ThrowIfDisposed(); NativeMethods.MidiEffectCommand(_handle, trackId, index, cmd); }

    /// <summary>A MIDI effect's opaque state blob (the MIDI Effect Rack: its whole structure); empty for params-only effects.</summary>
    public byte[] MidiEffectGetState(int trackId, int index)
    {
        ThrowIfDisposed();
        int size = NativeMethods.MidiEffectGetState(_handle, trackId, index, null, 0);
        if (size <= 0) return Array.Empty<byte>();
        var buf = new byte[size];
        NativeMethods.MidiEffectGetState(_handle, trackId, index, buf, size);
        return buf;
    }

    /// <summary>Restores a MIDI effect's state blob; checkpoint makes it one undo step. False if it couldn't be applied.</summary>
    public bool MidiEffectSetState(int trackId, int index, byte[] data, bool checkpoint)
    {
        ThrowIfDisposed();
        return data.Length > 0 && NativeMethods.MidiEffectSetState(_handle, trackId, index, data, data.Length, checkpoint ? 1 : 0) == NativeMethods.NotaResult.Ok;
    }
    public string MidiEffectName(int trackId, int index) { ThrowIfDisposed(); return Marshal.PtrToStringUTF8(NativeMethods.MidiEffectName(_handle, trackId, index)) ?? ""; }
    public int MidiEffectParamCount(int trackId, int index) { ThrowIfDisposed(); return NativeMethods.MidiEffectParamCount(_handle, trackId, index); }
    public string MidiEffectParamName(int trackId, int index, int paramIndex) { ThrowIfDisposed(); return Marshal.PtrToStringUTF8(NativeMethods.MidiEffectParamName(_handle, trackId, index, paramIndex)) ?? ""; }
    public float MidiEffectParamMin(int trackId, int index, int paramIndex) { ThrowIfDisposed(); return NativeMethods.MidiEffectParamMin(_handle, trackId, index, paramIndex); }
    public float MidiEffectParamMax(int trackId, int index, int paramIndex) { ThrowIfDisposed(); return NativeMethods.MidiEffectParamMax(_handle, trackId, index, paramIndex); }
    public float MidiEffectGetParam(int trackId, int index, int paramIndex) { ThrowIfDisposed(); return NativeMethods.MidiEffectGetParam(_handle, trackId, index, paramIndex); }
    public void MidiEffectSetParam(int trackId, int index, int paramIndex, float value) { ThrowIfDisposed(); NativeMethods.MidiEffectSetParam(_handle, trackId, index, paramIndex, value); }
    public void SetMidiEffectBypassed(int trackId, int index, bool bypassed) { ThrowIfDisposed(); NativeMethods.MidiEffectSetBypassed(_handle, trackId, index, bypassed ? 1 : 0); }
    public bool MidiEffectBypassed(int trackId, int index) { ThrowIfDisposed(); return NativeMethods.MidiEffectBypassed(_handle, trackId, index) != 0; }
    public void SetMidiEffectFolded(int trackId, int index, bool folded) { ThrowIfDisposed(); NativeMethods.MidiEffectSetFolded(_handle, trackId, index, folded ? 1 : 0); }
    public bool MidiEffectFolded(int trackId, int index) { ThrowIfDisposed(); return NativeMethods.MidiEffectFolded(_handle, trackId, index) != 0; }
    public void SetMidiEffectCcDest(int trackId, int index, int destDevice, int destParam) { ThrowIfDisposed(); NativeMethods.MidiEffectSetCcDest(_handle, trackId, index, destDevice, destParam); }
    public void SetMidiEffectCcDepth(int trackId, int index, float depth) { ThrowIfDisposed(); NativeMethods.MidiEffectSetCcDepth(_handle, trackId, index, depth); }
    public int MidiEffectCcDestDevice(int trackId, int index) { ThrowIfDisposed(); return NativeMethods.MidiEffectCcDestDevice(_handle, trackId, index); }
    public int MidiEffectCcDestParam(int trackId, int index) { ThrowIfDisposed(); return NativeMethods.MidiEffectCcDestParam(_handle, trackId, index); }
    public (int Chain, int Slot) MidiEffectCcDestPath(int trackId, int index)
    {
        ThrowIfDisposed();
        return NativeMethods.MidiEffectCcDestPath(_handle, trackId, index, out int c, out int s) == 0 ? (c, s) : (-1, -1);
    }
    public bool SetMidiEffectCcDestPath(int trackId, int index, int chain, int slot)
    { ThrowIfDisposed(); return NativeMethods.MidiEffectSetCcDestPath(_handle, trackId, index, chain, slot) == 0; }
    public NestedCcDest? RackChainMidiCcDest(int trackId, int rackAddress, int chain, int index)
    {
        ThrowIfDisposed();
        return NativeMethods.RackChainMidiCcDest(_handle, trackId, rackAddress, chain, index, out int dev, out int dc, out int ds,
                                                 out int p, out float depth) == 0 ? new NestedCcDest(dev, dc, ds, p, depth) : null;
    }
    public bool RackChainMidiSetCcDest(int trackId, int rackAddress, int chain, int index, NestedCcDest dest)
    {
        ThrowIfDisposed();
        return NativeMethods.RackChainMidiSetCcDest(_handle, trackId, rackAddress, chain, index, dest.Device, dest.Chain,
                                                    dest.Slot, dest.Param, dest.Depth) == 0;
    }
    public NestedSidechain? RackChainSidechain(int trackId, int rackAddress, int chain, int slot)
    {
        ThrowIfDisposed();
        return NativeMethods.RackChainSidechain(_handle, trackId, rackAddress, chain, slot, out int src, out int pre,
                                                out float g, out float m) == 0 ? new NestedSidechain(src, pre != 0, g, m) : null;
    }
    public int RackChainSetSidechain(int trackId, int rackAddress, int chain, int slot, NestedSidechain sc)
    {
        ThrowIfDisposed();
        return NativeMethods.RackChainSetSidechain(_handle, trackId, rackAddress, chain, slot, sc.SourceTrack, sc.TapPre ? 1 : 0,
                                                   sc.GainDb, sc.Mix);
    }
    public float MidiEffectCcDepth(int trackId, int index) { ThrowIfDisposed(); return NativeMethods.MidiEffectCcDepth(_handle, trackId, index); }

    public void SetDeviceSidechainSource(int trackId, int deviceIndex, int sourceTrackId)
    { ThrowIfDisposed(); NativeMethods.DeviceSetSidechainSource(_handle, trackId, deviceIndex, sourceTrackId); }

    public int DeviceSidechainSource(int trackId, int deviceIndex)
    { ThrowIfDisposed(); return NativeMethods.DeviceSidechainSource(_handle, trackId, deviceIndex); }

    public bool DeviceAcceptsSidechain(int trackId, int deviceIndex)
    { ThrowIfDisposed(); return NativeMethods.DeviceAcceptsSidechain(_handle, trackId, deviceIndex) != 0; }

    // Sidechain sub-sources (specs/050).
    public int TrackPartCount(int trackId) { ThrowIfDisposed(); return NativeMethods.TrackPartCount(_handle, trackId); }
    public string TrackPartName(int trackId, int index)
    {
        ThrowIfDisposed();
        int n = NativeMethods.TrackPartName(_handle, trackId, index, null, 0);
        if (n <= 0) return "";
        var buf = new byte[n + 1];
        NativeMethods.TrackPartName(_handle, trackId, index, buf, buf.Length);
        return System.Text.Encoding.UTF8.GetString(buf, 0, n);
    }
    public int SetDeviceSidechainKey(int trackId, int deviceIndex, int sourceTrackId, int part)
    { ThrowIfDisposed(); return NativeMethods.DeviceSetSidechainKey(_handle, trackId, deviceIndex, sourceTrackId, part); }
    public SidechainKey DeviceSidechainKey(int trackId, int deviceIndex)
    {
        ThrowIfDisposed();
        return NativeMethods.DeviceSidechainKey(_handle, trackId, deviceIndex, out int src, out int part) == 0
            ? new SidechainKey(src, part) : SidechainKey.None;
    }
    public int SetInstrumentSidechainKey(int trackId, int sourceTrackId, int part)
    { ThrowIfDisposed(); return NativeMethods.TrackSetInstrumentSidechainKey(_handle, trackId, sourceTrackId, part); }
    public SidechainKey InstrumentSidechainKey(int trackId)
    {
        ThrowIfDisposed();
        return NativeMethods.TrackInstrumentSidechainKey(_handle, trackId, out int src, out int part) == 0
            ? new SidechainKey(src, part) : SidechainKey.None;
    }
    public int RackChainSidechainPart(int trackId, int rackAddress, int chain, int slot)
    {
        ThrowIfDisposed();
        return NativeMethods.RackChainSidechainPart(_handle, trackId, rackAddress, chain, slot, out int part) == 0 ? part : SidechainKey.WholeTrack;
    }
    public int RackChainSetSidechainKey(int trackId, int rackAddress, int chain, int slot, NestedSidechain sc, int part)
    {
        ThrowIfDisposed();
        return NativeMethods.RackChainSetSidechainKey(_handle, trackId, rackAddress, chain, slot, sc.SourceTrack, part,
                                                      sc.TapPre ? 1 : 0, sc.GainDb, sc.Mix);
    }
    public int RackChainSetSidechainPart(int trackId, int rackAddress, int chain, int slot, int part)
    { ThrowIfDisposed(); return NativeMethods.RackChainSetSidechainPart(_handle, trackId, rackAddress, chain, slot, part); }
    public int SidechainRouteCapacity() { ThrowIfDisposed(); return NativeMethods.SidechainRouteCapacity(_handle); }
    public int SidechainRoutesFree() { ThrowIfDisposed(); return NativeMethods.SidechainRoutesFree(_handle); }
    public bool SidechainRouteInUse(int sourceTrackId, int part)
    { ThrowIfDisposed(); return NativeMethods.SidechainRouteInUse(_handle, sourceTrackId, part) != 0; }

    public void SetInstrumentSidechainSource(int trackId, int sourceTrackId)
    { ThrowIfDisposed(); NativeMethods.TrackSetInstrumentSidechainSource(_handle, trackId, sourceTrackId); }
    public int InstrumentSidechainSource(int trackId)
    { ThrowIfDisposed(); return NativeMethods.TrackInstrumentSidechainSource(_handle, trackId); }
    public bool InstrumentAcceptsSidechain(int trackId)
    { ThrowIfDisposed(); return NativeMethods.TrackInstrumentAcceptsSidechain(_handle, trackId) != 0; }

    public void SetDeviceSidechainGain(int trackId, int deviceIndex, float gainDb)
    { ThrowIfDisposed(); NativeMethods.DeviceSetSidechainGain(_handle, trackId, deviceIndex, gainDb); }
    public float DeviceSidechainGain(int trackId, int deviceIndex)
    { ThrowIfDisposed(); return NativeMethods.DeviceSidechainGain(_handle, trackId, deviceIndex); }

    public void SetDeviceSidechainMix(int trackId, int deviceIndex, float mix)
    { ThrowIfDisposed(); NativeMethods.DeviceSetSidechainMix(_handle, trackId, deviceIndex, mix); }
    public float DeviceSidechainMix(int trackId, int deviceIndex)
    { ThrowIfDisposed(); return NativeMethods.DeviceSidechainMix(_handle, trackId, deviceIndex); }

    public void SetDeviceSidechainTapPre(int trackId, int deviceIndex, bool pre)
    { ThrowIfDisposed(); NativeMethods.DeviceSetSidechainTapPre(_handle, trackId, deviceIndex, pre ? 1 : 0); }
    public bool DeviceSidechainTapPre(int trackId, int deviceIndex)
    { ThrowIfDisposed(); return NativeMethods.DeviceSidechainTapPre(_handle, trackId, deviceIndex) != 0; }

    /// <summary>Deterministic DSP self-test of the built-in EQ + Compressor. True if sane.</summary>
    public static bool FxSelfTest() => NativeMethods.FxSelfTest() != 0;
    /// <summary>The EQ cards' spectrum analyzer over <paramref name="mono"/> on a fixed clock (a
    /// frame every <paramref name="hop"/> samples, <paramref name="dt"/> s apart), for tests:
    /// each frame's 256-point curve in dB.</summary>
    public static float[][] SpectrumAnalyzeOffline(float[] mono, double sampleRate, int hop, double dt, int maxFrames)
    {
        const int pts = 256;
        var flat = new float[maxFrames * pts];
        int n = NativeMethods.SpectrumAnalyzeOffline(mono, mono.Length, sampleRate, hop, dt, flat, maxFrames);
        return Enumerable.Range(0, Math.Max(0, n)).Select(f => flat.AsSpan(f * pts, pts).ToArray()).ToArray();
    }

    /// <summary>Opens a hosted plugin's native GUI. deviceIndex &lt; 0 = the instrument.</summary>
    public void OpenPluginEditor(int trackId, int deviceIndex)
    {
        ThrowIfDisposed();
        Check(NativeMethods.PluginOpenEditor(_handle, trackId, deviceIndex));
    }

    /// <summary>Hides a hosted plugin's native GUI.</summary>
    public void ClosePluginEditor(int trackId, int deviceIndex)
    {
        ThrowIfDisposed();
        Check(NativeMethods.PluginCloseEditor(_handle, trackId, deviceIndex));
    }

    /// <summary>Whether a hosted plugin's native GUI is on screen.</summary>
    public bool PluginEditorIsOpen(int trackId, int deviceIndex)
    {
        ThrowIfDisposed();
        return NativeMethods.PluginEditorIsOpen(_handle, trackId, deviceIndex) != 0;
    }

    /// <summary>Reads a hosted plugin's opaque state blob (for project save). Empty for built-ins.</summary>
    public byte[] GetPluginState(int trackId, int deviceIndex)
    {
        ThrowIfDisposed();
        int size = NativeMethods.PluginGetState(_handle, trackId, deviceIndex, null, 0);
        if (size <= 0) return Array.Empty<byte>();
        var buf = new byte[size];
        NativeMethods.PluginGetState(_handle, trackId, deviceIndex, buf, size);
        return buf;
    }

    /// <summary>Restores a hosted plugin's state from a previously saved blob.</summary>
    public void SetPluginState(int trackId, int deviceIndex, byte[] data)
    {
        ThrowIfDisposed();
        Check(NativeMethods.PluginSetState(_handle, trackId, deviceIndex, data, data.Length));
    }

    /// <summary>The picture of a hosted plug-in's window taken when it was last hidden (JPEG,
    /// specs/046); empty when there is none.</summary>
    public byte[] GetPluginPreview(int trackId, int deviceIndex)
    {
        ThrowIfDisposed();
        int size = NativeMethods.PluginPreviewGet(_handle, trackId, deviceIndex, null, 0);
        if (size <= 0) return Array.Empty<byte>();
        var buf = new byte[size];
        int got = NativeMethods.PluginPreviewGet(_handle, trackId, deviceIndex, buf, size);
        return got == size ? buf : Array.Empty<byte>();   // replaced in between: next poll catches it
    }

    /// <summary>Replaces a device's editor preview (project load); empty clears it. False for an
    /// unknown device or an oversized blob — the card then just stays plain.</summary>
    public bool SetPluginPreview(int trackId, int deviceIndex, byte[] jpeg)
    {
        ThrowIfDisposed();
        return NativeMethods.PluginPreviewSet(_handle, trackId, deviceIndex, jpeg.Length > 0 ? jpeg : null, jpeg.Length) == NativeMethods.NotaResult.Ok;
    }

    /// <summary>Changes whenever the device's editor preview does; 0 = none.</summary>
    public int PluginPreviewSerial(int trackId, int deviceIndex)
    {
        ThrowIfDisposed();
        return NativeMethods.PluginPreviewSerial(_handle, trackId, deviceIndex);
    }

    /// <summary>Bypasses (or re-enables) the effect at deviceIndex on a track.</summary>
    public void SetDeviceBypassed(int trackId, int deviceIndex, bool bypassed)
    {
        ThrowIfDisposed();
        Check(NativeMethods.SetDeviceBypassed(_handle, trackId, deviceIndex, bypassed ? 1 : 0));
    }

    /// <summary>Whether the effect at deviceIndex is bypassed.</summary>
    public bool DeviceBypassed(int trackId, int deviceIndex)
    {
        ThrowIfDisposed();
        return NativeMethods.DeviceBypassed(_handle, trackId, deviceIndex) != 0;
    }

    /// <summary>Folds (or unfolds) the device at deviceIndex in the Devices panel (specs/022);
    /// -1 = the instrument. A view flag, saved with the project.</summary>
    public void SetDeviceFolded(int trackId, int deviceIndex, bool folded)
    {
        ThrowIfDisposed();
        NativeMethods.SetDeviceFolded(_handle, trackId, deviceIndex, folded ? 1 : 0);
    }

    /// <summary>Whether the device at deviceIndex (-1 = the instrument) is folded.</summary>
    public bool DeviceFolded(int trackId, int deviceIndex)
    {
        ThrowIfDisposed();
        return NativeMethods.DeviceFolded(_handle, trackId, deviceIndex) != 0;
    }

    /// <summary>Total reported latency (samples) of a track's plugin chain (M3-7).</summary>
    public int TrackLatencySamples(int trackId)
    {
        ThrowIfDisposed();
        return NativeMethods.TrackLatencySamples(_handle, trackId);
    }

    /// <summary>Deterministic self-test of the delay-compensation line. True if correct.</summary>
    public static bool PdcSelfTest() => NativeMethods.PdcSelfTest() != 0;

    /// <summary>Instrument identity: 0=Synth, 1=Sampler, -1=plugin/unknown, -2=no instrument.</summary>
    public int TrackInstrumentKind(int trackId) { ThrowIfDisposed(); return NativeMethods.TrackInstrumentKind(_handle, trackId); }
    public long TrackInstrumentId(int trackId) { ThrowIfDisposed(); return NativeMethods.TrackInstrumentId(_handle, trackId); }
    public bool TrackInstrumentSupportsMpe(int trackId) { ThrowIfDisposed(); return NativeMethods.TrackInstrumentSupportsMpe(_handle, trackId) != 0; }

    /// <summary>Built-in device kind (0=EQ,1=Comp,2=Reverb,3=Delay,4=Utility) or -1 for a plugin.</summary>
    public int TrackDeviceBuiltinKind(int trackId, int deviceIndex) { ThrowIfDisposed(); return NativeMethods.TrackDeviceBuiltinKind(_handle, trackId, deviceIndex); }
    public long TrackDeviceId(int trackId, int deviceIndex) { ThrowIfDisposed(); return NativeMethods.TrackDeviceId(_handle, trackId, deviceIndex); }

    /// <summary>Stable identifier of a track's plugin instrument (empty if it isn't a plugin, M7-6c).</summary>
    public string TrackInstrumentPluginId(int trackId) { ThrowIfDisposed(); return Marshal.PtrToStringUTF8(NativeMethods.TrackInstrumentPluginId(_handle, trackId)) ?? ""; }

    /// <summary>Stable identifier of a track's plugin effect (empty if it isn't a plugin, M7-6c).</summary>
    public string TrackDevicePluginId(int trackId, int deviceIndex) { ThrowIfDisposed(); return Marshal.PtrToStringUTF8(NativeMethods.TrackDevicePluginId(_handle, trackId, deviceIndex)) ?? ""; }

    // --- hosted-plugin parameters (M9-B). deviceIndex < 0 = the instrument. ---
    public int PluginParamCount(int trackId, int deviceIndex)
    { ThrowIfDisposed(); return NativeMethods.PluginParamCount(_handle, trackId, deviceIndex); }
    /// <summary>Where a param index saved before Nota Twin's layout grew (#531) sits today;
    /// any other device's index comes back unchanged.</summary>
    public int PluginParamIndexFromV1(int trackId, int deviceIndex, int paramIndex)
    { ThrowIfDisposed(); return NativeMethods.PluginParamIndexFromV1(_handle, trackId, deviceIndex, paramIndex); }
    public string PluginParamId(int trackId, int deviceIndex, int paramIndex)
    { ThrowIfDisposed(); return Marshal.PtrToStringUTF8(NativeMethods.PluginParamId(_handle, trackId, deviceIndex, paramIndex)) ?? ""; }
    public string PluginParamName(int trackId, int deviceIndex, int paramIndex)
    { ThrowIfDisposed(); return Marshal.PtrToStringUTF8(NativeMethods.PluginParamName(_handle, trackId, deviceIndex, paramIndex)) ?? ""; }
    public string PluginParamText(int trackId, int deviceIndex, int paramIndex)
    { ThrowIfDisposed(); return Marshal.PtrToStringUTF8(NativeMethods.PluginParamText(_handle, trackId, deviceIndex, paramIndex)) ?? ""; }
    public float PluginParamDefault(int trackId, int deviceIndex, int paramIndex)
    { ThrowIfDisposed(); return NativeMethods.PluginParamDefault(_handle, trackId, deviceIndex, paramIndex); }
    public float PluginParamGet(int trackId, int deviceIndex, int paramIndex)
    { ThrowIfDisposed(); return NativeMethods.PluginParamGet(_handle, trackId, deviceIndex, paramIndex); }
    public void PluginParamSet(int trackId, int deviceIndex, int paramIndex, float normalized)
    { ThrowIfDisposed(); Check(NativeMethods.PluginParamSet(_handle, trackId, deviceIndex, paramIndex, normalized)); }
    public int AddPluginAutomationLane(int trackId, int deviceIndex, string paramId)
    { ThrowIfDisposed(); return NativeMethods.AddPluginAutomationLane(_handle, trackId, deviceIndex, paramId); }
    public string AutomationLaneParamId(int trackId, int laneIndex)
    { ThrowIfDisposed(); return Marshal.PtrToStringUTF8(NativeMethods.AutomationLaneParamId(_handle, trackId, laneIndex)) ?? ""; }
    public (int Chain, int Slot) AutomationLanePath(int trackId, int laneIndex)
    {
        ThrowIfDisposed();
        return NativeMethods.AutomationLanePath(_handle, trackId, laneIndex, out int c, out int sl) == NativeMethods.NotaResult.Ok ? (c, sl) : (-1, -1);
    }
    public int AddNestedAutomationLane(int trackId, AutomationTarget target, int deviceIndex, int chain, int slot, int paramIndex, string? paramId)
    { ThrowIfDisposed(); return NativeMethods.AddNestedAutomationLane(_handle, trackId, (int)target, deviceIndex, chain, slot, paramIndex, paramId); }
    public int PluginLastTouchedParam(int trackId, int deviceIndex)
    { ThrowIfDisposed(); return NativeMethods.PluginLastTouchedParam(_handle, trackId, deviceIndex); }
}