// 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") } }