// BitReduce.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import LyrebirdSynth /// Shared zero-fill fallback block, allocated once at module load, so the RT path never allocates. private let bitReduceZeroBlock: [Double] = makeSampleBuffer() /// Bit-depth reducer: quantises the signal to `2^bits` amplitude levels, producing the gritty /// 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 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. let _input: any ValidGeneratorInput /// `true` when `_input` resolved to a generator; classified once so the RT path runs no /// `is`/`as?` check. let _inputIsGenerator: Bool /// Quantisation bit depth, read at block rate. Pass a control-rate node or scalar. let _bits: any ValidGeneratorInput /// Quantisation bounds. private let minimumBits: Double = 1.0 private let maximumBits: Double = 16.0 /// Creates a bit-depth reducer. /// /// - Parameters: /// - input: Signal to quantise. /// - bits: Bit depth (control rate). Clamped to `[1, 16]`. public init( input: any ValidGeneratorInput, bits: any ValidGeneratorInput ) { let resolvedInput: any ValidGeneratorInput = input._resolvedInput() _input = resolvedInput _inputIsGenerator = resolvedInput is any Generator _bits = bits._resolvedInput() super.init() } public func _computeSamples( graph: SynthGraph, count: Int ) -> [[Double]] { _checkCount(count) guard count > 0 else { return _result } // 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`). // 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 let inverseStep: Double = levels / 2.0 let inputSamples: [Double] = _inputIsGenerator ? (_input.calculatedSamples(graph: graph, count: count).first ?? bitReduceZeroBlock) : bitReduceZeroBlock let inputCount: Int = inputSamples.count let inputScalar: Double = _inputIsGenerator ? 0.0 : _input.floatValue(graph: graph) for i: Int in 0..