Files
Lyrebird/Sources/Lyrebird/Buffers/WavetableSet.swift
T
josh b6fdee8bfc Lyrebird 2.0.0 — Linux support
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>
2026-09-10 21:09:11 -07:00

204 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.
// WavetableSet.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdDSP
import Foundation
// MARK: - WavetableSet
/// An immutable ordered collection of `LyrebirdBuffer` wavetables.
///
/// `WavetableSet` provides factory methods for morphing sets (interpolated between two
/// source tables), phase-rotated sets, and partial-matrix spectral sets.
///
/// Each buffer in the set has the same `count` (frame count). All buffers are mono
/// (`channelCount == 1`), ready for direct use with `OscTable.Audio`.
///
/// ## Usage
///
/// ```swift
/// // Morph from sine → sawtooth in 8 steps
/// let sine = LyrebirdBuffer(count: 32768); sine.fillSine()
/// let saw = LyrebirdBuffer(count: 32768); saw.fill(partials: 32)
/// let set = WavetableSet.interpolating(from: sine, to: saw, steps: 8)
/// ```
public struct WavetableSet {
/// The ordered array of wavetables.
public let buffers: [LyrebirdBuffer]
/// Number of tables in the set.
public var count: Int { buffers.count }
/// Frame count of each table.
public var tableSize: Int { buffers.first.map { $0.count } ?? 0 }
/// Creates a `WavetableSet` wrapping an existing array of buffers.
///
/// - Parameter buffers: Non-empty array of mono `LyrebirdBuffer`s, all the same length.
/// Precondition-traps if the array is empty or any buffer has `channelCount != 1`.
public init(buffers: [LyrebirdBuffer]) {
precondition(!buffers.isEmpty, "WavetableSet: buffers must not be empty")
let size: Int = buffers[0].count
for (i, buf) in buffers.enumerated() {
precondition(
buf.channelCount == lyrebirdBufferMonoChannelCount,
"WavetableSet: buffer[\(i)] must be mono (channelCount == 1)"
)
precondition(
buf.count == size,
"WavetableSet: all buffers must have the same count; "
+ "buffer[0].count == \(size) but buffer[\(i)].count == \(buf.count)"
)
}
self.buffers = buffers
}
// MARK: - Factory: interpolating
/// Creates a set of `steps` tables by linearly interpolating between `from` and `to`.
///
/// - Parameters:
/// - from: Source table (index 0). Must be mono.
/// - to: Destination table (index `steps − 1`). Must be mono and the same `count` as `from`.
/// - steps: Number of tables to produce, including `from` (at α=0) and `to` (at α=1).
/// Must be ≥ 2.
/// - Returns: A `WavetableSet` of `steps` tables.
public static func interpolating(
from: LyrebirdBuffer,
to: LyrebirdBuffer,
steps: Int
) -> WavetableSet {
precondition(steps >= 2, "WavetableSet.interpolating: steps must be ≥ 2, got \(steps)")
precondition(
from.channelCount == lyrebirdBufferMonoChannelCount,
"WavetableSet.interpolating: 'from' buffer must be mono"
)
precondition(
to.channelCount == lyrebirdBufferMonoChannelCount,
"WavetableSet.interpolating: 'to' buffer must be mono"
)
precondition(
from.count == to.count,
"WavetableSet.interpolating: 'from' and 'to' must have the same count; "
+ "from.count == \(from.count), to.count == \(to.count)"
)
let tableSize: Int = from.count
let stepCount: Double = Double(steps - 1)
var tables: [LyrebirdBuffer] = []
tables.reserveCapacity(steps)
var tempA: [Double] = [Double](repeating: 0, count: tableSize)
for step: Int in 0..<steps {
let alpha: Double = Double(step) / stepCount
let oneMinusAlpha: Double = 1.0 - alpha
let buf: LyrebirdBuffer = LyrebirdBuffer(count: tableSize)
buf.withMutableStorage { dst, frames, _ in
from.withStorage { srcA, _, _ in
to.withStorage { srcB, _, _ in
// dst = srcA * (1 - alpha) + srcB * alpha
// dst = srcA * scalarA + srcB * scalarB via vDSP_vsmul + vDSP_vsma
var scalarA: Double = oneMinusAlpha
var scalarB: Double = alpha
let n: vDSP_Length = vDSP_Length(frames)
tempA.withUnsafeMutableBufferPointer { tptrA in
guard let tbaseA: UnsafeMutablePointer<Double> = tptrA.baseAddress else { return }
vDSP_vsmulD(srcA, 1, &scalarA, tbaseA, 1, n)
// dst = srcB * scalarB + tempA
vDSP_vsmaD(srcB, 1, &scalarB, tbaseA, 1, dst, 1, n)
}
}
}
}
tables.append(buf)
}
return WavetableSet(buffers: tables)
}
// MARK: - Factory: rotatingPhases
/// Creates a set of `steps` tables by rotating the phase of `buffer` across a full cycle.
///
/// Table `i` contains the source waveform shifted by `i / steps × 2π` radians.
/// This is achieved by computing the phase of each partial, rotating it, then re-synthesising.
/// For a single-cycle waveform the rotation is equivalent to a time-domain circular shift.
///
/// - Parameters:
/// - buffer: Source mono wavetable.
/// - steps: Number of tables (phases) to produce. Must be ≥ 1.
/// - Returns: A `WavetableSet` of `steps` tables.
public static func rotatingPhases(
buffer: LyrebirdBuffer,
steps: Int
) -> WavetableSet {
precondition(steps >= 1, "WavetableSet.rotatingPhases: steps must be ≥ 1, got \(steps)")
precondition(
buffer.channelCount == lyrebirdBufferMonoChannelCount,
"WavetableSet.rotatingPhases: buffer must be mono"
)
let tableSize: Int = buffer.count
var tables: [LyrebirdBuffer] = []
tables.reserveCapacity(steps)
for step: Int in 0..<steps {
let phaseOffset: Double = Double(step) / Double(steps) // [0, 1)
let buf: LyrebirdBuffer = LyrebirdBuffer(count: tableSize)
buf.withMutableStorage { dst, frames, _ in
// Circular shift: dst[i] = src[(i + shift) % frames]
let shift: Int = Int(phaseOffset * Double(frames)) % frames
buffer.withStorage { src, _, _ in
for i: Int in 0..<frames {
let srcIndex: Int = (i + shift) % frames
dst[i] = src[srcIndex]
}
}
}
tables.append(buf)
}
return WavetableSet(buffers: tables)
}
// MARK: - Factory: fromPartialMatrix
/// Creates a set of tables from a 2-D partial-amplitude matrix.
///
/// Each row in `partials` defines one table as an array of harmonic amplitudes
/// (index 0 = DC/fundamental, index k = (k+1)th harmonic). Tables are synthesised
/// using additive sine summation with unit phases.
///
/// - Parameters:
/// - partials: 2-D array `[tableIndex][harmonicIndex]`. All inner arrays must have
/// the same length. Must not be empty.
/// - tableSize: Frame count for each output buffer. Defaults to `lyrebirdDefaultTableSize`.
/// - Returns: A `WavetableSet` whose `count` equals `partials.count`.
public static func fromPartialMatrix(
partials: [[Double]],
tableSize: Int = lyrebirdDefaultTableSize
) -> WavetableSet {
precondition(!partials.isEmpty, "WavetableSet.fromPartialMatrix: partials must not be empty")
let harmonicCount: Int = partials[0].count
for (i, row) in partials.enumerated() {
precondition(
row.count == harmonicCount,
"WavetableSet.fromPartialMatrix: all rows must have the same length; "
+ "row[0].count == \(harmonicCount) but row[\(i)].count == \(row.count)"
)
}
let tables: [LyrebirdBuffer] = partials.map { amps in
let buf: LyrebirdBuffer = LyrebirdBuffer(count: tableSize)
buf.fill(harmonics: Array(1...amps.count), amplitudes: amps)
return buf
}
return WavetableSet(buffers: tables)
}
}