Repository Public
1// ORIX Sonata2// File: Packages/SonataBridge/Tests/SonataBridgeTests/PipelineTests.swift3// Description: The whole chain through the C ABI: compile, timeline, overrides and conflicts,4// engine load and playback (offline clock), hot swap, render to a file and reading it back,5// and (opt-in) the real output device with the monitor muted.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import Testing11@testable import SonataBridge1213let piece = """14import std.music15import std.instruments16import std.effects1718composition "Pipeline" {19 tempo 120bpm20 signature 4/421 instrument piano: GrandPiano {22 gain -6dB23 play A4 duration 1/224 chord [C4, E4, G4] duration 1/225 }26 instrument lead: SynthLead {27 gain -12dB28 play A3 duration 1/129 }30}3132"""3334func rmsDb(_ x: [Float]) -> Double {35 guard !x.isEmpty else { return -200 }36 let ms = x.reduce(0.0) { $0 + Double($1) * Double($1) } / Double(x.count)37 return ms > 0 ? 10 * log10(ms) : -20038}3940@Test func compileGivesDiagnosticsAndTimeline() async throws {41 let session = SonataCompilerSession()42 let ok = try await session.compile(name: "main.sonata", source: piece)43 #expect(ok.ok, "\(ok.diagnostics.map(\.message))")44 let t = try #require(ok.timeline)45 #expect(t.title == "Pipeline")46 #expect(t.tracks.map(\.name) == ["piano", "lead"])47 #expect(t.tracks[0].notes.count == 4)48 #expect(abs(t.durationSec - 2.0) < 1e-9)49 #expect(t.bars.first?.beatSec == [0, 0.5, 1, 1.5])50 #expect(t.bars.first?.beat == Ratio(num: 1, den: 4))51 #expect(ok.stats.events == 5 && ok.stats.nodes > 0 && ok.stats.totalUs > 0)52 // Each note knows the statement it came from.53 let first = t.tracks[0].notes[0]54 let utf8 = Array(piece.utf8)55 #expect(String(decoding: utf8[first.spanStart..<first.spanEnd], as: UTF8.self).contains("A4"))5657 // An error: reported with its position; the previous valid program is kept.58 let broken = piece.replacingOccurrences(of: "GrandPiano", with: "GrandPiana")59 let bad = try await session.compile(name: "main.sonata", source: broken)60 #expect(!bad.ok)61 let d = try #require(bad.errors.first)62 #expect(d.line == 8 && d.file == "main.sonata")63 #expect(d.suggestion?.contains("GrandPiano") == true || d.fix?.replacement.contains("GrandPiano") == true || d.message.contains("GrandPiano"))64 #expect(await session.hasProgram)65 #expect(SonataLibrary.highlight(piece).contains { $0.kind == .note })66 #expect(try SonataLibrary.format(piece).ok)67}6869@Test func overridesAreAppliedAndConflictsReported() async throws {70 let session = SonataCompilerSession()71 let overrides = #"{"strips":[{"strip":"piano","gain_db":-20,"mute":true},{"strip":"ghost","pan":1}],"notes":[{"track":"piano","index":0,"original_start":{"num":0,"den":1},"original_pitch":69,"pitch":72},{"track":"piano","index":0,"original_start":{"num":1,"den":4},"original_pitch":69,"pitch":10}],"added":[{"track":"lead","start":{"num":1,"den":1},"duration":{"num":1,"den":4},"pitch":60,"velocity":0.5}]}"#72 let r = try await session.compile(name: "main.sonata", source: piece, options: .init(overridesJSON: overrides))73 #expect(r.ok)74 let t = try #require(r.timeline)75 #expect(t.tracks[0].gainDb == -20 && t.tracks[0].mute)76 #expect(t.tracks[0].notes.first { $0.index == 0 }?.pitch == 72)77 #expect(r.conflicts.count == 2, "\(r.conflicts)")78 #expect(r.conflicts.contains { $0.kind == "strip" && $0.reason.contains("ghost") })79 #expect(r.conflicts.contains { $0.kind == "note" && $0.reason.contains("changed in the code") })80 let added = try #require(t.tracks[1].notes.first { $0.added })81 #expect(added.pitch == 60 && abs(added.startSec - 2.0) < 1e-9)82 #expect(abs(t.durationSec - 2.5) < 1e-9)83}8485@Test func enginePlaysTheProgramAndHotSwaps() async throws {86 let session = SonataCompilerSession()87 #expect(try await session.compile(name: "main.sonata", source: piece).ok)88 let engine = SonataEngineHandle(sampleRate: 48_000, maxBlockFrames: 256)89 let load = try await session.load(into: engine)90 #expect((load.nodes ?? 0) > 0)91 engine.play()92 let (l, r) = engine.renderOffline(frames: 48_000)93 // The program is installed by the audio thread at its first block after the load.94 #expect(abs(engine.duration - 2.0) < 1e-3, "duration \(engine.duration)")95 #expect(engine.state == .playing)96 #expect(abs(engine.position - 1.0) < 0.01, "position follows the audio clock: \(engine.position)")97 #expect(rmsDb(l) > -60 && rmsDb(r) > -60, "audible: \(rmsDb(l)) dBFS RMS")98 #expect(l.allSatisfy { $0.isFinite && abs($0) <= 1 })99 let meters = engine.meters()100 #expect(meters.count == 3)101 #expect(meters.first { $0.strip == .master }!.peakLeft > 0.001)102103 // The piano plays A4 during the first second: the measured fundamental of its track is 440 Hz.104 engine.stop()105 _ = engine.renderOffline(frames: 96_000) // let the tails die106 engine.setTap(StripID(.track, 0))107 engine.setSolo(StripID(.track, 0), true)108 engine.play()109 _ = engine.renderOffline(frames: 36_000)110 var tl = [Float](repeating: 0, count: 16_384), tr = tl111 #expect(engine.readTap(left: &tl, right: &tr, frames: 16_384) == 16_384)112 let m = try #require(SonataAnalysis.measure(tl, sampleRate: 48_000))113 let f = try #require(m.fundamentalHz)114 #expect(abs(1200 * log2(f / 440)) < 5, "piano A4 measured at \(f) Hz")115 engine.setSolo(StripID(.track, 0), false)116117 // Hot swap while playing: new program, same position, no discontinuity beyond normal audio.118 let transposed = piece.replacingOccurrences(of: "play A3 duration 1/1", with: "play E3 duration 1/1")119 #expect(try await session.compile(name: "main.sonata", source: transposed).ok)120 let before = engine.position121 _ = try await session.load(into: engine)122 let (sl, _) = engine.renderOffline(frames: 9_600)123 #expect(abs(engine.position - before - 0.2) < 0.01, "the transport did not jump: \(before) -> \(engine.position)")124 let jump = zip(sl, sl.dropFirst()).map { abs($1 - $0) }.max() ?? 0125 #expect(jump < 0.5, "no click at the swap: largest step \(jump)")126 #expect(engine.statistics().scrubbedSamples == 0)127128 // Seek and loop.129 engine.setLoop(enabled: true, start: 0.5, end: 1.0)130 engine.seek(seconds: 0.9)131 _ = engine.renderOffline(frames: 24_000)132 #expect(engine.position >= 0.5 && engine.position < 1.0, "inside the cycle: \(engine.position)")133}134135@Test func renderWritesAFileThatReadsBackWithItsLevels() async throws {136 let dir = FileManager.default.temporaryDirectory.appendingPathComponent("sonata-bridge-" + UUID().uuidString)137 try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)138 defer { try? FileManager.default.removeItem(at: dir) }139 let session = SonataCompilerSession()140 #expect(try await session.compile(name: "main.sonata", source: piece).ok)141 var options = RenderOptions(path: dir.appendingPathComponent("out.flac").path)142 options.format = "flac"143 options.bitDepth = 24144 options.stems = true145 let progress = ProgressRecorder()146 let result = try await session.render(options) { progress.record($0) }147 #expect(result.ok && result.files.count == 3, "\(result.error ?? "") \(result.files.map(\.path))")148 #expect(progress.values.last == 1 && progress.values == progress.values.sorted())149 let master = try #require(result.files.first)150 #expect(master.sampleRate == 48_000 && master.channels == 2 && master.frames >= 96_000)151 #expect(master.peakDb < -0.9, "the master limiter holds -1 dBFS: \(master.peakDb)")152 #expect(master.lufs > -60 && master.lufs < -5)153154 let audio = try DecodedAudio(url: URL(fileURLWithPath: master.path))155 #expect(audio.frames == master.frames && audio.channels == 2 && audio.sampleRate == 48_000)156 let o = audio.overview(channel: 0, startFrame: 0, framesPerBucket: Double(audio.frames) / 200, buckets: 200)157 #expect(o.max.count == 200)158 let peak = max(o.max.max() ?? 0, -(o.min.min() ?? 0))159 #expect(abs(20 * log10(Double(peak)) - master.peakDb) < 0.01, "the overview shows the file's real peak")160 // Exact at sample zoom: one bucket per frame equals the samples.161 let s = audio.samples(channel: 0, start: 4_800, count: 64)162 let fine = audio.overview(channel: 0, startFrame: 4_800, framesPerBucket: 1, buckets: 64)163 #expect(fine.max == s && fine.min == s)164165 // Refuses to replace without being told; cancellation leaves no file.166 options.overwrite = false167 let again = try await session.render(options)168 #expect(!again.ok && (again.error ?? "").contains("exists"))169 var other = RenderOptions(path: dir.appendingPathComponent("cancelled.wav").path)170 other.overwrite = true171 let cancel = RenderCancellation()172 cancel.cancel()173 let cancelled = try await session.render(other, cancellation: cancel)174 #expect(cancelled.cancelled && !FileManager.default.fileExists(atPath: other.path))175176 // MusicXML and MIDI exports.177 let mid = dir.appendingPathComponent("p.mid")178 #expect(try await session.exportFile(format: "midi", to: mid, overwrite: false).ok)179 #expect(try Data(contentsOf: mid).prefix(4) == Data("MThd".utf8))180 #expect(try SonataLibrary.importMIDI(path: mid.path).contains("composition"))181 #expect(try await session.exportFile(format: "midi", to: mid, overwrite: false).ok == false)182}183184final class ProgressRecorder: @unchecked Sendable {185 private let lock = NSLock()186 private var stored: [Double] = []187 func record(_ v: Double) {188 lock.lock()189 stored.append(v)190 lock.unlock()191 }192 var values: [Double] {193 lock.lock()194 defer { lock.unlock() }195 return stored196 }197}198199/// Opens the real default output device and runs the engine through AVAudioEngine for two200/// seconds with the monitor fully muted (digital silence reaches the device). Opt-in:201/// `SONATA_DEVICE_TEST=1 swift test`.202@Test(.enabled(if: ProcessInfo.processInfo.environment["SONATA_DEVICE_TEST"] == "1"))203func realDeviceCallbackRunsMuted() async throws {204 let session = SonataCompilerSession()205 #expect(try await session.compile(name: "main.sonata", source: piece).ok)206 let host = AudioHost(preferredSampleRate: 48_000)207 host.engine.setMonitorGain(db: -120)208 host.start()209 guard case .running(let rate, _) = host.state else {210 Issue.record("the output device did not start: \(host.state)")211 return212 }213 host.engine.setMonitorGain(db: -120) // the engine may have been replaced at the device rate214 _ = try await session.load(into: host.engine)215 host.engine.resetStatistics()216 host.engine.play()217 try await Task.sleep(for: .seconds(2))218 let stats = host.engine.statistics()219 let position = host.engine.position220 host.engine.stop()221 host.stop()222 print("DEVICE rate=\(rate) callbacks=\(stats.callbacks) mean=\(stats.meanMicros)us p99=\(stats.p99Micros)us max=\(stats.maxMicros)us overruns=\(stats.overruns) voices=\(stats.peakVoices) position=\(position)")223 #expect(stats.callbacks > 50)224 #expect(position > 1.5 && position <= 2.01 + 0.2, "the transport follows the device clock: \(position)")225 #expect(stats.overruns == 0)226}227228@Test func editorQueriesAnswerFromTheCompiler() async throws {229 let session = SonataCompilerSession()230 #expect(try await session.compile(name: "main.sonata", source: piece).ok)231 // Completion after "instrument x: Gra" proposes GrandPiano and replaces the typed prefix.232 let partial = piece.replacingOccurrences(of: "instrument piano: GrandPiano {", with: "instrument piano: Gra")233 let offset = partial.utf8.count - (partial.utf8.count - (partial.range(of: "piano: Gra").map { partial.utf8.distance(from: partial.startIndex, to: $0.upperBound) } ?? 0))234 let items = await session.completions(source: partial, offset: offset)235 let grand = try #require(items.first { $0.label == "GrandPiano" }, "\(items.prefix(8).map(\.label))")236 #expect(grand.replaceEnd - grand.replaceStart == 3)237238 let at = piece.utf8.distance(from: piece.startIndex, to: piece.range(of: "GrandPiano")!.lowerBound) + 2239 let hover = try #require(await session.hover(source: piece, offset: at))240 #expect(hover.markdown.localizedCaseInsensitiveContains("piano"))241 let definition = try #require(await session.definition(source: piece, offset: at))242 #expect(definition.file == "std.instruments")243 let symbols = await session.symbols(source: piece)244 #expect(symbols.contains { $0.name == "Pipeline" || $0.children.contains { $0.name == "piano" } }, "\(symbols.map(\.name))")245 let classes = Set(SonataLibrary.highlight(piece).map(\.kind))246 #expect(classes.isSuperset(of: [.keyword, .note, .number, .unit, .string]))247}248