Ver código fonte

Fruity Delay 2/3: wire the exact engines into the FL import, mixer, project files, tests and docs (REA round 52)

Ka1-S 1 mês atrás
pai
commit
a8edc93ade

+ 1 - 0
CMakeLists.txt

@@ -47,6 +47,7 @@ add_library(lynx_core STATIC
     src/core/VintagePhaser.cpp
     src/core/Vocodex.cpp
     src/core/MaximusFx.cpp
+    src/core/FruityDelay.cpp
     src/core/FlPatcher.cpp
     src/core/Inflate.cpp
     src/core/WavPack.cpp)

+ 8 - 0
docs/STATUS.md

@@ -275,6 +275,14 @@ accordingly. Highlights of what is **confirmed and applied**:
   Soundgoodizer runs the older engine copy of its own DLL with the preset `a…d.dat` read from the user's installation
   at import and Amount as the band mix. Within −139 dB of Maximus_x64.dll on 96 of the 100 demo states (53
   bit-identical) and within −126 dB of Soundgoodizer_x64.dll on every preset/amount; latency reported to PDC.
+- **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/Vocodex.cpp src/core/MaximusFx.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/MiniSynth.cpp src/core/Dx10.cpp src/core/Kepler.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/Vocodex.cpp src/core/MaximusFx.cpp src/core/FruityDelay.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/MiniSynth.cpp src/core/Dx10.cpp src/core/Kepler.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)
@@ -49,5 +49,6 @@ $CXX $FLAGS $CORE $WAVPACK tools/ogunrender.cpp -o build-local/ogunrender 2> >(g
 $CXX $FLAGS src/core/MiniSynth.cpp tools/minisynthrender.cpp -o build-local/minisynthrender 2> >(grep -v 'glibc version' >&2)
 $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/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/Vocodex.cpp src/core/MaximusFx.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/MiniSynth.cpp src/core/Dx10.cpp src/core/Kepler.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/Vocodex.cpp src/core/MaximusFx.cpp src/core/FruityDelay.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/MiniSynth.cpp src/core/Dx10.cpp src/core/Kepler.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

@@ -5,6 +5,7 @@
 #include "core/VintagePhaser.h"
 #include "core/Vocodex.h"
 #include "core/MaximusFx.h"
+#include "core/FruityDelay.h"
 
 #include "core/Biquad.h"
 
@@ -2133,6 +2134,21 @@ const EffectInfo& effectInfo (EffectKind kind)
                                                        { "Carrier", 0.0f }, { "Wet", 0.8f }, { "Side inputs", 0.0f } } };
     static const EffectInfo vocodexInfo { "Vocodex", {} }; // everything comes from FL's raw state (EffectSlot::state)
     static const EffectInfo maximusInfo { "Maximus", {} }; // the engine's state travels in EffectSlot::state (core/MaximusFx.h)
+    // 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 },
@@ -2228,6 +2244,8 @@ const EffectInfo& effectInfo (EffectKind kind)
         case EffectKind::vintagePhaser: return vintagePhaserInfo;
         case EffectKind::vocodex: return vocodexInfo;
         case EffectKind::maximus: return maximusInfo;
+        case EffectKind::fruityDelay2: return fruityDelay2Info;
+        case EffectKind::fruityDelay3: return fruityDelay3Info;
     }
     return eq;
 }
@@ -2494,6 +2512,12 @@ std::string formatEffectParam (EffectKind kind, int param, float v, double bpm)
                 std::snprintf (text, sizeof (text), "%d dB/oct", xover::dbPerOctave[xover::combo (v)]);
             return text;
 
+        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:
@@ -2561,6 +2585,8 @@ std::unique_ptr<Effect> makeEffect (EffectKind kind)
         case EffectKind::vintagePhaser: return makeVintagePhaser();
         case EffectKind::vocodex: return vocodex::make ({}); // without a state: passes the signal; use makeEffect (slot)
         case EffectKind::maximus: return maximusfx::make ({}); // without a state: passes the signal; use makeEffect (slot)
+        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)
     }

+ 34 - 0
src/core/FlEffects.cpp

@@ -2,6 +2,7 @@
 #include "core/VintagePhaser.h"
 #include "core/Vocodex.h"
 #include "core/MaximusFx.h"
+#include "core/FruityDelay.h"
 #include "core/SytrusEngine.h"
 #include "core/FlSynths.h"
 
@@ -924,8 +925,33 @@ std::optional<EffectSlot> effectFromFl (const std::string& pluginName, const std
     return effectFromFl (pluginName, state, bpm);
 }
 
+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 (pluginName == "Maximus") // FL's own engine from the saved state (REA_rodada36/38); the approximation otherwise
         if (auto exact = maximusExact (state))
             return exact;
@@ -1088,6 +1114,8 @@ std::vector<std::string> flPluginsForEffect (EffectKind kind)
         case EffectKind::compressor: return { "Fruity Limiter", "Fruity Compressor" };
         case EffectKind::reverb: 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 {};
     }
@@ -1096,6 +1124,12 @@ std::optional<FlParamMap> effectParamFromFl (const std::string& pluginName, int
 {
     auto is = [&] (const char* n) { return pluginName == n; };
 
+    // the exact Fruity Delay 2 / 3 take FL's controls as they are (value over the control's range)
+    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"))
     {
         if (k >= 0 && k < 7) // band gain: ±18 dB

+ 3 - 0
src/core/FlpImport.cpp

@@ -1296,6 +1296,9 @@ Song importFlp (const flp::Project& input, const FlpImportOptions& options)
             ++options.report->droppedEffects["Maximus (option not decoded: approximated)"];
         else if (plugin == "Soundgoodizer")
             ++options.report->droppedEffects["Soundgoodizer (preset file not found: approximated)"];
+        else if ((plugin == "Fruity Delay 2" && fx.kind != EffectKind::fruityDelay2)
+                 || (plugin == "Fruity Delay 3" && fx.kind != EffectKind::fruityDelay3))
+            ++options.report->droppedEffects[plugin + " (state not readable: approximated)"];
     };
 
     for (const auto& insert : project.mixer)

+ 85 - 25
src/core/FruityDelay.cpp

@@ -91,15 +91,26 @@ Ramp ramp (float& cur, float target, float maxStep, int n) noexcept
 }
 } // namespace
 
-Delay2Engine::Delay2Engine (const Delay2State& s, double sampleRate, double bpm, int maxBlock)
+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 / sampleRate;
+    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 = fbCur = (float) p[3] * 0.0078125f;
+    fbTarget = (float) p[3] * 0.0078125f;
     if (pan >= 0.0f)
     {
         auto g0 = 1.0f - pan;
@@ -124,15 +135,20 @@ Delay2Engine::Delay2Engine (const Delay2State& s, double sampleRate, double bpm,
     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) sampleRate) / 100000.0f));
-    const auto delay = std::max (1, roundEven ((double) (p[4] * (int) sampleRate) * 0.3125 / (double) (float) bpm));
-    offL = p[5] <= 0 ? offSamples : 0;
-    offR = p[5] <= 0 ? 0 : offSamples;
-    frames = delay + maxBlock + offSamples;
+    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;
-    tmp.resize ((std::size_t) maxBlock * 2);
 }
 
 void Delay2Engine::process (float* left, float* right, int n) noexcept
@@ -260,8 +276,50 @@ float tableAt (const float* t, float x) noexcept
     return (1.0f - fr) * t[i] + fr * t[i + 1];
 }
 
-// the engine's float sine (its library rounds a double-precision result; see §3.9)
-float sineF (float x) noexcept { return (float) std::sin ((double) x); }
+// 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); }
@@ -1011,6 +1069,7 @@ constexpr float engineDefaults[delay3Controls] { 1.0f, 0, 0, 0, 0.5f, 0.95f, 0,
 
 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();
@@ -1147,13 +1206,12 @@ public:
         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 || s.v != current.v || bpm != tempo)
-        {
-            // FL rebuilds the line on a time change; LYNX also restarts on any other change (rare: automation)
-            current = s;
-            tempo = bpm;
-            engine = std::make_unique<Delay2Engine> (s, rate, bpm, block);
-        }
+        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);
@@ -1172,20 +1230,20 @@ private:
 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.reset();
+        engine = std::make_unique<Delay3Engine> (rate);
+        fresh = true;
     }
-    void reset() noexcept override { engine.reset(); }
+    void reset() noexcept override { prepare (rate); }
 
     void process (float* left, float* right, int n, const EffectParams& params, double bpm) noexcept override
     {
-        bpm = bpm > 0.0 ? bpm : 120.0;
-        const bool fresh = engine == nullptr;
-        if (fresh)
-            engine = std::make_unique<Delay3Engine> (rate);
-        engine->setTempo (bpm);
+        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]);
@@ -1197,11 +1255,13 @@ public:
         }
         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;
 };

+ 8 - 2
src/core/FruityDelay.h

@@ -35,11 +35,17 @@ 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)
-    Delay2Engine (const Delay2State& s, double sampleRate, double bpm, int maxBlock = 512);
+    // 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;

+ 3 - 1
src/core/Song.h

@@ -290,7 +290,9 @@ enum class EffectKind : std::uint8_t
     squeeze,      // FL's Fruity Squeeze, exact (REA_rodada29 §2): quantiser, periodic gate, filter; raw values / max
     vintagePhaser, // FL's Vintage Phaser (REA_rodada29 §3, core/VintagePhaser.h): 36 normalised engine values
     vocodex,      // FL's Vocodex (REA_rodada35, core/Vocodex.h): built from FL's raw state (EffectSlot::state)
-    maximus       // FL's Maximus / Soundgoodizer engine (REA_rodada36/38, core/MaximusFx.h): built from EffectSlot::state
+    maximus,      // FL's Maximus / Soundgoodizer engine (REA_rodada36/38, core/MaximusFx.h): built from EffectSlot::state
+    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

@@ -140,6 +140,8 @@ const char* effectId (EffectKind k)
         case EffectKind::vintagePhaser: return "vintagePhaser";
         case EffectKind::vocodex: return "vocodex";
         case EffectKind::maximus: return "maximus";
+        case EffectKind::fruityDelay2: return "fruityDelay2";
+        case EffectKind::fruityDelay3: return "fruityDelay3";
     }
     return "eq";
 }
@@ -281,7 +283,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::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::fruityDelay2, EffectKind::fruityDelay3 })
         if (id == effectId (k))
             return k;
 

+ 2 - 1
src/ui/MixerComponent.cpp

@@ -1000,7 +1000,8 @@ constexpr int slotHeight = 24;
 const EffectKind allEffects[] = { EffectKind::eq,     EffectKind::parametricEq, EffectKind::compressor, EffectKind::limiter,
                                       EffectKind::delay,  EffectKind::reverb,       EffectKind::chorus,     EffectKind::filter,
                                       EffectKind::distortion, EffectKind::utility, EffectKind::volumeGate,
-                                      EffectKind::pitchShift, EffectKind::freqShift, EffectKind::lofi, EffectKind::effector, EffectKind::crossover, EffectKind::autoPan, EffectKind::vocoder, EffectKind::pitchCorrect };
+                                      EffectKind::pitchShift, EffectKind::freqShift, EffectKind::lofi, EffectKind::effector, EffectKind::crossover, EffectKind::autoPan, EffectKind::vocoder, EffectKind::pitchCorrect,
+                                      EffectKind::fruityDelay2, EffectKind::fruityDelay3 };
 } // namespace
 
 const std::vector<EffectKind>& addableEffects()

+ 115 - 0
tests/tests.cpp

@@ -38,6 +38,7 @@
 #include "core/Kepler.h"
 #include "core/HarmlessFx.h"
 #include "core/MaximusFx.h"
+#include "core/FruityDelay.h"
 #include "core/LiveEventQueue.h"
 #include "core/RackRenderer.h"
 #include "core/Scheduler.h"
@@ -778,6 +779,7 @@ TEST (flp_real_files)
     int dwChannels = 0, dwZones = 0, fpcKits = 0, padChannels = 0, padNotes = 0;
     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 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();
@@ -954,6 +956,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";
                     }
@@ -969,6 +973,8 @@ TEST (flp_real_files)
                         }
                         if (fx.kind == lynx::EffectKind::vocodex)
                             vocodexWithData += ! lynx::vocodex::splitInstallData (fx.state).second.sgDat.empty();
+                        delay2Exact += fx.kind == lynx::EffectKind::fruityDelay2;
+                        delay3Exact += fx.kind == lynx::EffectKind::fruityDelay3;
                     }
                 for (const auto& pat : full.patterns)
                     for (const auto& n : pat.notes)
@@ -1611,6 +1617,9 @@ TEST (flp_real_files)
     // option; the other Data folders add states with options not decoded
     CHECK (maximusSlots - maximusExact <= 16 && maximusExact >= 97 && sgzExact == sgzSlots && sgzSlots > 90);
     CHECK (vocodexWithData == vocodexSlots && vocodexSlots >= 10);
+    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;
@@ -8484,3 +8493,109 @@ TEST (minisynth_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;
+}