Merge bass-octaver-pedal: Boss OC-2 style bass octaver
This commit is contained in:
@@ -0,0 +1,141 @@
|
||||
// SubOctaveDivider.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Shared zero-fill fallback block, allocated once at module load. Returned when an upstream
|
||||
/// input yields no channel for a `_computeSamples` call, so the RT path never allocates.
|
||||
private let subOctaveDividerZeroBlock: [Double] = makeSampleBuffer()
|
||||
|
||||
/// Analog-style sub-octave generator: a hysteresis comparator feeding a T flip-flop chain.
|
||||
///
|
||||
/// This is the core of the classic Boss OC-2 octave-down algorithm. The input is treated
|
||||
/// as a square wave by a Schmitt-trigger comparator around zero; each rising edge clocks a
|
||||
/// toggle flip-flop. Toggling on every rising edge halves the frequency (`divisor: 2`,
|
||||
/// one octave down); toggling on every *second* rising edge quarters it (`divisor: 4`, two
|
||||
/// octaves down). The output is a hard `±1` square wave at `inputFrequency / divisor`.
|
||||
///
|
||||
/// The comparator runs in the time domain, so unlike an FFT pitch tracker it follows low
|
||||
/// bass fundamentals (sub-100 Hz) with no detection floor. It is strictly monophonic — fed
|
||||
/// a chord it tracks the dominant zero-crossing rate and glitches, exactly as the original
|
||||
/// analog divider does.
|
||||
///
|
||||
/// Feed it a band-limited, hard-limited signal (low-pass to isolate the fundamental, then a
|
||||
/// `tanh` limiter to square it up) for clean triggering; the raw guitar signal's upper
|
||||
/// harmonics cause double-triggering an octave too high.
|
||||
///
|
||||
/// Output is mono: only channel 0 of the input is read (a stereo input is mono-summed to its
|
||||
/// first channel before division).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to divide. Should be pre-conditioned to a near-square `±1` waveform.
|
||||
/// - divisor: Division ratio. `2` = one octave down, `4` = two octaves down. Even values
|
||||
/// only; `init` traps on `divisor < 2`, and odd values truncate toward the next lower
|
||||
/// even ratio (`divisor / 2` rising-edge count).
|
||||
public final class SubOctaveDivider: GeneratorBase, AudioGenerator {
|
||||
|
||||
/// Resolved input signal (classified once at `init`, never on the RT thread).
|
||||
let _input: any ValidGeneratorInput
|
||||
|
||||
/// `true` when `_input` resolved to an `any Generator`; `false` for a scalar constant.
|
||||
/// Classified once at `init` so the RT path never runs an `is`/`as?` type check and never
|
||||
/// hits `Double.calculatedSamples`, which would allocate every block.
|
||||
let _inputIsGenerator: Bool
|
||||
|
||||
/// Number of rising input edges between output toggles: `divisor / 2`. A divide-by-2
|
||||
/// square toggles every rising edge; divide-by-4 toggles every second rising edge.
|
||||
let _toggleEvery: Int
|
||||
|
||||
/// Comparator state: `true` once the input has risen above `compHigh`, `false` once it
|
||||
/// has fallen below `compLow`. The hysteresis band rejects zero-region noise.
|
||||
var _high: Bool = false
|
||||
|
||||
/// Rising edges seen since the last output toggle.
|
||||
var _edgeCount: Int = 0
|
||||
|
||||
/// Current square-wave output level, toggled between `+1` and `-1`.
|
||||
var _outState: Double = 1.0
|
||||
|
||||
/// Comparator switch-on threshold. Input must exceed this (from below) to register a
|
||||
/// rising edge. Small positive value rejects noise around zero for a limited input.
|
||||
private let compHigh: Double = 0.1
|
||||
|
||||
/// Comparator switch-off threshold. Input must fall below this to re-arm the rising-edge
|
||||
/// detector. The `compHigh` / `compLow` gap is the hysteresis band.
|
||||
private let compLow: Double = -0.1
|
||||
|
||||
/// Smallest accepted division ratio (one octave down).
|
||||
private static let minimumDivisor: Int = 2
|
||||
|
||||
/// Creates a sub-octave divider.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to divide. Should be pre-conditioned to a near-square `±1` waveform.
|
||||
/// - divisor: Division ratio. `2` = one octave down, `4` = two octaves down. Even values
|
||||
/// only; traps on `divisor < 2`, and odd values truncate toward the next lower even ratio.
|
||||
public init(
|
||||
input: any ValidGeneratorInput,
|
||||
divisor: Int
|
||||
) {
|
||||
precondition(divisor >= SubOctaveDivider.minimumDivisor,
|
||||
"SubOctaveDivider: divisor must be >= 2; got \(divisor).")
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
_input = resolvedInput
|
||||
_inputIsGenerator = resolvedInput is any Generator
|
||||
_toggleEvery = divisor / 2
|
||||
super.init()
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
var high: Bool = _high
|
||||
var edgeCount: Int = _edgeCount
|
||||
var outState: Double = _outState
|
||||
|
||||
// A scalar (constant) input never crosses the comparator thresholds, so no edges fire
|
||||
// and the output holds its current level. Skip the input pull entirely — this also
|
||||
// avoids `Double.calculatedSamples`, which would allocate on the RT thread.
|
||||
guard _inputIsGenerator else {
|
||||
for i: Int in 0..<count {
|
||||
_result[0][i] = outState
|
||||
}
|
||||
_high = high
|
||||
_edgeCount = edgeCount
|
||||
_outState = outState
|
||||
return _result
|
||||
}
|
||||
|
||||
let inputSamples: [Double] = _input.calculatedSamples(
|
||||
graph: graph, count: count).first ?? subOctaveDividerZeroBlock
|
||||
let inputCount: Int = inputSamples.count
|
||||
|
||||
for i: Int in 0..<count {
|
||||
// Bounds-safe read: a short upstream block falls back to silence past its end.
|
||||
let x: Double = i < inputCount ? inputSamples[i] : 0.0
|
||||
if !high && x > compHigh {
|
||||
// Rising edge: clock the flip-flop.
|
||||
high = true
|
||||
edgeCount += 1
|
||||
if edgeCount >= _toggleEvery {
|
||||
edgeCount = 0
|
||||
outState = -outState
|
||||
}
|
||||
} else if high && x < compLow {
|
||||
high = false
|
||||
}
|
||||
_result[0][i] = outState
|
||||
}
|
||||
|
||||
_high = high
|
||||
_edgeCount = edgeCount
|
||||
_outState = outState
|
||||
return _result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
// BassOctaverPedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Monophonic bass octaver modeled on the Boss OC-2 Octave.
|
||||
///
|
||||
/// Adds one and two sub-octaves below the input, mixed against the direct signal — the
|
||||
/// three-knob OC-2 panel layout (OCT1 = −1 octave, OCT2 = −2 octaves, Direct = dry level).
|
||||
///
|
||||
/// Two algorithms share the knobs, picked by the `mode` switch:
|
||||
///
|
||||
/// - **Flip-flop** (default): the authentic OC-2 path. The input is low-passed to isolate
|
||||
/// the fundamental, hard-limited into a square wave, then clocked through a ``SubOctaveDivider``
|
||||
/// T flip-flop chain to produce `±1` square sub-octaves an octave and two octaves down. Those
|
||||
/// squares are amplitude-followed off the dry signal so they track its dynamics, then
|
||||
/// low-passed to tame the square edges. Strictly monophonic; glitches on chords like the
|
||||
/// original. Tracks low bass fundamentals (sub-100 Hz) cleanly because the divider works in
|
||||
/// the time domain.
|
||||
/// - **Tracking**: an FFT pitch tracker (`FreqTracker`) drives square oscillators at half and
|
||||
/// quarter the detected frequency. Cleaner and glitch-free, but limited by the tracker's
|
||||
/// ~90 Hz detection floor — best for notes above the low bass register. Flip-flop is the
|
||||
/// bass mode.
|
||||
///
|
||||
/// ## Knobs
|
||||
/// - `oct1`: −1 octave voice level in `[0, 1]`.
|
||||
/// - `oct2`: −2 octave voice level in `[0, 1]`.
|
||||
/// - `direct`: Dry signal level in `[0, 1]`.
|
||||
///
|
||||
/// ## Switches
|
||||
/// - `mode` (two-state): `0` = Flip-flop (authentic OC-2), `1` = Tracking (pitch-tracked).
|
||||
public final class BassOctaverPedal: Pedal {
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// −1 octave voice level in `[0, 1]`.
|
||||
@UIParam public var oct1: Double = 0.7
|
||||
|
||||
/// −2 octave voice level in `[0, 1]`.
|
||||
@UIParam public var oct2: Double = 0.0
|
||||
|
||||
/// Dry (direct) signal level in `[0, 1]`.
|
||||
@UIParam public var direct: Double = 1.0
|
||||
|
||||
/// Algorithm selector. `0` = Flip-flop (authentic OC-2), `1` = Tracking. Driven by a two-state switch.
|
||||
@UIParam public var mode: Double = 0.0
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Pedal blends everything internally via the level knobs, so the base wet/dry stays fully wet.
|
||||
private static let defaultMix: Double = 1.0
|
||||
|
||||
/// DC-removal high-pass cutoff in Hz, applied before the divider's comparator.
|
||||
private let dcBlockFreq: Double = 30.0
|
||||
|
||||
/// Pre-divider low-pass cutoff in Hz. Isolates the fundamental so upper harmonics do not
|
||||
/// double-trigger the comparator an octave too high.
|
||||
private let conditionCutoff: Double = 500.0
|
||||
|
||||
/// Pre-gain into the `tanh` limiter. Large enough to square the conditioned signal to `±1`
|
||||
/// so the comparator sees clean edges regardless of input level.
|
||||
private let limiterDrive: Double = 50.0
|
||||
|
||||
/// Low-pass cutoff in Hz applied to each square sub-octave to soften its harsh edges.
|
||||
private let subToneCutoff: Double = 800.0
|
||||
|
||||
/// Butterworth Q (no resonant peak) for all conditioning filters.
|
||||
private let filterQ: Double = 0.707
|
||||
|
||||
/// Envelope-follower attack/release times in seconds; the sub-octaves track the dry dynamics.
|
||||
private let envAttack: Double = 0.005
|
||||
private let envRelease: Double = 0.1
|
||||
|
||||
/// Frequency multipliers for the tracking-mode oscillators (one and two octaves down).
|
||||
private let octave1Ratio: Double = 0.5
|
||||
private let octave2Ratio: Double = 0.25
|
||||
|
||||
/// Pitch-tracker detection bounds in Hz for tracking mode.
|
||||
private let trackMinFreq: Double = 60.0
|
||||
private let trackMaxFreq: Double = 1000.0
|
||||
|
||||
/// Division ratios for the flip-flop divider.
|
||||
private let divisorOctave1: Int = 2
|
||||
private let divisorOctave2: Int = 4
|
||||
|
||||
/// Half-step bias added before `Select`'s truncate-toward-zero index, turning the `mode`
|
||||
/// switch into a round-to-nearest position selector.
|
||||
private let selectRoundingBias: Double = 0.5
|
||||
|
||||
/// Switch position values.
|
||||
private let modeFlipFlopValue: Double = 0.0
|
||||
private let modeTrackingValue: Double = 1.0
|
||||
|
||||
// MARK: - Ranges
|
||||
|
||||
private let levelRange: ClosedRange<Double> = 0.0 ... 1.0
|
||||
|
||||
// MARK: - Knobs
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "OCT 1", node: $oct1, range: levelRange),
|
||||
PedalKnob(label: "OCT 2", node: $oct2, range: levelRange),
|
||||
PedalKnob(label: "Direct", node: $direct, range: levelRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Switches
|
||||
|
||||
public override var effectSwitches: [PedalSwitch] {
|
||||
[
|
||||
PedalSwitch(
|
||||
label: "Mode",
|
||||
node: $mode,
|
||||
options: [
|
||||
PedalSwitch.Option(title: "Flip", value: modeFlipFlopValue),
|
||||
PedalSwitch.Option(title: "Track", value: modeTrackingValue),
|
||||
]
|
||||
)
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a bass octaver pedal.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
|
||||
/// - outputBus: Audio bus index to write the output to. Defaults to `0`.
|
||||
public init(
|
||||
inputBus: Int = 0,
|
||||
outputBus: Int = 0
|
||||
) {
|
||||
super.init(
|
||||
name: "Bass Octaver",
|
||||
inputBus: inputBus,
|
||||
outputBus: outputBus,
|
||||
initialMix: BassOctaverPedal.defaultMix
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
// Sub-octaves track the dry signal's amplitude envelope.
|
||||
let env: AmplitudeFollower.Audio = AmplitudeFollower.Audio(
|
||||
in: dry,
|
||||
attackTime: envAttack,
|
||||
releaseTime: envRelease
|
||||
)
|
||||
|
||||
// Flip-flop branch: condition → limit → divide.
|
||||
let (oct1Flip, oct2Flip): (any ValidGeneratorInput, any ValidGeneratorInput) =
|
||||
flipFlopVoices(dry: dry, env: env)
|
||||
|
||||
// Tracking branch: pitch-track → square oscillators.
|
||||
let (oct1Track, oct2Track): (any ValidGeneratorInput, any ValidGeneratorInput) =
|
||||
trackingVoices(dry: dry, env: env)
|
||||
|
||||
// Per-voice mode select. `Select` advances both branches each block (warm state).
|
||||
let modeWhich: any ValidGeneratorInput = $mode + selectRoundingBias
|
||||
let oct1Voice: Select.Audio = Select.Audio(
|
||||
which: modeWhich,
|
||||
inputs: [oct1Flip, oct1Track]
|
||||
)
|
||||
let oct2Voice: Select.Audio = Select.Audio(
|
||||
which: modeWhich,
|
||||
inputs: [oct2Flip, oct2Track]
|
||||
)
|
||||
|
||||
// OC-2 mixer: direct + OCT1 + OCT2, each scaled by its level knob.
|
||||
let directVoice: any ValidGeneratorInput = dry * $direct
|
||||
let sub1: any ValidGeneratorInput = oct1Voice * $oct1
|
||||
let sub2: any ValidGeneratorInput = oct2Voice * $oct2
|
||||
return directVoice + sub1 + sub2
|
||||
}
|
||||
|
||||
/// Builds the authentic flip-flop sub-octave voices: condition the input to a square,
|
||||
/// clock the divider chain, amplitude-follow, then soften the square edges.
|
||||
private func flipFlopVoices(
|
||||
dry: any ValidGeneratorInput,
|
||||
env: AmplitudeFollower.Audio
|
||||
) -> (any ValidGeneratorInput, any ValidGeneratorInput) {
|
||||
let dcBlocked: RBJHighPass.Audio = RBJHighPass.Audio(
|
||||
input: dry,
|
||||
freq: dcBlockFreq,
|
||||
q: filterQ
|
||||
)
|
||||
let conditioned: RBJLowPass.Audio = RBJLowPass.Audio(
|
||||
input: dcBlocked,
|
||||
freq: conditionCutoff,
|
||||
q: filterQ
|
||||
)
|
||||
let limited: Tanh.Audio = Tanh.Audio(conditioned, mul: limiterDrive)
|
||||
|
||||
let div1: SubOctaveDivider = SubOctaveDivider(input: limited, divisor: divisorOctave1)
|
||||
let div2: SubOctaveDivider = SubOctaveDivider(input: limited, divisor: divisorOctave2)
|
||||
|
||||
let oct1: any ValidGeneratorInput = softened(div1) * env
|
||||
let oct2: any ValidGeneratorInput = softened(div2) * env
|
||||
return (oct1, oct2)
|
||||
}
|
||||
|
||||
/// Builds the pitch-tracked sub-octave voices: detect the fundamental, run square
|
||||
/// oscillators an octave and two octaves below it, amplitude-follow, then soften.
|
||||
private func trackingVoices(
|
||||
dry: any ValidGeneratorInput,
|
||||
env: AmplitudeFollower.Audio
|
||||
) -> (any ValidGeneratorInput, any ValidGeneratorInput) {
|
||||
let tracker: FreqTracker = FreqTracker(
|
||||
in: dry,
|
||||
minFreq: trackMinFreq,
|
||||
maxFreq: trackMaxFreq
|
||||
)
|
||||
let freq: any ValidGeneratorInput = tracker.freq
|
||||
let osc1: OscSquare.Audio = OscSquare.Audio(freq: freq * octave1Ratio)
|
||||
let osc2: OscSquare.Audio = OscSquare.Audio(freq: freq * octave2Ratio)
|
||||
|
||||
let oct1: any ValidGeneratorInput = softened(osc1) * env
|
||||
let oct2: any ValidGeneratorInput = softened(osc2) * env
|
||||
return (oct1, oct2)
|
||||
}
|
||||
|
||||
/// Low-passes a raw square sub-octave to soften its edges before mixing.
|
||||
private func softened(_ square: any ValidGeneratorInput) -> RBJLowPass.Audio {
|
||||
RBJLowPass.Audio(input: square, freq: subToneCutoff, q: filterQ)
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,7 @@ public enum PedalRegistry {
|
||||
"Feedback Delay": { FeedbackDelayPedal() },
|
||||
"Multi-Tap Delay": { MultiTapDelayPedal() },
|
||||
"Octave Splitter": { OctaveUpSplitterPedal() },
|
||||
"Bass Octaver": { BassOctaverPedal() },
|
||||
"Ping-Pong": { PingPongDelayPedal() },
|
||||
]
|
||||
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
// BassOctaverPedalTests.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("BassOctaverPedal")
|
||||
struct BassOctaverPedalTests {
|
||||
|
||||
/// Renders the pedal through an NRT engine with the given configuration and returns the
|
||||
/// output samples.
|
||||
private func render(
|
||||
configure: (BassOctaverPedal) -> 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: BassOctaverPedal = BassOctaverPedal(
|
||||
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)
|
||||
}
|
||||
|
||||
/// Sum of squared differences over a stable window of two renders.
|
||||
private func windowedSSD(_ a: [Float], _ b: [Float]) -> Double {
|
||||
let skipSamples: Int = 2048
|
||||
let windowSize: Int = 2048
|
||||
guard a.count >= skipSamples + windowSize,
|
||||
b.count >= skipSamples + windowSize else { return 0.0 }
|
||||
let aWindow: ArraySlice<Float> = a[skipSamples..<(skipSamples + windowSize)]
|
||||
let bWindow: ArraySlice<Float> = b[skipSamples..<(skipSamples + windowSize)]
|
||||
return zip(aWindow, bWindow).reduce(0.0) { acc, pair in
|
||||
let diff: Double = Double(pair.0 - pair.1)
|
||||
return acc + diff * diff
|
||||
}
|
||||
}
|
||||
|
||||
@Test func flipFlopModeProducesNonSilentOutput() throws {
|
||||
let samples: [Float] = try render { pedal in
|
||||
pedal.mode = 0.0 // flip-flop
|
||||
pedal.oct1 = 1.0
|
||||
pedal.direct = 0.0
|
||||
}
|
||||
#expect(!samples.isEmpty)
|
||||
#expect(hasNonSilentOutput(samples), "flip-flop octave was silent")
|
||||
}
|
||||
|
||||
@Test func trackingModeProducesNonSilentOutput() throws {
|
||||
let samples: [Float] = try render { pedal in
|
||||
pedal.mode = 1.0 // tracking
|
||||
pedal.oct1 = 1.0
|
||||
pedal.direct = 0.0
|
||||
}
|
||||
#expect(!samples.isEmpty)
|
||||
#expect(hasNonSilentOutput(samples), "tracking octave was silent")
|
||||
}
|
||||
|
||||
@Test func flipFlopAndTrackingModesDiffer() throws {
|
||||
let flip: [Float] = try render { pedal in
|
||||
pedal.mode = 0.0
|
||||
pedal.oct1 = 1.0
|
||||
pedal.direct = 0.0
|
||||
}
|
||||
let track: [Float] = try render { pedal in
|
||||
pedal.mode = 1.0
|
||||
pedal.oct1 = 1.0
|
||||
pedal.direct = 0.0
|
||||
}
|
||||
#expect(hasNonSilentOutput(flip), "flip render was silent")
|
||||
#expect(hasNonSilentOutput(track), "tracking render was silent")
|
||||
#expect(windowedSSD(flip, track) > 0, "flip-flop and tracking modes produced identical output")
|
||||
}
|
||||
|
||||
@Test func subOctaveVoicesDifferFromDirectOnly() throws {
|
||||
let directOnly: [Float] = try render { pedal in
|
||||
pedal.oct1 = 0.0
|
||||
pedal.oct2 = 0.0
|
||||
pedal.direct = 1.0
|
||||
}
|
||||
let withSubs: [Float] = try render { pedal in
|
||||
pedal.mode = 0.0
|
||||
pedal.oct1 = 1.0
|
||||
pedal.oct2 = 1.0
|
||||
pedal.direct = 1.0
|
||||
}
|
||||
#expect(hasNonSilentOutput(directOnly), "direct-only render was silent")
|
||||
#expect(windowedSSD(directOnly, withSubs) > 0, "adding sub-octaves did not change the output")
|
||||
}
|
||||
|
||||
@Test func exposesOctaveAndDirectKnobs() throws {
|
||||
let pedal: BassOctaverPedal = BassOctaverPedal()
|
||||
let labels: [String] = pedal.effectKnobs.map { $0.label }
|
||||
#expect(labels == ["OCT 1", "OCT 2", "Direct"])
|
||||
}
|
||||
|
||||
@Test func exposesTwoStateModeSwitch() throws {
|
||||
let pedal: BassOctaverPedal = BassOctaverPedal()
|
||||
let switches: [PedalSwitch] = pedal.effectSwitches
|
||||
#expect(switches.map { $0.label } == ["Mode"])
|
||||
#expect(switches.first?.options.map { $0.title } == ["Flip", "Track"])
|
||||
}
|
||||
|
||||
@Test func presetRoundTripPreservesMode() throws {
|
||||
let pedal: BassOctaverPedal = BassOctaverPedal()
|
||||
pedal.mode = 1.0
|
||||
pedal.oct2 = 0.5
|
||||
|
||||
let state: PedalState = pedal.captureState()
|
||||
|
||||
let restored: BassOctaverPedal = BassOctaverPedal()
|
||||
restored.applyState(state)
|
||||
#expect(restored.mode == 1.0)
|
||||
#expect(restored.oct2 == 0.5)
|
||||
}
|
||||
|
||||
@Test func registeredInBuiltInRegistry() throws {
|
||||
let pedal: Pedal? = PedalRegistry.makePedal(type: "Bass Octaver")
|
||||
#expect(pedal is BassOctaverPedal)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
// SubOctaveDividerTests.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("SubOctaveDivider")
|
||||
struct SubOctaveDividerTests {
|
||||
|
||||
/// Minimal synth: a sine oscillator into a `SubOctaveDivider`, written to a mono bus.
|
||||
private final class DividerSynth: SynthesizerBase {
|
||||
private let oscFreq: Double
|
||||
private let divisor: Int
|
||||
private let outBus: Int
|
||||
|
||||
init(oscFreq: Double, divisor: Int, outBus: Int) {
|
||||
self.oscFreq = oscFreq
|
||||
self.divisor = divisor
|
||||
self.outBus = outBus
|
||||
super.init()
|
||||
}
|
||||
|
||||
override func build() {
|
||||
let osc: OscSin.Audio = OscSin.Audio(freq: oscFreq)
|
||||
let divider: SubOctaveDivider = SubOctaveDivider(input: osc, divisor: divisor)
|
||||
output(bus: outBus, source: divider)
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders `oscFreq` through a divider and returns the measured output fundamental in Hz,
|
||||
/// estimated from rising zero-crossings of the left channel.
|
||||
private func measuredOutputFreq(
|
||||
oscFreq: Double,
|
||||
divisor: Int,
|
||||
sampleRate: Double = 44100.0
|
||||
) throws -> Double {
|
||||
let renderDuration: Double = 0.5
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||
duration: renderDuration,
|
||||
sampleRate: sampleRate
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
defer { engine.busAllocator.releaseAudioBus(dstBus) }
|
||||
|
||||
let synth: DividerSynth = DividerSynth(
|
||||
oscFreq: oscFreq,
|
||||
divisor: divisor,
|
||||
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()
|
||||
|
||||
let samples: [Float] = readStereoCAF(url: url, sampleRate: sampleRate)
|
||||
// Left channel = even interleaved indices.
|
||||
let stride: Int = 2
|
||||
var crossings: Int = 0
|
||||
var prev: Float = 0.0
|
||||
var frameCount: Int = 0
|
||||
var index: Int = 0
|
||||
while index < samples.count {
|
||||
let cur: Float = samples[index]
|
||||
if prev <= 0.0 && cur > 0.0 { crossings += 1 }
|
||||
prev = cur
|
||||
frameCount += 1
|
||||
index += stride
|
||||
}
|
||||
let seconds: Double = Double(frameCount) / sampleRate
|
||||
guard seconds > 0.0 else { return 0.0 }
|
||||
return Double(crossings) / seconds
|
||||
}
|
||||
|
||||
@Test func divideByTwoHalvesFrequency() throws {
|
||||
let oscFreq: Double = 440.0
|
||||
let measured: Double = try measuredOutputFreq(oscFreq: oscFreq, divisor: 2)
|
||||
let expected: Double = oscFreq / 2.0
|
||||
let tolerance: Double = 0.2
|
||||
#expect(measured > 0.0, "divide-by-2 produced no crossings")
|
||||
#expect(abs(measured - expected) / expected < tolerance,
|
||||
"divide-by-2: expected ≈\(expected) Hz, measured \(measured) Hz")
|
||||
}
|
||||
|
||||
@Test func divideByFourQuartersFrequency() throws {
|
||||
let oscFreq: Double = 440.0
|
||||
let measured: Double = try measuredOutputFreq(oscFreq: oscFreq, divisor: 4)
|
||||
let expected: Double = oscFreq / 4.0
|
||||
let tolerance: Double = 0.25
|
||||
#expect(measured > 0.0, "divide-by-4 produced no crossings")
|
||||
#expect(abs(measured - expected) / expected < tolerance,
|
||||
"divide-by-4: expected ≈\(expected) Hz, measured \(measured) Hz")
|
||||
}
|
||||
|
||||
@Test func divideByFourIsOneOctaveBelowDivideByTwo() throws {
|
||||
let oscFreq: Double = 440.0
|
||||
let two: Double = try measuredOutputFreq(oscFreq: oscFreq, divisor: 2)
|
||||
let four: Double = try measuredOutputFreq(oscFreq: oscFreq, divisor: 4)
|
||||
#expect(four > 0.0, "divide-by-4 produced no crossings")
|
||||
let ratio: Double = two / four
|
||||
// The two voices should sit exactly one octave apart (ratio ≈ 2).
|
||||
#expect(abs(ratio - 2.0) < 0.4, "expected ÷4 one octave below ÷2; ratio \(ratio)")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user