Address external review: generator tests, class param docs, nits

- Add deterministic generator-level tests: BitReduceTests (level snapping +
  1-bit floor), SampleRateDecimateTests (sample-and-hold groups), and
  ReverseDelayTests (silent-then-flat-replay). Asserts are output-gain
  independent.
- Add class-level `- Parameters:` doc blocks to BitReduce, SampleRateDecimate,
  and ReverseDelay (dual-location param docs).
- BitReduce: clamp the shift amount directly and note shift-safety; clarify
  mid-tread wording.
- ReverseDelay: comment the unreachable baseAddress guard.

Suite 247.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-06-27 21:46:23 -07:00
parent 7ceb93e411
commit 077a8ad9f0
7 changed files with 2849 additions and 2 deletions
@@ -13,7 +13,11 @@ private let bitReduceZeroBlock: [Double] = makeSampleBuffer()
/// quantisation noise of the "bit" half of a lo-fi / bitcrusher effect.
///
/// `bits` is read at control rate (once per block) and clamped to `[1, 16]`. Each sample is
/// rounded to the nearest step of size `2^(1-bits)` over the `[-1, 1]` range. Output is mono.
/// rounded to the nearest of `2^bits` levels over the `[-1, 1]` range (mid-tread). Output is mono.
///
/// - Parameters:
/// - input: Audio-rate signal to quantise.
/// - bits: Bit depth — quantises to `2^bits` levels. Control rate; clamped to `[1, 16]`.
public final class BitReduce: GeneratorBase, AudioGenerator {
/// Resolved input signal.
@@ -55,7 +59,8 @@ public final class BitReduce: GeneratorBase, AudioGenerator {
let bits: Double = min(max(_bits.floatValue(graph: graph), minimumBits), maximumBits)
// Number of quantisation levels = 2^bits, via an integer shift (avoids importing `pow`).
let bitsInt: Int = Int(bits.rounded())
// 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 levels: Double = Double(1 << bitsInt)
// Step between adjacent levels over [-1, 1], and its reciprocal for the round.
let step: Double = 2.0 / levels
@@ -24,6 +24,15 @@ private let reverseDelayZeroBlock: [Double] = makeSampleBuffer()
///
/// - Important: All buffers are pre-allocated at `init` for `maxDelay` seconds — the RT path never
/// allocates or resizes. Keep `delay <= maxDelay`; larger values are clamped.
///
/// - Parameters:
/// - input: Audio-rate signal to reverse.
/// - maxDelay: Maximum segment length in seconds; sizes the pre-allocated buffers.
/// - delay: Segment length in seconds. Control rate; clamped to `[1 frame, maxDelay]`; a change
/// applies at the next segment boundary.
/// - feedback: Reverse-trail feedback factor. Control rate; clamped to `[0, 0.95]`.
/// - sampleRate: Sample rate used to size buffers and convert seconds → frames; match the engine.
/// - fadeTime: Edge-fade length in seconds hiding the segment wrap. Defaults to `0.004`.
public final class ReverseDelay: GeneratorBase, AudioGenerator {
// MARK: - Inputs (classified once at init)
@@ -145,6 +154,8 @@ public final class ReverseDelay: GeneratorBase, AudioGenerator {
_bufferA.withUnsafeMutableBufferPointer { aBuffer in
_bufferB.withUnsafeMutableBufferPointer { bBuffer in
// `baseAddress` is non-nil for these always-non-empty buffers (sized `_maxFrames >= 1`
// at init), so this guard never fires; it satisfies the optional without an RT trap.
guard let aPointer: UnsafeMutablePointer<Double> = aBuffer.baseAddress,
let bPointer: UnsafeMutablePointer<Double> = bBuffer.baseAddress else { return }
_result[0].withUnsafeMutableBufferPointer { outBuffer in
@@ -15,6 +15,11 @@ private let sampleRateDecimateZeroBlock: [Double] = makeSampleBuffer()
///
/// `downsample` is read at control rate (once per block). `1` passes the signal through; `N` holds
/// each sample for `N` output samples (effective rate `sampleRate / N`). Output is mono (channel 0).
///
/// - Parameters:
/// - input: Audio-rate signal to decimate.
/// - downsample: Hold length in samples — effective rate is `sampleRate / downsample`. Control
/// rate; clamped to `>= 1` (`1` is transparent).
public final class SampleRateDecimate: GeneratorBase, AudioGenerator {
/// Resolved input signal.
@@ -0,0 +1,67 @@
// BitReduceTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
@MainActor
@Suite("BitReduce")
struct BitReduceTests {
/// Minimal synth: a constant DC value through a `BitReduce`, written to a mono bus.
private final class CrushSynth: SynthesizerBase {
private let value: Double
private let bits: Double
private let outBus: Int
init(value: Double, bits: Double, outBus: Int) {
self.value = value
self.bits = bits
self.outBus = outBus
super.init()
}
override func build() {
output(bus: outBus, source: BitReduce(input: value, bits: bits))
}
}
private func render(value: Double, bits: Double) throws -> [Float] {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05)
defer { try? FileManager.default.removeItem(at: url) }
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer { engine.busAllocator.releaseAudioBus(dstBus) }
let synth: CrushSynth = CrushSynth(value: value, bits: bits, outBus: dstBus.index)
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(synth)
try engine.add(master, position: NodePosition.after(synth))
try engine.start()
return readStereoCAF(url: url)
}
// Asserts are scale-independent: the test harness applies a fixed output gain/pan, so compare
// quantisation *levels* rather than absolute amplitudes.
@Test func snapsToDiscreteLevels() throws {
// 8 bits over [-1, 1]: step = 2/256, inverseStep = 128.
// 0.896 → round(114.688) = 115; 0.901 → round(115.328) = 115 (same level);
// 0.910 → round(116.48) = 116 (different level).
let sameA: [Float] = try render(value: 0.896, bits: 8.0)
let sameB: [Float] = try render(value: 0.901, bits: 8.0)
let other: [Float] = try render(value: 0.910, bits: 8.0)
#expect(sameA[200] == sameB[200], "values in the same 8-bit level should quantise identically")
#expect(sameA[200] != other[200], "values in different 8-bit levels should differ")
}
@Test func oneBitFloorsSmallValuesToZero() throws {
// 1 bit: levels = 2, step = 1.0; round(0.4) = 0 → exactly zero regardless of output gain.
let samples: [Float] = try render(value: 0.4, bits: 1.0)
#expect(abs(samples[200]) < 1e-5, "1-bit quantiser should floor 0.4 to 0")
}
}
@@ -0,0 +1,74 @@
// ReverseDelayTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
@MainActor
@Suite("ReverseDelay")
struct ReverseDelayTests {
/// Minimal synth: a DC value through a `ReverseDelay`, written to a mono bus.
private final class ReverseSynth: SynthesizerBase {
private let value: Double
private let delay: Double
private let outBus: Int
init(value: Double, delay: Double, outBus: Int) {
self.value = value
self.delay = delay
self.outBus = outBus
super.init()
}
override func build() {
output(bus: outBus, source: ReverseDelay(
input: value,
maxDelay: 0.1,
delay: delay,
feedback: 0.0,
sampleRate: 44100.0
))
}
}
private func render(value: Double, delay: Double) throws -> [Float] {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, sampleRate: 44100.0)
defer { try? FileManager.default.removeItem(at: url) }
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer { engine.busAllocator.releaseAudioBus(dstBus) }
let synth: ReverseSynth = ReverseSynth(value: value, delay: delay, outBus: dstBus.index)
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(synth)
try engine.add(master, position: NodePosition.after(synth))
try engine.start()
return readStereoCAF(url: url, sampleRate: 44100.0)
}
private func left(_ samples: [Float], _ frame: Int) -> Float {
samples[frame * 2]
}
@Test func firstSegmentIsSilentThenReplaysRecordedValue() throws {
// delay 0.02 s @ 44100 = 882-frame segments. Segment 1 [0, 882) plays the still-empty
// buffer (silence); segment 2 [882, 1764) reverses the recorded DC. Asserts are
// scale-independent (the harness applies a fixed output gain/pan): check silence vs.
// non-silent, and that the replayed DC is flat (reverse of a constant is the same constant).
let samples: [Float] = try render(value: 0.5, delay: 0.02)
// Mid segment 1: still recording, play buffer empty → silent.
#expect(abs(left(samples, 441)) < 1e-3, "first segment should be silent (nothing recorded yet)")
// Segment 2, clear of the edge fades → non-silent and constant (reversed DC).
let a: Float = left(samples, 1200)
let b: Float = left(samples, 1400)
#expect(abs(a) > 1e-2, "second segment should replay the recorded value (non-silent)")
#expect(abs(a - b) < 1e-3, "reversed DC should be flat across the segment")
}
}
@@ -0,0 +1,70 @@
// SampleRateDecimateTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
@MainActor
@Suite("SampleRateDecimate")
struct SampleRateDecimateTests {
/// Minimal synth: a sine through a `SampleRateDecimate`, written to a mono bus.
private final class DecimateSynth: SynthesizerBase {
private let freq: Double
private let factor: Double
private let outBus: Int
init(freq: Double, factor: Double, outBus: Int) {
self.freq = freq
self.factor = factor
self.outBus = outBus
super.init()
}
override func build() {
let osc: OscSin.Audio = OscSin.Audio(freq: freq)
output(bus: outBus, source: SampleRateDecimate(input: osc, downsample: factor))
}
}
private func render(freq: Double, factor: Double) throws -> [Float] {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05)
defer { try? FileManager.default.removeItem(at: url) }
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer { engine.busAllocator.releaseAudioBus(dstBus) }
let synth: DecimateSynth = DecimateSynth(freq: freq, factor: factor, outBus: dstBus.index)
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(synth)
try engine.add(master, position: NodePosition.after(synth))
try engine.start()
return readStereoCAF(url: url)
}
/// Left-channel frame `i` (interleaved stereo).
private func left(_ samples: [Float], _ frame: Int) -> Float {
samples[frame * 2]
}
@Test func holdsEachSampleForTheFactor() throws {
// Factor 4: frames latch at 0, 4, 8, … and hold for four output samples each.
let samples: [Float] = try render(freq: 2000.0, factor: 4.0)
// Group [8, 11] holds the value latched at frame 8 (a non-zero point on the sine).
#expect(left(samples, 8) == left(samples, 9))
#expect(left(samples, 8) == left(samples, 10))
#expect(left(samples, 8) == left(samples, 11))
// The next group latches a fresh value.
#expect(left(samples, 8) != left(samples, 12), "decimator did not re-latch at the group boundary")
}
@Test func factorOneIsTransparent() throws {
let samples: [Float] = try render(freq: 2000.0, factor: 1.0)
// No two adjacent samples forced equal — a moving sine should differ frame-to-frame.
#expect(left(samples, 8) != left(samples, 9), "factor 1 should pass the signal through unheld")
}
}
+2615
View File
File diff suppressed because it is too large Load Diff