Files
Lyrebird/Sources/Lyrebird/Generators/Analysis/ZeroCrossing.swift
T
josh f8878324fd v2.1.1 release: delay-click fix + internal consolidation
Mirror of Lyrebird dev HEAD (9f791c7c) minus maintainer-only paths. Patch release:
fixes the allpass fractional-delay click (DelayLine/CombFilter/AllpassFilter/
DelayLineFeedback under a modulated delay) and lands the internal code-quality
consolidation pass (~160 deduped sites + shared base classes/helpers, bit-identical
output). No public API removed or changed. See RELEASES.md.

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

224 lines
8.3 KiB
Swift

// ZeroCrossing.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdDSP
/// File-scope zero-fill block for ZeroCrossing — fallback when upstream returns no channel.
private let zeroCrossingZeroBlock: [Double] = [Double](
repeating: 0,
count: lyrebirdDefaultResultBufferSize
)
/// Minimum sample count between crossings required before a zero crossing is recognised.
/// Mirrors SuperCollider `ZeroCrossing_Ctor` guard (`counter > 4`) — rejects spurious
/// high-frequency noise crossings. A crossing is only recorded when the inter-crossing
/// sample count exceeds this threshold.
private let zeroCrossingMinCount: Int = 4
/// Zero-crossing frequency estimator. Equivalent to SuperCollider `ZeroCrossing`.
///
/// Counts samples between successive rising zero crossings (≤0 → >0 edges) and computes a
/// frequency estimate as `sampleRate / sampleCount`. The estimate is held between crossings
/// and starts at `0.0` until the first full period is measured.
///
/// `_prevSample` is lazy-initialised to the first input sample on the very first call,
/// matching SuperCollider's `ZeroCrossing_Ctor` (`m_previn = ZIN0(0)`). As a result,
/// a constant positive (DC) input produces no crossing and the output remains `0.0`.
/// Crossings require more than `zeroCrossingMinCount` (4) samples of inter-crossing
/// spacing — spurious noise crossings are rejected.
///
/// ```swift
/// // Estimate the frequency of an input signal.
/// let freq = ZeroCrossing.Audio(input: OscSin.Audio(freq: 440.0))
/// ZeroCrossing.Control(input: audioRateInput) // block-rate measurement
/// ```
///
/// - Parameters:
/// - input: Signal to analyse. Can be any `ValidGeneratorInput`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public enum ZeroCrossing {
// MARK: - Shared base
/// Shared stored properties for `ZeroCrossing.Audio` and `ZeroCrossing.Control`.
public class _Base: GeneratorBase {
let _input: any ValidGeneratorInput
let _mulAdd: MulAddSpec
/// Sample value from the previous `_computeSamples` call. Lazy-initialised to the
/// first input sample on first use; not meaningful before that point.
var _prevSample: Double = 0.0
/// Samples elapsed since the last rising zero crossing.
var _count: Int = 0
/// Most recently measured frequency estimate, held until the next crossing.
var _freq: Double = 0.0
/// `false` until the very first sample is processed; guards lazy-init of `_prevSample`.
var _initialized: Bool = false
init(
input: any ValidGeneratorInput,
mul: any ValidGeneratorInput,
add: any ValidGeneratorInput
) {
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
_input = resolvedInput
_mulAdd = MulAddSpec(mul: mul, add: add)
super.init()
}
}
// MARK: - Audio rate
/// Audio-rate zero-crossing frequency estimator.
///
/// Computes a per-sample frequency estimate from rising zero-crossing spacing.
/// The estimate is held between crossings. `_prevSample` is lazy-initialised to
/// the first input sample; constant DC input yields `0.0`. Crossings require more
/// than `zeroCrossingMinCount` (4) samples of spacing.
///
/// - Parameters:
/// - input: Signal to analyse.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public final class Audio: _Base, AudioGenerator {
/// - Parameters:
/// - input: Signal to analyse.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public override init(
input: any ValidGeneratorInput,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
super.init(input: input, mul: mul, add: add)
}
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
let inputSamples: [Double] = _input.calculatedSamples(
graph: graph, count: count).first ?? zeroCrossingZeroBlock
let sr: Double = graph.engine.sampleRate
var prevSample: Double = _prevSample
var xingCount: Int = _count
var freq: Double = _freq
var initialized: Bool = _initialized
for i: Int in 0..<count {
let x: Double = inputSamples[i]
if !initialized {
prevSample = x
initialized = true
}
xingCount += 1
if xingCount > zeroCrossingMinCount && prevSample <= 0 && x > 0 {
freq = sr / Double(xingCount)
xingCount = 0
}
prevSample = x
_result[0][i] = freq
}
_prevSample = prevSample
_count = xingCount
_freq = freq
_initialized = initialized
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
}
// MARK: - Control rate
/// Block-rate zero-crossing frequency estimator.
///
/// Scans the full audio-rate input block running the same state machine as `Audio`;
/// outputs the block-final frequency estimate as a flat block. The estimate is held
/// between crossings and starts at `0.0` until the first period is measured.
///
/// `_prevSample` is lazy-initialised to the first input sample; constant DC input
/// yields `0.0`. Crossings require more than `zeroCrossingMinCount` (4) samples of
/// spacing, matching SuperCollider behaviour.
///
/// Bypasses the sub-block loop — the state machine must scan the full audio block
/// exactly once per audio cycle to avoid double-advancing the crossing counter.
///
/// - Parameters:
/// - input: Signal to analyse.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public final class Control: _Base, BlockRateControlGenerator {
public var previousOutputValue: Double = 0.0
/// - Parameters:
/// - input: Signal to analyse.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public override init(
input: any ValidGeneratorInput,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
super.init(input: input, mul: mul, add: add)
}
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
let inputSamples: [Double] = _input.calculatedSamples(
graph: graph, count: count).first ?? zeroCrossingZeroBlock
let sr: Double = graph.engine.sampleRate
var prevSample: Double = _prevSample
var xingCount: Int = _count
var freq: Double = _freq
var initialized: Bool = _initialized
for i: Int in 0..<count {
let x: Double = inputSamples[i]
if !initialized {
prevSample = x
initialized = true
}
xingCount += 1
if xingCount > zeroCrossingMinCount && prevSample <= 0 && x > 0 {
freq = sr / Double(xingCount)
xingCount = 0
}
prevSample = x
}
_prevSample = prevSample
_count = xingCount
_freq = freq
_initialized = initialized
fillHeldResult(into: &_result, value: freq, previousOutputValue: &previousOutputValue, mulAdd: _mulAdd, graph: graph, count: count)
return _result
}
public func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
}
}
// MARK: - GeneratorEnum
extension ZeroCrossing: GeneratorEnum {
public typealias AudioType = ZeroCrossing.Audio
public typealias ControlType = ZeroCrossing.Control
}