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
@@ -18,7 +18,7 @@ final class BufferDemos: DemoProtocol {
func runDemo() {
// BufferDemos.swift lives at .../Demos/LyrebirdDemo/LyrebirdDemo/Demos/BufferDemos.swift
// — 4 components up to reach .../Demos/ where Perc.aiff lives.
let percURL = URL(fileURLWithPath: #filePath)
let percURL: URL = URL(fileURLWithPath: #filePath)
.deletingLastPathComponent() // .../Demos/
.deletingLastPathComponent() // .../LyrebirdDemo/
.deletingLastPathComponent() // .../LyrebirdDemo (package)/
@@ -35,13 +35,66 @@ final class BufferDemos: DemoProtocol {
exit(1)
}
let sampleRate = engine.sampleRate
let sampleRate: Double = engine.sampleRate
// SynthesizerBase is @MainActor-isolated. LyrebirdTask.run's body is @Sendable and
// non-async, so synth inits must happen BEFORE the closure on the main thread.
// runDemo() is reached from main.swift on the main thread, so assumeIsolated is valid.
let pitchSteps: [(Double, String)] = [
(0.5, "0.5 — octave down"),
(0.75, "0.75 — minor third down"),
(1.0, "1.0 — original pitch"),
(1.5, "1.5 — perfect fifth up"),
(2.0, "2.0 — octave up"),
]
let spectralRatios: [(Double, String)] = [
(0.5, "0.5 — octave down (phase vocoder)"),
(1.0, "1.0 — no shift (phase vocoder passthrough)"),
(1.5, "1.5 — perfect fifth up (phase vocoder)"),
(2.0, "2.0 — octave up (phase vocoder)"),
]
let diffuseSteps: [(Double, String)] = [
(0.0, "0.0 — bypass (mono passthrough on both channels)"),
(0.5, "0.5 — half decorrelation"),
(1.0, "1.0 — full per-channel phase randomisation"),
]
let stretchSteps: [(Double, String)] = [
(3.0, "3.0 — 3× stretch (one-third speed, pitch preserved)"),
(1.5, "1.5 — 1.5× stretch (three-quarter speed, pitch preserved)"),
(1.0, "1.0 — native speed (no stretch)"),
(0.5, "0.5 — 2× compression (double speed, pitch preserved)"),
(0.33, "0.33 — 3× compression (triple speed, pitch preserved)"),
]
// Pre-construct all synthesizers on the main actor before entering the @Sendable closure.
let (demo1, demo2, demo3, pitchRatioNode, demo4Array, demo5Array, demo6Array):
(PercPlayBuffer, PercBufferRead, PercPitchShift, ParameterNode,
[PercSpectralPitchShift], [PercSpectralStereoDiffuse], [PercTimeStretch]) =
MainActor.assumeIsolated {
let d1: PercPlayBuffer = PercPlayBuffer(buffer: percBuffer, engineSampleRate: sampleRate)
let d2: PercBufferRead = PercBufferRead(buffer: percBuffer)
let d3: PercPitchShift = PercPitchShift(buffer: percBuffer, engineSampleRate: sampleRate)
let prNode: ParameterNode = d3.$pitchRatio
let d4: [PercSpectralPitchShift] = spectralRatios.map { ratio, _ in
PercSpectralPitchShift(buffer: percBuffer, pitchRatio: ratio, engineSampleRate: sampleRate)
}
let d5: [PercSpectralStereoDiffuse] = diffuseSteps.map { amount, _ in
PercSpectralStereoDiffuse(buffer: percBuffer, amount: amount, engineSampleRate: sampleRate)
}
let d6: [PercTimeStretch] = stretchSteps.map { factor, _ in
PercTimeStretch(buffer: percBuffer, stretchFactor: factor)
}
return (d1, d2, d3, prNode, d4, d5, d6)
}
LyrebirdTask.run(engine: engine) { ctx in
// Demo 1 — PlayBuffer (looping at native rate)
print("\n── Demo 1: PlayBuffer (looping) ──")
let demo1 = PercPlayBuffer(buffer: percBuffer, engineSampleRate: sampleRate)
ctx.add(demo1)
try ctx.wait(seconds: 6)
ctx.remove(demo1)
@@ -49,7 +102,6 @@ final class BufferDemos: DemoProtocol {
// Demo 2 — BufferRead (sine-wave position scan)
print("\n── Demo 2: BufferRead (sine-wave position scan) ──")
let demo2 = PercBufferRead(buffer: percBuffer)
ctx.add(demo2)
try ctx.wait(seconds: 6)
ctx.remove(demo2)
@@ -57,19 +109,11 @@ final class BufferDemos: DemoProtocol {
// Demo 3 — PlayBuffer → PitchShift (cycling through pitch ratios)
print("\n── Demo 3: PlayBuffer → PitchShift ──")
let demo3 = PercPitchShift(buffer: percBuffer, engineSampleRate: sampleRate)
ctx.add(demo3)
let pitchSteps: [(Double, String)] = [
(0.5, "0.5 — octave down"),
(0.75, "0.75 — minor third down"),
(1.0, "1.0 — original pitch"),
(1.5, "1.5 — perfect fifth up"),
(2.0, "2.0 — octave up"),
]
for (ratio, label) in pitchSteps {
print(" pitchRatio \(label)")
demo3.pitchRatio = ratio
// Update via ParameterNode.value — nonisolated atomic setter, RT-safe.
pitchRatioNode.value = ratio
try ctx.wait(seconds: 3)
}
ctx.remove(demo3)
@@ -77,16 +121,9 @@ final class BufferDemos: DemoProtocol {
// Demo 4 — PlayBuffer → SpectralChain.Audio (with SpectralPitchShift)
print("\n── Demo 4: PlayBuffer → SpectralChain.Audio (SpectralPitchShift) ──")
let spectralRatios: [(Double, String)] = [
(0.5, "0.5 — octave down (phase vocoder)"),
(1.0, "1.0 — no shift (phase vocoder passthrough)"),
(1.5, "1.5 — perfect fifth up (phase vocoder)"),
(2.0, "2.0 — octave up (phase vocoder)"),
]
for (ratio, label) in spectralRatios {
for (index, (_, label)) in spectralRatios.enumerated() {
print(" pitchRatio \(label)")
let demo4 = PercSpectralPitchShift(buffer: percBuffer, pitchRatio: ratio, engineSampleRate: sampleRate)
let demo4: PercSpectralPitchShift = demo4Array[index]
ctx.add(demo4)
try ctx.wait(seconds: 5)
ctx.remove(demo4)
@@ -95,16 +132,9 @@ final class BufferDemos: DemoProtocol {
// Demo 5 — SpectralChain.Audio fan-out (mono → 2-channel decorrelated stereo)
print("\n── Demo 5: SpectralChain.Audio fan-out (SpectralStereoDiffuse) ──")
let diffuseSteps: [(Double, String)] = [
(0.0, "0.0 — bypass (mono passthrough on both channels)"),
(0.5, "0.5 — half decorrelation"),
(1.0, "1.0 — full per-channel phase randomisation"),
]
for (amount, label) in diffuseSteps {
for (index, (_, label)) in diffuseSteps.enumerated() {
print(" amount \(label)")
let demo5 = PercSpectralStereoDiffuse(
buffer: percBuffer, amount: amount, engineSampleRate: sampleRate)
let demo5: PercSpectralStereoDiffuse = demo5Array[index]
ctx.add(demo5)
try ctx.wait(seconds: 5)
ctx.remove(demo5)
@@ -113,17 +143,9 @@ final class BufferDemos: DemoProtocol {
// Demo 6 — TimeStretch (granular, pitch-preserved time stretching + compression)
print("\n── Demo 6: TimeStretch (granular time-stretch / compression) ──")
let stretchSteps: [(Double, String)] = [
(3.0, "3.0 — 3× stretch (one-third speed, pitch preserved)"),
(1.5, "1.5 — 1.5× stretch (three-quarter speed, pitch preserved)"),
(1.0, "1.0 — native speed (no stretch)"),
(0.5, "0.5 — 2× compression (double speed, pitch preserved)"),
(0.33, "0.33 — 3× compression (triple speed, pitch preserved)"),
]
for (factor, label) in stretchSteps {
for (index, (_, label)) in stretchSteps.enumerated() {
print(" stretchFactor \(label)")
let demo6 = PercTimeStretch(buffer: percBuffer, stretchFactor: factor)
let demo6: PercTimeStretch = demo6Array[index]
ctx.add(demo6)
try ctx.wait(seconds: 6)
ctx.remove(demo6)
@@ -4,14 +4,6 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
//
// BufferDemos 2.swift
// LyrebirdDemo
//
// Created by Joshua Parmenter on 5/6/26.
//
import Foundation
import LyrebirdSynth
@@ -25,13 +17,17 @@ final class ReverbDemo: DemoProtocol {
func runDemo() {
let sampleRate = engine.sampleRate
// sets up its own thread / timing, etc
LyrebirdTask.run(engine: engine) { [sampleRate] ctx in
let sampleRate: Double = engine.sampleRate
// SynthesizerBase is @MainActor-isolated. Pre-construct the synth on the main actor
// before entering the @Sendable LyrebirdTask closure. runDemo() is reached from
// main.swift on the main thread, so assumeIsolated is valid.
let reverbDemo: GVerbTest = MainActor.assumeIsolated {
GVerbTest(sampleRate: sampleRate)
}
LyrebirdTask.run(engine: engine) { ctx in
ctx.tempo = 60.0
let reverbDemo = GVerbTest(
sampleRate: sampleRate
)
ctx.add(reverbDemo)
try ctx.wait(beats: 6) // could also use seconds
ctx.remove(reverbDemo)
@@ -39,4 +35,3 @@ final class ReverbDemo: DemoProtocol {
}
}
}
@@ -26,6 +26,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
let binDelayController: BinDelayController
var window: LyrebirdWindow?
@MainActor
init(engine: SynthesisEngine) {
let scopeCapture = ScopeCapture(buses: [0, 1], bufferSize: 2048)
engine.scopeTap = scopeCapture
@@ -13,6 +13,7 @@ import LyrebirdSynth
/// first taps "Start Synthesizer" — this is necessary because
/// `SpectralBinDelayUI.init(sampleRate:)` requires the engine's committed
/// sample rate, which is only valid after `engine.start()` returns.
@MainActor
@Observable
final class BinDelayController {
@@ -7,6 +7,7 @@
import Observation
import LyrebirdSynth
@MainActor
@Observable
final class NoteController {
@@ -7,6 +7,7 @@
import Observation
import LyrebirdSynth
@MainActor
@Observable
final class VectorOscillatorController {
@@ -15,8 +15,13 @@ let engine = SynthesisEngine(
driver: CoreAudioDriver()
)
let delegate = AppDelegate(engine: engine)
let app = NSApplication.shared
app.setActivationPolicy(.regular)
app.delegate = delegate
app.run()
// AppDelegate.init is @MainActor (it builds @MainActor SynthesizerBase synths
// and UI controllers). Program entry runs on the main thread, so assert main-
// actor isolation for the AppKit bootstrap rather than hopping asynchronously.
MainActor.assumeIsolated {
let delegate: AppDelegate = AppDelegate(engine: engine)
let app: NSApplication = NSApplication.shared
app.setActivationPolicy(.regular)
app.delegate = delegate
app.run()
}
@@ -0,0 +1,24 @@
{
"originHash" : "2c98cd4172bcfb3eff9cb6e34a538f80f5e424aa73fbd5bea2b20cf0c8b539b7",
"pins" : [
{
"identity" : "linenoise-swift",
"kind" : "remoteSourceControl",
"location" : "https://github.com/andybest/linenoise-swift",
"state" : {
"revision" : "afc897c02b030af7333105c4fedcd843a8339238",
"version" : "0.0.3"
}
},
{
"identity" : "nimble",
"kind" : "remoteSourceControl",
"location" : "https://github.com/Quick/Nimble.git",
"state" : {
"revision" : "e9d769113660769a4d9dd3afb855562c0b7ae7b0",
"version" : "7.3.4"
}
}
],
"version" : 3
}
@@ -0,0 +1,344 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 60;
objects = {
/* Begin PBXBuildFile section */
A5D100000000000000000007 /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5D100000000000000000006 /* main.swift */; };
A5D100000000000000000013 /* Lyrebird in Frameworks */ = {isa = PBXBuildFile; productRef = A5D100000000000000000012 /* Lyrebird */; };
A5D100000000000000000015 /* ScoreVoice.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5D100000000000000000014 /* ScoreVoice.swift */; };
A5D100000000000000000019 /* DemoProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5D100000000000000000018 /* DemoProtocol.swift */; };
A5D10000000000000000001B /* ScoreDemo.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5D10000000000000000001A /* ScoreDemo.swift */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
A5D100000000000000000004 /* LyrebirdScoreDemo */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = LyrebirdScoreDemo; sourceTree = BUILT_PRODUCTS_DIR; };
A5D100000000000000000006 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };
A5D100000000000000000014 /* ScoreVoice.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScoreVoice.swift; sourceTree = "<group>"; };
A5D100000000000000000017 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
A5D100000000000000000020 /* LyrebirdScoreDemo.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = LyrebirdScoreDemo.entitlements; sourceTree = "<group>"; };
A5D100000000000000000018 /* DemoProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DemoProtocol.swift; sourceTree = "<group>"; };
A5D10000000000000000001A /* ScoreDemo.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScoreDemo.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
A5D100000000000000000009 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
A5D100000000000000000013 /* Lyrebird in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
A5D100000000000000000002 = {
isa = PBXGroup;
children = (
A5D100000000000000000005 /* LyrebirdScoreDemo */,
A5D100000000000000000003 /* Products */,
);
sourceTree = "<group>";
};
A5D100000000000000000003 /* Products */ = {
isa = PBXGroup;
children = (
A5D100000000000000000004 /* LyrebirdScoreDemo */,
);
name = Products;
sourceTree = "<group>";
};
A5D100000000000000000005 /* LyrebirdScoreDemo */ = {
isa = PBXGroup;
children = (
A5D100000000000000000006 /* main.swift */,
A5D100000000000000000016 /* Synthesizers */,
A5D10000000000000000001C /* Demos */,
A5D100000000000000000017 /* Info.plist */,
A5D100000000000000000020 /* LyrebirdScoreDemo.entitlements */,
);
path = LyrebirdScoreDemo;
sourceTree = "<group>";
};
A5D100000000000000000016 /* Synthesizers */ = {
isa = PBXGroup;
children = (
A5D100000000000000000014 /* ScoreVoice.swift */,
);
path = Synthesizers;
sourceTree = "<group>";
};
A5D10000000000000000001C /* Demos */ = {
isa = PBXGroup;
children = (
A5D100000000000000000018 /* DemoProtocol.swift */,
A5D10000000000000000001A /* ScoreDemo.swift */,
);
path = Demos;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
A5D10000000000000000000A /* LyrebirdScoreDemo */ = {
isa = PBXNativeTarget;
buildConfigurationList = A5D10000000000000000000B /* Build configuration list for PBXNativeTarget "LyrebirdScoreDemo" */;
buildPhases = (
A5D100000000000000000008 /* Sources */,
A5D100000000000000000009 /* Frameworks */,
);
buildRules = (
);
dependencies = (
);
name = LyrebirdScoreDemo;
packageProductDependencies = (
A5D100000000000000000012 /* Lyrebird */,
);
productName = LyrebirdScoreDemo;
productReference = A5D100000000000000000004 /* LyrebirdScoreDemo */;
productType = "com.apple.product-type.tool";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
A5D100000000000000000001 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 1600;
LastUpgradeCheck = 1600;
TargetAttributes = {
A5D10000000000000000000A = {
CreatedOnToolsVersion = 16.0;
};
};
};
buildConfigurationList = A5D10000000000000000000E /* Build configuration list for PBXProject "LyrebirdScoreDemo" */;
compatibilityVersion = "Xcode 14.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = A5D100000000000000000002;
packageReferences = (
A5D100000000000000000011 /* XCLocalSwiftPackageReference "../.." */,
);
productRefGroup = A5D100000000000000000003 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
A5D10000000000000000000A /* LyrebirdScoreDemo */,
);
};
/* End PBXProject section */
/* Begin PBXSourcesBuildPhase section */
A5D100000000000000000008 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
A5D100000000000000000007 /* main.swift in Sources */,
A5D100000000000000000015 /* ScoreVoice.swift in Sources */,
A5D100000000000000000019 /* DemoProtocol.swift in Sources */,
A5D10000000000000000001B /* ScoreDemo.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin XCBuildConfiguration section */
A5D10000000000000000000C /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_ENTITLEMENTS = LyrebirdScoreDemo/LyrebirdScoreDemo.entitlements;
CODE_SIGN_IDENTITY = "-";
CODE_SIGN_STYLE = Manual;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_HARDENED_RUNTIME = YES;
INFOPLIST_FILE = LyrebirdScoreDemo/Info.plist;
MACOSX_DEPLOYMENT_TARGET = 15.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScoreDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 6.0;
};
name = Debug;
};
A5D10000000000000000000D /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_ENTITLEMENTS = LyrebirdScoreDemo/LyrebirdScoreDemo.entitlements;
CODE_SIGN_IDENTITY = "-";
CODE_SIGN_STYLE = Manual;
ENABLE_HARDENED_RUNTIME = YES;
INFOPLIST_FILE = LyrebirdScoreDemo/Info.plist;
MACOSX_DEPLOYMENT_TARGET = 15.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScoreDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 6.0;
};
name = Release;
};
A5D10000000000000000000F /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = macosx;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
A5D100000000000000000010 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = macosx;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
A5D10000000000000000000B /* Build configuration list for PBXNativeTarget "LyrebirdScoreDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
A5D10000000000000000000C /* Debug */,
A5D10000000000000000000D /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
A5D10000000000000000000E /* Build configuration list for PBXProject "LyrebirdScoreDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
A5D10000000000000000000F /* Debug */,
A5D100000000000000000010 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
/* Begin XCLocalSwiftPackageReference section */
A5D100000000000000000011 /* XCLocalSwiftPackageReference "../.." */ = {
isa = XCLocalSwiftPackageReference;
relativePath = ../..;
};
/* End XCLocalSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
A5D100000000000000000012 /* Lyrebird */ = {
isa = XCSwiftPackageProductDependency;
package = A5D100000000000000000011 /* XCLocalSwiftPackageReference "../.." */;
productName = Lyrebird;
};
/* End XCSwiftPackageProductDependency section */
};
rootObject = A5D100000000000000000001 /* Project object */;
}
@@ -0,0 +1,24 @@
{
"originHash" : "2c98cd4172bcfb3eff9cb6e34a538f80f5e424aa73fbd5bea2b20cf0c8b539b7",
"pins" : [
{
"identity" : "linenoise-swift",
"kind" : "remoteSourceControl",
"location" : "https://github.com/andybest/linenoise-swift",
"state" : {
"revision" : "afc897c02b030af7333105c4fedcd843a8339238",
"version" : "0.0.3"
}
},
{
"identity" : "nimble",
"kind" : "remoteSourceControl",
"location" : "https://github.com/Quick/Nimble.git",
"state" : {
"revision" : "e9d769113660769a4d9dd3afb855562c0b7ae7b0",
"version" : "7.3.4"
}
}
],
"version" : 3
}
@@ -0,0 +1,78 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2620"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES"
buildArchitectures = "Automatic">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A5D10000000000000000000A"
BuildableName = "LyrebirdScoreDemo"
BlueprintName = "LyrebirdScoreDemo"
ReferencedContainer = "container:LyrebirdScoreDemo.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
shouldAutocreateTestPlan = "YES">
</TestAction>
<LaunchAction
buildConfiguration = "Release"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A5D10000000000000000000A"
BuildableName = "LyrebirdScoreDemo"
BlueprintName = "LyrebirdScoreDemo"
ReferencedContainer = "container:LyrebirdScoreDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A5D10000000000000000000A"
BuildableName = "LyrebirdScoreDemo"
BlueprintName = "LyrebirdScoreDemo"
ReferencedContainer = "container:LyrebirdScoreDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,11 @@
// DemoProtocol.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
protocol DemoProtocol {
func runDemo()
}
@@ -0,0 +1,693 @@
// ScoreDemo.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LyrebirdSynth
/// Builds a multi-part Score using every DSL node type, exports MusicXML, round-trips
/// the document, and reports render statistics.
///
/// Call ``buildAndReport()`` after construction to export MusicXML and print the
/// round-trip summary. ``scheduleVoices(engine:)`` is marked ``@MainActor`` because
/// ``ScoreVoice`` (a ``SynthesizerBase`` subclass) is ``@MainActor``-isolated; call it
/// on the main thread before ``engine.start()``.
final class ScoreDemo: DemoProtocol {
// MARK: - Constants
/// Beats per minute for the demo score.
static let bpm: Double = 108.0
/// Seconds per beat at the demo tempo.
static let secondsPerBeat: Double = 60.0 / ScoreDemo.bpm
/// Extra render tail (seconds) to let the final release decay.
static let tailSeconds: Double = 1.2
/// Pan position for lead-part voices (MIDI channel 0): slightly left.
static let leadPan: Double = -0.4
/// Pan position for bass-part voices (other channels): slightly right.
static let bassPan: Double = 0.5
/// Scale applied to a `ScoreEvent`'s normalized velocity to set voice amplitude.
static let velocityToAmpScale: Double = 0.35
// MARK: - Properties
/// The score built at init time.
let score: Score
/// Total render duration in seconds, including tail.
let totalDuration: Double
// MARK: - Init
init() {
let builtScore: Score = ScoreDemo.makeScore()
self.score = builtScore
self.totalDuration = builtScore.totalBeats * ScoreDemo.secondsPerBeat
+ ScoreDemo.tailSeconds
}
// MARK: - DemoProtocol
/// Export MusicXML and print the round-trip event count. Does not interact with
/// the engine or schedule any voices.
func runDemo() {
// Step 1 — write MusicXML to Desktop.
let xmlURL: URL = FileManager.default.homeDirectoryForCurrentUser
.appendingPathComponent("Desktop/LyrebirdScoreDemo.musicxml")
let xmlString: String = score.toMusicXMLString()
do {
try xmlString.write(to: xmlURL, atomically: true, encoding: .utf8)
print("MusicXML written → \(xmlURL.path)")
} catch {
fputs("Failed to write MusicXML: \(error)\n", stderr)
}
// Step 2 — round-trip sanity check.
let xmlData: Data = score.toMusicXMLData()
do {
let rt: Score = try Score.fromMusicXML(data: xmlData)
let originalCount: Int = score.allEvents.count
let roundTripCount: Int = rt.allEvents.count
print("Round-trip events: \(originalCount) → \(roundTripCount)")
// Verify notation-only elements do not affect event count. Grace
// notes (lead), clef changes (bass), staff grouping + sustain-pedal
// marks (piano) are all skipped by flatten(), so the score's event
// count must equal the round-tripped count.
let selfConsistent: String = (originalCount == roundTripCount) ? "self-consistent" : "MISMATCH"
print("Notation-only event count: \(selfConsistent)")
// Verify tempo changes round-trip.
let originalChanges: Int = score.tempoChanges.count
let rtChanges: Int = rt.tempoChanges.count
print("Round-trip tempo changes: \(originalChanges) → \(rtChanges)")
if originalChanges == rtChanges {
for (orig, recovered): (TempoChange, TempoChange) in zip(score.tempoChanges, rt.tempoChanges) {
let measMatch: String = orig.measure == recovered.measure ? "OK" : "MISMATCH"
let bpmMatch: String = abs(orig.bpm - recovered.bpm) < 0.001 ? "OK" : "MISMATCH"
print(" TempoChange measure=\(orig.measure) \(measMatch) bpm=\(orig.bpm) \(bpmMatch)")
}
}
// Verify per-part key override + transpose round-trip on the clarinet part.
// Part order: 0=lead, 1=bass, 2=clarinet, 3=piano, 4=texture,
// 5=timeline, 6=autovoice, 7=polymeter — so the clarinet is index 2.
if rt.parts.count > 2 {
let clarinet: ScorePart = rt.parts[2]
let keyOK: String = (clarinet.keySignature == .aMajor) ? "OK" : "MISMATCH(\(String(describing: clarinet.keySignature)))"
let transposeOK: String = (clarinet.transpose == .bFlat) ? "OK" : "MISMATCH(\(String(describing: clarinet.transpose)))"
print("Clarinet part key override: \(keyOK)")
print("Clarinet part transpose (bFlat): \(transposeOK)")
print("Score key (G major): \(rt.keySignature == .gMajor ? "OK" : "MISMATCH(\(rt.keySignature))")")
}
} catch {
fputs("MusicXML round-trip failed: \(error)\n", stderr)
}
// Step 2b — sectioned showcase: multiple Sections assembled into one
// score (continuous measure numbers + per-section rehearsal marks),
// glissandi, slurs/hairpins, per-note display overrides, tacet fill,
// and a landscape page layout. Section labels export as standard
// <rehearsal> marks — system objects placed once above the top staff (tied
// to the section, not an instrument line, and collision-free). Some editors
// (e.g. Dorico) auto-sequence imported rehearsal marks as A, B, C and hide
// the authored text; that is an editor display setting. The
// `rehearsalMarksAsStaffText: true` option emits boxed <words> staff text
// instead, but that attaches to a staff and can collide with notation.
let showcase: Score = ScoreDemo.makeSectionedShowcase()
let showcaseURL: URL = FileManager.default.homeDirectoryForCurrentUser
.appendingPathComponent("Desktop/LyrebirdScoreSections.musicxml")
do {
try showcase.toMusicXMLString().write(to: showcaseURL, atomically: true, encoding: .utf8)
print("Sectioned showcase written → \(showcaseURL.path)")
// Report the assembled measure span + rehearsal marks.
let marks: [(measure: Int, label: String)] = showcase.rehearsalMarks
.sorted { $0.key < $1.key }
.map { (measure: $0.key, label: $0.value) }
let markList: String = marks.map { "\($0.label)@m\($0.measure)" }.joined(separator: ", ")
print("Sections → rehearsal marks: \(markList)")
print("Sectioned showcase parts: \(showcase.parts.map { $0.name }.joined(separator: ", "))")
} catch {
fputs("Failed to write sectioned showcase: \(error)\n", stderr)
}
// Step 3 — report render parameters.
let displayBeats: Double = score.totalBeats
let displayDur: Double = totalDuration
print(
String(
format: "Score: %.1f beats at %.0f BPM → %.2f s render (+ %.2f s tail)",
displayBeats,
ScoreDemo.bpm,
displayBeats * ScoreDemo.secondsPerBeat,
ScoreDemo.tailSeconds
)
)
print(String(format: "Total render: %.2f s", displayDur))
}
// MARK: - Voice scheduling
/// Schedule one ``ScoreVoice`` per non-rest event against the engine.
///
/// Must be called on the main actor because ``ScoreVoice`` (a ``SynthesizerBase``
/// subclass) is ``@MainActor``-isolated. Call this after constructing the engine
/// but before ``engine.start()``.
@MainActor
func scheduleVoices(engine: SynthesisEngine) {
let secondsPerBeat: Double = ScoreDemo.secondsPerBeat
let allEvents: [ScoreEvent] = score.allEvents
var scheduledCount: Int = 0
var failedCount: Int = 0
for event: ScoreEvent in allEvents {
guard !event.isRest else { continue }
guard let freqHz: Double = event.pitch.frequency else { continue }
let startSeconds: Double = event.beat * secondsPerBeat
let durSeconds: Double = event.performedDuration * secondsPerBeat
// Separate lead (slight left) from bass (slight right) by MIDI channel.
let pan: Double = event.channel == 0 ? ScoreDemo.leadPan : ScoreDemo.bassPan
let voice: ScoreVoice = ScoreVoice(
freqHz: freqHz,
amp: event.velocity * ScoreDemo.velocityToAmpScale,
durSeconds: durSeconds,
pan: pan
)
do {
try engine.schedule(voice, after: startSeconds)
scheduledCount += 1
} catch {
fputs("engine.schedule failed for beat \(event.beat): \(error)\n", stderr)
failedCount += 1
}
}
print("Scheduled \(scheduledCount) voices\(failedCount > 0 ? ", \(failedCount) failed" : "").")
}
// MARK: - Material-creation helpers
//
// Beyond hand-authoring notes, Lyrebird offers several ways to GENERATE score
// material. These helpers feed the `timeline` and `autovoice` parts.
// `ScoreTimeline` is throwing, so the `[ScoreElement]` is built here (outside
// the non-throwing score result-builder) and dropped into a `Part { … }` body.
/// Place notes at explicit musical beats and let the timeline fill the rests.
/// `BeatPosition.beat(_:)` is the felt-beat reading (4/4: beat 1 = downbeat,
/// beat 5 = bar-2 downbeat). See ``ScoreTimeline`` / ``BeatPosition``.
private static func makeTimelineMaterial() -> [ScoreElement] {
do {
return try ScoreTimeline.from(
(.beat(1.0), Note(.named(.d, 5), dur: .quarter, dyn: .mp)),
(.beat(5.0), Note(.named(.f, 5), dur: .quarter, dyn: .mp)),
(.bar(2, beat: 3.0), Note(.named(.a, 5), dur: .half, dyn: .mf, art: .tenuto)),
meter: MeterMap(.fourFour)
)
} catch {
print("[ScoreDemo] timeline material failed: \(error)")
return []
}
}
/// Overlapping placements distributed across voices automatically — a held
/// whole note under a moving line becomes two voices. See
/// ``ScoreTimeline/fillAutoVoiced(_:)``.
private static func makeAutoVoicedMaterial() -> [ScoreElement] {
do {
return try ScoreTimeline.fillAutoVoiced([
(beat: 0.0, element: Note(.named(.c, 4), dur: .whole, dyn: .p)),
(beat: 0.0, element: Note(.named(.e, 5), dur: .quarter, dyn: .mp)),
(beat: 1.0, element: Note(.named(.f, 5), dur: .quarter, dyn: .mp)),
(beat: 2.0, element: Note(.named(.g, 5), dur: .quarter, dyn: .mp)),
(beat: 3.0, element: Note(.named(.e, 5), dur: .quarter, dyn: .mp)),
])
} catch {
print("[ScoreDemo] auto-voiced material failed: \(error)")
return []
}
}
// MARK: - Score construction
/// Builds the demo score: eight parts, each chosen to exercise a different
/// authoring path.
///
/// The hand-authored `lead` part is written **inline** below to show direct
/// result-builder entry; every other part is built by its own `make…Part()`
/// helper for clearer encapsulation. The parts, in document order:
///
/// - **`lead`** *(inline)* — 8-bar melody: crescendo/diminuendo hairpins, a
/// triplet run, tied sixteenths, chords, a grace note (acciaccatura F♯5),
/// and a nested 5:4 ⊃ 3:2 tuplet.
/// - **`bass`** — sustained low line with double-stops, a mid-voice clef
/// change (bass → tenor → bass), a walking eighth-note run, and a triplet
/// fill. Hand-authored.
/// - **`clarinet`** — transposing-instrument demo (B♭): per-part key
/// override (A major) + `<transpose>`. Hand-authored.
/// - **`piano`** — grand staff. Staff 1 (treble) carries two voices (an
/// upper melody and a tied C-major triad); staff 2 (bass) carries a
/// sustained whole-note C under a sustain-pedal marking.
/// - **`texture`** — algorithmic generation via `Generate` (index-driven)
/// and `PatternNotes` (a seeded Brownian MIDI walk).
/// - **`timeline`** — notes placed at explicit `BeatPosition`s with rests
/// auto-filled (`ScoreTimeline`).
/// - **`autovoice`** — overlapping placements distributed across voices
/// automatically (`ScoreTimeline.fillAutoVoiced`).
/// - **`polymeter`** — runs in its OWN 3/4 meter while the score is 4/4
/// (per-part `MeterMap`).
///
/// Score-level features layered over all parts: a forward/backward repeat
/// with 1st/2nd endings (bars 1–4) and tempo changes at bar 3 (132 BPM) and
/// bar 7 (80 BPM). Both are notation-only — playback uses the base tempo.
private static func makeScore() -> Score {
return Score(
bpm: ScoreDemo.bpm,
timeSignature: TimeSignature(4, 4),
keySignature: .gMajor,
// Repeat of bars 1–3 with first/second endings. The backward repeat
// sits at the END of the first ending (bar 3) — the jump-back point.
// On the repeat, the first ending (bar 3) is skipped and the second
// ending (bar 4) plays straight through, so bar 4 has no repeat.
repeats: RepeatStructure(
forwardRepeatMeasures: [1],
backwardRepeatMeasures: [3],
endings: [
Ending(number: 1, startMeasure: 3, stopMeasure: 3),
Ending(number: 2, startMeasure: 4, stopMeasure: 4)
]
),
// Tempo changes. Bar 3 accelerates to 132 BPM; bar 7 relaxes to 80
// BPM. These are notation-only — playback still uses the base bpm
// (108). A tempo change is emitted in every part that reaches that
// measure: bar 3 exists in all parts (incl. the 4-bar piano), bar 7
// only in the 8-bar lead/bass.
tempoChanges: [
TempoChange(measure: 3, bpm: 132.0),
TempoChange(measure: 7, bpm: 80.0)
],
// Page layout — emitted as a MusicXML <defaults> block (US Letter,
// portrait). Engravers honour the page size, orientation, margins,
// and staff scaling on import.
pageLayout: PageLayout(size: .letter, orientation: .portrait)
) {
// Lead melody — kept INLINE to demonstrate direct result-builder
// entry. Every other part is built by a make…Part() helper below.
// 8 bars covering dynamics, articulations, a grace note, and a
// nested tuplet. Bars 1–2 include a Crescendo and Diminuendo hairpin.
Part("lead") {
// Bar 1 — arpeggiated C major with staccato, under a crescendo.
// The high C6 also starts a slur that overlaps into bar 2 —
// demonstrating a shared boundary where a slur-start and a
// hairpin coexist on the same note via the spanners: parameter.
Slur {
Crescendo {
Note(.named(.c, 5), dur: .quarter, dyn: .mf, art: .staccato)
Note(.named(.e, 5), dur: .quarter, dyn: .mf, art: .staccato)
Note(.named(.g, 5), dur: .quarter, dyn: .mf, art: .staccato)
// spanners: [.beginSlur] opens a slur here while the Crescendo
// block simultaneously marks this note with the wedge-start.
// The two annotations are independent fields on the atom and
// compose without conflict in MusicXML.
Note(.named(.c, 6), dur: .quarter, dyn: .f, art: .accent)
}
}
// Bar 2 — triplet run followed by legato half note, under a diminuendo.
// The slur started on the C6 above ends on the last triplet note (G5),
// which lies inside the Diminuendo block — the slur overlaps the hairpin.
Diminuendo {
Tuplet(3, inTimeOf: 2) {
Note(.named(.b, 5), dur: .quarter, dyn: .mp)
Note(.named(.a, 5), dur: .quarter, dyn: .mp, spanners: [.beginSlur])
// spanners: [.endSlur] closes the slur here. The Diminuendo
// block's wedge-start is on the B5 triplet note; the slur-stop
// lands on this G5 — overlapping spans, cleanly expressed.
Note(.named(.g, 5), dur: .quarter, dyn: .mp,
spanners: [.endSlur])
}
Note(.named(.f, 5), dur: .half, dyn: .p, art: .legato)
}
// Bar 3 — staccatissimo sixteenth notes, then tenuto half; the
// first two sixteenths are tied (authored tie: sounds
// as one eighth note but is notated as two tied sixteenths).
Note(.named(.e, 5), dur: .sixteenth, dyn: .ff, art: .staccatissimo, tie: true)
Note(.named(.e, 5), dur: .sixteenth, dyn: .ff)
Note(.named(.g, 5), dur: .sixteenth, dyn: .ff, art: .staccatissimo)
Note(.named(.a, 5), dur: .sixteenth, dyn: .ff, art: .staccatissimo)
Note(.named(.b, 5), dur: .half, dyn: .f, art: .tenuto)
Rest(dur: .quarter)
// Bar 4 — chord, rest, single note
Chord([.named(.c, 5), .named(.e, 5), .named(.g, 5)], dur: .half, dyn: .f, art: .accent)
Rest(dur: .quarter)
// Note-display override: a diamond notehead (e.g. a harmonic).
// Notation-only — the flattened event is unchanged.
Note(.named(.d, 5), dur: .quarter, dyn: .mf,
display: NoteDisplay(notehead: .diamond))
// Bar 5 — grace note (acciaccatura F#5) before a nested tuplet.
// Grace is notation-only; flatten() skips it and the
// event count is identical to a score without the grace note.
// The nested 5:4 ⊃ 3:2 tuplet demonstrates per-level
// <tuplet-actual>/<tuplet-normal> bracket engraving.
// Outer children: 3 quarters + inner(3 quarters × 2/3 = 2 quarter-slots)
// = 5 quarter-slots × 4/5 outer scale = 4 beats. Fits the 4/4 bar.
Grace(.named(.fSharp, 5))
Tuplet(5, inTimeOf: 4) {
Note(.named(.c, 5), dur: .quarter, dyn: .mp)
Note(.named(.d, 5), dur: .quarter, dyn: .mp)
Note(.named(.e, 5), dur: .quarter, dyn: .mp)
Tuplet(3, inTimeOf: 2) {
Note(.named(.f, 5), dur: .quarter, dyn: .mp)
Note(.named(.g, 5), dur: .quarter, dyn: .mp)
Note(.named(.gSharp, 5), dur: .quarter, dyn: .mp)
}
}
// Bar 6 — dotted quarter glissando down to the eighth, then a
// legato half. The glissando is a two-note span authored via the
// spanners: parameter (begin on A5, end on G5).
Note(.named(.a, 5), dur: .quarter.dotted, dyn: .mf,
spanners: [.beginGlissando(Glissando())])
Note(.named(.g, 5), dur: .eighth, dyn: .mp, spanners: [.endGlissando])
Note(.named(.fSharp, 5), dur: .half, dyn: .p, art: .legato)
// Bar 7 — marcato descent ppp
Note(.named(.e, 5), dur: .quarter, dyn: .fff, art: .marcato)
Note(.named(.d, 5), dur: .quarter, dyn: .ff)
Note(.named(.c, 5), dur: .quarter, dyn: .f)
Note(.named(.b, 4), dur: .quarter, dyn: .mf)
// Bar 8 — closing chord
Chord([.named(.c, 5), .named(.e, 5), .named(.g, 5), .named(.c, 6)], dur: .whole, dyn: .pp, art: .tenuto)
}
ScoreDemo.makeBassPart()
ScoreDemo.makeClarinetPart()
ScoreDemo.makePianoPart()
ScoreDemo.makeTexturePart()
ScoreDemo.makeTimelinePart()
ScoreDemo.makeAutoVoicePart()
ScoreDemo.makePolymeterPart()
}
}
// MARK: - Sectioned showcase
/// A second, self-contained score that demonstrates the section-based
/// authoring stack: multiple ``ScoreSection`` blocks assembled into one
/// score with continuous global measure numbers, per-section rehearsal
/// marks, a tacet instrument auto-filled with rests, glissandi/slides,
/// slurs and hairpins, an intra-note dynamic curve (messa di voce / niente
/// swell), per-note display overrides, and a landscape page layout.
///
/// Two instruments — `flute` (id `fl`) and `cello` (id `vc`) — are matched
/// across sections by `id`. Section labels are single letters (`A`, `B`, `C`):
/// rehearsal marks are system objects that editors typically render as a
/// sequence of letters, so single letters round-trip reliably while custom
/// words may be re-sequenced or hidden. Three sections run sequentially:
/// - **A** (4/4, 2 bars): flute states the theme under a slurred crescendo,
/// then a niente messa-di-voce swell (`dynamicCurve`) over the bar-2 whole
/// note; cello is TACET (auto-filled, stays bar-aligned).
/// - **B** (3/4, 2 bars): flute plays a wavy glissando and an x-notehead /
/// stemless note; cello enters with a straight `slide` glissando.
/// - **C** (4/4, 2 bars): a diminuendo close, a large-notehead final note,
/// sustained cello.
private static func makeSectionedShowcase() -> Score {
return Score(
bpm: 96.0,
keySignature: .cMajor,
// Landscape A4 — emitted as a MusicXML <defaults> block.
pageLayout: PageLayout(size: .a4, orientation: .landscape)
) {
Section("A") {
Part("flute", clef: .treble, id: "fl") {
Crescendo {
Slur {
Note(.named(.c, 5), dur: .quarter, dyn: .p)
Note(.named(.d, 5), dur: .quarter)
Note(.named(.e, 5), dur: .quarter)
Note(.named(.g, 5), dur: .quarter, dyn: .mf)
}
}
// Messa di voce on a single sustained note: a niente swell
// ◦< f >◦ authored via `dynamicCurve`. The dynamics and the
// crescendo/diminuendo hairpins (each closing on a niente
// circle) ride inside this one whole note — no tied split. The
// note's `dyn:` still drives playback velocity.
Note(.named(.c, 5), dur: .whole, dyn: .mf,
dynamicCurve: [(0.0, .niente), (0.5, .f), (1.0, .niente)])
}
// cello is tacet in section A — the lowering fills it with rests.
}
Section("B", meterMap: MeterMap(.threeFour)) {
Part("flute", clef: .treble, id: "fl") {
// Wavy glissando E5 → B5 (two-note span via spanners:).
Note(.named(.e, 5), dur: .quarter, dyn: .mf,
spanners: [.beginGlissando(Glissando())])
Note(.named(.b, 5), dur: .quarter, spanners: [.endGlissando])
// x-notehead (ghost / percussive) — notation-only.
Note(.named(.a, 5), dur: .quarter, display: NoteDisplay(notehead: .x))
// Bar 2: legato half + a stemless note.
Note(.named(.g, 5), dur: .half, dyn: .p, art: .legato)
Note(.named(.fSharp, 5), dur: .quarter,
display: NoteDisplay(hideStem: true))
}
Part("cello", clef: .bass, id: "vc") {
// Straight slide glissando C3 → G3, dashed line.
Note(.named(.c, 3), dur: .half.dotted, dyn: .mp,
spanners: [.beginGlissando(Glissando(kind: .slide, lineType: .dashed))])
Note(.named(.g, 3), dur: .half.dotted, spanners: [.endGlissando])
}
}
Section("C") {
Part("flute", clef: .treble, id: "fl") {
Diminuendo {
Note(.named(.g, 5), dur: .quarter, dyn: .f)
Note(.named(.e, 5), dur: .quarter)
Note(.named(.c, 5), dur: .half, dyn: .pp, art: .legato)
}
// Final note with a large notehead (single pitch, not a chord).
Note(.named(.c, 6), dur: .whole, dyn: .pp, art: .tenuto,
display: NoteDisplay(size: .large))
}
Part("cello", clef: .bass, id: "vc") {
Note(.named(.c, 3), dur: .whole, dyn: .mp)
Note(.named(.c, 3), dur: .whole, dyn: .pp)
}
}
}
}
// MARK: - Part-creation helpers
/// Bass line — sustained low harmonies with occasional double-stops, a
/// mid-voice clef change (bass → tenor → bass), a walking eighth-note run,
/// and a triplet fill. Single voice; carries Crescendo/Diminuendo-free
/// material at the low end of the texture.
private static func makeBassPart() -> ScorePart {
Part("bass", channel: 1, clef: .bass) {
// Bar 1 — low C whole note
Note(.named(.c, 2), dur: .whole, dyn: .mp)
// Bar 2 — G pedal
Note(.named(.g, 2), dur: .whole, dyn: .p)
// Bar 3 — half plus quarter, then quarter rest (sums to 4 beats)
Note(.named(.a, 2), dur: .half, dyn: .mf)
Note(.named(.e, 2), dur: .quarter, dyn: .p)
Rest(dur: .quarter)
// Bar 4 — double-stop chords
Chord([.named(.f, 2), .named(.c, 3)], dur: .half, dyn: .mp)
Chord([.named(.d, 2), .named(.a, 2)], dur: .half, dyn: .mp)
// Mid-voice clef change: switch to tenor clef for the
// walking line so it reads with fewer ledger lines, then switch
// back to bass for the low pedal in bar 6. Display-only — sounding
// pitches are unchanged.
ClefChange(.tenor)
// Bar 5 — walking eighth-note bass line
Note(.named(.c, 3), dur: .eighth, dyn: .mf)
Note(.named(.d, 3), dur: .eighth, dyn: .mp)
Note(.named(.e, 3), dur: .eighth, dyn: .mp)
Note(.named(.f, 3), dur: .eighth, dyn: .mp)
Note(.named(.g, 3), dur: .eighth, dyn: .mf)
Note(.named(.a, 3), dur: .eighth, dyn: .mp)
Note(.named(.b, 3), dur: .eighth, dyn: .mp)
Note(.named(.c, 4), dur: .eighth, dyn: .mf)
ClefChange(.bass)
// Bar 6 — pedal half + triplet fill
Note(.named(.g, 2), dur: .half, dyn: .mp, art: .tenuto)
Tuplet(3, inTimeOf: 2) {
Note(.named(.f, 2), dur: .quarter, dyn: .p)
Note(.named(.e, 2), dur: .quarter, dyn: .p)
Note(.named(.d, 2), dur: .quarter, dyn: .p)
}
// Bar 7 — marcato accent descent
Note(.named(.e, 2), dur: .quarter, dyn: .ff, art: .marcato)
Note(.named(.d, 2), dur: .quarter, dyn: .f, art: .staccato)
Note(.named(.c, 2), dur: .half, dyn: .mf)
// Bar 8 — final bass chord (ppp close)
Chord([.named(.c, 2), .named(.g, 2), .named(.c, 3)], dur: .whole, dyn: .ppp)
}
}
/// B♭ clarinet — transposing-instrument demonstration.
/// Score key: G major. Clarinet written key: A major (a major 2nd up,
/// because a B♭ instrument reads a major 2nd higher than concert pitch).
/// transpose: .bFlat → <transpose><diatonic>-1</diatonic><chromatic>-2</chromatic></transpose>.
/// Flatten returns these AS WRITTEN pitches; concert-pitch playback is future work.
/// Single voice.
private static func makeClarinetPart() -> ScorePart {
Part("clarinet", channel: 3, clef: .treble, keySignature: .aMajor, transpose: .bFlat) {
// Bar 1 — ascending A major scale fragment (written; sounds G major)
Note(.named(.a, 5), dur: .quarter, dyn: .mp)
Note(.named(.b, 5), dur: .quarter, dyn: .mp)
Note(.named(.cSharp, 6), dur: .quarter, dyn: .mf)
Note(.named(.d, 6), dur: .quarter, dyn: .mf)
// Bar 2 — descending to tonic (written A5, sounds G5)
Note(.named(.e, 6), dur: .quarter, dyn: .mf)
Note(.named(.d, 6), dur: .quarter, dyn: .mp)
Note(.named(.cSharp, 6), dur: .quarter, dyn: .mp)
Note(.named(.a, 5), dur: .quarter, dyn: .p)
}
}
/// Piano — a grand staff demonstrating multi-staff notation.
///
/// Staff 1 (treble) holds two independent voices:
/// - **Voice 1** — a 4-bar melodic fragment.
/// - **Voice 2** — sustained chord tones that overlay from beat 0; bars 1–2
/// tie a C-major triad (C4–E4–G4) across the barline so all three pitches
/// sustain.
/// Staff 2 (bass) holds **Voice 3** — a sustained whole-note C under a
/// sustain-pedal marking (pedal down before the note, released after it).
///
/// In MusicXML this encodes as one part with `<staves>2</staves>`, a
/// `<clef number="1">` (treble) / `<clef number="2">` (bass) pair, a
/// `<staff>` element on every note, `<backup>` between the three voices,
/// and `<pedal>` start/stop directions attached to staff 2.
private static func makePianoPart() -> ScorePart {
Part("piano", channel: 2, clef: .treble) {
Staff(1) {
Voice(1) {
// Bar 1 — stepwise ascent
Note(.named(.c, 5), dur: .quarter, dyn: .mp)
Note(.named(.d, 5), dur: .quarter, dyn: .mp)
Note(.named(.e, 5), dur: .quarter, dyn: .mf)
Note(.named(.f, 5), dur: .quarter, dyn: .mf)
// Bar 2 — triplet decoration with a half note landing
Tuplet(3, inTimeOf: 2) {
Note(.named(.g, 5), dur: .quarter, dyn: .mf)
Note(.named(.a, 5), dur: .quarter, dyn: .mp)
Note(.named(.g, 5), dur: .quarter, dyn: .mp)
}
Note(.named(.f, 5), dur: .half, dyn: .p, art: .legato)
// Bar 3 — eighth-note run with staccato
Note(.named(.e, 5), dur: .eighth, dyn: .f, art: .staccato)
Note(.named(.d, 5), dur: .eighth, dyn: .f, art: .staccato)
Note(.named(.c, 5), dur: .eighth, dyn: .mf, art: .staccato)
Note(.named(.d, 5), dur: .eighth, dyn: .mf, art: .staccato)
Note(.named(.e, 5), dur: .half, dyn: .p, art: .tenuto)
// Bar 4 — closing whole note
Note(.named(.c, 5), dur: .whole, dyn: .pp)
}
Voice(2) {
// Bar 1 — sustained C major triad tied to bar 2 (chord tie).
// The two identical chords sustain as one across the barline.
Chord([.named(.c, 4), .named(.e, 4), .named(.g, 4)], dur: .whole, dyn: .mp, tie: true)
// Bar 2 — same C major triad (tie target: merges with bar 1 above)
Chord([.named(.c, 4), .named(.e, 4), .named(.g, 4)], dur: .whole, dyn: .mp)
// Bar 3 — A minor
Chord([.named(.a, 3), .named(.c, 4), .named(.e, 4)], dur: .whole, dyn: .mp)
// Bar 4 — close on C major
Chord([.named(.c, 4), .named(.e, 4), .named(.g, 4)], dur: .whole, dyn: .pp)
}
}
Staff(2, clef: .bass) {
Voice(3) {
// Bar 1 — sustained bass C under the sustain pedal. Pedal
// down before the note, released after; both pedal marks are
// notation-only (skipped by flatten(), no ScoreEvent).
Pedal(.start)
Note(.named(.c, 3), dur: .whole, dyn: .mp)
Pedal(.stop)
}
}
}
}
/// Texture — algorithmic note generation. Demonstrates the two generative
/// helpers, both returning `[ScoreElement]` that drops straight into the Part
/// body via the result builder.
private static func makeTexturePart() -> ScorePart {
Part("texture", channel: 4, clef: .treble) {
// `Generate` maps each index 0..<8 through the builder closure —
// here a sixteenth-note whole-tone fragment driven by the index.
Generate(8) { i in
Note(midi: 72 + (i % 6) * 2, dur: .sixteenth, dyn: .pp, art: .staccato)
}
// `PatternNotes` pulls pitches and rhythms from `Pattern` value
// sources: a seeded Brownian MIDI walk for pitch, a repeating
// eighth/eighth/quarter cell for rhythm. Stops early if the pitch
// pattern exhausts before `count`.
PatternNotes(
count: 12,
midi: Pattern.brownian(low: 60.0, high: 84.0, step: 4.0, length: 12, seed: 42),
durations: Pattern.sequence([.eighth, .eighth, .quarter]),
dyn: .p
)
}
}
/// Timeline — notes placed at explicit musical beats (`BeatPosition`), with
/// rests auto-filled by `ScoreTimeline`. Material built in
/// ``makeTimelineMaterial()`` (`ScoreTimeline` is throwing). Single voice.
private static func makeTimelinePart() -> ScorePart {
let material: [ScoreElement] = ScoreDemo.makeTimelineMaterial()
return Part("timeline", channel: 5, clef: .treble) {
material
}
}
/// Auto-voiced — overlapping placements distributed across voices
/// automatically (a held whole note + a moving line → two voices). Material
/// built in ``makeAutoVoicedMaterial()``.
private static func makeAutoVoicePart() -> ScorePart {
let material: [ScoreElement] = ScoreDemo.makeAutoVoicedMaterial()
return Part("autovoice", channel: 6, clef: .treble) {
material
}
}
/// Polymeter — this part runs in its OWN 3/4 meter while the rest of the
/// score is 4/4. Per-part `meterMap` → independent barlines; the encoder
/// renders each part against its own meter. Single voice.
private static func makePolymeterPart() -> ScorePart {
Part("polymeter", channel: 7, clef: .bass, meterMap: MeterMap(.threeFour)) {
for _: Int in 0..<6 {
Note(.named(.g, 2), dur: .quarter, dyn: .mp)
}
}
}
}
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>NSDesktopFolderUsageDescription</key>
<string>LyrebirdScoreDemo writes rendered audio and MusicXML files to the Desktop.</string>
<key>NSDocumentsFolderUsageDescription</key>
<string>LyrebirdScoreDemo writes rendered audio files to Documents.</string>
</dict>
</plist>
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.app-sandbox</key>
<false/>
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
</dict>
</plist>
@@ -0,0 +1,76 @@
// ScoreVoice.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// A self-terminating NRT voice driven by a ``ScoreEvent``.
///
/// Plays a sawtooth oscillator through a percussive amplitude envelope. The
/// envelope runs to completion and frees the synthesizer node automatically
/// via ``DoneAction/freeNode``, so voices do not pile up during NRT render.
///
/// - Parameters:
/// - freqHz: Fundamental frequency in Hz. Stays within audible range; no internal clamping.
/// - amp: Linear amplitude in `[0, 1]` — maps directly from ``ScoreEvent/velocity``.
/// - durSeconds: Played duration in seconds. The sustain stage occupies the bulk of this
/// duration; a fixed 10 ms attack and 60 ms release are subtracted first. If
/// `durSeconds` is very short (< 70 ms), the sustain collapses to zero and the voice
/// becomes purely percussive.
/// - pan: Stereo position in `[-1, 1]`. Default `0.0` (centre).
final class ScoreVoice: SynthesizerBase {
/// Fundamental frequency in Hz. No internal clamping; stay within audible range.
let freqHz: Double
/// Linear amplitude in `[0, 1]`, from the score event's normalized velocity.
let amp: Double
/// Played duration in seconds — determines sustain stage length.
let durSeconds: Double
/// Stereo pan position in `[-1, 1]`.
let pan: Double
/// Fixed attack duration in seconds.
private static let attackSeconds: Double = 0.01
/// Fixed release duration in seconds.
private static let releaseSeconds: Double = 0.06
init(
freqHz: Double,
amp: Double,
durSeconds: Double,
pan: Double = 0.0
) {
self.freqHz = freqHz
self.amp = amp
self.durSeconds = durSeconds
self.pan = pan
super.init()
}
override func build() {
let attack: Double = ScoreVoice.attackSeconds
let release: Double = ScoreVoice.releaseSeconds
let sustainSeconds: Double = max(0.0, durSeconds - attack - release)
let envelope: Envelope = Envelope(
levels: [0.0, 1.0, 0.8, 0.0],
durations: [attack, sustainSeconds, release],
curves: [-4.0, 0.0, -6.0]
)
// Sawtooth oscillator scaled by envelope and amplitude.
let osc: OscSawtooth.Audio = OscSawtooth.Audio(freq: freqHz)
let env: EnvelopeGen.Control = EnvelopeGen.Control(
envelope: envelope,
doneAction: .freeNode
)
let sig: any ValidGeneratorInput = osc * env * amp
output(bus: 0, source: Pan2(input: sig, pan: pan))
}
}
@@ -0,0 +1,48 @@
// main.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LyrebirdSynth
// Output paths — both land on the Desktop.
let cafURL: URL = FileManager.default.homeDirectoryForCurrentUser
.appendingPathComponent("Desktop/LyrebirdScoreDemo.caf")
// Render parameters.
let sampleRate: Double = 48000
let blockSize: Int = 512
// Build the score first — totalDuration must be known before NRTDriver is created.
let demo: ScoreDemo = ScoreDemo()
let totalDuration: Double = demo.totalDuration
// MusicXML export and round-trip before audio engine creation.
demo.runDemo()
// Create NRTDriver and engine.
let driver: NRTDriver = NRTDriver(outputURL: cafURL, duration: totalDuration)
let engine: SynthesisEngine = SynthesisEngine(
blockSize: blockSize,
sampleRate: sampleRate,
numOutputChannels: 2,
numInputChannels: 0,
driver: driver
)
// Schedule all score voices. SynthesizerBase (and thus scheduleVoices) is
// @MainActor-isolated; SwiftPM's top-level entry point is itself main-actor
// isolated, so this is a plain direct call — no MainActor hop needed.
demo.scheduleVoices(engine: engine)
print(String(format: "Rendering %.2f s → %@", totalDuration, cafURL.path))
do {
try engine.start()
print("Done.")
} catch {
fputs("Render failed: \(error)\n", stderr)
exit(1)
}
+24
View File
@@ -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
}
+25
View File
@@ -0,0 +1,25 @@
// Package.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// swift-tools-version: 6.0
import PackageDescription
let package = Package(
name: "LyrebirdScoreDemo",
platforms: [.macOS(.v15)],
dependencies: [
.package(path: "../.."),
],
targets: [
.executableTarget(
name: "LyrebirdScoreDemo",
dependencies: [
.product(name: "Lyrebird", package: "LyrebirdII"),
],
path: "LyrebirdScoreDemo"
),
]
)
@@ -9,9 +9,10 @@
/* Begin PBXBuildFile section */
C8D0000000000000000000C /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8D00000000000000000007 /* main.swift */; };
C8D0000000000000000000D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8D00000000000000000008 /* AppDelegate.swift */; };
C8D0000000000000000000F /* LyrebirdUI in Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdUI */; };
C8D00000000000000000021 /* LyrebirdLiveCompile in Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001F /* LyrebirdLiveCompile */; };
C8D00000000000000000022 /* LyrebirdLiveCompileUI in Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUI */; };
C8D0000000000000000000F /* LyrebirdDynamic in Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdDynamic */; };
C8D00000000000000000022 /* LyrebirdLiveCompileUIDynamic in Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */; };
C8D00000000000000000036 /* LyrebirdDynamic in Embed Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdDynamic */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
C8D00000000000000000034 /* LyrebirdLiveCompileUIDynamic in Embed Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
@@ -27,14 +28,28 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
C8D0000000000000000000F /* LyrebirdUI in Frameworks */,
C8D00000000000000000021 /* LyrebirdLiveCompile in Frameworks */,
C8D00000000000000000022 /* LyrebirdLiveCompileUI in Frameworks */,
C8D0000000000000000000F /* LyrebirdDynamic in Frameworks */,
C8D00000000000000000022 /* LyrebirdLiveCompileUIDynamic in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXCopyFilesBuildPhase section */
C8D00000000000000000035 /* Embed Frameworks */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "";
dstSubfolderSpec = 10;
files = (
C8D00000000000000000036 /* LyrebirdDynamic in Embed Frameworks */,
C8D00000000000000000034 /* LyrebirdLiveCompileUIDynamic in Embed Frameworks */,
);
name = "Embed Frameworks";
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXGroup section */
C8D00000000000000000002 = {
isa = PBXGroup;
@@ -73,6 +88,7 @@
C8D00000000000000000011 /* Sources */,
C8D00000000000000000012 /* Frameworks */,
C8D00000000000000000013 /* Resources */,
C8D00000000000000000035 /* Embed Frameworks */,
);
buildRules = (
);
@@ -80,9 +96,8 @@
);
name = LyrebirdScratchDemo;
packageProductDependencies = (
C8D0000000000000000001D /* LyrebirdUI */,
C8D0000000000000000001F /* LyrebirdLiveCompile */,
C8D00000000000000000020 /* LyrebirdLiveCompileUI */,
C8D0000000000000000001D /* LyrebirdDynamic */,
C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */,
);
productName = LyrebirdScratchDemo;
productReference = C8D00000000000000000004 /* LyrebirdScratchDemo.app */;
@@ -248,6 +263,10 @@
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
// Xcode 26 explicit-module-build regression: SPM dynamic-library
// framework binaries (LyrebirdDynamic / LyrebirdLiveCompileUIDynamic)
// are not emitted under the integrated driver. Classic driver fixes it.
SWIFT_USE_INTEGRATED_DRIVER = NO;
};
name = Debug;
};
@@ -303,6 +322,8 @@
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
// Xcode 26 explicit-module-build regression — see Debug config.
SWIFT_USE_INTEGRATED_DRIVER = NO;
};
name = Release;
};
@@ -341,20 +362,15 @@
/* End XCLocalSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
C8D0000000000000000001D /* LyrebirdUI */ = {
C8D0000000000000000001D /* LyrebirdDynamic */ = {
isa = XCSwiftPackageProductDependency;
package = C8D0000000000000000001B /* XCLocalSwiftPackageReference "../.." */;
productName = LyrebirdUI;
productName = LyrebirdDynamic;
};
C8D0000000000000000001F /* LyrebirdLiveCompile */ = {
C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */ = {
isa = XCSwiftPackageProductDependency;
package = C8D0000000000000000001E /* XCLocalSwiftPackageReference "../../LiveCompile" */;
productName = LyrebirdLiveCompile;
};
C8D00000000000000000020 /* LyrebirdLiveCompileUI */ = {
isa = XCSwiftPackageProductDependency;
package = C8D0000000000000000001E /* XCLocalSwiftPackageReference "../../LiveCompile" */;
productName = LyrebirdLiveCompileUI;
productName = LyrebirdLiveCompileUIDynamic;
};
/* End XCSwiftPackageProductDependency section */
};
@@ -0,0 +1,24 @@
{
"originHash" : "52fa7c84ca46dcb1ce0f4374a4fb0a5d2c97be57f306d91b8e9efb54af7c3c9e",
"pins" : [
{
"identity" : "linenoise-swift",
"kind" : "remoteSourceControl",
"location" : "https://github.com/andybest/linenoise-swift",
"state" : {
"revision" : "afc897c02b030af7333105c4fedcd843a8339238",
"version" : "0.0.3"
}
},
{
"identity" : "nimble",
"kind" : "remoteSourceControl",
"location" : "https://github.com/Quick/Nimble.git",
"state" : {
"revision" : "e9d769113660769a4d9dd3afb855562c0b7ae7b0",
"version" : "7.3.4"
}
}
],
"version" : 3
}
@@ -7,18 +7,28 @@
import AppKit
import SwiftUI
import LyrebirdSynth
import LyrebirdUI
import LyrebirdLiveCompile
// LyrebirdLiveCompile (LiveSession, …) is re-exported by LyrebirdLiveCompileUI.
import LyrebirdLiveCompileUI
// This demo deliberately does NOT link `LyrebirdUI`. The live-compile stack
// (`LyrebirdLiveCompileUIDynamic`) dynamic-links the single shared
// `LyrebirdDynamic.framework` copy of `LyrebirdSynth`; linking the static
// `LyrebirdUI` product would static-fold a SECOND copy of every `LyrebirdSynth`
// ObjC class into the app binary (intra-package `LyrebirdUI → LyrebirdSynth` is
// always a static edge), producing duplicate-class registration and the
// "mysterious crashes" the runtime warns about. The only `LyrebirdUI` symbol
// this demo used was `LyrebirdWindow`, an `NSWindow`/`NSHostingController`
// wrapper with no `LyrebirdSynth` dependency — inlined below instead.
final class AppDelegate: NSObject, NSApplicationDelegate {
let engine: SynthesisEngine
let session: LiveSession
var model: LyrebirdScratchModel?
var menuController: LyrebirdScratchMenuController?
var window: LyrebirdWindow?
var window: NSWindow?
@MainActor
init(engine: SynthesisEngine) {
self.engine = engine
self.session = LiveSession(engine: engine)
@@ -32,20 +42,30 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
print("[LyrebirdScratchDemo] Engine failed to start: \(error)")
}
let model = LyrebirdScratchModel(session: session)
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session)
self.model = model
let menuController = LyrebirdScratchMenuController(model: model)
let menuController: LyrebirdScratchMenuController = LyrebirdScratchMenuController(model: model)
menuController.installMainMenu()
self.menuController = menuController
window = LyrebirdWindow(
title: "Lyrebird — Live Scratch",
width: 720,
height: 560
let windowWidth: CGFloat = 720
let windowHeight: CGFloat = 560
let hosting: NSHostingController<LyrebirdScratchView> =
NSHostingController(rootView: LyrebirdScratchView(model: model))
let initialSize: CGSize = CGSize(width: windowWidth, height: windowHeight)
let win: NSWindow = NSWindow(
contentRect: NSRect(origin: .zero, size: initialSize),
styleMask: [.titled, .closable, .resizable, .miniaturizable],
backing: .buffered,
defer: false
)
window?.open {
LyrebirdScratchView(model: model)
}
// Keep ownership in Swift — NSWindow defaults to releasing on close.
win.isReleasedWhenClosed = false
win.title = "Lyrebird — Live Scratch"
win.contentViewController = hosting
win.center()
win.makeKeyAndOrderFront(nil)
self.window = win
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
@@ -17,7 +17,7 @@
This app is a direct-distribution developer tool, not a Mac App Store
submission. Sandbox OFF is the only viable configuration for v1.
Phase 147 polish can revisit if an XPC-worker approach is adopted.
This could be revisited if an XPC-worker approach is adopted.
com.apple.security.app-sandbox key is absent (defaults false).
-->
@@ -6,9 +6,8 @@
import AppKit
import LyrebirdSynth
import LyrebirdLiveCompile
let engine = SynthesisEngine(
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 512,
sampleRate: 48000,
numOutputChannels: 2,
@@ -16,8 +15,14 @@ let engine = SynthesisEngine(
driver: CoreAudioDriver()
)
let delegate = AppDelegate(engine: engine)
let app = NSApplication.shared
app.setActivationPolicy(.regular)
app.delegate = delegate
app.run()
// AppDelegate.init is `@MainActor` (mirrors the other demos' bootstrap — since
// `SynthesizerBase` is `@MainActor`, AppKit-side construction is main-actor
// isolated). Program entry runs on the main thread, so assert main-actor
// isolation for the AppKit bootstrap rather than hopping asynchronously.
MainActor.assumeIsolated {
let delegate: AppDelegate = AppDelegate(engine: engine)
let app: NSApplication = NSApplication.shared
app.setActivationPolicy(.regular)
app.delegate = delegate
app.run()
}
@@ -16,6 +16,7 @@ private let demo: Demo = .vector
// ──────────────────────────────────────────────────────────────────────────────
@main
@MainActor
struct LyrebirdiOSDemoApp: App {
let engine: SynthesisEngine
@@ -13,6 +13,7 @@ import LyrebirdSynth
/// first taps "Start Synthesizer" — this is necessary because
/// `SpectralBinDelayUI.init(sampleRate:)` requires the engine's committed
/// sample rate, which is only valid after `engine.start()` returns.
@MainActor
@Observable
final class BinDelayController {
@@ -7,6 +7,7 @@
import Observation
import LyrebirdSynth
@MainActor
@Observable
final class NoteController {
@@ -7,6 +7,7 @@
import Observation
import LyrebirdSynth
@MainActor
@Observable
final class VectorOscillatorController {