163 lines
7.0 KiB
Swift
163 lines
7.0 KiB
Swift
// BusAllocator.swift
|
|
// Lyrebird
|
|
//
|
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
/// Language-side bus allocation for `SynthesisEngine` audio and control buses.
|
|
///
|
|
/// `BusAllocator` tracks which buses are free and allocates contiguous blocks on request.
|
|
/// Hardware output and input buses are pre-marked as in-use at init time.
|
|
///
|
|
/// **Thread safety:** protected by an internal `NSLock`; safe to call from any language-side
|
|
/// thread. Never call from the RT audio thread — lock acquisition is not RT-safe.
|
|
|
|
import Foundation
|
|
|
|
/// Language-side allocator for audio and control buses on a `SynthesisEngine`.
|
|
///
|
|
/// Hardware output and input audio buses are pre-marked in-use at init.
|
|
/// Control buses have no hardware reservation.
|
|
///
|
|
/// **Thread safety:** protected by an internal `NSLock`. Safe to call from any language-side
|
|
/// thread. Never call from the RT audio thread — lock acquisition is not RT-safe.
|
|
public final class BusAllocator: @unchecked Sendable {
|
|
// Sendable invariant: all mutable state (`audioFreeList`, `controlFreeList`) is
|
|
// serialised by `_lock`. Reads of immutable `let` storage do not need the lock.
|
|
|
|
private var audioFreeList: [Bool]
|
|
private var controlFreeList: [Bool]
|
|
private var hardwareAudioEnd: Int
|
|
private let _lock: NSLock = NSLock()
|
|
|
|
/// Internal — constructed only by `SynthesisEngine`.
|
|
init(
|
|
numAudioBuses: Int,
|
|
numControlBuses: Int,
|
|
numOutputChannels: Int,
|
|
numInputChannels: Int
|
|
) {
|
|
audioFreeList = [Bool](repeating: true, count: numAudioBuses)
|
|
controlFreeList = [Bool](repeating: true, count: numControlBuses)
|
|
hardwareAudioEnd = numOutputChannels + numInputChannels
|
|
|
|
for i: Int in 0..<min(hardwareAudioEnd, numAudioBuses) {
|
|
audioFreeList[i] = false
|
|
}
|
|
}
|
|
|
|
/// Resets the audio bus free list and re-applies the hardware reservation
|
|
/// for the supplied output / input channel counts.
|
|
///
|
|
/// Invoked by ``SynthesisEngine`` when its `numOutputChannels` /
|
|
/// `numInputChannels` are mutated while the engine is stopped. Any audio
|
|
/// bus allocations issued prior to this call are invalidated — the
|
|
/// corresponding ``AudioBus`` handles still exist on the caller side but
|
|
/// their slots are no longer reserved.
|
|
///
|
|
/// Control bus allocations are **not** touched: control buses have no
|
|
/// hardware reservation and are independent of audio channel counts.
|
|
///
|
|
/// Non-RT, language-side only.
|
|
internal func _reconfigureHardwareReservation(
|
|
numOutputChannels: Int,
|
|
numInputChannels: Int
|
|
) {
|
|
_lock.withLock {
|
|
for i: Int in 0..<audioFreeList.count { audioFreeList[i] = true }
|
|
hardwareAudioEnd = numOutputChannels + numInputChannels
|
|
for i: Int in 0..<min(hardwareAudioEnd, audioFreeList.count) {
|
|
audioFreeList[i] = false
|
|
}
|
|
}
|
|
}
|
|
|
|
// MARK: - Public allocate / release API
|
|
|
|
/// Allocates the first contiguous block of `channelCount` free audio buses.
|
|
/// Throws `BusAllocatorError.noFreeBus` if no block of that size is available.
|
|
public func allocateAudioBus(channelCount: Int) throws -> AudioBus {
|
|
let index: Int = try _allocate(in: &audioFreeList, channelCount: channelCount)
|
|
return AudioBus(index: index, channelCount: channelCount)
|
|
}
|
|
|
|
/// Releases a previously allocated audio bus block back to the free pool.
|
|
/// Hardware buses (output + input channels) are silently ignored.
|
|
/// Calling twice for the same bus is a programming error (asserted in debug builds).
|
|
public func releaseAudioBus(_ bus: AudioBus) {
|
|
// `hardwareAudioEnd` is mutated by `_reconfigureHardwareReservation`
|
|
// under `_lock`. Pass a sentinel and let `_release` read the live value
|
|
// inside the same lock acquisition.
|
|
_release(in: &audioFreeList, bus.index, channelCount: bus.channelCount,
|
|
honoursHardwareReservation: true, label: "audio")
|
|
}
|
|
|
|
/// Allocates the first contiguous block of `channelCount` free control buses.
|
|
/// Throws `BusAllocatorError.noFreeBus` if no block of that size is available.
|
|
public func allocateControlBus(channelCount: Int = 1) throws -> ControlBus {
|
|
let index: Int = try _allocate(in: &controlFreeList, channelCount: channelCount)
|
|
return ControlBus(index: index, channelCount: channelCount)
|
|
}
|
|
|
|
/// Releases a previously allocated control bus block back to the free pool.
|
|
/// Calling twice for the same bus is a programming error (asserted in debug builds).
|
|
public func releaseControlBus(_ bus: ControlBus) {
|
|
_release(in: &controlFreeList, bus.index, channelCount: bus.channelCount,
|
|
honoursHardwareReservation: false, label: "control")
|
|
}
|
|
|
|
// MARK: - Generic allocate / release helpers
|
|
|
|
/// First-fit contiguous-block allocator on a free-list of booleans. Marks the chosen
|
|
/// `channelCount` slots as in-use and returns the start index. Throws on no-free-block.
|
|
private func _allocate(
|
|
in freeList: inout [Bool],
|
|
channelCount: Int
|
|
) throws -> Int {
|
|
precondition(channelCount >= 1, "BusAllocator: channelCount must be >= 1")
|
|
return try _lock.withLock {
|
|
let n: Int = freeList.count
|
|
guard channelCount <= n else {
|
|
throw BusAllocatorError.noFreeBus(channelCount: channelCount)
|
|
}
|
|
var start: Int = 0
|
|
outer: while start <= n - channelCount {
|
|
for i: Int in start..<(start + channelCount) {
|
|
if !freeList[i] {
|
|
start = i + 1
|
|
continue outer
|
|
}
|
|
}
|
|
for i: Int in start..<(start + channelCount) {
|
|
freeList[i] = false
|
|
}
|
|
return start
|
|
}
|
|
throw BusAllocatorError.noFreeBus(channelCount: channelCount)
|
|
}
|
|
}
|
|
|
|
/// Marks `[startIndex, startIndex + channelCount)` slots back to free. When
|
|
/// `honoursHardwareReservation` is `true` the current `hardwareAudioEnd`
|
|
/// (read under the same lock acquisition that performs the release) acts
|
|
/// as the floor — slots below it are silently skipped. Double-release on
|
|
/// non-reserved slots is asserted in debug builds.
|
|
private func _release(
|
|
in freeList: inout [Bool],
|
|
_ startIndex: Int,
|
|
channelCount: Int,
|
|
honoursHardwareReservation: Bool,
|
|
label: String
|
|
) {
|
|
guard channelCount > 0, startIndex >= 0 else { return }
|
|
_lock.withLock {
|
|
let minIndex: Int = honoursHardwareReservation ? hardwareAudioEnd : 0
|
|
for i: Int in startIndex..<(startIndex + channelCount) {
|
|
guard i >= minIndex && i < freeList.count else { continue }
|
|
assert(!freeList[i], "BusAllocator: double-free for \(label) bus \(i)")
|
|
freeList[i] = true
|
|
}
|
|
}
|
|
}
|
|
}
|