Răsfoiți Sursa

Clips de automação: volume/pan de canal e mixer, parâmetros de efeitos e de plugins, editor de pontos com curva

Kauan 1 lună în urmă
părinte
comite
a1d871e270

+ 2 - 1
CMakeLists.txt

@@ -65,7 +65,8 @@ if(LYNX_BUILD_APP)
         src/ui/PlaylistComponent.cpp
         src/ui/MixerComponent.cpp
         src/ui/PluginWindow.cpp
-        src/ui/ExportDialog.cpp)
+        src/ui/ExportDialog.cpp
+        src/ui/AutomationUi.cpp)
 
     target_compile_definitions(LYNX PRIVATE
         JUCE_WEB_BROWSER=0

+ 1 - 1
scripts/build-windows-zig.sh

@@ -69,7 +69,7 @@ fi
 APP_SOURCES=(src/Main.cpp
              src/engine/AudioEngine.cpp src/engine/ChannelRackProcessor.cpp src/engine/Metronome.cpp
              src/engine/SampleLibrary.cpp src/engine/ProjectFile.cpp src/engine/PluginHost.cpp src/engine/Exporter.cpp
-             src/ui/MainComponent.cpp src/ui/ChannelRackComponent.cpp src/ui/PianoRollComponent.cpp src/ui/PlaylistComponent.cpp src/ui/MixerComponent.cpp src/ui/PluginWindow.cpp src/ui/ExportDialog.cpp
+             src/ui/MainComponent.cpp src/ui/ChannelRackComponent.cpp src/ui/PianoRollComponent.cpp src/ui/PlaylistComponent.cpp src/ui/MixerComponent.cpp src/ui/PluginWindow.cpp src/ui/ExportDialog.cpp src/ui/AutomationUi.cpp
              src/core/Song.cpp src/core/Scheduler.cpp src/core/Instruments.cpp src/core/RackRenderer.cpp
              src/core/FlpImport.cpp src/core/Effects.cpp src/core/NoteEdit.cpp src/core/Recorder.cpp src/flp/Flp.cpp
              src/platform/MingwFixes.cpp)

+ 26 - 3
src/Main.cpp

@@ -21,7 +21,8 @@ public:
 
         if (args.contains ("--selftest"))
         {
-            runSelfTest (args[args.indexOf ("--selftest") + 1].unquoted());
+            const auto i = args.indexOf ("--selftest");
+            runSelfTest (args[i + 1].unquoted(), args[i + 2].unquoted());
             return;
         }
 
@@ -74,7 +75,7 @@ public:
 private:
     // LYNX.exe --selftest relatorio.txt: renderiza 2 s sem placa de som e grava o resultado.
     // Código de saída 0 = saiu áudio, 1 = silêncio.
-    void runSelfTest (const juce::String& reportPath)
+    void runSelfTest (const juce::String& reportPath, const juce::String& demoProjectPath)
     {
         lynx::AudioEngine offline (false);
         const auto peak = offline.renderOffline (2.0, 48000.0);
@@ -87,13 +88,35 @@ private:
         original.mode = lynx::PlayMode::song;
         original.mixer[3].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
         original.mixer[3].effects[0].params[1] = 0.25f;
+        lynx::Automation automation;
+        automation.name = "Pan";
+        automation.target = { lynx::AutomationTargetKind::effectParam, 3, 0, 1 };
+        automation.points = { { 0, 0.25f, 0.5f }, { 3840, 1.0f, 0.0f } };
+        original.automations.push_back (automation);
+        lynx::Clip automationClip;
+        automationClip.kind = lynx::ClipKind::automation;
+        automationClip.automation = 0;
+        automationClip.track = 4;
+        automationClip.length = 3840;
+        original.playlist.push_back (automationClip);
+        original.loopStart = 960;
+        original.loopEnd = 7680;
         juce::String error;
+
+        if (demoProjectPath.isNotEmpty()) // projeto de exemplo para conferir a UI com --snapshot
+            lynx::ProjectFile::save (original, juce::File (demoProjectPath), error);
+
         const auto reloaded = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (original), error);
         const auto projectOk = reloaded && reloaded->channels.size() == original.channels.size()
                                && reloaded->channels[0].name == original.channels[0].name
                                && reloaded->patterns[0].notes.size() == original.patterns[0].notes.size()
                                && reloaded->patterns[0].notes[3].start == original.patterns[0].notes[3].start
-                               && reloaded->mode == lynx::PlayMode::song && reloaded->playlist.size() == 1
+                               && reloaded->mode == lynx::PlayMode::song && reloaded->playlist.size() == 2
+                               && reloaded->playlist[1].kind == lynx::ClipKind::automation && reloaded->playlist[1].automation == 0
+                               && reloaded->automations.size() == 1 && reloaded->automations[0].target == automation.target
+                               && reloaded->automations[0].points.size() == 2 && reloaded->automations[0].points[0].tension == 0.5f
+                               && reloaded->automations[0].points[1].tick == 3840
+                               && reloaded->loopStart == 960 && reloaded->loopEnd == 7680
                                && reloaded->playlist[0].offset == 960 && reloaded->playlist[0].track == 2
                                && reloaded->mixer[3].effects.size() == 1
                                && reloaded->mixer[3].effects[0].kind == lynx::EffectKind::delay

+ 24 - 24
src/core/Effects.cpp

@@ -100,15 +100,15 @@ public:
             b.reset();
     }
 
-    void process (float* l, float* r, int n, const EffectSlot& slot, double) noexcept override
+    void process (float* l, float* r, int n, const EffectParams& params, double) noexcept override
     {
-        if (slot.params != lastParams)
+        if (params != lastParams)
         {
-            lastParams = slot.params;
-            bands[0].shelf (sampleRate, 120.0, eqGainDb (slot.params[0]), false);
-            bands[1].peaking (sampleRate, eqMidHz (slot.params[2]), 0.8, eqGainDb (slot.params[1]));
-            bands[2].shelf (sampleRate, 8000.0, eqGainDb (slot.params[3]), true);
-            output = dbToGain (eqGainDb (slot.params[4]));
+            lastParams = params;
+            bands[0].shelf (sampleRate, 120.0, eqGainDb (params[0]), false);
+            bands[1].peaking (sampleRate, eqMidHz (params[2]), 0.8, eqGainDb (params[1]));
+            bands[2].shelf (sampleRate, 8000.0, eqGainDb (params[3]), true);
+            output = dbToGain (eqGainDb (params[4]));
         }
 
         for (int i = 0; i < n; ++i)
@@ -141,13 +141,13 @@ public:
     void prepare (double sr) noexcept override { sampleRate = sr; reset(); }
     void reset() noexcept override { envelopeDb = 0.0f; }
 
-    void process (float* l, float* r, int n, const EffectSlot& slot, double) noexcept override
+    void process (float* l, float* r, int n, const EffectParams& params, double) noexcept override
     {
-        const auto threshold = compThresholdDb (slot.params[0]);
-        const auto ratio = compRatio (slot.params[1]);
-        const auto attack = (float) std::exp (-1.0 / (compAttackMs (slot.params[2]) * 0.001 * sampleRate));
-        const auto release = (float) std::exp (-1.0 / (compReleaseMs (slot.params[3]) * 0.001 * sampleRate));
-        const auto makeup = dbToGain (compMakeupDb (slot.params[4]));
+        const auto threshold = compThresholdDb (params[0]);
+        const auto ratio = compRatio (params[1]);
+        const auto attack = (float) std::exp (-1.0 / (compAttackMs (params[2]) * 0.001 * sampleRate));
+        const auto release = (float) std::exp (-1.0 / (compReleaseMs (params[3]) * 0.001 * sampleRate));
+        const auto makeup = dbToGain (compMakeupDb (params[4]));
 
         for (int i = 0; i < n; ++i)
         {
@@ -195,15 +195,15 @@ public:
         write = 0;
     }
 
-    void process (float* l, float* r, int n, const EffectSlot& slot, double bpm) noexcept override
+    void process (float* l, float* r, int n, const EffectParams& params, double bpm) noexcept override
     {
-        const auto beats = delayDivisions[(std::size_t) delayIndex (slot.params[0])];
+        const auto beats = delayDivisions[(std::size_t) delayIndex (params[0])];
         const auto seconds = std::min (maxSeconds - 0.01, beats * 60.0 / std::max (bpm, 20.0));
         const auto delaySamples = std::max<std::size_t> (1, (std::size_t) (seconds * sampleRate));
-        const auto feedback = slot.params[1] * 0.95f;
-        const auto mix = slot.params[2];
-        const auto pingPong = slot.params[3] > 0.5f;
-        const auto dampCoeff = 1.0f - slot.params[4] * 0.9f; // 1 = sem filtro no retorno
+        const auto feedback = params[1] * 0.95f;
+        const auto mix = params[2];
+        const auto pingPong = params[3] > 0.5f;
+        const auto dampCoeff = 1.0f - params[4] * 0.9f; // 1 = sem filtro no retorno
         const auto size = buffer[0].size();
 
         for (int i = 0; i < n; ++i)
@@ -301,12 +301,12 @@ public:
             }
     }
 
-    void process (float* l, float* r, int n, const EffectSlot& slot, double) noexcept override
+    void process (float* l, float* r, int n, const EffectParams& params, double) noexcept override
     {
-        const auto feedback = 0.7f + slot.params[0] * 0.28f; // tamanho da sala
-        const auto damping = slot.params[1] * 0.4f;
-        const auto width = slot.params[2];
-        const auto mix = slot.params[3];
+        const auto feedback = 0.7f + params[0] * 0.28f; // tamanho da sala
+        const auto damping = params[1] * 0.4f;
+        const auto width = params[2];
+        const auto mix = params[3];
         const auto wet1 = width / 2.0f + 0.5f;
         const auto wet2 = (1.0f - width) / 2.0f;
         constexpr float inputGain = 0.015f;

+ 3 - 1
src/core/Effects.h

@@ -41,7 +41,9 @@ public:
     virtual void reset() noexcept = 0;
 
     // Processa no lugar. Os parâmetros chegam a cada bloco (podem mudar a qualquer momento).
-    virtual void process (float* left, float* right, int n, const EffectSlot& slot, double bpm) noexcept = 0;
+    virtual void process (float* left, float* right, int n, const EffectParams& params, double bpm) noexcept = 0;
+    // Parâmetro automatizado de plugin (os internos recebem os parâmetros em process()). 0..1.
+    virtual void setParameter (int /*index*/, float /*value*/) noexcept {}
 };
 
 std::unique_ptr<Effect> makeEffect (EffectKind kind);

+ 2 - 0
src/core/Instruments.h

@@ -27,6 +27,8 @@ public:
 
     // Soma (não sobrescreve) n samples em left/right, já aplicando os ganhos.
     virtual void render (float* left, float* right, int n, float gainLeft, float gainRight) noexcept = 0;
+    // Parâmetro automatizado (plugins). 0..1. Thread de áudio.
+    virtual void setParameter (int /*index*/, float /*value*/) noexcept {}
 };
 
 // Áudio de um sample já decodificado (carregado fora da thread de áudio).

+ 194 - 9
src/core/RackRenderer.cpp

@@ -3,6 +3,7 @@
 #include <algorithm>
 #include <cmath>
 #include <cstring>
+#include <limits>
 
 namespace lynx
 {
@@ -25,7 +26,7 @@ class BypassEffect final : public Effect
 public:
     void prepare (double) noexcept override {}
     void reset() noexcept override {}
-    void process (float*, float*, int, const EffectSlot&, double) noexcept override {}
+    void process (float*, float*, int, const EffectParams&, double) noexcept override {}
 };
 } // namespace
 
@@ -128,9 +129,92 @@ std::unique_ptr<const RackState> RackState::build (Song song,
 
     state->song = std::move (song);
     state->sampleRate = sampleRate;
+    state->buildAutomationTables();
     return state;
 }
 
+void RackState::buildAutomationTables()
+{
+    const auto& automations = song.automations;
+    const auto count = std::min<int> ((int) automations.size(), maxAutomations);
+
+    automationClips.assign ((std::size_t) count, {});
+
+    for (int i = 0; i < (int) song.playlist.size(); ++i)
+    {
+        const auto& c = song.playlist[(std::size_t) i];
+
+        if (c.kind == ClipKind::automation && c.automation >= 0 && c.automation < count && c.length > 0)
+            automationClips[(std::size_t) c.automation].push_back (i);
+    }
+
+    for (auto& clips : automationClips)
+        std::sort (clips.begin(), clips.end(),
+                   [this] (int a, int b) { return song.playlist[(std::size_t) a].start < song.playlist[(std::size_t) b].start; });
+
+    channelVolumeAuto.assign (song.channels.size(), -1);
+    channelPanAuto.assign (song.channels.size(), -1);
+    mixerVolumeAuto.assign (song.mixer.size(), -1);
+    mixerPanAuto.assign (song.mixer.size(), -1);
+    effectParamAuto.assign (song.mixer.size(), {});
+
+    for (std::size_t t = 0; t < song.mixer.size(); ++t)
+    {
+        std::array<int, maxEffectParams> none;
+        none.fill (-1);
+        effectParamAuto[t].assign (song.mixer[t].effects.size(), none);
+    }
+
+    pluginParams.clear();
+    hasAutomation = false;
+
+    // a última automação de um mesmo alvo ganha
+    for (int a = 0; a < count; ++a)
+    {
+        if (automationClips[(std::size_t) a].empty())
+            continue;
+
+        const auto& t = automations[(std::size_t) a].target;
+        const auto channelOk = t.index >= 0 && t.index < (int) song.channels.size();
+        const auto trackOk = t.index >= 0 && t.index < (int) song.mixer.size();
+        auto used = true;
+
+        switch (t.kind)
+        {
+            case AutomationTargetKind::channelVolume: if (channelOk) channelVolumeAuto[(std::size_t) t.index] = a; else used = false; break;
+            case AutomationTargetKind::channelPan: if (channelOk) channelPanAuto[(std::size_t) t.index] = a; else used = false; break;
+            case AutomationTargetKind::mixerVolume: if (trackOk) mixerVolumeAuto[(std::size_t) t.index] = a; else used = false; break;
+            case AutomationTargetKind::mixerPan: if (trackOk) mixerPanAuto[(std::size_t) t.index] = a; else used = false; break;
+
+            case AutomationTargetKind::channelParam:
+                if (channelOk && song.channels[(std::size_t) t.index].instrument == InstrumentKind::plugin)
+                    pluginParams.push_back ({ a, t.index, 0, 0, t.param });
+                else
+                    used = false;
+                break;
+
+            case AutomationTargetKind::effectParam:
+            {
+                const auto slotOk = trackOk && t.slot >= 0 && t.slot < (int) song.mixer[(std::size_t) t.index].effects.size();
+
+                if (! slotOk)
+                    used = false;
+                else if (song.mixer[(std::size_t) t.index].effects[(std::size_t) t.slot].kind == EffectKind::plugin)
+                    pluginParams.push_back ({ a, -1, t.index, t.slot, t.param });
+                else if (t.param >= 0 && t.param < maxEffectParams)
+                    effectParamAuto[(std::size_t) t.index][(std::size_t) t.slot][(std::size_t) t.param] = a;
+                else
+                    used = false;
+                break;
+            }
+
+            case AutomationTargetKind::none: used = false; break;
+        }
+
+        hasAutomation = hasAutomation || used;
+    }
+}
+
 namespace
 {
 // Pan de potência constante: no centro os dois lados ficam em 1 (0 dB).
@@ -154,6 +238,7 @@ float peakOf (const float* data, int n) noexcept
 
 void RackRenderer::prepare (double sr, int maxBlockSize)
 {
+    automationValues.fill (std::numeric_limits<float>::quiet_NaN());
     sampleRate = sr;
     blockCapacity = std::max (64, maxBlockSize);
     mixBuffers.assign ((std::size_t) maxMixerTracks * 2 * (std::size_t) blockCapacity, 0.0f);
@@ -174,17 +259,91 @@ float* RackRenderer::trackBuffer (int track, int channel) noexcept
     return mixBuffers.data() + ((std::size_t) track * 2 + (std::size_t) channel) * (std::size_t) blockCapacity;
 }
 
+float RackRenderer::automated (int automation, float base) const noexcept
+{
+    if (automation < 0)
+        return base;
+
+    const auto v = automationValues[(std::size_t) automation];
+    return std::isnan (v) ? base : v;
+}
+
+namespace
+{
+// Valor de uma automação numa posição da música: dentro de um clip, a curva; entre clips,
+// o último valor do clip anterior; antes do primeiro, o valor inicial dele. Só depende da
+// posição, então tocar de qualquer ponto (ou exportar) dá o mesmo resultado.
+float automationValueAt (const Song& song, const Automation& automation, const std::vector<int>& clips, double tick) noexcept
+{
+    const Clip* before = nullptr;
+
+    for (auto i : clips) // ordenados por início
+    {
+        const auto& c = song.playlist[(std::size_t) i];
+
+        if (tick < (double) c.start)
+            break;
+
+        if (tick < (double) c.end())
+            return automation.valueAt (tick - (double) c.start + (double) c.offset);
+
+        before = &c;
+    }
+
+    if (before != nullptr)
+        return automation.valueAt ((double) (before->length + before->offset));
+
+    const auto& first = song.playlist[(std::size_t) clips.front()];
+    return automation.valueAt ((double) first.offset);
+}
+} // namespace
+
+void RackRenderer::updateAutomation (const RackState& state, double startTick) noexcept
+{
+    const auto& song = state.song;
+
+    // no modo pattern a Playlist não toca: os valores ficam como estavam
+    if (song.mode != PlayMode::song)
+        return;
+
+    const auto length = (double) std::max<std::int64_t> (1, song.songLength());
+    const auto tick = std::fmod (std::max (0.0, startTick), length);
+
+    for (std::size_t a = 0; a < state.automationClips.size(); ++a)
+        if (! state.automationClips[a].empty())
+            automationValues[a] = automationValueAt (song, song.automations[a], state.automationClips[a], tick);
+
+    for (const auto& b : state.pluginParams)
+    {
+        const auto v = automationValues[(std::size_t) b.automation];
+
+        if (std::isnan (v))
+            continue;
+
+        if (b.channel >= 0)
+        {
+            if (b.channel < (int) state.instruments.size())
+                state.instruments[(std::size_t) b.channel]->setParameter (b.param, v);
+        }
+        else if (b.track < (int) state.effects.size() && b.slot < (int) state.effects[(std::size_t) b.track].size())
+            state.effects[(std::size_t) b.track][(std::size_t) b.slot]->setParameter (b.param, v);
+    }
+}
+
 void RackRenderer::renderSegment (const RackState& state, int offset, int n) noexcept
 {
     const auto& channels = state.song.channels;
     const auto tracks = std::max<int> (1, (int) state.song.mixer.size());
+    const auto automation = state.hasAutomation;
 
     for (std::size_t i = 0; i < state.instruments.size() && i < channels.size(); ++i)
     {
         const auto& c = channels[i];
         const auto track = std::clamp (c.mixerTrack, 0, tracks - 1);
+        const auto volume = automation ? automated (state.channelVolumeAuto[i], c.volume) : c.volume;
+        const auto pan = automation ? automated (state.channelPanAuto[i], (c.pan + 1.0f) * 0.5f) * 2.0f - 1.0f : c.pan;
         float gl = 0.0f, gr = 0.0f;
-        panGains (c.pan, c.volume, gl, gr);
+        panGains (pan, volume, gl, gr);
         state.instruments[i]->render (trackBuffer (track, 0) + offset, trackBuffer (track, 1) + offset, n, gl, gr);
     }
 }
@@ -198,8 +357,23 @@ void RackRenderer::runEffects (const RackState& state, int track, int n) noexcep
     const auto& effects = state.effects[(std::size_t) track];
 
     for (std::size_t i = 0; i < effects.size() && i < slots.size(); ++i)
-        if (slots[i].enabled)
-            effects[i]->process (trackBuffer (track, 0), trackBuffer (track, 1), n, slots[i], state.song.bpm);
+    {
+        if (! slots[i].enabled)
+            continue;
+
+        if (state.hasAutomation && slots[i].kind != EffectKind::plugin)
+        {
+            auto params = slots[i].params; // cópia de 6 floats, sem alocação
+            const auto& autos = state.effectParamAuto[(std::size_t) track][i];
+
+            for (std::size_t p = 0; p < params.size(); ++p)
+                params[p] = automated (autos[p], params[p]);
+
+            effects[i]->process (trackBuffer (track, 0), trackBuffer (track, 1), n, params, state.song.bpm);
+        }
+        else
+            effects[i]->process (trackBuffer (track, 0), trackBuffer (track, 1), n, slots[i].params, state.song.bpm);
+    }
 }
 
 void RackRenderer::process (const RackState* state,
@@ -268,10 +442,13 @@ void RackRenderer::process (const RackState* state,
         }
     }
 
-    // Blocos maiores que os buffers do mixer são feitos em pedaços.
-    for (int done = 0; done < numSamples; done += blockCapacity)
+    // Blocos maiores que os buffers do mixer são feitos em pedaços. Com automação, pedaços
+    // pequenos para os valores andarem suavemente.
+    const auto chunk = state->hasAutomation ? std::min (blockCapacity, 128) : blockCapacity;
+
+    for (int done = 0; done < numSamples; done += chunk)
     {
-        const auto n = std::min (blockCapacity, numSamples - done);
+        const auto n = std::min (chunk, numSamples - done);
         processChunk (*state, playing, startTick + done * tps, n, left + done, right + done, meters);
         resumeAudio = false;
     }
@@ -283,6 +460,9 @@ void RackRenderer::processChunk (const RackState& state, bool playing, double st
     const auto& song = state.song;
     const auto tracks = std::max<int> (1, (int) song.mixer.size());
 
+    if (state.hasAutomation)
+        updateAutomation (state, startTick);
+
     for (int t = 0; t < tracks; ++t)
     {
         std::memset (trackBuffer (t, 0), 0, sizeof (float) * (std::size_t) numSamples);
@@ -350,8 +530,11 @@ void RackRenderer::processChunk (const RackState& state, bool playing, double st
 
         runEffects (state, t, numSamples);
 
+        const auto volume = state.hasAutomation ? automated (state.mixerVolumeAuto[(std::size_t) t], track.volume) : track.volume;
+        const auto pan = state.hasAutomation ? automated (state.mixerPanAuto[(std::size_t) t], (track.pan + 1.0f) * 0.5f) * 2.0f - 1.0f
+                                             : track.pan;
         float gl = 0.0f, gr = 0.0f;
-        panGains (track.pan, track.volume / unityFader, gl, gr);
+        panGains (pan, volume / unityFader, gl, gr);
         const auto* l = trackBuffer (t, 0);
         const auto* r = trackBuffer (t, 1);
 
@@ -373,7 +556,9 @@ void RackRenderer::processChunk (const RackState& state, bool playing, double st
     if (! song.mixer.empty())
     {
         const auto& master = song.mixer[0];
-        panGains (master.pan, master.muted ? 0.0f : master.volume / unityFader, gl, gr);
+        const auto volume = state.hasAutomation ? automated (state.mixerVolumeAuto[0], master.volume) : master.volume;
+        const auto pan = state.hasAutomation ? automated (state.mixerPanAuto[0], (master.pan + 1.0f) * 0.5f) * 2.0f - 1.0f : master.pan;
+        panGains (pan, master.muted ? 0.0f : volume / unityFader, gl, gr);
     }
 
     for (int i = 0; i < numSamples; ++i)

+ 24 - 0
src/core/RackRenderer.h

@@ -3,6 +3,7 @@
 // Junta Song + instrumentos + scheduler: dado o estado do transporte, gera o
 // áudio estéreo de um bloco com as notas disparadas no sample exato.
 
+#include <array>
 #include <functional>
 #include <memory>
 #include <string>
@@ -26,6 +27,26 @@ struct RackState
     std::vector<std::vector<std::shared_ptr<Effect>>> effects; // [trilha do mixer][slot]
     double sampleRate = 44100.0; // taxa com que os instrumentos novos foram preparados
 
+    // Automação, pré-processada para a thread de áudio só consultar tabelas.
+    // Índices em song.automations, ou -1 = sem automação.
+    static constexpr int maxAutomations = 1024;
+    std::vector<std::vector<int>> automationClips; // por automação: clips na Playlist
+    std::vector<int> channelVolumeAuto, channelPanAuto;
+    std::vector<int> mixerVolumeAuto, mixerPanAuto;
+    std::vector<std::vector<std::array<int, maxEffectParams>>> effectParamAuto; // [trilha][slot][param] (internos)
+
+    struct PluginParamBinding
+    {
+        int automation = 0;
+        int channel = -1;       // instrumento do canal, ou
+        int track = 0, slot = 0; // efeito no slot
+        int param = 0;
+    };
+    std::vector<PluginParamBinding> pluginParams;
+    bool hasAutomation = false;
+
+    void buildAutomationTables();
+
     // Carrega (ou pega do cache) o áudio de um arquivo; nullptr se não conseguir.
     using SampleProvider = std::function<std::shared_ptr<const SampleData> (const std::string& path)>;
 
@@ -81,6 +102,8 @@ private:
                        float* left, float* right, MeterBank* meters) noexcept;
     void renderSegment (const RackState& state, int offset, int n) noexcept;
     void runEffects (const RackState& state, int track, int n) noexcept;
+    void updateAutomation (const RackState& state, double startTick) noexcept;
+    float automated (int automation, float base) const noexcept;
     float* trackBuffer (int track, int channel) noexcept;
 
     double sampleRate = 44100.0;
@@ -90,6 +113,7 @@ private:
     const RackState* lastState = nullptr;
     EventBuffer events;
     std::vector<float> mixBuffers; // maxMixerTracks * 2 * blockCapacity
+    std::array<float, RackState::maxAutomations> automationValues {}; // NaN = ainda não avaliada
     int blockCapacity = 0;
 };
 } // namespace lynx

+ 1 - 1
src/core/Scheduler.cpp

@@ -124,7 +124,7 @@ void scheduleSong (const Song& song, double startTick, int numSamples, double tp
             continue;
         }
 
-        if (clip.pattern < 0 || clip.pattern >= (int) song.patterns.size() || clip.length <= 0)
+        if (clip.kind != ClipKind::pattern || clip.pattern < 0 || clip.pattern >= (int) song.patterns.size() || clip.length <= 0)
             continue;
 
         // folga de um tick para pegar o "off" que cai exatamente no fim do clip

+ 121 - 0
src/core/Song.cpp

@@ -1,6 +1,7 @@
 #include "core/Song.h"
 
 #include <algorithm>
+#include <cmath>
 
 namespace lynx
 {
@@ -124,6 +125,126 @@ void Song::removeChannel (int index)
     for (auto& c : playlist)
         if (c.kind == ClipKind::audio && c.channel > index)
             --c.channel;
+
+    for (auto& a : automations)
+    {
+        auto& t = a.target;
+        const auto onChannel = t.kind == AutomationTargetKind::channelVolume || t.kind == AutomationTargetKind::channelPan
+                               || t.kind == AutomationTargetKind::channelParam;
+
+        if (onChannel && t.index == index)
+            t.kind = AutomationTargetKind::none;
+        else if (onChannel && t.index > index)
+            --t.index;
+    }
+}
+
+void Song::swapEffectSlots (int track, int a, int b)
+{
+    if (track < 0 || track >= (int) mixer.size())
+        return;
+
+    auto& fx = mixer[(std::size_t) track].effects;
+
+    if (a < 0 || b < 0 || a >= (int) fx.size() || b >= (int) fx.size())
+        return;
+
+    std::swap (fx[(std::size_t) a], fx[(std::size_t) b]);
+
+    for (auto& au : automations)
+        if (au.target.kind == AutomationTargetKind::effectParam && au.target.index == track)
+            au.target.slot = au.target.slot == a ? b : au.target.slot == b ? a : au.target.slot;
+}
+
+void Song::removeEffectSlot (int track, int slot)
+{
+    if (track < 0 || track >= (int) mixer.size() || slot < 0 || slot >= (int) mixer[(std::size_t) track].effects.size())
+        return;
+
+    auto& fx = mixer[(std::size_t) track].effects;
+    fx.erase (fx.begin() + slot);
+
+    for (auto& au : automations)
+        if (au.target.kind == AutomationTargetKind::effectParam && au.target.index == track)
+        {
+            if (au.target.slot == slot)
+                au.target.kind = AutomationTargetKind::none;
+            else if (au.target.slot > slot)
+                --au.target.slot;
+        }
+}
+
+void Song::removeAutomation (int index)
+{
+    if (index < 0 || index >= (int) automations.size())
+        return;
+
+    automations.erase (automations.begin() + index);
+    playlist.erase (std::remove_if (playlist.begin(), playlist.end(),
+                                    [index] (const Clip& c) { return c.kind == ClipKind::automation && c.automation == index; }),
+                    playlist.end());
+
+    for (auto& c : playlist)
+        if (c.kind == ClipKind::automation && c.automation > index)
+            --c.automation;
+}
+
+float Song::targetValue (const AutomationTarget& t) const noexcept
+{
+    const auto validChannel = t.index >= 0 && t.index < (int) channels.size();
+    const auto validTrack = t.index >= 0 && t.index < (int) mixer.size();
+
+    switch (t.kind)
+    {
+        case AutomationTargetKind::channelVolume: return validChannel ? channels[(std::size_t) t.index].volume : -1.0f;
+        case AutomationTargetKind::channelPan: return validChannel ? (channels[(std::size_t) t.index].pan + 1.0f) * 0.5f : -1.0f;
+        case AutomationTargetKind::mixerVolume: return validTrack ? mixer[(std::size_t) t.index].volume : -1.0f;
+        case AutomationTargetKind::mixerPan: return validTrack ? (mixer[(std::size_t) t.index].pan + 1.0f) * 0.5f : -1.0f;
+        case AutomationTargetKind::effectParam:
+            if (validTrack && t.slot >= 0 && t.slot < (int) mixer[(std::size_t) t.index].effects.size()
+                && mixer[(std::size_t) t.index].effects[(std::size_t) t.slot].kind != EffectKind::plugin && t.param >= 0
+                && t.param < maxEffectParams)
+                return mixer[(std::size_t) t.index].effects[(std::size_t) t.slot].params[(std::size_t) t.param];
+            return validTrack ? 0.5f : -1.0f; // parâmetro de plugin: o valor mora no plugin
+        case AutomationTargetKind::channelParam: return validChannel ? 0.5f : -1.0f;
+        case AutomationTargetKind::none: break;
+    }
+
+    return -1.0f;
+}
+
+float Automation::valueAt (double tick) const noexcept
+{
+    if (points.empty())
+        return 0.5f;
+
+    if (tick <= (double) points.front().tick)
+        return points.front().value;
+
+    for (std::size_t i = 1; i < points.size(); ++i)
+    {
+        const auto& a = points[i - 1];
+        const auto& b = points[i];
+
+        if (tick < (double) b.tick)
+        {
+            const auto span = (double) std::max<std::int64_t> (1, b.tick - a.tick);
+            auto t = (float) ((tick - (double) a.tick) / span);
+
+            // tensão: expoente da curva (positiva = sobe devagar e acelera)
+            if (a.tension != 0.0f)
+                t = std::pow (t, std::pow (2.0f, a.tension * 3.0f));
+
+            return a.value + (b.value - a.value) * t;
+        }
+    }
+
+    return points.back().value;
+}
+
+std::int64_t Automation::length() const noexcept
+{
+    return points.empty() ? 1 : std::max<std::int64_t> (1, points.back().tick);
 }
 
 Song makeExportSong (const Song& song, bool wholeSong, std::int64_t tailTicks, std::int64_t& musicLength)

+ 60 - 2
src/core/Song.h

@@ -62,12 +62,13 @@ enum class EffectKind : std::uint8_t
 
 constexpr int maxEffectParams = 6;
 constexpr int maxEffectSlots = 10; // como no FL
+using EffectParams = std::array<float, maxEffectParams>;
 
 struct EffectSlot
 {
     EffectKind kind = EffectKind::eq;
     bool enabled = true;
-    std::array<float, maxEffectParams> params {}; // 0..1; o significado depende do efeito
+    EffectParams params {}; // 0..1; o significado depende do efeito
     PluginRef plugin;                             // usado quando kind == plugin
 };
 
@@ -107,7 +108,51 @@ struct Pattern
 enum class ClipKind : std::uint8_t
 {
     pattern,
-    audio
+    audio,
+    automation
+};
+
+// O que um clip de automação controla. Valores sempre 0..1 (como os knobs do modelo).
+enum class AutomationTargetKind : std::uint8_t
+{
+    none,          // alvo removido (o clip fica mudo)
+    channelVolume, // index = canal
+    channelPan,    // index = canal (0..1 -> -1..1)
+    channelParam,  // index = canal com plugin; param = índice do parâmetro do plugin
+    mixerVolume,   // index = trilha do mixer (0 = Master)
+    mixerPan,      // index = trilha
+    effectParam    // index = trilha, slot, param (efeito interno ou plugin)
+};
+
+struct AutomationTarget
+{
+    AutomationTargetKind kind = AutomationTargetKind::none;
+    int index = 0;
+    int slot = 0;
+    int param = 0;
+
+    bool operator== (const AutomationTarget& o) const noexcept
+    {
+        return kind == o.kind && index == o.index && slot == o.slot && param == o.param;
+    }
+};
+
+struct AutomationPoint
+{
+    std::int64_t tick = 0; // a partir do início da automação
+    float value = 0.5f;    // 0..1
+    float tension = 0.0f;  // curva até o próximo ponto: -1..1 (0 = reta)
+};
+
+struct Automation
+{
+    std::string name;
+    AutomationTarget target;
+    std::vector<AutomationPoint> points; // ordenados por tick (mantido por quem edita)
+
+    // Valor em `tick` (antes do primeiro ponto = primeiro valor; depois do último = último).
+    float valueAt (double tick) const noexcept;
+    std::int64_t length() const noexcept; // tick do último ponto (mínimo 1)
 };
 
 // Um bloco na Playlist: um trecho de uma pattern, ou um trecho do áudio de um canal audioClip.
@@ -120,6 +165,7 @@ struct Clip
     std::int64_t offset = 0;  // quanto do começo da pattern/áudio é pulado (ticks)
     ClipKind kind = ClipKind::pattern;
     int channel = -1;         // clips de áudio: canal (audioClip) que tem o sample
+    int automation = -1;      // clips de automação: índice em Song::automations
 
     std::int64_t end() const noexcept { return start + length; }
 };
@@ -145,6 +191,7 @@ struct Song
     bool hasLoop() const noexcept { return loopEnd > loopStart; }
 
     std::vector<MixerTrack> mixer; // [0] = Master; vazio = tudo direto na saída
+    std::vector<Automation> automations;
 
     static std::vector<MixerTrack> defaultMixer (int inserts = 16);
     // Primeiro insert que nenhum canal usa (ou o último, se todos estiverem ocupados).
@@ -157,8 +204,19 @@ struct Song
     void removePattern (int index);
 
     // Remove um canal com as notas e clips de áudio dele, e reindexa os demais.
+    // Automações desse canal ficam sem alvo.
     void removeChannel (int index);
 
+    // Troca/remove slots de efeito mantendo as automações apontando para o efeito certo.
+    void swapEffectSlots (int track, int a, int b);
+    void removeEffectSlot (int track, int slot);
+
+    // Remove uma automação e os clips dela.
+    void removeAutomation (int index);
+
+    // Valor atual (do modelo, sem automação) do alvo, 0..1; -1 se o alvo não existir.
+    float targetValue (const AutomationTarget& target) const noexcept;
+
     static Song makeDefault();
 };
 

+ 20 - 1
src/engine/PluginHost.cpp

@@ -24,6 +24,15 @@ void preparePlugin (juce::AudioPluginInstance& plugin, double sampleRate, int bl
     plugin.prepareToPlay (sampleRate, blockSize);
 }
 
+void setPluginParameter (juce::AudioPluginInstance& plugin, int index, float value) noexcept
+{
+    const auto& params = plugin.getParameters();
+
+    if (index >= 0 && index < params.size())
+        if (auto* p = params[index]; p->getValue() != value)
+            p->setValue (value);
+}
+
 int bufferChannels (const juce::AudioPluginInstance& plugin)
 {
     return juce::jmax (2, plugin.getTotalNumInputChannels(), plugin.getTotalNumOutputChannels());
@@ -61,6 +70,11 @@ void PluginInstrument::allNotesOff() noexcept
     midi.addEvent (juce::MidiMessage::allSoundOff (1), 0);
 }
 
+void PluginInstrument::setParameter (int index, float value) noexcept
+{
+    setPluginParameter (*plugin, index, value);
+}
+
 void PluginInstrument::render (float* left, float* right, int n, float gl, float gr) noexcept
 {
     for (int done = 0; done < n;)
@@ -98,7 +112,12 @@ PluginEffect::~PluginEffect()
     plugin->releaseResources();
 }
 
-void PluginEffect::process (float* left, float* right, int n, const EffectSlot&, double) noexcept
+void PluginEffect::setParameter (int index, float value) noexcept
+{
+    setPluginParameter (*plugin, index, value);
+}
+
+void PluginEffect::process (float* left, float* right, int n, const EffectParams&, double) noexcept
 {
     for (int done = 0; done < n;)
     {

+ 3 - 1
src/engine/PluginHost.h

@@ -26,6 +26,7 @@ public:
     void noteOff (int key) noexcept override;
     void allNotesOff() noexcept override;
     void render (float* left, float* right, int n, float gainLeft, float gainRight) noexcept override;
+    void setParameter (int index, float value) noexcept override;
 
 private:
     std::unique_ptr<juce::AudioPluginInstance> plugin;
@@ -44,7 +45,8 @@ public:
 
     void prepare (double) noexcept override {}
     void reset() noexcept override {}
-    void process (float* left, float* right, int n, const EffectSlot& slot, double bpm) noexcept override;
+    void process (float* left, float* right, int n, const EffectParams& params, double bpm) noexcept override;
+    void setParameter (int index, float value) noexcept override;
 
 private:
     std::unique_ptr<juce::AudioPluginInstance> plugin;

+ 78 - 2
src/engine/ProjectFile.cpp

@@ -74,6 +74,31 @@ std::optional<EffectKind> effectFromId (const juce::String& id)
 
     return std::nullopt; // efeito de uma versão futura: ignorado
 }
+
+const char* targetKindName (AutomationTargetKind k)
+{
+    switch (k)
+    {
+        case AutomationTargetKind::channelVolume: return "channelVolume";
+        case AutomationTargetKind::channelPan: return "channelPan";
+        case AutomationTargetKind::channelParam: return "channelParam";
+        case AutomationTargetKind::mixerVolume: return "mixerVolume";
+        case AutomationTargetKind::mixerPan: return "mixerPan";
+        case AutomationTargetKind::effectParam: return "effectParam";
+        case AutomationTargetKind::none: break;
+    }
+    return "none";
+}
+
+AutomationTargetKind targetKindFromName (const juce::String& name)
+{
+    for (auto k : { AutomationTargetKind::channelVolume, AutomationTargetKind::channelPan, AutomationTargetKind::channelParam,
+                    AutomationTargetKind::mixerVolume, AutomationTargetKind::mixerPan, AutomationTargetKind::effectParam })
+        if (name == targetKindName (k))
+            return k;
+
+    return AutomationTargetKind::none;
+}
 } // namespace
 
 juce::String toJson (const Song& song)
@@ -134,11 +159,33 @@ juce::String toJson (const Song& song)
 
     root->setProperty ("patterns", patterns);
 
+    juce::Array<juce::var> automations;
+
+    for (const auto& a : song.automations)
+    {
+        auto o = std::make_unique<juce::DynamicObject>();
+        o->setProperty ("name", str (a.name));
+        o->setProperty ("target", juce::Array<juce::var> { targetKindName (a.target.kind), a.target.index, a.target.slot, a.target.param });
+        juce::Array<juce::var> points;
+
+        for (const auto& pt : a.points)
+            points.add (juce::Array<juce::var> { (juce::int64) pt.tick, juce::roundToInt (pt.value * 10000.0f) / 10000.0,
+                                                 juce::roundToInt (pt.tension * 1000.0f) / 1000.0 });
+
+        o->setProperty ("points", points);
+        automations.add (juce::var (o.release()));
+    }
+
+    if (! automations.isEmpty())
+        root->setProperty ("automations", automations);
+
     juce::Array<juce::var> clips;
 
+    // [pattern, trilha, início, duração, offset, tipo (0 pattern, 1 áudio, 2 automação), canal ou automação]
     for (const auto& c : song.playlist)
         clips.add (juce::Array<juce::var> { c.pattern, c.track, (juce::int64) c.start, (juce::int64) c.length,
-                                            (juce::int64) c.offset, c.kind == ClipKind::audio ? 1 : 0, c.channel });
+                                            (juce::int64) c.offset, (int) c.kind,
+                                            c.kind == ClipKind::automation ? c.automation : c.channel });
 
     root->setProperty ("playlist", clips);
 
@@ -262,6 +309,27 @@ std::optional<Song> fromJson (const juce::String& json, juce::String& error)
     if (song.patterns.empty())
         song.patterns.emplace_back().name = "Pattern 1";
 
+    if (auto* automations = root["automations"].getArray())
+        for (const auto& a : *automations)
+        {
+            Automation automation;
+            automation.name = a["name"].toString().toStdString();
+
+            if (const auto& t = a["target"]; t.isArray() && t.size() == 4)
+                automation.target = { targetKindFromName (t[0].toString()), (int) t[1], (int) t[2], (int) t[3] };
+
+            if (auto* points = a["points"].getArray())
+                for (const auto& pt : *points)
+                    if (pt.isArray() && pt.size() >= 2)
+                        automation.points.push_back ({ juce::jmax<juce::int64> (0, (juce::int64) pt[0]),
+                                                       juce::jlimit (0.0f, 1.0f, (float) (double) pt[1]),
+                                                       pt.size() >= 3 ? juce::jlimit (-1.0f, 1.0f, (float) (double) pt[2]) : 0.0f });
+
+            std::stable_sort (automation.points.begin(), automation.points.end(),
+                              [] (const AutomationPoint& x, const AutomationPoint& y) { return x.tick < y.tick; });
+            song.automations.push_back (std::move (automation));
+        }
+
     if (auto* clips = root["playlist"].getArray())
         for (const auto& c : *clips)
         {
@@ -275,7 +343,15 @@ std::optional<Song> fromJson (const juce::String& json, juce::String& error)
             clip.length = (juce::int64) c[3];
             clip.offset = juce::jmax<juce::int64> (0, (juce::int64) c[4]);
 
-            if (c.size() >= 7 && (int) c[5] == 1) // [.., tipo, canal]; arquivos antigos têm só 5 campos
+            if (c.size() >= 7 && (int) c[5] == 2)
+            {
+                clip.kind = ClipKind::automation;
+                clip.automation = (int) c[6];
+
+                if (clip.automation >= 0 && clip.automation < (int) song.automations.size() && clip.length > 0)
+                    song.playlist.push_back (clip);
+            }
+            else if (c.size() >= 7 && (int) c[5] == 1) // [.., tipo, canal]; arquivos antigos têm só 5 campos
             {
                 clip.kind = ClipKind::audio;
                 clip.channel = (int) c[6];

+ 504 - 0
src/ui/AutomationUi.cpp

@@ -0,0 +1,504 @@
+#include "ui/AutomationUi.h"
+
+#include <map>
+
+#include "core/Effects.h"
+#include "engine/Text.h"
+#include "ui/Theme.h"
+
+namespace lynx
+{
+namespace
+{
+juce::String nameOf (const std::string& s)
+{
+    return juce::String::fromUTF8 (s.c_str());
+}
+
+juce::AudioPluginInstance* pluginFor (AudioEngine& engine, const AutomationTarget& t)
+{
+    if (t.kind == AutomationTargetKind::channelParam)
+        if (auto* p = dynamic_cast<PluginInstrument*> (engine.getChannelInstrument (t.index).get()))
+            return &p->getInstance();
+
+    if (t.kind == AutomationTargetKind::effectParam)
+        if (auto* p = dynamic_cast<PluginEffect*> (engine.getEffect (t.index, t.slot).get()))
+            return &p->getInstance();
+
+    return nullptr;
+}
+
+// Editor dos pontos: tempo na horizontal (compassos), valor na vertical.
+//  - clique no vazio cria um ponto; arrastar move; clique direito apaga
+//  - arrastar com Alt sobre um trecho muda a curva (tensão)
+//  - Ctrl+roda dá zoom; roda rola
+class AutomationEditor final : public juce::Component,
+                               private juce::ChangeListener,
+                               private juce::Timer
+{
+public:
+    AutomationEditor (AudioEngine& e, int index)
+        : engine (e),
+          automation (index)
+    {
+        engine.addChangeListener (this);
+        setSize (760, 300);
+        startTimerHz (30);
+    }
+
+    ~AutomationEditor() override { engine.removeChangeListener (this); }
+
+    int getIndex() const noexcept { return automation; }
+
+    void paint (juce::Graphics& g) override
+    {
+        g.fillAll (theme::window);
+        const auto* a = current();
+
+        if (a == nullptr)
+            return;
+
+        const auto& song = engine.getSong();
+        const auto area = plotArea();
+        const auto bar = (std::int64_t) ppq * juce::jmax (1, song.beatsPerBar);
+
+        g.setColour (juce::Colour (0xff262b30));
+        g.fillRect (area);
+
+        // grade: tempos e compassos
+        const auto beatPixels = ppq * pixelsPerTick;
+        const auto lastTick = (std::int64_t) xToTick (area.getRight());
+
+        for (auto tick = (std::int64_t) std::floor (scroll / ppq) * ppq; tick <= lastTick; tick += ppq)
+        {
+            const auto isBar = tick % bar == 0;
+
+            if (! isBar && beatPixels < 8.0)
+                continue;
+
+            const auto x = (int) tickToX ((double) tick);
+            g.setColour (isBar ? juce::Colour (0xff15181b) : juce::Colour (0xff2c3238));
+            g.drawVerticalLine (x, (float) area.getY(), (float) area.getBottom());
+
+            if (isBar)
+            {
+                g.setColour (theme::text.withAlpha (0.6f));
+                g.setFont (juce::FontOptions (11.0f));
+                g.drawText (juce::String (tick / bar + 1), x + 3, 2, 40, 16, juce::Justification::centredLeft);
+            }
+        }
+
+        for (auto v : { 0.25f, 0.5f, 0.75f })
+        {
+            g.setColour (juce::Colour (0xff2f353c));
+            g.drawHorizontalLine ((int) valueToY (v), (float) area.getX(), (float) area.getRight());
+        }
+
+        // curva
+        juce::Path curve;
+        const auto& points = a->points;
+
+        for (auto x = area.getX(); x <= area.getRight(); x += 2)
+        {
+            const auto y = valueToY (a->valueAt (xToTick (x)));
+
+            if (x == area.getX())
+                curve.startNewSubPath ((float) x, y);
+            else
+                curve.lineTo ((float) x, y);
+        }
+
+        g.setColour (theme::accentGreen);
+        g.strokePath (curve, juce::PathStrokeType (2.0f));
+
+        for (std::size_t i = 0; i < points.size(); ++i)
+        {
+            const auto p = pointPosition (points[i]);
+            g.setColour ((int) i == hoverPoint || (int) i == dragPoint ? juce::Colours::white : theme::accentGreen);
+            g.fillEllipse (p.x - 5.0f, p.y - 5.0f, 10.0f, 10.0f);
+            g.setColour (juce::Colours::black.withAlpha (0.6f));
+            g.drawEllipse (p.x - 5.0f, p.y - 5.0f, 10.0f, 10.0f, 1.0f);
+        }
+
+        // cursor de reprodução (na posição do clip que estiver tocando)
+        if (playhead >= 0.0)
+        {
+            g.setColour (theme::playhead);
+            g.drawVerticalLine ((int) tickToX (playhead), (float) area.getY(), (float) area.getBottom());
+        }
+
+        g.setColour (theme::text.withAlpha (0.45f));
+        g.setFont (juce::FontOptions (11.0f));
+        g.drawText (utf8 ("Clique: novo ponto · arrastar: mover · clique direito: apagar · Alt+arrastar: curva · Ctrl+roda: zoom"),
+                    area.getX(), getHeight() - 18, area.getWidth(), 16, juce::Justification::centredLeft);
+
+        if (hoverPoint >= 0 && hoverPoint < (int) points.size())
+        {
+            const auto p = pointPosition (points[(std::size_t) hoverPoint]);
+            g.setColour (theme::text);
+            g.drawText (juce::String (juce::roundToInt (points[(std::size_t) hoverPoint].value * 100.0f)) + "%",
+                        (int) p.x + 8, (int) p.y - 18, 60, 14, juce::Justification::centredLeft);
+        }
+    }
+
+    void mouseMove (const juce::MouseEvent& e) override
+    {
+        const auto hit = pointAt (e.position);
+
+        if (hit != hoverPoint)
+        {
+            hoverPoint = hit;
+            repaint();
+        }
+    }
+
+    void mouseDown (const juce::MouseEvent& e) override
+    {
+        const auto* a = current();
+
+        if (a == nullptr || ! plotArea().contains (e.getPosition()))
+            return;
+
+        const auto hit = pointAt (e.position);
+
+        if (e.mods.isPopupMenu())
+        {
+            if (hit >= 0 && a->points.size() > 1)
+                edit ([hit] (Automation& x) { x.points.erase (x.points.begin() + hit); });
+            return;
+        }
+
+        if (e.mods.isAltDown())
+        {
+            // segmento sob o mouse: o ponto à esquerda guarda a tensão
+            tensionPoint = -1;
+            const auto tick = xToTick (e.x);
+
+            for (int i = 0; i + 1 < (int) a->points.size(); ++i)
+                if (tick >= (double) a->points[(std::size_t) i].tick && tick < (double) a->points[(std::size_t) i + 1].tick)
+                    tensionPoint = i;
+
+            if (tensionPoint >= 0)
+                tensionStart = a->points[(std::size_t) tensionPoint].tension;
+            return;
+        }
+
+        if (hit >= 0)
+        {
+            dragPoint = hit;
+            return;
+        }
+
+        AutomationPoint p;
+        p.tick = snap (xToTick (e.x), ! e.mods.isShiftDown());
+        p.value = yToValue (e.y);
+        edit ([p] (Automation& x) {
+            x.points.push_back (p);
+            std::stable_sort (x.points.begin(), x.points.end(), [] (auto& l, auto& r) { return l.tick < r.tick; });
+        });
+
+        for (int i = 0; i < (int) current()->points.size(); ++i)
+            if (current()->points[(std::size_t) i].tick == p.tick && current()->points[(std::size_t) i].value == p.value)
+                dragPoint = i;
+    }
+
+    void mouseDrag (const juce::MouseEvent& e) override
+    {
+        const auto* a = current();
+
+        if (a == nullptr)
+            return;
+
+        if (tensionPoint >= 0 && tensionPoint < (int) a->points.size())
+        {
+            const auto tension = juce::jlimit (-1.0f, 1.0f, tensionStart + (float) e.getDistanceFromDragStartY() / 100.0f);
+            edit ([i = tensionPoint, tension] (Automation& x) { x.points[(std::size_t) i].tension = tension; });
+            return;
+        }
+
+        if (dragPoint < 0 || dragPoint >= (int) a->points.size())
+            return;
+
+        // o ponto não passa dos vizinhos (a ordem não muda durante o arraste)
+        const auto& points = a->points;
+        auto tick = snap (xToTick (e.x), ! e.mods.isShiftDown());
+        const auto lo = dragPoint > 0 ? points[(std::size_t) dragPoint - 1].tick : 0;
+        const auto hi = dragPoint + 1 < (int) points.size() ? points[(std::size_t) dragPoint + 1].tick : std::numeric_limits<std::int64_t>::max();
+        tick = juce::jlimit (lo, hi, tick);
+        const auto value = yToValue (e.y);
+
+        edit ([i = dragPoint, tick, value] (Automation& x) {
+            x.points[(std::size_t) i].tick = tick;
+            x.points[(std::size_t) i].value = value;
+        });
+    }
+
+    void mouseUp (const juce::MouseEvent&) override
+    {
+        dragPoint = tensionPoint = -1;
+        repaint();
+    }
+
+    void mouseWheelMove (const juce::MouseEvent& e, const juce::MouseWheelDetails& wheel) override
+    {
+        if (e.mods.isCtrlDown())
+        {
+            const auto anchor = xToTick (e.x);
+            pixelsPerTick = juce::jlimit (4.0 / (4 * ppq), 600.0 / (4 * ppq), pixelsPerTick * (wheel.deltaY > 0 ? 1.2 : 1.0 / 1.2));
+            scroll = juce::jmax (0.0, anchor - (e.x - plotArea().getX()) / pixelsPerTick);
+        }
+        else
+            scroll = juce::jmax (0.0, scroll - (wheel.deltaY + wheel.deltaX) * 300.0 / pixelsPerTick);
+
+        repaint();
+    }
+
+private:
+    const Automation* current() const
+    {
+        const auto& song = engine.getSong();
+        return automation >= 0 && automation < (int) song.automations.size() ? &song.automations[(std::size_t) automation] : nullptr;
+    }
+
+    void edit (const std::function<void (Automation&)>& fn)
+    {
+        engine.editSong ([this, &fn] (Song& s) {
+            if (automation >= 0 && automation < (int) s.automations.size())
+                fn (s.automations[(std::size_t) automation]);
+        });
+    }
+
+    juce::Rectangle<int> plotArea() const { return getLocalBounds().withTrimmedTop (18).withTrimmedBottom (20).reduced (8, 4); }
+    double tickToX (double tick) const { return plotArea().getX() + (tick - scroll) * pixelsPerTick; }
+    double xToTick (int x) const { return juce::jmax (0.0, (x - plotArea().getX()) / pixelsPerTick + scroll); }
+    float valueToY (float v) const { return (float) plotArea().getBottom() - v * (float) plotArea().getHeight(); }
+    float yToValue (int y) const { return juce::jlimit (0.0f, 1.0f, (float) (plotArea().getBottom() - y) / (float) plotArea().getHeight()); }
+
+    std::int64_t snap (double tick, bool on) const
+    {
+        const auto grid = on ? (double) ticksPerStep : 1.0;
+        return (std::int64_t) std::round (tick / grid) * (std::int64_t) grid;
+    }
+
+    juce::Point<float> pointPosition (const AutomationPoint& p) const { return { (float) tickToX ((double) p.tick), valueToY (p.value) }; }
+
+    int pointAt (juce::Point<float> pos) const
+    {
+        const auto* a = current();
+
+        if (a == nullptr)
+            return -1;
+
+        for (int i = (int) a->points.size() - 1; i >= 0; --i)
+            if (pointPosition (a->points[(std::size_t) i]).getDistanceFrom (pos) < 8.0f)
+                return i;
+
+        return -1;
+    }
+
+    void changeListenerCallback (juce::ChangeBroadcaster*) override
+    {
+        if (current() == nullptr) // automação removida: fecha
+        {
+            juce::MessageManager::callAsync ([safe = juce::Component::SafePointer<Component> (getParentComponent())] {
+                if (auto* w = dynamic_cast<juce::DocumentWindow*> (safe.getComponent()))
+                    w->closeButtonPressed();
+            });
+            return;
+        }
+
+        if (auto* w = findParentComponentOfClass<juce::DocumentWindow>())
+            w->setName (utf8 ("Automação - ") + juce::String::fromUTF8 (current()->name.c_str()));
+
+        repaint();
+    }
+
+    void timerCallback() override
+    {
+        // posição dentro da automação, se algum clip dela estiver sob o cursor
+        auto tick = -1.0;
+        const auto& song = engine.getSong();
+
+        if (song.mode == PlayMode::song && engine.getTransport().playing.load())
+        {
+            const auto position = std::fmod (engine.getTransport().positionTicks.load(), (double) juce::jmax<std::int64_t> (1, song.songLength()));
+
+            for (const auto& c : song.playlist)
+                if (c.kind == ClipKind::automation && c.automation == automation && position >= (double) c.start && position < (double) c.end())
+                    tick = position - (double) c.start + (double) c.offset;
+        }
+
+        if (tick != playhead)
+        {
+            playhead = tick;
+            repaint();
+        }
+    }
+
+    AudioEngine& engine;
+    int automation;
+    double pixelsPerTick = 120.0 / (4 * ppq);
+    double scroll = 0.0;
+    int dragPoint = -1, hoverPoint = -1, tensionPoint = -1;
+    float tensionStart = 0.0f;
+    double playhead = -1.0;
+};
+
+class AutomationWindow final : public juce::DocumentWindow
+{
+public:
+    AutomationWindow (AudioEngine& engine, int index, const juce::String& title)
+        : juce::DocumentWindow (title, theme::window, DocumentWindow::closeButton)
+    {
+        setUsingNativeTitleBar (true);
+        setContentOwned (new AutomationEditor (engine, index), true);
+        setResizable (true, false);
+        setResizeLimits (400, 200, 4000, 2000);
+        centreWithSize (getWidth(), getHeight());
+        setVisible (true);
+    }
+
+    int getIndex() const { return static_cast<AutomationEditor*> (getContentComponent())->getIndex(); }
+
+    void closeButtonPressed() override;
+};
+
+std::vector<std::unique_ptr<AutomationWindow>>& windows()
+{
+    static std::vector<std::unique_ptr<AutomationWindow>> open;
+    return open;
+}
+
+void AutomationWindow::closeButtonPressed()
+{
+    auto* self = this;
+    juce::MessageManager::callAsync ([self] {
+        auto& open = windows();
+        open.erase (std::remove_if (open.begin(), open.end(), [self] (auto& w) { return w.get() == self; }), open.end());
+    });
+}
+} // namespace
+
+juce::String describeAutomationTarget (AudioEngine& engine, const AutomationTarget& t)
+{
+    const auto& song = engine.getSong();
+    const auto channelName = t.index >= 0 && t.index < (int) song.channels.size() ? nameOf (song.channels[(std::size_t) t.index].name) : juce::String ("?");
+    const auto trackName = t.index >= 0 && t.index < (int) song.mixer.size() ? nameOf (song.mixer[(std::size_t) t.index].name) : juce::String ("?");
+
+    switch (t.kind)
+    {
+        case AutomationTargetKind::channelVolume: return channelName + " - Volume";
+        case AutomationTargetKind::channelPan: return channelName + " - Pan";
+        case AutomationTargetKind::mixerVolume: return trackName + " - Volume";
+        case AutomationTargetKind::mixerPan: return trackName + " - Pan";
+
+        case AutomationTargetKind::channelParam:
+        case AutomationTargetKind::effectParam:
+        {
+            juce::String param = juce::String ("Param ") + juce::String (t.param + 1);
+
+            if (auto* plugin = pluginFor (engine, t))
+            {
+                if (t.param >= 0 && t.param < plugin->getParameters().size())
+                    param = plugin->getParameters()[t.param]->getName (40);
+            }
+            else if (t.kind == AutomationTargetKind::effectParam && t.index < (int) song.mixer.size()
+                     && t.slot < (int) song.mixer[(std::size_t) t.index].effects.size())
+            {
+                const auto& info = effectInfo (song.mixer[(std::size_t) t.index].effects[(std::size_t) t.slot].kind);
+
+                if (t.param >= 0 && t.param < (int) info.params.size())
+                    param = utf8 (info.params[(std::size_t) t.param].name);
+            }
+
+            return (t.kind == AutomationTargetKind::channelParam ? channelName : trackName) + " - " + param;
+        }
+
+        case AutomationTargetKind::none: break;
+    }
+
+    return utf8 ("(sem alvo)");
+}
+
+void createAutomationClip (AudioEngine& engine, const AutomationTarget& target)
+{
+    auto value = engine.getSong().targetValue (target);
+
+    if (auto* plugin = pluginFor (engine, target); plugin != nullptr && target.param < plugin->getParameters().size())
+        value = plugin->getParameters()[target.param]->getValue();
+
+    if (value < 0.0f)
+        return;
+
+    const auto name = describeAutomationTarget (engine, target).toStdString();
+
+    engine.editSong ([&] (Song& s) {
+        const auto bar = (std::int64_t) ppq * std::max (1, s.beatsPerBar);
+        const auto length = s.playlist.empty() ? bar * 4 : s.songLength();
+
+        Automation a;
+        a.name = name;
+        a.target = target;
+        a.points = { { 0, value, 0.0f }, { length, value, 0.0f } };
+        s.automations.push_back (std::move (a));
+
+        int track = 0;
+        for (const auto& c : s.playlist)
+            track = std::max (track, c.track + 1);
+
+        Clip clip;
+        clip.kind = ClipKind::automation;
+        clip.automation = (int) s.automations.size() - 1;
+        clip.track = track;
+        clip.length = length;
+        s.playlist.push_back (clip);
+    });
+
+    openAutomationEditor (engine, (int) engine.getSong().automations.size() - 1);
+}
+
+void openAutomationEditor (AudioEngine& engine, int index)
+{
+    if (index < 0 || index >= (int) engine.getSong().automations.size())
+        return;
+
+    for (auto& w : windows())
+        if (w->getIndex() == index)
+        {
+            w->toFront (true);
+            return;
+        }
+
+    windows().push_back (std::make_unique<AutomationWindow> (
+        engine, index, utf8 ("Automação - ") + nameOf (engine.getSong().automations[(std::size_t) index].name)));
+}
+
+void closeAutomationEditors()
+{
+    windows().clear();
+}
+
+void addAutomationItem (juce::PopupMenu& menu, AudioEngine& engine, const AutomationTarget& target)
+{
+    menu.addItem (utf8 ("Criar clip de automação"), [&engine, target] { createAutomationClip (engine, target); });
+}
+
+void addPluginParameterItems (juce::PopupMenu& menu, AudioEngine& engine, juce::AudioPluginInstance& plugin,
+                              const AutomationTarget& base)
+{
+    juce::PopupMenu params;
+    const auto& list = plugin.getParameters();
+
+    for (int i = 0; i < list.size() && i < 512; ++i)
+    {
+        auto target = base;
+        target.param = i;
+        params.addItem (list[i]->getName (60), [&engine, target] { createAutomationClip (engine, target); });
+    }
+
+    if (list.isEmpty())
+        params.addItem (utf8 ("(o plugin não expõe parâmetros)"), false, false, [] {});
+
+    menu.addSubMenu (utf8 ("Automatizar parâmetro do plugin"), params);
+}
+} // namespace lynx

+ 24 - 0
src/ui/AutomationUi.h

@@ -0,0 +1,24 @@
+#pragma once
+
+#include "engine/AudioEngine.h"
+
+namespace lynx
+{
+// Nome legível do que uma automação controla ("Kick - Volume", "Insert 3 - Pan"...).
+juce::String describeAutomationTarget (AudioEngine& engine, const AutomationTarget& target);
+
+// Cria uma automação do alvo, começando no valor atual, e um clip dela na Playlist
+// (do início da música até o fim dela, numa trilha livre), como o "Create automation clip" do FL.
+void createAutomationClip (AudioEngine& engine, const AutomationTarget& target);
+
+// Abre (ou traz para frente) a janela de edição dos pontos de uma automação.
+void openAutomationEditor (AudioEngine& engine, int automation);
+void closeAutomationEditors();
+
+// Item "Criar clip de automação" para menus de knob.
+void addAutomationItem (juce::PopupMenu& menu, AudioEngine& engine, const AutomationTarget& target);
+
+// Submenu com os parâmetros de um plugin (instrumento do canal ou efeito do slot).
+void addPluginParameterItems (juce::PopupMenu& menu, AudioEngine& engine, juce::AudioPluginInstance& plugin,
+                              const AutomationTarget& base);
+} // namespace lynx

+ 15 - 0
src/ui/ChannelRackComponent.cpp

@@ -1,5 +1,7 @@
 #include "ui/ChannelRackComponent.h"
 
+#include "ui/AutomationUi.h"
+
 #include "engine/Text.h"
 
 #include "ui/PluginWindow.h"
@@ -269,6 +271,14 @@ void ChannelRackComponent::mouseDown (const juce::MouseEvent& e)
 
         case Area::pan:
         case Area::volume:
+            if (e.mods.isPopupMenu())
+            {
+                juce::PopupMenu menu;
+                addAutomationItem (menu, engine, { area == Area::pan ? AutomationTargetKind::channelPan : AutomationTargetKind::channelVolume, row });
+                menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
+                return;
+            }
+
             knobDrag = area;
             knobRow = row;
             knobStartValue = area == Area::pan ? song.channels[(std::size_t) row].pan : song.channels[(std::size_t) row].volume;
@@ -421,8 +431,13 @@ void ChannelRackComponent::showChannelMenu (int channel)
                       false, false, [] {});
 
     if (c.instrument == InstrumentKind::plugin)
+    {
         menu.addItem (utf8 ("Abrir interface do plugin"), [this, channel] { openPluginWindow (channel); });
 
+        if (auto* p = dynamic_cast<PluginInstrument*> (engine.getChannelInstrument (channel).get()))
+            addPluginParameterItems (menu, engine, p->getInstance(), { AutomationTargetKind::channelParam, channel, 0, 0 });
+    }
+
     menu.addItem ("Piano Roll", [this] {
         if (onOpenPianoRoll)
             onOpenPianoRoll();

+ 2 - 0
src/ui/MainComponent.cpp

@@ -3,6 +3,7 @@
 #include "engine/Text.h"
 
 #include "engine/ProjectFile.h"
+#include "ui/AutomationUi.h"
 #include "ui/ExportDialog.h"
 #include "ui/PluginWindow.h"
 #include "ui/Theme.h"
@@ -130,6 +131,7 @@ MainComponent::MainComponent (AudioEngine& e)
 MainComponent::~MainComponent()
 {
     PluginWindows::closeAll(); // interfaces de plugin antes do engine
+    closeAutomationEditors();
     engine.removeChangeListener (this);
     stopTimer();
 }

+ 28 - 12
src/ui/MixerComponent.cpp

@@ -1,5 +1,7 @@
 #include "ui/MixerComponent.h"
 
+#include "ui/AutomationUi.h"
+
 #include "core/Effects.h"
 #include "engine/Text.h"
 #include "ui/PluginWindow.h"
@@ -289,6 +291,14 @@ void MixerStrips::mouseDown (const juce::MouseEvent& e)
             onSelectionChanged (t);
     }
 
+    if (e.mods.isPopupMenu() && (part == Part::pan || part == Part::fader))
+    {
+        juce::PopupMenu menu;
+        addAutomationItem (menu, engine, { part == Part::pan ? AutomationTargetKind::mixerPan : AutomationTargetKind::mixerVolume, t });
+        menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
+        return;
+    }
+
     if (e.mods.isPopupMenu())
     {
         showMenu (t);
@@ -647,6 +657,15 @@ void EffectsPanel::mouseDown (const juce::MouseEvent& e)
 
     dragParam = knobAt (e.getPosition());
 
+    if (dragParam >= 0 && e.mods.isPopupMenu())
+    {
+        juce::PopupMenu menu;
+        addAutomationItem (menu, engine, { AutomationTargetKind::effectParam, track, selectedSlot, dragParam });
+        menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
+        dragParam = -1;
+        return;
+    }
+
     if (dragParam >= 0)
         dragStart = (*s)[(std::size_t) selectedSlot].params[(std::size_t) dragParam];
 }
@@ -751,25 +770,22 @@ void EffectsPanel::showSlotMenu (int slot)
     juce::PopupMenu menu;
     menu.addSubMenu ("Trocar por", replace);
     menu.addItem ("Mover para cima", slot > 0, false, [this, slot] {
-        engine.editSong ([t = track, slot] (Song& song) {
-            auto& fx = song.mixer[(std::size_t) t].effects;
-            std::swap (fx[(std::size_t) slot], fx[(std::size_t) slot - 1]);
-        });
+        engine.editSong ([t = track, slot] (Song& song) { song.swapEffectSlots (t, slot, slot - 1); });
         selectedSlot = slot - 1;
     });
     menu.addItem ("Mover para baixo", slot < count - 1, false, [this, slot] {
-        engine.editSong ([t = track, slot] (Song& song) {
-            auto& fx = song.mixer[(std::size_t) t].effects;
-            std::swap (fx[(std::size_t) slot], fx[(std::size_t) slot + 1]);
-        });
+        engine.editSong ([t = track, slot] (Song& song) { song.swapEffectSlots (t, slot, slot + 1); });
         selectedSlot = slot + 1;
     });
+    if ((*slots())[(std::size_t) slot].kind == EffectKind::plugin)
+    {
+        if (auto* p = dynamic_cast<PluginEffect*> (engine.getEffect (track, slot).get()))
+            addPluginParameterItems (menu, engine, p->getInstance(), { AutomationTargetKind::effectParam, track, slot, 0 });
+    }
+
     menu.addSeparator();
     menu.addItem ("Remover", [this, slot] {
-        engine.editSong ([t = track, slot] (Song& song) {
-            auto& fx = song.mixer[(std::size_t) t].effects;
-            fx.erase (fx.begin() + slot);
-        });
+        engine.editSong ([t = track, slot] (Song& song) { song.removeEffectSlot (t, slot); });
         selectedSlot = juce::jmin (slot, (int) slots()->size() - 1);
         repaint();
     });

+ 90 - 1
src/ui/PlaylistComponent.cpp

@@ -2,6 +2,7 @@
 
 #include "core/NoteEdit.h"
 #include "engine/Text.h"
+#include "ui/AutomationUi.h"
 
 #include "ui/Theme.h"
 
@@ -166,6 +167,18 @@ void PlaylistComponent::paint (juce::Graphics& g)
 
             const auto r = juce::Rectangle<float> (x0, y + 1.0f, juce::jmax (3.0f, x1 - x0 - 1.0f), (float) trackHeight - 3.0f);
 
+            if (c.kind == ClipKind::automation)
+            {
+                paintAutomationClip (g, c, r);
+
+                if (isSelected (i))
+                {
+                    g.setColour (juce::Colour (0xffff6f6f));
+                    g.drawRoundedRectangle (r, 3.0f, 2.0f);
+                }
+                continue;
+            }
+
             if (c.kind == ClipKind::audio)
             {
                 paintAudioClip (g, c, r);
@@ -407,6 +420,54 @@ void PlaylistComponent::paintAudioClip (juce::Graphics& g, const Clip& c, juce::
     }
 }
 
+void PlaylistComponent::paintAutomationClip (juce::Graphics& g, const Clip& c, juce::Rectangle<float> r)
+{
+    const auto& song = engine.getSong();
+
+    if (c.automation < 0 || c.automation >= (int) song.automations.size())
+        return;
+
+    const auto& automation = song.automations[(std::size_t) c.automation];
+    const auto colour = automation.target.kind == AutomationTargetKind::none ? juce::Colour (0xff555555) : juce::Colour (0xff5f7a5a);
+
+    g.setColour (colour.withAlpha (0.55f));
+    g.fillRoundedRectangle (r, 3.0f);
+    g.setColour (colour.darker (0.6f));
+    g.drawRoundedRectangle (r, 3.0f, 1.0f);
+
+    const auto title = r.withHeight (13.0f);
+    g.setColour (colour.darker (0.4f));
+    g.fillRoundedRectangle (title, 3.0f);
+
+    if (r.getWidth() > 24)
+    {
+        g.setColour (juce::Colours::white);
+        g.drawText (juce::String::fromUTF8 (automation.name.c_str()), title.reduced (3, 0).toNearestInt(), juce::Justification::centredLeft, true);
+    }
+
+    // curva da automação no trecho do clip
+    const auto body = r.withTrimmedTop (14.0f).reduced (1.0f, 2.0f);
+    const auto clip = g.getClipBounds().toFloat();
+    juce::Path curve;
+    bool started = false;
+
+    for (auto x = std::max (body.getX(), clip.getX()); x <= std::min (body.getRight(), clip.getRight()); x += 2.0f)
+    {
+        const auto value = automation.valueAt ((double) c.offset + xToTick ((int) x) - (double) c.start);
+        const auto y = body.getBottom() - value * body.getHeight();
+
+        if (! started)
+            curve.startNewSubPath (x, y);
+        else
+            curve.lineTo (x, y);
+
+        started = true;
+    }
+
+    g.setColour (juce::Colour (0xffb8f0a8));
+    g.strokePath (curve, juce::PathStrokeType (1.5f));
+}
+
 int PlaylistComponent::clipAt (int x, int y, bool& onRightEdge) const
 {
     const auto& playlist = engine.getSong().playlist;
@@ -747,6 +808,25 @@ void PlaylistComponent::showClipMenu (int index)
         });
     }
 
+    if (clip.kind == ClipKind::automation && clip.automation >= 0 && clip.automation < (int) engine.getSong().automations.size())
+    {
+        menu.addSectionHeader (juce::String::fromUTF8 (engine.getSong().automations[(std::size_t) clip.automation].name.c_str()));
+        menu.addItem (utf8 ("Editar pontos..."), [this, a = clip.automation] { openAutomationEditor (engine, a); });
+        menu.addItem (utf8 ("Tornar única"), [this, index] {
+            engine.editSong ([index] (Song& s) {
+                auto& c = s.playlist[(std::size_t) index];
+                auto copy = s.automations[(std::size_t) c.automation];
+                copy.name += " #2";
+                s.automations.push_back (std::move (copy));
+                c.automation = (int) s.automations.size() - 1;
+            });
+        });
+        menu.addItem (utf8 ("Apagar a automação (todos os clips dela)"), [this, a = clip.automation] {
+            setSelection ({});
+            engine.editSong ([a] (Song& s) { s.removeAutomation (a); });
+        });
+    }
+
     menu.addItem (targets.size() > 1 ? "Apagar selecionados" : "Apagar", [this, targets] {
         setSelection ({});
         engine.editSong ([targets] (Song& s) {
@@ -805,6 +885,8 @@ void PlaylistComponent::pasteClips()
                 continue;
             if (c.kind == ClipKind::audio && c.channel >= (int) s.channels.size())
                 continue;
+            if (c.kind == ClipKind::automation && c.automation >= (int) s.automations.size())
+                continue;
 
             c.start = c.start - first + target;
             added.push_back ((int) s.playlist.size());
@@ -914,7 +996,14 @@ void PlaylistComponent::mouseDoubleClick (const juce::MouseEvent& e)
     bool edge = false;
     const auto hit = gridArea().contains (e.getPosition()) ? clipAt (e.x, e.y, edge) : -1;
 
-    if (hit >= 0 && engine.getSong().playlist[(std::size_t) hit].kind == ClipKind::pattern && onOpenPattern)
+    if (hit < 0)
+        return;
+
+    const auto& clip = engine.getSong().playlist[(std::size_t) hit];
+
+    if (clip.kind == ClipKind::automation)
+        openAutomationEditor (engine, clip.automation);
+    else if (clip.kind == ClipKind::pattern && onOpenPattern)
         onOpenPattern();
 }
 

+ 1 - 0
src/ui/PlaylistComponent.h

@@ -84,6 +84,7 @@ private:
     void duplicateSelection();
     void seekTo (int x);
     void paintAudioClip (juce::Graphics& g, const Clip& clip, juce::Rectangle<float> bounds);
+    void paintAutomationClip (juce::Graphics& g, const Clip& clip, juce::Rectangle<float> bounds);
     const std::vector<float>* waveformFor (const std::string& path);
 
     static constexpr std::size_t waveformBucket = 256; // frames por ponto da forma de onda

+ 62 - 3
tests/tests.cpp

@@ -859,7 +859,7 @@ float runEffectOnSine (lynx::EffectKind kind, const std::function<void (lynx::Ef
     for (int i = 0; i < frames; ++i)
         l[(std::size_t) i] = r[(std::size_t) i] = amp * (float) std::sin (6.283185307 * hz * i / 48000.0);
     for (int i = 0; i < frames; i += 480)
-        fx->process (l.data() + i, r.data() + i, std::min (480, frames - i), slot, 120.0);
+        fx->process (l.data() + i, r.data() + i, std::min (480, frames - i), slot.params, 120.0);
     float peak = 0.0f;
     for (int i = frames / 2; i < frames; ++i) // segunda metade: já estabilizado
     {
@@ -898,7 +898,7 @@ TEST (effects_delay_echoes_on_tempo_and_reverb_has_tail)
     slot.params[4] = 0.0f;        // sem abafar
     std::vector<float> l (48000, 0.0f), r (48000, 0.0f);
     l[0] = r[0] = 1.0f;
-    delay->process (l.data(), r.data(), 48000, slot, 120.0);
+    delay->process (l.data(), r.data(), 48000, slot.params, 120.0);
     CHECK (std::abs (l[24000] - 1.0f) < 1e-4f);
     CHECK (std::abs (l[12000]) < 1e-6f);
 
@@ -909,7 +909,7 @@ TEST (effects_delay_echoes_on_tempo_and_reverb_has_tail)
     std::fill (l.begin(), l.end(), 0.0f);
     std::fill (r.begin(), r.end(), 0.0f);
     l[0] = r[0] = 1.0f;
-    reverb->process (l.data(), r.data(), 48000, rs, 120.0);
+    reverb->process (l.data(), r.data(), 48000, rs.params, 120.0);
     float tail = 0.0f;
     for (int i = 4800; i < 9600; ++i) // entre 100 e 200 ms depois do impulso
         tail = std::max (tail, std::abs (l[(std::size_t) i]));
@@ -1230,6 +1230,65 @@ TEST (recorder_builds_notes_in_pattern_and_song_mode)
     CHECK (lynx::patternPositionForTick (song, 100.0, loop) == 100); // fora do clip: como loop
 }
 
+TEST (automation_curve_and_playback)
+{
+    lynx::Automation a;
+    a.points = { { 0, 0.0f }, { 960, 1.0f }, { 1920, 0.5f, 0.0f } };
+    CHECK (a.valueAt (-10.0) == 0.0f && a.valueAt (480.0) == 0.5f && a.valueAt (5000.0) == 0.5f);
+    CHECK (a.length() == 1920);
+    a.points[0].tension = 1.0f; // curva: começa devagar
+    CHECK (a.valueAt (480.0) < 0.2f && a.valueAt (480.0) > 0.0f);
+
+    // Master automatizado: silêncio no primeiro compasso, som no segundo, e o último valor
+    // fica valendo depois do fim do clip de automação
+    auto song = lynx::Song::makeDefault();
+    song.bpm = 120.0;
+    song.mode = lynx::PlayMode::song;
+    const auto bar = (std::int64_t) lynx::ppq * 4;
+    for (int b = 0; b < 3; ++b)
+        song.playlist.push_back ({ 0, 0, bar * b, bar, 0 });
+    lynx::Automation master;
+    master.target = { lynx::AutomationTargetKind::mixerVolume, 0 };
+    master.points = { { 0, 0.0f }, { bar - 1, 0.0f }, { bar, 0.8f } };
+    song.automations.push_back (master);
+    lynx::Clip ac;
+    ac.kind = lynx::ClipKind::automation;
+    ac.automation = 0;
+    ac.track = 1;
+    ac.length = bar + bar / 2;
+    song.playlist.push_back (ac);
+
+    const double sr = 48000.0;
+    auto state = lynx::RackState::build (song, nullptr, sr);
+    CHECK (state->hasAutomation && state->mixerVolumeAuto[0] == 0 && state->automationClips[0].size() == 1);
+
+    lynx::RackRenderer r;
+    r.prepare (sr, 512);
+    std::vector<float> l (512), rr (512);
+    const auto tps = lynx::ticksPerSample (song.bpm, sr);
+    float peakBar1 = 0.0f, peakBar2 = 0.0f, peakBar3 = 0.0f;
+
+    for (double tick = 0.0; tick < (double) (bar * 3); tick += 512 * tps)
+    {
+        r.process (state.get(), true, tick, 512, l.data(), rr.data());
+        auto& peak = tick < (double) bar - 512 * tps ? peakBar1 : tick < (double) bar * 2 ? peakBar2 : peakBar3;
+        for (auto v : l)
+            peak = std::max (peak, std::abs (v));
+    }
+
+    CHECK (peakBar1 < 1.0e-6f);
+    CHECK (peakBar2 > 0.05f);
+    CHECK (peakBar3 > 0.05f); // depois do clip: segue no último valor
+
+    // alvo removido: automação some das tabelas
+    song.removeChannel (0);
+    song.automations[0].target = { lynx::AutomationTargetKind::channelVolume, 0 };
+    song.removeChannel (0);
+    CHECK (song.automations[0].target.kind == lynx::AutomationTargetKind::none);
+    song.removeAutomation (0);
+    CHECK (song.automations.empty() && song.playlist.size() == 3);
+}
+
 int main (int argc, char** argv)
 {
     if (argc > 1)