// OversampledRingModulator.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import LyrebirdSynth import Darwin /// 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 oversampledRingModZeroBlock: [Double] = makeSampleBuffer() /// Ring modulator (`input × sine carrier`) evaluated at 2× or 4× the engine sample rate. /// /// A ring modulator's product produces sum-and-difference sidebands at `f_in ± f_carrier`. The /// sum sideband can land above the engine Nyquist and fold back as an inharmonic alias — /// worst with a high carrier and bright input. Evaluating the multiply at an oversampled rate /// (the input upsampled through a halfband FIR, the carrier generated directly at the /// oversampled rate) pushes the sum term below the upsampled Nyquist, then the matching /// downsampler filters it out before returning to the engine rate. /// /// Output is mono (channel 0 of the input is used). /// /// - Parameters: /// - input: Signal to modulate. /// - freq: Carrier frequency in Hz. Read once per block. Defaults to `220.0`. /// - oversample: Oversampling factor — `2` or `4`. Defaults to `2`. public final class OversampledRingModulator: GeneratorBase, AudioGenerator { /// Resolved input signal (classified once at `init`, never on the RT thread). private let inputSource: any ValidGeneratorInput /// Resolved carrier-frequency control. Read once per block. private let freqInput: any ValidGeneratorInput /// Oversampling factor — `2` or `4`, fixed at init. private let oversampleFactor: Int /// Carrier phase in radians, advanced at the oversampled rate and wrapped to `[0, 2π)`. private var phase: Double = 0.0 /// 2× halfband oversampling state (used when `oversampleFactor == 2`). private var upsampler2x: HalfbandUpsampler2x private var downsampler2x: HalfbandDownsampler2x /// 4× halfband oversampling state (used when `oversampleFactor == 4`). private var upsampler4x: HalfbandUpsampler4x private var downsampler4x: HalfbandDownsampler4x private let twoPi: Double = 2.0 * Double.pi /// Creates an oversampled ring modulator. /// /// - Parameters: /// - input: Signal to modulate. /// - freq: Carrier frequency in Hz. Read once per block. Defaults to `220.0`. /// - oversample: Oversampling factor — `2` or `4`. Defaults to `2`. public init( _ input: any ValidGeneratorInput, freq: any ValidGeneratorInput = 220.0, oversample: Int = 2 ) { precondition( oversample == 2 || oversample == 4, "OversampledRingModulator: oversample must be 2 or 4" ) let resolvedInput: any ValidGeneratorInput = input._resolvedInput() let resolvedFreq: any ValidGeneratorInput = freq._resolvedInput() inputSource = resolvedInput freqInput = resolvedFreq oversampleFactor = oversample upsampler2x = HalfbandUpsampler2x() downsampler2x = HalfbandDownsampler2x() upsampler4x = HalfbandUpsampler4x() downsampler4x = HalfbandDownsampler4x() super.init() } public func _computeSamples( graph: SynthGraph, count: Int ) -> [[Double]] { _checkCount(count) guard count > 0 else { return _result } let input: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first ?? oversampledRingModZeroBlock let sr: Double = graph.engine.sampleRate // A degenerate sample rate would make phaseInc NaN/Inf and latch NaN into the // persisted phase; zero-fill and bail, matching MoogLadder's guard. guard sr >= 1.0 else { _result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer) in guard let dstP: UnsafeMutablePointer = dst.baseAddress else { return } for i: Int in 0..) in guard let dstP: UnsafeMutablePointer = dst.baseAddress else { return } if useFourX { for i: Int in 0..= twoPi || localPhase < 0 { localPhase = localPhase.truncatingRemainder(dividingBy: twoPi) if localPhase < 0 { localPhase += twoPi } } dstP[i] = downsampler4x.process(ya, yb, yc, yd) } } else { for i: Int in 0..= twoPi || localPhase < 0 { localPhase = localPhase.truncatingRemainder(dividingBy: twoPi) if localPhase < 0 { localPhase += twoPi } } dstP[i] = downsampler2x.process(ya, yb) } } } phase = localPhase return _result } }