Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ca1ee503cc | |||
| 1c03e39eac | |||
| f59fd3b55a |
@@ -61,6 +61,7 @@ The `.githooks/pre-commit` hook calls `--check`. Skips silently when `~/.claude/
|
||||
- TemporalStream / language-side value generation → `Sources/Lyrebird/Lyrebird.docc/TemporalDemand.md`
|
||||
- Polyphonic voice pool / step sequencer → `docs/tooling/routine-task.md`
|
||||
- Score / ScorePlayer / SMF / MusicXML → `Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md`
|
||||
- Pitch / scale theory toolkit (spelling-aware `Interval` / `Scale` / `PitchCollection` / 12-tone rows, diatonic-vs-chromatic transposition, scale mapping; → notation + Hz/seconds for synthesis) → `docs/stdlib/theory.md` (types under `Sources/Lyrebird/Score/Theory/`)
|
||||
- Performance event sequencing / `LyrebirdProcess` / `LyrebirdEventList` → `Sources/Lyrebird/Lyrebird.docc/ProcessSystem.md`
|
||||
- NRT / offline render → `docs/tooling/nrt-guide.md`
|
||||
|
||||
@@ -138,7 +139,7 @@ One-liners. Detail and rationale lives in linked docs.
|
||||
|
||||
**Never drop new files at `Sources/Lyrebird/` root.** Every new `.swift` file goes into a subfolder grouped by function. Existing top-level subfolders (alphabetical):
|
||||
|
||||
`AUv3/` `AudioDrivers/` `Buffers/` `Buses/` `Capture/` `Diagnostics/` `Distributions/` `Engine/` `Envelopes/` `External/` `GeneratorCore/` `Generators/` `Kinds/` `MIDI/` `Math/` `NodeTree/` `OSC/` `Oversampling/` `Parameters/` `Patterns/` `Process/` `Scheduling/` `Score/` `Spectral/` `Synthesizer/` `TemporalStream/` `Trigger/` `ValueCompute/` `Voices/`
|
||||
`AUv3/` `AudioDrivers/` `Buffers/` `Buses/` `Capture/` `Diagnostics/` `Distributions/` `Engine/` `Envelopes/` `External/` `GeneratorCore/` `Generators/` `Kinds/` `MIDI/` `Math/` `NodeTree/` `OSC/` `Oversampling/` `Parameters/` `Patterns/` `Process/` `Scheduling/` `Score/` `Spectral/` `Synthesizer/` `TemporalStream/` `Trigger/` `Utilities/` `ValueCompute/` `Voices/`
|
||||
|
||||
Rule:
|
||||
|
||||
@@ -178,6 +179,23 @@ Call-site pattern: every `engine.add` invocation needs `try`. In non-throwing co
|
||||
|
||||
Hard rules. Review agents flag violations.
|
||||
|
||||
### No phase numbers in code or docs
|
||||
Never write phase numbers (`Phase 228`, `Phase 228c`, `phase-224`, `pre-Phase-209c`, `// Phase 216:`, `(Phase 201)`, `— Phase 214`) in source comments, doc-comments (`///`), `.docc` markdown, `@Suite`/`@Test` display strings, or test function / type / file names. Phase numbers are meaningless to external readers — they belong **only** in planning docs (`docs/00-working-order.md`, `docs/01-completed-working-order.md`), commit messages, and `MEMORY.md`/phase history. Describe the **behavior or reason** instead:
|
||||
```swift
|
||||
// WRONG
|
||||
// Phase 216: emit a tempo direction for this measure when a TempoChange targets it.
|
||||
let cap = ... // Phase 228c
|
||||
/// > Note: Phase 224 wires this as model state.
|
||||
@Suite("EngineHost (Phase 197)")
|
||||
|
||||
// RIGHT
|
||||
// Emit a tempo direction for this measure when a TempoChange targets it.
|
||||
let cap = ...
|
||||
/// > Note: this is model state.
|
||||
@Suite("EngineHost")
|
||||
```
|
||||
Exception: the DSP term **"phase"** that is NOT a planning reference — oscillator `phase`, `phase accumulator`, `phase offset`, `_phase`, `initPhase`, `phase modulation`, "Phase 0.25 in an 8-sample table" — is a real audio term, never touch it. The rule targets `Phase <number>` planning tags only.
|
||||
|
||||
### No force unwraps
|
||||
Never `!` on optionals or `try!`. Hotspots: `UnsafeBufferPointer.baseAddress` in Accelerate calls, `Array.first!`/`last!` on output channels, `try!` in test helpers, `dict[key]!`.
|
||||
```swift
|
||||
|
||||
@@ -18,7 +18,7 @@ final class BufferDemos: DemoProtocol {
|
||||
func runDemo() {
|
||||
// BufferDemos.swift lives at .../Demos/LyrebirdDemo/LyrebirdDemo/Demos/BufferDemos.swift
|
||||
// — 4 components up to reach .../Demos/ where Perc.aiff lives.
|
||||
let percURL = URL(fileURLWithPath: #filePath)
|
||||
let percURL: URL = URL(fileURLWithPath: #filePath)
|
||||
.deletingLastPathComponent() // .../Demos/
|
||||
.deletingLastPathComponent() // .../LyrebirdDemo/
|
||||
.deletingLastPathComponent() // .../LyrebirdDemo (package)/
|
||||
@@ -35,13 +35,66 @@ final class BufferDemos: DemoProtocol {
|
||||
exit(1)
|
||||
}
|
||||
|
||||
let sampleRate = engine.sampleRate
|
||||
let sampleRate: Double = engine.sampleRate
|
||||
|
||||
// SynthesizerBase is @MainActor-isolated. LyrebirdTask.run's body is @Sendable and
|
||||
// non-async, so synth inits must happen BEFORE the closure on the main thread.
|
||||
// runDemo() is reached from main.swift on the main thread, so assumeIsolated is valid.
|
||||
|
||||
let pitchSteps: [(Double, String)] = [
|
||||
(0.5, "0.5 — octave down"),
|
||||
(0.75, "0.75 — minor third down"),
|
||||
(1.0, "1.0 — original pitch"),
|
||||
(1.5, "1.5 — perfect fifth up"),
|
||||
(2.0, "2.0 — octave up"),
|
||||
]
|
||||
|
||||
let spectralRatios: [(Double, String)] = [
|
||||
(0.5, "0.5 — octave down (phase vocoder)"),
|
||||
(1.0, "1.0 — no shift (phase vocoder passthrough)"),
|
||||
(1.5, "1.5 — perfect fifth up (phase vocoder)"),
|
||||
(2.0, "2.0 — octave up (phase vocoder)"),
|
||||
]
|
||||
|
||||
let diffuseSteps: [(Double, String)] = [
|
||||
(0.0, "0.0 — bypass (mono passthrough on both channels)"),
|
||||
(0.5, "0.5 — half decorrelation"),
|
||||
(1.0, "1.0 — full per-channel phase randomisation"),
|
||||
]
|
||||
|
||||
let stretchSteps: [(Double, String)] = [
|
||||
(3.0, "3.0 — 3× stretch (one-third speed, pitch preserved)"),
|
||||
(1.5, "1.5 — 1.5× stretch (three-quarter speed, pitch preserved)"),
|
||||
(1.0, "1.0 — native speed (no stretch)"),
|
||||
(0.5, "0.5 — 2× compression (double speed, pitch preserved)"),
|
||||
(0.33, "0.33 — 3× compression (triple speed, pitch preserved)"),
|
||||
]
|
||||
|
||||
// Pre-construct all synthesizers on the main actor before entering the @Sendable closure.
|
||||
let (demo1, demo2, demo3, pitchRatioNode, demo4Array, demo5Array, demo6Array):
|
||||
(PercPlayBuffer, PercBufferRead, PercPitchShift, ParameterNode,
|
||||
[PercSpectralPitchShift], [PercSpectralStereoDiffuse], [PercTimeStretch]) =
|
||||
MainActor.assumeIsolated {
|
||||
let d1: PercPlayBuffer = PercPlayBuffer(buffer: percBuffer, engineSampleRate: sampleRate)
|
||||
let d2: PercBufferRead = PercBufferRead(buffer: percBuffer)
|
||||
let d3: PercPitchShift = PercPitchShift(buffer: percBuffer, engineSampleRate: sampleRate)
|
||||
let prNode: ParameterNode = d3.$pitchRatio
|
||||
|
||||
let d4: [PercSpectralPitchShift] = spectralRatios.map { ratio, _ in
|
||||
PercSpectralPitchShift(buffer: percBuffer, pitchRatio: ratio, engineSampleRate: sampleRate)
|
||||
}
|
||||
let d5: [PercSpectralStereoDiffuse] = diffuseSteps.map { amount, _ in
|
||||
PercSpectralStereoDiffuse(buffer: percBuffer, amount: amount, engineSampleRate: sampleRate)
|
||||
}
|
||||
let d6: [PercTimeStretch] = stretchSteps.map { factor, _ in
|
||||
PercTimeStretch(buffer: percBuffer, stretchFactor: factor)
|
||||
}
|
||||
return (d1, d2, d3, prNode, d4, d5, d6)
|
||||
}
|
||||
|
||||
LyrebirdTask.run(engine: engine) { ctx in
|
||||
// Demo 1 — PlayBuffer (looping at native rate)
|
||||
|
||||
print("\n── Demo 1: PlayBuffer (looping) ──")
|
||||
let demo1 = PercPlayBuffer(buffer: percBuffer, engineSampleRate: sampleRate)
|
||||
ctx.add(demo1)
|
||||
try ctx.wait(seconds: 6)
|
||||
ctx.remove(demo1)
|
||||
@@ -49,7 +102,6 @@ final class BufferDemos: DemoProtocol {
|
||||
|
||||
// Demo 2 — BufferRead (sine-wave position scan)
|
||||
print("\n── Demo 2: BufferRead (sine-wave position scan) ──")
|
||||
let demo2 = PercBufferRead(buffer: percBuffer)
|
||||
ctx.add(demo2)
|
||||
try ctx.wait(seconds: 6)
|
||||
ctx.remove(demo2)
|
||||
@@ -57,19 +109,11 @@ final class BufferDemos: DemoProtocol {
|
||||
|
||||
// Demo 3 — PlayBuffer → PitchShift (cycling through pitch ratios)
|
||||
print("\n── Demo 3: PlayBuffer → PitchShift ──")
|
||||
let demo3 = PercPitchShift(buffer: percBuffer, engineSampleRate: sampleRate)
|
||||
ctx.add(demo3)
|
||||
|
||||
let pitchSteps: [(Double, String)] = [
|
||||
(0.5, "0.5 — octave down"),
|
||||
(0.75, "0.75 — minor third down"),
|
||||
(1.0, "1.0 — original pitch"),
|
||||
(1.5, "1.5 — perfect fifth up"),
|
||||
(2.0, "2.0 — octave up"),
|
||||
]
|
||||
for (ratio, label) in pitchSteps {
|
||||
print(" pitchRatio \(label)")
|
||||
demo3.pitchRatio = ratio
|
||||
// Update via ParameterNode.value — nonisolated atomic setter, RT-safe.
|
||||
pitchRatioNode.value = ratio
|
||||
try ctx.wait(seconds: 3)
|
||||
}
|
||||
ctx.remove(demo3)
|
||||
@@ -77,16 +121,9 @@ final class BufferDemos: DemoProtocol {
|
||||
|
||||
// Demo 4 — PlayBuffer → SpectralChain.Audio (with SpectralPitchShift)
|
||||
print("\n── Demo 4: PlayBuffer → SpectralChain.Audio (SpectralPitchShift) ──")
|
||||
|
||||
let spectralRatios: [(Double, String)] = [
|
||||
(0.5, "0.5 — octave down (phase vocoder)"),
|
||||
(1.0, "1.0 — no shift (phase vocoder passthrough)"),
|
||||
(1.5, "1.5 — perfect fifth up (phase vocoder)"),
|
||||
(2.0, "2.0 — octave up (phase vocoder)"),
|
||||
]
|
||||
for (ratio, label) in spectralRatios {
|
||||
for (index, (_, label)) in spectralRatios.enumerated() {
|
||||
print(" pitchRatio \(label)")
|
||||
let demo4 = PercSpectralPitchShift(buffer: percBuffer, pitchRatio: ratio, engineSampleRate: sampleRate)
|
||||
let demo4: PercSpectralPitchShift = demo4Array[index]
|
||||
ctx.add(demo4)
|
||||
try ctx.wait(seconds: 5)
|
||||
ctx.remove(demo4)
|
||||
@@ -95,16 +132,9 @@ final class BufferDemos: DemoProtocol {
|
||||
|
||||
// Demo 5 — SpectralChain.Audio fan-out (mono → 2-channel decorrelated stereo)
|
||||
print("\n── Demo 5: SpectralChain.Audio fan-out (SpectralStereoDiffuse) ──")
|
||||
|
||||
let diffuseSteps: [(Double, String)] = [
|
||||
(0.0, "0.0 — bypass (mono passthrough on both channels)"),
|
||||
(0.5, "0.5 — half decorrelation"),
|
||||
(1.0, "1.0 — full per-channel phase randomisation"),
|
||||
]
|
||||
for (amount, label) in diffuseSteps {
|
||||
for (index, (_, label)) in diffuseSteps.enumerated() {
|
||||
print(" amount \(label)")
|
||||
let demo5 = PercSpectralStereoDiffuse(
|
||||
buffer: percBuffer, amount: amount, engineSampleRate: sampleRate)
|
||||
let demo5: PercSpectralStereoDiffuse = demo5Array[index]
|
||||
ctx.add(demo5)
|
||||
try ctx.wait(seconds: 5)
|
||||
ctx.remove(demo5)
|
||||
@@ -113,17 +143,9 @@ final class BufferDemos: DemoProtocol {
|
||||
|
||||
// Demo 6 — TimeStretch (granular, pitch-preserved time stretching + compression)
|
||||
print("\n── Demo 6: TimeStretch (granular time-stretch / compression) ──")
|
||||
|
||||
let stretchSteps: [(Double, String)] = [
|
||||
(3.0, "3.0 — 3× stretch (one-third speed, pitch preserved)"),
|
||||
(1.5, "1.5 — 1.5× stretch (three-quarter speed, pitch preserved)"),
|
||||
(1.0, "1.0 — native speed (no stretch)"),
|
||||
(0.5, "0.5 — 2× compression (double speed, pitch preserved)"),
|
||||
(0.33, "0.33 — 3× compression (triple speed, pitch preserved)"),
|
||||
]
|
||||
for (factor, label) in stretchSteps {
|
||||
for (index, (_, label)) in stretchSteps.enumerated() {
|
||||
print(" stretchFactor \(label)")
|
||||
let demo6 = PercTimeStretch(buffer: percBuffer, stretchFactor: factor)
|
||||
let demo6: PercTimeStretch = demo6Array[index]
|
||||
ctx.add(demo6)
|
||||
try ctx.wait(seconds: 6)
|
||||
ctx.remove(demo6)
|
||||
|
||||
@@ -4,14 +4,6 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
//
|
||||
// BufferDemos 2.swift
|
||||
// LyrebirdDemo
|
||||
//
|
||||
// Created by Joshua Parmenter on 5/6/26.
|
||||
//
|
||||
|
||||
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
@@ -25,13 +17,17 @@ final class ReverbDemo: DemoProtocol {
|
||||
|
||||
func runDemo() {
|
||||
|
||||
let sampleRate = engine.sampleRate
|
||||
// sets up its own thread / timing, etc
|
||||
LyrebirdTask.run(engine: engine) { [sampleRate] ctx in
|
||||
let sampleRate: Double = engine.sampleRate
|
||||
|
||||
// SynthesizerBase is @MainActor-isolated. Pre-construct the synth on the main actor
|
||||
// before entering the @Sendable LyrebirdTask closure. runDemo() is reached from
|
||||
// main.swift on the main thread, so assumeIsolated is valid.
|
||||
let reverbDemo: GVerbTest = MainActor.assumeIsolated {
|
||||
GVerbTest(sampleRate: sampleRate)
|
||||
}
|
||||
|
||||
LyrebirdTask.run(engine: engine) { ctx in
|
||||
ctx.tempo = 60.0
|
||||
let reverbDemo = GVerbTest(
|
||||
sampleRate: sampleRate
|
||||
)
|
||||
ctx.add(reverbDemo)
|
||||
try ctx.wait(beats: 6) // could also use seconds
|
||||
ctx.remove(reverbDemo)
|
||||
@@ -39,4 +35,3 @@ final class ReverbDemo: DemoProtocol {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
let binDelayController: BinDelayController
|
||||
var window: LyrebirdWindow?
|
||||
|
||||
@MainActor
|
||||
init(engine: SynthesisEngine) {
|
||||
let scopeCapture = ScopeCapture(buses: [0, 1], bufferSize: 2048)
|
||||
engine.scopeTap = scopeCapture
|
||||
|
||||
@@ -13,6 +13,7 @@ import LyrebirdSynth
|
||||
/// first taps "Start Synthesizer" — this is necessary because
|
||||
/// `SpectralBinDelayUI.init(sampleRate:)` requires the engine's committed
|
||||
/// sample rate, which is only valid after `engine.start()` returns.
|
||||
@MainActor
|
||||
@Observable
|
||||
final class BinDelayController {
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
import Observation
|
||||
import LyrebirdSynth
|
||||
|
||||
@MainActor
|
||||
@Observable
|
||||
final class NoteController {
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
import Observation
|
||||
import LyrebirdSynth
|
||||
|
||||
@MainActor
|
||||
@Observable
|
||||
final class VectorOscillatorController {
|
||||
|
||||
|
||||
@@ -15,8 +15,13 @@ let engine = SynthesisEngine(
|
||||
driver: CoreAudioDriver()
|
||||
)
|
||||
|
||||
let delegate = AppDelegate(engine: engine)
|
||||
let app = NSApplication.shared
|
||||
app.setActivationPolicy(.regular)
|
||||
app.delegate = delegate
|
||||
app.run()
|
||||
// AppDelegate.init is @MainActor (it builds @MainActor SynthesizerBase synths
|
||||
// and UI controllers). Program entry runs on the main thread, so assert main-
|
||||
// actor isolation for the AppKit bootstrap rather than hopping asynchronously.
|
||||
MainActor.assumeIsolated {
|
||||
let delegate: AppDelegate = AppDelegate(engine: engine)
|
||||
let app: NSApplication = NSApplication.shared
|
||||
app.setActivationPolicy(.regular)
|
||||
app.delegate = delegate
|
||||
app.run()
|
||||
}
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"originHash" : "2c98cd4172bcfb3eff9cb6e34a538f80f5e424aa73fbd5bea2b20cf0c8b539b7",
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "linenoise-swift",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/andybest/linenoise-swift",
|
||||
"state" : {
|
||||
"revision" : "afc897c02b030af7333105c4fedcd843a8339238",
|
||||
"version" : "0.0.3"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "nimble",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/Quick/Nimble.git",
|
||||
"state" : {
|
||||
"revision" : "e9d769113660769a4d9dd3afb855562c0b7ae7b0",
|
||||
"version" : "7.3.4"
|
||||
}
|
||||
}
|
||||
],
|
||||
"version" : 3
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
// !$*UTF8*$!
|
||||
{
|
||||
archiveVersion = 1;
|
||||
classes = {
|
||||
};
|
||||
objectVersion = 60;
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
A5D100000000000000000007 /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5D100000000000000000006 /* main.swift */; };
|
||||
A5D100000000000000000013 /* Lyrebird in Frameworks */ = {isa = PBXBuildFile; productRef = A5D100000000000000000012 /* Lyrebird */; };
|
||||
A5D100000000000000000015 /* ScoreVoice.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5D100000000000000000014 /* ScoreVoice.swift */; };
|
||||
A5D100000000000000000019 /* DemoProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5D100000000000000000018 /* DemoProtocol.swift */; };
|
||||
A5D10000000000000000001B /* ScoreDemo.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5D10000000000000000001A /* ScoreDemo.swift */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
A5D100000000000000000004 /* LyrebirdScoreDemo */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = LyrebirdScoreDemo; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
A5D100000000000000000006 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };
|
||||
A5D100000000000000000014 /* ScoreVoice.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScoreVoice.swift; sourceTree = "<group>"; };
|
||||
A5D100000000000000000017 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
A5D100000000000000000020 /* LyrebirdScoreDemo.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = LyrebirdScoreDemo.entitlements; sourceTree = "<group>"; };
|
||||
A5D100000000000000000018 /* DemoProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DemoProtocol.swift; sourceTree = "<group>"; };
|
||||
A5D10000000000000000001A /* ScoreDemo.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScoreDemo.swift; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
A5D100000000000000000009 /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
A5D100000000000000000013 /* Lyrebird in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
A5D100000000000000000002 = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
A5D100000000000000000005 /* LyrebirdScoreDemo */,
|
||||
A5D100000000000000000003 /* Products */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
A5D100000000000000000003 /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
A5D100000000000000000004 /* LyrebirdScoreDemo */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
A5D100000000000000000005 /* LyrebirdScoreDemo */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
A5D100000000000000000006 /* main.swift */,
|
||||
A5D100000000000000000016 /* Synthesizers */,
|
||||
A5D10000000000000000001C /* Demos */,
|
||||
A5D100000000000000000017 /* Info.plist */,
|
||||
A5D100000000000000000020 /* LyrebirdScoreDemo.entitlements */,
|
||||
);
|
||||
path = LyrebirdScoreDemo;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
A5D100000000000000000016 /* Synthesizers */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
A5D100000000000000000014 /* ScoreVoice.swift */,
|
||||
);
|
||||
path = Synthesizers;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
A5D10000000000000000001C /* Demos */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
A5D100000000000000000018 /* DemoProtocol.swift */,
|
||||
A5D10000000000000000001A /* ScoreDemo.swift */,
|
||||
);
|
||||
path = Demos;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
A5D10000000000000000000A /* LyrebirdScoreDemo */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = A5D10000000000000000000B /* Build configuration list for PBXNativeTarget "LyrebirdScoreDemo" */;
|
||||
buildPhases = (
|
||||
A5D100000000000000000008 /* Sources */,
|
||||
A5D100000000000000000009 /* Frameworks */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
);
|
||||
name = LyrebirdScoreDemo;
|
||||
packageProductDependencies = (
|
||||
A5D100000000000000000012 /* Lyrebird */,
|
||||
);
|
||||
productName = LyrebirdScoreDemo;
|
||||
productReference = A5D100000000000000000004 /* LyrebirdScoreDemo */;
|
||||
productType = "com.apple.product-type.tool";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
|
||||
/* Begin PBXProject section */
|
||||
A5D100000000000000000001 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
BuildIndependentTargetsInParallel = 1;
|
||||
LastSwiftUpdateCheck = 1600;
|
||||
LastUpgradeCheck = 1600;
|
||||
TargetAttributes = {
|
||||
A5D10000000000000000000A = {
|
||||
CreatedOnToolsVersion = 16.0;
|
||||
};
|
||||
};
|
||||
};
|
||||
buildConfigurationList = A5D10000000000000000000E /* Build configuration list for PBXProject "LyrebirdScoreDemo" */;
|
||||
compatibilityVersion = "Xcode 14.0";
|
||||
developmentRegion = en;
|
||||
hasScannedForEncodings = 0;
|
||||
knownRegions = (
|
||||
en,
|
||||
Base,
|
||||
);
|
||||
mainGroup = A5D100000000000000000002;
|
||||
packageReferences = (
|
||||
A5D100000000000000000011 /* XCLocalSwiftPackageReference "../.." */,
|
||||
);
|
||||
productRefGroup = A5D100000000000000000003 /* Products */;
|
||||
projectDirPath = "";
|
||||
projectRoot = "";
|
||||
targets = (
|
||||
A5D10000000000000000000A /* LyrebirdScoreDemo */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
A5D100000000000000000008 /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
A5D100000000000000000007 /* main.swift in Sources */,
|
||||
A5D100000000000000000015 /* ScoreVoice.swift in Sources */,
|
||||
A5D100000000000000000019 /* DemoProtocol.swift in Sources */,
|
||||
A5D10000000000000000001B /* ScoreDemo.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin XCBuildConfiguration section */
|
||||
A5D10000000000000000000C /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_ENTITLEMENTS = LyrebirdScoreDemo/LyrebirdScoreDemo.entitlements;
|
||||
CODE_SIGN_IDENTITY = "-";
|
||||
CODE_SIGN_STYLE = Manual;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
ENABLE_HARDENED_RUNTIME = YES;
|
||||
INFOPLIST_FILE = LyrebirdScoreDemo/Info.plist;
|
||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScoreDemo;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_VERSION = 6.0;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
A5D10000000000000000000D /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_ENTITLEMENTS = LyrebirdScoreDemo/LyrebirdScoreDemo.entitlements;
|
||||
CODE_SIGN_IDENTITY = "-";
|
||||
CODE_SIGN_STYLE = Manual;
|
||||
ENABLE_HARDENED_RUNTIME = YES;
|
||||
INFOPLIST_FILE = LyrebirdScoreDemo/Info.plist;
|
||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScoreDemo;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_VERSION = 6.0;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
A5D10000000000000000000F /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
CLANG_ANALYZER_NONNULL = YES;
|
||||
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
|
||||
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_ARC = YES;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
||||
CLANG_WARN_BOOL_CONVERSION = YES;
|
||||
CLANG_WARN_COMMA = YES;
|
||||
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
||||
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
|
||||
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
||||
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
|
||||
CLANG_WARN_EMPTY_BODY = YES;
|
||||
CLANG_WARN_ENUM_CONVERSION = YES;
|
||||
CLANG_WARN_INFINITE_RECURSION = YES;
|
||||
CLANG_WARN_INT_CONVERSION = YES;
|
||||
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
|
||||
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
||||
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
|
||||
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
||||
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
||||
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
||||
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
ENABLE_TESTABILITY = YES;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu17;
|
||||
GCC_DYNAMIC_NO_PIC = NO;
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
GCC_OPTIMIZATION_LEVEL = 0;
|
||||
GCC_PREPROCESSOR_DEFINITIONS = (
|
||||
"DEBUG=1",
|
||||
"$(inherited)",
|
||||
);
|
||||
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
|
||||
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
|
||||
GCC_WARN_UNDECLARED_SELECTOR = YES;
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
|
||||
MTL_FAST_MATH = YES;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SDKROOT = macosx;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
A5D100000000000000000010 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
CLANG_ANALYZER_NONNULL = YES;
|
||||
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
|
||||
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_ARC = YES;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
||||
CLANG_WARN_BOOL_CONVERSION = YES;
|
||||
CLANG_WARN_COMMA = YES;
|
||||
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
||||
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
|
||||
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
||||
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
|
||||
CLANG_WARN_EMPTY_BODY = YES;
|
||||
CLANG_WARN_ENUM_CONVERSION = YES;
|
||||
CLANG_WARN_INFINITE_RECURSION = YES;
|
||||
CLANG_WARN_INT_CONVERSION = YES;
|
||||
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
|
||||
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
||||
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
|
||||
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
||||
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
||||
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
||||
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
ENABLE_NS_ASSERTIONS = NO;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu17;
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
|
||||
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
|
||||
GCC_WARN_UNDECLARED_SELECTOR = YES;
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
MTL_ENABLE_DEBUG_INFO = NO;
|
||||
MTL_FAST_MATH = YES;
|
||||
SDKROOT = macosx;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
A5D10000000000000000000B /* Build configuration list for PBXNativeTarget "LyrebirdScoreDemo" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
A5D10000000000000000000C /* Debug */,
|
||||
A5D10000000000000000000D /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
A5D10000000000000000000E /* Build configuration list for PBXProject "LyrebirdScoreDemo" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
A5D10000000000000000000F /* Debug */,
|
||||
A5D100000000000000000010 /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
/* End XCConfigurationList section */
|
||||
|
||||
/* Begin XCLocalSwiftPackageReference section */
|
||||
A5D100000000000000000011 /* XCLocalSwiftPackageReference "../.." */ = {
|
||||
isa = XCLocalSwiftPackageReference;
|
||||
relativePath = ../..;
|
||||
};
|
||||
/* End XCLocalSwiftPackageReference section */
|
||||
|
||||
/* Begin XCSwiftPackageProductDependency section */
|
||||
A5D100000000000000000012 /* Lyrebird */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
package = A5D100000000000000000011 /* XCLocalSwiftPackageReference "../.." */;
|
||||
productName = Lyrebird;
|
||||
};
|
||||
/* End XCSwiftPackageProductDependency section */
|
||||
};
|
||||
rootObject = A5D100000000000000000001 /* Project object */;
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"originHash" : "2c98cd4172bcfb3eff9cb6e34a538f80f5e424aa73fbd5bea2b20cf0c8b539b7",
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "linenoise-swift",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/andybest/linenoise-swift",
|
||||
"state" : {
|
||||
"revision" : "afc897c02b030af7333105c4fedcd843a8339238",
|
||||
"version" : "0.0.3"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "nimble",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/Quick/Nimble.git",
|
||||
"state" : {
|
||||
"revision" : "e9d769113660769a4d9dd3afb855562c0b7ae7b0",
|
||||
"version" : "7.3.4"
|
||||
}
|
||||
}
|
||||
],
|
||||
"version" : 3
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "2620"
|
||||
version = "1.7">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES"
|
||||
buildArchitectures = "Automatic">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "A5D10000000000000000000A"
|
||||
BuildableName = "LyrebirdScoreDemo"
|
||||
BlueprintName = "LyrebirdScoreDemo"
|
||||
ReferencedContainer = "container:LyrebirdScoreDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
shouldAutocreateTestPlan = "YES">
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Release"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "A5D10000000000000000000A"
|
||||
BuildableName = "LyrebirdScoreDemo"
|
||||
BlueprintName = "LyrebirdScoreDemo"
|
||||
ReferencedContainer = "container:LyrebirdScoreDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "A5D10000000000000000000A"
|
||||
BuildableName = "LyrebirdScoreDemo"
|
||||
BlueprintName = "LyrebirdScoreDemo"
|
||||
ReferencedContainer = "container:LyrebirdScoreDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -0,0 +1,11 @@
|
||||
// DemoProtocol.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
|
||||
protocol DemoProtocol {
|
||||
func runDemo()
|
||||
}
|
||||
@@ -0,0 +1,693 @@
|
||||
// ScoreDemo.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Builds a multi-part Score using every DSL node type, exports MusicXML, round-trips
|
||||
/// the document, and reports render statistics.
|
||||
///
|
||||
/// Call ``buildAndReport()`` after construction to export MusicXML and print the
|
||||
/// round-trip summary. ``scheduleVoices(engine:)`` is marked ``@MainActor`` because
|
||||
/// ``ScoreVoice`` (a ``SynthesizerBase`` subclass) is ``@MainActor``-isolated; call it
|
||||
/// on the main thread before ``engine.start()``.
|
||||
final class ScoreDemo: DemoProtocol {
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Beats per minute for the demo score.
|
||||
static let bpm: Double = 108.0
|
||||
|
||||
/// Seconds per beat at the demo tempo.
|
||||
static let secondsPerBeat: Double = 60.0 / ScoreDemo.bpm
|
||||
|
||||
/// Extra render tail (seconds) to let the final release decay.
|
||||
static let tailSeconds: Double = 1.2
|
||||
|
||||
/// Pan position for lead-part voices (MIDI channel 0): slightly left.
|
||||
static let leadPan: Double = -0.4
|
||||
|
||||
/// Pan position for bass-part voices (other channels): slightly right.
|
||||
static let bassPan: Double = 0.5
|
||||
|
||||
/// Scale applied to a `ScoreEvent`'s normalized velocity to set voice amplitude.
|
||||
static let velocityToAmpScale: Double = 0.35
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
/// The score built at init time.
|
||||
let score: Score
|
||||
|
||||
/// Total render duration in seconds, including tail.
|
||||
let totalDuration: Double
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
init() {
|
||||
let builtScore: Score = ScoreDemo.makeScore()
|
||||
self.score = builtScore
|
||||
self.totalDuration = builtScore.totalBeats * ScoreDemo.secondsPerBeat
|
||||
+ ScoreDemo.tailSeconds
|
||||
}
|
||||
|
||||
// MARK: - DemoProtocol
|
||||
|
||||
/// Export MusicXML and print the round-trip event count. Does not interact with
|
||||
/// the engine or schedule any voices.
|
||||
func runDemo() {
|
||||
// Step 1 — write MusicXML to Desktop.
|
||||
let xmlURL: URL = FileManager.default.homeDirectoryForCurrentUser
|
||||
.appendingPathComponent("Desktop/LyrebirdScoreDemo.musicxml")
|
||||
let xmlString: String = score.toMusicXMLString()
|
||||
do {
|
||||
try xmlString.write(to: xmlURL, atomically: true, encoding: .utf8)
|
||||
print("MusicXML written → \(xmlURL.path)")
|
||||
} catch {
|
||||
fputs("Failed to write MusicXML: \(error)\n", stderr)
|
||||
}
|
||||
|
||||
// Step 2 — round-trip sanity check.
|
||||
let xmlData: Data = score.toMusicXMLData()
|
||||
do {
|
||||
let rt: Score = try Score.fromMusicXML(data: xmlData)
|
||||
let originalCount: Int = score.allEvents.count
|
||||
let roundTripCount: Int = rt.allEvents.count
|
||||
print("Round-trip events: \(originalCount) → \(roundTripCount)")
|
||||
// Verify notation-only elements do not affect event count. Grace
|
||||
// notes (lead), clef changes (bass), staff grouping + sustain-pedal
|
||||
// marks (piano) are all skipped by flatten(), so the score's event
|
||||
// count must equal the round-tripped count.
|
||||
let selfConsistent: String = (originalCount == roundTripCount) ? "self-consistent" : "MISMATCH"
|
||||
print("Notation-only event count: \(selfConsistent)")
|
||||
// Verify tempo changes round-trip.
|
||||
let originalChanges: Int = score.tempoChanges.count
|
||||
let rtChanges: Int = rt.tempoChanges.count
|
||||
print("Round-trip tempo changes: \(originalChanges) → \(rtChanges)")
|
||||
if originalChanges == rtChanges {
|
||||
for (orig, recovered): (TempoChange, TempoChange) in zip(score.tempoChanges, rt.tempoChanges) {
|
||||
let measMatch: String = orig.measure == recovered.measure ? "OK" : "MISMATCH"
|
||||
let bpmMatch: String = abs(orig.bpm - recovered.bpm) < 0.001 ? "OK" : "MISMATCH"
|
||||
print(" TempoChange measure=\(orig.measure) \(measMatch) bpm=\(orig.bpm) \(bpmMatch)")
|
||||
}
|
||||
}
|
||||
// Verify per-part key override + transpose round-trip on the clarinet part.
|
||||
// Part order: 0=lead, 1=bass, 2=clarinet, 3=piano, 4=texture,
|
||||
// 5=timeline, 6=autovoice, 7=polymeter — so the clarinet is index 2.
|
||||
if rt.parts.count > 2 {
|
||||
let clarinet: ScorePart = rt.parts[2]
|
||||
let keyOK: String = (clarinet.keySignature == .aMajor) ? "OK" : "MISMATCH(\(String(describing: clarinet.keySignature)))"
|
||||
let transposeOK: String = (clarinet.transpose == .bFlat) ? "OK" : "MISMATCH(\(String(describing: clarinet.transpose)))"
|
||||
print("Clarinet part key override: \(keyOK)")
|
||||
print("Clarinet part transpose (bFlat): \(transposeOK)")
|
||||
print("Score key (G major): \(rt.keySignature == .gMajor ? "OK" : "MISMATCH(\(rt.keySignature))")")
|
||||
}
|
||||
} catch {
|
||||
fputs("MusicXML round-trip failed: \(error)\n", stderr)
|
||||
}
|
||||
|
||||
// Step 2b — sectioned showcase: multiple Sections assembled into one
|
||||
// score (continuous measure numbers + per-section rehearsal marks),
|
||||
// glissandi, slurs/hairpins, per-note display overrides, tacet fill,
|
||||
// and a landscape page layout. Section labels export as standard
|
||||
// <rehearsal> marks — system objects placed once above the top staff (tied
|
||||
// to the section, not an instrument line, and collision-free). Some editors
|
||||
// (e.g. Dorico) auto-sequence imported rehearsal marks as A, B, C and hide
|
||||
// the authored text; that is an editor display setting. The
|
||||
// `rehearsalMarksAsStaffText: true` option emits boxed <words> staff text
|
||||
// instead, but that attaches to a staff and can collide with notation.
|
||||
let showcase: Score = ScoreDemo.makeSectionedShowcase()
|
||||
let showcaseURL: URL = FileManager.default.homeDirectoryForCurrentUser
|
||||
.appendingPathComponent("Desktop/LyrebirdScoreSections.musicxml")
|
||||
do {
|
||||
try showcase.toMusicXMLString().write(to: showcaseURL, atomically: true, encoding: .utf8)
|
||||
print("Sectioned showcase written → \(showcaseURL.path)")
|
||||
// Report the assembled measure span + rehearsal marks.
|
||||
let marks: [(measure: Int, label: String)] = showcase.rehearsalMarks
|
||||
.sorted { $0.key < $1.key }
|
||||
.map { (measure: $0.key, label: $0.value) }
|
||||
let markList: String = marks.map { "\($0.label)@m\($0.measure)" }.joined(separator: ", ")
|
||||
print("Sections → rehearsal marks: \(markList)")
|
||||
print("Sectioned showcase parts: \(showcase.parts.map { $0.name }.joined(separator: ", "))")
|
||||
} catch {
|
||||
fputs("Failed to write sectioned showcase: \(error)\n", stderr)
|
||||
}
|
||||
|
||||
// Step 3 — report render parameters.
|
||||
let displayBeats: Double = score.totalBeats
|
||||
let displayDur: Double = totalDuration
|
||||
print(
|
||||
String(
|
||||
format: "Score: %.1f beats at %.0f BPM → %.2f s render (+ %.2f s tail)",
|
||||
displayBeats,
|
||||
ScoreDemo.bpm,
|
||||
displayBeats * ScoreDemo.secondsPerBeat,
|
||||
ScoreDemo.tailSeconds
|
||||
)
|
||||
)
|
||||
print(String(format: "Total render: %.2f s", displayDur))
|
||||
}
|
||||
|
||||
// MARK: - Voice scheduling
|
||||
|
||||
/// Schedule one ``ScoreVoice`` per non-rest event against the engine.
|
||||
///
|
||||
/// Must be called on the main actor because ``ScoreVoice`` (a ``SynthesizerBase``
|
||||
/// subclass) is ``@MainActor``-isolated. Call this after constructing the engine
|
||||
/// but before ``engine.start()``.
|
||||
@MainActor
|
||||
func scheduleVoices(engine: SynthesisEngine) {
|
||||
let secondsPerBeat: Double = ScoreDemo.secondsPerBeat
|
||||
let allEvents: [ScoreEvent] = score.allEvents
|
||||
var scheduledCount: Int = 0
|
||||
var failedCount: Int = 0
|
||||
|
||||
for event: ScoreEvent in allEvents {
|
||||
guard !event.isRest else { continue }
|
||||
guard let freqHz: Double = event.pitch.frequency else { continue }
|
||||
|
||||
let startSeconds: Double = event.beat * secondsPerBeat
|
||||
let durSeconds: Double = event.performedDuration * secondsPerBeat
|
||||
|
||||
// Separate lead (slight left) from bass (slight right) by MIDI channel.
|
||||
let pan: Double = event.channel == 0 ? ScoreDemo.leadPan : ScoreDemo.bassPan
|
||||
|
||||
let voice: ScoreVoice = ScoreVoice(
|
||||
freqHz: freqHz,
|
||||
amp: event.velocity * ScoreDemo.velocityToAmpScale,
|
||||
durSeconds: durSeconds,
|
||||
pan: pan
|
||||
)
|
||||
|
||||
do {
|
||||
try engine.schedule(voice, after: startSeconds)
|
||||
scheduledCount += 1
|
||||
} catch {
|
||||
fputs("engine.schedule failed for beat \(event.beat): \(error)\n", stderr)
|
||||
failedCount += 1
|
||||
}
|
||||
}
|
||||
|
||||
print("Scheduled \(scheduledCount) voices\(failedCount > 0 ? ", \(failedCount) failed" : "").")
|
||||
}
|
||||
|
||||
// MARK: - Material-creation helpers
|
||||
//
|
||||
// Beyond hand-authoring notes, Lyrebird offers several ways to GENERATE score
|
||||
// material. These helpers feed the `timeline` and `autovoice` parts.
|
||||
// `ScoreTimeline` is throwing, so the `[ScoreElement]` is built here (outside
|
||||
// the non-throwing score result-builder) and dropped into a `Part { … }` body.
|
||||
|
||||
/// Place notes at explicit musical beats and let the timeline fill the rests.
|
||||
/// `BeatPosition.beat(_:)` is the felt-beat reading (4/4: beat 1 = downbeat,
|
||||
/// beat 5 = bar-2 downbeat). See ``ScoreTimeline`` / ``BeatPosition``.
|
||||
private static func makeTimelineMaterial() -> [ScoreElement] {
|
||||
do {
|
||||
return try ScoreTimeline.from(
|
||||
(.beat(1.0), Note(.named(.d, 5), dur: .quarter, dyn: .mp)),
|
||||
(.beat(5.0), Note(.named(.f, 5), dur: .quarter, dyn: .mp)),
|
||||
(.bar(2, beat: 3.0), Note(.named(.a, 5), dur: .half, dyn: .mf, art: .tenuto)),
|
||||
meter: MeterMap(.fourFour)
|
||||
)
|
||||
} catch {
|
||||
print("[ScoreDemo] timeline material failed: \(error)")
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/// Overlapping placements distributed across voices automatically — a held
|
||||
/// whole note under a moving line becomes two voices. See
|
||||
/// ``ScoreTimeline/fillAutoVoiced(_:)``.
|
||||
private static func makeAutoVoicedMaterial() -> [ScoreElement] {
|
||||
do {
|
||||
return try ScoreTimeline.fillAutoVoiced([
|
||||
(beat: 0.0, element: Note(.named(.c, 4), dur: .whole, dyn: .p)),
|
||||
(beat: 0.0, element: Note(.named(.e, 5), dur: .quarter, dyn: .mp)),
|
||||
(beat: 1.0, element: Note(.named(.f, 5), dur: .quarter, dyn: .mp)),
|
||||
(beat: 2.0, element: Note(.named(.g, 5), dur: .quarter, dyn: .mp)),
|
||||
(beat: 3.0, element: Note(.named(.e, 5), dur: .quarter, dyn: .mp)),
|
||||
])
|
||||
} catch {
|
||||
print("[ScoreDemo] auto-voiced material failed: \(error)")
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Score construction
|
||||
|
||||
/// Builds the demo score: eight parts, each chosen to exercise a different
|
||||
/// authoring path.
|
||||
///
|
||||
/// The hand-authored `lead` part is written **inline** below to show direct
|
||||
/// result-builder entry; every other part is built by its own `make…Part()`
|
||||
/// helper for clearer encapsulation. The parts, in document order:
|
||||
///
|
||||
/// - **`lead`** *(inline)* — 8-bar melody: crescendo/diminuendo hairpins, a
|
||||
/// triplet run, tied sixteenths, chords, a grace note (acciaccatura F♯5),
|
||||
/// and a nested 5:4 ⊃ 3:2 tuplet.
|
||||
/// - **`bass`** — sustained low line with double-stops, a mid-voice clef
|
||||
/// change (bass → tenor → bass), a walking eighth-note run, and a triplet
|
||||
/// fill. Hand-authored.
|
||||
/// - **`clarinet`** — transposing-instrument demo (B♭): per-part key
|
||||
/// override (A major) + `<transpose>`. Hand-authored.
|
||||
/// - **`piano`** — grand staff. Staff 1 (treble) carries two voices (an
|
||||
/// upper melody and a tied C-major triad); staff 2 (bass) carries a
|
||||
/// sustained whole-note C under a sustain-pedal marking.
|
||||
/// - **`texture`** — algorithmic generation via `Generate` (index-driven)
|
||||
/// and `PatternNotes` (a seeded Brownian MIDI walk).
|
||||
/// - **`timeline`** — notes placed at explicit `BeatPosition`s with rests
|
||||
/// auto-filled (`ScoreTimeline`).
|
||||
/// - **`autovoice`** — overlapping placements distributed across voices
|
||||
/// automatically (`ScoreTimeline.fillAutoVoiced`).
|
||||
/// - **`polymeter`** — runs in its OWN 3/4 meter while the score is 4/4
|
||||
/// (per-part `MeterMap`).
|
||||
///
|
||||
/// Score-level features layered over all parts: a forward/backward repeat
|
||||
/// with 1st/2nd endings (bars 1–4) and tempo changes at bar 3 (132 BPM) and
|
||||
/// bar 7 (80 BPM). Both are notation-only — playback uses the base tempo.
|
||||
private static func makeScore() -> Score {
|
||||
return Score(
|
||||
bpm: ScoreDemo.bpm,
|
||||
timeSignature: TimeSignature(4, 4),
|
||||
keySignature: .gMajor,
|
||||
// Repeat of bars 1–3 with first/second endings. The backward repeat
|
||||
// sits at the END of the first ending (bar 3) — the jump-back point.
|
||||
// On the repeat, the first ending (bar 3) is skipped and the second
|
||||
// ending (bar 4) plays straight through, so bar 4 has no repeat.
|
||||
repeats: RepeatStructure(
|
||||
forwardRepeatMeasures: [1],
|
||||
backwardRepeatMeasures: [3],
|
||||
endings: [
|
||||
Ending(number: 1, startMeasure: 3, stopMeasure: 3),
|
||||
Ending(number: 2, startMeasure: 4, stopMeasure: 4)
|
||||
]
|
||||
),
|
||||
// Tempo changes. Bar 3 accelerates to 132 BPM; bar 7 relaxes to 80
|
||||
// BPM. These are notation-only — playback still uses the base bpm
|
||||
// (108). A tempo change is emitted in every part that reaches that
|
||||
// measure: bar 3 exists in all parts (incl. the 4-bar piano), bar 7
|
||||
// only in the 8-bar lead/bass.
|
||||
tempoChanges: [
|
||||
TempoChange(measure: 3, bpm: 132.0),
|
||||
TempoChange(measure: 7, bpm: 80.0)
|
||||
],
|
||||
// Page layout — emitted as a MusicXML <defaults> block (US Letter,
|
||||
// portrait). Engravers honour the page size, orientation, margins,
|
||||
// and staff scaling on import.
|
||||
pageLayout: PageLayout(size: .letter, orientation: .portrait)
|
||||
) {
|
||||
// Lead melody — kept INLINE to demonstrate direct result-builder
|
||||
// entry. Every other part is built by a make…Part() helper below.
|
||||
// 8 bars covering dynamics, articulations, a grace note, and a
|
||||
// nested tuplet. Bars 1–2 include a Crescendo and Diminuendo hairpin.
|
||||
Part("lead") {
|
||||
// Bar 1 — arpeggiated C major with staccato, under a crescendo.
|
||||
// The high C6 also starts a slur that overlaps into bar 2 —
|
||||
// demonstrating a shared boundary where a slur-start and a
|
||||
// hairpin coexist on the same note via the spanners: parameter.
|
||||
Slur {
|
||||
Crescendo {
|
||||
Note(.named(.c, 5), dur: .quarter, dyn: .mf, art: .staccato)
|
||||
Note(.named(.e, 5), dur: .quarter, dyn: .mf, art: .staccato)
|
||||
Note(.named(.g, 5), dur: .quarter, dyn: .mf, art: .staccato)
|
||||
// spanners: [.beginSlur] opens a slur here while the Crescendo
|
||||
// block simultaneously marks this note with the wedge-start.
|
||||
// The two annotations are independent fields on the atom and
|
||||
// compose without conflict in MusicXML.
|
||||
Note(.named(.c, 6), dur: .quarter, dyn: .f, art: .accent)
|
||||
}
|
||||
}
|
||||
|
||||
// Bar 2 — triplet run followed by legato half note, under a diminuendo.
|
||||
// The slur started on the C6 above ends on the last triplet note (G5),
|
||||
// which lies inside the Diminuendo block — the slur overlaps the hairpin.
|
||||
Diminuendo {
|
||||
Tuplet(3, inTimeOf: 2) {
|
||||
Note(.named(.b, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.a, 5), dur: .quarter, dyn: .mp, spanners: [.beginSlur])
|
||||
// spanners: [.endSlur] closes the slur here. The Diminuendo
|
||||
// block's wedge-start is on the B5 triplet note; the slur-stop
|
||||
// lands on this G5 — overlapping spans, cleanly expressed.
|
||||
Note(.named(.g, 5), dur: .quarter, dyn: .mp,
|
||||
spanners: [.endSlur])
|
||||
}
|
||||
Note(.named(.f, 5), dur: .half, dyn: .p, art: .legato)
|
||||
}
|
||||
// Bar 3 — staccatissimo sixteenth notes, then tenuto half; the
|
||||
// first two sixteenths are tied (authored tie: sounds
|
||||
// as one eighth note but is notated as two tied sixteenths).
|
||||
Note(.named(.e, 5), dur: .sixteenth, dyn: .ff, art: .staccatissimo, tie: true)
|
||||
Note(.named(.e, 5), dur: .sixteenth, dyn: .ff)
|
||||
Note(.named(.g, 5), dur: .sixteenth, dyn: .ff, art: .staccatissimo)
|
||||
Note(.named(.a, 5), dur: .sixteenth, dyn: .ff, art: .staccatissimo)
|
||||
Note(.named(.b, 5), dur: .half, dyn: .f, art: .tenuto)
|
||||
Rest(dur: .quarter)
|
||||
|
||||
// Bar 4 — chord, rest, single note
|
||||
Chord([.named(.c, 5), .named(.e, 5), .named(.g, 5)], dur: .half, dyn: .f, art: .accent)
|
||||
Rest(dur: .quarter)
|
||||
// Note-display override: a diamond notehead (e.g. a harmonic).
|
||||
// Notation-only — the flattened event is unchanged.
|
||||
Note(.named(.d, 5), dur: .quarter, dyn: .mf,
|
||||
display: NoteDisplay(notehead: .diamond))
|
||||
// Bar 5 — grace note (acciaccatura F#5) before a nested tuplet.
|
||||
// Grace is notation-only; flatten() skips it and the
|
||||
// event count is identical to a score without the grace note.
|
||||
// The nested 5:4 ⊃ 3:2 tuplet demonstrates per-level
|
||||
// <tuplet-actual>/<tuplet-normal> bracket engraving.
|
||||
// Outer children: 3 quarters + inner(3 quarters × 2/3 = 2 quarter-slots)
|
||||
// = 5 quarter-slots × 4/5 outer scale = 4 beats. Fits the 4/4 bar.
|
||||
Grace(.named(.fSharp, 5))
|
||||
Tuplet(5, inTimeOf: 4) {
|
||||
Note(.named(.c, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.d, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.e, 5), dur: .quarter, dyn: .mp)
|
||||
Tuplet(3, inTimeOf: 2) {
|
||||
Note(.named(.f, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.g, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.gSharp, 5), dur: .quarter, dyn: .mp)
|
||||
}
|
||||
}
|
||||
|
||||
// Bar 6 — dotted quarter glissando down to the eighth, then a
|
||||
// legato half. The glissando is a two-note span authored via the
|
||||
// spanners: parameter (begin on A5, end on G5).
|
||||
Note(.named(.a, 5), dur: .quarter.dotted, dyn: .mf,
|
||||
spanners: [.beginGlissando(Glissando())])
|
||||
Note(.named(.g, 5), dur: .eighth, dyn: .mp, spanners: [.endGlissando])
|
||||
Note(.named(.fSharp, 5), dur: .half, dyn: .p, art: .legato)
|
||||
|
||||
// Bar 7 — marcato descent ppp
|
||||
Note(.named(.e, 5), dur: .quarter, dyn: .fff, art: .marcato)
|
||||
Note(.named(.d, 5), dur: .quarter, dyn: .ff)
|
||||
Note(.named(.c, 5), dur: .quarter, dyn: .f)
|
||||
Note(.named(.b, 4), dur: .quarter, dyn: .mf)
|
||||
|
||||
// Bar 8 — closing chord
|
||||
Chord([.named(.c, 5), .named(.e, 5), .named(.g, 5), .named(.c, 6)], dur: .whole, dyn: .pp, art: .tenuto)
|
||||
}
|
||||
|
||||
ScoreDemo.makeBassPart()
|
||||
ScoreDemo.makeClarinetPart()
|
||||
ScoreDemo.makePianoPart()
|
||||
ScoreDemo.makeTexturePart()
|
||||
ScoreDemo.makeTimelinePart()
|
||||
ScoreDemo.makeAutoVoicePart()
|
||||
ScoreDemo.makePolymeterPart()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Sectioned showcase
|
||||
|
||||
/// A second, self-contained score that demonstrates the section-based
|
||||
/// authoring stack: multiple ``ScoreSection`` blocks assembled into one
|
||||
/// score with continuous global measure numbers, per-section rehearsal
|
||||
/// marks, a tacet instrument auto-filled with rests, glissandi/slides,
|
||||
/// slurs and hairpins, an intra-note dynamic curve (messa di voce / niente
|
||||
/// swell), per-note display overrides, and a landscape page layout.
|
||||
///
|
||||
/// Two instruments — `flute` (id `fl`) and `cello` (id `vc`) — are matched
|
||||
/// across sections by `id`. Section labels are single letters (`A`, `B`, `C`):
|
||||
/// rehearsal marks are system objects that editors typically render as a
|
||||
/// sequence of letters, so single letters round-trip reliably while custom
|
||||
/// words may be re-sequenced or hidden. Three sections run sequentially:
|
||||
/// - **A** (4/4, 2 bars): flute states the theme under a slurred crescendo,
|
||||
/// then a niente messa-di-voce swell (`dynamicCurve`) over the bar-2 whole
|
||||
/// note; cello is TACET (auto-filled, stays bar-aligned).
|
||||
/// - **B** (3/4, 2 bars): flute plays a wavy glissando and an x-notehead /
|
||||
/// stemless note; cello enters with a straight `slide` glissando.
|
||||
/// - **C** (4/4, 2 bars): a diminuendo close, a large-notehead final note,
|
||||
/// sustained cello.
|
||||
private static func makeSectionedShowcase() -> Score {
|
||||
return Score(
|
||||
bpm: 96.0,
|
||||
keySignature: .cMajor,
|
||||
// Landscape A4 — emitted as a MusicXML <defaults> block.
|
||||
pageLayout: PageLayout(size: .a4, orientation: .landscape)
|
||||
) {
|
||||
Section("A") {
|
||||
Part("flute", clef: .treble, id: "fl") {
|
||||
Crescendo {
|
||||
Slur {
|
||||
Note(.named(.c, 5), dur: .quarter, dyn: .p)
|
||||
Note(.named(.d, 5), dur: .quarter)
|
||||
Note(.named(.e, 5), dur: .quarter)
|
||||
Note(.named(.g, 5), dur: .quarter, dyn: .mf)
|
||||
}
|
||||
}
|
||||
// Messa di voce on a single sustained note: a niente swell
|
||||
// ◦< f >◦ authored via `dynamicCurve`. The dynamics and the
|
||||
// crescendo/diminuendo hairpins (each closing on a niente
|
||||
// circle) ride inside this one whole note — no tied split. The
|
||||
// note's `dyn:` still drives playback velocity.
|
||||
Note(.named(.c, 5), dur: .whole, dyn: .mf,
|
||||
dynamicCurve: [(0.0, .niente), (0.5, .f), (1.0, .niente)])
|
||||
}
|
||||
// cello is tacet in section A — the lowering fills it with rests.
|
||||
}
|
||||
|
||||
Section("B", meterMap: MeterMap(.threeFour)) {
|
||||
Part("flute", clef: .treble, id: "fl") {
|
||||
// Wavy glissando E5 → B5 (two-note span via spanners:).
|
||||
Note(.named(.e, 5), dur: .quarter, dyn: .mf,
|
||||
spanners: [.beginGlissando(Glissando())])
|
||||
Note(.named(.b, 5), dur: .quarter, spanners: [.endGlissando])
|
||||
// x-notehead (ghost / percussive) — notation-only.
|
||||
Note(.named(.a, 5), dur: .quarter, display: NoteDisplay(notehead: .x))
|
||||
// Bar 2: legato half + a stemless note.
|
||||
Note(.named(.g, 5), dur: .half, dyn: .p, art: .legato)
|
||||
Note(.named(.fSharp, 5), dur: .quarter,
|
||||
display: NoteDisplay(hideStem: true))
|
||||
}
|
||||
Part("cello", clef: .bass, id: "vc") {
|
||||
// Straight slide glissando C3 → G3, dashed line.
|
||||
Note(.named(.c, 3), dur: .half.dotted, dyn: .mp,
|
||||
spanners: [.beginGlissando(Glissando(kind: .slide, lineType: .dashed))])
|
||||
Note(.named(.g, 3), dur: .half.dotted, spanners: [.endGlissando])
|
||||
}
|
||||
}
|
||||
|
||||
Section("C") {
|
||||
Part("flute", clef: .treble, id: "fl") {
|
||||
Diminuendo {
|
||||
Note(.named(.g, 5), dur: .quarter, dyn: .f)
|
||||
Note(.named(.e, 5), dur: .quarter)
|
||||
Note(.named(.c, 5), dur: .half, dyn: .pp, art: .legato)
|
||||
}
|
||||
// Final note with a large notehead (single pitch, not a chord).
|
||||
Note(.named(.c, 6), dur: .whole, dyn: .pp, art: .tenuto,
|
||||
display: NoteDisplay(size: .large))
|
||||
}
|
||||
Part("cello", clef: .bass, id: "vc") {
|
||||
Note(.named(.c, 3), dur: .whole, dyn: .mp)
|
||||
Note(.named(.c, 3), dur: .whole, dyn: .pp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Part-creation helpers
|
||||
|
||||
/// Bass line — sustained low harmonies with occasional double-stops, a
|
||||
/// mid-voice clef change (bass → tenor → bass), a walking eighth-note run,
|
||||
/// and a triplet fill. Single voice; carries Crescendo/Diminuendo-free
|
||||
/// material at the low end of the texture.
|
||||
private static func makeBassPart() -> ScorePart {
|
||||
Part("bass", channel: 1, clef: .bass) {
|
||||
// Bar 1 — low C whole note
|
||||
Note(.named(.c, 2), dur: .whole, dyn: .mp)
|
||||
|
||||
// Bar 2 — G pedal
|
||||
Note(.named(.g, 2), dur: .whole, dyn: .p)
|
||||
|
||||
// Bar 3 — half plus quarter, then quarter rest (sums to 4 beats)
|
||||
Note(.named(.a, 2), dur: .half, dyn: .mf)
|
||||
Note(.named(.e, 2), dur: .quarter, dyn: .p)
|
||||
Rest(dur: .quarter)
|
||||
|
||||
// Bar 4 — double-stop chords
|
||||
Chord([.named(.f, 2), .named(.c, 3)], dur: .half, dyn: .mp)
|
||||
Chord([.named(.d, 2), .named(.a, 2)], dur: .half, dyn: .mp)
|
||||
|
||||
// Mid-voice clef change: switch to tenor clef for the
|
||||
// walking line so it reads with fewer ledger lines, then switch
|
||||
// back to bass for the low pedal in bar 6. Display-only — sounding
|
||||
// pitches are unchanged.
|
||||
ClefChange(.tenor)
|
||||
// Bar 5 — walking eighth-note bass line
|
||||
Note(.named(.c, 3), dur: .eighth, dyn: .mf)
|
||||
Note(.named(.d, 3), dur: .eighth, dyn: .mp)
|
||||
Note(.named(.e, 3), dur: .eighth, dyn: .mp)
|
||||
Note(.named(.f, 3), dur: .eighth, dyn: .mp)
|
||||
Note(.named(.g, 3), dur: .eighth, dyn: .mf)
|
||||
Note(.named(.a, 3), dur: .eighth, dyn: .mp)
|
||||
Note(.named(.b, 3), dur: .eighth, dyn: .mp)
|
||||
Note(.named(.c, 4), dur: .eighth, dyn: .mf)
|
||||
|
||||
ClefChange(.bass)
|
||||
// Bar 6 — pedal half + triplet fill
|
||||
Note(.named(.g, 2), dur: .half, dyn: .mp, art: .tenuto)
|
||||
Tuplet(3, inTimeOf: 2) {
|
||||
Note(.named(.f, 2), dur: .quarter, dyn: .p)
|
||||
Note(.named(.e, 2), dur: .quarter, dyn: .p)
|
||||
Note(.named(.d, 2), dur: .quarter, dyn: .p)
|
||||
}
|
||||
|
||||
// Bar 7 — marcato accent descent
|
||||
Note(.named(.e, 2), dur: .quarter, dyn: .ff, art: .marcato)
|
||||
Note(.named(.d, 2), dur: .quarter, dyn: .f, art: .staccato)
|
||||
Note(.named(.c, 2), dur: .half, dyn: .mf)
|
||||
|
||||
// Bar 8 — final bass chord (ppp close)
|
||||
Chord([.named(.c, 2), .named(.g, 2), .named(.c, 3)], dur: .whole, dyn: .ppp)
|
||||
}
|
||||
}
|
||||
|
||||
/// B♭ clarinet — transposing-instrument demonstration.
|
||||
/// Score key: G major. Clarinet written key: A major (a major 2nd up,
|
||||
/// because a B♭ instrument reads a major 2nd higher than concert pitch).
|
||||
/// transpose: .bFlat → <transpose><diatonic>-1</diatonic><chromatic>-2</chromatic></transpose>.
|
||||
/// Flatten returns these AS WRITTEN pitches; concert-pitch playback is future work.
|
||||
/// Single voice.
|
||||
private static func makeClarinetPart() -> ScorePart {
|
||||
Part("clarinet", channel: 3, clef: .treble, keySignature: .aMajor, transpose: .bFlat) {
|
||||
// Bar 1 — ascending A major scale fragment (written; sounds G major)
|
||||
Note(.named(.a, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.b, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.cSharp, 6), dur: .quarter, dyn: .mf)
|
||||
Note(.named(.d, 6), dur: .quarter, dyn: .mf)
|
||||
|
||||
// Bar 2 — descending to tonic (written A5, sounds G5)
|
||||
Note(.named(.e, 6), dur: .quarter, dyn: .mf)
|
||||
Note(.named(.d, 6), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.cSharp, 6), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.a, 5), dur: .quarter, dyn: .p)
|
||||
}
|
||||
}
|
||||
|
||||
/// Piano — a grand staff demonstrating multi-staff notation.
|
||||
///
|
||||
/// Staff 1 (treble) holds two independent voices:
|
||||
/// - **Voice 1** — a 4-bar melodic fragment.
|
||||
/// - **Voice 2** — sustained chord tones that overlay from beat 0; bars 1–2
|
||||
/// tie a C-major triad (C4–E4–G4) across the barline so all three pitches
|
||||
/// sustain.
|
||||
/// Staff 2 (bass) holds **Voice 3** — a sustained whole-note C under a
|
||||
/// sustain-pedal marking (pedal down before the note, released after it).
|
||||
///
|
||||
/// In MusicXML this encodes as one part with `<staves>2</staves>`, a
|
||||
/// `<clef number="1">` (treble) / `<clef number="2">` (bass) pair, a
|
||||
/// `<staff>` element on every note, `<backup>` between the three voices,
|
||||
/// and `<pedal>` start/stop directions attached to staff 2.
|
||||
private static func makePianoPart() -> ScorePart {
|
||||
Part("piano", channel: 2, clef: .treble) {
|
||||
Staff(1) {
|
||||
Voice(1) {
|
||||
// Bar 1 — stepwise ascent
|
||||
Note(.named(.c, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.d, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.e, 5), dur: .quarter, dyn: .mf)
|
||||
Note(.named(.f, 5), dur: .quarter, dyn: .mf)
|
||||
|
||||
// Bar 2 — triplet decoration with a half note landing
|
||||
Tuplet(3, inTimeOf: 2) {
|
||||
Note(.named(.g, 5), dur: .quarter, dyn: .mf)
|
||||
Note(.named(.a, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.g, 5), dur: .quarter, dyn: .mp)
|
||||
}
|
||||
Note(.named(.f, 5), dur: .half, dyn: .p, art: .legato)
|
||||
|
||||
// Bar 3 — eighth-note run with staccato
|
||||
Note(.named(.e, 5), dur: .eighth, dyn: .f, art: .staccato)
|
||||
Note(.named(.d, 5), dur: .eighth, dyn: .f, art: .staccato)
|
||||
Note(.named(.c, 5), dur: .eighth, dyn: .mf, art: .staccato)
|
||||
Note(.named(.d, 5), dur: .eighth, dyn: .mf, art: .staccato)
|
||||
Note(.named(.e, 5), dur: .half, dyn: .p, art: .tenuto)
|
||||
|
||||
// Bar 4 — closing whole note
|
||||
Note(.named(.c, 5), dur: .whole, dyn: .pp)
|
||||
}
|
||||
Voice(2) {
|
||||
// Bar 1 — sustained C major triad tied to bar 2 (chord tie).
|
||||
// The two identical chords sustain as one across the barline.
|
||||
Chord([.named(.c, 4), .named(.e, 4), .named(.g, 4)], dur: .whole, dyn: .mp, tie: true)
|
||||
|
||||
// Bar 2 — same C major triad (tie target: merges with bar 1 above)
|
||||
Chord([.named(.c, 4), .named(.e, 4), .named(.g, 4)], dur: .whole, dyn: .mp)
|
||||
|
||||
// Bar 3 — A minor
|
||||
Chord([.named(.a, 3), .named(.c, 4), .named(.e, 4)], dur: .whole, dyn: .mp)
|
||||
|
||||
// Bar 4 — close on C major
|
||||
Chord([.named(.c, 4), .named(.e, 4), .named(.g, 4)], dur: .whole, dyn: .pp)
|
||||
}
|
||||
}
|
||||
Staff(2, clef: .bass) {
|
||||
Voice(3) {
|
||||
// Bar 1 — sustained bass C under the sustain pedal. Pedal
|
||||
// down before the note, released after; both pedal marks are
|
||||
// notation-only (skipped by flatten(), no ScoreEvent).
|
||||
Pedal(.start)
|
||||
Note(.named(.c, 3), dur: .whole, dyn: .mp)
|
||||
Pedal(.stop)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Texture — algorithmic note generation. Demonstrates the two generative
|
||||
/// helpers, both returning `[ScoreElement]` that drops straight into the Part
|
||||
/// body via the result builder.
|
||||
private static func makeTexturePart() -> ScorePart {
|
||||
Part("texture", channel: 4, clef: .treble) {
|
||||
// `Generate` maps each index 0..<8 through the builder closure —
|
||||
// here a sixteenth-note whole-tone fragment driven by the index.
|
||||
Generate(8) { i in
|
||||
Note(midi: 72 + (i % 6) * 2, dur: .sixteenth, dyn: .pp, art: .staccato)
|
||||
}
|
||||
// `PatternNotes` pulls pitches and rhythms from `Pattern` value
|
||||
// sources: a seeded Brownian MIDI walk for pitch, a repeating
|
||||
// eighth/eighth/quarter cell for rhythm. Stops early if the pitch
|
||||
// pattern exhausts before `count`.
|
||||
PatternNotes(
|
||||
count: 12,
|
||||
midi: Pattern.brownian(low: 60.0, high: 84.0, step: 4.0, length: 12, seed: 42),
|
||||
durations: Pattern.sequence([.eighth, .eighth, .quarter]),
|
||||
dyn: .p
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Timeline — notes placed at explicit musical beats (`BeatPosition`), with
|
||||
/// rests auto-filled by `ScoreTimeline`. Material built in
|
||||
/// ``makeTimelineMaterial()`` (`ScoreTimeline` is throwing). Single voice.
|
||||
private static func makeTimelinePart() -> ScorePart {
|
||||
let material: [ScoreElement] = ScoreDemo.makeTimelineMaterial()
|
||||
return Part("timeline", channel: 5, clef: .treble) {
|
||||
material
|
||||
}
|
||||
}
|
||||
|
||||
/// Auto-voiced — overlapping placements distributed across voices
|
||||
/// automatically (a held whole note + a moving line → two voices). Material
|
||||
/// built in ``makeAutoVoicedMaterial()``.
|
||||
private static func makeAutoVoicePart() -> ScorePart {
|
||||
let material: [ScoreElement] = ScoreDemo.makeAutoVoicedMaterial()
|
||||
return Part("autovoice", channel: 6, clef: .treble) {
|
||||
material
|
||||
}
|
||||
}
|
||||
|
||||
/// Polymeter — this part runs in its OWN 3/4 meter while the rest of the
|
||||
/// score is 4/4. Per-part `meterMap` → independent barlines; the encoder
|
||||
/// renders each part against its own meter. Single voice.
|
||||
private static func makePolymeterPart() -> ScorePart {
|
||||
Part("polymeter", channel: 7, clef: .bass, meterMap: MeterMap(.threeFour)) {
|
||||
for _: Int in 0..<6 {
|
||||
Note(.named(.g, 2), dur: .quarter, dyn: .mp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<key>NSDesktopFolderUsageDescription</key>
|
||||
<string>LyrebirdScoreDemo writes rendered audio and MusicXML files to the Desktop.</string>
|
||||
<key>NSDocumentsFolderUsageDescription</key>
|
||||
<string>LyrebirdScoreDemo writes rendered audio files to Documents.</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.security.app-sandbox</key>
|
||||
<false/>
|
||||
<key>com.apple.security.cs.disable-library-validation</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,76 @@
|
||||
// ScoreVoice.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
|
||||
/// A self-terminating NRT voice driven by a ``ScoreEvent``.
|
||||
///
|
||||
/// Plays a sawtooth oscillator through a percussive amplitude envelope. The
|
||||
/// envelope runs to completion and frees the synthesizer node automatically
|
||||
/// via ``DoneAction/freeNode``, so voices do not pile up during NRT render.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - freqHz: Fundamental frequency in Hz. Stays within audible range; no internal clamping.
|
||||
/// - amp: Linear amplitude in `[0, 1]` — maps directly from ``ScoreEvent/velocity``.
|
||||
/// - durSeconds: Played duration in seconds. The sustain stage occupies the bulk of this
|
||||
/// duration; a fixed 10 ms attack and 60 ms release are subtracted first. If
|
||||
/// `durSeconds` is very short (< 70 ms), the sustain collapses to zero and the voice
|
||||
/// becomes purely percussive.
|
||||
/// - pan: Stereo position in `[-1, 1]`. Default `0.0` (centre).
|
||||
final class ScoreVoice: SynthesizerBase {
|
||||
|
||||
/// Fundamental frequency in Hz. No internal clamping; stay within audible range.
|
||||
let freqHz: Double
|
||||
|
||||
/// Linear amplitude in `[0, 1]`, from the score event's normalized velocity.
|
||||
let amp: Double
|
||||
|
||||
/// Played duration in seconds — determines sustain stage length.
|
||||
let durSeconds: Double
|
||||
|
||||
/// Stereo pan position in `[-1, 1]`.
|
||||
let pan: Double
|
||||
|
||||
/// Fixed attack duration in seconds.
|
||||
private static let attackSeconds: Double = 0.01
|
||||
|
||||
/// Fixed release duration in seconds.
|
||||
private static let releaseSeconds: Double = 0.06
|
||||
|
||||
init(
|
||||
freqHz: Double,
|
||||
amp: Double,
|
||||
durSeconds: Double,
|
||||
pan: Double = 0.0
|
||||
) {
|
||||
self.freqHz = freqHz
|
||||
self.amp = amp
|
||||
self.durSeconds = durSeconds
|
||||
self.pan = pan
|
||||
super.init()
|
||||
}
|
||||
|
||||
override func build() {
|
||||
let attack: Double = ScoreVoice.attackSeconds
|
||||
let release: Double = ScoreVoice.releaseSeconds
|
||||
let sustainSeconds: Double = max(0.0, durSeconds - attack - release)
|
||||
|
||||
let envelope: Envelope = Envelope(
|
||||
levels: [0.0, 1.0, 0.8, 0.0],
|
||||
durations: [attack, sustainSeconds, release],
|
||||
curves: [-4.0, 0.0, -6.0]
|
||||
)
|
||||
|
||||
// Sawtooth oscillator scaled by envelope and amplitude.
|
||||
let osc: OscSawtooth.Audio = OscSawtooth.Audio(freq: freqHz)
|
||||
let env: EnvelopeGen.Control = EnvelopeGen.Control(
|
||||
envelope: envelope,
|
||||
doneAction: .freeNode
|
||||
)
|
||||
let sig: any ValidGeneratorInput = osc * env * amp
|
||||
output(bus: 0, source: Pan2(input: sig, pan: pan))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// main.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
// Output paths — both land on the Desktop.
|
||||
let cafURL: URL = FileManager.default.homeDirectoryForCurrentUser
|
||||
.appendingPathComponent("Desktop/LyrebirdScoreDemo.caf")
|
||||
|
||||
// Render parameters.
|
||||
let sampleRate: Double = 48000
|
||||
let blockSize: Int = 512
|
||||
|
||||
// Build the score first — totalDuration must be known before NRTDriver is created.
|
||||
let demo: ScoreDemo = ScoreDemo()
|
||||
let totalDuration: Double = demo.totalDuration
|
||||
|
||||
// MusicXML export and round-trip before audio engine creation.
|
||||
demo.runDemo()
|
||||
|
||||
// Create NRTDriver and engine.
|
||||
let driver: NRTDriver = NRTDriver(outputURL: cafURL, duration: totalDuration)
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: blockSize,
|
||||
sampleRate: sampleRate,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
driver: driver
|
||||
)
|
||||
|
||||
// Schedule all score voices. SynthesizerBase (and thus scheduleVoices) is
|
||||
// @MainActor-isolated; SwiftPM's top-level entry point is itself main-actor
|
||||
// isolated, so this is a plain direct call — no MainActor hop needed.
|
||||
demo.scheduleVoices(engine: engine)
|
||||
|
||||
print(String(format: "Rendering %.2f s → %@", totalDuration, cafURL.path))
|
||||
|
||||
do {
|
||||
try engine.start()
|
||||
print("Done.")
|
||||
} catch {
|
||||
fputs("Render failed: \(error)\n", stderr)
|
||||
exit(1)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"originHash" : "4acd68de25440f1fcc60a86a69d66a0516f6e9d4f2d769aaab597e24b64fd245",
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "linenoise-swift",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/andybest/linenoise-swift",
|
||||
"state" : {
|
||||
"revision" : "afc897c02b030af7333105c4fedcd843a8339238",
|
||||
"version" : "0.0.3"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "nimble",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/Quick/Nimble.git",
|
||||
"state" : {
|
||||
"revision" : "e9d769113660769a4d9dd3afb855562c0b7ae7b0",
|
||||
"version" : "7.3.4"
|
||||
}
|
||||
}
|
||||
],
|
||||
"version" : 3
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// Package.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// swift-tools-version: 6.0
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "LyrebirdScoreDemo",
|
||||
platforms: [.macOS(.v15)],
|
||||
dependencies: [
|
||||
.package(path: "../.."),
|
||||
],
|
||||
targets: [
|
||||
.executableTarget(
|
||||
name: "LyrebirdScoreDemo",
|
||||
dependencies: [
|
||||
.product(name: "Lyrebird", package: "LyrebirdII"),
|
||||
],
|
||||
path: "LyrebirdScoreDemo"
|
||||
),
|
||||
]
|
||||
)
|
||||
@@ -9,9 +9,10 @@
|
||||
/* Begin PBXBuildFile section */
|
||||
C8D0000000000000000000C /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8D00000000000000000007 /* main.swift */; };
|
||||
C8D0000000000000000000D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8D00000000000000000008 /* AppDelegate.swift */; };
|
||||
C8D0000000000000000000F /* LyrebirdUI in Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdUI */; };
|
||||
C8D00000000000000000021 /* LyrebirdLiveCompile in Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001F /* LyrebirdLiveCompile */; };
|
||||
C8D00000000000000000022 /* LyrebirdLiveCompileUI in Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUI */; };
|
||||
C8D0000000000000000000F /* LyrebirdDynamic in Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdDynamic */; };
|
||||
C8D00000000000000000022 /* LyrebirdLiveCompileUIDynamic in Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */; };
|
||||
C8D00000000000000000036 /* LyrebirdDynamic in Embed Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdDynamic */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
|
||||
C8D00000000000000000034 /* LyrebirdLiveCompileUIDynamic in Embed Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
@@ -27,14 +28,28 @@
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
C8D0000000000000000000F /* LyrebirdUI in Frameworks */,
|
||||
C8D00000000000000000021 /* LyrebirdLiveCompile in Frameworks */,
|
||||
C8D00000000000000000022 /* LyrebirdLiveCompileUI in Frameworks */,
|
||||
C8D0000000000000000000F /* LyrebirdDynamic in Frameworks */,
|
||||
C8D00000000000000000022 /* LyrebirdLiveCompileUIDynamic in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXCopyFilesBuildPhase section */
|
||||
C8D00000000000000000035 /* Embed Frameworks */ = {
|
||||
isa = PBXCopyFilesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
dstPath = "";
|
||||
dstSubfolderSpec = 10;
|
||||
files = (
|
||||
C8D00000000000000000036 /* LyrebirdDynamic in Embed Frameworks */,
|
||||
C8D00000000000000000034 /* LyrebirdLiveCompileUIDynamic in Embed Frameworks */,
|
||||
);
|
||||
name = "Embed Frameworks";
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXCopyFilesBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
C8D00000000000000000002 = {
|
||||
isa = PBXGroup;
|
||||
@@ -73,6 +88,7 @@
|
||||
C8D00000000000000000011 /* Sources */,
|
||||
C8D00000000000000000012 /* Frameworks */,
|
||||
C8D00000000000000000013 /* Resources */,
|
||||
C8D00000000000000000035 /* Embed Frameworks */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
@@ -80,9 +96,8 @@
|
||||
);
|
||||
name = LyrebirdScratchDemo;
|
||||
packageProductDependencies = (
|
||||
C8D0000000000000000001D /* LyrebirdUI */,
|
||||
C8D0000000000000000001F /* LyrebirdLiveCompile */,
|
||||
C8D00000000000000000020 /* LyrebirdLiveCompileUI */,
|
||||
C8D0000000000000000001D /* LyrebirdDynamic */,
|
||||
C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */,
|
||||
);
|
||||
productName = LyrebirdScratchDemo;
|
||||
productReference = C8D00000000000000000004 /* LyrebirdScratchDemo.app */;
|
||||
@@ -248,6 +263,10 @@
|
||||
STRING_CATALOG_GENERATE_SYMBOLS = YES;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
// Xcode 26 explicit-module-build regression: SPM dynamic-library
|
||||
// framework binaries (LyrebirdDynamic / LyrebirdLiveCompileUIDynamic)
|
||||
// are not emitted under the integrated driver. Classic driver fixes it.
|
||||
SWIFT_USE_INTEGRATED_DRIVER = NO;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
@@ -303,6 +322,8 @@
|
||||
STRING_CATALOG_GENERATE_SYMBOLS = YES;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
// Xcode 26 explicit-module-build regression — see Debug config.
|
||||
SWIFT_USE_INTEGRATED_DRIVER = NO;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
@@ -341,20 +362,15 @@
|
||||
/* End XCLocalSwiftPackageReference section */
|
||||
|
||||
/* Begin XCSwiftPackageProductDependency section */
|
||||
C8D0000000000000000001D /* LyrebirdUI */ = {
|
||||
C8D0000000000000000001D /* LyrebirdDynamic */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
package = C8D0000000000000000001B /* XCLocalSwiftPackageReference "../.." */;
|
||||
productName = LyrebirdUI;
|
||||
productName = LyrebirdDynamic;
|
||||
};
|
||||
C8D0000000000000000001F /* LyrebirdLiveCompile */ = {
|
||||
C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
package = C8D0000000000000000001E /* XCLocalSwiftPackageReference "../../LiveCompile" */;
|
||||
productName = LyrebirdLiveCompile;
|
||||
};
|
||||
C8D00000000000000000020 /* LyrebirdLiveCompileUI */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
package = C8D0000000000000000001E /* XCLocalSwiftPackageReference "../../LiveCompile" */;
|
||||
productName = LyrebirdLiveCompileUI;
|
||||
productName = LyrebirdLiveCompileUIDynamic;
|
||||
};
|
||||
/* End XCSwiftPackageProductDependency section */
|
||||
};
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"originHash" : "52fa7c84ca46dcb1ce0f4374a4fb0a5d2c97be57f306d91b8e9efb54af7c3c9e",
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "linenoise-swift",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/andybest/linenoise-swift",
|
||||
"state" : {
|
||||
"revision" : "afc897c02b030af7333105c4fedcd843a8339238",
|
||||
"version" : "0.0.3"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "nimble",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/Quick/Nimble.git",
|
||||
"state" : {
|
||||
"revision" : "e9d769113660769a4d9dd3afb855562c0b7ae7b0",
|
||||
"version" : "7.3.4"
|
||||
}
|
||||
}
|
||||
],
|
||||
"version" : 3
|
||||
}
|
||||
@@ -7,18 +7,28 @@
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
import LyrebirdLiveCompile
|
||||
// LyrebirdLiveCompile (LiveSession, …) is re-exported by LyrebirdLiveCompileUI.
|
||||
import LyrebirdLiveCompileUI
|
||||
|
||||
// This demo deliberately does NOT link `LyrebirdUI`. The live-compile stack
|
||||
// (`LyrebirdLiveCompileUIDynamic`) dynamic-links the single shared
|
||||
// `LyrebirdDynamic.framework` copy of `LyrebirdSynth`; linking the static
|
||||
// `LyrebirdUI` product would static-fold a SECOND copy of every `LyrebirdSynth`
|
||||
// ObjC class into the app binary (intra-package `LyrebirdUI → LyrebirdSynth` is
|
||||
// always a static edge), producing duplicate-class registration and the
|
||||
// "mysterious crashes" the runtime warns about. The only `LyrebirdUI` symbol
|
||||
// this demo used was `LyrebirdWindow`, an `NSWindow`/`NSHostingController`
|
||||
// wrapper with no `LyrebirdSynth` dependency — inlined below instead.
|
||||
|
||||
final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
|
||||
let engine: SynthesisEngine
|
||||
let session: LiveSession
|
||||
var model: LyrebirdScratchModel?
|
||||
var menuController: LyrebirdScratchMenuController?
|
||||
var window: LyrebirdWindow?
|
||||
var window: NSWindow?
|
||||
|
||||
@MainActor
|
||||
init(engine: SynthesisEngine) {
|
||||
self.engine = engine
|
||||
self.session = LiveSession(engine: engine)
|
||||
@@ -32,20 +42,30 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
print("[LyrebirdScratchDemo] Engine failed to start: \(error)")
|
||||
}
|
||||
|
||||
let model = LyrebirdScratchModel(session: session)
|
||||
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session)
|
||||
self.model = model
|
||||
let menuController = LyrebirdScratchMenuController(model: model)
|
||||
let menuController: LyrebirdScratchMenuController = LyrebirdScratchMenuController(model: model)
|
||||
menuController.installMainMenu()
|
||||
self.menuController = menuController
|
||||
|
||||
window = LyrebirdWindow(
|
||||
title: "Lyrebird — Live Scratch",
|
||||
width: 720,
|
||||
height: 560
|
||||
let windowWidth: CGFloat = 720
|
||||
let windowHeight: CGFloat = 560
|
||||
let hosting: NSHostingController<LyrebirdScratchView> =
|
||||
NSHostingController(rootView: LyrebirdScratchView(model: model))
|
||||
let initialSize: CGSize = CGSize(width: windowWidth, height: windowHeight)
|
||||
let win: NSWindow = NSWindow(
|
||||
contentRect: NSRect(origin: .zero, size: initialSize),
|
||||
styleMask: [.titled, .closable, .resizable, .miniaturizable],
|
||||
backing: .buffered,
|
||||
defer: false
|
||||
)
|
||||
window?.open {
|
||||
LyrebirdScratchView(model: model)
|
||||
}
|
||||
// Keep ownership in Swift — NSWindow defaults to releasing on close.
|
||||
win.isReleasedWhenClosed = false
|
||||
win.title = "Lyrebird — Live Scratch"
|
||||
win.contentViewController = hosting
|
||||
win.center()
|
||||
win.makeKeyAndOrderFront(nil)
|
||||
self.window = win
|
||||
}
|
||||
|
||||
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
|
||||
This app is a direct-distribution developer tool, not a Mac App Store
|
||||
submission. Sandbox OFF is the only viable configuration for v1.
|
||||
Phase 147 polish can revisit if an XPC-worker approach is adopted.
|
||||
This could be revisited if an XPC-worker approach is adopted.
|
||||
|
||||
com.apple.security.app-sandbox key is absent (defaults false).
|
||||
-->
|
||||
|
||||
@@ -6,9 +6,8 @@
|
||||
|
||||
import AppKit
|
||||
import LyrebirdSynth
|
||||
import LyrebirdLiveCompile
|
||||
|
||||
let engine = SynthesisEngine(
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 512,
|
||||
sampleRate: 48000,
|
||||
numOutputChannels: 2,
|
||||
@@ -16,8 +15,14 @@ let engine = SynthesisEngine(
|
||||
driver: CoreAudioDriver()
|
||||
)
|
||||
|
||||
let delegate = AppDelegate(engine: engine)
|
||||
let app = NSApplication.shared
|
||||
app.setActivationPolicy(.regular)
|
||||
app.delegate = delegate
|
||||
app.run()
|
||||
// AppDelegate.init is `@MainActor` (mirrors the other demos' bootstrap — since
|
||||
// `SynthesizerBase` is `@MainActor`, AppKit-side construction is main-actor
|
||||
// isolated). Program entry runs on the main thread, so assert main-actor
|
||||
// isolation for the AppKit bootstrap rather than hopping asynchronously.
|
||||
MainActor.assumeIsolated {
|
||||
let delegate: AppDelegate = AppDelegate(engine: engine)
|
||||
let app: NSApplication = NSApplication.shared
|
||||
app.setActivationPolicy(.regular)
|
||||
app.delegate = delegate
|
||||
app.run()
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ private let demo: Demo = .vector
|
||||
// ──────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
@main
|
||||
@MainActor
|
||||
struct LyrebirdiOSDemoApp: App {
|
||||
|
||||
let engine: SynthesisEngine
|
||||
|
||||
@@ -13,6 +13,7 @@ import LyrebirdSynth
|
||||
/// first taps "Start Synthesizer" — this is necessary because
|
||||
/// `SpectralBinDelayUI.init(sampleRate:)` requires the engine's committed
|
||||
/// sample rate, which is only valid after `engine.start()` returns.
|
||||
@MainActor
|
||||
@Observable
|
||||
final class BinDelayController {
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
import Observation
|
||||
import LyrebirdSynth
|
||||
|
||||
@MainActor
|
||||
@Observable
|
||||
final class NoteController {
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
import Observation
|
||||
import LyrebirdSynth
|
||||
|
||||
@MainActor
|
||||
@Observable
|
||||
final class VectorOscillatorController {
|
||||
|
||||
|
||||
@@ -108,6 +108,7 @@ Full reference: [`docs/tooling/cli-guide.md`](docs/tooling/cli-guide.md).
|
||||
| `demo` | SPM-only | A `SineTone` synth with `@LiveParam` frequency/amplitude. | `CoreAudioDriver` |
|
||||
| `ui-demo` | SPM-only | AppKit window with `@UIParam` knobs + `LyrebirdWindow`. | `CoreAudioDriver` |
|
||||
| `nrt` | SPM-only | Renders to `output.caf`, no hardware needed. | `NRTDriver` |
|
||||
| `score` | SPM-only | Authors a `Score` with the notation DSL, exports `score.musicxml` (round-trips it), then renders the events offline to `.caf`. | `NRTDriver` |
|
||||
| `macos-ui-xcode` | Xcode-project | macOS `.app` bundle (AppKit + SwiftUI), hardened runtime. | `CoreAudioDriver` |
|
||||
| `ios-ui` | Xcode-project | iOS `.app` (SwiftUI), with `AVAudioSession` activation. | `iOSAudioDriver` (RemoteIO) |
|
||||
| `auv3` | Xcode-project | AUv3 host `.app` + `aumu` `.appex` subclassing `LyrebirdAudioUnit`. | `AUv3Driver` |
|
||||
@@ -120,7 +121,9 @@ open <name>/<name>.xcworkspace # SPM-only & Xcode-project templates both shi
|
||||
cd <name> && lyrebird run
|
||||
```
|
||||
|
||||
To develop against a local Lyrebird checkout instead of the remote URL (path dependency + an `XCLocalSwiftPackageReference` in the generated project):
|
||||
**Lyrebird dependency, default behaviour.** When run from a Lyrebird source checkout (e.g. `swift run LyrebirdCLI new …`), the scaffolder pins the generated project to *that same checkout* as a `path:` dependency (and an `XCLocalSwiftPackageReference` in Xcode-bearing templates). This keeps the emitted template source and the Lyrebird it builds against in lockstep — pre-1.0-stable, the published tag lags unreleased Score/Generator API. The CLI prints the chosen dependency, e.g. `Lyrebird dependency: local checkout at /Users/me/Documents/LyrebirdII`. If no local checkout is derivable (an installed binary with no source tree), it falls back to the published remote package and warns.
|
||||
|
||||
Override the checkout explicitly with `--lyrebird-path`:
|
||||
|
||||
```bash
|
||||
lyrebird new <name> --template <t> --lyrebird-path /Users/me/Documents/LyrebirdII
|
||||
@@ -246,11 +249,92 @@ open MyApp/MyApp.xcworkspace # set your signing team, then run on device/si
|
||||
|
||||
The iOS template uses `iOSAudioDriver` (RemoteIO) and activates an `AVAudioSession` at launch; the synth/UI code is otherwise identical to the macOS UI template. The reference app is [`Demos/LyrebirdiOSDemo`](Demos/LyrebirdiOSDemo/).
|
||||
|
||||
### 6. Score / notation (MusicXML + offline render)
|
||||
|
||||
```bash
|
||||
lyrebird new MyScore --template score # aliases: score-musicxml, musicxml
|
||||
cd MyScore && lyrebird run # writes score.musicxml, round-trips it, renders .caf
|
||||
```
|
||||
|
||||
The `score` template authors music in the language-side **Score DSL** — a result-builder of `Note` / `Rest` / `Chord` / `Tuplet` with exact rational tuplet math (no float drift across nested ratios), spelling-aware pitches (`Note(.named(.c, 5))`), dynamics, and articulations. It exports MusicXML, parses it back for a round-trip sanity check, then schedules one self-freeing voice per `ScoreEvent` against an `NRTDriver`:
|
||||
|
||||
```swift
|
||||
import LyrebirdSynth
|
||||
|
||||
let score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
|
||||
Part("lead") {
|
||||
Note(.named(.c, 5), dur: .quarter, dyn: .mf, art: .staccato)
|
||||
Note(.named(.e, 5), dur: .eighth.dotted, dyn: .mf)
|
||||
Rest(dur: .eighth)
|
||||
Tuplet(3, inTimeOf: 2) {
|
||||
Note(.named(.g, 5), dur: .quarter)
|
||||
Note(.named(.a, 5), dur: .quarter)
|
||||
Note(.named(.b, 5), dur: .quarter)
|
||||
}
|
||||
Chord([.named(.c, 5), .named(.e, 5), .named(.g, 5)], dur: .half, dyn: .f, art: .tenuto)
|
||||
}
|
||||
Part("bass", channel: 1, clef: .bass) {
|
||||
Note(.named(.c, 3), dur: .whole, dyn: .mp)
|
||||
}
|
||||
}
|
||||
|
||||
let xml = score.toMusicXMLString() // export
|
||||
let restored = try Score.fromMusicXML(data: score.toMusicXMLData()) // round-trip
|
||||
for event in score.allEvents { // flat, absolute-beat events (rests excluded)
|
||||
let hz = event.pitch.frequency ?? 0
|
||||
// schedule a voice at event.beat * secondsPerBeat for event.performedDuration …
|
||||
}
|
||||
```
|
||||
|
||||
Notable score features:
|
||||
|
||||
- **Notation model** — per-part `Clef` (`.auto` infers from pitch range), `KeySignature` (score-level + per-part override), `TempoChange` (measure-indexed), `RepeatStructure` / volta `Ending`, transposing-instrument `Transpose`, grace notes, chord ties, and nested tuplet brackets. These are notation-only — `flatten()` / playback use the base `bpm`.
|
||||
- **MusicXML round-trip** — `score.toMusicXMLString()` / `.toMusicXMLData()` out, `Score.fromMusicXML(data:)` back. Spelling (letter + accidental, microtonal nine-step grid) is preserved.
|
||||
- **Sounding vs. notated duration** — `ScoreEvent.duration` is notated; `event.performedDuration` applies `articulation.durationScale` for audio / MIDI note-off.
|
||||
- **Playback** — `ScorePlayer` walks the flat event list against a `LyrebirdClock` on a `LyrebirdRoutine` (mirrors `MIDIFilePlayer`); SMF bridges via `Score+MIDIFile`.
|
||||
- **Pitch / scale theory toolkit** — spelling-aware `Interval` / `Scale` / `PitchCollection` / 12-tone rows, diatonic-vs-chromatic transposition, scale-to-scale mapping; results drop straight into the DSL (`Note(.named(...))`). See [`docs/stdlib/theory.md`](docs/stdlib/theory.md).
|
||||
|
||||
The template writes both files into the **project root** (next to `Package.swift`) via `LyrebirdPaths.projectRoot()` — see [File output locations](#file-output-locations) — so output lands in the same place whether you run with `lyrebird run`, `swift run`, or Xcode.
|
||||
|
||||
Full guide: `Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md`. Reference project: [`Demos/LyrebirdScoreDemo`](Demos/LyrebirdScoreDemo/).
|
||||
|
||||
---
|
||||
|
||||
## File output locations
|
||||
|
||||
When a project writes files (an NRT `.caf`, a MusicXML export, a recording), *where* they land depends on how the binary is launched: `lyrebird run` / `swift run` set the working directory to the package root, but **Xcode sets it to `DerivedData`** and a bare binary inherits whatever shell launched it. Hardcoding `URL(fileURLWithPath: "out.caf")` therefore drops files in surprising places.
|
||||
|
||||
`LyrebirdPaths` (core `Lyrebird` module) resolves the common locations for you:
|
||||
|
||||
| Member | Resolves to | Use for |
|
||||
|---|---|---|
|
||||
| `LyrebirdPaths.projectRoot()` | Folder containing `Package.swift`, found by walking up from the **calling source file** at compile time. Returns `URL?`. | Dev-time render/export output you want beside your project, independent of launch method. |
|
||||
| `LyrebirdPaths.documents` | `.documentDirectory` (`~/Documents` on macOS; the app sandbox Documents on iOS). | **Shipped apps** writing user-visible data. The right choice on iOS. |
|
||||
| `LyrebirdPaths.applicationSupport` | `.applicationSupportDirectory` | App-managed data (presets, state) not meant to be user-visible. |
|
||||
| `LyrebirdPaths.caches` | `.cachesDirectory` | Regenerable data the system may purge. |
|
||||
| `LyrebirdPaths.temporary` | Per-process temp dir | Scratch files. |
|
||||
| `LyrebirdPaths.home` | User home | — |
|
||||
| `LyrebirdPaths.currentWorkingDirectory` | Process cwd | Equals project root under `lyrebird run`; a sensible `??` fallback for `projectRoot()`. |
|
||||
| `LyrebirdPaths.desktop` *(macOS only)* | `.desktopDirectory`. Returns `URL?`. | Quick dev dumps. Needs an entitlement in a sandboxed app. |
|
||||
|
||||
```swift
|
||||
import LyrebirdSynth
|
||||
|
||||
// Dev-time: write beside the project, regardless of launch method.
|
||||
let dir = LyrebirdPaths.projectRoot() ?? LyrebirdPaths.currentWorkingDirectory
|
||||
let cafURL = dir.appendingPathComponent("render.caf")
|
||||
|
||||
// Shipped app (iOS/macOS): write where the sandbox allows.
|
||||
let userOut = LyrebirdPaths.documents.appendingPathComponent("render.caf")
|
||||
```
|
||||
|
||||
`projectRoot()` is a compile-time, source-anchored path — it reflects where the binary was **built**, so it does not exist on another user's machine. Use it for development output only; use `documents` / `applicationSupport` in anything you distribute. It walks up to `Package.swift` by default; pass a dot-prefixed `marker: ".xcodeproj"` (or `.xcworkspace`) — matched by extension, so it finds `MyApp.xcodeproj` — for an Xcode-project layout with no manifest.
|
||||
|
||||
---
|
||||
|
||||
## Xcode file templates
|
||||
|
||||
Beyond whole projects, the CLI installs **New File…** templates so you can add a Generator, Synthesizer, Task, Oscillator, Filter, Spectral Processor, AUv3 source-slot synth, test suite, and more without boilerplate:
|
||||
Beyond whole projects, the CLI installs **New File…** templates so you can add a Generator, Synthesizer, Task, Oscillator, Filter, Spectral Processor, Score, AUv3 source-slot synth, test suite, and more without boilerplate:
|
||||
|
||||
```bash
|
||||
lyrebird install-templates # New File… ▸ Lyrebird section appears in Xcode
|
||||
@@ -263,7 +347,7 @@ From a repo checkout you can equivalently run `bash scripts/install-xcode-templa
|
||||
|
||||
## Reference projects
|
||||
|
||||
The repo ships six runnable demos in [`Demos/`](Demos/), opened via `Lyrebird.xcworkspace`, covering every template above — start there to see complete, working code:
|
||||
The repo ships seven runnable demos in [`Demos/`](Demos/), opened via `Lyrebird.xcworkspace`, covering every template above — start there to see complete, working code:
|
||||
|
||||
| Demo | Mirrors template |
|
||||
|---|---|
|
||||
@@ -271,6 +355,7 @@ The repo ships six runnable demos in [`Demos/`](Demos/), opened via `Lyrebird.xc
|
||||
| [`LyrebirdMacOSDemo`](Demos/LyrebirdMacOSDemo/) | `macos-ui-xcode` |
|
||||
| [`LyrebirdiOSDemo`](Demos/LyrebirdiOSDemo/) | `ios-ui` |
|
||||
| [`LyrebirdNRTDemo`](Demos/LyrebirdNRTDemo/) | `nrt` |
|
||||
| [`LyrebirdScoreDemo`](Demos/LyrebirdScoreDemo/) | `score` |
|
||||
| [`LyrebirdAUv3Demo`](Demos/LyrebirdAUv3Demo/) | `auv3` |
|
||||
| [`LyrebirdScratchDemo`](Demos/LyrebirdScratchDemo/) | live-coding scratchpad |
|
||||
|
||||
|
||||
+22
-9
@@ -1,26 +1,26 @@
|
||||
# Lyrebird — Start Here
|
||||
|
||||
Six demo projects live in this workspace. This guide covers how to open them, what each one does, where to add your own synthesizers, and the gotchas that will bite you if you don't know about them.
|
||||
Seven demo projects live in this workspace. This guide covers how to open them, what each one does, where to add your own synthesizers, and the gotchas that will bite you if you don't know about them.
|
||||
|
||||
---
|
||||
|
||||
## Opening the Workspace
|
||||
|
||||
Open **`Lyrebird.xcworkspace`** — not any individual `.xcodeproj` file. The workspace links all six demo projects together so they share the local Lyrebird package.
|
||||
Open **`Lyrebird.xcworkspace`** — not any individual `.xcodeproj` file. The workspace links all seven demo projects together so they share the local Lyrebird package.
|
||||
|
||||
Once open, pick a scheme from the scheme picker at the top of the Xcode window and hit Run.
|
||||
|
||||
---
|
||||
|
||||
## The Six Demos
|
||||
## The Seven Demos
|
||||
|
||||
### LyrebirdDemo — Real-Time CLI
|
||||
|
||||
A command-line tool that plays audio through your default output device using `CoreAudioDriver`.
|
||||
|
||||
- **Where to add synthesizers:** `Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/` — `SineTone.swift` and `DelaySample.swift` are the starting examples
|
||||
- **Wire it up:** in `main.swift`, call `engine.schedule(MySynth(), after: 0.0)`
|
||||
- **To stop:** Ctrl-C in the Xcode console, or just let the synthesizer's done action free it
|
||||
- **Where to add synthesizers:** `Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/` — `General/SineTone.swift` and `General/DelaySample.swift` are the starting examples (the folder is grouped into `General/`, `Buffer/`, `Granular/`, `Spectral/`)
|
||||
- **Wire it up:** `main.swift` adds a synth and plays it — `try engine.add(mySynth)`, or `try engine.schedule(mySynth, after: seconds)` for sample-accurate start. (As shipped, `main.swift` runs a demo harness — `BufferDemos(engine: engine).runDemo()`; swap in your own.)
|
||||
- **To stop:** Ctrl-C in the Xcode console, or give a voice an envelope/line that frees itself (see below)
|
||||
|
||||
You can also run this from the terminal: `cd Demos/LyrebirdDemo && swift run`
|
||||
|
||||
@@ -36,8 +36,8 @@ A SwiftUI app with a live oscilloscope, parameter knobs, and real-time audio.
|
||||
|
||||
```swift
|
||||
final class MySynth: SynthesizerBase {
|
||||
@UIParam var freq: LyrebirdFloat = 440.0
|
||||
@UIParam var amp: LyrebirdFloat = 0.5
|
||||
@UIParam var freq: Double = 440.0
|
||||
@UIParam var amp: Double = 0.5
|
||||
|
||||
override func build() {
|
||||
let sig = OscSin.Audio(freq: freq) * amp
|
||||
@@ -105,6 +105,17 @@ let right = In.Audio(bus: 3) // numOutputChannels + 1
|
||||
|
||||
---
|
||||
|
||||
### LyrebirdScoreDemo — Score / MusicXML + Offline Render
|
||||
|
||||
A command-line tool that builds notated `Score`s with the result-builder DSL, exports them to MusicXML on the Desktop, round-trips them through the parser as a sanity check, then renders the audio to a CAF file via `NRTDriver`.
|
||||
|
||||
- **Output files:** `~/Desktop/LyrebirdScoreDemo.musicxml` (a multi-part demo score), `~/Desktop/LyrebirdScoreSections.musicxml` (a sectioned showcase), and `~/Desktop/LyrebirdScoreDemo.caf` (rendered audio). Open the `.musicxml` in Dorico / MuseScore / Finale; open the `.caf` in any DAW.
|
||||
- **Where the score is built:** `Demos/LyrebirdScoreDemo/LyrebirdScoreDemo/Demos/ScoreDemo.swift` — `makeScore()` (eight parts) and `makeSectionedShowcase()`.
|
||||
- **Notation coverage:** clefs, keys, dynamics/hairpins, ties, tuplets, grace notes, multi-staff `Staff`/`Voice`, sustain `Pedal`, repeats with 1st/2nd endings, `Section`s + rehearsal marks, glissandi, per-note display overrides, and page layout. Reference: [`Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md`](Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md).
|
||||
- **Rehearsal-mark tip:** use single-letter `Section` labels (`"A"`, `"B"`, `"C"`) — notation editors auto-sequence rehearsal marks and hide custom words.
|
||||
|
||||
---
|
||||
|
||||
### LyrebirdAUv3Demo — AUv3 Plugin Reference
|
||||
|
||||
A container app + `.appex` extension target shipping **Realized Sound: LyrebirdFM** — a two-operator FM synthesizer wrapped as an `aumu` Audio Unit v3. Loadable in Logic, GarageBand, AUM, Loopy Pro, and any other AUv3 host on macOS.
|
||||
@@ -152,11 +163,12 @@ final class MySynth: SynthesizerBase {
|
||||
override func build() {
|
||||
let sig = OscSin.Audio(freq: 440) * 0.3
|
||||
output(bus: 0, source: Pan2(input: sig, pan: 0))
|
||||
doneAction = .freeEnclosing
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Self-freeing voices:** there is no `doneAction` property to set on the synthesizer. Instead, build a `DoneActionWatchable` generator — `EnvelopeGen`, `Line`, `ExponentialLine`, etc. — **inside `build()`** with `doneAction: .freeNode`; it self-registers, and the engine frees the node when that generator finishes. (`DoneAction` cases are `.nothing`, `.freeNode`, `.loop`.)
|
||||
|
||||
---
|
||||
|
||||
## Common Gotchas
|
||||
@@ -182,6 +194,7 @@ final class MySynth: SynthesizerBase {
|
||||
| Synthesizer and node tree | `docs/protocols/synthesizer.md` |
|
||||
| All built-in generators | `docs/stdlib/generators.md` |
|
||||
| NRT / offline rendering | `docs/tooling/nrt-guide.md` |
|
||||
| Score / MusicXML authoring | `Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md` |
|
||||
| REPL / hot-swap | `docs/tooling/repl.md` |
|
||||
| Xcode file templates | `docs/tooling/xcode-templates.md` |
|
||||
| GUI / parameter binding | `docs/ui/gui-system.md` |
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
// swift-tools-version: 6.0
|
||||
import PackageDescription
|
||||
|
||||
// Phase 167 — `LyrebirdLiveCompile` and `LyrebirdLiveCompileUI` live in this
|
||||
// `LyrebirdLiveCompile` and `LyrebirdLiveCompileUI` live in this
|
||||
// sub-package so that cross-package `.product(name:, package:)` dependency
|
||||
// resolution forces SwiftPM to dynamic-link `libLyrebirdLiveCompile.dylib`
|
||||
// against `libLyrebird.dylib` instead of statically embedding `Lyrebird`'s
|
||||
@@ -20,13 +20,25 @@ let package = Package(
|
||||
name: "LyrebirdLiveCompile",
|
||||
platforms: [.macOS(.v15)],
|
||||
products: [
|
||||
// Product name ≠ target name (mirrors the main package's
|
||||
// `Lyrebird`/`LyrebirdDynamic` pairing). A `.dynamic` product whose name
|
||||
// EQUALS its target name collides in Xcode when that target is also
|
||||
// referenced as a static link elsewhere in the same build graph:
|
||||
// "Swift package target 'X' is linked as a static library by … but
|
||||
// cannot be built dynamically because there is a package product with
|
||||
// the same name." Naming the dynamic products `…Dynamic` removes the
|
||||
// collision so each target builds as a single shared dylib that every
|
||||
// consumer links dynamically. Target/module names are unchanged, so
|
||||
// `import LyrebirdLiveCompile` / `import LyrebirdLiveCompileUI` and the
|
||||
// test targets (which reference targets by name) are unaffected.
|
||||
.library(
|
||||
name: "LyrebirdLiveCompile",
|
||||
name: "LyrebirdLiveCompileDynamic",
|
||||
type: .dynamic,
|
||||
targets: ["LyrebirdLiveCompile"]
|
||||
),
|
||||
.library(
|
||||
name: "LyrebirdLiveCompileUI",
|
||||
name: "LyrebirdLiveCompileUIDynamic",
|
||||
type: .dynamic,
|
||||
targets: ["LyrebirdLiveCompileUI"]
|
||||
),
|
||||
],
|
||||
@@ -48,7 +60,7 @@ let package = Package(
|
||||
.product(name: "LyrebirdDynamic", package: "Lyrebird"),
|
||||
],
|
||||
path: "Sources/LyrebirdLiveCompileUI"
|
||||
// Swift 6 language mode (Phase 203): inherits the swift-tools 6.0 default.
|
||||
// Swift 6 language mode: inherits the swift-tools 6.0 default.
|
||||
),
|
||||
.testTarget(
|
||||
name: "LyrebirdLiveCompileTests",
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 142 core
|
||||
// LyrebirdLiveCompile — core
|
||||
//
|
||||
// `CompiledSnippet` owns the `dlopen` handle and the resolved entry function
|
||||
// pointer for one snippet's dylib. Held by the live session for the lifetime of
|
||||
@@ -35,7 +35,7 @@ public final class CompiledSnippet: @unchecked Sendable {
|
||||
/// Path to the dylib that was `dlopen`'d.
|
||||
public let dylibPath: String
|
||||
|
||||
/// Resolved entry function pointer. Calling this is Phase 143's job.
|
||||
/// Resolved entry function pointer. The snippet harness calls this.
|
||||
public let entry: SnippetEntry
|
||||
|
||||
/// Raw `dlopen` handle. Kept so the OS keeps the dylib mapped.
|
||||
|
||||
@@ -4,13 +4,13 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 144
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// One parsed `swiftc` diagnostic, with `line` already mapped from the wrapped-
|
||||
// snippet coordinate space back to the user's snippet coordinate space (via the
|
||||
// `userBodyLineOffset` from `SnippetHarness.wrap(userBody:)`).
|
||||
//
|
||||
// The editor in Phase 145 (`LyrebirdScratchView`) renders diagnostics in its
|
||||
// The editor (`LyrebirdScratchView`) renders diagnostics in its
|
||||
// margin gutter using `(line, column)` directly.
|
||||
|
||||
#if os(macOS)
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 144
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// `DiagnosticParser.parse(stderr:userBodyLineOffset:)` walks the swiftc stderr
|
||||
// stream line by line, extracts diagnostics matching the standard
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 144
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// Severity classifier for a parsed swiftc diagnostic line.
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 142 core
|
||||
// LyrebirdLiveCompile — core
|
||||
//
|
||||
// Errors raised by `LiveCompiler.compile(source:)`. RT path never sees these:
|
||||
// compilation is a main-thread (or background-queue) operation that runs long
|
||||
|
||||
@@ -4,12 +4,12 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 142 core
|
||||
// LyrebirdLiveCompile — core
|
||||
//
|
||||
// `LiveCompiler.compile(source:)` shells out to `swiftc -emit-library`, then
|
||||
// `dlopen`s the resulting dylib and resolves the snippet entry symbol. No UI,
|
||||
// no `SynthesisEngine` binding (those land in phases 143–146). macOS only —
|
||||
// iOS cannot exec swiftc.
|
||||
// no `SynthesisEngine` binding (those are handled by the harness and session
|
||||
// layers). macOS only — iOS cannot exec swiftc.
|
||||
|
||||
import Foundation
|
||||
#if os(macOS)
|
||||
@@ -34,8 +34,8 @@ public enum LiveCompiler {
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - source: Full Swift source, including the `@_cdecl("lyrebird_snippet_entry")`
|
||||
/// entry. Phase 143's `SnippetHarness` will wrap user input in a preamble that
|
||||
/// provides this; Phase 142 callers (incl. tests) write the full file.
|
||||
/// entry. `SnippetHarness` wraps user input in a preamble that provides
|
||||
/// this; direct callers (incl. tests) write the full file.
|
||||
/// - extraSwiftcArgs: Extra args appended to the `swiftc` invocation. Tests use
|
||||
/// this for `-suppress-warnings` etc. Production callers leave empty.
|
||||
/// - Returns: `CompiledSnippet` holding the dlopen handle and entry pointer.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 143
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// `LiveSession` owns the `SynthesisEngine` and tracks every `Synthesizer` that
|
||||
// each snippet `play(_:)`s, so the next non-additive re-evaluation can
|
||||
@@ -23,7 +23,7 @@ import LyrebirdSynth
|
||||
/// Snippets receive a `SnippetContext` bound to this session through
|
||||
/// `compileAndRun(_:additive:)`.
|
||||
///
|
||||
/// `@unchecked Sendable` (Phase 203): a `LiveSession` is shared between its `@MainActor`
|
||||
/// `@unchecked Sendable`: a `LiveSession` is shared between its `@MainActor`
|
||||
/// owner (`LyrebirdScratchModel`) and the `nonisolated` `compileAndRunAsync` it calls, so
|
||||
/// Swift 6 requires it to be `Sendable`. The conformance is sound by construction:
|
||||
///
|
||||
@@ -70,7 +70,7 @@ public final class LiveSession: @unchecked Sendable {
|
||||
engine: SynthesisEngine,
|
||||
importPaths: [URL] = LiveSession.defaultImportPaths(),
|
||||
librarySearchPaths: [URL] = LiveSession.defaultLibrarySearchPaths(),
|
||||
libraries: [String] = ["LyrebirdDynamic", "LyrebirdLiveCompile"],
|
||||
libraries: [String] = ["LyrebirdDynamic", "LyrebirdLiveCompileDynamic"],
|
||||
rpaths: [URL] = LiveSession.defaultRpaths()
|
||||
) {
|
||||
self.engine = engine
|
||||
@@ -91,7 +91,7 @@ public final class LiveSession: @unchecked Sendable {
|
||||
/// (⌘⇧↩ semantics in the future `LyrebirdScratchView` editor).
|
||||
/// - Returns: The compiled snippet handle. Retained internally so the dylib
|
||||
/// stays mapped; callers can ignore it.
|
||||
/// `@MainActor` (Phase 203): runs the snippet entry — and thus the user body's
|
||||
/// `@MainActor`: runs the snippet entry — and thus the user body's
|
||||
/// `MainActor.assumeIsolated { … }` and any `context.play(_:)` → `engine.add` — on the
|
||||
/// main thread, synchronously (swiftc compile included). The async variant
|
||||
/// ``compileAndRunAsync(_:additive:)`` keeps the compile off-main.
|
||||
@@ -112,8 +112,8 @@ public final class LiveSession: @unchecked Sendable {
|
||||
/// engine-touching steps (`clearTracked()` and the snippet entry via `runEntry`) then run
|
||||
/// on the **main actor**.
|
||||
///
|
||||
/// Running the entry on the main actor matters (Phase 203): the snippet's
|
||||
/// `context.play(_:)` calls `engine.add(_:)`, which is `@MainActor` (Phase 201) and
|
||||
/// Running the entry on the main actor matters: the snippet's
|
||||
/// `context.play(_:)` calls `engine.add(_:)`, which is `@MainActor` and
|
||||
/// mutates `engine.nodeTreeMirror` — state observed by SwiftUI on the main thread. A
|
||||
/// `nonisolated async` method resumes on the generic executor, NOT the caller's actor, so
|
||||
/// the hop is explicit here rather than assumed.
|
||||
@@ -288,7 +288,7 @@ public final class LiveSession: @unchecked Sendable {
|
||||
///
|
||||
/// Searches, in order:
|
||||
/// 1. Walks up from `Bundle(for: LiveSession.self).bundleURL` — this resolves
|
||||
/// to the directory holding `libLyrebirdLiveCompile.dylib` at runtime,
|
||||
/// to the directory holding `libLyrebirdLiveCompileDynamic.dylib` at runtime,
|
||||
/// which is the SPM debug/release dir.
|
||||
/// 2. Walks up from `Bundle.main.executableURL` — fallback for the case
|
||||
/// where the host bundles the dylibs into an `.app`.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 144
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// `LiveSession.compileAndRun(_:additive:)` throws this richer error so callers
|
||||
// see diagnostics pre-mapped to user-snippet coordinates. Other `LiveCompileError`
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 143
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// `SnippetContext` is the public API surface the user's snippet talks to. The
|
||||
// host (via `LiveSession.compileAndRun`) constructs one of these, passes the
|
||||
|
||||
@@ -4,16 +4,15 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 142 core
|
||||
// LyrebirdLiveCompile — core
|
||||
//
|
||||
// C ABI signature of the snippet's exported entry point.
|
||||
|
||||
#if os(macOS)
|
||||
|
||||
/// Snippets export this symbol via `@_cdecl("lyrebird_snippet_entry")`. Phase
|
||||
/// 143 will pass a pointer to a `LiveSession` (or harness context) here;
|
||||
/// Phase 142 only requires that snippets can declare a function matching this
|
||||
/// signature.
|
||||
/// Snippets export this symbol via `@_cdecl("lyrebird_snippet_entry")`. The host
|
||||
/// passes a pointer to a `LiveSession` (or harness context) here; snippets need
|
||||
/// only declare a function matching this signature.
|
||||
public typealias SnippetEntry = @convention(c) (UnsafeMutableRawPointer?) -> Void
|
||||
|
||||
#endif
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 143
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// `SnippetHarness.wrap(userBody:)` produces the full Swift source that
|
||||
// `LiveCompiler.compile(source:)` feeds to swiftc. The preamble imports the
|
||||
@@ -18,9 +18,9 @@ public enum SnippetHarness {
|
||||
|
||||
/// Wraps `userBody` in the standard preamble.
|
||||
///
|
||||
/// The user body runs inside `MainActor.assumeIsolated { … }` (Phase 203): snippets call
|
||||
/// The user body runs inside `MainActor.assumeIsolated { … }`: snippets call
|
||||
/// `@MainActor` API — `context.play(_:)` and `SynthesizerBase` subclass construction
|
||||
/// (both `@MainActor` since Phase 201) — which would not compile from the nonisolated
|
||||
/// (both `@MainActor`) — which would not compile from the nonisolated
|
||||
/// `@_cdecl` entry under Swift 6. The `assumeIsolated` closure gives the body main-actor
|
||||
/// isolation at compile time; it is safe at runtime because `LiveSession` always invokes
|
||||
/// the entry on the main actor (`compileAndRunAsync` hops via `MainActor.run`;
|
||||
|
||||
@@ -4,11 +4,11 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 143
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// Output of `SnippetHarness.wrap(userBody:)`. Carries the full Swift source
|
||||
// that `swiftc` will compile, plus the 1-based line number on which the user's
|
||||
// body begins. Phase 144's diagnostic parser subtracts `userBodyLineOffset - 1`
|
||||
// body begins. The diagnostic parser subtracts `userBodyLineOffset - 1`
|
||||
// from each swiftc-reported line so error rows point back at the row the user
|
||||
// typed.
|
||||
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
# Live coding with `LyrebirdScratchView`
|
||||
|
||||
A SwiftUI scratchpad for hot-swapping snippets through `LyrebirdLiveCompile`.
|
||||
|
||||
## Overview
|
||||
|
||||
`LyrebirdScratchView` pairs an `NSTextView`-backed Swift editor with a `LiveSession`
|
||||
that owns the audio engine. Pressing **⌘↩** wraps the snippet body in the standard
|
||||
harness, shells out to `swiftc`, `dlopen`s the resulting dylib, and calls the
|
||||
snippet's `lyrebird_snippet_entry` with a `SnippetContext` bound to the session.
|
||||
Synthesizers played via `context.play(_:)` are tracked, so the next non-additive
|
||||
run replaces them. **⌘⇧↩** layers a new snippet on top of the prior ones.
|
||||
|
||||
Compile diagnostics from a failing snippet are parsed by `DiagnosticParser`
|
||||
and rendered beneath the editor with line numbers already remapped from the wrapped
|
||||
source back to the user's snippet coordinates.
|
||||
|
||||
The view is macOS-only — `LyrebirdLiveCompile` shells out to `swiftc`, which is
|
||||
unavailable on iOS. The nested `LiveCompile/` sub-package declares
|
||||
`platforms: [.macOS(.v15)]` and cannot be added to an iOS target.
|
||||
|
||||
## Hosting
|
||||
|
||||
```swift
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI // LyrebirdWindow
|
||||
import LyrebirdLiveCompile // LiveSession
|
||||
import LyrebirdLiveCompileUI // LyrebirdScratchView
|
||||
|
||||
let engine = SynthesisEngine(/* … */)
|
||||
try engine.start()
|
||||
|
||||
let session = LiveSession(engine: engine)
|
||||
let window = LyrebirdWindow(title: "Lyrebird Scratch", width: 640, height: 480)
|
||||
window.open {
|
||||
LyrebirdScratchView(session: session)
|
||||
}
|
||||
```
|
||||
|
||||
## Keyboard shortcuts
|
||||
|
||||
| Shortcut | Action |
|
||||
|----------|--------|
|
||||
| ⌘↩ | Compile + run. Removes synths from the previous run before executing. |
|
||||
| ⌘⇧↩ | Compile + run additively. Keeps previously played synths in the engine. |
|
||||
|
||||
The toolbar exposes both as buttons plus a `Clear Synths` button that calls
|
||||
`LiveSession.clearTracked()` directly.
|
||||
|
||||
## Snippet API surface
|
||||
|
||||
A snippet has one local in scope:
|
||||
|
||||
```swift
|
||||
context: SnippetContext
|
||||
```
|
||||
|
||||
`SnippetContext` is intentionally minimal in v1:
|
||||
|
||||
- `context.engine` — the host `SynthesisEngine`.
|
||||
- `context.play(_:)` — add a `Synthesizer` to the engine and register it for
|
||||
cleanup on the next non-additive run.
|
||||
- `context.reportMessage(_:)` — write back to the host (used by tests; handy for
|
||||
`print`-style probes during development).
|
||||
|
||||
## Threading
|
||||
|
||||
All UI is `@MainActor`-isolated. `LiveSession.compileAndRun` is invoked
|
||||
synchronously inside the button action, so the editor freezes for the duration
|
||||
of the `swiftc` invocation (≈ 1 second cold, much faster on warm cache). v1
|
||||
accepts that trade-off; an off-main compile path is on the polish list.
|
||||
|
||||
## Limitations
|
||||
|
||||
- macOS only.
|
||||
- No syntax highlighting, code completion, or line-number gutter (deferred).
|
||||
- Compiled dylibs are leaked by design — types in a loaded snippet may still be
|
||||
referenced by tracked synths; unloading is unsafe.
|
||||
- The host `.app` must not be sandboxed and must allow library validation to be
|
||||
disabled, since `swiftc` is invoked via `Process` and the resulting unsigned
|
||||
dylib is `dlopen`'d.
|
||||
|
||||
## Topics
|
||||
|
||||
- ``LyrebirdScratchView``
|
||||
- ``LyrebirdScratchModel``
|
||||
@@ -1,288 +0,0 @@
|
||||
// LyrebirdScratchMenuController.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import AppKit
|
||||
import UniformTypeIdentifiers
|
||||
import LyrebirdSynth
|
||||
import LyrebirdLiveCompile
|
||||
|
||||
/// Builds and installs the macOS application menu bar for a live-coding host
|
||||
/// driven by a `LyrebirdScratchModel`. Owns the action targets so menu items
|
||||
/// stay wired for the lifetime of the controller.
|
||||
@MainActor
|
||||
public final class LyrebirdScratchMenuController: NSObject {
|
||||
|
||||
public let model: LyrebirdScratchModel
|
||||
|
||||
public init(model: LyrebirdScratchModel) {
|
||||
self.model = model
|
||||
}
|
||||
|
||||
/// Construct the full menu bar (App / File / Edit / Run / View / Window /
|
||||
/// Help) and assign it to `NSApplication.shared.mainMenu`.
|
||||
public func installMainMenu(appName: String = "LyrebirdScratchDemo") {
|
||||
let mainMenu: NSMenu = NSMenu()
|
||||
|
||||
mainMenu.addItem(appMenuItem(appName: appName))
|
||||
mainMenu.addItem(fileMenuItem())
|
||||
mainMenu.addItem(editMenuItem())
|
||||
mainMenu.addItem(runMenuItem())
|
||||
mainMenu.addItem(viewMenuItem())
|
||||
mainMenu.addItem(windowMenuItem())
|
||||
|
||||
NSApplication.shared.mainMenu = mainMenu
|
||||
}
|
||||
|
||||
// MARK: App menu
|
||||
|
||||
private func appMenuItem(appName: String) -> NSMenuItem {
|
||||
let item: NSMenuItem = NSMenuItem()
|
||||
let menu: NSMenu = NSMenu(title: appName)
|
||||
menu.addItem(NSMenuItem(title: "About \(appName)",
|
||||
action: #selector(NSApplication.orderFrontStandardAboutPanel(_:)),
|
||||
keyEquivalent: ""))
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
let services: NSMenuItem = NSMenuItem(title: "Services", action: nil, keyEquivalent: "")
|
||||
let servicesMenu: NSMenu = NSMenu(title: "Services")
|
||||
services.submenu = servicesMenu
|
||||
NSApplication.shared.servicesMenu = servicesMenu
|
||||
menu.addItem(services)
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(NSMenuItem(title: "Hide \(appName)",
|
||||
action: #selector(NSApplication.hide(_:)),
|
||||
keyEquivalent: "h"))
|
||||
let hideOthers: NSMenuItem = NSMenuItem(title: "Hide Others",
|
||||
action: #selector(NSApplication.hideOtherApplications(_:)),
|
||||
keyEquivalent: "h")
|
||||
hideOthers.keyEquivalentModifierMask = [.command, .option]
|
||||
menu.addItem(hideOthers)
|
||||
menu.addItem(NSMenuItem(title: "Show All",
|
||||
action: #selector(NSApplication.unhideAllApplications(_:)),
|
||||
keyEquivalent: ""))
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(NSMenuItem(title: "Quit \(appName)",
|
||||
action: #selector(NSApplication.terminate(_:)),
|
||||
keyEquivalent: "q"))
|
||||
item.submenu = menu
|
||||
return item
|
||||
}
|
||||
|
||||
// MARK: File menu
|
||||
|
||||
private func fileMenuItem() -> NSMenuItem {
|
||||
let item: NSMenuItem = NSMenuItem()
|
||||
let menu: NSMenu = NSMenu(title: "File")
|
||||
menu.addItem(target(NSMenuItem(title: "New",
|
||||
action: #selector(newSnippet(_:)),
|
||||
keyEquivalent: "n")))
|
||||
menu.addItem(target(NSMenuItem(title: "Open…",
|
||||
action: #selector(openSnippet(_:)),
|
||||
keyEquivalent: "o")))
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(target(NSMenuItem(title: "Save",
|
||||
action: #selector(saveSnippet(_:)),
|
||||
keyEquivalent: "s")))
|
||||
let saveAs: NSMenuItem = NSMenuItem(title: "Save As…",
|
||||
action: #selector(saveSnippetAs(_:)),
|
||||
keyEquivalent: "s")
|
||||
saveAs.keyEquivalentModifierMask = [.command, .shift]
|
||||
menu.addItem(target(saveAs))
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(NSMenuItem(title: "Close",
|
||||
action: #selector(NSWindow.performClose(_:)),
|
||||
keyEquivalent: "w"))
|
||||
item.submenu = menu
|
||||
return item
|
||||
}
|
||||
|
||||
// MARK: Edit menu — wires to the first responder so NSTextView gets it
|
||||
|
||||
private func editMenuItem() -> NSMenuItem {
|
||||
let item: NSMenuItem = NSMenuItem()
|
||||
let menu: NSMenu = NSMenu(title: "Edit")
|
||||
menu.addItem(NSMenuItem(title: "Undo",
|
||||
action: Selector(("undo:")),
|
||||
keyEquivalent: "z"))
|
||||
let redo: NSMenuItem = NSMenuItem(title: "Redo",
|
||||
action: Selector(("redo:")),
|
||||
keyEquivalent: "z")
|
||||
redo.keyEquivalentModifierMask = [.command, .shift]
|
||||
menu.addItem(redo)
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(NSMenuItem(title: "Cut",
|
||||
action: #selector(NSText.cut(_:)),
|
||||
keyEquivalent: "x"))
|
||||
menu.addItem(NSMenuItem(title: "Copy",
|
||||
action: #selector(NSText.copy(_:)),
|
||||
keyEquivalent: "c"))
|
||||
menu.addItem(NSMenuItem(title: "Paste",
|
||||
action: #selector(NSText.paste(_:)),
|
||||
keyEquivalent: "v"))
|
||||
menu.addItem(NSMenuItem(title: "Select All",
|
||||
action: #selector(NSText.selectAll(_:)),
|
||||
keyEquivalent: "a"))
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
let find: NSMenuItem = NSMenuItem(title: "Find…",
|
||||
action: #selector(NSTextView.performFindPanelAction(_:)),
|
||||
keyEquivalent: "f")
|
||||
find.tag = Int(NSFindPanelAction.showFindPanel.rawValue)
|
||||
menu.addItem(find)
|
||||
item.submenu = menu
|
||||
return item
|
||||
}
|
||||
|
||||
// MARK: Run menu
|
||||
|
||||
private func runMenuItem() -> NSMenuItem {
|
||||
let item: NSMenuItem = NSMenuItem()
|
||||
let menu: NSMenu = NSMenu(title: "Run")
|
||||
menu.addItem(target(NSMenuItem(title: "Run",
|
||||
action: #selector(runSnippet(_:)),
|
||||
keyEquivalent: "\r")))
|
||||
let runAdd: NSMenuItem = NSMenuItem(title: "Run Additive",
|
||||
action: #selector(runSnippetAdditive(_:)),
|
||||
keyEquivalent: "\r")
|
||||
runAdd.keyEquivalentModifierMask = [.command, .shift]
|
||||
menu.addItem(target(runAdd))
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(target(NSMenuItem(title: "Clear Tracked Synths",
|
||||
action: #selector(clearSynths(_:)),
|
||||
keyEquivalent: "k")))
|
||||
item.submenu = menu
|
||||
return item
|
||||
}
|
||||
|
||||
// MARK: View menu
|
||||
|
||||
private func viewMenuItem() -> NSMenuItem {
|
||||
let item: NSMenuItem = NSMenuItem()
|
||||
let menu: NSMenu = NSMenu(title: "View")
|
||||
let wrap: NSMenuItem = target(NSMenuItem(title: "Wrap Lines",
|
||||
action: #selector(toggleWrap(_:)),
|
||||
keyEquivalent: "l"))
|
||||
wrap.keyEquivalentModifierMask = [.command, .option]
|
||||
menu.addItem(wrap)
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
let inc: NSMenuItem = target(NSMenuItem(title: "Increase Font Size",
|
||||
action: #selector(increaseFontSize(_:)),
|
||||
keyEquivalent: "+"))
|
||||
menu.addItem(inc)
|
||||
menu.addItem(target(NSMenuItem(title: "Decrease Font Size",
|
||||
action: #selector(decreaseFontSize(_:)),
|
||||
keyEquivalent: "-")))
|
||||
menu.addItem(target(NSMenuItem(title: "Reset Font Size",
|
||||
action: #selector(resetFontSize(_:)),
|
||||
keyEquivalent: "0")))
|
||||
item.submenu = menu
|
||||
return item
|
||||
}
|
||||
|
||||
// MARK: Window menu
|
||||
|
||||
private func windowMenuItem() -> NSMenuItem {
|
||||
let item: NSMenuItem = NSMenuItem()
|
||||
let menu: NSMenu = NSMenu(title: "Window")
|
||||
menu.addItem(NSMenuItem(title: "Minimize",
|
||||
action: #selector(NSWindow.performMiniaturize(_:)),
|
||||
keyEquivalent: "m"))
|
||||
menu.addItem(NSMenuItem(title: "Zoom",
|
||||
action: #selector(NSWindow.performZoom(_:)),
|
||||
keyEquivalent: ""))
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(NSMenuItem(title: "Bring All to Front",
|
||||
action: #selector(NSApplication.arrangeInFront(_:)),
|
||||
keyEquivalent: ""))
|
||||
item.submenu = menu
|
||||
NSApplication.shared.windowsMenu = menu
|
||||
return item
|
||||
}
|
||||
|
||||
// MARK: - Action targets
|
||||
|
||||
private func target(_ item: NSMenuItem) -> NSMenuItem {
|
||||
item.target = self
|
||||
return item
|
||||
}
|
||||
|
||||
@objc private func newSnippet(_ sender: Any?) {
|
||||
model.text = LyrebirdScratchModel.defaultPlaceholder
|
||||
}
|
||||
|
||||
@objc private func openSnippet(_ sender: Any?) {
|
||||
let panel: NSOpenPanel = NSOpenPanel()
|
||||
panel.allowedContentTypes = [.swiftSource]
|
||||
panel.allowsMultipleSelection = false
|
||||
panel.canChooseDirectories = false
|
||||
panel.message = "Open a Lyrebird snippet"
|
||||
if panel.runModal() == .OK, let url: URL = panel.url {
|
||||
do {
|
||||
try model.load(from: url)
|
||||
} catch {
|
||||
model.reportLoadError(url: url, error: error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func saveSnippet(_ sender: Any?) {
|
||||
if let url: URL = model.documentURL {
|
||||
do {
|
||||
try model.save(to: url)
|
||||
} catch {
|
||||
model.reportSaveError(url: url, error: error)
|
||||
}
|
||||
return
|
||||
}
|
||||
saveSnippetAs(sender)
|
||||
}
|
||||
|
||||
@objc private func saveSnippetAs(_ sender: Any?) {
|
||||
let panel: NSSavePanel = NSSavePanel()
|
||||
panel.allowedContentTypes = [.swiftSource]
|
||||
panel.nameFieldStringValue = model.documentURL?.lastPathComponent ?? "snippet.swift"
|
||||
panel.message = "Save Lyrebird snippet"
|
||||
if panel.runModal() == .OK, let url: URL = panel.url {
|
||||
do {
|
||||
try model.save(to: url)
|
||||
} catch {
|
||||
model.reportSaveError(url: url, error: error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func runSnippet(_ sender: Any?) {
|
||||
Task { @MainActor in _ = await model.run(additive: false) }
|
||||
}
|
||||
|
||||
@objc private func runSnippetAdditive(_ sender: Any?) {
|
||||
Task { @MainActor in _ = await model.run(additive: true) }
|
||||
}
|
||||
|
||||
@objc private func clearSynths(_ sender: Any?) {
|
||||
model.clearTracked()
|
||||
}
|
||||
|
||||
@objc private func toggleWrap(_ sender: Any?) {
|
||||
model.toggleWrapsLines()
|
||||
if let item: NSMenuItem = sender as? NSMenuItem {
|
||||
item.state = model.wrapsLines ? .on : .off
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func increaseFontSize(_ sender: Any?) {
|
||||
model.bumpFontSize(by: 1)
|
||||
}
|
||||
|
||||
@objc private func decreaseFontSize(_ sender: Any?) {
|
||||
model.bumpFontSize(by: -1)
|
||||
}
|
||||
|
||||
@objc private func resetFontSize(_ sender: Any?) {
|
||||
model.resetFontSize()
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,227 +0,0 @@
|
||||
// LyrebirdScratchModel.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdUI/LiveCompile — Phase 145
|
||||
//
|
||||
// Backing model for `LyrebirdScratchView`. Owns the editable snippet text, the
|
||||
// most recent compile result, and the host `LiveSession`. Pulled out of the
|
||||
// view so logic can be exercised without instantiating SwiftUI.
|
||||
//
|
||||
// macOS only — wraps `LyrebirdLiveCompile`, which itself is macOS-only.
|
||||
|
||||
#if os(macOS)
|
||||
import Foundation
|
||||
import CoreGraphics
|
||||
import LyrebirdSynth
|
||||
import LyrebirdLiveCompile
|
||||
|
||||
/// Observable backing model for `LyrebirdScratchView`.
|
||||
///
|
||||
/// Drives one live-coding editor pane. `run(additive:)` awaits
|
||||
/// `LiveSession.compileAndRunAsync` so the swiftc invocation runs off the main
|
||||
/// actor and the editor stays responsive. ``isCompiling`` flips around the
|
||||
/// await so SwiftUI can disable the Run buttons and surface a "Compiling…"
|
||||
/// status while the dylib build is in flight.
|
||||
@MainActor
|
||||
public final class LyrebirdScratchModel: ObservableObject {
|
||||
|
||||
/// Default placeholder text loaded into a fresh model. Walks the user
|
||||
/// through the two keyboard shortcuts and the in-snippet API surface.
|
||||
/// `nonisolated` so callers in a non-main context (e.g. SwiftUI init's
|
||||
/// default-argument evaluation, which is not implicitly main-actor) can
|
||||
/// reference it without a Swift 6 isolation diagnostic.
|
||||
public nonisolated static let defaultPlaceholder: String = """
|
||||
// ⌘↩ — compile + run (removes synths from the previous run first).
|
||||
// ⌘⇧↩ — additive run (keep previously played synths around).
|
||||
//
|
||||
// The snippet body has `context: SnippetContext` in scope.
|
||||
// `context.engine` → the host `SynthesisEngine`.
|
||||
// `context.play(synth)` → adds a `Synthesizer` and tracks it for cleanup.
|
||||
// `context.reportMessage(_)`→ writes back to the host (useful for `print`-style probes).
|
||||
|
||||
class SineSynth: SynthesizerBase {
|
||||
override func build() {
|
||||
let sine = OscSin.Audio(freq: 440, mul: 0.15)
|
||||
let stereo = Pan2(input: sine, pan: 0)
|
||||
output(bus: 0, source: stereo)
|
||||
}
|
||||
}
|
||||
|
||||
let synth = SineSynth()
|
||||
_ = context.play(synth)
|
||||
context.reportMessage("playing 440 Hz sine — stereo, centered")
|
||||
|
||||
"""
|
||||
|
||||
/// Current editor text. View binds to this; user edits flow back here via
|
||||
/// the `NSTextView` delegate inside `LyrebirdScratchView`.
|
||||
@Published public var text: String
|
||||
|
||||
/// Parsed swiftc diagnostics from the last `run(additive:)` invocation.
|
||||
/// Empty when the last run compiled cleanly or has not yet been attempted.
|
||||
@Published public private(set) var diagnostics: [Diagnostic] = []
|
||||
|
||||
/// Single-line human-readable status line shown beneath the editor.
|
||||
/// Updated by `run(additive:)` and `clearTracked()`.
|
||||
@Published public private(set) var statusMessage: String = ""
|
||||
|
||||
/// Mirror of `session.trackedSynthCount`, refreshed after every `run` /
|
||||
/// `clearTracked` call so the toolbar can show the count without polling.
|
||||
@Published public private(set) var trackedSynthCount: Int
|
||||
|
||||
/// `true` while a `run(additive:)` invocation is awaiting the background
|
||||
/// swiftc compile. View code disables Run / Run Additive buttons against
|
||||
/// this so a second compile cannot stack on top of a still-running one.
|
||||
@Published public private(set) var isCompiling: Bool = false
|
||||
|
||||
/// URL of the file the editor text was last saved to or loaded from. `nil`
|
||||
/// when the editor holds unsaved scratch content. The view uses this to
|
||||
/// distinguish a silent overwrite (⌘S) from a Save As… prompt.
|
||||
@Published public private(set) var documentURL: URL?
|
||||
|
||||
/// Editor font size in points. Clamped to `[minFontSize, maxFontSize]`.
|
||||
@Published public var fontSize: CGFloat = 13
|
||||
|
||||
/// When `true`, lines wrap at the editor's right edge instead of scrolling
|
||||
/// horizontally.
|
||||
@Published public var wrapsLines: Bool = true
|
||||
|
||||
public let session: LiveSession
|
||||
|
||||
public nonisolated static let minFontSize: CGFloat = 9
|
||||
public nonisolated static let maxFontSize: CGFloat = 32
|
||||
public nonisolated static let defaultFontSize: CGFloat = 13
|
||||
|
||||
public func bumpFontSize(by delta: CGFloat) {
|
||||
fontSize = max(LyrebirdScratchModel.minFontSize,
|
||||
min(LyrebirdScratchModel.maxFontSize, fontSize + delta))
|
||||
}
|
||||
|
||||
public func resetFontSize() {
|
||||
fontSize = LyrebirdScratchModel.defaultFontSize
|
||||
}
|
||||
|
||||
public func toggleWrapsLines() {
|
||||
wrapsLines.toggle()
|
||||
}
|
||||
|
||||
/// - Parameters:
|
||||
/// - session: Host `LiveSession` the model forwards compile + cleanup
|
||||
/// calls to. Retained for the model's lifetime.
|
||||
/// - initialText: Seed text loaded into `text`. Defaults to
|
||||
/// ``defaultPlaceholder``.
|
||||
public init(
|
||||
session: LiveSession,
|
||||
initialText: String = LyrebirdScratchModel.defaultPlaceholder
|
||||
) {
|
||||
self.session = session
|
||||
self.text = initialText
|
||||
self.trackedSynthCount = session.trackedSynthCount
|
||||
}
|
||||
|
||||
/// Compile and execute the current `text`. Updates `diagnostics`,
|
||||
/// `statusMessage`, `trackedSynthCount`, and ``isCompiling``.
|
||||
///
|
||||
/// Awaits `LiveSession.compileAndRunAsync`, which runs swiftc on a
|
||||
/// `Task.detached`. The view's Run / Run Additive buttons bind to
|
||||
/// ``isCompiling`` and stay disabled until this method returns.
|
||||
///
|
||||
/// - Parameter additive: When `false`, the session removes every
|
||||
/// previously tracked synth before running. When `true`, prior synths
|
||||
/// stay in the engine (⌘⇧↩ in the view).
|
||||
/// - Returns: `true` when the snippet compiled and its entry returned
|
||||
/// without throwing; `false` otherwise.
|
||||
@discardableResult
|
||||
public func run(additive: Bool) async -> Bool {
|
||||
guard !isCompiling else { return false }
|
||||
let body: String = text
|
||||
diagnostics = []
|
||||
statusMessage = "Compiling…"
|
||||
isCompiling = true
|
||||
defer {
|
||||
isCompiling = false
|
||||
trackedSynthCount = session.trackedSynthCount
|
||||
}
|
||||
do {
|
||||
try await session.compileAndRunAsync(body, additive: additive)
|
||||
let mode: String = additive ? "additive" : "replaced"
|
||||
statusMessage = "Ran (\(mode)). Tracked synths: \(session.trackedSynthCount)."
|
||||
return true
|
||||
} catch let sessionError as LiveSessionError {
|
||||
switch sessionError {
|
||||
case .snippetCompileFailed(let diags, let underlying):
|
||||
if diags.isEmpty {
|
||||
diagnostics = [Diagnostic(
|
||||
line: nil,
|
||||
column: 0,
|
||||
severity: .error,
|
||||
message: "\(underlying)",
|
||||
rawLine: 0
|
||||
)]
|
||||
statusMessage = "Compile failed — see diagnostics below."
|
||||
} else {
|
||||
diagnostics = diags
|
||||
let plural: String = diags.count == 1 ? "" : "s"
|
||||
statusMessage = "Compile failed — \(diags.count) diagnostic\(plural)."
|
||||
}
|
||||
case .compilerError(let underlying):
|
||||
statusMessage = "Compiler error: \(underlying)"
|
||||
}
|
||||
return false
|
||||
} catch {
|
||||
statusMessage = "Error: \(error)"
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Forward to `LiveSession.clearTracked()` and refresh `trackedSynthCount`.
|
||||
public func clearTracked() {
|
||||
session.clearTracked()
|
||||
trackedSynthCount = session.trackedSynthCount
|
||||
statusMessage = "Cleared tracked synths."
|
||||
}
|
||||
|
||||
// MARK: - Snippet save / load
|
||||
|
||||
/// Replace `text` with the UTF-8 contents at `url`, set ``documentURL``
|
||||
/// for subsequent saves, and refresh the status line.
|
||||
///
|
||||
/// - Parameter url: File to read. Caller (view) is responsible for the
|
||||
/// `NSOpenPanel` UI; this method does the IO.
|
||||
public func load(from url: URL) throws {
|
||||
let loaded: String = try String(contentsOf: url, encoding: .utf8)
|
||||
text = loaded
|
||||
documentURL = url
|
||||
diagnostics = []
|
||||
statusMessage = "Loaded \(url.lastPathComponent)."
|
||||
}
|
||||
|
||||
/// Write `text` to `url` as UTF-8, set ``documentURL``, refresh status.
|
||||
///
|
||||
/// - Parameter url: Destination. Overwrites if present. Caller drives the
|
||||
/// `NSSavePanel` UI.
|
||||
public func save(to url: URL) throws {
|
||||
try text.write(to: url, atomically: true, encoding: .utf8)
|
||||
documentURL = url
|
||||
statusMessage = "Saved \(url.lastPathComponent)."
|
||||
}
|
||||
|
||||
/// Surface a load failure on the status line without throwing across the
|
||||
/// view layer. Called by the view after `NSOpenPanel` returned a URL that
|
||||
/// `load(from:)` rejected.
|
||||
public func reportLoadError(url: URL, error: Error) {
|
||||
statusMessage = "Load failed (\(url.lastPathComponent)): \(error.localizedDescription)"
|
||||
}
|
||||
|
||||
/// Surface a save failure on the status line without throwing across the
|
||||
/// view layer. Called by the view after `NSSavePanel` returned a URL that
|
||||
/// `save(to:)` rejected.
|
||||
public func reportSaveError(url: URL, error: Error) {
|
||||
statusMessage = "Save failed (\(url.lastPathComponent)): \(error.localizedDescription)"
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,409 +0,0 @@
|
||||
// LyrebirdScratchView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdUI/LiveCompile — Phase 145
|
||||
//
|
||||
// `LyrebirdScratchView` — SwiftUI scratchpad editor for live-coded snippets.
|
||||
// Wraps an `NSTextView` for the editor surface, drives a `LyrebirdScratchModel`
|
||||
// for compile state, and surfaces parsed `Diagnostic`s in a scrollable list
|
||||
// below the editor. macOS-only; iOS hosting is deferred (no swiftc on device).
|
||||
|
||||
#if os(macOS)
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
import UniformTypeIdentifiers
|
||||
import LyrebirdSynth
|
||||
import LyrebirdLiveCompile
|
||||
|
||||
/// SwiftUI scratchpad for live-compiled Lyrebird snippets.
|
||||
///
|
||||
/// Pair with a `LiveSession` that owns the audio engine, drop the view into a
|
||||
/// `LyrebirdWindow`, and ⌘↩ replaces the prior run while ⌘⇧↩ adds to it.
|
||||
/// Diagnostics from a failed compile are listed under the editor with the
|
||||
/// user's snippet-row coordinates already mapped by `DiagnosticParser`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - session: Host `LiveSession` owning the `SynthesisEngine`. Forwarded
|
||||
/// into the backing ``LyrebirdScratchModel``.
|
||||
/// - initialText: Seed text loaded into the editor. Defaults to
|
||||
/// ``LyrebirdScratchModel/defaultPlaceholder``.
|
||||
///
|
||||
/// ## Hosting
|
||||
///
|
||||
/// ```swift
|
||||
/// import LyrebirdUI // LyrebirdWindow
|
||||
/// import LyrebirdLiveCompile // LiveSession
|
||||
/// import LyrebirdLiveCompileUI // LyrebirdScratchView
|
||||
///
|
||||
/// let session = LiveSession(engine: engine)
|
||||
/// let win = LyrebirdWindow(title: "Lyrebird Scratch", width: 640, height: 480)
|
||||
/// win.open { LyrebirdScratchView(session: session) }
|
||||
/// ```
|
||||
///
|
||||
/// ## Threading
|
||||
///
|
||||
/// All UI work is `@MainActor`-isolated. The Run / Run Additive buttons
|
||||
/// dispatch a `Task` that awaits `LyrebirdScratchModel.run(additive:)`, which
|
||||
/// itself awaits `LiveSession.compileAndRunAsync`. The swiftc subprocess runs
|
||||
/// on a background `Task.detached`; the snippet entry then resumes on the
|
||||
/// main actor so it can touch UI-side state. Both Run buttons disable while
|
||||
/// ``LyrebirdScratchModel/isCompiling`` is `true`.
|
||||
@MainActor
|
||||
public struct LyrebirdScratchView: View {
|
||||
|
||||
@StateObject private var model: LyrebirdScratchModel
|
||||
@State private var engineTick: Int = 0
|
||||
private let engineRefresh = Timer.publish(every: 0.5, on: .main, in: .common).autoconnect()
|
||||
|
||||
/// Construct with a fresh `LyrebirdScratchModel` wrapping `session`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - session: Host live-coding session owning the audio engine. The view
|
||||
/// does not retain a reference of its own; the wrapped model does.
|
||||
/// - initialText: Seed text loaded into the editor. Defaults to the
|
||||
/// onboarding placeholder explaining the two keyboard shortcuts.
|
||||
public init(
|
||||
session: LiveSession,
|
||||
initialText: String = LyrebirdScratchModel.defaultPlaceholder
|
||||
) {
|
||||
_model = StateObject(wrappedValue: LyrebirdScratchModel(
|
||||
session: session,
|
||||
initialText: initialText
|
||||
))
|
||||
}
|
||||
|
||||
/// Construct against a pre-built model. Lets tests or alternate hosts
|
||||
/// inject a model with custom session, text, or pre-populated state.
|
||||
public init(model: LyrebirdScratchModel) {
|
||||
_model = StateObject(wrappedValue: model)
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
engineBar
|
||||
Divider()
|
||||
ScratchEditor(
|
||||
text: Binding(
|
||||
get: { model.text },
|
||||
set: { model.text = $0 }
|
||||
),
|
||||
fontSize: model.fontSize,
|
||||
wrapsLines: model.wrapsLines
|
||||
)
|
||||
.frame(minHeight: editorMinHeight)
|
||||
Divider()
|
||||
statusBar
|
||||
if !model.diagnostics.isEmpty {
|
||||
Divider()
|
||||
diagnosticsList
|
||||
}
|
||||
}
|
||||
.frame(minWidth: scratchMinWidth, minHeight: scratchMinHeight)
|
||||
.onReceive(engineRefresh) { _ in engineTick &+= 1 }
|
||||
}
|
||||
|
||||
private var engineBar: some View {
|
||||
let engine: SynthesisEngine = model.session.engine
|
||||
return HStack(spacing: toolbarSpacing) {
|
||||
Circle()
|
||||
.fill(engine.isRunning ? Color.green : Color.red)
|
||||
.frame(width: engineDotSize, height: engineDotSize)
|
||||
Text(engine.isRunning ? "engine running" : "engine stopped")
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
Spacer()
|
||||
Text("\(Int(engine.sampleRate)) Hz · \(engine.numOutputChannels) ch · CPU \(formatCPU(engine.averageCPU))")
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
Spacer().frame(width: 8)
|
||||
Text("synths: \(model.trackedSynthCount)")
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.padding(.horizontal, toolbarPadding)
|
||||
.padding(.vertical, 6)
|
||||
.id(engineTick)
|
||||
}
|
||||
|
||||
private func formatCPU(_ value: Double) -> String {
|
||||
String(format: "%.0f%%", value * 100)
|
||||
}
|
||||
|
||||
public func runSnippet(additive: Bool) {
|
||||
Task { @MainActor in
|
||||
_ = await model.run(additive: additive)
|
||||
}
|
||||
}
|
||||
|
||||
public func presentOpenPanel() {
|
||||
let panel: NSOpenPanel = NSOpenPanel()
|
||||
panel.allowedContentTypes = [.swiftSource]
|
||||
panel.allowsMultipleSelection = false
|
||||
panel.canChooseDirectories = false
|
||||
panel.message = "Open a Lyrebird snippet"
|
||||
if panel.runModal() == .OK, let url: URL = panel.url {
|
||||
do {
|
||||
try model.load(from: url)
|
||||
} catch {
|
||||
model.reportLoadError(url: url, error: error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func saveOrPromptForLocation() {
|
||||
if let url: URL = model.documentURL {
|
||||
do {
|
||||
try model.save(to: url)
|
||||
} catch {
|
||||
model.reportSaveError(url: url, error: error)
|
||||
}
|
||||
return
|
||||
}
|
||||
presentSavePanel()
|
||||
}
|
||||
|
||||
public func presentSavePanel() {
|
||||
let panel: NSSavePanel = NSSavePanel()
|
||||
panel.allowedContentTypes = [.swiftSource]
|
||||
panel.nameFieldStringValue = model.documentURL?.lastPathComponent ?? "snippet.swift"
|
||||
panel.message = "Save Lyrebird snippet"
|
||||
if panel.runModal() == .OK, let url: URL = panel.url {
|
||||
do {
|
||||
try model.save(to: url)
|
||||
} catch {
|
||||
model.reportSaveError(url: url, error: error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var statusBar: some View {
|
||||
HStack {
|
||||
Text(model.statusMessage.isEmpty ? "Ready." : model.statusMessage)
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
.lineLimit(1)
|
||||
.truncationMode(.middle)
|
||||
Spacer()
|
||||
}
|
||||
.padding(.horizontal, statusHPad)
|
||||
.padding(.vertical, statusVPad)
|
||||
}
|
||||
|
||||
private var diagnosticsList: some View {
|
||||
ScrollView {
|
||||
LazyVStack(alignment: .leading, spacing: diagnosticRowSpacing) {
|
||||
ForEach(Array(model.diagnostics.enumerated()), id: \.offset) { _, diag in
|
||||
DiagnosticRow(diagnostic: diag)
|
||||
}
|
||||
}
|
||||
.padding(diagnosticListPadding)
|
||||
}
|
||||
.frame(minHeight: diagnosticsMinHeight, maxHeight: diagnosticsMaxHeight)
|
||||
}
|
||||
|
||||
// Layout constants — all in points. Kept private; tuned to match
|
||||
// LyrebirdEngineStatusView's visual density.
|
||||
private let scratchMinWidth: CGFloat = 520
|
||||
private let scratchMinHeight: CGFloat = 420
|
||||
private let editorMinHeight: CGFloat = 240
|
||||
private let toolbarSpacing: CGFloat = 8
|
||||
private let toolbarPadding: CGFloat = 8
|
||||
private let toolbarDividerHeight: CGFloat = 18
|
||||
private let statusHPad: CGFloat = 8
|
||||
private let statusVPad: CGFloat = 4
|
||||
private let diagnosticRowSpacing: CGFloat = 2
|
||||
private let diagnosticListPadding: CGFloat = 8
|
||||
private let diagnosticsMinHeight: CGFloat = 80
|
||||
private let diagnosticsMaxHeight: CGFloat = 200
|
||||
private let engineDotSize: CGFloat = 8
|
||||
}
|
||||
|
||||
/// One row in the diagnostics list. Renders `(line:col)`, severity, and
|
||||
/// message in a compact monospaced row.
|
||||
private struct DiagnosticRow: View {
|
||||
|
||||
let diagnostic: Diagnostic
|
||||
|
||||
var body: some View {
|
||||
HStack(alignment: .firstTextBaseline, spacing: rowGutter) {
|
||||
Text(locationString)
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(minWidth: locationColumnWidth, alignment: .leading)
|
||||
Text(diagnostic.severity.rawValue)
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(color(for: diagnostic.severity))
|
||||
.frame(minWidth: severityColumnWidth, alignment: .leading)
|
||||
Text(diagnostic.message)
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.textSelection(.enabled)
|
||||
.multilineTextAlignment(.leading)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
}
|
||||
|
||||
private var locationString: String {
|
||||
if let line: Int = diagnostic.line {
|
||||
return "\(line):\(diagnostic.column)"
|
||||
}
|
||||
return "preamble:\(diagnostic.rawLine):\(diagnostic.column)"
|
||||
}
|
||||
|
||||
private func color(for severity: DiagnosticSeverity) -> Color {
|
||||
switch severity {
|
||||
case .error: return .red
|
||||
case .warning: return .orange
|
||||
case .note: return .secondary
|
||||
}
|
||||
}
|
||||
|
||||
private let rowGutter: CGFloat = 8
|
||||
private let locationColumnWidth: CGFloat = 80
|
||||
private let severityColumnWidth: CGFloat = 56
|
||||
}
|
||||
|
||||
/// `NSViewRepresentable` wrapping a vanilla `NSTextView` inside an
|
||||
/// `NSScrollView`. Monospaced 13 pt, plain text, no smart-quote / dash /
|
||||
/// auto-correct interference — matches the editor expectations of someone
|
||||
/// typing Swift code.
|
||||
private struct ScratchEditor: NSViewRepresentable {
|
||||
|
||||
@Binding var text: String
|
||||
let fontSize: CGFloat
|
||||
let wrapsLines: Bool
|
||||
|
||||
final class Coordinator: NSObject, NSTextViewDelegate {
|
||||
var parent: ScratchEditor
|
||||
init(_ parent: ScratchEditor) { self.parent = parent }
|
||||
|
||||
func textDidChange(_ notification: Notification) {
|
||||
guard let tv: NSTextView = notification.object as? NSTextView else { return }
|
||||
parent.text = tv.string
|
||||
}
|
||||
}
|
||||
|
||||
func makeCoordinator() -> Coordinator { Coordinator(self) }
|
||||
|
||||
func makeNSView(context: Context) -> NSScrollView {
|
||||
let scroll: NSScrollView = NSTextView.scrollableTextView()
|
||||
if let tv: NSTextView = scroll.documentView as? NSTextView {
|
||||
configure(tv, in: scroll, with: context.coordinator)
|
||||
}
|
||||
return scroll
|
||||
}
|
||||
|
||||
func updateNSView(_ scroll: NSScrollView, context: Context) {
|
||||
context.coordinator.parent = self
|
||||
guard let tv: NSTextView = scroll.documentView as? NSTextView else { return }
|
||||
let font: NSFont = NSFont.monospacedSystemFont(ofSize: fontSize, weight: .regular)
|
||||
let fontChanged: Bool = (tv.font?.pointSize ?? -1) != fontSize
|
||||
if fontChanged {
|
||||
tv.font = font
|
||||
}
|
||||
let paragraphStyle: NSParagraphStyle = makeParagraphStyle(for: font)
|
||||
tv.defaultParagraphStyle = paragraphStyle
|
||||
tv.typingAttributes = makeAttrs(font: font, paragraph: paragraphStyle)
|
||||
applyWrap(to: tv, in: scroll)
|
||||
if tv.string != text {
|
||||
replaceText(in: tv, with: text, font: font, paragraph: paragraphStyle)
|
||||
} else if fontChanged {
|
||||
reapplyAttrs(to: tv, font: font, paragraph: paragraphStyle)
|
||||
}
|
||||
}
|
||||
|
||||
private func makeAttrs(font: NSFont, paragraph: NSParagraphStyle) -> [NSAttributedString.Key: Any] {
|
||||
[
|
||||
.font: font,
|
||||
.foregroundColor: NSColor.labelColor,
|
||||
.paragraphStyle: paragraph,
|
||||
]
|
||||
}
|
||||
|
||||
private func makeParagraphStyle(for font: NSFont) -> NSParagraphStyle {
|
||||
let style: NSMutableParagraphStyle = NSMutableParagraphStyle()
|
||||
let spaceAdvance: CGFloat = (" " as NSString).size(withAttributes: [.font: font]).width
|
||||
let tabWidth: CGFloat = spaceAdvance * tabSpaces
|
||||
style.tabStops = []
|
||||
style.defaultTabInterval = tabWidth
|
||||
return style
|
||||
}
|
||||
|
||||
private func replaceText(in tv: NSTextView,
|
||||
with newText: String,
|
||||
font: NSFont,
|
||||
paragraph: NSParagraphStyle) {
|
||||
let attrs: [NSAttributedString.Key : Any] = makeAttrs(font: font, paragraph: paragraph)
|
||||
let attributed: NSAttributedString = NSAttributedString(string: newText, attributes: attrs)
|
||||
tv.textStorage?.setAttributedString(attributed)
|
||||
tv.typingAttributes = attrs
|
||||
}
|
||||
|
||||
private func reapplyAttrs(to tv: NSTextView,
|
||||
font: NSFont,
|
||||
paragraph: NSParagraphStyle) {
|
||||
guard let storage: NSTextStorage = tv.textStorage else { return }
|
||||
let attrs: [NSAttributedString.Key : Any] = makeAttrs(font: font, paragraph: paragraph)
|
||||
let range: NSRange = NSRange(location: 0, length: storage.length)
|
||||
storage.setAttributes(attrs, range: range)
|
||||
tv.typingAttributes = attrs
|
||||
}
|
||||
|
||||
private func applyWrap(to tv: NSTextView, in scroll: NSScrollView) {
|
||||
guard let container: NSTextContainer = tv.textContainer else { return }
|
||||
if wrapsLines {
|
||||
scroll.hasHorizontalScroller = false
|
||||
tv.isHorizontallyResizable = false
|
||||
tv.autoresizingMask = [.width]
|
||||
container.widthTracksTextView = true
|
||||
container.containerSize = NSSize(width: CGFloat.greatestFiniteMagnitude,
|
||||
height: CGFloat.greatestFiniteMagnitude)
|
||||
} else {
|
||||
scroll.hasHorizontalScroller = true
|
||||
tv.isHorizontallyResizable = true
|
||||
tv.autoresizingMask = []
|
||||
container.widthTracksTextView = false
|
||||
container.containerSize = NSSize(width: CGFloat.greatestFiniteMagnitude,
|
||||
height: CGFloat.greatestFiniteMagnitude)
|
||||
tv.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude,
|
||||
height: CGFloat.greatestFiniteMagnitude)
|
||||
}
|
||||
tv.needsDisplay = true
|
||||
}
|
||||
|
||||
private func configure(_ tv: NSTextView, in scroll: NSScrollView, with coordinator: Coordinator) {
|
||||
tv.delegate = coordinator
|
||||
let editorFont: NSFont = NSFont.monospacedSystemFont(ofSize: fontSize, weight: .regular)
|
||||
tv.font = editorFont
|
||||
tv.isRichText = false
|
||||
tv.isAutomaticQuoteSubstitutionEnabled = false
|
||||
tv.isAutomaticDashSubstitutionEnabled = false
|
||||
tv.isAutomaticTextReplacementEnabled = false
|
||||
tv.isAutomaticSpellingCorrectionEnabled = false
|
||||
tv.smartInsertDeleteEnabled = false
|
||||
tv.allowsUndo = true
|
||||
tv.usesFindBar = true
|
||||
tv.textContainerInset = NSSize(width: editorInset, height: editorInset)
|
||||
tv.drawsBackground = true
|
||||
tv.backgroundColor = .textBackgroundColor
|
||||
tv.textColor = .labelColor
|
||||
tv.insertionPointColor = .labelColor
|
||||
tv.selectedTextAttributes = [
|
||||
.backgroundColor: NSColor.selectedTextBackgroundColor,
|
||||
.foregroundColor: NSColor.selectedTextColor,
|
||||
]
|
||||
let paragraphStyle: NSParagraphStyle = makeParagraphStyle(for: editorFont)
|
||||
tv.defaultParagraphStyle = paragraphStyle
|
||||
tv.typingAttributes = makeAttrs(font: editorFont, paragraph: paragraphStyle)
|
||||
applyWrap(to: tv, in: scroll)
|
||||
replaceText(in: tv, with: text, font: editorFont, paragraph: paragraphStyle)
|
||||
}
|
||||
|
||||
private let editorInset: CGFloat = 6
|
||||
private let tabSpaces: CGFloat = 4
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,145 +0,0 @@
|
||||
// ScratchLineNumberRuler.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdUI/LiveCompile — Phase 147
|
||||
//
|
||||
// Vertical line-number gutter for `ScratchEditor`'s `NSTextView`. Installed as
|
||||
// the scroll view's `verticalRulerView` so it tracks scroll position for free.
|
||||
// Reads laid-out glyph rects from the text view's layout manager and writes one
|
||||
// 1-based line label per visible line into the ruler's bounds.
|
||||
|
||||
#if os(macOS)
|
||||
import AppKit
|
||||
|
||||
/// `NSRulerView` subclass rendering one right-aligned line number per laid-out
|
||||
/// line of the host `NSTextView`. Tracks the text view's scroll origin via the
|
||||
/// `boundsDidChangeNotification` posted by the enclosing `NSClipView` and
|
||||
/// invalidates itself on every text edit and frame change.
|
||||
final class ScratchLineNumberRuler: NSRulerView {
|
||||
|
||||
/// Re-resolved on every `draw` so the ruler picks up font / layout-manager
|
||||
/// swaps the text view performs after attachment.
|
||||
private weak var textView: NSTextView?
|
||||
|
||||
init(scrollView: NSScrollView, textView: NSTextView) {
|
||||
self.textView = textView
|
||||
super.init(scrollView: scrollView, orientation: .verticalRuler)
|
||||
self.clientView = textView
|
||||
self.ruleThickness = gutterWidth
|
||||
let center: NotificationCenter = NotificationCenter.default
|
||||
center.addObserver(self,
|
||||
selector: #selector(invalidateForChange(_:)),
|
||||
name: NSText.didChangeNotification,
|
||||
object: textView)
|
||||
center.addObserver(self,
|
||||
selector: #selector(invalidateForChange(_:)),
|
||||
name: NSView.frameDidChangeNotification,
|
||||
object: textView)
|
||||
let clipView: NSClipView = scrollView.contentView
|
||||
clipView.postsBoundsChangedNotifications = true
|
||||
center.addObserver(self,
|
||||
selector: #selector(invalidateForChange(_:)),
|
||||
name: NSView.boundsDidChangeNotification,
|
||||
object: clipView)
|
||||
}
|
||||
|
||||
required init(coder: NSCoder) {
|
||||
fatalError("ScratchLineNumberRuler does not support NSCoder init")
|
||||
}
|
||||
|
||||
deinit {
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
}
|
||||
|
||||
@objc private func invalidateForChange(_ note: Notification) {
|
||||
needsDisplay = true
|
||||
}
|
||||
|
||||
override func drawHashMarksAndLabels(in rect: NSRect) {
|
||||
guard let textView: NSTextView,
|
||||
let layoutManager: NSLayoutManager = textView.layoutManager,
|
||||
let textContainer: NSTextContainer = textView.textContainer else {
|
||||
return
|
||||
}
|
||||
|
||||
gutterFillColor.setFill()
|
||||
rect.fill()
|
||||
gutterDividerColor.setStroke()
|
||||
let dividerPath: NSBezierPath = NSBezierPath()
|
||||
let dividerX: CGFloat = bounds.maxX - dividerHalfPixel
|
||||
dividerPath.move(to: NSPoint(x: dividerX, y: rect.minY))
|
||||
dividerPath.line(to: NSPoint(x: dividerX, y: rect.maxY))
|
||||
dividerPath.lineWidth = 1
|
||||
dividerPath.stroke()
|
||||
|
||||
let nsText: NSString = textView.string as NSString
|
||||
let totalLength: Int = nsText.length
|
||||
let visibleRect: NSRect = scrollView?.contentView.bounds ?? .zero
|
||||
let glyphRange: NSRange = layoutManager.glyphRange(forBoundingRect: visibleRect, in: textContainer)
|
||||
let charRange: NSRange = layoutManager.characterRange(forGlyphRange: glyphRange, actualGlyphRange: nil)
|
||||
let inset: CGFloat = textView.textContainerInset.height
|
||||
let attrs: [NSAttributedString.Key: Any] = [
|
||||
.font: rulerFont,
|
||||
.foregroundColor: gutterTextColor,
|
||||
]
|
||||
|
||||
var lineIndex: Int = lineNumber(at: charRange.location, in: nsText)
|
||||
var cursor: Int = charRange.location
|
||||
let visibleEnd: Int = NSMaxRange(charRange)
|
||||
while cursor < visibleEnd && cursor <= totalLength {
|
||||
// `lineRange(for:)` advances cursor by the full line including its
|
||||
// terminator, so `\r`, `\n`, and `\r\n` line endings are all
|
||||
// handled by Foundation.
|
||||
let probeLength: Int = (cursor == totalLength) ? 0 : 0
|
||||
let lineRange: NSRange = nsText.lineRange(for: NSRange(location: cursor, length: probeLength))
|
||||
let lineGlyphRange: NSRange = layoutManager.glyphRange(forCharacterRange: lineRange,
|
||||
actualCharacterRange: nil)
|
||||
let usedRect: NSRect = layoutManager.boundingRect(forGlyphRange: lineGlyphRange,
|
||||
in: textContainer)
|
||||
let yInView: CGFloat = usedRect.minY + inset - visibleRect.minY
|
||||
let label: NSString = "\(lineIndex)" as NSString
|
||||
let size: CGSize = label.size(withAttributes: attrs)
|
||||
let drawPoint: NSPoint = NSPoint(
|
||||
x: bounds.maxX - size.width - rightInset,
|
||||
y: yInView + ((usedRect.height - size.height) * 0.5)
|
||||
)
|
||||
label.draw(at: drawPoint, withAttributes: attrs)
|
||||
|
||||
let advance: Int = NSMaxRange(lineRange)
|
||||
if advance <= cursor { break } // defensive — empty trailing line
|
||||
cursor = advance
|
||||
lineIndex += 1
|
||||
}
|
||||
}
|
||||
|
||||
// 1-based line number of the character at `loc`. Delegates to
|
||||
// `NSString.enumerateSubstrings(.byLines)` so CR, LF, and CRLF endings are
|
||||
// all counted correctly. Linear in `loc`, runs once per draw on the prefix
|
||||
// that precedes the first visible line.
|
||||
private func lineNumber(at loc: Int, in text: NSString) -> Int {
|
||||
if loc <= 0 { return 1 }
|
||||
var line: Int = 1
|
||||
let prefixRange: NSRange = NSRange(location: 0, length: loc)
|
||||
text.enumerateSubstrings(in: prefixRange,
|
||||
options: [.byLines, .substringNotRequired]) { _, _, _, _ in
|
||||
line += 1
|
||||
}
|
||||
return line
|
||||
}
|
||||
|
||||
private let gutterWidth: CGFloat = 40
|
||||
private let rightInset: CGFloat = 6
|
||||
private let dividerHalfPixel: CGFloat = 0.5 // crisp 1px divider on Retina
|
||||
private let rulerFontSize: CGFloat = 11
|
||||
private let gutterFillColor: NSColor = NSColor.controlBackgroundColor
|
||||
private let gutterDividerColor: NSColor = NSColor.separatorColor
|
||||
private let gutterTextColor: NSColor = NSColor.tertiaryLabelColor
|
||||
private var rulerFont: NSFont {
|
||||
NSFont.monospacedSystemFont(ofSize: rulerFontSize, weight: .regular)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -52,7 +52,7 @@ struct LiveSessionDiagnosticsTests {
|
||||
@Test
|
||||
func compilerErrorWrapsUnderlyingForNonCompileFailures() {
|
||||
// Force a non-compile error by pointing at a build dir that doesn't exist.
|
||||
// The Phase 142 compile path still succeeds (a swiftc invocation with -I
|
||||
// The compile path still succeeds (a swiftc invocation with -I
|
||||
// pointing at a missing dir surfaces as `compileFailed` via swiftc's own
|
||||
// "no such module" — not `compilerError`). Instead, drive a real
|
||||
// compilerError case by routing through a LiveCompileError that isn't
|
||||
@@ -60,7 +60,7 @@ struct LiveSessionDiagnosticsTests {
|
||||
// entrySymbolMissing — but a real run with full build dir succeeds.
|
||||
// We just verify the type LiveSessionError.compilerError exists and is
|
||||
// representable; behavioural coverage of non-compileFailed cases is
|
||||
// exercised at the LiveCompiler layer (Phase 142 tests).
|
||||
// exercised at the LiveCompiler layer.
|
||||
let err: LiveSessionError = LiveSessionError.compilerError(.swiftcNotFound)
|
||||
#expect(String(describing: err).contains("swiftc"))
|
||||
}
|
||||
|
||||
@@ -74,9 +74,9 @@ struct LiveSessionTests {
|
||||
#expect(session.lastSnippetMessage == "async hello")
|
||||
}
|
||||
|
||||
/// Phase 203 runtime guard: a snippet driven through `compileAndRunAsync` that calls
|
||||
/// Runtime guard: a snippet driven through `compileAndRunAsync` that calls
|
||||
/// `context.play(_:)` actually adds and tracks a synth. `context.play` → `engine.add` is
|
||||
/// `@MainActor` (Phase 201); `compileAndRunAsync` resumes the snippet entry on the main
|
||||
/// `@MainActor`; `compileAndRunAsync` resumes the snippet entry on the main
|
||||
/// actor (not the nonisolated executor it suspends on), so this exercises that hop.
|
||||
@Test
|
||||
func asyncCompileAndRunPlaysAndTracksSynth() async throws {
|
||||
|
||||
@@ -72,8 +72,8 @@ struct LyrebirdScratchModelTests {
|
||||
func runInvalidSnippetSurfacesUserCoordinateDiagnostics() async throws {
|
||||
let session: LiveSession = makeSession()
|
||||
// `let x: Int = "nope"` — guaranteed type-check error on the first row
|
||||
// of the user body. Phase 144 maps the wrapped-source line back to
|
||||
// user line 1.
|
||||
// of the user body. The diagnostic parser maps the wrapped-source line
|
||||
// back to user line 1.
|
||||
let model: LyrebirdScratchModel = LyrebirdScratchModel(
|
||||
session: session,
|
||||
initialText: "let x: Int = \"nope\"\n"
|
||||
|
||||
+3
@@ -19,4 +19,7 @@
|
||||
<FileRef
|
||||
location = "group:Demos/LyrebirdScratchDemo/LyrebirdScratchDemo.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Demos/LyrebirdScoreDemo/LyrebirdScoreDemo.xcodeproj">
|
||||
</FileRef>
|
||||
</Workspace>
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
# Lyrebird
|
||||
|
||||
Lyrebird is a native macOS audio synthesis framework written in Swift. Users write Swift code that implements the `Generator` and `Synthesizer` protocols against the Lyrebird engine — there is no separate scripting language. The framework handles Core Audio I/O, a pre-allocated bus memory system, and a node tree for ordering signal evaluation. The design is informed by 20+ years of SuperCollider practice, adapted to Swift idioms and a single-process architecture.
|
||||
|
||||
Development follows an interpret-then-compile workflow: sketch and perform in the Swift REPL with Lyrebird loaded, then graduate working code to a Swift Package project for compiled, optimized execution.
|
||||
|
||||
## Locked Decisions
|
||||
|
||||
| Decision | Choice |
|
||||
|---|---|
|
||||
| Implementation language | Swift |
|
||||
| Platform | macOS 15+ (requires `Synchronization.Atomic` for SPSCQueue) |
|
||||
| Swift tools version | 6.0 (required for macOS 15 platform target) |
|
||||
| Audio I/O | Direct Core Audio (`kAudioUnitSubType_HALOutput`) — no AVAudioEngine |
|
||||
| NRT rendering | `NRTDriver` — fixed-duration tight loop, `ExtAudioFile` AIFF/WAV output; event-driven stop is a stretch goal |
|
||||
| Execution model | Interpreted (REPL) → compiled (Swift Package) |
|
||||
| Bus system | Pre-allocated, SC convention (128 audio / 4096 control) |
|
||||
| Block size | Configurable at engine init |
|
||||
| Testing | Swift Testing framework — no Xcode Playgrounds |
|
||||
| REPL | Swift REPL + LineNoise |
|
||||
| Hot reload | Interpret-then-compile |
|
||||
| Inter-file modularity | Swift Package module system |
|
||||
| Package targets | `Lyrebird` (library), `LyrebirdDemo` (executable smoke test), `LyrebirdTests` (test) |
|
||||
|
||||
## SuperCollider Lineage
|
||||
|
||||
The designer has 20+ years of SC experience. SC concepts map to Lyrebird as follows:
|
||||
|
||||
| SuperCollider | Lyrebird |
|
||||
|---|---|
|
||||
| UGen | `Generator` protocol |
|
||||
| SynthDef / Synth | `Synthesizer` protocol |
|
||||
| Group | `Group` (node tree ordering) |
|
||||
| Audio/control bus | Pre-allocated bus memory |
|
||||
| `In` / `Out` UGen | `In` / `Out` generators |
|
||||
| sclang | Swift |
|
||||
| scsynth | `SynthesisEngine` |
|
||||
|
||||
## Document Index
|
||||
|
||||
| Doc | Topic |
|
||||
|---|---|
|
||||
| `docs/00-working-order.md` | Phased implementation sequence |
|
||||
| `docs/engine/synthesis-engine.md` | SynthesisEngine, Core Audio AUHAL |
|
||||
| `docs/engine/bus-system.md` | Bus memory model, In/Out |
|
||||
| `docs/engine/scheduling.md` | Sample-accurate scheduling, SPSCQueue, sub-block splitting |
|
||||
| `docs/protocols/generator.md` | Generator protocol hierarchy |
|
||||
| `docs/protocols/synthesizer.md` | Synthesizer protocol, node tree |
|
||||
| `docs/signal-flow/signal-flow.md` | DAG evaluation, block processing |
|
||||
| `docs/tooling/repl.md` | REPL, LineNoise, hot-swap |
|
||||
| `docs/tooling/project-system.md` | Swift Package model, CLI |
|
||||
| `docs/stdlib/generators.md` | Built-in generator library |
|
||||
| `docs/ui/gui-system.md` | Native SwiftUI GUI, parameter binding, control windows |
|
||||
|
||||
## Legacy Reference
|
||||
|
||||
`legacy/Lyrebird/LyrebirdSynth/Lyrebird/` — a working prototype from ~10 years ago. Good source for: `ValidGeneratorInput` protocol pattern, operator overloading approach, sine table oscillator, envelope curve math, delay interpolation. Do not copy verbatim — modernize to Swift concurrency, add Core Audio integration, expand test coverage.
|
||||
@@ -329,6 +329,7 @@ swift package --disable-sandbox preview-documentation --target Lyrebird
|
||||
| Topic | Doc |
|
||||
|---|---|
|
||||
| **Start here / demo projects** | [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md) |
|
||||
| **What's new / release notes** | [`RELEASES.md`](RELEASES.md) |
|
||||
| Engine setup and Core Audio | `docs/engine/synthesis-engine.md` |
|
||||
| Bus memory / In / Out | `docs/engine/bus-system.md` |
|
||||
| Sample-accurate scheduling | `docs/engine/scheduling.md` |
|
||||
@@ -359,6 +360,12 @@ swift package --disable-sandbox preview-documentation --target Lyrebird
|
||||
|
||||
---
|
||||
|
||||
## Release notes
|
||||
|
||||
Per-version changes are in [`RELEASES.md`](RELEASES.md). The current release
|
||||
(1.1) adds the algorithmic-composition stack: a music-theory toolkit, pattern
|
||||
library, score DSL, and MusicXML / MIDI round-trips.
|
||||
|
||||
## Contributing
|
||||
|
||||
New Generators (in-tree) and out-of-tree extension packages are both welcome — see [`CONTRIBUTING.md`](CONTRIBUTING.md).
|
||||
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
# Releases
|
||||
|
||||
Notable changes per release. Newest first.
|
||||
|
||||
This project follows semantic versioning: a minor bump (1.0 → 1.1) adds
|
||||
functionality in a backward-compatible way.
|
||||
|
||||
---
|
||||
|
||||
## 1.1 — Enhanced algorithmic composition tools
|
||||
|
||||
Release 1.1 turns Lyrebird's score side from a thin event list into a full
|
||||
**algorithmic composition and notation toolkit**: a spelling-aware music-theory
|
||||
layer, a pattern/sequence library, a composable score DSL, and lossless MusicXML
|
||||
and Standard MIDI File round-trips. The real-time synthesis engine is unchanged —
|
||||
this release is additive and language-side.
|
||||
|
||||
### Music theory toolkit
|
||||
|
||||
- Spelling-aware **`Interval`**, **`Scale`**, and **`PitchCollection`** types
|
||||
(cells, sets, 12-tone rows) built on the existing `Letter` / `Accidental` /
|
||||
`NoteName` / `Pitch` foundation.
|
||||
- Diatonic-vs-chromatic transposition that preserves enharmonic spelling
|
||||
(`B♯` stays `B♯`, never collapses to `C`), scale-degree mapping between scales,
|
||||
and conversion straight to Hz / seconds for synthesis.
|
||||
- **`Pitch.mapIntoRange(low:high:)`** — fold a pitch into a register by whole
|
||||
octaves while preserving pitch class and spelling.
|
||||
- See [`docs/stdlib/theory.md`](docs/stdlib/theory.md).
|
||||
|
||||
### Patterns
|
||||
|
||||
- `Pattern<T>` factory catalog for sequences, series, random and stochastic
|
||||
distributions (uniform, brownian, gaussian, cauchy, beta, weighted, shuffle…),
|
||||
and combinators (map, filter, stutter, switching, interleave, round-robin…).
|
||||
- **`Pattern.sequence(_:repeats:offset:)`** — start a sequence partway through
|
||||
its list via `offset`.
|
||||
- Euclidean rhythm generator.
|
||||
- See [`Sources/Lyrebird/Lyrebird.docc/RoutineTask.md`](Sources/Lyrebird/Lyrebird.docc/RoutineTask.md).
|
||||
|
||||
### Score DSL and notation
|
||||
|
||||
- A result-builder score DSL — `Score`, `Part`, `Note`, `Rest`, `Chord`,
|
||||
`Tuplet`, `Voice`, `Staff` — that flattens to sample-accurate `ScoreEvent`s and
|
||||
plays back through `ScorePlayer`.
|
||||
- Notation features: dynamics, articulations, **crescendo / diminuendo hairpins**,
|
||||
**slurs** (a `Slur { }` block plus per-note `spanners:` for shared-boundary and
|
||||
overlapping spans), authored ties, grace notes, repeats and volta endings,
|
||||
mid-piece tempo changes, key signatures and transposing parts, mid-voice clef
|
||||
changes, grand-staff `Staff` grouping, and sustain `Pedal` marks.
|
||||
- Meter: `TimeSignature` + segmented `MeterMap`, mid-piece meter changes,
|
||||
anacrusis (pickup) bars, and polymeter (per-part meter overrides).
|
||||
- `ScoreTimeline` musical addressing (`BeatPosition`) with overlap policies and
|
||||
multi-voice fills.
|
||||
- See [`Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md`](Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md).
|
||||
|
||||
### Score structure and page layout
|
||||
|
||||
- **`Section { }`** blocks group parts into sequential sections, each with its
|
||||
own local bar/beat numbering. Assembled into a `Score`, sections render
|
||||
sequentially with continuous global measure numbers and a rehearsal mark per
|
||||
section; tacet instruments are auto-filled so every staff stays bar-aligned.
|
||||
`ScorePart` gains an `id` (defaults to `name`) to match the same instrument
|
||||
across sections.
|
||||
- **`PageLayout`** sets MusicXML page defaults: page size
|
||||
(`letter` / `legal` / `tabloid` / `a4` / `a3` / custom mm), `portrait` /
|
||||
`landscape` orientation, per-side odd/even margins, and `<scaling>`. Authored
|
||||
in millimeters and converted to MusicXML tenths on export.
|
||||
- **`NoteDisplay`** per-note display overrides via a `display:` parameter on
|
||||
`Note` / `Chord`: custom notehead shape (`x`, `diamond`, `slash`, `.hidden`,
|
||||
raw `.other(_)`, …), note size (`cue` / `large`), hidden stem, and hidden
|
||||
beam.
|
||||
- **Glissandos / slides** between two notes via the spanner API
|
||||
(`.beginGlissando(_:)` / `.endGlissando`): glissando (wavy/curved) or slide
|
||||
(straight) `kind`, a line type (`solid` / `dashed` / `dotted` / `wavy`), and an
|
||||
optional text label.
|
||||
|
||||
### Import / export
|
||||
|
||||
- **MusicXML** export and import (`score-partwise` 4.0) with a spelling- and
|
||||
event-faithful round trip across the notation features above.
|
||||
- **Standard MIDI File** round-trip (`Score` ↔ SMF).
|
||||
|
||||
### API and internals
|
||||
|
||||
- `Score.timeSignature` and the `Score` initializers take a typed
|
||||
`TimeSignature` (a `(numerator, denominator)` pair converts via
|
||||
`TimeSignature(_:)`) instead of a raw tuple.
|
||||
- Internal cleanups with no API impact: the MusicXML encoder and parser were
|
||||
split from two monoliths into focused, grouped extension files, and the
|
||||
parser's per-`<note>` state was extracted into a dedicated value type.
|
||||
|
||||
> **Namespace note:** the score DSL exposes capitalized free functions
|
||||
> (`Note`, `Chord`, `Voice`, `Slur`, `Crescendo`, …). `Voice` in particular can
|
||||
> collide with same-named types from other frameworks — qualify or alias if you
|
||||
> hit an ambiguity.
|
||||
|
||||
---
|
||||
|
||||
## 1.0 — Initial release
|
||||
|
||||
First public release: the real-time synthesis engine, the `Generator` /
|
||||
`Synthesizer` protocols and standard-library generators, the Core Audio and
|
||||
non-real-time drivers, `LyrebirdUI`, the `lyrebird` CLI and project scaffolding,
|
||||
and the AUv3 plug-in support.
|
||||
@@ -1,21 +0,0 @@
|
||||
// main.swift
|
||||
// MainActorConsumer (Phase 201 regression fixture)
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
|
||||
// PHASE 201 GUARANTEE: a consumer under the MainActor-default build mode subclasses
|
||||
// `SynthesizerBase` and overrides `build()` with NO `nonisolated`, NO `@preconcurrency`,
|
||||
// NO `@MainActor`, NO `nonisolated override init`. If this stops compiling, the
|
||||
// language-side actor-isolation guarantee has regressed.
|
||||
final class ToneSynth: SynthesizerBase {
|
||||
@LiveParam var freq: Double = 440
|
||||
override func build() {
|
||||
output(bus: 0, source: OscSin.Audio(freq: $freq) * 0.2)
|
||||
}
|
||||
}
|
||||
|
||||
let synth = ToneSynth()
|
||||
print("Phase 201 regression fixture OK: \(synth)")
|
||||
@@ -82,7 +82,7 @@ open class LyrebirdAudioUnit: AUAudioUnit {
|
||||
/// Required override. Construct and return the synthesizer instance that this
|
||||
/// AU should host.
|
||||
///
|
||||
/// `@MainActor` (Phase 201): the override constructs a `@MainActor` `SynthesizerBase`
|
||||
/// `@MainActor`: the override constructs a `@MainActor` `SynthesizerBase`
|
||||
/// subclass, so the factory must be main-actor-isolated for a consumer building under
|
||||
/// the MainActor-default mode to override it with no concurrency annotations — the same
|
||||
/// rationale as `SynthesizerBase.build()`. Invoked from `init` on the host's main thread.
|
||||
@@ -443,7 +443,7 @@ open class LyrebirdAudioUnit: AUAudioUnit {
|
||||
newEngine.auOutputBusOffsets = _outputBusOffsets
|
||||
newEngine.auInputBusOffsets = _inputBusOffsets
|
||||
try newEngine.start()
|
||||
// `engine.add` is `@MainActor` (Phase 201). `allocateRenderResources()` overrides
|
||||
// `engine.add` is `@MainActor`. `allocateRenderResources()` overrides
|
||||
// `AUAudioUnit`'s nonisolated declaration, so this method cannot itself be
|
||||
// `@MainActor`. AU hosts usually call render-resource allocation on the main thread,
|
||||
// but the contract does not guarantee it — the bridge runs the add inline when on
|
||||
|
||||
@@ -9,7 +9,7 @@ import Foundation
|
||||
/// Run a `@MainActor` node-tree mutation from a language-side dispatch adapter that may
|
||||
/// execute either on the main thread or inline on a background NRT driver thread.
|
||||
///
|
||||
/// Phase 201 made the engine's add / schedule path and `Synthesizer.build`/`release`/`free`
|
||||
/// The engine's add / schedule path and `Synthesizer.build`/`release`/`free` are
|
||||
/// `@MainActor`. Most language-side adapters dispatch those mutations through
|
||||
/// `DispatchQueue.main.async`, so they already run on main. Two adapters can run a mutation
|
||||
/// **inline on the calling thread**:
|
||||
|
||||
@@ -1745,7 +1745,7 @@ public final class SynthesisEngine {
|
||||
/// All allocation and `build()`/`rebuildGraph()` happen here on the calling thread;
|
||||
/// the RT thread never allocates in `applyEvent`.
|
||||
/// `@MainActor`: invokes `build()` / `rebuildGraph()` (the `@MainActor` language-side
|
||||
/// add surface — Phase 201). The node-tree add path runs on the main thread by
|
||||
/// add surface). The node-tree add path runs on the main thread by
|
||||
/// contract (it also touches `nodeTreeMirror`, observed by SwiftUI).
|
||||
@MainActor private func prepareNode(_ synth: any Synthesizer) -> PreparedNode {
|
||||
if let base: SynthesizerBase = synth as? SynthesizerBase {
|
||||
|
||||
+2
-2
@@ -57,7 +57,7 @@ public struct LyrebirdMessageContext: @unchecked Sendable {
|
||||
let args: SynthArgs = SynthArgs(engine, synth)
|
||||
_dispatch {
|
||||
// `_dispatch` runs this on main (default `DispatchQueue.main.async`) or inline on
|
||||
// the NRT driver thread. `engine.add` is `@MainActor` (Phase 201); the bridge runs
|
||||
// the NRT driver thread. `engine.add` is `@MainActor`; the bridge runs
|
||||
// it inline when already on main and hops synchronously otherwise — never traps.
|
||||
lyrebirdRunMainActorMutation {
|
||||
do { try args.engine.add(args.synth) }
|
||||
@@ -133,7 +133,7 @@ public struct LyrebirdMessageContext: @unchecked Sendable {
|
||||
// but a warning posts to LyrebirdMessageCenter so debug builds get
|
||||
// visibility into typo'd OSC / MIDI param names that would
|
||||
// otherwise route silently to nowhere.
|
||||
// `updateParameter` is `@MainActor` (Phase 201). `_dispatch` runs this on main
|
||||
// `updateParameter` is `@MainActor`. `_dispatch` runs this on main
|
||||
// (default) or inline on the NRT driver — the bridge runs inline on main and hops
|
||||
// synchronously off-main, never trapping.
|
||||
lyrebirdRunMainActorMutation {
|
||||
|
||||
@@ -522,3 +522,8 @@ extension ConvolutionReverb.Audio {
|
||||
/// Right output channel (channel 1). Available only when IR has 2+ channels.
|
||||
public var right: ChannelSelect.Audio { self[1] }
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
|
||||
// `GeneratorEnum` conformance is intentionally omitted — this is an Audio-only
|
||||
// generator with no paired `Control` variant.
|
||||
|
||||
@@ -284,3 +284,8 @@ extension FreeVerb.Audio {
|
||||
/// Right output channel (channel 1). Equivalent to `self[1]`.
|
||||
public var right: ChannelSelect.Audio { self[1] }
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
|
||||
// `GeneratorEnum` conformance is intentionally omitted — this is an Audio-only
|
||||
// generator with no paired `Control` variant.
|
||||
|
||||
@@ -538,3 +538,8 @@ extension GVerb.Audio {
|
||||
/// Right output channel (channel 1). Equivalent to `self[1]`.
|
||||
public var right: ChannelSelect.Audio { self[1] }
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
|
||||
// `GeneratorEnum` conformance is intentionally omitted — this is an Audio-only
|
||||
// generator with no paired `Control` variant.
|
||||
|
||||
@@ -704,3 +704,8 @@ extension PlateReverb.Audio {
|
||||
/// Right output channel (channel 1). Equivalent to `self[1]`.
|
||||
public var right: ChannelSelect.Audio { self[1] }
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
|
||||
// `GeneratorEnum` conformance is intentionally omitted — this is an Audio-only
|
||||
// generator with no paired `Control` variant.
|
||||
|
||||
@@ -404,3 +404,8 @@ extension SpringReverb.Audio {
|
||||
/// Right output channel (channel 1). Only valid when `stereo: true`.
|
||||
public var right: ChannelSelect.Audio { self[1] }
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
|
||||
// `GeneratorEnum` conformance is intentionally omitted — this is an Audio-only
|
||||
// generator with no paired `Control` variant.
|
||||
|
||||
@@ -150,6 +150,10 @@ inside the range. In that case `self` is returned unchanged:
|
||||
`self` is also returned unchanged when `modulo <= 0` or `high < low`.
|
||||
RT-safe (pure scalar arithmetic, `O(1)`).
|
||||
|
||||
> Tip: ``Pitch/mapIntoRange(low:high:)`` is the spelling-aware counterpart for
|
||||
> the Score theory layer — it folds a `Pitch` into a `[low, high]` register by
|
||||
> whole octaves while preserving the note name (`B♭` stays `B♭`, never `A♯`).
|
||||
|
||||
---
|
||||
|
||||
## Tempo and Time
|
||||
|
||||
@@ -36,7 +36,7 @@ Every `Pattern<T>` variant is constructed via a static factory method on `Patter
|
||||
|
||||
| Factory | Behaviour |
|
||||
|---|---|
|
||||
| ``Pattern/sequence(_:repeats:)`` | Cycle through array `repeats` times. `-1` infinite. |
|
||||
| ``Pattern/sequence(_:repeats:offset:)`` | Cycle through array `repeats` times. `-1` infinite. `offset` shifts only the first pass — opens at `values[offset]` (wraps modulo count), runs to the array end, then later cycles run full from index 0. |
|
||||
| ``Pattern/shuffle(_:repeats:seed:)`` | Fisher-Yates permute once at init; cycle. Same permutation replays on reset. SC `Pshuf`. |
|
||||
| ``Pattern/nonRepeatingRandom(_:repeats:seed:)`` | Random pick avoiding same *index* as previous. Index-vs-value caveat for duplicate-value pools. SC `Pxrand`. |
|
||||
| ``Pattern/weightedRandom(_:weights:repeats:seed:)`` | Pick proportional to weight. Init preconditions: equal count, finite non-negative weights, positive sum. SC `Pwrand`. |
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -32,7 +32,7 @@ Optional GUI module.
|
||||
import LyrebirdUI
|
||||
```
|
||||
|
||||
Provides: `LyrebirdWindow` (AppKit/SwiftUI host), `@SynthParam` property wrapper, and pre-built slider/knob views. Builds under Swift 6 language mode (Phase 202).
|
||||
Provides: `LyrebirdWindow` (AppKit/SwiftUI host), `@SynthParam` property wrapper, and pre-built slider/knob views. Builds under Swift 6 language mode.
|
||||
|
||||
**Rule:** never import `LyrebirdUI` in `Lyrebird` — GUI code must stay in this module only.
|
||||
|
||||
@@ -49,7 +49,7 @@ lyrebird export MySynth
|
||||
lyrebird repl
|
||||
```
|
||||
|
||||
Provides an interactive `lyrebird>` shell with history and tab completion. Builds under Swift 6 language mode (Phase 202).
|
||||
Provides an interactive `lyrebird>` shell with history and tab completion. Builds under Swift 6 language mode.
|
||||
|
||||
See <doc:CLIGuide> for a full walkthrough.
|
||||
|
||||
|
||||
@@ -109,7 +109,7 @@ public final class Group: Synthesizer {
|
||||
///
|
||||
/// Language-side only — do not call from the RT thread.
|
||||
///
|
||||
/// `@MainActor` (Phase 201): the child cascade calls the `@MainActor`
|
||||
/// `@MainActor`: the child cascade calls the `@MainActor`
|
||||
/// `child.release`/`child.free`. The self-free poll timer — which runs its handler on a
|
||||
/// utility queue and therefore must NOT be main-actor-isolated — is installed by the
|
||||
/// `nonisolated` helper `_startSelfFreeTimer(engine:)` so the handler does not inherit
|
||||
@@ -161,7 +161,7 @@ public final class Group: Synthesizer {
|
||||
/// count reaches zero.
|
||||
///
|
||||
/// `nonisolated` so the `setEventHandler` closure does NOT inherit `release`'s
|
||||
/// `@MainActor` isolation (Phase 201) — a main-actor-isolated handler would trap
|
||||
/// `@MainActor` isolation — a main-actor-isolated handler would trap
|
||||
/// (`dispatch_assert_queue_fail`) when the timer fires on the utility queue. The handler
|
||||
/// touches only the atomic count off-main and hops to main (via the `@unchecked Sendable`
|
||||
/// ``GroupFreeArgs``) for the actual `free`.
|
||||
|
||||
@@ -4,24 +4,37 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Engine backing ``Pattern/sequence(_:repeats:)``.
|
||||
/// Engine backing ``Pattern/sequence(_:repeats:offset:)``.
|
||||
///
|
||||
/// Cycles through `values` in order. Each full pass increments the cycle counter.
|
||||
/// `repeats` full cycles exhaust the source; `-1` is infinite.
|
||||
///
|
||||
/// `offset` shifts only the *first* pass: emission starts at `values[offset]`
|
||||
/// and runs to the end of the array (a short opening pass), after which every
|
||||
/// later cycle runs the full array from index `0`. `reset()` returns to the
|
||||
/// offset start.
|
||||
internal final class SequencePatternEngine<T>: _PatternEngine {
|
||||
internal typealias Element = T
|
||||
|
||||
private let _values: [T]
|
||||
private let _repeats: Int
|
||||
private var _index: Int = 0
|
||||
private let _offset: Int
|
||||
private var _index: Int
|
||||
private var _cycleCount: Int = 0
|
||||
|
||||
internal init(
|
||||
values: [T],
|
||||
repeats: Int
|
||||
repeats: Int,
|
||||
offset: Int = 0
|
||||
) {
|
||||
_values = values
|
||||
_repeats = repeats
|
||||
// Normalise the offset into [0, count) so out-of-range / negative
|
||||
// offsets wrap rather than trap. Empty arrays pin to 0 (next() guards).
|
||||
let count: Int = values.count
|
||||
let normalized: Int = count > 0 ? ((offset % count) + count) % count : 0
|
||||
_offset = normalized
|
||||
_index = normalized
|
||||
}
|
||||
|
||||
internal var isExhausted: Bool {
|
||||
@@ -40,7 +53,7 @@ internal final class SequencePatternEngine<T>: _PatternEngine {
|
||||
}
|
||||
|
||||
internal func reset() {
|
||||
_index = 0
|
||||
_index = _offset
|
||||
_cycleCount = 0
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,11 +14,28 @@ public extension Pattern {
|
||||
/// increments the cycle counter. `repeats` full cycles exhaust the source;
|
||||
/// `-1` is infinite.
|
||||
///
|
||||
/// `offset` shifts only the *first* pass: emission starts at
|
||||
/// `values[offset]` and runs to the end of the array (a short opening
|
||||
/// pass), after which every later cycle runs the full array from index `0`.
|
||||
/// `Pattern.sequence([.eighth, .eighth, .quarter], offset: 1)` opens with
|
||||
/// `[.eighth, .quarter]` then loops the full list. The offset wraps
|
||||
/// (modulo `values.count`) so out-of-range or negative values are legal.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - values: Elements to cycle through. Copied at init time.
|
||||
/// - repeats: Number of full cycles before exhaustion. `-1` = infinite.
|
||||
static func sequence(_ values: [T], repeats: Int = -1) -> Pattern<T> {
|
||||
Pattern(engine: SequencePatternEngine(values: values, repeats: repeats))
|
||||
/// - offset: Starting index for the first pass only. Wraps modulo
|
||||
/// `values.count`. Defaults to `0`.
|
||||
static func sequence(
|
||||
_ values: [T],
|
||||
repeats: Int = -1,
|
||||
offset: Int = 0
|
||||
) -> Pattern<T> {
|
||||
Pattern(engine: SequencePatternEngine(
|
||||
values: values,
|
||||
repeats: repeats,
|
||||
offset: offset
|
||||
))
|
||||
}
|
||||
|
||||
/// Permutes `values` once at init via Fisher-Yates, then cycles through
|
||||
|
||||
@@ -62,7 +62,7 @@ final class ProcessRouteSynth: SynthesizerBase {
|
||||
///
|
||||
/// `nonisolated(unsafe)`: assigned in `build()` on main; the `LyrebirdProcess` watcher
|
||||
/// reads `envGen?.needsFree` (an atomic flag) from a utility-queue timer. Effectively
|
||||
/// immutable after `build()`; cross-thread read is safe (Phase 201).
|
||||
/// immutable after `build()`; cross-thread read is safe.
|
||||
nonisolated(unsafe) private(set) var envGen: EnvelopeGen.Audio?
|
||||
|
||||
init(
|
||||
@@ -180,7 +180,7 @@ final class ProcessRouteSynth: SynthesizerBase {
|
||||
/// `bus` (or to any other downstream consumer) if master amp control is wanted.
|
||||
/// - target: Where to insert this process's group in the node tree.
|
||||
/// - body: `async` closure invoked with a ``LyrebirdProcessContext``. Runs on the
|
||||
/// `@MainActor` (Phase 201) so it can construct `@MainActor` `SynthesizerBase`
|
||||
/// `@MainActor` so it can construct `@MainActor` `SynthesizerBase`
|
||||
/// subclasses and call `ctx.add(_:)` directly — no `await MainActor.run { … }`
|
||||
/// wrapping needed. `await ctx.wait(_:)` suspends without blocking the main thread.
|
||||
/// - onRelease: Optional callback invoked when ``release(reltime:)`` is
|
||||
@@ -782,7 +782,7 @@ public final class LyrebirdProcess: @unchecked Sendable {
|
||||
/// from whichever thread drops the final process reference.
|
||||
deinit {
|
||||
guard let engine: SynthesisEngine = _engine else { return }
|
||||
// `Group.free` is `@MainActor` (Phase 201) — it touches `nodeTreeMirror`. deinit is
|
||||
// `Group.free` is `@MainActor` — it touches `nodeTreeMirror`. deinit is
|
||||
// nonisolated and may run on any thread, so hop the group-free to main. The bus
|
||||
// release + DiskOut close are nonisolated and run inline. Capture locals (not self,
|
||||
// which is mid-deinit) for the async closure.
|
||||
|
||||
@@ -20,7 +20,7 @@ public protocol LyrebirdProcessFactory: Sendable {
|
||||
/// Each call should return an independent process — callers may
|
||||
/// invoke this repeatedly to spawn distinct concurrent processes.
|
||||
///
|
||||
/// `@MainActor` (Phase 201): conformers typically construct `@MainActor`
|
||||
/// `@MainActor`: conformers typically construct `@MainActor`
|
||||
/// `SynthesizerBase` subclasses here, so the factory method is main-actor-isolated.
|
||||
/// The protocol stays `Sendable` (factories are stored / passed across actors); only
|
||||
/// the build step is pinned to main.
|
||||
|
||||
@@ -40,23 +40,23 @@ public enum Articulation: Hashable, Sendable {
|
||||
// MARK: - Performance scaling constants
|
||||
|
||||
/// Duration multiplier for ``staccato``.
|
||||
public static let staccatoDurationScale: Double = 0.5
|
||||
static let staccatoDurationScale: Double = 0.5
|
||||
|
||||
/// Duration multiplier for ``staccatissimo``.
|
||||
public static let staccatissimoDurationScale: Double = 0.25
|
||||
static let staccatissimoDurationScale: Double = 0.25
|
||||
|
||||
/// Duration multiplier for ``legato`` — slight overlap into the next note.
|
||||
/// Players that don't tolerate overlap should clamp to `1.0`.
|
||||
public static let legatoDurationScale: Double = 1.05
|
||||
static let legatoDurationScale: Double = 1.05
|
||||
|
||||
/// Duration multiplier for ``marcato``.
|
||||
public static let marcatoDurationScale: Double = 0.85
|
||||
static let marcatoDurationScale: Double = 0.85
|
||||
|
||||
/// Velocity bonus added by ``accent``.
|
||||
public static let accentVelocityBonus: Double = 0.15
|
||||
static let accentVelocityBonus: Double = 0.15
|
||||
|
||||
/// Velocity bonus added by ``marcato``.
|
||||
public static let marcatoVelocityBonus: Double = 0.25
|
||||
static let marcatoVelocityBonus: Double = 0.25
|
||||
|
||||
// MARK: - Performance scaling
|
||||
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
// BarlineStyle.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Visual style of a measure's **right** barline, independent of repeat
|
||||
/// structure.
|
||||
///
|
||||
/// Used to mark a section boundary (`.double`), the end of a movement or piece
|
||||
/// (`.final`), or any of the other notation-standard barline glyphs. Set per
|
||||
/// section via ``Section(_:meterMap:keySignature:tempoChanges:repeats:endBarline:parts:)``
|
||||
/// (recorded at the section's last global measure), or directly on a flat score
|
||||
/// via ``Score/measureBarlines``.
|
||||
///
|
||||
/// ## Precedence vs repeats
|
||||
///
|
||||
/// When a measure also carries a **backward repeat** (`:|`), the repeat's
|
||||
/// `light-heavy` barline wins and the section style is suppressed — a repeat
|
||||
/// barline is already a heavy barline and stacking a second bar-style produces
|
||||
/// invalid notation. A `BarlineStyle` therefore only renders when no
|
||||
/// backward-repeat / ending-stop barline already occupies the same right barline.
|
||||
///
|
||||
/// ## Round-trip
|
||||
///
|
||||
/// Like rehearsal marks, barline styles are **emit-only** — they are written to
|
||||
/// MusicXML but are not reconstructed when a score is decoded from MusicXML.
|
||||
///
|
||||
/// Each case maps to a MusicXML 4.0 `<bar-style>` value via ``musicXMLBarStyle``.
|
||||
public enum BarlineStyle: String, Sendable, Equatable, CaseIterable {
|
||||
|
||||
/// A normal thin barline (`<bar-style>regular</bar-style>`). Rarely needed
|
||||
/// explicitly — it is the default barline drawn between measures.
|
||||
case regular
|
||||
|
||||
/// A thin double barline (`light-light`). The conventional section divider.
|
||||
case double
|
||||
|
||||
/// A thin-then-thick final barline (`light-heavy`). Marks the end of a
|
||||
/// movement or the whole piece.
|
||||
case final
|
||||
|
||||
/// A single thick barline (`heavy`).
|
||||
case heavy
|
||||
|
||||
/// A dashed barline (`dashed`).
|
||||
case dashed
|
||||
|
||||
/// A dotted barline (`dotted`).
|
||||
case dotted
|
||||
|
||||
/// A short barline crossing only the middle staff lines (`tick`).
|
||||
case tick
|
||||
|
||||
/// A short barline crossing the middle two staff spaces (`short`).
|
||||
case short
|
||||
|
||||
/// An invisible (suppressed) barline (`none`).
|
||||
case invisible
|
||||
|
||||
/// The MusicXML 4.0 `<bar-style>` token for this style.
|
||||
public var musicXMLBarStyle: String {
|
||||
switch self {
|
||||
case .regular: return "regular"
|
||||
case .double: return "light-light"
|
||||
case .final: return "light-heavy"
|
||||
case .heavy: return "heavy"
|
||||
case .dashed: return "dashed"
|
||||
case .dotted: return "dotted"
|
||||
case .tick: return "tick"
|
||||
case .short: return "short"
|
||||
case .invisible: return "none"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
// BeatPosition.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// A musician-friendly position on a part timeline, resolved against a
|
||||
/// ``MeterMap`` to an absolute quarter-note beat (the engine's one true unit,
|
||||
/// see ``ScoreEvent/beat``).
|
||||
///
|
||||
/// **`beat` means the felt beat you conduct** — the felt beat defined by the
|
||||
/// signature's ``TimeSignature/beatGrouping``. This keeps `beat` consistent
|
||||
/// across meters: beat 1 is always the downbeat, beat 2 the next conducted beat.
|
||||
/// In `4/4` the beat is the quarter; in compound `6/8` `[3,3]` the beat is the
|
||||
/// dotted-quarter (two beats per bar); in additive `3+3+2` the three beats are
|
||||
/// dotted-quarter, dotted-quarter, quarter. For the finer notated note-value
|
||||
/// (the eighth in `6/8`) use `division`, the less-common granular addressing.
|
||||
///
|
||||
/// Addressing surfaces (all 1-based except `.quarters`):
|
||||
///
|
||||
/// - ``quarters(_:)-(Double)`` / ``quarters(_:)-(Fraction)`` — absolute 0-based
|
||||
/// quarter beats, meter-free. `Fraction` form is exact (triplet positions).
|
||||
/// - ``beat(_:)`` — flat 1-based felt beat, counted continuously across bars
|
||||
/// (constant initial meter, anacrusis-free). In `4/4`, beat 5 → quarter 4; in
|
||||
/// `6/8`, beat 3 → quarter 3 (bar-2 downbeat). The `from((1.0,…),(5.0,…))`
|
||||
/// reading.
|
||||
/// - ``bar(_:beat:)`` — 1-based bar + 1-based felt beat (via `beatGrouping`),
|
||||
/// fully meter-aware (per-bar signature + anacrusis). Fractional beats
|
||||
/// interpolate within the beat.
|
||||
/// - ``bar(_:division:)`` — 1-based bar + 1-based denominator-note division. In
|
||||
/// `6/8`, `bar 1, division 4` is the 4th eighth. The granular escape hatch.
|
||||
///
|
||||
/// Anacrusis (``MeterMap/anacrusis``): for `.bar(...)`, quarter `0` is the pickup
|
||||
/// start, bar `1` is the first full measure (so `.bar(1, beat: 1)` resolves to
|
||||
/// `anacrusis`); address pickup beats with `bar: 0`. Flat `.beat` ignores the
|
||||
/// anacrusis.
|
||||
public struct BeatPosition: Sendable, Hashable {
|
||||
|
||||
enum Kind: Sendable, Hashable {
|
||||
case quarters(Fraction)
|
||||
case beat(Fraction)
|
||||
case barBeat(bar: Int, beat: Fraction)
|
||||
case barDivision(bar: Int, division: Fraction)
|
||||
}
|
||||
|
||||
let kind: Kind
|
||||
|
||||
// MARK: - Factories
|
||||
|
||||
/// Absolute 0-based quarter beats (meter-free). Quantized to
|
||||
/// ``Fraction/beatApproxDenominator``.
|
||||
public static func quarters(_ q: Double) -> BeatPosition {
|
||||
BeatPosition(kind: .quarters(fractionFromBeats(q)))
|
||||
}
|
||||
|
||||
/// Absolute 0-based quarter beats as an exact ``Fraction`` (meter-free).
|
||||
/// Use for triplet / rational positions that must not round.
|
||||
public static func quarters(_ q: Fraction) -> BeatPosition {
|
||||
BeatPosition(kind: .quarters(q))
|
||||
}
|
||||
|
||||
/// Flat 1-based felt beat, counted continuously across bars (constant initial
|
||||
/// meter, anacrusis-free). `beat(1)` is the start; `beat(5)` in `4/4` is
|
||||
/// quarter `4`; `beat(3)` in `6/8` is quarter `3`.
|
||||
public static func beat(_ b: Double) -> BeatPosition {
|
||||
BeatPosition(kind: .beat(fractionFromBeats(b)))
|
||||
}
|
||||
|
||||
/// 1-based bar + 1-based felt beat (via ``TimeSignature/beatGrouping``),
|
||||
/// fully meter-aware. `bar: 0` addresses the pickup. Fractional beats
|
||||
/// interpolate within the beat; the integer part must be in
|
||||
/// `[1, beatsPerBar]` (out-of-range traps).
|
||||
public static func bar(_ bar: Int, beat: Double) -> BeatPosition {
|
||||
BeatPosition(kind: .barBeat(bar: bar, beat: fractionFromBeats(beat)))
|
||||
}
|
||||
|
||||
/// 1-based bar + 1-based denominator-note division (the granular notated
|
||||
/// note-value). In `6/8`, `division 4` is the 4th eighth. `bar: 0` addresses
|
||||
/// the pickup.
|
||||
public static func bar(_ bar: Int, division: Double) -> BeatPosition {
|
||||
BeatPosition(kind: .barDivision(bar: bar, division: fractionFromBeats(division)))
|
||||
}
|
||||
|
||||
// MARK: - Resolution
|
||||
|
||||
/// Resolve to an absolute quarter-note beat against a meter map.
|
||||
///
|
||||
/// - Parameter meterMap: The governing meter map (provides per-bar signatures,
|
||||
/// bar offsets, and the anacrusis).
|
||||
/// - Returns: Absolute quarter beats (may be negative for malformed input —
|
||||
/// callers should reject negatives).
|
||||
public func resolve(in meterMap: MeterMap) -> Fraction {
|
||||
let oneBeat: Fraction = .one
|
||||
switch kind {
|
||||
case .quarters(let q):
|
||||
return q
|
||||
|
||||
case .beat(let b):
|
||||
// Flat felt beat: wrap continuously across bars of the initial
|
||||
// signature, anacrusis-free.
|
||||
let ts: TimeSignature = meterMap.initial
|
||||
let beatsPerBar: Int = ts.beatsPerBar
|
||||
let bValue: Double = b.double
|
||||
let integerBeat: Int = Int(bValue.rounded(.down))
|
||||
precondition(integerBeat >= 1, "BeatPosition: beat must be >= 1, got \(bValue)")
|
||||
let barIndex: Int = (integerBeat - 1) / beatsPerBar
|
||||
let beatInBar: Int = (integerBeat - 1) % beatsPerBar
|
||||
let frac: Double = bValue - Double(integerBeat)
|
||||
let barStart: Fraction = Fraction(barIndex, 1) * ts.measureQuarters
|
||||
let beatArg: Fraction = fractionFromBeats(Double(beatInBar + 1) + frac)
|
||||
return barStart + BeatPosition.beatOffset(beatArg, in: ts)
|
||||
|
||||
case .barBeat(let bar, let beat):
|
||||
let ts: TimeSignature = meterMap.timeSignature(atBar: bar)
|
||||
return meterMap.barStartQuarters(bar) + BeatPosition.beatOffset(beat, in: ts)
|
||||
|
||||
case .barDivision(let bar, let division):
|
||||
let ts: TimeSignature = meterMap.timeSignature(atBar: bar)
|
||||
let unit: Fraction = ts.divisionQuarters
|
||||
return meterMap.barStartQuarters(bar) + (division - oneBeat) * unit
|
||||
}
|
||||
}
|
||||
|
||||
/// Quarter-beat offset of a (possibly fractional, 1-based) felt beat within a
|
||||
/// bar of the given signature.
|
||||
///
|
||||
/// - Precondition: the integer part of `beat` is in `[1, beatsPerBar]`. A
|
||||
/// beat outside that range (e.g. `beat 3` in a 2-beat `6/8`, or `beat 0`)
|
||||
/// is a placement error and traps rather than silently snapping to a wrong
|
||||
/// beat. A fractional beat interpolates within its felt beat; `N.f` for the
|
||||
/// last beat stays inside the bar.
|
||||
private static func beatOffset(
|
||||
_ beat: Fraction,
|
||||
in ts: TimeSignature
|
||||
) -> Fraction {
|
||||
let beatValue: Double = beat.double
|
||||
let floored: Int = Int(beatValue.rounded(.down))
|
||||
let lastBeatIndex: Int = ts.beatsPerBar
|
||||
precondition(
|
||||
floored >= 1 && floored <= lastBeatIndex,
|
||||
"BeatPosition: beat \(beatValue) out of range [1, \(lastBeatIndex)] for \(ts.numerator)/\(ts.denominator)"
|
||||
)
|
||||
let onset: Fraction = ts.beatOnsetsQuarters[floored - 1]
|
||||
let frac: Double = beatValue - Double(floored)
|
||||
if frac <= 0 {
|
||||
return onset
|
||||
}
|
||||
// Interpolate within the felt beat by its quarter length.
|
||||
return onset + fractionFromBeats(frac) * ts.beatLengthsQuarters[floored - 1]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
// Clef.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// The clef assigned to a ``ScorePart`` for MusicXML encoding and display.
|
||||
///
|
||||
/// ### Cases
|
||||
///
|
||||
/// - ``treble`` — G clef on line 2. Standard treble staff. Use for soprano, alto,
|
||||
/// violin, flute, piano right hand, etc.
|
||||
/// - ``bass`` — F clef on line 4. Standard bass staff. Use for bass, cello, tuba,
|
||||
/// piano left hand (low range), etc.
|
||||
/// - ``alto`` — C clef on line 3. Alto clef. Use for viola.
|
||||
/// - ``tenor`` — C clef on line 4. Tenor clef. Use for cello (upper register),
|
||||
/// trombone (upper register), bassoon (upper register).
|
||||
/// - ``treble8vb`` — G clef on line 2 with `clef-octave-change -1`. Octave-transposing
|
||||
/// treble clef sounding an octave lower than written. Use for tenor voice, guitar.
|
||||
/// - ``percussion`` — Percussion clef (no line). Use for unpitched percussion parts.
|
||||
/// - ``auto`` — Infer the appropriate clef from the part's pitch content at encode time.
|
||||
/// Resolves to `.treble` or `.bass` based on the median MIDI pitch of the part's
|
||||
/// pitched events (median < ``autoBassThresholdMidi`` → `.bass`, else → `.treble`).
|
||||
/// `.auto` is the default for the ``Part(_:channel:clef:elements:)`` DSL constructor.
|
||||
public enum Clef: Sendable, Hashable {
|
||||
|
||||
/// G clef, line 2.
|
||||
case treble
|
||||
|
||||
/// F clef, line 4.
|
||||
case bass
|
||||
|
||||
/// C clef, line 3 (viola).
|
||||
case alto
|
||||
|
||||
/// C clef, line 4 (tenor voice / cello upper register).
|
||||
case tenor
|
||||
|
||||
/// G clef, line 2, `clef-octave-change -1` (tenor voice, guitar).
|
||||
case treble8vb
|
||||
|
||||
/// Percussion clef (no line). For unpitched percussion parts.
|
||||
case percussion
|
||||
|
||||
/// Infer treble or bass from the part's pitch range at encode time.
|
||||
///
|
||||
/// At ``Score/toMusicXMLString(divisions:)`` time the median MIDI pitch of the
|
||||
/// part's non-rest pitched notes is computed. If the median is below
|
||||
/// ``autoBassThresholdMidi`` (57 — A3), `.bass` is chosen; otherwise `.treble`.
|
||||
/// If the part has no pitched notes, `.treble` is chosen.
|
||||
case auto
|
||||
|
||||
// MARK: - Auto-inference threshold
|
||||
|
||||
/// MIDI note number (A3 = 57) below which the `.auto` case resolves to `.bass`.
|
||||
///
|
||||
/// The value 57 (A3) sits midway between the bass-clef sweet spot (D2–E4) and
|
||||
/// the treble-clef sweet spot (F3–A5); it maps to the lowest note of an alto
|
||||
/// voice and is a natural dividing point.
|
||||
public static let autoBassThresholdMidi: Int = 57
|
||||
|
||||
// MARK: - MusicXML mapping
|
||||
|
||||
/// The MusicXML `<clef>` children for this clef case.
|
||||
///
|
||||
/// Returns `(sign:, line:, octaveChange:)`.
|
||||
/// - `sign`: MusicXML `<sign>` text (`"G"`, `"F"`, `"C"`, `"percussion"`).
|
||||
/// - `line`: MusicXML `<line>` integer, or `nil` when the element must be omitted
|
||||
/// (e.g. percussion).
|
||||
/// - `octaveChange`: MusicXML `<clef-octave-change>` integer, or `nil` when
|
||||
/// the element must be omitted.
|
||||
///
|
||||
/// - Precondition: Do not call on `.auto`; resolve it first via
|
||||
/// ``inferred(forMedianMidi:)``.
|
||||
public var musicXMLClef: (sign: String, line: Int?, octaveChange: Int?) {
|
||||
switch self {
|
||||
case .treble:
|
||||
return (sign: "G", line: 2, octaveChange: nil)
|
||||
case .bass:
|
||||
return (sign: "F", line: 4, octaveChange: nil)
|
||||
case .alto:
|
||||
return (sign: "C", line: 3, octaveChange: nil)
|
||||
case .tenor:
|
||||
return (sign: "C", line: 4, octaveChange: nil)
|
||||
case .treble8vb:
|
||||
return (sign: "G", line: 2, octaveChange: -1)
|
||||
case .percussion:
|
||||
return (sign: "percussion", line: nil, octaveChange: nil)
|
||||
case .auto:
|
||||
// Defensive fallback — callers should resolve .auto before calling
|
||||
// this property. Return treble so output is always valid XML.
|
||||
return (sign: "G", line: 2, octaveChange: nil)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Auto-inference
|
||||
|
||||
/// Return the appropriate concrete clef for a part given its median MIDI pitch.
|
||||
///
|
||||
/// - Parameter median: The median MIDI note number of the part's non-rest pitched
|
||||
/// events, or `nil` / absent when the part contains no pitched events.
|
||||
/// - Values below ``autoBassThresholdMidi`` (57) return `.bass`.
|
||||
/// - Values at or above the threshold return `.treble`.
|
||||
/// - `nil` (empty / rest-only part) returns `.treble`.
|
||||
/// - Returns: `.treble` or `.bass` — never `.auto` or any other case.
|
||||
public static func inferred(forMedianMidi median: Int?) -> Clef {
|
||||
guard let m: Int = median else { return .treble }
|
||||
return m < Clef.autoBassThresholdMidi ? .bass : .treble
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,14 @@ public enum Dynamic: Hashable, Sendable {
|
||||
case ff
|
||||
case fff
|
||||
|
||||
/// No sound — velocity zero, printed as `n` in MusicXML.
|
||||
///
|
||||
/// Use `.niente` at the start or end of a crescendo/diminuendo (al niente /
|
||||
/// dal niente) or as the initial/final point of a ``dynamicCurve:`` to indicate
|
||||
/// silence at that position. The `<n/>` MusicXML child element is the
|
||||
/// standard MusicXML 4.0 representation.
|
||||
case niente
|
||||
|
||||
/// Escape hatch — caller-supplied normalized `[0, 1]` velocity. The value
|
||||
/// is clamped to `[0, 1]` when ``velocity`` is read.
|
||||
case raw(Double)
|
||||
@@ -37,12 +45,12 @@ public enum Dynamic: Hashable, Sendable {
|
||||
public static let fffVelocity: Double = 1.00
|
||||
|
||||
/// Maximum MIDI velocity, used by ``midiVelocity``.
|
||||
public static let midiMaxVelocity: Double = Double(Pitch.maxMidiNote)
|
||||
static let midiMaxVelocity: Double = Double(Pitch.maxMidiNote)
|
||||
|
||||
// MARK: - Conversion
|
||||
|
||||
/// Normalized velocity in `[0, 1]`. `mf` anchored at `0.6` and `f` at
|
||||
/// `0.85`. ``raw(_:)`` values are clamped to `[0, 1]`.
|
||||
/// `0.85`. ``raw(_:)`` values are clamped to `[0, 1]`. ``niente`` returns `0.0`.
|
||||
public var velocity: Double {
|
||||
switch self {
|
||||
case .ppp: return Dynamic.pppVelocity
|
||||
@@ -53,6 +61,7 @@ public enum Dynamic: Hashable, Sendable {
|
||||
case .f: return Dynamic.fVelocity
|
||||
case .ff: return Dynamic.ffVelocity
|
||||
case .fff: return Dynamic.fffVelocity
|
||||
case .niente: return 0.0
|
||||
case .raw(let v): return max(0.0, min(1.0, v))
|
||||
}
|
||||
}
|
||||
@@ -63,4 +72,44 @@ public enum Dynamic: Hashable, Sendable {
|
||||
UInt8(min(Dynamic.midiMaxVelocity,
|
||||
max(0.0, (velocity * Dynamic.midiMaxVelocity).rounded())))
|
||||
}
|
||||
|
||||
// MARK: - MusicXML mapping
|
||||
|
||||
/// The standard MusicXML `<dynamics>` child element name for this dynamic.
|
||||
///
|
||||
/// Named cases map to the nine standard MusicXML element names (`"ppp"` …
|
||||
/// `"fff"` plus `"n"` for ``niente``). ``raw(_:)`` returns `nil` — the
|
||||
/// caller must use `<other-dynamics>` with the raw value text.
|
||||
public var musicXMLDynamic: String? {
|
||||
switch self {
|
||||
case .ppp: return "ppp"
|
||||
case .pp: return "pp"
|
||||
case .p: return "p"
|
||||
case .mp: return "mp"
|
||||
case .mf: return "mf"
|
||||
case .f: return "f"
|
||||
case .ff: return "ff"
|
||||
case .fff: return "fff"
|
||||
case .niente: return "n"
|
||||
case .raw: return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Inverse of ``musicXMLDynamic``: map a standard MusicXML dynamics element
|
||||
/// name to the corresponding ``Dynamic`` case. Returns `nil` for any name
|
||||
/// that is not one of the nine standard names.
|
||||
public static func fromMusicXMLName(_ name: String) -> Dynamic? {
|
||||
switch name {
|
||||
case "ppp": return .ppp
|
||||
case "pp": return .pp
|
||||
case "p": return .p
|
||||
case "mp": return .mp
|
||||
case "mf": return .mf
|
||||
case "f": return .f
|
||||
case "ff": return .ff
|
||||
case "fff": return .fff
|
||||
case "n": return .niente
|
||||
default: return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
// Ending.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// A volta (1st/2nd/…) ending bracket that spans one or more measures.
|
||||
///
|
||||
/// Endings are score-level structural annotations used with a ``RepeatStructure``
|
||||
/// to describe which measures belong to each volta bracket. They are
|
||||
/// **notation-only** — ``ScorePart/flatten()`` is unaffected and does not
|
||||
/// unfold repeats for playback (future work).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - number: Volta number, starting at 1. A 1st ending uses `number: 1`, a
|
||||
/// 2nd ending uses `number: 2`, and so on.
|
||||
/// - startMeasure: 1-based measure number where the ending bracket begins (inclusive).
|
||||
/// - stopMeasure: 1-based measure number where the ending bracket ends (inclusive).
|
||||
/// Must be `>= startMeasure`.
|
||||
public struct Ending: Sendable, Hashable {
|
||||
|
||||
/// Volta number (1, 2, …). Must be >= 1.
|
||||
public let number: Int
|
||||
|
||||
/// 1-based measure number where the ending bracket starts (inclusive).
|
||||
public let startMeasure: Int
|
||||
|
||||
/// 1-based measure number where the ending bracket stops (inclusive).
|
||||
public let stopMeasure: Int
|
||||
|
||||
/// Create a volta ending bracket.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - number: Volta number, starting at 1. Precondition: `>= 1`.
|
||||
/// - startMeasure: 1-based measure number where the bracket begins. Precondition: `>= 1`.
|
||||
/// - stopMeasure: 1-based measure number where the bracket ends (inclusive).
|
||||
/// Precondition: `>= startMeasure`.
|
||||
public init(number: Int, startMeasure: Int, stopMeasure: Int) {
|
||||
precondition(number >= 1, "Ending: number must be >= 1, got \(number)")
|
||||
precondition(startMeasure >= 1, "Ending: startMeasure must be >= 1, got \(startMeasure)")
|
||||
precondition(
|
||||
stopMeasure >= startMeasure,
|
||||
"Ending: stopMeasure (\(stopMeasure)) must be >= startMeasure (\(startMeasure))"
|
||||
)
|
||||
self.number = number
|
||||
self.startMeasure = startMeasure
|
||||
self.stopMeasure = stopMeasure
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
// FermataShape.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// The shape of a fermata symbol, corresponding to MusicXML 4.0 fermata shape values.
|
||||
///
|
||||
/// Use as the associated value of ``NotationMark/fermata(_:)``.
|
||||
///
|
||||
/// Common shorthands:
|
||||
/// - "Long fermata" = `.square`
|
||||
/// - "Very long / longa fermata" = `.doubleSquare`
|
||||
///
|
||||
/// > Note: ``NotationMark`` is emit-only — ``Score/fromMusicXML(data:)`` does not
|
||||
/// > parse fermata shapes back into `NotationMark` values.
|
||||
public enum FermataShape: Hashable, Sendable {
|
||||
|
||||
/// Standard curved fermata (the most common kind). MusicXML `<fermata/>`.
|
||||
case normal
|
||||
|
||||
/// Pointed / angled fermata. MusicXML body text: `angled`.
|
||||
case angled
|
||||
|
||||
/// Square fermata — the conventional "long fermata". MusicXML body text: `square`.
|
||||
case square
|
||||
|
||||
/// Double angled fermata. MusicXML body text: `double-angled`.
|
||||
case doubleAngled
|
||||
|
||||
/// Double square fermata — the conventional "very long / longa fermata".
|
||||
/// MusicXML body text: `double-square`.
|
||||
case doubleSquare
|
||||
|
||||
/// Double dot fermata. MusicXML body text: `double-dot`.
|
||||
case doubleDot
|
||||
|
||||
/// Half-curve fermata. MusicXML body text: `half-curve`.
|
||||
case halfCurve
|
||||
|
||||
/// Curlew fermata. MusicXML body text: `curlew`.
|
||||
case curlew
|
||||
|
||||
/// The MusicXML body text for shapes other than `.normal`.
|
||||
/// Returns `nil` for `.normal` (which emits as self-closing `<fermata/>`).
|
||||
var musicXMLBodyText: String? {
|
||||
switch self {
|
||||
case .normal: return nil
|
||||
case .angled: return "angled"
|
||||
case .square: return "square"
|
||||
case .doubleAngled: return "double-angled"
|
||||
case .doubleSquare: return "double-square"
|
||||
case .doubleDot: return "double-dot"
|
||||
case .halfCurve: return "half-curve"
|
||||
case .curlew: return "curlew"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -68,6 +68,13 @@ public struct Fraction: Hashable, Equatable, Sendable {
|
||||
/// `1/1`.
|
||||
public static let one: Fraction = Fraction(num: 1, den: 1)
|
||||
|
||||
/// Denominator used to quantize a `Double` beat value into an exact
|
||||
/// ``Fraction`` (`2^20`). The single source of truth for the score system's
|
||||
/// `.beats(Double)` → ``Fraction`` re-encoding — referenced by `ScorePart`,
|
||||
/// the MusicXML parser, and the rest-fill helpers. Practical exact range
|
||||
/// (paired with the ``<(_:_:)`` cross-product overflow note) is ~8 000 beats.
|
||||
static let beatApproxDenominator: Int64 = 1 << 20
|
||||
|
||||
// MARK: - Arithmetic
|
||||
|
||||
/// `a/b + c/d = (ad + bc) / bd`, reduced.
|
||||
@@ -109,6 +116,11 @@ public struct Fraction: Hashable, Equatable, Sendable {
|
||||
lhs + Fraction(num: -rhs.num, den: rhs.den)
|
||||
}
|
||||
|
||||
/// In-place subtraction.
|
||||
public static func -= (lhs: inout Fraction, rhs: Fraction) {
|
||||
lhs = lhs - rhs
|
||||
}
|
||||
|
||||
// MARK: - Comparison
|
||||
|
||||
/// Compares cross-products of the two fractions in `Int64`.
|
||||
@@ -156,3 +168,10 @@ public struct Fraction: Hashable, Equatable, Sendable {
|
||||
// MARK: - Comparable conformance
|
||||
|
||||
extension Fraction: Comparable {}
|
||||
|
||||
// MARK: - AdditiveArithmetic conformance
|
||||
|
||||
/// `Fraction` is an exact additive-arithmetic type: it has `+`, `-`, `+=`, `-=`,
|
||||
/// and ``zero``. The conformance lets generic algorithms (e.g. the score
|
||||
/// rest-fill helper) operate uniformly over `Fraction` and `Double` cursors.
|
||||
extension Fraction: AdditiveArithmetic {}
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
// Glissando.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// A descriptor for a glissando or slide span between two notes.
|
||||
///
|
||||
/// `Glissando` is attached to a note via the ``Spanner/beginGlissando(_:)``
|
||||
/// case on the START note of the span. The stop note carries
|
||||
/// ``Spanner/endGlissando``.
|
||||
///
|
||||
/// ```swift
|
||||
/// // Wavy glissando with default settings — G5 slides to C6:
|
||||
/// Note(.g, 5, dur: .quarter, spanners: [.beginGlissando(Glissando())])
|
||||
/// Note(.c, 6, dur: .quarter, spanners: [.endGlissando])
|
||||
///
|
||||
/// // Measured slide with explicit text label:
|
||||
/// Note(.c, 5, dur: .quarter,
|
||||
/// spanners: [.beginGlissando(Glissando(kind: .slide, lineType: .solid, text: "slide"))])
|
||||
/// Note(.e, 5, dur: .quarter, spanners: [.endGlissando])
|
||||
/// ```
|
||||
///
|
||||
/// ## MusicXML output
|
||||
///
|
||||
/// On the start note, inside `<notations>`:
|
||||
/// ```xml
|
||||
/// <glissando type="start" line-type="wavy" number="1"/>
|
||||
/// <!-- or, when text is present: -->
|
||||
/// <glissando type="start" line-type="wavy" number="1">gliss.</glissando>
|
||||
/// ```
|
||||
///
|
||||
/// On the stop note, inside `<notations>`:
|
||||
/// ```xml
|
||||
/// <glissando type="stop" number="1"/>
|
||||
/// ```
|
||||
///
|
||||
/// `.slide` kind emits `<slide>` instead of `<glissando>`.
|
||||
///
|
||||
/// ## Decode note
|
||||
///
|
||||
/// `<glissando>` and `<slide>` elements from an imported MusicXML file are
|
||||
/// **not** currently parsed back into ``Glissando`` spanners. This is an
|
||||
/// emit-only feature.
|
||||
public struct Glissando: Sendable, Hashable {
|
||||
|
||||
/// Whether to emit `<glissando>` (wavy/curved, unmeasured) or `<slide>`
|
||||
/// (straight, measured portamento).
|
||||
///
|
||||
/// Defaults to `.glissando`.
|
||||
public var kind: GlissandoKind
|
||||
|
||||
/// The visual line style for the glissando span.
|
||||
///
|
||||
/// Corresponds to the `line-type` attribute in MusicXML. Defaults to
|
||||
/// `.wavy`, the conventional style for an unmeasured glissando.
|
||||
public var lineType: GlissandoLineType
|
||||
|
||||
/// Optional text label emitted as element body text on the start note,
|
||||
/// e.g. `"gliss."`.
|
||||
///
|
||||
/// When non-nil the start element is written in the non-self-closing form:
|
||||
/// `<glissando …>gliss.</glissando>`. When `nil` the self-closing form is
|
||||
/// used: `<glissando …/>`. Defaults to `nil`.
|
||||
public var text: String?
|
||||
|
||||
/// Create a `Glissando` descriptor.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - kind: ``GlissandoKind/glissando`` (wavy, unmeasured) or
|
||||
/// ``GlissandoKind/slide`` (straight, measured). Defaults to
|
||||
/// `.glissando`.
|
||||
/// - lineType: Visual line style. Defaults to `.wavy`.
|
||||
/// - text: Optional label emitted as element content on the start note
|
||||
/// (e.g. `"gliss."`). Defaults to `nil`.
|
||||
public init(
|
||||
kind: GlissandoKind = .glissando,
|
||||
lineType: GlissandoLineType = .wavy,
|
||||
text: String? = nil
|
||||
) {
|
||||
self.kind = kind
|
||||
self.lineType = lineType
|
||||
self.text = text
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// GlissandoKind.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// The kind of glissando notation span.
|
||||
///
|
||||
/// MusicXML provides two distinct glissando elements, both placed inside
|
||||
/// `<notations>` with `type="start"` on the first note and `type="stop"` on
|
||||
/// the second:
|
||||
///
|
||||
/// | `GlissandoKind` | MusicXML element |
|
||||
/// |---|---|
|
||||
/// | `.glissando` | `<glissando>` — wavy or curved, unmeasured portamento |
|
||||
/// | `.slide` | `<slide>` — straight line, measured (portamento) |
|
||||
///
|
||||
/// Choose `.glissando` for an approximate or unmeasured pitch sweep (typically
|
||||
/// drawn with a wavy or curved line). Choose `.slide` for a precisely measured
|
||||
/// portamento (typically drawn with a straight line).
|
||||
///
|
||||
/// ## Decode note
|
||||
///
|
||||
/// `<glissando>` and `<slide>` elements from an imported MusicXML file are
|
||||
/// **not** currently parsed back into ``Glissando`` spanners. This is an
|
||||
/// emit-only feature.
|
||||
public enum GlissandoKind: Sendable, Hashable {
|
||||
/// A wavy or curved, unmeasured pitch sweep between two notes.
|
||||
///
|
||||
/// Maps to `<glissando>` in MusicXML.
|
||||
case glissando
|
||||
|
||||
/// A straight-line, measured portamento between two notes.
|
||||
///
|
||||
/// Maps to `<slide>` in MusicXML.
|
||||
case slide
|
||||
|
||||
/// The MusicXML element name for this glissando kind.
|
||||
///
|
||||
/// `"glissando"` for `.glissando`; `"slide"` for `.slide`.
|
||||
public var musicXMLElementName: String {
|
||||
switch self {
|
||||
case .glissando: return "glissando"
|
||||
case .slide: return "slide"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// GlissandoLineType.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// The visual line style for a glissando or slide span.
|
||||
///
|
||||
/// Corresponds to the MusicXML `line-type` attribute on `<glissando>` and
|
||||
/// `<slide>` elements.
|
||||
///
|
||||
/// | `GlissandoLineType` | `line-type` attribute |
|
||||
/// |---|---|
|
||||
/// | `.solid` | `"solid"` |
|
||||
/// | `.dashed` | `"dashed"` |
|
||||
/// | `.dotted` | `"dotted"` |
|
||||
/// | `.wavy` | `"wavy"` |
|
||||
///
|
||||
/// The default for a ``Glissando`` is `.wavy`, which is the conventional
|
||||
/// notation for an unmeasured glissando. Use `.solid` for a measured slide.
|
||||
///
|
||||
/// ## Decode note
|
||||
///
|
||||
/// `line-type` attributes from an imported MusicXML file are **not** currently
|
||||
/// parsed back into ``GlissandoLineType`` values. This is an emit-only feature.
|
||||
public enum GlissandoLineType: Sendable, Hashable {
|
||||
/// A continuous, unbroken line.
|
||||
case solid
|
||||
/// A dashed line.
|
||||
case dashed
|
||||
/// A dotted line.
|
||||
case dotted
|
||||
/// A wavy line — the conventional notation for an unmeasured glissando.
|
||||
case wavy
|
||||
|
||||
/// The MusicXML `line-type` attribute value for this line style.
|
||||
public var musicXMLValue: String {
|
||||
switch self {
|
||||
case .solid: return "solid"
|
||||
case .dashed: return "dashed"
|
||||
case .dotted: return "dotted"
|
||||
case .wavy: return "wavy"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
// KeySignature.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// A Western tonal key signature expressed as a circle-of-fifths position and mode.
|
||||
///
|
||||
/// The ``fifths`` value follows the MusicXML 4.0 `<fifths>` convention:
|
||||
///
|
||||
/// - `0` — C major / A minor (no accidentals)
|
||||
/// - Positive — sharps: `+1` = G major / E minor (one sharp), `+2` = D major, …, `+7` = C♯ major
|
||||
/// - Negative — flats: `-1` = F major / D minor (one flat), `-2` = B♭ major, …, `-7` = C♭ major
|
||||
///
|
||||
/// Use the named static-let constants (e.g. `.gMajor`, `.aMinor`) rather than the raw
|
||||
/// `fifths:` integer wherever possible — they document intent at the call site.
|
||||
///
|
||||
/// ```swift
|
||||
/// let score = Score(bpm: 120, timeSignature: TimeSignature(4, 4), keySignature: .gMajor)
|
||||
/// ```
|
||||
///
|
||||
/// `KeySignature` is score-level: the same key signature is emitted in every part's
|
||||
/// measure-1 `<attributes>` block. Per-part transposing keys are not supported in
|
||||
/// this release.
|
||||
///
|
||||
/// ## MusicXML round-trip
|
||||
///
|
||||
/// ``Score/toMusicXMLString(divisions:)`` emits `<key><fifths>N</fifths><mode>major|minor</mode></key>`
|
||||
/// after `<divisions>` and before `<time>` in measure 1 of every part.
|
||||
/// ``Score/fromMusicXML(data:)`` reads `<fifths>` and `<mode>` from the FIRST `<key>`
|
||||
/// encountered in the document and restores the ``KeySignature`` on the parsed ``Score``.
|
||||
/// Documents without a `<key>` element default to `.cMajor` (fifths 0, major).
|
||||
public struct KeySignature: Hashable, Sendable {
|
||||
|
||||
/// Tonal mode: major or minor.
|
||||
public enum Mode: String, Hashable, Sendable {
|
||||
case major
|
||||
case minor
|
||||
}
|
||||
|
||||
/// Circle-of-fifths position. `0` = C major / A minor; positive = sharps; negative = flats.
|
||||
/// Range: `−7…+7` (enforced by the initialiser precondition).
|
||||
public let fifths: Int
|
||||
|
||||
/// Tonal mode (major or minor).
|
||||
public let mode: Mode
|
||||
|
||||
/// Create a `KeySignature` from a raw circle-of-fifths value and mode.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - fifths: Circle-of-fifths position. Must be in `−7...7`.
|
||||
/// `0` = C major / A minor, `+N` = N sharps, `−N` = N flats.
|
||||
/// - mode: `.major` (default) or `.minor`.
|
||||
public init(
|
||||
fifths: Int,
|
||||
mode: Mode = .major
|
||||
) {
|
||||
precondition(
|
||||
(-7...7).contains(fifths),
|
||||
"KeySignature: fifths must be in -7...7, got \(fifths)"
|
||||
)
|
||||
self.fifths = fifths
|
||||
self.mode = mode
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Major key statics
|
||||
|
||||
extension KeySignature {
|
||||
|
||||
// Sharp major keys (0 to +7)
|
||||
/// C major — no accidentals.
|
||||
public static let cMajor: KeySignature = KeySignature(fifths: 0, mode: .major)
|
||||
/// G major — 1 sharp (F♯).
|
||||
public static let gMajor: KeySignature = KeySignature(fifths: 1, mode: .major)
|
||||
/// D major — 2 sharps.
|
||||
public static let dMajor: KeySignature = KeySignature(fifths: 2, mode: .major)
|
||||
/// A major — 3 sharps.
|
||||
public static let aMajor: KeySignature = KeySignature(fifths: 3, mode: .major)
|
||||
/// E major — 4 sharps.
|
||||
public static let eMajor: KeySignature = KeySignature(fifths: 4, mode: .major)
|
||||
/// B major — 5 sharps.
|
||||
public static let bMajor: KeySignature = KeySignature(fifths: 5, mode: .major)
|
||||
/// F♯ major — 6 sharps.
|
||||
public static let fSharpMajor: KeySignature = KeySignature(fifths: 6, mode: .major)
|
||||
/// C♯ major — 7 sharps.
|
||||
public static let cSharpMajor: KeySignature = KeySignature(fifths: 7, mode: .major)
|
||||
|
||||
// Flat major keys (-1 to -7)
|
||||
/// F major — 1 flat (B♭).
|
||||
public static let fMajor: KeySignature = KeySignature(fifths: -1, mode: .major)
|
||||
/// B♭ major — 2 flats.
|
||||
public static let bFlatMajor: KeySignature = KeySignature(fifths: -2, mode: .major)
|
||||
/// E♭ major — 3 flats.
|
||||
public static let eFlatMajor: KeySignature = KeySignature(fifths: -3, mode: .major)
|
||||
/// A♭ major — 4 flats.
|
||||
public static let aFlatMajor: KeySignature = KeySignature(fifths: -4, mode: .major)
|
||||
/// D♭ major — 5 flats.
|
||||
public static let dFlatMajor: KeySignature = KeySignature(fifths: -5, mode: .major)
|
||||
/// G♭ major — 6 flats.
|
||||
public static let gFlatMajor: KeySignature = KeySignature(fifths: -6, mode: .major)
|
||||
/// C♭ major — 7 flats.
|
||||
public static let cFlatMajor: KeySignature = KeySignature(fifths: -7, mode: .major)
|
||||
}
|
||||
|
||||
// MARK: - Minor key statics
|
||||
|
||||
extension KeySignature {
|
||||
|
||||
// Sharp minor keys (0 to +7)
|
||||
/// A minor — no accidentals.
|
||||
public static let aMinor: KeySignature = KeySignature(fifths: 0, mode: .minor)
|
||||
/// E minor — 1 sharp.
|
||||
public static let eMinor: KeySignature = KeySignature(fifths: 1, mode: .minor)
|
||||
/// B minor — 2 sharps.
|
||||
public static let bMinor: KeySignature = KeySignature(fifths: 2, mode: .minor)
|
||||
/// F♯ minor — 3 sharps.
|
||||
public static let fSharpMinor: KeySignature = KeySignature(fifths: 3, mode: .minor)
|
||||
/// C♯ minor — 4 sharps.
|
||||
public static let cSharpMinor: KeySignature = KeySignature(fifths: 4, mode: .minor)
|
||||
/// G♯ minor — 5 sharps.
|
||||
public static let gSharpMinor: KeySignature = KeySignature(fifths: 5, mode: .minor)
|
||||
/// D♯ minor — 6 sharps.
|
||||
public static let dSharpMinor: KeySignature = KeySignature(fifths: 6, mode: .minor)
|
||||
/// A♯ minor — 7 sharps.
|
||||
public static let aSharpMinor: KeySignature = KeySignature(fifths: 7, mode: .minor)
|
||||
|
||||
// Flat minor keys (-1 to -7)
|
||||
/// D minor — 1 flat.
|
||||
public static let dMinor: KeySignature = KeySignature(fifths: -1, mode: .minor)
|
||||
/// G minor — 2 flats.
|
||||
public static let gMinor: KeySignature = KeySignature(fifths: -2, mode: .minor)
|
||||
/// C minor — 3 flats.
|
||||
public static let cMinor: KeySignature = KeySignature(fifths: -3, mode: .minor)
|
||||
/// F minor — 4 flats.
|
||||
public static let fMinor: KeySignature = KeySignature(fifths: -4, mode: .minor)
|
||||
/// B♭ minor — 5 flats.
|
||||
public static let bFlatMinor: KeySignature = KeySignature(fifths: -5, mode: .minor)
|
||||
/// E♭ minor — 6 flats.
|
||||
public static let eFlatMinor: KeySignature = KeySignature(fifths: -6, mode: .minor)
|
||||
/// A♭ minor — 7 flats.
|
||||
public static let aFlatMinor: KeySignature = KeySignature(fifths: -7, mode: .minor)
|
||||
}
|
||||
@@ -116,7 +116,7 @@ extension MIDIFile {
|
||||
|
||||
return Score(
|
||||
bpm: bpm,
|
||||
timeSignature: timeSignature,
|
||||
timeSignature: TimeSignature(timeSignature),
|
||||
parts: parts
|
||||
)
|
||||
}
|
||||
@@ -294,22 +294,32 @@ extension MIDIFile {
|
||||
private static func elementsFromScoreEvents(
|
||||
_ events: [ScoreEvent]
|
||||
) -> [ScoreElement] {
|
||||
var elements: [ScoreElement] = []
|
||||
var cursor: Double = 0.0
|
||||
let sorted: [ScoreEvent] = events.sorted { $0.beat < $1.beat }
|
||||
for event: ScoreEvent in sorted {
|
||||
if event.beat > cursor {
|
||||
elements.append(.rest(duration: .beats(event.beat - cursor)))
|
||||
}
|
||||
elements.append(.note(
|
||||
event.pitch,
|
||||
duration: .beats(event.duration),
|
||||
dynamic: .raw(event.velocity),
|
||||
articulation: event.articulation,
|
||||
voice: event.voice
|
||||
))
|
||||
cursor = event.beat + event.duration
|
||||
let pairs: [(position: Double, element: ScoreElement)] = sorted.map { event in
|
||||
(
|
||||
position: event.beat,
|
||||
element: ScoreElement.note(
|
||||
event.pitch,
|
||||
duration: .beats(event.duration),
|
||||
dynamic: .raw(event.velocity),
|
||||
articulation: event.articulation,
|
||||
voice: event.voice,
|
||||
tie: false
|
||||
)
|
||||
)
|
||||
}
|
||||
return elements
|
||||
// Shared gap-fill in Double space (preserves `.beats` representation).
|
||||
// onOverlap is a no-op to keep the documented lossy monophonic behavior
|
||||
// for overlapping SMF input — overlaps are not rejected here.
|
||||
return fillRests(
|
||||
sorted: pairs,
|
||||
duration: { element in
|
||||
if case .note(_, let dur, _, _, _, _) = element { return dur.beats }
|
||||
if case .rest(let dur) = element { return dur.beats }
|
||||
return 0.0
|
||||
},
|
||||
makeRest: { gap in .rest(duration: .beats(gap)) },
|
||||
onOverlap: { _, _, _ in }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
// MeterMap.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// A segmented map of ``TimeSignature`` over bars, plus an optional anacrusis.
|
||||
///
|
||||
/// A meter map governs barline placement and beat addressing for a whole
|
||||
/// ``Score`` (``Score/meterMap``) or, when a part overrides polymetrically, a
|
||||
/// whole ``ScorePart`` (``ScorePart/meterMap``). A part override is
|
||||
/// **all-or-nothing**: a part either inherits the score map entirely (`nil`) or
|
||||
/// supplies its own *complete* map — it can never patch a single segment of the
|
||||
/// score map.
|
||||
///
|
||||
/// Segments are 1-based by ``Segment/startBar``; the first segment must start at
|
||||
/// bar 1, and segments are stored sorted. The signature governing any bar is the
|
||||
/// last segment whose `startBar <= bar`.
|
||||
///
|
||||
/// ## Anacrusis (pickup)
|
||||
///
|
||||
/// ``anacrusis`` is the length of an incomplete pickup measure, in quarter-note
|
||||
/// beats. Absolute quarter `0.0` is the start of the pickup; the first full
|
||||
/// barline falls at `anacrusis` quarters. The pickup is **bar 0** (engraved
|
||||
/// `implicit="yes"`); **bar 1** is the first complete measure. Existing 1-based
|
||||
/// measure references (``TempoChange``, ``Ending``) continue to mean bar `>= 1`
|
||||
/// (the pickup is excluded).
|
||||
///
|
||||
/// The MusicXML encoder renders the full map: a fresh `<time>` at each mid-piece
|
||||
/// change, per-measure capacity, the anacrusis as an implicit pickup measure, and
|
||||
/// per-part polymeter overrides. Round-trip reads meter score-globally (from the
|
||||
/// first part), so per-part overrides do not survive ``Score/fromMusicXML(data:)``.
|
||||
public struct MeterMap: Sendable, Hashable {
|
||||
|
||||
/// One `(startBar, TimeSignature)` segment of a meter map.
|
||||
public struct Segment: Sendable, Hashable {
|
||||
|
||||
/// 1-based bar at which this signature takes effect (`>= 1`).
|
||||
public let startBar: Int
|
||||
|
||||
/// The signature in force from ``startBar`` until the next segment.
|
||||
public let timeSignature: TimeSignature
|
||||
|
||||
/// - Parameters:
|
||||
/// - startBar: 1-based bar where this signature begins (`>= 1`).
|
||||
/// - timeSignature: The signature taking effect at `startBar`.
|
||||
public init(
|
||||
startBar: Int,
|
||||
_ timeSignature: TimeSignature
|
||||
) {
|
||||
precondition(startBar >= 1, "MeterMap.Segment: startBar must be >= 1, got \(startBar)")
|
||||
self.startBar = startBar
|
||||
self.timeSignature = timeSignature
|
||||
}
|
||||
}
|
||||
|
||||
/// Segments sorted by ``Segment/startBar``; the first starts at bar 1, and
|
||||
/// no two segments share a `startBar`.
|
||||
public let segments: [Segment]
|
||||
|
||||
/// Pickup length in quarter-note beats. `0` (the default) means no pickup.
|
||||
public let anacrusis: Fraction
|
||||
|
||||
// MARK: - Construction
|
||||
|
||||
/// Designated initializer.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - segments: One or more segments. Sorted internally; the earliest must
|
||||
/// start at bar 1, and `startBar` values must be unique.
|
||||
/// - anacrusis: Pickup length in quarter-note beats (`>= 0`). Defaults to `0`.
|
||||
public init(
|
||||
segments: [Segment],
|
||||
anacrusis: Fraction = .zero
|
||||
) {
|
||||
precondition(!segments.isEmpty, "MeterMap: requires at least one segment")
|
||||
let sorted: [Segment] = segments.sorted { $0.startBar < $1.startBar }
|
||||
precondition(
|
||||
sorted[0].startBar == 1,
|
||||
"MeterMap: the first segment must start at bar 1, got \(sorted[0].startBar)"
|
||||
)
|
||||
var previousBar: Int = 0
|
||||
for segment: Segment in sorted {
|
||||
precondition(
|
||||
segment.startBar != previousBar,
|
||||
"MeterMap: duplicate startBar \(segment.startBar)"
|
||||
)
|
||||
previousBar = segment.startBar
|
||||
}
|
||||
precondition(anacrusis >= .zero, "MeterMap: anacrusis must be >= 0, got \(anacrusis.double)")
|
||||
self.segments = sorted
|
||||
self.anacrusis = anacrusis
|
||||
}
|
||||
|
||||
/// Convenience initializer for a single constant meter across the whole piece.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - timeSignature: The constant signature.
|
||||
/// - anacrusis: Pickup length in quarter-note beats (`>= 0`). Defaults to `0`.
|
||||
public init(
|
||||
_ timeSignature: TimeSignature,
|
||||
anacrusis: Fraction = .zero
|
||||
) {
|
||||
self.init(
|
||||
segments: [Segment(startBar: 1, timeSignature)],
|
||||
anacrusis: anacrusis
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Lookup
|
||||
|
||||
/// The signature governing a given 1-based bar — the last segment whose
|
||||
/// `startBar <= bar`. For `bar < 1` (e.g. the pickup, bar 0) returns
|
||||
/// ``initial``.
|
||||
///
|
||||
/// - Parameter bar: 1-based bar number (or `0` for the pickup).
|
||||
/// - Returns: The ``TimeSignature`` in force at that bar.
|
||||
public func timeSignature(atBar bar: Int) -> TimeSignature {
|
||||
// Segments are sorted ascending by startBar; the governing signature is
|
||||
// the last whose startBar <= bar. Scan from the end and stop at the first
|
||||
// match (falls back to the bar-1 signature for bar < 1, e.g. the pickup).
|
||||
for segment: Segment in segments.reversed() where segment.startBar <= bar {
|
||||
return segment.timeSignature
|
||||
}
|
||||
return segments[0].timeSignature
|
||||
}
|
||||
|
||||
/// Absolute quarter-beat at which a given 1-based bar begins.
|
||||
///
|
||||
/// Bar 1 begins at ``anacrusis`` (after the pickup); each later bar adds the
|
||||
/// ``TimeSignature/measureQuarters`` capacity of the bars before it (honoring
|
||||
/// mid-piece meter changes). Bar `<= 0` (the pickup) begins at quarter `0`.
|
||||
///
|
||||
/// - Parameter bar: 1-based bar number (or `0`/negative for the pickup).
|
||||
/// - Returns: The bar's start offset in quarter beats.
|
||||
public func barStartQuarters(_ bar: Int) -> Fraction {
|
||||
if bar <= 0 { return .zero }
|
||||
var acc: Fraction = anacrusis
|
||||
var k: Int = 1
|
||||
while k < bar {
|
||||
acc = acc + timeSignature(atBar: k).measureQuarters
|
||||
k += 1
|
||||
}
|
||||
return acc
|
||||
}
|
||||
|
||||
/// The bar-1 signature.
|
||||
public var initial: TimeSignature {
|
||||
segments[0].timeSignature
|
||||
}
|
||||
|
||||
/// `true` when the map holds a single segment (one signature for the whole
|
||||
/// piece).
|
||||
public var isConstant: Bool {
|
||||
segments.count == 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,378 @@
|
||||
// MusicXMLParser+Build.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
extension _MusicXMLParser {
|
||||
func parsedScore() throws -> Score {
|
||||
if let err: MusicXMLError = rootError { throw err }
|
||||
|
||||
// Build the RepeatStructure from accumulated barline data.
|
||||
let sortedEndings: [Ending] = parsedEndings.sorted { $0.startMeasure < $1.startMeasure }
|
||||
let repeatStructure: RepeatStructure
|
||||
if parsedForwardRepeatMeasures.isEmpty
|
||||
&& parsedBackwardRepeatMeasures.isEmpty
|
||||
&& sortedEndings.isEmpty
|
||||
{
|
||||
repeatStructure = .none
|
||||
} else {
|
||||
repeatStructure = RepeatStructure(
|
||||
forwardRepeatMeasures: parsedForwardRepeatMeasures,
|
||||
backwardRepeatMeasures: parsedBackwardRepeatMeasures,
|
||||
endings: sortedEndings
|
||||
)
|
||||
}
|
||||
|
||||
// Build sorted, deduplicated TempoChange array from the
|
||||
// measure→bpm map collected from the first part. Excludes measure 1
|
||||
// (that is Score.bpm). Sorted ascending by measure number so callers
|
||||
// get a predictable ordering.
|
||||
let sortedTempoChanges: [TempoChange] = parsedTempoChangesByMeasure
|
||||
.filter { $0.key >= 2 }
|
||||
.sorted { $0.key < $1.key }
|
||||
.map { TempoChange(measure: $0.key, bpm: $0.value) }
|
||||
|
||||
// Compute the anacrusis from the pickup cursor if an implicit
|
||||
// first measure was detected. `pickupCursorDivisionsAtEnd` is 0 for
|
||||
// documents without a pickup (the default Fraction.zero path).
|
||||
let resolvedAnacrusis: Fraction = {
|
||||
guard firstMeasureIsImplicit && pickupCursorDivisionsAtEnd > 0 else {
|
||||
return .zero
|
||||
}
|
||||
let divisor: Int = pickupDivisions > 0 ? pickupDivisions : _MusicXMLParser.defaultDivisions
|
||||
return Fraction(
|
||||
num: Int64(pickupCursorDivisionsAtEnd),
|
||||
den: Int64(divisor)
|
||||
)
|
||||
}()
|
||||
|
||||
// Build a MeterMap from the per-measure <time> records.
|
||||
//
|
||||
// If no <time> was parsed at all, fall back to the default 4/4 constant map.
|
||||
// If only one <time> was parsed (constant meter), produce a single-segment
|
||||
// map so the Score round-trips byte-identical to the constant-meter behaviour.
|
||||
// For multiple <time> blocks (mid-piece meter changes):
|
||||
// 1. Sort segments by bar number.
|
||||
// 2. Guarantee a bar-1 segment (prepend if the lowest key > 1 using the
|
||||
// back-compat timeSignature tuple so the initial signature is preserved).
|
||||
// 3. Deduplicate consecutive segments with an equal TimeSignature (spurious
|
||||
// repeated identical <time> elements should not create extra segments).
|
||||
//
|
||||
// The `anacrusis` field is carried through from `resolvedAnacrusis`.
|
||||
// For documents without a pickup it is Fraction.zero — MeterMap defaults to .zero
|
||||
// so no-anacrusis output is byte-identical.
|
||||
let parsedMeterMap: MeterMap = {
|
||||
if parsedMeterByMeasure.isEmpty {
|
||||
return MeterMap(TimeSignature(timeSignature), anacrusis: resolvedAnacrusis)
|
||||
}
|
||||
// Sort by measure number.
|
||||
let sortedPairs: [(Int, TimeSignature)] = parsedMeterByMeasure
|
||||
.sorted { $0.key < $1.key }
|
||||
.map { ($0.key, $0.value) }
|
||||
// Guarantee a bar-1 segment.
|
||||
var pairs: [(Int, TimeSignature)] = sortedPairs
|
||||
if pairs[0].0 > 1 {
|
||||
pairs.insert((1, TimeSignature(timeSignature)), at: 0)
|
||||
}
|
||||
// Deduplicate consecutive identical TimeSignature values.
|
||||
var deduped: [(Int, TimeSignature)] = []
|
||||
for pair: (Int, TimeSignature) in pairs {
|
||||
if let last: (Int, TimeSignature) = deduped.last, last.1 == pair.1 {
|
||||
// Same signature as the previous kept segment — skip.
|
||||
continue
|
||||
}
|
||||
deduped.append(pair)
|
||||
}
|
||||
// Build MeterMap.Segment array.
|
||||
let segments: [MeterMap.Segment] = deduped.map { bar, ts in
|
||||
MeterMap.Segment(startBar: bar, ts)
|
||||
}
|
||||
return MeterMap(segments: segments, anacrusis: resolvedAnacrusis)
|
||||
}()
|
||||
|
||||
guard !parts.isEmpty else {
|
||||
// Tolerate empty documents — produce an empty Score rather
|
||||
// than throwing, so very-minimal MusicXML still parses.
|
||||
return Score(
|
||||
bpm: bpm,
|
||||
meterMap: parsedMeterMap,
|
||||
keySignature: keySignature,
|
||||
repeats: repeatStructure,
|
||||
tempoChanges: sortedTempoChanges,
|
||||
parts: []
|
||||
)
|
||||
}
|
||||
|
||||
// The score-level key is the FIRST part's parsed key (first-wins,
|
||||
// consistent with the single-key behaviour). Per-part key overrides are set when
|
||||
// a part's key DIFFERS from the first part's key. Parts matching the first
|
||||
// part's key get nil overrides so non-transposing scores round-trip byte-identical
|
||||
// at the model level (no spurious overrides are created).
|
||||
let firstPartKey: KeySignature = parts[0].keySignature ?? keySignature
|
||||
// Update the score-level key to the first part's parsed key (if any), so
|
||||
// the Score carries the same key as the global parser's `keySignature` field
|
||||
// (which is set from the first `<key>` element document-wide — this is the
|
||||
// same value but we re-derive it here for clarity).
|
||||
let resolvedScoreKey: KeySignature = firstPartKey
|
||||
|
||||
let scoreParts: [ScorePart] = parts.map { builder in
|
||||
// A per-part key override is set only when this part's key DIFFERS from the
|
||||
// first part's key. Matching parts (or parts with no parsed key) get nil.
|
||||
let partKey: KeySignature? = {
|
||||
guard let pk: KeySignature = builder.keySignature else { return nil }
|
||||
return pk != resolvedScoreKey ? pk : nil
|
||||
}()
|
||||
return ScorePart(
|
||||
name: builder.name,
|
||||
channel: 0,
|
||||
clef: builder.clef,
|
||||
keySignature: partKey,
|
||||
transpose: builder.transpose,
|
||||
elements: _MusicXMLParser.reconstructElements(from: builder.entries)
|
||||
)
|
||||
}
|
||||
return Score(
|
||||
bpm: bpm,
|
||||
meterMap: parsedMeterMap,
|
||||
keySignature: resolvedScoreKey,
|
||||
repeats: repeatStructure,
|
||||
tempoChanges: sortedTempoChanges,
|
||||
parts: scoreParts
|
||||
)
|
||||
}
|
||||
|
||||
/// Reconstruct a flat `[ScoreElement]` from beat-stamped entries.
|
||||
///
|
||||
/// Single-voice parts (all entries share the same voice number, or the
|
||||
/// entries are already in the legacy flat sequential order where voice numbers
|
||||
/// don't require partitioning) return the elements in document order —
|
||||
/// exactly the same list as the legacy single-voice parser produced.
|
||||
///
|
||||
/// Multi-voice parts group entries by voice number, sort each voice's
|
||||
/// entries by absolute beat, reconstruct them with inter-event rests to
|
||||
/// fill gaps, and wrap each voice in a `.voice(n, [...])` case. The part
|
||||
/// then contains exactly one `.voice` element per distinct voice number.
|
||||
///
|
||||
/// **Single-voice invariant**: if only one voice is present the result is
|
||||
/// byte-identical to the legacy single-voice flat element list (no `.voice`
|
||||
/// wrapper, no structural change).
|
||||
static func reconstructElements(from entries: [_PartEntry]) -> [ScoreElement] {
|
||||
guard !entries.isEmpty else { return [] }
|
||||
|
||||
// Determine distinct voices.
|
||||
var voiceSet: Set<Int> = Set<Int>()
|
||||
for entry: _PartEntry in entries {
|
||||
voiceSet.insert(entry.voice)
|
||||
}
|
||||
|
||||
// SINGLE-VOICE FAST PATH: return elements in document order — identical
|
||||
// to the legacy single-voice output, no structural change.
|
||||
// Wrap any wedge spans present in the entries.
|
||||
if voiceSet.count <= 1 {
|
||||
let rawElements: [ScoreElement] = entries.map { $0.element }
|
||||
return wrapWedgeSpans(in: rawElements, from: entries)
|
||||
}
|
||||
|
||||
// MULTI-VOICE PATH: partition entries by voice, sort each partition by
|
||||
// absolute beat, fill gaps with rests, and wrap in `.voice(n, [...])`.
|
||||
let sortedVoices: [Int] = voiceSet.sorted()
|
||||
var result: [ScoreElement] = []
|
||||
|
||||
for voice: Int in sortedVoices {
|
||||
let voiceEntries: [_PartEntry] = entries
|
||||
.filter { $0.voice == voice }
|
||||
.sorted { lhs, rhs in
|
||||
if lhs.beat != rhs.beat { return lhs.beat < rhs.beat }
|
||||
// Tie-break at equal beat: zero-duration notational marks
|
||||
// (clef changes, grace notes) sort before the sounding note
|
||||
// they precede, so an inline clef change renders ahead of its
|
||||
// following note rather than after it. Two zero-duration marks
|
||||
// at the same beat compare equal both ways and keep document
|
||||
// order — relies on `sorted` being stable (guaranteed since
|
||||
// Swift 5).
|
||||
let lhsZero: Bool = elementDuration(lhs.element) == .zero
|
||||
let rhsZero: Bool = elementDuration(rhs.element) == .zero
|
||||
return lhsZero && !rhsZero
|
||||
}
|
||||
|
||||
// Build the element list for this voice, inserting rests for beat
|
||||
// gaps via the shared rest-fill helper. `voiceEntries` is pre-sorted
|
||||
// (with the zero-duration tiebreak above). The transform zeroes the
|
||||
// voice field on each element so `_flatten` uses the Voice block's
|
||||
// voiceFallback rather than the 0-based pendingChordVoice field.
|
||||
// onOverlap is a no-op: a MusicXML voice is monophonic by
|
||||
// construction, so overlaps don't arise here.
|
||||
let voiceElements: [ScoreElement] = fillRests(
|
||||
sorted: voiceEntries.map { (position: $0.beat, element: $0.element) },
|
||||
duration: { elementDuration($0) },
|
||||
makeRest: { .rest(duration: .fraction($0)) },
|
||||
onOverlap: { _, _, _ in },
|
||||
transform: { zeroVoice($0) }
|
||||
)
|
||||
|
||||
// Wrap wedge spans within this voice's element list.
|
||||
let wrappedVoiceElements: [ScoreElement] = wrapWedgeSpans(
|
||||
in: voiceElements,
|
||||
from: voiceEntries
|
||||
)
|
||||
result.append(.voice(voice, wrappedVoiceElements))
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
/// Wrap runs of elements identified by wedge-start / wedge-stop annotations
|
||||
/// in the corresponding `_PartEntry` list into `.wedge(kind, [...])` wrappers.
|
||||
///
|
||||
/// ## Algorithm
|
||||
///
|
||||
/// Scans the `entries` array for `wedgeStart` / `wedgeStop` markers. For each
|
||||
/// non-overlapping span `[startIdx, stopIdx]`:
|
||||
/// - Elements from `startIdx` through `stopIdx` (inclusive) are wrapped in
|
||||
/// `.wedge(kind, [...])`.
|
||||
/// - Elements before/between/after wedge spans are emitted as-is.
|
||||
///
|
||||
/// Index mapping requires `elements.count == entries.count`. This holds for
|
||||
/// the single-voice path. For the multi-voice path `elements` includes
|
||||
/// synthetic gap-fill rests that have NO corresponding entry, so the counts
|
||||
/// DIFFER whenever a voice has inter-event gaps; in that case the guard below
|
||||
/// triggers the safe fallback — NO wedge wrapping is applied and the
|
||||
/// `elements` are returned unchanged. Event round-trip is unaffected either
|
||||
/// way (wedges are transparent to `flatten()`); only the structural `.wedge`
|
||||
/// wrapper is dropped for multi-voice parts. This is the documented
|
||||
/// multi-voice wedge limitation (analogous to tuplets not round-tripping).
|
||||
///
|
||||
/// If an entry's `wedgeStart` cannot be matched to a subsequent `wedgeStop`
|
||||
/// (malformed document), the span extends to the end of the array.
|
||||
static func wrapWedgeSpans(
|
||||
in elements: [ScoreElement],
|
||||
from entries: [_PartEntry]
|
||||
) -> [ScoreElement] {
|
||||
// If neither the entries nor elements have wedge annotations, return as-is.
|
||||
let hasWedge: Bool = entries.contains { $0.wedgeStart != nil || $0.wedgeStop }
|
||||
guard hasWedge else { return elements }
|
||||
|
||||
// Build a parallel array of (wedgeStart, wedgeStop) using entries indices.
|
||||
// For the single-voice path, elements.count == entries.count.
|
||||
// For multi-voice, entries does not include gap-fill rests, so index
|
||||
// alignment is only valid for the elements that came from entries.
|
||||
// Since gap-fill rests never carry wedge annotations (they are synthetic),
|
||||
// we treat the entries and elements arrays as parallel for wedge annotation
|
||||
// purposes when they have the same length.
|
||||
guard elements.count == entries.count else {
|
||||
// Length mismatch (multi-voice with gap-fill rests): fall back to
|
||||
// unannotated output — event round-trip is still correct because
|
||||
// wedges are transparent to flattening.
|
||||
return elements
|
||||
}
|
||||
|
||||
var result: [ScoreElement] = []
|
||||
var i: Int = 0
|
||||
|
||||
while i < elements.count {
|
||||
if let kind: WedgeKind = entries[i].wedgeStart {
|
||||
// Found a wedge-start. Collect elements up to and including the
|
||||
// matching wedge-stop (or the end of the array if no stop is found).
|
||||
var j: Int = i
|
||||
// Search for the wedge-stop in the same voice (same-voice entries
|
||||
// are already filtered for multi-voice; single-voice searches all).
|
||||
while j < entries.count && !entries[j].wedgeStop {
|
||||
j += 1
|
||||
}
|
||||
// j now points at the stop entry (or one past the end if not found).
|
||||
// Cap at the last valid index.
|
||||
let stopIdx: Int = min(j, elements.count - 1)
|
||||
let spanElements: [ScoreElement] = Array(elements[i...stopIdx])
|
||||
result.append(.wedge(kind, spanElements))
|
||||
i = stopIdx + 1
|
||||
} else {
|
||||
result.append(elements[i])
|
||||
i += 1
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
/// Return a copy of `element` with its voice field zeroed out.
|
||||
///
|
||||
/// Used by `reconstructElements` when building per-voice element lists:
|
||||
/// elements are wrapped in `.voice(n, [...])` blocks, so their own voice
|
||||
/// field should be `0` (the fallback indicator) to let `_flatten` use the
|
||||
/// enclosing Voice block's number via `voiceFallback`. The MusicXML parser
|
||||
/// stores `pendingChordVoice = max(0, noteContext.voice-1)` in the voice field
|
||||
/// (a 0-based offset) which would otherwise override the block's voiceFallback
|
||||
/// for notes whose voice field is non-zero (e.g. MusicXML `<voice>2</voice>`
|
||||
/// maps to `pendingChordVoice = 1`).
|
||||
static func zeroVoice(_ element: ScoreElement) -> ScoreElement {
|
||||
switch element {
|
||||
case .note(let p, let dur, let dyn, let art, _, _):
|
||||
return .note(p, duration: dur, dynamic: dyn, articulation: art, voice: 0, tie: false)
|
||||
case .chord(let ps, let dur, let dyn, let art, _, _):
|
||||
// Authored chord ties do not round-trip through zeroVoice (the parser
|
||||
// flushes chords without a tie field; voice zeroing is a pre-Voice-block
|
||||
// clean-up step and authored ties are already merged before reaching here).
|
||||
return .chord(ps, duration: dur, dynamic: dyn, articulation: art, voice: 0, tie: false)
|
||||
case .rest, .tuplet, .voice, .wedge, .grace, .clefChange, .staff, .pedal,
|
||||
.slur, .spanned, .displayed, .marked, .dynamicCurve, .fillMeasure:
|
||||
return element
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract the duration of a `ScoreElement` as a `Fraction` (in quarter-beats).
|
||||
/// Used by `reconstructElements` to compute per-voice cursor positions.
|
||||
/// Only `.note`, `.rest`, and `.chord` carry durations; `.tuplet` and
|
||||
/// `.voice` are not expected in parsed entry lists (the parser produces
|
||||
/// only flat note/rest/chord elements).
|
||||
static func elementDuration(_ element: ScoreElement) -> Fraction {
|
||||
switch element {
|
||||
case .note(_, let dur, _, _, _, _):
|
||||
return dur.asFraction ?? .zero
|
||||
case .rest(let dur):
|
||||
return dur.asFraction ?? .zero
|
||||
case .chord(_, let dur, _, _, _, _):
|
||||
return dur.asFraction ?? .zero
|
||||
case .tuplet:
|
||||
return .zero
|
||||
case .voice:
|
||||
return .zero
|
||||
case .wedge:
|
||||
return .zero
|
||||
case .grace:
|
||||
// Grace notes have no duration — they do not advance the cursor.
|
||||
return .zero
|
||||
case .clefChange:
|
||||
// Clef changes have no duration — they do not advance the cursor.
|
||||
return .zero
|
||||
case .staff:
|
||||
// Staff blocks overlay from beat 0 — zero duration in this context.
|
||||
return .zero
|
||||
case .pedal:
|
||||
// Pedal marks have no duration — they do not advance the cursor.
|
||||
return .zero
|
||||
case .slur:
|
||||
// Slur blocks are not expected in the parser's flat entry list.
|
||||
return .zero
|
||||
case .spanned:
|
||||
// Spanned elements are not expected in the parser's flat entry list.
|
||||
return .zero
|
||||
case .displayed:
|
||||
// Displayed wrappers are not expected in the parser's flat entry list.
|
||||
return .zero
|
||||
case .marked:
|
||||
// Marked wrappers are not expected in the parser's flat entry list.
|
||||
return .zero
|
||||
case .dynamicCurve:
|
||||
// Dynamic curve wrappers are not expected in the parser's flat entry list.
|
||||
return .zero
|
||||
case .fillMeasure:
|
||||
// FillMeasure is expanded at Score init time and never appears in the
|
||||
// parser's flat entry list. Treat as zero duration (no-op).
|
||||
return .zero
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,500 @@
|
||||
// MusicXMLParser+Commit.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
extension _MusicXMLParser {
|
||||
// MARK: - Note commit
|
||||
|
||||
func commitCurrentNote() {
|
||||
guard let partIndex: Int = currentPartIndex else { return }
|
||||
|
||||
// Grace notes have no <duration> and do not advance the cursor.
|
||||
// Commit as a .grace element directly, bypassing tie-merge and chord buffering.
|
||||
if noteContext.isGrace {
|
||||
// Flush any pending chord BEFORE the grace note (the grace ornaments the
|
||||
// FOLLOWING main note — it appears before it in document order).
|
||||
flushPendingChord(into: partIndex)
|
||||
// Build the pitch from the parsed step/alter/octave (or skip if unrecognised).
|
||||
if let step: String = noteContext.pitchStep,
|
||||
let pitch: Pitch = makePitch(
|
||||
step: step,
|
||||
alter: noteContext.pitchAlter,
|
||||
octave: noteContext.pitchOctave
|
||||
)
|
||||
{
|
||||
let absoluteBeatNow: Fraction = Fraction(
|
||||
num: Int64(parts[partIndex].absoluteCursorDivisions),
|
||||
den: Int64(currentDivisions)
|
||||
)
|
||||
let entry: _PartEntry = _PartEntry(
|
||||
beat: absoluteBeatNow,
|
||||
voice: noteContext.voice,
|
||||
element: .grace(pitch, slashed: noteContext.graceSlashed)
|
||||
)
|
||||
parts[partIndex].entries.append(entry)
|
||||
// Cursor does NOT advance — grace notes have no duration.
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Span model: resolve the effective articulation for this note.
|
||||
// Slur state is tracked per-voice (via `slurActiveByVoice`) so that a slur
|
||||
// open in voice 1 does not contaminate notes in voice 2 after a `<backup>`.
|
||||
//
|
||||
// Priority order:
|
||||
// 1. If this note carries `<slur type="start"/>`: mark `.legato` and
|
||||
// activate the span for this voice.
|
||||
// 2. If `slurActiveByVoice[noteContext.voice]` is true and this note does NOT carry
|
||||
// `stop`: mark `.legato` (interior span member).
|
||||
// 3. If this note carries `<slur type="stop"/>`: do NOT force `.legato`
|
||||
// (the stop note is the slur target, not a slur member). Clear the span
|
||||
// for this voice.
|
||||
// 4. Otherwise: use the articulation parsed from `<articulations>`.
|
||||
//
|
||||
// Note: `noteContext.articulation` may already be `.legato` from a genuine
|
||||
// `<articulations><legato/>` element (hypothetical; not standard MusicXML)
|
||||
// — we override only when slur markup requires it.
|
||||
let voiceSlurActive: Bool = slurActiveByVoice[noteContext.voice, default: false]
|
||||
if noteContext.hasSlurStart {
|
||||
noteContext.articulation = .legato
|
||||
slurActiveByVoice[noteContext.voice] = true
|
||||
} else if voiceSlurActive && !noteContext.hasSlurStop {
|
||||
// Interior span member — mark legato.
|
||||
noteContext.articulation = .legato
|
||||
}
|
||||
if noteContext.hasSlurStop {
|
||||
// Stop note is the span boundary — NOT marked `.legato`.
|
||||
// The stop note keeps its own parsed articulation (usually `.normal`).
|
||||
// If this note also has `start` (rare end-of-part edge where a run's
|
||||
// last legato note carries start+stop), the `noteContext.hasSlurStart` branch
|
||||
// above already set `.legato`, which is acceptable for that edge case.
|
||||
slurActiveByVoice[noteContext.voice] = false
|
||||
}
|
||||
|
||||
// Fix 1: build an exact rational duration rather than a Double.
|
||||
// Fraction auto-reduces, so e.g. divisions=3/divisions=3 → 1/1 exactly,
|
||||
// and a triplet-quarter (2 divisions out of 3) → 2/3 exactly.
|
||||
let noteDuration: NoteDuration = .fraction(
|
||||
Fraction(
|
||||
num: Int64(noteContext.durationDivisions),
|
||||
den: Int64(currentDivisions)
|
||||
)
|
||||
)
|
||||
let pitch: Pitch? = (noteContext.pitchStep != nil && !noteContext.isRest)
|
||||
? makePitch(
|
||||
step: noteContext.pitchStep ?? "",
|
||||
alter: noteContext.pitchAlter,
|
||||
octave: noteContext.pitchOctave
|
||||
)
|
||||
: nil
|
||||
|
||||
// Capture the absolute beat from the cursor BEFORE advancing.
|
||||
// For chord-mates the cursor is NOT advanced (it was already
|
||||
// advanced by the chord lead note).
|
||||
let absoluteCursorNow: Int = parts[partIndex].absoluteCursorDivisions
|
||||
let absoluteBeatNow: Fraction = Fraction(
|
||||
num: Int64(absoluteCursorNow),
|
||||
den: Int64(currentDivisions)
|
||||
)
|
||||
|
||||
if noteContext.isChord {
|
||||
// Chord-mate: append pitch to the pending chord buffer. Cursor
|
||||
// does not advance. If parsing produced no pitch (malformed
|
||||
// chord-mate), drop the entry silently.
|
||||
//
|
||||
// If this chord-mate carries a tie-stop, attempt to merge it into
|
||||
// the last emitted element that contains the same pitch in the
|
||||
// same voice. When the merge succeeds the duration is already
|
||||
// folded into the prior element, so we do NOT buffer this mate —
|
||||
// buffering would produce a spurious extra chord element on flush.
|
||||
// When the merge fails (no prior element carries this pitch) the
|
||||
// pitch is new and must be buffered normally so it is not lost.
|
||||
//
|
||||
// Special case: if the lead note's tie-stop for this note group
|
||||
// already merged a `.chord` element that contains this pitch (tracked
|
||||
// via `lastMergedChordLocation`), the duration has already been
|
||||
// extended for ALL pitches in that chord. Do not merge again.
|
||||
if let p: Pitch = pitch {
|
||||
if noteContext.tieStop {
|
||||
// Check whether the lead note's merge already covered this pitch.
|
||||
let alreadyCoveredByLeadMerge: Bool = {
|
||||
guard let loc: (partIndex: Int, elementIndex: Int) = lastMergedChordLocation,
|
||||
loc.partIndex == partIndex else { return false }
|
||||
let elem: ScoreElement = parts[loc.partIndex].entries[loc.elementIndex].element
|
||||
if case .chord(let pitches, _, _, _, _, _) = elem {
|
||||
return pitches.contains(p)
|
||||
}
|
||||
return false
|
||||
}()
|
||||
if alreadyCoveredByLeadMerge {
|
||||
// Skip — duration was already folded in by the lead merge.
|
||||
} else {
|
||||
let mergedIdx: Int? = tryMergeTieStop(
|
||||
pitch: p,
|
||||
extraDuration: noteDuration,
|
||||
voice: max(0, noteContext.voice - 1),
|
||||
partIndex: partIndex
|
||||
)
|
||||
if mergedIdx == nil {
|
||||
pendingChordPitches.append(p)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
pendingChordPitches.append(p)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Non-chord note (lead) — flush any pending chord first, and reset
|
||||
// the chord-merge-location tracker for this new lead group.
|
||||
flushPendingChord(into: partIndex)
|
||||
lastMergedChordLocation = nil
|
||||
|
||||
if noteContext.isRest {
|
||||
// Rests use the current voice number for beat-grouping purposes.
|
||||
let entry: _PartEntry = _PartEntry(
|
||||
beat: absoluteBeatNow,
|
||||
voice: noteContext.voice,
|
||||
element: .rest(duration: noteDuration)
|
||||
)
|
||||
parts[partIndex].entries.append(entry)
|
||||
// Advance cursor by this rest's duration.
|
||||
parts[partIndex].absoluteCursorDivisions += noteContext.durationDivisions
|
||||
} else if let p: Pitch = pitch {
|
||||
// Tie-stop: try to merge this note into the last emitted element
|
||||
// of the same pitch in the same voice, rather than emitting a new
|
||||
// element. This collapses barline-split tied pairs back into one
|
||||
// element so round-trips preserve element count + durations.
|
||||
if noteContext.tieStop {
|
||||
let mergedIdx: Int? = tryMergeTieStop(
|
||||
pitch: p,
|
||||
extraDuration: noteDuration,
|
||||
voice: max(0, noteContext.voice - 1),
|
||||
partIndex: partIndex
|
||||
)
|
||||
if let idx: Int = mergedIdx {
|
||||
// Record the merge location so chord-mates in this note
|
||||
// group can detect that their pitch was already extended.
|
||||
if case .chord = parts[partIndex].entries[idx].element {
|
||||
lastMergedChordLocation = (partIndex: partIndex, elementIndex: idx)
|
||||
}
|
||||
// Merged successfully — advance cursor and don't buffer a new chord lead.
|
||||
parts[partIndex].absoluteCursorDivisions += noteContext.durationDivisions
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Buffer this note as the chord lead — flushed when the next
|
||||
// non-chord-mate or end-of-part arrives.
|
||||
// Capture currentDynamic NOW so a subsequent <direction> element
|
||||
// that arrives before the flush does not overwrite this note's
|
||||
// dynamic (the dynamic belongs to the note, not to the flush moment).
|
||||
pendingChordPitches = [p]
|
||||
pendingChordDuration = noteDuration
|
||||
pendingChordVoice = max(0, noteContext.voice - 1)
|
||||
pendingChordArticulation = noteContext.articulation
|
||||
pendingChordDynamic = currentDynamic
|
||||
pendingChordBeat = absoluteBeatNow
|
||||
// Advance cursor for this lead note.
|
||||
parts[partIndex].absoluteCursorDivisions += noteContext.durationDivisions
|
||||
} else {
|
||||
// Unrecognised pitch + not a rest — treat as rest to keep
|
||||
// cursor advancing rather than dropping silently.
|
||||
let entry: _PartEntry = _PartEntry(
|
||||
beat: absoluteBeatNow,
|
||||
voice: noteContext.voice,
|
||||
element: .rest(duration: noteDuration)
|
||||
)
|
||||
parts[partIndex].entries.append(entry)
|
||||
parts[partIndex].absoluteCursorDivisions += noteContext.durationDivisions
|
||||
}
|
||||
}
|
||||
|
||||
/// Attempt to merge a tie-stop note into the immediately-preceding
|
||||
/// element of the same voice that carries the matching pitch.
|
||||
///
|
||||
/// Fix 2: the search is bounded to the IMMEDIATELY-preceding emitted
|
||||
/// element of the same voice (the last note or chord in the voice at the
|
||||
/// tail of the element list). If that element doesn't match pitch + voice,
|
||||
/// no merge is performed — the tie-stop is emitted as a normal new element.
|
||||
/// This prevents a stray `<tie type="stop"/>` on a later same-pitch note
|
||||
/// from incorrectly extending an unrelated earlier note.
|
||||
///
|
||||
/// Returns the index of the merged element on success, or `nil` when no
|
||||
/// matching immediately-prior element was found.
|
||||
@discardableResult
|
||||
func tryMergeTieStop(
|
||||
pitch: Pitch,
|
||||
extraDuration: NoteDuration,
|
||||
voice: Int,
|
||||
partIndex: Int
|
||||
) -> Int? {
|
||||
// Find the last emitted element that belongs to this voice (scanning
|
||||
// backward to skip elements from other voices). If that element
|
||||
// does NOT carry the expected pitch, do not merge — emit normally.
|
||||
let entries: [_PartEntry] = parts[partIndex].entries
|
||||
for i: Int in stride(from: entries.count - 1, through: 0, by: -1) {
|
||||
let element: ScoreElement = entries[i].element
|
||||
switch element {
|
||||
case .note(let ep, let dur, let dyn, let art, let ev, _):
|
||||
if ev != voice {
|
||||
// Different voice — keep scanning to skip its notes.
|
||||
continue
|
||||
}
|
||||
// This is the immediately-preceding note in this voice.
|
||||
// Only merge if pitch matches; otherwise stop scanning.
|
||||
guard ep == pitch else { return nil }
|
||||
let newDur: NoteDuration = addDurations(dur, extraDuration)
|
||||
parts[partIndex].replaceElement(
|
||||
at: i,
|
||||
with: .note(ep, duration: newDur, dynamic: dyn, articulation: art, voice: ev, tie: false)
|
||||
)
|
||||
return i
|
||||
|
||||
case .chord(let pitches, let dur, let dyn, let art, let ev, _):
|
||||
if ev != voice {
|
||||
continue
|
||||
}
|
||||
// Immediately-preceding chord in this voice.
|
||||
guard pitches.contains(pitch) else { return nil }
|
||||
let newDur: NoteDuration = addDurations(dur, extraDuration)
|
||||
parts[partIndex].replaceElement(
|
||||
at: i,
|
||||
with: .chord(pitches, duration: newDur, dynamic: dyn, articulation: art, voice: ev, tie: false)
|
||||
)
|
||||
return i
|
||||
|
||||
case .rest:
|
||||
// Rests don't carry pitches; continue scanning backwards for
|
||||
// the immediately-preceding pitched event of this voice.
|
||||
continue
|
||||
|
||||
case .tuplet:
|
||||
// Don't look inside tuplets for merge targets.
|
||||
return nil
|
||||
|
||||
case .voice:
|
||||
// Voice wrapper elements are not expected in the parser's flat
|
||||
// entry list — stop scanning at any unexpected case.
|
||||
return nil
|
||||
|
||||
case .wedge:
|
||||
// Wedge wrapper elements are not expected in the parser's flat
|
||||
// entry list — stop scanning at any unexpected case.
|
||||
return nil
|
||||
|
||||
case .grace:
|
||||
// Grace notes are durationless and are not merge targets.
|
||||
// Continue scanning backward past any preceding grace elements.
|
||||
continue
|
||||
|
||||
case .clefChange:
|
||||
// Clef changes are durationless and are not merge targets.
|
||||
// Continue scanning past them.
|
||||
continue
|
||||
|
||||
case .staff:
|
||||
// Staff blocks are not expected in the parser's flat entry list.
|
||||
return nil
|
||||
|
||||
case .pedal:
|
||||
// Pedal marks are durationless and are not merge targets.
|
||||
// Continue scanning backward past them.
|
||||
continue
|
||||
|
||||
case .slur:
|
||||
// Slur blocks are structural span wrappers, not notes, and never
|
||||
// appear in the parser's flat entry list. Stop the backward scan
|
||||
// here — matching the sibling wrappers `.wedge` / `.voice` /
|
||||
// `.staff` — so a tie-merge never binds across a structural
|
||||
// boundary if a future round-trip extension introduces one.
|
||||
return nil
|
||||
|
||||
case .spanned:
|
||||
// Spanned elements are structural wrappers, not notes. Stop the
|
||||
// backward scan for the same reason as `.slur` above.
|
||||
return nil
|
||||
|
||||
case .displayed:
|
||||
// Displayed wrappers are structural span wrappers, not notes.
|
||||
// Stop the backward scan here — the parser does not produce these
|
||||
// in its flat entry list, and a tie-merge must not cross structural
|
||||
// wrappers.
|
||||
return nil
|
||||
|
||||
case .marked:
|
||||
// Marked wrappers are structural span wrappers, not notes.
|
||||
// Stop the backward scan here — the parser does not produce these
|
||||
// in its flat entry list, and a tie-merge must not cross structural
|
||||
// wrappers.
|
||||
return nil
|
||||
|
||||
case .dynamicCurve:
|
||||
// Dynamic curve wrappers are structural wrappers, not notes.
|
||||
// Stop the backward scan here — the parser does not produce these
|
||||
// in its flat entry list.
|
||||
return nil
|
||||
|
||||
case .fillMeasure:
|
||||
// FillMeasure is expanded at Score init time and never appears in
|
||||
// the parser's flat entry list. Stop the backward scan to avoid
|
||||
// crossing this marker if one ever appears by mistake.
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
/// Add two `NoteDuration` values using exact `Fraction` arithmetic when
|
||||
/// both operands are `.fraction`. Falls back to `Double` only when
|
||||
/// either operand is `.beats`.
|
||||
///
|
||||
/// Fix 1: this ensures tie-merge produces exact rational sums (e.g.
|
||||
/// a triplet quarter 2/3 + 2/3 = 4/3) without floating-point drift.
|
||||
func addDurations(
|
||||
_ a: NoteDuration,
|
||||
_ b: NoteDuration
|
||||
) -> NoteDuration {
|
||||
switch (a, b) {
|
||||
case (.fraction(let fa), .fraction(let fb)):
|
||||
return .fraction(fa + fb)
|
||||
case (.fraction(let fa), .beats(let bb)):
|
||||
// Convert the Double to a high-precision fraction and add exactly.
|
||||
let denominator: Int64 = Fraction.beatApproxDenominator
|
||||
let extraNum: Int64 = Int64((bb * Double(denominator)).rounded())
|
||||
let extraFrac: Fraction = Fraction(num: extraNum, den: denominator)
|
||||
return .fraction(fa + extraFrac)
|
||||
case (.beats(let ba), .fraction(let fb)):
|
||||
let denominator: Int64 = Fraction.beatApproxDenominator
|
||||
let baseNum: Int64 = Int64((ba * Double(denominator)).rounded())
|
||||
let baseFrac: Fraction = Fraction(num: baseNum, den: denominator)
|
||||
return .fraction(baseFrac + fb)
|
||||
case (.beats(let ba), .beats(let bb)):
|
||||
return .beats(ba + bb)
|
||||
}
|
||||
}
|
||||
|
||||
/// Emit any buffered chord lead + chord-mate pitches as either a
|
||||
/// `.note` (singleton) or `.chord(...)` (multi-pitch) element.
|
||||
func flushPendingChord(into partIndex: Int) {
|
||||
guard !pendingChordPitches.isEmpty else { return }
|
||||
let dur: NoteDuration = pendingChordDuration
|
||||
let beat: Fraction = pendingChordBeat
|
||||
// The MusicXML voice number is the 1-based value from <voice>; the
|
||||
// ScoreElement voice field stores the 0-based fallback index
|
||||
// (pendingChordVoice = max(0, noteContext.voice - 1)). For the _PartEntry
|
||||
// grouping we use the 1-based MusicXML voice (pendingChordVoice + 1)
|
||||
// so entries in the same <voice> slot are partitioned together.
|
||||
// ScoreElement's voice field stays 0-based as before.
|
||||
let mxVoice: Int = pendingChordVoice + 1
|
||||
// Use the dynamic captured at lead-note commit time (pendingChordDynamic),
|
||||
// not the current dynamic at flush time. A <direction> arriving between
|
||||
// commit and flush must not overwrite this note group's dynamic.
|
||||
let element: ScoreElement
|
||||
if pendingChordPitches.count == 1 {
|
||||
element = .note(
|
||||
pendingChordPitches[0],
|
||||
duration: dur,
|
||||
dynamic: pendingChordDynamic,
|
||||
articulation: pendingChordArticulation,
|
||||
voice: pendingChordVoice,
|
||||
tie: false
|
||||
)
|
||||
} else {
|
||||
element = .chord(
|
||||
pendingChordPitches,
|
||||
duration: dur,
|
||||
dynamic: pendingChordDynamic,
|
||||
articulation: pendingChordArticulation,
|
||||
voice: pendingChordVoice,
|
||||
tie: false
|
||||
)
|
||||
}
|
||||
// Apply any pending wedge-start annotation to this entry.
|
||||
// The wedge-start direction appeared before this note in the document.
|
||||
let wedgeStartForThisNote: WedgeKind? = pendingWedgeStartForNextNote
|
||||
pendingWedgeStartForNextNote = nil
|
||||
var entry: _PartEntry = _PartEntry(beat: beat, voice: mxVoice, element: element)
|
||||
entry.wedgeStart = wedgeStartForThisNote
|
||||
parts[partIndex].entries.append(entry)
|
||||
pendingChordPitches.removeAll(keepingCapacity: true)
|
||||
}
|
||||
|
||||
/// Build a `Pitch.named(...)` from MusicXML primitives. Returns nil
|
||||
/// when `step` is unrecognised or `alter` is outside the supported
|
||||
/// 50-cent grid.
|
||||
func makePitch(
|
||||
step: String,
|
||||
alter: Double,
|
||||
octave: Int
|
||||
) -> Pitch? {
|
||||
guard let letter: Letter = _MusicXMLParser.letterForStep(step) else { return nil }
|
||||
guard let accidental: Accidental = _MusicXMLParser.accidentalForAlter(alter) else { return nil }
|
||||
return .named(NoteName(letter: letter, accidental: accidental), octave)
|
||||
}
|
||||
|
||||
static func letterForStep(_ step: String) -> Letter? {
|
||||
switch step.uppercased() {
|
||||
case "A": return .a
|
||||
case "B": return .b
|
||||
case "C": return .c
|
||||
case "D": return .d
|
||||
case "E": return .e
|
||||
case "F": return .f
|
||||
case "G": return .g
|
||||
default: return nil
|
||||
}
|
||||
}
|
||||
|
||||
static func accidentalForAlter(_ alter: Double) -> Accidental? {
|
||||
switch alter {
|
||||
case -2.0: return .doubleFlat
|
||||
case -1.5: return .threeQuarterFlat
|
||||
case -1.0: return .flat
|
||||
case -0.5: return .quarterFlat
|
||||
case 0.0: return .natural
|
||||
case 0.5: return .quarterSharp
|
||||
case 1.0: return .sharp
|
||||
case 1.5: return .threeQuarterSharp
|
||||
case 2.0: return .doubleSharp
|
||||
default: return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Map a parsed `(sign, line, octaveChange)` triple to a ``Clef`` case.
|
||||
///
|
||||
/// Inverse of ``Clef/musicXMLClef``. Unknown combinations fall back to
|
||||
/// `.treble` so parse results are always valid.
|
||||
internal static func clefFromParsed(
|
||||
sign: String,
|
||||
line: Int?,
|
||||
octaveChange: Int?
|
||||
) -> Clef {
|
||||
let normalised: String = sign.lowercased()
|
||||
switch normalised {
|
||||
case "g":
|
||||
// G clef with octave-change -1 → treble8vb (guitar, tenor voice).
|
||||
if octaveChange == -1 { return .treble8vb }
|
||||
return .treble
|
||||
case "f":
|
||||
// Standard bass clef is line 4; other F-clef positions are unusual —
|
||||
// treat any F clef as bass for now.
|
||||
return .bass
|
||||
case "c":
|
||||
if line == 3 { return .alto }
|
||||
if line == 4 { return .tenor }
|
||||
// Other C-clef lines — fall through to treble.
|
||||
return .treble
|
||||
case "percussion":
|
||||
return .percussion
|
||||
default:
|
||||
// Unknown sign (tab, jianpu, etc.) — safe fallback.
|
||||
return .treble
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,771 @@
|
||||
// MusicXMLParser+Delegate.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
extension _MusicXMLParser {
|
||||
// MARK: - XMLParserDelegate
|
||||
|
||||
func parser(
|
||||
_ parser: XMLParser,
|
||||
didStartElement elementName: String,
|
||||
namespaceURI: String?,
|
||||
qualifiedName qName: String?,
|
||||
attributes attributeDict: [String: String] = [:]
|
||||
) {
|
||||
elementStack.append(elementName)
|
||||
currentText = ""
|
||||
|
||||
// Root validation
|
||||
if elementStack.count == 1 {
|
||||
if elementName == _MusicXMLParser.timewiseRootName {
|
||||
rootError = .unsupportedTimewiseDocument
|
||||
parser.abortParsing()
|
||||
return
|
||||
}
|
||||
guard elementName == _MusicXMLParser.rootElementName else {
|
||||
rootError = .unsupportedRoot(elementName)
|
||||
parser.abortParsing()
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
switch elementName {
|
||||
case "part-list":
|
||||
inPartList = true
|
||||
|
||||
case "score-part" where inPartList:
|
||||
currentScorePartID = attributeDict["id"]
|
||||
currentScorePartName = nil
|
||||
|
||||
case "part" where !inPartList:
|
||||
// `<part id="P1">`. Resolve to a builder using the part-list.
|
||||
let id: String = attributeDict["id"] ?? ""
|
||||
if let entry: (id: String, name: String) = partListEntries.first(where: { $0.id == id }) {
|
||||
let builder: _PartBuilder = _PartBuilder(id: entry.id, name: entry.name)
|
||||
parts.append(builder)
|
||||
currentPartIndex = parts.count - 1
|
||||
} else {
|
||||
// No matching score-part — synthesize a default builder so
|
||||
// events still land somewhere.
|
||||
let builder: _PartBuilder = _PartBuilder(id: id, name: "Part \(parts.count + 1)")
|
||||
parts.append(builder)
|
||||
currentPartIndex = parts.count - 1
|
||||
}
|
||||
currentDivisions = _MusicXMLParser.defaultDivisions
|
||||
// Reset per-voice slur-span state at the start of each new part.
|
||||
slurActiveByVoice = [:]
|
||||
// Reset dynamic to the default at the start of each part, and
|
||||
// clear any direction-parsing flags that a malformed prior part
|
||||
// might have left set (defensive — a part ending mid-<direction>
|
||||
// must not leak flag state into the next part).
|
||||
currentDynamic = .mf
|
||||
pendingDynamic = nil
|
||||
inDirection = false
|
||||
inDirectionType = false
|
||||
inDynamics = false
|
||||
// Reset wedge state at part start.
|
||||
wedgeActiveByVoice = [:]
|
||||
pendingWedgeStart = nil
|
||||
pendingWedgeStop = false
|
||||
pendingWedgeStartForNextNote = nil
|
||||
// Reset per-part measure counter.
|
||||
currentMeasureNumber = 0
|
||||
// Reset per-part key + transpose accumulation state.
|
||||
inTranspose = false
|
||||
transposeDiatonic = 0
|
||||
transposeChromatic = 0
|
||||
transposeOctaveChange = 0
|
||||
|
||||
case "measure" where currentPartIndex != nil:
|
||||
// Detect the first measure's implicit attribute.
|
||||
// When `implicit="yes"` on the very first measure of the first part,
|
||||
// the measure is the pickup (measure 0). We adjust `currentMeasureNumber`
|
||||
// so it becomes 0 for the pickup instead of 1, keeping subsequent full
|
||||
// bars at 1..N (all existing <time> / repeat / tempo-change maps remain
|
||||
// correctly 1-based).
|
||||
//
|
||||
// The adjustment: decrement by 1 BEFORE the `+= 1` below so the
|
||||
// effective result is 0. Only applied once (first measure of first part).
|
||||
if isFirstPart && currentMeasureNumber == 0 {
|
||||
let isImplicit: Bool = attributeDict["implicit"] == "yes"
|
||||
if isImplicit {
|
||||
firstMeasureIsImplicit = true
|
||||
// Pre-decrement so +1 below produces 0 for the pickup measure.
|
||||
currentMeasureNumber = -1
|
||||
}
|
||||
}
|
||||
// Track measure number. Incremented here for every measure.
|
||||
currentMeasureNumber += 1
|
||||
|
||||
case "barline" where currentPartIndex != nil && isFirstPart:
|
||||
// Begin a barline block; capture location attribute.
|
||||
inBarline = true
|
||||
barlineLocation = attributeDict["location"] ?? ""
|
||||
barlineHasRepeatForward = false
|
||||
barlineHasRepeatBackward = false
|
||||
barlineEndingNumber = 0
|
||||
barlineEndingType = ""
|
||||
|
||||
case "repeat" where inBarline && isFirstPart:
|
||||
// `<repeat direction="forward|backward"/>`.
|
||||
if let direction: String = attributeDict["direction"] {
|
||||
if direction == "forward" { barlineHasRepeatForward = true }
|
||||
if direction == "backward" { barlineHasRepeatBackward = true }
|
||||
}
|
||||
|
||||
case "ending" where inBarline && isFirstPart:
|
||||
// `<ending number="N" type="start|stop|discontinue"/>`.
|
||||
if let numStr: String = attributeDict["number"],
|
||||
let num: Int = Int(numStr),
|
||||
let type_: String = attributeDict["type"]
|
||||
{
|
||||
barlineEndingNumber = num
|
||||
barlineEndingType = type_
|
||||
}
|
||||
|
||||
case "note":
|
||||
// Reset all per-note accumulator state in one shot.
|
||||
noteContext = _NoteContext()
|
||||
|
||||
case "grace":
|
||||
// `<grace/>` or `<grace slash="yes"/>` marks this note
|
||||
// as a grace note. No `<duration>` is expected; the note will be
|
||||
// committed as a `.grace(pitch, slashed:)` element that does not
|
||||
// advance the beat cursor.
|
||||
noteContext.isGrace = true
|
||||
noteContext.graceSlashed = attributeDict["slash"] == "yes"
|
||||
|
||||
case "rest":
|
||||
noteContext.isRest = true
|
||||
|
||||
case "chord":
|
||||
noteContext.isChord = true
|
||||
|
||||
case "pitch":
|
||||
inPitch = true
|
||||
|
||||
case "notations":
|
||||
inNotations = true
|
||||
|
||||
case "time":
|
||||
inTime = true
|
||||
// Reset per-<time>-block accumulators so each <time> element is
|
||||
// self-contained (matches the per-key reset pattern for <key>).
|
||||
pendingTimeBeatCount = 0
|
||||
pendingTimeBeatType = 0
|
||||
|
||||
case "key":
|
||||
inKey = true
|
||||
// Reset per-key accumulation state.
|
||||
keyFifths = 0
|
||||
keyMode = "major"
|
||||
|
||||
case "clef":
|
||||
inClef = true
|
||||
// Reset per-clef accumulation state.
|
||||
clefSign = ""
|
||||
clefLine = nil
|
||||
clefOctaveChange = nil
|
||||
|
||||
case "transpose" where currentPartIndex != nil:
|
||||
// Begin a <transpose> block. Reset accumulation state.
|
||||
inTranspose = true
|
||||
transposeDiatonic = 0
|
||||
transposeChromatic = 0
|
||||
transposeOctaveChange = 0
|
||||
|
||||
case "backup" where currentPartIndex != nil:
|
||||
inBackup = true
|
||||
backupForwardDivisions = 0
|
||||
|
||||
case "forward" where currentPartIndex != nil:
|
||||
inForward = true
|
||||
backupForwardDivisions = 0
|
||||
|
||||
case "direction" where currentPartIndex != nil:
|
||||
// Begin a direction block; reset pending dynamic, wedge, pedal, and tempo for this block.
|
||||
inDirection = true
|
||||
pendingDynamic = nil
|
||||
pendingWedgeStart = nil
|
||||
pendingWedgeStop = false
|
||||
pendingPedalKind = nil
|
||||
// Reset the per-direction tempo accumulator.
|
||||
pendingDirectionTempo = nil
|
||||
|
||||
case "direction-type" where inDirection:
|
||||
inDirectionType = true
|
||||
|
||||
case "dynamics" where inDirectionType:
|
||||
inDynamics = true
|
||||
|
||||
case "wedge" where inDirectionType:
|
||||
// Parse <wedge type="crescendo|diminuendo|stop"/>.
|
||||
// The type attribute determines whether this is a span open or close.
|
||||
if let wedgeType: String = attributeDict["type"] {
|
||||
switch wedgeType {
|
||||
case "crescendo": pendingWedgeStart = .crescendo
|
||||
case "diminuendo": pendingWedgeStart = .diminuendo
|
||||
case "stop": pendingWedgeStop = true
|
||||
default: break
|
||||
}
|
||||
}
|
||||
|
||||
case "pedal" where inDirectionType:
|
||||
// Parse <pedal type="start|stop" line="yes"/>. Only "start" and "stop"
|
||||
// are surfaced; "change" and "continue" are ignored for round-trip
|
||||
// purposes (Lyrebird only emits start/stop).
|
||||
if let pedalType: String = attributeDict["type"] {
|
||||
switch pedalType {
|
||||
case "start": pendingPedalKind = .start
|
||||
case "stop": pendingPedalKind = .stop
|
||||
default: break
|
||||
}
|
||||
}
|
||||
|
||||
case "staves" where currentPartIndex != nil:
|
||||
// <staves>N</staves> inside <attributes> — accepted but not used for
|
||||
// element reconstruction. The Staff(...) grouping is a notation-only
|
||||
// structural layer documented as not round-tripping: the per-note
|
||||
// <staff> value is parsed (see `noteContext.staff`) but currently discarded,
|
||||
// so decoded notes come back partitioned only by <voice>, not regrouped
|
||||
// into Staff blocks. Sounding pitches / durations / pedal marks survive.
|
||||
break
|
||||
|
||||
// Standard MusicXML dynamics element names.
|
||||
// The element name itself (e.g. `<mf/>`) is the dynamic — no text content.
|
||||
case "ppp" where inDynamics: pendingDynamic = .ppp
|
||||
case "pp" where inDynamics: pendingDynamic = .pp
|
||||
case "p" where inDynamics: pendingDynamic = .p
|
||||
case "mp" where inDynamics: pendingDynamic = .mp
|
||||
case "mf" where inDynamics: pendingDynamic = .mf
|
||||
case "f" where inDynamics: pendingDynamic = .f
|
||||
case "ff" where inDynamics: pendingDynamic = .ff
|
||||
case "fff" where inDynamics: pendingDynamic = .fff
|
||||
case "n" where inDynamics: pendingDynamic = .niente
|
||||
|
||||
case "articulations":
|
||||
inArticulations = true
|
||||
|
||||
case "staccato" where inArticulations: noteContext.articulation = .staccato
|
||||
case "staccatissimo" where inArticulations: noteContext.articulation = .staccatissimo
|
||||
case "tenuto" where inArticulations: noteContext.articulation = .tenuto
|
||||
case "accent" where inArticulations: noteContext.articulation = .accent
|
||||
case "strong-accent" where inArticulations: noteContext.articulation = .marcato
|
||||
|
||||
case "slur" where inNotations:
|
||||
// Span-based slur tracking (no `continue`).
|
||||
//
|
||||
// Rule (matches the encoder's span-based convention):
|
||||
// • On `start`: record that this note opens a slur span.
|
||||
// The note itself is marked `.legato` in `commitCurrentNote`.
|
||||
// `slurActiveByVoice[voice]` is set to `true` there too.
|
||||
// • On `stop`: record that this note closes a slur span.
|
||||
// The stop note is NOT marked legato. `slurActiveByVoice[voice]` is cleared.
|
||||
// • Interior notes (no `start` or `stop`) are marked `.legato`
|
||||
// automatically while `slurActiveByVoice[voice] == true` in
|
||||
// `commitCurrentNote`.
|
||||
// • `continue` elements (from legacy documents) are treated as
|
||||
// interior-span markers: they do not change `slurActiveByVoice` and
|
||||
// do not mark legato on their own note — the span tracking handles it.
|
||||
if let kind: String = attributeDict["type"] {
|
||||
if kind == "start" {
|
||||
noteContext.hasSlurStart = true
|
||||
} else if kind == "stop" {
|
||||
noteContext.hasSlurStop = true
|
||||
}
|
||||
// `continue` is intentionally ignored — the span model makes it
|
||||
// unnecessary. Interior notes are already covered by `slurActiveByVoice`.
|
||||
}
|
||||
|
||||
case "tie":
|
||||
// `<tie type="stop"/>` — the sounding tie signal that drives
|
||||
// tie-merge: a tie-stop note is merged back into the prior note of
|
||||
// the same pitch so that barline-split note pairs round-trip as a
|
||||
// single ScoreElement. `<tie type="start"/>` carries no decode-side
|
||||
// information (the merge is driven entirely by the stop), so it is
|
||||
// not tracked. Ignore `<tied>` (the notation-only companion).
|
||||
if let kind: String = attributeDict["type"] {
|
||||
if kind == "stop" { noteContext.tieStop = true }
|
||||
}
|
||||
|
||||
case "sound":
|
||||
// Tempo can arrive as an attribute on `<sound tempo="X"/>` (common
|
||||
// in MuseScore ≤ 3 and MIDI-to-MusicXML converters that omit the
|
||||
// metronome block) OR as text inside `<metronome><per-minute>`.
|
||||
// First-write-wins via `sawTempo`.
|
||||
if let t: String = attributeDict["tempo"], let v: Double = Double(t), v > 0 {
|
||||
if !sawTempo {
|
||||
bpm = v
|
||||
sawTempo = true
|
||||
}
|
||||
// For mid-piece directions (measure >= 2, first part only),
|
||||
// capture the tempo value for TempoChange construction. First value
|
||||
// seen inside this direction block wins (`pendingDirectionTempo` is nil
|
||||
// until explicitly set here or in `per-minute`).
|
||||
if isFirstPart && currentMeasureNumber >= 2 && inDirection && pendingDirectionTempo == nil {
|
||||
pendingDirectionTempo = v
|
||||
}
|
||||
}
|
||||
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
func parser(
|
||||
_ parser: XMLParser,
|
||||
foundCharacters string: String
|
||||
) {
|
||||
currentText += string
|
||||
}
|
||||
|
||||
func parser(
|
||||
_ parser: XMLParser,
|
||||
didEndElement elementName: String,
|
||||
namespaceURI: String?,
|
||||
qualifiedName qName: String?
|
||||
) {
|
||||
defer {
|
||||
if !elementStack.isEmpty { elementStack.removeLast() }
|
||||
currentText = ""
|
||||
}
|
||||
let trimmed: String = currentText.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
|
||||
switch elementName {
|
||||
case "part-list":
|
||||
inPartList = false
|
||||
|
||||
case "score-part" where inPartList:
|
||||
if let id: String = currentScorePartID {
|
||||
let name: String = currentScorePartName ?? "Part \(partListEntries.count + 1)"
|
||||
partListEntries.append((id: id, name: name))
|
||||
}
|
||||
currentScorePartID = nil
|
||||
currentScorePartName = nil
|
||||
|
||||
case "part-name" where inPartList:
|
||||
currentScorePartName = trimmed
|
||||
|
||||
case "barline" where isFirstPart && inBarline:
|
||||
// Commit the accumulated barline data for this measure.
|
||||
inBarline = false
|
||||
if barlineLocation == "left" && barlineHasRepeatForward {
|
||||
parsedForwardRepeatMeasures.insert(currentMeasureNumber)
|
||||
}
|
||||
if barlineLocation == "right" && barlineHasRepeatBackward {
|
||||
parsedBackwardRepeatMeasures.insert(currentMeasureNumber)
|
||||
}
|
||||
if barlineEndingNumber >= 1 {
|
||||
if barlineEndingType == "start" {
|
||||
pendingEndingStarts[barlineEndingNumber] = currentMeasureNumber
|
||||
} else if barlineEndingType == "stop" || barlineEndingType == "discontinue" {
|
||||
if let startMeasure: Int = pendingEndingStarts[barlineEndingNumber] {
|
||||
let ending: Ending = Ending(
|
||||
number: barlineEndingNumber,
|
||||
startMeasure: startMeasure,
|
||||
stopMeasure: currentMeasureNumber
|
||||
)
|
||||
parsedEndings.append(ending)
|
||||
pendingEndingStarts.removeValue(forKey: barlineEndingNumber)
|
||||
}
|
||||
}
|
||||
}
|
||||
barlineEndingNumber = 0
|
||||
barlineEndingType = ""
|
||||
|
||||
case "measure" where currentPartIndex != nil && isFirstPart && !firstMeasureEnded:
|
||||
// Capture the absolute cursor position at the end of the
|
||||
// first implicit measure (the pickup). This is only done once (first
|
||||
// part, first measure). `firstMeasureEnded` prevents re-entry.
|
||||
//
|
||||
// `currentMeasureNumber == 0` when the pickup is present (see the
|
||||
// `<measure>` open handler). We check this to avoid capturing the
|
||||
// cursor for an ordinary measure-1 close in a no-anacrusis document.
|
||||
firstMeasureEnded = true
|
||||
if firstMeasureIsImplicit && currentMeasureNumber == 0 {
|
||||
if let idx: Int = currentPartIndex {
|
||||
// Flush any pending chord before reading the cursor so it is accurate.
|
||||
flushPendingChord(into: idx)
|
||||
pickupCursorDivisionsAtEnd = parts[idx].absoluteCursorDivisions
|
||||
pickupDivisions = currentDivisions
|
||||
}
|
||||
}
|
||||
|
||||
case "part" where currentPartIndex != nil:
|
||||
// Flush any chord still pending at end-of-part.
|
||||
if let idx: Int = currentPartIndex {
|
||||
flushPendingChord(into: idx)
|
||||
}
|
||||
// Barlines are read from the first part only.
|
||||
isFirstPart = false
|
||||
currentPartIndex = nil
|
||||
|
||||
case "divisions":
|
||||
if let v: Int = Int(trimmed), v > 0 {
|
||||
currentDivisions = v
|
||||
}
|
||||
|
||||
case "beats" where inTime:
|
||||
// Accumulate beat count for the CURRENT <time> block.
|
||||
// Both the first-time-signature path (tuple) and all subsequent
|
||||
// <time> blocks (MeterMap) use the per-block pendingTimeBeatCount
|
||||
// accumulator so they don't overwrite each other prematurely.
|
||||
if let v: Int = Int(trimmed), v > 0 {
|
||||
pendingTimeBeatCount = v
|
||||
// Back-compat: also update the tuple from the first <time>.
|
||||
if !sawTimeSignature {
|
||||
timeSignature = (v, timeSignature.1)
|
||||
}
|
||||
}
|
||||
|
||||
case "beat-type" where inTime:
|
||||
// Accumulate beat-type for the CURRENT <time> block.
|
||||
if let v: Int = Int(trimmed), v > 0 {
|
||||
pendingTimeBeatType = v
|
||||
// Back-compat: also update the tuple from the first <time>.
|
||||
if !sawTimeSignature {
|
||||
timeSignature = (timeSignature.0, v)
|
||||
}
|
||||
}
|
||||
|
||||
case "time":
|
||||
// Commit the completed <time> block.
|
||||
// Every <time> in the first part is recorded in parsedMeterByMeasure
|
||||
// (keyed by 1-based measure number, first-wins per measure) so that
|
||||
// parsedScore() can build a multi-segment MeterMap.
|
||||
// The back-compat timeSignature tuple is locked by sawTimeSignature
|
||||
// (unchanged behaviour: first <time> wins for the tuple).
|
||||
inTime = false
|
||||
if isFirstPart
|
||||
&& pendingTimeBeatCount > 0
|
||||
&& pendingTimeBeatType > 0
|
||||
{
|
||||
let measureKey: Int = max(1, currentMeasureNumber)
|
||||
if parsedMeterByMeasure[measureKey] == nil {
|
||||
// Default-grouping initializer — MusicXML carries no beat
|
||||
// grouping, so grouping is re-inferred from num/den.
|
||||
parsedMeterByMeasure[measureKey] = TimeSignature(
|
||||
pendingTimeBeatCount,
|
||||
pendingTimeBeatType
|
||||
)
|
||||
}
|
||||
}
|
||||
// Reset per-<time>-block accumulators.
|
||||
pendingTimeBeatCount = 0
|
||||
pendingTimeBeatType = 0
|
||||
sawTimeSignature = true
|
||||
|
||||
case "fifths" where inKey:
|
||||
if let v: Int = Int(trimmed) {
|
||||
keyFifths = v
|
||||
}
|
||||
|
||||
case "mode" where inKey:
|
||||
keyMode = trimmed
|
||||
|
||||
case "key":
|
||||
inKey = false
|
||||
// Store the parsed key per part (first-key-per-part wins for
|
||||
// each individual part). The global `keySignature` / `sawKeySignature`
|
||||
// still record the first key seen document-wide (first-part's first key)
|
||||
// so the Score-level key is unchanged for non-transposing scores.
|
||||
let parsedMode: KeySignature.Mode = (keyMode == "minor") ? .minor : .major
|
||||
// Clamp fifths to -7...7 defensively (malformed documents may have out-of-range values).
|
||||
let parsedFifths: Int = max(-7, min(7, keyFifths))
|
||||
let parsedKey: KeySignature = KeySignature(fifths: parsedFifths, mode: parsedMode)
|
||||
if let idx: Int = currentPartIndex, parts[idx].keySignature == nil {
|
||||
// First key in this part — record it on the builder.
|
||||
parts[idx].keySignature = parsedKey
|
||||
}
|
||||
// First-wins document-wide: also set the global key from the very first
|
||||
// <key> element seen (for backward-compat with Score.keySignature).
|
||||
if !sawKeySignature {
|
||||
keySignature = parsedKey
|
||||
sawKeySignature = true
|
||||
}
|
||||
|
||||
case "sign" where inClef:
|
||||
clefSign = trimmed
|
||||
|
||||
case "line" where inClef:
|
||||
if let v: Int = Int(trimmed) {
|
||||
clefLine = v
|
||||
}
|
||||
|
||||
case "clef-octave-change" where inClef:
|
||||
if let v: Int = Int(trimmed) {
|
||||
clefOctaveChange = v
|
||||
}
|
||||
|
||||
case "clef":
|
||||
inClef = false
|
||||
// Map the parsed (sign, line, octaveChange) back to a Clef case.
|
||||
if let idx: Int = currentPartIndex {
|
||||
let parsedClef: Clef = _MusicXMLParser.clefFromParsed(
|
||||
sign: clefSign,
|
||||
line: clefLine,
|
||||
octaveChange: clefOctaveChange
|
||||
)
|
||||
if !parts[idx].clefWasSet {
|
||||
// First clef in the part → the part-level (measure-1) clef.
|
||||
parts[idx].clef = parsedClef
|
||||
parts[idx].clefWasSet = true
|
||||
} else {
|
||||
// A later <clef> is a mid-voice clef change. Commit it as a
|
||||
// zero-duration `.clefChange` entry at the current cursor beat,
|
||||
// in document order (between the surrounding notes). Flush any
|
||||
// buffered chord first so ordering is preserved (mirrors the
|
||||
// <forward> rest-insertion path).
|
||||
//
|
||||
// Assumptions (acceptable for the encoder's own output; both
|
||||
// hold for every Lyrebird-emitted document):
|
||||
// • `noteContext.voice` is the voice that owns this clef change. In a
|
||||
// multi-voice part a mid-clef between two voices' streams is
|
||||
// attributed to the most-recently-seen voice; this only
|
||||
// affects sort-tiebreaker ordering, never sounding output.
|
||||
// • `currentDivisions` is current. A <divisions> change in the
|
||||
// same <attributes> block as a mid <clef> would stale the
|
||||
// beat; Lyrebird only emits <divisions> in measure-1.
|
||||
flushPendingChord(into: idx)
|
||||
let beatNow: Fraction = Fraction(
|
||||
num: Int64(parts[idx].absoluteCursorDivisions),
|
||||
den: Int64(currentDivisions)
|
||||
)
|
||||
parts[idx].entries.append(_PartEntry(
|
||||
beat: beatNow,
|
||||
voice: noteContext.voice,
|
||||
element: .clefChange(parsedClef)
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
case "diatonic" where inTranspose:
|
||||
if let v: Int = Int(trimmed) {
|
||||
transposeDiatonic = v
|
||||
}
|
||||
|
||||
case "chromatic" where inTranspose:
|
||||
if let v: Int = Int(trimmed) {
|
||||
transposeChromatic = v
|
||||
}
|
||||
|
||||
case "octave-change" where inTranspose:
|
||||
if let v: Int = Int(trimmed) {
|
||||
transposeOctaveChange = v
|
||||
}
|
||||
|
||||
case "transpose":
|
||||
inTranspose = false
|
||||
// Commit the parsed transpose to the current part builder.
|
||||
// First-transpose-per-part wins (mid-part transpose changes are ignored).
|
||||
if let idx: Int = currentPartIndex, parts[idx].transpose == nil {
|
||||
parts[idx].transpose = Transpose(
|
||||
chromatic: transposeChromatic,
|
||||
diatonic: transposeDiatonic,
|
||||
octaveChange: transposeOctaveChange
|
||||
)
|
||||
}
|
||||
|
||||
case "per-minute":
|
||||
if let v: Double = Double(trimmed), v > 0 {
|
||||
if !sawTempo {
|
||||
bpm = v
|
||||
sawTempo = true
|
||||
}
|
||||
// For mid-piece directions (measure >= 2, first part only),
|
||||
// capture from <per-minute>. The FIRST tempo element seen in document
|
||||
// order within this direction block wins (`pendingDirectionTempo == nil`
|
||||
// guard); the encoder emits <per-minute> before <sound tempo>, so
|
||||
// per-minute wins for Lyrebird-produced documents.
|
||||
if isFirstPart && currentMeasureNumber >= 2 && inDirection && pendingDirectionTempo == nil {
|
||||
pendingDirectionTempo = v
|
||||
}
|
||||
}
|
||||
|
||||
case "step":
|
||||
if inPitch { noteContext.pitchStep = trimmed }
|
||||
|
||||
case "alter":
|
||||
if inPitch, let v: Double = Double(trimmed) {
|
||||
noteContext.pitchAlter = v
|
||||
}
|
||||
|
||||
case "octave":
|
||||
if inPitch, let v: Int = Int(trimmed) {
|
||||
noteContext.pitchOctave = v
|
||||
}
|
||||
|
||||
case "pitch":
|
||||
inPitch = false
|
||||
|
||||
case "duration":
|
||||
if let v: Int = Int(trimmed), v >= 0 {
|
||||
if inBackup || inForward {
|
||||
backupForwardDivisions = v
|
||||
} else {
|
||||
noteContext.durationDivisions = v
|
||||
}
|
||||
}
|
||||
|
||||
case "backup":
|
||||
inBackup = false
|
||||
// Rewind the absolute cursor for the current part.
|
||||
if let idx: Int = currentPartIndex, backupForwardDivisions > 0 {
|
||||
parts[idx].absoluteCursorDivisions = max(
|
||||
0,
|
||||
parts[idx].absoluteCursorDivisions - backupForwardDivisions
|
||||
)
|
||||
}
|
||||
backupForwardDivisions = 0
|
||||
|
||||
case "forward":
|
||||
inForward = false
|
||||
// Advance the absolute cursor for the current part by inserting a
|
||||
// rest element. The rest ensures single-voice sequential flatten()
|
||||
// positions subsequent notes correctly. Multi-voice reconstruction
|
||||
// uses the stored absolute beat instead, but the rest is harmless.
|
||||
if let idx: Int = currentPartIndex, backupForwardDivisions > 0 {
|
||||
let beatBefore: Fraction = Fraction(
|
||||
num: Int64(parts[idx].absoluteCursorDivisions),
|
||||
den: Int64(currentDivisions)
|
||||
)
|
||||
let fwdDur: NoteDuration = .fraction(Fraction(
|
||||
num: Int64(backupForwardDivisions),
|
||||
den: Int64(currentDivisions)
|
||||
))
|
||||
let restEntry: _PartEntry = _PartEntry(
|
||||
beat: beatBefore,
|
||||
voice: noteContext.voice,
|
||||
element: .rest(duration: fwdDur)
|
||||
)
|
||||
// Flush any pending chord before inserting the rest.
|
||||
flushPendingChord(into: idx)
|
||||
parts[idx].entries.append(restEntry)
|
||||
parts[idx].absoluteCursorDivisions += backupForwardDivisions
|
||||
}
|
||||
backupForwardDivisions = 0
|
||||
|
||||
case "voice":
|
||||
if let v: Int = Int(trimmed), v >= 1 {
|
||||
noteContext.voice = v
|
||||
}
|
||||
|
||||
case "staff" where !inBarline:
|
||||
// <staff> inside a <note> element — which staff the note belongs to.
|
||||
// Parsed for completeness but currently discarded: `_PartEntry` has no
|
||||
// staff field, so decoded notes are not regrouped into Staff blocks
|
||||
// (documented-lossy; see the <staves> case). Not to be confused with
|
||||
// the unrelated <staves> inside <attributes>.
|
||||
if let v: Int = Int(trimmed), v >= 1 {
|
||||
noteContext.staff = v
|
||||
}
|
||||
|
||||
case "other-dynamics" where inDynamics:
|
||||
// `<other-dynamics>` text is a raw velocity Double encoded by the
|
||||
// Lyrebird encoder (e.g. "0.42" for `.raw(0.42)`). Parse as Double
|
||||
// and build `.raw(_:)` if valid; ignore otherwise.
|
||||
if let v: Double = Double(trimmed), v.isFinite {
|
||||
pendingDynamic = .raw(v)
|
||||
}
|
||||
|
||||
case "dynamics":
|
||||
inDynamics = false
|
||||
|
||||
case "direction-type":
|
||||
inDirectionType = false
|
||||
|
||||
case "direction":
|
||||
inDirection = false
|
||||
// Commit the pending dynamic (if any) as the new current dynamic.
|
||||
if let dyn: Dynamic = pendingDynamic {
|
||||
currentDynamic = dyn
|
||||
}
|
||||
pendingDynamic = nil
|
||||
|
||||
// Commit pending pedal mark as a zero-duration entry at the current cursor.
|
||||
// Pedal marks are notation-only — they do not advance the cursor.
|
||||
if let kind: PedalKind = pendingPedalKind, let partIdx: Int = currentPartIndex {
|
||||
flushPendingChord(into: partIdx)
|
||||
let beatNow: Fraction = Fraction(
|
||||
num: Int64(parts[partIdx].absoluteCursorDivisions),
|
||||
den: Int64(currentDivisions)
|
||||
)
|
||||
parts[partIdx].entries.append(_PartEntry(
|
||||
beat: beatNow,
|
||||
voice: noteContext.voice,
|
||||
element: .pedal(kind)
|
||||
))
|
||||
}
|
||||
pendingPedalKind = nil
|
||||
|
||||
// Commit mid-piece tempo change.
|
||||
// Record the first tempo seen in this direction block for this measure
|
||||
// (first-wins: if `parsedTempoChangesByMeasure` already has a value for
|
||||
// this measure number from an earlier direction, leave it untouched).
|
||||
if isFirstPart && currentMeasureNumber >= 2 {
|
||||
if let v: Double = pendingDirectionTempo {
|
||||
if parsedTempoChangesByMeasure[currentMeasureNumber] == nil {
|
||||
parsedTempoChangesByMeasure[currentMeasureNumber] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
pendingDirectionTempo = nil
|
||||
|
||||
// Commit pending wedge state.
|
||||
// A wedge-start is queued to attach to the NEXT flushed note/chord.
|
||||
// A wedge-stop attaches to the LAST flushed entry in the active wedge voice.
|
||||
if let startKind: WedgeKind = pendingWedgeStart {
|
||||
pendingWedgeStartForNextNote = startKind
|
||||
// Mark the active voice so subsequent notes are within the span.
|
||||
// We use noteContext.voice (the voice of the note that will follow this direction).
|
||||
wedgeActiveByVoice[noteContext.voice] = startKind
|
||||
pendingWedgeStart = nil
|
||||
}
|
||||
if pendingWedgeStop {
|
||||
pendingWedgeStop = false
|
||||
// Attach the stop to the most-recently-flushed entry whose voice
|
||||
// has an open wedge. ASSUMPTION: at most one wedge is open per part
|
||||
// at a time (true for Lyrebird's own encoder, which marks wedge
|
||||
// spans per voice with no cross-voice overlap). If a malformed
|
||||
// third-party document opened two wedges in different voices
|
||||
// simultaneously, this scan would close whichever has the
|
||||
// latest entry — acceptable for the supported feature scope.
|
||||
if let partIdx: Int = currentPartIndex {
|
||||
for i: Int in stride(from: parts[partIdx].entries.count - 1, through: 0, by: -1) {
|
||||
let entry: _PartEntry = parts[partIdx].entries[i]
|
||||
let entryVoice: Int = entry.voice
|
||||
if wedgeActiveByVoice[entryVoice] != nil {
|
||||
parts[partIdx].entries[i].wedgeStop = true
|
||||
wedgeActiveByVoice[entryVoice] = nil
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
case "articulations":
|
||||
inArticulations = false
|
||||
|
||||
case "notations":
|
||||
inNotations = false
|
||||
|
||||
case "note":
|
||||
commitCurrentNote()
|
||||
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
|
||||
if rootError == nil {
|
||||
rootError = .xmlParseFailed(String(describing: parseError))
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -14,438 +14,284 @@ internal final class _MusicXMLParser: NSObject, XMLParserDelegate {
|
||||
|
||||
// MARK: - Output
|
||||
|
||||
private(set) var parts: [_PartBuilder] = []
|
||||
private(set) var bpm: Double = _MusicXMLParser.defaultBPM
|
||||
private(set) var timeSignature: (Int, Int) = (4, 4)
|
||||
private(set) var sawTempo: Bool = false
|
||||
private(set) var sawTimeSignature: Bool = false
|
||||
private(set) var rootError: MusicXMLError?
|
||||
var parts: [_PartBuilder] = []
|
||||
var bpm: Double = _MusicXMLParser.defaultBPM
|
||||
var timeSignature: (Int, Int) = (4, 4)
|
||||
var keySignature: KeySignature = .cMajor
|
||||
var sawTempo: Bool = false
|
||||
var sawTimeSignature: Bool = false
|
||||
var sawKeySignature: Bool = false
|
||||
var rootError: MusicXMLError?
|
||||
|
||||
// MARK: - Parsing state
|
||||
|
||||
/// Element name stack — used to scope text accumulation.
|
||||
private var elementStack: [String] = []
|
||||
var elementStack: [String] = []
|
||||
/// Accumulated text between current element's open and close tags.
|
||||
private var currentText: String = ""
|
||||
var currentText: String = ""
|
||||
|
||||
// <part-list> / <score-part> tracking
|
||||
private var inPartList: Bool = false
|
||||
private var partListEntries: [(id: String, name: String)] = []
|
||||
private var currentScorePartID: String?
|
||||
private var currentScorePartName: String?
|
||||
var inPartList: Bool = false
|
||||
var partListEntries: [(id: String, name: String)] = []
|
||||
var currentScorePartID: String?
|
||||
var currentScorePartName: String?
|
||||
|
||||
// <part> tracking
|
||||
private var currentPartIndex: Int? // index into `parts`
|
||||
private var currentDivisions: Int = _MusicXMLParser.defaultDivisions
|
||||
var currentPartIndex: Int? // index into `parts`
|
||||
var currentDivisions: Int = _MusicXMLParser.defaultDivisions
|
||||
|
||||
/// Buffer of chord-mate pitches accumulating from successive `<note>
|
||||
/// <chord/>` elements. Flushed as a single `.chord(...)` element
|
||||
/// when the next non-chord note (or end of part) arrives.
|
||||
private var pendingChordPitches: [Pitch] = []
|
||||
/// Articulation / duration / voice carried by the chord lead note.
|
||||
private var pendingChordDuration: Double = 0.0
|
||||
private var pendingChordVoice: Int = 0
|
||||
private var pendingChordArticulation: Articulation = .normal
|
||||
var pendingChordPitches: [Pitch] = []
|
||||
/// Articulation / duration / voice / dynamic carried by the chord lead note.
|
||||
var pendingChordDuration: NoteDuration = .zero
|
||||
var pendingChordVoice: Int = 0
|
||||
var pendingChordArticulation: Articulation = .normal
|
||||
/// Dynamic captured at chord lead-note commit time (from `currentDynamic`).
|
||||
/// Stored here so it is not overwritten if a `<direction>` arrives between
|
||||
/// the lead note's commit and the flush.
|
||||
var pendingChordDynamic: Dynamic = .mf
|
||||
/// Absolute beat of the chord lead note (captured from the cursor at lead-note commit time).
|
||||
var pendingChordBeat: Fraction = .zero
|
||||
/// When the most-recent non-chord tie-stop lead note merged into a `.chord`
|
||||
/// element, this records `(partIndex, elementIndex)` so that subsequent
|
||||
/// chord-mate tie-stops in the same note group can detect that the chord
|
||||
/// duration was already extended and must not merge again.
|
||||
var lastMergedChordLocation: (partIndex: Int, elementIndex: Int)? = nil
|
||||
|
||||
// <note> tracking
|
||||
private var noteIsRest: Bool = false
|
||||
private var noteIsChord: Bool = false
|
||||
private var notePitchStep: String?
|
||||
private var notePitchAlter: Double = 0.0
|
||||
private var notePitchOctave: Int = _MusicXMLParser.defaultMidiOctave
|
||||
private var noteDurationDivisions: Int = 0
|
||||
private var noteVoice: Int = 1
|
||||
private var noteArticulation: Articulation = .normal
|
||||
private var inPitch: Bool = false
|
||||
private var inArticulations: Bool = false
|
||||
private var inNotations: Bool = false
|
||||
private var inTime: Bool = false
|
||||
//
|
||||
// All per-`<note>` accumulator state lives in ``_NoteContext`` and is reset
|
||||
// in one assignment (`noteContext = _NoteContext()`) at each `<note>` open,
|
||||
// then read in `commitCurrentNote()` — the "reset on open, commit on close"
|
||||
// pattern. The `in…` nesting flags below are NOT per-note (they toggle on
|
||||
// their own element open/close) and stay on the class.
|
||||
var noteContext: _NoteContext = _NoteContext()
|
||||
var inPitch: Bool = false
|
||||
var inArticulations: Bool = false
|
||||
var inNotations: Bool = false
|
||||
var inTime: Bool = false
|
||||
var inKey: Bool = false
|
||||
var keyFifths: Int = 0
|
||||
var keyMode: String = "major"
|
||||
var inClef: Bool = false
|
||||
var clefSign: String = ""
|
||||
var clefLine: Int? = nil
|
||||
var clefOctaveChange: Int? = nil
|
||||
// <transpose> accumulation state (per part, reset in <part> open).
|
||||
var inTranspose: Bool = false
|
||||
var transposeDiatonic: Int = 0
|
||||
var transposeChromatic: Int = 0
|
||||
var transposeOctaveChange: Int = 0
|
||||
|
||||
// Pedal direction tracking.
|
||||
//
|
||||
// `<pedal type="start|stop" line="yes"/>` marks sustain-pedal marks.
|
||||
// Parsed inside a `<direction>` block and committed as a `.pedal(kind)`
|
||||
// zero-duration entry on `</direction>`.
|
||||
//
|
||||
// - `pendingPedalKind`: non-nil when a `<pedal>` element with a
|
||||
// recognised `type` was seen in the current direction block.
|
||||
var pendingPedalKind: PedalKind? = nil
|
||||
|
||||
// Slur span tracking (span-based, no `continue`).
|
||||
//
|
||||
// A slur span is a pair of ONE `<slur type="start"/>` and ONE
|
||||
// `<slur type="stop"/>` (same `number="1"`). Interior notes carry no `<slur>`.
|
||||
//
|
||||
// Span tracking state that persists across note elements, keyed by
|
||||
// MusicXML voice number (1-based). Using a per-voice dictionary rather than
|
||||
// a single Bool prevents a slur open in voice 1 from contaminating voice 2
|
||||
// after a `<backup>` rewinds the cursor to the start of the measure.
|
||||
//
|
||||
// - `slurActiveByVoice[v]` is `true` from the moment a `start` is seen in
|
||||
// voice `v` until the corresponding `stop` is seen in voice `v`.
|
||||
// - While `slurActiveByVoice[v] == true`, every committed non-stop note in
|
||||
// voice `v` is marked `.legato`.
|
||||
// - On `stop` in voice `v`: the stop note itself is NOT marked legato;
|
||||
// `slurActiveByVoice[v]` is cleared.
|
||||
//
|
||||
// The per-note transient slur flags (`hasSlurStart` / `hasSlurStop`, this
|
||||
// note element carries `<slur type="start|stop"/>`) live in ``_NoteContext``.
|
||||
var slurActiveByVoice: [Int: Bool] = [:]
|
||||
|
||||
// Backup / forward cursor tracking (multi-voice support).
|
||||
//
|
||||
// `<backup><duration>D</duration></backup>` rewinds the absolute part cursor
|
||||
// by D divisions so that a subsequent voice can write from the beginning of
|
||||
// the rewound position.
|
||||
// `<forward><duration>D</duration></forward>` advances the cursor by D
|
||||
// divisions (used to skip silences).
|
||||
//
|
||||
// `inBackup` / `inForward` flag which element's `<duration>` text to
|
||||
// accumulate into `backupForwardDivisions`.
|
||||
var inBackup: Bool = false
|
||||
var inForward: Bool = false
|
||||
var backupForwardDivisions: Int = 0
|
||||
|
||||
// Dynamic direction tracking.
|
||||
//
|
||||
// A `<direction>/<direction-type>/<dynamics>` block sets the current
|
||||
// dynamic that applies to subsequently-committed notes/chords (sticky).
|
||||
// A `<direction>` without a `<dynamics>` child is ignored for dynamic
|
||||
// purposes. Reset at part start to `.mf`.
|
||||
//
|
||||
// - `inDirection`: true from `<direction>` open to `</direction>`.
|
||||
// - `inDirectionType`: true from `<direction-type>` open to close.
|
||||
// - `inDynamics`: true from `<dynamics>` open to close.
|
||||
// - `pendingDynamic`: dynamic parsed from the current `<direction>` block,
|
||||
// or nil if no recognised dynamic was found yet.
|
||||
// - `currentDynamic`: the last committed dynamic (sticky); applied to
|
||||
// the next flushed note/chord.
|
||||
var inDirection: Bool = false
|
||||
var inDirectionType: Bool = false
|
||||
var inDynamics: Bool = false
|
||||
var pendingDynamic: Dynamic? = nil
|
||||
var currentDynamic: Dynamic = .mf
|
||||
|
||||
// Wedge (hairpin) span tracking.
|
||||
//
|
||||
// `<wedge type="crescendo|diminuendo"/>` marks the start of a wedge span.
|
||||
// `<wedge type="stop"/>` marks the end. Tracked per-voice so that a wedge
|
||||
// in voice 1 does not contaminate voice 2.
|
||||
//
|
||||
// - `wedgeActiveByVoice`: maps voice number → WedgeKind when a wedge span
|
||||
// is currently open for that voice; nil when no span is open.
|
||||
// - `pendingWedgeStart`: wedge start parsed from the current `<direction>`
|
||||
// block (set when `<wedge type="crescendo|diminuendo"/>` is seen).
|
||||
// - `pendingWedgeStop`: true when `<wedge type="stop"/>` is seen in the
|
||||
// current `<direction>` block.
|
||||
//
|
||||
// On `</direction>`:
|
||||
// - If `pendingWedgeStart` is non-nil: record as `pendingWedgeStartForNextNote`,
|
||||
// which is attached to the next committed note/chord's _PartEntry.
|
||||
// - If `pendingWedgeStop`: attach a wedge-stop annotation to the LAST
|
||||
// committed entry that is part of the active wedge span (the entry that
|
||||
// was most recently flushed for the active voice).
|
||||
//
|
||||
// `pendingWedgeStartForNextNote` is consumed on the next `flushPendingChord`.
|
||||
var wedgeActiveByVoice: [Int: WedgeKind] = [:]
|
||||
var pendingWedgeStart: WedgeKind? = nil
|
||||
var pendingWedgeStop: Bool = false
|
||||
var pendingWedgeStartForNextNote: WedgeKind? = nil
|
||||
|
||||
// Anacrusis tracking.
|
||||
//
|
||||
// When the first measure of the first part is `implicit="yes"` it is the
|
||||
// pickup (measure 0). `currentMeasureNumber` is set to 0 for it (see the
|
||||
// `<measure>` handler for the adjustment logic) and subsequent full bars
|
||||
// count as 1..N — so all existing `parsedMeterByMeasure` / repeat /
|
||||
// tempo-change maps stay correctly 1-based.
|
||||
//
|
||||
// `pickupCursorDivisionsAtEnd`: cursor position (in divisions) of the first
|
||||
// part's absolute cursor at the moment the implicit measure closes. Captured
|
||||
// via `absoluteCursorDivisions` on the first part builder. Used to compute
|
||||
// the resolved pickup Fraction (cursor / currentDivisions at that moment)
|
||||
// in `parsedScore()`.
|
||||
//
|
||||
// - `firstMeasureIsImplicit`: set when the very first `<measure>` open of
|
||||
// the first part carries `implicit="yes"`. Read-only after measure 0 ends.
|
||||
// - `firstMeasureEnded`: set after the first `<measure>` end is processed.
|
||||
// Prevents a second `<measure>` in the same part from being treated as
|
||||
// another implicit measure.
|
||||
// - `pickupCursorDivisionsAtEnd`: divisions cursor captured at the moment
|
||||
// `</measure>` closes the first (implicit) measure of the first part.
|
||||
var firstMeasureIsImplicit: Bool = false
|
||||
var firstMeasureEnded: Bool = false
|
||||
var pickupCursorDivisionsAtEnd: Int = 0
|
||||
var pickupDivisions: Int = _MusicXMLParser.defaultDivisions
|
||||
|
||||
// Repeat / ending tracking.
|
||||
//
|
||||
// Read from the FIRST part only (all parts share the same barline structure).
|
||||
// `isFirstPart` is set to false after the first part's `</part>` is seen.
|
||||
//
|
||||
// - `currentMeasureNumber`: normally 1-based; when a pickup (measure 0) is
|
||||
// present the counter starts at 0 for the implicit measure, then 1..N for
|
||||
// full bars. Reset to 0 at each `<part>` open; the pickup-adjustment
|
||||
// subtracts 1 before the first `+= 1` so the result is 0.
|
||||
// - `inBarline`: true from `<barline>` open to `</barline>`.
|
||||
// - `barlineLocation`: "left" or "right" from the `location` attribute.
|
||||
// - `barlineHasRepeatForward`: true when a `<repeat direction="forward"/>` was
|
||||
// seen inside the current `<barline>`.
|
||||
// - `barlineHasRepeatBackward`: true when a `<repeat direction="backward"/>` was seen.
|
||||
// - `barlineEndingNumber`: the `number` attribute of `<ending>` (0 = none seen).
|
||||
// - `barlineEndingType`: the `type` attribute of `<ending>` ("start", "stop",
|
||||
// "discontinue").
|
||||
//
|
||||
// Accumulated repeat state (built from first-part barlines):
|
||||
// - `parsedForwardRepeatMeasures`
|
||||
// - `parsedBackwardRepeatMeasures`
|
||||
// - `pendingEndingStarts`: number → startMeasure, waiting for a matching stop.
|
||||
// - `parsedEndings`
|
||||
var isFirstPart: Bool = true
|
||||
var currentMeasureNumber: Int = 0
|
||||
var inBarline: Bool = false
|
||||
var barlineLocation: String = ""
|
||||
var barlineHasRepeatForward: Bool = false
|
||||
var barlineHasRepeatBackward: Bool = false
|
||||
var barlineEndingNumber: Int = 0
|
||||
var barlineEndingType: String = ""
|
||||
|
||||
var parsedForwardRepeatMeasures: Set<Int> = []
|
||||
var parsedBackwardRepeatMeasures: Set<Int> = []
|
||||
/// Volta starts waiting for a matching stop: endingNumber → startMeasure.
|
||||
var pendingEndingStarts: [Int: Int] = [:]
|
||||
var parsedEndings: [Ending] = []
|
||||
|
||||
// Mid-piece tempo-change tracking.
|
||||
//
|
||||
// Read from the FIRST part only (all parts share the same tempo directions).
|
||||
// Within each `<direction>` block, `pendingDirectionTempo` accumulates the
|
||||
// first tempo value seen — either from `<metronome><per-minute>` (preferred)
|
||||
// or from `<sound tempo="X"/>`. On `</direction>`, if the current measure is
|
||||
// >= 2 and the value is non-nil, a `TempoChange` is recorded.
|
||||
//
|
||||
// `seenTempoInCurrentDirection` prevents a single direction block that carries
|
||||
// BOTH `<per-minute>` AND `<sound tempo>` from recording two changes.
|
||||
// - `pendingDirectionTempo`: nil at direction start; set to the first
|
||||
// tempo value read inside this direction block.
|
||||
var pendingDirectionTempo: Double? = nil
|
||||
/// Accumulated mid-piece tempo changes, keyed by measure number (first-wins).
|
||||
var parsedTempoChangesByMeasure: [Int: Double] = [:]
|
||||
|
||||
// Mid-piece meter-change tracking.
|
||||
//
|
||||
// Read from the FIRST part only (all parts share the same time-signature
|
||||
// attributes). Every `<time>` block from the first part is recorded here so
|
||||
// that the resulting `MeterMap` can express mid-piece meter changes.
|
||||
//
|
||||
// Per-`<time>` accumulation:
|
||||
// - `pendingTimeBeatCount`: the `<beats>` value parsed inside the CURRENT
|
||||
// `<time>` block (0 = not yet seen).
|
||||
// - `pendingTimeBeatType`: the `<beat-type>` value parsed inside the CURRENT
|
||||
// `<time>` block (0 = not yet seen).
|
||||
//
|
||||
// On `</time>` the pair is committed to `parsedMeterByMeasure` keyed by the
|
||||
// current 1-based measure number (first-wins per measure — a measure cannot
|
||||
// carry two different `<time>` blocks in well-formed MusicXML). The back-compat
|
||||
// `timeSignature` tuple is still set from the very FIRST `<time>` (unchanged).
|
||||
//
|
||||
// Grouping caveat: MusicXML `<time>` carries no beat-grouping information, so
|
||||
// the `TimeSignature` stored here uses the default-grouping convenience
|
||||
// initializer. A `6/8` authored as simple `[1,1,1,1,1,1]` round-trips as
|
||||
// compound `[3,3]` — numerator/denominator are preserved, grouping is re-inferred.
|
||||
var pendingTimeBeatCount: Int = 0
|
||||
var pendingTimeBeatType: Int = 0
|
||||
/// Accumulated mid-piece meter changes, keyed by 1-based measure number.
|
||||
/// First-wins per measure (a `<time>` block inside measure N is the governing
|
||||
/// signature starting at bar N). Only populated from the first part.
|
||||
var parsedMeterByMeasure: [Int: TimeSignature] = [:]
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
private static let rootElementName: String = "score-partwise"
|
||||
private static let timewiseRootName: String = "score-timewise"
|
||||
private static let defaultBPM: Double = 120.0
|
||||
private static let defaultDivisions: Int = 480
|
||||
/// Octave used as the per-note reset for `notePitchOctave` before `<octave>` is read.
|
||||
/// `4` is the middle-C octave in MIDI / MusicXML conventions.
|
||||
private static let defaultMidiOctave: Int = 4
|
||||
static let rootElementName: String = "score-partwise"
|
||||
static let timewiseRootName: String = "score-timewise"
|
||||
static let defaultBPM: Double = 120.0
|
||||
static let defaultDivisions: Int = 480
|
||||
/// Octave used as the per-note reset for ``_NoteContext/pitchOctave`` before
|
||||
/// `<octave>` is read. `4` is the middle-C octave in MIDI / MusicXML conventions.
|
||||
static let defaultMidiOctave: Int = 4
|
||||
|
||||
// MARK: - Public entry
|
||||
|
||||
func parsedScore() throws -> Score {
|
||||
if let err: MusicXMLError = rootError { throw err }
|
||||
|
||||
guard !parts.isEmpty else {
|
||||
// Tolerate empty documents — produce an empty Score rather
|
||||
// than throwing, so very-minimal MusicXML still parses.
|
||||
return Score(
|
||||
bpm: bpm,
|
||||
timeSignature: timeSignature,
|
||||
parts: []
|
||||
)
|
||||
}
|
||||
|
||||
let scoreParts: [ScorePart] = parts.map { builder in
|
||||
ScorePart(
|
||||
name: builder.name,
|
||||
channel: 0,
|
||||
elements: builder.elements
|
||||
)
|
||||
}
|
||||
return Score(
|
||||
bpm: bpm,
|
||||
timeSignature: timeSignature,
|
||||
parts: scoreParts
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - XMLParserDelegate
|
||||
|
||||
func parser(
|
||||
_ parser: XMLParser,
|
||||
didStartElement elementName: String,
|
||||
namespaceURI: String?,
|
||||
qualifiedName qName: String?,
|
||||
attributes attributeDict: [String: String] = [:]
|
||||
) {
|
||||
elementStack.append(elementName)
|
||||
currentText = ""
|
||||
|
||||
// Root validation
|
||||
if elementStack.count == 1 {
|
||||
if elementName == _MusicXMLParser.timewiseRootName {
|
||||
rootError = .unsupportedTimewiseDocument
|
||||
parser.abortParsing()
|
||||
return
|
||||
}
|
||||
guard elementName == _MusicXMLParser.rootElementName else {
|
||||
rootError = .unsupportedRoot(elementName)
|
||||
parser.abortParsing()
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
switch elementName {
|
||||
case "part-list":
|
||||
inPartList = true
|
||||
|
||||
case "score-part" where inPartList:
|
||||
currentScorePartID = attributeDict["id"]
|
||||
currentScorePartName = nil
|
||||
|
||||
case "part" where !inPartList:
|
||||
// `<part id="P1">`. Resolve to a builder using the part-list.
|
||||
let id: String = attributeDict["id"] ?? ""
|
||||
if let entry: (id: String, name: String) = partListEntries.first(where: { $0.id == id }) {
|
||||
let builder: _PartBuilder = _PartBuilder(id: entry.id, name: entry.name)
|
||||
parts.append(builder)
|
||||
currentPartIndex = parts.count - 1
|
||||
} else {
|
||||
// No matching score-part — synthesize a default builder so
|
||||
// events still land somewhere.
|
||||
let builder: _PartBuilder = _PartBuilder(id: id, name: "Part \(parts.count + 1)")
|
||||
parts.append(builder)
|
||||
currentPartIndex = parts.count - 1
|
||||
}
|
||||
currentDivisions = _MusicXMLParser.defaultDivisions
|
||||
|
||||
case "note":
|
||||
// Reset per-note state.
|
||||
noteIsRest = false
|
||||
noteIsChord = false
|
||||
notePitchStep = nil
|
||||
notePitchAlter = 0.0
|
||||
notePitchOctave = _MusicXMLParser.defaultMidiOctave
|
||||
noteDurationDivisions = 0
|
||||
noteVoice = 1
|
||||
noteArticulation = .normal
|
||||
|
||||
case "rest":
|
||||
noteIsRest = true
|
||||
|
||||
case "chord":
|
||||
noteIsChord = true
|
||||
|
||||
case "pitch":
|
||||
inPitch = true
|
||||
|
||||
case "notations":
|
||||
inNotations = true
|
||||
|
||||
case "time":
|
||||
inTime = true
|
||||
|
||||
case "articulations":
|
||||
inArticulations = true
|
||||
|
||||
case "staccato" where inArticulations: noteArticulation = .staccato
|
||||
case "staccatissimo" where inArticulations: noteArticulation = .staccatissimo
|
||||
case "tenuto" where inArticulations: noteArticulation = .tenuto
|
||||
case "accent" where inArticulations: noteArticulation = .accent
|
||||
case "strong-accent" where inArticulations: noteArticulation = .marcato
|
||||
|
||||
case "slur" where inNotations:
|
||||
// `<slur type="start"/>` (or "continue") sets legato on this note.
|
||||
// Whole-span legato run tracking is deferred — every slur-bearing
|
||||
// note is marked `.legato` so single-note round-trips work.
|
||||
if let kind: String = attributeDict["type"], kind == "start" || kind == "continue" {
|
||||
noteArticulation = .legato
|
||||
}
|
||||
|
||||
case "sound":
|
||||
// Tempo can arrive as an attribute on `<sound tempo="X"/>` (common
|
||||
// in MuseScore ≤ 3 and MIDI-to-MusicXML converters that omit the
|
||||
// metronome block) OR as text inside `<metronome><per-minute>`.
|
||||
// First-write-wins via `sawTempo`.
|
||||
if !sawTempo, let t: String = attributeDict["tempo"], let v: Double = Double(t), v > 0 {
|
||||
bpm = v
|
||||
sawTempo = true
|
||||
}
|
||||
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
func parser(
|
||||
_ parser: XMLParser,
|
||||
foundCharacters string: String
|
||||
) {
|
||||
currentText += string
|
||||
}
|
||||
|
||||
func parser(
|
||||
_ parser: XMLParser,
|
||||
didEndElement elementName: String,
|
||||
namespaceURI: String?,
|
||||
qualifiedName qName: String?
|
||||
) {
|
||||
defer {
|
||||
if !elementStack.isEmpty { elementStack.removeLast() }
|
||||
currentText = ""
|
||||
}
|
||||
let trimmed: String = currentText.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
|
||||
switch elementName {
|
||||
case "part-list":
|
||||
inPartList = false
|
||||
|
||||
case "score-part" where inPartList:
|
||||
if let id: String = currentScorePartID {
|
||||
let name: String = currentScorePartName ?? "Part \(partListEntries.count + 1)"
|
||||
partListEntries.append((id: id, name: name))
|
||||
}
|
||||
currentScorePartID = nil
|
||||
currentScorePartName = nil
|
||||
|
||||
case "part-name" where inPartList:
|
||||
currentScorePartName = trimmed
|
||||
|
||||
case "part" where currentPartIndex != nil:
|
||||
// Flush any chord still pending at end-of-part.
|
||||
if let idx: Int = currentPartIndex {
|
||||
flushPendingChord(into: idx)
|
||||
}
|
||||
currentPartIndex = nil
|
||||
|
||||
case "divisions":
|
||||
if let v: Int = Int(trimmed), v > 0 {
|
||||
currentDivisions = v
|
||||
}
|
||||
|
||||
case "beats" where inTime && !sawTimeSignature:
|
||||
if let v: Int = Int(trimmed), v > 0 {
|
||||
timeSignature = (v, timeSignature.1)
|
||||
}
|
||||
|
||||
case "beat-type" where inTime && !sawTimeSignature:
|
||||
if let v: Int = Int(trimmed), v > 0 {
|
||||
timeSignature = (timeSignature.0, v)
|
||||
}
|
||||
|
||||
case "time":
|
||||
// Lock in the first complete <time> block. Subsequent <time>
|
||||
// elements (mid-piece time-signature changes) are ignored — Score
|
||||
// carries a single timeSignature value in v1.
|
||||
inTime = false
|
||||
sawTimeSignature = true
|
||||
|
||||
case "per-minute":
|
||||
if !sawTempo, let v: Double = Double(trimmed), v > 0 {
|
||||
bpm = v
|
||||
sawTempo = true
|
||||
}
|
||||
|
||||
case "step":
|
||||
if inPitch { notePitchStep = trimmed }
|
||||
|
||||
case "alter":
|
||||
if inPitch, let v: Double = Double(trimmed) {
|
||||
notePitchAlter = v
|
||||
}
|
||||
|
||||
case "octave":
|
||||
if inPitch, let v: Int = Int(trimmed) {
|
||||
notePitchOctave = v
|
||||
}
|
||||
|
||||
case "pitch":
|
||||
inPitch = false
|
||||
|
||||
case "duration":
|
||||
if let v: Int = Int(trimmed), v >= 0 {
|
||||
noteDurationDivisions = v
|
||||
}
|
||||
|
||||
case "voice":
|
||||
if let v: Int = Int(trimmed), v >= 1 {
|
||||
noteVoice = v
|
||||
}
|
||||
|
||||
case "articulations":
|
||||
inArticulations = false
|
||||
|
||||
case "notations":
|
||||
inNotations = false
|
||||
|
||||
case "note":
|
||||
commitCurrentNote()
|
||||
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
|
||||
if rootError == nil {
|
||||
rootError = .xmlParseFailed(String(describing: parseError))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Note commit
|
||||
|
||||
private func commitCurrentNote() {
|
||||
guard let partIndex: Int = currentPartIndex else { return }
|
||||
let durationBeats: Double = Double(noteDurationDivisions) / Double(currentDivisions)
|
||||
let pitch: Pitch? = (notePitchStep != nil && !noteIsRest)
|
||||
? makePitch(
|
||||
step: notePitchStep ?? "",
|
||||
alter: notePitchAlter,
|
||||
octave: notePitchOctave
|
||||
)
|
||||
: nil
|
||||
|
||||
if noteIsChord {
|
||||
// Chord-mate: append pitch to the pending chord buffer. Cursor
|
||||
// does not advance. If parsing produced no pitch (malformed
|
||||
// chord-mate), drop the entry silently.
|
||||
if let p: Pitch = pitch {
|
||||
pendingChordPitches.append(p)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Non-chord note (lead) — flush any pending chord first.
|
||||
flushPendingChord(into: partIndex)
|
||||
|
||||
if noteIsRest {
|
||||
parts[partIndex].elements.append(
|
||||
.rest(duration: .beats(durationBeats))
|
||||
)
|
||||
} else if let p: Pitch = pitch {
|
||||
// Buffer this note as the chord lead — flushed when the next
|
||||
// chord-non-mate or end-of-part arrives. This lets a `<chord/>`
|
||||
// continuation upgrade the buffered single-note into a multi-
|
||||
// note `.chord(...)` element.
|
||||
pendingChordPitches = [p]
|
||||
pendingChordDuration = durationBeats
|
||||
pendingChordVoice = max(0, noteVoice - 1)
|
||||
pendingChordArticulation = noteArticulation
|
||||
} else {
|
||||
// Unrecognised pitch + not a rest — treat as rest to keep
|
||||
// cursor advancing rather than dropping silently.
|
||||
parts[partIndex].elements.append(
|
||||
.rest(duration: .beats(durationBeats))
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Emit any buffered chord lead + chord-mate pitches as either a
|
||||
/// `.note` (singleton) or `.chord(...)` (multi-pitch) element.
|
||||
private func flushPendingChord(into partIndex: Int) {
|
||||
guard !pendingChordPitches.isEmpty else { return }
|
||||
let dur: NoteDuration = NoteDuration.beats(pendingChordDuration)
|
||||
if pendingChordPitches.count == 1 {
|
||||
parts[partIndex].elements.append(
|
||||
.note(
|
||||
pendingChordPitches[0],
|
||||
duration: dur,
|
||||
dynamic: .mf,
|
||||
articulation: pendingChordArticulation,
|
||||
voice: pendingChordVoice
|
||||
)
|
||||
)
|
||||
} else {
|
||||
parts[partIndex].elements.append(
|
||||
.chord(
|
||||
pendingChordPitches,
|
||||
duration: dur,
|
||||
dynamic: .mf,
|
||||
articulation: pendingChordArticulation,
|
||||
voice: pendingChordVoice
|
||||
)
|
||||
)
|
||||
}
|
||||
pendingChordPitches.removeAll(keepingCapacity: true)
|
||||
}
|
||||
|
||||
/// Build a `Pitch.named(...)` from MusicXML primitives. Returns nil
|
||||
/// when `step` is unrecognised or `alter` is outside the supported
|
||||
/// 50-cent grid.
|
||||
private func makePitch(
|
||||
step: String,
|
||||
alter: Double,
|
||||
octave: Int
|
||||
) -> Pitch? {
|
||||
guard let letter: Letter = _MusicXMLParser.letterForStep(step) else { return nil }
|
||||
guard let accidental: Accidental = _MusicXMLParser.accidentalForAlter(alter) else { return nil }
|
||||
return .named(NoteName(letter: letter, accidental: accidental), octave)
|
||||
}
|
||||
|
||||
private static func letterForStep(_ step: String) -> Letter? {
|
||||
switch step.uppercased() {
|
||||
case "A": return .a
|
||||
case "B": return .b
|
||||
case "C": return .c
|
||||
case "D": return .d
|
||||
case "E": return .e
|
||||
case "F": return .f
|
||||
case "G": return .g
|
||||
default: return nil
|
||||
}
|
||||
}
|
||||
|
||||
private static func accidentalForAlter(_ alter: Double) -> Accidental? {
|
||||
switch alter {
|
||||
case -2.0: return .doubleFlat
|
||||
case -1.5: return .threeQuarterFlat
|
||||
case -1.0: return .flat
|
||||
case -0.5: return .quarterFlat
|
||||
case 0.0: return .natural
|
||||
case 0.5: return .quarterSharp
|
||||
case 1.0: return .sharp
|
||||
case 1.5: return .threeQuarterSharp
|
||||
case 2.0: return .doubleSharp
|
||||
default: return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Mutable per-part accumulator used during parsing.
|
||||
internal struct _PartBuilder {
|
||||
let id: String
|
||||
let name: String
|
||||
var elements: [ScoreElement] = []
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,290 @@
|
||||
// Score+MusicXMLAtoms.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
extension Score {
|
||||
// MARK: - Internal atom representation
|
||||
|
||||
/// The notated kind of a musical event.
|
||||
enum _AtomKind: Equatable {
|
||||
case note(Pitch)
|
||||
case chord([Pitch])
|
||||
case rest
|
||||
/// A grace note — emitted as a `<note><grace>` element with no `<duration>`,
|
||||
/// contributing zero to measure-fill accounting.
|
||||
case grace(Pitch, slashed: Bool)
|
||||
/// A mid-voice clef change — emitted as a mid-measure `<attributes><clef>`
|
||||
/// block with no `<duration>`, contributing zero to measure-fill accounting.
|
||||
case clefChange(Clef)
|
||||
/// A sustain-pedal direction — emitted as a `<direction placement="below">`
|
||||
/// block containing `<pedal type="start|stop" line="yes"/>`, contributing
|
||||
/// zero to measure-fill accounting.
|
||||
case pedal(PedalKind)
|
||||
}
|
||||
|
||||
/// One tuplet-bracket annotation on an atom: a `(number, isStart, isStop, localActual, localNormal)` record.
|
||||
///
|
||||
/// A single atom can carry two bracket entries when it is simultaneously the
|
||||
/// first/last note of both an inner and an outer tuplet level (nested tuplets).
|
||||
///
|
||||
/// `localActual` / `localNormal` hold the LOCAL ratio of THIS bracket level —
|
||||
/// i.e. the immediate `Tuplet(actual, inTimeOf: normal)` that introduced this
|
||||
/// bracket, NOT the cumulative product across all enclosing levels. These are
|
||||
/// compared against the atom's cumulative `tupletRatio` at emission time: when
|
||||
/// the two are equal (single-level or a level whose local matches the
|
||||
/// cumulative) the existing bare self-closing `<tuplet …/>` form is used;
|
||||
/// when they differ (a nested level whose local ≠ cumulative) the full
|
||||
/// `<tuplet-actual>`/`<tuplet-normal>` child block is added so readers can
|
||||
/// display the correct bracket number.
|
||||
struct _TupletBracket {
|
||||
/// Bracket number (1 = outermost, 2 = one level in, etc.).
|
||||
let number: Int
|
||||
/// True when this atom opens this bracket level.
|
||||
let isStart: Bool
|
||||
/// True when this atom closes this bracket level.
|
||||
let isStop: Bool
|
||||
/// The LOCAL actual count for this bracket level (not cumulative).
|
||||
let localActual: Int
|
||||
/// The LOCAL normal count for this bracket level (not cumulative).
|
||||
let localNormal: Int
|
||||
}
|
||||
|
||||
/// Slur span annotation placed on an atom by the pre-emission slur pass.
|
||||
///
|
||||
/// ## Convention (span-based, no `continue`)
|
||||
///
|
||||
/// A maximal run of N consecutive `.legato` notes in the same voice maps to
|
||||
/// exactly one slur span with ONE `<slur type="start"/>` and ONE
|
||||
/// `<slur type="stop"/>` (same `number="1"`):
|
||||
///
|
||||
/// - `<slur type="start"/>` on the FIRST legato note of the run.
|
||||
/// - `<slur type="stop"/>` on the note IMMEDIATELY AFTER the run (the first
|
||||
/// non-legato follower in the same voice). Interior legato notes (2nd..Nth)
|
||||
/// carry NO `<slur>` element.
|
||||
/// - When the run reaches the END of the part with no follower, `stop` is
|
||||
/// placed on the LAST legato note (best-effort; the final note's legato
|
||||
/// articulation is preserved in the source tree but that note reads
|
||||
/// non-legato after round-trip — documented lossy edge).
|
||||
/// - `continue` elements are never emitted.
|
||||
///
|
||||
/// Parser round-trip rule (span tracking, per voice):
|
||||
/// - On `start`: mark current note `.legato`, set `slurActiveByVoice[v] = true`.
|
||||
/// - While `slurActiveByVoice[v]` and next note carries no `stop`: mark it `.legato`.
|
||||
/// - On `stop`: stop note is NOT marked legato; set `slurActiveByVoice[v] = false`.
|
||||
struct _SlurAnnotation {
|
||||
/// Emit `<slur number="1" type="start"/>` on this note.
|
||||
let emitStart: Bool
|
||||
/// Emit `<slur number="1" type="stop"/>` on this note.
|
||||
let emitStop: Bool
|
||||
|
||||
static let none: _SlurAnnotation = _SlurAnnotation(
|
||||
emitStart: false, emitStop: false
|
||||
)
|
||||
}
|
||||
|
||||
/// Wedge (hairpin) annotation placed on an atom by the tree-walk wedge pass.
|
||||
///
|
||||
/// ## Convention
|
||||
///
|
||||
/// When a `.wedge(kind, children)` element is encountered during atom collection,
|
||||
/// the children are recursed normally and then the FIRST child atom receives
|
||||
/// `wedgeStart = kind` and the LAST child atom receives `wedgeStop = true`.
|
||||
///
|
||||
/// Emission rules:
|
||||
/// - BEFORE emitting a note that has `wedgeStart != nil`, emit a
|
||||
/// `<direction placement="below"><direction-type><wedge type="crescendo|diminuendo"/></direction-type></direction>`.
|
||||
/// - AFTER emitting a note that has `wedgeStop == true`, emit a
|
||||
/// `<direction placement="below"><direction-type><wedge type="stop"/></direction-type></direction>`.
|
||||
///
|
||||
/// A note may simultaneously have both a dynamic direction and a wedge direction —
|
||||
/// both are emitted (dynamic first, then wedge start). Wedges may cross barlines:
|
||||
/// the start annotation stays on the original first atom and the stop on the
|
||||
/// original last atom regardless of measure boundaries. Tied barline-continuation
|
||||
/// pieces do NOT carry wedge annotations (only the head and tail boundary atoms do).
|
||||
struct _WedgeAnnotation {
|
||||
/// When non-nil, emit a wedge-start direction of this kind before this note.
|
||||
let wedgeStart: WedgeKind?
|
||||
/// When `true`, emit a wedge-stop direction after this note.
|
||||
let wedgeStop: Bool
|
||||
|
||||
static let none: _WedgeAnnotation = _WedgeAnnotation(
|
||||
wedgeStart: nil, wedgeStop: false
|
||||
)
|
||||
}
|
||||
|
||||
/// Glissando (or slide) span annotation placed on an atom by the spanner
|
||||
/// application pass.
|
||||
///
|
||||
/// ## Convention
|
||||
///
|
||||
/// A glissando span is a two-note span: `.beginGlissando` on the first
|
||||
/// note and `.endGlissando` on the second. The encoder emits:
|
||||
///
|
||||
/// - START atom: `<glissando type="start" line-type="…" number="1"/>` (or
|
||||
/// `<slide …>`) inside `<notations>`.
|
||||
/// - STOP atom: `<glissando type="stop" number="1"/>` (matching element name).
|
||||
///
|
||||
/// The stop atom needs to know whether to emit `<glissando>` or `<slide>`.
|
||||
/// This is stored in `glissandoStopKind`, propagated from the opener's
|
||||
/// ``Glissando/kind`` during ``Score/validateSpannerBalance(atoms:)`` when
|
||||
/// the stop matches an open glissando.
|
||||
struct _GlissandoAnnotation {
|
||||
/// Non-nil on the START atom of a glissando span; carries the full descriptor.
|
||||
var glissandoStart: Glissando?
|
||||
/// `true` on the STOP atom of a glissando span.
|
||||
var glissandoStop: Bool
|
||||
/// The element kind (glissando vs slide) for the stop atom.
|
||||
///
|
||||
/// Propagated from the opener's ``Glissando/kind`` when the stop is
|
||||
/// matched to an open span during balance validation. `nil` until validated.
|
||||
var glissandoStopKind: GlissandoKind?
|
||||
|
||||
static let none: _GlissandoAnnotation = _GlissandoAnnotation(
|
||||
glissandoStart: nil,
|
||||
glissandoStop: false,
|
||||
glissandoStopKind: nil
|
||||
)
|
||||
}
|
||||
|
||||
/// Beam grouping position for a note within a beam group.
|
||||
///
|
||||
/// ## Convention
|
||||
///
|
||||
/// A maximal run of consecutive beamable (eighth or shorter, non-rest) notes
|
||||
/// that all fall within the SAME beat (integer quarter-beat from the measure
|
||||
/// start) forms one beam group:
|
||||
/// - First note of the group → `.begin`.
|
||||
/// - Interior notes → `.continue`.
|
||||
/// - Last note → `.end`.
|
||||
/// - A lone beamable note (group size 1) → `.none` (flagged, not beamed).
|
||||
///
|
||||
/// Only one beam level is emitted (`number="1"`). Secondary beams (e.g. a
|
||||
/// separate group for 16th sub-divisions within an eighth beam) are not
|
||||
/// implemented in this phase — a single `number="1"` beam suffices.
|
||||
///
|
||||
/// The `<beam>` element is a child of `<note>` placed after `<type>`/`<dot>`/
|
||||
/// `<time-modification>` and before `<notations>`, per MusicXML 4.0 §3.3.
|
||||
enum _BeamKind: Equatable {
|
||||
case none
|
||||
case begin
|
||||
case `continue`
|
||||
case end
|
||||
}
|
||||
|
||||
/// One atomic event produced by the tree walk, before barline splitting.
|
||||
struct _Atom {
|
||||
/// The kind of event (note, chord, or rest).
|
||||
let kind: _AtomKind
|
||||
/// The element's own nominal duration (used for `<type>`/`<dot>`
|
||||
/// derivation; for tuplet members this is the printed type, e.g.
|
||||
/// a triplet-quarter has rawDuration == .quarter).
|
||||
let rawDuration: NoteDuration
|
||||
/// Sounding duration in quarter-beats (rawDuration × accumulated
|
||||
/// tuplet scale). Used for `<duration>` ticks and cursor advance.
|
||||
let soundingDuration: Fraction
|
||||
/// Dynamic marking for this event.
|
||||
///
|
||||
/// For rests the value is a sentinel (`.mf`) — no `<direction>` is
|
||||
/// ever emitted for rest atoms regardless of this value.
|
||||
let dynamic: Dynamic
|
||||
/// Articulation for notation output.
|
||||
let articulation: Articulation
|
||||
/// Voice number (1-based in MusicXML).
|
||||
let voiceMusicXML: Int
|
||||
/// Immediate (actual, normal) tuplet ratio — nil when not inside a tuplet.
|
||||
///
|
||||
/// `normalType` carries the declared base note value of the enclosing
|
||||
/// `Tuplet(..., noteDuration:)` at the IMMEDIATE bracket level. When non-nil
|
||||
/// the encoder emits `<normal-type>` (and `<normal-dot/>` for dotted values)
|
||||
/// inside `<time-modification>`. When nil (no `noteDuration:` was declared),
|
||||
/// `<normal-type>` is omitted — output is byte-identical to the pre-existing
|
||||
/// behaviour.
|
||||
let tupletRatio: (actual: Int, normal: Int, normalType: NoteDuration?)?
|
||||
/// Tuplet bracket annotations for this atom, ordered outermost-first.
|
||||
/// Empty when not at any tuplet boundary.
|
||||
let tupletBrackets: [_TupletBracket]
|
||||
/// Slur annotation assigned by ``Score/annotateSlurs(atoms:)``.
|
||||
///
|
||||
/// Mutable annotation slot: the annotation passes set it after the atom
|
||||
/// is collected (see the `withSlur`/`withBeam`/`withWedge…` mutators).
|
||||
var slur: _SlurAnnotation
|
||||
/// Beam grouping annotation assigned by ``Score/annotateBeams(atoms:meterMap:)``.
|
||||
var beam: _BeamKind
|
||||
/// Wedge (hairpin) annotation assigned during atom collection from `.wedge` elements.
|
||||
var wedge: _WedgeAnnotation
|
||||
/// When `true` this atom is a barline-split tied continuation piece;
|
||||
/// it must NOT emit a `<direction>` even when its dynamic differs
|
||||
/// from the tracked last-emitted dynamic.
|
||||
var isTiedContinuation: Bool
|
||||
/// When `true`, this atom is the START of an authored tie (from a
|
||||
/// `.note(... tie: true)` element). The atom emits `<tie type="start"/>`
|
||||
/// and `<tied type="start"/>` in addition to any barline-split ties.
|
||||
///
|
||||
/// Distinct from `isTiedContinuation` (barline-split mechanism) — an atom
|
||||
/// can simultaneously be `tieAuthoredStart == true` and get barline-split
|
||||
/// (in that case both tie elements are emitted correctly).
|
||||
var tieAuthoredStart: Bool
|
||||
/// When `true`, this atom is the STOP of an authored tie (the immediately-
|
||||
/// following atom after a `tieAuthoredStart` atom, when the pitches match).
|
||||
/// Emits `<tie type="stop"/>` and `<tied type="stop"/>`.
|
||||
var tieAuthoredStop: Bool
|
||||
/// Staff number for this atom (1-based). Used only in multi-staff parts
|
||||
/// to emit `<staff>k</staff>` on notes and to route pedal directions to
|
||||
/// the correct staff. In single-staff parts every atom has `staff == 1`
|
||||
/// and no `<staff>` element is emitted.
|
||||
let staff: Int
|
||||
/// Notation display overrides for this atom.
|
||||
///
|
||||
/// Set during atom collection from a ``ScoreElement/displayed(_:_:)``
|
||||
/// wrapper. An all-defaults `NoteDisplay()` (``NoteDisplay/hasOverrides``
|
||||
/// == `false`) produces byte-identical MusicXML output — no extra elements
|
||||
/// are emitted.
|
||||
///
|
||||
/// Outer `displayed` wins when two `displayed` wrappers nest: the outer
|
||||
/// display is applied LAST and overwrites any inner display set earlier.
|
||||
var display: NoteDisplay = NoteDisplay()
|
||||
/// Glissando (or slide) span annotation assigned by the spanner application
|
||||
/// pass and validated by ``Score/validateSpannerBalance(atoms:)``.
|
||||
///
|
||||
/// An all-defaults `.none` annotation produces byte-identical output — no
|
||||
/// `<glissando>` or `<slide>` elements are emitted.
|
||||
var glissando: _GlissandoAnnotation = .none
|
||||
/// Notation-only marks (extra articulations, techniques, fermatas) set
|
||||
/// during atom collection from a ``ScoreElement/marked(_:_:)`` wrapper.
|
||||
///
|
||||
/// An empty array produces byte-identical MusicXML output — no extra
|
||||
/// elements are emitted.
|
||||
var marks: [NotationMark] = []
|
||||
|
||||
/// Intra-note dynamic curve points set during atom collection from a
|
||||
/// ``ScoreElement/dynamicCurve(_:_:)`` wrapper.
|
||||
///
|
||||
/// An empty array produces byte-identical MusicXML output — the curve
|
||||
/// emission path is skipped entirely, and the normal single-`dyn:`
|
||||
/// direction is emitted as usual.
|
||||
///
|
||||
/// For barline-crossing notes, only the HEAD (first) piece carries the
|
||||
/// curve; the leftover continuation atom always carries an empty array.
|
||||
var dynamicCurve: [(position: Double, dynamic: Dynamic)] = []
|
||||
}
|
||||
|
||||
/// Key identifying a dynamic direction by its position within a measure, for
|
||||
/// the per-staff redundant-dynamic collapse in the multi-voice encoder path.
|
||||
///
|
||||
/// Two atoms that open at the same metric `onset` on the same `staff` share a
|
||||
/// key; when ``toMusicXMLString(divisions:collapseRedundantDynamics:)`` collapse
|
||||
/// is enabled, the second identical dynamic at that key is suppressed. The dict
|
||||
/// is reset at the start of every measure, so a dynamic re-appearing in a later
|
||||
/// bar is always emitted.
|
||||
struct _DynamicDedupKey: Hashable {
|
||||
/// Onset of the dynamic measured from the start of its measure, in quarter-beats.
|
||||
let onset: Fraction
|
||||
/// Staff the dynamic belongs to (1-based).
|
||||
let staff: Int
|
||||
}
|
||||
|
||||
}
|
||||
@@ -21,33 +21,129 @@ extension Score {
|
||||
/// - `<part>` `<measure>` `<note>` blocks with `<pitch>` (`<step>`,
|
||||
/// `<alter>`, `<octave>`), `<rest/>`, `<duration>`, `<voice>`, and
|
||||
/// `<chord/>`.
|
||||
/// - `<attributes>` `<divisions>`, `<time>` (`<beats>` /
|
||||
/// `<beat-type>`).
|
||||
/// - `<attributes>` `<divisions>`, `<key>` (`<fifths>`, `<mode>` —
|
||||
/// first-wins; missing `<key>` defaults to `.cMajor`), `<time>` (`<beats>` /
|
||||
/// `<beat-type>`), `<clef>` (`<sign>`, `<line>`,
|
||||
/// `<clef-octave-change>`) — first clef per part wins.
|
||||
/// - `<direction>` `<sound tempo="X"/>` and `<metronome>`
|
||||
/// `<per-minute>`.
|
||||
/// `<per-minute>` — **measure 1** sets ``Score/bpm``; **measures ≥ 2**
|
||||
/// produce ``TempoChange`` entries in ``Score/tempoChanges`` (first part
|
||||
/// only; first-in-document wins per measure).
|
||||
/// - `<notations>` `<articulations>` `<staccato/>` /
|
||||
/// `<staccatissimo/>` / `<tenuto/>` / `<accent/>` /
|
||||
/// `<strong-accent/>`.
|
||||
/// - `<alter>` values on the 50-cent grid: `-2.0`, `-1.5`, `-1.0`,
|
||||
/// `-0.5`, `0`, `0.5`, `1.0`, `1.5`, `2.0`. Out-of-grid values
|
||||
/// are silently treated as a missing-pitch note (rest substitution).
|
||||
/// - `<backup><duration>D</duration></backup>` — rewinds the absolute
|
||||
/// cursor so that a subsequent voice can be read from the rewound
|
||||
/// position. Parts that contain `<backup>` are reconstructed as
|
||||
/// ``ScoreElement/voice(_:_:)`` blocks, one per distinct `<voice>`
|
||||
/// number, each sorted by absolute beat. Single-voice parts (no
|
||||
/// `<backup>`) are unaffected and return the same flat element list.
|
||||
/// - `<forward><duration>D</duration></forward>` — advances the cursor
|
||||
/// by inserting a silent rest element of the corresponding duration.
|
||||
///
|
||||
/// ## Mid-piece tempo changes
|
||||
///
|
||||
/// `<direction>` blocks in measures ≥ 2 that contain `<metronome><per-minute>`
|
||||
/// or `<sound tempo="X"/>` are decoded as ``TempoChange`` entries in
|
||||
/// ``Score/tempoChanges``. Reading is limited to the **first part** (all parts
|
||||
/// share identical tempo directions). A measure-1 tempo is the base
|
||||
/// ``Score/bpm`` and is NOT included in `tempoChanges`. When multiple
|
||||
/// directions appear in the same measure, the first-in-document order wins
|
||||
/// (same as `<per-minute>` is preferred over `<sound tempo>` for the base bpm).
|
||||
///
|
||||
/// `tempoChanges` is returned sorted ascending by measure number. Playback does
|
||||
/// **not** realize mid-piece tempo changes — ``ScorePlayer`` and NRT rendering
|
||||
/// use the single base ``Score/bpm`` throughout (future work).
|
||||
///
|
||||
/// ## Repeat / ending barlines
|
||||
///
|
||||
/// `<barline location="left">` carrying `<repeat direction="forward"/>` sets
|
||||
/// a forward repeat at the containing measure number. `<barline location="right">`
|
||||
/// carrying `<repeat direction="backward"/>` sets a backward repeat.
|
||||
/// `<ending number="N" type="start"/>` inside a left barline and
|
||||
/// `<ending number="N" type="stop|discontinue"/>` inside a right barline are
|
||||
/// paired by number to construct ``Ending`` values. All barlines are read
|
||||
/// from the **first part** (parts share identical barline structure). The
|
||||
/// resulting ``RepeatStructure`` is stored on the decoded ``Score/repeats``
|
||||
/// property. Documents without `<barline>` elements yield ``RepeatStructure/none``.
|
||||
///
|
||||
/// Playback does **not** unfold repeats — ``ScorePart/flatten()`` is unchanged
|
||||
/// (notation-only, future work).
|
||||
///
|
||||
/// ## Currently NOT parsed
|
||||
///
|
||||
/// - `score-timewise` documents (use `score-partwise` only). Trips
|
||||
/// ``MusicXMLError/unsupportedTimewiseDocument``.
|
||||
/// - `<backup>` / `<forward>` (used to express polyphonic voice
|
||||
/// layering) — voices share the cursor in the v1 parser; multi-
|
||||
/// voice scores will land out of order.
|
||||
/// - Tied notes — the `<tie>` element is ignored; a tied pair shows
|
||||
/// up as two separate ``ScoreEvent``s in the resulting ``Score``.
|
||||
/// - Tuplets via `<time-modification>` — not surfaced as a Tuplet
|
||||
/// wrapper; durations come through verbatim, but note that
|
||||
/// MusicXML triplets typically encode duration AS-IF triplet,
|
||||
/// meaning `Score.flatten()` will reproduce the timings without
|
||||
/// needing a Tuplet wrapper.
|
||||
/// - `<key>`, `<clef>`, `<lyric>`, slurs, beams, ornaments,
|
||||
/// dynamics directions.
|
||||
/// wrapper; durations come through verbatim as ``NoteDuration/fraction(_:)``
|
||||
/// values (exact rational from `<duration>` / `<divisions>`), so
|
||||
/// `Score.flatten()` will reproduce the timings without needing a
|
||||
/// Tuplet wrapper.
|
||||
/// - **Staff grouping** — the `.staff(n, clef:){…}` block structure is not
|
||||
/// reconstructed. `<staff>` numbers on `<note>` elements are read for clef
|
||||
/// resolution but discarded for grouping; notes are reconstructed by
|
||||
/// `<voice>` partitioning only. A grand-staff part round-trips its events
|
||||
/// and pitches but flattens the explicit staff grouping (documented-lossy).
|
||||
/// - **Per-part polymetric meter** (``ScorePart/meterMap``) — a part-level
|
||||
/// meter override is export-faithful but not reconstructed on decode. The
|
||||
/// decoded ``Score/meterMap`` is read from the first part only; per-part
|
||||
/// overrides do not survive the round trip.
|
||||
/// - **Sections / rehearsal marks** — ``ScoreSection`` values are not
|
||||
/// reconstructed from MusicXML (the section boundaries and rehearsal-mark
|
||||
/// labels are emit-only in v1). The decoded ``Score/rehearsalMarks`` map is
|
||||
/// always empty after a round-trip; `<rehearsal>` elements in the source
|
||||
/// document are silently skipped.
|
||||
/// - `<lyric>`, ornaments.
|
||||
/// - **`<defaults>` / `<page-layout>`** — page layout information is emit-only in v1.
|
||||
/// The `<defaults>` block (including `<scaling>` and `<page-layout>`) is silently
|
||||
/// skipped on decode; ``Score/pageLayout`` is always `nil` after a round-trip.
|
||||
///
|
||||
/// ## Dynamic directions
|
||||
///
|
||||
/// `<direction>/<direction-type>/<dynamics>` blocks set the current
|
||||
/// dynamic that applies to subsequently-committed notes and chords
|
||||
/// (sticky — the dynamic stays until the next direction). Named child
|
||||
/// elements (`<pp/>` … `<fff/>`) map to the corresponding ``Dynamic``
|
||||
/// case. `<other-dynamics>` text that parses as a `Double` maps to
|
||||
/// ``Dynamic/raw(_:)``. Directions without a recognized `<dynamics>`
|
||||
/// child are ignored for dynamic purposes.
|
||||
///
|
||||
/// The current dynamic is reset to `.mf` at the start of each part.
|
||||
/// Multi-voice: a `<direction>` applies to all voices from the point it
|
||||
/// appears in the document until the next direction. The sticky model is
|
||||
/// correct for the common single-direction-per-note encoding produced by
|
||||
/// Lyrebird's encoder, and for scores where dynamics are annotated once
|
||||
/// per passage.
|
||||
///
|
||||
/// `<sound dynamics="X"/>` elements are NOT parsed for dynamic purposes —
|
||||
/// velocity is the Lyrebird-side playback path (`ScoreEvent.velocity`).
|
||||
///
|
||||
/// ## Tie-merge
|
||||
///
|
||||
/// `<tie type="stop"/>` notes are merged into their immediately-preceding
|
||||
/// same-pitch, same-voice note (the bounded backward scan in the parser
|
||||
/// only matches the directly-adjacent predecessor). Merged durations
|
||||
/// use exact ``Fraction`` arithmetic (Fix 1). A stray
|
||||
/// `<tie type="stop"/>` with no immediately-adjacent matching predecessor
|
||||
/// (Fix 2) is emitted as a normal new note rather than merging
|
||||
/// into an unrelated earlier note of the same pitch.
|
||||
///
|
||||
/// ## Authored-tie round-trip
|
||||
///
|
||||
/// An authored tie (`Note(..., tie: true)` in the DSL) is encoded as two
|
||||
/// tied noteheads — `<tie type="start"/>` on the first and `<tie type="stop"/>`
|
||||
/// on the second, plus `<tied>` in `<notations>`. The parser's tie-merge
|
||||
/// merges the two noteheads back into ONE ``ScoreElement`` with the summed
|
||||
/// duration. This is **event-preserving** (the event round-trip is exact:
|
||||
/// ``flatten()`` produces the same ``ScoreEvent`` list) but
|
||||
/// **structure-collapsing** (the two-notehead authored tie is folded into
|
||||
/// one element, consistent with how barline-split ties already round-trip).
|
||||
/// The `tie: false` field on the round-tripped element reflects that the
|
||||
/// structural authoring information is not preserved — only the sounding
|
||||
/// event is.
|
||||
///
|
||||
/// - Parameter data: UTF-8 MusicXML byte data.
|
||||
/// - Returns: A ``Score`` reconstructed from the document.
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,53 @@
|
||||
// _NoteContext.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Per-`<note>` accumulator state for ``_MusicXMLParser``.
|
||||
///
|
||||
/// Every field is reset together at each `<note>` open (one
|
||||
/// `noteContext = _NoteContext()` assignment instead of N individual resets)
|
||||
/// and read in `commitCurrentNote()` — the "reset on open, commit on close"
|
||||
/// pattern. Document- and part-level state (parts, meter map, repeat structure,
|
||||
/// tempo changes, pickup tracking, the per-voice slur/wedge maps, the `in…`
|
||||
/// element-nesting flags) stays on the parser class; only state that logically
|
||||
/// belongs to the single note currently being parsed lives here.
|
||||
///
|
||||
/// The default values are the reset values, so `_NoteContext()` is the canonical
|
||||
/// "fresh note" state.
|
||||
internal struct _NoteContext {
|
||||
/// `<rest/>` child seen — commit as a rest rather than a pitched note.
|
||||
var isRest: Bool = false
|
||||
/// `<chord/>` child seen — this note stacks onto the previous note's onset.
|
||||
var isChord: Bool = false
|
||||
/// `<grace>` child seen (no `<duration>`) — commit as a `.grace` element
|
||||
/// without advancing the beat cursor.
|
||||
var isGrace: Bool = false
|
||||
/// `<grace slash="yes"/>`. `true` = acciaccatura; `false` = appoggiatura
|
||||
/// (no slash attribute or `slash="no"`).
|
||||
var graceSlashed: Bool = false
|
||||
/// `<pitch><step>` letter (`"C"`…`"B"`); `nil` until `<step>` is read.
|
||||
var pitchStep: String? = nil
|
||||
/// `<pitch><alter>` chromatic offset in semitones (sharp `+`, flat `−`).
|
||||
var pitchAlter: Double = 0.0
|
||||
/// `<pitch><octave>`. Reset to the middle-C octave before `<octave>` is read.
|
||||
var pitchOctave: Int = _MusicXMLParser.defaultMidiOctave
|
||||
/// `<duration>` in divisions (ticks); `0` until read.
|
||||
var durationDivisions: Int = 0
|
||||
/// `<voice>` number (1-based). Default `1` when no `<voice>` is present.
|
||||
var voice: Int = 1
|
||||
/// `<staff>` number (1-based). Default `1` for single-staff parts.
|
||||
var staff: Int = 1
|
||||
/// Articulation parsed from `<notations><articulations>` children.
|
||||
var articulation: Articulation = .normal
|
||||
/// `<tie type="stop"/>` present on this note — drives tie-merge on decode.
|
||||
/// (`<tie type="start"/>` is not tracked; the merge is stop-driven.)
|
||||
var tieStop: Bool = false
|
||||
/// `<slur type="start"/>` present on this note element.
|
||||
var hasSlurStart: Bool = false
|
||||
/// `<slur type="stop"/>` present on this note element.
|
||||
var hasSlurStop: Bool = false
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
// _PartBuilder.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Mutable per-part accumulator used during parsing.
|
||||
internal struct _PartBuilder {
|
||||
let id: String
|
||||
let name: String
|
||||
/// Clef read from the first `<clef>` element in this part. Defaults to
|
||||
/// `.treble`; set once (first-clef-per-part wins) when the first `<clef>`
|
||||
/// block is encountered — `clefWasSet` distinguishes "not yet parsed" from
|
||||
/// a legitimately-parsed treble clef, so a later mid-part `<clef>` change
|
||||
/// does not overwrite the first.
|
||||
var clef: Clef = .treble
|
||||
var clefWasSet: Bool = false
|
||||
/// Key signature read from the first `<key>` element in this part.
|
||||
/// Nil until a `<key>` block is parsed. Used to set a per-part override
|
||||
/// when this part's key differs from the first part's key.
|
||||
var keySignature: KeySignature? = nil
|
||||
/// Transpose read from the `<transpose>` element in this part.
|
||||
/// Nil until a `<transpose>` block is parsed.
|
||||
var transpose: Transpose? = nil
|
||||
/// Absolute cursor position in divisions. Updated after each note / rest is
|
||||
/// committed; rewound by `<backup>` and advanced by `<forward>`.
|
||||
var absoluteCursorDivisions: Int = 0
|
||||
/// Beat-stamped events collected in document order. Voice grouping and
|
||||
/// element reconstruction happen in `_MusicXMLParser.parsedScore()`.
|
||||
var entries: [_PartEntry] = []
|
||||
|
||||
/// Replace the ScoreElement at the given index (used by tie-merge).
|
||||
mutating func replaceElement(at index: Int, with element: ScoreElement) {
|
||||
entries[index].element = element
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user