367 lines
17 KiB
Swift
367 lines
17 KiB
Swift
// NRTDriverTests.swift
|
|
// Lyrebird
|
|
//
|
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
import Testing
|
|
import AudioToolbox
|
|
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
|
|
|
@Suite("NRTDriver")
|
|
struct NRTDriverTests {
|
|
|
|
func makeTempURL() -> URL {
|
|
FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString + ".caf")
|
|
}
|
|
|
|
func makeNRTEngine(outputURL: URL, duration: Double,
|
|
blockSize: Int = 512, sampleRate: Double = 44100,
|
|
numOutputChannels: Int = 2,
|
|
numInputChannels: Int = 0,
|
|
inputURL: URL? = nil,
|
|
inputStartOffset: Double = 0.0) -> SynthesisEngine {
|
|
let driver: NRTDriver = NRTDriver(outputURL: outputURL, duration: duration,
|
|
inputURL: inputURL, inputStartOffset: inputStartOffset)
|
|
return SynthesisEngine(
|
|
blockSize: blockSize,
|
|
sampleRate: sampleRate,
|
|
numOutputChannels: numOutputChannels,
|
|
numInputChannels: numInputChannels,
|
|
numAudioBuses: 128,
|
|
numControlBuses: 4096,
|
|
driver: driver
|
|
)
|
|
}
|
|
|
|
@Test func outputFileIsCreated() throws {
|
|
let url: URL = makeTempURL()
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
let engine: SynthesisEngine = makeNRTEngine(outputURL: url, duration: 0.1)
|
|
try engine.start()
|
|
#expect(FileManager.default.fileExists(atPath: url.path))
|
|
}
|
|
|
|
@Test func rendersCorrectNumberOfBlocks() throws {
|
|
// ceil(44100.0 / 512.0) = 87 blocks
|
|
let url: URL = makeTempURL()
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
let engine: SynthesisEngine = makeNRTEngine(outputURL: url, duration: 1.0)
|
|
var evaluatorCallCount: Int = 0
|
|
engine._segmentEvaluator = { _, _ in evaluatorCallCount += 1 }
|
|
try engine.start()
|
|
// 87 blocks, 1 evaluator call per block (no events)
|
|
#expect(evaluatorCallCount == 87)
|
|
}
|
|
|
|
@Test func currentTimeAfterNRTRender() throws {
|
|
// ceil(44100.0 / 512.0) = 87 blocks; 87 * 512 = 44544
|
|
let url: URL = makeTempURL()
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
let engine: SynthesisEngine = makeNRTEngine(outputURL: url, duration: 1.0)
|
|
try engine.start()
|
|
#expect(engine.currentTime == 87 * 512)
|
|
}
|
|
|
|
@Test func outputFileIsNonEmpty() throws {
|
|
let url: URL = makeTempURL()
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
let engine: SynthesisEngine = makeNRTEngine(outputURL: url, duration: 0.1)
|
|
try engine.start()
|
|
let attrs: [FileAttributeKey : Any] = try FileManager.default.attributesOfItem(atPath: url.path)
|
|
let size: Int = attrs[.size] as? Int ?? 0
|
|
#expect(size > 0)
|
|
}
|
|
|
|
@Test func silentRenderProducesZeroSamples() throws {
|
|
let url: URL = makeTempURL()
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
let engine: SynthesisEngine = makeNRTEngine(outputURL: url, duration: 0.1,
|
|
blockSize: 512, sampleRate: 44100,
|
|
numOutputChannels: 2)
|
|
try engine.start()
|
|
|
|
// Read back samples using ExtAudioFile
|
|
var fileRef: ExtAudioFileRef?
|
|
let openStatus: OSStatus = ExtAudioFileOpenURL(url as CFURL, &fileRef)
|
|
#expect(openStatus == noErr)
|
|
guard let fileRef: ExtAudioFileRef else { return }
|
|
defer { ExtAudioFileDispose(fileRef) }
|
|
|
|
// Set client format: Float32, interleaved, 2 channels, 44100 Hz
|
|
var clientFormat: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
|
mSampleRate: 44100,
|
|
mFormatID: kAudioFormatLinearPCM,
|
|
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
|
mBytesPerPacket: 8,
|
|
mFramesPerPacket: 1,
|
|
mBytesPerFrame: 8,
|
|
mChannelsPerFrame: 2,
|
|
mBitsPerChannel: 32,
|
|
mReserved: 0
|
|
)
|
|
let setFmtStatus: OSStatus = ExtAudioFileSetProperty(
|
|
fileRef,
|
|
kExtAudioFileProperty_ClientDataFormat,
|
|
UInt32(MemoryLayout<AudioStreamBasicDescription>.size),
|
|
&clientFormat
|
|
)
|
|
#expect(setFmtStatus == noErr)
|
|
|
|
// Read first block (512 frames * 2 channels = 1024 floats)
|
|
let numFrames: UInt32 = 512
|
|
var buffer: [Float] = [Float](repeating: 99.0, count: Int(numFrames * 2))
|
|
var framesRead: UInt32 = numFrames
|
|
buffer.withUnsafeMutableBufferPointer { ptr in
|
|
var bufList: AudioBufferList = AudioBufferList(
|
|
mNumberBuffers: 1,
|
|
mBuffers: AudioBuffer(
|
|
mNumberChannels: 2,
|
|
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
|
|
mData: ptr.baseAddress
|
|
)
|
|
)
|
|
_ = ExtAudioFileRead(fileRef, &framesRead, &bufList)
|
|
}
|
|
|
|
for sample: Float in buffer.prefix(Int(framesRead) * 2) {
|
|
#expect(sample == 0.0)
|
|
}
|
|
}
|
|
|
|
// MARK: - Soundfile input tests
|
|
|
|
// Write a stereo interleaved Float32 WAV to a temp file.
|
|
private func writeTempStereoWAV(left: [Float], right: [Float],
|
|
sampleRate: Double = 44100) throws -> URL {
|
|
precondition(left.count == right.count)
|
|
let url: URL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString + ".wav")
|
|
let nch: UInt32 = 2
|
|
var fmt: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
|
mSampleRate: sampleRate, mFormatID: kAudioFormatLinearPCM,
|
|
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
|
mBytesPerPacket: 4 * nch, mFramesPerPacket: 1,
|
|
mBytesPerFrame: 4 * nch, mChannelsPerFrame: nch,
|
|
mBitsPerChannel: 32, mReserved: 0)
|
|
var ref: ExtAudioFileRef?
|
|
guard ExtAudioFileCreateWithURL(url as CFURL, kAudioFileWAVEType, &fmt, nil,
|
|
AudioFileFlags.eraseFile.rawValue, &ref) == noErr,
|
|
let ref: ExtAudioFileRef else { throw NRTDriverError.cannotCreateFile(-1) }
|
|
defer { ExtAudioFileDispose(ref) }
|
|
ExtAudioFileSetProperty(ref, kExtAudioFileProperty_ClientDataFormat,
|
|
UInt32(MemoryLayout<AudioStreamBasicDescription>.size), &fmt)
|
|
var interleaved: [Float] = [Float](repeating: 0, count: left.count * 2)
|
|
for i: Int in 0..<left.count { interleaved[i * 2] = left[i]; interleaved[i * 2 + 1] = right[i] }
|
|
interleaved.withUnsafeMutableBufferPointer { ptr in
|
|
var bl: AudioBufferList = AudioBufferList(mNumberBuffers: 1,
|
|
mBuffers: AudioBuffer(mNumberChannels: nch,
|
|
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
|
|
mData: ptr.baseAddress))
|
|
_ = ExtAudioFileWrite(ref, UInt32(left.count), &bl)
|
|
}
|
|
return url
|
|
}
|
|
|
|
// Write a mono Float32 WAV to a temp file.
|
|
private func writeTempMonoWAV(samples: [Float], sampleRate: Double = 44100) throws -> URL {
|
|
let url: URL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString + ".wav")
|
|
var fmt: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
|
mSampleRate: sampleRate, mFormatID: kAudioFormatLinearPCM,
|
|
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
|
mBytesPerPacket: 4, mFramesPerPacket: 1,
|
|
mBytesPerFrame: 4, mChannelsPerFrame: 1,
|
|
mBitsPerChannel: 32, mReserved: 0)
|
|
var ref: ExtAudioFileRef?
|
|
guard ExtAudioFileCreateWithURL(url as CFURL, kAudioFileWAVEType, &fmt, nil,
|
|
AudioFileFlags.eraseFile.rawValue, &ref) == noErr,
|
|
let ref: ExtAudioFileRef else { throw NRTDriverError.cannotCreateFile(-1) }
|
|
defer { ExtAudioFileDispose(ref) }
|
|
ExtAudioFileSetProperty(ref, kExtAudioFileProperty_ClientDataFormat,
|
|
UInt32(MemoryLayout<AudioStreamBasicDescription>.size), &fmt)
|
|
var mutable: [Float] = samples
|
|
mutable.withUnsafeMutableBufferPointer { ptr in
|
|
var bl: AudioBufferList = AudioBufferList(mNumberBuffers: 1,
|
|
mBuffers: AudioBuffer(mNumberChannels: 1,
|
|
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
|
|
mData: ptr.baseAddress))
|
|
_ = ExtAudioFileWrite(ref, UInt32(samples.count), &bl)
|
|
}
|
|
return url
|
|
}
|
|
|
|
// Read back the first `frameCount` stereo frames from a CAF output file.
|
|
private func readCafStereoSamples(url: URL, frameCount: Int) throws -> (left: [Float], right: [Float]) {
|
|
var ref: ExtAudioFileRef?
|
|
guard ExtAudioFileOpenURL(url as CFURL, &ref) == noErr, let ref: ExtAudioFileRef else {
|
|
return ([], [])
|
|
}
|
|
defer { ExtAudioFileDispose(ref) }
|
|
var fmt: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
|
mSampleRate: 44100, mFormatID: kAudioFormatLinearPCM,
|
|
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
|
mBytesPerPacket: 8, mFramesPerPacket: 1,
|
|
mBytesPerFrame: 8, mChannelsPerFrame: 2,
|
|
mBitsPerChannel: 32, mReserved: 0)
|
|
ExtAudioFileSetProperty(ref, kExtAudioFileProperty_ClientDataFormat,
|
|
UInt32(MemoryLayout<AudioStreamBasicDescription>.size), &fmt)
|
|
var buf: [Float] = [Float](repeating: 0, count: frameCount * 2)
|
|
var frames: UInt32 = UInt32(frameCount)
|
|
buf.withUnsafeMutableBufferPointer { ptr in
|
|
var bl: AudioBufferList = AudioBufferList(mNumberBuffers: 1,
|
|
mBuffers: AudioBuffer(mNumberChannels: 2,
|
|
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
|
|
mData: ptr.baseAddress))
|
|
_ = ExtAudioFileRead(ref, &frames, &bl)
|
|
}
|
|
let left: [Float] = stride(from: 0, to: Int(frames) * 2, by: 2).map { buf[$0] }
|
|
let right: [Float] = stride(from: 1, to: Int(frames) * 2, by: 2).map { buf[$0] }
|
|
return (left, right)
|
|
}
|
|
|
|
/// Stereo WAV routed through In.Audio(bus:0/1) → Out.Audio(bus:0) — output should contain
|
|
/// the input signal.
|
|
@Test func stereoInputFileFeeds2Channels() throws {
|
|
let frameCount: Int = 512
|
|
let inputLeft: [Float] = [Float](repeating: 0.5, count: frameCount)
|
|
let inputRight: [Float] = [Float](repeating: 0.25, count: frameCount)
|
|
let inputWAV: URL = try writeTempStereoWAV(left: inputLeft, right: inputRight)
|
|
defer { try? FileManager.default.removeItem(at: inputWAV) }
|
|
|
|
let outURL: URL = makeTempURL()
|
|
defer { try? FileManager.default.removeItem(at: outURL) }
|
|
|
|
final class PassThrough: SynthesizerBase {
|
|
override func build() {
|
|
// numOutputChannels=2, so input ch 0 is bus 2, input ch 1 is bus 3.
|
|
output(bus: 0, source: In.Audio(bus: 2))
|
|
output(bus: 1, source: In.Audio(bus: 3))
|
|
}
|
|
}
|
|
|
|
let engine: SynthesisEngine = makeNRTEngine(outputURL: outURL, duration: Double(frameCount) / 44100,
|
|
numOutputChannels: 2, numInputChannels: 2,
|
|
inputURL: inputWAV)
|
|
try engine.add(PassThrough())
|
|
try engine.start()
|
|
|
|
let (left, right) = try readCafStereoSamples(url: outURL, frameCount: frameCount)
|
|
#expect(left.allSatisfy { abs($0 - 0.5) < 0.001 })
|
|
#expect(right.allSatisfy { abs($0 - 0.25) < 0.001 })
|
|
}
|
|
|
|
/// `inputStartOffset` skips the first N seconds of the source file.
|
|
@Test func inputStartOffsetSkipsLeadingSilence() throws {
|
|
let sampleRate: Double = 44100
|
|
let blockSize: Int = 512
|
|
// 1-block silence followed by 1-block tone.
|
|
let silence: [Float] = [Float](repeating: 0.0, count: blockSize)
|
|
let tone: [Float] = [Float](repeating: 0.8, count: blockSize)
|
|
let inputWAV: URL = try writeTempMonoWAV(samples: silence + tone, sampleRate: sampleRate)
|
|
defer { try? FileManager.default.removeItem(at: inputWAV) }
|
|
|
|
let outURL: URL = makeTempURL()
|
|
defer { try? FileManager.default.removeItem(at: outURL) }
|
|
|
|
final class MonoThrough: SynthesizerBase {
|
|
override func build() {
|
|
// numOutputChannels=2, so mono input ch 0 is bus 2.
|
|
output(bus: 0, source: In.Audio(bus: 2))
|
|
output(bus: 1, source: In.Audio(bus: 2))
|
|
}
|
|
}
|
|
|
|
let offsetSeconds: Double = Double(blockSize) / sampleRate
|
|
let engine: SynthesisEngine = makeNRTEngine(outputURL: outURL, duration: Double(blockSize) / sampleRate,
|
|
numOutputChannels: 2, numInputChannels: 1,
|
|
inputURL: inputWAV, inputStartOffset: offsetSeconds)
|
|
try engine.add(MonoThrough())
|
|
try engine.start()
|
|
|
|
let (left, _) = try readCafStereoSamples(url: outURL, frameCount: blockSize)
|
|
// After skipping the silence block, the first output block should be the tone.
|
|
#expect(left.allSatisfy { abs($0 - 0.8) < 0.001 })
|
|
}
|
|
|
|
/// When the input file ends before render duration, remaining output is silence (no crash).
|
|
@Test func inputEOFPadsWithZeros() throws {
|
|
let sampleRate: Double = 44100
|
|
// Short file: only 256 frames, render for a full 512-frame block.
|
|
let inputWAV: URL = try writeTempMonoWAV(samples: [Float](repeating: 0.6, count: 256),
|
|
sampleRate: sampleRate)
|
|
defer { try? FileManager.default.removeItem(at: inputWAV) }
|
|
|
|
let outURL: URL = makeTempURL()
|
|
defer { try? FileManager.default.removeItem(at: outURL) }
|
|
|
|
final class MonoThrough: SynthesizerBase {
|
|
override func build() {
|
|
// numOutputChannels=2, so mono input ch 0 is bus 2.
|
|
output(bus: 0, source: In.Audio(bus: 2))
|
|
output(bus: 1, source: In.Audio(bus: 2))
|
|
}
|
|
}
|
|
|
|
let engine: SynthesisEngine = makeNRTEngine(outputURL: outURL,
|
|
duration: Double(512) / sampleRate,
|
|
numOutputChannels: 2, numInputChannels: 1,
|
|
inputURL: inputWAV)
|
|
try engine.add(MonoThrough())
|
|
// Must not throw.
|
|
try engine.start()
|
|
|
|
let (left, _) = try readCafStereoSamples(url: outURL, frameCount: 512)
|
|
// First 256 frames: tone; remaining 256: silence.
|
|
let firstHalf: [Float] = Array(left.prefix(256))
|
|
let secondHalf: [Float] = Array(left.suffix(256))
|
|
#expect(firstHalf.allSatisfy { abs($0 - 0.6) < 0.001 })
|
|
#expect(secondHalf.allSatisfy { $0 == 0.0 })
|
|
}
|
|
|
|
/// No inputURL → existing behaviour unchanged (no regression).
|
|
@Test func nilInputPreservesExistingBehavior() throws {
|
|
let url: URL = makeTempURL()
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
// numInputChannels: 0, inputURL: nil — same as original makeNRTEngine
|
|
let engine: SynthesisEngine = makeNRTEngine(outputURL: url, duration: 0.1,
|
|
numOutputChannels: 2, numInputChannels: 0,
|
|
inputURL: nil)
|
|
try engine.start()
|
|
#expect(FileManager.default.fileExists(atPath: url.path))
|
|
}
|
|
|
|
/// Mono file into a 2-input engine: input bus 0 has signal, input bus 1 stays zero.
|
|
@Test func monoFilePopulatesOnlyFirstInputBus() throws {
|
|
let sampleRate: Double = 44100
|
|
let frameCount: Int = 512
|
|
let inputWAV: URL = try writeTempMonoWAV(samples: [Float](repeating: 0.7, count: frameCount),
|
|
sampleRate: sampleRate)
|
|
defer { try? FileManager.default.removeItem(at: inputWAV) }
|
|
|
|
let outURL: URL = makeTempURL()
|
|
defer { try? FileManager.default.removeItem(at: outURL) }
|
|
|
|
// Route input bus 0 → output bus 0, input bus 1 → output bus 1.
|
|
final class DualBusThrough: SynthesizerBase {
|
|
override func build() {
|
|
// numOutputChannels=2, so input ch 0 is bus 2, ch 1 is bus 3.
|
|
output(bus: 0, source: In.Audio(bus: 2))
|
|
output(bus: 1, source: In.Audio(bus: 3))
|
|
}
|
|
}
|
|
|
|
let engine: SynthesisEngine = makeNRTEngine(outputURL: outURL,
|
|
duration: Double(frameCount) / sampleRate,
|
|
numOutputChannels: 2, numInputChannels: 2,
|
|
inputURL: inputWAV)
|
|
try engine.add(DualBusThrough())
|
|
try engine.start()
|
|
|
|
let (left, right) = try readCafStereoSamples(url: outURL, frameCount: frameCount)
|
|
#expect(left.allSatisfy { abs($0 - 0.7) < 0.001 })
|
|
#expect(right.allSatisfy { $0 == 0.0 })
|
|
}
|
|
}
|