bugfixes, better MusicXML support and 1.1.0

This commit is contained in:
2026-06-10 08:41:07 -07:00
parent 6d3a0930a1
commit f59fd3b55a
228 changed files with 32271 additions and 2586 deletions
@@ -0,0 +1,128 @@
// ProjectScaffolderBuildTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable import LyrebirdCLI
/// Slow integration suite: scaffolds each non-Xcode SPM template into a temp
/// directory, wires it to *this* Lyrebird checkout via `--lyrebird-path`, and
/// runs a real `swift build`, asserting exit 0.
///
/// The plain `ProjectScaffolderTests` suite only checks generated source via
/// *string substring* matches — it never compiles the templates against the
/// live Lyrebird API. That gap let several templates drift out of sync with the
/// API they pin: the `score` template's `Part(clef:)` / `event.performedDuration`
/// usage built against current `main` but not against the older published tag
/// the generated project resolved; `basic`/`demo` emitted an unbound `\(name)`;
/// `ui-demo`'s `AppDelegate.init` predated `SynthesizerBase`'s `@MainActor`.
/// This suite closes the gap by actually building the emitted sources against
/// *this* checkout — the same source the scaffolder now pins by default.
///
/// **Gated** behind the `LYREBIRD_RUN_BUILD_TESTS` env var because each case
/// does a full SPM dependency resolution (network) + a from-scratch compile of
/// the Lyrebird package — minutes per template, not milliseconds. Off by
/// default so the normal `swift test` run stays fast and offline.
///
/// Run with:
/// ```
/// LYREBIRD_RUN_BUILD_TESTS=1 swift test --no-parallel --filter ProjectScaffolderBuild
/// ```
@Suite(
"ProjectScaffolderBuild",
.enabled(if: ProcessInfo.processInfo.environment["LYREBIRD_RUN_BUILD_TESTS"] != nil,
"set LYREBIRD_RUN_BUILD_TESTS=1 to run the slow scaffold-and-build integration suite"),
// Swift Testing runs parametrized cases in parallel by default (the
// `swift test --no-parallel` flag only governs the XCTest path). Five
// concurrent `swift build` processes saturate the machine and contend, so
// serialize: each template builds one at a time.
.serialized
)
struct ProjectScaffolderBuildTests {
/// Absolute path to the root of this Lyrebird checkout — the directory
/// holding the top-level `Package.swift`. Derived from this source file's
/// location: `<root>/Tests/LyrebirdCLITests/ProjectScaffolderBuildTests.swift`.
static var lyrebirdCheckoutRoot: String {
URL(fileURLWithPath: #filePath)
.deletingLastPathComponent() // LyrebirdCLITests/
.deletingLastPathComponent() // Tests/
.deletingLastPathComponent() // <root>/
.path
}
/// Every SPM template that emits a `Package.swift` + `main.swift`, keyed by
/// its canonical raw value. The xcode-bearing templates
/// (macos-ui-xcode/ios-ui/auv3) are excluded — they require `xcodebuild`,
/// code signing, and an app/extension host, not a plain `swift build`.
///
/// Raw strings (not `ProjectTemplate` cases) are the parametrized arguments
/// because `@Test(arguments:)` requires `Sendable` and the public
/// `ProjectTemplate` enum does not declare the conformance.
static let spmTemplateRawValues: [String] = ["basic", "demo", "nrt", "score", "ui-demo"]
@Test(arguments: spmTemplateRawValues)
func templateBuildsAgainstLiveLyrebird(_ rawValue: String) throws {
let template: ProjectTemplate = try #require(
ProjectTemplate(string: rawValue),
"unknown template raw value \(rawValue)"
)
#expect(template.shipsXcodeProject == false,
"this suite only covers SPM templates; \(template.rawValue) ships an .xcodeproj")
let fm: FileManager = FileManager.default
let tmp: String = fm.temporaryDirectory
.appendingPathComponent("LyrebirdBuildTest_\(template.rawValue)_\(UUID().uuidString)")
.path
try fm.createDirectory(atPath: tmp,
withIntermediateDirectories: true,
attributes: nil)
defer { try? fm.removeItem(atPath: tmp) }
// Wire the generated Package.swift to THIS checkout so the build
// compiles against the current API rather than the published tag.
let projectName: String = "BuildProbe"
try ProjectScaffolder.scaffold(
name: projectName,
template: template,
in: tmp,
lyrebirdPath: Self.lyrebirdCheckoutRoot
)
let projectRoot: String = (tmp as NSString).appendingPathComponent(projectName)
let result: (exitCode: Int32, output: String) = try Self.runSwiftBuild(in: projectRoot)
#expect(result.exitCode == 0,
"""
`swift build` failed for template \(template.rawValue) (exit \(result.exitCode)):
\(result.output)
""")
}
// MARK: - swift build runner
/// Run `swift build` in `directory`, capturing merged stdout+stderr.
private static func runSwiftBuild(in directory: String) throws -> (exitCode: Int32, output: String) {
let process: Process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
process.arguments = ["swift", "build"]
process.currentDirectoryURL = URL(fileURLWithPath: directory)
let pipe: Pipe = Pipe()
process.standardOutput = pipe
process.standardError = pipe
try process.run()
// Drain the pipe before waitUntilExit to avoid a deadlock when the
// child fills the 64 KB pipe buffer (a full compile is verbose).
let data: Data = pipe.fileHandleForReading.readDataToEndOfFile()
process.waitUntilExit()
let output: String = String(data: data, encoding: .utf8) ?? ""
return (process.terminationStatus, output)
}
}
@@ -140,7 +140,10 @@ struct ProjectScaffolderTests {
@Test func workspaceContentsReferencesPackage() {
let contents: String = ProjectScaffolder.workspaceContents()
#expect(contents.contains("group:Package.swift"))
// Must ref the package *directory* (`group:.`), not the Package.swift
// file — the file form loads a loose document with no schemes.
#expect(contents.contains("group:."))
#expect(!contents.contains("group:Package.swift"))
#expect(contents.contains("<Workspace"))
#expect(contents.hasPrefix("<?xml"))
}
@@ -170,8 +173,8 @@ struct ProjectScaffolderTests {
#expect(contents.contains("group:WS.xcodeproj"),
"xcode workspace must ref .xcodeproj for \(template.rawValue)")
} else {
#expect(contents.contains("group:Package.swift"),
"spm workspace must ref Package.swift for \(template.rawValue)")
#expect(contents.contains("group:."),
"spm workspace must ref the package dir for \(template.rawValue)")
}
}
}
@@ -223,6 +226,9 @@ struct ProjectScaffolderTests {
#expect(ProjectTemplate(string: "ui-demo") == .uiDemo)
#expect(ProjectTemplate(string: "uidemo") == .uiDemo)
#expect(ProjectTemplate(string: "nrt") == .nrt)
#expect(ProjectTemplate(string: "score") == .score)
#expect(ProjectTemplate(string: "score-musicxml") == .score)
#expect(ProjectTemplate(string: "SCORE") == .score)
#expect(ProjectTemplate(string: "DEMO") == .demo)
#expect(ProjectTemplate(string: "bogus") == nil)
#expect(ProjectTemplate(string: "macos-ui-xcode") == .macosUIXcode)
@@ -238,6 +244,7 @@ struct ProjectScaffolderTests {
#expect(ProjectTemplate.demo.shipsXcodeProject == false)
#expect(ProjectTemplate.uiDemo.shipsXcodeProject == false)
#expect(ProjectTemplate.nrt.shipsXcodeProject == false)
#expect(ProjectTemplate.score.shipsXcodeProject == false)
#expect(ProjectTemplate.macosUIXcode.shipsXcodeProject == true)
#expect(ProjectTemplate.iosUI.shipsXcodeProject == true)
#expect(ProjectTemplate.auv3.shipsXcodeProject == true)
@@ -433,6 +440,60 @@ struct ProjectScaffolderTests {
#expect(!manifest.contains(".package(name:"))
}
// MARK: - defaultLyrebirdCheckoutPath resolution
@Test func defaultCheckoutPathNonNilFromSourceTree() throws {
// These tests run from inside the Lyrebird source checkout, so the
// computed property must resolve to a real root holding Package.swift.
let resolved: String = try #require(ProjectScaffolder.defaultLyrebirdCheckoutPath)
let manifest: String = (resolved as NSString).appendingPathComponent("Package.swift")
#expect(FileManager.default.fileExists(atPath: manifest))
}
@Test func checkoutRootResolvesParentThreeLevelsUp() {
let tmp: String = FileManager.default.temporaryDirectory
.appendingPathComponent("LyrebirdCheckoutRoot_\(UUID().uuidString)")
.path
try? FileManager.default.createDirectory(atPath: tmp,
withIntermediateDirectories: true,
attributes: nil)
defer { try? FileManager.default.removeItem(atPath: tmp) }
let manifest: String = (tmp as NSString).appendingPathComponent("Package.swift")
try? "// swift-tools-version: 6.0\n// Lyrebird".write(toFile: manifest,
atomically: true, encoding: .utf8)
// Synthetic source path: <tmp>/Sources/LyrebirdCLI/X.swift → up 3 == <tmp>.
let synthetic: String = (tmp as NSString)
.appendingPathComponent("Sources/LyrebirdCLI/X.swift")
#expect(ProjectScaffolder.lyrebirdCheckoutRoot(forSourceFile: synthetic) == tmp)
}
@Test func checkoutRootNilWhenNoManifest() {
let tmp: String = FileManager.default.temporaryDirectory
.appendingPathComponent("LyrebirdCheckoutNil_\(UUID().uuidString)")
.path
try? FileManager.default.createDirectory(atPath: tmp,
withIntermediateDirectories: true,
attributes: nil)
defer { try? FileManager.default.removeItem(atPath: tmp) }
let synthetic: String = (tmp as NSString).appendingPathComponent("a/b/c.swift")
#expect(ProjectScaffolder.lyrebirdCheckoutRoot(forSourceFile: synthetic) == nil)
}
@Test func checkoutRootNilWhenManifestNotLyrebird() {
let tmp: String = FileManager.default.temporaryDirectory
.appendingPathComponent("LyrebirdCheckoutForeign_\(UUID().uuidString)")
.path
try? FileManager.default.createDirectory(atPath: tmp,
withIntermediateDirectories: true,
attributes: nil)
defer { try? FileManager.default.removeItem(atPath: tmp) }
let manifest: String = (tmp as NSString).appendingPathComponent("Package.swift")
try? "// some unrelated SwiftPM package".write(toFile: manifest,
atomically: true, encoding: .utf8)
let synthetic: String = (tmp as NSString).appendingPathComponent("a/b/c.swift")
#expect(ProjectScaffolder.lyrebirdCheckoutRoot(forSourceFile: synthetic) == nil)
}
@Test func macOSAppPBXProjUsesLocalPackageRefWhenPathSet() {
let pbx: String = ProjectScaffolder.macOSAppPBXProj(
name: "Foo",
@@ -606,6 +667,30 @@ struct ProjectScaffolderTests {
#expect(!manifest.contains("LyrebirdUI"))
}
// MARK: - score template
@Test func scoreMainSwiftBuildsAndExportsScore() {
let source: String = ProjectScaffolder.mainSwift(name: "MyPiece", template: .score)
#expect(source.contains("Score(bpm:"))
#expect(source.contains("toMusicXMLString"))
#expect(source.contains("fromMusicXML"))
#expect(source.contains("score.musicxml"))
}
@Test func scoreMainSwiftRendersOfflineWithNRTDriver() {
let source: String = ProjectScaffolder.mainSwift(name: "MyPiece", template: .score)
#expect(source.contains("NRTDriver"))
#expect(source.contains("score.caf"))
#expect(source.contains("engine.schedule"))
// Must not embed the Lyrebird copyright in emitted user source.
#expect(!source.contains("Joshua Parmenter"))
}
@Test func scorePackageManifestDoesNotIncludeLyrebirdUI() {
let manifest: String = ProjectScaffolder.packageManifest(name: "MyPiece", template: .score)
#expect(!manifest.contains("LyrebirdUI"))
}
// MARK: - basic template unchanged by default
@Test func defaultTemplateIsBasic() {
+135
View File
@@ -0,0 +1,135 @@
// BeatPositionTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("BeatPosition — meter-aware resolution to quarter beats")
struct BeatPositionTests {
private let fourFour: MeterMap = MeterMap(.fourFour)
private let threeFour: MeterMap = MeterMap(.threeFour)
private let sixEightCompound: MeterMap = MeterMap(.sixEightCompound)
private let sixEightSimple: MeterMap = MeterMap(.sixEightSimple)
private let nineEight: MeterMap = MeterMap(.nineEight)
// MARK: - quarters (meter-free)
@Test func quartersIsIdentity() {
#expect(BeatPosition.quarters(0.0).resolve(in: fourFour) == Fraction(0, 1))
#expect(BeatPosition.quarters(4.0).resolve(in: fourFour) == Fraction(4, 1))
}
@Test func quartersExactFraction() {
#expect(BeatPosition.quarters(Fraction(2, 3)).resolve(in: fourFour) == Fraction(2, 3))
}
// MARK: - flat beat
@Test func flatBeatFourFour() {
// beat 1 → quarter 0; beat 5 → quarter 4 (the from((1.0,…),(5.0,…)) reading).
#expect(BeatPosition.beat(1.0).resolve(in: fourFour) == Fraction(0, 1))
#expect(BeatPosition.beat(5.0).resolve(in: fourFour) == Fraction(4, 1))
}
@Test func flatBeatSixEight() {
// felt beat = dotted-quarter = 1.5 quarters. beat 1 → 0; beat 2 → 1.5;
// beat 3 → 3.0 (bar-2 downbeat — beat stays the conducted pulse).
#expect(BeatPosition.beat(1.0).resolve(in: sixEightCompound) == Fraction(0, 1))
#expect(BeatPosition.beat(2.0).resolve(in: sixEightCompound) == Fraction(3, 2))
#expect(BeatPosition.beat(3.0).resolve(in: sixEightCompound) == Fraction(3, 1))
}
// MARK: - bar + beat (felt beat via grouping)
@Test func barBeatFourFour() {
// 4/4: felt beat == quarter (grouping [1,1,1,1]).
#expect(BeatPosition.bar(1, beat: 1.0).resolve(in: fourFour) == Fraction(0, 1))
#expect(BeatPosition.bar(2, beat: 1.0).resolve(in: fourFour) == Fraction(4, 1))
#expect(BeatPosition.bar(2, beat: 3.0).resolve(in: fourFour) == Fraction(6, 1))
}
@Test func barBeatThreeFour() {
#expect(BeatPosition.bar(2, beat: 1.0).resolve(in: threeFour) == Fraction(3, 1))
}
@Test func barBeatCompoundSixEight() {
// [3,3] → felt beat onsets 0, 1.5; bar 2 beat 1 = 3.0.
#expect(BeatPosition.bar(1, beat: 1.0).resolve(in: sixEightCompound) == Fraction(0, 1))
#expect(BeatPosition.bar(1, beat: 2.0).resolve(in: sixEightCompound) == Fraction(3, 2))
#expect(BeatPosition.bar(2, beat: 1.0).resolve(in: sixEightCompound) == Fraction(3, 1))
}
@Test func barBeatSimpleSixEight() {
// [1,1,1,1,1,1] → felt beat 2 = one eighth = 0.5 quarter.
#expect(BeatPosition.bar(1, beat: 2.0).resolve(in: sixEightSimple) == Fraction(1, 2))
}
@Test func barBeatNineEight() {
// [3,3,3] → felt beat 3 onset = 3.0 quarters.
#expect(BeatPosition.bar(1, beat: 3.0).resolve(in: nineEight) == Fraction(3, 1))
}
@Test func barBeatAdditive332() {
// 8/8 grouped 3+3+2 → felt beats at 0, 1.5, 3.0; lengths 1.5, 1.5, 1.0.
let map: MeterMap = MeterMap(TimeSignature(8, 8, grouping: [3, 3, 2]))
#expect(BeatPosition.bar(1, beat: 1.0).resolve(in: map) == Fraction(0, 1))
#expect(BeatPosition.bar(1, beat: 2.0).resolve(in: map) == Fraction(3, 2))
#expect(BeatPosition.bar(1, beat: 3.0).resolve(in: map) == Fraction(3, 1))
}
@Test func barBeatFractionalInterpolates() {
// 6/8 [3,3]: beat 1.5 = halfway through the first dotted-quarter (0.75q).
#expect(BeatPosition.bar(1, beat: 1.5).resolve(in: sixEightCompound) == Fraction(3, 4))
}
@Test func barBeatFractionalInLastBeatStaysInBar() {
// 6/8 [3,3]: beat 2.5 = onset 1.5 + 0.5 × length 1.5 = 2.25q (< bar end 3).
#expect(BeatPosition.bar(1, beat: 2.5).resolve(in: sixEightCompound) == Fraction(9, 4))
}
@Test func barBeatUpperBoundaryValid() {
// beat == beatsPerBar resolves to the last felt-beat onset (not a trap).
#expect(BeatPosition.bar(1, beat: 2.0).resolve(in: sixEightCompound) == Fraction(3, 2))
}
// MARK: - bar + division (denominator-note granular addressing)
@Test func barDivisionSixEightCountsEighths() {
// 6/8: division = eighth. division 4 = 4th eighth = 1.5q; bar 2 div 1 = 3.0.
#expect(BeatPosition.bar(1, division: 1.0).resolve(in: sixEightCompound) == Fraction(0, 1))
#expect(BeatPosition.bar(1, division: 4.0).resolve(in: sixEightCompound) == Fraction(3, 2))
#expect(BeatPosition.bar(2, division: 1.0).resolve(in: sixEightCompound) == Fraction(3, 1))
}
@Test func barDivisionFourFourEqualsBeat() {
// In simple meters division == beat (quarter).
#expect(BeatPosition.bar(2, division: 3.0).resolve(in: fourFour) == Fraction(6, 1))
}
// MARK: - anacrusis
@Test func anacrusisOffsetsFullBars() {
let map: MeterMap = MeterMap(.fourFour, anacrusis: Fraction(1, 1))
// bar 1 (first full measure) starts after the 1-quarter pickup.
#expect(BeatPosition.bar(1, beat: 1.0).resolve(in: map) == Fraction(1, 1))
#expect(BeatPosition.bar(2, beat: 1.0).resolve(in: map) == Fraction(5, 1))
// pickup (bar 0) starts at quarter 0.
#expect(BeatPosition.bar(0, beat: 1.0).resolve(in: map) == Fraction(0, 1))
}
// MARK: - mid-piece meter change
@Test func meterChangeAccumulatesCapacities() {
let map: MeterMap = MeterMap(segments: [
MeterMap.Segment(startBar: 1, .fourFour),
MeterMap.Segment(startBar: 3, .threeFour),
])
#expect(BeatPosition.bar(3, beat: 1.0).resolve(in: map) == Fraction(8, 1)) // 4+4
#expect(BeatPosition.bar(4, beat: 1.0).resolve(in: map) == Fraction(11, 1)) // 4+4+3
}
}
@@ -1,4 +1,4 @@
// Phase201IsolationGuardTests.swift
// ActorIsolationGuardTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
@@ -8,7 +8,7 @@ import Testing
import Foundation
@testable import LyrebirdSynth
/// Phase 201/202 isolation guards.
/// Main-actor isolation guards.
///
/// These tests protect the main-actor isolation model against silent regression:
///
@@ -23,8 +23,8 @@ import Foundation
/// machinery (`MainActor`, `assumeIsolated`, `DispatchQueue`, `Task {`). Under the
/// Swift 6 language mode such a call would compile silently but violate the
/// `nonisolated` RT render contract. This is a source-text lint.
@Suite("Phase 201/202 isolation guards")
struct Phase201IsolationGuardTests {
@Suite("Actor isolation guards")
struct ActorIsolationGuardTests {
// MARK: - Guard A: off-main bridge
@@ -78,7 +78,7 @@ struct Phase201IsolationGuardTests {
override func build() { onBuild() }
}
let ctx: LyrebirdMessageContext = LyrebirdMessageContext(nrtEngine: engine)
// Synth construction is `@MainActor` (Phase 201); build it on main, then add from
// Synth construction is `@MainActor`; build it on main, then add from
// a background thread to exercise the off-main bridge hop.
let synth: ProbeSynth = await MainActor.run { ProbeSynth { builtCount.increment() } }
let done: DispatchSemaphore = DispatchSemaphore(value: 0)
@@ -148,7 +148,7 @@ struct Phase201IsolationGuardTests {
}
/// Repo root, derived from this file's path:
/// `<root>/Tests/LyrebirdTests/Concurrency/Phase201IsolationGuardTests.swift`.
/// `<root>/Tests/LyrebirdTests/Concurrency/ActorIsolationGuardTests.swift`.
private static var repoRoot: URL {
URL(fileURLWithPath: #filePath)
.deletingLastPathComponent() // Concurrency/
+317
View File
@@ -0,0 +1,317 @@
// DynamicCurveTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Testing
@testable import LyrebirdSynth
// MARK: - Helpers
/// Count occurrences of a substring in a string.
private func count(_ substring: String, in string: String) -> Int {
var result: Int = 0
var searchRange: Range<String.Index> = string.startIndex..<string.endIndex
while let range: Range<String.Index> = string.range(of: substring, range: searchRange) {
result += 1
searchRange = range.upperBound..<string.endIndex
}
return result
}
/// Build a one-part score containing the supplied elements and return the
/// MusicXML string using the default `divisions` (480 PPQ).
private func xmlForElements(
_ elements: ScoreElement...,
divisions: Int = Score.defaultMusicXMLDivisions
) -> String {
let part: ScorePart = ScorePart(
name: "test",
elements: elements
)
let score: Score = Score(parts: [part])
return score.toMusicXMLString(divisions: divisions)
}
// MARK: - Suite
@Suite("DynamicCurve")
struct DynamicCurveTests {
// MARK: - Dynamic.niente
@Test("niente velocity is zero")
func nienteVelocity() {
#expect(Dynamic.niente.velocity == 0.0)
}
@Test("niente musicXMLDynamic is n")
func nienteMusicXMLDynamic() {
#expect(Dynamic.niente.musicXMLDynamic == "n")
}
@Test("fromMusicXMLName n returns niente")
func fromMusicXMLNameN() {
#expect(Dynamic.fromMusicXMLName("n") == .niente)
}
@Test("plain Note dyn:.niente emits n element and round-trips")
func plainNoteNiente() {
let xml: String = xmlForElements(Note(.c, 5, dur: .quarter, dyn: .niente))
// The dynamic direction should contain <n/>
#expect(xml.contains("<n/>"))
// Round-trip: the decoded score should have .niente as the dynamic
guard let decoded: Score = try? Score.fromMusicXML(data: Data(xml.utf8)) else {
Issue.record("Failed to decode MusicXML")
return
}
let events: [ScoreEvent] = decoded.parts.first?.flatten() ?? []
#expect(!events.isEmpty)
#expect(events.first?.velocity == Dynamic.niente.velocity)
}
// MARK: - 3-point messa di voce (pp < f > pp)
@Test("3-point messa di voce emits correct dynamics and hairpins")
func messaDiVoce() {
// doubleWhole = 8 quarter-beats, 480 PPQ → noteDivisions = 3840
// Point 0 offset = 0, point 0.5 offset = 1920, point 1.0 offset = 3840
let xml: String = xmlForElements(
Note(.c, 5, dur: .doubleWhole, dyn: .pp,
dynamicCurve: [(0.0, .pp), (0.5, .f), (1.0, .pp)])
)
// Dynamics: <pp/> at 0, <f/> at 0.5, <pp/> at 1.0
#expect(xml.contains("<pp/>"))
#expect(xml.contains("<f/>"))
// Two <pp/> instances: one at the start and one at the end
#expect(count("<pp/>", in: xml) == 2)
// One crescendo wedge start, one diminuendo wedge start
#expect(xml.contains("<wedge type=\"crescendo\""))
#expect(xml.contains("<wedge type=\"diminuendo\""))
// Two wedge stops
#expect(count("<wedge type=\"stop\"", in: xml) == 2)
// Check offsets: 0 at position 0, 1920 at 0.5, 3840 at 1.0
let offset0: String = "<offset>0</offset>"
let offset1920: String = "<offset>1920</offset>"
let offset3840: String = "<offset>3840</offset>"
#expect(xml.contains(offset0))
#expect(xml.contains(offset1920))
#expect(xml.contains(offset3840))
// Crescendo wedge is at offset 0, stop at 1920
// Diminuendo wedge is at offset 1920, stop at 3840
// Verify the crescendo/stop ordering: crescendo precedes its stop
let crescendoRange: Range<String.Index>? = xml.range(of: "crescendo")
let dimRange: Range<String.Index>? = xml.range(of: "diminuendo")
let stopFirst: Range<String.Index>? = xml.range(of: "<wedge type=\"stop\"")
#expect(crescendoRange != nil)
#expect(dimRange != nil)
#expect(stopFirst != nil)
if let cr: Range<String.Index> = crescendoRange,
let st: Range<String.Index> = stopFirst {
#expect(cr.lowerBound < st.lowerBound)
}
}
// MARK: - Equal-hold 4-point
@Test("4-point curve with hold emits one crescendo and one diminuendo")
func equalHold() {
// pp -> f -> f -> pp: the hold (f->f) produces NO wedge; one < and one >.
// Quarter note = 1 quarter-beat, 480 PPQ → noteDivisions = 480.
// 0.0 → 0, 0.3 → 144, 0.7 → 336, 1.0 → 480
let xml: String = xmlForElements(
Note(.c, 5, dur: .quarter, dyn: .pp,
dynamicCurve: [(0.0, .pp), (0.3, .f), (0.7, .f), (1.0, .pp)])
)
// <f/> should appear exactly once (change-only for the same value at 0.3 and 0.7)
#expect(count("<f/>", in: xml) == 1)
// Exactly one crescendo (pp→f) and one diminuendo (f→pp)
#expect(count("<wedge type=\"crescendo\"", in: xml) == 1)
#expect(count("<wedge type=\"diminuendo\"", in: xml) == 1)
// Two stops
#expect(count("<wedge type=\"stop\"", in: xml) == 2)
// The diminuendo start is at offset corresponding to 0.7
let offset336: String = "<offset>336</offset>"
#expect(xml.contains(offset336))
}
// MARK: - Niente hairpins
@Test("niente curve sets niente attribute on wedge start")
func nienteCurve() {
// (0, .niente) -> (0.5, .f) -> (1, .niente)
// crescendo starts at .niente → niente="yes" on crescendo
// diminuendo ends at .niente → niente="yes" on diminuendo
let xml: String = xmlForElements(
Note(.c, 5, dur: .whole, dyn: .mf,
dynamicCurve: [(0.0, .niente), (0.5, .f), (1.0, .niente)])
)
// Two <n/> (one at start, one at end)
#expect(count("<n/>", in: xml) == 2)
// Crescendo with niente="yes"
#expect(xml.contains("type=\"crescendo\" niente=\"yes\""))
// Diminuendo with niente="yes"
#expect(xml.contains("type=\"diminuendo\" niente=\"yes\""))
}
// MARK: - Suppression of plain dyn: direction
@Test("a curve-bearing note does NOT also emit its plain dyn: direction")
func suppression() {
// With a 3-point curve the plain <mf/> must NOT appear (the curve owns
// the dynamics). The curve emits pp and f but not mf.
let xml: String = xmlForElements(
Note(.c, 5, dur: .whole, dyn: .mf,
dynamicCurve: [(0.0, .pp), (0.5, .f), (1.0, .pp)])
)
// Count <dynamics> blocks: should equal the number of change-points in
// the curve (pp at 0, f at 0.5, pp at 1.0 = 3 blocks), NOT 3+1.
let dynamicsCount: Int = count("<dynamics>", in: xml)
#expect(dynamicsCount == 3)
// mf must not appear
#expect(!xml.contains("<mf/>"))
}
// MARK: - Next-note dynamic tracker
@Test("next note after a curve emits its direction when different from curve end")
func nextNoteTracking() {
// Curve ends at .pp; next note is .f → .f must be emitted.
let xml: String = xmlForElements(
Note(.c, 5, dur: .whole, dyn: .pp,
dynamicCurve: [(0.0, .pp), (0.5, .f), (1.0, .pp)]),
Note(.d, 5, dur: .quarter, dyn: .f)
)
// <f/> appears at least once in the second note's direction
// (it also appears inside the curve, so count >= 2 total).
#expect(count("<f/>", in: xml) >= 2)
// The last <f/> appearance is for the plain direction on the D note.
// Confirm by checking the note appears after all curve directions.
// We just confirm the second note's standalone direction is present
// by verifying count <dynamics> includes an extra one beyond the curve.
let dynamicsCount: Int = count("<dynamics>", in: xml)
// Curve has 3 change-points (pp, f, pp); the following D note adds 1 more.
#expect(dynamicsCount == 4)
}
// MARK: - Flatten transparency
@Test("flatten of dynamicCurve note produces same events as unwrapped note")
func flattenTransparency() {
let partWithCurve: ScorePart = ScorePart(
name: "test",
elements: [
Note(.c, 5, dur: .whole, dyn: .mf,
dynamicCurve: [(0.0, .pp), (0.5, .f), (1.0, .pp)])
]
)
let partPlain: ScorePart = ScorePart(
name: "test",
elements: [Note(.c, 5, dur: .whole, dyn: .mf)]
)
let curveEvents: [ScoreEvent] = partWithCurve.flatten()
let plainEvents: [ScoreEvent] = partPlain.flatten()
#expect(curveEvents.count == plainEvents.count)
if curveEvents.count == plainEvents.count {
for (curveEvent, plainEvent) in zip(curveEvents, plainEvents) {
#expect(curveEvent.pitch == plainEvent.pitch)
#expect(curveEvent.duration == plainEvent.duration)
#expect(curveEvent.velocity == plainEvent.velocity)
#expect(curveEvent.beat == plainEvent.beat)
}
}
}
// MARK: - Empty dynamicCurve is byte-identical
@Test("empty dynamicCurve produces byte-identical output")
func emptyCurveIdentical() {
let withEmpty: String = xmlForElements(
Note(.c, 5, dur: .quarter, dyn: .mf, dynamicCurve: [])
)
let withoutParam: String = xmlForElements(
Note(.c, 5, dur: .quarter, dyn: .mf)
)
#expect(withEmpty == withoutParam)
}
// MARK: - Chord supports dynamicCurve
@Test("Chord supports dynamicCurve and emits curve directions")
func chordWithCurve() {
let xml: String = xmlForElements(
Chord(
[Pitch.named(.c, 5), Pitch.named(.e, 5), Pitch.named(.g, 5)],
dur: .whole,
dyn: .mp,
dynamicCurve: [(0.0, .pp), (0.5, .f), (1.0, .pp)]
)
)
// Curve directions must appear and plain <mp/> must be suppressed.
#expect(xml.contains("<pp/>"))
#expect(xml.contains("<f/>"))
#expect(!xml.contains("<mp/>"))
#expect(xml.contains("<wedge type=\"crescendo\""))
#expect(xml.contains("<wedge type=\"diminuendo\""))
}
// MARK: - Multi-voice path
@Test("curve suppresses its own dyn but a sibling voice still emits")
func curveInMultiVoiceSuppressesOnlyItsOwnDynamic() {
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Voice(1) {
Note(.c, 5, dur: .whole, dyn: .mp,
dynamicCurve: [(0.0, .pp), (0.5, .f), (1.0, .pp)])
}
Voice(2) {
Note(.c, 4, dur: .whole, dyn: .ff)
}
}
}
let xml: String = score.toMusicXMLString()
// Voice 1's curve emits hairpins; its plain mp: is suppressed.
#expect(xml.contains("<wedge type=\"crescendo\""))
#expect(!xml.contains("<mp/>"))
// Voice 2's plain dynamic still emits.
#expect(xml.contains("<ff/>"))
}
// MARK: - Single-point curve
@Test("single-point curve emits one dynamic at its offset, no wedge")
func singlePointCurveEmitsDynamicNoWedge() {
// whole note = 4 beats → 1920 divisions; position 0.5 → offset 960.
let xml: String = xmlForElements(
Note(.c, 5, dur: .whole, dyn: .mp, dynamicCurve: [(0.5, .mf)])
)
#expect(xml.contains("<mf/>"))
#expect(xml.contains("<offset>960</offset>"))
#expect(count("<wedge", in: xml) == 0)
#expect(!xml.contains("<mp/>")) // plain dyn suppressed by the curve
}
// MARK: - Barline-crossing curve
@Test("curve on a barline-crossing note emits with offsets past the bar")
func curveOnBarlineCrossingNoteIsEmitted() {
// A breve (8 beats) in 4/4 crosses the barline. noteDivisions = 8*480 =
// 3840; position 1.0 → <offset>3840</offset> (past the first bar — a
// documented limitation, but the curve must still be emitted, not dropped).
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.c, 5, dur: .doubleWhole, dyn: .mp,
dynamicCurve: [(0.0, .pp), (0.5, .f), (1.0, .pp)])
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<wedge type=\"crescendo\""))
#expect(xml.contains("<wedge type=\"diminuendo\""))
#expect(xml.contains("<offset>3840</offset>"))
// Curve emitted once (on the head), not duplicated on the tied continuation.
#expect(count("<wedge type=\"crescendo\"", in: xml) == 1)
}
}
+5 -5
View File
@@ -136,7 +136,7 @@ struct AmplitudeFollowerTests {
#expect(!nonZero.isEmpty)
}
/// Phase 174 — denormal flush moved to once-per-block. Pre-heat the smoother
/// Denormal flush moved to once-per-block. Pre-heat the smoother
/// to ~1.0 with a loud DC input, then switch to a tiny-but-nonzero input
/// (1e-20) with very fast release — `_prevAmp` drops several orders of
/// magnitude per block, sweeping through the denormal regime that the
@@ -392,7 +392,7 @@ struct LookAheadLimiterTests {
#expect(abs(steadySample - 1.0) < 0.001)
}
/// Phase 173a — zero-look-ahead fast path is a pure peak follower (no ring, no deque).
/// Zero-look-ahead fast path is a pure peak follower (no ring, no deque).
/// A loud transient must clamp on the same sample (instantaneous attack), and after
/// the transient passes the gain must release back toward 1.0.
@Test func zeroLookAheadPeakFollowerInstantClamp() {
@@ -410,7 +410,7 @@ struct LookAheadLimiterTests {
#expect(abs(Double(block[engine.blockSize - 1]) - maxAmp) < 1e-9)
}
/// Phase 173a — denormal flush moved to once-per-block (was per-sample).
/// Denormal flush moved to once-per-block (was per-sample).
/// Sustained extreme reduction (tiny maxAmp on loud DC) drives `_gain` toward a
/// very small value; the once-per-block flush must keep it from becoming a
/// denormal that would slow down the RT path. Render long enough (~2 s) to
@@ -545,7 +545,7 @@ struct CompressorTests {
#expect(abs(steadySample - expectedGain) < 0.001)
}
/// Phase 174 — once-per-block denormal flush survives sustained extreme reduction.
/// Once-per-block denormal flush survives sustained extreme reduction.
/// 1.0 DC at threshold=-60 dB ratio=20:1 with makeup -40 dB drives gain very low;
/// output must stay finite + bounded over ~2 s.
@Test func denormalCadenceCompressor() {
@@ -671,7 +671,7 @@ struct ExpanderTests {
#expect(abs(steadySample - expectedOutput) < 0.0001)
}
/// Phase 174 — once-per-block denormal flush survives the gate path.
/// Once-per-block denormal flush survives the gate path.
/// ratio=0 (hard gate) on a sub-threshold signal drives gain → 1e-6 (−120 dB
/// floor); output must stay finite + bounded over ~2 s.
@Test func denormalCadenceExpander() {
+10 -10
View File
@@ -8,11 +8,11 @@ import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
/// NRT `build`-closure shim (Phase 201).
/// NRT `build`-closure shim.
///
/// `NRTJob.build` is a non-isolated `@Sendable (SynthesisEngine) throws -> Void`
/// that `EngineHost._executeJob` runs on a background task — *not* the main actor.
/// `SynthesisEngine.add(_:)` is `@MainActor` (Phase 201), so it cannot be invoked
/// `SynthesisEngine.add(_:)` is `@MainActor`, so it cannot be invoked
/// directly from inside the off-main build closure. The build closure runs *before*
/// `engine.start()`, so the engine is not yet rendering and nothing else touches it
/// concurrently; hopping the add onto the main actor synchronously is therefore safe
@@ -29,9 +29,9 @@ private func nrtBuildAdd(_ engine: SynthesisEngine, _ makeSynth: @escaping @Main
if let thrown: any Error = thrown { throw thrown }
}
/// Phase 197 — `EngineHost` facade coverage.
/// `EngineHost` facade coverage.
@MainActor
@Suite("EngineHost (Phase 197)")
@Suite("EngineHost")
struct EngineHostTests {
// MARK: - Test helpers
@@ -95,7 +95,7 @@ struct EngineHostTests {
}
}
/// Phase 197 re-review fix: pre-check throw must not leak the
/// Pre-check throw must not leak the
/// host lock. If `_validateRoleUnlocked` threw without `defer`-ed
/// unlock, every subsequent host call on the same instance would
/// deadlock on `_lock.lock()`. This test asserts the host is
@@ -125,10 +125,10 @@ struct EngineHostTests {
/// Same-`.rtOutput(deviceID:)` re-registration throws
/// `.duplicateRole` because the `Hashable` enum case already
/// discriminates by deviceID. Phase 198 (F8) dropped the dead
/// discriminates by deviceID. The dead
/// `.duplicateDevice` enum case that would have covered cross-role
/// same-device collisions — re-add when a future role shape
/// requires it.
/// same-device collisions was dropped — re-add when a future role
/// shape requires it.
@Test func makeEngineSameRtOutputRoleTwiceThrowsDuplicateRole() throws {
let host: EngineHost = EngineHost()
_ = try host.makeEngine(role: .rtOutput(deviceID: 42), config: makeConfig())
@@ -325,7 +325,7 @@ struct EngineHostTests {
#expect(caught is DeliberateBuildFailure)
}
/// Phase 198 (F1 re-review): a `build` closure that deliberately
/// A `build` closure that deliberately
/// throws `CancellationError` must propagate as a stream-level
/// throw, not be misclassified as a caller-cancel and silently
/// swallowed. The outer-catch `Task.isCancelled` guard distinguishes
@@ -361,7 +361,7 @@ struct EngineHostTests {
"got \(String(describing: caught))"))
}
/// Phase 198 (F1): caller breaking the for-await early must finish
/// Caller breaking the for-await early must finish
/// the stream cleanly, not throw `CancellationError`. The earlier
/// implementation forwarded the cooperative-cancel from
/// `withThrowingTaskGroup`'s for-await into `continuation.finish(throwing:)`,
+353
View File
@@ -0,0 +1,353 @@
// FillMeasureTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("FillMeasure — build-time measure-fill expansion")
struct FillMeasureTests {
// MARK: - 1. Basic fill in 4/4: 3 beats → 1-beat rest inserted
@Test func threeBeatsThenFillIn4_4() {
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("lead") {
Note(.c, 4, dur: .quarter) // beat 0
Note(.d, 4, dur: .quarter) // beat 1
Note(.e, 4, dur: .quarter) // beat 2 (cursor = 3 after)
FillMeasure() // fills 1 beat → rest at beat 3
Note(.f, 4, dur: .quarter) // should land at beat 4
}
}
let events: [ScoreEvent] = score.parts[0].flatten()
// 4 notes expected (FillMeasure → rest, not a sounding event)
#expect(events.count == 4)
// First three notes at beats 0, 1, 2
#expect(abs(events[0].beat - 0.0) < 1e-12)
#expect(abs(events[1].beat - 1.0) < 1e-12)
#expect(abs(events[2].beat - 2.0) < 1e-12)
// Note after FillMeasure lands at beat 4 (next downbeat of bar 2)
#expect(abs(events[3].beat - 4.0) < 1e-12)
#expect(events[3].pitch.midiNote == 65) // F4
}
@Test func threeBeatsThenFillIn4_4_barFilled() throws {
// Assert via MusicXML that bar 1 has 4 beats of content.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("lead") {
Note(.c, 4, dur: .quarter)
Note(.d, 4, dur: .quarter)
Note(.e, 4, dur: .quarter)
FillMeasure()
Note(.f, 4, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
// The generated MusicXML must have a <rest> element in measure 1.
// A properly bar-filled measure does not produce an "overfill" error
// in Dorico/MuseScore — we validate via the flatten beat position above.
#expect(xml.contains("<rest/>") || xml.contains("<rest>"))
}
// MARK: - 2. FillMeasure when cursor already on a barline → no-op
@Test func fillMeasureOnBarlineIsNoop() {
// 4 quarter notes exactly fill 4/4 bar 1; FillMeasure should insert nothing.
let scoreWithFill: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("lead") {
Note(.c, 4, dur: .quarter)
Note(.d, 4, dur: .quarter)
Note(.e, 4, dur: .quarter)
Note(.f, 4, dur: .quarter) // cursor = 4 after → exactly on barline
FillMeasure() // no-op
Note(.g, 4, dur: .quarter) // beat 4
}
}
let scoreWithout: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("lead") {
Note(.c, 4, dur: .quarter)
Note(.d, 4, dur: .quarter)
Note(.e, 4, dur: .quarter)
Note(.f, 4, dur: .quarter)
Note(.g, 4, dur: .quarter)
}
}
let eventsWithFill: [ScoreEvent] = scoreWithFill.parts[0].flatten()
let eventsWithout: [ScoreEvent] = scoreWithout.parts[0].flatten()
#expect(eventsWithFill.count == eventsWithout.count)
for i: Int in 0..<eventsWithFill.count {
#expect(abs(eventsWithFill[i].beat - eventsWithout[i].beat) < 1e-12)
}
}
// MARK: - 3. Generate: 8 sixteenths (2 beats) + 4 eighths (2 beats) = exactly 4 beats → no rest
@Test func generateFillExact() {
// 8 sixteenth notes = 2.0 beats; 4 eighth notes = 2.0 beats; total = 4.0 = bar.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("lead") {
Generate(8) { _ in [Note(.c, 4, dur: .sixteenth)] }
Generate(4) { _ in [Note(.c, 4, dur: .eighth)] }
FillMeasure() // no-op — already at beat 4
Note(.d, 4, dur: .quarter) // beat 4
}
}
let events: [ScoreEvent] = score.parts[0].flatten()
// 8 + 4 + 1 = 13 events
#expect(events.count == 13)
// Last note (after FillMeasure) starts at beat 4
let lastBeat: Double = events.last?.beat ?? -1.0
#expect(abs(lastBeat - 4.0) < 1e-12)
}
@Test func generateHalfFill() {
// 8 sixteenths (2 beats) + 3 eighths (1.5 beats) = 3.5 beats → fill 0.5 beat.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("lead") {
Generate(8) { _ in [Note(.c, 4, dur: .sixteenth)] }
Generate(3) { _ in [Note(.c, 4, dur: .eighth)] }
FillMeasure() // fills 0.5 beat (eighth rest)
Note(.d, 4, dur: .quarter) // beat 4
}
}
let events: [ScoreEvent] = score.parts[0].flatten()
// 8 + 3 + 1 = 12 sounding notes; FillMeasure → rest (no event)
#expect(events.count == 12)
let lastBeat: Double = events.last?.beat ?? -1.0
#expect(abs(lastBeat - 4.0) < 1e-12)
}
// MARK: - 4. Note after FillMeasure lands on next downbeat
@Test func noteAfterFillLandsOnDownbeat() {
// 2.5 beats in 4/4 → fill 1.5 beats → next note at beat 4.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("lead") {
Note(.c, 4, dur: .dotted(.quarter)) // 1.5 beats; cursor = 1.5
Note(.d, 4, dur: .quarter) // cursor = 2.5
FillMeasure() // fills 1.5 beats
Note(.e, 4, dur: .quarter) // beat 4
}
}
let events: [ScoreEvent] = score.parts[0].flatten()
#expect(events.count == 3)
#expect(abs(events[2].beat - 4.0) < 1e-12)
}
// MARK: - 5. FillMeasure inside a Voice block
@Test func fillMeasureInsideVoice() {
// Voice 1: 3 beats + FillMeasure → 1-beat rest, then note at beat 4.
// Voice 2: 1 whole note.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("lead") {
Voice(1) {
Note(.c, 4, dur: .quarter)
Note(.d, 4, dur: .quarter)
Note(.e, 4, dur: .quarter)
FillMeasure()
Note(.f, 4, dur: .quarter)
}
Voice(2) {
Note(.c, 3, dur: .whole)
}
}
}
let events: [ScoreEvent] = score.parts[0].flatten()
// Voice 1: 4 notes; Voice 2: 1 note.
let voice1: [ScoreEvent] = events.filter { $0.voice == 1 }
let voice2: [ScoreEvent] = events.filter { $0.voice == 2 }
#expect(voice1.count == 4)
#expect(voice2.count == 1)
// F4 (voice 1) lands at beat 4
let lastVoice1: ScoreEvent? = voice1.last
#expect(abs((lastVoice1?.beat ?? -1.0) - 4.0) < 1e-12)
}
// MARK: - 6. 3/4 meter: 2 beats + FillMeasure → 1-beat rest
@Test func fillMeasureIn3_4() {
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(3, 4)) {
Part("lead") {
Note(.c, 4, dur: .quarter) // beat 0
Note(.d, 4, dur: .quarter) // beat 1 (cursor = 2)
FillMeasure() // fills 1 beat → rest at beat 2
Note(.e, 4, dur: .quarter) // beat 3 (first beat of bar 2)
}
}
let events: [ScoreEvent] = score.parts[0].flatten()
#expect(events.count == 3)
#expect(abs(events[0].beat - 0.0) < 1e-12)
#expect(abs(events[1].beat - 1.0) < 1e-12)
#expect(abs(events[2].beat - 3.0) < 1e-12)
}
// MARK: - 7. Mid-piece meter change (4/4 → 3/4)
@Test func fillMeasureMidPieceMeterChange() {
// Bar 1: 4/4, bar 2: 3/4. FillMeasure in bar 2 region (after 4 beats).
let mmap: MeterMap = MeterMap(segments: [
MeterMap.Segment(startBar: 1, TimeSignature(4, 4)),
MeterMap.Segment(startBar: 2, TimeSignature(3, 4))
])
let score: Score = Score(bpm: 120, meterMap: mmap) {
Part("lead") {
// Fill bar 1 completely
Note(.c, 4, dur: .quarter)
Note(.d, 4, dur: .quarter)
Note(.e, 4, dur: .quarter)
Note(.f, 4, dur: .quarter) // cursor = 4 → on bar-2 downbeat
// In bar 2 (3/4): 2 quarter notes → cursor = 6
Note(.g, 4, dur: .quarter) // beat 4
Note(.a, 4, dur: .quarter) // beat 5; cursor = 6
FillMeasure() // fills 1 beat (bar 2 has 3 beats → need 1 more)
Note(.b, 4, dur: .quarter) // beat 7 (first beat of bar 3)
}
}
let events: [ScoreEvent] = score.parts[0].flatten()
// 6 notes + fill rest; should have 7 events
#expect(events.count == 7)
// Last note at beat 7
let lastBeat: Double = events.last?.beat ?? -1.0
#expect(abs(lastBeat - 7.0) < 1e-12)
}
// MARK: - 8. Sectioned score: FillMeasure inside a section aligns bar
@Test func fillMeasureInSectionedScore() {
// Section "A" has 3 beats of content + FillMeasure in 4/4 → spans 1 bar.
// Section "B" has a whole note.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Section("A") {
Part("lead") {
Note(.c, 4, dur: .quarter)
Note(.d, 4, dur: .quarter)
Note(.e, 4, dur: .quarter)
FillMeasure()
}
}
Section("B") {
Part("lead") {
Note(.f, 4, dur: .whole)
}
}
}
let events: [ScoreEvent] = score.parts[0].flatten()
// Section A: 3 notes; Section B: 1 note.
#expect(events.count == 4)
// Section B note starts at beat 4 (bar 2, beat 1)
let sectionBNote: ScoreEvent? = events.last
#expect(abs((sectionBNote?.beat ?? -1.0) - 4.0) < 1e-12)
// The score should span exactly 2 measures (8 beats)
let total: Double = score.totalBeats
#expect(abs(total - 8.0) < 1e-12)
}
// MARK: - 9. Score without FillMeasure is byte-identical (no regression)
@Test func scoreWithoutFillMeasureIsUnchanged() {
let scoreA: Score = Score(bpm: 120) {
Part("lead") {
Note(.c, 4, dur: .quarter)
Rest(dur: .quarter)
Note(.e, 4, dur: .half)
}
}
let scoreB: Score = Score(bpm: 120) {
Part("lead") {
Note(.c, 4, dur: .quarter)
Rest(dur: .quarter)
Note(.e, 4, dur: .half)
}
}
let eventsA: [ScoreEvent] = scoreA.parts[0].flatten()
let eventsB: [ScoreEvent] = scoreB.parts[0].flatten()
#expect(eventsA.count == eventsB.count)
for i: Int in 0..<eventsA.count {
#expect(abs(eventsA[i].beat - eventsB[i].beat) < 1e-12)
#expect(eventsA[i].pitch.midiNote == eventsB[i].pitch.midiNote)
}
// MusicXML output should also be identical
#expect(scoreA.toMusicXMLString() == scoreB.toMusicXMLString())
}
// MARK: - 10. Multiple FillMeasure in one part
@Test func multipleFillMeasures() {
// Bar 1: 3 beats + fill; Bar 2: 1 beat + fill.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("lead") {
Note(.c, 4, dur: .quarter) // beat 0
Note(.d, 4, dur: .quarter) // beat 1
Note(.e, 4, dur: .quarter) // beat 2; cursor = 3
FillMeasure() // fills 1 beat → cursor = 4
Note(.f, 4, dur: .quarter) // beat 4 (bar 2 downbeat)
FillMeasure() // fills 3 beats → cursor = 8
Note(.g, 4, dur: .quarter) // beat 8 (bar 3 downbeat)
}
}
let events: [ScoreEvent] = score.parts[0].flatten()
#expect(events.count == 5)
#expect(abs(events[3].beat - 4.0) < 1e-12)
#expect(abs(events[4].beat - 8.0) < 1e-12)
}
// MARK: - 11. FillMeasure as the first element (cursor 0) is a no-op
@Test func fillMeasureAtCursorZeroIsNoop() {
let withFill: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("lead") {
FillMeasure() // cursor 0, on barline → nothing
Note(.c, 4, dur: .quarter) // must land on beat 0
}
}
let without: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("lead") { Note(.c, 4, dur: .quarter) }
}
let a: [ScoreEvent] = withFill.parts[0].flatten()
let b: [ScoreEvent] = without.parts[0].flatten()
#expect(a.count == b.count)
#expect(abs(a[0].beat - 0.0) < 1e-12)
}
// MARK: - 12. FillMeasure under an anacrusis
@Test func fillMeasureWithAnacrusis() {
// 1-beat pickup (bar 0 = [0, 1)). A quarter fills the pickup exactly →
// cursor at beat 1 = bar-1 downbeat → FillMeasure is a no-op.
let onBarline: Score = Score(
bpm: 120,
meterMap: MeterMap(.fourFour, anacrusis: Fraction(1, 1))
) {
Part("lead") {
Note(.c, 4, dur: .quarter) // fills the pickup, cursor → 1.0
FillMeasure() // on the bar-1 downbeat → nothing
Note(.d, 4, dur: .quarter) // must land on beat 1.0
}
}
let events: [ScoreEvent] = onBarline.parts[0].flatten()
#expect(events.count == 2)
#expect(abs(events[1].beat - 1.0) < 1e-12)
// Partway through the pickup: an eighth (0.5) leaves 0.5 to the pickup's
// end → FillMeasure pads that 0.5, so the next note lands on the bar-1
// downbeat at 1.0.
let midPickup: Score = Score(
bpm: 120,
meterMap: MeterMap(.fourFour, anacrusis: Fraction(1, 1))
) {
Part("lead") {
Note(.c, 4, dur: .eighth) // 0.5 beat, cursor → 0.5
FillMeasure() // fills 0.5 → cursor 1.0
Note(.d, 4, dur: .quarter) // lands at beat 1.0
}
}
let ev2: [ScoreEvent] = midPickup.parts[0].flatten()
#expect(ev2.count == 2)
#expect(abs(ev2[1].beat - 1.0) < 1e-12)
}
}
+1 -1
View File
@@ -255,7 +255,7 @@ struct GVerbTests {
}
}
/// Phase 175 — branchless ring-buffer wrap exercised across many wraps of the
/// Branchless ring-buffer wrap exercised across many wraps of the
/// tap delay (44000 samples ≈ 1 s) and 4 FDN delay lines. Drive a quiet
/// non-zero input over ~3 s and assert output stays finite + bounded.
/// Single shared engine; `advanceBlock` bumps `segmentSerial` so the
@@ -66,7 +66,7 @@ struct GeneratorInputProviderTests {
#expect(value == 7.5)
}
// MARK: - Phase 170 — provider as first-class ValidGeneratorInput
// MARK: - Provider as first-class ValidGeneratorInput
@Test("ValidGeneratorInput._resolvedInput default returns self")
func defaultResolveIsIdentity() {
+393
View File
@@ -0,0 +1,393 @@
// GlissandoTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("Glissando — authoring, encoding, and validation")
struct GlissandoTests {
// MARK: - Basic glissando emission
@Test func glissandoDefaultEmitsWavyStartAndStop() {
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 5, dur: .quarter, spanners: [.beginGlissando(Glissando())])
Note(.e, 5, dur: .quarter, spanners: [.endGlissando])
}
}
let xml: String = score.toMusicXMLString()
// Start: <glissando type="start" line-type="wavy" number="1"/>
#expect(xml.contains("<glissando type=\"start\" line-type=\"wavy\" number=\"1\"/>"))
// Stop: <glissando type="stop" number="1"/>
#expect(xml.contains("<glissando type=\"stop\" number=\"1\"/>"))
// Exactly one start and one stop.
let startCount: Int = xml.components(separatedBy: "<glissando type=\"start\"").count - 1
let stopCount: Int = xml.components(separatedBy: "<glissando type=\"stop\"").count - 1
#expect(startCount == 1)
#expect(stopCount == 1)
// Start appears before stop in document order.
let startRange: Range<String.Index>? = xml.range(of: "<glissando type=\"start\"")
let stopRange: Range<String.Index>? = xml.range(of: "<glissando type=\"stop\"")
if let s: Range<String.Index> = startRange,
let t: Range<String.Index> = stopRange {
#expect(s.lowerBound < t.lowerBound)
} else {
Issue.record("Expected both glissando start and stop to appear in XML")
}
}
@Test func glissandoNoAnnotationProducesByteIdenticalOutput() {
// A score without any glissando must not contain <glissando> or <slide>.
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 5, dur: .quarter)
Note(.e, 5, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
#expect(!xml.contains("<glissando"))
#expect(!xml.contains("<slide"))
}
// MARK: - Slide kind
@Test func slideKindEmitsSlideElement() {
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 5, dur: .quarter,
spanners: [.beginGlissando(Glissando(kind: .slide, lineType: .solid))])
Note(.g, 5, dur: .quarter, spanners: [.endGlissando])
}
}
let xml: String = score.toMusicXMLString()
// Start uses <slide>, not <glissando>.
#expect(xml.contains("<slide type=\"start\" line-type=\"solid\" number=\"1\"/>"))
// Stop also uses <slide>.
#expect(xml.contains("<slide type=\"stop\" number=\"1\"/>"))
// No <glissando> element present.
#expect(!xml.contains("<glissando"))
}
@Test func stopElementMatchesStartKind_glissando() {
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 5, dur: .quarter, spanners: [.beginGlissando(Glissando(kind: .glissando))])
Note(.e, 5, dur: .quarter, spanners: [.endGlissando])
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<glissando type=\"stop\" number=\"1\"/>"))
#expect(!xml.contains("<slide type=\"stop\""))
}
@Test func stopElementMatchesStartKind_slide() {
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 5, dur: .quarter,
spanners: [.beginGlissando(Glissando(kind: .slide, lineType: .solid))])
Note(.g, 5, dur: .quarter, spanners: [.endGlissando])
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<slide type=\"stop\" number=\"1\"/>"))
#expect(!xml.contains("<glissando type=\"stop\""))
}
// MARK: - Line types
@Test func lineTypeSolidEmitsCorrectAttribute() {
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 5, dur: .quarter,
spanners: [.beginGlissando(Glissando(kind: .glissando, lineType: .solid))])
Note(.e, 5, dur: .quarter, spanners: [.endGlissando])
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("line-type=\"solid\""))
}
@Test func lineTypeDashedEmitsCorrectAttribute() {
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 5, dur: .quarter,
spanners: [.beginGlissando(Glissando(kind: .glissando, lineType: .dashed))])
Note(.e, 5, dur: .quarter, spanners: [.endGlissando])
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("line-type=\"dashed\""))
}
@Test func lineTypeDottedEmitsCorrectAttribute() {
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 5, dur: .quarter,
spanners: [.beginGlissando(Glissando(kind: .glissando, lineType: .dotted))])
Note(.e, 5, dur: .quarter, spanners: [.endGlissando])
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("line-type=\"dotted\""))
}
@Test func lineTypeWavyEmitsCorrectAttribute() {
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 5, dur: .quarter,
spanners: [.beginGlissando(Glissando(kind: .glissando, lineType: .wavy))])
Note(.e, 5, dur: .quarter, spanners: [.endGlissando])
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("line-type=\"wavy\""))
}
// MARK: - Text label
@Test func textLabelEmitsNonSelfClosingElement() {
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 5, dur: .quarter,
spanners: [.beginGlissando(Glissando(text: "gliss."))])
Note(.e, 5, dur: .quarter, spanners: [.endGlissando])
}
}
let xml: String = score.toMusicXMLString()
// Non-self-closing form with text content.
#expect(xml.contains("<glissando type=\"start\" line-type=\"wavy\" number=\"1\">gliss.</glissando>"))
// The self-closing form must NOT appear for the start.
let selfClosingStart: Int = xml.components(
separatedBy: "<glissando type=\"start\" line-type=\"wavy\" number=\"1\"/>"
).count - 1
#expect(selfClosingStart == 0)
}
@Test func textLabelNilEmitsSelfClosingElement() {
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 5, dur: .quarter,
spanners: [.beginGlissando(Glissando(text: nil))])
Note(.e, 5, dur: .quarter, spanners: [.endGlissando])
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<glissando type=\"start\" line-type=\"wavy\" number=\"1\"/>"))
#expect(!xml.contains(">gliss.</glissando>"))
}
@Test func textLabelWithXMLSpecialCharsIsEscaped() {
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 5, dur: .quarter,
spanners: [.beginGlissando(Glissando(text: "A&<B>"))])
Note(.e, 5, dur: .quarter, spanners: [.endGlissando])
}
}
let xml: String = score.toMusicXMLString()
// The escape function should have converted & → &amp;, < → &lt;, > → &gt;
#expect(xml.contains("A&amp;&lt;B&gt;"))
}
// MARK: - Unbalanced span handling
@Test func orphanStopDroppedAndDiagnosticPosted() async {
LyrebirdMessageCenter.shared.clear()
let score: Score = Score(bpm: 120) {
Part("p") {
// Only an endGlissando with no matching beginGlissando.
Note(.c, 5, dur: .quarter, spanners: [.endGlissando])
Note(.e, 5, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
// No glissando elements should be emitted.
#expect(!xml.contains("<glissando"))
#expect(!xml.contains("<slide"))
// Poll until the async diagnostic Task fires (up to ~50 yields).
let maxPolls: Int = 50
var pollCount: Int = 0
while pollCount < maxPolls {
await Task.yield()
let warnings: [LyrebirdMessage] = LyrebirdMessageCenter.shared.messages.filter {
$0.tier == .warning
}
if !warnings.isEmpty { break }
pollCount += 1
}
let warnings: [LyrebirdMessage] = LyrebirdMessageCenter.shared.messages.filter {
$0.tier == .warning
}
#expect(!warnings.isEmpty, "Expected a diagnostic warning for orphan glissando-stop")
#expect(warnings.contains { $0.text.contains("glissando") })
}
@Test func startWithNoStopDroppedAndDiagnosticPosted() async {
LyrebirdMessageCenter.shared.clear()
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 5, dur: .quarter, spanners: [.beginGlissando(Glissando())])
// No endGlissando — orphan start.
Note(.e, 5, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
// The orphan start must be dropped.
#expect(!xml.contains("<glissando type=\"start\""))
// Poll until the async diagnostic Task fires.
let maxPolls: Int = 50
var pollCount: Int = 0
while pollCount < maxPolls {
await Task.yield()
let warnings: [LyrebirdMessage] = LyrebirdMessageCenter.shared.messages.filter {
$0.tier == .warning
}
if !warnings.isEmpty { break }
pollCount += 1
}
let warnings: [LyrebirdMessage] = LyrebirdMessageCenter.shared.messages.filter {
$0.tier == .warning
}
#expect(!warnings.isEmpty, "Expected a diagnostic warning for orphan glissando-start")
#expect(warnings.contains { $0.text.contains("glissando") })
}
// MARK: - Composition with slur
@Test func glissandoComposesWithSlurOnSameNotes() {
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 5, dur: .quarter,
spanners: [.beginGlissando(Glissando()), .beginSlur])
Note(.e, 5, dur: .quarter,
spanners: [.endGlissando, .endSlur])
}
}
let xml: String = score.toMusicXMLString()
// Both slur and glissando start must be present.
#expect(xml.contains("<slur number=\"1\" type=\"start\"/>"))
#expect(xml.contains("<glissando type=\"start\" line-type=\"wavy\" number=\"1\"/>"))
// Both slur and glissando stop must be present.
#expect(xml.contains("<slur number=\"1\" type=\"stop\"/>"))
#expect(xml.contains("<glissando type=\"stop\" number=\"1\"/>"))
}
// MARK: - flatten unaffected
@Test func glissandoDoesNotAffectFlatten() {
// flatten() produces the same ScoreEvent list regardless of glissando spans
// (glissando is notation-only — no effect on beat positions or durations).
let partWithGlissando: ScorePart = Part("p") {
Note(.c, 5, dur: .quarter, spanners: [.beginGlissando(Glissando())])
Note(.e, 5, dur: .quarter, spanners: [.endGlissando])
}
let partPlain: ScorePart = Part("p") {
Note(.c, 5, dur: .quarter)
Note(.e, 5, dur: .quarter)
}
let eventsWithGlissando: [ScoreEvent] = partWithGlissando.flatten()
let eventsPlain: [ScoreEvent] = partPlain.flatten()
#expect(eventsWithGlissando.count == eventsPlain.count)
for (a, b): (ScoreEvent, ScoreEvent) in zip(eventsWithGlissando, eventsPlain) {
#expect(a.beat == b.beat)
#expect(a.duration == b.duration)
}
}
// MARK: - GlissandoKind
@Test func glissandoKindMusicXMLElementNames() {
#expect(GlissandoKind.glissando.musicXMLElementName == "glissando")
#expect(GlissandoKind.slide.musicXMLElementName == "slide")
}
// MARK: - GlissandoLineType
@Test func glissandoLineTypeMusicXMLValues() {
#expect(GlissandoLineType.solid.musicXMLValue == "solid")
#expect(GlissandoLineType.dashed.musicXMLValue == "dashed")
#expect(GlissandoLineType.dotted.musicXMLValue == "dotted")
#expect(GlissandoLineType.wavy.musicXMLValue == "wavy")
}
// MARK: - Glissando defaults
@Test func glissandoDefaultValues() {
let g: Glissando = Glissando()
#expect(g.kind == .glissando)
#expect(g.lineType == .wavy)
#expect(g.text == nil)
}
// MARK: - Multiple glissandos in sequence
@Test func multipleGlissandosInSequenceEmitCorrectly() {
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 5, dur: .quarter, spanners: [.beginGlissando(Glissando())])
Note(.e, 5, dur: .quarter, spanners: [.endGlissando])
// Second glissando span
Note(.g, 5, dur: .quarter, spanners: [.beginGlissando(Glissando(kind: .slide))])
Note(.b, 5, dur: .quarter, spanners: [.endGlissando])
}
}
let xml: String = score.toMusicXMLString()
// Two glissando starts: one wavy, one slide.
let glissandoStarts: Int = xml.components(separatedBy: "type=\"start\"").count - 1
// There should be 2 starts (one glissando, one slide).
#expect(glissandoStarts >= 2)
// First glissando stop uses <glissando>, second uses <slide>.
#expect(xml.contains("<glissando type=\"stop\" number=\"1\"/>"))
#expect(xml.contains("<slide type=\"stop\" number=\"1\"/>"))
}
@Test func glissandoStopSurvivesMultiVoiceBarlineSplit() {
// The stop note crosses a barline on the multi-voice encoder path, which
// reconstructs a leftover continuation atom. That reconstruction must
// carry the glissando-stop forward (regression: it previously reset to
// default, dropping the <glissando type="stop"/>).
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Voice(1) {
Note(.c, 5, dur: .quarter, spanners: [.beginGlissando(Glissando())])
// Stop note is a whole note starting on beat 2 → crosses the
// barline (splits at the bar end).
Note(.g, 5, dur: .whole, spanners: [.endGlissando])
}
Voice(2) {
Note(.c, 4, dur: .whole)
Note(.c, 4, dur: .whole)
}
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<glissando type=\"start\""))
#expect(xml.contains("<glissando type=\"stop\" number=\"1\"/>"),
"glissando stop must survive the multi-voice barline split")
}
@Test func singleAtomGlissandoDoesNotBreakNextSpanInVoice() {
// A degenerate single-note glissando (begin+end on one note) must clear
// the per-voice opener so a following real glissando span is not
// mis-flagged as a double-open and dropped.
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 5, dur: .quarter, spanners: [.beginGlissando(Glissando()), .endGlissando])
Note(.e, 5, dur: .quarter, spanners: [.beginGlissando(Glissando(kind: .slide))])
Note(.g, 5, dur: .quarter, spanners: [.endGlissando])
}
}
let xml: String = score.toMusicXMLString()
// The second (real, two-note) slide span must emit its start+stop.
#expect(xml.contains("<slide type=\"start\""),
"the span after a single-atom glissando must still open")
#expect(xml.contains("<slide type=\"stop\" number=\"1\"/>"),
"the span after a single-atom glissando must still close")
}
}
+116
View File
@@ -0,0 +1,116 @@
// IntervalTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@Suite("Interval — spelled diatonic intervals, semitone sizes, validity, analysis")
struct IntervalTests {
// MARK: - Semitone sizes from the catalogue
@Test func catalogueSemitones() {
#expect(Interval.unison.semitones == 0)
#expect(Interval.minorSecond.semitones == 1)
#expect(Interval.majorSecond.semitones == 2)
#expect(Interval.augmentedSecond.semitones == 3)
#expect(Interval.minorThird.semitones == 3)
#expect(Interval.majorThird.semitones == 4)
#expect(Interval.perfectFourth.semitones == 5)
#expect(Interval.augmentedFourth.semitones == 6)
#expect(Interval.diminishedFifth.semitones == 6)
#expect(Interval.perfectFifth.semitones == 7)
#expect(Interval.minorSixth.semitones == 8)
#expect(Interval.majorSixth.semitones == 9)
#expect(Interval.minorSeventh.semitones == 10)
#expect(Interval.majorSeventh.semitones == 11)
#expect(Interval.octave.semitones == 12)
}
@Test func diatonicSteps() {
#expect(Interval.unison.diatonicSteps == 0)
#expect(Interval.majorThird.diatonicSteps == 2)
#expect(Interval.perfectFifth.diatonicSteps == 4)
#expect(Interval.octave.diatonicSteps == 7)
}
// MARK: - Compound intervals
@Test func compoundNinth() throws {
let majorNinth: Interval = try Interval(number: 9, quality: .major)
#expect(majorNinth.semitones == 14)
#expect(majorNinth.diatonicSteps == 8)
}
@Test func compoundEleventh() throws {
let perfectEleventh: Interval = try Interval(number: 11, quality: .perfect)
#expect(perfectEleventh.semitones == 17)
}
// MARK: - Doubly augmented / diminished
@Test func doublyAugmentedAndDiminished() throws {
let doublyAugFourth: Interval = try Interval(number: 4, quality: .augmented(2))
#expect(doublyAugFourth.semitones == 7)
let doublyDimFifth: Interval = try Interval(number: 5, quality: .diminished(2))
#expect(doublyDimFifth.semitones == 5)
let diminishedSeventh: Interval = try Interval(number: 7, quality: .diminished(1))
#expect(diminishedSeventh.semitones == 9)
}
// MARK: - Validity rules
@Test func perfectClassRejectsMajorMinor() {
#expect(throws: IntervalError.self) {
_ = try Interval(number: 5, quality: .major)
}
#expect(throws: IntervalError.self) {
_ = try Interval(number: 4, quality: .minor)
}
}
@Test func imperfectClassRejectsPerfect() {
#expect(throws: IntervalError.self) {
_ = try Interval(number: 3, quality: .perfect)
}
#expect(throws: IntervalError.self) {
_ = try Interval(number: 6, quality: .perfect)
}
}
@Test func invalidNumberAndDegree() {
#expect(throws: IntervalError.self) {
_ = try Interval(number: 0, quality: .perfect)
}
#expect(throws: IntervalError.self) {
_ = try Interval(number: 3, quality: .augmented(0))
}
}
@Test func augmentedDiminishedAllowedOnAnyClass() throws {
_ = try Interval(number: 5, quality: .augmented(1)) // aug 5th
_ = try Interval(number: 2, quality: .diminished(1)) // dim 2nd
_ = try Interval(number: 1, quality: .augmented(1)) // aug unison
}
// MARK: - Interval analysis between two names
@Test func betweenAscending() throws {
#expect(try Interval.between(.c, .e) == Interval.majorThird)
#expect(try Interval.between(.c, .eFlat) == Interval.minorThird)
#expect(try Interval.between(.c, .g) == Interval.perfectFifth)
#expect(try Interval.between(.a, .bSharp) == Interval.augmentedSecond)
#expect(try Interval.between(.c, .c) == Interval.unison)
#expect(try Interval.between(.b, .f) == Interval.diminishedFifth)
}
@Test func betweenRejectsQuarterTone() {
#expect(throws: IntervalError.self) {
_ = try Interval.between(.cQuarterSharp, .e)
}
}
}
+103
View File
@@ -0,0 +1,103 @@
// MeterMapTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("MeterMap — segments, lookup, anacrusis; Score/Part wiring")
struct MeterMapTests {
// MARK: - Construction
@Test func constantConvenienceIsSingleSegment() {
let map: MeterMap = MeterMap(.fourFour)
#expect(map.isConstant)
#expect(map.segments.count == 1)
#expect(map.initial.tuple == (4, 4))
#expect(map.anacrusis == Fraction.zero)
}
@Test func segmentsSortedByStartBar() {
let map: MeterMap = MeterMap(segments: [
MeterMap.Segment(startBar: 5, .threeFour),
MeterMap.Segment(startBar: 1, .fourFour),
])
#expect(map.segments.map { $0.startBar } == [1, 5])
#expect(map.initial.tuple == (4, 4))
#expect(map.isConstant == false)
}
// MARK: - Lookup
@Test func timeSignatureAtBarPicksLastSegmentAtOrBeforeBar() {
let map: MeterMap = MeterMap(segments: [
MeterMap.Segment(startBar: 1, .fourFour),
MeterMap.Segment(startBar: 5, .threeFour),
MeterMap.Segment(startBar: 9, .sixEightCompound),
])
#expect(map.timeSignature(atBar: 1).tuple == (4, 4))
#expect(map.timeSignature(atBar: 4).tuple == (4, 4))
#expect(map.timeSignature(atBar: 5).tuple == (3, 4))
#expect(map.timeSignature(atBar: 8).tuple == (3, 4))
#expect(map.timeSignature(atBar: 9).tuple == (6, 8))
#expect(map.timeSignature(atBar: 100).tuple == (6, 8))
// Pickup (bar 0) → initial.
#expect(map.timeSignature(atBar: 0).tuple == (4, 4))
}
// MARK: - Anacrusis
@Test func anacrusisStored() {
let map: MeterMap = MeterMap(.fourFour, anacrusis: Fraction(1, 1))
#expect(map.anacrusis == Fraction(1, 1))
}
// MARK: - Score wiring
@Test func scoreDefaultsMeterMapFromTimeSignature() {
let score: Score = Score(timeSignature: TimeSignature(3, 4)) { Part("p") { Note(.c, 4, dur: .quarter) } }
#expect(score.meterMap.isConstant)
#expect(score.meterMap.initial.tuple == (3, 4))
#expect(score.timeSignature.tuple == (3, 4))
}
@Test func scoreTimeSignatureIsTypedAndEqualsMeterMapInitial() {
// timeSignature is now a TimeSignature (not a tuple): it equals the
// meterMap's bar-1 signature and supports Equatable / Hashable.
let score: Score = Score(timeSignature: TimeSignature(6, 8)) { Part("p") { Note(.c, 4, dur: .quarter) } }
#expect(score.timeSignature == score.meterMap.initial)
#expect(score.timeSignature == TimeSignature(6, 8))
let seen: Set<TimeSignature> = [score.timeSignature]
#expect(seen.contains(TimeSignature(6, 8)))
}
@Test func scoreExplicitMeterMapDrivesTimeSignatureTuple() {
let map: MeterMap = MeterMap(segments: [
MeterMap.Segment(startBar: 1, .sixEightCompound),
MeterMap.Segment(startBar: 3, .threeFour),
])
let score: Score = Score(meterMap: map) { Part("p") { Note(.c, 4, dur: .quarter) } }
// Back-compat tuple mirrors the bar-1 signature.
#expect(score.timeSignature.tuple == (6, 8))
#expect(score.meterMap.segments.count == 2)
}
@Test func partMeterMapDefaultsNilAndOverrides() {
let plain: ScorePart = Part("a") { Note(.c, 4, dur: .quarter) }
#expect(plain.meterMap == nil)
let poly: ScorePart = Part("b", meterMap: MeterMap(.sevenEightAdditive)) {
Note(.c, 4, dur: .quarter)
}
#expect(poly.meterMap?.initial.beatGrouping == [3, 2, 2])
}
}
// Local convenience used only by the test above.
extension TimeSignature {
static let sevenEightAdditive: TimeSignature = TimeSignature(7, 8, grouping: [3, 2, 2])
}
@@ -8,10 +8,10 @@ import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
/// Phase 196.6 — Multi-engine regression coverage.
/// Multi-engine regression coverage.
///
/// Validates the Phase 196 ownership-binding + lifecycle-coordinator
/// machinery against the two scenarios that motivated the phase:
/// Validates the ownership-binding + lifecycle-coordinator
/// machinery against the two scenarios that motivated it:
///
/// 1. **Two engines, two threads, disjoint Synth graphs** — drives both
/// engines for ≥ 1000 segments each in parallel. Acts as a
@@ -26,7 +26,7 @@ import Foundation
/// same-engine re-add without intervening `remove`, and accepts
/// re-add after `remove` clears the binding.
@MainActor
@Suite("Multi-engine regression (Phase 196.6)")
@Suite("Multi-engine regression")
struct MultiEngineRegressionTests {
// MARK: - Two-engine, two-thread driver
@@ -36,7 +36,7 @@ struct MultiEngineRegressionTests {
/// iterations. Joins both threads, stops both engines, and asserts
/// neither crashed nor produced obvious miscount.
///
/// `segmentCount = 1000` matches the Phase 196 plan exit criterion.
/// `segmentCount = 1000` matches the plan exit criterion.
/// Adjust upward for stress runs; downward to keep CI fast.
@Test func twoEnginesTwoThreadsDisjointGraphs() throws {
let segmentCount: Int = 1000
@@ -112,7 +112,7 @@ struct MultiEngineRegressionTests {
engineB.stop()
}
/// Phase 197.7 uniformity-contract regression — same two-engine
/// Uniformity-contract regression — same two-engine
/// two-thread workload as `twoEnginesTwoThreadsDisjointGraphs`, but
/// engines are constructed via `EngineHost.makeEngine` +
/// `host.startAll()` instead of direct-ctor. Verifies that the
@@ -272,7 +272,7 @@ struct MultiEngineRegressionTests {
// MARK: - LyrebirdBuffer read-only sharing
/// `bindReadOnly` allows the same buffer to be shared across multiple
/// engines concurrently. Phase 196.1 part-2 opt-in API.
/// engines concurrently. Opt-in API.
@Test func bufferReadOnlyShareAcrossEngines() throws {
let engineA: SynthesisEngine = makeTestEngine()
let engineB: SynthesisEngine = makeTestEngine()
@@ -296,7 +296,7 @@ struct MultiEngineRegressionTests {
buf.unbindReadOnly(from: engineB)
}
/// Phase 196 review fix #8: stale-pointer recovery in `_bind`.
/// Stale-pointer recovery in `_bind`.
///
/// If an engine deinits without unbinding a synth it owns, the raw
/// pointer in `_engineBinding` is dangling. The recovery path in
@@ -319,8 +319,7 @@ struct MultiEngineRegressionTests {
/// rather than stale-pointer recovery. Fixing this requires
/// replacing the raw-pointer-in-atomic with a coordinator-issued
/// monotonic UInt64 registration token (or stamping a generation
/// counter alongside the pointer). Tracked as a future improvement
/// — out of scope for Phase 196.
/// counter alongside the pointer). Tracked as a future improvement.
@Test func bindRecoversFromStaleEnginePointer() throws {
let synth: ConstantSynth = ConstantSynth(value: 0.1, outputBus: 0)
@@ -365,7 +364,7 @@ struct MultiEngineRegressionTests {
engineB.stop()
}
/// Phase 196 re-review fix: `unbindReadOnly` saturates at zero rather
/// `unbindReadOnly` saturates at zero rather
/// than wrapping to `Int.max` under unbalanced misuse. Without
/// saturation, an unbalanced unbind would permanently block any
/// subsequent `bindExclusive` because the refcount check in
@@ -0,0 +1,386 @@
// MusicXMLAnacrusisTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
/// Anacrusis (pickup measure) encoding + parser round-trip.
///
/// Constraint: scores with no anacrusis (`meterMap.anacrusis == .zero`) must
/// produce byte-identical output to the pre-anacrusis implementation.
@MainActor
@Suite("MusicXML — anacrusis (pickup measure) notation")
struct MusicXMLAnacrusisTests {
// MARK: - Part A: Encoder
/// A score with a one-quarter pickup emits `<measure number="0" implicit="yes">`
/// as its first measure.
@Test func pickupMeasureIsEmittedImplicit() {
let score: Score = Score(
bpm: 120,
meterMap: MeterMap(.fourFour, anacrusis: Fraction(1, 1))
) {
Part("Violin") {
Note(.c, 5, dur: .quarter)
Note(.d, 5, dur: .quarter)
Note(.e, 5, dur: .quarter)
Note(.f, 5, dur: .quarter)
Note(.g, 5, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
// Pickup measure must be number 0 with implicit="yes".
#expect(
xml.contains("<measure number=\"0\" implicit=\"yes\">"),
"encoder must emit <measure number=\"0\" implicit=\"yes\"> for the pickup"
)
}
/// The pickup measure's `<attributes>` block carries the initial time signature
/// (i.e. the 4/4 from bar 1, since the pickup uses the initial signature).
@Test func pickupMeasureCarriesInitialTimeSignature() {
let score: Score = Score(
bpm: 120,
meterMap: MeterMap(.fourFour, anacrusis: Fraction(1, 1))
) {
Part("p") {
// quarter pickup
Note(.c, 5, dur: .quarter)
// full 4/4 bar
Note(.d, 5, dur: .quarter)
Note(.e, 5, dur: .quarter)
Note(.f, 5, dur: .quarter)
Note(.g, 5, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
// The initial <time> must appear inside the pickup (the first <attributes> block).
// The pickup is the first measure so the attributes block is the first one emitted.
#expect(
xml.contains("<beats>4</beats>"),
"pickup measure's <attributes> must contain <beats>4</beats>"
)
#expect(
xml.contains("<beat-type>4</beat-type>"),
"pickup measure's <attributes> must contain <beat-type>4</beat-type>"
)
}
/// After the pickup, the first FULL bar is `<measure number="1">` (not 0, not 2).
@Test func firstFullBarIsNumberOne() {
let score: Score = Score(
bpm: 120,
meterMap: MeterMap(.fourFour, anacrusis: Fraction(1, 1))
) {
Part("p") {
// quarter pickup
Note(.c, 5, dur: .quarter)
// full 4/4 bar
Note(.d, 5, dur: .quarter)
Note(.e, 5, dur: .quarter)
Note(.f, 5, dur: .quarter)
Note(.g, 5, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
#expect(
xml.contains("<measure number=\"1\">"),
"the first full bar must be <measure number=\"1\">"
)
// The full bar must NOT be tagged implicit="yes".
// Check that there is no implicit="yes" on number="1".
#expect(
!xml.contains("<measure number=\"1\" implicit=\"yes\">"),
"the first full bar must NOT carry implicit=\"yes\""
)
}
/// The pickup measure contains exactly one quarter note (the pickup content),
/// and the first full bar contains four quarter notes.
@Test func pickupContainsOneNoteFullBarContainsFour() {
let score: Score = Score(
bpm: 120,
meterMap: MeterMap(.fourFour, anacrusis: Fraction(1, 1))
) {
Part("p") {
// quarter pickup: G5
Note(.g, 5, dur: .quarter)
// full 4/4 bar: C D E F
Note(.c, 5, dur: .quarter)
Note(.d, 5, dur: .quarter)
Note(.e, 5, dur: .quarter)
Note(.f, 5, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
// Locate the pickup measure block and verify it contains exactly one <note>.
// A simple containment check: the pickup block ends before <measure number="1">.
guard let pickupStart: String.Index = xml.range(
of: "<measure number=\"0\" implicit=\"yes\">"
)?.lowerBound else {
Issue.record("Pickup measure not found in XML output")
return
}
guard let bar1Start: String.Index = xml.range(
of: "<measure number=\"1\">"
)?.lowerBound else {
Issue.record("<measure number=\"1\"> not found in XML output")
return
}
let pickupBlock: String = String(xml[pickupStart..<bar1Start])
// Count <note> elements in the pickup block.
let noteTagCount: Int = pickupBlock.components(separatedBy: "<note>").count - 1
#expect(noteTagCount == 1, "pickup measure must contain exactly 1 <note>")
// The pickup note should be G5.
#expect(pickupBlock.contains("<step>G</step>"), "pickup note must be G")
#expect(pickupBlock.contains("<octave>5</octave>"), "pickup note must be octave 5")
}
// MARK: - Part B: Parser round-trip
/// A score with a one-quarter 4/4 anacrusis round-trips through MusicXML and
/// the parsed `meterMap.anacrusis` equals the original.
@Test func roundTripAnacrusis() throws {
let original: Score = Score(
bpm: 120,
meterMap: MeterMap(.fourFour, anacrusis: Fraction(1, 1))
) {
Part("p") {
// quarter pickup
Note(.c, 5, dur: .quarter)
// two full 4/4 bars
Note(.d, 5, dur: .quarter)
Note(.e, 5, dur: .quarter)
Note(.f, 5, dur: .quarter)
Note(.g, 5, dur: .quarter)
Note(.a, 5, dur: .quarter)
Note(.b, 5, dur: .quarter)
Note(.c, 6, dur: .quarter)
Note(.d, 6, dur: .quarter)
}
}
let data: Data = original.toMusicXMLData()
let parsed: Score = try Score.fromMusicXML(data: data)
#expect(
parsed.meterMap.anacrusis == Fraction(1, 1),
"round-trip must preserve anacrusis == Fraction(1,1)"
)
}
/// After round-trip the full-bar meter is preserved.
@Test func roundTripFullBarMeterPreserved() throws {
let original: Score = Score(
bpm: 120,
meterMap: MeterMap(.fourFour, anacrusis: Fraction(1, 1))
) {
Part("p") {
Note(.c, 5, dur: .quarter)
Note(.d, 5, dur: .quarter)
Note(.e, 5, dur: .quarter)
Note(.f, 5, dur: .quarter)
Note(.g, 5, dur: .quarter)
}
}
let data: Data = original.toMusicXMLData()
let parsed: Score = try Score.fromMusicXML(data: data)
#expect(
parsed.meterMap.initial.tuple == (4, 4),
"round-trip must preserve 4/4 time signature for full bars"
)
}
// MARK: - No-anacrusis byte-identity
/// A score without an anacrusis must produce output that does NOT contain
/// `implicit="yes"`, confirming byte-identical structure to the no-anacrusis baseline.
@Test func noAnacrusisOutputContainsNoImplicit() {
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.c, 4, dur: .quarter)
Note(.d, 4, dur: .quarter)
Note(.e, 4, dur: .quarter)
Note(.f, 4, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
#expect(
!xml.contains("implicit=\"yes\""),
"a no-anacrusis score must not emit implicit=\"yes\" anywhere"
)
#expect(
xml.contains("<measure number=\"1\">"),
"a no-anacrusis score must start with <measure number=\"1\">"
)
#expect(
!xml.contains("<measure number=\"0\""),
"a no-anacrusis score must not emit measure number 0"
)
}
/// A no-anacrusis score's XML is byte-identical to the reference encoder output
/// (no pickup support). We verify structural markers and the absence of
/// pickup-specific markup.
@Test func noAnacrusisRoundTripIsClean() throws {
let original: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("Piano") {
Note(.c, 4, dur: .quarter)
Note(.d, 4, dur: .quarter)
Note(.e, 4, dur: .quarter)
Note(.f, 4, dur: .quarter)
}
}
let data: Data = original.toMusicXMLData()
let parsed: Score = try Score.fromMusicXML(data: data)
#expect(
parsed.meterMap.anacrusis == .zero,
"no-anacrusis score must round-trip with anacrusis == .zero"
)
#expect(
parsed.meterMap.isConstant,
"no-anacrusis score must round-trip with isConstant == true"
)
#expect(
parsed.meterMap.initial.tuple == (4, 4),
"no-anacrusis score must round-trip with (4,4) initial signature"
)
}
// MARK: - Anacrusis + mid-piece meter change
/// A score with an anacrusis AND a mid-piece meter change round-trips with
/// both the anacrusis and all meter segments preserved.
@Test func anacrusissPlusMeterChangeRoundTrip() throws {
let meterMap: MeterMap = MeterMap(
segments: [
MeterMap.Segment(startBar: 1, .fourFour),
MeterMap.Segment(startBar: 3, .threeFour)
],
anacrusis: Fraction(1, 1)
)
let original: Score = Score(bpm: 120, meterMap: meterMap) {
Part("p") {
// one-quarter pickup
Note(.c, 5, dur: .quarter)
// bar 1 (4/4): 4 quarters
Note(.d, 5, dur: .quarter)
Note(.e, 5, dur: .quarter)
Note(.f, 5, dur: .quarter)
Note(.g, 5, dur: .quarter)
// bar 2 (4/4): 4 quarters
Note(.a, 5, dur: .quarter)
Note(.b, 5, dur: .quarter)
Note(.c, 6, dur: .quarter)
Note(.d, 6, dur: .quarter)
// bar 3 (3/4): 3 quarters
Note(.e, 6, dur: .quarter)
Note(.f, 6, dur: .quarter)
Note(.g, 6, dur: .quarter)
}
}
let data: Data = original.toMusicXMLData()
let parsed: Score = try Score.fromMusicXML(data: data)
#expect(
parsed.meterMap.anacrusis == Fraction(1, 1),
"anacrusis must survive round-trip when combined with mid-piece meter change"
)
#expect(
parsed.meterMap.timeSignature(atBar: 1).tuple == (4, 4),
"bar-1 signature must be 4/4 after round-trip"
)
#expect(
parsed.meterMap.timeSignature(atBar: 3).tuple == (3, 4),
"bar-3 signature must be 3/4 after round-trip"
)
}
// MARK: - Half-bar anacrusis
/// A half-bar (two-quarter) pickup in a 4/4 score round-trips with the
/// correct anacrusis duration.
@Test func halfBarAnacrusissRoundTrip() throws {
let original: Score = Score(
bpm: 96,
meterMap: MeterMap(.fourFour, anacrusis: Fraction(2, 1))
) {
Part("p") {
// two-quarter pickup
Note(.c, 5, dur: .quarter)
Note(.d, 5, dur: .quarter)
// full 4/4 bar
Note(.e, 5, dur: .quarter)
Note(.f, 5, dur: .quarter)
Note(.g, 5, dur: .quarter)
Note(.a, 5, dur: .quarter)
}
}
let data: Data = original.toMusicXMLData()
let xml: String = String(data: data, encoding: .utf8) ?? ""
let parsed: Score = try Score.fromMusicXML(data: data)
#expect(
xml.contains("<measure number=\"0\" implicit=\"yes\">"),
"half-bar pickup must emit measure 0 with implicit=\"yes\""
)
#expect(
parsed.meterMap.anacrusis == Fraction(2, 1),
"half-bar pickup anacrusis must round-trip as Fraction(2,1)"
)
}
/// Beam grouping must account the pickup against the pickup window (not the
/// full first-bar window), so the FULL bar after a pickup is beat-aligned
/// from beat 0. A 1-quarter pickup + a full 4/4 bar of eighths beams as four
/// pairs (4 `begin`s). Without the pickup-aware beam accounting the bar-1
/// eighths would be shifted by the pickup duration and mis-grouped.
@Test func pickupBeamingIsBeatAlignedInFullBar() {
let score: Score = Score(
bpm: 120,
meterMap: MeterMap(.fourFour, anacrusis: Fraction(1, 1))
) {
Part("flute") {
Note(.c, 5, dur: .quarter) // pickup (1 quarter)
// Full bar 1: eight eighths → four beamed pairs.
Note(.d, 5, dur: .eighth)
Note(.e, 5, dur: .eighth)
Note(.f, 5, dur: .eighth)
Note(.g, 5, dur: .eighth)
Note(.a, 5, dur: .eighth)
Note(.b, 5, dur: .eighth)
Note(.c, 6, dur: .eighth)
Note(.d, 6, dur: .eighth)
}
}
let xml: String = score.toMusicXMLString()
let beginCount: Int = xml.components(separatedBy: "<beam number=\"1\">begin</beam>").count - 1
#expect(
beginCount == 4,
"expected 4 beam pairs (beat-aligned) in the full bar after the pickup, got \(beginCount)"
)
}
}
@@ -0,0 +1,121 @@
// MusicXMLDynamicCollapseTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable import LyrebirdSynth
@MainActor
@Suite("MusicXML redundant-dynamic collapse in multi-voice parts")
struct MusicXMLDynamicCollapseTests {
/// Count non-overlapping occurrences of `needle` in `haystack`.
private func countOccurrences(of needle: String, in haystack: String) -> Int {
haystack.components(separatedBy: needle).count - 1
}
@Test("Identical dynamics across voices on one staff collapse to a single direction")
func identicalDynamicsOnOneStaffCollapse() {
let score: Score = Score(bpm: 120) {
Part("piano", clef: .treble) {
Voice(1) { Note(.named(.c, 5), dur: .whole, dyn: .mp) }
Voice(2) { Note(.named(.c, 4), dur: .whole, dyn: .mp) }
}
}
// Default (collapse on): both voices open mp at beat 0 → one <mp/>.
let collapsed: String = score.toMusicXMLString()
#expect(countOccurrences(of: "<mp/>", in: collapsed) == 1)
// Disabled: raw one-direction-per-voice → two <mp/>.
let raw: String = score.toMusicXMLString(collapseRedundantDynamics: false)
#expect(countOccurrences(of: "<mp/>", in: raw) == 2)
}
@Test("Each staff of a grand staff keeps its own dynamic")
func grandStaffCollapsesPerStaff() {
let score: Score = Score(bpm: 120) {
Part("piano", clef: .treble) {
Staff(1) {
Voice(1) { Note(.named(.c, 5), dur: .whole, dyn: .mp) }
Voice(2) { Note(.named(.e, 4), dur: .whole, dyn: .mp) }
}
Staff(2, clef: .bass) {
Voice(3) { Note(.named(.c, 3), dur: .whole, dyn: .mp) }
}
}
}
// Per-staff collapse: staff 1 merges V1+V2 (one mp), staff 2 keeps its own
// (one mp) → two total, not three.
let collapsed: String = score.toMusicXMLString()
#expect(countOccurrences(of: "<mp/>", in: collapsed) == 2)
// Disabled → one per voice → three.
let raw: String = score.toMusicXMLString(collapseRedundantDynamics: false)
#expect(countOccurrences(of: "<mp/>", in: raw) == 3)
}
@Test("Different dynamics at the same onset on one staff are both emitted")
func differentDynamicsPreserved() {
let score: Score = Score(bpm: 120) {
Part("piano", clef: .treble) {
Voice(1) { Note(.named(.c, 5), dur: .whole, dyn: .f) }
Voice(2) { Note(.named(.c, 4), dur: .whole, dyn: .p) }
}
}
// Collapse only merges *identical* dynamics; f and p both survive.
let collapsed: String = score.toMusicXMLString()
#expect(countOccurrences(of: "<f/>", in: collapsed) == 1)
#expect(countOccurrences(of: "<p/>", in: collapsed) == 1)
}
@Test("Collapse record resets each measure so a recurring dynamic re-emits")
func collapseRecordResetsPerMeasure() {
// Two voices, three bars each: mp, f, mp. The bar-3 mp recurs at the same
// onset as the bar-1 mp; a measure-scoped dedup record must re-emit it
// (a stale record would wrongly suppress it).
let score: Score = Score(bpm: 120) {
Part("piano", clef: .treble) {
Voice(1) {
Note(.named(.c, 5), dur: .whole, dyn: .mp)
Note(.named(.c, 5), dur: .whole, dyn: .f)
Note(.named(.c, 5), dur: .whole, dyn: .mp)
}
Voice(2) {
Note(.named(.c, 4), dur: .whole, dyn: .mp)
Note(.named(.c, 4), dur: .whole, dyn: .f)
Note(.named(.c, 4), dur: .whole, dyn: .mp)
}
}
}
let collapsed: String = score.toMusicXMLString()
// Bar 1 mp (collapsed to 1) + bar 3 mp (collapsed to 1) = 2; bar 2 f = 1.
#expect(countOccurrences(of: "<mp/>", in: collapsed) == 2)
#expect(countOccurrences(of: "<f/>", in: collapsed) == 1)
}
@Test("Collapse applies on the barline-split emit path at a non-zero onset")
func collapseAppliesOnBarlineSplitPath() {
// Each voice rests a half then holds a whole note that STARTS at beat 2
// and crosses into the next bar — driving the encoder's barline-split
// emit site at onset 2.0 (not 0). The dynamic is emitted only before the
// head piece (the tied continuation is suppressed), so the two voices'
// identical mp at onset 2.0 must collapse to one.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("piano", clef: .treble) {
Voice(1) {
Rest(dur: .half)
Note(.named(.c, 5), dur: .whole, dyn: .mp)
}
Voice(2) {
Rest(dur: .half)
Note(.named(.c, 4), dur: .whole, dyn: .mp)
}
}
}
let collapsed: String = score.toMusicXMLString()
#expect(countOccurrences(of: "<mp/>", in: collapsed) == 1)
let raw: String = score.toMusicXMLString(collapseRedundantDynamics: false)
#expect(countOccurrences(of: "<mp/>", in: raw) == 2)
}
}
@@ -0,0 +1,334 @@
// MusicXMLMeterChangeTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("MusicXML encoder — mid-piece meter-change notation")
struct MusicXMLMeterChangeTests {
// MARK: - Constant-meter guard: output must remain byte-identical
/// A constant-meter score (single-segment meterMap) must produce the same
/// output whether it is built with the `timeSignature:` parameter or an
/// explicit `meterMap:` wrapping the same signature.
@Test func constantMeterOutputIsUnchangedByExplicitMeterMap() {
// Build via the timeSignature: parameter.
let scoreTuple: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.c, 4, dur: .quarter)
Note(.d, 4, dur: .quarter)
Note(.e, 4, dur: .quarter)
Note(.f, 4, dur: .quarter)
}
}
// Build via explicit single-segment meterMap.
let scoreMeter: Score = Score(
bpm: 120,
meterMap: MeterMap(.fourFour)
) {
Part("p") {
Note(.c, 4, dur: .quarter)
Note(.d, 4, dur: .quarter)
Note(.e, 4, dur: .quarter)
Note(.f, 4, dur: .quarter)
}
}
let xmlTuple: String = scoreTuple.toMusicXMLString()
let xmlMeter: String = scoreMeter.toMusicXMLString()
#expect(xmlTuple == xmlMeter, "Constant-meter output must be byte-identical via both paths")
}
// MARK: - Measure-1 time signature
/// A score with meterMap starting 4/4 emits `<beats>4</beats><beat-type>4</beat-type>`
/// inside `<measure number="1">`.
@Test func meterChangeBarOneEmitsFourFour() {
let score: Score = Score(
bpm: 120,
meterMap: MeterMap(segments: [
MeterMap.Segment(startBar: 1, .fourFour),
MeterMap.Segment(startBar: 3, .threeFour)
])
) {
Part("p") {
// 4 quarters × 2 bars = bar 1–2 in 4/4, then bar 3 in 3/4.
Note(.c, 4, dur: .quarter)
Note(.d, 4, dur: .quarter)
Note(.e, 4, dur: .quarter)
Note(.f, 4, dur: .quarter)
// bar 2
Note(.g, 4, dur: .quarter)
Note(.a, 4, dur: .quarter)
Note(.b, 4, dur: .quarter)
Note(.c, 5, dur: .quarter)
// bar 3 (3/4)
Note(.d, 5, dur: .quarter)
Note(.e, 5, dur: .quarter)
Note(.f, 5, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
// Measure 1: 4/4 in the attributes block.
let measure1Range: Range<String.Index>? = xml.range(of: "<measure number=\"1\">")
#expect(measure1Range != nil, "measure 1 must exist")
// The measure-1 <time> block must say 4/4.
#expect(
xml.contains("<beats>4</beats>"),
"bar-1 time must emit <beats>4</beats>"
)
#expect(
xml.contains("<beat-type>4</beat-type>"),
"bar-1 time must emit <beat-type>4</beat-type>"
)
}
// MARK: - Meter change at bar 3: 4/4 → 3/4
/// Bar 3 must carry a `<time>` change block and bar 2 must NOT carry one.
@Test func meterChangeEmitsTimeAtChangeBar() {
let score: Score = Score(
bpm: 120,
meterMap: MeterMap(segments: [
MeterMap.Segment(startBar: 1, .fourFour),
MeterMap.Segment(startBar: 3, .threeFour)
])
) {
Part("p") {
// bar 1 (4/4): four quarters
Note(.c, 4, dur: .quarter)
Note(.d, 4, dur: .quarter)
Note(.e, 4, dur: .quarter)
Note(.f, 4, dur: .quarter)
// bar 2 (4/4): four quarters
Note(.g, 4, dur: .quarter)
Note(.a, 4, dur: .quarter)
Note(.b, 4, dur: .quarter)
Note(.c, 5, dur: .quarter)
// bar 3 (3/4): three quarters
Note(.d, 5, dur: .quarter)
Note(.e, 5, dur: .quarter)
Note(.f, 5, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
// Locate the three measure blocks.
let m1Start: String.Index? = xml.range(of: "<measure number=\"1\">")?.lowerBound
let m2Start: String.Index? = xml.range(of: "<measure number=\"2\">")?.lowerBound
let m3Start: String.Index? = xml.range(of: "<measure number=\"3\">")?.lowerBound
let m4Start: String.Index? = xml.range(of: "<measure number=\"4\">")?.lowerBound
#expect(m1Start != nil, "measure 1 must exist")
#expect(m2Start != nil, "measure 2 must exist")
#expect(m3Start != nil, "measure 3 must exist")
guard let m2Idx: String.Index = m2Start,
let m3Idx: String.Index = m3Start else {
return
}
// Isolate the measure-2 and measure-3 text spans.
let m3EndIdx: String.Index = m4Start ?? xml.endIndex
let measure2Text: String = String(xml[m2Idx..<m3Idx])
let measure3Text: String = String(xml[m3Idx..<m3EndIdx])
// Measure 2: must NOT carry a new <time> element (same meter as bar 1).
#expect(
!measure2Text.contains("<time>"),
"bar 2 must not emit a new <time> when meter is unchanged"
)
// Measure 3: MUST carry a <time> change for 3/4.
#expect(
measure3Text.contains("<time>"),
"bar 3 must emit a <time> block at the meter change"
)
#expect(
measure3Text.contains("<beats>3</beats>"),
"bar 3 <time> must say <beats>3</beats>"
)
#expect(
measure3Text.contains("<beat-type>4</beat-type>"),
"bar 3 <time> must say <beat-type>4</beat-type>"
)
// Measure 3 time block must be inside <attributes>, NOT carry <divisions> or <key>.
let hasTimeInAttributes: Bool = measure3Text.contains("<attributes>")
&& measure3Text.contains("<time>")
#expect(hasTimeInAttributes, "bar 3 <time> must be wrapped in <attributes>")
#expect(
!measure3Text.contains("<divisions>"),
"bar 3 meter-change <attributes> must not re-emit <divisions>"
)
#expect(
!measure3Text.contains("<key>"),
"bar 3 meter-change <attributes> must not re-emit <key>"
)
}
// MARK: - Bar capacity: bar 3 holds 3 quarters, not 4
/// After a 4/4 → 3/4 change at bar 3, a whole note written before bar 3
/// that overflows into bar 3 is split using the correct capacities:
/// the bar-2 fragment fills the 4 remaining quarters of bar 2, and the
/// bar-3 fragment uses 3 quarters (not 4) as the bar-3 capacity.
@Test func meterChangeBarCapacitySplitsNoteCorrectly() {
// Build a score where bar 2 starts at quarter 4, bar 3 at quarter 8.
// A whole note (4 quarters) beginning at the start of bar 2 will
// exactly fill bar 2. Then a dotted-half note (3 quarters) will fill bar 3.
let score: Score = Score(
bpm: 120,
meterMap: MeterMap(segments: [
MeterMap.Segment(startBar: 1, .fourFour),
MeterMap.Segment(startBar: 3, .threeFour)
])
) {
Part("p") {
// bar 1 (4/4): four quarters → 4 quarters consumed
Note(.c, 4, dur: .quarter)
Note(.d, 4, dur: .quarter)
Note(.e, 4, dur: .quarter)
Note(.f, 4, dur: .quarter)
// bar 2 (4/4): whole note → fills bar 2 exactly (4 quarters)
Note(.g, 4, dur: .whole)
// bar 3 (3/4): dotted half → fills bar 3 exactly (3 quarters)
Note(.a, 4, dur: .half.dotted)
}
}
let xml: String = score.toMusicXMLString()
// Three measures must exist.
#expect(xml.contains("<measure number=\"1\">"), "measure 1 must exist")
#expect(xml.contains("<measure number=\"2\">"), "measure 2 must exist")
#expect(xml.contains("<measure number=\"3\">"), "measure 3 must exist")
// No measure 4 — all notes fit exactly into 3 bars.
#expect(!xml.contains("<measure number=\"4\">"), "no measure 4 should be emitted")
// Locate bar 2 and bar 3 text spans for isolated inspection.
let m2Start: String.Index? = xml.range(of: "<measure number=\"2\">")?.lowerBound
let m3Start: String.Index? = xml.range(of: "<measure number=\"3\">")?.lowerBound
guard let m2Idx: String.Index = m2Start,
let m3Idx: String.Index = m3Start else {
return
}
let measure2Text: String = String(xml[m2Idx..<m3Idx])
let measure3Text: String = String(xml[m3Idx...])
// Bar 2 contains a whole note (type "whole").
#expect(measure2Text.contains("<type>whole</type>"), "bar 2 must contain the whole note")
// Bar 2 must NOT be split (only 1 note element — the whole note).
let measure2NoteCount: Int = measure2Text.components(separatedBy: "<note>").count - 1
#expect(measure2NoteCount == 1, "bar 2 should hold exactly the whole note (no split needed)")
// Bar 3 contains a dotted-half note (type "half" with one <dot/>).
#expect(measure3Text.contains("<type>half</type>"), "bar 3 must contain the dotted-half note")
#expect(measure3Text.contains("<dot/>"), "bar 3 dotted-half must carry a <dot/>")
// Bar 3 meter change <time> emits 3/4.
#expect(measure3Text.contains("<beats>3</beats>"), "bar 3 must emit 3/4 time signature")
}
// MARK: - Cross-barline tie correctly splits using different capacities
/// A note longer than a 4/4 bar that begins in bar 1 and crosses into a
/// 3/4 bar 3 (after also crossing bar 2 in 4/4) is split into three tied
/// pieces whose durations match each bar's capacity.
///
/// Score: bar 1 = 4/4, bar 3 = 3/4.
/// Place a note of 11 quarters beginning at measure 1 beat 1:
/// piece 1 → bar 1 (4 quarters), piece 2 → bar 2 (4 quarters),
/// piece 3 → bar 3 (3 quarters). Total = 11 quarters.
@Test func crossBarlineTieSplitsWithVariableCapacity() {
// 11 quarter-beats = 1 whole (4) + 1 whole (4) + 1 dottedHalf (3)
// expressed as a raw Fraction duration so it spans all three bars.
let elevenQuarters: NoteDuration = .fraction(Fraction(11, 1))
let score: Score = Score(
bpm: 120,
meterMap: MeterMap(segments: [
MeterMap.Segment(startBar: 1, .fourFour),
MeterMap.Segment(startBar: 3, .threeFour)
])
) {
Part("p") {
Note(.c, 4, dur: elevenQuarters)
}
}
let xml: String = score.toMusicXMLString()
// Three measures must be emitted.
#expect(xml.contains("<measure number=\"1\">"), "measure 1 must exist")
#expect(xml.contains("<measure number=\"2\">"), "measure 2 must exist")
#expect(xml.contains("<measure number=\"3\">"), "measure 3 must exist")
#expect(!xml.contains("<measure number=\"4\">"), "no measure 4 should be emitted")
// Exactly three <note> elements should exist (one tied piece per bar).
let noteCount: Int = xml.components(separatedBy: "<note>").count - 1
#expect(noteCount == 3, "11-quarter note crossing 4/4|4/4|3/4 barlines should split into 3 tied pieces")
// All pieces must carry tie-start or tie-stop elements (the split mechanism).
let tieStartCount: Int = xml.components(separatedBy: "<tie type=\"start\"/>").count - 1
let tieStopCount: Int = xml.components(separatedBy: "<tie type=\"stop\"/>").count - 1
#expect(tieStartCount >= 1, "tied continuation must carry at least one tie-start")
#expect(tieStopCount >= 1, "tied continuation must carry at least one tie-stop")
// Bar 3 must emit the 3/4 meter change.
let m3Start: String.Index? = xml.range(of: "<measure number=\"3\">")?.lowerBound
guard let m3Idx: String.Index = m3Start else { return }
let measure3Text: String = String(xml[m3Idx...])
#expect(
measure3Text.contains("<beats>3</beats>"),
"bar 3 must emit 3/4 time-signature change"
)
}
// MARK: - measureCount variable-capacity correctness
/// A 4/4→3/4 change at bar 3 with exactly 11 quarter-notes of content
/// should require exactly 3 bars (not the 3 bars ceiling from 4/4 alone
/// which would be ceiling(11/4) = 3 but from a different arithmetic path).
/// This test anchors the count via the total measure count in the XML.
@Test func meterChangeMeasureCountIsCorrect() {
// 4 + 4 + 3 = 11 quarters, exactly filling 3 bars.
let score: Score = Score(
bpm: 120,
meterMap: MeterMap(segments: [
MeterMap.Segment(startBar: 1, .fourFour),
MeterMap.Segment(startBar: 3, .threeFour)
])
) {
Part("p") {
// bar 1 (4/4)
Note(.c, 4, dur: .quarter)
Note(.d, 4, dur: .quarter)
Note(.e, 4, dur: .quarter)
Note(.f, 4, dur: .quarter)
// bar 2 (4/4)
Note(.g, 4, dur: .quarter)
Note(.a, 4, dur: .quarter)
Note(.b, 4, dur: .quarter)
Note(.c, 5, dur: .quarter)
// bar 3 (3/4)
Note(.d, 5, dur: .quarter)
Note(.e, 5, dur: .quarter)
Note(.f, 5, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<measure number=\"3\">"), "must emit exactly 3 measures")
#expect(!xml.contains("<measure number=\"4\">"), "must not emit a 4th measure")
}
}
@@ -0,0 +1,218 @@
// MusicXMLMeterRoundTripTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
/// MusicXML round-trip for `MeterMap` (parser reads all `<time>`
/// elements into segments; encoder emits `<time>` per segment).
///
/// Constant-meter round-trip byte-identity is the hard constraint; these tests
/// add coverage for multi-segment (mid-piece) maps.
///
/// Grouping caveat: MusicXML `<time>` carries no beat-grouping attribute, so a
/// re-parsed `TimeSignature` uses the default-grouping inference. A `6/8`
/// authored as compound `[3,3]` survives the trip faithfully; a `6/8` authored
/// as simple `[1,1,1,1,1,1]` round-trips as compound `[3,3]`. Numerator and
/// denominator are always preserved.
@MainActor
@Suite("MusicXML — MeterMap round-trip")
struct MusicXMLMeterRoundTripTests {
// MARK: - Constant-meter round-trip
/// A single-segment (constant-meter) score must parse back with
/// `meterMap.isConstant == true` and the same `(num, den)` tuple.
@Test func constantMeterRoundTrip() throws {
let original: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.c, 4, dur: .quarter)
Note(.d, 4, dur: .quarter)
Note(.e, 4, dur: .quarter)
Note(.f, 4, dur: .quarter)
}
}
let data: Data = original.toMusicXMLData()
let parsed: Score = try Score.fromMusicXML(data: data)
#expect(parsed.meterMap.isConstant,
"constant-meter score must parse back with isConstant == true")
#expect(parsed.timeSignature.tuple == (4, 4),
"constant-meter round-trip must preserve (4, 4)")
#expect(parsed.meterMap.initial.tuple == (4, 4),
"meterMap.initial must reflect (4, 4) after round-trip")
}
/// A 3/4 constant-meter score round-trips with the tuple preserved.
@Test func constantMeterThreeFourRoundTrip() throws {
let original: Score = Score(bpm: 96, timeSignature: TimeSignature(3, 4)) {
Part("p") {
Note(.c, 4, dur: .quarter)
Note(.d, 4, dur: .quarter)
Note(.e, 4, dur: .quarter)
}
}
let data: Data = original.toMusicXMLData()
let parsed: Score = try Score.fromMusicXML(data: data)
#expect(parsed.meterMap.isConstant,
"3/4 constant-meter must parse back with isConstant == true")
#expect(parsed.meterMap.initial.tuple == (3, 4),
"3/4 constant-meter must preserve tuple after round-trip")
}
// MARK: - Multi-segment (mid-piece meter change) round-trip
/// A two-segment meterMap (4/4 at bar 1, 3/4 at bar 3) round-trips
/// through MusicXML with both segments intact at the correct bar numbers,
/// and `timeSignature(atBar: 3).tuple == (3, 4)`.
@Test func twoSegmentMeterMapRoundTrip() throws {
let original: Score = Score(
bpm: 120,
meterMap: MeterMap(segments: [
MeterMap.Segment(startBar: 1, .fourFour),
MeterMap.Segment(startBar: 3, .threeFour)
])
) {
Part("p") {
// bar 1 (4/4): four quarters
Note(.c, 4, dur: .quarter)
Note(.d, 4, dur: .quarter)
Note(.e, 4, dur: .quarter)
Note(.f, 4, dur: .quarter)
// bar 2 (4/4): four quarters
Note(.g, 4, dur: .quarter)
Note(.a, 4, dur: .quarter)
Note(.b, 4, dur: .quarter)
Note(.c, 5, dur: .quarter)
// bar 3 (3/4): three quarters
Note(.d, 5, dur: .quarter)
Note(.e, 5, dur: .quarter)
Note(.f, 5, dur: .quarter)
}
}
let data: Data = original.toMusicXMLData()
let parsed: Score = try Score.fromMusicXML(data: data)
// Back-compat: timeSignature tuple reflects bar-1 (first <time> wins).
#expect(parsed.timeSignature.tuple == (4, 4),
"back-compat tuple must reflect bar-1 signature (4, 4)")
let map: MeterMap = parsed.meterMap
#expect(!map.isConstant,
"parsed meterMap must NOT be constant for a two-segment map")
let segCount: Int = map.segments.count
#expect(segCount == 2,
"parsed meterMap must have 2 segments; got \(segCount)")
// Bar-1 signature: 4/4.
let bar1TS: TimeSignature = map.timeSignature(atBar: 1)
#expect(bar1TS.tuple == (4, 4),
"bar-1 signature must be (4, 4); got \(bar1TS.tuple)")
// Bar-2 signature: still 4/4 (governed by bar-1 segment).
let bar2TS: TimeSignature = map.timeSignature(atBar: 2)
#expect(bar2TS.tuple == (4, 4),
"bar-2 signature must be (4, 4) — governed by bar-1 segment; got \(bar2TS.tuple)")
// Bar-3 signature: 3/4.
let bar3TS: TimeSignature = map.timeSignature(atBar: 3)
#expect(bar3TS.tuple == (3, 4),
"bar-3 signature must be (3, 4) after round-trip; got \(bar3TS.tuple)")
// Segment startBars: first starts at bar 1, second at bar 3.
let sortedSegments: [MeterMap.Segment] = map.segments.sorted { $0.startBar < $1.startBar }
#expect(sortedSegments[0].startBar == 1,
"first segment must start at bar 1")
#expect(sortedSegments[1].startBar == 3,
"second segment must start at bar 3")
}
// MARK: - Grouping caveat: numerator/denominator survive, grouping is re-inferred
/// MusicXML `<time>` carries no beat-grouping; numerator and denominator are
/// faithfully preserved across the round-trip, but the `beatGrouping` is
/// re-inferred from the default-grouping rule. This is the documented
/// round-trip caveat.
@Test func groupingCaveatNumDenPreservedGroupingReInferred() throws {
// 6/8 as compound [3,3] (the default for 6/8).
let original: Score = Score(
bpm: 120,
meterMap: MeterMap(.sixEightCompound)
) {
Part("p") {
// 6 eighth notes = one bar of 6/8.
Note(.c, 4, dur: .eighth)
Note(.d, 4, dur: .eighth)
Note(.e, 4, dur: .eighth)
Note(.f, 4, dur: .eighth)
Note(.g, 4, dur: .eighth)
Note(.a, 4, dur: .eighth)
}
}
let data: Data = original.toMusicXMLData()
let parsed: Score = try Score.fromMusicXML(data: data)
#expect(parsed.meterMap.initial.numerator == 6,
"numerator must survive round-trip; got \(parsed.meterMap.initial.numerator)")
#expect(parsed.meterMap.initial.denominator == 8,
"denominator must survive round-trip; got \(parsed.meterMap.initial.denominator)")
// Default-grouping inference for 6/8 yields compound [3, 3].
#expect(parsed.meterMap.initial.beatGrouping == [3, 3],
"6/8 must re-infer compound [3, 3] after round-trip")
}
// MARK: - Deduplication of repeated identical <time> elements
/// A MusicXML document that repeats the same `<time>` block in every measure
/// (some engravers emit this) must parse back as a constant-meter map, not as
/// N identical segments.
@Test func repeatedIdenticalTimeElementsDeduplicateToConstant() throws {
// Manually craft a document that emits <time>4/4</time> in bar 1 and
// bar 2 (redundant repetition — some engravers do this).
let xml: String = """
<?xml version="1.0"?>
<score-partwise version="4.0">
<part-list>
<score-part id="P1"><part-name>p</part-name></score-part>
</part-list>
<part id="P1">
<measure number="1">
<attributes>
<divisions>1</divisions>
<time><beats>4</beats><beat-type>4</beat-type></time>
</attributes>
<note>
<pitch><step>C</step><octave>4</octave></pitch>
<duration>1</duration><voice>1</voice>
</note>
</measure>
<measure number="2">
<attributes>
<time><beats>4</beats><beat-type>4</beat-type></time>
</attributes>
<note>
<pitch><step>D</step><octave>4</octave></pitch>
<duration>1</duration><voice>1</voice>
</note>
</measure>
</part>
</score-partwise>
"""
let score: Score = try Score.fromMusicXML(data: Data(xml.utf8))
// Deduplicated: two identical 4/4 segments collapse to one.
#expect(score.meterMap.isConstant,
"repeated identical <time> elements must collapse to a constant (single-segment) meterMap")
#expect(score.meterMap.initial.tuple == (4, 4),
"deduplicated constant map must reflect (4, 4)")
}
}
@@ -0,0 +1,108 @@
// MusicXMLPolymeterTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
/// Polymeter: each ``ScorePart`` may carry its own ``MeterMap`` (via
/// `Part(_:meterMap:)`), and the MusicXML encoder renders every part against its
/// own effective meter map. Parts encode independently in `score-partwise`, so
/// different bar groupings (and bar counts) coexist with no shared barline grid.
@MainActor
@Suite("MusicXML — polymeter (per-part meter maps)")
struct MusicXMLPolymeterTests {
/// Extract the inner XML of a single `<part id="…">…</part>` block.
private func partXML(_ xml: String, id: String) -> String {
guard let start: Range<String.Index> = xml.range(of: "<part id=\"\(id)\">") else { return "" }
let rest: Substring = xml[start.upperBound...]
guard let end: Range<Substring.Index> = rest.range(of: "</part>") else { return String(rest) }
return String(rest[..<end.lowerBound])
}
private func measureCount(_ partXML: String) -> Int {
partXML.components(separatedBy: "<measure ").count - 1
}
@Test func eachPartUsesOwnMeterAndMeasureCount() {
// Part A: 4/4, 12 quarters → 3 measures. Part B: 3/4, 12 quarters → 4 measures.
let score: Score = Score {
Part("A") {
for _: Int in 0..<12 { Note(.c, 5, dur: .quarter) }
}
Part("B", meterMap: MeterMap(.threeFour)) {
for _: Int in 0..<12 { Note(.c, 4, dur: .quarter) }
}
}
let xml: String = score.toMusicXMLString()
let a: String = partXML(xml, id: "P1")
let b: String = partXML(xml, id: "P2")
#expect(a.contains("<beats>4</beats>"))
#expect(measureCount(a) == 3)
#expect(b.contains("<beats>3</beats>"))
#expect(measureCount(b) == 4)
}
@Test func partsDoNotLeakEachOthersMeter() {
let score: Score = Score {
Part("A") {
for _: Int in 0..<12 { Note(.c, 5, dur: .quarter) }
}
Part("B", meterMap: MeterMap(.threeFour)) {
for _: Int in 0..<12 { Note(.c, 4, dur: .quarter) }
}
}
let xml: String = score.toMusicXMLString()
let a: String = partXML(xml, id: "P1")
let b: String = partXML(xml, id: "P2")
// The 4/4 part never emits a 3/4 time, and vice versa.
#expect(a.contains("<beats>3</beats>") == false)
#expect(b.contains("<beats>4</beats>") == false)
}
@Test func perPartMidPieceMeterChange() {
// Part B changes 3/4 → 2/4 at its bar 3 while Part A stays 4/4 throughout.
let bMap: MeterMap = MeterMap(segments: [
MeterMap.Segment(startBar: 1, .threeFour),
MeterMap.Segment(startBar: 3, .twoFour),
])
let score: Score = Score {
Part("A") {
for _: Int in 0..<8 { Note(.c, 5, dur: .quarter) }
}
Part("B", meterMap: bMap) {
for _: Int in 0..<8 { Note(.c, 4, dur: .quarter) }
}
}
let xml: String = score.toMusicXMLString()
let a: String = partXML(xml, id: "P1")
let b: String = partXML(xml, id: "P2")
// A: constant 4/4 → exactly one <time>.
#expect(a.components(separatedBy: "<time>").count - 1 == 1)
// B: 3/4 then 2/4 → two <time> blocks.
#expect(b.components(separatedBy: "<time>").count - 1 == 2)
#expect(b.contains("<beats>3</beats>"))
#expect(b.contains("<beats>2</beats>"))
}
@Test func perPartAnacrusisIsIndependent() {
// Part A has a one-quarter pickup; Part B has none.
let score: Score = Score {
Part("A", meterMap: MeterMap(.fourFour, anacrusis: Fraction(1, 1))) {
for _: Int in 0..<5 { Note(.c, 5, dur: .quarter) } // pickup + one full bar
}
Part("B") {
for _: Int in 0..<4 { Note(.c, 4, dur: .quarter) }
}
}
let xml: String = score.toMusicXMLString()
let a: String = partXML(xml, id: "P1")
let b: String = partXML(xml, id: "P2")
#expect(a.contains("implicit=\"yes\""))
#expect(b.contains("implicit=\"yes\"") == false)
}
}
@@ -0,0 +1,153 @@
// MusicXMLRepeatPartPaddingTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable import LyrebirdSynth
@MainActor
@Suite("MusicXML repeat-barline padding for short parts")
struct MusicXMLRepeatPartPaddingTests {
/// Extract the `<part id="P{index}">…</part>` block (1-based part index).
private func partBlock(_ xml: String, index: Int) -> String {
let open: String = "<part id=\"P\(index)\">"
guard let start: Range<String.Index> = xml.range(of: open),
let end: Range<String.Index> = xml.range(
of: "</part>",
range: start.upperBound..<xml.endIndex
)
else { return "" }
return String(xml[start.upperBound..<end.lowerBound])
}
private func measureCount(_ block: String) -> Int {
block.components(separatedBy: "<measure number=").count - 1
}
private func repeatsBars1to4() -> RepeatStructure {
RepeatStructure(
forwardRepeatMeasures: [1],
backwardRepeatMeasures: [3],
endings: [
Ending(number: 1, startMeasure: 3, stopMeasure: 3),
Ending(number: 2, startMeasure: 4, stopMeasure: 4)
]
)
}
@Test("Short single-voice part is padded to the repeat span and carries the barlines")
func shortSingleVoicePartPadded() {
let score: Score = Score(
bpm: 120,
timeSignature: TimeSignature(4, 4),
repeats: repeatsBars1to4()
) {
Part("long", clef: .treble) {
for _: Int in 0..<4 { Note(.named(.c, 5), dur: .whole) }
}
Part("short", clef: .treble) {
Note(.named(.c, 4), dur: .whole)
}
}
let xml: String = score.toMusicXMLString()
let shortBlock: String = partBlock(xml, index: 2)
// Padded from 1 natural bar up to measure 4 (the repeat span).
#expect(measureCount(shortBlock) == 4)
// The short part now carries the backward repeat (m3) and both endings.
#expect(shortBlock.contains("<repeat direction=\"backward\""))
#expect(shortBlock.contains("<ending number=\"1\""))
#expect(shortBlock.contains("<ending number=\"2\""))
// The padded measures are whole-measure rests.
#expect(shortBlock.contains("<rest measure=\"yes\"/>"))
}
@Test("Short multi-voice part is padded to the repeat span")
func shortMultiVoicePartPadded() {
let score: Score = Score(
bpm: 120,
timeSignature: TimeSignature(4, 4),
repeats: repeatsBars1to4()
) {
Part("long", clef: .treble) {
for _: Int in 0..<4 { Note(.named(.c, 5), dur: .whole) }
}
Part("short", clef: .treble) {
Voice(1) { Note(.named(.e, 5), dur: .whole) }
Voice(2) { Note(.named(.c, 4), dur: .whole) }
}
}
let xml: String = score.toMusicXMLString()
let shortBlock: String = partBlock(xml, index: 2)
#expect(measureCount(shortBlock) == 4)
#expect(shortBlock.contains("<repeat direction=\"backward\""))
}
@Test("Polymetric part is NOT padded — its barline grid cannot align")
func polymetricPartNotPadded() {
let score: Score = Score(
bpm: 120,
timeSignature: TimeSignature(4, 4),
repeats: repeatsBars1to4()
) {
Part("long", clef: .treble) {
for _: Int in 0..<4 { Note(.named(.c, 5), dur: .whole) }
}
Part("poly", clef: .bass, meterMap: MeterMap(.threeFour)) {
for _: Int in 0..<3 { Note(.named(.g, 2), dur: .quarter) }
}
}
let xml: String = score.toMusicXMLString()
let polyBlock: String = partBlock(xml, index: 2)
// 3 quarters in 3/4 = one bar; left at natural length, not padded to 4.
#expect(measureCount(polyBlock) == 1)
// With no measure 3, it carries no backward repeat.
#expect(!polyBlock.contains("<repeat direction=\"backward\""))
}
@Test("A score with no repeats leaves short parts unchanged")
func noRepeatsLeavesShortPartUnchanged() {
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("long", clef: .treble) {
for _: Int in 0..<4 { Note(.named(.c, 5), dur: .whole) }
}
Part("short", clef: .treble) {
Note(.named(.c, 4), dur: .whole)
}
}
let xml: String = score.toMusicXMLString()
let shortBlock: String = partBlock(xml, index: 2)
// No repeat structure → no padding → natural single bar.
#expect(measureCount(shortBlock) == 1)
}
@Test("Anacrusis part with short content pads full bars 1…N above the pickup")
func anacrusisShortPartPadded() {
// A one-quarter pickup (bar 0) then 4/4. The short part fills only the
// pickup, so it has zero full bars naturally and must pad full bars 1…4
// without re-emitting or skipping the pickup (bar 0).
let score: Score = Score(
bpm: 120,
meterMap: MeterMap(.fourFour, anacrusis: Fraction(1, 1)),
repeats: repeatsBars1to4()
) {
Part("long", clef: .treble) {
Note(.named(.e, 5), dur: .quarter) // pickup
for _: Int in 0..<4 { Note(.named(.c, 5), dur: .whole) }
}
Part("short", clef: .treble) {
Note(.named(.e, 5), dur: .quarter) // fills the pickup only
}
}
let xml: String = score.toMusicXMLString()
let shortBlock: String = partBlock(xml, index: 2)
// Pickup (measure 0) + four padded full bars = 5 measures.
#expect(measureCount(shortBlock) == 5)
#expect(shortBlock.contains("<measure number=\"0\" implicit=\"yes\""))
#expect(shortBlock.contains("<repeat direction=\"backward\""))
#expect(shortBlock.contains("<ending number=\"2\""))
}
}
File diff suppressed because it is too large Load Diff
@@ -1,4 +1,4 @@
// Phase57NoiseTests.swift
// NoiseTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
+302
View File
@@ -0,0 +1,302 @@
// NotationMarkTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("NotationMark — per-note notation marks")
struct NotationMarkTests {
// MARK: - Helpers
/// Build a single-quarter-note score and return its MusicXML string.
private func singleNoteScore(marks: [NotationMark] = [], art: Articulation = .normal) -> String {
let score: Score = Score(bpm: 120) {
Part("test") {
Note(.c, 5, dur: .quarter, art: art, marks: marks)
}
}
return score.toMusicXMLString()
}
// MARK: - 1. Empty marks — byte-identical to plain note
@Test func emptyMarksProducesByteIdenticalOutput() {
let plain: String = Score(bpm: 120) {
Part("test") {
Note(.c, 5, dur: .quarter)
}
}.toMusicXMLString()
let withEmpty: String = Score(bpm: 120) {
Part("test") {
Note(.c, 5, dur: .quarter, marks: [])
}
}.toMusicXMLString()
#expect(plain == withEmpty)
}
// MARK: - 2. Multiple articulation marks → one <articulations> block
@Test func multipleArticulationMarksEmitSingleBlock() {
let xml: String = singleNoteScore(marks: [.staccato, .accent])
// One <articulations> block containing both glyphs.
#expect(xml.contains("<articulations>"))
#expect(xml.contains("<staccato/>"))
#expect(xml.contains("<accent/>"))
// Only one open/close pair of <articulations>.
let openCount: Int = xml.components(separatedBy: "<articulations>").count - 1
#expect(openCount == 1)
}
// MARK: - 3. art: + marks: deduplication
@Test func artAndMarksDeduplicateStaccato() {
let xml: String = singleNoteScore(marks: [.staccato], art: .staccato)
// <staccato/> must appear exactly once.
let count: Int = xml.components(separatedBy: "<staccato/>").count - 1
#expect(count == 1)
}
@Test func artStaccatoAloneProducesOneGlyph() {
let xml: String = singleNoteScore(art: .staccato)
let count: Int = xml.components(separatedBy: "<staccato/>").count - 1
#expect(count == 1)
}
// MARK: - 4. No marks — byte-identical regression (plain art: staccato path unchanged)
@Test func noMarksWithArticulationIsByteIdenticalToPreviousBehavior() {
// A note with art:.staccato and no marks must produce identical XML to
// the same note authored before marks: was added (regression guard).
let xml: String = singleNoteScore(art: .staccato)
#expect(xml.contains("<articulations>"))
#expect(xml.contains("<staccato/>"))
// No technical or fermata blocks.
#expect(!xml.contains("<technical>"))
#expect(!xml.contains("<fermata"))
}
// MARK: - 5. Technique marks → <technical> block
@Test func leftHandPizzicatoEmitsStoppedElement() {
let xml: String = singleNoteScore(marks: [.leftHandPizzicato])
#expect(xml.contains("<technical>"))
#expect(xml.contains("<stopped/>"))
}
@Test func snapPizzicatoEmitsElement() {
let xml: String = singleNoteScore(marks: [.snapPizzicato])
#expect(xml.contains("<technical>"))
#expect(xml.contains("<snap-pizzicato/>"))
}
@Test func upBowEmitsElement() {
let xml: String = singleNoteScore(marks: [.upBow])
#expect(xml.contains("<technical>"))
#expect(xml.contains("<up-bow/>"))
}
@Test func downBowEmitsElement() {
let xml: String = singleNoteScore(marks: [.downBow])
#expect(xml.contains("<technical>"))
#expect(xml.contains("<down-bow/>"))
}
@Test func harmonicEmitsElement() {
let xml: String = singleNoteScore(marks: [.harmonic])
#expect(xml.contains("<technical>"))
#expect(xml.contains("<harmonic/>"))
}
@Test func openStringEmitsElement() {
let xml: String = singleNoteScore(marks: [.openString])
#expect(xml.contains("<technical>"))
#expect(xml.contains("<open-string/>"))
}
// MARK: - 6. Fermata marks
@Test func fermataShapeNormalEmitsSelfClosing() {
let xml: String = singleNoteScore(marks: [.fermata(.normal)])
// Normal fermata: self-closing <fermata/>.
#expect(xml.contains("<fermata/>"))
// Must NOT emit a body text form like <fermata>normal</fermata>.
#expect(!xml.contains("<fermata>"))
}
@Test func fermataShapeSquareEmitsBodyText() {
let xml: String = singleNoteScore(marks: [.fermata(.square)])
#expect(xml.contains("<fermata>square</fermata>"))
}
@Test func fermataShapeDoubleSquareEmitsBodyText() {
let xml: String = singleNoteScore(marks: [.fermata(.doubleSquare)])
#expect(xml.contains("<fermata>double-square</fermata>"))
}
@Test func fermataShapeAngledEmitsBodyText() {
let xml: String = singleNoteScore(marks: [.fermata(.angled)])
#expect(xml.contains("<fermata>angled</fermata>"))
}
@Test func fermataShapeDoubleAngledEmitsBodyText() {
let xml: String = singleNoteScore(marks: [.fermata(.doubleAngled)])
#expect(xml.contains("<fermata>double-angled</fermata>"))
}
@Test func fermataShapeDoubleDotEmitsBodyText() {
let xml: String = singleNoteScore(marks: [.fermata(.doubleDot)])
#expect(xml.contains("<fermata>double-dot</fermata>"))
}
@Test func fermataShapeHalfCurveEmitsBodyText() {
let xml: String = singleNoteScore(marks: [.fermata(.halfCurve)])
#expect(xml.contains("<fermata>half-curve</fermata>"))
}
@Test func fermataShapeCurlewEmitsBodyText() {
let xml: String = singleNoteScore(marks: [.fermata(.curlew)])
#expect(xml.contains("<fermata>curlew</fermata>"))
}
// MARK: - 7. DTD order: <technical> before <articulations> before <fermata>
@Test func dtdOrderTechnicalBeforeArticulationsBeforeFermata() {
let xml: String = singleNoteScore(marks: [.staccato, .upBow, .fermata(.normal)])
let technicalRange: Range<String.Index>? = xml.range(of: "<technical>")
let articulationsRange: Range<String.Index>? = xml.range(of: "<articulations>")
let fermataRange: Range<String.Index>? = xml.range(of: "<fermata")
// All three must be present.
#expect(technicalRange != nil)
#expect(articulationsRange != nil)
#expect(fermataRange != nil)
if let tech: Range<String.Index> = technicalRange,
let art: Range<String.Index> = articulationsRange,
let ferm: Range<String.Index> = fermataRange
{
// <technical> comes before <articulations> comes before <fermata>.
#expect(tech.lowerBound < art.lowerBound)
#expect(art.lowerBound < ferm.lowerBound)
}
}
// MARK: - 8. flatten: .marked note produces same ScoreEvent as plain note
@Test func flattenMarkedNoteProducesSameEvents() {
let markedPart: ScorePart = ScorePart(
name: "test",
elements: [Note(.c, 5, dur: .quarter, marks: [.staccato, .fermata(.normal), .upBow])]
)
let plainPart: ScorePart = ScorePart(
name: "test",
elements: [Note(.c, 5, dur: .quarter)]
)
let markedEvents: [ScoreEvent] = markedPart.flatten()
let plainEvents: [ScoreEvent] = plainPart.flatten()
#expect(markedEvents.count == plainEvents.count)
for (m, p): (ScoreEvent, ScoreEvent) in zip(markedEvents, plainEvents) {
#expect(m.pitch == p.pitch)
#expect(m.duration == p.duration)
}
}
// MARK: - 9. Chord marks work
@Test func chordMarksEmitOnEachNotehead() {
let score: Score = Score(bpm: 120) {
Part("test") {
Chord(
[Pitch.named(.c, 5), Pitch.named(.e, 5)],
dur: .quarter,
marks: [.staccato, .upBow]
)
}
}
let xml: String = score.toMusicXMLString()
// Both noteheads of the chord should carry the marks.
let staccatoCount: Int = xml.components(separatedBy: "<staccato/>").count - 1
#expect(staccatoCount == 2)
let upBowCount: Int = xml.components(separatedBy: "<up-bow/>").count - 1
#expect(upBowCount == 2)
}
// MARK: - 10. No-marks note is byte-identical to pre-marks baseline (plain .normal art)
@Test func plainNoteWithNoMarksIsByteIdenticalToPlainNote() {
// A note with no marks: and art:.normal must produce byte-identical XML to
// the same note built without any marks: parameter at all. This guards that
// the .marked wrapper is NOT applied when marks is empty.
let xmlNoParam: String = Score(bpm: 120) {
Part("test") {
Note(.d, 4, dur: .half)
}
}.toMusicXMLString()
let xmlEmptyMarks: String = Score(bpm: 120) {
Part("test") {
Note(.d, 4, dur: .half, marks: [])
}
}.toMusicXMLString()
#expect(xmlNoParam == xmlEmptyMarks)
// Neither should contain any extra elements.
#expect(!xmlNoParam.contains("<notations>"))
}
// MARK: - 11. marcato → <strong-accent/>
@Test func marcatoMarkEmitsStrongAccent() {
let xml: String = singleNoteScore(marks: [.marcato])
#expect(xml.contains("<strong-accent/>"))
}
// MARK: - 12. tenuto → <tenuto/>
@Test func tenutoMarkEmitsTenuto() {
let xml: String = singleNoteScore(marks: [.tenuto])
#expect(xml.contains("<tenuto/>"))
}
// MARK: - 13. staccatissimo → <staccatissimo/>
@Test func staccatissimoMarkEmitsStaccatissimo() {
let xml: String = singleNoteScore(marks: [.staccatissimo])
#expect(xml.contains("<staccatissimo/>"))
}
// MARK: - 14. art + marks dedup for marcato (enum name ≠ XML element name)
@Test func artAndMarksDeduplicateMarcato() {
// .marcato is the one glyph whose enum case name differs from its MusicXML
// element (<strong-accent/>). Both art: and marks: supplying it must still
// emit exactly one <strong-accent/>.
let xml: String = singleNoteScore(marks: [.marcato], art: .marcato)
#expect(xml.components(separatedBy: "<strong-accent/>").count - 1 == 1)
}
// MARK: - 15. marks survive a multi-voice barline-crossing split
@Test func marksSurviveMultiVoiceBarlineSplit() {
// Voice 2's whole note starts on beat 3 and crosses into the next bar; the
// multi-voice encoder splits it into two tied pieces via the leftover-atom
// reconstruction. Both pieces must carry the staccato mark.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Voice(1) { Note(.c, 5, dur: .whole) }
Voice(2) {
Rest(dur: .half)
Note(.g, 4, dur: .whole, marks: [.staccato]) // beats 3-4 + 1-2 next bar
}
}
}
let xml: String = score.toMusicXMLString()
// Two tied pieces, each with <staccato/>.
#expect(xml.components(separatedBy: "<staccato/>").count - 1 == 2)
}
}
+484
View File
@@ -0,0 +1,484 @@
// NoteDisplayTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("NoteDisplay — per-note notation overrides")
struct NoteDisplayTests {
// MARK: - 1. Nil / no-override path — byte-identical output
@Test func nilDisplayProducesNoByteDifference() throws {
// A note with no display parameter must produce byte-identical MusicXML
// to the same note with display: nil (the default).
let score: Score = Score(bpm: 120) {
Part("test") {
Note(.c, 5, dur: .quarter)
}
}
let scoreWithNil: Score = Score(bpm: 120) {
Part("test") {
Note(.c, 5, dur: .quarter, display: nil)
}
}
let xml: String = try score.toMusicXMLString()
let xmlNil: String = try scoreWithNil.toMusicXMLString()
#expect(xml == xmlNil)
// Also confirm none of the display elements are present.
#expect(!xml.contains("<notehead>"))
#expect(!xml.contains("<stem>"))
#expect(!xml.contains("size=\""))
}
@Test func allDefaultsNoteDisplayProducesNoByteDifference() throws {
// NoteDisplay() with all defaults is a no-op when hasOverrides == false.
let score: Score = Score(bpm: 120) {
Part("test") {
Note(.c, 5, dur: .quarter)
}
}
let scoreWithDefault: Score = Score(bpm: 120) {
Part("test") {
Note(.c, 5, dur: .quarter, display: NoteDisplay())
}
}
let xml: String = try score.toMusicXMLString()
let xmlDefault: String = try scoreWithDefault.toMusicXMLString()
#expect(xml == xmlDefault)
}
// MARK: - 2. Notehead shapes → <notehead>VALUE</notehead>
@Test func noteheadXEmitsCorrectElement() throws {
let score: Score = Score(bpm: 120) {
Part("test") {
Note(.c, 5, dur: .quarter, display: NoteDisplay(notehead: .x))
}
}
let xml: String = try score.toMusicXMLString()
#expect(xml.contains("<notehead>x</notehead>"))
}
@Test func noteheadDiamondEmitsCorrectElement() throws {
let score: Score = Score(bpm: 120) {
Part("test") {
Note(.c, 5, dur: .quarter, display: NoteDisplay(notehead: .diamond))
}
}
let xml: String = try score.toMusicXMLString()
#expect(xml.contains("<notehead>diamond</notehead>"))
}
@Test func noteheadNoneEmitsHiddenNotehead() throws {
let score: Score = Score(bpm: 120) {
Part("test") {
Note(.c, 5, dur: .quarter, display: NoteDisplay(notehead: .hidden))
}
}
let xml: String = try score.toMusicXMLString()
#expect(xml.contains("<notehead>none</notehead>"))
}
@Test func noteheadCircleXEmitsHyphenatedValue() throws {
let score: Score = Score(bpm: 120) {
Part("test") {
Note(.c, 5, dur: .quarter, display: NoteDisplay(notehead: .circleX))
}
}
let xml: String = try score.toMusicXMLString()
#expect(xml.contains("<notehead>circle-x</notehead>"))
}
@Test func noteheadOtherClusterPassesThroughVerbatim() throws {
let score: Score = Score(bpm: 120) {
Part("test") {
Note(.c, 5, dur: .quarter, display: NoteDisplay(notehead: .other("cluster")))
}
}
let xml: String = try score.toMusicXMLString()
#expect(xml.contains("<notehead>cluster</notehead>"))
}
@Test func noteheadOtherIsXMLEscaped() throws {
// .other with reserved XML characters should be escaped.
let score: Score = Score(bpm: 120) {
Part("test") {
Note(.c, 5, dur: .quarter, display: NoteDisplay(notehead: .other("<test>")))
}
}
let xml: String = try score.toMusicXMLString()
#expect(xml.contains("<notehead>&lt;test&gt;</notehead>"))
#expect(!xml.contains("<notehead><test></notehead>"))
}
// MARK: - 3. NoteSize → <type size="...">
@Test func sizeNilProducesNoByteDifference() throws {
let score: Score = Score(bpm: 120) {
Part("test") {
Note(.c, 5, dur: .quarter)
}
}
let scoreWithNilSize: Score = Score(bpm: 120) {
Part("test") {
Note(.c, 5, dur: .quarter, display: NoteDisplay(size: nil))
}
}
let xml: String = try score.toMusicXMLString()
let xmlNilSize: String = try scoreWithNilSize.toMusicXMLString()
#expect(xml == xmlNilSize)
#expect(!xml.contains("size="))
}
@Test func sizeNormalProducesNoByteDifference() throws {
// size: .normal is the same as nil — musicXMLTypeSize returns nil, so no size= attribute.
// NoteDisplay(size: .normal).hasOverrides must be false.
let score: Score = Score(bpm: 120) {
Part("test") {
Note(.c, 5, dur: .quarter)
}
}
let scoreWithNormal: Score = Score(bpm: 120) {
Part("test") {
Note(.c, 5, dur: .quarter, display: NoteDisplay(size: .normal))
}
}
let displayNormal: NoteDisplay = NoteDisplay(size: .normal)
#expect(!displayNormal.hasOverrides)
let xml: String = try score.toMusicXMLString()
let xmlNormal: String = try scoreWithNormal.toMusicXMLString()
#expect(xml == xmlNormal)
}
@Test func sizeCueEmitsSizeAttributeOnType() throws {
let score: Score = Score(bpm: 120) {
Part("test") {
Note(.c, 5, dur: .eighth, display: NoteDisplay(size: .cue))
}
}
let xml: String = try score.toMusicXMLString()
#expect(xml.contains("<type size=\"cue\">eighth</type>"))
#expect(!xml.contains("<type>eighth</type>"))
}
@Test func sizeLargeEmitsSizeAttributeOnType() throws {
let score: Score = Score(bpm: 120) {
Part("test") {
Note(.c, 5, dur: .quarter, display: NoteDisplay(size: .large))
}
}
let xml: String = try score.toMusicXMLString()
#expect(xml.contains("<type size=\"large\">quarter</type>"))
}
// MARK: - 4. hideStem → <stem>none</stem>
@Test func hideStemEmitsStemNone() throws {
let score: Score = Score(bpm: 120) {
Part("test") {
Note(.c, 5, dur: .quarter, display: NoteDisplay(hideStem: true))
}
}
let xml: String = try score.toMusicXMLString()
#expect(xml.contains("<stem>none</stem>"))
}
@Test func hideStemFalseProducesNoByteDifference() throws {
let score: Score = Score(bpm: 120) {
Part("test") {
Note(.c, 5, dur: .quarter)
}
}
let scoreNoStem: Score = Score(bpm: 120) {
Part("test") {
Note(.c, 5, dur: .quarter, display: NoteDisplay(hideStem: false))
}
}
let xml: String = try score.toMusicXMLString()
let xmlNoStem: String = try scoreNoStem.toMusicXMLString()
#expect(xml == xmlNoStem)
#expect(!xml.contains("<stem>"))
}
@Test func hideStemAppearsAfterTimeModificationBeforeStaff() throws {
// Verify the MusicXML child-element order: time-modification → stem → notehead → staff.
// Use a quarter note (no time-modification) to keep the test simple — we verify
// that <stem> appears BEFORE any <notehead> and the two appear within the note block.
let score: Score = Score(bpm: 120) {
Part("test") {
Note(.c, 5, dur: .quarter, display: NoteDisplay(notehead: .x, hideStem: true))
}
}
let xml: String = try score.toMusicXMLString()
#expect(xml.contains("<stem>none</stem>"))
#expect(xml.contains("<notehead>x</notehead>"))
// stem must appear before notehead in the output string.
let stemRange: Range<String.Index>? = xml.range(of: "<stem>none</stem>")
let noteheadRange: Range<String.Index>? = xml.range(of: "<notehead>x</notehead>")
#expect(stemRange != nil)
#expect(noteheadRange != nil)
if let stemR: Range<String.Index> = stemRange,
let nhR: Range<String.Index> = noteheadRange {
#expect(stemR.lowerBound < nhR.lowerBound)
}
}
// MARK: - 5. hideBeam — breaks a beam run at the marked note
@Test func hideBeamBreaksBeamRun() throws {
// Four eighth notes in a row normally form one beam group (begin/continue/continue/end).
// Marking the SECOND note with hideBeam should break the run so the second note
// carries no <beam> element and the surrounding run is split.
let scoreBeamed: Score = Score(bpm: 120) {
Part("test") {
Note(.c, 5, dur: .eighth)
Note(.d, 5, dur: .eighth)
Note(.e, 5, dur: .eighth)
Note(.f, 5, dur: .eighth)
}
}
let scoreHideBeam: Score = Score(bpm: 120) {
Part("test") {
Note(.c, 5, dur: .eighth)
Note(.d, 5, dur: .eighth, display: NoteDisplay(hideBeam: true))
Note(.e, 5, dur: .eighth)
Note(.f, 5, dur: .eighth)
}
}
let xmlBeamed: String = try scoreBeamed.toMusicXMLString()
let xmlHide: String = try scoreHideBeam.toMusicXMLString()
// The beamed version has exactly 4 <beam> elements (begin/continue/continue/end).
let beamedCount: Int = xmlBeamed.components(separatedBy: "<beam number=\"1\">").count - 1
#expect(beamedCount == 4)
// The hide-beam version has fewer <beam> elements because the run broke.
let hideCount: Int = xmlHide.components(separatedBy: "<beam number=\"1\">").count - 1
#expect(hideCount < beamedCount)
// The hide-beam version should still contain some beams for the intact sub-runs.
#expect(hideCount > 0)
}
@Test func hideBeamFalseProducesNoByteDifference() throws {
let score: Score = Score(bpm: 120) {
Part("test") {
Note(.c, 5, dur: .eighth)
Note(.d, 5, dur: .eighth)
}
}
let scoreNoHide: Score = Score(bpm: 120) {
Part("test") {
Note(.c, 5, dur: .eighth)
Note(.d, 5, dur: .eighth, display: NoteDisplay(hideBeam: false))
}
}
let xml: String = try score.toMusicXMLString()
let xmlNoHide: String = try scoreNoHide.toMusicXMLString()
#expect(xml == xmlNoHide)
}
// MARK: - 6. display composes with spanners
@Test func displayComposesWithSpanners() throws {
// A note with BOTH spanners: and display: should emit both the notehead
// override AND the slur markup.
let score: Score = Score(bpm: 120) {
Part("test") {
Note(.c, 5, dur: .quarter, spanners: [.beginSlur], display: NoteDisplay(notehead: .diamond))
Note(.e, 5, dur: .quarter, spanners: [.endSlur])
}
}
let xml: String = try score.toMusicXMLString()
#expect(xml.contains("<notehead>diamond</notehead>"))
#expect(xml.contains("<slur number=\"1\" type=\"start\"/>"))
#expect(xml.contains("<slur number=\"1\" type=\"stop\"/>"))
}
@Test func displayComposesWithSlurBlock() throws {
// A note wrapped in Slur{} AND a display should emit both.
let score: Score = Score(bpm: 120) {
Part("test") {
Slur {
Note(.c, 5, dur: .quarter, display: NoteDisplay(notehead: .x))
Note(.e, 5, dur: .quarter)
}
}
}
let xml: String = try score.toMusicXMLString()
#expect(xml.contains("<notehead>x</notehead>"))
#expect(xml.contains("<slur number=\"1\" type=\"start\"/>"))
}
// MARK: - 7. flatten transparency
@Test func displayedFlattenIsTransparent() {
// A .displayed note must produce the SAME ScoreEvent list as the unwrapped note.
let part: ScorePart = ScorePart(
name: "test",
elements: [
Note(.c, 5, dur: .quarter, display: NoteDisplay(notehead: .x, hideStem: true))
]
)
let plainPart: ScorePart = ScorePart(
name: "test",
elements: [
Note(.c, 5, dur: .quarter)
]
)
let events: [ScoreEvent] = part.flatten()
let plainEvents: [ScoreEvent] = plainPart.flatten()
#expect(events.count == plainEvents.count)
#expect(events.count == 1)
#expect(events[0].beat == plainEvents[0].beat)
#expect(events[0].duration == plainEvents[0].duration)
#expect(events[0].pitch.midiNote == plainEvents[0].pitch.midiNote)
}
@Test func displayedChordFlattenIsTransparent() {
// A .displayed chord must produce the same ScoreEvent list as the unwrapped chord.
let part: ScorePart = ScorePart(
name: "test",
elements: [
Chord([(.c, 5), (.e, 5)], dur: .half, display: NoteDisplay(notehead: .diamond))
]
)
let plainPart: ScorePart = ScorePart(
name: "test",
elements: [
Chord([(.c, 5), (.e, 5)], dur: .half)
]
)
let events: [ScoreEvent] = part.flatten()
let plainEvents: [ScoreEvent] = plainPart.flatten()
#expect(events.count == plainEvents.count)
#expect(events.count == 2)
}
// MARK: - 8. Rests ignore display
@Test func restIgnoresNoteheadAndStem() throws {
// A rest followed by a note with display. Verify the rest carries no <notehead> or <stem>.
let score: Score = Score(bpm: 120) {
Part("test") {
Rest(dur: .quarter)
Note(.c, 5, dur: .quarter, display: NoteDisplay(notehead: .x, hideStem: true))
}
}
let xml: String = try score.toMusicXMLString()
// The note has the overrides; the rest should not.
#expect(xml.contains("<notehead>x</notehead>"))
#expect(xml.contains("<stem>none</stem>"))
// Verify: a plain Rest does not produce <notehead> even when the part contains
// an atom with a notehead override. The rest's own XML block must not contain these.
// Split by <note> blocks and check the rest block specifically.
let noteBlocks: [Substring] = xml.split(separator: "\n").filter { $0.contains("<rest") }
for block: Substring in noteBlocks {
// None of the rest-only lines should contain notehead or stem overrides.
#expect(!block.contains("notehead"))
#expect(!block.contains("stem"))
}
}
// MARK: - 9. Notehead enum values
@Test func noteheadMusicXMLValues() {
#expect(Notehead.normal.musicXMLValue == "normal")
#expect(Notehead.x.musicXMLValue == "x")
#expect(Notehead.diamond.musicXMLValue == "diamond")
#expect(Notehead.triangle.musicXMLValue == "triangle")
#expect(Notehead.slash.musicXMLValue == "slash")
#expect(Notehead.cross.musicXMLValue == "cross")
#expect(Notehead.circleX.musicXMLValue == "circle-x")
#expect(Notehead.square.musicXMLValue == "square")
#expect(Notehead.hidden.musicXMLValue == "none")
#expect(Notehead.other("xyz").musicXMLValue == "xyz")
}
@Test func noteSizeMusicXMLTypeSize() {
#expect(NoteSize.cue.musicXMLTypeSize == "cue")
#expect(NoteSize.normal.musicXMLTypeSize == nil)
#expect(NoteSize.large.musicXMLTypeSize == "large")
}
@Test func noteDisplayHasOverrides() {
#expect(!NoteDisplay().hasOverrides)
// size: .normal is equivalent to nil — no size attribute emitted, so not an override.
#expect(!NoteDisplay(size: .normal).hasOverrides)
#expect(!NoteDisplay(size: nil).hasOverrides)
#expect(NoteDisplay(notehead: .x).hasOverrides)
#expect(NoteDisplay(notehead: .hidden).hasOverrides)
#expect(NoteDisplay(size: .cue).hasOverrides)
#expect(NoteDisplay(size: .large).hasOverrides)
#expect(NoteDisplay(hideStem: true).hasOverrides)
#expect(NoteDisplay(hideBeam: true).hasOverrides)
}
// MARK: - 10. Chord display overrides
@Test func chordDisplayEmitsNoteheadOnAllNoteheads() throws {
let score: Score = Score(bpm: 120) {
Part("test") {
Chord([(.c, 5), (.e, 5)], dur: .quarter, display: NoteDisplay(notehead: .x))
}
}
let xml: String = try score.toMusicXMLString()
// Both noteheads in the chord should carry the notehead override.
let count: Int = xml.components(separatedBy: "<notehead>x</notehead>").count - 1
#expect(count == 2)
}
@Test func chordHideStemEmitsStemNone() throws {
let score: Score = Score(bpm: 120) {
Part("test") {
Chord([(.c, 5), (.e, 5)], dur: .quarter, display: NoteDisplay(hideStem: true))
}
}
let xml: String = try score.toMusicXMLString()
#expect(xml.contains("<stem>none</stem>"))
}
// MARK: - 11. Barline-split inherits display
@Test func barlineSplitNoteInheritsDisplay() throws {
// A note that crosses a barline is split into two tied pieces; both pieces
// should carry the display override (e.g. <notehead>x</notehead>).
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(3, 4)) {
Part("test") {
// A dotted-half that fits in one bar, plus a quarter that wraps into bar 2.
// Use a whole note which crosses the 3/4 barline:
// 4 beats in a 3/4 bar → splits into dotted-half + quarter.
Note(.c, 5, dur: .whole, display: NoteDisplay(notehead: .diamond))
}
}
let xml: String = try score.toMusicXMLString()
// The whole note splits into exactly two tied pieces (dotted-half + quarter);
// both must carry the diamond notehead.
let count: Int = xml.components(separatedBy: "<notehead>diamond</notehead>").count - 1
#expect(count == 2)
}
@Test func barlineSplitDisplayInheritedOnMultiVoicePath() throws {
// The multi-voice encoder path reconstructs a leftover continuation atom
// for the part of a note past the barline. That reconstruction must carry
// the display override forward (regression: it previously reset to default,
// dropping the notehead on the continuation piece).
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(3, 4)) {
Part("test") {
Voice(1) {
Note(.c, 5, dur: .whole, display: NoteDisplay(notehead: .diamond))
}
Voice(2) {
Note(.e, 4, dur: .whole)
}
}
}
let xml: String = try score.toMusicXMLString()
// Voice 1's whole note splits into two tied pieces across the 3/4 barline;
// both pieces must keep the diamond notehead.
let count: Int = xml.components(separatedBy: "<notehead>diamond</notehead>").count - 1
#expect(count == 2)
}
}
@@ -0,0 +1,93 @@
// NoteDurationTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable import LyrebirdSynth
@MainActor
@Suite("NoteDuration — double whole + British names")
struct NoteDurationTests {
@Test func doubleWholeIsEightBeats() {
#expect(NoteDuration.doubleWhole.beats == 8.0)
#expect(NoteDuration.doubleWhole.asFraction == Fraction(num: 8, den: 1))
}
@Test func britishNamesAliasAmericanDurations() {
#expect(NoteDuration.breve == .doubleWhole)
#expect(NoteDuration.semibreve == .whole)
#expect(NoteDuration.minim == .half)
#expect(NoteDuration.crotchet == .quarter)
#expect(NoteDuration.quaver == .eighth)
#expect(NoteDuration.semiquaver == .sixteenth)
#expect(NoteDuration.demisemiquaver == .thirtySecond)
#expect(NoteDuration.hemidemisemiquaver == .sixtyFourth)
}
@Test func britishNamesCarryCorrectBeats() {
#expect(NoteDuration.breve.beats == 8.0)
#expect(NoteDuration.semibreve.beats == 4.0)
#expect(NoteDuration.minim.beats == 2.0)
#expect(NoteDuration.crotchet.beats == 1.0)
#expect(NoteDuration.quaver.beats == 0.5)
#expect(NoteDuration.semiquaver.beats == 0.25)
#expect(NoteDuration.demisemiquaver.beats == 0.125)
#expect(NoteDuration.hemidemisemiquaver.beats == 0.0625)
}
@Test func doubleWholeEncodesAsBreveType() {
// An 8-beat bar (8/4) holds a whole breve, which the encoder maps to
// <type>breve</type>.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(8, 4)) {
Part("p") {
Note(.named(.c, 4), dur: .doubleWhole)
}
}
#expect(score.toMusicXMLString().contains("<type>breve</type>"))
}
@Test func doubleWholeInFourFourSplitsToTiedWholes() {
// A breve (8 beats) does not fit a 4/4 bar — it splits into two tied
// wholes. Each tied piece must read <type>whole</type>, never breve.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.named(.c, 4), dur: .doubleWhole)
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.components(separatedBy: "<type>whole</type>").count - 1 == 2)
#expect(!xml.contains("<type>breve</type>"))
}
@Test func doubleWholeMultiVoiceSplitsToTiedWholes() {
// Multi-voice path: each voice's breve splits into two tied wholes. The
// barline continuation piece must be typed by its leftover (whole), not by
// the original note value (breve) — a regression guard for the multi-voice
// leftover-atom rawDuration fix.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Voice(1) { Note(.named(.c, 5), dur: .doubleWhole) }
Voice(2) { Note(.named(.c, 4), dur: .doubleWhole) }
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.components(separatedBy: "<type>whole</type>").count - 1 == 4)
#expect(!xml.contains("<type>breve</type>"))
}
@Test func doubleWholeRoundTripsByDuration() throws {
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(8, 4)) {
Part("p") {
Note(.named(.c, 4), dur: .doubleWhole)
}
}
let rt: Score = try Score.fromMusicXML(data: score.toMusicXMLData())
// One sounding event of 8 beats survives the round-trip.
let events: [ScoreEvent] = rt.allEvents.filter { !$0.isRest }
#expect(events.count == 1)
#expect(events.first?.duration == 8.0)
}
}
@@ -0,0 +1,78 @@
// NoteNameTransposeTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@Suite("NoteName transposition — spelling-correct interval application")
struct NoteNameTransposeTests {
// MARK: - Plan worked examples (must pass)
@Test func augmentedSecondUpFromAGivesBSharp() throws {
let result: NoteName = try NoteName.a.transposed(by: .augmentedSecond, .up)
#expect(result == .bSharp)
#expect(result != .c) // NOT a plain chromatic shift
}
@Test func majorThirdUpFromCGivesE() throws {
#expect(try NoteName.c.transposed(by: .majorThird) == .e)
}
@Test func majorThirdUpFromEGivesGSharp() throws {
#expect(try NoteName.e.transposed(by: .majorThird) == .gSharp)
}
@Test func minorThirdUpFromCGivesEFlat() throws {
#expect(try NoteName.c.transposed(by: .minorThird) == .eFlat)
}
@Test func perfectFourthUpFromBGivesE() throws {
#expect(try NoteName.b.transposed(by: .perfectFourth) == .e)
}
@Test func minorThirdDownFromFSharpGivesDSharp() throws {
let result: NoteName = try NoteName.fSharp.transposed(by: .minorThird, .down)
#expect(result == .dSharp)
}
@Test func majorSecondUpFromCFlatGivesDFlat() throws {
#expect(try NoteName.cFlat.transposed(by: .majorSecond) == .dFlat)
}
// MARK: - Round-trip up then down
@Test func upThenDownReturnsOriginal() throws {
for name: NoteName in [.c, .fSharp, .bFlat, .e, .aFlat] {
let up: NoteName = try name.transposed(by: .perfectFifth, .up)
let back: NoteName = try up.transposed(by: .perfectFifth, .down)
#expect(back == name)
}
}
// MARK: - Unison and octave preserve the name
@Test func unisonAndOctavePreserveName() throws {
#expect(try NoteName.fSharp.transposed(by: .unison) == .fSharp)
#expect(try NoteName.bFlat.transposed(by: .octave) == .bFlat)
}
// MARK: - Out-of-range and quarter-tone errors
@Test func unrepresentableSpellingThrows() {
// F𝄪 (double sharp) up an augmented second would need a triple sharp on G.
#expect(throws: IntervalError.self) {
_ = try NoteName.fDoubleSharp.transposed(by: .augmentedSecond, .up)
}
}
@Test func quarterToneInputThrows() {
#expect(throws: IntervalError.self) {
_ = try NoteName.cQuarterSharp.transposed(by: .majorThird)
}
}
}
+404
View File
@@ -0,0 +1,404 @@
// PageLayoutTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable import LyrebirdSynth
@MainActor
@Suite("PageLayout")
struct PageLayoutTests {
// MARK: - Helpers
/// Build a minimal one-part score with optional pageLayout.
private func makeScore(pageLayout: PageLayout? = nil) -> Score {
Score(
bpm: 120,
parts: [
ScorePart(name: "Piano", elements: [Note(.c, 4, dur: .quarter)])
],
pageLayout: pageLayout
)
}
/// Parse the first occurrence of `tag` content from `xml`.
/// Returns the text between `<tag>` and `</tag>`, or nil when absent.
private func extractElement(tag: String, from xml: String) -> String? {
let open: String = "<\(tag)>"
let close: String = "</\(tag)>"
guard let startIdx: String.Index = xml.range(of: open)?.upperBound,
let endIdx: String.Index = xml.range(of: close)?.lowerBound else {
return nil
}
return String(xml[startIdx..<endIdx])
}
/// Return true when `xml` contains `<defaults>`.
private func hasDefaults(_ xml: String) -> Bool {
xml.contains("<defaults>")
}
// MARK: - nil pageLayout → no <defaults>
@Test("nil pageLayout: output contains no <defaults>")
func nilPageLayoutProducesNoDefaults() {
let withNil: Score = makeScore(pageLayout: nil)
let withoutParam: Score = makeScore()
let xmlNil: String = withNil.toMusicXMLString()
let xmlWithout: String = withoutParam.toMusicXMLString()
#expect(!hasDefaults(xmlNil))
#expect(!hasDefaults(xmlWithout))
// Byte-identical: both paths produce the same output.
#expect(xmlNil == xmlWithout)
}
// MARK: - Letter portrait
@Test("Letter portrait: <defaults> present, width < height")
func letterPortraitDimensions() {
let layout: PageLayout = PageLayout(size: .letter, orientation: .portrait)
let score: Score = makeScore(pageLayout: layout)
let xml: String = score.toMusicXMLString()
#expect(hasDefaults(xml))
// Under default scaling (7.0 mm = 40.0 tenths), tenthsPerMM = 40/7.
// Letter portrait: width = 215.9 * (40/7), height = 279.4 * (40/7).
let tpm: Double = 40.0 / 7.0
let expectedWidth: Double = 215.9 * tpm
let expectedHeight: Double = 279.4 * tpm
let widthStr: String? = extractElement(tag: "page-width", from: xml)
let heightStr: String? = extractElement(tag: "page-height", from: xml)
#expect(widthStr != nil)
#expect(heightStr != nil)
if let w: Double = widthStr.flatMap(Double.init),
let h: Double = heightStr.flatMap(Double.init) {
#expect(abs(w - expectedWidth) < 0.001)
#expect(abs(h - expectedHeight) < 0.001)
// Portrait: width < height.
#expect(w < h)
}
}
// MARK: - Letter landscape
@Test("Letter landscape: width > height (orientation swap)")
func letterLandscapeSwapsWidthHeight() {
let layout: PageLayout = PageLayout(size: .letter, orientation: .landscape)
let score: Score = makeScore(pageLayout: layout)
let xml: String = score.toMusicXMLString()
#expect(hasDefaults(xml))
let tpm: Double = 40.0 / 7.0
// Landscape: physical width = portrait height, physical height = portrait width.
let expectedWidth: Double = 279.4 * tpm
let expectedHeight: Double = 215.9 * tpm
let widthStr: String? = extractElement(tag: "page-width", from: xml)
let heightStr: String? = extractElement(tag: "page-height", from: xml)
if let w: Double = widthStr.flatMap(Double.init),
let h: Double = heightStr.flatMap(Double.init) {
#expect(abs(w - expectedWidth) < 0.001)
#expect(abs(h - expectedHeight) < 0.001)
// Landscape: width > height.
#expect(w > h)
}
}
// MARK: - A4 landscape
@Test("A4 landscape: correct tenths under default scaling")
func a4LandscapeTenths() {
let layout: PageLayout = PageLayout(size: .a4, orientation: .landscape)
let score: Score = makeScore(pageLayout: layout)
let xml: String = score.toMusicXMLString()
#expect(hasDefaults(xml))
let tpm: Double = 40.0 / 7.0
// A4: portrait width = 210 mm, height = 297 mm.
// Landscape: page-width = 297 * tpm, page-height = 210 * tpm.
let expectedWidth: Double = 297.0 * tpm // ≈ 1697.143
let expectedHeight: Double = 210.0 * tpm // = 1200.0
let widthStr: String? = extractElement(tag: "page-width", from: xml)
let heightStr: String? = extractElement(tag: "page-height", from: xml)
if let w: Double = widthStr.flatMap(Double.init),
let h: Double = heightStr.flatMap(Double.init) {
#expect(abs(w - expectedWidth) < 0.001)
#expect(abs(h - expectedHeight) < 0.001)
}
}
// MARK: - Custom page size
@Test("custom(widthMM:heightMM:) round-trips to correct tenths")
func customPageSizeTenths() {
let customWidthMM: Double = 100.0
let customHeightMM: Double = 150.0
let layout: PageLayout = PageLayout(
size: .custom(widthMillimeters: customWidthMM, heightMillimeters: customHeightMM),
orientation: .portrait
)
let score: Score = makeScore(pageLayout: layout)
let xml: String = score.toMusicXMLString()
let tpm: Double = 40.0 / 7.0
let expectedWidth: Double = customWidthMM * tpm
let expectedHeight: Double = customHeightMM * tpm
let widthStr: String? = extractElement(tag: "page-width", from: xml)
let heightStr: String? = extractElement(tag: "page-height", from: xml)
if let w: Double = widthStr.flatMap(Double.init),
let h: Double = heightStr.flatMap(Double.init) {
#expect(abs(w - expectedWidth) < 0.001)
#expect(abs(h - expectedHeight) < 0.001)
}
}
// MARK: - Symmetric margins → type="both"
@Test("symmetric margins emit single type=\"both\" page-margins block")
func symmetricMarginsEmitBoth() {
let layout: PageLayout = PageLayout(
size: .a4,
orientation: .portrait,
margins: PageLayout.Margins(uniformMillimeters: 20.0)
)
let score: Score = makeScore(pageLayout: layout)
let xml: String = score.toMusicXMLString()
#expect(xml.contains("type=\"both\""))
#expect(!xml.contains("type=\"odd\""))
#expect(!xml.contains("type=\"even\""))
}
// MARK: - Asymmetric odd/even → two page-margins blocks
@Test("asymmetric odd/even margins emit two page-margins blocks")
func asymmetricMarginsEmitOddAndEven() {
let oddMargins: PageLayout.Margins = PageLayout.Margins(
leftMillimeters: 30.0,
rightMillimeters: 15.0,
topMillimeters: 20.0,
bottomMillimeters: 20.0
)
let evenMargins: PageLayout.Margins = PageLayout.Margins(
leftMillimeters: 15.0,
rightMillimeters: 30.0,
topMillimeters: 20.0,
bottomMillimeters: 20.0
)
let layout: PageLayout = PageLayout(
size: .a4,
orientation: .portrait,
oddMargins: oddMargins,
evenMargins: evenMargins
)
let score: Score = makeScore(pageLayout: layout)
let xml: String = score.toMusicXMLString()
#expect(xml.contains("type=\"odd\""))
#expect(xml.contains("type=\"even\""))
#expect(!xml.contains("type=\"both\""))
// Verify the actual margin tenths, not just the block labels. Under the
// default scaling (40 tenths / 7 mm), a 30 mm margin → 30 * 40/7 tenths.
let tenthsPerMM: Double = 40.0 / 7.0
let expectedOddLeft: Double = 30.0 * tenthsPerMM
let expectedEvenRight: Double = 30.0 * tenthsPerMM
// The encoder emits the odd block first, then the even block.
let oddLeft: Double? = Self.firstMarginValue(in: xml, after: "type=\"odd\"", tag: "left-margin")
let evenRight: Double? = Self.firstMarginValue(in: xml, after: "type=\"even\"", tag: "right-margin")
#expect(oddLeft != nil && abs((oddLeft ?? 0) - expectedOddLeft) < 0.01)
#expect(evenRight != nil && abs((evenRight ?? 0) - expectedEvenRight) < 0.01)
}
/// Parse the first `<tag>VALUE</tag>` appearing after `marker` in `xml`.
private static func firstMarginValue(in xml: String, after marker: String, tag: String) -> Double? {
guard let markerRange: Range<String.Index> = xml.range(of: marker) else { return nil }
let tail: Substring = xml[markerRange.upperBound...]
let open: String = "<\(tag)>"
let close: String = "</\(tag)>"
guard let openRange: Range<Substring.Index> = tail.range(of: open),
let closeRange: Range<Substring.Index> = tail.range(of: close),
openRange.upperBound < closeRange.lowerBound
else { return nil }
return Double(tail[openRange.upperBound..<closeRange.lowerBound])
}
// MARK: - Scaling override
@Test("scaling override changes <millimeters>/<tenths> and scales page dims")
func scalingOverride() {
let customScaling: PageLayout.Scaling = PageLayout.Scaling(
millimeters: 5.0,
tenths: 30.0
)
let layout: PageLayout = PageLayout(
size: .a4,
orientation: .portrait,
scaling: customScaling
)
let score: Score = makeScore(pageLayout: layout)
let xml: String = score.toMusicXMLString()
#expect(hasDefaults(xml))
// Verify <millimeters> and <tenths> values.
let mmStr: String? = extractElement(tag: "millimeters", from: xml)
let tenthsStr: String? = extractElement(tag: "tenths", from: xml)
#expect(mmStr == "5")
#expect(tenthsStr == "30")
// Page height with custom scaling: A4 portrait height = 297 mm.
// tenthsPerMM = 30/5 = 6.0; height = 297 * 6.0 = 1782.0 tenths.
let tpm: Double = 30.0 / 5.0
let expectedHeight: Double = 297.0 * tpm
let heightStr: String? = extractElement(tag: "page-height", from: xml)
if let h: Double = heightStr.flatMap(Double.init) {
#expect(abs(h - expectedHeight) < 0.001)
}
}
// MARK: - Section-based score threads pageLayout through
@Test("section-based Score with pageLayout emits <defaults>")
func sectionBasedScoreEmitsDefaults() {
let layout: PageLayout = PageLayout(size: .a4, orientation: .portrait)
let score: Score = Score(
sections: [
ScoreSection(name: "Intro", parts: [
ScorePart(name: "lead", elements: [Note(.c, 4, dur: .whole)])
])
],
bpm: 120,
pageLayout: layout
)
let xml: String = score.toMusicXMLString()
#expect(hasDefaults(xml))
}
// MARK: - DSL flat init with pageLayout
@Test("DSL flat init with pageLayout emits <defaults>")
func dslFlatInitEmitsDefaults() {
let layout: PageLayout = PageLayout(size: .letter, orientation: .portrait)
let score: Score = Score(bpm: 120, pageLayout: layout) {
Part("Piano") {
Note(.c, 4, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
#expect(hasDefaults(xml))
}
// MARK: - DSL section init with pageLayout
@Test("DSL section init with pageLayout emits <defaults>")
func dslSectionInitEmitsDefaults() {
let layout: PageLayout = PageLayout(size: .a4, orientation: .landscape)
let score: Score = Score(bpm: 120, pageLayout: layout) {
Section("A") {
Part("lead") {
Note(.c, 4, dur: .whole)
}
}
}
let xml: String = score.toMusicXMLString()
#expect(hasDefaults(xml))
}
// MARK: - <defaults> appears before <part-list>
@Test("<defaults> block appears before <part-list> in document order")
func defaultsBeforePartList() {
let layout: PageLayout = PageLayout(size: .a4, orientation: .portrait)
let score: Score = makeScore(pageLayout: layout)
let xml: String = score.toMusicXMLString()
#expect(hasDefaults(xml))
guard let defaultsRange: Range<String.Index> = xml.range(of: "<defaults>"),
let partListRange: Range<String.Index> = xml.range(of: "<part-list>") else {
Issue.record("<defaults> or <part-list> not found in output")
return
}
#expect(defaultsRange.lowerBound < partListRange.lowerBound)
}
// MARK: - PageLayout.Margins uniform init
@Test("PageLayout.Margins uniform init sets all sides equal")
func marginsUniformInit() {
let margins: PageLayout.Margins = PageLayout.Margins(uniformMillimeters: 12.0)
#expect(margins.leftMillimeters == 12.0)
#expect(margins.rightMillimeters == 12.0)
#expect(margins.topMillimeters == 12.0)
#expect(margins.bottomMillimeters == 12.0)
}
// MARK: - PageLayout.Scaling default
@Test("PageLayout.Scaling default has 7mm = 40 tenths")
func scalingDefault() {
let s: PageLayout.Scaling = .default
#expect(s.millimeters == 7.0)
#expect(s.tenths == 40.0)
}
// MARK: - Margins default
@Test("PageLayout.Margins default has 15mm all sides")
func marginsDefault() {
let m: PageLayout.Margins = .default
#expect(m.leftMillimeters == 15.0)
#expect(m.rightMillimeters == 15.0)
#expect(m.topMillimeters == 15.0)
#expect(m.bottomMillimeters == 15.0)
}
// MARK: - tenthsPerMillimeter helper
@Test("tenthsPerMillimeter computed correctly from scaling")
func tenthsPerMillimeter() {
let layout: PageLayout = PageLayout()
// Default: 40.0 / 7.0
let expected: Double = 40.0 / 7.0
#expect(abs(layout.tenthsPerMillimeter - expected) < 1e-10)
}
// MARK: - PageSize portraitMillimeters
@Test("PageSize.portraitMillimeters returns correct values for all standard sizes")
func pageSizePortraitMillimeters() {
let letterPortrait: (width: Double, height: Double) = PageLayout.PageSize.letter.portraitMillimeters
#expect(letterPortrait.width == 215.9)
#expect(letterPortrait.height == 279.4)
let a4Portrait: (width: Double, height: Double) = PageLayout.PageSize.a4.portraitMillimeters
#expect(a4Portrait.width == 210.0)
#expect(a4Portrait.height == 297.0)
let a3Portrait: (width: Double, height: Double) = PageLayout.PageSize.a3.portraitMillimeters
#expect(a3Portrait.width == 297.0)
#expect(a3Portrait.height == 420.0)
let legalPortrait: (width: Double, height: Double) = PageLayout.PageSize.legal.portraitMillimeters
#expect(legalPortrait.width == 215.9)
#expect(legalPortrait.height == 355.6)
let tabloidPortrait: (width: Double, height: Double) = PageLayout.PageSize.tabloid.portraitMillimeters
#expect(tabloidPortrait.width == 279.4)
#expect(tabloidPortrait.height == 431.8)
}
}
+45
View File
@@ -98,4 +98,49 @@ struct PatternTests {
#expect(pat.next() == "mi")
#expect(pat.next() == "do") // wraps
}
@Test func offsetShiftsOnlyFirstPass() {
// First pass opens at index 1 and runs short; later cycles run full.
let pat: Pattern<Int> = Pattern.sequence([1, 2, 3], offset: 1)
#expect(pat.next() == 2)
#expect(pat.next() == 3)
#expect(pat.next() == 1) // full cycle from index 0
#expect(pat.next() == 2)
#expect(pat.next() == 3)
#expect(pat.next() == 1) // and again
}
@Test func offsetResetReturnsToOffsetStart() {
let pat: Pattern<Int> = Pattern.sequence([1, 2, 3], offset: 2)
#expect(pat.next() == 3)
#expect(pat.next() == 1)
pat.reset()
#expect(pat.next() == 3) // back to the offset start, not index 0
}
@Test func offsetCountsShortFirstPassAsACycle() {
// repeats: 2, offset: 1 → short pass [2,3] then one full [1,2,3].
let pat: Pattern<Int> = Pattern.sequence([1, 2, 3], repeats: 2, offset: 1)
#expect(pat.next() == 2)
#expect(pat.next() == 3)
#expect(pat.next() == 1)
#expect(pat.next() == 2)
#expect(pat.next() == 3)
#expect(pat.next() == nil)
#expect(pat.isExhausted)
}
@Test func offsetWrapsOutOfRange() {
// offset 4 on a 3-element list normalises to index 1.
let pat: Pattern<Int> = Pattern.sequence([1, 2, 3], offset: 4)
#expect(pat.next() == 2)
// Negative offsets wrap too: -1 → index 2.
let neg: Pattern<Int> = Pattern.sequence([1, 2, 3], offset: -1)
#expect(neg.next() == 3)
}
@Test func offsetOnEmptyValuesIsSafe() {
let pat: Pattern<Int> = Pattern<Int>.sequence([], offset: 5)
#expect(pat.next() == nil)
}
}
@@ -0,0 +1,84 @@
// PitchCollectionMapTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@Suite("PitchCollection scale mapping — re-assign by degree, correct spelling")
struct PitchCollectionMapTests {
private func cell(_ pitches: Pitch...) -> PitchCollection {
PitchCollection(pitches: pitches)
}
// MARK: - Plan worked examples
@Test func cMajorTriadToDMajor() throws {
let cMajor: Scale = try Scale.major(.c)
let dMajor: Scale = try Scale.major(.d)
let triad: PitchCollection = cell(.named(.c, 4), .named(.e, 4), .named(.g, 4))
let mapped: PitchCollection = try triad.mapped(from: cMajor, to: dMajor)
#expect(mapped.pitches == [.named(.d, 4), .named(.fSharp, 4), .named(.a, 4)])
}
@Test func cMajorTriadToEFlatMajor() throws {
let cMajor: Scale = try Scale.major(.c)
let eFlatMajor: Scale = try Scale.major(.eFlat)
let triad: PitchCollection = cell(.named(.c, 4), .named(.e, 4), .named(.g, 4))
let mapped: PitchCollection = try triad.mapped(from: cMajor, to: eFlatMajor)
#expect(mapped.pitches == [.named(.eFlat, 4), .named(.g, 4), .named(.bFlat, 4)])
}
// MARK: - referenceScale carried
@Test func mappedSetsTargetReferenceScale() throws {
let cMajor: Scale = try Scale.major(.c)
let gMajor: Scale = try Scale.major(.g)
let mapped: PitchCollection = try cell(.named(.c, 4)).mapped(from: cMajor, to: gMajor)
#expect(mapped.referenceScale == gMajor)
}
// MARK: - Mode change (major -> minor) keeps degree, changes colour
@Test func majorToMinorChangesThirdAndSixth() throws {
let cMajor: Scale = try Scale.major(.c)
let cMinor: Scale = try Scale.aeolian(.c)
let line: PitchCollection = cell(.named(.c, 4), .named(.e, 4), .named(.a, 4))
let mapped: PitchCollection = try line.mapped(from: cMajor, to: cMinor)
// Degree 0/2/5 of C natural minor = C / Eb / Ab.
#expect(mapped.pitches == [.named(.c, 4), .named(.eFlat, 4), .named(.aFlat, 4)])
}
// MARK: - Octave register survives across the octave boundary
@Test func mappingPreservesRegister() throws {
let cMajor: Scale = try Scale.major(.c)
let dMajor: Scale = try Scale.major(.d)
// B4 is degree 6 of C major; in D major degree 6 is C#5.
let mapped: PitchCollection = try cell(.named(.b, 4)).mapped(from: cMajor, to: dMajor)
#expect(mapped.pitches == [.named(.cSharp, 5)])
}
// MARK: - Degree-count mismatch: by-index with wrap
@Test func pentatonicToHeptatonicByIndex() throws {
let cPent: Scale = try Scale.majorPentatonic(.c) // C D E G A (5)
let cMajor: Scale = try Scale.major(.c) // C D E F G A B (7)
// Pentatonic degrees 0-1-2 (C-D-E) map to major degrees 0-1-2 (C-D-E).
let mapped: PitchCollection = try cell(.named(.c, 4), .named(.d, 4), .named(.e, 4))
.mapped(from: cPent, to: cMajor)
#expect(mapped.pitches == [.named(.c, 4), .named(.d, 4), .named(.e, 4)])
}
@Test func nonNamedPitchThrows() throws {
let cMajor: Scale = try Scale.major(.c)
let dMajor: Scale = try Scale.major(.d)
#expect(throws: ScaleError.self) {
_ = try cell(.midi(60)).mapped(from: cMajor, to: dMajor)
}
}
}
@@ -0,0 +1,132 @@
// PitchCollectionTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@Suite("PitchCollection — spelled cell ops + 12-tone row forms")
struct PitchCollectionTests {
// MARK: - Cell transformations
@Test func retrogradeReverses() {
let cell: PitchCollection = PitchCollection(pitches: [
.named(.c, 4), .named(.d, 4), .named(.e, 4),
])
#expect(cell.retrograde.pitches == [.named(.e, 4), .named(.d, 4), .named(.c, 4)])
}
@Test func transposedChromaticSpellsCorrectly() throws {
let cell: PitchCollection = PitchCollection(pitches: [
.named(.c, 4), .named(.d, 4), .named(.e, 4),
])
let up: PitchCollection = try cell.transposedChromatic(by: .majorThird)
#expect(up.pitches == [.named(.e, 4), .named(.fSharp, 4), .named(.gSharp, 4)])
}
@Test func invertedAroundAxisPreservesSpelling() throws {
let cell: PitchCollection = PitchCollection(pitches: [
.named(.c, 4), .named(.e, 4), .named(.g, 4),
])
let inv: PitchCollection = try cell.inverted(around: .named(.c, 4))
// C stays; E (M3 up) → Ab below; G (P5 up) → F below.
#expect(inv.pitches == [.named(.c, 4), .named(.aFlat, 3), .named(.f, 3)])
}
@Test func octaveReducedFoldsToPitchClasses() {
let cell: PitchCollection = PitchCollection(pitches: [
.named(.c, 2), .named(.fSharp, 6), .named(.bFlat, 3),
])
let reduced: PitchCollection = cell.octaveReduced
#expect(reduced.pitches == [.named(.c, 4), .named(.fSharp, 4), .named(.bFlat, 4)])
}
// MARK: - 12-tone row validation
private var chromaticRow: PitchCollection {
PitchCollection(pitches: [
.named(.c, 4), .named(.cSharp, 4), .named(.d, 4), .named(.dSharp, 4),
.named(.e, 4), .named(.f, 4), .named(.fSharp, 4), .named(.g, 4),
.named(.gSharp, 4), .named(.a, 4), .named(.aSharp, 4), .named(.b, 4),
])
}
@Test func isToneRowDetection() {
#expect(chromaticRow.isToneRow)
let short: PitchCollection = PitchCollection(pitches: [.named(.c, 4), .named(.d, 4)])
#expect(!short.isToneRow)
}
@Test func notToneRowThrows() {
let short: PitchCollection = PitchCollection(pitches: [.named(.c, 4), .named(.d, 4)])
#expect(throws: ToneRowError.self) {
_ = try short.toneRowMatrix()
}
}
@Test func primeIsRowAtPitchClassOctave() throws {
let prime: PitchCollection = try chromaticRow.toneRowPrime()
#expect(prime.pitches == chromaticRow.pitches)
}
@Test func inversionMirrorsAboutFirst() throws {
let inversion: PitchCollection = try chromaticRow.toneRowInversion()
// I0 of the ascending chromatic from C: C B A# A G# G F# F E D# D C#.
let expected: [Pitch] = [
.named(.c, 4), .named(.b, 4), .named(.aSharp, 4), .named(.a, 4),
.named(.gSharp, 4), .named(.g, 4), .named(.fSharp, 4), .named(.f, 4),
.named(.e, 4), .named(.dSharp, 4), .named(.d, 4), .named(.cSharp, 4),
]
#expect(inversion.pitches == expected)
}
@Test func transposedShiftsPitchClasses() throws {
let t1: PitchCollection = try chromaticRow.toneRowTransposed(1)
#expect(t1.pitches.first == .named(.cSharp, 4))
#expect(t1.pitches.last == .named(.c, 4))
}
@Test func retrogradeRowReverses() throws {
let retro: PitchCollection = try chromaticRow.toneRowRetrograde()
#expect(retro.pitches.first == .named(.b, 4))
#expect(retro.pitches.last == .named(.c, 4))
}
@Test func matrixStructure() throws {
let matrix: [[NoteName]] = try chromaticRow.toneRowMatrix()
#expect(matrix.count == 12)
#expect(matrix.allSatisfy { $0.count == 12 })
// Top row = prime.
#expect(matrix[0] == [
.c, .cSharp, .d, .dSharp, .e, .f, .fSharp, .g, .gSharp, .a, .aSharp, .b,
])
// Left column = inversion.
let leftColumn: [NoteName] = matrix.map { $0[0] }
#expect(leftColumn == [
.c, .b, .aSharp, .a, .gSharp, .g, .fSharp, .f, .e, .dSharp, .d, .cSharp,
])
// Main diagonal is all the tonic pitch-class (cell[i][i] returns to P0[0]).
for i: Int in 0..<12 {
#expect(matrix[i][i] == .c)
}
}
// MARK: - Row spelling preservation (flats survive)
@Test func rowSpellingPreservedAcrossForms() throws {
// A row spelling pc 6 as Gb (not F#) and pc 3 as Eb (not D#).
let flatRow: PitchCollection = PitchCollection(pitches: [
.named(.c, 4), .named(.dFlat, 4), .named(.d, 4), .named(.eFlat, 4),
.named(.e, 4), .named(.f, 4), .named(.gFlat, 4), .named(.g, 4),
.named(.aFlat, 4), .named(.a, 4), .named(.bFlat, 4), .named(.b, 4),
])
let t1: PitchCollection = try flatRow.toneRowTransposed(1)
// Every derived pitch-class is spelled via the row's own map — pc 6 = Gb.
#expect(t1.pitches.contains(.named(.gFlat, 4)))
#expect(!t1.pitches.contains(.named(.fSharp, 4)))
}
}
@@ -0,0 +1,99 @@
// PitchMapIntoRangeTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@Suite("Pitch.mapIntoRange — octave-fold into a register, spelling preserved")
struct PitchMapIntoRangeTests {
// MARK: - Named: octave fold preserving spelling
@Test func foldsUpIntoRange() {
let result: Pitch = Pitch.named(.c, 3)
.mapIntoRange(low: .named(.a, 4), high: .named(.a, 5))
#expect(result == .named(.c, 5))
}
@Test func foldsDownIntoRange() {
// C7 folded down into [A4, A5] → C5.
let result: Pitch = Pitch.named(.c, 7)
.mapIntoRange(low: .named(.a, 4), high: .named(.a, 5))
#expect(result == .named(.c, 5))
}
@Test func wideRangeFoldsUpToNearestRepresentative() {
// [A4, A6] spans two octaves; C3 below range → first C going up = C5.
let result: Pitch = Pitch.named(.c, 3)
.mapIntoRange(low: .named(.a, 4), high: .named(.a, 6))
#expect(result == .named(.c, 5))
}
@Test func wideRangeFoldsDownToNearestRepresentative() {
// C7 above range → first C going down = C6 (not C5).
let result: Pitch = Pitch.named(.c, 7)
.mapIntoRange(low: .named(.a, 4), high: .named(.a, 6))
#expect(result == .named(.c, 6))
}
@Test func alreadyInRangeReturnsUnchanged() {
let p: Pitch = Pitch.named(.c, 5)
#expect(p.mapIntoRange(low: .named(.a, 4), high: .named(.a, 5)) == p)
}
@Test func flatStaysFlatNeverRespelled() {
// A B♭ must come back a B♭, not an enharmonic A♯.
let result: Pitch = Pitch.named(.bFlat, 2)
.mapIntoRange(low: .named(.c, 4), high: .named(.c, 5))
#expect(result == .named(.bFlat, 4))
}
// MARK: - No representative → unchanged
@Test func noRepresentativeInSubOctaveRangeReturnsOriginal() {
// [C4, E4] spans < an octave; pitch class G has no member there.
let p: Pitch = Pitch.named(.g, 2)
#expect(p.mapIntoRange(low: .named(.c, 4), high: .named(.e, 4)) == p)
}
@Test func representativeExistsInSubOctaveRange() {
// [C4, E4]; D2 → D4 sits inside.
let result: Pitch = Pitch.named(.d, 2)
.mapIntoRange(low: .named(.c, 4), high: .named(.e, 4))
#expect(result == .named(.d, 4))
}
// MARK: - midi / freq cases
@Test func midiFoldsNumerically() {
// C3 = 48, into [A4=69, A5=81] → C5 = 72.
#expect(Pitch.midi(48).mapIntoRange(low: .midi(69), high: .midi(81)) == .midi(72))
}
@Test func freqFoldsByOctaveKeepingCents() {
// 110 Hz (A2) into [A4=440, A5=880] → 440 Hz.
if case .freq(let hz) = Pitch.freq(110.0)
.mapIntoRange(low: .freq(440.0), high: .freq(880.0)) {
#expect(abs(hz - 440.0) < 1e-9)
} else {
Issue.record("expected a .freq result")
}
}
// MARK: - Degenerate inputs → unchanged
@Test func restReturnsUnchanged() {
let r: Pitch = .rest
#expect(r.mapIntoRange(low: .named(.a, 4), high: .named(.a, 5)) == r)
}
@Test func invertedBoundsReturnOriginal() {
let p: Pitch = Pitch.named(.c, 3)
// high < low → no-op.
#expect(p.mapIntoRange(low: .named(.a, 5), high: .named(.a, 4)) == p)
}
}
@@ -0,0 +1,79 @@
// PitchTransposeTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@Suite("Pitch transposition — spelled octave bookkeeping + numeric shift")
struct PitchTransposeTests {
// MARK: - Named: spelling + octave
@Test func majorThirdUpStaysInOctave() throws {
let result: Pitch = try Pitch.named(.c, 4).transposed(by: .majorThird)
#expect(result == .named(.e, 4))
}
@Test func perfectFourthUpFromBCrossesOctave() throws {
// B4 + P4 = E5 (letter wraps past C).
let result: Pitch = try Pitch.named(.b, 4).transposed(by: .perfectFourth)
#expect(result == .named(.e, 5))
}
@Test func octaveUpAddsOneOctave() throws {
#expect(try Pitch.named(.c, 4).transposed(by: .octave) == .named(.c, 5))
}
@Test func minorThirdDownStaysInOctave() throws {
let result: Pitch = try Pitch.named(.fSharp, 4).transposed(by: .minorThird, .down)
#expect(result == .named(.dSharp, 4))
}
@Test func cFlatMajorSecondUpKeepsOctave() throws {
// C♭4 lives in octave 4; +M2 → D♭4.
let result: Pitch = try Pitch.named(.cFlat, 4).transposed(by: .majorSecond)
#expect(result == .named(.dFlat, 4))
}
@Test func bSharpFromANamedKeepsMidiConsistency() throws {
// A4 +aug2 = B♯4; MIDI must match A4 + 3 semitones.
let a4: Pitch = .named(.a, 4)
let result: Pitch = try a4.transposed(by: .augmentedSecond)
#expect(result == .named(.bSharp, 4))
#expect(result.midiNote == (a4.midiNote.map { $0 + 3 }))
}
// MARK: - Compound interval octave bookkeeping
@Test func majorNinthUpCrossesOctave() throws {
let majorNinth: Interval = try Interval(number: 9, quality: .major)
let result: Pitch = try Pitch.named(.c, 4).transposed(by: majorNinth)
#expect(result == .named(.d, 5))
}
// MARK: - MIDI / freq numeric shift (spelling lost)
@Test func midiShiftsBySemitones() throws {
#expect(try Pitch.midi(60).transposed(by: .majorThird) == .midi(64))
#expect(try Pitch.midi(60).transposed(by: .perfectFifth, .down) == .midi(53))
}
@Test func freqShiftsByRatio() throws {
let result: Pitch = try Pitch.freq(440.0).transposed(by: .octave)
guard case .freq(let hz) = result else {
Issue.record("expected .freq")
return
}
let expectedHz: Double = 880.0
let tolerance: Double = 1e-9
#expect(abs(hz - expectedHz) < tolerance)
}
@Test func restUnchanged() throws {
#expect(try Pitch.rest.transposed(by: .majorThird).isRest)
}
}
+1 -1
View File
@@ -245,7 +245,7 @@ struct PlateReverbTests {
"mulAdd(2,1) on silent/passthrough R must produce 1.0; got \(out[1][0])")
}
/// Phase 175 — branchless ring-buffer wrap exercised across many wraps of all
/// Branchless ring-buffer wrap exercised across many wraps of all
/// internal delay lines (preDelay + dl1L/R + dl2L/R + 4 input diffusers +
/// 2 modulated tank allpasses + 2 fixed tank allpasses). Drive a quiet
/// non-zero input over ~3 s and assert output stays finite + bounded.
@@ -20,7 +20,7 @@ import Foundation
/// ```
///
/// must hold at the peak value (1.0) indefinitely while gate > 0, not at
/// `levels[releaseNode + 1] = levels[2] = 0` (the pre-Phase-162 behavior).
/// `levels[releaseNode + 1] = levels[2] = 0` (the earlier behavior).
@MainActor
@Suite("LyrebirdProcess envelope holds at releaseNode level index")
struct LyrebirdProcessReleaseNodeHoldTest {
+1 -1
View File
@@ -450,7 +450,7 @@ struct RecordBufferTests {
#expect(rec.buffer.channelCount == 1)
}
// MARK: - Phase 173b fast-path coverage
// MARK: - Fast-path coverage
/// Default-mode hot path: `recLevel == 1`, `preLevel == 0`, `run == 1`, `loop == true`.
/// Pre-existing buffer content must be overwritten (pre == 0 → no read-back).
@@ -0,0 +1,667 @@
// RepeatStructureTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("RepeatStructure and Ending")
struct RepeatStructureTests {
// MARK: - 1. Model: Ending init preconditions and value semantics
@Test func endingValidInit() {
let ending: Ending = Ending(number: 1, startMeasure: 3, stopMeasure: 5)
#expect(ending.number == 1)
#expect(ending.startMeasure == 3)
#expect(ending.stopMeasure == 5)
}
@Test func endingNumberMustBeAtLeastOne() {
// Precondition: number >= 1.
// We verify valid boundary values; the precondition traps on 0 (not tested in-process).
let e1: Ending = Ending(number: 1, startMeasure: 1, stopMeasure: 1)
#expect(e1.number == 1)
let e2: Ending = Ending(number: 2, startMeasure: 2, stopMeasure: 4)
#expect(e2.number == 2)
}
@Test func endingSingleMeasureSpan() {
// startMeasure == stopMeasure is valid (single-measure ending).
let ending: Ending = Ending(number: 1, startMeasure: 4, stopMeasure: 4)
#expect(ending.startMeasure == ending.stopMeasure)
}
@Test func endingHashableEquality() {
let a: Ending = Ending(number: 1, startMeasure: 3, stopMeasure: 3)
let b: Ending = Ending(number: 1, startMeasure: 3, stopMeasure: 3)
let c: Ending = Ending(number: 2, startMeasure: 4, stopMeasure: 4)
#expect(a == b)
#expect(a != c)
var set: Set<Ending> = Set<Ending>()
set.insert(a)
set.insert(b)
#expect(set.count == 1)
set.insert(c)
#expect(set.count == 2)
}
// MARK: - 2. Model: RepeatStructure isEmpty / .none
@Test func repeatStructureNoneIsEmpty() {
#expect(RepeatStructure.none.isEmpty)
#expect(RepeatStructure.none.forwardRepeatMeasures.isEmpty)
#expect(RepeatStructure.none.backwardRepeatMeasures.isEmpty)
#expect(RepeatStructure.none.endings.isEmpty)
}
@Test func repeatStructureDefaultInit() {
let rs: RepeatStructure = RepeatStructure()
#expect(rs.isEmpty)
}
@Test func repeatStructureNonEmptyForward() {
let rs: RepeatStructure = RepeatStructure(forwardRepeatMeasures: [1])
#expect(!rs.isEmpty)
}
@Test func repeatStructureNonEmptyBackward() {
let rs: RepeatStructure = RepeatStructure(backwardRepeatMeasures: [4])
#expect(!rs.isEmpty)
}
@Test func repeatStructureNonEmptyEndings() {
let rs: RepeatStructure = RepeatStructure(
endings: [Ending(number: 1, startMeasure: 3, stopMeasure: 3)]
)
#expect(!rs.isEmpty)
}
@Test func repeatStructureHashableEquality() {
let a: RepeatStructure = RepeatStructure(
forwardRepeatMeasures: [1],
backwardRepeatMeasures: [4],
endings: [Ending(number: 1, startMeasure: 3, stopMeasure: 3)]
)
let b: RepeatStructure = RepeatStructure(
forwardRepeatMeasures: [1],
backwardRepeatMeasures: [4],
endings: [Ending(number: 1, startMeasure: 3, stopMeasure: 3)]
)
#expect(a == b)
}
// MARK: - 3. Score carries repeats
@Test func scoreDefaultRepeatsIsNone() {
let score: Score = Score(bpm: 120) {
Part("p") { Note(.c, 4, dur: .quarter) }
}
#expect(score.repeats.isEmpty)
#expect(score.repeats == RepeatStructure.none)
}
@Test func scorePassthroughRepeats() {
let rs: RepeatStructure = RepeatStructure(
forwardRepeatMeasures: [1],
backwardRepeatMeasures: [4],
endings: [
Ending(number: 1, startMeasure: 3, stopMeasure: 3),
Ending(number: 2, startMeasure: 4, stopMeasure: 4)
]
)
let score: Score = Score(
bpm: 120,
timeSignature: TimeSignature(4, 4),
repeats: rs
) {
Part("p") { Note(.c, 4, dur: .quarter) }
}
#expect(score.repeats == rs)
}
// MARK: - 4. Encoder: .none emits zero <barline> elements
@Test func noRepeatStructureEmitsNoBarlineElements() {
// A score with .none repeats (the default) must produce byte-identical
// output with respect to barlines — specifically, ZERO <barline> elements.
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 4, dur: .quarter)
Note(.d, 4, dur: .quarter)
Note(.e, 4, dur: .quarter)
Note(.f, 4, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
#expect(!xml.contains("<barline"),
"score with no RepeatStructure must emit zero <barline> elements; got:\n\(xml)")
}
// MARK: - 5. Encoder: forward repeat barline
@Test func forwardRepeatAtMeasureOneEmitsLeftBarline() {
// 4/4 score, 2 measures (8 beats); forward repeat at measure 1.
let score: Score = Score(
bpm: 120,
timeSignature: TimeSignature(4, 4),
repeats: RepeatStructure(forwardRepeatMeasures: [1])
) {
Part("p") {
Note(.c, 4, dur: .whole)
Note(.d, 4, dur: .whole)
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<barline location=\"left\">"),
"forward repeat must emit a left barline; got:\n\(xml)")
#expect(xml.contains("<repeat direction=\"forward\"/>"),
"forward repeat must emit <repeat direction=\"forward\"/>; got:\n\(xml)")
#expect(xml.contains("<bar-style>heavy-light</bar-style>"),
"forward repeat left barline must carry heavy-light bar-style; got:\n\(xml)")
// No right barline for measure 1 in this test.
#expect(!xml.contains("<repeat direction=\"backward\"/>"),
"no backward repeat should be present; got:\n\(xml)")
}
@Test func forwardRepeatAtMeasureTwoEmitsCorrectMeasure() {
// Forward repeat on measure 2 must NOT put the barline in measure 1.
let score: Score = Score(
bpm: 120,
timeSignature: TimeSignature(4, 4),
repeats: RepeatStructure(forwardRepeatMeasures: [2])
) {
Part("p") {
Note(.c, 4, dur: .whole) // measure 1
Note(.d, 4, dur: .whole) // measure 2
Note(.e, 4, dur: .whole) // measure 3
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<barline location=\"left\">"),
"forward repeat at measure 2 must emit a left barline; got:\n\(xml)")
#expect(xml.contains("<repeat direction=\"forward\"/>"),
"must emit forward repeat; got:\n\(xml)")
}
// MARK: - 6. Encoder: backward repeat barline
@Test func backwardRepeatEmitsRightBarline() {
// 4/4, 4 measures; backward repeat at measure 4.
let score: Score = Score(
bpm: 120,
timeSignature: TimeSignature(4, 4),
repeats: RepeatStructure(backwardRepeatMeasures: [4])
) {
Part("p") {
Note(.c, 4, dur: .whole)
Note(.d, 4, dur: .whole)
Note(.e, 4, dur: .whole)
Note(.f, 4, dur: .whole)
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<barline location=\"right\">"),
"backward repeat must emit a right barline; got:\n\(xml)")
#expect(xml.contains("<repeat direction=\"backward\"/>"),
"backward repeat must emit <repeat direction=\"backward\"/>; got:\n\(xml)")
#expect(xml.contains("<bar-style>light-heavy</bar-style>"),
"backward repeat right barline must carry light-heavy bar-style; got:\n\(xml)")
}
// MARK: - 7. Encoder: ending brackets
@Test func endingStartEmitsStartTypeOnLeftBarline() {
// 1st ending starts at measure 3 — measure 3's left barline carries
// <ending number="1" type="start"/>.
let score: Score = Score(
bpm: 120,
timeSignature: TimeSignature(4, 4),
repeats: RepeatStructure(
endings: [Ending(number: 1, startMeasure: 3, stopMeasure: 3)]
)
) {
Part("p") {
Note(.c, 4, dur: .whole)
Note(.d, 4, dur: .whole)
Note(.e, 4, dur: .whole)
Note(.f, 4, dur: .whole)
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<ending number=\"1\" type=\"start\"/>"),
"1st ending must emit <ending number=\"1\" type=\"start\"/>; got:\n\(xml)")
}
@Test func endingStopEmitsStopTypeOnRightBarline() {
// 1st ending stops at measure 3 — measure 3's right barline carries
// <ending number="1" type="stop"/>.
let score: Score = Score(
bpm: 120,
timeSignature: TimeSignature(4, 4),
repeats: RepeatStructure(
endings: [Ending(number: 1, startMeasure: 3, stopMeasure: 3)]
)
) {
Part("p") {
Note(.c, 4, dur: .whole)
Note(.d, 4, dur: .whole)
Note(.e, 4, dur: .whole)
Note(.f, 4, dur: .whole)
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<ending number=\"1\" type=\"stop\"/>"),
"1st ending must emit <ending number=\"1\" type=\"stop\"/>; got:\n\(xml)")
}
@Test func multiMeasureEndingEmitsContinueOnInteriorMeasures() {
// A 3-measure ending (bars 2–4): bar 2 left = start, bars 3 and 4 left
// = continue (so the volta bracket renders unbroken), bar 4 right = stop.
let score: Score = Score(
bpm: 120,
timeSignature: TimeSignature(4, 4),
repeats: RepeatStructure(
endings: [Ending(number: 1, startMeasure: 2, stopMeasure: 4)]
)
) {
Part("p") {
Note(.c, 4, dur: .whole)
Note(.d, 4, dur: .whole)
Note(.e, 4, dur: .whole)
Note(.f, 4, dur: .whole)
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<ending number=\"1\" type=\"start\"/>"),
"bar 2 must emit ending start; got:\n\(xml)")
#expect(xml.contains("<ending number=\"1\" type=\"continue\"/>"),
"interior bars must emit ending continue; got:\n\(xml)")
#expect(xml.contains("<ending number=\"1\" type=\"stop\"/>"),
"bar 4 must emit ending stop; got:\n\(xml)")
// Two interior measures (3 and 4) each carry a continue → 2 occurrences.
let continueCount: Int = xml.components(
separatedBy: "<ending number=\"1\" type=\"continue\"/>"
).count - 1
#expect(continueCount == 2,
"expected 2 continue brackets (bars 3 + 4); got \(continueCount);\n\(xml)")
}
@Test func fullRepeatWithTwoEndingsEmitsAllBarlines() {
// Forward repeat at bar 1, backward repeat at bar 4.
// 1st ending: bar 3, 2nd ending: bar 4.
let score: Score = Score(
bpm: 120,
timeSignature: TimeSignature(4, 4),
repeats: RepeatStructure(
forwardRepeatMeasures: [1],
backwardRepeatMeasures: [4],
endings: [
Ending(number: 1, startMeasure: 3, stopMeasure: 3),
Ending(number: 2, startMeasure: 4, stopMeasure: 4)
]
)
) {
Part("p") {
Note(.c, 4, dur: .whole)
Note(.d, 4, dur: .whole)
Note(.e, 4, dur: .whole)
Note(.f, 4, dur: .whole)
}
}
let xml: String = score.toMusicXMLString()
// Forward repeat.
#expect(xml.contains("<repeat direction=\"forward\"/>"),
"must have forward repeat; got:\n\(xml)")
// Backward repeat.
#expect(xml.contains("<repeat direction=\"backward\"/>"),
"must have backward repeat; got:\n\(xml)")
// 1st ending start and stop.
#expect(xml.contains("<ending number=\"1\" type=\"start\"/>"),
"must have 1st ending start; got:\n\(xml)")
#expect(xml.contains("<ending number=\"1\" type=\"stop\"/>"),
"must have 1st ending stop; got:\n\(xml)")
// 2nd ending start and stop.
#expect(xml.contains("<ending number=\"2\" type=\"start\"/>"),
"must have 2nd ending start; got:\n\(xml)")
#expect(xml.contains("<ending number=\"2\" type=\"stop\"/>"),
"must have 2nd ending stop; got:\n\(xml)")
}
// MARK: - 8. Encoder: barlines appear in EVERY part of a multi-part score
@Test func barlinesEmittedInEveryPart() {
// A two-part score with forward + backward repeats: both parts must carry
// the barline XML. Count occurrences of the forward repeat element.
let score: Score = Score(
bpm: 120,
timeSignature: TimeSignature(4, 4),
repeats: RepeatStructure(
forwardRepeatMeasures: [1],
backwardRepeatMeasures: [2]
)
) {
Part("soprano") {
Note(.c, 5, dur: .whole)
Note(.d, 5, dur: .whole)
}
Part("alto") {
Note(.g, 4, dur: .whole)
Note(.f, 4, dur: .whole)
}
}
let xml: String = score.toMusicXMLString()
// Count occurrences — must appear once per part (2 parts).
let forwardCount: Int = xml.components(
separatedBy: "<repeat direction=\"forward\"/>"
).count - 1
#expect(forwardCount == 2,
"forward repeat must appear once per part (2); got \(forwardCount);\n\(xml)")
let backwardCount: Int = xml.components(
separatedBy: "<repeat direction=\"backward\"/>"
).count - 1
#expect(backwardCount == 2,
"backward repeat must appear once per part (2); got \(backwardCount);\n\(xml)")
}
// MARK: - 9. Encoder: multi-voice — left/right barline emitted ONCE per measure
@Test func multiVoicePartEmitsBarlineOncePerMeasure() {
// A two-voice, two-measure part with a forward repeat at measure 1.
// The left barline at measure 1 must appear exactly ONCE (not once per voice).
let score: Score = Score(
bpm: 120,
timeSignature: TimeSignature(4, 4),
repeats: RepeatStructure(forwardRepeatMeasures: [1])
) {
Part("piano") {
Voice(1) {
Note(.e, 5, dur: .whole)
Note(.f, 5, dur: .whole)
}
Voice(2) {
Note(.c, 4, dur: .whole)
Note(.d, 4, dur: .whole)
}
}
}
let xml: String = score.toMusicXMLString()
// Left barline at measure 1 must appear exactly once.
let leftBarlineCount: Int = xml.components(
separatedBy: "<barline location=\"left\">"
).count - 1
#expect(leftBarlineCount == 1,
"multi-voice part must emit the left barline exactly once; got \(leftBarlineCount);\n\(xml)")
let forwardCount: Int = xml.components(
separatedBy: "<repeat direction=\"forward\"/>"
).count - 1
#expect(forwardCount == 1,
"forward repeat must appear exactly once in a single-part multi-voice score; got \(forwardCount);\n\(xml)")
}
// MARK: - 10. Parser: barline-less document yields .none
@Test func parserProducesNoneForBarlinelessDocument() throws {
// A plain score without any <barline> elements round-trips with
// repeats == .none.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.c, 4, dur: .whole)
Note(.d, 4, dur: .whole)
}
}
let data: Data = score.toMusicXMLData()
let parsed: Score = try Score.fromMusicXML(data: data)
#expect(parsed.repeats.isEmpty,
"a barline-less document must parse to RepeatStructure.none; got \(parsed.repeats)")
}
// MARK: - 11. Parser: forward and backward repeats parsed correctly
@Test func parserReadsForwardRepeatMeasure() throws {
let score: Score = Score(
bpm: 120,
timeSignature: TimeSignature(4, 4),
repeats: RepeatStructure(forwardRepeatMeasures: [1])
) {
Part("p") {
Note(.c, 4, dur: .whole)
Note(.d, 4, dur: .whole)
}
}
let data: Data = score.toMusicXMLData()
let parsed: Score = try Score.fromMusicXML(data: data)
#expect(parsed.repeats.forwardRepeatMeasures.contains(1),
"measure 1 must be in forwardRepeatMeasures after parse; got \(parsed.repeats)")
}
@Test func parserReadsBackwardRepeatMeasure() throws {
let score: Score = Score(
bpm: 120,
timeSignature: TimeSignature(4, 4),
repeats: RepeatStructure(backwardRepeatMeasures: [4])
) {
Part("p") {
Note(.c, 4, dur: .whole)
Note(.d, 4, dur: .whole)
Note(.e, 4, dur: .whole)
Note(.f, 4, dur: .whole)
}
}
let data: Data = score.toMusicXMLData()
let parsed: Score = try Score.fromMusicXML(data: data)
#expect(parsed.repeats.backwardRepeatMeasures.contains(4),
"measure 4 must be in backwardRepeatMeasures after parse; got \(parsed.repeats)")
}
@Test func parserReadsEndingPairs() throws {
let score: Score = Score(
bpm: 120,
timeSignature: TimeSignature(4, 4),
repeats: RepeatStructure(
forwardRepeatMeasures: [1],
backwardRepeatMeasures: [4],
endings: [
Ending(number: 1, startMeasure: 3, stopMeasure: 3),
Ending(number: 2, startMeasure: 4, stopMeasure: 4)
]
)
) {
Part("p") {
Note(.c, 4, dur: .whole)
Note(.d, 4, dur: .whole)
Note(.e, 4, dur: .whole)
Note(.f, 4, dur: .whole)
}
}
let data: Data = score.toMusicXMLData()
let parsed: Score = try Score.fromMusicXML(data: data)
let endings: [Ending] = parsed.repeats.endings
#expect(endings.count == 2,
"two endings must be parsed; got \(endings.count): \(endings)")
let e1: Ending? = endings.first { $0.number == 1 }
let e2: Ending? = endings.first { $0.number == 2 }
#expect(e1?.startMeasure == 3, "1st ending must start at measure 3; got \(String(describing: e1))")
#expect(e1?.stopMeasure == 3, "1st ending must stop at measure 3; got \(String(describing: e1))")
#expect(e2?.startMeasure == 4, "2nd ending must start at measure 4; got \(String(describing: e2))")
#expect(e2?.stopMeasure == 4, "2nd ending must stop at measure 4; got \(String(describing: e2))")
}
// MARK: - 12. Round-trip: full RepeatStructure encodes then parses back identically
@Test func roundTripRepeatStructure() throws {
let originalRepeats: RepeatStructure = RepeatStructure(
forwardRepeatMeasures: [1],
backwardRepeatMeasures: [4],
endings: [
Ending(number: 1, startMeasure: 3, stopMeasure: 3),
Ending(number: 2, startMeasure: 4, stopMeasure: 4)
]
)
let score: Score = Score(
bpm: 120,
timeSignature: TimeSignature(4, 4),
repeats: originalRepeats
) {
Part("p") {
Note(.c, 4, dur: .whole)
Note(.d, 4, dur: .whole)
Note(.e, 4, dur: .whole)
Note(.f, 4, dur: .whole)
}
}
let data: Data = score.toMusicXMLData()
let parsed: Score = try Score.fromMusicXML(data: data)
#expect(parsed.repeats == originalRepeats,
"round-trip must recover the exact RepeatStructure; got \(parsed.repeats)")
}
// MARK: - 13. flatten event count unchanged with vs without repeats
@Test func flattenEventCountUnchangedWithRepeats() {
let withoutRepeats: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.c, 4, dur: .whole)
Note(.d, 4, dur: .whole)
Note(.e, 4, dur: .whole)
Note(.f, 4, dur: .whole)
}
}
let withRepeats: Score = Score(
bpm: 120,
timeSignature: TimeSignature(4, 4),
repeats: RepeatStructure(
forwardRepeatMeasures: [1],
backwardRepeatMeasures: [4],
endings: [
Ending(number: 1, startMeasure: 3, stopMeasure: 3),
Ending(number: 2, startMeasure: 4, stopMeasure: 4)
]
)
) {
Part("p") {
Note(.c, 4, dur: .whole)
Note(.d, 4, dur: .whole)
Note(.e, 4, dur: .whole)
Note(.f, 4, dur: .whole)
}
}
let eventsWithout: [ScoreEvent] = withoutRepeats.parts[0].flatten()
let eventsWith: [ScoreEvent] = withRepeats.parts[0].flatten()
#expect(eventsWithout.count == eventsWith.count,
"flatten event count must be unchanged by RepeatStructure; got \(eventsWithout.count) vs \(eventsWith.count)")
}
// MARK: - 14. Round-trip: flatten event count preserved across encode/parse
@Test func roundTripFlattenEventCountPreserved() throws {
let score: Score = Score(
bpm: 120,
timeSignature: TimeSignature(4, 4),
repeats: RepeatStructure(
forwardRepeatMeasures: [1],
backwardRepeatMeasures: [4],
endings: [
Ending(number: 1, startMeasure: 3, stopMeasure: 3),
Ending(number: 2, startMeasure: 4, stopMeasure: 4)
]
)
) {
Part("p") {
Note(.c, 4, dur: .whole)
Note(.d, 4, dur: .whole)
Note(.e, 4, dur: .whole)
Note(.f, 4, dur: .whole)
}
}
let originalCount: Int = score.allEvents.count
let data: Data = score.toMusicXMLData()
let parsed: Score = try Score.fromMusicXML(data: data)
let parsedCount: Int = parsed.allEvents.count
#expect(originalCount == parsedCount,
"round-trip must preserve flatten event count; got \(originalCount) → \(parsedCount)")
}
// MARK: - 15. Multi-part round-trip: barlines appear in all parts exactly once per measure
@Test func multiPartRoundTripBarlinesInAllParts() throws {
let score: Score = Score(
bpm: 120,
timeSignature: TimeSignature(4, 4),
repeats: RepeatStructure(
forwardRepeatMeasures: [1],
backwardRepeatMeasures: [2]
)
) {
Part("part1") {
Note(.c, 5, dur: .whole)
Note(.d, 5, dur: .whole)
}
Part("part2") {
Note(.g, 4, dur: .whole)
Note(.f, 4, dur: .whole)
}
Part("part3") {
Note(.c, 3, dur: .whole)
Note(.d, 3, dur: .whole)
}
}
let xml: String = score.toMusicXMLString()
// Three parts — each must have the forward repeat once.
let forwardCount: Int = xml.components(
separatedBy: "<repeat direction=\"forward\"/>"
).count - 1
#expect(forwardCount == 3,
"three-part score must emit forward repeat once per part; got \(forwardCount)")
// The parser reads only from the first part — round-trip correctness.
let data: Data = Data(xml.utf8)
let parsed: Score = try Score.fromMusicXML(data: data)
#expect(parsed.repeats.forwardRepeatMeasures.contains(1),
"parsed score must have forward repeat at measure 1; got \(parsed.repeats)")
#expect(parsed.repeats.backwardRepeatMeasures.contains(2),
"parsed score must have backward repeat at measure 2; got \(parsed.repeats)")
}
@Test func finalEndingWithoutBackwardRepeatEmitsDiscontinue() throws {
// Backward repeat sits at the END of the 1st ending (bar 3). The 2nd
// ending (bar 4) continues forward with no repeat on its barline, so it
// must close OPEN — MusicXML `type="discontinue"` — while the 1st ending
// (which jumps back) closes with a downward hook — `type="stop"`.
let score: Score = Score(
bpm: 120,
timeSignature: TimeSignature(4, 4),
repeats: RepeatStructure(
forwardRepeatMeasures: [1],
backwardRepeatMeasures: [3],
endings: [
Ending(number: 1, startMeasure: 3, stopMeasure: 3),
Ending(number: 2, startMeasure: 4, stopMeasure: 4)
]
)
) {
Part("p") {
Note(.c, 4, dur: .whole)
Note(.d, 4, dur: .whole)
Note(.e, 4, dur: .whole)
Note(.f, 4, dur: .whole)
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<ending number=\"1\" type=\"stop\"/>"),
"1st ending (with backward repeat) closes with a hook; got:\n\(xml)")
#expect(xml.contains("<ending number=\"2\" type=\"discontinue\"/>"),
"final ending continues forward and must be open (discontinue); got:\n\(xml)")
#expect(!xml.contains("<ending number=\"2\" type=\"stop\"/>"),
"final ending must not close with a hook; got:\n\(xml)")
// Round-trip: the parser accepts `discontinue` as an ending close, so the
// 2nd ending survives and re-encodes as discontinue again.
let parsed: Score = try Score.fromMusicXML(data: score.toMusicXMLData())
let reEncoded: String = parsed.toMusicXMLString()
#expect(reEncoded.contains("<ending number=\"2\" type=\"discontinue\"/>"),
"discontinue ending must round-trip; got:\n\(reEncoded)")
}
}
@@ -0,0 +1,83 @@
// ScaleDiatonicTransposeTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@Suite("Scale diatonic transposition — move by scale degrees, stay in scale")
struct ScaleDiatonicTransposeTests {
private func cell(_ pitches: Pitch...) -> PitchCollection {
PitchCollection(pitches: pitches)
}
// MARK: - Plan worked example
@Test func upAThirdInCMajor() throws {
let cMajor: Scale = try Scale.major(.c)
let input: PitchCollection = cell(.named(.c, 4), .named(.d, 4), .named(.e, 4))
let result: PitchCollection = try cMajor.transposeDiatonic(input, byDegrees: 2)
// E-F-G, NOT E-F#-G#.
#expect(result.pitches == [.named(.e, 4), .named(.f, 4), .named(.g, 4)])
}
// MARK: - Direction + octave wrap
@Test func downASecondWrapsOctave() throws {
let cMajor: Scale = try Scale.major(.c)
let input: PitchCollection = cell(.named(.c, 4), .named(.d, 4))
let result: PitchCollection = try cMajor.transposeDiatonic(input, byDegrees: -1)
#expect(result.pitches == [.named(.b, 3), .named(.c, 4)])
}
@Test func upAnOctaveOfDegrees() throws {
let cMajor: Scale = try Scale.major(.c)
let input: PitchCollection = cell(.named(.e, 4), .named(.g, 4))
let result: PitchCollection = try cMajor.transposeDiatonic(input, byDegrees: 7)
#expect(result.pitches == [.named(.e, 5), .named(.g, 5)])
}
// MARK: - Non-C tonic register handling
@Test func diatonicInAMajorRegisters() throws {
let aMajor: Scale = try Scale.major(.a)
let input: PitchCollection = cell(.named(.a, 4), .named(.gSharp, 4))
let result: PitchCollection = try aMajor.transposeDiatonic(input, byDegrees: 1)
// A4 -> B4; G#4 is the leading tone just below A4, so +1 degree -> A4.
#expect(result.pitches == [.named(.b, 4), .named(.a, 4)])
}
// MARK: - Modal-vs-chromatic contrast (locks the distinction)
@Test func diatonicVersusChromaticThird() throws {
let cMajor: Scale = try Scale.major(.c)
let input: PitchCollection = cell(.named(.c, 4), .named(.d, 4), .named(.e, 4))
let diatonic: PitchCollection = try cMajor.transposeDiatonic(input, byDegrees: 2)
let chromatic: PitchCollection = try input.transposedChromatic(by: .majorThird)
#expect(diatonic.pitches == [.named(.e, 4), .named(.f, 4), .named(.g, 4)])
#expect(chromatic.pitches == [.named(.e, 4), .named(.fSharp, 4), .named(.gSharp, 4)])
#expect(diatonic.pitches != chromatic.pitches)
}
// MARK: - Chromatic (non-scale) pitch carries its alteration
@Test func nonScalePitchCarriesAlteration() throws {
let cMajor: Scale = try Scale.major(.c)
// F# is the raised 4th; up two degrees -> raised 6th = A#.
let input: PitchCollection = cell(.named(.fSharp, 4))
let result: PitchCollection = try cMajor.transposeDiatonic(input, byDegrees: 2)
#expect(result.pitches == [.named(.aSharp, 4)])
}
@Test func nonNamedPitchThrows() throws {
let cMajor: Scale = try Scale.major(.c)
let input: PitchCollection = cell(.midi(60))
#expect(throws: ScaleError.self) {
_ = try cMajor.transposeDiatonic(input, byDegrees: 1)
}
}
}
+136
View File
@@ -0,0 +1,136 @@
// ScaleTheoryTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@Suite("Scale — modes, symmetric scales, spelling, degree queries")
struct ScaleTheoryTests {
// MARK: - Diatonic mode spelling
@Test func dMajorUsesSevenDistinctLetters() throws {
let scale: Scale = try Scale.major(.d)
#expect(scale.degrees == [.d, .e, .fSharp, .g, .a, .b, .cSharp])
}
@Test func bFlatMajorSpelling() throws {
let scale: Scale = try Scale.major(.bFlat)
#expect(scale.degrees == [.bFlat, .c, .d, .eFlat, .f, .g, .a])
}
@Test func aHarmonicMinorRaisesSeventh() throws {
let scale: Scale = try Scale.harmonicMinor(.a)
#expect(scale.degrees == [.a, .b, .c, .d, .e, .f, .gSharp])
}
@Test func eFlatDorian() throws {
let scale: Scale = try Scale.dorian(.eFlat)
// Eb F Gb Ab Bb C Db
#expect(scale.degrees == [.eFlat, .f, .gFlat, .aFlat, .bFlat, .c, .dFlat])
}
// MARK: - Symmetric scale canonical spelling
@Test func wholeToneCSpelling() throws {
let scale: Scale = try Scale.wholeTone(.c)
#expect(scale.degrees == [.c, .d, .e, .fSharp, .gSharp, .aSharp])
}
@Test func chromaticCSpelling() throws {
let scale: Scale = try Scale.chromatic(.c)
#expect(scale.degrees == [
.c, .cSharp, .d, .dSharp, .e, .f,
.fSharp, .g, .gSharp, .a, .aSharp, .b,
])
}
@Test func octatonicHalfWholeCSpelling() throws {
let scale: Scale = try Scale.octatonicHalfWhole(.c)
#expect(scale.degrees == [.c, .dFlat, .eFlat, .e, .fSharp, .g, .a, .bFlat])
}
@Test func majorPentatonicCSpelling() throws {
let scale: Scale = try Scale.majorPentatonic(.c)
#expect(scale.degrees == [.c, .d, .e, .g, .a])
}
@Test func bluesCSpelling() throws {
let scale: Scale = try Scale.blues(.c)
#expect(scale.degrees == [.c, .eFlat, .f, .gFlat, .g, .bFlat])
}
// MARK: - Membership
@Test func containsByPitchClass() throws {
let cMajor: Scale = try Scale.major(.c)
#expect(cMajor.contains(.e))
#expect(cMajor.contains(.f))
#expect(!cMajor.contains(.fSharp))
// Enharmonic equivalent of B (Cb) is in C major by pitch-class.
#expect(cMajor.contains(.cFlat))
}
// MARK: - Degree lookup
@Test func degreeExactAndAltered() throws {
let cMajor: Scale = try Scale.major(.c)
#expect(cMajor.degree(of: .c)?.index == 0)
#expect(cMajor.degree(of: .g)?.index == 4)
#expect(cMajor.degree(of: .g)?.alteration == 0)
// F# is the raised fourth degree.
let raisedFourth: ScaleDegree? = cMajor.degree(of: .fSharp)
#expect(raisedFourth?.index == 3)
#expect(raisedFourth?.alteration == 1)
// Eb is the lowered third degree.
let loweredThird: ScaleDegree? = cMajor.degree(of: .eFlat)
#expect(loweredThird?.index == 2)
#expect(loweredThird?.alteration == -1)
}
// MARK: - noteName / pitch at degree
@Test func noteNameAtDegreeWraps() throws {
let cMajor: Scale = try Scale.major(.c)
#expect(cMajor.noteName(atDegree: 0) == .c)
#expect(cMajor.noteName(atDegree: 7) == .c) // wraps
#expect(cMajor.noteName(atDegree: 9) == .e) // 9 mod 7 = 2
#expect(cMajor.noteName(atDegree: -1) == .b) // wraps backward
}
@Test func pitchAtDegreeOctaveBookkeeping() throws {
let cMajor: Scale = try Scale.major(.c)
#expect(cMajor.pitch(atDegree: 0, octave: 4) == .named(.c, 4))
#expect(cMajor.pitch(atDegree: 2, octave: 4) == .named(.e, 4))
#expect(cMajor.pitch(atDegree: 7, octave: 4) == .named(.c, 5)) // octave up
}
@Test func pitchAtDegreeWithHighTonicBumpsOctave() throws {
// A major: third degree C# sits above A, so A4's third is C#5.
let aMajor: Scale = try Scale.major(.a)
#expect(aMajor.pitch(atDegree: 0, octave: 4) == .named(.a, 4))
#expect(aMajor.pitch(atDegree: 2, octave: 4) == .named(.cSharp, 5))
#expect(aMajor.pitch(atDegree: 5, octave: 4) == .named(.fSharp, 5))
#expect(aMajor.pitch(atDegree: 7, octave: 4) == .named(.a, 5))
}
// MARK: - Arbitrary pitch-set scale
@Test func scaleFromNamedPitches() throws {
let scale: Scale = try Scale(tonic: .c, pitches: [
.named(.c, 4), .named(.e, 4), .named(.g, 4),
])
#expect(scale.degrees == [.c, .e, .g])
#expect(scale.degree(of: .e)?.index == 1)
}
@Test func tonicMismatchThrows() {
#expect(throws: ScaleError.self) {
_ = try Scale(tonic: .c, degrees: [.d, .e, .f])
}
}
}
@@ -1,4 +1,4 @@
// Phase60ScatterCollectionTests.swift
// ScatterCollectionTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
@@ -0,0 +1,115 @@
// ScoreGenerativeTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("Score — Generate / PatternNotes algorithmic generators")
struct ScoreGenerativeTests {
// MARK: - Generate
@Test func generateMapsEachIndex() {
let elements: [ScoreElement] = Generate(4) { i in
Note(midi: 60 + i, dur: .quarter)
}
let part: ScorePart = ScorePart(name: "p", elements: elements)
let events: [ScoreEvent] = part.flatten()
#expect(events.count == 4)
#expect(events[0].pitch.midiNote == 60)
#expect(events[3].pitch.midiNote == 63)
#expect(events[1].beat == 1.0)
}
@Test func generateZeroCountYieldsEmpty() {
let elements: [ScoreElement] = Generate(0) { i in
Note(midi: 60 + i, dur: .quarter)
}
#expect(elements.isEmpty)
}
@Test func generateBodyMayEmitMultiplePerIndex() {
// Each index emits a note + a rest → 6 elements, 3 sounding events.
let elements: [ScoreElement] = Generate(3) { i in
Note(midi: 60 + i, dur: .eighth)
Rest(dur: .eighth)
}
#expect(elements.count == 6)
let events: [ScoreEvent] = ScorePart(name: "p", elements: elements).flatten()
#expect(events.count == 3)
}
@Test func generateLargeRun() {
let n: Int = 1000
let elements: [ScoreElement] = Generate(n) { i in
Note(midi: 48 + (i % 12), dur: .sixteenth)
}
#expect(elements.count == n)
}
// MARK: - PatternNotes (pitch pattern)
@Test func patternNotesFromPitchPattern() {
let pitchPat: Pattern<Pitch> = Pattern.sequence(
[.named(.c, 5), .named(.e, 5), .named(.g, 5)], repeats: 2
)
let elements: [ScoreElement] = PatternNotes(count: 6, pitches: pitchPat, dur: .eighth)
let events: [ScoreEvent] = ScorePart(name: "p", elements: elements).flatten()
#expect(events.count == 6)
#expect(events[0].pitch.midiNote == 72) // C5
#expect(events[1].pitch.midiNote == 76) // E5
#expect(events[2].pitch.midiNote == 79) // G5
#expect(events[3].pitch.midiNote == 72) // wrap
#expect(events[0].duration == 0.5) // eighth
}
@Test func patternNotesStopsWhenPitchPatternExhausts() {
// Pattern yields only 3 values; ask for 10 → stop at 3.
let pitchPat: Pattern<Pitch> = Pattern.sequence(
[.named(.c, 4), .named(.d, 4), .named(.e, 4)], repeats: 1
)
let elements: [ScoreElement] = PatternNotes(count: 10, pitches: pitchPat)
#expect(elements.count == 3)
}
@Test func patternNotesRhythmPatternDrivesDuration() {
let pitchPat: Pattern<Pitch> = Pattern.sequence([.named(.c, 4)], repeats: 4)
let rhythmPat: Pattern<NoteDuration> = Pattern.sequence([.quarter, .eighth])
let elements: [ScoreElement] = PatternNotes(
count: 4, pitches: pitchPat, durations: rhythmPat
)
let events: [ScoreEvent] = ScorePart(name: "p", elements: elements).flatten()
#expect(events.count == 4)
#expect(events[0].duration == 1.0) // quarter
#expect(events[1].duration == 0.5) // eighth
#expect(events[2].duration == 1.0) // sequence wraps
#expect(events[3].duration == 0.5)
}
// MARK: - PatternNotes (MIDI Double pattern)
@Test func patternNotesFromMidiPattern() {
let midiPat: Pattern<Double> = Pattern.series(start: 60.0, step: 2.0, length: 4)
let elements: [ScoreElement] = PatternNotes(count: 4, midi: midiPat, dur: .quarter)
let events: [ScoreEvent] = ScorePart(name: "p", elements: elements).flatten()
#expect(events.count == 4)
#expect(events[0].pitch.midiNote == 60)
#expect(events[1].pitch.midiNote == 62)
#expect(events[3].pitch.midiNote == 66)
}
@Test func patternNotesMidiRoundsAndClamps() {
// 59.6 → 60; -5 → 0 (clamp low); 200 → 127 (clamp high).
let midiPat: Pattern<Double> = Pattern.sequence([59.6, -5.0, 200.0], repeats: 1)
let elements: [ScoreElement] = PatternNotes(count: 3, midi: midiPat)
let events: [ScoreEvent] = ScorePart(name: "p", elements: elements).flatten()
#expect(events.count == 3)
#expect(events[0].pitch.midiNote == 60)
#expect(events[1].pitch.midiNote == 0)
#expect(events[2].pitch.midiNote == 127)
}
}
@@ -68,7 +68,7 @@ struct ScoreSMFBridgeTests {
}
@Test func timeSignatureMetaRoundTrips() throws {
let score: Score = Score(bpm: 120, timeSignature: (3, 8)) {
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(3, 8)) {
Part("p") { Note(.c, 4, dur: .quarter) }
}
let data: Data = score.toMIDIFileBytes()
@@ -165,7 +165,7 @@ struct ScoreSMFBridgeTests {
@Test func parsedFileToScorePreservesTempo() throws {
// Build a SMF with tempo = 100 BPM via Score.toMIDIFileBytes round-trip.
let original: Score = Score(bpm: 100, timeSignature: (3, 4)) {
let original: Score = Score(bpm: 100, timeSignature: TimeSignature(3, 4)) {
Part("Test") { Note(.c, 4, dur: .quarter) }
}
let data: Data = original.toMIDIFileBytes()
@@ -173,7 +173,7 @@ struct ScoreSMFBridgeTests {
let recovered: Score = parsed.toScore()
#expect(abs(recovered.bpm - 100.0) < 1e-3)
#expect(recovered.timeSignature == (3, 4))
#expect(recovered.timeSignature.tuple == (3, 4))
}
@Test func parsedFileToScoreUsesTrackNameForPart() throws {
+699
View File
@@ -0,0 +1,699 @@
// ScoreSectionTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
// MARK: - ScoreSectionTests
@MainActor
@Suite("ScoreSection — section-based score authoring")
struct ScoreSectionTests {
// MARK: - 1. Back-compat: flat Score(parts:) is unchanged
@Test func flatScorePartsUnchanged() {
let score: Score = Score(bpm: 120) {
Part("lead") {
Note(.c, 4, dur: .quarter)
Note(.e, 4, dur: .quarter)
}
Part("bass", channel: 1) {
Note(.c, 2, dur: .half)
}
}
#expect(score.parts.count == 2)
#expect(score.rehearsalMarks.isEmpty)
let leadEvents: [ScoreEvent] = score.parts[0].flatten()
#expect(leadEvents.count == 2)
#expect(leadEvents[0].beat == 0.0)
#expect(leadEvents[1].beat == 1.0)
}
// MARK: - 2. Two sections concatenate with continuous global measure numbers
@Test func twoSectionsContinuousGlobalMeasures() {
// Section A: 4/4, 1 bar (measures 1)
// Section B: 4/4, 1 bar (measures 2)
// Both sections have the same "lead" part.
let score: Score = Score(bpm: 120) {
Section("A") {
Part("lead") {
Note(.c, 4, dur: .whole)
}
}
Section("B") {
Part("lead") {
Note(.g, 4, dur: .whole)
}
}
}
#expect(score.parts.count == 1)
// Section A lands at measure 1, Section B at measure 2.
#expect(score.rehearsalMarks[1] == "A")
#expect(score.rehearsalMarks[2] == "B")
// The flat part must have 2 beats from section A (4 beats whole) +
// 2 beats from section B = 8 beats total (two wholes).
let events: [ScoreEvent] = score.parts[0].flatten()
#expect(events.count == 2)
// First note at beat 0, second at beat 4 (after one 4/4 bar).
#expect(abs(events[0].beat - 0.0) < 1e-12)
#expect(abs(events[1].beat - 4.0) < 1e-12)
}
// MARK: - 3. TACET instrument gets rest-filled and stays bar-aligned
@Test func tacetInstrumentFillsWithRests() {
// Section A (4/4, 1 bar): "lead" plays, "bass" is TACET.
// Section B (4/4, 1 bar): "bass" plays, "lead" is TACET.
let score: Score = Score(bpm: 120) {
Section("A") {
Part("lead") {
Note(.c, 4, dur: .whole)
}
}
Section("B") {
Part("bass") {
Note(.c, 2, dur: .whole)
}
}
}
#expect(score.parts.count == 2)
// "lead" should have: whole-note in section A + rest in section B.
// When flattened: 1 sounding event at beat 0, rest is not a sounding event.
let leadPart: ScorePart = score.parts[0]
#expect(leadPart.id == "lead")
let leadEvents: [ScoreEvent] = leadPart.flatten()
#expect(leadEvents.count == 1)
#expect(abs(leadEvents[0].beat - 0.0) < 1e-12)
// "bass" should have: rest in section A + whole-note in section B.
// The whole-note in section B starts at beat 4 (after the 4/4 section A).
let bassPart: ScorePart = score.parts[1]
#expect(bassPart.id == "bass")
let bassEvents: [ScoreEvent] = bassPart.flatten()
#expect(bassEvents.count == 1)
#expect(abs(bassEvents[0].beat - 4.0) < 1e-12)
}
// MARK: - 3b. A present-but-short part is padded to the section's longest part
@Test func presentShortPartPaddedToSectionSpan() {
// Section A (4/4): violin plays 1 bar, cello plays 3 bars. The violin must
// be rest-padded to the section's full span (3 bars) so every present part
// bar-aligns to the last measure expressed across the parts.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Section("A") {
Part("violin") {
Note(.c, 5, dur: .whole) // 1 bar
}
Part("cello") {
Note(.c, 3, dur: .whole)
Note(.d, 3, dur: .whole)
Note(.e, 3, dur: .whole) // 3 bars
}
}
}
// Both parts span 3 full bars (12 quarter-beats) after padding.
#expect(abs(score.parts[0].lastBeat() - 4.0) < 1e-12) // violin sounds 1 bar
#expect(abs(score.totalBeats - 12.0) < 1e-12) // section spans 3 bars
// The encoded violin part has 3 measures (padded), matching the cello.
let xml: String = score.toMusicXMLString()
let violinBlock: String = {
guard let r: Range<String.Index> = xml.range(of: "<part id=\"P1\">"),
let e: Range<String.Index> = xml.range(of: "</part>", range: r.upperBound..<xml.endIndex)
else { return "" }
return String(xml[r.upperBound..<e.lowerBound])
}()
#expect(violinBlock.components(separatedBy: "<measure number=").count - 1 == 3)
}
// MARK: - 4. Rehearsal marks land at correct global measures with section names
@Test func rehearsalMarksAtCorrectGlobalMeasures() {
// Three 4/4 sections of varying lengths:
// Intro: 2 bars (whole notes fill 2 bars of 4/4), A: 1 bar, B: 3 bars.
// Build 2-bar Intro: two whole notes.
let score: Score = Score(bpm: 120) {
Section("Intro") {
Part("lead") {
Note(.c, 4, dur: .whole)
Note(.d, 4, dur: .whole)
}
}
Section("A") {
Part("lead") {
Note(.e, 4, dur: .whole)
}
}
Section("B") {
Part("lead") {
Note(.f, 4, dur: .whole)
Note(.g, 4, dur: .whole)
Note(.a, 4, dur: .whole)
}
}
}
// Intro spans bars 1–2, A bar 3, B bars 4–6.
#expect(score.rehearsalMarks[1] == "Intro")
#expect(score.rehearsalMarks[3] == "A")
#expect(score.rehearsalMarks[4] == "B")
// Bars 2, 5, 6 must not carry rehearsal marks.
#expect(score.rehearsalMarks[2] == nil)
#expect(score.rehearsalMarks[5] == nil)
// Also confirm that the score has the right total beats: 6 wholes = 24 beats.
let events: [ScoreEvent] = score.parts[0].flatten()
#expect(events.count == 6)
#expect(abs(events[5].beat - 20.0) < 1e-12) // last note: 5 whole notes × 4 beats = 20
}
// MARK: - 5. Section's local tempoChange is offset into the global map
@Test func sectionTempoChangeOffsetCorrectly() {
// Section A: 4/4, 1 bar. TempoChange at local measure 1 → global measure 1.
// Section B: 4/4, 2 bars. TempoChange at local measure 2 → global measure 3.
let score: Score = Score(bpm: 120) {
Section("A", tempoChanges: [TempoChange(measure: 1, bpm: 80)]) {
Part("lead") { Note(.c, 4, dur: .whole) }
}
Section("B", tempoChanges: [TempoChange(measure: 2, bpm: 160)]) {
Part("lead") {
Note(.d, 4, dur: .whole)
Note(.e, 4, dur: .whole)
}
}
}
// Global tempoChanges should have:
// measure 1, bpm 80 (from section A local measure 1 + offset 0)
// measure 3, bpm 160 (from section B local measure 2 + offset 1)
let tc: [TempoChange] = score.tempoChanges
// There are 2 entries (both are >= 1 local measures; the base bpm is score.bpm).
#expect(tc.count == 2)
let tc1: TempoChange? = tc.first { $0.measure == 1 }
let tc3: TempoChange? = tc.first { $0.measure == 3 }
#expect(tc1 != nil)
#expect(tc3 != nil)
#expect(abs((tc1?.bpm ?? 0) - 80.0) < 1e-10)
#expect(abs((tc3?.bpm ?? 0) - 160.0) < 1e-10)
}
// MARK: - 6. Section's local repeat structure is offset correctly
@Test func sectionRepeatsOffsetCorrectly() {
// Section A: 1 bar with a forward repeat at local bar 1 and backward at local bar 1.
// Section B: 2 bars with backward repeat at local bar 2.
let sectionARepeats: RepeatStructure = RepeatStructure(
forwardRepeatMeasures: [1],
backwardRepeatMeasures: [1]
)
let sectionBRepeats: RepeatStructure = RepeatStructure(
backwardRepeatMeasures: [2]
)
let score: Score = Score(bpm: 120) {
Section("A", repeats: sectionARepeats) {
Part("lead") { Note(.c, 4, dur: .whole) }
}
Section("B", repeats: sectionBRepeats) {
Part("lead") {
Note(.d, 4, dur: .whole)
Note(.e, 4, dur: .whole)
}
}
}
// Section A occupies global bar 1; its forward + backward repeat are at global bar 1.
// Section B occupies global bars 2–3; its backward repeat is at global bar 3.
#expect(score.repeats.forwardRepeatMeasures.contains(1))
#expect(score.repeats.backwardRepeatMeasures.contains(1))
#expect(score.repeats.backwardRepeatMeasures.contains(3))
// Global bar 2 has no backward repeat.
#expect(!score.repeats.backwardRepeatMeasures.contains(2))
}
// MARK: - 7. Section meter changes are reflected in the global meterMap
@Test func sectionMeterMapOffsetAndMerged() {
// Section A: 4/4, 1 bar.
// Section B: 3/4, 1 bar.
let section3_4: MeterMap = MeterMap(TimeSignature(3, 4))
let score: Score = Score(bpm: 120) {
Section("A") {
Part("lead") { Note(.c, 4, dur: .whole) }
}
Section("B", meterMap: section3_4) {
Part("lead") {
Note(.g, 4, dur: .quarter)
Note(.a, 4, dur: .quarter)
Note(.b, 4, dur: .quarter)
}
}
}
// Global meter: 4/4 at bar 1, 3/4 at bar 2.
#expect(score.meterMap.segments.count == 2)
let bar1sig: TimeSignature = score.meterMap.timeSignature(atBar: 1)
let bar2sig: TimeSignature = score.meterMap.timeSignature(atBar: 2)
#expect(bar1sig.numerator == 4 && bar1sig.denominator == 4)
#expect(bar2sig.numerator == 3 && bar2sig.denominator == 4)
// Flattened events: 1 whole in section A (beat 0), 3 quarters in section B
// (beats 4, 5, 6 — since section A is 4 quarters long).
let events: [ScoreEvent] = score.parts[0].flatten()
#expect(events.count == 4)
#expect(abs(events[0].beat - 0.0) < 1e-12)
#expect(abs(events[1].beat - 4.0) < 1e-12)
#expect(abs(events[2].beat - 5.0) < 1e-12)
#expect(abs(events[3].beat - 6.0) < 1e-12)
}
// MARK: - 8. Part(id:) defaults to name; matching by id across sections
@Test func partIDDefaultsToName() {
let part: ScorePart = Part("lead") { Note(.c, 4, dur: .quarter) }
#expect(part.id == "lead")
#expect(part.name == "lead")
}
@Test func partIDExplicitOverride() {
let part: ScorePart = Part("Lead Guitar", id: "lead") {
Note(.c, 4, dur: .quarter)
}
#expect(part.id == "lead")
#expect(part.name == "Lead Guitar")
}
// MARK: - 9. Cross-section matching by id, even with different display names
@Test func matchByIDDifferentNameAcrossSections() {
// Section A: instrument with id "lead" named "Solo Lead"
// Section B: same instrument id "lead" but named "Rhythm Lead"
// They should merge into a single flat part.
let score: Score = Score(bpm: 120) {
Section("A") {
Part("Solo Lead", id: "lead") {
Note(.c, 5, dur: .whole)
}
}
Section("B") {
Part("Rhythm Lead", id: "lead") {
Note(.e, 5, dur: .whole)
}
}
}
// One part total, identified by the first-seen name "Solo Lead".
#expect(score.parts.count == 1)
let p: ScorePart = score.parts[0]
#expect(p.id == "lead")
#expect(p.name == "Solo Lead") // first-seen name wins
// Both notes should appear: C5 at beat 0, E5 at beat 4.
let events: [ScoreEvent] = p.flatten()
#expect(events.count == 2)
#expect(abs(events[0].beat - 0.0) < 1e-12)
#expect(abs(events[1].beat - 4.0) < 1e-12)
let midiNotes: [Int] = events.compactMap { $0.pitch.midiNote }.sorted()
#expect(midiNotes == [72, 76]) // C5=72, E5=76
}
// MARK: - 10. Flatten / playback sequences events with correct global beat offsets
@Test func flattenedEventsHaveCorrectGlobalBeats() {
// Three 4/4 sections, each 1 bar.
// Section A: quarter note C4
// Section B: half note E4
// Section C: whole note G4
let score: Score = Score(bpm: 120) {
Section("A") {
Part("p") { Note(.c, 4, dur: .quarter) }
}
Section("B") {
Part("p") { Note(.e, 4, dur: .half) }
}
Section("C") {
Part("p") { Note(.g, 4, dur: .whole) }
}
}
let events: [ScoreEvent] = score.parts[0].flatten()
#expect(events.count == 3)
// Section A: beat 0 (bar 1 starts at beat 0)
#expect(abs(events[0].beat - 0.0) < 1e-12)
// Section B: beat 4 (bar 2 starts at beat 4)
#expect(abs(events[1].beat - 4.0) < 1e-12)
// Section C: beat 8 (bar 3 starts at beat 8)
#expect(abs(events[2].beat - 8.0) < 1e-12)
}
// MARK: - 11. MusicXML output contains rehearsal marks at correct measures
@Test func musicXMLContainsRehearsalMarks() {
let score: Score = Score(bpm: 120) {
Section("Intro") {
Part("p") { Note(.c, 4, dur: .whole) }
}
Section("A") {
Part("p") { Note(.g, 4, dur: .whole) }
}
}
let xml: String = score.toMusicXMLString()
// Measure 1 should contain a rehearsal "Intro".
#expect(xml.contains("<rehearsal>Intro</rehearsal>"))
// Measure 2 should contain a rehearsal "A".
#expect(xml.contains("<rehearsal>A</rehearsal>"))
}
@Test func rehearsalMarksAsStaffTextEmitsBoxedWords() {
// Multi-part score so the system-object constraint (mark in the first part
// only) is exercised for the <words> path too.
let score: Score = Score(bpm: 120) {
Section("Intro") {
Part("lead") { Note(.c, 4, dur: .whole) }
Part("bass") { Note(.c, 2, dur: .whole) }
}
Section("A") {
Part("lead") { Note(.g, 4, dur: .whole) }
Part("bass") { Note(.g, 2, dur: .whole) }
}
}
// Default: standard <rehearsal> elements, no <words>.
let standard: String = score.toMusicXMLString()
#expect(standard.contains("<rehearsal>Intro</rehearsal>"))
#expect(!standard.contains("<words"))
// As staff text: boxed <words>, verbatim labels, no <rehearsal>.
let introBox: String = "<words enclosure=\"rectangle\" font-weight=\"bold\">Intro</words>"
let aBox: String = "<words enclosure=\"rectangle\" font-weight=\"bold\">A</words>"
let asWords: String = score.toMusicXMLString(rehearsalMarksAsStaffText: true)
#expect(asWords.contains(introBox))
#expect(asWords.contains(aBox))
#expect(!asWords.contains("<rehearsal>"))
// System object: each label appears exactly once (first part only).
#expect(asWords.components(separatedBy: introBox).count - 1 == 1)
#expect(asWords.components(separatedBy: aBox).count - 1 == 1)
// The Data convenience honours the flag too.
let dataString: String = String(
decoding: score.toMusicXMLData(rehearsalMarksAsStaffText: true),
as: UTF8.self
)
#expect(dataString.contains(introBox))
}
// MARK: - 12. Rehearsal marks only appear in the first part (system objects)
@Test func rehearsalMarksOnlyInFirstPart() {
let score: Score = Score(bpm: 120) {
Section("Verse") {
Part("lead") { Note(.c, 4, dur: .whole) }
Part("bass") { Note(.c, 2, dur: .whole) }
}
Section("Chorus") {
Part("lead") { Note(.g, 4, dur: .whole) }
Part("bass") { Note(.g, 2, dur: .whole) }
}
}
let xml: String = score.toMusicXMLString()
// Count rehearsal mark occurrences — should be exactly 2 (one per section,
// both in the first part only).
let verseCount: Int = xml.components(separatedBy: "<rehearsal>Verse</rehearsal>").count - 1
let chorusCount: Int = xml.components(separatedBy: "<rehearsal>Chorus</rehearsal>").count - 1
#expect(verseCount == 1)
#expect(chorusCount == 1)
}
// MARK: - 13. Two consecutive same-meter sections deduplicate segment
@Test func consecutiveSameMeterSectionsDeduplicateSegment() {
let score: Score = Score(bpm: 120) {
Section("A") {
Part("p") { Note(.c, 4, dur: .whole) }
}
Section("B") {
Part("p") { Note(.g, 4, dur: .whole) }
}
}
// Both sections are default 4/4. The global meterMap should have exactly
// one segment (deduplicated consecutive equal signatures).
#expect(score.meterMap.segments.count == 1)
#expect(score.meterMap.timeSignature(atBar: 1).numerator == 4)
}
// MARK: - 14. Section DSL builder produces correct ScoreSection
@Test func sectionDSLBuilderProducesCorrectSection() {
let section: ScoreSection = Section("MySection", tempoChanges: [TempoChange(measure: 1, bpm: 90)]) {
Part("p") { Note(.c, 4, dur: .whole) }
}
#expect(section.name == "MySection")
#expect(section.parts.count == 1)
#expect(section.tempoChanges.count == 1)
#expect(abs(section.tempoChanges[0].bpm - 90.0) < 1e-10)
#expect(section.tempoChanges[0].measure == 1)
}
// MARK: - 15. ScoreSectionBuilder array initializer
@Test func scoreArraySectionInit() {
let sections: [ScoreSection] = [
ScoreSection(name: "X", parts: [
ScorePart(name: "p", elements: [Note(.c, 4, dur: .whole)])
]),
ScoreSection(name: "Y", parts: [
ScorePart(name: "p", elements: [Note(.g, 4, dur: .whole)])
])
]
let score: Score = Score(sections: sections, bpm: 100)
#expect(score.parts.count == 1)
#expect(score.rehearsalMarks[1] == "X")
#expect(score.rehearsalMarks[2] == "Y")
}
// MARK: - First-section anacrusis keeps TACET parts aligned
@Test func firstSectionAnacrusisKeepsTacetAligned() {
// Section A: 4/4 with a 1-beat pickup. "lead" plays the pickup quarter +
// a full bar (1 + 4 = 5 beats); "bass" is TACET. Section B: "bass" plays.
// The bass's section-B onset must be at global beat 5 (pickup 1 + bar 4),
// not 4 — i.e. the TACET fill must include the anacrusis.
let pickup: Fraction = Fraction(num: 1, den: 1) // one quarter
let score: Score = Score(bpm: 120) {
Section("A", meterMap: MeterMap(TimeSignature(4, 4), anacrusis: pickup)) {
Part("lead") {
Note(.c, 5, dur: .quarter) // pickup
Note(.d, 5, dur: .whole) // bar 1
}
}
Section("B") {
Part("bass") {
Note(.c, 2, dur: .whole)
}
}
}
let bassPart: ScorePart = score.parts.first { $0.id == "bass" } ?? score.parts[1]
let bassEvents: [ScoreEvent] = bassPart.flatten()
#expect(bassEvents.count == 1)
#expect(abs(bassEvents[0].beat - 5.0) < 1e-12,
"TACET bass must be padded by pickup(1) + bar(4) = 5 beats before section B")
}
// MARK: - Key signature: first section wins (rendered in measure 1)
@Test func firstSectionKeySignatureWins() {
// Section A declares G major, section B declares D major. The assembled
// score's global key is G major (measure 1 belongs to the first section).
let score: Score = Score(bpm: 120) {
Section("A", keySignature: .gMajor) {
Part("lead") { Note(.g, 4, dur: .whole) }
}
Section("B", keySignature: .dMajor) {
Part("lead") { Note(.d, 4, dur: .whole) }
}
}
#expect(score.keySignature == .gMajor)
}
@Test func pickupOnlySectionFloorsToOneMeasureNoCollision() {
// A first section whose entire content fits within its pickup would make
// _measureSpan return 0; flooring to 1 measure must keep measure offsets
// distinct so the next section (with a DIFFERENT meter) does not collide a
// meter segment / rehearsal mark at the same global bar (which previously
// tripped MeterMap's duplicate-startBar precondition).
let pickup: Fraction = Fraction(num: 1, den: 1) // one quarter == content below
let score: Score = Score(bpm: 120) {
Section("P", meterMap: MeterMap(TimeSignature(4, 4), anacrusis: pickup)) {
Part("lead") { Note(.c, 5, dur: .quarter) } // fits within the pickup
}
Section("Q", meterMap: MeterMap(TimeSignature(3, 4))) {
Part("lead") { Note(.d, 5, dur: .dotted(.half)) }
}
}
// Distinct rehearsal marks at distinct global measures (no clobber).
#expect(score.rehearsalMarks[1] == "P")
#expect(score.rehearsalMarks[2] == "Q")
// Encoding must not trap (the meter segments land at distinct bars).
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<rehearsal>P</rehearsal>"))
#expect(xml.contains("<rehearsal>Q</rehearsal>"))
}
@Test func firstSectionNilKeyFallsBackToCallerKey() {
// First section has no key override → the caller-supplied score key wins.
let score: Score = Score(bpm: 120, keySignature: .fMajor) {
Section("A") {
Part("lead") { Note(.f, 4, dur: .whole) }
}
Section("B", keySignature: .dMajor) {
Part("lead") { Note(.d, 4, dur: .whole) }
}
}
#expect(score.keySignature == .fMajor)
}
// MARK: - Score-level timeSignature applies to sections
@Test func scoreTimeSignatureAppliesToSectionsWithoutMeterMap() {
// Score-level 3/4 governs section A (no meterMap); section B overrides to 2/4.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(3, 4)) {
Section("A") {
Part("p") {
Note(.c, 5, dur: .quarter)
Note(.d, 5, dur: .quarter)
Note(.e, 5, dur: .quarter) // 3 quarters = one bar of 3/4
}
}
Section("B", meterMap: MeterMap(TimeSignature(2, 4))) {
Part("p") {
Note(.c, 5, dur: .quarter)
Note(.d, 5, dur: .quarter) // 2 quarters = one bar of 2/4
}
}
}
#expect(score.meterMap.timeSignature(atBar: 1).tuple == (3, 4)) // inherited
#expect(score.meterMap.timeSignature(atBar: 2).tuple == (2, 4)) // override wins
}
@Test func sectionsDefaultTo4_4WhenNoScoreTimeSignature() {
let score: Score = Score(bpm: 120) {
Section("A") {
Part("p") { Note(.c, 5, dur: .whole) }
}
}
#expect(score.meterMap.timeSignature(atBar: 1).tuple == (4, 4))
}
@Test func scoreSectionsAcceptTimeSignatureAndKeySignatureTogether() {
// The previously-impossible combination: timeSignature + keySignature + sections.
let score: Score = Score(
bpm: 120,
timeSignature: TimeSignature(4, 4),
keySignature: .dMinor
) {
Section("A") {
Part("p") { Note(.c, 5, dur: .whole) }
}
}
#expect(score.keySignature == .dMinor)
#expect(score.meterMap.timeSignature(atBar: 1).tuple == (4, 4))
#expect(score.rehearsalMarks[1] == "A")
}
// MARK: - Section end barlines
@Test func sectionEndBarlineRecordedAtLastGlobalMeasure() {
// Section A: 2 bars of 4/4 → last bar is global measure 2.
// Section B: 1 bar → last bar is global measure 3.
let score: Score = Score {
Section("A", endBarline: .double) {
Part("p") {
Note(.c, 5, dur: .whole)
Note(.d, 5, dur: .whole)
}
}
Section("B", endBarline: .final) {
Part("p") { Note(.e, 5, dur: .whole) }
}
}
#expect(score.measureBarlines[2] == .double)
#expect(score.measureBarlines[3] == .final)
// Sections without endBarline contribute nothing.
#expect(score.measureBarlines.count == 2)
}
@Test func sectionEndBarlineEmitsBarStyle() {
let score: Score = Score {
Section("A", endBarline: .double) {
Part("p") { Note(.c, 5, dur: .whole) }
}
Section("B", endBarline: .final) {
Part("p") { Note(.e, 5, dur: .whole) }
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<bar-style>light-light</bar-style>"))
#expect(xml.contains("<bar-style>light-heavy</bar-style>"))
}
@Test func backwardRepeatSuppressesSectionBarStyle() {
// A backward repeat on the same (last) measure must win — the section's
// .final style is suppressed so only one light-heavy bar-style emits, and
// a backward <repeat> is present.
let score: Score = Score {
Section("A", repeats: RepeatStructure(backwardRepeatMeasures: [1]), endBarline: .final) {
Part("p") { Note(.c, 5, dur: .whole) }
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<repeat direction=\"backward\"/>"))
// Exactly one light-heavy bar-style (the repeat's), not two stacked.
let occurrences: Int = xml.components(separatedBy: "<bar-style>light-heavy</bar-style>").count - 1
#expect(occurrences == 1)
}
@Test func allBarlineStylesMapToMusicXMLTokens() {
let expected: [(BarlineStyle, String)] = [
(.regular, "regular"), (.double, "light-light"), (.final, "light-heavy"),
(.heavy, "heavy"), (.dashed, "dashed"), (.dotted, "dotted"),
(.tick, "tick"), (.short, "short"), (.invisible, "none")
]
// Exhaustive: every case must be exercised (count guards against a new
// case slipping through untested).
#expect(expected.count == BarlineStyle.allCases.count)
for (style, token): (BarlineStyle, String) in expected {
#expect(style.musicXMLBarStyle == token)
}
}
@Test func sectionBarStyleCoexistsWithEndingStopInDTDOrder() {
// An endBarline landing on a measure that is also an ending-stop (hook
// ending, no backward repeat) must emit both, with the bar-style BEFORE
// the ending per the MusicXML <barline> child order.
let score: Score = Score {
Section("A", repeats: RepeatStructure(endings: [Ending(number: 1, startMeasure: 1, stopMeasure: 1)]), endBarline: .double) {
Part("p") { Note(.c, 5, dur: .whole) }
}
}
let xml: String = score.toMusicXMLString()
// The right barline carries the bar-style and the ending STOP; assert the
// bar-style precedes the ending-stop (the ending START sits in the left
// barline earlier in the document and is not what we compare against).
guard let barStyleIdx: Range<String.Index> = xml.range(of: "<bar-style>light-light</bar-style>"),
let endingStopIdx: Range<String.Index> = xml.range(of: "type=\"stop\"") else {
Issue.record("expected both bar-style and ending-stop in output")
return
}
#expect(barStyleIdx.lowerBound < endingStopIdx.lowerBound)
}
@Test func noEndBarlineProducesNoExtraBarStyle() {
let score: Score = Score {
Section("A") {
Part("p") { Note(.c, 5, dur: .whole) }
}
}
let xml: String = score.toMusicXMLString()
#expect(!xml.contains("<bar-style>"))
#expect(score.measureBarlines.isEmpty)
}
}
+51 -4
View File
@@ -79,9 +79,11 @@ struct ScoreTests {
#expect(abs(events[1].beat - third) < 1e-15)
#expect(abs(events[2].beat - 2.0 * third) < 1e-15)
// Total span = 2 beats — verify via lastBeat()
// duration is "played" duration = nominal × articulation.scale; nominal=2/3, scale=1.0
// duration is the notated duration; nominal=2/3, articulation=.normal (scale=1.0)
// so notated == performed == 2/3 beat.
for e: ScoreEvent in events {
#expect(abs(e.duration - third) < 1e-15)
#expect(abs(e.performedDuration - third) < 1e-15)
}
}
@@ -150,6 +152,17 @@ struct ScoreTests {
#expect(events[1].beat == 1.5)
}
@Test func dotConveniencePropertiesMatchStatics() {
// `.dotted` / `.doubleDotted` computed properties equal the static funcs.
#expect(NoteDuration.quarter.dotted.beats == NoteDuration.dotted(.quarter).beats)
#expect(NoteDuration.quarter.dotted.beats == 1.5)
#expect(NoteDuration.half.doubleDotted.beats == NoteDuration.doubleDotted(.half).beats)
#expect(NoteDuration.quarter.doubleDotted.beats == 1.75)
// Double-dotted is 7/4, NOT the 9/4 of chaining `.dotted.dotted`.
#expect(NoteDuration.quarter.doubleDotted.beats != NoteDuration.quarter.dotted.dotted.beats)
#expect(NoteDuration.quarter.dotted.dotted.beats == 2.25)
}
// MARK: - 8. Dynamic → velocity mapping
@Test func dynamicMapsToVelocity() {
@@ -172,10 +185,15 @@ struct ScoreTests {
Note(.c, 4, dur: .quarter, dyn: .mf, art: .accent),
])
let events: [ScoreEvent] = part.flatten()
// staccato: duration × 0.5
#expect(abs(events[0].duration - 0.5) < 1e-15)
// accent: duration unchanged, velocity = mf + 0.15
// staccato: notated duration is unchanged (quarter = 1.0 beat);
// performedDuration applies the 0.5 scale.
#expect(events[0].duration == 1.0, "notated duration is always the written beat value")
#expect(abs(events[0].performedDuration - 0.5) < 1e-15,
"staccato performed duration = notated × 0.5")
// accent: notated duration unchanged, velocity = mf + 0.15
#expect(events[1].duration == 1.0)
#expect(events[1].performedDuration == 1.0,
"accent does not alter performed duration (scale = 1.0)")
#expect(abs(events[1].velocity - (Dynamic.mf.velocity + 0.15)) < 1e-15)
}
@@ -188,6 +206,35 @@ struct ScoreTests {
#expect(events[0].velocity == 1.0)
}
// MARK: - 9b. performedDuration covers all articulation cases
@Test func performedDurationAllArticulations() {
// Half note (2.0 beats notated) under each articulation.
let part: ScorePart = ScorePart(name: "p", elements: [
Note(.c, 4, dur: .half, art: .normal),
Note(.c, 4, dur: .half, art: .staccato),
Note(.c, 4, dur: .half, art: .staccatissimo),
Note(.c, 4, dur: .half, art: .legato),
Note(.c, 4, dur: .half, art: .tenuto),
Note(.c, 4, dur: .half, art: .accent),
Note(.c, 4, dur: .half, art: .marcato),
])
let events: [ScoreEvent] = part.flatten()
// All notated durations must be the half note (2.0 beats).
for e: ScoreEvent in events {
#expect(e.duration == 2.0,
"notated duration must always equal the written beat value (\(e.articulation))")
}
// Performed durations apply each articulation's durationScale.
#expect(abs(events[0].performedDuration - 2.0) < 1e-15, "normal ×1.0")
#expect(abs(events[1].performedDuration - 1.0) < 1e-15, "staccato ×0.5")
#expect(abs(events[2].performedDuration - 0.5) < 1e-15, "staccatissimo ×0.25")
#expect(abs(events[3].performedDuration - 2.1) < 1e-12, "legato ×1.05")
#expect(abs(events[4].performedDuration - 2.0) < 1e-15, "tenuto ×1.0")
#expect(abs(events[5].performedDuration - 2.0) < 1e-15, "accent ×1.0")
#expect(abs(events[6].performedDuration - 1.7) < 1e-12, "marcato ×0.85")
}
// MARK: - 10. DSL: full Score with parts + builders
@Test func dslAssemblesFullScore() {
@@ -0,0 +1,376 @@
// ScoreTimelineTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("ScoreTimeline — beat placement + rest auto-fill")
struct ScoreTimelineTests {
// MARK: - Helpers
private func restBeats(_ element: ScoreElement) -> Double? {
if case .rest(let dur) = element { return dur.beats }
return nil
}
// MARK: - Gap fill
@Test func fillsGapWithRest() throws {
// Quarter at beat 0, quarter at beat 4 → Note, Rest(3q), Note.
let elements: [ScoreElement] = try ScoreTimeline.from(
(beat: 0.0, element: Note(.e, 5, dur: .quarter)),
(beat: 4.0, element: Note(.e, 5, dur: .quarter))
)
#expect(elements.count == 3)
#expect(restBeats(elements[1]) == 3.0)
let events: [ScoreEvent] = ScorePart(name: "p", elements: elements).flatten()
#expect(events.count == 2)
#expect(events[0].beat == 0.0)
#expect(events[1].beat == 4.0)
}
@Test func leadingRestWhenFirstElementAfterZero() throws {
let elements: [ScoreElement] = try ScoreTimeline.from(
(beat: 2.0, element: Note(.c, 4, dur: .quarter))
)
#expect(elements.count == 2)
#expect(restBeats(elements[0]) == 2.0)
let events: [ScoreEvent] = ScorePart(name: "p", elements: elements).flatten()
#expect(events.count == 1)
#expect(events[0].beat == 2.0)
}
@Test func exactAdjacencyInsertsNoRest() throws {
// Half (2 beats) at 0, quarter at 2 → no rest between.
let elements: [ScoreElement] = try ScoreTimeline.from(
(beat: 0.0, element: Note(.c, 4, dur: .half)),
(beat: 2.0, element: Note(.d, 4, dur: .quarter))
)
#expect(elements.count == 2)
#expect(restBeats(elements[0]) == nil) // first is the note, not a rest
}
@Test func unsortedInputIsSorted() throws {
let elements: [ScoreElement] = try ScoreTimeline.from(
(beat: 4.0, element: Note(.g, 5, dur: .quarter)),
(beat: 0.0, element: Note(.c, 5, dur: .quarter))
)
let events: [ScoreEvent] = ScorePart(name: "p", elements: elements).flatten()
#expect(events.count == 2)
#expect(events[0].beat == 0.0)
#expect(events[0].pitch.midiNote == 72) // C5 sorted first
#expect(events[1].beat == 4.0)
#expect(events[1].pitch.midiNote == 79) // G5
}
// MARK: - Chords + larger placements
@Test func chordPlacement() throws {
let elements: [ScoreElement] = try ScoreTimeline.from(
(beat: 0.0, element: Chord([.named(.c, 4), .named(.e, 4), .named(.g, 4)], dur: .quarter)),
(beat: 2.0, element: Note(.c, 5, dur: .quarter))
)
let events: [ScoreEvent] = ScorePart(name: "p", elements: elements).flatten()
// 3 chord notes at beat 0 + 1 note at beat 2.
#expect(events.filter { $0.beat == 0.0 }.count == 3)
#expect(events.filter { $0.beat == 2.0 }.count == 1)
}
// MARK: - Compound element spans (scoreElementBeatSpan)
@Test func tupletPlacementAdvancesCursorCorrectly() throws {
// A 3-in-2 triplet of quarters spans 2 quarter beats (3 × 1 × 2/3).
// Placing it at beat 0 and a note at beat 2 → exact adjacency, no rest,
// no overlap throw.
let triplet: ScoreElement = Tuplet(3, inTimeOf: 2) {
Note(.c, 5, dur: .quarter)
Note(.d, 5, dur: .quarter)
Note(.e, 5, dur: .quarter)
}
let elements: [ScoreElement] = try ScoreTimeline.from(
(beat: 0.0, element: triplet),
(beat: 2.0, element: Note(.f, 5, dur: .quarter))
)
// tuplet + note, no inserted rest.
#expect(elements.count == 2)
let events: [ScoreEvent] = ScorePart(name: "p", elements: elements).flatten()
#expect(events.count == 4) // 3 triplet notes + 1
#expect(events[3].beat == 2.0) // landing note exactly at 2
}
@Test func tupletSpanGapInsertsRest() throws {
// Same triplet (span 2) at beat 0, next note at beat 3 → 1-beat rest gap.
let triplet: ScoreElement = Tuplet(3, inTimeOf: 2) {
Note(.c, 5, dur: .quarter)
Note(.d, 5, dur: .quarter)
Note(.e, 5, dur: .quarter)
}
let elements: [ScoreElement] = try ScoreTimeline.from(
(beat: 0.0, element: triplet),
(beat: 3.0, element: Note(.f, 5, dur: .quarter))
)
#expect(elements.count == 3)
#expect(restBeats(elements[1]) == 1.0)
}
@Test func wedgeIsTransparentToCursor() throws {
// A crescendo over two quarters spans 2 beats; a note at beat 2 abuts it.
let cresc: ScoreElement = Crescendo {
Note(.c, 5, dur: .quarter, dyn: .p)
Note(.d, 5, dur: .quarter, dyn: .f)
}
let elements: [ScoreElement] = try ScoreTimeline.from(
(beat: 0.0, element: cresc),
(beat: 2.0, element: Note(.e, 5, dur: .quarter))
)
#expect(elements.count == 2) // no rest inserted
let events: [ScoreEvent] = ScorePart(name: "p", elements: elements).flatten()
#expect(events.last?.beat == 2.0)
}
@Test func zeroSpanGraceDoesNotAdvanceCursor() throws {
// A grace note has zero span — a following note at beat 0 is NOT an
// overlap (cursor stays at 0), and a note at beat 1 still gets a rest gap
// measured from 0.
let elements: [ScoreElement] = try ScoreTimeline.from(
(beat: 0.0, element: Grace(.fSharp, 5)),
(beat: 1.0, element: Note(.g, 5, dur: .quarter))
)
// grace + rest(1) + note.
#expect(restBeats(elements[1]) == 1.0)
}
// MARK: - Overlap
@Test func overlapThrows() {
// Half (2 beats) at 0 overlaps a note placed at beat 1.
#expect(throws: ScoreTimelineError.self) {
_ = try ScoreTimeline.from(
(beat: 0.0, element: Note(.c, 4, dur: .half)),
(beat: 1.0, element: Note(.d, 4, dur: .quarter))
)
}
}
@Test func overlapErrorCarriesBeats() {
do {
_ = try ScoreTimeline.from(
(beat: 0.0, element: Note(.c, 4, dur: .half)),
(beat: 1.0, element: Note(.d, 4, dur: .quarter))
)
Issue.record("expected overlap throw")
} catch let ScoreTimelineError.overlap(atBeat, previousEndsAtBeat, desc) {
#expect(atBeat == 1.0)
#expect(previousEndsAtBeat == 2.0)
#expect(desc == "note")
} catch {
Issue.record("unexpected error: \(error)")
}
}
// MARK: - Negative beat
@Test func negativeBeatThrows() {
#expect(throws: ScoreTimelineError.self) {
_ = try ScoreTimeline.from(
(beat: -1.0, element: Note(.c, 4, dur: .quarter))
)
}
}
// MARK: - Dictionary overload
@Test func dictionaryOverload() throws {
let elements: [ScoreElement] = try ScoreTimeline.fill([
0.0: Note(.c, 4, dur: .quarter),
4.0: Note(.g, 4, dur: .quarter),
])
let events: [ScoreEvent] = ScorePart(name: "p", elements: elements).flatten()
#expect(events.count == 2)
#expect(events[0].beat == 0.0)
#expect(events[1].beat == 4.0)
}
// MARK: - Empty
@Test func emptyYieldsEmpty() throws {
let elements: [ScoreElement] = try ScoreTimeline.fill([])
#expect(elements.isEmpty)
}
// MARK: - BeatPosition (meter-aware) overload
@Test func musicalBeatAddressingMatchesUserExample() throws {
// The original pseudocode: beat 1 and beat 5 in 4/4 → Note, Rest(3q), Note.
let elements: [ScoreElement] = try ScoreTimeline.from(
(.beat(1.0), Note(.e, 5, dur: .quarter)),
(.beat(5.0), Note(.e, 5, dur: .quarter)),
meter: MeterMap(.fourFour)
)
#expect(elements.count == 3)
#expect(restBeats(elements[1]) == 3.0)
let events: [ScoreEvent] = ScorePart(name: "p", elements: elements).flatten()
#expect(events.count == 2)
#expect(events[0].beat == 0.0)
#expect(events[1].beat == 4.0)
}
@Test func barAddressingDefaultsToFourFour() throws {
let elements: [ScoreElement] = try ScoreTimeline.fill([
(.bar(1, beat: 1.0), Note(.c, 5, dur: .quarter)),
(.bar(2, beat: 1.0), Note(.g, 5, dur: .quarter)),
])
let events: [ScoreEvent] = ScorePart(name: "p", elements: elements).flatten()
#expect(events.count == 2)
#expect(events[1].beat == 4.0) // bar 2 downbeat
}
@Test func compoundBeatAddressing() throws {
// 6/8 compound: beat 1 (felt dotted-quarter) of bar 1 and bar 2 — 3q apart.
let elements: [ScoreElement] = try ScoreTimeline.from(
(.bar(1, beat: 1.0), Note(.c, 5, dur: .quarter)),
(.bar(2, beat: 1.0), Note(.d, 5, dur: .quarter)),
meter: MeterMap(.sixEightCompound)
)
let events: [ScoreEvent] = ScorePart(name: "p", elements: elements).flatten()
#expect(events.count == 2)
#expect(events[1].beat == 3.0)
}
// MARK: - Overlap policy: truncatePrevious
private func noteBeats(_ element: ScoreElement) -> Double? {
if case .note(_, let dur, _, _, _, _) = element { return dur.beats }
return nil
}
@Test func truncatePreviousShortensOverlap() throws {
// Half (2q) at 0 overlaps a note at beat 1 → previous shortened to 1q.
let elements: [ScoreElement] = try ScoreTimeline.fill([
(beat: 0.0, element: Note(.c, 4, dur: .half)),
(beat: 1.0, element: Note(.d, 4, dur: .quarter)),
], overlap: .truncatePrevious)
#expect(elements.count == 2)
#expect(noteBeats(elements[0]) == 1.0) // truncated half → quarter
let events: [ScoreEvent] = ScorePart(name: "p", elements: elements).flatten()
#expect(events.count == 2)
#expect(events[1].beat == 1.0)
}
@Test func truncateSameStartThrows() {
// Two notes at beat 0 would truncate the first to zero → reject.
#expect(throws: ScoreTimelineError.self) {
_ = try ScoreTimeline.fill([
(beat: 0.0, element: Note(.c, 4, dur: .quarter)),
(beat: 0.0, element: Note(.e, 4, dur: .quarter)),
], overlap: .truncatePrevious)
}
}
@Test func truncateNonTruncatableThrows() {
// A tuplet (span 2) overlapping a note can't be truncated → throws.
let triplet: ScoreElement = Tuplet(3, inTimeOf: 2) {
Note(.c, 5, dur: .quarter)
Note(.d, 5, dur: .quarter)
Note(.e, 5, dur: .quarter)
}
#expect(throws: ScoreTimelineError.self) {
_ = try ScoreTimeline.fill([
(beat: 0.0, element: triplet),
(beat: 1.0, element: Note(.f, 5, dur: .quarter)),
], overlap: .truncatePrevious)
}
}
// MARK: - Multi-voice (explicit)
@Test func fillVoicesProducesVoiceBlocks() throws {
let elements: [ScoreElement] = try ScoreTimeline.fillVoices([
(beat: 0.0, voice: 1, element: Note(.c, 5, dur: .whole)),
(beat: 0.0, voice: 2, element: Note(.c, 4, dur: .half)),
(beat: 2.0, voice: 2, element: Note(.e, 4, dur: .half)),
])
#expect(elements.count == 2)
guard case .voice(let v1, _) = elements[0] else { Issue.record("voice 1"); return }
guard case .voice(let v2, _) = elements[1] else { Issue.record("voice 2"); return }
#expect(v1 == 1)
#expect(v2 == 2)
let events: [ScoreEvent] = ScorePart(name: "p", elements: elements).flatten()
#expect(events.count == 3) // 1 in voice 1 + 2 in voice 2
}
// MARK: - Multi-voice (auto)
@Test func autoVoicedSplitsOverlap() throws {
// Half (2q) at 0 overlaps a quarter at 1 → two voices.
let elements: [ScoreElement] = try ScoreTimeline.fillAutoVoiced([
(beat: 0.0, element: Note(.c, 4, dur: .half)),
(beat: 1.0, element: Note(.d, 4, dur: .quarter)),
])
#expect(elements.count == 2)
guard case .voice = elements[0] else { Issue.record("expected .voice"); return }
}
@Test func autoVoicedNonOverlapSingleVoice() throws {
let elements: [ScoreElement] = try ScoreTimeline.fillAutoVoiced([
(beat: 0.0, element: Note(.c, 4, dur: .quarter)),
(beat: 2.0, element: Note(.d, 4, dur: .quarter)),
])
#expect(elements.count == 1) // single voice, no overlap
guard case .voice(let n, _) = elements[0] else { Issue.record("expected .voice"); return }
#expect(n == 1)
}
@Test func fillVoicesInvalidVoiceThrows() {
#expect(throws: ScoreTimelineError.self) {
_ = try ScoreTimeline.fillVoices([
(beat: 0.0, voice: 0, element: Note(.c, 4, dur: .quarter)),
])
}
}
@Test func fillVoicesBeatPositionOverload() throws {
let elements: [ScoreElement] = try ScoreTimeline.fillVoices([
(.bar(1, beat: 1.0), voice: 1, element: Note(.c, 5, dur: .whole)),
(.bar(2, beat: 1.0), voice: 2, element: Note(.c, 4, dur: .quarter)),
], meter: MeterMap(.fourFour))
#expect(elements.count == 2)
guard case .voice(1, _) = elements[0] else { Issue.record("voice 1"); return }
guard case .voice(2, _) = elements[1] else { Issue.record("voice 2"); return }
}
@Test func fillAutoVoicedBeatPositionOverload() throws {
// Two notes at the same downbeat (bar 1 beat 1) → two voices.
let elements: [ScoreElement] = try ScoreTimeline.fillAutoVoiced([
(.bar(1, beat: 1.0), Note(.c, 5, dur: .quarter)),
(.bar(1, beat: 1.0), Note(.e, 5, dur: .quarter)),
], meter: MeterMap(.fourFour))
#expect(elements.count == 2)
}
@Test func autoVoicedThreeWayOverlap() throws {
// Three notes all starting at 0 → three voices.
let elements: [ScoreElement] = try ScoreTimeline.fillAutoVoiced([
(beat: 0.0, element: Note(.c, 4, dur: .quarter)),
(beat: 0.0, element: Note(.e, 4, dur: .quarter)),
(beat: 0.0, element: Note(.g, 4, dur: .quarter)),
])
#expect(elements.count == 3)
}
@Test func negativeResolvedBeatThrows() {
// A position resolving before beat 0 is rejected by the fill guard.
#expect(throws: ScoreTimelineError.self) {
_ = try ScoreTimeline.from(
(.quarters(-1.0), Note(.c, 4, dur: .quarter)),
meter: MeterMap(.fourFour)
)
}
}
}
+581
View File
@@ -0,0 +1,581 @@
// SlurSpannerTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("SlurSpanner — authoring, encoding, and validation")
struct SlurSpannerTests {
// MARK: - Slur {} block
@Test func slurBlockEmitsStartOnFirstNoteStopOnLast() {
let score: Score = Score(bpm: 120) {
Part("p") {
Slur {
Note(.c, 5, dur: .quarter)
Note(.d, 5, dur: .quarter)
Note(.e, 5, dur: .quarter)
Note(.f, 5, dur: .quarter)
}
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<slur number=\"1\" type=\"start\"/>"))
#expect(xml.contains("<slur number=\"1\" type=\"stop\"/>"))
// The middle notes should NOT carry slur annotations.
// Count occurrences: exactly one start and one stop.
// Note: tie annotations also use type="start"/"stop", so count only slur lines.
let slurStart: Int = xml.components(separatedBy: "<slur number=\"1\" type=\"start\"/>").count - 1
let slurStop: Int = xml.components(separatedBy: "<slur number=\"1\" type=\"stop\"/>").count - 1
#expect(slurStart == 1)
#expect(slurStop == 1)
// Verify start and stop appear in document order (start index < stop index).
let startRange: Range<String.Index>? = xml.range(of: "<slur number=\"1\" type=\"start\"/>")
let stopRange: Range<String.Index>? = xml.range(of: "<slur number=\"1\" type=\"stop\"/>")
if let s: Range<String.Index> = startRange, let t: Range<String.Index> = stopRange {
#expect(s.lowerBound < t.lowerBound)
} else {
Issue.record("Expected both slur start and stop to appear in XML")
}
}
@Test func slurBlockSingleNoteEmitsStartAndStopOnSameNote() {
let score: Score = Score(bpm: 120) {
Part("p") {
Slur {
Note(.c, 5, dur: .quarter)
}
}
}
let xml: String = score.toMusicXMLString()
// Single atom: both start and stop land on the same <note> block.
// Both should appear in a single <notations> block.
let slurStart: Int = xml.components(separatedBy: "<slur number=\"1\" type=\"start\"/>").count - 1
let slurStop: Int = xml.components(separatedBy: "<slur number=\"1\" type=\"stop\"/>").count - 1
#expect(slurStart == 1)
#expect(slurStop == 1)
// Both must appear within the same <notations>…</notations> block.
// Find the single <note> block and check both are inside it.
let noteBlocks: [Substring] = xml.split(separator: Character("\n"), omittingEmptySubsequences: false)
var inNotations: Bool = false
var foundStart: Bool = false
var foundStop: Bool = false
for line: Substring in noteBlocks {
if line.contains("<notations>") { inNotations = true }
if inNotations && line.contains("<slur number=\"1\" type=\"start\"/>") { foundStart = true }
if inNotations && line.contains("<slur number=\"1\" type=\"stop\"/>") { foundStop = true }
if line.contains("</notations>") { inNotations = false }
}
#expect(foundStart)
#expect(foundStop)
}
@Test func slurBlockSkipsRestsAsEndpoint() {
let score: Score = Score(bpm: 120) {
Part("p") {
Slur {
Rest(dur: .quarter)
Note(.c, 5, dur: .quarter)
Note(.d, 5, dur: .quarter)
Rest(dur: .quarter)
}
}
}
let xml: String = score.toMusicXMLString()
// Start on the first non-rest note (C5), stop on the last non-rest note (D5).
let slurStart: Int = xml.components(separatedBy: "<slur number=\"1\" type=\"start\"/>").count - 1
let slurStop: Int = xml.components(separatedBy: "<slur number=\"1\" type=\"stop\"/>").count - 1
#expect(slurStart == 1)
#expect(slurStop == 1)
}
// MARK: - Per-note spanners
@Test func perNoteBeginSlurEmitsStartOnThatNote() {
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 5, dur: .quarter, spanners: [.beginSlur])
Note(.d, 5, dur: .quarter)
Note(.e, 5, dur: .quarter, spanners: [.endSlur])
}
}
let xml: String = score.toMusicXMLString()
let slurStart: Int = xml.components(separatedBy: "<slur number=\"1\" type=\"start\"/>").count - 1
let slurStop: Int = xml.components(separatedBy: "<slur number=\"1\" type=\"stop\"/>").count - 1
#expect(slurStart == 1)
#expect(slurStop == 1)
// Start before stop in document order.
let startRange: Range<String.Index>? = xml.range(of: "<slur number=\"1\" type=\"start\"/>")
let stopRange: Range<String.Index>? = xml.range(of: "<slur number=\"1\" type=\"stop\"/>")
if let s: Range<String.Index> = startRange, let t: Range<String.Index> = stopRange {
#expect(s.lowerBound < t.lowerBound)
} else {
Issue.record("Expected both slur start and stop in XML")
}
}
@Test func perNoteBeginCrescendoEmitsWedge() {
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 5, dur: .quarter, spanners: [.beginCrescendo])
Note(.d, 5, dur: .quarter)
Note(.e, 5, dur: .quarter, spanners: [.endHairpin])
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<wedge type=\"crescendo\"/>"))
#expect(xml.contains("<wedge type=\"stop\"/>"))
}
@Test func perNoteBeginDiminuendoEmitsWedge() {
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.f, 5, dur: .quarter, spanners: [.beginDiminuendo])
Note(.e, 5, dur: .quarter)
Note(.d, 5, dur: .quarter, spanners: [.endHairpin])
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<wedge type=\"diminuendo\"/>"))
#expect(xml.contains("<wedge type=\"stop\"/>"))
}
// MARK: - Shared-boundary / overlap case
@Test func sharedBoundarySlurStartAndHairpinStopOnSameNote() {
// A note that simultaneously ends a hairpin AND starts a slur.
// Both annotations must appear in the XML.
let score: Score = Score(bpm: 120) {
Part("p") {
// Bar 1: crescendo opens here
Note(.c, 5, dur: .quarter, spanners: [.beginCrescendo])
Note(.d, 5, dur: .quarter)
// This note: crescendo ends AND slur starts (shared boundary)
Note(.e, 5, dur: .quarter, spanners: [.endHairpin, .beginSlur])
// Bar 1 continues with the slur
Note(.f, 5, dur: .quarter, spanners: [.endSlur])
}
}
let xml: String = score.toMusicXMLString()
// Wedge stop after E5
#expect(xml.contains("<wedge type=\"crescendo\"/>"))
#expect(xml.contains("<wedge type=\"stop\"/>"))
// Slur start on E5, slur stop on F5
#expect(xml.contains("<slur number=\"1\" type=\"start\"/>"))
#expect(xml.contains("<slur number=\"1\" type=\"stop\"/>"))
// In document order: crescendo start < wedge stop and slur start < slur stop
let crescRange: Range<String.Index>? = xml.range(of: "<wedge type=\"crescendo\"/>")
let wedgeStopRange: Range<String.Index>? = xml.range(of: "<wedge type=\"stop\"/>")
let slurStartRange: Range<String.Index>? = xml.range(of: "<slur number=\"1\" type=\"start\"/>")
let slurStopRange: Range<String.Index>? = xml.range(of: "<slur number=\"1\" type=\"stop\"/>")
if let cr: Range<String.Index> = crescRange,
let ws: Range<String.Index> = wedgeStopRange,
let ss: Range<String.Index> = slurStartRange,
let st: Range<String.Index> = slurStopRange
{
#expect(cr.lowerBound < ws.lowerBound)
#expect(ss.lowerBound < st.lowerBound)
} else {
Issue.record("Expected all four spanner markers in XML")
}
}
@Test func crescendoBlockAndSlurBlockCanOverlap() {
// Slur begins inside a Crescendo block — the slur-start and wedge-start
// both land on the first note of the Slur, while the crescendo was opened
// by the Crescendo block's first note (C5). The slur-stop lands on the last
// Slur note; the wedge-stop lands on the last Crescendo note (F5).
let score: Score = Score(bpm: 120) {
Part("p") {
Crescendo {
Note(.c, 5, dur: .quarter, dyn: .p)
Note(.d, 5, dur: .quarter)
Slur {
Note(.e, 5, dur: .quarter)
Note(.f, 5, dur: .quarter, dyn: .f)
}
}
}
}
let xml: String = score.toMusicXMLString()
// Crescendo (hairpin) must appear.
#expect(xml.contains("<wedge type=\"crescendo\"/>"))
#expect(xml.contains("<wedge type=\"stop\"/>"))
// Slur must appear.
#expect(xml.contains("<slur number=\"1\" type=\"start\"/>"))
#expect(xml.contains("<slur number=\"1\" type=\"stop\"/>"))
}
// MARK: - Flatten transparency
@Test func slurBlockFlattenIsIdenticalToUnwrapped() {
// The ScoreEvent list from a Slur-wrapped span must equal the list from
// the same notes without the wrapper.
let partWithSlur: ScorePart = ScorePart(
name: "p",
elements: [
ScoreElement.slur([
ScoreElement.note(.named(.c, 5), duration: .quarter, dynamic: .mf,
articulation: .normal, voice: 0, tie: false),
ScoreElement.note(.named(.d, 5), duration: .quarter, dynamic: .mf,
articulation: .normal, voice: 0, tie: false)
])
]
)
let partWithout: ScorePart = ScorePart(
name: "p",
elements: [
ScoreElement.note(.named(.c, 5), duration: .quarter, dynamic: .mf,
articulation: .normal, voice: 0, tie: false),
ScoreElement.note(.named(.d, 5), duration: .quarter, dynamic: .mf,
articulation: .normal, voice: 0, tie: false)
]
)
let eventsWithSlur: [ScoreEvent] = partWithSlur.flatten()
let eventsWithout: [ScoreEvent] = partWithout.flatten()
#expect(eventsWithSlur.count == eventsWithout.count)
for (a, b): (ScoreEvent, ScoreEvent) in zip(eventsWithSlur, eventsWithout) {
#expect(a.beat == b.beat)
#expect(a.duration == b.duration)
#expect(a.pitch == b.pitch)
}
}
@Test func spannedElementFlattenIsIdenticalToUnwrapped() {
let partWithSpanned: ScorePart = ScorePart(
name: "p",
elements: [
ScoreElement.spanned(
[.beginSlur],
ScoreElement.note(.named(.c, 5), duration: .quarter, dynamic: .mf,
articulation: .normal, voice: 0, tie: false)
)
]
)
let partWithout: ScorePart = ScorePart(
name: "p",
elements: [
ScoreElement.note(.named(.c, 5), duration: .quarter, dynamic: .mf,
articulation: .normal, voice: 0, tie: false)
]
)
let eventsWithSpanned: [ScoreEvent] = partWithSpanned.flatten()
let eventsWithout: [ScoreEvent] = partWithout.flatten()
#expect(eventsWithSpanned.count == eventsWithout.count)
if let a: ScoreEvent = eventsWithSpanned.first, let b: ScoreEvent = eventsWithout.first {
#expect(a.beat == b.beat)
#expect(a.duration == b.duration)
#expect(a.pitch == b.pitch)
}
}
// MARK: - Validation: unbalanced spanners
@Test func unbalancedEndSlurWithNoOpenIsDropped() {
// An .endSlur with no preceding .beginSlur should be silently dropped
// (no <slur type="stop"/> in the output) and a diagnostic posted.
LyrebirdMessageCenter.shared.clear()
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 5, dur: .quarter, spanners: [.endSlur])
Note(.d, 5, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
// Dropped: no slur stop in output.
#expect(!xml.contains("<slur number=\"1\" type=\"stop\"/>"))
// No slur start either (none was authored).
#expect(!xml.contains("<slur number=\"1\" type=\"start\"/>"))
}
@Test func unbalancedEndHairpinWithNoOpenIsDropped() {
LyrebirdMessageCenter.shared.clear()
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 5, dur: .quarter, spanners: [.endHairpin])
Note(.d, 5, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
// No wedge-stop should appear.
#expect(!xml.contains("<wedge type=\"stop\"/>"))
}
@Test func doubleOpenHairpinDropsRedundantStartWithoutSynthesizingStop() {
// Two hairpin starts, one stop: the redundant second start is dropped.
// The validator must NOT synthesize a spurious wedge-stop on the dropped
// start — exactly one crescendo start and one stop should survive.
LyrebirdMessageCenter.shared.clear()
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 5, dur: .quarter, spanners: [.beginCrescendo])
Note(.d, 5, dur: .quarter, spanners: [.beginCrescendo])
Note(.e, 5, dur: .quarter, spanners: [.endHairpin])
}
}
let xml: String = score.toMusicXMLString()
let crescStarts: Int = xml.components(separatedBy: "<wedge type=\"crescendo\"/>").count - 1
let wedgeStops: Int = xml.components(separatedBy: "<wedge type=\"stop\"/>").count - 1
#expect(crescStarts == 1, "redundant second crescendo start must be dropped")
#expect(wedgeStops == 1, "exactly one stop — no spurious stop synthesized on the dropped start")
}
@Test func diagnosticIsPostedForUnbalancedSpanner() async {
// An orphan endSlur causes a warning to be posted via
// `Task { @MainActor in LyrebirdMessageCenter.shared.warning(...) }` inside
// validateSpannerBalance. Poll in a bounded loop (up to ~50 yields) rather
// than relying on a fixed yield count, so the test is deterministic under
// load without being fragile to scheduler jitter.
LyrebirdMessageCenter.shared.clear()
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 5, dur: .quarter, spanners: [.endSlur])
}
}
// Trigger encoding (this fires the Task { @MainActor in ... } inside validateSpannerBalance).
let _: String = score.toMusicXMLString()
// Poll until a warning appears or the bound is hit.
let maxPolls: Int = 50
var pollCount: Int = 0
while pollCount < maxPolls {
await Task.yield()
let warnings: [LyrebirdMessage] = LyrebirdMessageCenter.shared.messages.filter {
$0.tier == .warning
}
if !warnings.isEmpty { break }
pollCount += 1
}
// A warning should now be in the message center.
let warnings: [LyrebirdMessage] = LyrebirdMessageCenter.shared.messages.filter {
$0.tier == .warning
}
#expect(!warnings.isEmpty)
}
// MARK: - Note DSL spanners: / param does not affect output when empty
@Test func noteWithEmptySpannersIsIdenticalToPlainNote() {
let scoreWithEmpty: Score = Score(bpm: 120) {
Part("p") { Note(.c, 5, dur: .quarter, spanners: []) }
}
let scorePlain: Score = Score(bpm: 120) {
Part("p") { Note(.c, 5, dur: .quarter) }
}
#expect(scoreWithEmpty.toMusicXMLString() == scorePlain.toMusicXMLString())
}
// MARK: - Chord spanners
@Test func chordSpannersEmitSlurOnChordAtom() {
let score: Score = Score(bpm: 120) {
Part("p") {
Chord([.named(.c, 5), .named(.e, 5)], dur: .quarter, spanners: [.beginSlur])
Note(.d, 5, dur: .quarter, spanners: [.endSlur])
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<slur number=\"1\" type=\"start\"/>"))
#expect(xml.contains("<slur number=\"1\" type=\"stop\"/>"))
}
// MARK: - Existing slur round-trip unaffected
@Test func legatoSlurRoundTripUnaffected() {
// The existing legato-articulation slur path (annotateSlurs over .legato notes)
// must still work correctly — the new Slur {} block does not interfere.
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 5, dur: .quarter, art: .legato)
Note(.d, 5, dur: .quarter, art: .legato)
Note(.e, 5, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
// Legato run of C5-D5 should produce one slur start (on C5) and
// one slur stop (on E5 — the non-legato follower).
let slurStart: Int = xml.components(separatedBy: "<slur number=\"1\" type=\"start\"/>").count - 1
let slurStop: Int = xml.components(separatedBy: "<slur number=\"1\" type=\"stop\"/>").count - 1
#expect(slurStart == 1)
#expect(slurStop == 1)
}
// MARK: - Existing wedge round-trip unaffected
@Test func crescendoBlockRoundTripUnaffected() {
let score: Score = Score(bpm: 120) {
Part("p") {
Crescendo {
Note(.c, 5, dur: .quarter, dyn: .p)
Note(.d, 5, dur: .quarter)
Note(.e, 5, dur: .quarter)
Note(.f, 5, dur: .quarter, dyn: .f)
}
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<wedge type=\"crescendo\"/>"))
#expect(xml.contains("<wedge type=\"stop\"/>"))
// No unexpected slur markup.
#expect(!xml.contains("<slur"))
}
// MARK: - Authored-slur / legato-auto-slur interaction (blocking bug regression)
/// A note that is BOTH a `.legato` note AND a `Slur {}` endpoint must keep
/// its authored slur annotation. The legato auto-slur must not clobber the
/// authored `emitStart`/`emitStop` flags, and the output must contain exactly
/// one balanced `<slur start>` / `<slur stop>` pair with no dangling open.
@Test func legatoNoteAtSlurBlockBoundaryKeepsAuthoredSlur() {
// C5 is legato AND is the last note inside a Slur {} block (authored stop).
// D5 (the non-legato follower) would normally receive the auto-slur stop,
// but the authored stop on C5 takes precedence — the auto-slur must be
// suppressed so only one balanced pair is emitted.
let score: Score = Score(bpm: 120) {
Part("p") {
Slur {
Note(.a, 4, dur: .quarter)
Note(.b, 4, dur: .quarter)
Note(.c, 5, dur: .quarter, art: .legato)
}
Note(.d, 5, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
// Exactly one start and one stop — no dangling extra span.
let slurStart: Int = xml.components(separatedBy: "<slur number=\"1\" type=\"start\"/>").count - 1
let slurStop: Int = xml.components(separatedBy: "<slur number=\"1\" type=\"stop\"/>").count - 1
#expect(slurStart == 1, "authored Slur {} block must emit exactly one slur start")
#expect(slurStop == 1, "authored Slur {} block must emit exactly one slur stop")
// Start must precede stop in document order.
let startRange: Range<String.Index>? = xml.range(of: "<slur number=\"1\" type=\"start\"/>")
let stopRange: Range<String.Index>? = xml.range(of: "<slur number=\"1\" type=\"stop\"/>")
if let s: Range<String.Index> = startRange, let t: Range<String.Index> = stopRange {
#expect(s.lowerBound < t.lowerBound, "slur start must appear before slur stop")
} else {
Issue.record("Expected exactly one slur start and one slur stop in XML")
}
}
/// An authored `Slur {}` block overlapping a `.legato` run in the same voice
/// must NOT emit two concurrent `number="1"` spans. The auto-slur for the
/// legato run must be suppressed; only the authored slur survives.
@Test func authoredSlurOverlappingLegatoRunDoesNotEmitTwoConcurrentSpans() {
// Slur {} wraps C5-D5-E5. D5 is also legato, which would normally trigger
// an auto-slur run of length 1 (D5 only, E5 is the follower). The authored
// slur on this voice prevents the auto-slur from firing.
let score: Score = Score(bpm: 120) {
Part("p") {
Slur {
Note(.c, 5, dur: .quarter)
Note(.d, 5, dur: .quarter, art: .legato)
Note(.e, 5, dur: .quarter)
}
Note(.f, 5, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
// Only one pair of slur start/stop — no two concurrent number="1" spans.
let slurStart: Int = xml.components(separatedBy: "<slur number=\"1\" type=\"start\"/>").count - 1
let slurStop: Int = xml.components(separatedBy: "<slur number=\"1\" type=\"stop\"/>").count - 1
#expect(slurStart == 1, "exactly one slur start: authored wins, auto-slur suppressed")
#expect(slurStop == 1, "exactly one slur stop: authored wins, auto-slur suppressed")
// Verify the authored slur spans the full block (start on first note, stop on last).
// Both markers must appear in document order.
let startRange: Range<String.Index>? = xml.range(of: "<slur number=\"1\" type=\"start\"/>")
let stopRange: Range<String.Index>? = xml.range(of: "<slur number=\"1\" type=\"stop\"/>")
if let s: Range<String.Index> = startRange, let t: Range<String.Index> = stopRange {
#expect(s.lowerBound < t.lowerBound, "slur start must appear before slur stop")
} else {
Issue.record("Expected exactly one slur start and one slur stop in XML")
}
}
// MARK: - Orphan-open-at-end-of-part cleanup
@Test func orphanOpenSlurAtEndOfPartIsDropped() {
// A slur that opens but never closes: the opener start is dropped, so no
// slur markup is emitted.
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 5, dur: .quarter, spanners: [.beginSlur])
Note(.d, 5, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
#expect(!xml.contains("<slur number=\"1\" type=\"start\"/>"))
#expect(!xml.contains("<slur number=\"1\" type=\"stop\"/>"))
}
@Test func orphanOpenHairpinAtEndOfPartIsDropped() {
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 5, dur: .quarter, spanners: [.beginCrescendo])
Note(.d, 5, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
#expect(!xml.contains("<wedge type=\"crescendo\"/>"))
#expect(!xml.contains("<wedge type=\"stop\"/>"))
}
@Test func balancedSlurSurvivesWhenLaterSlurInSameVoiceIsOrphaned() {
// Two slur spans in one voice: the first is balanced, the second opens
// and never closes. The cleanup must drop ONLY the second (orphan) start,
// leaving the first span's start+stop intact. This guards against the
// "find first emitStart" misattribution bug (which would drop the first,
// balanced span and leave the orphan emitted).
let score: Score = Score(bpm: 120) {
Part("p") {
// Balanced span: C5 → D5.
Note(.c, 5, dur: .quarter, spanners: [.beginSlur])
Note(.d, 5, dur: .quarter, spanners: [.endSlur])
// Orphan span: E5 opens, never closes.
Note(.e, 5, dur: .quarter, spanners: [.beginSlur])
Note(.f, 5, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
// Exactly one balanced start/stop pair survives (the first span); the
// orphan second start is dropped.
let slurStart: Int = xml.components(separatedBy: "<slur number=\"1\" type=\"start\"/>").count - 1
let slurStop: Int = xml.components(separatedBy: "<slur number=\"1\" type=\"stop\"/>").count - 1
#expect(slurStart == 1, "only the balanced span's start should survive")
#expect(slurStop == 1, "the balanced span's stop must remain")
// The surviving start must precede the stop (it is the first span, not the orphan).
let startRange: Range<String.Index>? = xml.range(of: "<slur number=\"1\" type=\"start\"/>")
let stopRange: Range<String.Index>? = xml.range(of: "<slur number=\"1\" type=\"stop\"/>")
if let s: Range<String.Index> = startRange, let t: Range<String.Index> = stopRange {
#expect(s.lowerBound < t.lowerBound)
} else {
Issue.record("Expected the balanced span's start and stop to survive")
}
}
@Test func balancedHairpinSurvivesWhenLaterHairpinInSameVoiceIsOrphaned() {
// Hairpin analog of the slur multi-span survival test: a balanced
// crescendo followed by an orphan-open crescendo in the same voice.
// Cleanup must drop ONLY the orphan second start, keeping the first
// balanced hairpin's start + stop.
let score: Score = Score(bpm: 120) {
Part("p") {
// Balanced hairpin: C5 → D5.
Note(.c, 5, dur: .quarter, spanners: [.beginCrescendo])
Note(.d, 5, dur: .quarter, spanners: [.endHairpin])
// Orphan hairpin: E5 opens, never closes.
Note(.e, 5, dur: .quarter, spanners: [.beginCrescendo])
Note(.f, 5, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
let crescStarts: Int = xml.components(separatedBy: "<wedge type=\"crescendo\"/>").count - 1
let wedgeStops: Int = xml.components(separatedBy: "<wedge type=\"stop\"/>").count - 1
#expect(crescStarts == 1, "only the balanced hairpin's start should survive")
#expect(wedgeStops == 1, "the balanced hairpin's stop must remain")
}
}
+1 -1
View File
@@ -179,7 +179,7 @@ struct SpringReverbTests {
"mulAdd(2, 1) on silent input must produce 1.0; got \(out[0][0])")
}
/// Phase 175 — branchless ring-buffer wrap exercised across many wraps.
/// Branchless ring-buffer wrap exercised across many wraps.
/// Render long enough that the main delay line (≈ 50 ms × 44100 ≈ 2205 samples)
/// wraps multiple times. Drive a quiet but non-zero input to keep ring values
/// non-trivial and verify output stays finite + bounded over the full render.
@@ -0,0 +1,218 @@
// StaffPedalRoundTripTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
/// Round-trip tests for the Staff / Pedal encode→decode path.
///
/// ## What round-trips
///
/// - Event count and sounding pitches survive round-trip (flatten() on the
/// decoded Score produces the same number of events as flatten() on the source).
/// - Pedal marks (`<pedal type="start|stop">`) are decoded back to `.pedal`
/// elements in the reconstructed `ScorePart`.
/// - Per-staff clef values are decoded from `<clef number="k">` and stored on
/// the `ScorePart.clef` (first-staff clef wins for the part-level clef).
///
/// ## What does NOT round-trip (documented-lossy)
///
/// - The `.staff(n, clef, [children])` grouping structure is NOT reconstructed.
/// After decode, notes that were in Staff(1) and Staff(2) are partitioned only
/// by voice number — the structural `Staff(...)` wrapper is lost. This is
/// analogous to how tuplet structure is not reconstructed from `<time-modification>`.
/// - Multiple distinct staves collapse back to a flat multi-voice structure
/// (each voice's notes are wrapped in a `.voice(n, [...])` block, unaffected
/// by the original staff grouping).
@MainActor
@Suite("Staff and Pedal — MusicXML round-trip")
struct StaffPedalRoundTripTests {
// MARK: - Single-staff parts — regression guard
@Test func singleStaffPartRoundTripsUnchanged() throws {
let score: Score = Score(bpm: 120) {
Part("piano") {
Note(.c, 4, dur: .quarter)
Note(.d, 4, dur: .quarter)
Note(.e, 4, dur: .quarter)
Note(.f, 4, dur: .quarter)
}
}
let data: Data = score.toMusicXMLData()
let decoded: Score = try Score.fromMusicXML(data: data)
#expect(decoded.parts.count == 1)
let sourceEvents: [ScoreEvent] = score.parts[0].flatten()
let decodedEvents: [ScoreEvent] = decoded.parts[0].flatten()
#expect(decodedEvents.count == sourceEvents.count)
let sourceMidis: [Int] = sourceEvents.compactMap { $0.pitch.midiNote }.sorted()
let decodedMidis: [Int] = decodedEvents.compactMap { $0.pitch.midiNote }.sorted()
#expect(decodedMidis == sourceMidis)
}
// MARK: - Multi-staff round-trip — event count and pitches
@Test func multiStaffEventCountSurvivesRoundTrip() throws {
// Two-staff piano part with 3 events total (2 in staff 1, 1 in staff 2).
let score: Score = Score(bpm: 120) {
Part("piano", clef: .treble) {
Staff(1) {
Voice(1) { Note(.e, 5, dur: .half) }
Voice(2) { Note(.c, 5, dur: .half) }
}
Staff(2, clef: .bass) {
Voice(3) { Note(.c, 3, dur: .whole) }
}
}
}
let sourceEvents: [ScoreEvent] = score.parts[0].flatten()
#expect(sourceEvents.count == 3)
let data: Data = score.toMusicXMLData()
let decoded: Score = try Score.fromMusicXML(data: data)
let decodedEvents: [ScoreEvent] = decoded.parts[0].flatten()
#expect(decodedEvents.count == sourceEvents.count)
}
@Test func multiStaffPitchesSurviveRoundTrip() throws {
let score: Score = Score(bpm: 120) {
Part("piano", clef: .treble) {
Staff(1) {
Voice(1) { Note(.c, 5, dur: .whole) }
}
Staff(2, clef: .bass) {
Voice(2) { Note(.c, 3, dur: .whole) }
}
}
}
let data: Data = score.toMusicXMLData()
let decoded: Score = try Score.fromMusicXML(data: data)
let decodedEvents: [ScoreEvent] = decoded.parts[0].flatten()
let midis: [Int] = decodedEvents.compactMap { $0.pitch.midiNote }.sorted()
// C3 = MIDI 48, C5 = MIDI 72
#expect(midis == [48, 72])
}
@Test func multiStaffClefSurvivesRoundTrip() throws {
// Staff 2 uses bass clef — verify the decoded part picks it up.
let score: Score = Score(bpm: 120) {
Part("piano", clef: .treble) {
Staff(1) {
Voice(1) { Note(.c, 5, dur: .whole) }
}
Staff(2, clef: .bass) {
Voice(2) { Note(.c, 3, dur: .whole) }
}
}
}
let xml: String = score.toMusicXMLString()
// Sanity: encoded XML has both clef numbers.
#expect(xml.contains("<clef number=\"1\">"))
#expect(xml.contains("<clef number=\"2\">"))
let data: Data = Data(xml.utf8)
let decoded: Score = try Score.fromMusicXML(data: data)
// The decoded part's clef comes from staff 1's clef (first clef in the part
// wins for the part-level clef — existing round-trip convention).
// Staff 1 is treble, so the decoded part clef is treble.
#expect(decoded.parts[0].clef == .treble)
}
// MARK: - Pedal round-trip
@Test func pedalStartStopSurviveRoundTrip() throws {
let score: Score = Score(bpm: 120) {
Part("piano") {
Pedal(.start)
Note(.c, 4, dur: .half)
Note(.d, 4, dur: .half)
Pedal(.stop)
}
}
let data: Data = score.toMusicXMLData()
let decoded: Score = try Score.fromMusicXML(data: data)
// Event count should be preserved (2 sounding notes).
let decodedEvents: [ScoreEvent] = decoded.parts[0].flatten()
#expect(decodedEvents.count == 2)
// The decoded part should contain pedal elements.
let decodedElements: [ScoreElement] = decoded.parts[0].elements
let pedalElements: [ScoreElement] = decodedElements.filter {
if case .pedal = $0 { return true }
return false
}
#expect(pedalElements.count == 2)
// Verify start and stop are both present.
let hasStart: Bool = pedalElements.contains {
if case .pedal(let k) = $0 { return k == .start }
return false
}
let hasStop: Bool = pedalElements.contains {
if case .pedal(let k) = $0 { return k == .stop }
return false
}
#expect(hasStart)
#expect(hasStop)
}
@Test func pedalDoesNotProduceScoreEventsAfterRoundTrip() throws {
let score: Score = Score(bpm: 120) {
Part("piano") {
Pedal(.start)
Note(.c, 4, dur: .quarter)
Pedal(.stop)
}
}
let data: Data = score.toMusicXMLData()
let decoded: Score = try Score.fromMusicXML(data: data)
let events: [ScoreEvent] = decoded.parts[0].flatten()
// Only the quarter note should be an event; pedal marks are zero-duration.
#expect(events.count == 1)
#expect(events[0].pitch.midiNote == 60) // C4 = MIDI 60
}
// MARK: - Multi-staff + pedal combined round-trip
@Test func multiStaffWithPedalPreservesEventCountAndPedals() throws {
let score: Score = Score(bpm: 120) {
Part("piano", clef: .treble) {
Staff(1) {
Voice(1) { Note(.c, 5, dur: .whole) }
}
Staff(2, clef: .bass) {
Voice(2) {
Pedal(.start)
Note(.c, 3, dur: .whole)
Pedal(.stop)
}
}
}
}
let data: Data = score.toMusicXMLData()
let decoded: Score = try Score.fromMusicXML(data: data)
// Event count: 2 sounding notes (one per staff).
let decodedEvents: [ScoreEvent] = decoded.parts[0].flatten()
#expect(decodedEvents.count == 2)
// Pedal elements should be present somewhere in the decoded part.
func containsPedal(_ elements: [ScoreElement]) -> Bool {
for element: ScoreElement in elements {
switch element {
case .pedal: return true
case .voice(_, let children): if containsPedal(children) { return true }
case .staff(_, _, let children): if containsPedal(children) { return true }
default: break
}
}
return false
}
#expect(containsPedal(decoded.parts[0].elements))
}
}
+281
View File
@@ -0,0 +1,281 @@
// StaffPedalTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("Staff and Pedal notation — DSL, flatten, and MusicXML encode")
struct StaffPedalTests {
// MARK: - PedalKind
@Test func pedalKindMusicXMLType() {
#expect(PedalKind.start.musicXMLType == "start")
#expect(PedalKind.stop.musicXMLType == "stop")
}
// MARK: - Staff DSL
@Test func staffDSLBuildsStaffElement() {
let element: ScoreElement = Staff(2, clef: .bass) {
Note(.c, 3, dur: .whole, dyn: .mp)
}
guard case .staff(let number, let clef, let children) = element else {
Issue.record("Expected .staff case")
return
}
#expect(number == 2)
#expect(clef == .bass)
#expect(children.count == 1)
}
@Test func staffDSLWithNoClefStoresNil() {
let element: ScoreElement = Staff(1) {
Note(.c, 4, dur: .quarter)
}
guard case .staff(let number, let clef, _) = element else {
Issue.record("Expected .staff case")
return
}
#expect(number == 1)
#expect(clef == nil)
}
@Test func staffPreconditionMinimumOneIsEnforced() {
// Verify that number >= 1 is the accepted lower bound by testing valid values.
// (Precondition trap on 0 is a runtime-only test; we confirm the happy path.)
let element: ScoreElement = Staff(1) { Rest(dur: .quarter) }
if case .staff(let n, _, _) = element {
#expect(n == 1)
}
}
// MARK: - Pedal DSL
@Test func pedalDSLBuildsStartElement() {
let element: ScoreElement = Pedal(.start)
guard case .pedal(let kind) = element else {
Issue.record("Expected .pedal case")
return
}
#expect(kind == .start)
}
@Test func pedalDSLBuildsStopElement() {
let element: ScoreElement = Pedal(.stop)
guard case .pedal(let kind) = element else {
Issue.record("Expected .pedal case")
return
}
#expect(kind == .stop)
}
// MARK: - flatten() — Staff produces ScoreEvents
@Test func staffFlattenYieldsNotesFromChildren() {
let part: ScorePart = ScorePart(name: "piano", elements: [
Staff(1) {
Voice(1) { Note(.c, 5, dur: .quarter) }
},
Staff(2, clef: .bass) {
Voice(2) { Note(.c, 3, dur: .whole) }
},
])
let events: [ScoreEvent] = part.flatten()
#expect(events.count == 2)
let midis: [Int] = events.compactMap { $0.pitch.midiNote }.sorted()
// C3 = MIDI 48, C5 = MIDI 72
#expect(midis.contains(48))
#expect(midis.contains(72))
}
@Test func staffFlattenDoesNotAdvanceOuterCursor() {
// Two Staff blocks — both start at beat 0.
let part: ScorePart = ScorePart(name: "p", elements: [
Staff(1) {
Note(.e, 5, dur: .quarter, voice: 1)
Note(.d, 5, dur: .quarter, voice: 1)
},
Staff(2, clef: .bass) {
Note(.c, 3, dur: .half, voice: 2)
},
])
let events: [ScoreEvent] = part.flatten()
#expect(events.count == 3)
// Staff 2 whole note starts at beat 0.
let staff2Events: [ScoreEvent] = events.filter { $0.voice == 2 }
#expect(staff2Events.count == 1)
#expect(staff2Events[0].beat == 0.0)
#expect(staff2Events[0].duration == 2.0)
}
// MARK: - flatten() — Pedal is skipped
@Test func pedalIsSkippedByFlatten() {
let part: ScorePart = ScorePart(name: "p", elements: [
Pedal(.start),
Note(.c, 4, dur: .quarter),
Note(.d, 4, dur: .quarter),
Pedal(.stop),
])
let events: [ScoreEvent] = part.flatten()
// Only the two notes should appear; pedal marks contribute no events.
#expect(events.count == 2)
#expect(events[0].beat == 0.0)
#expect(events[1].beat == 1.0)
}
// MARK: - Single-staff encode — byte-identical regression guard
@Test func singleStaffPartEmitsNoByteDifference() {
// A part with no Staff(...) block should emit exactly the same XML as before.
let scoreA: Score = Score(bpm: 120) {
Part("piano") {
Note(.c, 4, dur: .quarter)
Note(.d, 4, dur: .quarter)
}
}
let xmlA: String = scoreA.toMusicXMLString()
#expect(!xmlA.contains("<staves>"))
#expect(!xmlA.contains("<clef number="))
#expect(!xmlA.contains("<staff>"))
}
// MARK: - Multi-staff encode
@Test func multiStaffPartEmitsStavesElement() {
let score: Score = Score(bpm: 120) {
Part("piano", clef: .treble) {
Staff(1) {
Voice(1) { Note(.c, 5, dur: .whole) }
}
Staff(2, clef: .bass) {
Voice(2) { Note(.c, 3, dur: .whole) }
}
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<staves>2</staves>"))
}
@Test func multiStaffPartEmitsPerStaffClef() {
let score: Score = Score(bpm: 120) {
Part("piano", clef: .treble) {
Staff(1) {
Voice(1) { Note(.c, 5, dur: .whole) }
}
Staff(2, clef: .bass) {
Voice(2) { Note(.c, 3, dur: .whole) }
}
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<clef number=\"1\">"))
#expect(xml.contains("<clef number=\"2\">"))
// Staff-1 clef: treble (G, line 2)
// Staff-2 clef: bass (F, line 4)
#expect(xml.contains("<sign>G</sign>"))
#expect(xml.contains("<sign>F</sign>"))
// Should NOT contain a bare <clef> (no number attribute) in attributes.
// The bare form only appears in the mid-measure <attributes><clef> block.
// Quick sanity: verify <clef number= appears, not just <clef>.
let clefCount: Int = xml.components(separatedBy: "<clef number=").count - 1
#expect(clefCount == 2)
}
@Test func multiStaffPartEmitsStaffElementOnNotes() {
let score: Score = Score(bpm: 120) {
Part("piano", clef: .treble) {
Staff(1) {
Voice(1) { Note(.c, 5, dur: .whole) }
}
Staff(2, clef: .bass) {
Voice(2) { Note(.c, 3, dur: .whole) }
}
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<staff>1</staff>"))
#expect(xml.contains("<staff>2</staff>"))
}
// MARK: - Pedal encode — single-staff (no <staff> child in direction)
@Test func pedalEmitsSingleStaffDirection() {
let score: Score = Score(bpm: 120) {
Part("piano") {
Pedal(.start)
Note(.c, 4, dur: .whole)
Pedal(.stop)
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<pedal type=\"start\" line=\"yes\"/>"))
#expect(xml.contains("<pedal type=\"stop\" line=\"yes\"/>"))
// Single-staff: no <staff> inside the direction.
let directionBlocks: [String] = xml.components(separatedBy: "<direction placement=\"below\">")
// There should be at least the dynamic direction + 2 pedal directions.
// Each pedal direction block should NOT contain <staff>.
let pedalStartBlock: Bool = directionBlocks.contains { $0.contains("pedal type=\"start\"") && !$0.contains("<staff>") }
#expect(pedalStartBlock)
}
@Test func pedalEmitsMultiStaffDirectionWithStaff() {
let score: Score = Score(bpm: 120) {
Part("piano", clef: .treble) {
Staff(1) {
Voice(1) { Note(.c, 5, dur: .quarter) }
}
Staff(2, clef: .bass) {
Voice(2) {
Pedal(.start)
Note(.c, 3, dur: .whole)
Pedal(.stop)
}
}
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<pedal type=\"start\" line=\"yes\"/>"))
#expect(xml.contains("<pedal type=\"stop\" line=\"yes\"/>"))
// Multi-staff: the pedal direction authored under Staff(2) should carry <staff>2</staff>.
// Check that the pedal start direction contains the staff element.
// The direction block is:
// <direction placement="below">
// <direction-type>
// <pedal type="start" line="yes"/>
// </direction-type>
// <staff>2</staff> ← present in multi-staff
// </direction>
let hasPedalWithStaff2: Bool = xml.contains("pedal type=\"start\"") && xml.contains("<staff>2</staff>")
#expect(hasPedalWithStaff2)
}
@Test("Staff block contributes zero span to a ScoreTimeline fill")
func staffContributesZeroSpanToTimelineFill() throws {
// A Staff block overlays from beat 0, so it must NOT advance the timeline
// cursor. Placing a whole-note Staff at beat 1 and a quarter note at beat 2
// must resolve without an overlap trap — which WOULD fire if the staff's
// four-beat span advanced the cursor past the second placement.
let filled: [ScoreElement] = try ScoreTimeline.fill(
[
(.beat(1.0), Staff(1) { Note(.named(.c, 4), dur: .whole) }),
(.beat(2.0), Note(.named(.d, 4), dur: .quarter)),
],
meter: MeterMap(.fourFour)
)
let staffCount: Int = filled.filter { if case .staff = $0 { return true } else { return false } }.count
let restCount: Int = filled.filter { if case .rest = $0 { return true } else { return false } }.count
let noteCount: Int = filled.filter { if case .note = $0 { return true } else { return false } }.count
// One Staff, one gap-bridging rest (beat 1 → beat 2), one note — the staff
// consumed zero timeline space.
#expect(staffCount == 1)
#expect(noteCount == 1)
#expect(restCount == 1)
}
}
@@ -475,9 +475,9 @@ struct LFLineNoiseTests {
// first random endValue produced by the seeded xorshift64 in init.
// With freq=1, sampleRate=100: 100 samples per segment.
// endValue value pre-computed from the seed XOR-mixed with LFLineNoise.Audio's
// unique mix constant (Phase 191: 0xD9C8_B7A6_9584_7362), then one xorshift64 step
// mapped to [-1, 1]. Phase 191 unique per-(type, rate) mix constants changed this
// value from its pre-191 baseline.
// unique mix constant (0xD9C8_B7A6_9584_7362), then one xorshift64 step
// mapped to [-1, 1]. Unique per-(type, rate) mix constants determine this
// value.
// At samplePos=0: t=0/100=0, output = startValue + (endValue - startValue)*0 = 0.0
// At samplePos=50: t=50/100=0.5, output = endValue * 0.5
let endValue: Double = 0.9148710322550571
@@ -2590,7 +2590,7 @@ struct DelayLineTests {
#expect(s.allSatisfy { abs($0) <= 1.0 + 1e-6 })
}
/// Phase 176 — branchless wrap on the power-of-2 ring buffer exercised across
/// Branchless wrap on the power-of-2 ring buffer exercised across
/// many wraps. With `maxDelay = 0.01` (≈ 441 samples at 44.1 kHz, rounded up
/// to the next PoT = 512), a ~2 s render at blockSize 64 = ~1378 blocks does
/// ~172 full wraps of the ring buffer. Drive a small but non-zero input
@@ -3018,7 +3018,7 @@ struct LFCurveNoiseTests {
// a = 0.5*(y0+y2) - y1, b = 0.5*(y2-y0)
// output = (a*0 + b)*0 + y1 = y1
// y0, y1, y2 seeded by three xorshift64 calls from the mixed seed.
// Pre-computed under Phase 191's unique per-(type, rate) mix constant
// Pre-computed under the unique per-(type, rate) mix constant
// (LFCurveNoise.Audio = 0x4B2C_3A1D_8E7F_6D5C). y1 = second of three
// xorshift64Next() draws after seeding with `12345 XOR mixConstant`.
let expectedFirstSample: Double = 0.049728941172129115
@@ -3044,15 +3044,14 @@ struct LFCurveNoiseTests {
let graph2: SynthGraph = makeSynthGraph(engine: engine2)
let testFreq: Double = 5.0
// Phase 191 — LFCurveNoise.Audio and LFLineNoise.Audio now have
// LFCurveNoise.Audio and LFLineNoise.Audio have
// distinct mix constants, so a "shared seed" no longer produces
// identical PRNG trajectories. The smoothness ordering check
// (parabolic interpolation second-diff RMS < linear-interpolation
// second-diff RMS) is an intrinsic property of the interpolation
// mode, but the specific sample sequences make it data-dependent.
// Seed 42 lands a clean ordering; see Phase 191 cleanup commit for
// the seed-sweep that confirmed >half of small seeds preserve the
// ordering after decorrelation.
// Seed 42 lands a clean ordering; a seed-sweep confirmed >half of
// small seeds preserve the ordering after decorrelation.
let sharedSeed: UInt64 = 42
let numBlocks: Int = 50
let blockCount: Int = 100
@@ -213,7 +213,7 @@ import Testing
@Test func dropsCountedWhenQueueFull() throws {
// Fill the queue without draining (do NOT start the engine — processBlock drains it).
// Phase 196.2: engine.add now throws EngineAddError.pendingQueueFull
// engine.add throws EngineAddError.pendingQueueFull
// instead of returning Bool false. Test reformulated to count
// successful enqueues via do/catch.
let e: SynthesisEngine = makeTestEngine(blockSize: 8, eventQueueCapacity: 4)
@@ -0,0 +1,76 @@
// TheoryMusicXMLRoundTripTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
/// Confirms spellings produced by theory-layer transposition survive a full
/// MusicXML encode → decode round-trip (the spelled letter + accidental are not
/// collapsed to an enharmonic equivalent).
@Suite("Theory → MusicXML round-trip — transposed spellings survive export")
struct TheoryMusicXMLRoundTripTests {
/// Build a single-part score from named pitches (quarter notes).
private func score(from pitches: [Pitch]) throws -> Score {
var notes: [(NoteName, Int)] = []
for pitch: Pitch in pitches {
guard case .named(let name, let octave) = pitch else {
throw ScaleError.nonNamedPitch(pitch)
}
notes.append((name, octave))
}
return Score(bpm: 120) {
Part("p") {
for note: (NoteName, Int) in notes {
Note(note.0, note.1, dur: .quarter)
}
}
}
}
private func roundTrip(_ score: Score) throws -> [NoteName] {
let xml: String = score.toMusicXMLString()
let decoded: Score = try Score.fromMusicXML(data: Data(xml.utf8))
let events: [ScoreEvent] = decoded.parts[0].flatten()
var names: [NoteName] = []
for event: ScoreEvent in events {
guard case .named(let name, _) = event.pitch else { continue }
names.append(name)
}
return names
}
@Test func chromaticTransposeSharpSpellingsSurvive() throws {
// C-D-A up a major third = E-F#-C# (sharps must survive, not become Gb etc).
let phrase: PitchCollection = PitchCollection(pitches: [
.named(.c, 4), .named(.d, 4), .named(.a, 4),
])
let up: PitchCollection = try phrase.transposedChromatic(by: .majorThird)
let names: [NoteName] = try roundTrip(try score(from: up.pitches))
#expect(names == [.e, .fSharp, .cSharp])
}
@Test func augmentedSecondBSharpSurvives() throws {
// A +aug2 = B# — the round-trip must NOT collapse it to C natural.
let up: Pitch = try Pitch.named(.a, 4).transposed(by: .augmentedSecond)
let names: [NoteName] = try roundTrip(try score(from: [up]))
#expect(names == [.bSharp])
#expect(names.first != .c)
}
@Test func flatModeMappingSurvives() throws {
// C major triad mapped to Eb major = Eb-G-Bb (flats must survive).
let cMajor: Scale = try Scale.major(.c)
let eFlatMajor: Scale = try Scale.major(.eFlat)
let triad: PitchCollection = PitchCollection(pitches: [
.named(.c, 4), .named(.e, 4), .named(.g, 4),
])
let mapped: PitchCollection = try triad.mapped(from: cMajor, to: eFlatMajor)
let names: [NoteName] = try roundTrip(try score(from: mapped.pitches))
#expect(names == [.eFlat, .g, .bFlat])
}
}
@@ -0,0 +1,96 @@
// TimeSignatureTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("TimeSignature — grouping, compound, derived")
struct TimeSignatureTests {
// MARK: - Default grouping inference
@Test func simpleMetersGroupByOne() {
#expect(TimeSignature(4, 4).beatGrouping == [1, 1, 1, 1])
#expect(TimeSignature(3, 4).beatGrouping == [1, 1, 1])
#expect(TimeSignature(2, 2).beatGrouping == [1, 1])
#expect(TimeSignature(5, 4).beatGrouping == [1, 1, 1, 1, 1])
}
@Test func compoundMetersGroupByThree() {
#expect(TimeSignature(6, 8).beatGrouping == [3, 3])
#expect(TimeSignature(9, 8).beatGrouping == [3, 3, 3])
#expect(TimeSignature(12, 8).beatGrouping == [3, 3, 3, 3])
#expect(TimeSignature(6, 16).beatGrouping == [3, 3])
}
@Test func threeEightIsSimpleNotCompound() {
// numerator must be > 3 for the compound default.
#expect(TimeSignature(3, 8).beatGrouping == [1, 1, 1])
#expect(TimeSignature(3, 8).isCompound == false)
}
@Test func quarterDenominatorNeverCompoundByDefault() {
// 6/4 is divisible by 3 but denominator 4 is not a compound unit.
#expect(TimeSignature(6, 4).beatGrouping == [1, 1, 1, 1, 1, 1])
}
// MARK: - Explicit override
@Test func slowSixEightCanBeSimple() {
let ts: TimeSignature = TimeSignature(6, 8, grouping: [1, 1, 1, 1, 1, 1])
#expect(ts.isCompound == false)
#expect(ts.beatsPerBar == 6)
}
@Test func additiveComplexMeter() {
// 3+3+2 / 8 → dotted-quarter, dotted-quarter, quarter.
let ts: TimeSignature = TimeSignature(8, 8, grouping: [3, 3, 2])
#expect(ts.beatGrouping == [3, 3, 2])
#expect(ts.isCompound == true)
#expect(ts.beatsPerBar == 3)
}
// MARK: - Derived values
@Test func measureQuartersMatchesNumDenom() {
#expect(TimeSignature(4, 4).measureQuarters == Fraction(4, 1))
#expect(TimeSignature(3, 4).measureQuarters == Fraction(3, 1))
#expect(TimeSignature(6, 8).measureQuarters == Fraction(3, 1))
#expect(TimeSignature(7, 8).measureQuarters == Fraction(7, 2))
#expect(TimeSignature(2, 2).measureQuarters == Fraction(4, 1))
}
@Test func isCompoundReflectsGrouping() {
#expect(TimeSignature(4, 4).isCompound == false)
#expect(TimeSignature(6, 8).isCompound == true)
#expect(TimeSignature(6, 8, grouping: [1, 1, 1, 1, 1, 1]).isCompound == false)
}
// MARK: - Construction conveniences
@Test func tupleInitInfersGrouping() {
let ts: TimeSignature = TimeSignature((6, 8))
#expect(ts.numerator == 6)
#expect(ts.denominator == 8)
#expect(ts.beatGrouping == [3, 3])
#expect(ts.tuple == (6, 8))
}
@Test func namedStatics() {
#expect(TimeSignature.fourFour.tuple == (4, 4))
#expect(TimeSignature.sixEightCompound.beatGrouping == [3, 3])
#expect(TimeSignature.sixEightSimple.beatGrouping == [1, 1, 1, 1, 1, 1])
#expect(TimeSignature.nineEight.beatsPerBar == 3)
#expect(TimeSignature.cutTime.measureQuarters == Fraction(4, 1))
}
@Test func hashableEquality() {
#expect(TimeSignature(4, 4) == TimeSignature(4, 4))
// same num/denom, different grouping → not equal.
#expect(TimeSignature(6, 8) != TimeSignature(6, 8, grouping: [1, 1, 1, 1, 1, 1]))
}
}
@@ -0,0 +1,261 @@
// TupletNoteDurationTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable import LyrebirdSynth
@MainActor
@Suite("Tuplet noteDuration validation")
struct TupletNoteDurationTests {
// MARK: - Matching contents → no warning
@Test func threeQuartersFillQuarterTriplet() {
let kids: [ScoreElement] = [
Note(.c, 5, dur: .quarter),
Note(.d, 5, dur: .quarter),
Note(.e, 5, dur: .quarter)
]
#expect(tupletContentsMismatchWarning(
actual: 3, normal: 2, noteDuration: .quarter, children: kids
) == nil)
}
@Test func fiveSixteenthsFillSixteenthQuintuplet() {
let kids: [ScoreElement] = (0..<5).map { _ in Note(.c, 5, dur: .sixteenth) }
#expect(tupletContentsMismatchWarning(
actual: 5, normal: 4, noteDuration: .sixteenth, children: kids
) == nil)
}
@Test func mixedRhythmThatTotalsCorrectlyIsOk() {
// The bracket means "3 quarters' worth"; a half + quarter (2 + 1 = 3
// quarter-beats) fills it even though the rhythm is not 3 equal notes.
let kids: [ScoreElement] = [
Note(.c, 5, dur: .half),
Note(.d, 5, dur: .quarter)
]
#expect(tupletContentsMismatchWarning(
actual: 3, normal: 2, noteDuration: .quarter, children: kids
) == nil)
}
// MARK: - Mismatched contents → warning
@Test func wholeNoteInQuarterTripletWarns() {
// The exact authoring bug: a whole note inside a 3:2 quarter triplet
// (contents total 1 + 4 + 1 = 6, but 3 quarters = 3) → over-fills.
let kids: [ScoreElement] = [
Note(.c, 5, dur: .quarter),
Note(.d, 5, dur: .whole),
Note(.e, 5, dur: .quarter)
]
let warning: String? = tupletContentsMismatchWarning(
actual: 3, normal: 2, noteDuration: .quarter, children: kids
)
#expect(warning != nil)
}
@Test func underfilledTripletWarns() {
// Only 2 quarters where 3 are expected.
let kids: [ScoreElement] = [
Note(.c, 5, dur: .quarter),
Note(.d, 5, dur: .quarter)
]
#expect(tupletContentsMismatchWarning(
actual: 3, normal: 2, noteDuration: .quarter, children: kids
) != nil)
}
// MARK: - The DSL still builds a valid element on mismatch (warning, not trap)
@Test func tupletStillBuildsOnMismatch() {
let element: ScoreElement = Tuplet(3, inTimeOf: 2, noteDuration: .quarter) {
Note(.c, 5, dur: .whole) // mismatched on purpose
}
if case .tuplet(let a, let n, _, _) = element {
#expect(a == 3)
#expect(n == 2)
} else {
Issue.record("Tuplet must still return a .tuplet element despite the warning")
}
}
// MARK: - Nested tuplets count by their COMPRESSED span (no false positive)
@Test func nestedTupletCountedByCompressedSpan() {
// A nested eighth-triplet (3 eighths in the time of 2) occupies exactly one
// quarter of the OUTER bracket. So [quarter, quarter, nested] totals 3
// outer-quarters → fills a quarter triplet exactly → no warning.
let nested: ScoreElement = Tuplet(3, inTimeOf: 2) {
Note(.c, 5, dur: .eighth)
Note(.d, 5, dur: .eighth)
Note(.e, 5, dur: .eighth)
}
let kids: [ScoreElement] = [
Note(.c, 5, dur: .quarter),
Note(.d, 5, dur: .quarter),
nested
]
#expect(tupletContentsMismatchWarning(
actual: 3, normal: 2, noteDuration: .quarter, children: kids
) == nil)
}
@Test func nestedTupletThatUnderfillsWarns() {
// A nested quarter-triplet (3 quarters in the time of 2) occupies only TWO
// outer-quarters — it does NOT fill a 3-quarter outer bracket → warning.
let nested: ScoreElement = Tuplet(3, inTimeOf: 2) {
Note(.c, 5, dur: .quarter)
Note(.d, 5, dur: .quarter)
Note(.e, 5, dur: .quarter)
}
#expect(tupletContentsMismatchWarning(
actual: 3, normal: 2, noteDuration: .quarter, children: [nested]
) != nil)
}
// MARK: - Message distinguishes over-fill from under-fill
@Test func messageReportsDirection() {
let over: String? = tupletContentsMismatchWarning(
actual: 3, normal: 2, noteDuration: .quarter,
children: [Note(.c, 5, dur: .whole)] // 4 > 3
)
#expect(over?.contains("over-fill") == true)
let under: String? = tupletContentsMismatchWarning(
actual: 3, normal: 2, noteDuration: .quarter,
children: [Note(.c, 5, dur: .quarter)] // 1 < 3
)
#expect(under?.contains("under-fill") == true)
}
// MARK: - Without noteDuration, no validation (flexible tuplets)
@Test func noNoteDurationStillBuilds() {
let element: ScoreElement = Tuplet(3, inTimeOf: 2) {
Note(.c, 5, dur: .whole) // would warn IF a noteDuration were declared
}
if case .tuplet = element { } else {
Issue.record("expected .tuplet")
}
}
// MARK: - <normal-type> emission
/// A half-note triplet authored with `noteDuration: .half` must emit
/// `<normal-type>half</normal-type>` inside `<time-modification>` for every
/// tuplet member. Three members → appears exactly 3 times in the XML.
@Test func halfNoteTripletEmitsNormalType() {
let score: Score = Score(bpm: 60.0) {
Part("test") {
Tuplet(3, inTimeOf: 2, noteDuration: .half) {
Note(.c, 5, dur: .quarter)
Note(.d, 5, dur: .whole)
Note(.e, 5, dur: .quarter)
}
}
}
let xml: String = score.toMusicXMLString()
// Each of the 3 members must carry <normal-type>half</normal-type>.
let occurrences: Int = xml.components(separatedBy: "<normal-type>half</normal-type>").count - 1
#expect(occurrences == 3)
// Sanity: actual- and normal-notes are also present (3 and 2).
#expect(xml.contains("<actual-notes>3</actual-notes>"))
#expect(xml.contains("<normal-notes>2</normal-notes>"))
}
/// A standard eighth-triplet WITHOUT `noteDuration:` must NOT emit `<normal-type>`.
/// Byte-identical guard: the tag must be completely absent.
@Test func standardTripletWithoutNoteDurationEmitsNoNormalType() {
let score: Score = Score(bpm: 60.0) {
Part("test") {
Tuplet(3, inTimeOf: 2) {
Note(.c, 5, dur: .eighth)
Note(.d, 5, dur: .eighth)
Note(.e, 5, dur: .eighth)
}
// Fill remainder of the 4/4 bar so the measure is valid.
Note(.f, 5, dur: .eighth)
}
}
let xml: String = score.toMusicXMLString()
#expect(!xml.contains("<normal-type>"))
}
/// A dotted base value (`noteDuration: .quarter.dotted`) must emit
/// `<normal-type>quarter</normal-type>` followed by `<normal-dot/>`.
@Test func dottedNoteDurationEmitsNormalTypeAndDot() {
let score: Score = Score(bpm: 60.0) {
Part("test") {
// 3 dotted-quarters in time of 2: 3 × 1.5 = 4.5 quarter-beats.
// Place in a 9/8 bar (same total) or just test the XML content.
Tuplet(3, inTimeOf: 2, noteDuration: .quarter.dotted) {
Note(.c, 5, dur: .quarter.dotted)
Note(.d, 5, dur: .quarter.dotted)
Note(.e, 5, dur: .quarter.dotted)
}
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<normal-type>quarter</normal-type>"))
#expect(xml.contains("<normal-dot/>"))
}
/// Flattening a tuplet with `noteDuration:` yields the same `ScoreEvent` list
/// as flattening one without — the field is notation-only.
@Test func normalTypeIsNotationOnly() {
let scoreWith: Score = Score(bpm: 60.0) {
Part("test") {
Tuplet(3, inTimeOf: 2, noteDuration: .quarter) {
Note(.c, 5, dur: .quarter)
Note(.d, 5, dur: .quarter)
Note(.e, 5, dur: .quarter)
}
}
}
let scoreWithout: Score = Score(bpm: 60.0) {
Part("test") {
Tuplet(3, inTimeOf: 2) {
Note(.c, 5, dur: .quarter)
Note(.d, 5, dur: .quarter)
Note(.e, 5, dur: .quarter)
}
}
}
let eventsWithNormalType: [ScoreEvent] = scoreWith.parts[0].flatten()
let eventsWithoutNormalType: [ScoreEvent] = scoreWithout.parts[0].flatten()
#expect(eventsWithNormalType.count == eventsWithoutNormalType.count)
// Sounding durations must be identical.
for (a, b): (ScoreEvent, ScoreEvent) in zip(eventsWithNormalType, eventsWithoutNormalType) {
#expect(a.duration == b.duration)
}
}
/// Nested tuplets carry their OWN declared note value: the inner bracket's
/// `noteDuration` reaches only the inner atoms, and the outer bracket (with no
/// `noteDuration`) emits no `<normal-type>` at all — no bleed-through.
@Test func nestedTupletNormalTypeIsInnerOnly() {
let score: Score = Score(bpm: 60.0) {
Part("test") {
Tuplet(3, inTimeOf: 2) { // outer: no noteDuration
Note(.c, 5, dur: .quarter)
Note(.d, 5, dur: .quarter)
Tuplet(3, inTimeOf: 2, noteDuration: .eighth) { // inner: eighth
Note(.e, 5, dur: .eighth)
Note(.f, 5, dur: .eighth)
Note(.g, 5, dur: .eighth)
}
}
}
}
let xml: String = score.toMusicXMLString()
// Only the 3 inner atoms carry <normal-type>eighth</normal-type>.
#expect(xml.components(separatedBy: "<normal-type>eighth</normal-type>").count - 1 == 3)
// No other <normal-type> (the outer bracket declared none → no bleed).
#expect(xml.components(separatedBy: "<normal-type>").count - 1 == 3)
}
}
@@ -0,0 +1,100 @@
// LyrebirdPathsTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Testing
@testable import LyrebirdSynth
@Suite("LyrebirdPaths")
struct LyrebirdPathsTests {
@Test("projectRoot finds the package directory containing Package.swift")
func projectRootFindsPackage() throws {
// This test file lives under the Lyrebird package, so the default
// Package.swift marker must resolve to a directory that contains it.
let root: URL = try #require(LyrebirdPaths.projectRoot())
let manifest: URL = root.appendingPathComponent("Package.swift")
#expect(FileManager.default.fileExists(atPath: manifest.path))
}
@Test("projectRoot returns nil when the marker is never found")
func projectRootMissingMarkerReturnsNil() {
let result: URL? = LyrebirdPaths.projectRoot(
marker: "definitely-not-a-real-marker-file.xyz"
)
#expect(result == nil)
}
@Test("projectRoot honours a custom marker located in the source path")
func projectRootCustomMarker() throws {
// A temp tree: <tmp>/proj/<MARKER>, with a nested source file.
let marker: String = "MyProject.xcodeproj"
let fm: FileManager = FileManager.default
let proj: URL = fm.temporaryDirectory
.appendingPathComponent("LyrebirdPathsTest-\(UUID().uuidString)")
let nestedDir: URL = proj.appendingPathComponent("Sources/App")
try fm.createDirectory(at: nestedDir, withIntermediateDirectories: true)
defer { try? fm.removeItem(at: proj) }
// Create the marker directory and a fake source file under the nesting.
try fm.createDirectory(
at: proj.appendingPathComponent(marker),
withIntermediateDirectories: true
)
let fakeSource: URL = nestedDir.appendingPathComponent("main.swift")
try Data().write(to: fakeSource)
let found: URL = try #require(
LyrebirdPaths.projectRoot(from: fakeSource.path, marker: marker)
)
// Resolve symlinks: macOS /tmp → /private/tmp.
#expect(found.resolvingSymlinksInPath().path
== proj.resolvingSymlinksInPath().path)
}
@Test("projectRoot matches a dot-prefixed marker by extension")
func projectRootExtensionMarker() throws {
// <tmp>/proj/MyApp.xcodeproj + a nested source file; marker ".xcodeproj"
// must match the differently-named bundle by extension.
let fm: FileManager = FileManager.default
let proj: URL = fm.temporaryDirectory
.appendingPathComponent("LyrebirdPathsExt-\(UUID().uuidString)")
let nestedDir: URL = proj.appendingPathComponent("Sources/App")
try fm.createDirectory(at: nestedDir, withIntermediateDirectories: true)
defer { try? fm.removeItem(at: proj) }
try fm.createDirectory(
at: proj.appendingPathComponent("MyApp.xcodeproj"),
withIntermediateDirectories: true
)
let fakeSource: URL = nestedDir.appendingPathComponent("main.swift")
try Data().write(to: fakeSource)
let found: URL = try #require(
LyrebirdPaths.projectRoot(from: fakeSource.path, marker: ".xcodeproj")
)
#expect(found.resolvingSymlinksInPath().path
== proj.resolvingSymlinksInPath().path)
}
@Test("standard sandbox directories resolve to non-empty paths")
func sandboxDirectoriesResolve() {
#expect(!LyrebirdPaths.documents.path.isEmpty)
#expect(!LyrebirdPaths.applicationSupport.path.isEmpty)
#expect(!LyrebirdPaths.caches.path.isEmpty)
#expect(!LyrebirdPaths.temporary.path.isEmpty)
#expect(!LyrebirdPaths.home.path.isEmpty)
#expect(!LyrebirdPaths.currentWorkingDirectory.path.isEmpty)
}
#if os(macOS)
@Test("desktop resolves on macOS")
func desktopResolves() throws {
let desktop: URL = try #require(LyrebirdPaths.desktop)
#expect(desktop.lastPathComponent == "Desktop")
}
#endif
}
@@ -0,0 +1,88 @@
// _DocTheorySnippetCheckTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@Suite("doc snippet check — docs/stdlib/theory.md examples compile + match")
struct _DocTheorySnippetCheckTests {
@Test func snippetsCompileAndMatch() throws {
// Intervals
#expect(Interval.majorThird.semitones == 4)
#expect(Interval.augmentedSecond.semitones == 3)
#expect(Interval.majorThird.diatonicSteps == 2)
let majorNinth: Interval = try Interval(number: 9, quality: .major)
#expect(majorNinth.semitones == 14)
#expect(try Interval.between(.a, .bSharp) == .augmentedSecond)
let directed: (interval: Interval, direction: IntervalDirection) =
try Interval.directed(from: .named(.c, 4), to: .named(.e, 5))
#expect(directed.direction == .up)
// Transposition
#expect(try NoteName.a.transposed(by: .augmentedSecond) == .bSharp)
#expect(try Pitch.named(.b, 4).transposed(by: .perfectFourth) == .named(.e, 5))
#expect(try Pitch.named(.c, 4).transposed(by: majorNinth) == .named(.d, 5))
// Scales
#expect(try Scale.major(.d).degrees == [.d, .e, .fSharp, .g, .a, .b, .cSharp])
#expect(try Scale.wholeTone(.c).degrees == [.c, .d, .e, .fSharp, .gSharp, .aSharp])
let cMajor: Scale = try Scale.major(.c)
#expect(cMajor.degree(of: .fSharp)?.alteration == 1)
#expect(cMajor.pitch(atDegree: 2, octave: 4) == .named(.e, 4))
// Collections
let cell: PitchCollection = PitchCollection(pitches: [.named(.c, 4), .named(.e, 4), .named(.g, 4)])
#expect(try cell.transposedChromatic(by: .majorThird).pitches
== [.named(.e, 4), .named(.gSharp, 4), .named(.b, 4)])
#expect(try cell.inverted(around: .named(.c, 4)).pitches
== [.named(.c, 4), .named(.aFlat, 3), .named(.f, 3)])
// Diatonic vs chromatic
let line: PitchCollection = PitchCollection(pitches: [.named(.c, 4), .named(.d, 4), .named(.e, 4)])
#expect(try cMajor.transposeDiatonic(line, byDegrees: 2).pitches
== [.named(.e, 4), .named(.f, 4), .named(.g, 4)])
// Mapping
let triad: PitchCollection = PitchCollection(pitches: [.named(.c, 4), .named(.e, 4), .named(.g, 4)])
#expect(try triad.mapped(from: cMajor, to: try Scale.major(.d)).pitches
== [.named(.d, 4), .named(.fSharp, 4), .named(.a, 4)])
#expect(try triad.mapped(from: cMajor, to: try Scale.aeolian(.c)).pitches
== [.named(.c, 4), .named(.eFlat, 4), .named(.g, 4)])
// Pitch -> frequency, duration -> seconds
#expect(Pitch.named(.a, 4).frequency == 440.0)
let cQuarterSharpHz: Double? = Pitch.named(.cQuarterSharp, 4).frequency
let quarterToneTolerance: Double = 0.1
if let hz: Double = cQuarterSharpHz {
#expect(abs(hz - 269.29) < quarterToneTolerance)
} else {
Issue.record("expected a frequency for C quarter-sharp")
}
let bpm: Double = 120.0
let secondsPerBeat: Double = 60.0 / bpm
#expect(NoteDuration.eighth.beats * secondsPerBeat == 0.25)
#expect(NoteDuration.quarter.dotted.beats * secondsPerBeat == 0.75)
let gSharp4: Pitch = try Pitch.named(.e, 4).transposed(by: .majorThird)
#expect(gSharp4 == .named(.gSharp, 4))
#expect(gSharp4.frequency != nil)
// Notation: build a score from theory output, round-trip MusicXML
let up: PitchCollection = try PitchCollection(pitches: [.named(.c, 4), .named(.d, 4), .named(.a, 4)])
.transposedChromatic(by: .majorThird)
let score: Score = Score(bpm: 120) {
Part("theory") {
for pitch: Pitch in up.pitches {
Note(pitch, dur: .quarter)
}
}
}
let xml: String = score.toMusicXMLString()
let decoded: Score = try Score.fromMusicXML(data: Data(xml.utf8))
#expect(decoded.parts.count == 1)
}
}