Files
ShoeGaze/Sources/LyrebirdShoeGaze/Generators/SubOctaveDivider.swift
T
josh 2ba57cadd6 Add Bass Octaver pedal (Boss OC-2 style)
Monophonic octave-down pedal with OCT1/OCT2/Direct knobs and a Mode
switch between two algorithms:

- Flip-flop (default): a hysteresis comparator clocks a T flip-flop
  divider chain (new SubOctaveDivider generator) to produce square
  sub-octaves one and two octaves down, amplitude-followed off the dry
  signal. Time-domain — tracks low bass with no detection floor.
- Tracking: FreqTracker drives square oscillators at half and quarter
  the detected frequency. Cleaner, but limited by the tracker's ~90 Hz
  floor; flip-flop is the bass mode.

SubOctaveDivider classifies its input as generator-or-scalar at init to
keep _computeSamples allocation-free, uses a shared file-scope zero
block, bounds-checks the input read, and traps on divisor < 2.

Tests: BassOctaverPedal integration (both modes non-silent, modes
differ, sub-octaves change output, knobs/switch/preset/registry) and
SubOctaveDivider deterministic frequency-division (divisor 2 -> /2,
divisor 4 -> /4, /4 one octave below /2). 127 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-21 20:43:03 -07:00

142 lines
6.0 KiB
Swift

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