8eb64f883f
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
1086 lines
41 KiB
Swift
1086 lines
41 KiB
Swift
// LyrebirdEventListRecordingTests.swift
|
||
// Lyrebird
|
||
//
|
||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||
// SPDX-License-Identifier: MIT
|
||
|
||
import Testing
|
||
import Foundation
|
||
import AudioToolbox
|
||
import Synchronization
|
||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||
|
||
// MARK: - Shared fixtures (recording-specific)
|
||
|
||
/// Build a test engine backed by OfflineDriver (no real-time audio).
|
||
private func makeRecordingTestEngine(sampleRate: Double = 44100) -> SynthesisEngine {
|
||
SynthesisEngine(
|
||
blockSize: 64,
|
||
sampleRate: sampleRate,
|
||
numOutputChannels: 2,
|
||
numInputChannels: 0,
|
||
numAudioBuses: 128,
|
||
numControlBuses: 64,
|
||
driver: OfflineDriver()
|
||
)
|
||
}
|
||
|
||
/// Short auto-releasing envelope (~40 ms).
|
||
private func shortAutoEnvelope() -> Envelope {
|
||
Envelope(
|
||
levels: [0.0, 1.0, 0.0],
|
||
durations: [0.02, 0.02],
|
||
curves: [.lin, .lin]
|
||
)
|
||
}
|
||
|
||
/// Sustained envelope — holds until released.
|
||
private func sustainedEnvelope() -> Envelope {
|
||
Envelope(
|
||
levels: [0.0, 1.0, 0.0],
|
||
durations: [0.02, 0.05],
|
||
curves: [.lin, .lin],
|
||
releaseNode: 2
|
||
)
|
||
}
|
||
|
||
/// Drives `engine.processBlock` in bursts so engine-time advances faster than wall-time.
|
||
private final class TestBlockDriver: @unchecked Sendable {
|
||
private let _running: Atomic<Bool> = Atomic<Bool>(false)
|
||
private let _done: DispatchSemaphore = DispatchSemaphore(value: 0)
|
||
private let _engine: SynthesisEngine
|
||
// 32 × 64 samples @ 44.1 kHz ≈ 46 ms audio per 1 ms wall sleep → ~46× realtime.
|
||
// Headroom absorbs scheduler jitter so wall-clock test timeouts don't expire
|
||
// before engine-time advances past envelope releases / process completions.
|
||
private static let blocksPerBurst: Int = 32
|
||
private static let wallSleepSeconds: TimeInterval = 0.001
|
||
|
||
init(engine: SynthesisEngine) { _engine = engine }
|
||
|
||
func start() {
|
||
_running.store(true, ordering: .relaxed)
|
||
let thread: Thread = Thread { [self] in
|
||
while self._running.load(ordering: .relaxed) {
|
||
for _ in 0..<Self.blocksPerBurst {
|
||
self._engine.processBlock(inputSamples: [])
|
||
}
|
||
Thread.sleep(forTimeInterval: Self.wallSleepSeconds)
|
||
}
|
||
self._done.signal()
|
||
}
|
||
thread.qualityOfService = .userInteractive
|
||
thread.start()
|
||
}
|
||
|
||
/// Stop and **join** the pump thread: blocks until the loop has finished its
|
||
/// in-flight block and exited, so no `processBlock` can run after `stop()`
|
||
/// returns to race the engine's own `stop()`. Idempotent and safe if never
|
||
/// started (the `true → false` transition is the one that joins).
|
||
func stop() {
|
||
guard _running.exchange(false, ordering: .relaxed) else { return }
|
||
_done.wait()
|
||
}
|
||
}
|
||
|
||
/// Thread-safe one-shot fulfillment token.
|
||
private final class AsyncExpectation: @unchecked Sendable {
|
||
private let _lock: NSLock = NSLock()
|
||
private var _fulfilled: Bool = false
|
||
|
||
var isFulfilled: Bool { _lock.withLock { _fulfilled } }
|
||
func fulfill() { _lock.withLock { _fulfilled = true } }
|
||
|
||
func waitForFulfillment(timeout: Double) async -> Bool {
|
||
let pollNs: UInt64 = 5_000_000
|
||
let deadlineNs: UInt64 = DispatchTime.now().uptimeNanoseconds
|
||
+ UInt64(timeout * 1_000_000_000)
|
||
while true {
|
||
if isFulfilled { return true }
|
||
let nowNs: UInt64 = DispatchTime.now().uptimeNanoseconds
|
||
if nowNs >= deadlineNs { return isFulfilled }
|
||
try? await Task.sleep(nanoseconds: pollNs)
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Thread-safe box for cross-thread value sharing.
|
||
private final class Box<T>: @unchecked Sendable {
|
||
private let _lock: NSLock = NSLock()
|
||
private var _value: T
|
||
init(_ value: T) { _value = value }
|
||
func get() -> T { _lock.withLock { _value } }
|
||
func mutate(_ transform: (inout T) -> Void) { _lock.withLock { transform(&_value) } }
|
||
}
|
||
|
||
// MARK: - Audio file inspection helpers
|
||
|
||
/// Returns the number of frames and channel count in a file at `url`.
|
||
/// Uses `ExtAudioFile` to query metadata regardless of encoding.
|
||
private func audioFileInfo(url: URL) -> (frames: Int, channels: Int)? {
|
||
var ref: ExtAudioFileRef?
|
||
guard ExtAudioFileOpenURL(url as CFURL, &ref) == noErr, let ref: ExtAudioFileRef else { return nil }
|
||
defer { ExtAudioFileDispose(ref) }
|
||
|
||
var frameCount: Int64 = 0
|
||
var propSize: UInt32 = UInt32(MemoryLayout<Int64>.size)
|
||
let frameStatus: OSStatus = ExtAudioFileGetProperty(
|
||
ref,
|
||
kExtAudioFileProperty_FileLengthFrames,
|
||
&propSize,
|
||
&frameCount
|
||
)
|
||
guard frameStatus == noErr else { return nil }
|
||
|
||
var desc: AudioStreamBasicDescription = AudioStreamBasicDescription()
|
||
var descSize: UInt32 = UInt32(MemoryLayout<AudioStreamBasicDescription>.size)
|
||
let descStatus: OSStatus = ExtAudioFileGetProperty(
|
||
ref,
|
||
kExtAudioFileProperty_FileDataFormat,
|
||
&descSize,
|
||
&desc
|
||
)
|
||
guard descStatus == noErr else { return nil }
|
||
|
||
return (frames: Int(frameCount), channels: Int(desc.mChannelsPerFrame))
|
||
}
|
||
|
||
/// Read all frames from `url` as Float32, decoded to `channelCount` channels.
|
||
private func readAudioFileAsFloat32(url: URL, channelCount: Int) -> [[Float]]? {
|
||
var ref: ExtAudioFileRef?
|
||
guard ExtAudioFileOpenURL(url as CFURL, &ref) == noErr, let ref: ExtAudioFileRef else { return nil }
|
||
defer { ExtAudioFileDispose(ref) }
|
||
|
||
var frameCount: Int64 = 0
|
||
var propSize: UInt32 = UInt32(MemoryLayout<Int64>.size)
|
||
ExtAudioFileGetProperty(
|
||
ref, kExtAudioFileProperty_FileLengthFrames, &propSize, &frameCount
|
||
)
|
||
guard frameCount > 0 else { return nil }
|
||
|
||
let nch: UInt32 = UInt32(channelCount)
|
||
let f32ByteSize: UInt32 = UInt32(MemoryLayout<Float>.size)
|
||
var clientFmt: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
||
mSampleRate: 44100,
|
||
mFormatID: kAudioFormatLinearPCM,
|
||
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
||
mBytesPerPacket: f32ByteSize * nch,
|
||
mFramesPerPacket: 1,
|
||
mBytesPerFrame: f32ByteSize * nch,
|
||
mChannelsPerFrame: nch,
|
||
mBitsPerChannel: 32,
|
||
mReserved: 0
|
||
)
|
||
ExtAudioFileSetProperty(
|
||
ref,
|
||
kExtAudioFileProperty_ClientDataFormat,
|
||
UInt32(MemoryLayout<AudioStreamBasicDescription>.size),
|
||
&clientFmt
|
||
)
|
||
|
||
var interleaved: [Float] = [Float](repeating: 0, count: Int(frameCount) * channelCount)
|
||
var frames: UInt32 = UInt32(frameCount)
|
||
interleaved.withUnsafeMutableBufferPointer { ptr in
|
||
guard let base: UnsafeMutablePointer<Float> = ptr.baseAddress else { return }
|
||
var bl: AudioBufferList = AudioBufferList(
|
||
mNumberBuffers: 1,
|
||
mBuffers: AudioBuffer(
|
||
mNumberChannels: nch,
|
||
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
|
||
mData: base
|
||
)
|
||
)
|
||
_ = ExtAudioFileRead(ref, &frames, &bl)
|
||
}
|
||
|
||
let n: Int = Int(frames)
|
||
guard n > 0 else { return nil }
|
||
var result: [[Float]] = Array(repeating: [Float](repeating: 0, count: n), count: channelCount)
|
||
for f: Int in 0..<n {
|
||
for ch: Int in 0..<channelCount {
|
||
result[ch][f] = interleaved[f * channelCount + ch]
|
||
}
|
||
}
|
||
return result
|
||
}
|
||
|
||
/// Returns a temporary directory for recording tests. The caller is responsible
|
||
/// for removing it after the test.
|
||
private func makeTempDir() -> URL {
|
||
FileManager.default.temporaryDirectory
|
||
.appendingPathComponent(UUID().uuidString)
|
||
}
|
||
|
||
/// Remove a directory if it exists (best-effort cleanup).
|
||
private func removeTempDir(_ url: URL) {
|
||
try? FileManager.default.removeItem(at: url)
|
||
}
|
||
|
||
// MARK: - Suite
|
||
|
||
@MainActor
|
||
@Suite("LyrebirdEventListRecording")
|
||
struct LyrebirdEventListRecordingTests {
|
||
|
||
// MARK: - Test 1: basic record + file appears and is non-empty
|
||
|
||
@Test("record() then play one process → stem file appears and is non-empty")
|
||
func testBasicRecordFileAppears() async throws {
|
||
let tempDir: URL = makeTempDir()
|
||
defer { removeTempDir(tempDir) }
|
||
|
||
let engine: SynthesisEngine = makeRecordingTestEngine()
|
||
try engine.start()
|
||
defer { engine.stop() }
|
||
|
||
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
|
||
driver.start()
|
||
defer { driver.stop() }
|
||
|
||
let finished: AsyncExpectation = AsyncExpectation()
|
||
|
||
let proc: LyrebirdProcess = LyrebirdProcess(
|
||
id: "basic-rec-proc",
|
||
envelope: shortAutoEnvelope(),
|
||
numChannels: 1,
|
||
body: { ctx in await ctx.wait(0.01) },
|
||
onFinished: { finished.fulfill() }
|
||
)
|
||
|
||
let eventList: LyrebirdEventList = try LyrebirdEventList(
|
||
id: "basic-rec-list",
|
||
events: [LyrebirdEvent(starts: [proc])],
|
||
engine: engine,
|
||
bus: AudioBus(index: 0, channelCount: 2)
|
||
)
|
||
|
||
eventList.record(directory: tempDir, format: .wavFloat32)
|
||
#expect(eventList.isRecording)
|
||
#expect(eventList.recordDirectory == tempDir)
|
||
|
||
eventList.next()
|
||
|
||
// Wait for process to finish (envelope auto-ends in ~40 ms).
|
||
let ok: Bool = await finished.waitForFulfillment(timeout: 10.0)
|
||
#expect(ok, "Process should complete within timeout")
|
||
|
||
// Give DiskOut.close() time to flush.
|
||
try await Task.sleep(nanoseconds: 100_000_000)
|
||
|
||
// Find the stem file.
|
||
let files: [URL] = (try? FileManager.default.contentsOfDirectory(
|
||
at: tempDir,
|
||
includingPropertiesForKeys: nil
|
||
)) ?? []
|
||
#expect(!files.isEmpty, "At least one stem file should have been created")
|
||
|
||
// Verify the file is non-empty.
|
||
guard let stemFile: URL = files.first else { return }
|
||
let attrs: [FileAttributeKey : Any] = try FileManager.default.attributesOfItem(atPath: stemFile.path)
|
||
let fileSize: Int = attrs[.size] as? Int ?? 0
|
||
#expect(fileSize > 0, "Stem file should be non-empty; size=\(fileSize)")
|
||
|
||
eventList.killAll()
|
||
}
|
||
|
||
@Test("record() rejects compressed formats — recording stays disabled", arguments: [
|
||
AudioFileFormat.aacHigh, .aacMedium, .alac
|
||
])
|
||
func testRecordRejectsCompressed(format: AudioFileFormat) throws {
|
||
let tempDir: URL = makeTempDir()
|
||
defer { removeTempDir(tempDir) }
|
||
|
||
let engine: SynthesisEngine = makeRecordingTestEngine()
|
||
let eventList: LyrebirdEventList = try LyrebirdEventList(
|
||
id: "compressed-reject-list",
|
||
events: [],
|
||
engine: engine,
|
||
bus: AudioBus(index: 0, channelCount: 2)
|
||
)
|
||
|
||
// Compressed stems are unsupported (DiskOut is PCM/RF64 only) — record() must
|
||
// refuse and leave recording disabled rather than fail silently per-process.
|
||
eventList.record(directory: tempDir, format: format)
|
||
#expect(eventList.isRecording == false)
|
||
#expect(eventList.recordDirectory == nil)
|
||
}
|
||
|
||
// MARK: - Test 2: filename format verification
|
||
|
||
@Test("stem filename encodes eventListID, offset, processID, playIndex")
|
||
func testFilenameFormat() async throws {
|
||
let tempDir: URL = makeTempDir()
|
||
defer { removeTempDir(tempDir) }
|
||
|
||
let engine: SynthesisEngine = makeRecordingTestEngine()
|
||
try engine.start()
|
||
defer { engine.stop() }
|
||
|
||
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
|
||
driver.start()
|
||
defer { driver.stop() }
|
||
|
||
let finished: AsyncExpectation = AsyncExpectation()
|
||
|
||
let proc: LyrebirdProcess = LyrebirdProcess(
|
||
id: "fname-proc",
|
||
envelope: shortAutoEnvelope(),
|
||
numChannels: 1,
|
||
body: { ctx in await ctx.wait(0.01) },
|
||
onFinished: { finished.fulfill() }
|
||
)
|
||
|
||
let eventList: LyrebirdEventList = try LyrebirdEventList(
|
||
id: "fname-list",
|
||
events: [LyrebirdEvent(starts: [proc])],
|
||
engine: engine,
|
||
bus: AudioBus(index: 0, channelCount: 2)
|
||
)
|
||
|
||
eventList.record(directory: tempDir, format: .wavFloat32)
|
||
eventList.next()
|
||
|
||
let ok: Bool = await finished.waitForFulfillment(timeout: 10.0)
|
||
#expect(ok)
|
||
|
||
try await Task.sleep(nanoseconds: 100_000_000)
|
||
|
||
let files: [URL] = (try? FileManager.default.contentsOfDirectory(
|
||
at: tempDir,
|
||
includingPropertiesForKeys: nil
|
||
)) ?? []
|
||
guard let stemFile: URL = files.first else {
|
||
#expect(Bool(false), "Expected at least one stem file")
|
||
return
|
||
}
|
||
|
||
let name: String = stemFile.deletingPathExtension().lastPathComponent
|
||
let ext: String = stemFile.pathExtension
|
||
|
||
// Extension should be "wav".
|
||
#expect(ext == "wav", "Extension should be wav; got \(ext)")
|
||
|
||
// Split on "_" — components: [eventListID, offset, processID, playIndex]
|
||
// But IDs can contain "_", so we need to parse more carefully.
|
||
// The offset is the second field: a fixed-width decimal like "0000000.0000".
|
||
// We verify by checking that the sanitised IDs appear in the name.
|
||
let sanitisedListID: String = "fname-list"
|
||
let sanitisedProcID: String = "fname-proc"
|
||
|
||
#expect(name.contains(sanitisedListID),
|
||
"Filename should contain eventListID; name=\(name)")
|
||
#expect(name.contains(sanitisedProcID),
|
||
"Filename should contain processID; name=\(name)")
|
||
// playIndex 0 appears at the end.
|
||
#expect(name.hasSuffix("_0"),
|
||
"Filename should end with _<playIndex> (0 for first play); name=\(name)")
|
||
|
||
// The offset field is between the list ID and process ID.
|
||
// It should be parseable as a floating-point number.
|
||
let listIDLen: Int = sanitisedListID.count
|
||
let remainder: String = String(name.dropFirst(listIDLen + 1)) // drop "fname-list_"
|
||
let offsetEnd: String.Index = remainder.firstIndex(of: "_") ?? remainder.endIndex
|
||
let offsetStr: String = String(remainder[..<offsetEnd])
|
||
let offsetVal: Double? = Double(offsetStr)
|
||
#expect(offsetVal != nil, "Offset component should be parseable as Double; got '\(offsetStr)'")
|
||
let offset: Double = offsetVal ?? -1.0
|
||
#expect(offset >= 0.0, "Offset should be non-negative; got \(offset)")
|
||
|
||
eventList.killAll()
|
||
}
|
||
|
||
// MARK: - Test 3: playIndex increments on repeated plays
|
||
|
||
@Test("same process played twice has playIndex 0 then 1")
|
||
func testPlayIndexIncrements() async throws {
|
||
let tempDir: URL = makeTempDir()
|
||
defer { removeTempDir(tempDir) }
|
||
|
||
let engine: SynthesisEngine = makeRecordingTestEngine()
|
||
try engine.start()
|
||
defer { engine.stop() }
|
||
|
||
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
|
||
driver.start()
|
||
defer { driver.stop() }
|
||
|
||
// We need two different process instances because a process resets to idle
|
||
// only after teardown, and the test would deadlock if we tried to reuse.
|
||
let finished0: AsyncExpectation = AsyncExpectation()
|
||
let finished1: AsyncExpectation = AsyncExpectation()
|
||
|
||
let proc0: LyrebirdProcess = LyrebirdProcess(
|
||
id: "idx-proc",
|
||
envelope: shortAutoEnvelope(),
|
||
numChannels: 1,
|
||
body: { ctx in await ctx.wait(0.01) },
|
||
onFinished: { finished0.fulfill() }
|
||
)
|
||
let proc1: LyrebirdProcess = LyrebirdProcess(
|
||
id: "idx-proc", // same id string — playIndex differentiates them
|
||
envelope: shortAutoEnvelope(),
|
||
numChannels: 1,
|
||
body: { ctx in await ctx.wait(0.01) },
|
||
onFinished: { finished1.fulfill() }
|
||
)
|
||
|
||
let eventList: LyrebirdEventList = try LyrebirdEventList(
|
||
id: "idx-list",
|
||
events: [
|
||
LyrebirdEvent(starts: [proc0]),
|
||
LyrebirdEvent(starts: [proc1])
|
||
],
|
||
engine: engine,
|
||
bus: AudioBus(index: 0, channelCount: 2)
|
||
)
|
||
|
||
eventList.record(directory: tempDir, format: .wavFloat32)
|
||
eventList.next() // fires proc0 (playIndex 0)
|
||
|
||
let ok0: Bool = await finished0.waitForFulfillment(timeout: 10.0)
|
||
#expect(ok0, "proc0 should complete")
|
||
|
||
eventList.next() // fires proc1 (playIndex 0 — different instance)
|
||
|
||
let ok1: Bool = await finished1.waitForFulfillment(timeout: 10.0)
|
||
#expect(ok1, "proc1 should complete")
|
||
|
||
try await Task.sleep(nanoseconds: 150_000_000)
|
||
|
||
let files: [URL] = ((try? FileManager.default.contentsOfDirectory(
|
||
at: tempDir,
|
||
includingPropertiesForKeys: nil
|
||
)) ?? []).sorted { $0.lastPathComponent < $1.lastPathComponent }
|
||
|
||
// Two files expected.
|
||
#expect(files.count == 2, "Expected 2 stem files; got \(files.count)")
|
||
|
||
// Verify distinct filenames and distinct playIndex suffixes.
|
||
if files.count == 2 {
|
||
let name0: String = files[0].deletingPathExtension().lastPathComponent
|
||
let name1: String = files[1].deletingPathExtension().lastPathComponent
|
||
#expect(name0 != name1, "Two plays should produce distinct filenames")
|
||
// Offsets should differ too (proc1 fires later than proc0).
|
||
// Check that both end in _0 (each is the 0th play of its instance).
|
||
#expect(name0.hasSuffix("_0"), "First file should end with _0; name=\(name0)")
|
||
#expect(name1.hasSuffix("_0"), "Second file should end with _0; name=\(name1)")
|
||
}
|
||
|
||
eventList.killAll()
|
||
}
|
||
|
||
// MARK: - Test 4: late-start recording
|
||
|
||
@Test("late-start: event 0 no recording; record() called; event 1 gets recorded")
|
||
func testLateStart() async throws {
|
||
let tempDir: URL = makeTempDir()
|
||
defer { removeTempDir(tempDir) }
|
||
|
||
let engine: SynthesisEngine = makeRecordingTestEngine()
|
||
try engine.start()
|
||
defer { engine.stop() }
|
||
|
||
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
|
||
driver.start()
|
||
defer { driver.stop() }
|
||
|
||
let finished0: AsyncExpectation = AsyncExpectation()
|
||
let finished1: AsyncExpectation = AsyncExpectation()
|
||
|
||
let proc0: LyrebirdProcess = LyrebirdProcess(
|
||
id: "late-proc-0",
|
||
envelope: shortAutoEnvelope(),
|
||
numChannels: 1,
|
||
body: { ctx in await ctx.wait(0.01) },
|
||
onFinished: { finished0.fulfill() }
|
||
)
|
||
let proc1: LyrebirdProcess = LyrebirdProcess(
|
||
id: "late-proc-1",
|
||
envelope: shortAutoEnvelope(),
|
||
numChannels: 1,
|
||
body: { ctx in await ctx.wait(0.01) },
|
||
onFinished: { finished1.fulfill() }
|
||
)
|
||
|
||
let eventList: LyrebirdEventList = try LyrebirdEventList(
|
||
id: "late-list",
|
||
events: [
|
||
LyrebirdEvent(starts: [proc0]),
|
||
LyrebirdEvent(starts: [proc1])
|
||
],
|
||
engine: engine,
|
||
bus: AudioBus(index: 0, channelCount: 2)
|
||
)
|
||
|
||
// Fire event 0 WITHOUT recording.
|
||
eventList.next()
|
||
|
||
let ok0: Bool = await finished0.waitForFulfillment(timeout: 10.0)
|
||
#expect(ok0, "proc0 should complete")
|
||
try await Task.sleep(nanoseconds: 100_000_000)
|
||
|
||
// Enable recording AFTER event 0 has finished.
|
||
eventList.record(directory: tempDir, format: .wavFloat32)
|
||
|
||
// Fire event 1 WITH recording.
|
||
eventList.next()
|
||
|
||
let ok1: Bool = await finished1.waitForFulfillment(timeout: 10.0)
|
||
#expect(ok1, "proc1 should complete")
|
||
try await Task.sleep(nanoseconds: 150_000_000)
|
||
|
||
let files: [URL] = (try? FileManager.default.contentsOfDirectory(
|
||
at: tempDir,
|
||
includingPropertiesForKeys: nil
|
||
)) ?? []
|
||
|
||
// Only proc1's file should exist.
|
||
#expect(files.count == 1, "Only proc1 should have a stem file; got \(files.count)")
|
||
if let f: URL = files.first {
|
||
#expect(f.lastPathComponent.contains("late-proc-1"),
|
||
"Stem file should be for proc1; name=\(f.lastPathComponent)")
|
||
}
|
||
|
||
eventList.killAll()
|
||
}
|
||
|
||
// MARK: - Test 5: stopRecord() mid-piece
|
||
|
||
@Test("stopRecord() prevents new processes from recording; existing recording continues to teardown")
|
||
func testStopRecordMidPiece() async throws {
|
||
let tempDir: URL = makeTempDir()
|
||
defer { removeTempDir(tempDir) }
|
||
|
||
let engine: SynthesisEngine = makeRecordingTestEngine()
|
||
try engine.start()
|
||
defer { engine.stop() }
|
||
|
||
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
|
||
driver.start()
|
||
defer { driver.stop() }
|
||
|
||
let finished0: AsyncExpectation = AsyncExpectation()
|
||
let finished1: AsyncExpectation = AsyncExpectation()
|
||
|
||
let proc0: LyrebirdProcess = LyrebirdProcess(
|
||
id: "stop-rec-proc0",
|
||
envelope: shortAutoEnvelope(),
|
||
numChannels: 1,
|
||
body: { ctx in await ctx.wait(0.01) },
|
||
onFinished: { finished0.fulfill() }
|
||
)
|
||
let proc1: LyrebirdProcess = LyrebirdProcess(
|
||
id: "stop-rec-proc1",
|
||
envelope: shortAutoEnvelope(),
|
||
numChannels: 1,
|
||
body: { ctx in await ctx.wait(0.01) },
|
||
onFinished: { finished1.fulfill() }
|
||
)
|
||
|
||
let eventList: LyrebirdEventList = try LyrebirdEventList(
|
||
id: "stop-rec-list",
|
||
events: [
|
||
LyrebirdEvent(starts: [proc0]),
|
||
LyrebirdEvent(starts: [proc1])
|
||
],
|
||
engine: engine,
|
||
bus: AudioBus(index: 0, channelCount: 2)
|
||
)
|
||
|
||
// Start recording then play proc0.
|
||
eventList.record(directory: tempDir, format: .wavFloat32)
|
||
eventList.next()
|
||
|
||
// Wait for proc0 to finish — its DiskOut should have closed.
|
||
let ok0: Bool = await finished0.waitForFulfillment(timeout: 10.0)
|
||
#expect(ok0, "proc0 should complete")
|
||
try await Task.sleep(nanoseconds: 100_000_000)
|
||
|
||
// Stop recording, then play proc1.
|
||
eventList.stopRecord()
|
||
#expect(!eventList.isRecording)
|
||
#expect(eventList.recordDirectory == nil)
|
||
|
||
eventList.next()
|
||
|
||
let ok1: Bool = await finished1.waitForFulfillment(timeout: 10.0)
|
||
#expect(ok1, "proc1 should complete")
|
||
try await Task.sleep(nanoseconds: 150_000_000)
|
||
|
||
let files: [URL] = (try? FileManager.default.contentsOfDirectory(
|
||
at: tempDir,
|
||
includingPropertiesForKeys: nil
|
||
)) ?? []
|
||
|
||
// Only proc0's file (from before stopRecord) should exist.
|
||
#expect(files.count == 1, "Only proc0's stem file should exist; got \(files.count)")
|
||
if let f: URL = files.first {
|
||
#expect(f.lastPathComponent.contains("stop-rec-proc0"),
|
||
"File should be for proc0; name=\(f.lastPathComponent)")
|
||
}
|
||
|
||
eventList.killAll()
|
||
}
|
||
|
||
// MARK: - Test 6: reset() clears recording state
|
||
|
||
@Test("reset() calls stopRecord() — isRecording is false after reset")
|
||
func testResetClearsRecordingState() throws {
|
||
let engine: SynthesisEngine = makeRecordingTestEngine()
|
||
let tempDir: URL = makeTempDir()
|
||
defer { removeTempDir(tempDir) }
|
||
|
||
let eventList: LyrebirdEventList = try LyrebirdEventList(
|
||
id: "reset-rec-list",
|
||
events: [],
|
||
engine: engine
|
||
)
|
||
|
||
eventList.record(directory: tempDir, format: .wavFloat32)
|
||
#expect(eventList.isRecording)
|
||
#expect(eventList.recordDirectory == tempDir)
|
||
|
||
eventList.reset()
|
||
|
||
#expect(!eventList.isRecording, "isRecording should be false after reset()")
|
||
#expect(eventList.recordDirectory == nil, "recordDirectory should be nil after reset()")
|
||
}
|
||
|
||
// MARK: - Test 7: format selection — wavInt16 produces smaller file than wavFloat32
|
||
|
||
@Test("wavInt16 produces smaller file than wavFloat32 for same signal duration")
|
||
func testFormatSelection() async throws {
|
||
let tempDirF32: URL = makeTempDir()
|
||
let tempDirI16: URL = makeTempDir()
|
||
defer { removeTempDir(tempDirF32); removeTempDir(tempDirI16) }
|
||
|
||
let sampleRate: Double = 44100.0
|
||
let blockSize: Int = 64
|
||
let engine: SynthesisEngine = SynthesisEngine(
|
||
blockSize: blockSize,
|
||
sampleRate: sampleRate,
|
||
numOutputChannels: 2,
|
||
numInputChannels: 0,
|
||
numAudioBuses: 128,
|
||
numControlBuses: 64,
|
||
driver: OfflineDriver()
|
||
)
|
||
try engine.start()
|
||
defer { engine.stop() }
|
||
|
||
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
|
||
driver.start()
|
||
defer { driver.stop() }
|
||
|
||
// --- Float32 run ---
|
||
let finishedF32: AsyncExpectation = AsyncExpectation()
|
||
let procF32: LyrebirdProcess = LyrebirdProcess(
|
||
id: "fmt-test-proc",
|
||
envelope: shortAutoEnvelope(),
|
||
numChannels: 1,
|
||
body: { ctx in await ctx.wait(0.01) },
|
||
onFinished: { finishedF32.fulfill() }
|
||
)
|
||
|
||
let eventListF32: LyrebirdEventList = try LyrebirdEventList(
|
||
id: "fmt-list",
|
||
events: [LyrebirdEvent(starts: [procF32])],
|
||
engine: engine,
|
||
bus: AudioBus(index: 0, channelCount: 2)
|
||
)
|
||
eventListF32.record(directory: tempDirF32, format: .wavFloat32)
|
||
eventListF32.next()
|
||
_ = await finishedF32.waitForFulfillment(timeout: 10.0)
|
||
try await Task.sleep(nanoseconds: 150_000_000)
|
||
eventListF32.killAll()
|
||
|
||
// --- Int16 run ---
|
||
// Need to reset processes — proc instances can't be reused, create new list.
|
||
let finishedI16: AsyncExpectation = AsyncExpectation()
|
||
let procI16: LyrebirdProcess = LyrebirdProcess(
|
||
id: "fmt-test-proc",
|
||
envelope: shortAutoEnvelope(),
|
||
numChannels: 1,
|
||
body: { ctx in await ctx.wait(0.01) },
|
||
onFinished: { finishedI16.fulfill() }
|
||
)
|
||
|
||
let eventListI16: LyrebirdEventList = try LyrebirdEventList(
|
||
id: "fmt-list",
|
||
events: [LyrebirdEvent(starts: [procI16])],
|
||
engine: engine,
|
||
bus: AudioBus(index: 0, channelCount: 2)
|
||
)
|
||
eventListI16.record(directory: tempDirI16, format: .wavInt16)
|
||
eventListI16.next()
|
||
_ = await finishedI16.waitForFulfillment(timeout: 10.0)
|
||
try await Task.sleep(nanoseconds: 150_000_000)
|
||
eventListI16.killAll()
|
||
|
||
// Measure file sizes.
|
||
let filesF32: [URL] = (try? FileManager.default.contentsOfDirectory(
|
||
at: tempDirF32, includingPropertiesForKeys: nil
|
||
)) ?? []
|
||
let filesI16: [URL] = (try? FileManager.default.contentsOfDirectory(
|
||
at: tempDirI16, includingPropertiesForKeys: nil
|
||
)) ?? []
|
||
|
||
#expect(!filesF32.isEmpty, "Float32 stem file should exist")
|
||
#expect(!filesI16.isEmpty, "Int16 stem file should exist")
|
||
|
||
let sizeF32: Int = (try? FileManager.default.attributesOfItem(
|
||
atPath: filesF32.first?.path ?? ""))?[.size] as? Int ?? 0
|
||
let sizeI16: Int = (try? FileManager.default.attributesOfItem(
|
||
atPath: filesI16.first?.path ?? ""))?[.size] as? Int ?? 0
|
||
|
||
// Int16 (2 bytes/sample) should produce half the PCM payload of Float32 (4 bytes/sample).
|
||
// With headers the ratio will be slightly less than 2:1, but still clearly smaller.
|
||
#expect(sizeI16 < sizeF32,
|
||
"wavInt16 (\(sizeI16) bytes) should be smaller than wavFloat32 (\(sizeF32) bytes)")
|
||
#expect(sizeI16 > 0, "wavInt16 file should be non-empty")
|
||
#expect(sizeF32 > 0, "wavFloat32 file should be non-empty")
|
||
}
|
||
|
||
// MARK: - Test 8: channel count — stereo and quad
|
||
|
||
@Test("numChannels=2 produces stereo file; numChannels=4 produces 4-channel file")
|
||
func testChannelCount() async throws {
|
||
let tempDir2ch: URL = makeTempDir()
|
||
let tempDir4ch: URL = makeTempDir()
|
||
defer { removeTempDir(tempDir2ch); removeTempDir(tempDir4ch) }
|
||
|
||
let engine: SynthesisEngine = makeRecordingTestEngine()
|
||
try engine.start()
|
||
defer { engine.stop() }
|
||
|
||
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
|
||
driver.start()
|
||
defer { driver.stop() }
|
||
|
||
let fin2: AsyncExpectation = AsyncExpectation()
|
||
let proc2: LyrebirdProcess = LyrebirdProcess(
|
||
id: "ch2-proc",
|
||
envelope: shortAutoEnvelope(),
|
||
numChannels: 2,
|
||
body: { ctx in await ctx.wait(0.01) },
|
||
onFinished: { fin2.fulfill() }
|
||
)
|
||
|
||
let el2: LyrebirdEventList = try LyrebirdEventList(
|
||
id: "ch2-list",
|
||
events: [LyrebirdEvent(starts: [proc2])],
|
||
engine: engine,
|
||
bus: AudioBus(index: 0, channelCount: 2)
|
||
)
|
||
el2.record(directory: tempDir2ch, format: .wavFloat32)
|
||
el2.next()
|
||
_ = await fin2.waitForFulfillment(timeout: 10.0)
|
||
try await Task.sleep(nanoseconds: 150_000_000)
|
||
el2.killAll()
|
||
|
||
let fin4: AsyncExpectation = AsyncExpectation()
|
||
let proc4: LyrebirdProcess = LyrebirdProcess(
|
||
id: "ch4-proc",
|
||
envelope: shortAutoEnvelope(),
|
||
numChannels: 4,
|
||
body: { ctx in await ctx.wait(0.01) },
|
||
onFinished: { fin4.fulfill() }
|
||
)
|
||
|
||
let el4: LyrebirdEventList = try LyrebirdEventList(
|
||
id: "ch4-list",
|
||
events: [LyrebirdEvent(starts: [proc4])],
|
||
engine: engine,
|
||
bus: AudioBus(index: 0, channelCount: 4)
|
||
)
|
||
el4.record(directory: tempDir4ch, format: .wavFloat32)
|
||
el4.next()
|
||
_ = await fin4.waitForFulfillment(timeout: 10.0)
|
||
try await Task.sleep(nanoseconds: 150_000_000)
|
||
el4.killAll()
|
||
|
||
// Verify channel counts in the files.
|
||
let files2: [URL] = (try? FileManager.default.contentsOfDirectory(
|
||
at: tempDir2ch, includingPropertiesForKeys: nil
|
||
)) ?? []
|
||
let files4: [URL] = (try? FileManager.default.contentsOfDirectory(
|
||
at: tempDir4ch, includingPropertiesForKeys: nil
|
||
)) ?? []
|
||
|
||
#expect(!files2.isEmpty, "2-channel stem file should exist")
|
||
#expect(!files4.isEmpty, "4-channel stem file should exist")
|
||
|
||
if let f2: URL = files2.first, let info2: (frames: Int, channels: Int) = audioFileInfo(url: f2) {
|
||
#expect(info2.channels == 2, "Stem file should be 2 channels; got \(info2.channels)")
|
||
}
|
||
if let f4: URL = files4.first, let info4: (frames: Int, channels: Int) = audioFileInfo(url: f4) {
|
||
#expect(info4.channels == 4, "Stem file should be 4 channels; got \(info4.channels)")
|
||
}
|
||
}
|
||
|
||
// MARK: - Test 9: standalone Process — no recording API, regression
|
||
|
||
@Test("standalone Process still works when no recording API is wired")
|
||
func testStandaloneProcessRegression() async throws {
|
||
let engine: SynthesisEngine = makeRecordingTestEngine()
|
||
try engine.start()
|
||
defer { engine.stop() }
|
||
|
||
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
|
||
driver.start()
|
||
defer { driver.stop() }
|
||
|
||
let finished: AsyncExpectation = AsyncExpectation()
|
||
|
||
let proc: LyrebirdProcess = LyrebirdProcess(
|
||
id: "standalone-step3",
|
||
envelope: shortAutoEnvelope(),
|
||
numChannels: 1,
|
||
body: { ctx in await ctx.wait(0.01) },
|
||
onFinished: { finished.fulfill() }
|
||
)
|
||
|
||
// Standalone process — no _recordingConfig set.
|
||
#expect(proc._recordingConfig == nil)
|
||
|
||
proc.play(engine: engine)
|
||
let ok: Bool = await finished.waitForFulfillment(timeout: 10.0)
|
||
#expect(ok, "Standalone process should complete normally")
|
||
#expect(!proc.isRunning)
|
||
}
|
||
|
||
// MARK: - Test 10: filesystem-unsafe ID characters are sanitised
|
||
|
||
@Test("ID with '/' and spaces is sanitised in filename")
|
||
func testFilesystemUnsafeIDSanitised() async throws {
|
||
let tempDir: URL = makeTempDir()
|
||
defer { removeTempDir(tempDir) }
|
||
|
||
let engine: SynthesisEngine = makeRecordingTestEngine()
|
||
try engine.start()
|
||
defer { engine.stop() }
|
||
|
||
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
|
||
driver.start()
|
||
defer { driver.stop() }
|
||
|
||
let finished: AsyncExpectation = AsyncExpectation()
|
||
|
||
// IDs containing filesystem-unsafe characters.
|
||
let proc: LyrebirdProcess = LyrebirdProcess(
|
||
id: "proc/with spaces&special",
|
||
envelope: shortAutoEnvelope(),
|
||
numChannels: 1,
|
||
body: { ctx in await ctx.wait(0.01) },
|
||
onFinished: { finished.fulfill() }
|
||
)
|
||
|
||
let eventList: LyrebirdEventList = try LyrebirdEventList(
|
||
id: "list/with spaces",
|
||
events: [LyrebirdEvent(starts: [proc])],
|
||
engine: engine,
|
||
bus: AudioBus(index: 0, channelCount: 2)
|
||
)
|
||
|
||
eventList.record(directory: tempDir, format: .wavFloat32)
|
||
eventList.next()
|
||
|
||
_ = await finished.waitForFulfillment(timeout: 10.0)
|
||
try await Task.sleep(nanoseconds: 150_000_000)
|
||
|
||
let files: [URL] = (try? FileManager.default.contentsOfDirectory(
|
||
at: tempDir,
|
||
includingPropertiesForKeys: nil
|
||
)) ?? []
|
||
|
||
#expect(!files.isEmpty, "Stem file should have been created despite unsafe IDs")
|
||
|
||
if let f: URL = files.first {
|
||
let name: String = f.lastPathComponent
|
||
// Name must not contain '/' or ' '.
|
||
#expect(!name.contains("/"), "Filename must not contain '/' after sanitisation")
|
||
#expect(!name.contains(" "), "Filename must not contain spaces after sanitisation")
|
||
// Sanitised list ID prefix.
|
||
#expect(name.hasPrefix("list_with_spaces"),
|
||
"List ID should be sanitised to 'list_with_spaces'; name=\(name)")
|
||
}
|
||
|
||
eventList.killAll()
|
||
}
|
||
|
||
// MARK: - Test 11: DiskOut closes cleanly — file is readable after teardown
|
||
|
||
@Test("file is fully flushed and readable after process teardown")
|
||
func testDiskOutClosesCleanly() async throws {
|
||
let tempDir: URL = makeTempDir()
|
||
defer { removeTempDir(tempDir) }
|
||
|
||
let engine: SynthesisEngine = makeRecordingTestEngine()
|
||
try engine.start()
|
||
defer { engine.stop() }
|
||
|
||
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
|
||
driver.start()
|
||
defer { driver.stop() }
|
||
|
||
let finished: AsyncExpectation = AsyncExpectation()
|
||
|
||
let proc: LyrebirdProcess = LyrebirdProcess(
|
||
id: "clean-close-proc",
|
||
envelope: shortAutoEnvelope(),
|
||
numChannels: 1,
|
||
body: { ctx in await ctx.wait(0.01) },
|
||
onFinished: { finished.fulfill() }
|
||
)
|
||
|
||
let eventList: LyrebirdEventList = try LyrebirdEventList(
|
||
id: "clean-close-list",
|
||
events: [LyrebirdEvent(starts: [proc])],
|
||
engine: engine,
|
||
bus: AudioBus(index: 0, channelCount: 2)
|
||
)
|
||
|
||
eventList.record(directory: tempDir, format: .wavFloat32)
|
||
eventList.next()
|
||
|
||
_ = await finished.waitForFulfillment(timeout: 10.0)
|
||
try await Task.sleep(nanoseconds: 150_000_000)
|
||
|
||
let files: [URL] = (try? FileManager.default.contentsOfDirectory(
|
||
at: tempDir,
|
||
includingPropertiesForKeys: nil
|
||
)) ?? []
|
||
|
||
guard let stemFile: URL = files.first else {
|
||
#expect(Bool(false), "Expected a stem file")
|
||
return
|
||
}
|
||
|
||
// Open the file via ExtAudioFile — a truncated or corrupt file would fail here.
|
||
guard let info: (frames: Int, channels: Int) = audioFileInfo(url: stemFile) else {
|
||
#expect(Bool(false), "stem file should be openable; may be corrupt or truncated")
|
||
return
|
||
}
|
||
|
||
#expect(info.frames > 0, "Stem file should contain audio frames; got \(info.frames)")
|
||
#expect(info.channels == 1, "Stem file should be mono; got \(info.channels)")
|
||
|
||
// Read samples and verify they are parseable.
|
||
let samples: [[Float]]? = readAudioFileAsFloat32(url: stemFile, channelCount: 1)
|
||
#expect(samples != nil, "Should be able to read float samples from stem file")
|
||
if let s: [[Float]] = samples {
|
||
#expect(!s.isEmpty, "Samples array should not be empty")
|
||
}
|
||
|
||
eventList.killAll()
|
||
}
|
||
|
||
// MARK: - Test 12: isRecording / recordDirectory / recordFormat accessors
|
||
|
||
@Test("record() and stopRecord() update accessor properties correctly")
|
||
func testRecordingAccessors() throws {
|
||
let engine: SynthesisEngine = makeRecordingTestEngine()
|
||
let tempDir: URL = makeTempDir()
|
||
defer { removeTempDir(tempDir) }
|
||
|
||
let eventList: LyrebirdEventList = try LyrebirdEventList(
|
||
id: "accessors-list",
|
||
events: [],
|
||
engine: engine
|
||
)
|
||
|
||
// Initial state.
|
||
#expect(!eventList.isRecording)
|
||
#expect(eventList.recordDirectory == nil)
|
||
// Default format is wavFloat32 (internal default; accessors reflect it).
|
||
|
||
// Enable recording.
|
||
eventList.record(directory: tempDir, format: .wavInt24)
|
||
#expect(eventList.isRecording)
|
||
#expect(eventList.recordDirectory == tempDir)
|
||
#expect(eventList.recordFormat.fileExtension == "wav")
|
||
|
||
// Disable recording.
|
||
eventList.stopRecord()
|
||
#expect(!eventList.isRecording)
|
||
#expect(eventList.recordDirectory == nil)
|
||
}
|
||
|
||
// MARK: - Test 13 (B6 regression): stem filename offset derived from sample time
|
||
|
||
/// Verifies that the offset component of a stem filename is derived from the
|
||
/// engine's sample time rather than wall-clock time. The expected offset is
|
||
/// `(engineTimeAtPlay - engineTimeAtFirstEvent) / sampleRate`. For the first
|
||
/// event of a session the offset is always `0.0000000.0000` (zero samples elapsed).
|
||
@Test("B6 regression: stem filename offset is sample-time-based, matches timeline offset")
|
||
func testStemOffsetFromSampleTime() async throws {
|
||
let tempDir: URL = makeTempDir()
|
||
defer { removeTempDir(tempDir) }
|
||
|
||
let engine: SynthesisEngine = makeRecordingTestEngine()
|
||
try engine.start()
|
||
defer { engine.stop() }
|
||
|
||
let driver: TestBlockDriver = TestBlockDriver(engine: engine)
|
||
driver.start()
|
||
defer { driver.stop() }
|
||
|
||
let finished: AsyncExpectation = AsyncExpectation()
|
||
|
||
// The first process of a session always has offset == 0.0 (plays at first event,
|
||
// which also defines the origin).
|
||
let proc: LyrebirdProcess = LyrebirdProcess(
|
||
id: "b6-offset-proc",
|
||
envelope: shortAutoEnvelope(),
|
||
numChannels: 1,
|
||
body: { ctx in await ctx.wait(0.01) },
|
||
onFinished: { finished.fulfill() }
|
||
)
|
||
|
||
let eventList: LyrebirdEventList = try LyrebirdEventList(
|
||
id: "b6-offset-list",
|
||
events: [LyrebirdEvent(starts: [proc])],
|
||
engine: engine,
|
||
bus: AudioBus(index: 0, channelCount: 2)
|
||
)
|
||
|
||
eventList.record(directory: tempDir, format: .wavFloat32)
|
||
eventList.next() // fires event 0 — this is also the first event, so offset == 0
|
||
|
||
let ok: Bool = await finished.waitForFulfillment(timeout: 10.0)
|
||
#expect(ok, "Process should complete within timeout")
|
||
try await Task.sleep(nanoseconds: 150_000_000)
|
||
|
||
// The filename offset for the first-ever event is always 0.0000000.0000
|
||
// because engine sample time at first event == engine sample time at play.
|
||
let files: [URL] = (try? FileManager.default.contentsOfDirectory(
|
||
at: tempDir,
|
||
includingPropertiesForKeys: nil
|
||
)) ?? []
|
||
#expect(files.count == 1, "Expected exactly 1 stem file; got \(files.count)")
|
||
|
||
if let stemFile: URL = files.first {
|
||
let name: String = stemFile.deletingPathExtension().lastPathComponent
|
||
// Offset field is the second component after the sanitised list ID.
|
||
let listIDLen: Int = "b6-offset-list".count
|
||
let remainder: String = String(name.dropFirst(listIDLen + 1))
|
||
let offsetEnd: String.Index = remainder.firstIndex(of: "_") ?? remainder.endIndex
|
||
let offsetStr: String = String(remainder[..<offsetEnd])
|
||
let offsetVal: Double = Double(offsetStr) ?? -1.0
|
||
|
||
// The timeline entry for the first event should also have offset == 0.0.
|
||
let timelineOffset: Double = eventList.timeline.first?.offset ?? -1.0
|
||
|
||
#expect(
|
||
abs(offsetVal - timelineOffset) < 0.001,
|
||
"Stem filename offset (\(offsetVal)) should match timeline entry offset (\(timelineOffset))"
|
||
)
|
||
#expect(
|
||
offsetVal >= 0.0,
|
||
"Stem filename offset should be non-negative; got \(offsetVal)"
|
||
)
|
||
}
|
||
|
||
eventList.killAll()
|
||
}
|
||
}
|