فهرست منبع

Merge remote-tracking branch 'origin/main' into feature/input88

# Conflicts:
#	src/core/RackRenderer.h
#	src/engine/ChannelRackProcessor.h
#	src/ui/I18nData.h
#	tests/tests.cpp
Ka1-S 1 ماه پیش
والد
کامیت
d3742e4afe
52فایلهای تغییر یافته به همراه6283 افزوده شده و 2996 حذف شده
  1. 1 0
      CMakeLists.txt
  2. 6 1
      docs/analise/REA_rodada2.md
  3. 189 0
      docs/analise/REA_rodada87.md
  4. 130 0
      docs/analise/REA_rodada89.md
  5. 18 7
      resources/i18n/pt-BR.txt
  6. 1 1
      scripts/build-windows-zig.sh
  7. 161 0
      src/Main.cpp
  8. 158 20
      src/core/ConvolverFx.cpp
  9. 2 0
      src/core/Effects.cpp
  10. 109 0
      src/core/FlWrapper.cpp
  11. 24 0
      src/core/FlWrapper.h
  12. 46 6
      src/core/FlpImport.cpp
  13. 16 2
      src/core/FrequencySplitter.cpp
  14. 1 0
      src/core/FrequencySplitter.h
  15. 4 2
      src/core/HarmlessFx.cpp
  16. 19 1
      src/core/Instruments.cpp
  17. 14 0
      src/core/Instruments.h
  18. 68 16
      src/core/ParametricEqLinear.cpp
  19. 9 0
      src/core/ParametricEqLinear.h
  20. 17 0
      src/core/Preferences.cpp
  21. 5 0
      src/core/Preferences.h
  22. 120 1
      src/core/RackRenderer.cpp
  23. 21 1
      src/core/RackRenderer.h
  24. 110 0
      src/core/RtStats.h
  25. 127 12
      src/core/WorkerPool.cpp
  26. 24 5
      src/core/WorkerPool.h
  27. 196 9
      src/engine/AudioEngine.cpp
  28. 44 1
      src/engine/AudioEngine.h
  29. 2 0
      src/engine/ChannelRackProcessor.h
  30. 2 0
      src/engine/ClapFormat.cpp
  31. 1 1
      src/engine/ClapFormat.h
  32. 94 5
      src/engine/PluginHost.cpp
  33. 11 2
      src/engine/PluginHost.h
  34. 818 0
      src/engine/Vst2Format.cpp
  35. 36 0
      src/engine/Vst2Format.h
  36. 28 7
      src/flp/Flp.cpp
  37. 7 1
      src/flp/Flp.h
  38. 2 2
      src/ui/ChannelRackComponent.cpp
  39. 2874 2872
      src/ui/I18nData.h
  40. 18 2
      src/ui/MainComponent.cpp
  41. 2 1
      src/ui/MissingFilesDialog.cpp
  42. 1 1
      src/ui/MixerComponent.cpp
  43. 2 2
      src/ui/PluginWindow.cpp
  44. 1 1
      src/ui/SettingsDialog.cpp
  45. 6 2
      src/ui/SettingsPages.cpp
  46. 1 1
      src/ui/SetupWizard.cpp
  47. 30 1
      src/ui/Toolbar.cpp
  48. 7 0
      src/ui/Toolbar.h
  49. 39 0
      tests/ConvolverTests.inc
  50. 355 7
      tests/tests.cpp
  51. 148 3
      tools/renderwav.cpp
  52. 158 0
      tools/testplugin/lynx_test_vst2.c

+ 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]**
 

+ 189 - 0
docs/analise/REA_rodada87.md

@@ -0,0 +1,189 @@
+# Round 87: audio crackles during playback ("picotando") — real-time audit, fixes and instrumentation
+
+Branch `feature/glitch87`. English, clean-room (FL Studio's engine was only inspected for *how* it schedules its
+audio threads; no Image-Line code is in the repository).
+
+User report (v0.1.5): real-world FL projects (a friend's `.flp` files with samples, native FL plugin ports, maybe
+VSTs) crackle on playback on a strong 12-core Windows PC.
+
+Evidence markers: **[MEASURED]** numbers from our tools on this machine, **[DECOMP]** disassembly of
+`FLEngine_x64.dll`, **[CODE]** reading of LYNX / JUCE / libc++ sources, **[model]** our interpretation,
+**not confirmed** where unknown.
+
+Work dir: `~/.claude/jobs/f8789b49/tmp/r87/` (scripts `brw2.sh` Linux renderwav, `bwin.sh` Windows renderwav with
+`OLDPOOL=1` for main's worker pool, `perfattach.sh` render-phase `perf`, `py/prof.py` symbolizer, `survey.sh` all
+demos, `ba.sh` before/after).
+
+## 1. Causes found
+
+### 1.0 Patchers were rebuilt about twice a second during playback (clicks + a frozen UI)
+
+[MEASURED] `--rtstress` on *Astes – Bien Duro* (window hidden): the engine's 30 Hz timer ran **1.6 times a second**
+(longest gap 713 ms) and the PDC plan was rebuilt **18 times in 10 s** ("unit 344: 0 → 1536 samples").
+[CODE] Two defects fed each other:
+
+1. `RackState::build` never reused a parallel container (FL's Patcher, `EffectKind::parallel`): every snapshot —
+   every knob turn, and every PDC re-plan — built a new Patcher, i.e. new children with empty reverb tails, delay
+   lines and linear-phase convolvers.
+2. A fresh Frequency Splitter in linear-phase mode reported latency 0 until its first block applied its parameters,
+   then 3n/4 (1536). The engine's timer sees a latency change → publishes a new snapshot (re-planned PDC: delay lines
+   of new lengths, i.e. emptied) → which rebuilds the Patcher → whose splitter reports 0 again → …
+
+So any project with a Patcher holding a linear-phase splitter/EQ re-planned forever: each round cost a full
+`RackState::build` on the UI thread (~0.6 s for this project: the UI froze between rounds) and, on the audio side,
+restarted the Patcher's effects and emptied the PDC delay lines of every edge whose length changed — audible
+dropouts/clicks roughly twice a second.
+
+Fix: a container is reused when its branches, children (kind, enabled, parameters, mix, state, sample, plugin id,
+side-chains, nested containers) and links are unchanged (`sameContainer`); the Frequency Splitter built from a slot
+reports its latency from the slot's parameters before its first block. After the fix: the timer runs at 30.0/s
+(longest gap 35 ms), one PDC re-plan right after loading (effects whose latency is known only after their first
+block — Fruity Limiter 0→88, Multiband Compressor 0→52, Pitch Shifter, Pitch correction 9→257, Compressor 64→0 —
+listed by `renderwav` for every demo; **not changed**, they re-plan once when added). Test
+`patcher_container_is_reused_across_snapshots`.
+
+### 1.1 The linear-phase FFT convolver evaluated sin/cos for every butterfly (most of a heavy project's CPU)
+
+[MEASURED] `perf` on the render phase of *Astes – Bien Duro* (262 channels, 71 inserts with effects): **55.6 %** of
+all samples inside `peqfl::FftConvolver::block()` — the block FFT convolution shared by Parametric EQ 2's linear-phase
+mode, Frequency Splitter's linear-phase crossover and Maximus's linear-phase band split. Its radix-2 FFT called
+`std::polar(1, angle)` (one `sin` + one `cos`, with range reduction) **per butterfly** and multiplied through
+`std::complex`'s NaN-recovery path; `block()` also allocated a `std::vector` on the audio thread every hop.
+Per-unit profile: one Patcher holding linear-phase splitters/EQs took **135 % of real time on its own** (more than a
+core), a Frequency Splitter 34 %.
+
+Fix: the twiddle factors are computed once per FFT size (same `std::polar` values, shared table), the complex product is
+written out for finite values (same expression order, contraction off), and the scratch buffers are preallocated.
+**The output is bit-identical** (`cmp` of 10 s raw renders before/after) and the single-thread CPU of that project went
+from a mean of 65–75 % of the deadline to ~35–40 % (§3).
+
+### 1.2 Fruity Convolver computed all its partition levels on the same sample (15 ms spikes)
+
+[MEASURED] Per-unit "longest single call": Fruity Convolver 14–16 ms in *Bombs Away*, *Edlan & Ella Noël*,
+*LollieVox* — longer than a whole 512-sample deadline (11.6 ms) in one call, every 16384 samples. [CODE] The
+zero-latency partitioned convolver (levels of 128/1024/8192/16384) ran every level whose block began on that sample,
+so at multiples of 16384 all four levels did their FFTs and multiply-accumulates at once.
+
+Fix: the larger levels' partitions now start at twice their size or later (128-level: 128…2048, 1024-level:
+2048…16384, 8192-level: 16384…65536, 16384-level: 65536…), so a level's output for block *b* depends only on input
+up to block *b−1*; that output is computed **during block b−1, a slice every 128 samples** (input copy, bit reversal,
+each FFT pass, each partition's multiply-accumulate, the inverse passes and the output are separate slices). Zero
+latency is kept; the convolution is the same (new test `convolver_long_kernel_matches_direct_convolution`: a sparse
+100 001-tap kernel spanning every level matches direct convolution within 2e-5; the FL goldens of
+`convolver_engine` still pass).
+
+### 1.3 The worker pool's wake-up was Sleep() polling on Windows
+
+[CODE] `WorkerPool` woke its threads with `std::counting_semaphore`. In the Windows build (Zig 0.14.1, libc++ for
+`x86_64-windows-gnu`) libc++ has no platform wait for Windows (`src/atomic.cpp`: only Linux futex, Apple ulock,
+FreeBSD umtx); the fallback polls with `__libcpp_timed_backoff_policy`: after 64 µs it sleeps `elapsed/2`, rounded
+**up** to whole milliseconds by `__libcpp_thread_sleep_for` (`Sleep(ceil(ms))`), and `Sleep(8)` after 128 ms. A
+worker idle between two audio blocks therefore woke **1–8 ms late**, often after the block's work was over: the
+audio thread did nearly everything alone, and the polling workers kept waking at MMCSS priority.
+
+Fix: workers spin briefly (250 µs, `_mm_pause`) after finishing — the next `parallelFor` of the same block (next mixer
+layer, next 128-sample automation chunk) comes microseconds later — then block on a real OS semaphore (Win32
+`CreateSemaphore`/`WaitForSingleObject`; the futex-backed `std::counting_semaphore` elsewhere). `run()` releases only
+as many permits as there are sleeping workers. New test `worker_pool_wakes_sleeping_workers`.
+
+[DECOMP] FL does the same kind of thing: a worker thread routine in `FLEngine_x64.dll` (`0xbb0920`) loads
+`AvSetMmThreadCharacteristicsW` / `AvSetMmThreadPriority` dynamically (names at `0x65d490`/`0x65d4cc`, stored at
+`0x15f40f8`/`0x15f4100` by the loader at `0x65cca6…`), registers the thread as **"Pro Audio"** (UTF-16 string at
+`0xbb0a28`), sets **`AVRT_PRIORITY_HIGH`** (`edx = 1`) and then loops waiting on an event object with an infinite
+timeout before each job. LYNX's workers now also call `AvSetMmThreadPriority(HIGH)` after joining "Pro Audio"
+(the JUCE WASAPI thread uses `AVRT_PRIORITY_NORMAL`). Which FL job types run on this thread class (mixer vs generator
+threads) is **not confirmed**. FL's option strings: "Multithreaded generator processing", "Multithreaded mixer
+processing", "Allow smart disable", "Buffer length %dsmp (%dms)" [DATA, strings].
+
+[MEASURED] Windows renderwav (real-time paced blocks of 512, 7 workers, *Astes*, after §1.1): main's pool p99 69–85 %,
+max 122–134 %, 1–4 blocks over the deadline; new pool p99 70 %, max 114 % (the first block only), 1 over. The pool is
+not the whole story on this project (its critical path is a few heavy serial inserts), but the late wake-ups are gone.
+
+### 1.4 Smaller findings
+
+- First block after playback starts: 2–3× the deadline in most demos [MEASURED] — one-time initialisation of the
+  effects' first `process()` (e.g. Fruity Delay 3's `settle()`, ~2.4 ms per instance). One possible click at the very
+  start of playback; **not changed** in this round.
+- `RackRenderer::process` prepares a snapshot's instruments/effects on the audio thread if the snapshot was built for
+  another sample rate (e.g. right after the device's rate changes): a Convolver/Delay 3 then allocates and builds
+  kernels on the audio thread. Rare (device rate change), **not changed** (the offline export relies on it).
+- Heavy units found by the survey (single-thread share of real time, demos): Fruity Convolver, Patchers with
+  linear-phase EQs (fixed above), Harmless pads (*Harmless Essentials*: mean 49 %, p99 166 % single-thread — needs
+  the workers), Sytrus/Ogun voices with 10–20 ms single calls at note starts (*Midnight Lady* Ogun 21 ms, *Classic
+  rave* 17 ms) **not investigated further**.
+- UI: the Playlist/Piano Roll/Channel Rack timers already repaint only the playhead columns; meters use relaxed
+  atomics; the snapshot exchange is lock-free; MIDI prefs use a spin lock the audio thread never takes. No lock shared
+  between the UI and the audio callback was found. Disk: samples above 30 s are memory-mapped disk caches that a
+  prefetch thread reads 4 s ahead (song mode); page faults remain possible after a seek **[model]**.
+- Default device: with no saved setup JUCE opened the default WASAPI shared device with its default period (typically
+  480 samples = 10 ms at 48 kHz). A fresh install now asks for **512 samples at 44.1/48 kHz** (1024 at 88.2/96 kHz)
+  when offered (`prefs::safeBufferSize`); a saved setup is untouched.
+
+## 2. Instrumentation (so the user can tell us)
+
+- `core/RtStats.h`: the audio callback records its duration against its deadline (buffer / rate): callbacks,
+  over-deadline count, 80–100 % count, late device calls (start-to-start gap > 1.9 deadlines + 2 ms), max and average
+  load, a 10 %-step histogram. Relaxed atomics only.
+- `RackRenderer` per-unit profile (`setProfiling`): CPU time and longest single call per channel and per insert effect
+  slot (two clock reads per active unit and chunk; on in the app).
+- App: the CPU meter's hint shows the over-deadline / late-call counts, the peak load and the three heaviest
+  channels/effects; the bar gets a peak mark and a red outline for 5 s after a missed deadline. Settings › Audio shows
+  "N blocks over the deadline (max X%)". `%APPDATA%\LYNX\audio-glitches.log` gets a line (at most every 2 s) whenever
+  callbacks miss the deadline or the device calls late: time, bar, device/type/rate/buffer/latency/driver dropouts,
+  the counters and the heaviest units.
+- `LYNX.exe --rtstress project.(flp|lynx) report.txt [seconds] [--buffer N]`: the normal window and the saved audio
+  device play the project from the start and the report lists the device, CPU, the counters, the histogram and the
+  heaviest units; `result=OK` / `GLITCHES`.
+- `renderwav` (build-local, also built for Windows by `tmp/r87/bwin.sh`): `LYNX_BLOCK`, `LYNX_THREADS`,
+  `LYNX_REALTIME=1` (blocks paced at real time so workers sleep between blocks as with a sound card),
+  `LYNX_PROFILE=1` (per-unit table + longest calls), `LYNX_PROFILE_CPU=1` (Linux: thread CPU clock for units); block
+  timing report (mean/p50/p99/max of the deadline, over-budget count, slowest block positions).
+
+## 3. Results
+
+**Core, single thread** [MEASURED] (`renderwav`, live quality, 512-sample blocks, first 20 s of the song; `before` =
+main + the instrumentation only, `after` = this branch without the app-side fixes, which renderwav does not exercise).
+Instructions retired (`perf stat`, independent of the machine's load, includes loading) and the thread-CPU share of the
+11.61 ms deadline per block (noisy on this shared machine):
+
+| Project | Instructions before → after | Blocks over the deadline before → after | p99 before → after |
+|---|---|---|---|
+| Astes – Bien Duro | 92.9 G → 51.7 G | 183 → 1 (of 1723) | 181 % → 68 % |
+| Purps On The Beat – Stroll Up | 124.1 G → 46.1 G | 1018 → 7 | 192 % → 94 % |
+| Bombs Away – I'm Awake | 44.8 G → 42.7 G | 46 → 3 | 137 % → 80 % |
+| LollieVox – I'll Be Your Madonna | 45.8 G → 41.9 G | 55 → 6 | 137 % → 88 % |
+| Edlan & Ella Noël – Song For You | 28.4 G → 26.3 G | 55 → 1 | 110 % → 43 % |
+| Olbaid – Harmless Essentials (control) | 44.50 G → 44.50 G | 20 → 43 (noise) | 103 % → 110 % |
+
+The 10 s raw render of *Astes* is bit-identical before/after the FFT change (`cmp`); the convolver's levels change
+the float summation order only (tests within 2e-5 of the FL goldens / of direct convolution).
+
+**App, Windows** [MEASURED] (`LYNX.exe --rtstress … 10`, this PC: Ryzen 5 3600, 6 cores / 12 threads, WASAPI shared,
+48 kHz, 512 samples = 10.67 ms, 7 workers, window shown):
+
+| Project | Over deadline | Average / max load | UI timer |
+|---|---|---|---|
+| Astes – Bien Duro (before the Patcher fix, window hidden) | 0 | 17 % / 65–85 % | 1.6/s, gaps 0.7 s, 18 PDC re-plans |
+| Astes – Bien Duro | 0 | 14–17 % / 42–44 % | 30/s, 1 re-plan at load |
+| Bombs Away | 0 | 18 % / 44 % | 30/s |
+| LollieVox | 0 | 22 % / 42 % | 30/s |
+| Purps On The Beat | 0 | 35 % / 59 % | 30/s |
+| Harmless Essentials | 0 | 7 % / 14 % | 30/s |
+| Astes at 256 samples (5.33 ms) | 18 in 10 s | 42 % / 148 % | — |
+
+The "load" here is the callback's time against its deadline, so with 7 workers it is far below the single-thread
+figures above. At 256 samples the heaviest demo still misses deadlines on this 6-core PC: the 512 default is
+justified; the glitch log also records one missed deadline right after loading (stopped, the effects' first block).
+
+## Where I stopped / next steps
+
+- Ask the user to run `LYNX.exe --rtstress "<friend's project>.flp" report.txt 30` (and send `report.txt` plus
+  `%APPDATA%\LYNX\audio-glitches.log`): the report names the device, the deadline misses, late device calls and the
+  heaviest channels/effects of *their* projects (VST plugins included).
+- Effects whose latency is known only after their first block (Limiter, Multiband Compressor, Pitch Shifter, Pitch
+  correction, Compressor) still re-plan PDC once when created; computing it at construction would avoid that click.
+- The first block after loading costs 2–3 deadlines (effects' first-block set-up, e.g. Delay 3's `settle()`).
+- Per-note start cost of Sytrus / Ogun voices (10–20 ms single calls in the survey) and Harmless pads.
+- `RackRenderer` still prepares a snapshot built for another sample rate on the audio thread (device rate change).
+- The two per-unit timers (round 84's `ProcessTimes` for the Plugin performance monitor, this round's `UnitTimes`) could
+  be merged.

+ 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`).

+ 18 - 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)"
@@ -1513,6 +1512,10 @@ countries: br
 "{0} is running: {1} Hz, output latency {2} ms" = "{0} está rodando: {1} Hz, latência de saída {2} ms"
 "Audio CPU load: {0}%" = "Carga de CPU do áudio: {0}%"
 "{0} dropouts (buffer underruns) so far" = "{0} falhas (buffer esvaziado) até agora"
+"{0} blocks over the deadline (max {1}%)" = "{0} blocos passaram do prazo (máx. {1}%)"
+"{0} audio blocks missed the deadline (crackles), the device called late {1} times; log: audio-glitches.log" = "{0} blocos de áudio passaram do prazo (estalos), o dispositivo chamou atrasado {1} vezes; registro: audio-glitches.log"
+"Heaviest: {0}" = "Mais pesados: {0}"
+"peak {0}%" = "pico {0}%"
 "Audio device" = "Dispositivo de áudio"
 "Driver settings..." = "Configurações do driver..."
 "Play a test sound" = "Tocar um som de teste"
@@ -1603,6 +1606,14 @@ countries: br
 "Input channels: none open. Choose an input device above to record a microphone or an instrument." = "Canais de entrada: nenhum aberto. Escolha um dispositivo de entrada acima para gravar um microfone ou um instrumento."
 "Input channels ({0}): {1}" = "Canais de entrada ({0}): {1}"
 
+# 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

+ 161 - 0
src/Main.cpp

@@ -96,6 +96,18 @@ public:
             return;
         }
 
+        if (args.contains ("--rtstress"))
+        {
+            // LYNX.exe --rtstress project.(flp|lynx) report.txt [seconds] [--buffer N] [--no-window]: the real app (window, audio device)
+            // plays the project and reports the callbacks that missed their deadline (REA round 87)
+            const auto i = args.indexOf ("--rtstress");
+            const auto seconds = args[i + 3].getDoubleValue();
+            const auto buffer = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 0;
+            juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
+            runRealtimeStress (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), seconds > 0.0 ? seconds : 30.0, buffer);
+            return;
+        }
+
         if (args.contains ("--selftest"))
         {
             const auto i = args.indexOf ("--selftest");
@@ -341,6 +353,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");
@@ -776,6 +795,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.
@@ -1177,6 +1264,80 @@ private:
         quit();
     }
 
+    // --rtstress: opens the project in the normal window with the saved audio device, plays it from the start for
+    // `seconds` and writes the real-time statistics (deadline misses, late device calls, load histogram, heaviest units)
+    void runRealtimeStress (const juce::File& project, const juce::File& report, double seconds, int bufferSize)
+    {
+        startupOptions = lynx::StartupOptions::load();
+        engine = std::make_unique<lynx::AudioEngine>();
+        crashEngine = engine.get();
+        if (bufferSize > 0)
+        {
+            auto setup = engine->getDeviceManager().getAudioDeviceSetup();
+            setup.bufferSize = bufferSize;
+            engine->getDeviceManager().setAudioDeviceSetup (setup, true);
+        }
+        createMainWindow();
+        if (! juce::JUCEApplication::getCommandLineParameters().contains ("--no-window")) // --no-window: is it the UI?
+            mainWindow->reveal();
+
+        juce::String error;
+        auto ok = false;
+        const auto loadStart = juce::Time::getMillisecondCounterHiRes();
+        if (project.hasFileExtension ("flp"))
+            ok = engine->importFlpFile (project, error);
+        else if (auto song = lynx::ProjectFile::load (project, error))
+        {
+            engine->setSong (std::move (*song));
+            ok = true;
+        }
+        const auto loadMs = juce::Time::getMillisecondCounterHiRes() - loadStart;
+
+        if (! ok)
+        {
+            report.replaceWithText ("project: " + project.getFullPathName() + "\nresult=ERROR " + error + "\n");
+            setApplicationReturnValue (1);
+            quit();
+            return;
+        }
+
+        // let the window draw the project, then play from the start with fresh statistics
+        juce::Timer::callAfterDelay (1500, [this, project, report, seconds, loadMs] {
+            if (engine == nullptr)
+                return;
+            engine->stop();
+            engine->rewind();
+            engine->getRtStats().reset();
+            engine->takeUiPulse();
+            engine->play();
+            juce::Timer::callAfterDelay ((int) (seconds * 1000.0), [this, project, report, seconds, loadMs] {
+                if (engine == nullptr)
+                    return;
+                engine->stop();
+                const auto s = engine->getRtStats().snapshot();
+                juce::String text;
+                text << "project: " << project.getFullPathName() << "\n"
+                     << "LYNX " << getApplicationVersion() << ", " << juce::SystemStats::getOperatingSystemName() << ", "
+                     << juce::SystemStats::getNumCpus() << " logical CPUs (" << juce::SystemStats::getNumPhysicalCpus() << " cores), "
+                     << juce::SystemStats::getCpuModel() << "\n"
+                     << "load " << juce::String (loadMs / 1000.0, 1) << " s, played " << juce::String (seconds, 0) << " s\n"
+                     << engine->describeRealtime();
+                const auto pulse = engine->takeUiPulse();
+                text << "  UI: the 30 Hz engine timer ran " << pulse.calls << " times (" << juce::String (pulse.calls / seconds, 1)
+                     << "/s), longest gap " << juce::String (pulse.maxGapMs, 0) << " ms" << (mainWindow == nullptr || ! mainWindow->isVisible() ? " (window hidden)" : "") << "\n";
+                text << "  load histogram (share of the deadline: callbacks):";
+                for (std::size_t b = 0; b < s.histogram.size(); ++b)
+                    if (s.histogram[b] > 0)
+                        text << " " << (int) (b * 10) << (b + 1 == s.histogram.size() ? juce::String ("+") : "-" + juce::String ((int) (b * 10 + 10))) << "%:" << (juce::int64) s.histogram[b];
+                text << "\n";
+                text << "result=" << (s.callbacks == 0 ? "ERROR no audio callbacks" : s.overBudget == 0 && s.lateCalls == 0 ? "OK" : "GLITCHES") << "\n";
+                report.replaceWithText (text);
+                setApplicationReturnValue (s.callbacks == 0 ? 1 : 0);
+                quit();
+            });
+        });
+    }
+
     // LYNX.exe --render project.(flp|lynx) output.wav [seconds]
     // Exports the current pattern to 24-bit WAV (for an imported .flp, the one with the most notes).
     void runRender (const juce::String& inputPath, const juce::String& outputPath, double seconds)

+ 158 - 20
src/core/ConvolverFx.cpp

@@ -48,6 +48,13 @@ float f32At (const std::vector<std::uint8_t>& d, std::size_t o) noexcept
     return v;
 }
 
+// (a + bi)(c + di) for finite values, without std::complex's NaN/infinity recovery branch (a hot loop)
+inline cd mul (const cd& z, const cd& w) noexcept
+{
+    const double a = z.real(), b = z.imag(), c = w.real(), d = w.imag();
+    return { a * c - b * d, a * d + b * c };
+}
+
 // ---------------------------------------------------------------------------------------------- radix-2 FFT
 class Fft
 {
@@ -73,24 +80,38 @@ public:
     int size() const noexcept { return n; }
     // in place; the inverse is unscaled
     void run (cd* a, bool inverse) const noexcept
+    {
+        bitReverse (a);
+        for (int len = 2; len <= n; len <<= 1)
+            pass (a, len, inverse);
+    }
+    // the transform in pieces (a large one spread over an audio block): the reordering, then log2(n) passes
+    int passes() const noexcept
+    {
+        int p = 0;
+        for (int len = 2; len <= n; len <<= 1)
+            ++p;
+        return p;
+    }
+    void bitReverse (cd* a) const noexcept
     {
         for (int i = 0; i < n; ++i)
             if (i < rev[(std::size_t) i])
                 std::swap (a[i], a[rev[(std::size_t) i]]);
-        for (int len = 2; len <= n; len <<= 1)
-        {
-            const int half = len / 2, step = n / len;
-            for (int i = 0; i < n; i += len)
-                for (int j = 0; j < half; ++j)
-                {
-                    cd w = tw[(std::size_t) (j * step)];
-                    if (inverse)
-                        w = std::conj (w);
-                    const cd u = a[i + j], v = a[i + j + half] * w;
-                    a[i + j] = u + v;
-                    a[i + j + half] = u - v;
-                }
-        }
+    }
+    void pass (cd* a, int len, bool inverse) const noexcept
+    {
+        const int half = len / 2, step = n / len;
+        for (int i = 0; i < n; i += len)
+            for (int j = 0; j < half; ++j)
+            {
+                cd w = tw[(std::size_t) (j * step)];
+                if (inverse)
+                    w = std::conj (w);
+                const cd u = a[i + j], v = mul (a[i + j + half], w);
+                a[i + j] = u + v;
+                a[i + j + half] = u - v;
+            }
     }
 
 private:
@@ -255,8 +276,11 @@ bool flat (const std::vector<EnvPoint>& e, double& level) noexcept
 }
 
 // ------------------------------------------------------------------------------- partitioned convolution
-// Zero-latency stereo convolution: a direct head, then uniformly partitioned overlap-save levels whose partitions
-// never start before their own size (so each level's output is ready when its block begins).
+// Zero-latency stereo convolution: a direct head, then uniformly partitioned overlap-save levels. The 128-sample level's
+// partitions start at its own size (its output is computed when its block begins); the larger levels' partitions start
+// at twice their size or later, so a block's output can be computed during the previous block, a slice every 128
+// samples (REA round 87: computing every level at once on the same sample took ~15 ms in one audio callback — a
+// crackle — once every 16384 samples).
 class Convolver
 {
 public:
@@ -269,8 +293,8 @@ public:
             headL[i] = i < kl.size() ? kl[i] : 0.0f, headR[i] = i < kr.size() ? kr[i] : 0.0f;
         levels.clear();
         static const int sizes[] = { 128, 1024, 8192, 16384 };
-        static const int starts[] = { 128, 1024, 8192, 65536 };
-        static const int ends[] = { 1024, 8192, 65536, 1 << 30 };
+        static const int starts[] = { 128, 2048, 16384, 65536 };
+        static const int ends[] = { 2048, 16384, 65536, 1 << 30 };
         for (int k = 0; k < 4; ++k)
         {
             if ((std::size_t) starts[k] >= len)
@@ -301,6 +325,11 @@ public:
             lv.xl.assign ((std::size_t) (lv.ages * bins), {});
             lv.xr.assign ((std::size_t) (lv.ages * bins), {});
             lv.out.assign ((std::size_t) (2 * lv.N), 0.0f);
+            lv.next.assign ((std::size_t) (2 * lv.N), 0.0f);
+            lv.spread = lv.j0 >= 2;
+            // the job's slices: copy + reorder + passes of the forward transform, one per partition, the inverse's
+            // reorder + passes, and the output
+            lv.units = 1 + 1 + lv.fft->passes() + lv.parts + 1 + 1 + lv.fft->passes() + 1;
             lv.work.assign ((std::size_t) (2 * lv.N), {});
             lv.accL.assign ((std::size_t) bins, {});
             lv.accR.assign ((std::size_t) bins, {});
@@ -324,7 +353,9 @@ public:
             std::fill (lv.xl.begin(), lv.xl.end(), cd {});
             std::fill (lv.xr.begin(), lv.xr.end(), cd {});
             std::fill (lv.out.begin(), lv.out.end(), 0.0f);
+            std::fill (lv.next.begin(), lv.next.end(), 0.0f);
             lv.newest = 0;
+            lv.done = lv.units; // no job in progress
         }
         t = 0;
     }
@@ -337,8 +368,23 @@ public:
         {
             if ((t & 127) == 0)
                 for (auto& lv : levels)
-                    if (t % lv.N == 0)
-                        step (lv);
+                {
+                    const auto phase = (int) (t % lv.N);
+                    if (! lv.spread)
+                    {
+                        if (phase == 0)
+                            step (lv);
+                        continue;
+                    }
+                    if (phase == 0)
+                    {
+                        advance (lv, lv.units); // (normally already complete)
+                        std::swap (lv.out, lv.next);
+                        startJob (lv);
+                    }
+                    // this 128-sample slice's share of the job: complete before the level's next block
+                    advance (lv, (int) (((long long) lv.units * (phase + 128) + lv.N - 1) / lv.N));
+                }
             const int w = (int) (t & mask);
             histL[(std::size_t) w] = l[s];
             histR[(std::size_t) w] = r[s];
@@ -369,8 +415,100 @@ private:
         std::vector<std::complex<float>> hl, hr, xl, xr; // spectra (N + 1 bins) of the partitions / of the inputs
         std::vector<cd> work, accL, accR;
         std::vector<float> out; // [0, N) left, [N, 2N) right: the level's output for the current block
+        // spread levels: the next block's output, built during the current one by `units` slices (`done` so far)
+        std::vector<float> next;
+        bool spread = false;
+        int units = 0, done = 0;
     };
 
+    // a spread level's block boundary: the newest 2N inputs go into the work buffer now (the history ring is
+    // overwritten during the block); the slices then compute the output of the block after this one
+    void startJob (Level& lv) noexcept
+    {
+        const int N = lv.N, mask = ring - 1;
+        for (int i = 0; i < 2 * N; ++i)
+        {
+            const auto q = (std::size_t) ((t - 2 * N + i) & mask);
+            lv.work[(std::size_t) i] = cd (histL[q], histR[q]);
+        }
+        lv.newest = (lv.newest + lv.ages - 1) % lv.ages;
+        lv.done = 0;
+    }
+
+    void advance (Level& lv, int target) noexcept
+    {
+        const int N = lv.N, bins = N + 1, passes = lv.fft->passes();
+        target = std::min (target, lv.units);
+        while (lv.done < target)
+        {
+            int u = lv.done++;
+            // 0: (inputs copied at the boundary) reorder, then the forward passes
+            if (u == 0)
+            {
+                lv.fft->bitReverse (lv.work.data());
+                continue;
+            }
+            u -= 1;
+            if (u < passes)
+            {
+                lv.fft->pass (lv.work.data(), 2 << u, false);
+                continue;
+            }
+            u -= passes;
+            if (u == 0)
+            {
+                split (lv.work, 2 * N, lv.xl.data() + lv.newest * bins, lv.xr.data() + lv.newest * bins);
+                std::fill (lv.accL.begin(), lv.accL.end(), cd {});
+                std::fill (lv.accR.begin(), lv.accR.end(), cd {});
+                continue;
+            }
+            u -= 1;
+            if (u < lv.parts)
+            {
+                // partition p meets the input that will be j0 − 1 + p blocks old in the next block
+                const int p = u;
+                const int slot = (lv.newest + lv.j0 - 2 + p) % lv.ages;
+                const auto* xl = lv.xl.data() + slot * bins;
+                const auto* xr = lv.xr.data() + slot * bins;
+                const auto* hl = lv.hl.data() + p * bins;
+                const auto* hr = lv.hr.data() + p * bins;
+                for (int k = 0; k < bins; ++k)
+                {
+                    lv.accL[(std::size_t) k] += mul (cd (xl[k]), cd (hl[k]));
+                    lv.accR[(std::size_t) k] += mul (cd (xr[k]), cd (hr[k]));
+                }
+                continue;
+            }
+            u -= lv.parts;
+            if (u == 0)
+            {
+                for (int k = 0; k <= N; ++k)
+                    lv.work[(std::size_t) k] = lv.accL[(std::size_t) k] + cd (0.0, 1.0) * lv.accR[(std::size_t) k];
+                for (int k = N + 1; k < 2 * N; ++k)
+                    lv.work[(std::size_t) k] = std::conj (lv.accL[(std::size_t) (2 * N - k)]) + cd (0.0, 1.0) * std::conj (lv.accR[(std::size_t) (2 * N - k)]);
+                continue;
+            }
+            u -= 1;
+            if (u == 0)
+            {
+                lv.fft->bitReverse (lv.work.data());
+                continue;
+            }
+            u -= 1;
+            if (u < passes)
+            {
+                lv.fft->pass (lv.work.data(), 2 << u, true);
+                continue;
+            }
+            const double inv = 1.0 / (double) (2 * N);
+            for (int i = 0; i < N; ++i)
+            {
+                lv.next[(std::size_t) i] = (float) (lv.work[(std::size_t) (N + i)].real() * inv);
+                lv.next[(std::size_t) (N + i)] = (float) (lv.work[(std::size_t) (N + i)].imag() * inv);
+            }
+        }
+    }
+
     // spectra of the two real signals packed in z = a + ib (bins 0…N of a 2N transform)
     template <typename T>
     static void split (const std::vector<cd>& z, int size, T* a, T* b) noexcept

+ 2 - 0
src/core/Effects.cpp

@@ -2889,6 +2889,8 @@ std::unique_ptr<Effect> makeEffect (const EffectSlot& slot)
         return flshape::makeWaveShaper (slot.state);
     if (slot.kind == EffectKind::parametricEq && peq::flLaw (slot.params))
         return std::make_unique<ParametricEq> (slot.params);
+    if (slot.kind == EffectKind::frequencySplitter)
+        return fsplit::make (slot.params);
     if (slot.kind == EffectKind::hyperChorus)
         return hyperchorusfx::make (hyperchorusfx::instanceOf (slot.state));
     if (slot.kind == EffectKind::vintageChorus)

+ 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;
             }

+ 16 - 2
src/core/FrequencySplitter.cpp

@@ -735,14 +735,19 @@ namespace
 class SplitterEffect final : public Effect
 {
 public:
-    SplitterEffect()
+    // `initial`: the slot's parameters, so the latency (linear-phase mode) is known before the first block — a
+    // latency that appears only after the first block makes the host re-plan its delay compensation (REA round 87)
+    explicit SplitterEffect (const EffectParams* initial = nullptr)
     {
         for (auto& b : bands)
             b.assign ((std::size_t) maxBlock, 0.0f);
+        if (initial != nullptr)
+            expected = *initial, hasExpected = true;
     }
 
     void prepare (double sr) noexcept override
     {
+        rate = sr;
         engine.prepare (sr);
         engine.reset (true);
     }
@@ -798,9 +803,17 @@ public:
         }
     }
 
-    int latencySamples() const noexcept override { return engine.latencySamples(); }
+    int latencySamples() const noexcept override
+    {
+        if (! applied && hasExpected)
+            return (int) (expected[4] * 1.998f) == 1 ? 3 * fftSize ((int) (expected[6] * 5.994f), (float) rate) / 4 : 0;
+        return engine.latencySamples();
+    }
 
 private:
+    double rate = 44100.0;
+    EffectParams expected {};
+    bool hasExpected = false;
     Engine engine;
     std::array<float, engineParams> last {};
     bool applied = false;
@@ -809,4 +822,5 @@ private:
 } // namespace
 
 std::unique_ptr<Effect> make() { return std::make_unique<SplitterEffect>(); }
+std::unique_ptr<Effect> make (const EffectParams& params) { return std::make_unique<SplitterEffect> (&params); }
 } // namespace lynx::fsplit

+ 1 - 0
src/core/FrequencySplitter.h

@@ -76,4 +76,5 @@ private:
 };
 
 std::unique_ptr<Effect> make();
+std::unique_ptr<Effect> make (const EffectParams& params); // latency known from the slot's parameters before the first block
 } // namespace lynx::fsplit

+ 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);
 

+ 68 - 16
src/core/ParametricEqLinear.cpp

@@ -3,6 +3,9 @@
 #include <algorithm>
 #include <cmath>
 #include <cstring>
+#include <map>
+#include <memory>
+#include <mutex>
 
 // bit-exactness needs every product and sum rounded on its own (no fused multiply-add)
 #if defined(__clang__)
@@ -43,9 +46,52 @@ float pow2Approx (float y)
     return 1.0f;
 }
 
-void fft (std::vector<std::complex<double>>& a, bool inverse)
+// Twiddle factors of the radix-2 transform below for size n, stage by stage (len = 2, 4, … n: the len/2 factors
+// e^(±2πik/len) start at len/2 − 1). Built once per size and shared; the values are the ones the transform computed
+// per butterfly before (std::polar of the same angle), so the output is unchanged — only the audio thread no longer
+// evaluates a sine and a cosine for every butterfly (REA round 87: this was most of a heavy project's CPU)
+std::shared_ptr<const Twiddles> twiddlesFor (int n)
+{
+    static std::mutex lock;
+    static std::map<int, std::shared_ptr<const Twiddles>> cache;
+    const std::lock_guard<std::mutex> guard (lock);
+    auto& entry = cache[n];
+    if (entry == nullptr)
+    {
+        auto t = std::make_shared<Twiddles>();
+        for (auto* table : { &t->forward, &t->inverse })
+        {
+            const bool inverse = table == &t->inverse;
+            table->reserve ((std::size_t) std::max (0, n - 1));
+            for (std::size_t len = 2; len <= (std::size_t) n; len <<= 1)
+            {
+                const double ang = (inverse ? twoPi : -twoPi) / (double) len;
+                for (std::size_t k = 0; k < len / 2; ++k)
+                    table->push_back (std::polar (1.0, ang * (double) k));
+            }
+        }
+        entry = std::move (t);
+    }
+    return entry;
+}
+
+// (a + bi)(c + di) as std::complex computes it for finite values, without its NaN/infinity recovery branch
+inline std::complex<double> mul (const std::complex<double>& z, const std::complex<double>& w) noexcept
+{
+    const double a = z.real(), b = z.imag(), c = w.real(), d = w.imag();
+    const double ac = a * c;
+    const double bd = b * d;
+    const double ad = a * d;
+    const double bc = b * c;
+    const double x = ac - bd;
+    const double y = ad + bc;
+    if (std::isnan (x) && std::isnan (y))
+        return z * w;
+    return { x, y };
+}
+
+void fft (std::complex<double>* a, std::size_t n, const std::vector<std::complex<double>>& tw) noexcept
 {
-    const auto n = a.size();
     for (std::size_t i = 1, j = 0; i < n; ++i)
     {
         auto bit = n >> 1;
@@ -57,14 +103,14 @@ void fft (std::vector<std::complex<double>>& a, bool inverse)
     }
     for (std::size_t len = 2; len <= n; len <<= 1)
     {
-        const double ang = (inverse ? twoPi : -twoPi) / (double) len;
+        const auto* w = tw.data() + (len / 2 - 1);
+        const auto half = len / 2;
         for (std::size_t i = 0; i < n; i += len)
-            for (std::size_t k = 0; k < len / 2; ++k)
+            for (std::size_t k = 0; k < half; ++k)
             {
-                const auto w = std::polar (1.0, ang * (double) k);
-                const auto u = a[i + k], v = a[i + k + len / 2] * w;
+                const auto u = a[i + k], v = mul (a[i + k + half], w[k]);
                 a[i + k] = u + v;
-                a[i + k + len / 2] = u - v;
+                a[i + k + half] = u - v;
             }
     }
 }
@@ -242,6 +288,9 @@ void FftConvolver::init (int size)
     hop = size / 2;
     pos = 0;
     kernel.assign ((std::size_t) n, {});
+    work.assign ((std::size_t) n, {});
+    work2.assign ((std::size_t) n, {});
+    twiddles = twiddlesFor (n);
     for (int c = 0; c < 2; ++c)
     {
         in[c].assign ((std::size_t) hop, 0.0f);
@@ -263,37 +312,40 @@ void FftConvolver::setKernel (const std::vector<float>& t)
 {
     // zero-phase impulse centred at n/2: (1/n)·IFFT of the table times (−1)^k, mirrored; its middle half is kept,
     // weighted by a sine window, and becomes an n/2-tap FIR with its centre at tap n/4 (§5.3)
-    std::vector<std::complex<double>> spec ((std::size_t) n);
+    // (in the preallocated buffers: a new response is loaded on the audio thread)
+    auto& spec = work;
+    std::fill (spec.begin(), spec.end(), std::complex<double> {});
     for (int k = 0; k <= n / 2; ++k)
         spec[(std::size_t) k] = (k & 1) ? -(double) t[(std::size_t) k] : (double) t[(std::size_t) k];
     for (int k = 1; k < n / 2; ++k)
         spec[(std::size_t) (n - k)] = spec[(std::size_t) k];
-    fft (spec, true);
+    fft (spec.data(), (std::size_t) n, twiddles->inverse);
     const float span = 1.0f / (float) (hop - 1);
-    std::vector<std::complex<double>> taps ((std::size_t) n);
+    auto& taps = work2;
+    std::fill (taps.begin(), taps.end(), std::complex<double> {});
     for (int i = 0; i < hop; ++i)
     {
         const auto h = (float) (spec[(std::size_t) (n / 4 + i)].real() / (double) n);
         const auto w = (float) std::sin ((double) ((float) i * span * 3.14159274f));
         taps[(std::size_t) i] = (double) (w * h);
     }
-    fft (taps, false);
-    kernel = taps;
+    fft (taps.data(), (std::size_t) n, twiddles->forward);
+    std::copy (taps.begin(), taps.end(), kernel.begin());
 }
 
 void FftConvolver::block() noexcept
 {
     const auto scale = 1.0f / (float) n;
-    std::vector<std::complex<double>> x ((std::size_t) n);
+    auto& x = work;
     for (int c = 0; c < 2; ++c)
     {
         std::fill (x.begin(), x.end(), std::complex<double> {});
         for (int i = 0; i < hop; ++i)
             x[(std::size_t) i] = (double) in[c][(std::size_t) i];
-        fft (x, false);
+        fft (x.data(), (std::size_t) n, twiddles->forward);
         for (int k = 0; k < n; ++k)
-            x[(std::size_t) k] *= kernel[(std::size_t) k];
-        fft (x, true);
+            x[(std::size_t) k] = mul (x[(std::size_t) k], kernel[(std::size_t) k]);
+        fft (x.data(), (std::size_t) n, twiddles->inverse);
         auto& o = out[c];
         std::copy (o.begin() + hop, o.end(), o.begin());
         std::fill (o.begin() + hop, o.end(), 0.0f);

+ 9 - 0
src/core/ParametricEqLinear.h

@@ -7,6 +7,7 @@
 
 #include <array>
 #include <complex>
+#include <memory>
 #include <vector>
 
 #include "core/ParametricEqFl.h"
@@ -30,11 +31,19 @@ LinearOptions parseLinearOptions (const std::vector<std::uint8_t>& state);
 // The engine's block FFT convolver (shared with Frequency Splitter's linear-phase mode and Maximus's linear-phase band
 // split, REA_rodada62): stereo, block n/2, FFT n, the kernel an n/2-tap windowed zero-phase FIR from an n/2 + 1 bin
 // magnitude table; output delayed by 3n/4. Computed here in double precision.
+// Twiddle factors of the convolver's FFT for one size (ParametricEqLinear.cpp)
+struct Twiddles
+{
+    std::vector<std::complex<double>> forward, inverse;
+};
+
 struct FftConvolver
 {
     int n = 0, hop = 0, pos = 0;
     std::vector<std::complex<double>> kernel;          // spectrum of the zero-padded FIR
     std::vector<float> in[2], out[2];                  // block input (hop) and overlap-add output (n), per channel
+    std::vector<std::complex<double>> work, work2;     // FFT scratch (n), so the audio thread does not allocate
+    std::shared_ptr<const Twiddles> twiddles;       // per-size table shared by every convolver of that size
     void init (int size);
     void clear() noexcept;
     void setKernel (const std::vector<float>& table);

+ 17 - 0
src/core/Preferences.cpp

@@ -132,6 +132,23 @@ double bufferLatencyMs (int bufferSamples, double sampleRate)
     return sampleRate > 0.0 ? 1000.0 * bufferSamples / sampleRate : 0.0;
 }
 
+int safeBufferSize (const std::vector<int>& available, int current, double sampleRate)
+{
+    const int target = sampleRate > 50000.0 ? (sampleRate > 100000.0 ? 2048 : 1024) : 512;
+    if (current >= target)
+        return current;
+    int best = 0, largest = 0;
+    for (const auto b : available)
+    {
+        largest = std::max (largest, b);
+        if (b >= target && (best == 0 || b < best))
+            best = b;
+    }
+    if (best == 0)
+        best = std::max (largest, current);
+    return best;
+}
+
 // --- MIDI -------------------------------------------------------------------------------------------------------
 
 float mapVelocity (float velocity, VelocityCurve curve) noexcept

+ 5 - 0
src/core/Preferences.h

@@ -40,6 +40,11 @@ int clampUndoLevels (int levels); // 10..1000
 // The latency one buffer adds, in milliseconds.
 double bufferLatencyMs (int bufferSamples, double sampleRate);
 
+// The buffer a fresh install starts with (REA round 87): about 10.7 ms (512 samples at 44.1/48 kHz, 1024 at 88.2/96 kHz)
+// so heavy projects do not crackle out of the box. The smallest offered size at or above that; the current size if it
+// is already larger; the largest offered one if none reaches it. 0 when nothing is offered.
+int safeBufferSize (const std::vector<int>& available, int current, double sampleRate);
+
 // --- MIDI (MIDI page) -------------------------------------------------------------------------------------------
 // How a played note's velocity reaches the instrument.
 enum class VelocityCurve

+ 120 - 1
src/core/RackRenderer.cpp

@@ -7,6 +7,9 @@
 #include "core/NewtoneFx.h"
 
 #include <algorithm>
+#include <chrono>
+#include <cstdlib>
+#include <ctime>
 #include <cmath>
 #include <cstring>
 #include <limits>
@@ -209,7 +212,8 @@ std::unique_ptr<const RackState> RackState::build (Song song,
 
             if (previous != nullptr && t < previous->song.mixer.size() && t < previous->effects.size()
                 && i < previous->song.mixer[t].effects.size() && i < previous->effects[t].size()
-                && previous->song.mixer[t].effects[i].kind == kind && kind != EffectKind::parallel // the container is rebuilt
+                && previous->song.mixer[t].effects[i].kind == kind
+                && (kind != EffectKind::parallel || sameContainer (previous->song.mixer[t].effects[i], slots[i])) // children are built in
                 && previous->song.mixer[t].effects[i].state == slots[i].state
                 && previous->song.mixer[t].effects[i].samplePath == slots[i].samplePath
                 && (kind != EffectKind::plugin
@@ -589,6 +593,104 @@ bool anyAbove (const float* l, const float* r, int n, float level) noexcept
 }
 } // namespace
 
+namespace
+{
+// A Patcher-style container bakes its children (kinds, states, parameters, routing) in when it is built, so it can be
+// reused only if all of that is unchanged. (It used to be rebuilt on every edit: its children's tails and delay lines
+// restarted, and a fresh linear-phase child reporting its latency only after the first block made the engine re-plan
+// PDC and rebuild it again, over and over — REA round 87.)
+bool sameSlotSetup (const EffectSlot& a, const EffectSlot& b);
+
+bool sameBranches (const EffectSlot& a, const EffectSlot& b)
+{
+    if (a.branches.size() != b.branches.size() || a.links.size() != b.links.size())
+        return false;
+    for (std::size_t i = 0; i < a.branches.size(); ++i)
+    {
+        const auto& x = a.branches[i];
+        const auto& y = b.branches[i];
+        if (x.gain != y.gain || x.chain.size() != y.chain.size())
+            return false;
+        for (std::size_t k = 0; k < x.chain.size(); ++k)
+            if (! sameSlotSetup (x.chain[k], y.chain[k]))
+                return false;
+    }
+    for (std::size_t i = 0; i < a.links.size(); ++i)
+    {
+        const auto& x = a.links[i];
+        const auto& y = b.links[i];
+        if (x.branch != y.branch || x.source != y.source || x.target != y.target || x.param != y.param || x.curve != y.curve)
+            return false;
+    }
+    return true;
+}
+
+bool sameSlotSetup (const EffectSlot& a, const EffectSlot& b)
+{
+    return a.kind == b.kind && a.enabled == b.enabled && a.params == b.params && a.mix == b.mix && a.plugin.id == b.plugin.id
+           && a.sidechain == b.sidechain && a.sidechain2 == b.sidechain2 && a.state == b.state && a.samplePath == b.samplePath
+           && sameBranches (a, b);
+}
+} // namespace
+
+bool sameContainer (const EffectSlot& a, const EffectSlot& b) { return sameBranches (a, b); }
+
+namespace
+{
+std::uint64_t nowNs() noexcept
+{
+#if defined(__linux__)
+    // diagnostics on a busy machine: LYNX_PROFILE_CPU=1 measures each unit in its thread's CPU time (renderwav)
+    static const bool threadCpu = std::getenv ("LYNX_PROFILE_CPU") != nullptr;
+    if (threadCpu)
+    {
+        timespec ts {};
+        clock_gettime (CLOCK_THREAD_CPUTIME_ID, &ts);
+        return (std::uint64_t) ts.tv_sec * 1000000000ull + (std::uint64_t) ts.tv_nsec;
+    }
+#endif
+    return (std::uint64_t) std::chrono::duration_cast<std::chrono::nanoseconds> (std::chrono::steady_clock::now().time_since_epoch()).count();
+}
+
+// Adds the time since `start` to `slot` when profiling (start = 0: profiling was off when the unit began)
+struct UnitTimer
+{
+    UnitTimer (bool on, std::atomic<std::uint64_t>& s, std::atomic<std::uint64_t>* m = nullptr) noexcept
+        : slot (s), longest (m), start (on ? nowNs() : 0) {}
+    ~UnitTimer()
+    {
+        if (start == 0)
+            return;
+        const auto used = nowNs() - start;
+        slot.fetch_add (used, std::memory_order_relaxed);
+        if (longest != nullptr)
+        {
+            auto current = longest->load (std::memory_order_relaxed);
+            while (used > current && ! longest->compare_exchange_weak (current, used, std::memory_order_relaxed))
+            {
+            }
+        }
+    }
+    std::atomic<std::uint64_t>& slot;
+    std::atomic<std::uint64_t>* longest;
+    std::uint64_t start;
+};
+} // namespace
+
+void RackRenderer::resetUnitTimes() noexcept
+{
+    for (auto& t : units->channelNs)
+        t.store (0, std::memory_order_relaxed);
+    for (auto& t : units->effectNs)
+        t.store (0, std::memory_order_relaxed);
+    for (auto& t : units->channelMaxNs)
+        t.store (0, std::memory_order_relaxed);
+    for (auto& t : units->effectMaxNs)
+        t.store (0, std::memory_order_relaxed);
+    units->processNs.store (0, std::memory_order_relaxed);
+    units->processedSamples.store (0, std::memory_order_relaxed);
+}
+
 void RackRenderer::prepare (double sr, int maxBlockSize)
 {
     automationValues.fill (std::numeric_limits<float>::quiet_NaN());
@@ -801,6 +903,7 @@ void RackRenderer::renderChannel (const RackState& state, int i, int n) noexcept
         return;
     }
     channelSilent[(std::size_t) i] = 0;
+    const UnitTimer timer (profiling.load (std::memory_order_relaxed), units->channelNs[(std::size_t) i], &units->channelMaxNs[(std::size_t) i]);
     std::memset (l, 0, sizeof (float) * (std::size_t) n);
     std::memset (r, 0, sizeof (float) * (std::size_t) n);
     int position = 0;
@@ -995,6 +1098,9 @@ void RackRenderer::runEffects (const RackState& state, int track, int n) noexcep
             std::memcpy (trackScratch (track, 1), r, sizeof (float) * (std::size_t) n);
         }
 
+        const UnitTimer timer (profiling.load (std::memory_order_relaxed), units->effectNs[std::min (key, units->effectNs.size() - 1)],
+                               &units->effectMaxNs[std::min (key, units->effectNs.size() - 1)]);
+
         if (state.hasAutomation && ! isPlugin)
         {
             auto params = slots[i].params; // copy without allocation
@@ -1049,6 +1155,9 @@ void RackRenderer::process (const RackState* state,
                             LiveEventQueue* moreLive) noexcept
 {
     const ScopedFlushDenormals noDenormals;
+    const UnitTimer timer (profiling.load (std::memory_order_relaxed), units->processNs);
+    if (profiling.load (std::memory_order_relaxed))
+        units->processedSamples.fetch_add ((std::uint64_t) std::max (0, numSamples), std::memory_order_relaxed);
     std::memset (left, 0, sizeof (float) * (std::size_t) numSamples);
     std::memset (right, 0, sizeof (float) * (std::size_t) numSamples);
     events.clear();
@@ -1168,6 +1277,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);

+ 21 - 1
src/core/RackRenderer.h

@@ -133,6 +133,8 @@ struct RackState
 
 class WorkerPool;
 
+// Whether a parallel container slot (FL's Patcher) can keep its built effect: same branches, children and links.
+bool sameContainer (const EffectSlot& a, const EffectSlot& b);
 // Time spent in each instrument and effect slot (the Plugin performance monitor, round 84). Counted only while
 // `enabled` is on; nanoseconds of processing and of audio rendered, accumulated (the reader takes differences).
 struct ProcessTimes
@@ -180,6 +182,23 @@ public:
 
     static void applyStereoForTest (const MixerTrack& t, float* l, float* r, int n) noexcept { applyStereo (t, l, r, n); }
 
+    // Per-unit CPU profile (REA round 87): the time spent in each channel (instrument, notes, PDC) and in each insert
+    // effect slot, accumulated while profiling is on. Off by default (it costs two clock reads per unit and chunk).
+    // Written by the audio thread and the workers, read by any thread (relaxed counters, nanoseconds).
+    static constexpr int maxChannels = 1024;
+    struct UnitTimes
+    {
+        std::array<std::atomic<std::uint64_t>, maxChannels> channelNs {};
+        std::array<std::atomic<std::uint64_t>, (std::size_t) maxMixerTracks * maxEffectSlots> effectNs {}; // [track * maxEffectSlots + slot]
+        std::array<std::atomic<std::uint64_t>, maxChannels> channelMaxNs {}; // longest single call (spikes)
+        std::array<std::atomic<std::uint64_t>, (std::size_t) maxMixerTracks * maxEffectSlots> effectMaxNs {};
+        std::atomic<std::uint64_t> processNs { 0 }, processedSamples { 0 };
+    };
+    void setProfiling (bool on) noexcept { profiling.store (on, std::memory_order_relaxed); }
+    bool isProfiling() const noexcept { return profiling.load (std::memory_order_relaxed); }
+    const UnitTimes& unitTimes() const noexcept { return *units; }
+    void resetUnitTimes() noexcept;
+
     // Tempo used in the last block (changes with tempo automation). The transport advances with it.
     double currentBpm() const noexcept { return bpm; }
 
@@ -213,7 +232,6 @@ private:
     std::array<float, RackState::maxAutomations> automationValues {}; // NaN = not evaluated yet
     std::array<float, maxMixerTracks * 2> lastTrackGain {}; // L/R gain of the previous block, for the ramp
     std::array<char, maxMixerTracks> trackActive {};        // the track output has sound in this block
-    static constexpr int maxChannels = 1024;
     std::array<char, maxChannels> channelSilent {};          // channel skipped in this chunk (idle, no notes)
     static constexpr int chunkCapacity = 512;               // chunks processed at once
     std::vector<float> channelBuffers;                      // maxChannels * 2 * chunkCapacity
@@ -223,6 +241,8 @@ private:
     LiveInput* liveInput = nullptr;
     int liveInputOffset = 0; // of the chunk within the process() block
     void mixLiveInput (const RackState& state, bool playing, int n) noexcept;
+    std::atomic<bool> profiling { false };
+    std::unique_ptr<UnitTimes> units = std::make_unique<UnitTimes>();
     std::unique_ptr<ProcessTimes> times = std::make_unique<ProcessTimes>();
 
     struct SmartDisableState

+ 110 - 0
src/core/RtStats.h

@@ -0,0 +1,110 @@
+#pragma once
+
+// Real-time health of the audio callback (REA round 87): how long each callback took against its deadline (the
+// buffer's duration), so a crackle can be told apart as "the processing was too slow" (over budget) or "the device
+// was late calling us" (gap between callbacks). The audio thread records with relaxed atomics (no locks, no
+// allocation); the UI, the log and --rtstress read snapshots.
+
+#include <algorithm>
+#include <array>
+#include <atomic>
+#include <cstdint>
+
+namespace lynx
+{
+class RtStats
+{
+public:
+    // Audio thread. `startMs`: when the callback began (a monotonic clock in ms), `usedMs`: how long it took,
+    // `budgetMs`: the buffer duration (numSamples / sampleRate).
+    void record (double startMs, double usedMs, double budgetMs) noexcept
+    {
+        callbacks.fetch_add (1, std::memory_order_relaxed);
+        const auto load = budgetMs > 0.0 ? usedMs / budgetMs : 0.0;
+        const auto permille = (std::uint32_t) std::min (100000.0, std::max (0.0, load * 1000.0));
+        raise (maxLoadPermille, permille);
+        raise (windowMaxPermille, permille);
+        totalUsedUs.fetch_add ((std::uint64_t) (usedMs * 1000.0), std::memory_order_relaxed);
+        totalBudgetUs.fetch_add ((std::uint64_t) (budgetMs * 1000.0), std::memory_order_relaxed);
+        histogram[(std::size_t) std::min<std::uint32_t> (permille / 100, bins - 1)].fetch_add (1, std::memory_order_relaxed);
+
+        if (load >= 1.0)
+        {
+            overBudget.fetch_add (1, std::memory_order_relaxed);
+            lastOverMs.store (startMs, std::memory_order_relaxed);
+        }
+        else if (load >= 0.8)
+            nearBudget.fetch_add (1, std::memory_order_relaxed);
+
+        // the device called later than one buffer after the previous call (plus a margin): it may have run dry
+        const auto previous = lastStartMs.exchange (startMs, std::memory_order_relaxed);
+        if (previous > 0.0 && budgetMs > 0.0 && startMs - previous > budgetMs * 1.9 + 2.0)
+        {
+            lateCalls.fetch_add (1, std::memory_order_relaxed);
+            lastLateMs.store (startMs, std::memory_order_relaxed);
+        }
+    }
+
+    // A pause in the calls that is not a glitch (device restarted, stopped): forget the previous start.
+    void deviceRestarted() noexcept { lastStartMs.store (0.0, std::memory_order_relaxed); }
+
+    static constexpr std::uint32_t bins = 16; // load histogram in 10 % steps; the last bin is >= 150 %
+
+    struct Snapshot
+    {
+        std::uint64_t callbacks = 0, overBudget = 0, nearBudget = 0, lateCalls = 0;
+        double maxLoad = 0.0;       // since the last reset (1 = the whole deadline)
+        double averageLoad = 0.0;   // processing time / deadline over everything since the last reset
+        double lastOverMs = 0.0, lastLateMs = 0.0;
+        std::array<std::uint64_t, bins> histogram {};
+    };
+
+    Snapshot snapshot() const noexcept
+    {
+        Snapshot s;
+        s.callbacks = callbacks.load (std::memory_order_relaxed);
+        s.overBudget = overBudget.load (std::memory_order_relaxed);
+        s.nearBudget = nearBudget.load (std::memory_order_relaxed);
+        s.lateCalls = lateCalls.load (std::memory_order_relaxed);
+        s.maxLoad = maxLoadPermille.load (std::memory_order_relaxed) / 1000.0;
+        const auto budget = (double) totalBudgetUs.load (std::memory_order_relaxed);
+        s.averageLoad = budget > 0.0 ? (double) totalUsedUs.load (std::memory_order_relaxed) / budget : 0.0;
+        s.lastOverMs = lastOverMs.load (std::memory_order_relaxed);
+        s.lastLateMs = lastLateMs.load (std::memory_order_relaxed);
+        for (std::size_t i = 0; i < bins; ++i)
+            s.histogram[i] = histogram[i].load (std::memory_order_relaxed);
+        return s;
+    }
+
+    // The highest load since the previous call (for a meter that shows peaks between UI frames).
+    double takeWindowMaxLoad() noexcept { return windowMaxPermille.exchange (0, std::memory_order_relaxed) / 1000.0; }
+
+    // Any thread (the counters are restarted, not synchronised with a callback in flight).
+    void reset() noexcept
+    {
+        for (auto* a : { &callbacks, &overBudget, &nearBudget, &lateCalls, &totalUsedUs, &totalBudgetUs })
+            a->store (0, std::memory_order_relaxed);
+        maxLoadPermille.store (0, std::memory_order_relaxed);
+        windowMaxPermille.store (0, std::memory_order_relaxed);
+        lastOverMs.store (0.0, std::memory_order_relaxed);
+        lastLateMs.store (0.0, std::memory_order_relaxed);
+        for (auto& h : histogram)
+            h.store (0, std::memory_order_relaxed);
+    }
+
+private:
+    static void raise (std::atomic<std::uint32_t>& slot, std::uint32_t v) noexcept
+    {
+        auto current = slot.load (std::memory_order_relaxed);
+        while (v > current && ! slot.compare_exchange_weak (current, v, std::memory_order_relaxed))
+        {
+        }
+    }
+
+    std::atomic<std::uint64_t> callbacks { 0 }, overBudget { 0 }, nearBudget { 0 }, lateCalls { 0 };
+    std::atomic<std::uint64_t> totalUsedUs { 0 }, totalBudgetUs { 0 };
+    std::atomic<std::uint32_t> maxLoadPermille { 0 }, windowMaxPermille { 0 };
+    std::atomic<double> lastStartMs { 0.0 }, lastOverMs { 0.0 }, lastLateMs { 0.0 };
+    std::array<std::atomic<std::uint64_t>, bins> histogram {};
+};
+} // namespace lynx

+ 127 - 12
src/core/WorkerPool.cpp

@@ -1,10 +1,62 @@
 #include "core/WorkerPool.h"
 
+#include <chrono>
+
 #include "core/Denormals.h"
 
+#if defined(_WIN32)
+ #ifndef WIN32_LEAN_AND_MEAN
+  #define WIN32_LEAN_AND_MEAN
+ #endif
+ #ifndef NOMINMAX
+  #define NOMINMAX
+ #endif
+ #include <windows.h>
+#else
+ #include <semaphore>
+#endif
+
+#if defined(__SSE2__) || defined(_M_X64) || defined(__x86_64__)
+ #include <immintrin.h>
+#endif
+
 namespace lynx
 {
-WorkerPool::WorkerPool (int n, std::function<void()> onThreadStart)
+namespace
+{
+inline void cpuRelax() noexcept
+{
+#if defined(__SSE2__) || defined(_M_X64) || defined(__x86_64__)
+    _mm_pause();
+#elif defined(__aarch64__)
+    asm volatile ("yield");
+#endif
+}
+} // namespace
+
+#if defined(_WIN32)
+struct WorkerPool::Semaphore
+{
+    Semaphore() : handle (CreateSemaphoreW (nullptr, 0, 0x7fffffff, nullptr)) {}
+    ~Semaphore()
+    {
+        if (handle != nullptr)
+            CloseHandle (handle);
+    }
+    void release (int n) noexcept { ReleaseSemaphore (handle, n, nullptr); }
+    void acquire() noexcept { WaitForSingleObject (handle, INFINITE); }
+    HANDLE handle;
+};
+#else
+struct WorkerPool::Semaphore
+{
+    void release (int n) noexcept { s.release (n); }
+    void acquire() noexcept { s.acquire(); }
+    std::counting_semaphore<0x7fffffff> s { 0 };
+};
+#endif
+
+WorkerPool::WorkerPool (int n, std::function<void()> onThreadStart) : wake (std::make_unique<Semaphore>())
 {
     // ticket 0: count 0, nothing to take until the first parallelFor
 
@@ -15,12 +67,19 @@ WorkerPool::WorkerPool (int n, std::function<void()> onThreadStart)
 WorkerPool::~WorkerPool()
 {
     quit.store (true);
-    wake.release ((std::ptrdiff_t) threads.size());
+    wake->release ((int) threads.size());
 
     for (auto& t : threads)
         t.join();
 }
 
+bool WorkerPool::hasWork() const noexcept
+{
+    constexpr auto mask = (std::uint64_t (1) << indexBits) - 1;
+    const auto t = ticket.load (std::memory_order_acquire);
+    return (t & mask) < ((t >> indexBits) & mask);
+}
+
 void WorkerPool::workerLoop (std::function<void()> onStart)
 {
     const ScopedFlushDenormals noDenormals;
@@ -28,29 +87,78 @@ void WorkerPool::workerLoop (std::function<void()> onStart)
     if (onStart)
         onStart();
 
-    while (true)
+    using clock = std::chrono::steady_clock;
+
+    while (! quit.load (std::memory_order_relaxed))
     {
-        wake.acquire();
+        // spin a little: within a block the next parallelFor (next mixer layer or chunk) follows right away
+        auto spinStart = clock::now();
+        auto found = false;
+
+        for (int i = 0;; ++i)
+        {
+            if (hasWork())
+            {
+                found = true;
+                break;
+            }
+
+            cpuRelax();
+
+            if ((i & 63) == 63)
+            {
+                if (quit.load (std::memory_order_relaxed))
+                    return;
+                if (clock::now() - spinStart > std::chrono::microseconds (spinMicros))
+                    break;
+            }
+        }
+
+        if (found)
+        {
+            work (true);
+            continue;
+        }
+
+        // sleep. Announce it first, then look once more: run() publishes the ticket before reading `sleeping`,
+        // so either it sees this worker asleep and releases the semaphore, or this check sees the work
+        sleeping.fetch_add (1, std::memory_order_seq_cst);
+
+        if (hasWork())
+        {
+            sleeping.fetch_sub (1, std::memory_order_seq_cst);
+            work (true);
+            continue;
+        }
+
+        wake->acquire();
+        sleeping.fetch_sub (1, std::memory_order_seq_cst);
+        wokenUp.fetch_add (1, std::memory_order_relaxed);
 
         if (quit.load())
             return;
 
-        work();
+        work (true);
     }
 }
 
-void WorkerPool::work() noexcept
+bool WorkerPool::work (bool isWorker) noexcept
 {
     constexpr auto mask = (std::uint64_t (1) << indexBits) - 1;
+    auto any = false;
+
     while (true)
     {
         const auto t = ticket.fetch_add (1, std::memory_order_acq_rel);
         const auto i = t & mask, n = (t >> indexBits) & mask;
 
         if (i >= n)
-            return;
+            return any;
 
         call (context, (int) i);
+        any = true;
+        if (isWorker)
+            byWorkers.fetch_add (1, std::memory_order_relaxed);
         done.fetch_add (1, std::memory_order_acq_rel);
     }
 }
@@ -72,13 +180,20 @@ void WorkerPool::run (int n, void* ctx, Call fn) noexcept
     done.store (0, std::memory_order_relaxed);
     ++generation;
     const auto base = generation << (2 * indexBits);
-    ticket.store (base | ((std::uint64_t) n << indexBits), std::memory_order_release); // from here on the workers may take indices
+    ticket.store (base | ((std::uint64_t) n << indexBits), std::memory_order_seq_cst); // from here on the workers may take indices
+
+    // wake only the sleepers that are needed (spinning workers already see the ticket)
+    if (const auto asleep = sleeping.load (std::memory_order_seq_cst); asleep > 0)
+        wake->release (std::min (asleep, n - 1));
 
-    wake.release ((std::ptrdiff_t) std::min<int> ((int) threads.size(), n - 1));
-    work();
+    work (false);
 
-    while (done.load (std::memory_order_acquire) < n)
-        std::this_thread::yield();
+    for (int spins = 0; done.load (std::memory_order_acquire) < n; ++spins)
+    {
+        cpuRelax();
+        if ((spins & 1023) == 1023)
+            std::this_thread::yield();
+    }
 
     ticket.store (base, std::memory_order_release); // count 0: late workers take nothing
 }

+ 24 - 5
src/core/WorkerPool.h

@@ -2,13 +2,20 @@
 
 // Thread pool for the audio thread to split a block's work (channels and
 // mixer tracks), like FL does with the mixer layers (docs/ANALISE_FL_STUDIO.md §2.2).
-// parallelFor neither allocates nor blocks on a mutex: workers wake via semaphore and take
-// indices from an atomic counter; the calling thread also works and spin-waits.
+// parallelFor neither allocates nor blocks on a mutex: workers take indices from an atomic counter; the calling
+// thread also works and spin-waits for the last index.
+//
+// Waking the workers (REA round 87): a worker that just finished spins for a short while (the next parallelFor of
+// the same block — the next mixer layer, the next chunk — comes microseconds later), then sleeps on an OS
+// semaphore (a Win32 semaphore on Windows, a futex-backed one elsewhere). std::counting_semaphore is NOT used:
+// the Windows libc++ build has no platform wait and falls back to Sleep() polling with growing intervals, so an
+// idle worker woke 1–8 ms late — later than a whole audio block — and the audio thread ended up doing all the
+// work alone.
 
 #include <atomic>
 #include <cstdint>
 #include <functional>
-#include <semaphore>
+#include <memory>
 #include <thread>
 #include <vector>
 
@@ -34,16 +41,27 @@ public:
         run (count, &fn, [] (void* f, int i) { (*static_cast<Fn*> (f)) (i); });
     }
 
+    // How long a worker keeps polling for new work after finishing before it sleeps (microseconds).
+    static constexpr int spinMicros = 250;
+
+    // Diagnostics: how many indices the workers (not the calling thread) ran, and how many times a worker
+    // was woken from sleep. Relaxed counters.
+    std::uint64_t indicesRunByWorkers() const noexcept { return byWorkers.load (std::memory_order_relaxed); }
+    std::uint64_t wakeUps() const noexcept { return wokenUp.load (std::memory_order_relaxed); }
+
 private:
     using Call = void (*) (void*, int);
 
     void run (int count, void* context, Call call) noexcept;
-    void work() noexcept;
+    bool work (bool isWorker) noexcept;
+    bool hasWork() const noexcept;
     void workerLoop (std::function<void()> onStart);
 
+    struct Semaphore; // OS semaphore (WorkerPool.cpp)
+    std::unique_ptr<Semaphore> wake;
     std::vector<std::thread> threads;
-    std::counting_semaphore<> wake { 0 };
     std::atomic<bool> quit { false };
+    std::atomic<int> sleeping { 0 }; // workers blocked (or about to block) on `wake`
 
     // current work (published before `ticket`). The ticket packs generation (bits 40+), count (bits 20…39) and the
     // next index (bits 0…19), so an index taken by a late worker always carries its own round's count: a worker
@@ -54,5 +72,6 @@ private:
     std::atomic<std::uint64_t> ticket { 0 };
     std::uint64_t generation = 0; // caller thread only
     std::atomic<int> done { 0 };
+    std::atomic<std::uint64_t> byWorkers { 0 }, wokenUp { 0 };
 };
 } // namespace lynx

+ 196 - 9
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"
@@ -54,9 +55,21 @@ void raiseAudioThreadPriority()
             return reinterpret_cast<AvSet> (reinterpret_cast<void*> (GetProcAddress (avrt, "AvSetMmThreadCharacteristicsW")));
         return nullptr;
     }();
+    // FL's audio worker threads also raise their MMCSS priority to "high" (FLEngine_x64.dll, REA round 87)
+    using AvPriority = int (__stdcall*) (void*, int);
+    static const auto avPriority = [] () -> AvPriority {
+        if (auto* avrt = LoadLibraryW (L"avrt.dll"))
+            return reinterpret_cast<AvPriority> (reinterpret_cast<void*> (GetProcAddress (avrt, "AvSetMmThreadPriority")));
+        return nullptr;
+    }();
     unsigned long task = 0;
 
-    if (avSet == nullptr || avSet (L"Pro Audio", &task) == nullptr)
+    if (auto* handle = avSet != nullptr ? avSet (L"Pro Audio", &task) : nullptr)
+    {
+        if (avPriority != nullptr)
+            avPriority (handle, 1 /* AVRT_PRIORITY_HIGH */);
+    }
+    else
         SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
    #endif
 }
@@ -105,9 +118,17 @@ AudioEngine::AudioEngine (bool openAudioDevice)
 
         // 0 inputs, 2 outputs; the device of the last session (Settings › Audio) if it is still there, else the default.
         const auto saved = juce::XmlDocument::parse (audioDeviceFile());
+        auto fresh = saved == nullptr;
         if (deviceManager.initialise (0, 2, saved.get(), true).isNotEmpty() && saved != nullptr)
+        {
             deviceManager.initialise (0, 2, nullptr, true);
+            fresh = true;
+        }
+        if (fresh)
+            chooseSafeBufferSize(); // no saved setup: a buffer with room for heavy projects (Settings › Audio changes it)
         deviceManager.addAudioCallback (this);
+        if (rackProcessor != nullptr)
+            rackProcessor->getRenderer().setProfiling (true); // per-unit CPU for the CPU meter and the glitch log
         deviceStateSaver = std::make_unique<DeviceStateSaver> (*this);
         midiPrefs = midiPrefsShared = prefs::MidiPrefs::fromText (midiSettingsFile().loadFileAsString().toStdString());
 
@@ -1174,9 +1195,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)
         {
@@ -1191,16 +1214,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)
@@ -1356,15 +1386,156 @@ void AudioEngine::applyControllers()
 
 void AudioEngine::timerCallback()
 {
+    updateRealtimeStats();
     applyControllers();
     updateRecording();
     rackExchange.collectGarbage();
 
     // Plugins are prepared at a fixed rate; if the device changed rate, recreate them.
     // A plugin whose latency changed (preset change, lookahead) requests a new PDC plan.
-    if (std::abs (transport.sampleRate.load() - lastPublishedShape.sampleRate) > 0.5
-        || lastPublishedShape.currentLatencies() != lastPublishedShape.latencies)
+    const auto rateChanged = std::abs (transport.sampleRate.load() - lastPublishedShape.sampleRate) > 0.5;
+    const auto latencies = lastPublishedShape.currentLatencies();
+    if (rateChanged || latencies != lastPublishedShape.latencies)
+    {
+        // (diagnostics: which unit's latency moved)
+        if (! rateChanged)
+            for (std::size_t i = 0; i < latencies.size() && i < lastPublishedShape.latencies.size(); ++i)
+                if (latencies[i] != lastPublishedShape.latencies[i])
+                {
+                    lastLatencyChange = juce::String ((int) i) + ": " + juce::String (lastPublishedShape.latencies[i]) + " -> " + juce::String (latencies[i]);
+                    break;
+                }
+        ++latencyRepublishes;
         publishSong();
+    }
+}
+
+void AudioEngine::chooseSafeBufferSize()
+{
+    auto* device = deviceManager.getCurrentAudioDevice();
+    if (device == nullptr)
+        return;
+    std::vector<int> sizes;
+    for (auto b : device->getAvailableBufferSizes())
+        sizes.push_back (b);
+    const auto current = device->getCurrentBufferSizeSamples();
+    const auto target = prefs::safeBufferSize (sizes, current, device->getCurrentSampleRate());
+    if (target > 0 && target != current)
+    {
+        auto setup = deviceManager.getAudioDeviceSetup();
+        setup.bufferSize = target;
+        deviceManager.setAudioDeviceSetup (setup, true);
+    }
+}
+
+juce::File AudioEngine::glitchLogFile() { return PluginHost::settingsFolder().getChildFile ("audio-glitches.log"); }
+
+void AudioEngine::updateRealtimeStats()
+{
+    // the message thread's pulse: this 30 Hz timer arriving late means the UI is saturated
+    {
+        const auto now = juce::Time::getMillisecondCounterHiRes();
+        if (lastUiPulseMs > 0.0)
+            uiPulse.maxGapMs = juce::jmax (uiPulse.maxGapMs, now - lastUiPulseMs);
+        lastUiPulseMs = now;
+        ++uiPulse.calls;
+    }
+
+    // every ~2 s: the share of real time each channel / insert effect took in that window
+    if (rackProcessor != nullptr && juce::Time::getMillisecondCounterHiRes() - lastUnitsWindowMs >= 2000.0)
+    {
+        lastUnitsWindowMs = juce::Time::getMillisecondCounterHiRes();
+        auto& renderer = rackProcessor->getRenderer();
+        const auto& units = renderer.unitTimes();
+        const auto processed = units.processedSamples.load (std::memory_order_relaxed);
+        const auto rate = juce::jmax (1.0, transport.sampleRate.load());
+        const auto audioNs = (double) (processed - std::min (processed, lastProcessedSamples)) / rate * 1.0e9;
+        lastProcessedSamples = processed;
+        lastChannelNs.resize (units.channelNs.size(), 0);
+        lastEffectNs.resize (units.effectNs.size(), 0);
+        std::vector<UnitLoad> loads;
+
+        auto take = [&] (const std::atomic<std::uint64_t>& total, std::uint64_t& last, std::atomic<std::uint64_t>& longest, auto&& name) {
+            const auto now = total.load (std::memory_order_relaxed);
+            const auto delta = now - std::min (now, last);
+            last = now;
+            const auto longestNs = const_cast<std::atomic<std::uint64_t>&> (longest).exchange (0, std::memory_order_relaxed);
+            if (delta > 0 && audioNs > 0.0)
+                loads.push_back ({ name(), (double) delta / audioNs, (double) longestNs * 1.0e-6 });
+        };
+        auto& mutableUnits = const_cast<RackRenderer::UnitTimes&> (units);
+        for (std::size_t c = 0; c < units.channelNs.size(); ++c)
+            take (units.channelNs[c], lastChannelNs[c], mutableUnits.channelMaxNs[c], [&] {
+                return c < song.channels.size() ? juce::String::fromUTF8 (song.channels[c].name.c_str()) : "Channel " + juce::String ((int) c + 1);
+            });
+        for (std::size_t k = 0; k < units.effectNs.size(); ++k)
+            take (units.effectNs[k], lastEffectNs[k], mutableUnits.effectMaxNs[k], [&] {
+                const auto t = k / (std::size_t) maxEffectSlots, slot = k % (std::size_t) maxEffectSlots;
+                juce::String effect;
+                if (t < song.mixer.size() && slot < song.mixer[t].effects.size())
+                {
+                    const auto& fx = song.mixer[t].effects[slot];
+                    effect = juce::String::fromUTF8 (fx.plugin.name.empty() ? effectInfo (fx.kind).name : fx.plugin.name.c_str());
+                }
+                const auto track = t == 0 ? juce::String ("Master") : (t < song.mixer.size() && ! song.mixer[t].name.empty() ? juce::String::fromUTF8 (song.mixer[t].name.c_str())
+                                                                                                               : "Insert " + juce::String ((int) t));
+                return track + " / " + juce::String ((int) slot + 1) + " " + effect;
+            });
+        std::sort (loads.begin(), loads.end(), [] (const UnitLoad& a, const UnitLoad& b) { return a.load > b.load; });
+        if (loads.size() > 8)
+            loads.resize (8);
+        if (audioNs > 0.0)
+            heaviestUnits = std::move (loads);
+    }
+
+    // a line in the glitch log when callbacks ran over their deadline or the device called late
+    const auto stats = rtStats.snapshot();
+    if ((stats.overBudget > loggedOver || stats.lateCalls > loggedLate) && juce::Time::getMillisecondCounterHiRes() - lastLogMs > 2000.0)
+    {
+        const auto file = glitchLogFile();
+        if (file.getSize() > 1024 * 1024)
+            file.moveFileTo (file.withFileExtension ("old.log"));
+        const auto bar = transport.positionTicks.load() / (double) (ppq * juce::jmax (1, song.beatsPerBar)) + 1.0;
+        file.appendText (juce::Time::getCurrentTime().formatted ("%Y-%m-%d %H:%M:%S") + "  over deadline +" + juce::String ((juce::int64) (stats.overBudget - loggedOver))
+                             + ", late calls +" + juce::String ((juce::int64) (stats.lateCalls - loggedLate)) + ", at bar " + juce::String (bar, 2)
+                             + (transport.playing.load() ? "" : " (stopped)") + "\n" + describeRealtime() + "\n",
+                         false, false, "\r\n");
+        loggedOver = stats.overBudget;
+        loggedLate = stats.lateCalls;
+        lastLogMs = juce::Time::getMillisecondCounterHiRes();
+    }
+}
+
+juce::String AudioEngine::describeRealtime (bool withUnits) const
+{
+    juce::String text;
+    if (auto* device = const_cast<juce::AudioDeviceManager&> (deviceManager).getCurrentAudioDevice())
+    {
+        const auto rate = device->getCurrentSampleRate();
+        const auto buffer = device->getCurrentBufferSizeSamples();
+        text << "  device: " << device->getTypeName() << " / " << device->getName() << ", " << (int) rate << " Hz, buffer " << buffer
+             << " samples (deadline " << juce::String (prefs::bufferLatencyMs (buffer, rate), 2) << " ms), output latency "
+             << device->getOutputLatencyInSamples() << " samples, driver dropouts " << device->getXRunCount() << "\n";
+    }
+    else
+        text << "  device: none\n";
+    const auto s = rtStats.snapshot();
+    text << "  callbacks " << (juce::int64) s.callbacks << ": over deadline " << (juce::int64) s.overBudget << ", 80-100% " << (juce::int64) s.nearBudget
+         << ", late device calls " << (juce::int64) s.lateCalls << ", average load " << juce::String (s.averageLoad * 100.0, 1) << "%, max "
+         << juce::String (s.maxLoad * 100.0, 0) << "%, workers " << (workers != nullptr ? workers->workers() : 0) << "\n";
+    if (latencyRepublishes > 0)
+        text << "  latency changes re-planned PDC " << latencyRepublishes << " times (last: unit " << lastLatencyChange << ")\n";
+    if (withUnits && heaviestUnits.empty())
+        text << "  heaviest: not measured yet\n";
+    if (withUnits && ! heaviestUnits.empty())
+    {
+        text << "  heaviest:";
+        for (std::size_t i = 0; i < heaviestUnits.size() && i < 5; ++i)
+            text << (i > 0 ? ";" : "") << " " << heaviestUnits[i].name << " " << juce::String (heaviestUnits[i].load * 100.0, 1) << "% (peak "
+                 << juce::String (heaviestUnits[i].longestMs, 1) << " ms)";
+        text << "\n";
+    }
+    return text;
 }
 
 std::shared_ptr<Instrument> AudioEngine::getChannelInstrument (int channel) const
@@ -1408,6 +1579,21 @@ void AudioEngine::audioDeviceIOCallbackWithContext (const float* const* inputCha
                                                     int numSamples,
                                                     const juce::AudioIODeviceCallbackContext& context)
 {
+    // real-time health: how long this callback took against its deadline (the buffer's duration)
+    const auto callbackStart = juce::Time::getMillisecondCounterHiRes();
+    struct Measure
+    {
+        ~Measure()
+        {
+            const auto rate = engine.transport.sampleRate.load (std::memory_order_relaxed);
+            if (rate > 0.0)
+                engine.rtStats.record (start, juce::Time::getMillisecondCounterHiRes() - start, 1000.0 * samples / rate);
+        }
+        AudioEngine& engine;
+        double start;
+        int samples;
+    } measure { *this, callbackStart, numSamples };
+
     if (transport.rewindRequested.exchange (false))
         transport.positionTicks.store (0.0);
 
@@ -1538,6 +1724,7 @@ void AudioEngine::audioDeviceIOCallbackWithContext (const float* const* inputCha
 
 void AudioEngine::audioDeviceAboutToStart (juce::AudioIODevice* device)
 {
+    rtStats.deviceRestarted();
     transport.sampleRate.store (device->getCurrentSampleRate());
 
     // the callback gets the open input channels only, in order: map device channel -> callback index

+ 44 - 1
src/engine/AudioEngine.h

@@ -16,6 +16,7 @@
 #include "core/Recorder.h"
 #include "core/WorkerPool.h"
 #include "core/RackRenderer.h"
+#include "core/RtStats.h"
 #include "core/FlpImport.h"
 #include "core/History.h"
 #include "core/SnapshotExchange.h"
@@ -55,6 +56,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.
@@ -269,6 +272,34 @@ public:
     void copyScope (float* destination, int count) const noexcept;
     static constexpr int scopeSize = 2048;
 
+    // Real-time health of the audio callback (REA round 87): callbacks over their deadline, late device calls, load.
+    const RtStats& getRtStats() const noexcept { return rtStats; }
+    RtStats& getRtStats() noexcept { return rtStats; }
+
+    // What takes the most audio CPU: channels and insert effects, as a share of real time over the last ~2 s of
+    // playback, heaviest first. UI thread.
+    struct UnitLoad
+    {
+        juce::String name;
+        double load = 0.0;      // CPU time / audio time (summed over the worker threads)
+        double longestMs = 0.0; // the longest single call in the window
+    };
+    const std::vector<UnitLoad>& getHeaviestUnits() const noexcept { return heaviestUnits; }
+
+    // How regularly the message thread runs the engine's 30 Hz timer (a saturated UI delays it). UI thread.
+    struct UiPulse
+    {
+        int calls = 0;
+        double maxGapMs = 0.0;
+    };
+    UiPulse takeUiPulse() noexcept { return std::exchange (uiPulse, {}); }
+
+    // Device, buffer, deadline and the callback statistics in a few lines (CPU meter hint, glitch log, --rtstress).
+    juce::String describeRealtime (bool withUnits = true) const;
+
+    // %APPDATA%\LYNX\audio-glitches.log: a line each time callbacks run over their deadline (at most every 2 s).
+    static juce::File glitchLogFile();
+
     // Total latency compensated by PDC (at the Master output), in samples.
     int getLatencySamples() const noexcept { return lastPublishedShape.pdc.total; }
 
@@ -292,6 +323,18 @@ private:
     double estimatedPositionNow() const noexcept;
 
     void buildInitialGraph();
+    void chooseSafeBufferSize();
+    void updateRealtimeStats(); // timer: unit loads over a window, glitch log
+    RtStats rtStats;
+    std::vector<UnitLoad> heaviestUnits;
+    std::vector<std::uint64_t> lastChannelNs, lastEffectNs;
+    std::uint64_t lastProcessedSamples = 0;
+    double lastUnitsWindowMs = 0.0, lastUiPulseMs = 0.0;
+    UiPulse uiPulse;
+    int latencyRepublishes = 0;   // PDC re-plans because a unit's latency changed (diagnostics)
+    juce::String lastLatencyChange;
+    std::uint64_t loggedOver = 0, loggedLate = 0;
+    double lastLogMs = 0.0;
     class PreviewPlayer* preview = nullptr; // graph node (owned by the graph)
     void publishSong();
 
@@ -368,7 +411,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/ChannelRackProcessor.h

@@ -44,6 +44,8 @@ public:
 
     // External audio input of the inserts (set before the device starts).
     void setLiveInput (LiveInput* input) noexcept { renderer.setLiveInput (input); }
+    // The renderer (its per-unit CPU profile, REA round 87).
+    RackRenderer& getRenderer() noexcept { return renderer; }
     // Per instrument / effect processing time (Plugin performance monitor).
     ProcessTimes& processTimes() noexcept { return renderer.processTimes(); }
 

+ 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)

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 2874 - 2872
src/ui/I18nData.h


+ 18 - 2
src/ui/MainComponent.cpp

@@ -2088,6 +2088,12 @@ void MainComponent::timerCallback()
         const auto held = (int) heldKeys.size();
         const auto notes = playing ? songstats::soundingNotes (engine.getSong(), transport.positionTicks.load()) : 0;
         perfMeter.setValues (engine.getDeviceManager().getCpuUsage(), toolbar::PerformanceMeter::processMemoryBytes(), notes + held);
+        const auto rt = engine.getRtStats().snapshot();
+        juce::StringArray heaviest;
+        for (const auto& u : engine.getHeaviestUnits())
+            if (heaviest.size() < 3 && u.load >= 0.01)
+                heaviest.add (u.name + " " + juce::String (juce::roundToInt (u.load * 100.0)) + "%");
+        perfMeter.setRealtime (rt.overBudget, rt.lateCalls, engine.getRtStats().takeWindowMaxLoad(), heaviest);
     }
 
     // If a dialog stole focus, give it back so the PC keyboard keeps playing (unless a detached panel has it).
@@ -2472,6 +2478,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());
     }
@@ -2662,7 +2672,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
@@ -2693,7 +2703,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
@@ -2939,6 +2950,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

@@ -2566,7 +2566,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)

+ 6 - 2
src/ui/SettingsPages.cpp

@@ -495,10 +495,14 @@ private:
                         juce::dontSendNotification);
         status.setColour (juce::Label::textColourId, theme::colour::textPrimary);
         const auto xruns = device->getXRunCount();
+        const auto rt = engine.getRtStats().snapshot();
+        const auto dot = juce::String::fromUTF8 ("   \xc2\xb7   ");
         load.setText (tr ("Audio CPU load: {0}%", { juce::String (juce::roundToInt (devices.getCpuUsage() * 100.0)) })
-                          + (xruns > 0 ? juce::String::fromUTF8 ("   \xc2\xb7   ") + tr ("{0} dropouts (buffer underruns) so far", { juce::String (xruns) }) : juce::String()),
+                          + (xruns > 0 ? dot + tr ("{0} dropouts (buffer underruns) so far", { juce::String (xruns) }) : juce::String())
+                          + (rt.overBudget > 0 ? dot + tr ("{0} blocks over the deadline (max {1}%)", { juce::String ((juce::int64) rt.overBudget), juce::String (juce::roundToInt (rt.maxLoad * 100.0)) })
+                                               : juce::String()),
                       juce::dontSendNotification);
-        load.setColour (juce::Label::textColourId, xruns > 0 ? theme::colour::warning : theme::colour::textSecondary);
+        load.setColour (juce::Label::textColourId, xruns > 0 || rt.overBudget > 0 ? theme::colour::warning : theme::colour::textSecondary);
     }
 
     void changeListenerCallback (juce::ChangeBroadcaster*) override { refresh(); }

+ 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;

+ 30 - 1
src/ui/Toolbar.cpp

@@ -418,6 +418,17 @@ void PerformanceMeter::setValues (double cpu01, std::int64_t memoryBytes, int po
     repaint();
 }
 
+void PerformanceMeter::setRealtime (std::uint64_t over, std::uint64_t late, double peak, const juce::StringArray& units)
+{
+    if (over > overDeadline || late > lateCalls)
+        lastGlitchAt = juce::jmax<juce::uint32> (1, juce::Time::getMillisecondCounter());
+    overDeadline = over;
+    lateCalls = late;
+    peakLoad = peak;
+    heaviest = units;
+    repaint();
+}
+
 void PerformanceMeter::paint (juce::Graphics& g)
 {
     using namespace theme;
@@ -440,6 +451,19 @@ void PerformanceMeter::paint (juce::Graphics& g)
     g.setColour (load < 0.6f ? colour::meterLow : load < 0.85f ? colour::meterMid : colour::meterClip);
     if (load > 0.0f)
         g.fillRoundedRectangle (bar.withWidth (juce::jmax (2.0f, bar.getWidth() * load)), 2.0f);
+    // the highest callback load since the last update (a thin mark), and a red edge for a few seconds after a
+    // callback missed its deadline (an audible crackle)
+    if (peakLoad > 0.0)
+    {
+        const auto x = bar.getX() + bar.getWidth() * (float) juce::jlimit (0.0, 1.0, peakLoad);
+        g.setColour (peakLoad < 0.85 ? colour::textSecondary : colour::meterClip);
+        g.fillRect (juce::Rectangle<float> (x - 1.0f, bar.getY(), 2.0f, bar.getHeight()));
+    }
+    if (lastGlitchAt != 0 && juce::Time::getMillisecondCounter() - lastGlitchAt < 5000)
+    {
+        g.setColour (colour::meterClip);
+        g.drawRoundedRectangle (bar.expanded (1.0f), 2.0f, 1.0f);
+    }
 
     // memory and polyphony
     auto left = row2.removeFromLeft (row2.getWidth() * 58 / 100);
@@ -465,7 +489,12 @@ ui::Hint PerformanceMeter::hintAt (juce::Point<int> p)
     if (p.y < getHeight() / 2)
     {
         h.text = tr ("CPU: how much of the audio deadline the processing takes; near 100% the sound breaks up");
-        h.value = juce::String (cpu * 100.0, 1) + "%";
+        if (overDeadline > 0 || lateCalls > 0)
+            h.text << "  " << tr ("{0} audio blocks missed the deadline (crackles), the device called late {1} times; log: audio-glitches.log",
+                                  { juce::String ((juce::int64) overDeadline), juce::String ((juce::int64) lateCalls) });
+        if (! heaviest.isEmpty())
+            h.text << "  " << tr ("Heaviest: {0}", { heaviest.joinIntoString (", ") });
+        h.value = juce::String (cpu * 100.0, 1) + "%" + (peakLoad > 0.0 ? "  (" + tr ("peak {0}%", { juce::String (juce::roundToInt (peakLoad * 100.0)) }) + ")" : juce::String());
     }
     else if (p.x < getWidth() * 58 / 100)
     {

+ 7 - 0
src/ui/Toolbar.h

@@ -105,12 +105,19 @@ class PerformanceMeter final : public juce::Component,
 {
 public:
     void setValues (double cpu01, std::int64_t memoryBytes, int polyphony);
+    // Real-time health (REA round 87): callbacks that missed their deadline (the crackles), the highest load since
+    // the last update and the heaviest channels / effects ("name 12%").
+    void setRealtime (std::uint64_t overDeadline, std::uint64_t lateCalls, double peakLoad, const juce::StringArray& heaviest);
     void paint (juce::Graphics& g) override;
     ui::Hint hintAt (juce::Point<int> position) override;
 
     static std::int64_t processMemoryBytes(); // working set of this process (0 if unknown)
 
 private:
+    std::uint64_t overDeadline = 0, lateCalls = 0;
+    double peakLoad = 0.0;
+    juce::StringArray heaviest;
+    juce::uint32 lastGlitchAt = 0; // ms counter of the last new over-deadline callback (0 = none)
     double cpu = 0.0, cpuSmoothed = 0.0;
     std::int64_t memory = 0;
     int voices = 0, peakVoices = 0;

+ 39 - 0
tests/ConvolverTests.inc

@@ -181,3 +181,42 @@ TEST (convolver_engine)
     std::vector<std::uint8_t> a, b;
     CHECK (lynx::convolver::unpackBlob (lynx::convolver::packBlob ({ 1, 2, 3 }, { 4, 5 }), a, b) && a.size() == 3 && b.size() == 2);
 }
+
+TEST (convolver_long_kernel_matches_direct_convolution)
+{
+    // a sparse 100k-tap kernel reaches every partition level (128, 1024, 8192, 16384); the larger levels compute a
+    // block's output during the previous block (REA round 87), which must not change the convolution
+    lynx::convolver::Kernel k;
+    k.l.assign (100001, 0.0f);
+    k.r.assign (100001, 0.0f);
+    const std::vector<std::pair<int, float>> taps { { 0, 0.5f }, { 77, -0.25f }, { 300, 0.2f }, { 1500, -0.15f }, { 2100, 0.1f }, { 9000, 0.3f },
+                                                    { 16500, -0.2f }, { 20000, 0.12f }, { 70000, -0.3f }, { 100000, 0.25f } };
+    for (const auto& [i, v] : taps)
+        k.l[(std::size_t) i] = v, k.r[(std::size_t) i] = -v;
+    k.tail = 200000;
+    lynx::convolver::Engine e;
+    e.setRate (44100);
+    e.setKernel (k);
+    e.setParams ({ 0, 1000, 0, 0 }); // no dry, full wet, no separation
+    e.reset (false);
+    const int total = 130000;
+    std::vector<float> x (total), l (total), r (total);
+    std::uint32_t seed = 5;
+    for (auto& v : x)
+        v = (float) ((seed = seed * 1664525u + 1013904223u) >> 8) / 16777216.0f - 0.5f;
+    l = x, r = x;
+    for (int done = 0; done < total; done += 512)
+        e.process (l.data() + done, r.data() + done, std::min (512, total - done));
+    const double wet = (double) l[0] / ((double) x[0] * 0.5); // the wet gain's float rounding
+    double worst = 0.0;
+    for (int i = 0; i < total; i += 7)
+    {
+        double y = 0.0;
+        for (const auto& [t, v] : taps)
+            if (i >= t)
+                y += (double) v * (double) x[(std::size_t) (i - t)];
+        worst = std::max ({ worst, std::abs (y * wet - (double) l[(std::size_t) i]), std::abs (-y * wet - (double) r[(std::size_t) i]) });
+    }
+    CHECK (std::abs (wet - 1.0) < 1e-3);
+    CHECK (worst < 2e-5);
+}

+ 355 - 7
tests/tests.cpp

@@ -1,7 +1,9 @@
 // Core tests (no JUCE). Usage: lynx_tests [folder-with-flp-files]
 
+#include <optional>
 #include <atomic>
 #include <chrono>
+#include <thread>
 #include <random>
 #include <cctype>
 #include <cmath>
@@ -102,6 +104,8 @@
 #include "core/Vocodex.h"
 #include "core/TimeStretch.h"
 #include "core/WorkerPool.h"
+#include "core/RtStats.h"
+#include "core/ParametricEqLinear.h"
 #include "core/Song.h"
 #include "core/NoteEdit.h"
 #include "core/Recorder.h"
@@ -286,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);
@@ -943,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;
@@ -1327,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);
@@ -2046,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,
@@ -3594,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));
@@ -4239,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;
@@ -5803,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)
@@ -7293,6 +7459,142 @@ TEST (worker_pool_runs_each_index_once_per_round)
     CHECK (wrongRound.load() == 0);
 }
 
+TEST (worker_pool_wakes_sleeping_workers)
+{
+    // rounds far apart (the workers have gone to sleep on the semaphore in between): every index still runs once,
+    // and the sleeping workers are woken (REA round 87: the Windows build used to poll with growing Sleep()s)
+    lynx::WorkerPool pool (3);
+    std::vector<std::atomic<int>> hits (16);
+    int failures = 0;
+    for (int r = 0; r < 12; ++r)
+    {
+        std::this_thread::sleep_for (std::chrono::microseconds (lynx::WorkerPool::spinMicros * 4));
+        for (auto& h : hits)
+            h.store (0);
+        auto fn = [&] (int i) {
+            std::this_thread::sleep_for (std::chrono::microseconds (200)); // long enough for woken workers to join
+            hits[(std::size_t) i].fetch_add (1);
+        };
+        pool.parallelFor (16, fn);
+        for (auto& h : hits)
+            failures += h.load() != 1;
+    }
+    CHECK (failures == 0);
+    CHECK (pool.wakeUps() > 0);
+    CHECK (pool.indicesRunByWorkers() > 0);
+}
+
+TEST (realtime_stats_count_deadline_misses_and_late_calls)
+{
+    lynx::RtStats stats;
+    // 10 ms deadline: 3 ms, 9 ms (80-100 %), 12 ms (over), then a call 40 ms after the previous one (late)
+    stats.record (100.0, 3.0, 10.0);
+    stats.record (110.0, 9.0, 10.0);
+    stats.record (120.0, 12.0, 10.0);
+    stats.record (160.0, 2.0, 10.0);
+    const auto s = stats.snapshot();
+    CHECK (s.callbacks == 4);
+    CHECK (s.overBudget == 1);
+    CHECK (s.nearBudget == 1);
+    CHECK (s.lateCalls == 1);
+    CHECK (std::abs (s.maxLoad - 1.2) < 1e-9);
+    CHECK (std::abs (s.averageLoad - 26.0 / 40.0) < 1e-3);
+    CHECK (s.histogram[3] == 1 && s.histogram[9] == 1 && s.histogram[12] == 1 && s.histogram[2] == 1);
+    CHECK (std::abs (stats.takeWindowMaxLoad() - 1.2) < 1e-9 && stats.takeWindowMaxLoad() == 0.0);
+    // a device restart is not a late call
+    stats.deviceRestarted();
+    stats.record (5000.0, 1.0, 10.0);
+    CHECK (stats.snapshot().lateCalls == 1);
+    stats.reset();
+    CHECK (stats.snapshot().callbacks == 0 && stats.snapshot().maxLoad == 0.0);
+}
+
+TEST (safe_default_buffer_size)
+{
+    const std::vector<int> wasapi { 144, 160, 192, 224, 256, 288, 320, 384, 448, 480, 512, 576, 640, 1024, 2048 };
+    CHECK (lynx::prefs::safeBufferSize (wasapi, 480, 48000.0) == 512);   // the 10 ms default becomes 512
+    CHECK (lynx::prefs::safeBufferSize (wasapi, 1024, 48000.0) == 1024); // already larger: kept
+    CHECK (lynx::prefs::safeBufferSize (wasapi, 480, 96000.0) == 1024);  // ~10.7 ms at 96 kHz
+    CHECK (lynx::prefs::safeBufferSize ({ 64, 128, 256 }, 128, 44100.0) == 256); // nothing reaches 512: the largest
+    CHECK (lynx::prefs::safeBufferSize ({}, 0, 44100.0) == 0);
+}
+
+TEST (linear_phase_convolver_matches_direct_convolution)
+{
+    // the block FFT convolver (cached twiddles, REA round 87) equals the direct convolution with its kernel
+    lynx::peqfl::FftConvolver c;
+    c.init (256);
+    std::vector<float> table (129, 1.0f);
+    for (int k = 40; k < 129; ++k)
+        table[(std::size_t) k] = 0.25f; // a high shelf cut
+    c.setKernel (table);
+    // impulse response through step()
+    std::vector<float> ir (600, 0.0f);
+    for (int i = 0; i < 600; ++i)
+    {
+        float l = i == 0 ? 1.0f : 0.0f, r = 0.0f;
+        c.step (l, r);
+        ir[(std::size_t) i] = l;
+    }
+    // then a noise signal, compared with direct convolution by that impulse response
+    lynx::peqfl::FftConvolver d;
+    d.init (256);
+    d.setKernel (table);
+    std::vector<float> x (2000), y (2000);
+    std::uint32_t seed = 1;
+    for (auto& v : x)
+        v = (float) ((seed = seed * 1664525u + 1013904223u) >> 8) / 16777216.0f - 0.5f;
+    for (std::size_t i = 0; i < x.size(); ++i)
+    {
+        float l = x[i], r = 0.0f;
+        d.step (l, r);
+        y[i] = l;
+    }
+    double worst = 0.0;
+    for (std::size_t i = 0; i < x.size(); ++i)
+    {
+        double direct = 0.0;
+        for (std::size_t k = 0; k < ir.size() && k <= i; ++k)
+            direct += (double) ir[k] * (double) x[i - k];
+        worst = std::max (worst, std::abs (direct - (double) y[i]));
+    }
+    CHECK (worst < 1e-4);
+    // and it delays by 3n/4 with the kernel's centre there
+    const auto peak = (std::size_t) (std::max_element (ir.begin(), ir.end(), [] (float a, float b) { return std::abs (a) < std::abs (b); }) - ir.begin());
+    CHECK (peak == 192);
+}
+
+TEST (patcher_container_is_reused_across_snapshots)
+{
+    // an unchanged Patcher keeps its built effect (its children's tails, delay lines and PDC stay put), and a
+    // linear-phase Frequency Splitter reports its latency before its first block (REA round 87: it used to be
+    // rebuilt on every snapshot and its latency appeared one block late, re-planning PDC in a loop)
+    auto song = lynx::Song::makeDefault();
+    if (song.mixer.size() < 2)
+        song.mixer.resize (2);
+    lynx::EffectSlot splitter;
+    splitter.kind = lynx::EffectKind::frequencySplitter;
+    splitter.params = lynx::makeEffectSlot (lynx::EffectKind::frequencySplitter).params;
+    splitter.params[4] = 0.6f; // linear-phase mode
+    splitter.params[6] = 0.0f; // quality 0
+    lynx::EffectSlot patcher;
+    patcher.kind = lynx::EffectKind::parallel;
+    patcher.branches.push_back ({ { splitter }, 1.0f });
+    patcher.branches.push_back ({ {}, 0.5f });
+    song.mixer[1].effects = { patcher };
+    const auto a = lynx::RackState::build (song, nullptr, 44100.0);
+    const auto b = lynx::RackState::build (song, a.get(), 44100.0);
+    CHECK (a->effects[1][0] == b->effects[1][0]);
+    CHECK (a->effects[1][0]->latencySamples() == 384); // 3/4 of the 512-point FFT, before any block
+    CHECK (a->latencies == a->currentLatencies());
+    song.mixer[1].effects[0].branches[0].chain[0].params[0] = 0.25f; // a child's parameter changed: rebuilt
+    const auto c = lynx::RackState::build (song, b.get(), 44100.0);
+    CHECK (c->effects[1][0] != b->effects[1][0]);
+    song.mixer[1].effects[0].branches[1].gain = 0.75f;
+    const auto d = lynx::RackState::build (song, c.get(), 44100.0);
+    CHECK (d->effects[1][0] != c->effects[1][0]);
+}
+
 TEST (ladder_filter_follows_toxic_law)
 {
     // the 4-pole ladder: −24 dB/oct far above the cutoff (vs −12 for the SVF), resonance raises the corner, and
@@ -14698,4 +15000,50 @@ TEST (event_editor_playback)
 }
 #include "PrefsTests.inc"
 #include "InputTests.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"

+ 148 - 3
tools/renderwav.cpp

@@ -1,6 +1,13 @@
 // renderwav: imports an .flp and renders a pattern with the built-in instruments.
 // Usage: renderwav project.flp output.wav [pattern-index] [loops]
 // Without an index, picks the pattern with the most notes.
+//
+// Real-time diagnostics (REA round 87), environment variables:
+//   LYNX_BLOCK=n      block size (default 256)
+//   LYNX_THREADS=n    n worker threads, as the app's audio engine uses
+//   LYNX_REALTIME=1   paces the blocks at real time (the workers sleep between blocks, as with a sound card)
+//   LYNX_PROFILE=1    per-channel / per-insert-effect CPU time, heaviest first
+// The block timing report (budget = block duration) is always printed.
 
 #include <cctype>
 #include <cstdio>
@@ -14,6 +21,14 @@
 #include <map>
 #include <string>
 #include <chrono>
+#include <thread>
+#include <time.h>
+#if defined(_WIN32)
+ #define WIN32_LEAN_AND_MEAN
+ #define NOMINMAX
+ #include <windows.h>
+ #include <mmsystem.h>
+#endif
 
 #include "WavReader.h"
 #include "core/FlpImport.h"
@@ -22,6 +37,22 @@
 
 namespace
 {
+// like the app's audio threads: MMCSS "Pro Audio" on Windows (with a 1 ms timer for the real-time pacing)
+void realtimePriority()
+{
+#if defined(_WIN32)
+    using AvSet = void* (__stdcall*) (const wchar_t*, unsigned long*);
+    static const auto avSet = [] () -> AvSet {
+        if (auto* avrt = LoadLibraryW (L"avrt.dll"))
+            return reinterpret_cast<AvSet> (reinterpret_cast<void*> (GetProcAddress (avrt, "AvSetMmThreadCharacteristicsW")));
+        return nullptr;
+    }();
+    unsigned long task = 0;
+    if (avSet == nullptr || avSet (L"Pro Audio", &task) == nullptr)
+        SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
+#endif
+}
+
 void writeWav (const char* path, const std::vector<float>& left, const std::vector<float>& right, int sampleRate)
 {
     std::ofstream out (path, std::ios::binary);
@@ -67,12 +98,18 @@ int main (int argc, char** argv)
 
     // On Linux/WSL FL lives under /mnt/c; the .flp paths use backslashes.
     const std::string flRoot = std::getenv ("FL_ROOT") ? std::getenv ("FL_ROOT")
+#if defined(_WIN32)
+                                                       : "C:/Program Files/Image-Line/FL Studio 2026";
+#else
                                                        : "/mnt/c/Program Files/Image-Line/FL Studio 2026";
+#endif
     auto toLocal = [] (std::string p) {
         std::replace (p.begin(), p.end(), '\\', '/');
         // absolute Windows paths ("C:/...") → the WSL mount ("/mnt/c/...")
+#if ! defined(_WIN32) // (the Windows build of this tool reads them as they are)
         if (p.size() > 2 && p[1] == ':' && p[2] == '/' && std::isalpha ((unsigned char) p[0]))
             p = "/mnt/" + std::string (1, (char) std::tolower ((unsigned char) p[0])) + p.substr (2);
+#endif
         return p;
     };
 
@@ -117,7 +154,7 @@ int main (int argc, char** argv)
     const auto lengthTicks = wholeSong ? songTicks : pattern.effectiveLength (song.beatsPerBar) * loops;
 
     constexpr int sampleRate = 44100;
-    constexpr int blockSize = 256;
+    const int blockSize = std::getenv ("LYNX_BLOCK") ? std::clamp (std::atoi (std::getenv ("LYNX_BLOCK")), 16, 8192) : 256;
     const auto tps = lynx::ticksPerSample (song.bpm, sampleRate);
     auto totalSamples = (std::size_t) (lengthTicks / tps) + sampleRate; // +1 s of tail
     if (const char* s = std::getenv ("LYNX_SECONDS"); s != nullptr && std::atof (s) > 0) // benchmark: render only the start
@@ -163,24 +200,132 @@ int main (int argc, char** argv)
     std::unique_ptr<lynx::WorkerPool> pool;
     if (const char* t = std::getenv ("LYNX_THREADS"); t != nullptr && std::atoi (t) > 0)
     {
-        pool = std::make_unique<lynx::WorkerPool> (std::atoi (t));
+        pool = std::make_unique<lynx::WorkerPool> (std::atoi (t), [] { realtimePriority(); });
         renderer.setWorkerPool (pool.get());
     }
-    renderer.prepare (sampleRate);
+    renderer.prepare (sampleRate, std::max (2048, blockSize));
+    const bool profile = std::getenv ("LYNX_PROFILE") != nullptr;
+    const bool realtime = std::getenv ("LYNX_REALTIME") != nullptr;
+#if defined(_WIN32)
+    timeBeginPeriod (1);
+    realtimePriority();
+#endif
+    renderer.setProfiling (profile);
 
     std::vector<float> left (totalSamples), right (totalSamples);
+    // the units whose latency is only known after their first block (the app then re-plans PDC once)
+    const auto latenciesBefore = state->currentLatencies();
     const auto started = std::chrono::steady_clock::now();
     double tick = 0.0;
+    const double budgetMs = 1000.0 * blockSize / sampleRate;
+    std::vector<double> wallMs, cpuMs;
+    auto threadCpuMs = [] {
+#if defined(_WIN32)
+        FILETIME created, exited, kernel, user;
+        GetThreadTimes (GetCurrentThread(), &created, &exited, &kernel, &user);
+        return (((std::uint64_t) user.dwHighDateTime << 32 | user.dwLowDateTime) + ((std::uint64_t) kernel.dwHighDateTime << 32 | kernel.dwLowDateTime)) * 1e-4;
+#else
+        timespec ts {};
+        clock_gettime (CLOCK_THREAD_CPUTIME_ID, &ts);
+        return ts.tv_sec * 1000.0 + ts.tv_nsec * 1e-6;
+#endif
+    };
 
     for (std::size_t pos = 0; pos < totalSamples; pos += blockSize)
     {
         const auto n = (int) std::min<std::size_t> (blockSize, totalSamples - pos);
         const bool playing = tick < (double) lengthTicks;
+        const auto t0 = std::chrono::steady_clock::now();
+        const auto c0 = threadCpuMs();
         renderer.process (state.get(), playing, tick, n, left.data() + pos, right.data() + pos);
+        wallMs.push_back (std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now() - t0).count());
+        cpuMs.push_back (threadCpuMs() - c0);
         tick += n * tps;
+
+        if (realtime) // the next block starts one block later, like a sound card's callback
+            std::this_thread::sleep_until (started + std::chrono::microseconds ((long long) ((pos + (std::size_t) n) * 1.0e6 / sampleRate)));
     }
 
+    {
+        const auto after = state->currentLatencies();
+        std::size_t index = song.channels.size();
+        for (std::size_t t = 0; t < song.mixer.size(); ++t)
+            for (std::size_t k = 0; k < state->effects[t].size(); ++k, ++index)
+                if (index < after.size() && after[index] != latenciesBefore[index])
+                    std::printf ("latency changed after the first block: insert %zu slot %zu %s: %d -> %d\n", t, k + 1,
+                                 lynx::effectInfo (song.mixer[t].effects[k].kind).name, latenciesBefore[index], after[index]);
+    }
     std::printf ("render: %.0f ms\n", std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now() - started).count());
+    {
+        auto report = [&] (const char* what, std::vector<double> v) {
+            if (v.empty())
+                return;
+            double sum = 0.0;
+            std::size_t over = 0, nearly = 0;
+            for (auto x : v)
+                sum += x, over += x >= budgetMs, nearly += x >= 0.8 * budgetMs && x < budgetMs;
+            std::sort (v.begin(), v.end());
+            auto pct = [&] (double p) { return v[std::min (v.size() - 1, (std::size_t) (p * (double) v.size()))]; };
+            std::printf ("blocks %s: %zu x %d samples (budget %.2f ms): mean %.0f%%, p50 %.0f%%, p99 %.0f%%, max %.0f%%; "
+                         "over budget %zu (%.2f%%), 80-100%% %zu\n",
+                         what, v.size(), blockSize, budgetMs, 100.0 * sum / (double) v.size() / budgetMs, 100.0 * pct (0.5) / budgetMs,
+                         100.0 * pct (0.99) / budgetMs, 100.0 * v.back() / budgetMs, over, 100.0 * (double) over / (double) v.size(), nearly);
+        };
+        report ("wall", wallMs);
+        {
+            // where the slowest blocks were (seconds into the render)
+            std::vector<std::size_t> order (cpuMs.size());
+            for (std::size_t i = 0; i < order.size(); ++i)
+                order[i] = i;
+            const auto& by = pool == nullptr ? cpuMs : wallMs;
+            std::sort (order.begin(), order.end(), [&] (std::size_t a, std::size_t b) { return by[a] > by[b]; });
+            std::printf ("slowest blocks:");
+            for (std::size_t i = 0; i < order.size() && i < 8; ++i)
+                std::printf (" %.2fs=%.0f%%", (double) (order[i] * (std::size_t) blockSize) / sampleRate, 100.0 * by[order[i]] / budgetMs);
+            std::printf ("\n");
+        }
+        if (pool == nullptr)
+            report ("thread-cpu", cpuMs);
+#if ! defined(LYNX_OLDPOOL)
+        if (pool != nullptr)
+            std::printf ("workers: %d threads ran %llu indices, %llu wake-ups\n", pool->workers(),
+                         (unsigned long long) pool->indicesRunByWorkers(), (unsigned long long) pool->wakeUps());
+#endif
+    }
+
+    if (profile)
+    {
+        const auto& u = renderer.unitTimes();
+        const auto total = (double) u.processNs.load();
+        struct Row
+        {
+            double ns;
+            std::string name;
+            double maxNs = 0.0;
+        };
+        std::vector<Row> rows;
+        for (std::size_t c = 0; c < song.channels.size() && c < (std::size_t) lynx::RackRenderer::maxChannels; ++c)
+            if (const auto ns = (double) u.channelNs[c].load(); ns > 0.0)
+                rows.push_back ({ ns, "channel " + std::to_string (c) + " \"" + song.channels[c].name + "\"", (double) u.channelMaxNs[c].load() });
+        for (std::size_t t = 0; t < song.mixer.size(); ++t)
+            for (std::size_t k = 0; k < song.mixer[t].effects.size() && k < (std::size_t) lynx::maxEffectSlots; ++k)
+                if (const auto ns = (double) u.effectNs[t * lynx::maxEffectSlots + k].load(); ns > 0.0)
+                    rows.push_back ({ ns, "insert " + std::to_string (t) + " slot " + std::to_string (k + 1) + " "
+                                              + lynx::effectInfo (song.mixer[t].effects[k].kind).name
+                                              + (song.mixer[t].effects[k].plugin.name.empty() ? "" : " (" + song.mixer[t].effects[k].plugin.name + ")"),
+                                          (double) u.effectMaxNs[t * lynx::maxEffectSlots + k].load() });
+        std::sort (rows.begin(), rows.end(), [] (const Row& a, const Row& b) { return a.ns > b.ns; });
+        const auto audioMs = 1000.0 * (double) u.processedSamples.load() / sampleRate;
+        std::printf ("profile: process %.0f ms for %.0f ms of audio (units below are CPU time, summed over threads)\n", total * 1e-6, audioMs);
+        for (std::size_t i = 0; i < rows.size() && i < 25; ++i)
+            std::printf ("  %6.1f%% of real time, longest call %7.2f ms  %s\n", 100.0 * rows[i].ns * 1e-6 / std::max (1.0, audioMs),
+                         rows[i].maxNs * 1e-6, rows[i].name.c_str());
+        // the spikes: units whose single call took longest
+        std::sort (rows.begin(), rows.end(), [] (const Row& a, const Row& b) { return a.maxNs > b.maxNs; });
+        std::printf ("longest single calls:\n");
+        for (std::size_t i = 0; i < rows.size() && i < 10; ++i)
+            std::printf ("  %7.2f ms  %s\n", rows[i].maxNs * 1e-6, rows[i].name.c_str());
+    }
 
     // LYNX_RAW=path: also write the un-normalized float samples (L block then R block), for bit-exact comparisons
     if (const char* raw = std::getenv ("LYNX_RAW"); raw != nullptr)

+ 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;
+}

برخی فایل ها در این مقایسه diff نمایش داده نمی شوند زیرا تعداد فایل ها بسیار زیاد است