Răsfoiți Sursa

Merge branch 'feature/delay3'

Ka1-S 1 lună în urmă
părinte
comite
5464b71

+ 1 - 0
CMakeLists.txt

@@ -55,6 +55,7 @@ add_library(lynx_core STATIC
     src/core/MaximusFx.cpp
     src/core/FruityDynamics.cpp
     src/core/FruityShapers.cpp
+    src/core/FruityDelay.cpp
     src/core/FlPatcher.cpp
     src/core/Inflate.cpp
     src/core/WavPack.cpp)

+ 8 - 0
docs/STATUS.md

@@ -322,6 +322,14 @@ accordingly. Highlights of what is **confirmed and applied**:
   behaviour (interpolated table, ×16 when oversampling is on). Soft Clipper: FL's exponential knee in x87 precision
   and its post law. Controls are editable LYNX parameters. Bit-identical to both DLLs on every installation state
   (57 WaveShaper states live and rendering, at 44.1 and 48 kHz; 12 Soft Clipper states plus edge cases).
+- **Fruity Delay 2 and Fruity Delay 3:** FL's exact engines as mixer effects (`core/FruityDelay`, REA round 52),
+  FL's raw controls as editable parameters. Delay 2: time in 1/192 beat, input pan/volume ramps, stereo offset,
+  normal/swapped/ping-pong loop with its one-pole cutoff in x87 precision. Delay 3 (the hosted third-party engine):
+  synced (1/192 beat) and unsynced time laws (cubic 1 ms…1 s), time smoothing glides or keep-pitch crossfades, LFO
+  modulation (the engine's FMA sine), diffusion all-passes, 10 Hz feedback high-pass, state-variable filter with
+  cutoff LFO, limit/saturate distortion, rate/bit reduction, colour, stereo spread, the three delay models and "off".
+  Bit-identical to the installation's DLLs on every installation state (60 + 85) at two tempos, at 48 kHz (one
+  Delay 3 state at −151 dB) and on 110 random Delay 3 states incl. tempo changes; LYNX starts them settled.
 - **Vocodex:** its own engine (`core/Vocodex.cpp`, REA round 35) built from FL's raw state, which the `.lynx`
   project keeps: band layout and the 13 per-band maps, 64-bit band-pass banks (orders 1–4, flatness, 2×
   oversampling above 11.05 kHz), PEAK/RMS followers, gate, saturation, double-precision smoother, unison, IPP-style

+ 267 - 0
docs/analise/REA_rodada52.md

@@ -0,0 +1,267 @@
+# Behavioural analysis of FL Studio 2026: round 52 (REA) — Fruity Delay 2 and Fruity Delay 3: exact engines
+
+> **Nature of this document.** Continuation of `REA_rodada7.md` §4 (state layouts of both delays) and
+> `REA_rodada8.md` §7.2 (Delay 3's unsynced time unit, left open). *Clean-room* reverse engineering, behavioural only.
+> No Image-Line code or pseudocode was copied: what is here are data layouts, formulas and behaviours described in
+> our own words. Addresses (`FUN_xxxxxxxx`), offsets and globals serve only to trace the evidence. No FLEX pack was
+> opened; no Image-Line preset or audio data was copied into the repository. The constants in LYNX's engine are the
+> numbers of the laws below (frequencies, periods, polynomial coefficients), not data files.
+>
+> **Rule for this round: no speculation.** Every value comes from decompilation (**[DECOMP]**), from the data
+> (**[DATA]**) or from running the installation's own DLLs, unmodified (**[EXEC]**). What could not be settled is
+> marked "not confirmed".
+
+| Marker | Meaning |
+|---|---|
+| **[DECOMP]** | read in the decompiled/disassembled code (Ghidra 12.1.4 headless + `objdump -M intel` where the float order matters) |
+| **[DATA]** | checked in `.flp`/`.fst` files of the installation, or a value read from a DLL's data section |
+| **[EXEC]** | result obtained by running the installation's own DLL (without modifying it) |
+
+- **Date:** 2026-10-15. Scratch directory (paths below are relative to it): `/home/kauan/.claude/jobs/f8789b49/tmp/r52/`.
+- **Targets** (all under `Plugins/Fruity/Effects/`):
+
+  | File | SHA-256 | Role |
+  |---|---|---|
+  | `Fruity Delay 2/Fruity Delay 2_x64.dll` | `d9a7674dca16cd95078b69aed7d68c56614598868a329d2bcfaabe0ec7a6f93d` | Delphi plugin with its own DSP |
+  | `Fruity Delay 3/Fruity Delay 3_x64.dll` | `b9d64b0918460d1a8c06ef48127e4d4d0c344b0459cfb33fd0b4e9e537cbfbd1` | Delphi wrapper (state, parameters, host events) |
+  | `Fruity Delay 3/engine_x64.dll` | `0b05f78f4fb18f7afceb39f8dc439fbe31477d4d7e2389e0167bdf1cd7828891` | the DSP: a third-party VST2 engine (RTTI `FLDelay3Plugin`, `ILDelay3`, `ParameterSmoother`; exports `CreateEngine`, `VSTPluginMain`) |
+
+- **EXEC harness:** `run/dl.c` → `dl_<n>.exe` (zig cc 0.14.1, x86_64-windows-gnu), round 48's effect harness extended
+  with the plugin's tempo event (`ProcessEvent` id 0 = tempo float bits, flags = samples per tick; sent before the
+  state, before and after the rate set-up, or at a sample position), a late state load (`statelate`), calls into the
+  engine DLL's own functions (`efn=`) and reads of its globals (`emem=`). Same safety measures as before (unmodified
+  DLLs, `SetErrorMode`, vectored fault handler, `TerminateProcess`, `timeout`).
+- **Drivers (our own code):** `py/survey52.py` (states of the installation → `data/states52.pkl`), `py/dl.py` (runs the
+  harness; test signals), `py/d2model.py` (Python model of Delay 2), `py/t_d2all.py` (model vs DLL),
+  `cpp/fdcmp.cpp` + `py/lx.py` (LYNX's C++ engines on the same inputs, with the plugin's set-up order),
+  `py/t_all.py` (every installation state), `py/t_rand.py` (random states over every control, tempo changes),
+  `py/t_math.py` + `cpp/mathref.c` (the engine's math library against glibc), `py/gold.py` (goldens of
+  `tests/tests.cpp`).
+
+Error measure everywhere: `20·log₁₀(‖LYNX − DLL‖ / ‖DLL‖)` over both channels; "−∞" = bit-identical.
+
+---
+
+## 0. Data survey **[DATA, `py/survey52.py`]**
+
+| Plugin | Demo-project slots | Template slots | Presets (`.fst`) | Unique states | Size |
+|---|---|---|---|---|---|
+| Fruity Delay 3 | 66 in 19 files | 44 in 12 files | 10 | 85 | 108 B (version 1 + 26 × i32) |
+| Fruity Delay 2 | 61 in 16 files | 0 | 6 | 60 | 32 B (8 × i32, no version) |
+
+Delay 3 states: delay type true stereo 39, ping pong 39, fake stereo 7; tempo sync on in 67; keep pitch on in 18;
+saturation type "saturate" 70, "limit" 15; filter LP 55, HP 19, BP 11; modulation on in 45, distortion in 28,
+diffusion in 31, rate reduction in 12, bit reduction in 6; 18 states unsynced (raw time 0…550). The delay type
+"Off" and the filter mode "Off" occur in no state (covered by the random states of §5).
+
+---
+
+## 1. Fruity Delay 2 — the engine **[DECOMP + EXEC]**
+
+### 1.1 Controls (layout of round 7 §4.2, laws corrected)
+
+| i | Control | Range | Law |
+|---|---|---|---|
+| 0 | Input pan | −128…128 | `p = v/128` (float) |
+| 1 | Input volume | 0…160 | `L11(v)`: `x = v·2⁻⁷` (float); 1 when x = 1, else `(e^{x·ln11} − 1)·0.1` with `ln 11` as a float, the result rounded to float |
+| 2 | Dry | 0…160 | `L11(v)` |
+| 3 | Feedback | 0…127 | `v/128` (not /127) |
+| 4 | **Time** | 1…768 | **1/192 of a beat**: `samples = round(v·rate·0.3125 / bpm)` (`0.3125 = 60/192`; ties to even; at least 1). Round 7's reading (1/48 beat) was 4× too long: the editor shows `v/48 : v%48` in sixteenths |
+| 5 | Stereo offset | −512…512 | `ms·100 = 50·(1001^{|v|/512} − 1)` (float steps), `samples = round(ms·100·rate/100000)`; v ≤ 0 delays the left input, v > 0 the right |
+| 6 | Mode | 0…2 | 0 normal, 1 swapped outputs (each channel feeds back into itself), 2 ping pong (cross feedback) |
+| 7 | Cutoff | 0…128 | one-pole coefficient `c = min(1, (21^{v/128} − 1)·0.05·(44100/rate))` |
+
+The tempo comes from the host's tempo event; a time, offset or tempo change recomputes the line (`FUN_006bfea0`).
+
+### 1.2 Signal path per block (`Eff_Render` `FUN_006c0910`)
+
+1. **Input matrix with gain ramps:** targets from pan p and volume g — p ≥ 0: `LL = (1−p)·g`, `LR = (p/2)·g`,
+   `RR = g − LR`, `RL = 0`; p < 0: `RR = (1+p)·g`, `RL = (−p/2)·g`, `LL = g − RL`, `LR = 0` (float steps in that order).
+   Each gain moves linearly toward its target, the per-sample step limited to `0.001·44100/rate`; a new instance
+   starts from 0, so FL fades the input in over ~1000 samples. `inL' = L·LL + R·RL`, `inR' = R·RR + L·LR` (SSE, float).
+2. The block is **added into the line** at the write position, the delayed channel `offset` samples further ahead.
+3. **The loop** (x87, extended precision; feedback ramped like the gains): per sample, read the line at the read
+   position (output = the read values, swapped in modes 1/2), then for each channel
+   `y = (read·fb + line[write] − s)·c + s; s = y` and `line[write] = y` (0 when |y| ≤ 2⁻²⁴); the read slot is cleared.
+   Filter states are kept as doubles between blocks.
+4. **Output:** `out = in·dry + wet` (x87, rounded to float); with dry = 0 the wet signal is the output.
+
+The line holds `delay + host block + offset` frames; FL resizes it on a time change (`FUN_006bb1f0`); what a resize
+does to its content is not confirmed (LYNX clears it).
+
+---
+
+## 2. Fruity Delay 3 — how FL hosts the engine **[DECOMP + EXEC]**
+
+- The Delphi plugin (`VMT 0x6e87d0`) only keeps the 26 raw controls (round 7 §4.1) and forwards them: controls 2,
+  3 and 13 go through raw (0/1), the others as `u = (v − min)·(1/(max − min))` in double, clamped to 0…1 and
+  rounded to float (`FUN_006e93b0`; ranges read from the controls at run time: Time 1…768, Time smoothing 0…1000,
+  Rate reduce 0…60000, Colour −3000…3000, the rest 0…6000 or 0…3). The tempo event goes to the engine's time info
+  (`FUN_006e9360`); `Eff_Render` splits the interleaved block, calls the engine's `processReplacing` and interleaves
+  back (`FUN_006e9b70`).
+- **Set-up order:** with the harness (state loaded, then the sample rate, then the block size) the engine behaves as
+  if its rate set-up ran twice after the state, first with the wrapper's creation rate (44 100) then with the new
+  rate — the only order that reproduces the DLL at 44.1 and 48 kHz (`py/t_seq.py`). In FL the host rate is the
+  project rate from the start, so both runs use the project rate (not confirmed directly in FL; LYNX starts settled,
+  §4).
+- The engine's controls (`FUN_1800029b0`, jump table at `0x180002f00`) — `u` = the value the wrapper sends:
+
+| i | Control | Engine law |
+|---|---|---|
+| 0 | Send | input gain `u` |
+| 1 | Delay type | `round(3u)`: 0 fake stereo, 1 true stereo, 2 ping pong, 3 off; a change clears the lines |
+| 2 | Tempo sync | on when ≥ 0.5 |
+| 3 | Keep pitch | on when ≥ 0.5 (time changes crossfade instead of gliding, §3.2) |
+| 4 | Time | §3.1 |
+| 5 | Time R / pan | `o = |u − 0.5|`; the side with u < 0.5 is the left; ping-pong input pan matrix: x = 2u − 1 ≥ 0 → `LL = 1−x`, `LR = (1−LL)/2`, `RR = 1 − LR`, `RL = 0`; else `RR = 1+x`, `RL = (1−RR)/2`, `LL = 1 − RL`, `LR = 0` |
+| 6 | Time smoothing | `T = u` seconds; glide coefficient `k = 1 − 0.01^{1/(T·rate)}` (1 when T = 0) |
+| 7 | Stereo spread | `a = 0.5u + 0.5`, `b = 1 − a`; outputs `L = a·cL + b·cR`, `R = a·cR + b·cL` |
+| 8 | Mod rate | LFO period from the table {8.872, 3.808, 1.833, 0.878, 0.398, 0.15, 0.05} s at `x = 0.99u·5.9994` (linear between entries); phase step `1/(rate·T)`; depth normaliser `√(T/8.872)` |
+| 9 | Mod amount | `0.1·u²` (u² in double) |
+| 10 | Cutoff mod | `0.5u` (LFO → cutoff) |
+| 11 | Diffusion | all-pass coefficient `g = 0.499·clamp(u)` (four all-passes) |
+| 12 | Diffusion spread | all-pass length, §3.1 |
+| 13 | Saturation type | `round(u)`: 0 limit, 1 saturate |
+| 14 | Feedback | `1.25u` |
+| 15 | Filter mode | `round(3u)`: LP, HP, BP, off |
+| 16, 17 | Cutoff, resonance | §3.4 |
+| 18 | Distortion | §3.5 |
+| 19, 20 | Hardness, symmetry | knee shape, §3.5 |
+| 21 | Rate reduce | `r = (1−u)³` |
+| 22 | Bit reduce | `q = (1−u)²`; scale `2^{(1 − √√q)·14 + 2}` |
+| 23 | Wet | `u` |
+| 24 | Colour | §3.6 |
+| 25 | Dry | `u` |
+
+- **Parameter smoothing** (`FUN_180002170`, `FUN_180002f70`): controls 0, 7, 10, 11, 14, 16–25 glide; every 8th
+  sample `x ← x + (target − x)·κ`, `κ = 1 − 0.01^{1/(0.005·rate)}`, applied through the law above; within 10⁻⁴ of the
+  target it snaps. The other controls apply at once. Starting values are the engine's defaults.
+- The engine renders with FTZ/DAZ on (`MXCSR | 0x8040`) and zeroes input samples inside ±10⁻¹³.
+
+---
+
+## 3. Fruity Delay 3 — the DSP **[DECOMP + EXEC]**
+
+### 3.1 Time law (`FUN_18000b1e0`) — closes round 8 §7.2
+
+- **Synced:** `n = trunc(767u + 0.5)`; seconds `t = ((n + 1)/192, float)·60/bpm`. The unit is **1/192 of a beat**
+  (raw 192 = 1 beat, 48 = a sixteenth; the editor shows `(n+1)/48 : (n+1)%48`). Round 7's "1/96" was wrong by 2.
+- **Unsynced:** `t = ((0.94u + 0.06)³ − 0.000216)·1.000216·0.999 + 0.001` seconds — 1 ms at the minimum, 1 s at the
+  maximum, a cubic in between (u = (raw − 1)/767; raw 80 ≈ 4.7 ms, 384 ≈ 149 ms). **Tempo-independent.**
+- `D = trunc(t·rate)` samples (as float). Diffusion length `n_d = trunc(max(1, min(1, D/(0.015·rate))·(rate/44100)·(590·spread + 65)))`.
+- **Fake stereo:** left tap `A = trunc(max(1, D − n_d))`, right tap `B = trunc(D − (1 − o)·D + A)` (swapped when the
+  offset is to the left), both read from one line fed with `(L+R)/2`.
+- **True stereo / ping pong:** main tap `C = trunc(max(1, D − n_d))`; the input pre-delays are 1 (no delay) and
+  `trunc(max(1, o²·D))` on the offset side.
+- The diffusion all-pass adds `n_d`, so the total is D.
+
+### 3.2 Time changes: glide or crossfade (`FUN_180008ff0`)
+
+Every tap length lives twice: an integer target and a double that the DSP reads. Without keep pitch the doubles
+glide `d ← d + (target − d)·k` per sample (k from control 6), snapping within 0.001 — the classic pitch-bending tape
+glide. With keep pitch, a change computes the other of two tap sets and crossfades linearly over `trunc(0.1·rate)`
+samples (weights updated after each sample). A host tempo change triggers the same.
+
+### 3.3 Per sample (`FUN_1800094b0` fake, `FUN_180009a20` true stereo, `FUN_18000a370` ping pong, mode 3 inline)
+
+1. LFO: output `(sin(2π·phase) + 1)/2` from the phase before the step (sine only — the shape is not a control).
+2. Modulation depth: `m ← m + (0.1u²·rate/2·norm − m)·(1 − 0.01^{1/(0.1·rate)})`; tap offset `(lfo + 0.5)·m` samples
+   (added in float for fake stereo, in double for the others).
+3. Filter coefficients every 4th sample (§3.4).
+4. Read the taps (linear interpolation between `w − i` and `w − i − 1`), weighted by the two tap sets.
+5. Feedback: the tap times `1.25u` (control 14) through a 10 Hz one-pole high-pass whose coefficients are computed at
+   44.1 kHz whatever the rate (fake stereo feeds back the left tap, or the right one when the offset is on the left).
+6. `send·input + feedback` → (fake stereo: saturation, then filter; the others: filter, then saturation) → two
+   all-passes (`y = (1 − g²)·d + g·x`, line fed `x − g·d`) → the main line(s); ping pong writes the left chain into
+   the right line and vice versa, its input through the pan matrix of control 5.
+7. Output: colour filter on each tap (§3.6) → spread → `wet·out + dry·in`; ping pong with saturation type 1 runs a
+   peak limiter (attack `1 − 0.1^{100/44100}`, release `1 − 0.1^{10/44100}`, divide when the envelope exceeds 1) on
+   its output. Delay type "Off" runs only filter → saturation → colour on the input (`wet·colour + dry·in`).
+
+Lines: 2²⁰ floats below 61 440 Hz (2²¹ up to 126 976 Hz, 2²² above), all-passes 2¹⁵.
+
+### 3.4 Filter (`FUN_18000ab70`, `FUN_18000bbe0/bcc0`)
+
+A state-variable filter (trapezoidal, two integrator states, outputs mixed by mode). Cutoff `c = clamp(cutoff +
+0.5u_mod·lfo)`; frequency from the tables LP/BP {270, 480, 1300, 7000, 22000} Hz and HP {20, 90, 400, 1300, 4200} Hz,
+interpolated at `3.999c` (BP: `3.6c`), at most 0.49·rate; `g = tan(f·3.1415/rate)` (the truncated π);
+`r = (clamp(res)/2)²`, `k = 1/(4r + 0.707)` (BP: `1/(4.6r + 0.107)`); `a1 = 1/((g + k)·g + 1)`, `a2 = a1·g`,
+`a3 = a2·g`; LP takes the second integrator, HP `x − k·v1 − v2`, BP `k·v1`. Mode "off" bypasses it.
+
+### 3.5 Saturation, distortion and the reducer (`FUN_18000b960/baa0`, `FUN_18000b0e0`, `FUN_18000bef0`, `FUN_1800011f0`)
+
+- **Rate reduce:** a sample-and-hold whose hold length is `max(1, (1 + 0.7435a − 0.0171a² + 0.0002a³)·rate/44100)`,
+  `a = 127r`, with a fractional counter carried over; **bit reduce:** `trunc(scale·x)/scale`. Both run first.
+- **Distortion** `x = 0.95u`: threshold `−30x` dB; makeup `(1/p)^{0.707}` with
+  `p = 2.9843x⁴ − 7.5177x³ + 6.8819x² − 3.1787x² + 1`.
+- **Limit (type 0):** divide by `10^{thr/20}·makeup`, an envelope on |x| (attack/release as in §3.3) divides when
+  above 1, multiply back.
+- **Saturate (type 1):** a soft knee per polarity — above the threshold `t = (1 ± symmetry)·10^{thr/20}·hardness` the
+  excess `d` (at most twice the knee width `w = max(10⁻¹¹, (1 ± symmetry)·10^{thr/20} − t)`) becomes
+  `(1 − d/(4w))·d + t`; times the makeup.
+
+### 3.6 Colour (`FUN_18000aeb0`)
+
+One-pole per channel: below 0.5 a low-pass from the LP table at `2u·3.9999`, above 0.5 a high-pass from the HP table
+at `2(u − 0.5)·3.9999`, exactly 0.5 = flat; `t = tan(f·π/rate)` (float π), LP `b0 = b1 = t/(t+1)`, HP
+`b0 = −b1 = 1/(t+1)`, `a1 = (1 − t)/(t + 1)`. A rate change recomputes them from the stored (≤ 0.49·rate) frequency.
+
+### 3.7 The engine's math library **[EXEC `py/t_math.py`, DECOMP `FUN_1800bf350`]**
+
+The engine links Microsoft's runtime: its `tan`/`pow` match glibc after rounding to float in every tested case
+(40 000 / 15 000 arguments), but its `sinf` differs from glibc's in 1.2 % of arguments and from `(float)sin(double)`
+in 0.1 %. On this machine (`__use_fma3_lib` = 1, read with `emem=`) it reduces the argument by π/2 in double with
+fused steps (two-part π/2) and evaluates degree-9/10 polynomials with FMA; LYNX evaluates the same steps with
+`std::fma`, which made the 22 modulation states bit-identical (they were at −119…−178 dB with a library sine).
+On a CPU without FMA the plugin takes a non-FMA path — not reproduced (not confirmed which CPUs FL users have).
+
+---
+
+## 4. What LYNX does with it
+
+- **`EffectKind::fruityDelay2` / `fruityDelay3`** (`core/FruityDelay`): mixer effects whose parameters are FL's raw
+  controls normalised over their ranges (so the generic LYNX editor edits them; the texts show FL's units). The FL
+  import routes every readable state there; the old approximations (round 7: generic delay snapped to 8 divisions)
+  remain only for unreadable states, which the import report lists. FL automation of the controls maps 1:1.
+- **Start-up:** FL runs the plugin long before playback; LYNX starts *settled*: Delay 2's input gains at their
+  targets, Delay 3's parameter glides, tap glides and modulation depth at their targets (the LFO starts at phase 0 —
+  FL's phase depends on how long it has been running).
+- **Tempo:** both follow the project tempo (Delay 2 recomputes its line on a change, Delay 3 glides or crossfades as
+  FL does). The engines themselves (`Delay2Engine`, `Delay3Engine`) also reproduce FL's own start (fade-in, glides),
+  which `tools/fdelayrender` uses for comparisons.
+
+---
+
+## 5. Verification **[EXEC]**
+
+| Check | Cases | Result |
+|---|---|---|
+| Delay 2 Python model vs DLL (`py/t_d2all.py`), music 2 s | 60 unique states × 120 / 87.5 BPM | 60/60 bit-identical at both tempos |
+| Delay 2 LYNX engine vs DLL (`py/t_all.py d2`), music 3 s | 60 states × 120 / 87.5 BPM | 60/60 bit-identical |
+| Delay 2 at 48 kHz, blocks of 300, noise bursts, 133 BPM (state loaded after the rate) | 60 states | 60/60 bit-identical |
+| Delay 3 LYNX engine vs DLL (`py/t_all.py d3`), music 3 s | 85 unique states × 120 / 87.5 BPM | 85/85 bit-identical at both tempos (63/85 before the FMA sine, worst −119.1 dB) |
+| Delay 3 at 48 kHz, blocks of 300, noise bursts, 133 BPM | 85 states | 84 bit-identical, 1 at −150.9 dB (a `tan` rounding in a cutoff-modulated filter, §6) |
+| Delay 3 random states (every control, types 0–3, filters 0–3, smoothing, keep pitch) | 40 @ 120 BPM, 40 @ 93 BPM | 80/80 bit-identical |
+| Delay 3 random states with a tempo change 128 → 97 BPM mid-render (glides / crossfades) | 30 | 30/30 bit-identical |
+| Unit tests (`tests/tests.cpp` `fruity_delay_engines`) | 5 Delay 3 + 3 Delay 2 states of our own vs DLL goldens; effects from FL states (echo positions at 2 tempos) | goldens within 2·10⁻⁶ (bit-identical when generated) |
+
+---
+
+## 6. Open items (not confirmed)
+
+- The order in which FL itself loads the state and sets the sample rate (§2): it decides whether a fresh FL instance
+  glides from the engine defaults; LYNX starts settled either way.
+- What Delay 2 keeps in its line after a resize (time/tempo change); LYNX clears it.
+- The plugin's non-FMA math path (other CPUs), and the engine's `tan` in rare roundings (one 48 kHz state at −151 dB).
+- The engine's GUI-only functions (`FUN_1800048d0`, `FUN_18000c030`) were not decoded.
+
+## Evidence index
+
+| Function / data | What | Marker |
+|---|---|---|
+| Delay 2 `FUN_006c0010` (ProcessParam), `FUN_006bfea0` (time/offset), `FUN_006bfdb0` (pan matrix), `FUN_006c0910` (render), `FUN_006bc060/1c0/2f0` + `FUN_006bbfa0/6bc0e0/6bc230` (mode loops), `FUN_005dff80` (ramp), `FUN_005df020` (input matrix), `FUN_005de9b0` (dry mix) | §1 | DECOMP + EXEC |
+| Delay 3 wrapper `FUN_006e93b0` (normalisation), `FUN_006e9360` (tempo), `FUN_006e9b70` (render), control ranges peeked at run time | §2 | DECOMP + EXEC |
+| engine `FUN_1800029b0` + jump table `0x180002f00` (laws), `FUN_180002170` + `FUN_180002f70` (smoother, process), `FUN_180004640` (rate), `FUN_1800088e0` (defaults), `FUN_180001540` (engine defaults) | §2 | DECOMP + EXEC |
+| `FUN_18000b1e0` (times), `FUN_180008ff0` (glide/crossfade), `FUN_1800094b0/9a20/a370` (modes), `FUN_1800012e0` (LFO), `FUN_18000b840` (LFO rate), tables at `0x180104a40/a68/a80` | §3.1–3.3 | DECOMP + EXEC |
+| `FUN_18000ab70` + `FUN_18000bbe0/bcc0` (filter), `FUN_18000b960/baa0` + `FUN_1800011f0` + `FUN_18000b0e0` + `FUN_18000bef0` (saturation), `FUN_18000aeb0` + `FUN_18000bdc0` (colour, one-poles), `FUN_18000b410` (lines, rates) | §3.4–3.6 | DECOMP + EXEC |
+| `FUN_1800bf350` (sinf, FMA path at `0x1800bf6f0`), `FUN_1800bfc40` (tan), `FUN_1800bcde0` (pow), `FUN_1800be480` (powf) | §3.7 | DECOMP + EXEC |

+ 2 - 1
scripts/build-local.sh

@@ -13,7 +13,7 @@ if [[ -z "${CXX:-}" ]]; then
 fi
 
 FLAGS="-std=c++20 -O2 -g -Wall -Wextra -Wpedantic -Isrc -Ithird_party/wavpack/include"
-CORE="src/flp/Flp.cpp src/core/Song.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/Vocodex.cpp src/core/MaximusFx.cpp src/core/FruityShapers.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/core/Scheduler.cpp src/core/Instruments.cpp src/core/RackRenderer.cpp src/core/FlpImport.cpp src/core/Effects.cpp"
+CORE="src/flp/Flp.cpp src/core/Song.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/Vocodex.cpp src/core/MaximusFx.cpp src/core/FruityDelay.cpp src/core/FruityShapers.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/core/Scheduler.cpp src/core/Instruments.cpp src/core/RackRenderer.cpp src/core/FlpImport.cpp src/core/Effects.cpp"
 
 mkdir -p build-local build-local/wavpack
 # workflow shell (key map, workspace layout, rack operations)
@@ -53,5 +53,6 @@ $CXX $FLAGS src/core/MiniSynth.cpp tools/minisynthrender.cpp -o build-local/mini
 $CXX $FLAGS src/core/Dx10.cpp tools/dx10render.cpp -o build-local/dx10render 2> >(grep -v 'glibc version' >&2)
 $CXX $FLAGS src/core/Kepler.cpp tools/keplerrender.cpp -o build-local/keplerrender 2> >(grep -v 'glibc version' >&2)
 $CXX $FLAGS src/core/PoiZone.cpp tools/poizonerender.cpp -o build-local/poizonerender 2> >(grep -v 'glibc version' >&2)
+$CXX $FLAGS src/core/FruityDelay.cpp tools/fdelayrender.cpp -o build-local/fdelayrender 2> >(grep -v 'glibc version' >&2)
 
 ./build-local/lynx_tests "$@"

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

@@ -75,7 +75,7 @@ APP_SOURCES=(src/Main.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/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/Vocodex.cpp src/core/MaximusFx.cpp src/core/FruityShapers.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
+             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/Vocodex.cpp src/core/MaximusFx.cpp src/core/FruityDelay.cpp src/core/FruityShapers.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
              src/platform/MingwFixes.cpp)
 
 # workflow shell: core (key map, workspace layout, rack operations) and UI (workspace desktop, control contract)

+ 26 - 0
src/core/Effects.cpp

@@ -8,6 +8,7 @@
 #include "core/MaximusFx.h"
 #include "core/FruityDynamics.h"
 #include "core/FruityShapers.h"
+#include "core/FruityDelay.h"
 
 #include "core/Biquad.h"
 
@@ -2174,6 +2175,21 @@ const EffectInfo& effectInfo (EffectKind kind)
                                                         { "Room size", 26000.0f / 65536 }, { "Diffusion", 1.0f }, { "Color", 0.5f },
                                                         { "Decay", 4700.0f / 65536 }, { "High damping", 10800.0f / 65536 }, { "Dry", 1.0f },
                                                         { "Wet", 13120.0f / 65536 } } };
+    // FL's raw controls normalised over their ranges (core/FruityDelay.h); defaults = FL's "Default" presets
+    static const EffectInfo fruityDelay2Info = [] {
+        EffectInfo info { "Fruity Delay 2", {} };
+        for (int i = 0; i < fldelay::delay2Controls; ++i)
+            info.params.push_back ({ fldelay::delay2ParamName (i), (float) (fldelay::delay2Default[(std::size_t) i] - fldelay::delay2Min[(std::size_t) i])
+                                                                      / (float) (fldelay::delay2Max[(std::size_t) i] - fldelay::delay2Min[(std::size_t) i]) });
+        return info;
+    }();
+    static const EffectInfo fruityDelay3Info = [] {
+        EffectInfo info { "Fruity Delay 3", {} };
+        for (int i = 0; i < fldelay::delay3Controls; ++i)
+            info.params.push_back ({ fldelay::delay3ParamName (i), (float) (fldelay::delay3Default[(std::size_t) i] - fldelay::delay3Min[(std::size_t) i])
+                                                                      / (float) (fldelay::delay3Max[(std::size_t) i] - fldelay::delay3Min[(std::size_t) i]) });
+        return info;
+    }();
     // raw FL values / max (the names are FL's controls, REA_rodada29 §2.1)
     static const EffectInfo squeezeInfo { "Squeeze", { { "Volume", 127.0f / 160.0f }, { "Mix", 0.5f }, { "Steps", 1.0f / 32768.0f },
                                                        { "Filter", 0.0f }, { "Filter type", 0.0f }, { "Resonance", 0.5f },
@@ -2275,6 +2291,8 @@ const EffectInfo& effectInfo (EffectKind kind)
         case EffectKind::fruitySoftClipper: return softClipperInfo;
         case EffectKind::reeverb2: return reeverb2Info;
         case EffectKind::reeverb1: return reeverb1Info;
+        case EffectKind::fruityDelay2: return fruityDelay2Info;
+        case EffectKind::fruityDelay3: return fruityDelay3Info;
     }
     return eq;
 }
@@ -2555,6 +2573,12 @@ std::string formatEffectParam (EffectKind kind, int param, float v, double bpm)
         case EffectKind::fruitySoftClipper:
             return flshape::softClipperParamText (param, v);
 
+        case EffectKind::fruityDelay2:
+            return fldelay::delay2ParamText (param, v);
+
+        case EffectKind::fruityDelay3:
+            return fldelay::delay3ParamText (param, v, bpm);
+
         case EffectKind::plugin:
         case EffectKind::parallel:
         case EffectKind::vocodex:
@@ -2630,6 +2654,8 @@ std::unique_ptr<Effect> makeEffect (EffectKind kind)
         case EffectKind::fruitySoftClipper: return flshape::makeSoftClipper();
         case EffectKind::reeverb2: return makeReeverb2();
         case EffectKind::reeverb1: return makeReeverb1();
+        case EffectKind::fruityDelay2: return fldelay::makeDelay2();
+        case EffectKind::fruityDelay3: return fldelay::makeDelay3();
         case EffectKind::pitchCorrect: return std::make_unique<PitchCorrect>();
         case EffectKind::plugin: break; // created by the app (RackState::Factories)
     }

+ 33 - 0
src/core/FlEffects.cpp

@@ -5,6 +5,7 @@
 #include "core/MaximusFx.h"
 #include "core/FruityDynamics.h"
 #include "core/FruityShapers.h"
+#include "core/FruityDelay.h"
 #include "core/SytrusEngine.h"
 #include "core/FlSynths.h"
 
@@ -972,8 +973,33 @@ std::optional<EffectSlot> fruityShaperExact (const std::string& pluginName, cons
     return std::nullopt;
 }
 
+std::optional<EffectSlot> fruityDelayExact (const std::string& pluginName, const std::vector<std::uint8_t>& state)
+{
+    // FL's own Fruity Delay 2 / Delay 3 engines from the saved controls (REA_rodada52); the approximations of
+    // REA_rodada7 remain for states that cannot be read (case-insensitive: FL 3 presets say "Fruity delay 2")
+    std::string lower = pluginName;
+    std::transform (lower.begin(), lower.end(), lower.begin(), [] (unsigned char c) { return (char) std::tolower (c); });
+    if (lower == "fruity delay 2")
+        if (const auto s = fldelay::parseDelay2 (state))
+        {
+            auto slot = makeEffectSlot (EffectKind::fruityDelay2);
+            fldelay::delay2ToParams (*s, slot.params.data());
+            return slot;
+        }
+    if (lower == "fruity delay 3")
+        if (const auto s = fldelay::parseDelay3 (state))
+        {
+            auto slot = makeEffectSlot (EffectKind::fruityDelay3);
+            fldelay::delay3ToParams (*s, slot.params.data());
+            return slot;
+        }
+    return std::nullopt;
+}
+
 std::optional<EffectSlot> effectFromFl (const std::string& pluginName, const std::vector<std::uint8_t>& state, double bpm)
 {
+    if (auto exact = fruityDelayExact (pluginName, state))
+        return exact;
     if (auto exact = fruityDynamicsExact (pluginName, state))
         return exact;
     if (auto exact = fruityShaperExact (pluginName, state))
@@ -1151,6 +1177,8 @@ std::vector<std::string> flPluginsForEffect (EffectKind kind)
         case EffectKind::reverb:
         case EffectKind::reeverb2: return { "Fruity Reeverb 2" };
         case EffectKind::delay: return { "Fruity Delay 3", "Fruity Delay 2" };
+        case EffectKind::fruityDelay2: return { "Fruity Delay 2" };
+        case EffectKind::fruityDelay3: return { "Fruity Delay 3" };
         case EffectKind::utility: return { "Fruity Stereo Shaper" };
         default: return {};
     }
@@ -1167,6 +1195,11 @@ std::optional<FlParamMap> effectParamFromFl (const std::string& pluginName, int
     // the exact WaveShaper (pre, mix, post) and Soft Clipper (threshold, post) take FL's controls over their ranges
     if ((is ("Fruity WaveShaper") && k >= 0 && k < 3) || (is ("Fruity Soft Clipper") && k >= 0 && k < 2))
         return FlParamMap { k, [] (float v) { return std::clamp (v, 0.0f, 1.0f); } };
+    // the exact Fruity Delay 2 / 3 likewise (every control)
+    if (is ("Fruity Delay 2") && k >= 0 && k < fldelay::delay2Controls)
+        return FlParamMap { k, [] (float v) { return std::clamp (v, 0.0f, 1.0f); } };
+    if (is ("Fruity Delay 3") && k >= 0 && k < fldelay::delay3Controls)
+        return FlParamMap { k, [] (float v) { return std::clamp (v, 0.0f, 1.0f); } };
 
     if (is ("Fruity Parametric EQ 2"))
     {

+ 3 - 1
src/core/FlpImport.cpp

@@ -1403,7 +1403,9 @@ Song importFlp (const flp::Project& input, const FlpImportOptions& options)
         else if (plugin == "Soundgoodizer")
             ++options.report->droppedEffects["Soundgoodizer (preset file not found: approximated)"];
         else if ((plugin == "Fruity Limiter" && fx.kind != EffectKind::fruityLimiter)
-                 || (plugin == "Fruity Compressor" && fx.kind != EffectKind::fruityCompressor))
+                 || (plugin == "Fruity Compressor" && fx.kind != EffectKind::fruityCompressor)
+                 || (plugin == "Fruity Delay 2" && fx.kind != EffectKind::fruityDelay2)
+                 || (plugin == "Fruity Delay 3" && fx.kind != EffectKind::fruityDelay3))
             ++options.report->droppedEffects[plugin + " (state not readable: approximated)"];
         else if ((plugin == "Fruity WaveShaper" && fx.kind != EffectKind::fruityWaveShaper)
                  || (plugin == "Fruity Soft Clipper" && fx.kind != EffectKind::fruitySoftClipper))

+ 1334 - 0
src/core/FruityDelay.cpp

@@ -0,0 +1,1334 @@
+#include "core/FruityDelay.h"
+
+#include <algorithm>
+#include <cmath>
+#include <cstdio>
+#include <cstring>
+
+#include "core/Denormals.h"
+
+// Bit-exactness with FL's plugins needs every float operation in the plugin's order and precision: no contraction
+// into fused multiply-adds, and the x87 extended precision of Delay 2's loops kept (long double; 80-bit on every x86
+// target LYNX is built for).
+#pragma GCC optimize ("fp-contract=off")
+#pragma STDC FP_CONTRACT OFF
+
+namespace lynx::fldelay
+{
+namespace
+{
+std::int32_t i32At (const std::vector<std::uint8_t>& d, std::size_t o) noexcept
+{
+    std::int32_t v = 0;
+    std::memcpy (&v, d.data() + o, 4);
+    return v;
+}
+
+// cvtsd2si: round to nearest, ties to even (the default SSE mode in FL and in LYNX)
+int roundEven (double x) noexcept { return (int) std::nearbyint (x); }
+} // namespace
+
+// =====================================================================================================================
+// Fruity Delay 2 (REA_rodada52 §2)
+// =====================================================================================================================
+
+const std::array<int, delay2Controls> delay2Min { -128, 0, 0, 0, 1, -512, 0, 0 };
+const std::array<int, delay2Controls> delay2Max { 128, 160, 160, 127, 768, 512, 2, 128 };
+const std::array<int, delay2Controls> delay2Default { 0, 128, 128, 64, 144, 0, 0, 128 };
+
+const char* delay2ParamName (int i) noexcept
+{
+    static const char* names[] { "Input pan", "Input volume", "Dry", "Feedback", "Time", "Stereo offset", "Mode", "Cutoff" };
+    return i >= 0 && i < delay2Controls ? names[i] : "";
+}
+
+std::optional<Delay2State> parseDelay2 (const std::vector<std::uint8_t>& state)
+{
+    if (state.size() < 32)
+        return std::nullopt;
+    Delay2State s;
+    for (int i = 0; i < delay2Controls; ++i)
+        s.v[(std::size_t) i] = std::clamp (i32At (state, 4 * (std::size_t) i), delay2Min[(std::size_t) i], delay2Max[(std::size_t) i]);
+    return s;
+}
+
+namespace
+{
+// FL's volume law: 1 at the unit position, else (11^x − 1)/10 with ln 11 as a float
+float flVolume (int raw) noexcept
+{
+    const auto x = (float) raw * 0.0078125f;
+    if (x == 1.0f)
+        return 1.0f;
+    constexpr float ln11 = 2.39789534f;
+    return (float) ((std::exp ((double) (x * ln11)) - 1.0) * (double) 0.1f);
+}
+
+// a per-sample linear ramp toward a target, its slope limited to `maxStep` per sample (start, increment, new value)
+struct Ramp
+{
+    float start, inc;
+};
+
+Ramp ramp (float& cur, float target, float maxStep, int n) noexcept
+{
+    const auto start = cur;
+    auto delta = target - start;
+    if (delta == 0.0f)
+        return { start, 0.0f };
+    cur = target;
+    delta = delta / (float) n;
+    if (std::fabs (delta) > maxStep)
+    {
+        delta = std::copysign (maxStep, delta);
+        cur = start + delta * (float) n;
+        if (std::fabs (cur) < 1.17549435e-38f)
+        {
+            cur = 0.0f;
+            delta = -start / (float) n;
+        }
+    }
+    return { start, delta };
+}
+} // namespace
+
+Delay2Engine::Delay2Engine (const Delay2State& s, double sampleRate, double bpm, int maxBlock, bool settled)
+    : rate (sampleRate), block (maxBlock)
+{
+    fbCur = (float) s.v[3] * 0.0078125f;
+    tmp.resize ((std::size_t) maxBlock * 2);
+    set (s, bpm);
+    if (settled)
+        for (int k = 0; k < 4; ++k)
+            gCur[k] = gTarget[k];
+}
+
+void Delay2Engine::set (const Delay2State& s, double bpm)
+{
+    const auto& p = s.v;
+    const auto ratio = 44100.0 / rate;
+    step = (float) (0.001 * ratio);
+    const auto pan = (float) p[0] * 0.0078125f;
+    const auto vol = flVolume (p[1]);
+    dry = flVolume (p[2]);
+    fbTarget = (float) p[3] * 0.0078125f;
+    if (pan >= 0.0f)
+    {
+        auto g0 = 1.0f - pan;
+        const auto g3 = ((1.0f - g0) * 0.5f) * vol;
+        g0 = g0 * vol;
+        gTarget[0] = g0;
+        gTarget[1] = vol - g3;
+        gTarget[2] = 0.0f;
+        gTarget[3] = g3;
+    }
+    else
+    {
+        auto g1 = pan + 1.0f;
+        const auto g2 = ((1.0f - g1) * 0.5f) * vol;
+        g1 = g1 * vol;
+        gTarget[0] = vol - g2;
+        gTarget[1] = g1;
+        gTarget[2] = g2;
+        gTarget[3] = 0.0f;
+    }
+    mode = p[6];
+    const auto c = (float) ((double) (float) (std::exp ((double) ((float) p[7] * 0.0078125f) * std::log (21.0)) - 1.0) * 0.05 * ratio);
+    coef = c < 1.0f ? c : 1.0f;
+    const auto off = (float) ((double) (float) (std::exp ((double) ((float) std::abs (p[5]) * 0.001953125f) * std::log (1001.0)) - 1.0) * 50.0);
+    const auto offSamples = roundEven ((double) ((off * (float) rate) / 100000.0f));
+    const auto delay = std::max (1, roundEven ((double) (p[4] * (int) rate) * 0.3125 / (double) (float) bpm));
+    const auto sign = p[5] <= 0 ? 0 : 1;
+    if (! line.empty() && delay == delaySamples && offSamples == offsetSamples && sign == offsetSign)
+        return;
+    delaySamples = delay;
+    offsetSamples = offSamples;
+    offsetSign = sign;
+    offL = sign == 0 ? offSamples : 0;
+    offR = sign == 0 ? 0 : offSamples;
+    frames = delay + block + offSamples;
+    line.assign ((std::size_t) frames * 2, 0.0f);
+    readPos = 0;
+    writePos = delay;
+}
+
+void Delay2Engine::process (float* left, float* right, int n) noexcept
+{
+    if (n <= 0)
+        return;
+    // input pan/volume matrix, each gain ramping toward its target
+    float g[4], gi[4];
+    for (int k = 0; k < 4; ++k)
+    {
+        const auto r = ramp (gCur[k], gTarget[k], step, n);
+        g[k] = r.start;
+        gi[k] = r.inc;
+    }
+    const bool ramping = gi[0] != 0.0f || gi[1] != 0.0f || gi[2] != 0.0f || gi[3] != 0.0f;
+    for (int i = 0; i < n; ++i)
+    {
+        const auto l = left[i], r = right[i];
+        tmp[(std::size_t) (2 * i)] = l * g[0] + r * g[2];
+        tmp[(std::size_t) (2 * i + 1)] = r * g[1] + l * g[3];
+        if (ramping)
+            for (int k = 0; k < 4; ++k)
+                g[k] += gi[k];
+    }
+    // into the line, each channel ahead of the write position by its stereo offset
+    for (int i = 0; i < n; ++i)
+    {
+        auto a = (writePos + offL + i) % frames;
+        line[(std::size_t) (2 * a)] += tmp[(std::size_t) (2 * i)];
+        a = (writePos + offR + i) % frames;
+        line[(std::size_t) (2 * a + 1)] += tmp[(std::size_t) (2 * i + 1)];
+    }
+    // the loop: x87 extended precision, states kept as doubles between blocks
+    const auto fr = ramp (fbCur, fbTarget, step, n);
+    long double fb = fr.start;
+    const long double inc = fr.inc, c = coef, thr = 5.9604644775390625e-08L;
+    long double sL = stL, sR = stR;
+    const bool toDst = dry == 0.0f;
+    for (int i = 0; i < n; ++i)
+    {
+        auto* rd = &line[(std::size_t) (2 * readPos)];
+        auto* wr = &line[(std::size_t) (2 * writePos)];
+        const long double lL = rd[0], lR = rd[1];
+        long double oL, oR, fL, fR;
+        if (mode == 0)
+            oL = lL, oR = lR, fL = lL, fR = lR;
+        else if (mode == 1)
+            oL = lR, oR = lL, fL = lL, fR = lR;
+        else
+            oL = lR, oR = lL, fL = lR, fR = lL;
+        auto y = (fL * fb + (long double) wr[0] - sL) * c + sL;
+        sL = y;
+        wr[0] = std::fabs (y) > thr ? (float) y : 0.0f;
+        y = (fR * fb + (long double) wr[1] - sR) * c + sR;
+        sR = y;
+        wr[1] = std::fabs (y) > thr ? (float) y : 0.0f;
+        fb += inc;
+        rd[0] = rd[1] = 0.0f;
+        readPos = readPos + 1 == frames ? 0 : readPos + 1;
+        writePos = writePos + 1 == frames ? 0 : writePos + 1;
+        if (toDst)
+        {
+            left[i] = (float) oL;
+            right[i] = (float) oR;
+        }
+        else
+        {
+            const long double dg = dry;
+            left[i] = (float) ((long double) left[i] * dg + (long double) (float) oL);
+            right[i] = (float) ((long double) right[i] * dg + (long double) (float) oR);
+        }
+    }
+    stL = (double) sL;
+    stR = (double) sR;
+}
+
+// =====================================================================================================================
+// Fruity Delay 3 (REA_rodada52 §3)
+// =====================================================================================================================
+
+const std::array<int, delay3Controls> delay3Min { 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -3000, 0 };
+const std::array<int, delay3Controls> delay3Max { 6000, 3, 1, 1, 768, 6000, 1000, 6000, 6000, 6000, 6000, 6000, 6000, 1, 6000, 3, 6000, 6000, 6000, 6000, 6000, 60000, 6000, 6000, 3000, 6000 };
+// FL's "Default" preset
+const std::array<int, delay3Controls> delay3Default { 6000, 1, 1, 0, 192, 3000, 500, 6000, 3000, 0, 0, 0, 0, 1, 3000, 0, 6000, 0, 0, 0, 0, 60000, 6000, 6000, 0, 6000 };
+
+const char* delay3ParamName (int i) noexcept
+{
+    static const char* names[] { "Send", "Delay type", "Tempo sync", "Keep pitch", "Time", "Time R / pan", "Time smoothing",
+                                 "Stereo spread", "Mod rate", "Mod amount", "Cutoff mod", "Diffusion", "Diffusion spread",
+                                 "Saturation type", "Feedback", "Filter mode", "Cutoff", "Resonance", "Distortion", "Hardness",
+                                 "Symmetry", "Rate reduce", "Bit reduce", "Wet", "Colour", "Dry" };
+    return i >= 0 && i < delay3Controls ? names[i] : "";
+}
+
+std::optional<Delay3State> parseDelay3 (const std::vector<std::uint8_t>& state)
+{
+    if (state.size() < 4 + 4 * (std::size_t) delay3Controls || i32At (state, 0) != 1)
+        return std::nullopt;
+    Delay3State s;
+    for (int i = 0; i < delay3Controls; ++i)
+        s.v[(std::size_t) i] = i32At (state, 4 + 4 * (std::size_t) i);
+    return s;
+}
+
+float delay3EngineValue (int control, int raw) noexcept
+{
+    if (control == 2 || control == 3 || control == 13)
+        return (float) raw;
+    const auto lo = delay3Min[(std::size_t) control], hi = delay3Max[(std::size_t) control];
+    auto u = (double) (raw - lo) * (1.0 / (double) (hi - lo));
+    u = u < 0.0 ? 0.0 : (u > 1.0 ? 1.0 : u);
+    return (float) u;
+}
+
+namespace
+{
+constexpr float lfoPeriods[8] { 8.872f, 3.808f, 1.833f, 0.878f, 0.398f, 0.15f, 0.05f, 0.0f };
+constexpr float lowTable[5] { 270.0f, 480.0f, 1300.0f, 7000.0f, 22000.0f };
+constexpr float highTable[5] { 20.0f, 90.0f, 400.0f, 1300.0f, 4200.0f };
+
+float tableAt (const float* t, float x) noexcept
+{
+    const auto i = (int) x;
+    const auto fr = x - (float) i;
+    return (1.0f - fr) * t[i] + fr * t[i + 1];
+}
+
+// The engine's float sine, as its runtime library computes it on a CPU with FMA (REA_rodada52 §3.9): the argument in
+// double, reduced by multiples of π/2 (two-part constant, fused steps), then the degree-9 sine or degree-10 cosine
+// polynomial evaluated with fused multiply-adds, the quadrant's sign applied and the result rounded to float.
+float sineF (float x) noexcept
+{
+    const auto xd = (double) x;
+    const auto ax = std::fabs (xd);
+    const auto sinPoly = [] (double r) noexcept
+    {
+        const auto r2 = r * r;
+        auto p = std::fma (r2, 2.7557319223985893e-06, -0.0001984126984126984);
+        p = std::fma (p, r2, 0.008333333333333333);
+        p = std::fma (p, r2, -0.16666666666666666);
+        return std::fma (p, r * r2, r);
+    };
+    if (ax <= 0.78539816339744828) // π/4
+    {
+        if (ax >= 0.0078125)
+            return (float) sinPoly (xd);
+        if (ax >= 0.0001220703125)
+            return (float) std::fma (-(xd * xd * xd), 0.16666666666666666, xd);
+        return x;
+    }
+    const auto n = (int) std::fma (ax, 0.6366197723675814, 0.5);
+    const auto fn = (double) n;
+    const auto r = std::fma (-fn, 1.5707963267341256, ax) - fn * 6.077100506506192e-11;
+    double y;
+    if ((n & 1) != 0)
+    {
+        const auto r2 = r * r;
+        const auto a = std::fma (r2, -0.5, 1.0);
+        auto b = std::fma (r2, -2.755731922398589e-07, 2.4801587301587298e-05);
+        b = std::fma (b, r2, -0.0013888888888888887);
+        b = std::fma (b, r2, 0.041666666666666664);
+        y = std::fma (b, r2 * r2, a);
+    }
+    else
+        y = sinPoly (r);
+    if ((n & 3) >= 2)
+        y = -y;
+    if (std::signbit (x))
+        y = -y;
+    return (float) y;
+}
+float tanF (float x) noexcept { return (float) std::tan ((double) x); }
+float powF (float b, float e) noexcept { return (float) std::pow ((double) b, (double) e); }
+float sqrtF (float x) noexcept { return std::sqrt (x); }
+
+// (int) of a non-negative float through 64 bits, its low 32 bits read back unsigned (the delay-index arithmetic)
+inline std::uint32_t truncIndex (float x) noexcept { return (std::uint32_t) (std::int64_t) x; }
+
+struct Line
+{
+    std::vector<float> buf;
+    std::uint32_t idx = 0, mask = 0;
+
+    void init (std::uint32_t size) { buf.assign (size, 0.0f); idx = 0; mask = size - 1; }
+    void clear() noexcept { std::fill (buf.begin(), buf.end(), 0.0f); }
+    // linear interpolation `d` samples behind position `w`
+    float read (std::uint32_t w, float d) const noexcept
+    {
+        const auto i = truncIndex (d);
+        const auto fr = d - (float) i;
+        const auto a = w - i;
+        return (1.0f - fr) * buf[a & mask] + fr * buf[(a - 1) & mask];
+    }
+    void push (float x) noexcept
+    {
+        buf[idx] = x;
+        idx = (idx + 1) & mask;
+    }
+};
+
+struct AllPass
+{
+    float g = 0.0f; // the diffusion amount (scaled by 0.499 when used)
+    Line line;
+};
+
+struct Svf
+{
+    float ic1 = 0, ic2 = 0, m0 = 0, m1 = 0, m2 = 1, a1 = 0, a2 = 0, a3 = 0;
+
+    float run (float x) noexcept
+    {
+        const auto v3 = x - ic2;
+        const auto v1 = ic1 * a1 + a2 * v3;
+        const auto v2 = ic1 * a2 + ic2 + a3 * v3;
+        ic1 = (v1 + v1) - ic1;
+        ic2 = (v2 + v2) - ic2;
+        return v1 * m1 + x * m0 + v2 * m2;
+    }
+};
+
+struct Reducer
+{
+    float amount = 0, bitsOn = 0, scale = 0, held = 0, ratio = 1, counter = 0;
+
+    float run (float x) noexcept
+    {
+        if (amount > 0.0f)
+        {
+            const auto a = amount * 127.0f;
+            auto p = a * 0.0002f * a * a - a * 0.0171f * a;
+            p = p + a * 0.7435f;
+            p = p + 1.0f;
+            const auto c = counter + 1.0f;
+            counter = c;
+            p = p * ratio;
+            const auto m = 1.0f > p ? 1.0f : p; // maxss
+            if (c < m)
+                x = held;
+            else if (0.0f > c || 0.0f >= m)
+            {
+                held = x;
+                counter = 0.0f;
+            }
+            else
+            {
+                held = x;
+                const auto q = c / m;
+                counter = (q - (float) (int) q) * c;
+            }
+        }
+        if (bitsOn > 0.0f)
+            return (float) (int) (scale * x) / scale;
+        return x;
+    }
+};
+
+struct OnePole
+{
+    float y1 = 0, x1 = 0, b0 = 1, b1 = 0, a1 = 0, freq = 0, piOverSr = 0;
+    int type = 2;
+    double rate = 44100.0;
+
+    // FL's set-up at a sample rate (the frequency argument is the previous one, as the plugin computes it)
+    void setRate (double sr) noexcept
+    {
+        rate = sr;
+        piOverSr = (float) (1.0 / sr) * 3.14159274f;
+        if (type == 0 || type == 1)
+        {
+            const auto arg = piOverSr * freq;
+            const auto lim = (float) sr * 0.49f;
+            freq = freq < lim ? freq : lim;
+            const auto t = tanF (arg);
+            if (type == 0)
+            {
+                b0 = t / (t + 1.0f);
+                b1 = b0;
+            }
+            else
+            {
+                b0 = 1.0f / (t + 1.0f);
+                b1 = -b0;
+            }
+            a1 = -(t - 1.0f) / (t + 1.0f);
+        }
+        else
+        {
+            type = 2;
+            b0 = 1.0f;
+            b1 = 0.0f;
+            a1 = 0.0f;
+        }
+    }
+    float run (float x) noexcept
+    {
+        const auto y = b0 * x + b1 * x1 + a1 * y1;
+        x1 = x;
+        y1 = y;
+        return y;
+    }
+};
+} // namespace
+
+struct Delay3Engine::Dsp
+{
+    double sr = 44100.0, tempo = 120.0;
+    // modulation LFO (sine)
+    float lfoPhase = 0, lfoRate = 0, lfoOut = 0, lfoInc = 0, lfoNorm = 1;
+    bool sync = false, keepPitch = false;
+    float distDb = 0, hardness = 1, symmetry = 0;
+    int filterMode = 0, coefCounter = 0, satType = 0;
+    float halfRate = 22050, cutoffMod = 0, send = 0.5f, dryMul = 1, colour = 0.5f, res = 0, cutoff = 0.5f;
+    float modAmt = 0, modDepth = 0, modCoef = 0, feedback = 0.99f, dry = 0.5f;
+    float panLL = 0.5f, panLR = 0, panRR = 0, panRL = 0.5f, spreadA = 1, spreadB = 0;
+    Line inL, inR, mainL, mainR;
+    float srF = 44100, piOverSr = 0;
+    Svf svfL, svfR;
+    Reducer redL, redR;
+    OnePole fbL, fbR, colL, colR;
+    float envL = 0, attack = 0, release = 0, envR = 0;
+    bool recompute = true;
+    int mode = 0;
+    float wet = 1;
+    AllPass ap[4];
+    bool fading = false;
+    int fadeFrom = 0, fadeTo = 1, fadeLen = 1000, fadeCount = 0;
+    float fadeStep = 0, weight[2] { 1.0f, 0.0f };
+    float diffSpread = 0.5f, time = 0, offset = 0.5f;
+    int nd[2] { 10, 10 }, dA[2] { 0, 0 }, dB[2] { 0, 0 }, dC[2] { 10, 10 };
+    double gnd[2] {}, gA[2] {}, gB[2] {}, gC[2] {};
+    bool offLeft = false;
+    double smoothK = 1.0, smoothT = 0.1;
+    float distPre = 1, distPost = 1;
+    float ws[8] {}, wsA = 0, wsB = 0, wsC = 0;
+
+    Dsp()
+    {
+        for (auto& a : ap)
+            a.line.init (0x8000);
+        const auto atk = (float) std::pow (0.1, 0.0022675736961451248);
+        const auto rel = (float) std::pow (0.1, 0.00022675736961451248);
+        attack = 1.0f - atk;
+        release = 1.0f - rel;
+        fbL.type = fbR.type = 0;
+        colL.type = colR.type = 0;
+        shaper (-3.0f, 1.0f, 0.0f);
+        setDistortion (0.0f);
+        prepare (44100.0);
+        setColour (0.5f);
+        cutoff = 0.5f;
+        cutoffMod = 0.0f;
+    }
+
+    // --- set-up ------------------------------------------------------------------------------------------------------
+    void setLfoRate (float x) noexcept
+    {
+        lfoRate = x;
+        const auto s = x * 5.9994001f;
+        const auto i = (int) s;
+        const auto fr = s - (float) i;
+        const auto period = (1.0f - fr) * lfoPeriods[i] + fr * lfoPeriods[i + 1];
+        lfoInc = 1.0f / ((float) sr * period);
+        const auto first = lfoPeriods[1] * 0.0f + lfoPeriods[0];
+        lfoNorm = (float) std::sqrt ((double) (period / first));
+    }
+
+    void shaper (float db, float hard, float sym) noexcept
+    {
+        wsA = db;
+        wsB = hard;
+        wsC = sym;
+        const auto g = powF (10.0f, db / 20.0f);
+        auto hi = (sym + 1.0f) * g;
+        auto lo = (1.0f - sym) * g;
+        ws[0] = hi * hard;
+        hi = hi - ws[0];
+        ws[1] = 1.0e-11f > hi ? 1.0e-11f : hi; // maxss
+        ws[2] = ws[1] + ws[1];
+        ws[3] = 0.25f / ws[1];
+        ws[4] = lo * hard;
+        lo = lo - ws[4];
+        ws[5] = 1.0e-11f > lo ? 1.0e-11f : lo;
+        ws[7] = 0.25f / ws[5];
+        ws[6] = ws[5] + ws[5];
+    }
+
+    void setDistortion (float v) noexcept
+    {
+        const auto x = v * 0.95f;
+        distDb = x * -30.0f;
+        shaper (distDb, hardness, symmetry);
+        auto p = x * 2.9842999f * x * x * x - x * 7.5177002f * x * x;
+        p = p + x * 6.8818998f * x;
+        p = p - x * 3.1787f * x;
+        p = p + 1.0f;
+        distPost = (float) std::pow ((double) (1.0f / p), (double) 0.707f);
+        distPre = powF (10.0f, distDb / 20.0f) * distPost;
+    }
+
+    void setColour (float v) noexcept
+    {
+        colour = v;
+        if (0.5f > v)
+        {
+            const auto f = tableAt (lowTable, (v + v) * 3.9999001f);
+            const auto t = tanF (f * colL.piOverSr);
+            colL.type = 0;
+            colL.freq = std::min (f, (float) colL.rate * 0.49f);
+            colL.b0 = t / (t + 1.0f);
+            colL.b1 = colL.b0;
+            colL.a1 = -(t - 1.0f) / (t + 1.0f);
+        }
+        else if (v == 0.5f)
+        {
+            colL.type = 2;
+            colL.b0 = 1.0f;
+            colL.b1 = 0.0f;
+            colL.a1 = 0.0f;
+        }
+        else
+        {
+            const auto f = tableAt (highTable, ((v - 0.5f) + (v - 0.5f)) * 3.9999001f);
+            const auto t = tanF (f * colL.piOverSr);
+            colL.type = 1;
+            colL.freq = std::min (f, (float) colL.rate * 0.49f);
+            colL.b0 = 1.0f / (t + 1.0f);
+            colL.b1 = -colL.b0;
+            colL.a1 = -(t - 1.0f) / (t + 1.0f);
+        }
+        colR.b0 = colL.b0;
+        colR.b1 = colL.b1;
+        colR.a1 = colL.a1;
+        colR.freq = colL.freq;
+        colR.type = colL.type;
+    }
+
+    void prepare (double rate)
+    {
+        sr = rate;
+        halfRate = (float) (rate * 0.5);
+        setLfoRate (lfoRate);
+        redL.ratio = redR.ratio = (float) (rate / 44100.0);
+        // the feedback filters: 10 Hz high-passes computed at 44.1 kHz whatever the rate
+        fbL.setRate (44100.0);
+        fbR.setRate (44100.0);
+        for (auto* f : { &fbL, &fbR })
+        {
+            f->type = 1;
+            f->freq = std::min (10.0f, (float) f->rate * 0.49f);
+            const auto t = tanF (f->piOverSr * 10.0f);
+            f->b0 = 1.0f / (t + 1.0f);
+            f->b1 = -f->b0;
+            f->a1 = -(t - 1.0f) / (t + 1.0f);
+        }
+        colL.setRate (rate);
+        colR.setRate (rate);
+        srF = (float) rate;
+        piOverSr = (float) (3.1415 / rate);
+        std::uint32_t size = 0x100000;
+        if (rate > 126976.0)
+            size = 0x400000;
+        else if (rate > 61440.0)
+            size = 0x200000;
+        inL.init (size);
+        inR.init (size);
+        mainL.init (size);
+        mainR.init (size);
+        fadeLen = (int) (rate * 0.1);
+        fadeStep = 1.0f / (float) fadeLen;
+        clear();
+        smoothK = smoothT != 0.0 ? 1.0 - std::pow (0.01, 1.0 / (smoothT * rate)) : 1.0;
+        modCoef = (float) (1.0 - std::pow (0.01, 1.0 / (rate * 0.1)));
+    }
+
+    void clear() noexcept
+    {
+        inL.clear();
+        inR.clear();
+        mainL.clear();
+        mainR.clear();
+        for (auto& a : ap)
+            a.line.clear();
+        svfL.ic1 = svfL.ic2 = svfR.ic1 = svfR.ic2 = 0.0f;
+        fbL.y1 = fbL.x1 = fbR.y1 = fbR.x1 = 0.0f;
+        redL.held = redR.held = 0.0f;
+        for (int k = 0; k < 2; ++k)
+        {
+            gnd[k] = nd[k];
+            gA[k] = dA[k];
+            gB[k] = dB[k];
+            gC[k] = dC[k];
+        }
+        times (0);
+        times (1);
+    }
+
+    // the delay lengths of set k (REA_rodada52 §3.3)
+    void times (int k) noexcept
+    {
+        double t;
+        if (! sync)
+        {
+            const auto u = (double) time * 0.94 + 0.06;
+            t = (u * u * u - 0.000216) * 1.0002160466660799 * 0.999 + 0.001;
+        }
+        else
+        {
+            const auto n = (int) (std::int64_t) (767.0 * (double) time + 0.5);
+            t = (double) ((float) (n + 1) / 192.0f) * (1.0 / (tempo / 60.0));
+        }
+        const auto total = (float) (int) (t * sr);
+        const auto r = total / ((float) sr * 0.015f);
+        const auto m = 1.0f < r ? 1.0f : r; // minss
+        const auto s = (float) (sr / 44100.0) * (diffSpread * 590.0f + 65.0f);
+        const auto ndv = m * s;
+        nd[k] = (int) (1.0f > ndv ? 1.0f : ndv);
+        offLeft = 0.5f > offset;
+        const auto o = (std::fabs (offset - 0.5f) + std::fabs (offset - 0.5f)) * 0.5f;
+        if (mode == 0)
+        {
+            const auto main = total - (float) nd[k];
+            dA[k] = (int) (1.0f > main ? 1.0f : main);
+            dB[k] = (int) ((total - (1.0f - o) * total) + (float) dA[k]);
+            if (offLeft)
+                std::swap (dA[k], dB[k]);
+        }
+        else if (mode == 1 || mode == 2)
+        {
+            dA[k] = 1;
+            const auto main = total - (float) nd[k];
+            const auto pre = o * total * o;
+            dC[k] = (int) (1.0f > main ? 1.0f : main);
+            dB[k] = (int) (1.0f > pre ? 1.0f : pre);
+            if (! offLeft)
+            {
+                dA[k] = dB[k];
+                dB[k] = 1;
+            }
+        }
+    }
+
+    // --- per sample --------------------------------------------------------------------------------------------------
+    void lfoTick() noexcept
+    {
+        const auto p = lfoPhase;
+        auto np = p + lfoInc;
+        np = np - (float) (int) np;
+        lfoOut = (sineF (p * 6.28318548f) + 1.0f) * 0.5f;
+        lfoPhase = np;
+    }
+
+    float modOffset() noexcept
+    {
+        auto target = modAmt * halfRate;
+        target = target * lfoNorm;
+        modDepth = (target - modDepth) * modCoef + modDepth;
+        return (lfoOut + 0.5f) * modDepth;
+    }
+
+    void coefficients() noexcept
+    {
+        if (coefCounter == 0 && filterMode <= 2)
+        {
+            auto x = cutoffMod * lfoOut;
+            x = x + cutoff;
+            const auto c = 0.0f > x ? 0.0f : (1.0f < x ? 1.0f : x);
+            auto r = 0.0f > res ? 0.0f : (1.0f < res ? 1.0f : res);
+            r = r * 0.5f;
+            r = r * r;
+            float k, f;
+            if (filterMode == 2)
+            {
+                k = 1.0f / (r * 4.5999999f + 0.107f);
+                f = tableAt (lowTable, c * 3.5999999f);
+            }
+            else
+            {
+                k = 1.0f / (r * 4.0f + 0.707f);
+                f = tableAt (filterMode == 1 ? highTable : lowTable, c * 3.9990001f);
+            }
+            const auto lim = srF * 0.49f;
+            const auto fc = lim > f ? f : lim;
+            const auto g = tanF (fc * piOverSr);
+            if (filterMode == 2)
+                svfL.m0 = 0.0f, svfL.m1 = k, svfL.m2 = 0.0f;
+            else if (filterMode == 1)
+                svfL.m0 = 1.0f, svfL.m1 = -k, svfL.m2 = -1.0f;
+            else
+                svfL.m0 = 0.0f, svfL.m1 = 0.0f, svfL.m2 = 1.0f;
+            svfL.a1 = 1.0f / ((g + k) * g + 1.0f);
+            svfL.a2 = svfL.a1 * g;
+            svfL.a3 = g * svfL.a2;
+            svfR.m0 = svfL.m0, svfR.m1 = svfL.m1, svfR.m2 = svfL.m2;
+            svfR.a1 = svfL.a1, svfR.a2 = svfL.a2, svfR.a3 = svfL.a3;
+        }
+        coefCounter = (coefCounter + 1) & 3;
+    }
+
+    float filter (Svf& s, float x) const noexcept { return filterMode >= 3 ? x : s.run (x); }
+
+    float saturate (Reducer& red, float& env, float x) noexcept
+    {
+        x = red.run (x);
+        if (satType == 0)
+        {
+            x = x / distPre;
+            const auto a = std::fabs (x);
+            env = a < env ? env + (a - env) * release : env + (a - env) * attack;
+            if (env > 1.0f)
+                x = x / env;
+            return distPre * x;
+        }
+        if (satType != 1)
+            return 0.0f;
+        // soft knee above the threshold, separately for each polarity (minss: the knee width when it is smaller)
+        if (x >= 0.0f)
+        {
+            if (ws[0] > x)
+                return x * distPost;
+            const auto over = x - ws[0];
+            const auto d = ws[2] < over ? ws[2] : over;
+            return ((1.0f - d * ws[3]) * d + ws[0]) * distPost;
+        }
+        const auto n = -x;
+        if (ws[4] > n)
+            return x * distPost;
+        const auto over = n - ws[4];
+        const auto d = ws[6] < over ? ws[6] : over;
+        return -((1.0f - d * ws[7]) * d + ws[4]) * distPost;
+    }
+
+    float allPass (AllPass& a, double delay, float s, float& out) noexcept
+    {
+        const auto g = a.g * 0.49900001f;
+        const auto d = a.line.read (a.line.idx, (float) delay);
+        a.line.push (s - d * g);
+        out = (1.0f - g * g) * d + g * s;
+        return d;
+    }
+
+    float colourRun (OnePole& f, float x) noexcept
+    {
+        const auto y = x * f.b0 + f.b1 * f.x1 + f.a1 * f.y1;
+        f.x1 = x;
+        f.y1 = y;
+        return y;
+    }
+
+    float feedbackRun (OnePole& f, float x) noexcept
+    {
+        const auto y = x * f.b0 + f.b1 * f.x1 + f.a1 * f.y1;
+        f.x1 = x;
+        f.y1 = y;
+        return y;
+    }
+
+    void modeFake (float& L, float& R, float A, float B) noexcept
+    {
+        const auto in = ((L + R) * 0.5f) * send;
+        lfoTick();
+        const auto mod = modOffset();
+        coefficients();
+        const auto w = mainL.idx;
+        const auto outL = mainL.read (w, (float) gA[0] + mod) * A + mainL.read (w, (float) gA[1] + mod) * B;
+        const auto outR = mainL.read (w, (float) gB[0] + mod) * A + mainL.read (w, (float) gB[1] + mod) * B;
+        const auto fb = feedbackRun (fbL, feedback * (offLeft ? outR : outL));
+        const auto s = filter (svfL, saturate (redL, envL, fb + in));
+        float o1, o2;
+        allPass (ap[0], gnd[0], s, o1);
+        allPass (ap[1], gnd[1], s, o2);
+        mainL.push (o2 * B + o1 * A);
+        const auto cL = colourRun (colL, outL);
+        const auto cR = colourRun (colR, outR);
+        L = (spreadB * cR + spreadA * cL) * wet + (L * dry) * dryMul;
+        R = (spreadB * cL + spreadA * cR) * wet + (R * dry) * dryMul;
+    }
+
+    void modeStereo (float& L, float& R, float A, float B, bool pingPong) noexcept
+    {
+        lfoTick();
+        const auto mod = (double) modOffset();
+        coefficients();
+        const auto mL = mainL.read (mainL.idx, (float) (mod + gC[0])) * A + mainL.read (mainL.idx, (float) (mod + gC[1])) * B;
+        const auto mR = mainR.read (mainR.idx, (float) (mod + gC[0])) * A + mainR.read (mainR.idx, (float) (mod + gC[1])) * B;
+        float xL, xR;
+        if (! pingPong)
+        {
+            inL.push (L);
+            xL = inL.read (inL.idx, (float) gA[1]) * B + inL.read (inL.idx, (float) gA[0]) * A;
+            inR.push (R);
+            xR = inR.read (inR.idx, (float) gB[1]) * B + inR.read (inR.idx, (float) gB[0]) * A;
+        }
+        else
+        {
+            xL = R * panRL + L * panLL;
+            xR = R * panRR + L * panLR;
+        }
+        const auto yL = feedbackRun (fbL, mL * feedback);
+        auto s = saturate (redL, envL, filter (svfL, xL * send + yL));
+        float o1, o2;
+        allPass (ap[0], gnd[0], s, o1);
+        allPass (ap[1], gnd[1], s, o2);
+        (pingPong ? mainR : mainL).push (o1 * A + o2 * B);
+        const auto yR = feedbackRun (fbR, mR * feedback);
+        s = saturate (redR, envR, filter (svfR, xR * send + yR));
+        allPass (ap[2], gnd[0], s, o1);
+        allPass (ap[3], gnd[1], s, o2);
+        (pingPong ? mainL : mainR).push (o1 * A + o2 * B);
+        const auto cL = colourRun (colL, mL);
+        const auto cR = colourRun (colR, mR);
+        auto oL = spreadA * cL + spreadB * cR;
+        auto oR = spreadA * cR + spreadB * cL;
+        if (pingPong && satType == 1)
+        {
+            oL = limit (envL, attack, release, oL);
+            oR = limit (envR, attack, release, oR);
+        }
+        L = (L * dry) * dryMul + oL * wet;
+        R = (R * dry) * dryMul + oR * wet;
+    }
+
+    static float limit (float& env, float atk, float rel, float x) noexcept
+    {
+        const auto a = std::fabs (x);
+        env = a < env ? (a - env) * rel + env : (a - env) * atk + env;
+        return env > 1.0f ? x / env : x;
+    }
+
+    void modeOff (float& L, float& R) noexcept
+    {
+        lfoTick();
+        coefficients();
+        const auto sL = saturate (redL, envL, filter (svfL, L));
+        const auto sR = saturate (redR, envR, filter (svfR, R));
+        const auto cL = colourRun (colL, sL);
+        const auto cR = colourRun (colR, sR);
+        L = (spreadB * cR + spreadA * cL) * wet + dry * L;
+        R = (spreadB * cL + spreadA * cR) * wet + dry * R;
+    }
+
+    static void glide (double& cur, int target, double k) noexcept
+    {
+        const auto t = (double) target;
+        if (cur == t)
+            return;
+        const auto diff = t - cur;
+        cur = std::fabs (diff) < 0.001 ? t : diff * k + cur;
+    }
+
+    void sample (float& L, float& R) noexcept
+    {
+        if (! keepPitch)
+        {
+            weight[0] = 1.0f;
+            weight[1] = 0.0f;
+            fadeFrom = 0;
+            fadeTo = 1;
+            if (recompute)
+            {
+                times (0);
+                recompute = false;
+            }
+            glide (gnd[0], nd[0], smoothK);
+            glide (gA[0], dA[0], smoothK);
+            glide (gB[0], dB[0], smoothK);
+            glide (gC[0], dC[0], smoothK);
+        }
+        else if (! fading && recompute)
+        {
+            fadeCount = 0;
+            recompute = false;
+            fading = true;
+            times (fadeTo);
+            gnd[fadeTo] = nd[fadeTo];
+            gA[fadeTo] = dA[fadeTo];
+            gB[fadeTo] = dB[fadeTo];
+            gC[fadeTo] = dC[fadeTo];
+        }
+        const auto A = weight[0], B = weight[1];
+        if (mode == 0)
+            modeFake (L, R, A, B);
+        else if (mode == 1)
+            modeStereo (L, R, A, B, false);
+        else if (mode == 2)
+            modeStereo (L, R, A, B, true);
+        else if (mode == 3)
+            modeOff (L, R);
+        if (keepPitch && fading)
+        {
+            const auto x = (float) fadeCount * fadeStep;
+            weight[fadeFrom] = 1.0f - x;
+            weight[fadeTo] = x;
+            if (++fadeCount == fadeLen)
+            {
+                std::swap (fadeFrom, fadeTo);
+                fading = false;
+            }
+        }
+    }
+
+    // the plugin's parameter law (REA_rodada52 §3.2)
+    void set (int i, float f, double v) noexcept
+    {
+        switch (i)
+        {
+            case 0: send = f; break;
+            case 1:
+            {
+                const auto m = (int) (std::int64_t) (3.0 * (double) f + 0.5);
+                if (m != mode)
+                {
+                    mode = m;
+                    clear();
+                    recompute = true;
+                }
+                break;
+            }
+            case 2: recompute = true; sync = v >= 0.5; break;
+            case 3:
+                keepPitch = v >= 0.5;
+                if (! keepPitch)
+                    recompute = true;
+                break;
+            case 4: time = f; recompute = true; break;
+            case 5:
+            {
+                auto x = (f + f) - 1.0f;
+                if (x >= 0.0f)
+                {
+                    x = 1.0f - x;
+                    panLL = x;
+                    panLR = (1.0f - x) * 0.5f;
+                    panRR = 1.0f - panLR;
+                    panRL = 0.0f;
+                }
+                else
+                {
+                    panRR = x + 1.0f;
+                    panRL = (1.0f - panRR) * 0.5f;
+                    panLL = 1.0f - panRL;
+                    panLR = 0.0f;
+                }
+                offset = f;
+                recompute = true;
+                break;
+            }
+            case 6:
+                smoothT = (double) f;
+                smoothK = smoothT == 0.0 ? 1.0 : 1.0 - std::pow (0.01, 1.0 / (smoothT * sr));
+                break;
+            case 7:
+                spreadA = f * 0.5f + 0.5f;
+                spreadB = 1.0f - spreadA;
+                break;
+            case 8: setLfoRate (f * 0.99000001f); break;
+            case 9: modAmt = (float) (v * v) * 0.1f; break;
+            case 10: cutoffMod = f * 0.5f; break;
+            case 11:
+            {
+                const auto g = 0.0f > f ? 0.0f : (1.0f < f ? 1.0f : f);
+                for (auto& a : ap)
+                    a.g = g;
+                break;
+            }
+            case 12: diffSpread = f; recompute = true; break;
+            case 13: satType = (int) (std::int64_t) (v + 0.5); break;
+            case 14: feedback = f * 1.25f; break;
+            case 15: filterMode = (int) (std::int64_t) (3.0 * v + 0.5); break;
+            case 16: cutoff = f; break;
+            case 17: res = f; break;
+            case 18: setDistortion (f); break;
+            case 19: hardness = f; shaper (distDb, f, symmetry); break;
+            case 20: symmetry = f; shaper (distDb, hardness, f); break;
+            case 21:
+            {
+                const auto x = (float) (1.0 - v);
+                const auto r = x * x * x;
+                redL.amount = redR.amount = r;
+                break;
+            }
+            case 22:
+            {
+                auto x = (float) (1.0 - v);
+                x = x * x;
+                const auto q = sqrtF (sqrtF (x));
+                const auto scale = (float) std::pow (2.0, (double) ((1.0f - q) * 14.0f + 2.0f));
+                redL.bitsOn = redR.bitsOn = x;
+                redL.scale = redR.scale = scale;
+                break;
+            }
+            case 23: wet = f; break;
+            case 24: setColour (f); break;
+            case 25: dry = f; break;
+            default: break;
+        }
+    }
+};
+
+namespace
+{
+bool smoothed (int i) noexcept
+{
+    switch (i)
+    {
+        case 0: case 7: case 10: case 11: case 14: case 16: case 17: case 18: case 19: case 20: case 21: case 22:
+        case 23: case 24: case 25:
+            return true;
+        default:
+            return false;
+    }
+}
+
+// the engine's own defaults (applied when it is created)
+constexpr float engineDefaults[delay3Controls] { 1.0f, 0, 0, 0, 0.5f, 0.95f, 0, 1.0f, 0.5f, 0, 0, 0, 0.5f, 0.5f, 0.5f, 0,
+                                                 1.0f, 0, 0, 0, 0, 0, 0, 0.5f, 0.5f, 1.0f };
+} // namespace
+
+Delay3Engine::Delay3Engine (double sampleRate) : d (std::make_unique<Dsp>())
+{
+    smooth.reserve (delay3Controls);
+    for (int i = 0; i < delay3Controls; ++i)
+        applyNow (i, engineDefaults[i]);
+    d->clear();
+    setSampleRate (sampleRate);
+}
+
+Delay3Engine::~Delay3Engine() = default;
+
+void Delay3Engine::applyNow (int index, float value) noexcept
+{
+    applied[index] = value;
+    d->set (index, value, (double) value);
+}
+
+void Delay3Engine::setParameter (int index, float value) noexcept
+{
+    if (index >= 0 && index < delay3Controls)
+        hostSet (index, value);
+}
+
+void Delay3Engine::setSampleRate (double sampleRate) noexcept
+{
+    smoothCoef = (float) (1.0 - std::pow (0.01, 1.0 / (sampleRate * 0.005)));
+    d->prepare (sampleRate);
+}
+
+void Delay3Engine::hostSet (int index, float value) noexcept
+{
+    const auto v = (double) value;
+    const auto f = (float) (v < 0.0 ? 0.0 : (v > 1.0 ? 1.0 : v));
+    if (! smoothed (index))
+    {
+        applyNow (index, f);
+        return;
+    }
+    for (auto& e : smooth)
+        if (e.first == index)
+        {
+            e.second = f;
+            return;
+        }
+    smooth.emplace_back (index, f);
+}
+
+void Delay3Engine::settle() noexcept
+{
+    for (const auto& [i, v] : smooth)
+        applyNow (i, v);
+    smooth.clear();
+    if (d->tempo != hostTempo)
+    {
+        d->tempo = hostTempo;
+        d->recompute = true;
+    }
+    // reach the time targets and the modulation depth at once
+    d->times (0);
+    d->times (1);
+    d->recompute = false;
+    for (int k = 0; k < 2; ++k)
+    {
+        d->gnd[k] = d->nd[k];
+        d->gA[k] = d->dA[k];
+        d->gB[k] = d->dB[k];
+        d->gC[k] = d->dC[k];
+    }
+    d->modDepth = (d->modAmt * d->halfRate) * d->lfoNorm;
+}
+
+void Delay3Engine::process (float* left, float* right, int n) noexcept
+{
+    ScopedFlushDenormals ftz;
+    if (d->tempo != hostTempo)
+    {
+        d->tempo = hostTempo;
+        d->recompute = true;
+    }
+    for (int s = 0; s < n; ++s)
+    {
+        if (++smoothCounter == 8)
+        {
+            smoothCounter = 0;
+            for (std::size_t k = 0; k < smooth.size();)
+            {
+                const auto [i, target] = smooth[k];
+                auto x = applied[i];
+                x = x + (target - x) * smoothCoef;
+                if (std::fabs (x - target) < 1.0e-4f)
+                {
+                    applyNow (i, target);
+                    smooth.erase (smooth.begin() + (std::ptrdiff_t) k);
+                }
+                else
+                {
+                    applyNow (i, x);
+                    ++k;
+                }
+            }
+        }
+        auto l = left[s], r = right[s];
+        if (l > -1.0e-13f && l < 1.0e-13f)
+            l = 0.0f;
+        if (r > -1.0e-13f && r < 1.0e-13f)
+            r = 0.0f;
+        d->sample (l, r);
+        left[s] = l;
+        right[s] = r;
+    }
+}
+
+// =====================================================================================================================
+// The LYNX effects
+// =====================================================================================================================
+
+namespace
+{
+int rawOf (float p, int lo, int hi) noexcept
+{
+    return std::clamp ((int) std::lround ((double) p * (hi - lo) + lo), lo, hi);
+}
+
+class Delay2Effect final : public Effect
+{
+public:
+    void prepare (double sampleRate) noexcept override
+    {
+        rate = sampleRate;
+        engine.reset();
+    }
+    void reset() noexcept override { engine.reset(); }
+
+    void process (float* left, float* right, int n, const EffectParams& params, double bpm) noexcept override
+    {
+        Delay2State s;
+        for (int i = 0; i < delay2Controls; ++i)
+            s.v[(std::size_t) i] = rawOf (params[(std::size_t) i], delay2Min[(std::size_t) i], delay2Max[(std::size_t) i]);
+        bpm = bpm > 0.0 ? bpm : 120.0;
+        if (engine == nullptr)
+            engine = std::make_unique<Delay2Engine> (s, rate, bpm, block, true);
+        else if (s.v != current.v || bpm != tempo)
+            engine->set (s, bpm);
+        current = s;
+        tempo = bpm;
+        for (int done = 0; done < n;)
+        {
+            const auto len = std::min (block, n - done);
+            engine->process (left + done, right + done, len);
+            done += len;
+        }
+    }
+
+private:
+    static constexpr int block = 512;
+    double rate = 44100.0, tempo = 0.0;
+    Delay2State current;
+    std::unique_ptr<Delay2Engine> engine;
+};
+
+class Delay3Effect final : public Effect
+{
+public:
+    // the engine (its lines: 4 × 4 MB at 44.1 kHz, as FL allocates them) is built here, off the audio thread
+    void prepare (double sampleRate) noexcept override
+    {
+        rate = sampleRate;
+        engine = std::make_unique<Delay3Engine> (rate);
+        fresh = true;
+    }
+    void reset() noexcept override { prepare (rate); }
+
+    void process (float* left, float* right, int n, const EffectParams& params, double bpm) noexcept override
+    {
+        if (engine == nullptr)
+            prepare (rate);
+        engine->setTempo (bpm > 0.0 ? bpm : 120.0);
+        for (int i = 0; i < delay3Controls; ++i)
+        {
+            const auto raw = rawOf (params[(std::size_t) i], delay3Min[(std::size_t) i], delay3Max[(std::size_t) i]);
+            if (fresh || raw != current[(std::size_t) i])
+            {
+                current[(std::size_t) i] = raw;
+                engine->setParameter (i, delay3EngineValue (i, raw));
+            }
+        }
+        if (fresh)
+            engine->settle();
+        fresh = false;
+        engine->process (left, right, n);
+    }
+
+private:
+    double rate = 44100.0;
+    bool fresh = true;
+    std::array<int, delay3Controls> current {};
+    std::unique_ptr<Delay3Engine> engine;
+};
+
+float normalised (int raw, int lo, int hi) noexcept { return (float) (raw - lo) / (float) (hi - lo); }
+} // namespace
+
+std::unique_ptr<Effect> makeDelay2() { return std::make_unique<Delay2Effect>(); }
+std::unique_ptr<Effect> makeDelay3() { return std::make_unique<Delay3Effect>(); }
+
+void delay2ToParams (const Delay2State& s, float* params) noexcept
+{
+    for (int i = 0; i < delay2Controls; ++i)
+        params[i] = normalised (s.v[(std::size_t) i], delay2Min[(std::size_t) i], delay2Max[(std::size_t) i]);
+}
+
+void delay3ToParams (const Delay3State& s, float* params) noexcept
+{
+    for (int i = 0; i < delay3Controls; ++i)
+        params[i] = normalised (std::clamp (s.v[(std::size_t) i], delay3Min[(std::size_t) i], delay3Max[(std::size_t) i]),
+                                delay3Min[(std::size_t) i], delay3Max[(std::size_t) i]);
+}
+
+std::string delay2ParamText (int i, float v)
+{
+    const auto raw = rawOf (v, delay2Min[(std::size_t) std::clamp (i, 0, 7)], delay2Max[(std::size_t) std::clamp (i, 0, 7)]);
+    char t[48];
+    switch (i)
+    {
+        case 0: std::snprintf (t, sizeof (t), "%d%%", (int) std::lround (raw / 1.28)); break;
+        case 1: case 2: std::snprintf (t, sizeof (t), "%d%%", (int) std::lround (raw / 1.6 * 1.25)); break;
+        case 3: std::snprintf (t, sizeof (t), "%d%%", (int) std::lround (raw / 1.27)); break;
+        case 4: std::snprintf (t, sizeof (t), "%d:%02d", raw / 48, raw % 48); break;
+        case 5: std::snprintf (t, sizeof (t), "%.1f ms", 0.5 * (std::pow (1001.0, std::abs (raw) / 512.0) - 1.0) * (raw < 0 ? -1.0 : 1.0)); break;
+        case 6: return raw == 0 ? "Normal" : (raw == 1 ? "Invert" : "Ping pong");
+        case 7: std::snprintf (t, sizeof (t), "%d%%", (int) std::lround (raw / 1.28)); break;
+        default: return {};
+    }
+    return t;
+}
+
+std::string delay3ParamText (int i, float v, double bpm)
+{
+    if (i < 0 || i >= delay3Controls)
+        return {};
+    const auto raw = rawOf (v, delay3Min[(std::size_t) i], delay3Max[(std::size_t) i]);
+    const auto u = (double) delay3EngineValue (i, raw);
+    char t[48];
+    switch (i)
+    {
+        case 1: return raw == 0 ? "Fake stereo" : (raw == 1 ? "True stereo" : (raw == 2 ? "Ping pong" : "Off"));
+        case 2: case 3: return raw != 0 ? "On" : "Off";
+        case 4:
+        {
+            const auto x = u * 0.94 + 0.06;
+            const auto ms = ((x * x * x - 0.000216) * 1.0002160466660799 * 0.999 + 0.001) * 1000.0;
+            const auto n = (int) (767.0 * u + 0.5) + 1;
+            std::snprintf (t, sizeof (t), "%d:%02d (%.0f ms unsynced)", n / 48, n % 48, ms);
+            (void) bpm;
+            break;
+        }
+        case 13: return raw != 0 ? "Saturate" : "Limit";
+        case 15: return raw == 0 ? "Low pass" : (raw == 1 ? "High pass" : (raw == 2 ? "Band pass" : "Off"));
+        case 24: std::snprintf (t, sizeof (t), "%.0f%%", u * 200.0 - 100.0); break;
+        default: std::snprintf (t, sizeof (t), "%.0f%%", u * 100.0); break;
+    }
+    return t;
+}
+} // namespace lynx::fldelay

+ 110 - 0
src/core/FruityDelay.h

@@ -0,0 +1,110 @@
+#pragma once
+
+// FL Studio's Fruity Delay 2 and Fruity Delay 3 as exact LYNX mixer effects (docs/analise/REA_rodada52.md; clean-room:
+// rebuilt from the observed behaviour of the plugins, no Image-Line code). Both effects keep FL's raw controls as
+// their parameters (value over the control's range, like the FL import reads them from the saved state), so the
+// LYNX editor can still change them.
+//
+// Delay 2: tempo-synced stereo delay (time in 1/192 of a beat), input pan/volume, dry level, feedback with a
+// one-pole low-pass in the loop, normal / swapped / ping-pong routing and a stereo time offset.
+// Delay 3: the third-party "Delay VST" engine FL hosts (send, delay model, time with or without tempo sync, time
+// smoothing or pitch-keeping crossfades, modulation LFO, diffusion all-passes, feedback filter, distortion,
+// sample-rate and bit reduction, output colour, stereo spread, wet and dry).
+
+#include <array>
+#include <cstdint>
+#include <memory>
+#include <optional>
+#include <vector>
+
+#include "core/Effects.h"
+
+namespace lynx::fldelay
+{
+// --- Fruity Delay 2 ---------------------------------------------------------------------------------------------------
+constexpr int delay2Controls = 8;
+extern const std::array<int, delay2Controls> delay2Min, delay2Max, delay2Default;
+const char* delay2ParamName (int i) noexcept;
+
+struct Delay2State
+{
+    std::array<int, delay2Controls> v {}; // input pan, input volume, dry, feedback, time, stereo offset, mode, cutoff
+};
+std::optional<Delay2State> parseDelay2 (const std::vector<std::uint8_t>& state);
+
+class Delay2Engine
+{
+public:
+    // maxBlock: the longest block process() will be given (it sizes the delay line like FL's host block).
+    // A new instance fades its input in (FL's gain ramps start at 0); `settled` starts at the targets instead.
+    Delay2Engine (const Delay2State& s, double sampleRate, double bpm, int maxBlock = 512, bool settled = false);
+    // New controls / tempo: gains, feedback, cutoff and mode change in place (ramped like FL); a new delay length
+    // or stereo offset rebuilds the line (FL resizes it; its content after a resize is not confirmed: cleared here)
+    void set (const Delay2State& s, double bpm);
+    void process (float* left, float* right, int n) noexcept; // in place, n <= maxBlock
+
+private:
+    double rate = 44100.0;
+    int block = 512, delaySamples = 0, offsetSamples = 0, offsetSign = 0;
+    std::vector<float> line; // interleaved L/R
+    int frames = 0, readPos = 0, writePos = 0, offL = 0, offR = 0;
+    int mode = 0;
+    float dry = 1.0f, fbTarget = 0.0f, fbCur = 0.0f, coef = 1.0f, step = 0.001f;
+    float gTarget[4] {}, gCur[4] {};
+    double stL = 0.0, stR = 0.0;
+    std::vector<float> tmp;
+};
+
+// --- Fruity Delay 3 ---------------------------------------------------------------------------------------------------
+constexpr int delay3Controls = 26;
+extern const std::array<int, delay3Controls> delay3Min, delay3Max, delay3Default;
+const char* delay3ParamName (int i) noexcept;
+
+struct Delay3State
+{
+    std::array<int, delay3Controls> v {};
+};
+std::optional<Delay3State> parseDelay3 (const std::vector<std::uint8_t>& state);
+// The value FL's wrapper hands the engine for a raw control (0…1; controls 2, 3 and 13 go through raw)
+float delay3EngineValue (int control, int raw) noexcept;
+
+class Delay3Engine
+{
+public:
+    explicit Delay3Engine (double sampleRate);
+    ~Delay3Engine();
+    Delay3Engine (const Delay3Engine&) = delete;
+    Delay3Engine& operator= (const Delay3Engine&) = delete;
+
+    // Host tempo (read at the start of each block, like the plugin's time info)
+    void setTempo (double bpm) noexcept { hostTempo = bpm; }
+    // A parameter change from the host (0…1): the plugin's smoothed controls glide toward it, the others apply now
+    void setParameter (int index, float value) noexcept;
+    // The host's sample-rate set-up (clears the lines; the delay times jump to their current targets)
+    void setSampleRate (double sampleRate) noexcept;
+    // LYNX start-up: lets every glide (parameter smoothing, time smoothing, modulation depth) reach its target, as
+    // after FL has been running for a while
+    void settle() noexcept;
+    void process (float* left, float* right, int n) noexcept; // in place
+
+    struct Dsp;
+
+private:
+    std::unique_ptr<Dsp> d;
+    double hostTempo = 120.0;
+    std::vector<std::pair<int, float>> smooth; // smoothed parameters: (index, target)
+    float applied[delay3Controls] {};
+    float smoothCoef = 1.0e-5f;
+    int smoothCounter = 0;
+    void applyNow (int index, float value) noexcept;
+    void hostSet (int index, float value) noexcept;
+};
+
+// The LYNX effects (parameters = FL's raw controls over their ranges)
+std::unique_ptr<Effect> makeDelay2();
+std::unique_ptr<Effect> makeDelay3();
+void delay2ToParams (const Delay2State& s, float* params) noexcept;
+void delay3ToParams (const Delay3State& s, float* params) noexcept;
+std::string delay2ParamText (int i, float v);
+std::string delay3ParamText (int i, float v, double bpm);
+} // namespace lynx::fldelay

+ 3 - 1
src/core/Song.h

@@ -300,7 +300,9 @@ enum class EffectKind : std::uint8_t
     fruityWaveShaper, // FL's Fruity WaveShaper, exact (REA_rodada51, core/FruityShapers.h): curve in EffectSlot::state, controls / range
     fruitySoftClipper, // FL's Fruity Soft Clipper, exact (REA_rodada51, core/FruityShapers.h): threshold, post / range
     reeverb2,     // FL's Fruity Reeverb 2, exact (REA_rodada49, core/Reeverb2.h): FL's 15 controls + 2 options, (raw − min) / range
-    reeverb1      // FL's Fruity Reeverb (first version), exact (REA_rodada49 §6, core/Reeverb2.h): FL's 10 controls, raw / max
+    reeverb1,     // FL's Fruity Reeverb (first version), exact (REA_rodada49 §6, core/Reeverb2.h): FL's 10 controls, raw / max
+    fruityDelay2, // FL's Fruity Delay 2, exact (REA_rodada52, core/FruityDelay.h): FL's 8 raw controls / range
+    fruityDelay3  // FL's Fruity Delay 3, exact (REA_rodada52, core/FruityDelay.h): FL's 26 raw controls / range
 };
 
 constexpr int maxEffectParams = 48; // the 7-band parametric EQ and the Pitcher use most of them

+ 3 - 1
src/engine/ProjectFile.cpp

@@ -151,6 +151,8 @@ const char* effectId (EffectKind k)
         case EffectKind::fruitySoftClipper: return "fruitySoftClipper";
         case EffectKind::reeverb2: return "reeverb2";
         case EffectKind::reeverb1: return "reeverb1";
+        case EffectKind::fruityDelay2: return "fruityDelay2";
+        case EffectKind::fruityDelay3: return "fruityDelay3";
     }
     return "eq";
 }
@@ -292,7 +294,7 @@ std::optional<EffectSlot> effectFromVar (const juce::var& e)
 std::optional<EffectKind> effectFromId (const juce::String& id)
 {
     for (auto k : { EffectKind::eq, EffectKind::compressor, EffectKind::delay, EffectKind::reverb, EffectKind::plugin,
-                    EffectKind::limiter, EffectKind::filter, EffectKind::distortion, EffectKind::chorus, EffectKind::parametricEq, EffectKind::utility, EffectKind::volumeGate, EffectKind::peakController, EffectKind::pitchShift, EffectKind::freqShift, EffectKind::parallel, EffectKind::lofi, EffectKind::effector, EffectKind::crossover, EffectKind::rhythmGain, EffectKind::autoPan, EffectKind::vocoder, EffectKind::pitchCorrect, EffectKind::squeeze, EffectKind::vintagePhaser, EffectKind::vocodex, EffectKind::maximus, EffectKind::fruityLimiter, EffectKind::fruityCompressor, EffectKind::fruityWaveShaper, EffectKind::fruitySoftClipper, EffectKind::reeverb2, EffectKind::reeverb1 })
+                    EffectKind::limiter, EffectKind::filter, EffectKind::distortion, EffectKind::chorus, EffectKind::parametricEq, EffectKind::utility, EffectKind::volumeGate, EffectKind::peakController, EffectKind::pitchShift, EffectKind::freqShift, EffectKind::parallel, EffectKind::lofi, EffectKind::effector, EffectKind::crossover, EffectKind::rhythmGain, EffectKind::autoPan, EffectKind::vocoder, EffectKind::pitchCorrect, EffectKind::squeeze, EffectKind::vintagePhaser, EffectKind::vocodex, EffectKind::maximus, EffectKind::fruityLimiter, EffectKind::fruityCompressor, EffectKind::fruityWaveShaper, EffectKind::fruitySoftClipper, EffectKind::reeverb2, EffectKind::reeverb1, EffectKind::fruityDelay2, EffectKind::fruityDelay3 })
         if (id == effectId (k))
             return k;
 

+ 2 - 1
src/ui/MixerComponent.cpp

@@ -1003,7 +1003,8 @@ const EffectKind allEffects[] = { EffectKind::eq,     EffectKind::parametricEq,
                                       EffectKind::pitchShift, EffectKind::freqShift, EffectKind::lofi, EffectKind::effector, EffectKind::crossover, EffectKind::autoPan, EffectKind::vocoder, EffectKind::pitchCorrect,
                                       EffectKind::fruityLimiter, EffectKind::fruityCompressor,
                                       EffectKind::fruityWaveShaper, EffectKind::fruitySoftClipper,
-                                      EffectKind::reeverb2, EffectKind::reeverb1 };
+                                      EffectKind::reeverb2, EffectKind::reeverb1,
+                                      EffectKind::fruityDelay2, EffectKind::fruityDelay3 };
 } // namespace
 
 const std::vector<EffectKind>& addableEffects()

+ 115 - 0
tests/tests.cpp

@@ -46,6 +46,7 @@
 #include "core/Denormals.h"
 #include "core/FruityDynamics.h"
 #include "core/FruityShapers.h"
+#include "core/FruityDelay.h"
 #include "core/LiveEventQueue.h"
 #include "core/RackRenderer.h"
 #include "core/Scheduler.h"
@@ -790,6 +791,7 @@ TEST (flp_real_files)
     int harmlessCompWanted = 0, harmlessCompLoaded = 0; // Harmless rack compressors / presets read from the installation
     int maximusSlots = 0, maximusExact = 0, sgzSlots = 0, sgzExact = 0, vocodexSlots = 0, vocodexWithData = 0; // REA_rodada40
     int shaperSlots = 0, shaperExact = 0, clipperSlots = 0, clipperExact = 0; // REA_rodada51
+    int delay2Slots = 0, delay2Exact = 0, delay3Slots = 0, delay3Exact = 0; // REA_rodada52
     // import with the installation's samples (realFlpDir is ...\Data): for DirectWave/FPC
     lynx::FlpImportOptions withFiles;
     const auto flRoot = std::filesystem::path (realFlpDir).parent_path().string();
@@ -1031,6 +1033,8 @@ TEST (flp_real_files)
                     for (const auto& slot : insert.slots)
                     {
                         maximusSlots += slot.plugin == "Maximus";
+                        delay2Slots += slot.plugin == "Fruity Delay 2";
+                        delay3Slots += slot.plugin == "Fruity Delay 3";
                         sgzSlots += slot.plugin == "Soundgoodizer";
                         vocodexSlots += slot.plugin == "Vocodex";
                         shaperSlots += slot.plugin == "Fruity WaveShaper";
@@ -1051,6 +1055,8 @@ TEST (flp_real_files)
                         if (fx.kind == lynx::EffectKind::fruityWaveShaper)
                             shaperExact += lynx::flshape::parseWaveShaper (fx.state).has_value() ? 1 : 0;
                         clipperExact += fx.kind == lynx::EffectKind::fruitySoftClipper;
+                        delay2Exact += fx.kind == lynx::EffectKind::fruityDelay2;
+                        delay3Exact += fx.kind == lynx::EffectKind::fruityDelay3;
                     }
                 for (const auto& pat : full.patterns)
                     for (const auto& n : pat.notes)
@@ -1710,6 +1716,9 @@ TEST (flp_real_files)
                  clipperExact, clipperSlots);
     // (Patcher graphs add WaveShaper nodes of their own to the imported mixer)
     CHECK (shaperExact >= shaperSlots && shaperSlots >= 70 && clipperExact >= clipperSlots && clipperSlots >= 25); // REA_rodada51
+    std::printf ("  Fruity Delay 2: %d of %d slots on the exact engine; Fruity Delay 3: %d of %d\n", delay2Exact, delay2Slots,
+                 delay3Exact, delay3Slots);
+    CHECK (delay2Exact == delay2Slots && delay2Slots >= 60 && delay3Exact == delay3Slots && delay3Slots >= 100); // REA_rodada52
 
     // 3x Osc channel presets shipped with FL (.fst): all become synth settings
     int presets = 0, presetsDecoded = 0;
@@ -9297,3 +9306,109 @@ TEST (bassdrum_engine)
 }
 // Workflow P2 (docs/WORKFLOW_FL.md)
 #include "WorkflowP2Tests.inc"
+
+TEST (fruity_delay_engines)
+{
+    // REA_rodada52: the engines on their own against the installation's DLLs (goldens = the DLL's output for the same
+    // input with FL's set-up order, EXEC: bit-identical), then the mixer effects built from FL states
+    const int n = 16384;
+    std::vector<float> inL ((std::size_t) n, 0.0f), inR ((std::size_t) n, 0.0f);
+    std::uint32_t seed = 1;
+    for (int i = 0; i < 4096; ++i) // a noise burst, then the echoes
+    {
+        seed = seed * 1664525u + 1013904223u;
+        inL[(std::size_t) i] = (float) ((int) (seed >> 16) - 32768) / 32768.0f * 0.5f;
+        seed = seed * 1664525u + 1013904223u;
+        inR[(std::size_t) i] = (float) ((int) (seed >> 16) - 32768) / 32768.0f * 0.5f;
+    }
+    using Golden = std::vector<std::tuple<int, float, float>>;
+    auto check = [&] (const std::vector<float>& l, const std::vector<float>& r, const Golden& golden) {
+        for (const auto& [i, gl, gr] : golden)
+            CHECK (std::abs (l[(std::size_t) i] - gl) < 2e-6f && std::abs (r[(std::size_t) i] - gr) < 2e-6f);
+    };
+    auto run3 = [&] (const std::array<int, 26>& raw, double bpm) {
+        lynx::fldelay::Delay3Engine e (44100.0);
+        e.setTempo (bpm);
+        for (int i = 0; i < 26; ++i)
+            e.setParameter (i, lynx::fldelay::delay3EngineValue (i, raw[(std::size_t) i]));
+        e.setSampleRate (44100.0); // FL's wrapper sets the rate up again after the state
+        e.setSampleRate (44100.0);
+        std::vector<float> l (inL), r (inR);
+        for (int s = 0; s < n; s += 512)
+            e.process (l.data() + s, r.data() + s, 512);
+        return std::make_pair (l, r);
+    };
+    auto run2 = [&] (const std::array<int, 8>& raw, double bpm) {
+        lynx::fldelay::Delay2State st;
+        st.v = raw;
+        lynx::fldelay::Delay2Engine e (st, 44100.0, bpm, 512);
+        std::vector<float> l (inL), r (inR);
+        for (int s = 0; s < n; s += 512)
+            e.process (l.data() + s, r.data() + s, 512);
+        return std::make_pair (l, r);
+    };
+    // Delay 3, true stereo, synced 1/8 beat, cutoff + resonance (Fruity Delay 3_x64.dll at 120 and 100 BPM)
+    const std::array<int, 26> a { 6000, 1, 1, 0, 24, 4000, 500, 5000, 3000, 0, 0, 0, 0, 1, 4200, 0, 4500, 1500, 0, 0, 0, 60000, 6000, 6000, 0, 6000 };
+    auto o = run3 (a, 120.0);
+    check (o.first, o.second, { { 3000, 0.399949551f, 0.598533869f }, { 6000, 0.116703831f, -0.315510482f }, { 9000, -0.150520369f, -0.250620633f },
+                                { 13000, 0.193608373f, 0.0598564595f }, { 16000, -0.0524701327f, 0.022601109f } });
+    o = run3 (a, 100.0);
+    check (o.first, o.second, { { 5000, 0.377422422f, 0.346570343f }, { 6000, -0.182619616f, 0.0488029197f }, { 11000, -0.00120426295f, 0.0253051519f },
+                                { 16000, 0.0806550607f, -0.0991330743f } });
+    // ping pong, keep pitch, modulation, cutoff LFO, diffusion, saturation, rate and bit reduction, colour
+    o = run3 ({ 5000, 2, 1, 1, 36, 2100, 500, 6000, 4500, 3000, 2000, 3500, 4000, 1, 3800, 2, 3500, 2500, 2500, 1200, 3000, 40000, 4000, 5500, -1200, 4000 }, 120.0);
+    check (o.first, o.second, { { 1500, 0.288540125f, -0.148862943f }, { 5000, 5.90502168e-06f, 0.111382999f }, { 8000, -0.0736631379f, -0.0305093247f },
+                                { 11000, -0.00831047911f, 0.0102323527f }, { 16000, 0.0175791476f, 0.0273917634f } });
+    // fake stereo, unsynced, high-pass, limit distortion, no dry
+    o = run3 ({ 6000, 0, 0, 0, 200, 3700, 0, 3000, 1500, 0, 0, 1500, 2000, 0, 3000, 1, 3000, 0, 3000, 0, 0, 60000, 6000, 6000, 1500, 0 }, 120.0);
+    check (o.first, o.second, { { 1500, 0.0825810209f, 0.0228505582f }, { 6000, -0.0427959524f, -0.0408911295f }, { 9000, 0.0114790015f, 0.019227922f },
+                                { 16000, -0.000312746735f, 0.00101647642f } });
+    // delay type "Off": filter, distortion and the bit/rate reduction on the dry path
+    o = run3 ({ 6000, 3, 1, 0, 24, 3000, 500, 6000, 3000, 0, 0, 0, 0, 1, 3000, 2, 2500, 4000, 4000, 3000, 1000, 30000, 2000, 6000, 800, 3000 }, 120.0);
+    check (o.first, o.second, { { 1500, 0.238686681f, -0.106820084f }, { 3000, 0.131528616f, 0.0665975735f }, { 5000, 9.94473215e-09f, -8.22819057e-09f },
+                                { 11000, 0.0f, 0.0f } });
+    // Delay 2: default, ping pong with a stereo offset, swapped without dry (Fruity Delay 2_x64.dll)
+    o = run2 ({ 0, 128, 128, 64, 36, 0, 0, 128 }, 120.0);
+    check (o.first, o.second, { { 3000, 0.211380005f, 0.277908325f }, { 5000, -0.223615795f, -0.0189359933f }, { 9000, 0.120054141f, -0.00297877868f },
+                                { 16000, 0.0182533264f, 0.105384827f } });
+    o = run2 ({ -40, 110, 90, 90, 24, -300, 2, 90 }, 100.0);
+    check (o.first, o.second, { { 3000, 0.0929639712f, 0.122222826f }, { 5000, -0.0884733275f, -0.0507739782f }, { 11000, 0.0589251742f, 0.0f },
+                                { 16000, -0.029524127f, 0.0128910914f } });
+    o = run2 ({ 60, 140, 0, 100, 30, 250, 1, 110 }, 120.0);
+    check (o.first, o.second, { { 1500, 0.0f, 0.0f }, { 5000, 0.176379532f, -0.212506086f }, { 8000, -0.324207425f, 0.0675852001f },
+                                { 13000, 0.145023212f, -0.104788139f } });
+
+    // the mixer effects from FL states: time law (Delay 3 synced 192 = 1 beat; Delay 2 144 = 3/4 beat), settled start
+    auto state3 = std::vector<std::uint8_t> (4 + 26 * 4, 0);
+    const std::array<int, 26> def3 { 6000, 1, 1, 0, 192, 3000, 500, 6000, 3000, 0, 0, 0, 0, 1, 0, 0, 6000, 0, 0, 0, 0, 60000, 6000, 6000, 0, 6000 };
+    state3[0] = 1;
+    std::memcpy (state3.data() + 4, def3.data(), 26 * 4);
+    const auto slot3 = lynx::effectFromFl ("Fruity Delay 3", state3, 120.0);
+    CHECK (slot3 && slot3->kind == lynx::EffectKind::fruityDelay3);
+    auto state2 = std::vector<std::uint8_t> (32, 0);
+    const std::array<int, 8> def2 { 0, 128, 128, 0, 144, 0, 0, 128 };
+    std::memcpy (state2.data(), def2.data(), 32);
+    const auto slot2 = lynx::effectFromFl ("Fruity delay 2", state2, 120.0);
+    CHECK (slot2 && slot2->kind == lynx::EffectKind::fruityDelay2);
+    CHECK (lynx::formatEffectParam (lynx::EffectKind::fruityDelay2, 4, slot2->params[4], 120.0) == "3:00");
+    auto echoAt = [] (const lynx::EffectSlot& slot, double bpm) {
+        auto fx = lynx::makeEffect (slot);
+        fx->prepare (44100.0);
+        std::vector<float> l (48000, 0.0f), r (48000, 0.0f);
+        l[100] = 1.0f;
+        for (int s = 0; s < 48000; s += 1024)
+            fx->process (l.data() + s, r.data() + s, std::min (1024, 48000 - s), slot.params, bpm);
+        int best = 200;
+        for (int i = 200; i < 48000; ++i)
+            if (std::abs (l[(std::size_t) i]) > std::abs (l[(std::size_t) best]))
+                best = i;
+        return best - 100;
+    };
+    if (slot3 && slot2)
+    {
+        CHECK (echoAt (*slot3, 120.0) == 22050);
+        CHECK (echoAt (*slot3, 150.0) == 17640);
+        CHECK (echoAt (*slot2, 120.0) == 16538);
+        CHECK (echoAt (*slot2, 140.0) == 14175);
+    }
+}

+ 82 - 0
tools/fdelayrender.cpp

@@ -0,0 +1,82 @@
+// Renders FL's Fruity Delay 2 / Fruity Delay 3 engines (core/FruityDelay) on a raw stereo float file, for comparing
+// with the plugins (REA_rodada52). The Delay 3 set-up follows FL's wrapper: state, then the sample rate twice.
+// usage: fdelayrender d2|d3 <state.bin> <in.f32> <out.f32> <sampleRate> <bpm> <block> [settle]
+#include "core/FruityDelay.h"
+
+#include <algorithm>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <vector>
+
+using namespace lynx::fldelay;
+
+static std::vector<std::uint8_t> readAll (const char* path)
+{
+    std::vector<std::uint8_t> v;
+    if (auto* f = std::fopen (path, "rb"))
+    {
+        std::uint8_t b[65536];
+        std::size_t n;
+        while ((n = std::fread (b, 1, sizeof b, f)) > 0)
+            v.insert (v.end(), b, b + n);
+        std::fclose (f);
+    }
+    return v;
+}
+
+int main (int argc, char** argv)
+{
+    if (argc < 8)
+    {
+        std::fprintf (stderr, "usage: fdelayrender d2|d3 state.bin in.f32 out.f32 sampleRate bpm block [settle]\n");
+        return 2;
+    }
+    const auto state = readAll (argv[2]);
+    const auto in = readAll (argv[3]);
+    const double rate = std::atof (argv[5]), bpm = std::atof (argv[6]);
+    const int block = std::max (1, std::atoi (argv[7]));
+    const bool settle = argc > 8 && std::strcmp (argv[8], "settle") == 0;
+    const std::size_t n = in.size() / 8;
+    std::vector<float> l (n), r (n);
+    for (std::size_t i = 0; i < n; ++i)
+    {
+        std::memcpy (&l[i], &in[8 * i], 4);
+        std::memcpy (&r[i], &in[8 * i + 4], 4);
+    }
+    if (std::strcmp (argv[1], "d3") == 0)
+    {
+        const auto s = parseDelay3 (state);
+        if (! s)
+            return 3;
+        Delay3Engine e (rate);
+        e.setTempo (bpm);
+        for (int i = 0; i < delay3Controls; ++i)
+            e.setParameter (i, delay3EngineValue (i, s->v[(std::size_t) i]));
+        e.setSampleRate (rate);
+        e.setSampleRate (rate);
+        if (settle)
+            e.settle();
+        for (std::size_t s0 = 0; s0 < n; s0 += (std::size_t) block)
+            e.process (&l[s0], &r[s0], (int) std::min ((std::size_t) block, n - s0));
+    }
+    else
+    {
+        const auto s = parseDelay2 (state);
+        if (! s)
+            return 3;
+        Delay2Engine e (*s, rate, bpm, block, settle);
+        for (std::size_t s0 = 0; s0 < n; s0 += (std::size_t) block)
+            e.process (&l[s0], &r[s0], (int) std::min ((std::size_t) block, n - s0));
+    }
+    if (auto* f = std::fopen (argv[4], "wb"))
+    {
+        for (std::size_t i = 0; i < n; ++i)
+        {
+            std::fwrite (&l[i], 4, 1, f);
+            std::fwrite (&r[i], 4, 1, f);
+        }
+        std::fclose (f);
+    }
+    return 0;
+}