Files
Lyrebird/Sources/Lyrebird/Generators/BusIO/MixIn.swift
T
2026-06-01 18:27:40 -07:00

146 lines
6.1 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.
// MixIn.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Accelerate
/// Multi-source audio-bus summing generator.
///
/// Reads N `AudioBus` slots (possibly non-contiguous indices) and sums them
/// channel-wise into a single output. Replaces the `signal + In.Audio(bus:) + …`
/// accumulator pattern used at the head of input-conditioning chains
/// (e.g. mixing N input synth buses into a recorder + limiter).
///
/// ## Why
///
/// Chaining N `In.Audio` nodes with `+` builds (N − 1) `BinaryOpGenerator.Audio`
/// add nodes, each with its own pre-allocated `_result` and its own `MulAdd` pass.
/// `MixIn.Audio` collapses the chain to a single node: one `_result`, one tight
/// summation loop. Bus indices need not be contiguous, so this covers the case
/// where `In.Audio(bus: 5, channels: N)` (consecutive-bus read) does not apply.
///
/// ## Multi-channel
///
/// All buses must have the same `channelCount`. The output's `outputChannelCount`
/// equals that shared channel count. Per-channel sums happen across all buses
/// (i.e. channel 0 of every bus is summed, channel 1 of every bus is summed, etc.).
///
/// ## RT-allocation model
///
/// Buses, channel count, and `MulAddSpec` are captured in `init`. `_result` is
/// pre-allocated by `GeneratorBase`. No heap allocation in `_computeSamples`.
///
/// ## Usage
///
/// ```swift
/// // Mix four mono input buses into a mono signal:
/// let mix = MixIn.Audio(buses: [b0, b1, b2, b3])
///
/// // Mix three stereo buses with a 0.5 output scale:
/// let mix = MixIn.Audio(buses: [bL, bM, bR], mul: 0.5)
/// ```
///
/// `GeneratorEnum` conformance is intentionally omitted — this is an Audio-only
/// generator with no paired `Control` variant. Control-bus mixing is not a
/// meaningful workflow at this time (`In.Control` already supports
/// contiguous-bus multi-channel reads).
///
/// - Parameters:
/// - buses: Non-empty array of `AudioBus` slots to sum. Indices need not be
/// contiguous. All buses must share `channelCount`; mismatched
/// channel counts trap at `init`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public enum MixIn {
/// Audio-rate multi-bus summer. See ``MixIn`` for the design overview.
///
/// - Parameters:
/// - buses: Non-empty array of `AudioBus` slots to sum. Indices need not be
/// contiguous. All buses must share `channelCount`; mismatched
/// channel counts trap at `init`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public final class Audio: GeneratorBase, AudioGenerator {
private let _buses: [AudioBus]
private let _chCount: Int
private let _mulAdd: MulAddSpec
public override var outputChannelCount: Int { _chCount }
/// - Parameters:
/// - buses: Non-empty array of `AudioBus` slots to sum. Indices need not be
/// contiguous. All buses must share `channelCount`; mismatched
/// channel counts trap at `init`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public init(
buses: [AudioBus],
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
precondition(!buses.isEmpty, "MixIn.Audio: buses array must be non-empty")
let firstChannelCount: Int = buses[0].channelCount
for b: AudioBus in buses {
precondition(
b.channelCount == firstChannelCount,
"MixIn.Audio: all buses must have the same channelCount; "
+ "got \(b.channelCount) at bus index \(b.index), expected \(firstChannelCount)"
)
}
_buses = buses
_chCount = firstChannelCount
_mulAdd = MulAddSpec(mul: mul, add: add)
super.init(channels: firstChannelCount)
}
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
guard count > 0 else { return _result }
let offset: Int = graph.busOffset
precondition(offset + count <= graph.engine.blockSize)
let chCount: Int = _chCount
let numAudioBuses: Int = graph.engine.numAudioBuses
// Zero output rows before accumulation.
for ch: Int in 0..<chCount {
_result[ch].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
vDSP_vclrD(dstP, 1, vDSP_Length(count))
}
}
// Sum each bus into `_result` channel-by-channel. Subscript directly
// inside `withUnsafeBufferPointer` to avoid a local `[Float]` retain
// on the RT path (matches `In.Audio`).
for b: AudioBus in _buses {
for ch: Int in 0..<chCount {
let busIdx: Int = b.index + ch
guard busIdx >= 0 && busIdx < numAudioBuses else { continue }
graph.engine.audioBuses[busIdx].withUnsafeBufferPointer { (src: UnsafeBufferPointer<Float>) in
guard let srcBase: UnsafePointer<Float> = src.baseAddress else { return }
precondition(offset + count <= src.count)
_result[ch].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
for i: Int in 0..<count {
dstP[i] += Double(srcBase[offset + i])
}
}
}
}
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
}
}