51 lines
1.8 KiB
Swift
51 lines
1.8 KiB
Swift
// CubicInterpolation.swift
|
||
// Lyrebird
|
||
//
|
||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||
// SPDX-License-Identifier: MIT
|
||
|
||
// MARK: - Catmull-Rom cubic kernel
|
||
|
||
/// Named coefficients of the 4-point Catmull-Rom cubic kernel (expanded form).
|
||
/// `2` is omitted — it is exempt from the named-constant rule and reads clearly
|
||
/// inline (`2 * p0`, `2 * pM1`).
|
||
private let catmullRomHalf: Double = 0.5
|
||
private let catmullRomFive: Double = 5.0
|
||
private let catmullRomFour: Double = 4.0
|
||
private let catmullRomThree: Double = 3.0
|
||
|
||
/// 4-point Catmull-Rom cubic interpolation.
|
||
///
|
||
/// Returns the spline value at `t ∈ [0, 1]` on the segment between `p0` and `p1`,
|
||
/// using the surrounding samples `pM1` (before `p0`) and `p2` (after `p1`):
|
||
///
|
||
/// ```
|
||
/// p(t) = 0.5 · ( 2·p0
|
||
/// + (−pM1 + p1)·t
|
||
/// + (2·pM1 − 5·p0 + 4·p1 − p2)·t²
|
||
/// + (−pM1 + 3·p0 − 3·p1 + p2)·t³ )
|
||
/// ```
|
||
///
|
||
/// This is the single source of the cubic kernel shared by every interpolated
|
||
/// reader in the framework — table-lookup oscillators (`OscSin`, `OscTable`,
|
||
/// `oscillatorTableReadCubic`), buffer playback (`PlayBuffer`), the chaotic
|
||
/// oscillators (`chaoticInterpolate`), and the fractional-delay lines
|
||
/// (`DelayLine`, `DelayLineFeedback`, `CombFilter`, `AllpassFilter`).
|
||
/// `@inline(__always)` so the generated code matches the previous hand-inlined form.
|
||
@inline(__always)
|
||
@_spi(LyrebirdExtensions)
|
||
public func catmullRomCubic(
|
||
_ pM1: Double,
|
||
_ p0: Double,
|
||
_ p1: Double,
|
||
_ p2: Double,
|
||
t: Double
|
||
) -> Double {
|
||
let t2: Double = t * t
|
||
let t3: Double = t2 * t
|
||
return catmullRomHalf * ((2 * p0)
|
||
+ (-pM1 + p1) * t
|
||
+ (2 * pM1 - catmullRomFive * p0 + catmullRomFour * p1 - p2) * t2
|
||
+ (-pM1 + catmullRomThree * p0 - catmullRomThree * p1 + p2) * t3)
|
||
}
|