8eb64f883f
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
946 lines
38 KiB
Swift
946 lines
38 KiB
Swift
// LyrebirdBufferFileIOTests.swift
|
|
// Lyrebird
|
|
//
|
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
import Testing
|
|
import Foundation
|
|
import AudioToolbox
|
|
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
|
|
|
// MARK: - Helpers
|
|
|
|
/// Write a mono Float32 WAV to a temp URL so tests can read it back via LyrebirdBuffer.
|
|
/// WAV reliably supports Float32; AIFF only supports it via AIFF-C.
|
|
/// Returns the URL of the created file.
|
|
private func writeTempMonoWAV(samples: [Float], sampleRate: Double = 44100) throws -> URL {
|
|
let url: URL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString)
|
|
.appendingPathExtension("wav")
|
|
|
|
var fmt: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
|
mSampleRate: sampleRate,
|
|
mFormatID: kAudioFormatLinearPCM,
|
|
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
|
mBytesPerPacket: 4,
|
|
mFramesPerPacket: 1,
|
|
mBytesPerFrame: 4,
|
|
mChannelsPerFrame: 1,
|
|
mBitsPerChannel: 32,
|
|
mReserved: 0
|
|
)
|
|
var fileRef: ExtAudioFileRef?
|
|
let createStatus: OSStatus = ExtAudioFileCreateWithURL(
|
|
url as CFURL, kAudioFileWAVEType, &fmt, nil,
|
|
AudioFileFlags.eraseFile.rawValue, &fileRef
|
|
)
|
|
guard createStatus == noErr, let fileRef: ExtAudioFileRef else {
|
|
throw LyrebirdBufferIOError.cannotCreateOutputFile(createStatus)
|
|
}
|
|
defer { ExtAudioFileDispose(fileRef) }
|
|
|
|
ExtAudioFileSetProperty(fileRef, kExtAudioFileProperty_ClientDataFormat,
|
|
UInt32(MemoryLayout<AudioStreamBasicDescription>.size), &fmt)
|
|
|
|
var mutableSamples: [Float] = samples
|
|
let sampleByteSize: UInt32 = UInt32(samples.count * MemoryLayout<Float>.size)
|
|
let frameCount: UInt32 = UInt32(samples.count)
|
|
mutableSamples.withUnsafeMutableBufferPointer { ptr in
|
|
var bufList: AudioBufferList = AudioBufferList(
|
|
mNumberBuffers: 1,
|
|
mBuffers: AudioBuffer(
|
|
mNumberChannels: 1,
|
|
mDataByteSize: sampleByteSize,
|
|
mData: ptr.baseAddress
|
|
)
|
|
)
|
|
_ = ExtAudioFileWrite(fileRef, frameCount, &bufList)
|
|
}
|
|
return url
|
|
}
|
|
|
|
/// Write a stereo (2-channel) interleaved Float32 WAV.
|
|
/// `left` and `right` must have equal length.
|
|
private func writeTempStereoWAV(left: [Float], right: [Float], sampleRate: Double = 44100) throws -> URL {
|
|
precondition(left.count == right.count)
|
|
let url: URL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString)
|
|
.appendingPathExtension("wav")
|
|
|
|
let channelCount: UInt32 = 2
|
|
var fmt: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
|
mSampleRate: sampleRate,
|
|
mFormatID: kAudioFormatLinearPCM,
|
|
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
|
mBytesPerPacket: 4 * channelCount,
|
|
mFramesPerPacket: 1,
|
|
mBytesPerFrame: 4 * channelCount,
|
|
mChannelsPerFrame: channelCount,
|
|
mBitsPerChannel: 32,
|
|
mReserved: 0
|
|
)
|
|
var fileRef: ExtAudioFileRef?
|
|
let createStatus: OSStatus = ExtAudioFileCreateWithURL(
|
|
url as CFURL, kAudioFileWAVEType, &fmt, nil,
|
|
AudioFileFlags.eraseFile.rawValue, &fileRef
|
|
)
|
|
guard createStatus == noErr, let fileRef: ExtAudioFileRef else {
|
|
throw LyrebirdBufferIOError.cannotCreateOutputFile(createStatus)
|
|
}
|
|
defer { ExtAudioFileDispose(fileRef) }
|
|
|
|
ExtAudioFileSetProperty(fileRef, kExtAudioFileProperty_ClientDataFormat,
|
|
UInt32(MemoryLayout<AudioStreamBasicDescription>.size), &fmt)
|
|
|
|
// Interleave left and right samples.
|
|
var interleaved: [Float] = [Float](repeating: 0, count: left.count * 2)
|
|
for i: Int in 0..<left.count {
|
|
interleaved[i * 2] = left[i]
|
|
interleaved[i * 2 + 1] = right[i]
|
|
}
|
|
|
|
let interleavedByteSize: UInt32 = UInt32(interleaved.count * MemoryLayout<Float>.size)
|
|
let frameCount: UInt32 = UInt32(left.count)
|
|
interleaved.withUnsafeMutableBufferPointer { ptr in
|
|
var bufList: AudioBufferList = AudioBufferList(
|
|
mNumberBuffers: 1,
|
|
mBuffers: AudioBuffer(
|
|
mNumberChannels: channelCount,
|
|
mDataByteSize: interleavedByteSize,
|
|
mData: ptr.baseAddress
|
|
)
|
|
)
|
|
_ = ExtAudioFileWrite(fileRef, frameCount, &bufList)
|
|
}
|
|
return url
|
|
}
|
|
|
|
/// Write an N-channel interleaved Float32 WAV to a temp URL.
|
|
/// `channels` is an array of per-channel sample arrays — all must have equal length.
|
|
private func writeTempMultichannelWAV(channels: [[Float]], sampleRate: Double = 44100) throws -> URL {
|
|
precondition(!channels.isEmpty)
|
|
let frameCount: Int = channels[0].count
|
|
precondition(channels.allSatisfy { $0.count == frameCount })
|
|
|
|
let url: URL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString)
|
|
.appendingPathExtension("wav")
|
|
|
|
let nChannels: UInt32 = UInt32(channels.count)
|
|
var fmt: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
|
mSampleRate: sampleRate,
|
|
mFormatID: kAudioFormatLinearPCM,
|
|
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
|
mBytesPerPacket: 4 * nChannels,
|
|
mFramesPerPacket: 1,
|
|
mBytesPerFrame: 4 * nChannels,
|
|
mChannelsPerFrame: nChannels,
|
|
mBitsPerChannel: 32,
|
|
mReserved: 0
|
|
)
|
|
var fileRef: ExtAudioFileRef?
|
|
let createStatus: OSStatus = ExtAudioFileCreateWithURL(
|
|
url as CFURL, kAudioFileWAVEType, &fmt, nil,
|
|
AudioFileFlags.eraseFile.rawValue, &fileRef
|
|
)
|
|
guard createStatus == noErr, let fileRef: ExtAudioFileRef else {
|
|
throw LyrebirdBufferIOError.cannotCreateOutputFile(createStatus)
|
|
}
|
|
defer { ExtAudioFileDispose(fileRef) }
|
|
|
|
ExtAudioFileSetProperty(fileRef, kExtAudioFileProperty_ClientDataFormat,
|
|
UInt32(MemoryLayout<AudioStreamBasicDescription>.size), &fmt)
|
|
|
|
// Interleave all channels.
|
|
var interleaved: [Float] = [Float](repeating: 0, count: frameCount * channels.count)
|
|
for frame: Int in 0..<frameCount {
|
|
for ch: Int in 0..<channels.count {
|
|
interleaved[frame * channels.count + ch] = channels[ch][frame]
|
|
}
|
|
}
|
|
|
|
let interleavedByteSize: UInt32 = UInt32(interleaved.count * MemoryLayout<Float>.size)
|
|
let frames: UInt32 = UInt32(frameCount)
|
|
interleaved.withUnsafeMutableBufferPointer { ptr in
|
|
var bufList: AudioBufferList = AudioBufferList(
|
|
mNumberBuffers: 1,
|
|
mBuffers: AudioBuffer(
|
|
mNumberChannels: nChannels,
|
|
mDataByteSize: interleavedByteSize,
|
|
mData: ptr.baseAddress
|
|
)
|
|
)
|
|
_ = ExtAudioFileWrite(fileRef, frames, &bufList)
|
|
}
|
|
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
|
|
@Suite("LyrebirdBuffer.load")
|
|
struct LyrebirdBufferLoadTests {
|
|
|
|
@Test("load allocates a buffer sized to the file's frame count")
|
|
func loadSizesBufferToFrameCount() throws {
|
|
let frameCount: Int = 256
|
|
let url: URL = try writeTempMonoWAV(samples: [Float](repeating: 0.5, count: frameCount))
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
|
|
let buffer: LyrebirdBuffer = try LyrebirdBuffer.load(url: url)
|
|
#expect(buffer.count == frameCount)
|
|
}
|
|
|
|
@Test("load round-trips mono samples accurately")
|
|
func loadRoundTripMono() throws {
|
|
let samples: [Float] = [0.1, 0.2, 0.3, -0.4, -0.5, 0.6]
|
|
let url: URL = try writeTempMonoWAV(samples: samples)
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
|
|
let buffer: LyrebirdBuffer = try LyrebirdBuffer.load(url: url)
|
|
#expect(buffer.count == samples.count)
|
|
let tolerance: Double = 1e-6
|
|
for i: Int in 0..<samples.count {
|
|
#expect(abs(buffer[i] - Double(samples[i])) < tolerance,
|
|
"Sample \(i): expected \(samples[i]), got \(buffer[i])")
|
|
}
|
|
}
|
|
|
|
@Test("load channel 0 extracts left channel of stereo file")
|
|
func loadChannelZeroFromStereo() throws {
|
|
let left: [Float] = [0.1, 0.2, 0.3, 0.4]
|
|
let right: [Float] = [-0.1, -0.2, -0.3, -0.4]
|
|
let url: URL = try writeTempStereoWAV(left: left, right: right)
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
|
|
let buffer: LyrebirdBuffer = try LyrebirdBuffer.load(url: url, channel: 0)
|
|
#expect(buffer.count == left.count)
|
|
let tolerance: Double = 1e-6
|
|
for i: Int in 0..<left.count {
|
|
#expect(abs(buffer[i] - Double(left[i])) < tolerance)
|
|
}
|
|
}
|
|
|
|
@Test("load channel 1 extracts right channel of stereo file")
|
|
func loadChannelOneFromStereo() throws {
|
|
let left: [Float] = [0.1, 0.2, 0.3, 0.4]
|
|
let right: [Float] = [-0.1, -0.2, -0.3, -0.4]
|
|
let url: URL = try writeTempStereoWAV(left: left, right: right)
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
|
|
let buffer: LyrebirdBuffer = try LyrebirdBuffer.load(url: url, channel: 1)
|
|
#expect(buffer.count == right.count)
|
|
let tolerance: Double = 1e-6
|
|
for i: Int in 0..<right.count {
|
|
#expect(abs(buffer[i] - Double(right[i])) < tolerance)
|
|
}
|
|
}
|
|
|
|
@Test("load with normalise scales peak to 1.0")
|
|
func loadNormalise() throws {
|
|
let samples: [Float] = [0.0, 0.25, 0.5, -0.5, 0.25]
|
|
let url: URL = try writeTempMonoWAV(samples: samples)
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
|
|
let buffer: LyrebirdBuffer = try LyrebirdBuffer.load(url: url, normalise: true)
|
|
// Peak input is 0.5, so after normalisation every value is doubled.
|
|
let tolerance: Double = 1e-5
|
|
#expect(abs(buffer[2] - 1.0) < tolerance) // 0.5 / 0.5 = 1.0
|
|
#expect(abs(buffer[3] - (-1.0)) < tolerance) // -0.5 / 0.5 = -1.0
|
|
#expect(abs(buffer[4] - 0.5) < tolerance) // 0.25 / 0.5 = 0.5
|
|
}
|
|
|
|
@Test("load normalise on silent file does not divide by zero")
|
|
func loadNormaliseSilent() throws {
|
|
let url: URL = try writeTempMonoWAV(samples: [Float](repeating: 0, count: 64))
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
|
|
let buffer: LyrebirdBuffer = try LyrebirdBuffer.load(url: url, normalise: true)
|
|
for i: Int in 0..<buffer.count {
|
|
#expect(buffer[i] == 0.0)
|
|
}
|
|
}
|
|
|
|
@Test("load throws channelOutOfRange when channel exceeds file channel count")
|
|
func loadChannelOutOfRange() throws {
|
|
let url: URL = try writeTempMonoWAV(samples: [0.1, 0.2, 0.3])
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
|
|
#expect(throws: (any Error).self) {
|
|
_ = try LyrebirdBuffer.load(url: url, channel: 1) // mono file has only channel 0
|
|
}
|
|
}
|
|
|
|
@Test("load throws on missing file")
|
|
func loadMissingFile() {
|
|
let url: URL = URL(fileURLWithPath: "/nonexistent/path/buffer.wav")
|
|
#expect(throws: (any Error).self) {
|
|
_ = try LyrebirdBuffer.load(url: url)
|
|
}
|
|
}
|
|
}
|
|
|
|
// MARK: - fill(fromFile:channel:normalise:)
|
|
|
|
@MainActor
|
|
@Suite("LyrebirdBuffer.fill(fromFile:)")
|
|
struct LyrebirdBufferFillFromFileTests {
|
|
|
|
@Test("fill(fromFile:) populates an existing buffer")
|
|
func fillExistingBuffer() throws {
|
|
let samples: [Float] = [0.1, 0.2, 0.3, 0.4, 0.5]
|
|
let url: URL = try writeTempMonoWAV(samples: samples)
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
|
|
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: samples.count)
|
|
try buffer.fill(fromFile: url)
|
|
|
|
let tolerance: Double = 1e-6
|
|
for i: Int in 0..<samples.count {
|
|
#expect(abs(buffer[i] - Double(samples[i])) < tolerance)
|
|
}
|
|
}
|
|
|
|
@Test("fill(fromFile:) truncates a longer file to buffer size")
|
|
func fillTruncatesLongerFile() throws {
|
|
let samples: [Float] = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]
|
|
let url: URL = try writeTempMonoWAV(samples: samples)
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
|
|
let bufferCount: Int = 4
|
|
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: bufferCount)
|
|
try buffer.fill(fromFile: url)
|
|
|
|
let tolerance: Double = 1e-6
|
|
for i: Int in 0..<bufferCount {
|
|
#expect(abs(buffer[i] - Double(samples[i])) < tolerance)
|
|
}
|
|
}
|
|
|
|
@Test("fill(fromFile:) zero-pads a shorter file")
|
|
func fillZeroPadsShorterFile() throws {
|
|
let samples: [Float] = [0.5, 0.6]
|
|
let url: URL = try writeTempMonoWAV(samples: samples)
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
|
|
let bufferCount: Int = 8
|
|
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: bufferCount)
|
|
buffer.fill(with: 1.0) // pre-fill with non-zero
|
|
try buffer.fill(fromFile: url)
|
|
|
|
#expect(abs(buffer[0] - 0.5) < 1e-6)
|
|
#expect(abs(buffer[1] - 0.6) < 1e-6)
|
|
for i: Int in 2..<bufferCount {
|
|
#expect(buffer[i] == 0.0, "Expected zero pad at index \(i)")
|
|
}
|
|
}
|
|
}
|
|
|
|
// MARK: - write(to:format:sampleRate:)
|
|
|
|
@MainActor
|
|
@Suite("LyrebirdBuffer.write")
|
|
struct LyrebirdBufferWriteTests {
|
|
|
|
@Test("write + load round-trip for AIFF format")
|
|
func roundTripAIFF() throws {
|
|
let values: [Double] = [0.1, 0.2, -0.3, 0.4, -0.5]
|
|
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: values.count)
|
|
buffer.fill { i, _ in values[i] }
|
|
|
|
let url: URL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString)
|
|
.appendingPathExtension("aiff")
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
|
|
try buffer.write(to: url, format: .aiff, sampleRate: 44100)
|
|
|
|
let loaded: LyrebirdBuffer = try LyrebirdBuffer.load(url: url)
|
|
#expect(loaded.count == values.count)
|
|
let tolerance: Double = 1e-6
|
|
for i: Int in 0..<values.count {
|
|
#expect(abs(loaded[i] - values[i]) < tolerance,
|
|
"AIFF round-trip mismatch at \(i): \(loaded[i]) vs \(values[i])")
|
|
}
|
|
}
|
|
|
|
@Test("write + load round-trip for WAV format")
|
|
func roundTripWAV() throws {
|
|
let values: [Double] = [-0.9, 0.0, 0.9, 0.5, -0.5]
|
|
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: values.count)
|
|
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: .wav, sampleRate: 44100)
|
|
|
|
let loaded: LyrebirdBuffer = try LyrebirdBuffer.load(url: url)
|
|
#expect(loaded.count == values.count)
|
|
let tolerance: Double = 1e-6
|
|
for i: Int in 0..<values.count {
|
|
#expect(abs(loaded[i] - values[i]) < tolerance,
|
|
"WAV round-trip mismatch at \(i): \(loaded[i]) vs \(values[i])")
|
|
}
|
|
}
|
|
|
|
@Test("write + load round-trip for CAF format")
|
|
func roundTripCAF() throws {
|
|
let values: [Double] = [0.25, -0.25, 0.75, -0.75]
|
|
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: values.count)
|
|
buffer.fill { i, _ in values[i] }
|
|
|
|
let url: URL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString)
|
|
.appendingPathExtension("caf")
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
|
|
try buffer.write(to: url, format: .caf, sampleRate: 48000)
|
|
|
|
let loaded: LyrebirdBuffer = try LyrebirdBuffer.load(url: url)
|
|
#expect(loaded.count == values.count)
|
|
let tolerance: Double = 1e-6
|
|
for i: Int in 0..<values.count {
|
|
#expect(abs(loaded[i] - values[i]) < tolerance,
|
|
"CAF round-trip mismatch at \(i)")
|
|
}
|
|
}
|
|
|
|
@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)
|
|
buffer.fillSine()
|
|
|
|
let url: URL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString)
|
|
.appendingPathExtension("caf")
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
|
|
try buffer.write(to: url, format: .caf)
|
|
|
|
let attrs: [FileAttributeKey : Any] = try FileManager.default.attributesOfItem(atPath: url.path)
|
|
let fileSize: Int = attrs[.size] as? Int ?? 0
|
|
#expect(fileSize > 0)
|
|
}
|
|
|
|
@Test("write throws on unwritable path")
|
|
func writeThrowsOnBadPath() {
|
|
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: 8)
|
|
let badURL: URL = URL(fileURLWithPath: "/nonexistent/dir/out.aiff")
|
|
#expect(throws: (any Error).self) {
|
|
try buffer.write(to: badURL)
|
|
}
|
|
}
|
|
|
|
@Test("write large buffer round-trips correctly across chunk boundaries")
|
|
func writeLargeBufferRoundTrip() throws {
|
|
// 9000 samples crosses the 4096-frame chunk boundary twice.
|
|
let count: Int = 9000
|
|
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: count)
|
|
buffer.fill { i, n in Double(i) / Double(n) } // ramp 0→1
|
|
|
|
let url: URL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString)
|
|
.appendingPathExtension("caf")
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
|
|
try buffer.write(to: url, format: .caf)
|
|
let loaded: LyrebirdBuffer = try LyrebirdBuffer.load(url: url)
|
|
|
|
#expect(loaded.count == count)
|
|
// Spot-check a few samples across chunk boundaries.
|
|
let tolerance: Double = 1e-5
|
|
for i: Int in [0, 1024, 4095, 4096, 4097, 8192, count - 1] {
|
|
let expected: Double = Double(i) / Double(count)
|
|
#expect(abs(loaded[i] - expected) < tolerance,
|
|
"Chunk boundary mismatch at index \(i)")
|
|
}
|
|
}
|
|
}
|
|
|
|
// MARK: - loadAllChannels(url:normalise:)
|
|
|
|
@MainActor
|
|
@Suite("LyrebirdBuffer.loadAllChannels")
|
|
struct LyrebirdBufferLoadAllChannelsTests {
|
|
|
|
@Test("loadAllChannels mono file → channelCount == 1, values match")
|
|
func loadAllChannelsMono() throws {
|
|
let samples: [Float] = [0.1, 0.2, 0.3, -0.4, -0.5, 0.6]
|
|
let url: URL = try writeTempMultichannelWAV(channels: [samples])
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
|
|
let buffer: LyrebirdBuffer = try LyrebirdBuffer.loadAllChannels(url: url)
|
|
#expect(buffer.count == samples.count)
|
|
#expect(buffer.channelCount == 1)
|
|
#expect(buffer.totalSampleCount == samples.count)
|
|
|
|
let tolerance: Double = 1e-6
|
|
for i: Int in 0..<samples.count {
|
|
#expect(abs(buffer[i, 0] - Double(samples[i])) < tolerance,
|
|
"Mono sample mismatch at frame \(i)")
|
|
}
|
|
}
|
|
|
|
@Test("loadAllChannels stereo file → channelCount == 2, both channels correct")
|
|
func loadAllChannelsStereo() throws {
|
|
let left: [Float] = [0.1, 0.2, 0.3, 0.4]
|
|
let right: [Float] = [-0.1, -0.2, -0.3, -0.4]
|
|
let url: URL = try writeTempMultichannelWAV(channels: [left, right])
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
|
|
let buffer: LyrebirdBuffer = try LyrebirdBuffer.loadAllChannels(url: url)
|
|
#expect(buffer.count == left.count)
|
|
#expect(buffer.channelCount == 2)
|
|
#expect(buffer.totalSampleCount == left.count * 2)
|
|
|
|
let tolerance: Double = 1e-6
|
|
for i: Int in 0..<left.count {
|
|
#expect(abs(buffer[i, 0] - Double(left[i])) < tolerance,
|
|
"Left channel mismatch at frame \(i)")
|
|
#expect(abs(buffer[i, 1] - Double(right[i])) < tolerance,
|
|
"Right channel mismatch at frame \(i)")
|
|
}
|
|
}
|
|
|
|
@Test("loadAllChannels 4-channel file → all channels verified")
|
|
func loadAllChannelsFourChannel() throws {
|
|
let frameCount: Int = 8
|
|
let ch0: [Float] = (0..<frameCount).map { Float($0) * 0.1 }
|
|
let ch1: [Float] = (0..<frameCount).map { Float($0) * 0.2 }
|
|
let ch2: [Float] = (0..<frameCount).map { Float($0) * -0.1 }
|
|
let ch3: [Float] = (0..<frameCount).map { Float($0) * -0.2 }
|
|
let url: URL = try writeTempMultichannelWAV(channels: [ch0, ch1, ch2, ch3])
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
|
|
let buffer: LyrebirdBuffer = try LyrebirdBuffer.loadAllChannels(url: url)
|
|
#expect(buffer.count == frameCount)
|
|
#expect(buffer.channelCount == 4)
|
|
|
|
let tolerance: Double = 1e-6
|
|
let channels: [[Float]] = [ch0, ch1, ch2, ch3]
|
|
for ch: Int in 0..<4 {
|
|
for frame: Int in 0..<frameCount {
|
|
#expect(abs(buffer[frame, ch] - Double(channels[ch][frame])) < tolerance,
|
|
"Channel \(ch) frame \(frame) mismatch")
|
|
}
|
|
}
|
|
}
|
|
|
|
@Test("loadAllChannels with normalise scales global peak to 1.0")
|
|
func loadAllChannelsNormalise() throws {
|
|
// Stereo: left peaks at 0.5, right peaks at 0.4 → global peak 0.5
|
|
let left: [Float] = [0.0, 0.5, -0.25]
|
|
let right: [Float] = [0.4, 0.0, 0.2]
|
|
let url: URL = try writeTempMultichannelWAV(channels: [left, right])
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
|
|
let buffer: LyrebirdBuffer = try LyrebirdBuffer.loadAllChannels(url: url, normalise: true)
|
|
let tolerance: Double = 1e-5
|
|
// Left channel: 0.5 / 0.5 = 1.0 at frame 1
|
|
#expect(abs(buffer[1, 0] - 1.0) < tolerance)
|
|
// Right channel: 0.4 / 0.5 = 0.8 at frame 0
|
|
#expect(abs(buffer[0, 1] - 0.8) < tolerance)
|
|
}
|
|
|
|
@Test("loadAllChannels normalise on silent file does not divide by zero")
|
|
func loadAllChannelsNormaliseSilent() throws {
|
|
let url: URL = try writeTempMultichannelWAV(
|
|
channels: [[Float](repeating: 0, count: 32), [Float](repeating: 0, count: 32)]
|
|
)
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
|
|
let buffer: LyrebirdBuffer = try LyrebirdBuffer.loadAllChannels(url: url, normalise: true)
|
|
for frame: Int in 0..<buffer.count {
|
|
for ch: Int in 0..<buffer.channelCount {
|
|
#expect(buffer[frame, ch] == 0.0)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// MARK: - Multichannel write round-trips
|
|
|
|
@MainActor
|
|
@Suite("LyrebirdBuffer multichannel write")
|
|
struct LyrebirdBufferMultichannelWriteTests {
|
|
|
|
@Test("2-channel CAF write + loadAllChannels round-trip")
|
|
func writeStereoCAFRoundTrip() throws {
|
|
let frameCount: Int = 64
|
|
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: frameCount, channelCount: 2)
|
|
// Populate interleaved storage via the linear subscript workaround:
|
|
// Since fill methods are mono-only, use loadAllChannels as both writer and reader.
|
|
// Instead: write a known stereo WAV, load it with loadAllChannels, then write CAF, reload.
|
|
let left: [Float] = (0..<frameCount).map { Float($0) / Float(frameCount) }
|
|
let right: [Float] = (0..<frameCount).map { -Float($0) / Float(frameCount) }
|
|
let srcURL: URL = try writeTempMultichannelWAV(channels: [left, right])
|
|
defer { try? FileManager.default.removeItem(at: srcURL) }
|
|
|
|
let loaded: LyrebirdBuffer = try LyrebirdBuffer.loadAllChannels(url: srcURL)
|
|
#expect(loaded.channelCount == 2)
|
|
|
|
let cafURL: URL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString)
|
|
.appendingPathExtension("caf")
|
|
defer { try? FileManager.default.removeItem(at: cafURL) }
|
|
|
|
try loaded.write(to: cafURL, format: .caf)
|
|
let reloaded: LyrebirdBuffer = try LyrebirdBuffer.loadAllChannels(url: cafURL)
|
|
|
|
#expect(reloaded.count == frameCount)
|
|
#expect(reloaded.channelCount == 2)
|
|
|
|
let tolerance: Double = 1e-6
|
|
for frame: Int in 0..<frameCount {
|
|
#expect(abs(reloaded[frame, 0] - Double(left[frame])) < tolerance,
|
|
"Left channel mismatch at frame \(frame)")
|
|
#expect(abs(reloaded[frame, 1] - Double(right[frame])) < tolerance,
|
|
"Right channel mismatch at frame \(frame)")
|
|
}
|
|
}
|
|
|
|
@Test("3-channel CAF write + loadAllChannels round-trip")
|
|
func writeThreeChannelCAFRoundTrip() throws {
|
|
let frameCount: Int = 32
|
|
let ch0: [Float] = (0..<frameCount).map { Float($0) * 0.01 }
|
|
let ch1: [Float] = (0..<frameCount).map { Float($0) * 0.02 }
|
|
let ch2: [Float] = (0..<frameCount).map { -Float($0) * 0.01 }
|
|
|
|
let srcURL: URL = try writeTempMultichannelWAV(channels: [ch0, ch1, ch2])
|
|
defer { try? FileManager.default.removeItem(at: srcURL) }
|
|
|
|
let loaded: LyrebirdBuffer = try LyrebirdBuffer.loadAllChannels(url: srcURL)
|
|
#expect(loaded.channelCount == 3)
|
|
|
|
let cafURL: URL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString)
|
|
.appendingPathExtension("caf")
|
|
defer { try? FileManager.default.removeItem(at: cafURL) }
|
|
|
|
try loaded.write(to: cafURL, format: .caf)
|
|
let reloaded: LyrebirdBuffer = try LyrebirdBuffer.loadAllChannels(url: cafURL)
|
|
|
|
#expect(reloaded.count == frameCount)
|
|
#expect(reloaded.channelCount == 3)
|
|
|
|
let tolerance: Double = 1e-6
|
|
let channels: [[Float]] = [ch0, ch1, ch2]
|
|
for ch: Int in 0..<3 {
|
|
for frame: Int in 0..<frameCount {
|
|
#expect(abs(reloaded[frame, ch] - Double(channels[ch][frame])) < tolerance,
|
|
"Channel \(ch) frame \(frame) mismatch")
|
|
}
|
|
}
|
|
}
|
|
|
|
@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]
|
|
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: values.count)
|
|
buffer.fill { i, _ in values[i] }
|
|
#expect(buffer.channelCount == 1)
|
|
|
|
let url: URL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString)
|
|
.appendingPathExtension("caf")
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
|
|
try buffer.write(to: url, format: .caf)
|
|
|
|
// load(url:) should still work correctly for mono files.
|
|
let loaded: LyrebirdBuffer = try LyrebirdBuffer.load(url: url)
|
|
#expect(loaded.count == values.count)
|
|
#expect(loaded.channelCount == 1)
|
|
|
|
let tolerance: Double = 1e-6
|
|
for i: Int in 0..<values.count {
|
|
#expect(abs(loaded[i] - values[i]) < tolerance,
|
|
"Mono regression mismatch at \(i)")
|
|
}
|
|
}
|
|
}
|
|
|
|
// MARK: - Channel-count validation
|
|
|
|
/// Build a minimal raw WAV file in memory with a specified channel count.
|
|
///
|
|
/// The resulting bytes form a valid enough WAV header that `ExtAudioFileOpenURL` will
|
|
/// open the file and populate the ASBD from the fmt chunk. With an out-of-range channel
|
|
/// count, our `queryFileProperties` guard fires before any allocation.
|
|
///
|
|
/// Format: IEEE float PCM (fmt tag 0x0003), 32-bit, `sampleRate` Hz, `nChannels` channels,
|
|
/// zero data frames.
|
|
///
|
|
/// - Note: `channelCount` must be ≤ 16383 (`UInt16.max / 4`) to avoid `blockAlign`
|
|
/// overflowing `UInt16`. The tests in this file only use values of 0 and 100.
|
|
private func writeTempRawWAV(channelCount: UInt16, sampleRate: UInt32 = 44100) throws -> URL {
|
|
precondition(channelCount <= 16383, "channelCount overflows UInt16 blockAlign for values > 16383")
|
|
|
|
let url: URL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString)
|
|
.appendingPathExtension("wav")
|
|
|
|
// WAV fmt chunk for IEEE float: 16-byte base + 2-byte cbSize extension field.
|
|
let fmtChunkSize: UInt32 = 18
|
|
// RIFF payload = 4 (WAVE tag) + 8 (fmt chunk header) + fmtChunkSize + 8 (data chunk header).
|
|
let riffPayloadSize: UInt32 = 4 + 8 + fmtChunkSize + 8
|
|
|
|
let waveFormatIEEEFloat: UInt16 = 3 // WAVE_FORMAT_IEEE_FLOAT
|
|
let bitsPerSample: UInt16 = 32
|
|
let bytesPerSample: UInt16 = bitsPerSample / 8
|
|
let blockAlign: UInt16 = channelCount * bytesPerSample
|
|
let byteRate: UInt32 = sampleRate * UInt32(blockAlign)
|
|
let cbSizeZero: UInt16 = 0 // no extension data
|
|
|
|
// Total raw byte count: 4-byte "RIFF" tag + 4-byte length field + riffPayloadSize.
|
|
let rawFileByteCount: Int = 4 + 4 + Int(riffPayloadSize)
|
|
var bytes: [UInt8] = [UInt8]()
|
|
bytes.reserveCapacity(rawFileByteCount)
|
|
|
|
func appendLE32(_ v: UInt32) {
|
|
bytes.append(UInt8(v & 0xFF))
|
|
bytes.append(UInt8((v >> 8) & 0xFF))
|
|
bytes.append(UInt8((v >> 16) & 0xFF))
|
|
bytes.append(UInt8((v >> 24) & 0xFF))
|
|
}
|
|
func appendLE16(_ v: UInt16) {
|
|
bytes.append(UInt8(v & 0xFF))
|
|
bytes.append(UInt8((v >> 8) & 0xFF))
|
|
}
|
|
func appendASCII(_ s: String) { s.utf8.forEach { bytes.append($0) } }
|
|
|
|
appendASCII("RIFF")
|
|
appendLE32(riffPayloadSize)
|
|
appendASCII("WAVE")
|
|
|
|
// fmt chunk
|
|
appendASCII("fmt ")
|
|
appendLE32(fmtChunkSize)
|
|
appendLE16(waveFormatIEEEFloat)
|
|
appendLE16(channelCount)
|
|
appendLE32(sampleRate)
|
|
appendLE32(byteRate)
|
|
appendLE16(blockAlign)
|
|
appendLE16(bitsPerSample)
|
|
appendLE16(cbSizeZero)
|
|
|
|
// data chunk (0 frames)
|
|
appendASCII("data")
|
|
appendLE32(0)
|
|
|
|
assert(bytes.count == rawFileByteCount, "WAV byte count mismatch: expected \(rawFileByteCount), got \(bytes.count)")
|
|
try Data(bytes).write(to: url)
|
|
return url
|
|
}
|
|
|
|
@MainActor
|
|
@Suite("LyrebirdBufferFileIO channel-count validation")
|
|
struct LyrebirdBufferChannelCountValidationTests {
|
|
|
|
// MARK: load
|
|
|
|
@Test("load throws invalidChannelCount for over-limit channel count")
|
|
func loadThrowsInvalidChannelCountOverLimit() throws {
|
|
// lyrebirdMaxFileChannelCount is 8; use 100 to trigger the guard.
|
|
let overLimitChannelCount: UInt16 = 100
|
|
let url: URL = try writeTempRawWAV(channelCount: overLimitChannelCount)
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
|
|
#expect(throws: LyrebirdBufferIOError.invalidChannelCount(Int(overLimitChannelCount))) {
|
|
_ = try LyrebirdBuffer.load(url: url)
|
|
}
|
|
}
|
|
|
|
@Test("load throws some error for zero channel count")
|
|
func loadThrowsForZeroChannelCount() throws {
|
|
// mChannelsPerFrame = 0 is rejected either by our guard (invalidChannelCount(0))
|
|
// or by the OS at open/query time — either way, load must throw.
|
|
let url: URL = try writeTempRawWAV(channelCount: 0)
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
|
|
#expect(throws: (any Error).self) {
|
|
_ = try LyrebirdBuffer.load(url: url)
|
|
}
|
|
}
|
|
|
|
// MARK: fill(fromFile:)
|
|
|
|
@Test("fill(fromFile:) throws invalidChannelCount for over-limit channel count")
|
|
func fillThrowsInvalidChannelCountOverLimit() throws {
|
|
let overLimitChannelCount: UInt16 = 100
|
|
let url: URL = try writeTempRawWAV(channelCount: overLimitChannelCount)
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
|
|
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: 64)
|
|
#expect(throws: LyrebirdBufferIOError.invalidChannelCount(Int(overLimitChannelCount))) {
|
|
try buffer.fill(fromFile: url)
|
|
}
|
|
}
|
|
|
|
@Test("fill(fromFile:) throws some error for zero channel count")
|
|
func fillThrowsForZeroChannelCount() throws {
|
|
let url: URL = try writeTempRawWAV(channelCount: 0)
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
|
|
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: 64)
|
|
#expect(throws: (any Error).self) {
|
|
try buffer.fill(fromFile: url)
|
|
}
|
|
}
|
|
|
|
// MARK: loadAllChannels
|
|
|
|
@Test("loadAllChannels throws invalidChannelCount for over-limit channel count")
|
|
func loadAllChannelsThrowsInvalidChannelCountOverLimit() throws {
|
|
let overLimitChannelCount: UInt16 = 100
|
|
let url: URL = try writeTempRawWAV(channelCount: overLimitChannelCount)
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
|
|
#expect(throws: LyrebirdBufferIOError.invalidChannelCount(Int(overLimitChannelCount))) {
|
|
_ = try LyrebirdBuffer.loadAllChannels(url: url)
|
|
}
|
|
}
|
|
|
|
@Test("loadAllChannels throws some error for zero channel count")
|
|
func loadAllChannelsThrowsForZeroChannelCount() throws {
|
|
let url: URL = try writeTempRawWAV(channelCount: 0)
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
|
|
#expect(throws: (any Error).self) {
|
|
_ = try LyrebirdBuffer.loadAllChannels(url: url)
|
|
}
|
|
}
|
|
|
|
// MARK: regression: valid 8-channel file still loads
|
|
|
|
@Test("load succeeds for exactly lyrebirdMaxFileChannelCount channels")
|
|
func loadSucceedsAtMaxChannelCount() throws {
|
|
// Use lyrebirdMaxFileChannelCount directly so the test tracks the constant.
|
|
let maxChannels: Int = lyrebirdMaxFileChannelCount
|
|
// Small even frame count; not boundary-significant.
|
|
let frameCount: Int = 4
|
|
let channels: [[Float]] = (0..<maxChannels).map { ch in
|
|
(0..<frameCount).map { frame in Float(ch) * 0.1 + Float(frame) * 0.01 }
|
|
}
|
|
let url: URL = try writeTempMultichannelWAV(channels: channels)
|
|
defer { try? FileManager.default.removeItem(at: url) }
|
|
|
|
let buffer: LyrebirdBuffer = try LyrebirdBuffer.loadAllChannels(url: url)
|
|
#expect(buffer.channelCount == maxChannels)
|
|
#expect(buffer.count == frameCount)
|
|
}
|
|
}
|