Files
Lyrebird/Sources/Lyrebird/Math/LyrebirdConstants.swift
T

184 lines
8.2 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// LyrebirdConstants.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Module-level constants shared across the Lyrebird framework.
// MARK: - Audio format constants
/// Bytes per audio sample — 32-bit IEEE 754 float = 4 bytes.
///
/// Used by `CoreAudioDriver`, `iOSAudioDriver`, and `NRTDriver` when computing
/// `AudioBuffer.mDataByteSize` and `AudioStreamBasicDescription.mBytesPerFrame`.
/// Named to eliminate the magic literal `4` from all driver code.
internal let lyrebirdBytesPerSample: UInt32 = 4
// MARK: - Generator output buffer sizing
/// Pre-allocation size for built-in `AudioGenerator` output buffers.
///
/// All built-in generators allocate their `_result[0]` buffer at this size in `init`.
/// `SynthesisEngine.init` enforces `blockSize <= lyrebirdDefaultResultBufferSize`
/// so that no generator ever allocates on the RT render thread after start-up.
public let lyrebirdDefaultResultBufferSize: Int = 512
/// Control-rate sub-block size used by RT drivers (`CoreAudioDriver`, `iOSAudioDriver`)
/// when no explicit `controlBlockSize` is passed to `SynthesisEngine.init`.
///
/// Enables 64-sample control granularity on hardware I/O. Pass a different power-of-two
/// value to `SynthesisEngine.init(controlBlockSize:)` to override. `OfflineDriver` returns
/// `nil`, so engines created with `OfflineDriver` default to full-block mode.
public let lyrebirdDefaultControlBlockSize: Int = 64
/// Pass as `controlBlockSize` (or returned by `NRTDriver.suggestedControlBlockSize`)
/// to make every `ControlGenerator` advance its state machine once per sample.
///
/// At this setting the sub-block loop runs `blockSize` times per segment, giving
/// maximum envelope and modulation resolution. CPU cost is acceptable for offline
/// (NRT) rendering; use a larger power-of-two for real-time use.
public let lyrebirdSampleAccurateControlBlockSize: Int = 1
// MARK: - Lookup table sizing
/// Default sample count for shared lookup tables (sine, Hanning window, etc.).
///
/// Must be a power of two so that bitmask wrapping (`& (size - 1)`) can replace
/// integer modulo in inner synthesis loops. The shared tables stored on
/// `SynthesisEngine.sharedTables` are always allocated at this size.
public let lyrebirdDefaultTableSize: Int = 32768
// MARK: - Filter limits
/// Maximum order for `ButterworthLowPass` and `ButterworthHighPass`.
/// Orders above this are clamped at `init` time. Order 8 = 4 biquad stages (−48 dB/oct).
public let maxButterworthOrder: Int = 8
// MARK: - Buffer channel count
/// The channel count for a mono `LyrebirdBuffer` — used in `precondition` messages and
/// assertions throughout the framework. Naming the constant avoids magic `1` literals.
public let lyrebirdBufferMonoChannelCount: Int = 1
/// Maximum channel count supported by `LyrebirdBuffer.write(to:)` and
/// `LyrebirdBuffer.loadAllChannels(url:)`.
///
/// WAV (WAVE_FORMAT_EXTENSIBLE) supports up to 18 channels; CAF has no practical limit.
/// AIFF-C is best restricted to stereo for compatibility with legacy readers.
/// 8 is a conservative, practical ceiling that covers 7.1 surround and all common
/// multichannel configurations.
public let lyrebirdMaxFileChannelCount: Int = 8
// MARK: - Granular synthesis
/// Pre-allocated grain pool size for `BufferGrain`.
///
/// All `GrainState` slots are allocated at `BufferGrain.init` time. `_computeSamples` never
/// grows the pool — when all slots are active, new trigger events are silently dropped
/// until a slot becomes free. 64 simultaneous grains is sufficient for standard granular
/// densities up to a few hundred grains/second at typical block sizes.
public let lyrebirdGrainPoolSize: Int = 64
/// Circular capture buffer size for `InputGrain`, in frames.
///
/// 131072 = 2^17 ≈ 3.0 s at 44 100 Hz / 2.7 s at 48 000 Hz.
/// Pre-allocated at `InputGrain.init` time; never resized on the RT thread.
public let lyrebirdInputGrainSize: Int = 131072
/// Maximum FM modulation index for `FMGrain`.
///
/// Clamps `mIdx` at grain trigger time so `rawCarrier = synthPhase + modIndex × modOut × tsdtp`
/// remains representable as `Int` and `Int(rawCarrier.rounded(.down))` never traps on the RT thread.
/// At index 1000 the peak table-index displacement is ~5.2 M — far beyond musical range but
/// safely within `Int` bounds for `lyrebirdDefaultTableSize` = 32 768.
public let lyrebirdMaxFMModIndex: Double = 1000.0
/// Fallback seed for `GranularBase` when `clock_gettime_nsec_np` returns 0.
/// A non-zero seed is required; xorshift64 is stuck at 0 forever if seeded with 0.
public let lyrebirdGranularDefaultSeed: UInt64 = 0xDEAD_BEEF_CAFE_1337
// MARK: - PRNG seed helpers
/// Returns a non-zero xorshift64 seed from an optional caller seed.
/// Applies `mixConstant` to decorrelate Audio/Control instances of the same generator.
///
/// If `seed` is nil, uses the current uptime in nanoseconds as the raw seed.
/// `lyrebirdGranularDefaultSeed` is substituted when the raw value is zero.
@inline(__always)
func lyrebirdSeedXorshift64(
from seed: UInt64?,
mixConstant: UInt64
) -> UInt64 {
let raw: UInt64 = seed ?? clock_gettime_nsec_np(CLOCK_UPTIME_RAW)
let mixed: UInt64 = (raw == 0 ? lyrebirdGranularDefaultSeed : raw) ^ mixConstant
return mixed == 0 ? mixConstant : mixed
}
/// Convenience overload for generators that do not need an Audio/Control decorrelation
/// `mixConstant`. Equivalent to `lyrebirdSeedXorshift64(from: seed, mixConstant: 0)`.
///
/// Use for stand-alone PRNG owners (e.g. `DemandTemporalTendency`, `DemandTemporalBrownian`) that
/// hold a single xorshift state — there is no sibling Audio/Control instance to decorrelate
/// from. Bit-identical output to the two-argument form with `mixConstant: 0`.
@inline(__always)
func lyrebirdSeedXorshift64(from seed: UInt64?) -> UInt64 {
lyrebirdSeedXorshift64(from: seed, mixConstant: 0)
}
// MARK: - Mathematical constants
/// Two π: the radian measure of a full cycle.
///
/// Shared by oscillator, modulation, and filter code. Avoids per-function `let twoPi` locals.
internal let lyrebirdTwoPi: Double = 2.0 * Double.pi
// MARK: - Sample rate limits
/// Maximum sample rate supported by Lyrebird hardware drivers.
///
/// Used by generators that pre-allocate buffers sized for the worst-case sample rate
/// (e.g. `PitchShift` checks that window size × max pitch ratio fits in the circular
/// capture buffer at this rate). Hardware typically tops out at 192 kHz; drivers
/// configured for higher rates would require increasing this constant.
public let lyrebirdMaxSupportedSampleRate: Double = 192_000.0
// MARK: - Audio stream format
/// Bits per channel for the float32 PCM stream format used by all Lyrebird drivers
/// (CoreAudio, iOS RemoteIO, NRT). Matches `lyrebirdBytesPerSample = 4`.
public let lyrebirdBitsPerSample: UInt32 = 32
// MARK: - SynthesisEngine defaults
/// Default audio bus count when none is supplied to `SynthesisEngine.init`.
public let lyrebirdDefaultNumAudioBuses: Int = 128
/// Default control bus count when none is supplied to `SynthesisEngine.init`.
public let lyrebirdDefaultNumControlBuses: Int = 4096
/// Default scheduling pending-event-queue capacity when none is supplied to
/// `SynthesisEngine.init`. Must be a power of two.
public let lyrebirdDefaultEventQueueCapacity: Int = 1024
/// Default sample rate in Hz when none is supplied (used by `NRTJob`
/// default and convenience constructors). 44100 matches the standard
/// CD-quality rate; callers that require a specific rate should pass
/// it explicitly to `SynthesisEngine.init` / `NRTJob.init`.
public let lyrebirdDefaultSampleRate: Double = 44100.0
// MARK: - Butterworth filter Accelerate-vDSP background queues
/// Coefficient-update SPSC queue capacity for `Butterworth*` filters' background
/// `vDSP_biquad_SetCoefficients` setup thread. Power of two.
internal let butterworthCoeffQueueCapacity: Int = 4
/// Response SPSC queue capacity from background setup thread back to RT.
internal let butterworthRespQueueCapacity: Int = 2
/// Kill-queue capacity for retired vDSP setup handles awaiting `vDSP_biquad_DestroySetup`.
/// Sized for high-coefficient-churn workloads (rapidly modulated cutoff).
internal let butterworthKillQueueCapacity: Int = 32