Files
Lyrebird/Sources/Lyrebird/Generators/Oscillators/OscSquare.swift
T

179 lines
6.4 KiB
Swift

// OscSquare.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// MARK: - OscSquare
/// Band-limited square wave oscillator using polyBLEP correction at both edges.
///
/// Produces a 50% duty-cycle square wave in the range `[-1, 1]`. PolyBLEP is applied at
/// both the rising edge (phase = 0) and the falling edge (phase = 0.5).
///
/// - Parameters:
/// - freq: Frequency in Hz. No internal clamping.
/// - phase: Initial phase offset in cycles `[0, 1)`. Defaults to `0.0`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public enum OscSquare {
// MARK: - Shared base
/// Shared state for audio-rate and control-rate square oscillator variants.
public class _Base: OscillatorBase {}
// MARK: - Audio
/// Audio-rate band-limited square wave oscillator.
///
/// Evaluates frequency per sample; supports audio-rate frequency modulation.
///
/// - Parameters:
/// - freq: Frequency in Hz. No internal clamping.
/// - phase: Initial phase offset in cycles `[0, 1)`. Defaults to `0.0`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public final class Audio: _Base, AudioGenerator {
/// - Parameters:
/// - freq: Frequency in Hz. No internal clamping.
/// - phase: Initial phase offset in cycles `[0, 1)`. Defaults to `0.0`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public override init(
freq: any ValidGeneratorInput,
phase: Double = 0.0,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
super.init(freq: freq, phase: phase, mul: mul, add: add)
}
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
let sampleRate: Double = Double(graph.engine.sampleRate)
let freqSamples: [Double]?
let scalarDt: Double
if _freqIsGenerator {
freqSamples = _freqInput.calculatedSamples(graph: graph, count: count).first
scalarDt = 0
} else {
freqSamples = nil
scalarDt = _freqInput.floatValue(graph: graph) / sampleRate
}
for i: Int in 0..<count {
let dt: Double
if let fs: [Double] = freqSamples {
dt = (i < fs.count ? fs[i] : 0) / sampleRate
} else {
dt = scalarDt
}
// Raw square
let rawSquare: Double = _phase < oscBLHalfPhase ? 1.0 : -1.0
// PolyBLEP at rising edge (phase = 0 wrap)
let blepRising: Double = polyBLEP(_phase, dt)
// PolyBLEP at falling edge (phase = 0.5)
// Shift phase by -0.5 so the falling edge is at a virtual "wrap" point
let phaseFalling: Double = _phase < oscBLHalfPhase ? _phase + oscBLHalfPhase : _phase - oscBLHalfPhase
let blepFalling: Double = polyBLEP(phaseFalling, dt)
_result[0][i] = rawSquare + blepRising - blepFalling
_phase += dt
if _phase >= 1.0 { _phase -= 1.0 }
else if _phase < 0.0 { _phase += 1.0 }
if _phase >= 1.0 || _phase < 0.0 {
_phase = _phase.truncatingRemainder(dividingBy: 1.0)
if _phase < 0.0 { _phase += 1.0 }
}
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
}
// MARK: - Control
/// Control-rate band-limited square wave oscillator. Advances phase once per block.
///
/// - Parameters:
/// - freq: Frequency in Hz. No internal clamping.
/// - phase: Initial phase offset in cycles `[0, 1)`. Defaults to `0.0`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public final class Control: _Base, ControlGenerator {
public var previousOutputValue: Double = 0.0
private var _rampTarget: Double = 0.0
/// - Parameters:
/// - freq: Frequency in Hz. No internal clamping.
/// - phase: Initial phase offset in cycles `[0, 1)`. Defaults to `0.0`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public override init(
freq: any ValidGeneratorInput,
phase: Double = 0.0,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
super.init(freq: freq, phase: phase, mul: mul, add: add)
_setupSubBlockBuffer()
}
// Bypass sub-block loop: phase must advance exactly once per audio block.
public func calculatedSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_calculatedSamplesBlockRate(graph: graph, count: count)
}
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
let sampleRate: Double = Double(graph.engine.sampleRate)
let countFloat: Double = Double(count)
let freq: Double
if _freqIsGenerator {
freq = _freqInput.calculatedSamples(graph: graph, count: count).first?.first ?? 0
} else {
freq = _freqInput.floatValue(graph: graph)
}
let dt: Double = freq / sampleRate
_phase += dt * countFloat
normalizeOscPhase(&_phase)
let target: Double = _phase < oscBLHalfPhase ? 1.0 : -1.0
let rampStart: Double = _rampTarget
_rampTarget = target
guard count > 0 else { return _result }
previousOutputValue = fillRampedResult(
into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count)
return _result
}
}
}
extension OscSquare: GeneratorEnum {
public typealias AudioType = OscSquare.Audio
public typealias ControlType = OscSquare.Control
}