bugfixes, better MusicXML support and 1.1.0

This commit is contained in:
2026-06-10 08:41:07 -07:00
parent 6d3a0930a1
commit f59fd3b55a
228 changed files with 32271 additions and 2586 deletions
+230 -14
View File
@@ -18,6 +18,9 @@ public enum ProjectTemplate: String, CaseIterable, Equatable {
case uiDemo = "ui-demo"
/// Non-real-time render: `NRTDriver` writes a `.caf` file and exits.
case nrt = "nrt"
/// Score / MusicXML render: builds a `Score` with the DSL, exports a
/// `.musicxml` document, and renders the score offline with `NRTDriver`.
case score = "score"
/// macOS `.app` bundle wrapping an AppKit + SwiftUI host of a `@UIParam` synth.
/// Generates a full `<name>.xcodeproj` referencing Lyrebird via remote SPM dep.
case macosUIXcode = "macos-ui-xcode"
@@ -35,6 +38,8 @@ public enum ProjectTemplate: String, CaseIterable, Equatable {
case "demo": self = .demo
case "ui-demo", "uidemo", "ui_demo": self = .uiDemo
case "nrt": self = .nrt
case "score", "score-musicxml", "scoremusicxml", "musicxml":
self = .score
case "macos-ui-xcode", "macosuixcode", "macos_ui_xcode":
self = .macosUIXcode
case "ios-ui", "iosui", "ios_ui":
@@ -52,7 +57,7 @@ public enum ProjectTemplate: String, CaseIterable, Equatable {
/// (auv3) an `.appex` extension target — none of which SwiftPM can express.
public var shipsXcodeProject: Bool {
switch self {
case .basic, .demo, .uiDemo, .nrt: return false
case .basic, .demo, .uiDemo, .nrt, .score: return false
case .macosUIXcode, .iosUI, .auv3: return true
}
}
@@ -95,6 +100,44 @@ public enum ProjectScaffolder {
// MARK: - Public API
/// Absolute path to the Lyrebird checkout this CLI was *built* from, derived
/// from the compile-time source location of this file
/// (`<root>/Sources/LyrebirdCLI/ProjectScaffolder.swift`).
///
/// Used as the default SPM dependency for scaffolded projects when the caller
/// passes no explicit `--lyrebird-path`, so generated projects track the
/// current `main` API rather than the published `from:` tag — which lags
/// unreleased Score/Generator features (e.g. `Part(clef:)`,
/// `ScoreEvent.performedDuration`). This is the pre-1.0-stable policy: the
/// template source and the dependency it pins both come from one checkout, so
/// they never drift.
///
/// Returns `nil` when the derived root no longer holds the Lyrebird
/// `Package.swift` (the binary was installed away from its source tree);
/// callers then fall back to the remote versioned dependency.
static var defaultLyrebirdCheckoutPath: String? {
lyrebirdCheckoutRoot(forSourceFile: #filePath)
}
/// Testable core of ``defaultLyrebirdCheckoutPath``. Given a source file at
/// `<root>/Sources/LyrebirdCLI/<file>.swift`, walks up three directory
/// levels to `<root>` and returns it iff `<root>/Package.swift` exists and
/// names Lyrebird. Returns `nil` otherwise. Split out so the happy- and
/// nil-paths can be unit-tested with synthetic paths (the computed property
/// is hard-wired to its own `#filePath`).
static func lyrebirdCheckoutRoot(forSourceFile sourceFile: String) -> String? {
let root: URL = URL(fileURLWithPath: sourceFile)
.deletingLastPathComponent() // strip <file>.swift → Sources/LyrebirdCLI/
.deletingLastPathComponent() // → Sources/
.deletingLastPathComponent() // → <root>/
let manifest: String = root.appendingPathComponent("Package.swift").path
guard FileManager.default.fileExists(atPath: manifest) else { return nil }
// Guard against pointing at an unrelated parent Package.swift.
guard let contents: String = try? String(contentsOfFile: manifest, encoding: .utf8),
contents.contains("Lyrebird") else { return nil }
return root.path
}
/// Scaffold a new Lyrebird project named `name` inside `parentDirectory`.
///
/// - Parameters:
@@ -102,10 +145,13 @@ public enum ProjectScaffolder {
/// - template: Starter template style (default `.basic`).
/// - parentDirectory: Directory in which to create the project folder.
/// Defaults to the current working directory.
/// - lyrebirdPath: Optional absolute path to a local Lyrebird checkout
/// to wire into the generated `Package.swift` as a `path:` dependency
/// (useful when developing against an unmerged Lyrebird branch).
/// `nil` → use the published GitHub package as the dependency.
/// - lyrebirdPath: Absolute path to a local Lyrebird checkout to wire into
/// the generated `Package.swift` as a `path:` dependency. `nil` → use
/// the published remote package. This is a faithful passthrough: the
/// `new` CLI command resolves `nil` to ``defaultLyrebirdCheckoutPath``
/// *before* calling this (see `LyrebirdCLI.runNew`), so default
/// scaffolds track current `main`; direct library callers get the
/// documented `nil` → remote behaviour.
/// - Throws: `ProjectScaffolder.Error` on name validation failure or file system errors.
public static func scaffold(
name: String,
@@ -252,7 +298,7 @@ public enum ProjectScaffolder {
case .auv3:
try writeAUv3Files(name: name, projectRoot: projectRoot,
lyrebirdPath: lyrebirdPath, fm: fm)
case .basic, .demo, .uiDemo, .nrt:
case .basic, .demo, .uiDemo, .nrt, .score:
// Unreachable — shipsXcodeProject filters these out at dispatch.
try? fm.removeItem(atPath: projectRoot)
throw Error.fileSystemError(
@@ -324,7 +370,7 @@ public enum ProjectScaffolder {
// the dep is local or remote.
let targetDeps: String
switch template {
case .basic, .demo, .nrt:
case .basic, .demo, .nrt, .score:
targetDeps = #""Lyrebird""#
case .uiDemo:
targetDeps = #""Lyrebird", .product(name: "LyrebirdUI", package: "Lyrebird")"#
@@ -382,6 +428,7 @@ public enum ProjectScaffolder {
case .demo: return mainSwiftDemo(name: name)
case .uiDemo: return mainSwiftUIDemo(name: name)
case .nrt: return mainSwiftNRT(name: name)
case .score: return mainSwiftScore(name: name)
case .macosUIXcode, .iosUI, .auv3:
// Xcode-bearing templates don't emit a `main.swift` under
// `Sources/<name>/`. Dispatch never reaches this function for
@@ -416,7 +463,7 @@ public enum ProjectScaffolder {
fatalError("Engine failed to start: \\(error)")
}
print("\\(name) running — press Ctrl+C to stop")
print("\(name) running — press Ctrl+C to stop")
RunLoop.main.run()
"""
}
@@ -464,7 +511,7 @@ public enum ProjectScaffolder {
fatalError("Engine.add failed: \\(error)")
}
print("\\(name) running — press Ctrl+C to stop")
print("\(name) running — press Ctrl+C to stop")
print("Update tone.freq or tone.amp from the REPL to change parameters.")
RunLoop.main.run()
"""
@@ -548,6 +595,170 @@ public enum ProjectScaffolder {
"""
}
// MARK: score
private static func mainSwiftScore(name: String) -> String {
"""
// \(name) — Score / MusicXML render
import Foundation
import LyrebirdSynth
// MARK: - ScoreVoice
/// One self-freeing voice per score event. The envelope's `freeNode`
/// done-action removes the synth when its note finishes, so scheduled
/// voices never accumulate during the offline render.
final class ScoreVoice: SynthesizerBase {
let freqHz: Double
let amp: Double
let durSeconds: Double
let pan: Double
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 = 0.01
let release = 0.06
let sustain = max(0.0, durSeconds - attack - release)
let envelope = Envelope(
levels: [0.0, 1.0, 0.8, 0.0],
durations: [attack, sustain, release],
curves: [-4.0, 0.0, -6.0]
)
let osc = OscSawtooth.Audio(freq: freqHz)
let env = EnvelopeGen.Control(envelope: envelope, doneAction: .freeNode)
output(bus: 0, source: Pan2(input: osc * env * amp, pan: pan))
}
}
// MARK: - Build the score
let bpm = 120.0
let secondsPerBeat = 60.0 / bpm
// Author music with the Score DSL: Note, Rest, Chord, Tuplet, dynamics,
// and articulations. Pitch spelling (letter + accidental) is preserved
// through MusicXML export. `Generate` and `PatternNotes` add algorithmic
// generation (see the "texture" part below).
//
// Further notation (see the Lyrebird ScoreSystem docs): Slur / Crescendo /
// Diminuendo spans, per-note `spanners:` (overlapping spans, glissandi /
// slides), per-note `display:` (NoteDisplay — notehead/size/hide stem or
// beam), `Section("…") { }` blocks with rehearsal marks, and a `pageLayout:`
// (PageLayout — page size, orientation, margins).
let score = Score(bpm: bpm, timeSignature: TimeSignature(4, 4)) {
Part("lead") {
// A crescendo hairpin over the opening arpeggio (notation-only).
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: .f, art: .accent)
}
Rest(dur: .quarter)
Tuplet(3, inTimeOf: 2) {
Note(.named(.b, 5), dur: .quarter, dyn: .mp)
Note(.named(.a, 5), dur: .quarter, dyn: .mp)
Note(.named(.g, 5), dur: .quarter, dyn: .mp)
}
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)
Note(.named(.g, 2), dur: .half, dyn: .p)
Note(.named(.c, 3), dur: .half, dyn: .mp, art: .tenuto)
}
// Texture — algorithmic generation. `Generate` maps an index range
// through the builder; `PatternNotes` pulls from a `Pattern` source.
Part("texture", channel: 2) {
Generate(8) { i in
Note(midi: 72 + (i % 6) * 2, dur: .sixteenth, dyn: .pp, art: .staccato)
}
PatternNotes(count: 4, midi: Pattern.series(start: 60, step: 3, length: 4), dur: .eighth, dyn: .p)
}
}
// MARK: - Output location
// Write next to this project's source rather than the launch directory.
// `LyrebirdPaths.projectRoot()` walks up from this file to the folder
// containing Package.swift, so output lands in the project regardless of
// how the binary is launched (lyrebird run, swift run, or Xcode — whose
// working directory is DerivedData). Dev-time convenience; for a shipped
// app writing user data, use `LyrebirdPaths.documents` instead.
let outputDir = LyrebirdPaths.projectRoot() ?? LyrebirdPaths.currentWorkingDirectory
// MARK: - Export MusicXML
let xmlURL = outputDir.appendingPathComponent("score.musicxml")
do {
let xml = score.toMusicXMLString()
try xml.write(to: xmlURL, atomically: true, encoding: .utf8)
print("MusicXML written → \\(xmlURL.path)")
} catch {
fputs("MusicXML export failed: \\(error)\\n", stderr)
exit(1)
}
// Round-trip sanity check: parse the document back in and compare counts.
do {
let restored = try Score.fromMusicXML(data: score.toMusicXMLData())
print("Round-trip events: \\(score.allEvents.count) → \\(restored.allEvents.count)")
} catch {
fputs("MusicXML round-trip failed: \\(error)\\n", stderr)
}
// MARK: - Render the score offline
let tailSeconds = 1.5
let renderDuration = score.totalBeats * secondsPerBeat + tailSeconds
let outputURL = outputDir.appendingPathComponent("score.caf")
let engine = SynthesisEngine(
blockSize: \(scaffoldDefaultBlockSize),
sampleRate: \(scaffoldDefaultSampleRate),
numOutputChannels: \(scaffoldDefaultOutputChannels),
numInputChannels: 0,
driver: NRTDriver(outputURL: outputURL, duration: renderDuration)
)
// Schedule one voice per sounding event BEFORE start() — NRTDriver
// renders synchronously inside start().
var scheduled = 0
for event in score.allEvents {
guard !event.isRest else { continue }
guard let freqHz = event.pitch.frequency else { continue }
let pan = event.channel == 0 ? -0.4 : 0.5
let voice = ScoreVoice(
freqHz: freqHz,
amp: event.velocity * 0.35,
durSeconds: event.performedDuration * secondsPerBeat,
pan: pan
)
do {
try engine.schedule(voice, after: event.beat * secondsPerBeat)
scheduled += 1
} catch {
fputs("engine.schedule failed: \\(error)\\n", stderr)
}
}
print("Scheduled \\(scheduled) voices.")
do {
try engine.start()
print("Rendered \\(renderDuration)s → \\(outputURL.path)")
} catch {
fputs("Render failed: \\(error)\\n", stderr)
exit(1)
}
"""
}
// MARK: - ui-demo additional files
/// `AppDelegate.swift` content for a ui-demo project.
@@ -563,6 +774,7 @@ public enum ProjectScaffolder {
let synth: \(name)Synth
var window: LyrebirdWindow?
@MainActor
init(engine: SynthesisEngine) {
self.engine = engine
self.synth = \(name)Synth()
@@ -629,17 +841,21 @@ public enum ProjectScaffolder {
// MARK: - Xcode workspace
/// `contents.xcworkspacedata` body. Single `FileRef` to `Package.swift`
/// so opening the workspace in Xcode loads the SPM package with full
/// project navigation, debugging, and SwiftUI previews. Identical for
/// every template — the file lives at `<name>.xcworkspace/contents.xcworkspacedata`.
/// `contents.xcworkspacedata` body. The single `FileRef` points at the
/// workspace's enclosing directory (`group:.`) — the package root that
/// holds `Package.swift` — so Xcode recognises it as a Swift package and
/// opens the full `Sources/` / `Tests/` tree with a runnable scheme.
/// (Referencing the `Package.swift` *file* instead loads a single loose
/// document with no schemes — `xcodebuild -list` reports "no schemes".)
/// Identical for every SPM template — the file lives at
/// `<name>.xcworkspace/contents.xcworkspacedata`.
public static func workspaceContents() -> String {
"""
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:Package.swift">
location = "group:.">
</FileRef>
</Workspace>
"""