3 Commits

Author SHA1 Message Date
josh 8775134d4f Harden new generators against non-finite control inputs
Sanitise control-rate reads (finite check + clamp) before they reach
seconds→frames Int conversions or feedback math, so a NaN/inf/huge size,
delay, downsample, bits, decay, shimmer, damp, or feedback can never trap
the Int() conversion nor poison a feedback loop:
- ShimmerReverb: clamp() helper; bound size to maxSizeSeconds before Int.
- ReverseDelay: finite-clamp delay (to maxDelaySeconds) and feedback.
- SampleRateDecimate: clamp downsample to [1, maximumFactor] before Int.
- BitReduce: finite-guard bits before Int(bits.rounded()).

Adds a ShimmerReverb regression test (NaN controls → finite output).
Keeps `import Foundation` in ShimmerReverb (cos for the init-time Hann
table) with a clarifying comment. Suite 256.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 11:14:42 -07:00
josh 7a39a2477e ShimmerReverb: flush denormals in tank feedback; clarify grain-read doc
Review nits: denormal-flush the recirculated tank value (not just the
damping state) so denormals can't persist in the buffer and burn RT CPU;
document that the octave-up grains read the recent wet tank content.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 09:33:24 -07:00
josh a12f58e1d1 chore: gitignore review.diff (transient review artifact)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 09:26:30 -07:00
6 changed files with 54 additions and 12 deletions
+1
View File
@@ -19,3 +19,4 @@ DerivedData/
# Note: Package.resolved is intentionally tracked to pin the Lyrebird dependency. # Note: Package.resolved is intentionally tracked to pin the Lyrebird dependency.
icon-source.png icon-source.png
review.diff
@@ -57,7 +57,10 @@ public final class BitReduce: GeneratorBase, AudioGenerator {
_checkCount(count) _checkCount(count)
guard count > 0 else { return _result } guard count > 0 else { return _result }
let bits: Double = min(max(_bits.floatValue(graph: graph), minimumBits), maximumBits) // Sanitise the control read (finite + clamped) so `Int(bits.rounded())` can't trap on a
// NaN/inf input.
let rawBits: Double = _bits.floatValue(graph: graph)
let bits: Double = rawBits.isFinite ? min(max(rawBits, minimumBits), maximumBits) : minimumBits
// Number of quantisation levels = 2^bits, via an integer shift (avoids importing `pow`). // Number of quantisation levels = 2^bits, via an integer shift (avoids importing `pow`).
// Clamp the shift amount directly too: `1 << bitsInt` is only safe while bits ∈ [1, 16]. // Clamp the shift amount directly too: `1 << bitsInt` is only safe while bits ∈ [1, 16].
let bitsInt: Int = min(max(Int(bits.rounded()), 1), 16) let bitsInt: Int = min(max(Int(bits.rounded()), 1), 16)
@@ -125,11 +125,16 @@ public final class ReverseDelay: GeneratorBase, AudioGenerator {
guard count > 0 else { return _result } guard count > 0 else { return _result }
let sampleRate: Double = graph.engine.sampleRate let sampleRate: Double = graph.engine.sampleRate
let delaySeconds: Double = _delay.floatValue(graph: graph) // Sanitise control reads (finite + clamped): a NaN/inf/huge `delay` would otherwise trap the
// seconds→frames `Int` conversion, and a NaN `feedback` would poison the loop.
let maxDelaySeconds: Double = Double(_maxFrames) / sampleRate
let rawDelay: Double = _delay.floatValue(graph: graph)
let delaySeconds: Double = rawDelay.isFinite ? min(max(rawDelay, 0.0), maxDelaySeconds) : 0.0
let rawFeedback: Double = _feedback.floatValue(graph: graph) let rawFeedback: Double = _feedback.floatValue(graph: graph)
let feedback: Double = min(max(rawFeedback, 0.0), maxFeedback) let feedback: Double = rawFeedback.isFinite ? min(max(rawFeedback, 0.0), maxFeedback) : 0.0
// Target segment length, applied at the next boundary so a read never changes length mid-segment. // Target segment length, applied at the next boundary so a read never changes length mid-segment.
// `delaySeconds` is bounded to `maxDelaySeconds`, so the `Int` conversion cannot overflow.
let targetLen: Int = min(max(Int((delaySeconds * sampleRate).rounded()), 1), _maxFrames) let targetLen: Int = min(max(Int((delaySeconds * sampleRate).rounded()), 1), _maxFrames)
let inputSamples: [Double] = _inputIsGenerator let inputSamples: [Double] = _inputIsGenerator
@@ -41,6 +41,10 @@ public final class SampleRateDecimate: GeneratorBase, AudioGenerator {
/// Smallest decimation factor (pass-through). /// Smallest decimation factor (pass-through).
private let minimumFactor: Int = 1 private let minimumFactor: Int = 1
/// Largest accepted decimation factor — bounds the control read so the `Int` conversion can
/// never overflow on a NaN/inf/huge input.
private let maximumFactor: Double = 1_048_576.0
/// Creates a sample-rate decimator. /// Creates a sample-rate decimator.
/// ///
/// - Parameters: /// - Parameters:
@@ -64,7 +68,12 @@ public final class SampleRateDecimate: GeneratorBase, AudioGenerator {
_checkCount(count) _checkCount(count)
guard count > 0 else { return _result } guard count > 0 else { return _result }
let factor: Int = max(minimumFactor, Int(_downsample.floatValue(graph: graph).rounded())) // Sanitise the control read (finite + clamped) so the `Int` conversion can't overflow.
let raw: Double = _downsample.floatValue(graph: graph)
let safeFactor: Double = raw.isFinite
? min(max(raw, Double(minimumFactor)), maximumFactor)
: Double(minimumFactor)
let factor: Int = Int(safeFactor.rounded())
let inputSamples: [Double] = _inputIsGenerator let inputSamples: [Double] = _inputIsGenerator
? (_input.calculatedSamples(graph: graph, count: count).first ?? sampleRateDecimateZeroBlock) ? (_input.calculatedSamples(graph: graph, count: count).first ?? sampleRateDecimateZeroBlock)
@@ -4,7 +4,7 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound // Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
import Foundation import Foundation // `cos` for the init-time Hann window (not used on the RT path)
import LyrebirdSynth import LyrebirdSynth
/// Shared zero-fill fallback block, allocated once at module load, so the RT path never allocates. /// Shared zero-fill fallback block, allocated once at module load, so the RT path never allocates.
@@ -25,9 +25,10 @@ private let shimmerReverbZeroBlock: [Double] = makeSampleBuffer()
/// feedback = decay·damped + shimmer·pitched → written back into the tank /// feedback = decay·damped + shimmer·pitched → written back into the tank
/// ``` /// ```
/// ///
/// The octave-up is a two-grain, 50%-overlap, Hann-windowed reader running at 2× over the tank /// The octave-up is a two-grain, 50%-overlap, Hann-windowed reader running at 2× over the most
/// buffer (a tape-style pitch raise). A per-sample safety clamp + denormal flush keep the loop /// recent `grain` samples of the tank (the live wet content), a tape-style pitch raise whose
/// bounded even at high `decay` / `shimmer`. /// pitched output recirculates through the feedback. A per-sample safety clamp + denormal flush
/// keep the loop bounded even at high `decay` / `shimmer`.
/// ///
/// `size`, `decay`, `shimmer`, and `damp` are read at control rate (once per block). Output is mono. /// `size`, `decay`, `shimmer`, and `damp` are read at control rate (once per block). Output is mono.
/// ///
@@ -153,12 +154,17 @@ public final class ShimmerReverb: GeneratorBase, AudioGenerator {
guard count > 0 else { return _result } guard count > 0 else { return _result }
let sampleRate: Double = graph.engine.sampleRate let sampleRate: Double = graph.engine.sampleRate
let sizeSeconds: Double = _size.floatValue(graph: graph) // Sanitise control reads (finite + clamped) so a NaN/inf/huge value can never reach the
let decay: Double = min(max(_decay.floatValue(graph: graph), 0.0), maxDecay) // feedback math or trap the seconds→frames `Int` conversion.
let shimmer: Double = min(max(_shimmer.floatValue(graph: graph), 0.0), maxShimmer) let maxSizeSeconds: Double = Double(_maxDelayFrames) / sampleRate
let damp: Double = min(max(_damp.floatValue(graph: graph), 0.0), 1.0) let sizeSeconds: Double = ShimmerReverb.clamp(_size.floatValue(graph: graph), minSizeSeconds, maxSizeSeconds)
let decay: Double = ShimmerReverb.clamp(_decay.floatValue(graph: graph), 0.0, maxDecay)
let shimmer: Double = ShimmerReverb.clamp(_shimmer.floatValue(graph: graph), 0.0, maxShimmer)
let damp: Double = ShimmerReverb.clamp(_damp.floatValue(graph: graph), 0.0, 1.0)
let minFrames: Int = max(1, Int((minSizeSeconds * sampleRate).rounded())) let minFrames: Int = max(1, Int((minSizeSeconds * sampleRate).rounded()))
// `sizeSeconds` is bounded to `maxSizeSeconds`, so `sizeSeconds · sampleRate <= _maxDelayFrames`
// and the `Int` conversion cannot overflow.
let sizeFrames: Int = min(max(Int((sizeSeconds * sampleRate).rounded()), minFrames), _maxDelayFrames) let sizeFrames: Int = min(max(Int((sizeSeconds * sampleRate).rounded()), minFrames), _maxDelayFrames)
let halfGrain: Int = _grainFrames / 2 let halfGrain: Int = _grainFrames / 2
@@ -214,6 +220,8 @@ public final class ShimmerReverb: GeneratorBase, AudioGenerator {
var writeVal: Double = diffused + decay * damped + shimmer * pitched var writeVal: Double = diffused + decay * damped + shimmer * pitched
if writeVal > safetyClamp { writeVal = safetyClamp } if writeVal > safetyClamp { writeVal = safetyClamp }
else if writeVal < -safetyClamp { writeVal = -safetyClamp } else if writeVal < -safetyClamp { writeVal = -safetyClamp }
// Flush denormals so they never recirculate in the tank (RT CPU guard).
if abs(writeVal) < denormalFloor { writeVal = 0.0 }
tank[writePos] = writeVal tank[writePos] = writeVal
out[i] = damped out[i] = damped
@@ -255,6 +263,13 @@ public final class ShimmerReverb: GeneratorBase, AudioGenerator {
return y return y
} }
/// Returns `v` clamped to `[lo, hi]`, or `lo` when `v` is not finite — sanitising control reads
/// before they reach the feedback math or an `Int` frame conversion.
private static func clamp(_ v: Double, _ lo: Double, _ hi: Double) -> Double {
guard v.isFinite else { return lo }
return min(max(v, lo), hi)
}
/// Wraps `index` into `[0, length)` (handles a single negative wrap, as produced by /// Wraps `index` into `[0, length)` (handles a single negative wrap, as produced by
/// `writePos - offset` with `offset <= length`). /// `writePos - offset` with `offset <= length`).
private static func wrap(_ index: Int, _ length: Int) -> Int { private static func wrap(_ index: Int, _ length: Int) -> Int {
@@ -95,6 +95,15 @@ struct ShimmerReverbTests {
#expect(abs(h / l - 2.0) < 0.01, "DC gain should be exactly linear (ratio 2.0)") #expect(abs(h / l - 2.0) < 0.01, "DC gain should be exactly linear (ratio 2.0)")
} }
@Test func nonFiniteControlsProduceFiniteOutput() throws {
// NaN control reads must be sanitised (not trap the seconds→frames conversion nor poison
// the feedback): the output must stay finite.
let samples: [Float] = try render(
oscFreq: 440.0, dc: 0.0, size: Double.nan, decay: Double.nan, shimmer: Double.nan
)
#expect(samples.allSatisfy { $0.isFinite }, "non-finite controls produced NaN/inf output")
}
@Test func decayChangesTheTail() throws { @Test func decayChangesTheTail() throws {
// Small tank so feedback round-trips compound within the reader's window; different decay // Small tank so feedback round-trips compound within the reader's window; different decay
// must change the tail (direction-agnostic — a tuned comb is not monotonic in level). // must change the tail (direction-agnostic — a tuned comb is not monotonic in level).