diff --git a/CLAUDE.md b/CLAUDE.md index 07324b1..f4e0f0c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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 ` 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 diff --git a/Demos/LyrebirdDemo/LyrebirdDemo/Demos/BufferDemos.swift b/Demos/LyrebirdDemo/LyrebirdDemo/Demos/BufferDemos.swift index cb363ea..20de493 100644 --- a/Demos/LyrebirdDemo/LyrebirdDemo/Demos/BufferDemos.swift +++ b/Demos/LyrebirdDemo/LyrebirdDemo/Demos/BufferDemos.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) diff --git a/Demos/LyrebirdDemo/LyrebirdDemo/Demos/ReverbDemo.swift b/Demos/LyrebirdDemo/LyrebirdDemo/Demos/ReverbDemo.swift index 21f103f..11cb7d3 100644 --- a/Demos/LyrebirdDemo/LyrebirdDemo/Demos/ReverbDemo.swift +++ b/Demos/LyrebirdDemo/LyrebirdDemo/Demos/ReverbDemo.swift @@ -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 { } } } - diff --git a/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/AppDelegate.swift b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/AppDelegate.swift index 2537f49..b6b372a 100644 --- a/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/AppDelegate.swift +++ b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/AppDelegate.swift @@ -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 diff --git a/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/UI/BinDelayController.swift b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/UI/BinDelayController.swift index 146665d..ab1d5bb 100644 --- a/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/UI/BinDelayController.swift +++ b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/UI/BinDelayController.swift @@ -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 { diff --git a/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/UI/NoteController.swift b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/UI/NoteController.swift index 641a6d6..f039808 100644 --- a/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/UI/NoteController.swift +++ b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/UI/NoteController.swift @@ -7,6 +7,7 @@ import Observation import LyrebirdSynth +@MainActor @Observable final class NoteController { diff --git a/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/UI/VectorOscillatorController.swift b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/UI/VectorOscillatorController.swift index a2de487..de868f1 100644 --- a/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/UI/VectorOscillatorController.swift +++ b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/UI/VectorOscillatorController.swift @@ -7,6 +7,7 @@ import Observation import LyrebirdSynth +@MainActor @Observable final class VectorOscillatorController { diff --git a/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/main.swift b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/main.swift index 1b62a2a..9a4be6f 100644 --- a/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/main.swift +++ b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/main.swift @@ -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() +} diff --git a/Demos/LyrebirdNRTDemo/LyrebirdNRTDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Demos/LyrebirdNRTDemo/LyrebirdNRTDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 0000000..073b396 --- /dev/null +++ b/Demos/LyrebirdNRTDemo/LyrebirdNRTDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -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 +} diff --git a/Demos/LyrebirdScoreDemo/LyrebirdScoreDemo.xcodeproj/project.pbxproj b/Demos/LyrebirdScoreDemo/LyrebirdScoreDemo.xcodeproj/project.pbxproj new file mode 100644 index 0000000..7fb8504 --- /dev/null +++ b/Demos/LyrebirdScoreDemo/LyrebirdScoreDemo.xcodeproj/project.pbxproj @@ -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 = ""; }; + A5D100000000000000000014 /* ScoreVoice.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScoreVoice.swift; sourceTree = ""; }; + A5D100000000000000000017 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + A5D100000000000000000020 /* LyrebirdScoreDemo.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = LyrebirdScoreDemo.entitlements; sourceTree = ""; }; + A5D100000000000000000018 /* DemoProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DemoProtocol.swift; sourceTree = ""; }; + A5D10000000000000000001A /* ScoreDemo.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScoreDemo.swift; sourceTree = ""; }; +/* 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 = ""; + }; + A5D100000000000000000003 /* Products */ = { + isa = PBXGroup; + children = ( + A5D100000000000000000004 /* LyrebirdScoreDemo */, + ); + name = Products; + sourceTree = ""; + }; + A5D100000000000000000005 /* LyrebirdScoreDemo */ = { + isa = PBXGroup; + children = ( + A5D100000000000000000006 /* main.swift */, + A5D100000000000000000016 /* Synthesizers */, + A5D10000000000000000001C /* Demos */, + A5D100000000000000000017 /* Info.plist */, + A5D100000000000000000020 /* LyrebirdScoreDemo.entitlements */, + ); + path = LyrebirdScoreDemo; + sourceTree = ""; + }; + A5D100000000000000000016 /* Synthesizers */ = { + isa = PBXGroup; + children = ( + A5D100000000000000000014 /* ScoreVoice.swift */, + ); + path = Synthesizers; + sourceTree = ""; + }; + A5D10000000000000000001C /* Demos */ = { + isa = PBXGroup; + children = ( + A5D100000000000000000018 /* DemoProtocol.swift */, + A5D10000000000000000001A /* ScoreDemo.swift */, + ); + path = Demos; + sourceTree = ""; + }; +/* 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 */; +} diff --git a/Demos/LyrebirdScoreDemo/LyrebirdScoreDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Demos/LyrebirdScoreDemo/LyrebirdScoreDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 0000000..073b396 --- /dev/null +++ b/Demos/LyrebirdScoreDemo/LyrebirdScoreDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -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 +} diff --git a/Demos/LyrebirdScoreDemo/LyrebirdScoreDemo.xcodeproj/xcshareddata/xcschemes/LyrebirdScoreDemo.xcscheme b/Demos/LyrebirdScoreDemo/LyrebirdScoreDemo.xcodeproj/xcshareddata/xcschemes/LyrebirdScoreDemo.xcscheme new file mode 100644 index 0000000..9ba5566 --- /dev/null +++ b/Demos/LyrebirdScoreDemo/LyrebirdScoreDemo.xcodeproj/xcshareddata/xcschemes/LyrebirdScoreDemo.xcscheme @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Demos/LyrebirdScoreDemo/LyrebirdScoreDemo/Demos/DemoProtocol.swift b/Demos/LyrebirdScoreDemo/LyrebirdScoreDemo/Demos/DemoProtocol.swift new file mode 100644 index 0000000..c237561 --- /dev/null +++ b/Demos/LyrebirdScoreDemo/LyrebirdScoreDemo/Demos/DemoProtocol.swift @@ -0,0 +1,11 @@ +// DemoProtocol.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth + +protocol DemoProtocol { + func runDemo() +} diff --git a/Demos/LyrebirdScoreDemo/LyrebirdScoreDemo/Demos/ScoreDemo.swift b/Demos/LyrebirdScoreDemo/LyrebirdScoreDemo/Demos/ScoreDemo.swift new file mode 100644 index 0000000..ca1049b --- /dev/null +++ b/Demos/LyrebirdScoreDemo/LyrebirdScoreDemo/Demos/ScoreDemo.swift @@ -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 + // 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 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) + ``. 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 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 + // / 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 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 → -1-2. + /// 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 `2`, a + /// `` (treble) / `` (bass) pair, a + /// `` element on every note, `` between the three voices, + /// and `` 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) + } + } + } +} diff --git a/Demos/LyrebirdScoreDemo/LyrebirdScoreDemo/Info.plist b/Demos/LyrebirdScoreDemo/LyrebirdScoreDemo/Info.plist new file mode 100644 index 0000000..1c3dc74 --- /dev/null +++ b/Demos/LyrebirdScoreDemo/LyrebirdScoreDemo/Info.plist @@ -0,0 +1,14 @@ + + + + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleVersion + 1 + NSDesktopFolderUsageDescription + LyrebirdScoreDemo writes rendered audio and MusicXML files to the Desktop. + NSDocumentsFolderUsageDescription + LyrebirdScoreDemo writes rendered audio files to Documents. + + diff --git a/Demos/LyrebirdScoreDemo/LyrebirdScoreDemo/LyrebirdScoreDemo.entitlements b/Demos/LyrebirdScoreDemo/LyrebirdScoreDemo/LyrebirdScoreDemo.entitlements new file mode 100644 index 0000000..80fbf9c --- /dev/null +++ b/Demos/LyrebirdScoreDemo/LyrebirdScoreDemo/LyrebirdScoreDemo.entitlements @@ -0,0 +1,10 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.disable-library-validation + + + diff --git a/Demos/LyrebirdScoreDemo/LyrebirdScoreDemo/Synthesizers/ScoreVoice.swift b/Demos/LyrebirdScoreDemo/LyrebirdScoreDemo/Synthesizers/ScoreVoice.swift new file mode 100644 index 0000000..8af4933 --- /dev/null +++ b/Demos/LyrebirdScoreDemo/LyrebirdScoreDemo/Synthesizers/ScoreVoice.swift @@ -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)) + } +} diff --git a/Demos/LyrebirdScoreDemo/LyrebirdScoreDemo/main.swift b/Demos/LyrebirdScoreDemo/LyrebirdScoreDemo/main.swift new file mode 100644 index 0000000..c73af15 --- /dev/null +++ b/Demos/LyrebirdScoreDemo/LyrebirdScoreDemo/main.swift @@ -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) +} diff --git a/Demos/LyrebirdScoreDemo/Package.resolved b/Demos/LyrebirdScoreDemo/Package.resolved new file mode 100644 index 0000000..921a7bf --- /dev/null +++ b/Demos/LyrebirdScoreDemo/Package.resolved @@ -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 +} diff --git a/Demos/LyrebirdScoreDemo/Package.swift b/Demos/LyrebirdScoreDemo/Package.swift new file mode 100644 index 0000000..0a7ac1b --- /dev/null +++ b/Demos/LyrebirdScoreDemo/Package.swift @@ -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" + ), + ] +) diff --git a/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo.xcodeproj/project.pbxproj b/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo.xcodeproj/project.pbxproj index 3387d8d..f4ff1e9 100644 --- a/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo.xcodeproj/project.pbxproj +++ b/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo.xcodeproj/project.pbxproj @@ -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 */ }; diff --git a/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 0000000..cada953 --- /dev/null +++ b/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -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 +} diff --git a/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo/AppDelegate.swift b/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo/AppDelegate.swift index 3b4a976..c31b355 100644 --- a/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo/AppDelegate.swift +++ b/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo/AppDelegate.swift @@ -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 = + 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 { diff --git a/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo/LyrebirdScratchDemo.entitlements b/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo/LyrebirdScratchDemo.entitlements index a1e8b01..0c014e2 100644 --- a/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo/LyrebirdScratchDemo.entitlements +++ b/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo/LyrebirdScratchDemo.entitlements @@ -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). --> diff --git a/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo/main.swift b/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo/main.swift index d7ee605..068cea9 100644 --- a/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo/main.swift +++ b/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo/main.swift @@ -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() +} diff --git a/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/LyrebirdiOSDemoApp.swift b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/LyrebirdiOSDemoApp.swift index 44ddcb5..827e247 100644 --- a/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/LyrebirdiOSDemoApp.swift +++ b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/LyrebirdiOSDemoApp.swift @@ -16,6 +16,7 @@ private let demo: Demo = .vector // ────────────────────────────────────────────────────────────────────────────── @main +@MainActor struct LyrebirdiOSDemoApp: App { let engine: SynthesisEngine diff --git a/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/BinDelayController.swift b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/BinDelayController.swift index 146665d..ab1d5bb 100644 --- a/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/BinDelayController.swift +++ b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/BinDelayController.swift @@ -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 { diff --git a/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/NoteController.swift b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/NoteController.swift index 641a6d6..f039808 100644 --- a/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/NoteController.swift +++ b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/NoteController.swift @@ -7,6 +7,7 @@ import Observation import LyrebirdSynth +@MainActor @Observable final class NoteController { diff --git a/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/VectorOscillatorController.swift b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/VectorOscillatorController.swift index a2de487..de868f1 100644 --- a/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/VectorOscillatorController.swift +++ b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/VectorOscillatorController.swift @@ -7,6 +7,7 @@ import Observation import LyrebirdSynth +@MainActor @Observable final class VectorOscillatorController { diff --git a/INSTALLATION_AND_USAGE.md b/INSTALLATION_AND_USAGE.md index 19259ca..826c354 100644 --- a/INSTALLATION_AND_USAGE.md +++ b/INSTALLATION_AND_USAGE.md @@ -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 /.xcworkspace # SPM-only & Xcode-project templates both shi cd && 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 --template --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 | diff --git a/LYREBIRD_START_HERE.md b/LYREBIRD_START_HERE.md index dd6249f..bbf95ba 100644 --- a/LYREBIRD_START_HERE.md +++ b/LYREBIRD_START_HERE.md @@ -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` | diff --git a/LiveCompile/Package.swift b/LiveCompile/Package.swift index d16edd5..2891818 100644 --- a/LiveCompile/Package.swift +++ b/LiveCompile/Package.swift @@ -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", diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/CompiledSnippet.swift b/LiveCompile/Sources/LyrebirdLiveCompile/CompiledSnippet.swift index 0e6053d..bf190ea 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/CompiledSnippet.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/CompiledSnippet.swift @@ -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. diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/Diagnostic.swift b/LiveCompile/Sources/LyrebirdLiveCompile/Diagnostic.swift index c86dd56..0f2c0a0 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/Diagnostic.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/Diagnostic.swift @@ -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) diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/DiagnosticParser.swift b/LiveCompile/Sources/LyrebirdLiveCompile/DiagnosticParser.swift index 7710005..617e282 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/DiagnosticParser.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/DiagnosticParser.swift @@ -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 diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/DiagnosticSeverity.swift b/LiveCompile/Sources/LyrebirdLiveCompile/DiagnosticSeverity.swift index e49a1eb..1559bd4 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/DiagnosticSeverity.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/DiagnosticSeverity.swift @@ -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. diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/LiveCompileError.swift b/LiveCompile/Sources/LyrebirdLiveCompile/LiveCompileError.swift index a56a0e7..f360ade 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/LiveCompileError.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/LiveCompileError.swift @@ -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 diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/LiveCompiler.swift b/LiveCompile/Sources/LyrebirdLiveCompile/LiveCompiler.swift index a856a49..a8cd358 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/LiveCompiler.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/LiveCompiler.swift @@ -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. diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/LiveSession.swift b/LiveCompile/Sources/LyrebirdLiveCompile/LiveSession.swift index ce360df..58f9f32 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/LiveSession.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/LiveSession.swift @@ -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`. diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/LiveSessionError.swift b/LiveCompile/Sources/LyrebirdLiveCompile/LiveSessionError.swift index 15a743a..2815e1b 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/LiveSessionError.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/LiveSessionError.swift @@ -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` diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/SnippetContext.swift b/LiveCompile/Sources/LyrebirdLiveCompile/SnippetContext.swift index 0653e37..4da672f 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/SnippetContext.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/SnippetContext.swift @@ -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 diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/SnippetEntry.swift b/LiveCompile/Sources/LyrebirdLiveCompile/SnippetEntry.swift index 047a2a6..607ff83 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/SnippetEntry.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/SnippetEntry.swift @@ -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 diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/SnippetHarness.swift b/LiveCompile/Sources/LyrebirdLiveCompile/SnippetHarness.swift index 4baeb22..e2bb6f9 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/SnippetHarness.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/SnippetHarness.swift @@ -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`; diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/WrappedSnippet.swift b/LiveCompile/Sources/LyrebirdLiveCompile/WrappedSnippet.swift index edf37da..0f05e80 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/WrappedSnippet.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/WrappedSnippet.swift @@ -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. diff --git a/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdLiveCompileUI.docc/LiveCoding.md b/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdLiveCompileUI.docc/LiveCoding.md deleted file mode 100644 index bc5a8a0..0000000 --- a/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdLiveCompileUI.docc/LiveCoding.md +++ /dev/null @@ -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`` diff --git a/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdScratchModel.swift b/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdScratchModel.swift index 08da9c4..d6d6a76 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdScratchModel.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdScratchModel.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -// LyrebirdUI/LiveCompile — Phase 145 +// LyrebirdUI/LiveCompile // // Backing model for `LyrebirdScratchView`. Owns the editable snippet text, the // most recent compile result, and the host `LiveSession`. Pulled out of the @@ -16,7 +16,11 @@ import Foundation import CoreGraphics import LyrebirdSynth -import LyrebirdLiveCompile +// Re-exported so consumers that link only the `LyrebirdLiveCompileUI` product +// (e.g. the LyrebirdScratchDemo app) get the `LyrebirdLiveCompile` API +// (`LiveSession`, …) without separately linking the `LyrebirdLiveCompile` +// dynamic product — which clashes in Xcode with the static target embed. +@_exported import LyrebirdLiveCompile /// Observable backing model for `LyrebirdScratchView`. /// diff --git a/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdScratchView.swift b/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdScratchView.swift index 999db63..229ae8a 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdScratchView.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdScratchView.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -// LyrebirdUI/LiveCompile — Phase 145 +// LyrebirdUI/LiveCompile // // `LyrebirdScratchView` — SwiftUI scratchpad editor for live-coded snippets. // Wraps an `NSTextView` for the editor surface, drives a `LyrebirdScratchModel` diff --git a/LiveCompile/Sources/LyrebirdLiveCompileUI/ScratchLineNumberRuler.swift b/LiveCompile/Sources/LyrebirdLiveCompileUI/ScratchLineNumberRuler.swift index 90e34ff..4768a34 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompileUI/ScratchLineNumberRuler.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompileUI/ScratchLineNumberRuler.swift @@ -4,7 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -// LyrebirdUI/LiveCompile — Phase 147 +// LyrebirdUI/LiveCompile // // Vertical line-number gutter for `ScratchEditor`'s `NSTextView`. Installed as // the scroll view's `verticalRulerView` so it tracks scroll position for free. diff --git a/LiveCompile/Tests/LyrebirdLiveCompileTests/LiveSessionDiagnosticsTests.swift b/LiveCompile/Tests/LyrebirdLiveCompileTests/LiveSessionDiagnosticsTests.swift index e040453..b6c5766 100644 --- a/LiveCompile/Tests/LyrebirdLiveCompileTests/LiveSessionDiagnosticsTests.swift +++ b/LiveCompile/Tests/LyrebirdLiveCompileTests/LiveSessionDiagnosticsTests.swift @@ -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")) } diff --git a/LiveCompile/Tests/LyrebirdLiveCompileTests/LiveSessionTests.swift b/LiveCompile/Tests/LyrebirdLiveCompileTests/LiveSessionTests.swift index be34f66..3238afa 100644 --- a/LiveCompile/Tests/LyrebirdLiveCompileTests/LiveSessionTests.swift +++ b/LiveCompile/Tests/LyrebirdLiveCompileTests/LiveSessionTests.swift @@ -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 { diff --git a/LiveCompile/Tests/LyrebirdLiveCompileUITests/LyrebirdScratchModelTests.swift b/LiveCompile/Tests/LyrebirdLiveCompileUITests/LyrebirdScratchModelTests.swift index 7efa586..81882cb 100644 --- a/LiveCompile/Tests/LyrebirdLiveCompileUITests/LyrebirdScratchModelTests.swift +++ b/LiveCompile/Tests/LyrebirdLiveCompileUITests/LyrebirdScratchModelTests.swift @@ -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" diff --git a/Lyrebird.xcworkspace/contents.xcworkspacedata b/Lyrebird.xcworkspace/contents.xcworkspacedata index 3bda614..920121f 100644 --- a/Lyrebird.xcworkspace/contents.xcworkspacedata +++ b/Lyrebird.xcworkspace/contents.xcworkspacedata @@ -19,4 +19,7 @@ + + diff --git a/PLAN.md b/PLAN.md new file mode 100644 index 0000000..956dbae --- /dev/null +++ b/PLAN.md @@ -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. diff --git a/README.md b/README.md index 901b949..727182b 100644 --- a/README.md +++ b/README.md @@ -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). diff --git a/RELEASES.md b/RELEASES.md new file mode 100644 index 0000000..c5e8764 --- /dev/null +++ b/RELEASES.md @@ -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` 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 ``. 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-`` 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. diff --git a/Sources/Lyrebird/AUv3/LyrebirdAudioUnit.swift b/Sources/Lyrebird/AUv3/LyrebirdAudioUnit.swift index c83b61e..53a5209 100644 --- a/Sources/Lyrebird/AUv3/LyrebirdAudioUnit.swift +++ b/Sources/Lyrebird/AUv3/LyrebirdAudioUnit.swift @@ -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 diff --git a/Sources/Lyrebird/Engine/MainActorMutationBridge.swift b/Sources/Lyrebird/Engine/MainActorMutationBridge.swift index 218cee4..6383215 100644 --- a/Sources/Lyrebird/Engine/MainActorMutationBridge.swift +++ b/Sources/Lyrebird/Engine/MainActorMutationBridge.swift @@ -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**: diff --git a/Sources/Lyrebird/Engine/SynthesisEngine.swift b/Sources/Lyrebird/Engine/SynthesisEngine.swift index 60ad538..e74679a 100644 --- a/Sources/Lyrebird/Engine/SynthesisEngine.swift +++ b/Sources/Lyrebird/Engine/SynthesisEngine.swift @@ -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 { diff --git a/Sources/Lyrebird/External/LyrebirdMessageContext.swift b/Sources/Lyrebird/External/LyrebirdMessageContext.swift index 09f5139..1c810d9 100644 --- a/Sources/Lyrebird/External/LyrebirdMessageContext.swift +++ b/Sources/Lyrebird/External/LyrebirdMessageContext.swift @@ -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 { diff --git a/Sources/Lyrebird/Generators/Reverb/ConvolutionReverb.swift b/Sources/Lyrebird/Generators/Reverb/ConvolutionReverb.swift index ea5b49f..ac0f4ce 100644 --- a/Sources/Lyrebird/Generators/Reverb/ConvolutionReverb.swift +++ b/Sources/Lyrebird/Generators/Reverb/ConvolutionReverb.swift @@ -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. diff --git a/Sources/Lyrebird/Generators/Reverb/FreeVerb.swift b/Sources/Lyrebird/Generators/Reverb/FreeVerb.swift index 10c006c..dff0ea8 100644 --- a/Sources/Lyrebird/Generators/Reverb/FreeVerb.swift +++ b/Sources/Lyrebird/Generators/Reverb/FreeVerb.swift @@ -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. diff --git a/Sources/Lyrebird/Generators/Reverb/GVerb.swift b/Sources/Lyrebird/Generators/Reverb/GVerb.swift index 6976a90..6fd5747 100644 --- a/Sources/Lyrebird/Generators/Reverb/GVerb.swift +++ b/Sources/Lyrebird/Generators/Reverb/GVerb.swift @@ -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. diff --git a/Sources/Lyrebird/Generators/Reverb/PlateReverb.swift b/Sources/Lyrebird/Generators/Reverb/PlateReverb.swift index 8419e34..4b86798 100644 --- a/Sources/Lyrebird/Generators/Reverb/PlateReverb.swift +++ b/Sources/Lyrebird/Generators/Reverb/PlateReverb.swift @@ -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. diff --git a/Sources/Lyrebird/Generators/Reverb/SpringReverb.swift b/Sources/Lyrebird/Generators/Reverb/SpringReverb.swift index 49ed617..d187183 100644 --- a/Sources/Lyrebird/Generators/Reverb/SpringReverb.swift +++ b/Sources/Lyrebird/Generators/Reverb/SpringReverb.swift @@ -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. diff --git a/Sources/Lyrebird/Lyrebird.docc/Generators/MusicalMath.md b/Sources/Lyrebird/Lyrebird.docc/Generators/MusicalMath.md index d7c6d38..8e72ede 100644 --- a/Sources/Lyrebird/Lyrebird.docc/Generators/MusicalMath.md +++ b/Sources/Lyrebird/Lyrebird.docc/Generators/MusicalMath.md @@ -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 diff --git a/Sources/Lyrebird/Lyrebird.docc/RoutineTask.md b/Sources/Lyrebird/Lyrebird.docc/RoutineTask.md index 07ca136..36325fe 100644 --- a/Sources/Lyrebird/Lyrebird.docc/RoutineTask.md +++ b/Sources/Lyrebird/Lyrebird.docc/RoutineTask.md @@ -36,7 +36,7 @@ Every `Pattern` 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`. | diff --git a/Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md b/Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md index 6cd4558..a1a0c50 100644 --- a/Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md +++ b/Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md @@ -10,6 +10,8 @@ Author musical scores in Swift. Notes, rests, chords, dynamics, articulations, a Lyrebird's score system gives you a language-side musical-event representation distinct from MIDI files: you write Swift, you get a flat list of `ScoreEvent` instances with absolute beat positions. Tuplet ratios compose under nesting via `Fraction` arithmetic; only the final `ScoreEvent.beat` and `ScoreEvent.duration` are emitted as `Double`. No floating-point drift across nested `Tuplet(3, inTimeOf: 2)` layers. +`ScoreEvent.duration` is the **notated** duration (pre-articulation). To get the **sounding** (performed) duration — i.e. the actual note length for audio synthesis, MIDI note-off, or SMF — call `event.performedDuration`, which applies `articulation.durationScale`. Engraving and MusicXML use `duration`; audio and MIDI use `performedDuration`. + The score itself is purely declarative. ``ScorePlayer`` walks the flat event list against a `LyrebirdClock` on a `LyrebirdRoutine` thread (mirroring `MIDIFilePlayer`), and SMF / MusicXML bridges let you round-trip between formats. ## Authoring @@ -29,7 +31,8 @@ let score = Score(bpm: 120) { Chord([(.c, 4), (.e, 4), (.g, 4)], dur: .half, dyn: .f) } - Part("bass", channel: 1) { + // Explicit bass clef; default .auto would also infer .bass from these pitches. + Part("bass", channel: 1, clef: .bass) { Note(.c, 2, dur: .whole, dyn: .mp) } } @@ -40,22 +43,542 @@ for event in leadEvents { } ``` +## Algorithmic generation + +The builder supports native Swift control flow directly — `for` loops collect via +the builder's `buildArray`, `if`/`else` via `buildOptional`/`buildEither`. +`.forEach` will **not** work: its closure body produces `Void`, so the notes are +discarded. Reach for a `for` loop: + +```swift +Part("lead") { + for pitch in [Pitch.named(.c, 5), .named(.e, 5), .named(.g, 5)] { + Note(pitch, dur: .quarter, art: .staccato) + } +} +``` + +Two helpers go further when the run is reusable, index-driven, or fed by a +``Pattern``. Both return `[ScoreElement]` that drops straight into a +`Part`/`Tuplet`/`Voice` body: + +- ``Generate(_:_:)`` maps each index `0 ..< count` through a builder closure. + The body is a full builder block, so an index may emit zero, one, or many + elements (loops, `if`, chords, nested `Tuplet`/`Voice`). +- ``PatternNotes(count:pitches:dur:durations:dyn:dynamics:art:)`` and its + `midi:` overload pull pitches — and optionally per-note rhythm and dynamic — + from ``Pattern`` value sources. The pitch pattern drives length: if it + exhausts before `count`, generation stops early. Aux patterns fall back to the + scalar `dur` / `dyn` when omitted or exhausted. The `midi:` overload rounds and + clamps each `Double` to MIDI `[0, 127]`. + +```swift +Part("texture") { + // 1000 sixteenths walking a whole-tone fragment by index. + Generate(1000) { i in + Note(midi: 48 + (i % 12), dur: .sixteenth, dyn: .mp) + } + // A seeded Brownian MIDI walk with a repeating rhythm cell. + PatternNotes( + count: 12, + midi: Pattern.brownian(low: 60, high: 84, step: 4, length: 12, seed: 42), + durations: Pattern.sequence([.eighth, .eighth, .quarter]), + dyn: .p + ) +} +``` + +For one-off generation, a plain function returning `[ScoreElement]` (or a bare +`for` loop) is just as valid — these helpers are sugar over that pattern, not a +new builder type. + ## Core types | Type | Role | |------|------| | ``Score`` | Top-level container with `bpm`, `timeSignature`, `parts` | -| ``ScorePart`` | One named timeline of elements; supports per-part MIDI channel hint | -| ``ScoreElement`` | Unflattened tree node — note / rest / chord / tuplet | +| ``ScorePart`` | One named timeline of elements; supports per-part MIDI channel hint and ``Clef`` | +| ``ScoreElement`` | Unflattened tree node — note / rest / chord / tuplet / **voice** | | ``ScoreEvent`` | Flat output of ``ScorePart/flatten()`` — absolute beat + duration + velocity | | ``Pitch`` | `.midi(Int)` / `.freq(Double)` / `.named(NoteName, Int)` / `.rest` | | ``Letter`` | Diatonic letter `C`, `D`, `E`, `F`, `G`, `A`, `B` (determines octave of containing pitch) | | ``Accidental`` | Nine-step microtonal grid: `doubleFlat`, `threeQuarterFlat`, `flat`, `quarterFlat`, `natural`, `quarterSharp`, `sharp`, `threeQuarterSharp`, `doubleSharp` | | ``NoteName`` | `(Letter, Accidental)` struct preserving spelling. `C♭` and `B` produce the same MIDI but are distinct values | -| ``NoteDuration`` | `.fraction(Fraction)` (preferred) or `.beats(Double)`; named conveniences (`.whole`, `.half`, `.quarter`, `.eighth`, …, `.dotted(_:)`, `.doubleDotted(_:)`) | +| ``NoteDuration`` | `.fraction(Fraction)` (preferred) or `.beats(Double)`; named conveniences from `.doubleWhole` (breve, 8 beats) down through `.whole`, `.half`, `.quarter`, `.eighth`, … `.sixtyFourth`. British names are aliases for the same values: `.breve`, `.semibreve`, `.minim`, `.crotchet`, `.quaver`, `.semiquaver`, `.demisemiquaver`, `.hemidemisemiquaver`. Dot it with the `.dotted` / `.doubleDotted` properties — `.quarter.dotted` (×3/2), `.half.doubleDotted` (×7/4) — or the `.dotted(_:)` / `.doubleDotted(_:)` static funcs | | ``Dynamic`` | `.ppp`–`.fff` and `.raw(Double)`; `.velocity` returns normalized `[0, 1]` | -| ``Articulation`` | `.normal`, `.staccato`, `.staccatissimo`, `.legato`, `.tenuto`, `.accent`, `.marcato` — affects played duration and velocity | +| ``Articulation`` | `.normal`, `.staccato`, `.staccatissimo`, `.legato`, `.tenuto`, `.accent`, `.marcato` — the single `art:` value; affects played duration and velocity *and* emits its glyph | +| ``NotationMark`` | Notation-only `marks:` list on a note/chord — extra articulation glyphs, string/technique symbols (`.leftHandPizzicato`, `.snapPizzicato`, `.upBow`, `.downBow`, `.harmonic`, `.openString`), and `.fermata(`` ``FermataShape`` ``)`. Emits `` / `` / ``; does not affect playback. Emit-only (not parsed back) | +| ``FermataShape`` | `.normal`, `.angled`, `.square` (long), `.doubleSquare` (very long / longa), `.doubleAngled`, `.doubleDot`, `.halfCurve`, `.curlew` | | ``Fraction`` | Reduced `Int64` rational; backbone of exact tuplet arithmetic | +| ``Clef`` | Per-part MusicXML clef: `.treble`, `.bass`, `.alto`, `.tenor`, `.treble8vb`, `.percussion`, `.auto` | +| ``KeySignature`` | Score-level key signature: `fifths` (circle-of-fifths integer) + ``KeySignature/Mode`` (`.major` / `.minor`). Also available as a per-part override on ``ScorePart`` | +| ``Transpose`` | Per-part transposing-instrument spec: `chromatic` + `diatonic` + `octaveChange` (written→sounding). Notation-only; named conveniences `.bFlat`, `.a`, `.eFlat`, `.fHorn` | +| ``RepeatStructure`` | Score-level repeat barline and volta-ending description (measure-indexed, notation-only) | +| ``Ending`` | One volta bracket: `number` (1, 2, …), `startMeasure`, `stopMeasure` (1-based, inclusive) | +| ``TempoChange`` | Mid-piece tempo change: `measure` (1-based) + `bpm` (> 0); notation-only | + +## Tempo Changes + +``TempoChange`` describes where a new tempo takes effect in the score. It is a **score-level, measure-indexed, notation-only** annotation: + +- **Score-level**: one `[TempoChange]` array applies to all parts uniformly. Every part receives the same tempo `` element at the matching measure. +- **Measure-indexed**: each change is anchored to a 1-based measure number. +- **Notation-only**: ``ScorePart/flatten()`` is **unaffected**. ``ScorePlayer`` and NRT rendering use the single base ``Score/bpm`` throughout. Segmented beat-to-seconds tempo-map playback is planned for a future phase. + +```swift +let score = Score( + bpm: 120, + tempoChanges: [ + TempoChange(measure: 5, bpm: 160), // allegro at bar 5 + TempoChange(measure: 9, bpm: 72) // adagio at bar 9 + ] +) { + Part("melody") { … } +} +``` + +The `tempoChanges:` parameter defaults to `[]` so existing call sites are unchanged. + +### Measure-1 rule + +``Score/bpm`` always supplies the measure-1 tempo. A `TempoChange` targeting measure 1 is superseded by `bpm` during encoding (the encoder writes `bpm` for measure 1 and ignores any `TempoChange` at that measure). Use `tempoChanges` for measures ≥ 2. + +### Deduplication + +When two `TempoChange` values target the same measure, **first-in-array order wins** during encoding. The parser applies the same rule (first-in-document wins per measure). + +### TempoChange properties + +| Property | Type | Description | +|---|---|---| +| `measure` | `Int` | 1-based measure number where the new tempo takes effect. Must be ≥ 1. | +| `bpm` | `Double` | New tempo in quarter-note beats per minute. Must be > 0. | + +### MusicXML encoding + +``Score/toMusicXMLString(divisions:)`` emits a tempo `` block at the start of each matching measure, in **every** part. The format is identical to the measure-1 base-tempo direction: + +```xml + + + + quarter + 160 + + + + +``` + +When `tempoChanges` is empty, **zero** extra tempo directions are emitted — output is byte-identical to a score without any tempo changes. + +### MusicXML parsing + +``Score/fromMusicXML(data:)`` reads tempo directions from the **first part** (all parts share identical tempo directions). A `` block in measure 1 sets ``Score/bpm``; blocks in measures ≥ 2 produce ``TempoChange`` entries in ``Score/tempoChanges``. `` is preferred over `` when both appear in the same block. The result is sorted ascending by measure number and deduplicated (first-in-document wins per measure). + +### Notation-only limitation + +Playback does **not** realize tempo changes. ``ScorePlayer`` fires note-on events at beat times computed from the single base ``Score/bpm``. Implementing a tempo map (segmented beat-to-seconds conversion respecting each ``TempoChange`` interval) is planned for a future phase. + +## Repeats and Endings + +``RepeatStructure`` describes where forward/backward repeat barlines and volta ending brackets (1st ending, 2nd ending, …) appear in the score. It is a **score-level, measure-indexed, notation-only** annotation: + +- **Score-level**: one `RepeatStructure` applies to all parts uniformly. Every part receives the same `` elements at the same measure numbers in MusicXML. +- **Measure-indexed**: forward repeats, backward repeats, and ending brackets are specified by 1-based measure number. +- **Notation-only**: ``ScorePart/flatten()`` is **unaffected**. Playback does not unfold repeats and does not duplicate events in the ``ScoreEvent`` list — that is future work. + +```swift +let score = Score( + bpm: 120, + timeSignature: TimeSignature(4, 4), + repeats: RepeatStructure( + forwardRepeatMeasures: [1], // |: at the left edge of bar 1 + backwardRepeatMeasures: [4], // :| at the right edge of bar 4 + endings: [ + Ending(number: 1, startMeasure: 3, stopMeasure: 3), // 1st ending + Ending(number: 2, startMeasure: 4, stopMeasure: 4) // 2nd ending + ] + ) +) { + Part("melody") { … } +} +``` + +The `repeats:` parameter defaults to ``RepeatStructure/none`` (empty — zero `` elements) so existing call sites that omit it are unchanged. + +### RepeatStructure properties + +| Property | Type | Description | +|---|---|---| +| `forwardRepeatMeasures` | `Set` | 1-based measure numbers whose **left** barline is a forward repeat (`|:`) | +| `backwardRepeatMeasures` | `Set` | 1-based measure numbers whose **right** barline is a backward repeat (`:|`) | +| `endings` | `[Ending]` | Volta brackets | +| `isEmpty` | `Bool` | `true` when all sets/arrays are empty (the `.none` default) | + +### Ending properties + +| Property | Type | Description | +|---|---|---| +| `number` | `Int` | Volta number (`1` = 1st ending, `2` = 2nd ending, …). Must be ≥ 1. | +| `startMeasure` | `Int` | 1-based measure number where the bracket begins (inclusive). Must be ≥ 1. | +| `stopMeasure` | `Int` | 1-based measure number where the bracket ends (inclusive). Must be ≥ `startMeasure`. | + +### MusicXML barline encoding + +``Score/toMusicXMLString(divisions:)`` emits `` elements inside each matching `` block, in **every** part. Child element order follows the MusicXML 4.0 DTD (``, ``, ``): + +**Left barline** (forward repeat and/or ending start) — emitted after `` and the tempo direction, before the first note/rest: + +```xml + + heavy-light + + + +``` + +An ending-only left barline (no forward repeat) omits `` and ``. A forward-repeat-only left barline omits ``. + +**Right barline** (backward repeat and/or ending stop) — emitted immediately before ``: + +```xml + + light-heavy + + + +``` + +When `repeats.isEmpty` is `true`, **zero** `` elements are emitted — output is byte-identical to a score without any repeat structure. + +**Multi-voice parts**: the left barline is emitted once at the very start of the measure (before voice 1), the right barline once at the very end (after the last voice). Barlines are NOT duplicated per voice. + +### MusicXML barline parsing + +``Score/fromMusicXML(data:)`` reads `` elements from the **first part** (all parts share identical barlines). Accumulation: + +- `` inside a `` → adds the containing measure number to `forwardRepeatMeasures`. +- `` inside a `` → adds to `backwardRepeatMeasures`. +- `` → records the pending start measure for volta N. +- `` → pairs with the pending start to form an ``Ending`` and appends it to `endings`. + +Documents without `` elements produce ``Score/repeats`` == ``RepeatStructure/none``. + +### Notation-only limitation + +Playback does **not** unfold repeats. ``ScorePart/flatten()`` returns events in document order without duplicating the repeated sections. Implementing playback unfolding (expanding the flat event list for repeated passages) is planned for a future phase. + +## Meter and time signatures + +A ``TimeSignature`` is a numerator/denominator plus an explicit **beat grouping** — +a partition of the numerator into felt beats, in denominator-note units. Simple, +compound, and complex/additive meters are all just groupings, so there is no +special-casing: + +- Simple `4/4` → `[1, 1, 1, 1]` (four quarter beats). +- Compound `6/8` → `[3, 3]` (two dotted-quarter beats). Auto-inferred when the + denominator is `8`/`16`, the numerator is a multiple of three, and `> 3`. +- Slow `6/8` felt as six eighths → `TimeSignature(6, 8, grouping: [1, 1, 1, 1, 1, 1])`. +- Additive `3+3+2` over eighths → `TimeSignature(8, 8, grouping: [3, 3, 2])`. + +`beat` everywhere in the meter / positioning layer means the **felt (conducted) +beat** defined by the grouping — consistent across meters (`beat 1` is always the +downbeat). The finer denominator-note unit is the `division`. (This is distinct +from the absolute-timeline "beat" in ``ScoreEvent/beat`` / `bpm`, which is always +one quarter note — the machine unit that musical positions resolve down to.) + +A ``MeterMap`` is a segmented map of `(startBar, TimeSignature)` plus an optional +``MeterMap/anacrusis`` (pickup length in quarter beats). It governs barlines for a +whole score (``Score/meterMap``) or, polymetrically, a single part +(``ScorePart/meterMap``). + +```swift +let score = Score( + meterMap: MeterMap(segments: [ + MeterMap.Segment(startBar: 1, .fourFour), + MeterMap.Segment(startBar: 5, .threeFour), // mid-piece change at bar 5 + ], anacrusis: Fraction(1, 1)) // one-quarter pickup +) { + Part("lead") { … } +} +``` + +The MusicXML encoder emits a fresh `