// 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.size), &fmt) var mutableSamples: [Float] = samples let sampleByteSize: UInt32 = UInt32(samples.count * MemoryLayout.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.size), &fmt) // Interleave left and right samples. var interleaved: [Float] = [Float](repeating: 0, count: left.count * 2) for i: Int in 0...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.size), &fmt) // Interleave all channels. var interleaved: [Float] = [Float](repeating: 0, count: frameCount * channels.count) for frame: Int in 0...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 } // MARK: - load(url:channel:normalise:) @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.. 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:) @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.. 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 } @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..