Files

497 lines
18 KiB
Swift

// EngineHostTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import AudioToolbox
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
/// NRT `build`-closure shim.
///
/// `NRTJob.build` is a non-isolated `@Sendable (SynthesisEngine) throws -> Void`
/// that `EngineHost._executeJob` runs on a background task — *not* the main actor.
/// `SynthesisEngine.add(_:)` is `@MainActor`, so it cannot be invoked
/// directly from inside the off-main build closure. The build closure runs *before*
/// `engine.start()`, so the engine is not yet rendering and nothing else touches it
/// concurrently; hopping the add onto the main actor synchronously is therefore safe
/// in this narrow window. The `nonisolated(unsafe)` captures move the non-`Sendable`
/// engine/synth across the hop — sound because of that exclusivity.
private func nrtBuildAdd(_ engine: SynthesisEngine, _ makeSynth: @escaping @MainActor () -> any Synthesizer) throws {
nonisolated(unsafe) let e: SynthesisEngine = engine
var thrown: (any Error)? = nil
DispatchQueue.main.sync {
MainActor.assumeIsolated {
do { try e.add(makeSynth()) } catch { thrown = error }
}
}
if let thrown: any Error = thrown { throw thrown }
}
/// `EngineHost` facade coverage.
@MainActor
@Suite("EngineHost")
struct EngineHostTests {
// MARK: - Test helpers
/// Build a fresh `SynthesisEngineConfig` suitable for unit tests
/// (small block size, offline driver, zero input channels).
private func makeConfig() -> SynthesisEngineConfig {
SynthesisEngineConfig(
blockSize: 64,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 16,
numControlBuses: 16,
eventQueueCapacity: 16,
driver: OfflineDriver()
)
}
// MARK: - 197.1 makeEngine
@Test func makeEngineRegistersUnderRole() throws {
let host: EngineHost = EngineHost()
let engine: SynthesisEngine = try host.makeEngine(
role: .nrtRender(slot: 0),
config: makeConfig()
)
#expect(host.engineCount == 1)
#expect(host.engine(for: .nrtRender(slot: 0)) === engine)
#expect(host.role(for: engine) == .nrtRender(slot: 0))
}
@Test func makeEngineMultipleRolesDistinctEngines() throws {
let host: EngineHost = EngineHost()
let a: SynthesisEngine = try host.makeEngine(role: .nrtRender(slot: 0), config: makeConfig())
let b: SynthesisEngine = try host.makeEngine(role: .nrtRender(slot: 1), config: makeConfig())
let c: SynthesisEngine = try host.makeEngine(role: .auxiliary(name: "analysis"), config: makeConfig())
#expect(host.engineCount == 3)
#expect(a.identifier != b.identifier)
#expect(b.identifier != c.identifier)
#expect(a.identifier != c.identifier)
}
@Test func makeEngineDuplicateRoleThrows() throws {
let host: EngineHost = EngineHost()
_ = try host.makeEngine(role: .nrtRender(slot: 0), config: makeConfig())
var caught: EngineHostError? = nil
do {
_ = try host.makeEngine(role: .nrtRender(slot: 0), config: makeConfig())
} catch let error as EngineHostError {
caught = error
}
#expect(caught != nil)
if case .duplicateRole(let role) = caught {
#expect(role == .nrtRender(slot: 0))
} else {
Issue.record("Expected .duplicateRole, got \(String(describing: caught))")
}
}
/// Pre-check throw must not leak the
/// host lock. If `_validateRoleUnlocked` threw without `defer`-ed
/// unlock, every subsequent host call on the same instance would
/// deadlock on `_lock.lock()`. This test asserts the host is
/// still usable after a `.duplicateRole` throw — a deadlock would
/// hang the test indefinitely (Swift Testing default per-test
/// timeout kicks in).
@Test func hostStillUsableAfterDuplicateRoleThrow() throws {
let host: EngineHost = EngineHost()
_ = try host.makeEngine(role: .nrtRender(slot: 0), config: makeConfig())
// First duplicate — throws.
do {
_ = try host.makeEngine(role: .nrtRender(slot: 0), config: makeConfig())
Issue.record("Expected throw on duplicate role")
} catch is EngineHostError {
// Expected
}
// Subsequent calls must not deadlock.
#expect(host.engineCount == 1)
#expect(host.engine(for: .nrtRender(slot: 0)) != nil)
_ = try host.makeEngine(role: .nrtRender(slot: 1), config: makeConfig())
#expect(host.engineCount == 2)
}
// MARK: - 197.2 Role exclusivity (rtOutput device)
/// Same-`.rtOutput(deviceID:)` re-registration throws
/// `.duplicateRole` because the `Hashable` enum case already
/// discriminates by deviceID. The dead
/// `.duplicateDevice` enum case that would have covered cross-role
/// same-device collisions was dropped — re-add when a future role
/// shape requires it.
@Test func makeEngineSameRtOutputRoleTwiceThrowsDuplicateRole() throws {
let host: EngineHost = EngineHost()
_ = try host.makeEngine(role: .rtOutput(deviceID: 42), config: makeConfig())
var caught: EngineHostError? = nil
do {
_ = try host.makeEngine(role: .rtOutput(deviceID: 42), config: makeConfig())
} catch let error as EngineHostError {
caught = error
}
#expect(caught != nil)
if case .duplicateRole(let role) = caught {
#expect(role == .rtOutput(deviceID: 42))
} else {
Issue.record("Expected .duplicateRole, got \(String(describing: caught))")
}
}
// MARK: - 197.3 Lookup + lifecycle
@Test func engineForUnregisteredRoleReturnsNil() {
let host: EngineHost = EngineHost()
#expect(host.engine(for: .nrtRender(slot: 99)) == nil)
}
@Test func rolesSnapshotContainsAllRegistered() throws {
let host: EngineHost = EngineHost()
_ = try host.makeEngine(role: .nrtRender(slot: 0), config: makeConfig())
_ = try host.makeEngine(role: .auxiliary(name: "fx"), config: makeConfig())
let roles: [EngineHostRole] = host.roles
#expect(roles.count == 2)
#expect(roles.contains(.nrtRender(slot: 0)))
#expect(roles.contains(.auxiliary(name: "fx")))
}
@Test func startAllStartsEveryEngine() throws {
let host: EngineHost = EngineHost()
let a: SynthesisEngine = try host.makeEngine(role: .nrtRender(slot: 0), config: makeConfig())
let b: SynthesisEngine = try host.makeEngine(role: .nrtRender(slot: 1), config: makeConfig())
#expect(a.isRunning == false)
#expect(b.isRunning == false)
try host.startAll()
#expect(a.isRunning == true)
#expect(b.isRunning == true)
host.stopAll()
#expect(a.isRunning == false)
#expect(b.isRunning == false)
}
@Test func stopAllIdempotent() throws {
let host: EngineHost = EngineHost()
_ = try host.makeEngine(role: .nrtRender(slot: 0), config: makeConfig())
// Never started — stopAll should be a no-op (engine.stop()
// is documented as safe when not running).
host.stopAll()
host.stopAll()
}
// MARK: - 197.5 Adoption
@Test func adoptExistingEngine() throws {
// Construct engine outside the host — exercises the migration
// / direct-ctor scenario.
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 64,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 0,
driver: OfflineDriver()
)
let host: EngineHost = EngineHost()
try host.adopt(existing: engine, role: .custom("imported"))
#expect(host.engineCount == 1)
#expect(host.engine(for: .custom("imported")) === engine)
#expect(host.role(for: engine) == .custom("imported"))
}
// MARK: - 197.4 NRT batch render
/// Build a temporary scratch directory for NRT output files,
/// auto-cleaned at end of test via the returned cleanup closure.
private func makeScratchDir() throws -> (URL, () -> Void) {
let fm: FileManager = FileManager.default
let dir: URL = fm.temporaryDirectory.appendingPathComponent(
"EngineHostTests_\(UUID().uuidString)"
)
try fm.createDirectory(at: dir, withIntermediateDirectories: true)
return (dir, { try? fm.removeItem(at: dir) })
}
/// Lightweight test synthesizer: writes a constant value to bus 0.
private final class ConstSynth: SynthesizerBase {
let value: Double
init(value: Double) {
self.value = value
super.init()
}
override func build() {
addOutputGenerator(Out.Audio(bus: 0, source: value))
}
}
@Test func renderConcurrentEmptyJobsFinishesImmediately() async throws {
let host: EngineHost = EngineHost()
var count: Int = 0
for try await _ in host.renderConcurrent(jobs: []) {
count += 1
}
#expect(count == 0)
}
@Test func renderConcurrentYieldsOnePerJob() async throws {
let (dir, cleanup): (URL, () -> Void) = try makeScratchDir()
defer { cleanup() }
let host: EngineHost = EngineHost()
let jobs: [NRTJob] = (0..<4).map { i in
NRTJob(
outputURL: dir.appendingPathComponent("out_\(i).caf"),
duration: 0.05,
blockSize: 64,
sampleRate: 44100,
numOutputChannels: 2
) { engine in
try nrtBuildAdd(engine) { ConstSynth(value: 0.1 * Double(i + 1)) }
}
}
var results: [NRTResult] = []
for try await result: NRTResult in host.renderConcurrent(jobs: jobs, maxConcurrent: 2) {
results.append(result)
}
#expect(results.count == jobs.count)
// Every job index reported exactly once (completion order varies).
let indices: Set<Int> = Set(results.map(\.jobIndex))
#expect(indices == Set(0..<jobs.count))
// Every output file should exist + non-empty.
for result: NRTResult in results {
let attrs: [FileAttributeKey: Any] = try FileManager.default.attributesOfItem(
atPath: result.outputURL.path
)
let size: Int = (attrs[.size] as? Int) ?? 0
#expect(size > 0, "Output file \(result.outputURL.lastPathComponent) is empty")
}
}
@Test func renderConcurrentHonoursJobFormat() async throws {
let (dir, cleanup): (URL, () -> Void) = try makeScratchDir()
defer { cleanup() }
let host: EngineHost = EngineHost()
// A non-default format (WAV / Int16) must reach the output file.
let outURL: URL = dir.appendingPathComponent("stem.wav")
let jobs: [NRTJob] = [
NRTJob(
outputURL: outURL,
duration: 0.05,
format: .wavInt16,
blockSize: 64,
sampleRate: 44100,
numOutputChannels: 2
) { engine in
try nrtBuildAdd(engine) { ConstSynth(value: 0.25) }
}
]
var results: [NRTResult] = []
for try await result: NRTResult in host.renderConcurrent(jobs: jobs) {
results.append(result)
}
#expect(results.count == 1)
var fileRef: ExtAudioFileRef?
#expect(ExtAudioFileOpenURL(outURL as CFURL, &fileRef) == noErr)
let ref: ExtAudioFileRef = try #require(fileRef)
defer { ExtAudioFileDispose(ref) }
var asbd: AudioStreamBasicDescription = AudioStreamBasicDescription()
var size: UInt32 = UInt32(MemoryLayout<AudioStreamBasicDescription>.size)
#expect(ExtAudioFileGetProperty(ref, kExtAudioFileProperty_FileDataFormat, &size, &asbd) == noErr)
#expect(asbd.mBitsPerChannel == 16)
#expect(asbd.mFormatFlags & kAudioFormatFlagIsSignedInteger != 0)
#expect(asbd.mFormatFlags & kAudioFormatFlagIsFloat == 0)
}
@Test func renderConcurrentPropagatesBuildFailure() async throws {
let (dir, cleanup): (URL, () -> Void) = try makeScratchDir()
defer { cleanup() }
struct DeliberateBuildFailure: Error {}
let host: EngineHost = EngineHost()
let jobs: [NRTJob] = [
NRTJob(
outputURL: dir.appendingPathComponent("ok.caf"),
duration: 0.05,
blockSize: 64,
sampleRate: 44100,
numOutputChannels: 2
) { engine in
try nrtBuildAdd(engine) { ConstSynth(value: 0.1) }
},
NRTJob(
outputURL: dir.appendingPathComponent("fail.caf"),
duration: 0.05,
blockSize: 64,
sampleRate: 44100,
numOutputChannels: 2
) { _ in
throw DeliberateBuildFailure()
}
]
var caught: (any Error)? = nil
do {
for try await _ in host.renderConcurrent(jobs: jobs, maxConcurrent: 2) {
// drain
}
} catch {
caught = error
}
#expect(caught is DeliberateBuildFailure)
}
/// A `build` closure that deliberately
/// throws `CancellationError` must propagate as a stream-level
/// throw, not be misclassified as a caller-cancel and silently
/// swallowed. The outer-catch `Task.isCancelled` guard distinguishes
/// the two sources of `CancellationError`.
@Test func renderConcurrentBuildCancellationErrorPropagates() async throws {
let (dir, cleanup): (URL, () -> Void) = try makeScratchDir()
defer { cleanup() }
let host: EngineHost = EngineHost()
let jobs: [NRTJob] = [
NRTJob(
outputURL: dir.appendingPathComponent("cancel_thrown.caf"),
duration: 0.05,
blockSize: 64,
sampleRate: 44100,
numOutputChannels: 2
) { _ in
throw CancellationError()
}
]
var caught: (any Error)? = nil
do {
for try await _: NRTResult in host.renderConcurrent(jobs: jobs, maxConcurrent: 1) {
// drain
}
} catch {
caught = error
}
let isCancellationError: Bool = caught is CancellationError
#expect(isCancellationError,
Comment(rawValue: "build closure throwing CancellationError must surface as a stream throw, " +
"got \(String(describing: caught))"))
}
/// Caller breaking the for-await early must finish
/// the stream cleanly, not throw `CancellationError`. The earlier
/// implementation forwarded the cooperative-cancel from
/// `withThrowingTaskGroup`'s for-await into `continuation.finish(throwing:)`,
/// surfacing a thrown termination even on caller-initiated cancel.
@Test func renderConcurrentCallerCancelFinishesCleanly() async throws {
let (dir, cleanup): (URL, () -> Void) = try makeScratchDir()
defer { cleanup() }
let host: EngineHost = EngineHost()
// Enough jobs that the for-await iterates more than once and we
// can break midway.
let jobs: [NRTJob] = (0..<6).map { i in
NRTJob(
outputURL: dir.appendingPathComponent("cancel_\(i).caf"),
duration: 0.05,
blockSize: 64,
sampleRate: 44100,
numOutputChannels: 2
) { engine in
try nrtBuildAdd(engine) { ConstSynth(value: 0.1) }
}
}
var caught: (any Error)? = nil
var seenResults: Int = 0
do {
for try await _: NRTResult in host.renderConcurrent(jobs: jobs, maxConcurrent: 2) {
seenResults += 1
if seenResults == 1 {
break
}
}
} catch {
caught = error
}
#expect(caught == nil,
Comment(rawValue: "Caller-initiated cancel must not throw; got \(String(describing: caught))"))
// Allow >= 1 to absorb scheduler-ordering windows where a
// second result lands before the for-await's `break`
// propagates through the AsyncSequence machinery.
#expect(seenResults >= 1)
}
@Test func renderConcurrentRespectsMaxConcurrentClamp() async throws {
// Clamp `0` upward to `1`. Single-job stream finishes cleanly.
let (dir, cleanup): (URL, () -> Void) = try makeScratchDir()
defer { cleanup() }
let host: EngineHost = EngineHost()
let jobs: [NRTJob] = [
NRTJob(
outputURL: dir.appendingPathComponent("clamp.caf"),
duration: 0.05,
blockSize: 64,
sampleRate: 44100,
numOutputChannels: 2
) { engine in
try nrtBuildAdd(engine) { ConstSynth(value: 0.1) }
}
]
var count: Int = 0
for try await _ in host.renderConcurrent(jobs: jobs, maxConcurrent: 0) {
count += 1
}
#expect(count == 1)
}
@Test func adoptDuplicateRoleThrows() throws {
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 64,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 0,
driver: OfflineDriver()
)
let host: EngineHost = EngineHost()
_ = try host.makeEngine(role: .nrtRender(slot: 0), config: makeConfig())
var caught: EngineHostError? = nil
do {
try host.adopt(existing: engine, role: .nrtRender(slot: 0))
} catch let error as EngineHostError {
caught = error
}
#expect(caught != nil)
if case .duplicateRole = caught {
// Expected
} else {
Issue.record("Expected .duplicateRole, got \(String(describing: caught))")
}
}
}