Files
Lyrebird/Sources/Lyrebird/Generators/Panning/AmbiDecoder1.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

243 lines
9.4 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.
// AmbiDecoder1.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdDSP
/// 1st-order B-format Ambisonics decoder.
///
/// Takes any 4-row Generator (channels ordered [W, X, Y, Z]) and decodes it to an
/// arbitrary number of loudspeakers. The typical input is an `AmbiEncoder1`; manual
/// B-format injection via `GeneratorArray([w, x, y, z])` of mono components is also
/// supported (a 4-element `GeneratorArray` reports `outputChannelCount == 4`).
///
/// ## Decode formula
///
/// For each speaker k at (az_k, el_k):
/// ```
/// output_k = (1/√2)×W + cos(az_k)×cos(el_k)×X + sin(az_k)×cos(el_k)×Y + sin(el_k)×Z
/// ```
///
/// The decode matrix is computed once at `init` from the speaker positions and never
/// modified at runtime — no RT allocation.
///
/// ## Speaker positions
///
/// Positions are in radians, following the same convention as `AmbiEncoder1`:
/// - `az`: 0 = front, π/2 = left, −π/2 = right
/// - `el`: 0 = horizontal, π/2 = above, −π/2 = below
///
/// ## Output
///
/// `speakers.count` channels. Wire via `output(buses:source:)` to write all speakers at
/// once, or extract individual speaker feeds inline using the `[n]` subscript:
///
/// ```swift
/// let enc = AmbiEncoder1(input: source, azimuth: az, elevation: el)
/// let dec = AmbiDecoder1(input: enc, speakers: quadspeakers)
///
/// // Route all speakers:
/// output(buses: Array(0..<4), source: dec)
///
/// // Route individual speakers with per-speaker processing:
/// output(bus: 0, source: dec[0] * frontGain) // L-front
/// output(bus: 1, source: dec[1] * frontGain) // R-front
/// output(bus: 2, source: dec[2]) // R-rear
/// output(bus: 3, source: dec[3]) // L-rear
/// ```
///
/// ```swift
/// let enc = AmbiEncoder1(input: source, azimuth: az, elevation: el)
///
/// // Stereo (L/R) decode:
/// let dec = AmbiDecoder1(
/// input: enc,
/// speakers: [(az: .pi / 2, el: 0), // L (90° left)
/// (az: -.pi / 2, el: 0)] // R (90° right)
/// )
///
/// // Quad decode (hand-written):
/// let quad = AmbiDecoder1(
/// input: enc,
/// speakers: [(az: 3 * .pi / 4, el: 0), // L-front
/// (az: .pi / 4, el: 0), // R-front
/// (az: -.pi / 4, el: 0), // R-rear
/// (az: -3 * .pi / 4, el: 0)] // L-rear
/// )
/// ```
///
/// For the common symmetric rigs (quad / hexagon / octagon / cube / double-hexagon /
/// double-octagon), use `AmbiSpeakerLayout` to build the speaker array:
///
/// ```swift
/// let quad = AmbiDecoder1(input: enc, speakers: AmbiSpeakerLayout.quad())
/// let oct = AmbiDecoder1(input: enc, speakers: AmbiSpeakerLayout.octagon())
/// let cube = AmbiDecoder1(input: enc,
/// speakers: AmbiSpeakerLayout.cube(elevation: .pi / 6))
/// // Arbitrary stack — 7 vertices, 2 layers:
/// let rig = AmbiDecoder1(
/// input: enc,
/// speakers: AmbiSpeakerLayout.stackedRings(vertices: 7, layers: 2,
/// elevation: .pi / 6)
/// )
/// ```
///
/// ## Manual B-format
///
/// For testing or static-coefficient scenarios, build a 4-row source explicitly with
/// `GeneratorArray`:
///
/// ```swift
/// let bformat = GeneratorArray([w, x, y, z]) // each a mono Generator
/// let dec = AmbiDecoder1(input: bformat, speakers: quadspeakers)
/// ```
///
/// - Parameters:
/// - input: 4-row B-format source [W, X, Y, Z]. Any Generator with
/// `outputChannelCount == 4` is accepted (typically an `AmbiEncoder1`,
/// or a `GeneratorArray([w, x, y, z])` of mono components).
/// - speakers: Loudspeaker positions (azimuth, elevation) in radians.
/// - mul: Output multiplier applied after synthesis. Defaults to `1.0`.
/// - add: Offset added after multiplier. Defaults to `0.0`.
public final class AmbiDecoder1: GeneratorBase, AudioGenerator {
// MARK: - Input
private let _input: any Generator
// MARK: - Decode matrix: flat [speakerCount × 4] — stride 4: [wWeight, xWeight, yWeight, zWeight]
// Flat layout eliminates ARC retain/release on nested-array element access on the RT thread.
private let _decodeMatrix: [Double]
private let _speakerCount: Int
// MARK: - vDSP_mmulD scratch buffers (pre-allocated in init, never resized)
/// Row-major B-format block: 4 rows × lyrebirdDefaultResultBufferSize cols.
/// Packed from W/X/Y/Z arrays with stride = count before each matrix multiply.
private var _bformatMatrix: [Double]
/// Row-major flat decode output: speakerCount rows × lyrebirdDefaultResultBufferSize cols.
/// Unpacked back into _result after each matrix multiply.
private var _flatDecodeResult: [Double]
// MARK: - Output buffer
public override var outputChannelCount: Int { _speakerCount }
// MARK: - Fan-out cache (Generator protocol)
private let _mulAdd: MulAddSpec
// MARK: - Init
/// - Parameters:
/// - input: 4-row B-format source [W, X, Y, Z]. Any Generator with
/// `outputChannelCount == 4` is accepted (typically an `AmbiEncoder1`,
/// or a `GeneratorArray([w, x, y, z])` of mono components).
/// - speakers: Loudspeaker positions (azimuth, elevation) in radians.
/// - mul: Output multiplier applied after synthesis. Defaults to `1.0`.
/// - add: Offset added after multiplier. Defaults to `0.0`.
public init(
input: any Generator,
speakers: [(az: Double, el: Double)],
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
precondition(
input.outputChannelCount == 4,
"AmbiDecoder1: input must have outputChannelCount == 4 (W, X, Y, Z), "
+ "got \(input.outputChannelCount)"
)
precondition(
!speakers.isEmpty,
"AmbiDecoder1: speakers array must not be empty"
)
_input = input
_speakerCount = speakers.count
// Pre-compute flat decode matrix at init (not RT): row k = [wW, wX, wY, wZ].
// Flat [Double] avoids ARC retain/release on nested-array subscripts on RT thread.
var matrix: [Double] = [Double]()
matrix.reserveCapacity(speakers.count * 4)
for sp: (az: Double, el: Double) in speakers {
matrix.append(ambi1WScale)
matrix.append(cos(sp.az) * cos(sp.el))
matrix.append(sin(sp.az) * cos(sp.el))
matrix.append(sin(sp.el))
}
_decodeMatrix = matrix
let bufSize: Int = lyrebirdDefaultResultBufferSize
_bformatMatrix = [Double](repeating: 0, count: 4 * bufSize)
_flatDecodeResult = [Double](repeating: 0, count: speakers.count * bufSize)
_mulAdd = MulAddSpec(mul: mul, add: add)
super.init(channels: speakers.count)
}
// MARK: - Compute
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
let bformat: [[Double]] = _input.calculatedSamples(graph: graph, count: count)
guard bformat.count == 4 else { return _result }
// Pack W/X/Y/Z into a row-major (4 × count) matrix for vDSP_mmulD.
// Row stride = count so the layout matches what vDSP_mmulD expects.
_bformatMatrix.withUnsafeMutableBufferPointer { bfm in
guard let bfmBase: UnsafeMutablePointer<Double> = bfm.baseAddress else { return }
for (row, channel) in bformat.enumerated() {
channel.withUnsafeBufferPointer { src in
guard let srcBase: UnsafePointer<Double> = src.baseAddress else { return }
(bfmBase + row * count).update(from: srcBase, count: count)
}
}
}
// Decode: _flatDecodeResult[speakerCount × count]
// = _decodeMatrix[speakerCount × 4] × _bformatMatrix[4 × count]
_decodeMatrix.withUnsafeBufferPointer { mat in
_bformatMatrix.withUnsafeBufferPointer { bfm in
_flatDecodeResult.withUnsafeMutableBufferPointer { out in
guard let matBase: UnsafePointer<Double> = mat.baseAddress,
let bfmBase: UnsafePointer<Double> = bfm.baseAddress,
let outBase: UnsafeMutablePointer<Double> = out.baseAddress else { return }
vDSP_mmulD(matBase, 1,
bfmBase, 1,
outBase, 1,
vDSP_Length(_speakerCount),
vDSP_Length(count),
4)
}
}
}
// Unpack flat result back into per-speaker _result channels.
_flatDecodeResult.withUnsafeBufferPointer { flat in
guard let flatBase: UnsafePointer<Double> = flat.baseAddress else { return }
for k: Int in 0..<_speakerCount {
_result[k].withUnsafeMutableBufferPointer { dst in
guard let dstBase: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
dstBase.update(from: flatBase + k * count, count: count)
}
}
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
}
// MARK: - GeneratorEnum
// `GeneratorEnum` conformance is intentionally omitted — this is an Audio-only
// generator with no paired `Control` variant.