Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Tests/CoreTests/AudioTests.swift3// Description: Tests: real decoding of every announced format; engine transport, gain and gapless transitions.4import XCTest5import AVFoundation6@testable import SPMusicCore78final class AudioDecodingTests: XCTestCase {9 /// Every format the app announces is opened and decoded for real by Core Audio on this Mac, through the same10 /// callback-based reader that streaming uses.11 func testEveryAnnouncedFormatDecodesToTheRightSignal() throws {12 for f in Fixtures.formats {13 let url = try Fixtures.sine(f.name, hz: 440, seconds: 2, codecArgs: f.args)14 let dec = try AudioDecoder(source: try LocalFileSource(url: url), typeHint: AudioDecoder.typeHint(pathExtension: url.pathExtension))15 XCTAssertEqual(dec.info.sampleRate, 44100, f.name); XCTAssertEqual(dec.info.channels, 2, f.name)16 XCTAssertEqual(dec.info.duration, 2.0, accuracy: f.lossless ? 0.001 : 0.08, f.name)17 let buf = AVAudioPCMBuffer(pcmFormat: dec.processingFormat, frameCapacity: 44100)!18 XCTAssertEqual(try dec.read(into: buf), 44100, f.name)19 let x = Signal.samples(buf)[8000..<40000]20 XCTAssertEqual(Signal.frequency(x, rate: 44100), 440, accuracy: 3, f.name)21 XCTAssertGreaterThan(Signal.rms(x), 0.05, f.name)22 // Seeking lands on the requested frame.23 try dec.seek(toFrame: 44100 + 22050)24 var total: AVAudioFrameCount = 025 while true { let n = try dec.read(into: buf); if n == 0 { break }; total += n }26 XCTAssertEqual(Double(total), 22050, accuracy: f.lossless ? 2 : 4000, f.name)27 }28 }2930 func testLosslessBitDepthIsReportedFromTheFile() throws {31 let d16 = try AudioDecoder(source: LocalFileSource(url: Fixtures.sine("flac16.flac", hz: 440, seconds: 2, codecArgs: Fixtures.formats[0].args)))32 let d24 = try AudioDecoder(source: LocalFileSource(url: Fixtures.sine("flac24.flac", hz: 440, seconds: 2, codecArgs: Fixtures.formats[1].args)))33 XCTAssertEqual(d16.info.bitDepth, 16); XCTAssertEqual(d24.info.bitDepth, 24)34 let mp3 = try AudioDecoder(source: LocalFileSource(url: Fixtures.sine("mp3.mp3", hz: 440, seconds: 2, codecArgs: Fixtures.formats[5].args)))35 XCTAssertNil(mp3.info.bitDepth)36 }3738 func testAFileThatIsNotAudioIsRefused() throws {39 let url = Fixtures.dir.appendingPathComponent("fake.flac")40 try Data("this is not audio at all, just text pretending".utf8).write(to: url)41 XCTAssertThrowsError(try AudioDecoder(source: LocalFileSource(url: url), typeHint: AudioDecoder.typeHint(pathExtension: "flac")))42 }43}4445final class AudioEngineTests: XCTestCase {46 let rate = 44100.047 func makeEngine() -> AudioEngine { AudioEngine(offlineFormat: AVAudioFormat(standardFormatWithSampleRate: rate, channels: 2)!) }4849 /// Renders `seconds` of audio, letting the decoding queues keep up between blocks (offline rendering is faster than real time).50 func render(_ engine: AudioEngine, seconds: Double) -> [Float] { OfflinePlayer.render(engine, seconds: seconds, patience: 2) }51 func waitReady(_ engine: AudioEngine) { let d = Date().addingTimeInterval(5); while !engine.isFed(), Date() < d { usleep(2000) } }5253 func testPlaysPausesAndSeeks() throws {54 let url = try Fixtures.sine("sine440-6s.flac", hz: 440, seconds: 6, codecArgs: ["-c:a", "flac"])55 let engine = makeEngine()56 let token = UUID()57 engine.load(token: token, source: try LocalFileSource(url: url), typeHint: 0, autoplay: true)58 waitReady(engine)59 let a = render(engine, seconds: 1)60 XCTAssertEqual(Signal.frequency(a[4410...], rate: rate), 440, accuracy: 3)61 XCTAssertEqual(engine.status().position, 1.0, accuracy: 0.1)62 XCTAssertEqual(engine.status().duration, 6.0, accuracy: 0.01)6364 engine.pause()65 let silent = render(engine, seconds: 0.5)66 XCTAssertLessThan(Signal.rms(silent[2048...]), 0.001, "paused: nothing sounds")67 XCTAssertEqual(engine.status().position, 1.0, accuracy: 0.15, "paused: the position holds")6869 engine.seek(to: 4)70 engine.play(); waitReady(engine)71 _ = render(engine, seconds: 0.5)72 XCTAssertEqual(engine.status().position, 4.5, accuracy: 0.15)73 }7475 func testVolumeAndDirectModeGain() throws {76 let url = try Fixtures.sine("sine440-6s.flac", hz: 440, seconds: 6, codecArgs: ["-c:a", "flac"])77 let engine = makeEngine()78 engine.load(token: UUID(), source: try LocalFileSource(url: url), typeHint: 0, gainDB: -6, autoplay: true)79 waitReady(engine)80 let normal = Signal.rms(render(engine, seconds: 0.6)[8000...])81 var s = EngineSettings(); s.volume = 0.5; engine.apply(s)82 let half = Signal.rms(render(engine, seconds: 0.6)[8000...])83 XCTAssertEqual(half / normal, 0.5, accuracy: 0.05)84 // Direct mode ignores the normalisation gain: samples are not scaled before the mixer.85 var d = EngineSettings(); d.directMode = true; engine.apply(d)86 engine.load(token: UUID(), source: try LocalFileSource(url: url), typeHint: 0, gainDB: -6, autoplay: true)87 waitReady(engine)88 let direct = Signal.rms(render(engine, seconds: 0.6)[8000...])89 XCTAssertEqual(normal / direct, pow(10, -6.0 / 20), accuracy: 0.03)90 }9192 /// Two tracks in a row: the second starts on the sample where the first ends. No silence, no overlap.93 func testGaplessTransitionHasNoGap() async throws {94 let a = try Fixtures.sine("gap-a.flac", hz: 440, seconds: 2, codecArgs: ["-c:a", "flac"])95 let b = try Fixtures.sine("gap-b.flac", hz: 880, seconds: 2, codecArgs: ["-c:a", "flac"])96 let engine = makeEngine()97 let ta = UUID(), tb = UUID()98 let events = engine.events()99 engine.load(token: ta, source: try LocalFileSource(url: a), typeHint: 0, autoplay: true)100 engine.prepareNext(token: tb, source: try LocalFileSource(url: b), typeHint: 0)101 waitReady(engine)102 let x = render(engine, seconds: 4.4)103 // 5 ms windows across the whole programme: the level never collapses before the real end.104 let win = 220105 var firstQuiet: Int?106 for i in stride(from: 4410, to: x.count - win, by: win) where Signal.rms(x[i..<(i + win)]) < 0.02 { firstQuiet = i; break }107 let end = Double(firstQuiet ?? x.count) / rate108 XCTAssertEqual(end, 4.0, accuracy: 0.02, "audio is continuous for the 4 seconds of the two tracks")109 XCTAssertEqual(Signal.frequency(x[30000..<80000], rate: rate), 440, accuracy: 4)110 XCTAssertEqual(Signal.frequency(x[100000..<160000], rate: rate), 880, accuracy: 6)111 XCTAssertEqual(engine.status().token, tb)112 let collector = Task { () -> (Bool, Bool) in113 var sawAdvance = false, sawFinish = false114 for await e in events {115 if case .advanced(let t) = e, t == tb { sawAdvance = true }116 if case .finished(let t) = e, t == tb { sawFinish = true }117 if sawAdvance && sawFinish { break }118 }119 return (sawAdvance, sawFinish)120 }121 try await Task.sleep(nanoseconds: 400_000_000)122 collector.cancel()123 let (sawAdvance, sawFinish) = await collector.value124 XCTAssertTrue(sawAdvance, "the engine reports that it moved to the prepared track")125 XCTAssertTrue(sawFinish, "and that the last track ended")126 }127128 /// Tracks at different sample rates still follow each other (the mixer converts each deck to the output rate).129 func testTransitionBetweenDifferentSampleRates() throws {130 let a = try Fixtures.sine("rate-a.flac", hz: 440, seconds: 2, rate: 44100, codecArgs: ["-c:a", "flac"])131 let b = try Fixtures.sine("rate-b.flac", hz: 660, seconds: 2, rate: 96000, codecArgs: ["-c:a", "flac"])132 let engine = makeEngine()133 engine.load(token: UUID(), source: try LocalFileSource(url: a), typeHint: 0, autoplay: true)134 engine.prepareNext(token: UUID(), source: try LocalFileSource(url: b), typeHint: 0)135 waitReady(engine)136 let x = render(engine, seconds: 4.2)137 XCTAssertEqual(Signal.frequency(x[100000..<160000], rate: rate), 660, accuracy: 6)138 var gap = 0139 for i in stride(from: 4410, to: Int(3.9 * rate), by: 220) where Signal.rms(x[i..<(i + 220)]) < 0.02 { gap += 1 }140 XCTAssertLessThanOrEqual(gap, 4, "at most a few milliseconds of resampler settling at the junction")141 }142}143