Browse Source

VFX Sequencer: FL's bank state, the BlueARP-style engine, editor, tests

Ka1-S 1 tháng trước cách đây
mục cha
commit
797ef970d2

+ 1 - 0
CMakeLists.txt

@@ -128,6 +128,7 @@ add_library(lynx_core STATIC
     src/core/FlPatcher.cpp
     src/core/FlPatcher.cpp
     src/core/Patcher.cpp
     src/core/Patcher.cpp
     src/core/Vfx.cpp
     src/core/Vfx.cpp
+    src/core/VfxSequencer.cpp
     src/core/ThreeOsc.cpp
     src/core/ThreeOsc.cpp
     src/core/Plucked.cpp
     src/core/Plucked.cpp
     src/core/SoundFont.cpp
     src/core/SoundFont.cpp

BIN
Vfx.o


BIN
VfxSequencer.o


Những thai đổi đã bị hủy bỏ vì nó quá lớn
+ 0 - 0
scripts/build-local.sh


+ 7 - 75
src/core/Vfx.cpp

@@ -8,88 +8,18 @@
 
 
 #include "core/FlSynths.h"
 #include "core/FlSynths.h"
 #include "core/Song.h"
 #include "core/Song.h"
+#include "core/VfxDetail.h"
 #include "flp/Flp.h"
 #include "flp/Flp.h"
 
 
 namespace lynx::vfx
 namespace lynx::vfx
 {
 {
+using detail::Handoff;
+using detail::Reader;
+using detail::put;
+
 namespace
 namespace
 {
 {
 constexpr std::uint32_t lynxMagic = 0x5846564c; // "LVFX"
 constexpr std::uint32_t lynxMagic = 0x5846564c; // "LVFX"
-
-struct Reader
-{
-    const std::uint8_t* data;
-    std::size_t size, pos = 0;
-    bool failed = false;
-
-    template <typename T>
-    T get() noexcept
-    {
-        T v {};
-        if (failed || sizeof (T) > size - pos)
-        {
-            failed = true;
-            return v;
-        }
-        std::memcpy (&v, data + pos, sizeof (T));
-        pos += sizeof (T);
-        return v;
-    }
-    std::int32_t i32() noexcept { return get<std::int32_t>(); }
-    std::uint32_t u32() noexcept { return get<std::uint32_t>(); }
-    std::size_t left() const noexcept { return failed ? 0 : size - pos; }
-};
-
-template <typename T>
-void put (std::vector<std::uint8_t>& out, T v)
-{
-    const auto* p = reinterpret_cast<const std::uint8_t*> (&v);
-    out.insert (out.end(), p, p + sizeof (T));
-}
-
-// Settings handed from the UI thread to the audio thread without locks or allocation on the audio side (the
-// Patcher graph's pattern): the UI publishes a new object, the audio thread swaps it in and parks the old one, the
-// UI frees it on its next call.
-template <typename T>
-class Handoff
-{
-public:
-    explicit Handoff (T initial) : active (std::make_unique<T> (std::move (initial))) {}
-    explicit Handoff (std::unique_ptr<T> initial) : active (std::move (initial)) {}
-    ~Handoff()
-    {
-        delete pending.exchange (nullptr);
-        delete retired.exchange (nullptr);
-    }
-    void publish (T value)
-    {
-        delete retired.exchange (nullptr);
-        delete pending.exchange (new T (std::move (value)));
-    }
-    void publish (std::unique_ptr<T> value)
-    {
-        delete retired.exchange (nullptr);
-        delete pending.exchange (value.release());
-    }
-    // audio thread: true when new settings arrived
-    bool take() noexcept
-    {
-        auto* incoming = pending.exchange (nullptr);
-        if (incoming == nullptr)
-            return false;
-        auto* old = active.release();
-        active.reset (incoming);
-        delete retired.exchange (old); // (normally null: the UI frees it on its next call)
-        return true;
-    }
-    const T& get() const noexcept { return *active; }
-
-private:
-    std::unique_ptr<T> active;
-    std::atomic<T*> pending { nullptr };
-    std::atomic<T*> retired { nullptr };
-};
-
 } // namespace
 } // namespace
 
 
 int inputId (int key, int colour) noexcept { return (colour & 15) * 128 + (key & 127); }
 int inputId (int key, int colour) noexcept { return (colour & 15) * 128 + (key & 127); }
@@ -868,6 +798,7 @@ std::vector<std::uint8_t> defaultState (Kind kind)
         case Kind::levelScaler: return writeLevelScaler (defaultLevelScaler());
         case Kind::levelScaler: return writeLevelScaler (defaultLevelScaler());
         case Kind::keyboardSplitter: return writeKeyboardSplitter (defaultKeyboardSplitter());
         case Kind::keyboardSplitter: return writeKeyboardSplitter (defaultKeyboardSplitter());
         case Kind::envelope: return writeEnvelope (defaultEnvelope());
         case Kind::envelope: return writeEnvelope (defaultEnvelope());
+        case Kind::sequencer: return writeSequencer (defaultSequencer());
         default: break;
         default: break;
     }
     }
     return {};
     return {};
@@ -1732,6 +1663,7 @@ std::unique_ptr<Processor> makeProcessor (Kind kind, const std::vector<std::uint
             return std::make_unique<KeyboardSplitter> (parseKeyboardSplitter (fl).value_or (defaultKeyboardSplitter()));
             return std::make_unique<KeyboardSplitter> (parseKeyboardSplitter (fl).value_or (defaultKeyboardSplitter()));
         case Kind::envelope:
         case Kind::envelope:
             return std::make_unique<Envelope> (parseEnvelope (fl).value_or (defaultEnvelope()));
             return std::make_unique<Envelope> (parseEnvelope (fl).value_or (defaultEnvelope()));
+        case Kind::sequencer: return makeSequencer (fl);
         default: break;
         default: break;
     }
     }
     return std::make_unique<ThroughProcessor> (kind);
     return std::make_unique<ThroughProcessor> (kind);

+ 60 - 0
src/core/Vfx.h

@@ -241,6 +241,65 @@ EnvelopeSettings defaultEnvelope();
 std::optional<EnvelopeSettings> parseEnvelope (const std::vector<std::uint8_t>& fl);
 std::optional<EnvelopeSettings> parseEnvelope (const std::vector<std::uint8_t>& fl);
 std::vector<std::uint8_t> writeEnvelope (const EnvelopeSettings& s);
 std::vector<std::uint8_t> writeEnvelope (const EnvelopeSettings& s);
 
 
+// VFX Sequencer (FL's port of BlueARP): a bank of 128 step programs (six lanes of 64 steps each) and the
+// parameters that turn held notes into arpeggios / sequences. Kept as FL stores it, so a bank writes back as read.
+struct SequencerSettings
+{
+    enum Lane { scaleStep, octave, stepType, keySelect, velocity, gateStep, laneCount };
+    enum StepType { off, normal, rest, tie, chord, random };
+    struct Program
+    {
+        std::vector<std::int8_t> params;                         // FL param 39 + i (prgp), 42 or 43 bytes
+        std::array<std::uint8_t, 48> name {};                    // NUL-padded Latin-1
+        std::array<std::array<std::int8_t, 64>, laneCount> lanes {};
+        std::vector<std::vector<std::uint8_t>> extra;            // unknown chunks (tag, size, data) kept as they are
+        std::string nameText() const;
+        void setName (const std::string& n);
+        bool operator== (const Program&) const = default;
+    };
+    struct Chain
+    {
+        std::vector<std::uint8_t> head { 0, 0xff, 0xff, 0xff, 0xff }; // chnp (meaning unknown)
+        std::array<std::int8_t, 8> slots { -1, -1, -1, -1, -1, -1, -1, -1 };
+        std::array<std::uint8_t, 48> name {};
+        bool operator== (const Chain&) const = default;
+    };
+    std::uint32_t version = 2, engineVersion = 1;
+    std::vector<std::int8_t> fixp;   // FL params 0…19
+    std::vector<std::int8_t> fpgp;   // the program-level params that are global (FL param 39 + i)
+    std::vector<Chain> chains;
+    std::vector<Program> programs;
+    std::vector<std::vector<std::uint8_t>> extra;                // unknown bank chunks
+    std::vector<std::uint8_t> gui { 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0 }; // record 2 (the editor's combos)
+    std::vector<std::uint8_t> options;                           // record 3 (absent in FL's default state)
+    bool operator== (const SequencerSettings&) const = default;
+
+    // FL's parameter numbers
+    enum Param
+    {
+        midiIn = 1, arpMode = 5, currentProgram = 8, steps = 40, gate = 41, sync = 42, latch = 43, missingKeys = 44,
+        inputLow = 45, inputHigh = 46, outputLow = 47, outputHigh = 48, order = 49, fixedKey = 50, transposeOctaves = 51,
+        inputQuantize = 52, transposeSemitones = 53, swing = 55, restartOn = 56, forceKey = 57, forceScale = 58,
+        forceMode = 59, pageLock = 60, page = 61, patternShift = 62, inputWrapLow = 63, inputWrapHigh = 64, polyOctave = 65,
+        polyKeys = 66, missingOctave = 67, gateLaneMode = 69, randomVelocity = 70, randomGate = 71, randomStart = 72,
+        smartBend = 80, programMode = 81, inputRangeMode = 16, velocityMode = 17, selectedLayer = 68
+    };
+    // A parameter's value as the plugin uses it (FL's lookup: per program or global); 0 when it does not exist
+    int get (int param) const noexcept;
+    void set (int param, int value);
+    static bool perProgram (int param) noexcept;
+    static int minimum (int param) noexcept;
+    static int maximum (int param) noexcept;
+    int program() const noexcept; // the current program 0…
+    Program& current();
+    const Program& current() const;
+};
+SequencerSettings defaultSequencer();
+std::optional<SequencerSettings> parseSequencer (const std::vector<std::uint8_t>& fl);
+std::vector<std::uint8_t> writeSequencer (const SequencerSettings& s);
+// Rotates all six lanes of the current program by `delta` steps (FL's Pattern shift)
+void shiftPattern (SequencerSettings& s, int delta);
+
 // ---------------------------------------------------------------------------------------------------------------
 // ---------------------------------------------------------------------------------------------------------------
 // Presets
 // Presets
 
 
@@ -298,5 +357,6 @@ protected:
     double rate = 44100.0;
     double rate = 44100.0;
 };
 };
 std::unique_ptr<Processor> makeProcessor (Kind kind, const std::vector<std::uint8_t>& flState);
 std::unique_ptr<Processor> makeProcessor (Kind kind, const std::vector<std::uint8_t>& flState);
+std::unique_ptr<Processor> makeSequencer (const std::vector<std::uint8_t>& flState); // (VfxSequencer.cpp)
 } // namespace vfx
 } // namespace vfx
 } // namespace lynx
 } // namespace lynx

+ 90 - 0
src/core/VfxDetail.h

@@ -0,0 +1,90 @@
+#pragma once
+
+// Internals shared by the VFX sources (Vfx.cpp, VfxSequencer.cpp): byte reading / writing and the lock-free
+// settings hand-over to the audio thread.
+
+#include <algorithm>
+#include <atomic>
+#include <cstdint>
+#include <cstring>
+#include <memory>
+#include <vector>
+
+namespace lynx::vfx::detail
+{
+
+struct Reader
+{
+    const std::uint8_t* data;
+    std::size_t size, pos = 0;
+    bool failed = false;
+
+    template <typename T>
+    T get() noexcept
+    {
+        T v {};
+        if (failed || sizeof (T) > size - pos)
+        {
+            failed = true;
+            return v;
+        }
+        std::memcpy (&v, data + pos, sizeof (T));
+        pos += sizeof (T);
+        return v;
+    }
+    std::int32_t i32() noexcept { return get<std::int32_t>(); }
+    std::uint32_t u32() noexcept { return get<std::uint32_t>(); }
+    std::size_t left() const noexcept { return failed ? 0 : size - pos; }
+};
+
+template <typename T>
+void put (std::vector<std::uint8_t>& out, T v)
+{
+    const auto* p = reinterpret_cast<const std::uint8_t*> (&v);
+    out.insert (out.end(), p, p + sizeof (T));
+}
+
+// Settings handed from the UI thread to the audio thread without locks or allocation on the audio side (the
+// Patcher graph's pattern): the UI publishes a new object, the audio thread swaps it in and parks the old one, the
+// UI frees it on its next call.
+template <typename T>
+class Handoff
+{
+public:
+    explicit Handoff (T initial) : active (std::make_unique<T> (std::move (initial))) {}
+    explicit Handoff (std::unique_ptr<T> initial) : active (std::move (initial)) {}
+    ~Handoff()
+    {
+        delete pending.exchange (nullptr);
+        delete retired.exchange (nullptr);
+    }
+    void publish (T value)
+    {
+        delete retired.exchange (nullptr);
+        delete pending.exchange (new T (std::move (value)));
+    }
+    void publish (std::unique_ptr<T> value)
+    {
+        delete retired.exchange (nullptr);
+        delete pending.exchange (value.release());
+    }
+    // audio thread: true when new settings arrived
+    bool take() noexcept
+    {
+        auto* incoming = pending.exchange (nullptr);
+        if (incoming == nullptr)
+            return false;
+        auto* old = active.release();
+        active.reset (incoming);
+        delete retired.exchange (old); // (normally null: the UI frees it on its next call)
+        return true;
+    }
+    const T& get() const noexcept { return *active; }
+
+private:
+    std::unique_ptr<T> active;
+    std::atomic<T*> pending { nullptr };
+    std::atomic<T*> retired { nullptr };
+};
+
+} // namespace lynx::vfx::detail

+ 1451 - 0
src/core/VfxSequencer.cpp

@@ -0,0 +1,1451 @@
+// VFX Sequencer (round 164b, docs/analise/REA_rodada164b.md §Sequencer): FL's port of BlueARP — a bank of step
+// programs that turn held notes into arpeggios and sequences. The state is FL's (so FL's bank and projects load and
+// write back as they are); the engine follows the behaviour measured in FL's plugin (REA, clean-room: our own code).
+
+#include <algorithm>
+#include <cmath>
+#include <cstring>
+
+#include "core/Vfx.h"
+#include "core/VfxDetail.h"
+
+namespace lynx::vfx
+{
+using detail::Handoff;
+using detail::put;
+using detail::Reader;
+using S = SequencerSettings;
+
+namespace
+{
+// ---------------------------------------------------------------------------------------------------------------
+// Parameters
+
+struct ParamInfo
+{
+    int min, max, def;
+    bool perProgram;
+};
+
+// FL param 39 + i (the program-level block)
+constexpr ParamInfo programParams[43] = {
+    { 0, 127, 17, false },  // 0 PatchVerProg
+    { 0, 64, 16, true },    // 1 Steps
+    { 1, 125, 90, true },   // 2 Gate %
+    { 0, 12, 4, true },     // 3 Sync
+    { 0, 1, 0, false },     // 4 Latch
+    { 0, 4, 0, true },      // 5 Missing key substitution
+    { 0, 127, 0, false },   // 6 Input range low
+    { 0, 127, 127, false }, // 7 Input range high
+    { 0, 127, 0, false },   // 8 Output wrap low
+    { 0, 127, 127, false }, // 9 Output wrap high
+    { 0, 7, 0, true },      // 10 Order algorithm
+    { 0, 127, 64, true },   // 11 Fixed key
+    { -3, 3, 0, true },     // 12 Transpose octaves
+    { 0, 8, 1, false },     // 13 Input quantize
+    { -12, 12, 0, false },  // 14 Transpose semitones
+    { 0, 1, 0, false },     // 15 Page scroll
+    { -50, 50, 0, true },   // 16 Swing
+    { 0, 3, 0, false },     // 17 Restart on
+    { 0, 13, 0, true },     // 18 Force scale: key
+    { 0, 14, 0, true },     // 19 Force scale: scale
+    { 0, 1, 0, true },      // 20 Force scale: mode
+    { 0, 1, 0, false },     // 21 Page lock
+    { 0, 3, 0, false },     // 22 Page selected
+    { -8, 8, 0, false },    // 23 Pattern shift
+    { 0, 127, 0, false },   // 24 Input wrap low
+    { 0, 127, 127, false }, // 25 Input wrap high
+    { 0, 1, 0, true },      // 26 Polyphonic octave
+    { 0, 1, 0, true },      // 27 Polyphonic key select
+    { 0, 2, 0, true },      // 28 Missing key octave
+    { 0, 4, 0, false },     // 29 Selected layer
+    { 0, 1, 0, true },      // 30 Gate lane mode
+    { 0, 100, 0, true },    // 31 Randomize velocity
+    { 0, 100, 0, true },    // 32 Randomize gate
+    { 0, 100, 0, true },    // 33 Randomize start
+    { 0, 1, 0, false },     // 34 Latch mode
+    { 0, 1, 1, false },     // 35 Filter: pitch bend
+    { 0, 1, 1, false },     // 36 Filter: mod wheel
+    { 0, 1, 1, false },     // 37 Filter: aftertouch
+    { 0, 1, 0, false },     // 38 Filter: other CC
+    { 0, 3, 3, false },     // 39 Filter: sustain
+    { 0, 1, 0, false },     // 40 Sustain polarity
+    { -7, 7, 0, true },     // 41 Smart bend
+    { 0, 1, 0, true },      // 42 Program mode
+};
+
+// FL params 0…19
+constexpr ParamInfo globalParams[20] = {
+    { 0, 127, 17, false }, { -1, 15, -1, false }, { 0, 15, 0, false }, { 0, 5, 0, false },  { 0, 13, 0, false },
+    { 0, 6, 1, false },    { 0, 0, 0, false },    { 0, 120, 120, false }, { 0, 127, 3, false }, { 0, 5, 3, false },
+    { 1, 16, 8, false },   { -1, 15, -1, false }, { 0, 8, 5, false },  { 0, 1, 1, false },   { 0, 3, 0, false },
+    { 0, 2, 0, false },    { 0, 1, 0, false },    { 0, 2, 0, false },  { 0, 2, 0, false },   { 0, 1, 0, false },
+};
+
+const ParamInfo* info (int param) noexcept
+{
+    if (param >= 0 && param < 20)
+        return &globalParams[param];
+    if (param >= 39 && param < 39 + 43)
+        return &programParams[param - 39];
+    return nullptr;
+}
+
+// step length in beats per Sync index (1/64 … 3/8)
+constexpr double syncBeats[13] = { 0.0625, 1.0 / 12.0, 0.125, 1.0 / 6.0, 0.25, 1.0 / 3.0, 0.5, 2.0 / 3.0, 1.0, 0.1875, 0.375, 0.75, 1.5 };
+// input quantize grid in beats (index 2 "1/12" is 0.75 in FL's plugin; kept)
+constexpr double quantizeBeats[9] = { 0.0, 0.25, 0.75, 0.5, 2.0 / 3.0, 1.0, 2.0, 4.0, 8.0 };
+
+std::vector<std::uint8_t> chunk (const char* tag, const std::vector<std::uint8_t>& data)
+{
+    std::vector<std::uint8_t> out (tag, tag + 4);
+    put<std::uint32_t> (out, (std::uint32_t) data.size());
+    out.insert (out.end(), data.begin(), data.end());
+    return out;
+}
+
+template <typename T>
+std::vector<std::uint8_t> bytes (const T& c)
+{
+    std::vector<std::uint8_t> out (c.size());
+    std::memcpy (out.data(), c.data(), c.size());
+    return out;
+}
+
+std::array<std::uint8_t, 48> nameBytes (const std::string& s)
+{
+    std::array<std::uint8_t, 48> out {};
+    std::memcpy (out.data(), s.data(), std::min<std::size_t> (s.size(), 47));
+    return out;
+}
+
+void appendChunk (std::vector<std::uint8_t>& out, const std::vector<std::uint8_t>& c) { out.insert (out.end(), c.begin(), c.end()); }
+} // namespace
+
+std::string S::Program::nameText() const
+{
+    std::string s;
+    for (const auto c : name)
+    {
+        if (c == 0)
+            break;
+        s += (char) c;
+    }
+    return s;
+}
+
+void S::Program::setName (const std::string& n) { name = nameBytes (n); }
+
+bool S::perProgram (int param) noexcept
+{
+    const auto* i = info (param);
+    return i != nullptr && i->perProgram;
+}
+
+int S::minimum (int param) noexcept
+{
+    if (param >= 0x80 && param < 0x200)
+    {
+        static constexpr int lo[6] = { -12, 0, 0, 0, 0, -3 };
+        return lo[(param - 0x80) / 64];
+    }
+    const auto* i = info (param);
+    return i != nullptr ? i->min : 0;
+}
+
+int S::maximum (int param) noexcept
+{
+    if (param >= 0x80 && param < 0x200)
+    {
+        static constexpr int hi[6] = { 12, 127, 5, 127, 127, 16 };
+        return hi[(param - 0x80) / 64];
+    }
+    const auto* i = info (param);
+    return i != nullptr ? i->max : 0;
+}
+
+int S::program() const noexcept
+{
+    const auto p = fixp.size() > 8 ? (int) fixp[8] : 0;
+    return programs.empty() ? 0 : std::clamp (p, 0, (int) programs.size() - 1);
+}
+
+S::Program& S::current() { return programs[(std::size_t) program()]; }
+const S::Program& S::current() const { return programs[(std::size_t) program()]; }
+
+int S::get (int param) const noexcept
+{
+    if (param >= 0x80 && param < 0x200)
+    {
+        if (programs.empty())
+            return 0;
+        return current().lanes[(std::size_t) ((param - 0x80) / 64)][(std::size_t) ((param - 0x80) % 64)];
+    }
+    const auto* i = info (param);
+    if (i == nullptr)
+        return 0;
+    if (param < 20)
+        return (std::size_t) param < fixp.size() ? std::clamp ((int) fixp[(std::size_t) param], i->min, i->max) : i->def;
+    const auto k = (std::size_t) (param - 39);
+    if (i->perProgram)
+    {
+        if (programs.empty())
+            return i->def;
+        const auto& p = current().params;
+        return k < p.size() ? std::clamp ((int) p[k], i->min, i->max) : i->def;
+    }
+    return k < fpgp.size() ? std::clamp ((int) fpgp[k], i->min, i->max) : i->def;
+}
+
+void S::set (int param, int value)
+{
+    value = std::clamp (value, minimum (param), maximum (param));
+    if (param >= 0x80 && param < 0x200)
+    {
+        if (! programs.empty())
+            current().lanes[(std::size_t) ((param - 0x80) / 64)][(std::size_t) ((param - 0x80) % 64)] = (std::int8_t) value;
+        return;
+    }
+    const auto* i = info (param);
+    if (i == nullptr)
+        return;
+    auto store = [&] (std::vector<std::int8_t>& v, std::size_t k, int def) {
+        if (v.size() <= k)
+            v.resize (k + 1, (std::int8_t) def);
+        v[k] = (std::int8_t) value;
+    };
+    if (param < 20)
+        store (fixp, (std::size_t) param, i->def);
+    else if (i->perProgram)
+    {
+        if (! programs.empty())
+            store (current().params, (std::size_t) (param - 39), i->def);
+    }
+    else
+        store (fpgp, (std::size_t) (param - 39), i->def);
+}
+
+void shiftPattern (SequencerSettings& s, int delta)
+{
+    if (s.programs.empty())
+        return;
+    const auto steps = std::clamp (s.get (S::steps), 1, 64);
+    auto& p = s.current();
+    for (auto& lane : p.lanes)
+    {
+        auto old = lane;
+        for (int i = 0; i < steps; ++i)
+            lane[(std::size_t) ((((i + delta) % steps) + steps) % steps)] = old[(std::size_t) i];
+    }
+}
+
+// ---------------------------------------------------------------------------------------------------------------
+// LYNX's own bank (a fresh plugin without FL Studio's factory bank): a few programs written for LYNX
+
+SequencerSettings defaultSequencer()
+{
+    S s;
+    s.fixp = { 17, -1, 0, 0, 0, 1, 0, 120, 2, 3, 8, -1, 5, 1, 0, 0, 0, 0, 0, 0 };
+    s.fpgp = { 17, 16, 90, 4, 0, 0, 0, 127, 0, 127, 0, 64, 0, 1, 0, 0, 0, 0, 0, 0, 0,
+               0,  0,  0,  0, 127, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 3, 0, 0 };
+    for (int c = 0; c < 16; ++c)
+    {
+        S::Chain chain;
+        chain.name = nameBytes ("Chain " + std::string (c < 9 ? "0" : "") + std::to_string (c + 1));
+        s.chains.push_back (chain);
+    }
+    S::Program blank;
+    blank.params = s.fpgp;
+    for (auto& v : blank.lanes[S::octave]) v = 0x08;
+    for (auto& v : blank.lanes[S::stepType]) v = S::normal;
+    for (auto& v : blank.lanes[S::keySelect]) v = 0x04;
+    for (auto& v : blank.lanes[S::velocity]) v = 96;
+    blank.setName ("Initial");
+    s.programs.assign (128, blank);
+
+    auto make = [&] (int index, const std::string& name, auto&& fill) {
+        auto p = blank;
+        p.setName (name);
+        fill (p);
+        s.programs[(std::size_t) index] = p;
+    };
+    auto param = [] (S::Program& p, int flParam, int v) { p.params[(std::size_t) (flParam - 39)] = (std::int8_t) v; };
+    auto keys = [] (S::Program& p, std::initializer_list<int> slots) { // 1…5 = N1…N5, 0 = Fixed, -1 = Root
+        int i = 0;
+        for (int step = 0; step < 64; ++step)
+        {
+            const auto k = *(slots.begin() + (i++ % (int) slots.size()));
+            p.lanes[S::keySelect][(std::size_t) step] = (std::int8_t) (k == 0 ? 1 : k < 0 ? 2 : 1 << (k + 1));
+        }
+    };
+    make (1, "Thru", [&] (S::Program& p) { param (p, S::steps, 0); });
+    make (2, "Up 4 keys", [&] (S::Program& p) {
+        param (p, S::gate, 50);
+        param (p, S::missingKeys, 3);
+        keys (p, { 1, 2, 3, 4 });
+    });
+    make (3, "Down 4 keys", [&] (S::Program& p) {
+        param (p, S::gate, 50);
+        param (p, S::missingKeys, 2);
+        keys (p, { 4, 3, 2, 1 });
+    });
+    make (4, "Up and down 3 keys", [&] (S::Program& p) {
+        param (p, S::gate, 60);
+        param (p, S::missingKeys, 3);
+        keys (p, { 1, 2, 3, 2 });
+    });
+    make (5, "Up 2 octaves", [&] (S::Program& p) {
+        param (p, S::steps, 12);
+        param (p, S::gate, 60);
+        param (p, S::missingKeys, 1);
+        keys (p, { 1, 2, 3 });
+        for (int i = 3; i < 6; ++i)
+            p.lanes[S::octave][(std::size_t) i] = p.lanes[S::octave][(std::size_t) (i + 6)] = 0x10;
+    });
+    make (6, "Chord stabs", [&] (S::Program& p) {
+        param (p, S::gate, 40);
+        const int pattern[16] = { 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0 };
+        for (int i = 0; i < 64; ++i)
+            p.lanes[S::stepType][(std::size_t) i] = (std::int8_t) (pattern[i % 16] ? S::chord : S::off);
+    });
+    make (7, "Gated chords", [&] (S::Program& p) {
+        param (p, S::gate, 70);
+        const int pattern[16] = { 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 };
+        for (int i = 0; i < 64; ++i)
+            p.lanes[S::stepType][(std::size_t) i] = (std::int8_t) (pattern[i % 16] ? S::chord : S::off);
+    });
+    make (8, "Random notes", [&] (S::Program& p) {
+        param (p, S::gate, 50);
+        for (auto& v : p.lanes[S::stepType]) v = S::random;
+    });
+    make (9, "Octave bass", [&] (S::Program& p) {
+        param (p, S::gate, 40);
+        for (int i = 0; i < 64; ++i)
+        {
+            p.lanes[S::octave][(std::size_t) i] = (std::int8_t) (i % 2 == 0 ? 0x08 : 0x10);
+            p.lanes[S::velocity][(std::size_t) i] = (std::int8_t) (i % 4 == 0 ? 120 : 90);
+        }
+    });
+    make (10, "A minor run", [&] (S::Program& p) {
+        param (p, S::gate, 70);
+        param (p, S::forceKey, 2 + 9);
+        param (p, S::forceScale, 3);
+        const int run[16] = { 0, 1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 2, 1, 0, -1 };
+        for (int i = 0; i < 64; ++i)
+            p.lanes[S::scaleStep][(std::size_t) i] = (std::int8_t) run[i % 16];
+    });
+    make (11, "Scale of the chord", [&] (S::Program& p) {
+        param (p, S::gate, 70);
+        param (p, S::forceKey, 1);
+        param (p, S::forceScale, 1);
+        keys (p, { -1 });
+        const int run[16] = { 0, 2, 4, 7, 4, 2, 0, -1, 0, 2, 4, 5, 7, 5, 4, 2 };
+        for (int i = 0; i < 64; ++i)
+            p.lanes[S::scaleStep][(std::size_t) i] = (std::int8_t) run[i % 16];
+    });
+    make (12, "Accents", [&] (S::Program& p) {
+        param (p, S::gate, 55);
+        param (p, S::missingKeys, 1);
+        keys (p, { 1, 2, 3, 4 });
+        const int vel[4] = { 127, 64, 96, 64 };
+        for (int i = 0; i < 64; ++i)
+            p.lanes[S::velocity][(std::size_t) i] = (std::int8_t) vel[i % 4];
+    });
+    make (13, "Legato ties", [&] (S::Program& p) {
+        param (p, S::gate, 90);
+        param (p, S::missingKeys, 1);
+        keys (p, { 1, 2, 3, 2 });
+        for (int i = 0; i < 64; ++i)
+            if (i % 4 == 1)
+                p.lanes[S::stepType][(std::size_t) i] = S::tie;
+            else if (i % 8 == 7)
+                p.lanes[S::stepType][(std::size_t) i] = S::rest;
+    });
+    make (14, "Triplets up", [&] (S::Program& p) {
+        param (p, S::steps, 12);
+        param (p, S::sync, 5);
+        param (p, S::gate, 60);
+        param (p, S::missingKeys, 1);
+        keys (p, { 1, 2, 3 });
+    });
+    make (15, "Swing eighths", [&] (S::Program& p) {
+        param (p, S::steps, 8);
+        param (p, S::sync, 6);
+        param (p, S::gate, 50);
+        param (p, S::swing, 30);
+        param (p, S::missingKeys, 1);
+        keys (p, { 1, 3, 2, 3 });
+    });
+    return s;
+}
+
+// ---------------------------------------------------------------------------------------------------------------
+// FL's state
+
+std::optional<SequencerSettings> parseSequencer (const std::vector<std::uint8_t>& fl)
+{
+    Reader r { fl.data(), fl.size() };
+    S s;
+    s.version = r.u32();
+    if (r.failed || s.version != 2)
+        return std::nullopt;
+    s.gui.clear();
+    bool bank = false;
+    while (r.left() >= 12)
+    {
+        const auto id = r.u32();
+        const auto size = r.get<std::uint64_t>();
+        if (r.failed || size > r.left())
+            return std::nullopt;
+        const auto* data = fl.data() + r.pos;
+        r.pos += (std::size_t) size;
+        if (id == 2)
+            s.gui.assign (data, data + size);
+        else if (id == 3)
+            s.options.assign (data, data + size);
+        else if (id == 1)
+        {
+            Reader e { data, (std::size_t) size };
+            s.engineVersion = e.u32();
+            char tag[4];
+            if (e.left() < 8)
+                return std::nullopt;
+            std::memcpy (tag, data + e.pos, 4);
+            e.pos += 4;
+            const auto bankSize = e.u32();
+            if (e.failed || std::memcmp (tag, "bbnk", 4) != 0 || bankSize > e.left())
+                return std::nullopt;
+            // the bank's chunks
+            auto walk = [&] (std::size_t from, std::size_t to, auto&& onChunk) {
+                auto p = from;
+                while (p + 8 <= to)
+                {
+                    std::uint32_t n = 0;
+                    std::memcpy (&n, data + p + 4, 4);
+                    if (n > to - p - 8)
+                        return false;
+                    onChunk (data + p, data + p + 8, (std::size_t) n);
+                    p += 8 + n;
+                }
+                return p == to;
+            };
+            bool ok = true;
+            ok = walk (e.pos, e.pos + bankSize, [&] (const std::uint8_t* head, const std::uint8_t* body, std::size_t n) {
+                const std::string_view t ((const char*) head, 4);
+                if (t == "fixp")
+                    s.fixp.assign ((const std::int8_t*) body, (const std::int8_t*) body + n);
+                else if (t == "fpgp")
+                    s.fpgp.assign ((const std::int8_t*) body, (const std::int8_t*) body + n);
+                else if (t == "chnp")
+                {
+                    s.chains.emplace_back();
+                    s.chains.back().head.assign (body, body + n);
+                }
+                else if (t == "chns" && ! s.chains.empty())
+                    std::memcpy (s.chains.back().slots.data(), body, std::min<std::size_t> (n, 8));
+                else if (t == "chnn" && ! s.chains.empty())
+                    std::memcpy (s.chains.back().name.data(), body, std::min<std::size_t> (n, 48));
+                else if (t == "prog")
+                {
+                    S::Program p;
+                    const auto from = (std::size_t) (body - data);
+                    ok = ok && walk (from, from + n, [&] (const std::uint8_t* h, const std::uint8_t* b, std::size_t m) {
+                        const std::string_view u ((const char*) h, 4);
+                        if (u == "prgp")
+                            p.params.assign ((const std::int8_t*) b, (const std::int8_t*) b + m);
+                        else if (u == "pgnm")
+                            std::memcpy (p.name.data(), b, std::min<std::size_t> (m, 48));
+                        else if (u.substr (0, 3) == "stp" && u[3] >= '0' && u[3] <= '5' && m == 64)
+                            std::memcpy (p.lanes[(std::size_t) (u[3] - '0')].data(), b, 64);
+                        else
+                            p.extra.emplace_back (h, b + m);
+                    });
+                    s.programs.push_back (std::move (p));
+                }
+                else
+                    s.extra.emplace_back (head, body + n);
+            });
+            if (! ok)
+                return std::nullopt;
+            bank = true;
+        }
+    }
+    if (! bank || s.programs.empty() || s.fixp.size() < 20)
+        return std::nullopt;
+    return s;
+}
+
+std::vector<std::uint8_t> writeSequencer (const SequencerSettings& s)
+{
+    std::vector<std::uint8_t> bank;
+    std::vector<std::uint8_t> fixp (s.fixp.size()), fpgp (s.fpgp.size());
+    std::memcpy (fixp.data(), s.fixp.data(), fixp.size());
+    std::memcpy (fpgp.data(), s.fpgp.data(), fpgp.size());
+    appendChunk (bank, chunk ("fixp", fixp));
+    appendChunk (bank, chunk ("fpgp", fpgp));
+    for (const auto& c : s.chains)
+    {
+        appendChunk (bank, chunk ("chnp", c.head));
+        appendChunk (bank, chunk ("chns", bytes (c.slots)));
+        appendChunk (bank, chunk ("chnn", bytes (c.name)));
+    }
+    for (const auto& p : s.programs)
+    {
+        std::vector<std::uint8_t> prog;
+        std::vector<std::uint8_t> params (p.params.size());
+        std::memcpy (params.data(), p.params.data(), params.size());
+        appendChunk (prog, chunk ("prgp", params));
+        appendChunk (prog, chunk ("pgnm", bytes (p.name)));
+        for (int l = 0; l < S::laneCount; ++l)
+        {
+            const char tag[5] = { 's', 't', 'p', (char) ('0' + l), 0 };
+            appendChunk (prog, chunk (tag, bytes (p.lanes[(std::size_t) l])));
+        }
+        for (const auto& x : p.extra)
+            appendChunk (prog, x);
+        appendChunk (bank, chunk ("prog", prog));
+    }
+    for (const auto& x : s.extra)
+        appendChunk (bank, x);
+
+    std::vector<std::uint8_t> engine;
+    put<std::uint32_t> (engine, s.engineVersion);
+    appendChunk (engine, chunk ("bbnk", bank));
+
+    std::vector<std::uint8_t> out;
+    put<std::uint32_t> (out, s.version);
+    auto record = [&] (std::uint32_t id, const std::vector<std::uint8_t>& data) {
+        put<std::uint32_t> (out, id);
+        put<std::uint64_t> (out, (std::uint64_t) data.size());
+        out.insert (out.end(), data.begin(), data.end());
+    };
+    record (1, engine);
+    if (! s.gui.empty())
+        record (2, s.gui);
+    if (! s.options.empty())
+        record (3, s.options);
+    return out;
+}
+
+// ---------------------------------------------------------------------------------------------------------------
+// The engine
+
+namespace
+{
+struct Chord
+{
+    std::uint16_t mask;
+    bool inversion;
+    int rootOffset, score;
+    std::array<int, 2> completion;
+    std::array<std::int8_t, 7> scale;
+    int scaleCount;
+};
+
+constexpr std::uint16_t m (std::initializer_list<int> intervals)
+{
+    std::uint16_t v = 0;
+    for (const auto i : intervals)
+        v = (std::uint16_t) (v | (1u << i));
+    return v;
+}
+
+// chord masks, whether found on a note that is not the lowest, root offset, score, completion notes (order
+// "chord normalized"), and the scale each one implies (Force scale "detect")
+const Chord chords[38] = {
+    { m ({ 0, 7 }), false, 0, 20, { 0, 0 }, { 0, 0, 0, 0, 7, 7, 7 }, 7 },
+    { m ({ 0, 5 }), false, 0, 20, { 0, 0 }, { 0, 0, 0, 5, 5, 5, 5 }, 7 },
+    { m ({ 0, 4 }), false, 0, 20, { 7, 0 }, { 0, 2, 4, 5, 7, 7, 9 }, 7 },
+    { m ({ 0, 3 }), false, 0, 20, { 7, 0 }, { 0, 2, 3, 5, 7, 8, 10 }, 7 },
+    { m ({ 0, 4, 7 }), true, 0, 30, { 0, 0 }, { 0, 2, 4, 5, 7, 7, 9 }, 7 },
+    { m ({ 0, 3, 7 }), true, 0, 30, { 0, 0 }, { 0, 2, 3, 5, 7, 8, 10 }, 7 },
+    { m ({ 0, 5, 7 }), false, 0, 30, { 0, 0 }, { 0, 5, 5, 5, 7, 7, 7 }, 7 },
+    { m ({ 0, 2, 7 }), false, 0, 30, { 0, 0 }, { 0, 2, 2, 2, 7, 7, 7 }, 7 },
+    { m ({ 0, 3, 6 }), true, 0, 30, { 0, 0 }, { 0, 2, 3, 5, 6, 6, 6 }, 7 },
+    { m ({ 0, 4, 6 }), true, 0, 30, { 0, 0 }, { 0, 2, 4, 6, 7, 7, 7 }, 7 },
+    { m ({ 0, 4, 8 }), false, 0, 30, { 0, 0 }, { 0, 2, 5, 8, 9, 9, 11 }, 7 },
+    { m ({ 0, 2, 4 }), true, 0, 30, { 7, 0 }, { 0, 2, 2, 4, 4, 7, 7 }, 7 },
+    { m ({ 0, 2, 3 }), true, 0, 30, { 0, 0 }, { 0, 2, 2, 3, 3, 5, 7 }, 7 },
+    { m ({ 0, 4, 11 }), true, 0, 30, { 7, 0 }, { 0, 2, 4, 5, 7, 9, 11 }, 7 },
+    { m ({ 0, 3, 10 }), true, 0, 30, { 7, 0 }, { 0, 2, 3, 5, 7, 8, 10 }, 7 },
+    { m ({ 0, 4, 10 }), true, 0, 30, { 7, 0 }, { 0, 2, 4, 5, 7, 9, 10 }, 7 },
+    { m ({ 0, 4, 7, 11 }), true, 0, 40, { 0, 0 }, { 0, 2, 4, 5, 7, 9, 11 }, 7 },
+    { m ({ 0, 4, 7, 9 }), false, 0, 40, { 0, 0 }, { 0, 2, 4, 5, 7, 9, 11 }, 7 },
+    { m ({ 0, 4, 7, 10 }), true, 0, 40, { 0, 0 }, { 0, 2, 4, 5, 7, 9, 10 }, 7 },
+    { m ({ 0, 2, 4, 7 }), true, 0, 40, { 0, 0 }, { 0, 2, 4, 5, 7, 9, 11 }, 7 },
+    { m ({ 0, 2, 3, 7 }), true, 0, 40, { 0, 0 }, { 0, 2, 3, 5, 7, 8, 10 }, 7 },
+    { m ({ 0, 5, 7, 10 }), false, 0, 40, { 0, 0 }, { 0, 0, 5, 5, 7, 7, 10 }, 7 },
+    { m ({ 0, 2, 7, 10 }), false, 0, 40, { 0, 0 }, { 0, 2, 5, 5, 7, 7, 10 }, 7 },
+    { m ({ 0, 2, 4, 9 }), false, 2, 40, { 0, 0 }, { 0, 2, 5, 5, 7, 7, 10 }, 7 },
+    { m ({ 0, 4, 5, 11 }), false, 0, 40, { 7, 9 }, { 0, 2, 4, 5, 7, 9, 11 }, 7 },
+    { m ({ 0, 2, 3, 10 }), true, 0, 40, { 7, 0 }, { 0, 2, 3, 5, 7, 8, 10 }, 7 },
+    { m ({ 0, 3, 7, 9 }), true, 0, 40, { 0, 0 }, { 0, 2, 3, 5, 7, 8, 10 }, 7 },
+    { m ({ 0, 3, 7, 10 }), true, 0, 40, { 0, 0 }, { 0, 2, 3, 5, 7, 8, 10 }, 7 },
+    { m ({ 0, 3, 7, 11 }), true, 0, 40, { 0, 0 }, { 0, 2, 3, 5, 7, 8, 11 }, 7 },
+    { m ({ 0, 3, 6, 7 }), true, 0, 40, { 0, 0 }, { 0, 2, 3, 6, 7, 8, 10 }, 7 },
+    { m ({ 0, 3, 6, 9 }), false, 0, 40, { 0, 0 }, { 0, 2, 3, 6, 7, 10, 0 }, 6 },
+    { m ({ 0, 4, 6, 9 }), false, 0, 40, { 0, 0 }, { 0, 2, 4, 5, 6, 9, 0 }, 6 },
+    { m ({ 0, 4, 8, 9 }), false, 0, 40, { 0, 0 }, { 0, 2, 4, 5, 7, 9, 0 }, 6 },
+    { m ({ 0, 2, 4, 7, 11 }), true, 0, 50, { 0, 0 }, { 0, 2, 4, 5, 7, 9, 11 }, 7 },
+    { m ({ 0, 4, 5, 7, 11 }), true, 0, 50, { 0, 0 }, { 0, 2, 4, 5, 7, 9, 11 }, 7 },
+    { m ({ 0, 2, 3, 7, 10 }), true, 0, 50, { 0, 0 }, { 0, 2, 3, 5, 7, 8, 10 }, 7 },
+    { m ({ 0, 3, 5, 7, 10 }), true, 0, 50, { 0, 0 }, { 0, 2, 3, 5, 7, 8, 10 }, 7 },
+    { m ({ 0, 4, 5, 7, 9, 11 }), true, 0, 60, { 0, 0 }, { 0, 2, 4, 5, 7, 9, 11 }, 7 },
+};
+
+struct Scale
+{
+    std::array<std::int8_t, 7> degrees;
+    int count;
+};
+// Force scale 2…14
+const Scale scales[13] = {
+    { { 0, 2, 4, 5, 7, 9, 11 }, 7 }, { { 0, 2, 3, 5, 7, 8, 10 }, 7 }, { { 0, 2, 3, 5, 7, 8, 11 }, 7 },
+    { { 0, 2, 3, 5, 7, 9, 11 }, 7 }, { { 0, 2, 4, 7, 9 }, 5 },          { { 0, 3, 5, 7, 10 }, 5 },
+    { { 0, 2, 5, 7, 10 }, 5 },       { { 0, 3, 5, 6, 7, 10 }, 6 },      { { 0, 2, 3, 5, 7, 9, 10 }, 7 },
+    { { 0, 1, 3, 5, 7, 8, 10 }, 7 }, { { 0, 2, 4, 6, 7, 9, 11 }, 7 },   { { 0, 2, 4, 5, 7, 9, 10 }, 7 },
+    { { 0, 1, 3, 5, 6, 8, 10 }, 7 },
+};
+
+// The current program with every value resolved (built on the UI thread)
+struct Runtime
+{
+    int midiIn = -1, arpMode = 1, steps = 16, gate = 90, sync = 4, latch = 0, missing = 0, inLow = 0, inHigh = 127,
+        outLow = 0, outHigh = 127, order = 0, fixedKey = 64, transposeOctaves = 0, inputQuantize = 1, transposeSemitones = 0,
+        swing = 0, restartOn = 0, forceKey = 0, forceScale = 0, forceMode = 0, pageLock = 0, page = 0, wrapLow = 0,
+        wrapHigh = 127, polyOctave = 0, polyKeys = 0, missingOctave = 0, gateLaneMode = 0, randomVelocity = 0,
+        randomGate = 0, randomStart = 0, smartBend = 0, programMode = 0, inputRangeMode = 0, velocityMode = 0;
+    std::array<std::array<std::int8_t, 64>, 6> lanes {};
+};
+
+Runtime resolve (const S& s)
+{
+    Runtime r;
+    r.midiIn = s.get (S::midiIn);
+    r.arpMode = s.get (S::arpMode);
+    r.steps = s.get (S::steps);
+    r.gate = s.get (S::gate);
+    r.sync = s.get (S::sync);
+    r.latch = s.get (S::latch);
+    r.missing = s.get (S::missingKeys);
+    r.inLow = s.get (S::inputLow);
+    r.inHigh = s.get (S::inputHigh);
+    r.outLow = s.get (S::outputLow);
+    r.outHigh = s.get (S::outputHigh);
+    r.order = s.get (S::order);
+    r.fixedKey = s.get (S::fixedKey);
+    r.transposeOctaves = s.get (S::transposeOctaves);
+    r.inputQuantize = s.get (S::inputQuantize);
+    r.transposeSemitones = s.get (S::transposeSemitones);
+    r.swing = s.get (S::swing);
+    r.restartOn = s.get (S::restartOn);
+    r.forceKey = s.get (S::forceKey);
+    r.forceScale = s.get (S::forceScale);
+    r.forceMode = s.get (S::forceMode);
+    r.pageLock = s.get (S::pageLock);
+    r.page = s.get (S::page);
+    r.wrapLow = s.get (S::inputWrapLow);
+    r.wrapHigh = s.get (S::inputWrapHigh);
+    r.polyOctave = s.get (S::polyOctave);
+    r.polyKeys = s.get (S::polyKeys);
+    r.missingOctave = s.get (S::missingOctave);
+    r.gateLaneMode = s.get (S::gateLaneMode);
+    r.randomVelocity = s.get (S::randomVelocity);
+    r.randomGate = s.get (S::randomGate);
+    r.randomStart = s.get (S::randomStart);
+    r.smartBend = s.get (S::smartBend);
+    r.programMode = s.get (S::programMode);
+    r.inputRangeMode = s.get (S::inputRangeMode);
+    r.velocityMode = s.get (S::velocityMode);
+    if (! s.programs.empty())
+        r.lanes = s.current().lanes;
+    return r;
+}
+
+// FL's "MIDI velocity" here is the voice volume × 100 (velocity 100/128 = 100)
+int midiVelocity (float velocity) noexcept
+{
+    const auto volume = (std::pow (11.0, 1.28 * (double) velocity) - 1.0) / 10.0;
+    return (int) std::clamp (volume * 100.0 + 1e-9, 0.0, 127.0);
+}
+
+float voiceVelocity (int midi) noexcept
+{
+    const auto volume = std::max (0, midi) / 100.0;
+    return (float) std::clamp (std::log (10.0 * volume + 1.0) / std::log (11.0) / 1.28, 0.0, 1.0);
+}
+
+class Sequencer final : public Processor
+{
+public:
+    explicit Sequencer (const S& s) : settings (resolve (s)) {}
+
+    Kind kind() const noexcept override { return Kind::sequencer; }
+
+    bool configure (const std::vector<std::uint8_t>& fl) override
+    {
+        const auto s = parseSequencer (fl);
+        if (! s)
+            return false;
+        settings.publish (resolve (*s));
+        return true;
+    }
+
+    bool busy() const noexcept override { return heldCount > 0 || arpCount > 0 || soundingCount > 0 || thruCount > 0 || freeRun != 0; }
+
+    void releaseAll (EventList& out) noexcept override
+    {
+        killAll (0, out);
+        heldCount = arpCount = keyCount = 0;
+        freeRun = 0;
+        lastStep = -1;
+    }
+
+    void process (const Event* in, int count, int n, const Transport& t, EventList& out) noexcept override
+    {
+        if (settings.take())
+        {
+            const auto& r = settings.get();
+            if (r.arpMode != lastArpMode && lastArpMode >= 0)
+            {
+                killAll (0, out);
+                lastStep = -1;
+            }
+            keysDirty = arpCount > 0;
+        }
+        const auto& r = settings.get();
+        lastArpMode = r.arpMode;
+        sampleRate = t.sampleRate > 0.0 ? t.sampleRate : 44100.0;
+        const auto bpm = std::max (1.0, t.bpm);
+        const auto beatsPerSample = bpm / 60.0 / sampleRate;
+        stepSamples = sampleRate * 60.0 / bpm * syncBeats[std::clamp (r.sync, 0, 12)];
+
+        // transport start / stop
+        const auto songBeats = t.ticks / 960.0;
+        if (t.playing && ! wasPlaying)
+        {
+            anchored = false;
+            restartOffset = 0.0;
+            if (r.restartOn == 3)
+            {
+                restartOffset = quantizeUp (songBeats, r);
+                anchored = true;
+            }
+            freeRun = 0;
+            lastStep = -1;
+        }
+        else if (! t.playing && wasPlaying)
+        {
+            killAll (0, out);
+            heldCount = arpCount = keyCount = 0;
+            chordIndex = -1;
+            freeRun = 0;
+            lastStep = -1;
+        }
+        else if (t.playing && songBeats < lastSongBeats - 1e-6 && r.restartOn != 0) // (a loop jumped back)
+            restartOffset = std::min (restartOffset, songBeats);
+        wasPlaying = t.playing;
+
+        if (count == 0 && ! busy())
+        {
+            lastSongBeats = songBeats + n * beatsPerSample;
+            return;
+        }
+
+        int next = 0;
+        for (int s = 0; s < n; ++s)
+        {
+            while (next < count && in[next].offset <= s)
+                input (in[next++], s, songBeats + s * beatsPerSample, t.playing, r, out);
+
+            const auto playingArp = mode (r) == Mode::arp;
+            if (playingArp && arpCount > 0 && (t.playing || freeRun != 0))
+            {
+                const auto pos = t.playing ? songBeats + s * beatsPerSample : freeBeats;
+                const auto rel = t.playing ? pos - (r.restartOn == 0 ? 0.0 : restartOffset) : pos;
+                if (rel >= -1e-9)
+                {
+                    const auto step = stepIndex (std::max (0.0, rel), r);
+                    if (step != lastStep || regenerate)
+                    {
+                        const auto grid = quantizeBeats[std::clamp (r.inputQuantize, 0, 8)];
+                        const auto cell = grid > 0.0 ? (long long) std::floor (rel / grid + 1e-9) : -1;
+                        if (keysDirty && (grid <= 0.0 || cell != lastCell || keyCount == 0))
+                        {
+                            buildKeys (r);
+                            keysDirty = false;
+                        }
+                        lastCell = cell;
+                        if (step != lastStep || regenerate)
+                            generate (step, s, r, out);
+                        lastStep = step;
+                        regenerate = false;
+                    }
+                }
+            }
+            schedule (s, out);
+            if (! t.playing && freeRun != 0)
+            {
+                freeBeats += beatsPerSample;
+                if (freeRun == 2 && --tailSamples <= 0)
+                {
+                    freeRun = 0;
+                    freeBeats = 0.0;
+                    lastStep = -1;
+                }
+            }
+        }
+        while (next < count)
+            input (in[next++], std::max (0, n - 1), songBeats + n * beatsPerSample, t.playing, r, out);
+        lastSongBeats = songBeats + n * beatsPerSample;
+    }
+
+private:
+    enum class Mode { off, arp, thru };
+    struct Key
+    {
+        int note = 0, velocity = 96, order = 0;
+    };
+    struct Sounding
+    {
+        int note = 0, velocity = 0, id = 0;
+        double startDelay = 0.0, gate = 0.0;
+        bool started = false;
+    };
+    struct Thru
+    {
+        int input = 0, id = 0, note = 0;
+    };
+
+    Mode mode (const Runtime& r) const noexcept
+    {
+        switch (r.arpMode)
+        {
+            case 0: return Mode::off;
+            case 2: return Mode::thru;
+            case 3: case 4: case 5: case 6:
+            {
+                const auto threshold = r.arpMode <= 4 ? 2 : 3;
+                if (heldCount >= threshold)
+                    return r.steps < 2 ? Mode::thru : Mode::arp;
+                return r.arpMode == 4 || r.arpMode == 6 ? Mode::thru : Mode::off;
+            }
+            default: return r.steps < 2 ? Mode::thru : Mode::arp;
+        }
+    }
+
+    double quantizeUp (double beats, const Runtime& r) const noexcept
+    {
+        const auto grid = quantizeBeats[std::clamp (r.inputQuantize, 0, 8)];
+        return grid > 0.0 ? std::ceil (beats / grid - 1e-9) * grid : beats;
+    }
+
+    int stepIndex (double rel, const Runtime& r) const noexcept
+    {
+        const auto steps = std::max (1, r.steps);
+        const auto stepBeats = syncBeats[std::clamp (r.sync, 0, 12)];
+        const auto perBeat = 1.0 / stepBeats;
+        auto x = rel * perBeat;
+        if (r.sync > 7) // (FL's plugin wraps the long syncs this way)
+        {
+            const auto span = std::floor (steps * perBeat) * perBeat;
+            if (span > 0.0)
+                x = std::fmod (x, span);
+        }
+        if (r.swing != 0)
+        {
+            const auto k = std::floor (x / 2.0);
+            const auto f = x - 2.0 * k;
+            const auto threshold = r.swing >= 0 ? 1.0 : 0.0; // (FL: (s + 100) div 100)
+            if (f >= threshold)
+                x = 2.0 * k + 2.0 - (100.0 / (100.0 - r.swing)) * (2.0 - f);
+            else
+                x = 2.0 * k + (100.0 / (100.0 + r.swing)) * f;
+        }
+        auto step = (long long) std::floor (x + 1e-9);
+        if (r.pageLock != 0)
+            return std::min (steps - 1, r.page * 16 + (int) (step % 16));
+        return (int) (step % steps);
+    }
+
+    // --- input ------------------------------------------------------------------------------------------------
+
+    void input (const Event& e, int offset, double songBeats, bool playing, const Runtime& r, EventList& out) noexcept
+    {
+        const auto key = std::clamp (e.voice.key, 0, 127);
+        if (e.type == Event::Type::off)
+        {
+            for (int i = 0; i < thruCount; ++i)
+                if (thru[(std::size_t) i].input == e.id)
+                {
+                    off (thru[(std::size_t) i].id, thru[(std::size_t) i].note, offset, out);
+                    thru[(std::size_t) i] = thru[(std::size_t) --thruCount];
+                    break;
+                }
+            const auto before = mode (r);
+            removeKey (held, heldCount, key);
+            if (r.latch == 0)
+            {
+                removeKey (arp, arpCount, key);
+                keysDirty = true;
+            }
+            if (mode (r) != before)
+                modeChanged (offset, out);
+            if (heldCount == 0 && arpCount == 0)
+            {
+                anchoredByKey = false;
+                if (! playing && freeRun == 1)
+                {
+                    if (r.restartOn == 1)
+                    {
+                        freeRun = 0;
+                        freeBeats = 0.0;
+                        lastStep = -1;
+                    }
+                    else
+                    {
+                        freeRun = 2;
+                        tailSamples = (long long) sampleRate;
+                    }
+                }
+                keyCount = 0;
+                if (r.restartOn == 1 || r.restartOn == 2)
+                    lastStep = -1;
+            }
+            return;
+        }
+        if (e.type != Event::Type::on)
+            return;
+        const auto inRange = key >= r.inLow && key <= r.inHigh;
+        const auto velocity = midiVelocity (e.voice.velocity);
+        if (! inRange && r.inputRangeMode == 0)
+            return;
+        if (! inRange || r.arpMode == 2)
+        {
+            if (r.arpMode != 0)
+                thruNote (e, key, offset, r, out);
+            return;
+        }
+        const auto before = mode (r);
+        if (r.latch != 0 && heldCount == 0) // (a new chord replaces the latched one)
+            arpCount = 0;
+        const auto wasEmpty = arpCount == 0;
+        addKey (held, heldCount, key, velocity);
+        addKey (arp, arpCount, key, velocity);
+        keysDirty = true;
+        const auto now = mode (r);
+        if (now != before)
+            modeChanged (offset, out);
+        if (now == Mode::thru)
+        {
+            thruNote (e, key, offset, r, out);
+            return;
+        }
+        if (now != Mode::arp)
+            return;
+        if (! playing)
+        {
+            if (freeRun != 2)
+            {
+                freeBeats = 0.0;
+                lastStep = -1;
+            }
+            freeRun = 1;
+        }
+        else if (wasEmpty && ((r.restartOn == 1) || (r.restartOn == 2 && ! anchored)))
+        {
+            restartOffset = quantizeUp (songBeats, r);
+            anchored = true;
+            anchoredByKey = true;
+            lastStep = -1;
+        }
+        if (wasEmpty)
+        {
+            buildKeys (r);
+            keysDirty = false;
+            regenerate = true;
+        }
+    }
+
+    void addKey (std::array<Key, 16>& list, int& count, int note, int velocity) noexcept
+    {
+        removeKey (list, count, note);
+        if (count >= 16)
+            return;
+        list[(std::size_t) count++] = { note, velocity, ++arrivals };
+    }
+    static void removeKey (std::array<Key, 16>& list, int& count, int note) noexcept
+    {
+        for (int i = 0; i < count; ++i)
+            if (list[(std::size_t) i].note == note)
+            {
+                for (int j = i + 1; j < count; ++j)
+                    list[(std::size_t) (j - 1)] = list[(std::size_t) j];
+                --count;
+                return;
+            }
+    }
+    void modeChanged (int offset, EventList& out) noexcept
+    {
+        killAll (offset, out);
+        lastStep = -1;
+        regenerate = true;
+    }
+
+    void thruNote (const Event& e, int key, int offset, const Runtime& r, EventList& out) noexcept
+    {
+        if (thruCount >= (int) thru.size())
+            return;
+        const auto note = pitch (key, 0, false, r);
+        Voice v;
+        v.key = note;
+        v.velocity = e.voice.velocity;
+        const auto id = newId();
+        out.add (onEvent (offset, id, v));
+        thru[(std::size_t) thruCount++] = { e.id, id, note };
+    }
+
+    // --- the key list (FL: rebuilt on the input-quantize grid) ---------------------------------------------------
+
+    void buildKeys (const Runtime& r) noexcept
+    {
+        // pitch-sorted copy for chord detection
+        std::array<Key, 16> sorted = arp;
+        const auto n = arpCount;
+        for (int i = 1; i < n; ++i)
+        {
+            const auto k = sorted[(std::size_t) i];
+            auto j = i;
+            for (; j > 0 && sorted[(std::size_t) (j - 1)].note > k.note; --j)
+                sorted[(std::size_t) j] = sorted[(std::size_t) (j - 1)];
+            sorted[(std::size_t) j] = k;
+        }
+        detectChord (sorted, n);
+
+        keyCount = 0;
+        auto push = [&] (int note, int velocity) {
+            if (keyCount < 16)
+                keys[(std::size_t) keyCount++] = { std::clamp (note, 0, 127), velocity, 0 };
+        };
+        if (r.programMode == 1)
+        {
+            const auto* scale = activeScale (r);
+            push (r.fixedKey, 96);
+            if (scale != nullptr && scale->count > 5)
+                for (const auto d : { 2, 4, 5 })
+                    push (r.fixedKey + scale->degrees[(std::size_t) d], 96);
+            else
+            {
+                push (r.fixedKey + 5, 96);
+                push (r.fixedKey + 7, 96);
+            }
+        }
+        else if (r.order == 6 && chordIndex >= 0 && n > 0)
+        {
+            const auto& c = chords[chordIndex];
+            int v = 0;
+            for (int i = 0; i < 12; ++i)
+                if (c.mask & (1u << i))
+                    push (root + i, sorted[(std::size_t) (v++ % n)].velocity);
+            for (const auto x : c.completion)
+                if (x != 0)
+                    push (root + x, sorted[(std::size_t) (v++ % n)].velocity);
+        }
+        else if (r.order == 7 && chordIndex >= 0)
+        {
+            const auto& c = chords[chordIndex];
+            for (int i = 0; i < n; ++i)
+            {
+                const auto rel = ((sorted[(std::size_t) i].note - root) % 12 + 12) % 12;
+                if (c.mask & (1u << rel))
+                    push (root + rel, sorted[(std::size_t) i].velocity);
+            }
+        }
+        else
+        {
+            std::array<Key, 16> list = r.order == 0 || r.order == 1 || r.order >= 6 ? sorted : arp;
+            if (r.order == 4 || r.order == 5) // by velocity (ties keep their order)
+                for (int i = 1; i < n; ++i)
+                {
+                    const auto k = list[(std::size_t) i];
+                    auto j = i;
+                    for (; j > 0 && list[(std::size_t) (j - 1)].velocity > k.velocity; --j)
+                        list[(std::size_t) j] = list[(std::size_t) (j - 1)];
+                    list[(std::size_t) j] = k;
+                }
+            const auto reverse = r.order == 1 || r.order == 3 || r.order == 5;
+            for (int i = 0; i < n; ++i)
+            {
+                const auto& k = list[(std::size_t) (reverse ? n - 1 - i : i)];
+                push (k.note, k.velocity);
+            }
+        }
+        // input range wrap
+        for (int i = 0; i < keyCount; ++i)
+        {
+            auto& k = keys[(std::size_t) i].note;
+            while (k < r.wrapLow && k + 12 <= 127)
+                k += 12;
+            while (k > r.wrapHigh && k - 12 >= 0)
+                k -= 12;
+            k = std::clamp (k, std::min (r.wrapLow, r.wrapHigh), std::max (r.wrapLow, r.wrapHigh));
+        }
+        realKeys = keyCount;
+        // the missing keys N1…N5
+        filled = 0;
+        if (keyCount > 0 && keyCount < 5 && r.missing != 0)
+        {
+            const auto octave = r.missingOctave == 1 ? -12 : r.missingOctave == 2 ? 12 : 0;
+            for (int i = keyCount; i < 5; ++i)
+            {
+                Key k;
+                switch (r.missing)
+                {
+                    case 1: k = keys[(std::size_t) (i % realKeys)]; break;
+                    case 2: k = keys[0]; break;
+                    case 3: k = keys[(std::size_t) (realKeys - 1)]; break;
+                    default: k = { r.fixedKey, 96, 0 }; break;
+                }
+                k.note = std::clamp (k.note + octave, 0, 127);
+                keys[(std::size_t) i] = k;
+            }
+            filled = 5 - keyCount;
+        }
+    }
+
+    void detectChord (const std::array<Key, 16>& sorted, int n) noexcept
+    {
+        chordIndex = -1;
+        root = n > 0 ? sorted[0].note : 60;
+        int best = 0;
+        for (int b = 0; b < n; ++b)
+        {
+            const auto candidate = sorted[(std::size_t) b].note;
+            std::uint16_t mask = 0;
+            for (int i = 0; i < n; ++i)
+                mask = (std::uint16_t) (mask | (1u << (((sorted[(std::size_t) i].note - candidate) % 12 + 12) % 12)));
+            for (int c = 0; c < 38; ++c)
+            {
+                const auto& entry = chords[c];
+                if ((b == 0 || entry.inversion) && (entry.mask & ~mask) == 0 && entry.score > best)
+                {
+                    best = entry.score;
+                    chordIndex = c;
+                    root = candidate + entry.rootOffset;
+                }
+            }
+        }
+        if (chordIndex >= 0)
+            detectedScale = { chords[chordIndex].scale, chords[chordIndex].scaleCount };
+    }
+
+    const Scale* activeScale (const Runtime& r) const noexcept
+    {
+        if (r.forceScale == 1 && chordIndex >= 0)
+            return &detectedScale;
+        if (r.forceScale >= 2 && r.forceScale <= 14)
+            return &scales[r.forceScale - 2];
+        return nullptr;
+    }
+
+    // FL's pitch pipeline: scale forcing (snap down, move by scale steps), transpose, the output range
+    int pitch (int note, int scaleStep, bool force, const Runtime& r) const noexcept
+    {
+        auto key = r.forceKey - 2;
+        if (key == -1)
+            key = ((root % 12) + 12) % 12;
+        if (key == -2 && r.forceScale > 0 && keyCount > 0)
+            key = keys[0].note % 12;
+        const auto* scale = activeScale (r);
+        if (r.forceMode == 1 && scaleStep == 0)
+            force = false;
+        int n;
+        if (! force || scale == nullptr || key < 0)
+            n = note + scaleStep;
+        else
+        {
+            const auto rr = note - key + 12;
+            const auto octave = (int) std::floor (rr / 12.0) - 1;
+            const auto pc = ((rr % 12) + 12) % 12;
+            int d = 0;
+            for (int i = 0; i < scale->count; ++i)
+                if (scale->degrees[(std::size_t) i] <= pc)
+                    d = i;
+            d += scaleStep;
+            const auto carry = (int) std::floor ((double) d / scale->count);
+            d -= carry * scale->count;
+            n = std::clamp (scale->degrees[(std::size_t) d] + key + (octave + carry) * 12, 0, 127);
+        }
+        n += r.transposeSemitones + 12 * r.transposeOctaves;
+        if (n < r.outLow)
+        {
+            n += 12 * (int) std::ceil ((r.outLow - n) / 12.0);
+            if (n > r.outHigh)
+                n = r.outLow;
+        }
+        if (n > r.outHigh)
+        {
+            n -= 12 * (int) std::ceil ((n - r.outHigh) / 12.0);
+            if (n < r.outLow)
+                n = r.outHigh;
+        }
+        return std::clamp (n, 0, 127);
+    }
+
+    // --- one step ------------------------------------------------------------------------------------------------
+
+    int rand15() noexcept
+    {
+        seed ^= seed << 13;
+        seed ^= seed >> 17;
+        seed ^= seed << 5;
+        return (int) (seed & 0x7fff);
+    }
+
+    void generate (int step, int offset, const Runtime& r, EventList& out) noexcept
+    {
+        if (keyCount == 0 && r.programMode == 0)
+            return;
+        const auto s = (std::size_t) std::clamp (step, 0, 63);
+        const auto type = (int) r.lanes[S::stepType][s];
+        if (type == S::off || type == S::rest)
+            return;
+        struct Note
+        {
+            int note, velocity;
+        };
+        std::array<Note, 32> notes {};
+        int count = 0;
+        auto add = [&] (int note, int velocity) {
+            if (count < (int) notes.size())
+                notes[(std::size_t) count++] = { note, velocity };
+        };
+        if (type == S::chord)
+            for (int i = 0; i < realKeys; ++i)
+                add (keys[(std::size_t) i].note, keys[(std::size_t) i].velocity);
+        else if (type == S::random)
+        {
+            int pick = 0;
+            if (realKeys == 2)
+            {
+                pick = rand15() % 2;
+                if (pick == lastRandom && ++randomRepeats >= 3)
+                    pick = 1 - pick;
+                if (pick != lastRandom)
+                    randomRepeats = 0;
+            }
+            else if (realKeys > 2)
+            {
+                pick = rand15() % (realKeys - 1);
+                if (pick >= lastRandom && lastRandom >= 0)
+                    ++pick;
+            }
+            lastRandom = pick;
+            if (realKeys > 0)
+                add (keys[(std::size_t) pick].note, keys[(std::size_t) pick].velocity);
+        }
+        else
+        {
+            const auto select = (int) (std::uint8_t) r.lanes[S::keySelect][s];
+            const auto first = keyCount > 0 ? keys[0].velocity : 96;
+            for (int bit = 0; bit < 7; ++bit)
+            {
+                if ((select & (1 << bit)) == 0)
+                    continue;
+                if (bit == 0)
+                    add (r.fixedKey, 96);
+                else if (bit == 1)
+                    add (root, first);
+                else if (bit - 2 < keyCount + filled && bit - 2 < 5)
+                    add (keys[(std::size_t) (bit - 2)].note, keys[(std::size_t) (bit - 2)].velocity);
+            }
+        }
+        if (count == 0)
+            return;
+        // octaves (bit k = octave k − 3)
+        const auto octaves = (int) (std::uint8_t) r.lanes[S::octave][s];
+        if (r.polyOctave == 0)
+        {
+            int shift = 0;
+            for (int k = 0; k < 7; ++k)
+                if (octaves & (1 << k))
+                    shift += 12 * (k - 3);
+            for (int i = 0; i < count; ++i)
+                notes[(std::size_t) i].note += shift;
+        }
+        else
+        {
+            bool firstBit = true;
+            const auto base = notes[0];
+            for (int k = 0; k < 7; ++k)
+            {
+                if ((octaves & (1 << k)) == 0)
+                    continue;
+                if (firstBit)
+                {
+                    for (int i = 0; i < count; ++i)
+                        notes[(std::size_t) i].note += 12 * (k - 3);
+                    firstBit = false;
+                }
+                else
+                    add (base.note + 12 * (k - 3), base.velocity);
+            }
+        }
+        auto scaleStep = (int) r.lanes[S::scaleStep][s] + r.smartBend;
+        // gate (in steps)
+        auto gatePercent = (double) r.gate;
+        if (r.gateLaneMode == 0)
+            gatePercent = std::min (std::floor (std::pow (2.0, (double) r.lanes[S::gateStep][s]) * gatePercent + 0.5), r.steps * 100.0 - 1.0);
+        auto gate = gatePercent / 100.0;
+        if (r.randomGate > 0)
+            gate += r.randomGate * (rand15() - 16383) / 100.0 / 32767.0;
+        gate = std::max (0.01, gate);
+        // the following rests lengthen it; a tie makes it overlap the next note (legato)
+        for (int k = 1; k < r.steps; ++k)
+        {
+            const auto t = (int) r.lanes[S::stepType][(std::size_t) ((step + k) % std::max (1, r.steps))];
+            if (t == S::rest)
+            {
+                gate += 1.0;
+                continue;
+            }
+            if (t == S::tie && gate < 1.25)
+                gate = 1.25;
+            break;
+        }
+        double delay = 0.0;
+        if (r.randomStart > 0 && r.smartBend == 0)
+            delay = rand15() / 32767.0 * stepSamples * r.randomStart / 200.0;
+        for (int i = 0; i < count; ++i)
+        {
+            const auto note = pitch (notes[(std::size_t) i].note, scaleStep, true, r);
+            int velocity = r.lanes[S::velocity][s];
+            if (r.velocityMode == 1)
+                velocity = notes[(std::size_t) i].velocity;
+            else if (r.velocityMode == 2)
+                velocity = std::clamp (notes[(std::size_t) i].velocity + velocity - 96, 0, 127);
+            if (r.randomVelocity > 0)
+                velocity = std::clamp ((int) std::lround (velocity + r.randomVelocity * ((rand15() - 16383.5) / 32767.0) * 1.27), 0, 127);
+            start (note, velocity, offset, delay, gate * stepSamples, out);
+        }
+    }
+
+    void start (int note, int velocity, int offset, double delay, double gateSamples, EventList& out) noexcept
+    {
+        for (int i = 0; i < soundingCount; ++i)
+        {
+            auto& e = sounding[(std::size_t) i];
+            if (e.note != note)
+                continue;
+            if (e.started) // (the same pitch: retriggered)
+                off (e.id, e.note, offset, out);
+            e = { note, velocity, newId(), delay, gateSamples, false };
+            if (delay <= 0.0)
+                begin (e, offset, out);
+            return;
+        }
+        if (soundingCount >= (int) sounding.size())
+            return;
+        auto& e = sounding[(std::size_t) soundingCount++];
+        e = { note, velocity, newId(), delay, gateSamples, false };
+        if (delay <= 0.0)
+            begin (e, offset, out);
+    }
+
+    void begin (Sounding& e, int offset, EventList& out) noexcept
+    {
+        Voice v;
+        v.key = e.note;
+        v.velocity = voiceVelocity (e.velocity);
+        out.add (onEvent (offset, e.id, v));
+        e.started = true;
+    }
+
+    // one sample of the sounding notes: delayed starts, gate countdowns
+    void schedule (int offset, EventList& out) noexcept
+    {
+        for (int i = 0; i < soundingCount;)
+        {
+            auto& e = sounding[(std::size_t) i];
+            if (! e.started)
+            {
+                e.startDelay -= 1.0;
+                if (e.startDelay <= 0.0)
+                    begin (e, offset, out);
+                ++i;
+                continue;
+            }
+            e.gate -= 1.0;
+            if (e.gate < 0.01)
+            {
+                off (e.id, e.note, offset, out);
+                sounding[(std::size_t) i] = sounding[(std::size_t) --soundingCount];
+                continue;
+            }
+            ++i;
+        }
+    }
+
+    void killAll (int offset, EventList& out) noexcept
+    {
+        for (int i = 0; i < soundingCount; ++i)
+            if (sounding[(std::size_t) i].started)
+                off (sounding[(std::size_t) i].id, sounding[(std::size_t) i].note, offset, out);
+        soundingCount = 0;
+        for (int i = 0; i < thruCount; ++i)
+            off (thru[(std::size_t) i].id, thru[(std::size_t) i].note, offset, out);
+        thruCount = 0;
+    }
+
+    int newId() noexcept
+    {
+        const auto id = nextId++;
+        if (nextId > 1 << 30)
+            nextId = 1;
+        return id;
+    }
+
+    static Event onEvent (int offset, int id, const Voice& v) noexcept
+    {
+        Event e;
+        e.type = Event::Type::on;
+        e.offset = offset;
+        e.id = id;
+        e.voice = v;
+        return e;
+    }
+
+    static void off (int id, int note, int offset, EventList& out) noexcept
+    {
+        Event e;
+        e.type = Event::Type::off;
+        e.offset = offset;
+        e.id = id;
+        e.voice.key = note;
+        out.add (e);
+    }
+
+    Handoff<Runtime> settings;
+    std::array<Key, 16> held {}, arp {}, keys {};
+    int heldCount = 0, arpCount = 0, keyCount = 0, realKeys = 0, filled = 0;
+    int chordIndex = -1, root = 60;
+    std::array<Sounding, 16> sounding {};
+    int soundingCount = 0;
+    std::array<Thru, 64> thru {};
+    int thruCount = 0;
+    int nextId = 1, lastStep = -1, lastArpMode = -1, lastRandom = -1, randomRepeats = 0;
+    long long lastCell = -1, tailSamples = 0;
+    bool keysDirty = false, regenerate = false, wasPlaying = false, anchored = false, anchoredByKey = false;
+    int freeRun = 0; // 0 off, 1 running, 2 the second after the last key
+    double freeBeats = 0.0, restartOffset = 0.0, lastSongBeats = 0.0, stepSamples = 1.0, sampleRate = 44100.0;
+    std::uint32_t seed = 0x2545f491u;
+    int arrivals = 0;
+    Scale detectedScale {};
+};
+} // namespace
+
+std::unique_ptr<Processor> makeSequencer (const std::vector<std::uint8_t>& fl)
+{
+    return std::make_unique<Sequencer> (parseSequencer (fl).value_or (defaultSequencer()));
+}
+} // namespace lynx::vfx

+ 506 - 0
src/ui/VfxEditors.cpp

@@ -1322,6 +1322,507 @@ private:
     CurveEditor editor;
     CurveEditor editor;
 };
 };
 
 
+// ---------------------------------------------------------------------------------------------------------------
+// VFX Sequencer: the program (sequence) and its parameters on top, the note matrix (which key each step plays) and
+// one lane (velocity, octave, gate, step type or scale step) below, 16 steps per page
+
+class SequencerBody final : public Body
+{
+public:
+    using S = vfx::SequencerSettings;
+
+    SequencerBody()
+    {
+        program.onClick = [this] { showProgramMenu(); };
+        ui::setHint (program, tr ("The sequence (program) of the bank that plays; the bank keeps 128"));
+        addAndMakeVisible (program);
+        for (auto* b : { &prevProgram, &nextProgram, &dice })
+        {
+            b->setWantsKeyboardFocus (false);
+            addAndMakeVisible (b);
+        }
+        prevProgram.onClick = [this] { stepProgram (-1); };
+        nextProgram.onClick = [this] { stepProgram (1); };
+        dice.onClick = [this] {
+            // a random sequence of those that differ from the first (the bank's empty slots are copies of it)
+            std::vector<int> candidates;
+            for (int p = 1; p < (int) settings.programs.size(); ++p)
+                if (settings.programs[(std::size_t) p].lanes != settings.programs[0].lanes || settings.programs[(std::size_t) p].params != settings.programs[0].params)
+                    candidates.push_back (p);
+            if (! candidates.empty())
+                change ([n = candidates[(std::size_t) juce::Random::getSystemRandom().nextInt ((int) candidates.size())]] (S& s) { s.set (S::currentProgram, n); });
+        };
+        ui::setHint (dice, tr ("A random sequence"));
+        for (int p = 0; p < 4; ++p)
+        {
+            auto& b = pages[(std::size_t) p];
+            b.setButtonText (juce::String (p + 1));
+            b.setClickingTogglesState (false);
+            b.setColour (juce::TextButton::buttonOnColourId, theme::colour::accentMuted);
+            b.onClick = [this, p] { change ([p] (S& s) { s.set (S::page, p); }); };
+            ui::setHint (b, tr ("Steps {0} to {1}", { juce::String (p * 16 + 1), juce::String (p * 16 + 16) }));
+            addAndMakeVisible (b);
+        }
+        toggle (pageLock, tr ("Page lock"), S::pageLock, tr ("Plays only the page shown"));
+        toggle (latch, tr ("Latch"), S::latch, tr ("Latch: the notes keep playing after the keys are released, until a new chord"));
+        toggle (polyOctave, tr ("Poly"), S::polyOctave, tr ("Several octaves per step (else one)"));
+        toggle (polyKeys, tr ("Poly"), S::polyKeys, tr ("Several keys per step (else one)"));
+        toggle (gateLaneMode, tr ("Channels"), S::gateLaneMode, tr ("The gate lane sets each step's output channel instead of its length"));
+        shiftLeft.onClick = [this] { change ([] (S& s) { vfx::shiftPattern (s, -1); }); };
+        shiftRight.onClick = [this] { change ([] (S& s) { vfx::shiftPattern (s, 1); }); };
+        ui::setHint (shiftLeft, tr ("Shift the pattern one step earlier"));
+        ui::setHint (shiftRight, tr ("Shift the pattern one step later"));
+        for (auto* b : { &shiftLeft, &shiftRight })
+            addAndMakeVisible (b);
+
+        combo (arpMode, tr ("Mode"), S::arpMode, { tr ("Off"), tr ("On"), tr ("Thru"), tr ("On from 2 keys, else off"), tr ("On from 2 keys, else thru"),
+                                                    tr ("On from 3 keys, else off"), tr ("On from 3 keys, else thru") });
+        combo (sync, tr ("Step"), S::sync, { "1/64", "1/48", "1/32", "1/24", "1/16", "1/12", "1/8", "1/6", "1/4", "3/64", "3/32", "3/16", "3/8" });
+        combo (order, tr ("Order"), S::order, { tr ("By pitch"), tr ("By pitch, descending"), tr ("As played"), tr ("As played, reversed"),
+                                                 tr ("By velocity"), tr ("By velocity, descending"), tr ("Chord, normalized"), tr ("Chord, as played") });
+        combo (missing, tr ("Missing keys"), S::missingKeys, { tr ("Not played"), tr ("Cyclic"), tr ("First key"), tr ("Last key"), tr ("Fixed key") });
+        combo (missingOctave, tr ("Missing octave"), S::missingOctave, { tr ("Same"), "-1", "+1" });
+        combo (restart, tr ("Restart on"), S::restartOn, { tr ("Beat"), tr ("Key"), tr ("First key"), tr ("Play") });
+        juce::StringArray keysList { tr ("Off"), tr ("Detect") };
+        for (int k = 0; k < 12; ++k)
+            keysList.add (pitchClassName (k));
+        combo (forceKey, tr ("Scale key"), S::forceKey, keysList);
+        combo (forceScale, tr ("Scale"), S::forceScale, { tr ("Chromatic"), tr ("Detect"), tr ("Major"), tr ("Minor"), tr ("Harmonic minor"), tr ("Melodic minor"),
+                                                          tr ("Pentatonic major"), tr ("Pentatonic minor"), tr ("Pentatonic neutral"), tr ("Blues"),
+                                                          tr ("Dorian"), tr ("Phrygian"), tr ("Lydian"), tr ("Mixolydian"), tr ("Locrian") });
+        combo (forceMode, tr ("Scale mode"), S::forceMode, { tr ("All notes"), tr ("Scale steps only") });
+        combo (velocityMode, tr ("Velocity"), S::velocityMode, { tr ("From the lane"), tr ("From the keys"), tr ("Keys + lane") });
+        combo (quantize, tr ("Input quantize"), S::inputQuantize, { tr ("None"), "1/16", "1/12", "1/8", "1/6", "1/4", "1/2", tr ("1 bar"), tr ("2 bars") });
+        combo (programMode, tr ("Input"), S::programMode, { tr ("The held keys"), tr ("The fixed key") });
+        ui::setHint (arpMode, tr ("Mode: Thru passes the notes (transposed); the auto modes play only while enough keys are held"));
+        ui::setHint (order, tr ("Order: how the held keys are numbered N1, N2…"));
+        ui::setHint (missing, tr ("What the steps of a key that is not held play"));
+        ui::setHint (restart, tr ("Where the sequence starts: on the song's beats, at each new key, at the first key, at play"));
+        ui::setHint (forceKey, tr ("Scale key: Detect takes the held chord's root"));
+        ui::setHint (forceScale, tr ("Scale: the notes snap to it and the scale-step lane moves along it"));
+        ui::setHint (quantize, tr ("Input quantize: chord changes wait for this grid"));
+
+        knob (steps, tr ("Steps"), S::steps);
+        knob (gate, tr ("Gate"), S::gate, [] (double v) { return juce::String ((int) v) + " %"; });
+        knob (swing, tr ("Swing"), S::swing);
+        knob (transpose, tr ("Transpose"), S::transposeSemitones);
+        knob (octaves, tr ("Octave"), S::transposeOctaves);
+        knob (fixedKey, tr ("Fixed key"), S::fixedKey, [] (double v) { return keyName ((int) v); });
+        knob (randomVelocity, tr ("Rand. vel."), S::randomVelocity, [] (double v) { return juce::String ((int) v) + " %"; });
+        knob (randomGate, tr ("Rand. gate"), S::randomGate, [] (double v) { return juce::String ((int) v) + " %"; });
+        knob (randomStart, tr ("Rand. start"), S::randomStart, [] (double v) { return juce::String ((int) v) + " %"; });
+        knob (smartBend, tr ("Smart bend"), S::smartBend);
+        knob (outLow, tr ("Out low"), S::outputLow, [] (double v) { return keyName ((int) v); });
+        knob (outHigh, tr ("Out high"), S::outputHigh, [] (double v) { return keyName ((int) v); });
+
+        static const char* laneNames[] = { TR_NOOP ("Velocity"), TR_NOOP ("Octave"), TR_NOOP ("Gate"), TR_NOOP ("Step type"), TR_NOOP ("Scale step") };
+        for (int l = 0; l < 5; ++l)
+        {
+            auto& b = laneTabs[(std::size_t) l];
+            b.setButtonText (tr (laneNames[l]));
+            b.setClickingTogglesState (false);
+            b.setColour (juce::TextButton::buttonOnColourId, theme::colour::accentMuted);
+            b.onClick = [this, l] { change ([l] (S& s) { s.set (S::selectedLayer, l); }); };
+            addAndMakeVisible (b);
+        }
+        matrix.owner = lane.owner = this;
+        lane.isMatrix = false;
+        addAndMakeVisible (matrix);
+        addAndMakeVisible (lane);
+    }
+
+    void refresh (const std::vector<std::uint8_t>& fl) override
+    {
+        settings = vfx::parseSequencer (fl).value_or (vfx::defaultSequencer());
+        const auto p = settings.program();
+        program.setButtonText (juce::String (p + 1) + "  " + juce::String (settings.current().nameText()));
+        for (int k = 0; k < 4; ++k)
+            pages[(std::size_t) k].setToggleState (k == settings.get (S::page), juce::dontSendNotification);
+        for (int k = 0; k < 5; ++k)
+            laneTabs[(std::size_t) k].setToggleState (k == layer(), juce::dontSendNotification);
+        for (auto& [b, param] : toggles)
+            b->setToggleState (settings.get (param) != 0, juce::dontSendNotification);
+        for (auto& [c, param] : combos)
+            c->setSelectedItemIndex (settings.get (param) - S::minimum (param), juce::dontSendNotification);
+        polyOctave.setVisible (layer() == 1);
+        gateLaneMode.setVisible (layer() == 2);
+        for (auto* c : getChildren())
+            if (dynamic_cast<Knob*> (c) != nullptr)
+                c->repaint();
+        matrix.repaint();
+        lane.repaint();
+        repaint();
+    }
+
+    int preferredWidth() const override { return 940; }
+    int preferredHeight() const override { return 610; }
+
+    void resized() override
+    {
+        auto area = getLocalBounds().reduced (12, 4);
+        auto top = area.removeFromTop (30);
+        prevProgram.setBounds (top.removeFromLeft (26));
+        program.setBounds (top.removeFromLeft (300));
+        nextProgram.setBounds (top.removeFromLeft (26));
+        top.removeFromLeft (4);
+        dice.setBounds (top.removeFromLeft (30));
+        top.removeFromLeft (14);
+        latch.setBounds (top.removeFromLeft (80));
+        shiftRight.setBounds (top.removeFromRight (26));
+        shiftLeft.setBounds (top.removeFromRight (26));
+        top.removeFromRight (12);
+        pageLock.setBounds (top.removeFromRight (100));
+        for (int k = 3; k >= 0; --k)
+            pages[(std::size_t) k].setBounds (top.removeFromRight (30).reduced (1, 0));
+        area.removeFromTop (6);
+
+        // two rows of combos and knobs
+        auto layoutRow = [] (juce::Rectangle<int> row, std::initializer_list<juce::Component*> items, std::initializer_list<int> widths) {
+            auto w = widths.begin();
+            for (auto* c : items)
+            {
+                c->setBounds (row.removeFromLeft (*w++).reduced (3, 0));
+            }
+        };
+        auto row1 = area.removeFromTop (64);
+        layoutRow (row1.withTrimmedTop (18).withHeight (26), { &arpMode, &sync, &order, &missing, &missingOctave, &restart },
+                   { 150, 80, 160, 110, 80, 100 });
+        row1.removeFromLeft (680);
+        for (auto* k : { steps.get(), gate.get(), swing.get(), transpose.get() })
+            k->setBounds (row1.removeFromLeft (60));
+        auto row2 = area.removeFromTop (64);
+        layoutRow (row2.withTrimmedTop (18).withHeight (26), { &forceKey, &forceScale, &forceMode, &velocityMode, &quantize, &programMode },
+                   { 80, 150, 130, 120, 100, 100 });
+        row2.removeFromLeft (680);
+        for (auto* k : { octaves.get(), fixedKey.get(), outLow.get(), outHigh.get() })
+            k->setBounds (row2.removeFromLeft (60));
+        area.removeFromTop (8);
+
+        matrix.setBounds (area.removeFromTop (7 * 17 + 18));
+        area.removeFromTop (8);
+        auto tabs = area.removeFromTop (26);
+        for (auto& b : laneTabs)
+            b.setBounds (tabs.removeFromLeft (96).reduced (1, 0));
+        tabs.removeFromLeft (10);
+        polyOctave.setBounds (tabs.withWidth (80));
+        gateLaneMode.setBounds (tabs.withWidth (110));
+        polyKeys.setBounds (getLocalBounds().reduced (12, 0).getRight() - 70, matrix.getY(), 70, 18);
+        area.removeFromTop (4);
+        auto bottom = area.removeFromBottom (64);
+        for (auto* k : { randomVelocity.get(), randomGate.get(), randomStart.get(), smartBend.get() })
+            k->setBounds (bottom.removeFromLeft (70));
+        lane.setBounds (area);
+    }
+
+    void paint (juce::Graphics& g) override
+    {
+        g.setFont (theme::font (theme::type::caption));
+        g.setColour (theme::colour::textSecondary);
+        for (auto& [c, param] : combos)
+            g.drawText (theme::caps (c->getName()), c->getBounds().translated (0, -18).withHeight (16), juce::Justification::centredLeft);
+    }
+
+    // the step grid: the note matrix (rows Fixed, Root, N5…N1) or one lane
+    struct Grid final : juce::Component
+    {
+        SequencerBody* owner = nullptr;
+        bool isMatrix = true;
+
+        static constexpr int labelWidth = 70;
+
+        int laneKind() const { return isMatrix ? -1 : owner->layer(); }
+        int rows() const
+        {
+            switch (laneKind())
+            {
+                case -1: return 7;
+                case 1: return 7;  // octave −3…+3
+                case 2: return owner->settings.get (S::gateLaneMode) != 0 ? 0 : 9;
+                case 3: return 6;  // step type
+                default: return 0; // bars
+            }
+        }
+        juce::String rowName (int row) const
+        {
+            switch (laneKind())
+            {
+                case -1:
+                {
+                    static const char* names[] = { "Fixed", "Root", "N5", "N4", "N3", "N2", "N1" };
+                    return row < 2 ? tr (names[row]) : names[row];
+                }
+                case 1: return row == 3 ? "0" : (row < 3 ? "+" : "") + juce::String (3 - row);
+                case 2:
+                {
+                    static const char* names[] = { "32x", "16x", "8x", "4x", "2x", "1x", "1/2", "1/4", "1/8" };
+                    return names[row];
+                }
+                case 3:
+                {
+                    static const char* names[] = { TR_NOOP ("Random"), TR_NOOP ("Chord"), TR_NOOP ("Tie"), TR_NOOP ("Rest"), TR_NOOP ("Note"), TR_NOOP ("Off") };
+                    return tr (names[row]);
+                }
+                default: return {};
+            }
+        }
+        // the lane and its value range
+        int laneIndex() const
+        {
+            switch (laneKind())
+            {
+                case -1: return S::keySelect;
+                case 0: return S::velocity;
+                case 1: return S::octave;
+                case 2: return S::gateStep;
+                case 3: return S::stepType;
+                default: return S::scaleStep;
+            }
+        }
+        juce::Rectangle<int> cells() const { return getLocalBounds().withTrimmedLeft (labelWidth).withTrimmedBottom (18); }
+        int firstStep() const { return owner->settings.get (S::page) * 16; }
+        int stepAt (int x) const
+        {
+            const auto c = cells();
+            return firstStep() + juce::jlimit (0, 15, (x - c.getX()) * 16 / std::max (1, c.getWidth()));
+        }
+        int rowAt (int y) const
+        {
+            const auto c = cells();
+            return juce::jlimit (0, rows() - 1, (y - c.getY()) * rows() / std::max (1, c.getHeight()));
+        }
+        bool rowSet (int value, int row) const
+        {
+            switch (laneKind())
+            {
+                case -1: return (value & (1 << (row < 2 ? row : 8 - row))) != 0;
+                case 1: return (value & (1 << (6 - row))) != 0;
+                case 2: return value == 5 - row;
+                default: return value == 5 - row; // step type: row 0 = Random (5) … row 5 = Off (0)
+            }
+        }
+        int barMin() const { return laneKind() == 4 ? -12 : 0; }
+        int barMax() const { return laneKind() == 4 ? 12 : laneKind() == 2 ? 16 : 127; }
+
+        void paint (juce::Graphics& g) override
+        {
+            const auto& s = owner->settings;
+            const auto c = cells();
+            const auto steps = s.get (S::steps);
+            const auto lane = laneIndex();
+            const auto w = c.getWidth() / 16.0f;
+            g.setColour (theme::colour::bg0);
+            g.fillRect (c);
+            for (int k = 0; k < 16; ++k)
+            {
+                const auto step = firstStep() + k;
+                const auto x = c.getX() + k * w;
+                const auto used = step < steps;
+                if (k % 4 == 0)
+                {
+                    g.setColour (theme::colour::bg3.withAlpha (0.5f));
+                    g.fillRect (juce::Rectangle<float> (x, (float) c.getY(), w * 4.0f, (float) c.getHeight()).withWidth (w));
+                }
+                g.setColour (theme::colour::textSecondary);
+                g.setFont (theme::font (theme::type::caption));
+                g.drawText (juce::String (step + 1), juce::Rectangle<float> (x, (float) c.getBottom() + 2.0f, w, 14.0f), juce::Justification::centred);
+                const auto value = (int) s.programs[(std::size_t) s.program()].lanes[(std::size_t) lane][(std::size_t) step];
+                const auto type = (int) s.current().lanes[S::stepType][(std::size_t) step];
+                const auto silent = type == S::off || type == S::rest;
+                auto colour = used ? theme::colour::accent : theme::colour::textDisabled;
+                if (rows() > 0)
+                {
+                    const auto h = c.getHeight() / (float) rows();
+                    for (int r = 0; r < rows(); ++r)
+                    {
+                        const auto cell = juce::Rectangle<float> (x, c.getY() + r * h, w, h).reduced (1.5f);
+                        g.setColour (theme::colour::bg4.withAlpha (used ? 1.0f : 0.4f));
+                        g.fillRoundedRectangle (cell, 2.0f);
+                        if (rowSet (value, r))
+                        {
+                            auto col = colour;
+                            if (isMatrix && (silent || type == S::chord || type == S::random))
+                                col = col.withAlpha (0.35f); // (those steps do not use the matrix)
+                            g.setColour (col);
+                            g.fillRoundedRectangle (cell, 2.0f);
+                        }
+                    }
+                }
+                else
+                {
+                    const auto lo = barMin(), hi = barMax();
+                    auto zero = (float) c.getBottom();
+                    if (lo < 0)
+                        zero = c.getY() + c.getHeight() * (float) hi / (float) (hi - lo);
+                    const auto y = c.getY() + c.getHeight() * (float) (hi - value) / (float) (hi - lo);
+                    auto bar = juce::Rectangle<float>::leftTopRightBottom (x + 2.0f, std::min (y, zero), x + w - 2.0f, std::max (y, zero));
+                    g.setColour (colour.withAlpha (silent ? 0.35f : 1.0f));
+                    g.fillRect (bar.withHeight (std::max (2.0f, bar.getHeight())));
+                    g.setColour (theme::colour::textPrimary);
+                    g.setFont (theme::font (theme::type::caption));
+                    const auto text = laneKind() == 2 ? (value == 0 ? juce::String ("-") : juce::String (value)) : juce::String (value);
+                    g.drawText (text, juce::Rectangle<float> (x, (float) c.getY() + 2.0f, w, 12.0f), juce::Justification::centred);
+                    if (lo < 0)
+                    {
+                        g.setColour (theme::colour::borderStrong);
+                        g.drawHorizontalLine ((int) zero, x, x + w);
+                    }
+                }
+            }
+            // row labels
+            g.setFont (theme::font (theme::type::caption));
+            g.setColour (theme::colour::textSecondary);
+            if (rows() > 0)
+            {
+                const auto h = c.getHeight() / (float) rows();
+                for (int r = 0; r < rows(); ++r)
+                    g.drawText (rowName (r), juce::Rectangle<float> (0.0f, c.getY() + r * h, labelWidth - 6.0f, h), juce::Justification::centredRight);
+            }
+            else
+                g.drawText (laneKind() == 4 ? tr ("Semitones / scale steps") : laneKind() == 2 ? tr ("Channel") : tr ("Velocity"),
+                            juce::Rectangle<int> (0, c.getY(), labelWidth - 6, c.getHeight()), juce::Justification::centredRight, true);
+        }
+
+        void mouseDown (const juce::MouseEvent& e) override
+        {
+            lastStep = -1;
+            if (rows() > 0)
+            {
+                const auto step = stepAt (e.x);
+                const auto row = rowAt (e.y);
+                const auto& s = owner->settings;
+                const auto value = (int) s.current().lanes[(std::size_t) laneIndex()][(std::size_t) step];
+                // a click sets the row; in a poly lane it toggles it
+                painting = ! rowSet (value, row);
+                paintRow = row;
+            }
+            mouseDrag (e);
+        }
+
+        void mouseDrag (const juce::MouseEvent& e) override
+        {
+            const auto step = stepAt (e.x);
+            const auto lane = laneIndex();
+            const auto right = e.mods.isPopupMenu();
+            if (rows() > 0)
+            {
+                if (step == lastStep)
+                    return;
+                lastStep = step;
+                const auto kind = laneKind();
+                const auto row = paintRow;
+                const auto set = painting;
+                const auto poly = (kind == -1 && owner->settings.get (S::polyKeys) != 0) || (kind == 1 && owner->settings.get (S::polyOctave) != 0);
+                owner->change ([=] (S& s) {
+                    auto& v = s.current().lanes[(std::size_t) lane][(std::size_t) step];
+                    if (kind == -1 || kind == 1)
+                    {
+                        const auto bit = kind == -1 ? (row < 2 ? row : 8 - row) : 6 - row;
+                        if (right)
+                            v = 0; // (right-click: the step plays nothing)
+                        else if (poly)
+                            v = (std::int8_t) (set ? (v | (1 << bit)) : (v & ~(1 << bit)));
+                        else
+                            v = (std::int8_t) (1 << bit);
+                    }
+                    else
+                        v = (std::int8_t) (5 - row);
+                });
+                return;
+            }
+            const auto c = cells();
+            const auto lo = barMin(), hi = barMax();
+            const auto value = right ? (laneKind() == 0 ? 96 : 0)
+                                     : juce::jlimit (lo, hi, (int) std::lround (hi - (e.y - c.getY()) * (double) (hi - lo) / std::max (1, c.getHeight())));
+            owner->change ([=] (S& s) { s.current().lanes[(std::size_t) lane][(std::size_t) step] = (std::int8_t) value; });
+        }
+
+        int lastStep = -1, paintRow = 0;
+        bool painting = true;
+    };
+
+private:
+    int layer() const { return juce::jlimit (0, 4, settings.get (S::selectedLayer)); }
+
+    void change (std::function<void (S&)> f)
+    {
+        if (edit)
+            edit ([f] (std::vector<std::uint8_t>& fl) {
+                auto s = vfx::parseSequencer (fl).value_or (vfx::defaultSequencer());
+                f (s);
+                fl = vfx::writeSequencer (s);
+            });
+    }
+
+    void toggle (juce::ToggleButton& b, const juce::String& text, int param, const juce::String& hint)
+    {
+        b.setButtonText (text);
+        b.onClick = [this, &b, param] { change ([param, on = b.getToggleState()] (S& s) { s.set (param, on ? 1 : 0); }); };
+        ui::setHint (b, hint);
+        addAndMakeVisible (b);
+        toggles.push_back ({ &b, param });
+    }
+
+    void combo (juce::ComboBox& c, const juce::String& name, int param, const juce::StringArray& items)
+    {
+        c.setName (name);
+        c.addItemList (items, 1);
+        c.onChange = [this, &c, param] { change ([param, v = c.getSelectedItemIndex() + S::minimum (param)] (S& s) { s.set (param, v); }); };
+        ui::setHint (c, name);
+        addAndMakeVisible (c);
+        combos.push_back ({ &c, param });
+    }
+
+    void knob (std::unique_ptr<Knob>& k, const juce::String& name, int param, std::function<juce::String (double)> text = nullptr)
+    {
+        const auto lo = S::minimum (param), hi = S::maximum (param);
+        k = std::make_unique<Knob> (intSpec (name, lo, hi, defaultOf (param), std::move (text)), [this, param] { return (double) settings.get (param); },
+                                    [this, param] (double v) { change ([param, v] (S& s) { s.set (param, (int) std::lround (v)); }); });
+        k->caption = name;
+        addAndMakeVisible (*k);
+    }
+
+    static int defaultOf (int param)
+    {
+        static const auto blank = [] {
+            auto s = vfx::defaultSequencer();
+            s.set (S::currentProgram, 0);
+            return s;
+        }();
+        return blank.get (param);
+    }
+
+    void showProgramMenu()
+    {
+        juce::PopupMenu menu;
+        for (int group = 0; group < (int) settings.programs.size(); group += 16)
+        {
+            juce::PopupMenu sub;
+            for (int p = group; p < std::min (group + 16, (int) settings.programs.size()); ++p)
+                sub.addItem (juce::String (p + 1) + "  " + juce::String (settings.programs[(std::size_t) p].nameText()), true, p == settings.program(),
+                             [this, p] { change ([p] (S& s) { s.set (S::currentProgram, p); }); });
+            menu.addSubMenu (juce::String (group + 1) + "-" + juce::String (group + 16), sub, true, nullptr, settings.program() / 16 == group / 16);
+        }
+        menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&program));
+    }
+
+    void stepProgram (int delta)
+    {
+        const auto n = std::max (1, (int) settings.programs.size());
+        change ([delta, n] (S& s) { s.set (S::currentProgram, (s.program() + delta + n) % n); });
+    }
+
+    S settings = vfx::defaultSequencer();
+    juce::TextButton program, prevProgram { "<" }, nextProgram { ">" }, dice { "?" }, shiftLeft { "<<" }, shiftRight { ">>" };
+    std::array<juce::TextButton, 4> pages;
+    std::array<juce::TextButton, 5> laneTabs;
+    juce::ToggleButton pageLock, latch, polyOctave, polyKeys, gateLaneMode;
+    juce::ComboBox arpMode, sync, order, missing, missingOctave, restart, forceKey, forceScale, forceMode, velocityMode, quantize, programMode;
+    std::unique_ptr<Knob> steps, gate, swing, transpose, octaves, fixedKey, randomVelocity, randomGate, randomStart, smartBend, outLow, outHigh;
+    std::vector<std::pair<juce::ToggleButton*, int>> toggles;
+    std::vector<std::pair<juce::ComboBox*, int>> combos;
+    Grid matrix, lane;
+};
+
 // A kind LYNX does not edit yet: says so (its notes pass through)
 // A kind LYNX does not edit yet: says so (its notes pass through)
 class PendingBody final : public Body
 class PendingBody final : public Body
 {
 {
@@ -1346,6 +1847,7 @@ std::unique_ptr<Body> makeBody (vfx::Kind kind)
         case vfx::Kind::levelScaler: return std::make_unique<LevelScalerBody>();
         case vfx::Kind::levelScaler: return std::make_unique<LevelScalerBody>();
         case vfx::Kind::keyboardSplitter: return std::make_unique<KeyboardSplitterBody>();
         case vfx::Kind::keyboardSplitter: return std::make_unique<KeyboardSplitterBody>();
         case vfx::Kind::envelope: return std::make_unique<EnvelopeBody>();
         case vfx::Kind::envelope: return std::make_unique<EnvelopeBody>();
+        case vfx::Kind::sequencer: return std::make_unique<SequencerBody>();
         default: break;
         default: break;
     }
     }
     return std::make_unique<PendingBody>();
     return std::make_unique<PendingBody>();
@@ -1492,6 +1994,10 @@ private:
                 const auto folder = f.getParentDirectory() == base ? juce::String() : f.getParentDirectory().getFileName();
                 const auto folder = f.getParentDirectory() == base ? juce::String() : f.getParentDirectory().getFileName();
                 out.push_back ({ "FL Studio" + (folder.isEmpty() ? juce::String() : " / " + folder), f.getFileNameWithoutExtension(), {}, f });
                 out.push_back ({ "FL Studio" + (folder.isEmpty() ? juce::String() : " / " + folder), f.getFileNameWithoutExtension(), {}, f });
             }
             }
+            // the Sequencer's factory programs are one bank: the state of FL's plugin database entry
+            const auto bank = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin database/Effects/Patcher/VFX Sequencer.fst");
+            if (kind == vfx::Kind::sequencer && bank.existsAsFile())
+                out.push_back ({ "FL Studio", tr ("Factory bank"), {}, bank });
         }
         }
         return out;
         return out;
     }
     }

+ 270 - 0
tests/Vfx164Tests.inc

@@ -526,3 +526,273 @@ TEST (vfx_envelope_moves_the_notes_it_matches)
     const auto off = run (*p, { on (60) });
     const auto off = run (*p, { on (60) });
     CHECK (off.size() == 1 && off[0].voice.cents == 0.0f);
     CHECK (off.size() == 1 && off[0].voice.cents == 0.0f);
 }
 }
+
+namespace vfx164
+{
+// A sequencer note heard: its key, start and length in seconds, velocity (FL's 0…127, the volume × 100)
+struct SeqNote
+{
+    int key = 0;
+    double start = 0.0, length = -1.0;
+    int velocity = 0;
+};
+
+// Plays `input` (seconds, key, on / off) through the processor at 120 bpm / 48 kHz with the song playing from 0
+// (or stopped), and returns the notes it sent out
+std::vector<SeqNote> sequence (lynx::vfx::Processor& p, std::vector<std::tuple<double, int, bool>> input, double seconds,
+                               bool playing = true, float velocity = 100.0f / 128.0f)
+{
+    constexpr int block = 480;
+    constexpr double rate = 48000.0;
+    std::vector<SeqNote> notes;
+    std::map<int, std::size_t> open;
+    lynx::vfx::EventList out;
+    lynx::vfx::Transport t;
+    t.sampleRate = rate;
+    t.bpm = 120.0;
+    t.playing = playing;
+    for (long long at = 0; at < (long long) (seconds * rate); at += block)
+    {
+        std::vector<lynx::vfx::Event> in;
+        for (const auto& [time, key, down] : input)
+        {
+            const auto sample = (long long) std::llround (time * rate);
+            if (sample >= at && sample < at + block)
+            {
+                auto e = down ? on (key, (int) (sample - at), 0, velocity) : off (key, (int) (sample - at));
+                in.push_back (e);
+            }
+        }
+        t.ticks = playing ? (double) at / rate * 2.0 * 960.0 : 0.0;
+        out.clear();
+        p.process (in.data(), (int) in.size(), block, t, out);
+        out.sortByOffset();
+        for (int k = 0; k < out.size(); ++k)
+        {
+            const auto& e = out[k];
+            const auto time = (double) (at + e.offset) / rate;
+            if (e.type == lynx::vfx::Event::Type::on)
+            {
+                const auto volume = (std::pow (11.0, 1.28 * (double) e.voice.velocity) - 1.0) / 10.0;
+                open[e.id] = notes.size();
+                notes.push_back ({ e.voice.key, time, -1.0, (int) std::lround (volume * 100.0) });
+            }
+            else if (e.type == lynx::vfx::Event::Type::off && open.count (e.id))
+                notes[open[e.id]].length = time - notes[open[e.id]].start;
+        }
+    }
+    return notes;
+}
+
+lynx::vfx::SequencerSettings blankProgram()
+{
+    auto s = lynx::vfx::defaultSequencer();
+    s.set (lynx::vfx::SequencerSettings::currentProgram, 0); // "Initial": 16 × N1, gate 90 %, 1/16
+    return s;
+}
+
+std::unique_ptr<lynx::vfx::Processor> sequencer (const lynx::vfx::SequencerSettings& s)
+{
+    return lynx::vfx::makeProcessor (lynx::vfx::Kind::sequencer, lynx::vfx::writeSequencer (s));
+}
+} // namespace vfx164
+
+TEST (vfx_sequencer_state_round_trips_and_resolves_fl_params)
+{
+    using namespace lynx::vfx;
+    using S = SequencerSettings;
+    auto s = defaultSequencer();
+    const auto bytes = writeSequencer (s);
+    const auto back = parseSequencer (bytes);
+    CHECK (back && *back == s && writeSequencer (*back) == bytes);
+    CHECK (s.programs.size() == 128 && s.chains.size() == 16);
+    // per program: Steps; global: Transpose
+    s.set (S::currentProgram, 4);
+    s.set (S::steps, 12);
+    s.set (S::transposeSemitones, 5);
+    s.set (S::currentProgram, 6);
+    CHECK (s.get (S::steps) != 12 && s.get (S::transposeSemitones) == 5);
+    s.set (S::currentProgram, 4);
+    CHECK (s.get (S::steps) == 12);
+    // lanes: FL params 0x80 + 64 · lane + step
+    s.set (0x100 + 3, S::tie);
+    CHECK (s.current().lanes[S::stepType][3] == S::tie && s.get (0x100 + 3) == S::tie);
+    s.set (S::gate, 500);
+    CHECK (s.get (S::gate) == 125);
+    // pattern shift rotates the lanes of the steps in use
+    s.set (S::steps, 16);
+    s.current().lanes[S::velocity][0] = 127;
+    shiftPattern (s, 1);
+    CHECK (s.current().lanes[S::velocity][1] == 127);
+    shiftPattern (s, -2);
+    CHECK (s.current().lanes[S::velocity][15] == 127);
+    CHECK (! parseSequencer ({ 1, 0, 0, 0 }));
+    CHECK (defaultState (Kind::sequencer) == writeSequencer (defaultSequencer()));
+}
+
+TEST (vfx_sequencer_reads_fl_factory_bank)
+{
+    if (realFlpDir.empty())
+        return;
+    namespace fs = std::filesystem;
+    const auto file = fs::path (realFlpDir) / "Patches" / "Plugin database" / "Effects" / "Patcher" / "VFX Sequencer.fst";
+    if (! fs::exists (file))
+        return;
+    std::ifstream in (file, std::ios::binary);
+    const std::vector<std::uint8_t> bytes ((std::istreambuf_iterator<char> (in)), {});
+    const auto state = lynx::vfx::stateFromFlPreset (bytes, lynx::vfx::Kind::sequencer);
+    CHECK (state.has_value());
+    if (! state)
+        return;
+    const auto s = lynx::vfx::parseSequencer (*state);
+    CHECK (s.has_value());
+    if (! s)
+        return;
+    CHECK (lynx::vfx::writeSequencer (*s) == *state); // (byte for byte)
+    CHECK (s->programs.size() == 128 && s->program() == 3);
+    CHECK (s->current().nameText() == "Simple 4k Up 4 beats");
+    using S = lynx::vfx::SequencerSettings;
+    CHECK (s->get (S::steps) == 16 && s->get (S::gate) == 50 && s->get (S::missingKeys) == 3 && s->get (S::arpMode) == 1);
+    // T1: C4 E4 G4 held → 60 64 67 67 (N4 missing: the last key) on every 1/16, velocity 96, half a step long
+    auto p = lynx::vfx::makeProcessor (lynx::vfx::Kind::sequencer, *state);
+    const auto notes = vfx164::sequence (*p, { { 0.0, 60, true }, { 0.0, 64, true }, { 0.0, 67, true } }, 1.0);
+    CHECK (notes.size() >= 8);
+    const int expected[8] = { 60, 64, 67, 67, 60, 64, 67, 67 };
+    for (int i = 0; i < 8 && i < (int) notes.size(); ++i)
+    {
+        CHECK (notes[(std::size_t) i].key == expected[i]);
+        CHECK (std::abs (notes[(std::size_t) i].start - 0.125 * i) < 1e-4);
+        CHECK (notes[(std::size_t) i].velocity == 96);
+        CHECK (std::abs (notes[(std::size_t) i].length - 0.0625) < 1e-3);
+    }
+    // T2: output velocity = the key's
+    auto s2 = *s;
+    s2.set (S::velocityMode, 1);
+    auto p2 = vfx164::sequencer (s2);
+    const auto loud = vfx164::sequence (*p2, { { 0.0, 60, true }, { 0.0, 64, true } }, 0.3);
+    CHECK (! loud.empty() && loud[0].velocity == 100);
+    // T3 / T4: missing keys cyclic / not played
+    s2.set (S::velocityMode, 0);
+    s2.set (S::missingKeys, 1);
+    p2 = vfx164::sequencer (s2);
+    auto two = vfx164::sequence (*p2, { { 0.0, 60, true }, { 0.0, 64, true } }, 0.49);
+    CHECK (two.size() == 4 && two[2].key == 60 && two[3].key == 64);
+    s2.set (S::missingKeys, 0);
+    p2 = vfx164::sequencer (s2);
+    two = vfx164::sequence (*p2, { { 0.0, 60, true }, { 0.0, 64, true } }, 0.99);
+    CHECK (two.size() == 4 && two[2].key == 60 && std::abs (two[2].start - 0.5) < 1e-4);
+}
+
+TEST (vfx_sequencer_plays_fl_test_vectors)
+{
+    using namespace vfx164;
+    using S = lynx::vfx::SequencerSettings;
+    // T5: steps 0 = thru, transpose +2: the note passes at once and ends with its key
+    auto s = blankProgram();
+    s.set (S::steps, 0);
+    s.set (S::transposeSemitones, 2);
+    auto p = sequencer (s);
+    auto notes = sequence (*p, { { 0.0, 60, true }, { 1.0, 60, false } }, 1.5);
+    CHECK (notes.size() == 1 && notes[0].key == 62 && notes[0].start == 0.0 && std::abs (notes[0].length - 1.0) < 1e-3
+           && notes[0].velocity == 100);
+    // T6 / T7: C major forced, every scale step +1: D → E, C# snaps down to C → D; 0.9 of a step long
+    s = blankProgram();
+    s.set (S::forceKey, 2);
+    s.set (S::forceScale, 2);
+    for (int i = 0; i < 64; ++i)
+        s.set (0x80 + i, 1);
+    p = sequencer (s);
+    notes = sequence (*p, { { 0.0, 62, true } }, 0.49);
+    CHECK (notes.size() == 4 && notes[0].key == 64 && notes[3].key == 64 && std::abs (notes[0].length - 0.1125) < 1e-3);
+    p = sequencer (s);
+    notes = sequence (*p, { { 0.0, 61, true } }, 0.2);
+    CHECK (! notes.empty() && notes[0].key == 62);
+    // T8: swing +50: odd steps half a step late
+    s = blankProgram();
+    s.set (S::swing, 50);
+    p = sequencer (s);
+    notes = sequence (*p, { { 0.0, 60, true } }, 0.55);
+    CHECK (notes.size() == 5);
+    const double swung[5] = { 0.0, 0.1875, 0.25, 0.4375, 0.5 };
+    for (int i = 0; i < 5 && i < (int) notes.size(); ++i)
+        CHECK (std::abs (notes[(std::size_t) i].start - swung[i]) < 1e-3);
+    // T9: output wrap 48…59: E4 plays E3
+    s = blankProgram();
+    s.set (S::outputLow, 48);
+    s.set (S::outputHigh, 59);
+    p = sequencer (s);
+    notes = sequence (*p, { { 0.0, 64, true } }, 0.2);
+    CHECK (! notes.empty() && notes[0].key == 52);
+    // T10: a rest after a step lengthens it by a step; a tie makes it overlap the next (legato)
+    s = blankProgram();
+    s.set (0x100 + 1, S::rest);
+    s.set (0x100 + 2, S::tie);
+    p = sequencer (s);
+    notes = sequence (*p, { { 0.0, 60, true } }, 0.3);
+    CHECK (notes.size() == 2 && std::abs (notes[0].length - 1.9 * 0.125) < 1e-3 && std::abs (notes[1].start - 0.25) < 1e-4);
+    s.set (0x100 + 1, S::tie);
+    s.set (0x140 + 1, 0x08); // (N2: another key, so the tie overlaps it)
+    p = sequencer (s);
+    notes = sequence (*p, { { 0.0, 60, true }, { 0.0, 64, true } }, 0.2);
+    CHECK (notes.size() == 2 && notes[1].key == 64 && std::abs (notes[0].length - 1.25 * 0.125) < 1e-3);
+    // T11: chord normalized, every step a chord: G3 C4 E4 → C major in root position
+    s = blankProgram();
+    s.set (S::order, 6);
+    for (int i = 0; i < 64; ++i)
+        s.set (0x100 + i, S::chord);
+    p = sequencer (s);
+    notes = sequence (*p, { { 0.0, 55, true }, { 0.0, 60, true }, { 0.0, 64, true } }, 0.1);
+    std::vector<int> keys;
+    for (const auto& n : notes)
+        keys.push_back (n.key);
+    std::sort (keys.begin(), keys.end());
+    CHECK ((keys == std::vector<int> { 60, 64, 67 }));
+    // T12: stopped: the sequencer runs on its own clock while the key is held
+    s = blankProgram();
+    p = sequencer (s);
+    notes = sequence (*p, { { 0.0, 60, true }, { 0.3, 60, false } }, 1.5, false);
+    CHECK (notes.size() == 3 && std::abs (notes[2].start - 0.25) < 1e-3);
+    CHECK (! p->busy());
+    // octaves lane: bit 4 = +1 octave; key select: Fixed / Root
+    s = blankProgram();
+    s.set (0xC0, 0x10);
+    s.set (0x140 + 1, 0x01);
+    p = sequencer (s);
+    notes = sequence (*p, { { 0.0, 60, true } }, 0.2);
+    CHECK (notes.size() == 2 && notes[0].key == 72 && notes[1].key == 64);
+    // Arp mode off: nothing; a stop releases what sounds
+    s = blankProgram();
+    s.set (S::arpMode, 0);
+    p = sequencer (s);
+    CHECK (sequence (*p, { { 0.0, 60, true } }, 0.3).empty());
+}
+
+TEST (vfx_sequencer_cost_per_block)
+{
+    // the audio-thread cost: 4 held keys, 16 steps of chords, 1 s of 128-sample blocks
+    using namespace vfx164;
+    using S = lynx::vfx::SequencerSettings;
+    auto s = blankProgram();
+    for (int i = 0; i < 64; ++i)
+        s.set (0x100 + i, S::chord);
+    auto p = sequencer (s);
+    lynx::vfx::EventList out;
+    lynx::vfx::Transport t;
+    t.sampleRate = 48000.0;
+    t.bpm = 140.0;
+    t.playing = true;
+    std::vector<lynx::vfx::Event> in { on (60), on (64), on (67), on (71) };
+    const auto begin = std::chrono::steady_clock::now();
+    int notes = 0;
+    for (int b = 0; b < 375; ++b)
+    {
+        out.clear();
+        t.ticks = b * 128.0 / 48000.0 * (140.0 / 60.0) * 960.0;
+        p->process (b == 0 ? in.data() : nullptr, b == 0 ? 4 : 0, 128, t, out);
+        for (int k = 0; k < out.size(); ++k)
+            notes += out[k].type == lynx::vfx::Event::Type::on;
+    }
+    const auto ms = std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now() - begin).count();
+    std::printf ("  sequencer: 1 s of audio in %.3f ms (%d notes)\n", ms, notes);
+    CHECK (notes > 30 && ms < 20.0);
+}

Một số tệp đã không được hiển thị bởi vì quá nhiều tập tin thay đổi trong này khác