8eb64f883f
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
178 lines
8.0 KiB
Swift
178 lines
8.0 KiB
Swift
// 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))
|
|
}
|
|
}
|