b6fdee8bfc
Consolidated release: the cross-platform Linux port (engine, generators, CLI, REPL, NRT, portable DSP), live ALSA audio + ALSA MIDI + POSIX OSC + portable WAV codec, the GTK4 GUI (LyrebirdUI on the SwiftOpenUI backend), and the Linux live-coding scratchpad (LiveCompile). Apple platforms unchanged; all additive. See RELEASES.md and LINUX_README.md. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
728 lines
30 KiB
Swift
728 lines
30 KiB
Swift
// LyrebirdBufferWavetable.swift
|
||
// Lyrebird
|
||
//
|
||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||
// SPDX-License-Identifier: MIT
|
||
|
||
import LyrebirdDSP
|
||
import Foundation
|
||
|
||
// MARK: - LyrebirdBuffer wavetable generation extensions
|
||
|
||
extension LyrebirdBuffer {
|
||
|
||
// MARK: 2b.1 Partial series fill
|
||
|
||
/// Fill the buffer with a sum of `partialCount` harmonic sine partials (sawtooth spectrum).
|
||
///
|
||
/// Produces a band-limited sawtooth-like timbre:
|
||
/// `output = Σ sin(k × 2π × i / N) / k` for k = 1 … partialCount.
|
||
///
|
||
/// The result is normalised so the peak absolute value is 1.0. Requires a mono buffer.
|
||
///
|
||
/// - Parameters:
|
||
/// - partialCount: Number of harmonic partials to sum. Must be ≥ 1.
|
||
public func fill(partials partialCount: Int) {
|
||
precondition(
|
||
channelCount == lyrebirdBufferMonoChannelCount,
|
||
"fill(partials:) requires a mono buffer; this buffer has channelCount == \(channelCount)."
|
||
)
|
||
precondition(partialCount >= 1, "fill(partials:) requires partials ≥ 1, got \(partialCount)")
|
||
precondition(
|
||
_isValidForFill,
|
||
"fill(partials:) called on an invalidated LyrebirdBuffer"
|
||
)
|
||
|
||
let n: Int = count
|
||
let nDouble: Double = Double(n)
|
||
let twoPi: Double = 2.0 * .pi
|
||
|
||
withMutableStorage { dst, frames, _ in
|
||
// Zero the output
|
||
var zero: Double = 0
|
||
vDSP_vfillD(&zero, dst, 1, vDSP_Length(frames))
|
||
|
||
var partial: [Double] = [Double](repeating: 0, count: frames)
|
||
partial.withUnsafeMutableBufferPointer { pptr in
|
||
guard let pbase: UnsafeMutablePointer<Double> = pptr.baseAddress else { return }
|
||
|
||
for k: Int in 1...partialCount {
|
||
let kDouble: Double = Double(k)
|
||
let amplitude: Double = 1.0 / kDouble
|
||
// Fill partial[i] = amplitude * sin(k * 2π * i / N)
|
||
for i: Int in 0..<frames {
|
||
pbase[i] = amplitude * sin(kDouble * twoPi * Double(i) / nDouble)
|
||
}
|
||
// dst += partial (vDSP_vadd in place)
|
||
vDSP_vaddD(dst, 1, pbase, 1, dst, 1, vDSP_Length(frames))
|
||
}
|
||
}
|
||
|
||
// Normalise to peak 1.0
|
||
var peak: Double = 0
|
||
vDSP_maxmgvD(dst, 1, &peak, vDSP_Length(frames))
|
||
if peak > 0 {
|
||
var scale: Double = 1.0 / peak
|
||
vDSP_vsmulD(dst, 1, &scale, dst, 1, vDSP_Length(frames))
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Fill the buffer with a weighted sum of sine partials at specified harmonic numbers.
|
||
///
|
||
/// Allows arbitrary spectra by specifying which harmonics to include and their amplitudes.
|
||
/// The result is normalised so the peak absolute value is 1.0 (unless all amplitudes are 0).
|
||
/// Requires a mono buffer.
|
||
///
|
||
/// ```swift
|
||
/// // Square wave: odd harmonics only
|
||
/// buffer.fill(harmonics: [1, 3, 5, 7, 9], amplitudes: [1, 1/3, 1/5, 1/7, 1/9])
|
||
/// ```
|
||
///
|
||
/// - Parameters:
|
||
/// - harmonics: Array of harmonic numbers (1 = fundamental, 2 = first overtone, etc.).
|
||
/// Values must be ≥ 1. Must have the same length as `amplitudes`.
|
||
/// - amplitudes: Amplitude for each corresponding harmonic. Negative values invert phase.
|
||
/// Must have the same length as `harmonics`.
|
||
public func fill(
|
||
harmonics: [Int],
|
||
amplitudes: [Double]
|
||
) {
|
||
precondition(
|
||
channelCount == lyrebirdBufferMonoChannelCount,
|
||
"fill(harmonics:amplitudes:) requires a mono buffer; "
|
||
+ "this buffer has channelCount == \(channelCount)."
|
||
)
|
||
precondition(
|
||
harmonics.count == amplitudes.count,
|
||
"fill(harmonics:amplitudes:) requires harmonics.count == amplitudes.count; "
|
||
+ "got \(harmonics.count) and \(amplitudes.count)"
|
||
)
|
||
precondition(
|
||
_isValidForFill,
|
||
"fill(harmonics:amplitudes:) called on an invalidated LyrebirdBuffer"
|
||
)
|
||
precondition(
|
||
harmonics.allSatisfy { $0 >= 1 },
|
||
"fill(harmonics:amplitudes:) requires all harmonic values ≥ 1"
|
||
)
|
||
|
||
let frames: Int = count
|
||
let framesDouble: Double = Double(frames)
|
||
let twoPi: Double = 2.0 * .pi
|
||
|
||
withMutableStorage { dst, n, _ in
|
||
var zero: Double = 0
|
||
vDSP_vfillD(&zero, dst, 1, vDSP_Length(n))
|
||
|
||
var partial: [Double] = [Double](repeating: 0, count: n)
|
||
partial.withUnsafeMutableBufferPointer { pptr in
|
||
guard let pbase: UnsafeMutablePointer<Double> = pptr.baseAddress else { return }
|
||
|
||
for (harmonic, amplitude) in zip(harmonics, amplitudes) {
|
||
guard amplitude != 0 else { continue }
|
||
let kDouble: Double = Double(harmonic)
|
||
for i: Int in 0..<n {
|
||
pbase[i] = amplitude * sin(kDouble * twoPi * Double(i) / framesDouble)
|
||
}
|
||
vDSP_vaddD(dst, 1, pbase, 1, dst, 1, vDSP_Length(n))
|
||
}
|
||
}
|
||
|
||
// Normalise to peak 1.0
|
||
var peak: Double = 0
|
||
vDSP_maxmgvD(dst, 1, &peak, vDSP_Length(n))
|
||
if peak > 0 {
|
||
var scale: Double = 1.0 / peak
|
||
vDSP_vsmulD(dst, 1, &scale, dst, 1, vDSP_Length(n))
|
||
}
|
||
}
|
||
}
|
||
|
||
// MARK: 2b.2 Chebyshev polynomial tables
|
||
|
||
/// Fill the buffer with a weighted sum of Chebyshev polynomials of the first kind.
|
||
///
|
||
/// Used to create waveshaping transfer curves. The input domain is `[−1, 1]` (mapped from
|
||
/// the buffer index). `coefficients[0]` weights T₁(x), `coefficients[1]` weights T₂(x), etc.
|
||
///
|
||
/// T₁(x) = x, T₂(x) = 2x²−1, T₃(x) = 4x³−3x, etc. (computed iteratively with no trig).
|
||
///
|
||
/// The result is normalised to the peak absolute value of 1.0 (unless all coefficients are 0).
|
||
/// Requires a mono buffer.
|
||
///
|
||
/// - Parameters:
|
||
/// - coefficients: Array of weights for T₁, T₂, … Tₙ. Must not be empty.
|
||
public func fillChebyshev(coefficients: [Double]) {
|
||
precondition(
|
||
channelCount == lyrebirdBufferMonoChannelCount,
|
||
"fillChebyshev(coefficients:) requires a mono buffer; "
|
||
+ "this buffer has channelCount == \(channelCount)."
|
||
)
|
||
precondition(
|
||
!coefficients.isEmpty,
|
||
"fillChebyshev(coefficients:) requires at least one coefficient"
|
||
)
|
||
precondition(
|
||
_isValidForFill,
|
||
"fillChebyshev(coefficients:) called on an invalidated LyrebirdBuffer"
|
||
)
|
||
|
||
let frames: Int = count
|
||
let framesM1: Double = Double(frames - 1)
|
||
|
||
withMutableStorage { dst, n, _ in
|
||
var zero: Double = 0
|
||
vDSP_vfillD(&zero, dst, 1, vDSP_Length(n))
|
||
|
||
for i: Int in 0..<n {
|
||
// Map frame index to x in [-1, 1]
|
||
let x: Double = frames > 1 ? (2.0 * Double(i) / framesM1 - 1.0) : 0.0
|
||
var value: Double = 0
|
||
|
||
// Chebyshev recurrence: T₀=1, T₁=x, Tₙ=2x·Tₙ₋₁ − Tₙ₋₂
|
||
var tPrev: Double = 1.0 // T₀
|
||
var tCurr: Double = x // T₁
|
||
|
||
for (j, coeff) in coefficients.enumerated() {
|
||
if j == 0 {
|
||
// coefficients[0] corresponds to T₁
|
||
value += coeff * tCurr
|
||
} else {
|
||
// Advance recurrence: Tₙ₊₁ = 2x·Tₙ − Tₙ₋₁
|
||
let tNext: Double = 2.0 * x * tCurr - tPrev
|
||
tPrev = tCurr
|
||
tCurr = tNext
|
||
value += coeff * tCurr
|
||
}
|
||
}
|
||
|
||
dst[i] = value
|
||
}
|
||
|
||
// Normalise to peak 1.0
|
||
var peak: Double = 0
|
||
vDSP_maxmgvD(dst, 1, &peak, vDSP_Length(n))
|
||
if peak > 0 {
|
||
var scale: Double = 1.0 / peak
|
||
vDSP_vsmulD(dst, 1, &scale, dst, 1, vDSP_Length(n))
|
||
}
|
||
}
|
||
}
|
||
|
||
// MARK: 2b.3 Window function fills
|
||
|
||
/// Fill the buffer with a window function suitable for granular synthesis or FFT use.
|
||
///
|
||
/// All windows produce values in `[0, 1]` with zero or near-zero endpoints (except
|
||
/// `.hamming`, which has non-zero endpoints by design). Requires a mono buffer.
|
||
///
|
||
/// - Parameters:
|
||
/// - kind: The window shape. See `WindowKind` for options and formulas.
|
||
public func fillWindow(_ kind: WindowKind) {
|
||
precondition(
|
||
channelCount == lyrebirdBufferMonoChannelCount,
|
||
"fillWindow(_:) requires a mono buffer; this buffer has channelCount == \(channelCount)."
|
||
)
|
||
precondition(
|
||
_isValidForFill,
|
||
"fillWindow(_:) called on an invalidated LyrebirdBuffer"
|
||
)
|
||
|
||
let frames: Int = count
|
||
let framesDouble: Double = Double(frames)
|
||
let twoPi: Double = 2.0 * .pi
|
||
|
||
withMutableStorage { dst, n, _ in
|
||
switch kind {
|
||
case .rectangular:
|
||
// w[i] = 1 across the buffer (no taper).
|
||
for i: Int in 0..<n {
|
||
dst[i] = 1.0
|
||
}
|
||
|
||
case .hann:
|
||
// w[i] = 0.5 × (1 − cos(2π × i / N))
|
||
let hannA0: Double = 0.5
|
||
let hannA1: Double = 0.5
|
||
for i: Int in 0..<n {
|
||
dst[i] = hannA0 - hannA1 * cos(twoPi * Double(i) / framesDouble)
|
||
}
|
||
|
||
case .hamming:
|
||
// w[i] = 0.54 − 0.46 × cos(2π × i / N)
|
||
let hammingAlpha: Double = 0.54
|
||
let hammingBeta: Double = 0.46
|
||
for i: Int in 0..<n {
|
||
dst[i] = hammingAlpha - hammingBeta * cos(twoPi * Double(i) / framesDouble)
|
||
}
|
||
|
||
case .blackmanHarris:
|
||
// Four-term Blackman-Harris coefficients (Harris 1978)
|
||
let bh0: Double = 0.35875
|
||
let bh1: Double = 0.48829
|
||
let bh2: Double = 0.14128
|
||
let bh3: Double = 0.01168
|
||
for i: Int in 0..<n {
|
||
let phase: Double = twoPi * Double(i) / framesDouble
|
||
dst[i] = bh0
|
||
- bh1 * cos(phase)
|
||
+ bh2 * cos(2.0 * phase)
|
||
- bh3 * cos(3.0 * phase)
|
||
}
|
||
|
||
case .nuttall:
|
||
// Nuttall (1981) four-term coefficients
|
||
let nuttall0: Double = 0.355768
|
||
let nuttall1: Double = 0.487396
|
||
let nuttall2: Double = 0.144232
|
||
let nuttall3: Double = 0.012604
|
||
for i: Int in 0..<n {
|
||
let phase: Double = twoPi * Double(i) / framesDouble
|
||
dst[i] = nuttall0
|
||
- nuttall1 * cos(phase)
|
||
+ nuttall2 * cos(2.0 * phase)
|
||
- nuttall3 * cos(3.0 * phase)
|
||
}
|
||
|
||
case .flatTop:
|
||
// Flat-top window (Heinzel et al.)
|
||
let ft0: Double = 0.21557895
|
||
let ft1: Double = 0.41663158
|
||
let ft2: Double = 0.27726316
|
||
let ft3: Double = 0.08357895
|
||
let ft4: Double = 0.00694737
|
||
for i: Int in 0..<n {
|
||
let phase: Double = twoPi * Double(i) / framesDouble
|
||
dst[i] = ft0
|
||
- ft1 * cos(phase)
|
||
+ ft2 * cos(2.0 * phase)
|
||
- ft3 * cos(3.0 * phase)
|
||
+ ft4 * cos(4.0 * phase)
|
||
}
|
||
|
||
case .kaiser(let beta):
|
||
precondition(beta >= 0.0, "WindowKind.kaiser: beta must be ≥ 0, got \(beta)")
|
||
// w[i] = I₀(β × √(1 − (2i/N−1)²)) / I₀(β)
|
||
// where I₀ is the zeroth-order modified Bessel function of the first kind.
|
||
let denominator: Double = _besselI0(beta)
|
||
guard n > 1 else { dst[0] = 1.0; return }
|
||
let framesM1: Double = Double(n - 1)
|
||
for i: Int in 0..<n {
|
||
let normalised: Double = 2.0 * Double(i) / framesM1 - 1.0 // [-1, 1]
|
||
let arg: Double = beta * (1.0 - normalised * normalised).squareRoot()
|
||
dst[i] = _besselI0(arg) / denominator
|
||
}
|
||
|
||
case .bartlettHann:
|
||
// Bartlett-Hann: 0.62 − 0.48|i/N − 0.5| − 0.38 cos(2π × i / N)
|
||
let bhA0: Double = 0.62
|
||
let bhA1: Double = 0.48
|
||
let bhA2: Double = 0.38
|
||
for i: Int in 0..<n {
|
||
let normalised: Double = Double(i) / framesDouble
|
||
dst[i] = bhA0
|
||
- bhA1 * abs(normalised - 0.5)
|
||
- bhA2 * cos(twoPi * normalised)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// MARK: 2b.4 Waveshaper transfer curves
|
||
|
||
/// Fill the buffer with a waveshaper transfer curve over the domain `[−1, 1]`.
|
||
///
|
||
/// The output at each frame index represents the shaped output for a corresponding input
|
||
/// value. Use with `OscTable` or buffer-lookup to perform waveshaping distortion.
|
||
/// Requires a mono buffer.
|
||
///
|
||
/// - Parameters:
|
||
/// - kind: The waveshape curve. See `WaveshapeKind` for options and formulas.
|
||
public func fillWaveshaper(_ kind: WaveshapeKind) {
|
||
precondition(
|
||
channelCount == lyrebirdBufferMonoChannelCount,
|
||
"fillWaveshaper(_:) requires a mono buffer; this buffer has channelCount == \(channelCount)."
|
||
)
|
||
precondition(
|
||
_isValidForFill,
|
||
"fillWaveshaper(_:) called on an invalidated LyrebirdBuffer"
|
||
)
|
||
|
||
let frames: Int = count
|
||
let framesM1: Double = Double(frames - 1)
|
||
|
||
withMutableStorage { dst, n, _ in
|
||
switch kind {
|
||
case .hardClip:
|
||
for i: Int in 0..<n {
|
||
let x: Double = frames > 1 ? (2.0 * Double(i) / framesM1 - 1.0) : 0.0
|
||
dst[i] = max(-1.0, min(1.0, x))
|
||
}
|
||
|
||
case .softClip:
|
||
// tanh saturation: output approaches ±1 asymptotically
|
||
for i: Int in 0..<n {
|
||
let x: Double = frames > 1 ? (2.0 * Double(i) / framesM1 - 1.0) : 0.0
|
||
dst[i] = tanh(x)
|
||
}
|
||
|
||
case .foldback:
|
||
for i: Int in 0..<n {
|
||
let x: Double = frames > 1 ? (2.0 * Double(i) / framesM1 - 1.0) : 0.0
|
||
dst[i] = _foldback(x)
|
||
}
|
||
|
||
case .asymmetric(let knee):
|
||
precondition(
|
||
knee > 0 && knee <= 1.0,
|
||
"WaveshapeKind.asymmetric: knee must be in (0, 1], got \(knee)"
|
||
)
|
||
for i: Int in 0..<n {
|
||
let x: Double = frames > 1 ? (2.0 * Double(i) / framesM1 - 1.0) : 0.0
|
||
let absX: Double = abs(x)
|
||
if absX <= knee {
|
||
dst[i] = x // linear region
|
||
} else {
|
||
// Soft clip above the knee
|
||
let sign: Double = x >= 0 ? 1.0 : -1.0
|
||
let excess: Double = (absX - knee) / (1.0 - knee) // [0, 1]
|
||
dst[i] = sign * (knee + (1.0 - knee) * tanh(excess))
|
||
}
|
||
}
|
||
|
||
case .staircase(let steps):
|
||
precondition(
|
||
steps >= 2,
|
||
"WaveshapeKind.staircase: steps must be ≥ 2, got \(steps)"
|
||
)
|
||
let stepsDouble: Double = Double(steps)
|
||
let stepsMaxBin: Double = Double(steps - 1)
|
||
for i: Int in 0..<n {
|
||
let x: Double = frames > 1 ? (2.0 * Double(i) / framesM1 - 1.0) : 0.0
|
||
// Quantise to `steps` levels in [-1, 1]
|
||
let shifted: Double = (x + 1.0) * 0.5 * stepsDouble // [0, steps]
|
||
let bin: Double = min(floor(shifted), stepsMaxBin) // clamp to [0, steps-1]
|
||
let quantised: Double = (bin + 0.5) / stepsDouble // centred levels
|
||
dst[i] = max(-1.0, min(1.0, 2.0 * quantised - 1.0))
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Fill using a closure that maps each input value `x` in `[−1, 1]` to an output value.
|
||
///
|
||
/// The frame at index `i` receives `body(x)` where `x` spans `[−1, 1]` linearly.
|
||
/// Suitable for arbitrary custom waveshaping curves. Requires a mono buffer.
|
||
///
|
||
/// ```swift
|
||
/// buffer.fill { x in x * x * x } // cubic transfer
|
||
/// ```
|
||
///
|
||
/// - Parameters:
|
||
/// - body: Closure receiving `x` in `[−1, 1]` and returning the shaped output.
|
||
public func fill(body: (Double) -> Double) {
|
||
precondition(
|
||
channelCount == lyrebirdBufferMonoChannelCount,
|
||
"fill(_:) requires a mono buffer; this buffer has channelCount == \(channelCount)."
|
||
)
|
||
precondition(
|
||
_isValidForFill,
|
||
"fill(_:) called on an invalidated LyrebirdBuffer"
|
||
)
|
||
|
||
let frames: Int = count
|
||
let framesM1: Double = Double(frames - 1)
|
||
|
||
withMutableStorage { dst, n, _ in
|
||
for i: Int in 0..<n {
|
||
let x: Double = frames > 1 ? (2.0 * Double(i) / framesM1 - 1.0) : 0.0
|
||
dst[i] = body(x)
|
||
}
|
||
}
|
||
}
|
||
|
||
// MARK: 2b.5 Band-limited waveform tables
|
||
|
||
/// Fill the buffer with a band-limited periodic waveform, auto-capping partials at Nyquist.
|
||
///
|
||
/// The partial count is computed automatically as `floor(sampleRate / (2 × fundamental))`,
|
||
/// ensuring no aliasing at the given playback rate and fundamental frequency.
|
||
///
|
||
/// An optional Gibbs suppression sigma factor can be applied: each partial amplitude is
|
||
/// multiplied by `sinc(k × π / K)` (the Lanczos σ factor), reducing the Gibbs overshoot
|
||
/// at waveform edges at the cost of slightly reduced brightness.
|
||
///
|
||
/// The result is normalised to peak 1.0. Requires a mono buffer.
|
||
///
|
||
/// - Parameters:
|
||
/// - kind: Waveform shape — `.sawtooth`, `.square`, or `.triangle`.
|
||
/// - fundamental: Fundamental frequency in Hz. Must be > 0.
|
||
/// - sampleRate: Playback sample rate in Hz. Must be > 0. Used only to compute the
|
||
/// Nyquist-capped partial count; does not set `buffer.sampleRate`.
|
||
/// - suppressGibbs: When `true`, applies the Lanczos sigma factor to reduce ringing.
|
||
/// Defaults to `false`.
|
||
public func fillBandLimited(
|
||
_ kind: BandLimitedWaveformKind,
|
||
fundamental: Double,
|
||
sampleRate: Double,
|
||
suppressGibbs: Bool = false
|
||
) {
|
||
precondition(
|
||
channelCount == lyrebirdBufferMonoChannelCount,
|
||
"fillBandLimited(_:fundamental:sampleRate:) requires a mono buffer; "
|
||
+ "this buffer has channelCount == \(channelCount)."
|
||
)
|
||
precondition(fundamental > 0, "fillBandLimited: fundamental must be > 0, got \(fundamental)")
|
||
precondition(sampleRate > 0, "fillBandLimited: sampleRate must be > 0, got \(sampleRate)")
|
||
precondition(
|
||
_isValidForFill,
|
||
"fillBandLimited(_:fundamental:sampleRate:) called on an invalidated LyrebirdBuffer"
|
||
)
|
||
|
||
let nyquist: Double = sampleRate * 0.5
|
||
// Maximum number of partials that stay below Nyquist
|
||
let maxPartial: Int = max(1, Int(nyquist / fundamental))
|
||
|
||
let frames: Int = count
|
||
let framesDouble: Double = Double(frames)
|
||
let twoPi: Double = 2.0 * .pi
|
||
let maxPartialDouble: Double = Double(maxPartial)
|
||
|
||
withMutableStorage { dst, n, _ in
|
||
var zero: Double = 0
|
||
vDSP_vfillD(&zero, dst, 1, vDSP_Length(n))
|
||
|
||
var partial: [Double] = [Double](repeating: 0, count: n)
|
||
partial.withUnsafeMutableBufferPointer { pptr in
|
||
guard let pbase: UnsafeMutablePointer<Double> = pptr.baseAddress else { return }
|
||
|
||
switch kind {
|
||
case .sawtooth:
|
||
// Saw: Σ (amplitude / k) × sin(k × 2π × i/N) for k = 1 … maxPartial
|
||
for k: Int in 1...maxPartial {
|
||
let kDouble: Double = Double(k)
|
||
var amplitude: Double = 1.0 / kDouble
|
||
if suppressGibbs {
|
||
amplitude *= _lanczosσ(k: kDouble, maxK: maxPartialDouble)
|
||
}
|
||
for i: Int in 0..<n {
|
||
pbase[i] = amplitude * sin(kDouble * twoPi * Double(i) / framesDouble)
|
||
}
|
||
vDSP_vaddD(dst, 1, pbase, 1, dst, 1, vDSP_Length(n))
|
||
}
|
||
|
||
case .square:
|
||
// Square: Σ (1/(2k-1)) × sin((2k-1) × 2π × i/N) for odd harmonics
|
||
var k: Int = 1
|
||
while k <= maxPartial {
|
||
let kDouble: Double = Double(k)
|
||
var amplitude: Double = 1.0 / kDouble
|
||
if suppressGibbs {
|
||
amplitude *= _lanczosσ(k: kDouble, maxK: maxPartialDouble)
|
||
}
|
||
for i: Int in 0..<n {
|
||
pbase[i] = amplitude * sin(kDouble * twoPi * Double(i) / framesDouble)
|
||
}
|
||
vDSP_vaddD(dst, 1, pbase, 1, dst, 1, vDSP_Length(n))
|
||
k += 2
|
||
}
|
||
|
||
case .triangle:
|
||
// Triangle: Σ ((-1)^m / (2m+1)²) × sin((2m+1) × 2π × i/N)
|
||
var m: Int = 0
|
||
while true {
|
||
let harmonic: Int = 2 * m + 1
|
||
guard harmonic <= maxPartial else { break }
|
||
let hDouble: Double = Double(harmonic)
|
||
let sign: Double = (m % 2 == 0) ? 1.0 : -1.0
|
||
var amplitude: Double = sign / (hDouble * hDouble)
|
||
if suppressGibbs {
|
||
amplitude *= _lanczosσ(k: hDouble, maxK: maxPartialDouble)
|
||
}
|
||
for i: Int in 0..<n {
|
||
pbase[i] = amplitude * sin(hDouble * twoPi * Double(i) / framesDouble)
|
||
}
|
||
vDSP_vaddD(dst, 1, pbase, 1, dst, 1, vDSP_Length(n))
|
||
m += 1
|
||
}
|
||
}
|
||
}
|
||
|
||
// Normalise to peak 1.0
|
||
var peak: Double = 0
|
||
vDSP_maxmgvD(dst, 1, &peak, vDSP_Length(n))
|
||
if peak > 0 {
|
||
var scale: Double = 1.0 / peak
|
||
vDSP_vsmulD(dst, 1, &scale, dst, 1, vDSP_Length(n))
|
||
}
|
||
}
|
||
}
|
||
|
||
// MARK: 2b.6 Inharmonic partial series
|
||
|
||
/// Fill the buffer with a series of partials at arbitrary frequency ratios, amplitudes, and phases.
|
||
///
|
||
/// Each partial is defined by a frequency ratio relative to a normalised cycle (1.0 = fundamental),
|
||
/// an amplitude, and a phase offset in radians. Partials are summed and normalised to peak 1.0.
|
||
/// Requires a mono buffer.
|
||
///
|
||
/// ```swift
|
||
/// // Bell-like spectrum with inharmonic partials
|
||
/// buffer.fillPartials([
|
||
/// (ratio: 1.0, amp: 1.0, phase: 0.0),
|
||
/// (ratio: 2.76, amp: 0.6, phase: 0.0),
|
||
/// (ratio: 5.40, amp: 0.4, phase: 0.0),
|
||
/// (ratio: 8.93, amp: 0.25, phase: 0.0),
|
||
/// ])
|
||
/// ```
|
||
///
|
||
/// - Parameters:
|
||
/// - partials: Array of `(ratio: Double, amp: Double, phase: Double)` tuples. Must not be empty.
|
||
/// `ratio` is a frequency multiplier (1.0 = one full cycle per buffer). `amp` scales the partial.
|
||
/// `phase` is added to the sine argument, in radians.
|
||
public func fillPartials(_ partials: [(ratio: Double, amp: Double, phase: Double)]) {
|
||
precondition(
|
||
channelCount == lyrebirdBufferMonoChannelCount,
|
||
"fillPartials(_:) requires a mono buffer; this buffer has channelCount == \(channelCount)."
|
||
)
|
||
precondition(!partials.isEmpty, "fillPartials(_:) requires at least one partial")
|
||
precondition(
|
||
_isValidForFill,
|
||
"fillPartials(_:) called on an invalidated LyrebirdBuffer"
|
||
)
|
||
|
||
let frames: Int = count
|
||
let framesDouble: Double = Double(frames)
|
||
let twoPi: Double = 2.0 * .pi
|
||
|
||
withMutableStorage { dst, n, _ in
|
||
var zero: Double = 0
|
||
vDSP_vfillD(&zero, dst, 1, vDSP_Length(n))
|
||
|
||
var partial: [Double] = [Double](repeating: 0, count: n)
|
||
partial.withUnsafeMutableBufferPointer { pptr in
|
||
guard let pbase: UnsafeMutablePointer<Double> = pptr.baseAddress else { return }
|
||
for p: (ratio: Double, amp: Double, phase: Double) in partials {
|
||
guard p.amp != 0 else { continue }
|
||
for i: Int in 0..<n {
|
||
pbase[i] = p.amp * sin(p.ratio * twoPi * Double(i) / framesDouble + p.phase)
|
||
}
|
||
vDSP_vaddD(dst, 1, pbase, 1, dst, 1, vDSP_Length(n))
|
||
}
|
||
}
|
||
|
||
// Normalise to peak 1.0
|
||
var peak: Double = 0
|
||
vDSP_maxmgvD(dst, 1, &peak, vDSP_Length(n))
|
||
if peak > 0 {
|
||
var scale: Double = 1.0 / peak
|
||
vDSP_vsmulD(dst, 1, &scale, dst, 1, vDSP_Length(n))
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Fill the buffer using the piano string inharmonicity model.
|
||
///
|
||
/// Each harmonic k has frequency ratio `k × √(1 + β × k²)`, where β is the inharmonicity
|
||
/// coefficient. At `β == 0` the spectrum is perfectly harmonic; increasing β stretches
|
||
/// the upper partials (realistic piano behaviour).
|
||
///
|
||
/// Suitable for piano, marimba, and bell-like timbres. The result is normalised to peak 1.0.
|
||
/// Requires a mono buffer.
|
||
///
|
||
/// - Parameters:
|
||
/// - fundamental: Fundamental frequency in Hz. Used to label the spectrum; does not affect
|
||
/// buffer sample rate. Must be > 0.
|
||
/// - beta: Inharmonicity coefficient (dimensionless). Typical piano values: 0.0001–0.01.
|
||
/// Must be ≥ 0. At 0 the result is a harmonic spectrum.
|
||
/// - amplitudes: Amplitude for each harmonic (index 0 = fundamental). The number of
|
||
/// partials equals `amplitudes.count`. Must not be empty.
|
||
public func fillInharmonicPartials(
|
||
fundamental: Double,
|
||
beta: Double,
|
||
amplitudes: [Double]
|
||
) {
|
||
precondition(
|
||
channelCount == lyrebirdBufferMonoChannelCount,
|
||
"fillInharmonicPartials(fundamental:beta:amplitudes:) requires a mono buffer; "
|
||
+ "this buffer has channelCount == \(channelCount)."
|
||
)
|
||
precondition(fundamental > 0, "fillInharmonicPartials: fundamental must be > 0, got \(fundamental)")
|
||
precondition(beta >= 0, "fillInharmonicPartials: beta must be ≥ 0, got \(beta)")
|
||
precondition(!amplitudes.isEmpty, "fillInharmonicPartials: amplitudes must not be empty")
|
||
// All-zero amplitudes: every partial is skipped, producing a silent (zero) buffer.
|
||
precondition(
|
||
_isValidForFill,
|
||
"fillInharmonicPartials(fundamental:beta:amplitudes:) called on an invalidated LyrebirdBuffer"
|
||
)
|
||
|
||
// Build the inharmonic partial list
|
||
var partialList: [(ratio: Double, amp: Double, phase: Double)] = []
|
||
partialList.reserveCapacity(amplitudes.count)
|
||
|
||
for (idx, amp) in amplitudes.enumerated() {
|
||
guard amp != 0 else { continue }
|
||
let k: Double = Double(idx + 1)
|
||
// Inharmonic frequency ratio: k × √(1 + β × k²)
|
||
let ratio: Double = k * (1.0 + beta * k * k).squareRoot()
|
||
partialList.append((ratio: ratio, amp: amp, phase: 0.0))
|
||
}
|
||
|
||
fillPartials(partialList.isEmpty ? [(ratio: 1.0, amp: 0.0, phase: 0.0)] : partialList)
|
||
}
|
||
}
|
||
|
||
// MARK: - Private helpers
|
||
|
||
/// Zeroth-order modified Bessel function of the first kind I₀(x).
|
||
///
|
||
/// Computed via the power-series definition (always converges for beta used in audio windows).
|
||
/// Accurate to < 1.6e-7 for all `x`.
|
||
@inline(__always)
|
||
private func _besselI0(_ x: Double) -> Double {
|
||
// Use the power-series definition (always converges, sufficient accuracy for window widths
|
||
// encountered in audio — beta ≤ ~20).
|
||
var sum: Double = 1.0
|
||
var term: Double = 1.0
|
||
let halfX: Double = x * 0.5
|
||
let maxBesselSeriesTerms: Int = 40
|
||
for k: Int in 1...maxBesselSeriesTerms {
|
||
term *= (halfX / Double(k)) * (halfX / Double(k))
|
||
sum += term
|
||
if term < sum * 1.0e-12 { break }
|
||
}
|
||
return sum
|
||
}
|
||
|
||
/// Lanczos σ factor for Gibbs suppression.
|
||
///
|
||
/// `σ(k, K) = sinc(k × π / K) = sin(k × π / K) / (k × π / K)`
|
||
@inline(__always)
|
||
private func _lanczosσ(
|
||
k: Double,
|
||
maxK: Double
|
||
) -> Double {
|
||
let arg: Double = k * .pi / maxK
|
||
guard arg != 0 else { return 1.0 }
|
||
return sin(arg) / arg
|
||
}
|
||
|
||
/// Foldback distortion — reflects `x` across the ±1 boundaries.
|
||
@inline(__always)
|
||
private func _foldback(_ input: Double) -> Double {
|
||
var x: Double = input
|
||
// Iterate reflections until within [-1, 1]
|
||
let maxFoldbackReflections: Int = 16
|
||
var iterations: Int = 0
|
||
while (x > 1.0 || x < -1.0) && iterations < maxFoldbackReflections {
|
||
if x > 1.0 {
|
||
x = 2.0 - x
|
||
} else if x < -1.0 {
|
||
x = -2.0 - x
|
||
}
|
||
iterations += 1
|
||
}
|
||
return x
|
||
}
|