Explorar o código

Merge main into feature/glitch87

Ka1-S hai 1 mes
pai
achega
919c31d2fa

+ 1 - 0
CMakeLists.txt

@@ -201,6 +201,7 @@ if(LYNX_BUILD_APP)
         src/engine/Exporter.cpp
         src/engine/StreamPrefetcher.cpp
         src/engine/ClapFormat.cpp
+        src/engine/Vst2Format.cpp
         src/engine/MidiFileIo.cpp
         src/engine/PreviewPlayer.cpp
         src/ui/MainComponent.cpp

+ 6 - 1
docs/analise/REA_rodada2.md

@@ -472,7 +472,7 @@ in event `0xA9`**:
 | version < 20.99.1 | 32 B |
 | ≥ 20.99.1 and `(flagsA9 & 2) == 0` (includes files without `0xA9`) | **60 B** |
 | ≥ 20.99.1, bit 2 on and `(flagsA9 & 8) == 0` | **80 B** |
-| ≥ 20.99.1, bits 2 and 8 on | current native size (≥ 0x58 = 88 B **[HYP]**) |
+| ≥ 20.99.1, bits 2 and 8 on | current native size: **88 B** (confirmed on a real FL 26.1.3 project with `0xA9 = 15`: 724 items, round gf92) |
 
 In the demos: without `0xA9` → 60 B; `0xA9 = 7` → 80 B (24.2…25.2); `0xA9 = 15` (25.2.99/26.1) → native,
 but both files are empty **[DATA]**. Bit 1 of `0xA9` also converts a channel field
@@ -506,6 +506,11 @@ Layout (validated on 10,576 records of 80 B):
 | 0x48 | u32 | 0 |
 | 0x4C | i32 | −1 (in native; ignored in the 80 B one) |
 | 0x50 | u32 | 0 (native only) |
+| 0x54 | u32 | 0 (native 88 B only; seen 0 or small values) |
+
+Round gf92 (real FL 26.1.3 project): +0x24 and +0x2C are the fade-in / fade-out lengths in **milliseconds**
+(923.08 = 2 beats at 130 BPM; 461.5 = 1 beat), +0x34 the clip gain (linear: 0.05 … 1.65 seen; 0 on some clips).
+LYNX imports them since then (`PlaylistItem::fadeInMs/fadeOutMs/gain` → `Clip::fadeIn/fadeOut/gain`).
 
 ### 4.3 Playlist track: event `0xEE` (70 B) + name in `0xEF` **[DECOMP+DATA]**
 

+ 130 - 0
docs/analise/REA_rodada89.md

@@ -0,0 +1,130 @@
+# Round 89: why a real FL project plays much quieter in LYNX (level audit)
+
+Branch `feature/level89`. English, clean-room: FL Studio's binaries were only read for data layouts (no code or
+pseudocode copied). Trigger: a user's real project (newer FL, third-party VST plugins, own samples) plays much
+quieter in LYNX than in FL. The project itself was not available yet (see `tmp/r89/ASK_USER.md`), so this round
+covers every plausible cause found in LYNX and on the FL-vs-LYNX scoreboard of round 80.
+
+## 1. Third-party plugins: the most likely cause for a real user project
+
+Findings in LYNX before this round **[code read]**:
+
+- **VST2 was not hosted at all.** JUCE 8 only hosts VST2 with Steinberg's VST2 SDK, which is no longer
+  distributed, so `JUCE_PLUGINHOST_VST` was off. Every VST2 in an FL project (Serum 1, Sylenth1, Spire, many
+  limiters/clippers and freebies are VST2-only) was "missing": an instrument channel played a built-in synth preset
+  instead, an effect slot was **removed** (a master limiter/maximizer gone ⇒ the whole song several dB quieter).
+- A VST2 found as VST3 (FL swaps them) got **no state** (`convertState` only carried VST3 → VST3): the plugin played
+  its default patch at its default level, and nothing told the user.
+- A plugin found but **failing to load** became a silent instrument / bypassed effect with the error dropped.
+- A Fruity Wrapper blob that could not be parsed (e.g. a wrapper version newer than 12) was dropped silently: the
+  report skipped "Fruity Wrapper" entries.
+- Hosted plugins had **no play head**: JUCE gives them no tempo/position/transport, so tempo-synced effects
+  (volume shapers, sidechain-pumping tools, LFO filters, synced delays) ran at a default 120 BPM or stopped —
+  a ducking tool stuck "down" makes a channel or the master much quieter.
+
+Changes:
+
+- `src/engine/Vst2Format.{h,cpp}`: a VST2 host of our own (`juce::AudioPluginFormat` named "VST"), written from the
+  public VST 2.4 binary interface (AEffect, dispatcher opcodes, host callback, VstEvents/VstMidiEvent, VstTimeInfo):
+  scan (also shell plugins: one DLL, several IDs, via `effShellGetNextPlugin` / `audioMasterCurrentId`), instance
+  with stereo/mono buses (extra outputs of multi-out synths are rendered and the first pair is used; extra inputs get
+  silence), MIDI in, parameters (automation from the plugin, display text), programs, latency (`initialDelay`,
+  `audioMasterIOChanged`), tail, time info from the host play head, process level (offline while exporting), editor
+  in a child HWND with `effEditIdle`. Folders: Program Files\VSTPlugins, Steinberg\VSTPlugins, Common Files\VST2,
+  Common Files\Steinberg\VST2, plus FL's own plugin folders (already in the suggested folders).
+- **State**: the VST2 instance saves and restores **FL's own wrapper layout** (§2), so an FL project's VST2 state is
+  handed to the plugin unchanged (`adoptFlPlugins` → `convertState`), with FL's rules: the chunk goes to
+  `effSetChunk` as a bank (as a program only for version −6 states without "all programs"); raw parameters between
+  `effBeginSetProgram`/`effEndSetProgram`, per program when all programs were saved; then the current program.
+- `findForeign`: VST2 by its ID (`AEffect::uniqueID` = record 0x33), same-format preference for VST2.
+- Hosted plugins (VST2, VST3, CLAP) get a play head (`TimelinePlayHead` in `PluginHost.cpp`) fed by a timeline the
+  renderer publishes per chunk (`hostTimeline()` in `core/Instruments.h`): tempo (incl. tempo automation), PPQ
+  position, bar start, time signature, playing.
+- Warnings: `adoptFlPlugins(..., withoutState)` lists plugins found in the other format; `PluginHost` records load
+  failures (`getLoadFailures`). Both go to the **Missing files** window (Plugins tab, opened automatically after
+  the import) with what LYNX did ("Its default settings: the project saved them for the other format",
+  "Silence: the plugin is installed but did not load"), to the import report, and the window's summary now reads
+  "N plugin(s) will not sound as in FL Studio …". Unreadable wrapper blobs are counted in the import report
+  ("Fruity Wrapper (plugin state not readable)").
+- Test plugin `tools/testplugin/lynx_test_vst2.c` (a VST2 sine synth with a chunk state, built with zig) and
+  `LYNX.exe --vst2test "LYNX Test Synth.dll" report.txt`: scan, import from an FL-layout VST2 state found by ID,
+  render with two saved gains (level must follow the restored state ×4) and check the plugin read the song tempo.
+
+## 2. FL's VST2 state layout per version [DECOMP, FLEngine_x64.dll of FL Studio 2026]
+
+The state probe at `0xAC4920` (with its readers `0xAC45E0`, `0xAC4700`, `0xAC4780`) reads, all little-endian:
+
+| field | present when |
+|---|---|
+| i32 version | always; accepted −9 … −1 (≥ 0 and 123456 = other/none) |
+| u8 flags | v ≤ −6 (bit0 all programs; bit3 chunk plugin; bit1 an option) |
+| i32 size (−2 ⇒ i64 size follows) | v ≤ −5 |
+| i32 (meaning not confirmed) | v = −7 and size = 0 |
+| i32 current program | v ≤ −6 |
+| i32 current program | v = −5 or −4 (inside the chunk reader, before the size) |
+| i32 size (−2 ⇒ i64) | −4 ≤ v ≤ −1 |
+| chunk[size] | size > 0 |
+| i32 n + n × f32 | v = −2, or v ≤ −5 with size 0 or −1 |
+| i32 m + names (char[25]) | if ≥ 4 bytes remain; v ≤ −6 reads one name, older versions m names |
+
+`parseFlVst2State`/`writeFlVst2State` (`core/FlWrapper`) implement this; every VST2 state in the installation's
+demo projects decodes and writes back byte-identical (test `real FLPs`), plus synthetic −9/−6/−5 cases.
+
+## 3. Level paths checked in LYNX
+
+- Live playback and export run the same graph (`ChannelRackProcessor` → `RackRenderer`) and the same master
+  `softClip` (linear up to 0.9, then a tanh knee below 1.0); the only offline differences are quality switches
+  (`offlineRendering()`: resampler, Sytrus/Ogun/EQUO oversampling) — no gain stage differs. Device output (WASAPI/
+  ASIO) gets the buffer unchanged. The preview player (browser) alone has a 0.8 gain.
+- `PluginInstrument`/`PluginEffect`: stereo main bus requested, all buses enabled; mono plugins feed both sides;
+  channel volume/pan applied after the plugin like any channel.
+
+## 4. Scoreboard clusters (round 80 FL renders vs LYNX)
+
+Whole songs were a median −1.8 dB RMS quieter in LYNX (peaks equal: both hit the master ceiling). Per-channel stems
+(renderwav solo), synthetic FL projects rendered by `FL64.exe /R /Ewav` (in `C:\Users\kauan\lynx-test\r89\{syn,vol,mix}`,
+outside the repo) and env-gated experiments in a private source copy gave these causes (dB = LYNX − FL):
+
+1. **Routes to inserts ≥ 100 without a level record were dropped** (`FlpImport.cpp`, mixer routes) **[EXEC]**.
+   LYNX gave them level 0 (an FL 11 template rule). In FL 12.5's own render test with insert 1 routed only to
+   insert 100 and its level record removed, FL plays it at full level (−19.33 dB, as the original) and LYNX played
+   silence. Fixed for files saved by FL 12 and newer; FL 11 and older keep the old rule (Synth_dfr, FL 11.1,
+   unchanged). Square a Saw – Lightning −14.7 → +3.5 dB, Oxygen −4.8 → +0.1 dB. FL's "Advanced" templates (20.5+)
+   route inserts to bus tracks 117…125 this way, so a user project started from them came out nearly silent.
+   The exact version boundary between the two rules is **not confirmed**.
+2. **Playlist audio clips 5.2 dB too quiet** (`Instruments.cpp`, clip voices) **[EXEC]**: with the clip on an empty
+   insert and no stretch, FL is a constant +5.2 dB louder at channel volumes 2500/5000/7500 and hard-left pan, i.e. FL
+   plays a clip at unity at the default channel volume (10000/12800): clip voices are now scaled by
+   1/channelGain(10000/12800) = 1.8149. Generators and samplers already matched. Ookay – Thief −3.5 → −0.4 dB,
+   Chan Gibbons −2.5 → −0.7, Mic Check −1.2 → −0.3, Vocodex demo −0.9 → +0.5, Exploding Chips −4.8 → −2.7.
+3. **Master Maximus with the v14+ "linear-phase" band split fell back to the generic limiter** (`HarmlessFx.cpp`)
+   **[EXEC on the song]**: the exact engine with its normal crossover is far closer (LollieVox −4.96 → +0.47 dB,
+   flat across bands). The linear-phase split itself is still **not decoded** (`MaximusPreset::linearPhaseSplit`).
+4. **Fruity effects saved inside Fruity Wrapper as VST2 lost their settings** (`FlpImport.cpp`, `wrappedFruityState`)
+   **[DATA]**: old FL saved its own effects as VST2 plugins; the wrapper keeps their parameters as 0…1 floats (§2).
+   Fruity Compressor's 6 controls map linearly onto the native ranges — the untouched instances in RawFL
+   (`1.0, 0.02, 0.5, 0.038, 0.05, 0`) land exactly on the native defaults (0, 10, 0, 150, 200, 0) — so the exact
+   engine now gets the saved threshold/ratio/gain (up to +15 dB makeup on RawFL's buses) /attack/release/type.
+   The lookahead flag has no VST2 parameter (off; not confirmed). Wrapped Flanger/Chorus/Fast LP stay at defaults.
+5. Unsupported generators (FLEX) and missing third-party instruments play the internal synth: unrelated level
+   (Purps −5.1 dB, 808 bass on FLEX). Not changed; now reported loudly for third-party plugins (§1).
+6. FL's time-stretch of drum loops keeps every transient when compressing time (≈ +3.3 dB vs LYNX's stretch, which
+   keeps the RMS and drops hits): algorithm difference, not fixed.
+7. Layer channels (event 0x5E children) don't trigger their children: forwarding notes gave mixed results (Asher +1.2,
+   RawFL −0.2 dB); the layer's own level/options are not confirmed; not landed.
+
+Already exact **[EXEC]**: channel volume and pan laws for generators and samplers, mixer fader law, insert pan, master
+volume/pan, stereo separation.
+
+Measurement-tool gaps (renderwav, not the app; the round 80 scoreboard understates LYNX on some songs): no
+stretched-sample provider ("keep pitch" clips play unstretched), main's `tools/WavReader.h` can't read FL's
+Ogg-in-WAV pack samples, no mp3/flac reading (RawFL, Bien Duro, DEDZII use them).
+
+With 1–3 (+ the stretch provider in the tool) the demo-song median moves from about −1.8 to about −0.6 dB. Still
+clearly quieter: Purps (FLEX), RawFL (cause 4, now fixed for the compressors; not re-measured), Exploding Chips /
+Pumping objects (cause 6 and ≈ −3 dB on their Harmor/Harmless channels, not investigated), Create a chord
+progression (−3.6) and Sytrus Essentials (−2.2), not investigated.
+
+## Where I stopped / next steps
+
+- Waiting for the user's .flp + plugin list (`tmp/r89/ASK_USER.md`).

+ 14 - 7
resources/i18n/pt-BR.txt

@@ -155,7 +155,7 @@ countries: br
 "+ add channel" = "+ adicionar canal"
 "or drop an audio file here" = "ou solte um arquivo de áudio aqui"
 "Sampler (choose file)..." = "Sampler (escolher arquivo)..."
-"Plugin (VST3/CLAP)" = "Plugin (VST3/CLAP)"
+"Plugin (VST/VST3/CLAP)" = "Plugin (VST/VST3/CLAP)"
 "Sample: {0}" = "Sample: {0}"
 "Sampler settings (pitch, envelope, reverse)..." = "Configurações do sampler (pitch, envelope, reverso)..."
 "Slice sample (slicer): one slice per key and a pattern with the loop" = "Fatiar sample (slicer): uma fatia por tecla e um pattern com o loop"
@@ -547,9 +547,9 @@ countries: br
 "Export audio" = "Exportar áudio"
 "Export..." = "Exportar..."
 "Rendering insert to audio..." = "Renderizando insert em áudio..."
-"Scanning for plugins (VST3 and CLAP)..." = "Procurando plugins (VST3 e CLAP)..."
+"Scanning for plugins (VST, VST3 and CLAP)..." = "Procurando plugins (VST, VST3 e CLAP)..."
 "(no plugins found; use \"Scan for plugins\")" = "(nenhum plugin encontrado; use \"Procurar plugins\")"
-"Scan for plugins (VST3 and CLAP)..." = "Procurar plugins (VST3 e CLAP)..."
+"Scan for plugins (VST, VST3 and CLAP)..." = "Procurar plugins (VST, VST3 e CLAP)..."
 "Plugins" = "Plugins"
 "{0} new plugin(s) found." = "{0} plugin(s) novo(s) encontrado(s)."
 
@@ -1103,7 +1103,7 @@ countries: br
 "Plugin scan finished: {0} new plugins." = "Busca de plugins concluída: {0} plugins novos."
 "Setup wizard (language, audio, plugin folders)..." = "Assistente de configuração (idioma, áudio, pastas de plugins)..."
 "Stop the plugin scan" = "Parar a busca de plugins"
-"Scan for plugins (VST3 and CLAP)" = "Procurar plugins (VST3 e CLAP)"
+"Scan for plugins (VST, VST3 and CLAP)" = "Procurar plugins (VST, VST3 e CLAP)"
 "Plugins found on this PC:" = "Plugins encontrados neste PC:"
 "Plugins not installed on this PC (or in a folder LYNX doesn't scan; Options > Setup wizard):" = "Plugins não instalados neste PC (ou numa pasta que o LYNX não varre; Opções > Assistente de configuração):"
 "Samples found in another folder than the project says (FL Studio's folders or next to the project): {0}" = "Samples encontrados em outra pasta que a indicada no projeto (pastas do FL Studio ou junto ao projeto): {0}"
@@ -1118,7 +1118,7 @@ countries: br
 "Scan finished: {0} new, {1} plugins known." = "Busca concluída: {0} novo(s), {1} plugins conhecidos."
 "{0} plugins known. Scanning runs in the background; you can close this window." = "{0} plugins conhecidos. A busca roda em segundo plano; você pode fechar esta janela."
 "Audio output" = "Saída de áudio"
-"Plugin folders (VST3 and CLAP)" = "Pastas de plugins (VST3 e CLAP)"
+"Plugin folders (VST, VST3 and CLAP)" = "Pastas de plugins (VST, VST3 e CLAP)"
 "Remove" = "Remover"
 "Suggested folders" = "Pastas sugeridas"
 "Scan now" = "Procurar agora"
@@ -1252,7 +1252,6 @@ countries: br
 "{0} file(s) were found automatically in another folder." = "{0} arquivo(s) encontrado(s) automaticamente em outra pasta."
 "{0} found, {1} still missing" = "{0} encontrado(s), {1} ainda ausente(s)"
 "{0} more found in the same folder" = "mais {0} encontrado(s) na mesma pasta"
-"{0} plugin(s) are not installed (or not scanned): LYNX put something in their place." = "{0} plugin(s) não instalado(s) (ou não escaneado(s)): o LYNX colocou algo no lugar."
 "{0} sample(s) used by {1} could not be found on this PC." = "{0} sample(s) usado(s) por {1} não foi(foram) encontrado(s) neste PC."
 "{0} still missing, {1} found" = "{0} ainda ausente(s), {1} encontrado(s)"
 "Built-in synth (a preset chosen by the channel name)" = "Synth interno (um preset escolhido pelo nome do canal)"
@@ -1291,7 +1290,7 @@ countries: br
 "Browser folders" = "Pastas do Browser"
 "Shown in the Browser's folder list; also searched for missing samples." = "Aparecem na lista de pastas do Browser; também são usadas na busca de samples ausentes."
 "Plugin folders" = "Pastas de plugins"
-"Scanned for VST3 and CLAP plugins (Options > Scan for plugins)." = "Onde os plugins VST3 e CLAP são procurados (Opções > Procurar plugins)."
+"Scanned for VST, VST3 and CLAP plugins (Options > Scan for plugins)." = "Onde os plugins VST, VST3 e CLAP são procurados (Opções > Procurar plugins)."
 "Add a folder" = "Adicionar uma pasta"
 "Add..." = "Adicionar..."
 "(none yet)" = "(nenhuma ainda)"
@@ -1567,6 +1566,14 @@ countries: br
 "(open an output device first)" = "(abra um dispositivo de saída antes)"
 "(choose)" = "(escolha)"
 
+# Round 89: VST2 hosting, plugins that won't sound as in FL Studio
+"same VST2 ID" = "mesmo ID VST2"
+"the plugin could not start" = "o plugin não conseguiu iniciar"
+"Its default settings: the project saved them for the other format (VST2/VST3)" = "Configurações padrão: o projeto as salvou para o outro formato (VST2/VST3)"
+"Silence: the plugin is installed but did not load" = "Silêncio: o plugin está instalado mas não carregou"
+"Plugins found but playing their default settings (the project saved them for the other format, VST2/VST3):" = "Plugins encontrados mas tocando com as configurações padrão (o projeto as salvou para o outro formato, VST2/VST3):"
+"Plugins installed but not loaded (silent):" = "Plugins instalados mas não carregados (em silêncio):"
+"{0} plugin(s) will not sound as in FL Studio (not installed, not loaded, or without their settings): see what LYNX did with each." = "{0} plugin(s) não vão soar como no FL Studio (não instalados, não carregados ou sem as configurações): veja o que o LYNX fez com cada um."
 # --- Round 84: Export options, New project, Clip properties, Arrangements, Plugin performance monitor, Touch keyboard
 "Source" = "Origem"
 "Time" = "Tempo"

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

@@ -76,7 +76,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/WavPackFormat.cpp src/engine/ProjectFile.cpp src/engine/PluginHost.cpp src/engine/PluginSandbox.cpp src/engine/Exporter.cpp src/engine/StreamPrefetcher.cpp src/engine/ClapFormat.cpp src/engine/MidiFileIo.cpp src/engine/PreviewPlayer.cpp
+             src/engine/SampleLibrary.cpp src/engine/WavPackFormat.cpp src/engine/ProjectFile.cpp src/engine/PluginHost.cpp src/engine/PluginSandbox.cpp src/engine/Exporter.cpp src/engine/StreamPrefetcher.cpp src/engine/ClapFormat.cpp src/engine/Vst2Format.cpp src/engine/MidiFileIo.cpp src/engine/PreviewPlayer.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/WindowOwner.cpp src/ui/ParametricEqEditor.cpp src/ui/ExportDialog.cpp src/ui/AutomationUi.cpp src/ui/ChannelSettings.cpp src/ui/BrowserComponent.cpp src/ui/Theme.cpp src/ui/Icons.cpp src/ui/I18n.cpp src/ui/EditorTools.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/core/Pdc.cpp src/core/WorkerPool.cpp src/core/TimeStretch.cpp src/core/Arpeggiator.cpp src/core/SynthPresets.cpp src/core/Slicer.cpp src/core/Templates.cpp src/core/FlWrapper.cpp src/core/FlEffects.cpp src/core/Effector.cpp src/core/VintagePhaser.cpp src/core/Reeverb2.cpp src/core/LuxeVerb.cpp src/core/IldspMath.cpp src/core/ConvolverFx.cpp src/core/EquoFx.cpp src/core/PitchShifterFl.cpp src/core/SimSynth.cpp src/core/Wasp.cpp src/core/Granulizer.cpp src/core/Drumaxx.cpp src/core/FruityFilters.cpp src/core/NewtoneFx.cpp src/core/LovePhilter.cpp src/core/DistructorFx.cpp src/core/MultibandDelayFx.cpp src/core/FrequencySplitter.cpp src/core/Slayer.cpp src/core/FlangusFastDist.cpp src/core/FruityDelayBank.cpp src/core/FruityMultiband.cpp src/core/Vocodex.cpp src/core/FruityVocoder.cpp src/core/DelphiMath.cpp src/core/MaximusFx.cpp src/core/ParametricEqFl.cpp src/core/ParametricEqLinear.cpp src/core/FruityBasicFx.cpp src/core/TransistorBass.cpp src/core/GrossBeat.cpp src/core/StereoFx.cpp src/core/FruityDelay.cpp src/core/FruityShapers.cpp src/core/ChorusFx.cpp src/core/FruityDynamics.cpp src/core/FlSamplers.cpp src/core/FlSynths.cpp src/core/FlSytrus.cpp src/core/FlGenerators.cpp src/core/PhysicalModels.cpp src/core/DrumSynthLive.cpp src/core/SytrusEngine.cpp src/core/Harmless.cpp src/core/HarmlessFx.cpp src/core/Harmor.cpp src/core/Gms.cpp src/core/Morphine.cpp src/core/Ogun.cpp src/core/Toxic.cpp src/core/ToxicFx.cpp src/core/FruitKick.cpp src/core/BassDrum.cpp src/core/MiniSynth.cpp src/core/Dx10.cpp src/core/Kepler.cpp src/core/PoiZone.cpp src/core/FlPatcher.cpp src/core/Inflate.cpp src/core/WavPack.cpp src/flp/Flp.cpp

+ 75 - 0
src/Main.cpp

@@ -306,6 +306,13 @@ public:
             return;
         }
 
+        if (args.contains ("--vst2test"))
+        {
+            const auto i = args.indexOf ("--vst2test");
+            runVst2Test (args[i + 1].unquoted(), args[i + 2].unquoted());
+            return;
+        }
+
         if (args.contains ("--wrappertest"))
         {
             const auto i = args.indexOf ("--wrappertest");
@@ -741,6 +748,74 @@ private:
         quit();
     }
 
+    // LYNX.exe --vst2test "LYNX Test Synth.dll" report.txt (tools/testplugin/lynx_test_vst2.c): LYNX's own VST2 host.
+    // Scans the DLL, imports it the way an .flp holds it (Fruity Wrapper VST2 state with a chunk, REA_rodada89 §2),
+    // renders with two saved gains (the level must follow the restored state) and checks the plugin saw the song tempo.
+    void runVst2Test (const juce::String& pluginPath, const juce::String& reportPath)
+    {
+        juce::String report;
+        bool ok = false;
+        {
+            lynx::AudioEngine offline (false);
+            auto& host = offline.getPluginHost();
+            report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
+            std::optional<juce::PluginDescription> vst2;
+            for (const auto& type : host.getKnownPlugins().getTypes())
+                if (type.pluginFormatName == "VST")
+                    vst2 = type;
+
+            auto render = [&] (float gain, float& tempoSeen, int& adopted) {
+                lynx::FlVst2State state;
+                state.flags = 8;
+                state.chunk = { 'L', 'X', 'V', '2', 0, 0, 0, 0 };
+                std::memcpy (state.chunk.data() + 4, &gain, 4);
+                auto song = lynx::Song::makeDefault();
+                song.bpm = 137.0;
+                auto& f = song.channels[4].plugin.foreign;
+                f.format = lynx::ForeignPlugin::Format::vst2;
+                f.vst2Id = (std::uint32_t) vst2->uniqueId;
+                f.name = "Some other name"; // found by the VST2 ID
+                f.state = lynx::writeFlVst2State (state);
+                song.channels[4].volume = 1.0f;
+                song.patterns[0].notes.clear();
+                song.patterns[0].notes.push_back ({ 0, 4 * lynx::ppq, 4, 69, 1.0f });
+                for (std::size_t c = 0; c < song.channels.size(); ++c)
+                    if (c != 4)
+                        song.channels[c].muted = true;
+                adopted = host.adoptFlPlugins (song);
+                offline.setSong (song);
+                const auto peak = offline.renderOffline (1.0, 48000.0);
+                offline.capturePluginStates();
+                juce::MemoryBlock saved;
+                saved.fromBase64Encoding (juce::String (offline.getSong().channels[4].plugin.state));
+                lynx::FlVst2State back;
+                tempoSeen = 0.0f;
+                if (lynx::parseFlVst2State (std::vector<std::uint8_t> ((const std::uint8_t*) saved.getData(), (const std::uint8_t*) saved.getData() + saved.getSize()), back)
+                    && back.chunk.size() >= 12)
+                    std::memcpy (&tempoSeen, back.chunk.data() + 8, 4);
+                return peak;
+            };
+
+            if (vst2)
+            {
+                report << "plugin=" << vst2->name << " id=" << vst2->uniqueId << " instrument=" << (int) vst2->isInstrument << "\n";
+                float tempoA = 0, tempoB = 0;
+                int adoptedA = 0, adoptedB = 0;
+                const auto quiet = render (0.1f, tempoA, adoptedA);
+                const auto loud = render (0.4f, tempoB, adoptedB);
+                report << "adopted=" << adoptedA << "," << adoptedB << " peak_gain_0.1=" << quiet << " peak_gain_0.4=" << loud
+                       << " tempo_seen=" << tempoB * 1000.0f << "\n";
+                ok = adoptedA == 1 && adoptedB == 1 && quiet > 0.01f && std::abs (loud / quiet - 4.0f) < 0.2f
+                     && std::abs (tempoB * 1000.0f - 137.0f) < 0.01f;
+            }
+        }
+
+        report << "result=" << (ok ? "OK" : "FAILED") << "\n";
+        juce::File (reportPath).replaceWithText (report);
+        setApplicationReturnValue (ok ? 0 : 1);
+        quit();
+    }
+
     // LYNX.exe --wrappertest plugin.vst3 report.txt: builds a VST3 state the way FL's Fruity
     // Wrapper stores it (REA_rodada5 §3.2), runs it through the import (adoptFlPlugins) and checks
     // that the plugin comes back with the changed parameter.

+ 109 - 0
src/core/FlWrapper.cpp

@@ -195,4 +195,113 @@ std::vector<int> flVst3SlotPositions (const std::vector<std::int32_t>& savedSlot
 
     return positions;
 }
+
+bool parseFlVst2State (const std::vector<std::uint8_t>& state, FlVst2State& out)
+{
+    out = {};
+    std::size_t pos = 0;
+    bool ok = true;
+    auto take = [&] (void* dst, std::size_t n) {
+        if (! ok || pos + n > state.size())
+        {
+            ok = false;
+            return;
+        }
+        std::memcpy (dst, state.data() + pos, n);
+        pos += n;
+    };
+    auto i32 = [&] {
+        std::int32_t v = 0;
+        take (&v, 4);
+        return v;
+    };
+    auto size = [&] {
+        const auto marker = i32();
+        if (marker != -2)
+            return (std::int64_t) marker;
+        std::int64_t v = 0;
+        take (&v, 8);
+        return v;
+    };
+
+    const auto v = i32();
+    if (! ok || v >= 0 || v < -9)
+        return false; // ≥ 0 (and the 123456 marker): older layouts, not decoded
+    out.version = v;
+
+    std::int64_t chunkSize = -3; // FL's "not read yet"
+    if (v <= -6)
+        take (&out.flags, 1);
+    if (v <= -5)
+        chunkSize = size();
+    if (v == -7 && chunkSize == 0)
+        i32(); // an extra count only this version writes (its meaning is not confirmed)
+    if (v <= -6)
+        out.currentProgram = i32();
+    if (v == -5 || v == -4)
+        out.currentProgram = i32();
+    if (v >= -4)
+        chunkSize = size();
+    if (! ok || chunkSize > (std::int64_t) (state.size() - pos))
+        return false;
+    if (chunkSize > 0)
+    {
+        out.chunk.assign (state.begin() + (std::ptrdiff_t) pos, state.begin() + (std::ptrdiff_t) (pos + (std::size_t) chunkSize));
+        pos += (std::size_t) chunkSize;
+    }
+
+    // raw parameters: read only when there is no chunk (or for version −2)
+    if (v == -2 || (v <= -5 && (chunkSize == 0 || chunkSize == -1)))
+    {
+        const auto n = i32();
+        if (! ok || n < 0 || (std::size_t) n > (state.size() - pos) / 4)
+            return false;
+        out.params.resize ((std::size_t) n);
+        take (out.params.data(), (std::size_t) n * 4);
+    }
+
+    // program names (optional at the end)
+    if (ok && pos + 4 <= state.size())
+    {
+        const auto m = i32();
+        const auto names = m <= 0 ? 0 : (v <= -6 ? 1 : m);
+        for (int i = 0; i < names && pos + 25 <= state.size(); ++i)
+        {
+            out.programNames.push_back (text (state.data() + pos, 25, false));
+            pos += 25;
+        }
+    }
+
+    return ok;
+}
+
+std::vector<std::uint8_t> writeFlVst2State (const FlVst2State& s)
+{
+    std::vector<std::uint8_t> out;
+    auto put = [&] (const void* p, std::size_t n) { out.insert (out.end(), (const std::uint8_t*) p, (const std::uint8_t*) p + n); };
+    auto i32 = [&] (std::int32_t v) { put (&v, 4); };
+
+    i32 (-9);
+    put (&s.flags, 1);
+    i32 (-2);
+    const auto size = (std::int64_t) s.chunk.size();
+    put (&size, 8);
+    i32 (s.currentProgram);
+    if (! s.chunk.empty())
+    {
+        put (s.chunk.data(), s.chunk.size()); // FL writes nothing after the chunk
+        return out;
+    }
+    i32 ((std::int32_t) s.params.size());
+    if (! s.params.empty())
+        put (s.params.data(), s.params.size() * 4);
+    i32 (s.programNames.empty() ? 0 : 1);
+    if (! s.programNames.empty())
+    {
+        char name[25] {};
+        std::memcpy (name, s.programNames.front().data(), std::min<std::size_t> (24, s.programNames.front().size()));
+        put (name, 25);
+    }
+    return out;
+}
 } // namespace lynx

+ 24 - 0
src/core/FlWrapper.h

@@ -4,6 +4,7 @@
 // Format described in docs/analise/REA_rodada5.md (behavioral, clean-room).
 
 #include <cstdint>
+#include <string>
 #include <vector>
 
 #include "core/Song.h"
@@ -26,4 +27,27 @@ std::vector<std::int32_t> flVst3ParamSlots (const std::vector<std::uint8_t>& sta
 // plugin's current list (getParameterInfo order) without a slot gets the next free one. Returns
 // slot → position in `paramIds` (−1 = the slot's parameter no longer exists).
 std::vector<int> flVst3SlotPositions (const std::vector<std::int32_t>& savedSlots, const std::vector<std::uint32_t>& paramIds);
+
+// VST2 state FL stores in record 0x35 (REA_rodada5 §3.1, layouts per version in REA_rodada89 §2):
+// i32 version (−9…−1); v ≤ −6: u8 flags; v ≤ −5: i32 size (−2 ⇒ i64 size follows); v = −7 with no chunk: one
+// more i32; v ≤ −6: i32 current program; (v −5/−4: i32 program; v −4…−1: size as above); chunk[size];
+// without a chunk: i32 n + n × f32 (0…1); then i32 m + program names (char[25]; one name when v ≤ −6).
+struct FlVst2State
+{
+    std::int32_t version = -9;
+    std::uint8_t flags = 0;          // bit0 = all programs saved, bit3 = the plugin uses chunks
+    std::int32_t currentProgram = 0;
+    std::vector<std::uint8_t> chunk; // effGetChunk result (FL applies it with effSetChunk as a bank)
+    std::vector<float> params;       // numParams values, or numParams × numPrograms when flags bit0
+    std::vector<std::string> programNames;
+
+    bool allPrograms() const noexcept { return (flags & 1) != 0; }
+    // FL applies the chunk as a single program only for version −6 states saved without "all programs"
+    bool chunkIsProgram() const noexcept { return version == -6 && ! allPrograms(); }
+};
+
+// False for empty states, the "nothing to restore" marker (123456), versions ≥ 0 (not decoded) and truncated data.
+bool parseFlVst2State (const std::vector<std::uint8_t>& state, FlVst2State& out);
+// Writes the current (−9) layout; parseFlVst2State reads it back.
+std::vector<std::uint8_t> writeFlVst2State (const FlVst2State& state);
 } // namespace lynx

+ 46 - 6
src/core/FlpImport.cpp

@@ -42,6 +42,7 @@
 #include "core/FlSamplers.h"
 #include "core/FlSynths.h"
 #include "core/FlWrapper.h"
+#include "core/FruityDynamics.h"
 #include "core/SynthPresets.h"
 #include "core/NewtoneFx.h"
 
@@ -561,6 +562,32 @@ std::optional<SynthSettings> synthFromFlPreset (const std::vector<std::uint8_t>&
     }
 }
 
+namespace
+{
+// Old FL saved its own Fruity effects as VST2 plugins inside Fruity Wrapper: the wrapper keeps their parameters as
+// 0…1 floats (REA_rodada89 §2). Fruity Compressor's 6 controls map linearly onto its native ranges — an untouched
+// instance's floats land exactly on the native defaults [DATA, RawFL demo] — so its native state (layout v1:
+// 6 × i32) is rebuilt; the lookahead flag has no VST2 parameter (off, not confirmed). Other effects: defaults.
+std::vector<std::uint8_t> wrappedFruityState (const ForeignPlugin& plugin)
+{
+    std::vector<std::uint8_t> native;
+    FlVst2State state;
+    if (plugin.name != "Fruity Compressor" || ! parseFlVst2State (plugin.state, state) || state.params.size() < fldyn::compressorControls)
+        return native;
+    auto put = [&native] (std::int32_t v) {
+        for (int b = 0; b < 4; ++b)
+            native.push_back ((std::uint8_t) ((std::uint32_t) v >> (8 * b)));
+    };
+    put (1);
+    for (std::size_t k = 0; k < (std::size_t) fldyn::compressorControls; ++k)
+    {
+        const auto lo = fldyn::compressorMin[k], hi = fldyn::compressorMax[k];
+        put (lo + (std::int32_t) std::lround (std::clamp (state.params[k], 0.0f, 1.0f) * (float) (hi - lo)));
+    }
+    return native;
+}
+} // namespace
+
 Song importFlp (const flp::Project& input, const FlpImportOptions& options)
 {
     // Patcher used as an instrument: the channel becomes the main generator inside it (REA_rodada14 §1)
@@ -1573,6 +1600,8 @@ Song importFlp (const flp::Project& input, const FlpImportOptions& options)
                      || (plugin == "harmless" && def.instrument == InstrumentKind::harmless)
                      || (plugin == "harmor" && def.instrument == InstrumentKind::harmor))
                 ++r.converted[c.pluginName];
+            else if (plugin == "fruity wrapper" && def.plugin.foreign.format == ForeignPlugin::Format::none)
+                ++r.unsupported["Fruity Wrapper (plugin state not readable)"]; // e.g. a wrapper version newer than 12
             else if (plugin != "fruity wrapper" && plugin != "fruity keyboard controller" && plugin != "midi out"
                      && def.instrument == InstrumentKind::synth)
                 ++r.unsupported[c.pluginName]; // (Keyboard Controller only sends notes to other channels)
@@ -1618,11 +1647,14 @@ Song importFlp (const flp::Project& input, const FlpImportOptions& options)
         {
             track.toMaster = std::find (insert.routes.begin(), insert.routes.end(), 0) != insert.routes.end();
 
-            // The level comes from 0xE1 (below). Without a record, FL templates route every insert to the
-            // send tracks at the end of the mixer (100+) at level 0; routes to regular inserts are 100%.
+            // The level comes from 0xE1 (below). Without a record a route is 100%, except in FL 11 and older,
+            // whose templates route every insert to the send tracks at the end of the mixer (100+) at level 0.
+            // FL 12+ plays an unrecorded route to insert 100+ at full level (REA_rodada89 §4.1 [EXEC]: FL's
+            // "Advanced" templates feed bus tracks 117…125 that way); the exact version boundary is not confirmed.
+            const auto oldSendTracks = project.versionNumber < 12'000'000u;
             for (auto target : insert.routes)
                 if (target > 0 && target < tracks && target != insert.index)
-                    track.sends.push_back ({ target, target >= 100 ? 0.0f : 1.0f });
+                    track.sends.push_back ({ target, target >= 100 && oldSendTracks ? 0.0f : 1.0f });
         }
     }
 
@@ -1857,7 +1889,7 @@ Song importFlp (const flp::Project& input, const FlpImportOptions& options)
 
                 // old FL saved its own Fruity effects as VST2 inside the wrapper: becomes the internal effect
                 if (wrapped && foreign.format == ForeignPlugin::Format::vst2 && effectForFlPlugin (foreign.name))
-                    made = effectFromFl (foreign.name, {}, song.bpm);
+                    made = effectFromFl (foreign.name, wrappedFruityState (foreign), song.bpm);
                 else if (wrapped)
                 {
                     // the app swaps in the installed plugin; without it, the slot is removed
@@ -1880,8 +1912,9 @@ Song importFlp (const flp::Project& input, const FlpImportOptions& options)
                                                     "Fruity Formula Controller", "Fruity LSD", "Fruity dB Meter", "Fruity Spectroman" };
                     const auto harmless = std::any_of (std::begin (silent), std::end (silent), [&] (const char* n) { return slot.plugin == n; });
 
-                    if (options.report != nullptr && slot.plugin != "Fruity Wrapper" && ! harmless)
-                        ++options.report->droppedEffects[slot.plugin];
+                    if (options.report != nullptr && ! harmless)
+                        ++options.report->droppedEffects[slot.plugin == "Fruity Wrapper" ? std::string ("Fruity Wrapper (plugin state not readable)")
+                                                                                          : slot.plugin];
                     continue;
                 }
 
@@ -2346,6 +2379,13 @@ Song importFlp (const flp::Project& input, const FlpImportOptions& options)
                         clip.offset = (std::int64_t) std::llround (item.startOffset / 1000.0 * song.bpm / 60.0 * ppq);
                 }
 
+                // clip gain and fades (FL 20.99+ records); fades are in ms, at most the clip length
+                clip.gain = item.gain;
+                const auto msToTicks = [&] (float ms)
+                { return std::clamp ((std::int64_t) std::llround (ms / 1000.0 * song.bpm / 60.0 * ppq), (std::int64_t) 0, clip.length); };
+                clip.fadeIn = msToTicks (item.fadeInMs);
+                clip.fadeOut = msToTicks (item.fadeOutMs);
+
                 clips.push_back (clip);
                 continue;
             }

+ 4 - 2
src/core/HarmlessFx.cpp

@@ -202,6 +202,7 @@ struct MaximusPreset
     std::array<Band, 4> band {};
     bool valid = false;
     bool legacyFir = false; // "Linear-phase filters (legacy mode)": windowed-sinc FIR band split (FUN_0083c200)
+    bool linearPhaseSplit = false; // the v14+ linear-phase band split option: not decoded, the normal crossover is used
     MaximusBuild build = MaximusBuild::shared;
 };
 
@@ -427,8 +428,9 @@ std::shared_ptr<const MaximusPreset> makeMaximusPreset (const std::vector<std::u
     {
         if ((d[pos + 8] & 0x40) != 0)
             m->scale = 1.0f;
-        if ((d[pos + 8] & 0x01) != 0)
-            return nullptr; // linear-phase band split through Frequency Splitter's engine_x64.dll: not decoded
+        // linear-phase band split (through Frequency Splitter's engine_x64.dll) is not decoded: the exact engine
+        // with its normal crossover is far closer than the generic limiter (REA_rodada89 §4.3: LollieVox −5.0 → +0.5 dB)
+        m->linearPhaseSplit = (d[pos + 8] & 0x01) != 0;
         pos += 9 + 20;
     }
     if (version >= 15)

+ 19 - 1
src/core/Instruments.cpp

@@ -38,6 +38,16 @@
 
 namespace lynx
 {
+namespace
+{
+// 1 / channelGain at FL's default channel volume (10000 of 12800)
+float audioClipUnity() noexcept
+{
+    static const float unity = 1.0f / channelGain (10000.0f / 12800.0f);
+    return unity;
+}
+} // namespace
+
 namespace
 {
 constexpr double twoPi = 6.283185307179586;
@@ -1606,7 +1616,9 @@ public:
         *target = {};
         target->active = true;
         target->key = key;
-        target->velocity = velocity;
+        // FL plays a Playlist audio clip at unity gain at the channel's default volume (78%): the channel volume
+        // curve is relative to that point for clips (REA_rodada89 §4.2 [EXEC]: +5.2 dB at every volume and pan)
+        target->velocity = clipMode ? velocity * audioClipUnity() : velocity;
         target->data = data;
         target->zoneGain = zone != nullptr ? zone->zone.gain : 1.0f;
 
@@ -2474,6 +2486,12 @@ std::atomic<bool> offlineRenderingFlag { false };
 void setOfflineRendering (bool on) noexcept { offlineRenderingFlag.store (on); }
 bool offlineRendering() noexcept { return offlineRenderingFlag.load(); }
 
+HostTimeline& hostTimeline() noexcept
+{
+    static HostTimeline timeline;
+    return timeline;
+}
+
 std::unique_ptr<Instrument> makeInstrument (InstrumentKind kind, std::shared_ptr<const SampleData> sample)
 {
     if (kind == InstrumentKind::controller)

+ 14 - 0
src/core/Instruments.h

@@ -1,5 +1,7 @@
 #pragma once
 
+#include <atomic>
+
 // Built-in instruments: synthesized drums and synth, and a sampler. They let the
 // DAW make sound before plugin hosting exists and play imported projects.
 // Everything has fixed capacity: noteOn/render never allocate.
@@ -82,6 +84,18 @@ struct SampleData
 void setOfflineRendering (bool on) noexcept;
 bool offlineRendering() noexcept;
 
+// Where the song is, for hosted plugins (tempo-synced effects, LFO/volume shapers, arpeggiators read the host's
+// transport): the renderer publishes it at the start of each chunk it renders.
+struct HostTimeline
+{
+    std::atomic<double> tick { 0.0 };          // song position in LYNX ticks (ppq per quarter note)
+    std::atomic<double> bpm { 120.0 };
+    std::atomic<double> sampleRate { 44100.0 };
+    std::atomic<bool> playing { false };
+    std::atomic<int> beatsPerBar { 4 };
+};
+HostTimeline& hostTimeline() noexcept;
+
 // `sample` is only used by the sampler; without a sample the sampler is silent.
 std::unique_ptr<Instrument> makeInstrument (InstrumentKind kind, std::shared_ptr<const SampleData> sample = nullptr);
 

+ 10 - 0
src/core/RackRenderer.cpp

@@ -1276,6 +1276,16 @@ void RackRenderer::processChunk (const RackState& state, bool playing, double st
     chunkStartTick = startTick;
     chunkTps = ticksPerSample (bpm, sampleRate);
 
+    // hosted plugins read the transport from here (PluginHost's play head)
+    {
+        auto& timeline = hostTimeline();
+        timeline.tick.store (startTick, std::memory_order_relaxed);
+        timeline.bpm.store (bpm, std::memory_order_relaxed);
+        timeline.sampleRate.store (sampleRate, std::memory_order_relaxed);
+        timeline.beatsPerBar.store (std::max (1, song.beatsPerBar), std::memory_order_relaxed);
+        timeline.playing.store (playing, std::memory_order_relaxed);
+    }
+
     for (int t = 0; t < tracks; ++t)
     {
         std::memset (trackBuffer (t, 0), 0, sizeof (float) * (std::size_t) numSamples);

+ 16 - 6
src/engine/AudioEngine.cpp

@@ -4,6 +4,7 @@
 #include <map>
 
 #include "engine/Text.h"
+#include "ui/I18n.h"
 
 #include "core/FlpImport.h"
 #include "core/Instruments.h"
@@ -1010,9 +1011,11 @@ bool AudioEngine::importFlpFile (const juce::File& file, juce::String& error, co
 
         juce::StringArray missing;
         juce::StringArray matched;
-        plugins.adoptFlPlugins (imported, &missing, &matched);
+        juce::StringArray withoutState;
+        plugins.adoptFlPlugins (imported, &missing, &matched, &withoutState);
         missingPlugins = missing;
         matchedPlugins = matched;
+        pluginsWithoutState = withoutState;
         missingPluginDetails.clear();
         for (const auto& name : missing)
         {
@@ -1027,16 +1030,23 @@ bool AudioEngine::importFlpFile (const juce::File& file, juce::String& error, co
                 }
             missingPluginDetails.push_back (std::move (m));
         }
+        // found, but the project's settings are in the other format (VST2 <-> VST3): they play their default sound
+        for (const auto& line : withoutState)
+            missingPluginDetails.push_back ({ line.toStdString(), {}, TR_NOOP ("Its default settings: the project saved them for the other format (VST2/VST3)") });
 
+        plugins.clearLoadFailures();
         if (asEdit)
-        {
             editSong ([&imported] (Song& s) { s = std::move (imported); });
-            return true;
+        else
+        {
+            stop();
+            rewind();
+            setSong (std::move (imported));
         }
 
-        stop();
-        rewind();
-        setSong (std::move (imported));
+        // installed but failed to load (the rack was just built): silence / bypass, said as loudly as a missing one
+        for (const auto& line : plugins.getLoadFailures())
+            missingPluginDetails.push_back ({ line.toStdString(), {}, TR_NOOP ("Silence: the plugin is installed but did not load") });
         return true;
     }
     catch (const flp::Error& e)

+ 3 - 1
src/engine/AudioEngine.h

@@ -53,6 +53,8 @@ public:
     const juce::StringArray& getMissingPlugins() const noexcept { return missingPlugins; }
     // "plugin → file (how it was found)" for the plugins of the last imported .flp
     const juce::StringArray& getMatchedPlugins() const noexcept { return matchedPlugins; }
+    // plugins found whose saved settings could not be carried over (VST2 <-> VST3): "name (format)"
+    const juce::StringArray& getPluginsWithoutState() const noexcept { return pluginsWithoutState; }
     // What the last imported .flp converted, approximated or left out.
     const FlpImportReport& getImportReport() const noexcept { return importReport; }
     // The last imported .flp's plugins that were not found, with what uses them and what LYNX put in their place.
@@ -346,7 +348,7 @@ private:
     int takeLatency = 0;                           // input + output, in samples
     MeterBank meters;
     PluginHost plugins;
-    juce::StringArray missingPlugins, matchedPlugins;
+    juce::StringArray missingPlugins, matchedPlugins, pluginsWithoutState;
     FlpImportReport importReport;
     std::vector<MissingPlugin> missingPluginDetails;
     RenderStats lastRenderStats;

+ 2 - 0
src/engine/ClapFormat.cpp

@@ -1,4 +1,5 @@
 #include "engine/ClapFormat.h"
+#include "engine/Vst2Format.h"
 
 #include <array>
 #include <atomic>
@@ -922,5 +923,6 @@ void addPluginFormats (juce::AudioPluginFormatManager& manager)
 {
     manager.addDefaultFormats();
     manager.addFormat (new ClapPluginFormat());
+    manager.addFormat (new Vst2PluginFormat());
 }
 } // namespace lynx

+ 1 - 1
src/engine/ClapFormat.h

@@ -31,6 +31,6 @@ private:
                                PluginCreationCallback) override;
 };
 
-// Adds the LYNX formats (JUCE's + CLAP) to a manager.
+// Adds the LYNX formats (JUCE's VST3 + CLAP + our VST2 host) to a manager.
 void addPluginFormats (juce::AudioPluginFormatManager& manager);
 } // namespace lynx

+ 94 - 5
src/engine/PluginHost.cpp

@@ -5,6 +5,7 @@
 #include "core/FlWrapper.h"
 
 #include "engine/ClapFormat.h"
+#include "engine/Vst2Format.h"
 #include "engine/PluginSandbox.h"
 #include "engine/FlStudio.h"
 #include "ui/I18n.h"
@@ -42,6 +43,35 @@ void setPluginParameter (juce::AudioPluginInstance& plugin, int index, float val
             p->setValue (value);
 }
 
+// The song's transport as hosted plugins see it (tempo, position, play state), from the renderer's timeline.
+class TimelinePlayHead final : public juce::AudioPlayHead
+{
+public:
+    juce::Optional<PositionInfo> getPosition() const override
+    {
+        const auto& t = hostTimeline();
+        const auto bpm = t.bpm.load (std::memory_order_relaxed);
+        const auto rate = t.sampleRate.load (std::memory_order_relaxed);
+        const auto quarters = t.tick.load (std::memory_order_relaxed) / (double) ppq;
+        const auto beatsPerBar = juce::jmax (1, t.beatsPerBar.load (std::memory_order_relaxed));
+        PositionInfo info;
+        info.setBpm (bpm);
+        info.setTimeSignature (TimeSignature { beatsPerBar, 4 });
+        info.setPpqPosition (quarters);
+        info.setPpqPositionOfLastBarStart (std::floor (quarters / beatsPerBar) * beatsPerBar);
+        info.setTimeInSeconds (quarters * 60.0 / juce::jmax (1.0, bpm));
+        info.setTimeInSamples ((juce::int64) std::llround (quarters * 60.0 / juce::jmax (1.0, bpm) * rate));
+        info.setIsPlaying (t.playing.load (std::memory_order_relaxed));
+        return info;
+    }
+};
+
+juce::AudioPlayHead& timelinePlayHead()
+{
+    static TimelinePlayHead head;
+    return head;
+}
+
 int bufferChannels (const juce::AudioPluginInstance& plugin)
 {
     return juce::jmax (2, plugin.getTotalNumInputChannels(), plugin.getTotalNumOutputChannels());
@@ -56,6 +86,7 @@ PluginInstrument::PluginInstrument (std::unique_ptr<juce::AudioPluginInstance> i
 {
     buffer.setSize (bufferChannels (*plugin), blockSize);
     midi.ensureSize (8192); // the audio thread only adds events within this capacity
+    plugin->setPlayHead (&timelinePlayHead());
 }
 
 PluginInstrument::~PluginInstrument()
@@ -114,6 +145,7 @@ PluginEffect::PluginEffect (std::unique_ptr<juce::AudioPluginInstance> instance,
       blockSize (maxBlockSize)
 {
     buffer.setSize (bufferChannels (*plugin), blockSize);
+    plugin->setPlayHead (&timelinePlayHead());
 }
 
 PluginEffect::~PluginEffect()
@@ -216,6 +248,9 @@ juce::FileSearchPath PluginHost::defaultSearchPath()
     juce::FileSearchPath paths;
     // Same locations JUCE/Steinberg use by default on Windows.
     paths.add (juce::File::getSpecialLocation (juce::File::globalApplicationsDirectory).getChildFile ("Common Files/VST3"));
+    // VST2 (Vst2Format): the usual folders installers use
+    for (const auto* sub : { "VSTPlugins", "Steinberg/VSTPlugins", "Common Files/VST2", "Common Files/Steinberg/VST2" })
+        paths.add (juce::File::getSpecialLocation (juce::File::globalApplicationsDirectory).getChildFile (sub));
     paths.add (juce::File::getSpecialLocation (juce::File::globalApplicationsDirectory).getChildFile ("Common Files/CLAP"));
     paths.add (juce::File::getSpecialLocation (juce::File::windowsLocalAppData).getChildFile ("Programs/Common/CLAP"));
     paths.add (settingsFolder().getChildFile ("Plugins"));
@@ -521,6 +556,9 @@ std::optional<juce::PluginDescription> PluginHost::findForeign (const ForeignPlu
         if (plugin.format == ForeignPlugin::Format::vst3 && plugin.hasClassId && d.pluginFormatName == "VST3"
             && (d.deprecatedUid == vst3Hash (plugin.classId) || d.uniqueId == vst3NormalisedHash (plugin.classId)))
             return found (d, TR_NOOP ("same VST3 class ID"));
+        if (plugin.format == ForeignPlugin::Format::vst2 && plugin.vst2Id != 0 && d.pluginFormatName == Vst2PluginFormat::formatName
+            && (juce::uint32) d.uniqueId == plugin.vst2Id)
+            return found (d, TR_NOOP ("same VST2 ID"));
         if (plugin.format == ForeignPlugin::Format::clap && ! plugin.clapId.empty() && d.pluginFormatName == ClapPluginFormat::formatName
             && d.uniqueId == juce::String::fromUTF8 (plugin.clapId.c_str()).hashCode())
             return found (d, TR_NOOP ("same CLAP id"));
@@ -547,6 +585,7 @@ std::optional<juce::PluginDescription> PluginHost::findForeign (const ForeignPlu
     // a plugin installed in several formats: prefer the one FL used (VST3 → VST3, CLAP → CLAP), whose state carries over
     const auto sameFormat = plugin.format == ForeignPlugin::Format::vst3   ? juce::String ("VST3")
                             : plugin.format == ForeignPlugin::Format::clap ? juce::String (ClapPluginFormat::formatName)
+                            : plugin.format == ForeignPlugin::Format::vst2 ? juce::String (Vst2PluginFormat::formatName)
                                                                            : juce::String();
     std::optional<juce::PluginDescription> byName;
     for (const auto& d : types)
@@ -579,7 +618,9 @@ juce::StringArray PluginHost::filesToScanFor (const std::vector<FlpPluginUse>& u
     if (needed.empty())
         return files;
 
-    auto hosted = [] (const juce::String& path) { return path.endsWithIgnoreCase (".vst3") || path.endsWithIgnoreCase (".clap"); };
+    auto hosted = [] (const juce::String& path) {
+        return path.endsWithIgnoreCase (".vst3") || path.endsWithIgnoreCase (".clap") || path.endsWithIgnoreCase (".dll");
+    };
     auto addExisting = [&] (const std::string& path) {
         const auto p = juce::String::fromUTF8 (path.c_str()).replaceCharacter ('/', '\\');
         if (p.isNotEmpty() && juce::File::isAbsolutePath (p) && hosted (p) && juce::File (p).exists())
@@ -608,7 +649,7 @@ juce::StringArray PluginHost::filesToScanFor (const std::vector<FlpPluginUse>& u
     return worth;
 }
 
-int PluginHost::adoptFlPlugins (Song& song, juce::StringArray* missing, juce::StringArray* matched)
+int PluginHost::adoptFlPlugins (Song& song, juce::StringArray* missing, juce::StringArray* matched, juce::StringArray* withoutState)
 {
     int found = 0;
 
@@ -618,8 +659,16 @@ int PluginHost::adoptFlPlugins (Song& song, juce::StringArray* missing, juce::St
         if (f.format == ForeignPlugin::Format::clap && d.pluginFormatName == "CLAP")
             return f.state.size() > 4 ? juce::MemoryBlock (f.state.data() + 4, f.state.size() - 4).toBase64Encoding().toStdString() : std::string {};
 
+        // VST2: LYNX's VST2 host keeps FL's own state layout (REA_rodada89 §2)
+        if (f.format == ForeignPlugin::Format::vst2 && d.pluginFormatName == Vst2PluginFormat::formatName)
+        {
+            FlVst2State check;
+            return parseFlVst2State (f.state, check) ? juce::MemoryBlock (f.state.data(), f.state.size()).toBase64Encoding().toStdString()
+                                                     : std::string {};
+        }
+
         if (f.format != ForeignPlugin::Format::vst3 || d.pluginFormatName != "VST3")
-            return {}; // VST2 -> VST3: different state format; plugin at defaults
+            return {}; // VST2 <-> VST3: different state formats; plugin at defaults
 
         std::vector<std::uint8_t> component, controller;
 
@@ -655,6 +704,9 @@ int PluginHost::adoptFlPlugins (Song& song, juce::StringArray* missing, juce::St
         ref.id = d->createIdentifierString().toStdString();
         ref.name = d->name.toStdString();
         ref.state = convertState (ref.foreign, *d);
+        // found, but the project's settings could not be carried over: it plays its default sound
+        if (ref.state.empty() && ! ref.foreign.state.empty() && withoutState != nullptr)
+            withoutState->addIfNotAlreadyThere (juce::String::fromUTF8 (ref.foreign.name.c_str()) + " (" + d->pluginFormatName + ")");
         ref.foreign = {};
         ++found;
         return true;
@@ -766,19 +818,56 @@ std::unique_ptr<juce::AudioPluginInstance> PluginHost::instantiate (const Plugin
     return instance;
 }
 
+namespace
+{
+juce::String failureLine (const PluginRef& ref, const juce::String& why)
+{
+    const auto name = juce::String::fromUTF8 (ref.name.c_str());
+    if (why.isEmpty())
+        return name + ": " + tr ("the plugin could not start");
+    return why.startsWith (name) ? why : name + ": " + why;
+}
+} // namespace
+
+juce::StringArray PluginHost::getLoadFailures() const
+{
+    const std::scoped_lock lock (failuresLock);
+    return loadFailures;
+}
+
+void PluginHost::clearLoadFailures()
+{
+    const std::scoped_lock lock (failuresLock);
+    loadFailures.clear();
+}
+
 std::shared_ptr<Instrument> PluginHost::makeInstrument (const PluginRef& ref, double sampleRate, juce::String* error)
 {
-    if (auto instance = instantiate (ref, sampleRate, error))
+    juce::String why;
+    if (auto instance = instantiate (ref, sampleRate, &why))
         return std::make_shared<PluginInstrument> (std::move (instance), maxBlockSize);
 
+    {
+        const std::scoped_lock lock (failuresLock);
+        loadFailures.addIfNotAlreadyThere (failureLine (ref, why));
+    }
+    if (error != nullptr)
+        *error = why;
     return nullptr;
 }
 
 std::shared_ptr<Effect> PluginHost::makeEffect (const PluginRef& ref, double sampleRate, juce::String* error)
 {
-    if (auto instance = instantiate (ref, sampleRate, error))
+    juce::String why;
+    if (auto instance = instantiate (ref, sampleRate, &why))
         return std::make_shared<PluginEffect> (std::move (instance), maxBlockSize);
 
+    {
+        const std::scoped_lock lock (failuresLock);
+        loadFailures.addIfNotAlreadyThere (failureLine (ref, why));
+    }
+    if (error != nullptr)
+        *error = why;
     return nullptr;
 }
 

+ 11 - 2
src/engine/PluginHost.h

@@ -135,16 +135,23 @@ public:
 
     // Third-party plugins from an imported .flp (ForeignPlugin): finds the same plugin among the
     // scanned ones (VST3 by class ID, CLAP by id; then the file FL Studio's plugin database lists for it; then
-    // by name as a fallback, also for the VST2s LYNX doesn't host) and converts the VST3 state to JUCE's format.
+    // VST2 by its ID; by name as a fallback) and carries the state over (VST3: JUCE's format; VST2: FL's layout as is).
     // Matched channels become plugin channels; unmatched effect slots are dropped. Returns how many were matched.
     // `matched` gets one "name → file (how)" line per plugin found.
-    int adoptFlPlugins (Song& song, juce::StringArray* missing = nullptr, juce::StringArray* matched = nullptr);
+    // `withoutState` gets the plugins found whose saved settings couldn't be carried over (VST2 <-> VST3 swap).
+    int adoptFlPlugins (Song& song, juce::StringArray* missing = nullptr, juce::StringArray* matched = nullptr,
+                        juce::StringArray* withoutState = nullptr);
     std::optional<juce::PluginDescription> findForeign (const ForeignPlugin& plugin, bool instrument, juce::String* how = nullptr);
 
     // Plugin files worth a targeted scan so a project's plugins can be found: for each plugin not known yet, the
     // file FL's database or the project names, and same-named VST3/CLAP files in pluginFolders(). Cheap (no loading).
     juce::StringArray filesToScanFor (const std::vector<FlpPluginUse>& uses);
 
+    // Plugins of the song that are known but failed to load ("name: reason"; they play silence / are bypassed).
+    // Kept until clearLoadFailures (a new project). Any thread.
+    juce::StringArray getLoadFailures() const;
+    void clearLoadFailures();
+
     std::shared_ptr<Instrument> makeInstrument (const PluginRef& ref, double sampleRate, juce::String* error = nullptr);
     std::shared_ptr<Effect> makeEffect (const PluginRef& ref, double sampleRate, juce::String* error = nullptr);
 
@@ -169,6 +176,8 @@ private:
 
     class BackgroundScan;
     std::unique_ptr<BackgroundScan> background;
+    mutable std::mutex failuresLock;
+    juce::StringArray loadFailures;
     mutable std::mutex stateLock;
     ScanState state;
 };

+ 818 - 0
src/engine/Vst2Format.cpp

@@ -0,0 +1,818 @@
+#include "engine/Vst2Format.h"
+
+#include <array>
+#include <atomic>
+#include <cstring>
+#include <map>
+#include <mutex>
+
+#include <juce_gui_extra/juce_gui_extra.h>
+
+#include "core/FlWrapper.h"
+
+#if JUCE_WINDOWS
+ #include <windows.h>
+#endif
+
+namespace lynx
+{
+namespace
+{
+// --- the VST 2.4 binary interface (our own declarations of the public ABI) ---------------------------
+namespace abi
+{
+struct Effect;
+using HostCallback = std::intptr_t (*) (Effect*, std::int32_t opcode, std::int32_t index, std::intptr_t value, void* ptr, float opt);
+using Dispatcher = std::intptr_t (*) (Effect*, std::int32_t opcode, std::int32_t index, std::intptr_t value, void* ptr, float opt);
+using Process = void (*) (Effect*, float** inputs, float** outputs, std::int32_t frames);
+using SetParameter = void (*) (Effect*, std::int32_t index, float value);
+using GetParameter = float (*) (Effect*, std::int32_t index);
+using Entry = Effect* (*) (HostCallback);
+
+struct Effect
+{
+    std::int32_t magic;
+    Dispatcher dispatcher;
+    Process process; // accumulating (deprecated)
+    SetParameter setParameter;
+    GetParameter getParameter;
+    std::int32_t numPrograms, numParams, numInputs, numOutputs;
+    std::int32_t flags;
+    std::intptr_t hostReserved1, hostReserved2;
+    std::int32_t initialDelay;
+    std::int32_t realQualities, offQualities;
+    float ioRatio;
+    void* object;
+    void* user;
+    std::int32_t uniqueId, version;
+    Process processReplacing;
+    void* processDoubleReplacing;
+    char future[56];
+};
+
+constexpr std::int32_t magic = 0x56737450; // 'VstP'
+
+// Effect::flags
+constexpr std::int32_t hasEditor = 1 << 0, canReplacing = 1 << 4, programChunks = 1 << 5, isSynth = 1 << 8;
+
+// dispatcher opcodes
+enum : std::int32_t
+{
+    open = 0, close = 1, setProgram = 2, getProgram = 3, getProgramName = 5, getParamLabel = 6, getParamDisplay = 7,
+    getParamName = 8, setSampleRate = 10, setBlockSize = 11, mainsChanged = 12, editGetRect = 13, editOpen = 14,
+    editClose = 15, editIdle = 19, getChunk = 23, setChunk = 24, processEvents = 25, getProgramNameIndexed = 29,
+    getPlugCategory = 35, getEffectName = 45, getVendorString = 47, getProductString = 48, getVendorVersion = 49,
+    canDo = 51, getTailSize = 52, getVstVersion = 58, beginSetProgram = 67, endSetProgram = 68,
+    shellGetNextPlugin = 70, startProcess = 71, stopProcess = 72
+};
+
+// host callback opcodes
+enum : std::int32_t
+{
+    automate = 0, version = 1, currentId = 2, idle = 3, wantMidi = 6, getTime = 7, hostProcessEvents = 8,
+    ioChanged = 13, sizeWindow = 15, getSampleRate = 16, getBlockSize = 17, getInputLatency = 18,
+    getOutputLatency = 19, getCurrentProcessLevel = 23, getAutomationState = 24, hostGetVendorString = 32,
+    hostGetProductString = 33, hostGetVendorVersion = 34, hostCanDo = 37, getLanguage = 38, getDirectory = 41,
+    updateDisplay = 42, beginEdit = 43, endEdit = 44
+};
+
+constexpr std::int32_t categorySynth = 2, categoryShell = 10;
+
+struct MidiEvent // 32 bytes
+{
+    std::int32_t type = 1; // MIDI
+    std::int32_t byteSize = 32;
+    std::int32_t deltaFrames = 0;
+    std::int32_t flags = 1; // real-time
+    std::int32_t noteLength = 0, noteOffset = 0;
+    char data[4] {};
+    char detune = 0, noteOffVelocity = 0, reserved1 = 0, reserved2 = 0;
+};
+static_assert (sizeof (MidiEvent) == 32);
+
+struct Rect
+{
+    std::int16_t top, left, bottom, right;
+};
+
+struct TimeInfo
+{
+    double samplePos, sampleRate, nanoSeconds, ppqPos, tempo, barStartPos, cycleStartPos, cycleEndPos;
+    std::int32_t timeSigNumerator, timeSigDenominator, smpteOffset, smpteFrameRate, samplesToNextClock, flags;
+};
+constexpr std::int32_t transportChanged = 1, transportPlaying = 2, ppqValid = 1 << 9, tempoValid = 1 << 10,
+                       barsValid = 1 << 11, timeSigValid = 1 << 13;
+} // namespace abi
+
+// --- module loading ------------------------------------------------------------------------------------
+// A DLL is loaded once and stays loaded (some plugins crash when unloaded and loaded again).
+abi::Entry entryOf (const juce::String& path)
+{
+   #if JUCE_WINDOWS
+    static std::mutex mutex;
+    static std::map<juce::String, HMODULE> modules;
+    const std::lock_guard<std::mutex> lock (mutex);
+    auto& module = modules[path];
+    if (module == nullptr)
+        module = LoadLibraryW (path.toWideCharPointer());
+    if (module == nullptr)
+        return nullptr;
+    auto entry = (abi::Entry) (void*) GetProcAddress (module, "VSTPluginMain");
+    if (entry == nullptr)
+        entry = (abi::Entry) (void*) GetProcAddress (module, "main");
+    return entry;
+   #else
+    juce::ignoreUnused (path);
+    return nullptr;
+   #endif
+}
+
+class Vst2Instance;
+
+// Which instance an Effect belongs to (hostReserved1), and the shell sub-plugin being created (the plugin
+// asks for it through the callback before its Effect exists).
+std::mutex creationLock;
+std::atomic<std::int32_t> shellIdToCreate { 0 };
+
+std::intptr_t hostCallback (abi::Effect* effect, std::int32_t opcode, std::int32_t index, std::intptr_t value, void* ptr, float opt);
+
+juce::String dispatcherText (abi::Effect* e, std::int32_t opcode, std::int32_t index = 0)
+{
+    char text[512] {};
+    e->dispatcher (e, opcode, index, 0, text, 0.0f);
+    text[sizeof (text) - 1] = 0;
+    return juce::String::fromUTF8 (text).trim();
+}
+
+// Opens one plugin of the file (the shell sub-plugin `shellId`, or the plain plugin with 0); nullptr if it isn't a VST2.
+abi::Effect* openEffect (const juce::String& path, std::int32_t shellId)
+{
+    const auto entry = entryOf (path);
+    if (entry == nullptr)
+        return nullptr;
+    const std::lock_guard<std::mutex> lock (creationLock);
+    shellIdToCreate = shellId;
+    abi::Effect* effect = nullptr;
+    effect = entry (hostCallback);
+    shellIdToCreate = 0;
+    if (effect == nullptr || effect->magic != abi::magic || effect->dispatcher == nullptr)
+        return nullptr;
+    effect->hostReserved1 = 0;
+    effect->dispatcher (effect, abi::open, 0, 0, nullptr, 0.0f);
+    return effect;
+}
+
+void closeEffect (abi::Effect* effect)
+{
+    if (effect != nullptr)
+        effect->dispatcher (effect, abi::close, 0, 0, nullptr, 0.0f);
+}
+
+bool effectIsInstrument (abi::Effect* e)
+{
+    return (e->flags & abi::isSynth) != 0 || e->dispatcher (e, abi::getPlugCategory, 0, 0, nullptr, 0.0f) == abi::categorySynth;
+}
+
+juce::PluginDescription describe (abi::Effect* e, const juce::File& file, const juce::String& shellName, bool shared)
+{
+    juce::PluginDescription d;
+    auto name = shellName.isNotEmpty() ? shellName : dispatcherText (e, abi::getEffectName);
+    if (name.isEmpty())
+        name = dispatcherText (e, abi::getProductString);
+    if (name.isEmpty())
+        name = file.getFileNameWithoutExtension();
+    d.name = name;
+    d.descriptiveName = name;
+    d.pluginFormatName = Vst2PluginFormat::formatName;
+    d.manufacturerName = dispatcherText (e, abi::getVendorString);
+    d.version = juce::String ((int) e->dispatcher (e, abi::getVendorVersion, 0, 0, nullptr, 0.0f));
+    d.fileOrIdentifier = file.getFullPathName();
+    d.lastFileModTime = file.getLastModificationTime();
+    d.lastInfoUpdateTime = juce::Time::getCurrentTime();
+    d.uniqueId = d.deprecatedUid = e->uniqueId;
+    d.isInstrument = effectIsInstrument (e);
+    d.category = d.isInstrument ? "Synth" : "Effect";
+    d.numInputChannels = e->numInputs;
+    d.numOutputChannels = e->numOutputs;
+    d.hasSharedContainer = shared;
+    return d;
+}
+
+// --- parameter -------------------------------------------------------------------------------------------
+class Vst2Parameter final : public juce::HostedAudioProcessorParameter
+{
+public:
+    Vst2Parameter (abi::Effect* e, int i, const juce::String& n, const juce::String& l)
+        : effect (e), index (i), name (n), label (l)
+    {
+        value.store (e->getParameter != nullptr ? e->getParameter (e, i) : 0.0f);
+        defaultValue = value.load();
+    }
+
+    juce::String getParameterID() const override { return juce::String (index); }
+    float getValue() const override { return value.load(); }
+    void setValue (float v) override
+    {
+        value.store (v);
+        if (effect->setParameter != nullptr)
+            effect->setParameter (effect, index, v);
+    }
+    float getDefaultValue() const override { return defaultValue; }
+    juce::String getName (int maximumLength) const override { return name.substring (0, maximumLength); }
+    juce::String getLabel() const override { return label; }
+    float getValueForText (const juce::String& text) const override { return juce::jlimit (0.0f, 1.0f, text.getFloatValue()); }
+    juce::String getText (float v, int length) const override
+    {
+        // the plugin formats its current value only: ask it on the UI thread when it's the current one
+        if (juce::MessageManager::existsAndIsCurrentThread() && std::abs (v - value.load()) < 1.0e-6f)
+        {
+            const auto text = dispatcherText (effect, abi::getParamDisplay, index);
+            const auto unit = dispatcherText (effect, abi::getParamLabel, index);
+            if (text.isNotEmpty())
+                return (unit.isNotEmpty() ? text + " " + unit : text).substring (0, length);
+        }
+        return juce::String (v, 3).substring (0, length);
+    }
+
+    void setFromPlugin (float v) noexcept { value.store (v); }
+    void refresh() noexcept
+    {
+        if (effect->getParameter != nullptr)
+            value.store (effect->getParameter (effect, index));
+    }
+
+private:
+    abi::Effect* effect;
+    const int index;
+    const juce::String name, label;
+    std::atomic<float> value { 0.0f };
+    float defaultValue = 0.0f;
+};
+
+// --- instance ----------------------------------------------------------------------------------------------
+class Vst2Instance final : public juce::AudioPluginInstance
+{
+public:
+    Vst2Instance (abi::Effect* e, const juce::PluginDescription& d)
+        : AudioPluginInstance (busesFor (*e, d.isInstrument)),
+          effect (e),
+          description (d)
+    {
+        effect->hostReserved1 = (std::intptr_t) this;
+        for (int i = 0; i < effect->numParams; ++i)
+        {
+            auto parameter = std::make_unique<Vst2Parameter> (effect, i, dispatcherText (effect, abi::getParamName, i),
+                                                              dispatcherText (effect, abi::getParamLabel, i));
+            parameters.push_back (parameter.get());
+            addHostedParameter (std::move (parameter));
+        }
+        inputs.resize ((std::size_t) juce::jmax (0, effect->numInputs));
+        outputs.resize ((std::size_t) juce::jmax (0, effect->numOutputs));
+        events.resize (sizeof (std::int32_t) * 2 + sizeof (void*) * (maxEvents + 2));
+        midiEvents.resize (maxEvents);
+        timeInfo = {};
+    }
+
+    ~Vst2Instance() override
+    {
+        *alive = false;
+        releaseResources();
+        effect->dispatcher (effect, abi::close, 0, 0, nullptr, 0.0f);
+    }
+
+    // --- AudioProcessor ---------------------------------------------------------------------------------------
+    const juce::String getName() const override { return description.name; }
+    void fillInPluginDescription (juce::PluginDescription& d) const override { d = description; }
+
+    void prepareToPlay (double sampleRate, int blockSize) override
+    {
+        releaseResources();
+        maxBlock = juce::jmax (1, blockSize);
+        rate = sampleRate;
+        effect->dispatcher (effect, abi::setSampleRate, 0, 0, nullptr, (float) sampleRate);
+        effect->dispatcher (effect, abi::setBlockSize, 0, maxBlock, nullptr, 0.0f);
+        scratch.setSize (juce::jmax (1, effect->numOutputs + effect->numInputs), maxBlock);
+        effect->dispatcher (effect, abi::mainsChanged, 0, 1, nullptr, 0.0f);
+        effect->dispatcher (effect, abi::startProcess, 0, 0, nullptr, 0.0f);
+        active = true;
+        setLatencySamples (effect->initialDelay);
+    }
+
+    void releaseResources() override
+    {
+        if (! active)
+            return;
+        effect->dispatcher (effect, abi::stopProcess, 0, 0, nullptr, 0.0f);
+        effect->dispatcher (effect, abi::mainsChanged, 0, 0, nullptr, 0.0f);
+        active = false;
+    }
+
+    void processBlock (juce::AudioBuffer<float>& buffer, juce::MidiBuffer& midi) override
+    {
+        const auto n = buffer.getNumSamples();
+        audioThread.store (std::this_thread::get_id());
+
+        if (! active || n > maxBlock)
+        {
+            buffer.clear();
+            return;
+        }
+
+        updateTimeInfo (n);
+
+        // MIDI → VstEvents (preallocated; extra events are dropped)
+        int count = 0;
+        for (const auto m : midi)
+        {
+            if (count >= maxEvents)
+                break;
+            const auto& message = m.getMessage();
+            if (message.getRawDataSize() > 3 || message.isSysEx())
+                continue;
+            auto& e = midiEvents[(std::size_t) count];
+            e = {};
+            e.deltaFrames = juce::jlimit (0, n - 1, m.samplePosition);
+            std::memcpy (e.data, message.getRawData(), (std::size_t) message.getRawDataSize());
+            ++count;
+        }
+        if (count > 0)
+        {
+            auto* header = events.data();
+            const std::int32_t numEvents = count;
+            std::memcpy (header, &numEvents, 4);
+            std::memset (header + 4, 0, sizeof (void*) == 8 ? 12 : 4);
+            auto** list = reinterpret_cast<abi::MidiEvent**> (header + (sizeof (void*) == 8 ? 16 : 8));
+            for (int i = 0; i < count; ++i)
+                list[i] = &midiEvents[(std::size_t) i];
+            effect->dispatcher (effect, abi::processEvents, 0, 0, header, 0.0f);
+        }
+
+        // inputs: the buffer's channels (extra ones, e.g. a sidechain pair, get silence); outputs: scratch
+        const auto numIn = effect->numInputs, numOut = effect->numOutputs;
+        for (int ch = 0; ch < numIn; ++ch)
+        {
+            auto* in = scratch.getWritePointer (numOut + ch);
+            if (ch < buffer.getNumChannels() && ch < getTotalNumInputChannels())
+                juce::FloatVectorOperations::copy (in, buffer.getReadPointer (ch), n);
+            else
+                juce::FloatVectorOperations::clear (in, n);
+            inputs[(std::size_t) ch] = in;
+        }
+        for (int ch = 0; ch < numOut; ++ch)
+        {
+            outputs[(std::size_t) ch] = scratch.getWritePointer (ch);
+            juce::FloatVectorOperations::clear (outputs[(std::size_t) ch], n);
+        }
+
+        if ((effect->flags & abi::canReplacing) != 0 && effect->processReplacing != nullptr)
+            effect->processReplacing (effect, inputs.data(), outputs.data(), n);
+        else if (effect->process != nullptr)
+            effect->process (effect, inputs.data(), outputs.data(), n);
+
+        // main output: the first one or two outputs (a mono plugin feeds both sides)
+        for (int ch = 0; ch < buffer.getNumChannels(); ++ch)
+        {
+            if (numOut > 0)
+                buffer.copyFrom (ch, 0, scratch, juce::jmin (ch, juce::jmin (numOut, 2) - 1), 0, n);
+            else
+                buffer.clear (ch, 0, n);
+        }
+    }
+
+    double getTailLengthSeconds() const override
+    {
+        const auto samples = effect->dispatcher (effect, abi::getTailSize, 0, 0, nullptr, 0.0f);
+        return samples > 1 && rate > 0.0 ? (double) samples / rate : 0.0;
+    }
+    bool acceptsMidi() const override { return description.isInstrument; }
+    bool producesMidi() const override { return false; }
+
+    juce::AudioProcessorEditor* createEditor() override;
+    bool hasEditor() const override { return (effect->flags & abi::hasEditor) != 0; }
+
+    int getNumPrograms() override { return juce::jmax (1, effect->numPrograms); }
+    int getCurrentProgram() override { return (int) effect->dispatcher (effect, abi::getProgram, 0, 0, nullptr, 0.0f); }
+    void setCurrentProgram (int index) override
+    {
+        if (index >= 0 && index < effect->numPrograms)
+        {
+            effect->dispatcher (effect, abi::setProgram, 0, index, nullptr, 0.0f);
+            refreshParameters();
+        }
+    }
+    const juce::String getProgramName (int index) override
+    {
+        char text[256] {};
+        if (effect->dispatcher (effect, abi::getProgramNameIndexed, index, -1, text, 0.0f) != 0)
+            return juce::String::fromUTF8 (text);
+        return index == getCurrentProgram() ? dispatcherText (effect, abi::getProgramName) : juce::String();
+    }
+    void changeProgramName (int, const juce::String&) override {}
+
+    // State: FL Studio's wrapper layout (REA_rodada89 §2), so FL's own data restores as is.
+    void getStateInformation (juce::MemoryBlock& data) override
+    {
+        FlVst2State state;
+        state.currentProgram = getCurrentProgram();
+        if ((effect->flags & abi::programChunks) != 0)
+        {
+            state.flags = 8;
+            void* chunk = nullptr;
+            const auto size = effect->dispatcher (effect, abi::getChunk, 0, 0, &chunk, 0.0f);
+            if (chunk != nullptr && size > 0)
+                state.chunk.assign ((const std::uint8_t*) chunk, (const std::uint8_t*) chunk + size);
+        }
+        if (state.chunk.empty())
+            for (int i = 0; i < effect->numParams; ++i)
+                state.params.push_back (effect->getParameter != nullptr ? effect->getParameter (effect, i) : 0.0f);
+        const auto bytes = writeFlVst2State (state);
+        data.replaceAll (bytes.data(), bytes.size());
+    }
+
+    void setStateInformation (const void* data, int size) override
+    {
+        FlVst2State state;
+        if (! parseFlVst2State (std::vector<std::uint8_t> ((const std::uint8_t*) data, (const std::uint8_t*) data + size), state))
+            return;
+
+        const auto programs = effect->numPrograms;
+        if (! state.chunk.empty())
+        {
+            // FL: effSetChunk as a bank (index 0), as a program only for old version −6 states
+            effect->dispatcher (effect, abi::setChunk, state.chunkIsProgram() ? 1 : 0, (std::intptr_t) state.chunk.size(),
+                                state.chunk.data(), 0.0f);
+        }
+        else if (! state.params.empty() && effect->setParameter != nullptr)
+        {
+            const auto params = juce::jmax (1, effect->numParams);
+            const auto perProgram = state.allPrograms() && programs > 1 && (int) state.params.size() == params * programs;
+            for (int p = 0; p < (perProgram ? programs : 1); ++p)
+            {
+                if (perProgram)
+                    effect->dispatcher (effect, abi::setProgram, 0, p, nullptr, 0.0f);
+                effect->dispatcher (effect, abi::beginSetProgram, 0, 0, nullptr, 0.0f);
+                for (int i = 0; i < juce::jmin (effect->numParams, (int) state.params.size() - p * params); ++i)
+                    effect->setParameter (effect, i, state.params[(std::size_t) (p * params + i)]);
+                effect->dispatcher (effect, abi::endSetProgram, 0, 0, nullptr, 0.0f);
+            }
+        }
+        if (state.currentProgram >= 0 && state.currentProgram < programs && state.currentProgram != getCurrentProgram())
+            effect->dispatcher (effect, abi::setProgram, 0, state.currentProgram, nullptr, 0.0f);
+        refreshParameters();
+    }
+
+    // --- host callback -----------------------------------------------------------------------------------------
+    std::intptr_t callback (std::int32_t opcode, std::int32_t index, std::intptr_t value, void* ptr, float opt)
+    {
+        juce::ignoreUnused (ptr);
+        switch (opcode)
+        {
+            case abi::automate:
+                if (index >= 0 && index < (int) parameters.size())
+                {
+                    parameters[(std::size_t) index]->setFromPlugin (opt);
+                    if (juce::MessageManager::existsAndIsCurrentThread())
+                        parameters[(std::size_t) index]->sendValueChangedMessageToListeners (opt);
+                }
+                return 0;
+            case abi::getTime: return (std::intptr_t) &timeInfo;
+            case abi::ioChanged:
+                onMainThread ([this] { setLatencySamples (effect->initialDelay); });
+                return 1;
+            case abi::sizeWindow:
+                onMainThread ([this, w = index, h = (int) value] {
+                    if (auto* e = editor.getComponent())
+                    {
+                        const auto scale = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale;
+                        e->setSize (juce::roundToInt (w / scale), juce::roundToInt (h / scale));
+                    }
+                });
+                return 1;
+            case abi::getSampleRate: return (std::intptr_t) rate;
+            case abi::getBlockSize: return maxBlock;
+            case abi::getCurrentProcessLevel:
+                if (audioThread.load() == std::this_thread::get_id())
+                    return isNonRealtime() ? 4 : 2;
+                return 1;
+            case abi::updateDisplay:
+                onMainThread ([this] { refreshParameters(); updateHostDisplay(); });
+                return 1;
+            default: return 0;
+        }
+    }
+
+    void refreshParameters()
+    {
+        for (auto* p : parameters)
+            p->refresh();
+    }
+
+    abi::Effect* const effect;
+    juce::Component::SafePointer<juce::Component> editor;
+
+private:
+    static constexpr int maxEvents = 1024;
+
+    static BusesProperties busesFor (const abi::Effect& e, bool instrument)
+    {
+        BusesProperties buses;
+        auto set = [] (int channels) { return channels >= 2 ? juce::AudioChannelSet::stereo() : juce::AudioChannelSet::mono(); };
+        if (! instrument && e.numInputs > 0)
+            buses = buses.withInput ("Input", set (e.numInputs), true);
+        if (e.numOutputs > 0)
+            buses = buses.withOutput ("Output", set (e.numOutputs), true);
+        return buses;
+    }
+
+    void updateTimeInfo (int)
+    {
+        timeInfo = {};
+        timeInfo.sampleRate = rate;
+        timeInfo.tempo = 120.0;
+        timeInfo.timeSigNumerator = timeInfo.timeSigDenominator = 4;
+        timeInfo.flags = abi::tempoValid | abi::timeSigValid;
+        if (auto* head = getPlayHead())
+            if (const auto position = head->getPosition())
+            {
+                if (const auto bpm = position->getBpm())
+                    timeInfo.tempo = *bpm;
+                if (const auto samples = position->getTimeInSamples())
+                    timeInfo.samplePos = (double) *samples;
+                if (const auto ppq = position->getPpqPosition())
+                {
+                    timeInfo.ppqPos = *ppq;
+                    timeInfo.flags |= abi::ppqValid;
+                }
+                if (const auto bar = position->getPpqPositionOfLastBarStart())
+                {
+                    timeInfo.barStartPos = *bar;
+                    timeInfo.flags |= abi::barsValid;
+                }
+                if (const auto signature = position->getTimeSignature())
+                {
+                    timeInfo.timeSigNumerator = signature->numerator;
+                    timeInfo.timeSigDenominator = signature->denominator;
+                }
+                if (position->getIsPlaying())
+                    timeInfo.flags |= abi::transportPlaying;
+                if (position->getIsPlaying() != wasPlaying)
+                    timeInfo.flags |= abi::transportChanged;
+                wasPlaying = position->getIsPlaying();
+            }
+    }
+
+    void onMainThread (std::function<void()> fn)
+    {
+        juce::MessageManager::callAsync ([flag = alive, fn = std::move (fn)] {
+            if (*flag)
+                fn();
+        });
+    }
+
+    juce::PluginDescription description;
+    std::vector<Vst2Parameter*> parameters;
+    std::shared_ptr<std::atomic<bool>> alive = std::make_shared<std::atomic<bool>> (true);
+    bool active = false, wasPlaying = false;
+    int maxBlock = 512;
+    double rate = 44100.0;
+    juce::AudioBuffer<float> scratch;
+    std::vector<float*> inputs, outputs;
+    std::vector<std::uint8_t> events; // VstEvents header + pointer list
+    std::vector<abi::MidiEvent> midiEvents;
+    abi::TimeInfo timeInfo {};
+    std::atomic<std::thread::id> audioThread {};
+};
+
+std::intptr_t hostCallback (abi::Effect* effect, std::int32_t opcode, std::int32_t index, std::intptr_t value, void* ptr, float opt)
+{
+    switch (opcode)
+    {
+        case abi::version: return 2400;
+        case abi::currentId: return shellIdToCreate.load();
+        case abi::idle: return 0;
+        case abi::wantMidi: return 1;
+        case abi::getInputLatency:
+        case abi::getOutputLatency: return 0;
+        case abi::getAutomationState: return 1; // off
+        case abi::hostGetVendorString:
+        case abi::hostGetProductString:
+            if (ptr != nullptr)
+                std::strcpy ((char*) ptr, "LYNX");
+            return 1;
+        case abi::hostGetVendorVersion: return 1;
+        case abi::getLanguage: return 1; // English
+        case abi::hostCanDo:
+        {
+            static const char* yes[] = { "sendVstEvents", "sendVstMidiEvent", "sendVstTimeInfo", "receiveVstEvents",
+                                         "receiveVstMidiEvent", "sizeWindow", "supplyIdle", "startStopProcess" };
+            if (ptr != nullptr)
+                for (auto* s : yes)
+                    if (std::strcmp ((const char*) ptr, s) == 0)
+                        return 1;
+            return 0;
+        }
+        case abi::beginEdit:
+        case abi::endEdit: return 1;
+        case abi::getDirectory: return 0;
+        default: break;
+    }
+
+    if (effect != nullptr && effect->hostReserved1 != 0)
+        return reinterpret_cast<Vst2Instance*> (effect->hostReserved1)->callback (opcode, index, value, ptr, opt);
+
+    if (opcode == abi::getSampleRate)
+        return 44100;
+    if (opcode == abi::getBlockSize)
+        return 512;
+    return 0;
+}
+
+// The plugin's own window inside a child HWND (like the CLAP editor).
+class Vst2Editor final : public juce::AudioProcessorEditor,
+                         private juce::Timer
+{
+public:
+    explicit Vst2Editor (Vst2Instance& p)
+        : AudioProcessorEditor (p),
+          owner (p)
+    {
+        const auto scale = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale;
+        setSize (480, 320);
+        abi::Rect* rect = nullptr;
+        owner.effect->dispatcher (owner.effect, abi::editGetRect, 0, 0, &rect, 0.0f);
+        if (rect != nullptr && rect->right > rect->left && rect->bottom > rect->top)
+            setSize (juce::roundToInt ((rect->right - rect->left) / scale), juce::roundToInt ((rect->bottom - rect->top) / scale));
+        addAndMakeVisible (holder);
+        owner.editor = this;
+        startTimer (20);
+    }
+
+    ~Vst2Editor() override
+    {
+        stopTimer();
+        if (opened)
+            owner.effect->dispatcher (owner.effect, abi::editClose, 0, 0, nullptr, 0.0f);
+        holder.setHWND (nullptr);
+       #if JUCE_WINDOWS
+        if (container != nullptr)
+            DestroyWindow ((HWND) container);
+       #endif
+    }
+
+    void resized() override { holder.setBounds (getLocalBounds()); }
+
+private:
+    void timerCallback() override
+    {
+        if (opened)
+        {
+            owner.effect->dispatcher (owner.effect, abi::editIdle, 0, 0, nullptr, 0.0f);
+            return;
+        }
+       #if JUCE_WINDOWS
+        auto* peer = getPeer();
+        if (peer == nullptr)
+            return;
+        const auto scale = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale;
+        container = CreateWindowExW (0, L"STATIC", L"", WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, 0, 0,
+                                     juce::roundToInt (getWidth() * scale), juce::roundToInt (getHeight() * scale),
+                                     (HWND) peer->getNativeHandle(), nullptr, nullptr, nullptr);
+        holder.setHWND (container);
+        holder.setBounds (getLocalBounds());
+        owner.effect->dispatcher (owner.effect, abi::editOpen, 0, 0, container, 0.0f);
+        opened = true;
+        // some plugins only know their size once open
+        abi::Rect* rect = nullptr;
+        owner.effect->dispatcher (owner.effect, abi::editGetRect, 0, 0, &rect, 0.0f);
+        if (rect != nullptr && rect->right > rect->left && rect->bottom > rect->top)
+            setSize (juce::roundToInt ((rect->right - rect->left) / scale), juce::roundToInt ((rect->bottom - rect->top) / scale));
+       #else
+        stopTimer();
+       #endif
+    }
+
+    Vst2Instance& owner;
+    juce::HWNDComponent holder;
+    void* container = nullptr;
+    bool opened = false;
+};
+
+juce::AudioProcessorEditor* Vst2Instance::createEditor()
+{
+    return hasEditor() ? new Vst2Editor (*this) : nullptr;
+}
+} // namespace
+
+// --- format ---------------------------------------------------------------------------------------------------
+
+void Vst2PluginFormat::findAllTypesForFile (juce::OwnedArray<juce::PluginDescription>& results, const juce::String& path)
+{
+    if (! fileMightContainThisPluginType (path))
+        return;
+
+    auto* effect = openEffect (path, 0);
+    if (effect == nullptr)
+        return;
+
+    const juce::File file (path);
+    if (effect->dispatcher (effect, abi::getPlugCategory, 0, 0, nullptr, 0.0f) == abi::categoryShell)
+    {
+        // a shell (one DLL, several plugins): list each one by its ID and open it to describe it
+        std::vector<std::pair<std::int32_t, juce::String>> ids;
+        for (int guard = 0; guard < 4096; ++guard)
+        {
+            char name[256] {};
+            const auto id = (std::int32_t) effect->dispatcher (effect, abi::shellGetNextPlugin, 0, 0, name, 0.0f);
+            if (id == 0)
+                break;
+            ids.push_back ({ id, juce::String::fromUTF8 (name).trim() });
+        }
+        closeEffect (effect);
+        for (const auto& [id, name] : ids)
+            if (auto* sub = openEffect (path, id))
+            {
+                auto d = describe (sub, file, name, true);
+                d.uniqueId = d.deprecatedUid = id;
+                results.add (new juce::PluginDescription (d));
+                closeEffect (sub);
+            }
+        return;
+    }
+
+    results.add (new juce::PluginDescription (describe (effect, file, {}, false)));
+    closeEffect (effect);
+}
+
+bool Vst2PluginFormat::fileMightContainThisPluginType (const juce::String& path)
+{
+   #if JUCE_WINDOWS
+    const juce::File f (path);
+    // not the DLLs inside a VST3 bundle or a CLAP folder
+    return f.hasFileExtension (".dll") && f.existsAsFile() && ! path.containsIgnoreCase (".vst3") && ! path.containsIgnoreCase (".clap");
+   #else
+    juce::ignoreUnused (path);
+    return false;
+   #endif
+}
+
+juce::String Vst2PluginFormat::getNameOfPluginFromIdentifier (const juce::String& path)
+{
+    return juce::File (path).getFileNameWithoutExtension();
+}
+
+bool Vst2PluginFormat::pluginNeedsRescanning (const juce::PluginDescription& d)
+{
+    return juce::File (d.fileOrIdentifier).getLastModificationTime() != d.lastFileModTime;
+}
+
+bool Vst2PluginFormat::doesPluginStillExist (const juce::PluginDescription& d)
+{
+    return juce::File (d.fileOrIdentifier).exists();
+}
+
+juce::StringArray Vst2PluginFormat::searchPathsForPlugins (const juce::FileSearchPath& directories, bool recursive, bool)
+{
+    juce::StringArray found;
+   #if JUCE_WINDOWS
+    for (int i = 0; i < directories.getNumPaths(); ++i)
+        for (const auto& f : directories[i].findChildFiles (juce::File::findFiles, recursive, "*.dll"))
+            if (fileMightContainThisPluginType (f.getFullPathName()))
+                found.addIfNotAlreadyThere (f.getFullPathName());
+   #else
+    juce::ignoreUnused (directories, recursive);
+   #endif
+    return found;
+}
+
+juce::FileSearchPath Vst2PluginFormat::getDefaultLocationsToSearch()
+{
+    juce::FileSearchPath paths;
+   #if JUCE_WINDOWS
+    const auto programs = juce::File::getSpecialLocation (juce::File::globalApplicationsDirectory);
+    for (const auto* sub : { "VSTPlugins", "Steinberg/VSTPlugins", "Common Files/VST2", "Common Files/Steinberg/VST2" })
+        paths.add (programs.getChildFile (sub));
+   #endif
+    return paths;
+}
+
+void Vst2PluginFormat::createPluginInstance (const juce::PluginDescription& d, double sampleRate, int blockSize,
+                                             PluginCreationCallback callback)
+{
+    // a shell's sub-plugin: the ID the plugin asks the host for while being created
+    auto* effect = openEffect (d.fileOrIdentifier, d.hasSharedContainer ? d.uniqueId : 0);
+    if (effect == nullptr)
+    {
+        callback (nullptr, juce::String::fromUTF8 ("could not load ") + d.fileOrIdentifier);
+        return;
+    }
+    if (effect->uniqueId != d.uniqueId && ! d.hasSharedContainer)
+    {
+        closeEffect (effect);
+        callback (nullptr, juce::String::fromUTF8 ("a different plugin is now in ") + d.fileOrIdentifier);
+        return;
+    }
+    auto instance = std::make_unique<Vst2Instance> (effect, d);
+    instance->setRateAndBufferSizeDetails (sampleRate, blockSize);
+    callback (std::move (instance), {});
+}
+} // namespace lynx

+ 36 - 0
src/engine/Vst2Format.h

@@ -0,0 +1,36 @@
+#pragma once
+
+#include <juce_audio_processors/juce_audio_processors.h>
+
+namespace lynx
+{
+// VST2 plugin hosting. JUCE 8 only hosts VST2 with Steinberg's (no longer distributed) SDK, so this is a
+// host of our own, written from the publicly documented VST 2.4 binary interface (the AEffect structure, the
+// dispatcher opcodes and the host callback), as one more juce::AudioPluginFormat: scan, plugin list, plugin
+// window, saved state, latency and parameter automation go through the same paths as VST3 and CLAP.
+// The saved state is the layout FL Studio's wrapper writes (REA_rodada5 §3.1 / REA_rodada89 §2), so a
+// VST2 found for an imported .flp gets the project's settings unchanged.
+// Windows only (VST2 binaries are DLLs); elsewhere the format finds nothing.
+class Vst2PluginFormat final : public juce::AudioPluginFormat
+{
+public:
+    static constexpr const char* formatName = "VST";
+
+    juce::String getName() const override { return formatName; }
+
+    void findAllTypesForFile (juce::OwnedArray<juce::PluginDescription>& results, const juce::String& fileOrIdentifier) override;
+    bool fileMightContainThisPluginType (const juce::String& fileOrIdentifier) override;
+    juce::String getNameOfPluginFromIdentifier (const juce::String& fileOrIdentifier) override;
+    bool pluginNeedsRescanning (const juce::PluginDescription&) override;
+    bool doesPluginStillExist (const juce::PluginDescription&) override;
+    bool canScanForPlugins() const override { return true; }
+    bool isTrivialToScan() const override { return false; }
+    juce::StringArray searchPathsForPlugins (const juce::FileSearchPath& directories, bool recursive, bool allowAsync) override;
+    juce::FileSearchPath getDefaultLocationsToSearch() override;
+    bool requiresUnblockedMessageThreadDuringCreation (const juce::PluginDescription&) const override { return false; }
+
+private:
+    void createPluginInstance (const juce::PluginDescription&, double initialSampleRate, int initialBufferSize,
+                               PluginCreationCallback) override;
+};
+} // namespace lynx

+ 28 - 7
src/flp/Flp.cpp

@@ -1,6 +1,7 @@
 #include "flp/Flp.h"
 
 #include <algorithm>
+#include <cmath>
 #include <cstring>
 
 namespace flp
@@ -299,17 +300,27 @@ ControlId normalizeControlId (std::uint32_t raw)
     return { raw };
 }
 
-std::size_t playlistRecordSize (std::uint32_t versionNumber, std::size_t payloadSize)
+std::size_t playlistRecordSize (std::uint32_t versionNumber, std::size_t payloadSize, std::uint32_t flagsA9)
 {
-    // Sizes observed in the FL 2026 demos; the 60 → 80 change falls between 24.1.0 and 24.2.99.
-    const std::size_t preferred = versionNumber < version (20, 99, 1)   ? 32
-                                  : versionNumber < version (24, 2, 99) ? 60
-                                                                         : 80;
+    // REA_rodada2 §4.2: before 20.99.1 the record is 32 B; after it the file flags (0xA9) choose the layout:
+    // bit 1 off -> 60 B, bit 1 on and bit 3 off -> 80 B (24.2 ... 25.2), bits 1 and 3 on -> 88 B (25.2.99, 26.x).
+    // Files without 0xA9 fall back to the sizes seen in the demos for their version.
+    std::size_t preferred = 32;
+
+    if (versionNumber >= version (20, 99, 1))
+    {
+        if ((flagsA9 & 2) != 0)
+            preferred = (flagsA9 & 8) != 0 ? 88 : 80;
+        else if (flagsA9 != 0)
+            preferred = 60;
+        else
+            preferred = versionNumber < version (24, 2, 99) ? 60 : 80;
+    }
 
     if (payloadSize % preferred == 0)
         return preferred;
 
-    for (std::size_t size : { 80u, 60u, 32u })
+    for (std::size_t size : { 88u, 80u, 60u, 32u })
         if (payloadSize % size == 0)
             return size;
 
@@ -644,7 +655,7 @@ Project parseProject (std::span<const std::uint8_t> file, bool channelPreset)
                     arrangement(); // old files do not have the arrangement event
                 }
 
-                const auto recordSize = playlistRecordSize (project.versionNumber, e.data.size());
+                const auto recordSize = playlistRecordSize (project.versionNumber, e.data.size(), project.flagsA9);
 
                 if (recordSize == 0)
                 {
@@ -670,6 +681,16 @@ Project parseProject (std::span<const std::uint8_t> file, bool channelPreset)
                     item.patternStartTick = readLE<std::int32_t> (e.data, o + 24);
                     item.patternEndTick = readLE<std::int32_t> (e.data, o + 28);
 
+                    if (recordSize >= 60)
+                    {
+                        // REA_rodada2 §4.2 (+0x24 fade-in, +0x2C fade-out, +0x34 clip gain); fades in ms
+                        // (e.g. 923.08 = 2 beats at 130 BPM in a 26.1 project).
+                        const auto finiteOr = [] (float v, float fallback) { return std::isfinite (v) ? v : fallback; };
+                        item.fadeInMs = std::max (0.0f, finiteOr (readLE<float> (e.data, o + 0x24), 0.0f));
+                        item.fadeOutMs = std::max (0.0f, finiteOr (readLE<float> (e.data, o + 0x2C), 0.0f));
+                        item.gain = std::max (0.0f, finiteOr (readLE<float> (e.data, o + 0x34), 1.0f));
+                    }
+
                     const auto patternBase = base != 0 ? base : playlistPatternBase;
 
                     if (index > patternBase)

+ 7 - 1
src/flp/Flp.h

@@ -228,6 +228,11 @@ struct PlaylistItem
     std::int32_t patternEndTick = -1;
     float startOffset = 0.0f;
     float endOffset = 0.0f;
+
+    // Audio clips, records of 60 B and more (FL 20.99+): fades in milliseconds and the clip gain (linear).
+    float fadeInMs = 0.0f;
+    float fadeOutMs = 0.0f;
+    float gain = 1.0f;
 };
 
 struct PlaylistTrackInfo
@@ -308,7 +313,8 @@ Project parseProject (std::span<const std::uint8_t> file, bool channelPreset = f
 
 // Utilities exposed for tests
 std::uint32_t parseVersionNumber (const std::string& version);
-std::size_t playlistRecordSize (std::uint32_t versionNumber, std::size_t payloadSize);
+// `flagsA9`: the file flags event 0xA9 (0 when absent); it decides between the 60, 80 and 88 B layouts.
+std::size_t playlistRecordSize (std::uint32_t versionNumber, std::size_t payloadSize, std::uint32_t flagsA9 = 0);
 // Converts a controlID from old files (class 0x2..., sends at 0x1F40+d) to the current format.
 ControlId normalizeControlId (std::uint32_t raw);
 } // namespace flp

+ 2 - 2
src/ui/ChannelRackComponent.cpp

@@ -1510,7 +1510,7 @@ void ChannelRackComponent::showChannelMenu (int channel)
         });
         openPluginWindow (channel);
     });
-    instruments.addSubMenu (tr ("Plugin (VST3/CLAP)"), plugins);
+    instruments.addSubMenu (tr ("Plugin (VST/VST3/CLAP)"), plugins);
 
     juce::PopupMenu menu;
     menu.addSectionHeader (juce::String::fromUTF8 (c.name.c_str()));
@@ -1699,7 +1699,7 @@ void ChannelRackComponent::addInstrumentItems (juce::PopupMenu& menu, int insert
         openPluginWindow (added); // the plugin opens when added
         openEditorRow = added;
     });
-    menu.addSubMenu (tr ("Plugin (VST3/CLAP)"), plugins);
+    menu.addSubMenu (tr ("Plugin (VST/VST3/CLAP)"), plugins);
 }
 
 void ChannelRackComponent::showAddChannelMenu (int insertAt)

A diferenza do arquivo foi suprimida porque é demasiado grande
+ 2871 - 2869
src/ui/I18nData.h


+ 12 - 2
src/ui/MainComponent.cpp

@@ -2402,6 +2402,10 @@ void MainComponent::showMissingFiles (bool afterOpening)
                 if (fx.kind == EffectKind::plugin && ! fx.plugin.id.empty() && host.find (juce::String::fromUTF8 (fx.plugin.id.c_str())) == nullptr)
                     addPlugin (fx.plugin, song.mixer[t].name.empty() ? (t == 0 ? std::string ("Master") : "Insert " + std::to_string (t)) : song.mixer[t].name,
                                "Bypassed: the slot keeps the plugin's settings until it is installed");
+        // installed, but failed to load: they play silence / are bypassed
+        for (const auto& line : host.getLoadFailures())
+            if (std::none_of (info.plugins.begin(), info.plugins.end(), [&] (const MissingPlugin& p) { return p.name == line.toStdString(); }))
+                info.plugins.push_back ({ line.toStdString(), {}, "Silence: the plugin is installed but did not load" });
         if (currentFile.existsAsFile())
             info.searchFolders.add (currentFile.getParentDirectory().getFullPathName());
     }
@@ -2592,7 +2596,7 @@ juce::PopupMenu MainComponent::getMenuForIndex (int index, const juce::String&)
         menu.addSeparator();
         menu.addItem (tr ("Plugin manager..."), [this] { showPluginManager(); });
         const auto scanning = engine.getPluginHost().backgroundScan().running;
-        menu.addItem (scanning ? tr ("Stop the plugin scan") : tr ("Scan for plugins (VST3 and CLAP)"), [this, scanning] {
+        menu.addItem (scanning ? tr ("Stop the plugin scan") : tr ("Scan for plugins (VST, VST3 and CLAP)"), [this, scanning] {
             if (scanning)
                 engine.getPluginHost().cancelBackgroundScan();
             else
@@ -2623,7 +2627,8 @@ juce::PopupMenu MainComponent::getMenuForIndex (int index, const juce::String&)
         menu.addItem (tr ("Last FL Studio import report"), [this] {
             const auto& r = engine.getImportReport();
             if (r.converted.empty() && r.approximated.empty() && r.unsupported.empty() && r.droppedEffects.empty() && r.missingSamples == 0
-                && engine.getMissingPlugins().isEmpty() && engine.getMatchedPlugins().isEmpty())
+                && engine.getMissingPlugins().isEmpty() && engine.getMatchedPlugins().isEmpty() && engine.getPluginsWithoutState().isEmpty()
+                && engine.getPluginHost().getLoadFailures().isEmpty())
                 juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("FL Studio import"),
                                                         tr ("Nothing to report (no .flp imported in this session, or everything was converted)."));
             else
@@ -2869,6 +2874,11 @@ void MainComponent::showImportReport()
     if (! missing.isEmpty())
         text << tr ("Plugins not installed on this PC (or in a folder LYNX doesn't scan; Options > Setup wizard):") << "\n  "
              << missing.joinIntoString ("\n  ") << "\n\n";
+    if (const auto& lost = engine.getPluginsWithoutState(); ! lost.isEmpty())
+        text << tr ("Plugins found but playing their default settings (the project saved them for the other format, VST2/VST3):") << "\n  "
+             << lost.joinIntoString ("\n  ") << "\n\n";
+    if (const auto failed = engine.getPluginHost().getLoadFailures(); ! failed.isEmpty())
+        text << tr ("Plugins installed but not loaded (silent):") << "\n  " << failed.joinIntoString ("\n  ") << "\n\n";
     if (! r.droppedEffects.empty())
         text << tr ("Effects with no equivalent (left out):") << "\n" << list (r.droppedEffects) << "\n\n";
     if (r.missingSamples > 0)

+ 2 - 1
src/ui/MissingFilesDialog.cpp

@@ -232,7 +232,8 @@ private:
             lines.add (tr ("{0} sample(s) used by {1} could not be found on this PC.",
                            { juce::String ((int) info.files.size()), info.projectName.isNotEmpty() ? info.projectName : tr ("this project") }));
         if (! info.plugins.empty())
-            lines.add (tr ("{0} plugin(s) are not installed (or not scanned): LYNX put something in their place.", { juce::String ((int) info.plugins.size()) }));
+            lines.add (tr ("{0} plugin(s) will not sound as in FL Studio (not installed, not loaded, or without their settings): see what LYNX did with each.",
+                           { juce::String ((int) info.plugins.size()) }));
         if (! info.autoRelocated.empty())
             lines.add (tr ("{0} file(s) were found automatically in another folder.", { juce::String ((int) info.autoRelocated.size()) }));
         if (lines.isEmpty())

+ 1 - 1
src/ui/MixerComponent.cpp

@@ -2395,7 +2395,7 @@ void EffectsPanel::showAddMenu (int)
         repaint();
     });
     menu.addSeparator();
-    menu.addSubMenu (tr ("Plugin (VST3/CLAP)"), plugins);
+    menu.addSubMenu (tr ("Plugin (VST/VST3/CLAP)"), plugins);
 
     menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
 }

+ 2 - 2
src/ui/PluginWindow.cpp

@@ -66,7 +66,7 @@ class ScanThread final : public juce::ThreadWithProgressWindow
 {
 public:
     ScanThread (AudioEngine& e, std::function<void (int)> done)
-        : juce::ThreadWithProgressWindow (tr ("Scanning for plugins (VST3 and CLAP)..."), true, true),
+        : juce::ThreadWithProgressWindow (tr ("Scanning for plugins (VST, VST3 and CLAP)..."), true, true),
           engine (e),
           onDone (std::move (done))
     {
@@ -229,6 +229,6 @@ void addPluginItems (juce::PopupMenu& menu, AudioEngine& engine, bool instrument
         menu.addItem (tr ("(no plugins found; use \"Scan for plugins\")"), false, false, [] {});
 
     menu.addSeparator();
-    menu.addItem (tr ("Scan for plugins (VST3 and CLAP)..."), [&engine] { engine.getPluginHost().startBackgroundScan(); });
+    menu.addItem (tr ("Scan for plugins (VST, VST3 and CLAP)..."), [&engine] { engine.getPluginHost().startBackgroundScan(); });
 }
 } // namespace lynx

+ 1 - 1
src/ui/SettingsDialog.cpp

@@ -439,7 +439,7 @@ public:
             }, persistent);
 
         pluginFolders = std::make_unique<FolderList> (
-            tr ("Plugin folders"), tr ("Scanned for VST3 and CLAP plugins (Options > Scan for plugins)."),
+            tr ("Plugin folders"), tr ("Scanned for VST, VST3 and CLAP plugins (Options > Scan for plugins)."),
             [persistent, sample, &host] {
                 juce::StringArray list;
                 if (persistent)

+ 1 - 1
src/ui/SetupWizard.cpp

@@ -261,7 +261,7 @@ private:
 
     juce::Label title, intro, flStatus, scanStatus;
     SectionLabel languageLabel { tr ("Language") }, audioLabel { tr ("Audio output") }, flLabel { "FL Studio" },
-        foldersLabel { tr ("Plugin folders (VST3 and CLAP)") };
+        foldersLabel { tr ("Plugin folders (VST, VST3 and CLAP)") };
     juce::ComboBox languageBox;
     juce::AudioDeviceSelectorComponent devices;
     juce::StringArray folderList;

+ 216 - 7
tests/tests.cpp

@@ -1,5 +1,6 @@
 // Core tests (no JUCE). Usage: lynx_tests [folder-with-flp-files]
 
+#include <optional>
 #include <atomic>
 #include <chrono>
 #include <thread>
@@ -289,6 +290,80 @@ TEST (flp_playlist_record_size_by_version)
     CHECK (flp::playlistRecordSize (25002005, 7) == 0);
 }
 
+TEST (flp_playlist_record_size_by_file_flags)
+{
+    // REA_rodada2 §4.2: 0xA9 bit 1 -> 80 B, bits 1 and 3 -> the native 88 B record (FL 25.2.99 / 26.x)
+    CHECK (flp::playlistRecordSize (26001003, 88 * 4, 15) == 88); // 352 is also a multiple of 32
+    CHECK (flp::playlistRecordSize (26001003, 88 * 10, 15) == 88); // ... and of 80
+    CHECK (flp::playlistRecordSize (25002005, 160, 7) == 80);
+    CHECK (flp::playlistRecordSize (21000000, 120, 1) == 60);
+    CHECK (flp::playlistRecordSize (26001003, 63712) == 88); // no flags: the only size that fits besides 32
+}
+
+TEST (flp_native_88_byte_playlist_items_with_clip_gain_and_fades)
+{
+    // an FL 26.1 file: 0xA9 = 15, four 88 B items (352 B: the old 32 B guess read garbage from it)
+    FlpBuilder b (96);
+    b.ascii (0xC7, "26.1.3.5570");
+    b.u8 (0xA9); b.u32 (15);
+    b.u8 (0x9C); b.u32 (130000);
+    b.u8 (0x40); b.u16 (0);
+    b.u8 (0x15); b.u8 (4); // audio clip channel
+    b.utf16 (0xC4, u"C:\\nowhere\\clip.wav");
+
+    std::vector<std::uint8_t> items;
+    auto add = [&] (std::uint32_t pos, std::uint32_t len, std::uint16_t track, float fadeIn, float fadeOut, float gain) {
+        std::vector<std::uint8_t> r (88, 0);
+        const std::uint16_t base = 20480, idx = 0, rv = (std::uint16_t) (499 - track);
+        const float offs[] = { -1.0f, -1.0f };
+        std::memcpy (&r[0], &pos, 4);
+        std::memcpy (&r[4], &base, 2);
+        std::memcpy (&r[6], &idx, 2);
+        std::memcpy (&r[8], &len, 4);
+        std::memcpy (&r[12], &rv, 2);
+        std::memcpy (&r[0x18], offs, 8);
+        std::memcpy (&r[0x24], &fadeIn, 4);
+        std::memcpy (&r[0x2C], &fadeOut, 4);
+        std::memcpy (&r[0x34], &gain, 4);
+        const double stretch = 1.0;
+        const std::int32_t minusOne = -1;
+        std::memcpy (&r[0x40], &stretch, 8);
+        std::memcpy (&r[0x4C], &minusOne, 4);
+        items.insert (items.end(), r.begin(), r.end());
+    };
+    add (0, 384, 0, 0.0f, 0.0f, 1.0f);
+    add (384, 384, 1, 923.0769f, 461.5385f, 1.65f); // 2 beats in, 1 beat out at 130 BPM
+    add (768, 96, 2, 0.0f, 0.0f, 0.0f);
+    add (1536, 192, 3, 0.0f, 5000.0f, 0.5f);        // fade longer than the clip
+    b.data (0xE9, items);
+
+    const auto p = flp::parseProject (b.bytes);
+    CHECK (p.flagsA9 == 15);
+    CHECK (p.arrangements.size() == 1 && p.arrangements[0].items.size() == 4);
+    CHECK (p.warnings.empty());
+
+    if (p.arrangements.size() == 1 && p.arrangements[0].items.size() == 4)
+    {
+        const auto& it = p.arrangements[0].items;
+        CHECK (it[1].position == 384 && it[1].length == 384 && it[1].track == 1 && it[1].kind == flp::PlaylistItem::Kind::channelClip);
+        CHECK (it[3].position == 1536 && it[3].track == 3);
+        CHECK (std::abs (it[1].gain - 1.65f) < 1e-6f && std::abs (it[1].fadeInMs - 923.0769f) < 1e-3f);
+
+        const auto song = lynx::importFlp (p);
+        CHECK (song.playlist.size() == 4);
+
+        if (song.playlist.size() == 4)
+        {
+            const auto beat = (std::int64_t) lynx::ppq;
+            CHECK (song.playlist[0].gain == 1.0f && song.playlist[0].fadeIn == 0 && song.playlist[0].fadeOut == 0);
+            CHECK (std::abs (song.playlist[1].gain - 1.65f) < 1e-6f);
+            CHECK (std::llabs (song.playlist[1].fadeIn - 2 * beat) <= 1 && std::llabs (song.playlist[1].fadeOut - beat) <= 1);
+            CHECK (song.playlist[2].gain == 0.0f);
+            CHECK (song.playlist[3].fadeOut == song.playlist[3].length); // clamped
+        }
+    }
+}
+
 TEST (flp_parses_project_model)
 {
     FlpBuilder b (96);
@@ -946,7 +1021,7 @@ TEST (flp_real_files)
     }
 
     int files = 0, withNotes = 0, withPlaylist = 0, automations = 0, automationsWithTarget = 0, sends = 0;
-    int threeOsc = 0, threeOscDecoded = 0, wrapped = 0, wrappedParsed = 0, markers = 0, signatures = 0, trackEqs = 0;
+    int threeOsc = 0, threeOscDecoded = 0, wrapped = 0, wrappedParsed = 0, wrappedVst2 = 0, wrappedVst2State = 0, markers = 0, signatures = 0, trackEqs = 0;
     int harmless = 0, harmlessDecoded = 0, harmlessParsed = 0, harmlessKind = 0, sytrus = 0, sytrusDecoded = 0, sytrusEngine = 0, sytrusRendered = 0,
         sytrusSounding = 0;
     int harmor = 0, harmorUsable = 0, harmorKind = 0, harmorSounding = 0;
@@ -1330,6 +1405,14 @@ TEST (flp_real_files)
                 ++wrapped;
                 lynx::ForeignPlugin f;
                 wrappedParsed += lynx::parseFlWrapper (state, f) && f.format != lynx::ForeignPlugin::Format::none && ! f.name.empty();
+                if (f.format == lynx::ForeignPlugin::Format::vst2)
+                {
+                    // VST2 state (REA_rodada89 §2): every one decodes and writes back to the same bytes
+                    ++wrappedVst2;
+                    lynx::FlVst2State st;
+                    if (lynx::parseFlVst2State (f.state, st) && st.version == -9 && lynx::writeFlVst2State (st) == f.state)
+                        ++wrappedVst2State;
+                }
             };
             for (const auto& c : p.channels)
                 countWrapper (c.pluginName, c.pluginState);
@@ -2049,7 +2132,8 @@ TEST (flp_real_files)
     std::printf ("  %d FL effect presets, %d read\n", fxPresets, fxDecoded);
     CHECK (fxDecoded == fxPresets);
     CHECK (wrappedParsed == wrapped);
-    std::printf ("  %d plugins in Fruity Wrapper, %d read\n", wrapped, wrappedParsed);
+    CHECK (wrappedVst2State == wrappedVst2);
+    std::printf ("  %d plugins in Fruity Wrapper, %d read; %d VST2 states, %d decoded\n", wrapped, wrappedParsed, wrappedVst2, wrappedVst2State);
     std::printf ("  %d markers, %d time signature changes, %d tracks with EQ\n", markers, signatures, trackEqs);
     std::printf ("  %d parametric EQs (%d with FL settings), %d reverbs (%d without dry)\n", peqSlots, peqShaped, reverbs, reverbsDryless);
     std::printf ("  DirectWave: %d channels, %d zones; FPC: %d projects, %d pad channels, %d pad notes\n", dwChannels, dwZones, fpcKits,
@@ -3597,6 +3681,53 @@ TEST (fl_wrapper_state_parses_records_and_vst3_state)
     CHECK (positions == (std::vector<int> { 1, -1, -1, 0, 2 }));
     CHECK (lynx::flVst3SlotPositions ({}, { 5u, 6u }) == (std::vector<int> { 0, 1 })); // new instance: slot = position
 
+    // VST2 state (REA_rodada89 §2): chunk and raw-parameter layouts, current (−9) and older versions
+    {
+        lynx::FlVst2State st;
+        st.flags = 8;
+        st.currentProgram = 3;
+        st.chunk = bytes ("BANKCHUNK");
+        const auto withChunk = lynx::writeFlVst2State (st);
+        lynx::FlVst2State back;
+        CHECK (lynx::parseFlVst2State (withChunk, back));
+        CHECK (back.version == -9 && back.flags == 8 && back.currentProgram == 3 && back.chunk == bytes ("BANKCHUNK") && back.params.empty());
+        CHECK (! back.chunkIsProgram());
+
+        lynx::FlVst2State raw;
+        raw.flags = 1;
+        raw.params = { 0.25f, 0.5f, 1.0f };
+        raw.programNames = { "Init" };
+        const auto withParams = lynx::writeFlVst2State (raw);
+        CHECK (withParams.size() == 4 + 1 + 4 + 8 + 4 + 4 + 12 + 4 + 25);
+        CHECK (lynx::parseFlVst2State (withParams, back));
+        CHECK (back.chunk.empty() && back.params == raw.params && back.allPrograms() && back.programNames == std::vector<std::string> { "Init" });
+
+        // version −5: no flags, i32 size, then i32 program; −6 without "all programs": the chunk is one program
+        std::vector<std::uint8_t> v5;
+        for (auto v : { 0xFFFFFFFBu, 4u, 7u })
+            u32 (v5, v);
+        for (auto c : bytes ("ABCD"))
+            v5.push_back (c);
+        CHECK (lynx::parseFlVst2State (v5, back) && back.version == -5 && back.currentProgram == 7 && back.chunk == bytes ("ABCD"));
+        std::vector<std::uint8_t> v6;
+        u32 (v6, 0xFFFFFFFAu);
+        v6.push_back (0);
+        for (auto v : { 2u, 0u })
+            u32 (v6, v);
+        v6.push_back ('x');
+        v6.push_back ('y');
+        CHECK (lynx::parseFlVst2State (v6, back) && back.chunkIsProgram() && back.chunk == bytes ("xy"));
+
+        // nothing to restore (123456), unknown old layouts, truncated chunks
+        std::vector<std::uint8_t> marker;
+        u32 (marker, 123456u);
+        CHECK (! lynx::parseFlVst2State (marker, back));
+        auto cut = withChunk;
+        cut.pop_back();
+        CHECK (! lynx::parseFlVst2State (cut, back));
+        CHECK (! lynx::parseFlVst2State ({}, back));
+    }
+
     // version out of range or no type: not a usable wrapper
     blob[0] = 13;
     CHECK (! lynx::parseFlWrapper (blob, p));
@@ -4242,7 +4373,8 @@ TEST (audio_clips_trigger_cut_and_resume)
 
     // first block already playing mid-clip
     r.process (state.get(), true, 1.5 * lynx::ppq, 256, l.data(), rr.data());
-    CHECK (std::abs (l[0] - 0.75f) < 0.001f);
+    const auto unity = 1.0f / lynx::channelGain (10000.0f / 12800.0f); // clip level at 100% channel volume (REA_rodada89 §4.2)
+    CHECK (std::abs (l[0] - 0.75f * unity) < 0.002f);
 
     // the clip ends at beat 3: after the short fade, silence (the sample would still have audio)
     double tick = 3.0 * lynx::ppq - 10 * tps;
@@ -5806,10 +5938,41 @@ TEST (audio_clip_fades_and_gain)
         all.insert (all.end(), l.begin(), l.end());
     }
 
-    CHECK (all[100] < 0.01f);                            // fade-in start
-    CHECK (std::abs (all[12000] - 0.25f) < 0.02f);       // fade-in midpoint: half of 0.5
-    CHECK (std::abs (all[48000] - 0.5f) < 0.01f);        // body: the clip gain
-    CHECK (std::abs (all[96000 - 12000] - 0.25f) < 0.02f); // fade-out midpoint
+    // FL plays a clip at unity at the default channel volume (78%): at 100% it is that much louder (REA_rodada89 §4.2)
+    const auto unity = 1.0f / lynx::channelGain (10000.0f / 12800.0f);
+    CHECK (all[100] < 0.01f);                                       // fade-in start
+    CHECK (std::abs (all[12000] - 0.25f * unity) < 0.02f);          // fade-in midpoint: half of 0.5
+    CHECK (std::abs (all[48000] - 0.5f * unity) < 0.01f);           // body: the clip gain
+    CHECK (std::abs (all[96000 - 12000] - 0.25f * unity) < 0.02f);  // fade-out midpoint
+}
+
+TEST (audio_clip_unity_at_fl_default_volume)
+{
+    // a Playlist audio clip at FL's default channel volume (10000/12800) and centre pan plays its sample unchanged
+    auto dc = std::make_shared<lynx::SampleData>();
+    dc->left.assign (48000, 0.5f);
+    auto clip = lynx::makeInstrument (lynx::InstrumentKind::audioClip, dc);
+    clip->prepare (48000.0);
+    lynx::ChannelDef c;
+    c.instrument = lynx::InstrumentKind::audioClip;
+    c.volume = 10000.0f / 12800.0f;
+    clip->configure (c, 120.0);
+    clip->noteOn (60, 1.0f);
+    std::vector<float> l (4800, 0.0f), r (4800, 0.0f);
+    const auto g = lynx::channelGain (c.volume);
+    clip->render (l.data(), r.data(), 4800, g, g);
+    CHECK (std::abs (l[2400] - 0.5f) < 1.0e-3f && std::abs (r[2400] - 0.5f) < 1.0e-3f);
+
+    // a sampler channel (pattern notes) keeps the channel volume curve as it was
+    auto sampler = lynx::makeInstrument (lynx::InstrumentKind::sampler, dc);
+    sampler->prepare (48000.0);
+    c.instrument = lynx::InstrumentKind::sampler;
+    sampler->configure (c, 120.0);
+    sampler->noteOn (60, 1.0f);
+    std::fill (l.begin(), l.end(), 0.0f);
+    std::fill (r.begin(), r.end(), 0.0f);
+    sampler->render (l.data(), r.data(), 4800, g, g);
+    CHECK (std::abs (l[2400] - 0.5f * g) < 0.02f);
 }
 
 TEST (slicer_detects_hits_and_plays_slices_by_key)
@@ -14836,4 +14999,50 @@ TEST (event_editor_playback)
     CHECK (loop[0] < 1.0e-4f && loop[1] > 0.01f && loop[2] < 1.0e-4f && loop[3] > 0.01f);
 }
 #include "PrefsTests.inc"
+
+TEST (level_audit_demo_imports_round89)
+{
+    // REA_rodada89 §4: two demo projects whose FL renders were much louder than LYNX's
+    if (realFlpDir.empty())
+        return;
+    auto load = [] (const std::filesystem::path& path) -> std::optional<lynx::Song> {
+        if (! std::filesystem::exists (path))
+            return std::nullopt;
+        std::ifstream in (path, std::ios::binary);
+        const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
+        return lynx::importFlp (flp::parseProject (file));
+    };
+    const auto demos = std::filesystem::path (realFlpDir) / "Demo projects";
+
+    // FL 12+: a route to insert 100+ without a level record plays at 100% (the percussion bus of "Lightning")
+    if (const auto song = load (demos / "Product demos" / "Square a Saw - Lightning (VEELA Vocals Resynthesized).flp"))
+    {
+        int highRoutes = 0, highAtZero = 0;
+        for (const auto& t : song->mixer)
+            for (const auto& send : t.sends)
+                if (send.target >= 100)
+                {
+                    ++highRoutes;
+                    highAtZero += send.level <= 0.0f;
+                }
+        std::printf ("  Lightning: %d routes to inserts 100+, %d at level 0\n", highRoutes, highAtZero);
+        CHECK (highRoutes > 0 && highAtZero == 0);
+    }
+
+    // Fruity Compressors FL saved as VST2 inside Fruity Wrapper (RawFL): the exact engine with the saved controls
+    if (const auto song = load (demos / "Visual" / "ZGameEditor Visualizer" / "Treben - Gimbal and Sinan - RawFL.flp"))
+    {
+        int compressors = 0, withSettings = 0;
+        for (const auto& t : song->mixer)
+            for (const auto& fx : t.effects)
+                if (fx.kind == lynx::EffectKind::fruityCompressor)
+                {
+                    ++compressors;
+                    const auto defaults = lynx::makeEffectSlot (lynx::EffectKind::fruityCompressor);
+                    withSettings += fx.params != defaults.params;
+                }
+        std::printf ("  RawFL: %d wrapped Fruity Compressors on the exact engine, %d with their own settings\n", compressors, withSettings);
+        CHECK (compressors >= 10 && withSettings >= 8);
+    }
+}
 #include "DialogsTests84.inc"

+ 158 - 0
tools/testplugin/lynx_test_vst2.c

@@ -0,0 +1,158 @@
+/* A minimal VST2 instrument for testing LYNX's own VST2 host (src/engine/Vst2Format.cpp) without third-party
+ * plugins. Written against the VST 2.4 binary interface as LYNX declares it (no Steinberg headers):
+ *   zig cc -shared -O2 -target x86_64-windows-gnu tools/testplugin/lynx_test_vst2.c -o "LYNX Test Synth.dll"
+ *   LYNX.exe --vst2test "LYNX Test Synth.dll" report.txt
+ * Sound: a sine at the played note, amplitude = parameter 0 ("Gain") × velocity.
+ * Parameter 1 ("Tempo") reports the host tempo / 1000 it last read through audioMasterGetTime.
+ * State: a program chunk ('LXV2' + gain + last tempo/1000), so a host must restore it with effSetChunk.
+ */
+#include <math.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+typedef struct Effect Effect;
+typedef intptr_t (*HostCallback) (Effect*, int32_t, int32_t, intptr_t, void*, float);
+
+struct Effect
+{
+    int32_t magic;
+    intptr_t (*dispatcher) (Effect*, int32_t, int32_t, intptr_t, void*, float);
+    void (*process) (Effect*, float**, float**, int32_t);
+    void (*setParameter) (Effect*, int32_t, float);
+    float (*getParameter) (Effect*, int32_t);
+    int32_t numPrograms, numParams, numInputs, numOutputs, flags;
+    intptr_t resvd1, resvd2;
+    int32_t initialDelay, realQualities, offQualities;
+    float ioRatio;
+    void* object;
+    void* user;
+    int32_t uniqueId, version;
+    void (*processReplacing) (Effect*, float**, float**, int32_t);
+    void* processDoubleReplacing;
+    char future[56];
+};
+
+typedef struct
+{
+    int32_t type, byteSize, deltaFrames, flags, noteLength, noteOffset;
+    unsigned char data[4];
+    char detune, noteOffVelocity, r1, r2;
+} MidiEvent;
+
+typedef struct
+{
+    int32_t numEvents;
+    intptr_t reserved;
+    MidiEvent* events[2];
+} Events;
+
+typedef struct
+{
+    double samplePos, sampleRate, nanoSeconds, ppqPos, tempo, barStartPos, cycleStartPos, cycleEndPos;
+    int32_t num, den, smpteOffset, smpteFrameRate, samplesToNextClock, flags;
+} TimeInfo;
+
+typedef struct
+{
+    Effect effect;
+    HostCallback host;
+    float gain, tempo, rate;
+    int note;
+    float amplitude;
+    double phase;
+    unsigned char chunk[12];
+} Synth;
+
+static intptr_t dispatch (Effect* e, int32_t op, int32_t index, intptr_t value, void* ptr, float opt)
+{
+    Synth* s = (Synth*) e->object;
+    (void) index;
+    switch (op)
+    {
+        case 1: free (s); return 0;                                 /* close */
+        case 10: s->rate = opt; return 0;                           /* setSampleRate */
+        case 8: strcpy ((char*) ptr, index == 0 ? "Gain" : "Tempo"); return 0; /* getParamName */
+        case 23:                                                    /* getChunk */
+            memcpy (s->chunk, "LXV2", 4);
+            memcpy (s->chunk + 4, &s->gain, 4);
+            memcpy (s->chunk + 8, &s->tempo, 4); /* what the host's time info said (for the host test) */
+            *(void**) ptr = s->chunk;
+            return 12;
+        case 24:                                                    /* setChunk */
+            if (value >= 8 && memcmp (ptr, "LXV2", 4) == 0)
+                memcpy (&s->gain, (char*) ptr + 4, 4);
+            return 1;
+        case 25:                                                    /* processEvents */
+        {
+            Events* ev = (Events*) ptr;
+            for (int i = 0; i < ev->numEvents; ++i)
+            {
+                const unsigned char* d = ev->events[i]->data;
+                if ((d[0] & 0xF0) == 0x90 && d[2] > 0) { s->note = d[1]; s->amplitude = d[2] / 127.0f; }
+                else if ((d[0] & 0xF0) == 0x80 || ((d[0] & 0xF0) == 0x90 && d[2] == 0)) { if (d[1] == s->note) s->amplitude = 0.0f; }
+            }
+            return 1;
+        }
+        case 35: return 2;                                          /* getPlugCategory: synth */
+        case 45: strcpy ((char*) ptr, "LYNX Test Synth"); return 1; /* getEffectName */
+        case 47: strcpy ((char*) ptr, "LYNX"); return 1;            /* getVendorString */
+        case 58: return 2400;                                       /* getVstVersion */
+        default: return 0;
+    }
+}
+
+static void setParam (Effect* e, int32_t i, float v)
+{
+    Synth* s = (Synth*) e->object;
+    if (i == 0) s->gain = v;
+}
+
+static float getParam (Effect* e, int32_t i)
+{
+    Synth* s = (Synth*) e->object;
+    return i == 0 ? s->gain : s->tempo;
+}
+
+static void processReplacing (Effect* e, float** in, float** out, int32_t n)
+{
+    Synth* s = (Synth*) e->object;
+    (void) in;
+    const TimeInfo* t = (const TimeInfo*) s->host (e, 7, 0, 0, 0, 0.0f);
+    if (t != 0 && (t->flags & (1 << 10)))
+        s->tempo = (float) (t->tempo / 1000.0);
+    const double step = 440.0 * pow (2.0, (s->note - 69) / 12.0) / (s->rate > 0 ? s->rate : 44100.0);
+    for (int32_t i = 0; i < n; ++i)
+    {
+        const float v = s->gain * s->amplitude * (float) sin (2.0 * 3.14159265358979 * s->phase);
+        s->phase += step;
+        if (s->phase >= 1.0) s->phase -= 1.0;
+        out[0][i] = v;
+        out[1][i] = v;
+    }
+}
+
+__declspec (dllexport) Effect* VSTPluginMain (HostCallback host)
+{
+    Synth* s = (Synth*) calloc (1, sizeof (Synth));
+    if (s == 0 || host (0, 1, 0, 0, 0, 0.0f) == 0) /* audioMasterVersion */
+        return 0;
+    s->host = host;
+    s->gain = 0.5f;
+    s->rate = 44100.0f;
+    s->note = 69;
+    s->effect.magic = 0x56737450;
+    s->effect.dispatcher = dispatch;
+    s->effect.setParameter = setParam;
+    s->effect.getParameter = getParam;
+    s->effect.processReplacing = processReplacing;
+    s->effect.numPrograms = 1;
+    s->effect.numParams = 2;
+    s->effect.numInputs = 0;
+    s->effect.numOutputs = 2;
+    s->effect.flags = (1 << 4) | (1 << 5) | (1 << 8); /* replacing, program chunks, synth */
+    s->effect.object = s;
+    s->effect.uniqueId = 0x4C585632;                    /* 'LXV2' */
+    s->effect.version = 1;
+    return &s->effect;
+}

Algúns arquivos non se mostraron porque demasiados arquivos cambiaron neste cambio