Przeglądaj źródła

Parameter menu like FL: Init song with this position / Delete initial value (FL's initialized controls, reset when the song starts), Edit events in piano roll, Override global link (links for every project); the touched control wins over its automation while recording (REA round 146)

Ka1-S 1 miesiąc temu
rodzic
commit
3e5604db42

+ 12 - 0
resources/i18n/pt-BR.txt

@@ -3873,3 +3873,15 @@ countries: br
 "Hz|Beats" = "Hz|Tempos"
 "Left / right|8 steps" = "Esquerda / direita|8 passos"
 "Digital|Analog|Hot" = "Digital|Analógico|Quente"
+# REA round 146: parameter menu (initialized controls, piano roll events, global links)
+"Edit events in piano roll" = "Editar eventos no piano roll"
+"Init song with this position" = "Iniciar a música com esta posição"
+"Delete initial value" = "Apagar valor inicial"
+"Override global link... (for all projects: move a knob on the controller)" = "Sobrepor vínculo global... (para todos os projetos: mova um knob do controlador)"
+"Remove global link (CC {0})" = "Remover vínculo global (CC {0})"
+"No events yet: draw them here" = "Ainda sem eventos: desenhe-os aqui"
+"Deleting events" = "Apagando eventos"
+"Drawing events: {0}" = "Desenhando eventos: {0}"
+"Links (this project, then global)" = "Vínculos (deste projeto, depois os globais)"
+"global" = "global"
+"Pattern events" = "Eventos do pattern"

+ 5 - 1
src/core/FlpImport.cpp

@@ -2754,7 +2754,11 @@ Song importFlp (const flp::Project& input, const FlpImportOptions& options)
         {
             AutomationTarget target;
             if (const auto convert = convertor (c.id, target))
-                song.setTargetValue (target, convert (c.value));
+            {
+                const auto value = convert (c.value);
+                song.setTargetValue (target, value);
+                song.setInitialValue (target, value); // kept: reset whenever the song starts (REA round 146)
+            }
         }
     }
 

+ 19 - 0
src/core/Preferences.cpp

@@ -286,6 +286,10 @@ std::string MidiPrefs::toText() const
     // input=<enabled>|<midi channel>|<target>|<device name>
     for (const auto& i : inputs)
         out += "input=" + std::string (i.enabled ? "1" : "0") + "|" + std::to_string (i.midiChannel) + "|" + std::to_string (i.target) + "|" + i.name + "\n";
+    // link=<cc>|<channel>|<target kind>|<index>|<slot>|<param>
+    for (const auto& l : globalLinks)
+        out += "link=" + std::to_string (l.cc) + "|" + std::to_string (l.channel) + "|" + std::to_string (l.kind) + "|" + std::to_string (l.index)
+               + "|" + std::to_string (l.slot) + "|" + std::to_string (l.param) + "\n";
     return out;
 }
 
@@ -324,6 +328,21 @@ MidiPrefs MidiPrefs::fromText (const std::string& text)
             i.name = parts[3];
             p.setInput (i);
         }
+        else if (key == "link")
+        {
+            const auto parts = split (value, '|', 6);
+            if (parts.size() != 6)
+                continue;
+            GlobalLink l;
+            l.cc = std::clamp (toInt (trim (parts[0]), 0), 0, 127);
+            l.channel = std::clamp (toInt (trim (parts[1]), -1), -1, 15);
+            l.kind = std::max (0, toInt (trim (parts[2]), 0));
+            l.index = toInt (trim (parts[3]), 0);
+            l.slot = toInt (trim (parts[4]), 0);
+            l.param = toInt (trim (parts[5]), 0);
+            if (l.kind > 0 && l.kind <= 8) // AutomationTargetKind::channelVolume ... effectMix
+                p.globalLinks.push_back (l);
+        }
     }
 
     return p;

+ 11 - 0
src/core/Preferences.h

@@ -92,9 +92,20 @@ struct MidiInputPrefs
     bool operator== (const MidiInputPrefs&) const = default;
 };
 
+// A MIDI controller link kept in the settings, for every project (FL's "global" links of the Mapping\Generic
+// folder, made with a parameter's "Override global link...", form TMIDIInputForm_Generic "Global link settings";
+// REA round 146). A project's own link of the same target or controller wins.
+struct GlobalLink
+{
+    int cc = 0, channel = -1;                // channel -1 = any
+    int kind = 0, index = 0, slot = 0, param = 0; // the AutomationTarget (kind = its enum value)
+    bool operator== (const GlobalLink&) const = default;
+};
+
 struct MidiPrefs
 {
     std::vector<MidiInputPrefs> inputs; // the devices the user changed (others use the defaults)
+    std::vector<GlobalLink> globalLinks;
     VelocityCurve velocity = VelocityCurve::linear;
     bool pickup = false;                // a controller takes over a parameter only once it reaches its value
 

+ 47 - 1
src/core/RackRenderer.cpp

@@ -728,6 +728,28 @@ void RackState::buildAutomationTables()
         }
 }
 
+void RackState::slotsOfTarget (const Song& song, const AutomationTarget& target, std::vector<int>& out)
+{
+    out.clear();
+    if (target.kind == AutomationTargetKind::none)
+        return;
+    const auto count = std::min<int> ((int) song.automations.size(), maxAutomations);
+    for (int a = 0; a < count; ++a)
+        if (song.automations[(std::size_t) a].target == target)
+            out.push_back (a);
+
+    auto slot = count;
+    for (const auto& pattern : song.patterns)
+        for (const auto& lane : pattern.events)
+        {
+            if (lane.events.empty() || lane.target.kind == AutomationTargetKind::tempo || slot >= maxAutomations)
+                continue;
+            if (lane.target == target)
+                out.push_back (slot);
+            ++slot;
+        }
+}
+
 namespace
 {
 // Constant-power pan: at center both sides are 1 (0 dB).
@@ -982,6 +1004,28 @@ float automationValueAt (const Song& song, const Automation& automation, const s
 }
 } // namespace
 
+void RackRenderer::setOverriddenSlots (const std::vector<int>& slots) noexcept
+{
+    std::array<std::uint32_t, RackState::maxAutomations / 32> bits {};
+    for (const auto s : slots)
+        if (s >= 0 && s < RackState::maxAutomations)
+            bits[(std::size_t) s / 32] |= 1u << ((unsigned) s % 32);
+    for (std::size_t i = 0; i < bits.size(); ++i)
+        overridden[i].store (bits[i], std::memory_order_relaxed);
+    anyOverridden.store (! slots.empty(), std::memory_order_release);
+}
+
+void RackRenderer::clearOverriddenValues() noexcept
+{
+    if (! anyOverridden.load (std::memory_order_acquire))
+        return;
+    for (std::size_t w = 0; w < overridden.size(); ++w)
+        if (auto bits = overridden[w].load (std::memory_order_relaxed); bits != 0)
+            for (unsigned b = 0; b < 32; ++b)
+                if ((bits & (1u << b)) != 0)
+                    automationValues[w * 32 + b] = std::numeric_limits<float>::quiet_NaN(); // the control's own value
+}
+
 void RackRenderer::updateAutomation (const RackState& state, double startTick) noexcept
 {
     const auto& song = state.song;
@@ -1051,6 +1095,7 @@ void RackRenderer::updateAutomation (const RackState& state, double startTick) n
     // in pattern mode the Playlist does not play: values stay as they were
     if (song.mode != PlayMode::song)
     {
+        clearOverriddenValues();
         if (! state.eventLanes.empty()) // only the plugin parameters driven by pattern events
             applyPluginParams (state, std::min<int> ((int) song.automations.size(), RackState::maxAutomations));
         return;
@@ -1063,6 +1108,7 @@ void RackRenderer::updateAutomation (const RackState& state, double startTick) n
         if (! state.automationClips[a].empty())
             automationValues[a] = automationValueAt (song, song.automations[a], state.automationClips[a], tick);
 
+    clearOverriddenValues();
     applyPluginParams (state, 0);
 }
 
@@ -1586,7 +1632,7 @@ void RackRenderer::process (const RackState* state,
     // tempo automation: the tempo holds for the whole block (evaluated at its start)
     bpm = state->song.bpm;
 
-    if (state->tempoAutomation >= 0 && state->song.mode == PlayMode::song)
+    if (state->tempoAutomation >= 0 && state->song.mode == PlayMode::song && ! isSlotOverridden (state->tempoAutomation))
     {
         const auto length = (double) std::max<std::int64_t> (1, state->schedule.songLength);
         const auto& clips = state->automationClips[(std::size_t) state->tempoAutomation];

+ 16 - 0
src/core/RackRenderer.h

@@ -114,6 +114,9 @@ struct RackState
     void buildMixerGraph();
 
     void buildAutomationTables();
+    // The automation slots that drive `target` in a snapshot of `song` (its automations, then its pattern event
+    // lanes, numbered as buildAutomationTables numbers them). REA round 146: a touched control overrides them.
+    static void slotsOfTarget (const Song& song, const AutomationTarget& target, std::vector<int>& out);
 
     // MIDI Out channels (REA_rodada133 §4): which channels each one's notes and controls reach (the plugin channels
     // whose MIDI input port is its port), and the MIDI channel it sends on. Indexed by channel; empty / −1 otherwise.
@@ -243,6 +246,16 @@ public:
     static std::uint64_t nonFiniteEffectBlocks() noexcept;
     void resetUnitTimes() noexcept;
 
+    // FL's touched control wins over its playing automation while recording (REA round 146): the slots set here
+    // (RackState::slotsOfTarget) are not driven by automation clips / pattern events; the control's own value
+    // plays. UI thread writes, audio thread reads (relaxed: a block late at worst).
+    void setOverriddenSlots (const std::vector<int>& slots) noexcept;
+    bool isSlotOverridden (int slot) const noexcept
+    {
+        return slot >= 0 && slot < RackState::maxAutomations
+            && (overridden[(std::size_t) slot / 32].load (std::memory_order_relaxed) & (1u << ((unsigned) slot % 32))) != 0;
+    }
+
     // Tempo used in the last block (changes with tempo automation). The transport advances with it.
     double currentBpm() const noexcept { return bpm; }
 
@@ -276,6 +289,9 @@ private:
     EventBuffer events;
     std::vector<float> mixBuffers; // maxMixerTracks * 2 * blockCapacity
     std::array<float, RackState::maxAutomations> automationValues {}; // NaN = not evaluated yet
+    std::array<std::atomic<std::uint32_t>, RackState::maxAutomations / 32> overridden {}; // touched while recording
+    std::atomic<bool> anyOverridden { false };
+    void clearOverriddenValues() noexcept;
     std::array<float, maxMixerTracks * 2> lastTrackGain {}; // L/R gain of the previous block, for the ramp
     std::array<char, maxMixerTracks> trackActive {};        // the track output has sound in this block
     std::vector<float> tapBuffers;                          // RackState::maxSendTaps * 2 * chunkCapacity

+ 50 - 0
src/core/Song.cpp

@@ -190,6 +190,56 @@ void Song::removeDeadMidiLinks()
     midiLinks.erase (std::remove_if (midiLinks.begin(), midiLinks.end(),
                                      [] (const MidiLink& l) { return l.target.kind == AutomationTargetKind::none; }),
                      midiLinks.end());
+    initialValues.erase (std::remove_if (initialValues.begin(), initialValues.end(),
+                                         [] (const InitialValue& v) { return v.target.kind == AutomationTargetKind::none; }),
+                         initialValues.end());
+}
+
+std::vector<MidiLink> linksWithGlobal (const std::vector<MidiLink>& project, const std::vector<MidiLink>& global)
+{
+    auto out = project;
+    for (const auto& g : global)
+    {
+        const auto overridden = std::any_of (project.begin(), project.end(), [&] (const MidiLink& p) {
+            return p.target == g.target || (p.cc == g.cc && (p.channel < 0 || g.channel < 0 || p.channel == g.channel));
+        });
+        if (! overridden && g.target.kind != AutomationTargetKind::none)
+            out.push_back (g);
+    }
+    return out;
+}
+
+int Song::findInitialValue (const AutomationTarget& target) const noexcept
+{
+    for (int i = 0; i < (int) initialValues.size(); ++i)
+        if (initialValues[(std::size_t) i].target == target)
+            return i;
+    return -1;
+}
+
+void Song::setInitialValue (const AutomationTarget& target, float value)
+{
+    if (target.kind == AutomationTargetKind::none)
+        return;
+    value = std::clamp (value, 0.0f, 1.0f);
+    if (const auto i = findInitialValue (target); i >= 0)
+        initialValues[(std::size_t) i].value = value;
+    else
+        initialValues.push_back ({ target, value });
+}
+
+void Song::removeInitialValue (const AutomationTarget& target)
+{
+    initialValues.erase (std::remove_if (initialValues.begin(), initialValues.end(),
+                                         [&] (const InitialValue& v) { return v.target == target; }),
+                         initialValues.end());
+}
+
+void Song::applyInitialValues (const std::function<void (const AutomationTarget&, float)>& plugin)
+{
+    for (const auto& v : initialValues)
+        if (! setTargetValue (v.target, v.value) && plugin)
+            plugin (v.target, v.value);
 }
 
 int fruitySendTarget (const EffectSlot& slot) noexcept

+ 23 - 0
src/core/Song.h

@@ -6,6 +6,7 @@
 
 #include <array>
 #include <cstdint>
+#include <functional>
 #include <optional>
 #include <string>
 #include <vector>
@@ -779,6 +780,10 @@ struct MidiLink
     AutomationTarget target;
 };
 
+// The links a controller move follows: the project's, then the global ones (settings, every project) whose target
+// and controller the project does not link itself (REA round 146: a project link overrides a global one).
+std::vector<MidiLink> linksWithGlobal (const std::vector<MidiLink>& project, const std::vector<MidiLink>& global);
+
 // Header of a Playlist track.
 struct PlaylistTrack
 {
@@ -869,6 +874,8 @@ struct Song
             fn (a.target);
         for (auto& l : midiLinks)
             fn (l.target);
+        for (auto& v : initialValues)
+            fn (v.target);
         for (auto& p : patterns)
             for (auto& lane : p.events)
                 fn (lane.target);
@@ -906,6 +913,22 @@ struct Song
     std::vector<Automation> automations;
     std::vector<PlaylistTrack> playlistTracks; // index = track; tracks past the end use the default
     std::vector<MidiLink> midiLinks;
+    // FL's "initialized controls" (.flp 0xD8; the parameter menu's "Init song with this position", REA round 146):
+    // values the targets are reset to whenever the song starts playing in song mode (from any position), before
+    // the automation clips take over at their own position.
+    struct InitialValue
+    {
+        AutomationTarget target;
+        float value = 0.0f; // 0..1
+    };
+    std::vector<InitialValue> initialValues;
+    // Sets (replaces) / removes the target's initial value; the index into initialValues or -1.
+    void setInitialValue (const AutomationTarget& target, float value);
+    void removeInitialValue (const AutomationTarget& target);
+    int findInitialValue (const AutomationTarget& target) const noexcept;
+    // Resets the model's targets to their initial values; the plugin parameters among them (which don't live in
+    // the model) are passed to `plugin` when given.
+    void applyInitialValues (const std::function<void (const AutomationTarget&, float)>& plugin = {});
 
     bool isTrackMuted (int track) const noexcept
     {

+ 121 - 5
src/engine/AudioEngine.cpp

@@ -211,6 +211,7 @@ AudioEngine::AudioEngine (bool openAudioDevice)
             rackProcessor->getRenderer().setProfiling (true); // per-unit CPU for the CPU meter and the glitch log
         deviceStateSaver = std::make_unique<DeviceStateSaver> (*this);
         midiPrefs = midiPrefsShared = prefs::MidiPrefs::fromText (midiSettingsFile().loadFileAsString().toStdString());
+        saveGlobalLinks = true;
 
         prefetcher = std::make_unique<StreamPrefetcher> (transport);
         prefetcher->update (song, samples);
@@ -376,7 +377,46 @@ ProcessTimes* AudioEngine::getProcessTimes() noexcept
     return rackProcessor != nullptr ? &rackProcessor->processTimes() : nullptr;
 }
 
-void AudioEngine::play() noexcept { transport.playing.store (true); }
+void AudioEngine::play() noexcept
+{
+    if (! transport.playing.load())
+        resetToInitialValues();
+    transport.playing.store (true);
+}
+
+// FL resets its "initialized controls" whenever the song position is set in song mode (playing starts, a jump):
+// FUN_011e7470 plays the song's init list (PTR_DAT_015dfc48) before the pattern events (REA round 146).
+void AudioEngine::resetToInitialValues() noexcept
+{
+    if (song.initialValues.empty() || song.mode != PlayMode::song)
+        return;
+    try
+    {
+        auto differs = false;
+        for (const auto& v : song.initialValues)
+        {
+            const auto now = currentTargetValue (v.target);
+            differs = differs || (now >= 0.0f && std::abs (now - v.value) > 1.0e-6f);
+        }
+        if (! differs)
+            return;
+        std::vector<Song::InitialValue> plugins;
+        editSong ([&plugins] (Song& s) { s.applyInitialValues ([&plugins] (const AutomationTarget& t, float v) { plugins.push_back ({ t, v }); }); },
+                  false);
+        for (const auto& v : plugins)
+        {
+            if (v.target.kind == AutomationTargetKind::channelParam)
+                if (auto* p = dynamic_cast<PluginInstrument*> (getChannelInstrument (v.target.index).get()))
+                    p->setParameterFromUi (v.target.param, v.value);
+            if (v.target.kind == AutomationTargetKind::effectParam)
+                if (auto* p = dynamic_cast<PluginEffect*> (getEffect (v.target.index, v.target.slot).get()))
+                    p->setParameterFromUi (v.target.param, v.value);
+        }
+    }
+    catch (...)
+    {
+    }
+}
 
 void AudioEngine::stop() noexcept
 {
@@ -453,7 +493,12 @@ bool AudioEngine::isInsertArmed (int track) const noexcept
     return std::find (armedInserts.begin(), armedInserts.end(), track) != armedInserts.end();
 }
 void AudioEngine::rewind() noexcept { transport.rewindRequested.store (true); }
-void AudioEngine::seek (double ticks) noexcept { transport.seekRequest.store (juce::jmax (0.0, ticks)); }
+void AudioEngine::seek (double ticks) noexcept
+{
+    if (transport.playing.load())
+        resetToInitialValues(); // a jump while the song plays (FL sets the position the same way)
+    transport.seekRequest.store (juce::jmax (0.0, ticks));
+}
 
 void AudioEngine::copyScope (float* destination, int count) const noexcept
 {
@@ -1757,9 +1802,45 @@ void AudioEngine::publishSong()
     sendChangeMessage();
 }
 
+std::vector<MidiLink> AudioEngine::getGlobalLinks() const
+{
+    std::vector<MidiLink> out;
+    for (const auto& l : midiPrefs.globalLinks)
+        out.push_back ({ l.cc, l.channel, { (AutomationTargetKind) l.kind, l.index, l.slot, l.param } });
+    return out;
+}
+
+std::optional<MidiLink> AudioEngine::globalLinkOf (const AutomationTarget& target) const
+{
+    for (const auto& l : getGlobalLinks())
+        if (l.target == target)
+            return l;
+    return std::nullopt;
+}
+
+void AudioEngine::learnGlobalLink (const AutomationTarget& target)
+{
+    learning = target;
+    learningGlobal = true;
+    sendChangeMessage();
+}
+
+void AudioEngine::removeGlobalLink (const AutomationTarget& target)
+{
+    auto p = midiPrefs;
+    p.globalLinks.erase (std::remove_if (p.globalLinks.begin(), p.globalLinks.end(),
+                                         [&] (const prefs::GlobalLink& l) {
+                                             return l.kind == (int) target.kind && l.index == target.index && l.slot == target.slot
+                                                 && l.param == target.param;
+                                         }),
+                         p.globalLinks.end());
+    setMidiPrefs (p, saveGlobalLinks);
+}
+
 void AudioEngine::learnMidiController (const AutomationTarget& target)
 {
     learning = target;
+    learningGlobal = false;
     sendChangeMessage();
 }
 
@@ -1887,10 +1968,28 @@ void AudioEngine::updateAutomationRecording (bool active)
             writeFor (target).lastLocal = -1; // the next gesture on it starts a new stretch
     };
 
+    // FL: while recording, the moved control wins over its playing automation at once (REA round 146); the
+    // automation of a touched target does not drive it until the gesture ends and its points are written.
+    auto overrideTouched = [this] {
+        if (rackProcessor == nullptr)
+            return;
+        std::vector<int> slots, one;
+        for (const auto& t : touches)
+        {
+            RackState::slotsOfTarget (song, t.target, one);
+            slots.insert (slots.end(), one.begin(), one.end());
+        }
+        if (slots.empty() && ! automationOverrideActive)
+            return;
+        rackProcessor->getRenderer().setOverriddenSlots (slots);
+        automationOverrideActive = ! slots.empty();
+    };
+
     if (! recording)
     {
         commit ({});
         touches.clear();
+        overrideTouched();
         if (! active)
         {
             takeWrites.clear();
@@ -1934,6 +2033,7 @@ void AudioEngine::updateAutomationRecording (bool active)
     touches.erase (std::remove_if (touches.begin(), touches.end(),
                                    [&] (const Touch& t) { return std::find (ended.begin(), ended.end(), t.target) != ended.end(); }),
                    touches.end());
+    overrideTouched();
 }
 
 void AudioEngine::applyControllers()
@@ -1943,7 +2043,22 @@ void AudioEngine::applyControllers()
 
     while (controllerQueue.pop (e))
     {
-        if (learning.kind != AutomationTargetKind::none)
+        if (learning.kind != AutomationTargetKind::none && learningGlobal)
+        {
+            // "Override global link...": the link goes to the settings, for every project (REA round 146)
+            auto p = midiPrefs;
+            const prefs::GlobalLink g { e.cc, e.channel, (int) learning.kind, learning.index, learning.slot, learning.param };
+            p.globalLinks.erase (std::remove_if (p.globalLinks.begin(), p.globalLinks.end(),
+                                                 [&] (const prefs::GlobalLink& l) {
+                                                     return l.kind == g.kind && l.index == g.index && l.slot == g.slot && l.param == g.param;
+                                                 }),
+                                 p.globalLinks.end());
+            p.globalLinks.push_back (g);
+            learning = {};
+            learningGlobal = false;
+            setMidiPrefs (p, saveGlobalLinks);
+        }
+        else if (learning.kind != AutomationTargetKind::none)
         {
             // MIDI learn: replace the old link for the same target with the new one
             editSong ([t = learning, e] (Song& s) {
@@ -1957,14 +2072,15 @@ void AudioEngine::applyControllers()
         latest[{ e.cc, e.channel }] = e.value;
     }
 
-    if (latest.empty() || song.midiLinks.empty())
+    const auto links = linksWithGlobal (song.midiLinks, getGlobalLinks());
+    if (latest.empty() || links.empty())
         return;
 
     // one snapshot per frame, outside the undo history (like turning the knob)
     std::vector<std::pair<AutomationTarget, float>> changes;
 
     for (const auto& [key, value] : latest)
-        for (const auto& link : song.midiLinks)
+        for (const auto& link : links)
             if (link.cc == key.first && (link.channel < 0 || link.channel == key.second))
             {
                 const auto v = value / 127.0f;

+ 12 - 0
src/engine/AudioEngine.h

@@ -114,6 +114,9 @@ public:
 
     // Play pressed: with recording on, honours wait-for-input and the count-in; otherwise play().
     void startPlayback();
+    // The song's initial values (FL's initialized controls) back on their targets, in song mode; play() and a
+    // seek while playing do it (REA round 146). UI thread.
+    void resetToInitialValues() noexcept;
     bool isWaitingForInput() const noexcept { return waitingForInput.load(); }
     bool isCountingIn() const noexcept { return transport.countIn.load() > 0.0; }
 
@@ -214,6 +217,12 @@ public:
     // MIDI learn: the next CC received becomes a controller linked to `target`.
     void learnMidiController (const AutomationTarget& target);
     bool isLearningMidi() const noexcept { return learning.kind != AutomationTargetKind::none; }
+    // Global links (FL's "Override global link...", REA round 146): links in the MIDI settings that every project
+    // follows unless it links the same target or controller itself. The next CC received becomes `target`'s.
+    void learnGlobalLink (const AutomationTarget& target);
+    void removeGlobalLink (const AutomationTarget& target);
+    std::optional<MidiLink> globalLinkOf (const AutomationTarget& target) const;
+    std::vector<MidiLink> getGlobalLinks() const;
 
     // FL's "Last tweaked" (REA round 143: FLEngine keeps the last two moved parameters, Tools › Last tweaked /
     // Next to last tweaked, Add › Automation for last tweaked parameter). Every control that can be automated reports
@@ -453,6 +462,8 @@ private:
     };
     SpscQueue<ControllerEvent, 1024> controllerQueue; // MIDI thread -> UI (controllers)
     AutomationTarget learning;
+    bool learningGlobal = false;
+    bool saveGlobalLinks = false; // only the engine with an audio device (the app) writes the settings file
     void applyControllers();
     std::vector<RecordedEvent> uiRecorded;           // PC keyboard -> recording
     NoteRecorder recorder;
@@ -471,6 +482,7 @@ private:
     std::int64_t automationLoopLength = 0;
     int automationPattern = 0;
     int recordedAutomationPoints = 0;
+    bool automationOverrideActive = false; // touched targets override their automation in the renderer
     std::vector<AutomationWrite> takeWrites; // per target: where this take writes (its own clip grows)
     bool takeHasUndoStep = false;
     RecordOptions recordOptions;

+ 13 - 0
src/engine/ProjectFile.cpp

@@ -1325,6 +1325,14 @@ juce::String toJson (const Song& song)
         root->setProperty ("midiLinks", links);
     }
 
+    if (! song.initialValues.empty()) // FL's initialized controls (REA round 146)
+    {
+        juce::Array<juce::var> values;
+        for (const auto& v : song.initialValues)
+            values.add (juce::Array<juce::var> { targetKindName (v.target.kind), v.target.index, v.target.slot, v.target.param, v.value });
+        root->setProperty ("initialValues", values);
+    }
+
     root->setProperty ("playlist", clipsToVar (song.playlist));
 
     {
@@ -1570,6 +1578,11 @@ std::optional<Song> fromJson (const juce::String& json, juce::String& error)
                 song.midiLinks.push_back ({ juce::jlimit (0, 127, (int) l[0]), juce::jlimit (-1, 15, (int) l[1]),
                                             { targetKindFromName (l[2].toString()), (int) l[3], (int) l[4], (int) l[5] } });
 
+    if (auto* values = root["initialValues"].getArray())
+        for (const auto& v : *values)
+            if (v.isArray() && v.size() == 5)
+                song.setInitialValue ({ targetKindFromName (v[0].toString()), (int) v[1], (int) v[2], (int) v[3] }, (float) (double) v[4]);
+
     if (auto* tracks = root["playlistTracks"].getArray())
         for (const auto& t : *tracks)
             if (t.isArray() && t.size() == 3 && (int) t[0] >= 0 && (int) t[0] < 500)

+ 26 - 1
src/ui/AutomationUi.cpp

@@ -802,14 +802,37 @@ void addControllerLinkItems (juce::PopupMenu& menu, AudioEngine& engine, const A
     menu.addSubMenu (tr ("Link to internal controller"), sub);
 }
 
+std::function<void (const AutomationTarget&)> onEditEventsInPianoRoll;
+
 void addAutomationItem (juce::PopupMenu& menu, AudioEngine& engine, const AutomationTarget& target)
 {
-    menu.addItem (tr ("Create automation clip"), [&engine, target] { createAutomationClip (engine, target); });
     if (target.kind != AutomationTargetKind::tempo)
+    {
         menu.addItem (tr ("Edit events in the pattern"), [&engine, target] { openEventEditor (engine, target); });
+        if (onEditEventsInPianoRoll)
+            menu.addItem (tr ("Edit events in piano roll"), [target] {
+                if (onEditEventsInPianoRoll)
+                    onEditEventsInPianoRoll (target);
+            });
+    }
+    // FL's initialized controls (REA round 146): the value the song resets this control to whenever it starts
+    const auto initial = engine.getSong().findInitialValue (target);
+    menu.addItem (tr ("Init song with this position"), engine.currentTargetValue (target) >= 0.0f, initial >= 0, [&engine, target] {
+        const auto value = engine.currentTargetValue (target);
+        if (value >= 0.0f)
+            engine.editSong ([target, value] (Song& s) { s.setInitialValue (target, value); });
+    });
+    menu.addItem (tr ("Delete initial value"), initial >= 0, false, [&engine, target] {
+        engine.editSong ([target] (Song& s) { s.removeInitialValue (target); });
+    });
+    menu.addItem (tr ("Create automation clip"), [&engine, target] { createAutomationClip (engine, target); });
     menu.addItem (tr ("Link to MIDI controller (move a knob on the controller)"), [&engine, target] {
         engine.learnMidiController (target);
     });
+    // FL's "Override global link..." (form "Global link settings"): a link for every project, kept in the settings
+    menu.addItem (tr ("Override global link... (for all projects: move a knob on the controller)"), [&engine, target] {
+        engine.learnGlobalLink (target);
+    });
 
     if (target.kind != AutomationTargetKind::tempo)
         addControllerLinkItems (menu, engine, target);
@@ -824,6 +847,8 @@ void addAutomationItem (juce::PopupMenu& menu, AudioEngine& engine, const Automa
                                    s.midiLinks.end());
             });
         });
+    if (const auto global = engine.globalLinkOf (target))
+        menu.addItem (tr ("Remove global link (CC {0})", { juce::String (global->cc) }), [&engine, target] { engine.removeGlobalLink (target); });
 }
 
 juce::String midiParamLabel (int param)

+ 5 - 1
src/ui/AutomationUi.h

@@ -18,8 +18,12 @@ void closeAutomationEditors();
 // Just the editor (for --snapshot mode).
 std::unique_ptr<juce::Component> makeAutomationEditor (AudioEngine& engine, int automation);
 
-// "Create automation clip" item for knob menus.
+// A parameter's menu items, in FL's order (REA round 143 / 146): Edit events in the pattern, Edit events in piano
+// roll, Init song with this position, Delete initial value, Create automation clip; remote control: Link to MIDI
+// controller, Override global link..., internal controllers, unlink.
 void addAutomationItem (juce::PopupMenu& menu, AudioEngine& engine, const AutomationTarget& target);
+// Opens the Piano roll with the target's pattern events in its bottom lane (the main window sets it).
+extern std::function<void (const AutomationTarget&)> onEditEventsInPianoRoll;
 
 // An output of a built-in controller that knobs can be linked to (Envelope / Keyboard Controller channels, Formula and
 // Peak Controller mixer slots), as FL's "Link to controller" lists them.

+ 35 - 1
src/ui/I18nData.h

@@ -10875,6 +10875,40 @@ inline constexpr unsigned char ptBR[] = {
 104, 116, 124, 56, 32, 115, 116, 101, 112, 115, 34, 32, 61, 32, 34, 69, 115, 113, 117, 101, 114, 100, 97, 32,
 47, 32, 100, 105, 114, 101, 105, 116, 97, 124, 56, 32, 112, 97, 115, 115, 111, 115, 34, 10, 34, 68, 105, 103,
 105, 116, 97, 108, 124, 65, 110, 97, 108, 111, 103, 124, 72, 111, 116, 34, 32, 61, 32, 34, 68, 105, 103, 105,
-116, 97, 108, 124, 65, 110, 97, 108, 195, 179, 103, 105, 99, 111, 124, 81, 117, 101, 110, 116, 101, 34, 10,
+116, 97, 108, 124, 65, 110, 97, 108, 195, 179, 103, 105, 99, 111, 124, 81, 117, 101, 110, 116, 101, 34, 10, 35,
+32, 82, 69, 65, 32, 114, 111, 117, 110, 100, 32, 49, 52, 54, 58, 32, 112, 97, 114, 97, 109, 101, 116, 101,
+114, 32, 109, 101, 110, 117, 32, 40, 105, 110, 105, 116, 105, 97, 108, 105, 122, 101, 100, 32, 99, 111, 110, 116,
+114, 111, 108, 115, 44, 32, 112, 105, 97, 110, 111, 32, 114, 111, 108, 108, 32, 101, 118, 101, 110, 116, 115, 44,
+32, 103, 108, 111, 98, 97, 108, 32, 108, 105, 110, 107, 115, 41, 10, 34, 69, 100, 105, 116, 32, 101, 118, 101,
+110, 116, 115, 32, 105, 110, 32, 112, 105, 97, 110, 111, 32, 114, 111, 108, 108, 34, 32, 61, 32, 34, 69, 100,
+105, 116, 97, 114, 32, 101, 118, 101, 110, 116, 111, 115, 32, 110, 111, 32, 112, 105, 97, 110, 111, 32, 114, 111,
+108, 108, 34, 10, 34, 73, 110, 105, 116, 32, 115, 111, 110, 103, 32, 119, 105, 116, 104, 32, 116, 104, 105, 115,
+32, 112, 111, 115, 105, 116, 105, 111, 110, 34, 32, 61, 32, 34, 73, 110, 105, 99, 105, 97, 114, 32, 97, 32,
+109, 195, 186, 115, 105, 99, 97, 32, 99, 111, 109, 32, 101, 115, 116, 97, 32, 112, 111, 115, 105, 195, 167, 195,
+163, 111, 34, 10, 34, 68, 101, 108, 101, 116, 101, 32, 105, 110, 105, 116, 105, 97, 108, 32, 118, 97, 108, 117,
+101, 34, 32, 61, 32, 34, 65, 112, 97, 103, 97, 114, 32, 118, 97, 108, 111, 114, 32, 105, 110, 105, 99, 105,
+97, 108, 34, 10, 34, 79, 118, 101, 114, 114, 105, 100, 101, 32, 103, 108, 111, 98, 97, 108, 32, 108, 105, 110,
+107, 46, 46, 46, 32, 40, 102, 111, 114, 32, 97, 108, 108, 32, 112, 114, 111, 106, 101, 99, 116, 115, 58, 32,
+109, 111, 118, 101, 32, 97, 32, 107, 110, 111, 98, 32, 111, 110, 32, 116, 104, 101, 32, 99, 111, 110, 116, 114,
+111, 108, 108, 101, 114, 41, 34, 32, 61, 32, 34, 83, 111, 98, 114, 101, 112, 111, 114, 32, 118, 195, 173, 110,
+99, 117, 108, 111, 32, 103, 108, 111, 98, 97, 108, 46, 46, 46, 32, 40, 112, 97, 114, 97, 32, 116, 111, 100,
+111, 115, 32, 111, 115, 32, 112, 114, 111, 106, 101, 116, 111, 115, 58, 32, 109, 111, 118, 97, 32, 117, 109, 32,
+107, 110, 111, 98, 32, 100, 111, 32, 99, 111, 110, 116, 114, 111, 108, 97, 100, 111, 114, 41, 34, 10, 34, 82,
+101, 109, 111, 118, 101, 32, 103, 108, 111, 98, 97, 108, 32, 108, 105, 110, 107, 32, 40, 67, 67, 32, 123, 48,
+125, 41, 34, 32, 61, 32, 34, 82, 101, 109, 111, 118, 101, 114, 32, 118, 195, 173, 110, 99, 117, 108, 111, 32,
+103, 108, 111, 98, 97, 108, 32, 40, 67, 67, 32, 123, 48, 125, 41, 34, 10, 34, 78, 111, 32, 101, 118, 101,
+110, 116, 115, 32, 121, 101, 116, 58, 32, 100, 114, 97, 119, 32, 116, 104, 101, 109, 32, 104, 101, 114, 101, 34,
+32, 61, 32, 34, 65, 105, 110, 100, 97, 32, 115, 101, 109, 32, 101, 118, 101, 110, 116, 111, 115, 58, 32, 100,
+101, 115, 101, 110, 104, 101, 45, 111, 115, 32, 97, 113, 117, 105, 34, 10, 34, 68, 101, 108, 101, 116, 105, 110,
+103, 32, 101, 118, 101, 110, 116, 115, 34, 32, 61, 32, 34, 65, 112, 97, 103, 97, 110, 100, 111, 32, 101, 118,
+101, 110, 116, 111, 115, 34, 10, 34, 68, 114, 97, 119, 105, 110, 103, 32, 101, 118, 101, 110, 116, 115, 58, 32,
+123, 48, 125, 34, 32, 61, 32, 34, 68, 101, 115, 101, 110, 104, 97, 110, 100, 111, 32, 101, 118, 101, 110, 116,
+111, 115, 58, 32, 123, 48, 125, 34, 10, 34, 76, 105, 110, 107, 115, 32, 40, 116, 104, 105, 115, 32, 112, 114,
+111, 106, 101, 99, 116, 44, 32, 116, 104, 101, 110, 32, 103, 108, 111, 98, 97, 108, 41, 34, 32, 61, 32, 34,
+86, 195, 173, 110, 99, 117, 108, 111, 115, 32, 40, 100, 101, 115, 116, 101, 32, 112, 114, 111, 106, 101, 116, 111,
+44, 32, 100, 101, 112, 111, 105, 115, 32, 111, 115, 32, 103, 108, 111, 98, 97, 105, 115, 41, 34, 10, 34, 103,
+108, 111, 98, 97, 108, 34, 32, 61, 32, 34, 103, 108, 111, 98, 97, 108, 34, 10, 34, 80, 97, 116, 116, 101,
+114, 110, 32, 101, 118, 101, 110, 116, 115, 34, 32, 61, 32, 34, 69, 118, 101, 110, 116, 111, 115, 32, 100, 111,
+32, 112, 97, 116, 116, 101, 114, 110, 34, 10,
 };
 } // namespace lynx::i18n::data

+ 10 - 0
src/ui/MainComponent.cpp

@@ -431,6 +431,15 @@ MainComponent::MainComponent (AudioEngine& e, bool restoreUserSettings)
     ui::installSliderContract();
     // FL's Last tweaked and automation recording (REA round 143): every automatable control reports its moves
     ui::onTweak = [this] (const AutomationTarget& t) { engine.noteTweaked (t); };
+    // FL's "Edit events in piano roll" (REA round 146): the channel's own parameter selects its channel
+    onEditEventsInPianoRoll = [this] (const AutomationTarget& t) {
+        const auto onChannel = t.kind == AutomationTargetKind::channelVolume || t.kind == AutomationTargetKind::channelPan
+                               || t.kind == AutomationTargetKind::channelParam;
+        if (onChannel && t.index >= 0 && t.index < (int) engine.getSong().channels.size())
+            engine.setSelectedChannel (t.index);
+        openPianoRoll();
+        pianoRoll.showEventLane (t);
+    };
     PluginWindows::onGesture = [this] (const juce::AudioPluginInstance& plugin, int param, bool starting) {
         if (const auto t = engine.targetOfPlugin (plugin, param))
         {
@@ -477,6 +486,7 @@ MainComponent::~MainComponent()
     workspace.saveState();
     ui::uninstallSliderContract();
     ui::onTweak = nullptr;
+    onEditEventsInPianoRoll = nullptr;
     PluginWindows::onGesture = nullptr;
     engine.nameAutomation = nullptr;
     PluginWindows::closeAll(); // plugin UIs before the engine

+ 130 - 1
src/ui/PianoRollComponent.cpp

@@ -1,10 +1,12 @@
 #include "ui/PianoRollComponent.h"
 
 #include "core/EditorPolish.h"
+#include "core/EventEdit.h"
 #include "core/NoteEdit.h"
 #include "core/NoteTools.h"
 #include "engine/MidiFileIo.h"
 #include "engine/Text.h"
+#include "ui/AutomationUi.h"
 #include "ui/EventEditor.h"
 #include "ui/HintBar.h"
 #include "ui/I18n.h"
@@ -835,7 +837,38 @@ void PianoRollComponent::paint (juce::Graphics& g)
             g.drawHorizontalLine ((int) base, (float) lane.getX(), (float) lane.getRight());
         }
 
-        for (int i = 0; i < (int) pattern.notes.size(); ++i)
+        if (const auto target = eventLaneTarget()) // pattern events: held values, a dot on each event
+        {
+            const auto* events = eventedit::findLane (pattern, *target);
+            if (events != nullptr && ! events->events.empty())
+            {
+                juce::Path held;
+                const auto yOf = [&] (float v) { return (float) lane.getBottom() - 2.0f - usable * v; };
+                auto x = (float) tickToX (0.0);
+                auto y = yOf (events->events.front().value);
+                held.startNewSubPath (x, y);
+                for (const auto& ev : events->events)
+                {
+                    const auto ex = (float) tickToX ((double) ev.tick);
+                    held.lineTo (ex, y);
+                    y = yOf (ev.value);
+                    held.lineTo (ex, y);
+                }
+                held.lineTo ((float) lane.getRight(), y);
+                g.setColour (accent.withAlpha (0.85f));
+                g.strokePath (held, juce::PathStrokeType (1.5f));
+                for (const auto& ev : events->events)
+                    g.fillEllipse ((float) tickToX ((double) ev.tick) - 2.5f, yOf (ev.value) - 2.5f, 5.0f, 5.0f);
+            }
+            else
+            {
+                g.setColour (textDisabled);
+                g.setFont (theme::font (theme::type::small));
+                g.drawText (tr ("No events yet: draw them here"), lane.reduced (8, 4), juce::Justification::centredLeft, true);
+            }
+        }
+
+        for (int i = 0; i < (int) pattern.notes.size() && ! eventLaneTarget(); ++i)
         {
             const auto& n = pattern.notes[(std::size_t) i];
 
@@ -1220,6 +1253,15 @@ void PianoRollComponent::mouseDown (const juce::MouseEvent& e)
         return;
     }
 
+    if (velocityArea().contains (e.getPosition()) && eventLaneTarget())
+    {
+        // pattern events: drag draws one event per grid step, right-drag erases
+        lastVelocityX = e.x;
+        drag = e.mods.isRightButtonDown() ? Drag::eventErase : Drag::eventDraw;
+        drawEvents (e.x, e.x, e.y, drag == Drag::eventErase);
+        return;
+    }
+
     if (velocityArea().contains (e.getPosition()))
     {
         const auto lane = velocityArea();
@@ -1576,6 +1618,12 @@ void PianoRollComponent::mouseDrag (const juce::MouseEvent& e)
             lastVelocityX = e.x;
             return;
 
+        case Drag::eventDraw:
+        case Drag::eventErase:
+            drawEvents (lastVelocityX, e.x, e.y, drag == Drag::eventErase);
+            lastVelocityX = e.x;
+            return;
+
         case Drag::velocitySet:
             applyLaneValue (e.x, laneSetValue, lastVelocityX);
             lastVelocityX = e.x;
@@ -1840,6 +1888,15 @@ void PianoRollComponent::postDragHint (const juce::MouseEvent& e)
             hint.text = tr ("Resizing {0} note(s)  [Alt] no snap", { count });
             hint.value = juce::String ((double) notes[(std::size_t) dragNote].length / ticksPerStep, 2) + " " + tr ("steps");
             break;
+        case Drag::eventDraw:
+        case Drag::eventErase:
+        {
+            const auto lane = velocityArea();
+            const auto value = juce::jlimit (0.0f, 1.0f, (float) (lane.getBottom() - 2 - e.y) / (float) (lane.getHeight() - 8));
+            hint.text = drag == Drag::eventErase ? tr ("Deleting events") : tr ("Drawing events: {0}", { laneBox.getText() });
+            hint.value = juce::String (juce::roundToInt (value * 100.0f)) + "%";
+            break;
+        }
         case Drag::velocity:
         case Drag::velocitySet:
         case Drag::velocityLine:
@@ -3054,10 +3111,82 @@ void PianoRollComponent::changeListenerCallback (juce::ChangeBroadcaster*)
     }
 
     refreshChannelBox();
+    rebuildLaneBox();
     updateScrollBars();
     repaint();
 }
 
+std::optional<AutomationTarget> PianoRollComponent::eventLaneTarget() const
+{
+    const auto k = laneBox.getSelectedId() - eventLaneIdBase;
+    if (k >= 0 && k < (int) eventTargets.size())
+        return eventTargets[(std::size_t) k];
+    return std::nullopt;
+}
+
+void PianoRollComponent::rebuildLaneBox (std::optional<AutomationTarget> shown, bool force)
+{
+    // the pattern's event lanes, plus the one shown (it may have no events yet)
+    if (! shown)
+        shown = eventLaneTarget();
+    std::vector<AutomationTarget> targets;
+    for (const auto& lane : currentPattern (engine.getSong()).events)
+        if (lane.target.kind != AutomationTargetKind::none && ! lane.events.empty())
+            targets.push_back (lane.target);
+    if (shown && std::find (targets.begin(), targets.end(), *shown) == targets.end())
+        targets.push_back (*shown);
+    if (targets == eventTargets && ! force)
+        return;
+
+    eventTargets = targets;
+    const auto previous = laneBox.getSelectedId();
+    laneBox.clear (juce::dontSendNotification);
+    laneBox.addItem (tr ("Velocity"), 1);
+    laneBox.addItem (tr ("Pan"), 2);
+    laneBox.addItem (tr ("Fine pitch"), 3);
+    if (! eventTargets.empty())
+        laneBox.addSectionHeading (tr ("Pattern events"));
+    for (int k = 0; k < (int) eventTargets.size(); ++k)
+        laneBox.addItem (describeAutomationTarget (engine, eventTargets[(std::size_t) k]), eventLaneIdBase + k);
+    auto id = previous >= 1 && previous <= 3 ? previous : 1;
+    if (shown)
+        id = eventLaneIdBase + (int) (std::find (eventTargets.begin(), eventTargets.end(), *shown) - eventTargets.begin());
+    laneBox.setSelectedId (id, juce::dontSendNotification);
+}
+
+void PianoRollComponent::showEventLane (const AutomationTarget& target)
+{
+    rebuildLaneBox (target, true);
+    repaint();
+}
+
+void PianoRollComponent::drawEvents (int fromX, int toX, int y, bool erase)
+{
+    const auto target = eventLaneTarget();
+    if (! target)
+        return;
+    const auto lane = velocityArea();
+    const auto value = juce::jlimit (0.0f, 1.0f, (float) (lane.getBottom() - 2 - y) / (float) (lane.getHeight() - 8));
+    const auto step = std::max<std::int64_t> (1, gridTicks());
+    const auto t0 = std::max<std::int64_t> (0, (std::int64_t) std::floor (xToTick (juce::jmin (fromX, toX)) / (double) step) * step);
+    const auto t1 = std::max (t0 + step, (std::int64_t) std::floor (xToTick (juce::jmax (fromX, toX)) / (double) step) * step + step);
+    const auto pattern = engine.getSong().currentPattern;
+    engine.editSong ([&] (Song& s) {
+        if (pattern < 0 || pattern >= (int) s.patterns.size())
+            return;
+        auto& p = s.patterns[(std::size_t) pattern];
+        if (erase)
+        {
+            if (auto* l = eventedit::findLane (p, *target))
+                eventedit::erase (*l, t0, t1);
+            eventedit::removeEmptyLanes (p);
+        }
+        else
+            eventedit::fill (eventedit::laneFor (p, *target), t0, t1, value, step);
+    });
+    repaint (velocityArea());
+}
+
 void PianoRollComponent::timerCallback()
 {
     if (channelBox.getSelectedId() != engine.getSelectedChannel() + 1)

+ 12 - 1
src/ui/PianoRollComponent.h

@@ -70,6 +70,12 @@ public:
     // (called on open).
     void scrollToNotes (bool fitPattern = true);
 
+    // FL's parameter menu "Edit events in piano roll" (REA round 146): the bottom lane shows and draws the current
+    // pattern's events of `target` (the lane box lists the pattern's event lanes after the note properties).
+    void showEventLane (const AutomationTarget& target);
+    // The target the bottom lane edits when it shows pattern events.
+    std::optional<AutomationTarget> eventLaneTarget() const;
+
     // For tests/snapshots: selects all of the channel's notes.
     void selectAll();
 
@@ -94,7 +100,7 @@ public:
 
 private:
     enum class Drag { none, move, resize, resizeLeft, erase, keyboard, select, velocity, velocityLine, velocitySet, paint, muting, knife,
-                      zoomRange, listen, pan, keyZoom, keySelect, rulerSelect, drumPaint, stretch };
+                      zoomRange, listen, pan, keyZoom, keySelect, rulerSelect, drumPaint, stretch, eventDraw, eventErase };
 
     // Channel selector: the wheel steps through the channels with notes (Ctrl+wheel: all channels).
     class ChannelBox final : public juce::ComboBox
@@ -218,6 +224,11 @@ private:
     juce::uint32 lastWheelEdit = 0;    // wheel edits within a burst are one undo step
     std::vector<Note> laneOriginals;   // right-drag line / Shift+drag: the pattern's notes when it started
     float laneSetValue = 0.0f;
+    // pattern event lanes in the lane box (ids eventLaneIdBase + k; REA round 146)
+    static constexpr int eventLaneIdBase = 100;
+    std::vector<AutomationTarget> eventTargets;
+    void rebuildLaneBox (std::optional<AutomationTarget> shown = std::nullopt, bool force = false);
+    void drawEvents (int fromX, int toX, int y, bool erase);
     int keyZoomKey = 60, keyZoomStartRow = 14;
 
     // smooth wheel scrolling

+ 17 - 7
src/ui/SettingsPages.cpp

@@ -726,7 +726,7 @@ public:
         };
         styleNote (pickupNote, tr ("A controller moves a parameter only after reaching its current value, so nothing jumps."));
 
-        styleLabel (linksLabel, tr ("Links in this project"));
+        styleLabel (linksLabel, tr ("Links (this project, then global)"));
         linksLabel.setJustificationType (juce::Justification::topLeft);
         links.setModel (this);
         links.setRowHeight (24);
@@ -735,8 +735,11 @@ public:
         links.setOutlineThickness (1);
         removeLink.onClick = [this] {
             const auto row = links.getSelectedRow();
-            if (juce::isPositiveAndBelow (row, (int) engine.getSong().midiLinks.size()))
+            const auto projectLinks = (int) engine.getSong().midiLinks.size();
+            if (juce::isPositiveAndBelow (row, projectLinks))
                 engine.editSong ([row] (Song& s) { s.midiLinks.erase (s.midiLinks.begin() + row); });
+            else if (const auto global = engine.getGlobalLinks(); juce::isPositiveAndBelow (row - projectLinks, (int) global.size()))
+                engine.removeGlobalLink (global[(std::size_t) (row - projectLinks)].target);
         };
         removeAll.onClick = [this] { engine.editSong ([] (Song& s) { s.midiLinks.clear(); }); };
 
@@ -820,6 +823,9 @@ private:
         removeAll.setEnabled (! engine.getSong().midiLinks.empty());
     }
 
+    // the project's links, then the global ones (settings; FL's "Override global link...", REA round 146)
+    int linkRows() const { return (int) (engine.getSong().midiLinks.size() + engine.getGlobalLinks().size()); }
+
     void rebuildInputs()
     {
         rows.clear();
@@ -850,12 +856,15 @@ private:
     }
 
     // links list
-    int getNumRows() override { return juce::jmax (1, (int) engine.getSong().midiLinks.size()); }
+    int getNumRows() override { return juce::jmax (1, linkRows()); }
 
     void paintListBoxItem (int row, juce::Graphics& g, int width, int height, bool selected) override
     {
-        const auto& list = engine.getSong().midiLinks;
-        if (list.empty())
+        auto list = engine.getSong().midiLinks;
+        const auto projectLinks = (int) list.size();
+        for (const auto& l : engine.getGlobalLinks())
+            list.push_back (l);
+        if (list.empty() || row >= (int) list.size())
         {
             g.setFont (theme::font (theme::type::small));
             g.setColour (theme::colour::textDisabled);
@@ -873,10 +882,11 @@ private:
         const auto source = "CC " + juce::String (link.cc) + (link.channel >= 0 ? juce::String::fromUTF8 (" \xc2\xb7 ") + tr ("ch. {0}", { juce::String (link.channel + 1) }) : juce::String());
         g.drawText (source, 10, 0, 110, height, juce::Justification::centredLeft);
         g.setColour (theme::colour::textPrimary);
-        g.drawText (describeAutomationTarget (engine, link.target), 124, 0, width - 134, height, juce::Justification::centredLeft, true);
+        g.drawText (describeAutomationTarget (engine, link.target) + (row >= projectLinks ? "  (" + tr ("global") + ")" : juce::String()), 124, 0,
+                    width - 134, height, juce::Justification::centredLeft, true);
     }
 
-    void selectedRowsChanged (int) override { removeLink.setEnabled (links.getSelectedRow() >= 0 && ! engine.getSong().midiLinks.empty()); }
+    void selectedRowsChanged (int) override { removeLink.setEnabled (links.getSelectedRow() >= 0 && linkRows() > 0); }
 
     void changeListenerCallback (juce::ChangeBroadcaster*) override
     {

+ 105 - 0
tests/Rea146Tests.inc

@@ -0,0 +1,105 @@
+// --- REA round 146: the touched control wins over its automation while recording, initial values ------------------
+
+TEST (rea146_touched_control_overrides_its_automation)
+{
+    auto song = lynx::Song::makeDefault();
+    song.mode = lynx::PlayMode::song;
+    song.channels.clear();
+    song.playlist.clear();
+    song.automations.clear();
+    song.mixer = lynx::Song::defaultMixer (2);
+    song.mixer[0].inputChannel = 0; // a constant through the Master's input
+    song.mixer[0].monitor = lynx::InputMonitor::automatic;
+    const lynx::AutomationTarget target { lynx::AutomationTargetKind::mixerVolume, 0 };
+    lynx::Automation a;
+    a.target = target;
+    a.points = { { 0, 0.0f, 0.0f }, { 4 * lynx::ppq, 0.0f, 0.0f } }; // the Master's fader automated down to silence
+    song.automations.push_back (a);
+    lynx::Clip clip;
+    clip.kind = lynx::ClipKind::automation;
+    clip.automation = 0;
+    clip.length = 64 * lynx::ppq;
+    song.playlist.push_back (clip);
+    std::vector<int> slots;
+    lynx::RackState::slotsOfTarget (song, target, slots);
+    CHECK (slots.size() == 1 && slots[0] == 0);
+
+    auto state = lynx::RackState::build (song, nullptr, 48000.0);
+    lynx::RackRenderer renderer;
+    renderer.prepare (48000.0, 512);
+    lynx::LiveInput input;
+    renderer.setLiveInput (&input);
+    std::vector<float> in (512, 0.25f), l (512), r (512);
+    input.channels[0] = in.data();
+    input.channels[1] = in.data();
+    input.numChannels = 2;
+    auto run = [&] (int blocks) {
+        double tick = 0.0;
+        for (int b = 0; b < blocks; ++b, tick += 64.0)
+            renderer.process (state.get(), true, tick, 512, l.data(), r.data());
+        return std::abs (l[511]);
+    };
+    CHECK (run (8) < 1e-4f); // the automation plays: silence
+    renderer.setOverriddenSlots (slots); // touched while recording: the fader's own value plays
+    CHECK (renderer.isSlotOverridden (0) && ! renderer.isSlotOverridden (1));
+    const auto touched = run (8);
+    CHECK (touched > 0.05f);
+    renderer.setOverriddenSlots ({}); // released: the automation drives it again
+    CHECK (run (8) < 1e-4f);
+
+    // a pattern event lane on the same target gets its slot after the song's automations
+    song.patterns[0].events.push_back ({ target, { { 0, 0.5f } } });
+    lynx::RackState::slotsOfTarget (song, target, slots);
+    CHECK (slots.size() == 2 && slots[1] == 1);
+}
+
+TEST (rea146_initial_values_reset_the_song_like_fl)
+{
+    auto song = lynx::Song::makeDefault();
+    const lynx::AutomationTarget vol { lynx::AutomationTargetKind::mixerVolume, 1 };
+    const lynx::AutomationTarget pan { lynx::AutomationTargetKind::channelPan, 1 };
+    const lynx::AutomationTarget plug { lynx::AutomationTargetKind::effectParam, 1, 0, 3 };
+    song.setInitialValue (vol, 0.25f);
+    song.setInitialValue (vol, 0.5f); // replaces
+    song.setInitialValue (pan, 0.75f);
+    song.setInitialValue (plug, 0.1f);
+    CHECK (song.initialValues.size() == 3 && song.findInitialValue (vol) == 0 && song.initialValues[0].value == 0.5f);
+    song.setTargetValue (vol, 0.9f);
+    song.setTargetValue (pan, 0.1f);
+    std::vector<lynx::Song::InitialValue> plugins;
+    song.applyInitialValues ([&] (const lynx::AutomationTarget& t, float v) { plugins.push_back ({ t, v }); });
+    CHECK (std::abs (song.targetValue (vol) - 0.5f) < 1e-5f && std::abs (song.targetValue (pan) - 0.75f) < 1e-5f);
+    // the mixer slot has no effect: the value goes to the caller (a plugin's parameter lives in the plugin)
+    CHECK (plugins.size() == 1 && plugins[0].target == plug && plugins[0].value == 0.1f);
+    song.removeInitialValue (vol);
+    CHECK (song.findInitialValue (vol) < 0 && song.initialValues.size() == 2);
+    // removing channel 0 renumbers the target; removing its own channel drops it
+    song.removeChannel (0);
+    CHECK (song.findInitialValue ({ lynx::AutomationTargetKind::channelPan, 0 }) >= 0);
+    song.removeChannel (0);
+    CHECK (song.findInitialValue ({ lynx::AutomationTargetKind::channelPan, 0 }) < 0 && song.initialValues.size() == 1);
+}
+
+TEST (rea146_global_links_and_project_override)
+{
+    const lynx::AutomationTarget master { lynx::AutomationTargetKind::mixerVolume, 0 };
+    const lynx::AutomationTarget tempo { lynx::AutomationTargetKind::tempo, 0 };
+    const lynx::AutomationTarget pan { lynx::AutomationTargetKind::channelPan, 2 };
+    std::vector<lynx::MidiLink> global = { { 7, -1, master }, { 20, 0, tempo }, { 21, -1, pan } };
+    std::vector<lynx::MidiLink> project = { { 30, -1, master }, { 20, 1, pan } }; // same target / CC 20 on another channel
+    const auto links = lynx::linksWithGlobal (project, global);
+    // the project's two, then the tempo's global link (the Master's is overridden by the project's own target,
+    // the pan's too); CC 20 channel 1 vs channel 0 do not collide
+    CHECK (links.size() == 3 && links[2].target == tempo);
+    project = { { 21, 5, master } }; // CC 21 on channel 6 collides with the global "any channel" CC 21
+    const auto links2 = lynx::linksWithGlobal (project, global);
+    CHECK (links2.size() == 2 && links2[1].target == tempo);
+
+    lynx::prefs::MidiPrefs p;
+    p.pickup = true;
+    p.globalLinks.push_back ({ 7, -1, (int) lynx::AutomationTargetKind::mixerVolume, 0, 0, 0 });
+    p.globalLinks.push_back ({ 74, 3, (int) lynx::AutomationTargetKind::effectParam, 2, 1, 4 });
+    const auto back = lynx::prefs::MidiPrefs::fromText (p.toText());
+    CHECK (back == p);
+    CHECK (lynx::prefs::MidiPrefs::fromText ("link=7|-1|99|0|0|0\nlink=1|2\n").globalLinks.empty());
+}

+ 1 - 0
tests/tests.cpp

@@ -15545,6 +15545,7 @@ TEST (flp_pattern_events_import)
 #include "Rea143Tests.inc"
 #include "Rea143aTests.inc"
 #include "Rea143bTests.inc"
+#include "Rea146Tests.inc"
 #include "AudioEditTests.inc"
 #include "InputTests.inc"
 #include "../asio/InputDrift.h"