8eb64f883f
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
788 lines
36 KiB
Swift
788 lines
36 KiB
Swift
// DiskInOutTests.swift
|
|
// Lyrebird
|
|
//
|
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
import Testing
|
|
import AudioToolbox
|
|
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
|
|
|
// MARK: - Helpers
|
|
|
|
private func writeTempWAV(channels: [[Float]], sampleRate: Double = 44100) throws -> URL {
|
|
precondition(!channels.isEmpty)
|
|
let frameCount: Int = channels[0].count
|
|
let nch: UInt32 = UInt32(channels.count)
|
|
let url: URL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString + ".wav")
|
|
|
|
let float32ByteSize: UInt32 = UInt32(MemoryLayout<Float>.size)
|
|
let float32BitsPerChannel: UInt32 = 32
|
|
var fmt: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
|
mSampleRate: sampleRate,
|
|
mFormatID: kAudioFormatLinearPCM,
|
|
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
|
mBytesPerPacket: float32ByteSize * nch,
|
|
mFramesPerPacket: 1,
|
|
mBytesPerFrame: float32ByteSize * nch,
|
|
mChannelsPerFrame: nch,
|
|
mBitsPerChannel: float32BitsPerChannel,
|
|
mReserved: 0
|
|
)
|
|
var ref: ExtAudioFileRef?
|
|
guard ExtAudioFileCreateWithURL(url as CFURL, kAudioFileWAVEType, &fmt, nil,
|
|
AudioFileFlags.eraseFile.rawValue, &ref) == noErr,
|
|
let ref: ExtAudioFileRef else { throw DiskInError.cannotOpenFile(-1) }
|
|
defer { ExtAudioFileDispose(ref) }
|
|
ExtAudioFileSetProperty(ref, kExtAudioFileProperty_ClientDataFormat,
|
|
UInt32(MemoryLayout<AudioStreamBasicDescription>.size), &fmt)
|
|
|
|
var interleaved: [Float] = [Float](repeating: 0, count: frameCount * channels.count)
|
|
for f: Int in 0..<frameCount {
|
|
for ch: Int in 0..<channels.count {
|
|
interleaved[f * channels.count + ch] = channels[ch][f]
|
|
}
|
|
}
|
|
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))
|
|
_ = ExtAudioFileWrite(ref, UInt32(frameCount), &bl)
|
|
}
|
|
return url
|
|
}
|
|
|
|
private func readWAVSamples(url: URL, channelCount: Int,
|
|
sampleRate: Double = 44100) throws -> [[Float]] {
|
|
var ref: ExtAudioFileRef?
|
|
guard ExtAudioFileOpenURL(url as CFURL, &ref) == noErr, let ref: ExtAudioFileRef else { return [] }
|
|
defer { ExtAudioFileDispose(ref) }
|
|
|
|
// Query total frame count
|
|
var frameCount: Int64 = 0
|
|
var propSize: UInt32 = UInt32(MemoryLayout<Int64>.size)
|
|
ExtAudioFileGetProperty(ref, kExtAudioFileProperty_FileLengthFrames,
|
|
&propSize, &frameCount)
|
|
|
|
let nch: UInt32 = UInt32(channelCount)
|
|
let float32ByteSize: UInt32 = UInt32(MemoryLayout<Float>.size)
|
|
let float32BitsPerChannel: UInt32 = 32
|
|
var fmt: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
|
mSampleRate: sampleRate,
|
|
mFormatID: kAudioFormatLinearPCM,
|
|
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
|
mBytesPerPacket: float32ByteSize * nch,
|
|
mFramesPerPacket: 1,
|
|
mBytesPerFrame: float32ByteSize * nch,
|
|
mChannelsPerFrame: nch,
|
|
mBitsPerChannel: float32BitsPerChannel,
|
|
mReserved: 0
|
|
)
|
|
ExtAudioFileSetProperty(ref, kExtAudioFileProperty_ClientDataFormat,
|
|
UInt32(MemoryLayout<AudioStreamBasicDescription>.size), &fmt)
|
|
|
|
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)
|
|
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
|
|
}
|
|
|
|
private func makeNRTEngine(outputURL: URL, duration: Double,
|
|
blockSize: Int = 512, sampleRate: Double = 44100,
|
|
numOutputChannels: Int = 2) -> SynthesisEngine {
|
|
let driver: NRTDriver = NRTDriver(outputURL: outputURL, duration: duration)
|
|
return SynthesisEngine(
|
|
blockSize: blockSize,
|
|
sampleRate: sampleRate,
|
|
numOutputChannels: numOutputChannels,
|
|
numInputChannels: 0,
|
|
numAudioBuses: 64,
|
|
numControlBuses: 256,
|
|
driver: driver
|
|
)
|
|
}
|
|
|
|
// MARK: - Tests
|
|
|
|
@MainActor
|
|
@Suite("DiskIn / DiskOut")
|
|
struct DiskInOutTests {
|
|
|
|
// MARK: - DiskIn basic read
|
|
|
|
@Test func diskInReadsDCSignal() throws {
|
|
let sampleRate: Double = 44100
|
|
let frameCount: Int = 512
|
|
let dcValue: Float = 0.6
|
|
let wavURL: URL = try writeTempWAV(channels: [[Float](repeating: dcValue, count: frameCount)],
|
|
sampleRate: sampleRate)
|
|
defer { try? FileManager.default.removeItem(at: wavURL) }
|
|
|
|
let diskIn: DiskIn.Audio = try DiskIn.Audio(url: wavURL, channelCount: 1,
|
|
sampleRate: sampleRate, bufferFrames: 512)
|
|
|
|
let outURL: URL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString + ".caf")
|
|
defer { try? FileManager.default.removeItem(at: outURL) }
|
|
|
|
final class MonoPlayer: SynthesizerBase {
|
|
let di: DiskIn.Audio
|
|
init(_ d: DiskIn.Audio) { di = d }
|
|
override func build() {
|
|
output(bus: 0, source: di)
|
|
output(bus: 1, source: di[0])
|
|
}
|
|
}
|
|
|
|
let engine: SynthesisEngine = makeNRTEngine(outputURL: outURL,
|
|
duration: Double(frameCount) / sampleRate)
|
|
try engine.add(MonoPlayer(diskIn))
|
|
try engine.start()
|
|
|
|
// Read bus 0 output from the CAF file
|
|
var fileRef: ExtAudioFileRef?
|
|
guard ExtAudioFileOpenURL(outURL as CFURL, &fileRef) == noErr,
|
|
let fileRef: ExtAudioFileRef else { Issue.record("Could not open output file"); return }
|
|
defer { ExtAudioFileDispose(fileRef) }
|
|
|
|
var clientFmt: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
|
mSampleRate: sampleRate, mFormatID: kAudioFormatLinearPCM,
|
|
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
|
mBytesPerPacket: 2 * UInt32(MemoryLayout<Float>.size), mFramesPerPacket: 1,
|
|
mBytesPerFrame: 2 * UInt32(MemoryLayout<Float>.size), mChannelsPerFrame: 2,
|
|
mBitsPerChannel: 32, mReserved: 0
|
|
)
|
|
ExtAudioFileSetProperty(fileRef, kExtAudioFileProperty_ClientDataFormat,
|
|
UInt32(MemoryLayout<AudioStreamBasicDescription>.size),
|
|
&clientFmt)
|
|
|
|
var buf: [Float] = [Float](repeating: 0, count: frameCount * 2)
|
|
var framesRead: UInt32 = UInt32(frameCount)
|
|
buf.withUnsafeMutableBufferPointer { ptr in
|
|
guard let base: UnsafeMutablePointer<Float> = ptr.baseAddress else { return }
|
|
var bl: AudioBufferList = AudioBufferList(mNumberBuffers: 1,
|
|
mBuffers: AudioBuffer(mNumberChannels: 2,
|
|
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
|
|
mData: base))
|
|
_ = ExtAudioFileRead(fileRef, &framesRead, &bl)
|
|
}
|
|
|
|
// Frames are interleaved L/R; check L (bus 0) — skip first sample (ramp-up)
|
|
let leftSamples: [Float] = stride(from: 2, to: Int(framesRead) * 2 - 2, by: 2).map { buf[$0] }
|
|
#expect(leftSamples.allSatisfy { abs(Double($0) - Double(dcValue)) < 0.01 })
|
|
}
|
|
|
|
// MARK: - DiskIn stereo read
|
|
|
|
@Test func diskInReadsStereoChannels() throws {
|
|
let sampleRate: Double = 44100
|
|
let frameCount: Int = 512
|
|
let wavURL: URL = try writeTempWAV(
|
|
channels: [[Float](repeating: 0.3, count: frameCount),
|
|
[Float](repeating: 0.7, count: frameCount)],
|
|
sampleRate: sampleRate
|
|
)
|
|
defer { try? FileManager.default.removeItem(at: wavURL) }
|
|
|
|
let diskIn: DiskIn.Audio = try DiskIn.Audio(url: wavURL, channelCount: 2,
|
|
sampleRate: sampleRate, bufferFrames: 512)
|
|
|
|
let outURL: URL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString + ".caf")
|
|
defer { try? FileManager.default.removeItem(at: outURL) }
|
|
|
|
final class StereoPlayer: SynthesizerBase {
|
|
let di: DiskIn.Audio
|
|
init(_ d: DiskIn.Audio) { di = d }
|
|
override func build() {
|
|
output(bus: 0, source: di[0])
|
|
output(bus: 1, source: di[1])
|
|
}
|
|
}
|
|
|
|
let engine: SynthesisEngine = makeNRTEngine(outputURL: outURL,
|
|
duration: Double(frameCount) / sampleRate)
|
|
try engine.add(StereoPlayer(diskIn))
|
|
try engine.start()
|
|
|
|
var fileRef: ExtAudioFileRef?
|
|
guard ExtAudioFileOpenURL(outURL as CFURL, &fileRef) == noErr,
|
|
let fileRef: ExtAudioFileRef else { Issue.record("Could not open output"); return }
|
|
defer { ExtAudioFileDispose(fileRef) }
|
|
|
|
var clientFmt: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
|
mSampleRate: sampleRate, mFormatID: kAudioFormatLinearPCM,
|
|
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
|
mBytesPerPacket: 2 * UInt32(MemoryLayout<Float>.size), mFramesPerPacket: 1,
|
|
mBytesPerFrame: 2 * UInt32(MemoryLayout<Float>.size), mChannelsPerFrame: 2,
|
|
mBitsPerChannel: 32, mReserved: 0
|
|
)
|
|
ExtAudioFileSetProperty(fileRef, kExtAudioFileProperty_ClientDataFormat,
|
|
UInt32(MemoryLayout<AudioStreamBasicDescription>.size),
|
|
&clientFmt)
|
|
|
|
var buf: [Float] = [Float](repeating: 0, count: frameCount * 2)
|
|
var framesRead: UInt32 = UInt32(frameCount)
|
|
buf.withUnsafeMutableBufferPointer { ptr in
|
|
guard let base: UnsafeMutablePointer<Float> = ptr.baseAddress else { return }
|
|
var bl: AudioBufferList = AudioBufferList(mNumberBuffers: 1,
|
|
mBuffers: AudioBuffer(mNumberChannels: 2,
|
|
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
|
|
mData: base))
|
|
_ = ExtAudioFileRead(fileRef, &framesRead, &bl)
|
|
}
|
|
|
|
let left: [Float] = stride(from: 2, to: Int(framesRead) * 2 - 2, by: 2).map { buf[$0] }
|
|
let right: [Float] = stride(from: 3, to: Int(framesRead) * 2 - 1, by: 2).map { buf[$0] }
|
|
#expect(left.allSatisfy { abs($0 - 0.3) < 0.01 })
|
|
#expect(right.allSatisfy { abs($0 - 0.7) < 0.01 })
|
|
}
|
|
|
|
// MARK: - DiskIn loop
|
|
|
|
@Test func diskInLoopWrapsAtEOF() throws {
|
|
let sampleRate: Double = 44100
|
|
let fileFrames: Int = 256 // short file — shorter than one render block
|
|
let renderFrames: Int = 512 // render two file-lengths
|
|
|
|
// Ramp 0→1 over fileFrames so we can detect wrapping
|
|
let ramp: [Float] = (0..<fileFrames).map { Float($0) / Float(fileFrames - 1) }
|
|
let wavURL: URL = try writeTempWAV(channels: [ramp], sampleRate: sampleRate)
|
|
defer { try? FileManager.default.removeItem(at: wavURL) }
|
|
|
|
let diskIn: DiskIn.Audio = try DiskIn.Audio(url: wavURL, channelCount: 1,
|
|
sampleRate: sampleRate, loop: true,
|
|
bufferFrames: 256)
|
|
|
|
let outURL: URL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString + ".caf")
|
|
defer { try? FileManager.default.removeItem(at: outURL) }
|
|
|
|
final class LoopPlayer: SynthesizerBase {
|
|
let di: DiskIn.Audio
|
|
init(_ d: DiskIn.Audio) { di = d }
|
|
override func build() {
|
|
output(bus: 0, source: di)
|
|
output(bus: 1, source: di)
|
|
}
|
|
}
|
|
|
|
let engine: SynthesisEngine = makeNRTEngine(outputURL: outURL,
|
|
duration: Double(renderFrames) / sampleRate)
|
|
try engine.add(LoopPlayer(diskIn))
|
|
try engine.start()
|
|
|
|
var fileRef: ExtAudioFileRef?
|
|
guard ExtAudioFileOpenURL(outURL as CFURL, &fileRef) == noErr,
|
|
let fileRef: ExtAudioFileRef else { Issue.record("Could not open output"); return }
|
|
defer { ExtAudioFileDispose(fileRef) }
|
|
|
|
var clientFmt: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
|
mSampleRate: sampleRate, mFormatID: kAudioFormatLinearPCM,
|
|
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
|
mBytesPerPacket: 2 * UInt32(MemoryLayout<Float>.size), mFramesPerPacket: 1,
|
|
mBytesPerFrame: 2 * UInt32(MemoryLayout<Float>.size), mChannelsPerFrame: 2,
|
|
mBitsPerChannel: 32, mReserved: 0
|
|
)
|
|
ExtAudioFileSetProperty(fileRef, kExtAudioFileProperty_ClientDataFormat,
|
|
UInt32(MemoryLayout<AudioStreamBasicDescription>.size),
|
|
&clientFmt)
|
|
|
|
var buf: [Float] = [Float](repeating: 0, count: renderFrames * 2)
|
|
var framesRead: UInt32 = UInt32(renderFrames)
|
|
buf.withUnsafeMutableBufferPointer { ptr in
|
|
guard let base: UnsafeMutablePointer<Float> = ptr.baseAddress else { return }
|
|
var bl: AudioBufferList = AudioBufferList(mNumberBuffers: 1,
|
|
mBuffers: AudioBuffer(mNumberChannels: 2,
|
|
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
|
|
mData: base))
|
|
_ = ExtAudioFileRead(fileRef, &framesRead, &bl)
|
|
}
|
|
|
|
// The file wraps: second half of output should start near 0 again (not stay at 1).
|
|
// Check that the final sample is NOT close to 1.0 (it would be if no looping occurred).
|
|
let lastLeft: Float = buf[(Int(framesRead) - 1) * 2]
|
|
let midLeft: Float = buf[fileFrames * 2] // sample at the wrap point in the output
|
|
|
|
// After looping, the midpoint should be somewhere between 0 and 1 (near the start of ramp),
|
|
// not still at the end (1.0).
|
|
#expect(midLeft < 0.5)
|
|
// Verify we rendered something (not all silence)
|
|
let hasSignal: Bool = buf.prefix(Int(framesRead) * 2).contains { $0 > 0.01 }
|
|
#expect(hasSignal)
|
|
_ = lastLeft // suppress unused-variable warning
|
|
}
|
|
|
|
// MARK: - DiskIn EOF triggers doneAction
|
|
|
|
@Test func diskInEOFSetsFreeNodeFlag() throws {
|
|
let sampleRate: Double = 44100
|
|
let fileFrames: Int = 512
|
|
let wavURL: URL = try writeTempWAV(
|
|
channels: [[Float](repeating: 0.5, count: fileFrames)],
|
|
sampleRate: sampleRate
|
|
)
|
|
defer { try? FileManager.default.removeItem(at: wavURL) }
|
|
|
|
let diskIn: DiskIn.Audio = try DiskIn.Audio(url: wavURL, channelCount: 1,
|
|
sampleRate: sampleRate,
|
|
doneAction: .freeNode,
|
|
bufferFrames: 512)
|
|
|
|
let outURL: URL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString + ".caf")
|
|
defer { try? FileManager.default.removeItem(at: outURL) }
|
|
|
|
final class EOFPlayer: SynthesizerBase {
|
|
let di: DiskIn.Audio
|
|
init(_ d: DiskIn.Audio) { di = d }
|
|
override func build() {
|
|
output(bus: 0, source: di)
|
|
output(bus: 1, source: di)
|
|
}
|
|
}
|
|
|
|
// Render more than the file length so EOF is definitely reached.
|
|
let engine: SynthesisEngine = makeNRTEngine(outputURL: outURL,
|
|
duration: Double(fileFrames * 3) / sampleRate)
|
|
try engine.add(EOFPlayer(diskIn))
|
|
try engine.start()
|
|
|
|
// needsFree should be true after rendering past EOF.
|
|
#expect(diskIn.needsFree)
|
|
}
|
|
|
|
// MARK: - DiskIn multi-buffer (exercises BG refill path)
|
|
|
|
@Test func diskInReadsAcrossBufferBoundaries() throws {
|
|
let sampleRate: Double = 44100
|
|
// bufferFrames > fileFrames/2 so both halves are filled synchronously in init,
|
|
// avoiding BG-timing races in the NRT renderer. The half-swap path is still
|
|
// exercised (readPos crosses bufferFrames at sample 2048).
|
|
let blockSize: Int = 512 // NRT default
|
|
let bufferFrames: Int = 2048 // must be power-of-two, > fileFrames/2 = 1280
|
|
let fileFrames: Int = blockSize * 5 // 2560 frames — spans into the second half
|
|
let dcValue: Float = 0.42
|
|
|
|
let wavURL: URL = try writeTempWAV(
|
|
channels: [[Float](repeating: dcValue, count: fileFrames)],
|
|
sampleRate: sampleRate
|
|
)
|
|
defer { try? FileManager.default.removeItem(at: wavURL) }
|
|
|
|
let diskIn: DiskIn.Audio = try DiskIn.Audio(url: wavURL, channelCount: 1,
|
|
sampleRate: sampleRate,
|
|
doneAction: .freeNode,
|
|
bufferFrames: bufferFrames)
|
|
|
|
let outURL: URL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString + ".caf")
|
|
defer { try? FileManager.default.removeItem(at: outURL) }
|
|
|
|
final class LongPlayer: SynthesizerBase {
|
|
let di: DiskIn.Audio
|
|
init(_ d: DiskIn.Audio) { di = d }
|
|
override func build() {
|
|
output(bus: 0, source: di)
|
|
output(bus: 1, source: di)
|
|
}
|
|
}
|
|
|
|
// Render at least 2 extra blocks beyond the file so EOF detection completes
|
|
// even when fileFrames is an exact multiple of bufferFrames.
|
|
let renderFrames: Int = fileFrames + 2 * bufferFrames
|
|
let engine: SynthesisEngine = makeNRTEngine(outputURL: outURL,
|
|
duration: Double(renderFrames) / sampleRate)
|
|
try engine.add(LongPlayer(diskIn))
|
|
try engine.start()
|
|
|
|
var fileRef: ExtAudioFileRef?
|
|
guard ExtAudioFileOpenURL(outURL as CFURL, &fileRef) == noErr,
|
|
let fileRef: ExtAudioFileRef else { Issue.record("Could not open output"); return }
|
|
defer { ExtAudioFileDispose(fileRef) }
|
|
|
|
var clientFmt: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
|
mSampleRate: sampleRate, mFormatID: kAudioFormatLinearPCM,
|
|
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
|
mBytesPerPacket: 2 * UInt32(MemoryLayout<Float>.size), mFramesPerPacket: 1,
|
|
mBytesPerFrame: 2 * UInt32(MemoryLayout<Float>.size), mChannelsPerFrame: 2,
|
|
mBitsPerChannel: 32, mReserved: 0
|
|
)
|
|
ExtAudioFileSetProperty(fileRef, kExtAudioFileProperty_ClientDataFormat,
|
|
UInt32(MemoryLayout<AudioStreamBasicDescription>.size),
|
|
&clientFmt)
|
|
|
|
let readFrames: Int = fileFrames
|
|
var buf: [Float] = [Float](repeating: 0, count: readFrames * 2)
|
|
var framesRead: UInt32 = UInt32(readFrames)
|
|
buf.withUnsafeMutableBufferPointer { ptr in
|
|
guard let base: UnsafeMutablePointer<Float> = ptr.baseAddress else { return }
|
|
var bl: AudioBufferList = AudioBufferList(mNumberBuffers: 1,
|
|
mBuffers: AudioBuffer(mNumberChannels: 2,
|
|
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
|
|
mData: base))
|
|
_ = ExtAudioFileRead(fileRef, &framesRead, &bl)
|
|
}
|
|
|
|
let leftSamples: [Float] = stride(from: 2, to: Int(framesRead) * 2 - 2, by: 2).map { buf[$0] }
|
|
#expect(leftSamples.allSatisfy { abs(Double($0) - Double(dcValue)) < 0.02 })
|
|
#expect(diskIn.needsFree)
|
|
}
|
|
|
|
// MARK: - DiskOut round-trip
|
|
|
|
@Test func diskOutWritesAndDiskInReadsBack() throws {
|
|
let sampleRate: Double = 44100
|
|
let renderFrames: Int = 512
|
|
let testValue: Float = 0.55
|
|
|
|
let diskOutURL: URL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString + ".wav")
|
|
let nrtOutURL: URL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString + ".caf")
|
|
defer {
|
|
try? FileManager.default.removeItem(at: diskOutURL)
|
|
try? FileManager.default.removeItem(at: nrtOutURL)
|
|
}
|
|
|
|
let diskOut: DiskOut.Audio = try DiskOut.Audio(source: Double(testValue),
|
|
channelCount: 1,
|
|
url: diskOutURL,
|
|
sampleRate: sampleRate,
|
|
format: .wav,
|
|
bufferFrames: 512)
|
|
|
|
final class RecordSynth: SynthesizerBase {
|
|
let d: DiskOut.Audio
|
|
init(_ d: DiskOut.Audio) { self.d = d }
|
|
override func build() {
|
|
output(bus: 0, source: d)
|
|
output(bus: 1, source: d)
|
|
}
|
|
}
|
|
|
|
let engine: SynthesisEngine = makeNRTEngine(outputURL: nrtOutURL,
|
|
duration: Double(renderFrames) / sampleRate)
|
|
try engine.add(RecordSynth(diskOut))
|
|
try engine.start()
|
|
diskOut.close()
|
|
|
|
// Verify diskOut wrote the expected value to disk.
|
|
let channels: [[Float]] = try readWAVSamples(url: diskOutURL, channelCount: 1,
|
|
sampleRate: sampleRate)
|
|
#expect(channels.count == 1)
|
|
let samples: [Float] = channels[0]
|
|
#expect(samples.count >= 1)
|
|
// Skip first sample (may be zero due to startup); check the rest.
|
|
let interior: [Float] = Array(samples.dropFirst())
|
|
#expect(interior.allSatisfy { abs(Double($0) - Double(testValue)) < 0.01 })
|
|
}
|
|
|
|
@Test func diskOutSmallWavDoesNotTripLargeFileGuard() throws {
|
|
// A normal short WAV recording must not trip the 4 GB container guard, and
|
|
// the guard wiring must leave the drain intact (file written, no errors).
|
|
// The overflow *decision* is covered by AudioFileFormat.riffOverflow unit
|
|
// tests — actually writing 4 GB in CI is infeasible.
|
|
let sampleRate: Double = 44100
|
|
let renderFrames: Int = 512
|
|
let testValue: Float = 0.4
|
|
|
|
let diskOutURL: URL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString + ".wav")
|
|
let nrtOutURL: URL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString + ".caf")
|
|
defer {
|
|
try? FileManager.default.removeItem(at: diskOutURL)
|
|
try? FileManager.default.removeItem(at: nrtOutURL)
|
|
}
|
|
|
|
let diskOut: DiskOut.Audio = try DiskOut.Audio(source: Double(testValue),
|
|
channelCount: 1,
|
|
url: diskOutURL,
|
|
sampleRate: sampleRate,
|
|
format: .wavFloat32,
|
|
bufferFrames: 512)
|
|
|
|
final class RecordSynth: SynthesizerBase {
|
|
let d: DiskOut.Audio
|
|
init(_ d: DiskOut.Audio) { self.d = d }
|
|
override func build() { output(bus: 0, source: d) }
|
|
}
|
|
|
|
let engine: SynthesisEngine = makeNRTEngine(outputURL: nrtOutURL,
|
|
duration: Double(renderFrames) / sampleRate)
|
|
try engine.add(RecordSynth(diskOut))
|
|
try engine.start()
|
|
diskOut.close()
|
|
|
|
#expect(diskOut.fileTooLarge == false)
|
|
#expect(diskOut.writeError == false)
|
|
|
|
let channels: [[Float]] = try readWAVSamples(url: diskOutURL, channelCount: 1,
|
|
sampleRate: sampleRate)
|
|
#expect(channels.count == 1)
|
|
let interior: [Float] = Array(channels[0].dropFirst())
|
|
#expect(interior.allSatisfy { abs(Double($0) - Double(testValue)) < 0.01 })
|
|
}
|
|
|
|
@Test func diskOutRF64StreamingRoundTrip() throws {
|
|
// Stream a constant through DiskOut to an RF64 target, close (patches ds64
|
|
// sizes), then read back through CoreAudio to prove the streamed RF64 file is
|
|
// valid and the size patch landed.
|
|
let sampleRate: Double = 44100
|
|
let renderFrames: Int = 1024
|
|
let testValue: Float = 0.3
|
|
|
|
let diskOutURL: URL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString + ".wav")
|
|
let nrtOutURL: URL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString + ".caf")
|
|
defer {
|
|
try? FileManager.default.removeItem(at: diskOutURL)
|
|
try? FileManager.default.removeItem(at: nrtOutURL)
|
|
}
|
|
|
|
let diskOut: DiskOut.Audio = try DiskOut.Audio(source: Double(testValue),
|
|
channelCount: 2,
|
|
url: diskOutURL,
|
|
sampleRate: sampleRate,
|
|
format: .rf64Float32,
|
|
bufferFrames: 512)
|
|
|
|
final class RecordSynth: SynthesizerBase {
|
|
let d: DiskOut.Audio
|
|
init(_ d: DiskOut.Audio) { self.d = d }
|
|
override func build() {
|
|
output(bus: 0, source: d)
|
|
output(bus: 1, source: d)
|
|
}
|
|
}
|
|
|
|
let engine: SynthesisEngine = makeNRTEngine(outputURL: nrtOutURL,
|
|
duration: Double(renderFrames) / sampleRate)
|
|
try engine.add(RecordSynth(diskOut))
|
|
try engine.start()
|
|
diskOut.close()
|
|
|
|
#expect(diskOut.writeError == false)
|
|
#expect(diskOut.fileTooLarge == false)
|
|
|
|
// First four bytes must be the RF64 FourCC.
|
|
let head: Data = try Data(contentsOf: diskOutURL).prefix(4)
|
|
#expect(String(decoding: head, as: UTF8.self) == "RF64")
|
|
|
|
// CoreAudio reads it back; the streamed constant survives.
|
|
let reloaded: LyrebirdBuffer = try LyrebirdBuffer.loadAllChannels(url: diskOutURL)
|
|
#expect(reloaded.channelCount == 2)
|
|
#expect(reloaded.count > 0)
|
|
for f: Int in 1..<reloaded.count {
|
|
#expect(abs(reloaded[f, 0] - Double(testValue)) < 1e-4, "RF64 DiskOut ch0 frame \(f)")
|
|
}
|
|
}
|
|
|
|
// MARK: - DiskOut stereo round-trip
|
|
|
|
@Test func diskOutStereoRoundTrip() throws {
|
|
let sampleRate: Double = 44100
|
|
let renderFrames: Int = 512
|
|
|
|
let diskOutURL: URL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString + ".wav")
|
|
let nrtOutURL: URL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString + ".caf")
|
|
defer {
|
|
try? FileManager.default.removeItem(at: diskOutURL)
|
|
try? FileManager.default.removeItem(at: nrtOutURL)
|
|
}
|
|
|
|
// Write a sine-wave file, then record its stereo pan output via DiskOut.
|
|
let fileFrames: Int = 512
|
|
let sine: [Float] = (0..<fileFrames).map { Float(sin(2 * Double.pi * 440 * Double($0) / sampleRate)) }
|
|
let wavURL: URL = try writeTempWAV(channels: [sine], sampleRate: sampleRate)
|
|
defer { try? FileManager.default.removeItem(at: wavURL) }
|
|
|
|
let diskIn: DiskIn.Audio = try DiskIn.Audio(url: wavURL, channelCount: 1,
|
|
sampleRate: sampleRate, bufferFrames: 512)
|
|
// Pan to stereo: L=diskIn * 0.4, R=diskIn * 0.8
|
|
let leftSrc: BinaryOpGenerator = diskIn * (0.4 as Double)
|
|
let rightSrc: BinaryOpGenerator = diskIn * (0.8 as Double)
|
|
// Interleave both channels into a single 2-ch generator via BinaryOpGenerator
|
|
let diskOut: DiskOut.Audio = try DiskOut.Audio(source: leftSrc,
|
|
channelCount: 1,
|
|
url: diskOutURL,
|
|
sampleRate: sampleRate,
|
|
format: .wav,
|
|
bufferFrames: 512)
|
|
|
|
final class StereoRec: SynthesizerBase {
|
|
let di: DiskIn.Audio
|
|
let dol: DiskOut.Audio
|
|
let rightSrc: any ValidGeneratorInput
|
|
init(di: DiskIn.Audio, dol: DiskOut.Audio, rightSrc: any ValidGeneratorInput) {
|
|
self.di = di; self.dol = dol; self.rightSrc = rightSrc
|
|
}
|
|
override func build() {
|
|
output(bus: 0, source: dol)
|
|
output(bus: 1, source: rightSrc)
|
|
}
|
|
}
|
|
|
|
let engine: SynthesisEngine = makeNRTEngine(outputURL: nrtOutURL,
|
|
duration: Double(renderFrames) / sampleRate)
|
|
try engine.add(StereoRec(di: diskIn, dol: diskOut, rightSrc: rightSrc))
|
|
try engine.start()
|
|
diskOut.close()
|
|
|
|
let channels: [[Float]] = try readWAVSamples(url: diskOutURL, channelCount: 1,
|
|
sampleRate: sampleRate)
|
|
// DiskOut recorded the left channel (diskIn * 0.4). Verify it's non-zero
|
|
// and roughly matches the scaled sine.
|
|
let samples: [Float] = channels[0]
|
|
let nonZeroCount: Int = samples.filter { abs($0) > 0.001 }.count
|
|
#expect(nonZeroCount > fileFrames / 4)
|
|
}
|
|
|
|
// MARK: - Two concurrent DiskIn instances
|
|
|
|
@Test func twoConcurrentDiskInInstances() throws {
|
|
let sampleRate: Double = 44100
|
|
let frameCount: Int = 512
|
|
|
|
let wavA: URL = try writeTempWAV(channels: [[Float](repeating: 0.2, count: frameCount)],
|
|
sampleRate: sampleRate)
|
|
let wavB: URL = try writeTempWAV(channels: [[Float](repeating: 0.8, count: frameCount)],
|
|
sampleRate: sampleRate)
|
|
defer {
|
|
try? FileManager.default.removeItem(at: wavA)
|
|
try? FileManager.default.removeItem(at: wavB)
|
|
}
|
|
|
|
let diskInA: DiskIn.Audio = try DiskIn.Audio(url: wavA, channelCount: 1,
|
|
sampleRate: sampleRate, bufferFrames: 512)
|
|
let diskInB: DiskIn.Audio = try DiskIn.Audio(url: wavB, channelCount: 1,
|
|
sampleRate: sampleRate, bufferFrames: 512)
|
|
|
|
let outURL: URL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString + ".caf")
|
|
defer { try? FileManager.default.removeItem(at: outURL) }
|
|
|
|
final class DualPlayer: SynthesizerBase {
|
|
let a: DiskIn.Audio
|
|
let b: DiskIn.Audio
|
|
init(a: DiskIn.Audio, b: DiskIn.Audio) { self.a = a; self.b = b }
|
|
override func build() {
|
|
output(bus: 0, source: a) // 0.2 on left
|
|
output(bus: 1, source: b) // 0.8 on right
|
|
}
|
|
}
|
|
|
|
let engine: SynthesisEngine = makeNRTEngine(outputURL: outURL,
|
|
duration: Double(frameCount) / sampleRate)
|
|
try engine.add(DualPlayer(a: diskInA, b: diskInB))
|
|
try engine.start()
|
|
|
|
var fileRef: ExtAudioFileRef?
|
|
guard ExtAudioFileOpenURL(outURL as CFURL, &fileRef) == noErr,
|
|
let fileRef: ExtAudioFileRef else { Issue.record("Could not open output"); return }
|
|
defer { ExtAudioFileDispose(fileRef) }
|
|
|
|
var clientFmt: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
|
mSampleRate: sampleRate, mFormatID: kAudioFormatLinearPCM,
|
|
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
|
mBytesPerPacket: 2 * UInt32(MemoryLayout<Float>.size), mFramesPerPacket: 1,
|
|
mBytesPerFrame: 2 * UInt32(MemoryLayout<Float>.size), mChannelsPerFrame: 2,
|
|
mBitsPerChannel: 32, mReserved: 0
|
|
)
|
|
ExtAudioFileSetProperty(fileRef, kExtAudioFileProperty_ClientDataFormat,
|
|
UInt32(MemoryLayout<AudioStreamBasicDescription>.size),
|
|
&clientFmt)
|
|
|
|
var buf: [Float] = [Float](repeating: 0, count: frameCount * 2)
|
|
var framesRead: UInt32 = UInt32(frameCount)
|
|
buf.withUnsafeMutableBufferPointer { ptr in
|
|
guard let base: UnsafeMutablePointer<Float> = ptr.baseAddress else { return }
|
|
var bl: AudioBufferList = AudioBufferList(mNumberBuffers: 1,
|
|
mBuffers: AudioBuffer(mNumberChannels: 2,
|
|
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
|
|
mData: base))
|
|
_ = ExtAudioFileRead(fileRef, &framesRead, &bl)
|
|
}
|
|
|
|
let left: [Float] = stride(from: 2, to: Int(framesRead) * 2 - 2, by: 2).map { buf[$0] }
|
|
let right: [Float] = stride(from: 3, to: Int(framesRead) * 2 - 1, by: 2).map { buf[$0] }
|
|
#expect(left.allSatisfy { abs($0 - 0.2) < 0.01 })
|
|
#expect(right.allSatisfy { abs($0 - 0.8) < 0.01 })
|
|
}
|
|
|
|
// MARK: - DiskOut no-op after close
|
|
|
|
@Test func diskOutCloseIsIdempotent() throws {
|
|
let sampleRate: Double = 44100
|
|
let outURL: URL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString + ".wav")
|
|
let nrtURL: URL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString + ".caf")
|
|
defer {
|
|
try? FileManager.default.removeItem(at: outURL)
|
|
try? FileManager.default.removeItem(at: nrtURL)
|
|
}
|
|
|
|
let diskOut: DiskOut.Audio = try DiskOut.Audio(source: 0.0 as Double,
|
|
channelCount: 1,
|
|
url: outURL,
|
|
sampleRate: sampleRate,
|
|
format: .wav,
|
|
bufferFrames: 512)
|
|
let engine: SynthesisEngine = makeNRTEngine(outputURL: nrtURL, duration: 0.01)
|
|
final class Sink: SynthesizerBase {
|
|
let d: DiskOut.Audio
|
|
init(_ d: DiskOut.Audio) { self.d = d }
|
|
override func build() {
|
|
output(bus: 0, source: d)
|
|
output(bus: 1, source: d)
|
|
}
|
|
}
|
|
try engine.add(Sink(diskOut))
|
|
try engine.start()
|
|
diskOut.close()
|
|
diskOut.close() // second call must not crash or deadlock
|
|
#expect(FileManager.default.fileExists(atPath: outURL.path))
|
|
}
|
|
|
|
/// A `DiskOut.Audio` whose output path is unwritable must throw from `init`
|
|
/// rather than construct a half-built recorder. This throw happens before
|
|
/// `super.init()`, so the ring storage is freed by an explicit
|
|
/// `deallocate()` on the throw path (Swift does not run `deinit` for an
|
|
/// initializer that throws before `super.init()`).
|
|
@Test func diskOutInvalidURLThrows() {
|
|
// A path under a directory that does not exist — ExtAudioFileCreateWithURL fails.
|
|
let badURL: URL = URL(fileURLWithPath: "/nonexistent-dir-\(UUID().uuidString)/out.wav")
|
|
#expect(throws: DiskOutError.self) {
|
|
_ = try DiskOut.Audio(source: 0.0 as Double,
|
|
channelCount: 2,
|
|
url: badURL,
|
|
sampleRate: 44100,
|
|
format: .wav,
|
|
bufferFrames: 8192)
|
|
}
|
|
}
|
|
}
|