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:
@@ -0,0 +1,177 @@
|
||||
// AudioFileCompressedTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("AudioFileFormat compressed (AAC / ALAC)")
|
||||
struct AudioFileCompressedTests {
|
||||
|
||||
// MARK: - Derived properties
|
||||
|
||||
@Test("Compressed derived properties")
|
||||
func compressedProps() {
|
||||
for format: AudioFileFormat in [.aacHigh, .aacMedium, .alac] {
|
||||
#expect(format.audioFileTypeID == kAudioFileM4AType)
|
||||
#expect(format.fileExtension == "m4a")
|
||||
#expect(format.isCompressed == true)
|
||||
#expect(format.isFloatEncoding == false)
|
||||
#expect(format.usesRF64Writer == false)
|
||||
#expect(format.supportsLargeFiles == true) // not RIFF → 4 GB guard N/A
|
||||
#expect(format.riffOverflow(frameCount: Int.max / 4, channels: 8) == nil)
|
||||
}
|
||||
#expect(AudioFileFormat.aacHigh.aacBitrate == 256_000)
|
||||
#expect(AudioFileFormat.aacMedium.aacBitrate == 128_000)
|
||||
#expect(AudioFileFormat.alac.aacBitrate == nil)
|
||||
}
|
||||
|
||||
// MARK: - Container type on disk
|
||||
|
||||
@Test("Written m4a carries the requested codec", arguments: [
|
||||
(AudioFileFormat.aacHigh, kAudioFormatMPEG4AAC),
|
||||
(AudioFileFormat.aacMedium, kAudioFormatMPEG4AAC),
|
||||
(AudioFileFormat.alac, kAudioFormatAppleLossless),
|
||||
])
|
||||
func writtenCodecMatches(format: AudioFileFormat, formatID: AudioFormatID) throws {
|
||||
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: 4096)
|
||||
buffer.fillSine()
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString).appendingPathExtension("m4a")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
try buffer.write(to: url, format: format, sampleRate: 44100)
|
||||
|
||||
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.mFormatID == formatID)
|
||||
}
|
||||
|
||||
// MARK: - ALAC round-trip (lossless of the 24-bit source)
|
||||
|
||||
@Test("ALAC round-trips through CoreAudio within 24-bit tolerance")
|
||||
func alacRoundTrip() throws {
|
||||
let frameCount: Int = 4096
|
||||
let values: [Double] = (0..<frameCount).map { sin(2.0 * Double.pi * 5.0 * Double($0) / Double(frameCount)) * 0.5 }
|
||||
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: frameCount)
|
||||
buffer.fill { i, _ in values[i] }
|
||||
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString).appendingPathExtension("m4a")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
try buffer.write(to: url, format: .alac, sampleRate: 44100)
|
||||
let loaded: LyrebirdBuffer = try LyrebirdBuffer.load(url: url)
|
||||
|
||||
// ALAC is lossless of its 24-bit-quantised source; decoders may report a few
|
||||
// priming frames, so compare the overlapping interior. Tolerance ≈ 24-bit LSB.
|
||||
let tolerance: Double = 4.0 / 8388608.0
|
||||
let compareCount: Int = min(loaded.count, frameCount)
|
||||
#expect(compareCount > frameCount / 2) // most of the signal survived
|
||||
var maxErr: Double = 0
|
||||
for i: Int in 0..<compareCount {
|
||||
maxErr = max(maxErr, abs(loaded[i] - values[i]))
|
||||
}
|
||||
#expect(maxErr < tolerance, "ALAC max error \(maxErr) exceeds \(tolerance)")
|
||||
}
|
||||
|
||||
// MARK: - AAC round-trip (lossy — energy check)
|
||||
|
||||
@Test("AAC round-trips through CoreAudio and preserves signal energy", arguments: [
|
||||
AudioFileFormat.aacHigh, .aacMedium
|
||||
])
|
||||
func aacRoundTrip(format: AudioFileFormat) throws {
|
||||
let frameCount: Int = 8192
|
||||
let amplitude: Double = 0.5
|
||||
// A steady mid-band sine — AAC reconstructs this faithfully in energy terms.
|
||||
let values: [Double] = (0..<frameCount).map {
|
||||
sin(2.0 * Double.pi * 440.0 * Double($0) / 44100.0) * amplitude
|
||||
}
|
||||
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: frameCount)
|
||||
buffer.fill { i, _ in values[i] }
|
||||
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString).appendingPathExtension("m4a")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
try buffer.write(to: url, format: format, sampleRate: 44100)
|
||||
let loaded: LyrebirdBuffer = try LyrebirdBuffer.load(url: url)
|
||||
#expect(loaded.count > frameCount / 2)
|
||||
|
||||
// RMS of the decoded interior (skip the primed head) should be near the
|
||||
// input sine's RMS (amplitude / sqrt(2)); AAC is lossy so allow a wide band.
|
||||
let skip: Int = 2048
|
||||
guard loaded.count > skip else { Issue.record("decoded too short"); return }
|
||||
var sumSquares: Double = 0
|
||||
var n: Int = 0
|
||||
for i: Int in skip..<loaded.count {
|
||||
sumSquares += loaded[i] * loaded[i]
|
||||
n += 1
|
||||
}
|
||||
let rms: Double = (n > 0) ? (sumSquares / Double(n)).squareRoot() : 0
|
||||
let expectedRMS: Double = amplitude / 2.0.squareRoot()
|
||||
#expect(rms > expectedRMS * 0.6 && rms < expectedRMS * 1.4,
|
||||
"AAC decoded RMS \(rms) not near expected \(expectedRMS)")
|
||||
}
|
||||
|
||||
// MARK: - Bitrate config actually takes effect
|
||||
|
||||
/// The AAC bitrate tiers must differ on disk — proves `applyEncoderConfig` set the
|
||||
/// encoder bitrate rather than silently no-opping (both would otherwise default).
|
||||
@Test("aacHigh produces a larger file than aacMedium")
|
||||
func aacBitrateTiersDiffer() throws {
|
||||
let frameCount: Int = 44100 // ~1 s of broadband content at 44.1 kHz
|
||||
var rng: UInt64 = 0x1234_5678
|
||||
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: frameCount)
|
||||
buffer.fill { _, _ in
|
||||
// Cheap white-ish noise (xorshift) — broadband so bitrate matters.
|
||||
rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17
|
||||
return (Double(rng % 20000) / 10000.0 - 1.0) * 0.3
|
||||
}
|
||||
|
||||
func fileSize(_ format: AudioFileFormat) throws -> Int {
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString).appendingPathExtension("m4a")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
try buffer.write(to: url, format: format, sampleRate: 44100)
|
||||
let attrs: [FileAttributeKey: Any] = try FileManager.default.attributesOfItem(atPath: url.path)
|
||||
return (attrs[.size] as? Int) ?? 0
|
||||
}
|
||||
|
||||
let highSize: Int = try fileSize(.aacHigh)
|
||||
let mediumSize: Int = try fileSize(.aacMedium)
|
||||
#expect(highSize > mediumSize,
|
||||
"aacHigh (\(highSize) B) should exceed aacMedium (\(mediumSize) B)")
|
||||
}
|
||||
|
||||
// MARK: - DiskOut rejects compressed
|
||||
|
||||
@MainActor
|
||||
@Test("DiskOut.Audio rejects compressed formats", arguments: [
|
||||
AudioFileFormat.aacHigh, .aacMedium, .alac
|
||||
])
|
||||
func diskOutRejectsCompressed(format: AudioFileFormat) {
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString).appendingPathExtension("m4a")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
#expect {
|
||||
_ = try DiskOut.Audio(source: 0.0 as Double, channelCount: 1, url: url,
|
||||
sampleRate: 44100, format: format)
|
||||
} throws: { error in
|
||||
guard case DiskOutError.compressedFormatNotSupported(let rejected) = error
|
||||
else { return false }
|
||||
return rejected == format
|
||||
}
|
||||
// The guard fires before file creation — no file should exist.
|
||||
#expect(!FileManager.default.fileExists(atPath: url.path))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
// AudioFileFormatTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("AudioFileFormat")
|
||||
struct AudioFileFormatTests {
|
||||
|
||||
// MARK: - Derived properties (golden per case)
|
||||
|
||||
@Test("Container type IDs per case")
|
||||
func containerTypeIDs() {
|
||||
#expect(AudioFileFormat.wavFloat32.audioFileTypeID == kAudioFileWAVEType)
|
||||
#expect(AudioFileFormat.wavInt16.audioFileTypeID == kAudioFileWAVEType)
|
||||
#expect(AudioFileFormat.wavInt24.audioFileTypeID == kAudioFileWAVEType)
|
||||
#expect(AudioFileFormat.aiffFloat32.audioFileTypeID == kAudioFileAIFCType)
|
||||
#expect(AudioFileFormat.cafFloat32.audioFileTypeID == kAudioFileCAFType)
|
||||
}
|
||||
|
||||
@Test("File extensions per case")
|
||||
func fileExtensions() {
|
||||
#expect(AudioFileFormat.wavFloat32.fileExtension == "wav")
|
||||
#expect(AudioFileFormat.wavInt16.fileExtension == "wav")
|
||||
#expect(AudioFileFormat.wavInt24.fileExtension == "wav")
|
||||
#expect(AudioFileFormat.aiffFloat32.fileExtension == "aiff")
|
||||
#expect(AudioFileFormat.cafFloat32.fileExtension == "caf")
|
||||
}
|
||||
|
||||
@Test("Bit depth per case")
|
||||
func bitDepths() {
|
||||
#expect(AudioFileFormat.wavFloat32.fileBitsPerChannel == 32)
|
||||
#expect(AudioFileFormat.wavInt16.fileBitsPerChannel == 16)
|
||||
#expect(AudioFileFormat.wavInt24.fileBitsPerChannel == 24)
|
||||
#expect(AudioFileFormat.aiffFloat32.fileBitsPerChannel == 32)
|
||||
#expect(AudioFileFormat.cafFloat32.fileBitsPerChannel == 32)
|
||||
}
|
||||
|
||||
@Test("Float vs integer encoding per case")
|
||||
func floatEncoding() {
|
||||
#expect(AudioFileFormat.wavFloat32.isFloatEncoding == true)
|
||||
#expect(AudioFileFormat.aiffFloat32.isFloatEncoding == true)
|
||||
#expect(AudioFileFormat.cafFloat32.isFloatEncoding == true)
|
||||
#expect(AudioFileFormat.wavInt16.isFloatEncoding == false)
|
||||
#expect(AudioFileFormat.wavInt24.isFloatEncoding == false)
|
||||
}
|
||||
|
||||
@Test("Endianness per case (only AIFF-C is big-endian)")
|
||||
func endianness() {
|
||||
#expect(AudioFileFormat.aiffFloat32.isBigEndian == true)
|
||||
#expect(AudioFileFormat.wavFloat32.isBigEndian == false)
|
||||
#expect(AudioFileFormat.wavInt16.isBigEndian == false)
|
||||
#expect(AudioFileFormat.wavInt24.isBigEndian == false)
|
||||
#expect(AudioFileFormat.cafFloat32.isBigEndian == false)
|
||||
}
|
||||
|
||||
// MARK: - Back-compat shorthands
|
||||
|
||||
@Test("Back-compat shorthands map to Float32 cases")
|
||||
func backCompatShorthands() {
|
||||
#expect(AudioFileFormat.wav == .wavFloat32)
|
||||
#expect(AudioFileFormat.aiff == .aiffFloat32)
|
||||
#expect(AudioFileFormat.caf == .cafFloat32)
|
||||
}
|
||||
|
||||
/// The deprecated `DiskOutFormat` alias still resolves for external source
|
||||
/// compatibility. Annotated deprecated so the alias reference does not raise an
|
||||
/// in-tree deprecation warning (the whole point of the alias is out-of-tree use).
|
||||
@available(*, deprecated, message: "Exercises the deprecated DiskOutFormat alias.")
|
||||
@Test("DiskOutFormat alias still resolves to AudioFileFormat")
|
||||
func diskOutFormatAliasResolves() {
|
||||
#expect(DiskOutFormat.wavFloat32 == AudioFileFormat.wavFloat32)
|
||||
#expect(DiskOutFormat.aiff == AudioFileFormat.aiffFloat32)
|
||||
}
|
||||
|
||||
// MARK: - makeFileASBD golden fields
|
||||
|
||||
@Test("File ASBD — WAV Float32 stereo")
|
||||
func fileASBDWavFloat32() {
|
||||
let asbd: AudioStreamBasicDescription =
|
||||
AudioFileFormat.wavFloat32.makeFileASBD(sampleRate: 48000, channels: 2)
|
||||
#expect(asbd.mSampleRate == 48000)
|
||||
#expect(asbd.mFormatID == kAudioFormatLinearPCM)
|
||||
#expect(asbd.mBitsPerChannel == 32)
|
||||
#expect(asbd.mChannelsPerFrame == 2)
|
||||
#expect(asbd.mFramesPerPacket == 1)
|
||||
#expect(asbd.mBytesPerFrame == 8) // 4 bytes/sample × 2 ch
|
||||
#expect(asbd.mBytesPerPacket == 8)
|
||||
#expect(asbd.mFormatFlags & kAudioFormatFlagIsFloat != 0)
|
||||
#expect(asbd.mFormatFlags & kAudioFormatFlagIsPacked != 0)
|
||||
#expect(asbd.mFormatFlags & kAudioFormatFlagIsBigEndian == 0)
|
||||
#expect(asbd.mFormatFlags & kAudioFormatFlagIsSignedInteger == 0)
|
||||
}
|
||||
|
||||
@Test("File ASBD — WAV Int16 mono")
|
||||
func fileASBDWavInt16() {
|
||||
let asbd: AudioStreamBasicDescription =
|
||||
AudioFileFormat.wavInt16.makeFileASBD(sampleRate: 44100, channels: 1)
|
||||
#expect(asbd.mBitsPerChannel == 16)
|
||||
#expect(asbd.mBytesPerFrame == 2) // 2 bytes/sample × 1 ch
|
||||
#expect(asbd.mFormatFlags & kAudioFormatFlagIsSignedInteger != 0)
|
||||
#expect(asbd.mFormatFlags & kAudioFormatFlagIsFloat == 0)
|
||||
#expect(asbd.mFormatFlags & kAudioFormatFlagIsBigEndian == 0)
|
||||
}
|
||||
|
||||
@Test("File ASBD — WAV Int24 packed stereo")
|
||||
func fileASBDWavInt24() {
|
||||
let asbd: AudioStreamBasicDescription =
|
||||
AudioFileFormat.wavInt24.makeFileASBD(sampleRate: 96000, channels: 2)
|
||||
#expect(asbd.mBitsPerChannel == 24)
|
||||
#expect(asbd.mBytesPerFrame == 6) // 3 bytes/sample × 2 ch (packed)
|
||||
#expect(asbd.mFormatFlags & kAudioFormatFlagIsSignedInteger != 0)
|
||||
#expect(asbd.mFormatFlags & kAudioFormatFlagIsPacked != 0)
|
||||
}
|
||||
|
||||
@Test("File ASBD — AIFF-C Float32 is big-endian")
|
||||
func fileASBDAiffFloat32() {
|
||||
let asbd: AudioStreamBasicDescription =
|
||||
AudioFileFormat.aiffFloat32.makeFileASBD(sampleRate: 48000, channels: 1)
|
||||
#expect(asbd.mBitsPerChannel == 32)
|
||||
#expect(asbd.mBytesPerFrame == 4)
|
||||
#expect(asbd.mFormatFlags & kAudioFormatFlagIsFloat != 0)
|
||||
#expect(asbd.mFormatFlags & kAudioFormatFlagIsBigEndian != 0)
|
||||
}
|
||||
|
||||
// MARK: - makeClientASBD always native Float32
|
||||
|
||||
@Test("Client ASBD is native-endian Float32 regardless of file encoding")
|
||||
func clientASBDAlwaysFloat32() {
|
||||
for format: AudioFileFormat in [.wavFloat32, .wavInt16, .wavInt24, .aiffFloat32, .cafFloat32] {
|
||||
let asbd: AudioStreamBasicDescription =
|
||||
format.makeClientASBD(sampleRate: 48000, channels: 2)
|
||||
#expect(asbd.mFormatID == kAudioFormatLinearPCM)
|
||||
#expect(asbd.mBitsPerChannel == 32)
|
||||
#expect(asbd.mBytesPerFrame == 8) // Float32 × 2 ch
|
||||
#expect(asbd.mFormatFlags & kAudioFormatFlagIsFloat != 0)
|
||||
#expect(asbd.mFormatFlags & kAudioFormatFlagIsBigEndian == 0)
|
||||
#expect(asbd.mFormatFlags & kAudioFormatFlagIsSignedInteger == 0)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Large-file guard
|
||||
|
||||
@Test("supportsLargeFiles is true only for CAF")
|
||||
func supportsLargeFiles() {
|
||||
#expect(AudioFileFormat.cafFloat32.supportsLargeFiles == true)
|
||||
for format: AudioFileFormat in [.wavFloat32, .wavInt16, .wavInt24, .aiffFloat32] {
|
||||
#expect(format.supportsLargeFiles == false)
|
||||
}
|
||||
}
|
||||
|
||||
@Test("projectedByteCount tracks the format's bit depth")
|
||||
func projectedByteCount() {
|
||||
let frames: Int = 100
|
||||
let channels: Int = 2
|
||||
let bytesFloat32: Int = 4
|
||||
let bytesInt16: Int = 2
|
||||
let bytesInt24: Int = 3
|
||||
#expect(AudioFileFormat.wavFloat32.projectedByteCount(frameCount: frames, channels: channels) == frames * channels * bytesFloat32)
|
||||
#expect(AudioFileFormat.wavInt16.projectedByteCount(frameCount: frames, channels: channels) == frames * channels * bytesInt16)
|
||||
#expect(AudioFileFormat.wavInt24.projectedByteCount(frameCount: frames, channels: channels) == frames * channels * bytesInt24)
|
||||
#expect(AudioFileFormat.aiffFloat32.projectedByteCount(frameCount: frames, channels: channels) == frames * channels * bytesFloat32)
|
||||
}
|
||||
|
||||
@Test("riffOverflow flags an oversize WAV at the boundary and exempts CAF")
|
||||
func riffOverflowBoundary() {
|
||||
let cap: Int = lyrebirdMaxRIFFBytes
|
||||
let bytesPerSampleFloat32: Int = 4
|
||||
// Largest mono Float32 frame count that still fits under the cap.
|
||||
let underFrames: Int = cap / bytesPerSampleFloat32
|
||||
#expect(AudioFileFormat.wavFloat32.riffOverflow(frameCount: underFrames, channels: 1) == nil)
|
||||
|
||||
// One frame past that overflows (the cap's remainder mod 4 < 4 guarantees crossing).
|
||||
let over: (projected: Int, cap: Int)? =
|
||||
AudioFileFormat.wavFloat32.riffOverflow(frameCount: underFrames + 1, channels: 1)
|
||||
#expect(over != nil)
|
||||
#expect(over?.cap == cap)
|
||||
#expect((over?.projected ?? 0) > cap)
|
||||
|
||||
// AIFF-C is likewise 32-bit-capped.
|
||||
#expect(AudioFileFormat.aiffFloat32.riffOverflow(frameCount: underFrames + 1, channels: 1) != nil)
|
||||
|
||||
// CAF is 64-bit — never flagged, even for absurd sizes. (Returns nil before
|
||||
// projectedByteCount runs, so the multiply cannot overflow Int.)
|
||||
#expect(AudioFileFormat.cafFloat32.riffOverflow(frameCount: Int.max / 8, channels: 8) == nil)
|
||||
}
|
||||
|
||||
@Test("projectedByteCount / riffOverflow saturate instead of trapping on overflow")
|
||||
func projectedByteCountOverflowSafe() {
|
||||
// A frame count large enough to overflow the byte product must saturate to
|
||||
// Int.max (no trap) and be reported as over-cap for a 32-bit container.
|
||||
#expect(AudioFileFormat.wavFloat32.projectedByteCount(frameCount: Int.max, channels: 8) == Int.max)
|
||||
let over: (projected: Int, cap: Int)? =
|
||||
AudioFileFormat.wavFloat32.riffOverflow(frameCount: Int.max, channels: 8)
|
||||
#expect(over != nil)
|
||||
#expect(over?.projected == Int.max)
|
||||
}
|
||||
|
||||
@Test("LyrebirdBuffer.write throws fileTooLargeForContainer for oversize WAV projection")
|
||||
func bufferWriteGuardDecision() {
|
||||
// The decision the buffer guard makes is exactly riffOverflow — asserted here
|
||||
// without allocating a multi-GB buffer. A 200M-frame × 8ch Float32 projection
|
||||
// is ~6.4 GB > cap.
|
||||
let frames: Int = 200_000_000
|
||||
let channels: Int = 8
|
||||
#expect(AudioFileFormat.wavFloat32.riffOverflow(frameCount: frames, channels: channels) != nil)
|
||||
#expect(AudioFileFormat.cafFloat32.riffOverflow(frameCount: frames, channels: channels) == nil)
|
||||
}
|
||||
|
||||
// MARK: - Round-trip: write via factory-backed LyrebirdBuffer.write, reload
|
||||
|
||||
/// Write a mono ramp buffer in each Float32 container and reload it, confirming
|
||||
/// sample rate, frame count, and channel count survive the round-trip.
|
||||
@Test("Round-trip write→load preserves rate/frames/channels", arguments: [
|
||||
AudioFileFormat.wavFloat32, .aiffFloat32, .cafFloat32
|
||||
])
|
||||
func roundTripFloat32(format: AudioFileFormat) throws {
|
||||
let frameCount: Int = 256
|
||||
let sampleRate: Double = 44100
|
||||
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: frameCount)
|
||||
for i: Int in 0..<frameCount {
|
||||
buffer.setValue(Double(i) / Double(frameCount), at: i)
|
||||
}
|
||||
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString)
|
||||
.appendingPathExtension(format.fileExtension)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
try buffer.write(to: url, format: format, sampleRate: sampleRate)
|
||||
|
||||
let reloaded: LyrebirdBuffer = try LyrebirdBuffer.load(url: url)
|
||||
#expect(reloaded.count == frameCount)
|
||||
#expect(reloaded.channelCount == 1)
|
||||
let reloadedRate: Double = try #require(reloaded.sampleRate)
|
||||
#expect(abs(reloadedRate - sampleRate) < 1.0)
|
||||
|
||||
// Float32 is lossless for these ramp values — expect near-exact reload.
|
||||
let mid: Int = frameCount / 2
|
||||
#expect(abs(reloaded[mid] - buffer[mid]) < 1e-5)
|
||||
}
|
||||
|
||||
/// The written file's on-disk encoding matches the requested format's bit depth
|
||||
/// and float/integer flag (queried via the reopened file's data-format ASBD).
|
||||
@Test("Written file encoding matches requested format", arguments: [
|
||||
AudioFileFormat.wavFloat32, .wavInt16, .wavInt24, .aiffFloat32, .cafFloat32
|
||||
])
|
||||
func writtenEncodingMatches(format: AudioFileFormat) throws {
|
||||
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: 64)
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString)
|
||||
.appendingPathExtension(format.fileExtension)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
try buffer.write(to: url, format: format, sampleRate: 48000)
|
||||
|
||||
var fileRef: ExtAudioFileRef?
|
||||
let openStatus: OSStatus = ExtAudioFileOpenURL(url as CFURL, &fileRef)
|
||||
#expect(openStatus == noErr)
|
||||
let fileRef2: ExtAudioFileRef = try #require(fileRef)
|
||||
defer { ExtAudioFileDispose(fileRef2) }
|
||||
|
||||
var fileASBD: AudioStreamBasicDescription = AudioStreamBasicDescription()
|
||||
var size: UInt32 = UInt32(MemoryLayout<AudioStreamBasicDescription>.size)
|
||||
let status: OSStatus = ExtAudioFileGetProperty(
|
||||
fileRef2, kExtAudioFileProperty_FileDataFormat, &size, &fileASBD
|
||||
)
|
||||
#expect(status == noErr)
|
||||
#expect(fileASBD.mBitsPerChannel == format.fileBitsPerChannel)
|
||||
let isFloat: Bool = fileASBD.mFormatFlags & kAudioFormatFlagIsFloat != 0
|
||||
#expect(isFloat == format.isFloatEncoding)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
// RF64WriterTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("RF64Writer")
|
||||
struct RF64WriterTests {
|
||||
|
||||
// MARK: - Header golden bytes
|
||||
|
||||
@Test("RF64 header has RF64/WAVE/ds64/fmt/data structure")
|
||||
func headerStructure() throws {
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString).appendingPathExtension("wav")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: 8, channelCount: 2)
|
||||
try buffer.write(to: url, format: .rf64Float32, sampleRate: 48000)
|
||||
|
||||
let data: Data = try Data(contentsOf: url)
|
||||
#expect(data.count >= 104)
|
||||
func fourCC(_ off: Int) -> String { String(decoding: data[off..<off+4], as: UTF8.self) }
|
||||
#expect(fourCC(0) == "RF64")
|
||||
#expect(fourCC(8) == "WAVE")
|
||||
#expect(fourCC(12) == "ds64")
|
||||
#expect(fourCC(48) == "fmt ")
|
||||
#expect(fourCC(96) == "data")
|
||||
// RIFF-size and data-size sentinels.
|
||||
func u32(_ off: Int) -> UInt32 {
|
||||
data[off..<off+4].reversed().reduce(UInt32(0)) { ($0 << 8) | UInt32($1) }
|
||||
}
|
||||
#expect(u32(4) == 0xFFFF_FFFF) // RIFF size sentinel
|
||||
#expect(u32(100) == 0xFFFF_FFFF) // data size sentinel
|
||||
}
|
||||
|
||||
// MARK: - CoreAudio interop (RF64 read-back)
|
||||
|
||||
/// The definitive interop proof: write RF64 with RF64Writer, then reopen with
|
||||
/// CoreAudio's `ExtAudioFile` (via `LyrebirdBuffer.load`). CoreAudio reads RF64,
|
||||
/// so a successful load with matching samples proves the container is valid.
|
||||
@Test("RF64 Float32 round-trips through CoreAudio reader")
|
||||
func rf64Float32RoundTrip() throws {
|
||||
let frameCount: Int = 128
|
||||
let sampleRate: Double = 44100
|
||||
let values: [Double] = (0..<frameCount).map { -1.0 + 2.0 * Double($0) / Double(frameCount - 1) }
|
||||
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: frameCount)
|
||||
buffer.fill { i, _ in values[i] }
|
||||
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString).appendingPathExtension("wav")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
try buffer.write(to: url, format: .rf64Float32, sampleRate: sampleRate)
|
||||
|
||||
let loaded: LyrebirdBuffer = try LyrebirdBuffer.load(url: url)
|
||||
#expect(loaded.count == frameCount)
|
||||
#expect(loaded.channelCount == 1)
|
||||
let reloadedRate: Double = try #require(loaded.sampleRate)
|
||||
#expect(abs(reloadedRate - sampleRate) < 1.0)
|
||||
for i: Int in 0..<frameCount {
|
||||
#expect(abs(loaded[i] - values[i]) < 1e-5, "RF64 Float32 mismatch at \(i)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("RF64 Int24 round-trips through CoreAudio reader within one LSB")
|
||||
func rf64Int24RoundTrip() throws {
|
||||
let frameCount: Int = 128
|
||||
let values: [Double] = (0..<frameCount).map { -1.0 + 2.0 * Double($0) / Double(frameCount - 1) }
|
||||
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: frameCount)
|
||||
buffer.fill { i, _ in values[i] }
|
||||
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString).appendingPathExtension("wav")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
try buffer.write(to: url, format: .rf64Int24, sampleRate: 44100)
|
||||
|
||||
let loaded: LyrebirdBuffer = try LyrebirdBuffer.load(url: url)
|
||||
#expect(loaded.count == frameCount)
|
||||
let tolerance: Double = 2.0 / 8388608.0
|
||||
for i: Int in 0..<frameCount {
|
||||
#expect(abs(loaded[i] - values[i]) < tolerance, "RF64 Int24 mismatch at \(i)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("RF64 multichannel preserves channel order")
|
||||
func rf64MultichannelRoundTrip() throws {
|
||||
let frameCount: Int = 64
|
||||
let channelCount: Int = 3
|
||||
let ch: [[Double]] = [
|
||||
(0..<frameCount).map { 0.01 * Double($0) },
|
||||
(0..<frameCount).map { -0.02 * Double($0) },
|
||||
(0..<frameCount).map { 0.5 - 0.03 * Double($0) }
|
||||
]
|
||||
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: frameCount, channelCount: channelCount)
|
||||
for c: Int in 0..<channelCount {
|
||||
for f: Int in 0..<frameCount { buffer.setValue(ch[c][f], frame: f, channel: c) }
|
||||
}
|
||||
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString).appendingPathExtension("wav")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
try buffer.write(to: url, format: .rf64Float32, sampleRate: 48000)
|
||||
|
||||
let reloaded: LyrebirdBuffer = try LyrebirdBuffer.loadAllChannels(url: url)
|
||||
#expect(reloaded.channelCount == channelCount)
|
||||
#expect(reloaded.count == frameCount)
|
||||
for c: Int in 0..<channelCount {
|
||||
for f: Int in 0..<frameCount {
|
||||
#expect(abs(reloaded[f, c] - ch[c][f]) < 1e-5, "RF64 ch \(c) frame \(f) mismatch")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Odd `data`-payload length (mono Int24 × odd frames = odd byte count) must get a
|
||||
/// RIFF word-alignment pad byte and still read back correctly through CoreAudio.
|
||||
@Test("RF64 Int24 mono odd frame count round-trips (pad-byte path)")
|
||||
func rf64Int24OddFramesPadByte() throws {
|
||||
let frameCount: Int = 127 // 127 × 3 bytes = 381 (odd) → needs a pad byte
|
||||
let values: [Double] = (0..<frameCount).map { -0.5 + Double($0) / Double(frameCount) }
|
||||
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: frameCount)
|
||||
buffer.fill { i, _ in values[i] }
|
||||
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString).appendingPathExtension("wav")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
try buffer.write(to: url, format: .rf64Int24, sampleRate: 44100)
|
||||
|
||||
// File length must be even (header 104 + 381 data + 1 pad = 486).
|
||||
let fileBytes: Int = try Data(contentsOf: url).count
|
||||
#expect(fileBytes % 2 == 0)
|
||||
|
||||
let loaded: LyrebirdBuffer = try LyrebirdBuffer.load(url: url)
|
||||
#expect(loaded.count == frameCount)
|
||||
let tolerance: Double = 2.0 / 8388608.0
|
||||
for i: Int in 0..<frameCount {
|
||||
#expect(abs(loaded[i] - values[i]) < tolerance, "odd-frame Int24 mismatch at \(i)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("RF64 format is exempt from the 4 GB large-file guard")
|
||||
func rf64ExemptFromCap() {
|
||||
#expect(AudioFileFormat.rf64Float32.supportsLargeFiles == true)
|
||||
#expect(AudioFileFormat.rf64Int24.supportsLargeFiles == true)
|
||||
#expect(AudioFileFormat.rf64Float32.usesRF64Writer == true)
|
||||
// riffOverflow must never flag RF64, even at absurd sizes.
|
||||
#expect(AudioFileFormat.rf64Float32.riffOverflow(frameCount: Int.max / 8, channels: 8) == nil)
|
||||
}
|
||||
}
|
||||
@@ -496,6 +496,108 @@ struct DiskInOutTests {
|
||||
#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 {
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
/// NRT `build`-closure shim.
|
||||
@@ -286,6 +287,44 @@ struct EngineHostTests {
|
||||
}
|
||||
}
|
||||
|
||||
@Test func renderConcurrentHonoursJobFormat() async throws {
|
||||
let (dir, cleanup): (URL, () -> Void) = try makeScratchDir()
|
||||
defer { cleanup() }
|
||||
|
||||
let host: EngineHost = EngineHost()
|
||||
// A non-default format (WAV / Int16) must reach the output file.
|
||||
let outURL: URL = dir.appendingPathComponent("stem.wav")
|
||||
let jobs: [NRTJob] = [
|
||||
NRTJob(
|
||||
outputURL: outURL,
|
||||
duration: 0.05,
|
||||
format: .wavInt16,
|
||||
blockSize: 64,
|
||||
sampleRate: 44100,
|
||||
numOutputChannels: 2
|
||||
) { engine in
|
||||
try nrtBuildAdd(engine) { ConstSynth(value: 0.25) }
|
||||
}
|
||||
]
|
||||
|
||||
var results: [NRTResult] = []
|
||||
for try await result: NRTResult in host.renderConcurrent(jobs: jobs) {
|
||||
results.append(result)
|
||||
}
|
||||
#expect(results.count == 1)
|
||||
|
||||
var fileRef: ExtAudioFileRef?
|
||||
#expect(ExtAudioFileOpenURL(outURL as CFURL, &fileRef) == noErr)
|
||||
let ref: ExtAudioFileRef = try #require(fileRef)
|
||||
defer { ExtAudioFileDispose(ref) }
|
||||
var asbd: AudioStreamBasicDescription = AudioStreamBasicDescription()
|
||||
var size: UInt32 = UInt32(MemoryLayout<AudioStreamBasicDescription>.size)
|
||||
#expect(ExtAudioFileGetProperty(ref, kExtAudioFileProperty_FileDataFormat, &size, &asbd) == noErr)
|
||||
#expect(asbd.mBitsPerChannel == 16)
|
||||
#expect(asbd.mFormatFlags & kAudioFormatFlagIsSignedInteger != 0)
|
||||
#expect(asbd.mFormatFlags & kAudioFormatFlagIsFloat == 0)
|
||||
}
|
||||
|
||||
@Test func renderConcurrentPropagatesBuildFailure() async throws {
|
||||
let (dir, cleanup): (URL, () -> Void) = try makeScratchDir()
|
||||
defer { cleanup() }
|
||||
|
||||
@@ -176,6 +176,21 @@ private func writeTempMultichannelWAV(channels: [[Float]], sampleRate: Double =
|
||||
return url
|
||||
}
|
||||
|
||||
/// Reopen a written file and assert its on-disk PCM bit depth. A pure error-tolerance
|
||||
/// check cannot tell "correctly quantised to N-bit" from "quantiser silently disabled,
|
||||
/// still Float32" — a lossless Float32 round-trip has error smaller than the N-bit LSB
|
||||
/// tolerance and would pass. This positively confirms the integer encoding happened.
|
||||
private func expectFileBitDepth(_ url: URL, _ expected: UInt32) throws {
|
||||
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 == expected)
|
||||
}
|
||||
|
||||
// MARK: - load(url:channel:normalise:)
|
||||
|
||||
@MainActor
|
||||
@@ -409,6 +424,62 @@ struct LyrebirdBufferWriteTests {
|
||||
}
|
||||
}
|
||||
|
||||
@Test("write + load round-trip for WAV Int16 stays within one LSB")
|
||||
func roundTripWavInt16() throws {
|
||||
// A ramp across [-1, 1] exercises the quantiser over its full range.
|
||||
let frameCount: Int = 64
|
||||
let values: [Double] = (0..<frameCount).map { -1.0 + 2.0 * Double($0) / Double(frameCount - 1) }
|
||||
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: frameCount)
|
||||
buffer.fill { i, _ in values[i] }
|
||||
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString)
|
||||
.appendingPathExtension("wav")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
try buffer.write(to: url, format: .wavInt16, sampleRate: 44100)
|
||||
// Positively confirm the file is 16-bit — a tolerance-only check would pass
|
||||
// even if the write silently stayed Float32.
|
||||
try expectFileBitDepth(url, 16)
|
||||
|
||||
let loaded: LyrebirdBuffer = try LyrebirdBuffer.load(url: url)
|
||||
#expect(loaded.count == frameCount)
|
||||
// Int16 quantisation step = 1 / 32768 ≈ 3.05e-5. Allow ~2 LSB of slack
|
||||
// to cover rounding-mode differences in ExtAudioFile's conversion.
|
||||
let oneLSB: Double = 1.0 / 32768.0
|
||||
let tolerance: Double = 2.0 * oneLSB
|
||||
for i: Int in 0..<frameCount {
|
||||
#expect(abs(loaded[i] - values[i]) < tolerance,
|
||||
"Int16 round-trip error at \(i): \(loaded[i]) vs \(values[i])")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("write + load round-trip for WAV Int24 stays within one LSB")
|
||||
func roundTripWavInt24() throws {
|
||||
let frameCount: Int = 64
|
||||
let values: [Double] = (0..<frameCount).map { -1.0 + 2.0 * Double($0) / Double(frameCount - 1) }
|
||||
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: frameCount)
|
||||
buffer.fill { i, _ in values[i] }
|
||||
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString)
|
||||
.appendingPathExtension("wav")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
try buffer.write(to: url, format: .wavInt24, sampleRate: 44100)
|
||||
try expectFileBitDepth(url, 24)
|
||||
|
||||
let loaded: LyrebirdBuffer = try LyrebirdBuffer.load(url: url)
|
||||
#expect(loaded.count == frameCount)
|
||||
// Int24 quantisation step = 1 / 8388608 ≈ 1.19e-7. Allow ~2 LSB of slack.
|
||||
let oneLSB: Double = 1.0 / 8388608.0
|
||||
let tolerance: Double = 2.0 * oneLSB
|
||||
for i: Int in 0..<frameCount {
|
||||
#expect(abs(loaded[i] - values[i]) < tolerance,
|
||||
"Int24 round-trip error at \(i): \(loaded[i]) vs \(values[i])")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("write produces a file of non-zero size")
|
||||
func writeProducesNonEmptyFile() throws {
|
||||
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: 512)
|
||||
@@ -637,6 +708,44 @@ struct LyrebirdBufferMultichannelWriteTests {
|
||||
}
|
||||
}
|
||||
|
||||
@Test("3-channel WAV Int24 write preserves channel order within one LSB")
|
||||
func writeThreeChannelWavInt24RoundTrip() throws {
|
||||
let frameCount: Int = 32
|
||||
let channelCount: Int = 3
|
||||
// Distinct per-channel signals so a channel swap would fail the assert.
|
||||
let ch: [[Double]] = [
|
||||
(0..<frameCount).map { 0.01 * Double($0) },
|
||||
(0..<frameCount).map { -0.02 * Double($0) },
|
||||
(0..<frameCount).map { 0.5 - 0.03 * Double($0) }
|
||||
]
|
||||
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: frameCount, channelCount: channelCount)
|
||||
for c: Int in 0..<channelCount {
|
||||
for frame: Int in 0..<frameCount {
|
||||
buffer.setValue(ch[c][frame], frame: frame, channel: c)
|
||||
}
|
||||
}
|
||||
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString)
|
||||
.appendingPathExtension("wav")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
try buffer.write(to: url, format: .wavInt24, sampleRate: 44100)
|
||||
try expectFileBitDepth(url, 24)
|
||||
|
||||
let reloaded: LyrebirdBuffer = try LyrebirdBuffer.loadAllChannels(url: url)
|
||||
#expect(reloaded.count == frameCount)
|
||||
#expect(reloaded.channelCount == channelCount)
|
||||
|
||||
let tolerance: Double = 2.0 / 8388608.0 // ~2 LSB at 24-bit
|
||||
for c: Int in 0..<channelCount {
|
||||
for frame: Int in 0..<frameCount {
|
||||
#expect(abs(reloaded[frame, c] - ch[c][frame]) < tolerance,
|
||||
"Int24 channel \(c) frame \(frame) mismatch")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test("mono write + load backwards compatibility regression guard")
|
||||
func writeMonoBackwardsCompat() throws {
|
||||
let values: [Double] = [0.1, -0.2, 0.3, -0.4, 0.5]
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -282,6 +282,28 @@ struct LyrebirdEventListRecordingTests {
|
||||
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")
|
||||
|
||||
Reference in New Issue
Block a user