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