Skip to content

armgit / nota

Public Imported from GitHub
0

Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.

(fix) Nota Reverb no longer fires a loud, looping metallic burst

Egor Khindikaynena8e8dc7d01b4
diff --git a/.specify/bugs/reverb-metallic-burst/assessment.md b/.specify/bugs/reverb-metallic-burst/assessment.md
new file mode 100644
index 00000000..efbb10a7
--- /dev/null
+++ b/.specify/bugs/reverb-metallic-burst/assessment.md
@@ -0,0 +1,273 @@
+# Bug Assessment: Nota Reverb — sudden loud metallic burst after a while
+
+- **Slug**: reverb-metallic-burst
+- **Created**: 2026-10-13
+- **Source**: pasted text
+- **Verdict**: valid
+- **Severity**: high
+
+## ROOT CAUSE — CONFIRMED (2026-10-13, supersedes the hypothesis below)
+
+**An out-of-bounds read in `Reverb::Comb::process` (`Reverb.h:375-377`).**
+
+```cpp
+float rp = w - std::clamp(delay, 1.0f, (float)size - 2.0f);
+if (rp < 0) rp += size; // rp = -7.6e-6 → size - 7.6e-6 rounds to exactly `size` in float
+int i0 = (int)rp; // i0 == size → buf[size] is one past the end
+```
+
+The read position is fractional, because the comb length is `tuning·srScale·span_ ± LFO`.
+When it lands a hair *above* the integer write index (`w − delay ∈ (−ulp/2, 0)`, ulp ≈ 1.2–2.4e-4
+for sizes of 1000–4000), `rp + size` rounds to `size` and `buf[size]` reads the heap word right
+after the comb buffer. Whatever is there (allocator metadata, a neighbour's data) enters the
+feedback loop as a sample. Usually it is small and goes unnoticed. Sometimes it is a huge
+finite float, or a NaN — which is what the earlier "NaN guard" fix was really catching. A huge
+value then recirculates at the comb's pitch and is held at the soft clipper's ceiling: a loud,
+**looped, metallic** ring.
+It's a rare per-sample coincidence (16 combs × ~27 loop cycles/s × a ~1e-4 window), hence
+"after a while", seemingly random, and independent of what is played.
+
+Evidence:
+- **In-app flight recorder dump** (`~/nota-reverb-trace/20261013-122155-rv1-4.*`, Live Room
+ settings, 252 s in): params unchanged, input 0.46, comb input 0.0165, and in that same block
+ the **comb sum is 6.2e34**. The value didn't come from the input; it appeared inside a
+ comb. Afterwards the allpasses hold 6.2e34, the raw wet is 1.5e34, and the output is pinned
+ at ≈ 2.5 (soft-clip ceiling × Output).
+- **AddressSanitizer** on the standalone harness (user's sample + Live Room params) reports
+ `heap-buffer-overflow ... READ of size 4 ... 0 bytes after 9116-byte region` in
+ `Reverb::process` → `Comb::process`, with the buffer allocated by `Comb::init` in
+ `setSampleRate`. It triggers within the first minutes of the run.
+- Minimal repro of the arithmetic: `size=2500, w=100, delay=100.00001f` gives `rp=2500, i0=2500`.
+
+Why earlier fixes didn't help: the NaN/Inf guards only reject *non-finite* garbage. The soft
+clipper only bounds the level. Size smoothing addressed a different click. None of them stopped
+the out-of-bounds read.
+
+### Remediation (replaces "Proposed Remediation" below as the primary fix)
+
+1. `Comb::process`: make the wrap index-safe. After wrapping, clamp the index:
+ `int i0 = (int)rp; if (i0 >= size) i0 -= size;` (keep `i1` as is). Better still, compute
+ the read position in `double`, or as integer + fraction, and wrap the *integer* part.
+2. Same class, rarer (double precision): `Reverb::readPre` (`Reverb.h:347-353`) and
+ `Delay::read` (`Delay.h:318-324`) — apply the same `i0 >= n → i0 -= n` guard. Audit other
+ fractional delay reads (Chamber's algorithmic tail, Chorus/Flanger/Phaser) for the same
+ `if (rp < 0) rp += size; (int)rp` shape. Masked reads (`& (N-1)`, e.g. Keys, Vintage) are
+ safe.
+3. Regression test: a deterministic unit-level check that drives `Comb`-style reads with
+ `w − delay = −ulp/4` at several sizes and asserts the index stays in range. Plus a short ASan
+ soak of `Reverb::process` on noise with modulation on (CI or a dev script).
+4. Remove the temporary `ReverbTrace.h` instrumentation before merging.
+5. Optional follow-ups, separate from this bug: the resonance gain-staging issue described
+ below (Freeverb allpass at g up to 0.75, unnormalized comb gain, soft clipper above 0 dBFS).
+ Real, but it produces predictable overs on long presets, not this burst.
+
+## Report (verbatim or summarized)
+
+> Сейчас когда добавляю эффект Reverb в цепочку устройств, через какой-то время может
+> "выстрелить" резкий громкий металлический звук. Я не могу сказать четко, когда он
+> возникает, но проявляется это почти всегда спустя время. Этот баг уже пытались фиксить
+> несколько раз, но до сих пор он есть.
+
+Previous fix attempts (CHANGELOG):
+- an earlier release — NaN/Inf guards in the comb/allpass loops and tone filters
+ ("periodic metallic overdriven roar");
+- 0.34.0 — delay-length smoothing on Size/Algorithm change (`kSpanGlide`) + soft
+ saturator instead of a hard clip on the wet output.
+
+Neither touched the gain structure of the tail, which is where the burst comes from.
+
+## Symptom
+
+With Nota Reverb (builtin kind 2) on a track, a loud metallic ringing occasionally builds
+up and overloads the output (above 0 dBFS, rounded off by the wet soft clipper). It shows up
+"after a while" and seemingly at random. In practice it happens when a held note or a
+sustained partial lands on one of the tail's sharp resonances. Expected: a reverb tail with
+no ringing modes that sit tens of dB above the average response, and that never drives the
+output past full scale on normal-level input.
+
+## Reproduction
+
+Reproduced offline with a standalone harness (`/tmp/revtest/`, not in repo) that drives
+`nota::Reverb::process()` directly at 48 kHz, 512-frame blocks:
+
+1. Default Reverb, Dry/Wet 1.0 (or Decay ≈ 0.8 / Diffusion ≈ 0.8, Mix 0.5).
+2. Feed held saw notes at −12 dBFS (0.25 peak), random pitch MIDI 36–72, 2 s each, 300 notes.
+3. Watch the output peak per note.
+
+| Settings (decay / diffusion / mix) | Notes > 0 dBFS | Worst peak |
+|---|---|---|
+| 0.55 / 0.60 / 0.30 (defaults) | 0 / 300 | −7.2 dBFS |
+| 0.55 / 0.60 / 1.00 | 2 / 300 | +0.4 dBFS |
+| 0.80 / 0.80 / 0.50 | 2 / 300 | +0.4 dBFS |
+| 0.90 / 1.00 / 0.50 | **128 / 300** | **+5.6 dBFS** |
+
+The same run with the output allpasses swapped for true (unity-magnitude) Schroeder
+allpasses: 0 / 300 in every row, worst ≈ −10 dBFS.
+
+Wet impulse-response spectrum (20 Hz–8 kHz, Early Refl off, Mod Depth 0):
+
+| decay / diff / damp | current peak gain | current peak / median | true-allpass peak / median |
+|---|---|---|---|
+| 0.55 / 0.6 / 0.5 | 5.4× (+14.6 dB) | 16 dB | 16 dB |
+| 0.55 / 1.0 / 0.5 | 10.3× (+20.2 dB) | 19 dB | 16 dB |
+| 0.90 / 1.0 / 0.5 | 40.5× (+32.1 dB) | 29 dB | 23 dB |
+| 1.00 / 1.0 / 0.0 | 63.1× (+36.0 dB) | 32 dB | 27 dB |
+
+Random parameter automation (Decay, Size, Diffusion, Algorithm, Freeze…) over 20 simulated
+minutes gave peaks up to ≈ 2.1–2.3 (the soft-clip ceiling), but no NaN or unbounded growth.
+The loops are stable; the problem is gain, not instability.
+
+[NEEDS CLARIFICATION: which source material and Reverb settings the user had when they heard
+it — sustained synth/bass, long Decay, high Diffusion? Confirms the trigger but not the
+diagnosis.]
+
+## Suspected Code Paths
+
+- `src/native/nota.engine/src/Reverb.h:367-378` (`Reverb::Allpass::process`): this is the
+ Freeverb "allpass" (`out = -in + buf; buf = in + buf·g`), which is **not** allpass. Its
+ magnitude swings between `g/(1-g)` and `(2+g)/(1+g)`. Freeverb keeps g = 0.5, which is
+ close to flat. Here `diff = 0.4 + Diffusion·0.35` pushes g to 0.75, so each stage peaks at
+ ×3 (+9.5 dB). Four stages in series reach up to ×81 (+38 dB) where their peaks line up,
+ always including DC/low frequencies. This is the main extra coloration and gain.
+- `src/native/nota.engine/src/Reverb.h:133-137` (comb feedback): an honest RT60 gives
+ `fb` up to 0.995 (12 s). The comb resonance peak is `1/(1-fb)` (×200), but the input gain is
+ a constant `0.015`. Steady-state gain on a comb mode therefore grows with Decay and is never
+ normalized.
+- `src/native/nota.engine/src/Reverb.h:204-208, 274-278` (`softClip`): the last safety net
+ is transparent up to 1.2 and saturates toward ±2.2, *then* gets multiplied by `outG` (up to
+ ×2). So a resonance can reach the bus at ≈ +7…+13 dBFS. The tanh knee on a narrow ringing
+ mode is exactly the "loud metallic" sound.
+- `src/native/nota.engine/src/FluxSynth.h:451`: the same Freeverb allpass pattern (not part
+ of this bug; noted for consistency).
+
+## Root Cause Hypothesis (initial — superseded, see ROOT CAUSE above)
+
+The tail has extremely peaky steady-state gain. The output diffuser's Freeverb-style
+"allpass" stages, run at g up to 0.75 instead of Freeverb's 0.5, stack up to +38 dB of
+coloration. On top of that, the eight high-feedback combs have peak gain ∝ 1/(1-fb), which
+is not normalized against Decay. When a held note or partial hits one of these modes, it
+builds over roughly one RT60 into a narrow, loud ring. That explains "after a while" and
+"random": it depends on which pitch is held. The ring then drives the wet soft clipper,
+whose ceiling sits above full scale and is boosted again by Output. Previous fixes
+addressed NaN latching and pointer jumps, which are real but different mechanisms; the gain
+structure was never touched. Confidence: **high** for the mechanism (measured, and fixed in
+a harness by swapping the allpass). **Medium** that this is the exact trigger the user hits.
+The secondary race below could also produce a sudden burst, but only around engine start.
+
+## Proposed Remediation
+
+**Preferred**:
+1. Replace `Reverb::Allpass::process` with a true Schroeder allpass, the same form as
+ `DiffAp`: `v = in + g·buf; out = buf − g·v; buf = v`. Unity magnitude, same diffusion.
+ Keep the Diffusion → g mapping.
+2. Re-calibrate the wet level with a fixed makeup gain so the default preset's tail loudness
+ (wet RMS of the IR at default params) stays close to the current one. The true allpass
+ chain has a much lower mean gain (the median IR bin drops ~16 dB at defaults), so without
+ makeup the reverb would suddenly sound much quieter.
+3. Partially normalize the comb input against Decay, e.g. `inGain ∝ sqrt(1 − fb²)` blended
+ or clamped so long tails still get louder but the mode peak can't run away. Calibrate so
+ Decay 0.9–1.0 with Diffusion 1.0 keeps held −12 dBFS notes well under 0 dBFS at Mix 0.5.
+4. Make the wet safety net an actual ceiling: knee and limit at or below 0 dBFS *after*
+ `outG` (or apply `outG` before the soft clip). It stays a last resort, not the mechanism
+ that shapes the sound.
+
+**Alternatives**:
+- Keep the Freeverb allpass but cap g at 0.5 (original Freeverb). Smallest diff and keeps
+ the character, but Diffusion loses most of its range, and long-decay comb peaks
+ (point 3) remain.
+- Only lower the soft-clip ceiling. Removes the overload but not the metallic ringing. This
+ is the same symptomatic class as the previous attempts — not recommended alone.
+
+**Files likely to change**:
+- `src/native/nota.engine/src/Reverb.h`
+- `tests/Nota.SmokeTest/Program.cs` (or a new `ReverbTests.cs` in the smoke project)
+- `CHANGELOG.md` (`[Unreleased]` → Fixed)
+
+**Tests to add or update**:
+- Smoke regression: instrument track playing held notes across a pitch range at moderate
+ velocity → Nota Reverb with Decay 0.9, Diffusion 1.0, Mix 0.5 → render offline. Assert
+ master peak < 1.0 (0 dBFS) for every note. Use a deterministic source (see the smoke-level
+ memo: synth levels drift ±2 dB; a fixed WAV clip or a fixed-seed saw is safer).
+- Level-preservation check: wet RMS of a noise burst at default settings within ±1.5 dB of
+ the pre-fix value, so the recalibration doesn't change the default sound's loudness.
+- Keep the existing 20-minute random-automation soak idea as a dev harness. Optionally
+ promote a short version (a few seconds of random param jumps) to the smoke test: no NaN,
+ peak bounded.
+
+## Risks & Considerations
+
+- **Sound change**: a true allpass and decay normalization change the reverb's colour and
+ level. Existing projects will sound different (cleaner, possibly quieter at long Decay).
+ Calibrate carefully and mention it in the CHANGELOG. Param layout is untouched, so there is
+ no persistence or migration impact.
+- **Realtime**: all changes are arithmetic inside `process()`; no allocation, no locks.
+ Audio-thread rules hold.
+- **Secondary race (separate issue)**: `Engine::start()` (`Engine.cpp:62-65`) starts the
+ backend callback and *then* calls `propagateSampleRate()`. That runs
+ `Reverb::setSampleRate()` and reallocates the comb/allpass/pre-delay vectors on the
+ calling thread while the audio thread may already be in `process()`. This is a
+ use-after-free window that can inject garbage into the loops, and it affects every built-in
+ device with buffers. It only fires around engine start or device restart, not "after a
+ while", so it is unlikely to be this report — but it should be tracked separately.
+- `FluxSynth.h:451` uses the same non-allpass structure; out of scope here.
+
+## Open Questions
+
+- [NEEDS CLARIFICATION: typical Reverb settings and source when the burst happens (long
+ Decay? high Diffusion? sustained synth/pad/bass?)]
+- [NEEDS CLARIFICATION: how much loudness change at long Decay is acceptable after
+ normalization — keep "long = louder" partially, or flatten fully?]
+
+## Update 2026-10-13 — user reproduction (preset `Reverb_Bug01`)
+
+User reproduced it: one looped audio sample (warp mode 3, 168 BPM, 16-beat loop), Nota Reverb
+with `Reverb_Bug01`, which is exactly factory "Live Room" (Decay 0.44, Room, Mix 0.24). It fired
+5–10 min into looped playback. The Reverb card was open and the user was **switching presets**
+while playing. They describe the sound as possibly **looped** ("зацикленный"), not only metallic.
+With the Reverb removed from the chain, everything is fine.
+
+Harness results (all in `/tmp/revtest/`, not in repo) — **none reproduced the burst**:
+
+| Run | Duration | Result |
+|---|---|---|
+| `Reverb::process` alone, user's sample + exact params, 512 blocks | 30 min / 314 loops | per-loop peak constant (0.592) |
+| Real engine via C ABI, offline render, track + warp clip + Reverb, transport loop | 20 min, ± Reverb | peak constant (0.39–0.41) |
+| Same, block sizes 470/471, random 1–1024, 441 with 17s mixed in | 3 × 20 min | peak constant |
+| Real engine, **live CoreAudio backend** (master vol 0), polling track meter + Reverb scope every 2 ms | 25 min, ± Reverb | no anomaly, 0 xruns, peak ≤ 0.43 |
+| `Reverb::process` + random factory-preset switching every 1–8 s (applied like `PresetService.ApplyInPlace`: named value or default per param) | 15 min | worst 1.07 (Infinite Pad), 1.12 (Send · Plate); no burst/loop |
+
+Conclusions so far:
+- With "Live Room" settings the comb/allpass resonance gain (main hypothesis above) is too small
+ to explain a *sudden loud* event on this material. It still explains the >0 dBFS overs on
+ long-decay presets.
+- The deterministic engine path (offline and live, without the app UI) is clean. The trigger is
+ something only the running app does: preset switching from the card, the browser's preset
+ audition (`PresetAudition` → engine preview, which can loop — `nota_engine_set_preview_loop`),
+ or another UI-thread interaction.
+- Code read so far: `Engine::deviceSetParam` (atomic store + PDC check), `deviceParamDefault`
+ (builds a throw-away `Reverb` per call — wasteful, but no shared state), autosave/Capture
+ (read-only), Reverb card refresh (`scopeRead`, atomics only) — none mutates live DSP state.
+- Factory presets "Shimmer Freeze" and "Stone Hold" turn **Freeze** on. Stepping through
+ presets with Next/Prev passes through them and holds whatever tail is ringing as an endless
+ loop until a non-freeze preset is applied. A preset-switching session would therefore produce
+ a "looped" sound by design — confirm whether that is what was heard.
+
+Next step proposed: in-app instrumentation (env-guarded, e.g. `NOTA_REVERB_TRACE`). The Reverb
+keeps a ring buffer of its last ~3 s of input/output plus a per-block snapshot of params, `fb`,
+`span_`, comb-buffer max and freeze state. When the wet peak jumps >12 dB above its running
+level, it dumps the ring to a file. The user then reproduces with the normal workflow, and the
+dump tells us whether the input was already bad (source/preview), a param/state change caused
+it, or the loop ran away.
+
+### Instrumentation added (temporary, uncommitted)
+
+- `src/native/nota.engine/src/ReverbTrace.h` (new) + hooks in `Reverb.h` (`setSampleRate`,
+ `process`, member `trace_`). Inert unless `NOTA_REVERB_TRACE` is set (`1` → temp dir, or a path).
+- Triggers: raw wet ≥ 12 dB over its ~2 s running level, raw wet > 1.2 (soft-clip knee),
+ non-finite internal value, or **Kill tail** (manual save, bypasses the 15 s cooldown). At most
+ 12 dumps per instance.
+- Each dump: `<time>-rv<id>-<n>.wav` (4 ch float32: in L/R, out L/R; 8 s before + 1 s after),
+ `.csv` (per block: params, comb feedback, size glide, peaks at input / comb input / comb sum /
+ after allpasses / raw wet / output), `.txt` (reason, times).
+- Verified in a harness (auto, soft-clip and manual triggers) and on the real engine (2 min of the
+ user's loop: one instance, no false triggers). Remove before the fix lands.
diff --git a/.specify/bugs/reverb-metallic-burst/fix.md b/.specify/bugs/reverb-metallic-burst/fix.md
new file mode 100644
index 00000000..518271d1
--- /dev/null
+++ b/.specify/bugs/reverb-metallic-burst/fix.md
@@ -0,0 +1,94 @@
+# Bug Fix: Nota Reverb — sudden loud looped metallic burst
+
+- **Slug**: reverb-metallic-burst
+- **Fixed**: 2026-10-13
+- **Assessment**: ./assessment.md
+- **Status**: applied
+
+## Summary
+
+`Reverb::Comb::process` occasionally read `buf[size]`, one float past the end of its delay
+line. A fractional read position a hair past the write head wraps to `size − 1e-5`, which
+rounds to exactly `size` in float. The stray heap word, sometimes a huge finite value,
+recirculated in the comb as the loud looped ring. The read index is now wrapped back into
+range. The same edge case is guarded in the other fractional delay reads of the same shape,
+and a device-free self-test pins the case in the smoke test.
+
+## Changes
+
+| File | Change | Notes |
+|------|--------|-------|
+| `src/native/nota.engine/src/Reverb.h` | modified | `Comb::process`: `if (i0 >= size) i0 -= size;` after the wrap (the fix). `readPre`: same guard (double precision, much rarer). New public static `combWrapSelfTest()`. |
+| `src/native/nota.engine/src/Delay.h` | modified | `Delay::read`: same guard (double, same `rp += size; (int)rp` shape). |
+| `src/native/nota.engine/src/WavetableSynth.h` | modified | Chorus `tap` lambda: same guard (scope expansion, see below). |
+| `src/native/nota.engine/include/nota/nota_engine.h` | modified | New `nota_engine_reverb_wrap_selftest`. |
+| `src/native/nota.engine/src/nota_engine_device.cpp` | modified | C ABI entry → `Reverb::combWrapSelfTest()`. |
+| `src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs` | modified | P/Invoke `ReverbWrapSelfTest`. |
+| `src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs` | modified | `NotaEngine.ReverbWrapSelfTest()`. |
+| `tests/Nota.SmokeTest/Program.cs` | added test | Check in the "Nota Reverb" section. |
+| `CHANGELOG.md` | modified | `[Unreleased] → Fixed` entry. |
+| `src/native/nota.engine/src/ReverbTrace.h` | removed | Temporary flight recorder from the assessment (never committed), removed as the assessment required; `Reverb.h` hooks reverted. |
+
+## Diff Highlights
+
+```cpp
+// Reverb::Comb::process
+float rp = w - std::clamp(delay, 1.0f, (float)size - 2.0f);
+if (rp < 0) rp += size;
+int i0 = (int)rp; float frac = rp - i0;
+if (i0 >= size) i0 -= size; // rp + size can round up to exactly `size` in float
+int i1 = i0 + 1; if (i1 >= size) i1 -= size;
+```
+
+`frac` is taken before the wrap. When `i0 == size`, `rp == size`, so `frac == 0` and the read
+returns `buf[0]`, the sample the true position (`size − 1e-5`) is closest to.
+
+## Tests Added or Updated
+
+- `Reverb::combWrapSelfTest()` (via `nota_engine_reverb_wrap_selftest`, smoke check
+ "Reverb comb read stays inside its delay line at the wrap edge (no metallic burst)"). It
+ sweeps comb sizes 1000–4000 and write indices, and sets the delay to the next float above
+ `w`, the exact case where `rp + size` rounds to `size`. It fills the line with zeros except
+ `buf[0] = 1` and asserts the comb returns 1. It requires at least one size/index pair to
+ actually hit the rounding case, so it can't pass vacuously.
+
+## Local Verification
+
+- Self-test against the unfixed code (guard line removed in a copy): **ASan
+ heap-buffer-overflow**; without ASan **FAIL**. Against the fix: **PASS**, ASan clean.
+- `scripts/build.sh` → native Release build, `dotnet build Nota.sln -c Release`, smoke test
+ **SMOKE TEST PASSED**, including the new check and "every factory preset applies cleanly
+ (429 instrument, 944 effect, 0 failed)".
+- ASan soak of the fixed `Reverb::process` with the user's sample and Live Room params: 20 min /
+ 209 loops, clean, per-loop peak constant (0.592). Before the fix the same harness reported
+ the overflow within minutes.
+- ASan soak with random factory-preset switching every 1–8 s: 15 min, clean.
+- `src/managed/Nota.App/bin/{Debug,Release}/net10.0/libnota_engine.dylib` refreshed with the
+ fixed build (trace-free, exports `nota_engine_reverb_wrap_selftest`) so a Rider run picks it
+ up without a Rebuild.
+
+## Deviations from Assessment
+
+- **Scope expansion**: `WavetableSynth.h` chorus `tap` has the same `while (rp < 0) rp += sz;
+ (int)rp` shape (double) and was guarded too. Not listed in the assessment; found in the
+ audit it asked for.
+- **Audited, left unchanged**: Keys/Vintage/BeatRepeat (masked indices, safe); Flanger/Chorus
+ (floor + mask, safe); Ceiling/Compressor/Prism/Shutter (integer delays, safe).
+ Strata's loop position can round to `len` on reverse play. It reads `buf_[len]`, which sits
+ inside the `maxLoop_` allocation, so it is not out of bounds; it only reads a stale sample at
+ the loop seam. Listed as a follow-up.
+- The test is a device-free C-ABI self-test (the engine's existing pattern) rather than a
+ standalone unit test, because the engine has no native test runner.
+
+## Follow-ups
+
+- Strata: wrap `pos_` (or `p0`) the same way on reverse playback (seam sample, not a memory
+ error).
+- The gain-staging findings in the assessment are separate from this burst: the Freeverb
+ "allpass" at g up to 0.75, comb gain not normalized against Decay, and a soft-clip ceiling
+ above 0 dBFS. They cause predictable overs on long-decay presets (Infinite Pad, Send ·
+ Plate ≈ 1.1). A candidate for its own change.
+- `Engine::deviceParamDefault` builds a full throw-away device per call (21 Reverbs per
+ preset apply). Harmless, but wasteful.
+- Startup race: `Engine::start()` runs `propagateSampleRate()` after the audio callback is
+ live (noted in the assessment, separate issue).
diff --git a/.specify/bugs/reverb-metallic-burst/test.md b/.specify/bugs/reverb-metallic-burst/test.md
new file mode 100644
index 00000000..93b2694b
--- /dev/null
+++ b/.specify/bugs/reverb-metallic-burst/test.md
@@ -0,0 +1,64 @@
+# Bug Verification: Nota Reverb — sudden loud looped metallic burst
+
+- **Slug**: reverb-metallic-burst
+- **Tested**: 2026-10-13
+- **Assessment**: ./assessment.md
+- **Fix**: ./fix.md
+- **Result**: partial
+
+## Summary
+
+The root cause, an out-of-bounds comb read (`buf[size]`), reproduces deterministically under
+AddressSanitizer on the user's own loop with the code before the fix. With the fix it no
+longer occurs in 20 min of the same material, nor in random-automation soaks at 48 and 96 kHz.
+The new self-test passes, and the full smoke suite passes with no regressions. **Partial**
+only because the original in-app symptom (a burst after minutes of live playback) has not yet
+been re-checked in the running app after the fix. That is the one reproduction the assessment
+recorded that these checks don't exercise directly.
+
+## Checks Performed
+
+| Check | Command / Action | Result | Notes |
+|-------|------------------|--------|-------|
+| Reproduction, **pre-fix** (control) | ASan build of `Reverb::process` on `/tmp/revtest/s/loop.wav` (user's sample) + Live Room params, guard line removed (`/tmp/revtest/neg/Reverb.h`) | fail (expected) | `heap-buffer-overflow … 0 bytes after 9116-byte region` in `Comb::process` (`Reverb.h:173` in the copy), 2 s wall time |
+| Reproduction, **post-fix** | Same harness against the working tree, 20 min of audio | pass | 209 loops, ASan clean, per-loop peak constant 0.592 |
+| Random automation, 48 kHz | ASan, `t_sr` scenario 3 (Decay/Size/Diffusion/Algorithm/Freeze/… jumps every ~2 s), 10 min | pass | ASan clean; max 2.06 = soft-clip ceiling on extreme settings (gain-staging follow-up, not this bug) |
+| Random automation, 96 kHz | Same, 10 min | pass | ASan clean; different comb sizes |
+| Preset switching (from fix phase) | ASan, random factory-preset switching every 1–8 s, 15 min | pass | ASan clean |
+| New test | `dotnet run --project tests/Nota.SmokeTest -c Release` | pass | `[PASS] Reverb comb read stays inside its delay line at the wrap edge (no metallic burst)`. The fix phase showed the same self-test **fails** on the unfixed code (ASan overflow / FAIL). |
+| Regression suite | Same smoke run (drives the engine end-to-end; preceded by `scripts/build.sh` in the fix phase) | pass | `SMOKE TEST PASSED`, 3104 `[PASS]`, 0 `[FAIL]` |
+| Lint / warnings | `c++ -std=c++20 -fsyntax-only -Wall -Wextra` on `Reverb.h`, `Delay.h`, `WavetableSynth.h` | pass | No warnings in the changed headers. The project has no separate linter. |
+| In-app re-test after fix | Nota from Rider, looped sample + Reverb + preset switching, 15–20 min | not-run | Needs the user's session. The fixed `libnota_engine.dylib` is already in `bin/Debug` and `bin/Release`. |
+
+## Output Excerpts
+
+```
+pre-fix: ==44053==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x62500000c49c
+ READ of size 4 ... is located 0 bytes after 9116-byte region
+ #0 nota::Reverb::process(float*, int) Reverb.h:173
+post-fix: done: 209 loops, first-loop peak 0.592 rc=0
+48 kHz: scen 3 done, max=2.056 rc=0
+96 kHz: scen 3 done, max=2.020 rc=0
+smoke: [PASS] Reverb comb read stays inside its delay line at the wrap edge (no metallic burst)
+ SMOKE TEST PASSED
+```
+
+## Residual Risks
+
+- The in-app symptom has not been re-observed after the fix (see above). The trigger is rare
+ (minutes) and the garbage value depends on heap layout, so even an in-app absence over
+ 20 min is supporting evidence, not proof. The ASan control/fix pair is the decisive check.
+- The ASan soaks cover the standalone `Reverb`. Delay and the WavetableSynth chorus got the
+ same guard, but they were only exercised by the smoke suite, not by a dedicated ASan soak.
+ Their edge case is in double precision and ~10⁷× rarer.
+- Unrelated to this bug and still open (see `fix.md` follow-ups): overs up to the soft-clip
+ ceiling on extreme or long-decay settings, the Strata reverse-loop seam, and the startup
+ `propagateSampleRate` race.
+
+## Recommendation
+
+Hold for one in-app confirmation: run Nota from Rider with the looped sample, Nota Reverb
+(Live Room) and some preset switching for 15–20 min. If no burst occurs, close the bug as
+verified. Everything automatable is green, and the decisive ASan control shows the
+out-of-bounds read before the fix and none after. If a burst still occurs, re-enable the
+flight recorder from the assessment phase and re-run `/speckit-bug-assess` with the new dump.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 42bc23b8..51e73af9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -30,6 +30,11 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
(shortcut **F11**) enters and leaves full screen; on macOS the green button does it.
### Fixed
+- **Nota Reverb no longer fires a loud, looping metallic burst:** after a few minutes of
+ playback the reverb could suddenly ring at full level and keep ringing. The cause was a
+ rare off-by-one read just past the end of a reverb delay line, which pulled a garbage
+ value into the tail. The read now always stays inside the line. Nota Delay and the
+ Wavetable synth's chorus had the same rare edge case and are fixed too.
- **The preset picker opens from anywhere on it:** the preset field in a device header only
responded to a click on the preset's name. The whole field opens the list again.
- **The preset picker stays put:** a device's type and voice count (Consort's "DUO 1/2",
diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs
index 30b32271..cd6db64b 100644
--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs
@@ -73,6 +73,9 @@ internal static partial class NativeMethods
[LibraryImport(Lib, EntryPoint = "nota_device_scope")]
internal static partial int DeviceScope(IntPtr engine, int trackId, int deviceIndex, [Out] float[] outSamples, int maxSamples);
+ [LibraryImport(Lib, EntryPoint = "nota_engine_reverb_wrap_selftest")]
+ internal static partial int ReverbWrapSelfTest(IntPtr engine);
+
[LibraryImport(Lib, EntryPoint = "nota_device_action")]
internal static partial void DeviceAction(IntPtr engine, int trackId, int deviceIndex, int id, int iarg, float farg);
[LibraryImport(Lib, EntryPoint = "nota_device_layer_wave")]
diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs
index 50d4c913..3d026b92 100644
--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs
@@ -107,6 +107,10 @@ public sealed partial class NotaEngine
public int DeviceScope(int trackId, int deviceIndex, float[] outSamples, int maxSamples)
{ ThrowIfDisposed(); return NativeMethods.DeviceScope(_handle, trackId, deviceIndex, outSamples, maxSamples); }
+ /// <summary>Device-free self-test: the Reverb comb read stays inside its delay line at the wrap edge.</summary>
+ public bool ReverbWrapSelfTest()
+ { ThrowIfDisposed(); return NativeMethods.ReverbWrapSelfTest(_handle) != 0; }
+
public void DeviceAction(int trackId, int deviceIndex, int id, int iarg, float farg)
{ ThrowIfDisposed(); NativeMethods.DeviceAction(_handle, trackId, deviceIndex, id, iarg, farg); }
public int DeviceLayerWave(int trackId, int deviceIndex, int layer, float[] outSamples, int maxSamples)
diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.h
index f634a1d0..a4712128 100644
--- a/src/native/nota.engine/include/nota/nota_engine.h
+++ b/src/native/nota.engine/include/nota/nota_engine.h
@@ -1252,6 +1252,9 @@ NOTA_API float nota_builtin_device_param_default(const NotaEngine* engine,
* Nota EQ-8: a telemetry block, then its pre and post spectra); 0 for devices
* without one. Lock-free; torn reads are fine. */
NOTA_API int32_t nota_device_scope(const NotaEngine* engine, int32_t track_id, int32_t device_index, float* out, int32_t max_samples);
+/* Device-free self-test: Nota Reverb's comb read never indexes past its delay line when the
+ * read position lands a hair past the write head (the "metallic burst" bug). 1 = pass. */
+NOTA_API int32_t nota_engine_reverb_wrap_selftest(NotaEngine* engine);
/* Interactive-device command channel (the looper's Record/Overdub/Play/Stop/Undo/
* Clear and per-layer mute/gain). The engine applies it at the next quantize boundary. */
NOTA_API void nota_device_action(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t id, int32_t iarg, float farg);
diff --git a/src/native/nota.engine/src/Delay.h b/src/native/nota.engine/src/Delay.h
index 4a5c2073..4bc7cb79 100644
--- a/src/native/nota.engine/src/Delay.h
+++ b/src/native/nota.engine/src/Delay.h
@@ -318,7 +318,8 @@ private:
float read(const std::vector<float>& b, double delay) const {
double rp = write_ - std::clamp(delay, 1.0, static_cast<double>(size_) - 3.0);
while (rp < 0) rp += size_;
- const int i0 = static_cast<int>(rp); const float frac = static_cast<float>(rp - i0);
+ int i0 = static_cast<int>(rp); const float frac = static_cast<float>(rp - i0);
+ if (i0 >= size_) i0 -= size_; // a hair-negative rp + size_ can round up to exactly size_
int i1 = i0 + 1; if (i1 >= size_) i1 -= size_;
return b[i0] + (b[i1] - b[i0]) * frac;
}
diff --git a/src/native/nota.engine/src/Reverb.h b/src/native/nota.engine/src/Reverb.h
index 19a284f3..736c5f21 100644
--- a/src/native/nota.engine/src/Reverb.h
+++ b/src/native/nota.engine/src/Reverb.h
@@ -240,6 +240,27 @@ public:
float getParam(int32_t i) const override { return (i >= 0 && i < kNumParams) ? p_[i].load(std::memory_order_relaxed) : 0.0f; }
void setParam(int32_t i, float v) override { if (i >= 0 && i < kNumParams) p_[i].store(std::clamp(v, 0.0f, 1.0f), std::memory_order_relaxed); }
+ // Regression self-test for the comb read wrap (nota_engine_reverb_wrap_selftest): put the
+ // read position a hair past the write head — the case that used to read buf[size] — and
+ // check the comb reads its own first sample. Device-free, no allocation beyond the comb.
+ static bool combWrapSelfTest() {
+ int hits = 0;
+ for (int size : {1000, 1500, 2000, 2500, 3000, 4000}) {
+ for (int w : {2, 100, size / 2, size - 3}) {
+ Comb c; c.init(size);
+ std::fill(c.buf.begin(), c.buf.end(), 0.0f);
+ c.buf[0] = 1.0f; c.w = w; c.set(0.0f, 0.0f, 1.0f);
+ // Smallest float delay above w: w - delay is a tiny negative, rp + size rounds to size.
+ const float delay = std::nextafter(static_cast<float>(w), 1e9f);
+ float rp = w - delay; if (rp < 0) rp += size;
+ if (static_cast<int>(rp) != size) continue; // this size/w doesn't hit the rounding case
+ ++hits;
+ if (c.process(0.0f, delay) != 1.0f) return false;
+ }
+ }
+ return hits > 0; // the rounding case must actually have been exercised
+ }
+
// Nothing is added to the dry path — the wet is the effect itself.
int32_t latencySamples() const override { return 0; }
@@ -322,7 +343,8 @@ private:
const int n = static_cast<int>(b.size());
double rp = preW_ - std::clamp(delay, 0.0, static_cast<double>(n) - 2.0);
if (rp < 0) rp += n;
- const int i0 = static_cast<int>(rp); const float frac = static_cast<float>(rp - i0);
+ int i0 = static_cast<int>(rp); const float frac = static_cast<float>(rp - i0);
+ if (i0 >= n) i0 -= n; // a hair-negative rp + n can round up to exactly n
int i1 = i0 + 1; if (i1 >= n) i1 -= n;
return b[i0] + (b[i1] - b[i0]) * frac;
}
@@ -348,7 +370,13 @@ private:
if (!std::isfinite(in)) in = 0.0f;
float rp = w - std::clamp(delay, 1.0f, (float)size - 2.0f);
if (rp < 0) rp += size;
- int i0 = (int)rp; float frac = rp - i0; int i1 = i0 + 1; if (i1 >= size) i1 -= size;
+ int i0 = (int)rp; float frac = rp - i0;
+ // A read position a hair past the write head (w - delay ≈ -1e-5) wraps to
+ // size - 1e-5, which rounds to exactly `size` in float: buf[size] is one past the
+ // end. That stray heap word (often a huge finite float) recirculated as the loud
+ // looped "metallic burst". Keep the index in range.
+ if (i0 >= size) i0 -= size;
+ int i1 = i0 + 1; if (i1 >= size) i1 -= size;
float out = buf[i0] + (buf[i1] - buf[i0]) * frac;
store = out * damp2 + store * damp1;
// Never let a NaN/Inf latch into the recirculating loop (would ring forever, hot).
diff --git a/src/native/nota.engine/src/WavetableSynth.h b/src/native/nota.engine/src/WavetableSynth.h
index bd392d3f..2397f7d0 100644
--- a/src/native/nota.engine/src/WavetableSynth.h
+++ b/src/native/nota.engine/src/WavetableSynth.h
@@ -565,7 +565,7 @@ private:
const int sz = (int)chorusBuf_.size(); if (sz < 4) { outL = l; outR = r; return; }
chorusBuf_[chorusW_] = (l + r) * 0.5f;
const double rate = expMap(get(FxChorusRate), 0.1, 6.0); chorusPh_ += rate / sampleRate_; if (chorusPh_ >= 1.0) chorusPh_ -= 1.0;
- auto tap = [&](double phase) { double d = (0.008 + 0.006 * std::sin(kTwoPi * (phase - std::floor(phase)))) * sampleRate_; double rp = chorusW_ - d; while (rp < 0) rp += sz; int i0 = (int)rp; int i1 = (i0 + 1) % sz; float f = (float)(rp - i0); return chorusBuf_[i0] + (chorusBuf_[i1] - chorusBuf_[i0]) * f; };
+ auto tap = [&](double phase) { double d = (0.008 + 0.006 * std::sin(kTwoPi * (phase - std::floor(phase)))) * sampleRate_; double rp = chorusW_ - d; while (rp < 0) rp += sz; int i0 = (int)rp; float f = (float)(rp - i0); if (i0 >= sz) i0 -= sz; int i1 = (i0 + 1) % sz; return chorusBuf_[i0] + (chorusBuf_[i1] - chorusBuf_[i0]) * f; };
float a = 0.0f, b = 0.0f;
// Taps sit evenly around the LFO cycle; odd ones go left, even ones right.
for (int k = 0; k < voices; ++k) { float t = tap(chorusPh_ + (double)k / voices); if (k % 2 == 0) a += t; else b += t; }
diff --git a/src/native/nota.engine/src/nota_engine_device.cpp b/src/native/nota.engine/src/nota_engine_device.cpp
index 4631bbdf..e990f0ce 100644
--- a/src/native/nota.engine/src/nota_engine_device.cpp
+++ b/src/native/nota.engine/src/nota_engine_device.cpp
@@ -92,6 +92,9 @@ float nota_builtin_device_param_default(const NotaEngine* e, int32_t kind, int32
int32_t nota_device_scope(const NotaEngine* e, int32_t track_id, int32_t device_index, float* out, int32_t max_samples) {
return e ? CENG(e)->deviceScope(track_id, device_index, out, max_samples) : 0;
}
+int32_t nota_engine_reverb_wrap_selftest(NotaEngine* e) {
+ return (e && nota::Reverb::combWrapSelfTest()) ? 1 : 0;
+}
void nota_device_action(NotaEngine* e, int32_t track_id, int32_t device_index, int32_t id, int32_t iarg, float farg) {
if (e) ENG(e)->deviceAction(track_id, device_index, id, iarg, farg);
}
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index 03f03672..21176248 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -4227,6 +4227,7 @@ Console.WriteLine("-- Nota Reverb --");
const int Decay = 0, HFDamp = 1, PreDelay = 2, Size = 3, Algorithm = 10, Freeze = 11, DryWet = 12, Output = 13,
DryLevel = 14, EarlyRefl = 15, ModOnTail = 16, Vintage = 17, BassMono = 18, WetOnly = 19, LatencyComp = 20;
Check(rd >= 0 && re.TrackDeviceBuiltinKind(rt, rd) == 2 && re.DeviceParamCount(rt, rd) == 21, "add built-in Nota Reverb (kind 2, 21 params)");
+ Check(re.ReverbWrapSelfTest(), "Reverb comb read stays inside its delay line at the wrap edge (no metallic burst)");
Check(re.DeviceParamName(rt, rd, Decay) == "Decay" && re.DeviceParamName(rt, rd, Output) == "Output"
&& re.DeviceParamName(rt, rd, DryLevel) == "Dry Level" && re.DeviceParamName(rt, rd, EarlyRefl) == "Early Refl"
&& re.DeviceParamName(rt, rd, ModOnTail) == "Mod on Tail" && re.DeviceParamName(rt, rd, Vintage) == "Vintage"