Add Bitcrusher pedal with SampleRateDecimate and BitReduce generators
Two new RT-safe generators (ShoeGaze): SampleRateDecimate (sample-and-hold decimator, control-rate downsample factor) and BitReduce (quantise to 2^bits levels via integer shift, control-rate bit depth). BitcrusherPedal chains decimate → bit-reduce → tone low-pass (Crush/Bits/Tone). Registered with enclosure color + palette slot. Tests: build/non-silent, crush-changes-output, bits-change-output, knobs, registry. Suite 242. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -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..<count {
|
||||
let x: Double = _inputIsGenerator
|
||||
? (i < inputCount ? inputSamples[i] : 0.0)
|
||||
: inputScalar
|
||||
_result[0][i] = (x * inverseStep).rounded() * step
|
||||
}
|
||||
|
||||
return _result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
// SampleRateDecimate.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 sampleRateDecimateZeroBlock: [Double] = makeSampleBuffer()
|
||||
|
||||
/// Sample-rate reducer (decimator): a sample-and-hold that latches a new input value only once
|
||||
/// every `downsample` samples, holding it in between. The aliased, stair-stepped result is the
|
||||
/// "crushed sample rate" half of a lo-fi / bitcrusher effect.
|
||||
///
|
||||
/// `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).
|
||||
public final class SampleRateDecimate: 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
|
||||
|
||||
/// Downsample factor, read at block rate. Pass a control-rate node or scalar.
|
||||
let _downsample: any ValidGeneratorInput
|
||||
|
||||
/// Samples remaining before the next latch. `0` latches a fresh input on the current sample.
|
||||
var _countdown: Int = 0
|
||||
|
||||
/// Currently held output value.
|
||||
var _held: Double = 0.0
|
||||
|
||||
/// Smallest decimation factor (pass-through).
|
||||
private let minimumFactor: Int = 1
|
||||
|
||||
/// Creates a sample-rate decimator.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to decimate.
|
||||
/// - downsample: Hold length in samples (control rate). Clamped to `>= 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..<count {
|
||||
let x: Double = _inputIsGenerator
|
||||
? (i < inputCount ? inputSamples[i] : 0.0)
|
||||
: inputScalar
|
||||
if countdown <= 0 {
|
||||
held = x
|
||||
countdown = factor
|
||||
}
|
||||
countdown -= 1
|
||||
_result[0][i] = held
|
||||
}
|
||||
|
||||
_countdown = countdown
|
||||
_held = held
|
||||
return _result
|
||||
}
|
||||
}
|
||||
@@ -66,6 +66,7 @@ public extension PedalType {
|
||||
static let rotary = PedalType("Rotary")
|
||||
static let ringModulator = PedalType("Ring Modulator")
|
||||
static let diffuser = PedalType("Diffuser")
|
||||
static let bitcrusher = PedalType("Bitcrusher")
|
||||
|
||||
// Dynamics (additional)
|
||||
static let sustainer = PedalType("Sustainer")
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
// BitcrusherPedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Lo-fi bitcrusher: sample-rate decimation followed by bit-depth reduction.
|
||||
///
|
||||
/// A sample-and-hold drops the effective sample rate (aliasing, stair-stepping); a quantiser then
|
||||
/// reduces the bit depth (gritty quantisation noise). A post `Tone` low-pass tames the harsh
|
||||
/// aliasing for a more usable lo-fi voice. Wraps the ``SampleRateDecimate`` and ``BitReduce``
|
||||
/// generators, run fully wet so the pedal's `Mix` knob sets the blend.
|
||||
///
|
||||
/// ## Knobs
|
||||
/// - `crush`: Sample-rate decimation factor (hold length in samples). Range `[1, 50]`.
|
||||
/// - `bits`: Bit depth. Range `[1, 16]`.
|
||||
/// - `tone`: Post low-pass cutoff in Hz. Range `[800, 8000]`.
|
||||
public final class BitcrusherPedal: Pedal {
|
||||
|
||||
/// One-line description shown in the picker and info panel.
|
||||
public override var summary: String {
|
||||
"Lo-fi crusher: drops the sample rate and bit depth for gritty digital grunge."
|
||||
}
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Sample-rate decimation factor (hold length in samples). Range [1, 50].
|
||||
@UIParam public var crush: Double = 8.0
|
||||
|
||||
/// Bit depth. Range [1, 16].
|
||||
@UIParam public var bits: Double = 8.0
|
||||
|
||||
/// Post low-pass cutoff in Hz. Range [800, 8000].
|
||||
@UIParam public var tone: Double = 4000.0
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Bitcrusher is heard fully wet; the `Mix` knob can dial it back.
|
||||
private static let defaultMix: Double = 1.0
|
||||
|
||||
/// Butterworth Q (no resonant peak) for the tone low-pass.
|
||||
private let filterQ: Double = 0.707
|
||||
|
||||
// MARK: - Ranges
|
||||
|
||||
private let crushRange: ClosedRange<Double> = 1.0 ... 50.0
|
||||
private let bitsRange: ClosedRange<Double> = 1.0 ... 16.0
|
||||
private let toneRange: ClosedRange<Double> = 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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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",
|
||||
]
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user