Repository Public
1// ORIX Sonata2// File: Packages/SonataBridge/Tests/SonataBridgeTests/BridgeTests.swift3// Description: End-to-end checks through the C ABI: versions, registry, calibrated analysis,4// engine lifecycle without a device.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import Testing10@testable import SonataBridge1112func sine(_ hz: Double, amplitude: Double, count: Int, rate: Double = 48_000) -> [Float] {13 (0..<count).map { Float(amplitude * sin(2 * .pi * hz * Double($0) / rate)) }14}1516@Test func abiAndVersion() throws {17 try SonataLibrary.checkABI()18 let v = try SonataLibrary.version()19 #expect(v.languageVersion == "0.1")20 #expect(v.irVersion >= 1)21}2223@Test func spectrumIsCalibratedInDbfs() throws {24 // A sine exactly on a bin: every window must read its amplitude at that bin.25 let n = 409626 let bin = 12827 let hz = Double(bin) * 48_000 / Double(n)28 for window in FFTWindow.allCases {29 let db = try #require(SonataAnalysis.spectrum(sine(hz, amplitude: 0.5, count: n), window: window))30 #expect(db.count == n / 2 + 1)31 #expect(abs(Double(db[bin]) - (-6.0206)) < 0.05, "\(window.title): \(db[bin]) dBFS")32 #expect(db.firstIndex(of: db.max()!) == bin)33 }34 #expect(SonataAnalysis.spectrum([Float](repeating: 0, count: 1000), window: .hann) == nil)35}3637@Test func measurementFindsTheFundamental() throws {38 let x = sine(440, amplitude: 0.25, count: 48_000)39 let m = try #require(SonataAnalysis.measure(x, sampleRate: 48_000))40 let f = try #require(m.fundamentalHz)41 #expect(abs(f - 440) < 0.5)42 #expect(abs(m.peakDb - (-12.04)) < 0.05)43 #expect(abs(m.rmsDb - (-15.05)) < 0.05)44 #expect((m.thdPercent ?? 100) < 0.01)45}4647@Test func loudnessOfTheReferenceTone() throws {48 // EBU Tech 3341 case 1: 1 kHz stereo sine at -23 dBFS reads -23.0 LUFS (+-0.1).49 let amplitude = pow(10, -23.0 / 20)50 let x = sine(1000, amplitude: amplitude, count: 48_000 * 20)51 let l = try #require(SonataAnalysis.loudness(left: x, right: x, sampleRate: 48_000))52 #expect(abs(l.integrated - (-23.0)) < 0.1, "\(l.integrated) LUFS")53 #expect(abs(l.samplePeakDb - (-23.0)) < 0.05)54 #expect(abs(l.truePeakDb - (-23.0)) < 0.2)55 let s = try #require(SonataAnalysis.measureStereo(left: x, right: x))56 #expect(s.correlation > 0.999)57 #expect(abs(s.balance) < 1e-3)58}5960@Test func engineWithoutProgramIsSilentAndSafe() throws {61 let engine = SonataEngineHandle(sampleRate: 48_000, maxBlockFrames: 512)62 engine.play()63 let (l, r) = engine.renderOffline(frames: 4800)64 #expect(l.allSatisfy { $0 == 0 } && r.allSatisfy { $0 == 0 })65 #expect(engine.duration == 0)66 #expect(engine.meters().last?.strip == .master)67 let stats = engine.statistics()68 #expect(stats.callbacks > 0)69 #expect(stats.scrubbedSamples == 0)70 // Transport commands are applied by the audio thread at its next block.71 engine.stop()72 _ = engine.renderOffline(frames: 512)73 #expect(engine.state == .stopped)74}75