diff --git a/Sources/LyrebirdShoeGaze/Generators/BitReduce.swift b/Sources/LyrebirdShoeGaze/Generators/BitReduce.swift new file mode 100644 index 0000000..611108a --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Generators/BitReduce.swift @@ -0,0 +1,79 @@ +// 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 step of size `2^(1-bits)` over the `[-1, 1]` range. Output is mono. +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 } + + 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()) + 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..= 1`; `1` is transparent. + public init( + input: any ValidGeneratorInput, + downsample: any ValidGeneratorInput + ) { + let resolvedInput: any ValidGeneratorInput = input._resolvedInput() + _input = resolvedInput + _inputIsGenerator = resolvedInput is any Generator + _downsample = downsample._resolvedInput() + super.init() + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + guard count > 0 else { return _result } + + let factor: Int = max(minimumFactor, Int(_downsample.floatValue(graph: graph).rounded())) + + let inputSamples: [Double] = _inputIsGenerator + ? (_input.calculatedSamples(graph: graph, count: count).first ?? sampleRateDecimateZeroBlock) + : sampleRateDecimateZeroBlock + let inputCount: Int = inputSamples.count + let inputScalar: Double = _inputIsGenerator ? 0.0 : _input.floatValue(graph: graph) + + var countdown: Int = _countdown + var held: Double = _held + + for i: Int in 0.. = 1.0 ... 50.0 + private let bitsRange: ClosedRange = 1.0 ... 16.0 + private let toneRange: ClosedRange = 800.0 ... 8000.0 + + // MARK: - Knobs + + public override var effectKnobs: [PedalKnob] { + [ + PedalKnob(label: "Crush", node: $crush, range: crushRange), + PedalKnob(label: "Bits", node: $bits, range: bitsRange), + PedalKnob(label: "Tone", node: $tone, range: toneRange), + ] + } + + // MARK: - Init + + /// Creates a bitcrusher pedal. + /// + /// - Parameters: + /// - inputBus: Audio bus index to read the dry input from. Defaults to `0`. + /// - outputBus: Audio bus index to write the processed output to. Defaults to `0`. + public init( + inputBus: Int = 0, + outputBus: Int = 0 + ) { + super.init( + name: "Bitcrusher", + inputBus: inputBus, + outputBus: outputBus, + initialMix: BitcrusherPedal.defaultMix + ) + } + + // MARK: - Effect + + public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { + let decimated: SampleRateDecimate = SampleRateDecimate(input: dry, downsample: $crush) + let crushed: BitReduce = BitReduce(input: decimated, bits: $bits) + return RBJLowPass.Audio(input: crushed, freq: $tone, q: filterQ) + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift b/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift index b75e722..1c2b4a3 100644 --- a/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift +++ b/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift @@ -59,6 +59,7 @@ public enum PedalRegistry { "Sustainer": { SustainerPedal() }, "Ring Modulator": { RingModulatorPedal() }, "Diffuser": { DiffuserPedal() }, + "Bitcrusher": { BitcrusherPedal() }, ] /// Returns a new `Pedal` instance for the given type string, or `nil` if the type diff --git a/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift b/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift index 9a729b9..e3b50eb 100644 --- a/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift +++ b/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift @@ -53,8 +53,8 @@ public struct PedalPaletteView: View { private static let preferredOrder: [String] = [ "Overdrive", "Distortion", "Compressor", "Sustainer", "Limiter", "Noise Gate", "Fuzz", "Graphic EQ", "Tremolo", "Phaser", "Modulation", "Chorus", "Flanger", "Vibrato", "Rotary", - "Auto-Wah", "Mutant", "Ring Modulator", "Diffuser", "Bass Octaver", "Octave Splitter", - "Harmonizer", + "Auto-Wah", "Mutant", "Ring Modulator", "Diffuser", "Bitcrusher", "Bass Octaver", + "Octave Splitter", "Harmonizer", "Delay", "Feedback Delay", "Multi-Tap Delay", "Ping-Pong", "Reverse Delay", "Reverb", ] diff --git a/Sources/LyrebirdShoeGazeUI/PedalView.swift b/Sources/LyrebirdShoeGazeUI/PedalView.swift index 1ada91a..02cda08 100644 --- a/Sources/LyrebirdShoeGazeUI/PedalView.swift +++ b/Sources/LyrebirdShoeGazeUI/PedalView.swift @@ -41,6 +41,7 @@ private func enclosureColor(for displayName: String) -> Color { case "Ring Modulator": return Color(red: 0.64, green: 0.30, blue: 0.10) // burnt amber case "Diffuser": return Color(red: 0.34, green: 0.30, blue: 0.62) // periwinkle case "Harmonizer": return Color(red: 0.52, green: 0.20, blue: 0.40) // wine / mauve + case "Bitcrusher": return Color(red: 0.30, green: 0.34, blue: 0.40) // slate / digital gray default: return Color(red: 0.36, green: 0.36, blue: 0.38) // steel gray } } diff --git a/Tests/LyrebirdShoeGazeTests/BitcrusherPedalTests.swift b/Tests/LyrebirdShoeGazeTests/BitcrusherPedalTests.swift new file mode 100644 index 0000000..e9cd2ba --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/BitcrusherPedalTests.swift @@ -0,0 +1,85 @@ +// BitcrusherPedalTests.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("BitcrusherPedal") +struct BitcrusherPedalTests { + + private func render( + configure: (BitcrusherPedal) -> Void + ) throws -> [Float] { + let renderDuration: Double = 0.2 + let numAudioBuses: Int = 64 + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine( + duration: renderDuration, + numAudioBuses: numAudioBuses + ) + defer { try? FileManager.default.removeItem(at: url) } + + let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) + let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) + defer { + engine.busAllocator.releaseAudioBus(srcBus) + engine.busAllocator.releaseAudioBus(dstBus) + } + + let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index) + let pedal: BitcrusherPedal = BitcrusherPedal(inputBus: srcBus.index, outputBus: dstBus.index) + configure(pedal) + let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index) + + try engine.add(source) + try engine.add(pedal, position: NodePosition.after(source)) + try engine.add(master, position: NodePosition.after(pedal)) + try engine.start() + + return readStereoCAF(url: url) + } + + private func totalSSD(_ a: [Float], _ b: [Float]) -> Double { + zip(a, b).reduce(0.0) { acc, pair in + let diff: Double = Double(pair.0 - pair.1) + return acc + diff * diff + } + } + + @Test func buildsAndProducesNonSilentOutput() throws { + let samples: [Float] = try render { _ in } + #expect(!samples.isEmpty) + #expect(hasNonSilentOutput(samples), "bitcrusher output was silent") + } + + @Test func crushChangesOutput() throws { + let light: [Float] = try render { pedal in pedal.crush = 1.0; pedal.bits = 16.0; pedal.tone = 8000.0; pedal.mix = 1.0 } + let heavy: [Float] = try render { pedal in pedal.crush = 32.0; pedal.bits = 16.0; pedal.tone = 8000.0; pedal.mix = 1.0 } + #expect(hasNonSilentOutput(heavy), "decimated bitcrusher was silent") + #expect(totalSSD(light, heavy) > 0, "changing crush did not change the output") + } + + @Test func bitsChangeOutput() throws { + let clean: [Float] = try render { pedal in pedal.crush = 1.0; pedal.bits = 16.0; pedal.tone = 8000.0; pedal.mix = 1.0 } + let crushed: [Float] = try render { pedal in pedal.crush = 1.0; pedal.bits = 3.0; pedal.tone = 8000.0; pedal.mix = 1.0 } + #expect(hasNonSilentOutput(crushed), "bit-reduced output was silent") + #expect(totalSSD(clean, crushed) > 0, "changing bit depth did not change the output") + } + + @Test func exposesCrushBitsToneKnobs() throws { + let pedal: BitcrusherPedal = BitcrusherPedal() + let labels: [String] = pedal.effectKnobs.map { $0.label } + #expect(labels == ["Crush", "Bits", "Tone"]) + } + + @Test func registeredInBuiltInRegistry() throws { + let pedal: Pedal? = PedalRegistry.makePedal(type: "Bitcrusher") + #expect(pedal is BitcrusherPedal) + } +}