Files
Lyrebird/Sources/Lyrebird/Buses/ScratchBuses.swift
T
2026-06-01 18:27:40 -07:00

146 lines
6.4 KiB
Swift

// ScratchBuses.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Accelerate
/// Per-child scratch audio bus memory for `ParallelGroup` concurrent evaluation.
///
/// Each child in a `ParallelGroup` gets its own `ScratchBuses` instance pre-allocated
/// at `ParallelGroup.build()` time. `Out.Audio` writes into these scratch buses instead
/// of `engine.audioBuses` during concurrent evaluation. After all children complete,
/// `ParallelGroup.evaluate` sums all scratch slots into the real `engine.audioBuses`
/// via `vDSP_vadd`.
///
/// Never resized after allocation — all memory is owned for the lifetime of the parent
/// `ParallelGroup`.
final class ScratchBuses {
/// Per-bus Float sample buffers: `[busIndex][sampleIndex]`, sized to `blockSize`.
var buses: [[Float]]
/// Per-child Double→Float conversion buffer.
///
/// Each `ScratchBuses` owns its own conversion scratch so concurrent children
/// don't race on the shared `SynthesisEngine._busAccumulateScratch`.
private var conversionScratch: [Float]
/// Per-bus dirty mask used by `ParallelGroup` to skip the clear+merge passes
/// on buses no child wrote. `accumulate` sets `dirty[bus] = true` on every
/// write; `clearDirtyBuses(offset:count:)` wipes the dirty range and resets
/// the mask to all-false; the merge pass walks the post-evaluation set.
/// Pre-allocated to `numBuses`; never resized.
var dirty: [Bool]
let numBuses: Int
let blockSize: Int
init(
numBuses: Int,
blockSize: Int
) {
self.numBuses = numBuses
self.blockSize = blockSize
self.buses = [[Float]](
repeating: [Float](repeating: 0, count: blockSize),
count: numBuses
)
self.conversionScratch = [Float](repeating: 0, count: blockSize)
self.dirty = [Bool](repeating: false, count: numBuses)
}
/// Zero `count` samples at `offset` for every bus currently marked dirty,
/// then reset the dirty mask. Buses that no child wrote (`dirty[i] == false`)
/// are skipped — their scratch range is already zero from the previous
/// `clearDirtyBuses` or initialization. After this call returns, the mask
/// is all-false and ready to accumulate this segment's writes.
func clearDirtyBuses(
offset: Int,
count: Int
) {
let n: vDSP_Length = vDSP_Length(count)
for i: Int in 0..<numBuses {
if !dirty[i] { continue }
buses[i].withUnsafeMutableBufferPointer { buf in
guard let base: UnsafeMutablePointer<Float> = buf.baseAddress else { return }
vDSP_vclr(base.advanced(by: offset), 1, n)
}
dirty[i] = false
}
}
/// Convert `count` `Double` (Double) samples to Float and accumulate into `bus`
/// starting at `offset`. Equivalent to the batch `SynthesisEngine.addToAudioBus` path
/// but writes into this scratch slot instead of engine memory. Marks `bus` dirty
/// so the next `clearDirtyBuses` + merge pass touch it.
///
/// Concurrent safety: `ParallelGroup` gives each child its own `ScratchBuses`
/// instance (`scratchSlots[i]` only ever appears in iteration `i` of the
/// `concurrentPerform`), so the per-bus `dirty[bus] = true` store here is
/// race-free even when N>1 workers call `accumulate` simultaneously on
/// distinct slots.
func accumulate(
_ samples: [Double],
bus: Int,
offset: Int,
count: Int
) {
assert(bus >= 0 && bus < numBuses,
"ScratchBuses.accumulate: bus \(bus) out of range [0, \(numBuses))")
assert(offset + count <= blockSize,
"ScratchBuses.accumulate: offset \(offset) + count \(count) exceeds blockSize \(blockSize)")
dirty[bus] = true
let n: vDSP_Length = vDSP_Length(count)
samples.withUnsafeBufferPointer { src in
guard let srcBase: UnsafePointer<Double> = src.baseAddress else { return }
conversionScratch.withUnsafeMutableBufferPointer { conv in
guard let convBase: UnsafeMutablePointer<Float> = conv.baseAddress else { return }
vDSP_vdpsp(srcBase, 1, convBase, 1, n)
buses[bus].withUnsafeMutableBufferPointer { dst in
guard let dstBase: UnsafeMutablePointer<Float> = dst.baseAddress else { return }
vDSP_vadd(convBase, 1,
dstBase.advanced(by: offset), 1,
dstBase.advanced(by: offset), 1,
n)
}
}
}
}
/// Overwrite `count` samples into this child's scratch slot starting at `offset`.
/// Called by `ReplaceOut.Audio` when the synth runs inside a `ParallelGroup`.
///
/// - Important: This overwrites only **this child's scratch slot**, not the
/// engine's bus. The merge pass at end of the parallel group still adds
/// this slot's content to the engine bus alongside other siblings. Inside
/// a `ParallelGroup`, ReplaceOut therefore sets *this child's contribution*
/// to the given signal — it does not scrub other siblings' writes nor any
/// pre-existing engine-bus content. Outside a `ParallelGroup`, ReplaceOut
/// routes through `engine.setAudioBus` and does scrub prior writes.
func replace(
_ samples: [Double],
bus: Int,
offset: Int,
count: Int
) {
assert(bus >= 0 && bus < numBuses,
"ScratchBuses.replace: bus \(bus) out of range [0, \(numBuses))")
assert(offset + count <= blockSize,
"ScratchBuses.replace: offset \(offset) + count \(count) exceeds blockSize \(blockSize)")
let n: vDSP_Length = vDSP_Length(count)
samples.withUnsafeBufferPointer { src in
guard let srcBase: UnsafePointer<Double> = src.baseAddress else { return }
buses[bus].withUnsafeMutableBufferPointer { dst in
guard let dstBase: UnsafeMutablePointer<Float> = dst.baseAddress else { return }
// Convert Double → Float directly into the scratch slice.
vDSP_vdpsp(srcBase, 1, dstBase.advanced(by: offset), 1, n)
// Mark dirty only after a real write — empty/null buffer pointers
// bail out via the guards above without marking the bus.
dirty[bus] = true
}
}
}
}