v1.6.0 release: soundfile format expansion (WAV int depths + RF64 >4GB, AIFF/CAF, AAC/ALAC compressed, 4GB guard, unified AudioFileFormat)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-22 17:45:34 -07:00
parent 62b2f5dbec
commit 8eb64f883f
33 changed files with 2650 additions and 352 deletions
+209
View File
@@ -364,4 +364,213 @@ struct NRTDriverTests {
#expect(left.allSatisfy { abs($0 - 0.7) < 0.001 })
#expect(right.allSatisfy { $0 == 0.0 })
}
// MARK: - Output format selection
/// Build an NRT engine whose driver writes the given container/encoding.
func makeFormatEngine(outputURL: URL, format: AudioFileFormat, duration: Double,
sampleRate: Double = 44100,
numOutputChannels: Int = 2) -> SynthesisEngine {
let driver: NRTDriver = NRTDriver(outputURL: outputURL, duration: duration,
format: format)
return SynthesisEngine(
blockSize: 512,
sampleRate: sampleRate,
numOutputChannels: numOutputChannels,
numInputChannels: 0,
numAudioBuses: 128,
numControlBuses: 4096,
driver: driver
)
}
/// Render a short job in each container/encoding, then reopen the file and
/// assert its on-disk data format matches the requested case, plus the frame
/// count and channel count survive.
@Test("NRT output honours the requested container/encoding", arguments: [
AudioFileFormat.wavFloat32, .wavInt16, .wavInt24, .aiffFloat32, .cafFloat32
])
func nrtOutputFormat(format: AudioFileFormat) throws {
let sampleRate: Double = 44100
let numOutputChannels: Int = 2
let duration: Double = 0.1
// Matches NRTDriver's block math: ceil(duration * SR / blockSize) * blockSize.
let blockSize: Int = 512
let totalBlocks: Int = Int((duration * sampleRate / Double(blockSize)).rounded(.up))
let expectedFrames: Int = totalBlocks * blockSize
let url: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString)
.appendingPathExtension(format.fileExtension)
defer { try? FileManager.default.removeItem(at: url) }
let engine: SynthesisEngine = makeFormatEngine(
outputURL: url, format: format, duration: duration,
sampleRate: sampleRate, numOutputChannels: numOutputChannels
)
try engine.add(ConstantThrough())
try engine.start()
#expect(FileManager.default.fileExists(atPath: url.path))
var fileRef: ExtAudioFileRef?
let openStatus: OSStatus = ExtAudioFileOpenURL(url as CFURL, &fileRef)
#expect(openStatus == noErr)
let ref: ExtAudioFileRef = try #require(fileRef)
defer { ExtAudioFileDispose(ref) }
var asbd: AudioStreamBasicDescription = AudioStreamBasicDescription()
var propSize: UInt32 = UInt32(MemoryLayout<AudioStreamBasicDescription>.size)
let fmtStatus: OSStatus = ExtAudioFileGetProperty(
ref, kExtAudioFileProperty_FileDataFormat, &propSize, &asbd
)
#expect(fmtStatus == noErr)
#expect(asbd.mChannelsPerFrame == UInt32(numOutputChannels))
#expect(asbd.mBitsPerChannel == format.fileBitsPerChannel)
let isFloat: Bool = asbd.mFormatFlags & kAudioFormatFlagIsFloat != 0
#expect(isFloat == format.isFloatEncoding)
var frameCount: Int64 = 0
var countSize: UInt32 = UInt32(MemoryLayout<Int64>.size)
let countStatus: OSStatus = ExtAudioFileGetProperty(
ref, kExtAudioFileProperty_FileLengthFrames, &countSize, &frameCount
)
#expect(countStatus == noErr)
#expect(Int(frameCount) == expectedFrames)
}
/// A WAV render projected past the 4 GB RIFF cap must throw before rendering —
/// no file created, no per-block allocation. Driven by an absurd duration so the
/// guard fires immediately (the render loop is never entered).
@Test("NRT throws fileTooLargeForContainer for an oversize WAV render")
func nrtRejectsOversizeWav() {
let url: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString).appendingPathExtension("wav")
defer { try? FileManager.default.removeItem(at: url) }
let engine: SynthesisEngine = makeFormatEngine(
outputURL: url, format: .wavFloat32, duration: 100_000_000,
sampleRate: 48000, numOutputChannels: 2
)
#expect {
try engine.start()
} throws: { error in
guard case NRTDriverError.fileTooLargeForContainer(let projected, let cap) = error
else { return false }
return cap == lyrebirdMaxRIFFBytes && projected > cap
}
// Guard runs before ExtAudioFileCreateWithURL — the file must not exist.
#expect(!FileManager.default.fileExists(atPath: url.path))
}
/// NRT can render to the compressed M4A codecs (AAC / ALAC) via ExtAudioFile.
/// Read back through CoreAudio to prove the container is valid and non-silent.
@Test("NRT compressed (AAC / ALAC) render round-trips through CoreAudio", arguments: [
AudioFileFormat.aacHigh, .alac
])
func nrtCompressedRoundTrip(format: AudioFileFormat) throws {
let url: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString).appendingPathExtension("m4a")
defer { try? FileManager.default.removeItem(at: url) }
let engine: SynthesisEngine = makeFormatEngine(
outputURL: url, format: format, duration: 0.2,
sampleRate: 44100, numOutputChannels: 2
)
try engine.add(ConstantThrough())
try engine.start()
#expect(FileManager.default.fileExists(atPath: url.path))
let reloaded: LyrebirdBuffer = try LyrebirdBuffer.loadAllChannels(url: url)
#expect(reloaded.channelCount == 2)
#expect(reloaded.count > 0)
// Non-silent: the constant-0.5 source should decode to meaningful energy.
var peak: Double = 0
for f: Int in 0..<reloaded.count { peak = max(peak, abs(reloaded[f, 0])) }
#expect(peak > 0.1, "compressed NRT render decoded near-silent (peak \(peak))")
}
/// A non-finite, negative, or astronomically large duration must throw
/// `invalidDuration` rather than trapping in the `Int(Double)` block-count
/// conversion or the render range. `1e20` is finite and positive but its block
/// count exceeds `Int.max`, exercising the `< Double(Int.max)` bound.
@Test("NRT throws invalidDuration for NaN / negative / astronomical duration", arguments: [
Double.nan, -1.0, -0.001, Double.infinity, 1e20
])
func nrtRejectsInvalidDuration(duration: Double) {
let url: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString).appendingPathExtension("caf")
defer { try? FileManager.default.removeItem(at: url) }
let engine: SynthesisEngine = makeFormatEngine(
outputURL: url, format: .cafFloat32, duration: duration
)
#expect {
try engine.start()
} throws: { error in
guard case NRTDriverError.invalidDuration = error else { return false }
return true
}
}
/// NRT can render to RF64 (64-bit WAV via RF64Writer). Read back through the
/// CoreAudio reader to prove the container is valid.
@Test("NRT RF64 render round-trips through CoreAudio reader", arguments: [
AudioFileFormat.rf64Float32, .rf64Int24
])
func nrtRF64RoundTrip(format: AudioFileFormat) throws {
let sampleRate: Double = 44100
let numOutputChannels: Int = 2
let duration: Double = 0.05
let url: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString).appendingPathExtension("wav")
defer { try? FileManager.default.removeItem(at: url) }
let engine: SynthesisEngine = makeFormatEngine(
outputURL: url, format: format, duration: duration,
sampleRate: sampleRate, numOutputChannels: numOutputChannels
)
try engine.add(ConstantThrough())
try engine.start()
#expect(FileManager.default.fileExists(atPath: url.path))
// Reopen with CoreAudio (RF64-aware reader) and verify the constant 0.5 output.
let reloaded: LyrebirdBuffer = try LyrebirdBuffer.loadAllChannels(url: url)
#expect(reloaded.channelCount == numOutputChannels)
#expect(reloaded.count > 0)
let tolerance: Double = format == .rf64Int24 ? 2.0 / 8388608.0 : 1e-5
// Interior frames (skip the very first, which can be a startup zero).
for f: Int in 1..<reloaded.count {
#expect(abs(reloaded[f, 0] - 0.5) < tolerance, "RF64 NRT ch0 frame \(f)")
}
}
/// The default format (no `format:` argument) is still CAF / Float32 — the
/// pre-existing NRT contract must not change for callers that don't opt in.
@Test("NRT default output stays CAF / Float32")
func nrtDefaultFormatUnchanged() throws {
let url: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString).appendingPathExtension("caf")
defer { try? FileManager.default.removeItem(at: url) }
// makeNRTEngine builds NRTDriver with no format argument.
let engine: SynthesisEngine = makeNRTEngine(outputURL: url, duration: 0.1)
try engine.start()
var fileRef: ExtAudioFileRef?
#expect(ExtAudioFileOpenURL(url 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 == 32)
#expect(asbd.mFormatFlags & kAudioFormatFlagIsFloat != 0)
}
}
/// A synth that writes a constant to both output buses so the rendered file is
/// non-silent and integer encodings carry a verifiable non-zero value.
private final class ConstantThrough: SynthesizerBase {
override func build() {
output(bus: 0, source: 0.5)
output(bus: 1, source: 0.5)
}
}