Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 73191c958f | |||
| ca1ee503cc | |||
| 1c03e39eac | |||
| f59fd3b55a |
@@ -61,6 +61,7 @@ The `.githooks/pre-commit` hook calls `--check`. Skips silently when `~/.claude/
|
||||
- TemporalStream / language-side value generation → `Sources/Lyrebird/Lyrebird.docc/TemporalDemand.md`
|
||||
- Polyphonic voice pool / step sequencer → `docs/tooling/routine-task.md`
|
||||
- Score / ScorePlayer / SMF / MusicXML → `Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md`
|
||||
- Pitch / scale theory toolkit (spelling-aware `Interval` / `Scale` / `PitchCollection` / 12-tone rows, diatonic-vs-chromatic transposition, scale mapping; → notation + Hz/seconds for synthesis) → `docs/stdlib/theory.md` (types under `Sources/Lyrebird/Score/Theory/`)
|
||||
- Performance event sequencing / `LyrebirdProcess` / `LyrebirdEventList` → `Sources/Lyrebird/Lyrebird.docc/ProcessSystem.md`
|
||||
- NRT / offline render → `docs/tooling/nrt-guide.md`
|
||||
|
||||
@@ -138,7 +139,7 @@ One-liners. Detail and rationale lives in linked docs.
|
||||
|
||||
**Never drop new files at `Sources/Lyrebird/` root.** Every new `.swift` file goes into a subfolder grouped by function. Existing top-level subfolders (alphabetical):
|
||||
|
||||
`AUv3/` `AudioDrivers/` `Buffers/` `Buses/` `Capture/` `Diagnostics/` `Distributions/` `Engine/` `Envelopes/` `External/` `GeneratorCore/` `Generators/` `Kinds/` `MIDI/` `Math/` `NodeTree/` `OSC/` `Oversampling/` `Parameters/` `Patterns/` `Process/` `Scheduling/` `Score/` `Spectral/` `Synthesizer/` `TemporalStream/` `Trigger/` `ValueCompute/` `Voices/`
|
||||
`AUv3/` `AudioDrivers/` `Buffers/` `Buses/` `Capture/` `Diagnostics/` `Distributions/` `Engine/` `Envelopes/` `External/` `GeneratorCore/` `Generators/` `Kinds/` `MIDI/` `Math/` `NodeTree/` `OSC/` `Oversampling/` `Parameters/` `Patterns/` `Process/` `Scheduling/` `Score/` `Spectral/` `Synthesizer/` `TemporalStream/` `Trigger/` `Utilities/` `ValueCompute/` `Voices/`
|
||||
|
||||
Rule:
|
||||
|
||||
@@ -178,6 +179,23 @@ Call-site pattern: every `engine.add` invocation needs `try`. In non-throwing co
|
||||
|
||||
Hard rules. Review agents flag violations.
|
||||
|
||||
### No phase numbers in code or docs
|
||||
Never write phase numbers (`Phase 228`, `Phase 228c`, `phase-224`, `pre-Phase-209c`, `// Phase 216:`, `(Phase 201)`, `— Phase 214`) in source comments, doc-comments (`///`), `.docc` markdown, `@Suite`/`@Test` display strings, or test function / type / file names. Phase numbers are meaningless to external readers — they belong **only** in planning docs (`docs/00-working-order.md`, `docs/01-completed-working-order.md`), commit messages, and `MEMORY.md`/phase history. Describe the **behavior or reason** instead:
|
||||
```swift
|
||||
// WRONG
|
||||
// Phase 216: emit a tempo direction for this measure when a TempoChange targets it.
|
||||
let cap = ... // Phase 228c
|
||||
/// > Note: Phase 224 wires this as model state.
|
||||
@Suite("EngineHost (Phase 197)")
|
||||
|
||||
// RIGHT
|
||||
// Emit a tempo direction for this measure when a TempoChange targets it.
|
||||
let cap = ...
|
||||
/// > Note: this is model state.
|
||||
@Suite("EngineHost")
|
||||
```
|
||||
Exception: the DSP term **"phase"** that is NOT a planning reference — oscillator `phase`, `phase accumulator`, `phase offset`, `_phase`, `initPhase`, `phase modulation`, "Phase 0.25 in an 8-sample table" — is a real audio term, never touch it. The rule targets `Phase <number>` planning tags only.
|
||||
|
||||
### No force unwraps
|
||||
Never `!` on optionals or `try!`. Hotspots: `UnsafeBufferPointer.baseAddress` in Accelerate calls, `Array.first!`/`last!` on output channels, `try!` in test helpers, `dict[key]!`.
|
||||
```swift
|
||||
|
||||
@@ -18,7 +18,7 @@ final class BufferDemos: DemoProtocol {
|
||||
func runDemo() {
|
||||
// BufferDemos.swift lives at .../Demos/LyrebirdDemo/LyrebirdDemo/Demos/BufferDemos.swift
|
||||
// — 4 components up to reach .../Demos/ where Perc.aiff lives.
|
||||
let percURL = URL(fileURLWithPath: #filePath)
|
||||
let percURL: URL = URL(fileURLWithPath: #filePath)
|
||||
.deletingLastPathComponent() // .../Demos/
|
||||
.deletingLastPathComponent() // .../LyrebirdDemo/
|
||||
.deletingLastPathComponent() // .../LyrebirdDemo (package)/
|
||||
@@ -35,13 +35,66 @@ final class BufferDemos: DemoProtocol {
|
||||
exit(1)
|
||||
}
|
||||
|
||||
let sampleRate = engine.sampleRate
|
||||
let sampleRate: Double = engine.sampleRate
|
||||
|
||||
// SynthesizerBase is @MainActor-isolated. LyrebirdTask.run's body is @Sendable and
|
||||
// non-async, so synth inits must happen BEFORE the closure on the main thread.
|
||||
// runDemo() is reached from main.swift on the main thread, so assumeIsolated is valid.
|
||||
|
||||
let pitchSteps: [(Double, String)] = [
|
||||
(0.5, "0.5 — octave down"),
|
||||
(0.75, "0.75 — minor third down"),
|
||||
(1.0, "1.0 — original pitch"),
|
||||
(1.5, "1.5 — perfect fifth up"),
|
||||
(2.0, "2.0 — octave up"),
|
||||
]
|
||||
|
||||
let spectralRatios: [(Double, String)] = [
|
||||
(0.5, "0.5 — octave down (phase vocoder)"),
|
||||
(1.0, "1.0 — no shift (phase vocoder passthrough)"),
|
||||
(1.5, "1.5 — perfect fifth up (phase vocoder)"),
|
||||
(2.0, "2.0 — octave up (phase vocoder)"),
|
||||
]
|
||||
|
||||
let diffuseSteps: [(Double, String)] = [
|
||||
(0.0, "0.0 — bypass (mono passthrough on both channels)"),
|
||||
(0.5, "0.5 — half decorrelation"),
|
||||
(1.0, "1.0 — full per-channel phase randomisation"),
|
||||
]
|
||||
|
||||
let stretchSteps: [(Double, String)] = [
|
||||
(3.0, "3.0 — 3× stretch (one-third speed, pitch preserved)"),
|
||||
(1.5, "1.5 — 1.5× stretch (three-quarter speed, pitch preserved)"),
|
||||
(1.0, "1.0 — native speed (no stretch)"),
|
||||
(0.5, "0.5 — 2× compression (double speed, pitch preserved)"),
|
||||
(0.33, "0.33 — 3× compression (triple speed, pitch preserved)"),
|
||||
]
|
||||
|
||||
// Pre-construct all synthesizers on the main actor before entering the @Sendable closure.
|
||||
let (demo1, demo2, demo3, pitchRatioNode, demo4Array, demo5Array, demo6Array):
|
||||
(PercPlayBuffer, PercBufferRead, PercPitchShift, ParameterNode,
|
||||
[PercSpectralPitchShift], [PercSpectralStereoDiffuse], [PercTimeStretch]) =
|
||||
MainActor.assumeIsolated {
|
||||
let d1: PercPlayBuffer = PercPlayBuffer(buffer: percBuffer, engineSampleRate: sampleRate)
|
||||
let d2: PercBufferRead = PercBufferRead(buffer: percBuffer)
|
||||
let d3: PercPitchShift = PercPitchShift(buffer: percBuffer, engineSampleRate: sampleRate)
|
||||
let prNode: ParameterNode = d3.$pitchRatio
|
||||
|
||||
let d4: [PercSpectralPitchShift] = spectralRatios.map { ratio, _ in
|
||||
PercSpectralPitchShift(buffer: percBuffer, pitchRatio: ratio, engineSampleRate: sampleRate)
|
||||
}
|
||||
let d5: [PercSpectralStereoDiffuse] = diffuseSteps.map { amount, _ in
|
||||
PercSpectralStereoDiffuse(buffer: percBuffer, amount: amount, engineSampleRate: sampleRate)
|
||||
}
|
||||
let d6: [PercTimeStretch] = stretchSteps.map { factor, _ in
|
||||
PercTimeStretch(buffer: percBuffer, stretchFactor: factor)
|
||||
}
|
||||
return (d1, d2, d3, prNode, d4, d5, d6)
|
||||
}
|
||||
|
||||
LyrebirdTask.run(engine: engine) { ctx in
|
||||
// Demo 1 — PlayBuffer (looping at native rate)
|
||||
|
||||
print("\n── Demo 1: PlayBuffer (looping) ──")
|
||||
let demo1 = PercPlayBuffer(buffer: percBuffer, engineSampleRate: sampleRate)
|
||||
ctx.add(demo1)
|
||||
try ctx.wait(seconds: 6)
|
||||
ctx.remove(demo1)
|
||||
@@ -49,7 +102,6 @@ final class BufferDemos: DemoProtocol {
|
||||
|
||||
// Demo 2 — BufferRead (sine-wave position scan)
|
||||
print("\n── Demo 2: BufferRead (sine-wave position scan) ──")
|
||||
let demo2 = PercBufferRead(buffer: percBuffer)
|
||||
ctx.add(demo2)
|
||||
try ctx.wait(seconds: 6)
|
||||
ctx.remove(demo2)
|
||||
@@ -57,19 +109,11 @@ final class BufferDemos: DemoProtocol {
|
||||
|
||||
// Demo 3 — PlayBuffer → PitchShift (cycling through pitch ratios)
|
||||
print("\n── Demo 3: PlayBuffer → PitchShift ──")
|
||||
let demo3 = PercPitchShift(buffer: percBuffer, engineSampleRate: sampleRate)
|
||||
ctx.add(demo3)
|
||||
|
||||
let pitchSteps: [(Double, String)] = [
|
||||
(0.5, "0.5 — octave down"),
|
||||
(0.75, "0.75 — minor third down"),
|
||||
(1.0, "1.0 — original pitch"),
|
||||
(1.5, "1.5 — perfect fifth up"),
|
||||
(2.0, "2.0 — octave up"),
|
||||
]
|
||||
for (ratio, label) in pitchSteps {
|
||||
print(" pitchRatio \(label)")
|
||||
demo3.pitchRatio = ratio
|
||||
// Update via ParameterNode.value — nonisolated atomic setter, RT-safe.
|
||||
pitchRatioNode.value = ratio
|
||||
try ctx.wait(seconds: 3)
|
||||
}
|
||||
ctx.remove(demo3)
|
||||
@@ -77,16 +121,9 @@ final class BufferDemos: DemoProtocol {
|
||||
|
||||
// Demo 4 — PlayBuffer → SpectralChain.Audio (with SpectralPitchShift)
|
||||
print("\n── Demo 4: PlayBuffer → SpectralChain.Audio (SpectralPitchShift) ──")
|
||||
|
||||
let spectralRatios: [(Double, String)] = [
|
||||
(0.5, "0.5 — octave down (phase vocoder)"),
|
||||
(1.0, "1.0 — no shift (phase vocoder passthrough)"),
|
||||
(1.5, "1.5 — perfect fifth up (phase vocoder)"),
|
||||
(2.0, "2.0 — octave up (phase vocoder)"),
|
||||
]
|
||||
for (ratio, label) in spectralRatios {
|
||||
for (index, (_, label)) in spectralRatios.enumerated() {
|
||||
print(" pitchRatio \(label)")
|
||||
let demo4 = PercSpectralPitchShift(buffer: percBuffer, pitchRatio: ratio, engineSampleRate: sampleRate)
|
||||
let demo4: PercSpectralPitchShift = demo4Array[index]
|
||||
ctx.add(demo4)
|
||||
try ctx.wait(seconds: 5)
|
||||
ctx.remove(demo4)
|
||||
@@ -95,16 +132,9 @@ final class BufferDemos: DemoProtocol {
|
||||
|
||||
// Demo 5 — SpectralChain.Audio fan-out (mono → 2-channel decorrelated stereo)
|
||||
print("\n── Demo 5: SpectralChain.Audio fan-out (SpectralStereoDiffuse) ──")
|
||||
|
||||
let diffuseSteps: [(Double, String)] = [
|
||||
(0.0, "0.0 — bypass (mono passthrough on both channels)"),
|
||||
(0.5, "0.5 — half decorrelation"),
|
||||
(1.0, "1.0 — full per-channel phase randomisation"),
|
||||
]
|
||||
for (amount, label) in diffuseSteps {
|
||||
for (index, (_, label)) in diffuseSteps.enumerated() {
|
||||
print(" amount \(label)")
|
||||
let demo5 = PercSpectralStereoDiffuse(
|
||||
buffer: percBuffer, amount: amount, engineSampleRate: sampleRate)
|
||||
let demo5: PercSpectralStereoDiffuse = demo5Array[index]
|
||||
ctx.add(demo5)
|
||||
try ctx.wait(seconds: 5)
|
||||
ctx.remove(demo5)
|
||||
@@ -113,17 +143,9 @@ final class BufferDemos: DemoProtocol {
|
||||
|
||||
// Demo 6 — TimeStretch (granular, pitch-preserved time stretching + compression)
|
||||
print("\n── Demo 6: TimeStretch (granular time-stretch / compression) ──")
|
||||
|
||||
let stretchSteps: [(Double, String)] = [
|
||||
(3.0, "3.0 — 3× stretch (one-third speed, pitch preserved)"),
|
||||
(1.5, "1.5 — 1.5× stretch (three-quarter speed, pitch preserved)"),
|
||||
(1.0, "1.0 — native speed (no stretch)"),
|
||||
(0.5, "0.5 — 2× compression (double speed, pitch preserved)"),
|
||||
(0.33, "0.33 — 3× compression (triple speed, pitch preserved)"),
|
||||
]
|
||||
for (factor, label) in stretchSteps {
|
||||
for (index, (_, label)) in stretchSteps.enumerated() {
|
||||
print(" stretchFactor \(label)")
|
||||
let demo6 = PercTimeStretch(buffer: percBuffer, stretchFactor: factor)
|
||||
let demo6: PercTimeStretch = demo6Array[index]
|
||||
ctx.add(demo6)
|
||||
try ctx.wait(seconds: 6)
|
||||
ctx.remove(demo6)
|
||||
|
||||
@@ -4,14 +4,6 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
//
|
||||
// BufferDemos 2.swift
|
||||
// LyrebirdDemo
|
||||
//
|
||||
// Created by Joshua Parmenter on 5/6/26.
|
||||
//
|
||||
|
||||
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
@@ -25,13 +17,17 @@ final class ReverbDemo: DemoProtocol {
|
||||
|
||||
func runDemo() {
|
||||
|
||||
let sampleRate = engine.sampleRate
|
||||
// sets up its own thread / timing, etc
|
||||
LyrebirdTask.run(engine: engine) { [sampleRate] ctx in
|
||||
let sampleRate: Double = engine.sampleRate
|
||||
|
||||
// SynthesizerBase is @MainActor-isolated. Pre-construct the synth on the main actor
|
||||
// before entering the @Sendable LyrebirdTask closure. runDemo() is reached from
|
||||
// main.swift on the main thread, so assumeIsolated is valid.
|
||||
let reverbDemo: GVerbTest = MainActor.assumeIsolated {
|
||||
GVerbTest(sampleRate: sampleRate)
|
||||
}
|
||||
|
||||
LyrebirdTask.run(engine: engine) { ctx in
|
||||
ctx.tempo = 60.0
|
||||
let reverbDemo = GVerbTest(
|
||||
sampleRate: sampleRate
|
||||
)
|
||||
ctx.add(reverbDemo)
|
||||
try ctx.wait(beats: 6) // could also use seconds
|
||||
ctx.remove(reverbDemo)
|
||||
@@ -39,4 +35,3 @@ final class ReverbDemo: DemoProtocol {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
let binDelayController: BinDelayController
|
||||
var window: LyrebirdWindow?
|
||||
|
||||
@MainActor
|
||||
init(engine: SynthesisEngine) {
|
||||
let scopeCapture = ScopeCapture(buses: [0, 1], bufferSize: 2048)
|
||||
engine.scopeTap = scopeCapture
|
||||
|
||||
@@ -13,6 +13,7 @@ import LyrebirdSynth
|
||||
/// first taps "Start Synthesizer" — this is necessary because
|
||||
/// `SpectralBinDelayUI.init(sampleRate:)` requires the engine's committed
|
||||
/// sample rate, which is only valid after `engine.start()` returns.
|
||||
@MainActor
|
||||
@Observable
|
||||
final class BinDelayController {
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
import Observation
|
||||
import LyrebirdSynth
|
||||
|
||||
@MainActor
|
||||
@Observable
|
||||
final class NoteController {
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
import Observation
|
||||
import LyrebirdSynth
|
||||
|
||||
@MainActor
|
||||
@Observable
|
||||
final class VectorOscillatorController {
|
||||
|
||||
|
||||
@@ -15,8 +15,13 @@ let engine = SynthesisEngine(
|
||||
driver: CoreAudioDriver()
|
||||
)
|
||||
|
||||
let delegate = AppDelegate(engine: engine)
|
||||
let app = NSApplication.shared
|
||||
app.setActivationPolicy(.regular)
|
||||
app.delegate = delegate
|
||||
app.run()
|
||||
// AppDelegate.init is @MainActor (it builds @MainActor SynthesizerBase synths
|
||||
// and UI controllers). Program entry runs on the main thread, so assert main-
|
||||
// actor isolation for the AppKit bootstrap rather than hopping asynchronously.
|
||||
MainActor.assumeIsolated {
|
||||
let delegate: AppDelegate = AppDelegate(engine: engine)
|
||||
let app: NSApplication = NSApplication.shared
|
||||
app.setActivationPolicy(.regular)
|
||||
app.delegate = delegate
|
||||
app.run()
|
||||
}
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"originHash" : "2c98cd4172bcfb3eff9cb6e34a538f80f5e424aa73fbd5bea2b20cf0c8b539b7",
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "linenoise-swift",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/andybest/linenoise-swift",
|
||||
"state" : {
|
||||
"revision" : "afc897c02b030af7333105c4fedcd843a8339238",
|
||||
"version" : "0.0.3"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "nimble",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/Quick/Nimble.git",
|
||||
"state" : {
|
||||
"revision" : "e9d769113660769a4d9dd3afb855562c0b7ae7b0",
|
||||
"version" : "7.3.4"
|
||||
}
|
||||
}
|
||||
],
|
||||
"version" : 3
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
// !$*UTF8*$!
|
||||
{
|
||||
archiveVersion = 1;
|
||||
classes = {
|
||||
};
|
||||
objectVersion = 60;
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
A5D100000000000000000007 /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5D100000000000000000006 /* main.swift */; };
|
||||
A5D100000000000000000013 /* Lyrebird in Frameworks */ = {isa = PBXBuildFile; productRef = A5D100000000000000000012 /* Lyrebird */; };
|
||||
A5D100000000000000000015 /* ScoreVoice.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5D100000000000000000014 /* ScoreVoice.swift */; };
|
||||
A5D100000000000000000019 /* DemoProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5D100000000000000000018 /* DemoProtocol.swift */; };
|
||||
A5D10000000000000000001B /* ScoreDemo.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5D10000000000000000001A /* ScoreDemo.swift */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
A5D100000000000000000004 /* LyrebirdScoreDemo */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = LyrebirdScoreDemo; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
A5D100000000000000000006 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };
|
||||
A5D100000000000000000014 /* ScoreVoice.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScoreVoice.swift; sourceTree = "<group>"; };
|
||||
A5D100000000000000000017 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
A5D100000000000000000020 /* LyrebirdScoreDemo.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = LyrebirdScoreDemo.entitlements; sourceTree = "<group>"; };
|
||||
A5D100000000000000000018 /* DemoProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DemoProtocol.swift; sourceTree = "<group>"; };
|
||||
A5D10000000000000000001A /* ScoreDemo.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScoreDemo.swift; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
A5D100000000000000000009 /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
A5D100000000000000000013 /* Lyrebird in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
A5D100000000000000000002 = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
A5D100000000000000000005 /* LyrebirdScoreDemo */,
|
||||
A5D100000000000000000003 /* Products */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
A5D100000000000000000003 /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
A5D100000000000000000004 /* LyrebirdScoreDemo */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
A5D100000000000000000005 /* LyrebirdScoreDemo */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
A5D100000000000000000006 /* main.swift */,
|
||||
A5D100000000000000000016 /* Synthesizers */,
|
||||
A5D10000000000000000001C /* Demos */,
|
||||
A5D100000000000000000017 /* Info.plist */,
|
||||
A5D100000000000000000020 /* LyrebirdScoreDemo.entitlements */,
|
||||
);
|
||||
path = LyrebirdScoreDemo;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
A5D100000000000000000016 /* Synthesizers */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
A5D100000000000000000014 /* ScoreVoice.swift */,
|
||||
);
|
||||
path = Synthesizers;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
A5D10000000000000000001C /* Demos */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
A5D100000000000000000018 /* DemoProtocol.swift */,
|
||||
A5D10000000000000000001A /* ScoreDemo.swift */,
|
||||
);
|
||||
path = Demos;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
A5D10000000000000000000A /* LyrebirdScoreDemo */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = A5D10000000000000000000B /* Build configuration list for PBXNativeTarget "LyrebirdScoreDemo" */;
|
||||
buildPhases = (
|
||||
A5D100000000000000000008 /* Sources */,
|
||||
A5D100000000000000000009 /* Frameworks */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
);
|
||||
name = LyrebirdScoreDemo;
|
||||
packageProductDependencies = (
|
||||
A5D100000000000000000012 /* Lyrebird */,
|
||||
);
|
||||
productName = LyrebirdScoreDemo;
|
||||
productReference = A5D100000000000000000004 /* LyrebirdScoreDemo */;
|
||||
productType = "com.apple.product-type.tool";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
|
||||
/* Begin PBXProject section */
|
||||
A5D100000000000000000001 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
BuildIndependentTargetsInParallel = 1;
|
||||
LastSwiftUpdateCheck = 1600;
|
||||
LastUpgradeCheck = 1600;
|
||||
TargetAttributes = {
|
||||
A5D10000000000000000000A = {
|
||||
CreatedOnToolsVersion = 16.0;
|
||||
};
|
||||
};
|
||||
};
|
||||
buildConfigurationList = A5D10000000000000000000E /* Build configuration list for PBXProject "LyrebirdScoreDemo" */;
|
||||
compatibilityVersion = "Xcode 14.0";
|
||||
developmentRegion = en;
|
||||
hasScannedForEncodings = 0;
|
||||
knownRegions = (
|
||||
en,
|
||||
Base,
|
||||
);
|
||||
mainGroup = A5D100000000000000000002;
|
||||
packageReferences = (
|
||||
A5D100000000000000000011 /* XCLocalSwiftPackageReference "../.." */,
|
||||
);
|
||||
productRefGroup = A5D100000000000000000003 /* Products */;
|
||||
projectDirPath = "";
|
||||
projectRoot = "";
|
||||
targets = (
|
||||
A5D10000000000000000000A /* LyrebirdScoreDemo */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
A5D100000000000000000008 /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
A5D100000000000000000007 /* main.swift in Sources */,
|
||||
A5D100000000000000000015 /* ScoreVoice.swift in Sources */,
|
||||
A5D100000000000000000019 /* DemoProtocol.swift in Sources */,
|
||||
A5D10000000000000000001B /* ScoreDemo.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin XCBuildConfiguration section */
|
||||
A5D10000000000000000000C /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_ENTITLEMENTS = LyrebirdScoreDemo/LyrebirdScoreDemo.entitlements;
|
||||
CODE_SIGN_IDENTITY = "-";
|
||||
CODE_SIGN_STYLE = Manual;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
ENABLE_HARDENED_RUNTIME = YES;
|
||||
INFOPLIST_FILE = LyrebirdScoreDemo/Info.plist;
|
||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScoreDemo;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_VERSION = 6.0;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
A5D10000000000000000000D /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_ENTITLEMENTS = LyrebirdScoreDemo/LyrebirdScoreDemo.entitlements;
|
||||
CODE_SIGN_IDENTITY = "-";
|
||||
CODE_SIGN_STYLE = Manual;
|
||||
ENABLE_HARDENED_RUNTIME = YES;
|
||||
INFOPLIST_FILE = LyrebirdScoreDemo/Info.plist;
|
||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScoreDemo;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_VERSION = 6.0;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
A5D10000000000000000000F /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
CLANG_ANALYZER_NONNULL = YES;
|
||||
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
|
||||
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_ARC = YES;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
||||
CLANG_WARN_BOOL_CONVERSION = YES;
|
||||
CLANG_WARN_COMMA = YES;
|
||||
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
||||
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
|
||||
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
||||
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
|
||||
CLANG_WARN_EMPTY_BODY = YES;
|
||||
CLANG_WARN_ENUM_CONVERSION = YES;
|
||||
CLANG_WARN_INFINITE_RECURSION = YES;
|
||||
CLANG_WARN_INT_CONVERSION = YES;
|
||||
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
|
||||
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
||||
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
|
||||
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
||||
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
||||
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
||||
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
ENABLE_TESTABILITY = YES;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu17;
|
||||
GCC_DYNAMIC_NO_PIC = NO;
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
GCC_OPTIMIZATION_LEVEL = 0;
|
||||
GCC_PREPROCESSOR_DEFINITIONS = (
|
||||
"DEBUG=1",
|
||||
"$(inherited)",
|
||||
);
|
||||
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
|
||||
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
|
||||
GCC_WARN_UNDECLARED_SELECTOR = YES;
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
|
||||
MTL_FAST_MATH = YES;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SDKROOT = macosx;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
A5D100000000000000000010 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
CLANG_ANALYZER_NONNULL = YES;
|
||||
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
|
||||
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_ARC = YES;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
||||
CLANG_WARN_BOOL_CONVERSION = YES;
|
||||
CLANG_WARN_COMMA = YES;
|
||||
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
||||
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
|
||||
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
||||
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
|
||||
CLANG_WARN_EMPTY_BODY = YES;
|
||||
CLANG_WARN_ENUM_CONVERSION = YES;
|
||||
CLANG_WARN_INFINITE_RECURSION = YES;
|
||||
CLANG_WARN_INT_CONVERSION = YES;
|
||||
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
|
||||
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
||||
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
|
||||
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
||||
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
||||
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
||||
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
ENABLE_NS_ASSERTIONS = NO;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu17;
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
|
||||
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
|
||||
GCC_WARN_UNDECLARED_SELECTOR = YES;
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
MTL_ENABLE_DEBUG_INFO = NO;
|
||||
MTL_FAST_MATH = YES;
|
||||
SDKROOT = macosx;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
A5D10000000000000000000B /* Build configuration list for PBXNativeTarget "LyrebirdScoreDemo" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
A5D10000000000000000000C /* Debug */,
|
||||
A5D10000000000000000000D /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
A5D10000000000000000000E /* Build configuration list for PBXProject "LyrebirdScoreDemo" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
A5D10000000000000000000F /* Debug */,
|
||||
A5D100000000000000000010 /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
/* End XCConfigurationList section */
|
||||
|
||||
/* Begin XCLocalSwiftPackageReference section */
|
||||
A5D100000000000000000011 /* XCLocalSwiftPackageReference "../.." */ = {
|
||||
isa = XCLocalSwiftPackageReference;
|
||||
relativePath = ../..;
|
||||
};
|
||||
/* End XCLocalSwiftPackageReference section */
|
||||
|
||||
/* Begin XCSwiftPackageProductDependency section */
|
||||
A5D100000000000000000012 /* Lyrebird */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
package = A5D100000000000000000011 /* XCLocalSwiftPackageReference "../.." */;
|
||||
productName = Lyrebird;
|
||||
};
|
||||
/* End XCSwiftPackageProductDependency section */
|
||||
};
|
||||
rootObject = A5D100000000000000000001 /* Project object */;
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"originHash" : "2c98cd4172bcfb3eff9cb6e34a538f80f5e424aa73fbd5bea2b20cf0c8b539b7",
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "linenoise-swift",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/andybest/linenoise-swift",
|
||||
"state" : {
|
||||
"revision" : "afc897c02b030af7333105c4fedcd843a8339238",
|
||||
"version" : "0.0.3"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "nimble",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/Quick/Nimble.git",
|
||||
"state" : {
|
||||
"revision" : "e9d769113660769a4d9dd3afb855562c0b7ae7b0",
|
||||
"version" : "7.3.4"
|
||||
}
|
||||
}
|
||||
],
|
||||
"version" : 3
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "2620"
|
||||
version = "1.7">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES"
|
||||
buildArchitectures = "Automatic">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "A5D10000000000000000000A"
|
||||
BuildableName = "LyrebirdScoreDemo"
|
||||
BlueprintName = "LyrebirdScoreDemo"
|
||||
ReferencedContainer = "container:LyrebirdScoreDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
shouldAutocreateTestPlan = "YES">
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Release"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "A5D10000000000000000000A"
|
||||
BuildableName = "LyrebirdScoreDemo"
|
||||
BlueprintName = "LyrebirdScoreDemo"
|
||||
ReferencedContainer = "container:LyrebirdScoreDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "A5D10000000000000000000A"
|
||||
BuildableName = "LyrebirdScoreDemo"
|
||||
BlueprintName = "LyrebirdScoreDemo"
|
||||
ReferencedContainer = "container:LyrebirdScoreDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -0,0 +1,11 @@
|
||||
// DemoProtocol.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
|
||||
protocol DemoProtocol {
|
||||
func runDemo()
|
||||
}
|
||||
@@ -0,0 +1,693 @@
|
||||
// ScoreDemo.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Builds a multi-part Score using every DSL node type, exports MusicXML, round-trips
|
||||
/// the document, and reports render statistics.
|
||||
///
|
||||
/// Call ``buildAndReport()`` after construction to export MusicXML and print the
|
||||
/// round-trip summary. ``scheduleVoices(engine:)`` is marked ``@MainActor`` because
|
||||
/// ``ScoreVoice`` (a ``SynthesizerBase`` subclass) is ``@MainActor``-isolated; call it
|
||||
/// on the main thread before ``engine.start()``.
|
||||
final class ScoreDemo: DemoProtocol {
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Beats per minute for the demo score.
|
||||
static let bpm: Double = 108.0
|
||||
|
||||
/// Seconds per beat at the demo tempo.
|
||||
static let secondsPerBeat: Double = 60.0 / ScoreDemo.bpm
|
||||
|
||||
/// Extra render tail (seconds) to let the final release decay.
|
||||
static let tailSeconds: Double = 1.2
|
||||
|
||||
/// Pan position for lead-part voices (MIDI channel 0): slightly left.
|
||||
static let leadPan: Double = -0.4
|
||||
|
||||
/// Pan position for bass-part voices (other channels): slightly right.
|
||||
static let bassPan: Double = 0.5
|
||||
|
||||
/// Scale applied to a `ScoreEvent`'s normalized velocity to set voice amplitude.
|
||||
static let velocityToAmpScale: Double = 0.35
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
/// The score built at init time.
|
||||
let score: Score
|
||||
|
||||
/// Total render duration in seconds, including tail.
|
||||
let totalDuration: Double
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
init() {
|
||||
let builtScore: Score = ScoreDemo.makeScore()
|
||||
self.score = builtScore
|
||||
self.totalDuration = builtScore.totalBeats * ScoreDemo.secondsPerBeat
|
||||
+ ScoreDemo.tailSeconds
|
||||
}
|
||||
|
||||
// MARK: - DemoProtocol
|
||||
|
||||
/// Export MusicXML and print the round-trip event count. Does not interact with
|
||||
/// the engine or schedule any voices.
|
||||
func runDemo() {
|
||||
// Step 1 — write MusicXML to Desktop.
|
||||
let xmlURL: URL = FileManager.default.homeDirectoryForCurrentUser
|
||||
.appendingPathComponent("Desktop/LyrebirdScoreDemo.musicxml")
|
||||
let xmlString: String = score.toMusicXMLString()
|
||||
do {
|
||||
try xmlString.write(to: xmlURL, atomically: true, encoding: .utf8)
|
||||
print("MusicXML written → \(xmlURL.path)")
|
||||
} catch {
|
||||
fputs("Failed to write MusicXML: \(error)\n", stderr)
|
||||
}
|
||||
|
||||
// Step 2 — round-trip sanity check.
|
||||
let xmlData: Data = score.toMusicXMLData()
|
||||
do {
|
||||
let rt: Score = try Score.fromMusicXML(data: xmlData)
|
||||
let originalCount: Int = score.allEvents.count
|
||||
let roundTripCount: Int = rt.allEvents.count
|
||||
print("Round-trip events: \(originalCount) → \(roundTripCount)")
|
||||
// Verify notation-only elements do not affect event count. Grace
|
||||
// notes (lead), clef changes (bass), staff grouping + sustain-pedal
|
||||
// marks (piano) are all skipped by flatten(), so the score's event
|
||||
// count must equal the round-tripped count.
|
||||
let selfConsistent: String = (originalCount == roundTripCount) ? "self-consistent" : "MISMATCH"
|
||||
print("Notation-only event count: \(selfConsistent)")
|
||||
// Verify tempo changes round-trip.
|
||||
let originalChanges: Int = score.tempoChanges.count
|
||||
let rtChanges: Int = rt.tempoChanges.count
|
||||
print("Round-trip tempo changes: \(originalChanges) → \(rtChanges)")
|
||||
if originalChanges == rtChanges {
|
||||
for (orig, recovered): (TempoChange, TempoChange) in zip(score.tempoChanges, rt.tempoChanges) {
|
||||
let measMatch: String = orig.measure == recovered.measure ? "OK" : "MISMATCH"
|
||||
let bpmMatch: String = abs(orig.bpm - recovered.bpm) < 0.001 ? "OK" : "MISMATCH"
|
||||
print(" TempoChange measure=\(orig.measure) \(measMatch) bpm=\(orig.bpm) \(bpmMatch)")
|
||||
}
|
||||
}
|
||||
// Verify per-part key override + transpose round-trip on the clarinet part.
|
||||
// Part order: 0=lead, 1=bass, 2=clarinet, 3=piano, 4=texture,
|
||||
// 5=timeline, 6=autovoice, 7=polymeter — so the clarinet is index 2.
|
||||
if rt.parts.count > 2 {
|
||||
let clarinet: ScorePart = rt.parts[2]
|
||||
let keyOK: String = (clarinet.keySignature == .aMajor) ? "OK" : "MISMATCH(\(String(describing: clarinet.keySignature)))"
|
||||
let transposeOK: String = (clarinet.transpose == .bFlat) ? "OK" : "MISMATCH(\(String(describing: clarinet.transpose)))"
|
||||
print("Clarinet part key override: \(keyOK)")
|
||||
print("Clarinet part transpose (bFlat): \(transposeOK)")
|
||||
print("Score key (G major): \(rt.keySignature == .gMajor ? "OK" : "MISMATCH(\(rt.keySignature))")")
|
||||
}
|
||||
} catch {
|
||||
fputs("MusicXML round-trip failed: \(error)\n", stderr)
|
||||
}
|
||||
|
||||
// Step 2b — sectioned showcase: multiple Sections assembled into one
|
||||
// score (continuous measure numbers + per-section rehearsal marks),
|
||||
// glissandi, slurs/hairpins, per-note display overrides, tacet fill,
|
||||
// and a landscape page layout. Section labels export as standard
|
||||
// <rehearsal> marks — system objects placed once above the top staff (tied
|
||||
// to the section, not an instrument line, and collision-free). Some editors
|
||||
// (e.g. Dorico) auto-sequence imported rehearsal marks as A, B, C and hide
|
||||
// the authored text; that is an editor display setting. The
|
||||
// `rehearsalMarksAsStaffText: true` option emits boxed <words> staff text
|
||||
// instead, but that attaches to a staff and can collide with notation.
|
||||
let showcase: Score = ScoreDemo.makeSectionedShowcase()
|
||||
let showcaseURL: URL = FileManager.default.homeDirectoryForCurrentUser
|
||||
.appendingPathComponent("Desktop/LyrebirdScoreSections.musicxml")
|
||||
do {
|
||||
try showcase.toMusicXMLString().write(to: showcaseURL, atomically: true, encoding: .utf8)
|
||||
print("Sectioned showcase written → \(showcaseURL.path)")
|
||||
// Report the assembled measure span + rehearsal marks.
|
||||
let marks: [(measure: Int, label: String)] = showcase.rehearsalMarks
|
||||
.sorted { $0.key < $1.key }
|
||||
.map { (measure: $0.key, label: $0.value) }
|
||||
let markList: String = marks.map { "\($0.label)@m\($0.measure)" }.joined(separator: ", ")
|
||||
print("Sections → rehearsal marks: \(markList)")
|
||||
print("Sectioned showcase parts: \(showcase.parts.map { $0.name }.joined(separator: ", "))")
|
||||
} catch {
|
||||
fputs("Failed to write sectioned showcase: \(error)\n", stderr)
|
||||
}
|
||||
|
||||
// Step 3 — report render parameters.
|
||||
let displayBeats: Double = score.totalBeats
|
||||
let displayDur: Double = totalDuration
|
||||
print(
|
||||
String(
|
||||
format: "Score: %.1f beats at %.0f BPM → %.2f s render (+ %.2f s tail)",
|
||||
displayBeats,
|
||||
ScoreDemo.bpm,
|
||||
displayBeats * ScoreDemo.secondsPerBeat,
|
||||
ScoreDemo.tailSeconds
|
||||
)
|
||||
)
|
||||
print(String(format: "Total render: %.2f s", displayDur))
|
||||
}
|
||||
|
||||
// MARK: - Voice scheduling
|
||||
|
||||
/// Schedule one ``ScoreVoice`` per non-rest event against the engine.
|
||||
///
|
||||
/// Must be called on the main actor because ``ScoreVoice`` (a ``SynthesizerBase``
|
||||
/// subclass) is ``@MainActor``-isolated. Call this after constructing the engine
|
||||
/// but before ``engine.start()``.
|
||||
@MainActor
|
||||
func scheduleVoices(engine: SynthesisEngine) {
|
||||
let secondsPerBeat: Double = ScoreDemo.secondsPerBeat
|
||||
let allEvents: [ScoreEvent] = score.allEvents
|
||||
var scheduledCount: Int = 0
|
||||
var failedCount: Int = 0
|
||||
|
||||
for event: ScoreEvent in allEvents {
|
||||
guard !event.isRest else { continue }
|
||||
guard let freqHz: Double = event.pitch.frequency else { continue }
|
||||
|
||||
let startSeconds: Double = event.beat * secondsPerBeat
|
||||
let durSeconds: Double = event.performedDuration * secondsPerBeat
|
||||
|
||||
// Separate lead (slight left) from bass (slight right) by MIDI channel.
|
||||
let pan: Double = event.channel == 0 ? ScoreDemo.leadPan : ScoreDemo.bassPan
|
||||
|
||||
let voice: ScoreVoice = ScoreVoice(
|
||||
freqHz: freqHz,
|
||||
amp: event.velocity * ScoreDemo.velocityToAmpScale,
|
||||
durSeconds: durSeconds,
|
||||
pan: pan
|
||||
)
|
||||
|
||||
do {
|
||||
try engine.schedule(voice, after: startSeconds)
|
||||
scheduledCount += 1
|
||||
} catch {
|
||||
fputs("engine.schedule failed for beat \(event.beat): \(error)\n", stderr)
|
||||
failedCount += 1
|
||||
}
|
||||
}
|
||||
|
||||
print("Scheduled \(scheduledCount) voices\(failedCount > 0 ? ", \(failedCount) failed" : "").")
|
||||
}
|
||||
|
||||
// MARK: - Material-creation helpers
|
||||
//
|
||||
// Beyond hand-authoring notes, Lyrebird offers several ways to GENERATE score
|
||||
// material. These helpers feed the `timeline` and `autovoice` parts.
|
||||
// `ScoreTimeline` is throwing, so the `[ScoreElement]` is built here (outside
|
||||
// the non-throwing score result-builder) and dropped into a `Part { … }` body.
|
||||
|
||||
/// Place notes at explicit musical beats and let the timeline fill the rests.
|
||||
/// `BeatPosition.beat(_:)` is the felt-beat reading (4/4: beat 1 = downbeat,
|
||||
/// beat 5 = bar-2 downbeat). See ``ScoreTimeline`` / ``BeatPosition``.
|
||||
private static func makeTimelineMaterial() -> [ScoreElement] {
|
||||
do {
|
||||
return try ScoreTimeline.from(
|
||||
(.beat(1.0), Note(.named(.d, 5), dur: .quarter, dyn: .mp)),
|
||||
(.beat(5.0), Note(.named(.f, 5), dur: .quarter, dyn: .mp)),
|
||||
(.bar(2, beat: 3.0), Note(.named(.a, 5), dur: .half, dyn: .mf, art: .tenuto)),
|
||||
meter: MeterMap(.fourFour)
|
||||
)
|
||||
} catch {
|
||||
print("[ScoreDemo] timeline material failed: \(error)")
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/// Overlapping placements distributed across voices automatically — a held
|
||||
/// whole note under a moving line becomes two voices. See
|
||||
/// ``ScoreTimeline/fillAutoVoiced(_:)``.
|
||||
private static func makeAutoVoicedMaterial() -> [ScoreElement] {
|
||||
do {
|
||||
return try ScoreTimeline.fillAutoVoiced([
|
||||
(beat: 0.0, element: Note(.named(.c, 4), dur: .whole, dyn: .p)),
|
||||
(beat: 0.0, element: Note(.named(.e, 5), dur: .quarter, dyn: .mp)),
|
||||
(beat: 1.0, element: Note(.named(.f, 5), dur: .quarter, dyn: .mp)),
|
||||
(beat: 2.0, element: Note(.named(.g, 5), dur: .quarter, dyn: .mp)),
|
||||
(beat: 3.0, element: Note(.named(.e, 5), dur: .quarter, dyn: .mp)),
|
||||
])
|
||||
} catch {
|
||||
print("[ScoreDemo] auto-voiced material failed: \(error)")
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Score construction
|
||||
|
||||
/// Builds the demo score: eight parts, each chosen to exercise a different
|
||||
/// authoring path.
|
||||
///
|
||||
/// The hand-authored `lead` part is written **inline** below to show direct
|
||||
/// result-builder entry; every other part is built by its own `make…Part()`
|
||||
/// helper for clearer encapsulation. The parts, in document order:
|
||||
///
|
||||
/// - **`lead`** *(inline)* — 8-bar melody: crescendo/diminuendo hairpins, a
|
||||
/// triplet run, tied sixteenths, chords, a grace note (acciaccatura F♯5),
|
||||
/// and a nested 5:4 ⊃ 3:2 tuplet.
|
||||
/// - **`bass`** — sustained low line with double-stops, a mid-voice clef
|
||||
/// change (bass → tenor → bass), a walking eighth-note run, and a triplet
|
||||
/// fill. Hand-authored.
|
||||
/// - **`clarinet`** — transposing-instrument demo (B♭): per-part key
|
||||
/// override (A major) + `<transpose>`. Hand-authored.
|
||||
/// - **`piano`** — grand staff. Staff 1 (treble) carries two voices (an
|
||||
/// upper melody and a tied C-major triad); staff 2 (bass) carries a
|
||||
/// sustained whole-note C under a sustain-pedal marking.
|
||||
/// - **`texture`** — algorithmic generation via `Generate` (index-driven)
|
||||
/// and `PatternNotes` (a seeded Brownian MIDI walk).
|
||||
/// - **`timeline`** — notes placed at explicit `BeatPosition`s with rests
|
||||
/// auto-filled (`ScoreTimeline`).
|
||||
/// - **`autovoice`** — overlapping placements distributed across voices
|
||||
/// automatically (`ScoreTimeline.fillAutoVoiced`).
|
||||
/// - **`polymeter`** — runs in its OWN 3/4 meter while the score is 4/4
|
||||
/// (per-part `MeterMap`).
|
||||
///
|
||||
/// Score-level features layered over all parts: a forward/backward repeat
|
||||
/// with 1st/2nd endings (bars 1–4) and tempo changes at bar 3 (132 BPM) and
|
||||
/// bar 7 (80 BPM). Both are notation-only — playback uses the base tempo.
|
||||
private static func makeScore() -> Score {
|
||||
return Score(
|
||||
bpm: ScoreDemo.bpm,
|
||||
timeSignature: TimeSignature(4, 4),
|
||||
keySignature: .gMajor,
|
||||
// Repeat of bars 1–3 with first/second endings. The backward repeat
|
||||
// sits at the END of the first ending (bar 3) — the jump-back point.
|
||||
// On the repeat, the first ending (bar 3) is skipped and the second
|
||||
// ending (bar 4) plays straight through, so bar 4 has no repeat.
|
||||
repeats: RepeatStructure(
|
||||
forwardRepeatMeasures: [1],
|
||||
backwardRepeatMeasures: [3],
|
||||
endings: [
|
||||
Ending(number: 1, startMeasure: 3, stopMeasure: 3),
|
||||
Ending(number: 2, startMeasure: 4, stopMeasure: 4)
|
||||
]
|
||||
),
|
||||
// Tempo changes. Bar 3 accelerates to 132 BPM; bar 7 relaxes to 80
|
||||
// BPM. These are notation-only — playback still uses the base bpm
|
||||
// (108). A tempo change is emitted in every part that reaches that
|
||||
// measure: bar 3 exists in all parts (incl. the 4-bar piano), bar 7
|
||||
// only in the 8-bar lead/bass.
|
||||
tempoChanges: [
|
||||
TempoChange(measure: 3, bpm: 132.0),
|
||||
TempoChange(measure: 7, bpm: 80.0)
|
||||
],
|
||||
// Page layout — emitted as a MusicXML <defaults> block (US Letter,
|
||||
// portrait). Engravers honour the page size, orientation, margins,
|
||||
// and staff scaling on import.
|
||||
pageLayout: PageLayout(size: .letter, orientation: .portrait)
|
||||
) {
|
||||
// Lead melody — kept INLINE to demonstrate direct result-builder
|
||||
// entry. Every other part is built by a make…Part() helper below.
|
||||
// 8 bars covering dynamics, articulations, a grace note, and a
|
||||
// nested tuplet. Bars 1–2 include a Crescendo and Diminuendo hairpin.
|
||||
Part("lead") {
|
||||
// Bar 1 — arpeggiated C major with staccato, under a crescendo.
|
||||
// The high C6 also starts a slur that overlaps into bar 2 —
|
||||
// demonstrating a shared boundary where a slur-start and a
|
||||
// hairpin coexist on the same note via the spanners: parameter.
|
||||
Slur {
|
||||
Crescendo {
|
||||
Note(.named(.c, 5), dur: .quarter, dyn: .mf, art: .staccato)
|
||||
Note(.named(.e, 5), dur: .quarter, dyn: .mf, art: .staccato)
|
||||
Note(.named(.g, 5), dur: .quarter, dyn: .mf, art: .staccato)
|
||||
// spanners: [.beginSlur] opens a slur here while the Crescendo
|
||||
// block simultaneously marks this note with the wedge-start.
|
||||
// The two annotations are independent fields on the atom and
|
||||
// compose without conflict in MusicXML.
|
||||
Note(.named(.c, 6), dur: .quarter, dyn: .f, art: .accent)
|
||||
}
|
||||
}
|
||||
|
||||
// Bar 2 — triplet run followed by legato half note, under a diminuendo.
|
||||
// The slur started on the C6 above ends on the last triplet note (G5),
|
||||
// which lies inside the Diminuendo block — the slur overlaps the hairpin.
|
||||
Diminuendo {
|
||||
Tuplet(3, inTimeOf: 2) {
|
||||
Note(.named(.b, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.a, 5), dur: .quarter, dyn: .mp, spanners: [.beginSlur])
|
||||
// spanners: [.endSlur] closes the slur here. The Diminuendo
|
||||
// block's wedge-start is on the B5 triplet note; the slur-stop
|
||||
// lands on this G5 — overlapping spans, cleanly expressed.
|
||||
Note(.named(.g, 5), dur: .quarter, dyn: .mp,
|
||||
spanners: [.endSlur])
|
||||
}
|
||||
Note(.named(.f, 5), dur: .half, dyn: .p, art: .legato)
|
||||
}
|
||||
// Bar 3 — staccatissimo sixteenth notes, then tenuto half; the
|
||||
// first two sixteenths are tied (authored tie: sounds
|
||||
// as one eighth note but is notated as two tied sixteenths).
|
||||
Note(.named(.e, 5), dur: .sixteenth, dyn: .ff, art: .staccatissimo, tie: true)
|
||||
Note(.named(.e, 5), dur: .sixteenth, dyn: .ff)
|
||||
Note(.named(.g, 5), dur: .sixteenth, dyn: .ff, art: .staccatissimo)
|
||||
Note(.named(.a, 5), dur: .sixteenth, dyn: .ff, art: .staccatissimo)
|
||||
Note(.named(.b, 5), dur: .half, dyn: .f, art: .tenuto)
|
||||
Rest(dur: .quarter)
|
||||
|
||||
// Bar 4 — chord, rest, single note
|
||||
Chord([.named(.c, 5), .named(.e, 5), .named(.g, 5)], dur: .half, dyn: .f, art: .accent)
|
||||
Rest(dur: .quarter)
|
||||
// Note-display override: a diamond notehead (e.g. a harmonic).
|
||||
// Notation-only — the flattened event is unchanged.
|
||||
Note(.named(.d, 5), dur: .quarter, dyn: .mf,
|
||||
display: NoteDisplay(notehead: .diamond))
|
||||
// Bar 5 — grace note (acciaccatura F#5) before a nested tuplet.
|
||||
// Grace is notation-only; flatten() skips it and the
|
||||
// event count is identical to a score without the grace note.
|
||||
// The nested 5:4 ⊃ 3:2 tuplet demonstrates per-level
|
||||
// <tuplet-actual>/<tuplet-normal> bracket engraving.
|
||||
// Outer children: 3 quarters + inner(3 quarters × 2/3 = 2 quarter-slots)
|
||||
// = 5 quarter-slots × 4/5 outer scale = 4 beats. Fits the 4/4 bar.
|
||||
Grace(.named(.fSharp, 5))
|
||||
Tuplet(5, inTimeOf: 4) {
|
||||
Note(.named(.c, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.d, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.e, 5), dur: .quarter, dyn: .mp)
|
||||
Tuplet(3, inTimeOf: 2) {
|
||||
Note(.named(.f, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.g, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.gSharp, 5), dur: .quarter, dyn: .mp)
|
||||
}
|
||||
}
|
||||
|
||||
// Bar 6 — dotted quarter glissando down to the eighth, then a
|
||||
// legato half. The glissando is a two-note span authored via the
|
||||
// spanners: parameter (begin on A5, end on G5).
|
||||
Note(.named(.a, 5), dur: .quarter.dotted, dyn: .mf,
|
||||
spanners: [.beginGlissando(Glissando())])
|
||||
Note(.named(.g, 5), dur: .eighth, dyn: .mp, spanners: [.endGlissando])
|
||||
Note(.named(.fSharp, 5), dur: .half, dyn: .p, art: .legato)
|
||||
|
||||
// Bar 7 — marcato descent ppp
|
||||
Note(.named(.e, 5), dur: .quarter, dyn: .fff, art: .marcato)
|
||||
Note(.named(.d, 5), dur: .quarter, dyn: .ff)
|
||||
Note(.named(.c, 5), dur: .quarter, dyn: .f)
|
||||
Note(.named(.b, 4), dur: .quarter, dyn: .mf)
|
||||
|
||||
// Bar 8 — closing chord
|
||||
Chord([.named(.c, 5), .named(.e, 5), .named(.g, 5), .named(.c, 6)], dur: .whole, dyn: .pp, art: .tenuto)
|
||||
}
|
||||
|
||||
ScoreDemo.makeBassPart()
|
||||
ScoreDemo.makeClarinetPart()
|
||||
ScoreDemo.makePianoPart()
|
||||
ScoreDemo.makeTexturePart()
|
||||
ScoreDemo.makeTimelinePart()
|
||||
ScoreDemo.makeAutoVoicePart()
|
||||
ScoreDemo.makePolymeterPart()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Sectioned showcase
|
||||
|
||||
/// A second, self-contained score that demonstrates the section-based
|
||||
/// authoring stack: multiple ``ScoreSection`` blocks assembled into one
|
||||
/// score with continuous global measure numbers, per-section rehearsal
|
||||
/// marks, a tacet instrument auto-filled with rests, glissandi/slides,
|
||||
/// slurs and hairpins, an intra-note dynamic curve (messa di voce / niente
|
||||
/// swell), per-note display overrides, and a landscape page layout.
|
||||
///
|
||||
/// Two instruments — `flute` (id `fl`) and `cello` (id `vc`) — are matched
|
||||
/// across sections by `id`. Section labels are single letters (`A`, `B`, `C`):
|
||||
/// rehearsal marks are system objects that editors typically render as a
|
||||
/// sequence of letters, so single letters round-trip reliably while custom
|
||||
/// words may be re-sequenced or hidden. Three sections run sequentially:
|
||||
/// - **A** (4/4, 2 bars): flute states the theme under a slurred crescendo,
|
||||
/// then a niente messa-di-voce swell (`dynamicCurve`) over the bar-2 whole
|
||||
/// note; cello is TACET (auto-filled, stays bar-aligned).
|
||||
/// - **B** (3/4, 2 bars): flute plays a wavy glissando and an x-notehead /
|
||||
/// stemless note; cello enters with a straight `slide` glissando.
|
||||
/// - **C** (4/4, 2 bars): a diminuendo close, a large-notehead final note,
|
||||
/// sustained cello.
|
||||
private static func makeSectionedShowcase() -> Score {
|
||||
return Score(
|
||||
bpm: 96.0,
|
||||
keySignature: .cMajor,
|
||||
// Landscape A4 — emitted as a MusicXML <defaults> block.
|
||||
pageLayout: PageLayout(size: .a4, orientation: .landscape)
|
||||
) {
|
||||
Section("A") {
|
||||
Part("flute", clef: .treble, id: "fl") {
|
||||
Crescendo {
|
||||
Slur {
|
||||
Note(.named(.c, 5), dur: .quarter, dyn: .p)
|
||||
Note(.named(.d, 5), dur: .quarter)
|
||||
Note(.named(.e, 5), dur: .quarter)
|
||||
Note(.named(.g, 5), dur: .quarter, dyn: .mf)
|
||||
}
|
||||
}
|
||||
// Messa di voce on a single sustained note: a niente swell
|
||||
// ◦< f >◦ authored via `dynamicCurve`. The dynamics and the
|
||||
// crescendo/diminuendo hairpins (each closing on a niente
|
||||
// circle) ride inside this one whole note — no tied split. The
|
||||
// note's `dyn:` still drives playback velocity.
|
||||
Note(.named(.c, 5), dur: .whole, dyn: .mf,
|
||||
dynamicCurve: [(0.0, .niente), (0.5, .f), (1.0, .niente)])
|
||||
}
|
||||
// cello is tacet in section A — the lowering fills it with rests.
|
||||
}
|
||||
|
||||
Section("B", meterMap: MeterMap(.threeFour)) {
|
||||
Part("flute", clef: .treble, id: "fl") {
|
||||
// Wavy glissando E5 → B5 (two-note span via spanners:).
|
||||
Note(.named(.e, 5), dur: .quarter, dyn: .mf,
|
||||
spanners: [.beginGlissando(Glissando())])
|
||||
Note(.named(.b, 5), dur: .quarter, spanners: [.endGlissando])
|
||||
// x-notehead (ghost / percussive) — notation-only.
|
||||
Note(.named(.a, 5), dur: .quarter, display: NoteDisplay(notehead: .x))
|
||||
// Bar 2: legato half + a stemless note.
|
||||
Note(.named(.g, 5), dur: .half, dyn: .p, art: .legato)
|
||||
Note(.named(.fSharp, 5), dur: .quarter,
|
||||
display: NoteDisplay(hideStem: true))
|
||||
}
|
||||
Part("cello", clef: .bass, id: "vc") {
|
||||
// Straight slide glissando C3 → G3, dashed line.
|
||||
Note(.named(.c, 3), dur: .half.dotted, dyn: .mp,
|
||||
spanners: [.beginGlissando(Glissando(kind: .slide, lineType: .dashed))])
|
||||
Note(.named(.g, 3), dur: .half.dotted, spanners: [.endGlissando])
|
||||
}
|
||||
}
|
||||
|
||||
Section("C") {
|
||||
Part("flute", clef: .treble, id: "fl") {
|
||||
Diminuendo {
|
||||
Note(.named(.g, 5), dur: .quarter, dyn: .f)
|
||||
Note(.named(.e, 5), dur: .quarter)
|
||||
Note(.named(.c, 5), dur: .half, dyn: .pp, art: .legato)
|
||||
}
|
||||
// Final note with a large notehead (single pitch, not a chord).
|
||||
Note(.named(.c, 6), dur: .whole, dyn: .pp, art: .tenuto,
|
||||
display: NoteDisplay(size: .large))
|
||||
}
|
||||
Part("cello", clef: .bass, id: "vc") {
|
||||
Note(.named(.c, 3), dur: .whole, dyn: .mp)
|
||||
Note(.named(.c, 3), dur: .whole, dyn: .pp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Part-creation helpers
|
||||
|
||||
/// Bass line — sustained low harmonies with occasional double-stops, a
|
||||
/// mid-voice clef change (bass → tenor → bass), a walking eighth-note run,
|
||||
/// and a triplet fill. Single voice; carries Crescendo/Diminuendo-free
|
||||
/// material at the low end of the texture.
|
||||
private static func makeBassPart() -> ScorePart {
|
||||
Part("bass", channel: 1, clef: .bass) {
|
||||
// Bar 1 — low C whole note
|
||||
Note(.named(.c, 2), dur: .whole, dyn: .mp)
|
||||
|
||||
// Bar 2 — G pedal
|
||||
Note(.named(.g, 2), dur: .whole, dyn: .p)
|
||||
|
||||
// Bar 3 — half plus quarter, then quarter rest (sums to 4 beats)
|
||||
Note(.named(.a, 2), dur: .half, dyn: .mf)
|
||||
Note(.named(.e, 2), dur: .quarter, dyn: .p)
|
||||
Rest(dur: .quarter)
|
||||
|
||||
// Bar 4 — double-stop chords
|
||||
Chord([.named(.f, 2), .named(.c, 3)], dur: .half, dyn: .mp)
|
||||
Chord([.named(.d, 2), .named(.a, 2)], dur: .half, dyn: .mp)
|
||||
|
||||
// Mid-voice clef change: switch to tenor clef for the
|
||||
// walking line so it reads with fewer ledger lines, then switch
|
||||
// back to bass for the low pedal in bar 6. Display-only — sounding
|
||||
// pitches are unchanged.
|
||||
ClefChange(.tenor)
|
||||
// Bar 5 — walking eighth-note bass line
|
||||
Note(.named(.c, 3), dur: .eighth, dyn: .mf)
|
||||
Note(.named(.d, 3), dur: .eighth, dyn: .mp)
|
||||
Note(.named(.e, 3), dur: .eighth, dyn: .mp)
|
||||
Note(.named(.f, 3), dur: .eighth, dyn: .mp)
|
||||
Note(.named(.g, 3), dur: .eighth, dyn: .mf)
|
||||
Note(.named(.a, 3), dur: .eighth, dyn: .mp)
|
||||
Note(.named(.b, 3), dur: .eighth, dyn: .mp)
|
||||
Note(.named(.c, 4), dur: .eighth, dyn: .mf)
|
||||
|
||||
ClefChange(.bass)
|
||||
// Bar 6 — pedal half + triplet fill
|
||||
Note(.named(.g, 2), dur: .half, dyn: .mp, art: .tenuto)
|
||||
Tuplet(3, inTimeOf: 2) {
|
||||
Note(.named(.f, 2), dur: .quarter, dyn: .p)
|
||||
Note(.named(.e, 2), dur: .quarter, dyn: .p)
|
||||
Note(.named(.d, 2), dur: .quarter, dyn: .p)
|
||||
}
|
||||
|
||||
// Bar 7 — marcato accent descent
|
||||
Note(.named(.e, 2), dur: .quarter, dyn: .ff, art: .marcato)
|
||||
Note(.named(.d, 2), dur: .quarter, dyn: .f, art: .staccato)
|
||||
Note(.named(.c, 2), dur: .half, dyn: .mf)
|
||||
|
||||
// Bar 8 — final bass chord (ppp close)
|
||||
Chord([.named(.c, 2), .named(.g, 2), .named(.c, 3)], dur: .whole, dyn: .ppp)
|
||||
}
|
||||
}
|
||||
|
||||
/// B♭ clarinet — transposing-instrument demonstration.
|
||||
/// Score key: G major. Clarinet written key: A major (a major 2nd up,
|
||||
/// because a B♭ instrument reads a major 2nd higher than concert pitch).
|
||||
/// transpose: .bFlat → <transpose><diatonic>-1</diatonic><chromatic>-2</chromatic></transpose>.
|
||||
/// Flatten returns these AS WRITTEN pitches; concert-pitch playback is future work.
|
||||
/// Single voice.
|
||||
private static func makeClarinetPart() -> ScorePart {
|
||||
Part("clarinet", channel: 3, clef: .treble, keySignature: .aMajor, transpose: .bFlat) {
|
||||
// Bar 1 — ascending A major scale fragment (written; sounds G major)
|
||||
Note(.named(.a, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.b, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.cSharp, 6), dur: .quarter, dyn: .mf)
|
||||
Note(.named(.d, 6), dur: .quarter, dyn: .mf)
|
||||
|
||||
// Bar 2 — descending to tonic (written A5, sounds G5)
|
||||
Note(.named(.e, 6), dur: .quarter, dyn: .mf)
|
||||
Note(.named(.d, 6), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.cSharp, 6), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.a, 5), dur: .quarter, dyn: .p)
|
||||
}
|
||||
}
|
||||
|
||||
/// Piano — a grand staff demonstrating multi-staff notation.
|
||||
///
|
||||
/// Staff 1 (treble) holds two independent voices:
|
||||
/// - **Voice 1** — a 4-bar melodic fragment.
|
||||
/// - **Voice 2** — sustained chord tones that overlay from beat 0; bars 1–2
|
||||
/// tie a C-major triad (C4–E4–G4) across the barline so all three pitches
|
||||
/// sustain.
|
||||
/// Staff 2 (bass) holds **Voice 3** — a sustained whole-note C under a
|
||||
/// sustain-pedal marking (pedal down before the note, released after it).
|
||||
///
|
||||
/// In MusicXML this encodes as one part with `<staves>2</staves>`, a
|
||||
/// `<clef number="1">` (treble) / `<clef number="2">` (bass) pair, a
|
||||
/// `<staff>` element on every note, `<backup>` between the three voices,
|
||||
/// and `<pedal>` start/stop directions attached to staff 2.
|
||||
private static func makePianoPart() -> ScorePart {
|
||||
Part("piano", channel: 2, clef: .treble) {
|
||||
Staff(1) {
|
||||
Voice(1) {
|
||||
// Bar 1 — stepwise ascent
|
||||
Note(.named(.c, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.d, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.e, 5), dur: .quarter, dyn: .mf)
|
||||
Note(.named(.f, 5), dur: .quarter, dyn: .mf)
|
||||
|
||||
// Bar 2 — triplet decoration with a half note landing
|
||||
Tuplet(3, inTimeOf: 2) {
|
||||
Note(.named(.g, 5), dur: .quarter, dyn: .mf)
|
||||
Note(.named(.a, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.g, 5), dur: .quarter, dyn: .mp)
|
||||
}
|
||||
Note(.named(.f, 5), dur: .half, dyn: .p, art: .legato)
|
||||
|
||||
// Bar 3 — eighth-note run with staccato
|
||||
Note(.named(.e, 5), dur: .eighth, dyn: .f, art: .staccato)
|
||||
Note(.named(.d, 5), dur: .eighth, dyn: .f, art: .staccato)
|
||||
Note(.named(.c, 5), dur: .eighth, dyn: .mf, art: .staccato)
|
||||
Note(.named(.d, 5), dur: .eighth, dyn: .mf, art: .staccato)
|
||||
Note(.named(.e, 5), dur: .half, dyn: .p, art: .tenuto)
|
||||
|
||||
// Bar 4 — closing whole note
|
||||
Note(.named(.c, 5), dur: .whole, dyn: .pp)
|
||||
}
|
||||
Voice(2) {
|
||||
// Bar 1 — sustained C major triad tied to bar 2 (chord tie).
|
||||
// The two identical chords sustain as one across the barline.
|
||||
Chord([.named(.c, 4), .named(.e, 4), .named(.g, 4)], dur: .whole, dyn: .mp, tie: true)
|
||||
|
||||
// Bar 2 — same C major triad (tie target: merges with bar 1 above)
|
||||
Chord([.named(.c, 4), .named(.e, 4), .named(.g, 4)], dur: .whole, dyn: .mp)
|
||||
|
||||
// Bar 3 — A minor
|
||||
Chord([.named(.a, 3), .named(.c, 4), .named(.e, 4)], dur: .whole, dyn: .mp)
|
||||
|
||||
// Bar 4 — close on C major
|
||||
Chord([.named(.c, 4), .named(.e, 4), .named(.g, 4)], dur: .whole, dyn: .pp)
|
||||
}
|
||||
}
|
||||
Staff(2, clef: .bass) {
|
||||
Voice(3) {
|
||||
// Bar 1 — sustained bass C under the sustain pedal. Pedal
|
||||
// down before the note, released after; both pedal marks are
|
||||
// notation-only (skipped by flatten(), no ScoreEvent).
|
||||
Pedal(.start)
|
||||
Note(.named(.c, 3), dur: .whole, dyn: .mp)
|
||||
Pedal(.stop)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Texture — algorithmic note generation. Demonstrates the two generative
|
||||
/// helpers, both returning `[ScoreElement]` that drops straight into the Part
|
||||
/// body via the result builder.
|
||||
private static func makeTexturePart() -> ScorePart {
|
||||
Part("texture", channel: 4, clef: .treble) {
|
||||
// `Generate` maps each index 0..<8 through the builder closure —
|
||||
// here a sixteenth-note whole-tone fragment driven by the index.
|
||||
Generate(8) { i in
|
||||
Note(midi: 72 + (i % 6) * 2, dur: .sixteenth, dyn: .pp, art: .staccato)
|
||||
}
|
||||
// `PatternNotes` pulls pitches and rhythms from `Pattern` value
|
||||
// sources: a seeded Brownian MIDI walk for pitch, a repeating
|
||||
// eighth/eighth/quarter cell for rhythm. Stops early if the pitch
|
||||
// pattern exhausts before `count`.
|
||||
PatternNotes(
|
||||
count: 12,
|
||||
midi: Pattern.brownian(low: 60.0, high: 84.0, step: 4.0, length: 12, seed: 42),
|
||||
durations: Pattern.sequence([.eighth, .eighth, .quarter]),
|
||||
dyn: .p
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Timeline — notes placed at explicit musical beats (`BeatPosition`), with
|
||||
/// rests auto-filled by `ScoreTimeline`. Material built in
|
||||
/// ``makeTimelineMaterial()`` (`ScoreTimeline` is throwing). Single voice.
|
||||
private static func makeTimelinePart() -> ScorePart {
|
||||
let material: [ScoreElement] = ScoreDemo.makeTimelineMaterial()
|
||||
return Part("timeline", channel: 5, clef: .treble) {
|
||||
material
|
||||
}
|
||||
}
|
||||
|
||||
/// Auto-voiced — overlapping placements distributed across voices
|
||||
/// automatically (a held whole note + a moving line → two voices). Material
|
||||
/// built in ``makeAutoVoicedMaterial()``.
|
||||
private static func makeAutoVoicePart() -> ScorePart {
|
||||
let material: [ScoreElement] = ScoreDemo.makeAutoVoicedMaterial()
|
||||
return Part("autovoice", channel: 6, clef: .treble) {
|
||||
material
|
||||
}
|
||||
}
|
||||
|
||||
/// Polymeter — this part runs in its OWN 3/4 meter while the rest of the
|
||||
/// score is 4/4. Per-part `meterMap` → independent barlines; the encoder
|
||||
/// renders each part against its own meter. Single voice.
|
||||
private static func makePolymeterPart() -> ScorePart {
|
||||
Part("polymeter", channel: 7, clef: .bass, meterMap: MeterMap(.threeFour)) {
|
||||
for _: Int in 0..<6 {
|
||||
Note(.named(.g, 2), dur: .quarter, dyn: .mp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<key>NSDesktopFolderUsageDescription</key>
|
||||
<string>LyrebirdScoreDemo writes rendered audio and MusicXML files to the Desktop.</string>
|
||||
<key>NSDocumentsFolderUsageDescription</key>
|
||||
<string>LyrebirdScoreDemo writes rendered audio files to Documents.</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.security.app-sandbox</key>
|
||||
<false/>
|
||||
<key>com.apple.security.cs.disable-library-validation</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,76 @@
|
||||
// ScoreVoice.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
|
||||
/// A self-terminating NRT voice driven by a ``ScoreEvent``.
|
||||
///
|
||||
/// Plays a sawtooth oscillator through a percussive amplitude envelope. The
|
||||
/// envelope runs to completion and frees the synthesizer node automatically
|
||||
/// via ``DoneAction/freeNode``, so voices do not pile up during NRT render.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - freqHz: Fundamental frequency in Hz. Stays within audible range; no internal clamping.
|
||||
/// - amp: Linear amplitude in `[0, 1]` — maps directly from ``ScoreEvent/velocity``.
|
||||
/// - durSeconds: Played duration in seconds. The sustain stage occupies the bulk of this
|
||||
/// duration; a fixed 10 ms attack and 60 ms release are subtracted first. If
|
||||
/// `durSeconds` is very short (< 70 ms), the sustain collapses to zero and the voice
|
||||
/// becomes purely percussive.
|
||||
/// - pan: Stereo position in `[-1, 1]`. Default `0.0` (centre).
|
||||
final class ScoreVoice: SynthesizerBase {
|
||||
|
||||
/// Fundamental frequency in Hz. No internal clamping; stay within audible range.
|
||||
let freqHz: Double
|
||||
|
||||
/// Linear amplitude in `[0, 1]`, from the score event's normalized velocity.
|
||||
let amp: Double
|
||||
|
||||
/// Played duration in seconds — determines sustain stage length.
|
||||
let durSeconds: Double
|
||||
|
||||
/// Stereo pan position in `[-1, 1]`.
|
||||
let pan: Double
|
||||
|
||||
/// Fixed attack duration in seconds.
|
||||
private static let attackSeconds: Double = 0.01
|
||||
|
||||
/// Fixed release duration in seconds.
|
||||
private static let releaseSeconds: Double = 0.06
|
||||
|
||||
init(
|
||||
freqHz: Double,
|
||||
amp: Double,
|
||||
durSeconds: Double,
|
||||
pan: Double = 0.0
|
||||
) {
|
||||
self.freqHz = freqHz
|
||||
self.amp = amp
|
||||
self.durSeconds = durSeconds
|
||||
self.pan = pan
|
||||
super.init()
|
||||
}
|
||||
|
||||
override func build() {
|
||||
let attack: Double = ScoreVoice.attackSeconds
|
||||
let release: Double = ScoreVoice.releaseSeconds
|
||||
let sustainSeconds: Double = max(0.0, durSeconds - attack - release)
|
||||
|
||||
let envelope: Envelope = Envelope(
|
||||
levels: [0.0, 1.0, 0.8, 0.0],
|
||||
durations: [attack, sustainSeconds, release],
|
||||
curves: [-4.0, 0.0, -6.0]
|
||||
)
|
||||
|
||||
// Sawtooth oscillator scaled by envelope and amplitude.
|
||||
let osc: OscSawtooth.Audio = OscSawtooth.Audio(freq: freqHz)
|
||||
let env: EnvelopeGen.Control = EnvelopeGen.Control(
|
||||
envelope: envelope,
|
||||
doneAction: .freeNode
|
||||
)
|
||||
let sig: any ValidGeneratorInput = osc * env * amp
|
||||
output(bus: 0, source: Pan2(input: sig, pan: pan))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// main.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
// Output paths — both land on the Desktop.
|
||||
let cafURL: URL = FileManager.default.homeDirectoryForCurrentUser
|
||||
.appendingPathComponent("Desktop/LyrebirdScoreDemo.caf")
|
||||
|
||||
// Render parameters.
|
||||
let sampleRate: Double = 48000
|
||||
let blockSize: Int = 512
|
||||
|
||||
// Build the score first — totalDuration must be known before NRTDriver is created.
|
||||
let demo: ScoreDemo = ScoreDemo()
|
||||
let totalDuration: Double = demo.totalDuration
|
||||
|
||||
// MusicXML export and round-trip before audio engine creation.
|
||||
demo.runDemo()
|
||||
|
||||
// Create NRTDriver and engine.
|
||||
let driver: NRTDriver = NRTDriver(outputURL: cafURL, duration: totalDuration)
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: blockSize,
|
||||
sampleRate: sampleRate,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
driver: driver
|
||||
)
|
||||
|
||||
// Schedule all score voices. SynthesizerBase (and thus scheduleVoices) is
|
||||
// @MainActor-isolated; SwiftPM's top-level entry point is itself main-actor
|
||||
// isolated, so this is a plain direct call — no MainActor hop needed.
|
||||
demo.scheduleVoices(engine: engine)
|
||||
|
||||
print(String(format: "Rendering %.2f s → %@", totalDuration, cafURL.path))
|
||||
|
||||
do {
|
||||
try engine.start()
|
||||
print("Done.")
|
||||
} catch {
|
||||
fputs("Render failed: \(error)\n", stderr)
|
||||
exit(1)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"originHash" : "4acd68de25440f1fcc60a86a69d66a0516f6e9d4f2d769aaab597e24b64fd245",
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "linenoise-swift",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/andybest/linenoise-swift",
|
||||
"state" : {
|
||||
"revision" : "afc897c02b030af7333105c4fedcd843a8339238",
|
||||
"version" : "0.0.3"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "nimble",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/Quick/Nimble.git",
|
||||
"state" : {
|
||||
"revision" : "e9d769113660769a4d9dd3afb855562c0b7ae7b0",
|
||||
"version" : "7.3.4"
|
||||
}
|
||||
}
|
||||
],
|
||||
"version" : 3
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// Package.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// swift-tools-version: 6.0
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "LyrebirdScoreDemo",
|
||||
platforms: [.macOS(.v15)],
|
||||
dependencies: [
|
||||
.package(path: "../.."),
|
||||
],
|
||||
targets: [
|
||||
.executableTarget(
|
||||
name: "LyrebirdScoreDemo",
|
||||
dependencies: [
|
||||
.product(name: "Lyrebird", package: "LyrebirdII"),
|
||||
],
|
||||
path: "LyrebirdScoreDemo"
|
||||
),
|
||||
]
|
||||
)
|
||||
@@ -9,9 +9,10 @@
|
||||
/* Begin PBXBuildFile section */
|
||||
C8D0000000000000000000C /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8D00000000000000000007 /* main.swift */; };
|
||||
C8D0000000000000000000D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8D00000000000000000008 /* AppDelegate.swift */; };
|
||||
C8D0000000000000000000F /* LyrebirdUI in Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdUI */; };
|
||||
C8D00000000000000000021 /* LyrebirdLiveCompile in Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001F /* LyrebirdLiveCompile */; };
|
||||
C8D00000000000000000022 /* LyrebirdLiveCompileUI in Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUI */; };
|
||||
C8D0000000000000000000F /* LyrebirdDynamic in Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdDynamic */; };
|
||||
C8D00000000000000000022 /* LyrebirdLiveCompileUIDynamic in Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */; };
|
||||
C8D00000000000000000036 /* LyrebirdDynamic in Embed Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdDynamic */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
|
||||
C8D00000000000000000034 /* LyrebirdLiveCompileUIDynamic in Embed Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
@@ -27,14 +28,28 @@
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
C8D0000000000000000000F /* LyrebirdUI in Frameworks */,
|
||||
C8D00000000000000000021 /* LyrebirdLiveCompile in Frameworks */,
|
||||
C8D00000000000000000022 /* LyrebirdLiveCompileUI in Frameworks */,
|
||||
C8D0000000000000000000F /* LyrebirdDynamic in Frameworks */,
|
||||
C8D00000000000000000022 /* LyrebirdLiveCompileUIDynamic in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXCopyFilesBuildPhase section */
|
||||
C8D00000000000000000035 /* Embed Frameworks */ = {
|
||||
isa = PBXCopyFilesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
dstPath = "";
|
||||
dstSubfolderSpec = 10;
|
||||
files = (
|
||||
C8D00000000000000000036 /* LyrebirdDynamic in Embed Frameworks */,
|
||||
C8D00000000000000000034 /* LyrebirdLiveCompileUIDynamic in Embed Frameworks */,
|
||||
);
|
||||
name = "Embed Frameworks";
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXCopyFilesBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
C8D00000000000000000002 = {
|
||||
isa = PBXGroup;
|
||||
@@ -73,6 +88,7 @@
|
||||
C8D00000000000000000011 /* Sources */,
|
||||
C8D00000000000000000012 /* Frameworks */,
|
||||
C8D00000000000000000013 /* Resources */,
|
||||
C8D00000000000000000035 /* Embed Frameworks */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
@@ -80,9 +96,8 @@
|
||||
);
|
||||
name = LyrebirdScratchDemo;
|
||||
packageProductDependencies = (
|
||||
C8D0000000000000000001D /* LyrebirdUI */,
|
||||
C8D0000000000000000001F /* LyrebirdLiveCompile */,
|
||||
C8D00000000000000000020 /* LyrebirdLiveCompileUI */,
|
||||
C8D0000000000000000001D /* LyrebirdDynamic */,
|
||||
C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */,
|
||||
);
|
||||
productName = LyrebirdScratchDemo;
|
||||
productReference = C8D00000000000000000004 /* LyrebirdScratchDemo.app */;
|
||||
@@ -248,6 +263,10 @@
|
||||
STRING_CATALOG_GENERATE_SYMBOLS = YES;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
// Xcode 26 explicit-module-build regression: SPM dynamic-library
|
||||
// framework binaries (LyrebirdDynamic / LyrebirdLiveCompileUIDynamic)
|
||||
// are not emitted under the integrated driver. Classic driver fixes it.
|
||||
SWIFT_USE_INTEGRATED_DRIVER = NO;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
@@ -303,6 +322,8 @@
|
||||
STRING_CATALOG_GENERATE_SYMBOLS = YES;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
// Xcode 26 explicit-module-build regression — see Debug config.
|
||||
SWIFT_USE_INTEGRATED_DRIVER = NO;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
@@ -341,20 +362,15 @@
|
||||
/* End XCLocalSwiftPackageReference section */
|
||||
|
||||
/* Begin XCSwiftPackageProductDependency section */
|
||||
C8D0000000000000000001D /* LyrebirdUI */ = {
|
||||
C8D0000000000000000001D /* LyrebirdDynamic */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
package = C8D0000000000000000001B /* XCLocalSwiftPackageReference "../.." */;
|
||||
productName = LyrebirdUI;
|
||||
productName = LyrebirdDynamic;
|
||||
};
|
||||
C8D0000000000000000001F /* LyrebirdLiveCompile */ = {
|
||||
C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
package = C8D0000000000000000001E /* XCLocalSwiftPackageReference "../../LiveCompile" */;
|
||||
productName = LyrebirdLiveCompile;
|
||||
};
|
||||
C8D00000000000000000020 /* LyrebirdLiveCompileUI */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
package = C8D0000000000000000001E /* XCLocalSwiftPackageReference "../../LiveCompile" */;
|
||||
productName = LyrebirdLiveCompileUI;
|
||||
productName = LyrebirdLiveCompileUIDynamic;
|
||||
};
|
||||
/* End XCSwiftPackageProductDependency section */
|
||||
};
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"originHash" : "52fa7c84ca46dcb1ce0f4374a4fb0a5d2c97be57f306d91b8e9efb54af7c3c9e",
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "linenoise-swift",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/andybest/linenoise-swift",
|
||||
"state" : {
|
||||
"revision" : "afc897c02b030af7333105c4fedcd843a8339238",
|
||||
"version" : "0.0.3"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "nimble",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/Quick/Nimble.git",
|
||||
"state" : {
|
||||
"revision" : "e9d769113660769a4d9dd3afb855562c0b7ae7b0",
|
||||
"version" : "7.3.4"
|
||||
}
|
||||
}
|
||||
],
|
||||
"version" : 3
|
||||
}
|
||||
@@ -7,18 +7,28 @@
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
import LyrebirdLiveCompile
|
||||
// LyrebirdLiveCompile (LiveSession, …) is re-exported by LyrebirdLiveCompileUI.
|
||||
import LyrebirdLiveCompileUI
|
||||
|
||||
// This demo deliberately does NOT link `LyrebirdUI`. The live-compile stack
|
||||
// (`LyrebirdLiveCompileUIDynamic`) dynamic-links the single shared
|
||||
// `LyrebirdDynamic.framework` copy of `LyrebirdSynth`; linking the static
|
||||
// `LyrebirdUI` product would static-fold a SECOND copy of every `LyrebirdSynth`
|
||||
// ObjC class into the app binary (intra-package `LyrebirdUI → LyrebirdSynth` is
|
||||
// always a static edge), producing duplicate-class registration and the
|
||||
// "mysterious crashes" the runtime warns about. The only `LyrebirdUI` symbol
|
||||
// this demo used was `LyrebirdWindow`, an `NSWindow`/`NSHostingController`
|
||||
// wrapper with no `LyrebirdSynth` dependency — inlined below instead.
|
||||
|
||||
final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
|
||||
let engine: SynthesisEngine
|
||||
let session: LiveSession
|
||||
var model: LyrebirdScratchModel?
|
||||
var menuController: LyrebirdScratchMenuController?
|
||||
var window: LyrebirdWindow?
|
||||
var window: NSWindow?
|
||||
|
||||
@MainActor
|
||||
init(engine: SynthesisEngine) {
|
||||
self.engine = engine
|
||||
self.session = LiveSession(engine: engine)
|
||||
@@ -32,20 +42,30 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
print("[LyrebirdScratchDemo] Engine failed to start: \(error)")
|
||||
}
|
||||
|
||||
let model = LyrebirdScratchModel(session: session)
|
||||
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session)
|
||||
self.model = model
|
||||
let menuController = LyrebirdScratchMenuController(model: model)
|
||||
let menuController: LyrebirdScratchMenuController = LyrebirdScratchMenuController(model: model)
|
||||
menuController.installMainMenu()
|
||||
self.menuController = menuController
|
||||
|
||||
window = LyrebirdWindow(
|
||||
title: "Lyrebird — Live Scratch",
|
||||
width: 720,
|
||||
height: 560
|
||||
let windowWidth: CGFloat = 720
|
||||
let windowHeight: CGFloat = 560
|
||||
let hosting: NSHostingController<LyrebirdScratchView> =
|
||||
NSHostingController(rootView: LyrebirdScratchView(model: model))
|
||||
let initialSize: CGSize = CGSize(width: windowWidth, height: windowHeight)
|
||||
let win: NSWindow = NSWindow(
|
||||
contentRect: NSRect(origin: .zero, size: initialSize),
|
||||
styleMask: [.titled, .closable, .resizable, .miniaturizable],
|
||||
backing: .buffered,
|
||||
defer: false
|
||||
)
|
||||
window?.open {
|
||||
LyrebirdScratchView(model: model)
|
||||
}
|
||||
// Keep ownership in Swift — NSWindow defaults to releasing on close.
|
||||
win.isReleasedWhenClosed = false
|
||||
win.title = "Lyrebird — Live Scratch"
|
||||
win.contentViewController = hosting
|
||||
win.center()
|
||||
win.makeKeyAndOrderFront(nil)
|
||||
self.window = win
|
||||
}
|
||||
|
||||
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
|
||||
This app is a direct-distribution developer tool, not a Mac App Store
|
||||
submission. Sandbox OFF is the only viable configuration for v1.
|
||||
Phase 147 polish can revisit if an XPC-worker approach is adopted.
|
||||
This could be revisited if an XPC-worker approach is adopted.
|
||||
|
||||
com.apple.security.app-sandbox key is absent (defaults false).
|
||||
-->
|
||||
|
||||
@@ -6,9 +6,8 @@
|
||||
|
||||
import AppKit
|
||||
import LyrebirdSynth
|
||||
import LyrebirdLiveCompile
|
||||
|
||||
let engine = SynthesisEngine(
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 512,
|
||||
sampleRate: 48000,
|
||||
numOutputChannels: 2,
|
||||
@@ -16,8 +15,14 @@ let engine = SynthesisEngine(
|
||||
driver: CoreAudioDriver()
|
||||
)
|
||||
|
||||
let delegate = AppDelegate(engine: engine)
|
||||
let app = NSApplication.shared
|
||||
app.setActivationPolicy(.regular)
|
||||
app.delegate = delegate
|
||||
app.run()
|
||||
// AppDelegate.init is `@MainActor` (mirrors the other demos' bootstrap — since
|
||||
// `SynthesizerBase` is `@MainActor`, AppKit-side construction is main-actor
|
||||
// isolated). Program entry runs on the main thread, so assert main-actor
|
||||
// isolation for the AppKit bootstrap rather than hopping asynchronously.
|
||||
MainActor.assumeIsolated {
|
||||
let delegate: AppDelegate = AppDelegate(engine: engine)
|
||||
let app: NSApplication = NSApplication.shared
|
||||
app.setActivationPolicy(.regular)
|
||||
app.delegate = delegate
|
||||
app.run()
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ private let demo: Demo = .vector
|
||||
// ──────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
@main
|
||||
@MainActor
|
||||
struct LyrebirdiOSDemoApp: App {
|
||||
|
||||
let engine: SynthesisEngine
|
||||
|
||||
@@ -13,6 +13,7 @@ import LyrebirdSynth
|
||||
/// first taps "Start Synthesizer" — this is necessary because
|
||||
/// `SpectralBinDelayUI.init(sampleRate:)` requires the engine's committed
|
||||
/// sample rate, which is only valid after `engine.start()` returns.
|
||||
@MainActor
|
||||
@Observable
|
||||
final class BinDelayController {
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
import Observation
|
||||
import LyrebirdSynth
|
||||
|
||||
@MainActor
|
||||
@Observable
|
||||
final class NoteController {
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
import Observation
|
||||
import LyrebirdSynth
|
||||
|
||||
@MainActor
|
||||
@Observable
|
||||
final class VectorOscillatorController {
|
||||
|
||||
|
||||
@@ -108,6 +108,7 @@ Full reference: [`docs/tooling/cli-guide.md`](docs/tooling/cli-guide.md).
|
||||
| `demo` | SPM-only | A `SineTone` synth with `@LiveParam` frequency/amplitude. | `CoreAudioDriver` |
|
||||
| `ui-demo` | SPM-only | AppKit window with `@UIParam` knobs + `LyrebirdWindow`. | `CoreAudioDriver` |
|
||||
| `nrt` | SPM-only | Renders to `output.caf`, no hardware needed. | `NRTDriver` |
|
||||
| `score` | SPM-only | Authors a `Score` with the notation DSL, exports `score.musicxml` (round-trips it), then renders the events offline to `.caf`. | `NRTDriver` |
|
||||
| `macos-ui-xcode` | Xcode-project | macOS `.app` bundle (AppKit + SwiftUI), hardened runtime. | `CoreAudioDriver` |
|
||||
| `ios-ui` | Xcode-project | iOS `.app` (SwiftUI), with `AVAudioSession` activation. | `iOSAudioDriver` (RemoteIO) |
|
||||
| `auv3` | Xcode-project | AUv3 host `.app` + `aumu` `.appex` subclassing `LyrebirdAudioUnit`. | `AUv3Driver` |
|
||||
@@ -120,7 +121,9 @@ open <name>/<name>.xcworkspace # SPM-only & Xcode-project templates both shi
|
||||
cd <name> && lyrebird run
|
||||
```
|
||||
|
||||
To develop against a local Lyrebird checkout instead of the remote URL (path dependency + an `XCLocalSwiftPackageReference` in the generated project):
|
||||
**Lyrebird dependency, default behaviour.** When run from a Lyrebird source checkout (e.g. `swift run LyrebirdCLI new …`), the scaffolder pins the generated project to *that same checkout* as a `path:` dependency (and an `XCLocalSwiftPackageReference` in Xcode-bearing templates). This keeps the emitted template source and the Lyrebird it builds against in lockstep — pre-1.0-stable, the published tag lags unreleased Score/Generator API. The CLI prints the chosen dependency, e.g. `Lyrebird dependency: local checkout at /Users/me/Documents/LyrebirdII`. If no local checkout is derivable (an installed binary with no source tree), it falls back to the published remote package and warns.
|
||||
|
||||
Override the checkout explicitly with `--lyrebird-path`:
|
||||
|
||||
```bash
|
||||
lyrebird new <name> --template <t> --lyrebird-path /Users/me/Documents/LyrebirdII
|
||||
@@ -246,11 +249,92 @@ open MyApp/MyApp.xcworkspace # set your signing team, then run on device/si
|
||||
|
||||
The iOS template uses `iOSAudioDriver` (RemoteIO) and activates an `AVAudioSession` at launch; the synth/UI code is otherwise identical to the macOS UI template. The reference app is [`Demos/LyrebirdiOSDemo`](Demos/LyrebirdiOSDemo/).
|
||||
|
||||
### 6. Score / notation (MusicXML + offline render)
|
||||
|
||||
```bash
|
||||
lyrebird new MyScore --template score # aliases: score-musicxml, musicxml
|
||||
cd MyScore && lyrebird run # writes score.musicxml, round-trips it, renders .caf
|
||||
```
|
||||
|
||||
The `score` template authors music in the language-side **Score DSL** — a result-builder of `Note` / `Rest` / `Chord` / `Tuplet` with exact rational tuplet math (no float drift across nested ratios), spelling-aware pitches (`Note(.named(.c, 5))`), dynamics, and articulations. It exports MusicXML, parses it back for a round-trip sanity check, then schedules one self-freeing voice per `ScoreEvent` against an `NRTDriver`:
|
||||
|
||||
```swift
|
||||
import LyrebirdSynth
|
||||
|
||||
let score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
|
||||
Part("lead") {
|
||||
Note(.named(.c, 5), dur: .quarter, dyn: .mf, art: .staccato)
|
||||
Note(.named(.e, 5), dur: .eighth.dotted, dyn: .mf)
|
||||
Rest(dur: .eighth)
|
||||
Tuplet(3, inTimeOf: 2) {
|
||||
Note(.named(.g, 5), dur: .quarter)
|
||||
Note(.named(.a, 5), dur: .quarter)
|
||||
Note(.named(.b, 5), dur: .quarter)
|
||||
}
|
||||
Chord([.named(.c, 5), .named(.e, 5), .named(.g, 5)], dur: .half, dyn: .f, art: .tenuto)
|
||||
}
|
||||
Part("bass", channel: 1, clef: .bass) {
|
||||
Note(.named(.c, 3), dur: .whole, dyn: .mp)
|
||||
}
|
||||
}
|
||||
|
||||
let xml = score.toMusicXMLString() // export
|
||||
let restored = try Score.fromMusicXML(data: score.toMusicXMLData()) // round-trip
|
||||
for event in score.allEvents { // flat, absolute-beat events (rests excluded)
|
||||
let hz = event.pitch.frequency ?? 0
|
||||
// schedule a voice at event.beat * secondsPerBeat for event.performedDuration …
|
||||
}
|
||||
```
|
||||
|
||||
Notable score features:
|
||||
|
||||
- **Notation model** — per-part `Clef` (`.auto` infers from pitch range), `KeySignature` (score-level + per-part override), `TempoChange` (measure-indexed), `RepeatStructure` / volta `Ending`, transposing-instrument `Transpose`, grace notes, chord ties, and nested tuplet brackets. These are notation-only — `flatten()` / playback use the base `bpm`.
|
||||
- **MusicXML round-trip** — `score.toMusicXMLString()` / `.toMusicXMLData()` out, `Score.fromMusicXML(data:)` back. Spelling (letter + accidental, microtonal nine-step grid) is preserved.
|
||||
- **Sounding vs. notated duration** — `ScoreEvent.duration` is notated; `event.performedDuration` applies `articulation.durationScale` for audio / MIDI note-off.
|
||||
- **Playback** — `ScorePlayer` walks the flat event list against a `LyrebirdClock` on a `LyrebirdRoutine` (mirrors `MIDIFilePlayer`); SMF bridges via `Score+MIDIFile`.
|
||||
- **Pitch / scale theory toolkit** — spelling-aware `Interval` / `Scale` / `PitchCollection` / 12-tone rows, diatonic-vs-chromatic transposition, scale-to-scale mapping; results drop straight into the DSL (`Note(.named(...))`). See [`docs/stdlib/theory.md`](docs/stdlib/theory.md).
|
||||
|
||||
The template writes both files into the **project root** (next to `Package.swift`) via `LyrebirdPaths.projectRoot()` — see [File output locations](#file-output-locations) — so output lands in the same place whether you run with `lyrebird run`, `swift run`, or Xcode.
|
||||
|
||||
Full guide: `Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md`. Reference project: [`Demos/LyrebirdScoreDemo`](Demos/LyrebirdScoreDemo/).
|
||||
|
||||
---
|
||||
|
||||
## File output locations
|
||||
|
||||
When a project writes files (an NRT `.caf`, a MusicXML export, a recording), *where* they land depends on how the binary is launched: `lyrebird run` / `swift run` set the working directory to the package root, but **Xcode sets it to `DerivedData`** and a bare binary inherits whatever shell launched it. Hardcoding `URL(fileURLWithPath: "out.caf")` therefore drops files in surprising places.
|
||||
|
||||
`LyrebirdPaths` (core `Lyrebird` module) resolves the common locations for you:
|
||||
|
||||
| Member | Resolves to | Use for |
|
||||
|---|---|---|
|
||||
| `LyrebirdPaths.projectRoot()` | Folder containing `Package.swift`, found by walking up from the **calling source file** at compile time. Returns `URL?`. | Dev-time render/export output you want beside your project, independent of launch method. |
|
||||
| `LyrebirdPaths.documents` | `.documentDirectory` (`~/Documents` on macOS; the app sandbox Documents on iOS). | **Shipped apps** writing user-visible data. The right choice on iOS. |
|
||||
| `LyrebirdPaths.applicationSupport` | `.applicationSupportDirectory` | App-managed data (presets, state) not meant to be user-visible. |
|
||||
| `LyrebirdPaths.caches` | `.cachesDirectory` | Regenerable data the system may purge. |
|
||||
| `LyrebirdPaths.temporary` | Per-process temp dir | Scratch files. |
|
||||
| `LyrebirdPaths.home` | User home | — |
|
||||
| `LyrebirdPaths.currentWorkingDirectory` | Process cwd | Equals project root under `lyrebird run`; a sensible `??` fallback for `projectRoot()`. |
|
||||
| `LyrebirdPaths.desktop` *(macOS only)* | `.desktopDirectory`. Returns `URL?`. | Quick dev dumps. Needs an entitlement in a sandboxed app. |
|
||||
|
||||
```swift
|
||||
import LyrebirdSynth
|
||||
|
||||
// Dev-time: write beside the project, regardless of launch method.
|
||||
let dir = LyrebirdPaths.projectRoot() ?? LyrebirdPaths.currentWorkingDirectory
|
||||
let cafURL = dir.appendingPathComponent("render.caf")
|
||||
|
||||
// Shipped app (iOS/macOS): write where the sandbox allows.
|
||||
let userOut = LyrebirdPaths.documents.appendingPathComponent("render.caf")
|
||||
```
|
||||
|
||||
`projectRoot()` is a compile-time, source-anchored path — it reflects where the binary was **built**, so it does not exist on another user's machine. Use it for development output only; use `documents` / `applicationSupport` in anything you distribute. It walks up to `Package.swift` by default; pass a dot-prefixed `marker: ".xcodeproj"` (or `.xcworkspace`) — matched by extension, so it finds `MyApp.xcodeproj` — for an Xcode-project layout with no manifest.
|
||||
|
||||
---
|
||||
|
||||
## Xcode file templates
|
||||
|
||||
Beyond whole projects, the CLI installs **New File…** templates so you can add a Generator, Synthesizer, Task, Oscillator, Filter, Spectral Processor, AUv3 source-slot synth, test suite, and more without boilerplate:
|
||||
Beyond whole projects, the CLI installs **New File…** templates so you can add a Generator, Synthesizer, Task, Oscillator, Filter, Spectral Processor, Score, AUv3 source-slot synth, test suite, and more without boilerplate:
|
||||
|
||||
```bash
|
||||
lyrebird install-templates # New File… ▸ Lyrebird section appears in Xcode
|
||||
@@ -263,7 +347,7 @@ From a repo checkout you can equivalently run `bash scripts/install-xcode-templa
|
||||
|
||||
## Reference projects
|
||||
|
||||
The repo ships six runnable demos in [`Demos/`](Demos/), opened via `Lyrebird.xcworkspace`, covering every template above — start there to see complete, working code:
|
||||
The repo ships seven runnable demos in [`Demos/`](Demos/), opened via `Lyrebird.xcworkspace`, covering every template above — start there to see complete, working code:
|
||||
|
||||
| Demo | Mirrors template |
|
||||
|---|---|
|
||||
@@ -271,6 +355,7 @@ The repo ships six runnable demos in [`Demos/`](Demos/), opened via `Lyrebird.xc
|
||||
| [`LyrebirdMacOSDemo`](Demos/LyrebirdMacOSDemo/) | `macos-ui-xcode` |
|
||||
| [`LyrebirdiOSDemo`](Demos/LyrebirdiOSDemo/) | `ios-ui` |
|
||||
| [`LyrebirdNRTDemo`](Demos/LyrebirdNRTDemo/) | `nrt` |
|
||||
| [`LyrebirdScoreDemo`](Demos/LyrebirdScoreDemo/) | `score` |
|
||||
| [`LyrebirdAUv3Demo`](Demos/LyrebirdAUv3Demo/) | `auv3` |
|
||||
| [`LyrebirdScratchDemo`](Demos/LyrebirdScratchDemo/) | live-coding scratchpad |
|
||||
|
||||
|
||||
+22
-9
@@ -1,26 +1,26 @@
|
||||
# Lyrebird — Start Here
|
||||
|
||||
Six demo projects live in this workspace. This guide covers how to open them, what each one does, where to add your own synthesizers, and the gotchas that will bite you if you don't know about them.
|
||||
Seven demo projects live in this workspace. This guide covers how to open them, what each one does, where to add your own synthesizers, and the gotchas that will bite you if you don't know about them.
|
||||
|
||||
---
|
||||
|
||||
## Opening the Workspace
|
||||
|
||||
Open **`Lyrebird.xcworkspace`** — not any individual `.xcodeproj` file. The workspace links all six demo projects together so they share the local Lyrebird package.
|
||||
Open **`Lyrebird.xcworkspace`** — not any individual `.xcodeproj` file. The workspace links all seven demo projects together so they share the local Lyrebird package.
|
||||
|
||||
Once open, pick a scheme from the scheme picker at the top of the Xcode window and hit Run.
|
||||
|
||||
---
|
||||
|
||||
## The Six Demos
|
||||
## The Seven Demos
|
||||
|
||||
### LyrebirdDemo — Real-Time CLI
|
||||
|
||||
A command-line tool that plays audio through your default output device using `CoreAudioDriver`.
|
||||
|
||||
- **Where to add synthesizers:** `Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/` — `SineTone.swift` and `DelaySample.swift` are the starting examples
|
||||
- **Wire it up:** in `main.swift`, call `engine.schedule(MySynth(), after: 0.0)`
|
||||
- **To stop:** Ctrl-C in the Xcode console, or just let the synthesizer's done action free it
|
||||
- **Where to add synthesizers:** `Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/` — `General/SineTone.swift` and `General/DelaySample.swift` are the starting examples (the folder is grouped into `General/`, `Buffer/`, `Granular/`, `Spectral/`)
|
||||
- **Wire it up:** `main.swift` adds a synth and plays it — `try engine.add(mySynth)`, or `try engine.schedule(mySynth, after: seconds)` for sample-accurate start. (As shipped, `main.swift` runs a demo harness — `BufferDemos(engine: engine).runDemo()`; swap in your own.)
|
||||
- **To stop:** Ctrl-C in the Xcode console, or give a voice an envelope/line that frees itself (see below)
|
||||
|
||||
You can also run this from the terminal: `cd Demos/LyrebirdDemo && swift run`
|
||||
|
||||
@@ -36,8 +36,8 @@ A SwiftUI app with a live oscilloscope, parameter knobs, and real-time audio.
|
||||
|
||||
```swift
|
||||
final class MySynth: SynthesizerBase {
|
||||
@UIParam var freq: LyrebirdFloat = 440.0
|
||||
@UIParam var amp: LyrebirdFloat = 0.5
|
||||
@UIParam var freq: Double = 440.0
|
||||
@UIParam var amp: Double = 0.5
|
||||
|
||||
override func build() {
|
||||
let sig = OscSin.Audio(freq: freq) * amp
|
||||
@@ -105,6 +105,17 @@ let right = In.Audio(bus: 3) // numOutputChannels + 1
|
||||
|
||||
---
|
||||
|
||||
### LyrebirdScoreDemo — Score / MusicXML + Offline Render
|
||||
|
||||
A command-line tool that builds notated `Score`s with the result-builder DSL, exports them to MusicXML on the Desktop, round-trips them through the parser as a sanity check, then renders the audio to a CAF file via `NRTDriver`.
|
||||
|
||||
- **Output files:** `~/Desktop/LyrebirdScoreDemo.musicxml` (a multi-part demo score), `~/Desktop/LyrebirdScoreSections.musicxml` (a sectioned showcase), and `~/Desktop/LyrebirdScoreDemo.caf` (rendered audio). Open the `.musicxml` in Dorico / MuseScore / Finale; open the `.caf` in any DAW.
|
||||
- **Where the score is built:** `Demos/LyrebirdScoreDemo/LyrebirdScoreDemo/Demos/ScoreDemo.swift` — `makeScore()` (eight parts) and `makeSectionedShowcase()`.
|
||||
- **Notation coverage:** clefs, keys, dynamics/hairpins, ties, tuplets, grace notes, multi-staff `Staff`/`Voice`, sustain `Pedal`, repeats with 1st/2nd endings, `Section`s + rehearsal marks, glissandi, per-note display overrides, and page layout. Reference: [`Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md`](Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md).
|
||||
- **Rehearsal-mark tip:** use single-letter `Section` labels (`"A"`, `"B"`, `"C"`) — notation editors auto-sequence rehearsal marks and hide custom words.
|
||||
|
||||
---
|
||||
|
||||
### LyrebirdAUv3Demo — AUv3 Plugin Reference
|
||||
|
||||
A container app + `.appex` extension target shipping **Realized Sound: LyrebirdFM** — a two-operator FM synthesizer wrapped as an `aumu` Audio Unit v3. Loadable in Logic, GarageBand, AUM, Loopy Pro, and any other AUv3 host on macOS.
|
||||
@@ -152,11 +163,12 @@ final class MySynth: SynthesizerBase {
|
||||
override func build() {
|
||||
let sig = OscSin.Audio(freq: 440) * 0.3
|
||||
output(bus: 0, source: Pan2(input: sig, pan: 0))
|
||||
doneAction = .freeEnclosing
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Self-freeing voices:** there is no `doneAction` property to set on the synthesizer. Instead, build a `DoneActionWatchable` generator — `EnvelopeGen`, `Line`, `ExponentialLine`, etc. — **inside `build()`** with `doneAction: .freeNode`; it self-registers, and the engine frees the node when that generator finishes. (`DoneAction` cases are `.nothing`, `.freeNode`, `.loop`.)
|
||||
|
||||
---
|
||||
|
||||
## Common Gotchas
|
||||
@@ -182,6 +194,7 @@ final class MySynth: SynthesizerBase {
|
||||
| Synthesizer and node tree | `docs/protocols/synthesizer.md` |
|
||||
| All built-in generators | `docs/stdlib/generators.md` |
|
||||
| NRT / offline rendering | `docs/tooling/nrt-guide.md` |
|
||||
| Score / MusicXML authoring | `Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md` |
|
||||
| REPL / hot-swap | `docs/tooling/repl.md` |
|
||||
| Xcode file templates | `docs/tooling/xcode-templates.md` |
|
||||
| GUI / parameter binding | `docs/ui/gui-system.md` |
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
// swift-tools-version: 6.0
|
||||
import PackageDescription
|
||||
|
||||
// Phase 167 — `LyrebirdLiveCompile` and `LyrebirdLiveCompileUI` live in this
|
||||
// `LyrebirdLiveCompile` and `LyrebirdLiveCompileUI` live in this
|
||||
// sub-package so that cross-package `.product(name:, package:)` dependency
|
||||
// resolution forces SwiftPM to dynamic-link `libLyrebirdLiveCompile.dylib`
|
||||
// against `libLyrebird.dylib` instead of statically embedding `Lyrebird`'s
|
||||
@@ -20,13 +20,25 @@ let package = Package(
|
||||
name: "LyrebirdLiveCompile",
|
||||
platforms: [.macOS(.v15)],
|
||||
products: [
|
||||
// Product name ≠ target name (mirrors the main package's
|
||||
// `Lyrebird`/`LyrebirdDynamic` pairing). A `.dynamic` product whose name
|
||||
// EQUALS its target name collides in Xcode when that target is also
|
||||
// referenced as a static link elsewhere in the same build graph:
|
||||
// "Swift package target 'X' is linked as a static library by … but
|
||||
// cannot be built dynamically because there is a package product with
|
||||
// the same name." Naming the dynamic products `…Dynamic` removes the
|
||||
// collision so each target builds as a single shared dylib that every
|
||||
// consumer links dynamically. Target/module names are unchanged, so
|
||||
// `import LyrebirdLiveCompile` / `import LyrebirdLiveCompileUI` and the
|
||||
// test targets (which reference targets by name) are unaffected.
|
||||
.library(
|
||||
name: "LyrebirdLiveCompile",
|
||||
name: "LyrebirdLiveCompileDynamic",
|
||||
type: .dynamic,
|
||||
targets: ["LyrebirdLiveCompile"]
|
||||
),
|
||||
.library(
|
||||
name: "LyrebirdLiveCompileUI",
|
||||
name: "LyrebirdLiveCompileUIDynamic",
|
||||
type: .dynamic,
|
||||
targets: ["LyrebirdLiveCompileUI"]
|
||||
),
|
||||
],
|
||||
@@ -48,7 +60,7 @@ let package = Package(
|
||||
.product(name: "LyrebirdDynamic", package: "Lyrebird"),
|
||||
],
|
||||
path: "Sources/LyrebirdLiveCompileUI"
|
||||
// Swift 6 language mode (Phase 203): inherits the swift-tools 6.0 default.
|
||||
// Swift 6 language mode: inherits the swift-tools 6.0 default.
|
||||
),
|
||||
.testTarget(
|
||||
name: "LyrebirdLiveCompileTests",
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 142 core
|
||||
// LyrebirdLiveCompile — core
|
||||
//
|
||||
// `CompiledSnippet` owns the `dlopen` handle and the resolved entry function
|
||||
// pointer for one snippet's dylib. Held by the live session for the lifetime of
|
||||
@@ -35,7 +35,7 @@ public final class CompiledSnippet: @unchecked Sendable {
|
||||
/// Path to the dylib that was `dlopen`'d.
|
||||
public let dylibPath: String
|
||||
|
||||
/// Resolved entry function pointer. Calling this is Phase 143's job.
|
||||
/// Resolved entry function pointer. The snippet harness calls this.
|
||||
public let entry: SnippetEntry
|
||||
|
||||
/// Raw `dlopen` handle. Kept so the OS keeps the dylib mapped.
|
||||
|
||||
@@ -4,13 +4,13 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 144
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// One parsed `swiftc` diagnostic, with `line` already mapped from the wrapped-
|
||||
// snippet coordinate space back to the user's snippet coordinate space (via the
|
||||
// `userBodyLineOffset` from `SnippetHarness.wrap(userBody:)`).
|
||||
//
|
||||
// The editor in Phase 145 (`LyrebirdScratchView`) renders diagnostics in its
|
||||
// The editor (`LyrebirdScratchView`) renders diagnostics in its
|
||||
// margin gutter using `(line, column)` directly.
|
||||
|
||||
#if os(macOS)
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 144
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// `DiagnosticParser.parse(stderr:userBodyLineOffset:)` walks the swiftc stderr
|
||||
// stream line by line, extracts diagnostics matching the standard
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 144
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// Severity classifier for a parsed swiftc diagnostic line.
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 142 core
|
||||
// LyrebirdLiveCompile — core
|
||||
//
|
||||
// Errors raised by `LiveCompiler.compile(source:)`. RT path never sees these:
|
||||
// compilation is a main-thread (or background-queue) operation that runs long
|
||||
|
||||
@@ -4,12 +4,12 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 142 core
|
||||
// LyrebirdLiveCompile — core
|
||||
//
|
||||
// `LiveCompiler.compile(source:)` shells out to `swiftc -emit-library`, then
|
||||
// `dlopen`s the resulting dylib and resolves the snippet entry symbol. No UI,
|
||||
// no `SynthesisEngine` binding (those land in phases 143–146). macOS only —
|
||||
// iOS cannot exec swiftc.
|
||||
// no `SynthesisEngine` binding (those are handled by the harness and session
|
||||
// layers). macOS only — iOS cannot exec swiftc.
|
||||
|
||||
import Foundation
|
||||
#if os(macOS)
|
||||
@@ -34,8 +34,8 @@ public enum LiveCompiler {
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - source: Full Swift source, including the `@_cdecl("lyrebird_snippet_entry")`
|
||||
/// entry. Phase 143's `SnippetHarness` will wrap user input in a preamble that
|
||||
/// provides this; Phase 142 callers (incl. tests) write the full file.
|
||||
/// entry. `SnippetHarness` wraps user input in a preamble that provides
|
||||
/// this; direct callers (incl. tests) write the full file.
|
||||
/// - extraSwiftcArgs: Extra args appended to the `swiftc` invocation. Tests use
|
||||
/// this for `-suppress-warnings` etc. Production callers leave empty.
|
||||
/// - Returns: `CompiledSnippet` holding the dlopen handle and entry pointer.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 143
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// `LiveSession` owns the `SynthesisEngine` and tracks every `Synthesizer` that
|
||||
// each snippet `play(_:)`s, so the next non-additive re-evaluation can
|
||||
@@ -23,7 +23,7 @@ import LyrebirdSynth
|
||||
/// Snippets receive a `SnippetContext` bound to this session through
|
||||
/// `compileAndRun(_:additive:)`.
|
||||
///
|
||||
/// `@unchecked Sendable` (Phase 203): a `LiveSession` is shared between its `@MainActor`
|
||||
/// `@unchecked Sendable`: a `LiveSession` is shared between its `@MainActor`
|
||||
/// owner (`LyrebirdScratchModel`) and the `nonisolated` `compileAndRunAsync` it calls, so
|
||||
/// Swift 6 requires it to be `Sendable`. The conformance is sound by construction:
|
||||
///
|
||||
@@ -70,7 +70,7 @@ public final class LiveSession: @unchecked Sendable {
|
||||
engine: SynthesisEngine,
|
||||
importPaths: [URL] = LiveSession.defaultImportPaths(),
|
||||
librarySearchPaths: [URL] = LiveSession.defaultLibrarySearchPaths(),
|
||||
libraries: [String] = ["LyrebirdDynamic", "LyrebirdLiveCompile"],
|
||||
libraries: [String] = ["LyrebirdDynamic", "LyrebirdLiveCompileDynamic"],
|
||||
rpaths: [URL] = LiveSession.defaultRpaths()
|
||||
) {
|
||||
self.engine = engine
|
||||
@@ -91,7 +91,7 @@ public final class LiveSession: @unchecked Sendable {
|
||||
/// (⌘⇧↩ semantics in the future `LyrebirdScratchView` editor).
|
||||
/// - Returns: The compiled snippet handle. Retained internally so the dylib
|
||||
/// stays mapped; callers can ignore it.
|
||||
/// `@MainActor` (Phase 203): runs the snippet entry — and thus the user body's
|
||||
/// `@MainActor`: runs the snippet entry — and thus the user body's
|
||||
/// `MainActor.assumeIsolated { … }` and any `context.play(_:)` → `engine.add` — on the
|
||||
/// main thread, synchronously (swiftc compile included). The async variant
|
||||
/// ``compileAndRunAsync(_:additive:)`` keeps the compile off-main.
|
||||
@@ -112,8 +112,8 @@ public final class LiveSession: @unchecked Sendable {
|
||||
/// engine-touching steps (`clearTracked()` and the snippet entry via `runEntry`) then run
|
||||
/// on the **main actor**.
|
||||
///
|
||||
/// Running the entry on the main actor matters (Phase 203): the snippet's
|
||||
/// `context.play(_:)` calls `engine.add(_:)`, which is `@MainActor` (Phase 201) and
|
||||
/// Running the entry on the main actor matters: the snippet's
|
||||
/// `context.play(_:)` calls `engine.add(_:)`, which is `@MainActor` and
|
||||
/// mutates `engine.nodeTreeMirror` — state observed by SwiftUI on the main thread. A
|
||||
/// `nonisolated async` method resumes on the generic executor, NOT the caller's actor, so
|
||||
/// the hop is explicit here rather than assumed.
|
||||
@@ -288,7 +288,7 @@ public final class LiveSession: @unchecked Sendable {
|
||||
///
|
||||
/// Searches, in order:
|
||||
/// 1. Walks up from `Bundle(for: LiveSession.self).bundleURL` — this resolves
|
||||
/// to the directory holding `libLyrebirdLiveCompile.dylib` at runtime,
|
||||
/// to the directory holding `libLyrebirdLiveCompileDynamic.dylib` at runtime,
|
||||
/// which is the SPM debug/release dir.
|
||||
/// 2. Walks up from `Bundle.main.executableURL` — fallback for the case
|
||||
/// where the host bundles the dylibs into an `.app`.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 144
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// `LiveSession.compileAndRun(_:additive:)` throws this richer error so callers
|
||||
// see diagnostics pre-mapped to user-snippet coordinates. Other `LiveCompileError`
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 143
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// `SnippetContext` is the public API surface the user's snippet talks to. The
|
||||
// host (via `LiveSession.compileAndRun`) constructs one of these, passes the
|
||||
|
||||
@@ -4,16 +4,15 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 142 core
|
||||
// LyrebirdLiveCompile — core
|
||||
//
|
||||
// C ABI signature of the snippet's exported entry point.
|
||||
|
||||
#if os(macOS)
|
||||
|
||||
/// Snippets export this symbol via `@_cdecl("lyrebird_snippet_entry")`. Phase
|
||||
/// 143 will pass a pointer to a `LiveSession` (or harness context) here;
|
||||
/// Phase 142 only requires that snippets can declare a function matching this
|
||||
/// signature.
|
||||
/// Snippets export this symbol via `@_cdecl("lyrebird_snippet_entry")`. The host
|
||||
/// passes a pointer to a `LiveSession` (or harness context) here; snippets need
|
||||
/// only declare a function matching this signature.
|
||||
public typealias SnippetEntry = @convention(c) (UnsafeMutableRawPointer?) -> Void
|
||||
|
||||
#endif
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 143
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// `SnippetHarness.wrap(userBody:)` produces the full Swift source that
|
||||
// `LiveCompiler.compile(source:)` feeds to swiftc. The preamble imports the
|
||||
@@ -18,9 +18,9 @@ public enum SnippetHarness {
|
||||
|
||||
/// Wraps `userBody` in the standard preamble.
|
||||
///
|
||||
/// The user body runs inside `MainActor.assumeIsolated { … }` (Phase 203): snippets call
|
||||
/// The user body runs inside `MainActor.assumeIsolated { … }`: snippets call
|
||||
/// `@MainActor` API — `context.play(_:)` and `SynthesizerBase` subclass construction
|
||||
/// (both `@MainActor` since Phase 201) — which would not compile from the nonisolated
|
||||
/// (both `@MainActor`) — which would not compile from the nonisolated
|
||||
/// `@_cdecl` entry under Swift 6. The `assumeIsolated` closure gives the body main-actor
|
||||
/// isolation at compile time; it is safe at runtime because `LiveSession` always invokes
|
||||
/// the entry on the main actor (`compileAndRunAsync` hops via `MainActor.run`;
|
||||
|
||||
@@ -4,11 +4,11 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — Phase 143
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// Output of `SnippetHarness.wrap(userBody:)`. Carries the full Swift source
|
||||
// that `swiftc` will compile, plus the 1-based line number on which the user's
|
||||
// body begins. Phase 144's diagnostic parser subtracts `userBodyLineOffset - 1`
|
||||
// body begins. The diagnostic parser subtracts `userBodyLineOffset - 1`
|
||||
// from each swiftc-reported line so error rows point back at the row the user
|
||||
// typed.
|
||||
|
||||
|
||||
@@ -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`.
|
||||
///
|
||||
|
||||
@@ -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`
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -52,7 +52,7 @@ struct LiveSessionDiagnosticsTests {
|
||||
@Test
|
||||
func compilerErrorWrapsUnderlyingForNonCompileFailures() {
|
||||
// Force a non-compile error by pointing at a build dir that doesn't exist.
|
||||
// The Phase 142 compile path still succeeds (a swiftc invocation with -I
|
||||
// The compile path still succeeds (a swiftc invocation with -I
|
||||
// pointing at a missing dir surfaces as `compileFailed` via swiftc's own
|
||||
// "no such module" — not `compilerError`). Instead, drive a real
|
||||
// compilerError case by routing through a LiveCompileError that isn't
|
||||
@@ -60,7 +60,7 @@ struct LiveSessionDiagnosticsTests {
|
||||
// entrySymbolMissing — but a real run with full build dir succeeds.
|
||||
// We just verify the type LiveSessionError.compilerError exists and is
|
||||
// representable; behavioural coverage of non-compileFailed cases is
|
||||
// exercised at the LiveCompiler layer (Phase 142 tests).
|
||||
// exercised at the LiveCompiler layer.
|
||||
let err: LiveSessionError = LiveSessionError.compilerError(.swiftcNotFound)
|
||||
#expect(String(describing: err).contains("swiftc"))
|
||||
}
|
||||
|
||||
@@ -74,9 +74,9 @@ struct LiveSessionTests {
|
||||
#expect(session.lastSnippetMessage == "async hello")
|
||||
}
|
||||
|
||||
/// Phase 203 runtime guard: a snippet driven through `compileAndRunAsync` that calls
|
||||
/// Runtime guard: a snippet driven through `compileAndRunAsync` that calls
|
||||
/// `context.play(_:)` actually adds and tracks a synth. `context.play` → `engine.add` is
|
||||
/// `@MainActor` (Phase 201); `compileAndRunAsync` resumes the snippet entry on the main
|
||||
/// `@MainActor`; `compileAndRunAsync` resumes the snippet entry on the main
|
||||
/// actor (not the nonisolated executor it suspends on), so this exercises that hop.
|
||||
@Test
|
||||
func asyncCompileAndRunPlaysAndTracksSynth() async throws {
|
||||
|
||||
@@ -72,8 +72,8 @@ struct LyrebirdScratchModelTests {
|
||||
func runInvalidSnippetSurfacesUserCoordinateDiagnostics() async throws {
|
||||
let session: LiveSession = makeSession()
|
||||
// `let x: Int = "nope"` — guaranteed type-check error on the first row
|
||||
// of the user body. Phase 144 maps the wrapped-source line back to
|
||||
// user line 1.
|
||||
// of the user body. The diagnostic parser maps the wrapped-source line
|
||||
// back to user line 1.
|
||||
let model: LyrebirdScratchModel = LyrebirdScratchModel(
|
||||
session: session,
|
||||
initialText: "let x: Int = \"nope\"\n"
|
||||
|
||||
+3
@@ -19,4 +19,7 @@
|
||||
<FileRef
|
||||
location = "group:Demos/LyrebirdScratchDemo/LyrebirdScratchDemo.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Demos/LyrebirdScoreDemo/LyrebirdScoreDemo.xcodeproj">
|
||||
</FileRef>
|
||||
</Workspace>
|
||||
|
||||
@@ -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).
|
||||
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
# 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.1 — Real-time performance + score-timing fixes *(planned)*
|
||||
|
||||
A patch release: real-time CPU improvements to the synthesis engine's hot path,
|
||||
internal generator consolidation, and two score-side timing fixes. Fully
|
||||
backward-compatible — no public API changes.
|
||||
|
||||
### Real-time performance
|
||||
|
||||
The generator render path (`_computeSamples`) is now Accelerate-accelerated
|
||||
where it was previously scalar. Wins are largest for the primitives that appear
|
||||
in nearly every patch:
|
||||
|
||||
- **Unary math waveshapers** (`Sin` / `Cos` / `Exp` / `Log` / `Sqrt` / `Floor`
|
||||
/ `Ceil` / `Abs`) — vectorized via vForce / vDSP (~3× faster on a typical
|
||||
chained-op voice).
|
||||
- **Arithmetic operators** (`+` `−` `×` `÷` on generators, via
|
||||
`BinaryOpGenerator`) — vDSP dispatch, **bit-identical** to the scalar result
|
||||
(divide uses true-division, never reciprocal-multiply). Roughly 2–3.5× faster;
|
||||
applies to every `osc * gain + offset`-style graph.
|
||||
- **`LinLin`** — single fused `vDSP_vsmsaD` affine map (~27% faster).
|
||||
- **State-variable filter (`SVF`)** — shared per-block kernel; generator-driven
|
||||
cutoff uses block-boundary coefficient interpolation instead of a per-sample
|
||||
`sin()`.
|
||||
- **`Chorus` / `Flanger`** — power-of-two delay lines (bitwise index wrap).
|
||||
- **Butterworth band-pass / band-reject** — now use the same background-thread
|
||||
vDSP biquad-cascade path the low-pass / high-pass filters already had.
|
||||
|
||||
All vectorized paths keep a scalar fallback for short upstream blocks, so output
|
||||
is unchanged on every code path (transcendentals within tolerance; arithmetic
|
||||
and filter sums bit-exact).
|
||||
|
||||
### Internals (no API impact)
|
||||
|
||||
- Generator consolidation: the duplicated Butterworth cascade machinery, SVF
|
||||
block body, unary-math and binary-op inner loops, and power-of-two buffer
|
||||
sizing are now shared helpers (`ButterworthSectionEngine`, `runSVFBlock`,
|
||||
`UnaryMathVectorHelpers`, `BinaryOpVectorHelpers`, `lyrebirdNextPowerOfTwo`,
|
||||
`computeButterworthQs`). Several hundred lines of duplication removed.
|
||||
- New `LyrebirdBenchmark` target with before/after reference numbers
|
||||
(`docs/benchmarks/gp-baseline.md`).
|
||||
- Language-side consolidation: shared `isCounterExhausted` / `resetAll` Pattern
|
||||
helpers, a `_RandomPatternBase` for the random pattern engines, a
|
||||
`TemporalAlgorithmBase` for the counter-driven temporal algorithms, a shared
|
||||
MusicXML `<direction>` / `<pitch>` emit helper, and a single
|
||||
engine-mutation-to-main-queue dispatch helper shared by the routine/process
|
||||
contexts.
|
||||
|
||||
### Score / MusicXML
|
||||
|
||||
- **`ScorePart` entrance offset** — a part can enter later than the start of its
|
||||
section via `offset:` (`ScoreOffset.measures(_:)` / `.beats(_:)` /
|
||||
`.fraction(_:)`). Resolved at build time into leading rests (the same way
|
||||
`FillMeasure()` is resolved), so it flows through section sizing, MusicXML bar
|
||||
splitting, and `flatten()` with no special handling.
|
||||
- **MusicXML barline-fill fix** — corrected two emit-side defects in sectioned
|
||||
scores with rest-padded short parts: a barline-crossing atom that exactly
|
||||
filled a bar left the measure open (shifting every later note by one division,
|
||||
rendering constant 4/4 as 5/4), and section auto-padding used meter-agnostic
|
||||
rests that straddled barlines. Padding is now bar-grid aligned (clean
|
||||
whole-measure rests; anacrusis-aware). Lowering/playback math was already
|
||||
correct — both fixes are export-only.
|
||||
|
||||
---
|
||||
|
||||
## 1.1 — Enhanced algorithmic composition tools
|
||||
|
||||
Release 1.1 turns Lyrebird's score side from a thin event list into a full
|
||||
**algorithmic composition and notation toolkit**: a spelling-aware music-theory
|
||||
layer, a pattern/sequence library, a composable score DSL, and lossless MusicXML
|
||||
and Standard MIDI File round-trips. The real-time synthesis engine is unchanged —
|
||||
this release is additive and language-side.
|
||||
|
||||
### Music theory toolkit
|
||||
|
||||
- Spelling-aware **`Interval`**, **`Scale`**, and **`PitchCollection`** types
|
||||
(cells, sets, 12-tone rows) built on the existing `Letter` / `Accidental` /
|
||||
`NoteName` / `Pitch` foundation.
|
||||
- Diatonic-vs-chromatic transposition that preserves enharmonic spelling
|
||||
(`B♯` stays `B♯`, never collapses to `C`), scale-degree mapping between scales,
|
||||
and conversion straight to Hz / seconds for synthesis.
|
||||
- **`Pitch.mapIntoRange(low:high:)`** — fold a pitch into a register by whole
|
||||
octaves while preserving pitch class and spelling.
|
||||
- See [`docs/stdlib/theory.md`](docs/stdlib/theory.md).
|
||||
|
||||
### Patterns
|
||||
|
||||
- `Pattern<T>` factory catalog for sequences, series, random and stochastic
|
||||
distributions (uniform, brownian, gaussian, cauchy, beta, weighted, shuffle…),
|
||||
and combinators (map, filter, stutter, switching, interleave, round-robin…).
|
||||
- **`Pattern.sequence(_:repeats:offset:)`** — start a sequence partway through
|
||||
its list via `offset`.
|
||||
- Euclidean rhythm generator.
|
||||
- See [`Sources/Lyrebird/Lyrebird.docc/RoutineTask.md`](Sources/Lyrebird/Lyrebird.docc/RoutineTask.md).
|
||||
|
||||
### Score DSL and notation
|
||||
|
||||
- A result-builder score DSL — `Score`, `Part`, `Note`, `Rest`, `Chord`,
|
||||
`Tuplet`, `Voice`, `Staff` — that flattens to sample-accurate `ScoreEvent`s and
|
||||
plays back through `ScorePlayer`.
|
||||
- Notation features: dynamics, articulations, **crescendo / diminuendo hairpins**,
|
||||
**slurs** (a `Slur { }` block plus per-note `spanners:` for shared-boundary and
|
||||
overlapping spans), authored ties, grace notes, repeats and volta endings,
|
||||
mid-piece tempo changes, key signatures and transposing parts, mid-voice clef
|
||||
changes, grand-staff `Staff` grouping, and sustain `Pedal` marks.
|
||||
- Meter: `TimeSignature` + segmented `MeterMap`, mid-piece meter changes,
|
||||
anacrusis (pickup) bars, and polymeter (per-part meter overrides).
|
||||
- `ScoreTimeline` musical addressing (`BeatPosition`) with overlap policies and
|
||||
multi-voice fills.
|
||||
- See [`Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md`](Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md).
|
||||
|
||||
### Score structure and page layout
|
||||
|
||||
- **`Section { }`** blocks group parts into sequential sections, each with its
|
||||
own local bar/beat numbering. Assembled into a `Score`, sections render
|
||||
sequentially with continuous global measure numbers and a rehearsal mark per
|
||||
section; tacet instruments are auto-filled so every staff stays bar-aligned.
|
||||
`ScorePart` gains an `id` (defaults to `name`) to match the same instrument
|
||||
across sections.
|
||||
- **`PageLayout`** sets MusicXML page defaults: page size
|
||||
(`letter` / `legal` / `tabloid` / `a4` / `a3` / custom mm), `portrait` /
|
||||
`landscape` orientation, per-side odd/even margins, and `<scaling>`. Authored
|
||||
in millimeters and converted to MusicXML tenths on export.
|
||||
- **`NoteDisplay`** per-note display overrides via a `display:` parameter on
|
||||
`Note` / `Chord`: custom notehead shape (`x`, `diamond`, `slash`, `.hidden`,
|
||||
raw `.other(_)`, …), note size (`cue` / `large`), hidden stem, and hidden
|
||||
beam.
|
||||
- **Glissandos / slides** between two notes via the spanner API
|
||||
(`.beginGlissando(_:)` / `.endGlissando`): glissando (wavy/curved) or slide
|
||||
(straight) `kind`, a line type (`solid` / `dashed` / `dotted` / `wavy`), and an
|
||||
optional text label.
|
||||
|
||||
### Import / export
|
||||
|
||||
- **MusicXML** export and import (`score-partwise` 4.0) with a spelling- and
|
||||
event-faithful round trip across the notation features above.
|
||||
- **Standard MIDI File** round-trip (`Score` ↔ SMF).
|
||||
|
||||
### API and internals
|
||||
|
||||
- `Score.timeSignature` and the `Score` initializers take a typed
|
||||
`TimeSignature` (a `(numerator, denominator)` pair converts via
|
||||
`TimeSignature(_:)`) instead of a raw tuple.
|
||||
- Internal cleanups with no API impact: the MusicXML encoder and parser were
|
||||
split from two monoliths into focused, grouped extension files, and the
|
||||
parser's per-`<note>` state was extracted into a dedicated value type.
|
||||
|
||||
> **Namespace note:** the score DSL exposes capitalized free functions
|
||||
> (`Note`, `Chord`, `Voice`, `Slur`, `Crescendo`, …). `Voice` in particular can
|
||||
> collide with same-named types from other frameworks — qualify or alias if you
|
||||
> hit an ambiguity.
|
||||
|
||||
---
|
||||
|
||||
## 1.0 — Initial release
|
||||
|
||||
First public release: the real-time synthesis engine, the `Generator` /
|
||||
`Synthesizer` protocols and standard-library generators, the Core Audio and
|
||||
non-real-time drivers, `LyrebirdUI`, the `lyrebird` CLI and project scaffolding,
|
||||
and the AUv3 plug-in support.
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
// EngineDispatch.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Dispatch a throwing engine mutation to the main queue — preserving the
|
||||
/// `SynthesisEngine.pendingQueue` single-producer invariant — and log on failure.
|
||||
///
|
||||
/// Shared by the language-side context types (`LyrebirdRoutineContext`,
|
||||
/// `LyrebirdProcessContext`) whose `add` / `schedule` calls cross from a routine
|
||||
/// or process thread onto the main thread. `label` names the call site in the
|
||||
/// failure message only.
|
||||
func lyrebirdDispatchEngineOp(
|
||||
_ label: String,
|
||||
_ work: @escaping @MainActor () throws -> Void
|
||||
) {
|
||||
DispatchQueue.main.async {
|
||||
// The block runs on the main queue, so main-actor isolation holds.
|
||||
MainActor.assumeIsolated {
|
||||
do { try work() }
|
||||
catch { print("[Lyrebird] \(label) failed: \(error)") }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import Foundation
|
||||
/// Run a `@MainActor` node-tree mutation from a language-side dispatch adapter that may
|
||||
/// execute either on the main thread or inline on a background NRT driver thread.
|
||||
///
|
||||
/// Phase 201 made the engine's add / schedule path and `Synthesizer.build`/`release`/`free`
|
||||
/// The engine's add / schedule path and `Synthesizer.build`/`release`/`free` are
|
||||
/// `@MainActor`. Most language-side adapters dispatch those mutations through
|
||||
/// `DispatchQueue.main.async`, so they already run on main. Two adapters can run a mutation
|
||||
/// **inline on the calling thread**:
|
||||
|
||||
@@ -1745,7 +1745,7 @@ public final class SynthesisEngine {
|
||||
/// All allocation and `build()`/`rebuildGraph()` happen here on the calling thread;
|
||||
/// the RT thread never allocates in `applyEvent`.
|
||||
/// `@MainActor`: invokes `build()` / `rebuildGraph()` (the `@MainActor` language-side
|
||||
/// add surface — Phase 201). The node-tree add path runs on the main thread by
|
||||
/// add surface). The node-tree add path runs on the main thread by
|
||||
/// contract (it also touches `nodeTreeMirror`, observed by SwiftUI).
|
||||
@MainActor private func prepareNode(_ synth: any Synthesizer) -> PreparedNode {
|
||||
if let base: SynthesizerBase = synth as? SynthesizerBase {
|
||||
|
||||
+2
-2
@@ -57,7 +57,7 @@ public struct LyrebirdMessageContext: @unchecked Sendable {
|
||||
let args: SynthArgs = SynthArgs(engine, synth)
|
||||
_dispatch {
|
||||
// `_dispatch` runs this on main (default `DispatchQueue.main.async`) or inline on
|
||||
// the NRT driver thread. `engine.add` is `@MainActor` (Phase 201); the bridge runs
|
||||
// the NRT driver thread. `engine.add` is `@MainActor`; the bridge runs
|
||||
// it inline when already on main and hops synchronously otherwise — never traps.
|
||||
lyrebirdRunMainActorMutation {
|
||||
do { try args.engine.add(args.synth) }
|
||||
@@ -133,7 +133,7 @@ public struct LyrebirdMessageContext: @unchecked Sendable {
|
||||
// but a warning posts to LyrebirdMessageCenter so debug builds get
|
||||
// visibility into typo'd OSC / MIDI param names that would
|
||||
// otherwise route silently to nowhere.
|
||||
// `updateParameter` is `@MainActor` (Phase 201). `_dispatch` runs this on main
|
||||
// `updateParameter` is `@MainActor`. `_dispatch` runs this on main
|
||||
// (default) or inline on the NRT driver — the bridge runs inline on main and hops
|
||||
// synchronously off-main, never trapping.
|
||||
lyrebirdRunMainActorMutation {
|
||||
|
||||
@@ -72,7 +72,7 @@ public final class DelayLine: GeneratorBase, AudioGenerator {
|
||||
self.delayIsGenerator = resolvedDelay is any Generator
|
||||
|
||||
let maxSamples: Int = Int(ceil(maxDelay * sampleRate)) + 1
|
||||
let bufSize: Int = Self.nextPowerOf2(max(maxSamples, 2))
|
||||
let bufSize: Int = lyrebirdNextPowerOfTwo(max(maxSamples, 2))
|
||||
self.buffer = [Double](repeating: 0, count: bufSize)
|
||||
self.bufferMask = bufSize - 1
|
||||
self.maxDelaySamples = maxSamples - 1
|
||||
@@ -220,13 +220,6 @@ public final class DelayLine: GeneratorBase, AudioGenerator {
|
||||
let d: Double = y1
|
||||
return ((a * frac + b) * frac + c) * frac + d
|
||||
}
|
||||
|
||||
private static func nextPowerOf2(_ n: Int) -> Int {
|
||||
guard n > 1 else { return 1 }
|
||||
var result: Int = 1
|
||||
while result < n { result <<= 1 }
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
|
||||
@@ -129,7 +129,7 @@ public final class DelayLineFeedback: GeneratorBase, AudioGenerator {
|
||||
self.targetAmpIsGenerator = resolvedTargetAmp is any Generator
|
||||
|
||||
let maxSamples: Int = Int(ceil(maxDelay * sampleRate)) + 1
|
||||
let bufSize: Int = Self.nextPowerOf2(max(maxSamples, 2))
|
||||
let bufSize: Int = lyrebirdNextPowerOfTwo(max(maxSamples, 2))
|
||||
self.buffer = [Double](repeating: 0, count: bufSize)
|
||||
self.bufferMask = bufSize - 1
|
||||
self.maxDelaySamples = maxSamples - 1
|
||||
@@ -319,13 +319,6 @@ public final class DelayLineFeedback: GeneratorBase, AudioGenerator {
|
||||
let d: Double = y1
|
||||
return ((a * frac + b) * frac + c) * frac + d
|
||||
}
|
||||
|
||||
private static func nextPowerOf2(_ n: Int) -> Int {
|
||||
guard n > 1 else { return 1 }
|
||||
var result: Int = 1
|
||||
while result < n { result <<= 1 }
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
|
||||
@@ -86,7 +86,7 @@ public final class AllpassFilter: GeneratorBase, AudioGenerator {
|
||||
self.interpolation = interpolation
|
||||
|
||||
let maxSamples: Int = Int(ceil(maxDelay * sampleRate)) + 1
|
||||
let bufSize: Int = Self.nextPowerOf2(max(maxSamples, 2))
|
||||
let bufSize: Int = lyrebirdNextPowerOfTwo(max(maxSamples, 2))
|
||||
self.inputBuf = [Double](repeating: 0, count: bufSize)
|
||||
self.outputBuf = [Double](repeating: 0, count: bufSize)
|
||||
self.bufferMask = bufSize - 1
|
||||
@@ -258,13 +258,6 @@ public final class AllpassFilter: GeneratorBase, AudioGenerator {
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
private static func nextPowerOf2(_ n: Int) -> Int {
|
||||
guard n > 1 else { return 1 }
|
||||
var r: Int = 1
|
||||
while r < n { r <<= 1 }
|
||||
return r
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Local cubic interpolation
|
||||
|
||||
@@ -4,14 +4,19 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import Foundation
|
||||
|
||||
/// Cascaded Butterworth bandpass filter, orders 1–8 per section (2 × order total poles).
|
||||
///
|
||||
/// Implemented as an N-th order Butterworth HP section (cutoff = `lowFreq`) cascaded with
|
||||
/// an N-th order Butterworth LP section (cutoff = `highFreq`). Both sections share the same
|
||||
/// Butterworth Q values. The unified ping-pong cascade routes through a single `_scratch`
|
||||
/// buffer — no extra allocation on the RT thread.
|
||||
/// Implemented as two `ButterworthSectionEngine` instances in series: an N-th order
|
||||
/// Butterworth HP section (cutoff = `lowFreq`) cascaded with an N-th order Butterworth
|
||||
/// LP section (cutoff = `highFreq`). The HP engine writes into an intermediate buffer
|
||||
/// `_inter`; the LP engine reads `_inter` and writes to the final output. Both sections
|
||||
/// share the same per-stage Butterworth Q values.
|
||||
///
|
||||
/// Each engine manages its own scratch buffer and background-thread vDSP setup builder
|
||||
/// independently — no shared mutable state between the two sections on the RT thread.
|
||||
///
|
||||
/// Per-stage Q values follow the Butterworth pole formula:
|
||||
/// ```
|
||||
@@ -47,30 +52,11 @@ public enum ButterworthBandPass {
|
||||
/// Per-stage Butterworth Q values — `⌊order/2⌋` entries. Shared by both HP and LP sections.
|
||||
public let butterworthQs: [Double]
|
||||
|
||||
// HP section
|
||||
private var hpBiquadStages: [BiquadState]
|
||||
private var hpFirstOrder: FirstOrderState?
|
||||
private var cachedHPBiquadCoeffs: [BiquadCoeffs]
|
||||
private var cachedHPFO: (b0: Double, b1: Double, na1: Double) = (0, 0, 0)
|
||||
|
||||
// LP section
|
||||
private var lpBiquadStages: [BiquadState]
|
||||
private var lpFirstOrder: FirstOrderState?
|
||||
private var cachedLPBiquadCoeffs: [BiquadCoeffs]
|
||||
private var cachedLPFO: (b0: Double, b1: Double, na1: Double) = (0, 0, 0)
|
||||
|
||||
private var prevLowFreq: Double = -1.0
|
||||
private var prevHighFreq: Double = -1.0
|
||||
private var prevSampleRate: Double = -1.0
|
||||
|
||||
private var _scratch: [Double]
|
||||
private let hpEngine: ButterworthSectionEngine // HP section (lowFreq cutoff)
|
||||
private let lpEngine: ButterworthSectionEngine // LP section (highFreq cutoff)
|
||||
private var _inter: [Double] // HP output / LP input
|
||||
private let _mulAdd: MulAddSpec
|
||||
|
||||
/// Number of stages in each LP/HP section.
|
||||
private let sectionStageCount: Int
|
||||
/// Total stages = 2 × sectionStageCount.
|
||||
private let totalStageCount: Int
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to filter.
|
||||
/// - lowFreq: Lower edge of the passband in Hz (HP cutoff — content below this is attenuated). No internal clamping; stay below `highFreq` and Nyquist.
|
||||
@@ -86,7 +72,6 @@ public enum ButterworthBandPass {
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
let resolvedLowFreq: any ValidGeneratorInput = lowFreq._resolvedInput()
|
||||
let resolvedHighFreq: any ValidGeneratorInput = highFreq._resolvedInput()
|
||||
@@ -98,35 +83,24 @@ public enum ButterworthBandPass {
|
||||
|
||||
let clampedOrder: Int = min(max(order, 1), maxButterworthOrder)
|
||||
self.order = clampedOrder
|
||||
self.butterworthQs = computeButterworthQs(order: clampedOrder)
|
||||
|
||||
let numBiquads: Int = clampedOrder / 2
|
||||
var qs: [Double] = [Double]()
|
||||
if numBiquads > 0 {
|
||||
for k: Int in 1...numBiquads {
|
||||
let angle: Double = Double.pi * Double(2 * k + clampedOrder - 1)
|
||||
/ Double(2 * clampedOrder)
|
||||
qs.append(-1.0 / (2.0 * cos(angle)))
|
||||
}
|
||||
}
|
||||
self.butterworthQs = qs
|
||||
|
||||
let hasFO: Bool = clampedOrder % 2 == 1
|
||||
let stagesPerSection: Int = numBiquads + (hasFO ? 1 : 0)
|
||||
let numFilterSections: Int = 2 // HP section + LP section
|
||||
self.sectionStageCount = stagesPerSection
|
||||
self.totalStageCount = stagesPerSection * numFilterSections
|
||||
|
||||
self.hpBiquadStages = [BiquadState](repeating: BiquadState(), count: numBiquads)
|
||||
self.hpFirstOrder = hasFO ? FirstOrderState() : nil
|
||||
self.cachedHPBiquadCoeffs = [BiquadCoeffs](repeating: .zero, count: numBiquads)
|
||||
|
||||
self.lpBiquadStages = [BiquadState](repeating: BiquadState(), count: numBiquads)
|
||||
self.lpFirstOrder = hasFO ? FirstOrderState() : nil
|
||||
self.cachedLPBiquadCoeffs = [BiquadCoeffs](repeating: .zero, count: numBiquads)
|
||||
|
||||
self._scratch = makeSampleBuffer()
|
||||
self.hpEngine = ButterworthSectionEngine(
|
||||
order: clampedOrder,
|
||||
foCoeffs: { foHPCoeffs(freq: $0, sr: $1) },
|
||||
biquadCoeffs: { rbjHighPassCoeffs(freq: $0, q: $1, sampleRate: $2) },
|
||||
threadName: "LyrebirdButterworthBP-HP.vDSP"
|
||||
)
|
||||
self.lpEngine = ButterworthSectionEngine(
|
||||
order: clampedOrder,
|
||||
foCoeffs: { foLPCoeffs(freq: $0, sr: $1) },
|
||||
biquadCoeffs: { rbjLowPassCoeffs(freq: $0, q: $1, sampleRate: $2) },
|
||||
threadName: "LyrebirdButterworthBP-LP.vDSP"
|
||||
)
|
||||
self._inter = makeSampleBuffer()
|
||||
self._mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
@@ -138,234 +112,69 @@ public enum ButterworthBandPass {
|
||||
}
|
||||
let sr: Double = graph.engine.sampleRate
|
||||
|
||||
if lowFreqIsGenerator || highFreqIsGenerator {
|
||||
let lowSamples: [Double]? = lowFreqIsGenerator
|
||||
? lowFreqInput.calculatedSamples(graph: graph, count: count).first
|
||||
: nil
|
||||
let highSamples: [Double]? = highFreqIsGenerator
|
||||
? highFreqInput.calculatedSamples(graph: graph, count: count).first
|
||||
: nil
|
||||
|
||||
let lastI: Int = count - 1
|
||||
let lf0: Double = lowSamples.map { $0.isEmpty ? lowFreqInput.floatValue(graph: graph) : $0[0] }
|
||||
?? lowFreqInput.floatValue(graph: graph)
|
||||
let lfN: Double = lowSamples.map { $0.isEmpty ? lf0 : $0[min($0.count - 1, lastI)] } ?? lf0
|
||||
let hf0: Double = highSamples.map { $0.isEmpty ? highFreqInput.floatValue(graph: graph) : $0[0] }
|
||||
?? highFreqInput.floatValue(graph: graph)
|
||||
let hfN: Double = highSamples.map { $0.isEmpty ? hf0 : $0[min($0.count - 1, lastI)] } ?? hf0
|
||||
|
||||
runAudioRate(input: inputBlock, lf0: lf0, lfN: lfN, hf0: hf0, hfN: hfN, sr: sr, count: count)
|
||||
} else {
|
||||
let lowFreq: Double = lowFreqInput.floatValue(graph: graph)
|
||||
let highFreq: Double = highFreqInput.floatValue(graph: graph)
|
||||
if lowFreq != prevLowFreq || highFreq != prevHighFreq || sr != prevSampleRate {
|
||||
recomputeScalarCoeffs(lowFreq: lowFreq, highFreq: highFreq, sr: sr)
|
||||
prevLowFreq = lowFreq; prevHighFreq = highFreq; prevSampleRate = sr
|
||||
// Resolve the HP-section cutoff (lowFreq — the lower passband edge).
|
||||
let hpScalarFreq: Double
|
||||
let hpF0: Double
|
||||
let hpFN: Double
|
||||
if lowFreqIsGenerator {
|
||||
let lowSamples: [[Double]] = lowFreqInput.calculatedSamples(graph: graph, count: count)
|
||||
if let s: [Double] = lowSamples.first, !s.isEmpty {
|
||||
hpF0 = s[0]
|
||||
hpFN = s[min(s.count - 1, count - 1)]
|
||||
} else {
|
||||
let fv: Double = lowFreqInput.floatValue(graph: graph)
|
||||
hpF0 = fv; hpFN = fv
|
||||
}
|
||||
runScalar(input: inputBlock, count: count)
|
||||
hpScalarFreq = 0.0
|
||||
} else {
|
||||
hpScalarFreq = lowFreqInput.floatValue(graph: graph)
|
||||
hpF0 = 0.0; hpFN = 0.0
|
||||
}
|
||||
|
||||
// Resolve the LP-section cutoff (highFreq — the upper passband edge).
|
||||
let lpScalarFreq: Double
|
||||
let lpF0: Double
|
||||
let lpFN: Double
|
||||
if highFreqIsGenerator {
|
||||
let highSamples: [[Double]] = highFreqInput.calculatedSamples(graph: graph, count: count)
|
||||
if let s: [Double] = highSamples.first, !s.isEmpty {
|
||||
lpF0 = s[0]
|
||||
lpFN = s[min(s.count - 1, count - 1)]
|
||||
} else {
|
||||
let fv: Double = highFreqInput.floatValue(graph: graph)
|
||||
lpF0 = fv; lpFN = fv
|
||||
}
|
||||
lpScalarFreq = 0.0
|
||||
} else {
|
||||
lpScalarFreq = highFreqInput.floatValue(graph: graph)
|
||||
lpF0 = 0.0; lpFN = 0.0
|
||||
}
|
||||
|
||||
// Series: HP section (lowFreq cutoff) → intermediate buffer → LP section (highFreq cutoff) → output.
|
||||
hpEngine.process(
|
||||
input: inputBlock,
|
||||
freqIsGenerator: lowFreqIsGenerator,
|
||||
scalarFreq: hpScalarFreq,
|
||||
f0: hpF0,
|
||||
fN: hpFN,
|
||||
sr: sr,
|
||||
count: count,
|
||||
into: &_inter
|
||||
)
|
||||
lpEngine.process(
|
||||
input: _inter,
|
||||
freqIsGenerator: highFreqIsGenerator,
|
||||
scalarFreq: lpScalarFreq,
|
||||
f0: lpF0,
|
||||
fN: lpFN,
|
||||
sr: sr,
|
||||
count: count,
|
||||
into: &_result[0]
|
||||
)
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
// MARK: - Coefficient computation
|
||||
|
||||
private func recomputeScalarCoeffs(
|
||||
lowFreq: Double,
|
||||
highFreq: Double,
|
||||
sr: Double
|
||||
) {
|
||||
if hpFirstOrder != nil { cachedHPFO = foHPCoeffs(freq: lowFreq, sr: sr) }
|
||||
for i: Int in 0..<hpBiquadStages.count {
|
||||
cachedHPBiquadCoeffs[i] = rbjHighPassCoeffs(freq: lowFreq, q: butterworthQs[i], sampleRate: sr)
|
||||
}
|
||||
if lpFirstOrder != nil { cachedLPFO = foLPCoeffs(freq: highFreq, sr: sr) }
|
||||
for i: Int in 0..<lpBiquadStages.count {
|
||||
cachedLPBiquadCoeffs[i] = rbjLowPassCoeffs(freq: highFreq, q: butterworthQs[i], sampleRate: sr)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Unified cascade
|
||||
|
||||
/// Buffer routing: stage `i` of `stageCount` total writes to `_result[0]` when `(stageCount+i)%2==1`,
|
||||
/// else to `_scratch`. LP stages (i ≥ sectionStageCount) always have i > 0.
|
||||
private func runScalar(
|
||||
input: [Double],
|
||||
count: Int
|
||||
) {
|
||||
let stageCount: Int = totalStageCount
|
||||
|
||||
// HP section (stages 0 ..< sectionStageCount)
|
||||
var si: Int = 0
|
||||
if var fo: FirstOrderState = hpFirstOrder {
|
||||
let writesResult: Bool = (stageCount + 0) % 2 == 1
|
||||
if writesResult {
|
||||
fo.processBlock(input: input, b0: cachedHPFO.b0, b1: cachedHPFO.b1, na1: cachedHPFO.na1,
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
fo.processBlock(input: input, b0: cachedHPFO.b0, b1: cachedHPFO.b1, na1: cachedHPFO.na1,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
hpFirstOrder = fo
|
||||
si = 1
|
||||
}
|
||||
for bi: Int in 0..<hpBiquadStages.count {
|
||||
let i: Int = si + bi
|
||||
let writesResult: Bool = (stageCount + i) % 2 == 1
|
||||
if writesResult {
|
||||
if i == 0 {
|
||||
hpBiquadStages[bi].processBlock(input: input, coeffs: cachedHPBiquadCoeffs[bi],
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
hpBiquadStages[bi].processBlock(input: _scratch, coeffs: cachedHPBiquadCoeffs[bi],
|
||||
into: &_result[0], count: count)
|
||||
}
|
||||
} else {
|
||||
if i == 0 {
|
||||
hpBiquadStages[bi].processBlock(input: input, coeffs: cachedHPBiquadCoeffs[bi],
|
||||
into: &_scratch, count: count)
|
||||
} else {
|
||||
hpBiquadStages[bi].processBlock(input: _result[0], coeffs: cachedHPBiquadCoeffs[bi],
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// LP section (stages sectionStageCount ..< totalStageCount; i > 0 always)
|
||||
var lpi: Int = sectionStageCount
|
||||
if var fo: FirstOrderState = lpFirstOrder {
|
||||
let i: Int = lpi
|
||||
let writesResult: Bool = (stageCount + i) % 2 == 1
|
||||
if writesResult {
|
||||
fo.processBlock(input: _scratch, b0: cachedLPFO.b0, b1: cachedLPFO.b1, na1: cachedLPFO.na1,
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
fo.processBlock(input: _result[0], b0: cachedLPFO.b0, b1: cachedLPFO.b1, na1: cachedLPFO.na1,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
lpFirstOrder = fo
|
||||
lpi += 1
|
||||
}
|
||||
for bi: Int in 0..<lpBiquadStages.count {
|
||||
let i: Int = lpi + bi
|
||||
let writesResult: Bool = (stageCount + i) % 2 == 1
|
||||
if writesResult {
|
||||
lpBiquadStages[bi].processBlock(input: _scratch, coeffs: cachedLPBiquadCoeffs[bi],
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
lpBiquadStages[bi].processBlock(input: _result[0], coeffs: cachedLPBiquadCoeffs[bi],
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func runAudioRate(
|
||||
input: [Double],
|
||||
lf0: Double,
|
||||
lfN: Double,
|
||||
hf0: Double,
|
||||
hfN: Double,
|
||||
sr: Double,
|
||||
count: Int
|
||||
) {
|
||||
let stageCount: Int = totalStageCount
|
||||
|
||||
// Precompute HP boundary coefficients
|
||||
let hpFOS: (b0: Double, b1: Double, na1: Double)
|
||||
let hpFOE: (b0: Double, b1: Double, na1: Double)
|
||||
if hpFirstOrder != nil {
|
||||
hpFOS = foHPCoeffs(freq: lf0, sr: sr)
|
||||
hpFOE = foHPCoeffs(freq: lfN, sr: sr)
|
||||
} else {
|
||||
hpFOS = (0, 0, 0); hpFOE = (0, 0, 0)
|
||||
}
|
||||
|
||||
// Precompute LP boundary coefficients
|
||||
let lpFOS: (b0: Double, b1: Double, na1: Double)
|
||||
let lpFOE: (b0: Double, b1: Double, na1: Double)
|
||||
if lpFirstOrder != nil {
|
||||
lpFOS = foLPCoeffs(freq: hf0, sr: sr)
|
||||
lpFOE = foLPCoeffs(freq: hfN, sr: sr)
|
||||
} else {
|
||||
lpFOS = (0, 0, 0); lpFOE = (0, 0, 0)
|
||||
}
|
||||
|
||||
// HP section
|
||||
var si: Int = 0
|
||||
if var fo: FirstOrderState = hpFirstOrder {
|
||||
let writesResult: Bool = (stageCount + 0) % 2 == 1
|
||||
if writesResult {
|
||||
fo.processBlock(input: input,
|
||||
startB0: hpFOS.b0, startB1: hpFOS.b1, startNa1: hpFOS.na1,
|
||||
endB0: hpFOE.b0, endB1: hpFOE.b1, endNa1: hpFOE.na1,
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
fo.processBlock(input: input,
|
||||
startB0: hpFOS.b0, startB1: hpFOS.b1, startNa1: hpFOS.na1,
|
||||
endB0: hpFOE.b0, endB1: hpFOE.b1, endNa1: hpFOE.na1,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
hpFirstOrder = fo
|
||||
si = 1
|
||||
}
|
||||
for bi: Int in 0..<hpBiquadStages.count {
|
||||
let i: Int = si + bi
|
||||
let writesResult: Bool = (stageCount + i) % 2 == 1
|
||||
let startC: BiquadCoeffs = rbjHighPassCoeffs(freq: lf0, q: butterworthQs[bi], sampleRate: sr)
|
||||
let endC: BiquadCoeffs = rbjHighPassCoeffs(freq: lfN, q: butterworthQs[bi], sampleRate: sr)
|
||||
if writesResult {
|
||||
if i == 0 {
|
||||
hpBiquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
hpBiquadStages[bi].processBlock(input: _scratch, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_result[0], count: count)
|
||||
}
|
||||
} else {
|
||||
if i == 0 {
|
||||
hpBiquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_scratch, count: count)
|
||||
} else {
|
||||
hpBiquadStages[bi].processBlock(input: _result[0], startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// LP section (i > 0 always)
|
||||
var lpi: Int = sectionStageCount
|
||||
if var fo: FirstOrderState = lpFirstOrder {
|
||||
let i: Int = lpi
|
||||
let writesResult: Bool = (stageCount + i) % 2 == 1
|
||||
if writesResult {
|
||||
fo.processBlock(input: _scratch,
|
||||
startB0: lpFOS.b0, startB1: lpFOS.b1, startNa1: lpFOS.na1,
|
||||
endB0: lpFOE.b0, endB1: lpFOE.b1, endNa1: lpFOE.na1,
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
fo.processBlock(input: _result[0],
|
||||
startB0: lpFOS.b0, startB1: lpFOS.b1, startNa1: lpFOS.na1,
|
||||
endB0: lpFOE.b0, endB1: lpFOE.b1, endNa1: lpFOE.na1,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
lpFirstOrder = fo
|
||||
lpi += 1
|
||||
}
|
||||
for bi: Int in 0..<lpBiquadStages.count {
|
||||
let i: Int = lpi + bi
|
||||
let writesResult: Bool = (stageCount + i) % 2 == 1
|
||||
let startC: BiquadCoeffs = rbjLowPassCoeffs(freq: hf0, q: butterworthQs[bi], sampleRate: sr)
|
||||
let endC: BiquadCoeffs = rbjLowPassCoeffs(freq: hfN, q: butterworthQs[bi], sampleRate: sr)
|
||||
if writesResult {
|
||||
lpBiquadStages[bi].processBlock(input: _scratch, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
lpBiquadStages[bi].processBlock(input: _result[0], startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,17 +4,20 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import Foundation
|
||||
|
||||
/// Cascaded Butterworth band-reject (notch) filter, orders 1–8 per section (2 × order total poles).
|
||||
///
|
||||
/// Implemented as two parallel paths summed: an N-th order Butterworth LP section
|
||||
/// (cutoff = `lowFreq`) plus an N-th order Butterworth HP section (cutoff = `highFreq`).
|
||||
/// Content between `lowFreq` and `highFreq` is attenuated; content outside that band passes.
|
||||
/// Implemented as two parallel `ButterworthSectionEngine` instances summed: an N-th order
|
||||
/// Butterworth LP section (cutoff = `lowFreq`) plus an N-th order Butterworth HP section
|
||||
/// (cutoff = `highFreq`). Content between `lowFreq` and `highFreq` is attenuated; content
|
||||
/// outside that band passes.
|
||||
///
|
||||
/// The LP cascade writes to a dedicated `_lpResult` buffer; the HP cascade writes to
|
||||
/// `_result[0]`. Both share a single `_scratch` buffer (used sequentially). Final output
|
||||
/// is the element-wise sum written back into `_result[0]`. No RT allocation.
|
||||
/// The LP engine writes to a dedicated `_lpOut` buffer; the HP engine writes to `_result[0]`.
|
||||
/// Both engines have independent scratch buffers and background-thread vDSP setup builders —
|
||||
/// no shared mutable state between the two sections on the RT thread. The final output is the
|
||||
/// element-wise sum (`vDSP_vaddD`) of `_lpOut` into `_result[0]`. No RT allocation.
|
||||
///
|
||||
/// ## Usage
|
||||
/// ```swift
|
||||
@@ -45,32 +48,15 @@ public enum ButterworthBandReject {
|
||||
/// Per-stage Butterworth Q values — `⌊order/2⌋` entries. Shared by both LP and HP sections.
|
||||
public let butterworthQs: [Double]
|
||||
|
||||
// LP section
|
||||
private var lpBiquadStages: [BiquadState]
|
||||
private var lpFirstOrder: FirstOrderState?
|
||||
private var cachedLPBiquadCoeffs: [BiquadCoeffs]
|
||||
private var cachedLPFO: (b0: Double, b1: Double, na1: Double) = (0, 0, 0)
|
||||
|
||||
// HP section
|
||||
private var hpBiquadStages: [BiquadState]
|
||||
private var hpFirstOrder: FirstOrderState?
|
||||
private var cachedHPBiquadCoeffs: [BiquadCoeffs]
|
||||
private var cachedHPFO: (b0: Double, b1: Double, na1: Double) = (0, 0, 0)
|
||||
|
||||
private var prevLowFreq: Double = -1.0
|
||||
private var prevHighFreq: Double = -1.0
|
||||
private var prevSampleRate: Double = -1.0
|
||||
|
||||
private var _lpResult: [Double] // LP cascade output
|
||||
private var _scratch: [Double] // shared intermediate buffer
|
||||
private let lpEngine: ButterworthSectionEngine // LP section (lowFreq cutoff)
|
||||
private let hpEngine: ButterworthSectionEngine // HP section (highFreq cutoff)
|
||||
private var _lpOut: [Double] // LP cascade output buffer
|
||||
private let _mulAdd: MulAddSpec
|
||||
|
||||
private let sectionStageCount: Int
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to filter.
|
||||
/// - lowFreq: Upper edge of the reject band in Hz (LP cutoff — content below this is passed by the LP path). No internal clamping; stay below `highFreq` and Nyquist.
|
||||
/// - highFreq: Lower edge of the reject band in Hz (HP cutoff — content above this is passed by the HP path). No internal clamping; stay above `lowFreq`.
|
||||
/// - lowFreq: Lower edge of the reject band in Hz (LP cutoff — content below this is passed by the LP path). No internal clamping; stay below `highFreq` and Nyquist.
|
||||
/// - highFreq: Upper edge of the reject band in Hz (HP cutoff — content above this is passed by the HP path). No internal clamping; stay above `lowFreq`.
|
||||
/// - order: Filter order per section 1–8 (clamped internally). Total poles = 2 × order. Higher order = deeper, narrower notch but higher CPU cost. Defaults to `2`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
@@ -82,7 +68,6 @@ public enum ButterworthBandReject {
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
let resolvedLowFreq: any ValidGeneratorInput = lowFreq._resolvedInput()
|
||||
let resolvedHighFreq: any ValidGeneratorInput = highFreq._resolvedInput()
|
||||
@@ -94,33 +79,24 @@ public enum ButterworthBandReject {
|
||||
|
||||
let clampedOrder: Int = min(max(order, 1), maxButterworthOrder)
|
||||
self.order = clampedOrder
|
||||
self.butterworthQs = computeButterworthQs(order: clampedOrder)
|
||||
|
||||
let numBiquads: Int = clampedOrder / 2
|
||||
var qs: [Double] = [Double]()
|
||||
if numBiquads > 0 {
|
||||
for k: Int in 1...numBiquads {
|
||||
let angle: Double = Double.pi * Double(2 * k + clampedOrder - 1)
|
||||
/ Double(2 * clampedOrder)
|
||||
qs.append(-1.0 / (2.0 * cos(angle)))
|
||||
}
|
||||
}
|
||||
self.butterworthQs = qs
|
||||
|
||||
let hasFO: Bool = clampedOrder % 2 == 1
|
||||
self.sectionStageCount = numBiquads + (hasFO ? 1 : 0)
|
||||
|
||||
self.lpBiquadStages = [BiquadState](repeating: BiquadState(), count: numBiquads)
|
||||
self.lpFirstOrder = hasFO ? FirstOrderState() : nil
|
||||
self.cachedLPBiquadCoeffs = [BiquadCoeffs](repeating: .zero, count: numBiquads)
|
||||
|
||||
self.hpBiquadStages = [BiquadState](repeating: BiquadState(), count: numBiquads)
|
||||
self.hpFirstOrder = hasFO ? FirstOrderState() : nil
|
||||
self.cachedHPBiquadCoeffs = [BiquadCoeffs](repeating: .zero, count: numBiquads)
|
||||
|
||||
self._lpResult = makeSampleBuffer()
|
||||
self._scratch = makeSampleBuffer()
|
||||
self.lpEngine = ButterworthSectionEngine(
|
||||
order: clampedOrder,
|
||||
foCoeffs: { foLPCoeffs(freq: $0, sr: $1) },
|
||||
biquadCoeffs: { rbjLowPassCoeffs(freq: $0, q: $1, sampleRate: $2) },
|
||||
threadName: "LyrebirdButterworthBR-LP.vDSP"
|
||||
)
|
||||
self.hpEngine = ButterworthSectionEngine(
|
||||
order: clampedOrder,
|
||||
foCoeffs: { foHPCoeffs(freq: $0, sr: $1) },
|
||||
biquadCoeffs: { rbjHighPassCoeffs(freq: $0, q: $1, sampleRate: $2) },
|
||||
threadName: "LyrebirdButterworthBR-HP.vDSP"
|
||||
)
|
||||
self._lpOut = makeSampleBuffer()
|
||||
self._mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
@@ -132,250 +108,78 @@ public enum ButterworthBandReject {
|
||||
}
|
||||
let sr: Double = graph.engine.sampleRate
|
||||
|
||||
if lowFreqIsGenerator || highFreqIsGenerator {
|
||||
let lowSamples: [Double]? = lowFreqIsGenerator
|
||||
? lowFreqInput.calculatedSamples(graph: graph, count: count).first
|
||||
: nil
|
||||
let highSamples: [Double]? = highFreqIsGenerator
|
||||
? highFreqInput.calculatedSamples(graph: graph, count: count).first
|
||||
: nil
|
||||
|
||||
let lastI: Int = count - 1
|
||||
let lf0: Double = lowSamples.map { $0.isEmpty ? lowFreqInput.floatValue(graph: graph) : $0[0] }
|
||||
?? lowFreqInput.floatValue(graph: graph)
|
||||
let lfN: Double = lowSamples.map { $0.isEmpty ? lf0 : $0[min($0.count - 1, lastI)] } ?? lf0
|
||||
let hf0: Double = highSamples.map { $0.isEmpty ? highFreqInput.floatValue(graph: graph) : $0[0] }
|
||||
?? highFreqInput.floatValue(graph: graph)
|
||||
let hfN: Double = highSamples.map { $0.isEmpty ? hf0 : $0[min($0.count - 1, lastI)] } ?? hf0
|
||||
|
||||
runLPAudioRate(input: inputBlock, f0: lf0, fN: lfN, sr: sr, count: count)
|
||||
runHPAudioRate(input: inputBlock, f0: hf0, fN: hfN, sr: sr, count: count)
|
||||
} else {
|
||||
let lowFreq: Double = lowFreqInput.floatValue(graph: graph)
|
||||
let highFreq: Double = highFreqInput.floatValue(graph: graph)
|
||||
if lowFreq != prevLowFreq || highFreq != prevHighFreq || sr != prevSampleRate {
|
||||
recomputeScalarCoeffs(lowFreq: lowFreq, highFreq: highFreq, sr: sr)
|
||||
prevLowFreq = lowFreq; prevHighFreq = highFreq; prevSampleRate = sr
|
||||
// Resolve low-frequency (LP cutoff) inputs.
|
||||
let lpScalarFreq: Double
|
||||
let lpF0: Double
|
||||
let lpFN: Double
|
||||
if lowFreqIsGenerator {
|
||||
let lowSamples: [[Double]] = lowFreqInput.calculatedSamples(graph: graph, count: count)
|
||||
if let s: [Double] = lowSamples.first, !s.isEmpty {
|
||||
lpF0 = s[0]
|
||||
lpFN = s[min(s.count - 1, count - 1)]
|
||||
} else {
|
||||
let fv: Double = lowFreqInput.floatValue(graph: graph)
|
||||
lpF0 = fv; lpFN = fv
|
||||
}
|
||||
runLPScalar(input: inputBlock, count: count)
|
||||
runHPScalar(input: inputBlock, count: count)
|
||||
lpScalarFreq = 0.0
|
||||
} else {
|
||||
lpScalarFreq = lowFreqInput.floatValue(graph: graph)
|
||||
lpF0 = 0.0; lpFN = 0.0
|
||||
}
|
||||
|
||||
// Parallel sum: LP (in _lpResult) + HP (in _result[0]) → _result[0]
|
||||
for i: Int in 0..<count { _result[0][i] += _lpResult[i] }
|
||||
// Resolve high-frequency (HP cutoff) inputs.
|
||||
let hpScalarFreq: Double
|
||||
let hpF0: Double
|
||||
let hpFN: Double
|
||||
if highFreqIsGenerator {
|
||||
let highSamples: [[Double]] = highFreqInput.calculatedSamples(graph: graph, count: count)
|
||||
if let s: [Double] = highSamples.first, !s.isEmpty {
|
||||
hpF0 = s[0]
|
||||
hpFN = s[min(s.count - 1, count - 1)]
|
||||
} else {
|
||||
let fv: Double = highFreqInput.floatValue(graph: graph)
|
||||
hpF0 = fv; hpFN = fv
|
||||
}
|
||||
hpScalarFreq = 0.0
|
||||
} else {
|
||||
hpScalarFreq = highFreqInput.floatValue(graph: graph)
|
||||
hpF0 = 0.0; hpFN = 0.0
|
||||
}
|
||||
|
||||
// Parallel: LP section (lowFreq) and HP section (highFreq) each process the raw input.
|
||||
lpEngine.process(
|
||||
input: inputBlock,
|
||||
freqIsGenerator: lowFreqIsGenerator,
|
||||
scalarFreq: lpScalarFreq,
|
||||
f0: lpF0,
|
||||
fN: lpFN,
|
||||
sr: sr,
|
||||
count: count,
|
||||
into: &_lpOut
|
||||
)
|
||||
hpEngine.process(
|
||||
input: inputBlock,
|
||||
freqIsGenerator: highFreqIsGenerator,
|
||||
scalarFreq: hpScalarFreq,
|
||||
f0: hpF0,
|
||||
fN: hpFN,
|
||||
sr: sr,
|
||||
count: count,
|
||||
into: &_result[0]
|
||||
)
|
||||
|
||||
// Sum: LP (in _lpOut) + HP (in _result[0]) → _result[0]
|
||||
_lpOut.withUnsafeBufferPointer { lpBuf in
|
||||
_result[0].withUnsafeMutableBufferPointer { outBuf in
|
||||
guard let lpBase: UnsafePointer<Double> = lpBuf.baseAddress,
|
||||
let outBase: UnsafeMutablePointer<Double> = outBuf.baseAddress else { return }
|
||||
vDSP_vaddD(lpBase, 1, outBase, 1, outBase, 1, vDSP_Length(count))
|
||||
}
|
||||
}
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
// MARK: - Coefficient computation
|
||||
|
||||
private func recomputeScalarCoeffs(
|
||||
lowFreq: Double,
|
||||
highFreq: Double,
|
||||
sr: Double
|
||||
) {
|
||||
if lpFirstOrder != nil { cachedLPFO = foLPCoeffs(freq: lowFreq, sr: sr) }
|
||||
for i: Int in 0..<lpBiquadStages.count {
|
||||
cachedLPBiquadCoeffs[i] = rbjLowPassCoeffs(freq: lowFreq, q: butterworthQs[i], sampleRate: sr)
|
||||
}
|
||||
if hpFirstOrder != nil { cachedHPFO = foHPCoeffs(freq: highFreq, sr: sr) }
|
||||
for i: Int in 0..<hpBiquadStages.count {
|
||||
cachedHPBiquadCoeffs[i] = rbjHighPassCoeffs(freq: highFreq, q: butterworthQs[i], sampleRate: sr)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - LP cascade (primary buffer = _lpResult)
|
||||
|
||||
private func runLPScalar(
|
||||
input: [Double],
|
||||
count: Int
|
||||
) {
|
||||
let stageCount: Int = sectionStageCount
|
||||
var si: Int = 0
|
||||
if var fo: FirstOrderState = lpFirstOrder {
|
||||
let writesResult: Bool = (stageCount + 0) % 2 == 1
|
||||
if writesResult {
|
||||
fo.processBlock(input: input, b0: cachedLPFO.b0, b1: cachedLPFO.b1, na1: cachedLPFO.na1,
|
||||
into: &_lpResult, count: count)
|
||||
} else {
|
||||
fo.processBlock(input: input, b0: cachedLPFO.b0, b1: cachedLPFO.b1, na1: cachedLPFO.na1,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
lpFirstOrder = fo
|
||||
si = 1
|
||||
}
|
||||
for bi: Int in 0..<lpBiquadStages.count {
|
||||
let i: Int = si + bi
|
||||
let writesResult: Bool = (stageCount + i) % 2 == 1
|
||||
if writesResult {
|
||||
if i == 0 {
|
||||
lpBiquadStages[bi].processBlock(input: input, coeffs: cachedLPBiquadCoeffs[bi],
|
||||
into: &_lpResult, count: count)
|
||||
} else {
|
||||
lpBiquadStages[bi].processBlock(input: _scratch, coeffs: cachedLPBiquadCoeffs[bi],
|
||||
into: &_lpResult, count: count)
|
||||
}
|
||||
} else {
|
||||
if i == 0 {
|
||||
lpBiquadStages[bi].processBlock(input: input, coeffs: cachedLPBiquadCoeffs[bi],
|
||||
into: &_scratch, count: count)
|
||||
} else {
|
||||
lpBiquadStages[bi].processBlock(input: _lpResult, coeffs: cachedLPBiquadCoeffs[bi],
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - HP cascade (primary buffer = _result[0])
|
||||
|
||||
private func runHPScalar(
|
||||
input: [Double],
|
||||
count: Int
|
||||
) {
|
||||
let stageCount: Int = sectionStageCount
|
||||
var si: Int = 0
|
||||
if var fo: FirstOrderState = hpFirstOrder {
|
||||
let writesResult: Bool = (stageCount + 0) % 2 == 1
|
||||
if writesResult {
|
||||
fo.processBlock(input: input, b0: cachedHPFO.b0, b1: cachedHPFO.b1, na1: cachedHPFO.na1,
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
fo.processBlock(input: input, b0: cachedHPFO.b0, b1: cachedHPFO.b1, na1: cachedHPFO.na1,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
hpFirstOrder = fo
|
||||
si = 1
|
||||
}
|
||||
for bi: Int in 0..<hpBiquadStages.count {
|
||||
let i: Int = si + bi
|
||||
let writesResult: Bool = (stageCount + i) % 2 == 1
|
||||
if writesResult {
|
||||
if i == 0 {
|
||||
hpBiquadStages[bi].processBlock(input: input, coeffs: cachedHPBiquadCoeffs[bi],
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
hpBiquadStages[bi].processBlock(input: _scratch, coeffs: cachedHPBiquadCoeffs[bi],
|
||||
into: &_result[0], count: count)
|
||||
}
|
||||
} else {
|
||||
if i == 0 {
|
||||
hpBiquadStages[bi].processBlock(input: input, coeffs: cachedHPBiquadCoeffs[bi],
|
||||
into: &_scratch, count: count)
|
||||
} else {
|
||||
hpBiquadStages[bi].processBlock(input: _result[0], coeffs: cachedHPBiquadCoeffs[bi],
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Audio-rate paths
|
||||
|
||||
private func runLPAudioRate(
|
||||
input: [Double],
|
||||
f0: Double,
|
||||
fN: Double,
|
||||
sr: Double,
|
||||
count: Int
|
||||
) {
|
||||
let stageCount: Int = sectionStageCount
|
||||
var si: Int = 0
|
||||
if var fo: FirstOrderState = lpFirstOrder {
|
||||
let s: (b0: Double, b1: Double, na1: Double) = foLPCoeffs(freq: f0, sr: sr)
|
||||
let e: (b0: Double, b1: Double, na1: Double) = foLPCoeffs(freq: fN, sr: sr)
|
||||
let writesResult: Bool = (stageCount + 0) % 2 == 1
|
||||
if writesResult {
|
||||
fo.processBlock(input: input,
|
||||
startB0: s.b0, startB1: s.b1, startNa1: s.na1,
|
||||
endB0: e.b0, endB1: e.b1, endNa1: e.na1,
|
||||
into: &_lpResult, count: count)
|
||||
} else {
|
||||
fo.processBlock(input: input,
|
||||
startB0: s.b0, startB1: s.b1, startNa1: s.na1,
|
||||
endB0: e.b0, endB1: e.b1, endNa1: e.na1,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
lpFirstOrder = fo
|
||||
si = 1
|
||||
}
|
||||
for bi: Int in 0..<lpBiquadStages.count {
|
||||
let i: Int = si + bi
|
||||
let writesResult: Bool = (stageCount + i) % 2 == 1
|
||||
let startC: BiquadCoeffs = rbjLowPassCoeffs(freq: f0, q: butterworthQs[bi], sampleRate: sr)
|
||||
let endC: BiquadCoeffs = rbjLowPassCoeffs(freq: fN, q: butterworthQs[bi], sampleRate: sr)
|
||||
if writesResult {
|
||||
if i == 0 {
|
||||
lpBiquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_lpResult, count: count)
|
||||
} else {
|
||||
lpBiquadStages[bi].processBlock(input: _scratch, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_lpResult, count: count)
|
||||
}
|
||||
} else {
|
||||
if i == 0 {
|
||||
lpBiquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_scratch, count: count)
|
||||
} else {
|
||||
lpBiquadStages[bi].processBlock(input: _lpResult, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func runHPAudioRate(
|
||||
input: [Double],
|
||||
f0: Double,
|
||||
fN: Double,
|
||||
sr: Double,
|
||||
count: Int
|
||||
) {
|
||||
let stageCount: Int = sectionStageCount
|
||||
var si: Int = 0
|
||||
if var fo: FirstOrderState = hpFirstOrder {
|
||||
let s: (b0: Double, b1: Double, na1: Double) = foHPCoeffs(freq: f0, sr: sr)
|
||||
let e: (b0: Double, b1: Double, na1: Double) = foHPCoeffs(freq: fN, sr: sr)
|
||||
let writesResult: Bool = (stageCount + 0) % 2 == 1
|
||||
if writesResult {
|
||||
fo.processBlock(input: input,
|
||||
startB0: s.b0, startB1: s.b1, startNa1: s.na1,
|
||||
endB0: e.b0, endB1: e.b1, endNa1: e.na1,
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
fo.processBlock(input: input,
|
||||
startB0: s.b0, startB1: s.b1, startNa1: s.na1,
|
||||
endB0: e.b0, endB1: e.b1, endNa1: e.na1,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
hpFirstOrder = fo
|
||||
si = 1
|
||||
}
|
||||
for bi: Int in 0..<hpBiquadStages.count {
|
||||
let i: Int = si + bi
|
||||
let writesResult: Bool = (stageCount + i) % 2 == 1
|
||||
let startC: BiquadCoeffs = rbjHighPassCoeffs(freq: f0, q: butterworthQs[bi], sampleRate: sr)
|
||||
let endC: BiquadCoeffs = rbjHighPassCoeffs(freq: fN, q: butterworthQs[bi], sampleRate: sr)
|
||||
if writesResult {
|
||||
if i == 0 {
|
||||
hpBiquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
hpBiquadStages[bi].processBlock(input: _scratch, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_result[0], count: count)
|
||||
}
|
||||
} else {
|
||||
if i == 0 {
|
||||
hpBiquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_scratch, count: count)
|
||||
} else {
|
||||
hpBiquadStages[bi].processBlock(input: _result[0], startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
// ButterworthCascadeBase.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Thin Generator shell for the lowpass / highpass Butterworth filters.
|
||||
///
|
||||
/// All single-cascade machinery (biquad stages, optional first-order section, cached
|
||||
/// coefficients, scratch buffer, vDSP background-thread builder) lives in
|
||||
/// `ButterworthSectionEngine`. This class owns one engine, resolves its `input` and
|
||||
/// `freq` inputs, delegates the per-block computation, and applies `mul`/`add`.
|
||||
///
|
||||
/// Concrete filters subclass this and inject only their per-stage coefficient formulas
|
||||
/// and a thread name; all state and lifecycle live in the engine.
|
||||
///
|
||||
/// ## vDSP acceleration
|
||||
/// For constant or block-rate `freq` (non-generator), a background thread builds a
|
||||
/// `vDSP_biquad_SetupD` from the current coefficients and delivers it via a lock-free
|
||||
/// `SPSCQueue`. Once the setup arrives the biquad cascade uses `vDSP_biquadD`; the
|
||||
/// first-order section (odd orders) stays scalar. Audio-rate `freq` always uses the
|
||||
/// scalar interpolating path. All machinery lives inside `ButterworthSectionEngine`.
|
||||
public class _ButterworthCascadeBase: GeneratorBase, AudioGenerator {
|
||||
|
||||
private let inputSource: any ValidGeneratorInput
|
||||
private let freqInput: any ValidGeneratorInput
|
||||
private let freqIsGenerator: Bool
|
||||
private let _mulAdd: MulAddSpec
|
||||
|
||||
private let engine: ButterworthSectionEngine
|
||||
|
||||
/// Filter order, clamped to `[1, maxButterworthOrder]` at init.
|
||||
public var order: Int { engine.order }
|
||||
|
||||
/// Per-stage Butterworth Q values — `⌊order/2⌋` entries, computed once at init.
|
||||
public var butterworthQs: [Double] { engine.butterworthQs }
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to filter.
|
||||
/// - freq: Cutoff frequency in Hz. No internal clamping; stay below Nyquist (sampleRate / 2).
|
||||
/// - order: Filter order 1–8 (clamped internally).
|
||||
/// - mul: Output multiplier.
|
||||
/// - add: Output offset.
|
||||
/// - foCoeffs: First-order section coefficient formula `(freq, sr) -> (b0, b1, na1)`.
|
||||
/// - biquadCoeffs: Biquad-stage coefficient formula `(freq, q, sampleRate) -> BiquadCoeffs`.
|
||||
/// - threadName: Name for the background vDSP setup-builder thread.
|
||||
init(
|
||||
input: any ValidGeneratorInput,
|
||||
freq: any ValidGeneratorInput,
|
||||
order: Int,
|
||||
mul: any ValidGeneratorInput,
|
||||
add: any ValidGeneratorInput,
|
||||
foCoeffs: @escaping (Double, Double) -> (b0: Double, b1: Double, na1: Double),
|
||||
biquadCoeffs: @escaping (Double, Double, Double) -> BiquadCoeffs,
|
||||
threadName: String
|
||||
) {
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
let resolvedFreq: any ValidGeneratorInput = freq._resolvedInput()
|
||||
self.inputSource = resolvedInput
|
||||
self.freqInput = resolvedFreq
|
||||
self.freqIsGenerator = resolvedFreq is any Generator
|
||||
self._mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
self.engine = ButterworthSectionEngine(
|
||||
order: order,
|
||||
foCoeffs: foCoeffs,
|
||||
biquadCoeffs: biquadCoeffs,
|
||||
threadName: threadName
|
||||
)
|
||||
super.init()
|
||||
}
|
||||
|
||||
// MARK: - Compute
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
guard let inputBlock: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first else {
|
||||
return _result
|
||||
}
|
||||
let sr: Double = graph.engine.sampleRate
|
||||
|
||||
let f0: Double
|
||||
let fN: Double
|
||||
let scalarFreq: Double
|
||||
if freqIsGenerator {
|
||||
let freqSamplesOuter: [[Double]] = freqInput.calculatedSamples(graph: graph, count: count)
|
||||
if let freqSamples: [Double] = freqSamplesOuter.first, !freqSamples.isEmpty {
|
||||
f0 = freqSamples[0]
|
||||
fN = freqSamples[min(freqSamples.count - 1, count - 1)]
|
||||
} else {
|
||||
let fv: Double = freqInput.floatValue(graph: graph)
|
||||
f0 = fv
|
||||
fN = fv
|
||||
}
|
||||
scalarFreq = 0.0
|
||||
} else {
|
||||
scalarFreq = freqInput.floatValue(graph: graph)
|
||||
f0 = 0.0
|
||||
fN = 0.0
|
||||
}
|
||||
|
||||
engine.process(
|
||||
input: inputBlock,
|
||||
freqIsGenerator: freqIsGenerator,
|
||||
scalarFreq: scalarFreq,
|
||||
f0: f0,
|
||||
fN: fN,
|
||||
sr: sr,
|
||||
count: count,
|
||||
into: &_result[0]
|
||||
)
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// ButterworthHelpers.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
// MARK: - Butterworth pole-Q helper
|
||||
|
||||
/// Computes per-stage Butterworth Q values for a filter of the given (already-clamped) order.
|
||||
///
|
||||
/// Returns `⌊order / 2⌋` Q values, one per biquad stage, using the pole formula:
|
||||
/// ```
|
||||
/// Q_k = −1 / (2 · cos(π · (2k + order − 1) / (2 · order))) k = 1 … ⌊order / 2⌋
|
||||
/// ```
|
||||
///
|
||||
/// - Parameter order: Filter order, already clamped to `[1, maxButterworthOrder]`.
|
||||
/// - Returns: Array of Q values, empty when `order == 1` (first-order section only, no biquads).
|
||||
internal func computeButterworthQs(order: Int) -> [Double] {
|
||||
let numBiquads: Int = order / 2
|
||||
guard numBiquads > 0 else { return [] }
|
||||
var qs: [Double] = [Double]()
|
||||
qs.reserveCapacity(numBiquads)
|
||||
let twiceOrder: Double = Double(2 * order)
|
||||
for k: Int in 1...numBiquads {
|
||||
let numerator: Double = Double.pi * Double(2 * k + order - 1)
|
||||
let angle: Double = numerator / twiceOrder
|
||||
qs.append(-1.0 / (2.0 * cos(angle)))
|
||||
}
|
||||
return qs
|
||||
}
|
||||
@@ -4,17 +4,14 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import Foundation
|
||||
|
||||
/// Cascaded Butterworth highpass filter, orders 1–8.
|
||||
///
|
||||
/// Mirror of `ButterworthLowPass` — identical cascade logic; only the per-stage coefficient
|
||||
/// formula differs (RBJ HPF instead of LPF, and the bilinear first-order section is a HPF).
|
||||
///
|
||||
/// ## vDSP acceleration
|
||||
///
|
||||
/// Same Option-B background-thread strategy as `ButterworthLowPass`. See that class for details.
|
||||
/// Mirror of `ButterworthLowPass`: all cascade machinery lives in
|
||||
/// `_ButterworthCascadeBase`; this type injects the highpass coefficient
|
||||
/// formulas — RBJ highpass per biquad stage, and a bilinear first-order highpass
|
||||
/// for odd orders.
|
||||
///
|
||||
/// ## Usage
|
||||
/// ```swift
|
||||
@@ -30,369 +27,34 @@ import Foundation
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public enum ButterworthHighPass {
|
||||
|
||||
public final class Audio: GeneratorBase, AudioGenerator {
|
||||
public final class Audio: _ButterworthCascadeBase {
|
||||
|
||||
private static let bgPollInterval: TimeInterval = 0.001
|
||||
|
||||
private let inputSource: any ValidGeneratorInput
|
||||
private let freqInput: any ValidGeneratorInput
|
||||
private let freqIsGenerator: Bool
|
||||
|
||||
/// Filter order, clamped to `[1, maxButterworthOrder]` at init.
|
||||
public let order: Int
|
||||
|
||||
/// Per-stage Butterworth Q values — `⌊order/2⌋` entries, computed once at init.
|
||||
public let butterworthQs: [Double]
|
||||
|
||||
private var biquadStages: [BiquadState]
|
||||
private var firstOrderState: FirstOrderState?
|
||||
|
||||
private var _scratch: [Double]
|
||||
|
||||
private var cachedBiquadCoeffs: [BiquadCoeffs]
|
||||
private var cachedFO: (b0: Double, b1: Double, na1: Double) = (0, 0, 0)
|
||||
private var prevFreq: Double = -1.0
|
||||
private var prevSampleRate: Double = -1.0
|
||||
private let _mulAdd: MulAddSpec
|
||||
|
||||
// MARK: - vDSP cascade (background-thread Option B, RT-safe)
|
||||
|
||||
private var _vdspSetup: OpaquePointer?
|
||||
private var _vdspDelay: [Double]
|
||||
private let _vdspCoeffQueue: SPSCQueue<BiquadCoeffPacket>
|
||||
private let _vdspRespQueue: SPSCQueue<OpaquePointer>
|
||||
private let _vdspKillQueue: SPSCQueue<OpaquePointer>
|
||||
private let _bgDoneSema: DispatchSemaphore
|
||||
private let _bgSleepSema: DispatchSemaphore
|
||||
private var _vdspThread: Thread?
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to filter.
|
||||
/// - freq: Cutoff frequency in Hz. No internal clamping; stay below Nyquist (sampleRate / 2).
|
||||
/// - order: Filter order 1–8 (clamped internally). Each order adds −6 dB/oct slope. Higher order = steeper rolloff but higher CPU cost. Defaults to `4`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public init(
|
||||
input: any ValidGeneratorInput,
|
||||
freq: any ValidGeneratorInput,
|
||||
order: Int,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
let resolvedFreq: any ValidGeneratorInput = freq._resolvedInput()
|
||||
self.inputSource = resolvedInput
|
||||
self.freqInput = resolvedFreq
|
||||
self.freqIsGenerator = resolvedFreq is any Generator
|
||||
let clampedOrder: Int = min(max(order, 1), maxButterworthOrder)
|
||||
self.order = clampedOrder
|
||||
|
||||
let numBiquads: Int = clampedOrder / 2
|
||||
var qs: [Double] = [Double]()
|
||||
if numBiquads > 0 {
|
||||
for k: Int in 1...numBiquads {
|
||||
let angle: Double = Double.pi * Double(2 * k + clampedOrder - 1)
|
||||
/ Double(2 * clampedOrder)
|
||||
qs.append(-1.0 / (2.0 * cos(angle)))
|
||||
}
|
||||
}
|
||||
self.butterworthQs = qs
|
||||
self.biquadStages = [BiquadState](repeating: BiquadState(), count: numBiquads)
|
||||
self.firstOrderState = clampedOrder % 2 == 1 ? FirstOrderState() : nil
|
||||
self._scratch = makeSampleBuffer()
|
||||
self.cachedBiquadCoeffs = [BiquadCoeffs](repeating: .zero, count: numBiquads)
|
||||
|
||||
self._vdspSetup = nil
|
||||
let biquadDelayStateCount: Int = 2 * (numBiquads + 1)
|
||||
self._vdspDelay = numBiquads > 0
|
||||
? [Double](repeating: 0, count: biquadDelayStateCount)
|
||||
: []
|
||||
self._vdspCoeffQueue = SPSCQueue(capacity: butterworthCoeffQueueCapacity)
|
||||
self._vdspRespQueue = SPSCQueue(capacity: butterworthRespQueueCapacity)
|
||||
self._vdspKillQueue = SPSCQueue(capacity: butterworthKillQueueCapacity)
|
||||
self._bgDoneSema = DispatchSemaphore(value: 0)
|
||||
self._bgSleepSema = DispatchSemaphore(value: 0)
|
||||
self._mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
|
||||
if numBiquads > 0 {
|
||||
let cq: SPSCQueue<BiquadCoeffPacket> = _vdspCoeffQueue
|
||||
let rq: SPSCQueue<OpaquePointer> = _vdspRespQueue
|
||||
let kq: SPSCQueue<OpaquePointer> = _vdspKillQueue
|
||||
let doneSema: DispatchSemaphore = _bgDoneSema
|
||||
let sleepSema: DispatchSemaphore = _bgSleepSema
|
||||
let t: Thread = Thread {
|
||||
var shouldStop: Bool = false
|
||||
while !shouldStop {
|
||||
while let ptr: OpaquePointer = kq.dequeue() {
|
||||
vDSP_biquad_DestroySetupD(ptr)
|
||||
}
|
||||
if let packet: BiquadCoeffPacket = cq.dequeue() {
|
||||
packet.withUnsafeCoeffPtr { ptr in
|
||||
if let setup: vDSP_biquad_SetupD = vDSP_biquad_CreateSetupD(
|
||||
ptr, vDSP_Length(packet.numSections)
|
||||
) {
|
||||
if !rq.enqueue(setup) {
|
||||
vDSP_biquad_DestroySetupD(setup)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if sleepSema.wait(timeout: .now() + Audio.bgPollInterval) == .success { shouldStop = true }
|
||||
}
|
||||
while let ptr: OpaquePointer = kq.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
|
||||
while let ptr: OpaquePointer = rq.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
|
||||
doneSema.signal()
|
||||
}
|
||||
t.name = "LyrebirdButterworthHP.vDSP"
|
||||
t.qualityOfService = .userInteractive
|
||||
_vdspThread = t
|
||||
t.start()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Deinit
|
||||
|
||||
deinit {
|
||||
if _vdspThread != nil {
|
||||
_bgSleepSema.signal()
|
||||
_bgDoneSema.wait()
|
||||
}
|
||||
if let setup: OpaquePointer = _vdspSetup {
|
||||
vDSP_biquad_DestroySetupD(setup)
|
||||
}
|
||||
while let ptr: OpaquePointer = _vdspRespQueue.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
|
||||
while let ptr: OpaquePointer = _vdspKillQueue.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
|
||||
}
|
||||
|
||||
// MARK: - Generator protocol
|
||||
// MARK: - Compute
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
guard let inputBlock: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first else {
|
||||
return _result
|
||||
}
|
||||
let sr: Double = graph.engine.sampleRate
|
||||
let hasFO: Bool = firstOrderState != nil
|
||||
let totalStages: Int = biquadStages.count + (hasFO ? 1 : 0)
|
||||
|
||||
guard totalStages > 0 else {
|
||||
let n: Int = min(count, inputBlock.count)
|
||||
inputBlock.withUnsafeBufferPointer { srcBuf in
|
||||
_result[0].withUnsafeMutableBufferPointer { dstBuf in
|
||||
guard let srcBase: UnsafePointer<Double> = srcBuf.baseAddress,
|
||||
let dstBase: UnsafeMutablePointer<Double> = dstBuf.baseAddress else { return }
|
||||
if n > 0 { dstBase.update(from: srcBase, count: n) }
|
||||
if n < count {
|
||||
vDSP_vclrD(dstBase + n, 1, vDSP_Length(count - n))
|
||||
}
|
||||
}
|
||||
}
|
||||
return _result
|
||||
}
|
||||
|
||||
if freqIsGenerator {
|
||||
let freqSamplesOuter: [[Double]] = freqInput.calculatedSamples(graph: graph, count: count)
|
||||
let f0: Double
|
||||
let fN: Double
|
||||
if let freqSamples: [Double] = freqSamplesOuter.first, !freqSamples.isEmpty {
|
||||
f0 = freqSamples[0]
|
||||
fN = freqSamples[min(freqSamples.count - 1, count - 1)]
|
||||
} else {
|
||||
f0 = freqInput.floatValue(graph: graph)
|
||||
fN = f0
|
||||
}
|
||||
runAudioRate(input: inputBlock, f0: f0, fN: fN, sr: sr, N: totalStages, count: count)
|
||||
} else {
|
||||
let freq: Double = freqInput.floatValue(graph: graph)
|
||||
if freq != prevFreq || sr != prevSampleRate {
|
||||
recomputeScalarCoeffs(freq: freq, sr: sr)
|
||||
prevFreq = freq; prevSampleRate = sr
|
||||
if !biquadStages.isEmpty {
|
||||
let packet: BiquadCoeffPacket = BiquadCoeffPacket(from: cachedBiquadCoeffs)
|
||||
if !_vdspCoeffQueue.enqueue(packet) {
|
||||
// Queue full — reset sentinels so next block retries.
|
||||
prevFreq = -1.0; prevSampleRate = -1.0
|
||||
}
|
||||
}
|
||||
}
|
||||
if let newSetup: OpaquePointer = _vdspRespQueue.dequeue() {
|
||||
if let old: OpaquePointer = _vdspSetup {
|
||||
if !_vdspKillQueue.enqueue(old) {
|
||||
// Kill queue full (capacity 32, bg thread drains every 1ms).
|
||||
// Emergency same-thread destroy to prevent leak; violates RT-alloc rule
|
||||
// but is unreachable under normal operation.
|
||||
vDSP_biquad_DestroySetupD(old)
|
||||
}
|
||||
}
|
||||
_vdspSetup = newSetup
|
||||
}
|
||||
if let setup: OpaquePointer = _vdspSetup {
|
||||
runVDSP(input: inputBlock, count: count, setup: setup)
|
||||
} else {
|
||||
runScalar(input: inputBlock, N: totalStages, count: count)
|
||||
}
|
||||
}
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
// MARK: - Coefficient computation
|
||||
|
||||
private func recomputeScalarCoeffs(
|
||||
freq: Double,
|
||||
sr: Double
|
||||
) {
|
||||
if firstOrderState != nil {
|
||||
cachedFO = foHPCoeffs(freq: freq, sr: sr)
|
||||
}
|
||||
for i: Int in 0..<biquadStages.count {
|
||||
cachedBiquadCoeffs[i] = rbjHighPassCoeffs(freq: freq, q: butterworthQs[i], sampleRate: sr)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - vDSP cascade path
|
||||
|
||||
private func runVDSP(
|
||||
input: [Double],
|
||||
count: Int,
|
||||
setup: OpaquePointer
|
||||
) {
|
||||
if var fo: FirstOrderState = firstOrderState {
|
||||
fo.processBlock(input: input,
|
||||
b0: cachedFO.b0, b1: cachedFO.b1, na1: cachedFO.na1,
|
||||
into: &_scratch, count: count)
|
||||
firstOrderState = fo
|
||||
_scratch.withUnsafeBufferPointer { inBuf in
|
||||
_result[0].withUnsafeMutableBufferPointer { outBuf in
|
||||
_vdspDelay.withUnsafeMutableBufferPointer { delay in
|
||||
guard let d: UnsafeMutablePointer<Double> = delay.baseAddress, let i: UnsafePointer<Double> = inBuf.baseAddress,
|
||||
let o: UnsafeMutablePointer<Double> = outBuf.baseAddress else { return }
|
||||
vDSP_biquadD(setup, d, i, 1, o, 1, vDSP_Length(count))
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
input.withUnsafeBufferPointer { inBuf in
|
||||
_result[0].withUnsafeMutableBufferPointer { outBuf in
|
||||
_vdspDelay.withUnsafeMutableBufferPointer { delay in
|
||||
guard let d: UnsafeMutablePointer<Double> = delay.baseAddress, let i: UnsafePointer<Double> = inBuf.baseAddress,
|
||||
let o: UnsafeMutablePointer<Double> = outBuf.baseAddress else { return }
|
||||
vDSP_biquadD(setup, d, i, 1, o, 1, vDSP_Length(count))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Scalar cascade path
|
||||
|
||||
private func runScalar(
|
||||
input: [Double],
|
||||
N: Int,
|
||||
count: Int
|
||||
) {
|
||||
var si: Int = 0
|
||||
if var fo: FirstOrderState = firstOrderState {
|
||||
let writesResult: Bool = (N + 0) % 2 == 1
|
||||
if writesResult {
|
||||
fo.processBlock(input: input,
|
||||
b0: cachedFO.b0, b1: cachedFO.b1, na1: cachedFO.na1,
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
fo.processBlock(input: input,
|
||||
b0: cachedFO.b0, b1: cachedFO.b1, na1: cachedFO.na1,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
firstOrderState = fo
|
||||
si = 1
|
||||
}
|
||||
for bi: Int in 0..<biquadStages.count {
|
||||
let i: Int = si + bi
|
||||
let writesResult: Bool = (N + i) % 2 == 1
|
||||
let readsResult: Bool = i > 0 && (N + i) % 2 == 0
|
||||
if writesResult {
|
||||
if i == 0 {
|
||||
biquadStages[bi].processBlock(input: input, coeffs: cachedBiquadCoeffs[bi],
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
biquadStages[bi].processBlock(input: _scratch, coeffs: cachedBiquadCoeffs[bi],
|
||||
into: &_result[0], count: count)
|
||||
}
|
||||
} else {
|
||||
if readsResult {
|
||||
biquadStages[bi].processBlock(input: _result[0], coeffs: cachedBiquadCoeffs[bi],
|
||||
into: &_scratch, count: count)
|
||||
} else {
|
||||
biquadStages[bi].processBlock(input: input, coeffs: cachedBiquadCoeffs[bi],
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func runAudioRate(
|
||||
input: [Double],
|
||||
f0: Double,
|
||||
fN: Double,
|
||||
sr: Double,
|
||||
N: Int,
|
||||
count: Int
|
||||
) {
|
||||
var si: Int = 0
|
||||
if var fo: FirstOrderState = firstOrderState {
|
||||
let s: (b0: Double, b1: Double, na1: Double) = foHPCoeffs(freq: f0, sr: sr)
|
||||
let e: (b0: Double, b1: Double, na1: Double) = foHPCoeffs(freq: fN, sr: sr)
|
||||
let writesResult: Bool = (N + 0) % 2 == 1
|
||||
if writesResult {
|
||||
fo.processBlock(input: input,
|
||||
startB0: s.b0, startB1: s.b1, startNa1: s.na1,
|
||||
endB0: e.b0, endB1: e.b1, endNa1: e.na1,
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
fo.processBlock(input: input,
|
||||
startB0: s.b0, startB1: s.b1, startNa1: s.na1,
|
||||
endB0: e.b0, endB1: e.b1, endNa1: e.na1,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
firstOrderState = fo
|
||||
si = 1
|
||||
}
|
||||
for bi: Int in 0..<biquadStages.count {
|
||||
let i: Int = si + bi
|
||||
let writesResult: Bool = (N + i) % 2 == 1
|
||||
let readsResult: Bool = i > 0 && (N + i) % 2 == 0
|
||||
let startC: BiquadCoeffs = rbjHighPassCoeffs(freq: f0, q: butterworthQs[bi], sampleRate: sr)
|
||||
let endC: BiquadCoeffs = rbjHighPassCoeffs(freq: fN, q: butterworthQs[bi], sampleRate: sr)
|
||||
if writesResult {
|
||||
if i == 0 {
|
||||
biquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
biquadStages[bi].processBlock(input: _scratch, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_result[0], count: count)
|
||||
}
|
||||
} else {
|
||||
if readsResult {
|
||||
biquadStages[bi].processBlock(input: _result[0], startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_scratch, count: count)
|
||||
} else {
|
||||
biquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
}
|
||||
/// - Parameters:
|
||||
/// - input: Signal to filter.
|
||||
/// - freq: Cutoff frequency in Hz. No internal clamping; stay below Nyquist (sampleRate / 2).
|
||||
/// - order: Filter order 1–8 (clamped internally). Each order adds −6 dB/oct slope. Higher order = steeper rolloff but higher CPU cost. Defaults to `4`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public init(
|
||||
input: any ValidGeneratorInput,
|
||||
freq: any ValidGeneratorInput,
|
||||
order: Int,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(
|
||||
input: input,
|
||||
freq: freq,
|
||||
order: order,
|
||||
mul: mul,
|
||||
add: add,
|
||||
foCoeffs: { foHPCoeffs(freq: $0, sr: $1) },
|
||||
biquadCoeffs: { rbjHighPassCoeffs(freq: $0, q: $1, sampleRate: $2) },
|
||||
threadName: "LyrebirdButterworthHP.vDSP"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
} // close enum ButterworthHighPass
|
||||
|
||||
// MARK: - First-order HP coefficient helper
|
||||
|
||||
|
||||
@@ -4,29 +4,14 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import Foundation
|
||||
|
||||
/// Cascaded Butterworth lowpass filter, orders 1–8.
|
||||
///
|
||||
/// Order is fixed at `init`. For even orders the filter is all biquad stages; for odd
|
||||
/// orders a first-order section precedes the biquad cascade. All buffers are pre-allocated —
|
||||
/// no heap allocation occurs on the RT thread.
|
||||
///
|
||||
/// Per-stage Q values are derived at `init` from the Butterworth pole formula:
|
||||
/// ```
|
||||
/// Q_k = −1 / (2 · cos(π · (2k + N − 1) / (2N))) k = 1 … ⌊N/2⌋
|
||||
/// ```
|
||||
/// At block rate the shared `freq` input modulates all stage coefficients simultaneously.
|
||||
/// Audio-rate `freq` uses block-boundary coefficient interpolation independently per stage.
|
||||
///
|
||||
/// ## vDSP acceleration
|
||||
///
|
||||
/// For constant or block-rate `freq` (non-generator), a background thread builds a
|
||||
/// `vDSP_biquad_SetupD` from the current coefficients and delivers it via a lock-free
|
||||
/// `SPSCQueue`. Once the setup arrives the biquad cascade uses `vDSP_biquadD`; the
|
||||
/// first-order section (odd orders) stays scalar. Audio-rate `freq` always uses the
|
||||
/// scalar interpolating path.
|
||||
/// All cascade machinery (per-stage Butterworth Q, scalar / audio-rate-interpolated
|
||||
/// paths, and the background-thread `vDSP_biquad_SetupD` builder) lives in
|
||||
/// `_ButterworthCascadeBase`. This type injects the lowpass coefficient formulas:
|
||||
/// RBJ lowpass per biquad stage, and a bilinear first-order lowpass for odd orders.
|
||||
///
|
||||
/// ## Usage
|
||||
/// ```swift
|
||||
@@ -42,391 +27,34 @@ import Foundation
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public enum ButterworthLowPass {
|
||||
|
||||
public final class Audio: GeneratorBase, AudioGenerator {
|
||||
public final class Audio: _ButterworthCascadeBase {
|
||||
|
||||
private static let bgPollInterval: TimeInterval = 0.001
|
||||
|
||||
private let inputSource: any ValidGeneratorInput
|
||||
private let freqInput: any ValidGeneratorInput
|
||||
private let freqIsGenerator: Bool
|
||||
|
||||
/// Filter order, clamped to `[1, maxButterworthOrder]` at init.
|
||||
public let order: Int
|
||||
|
||||
/// Per-stage Butterworth Q values — `⌊order/2⌋` entries, computed once at init.
|
||||
public let butterworthQs: [Double]
|
||||
|
||||
private var biquadStages: [BiquadState]
|
||||
private var firstOrderState: FirstOrderState?
|
||||
|
||||
private var _scratch: [Double]
|
||||
|
||||
private var cachedBiquadCoeffs: [BiquadCoeffs]
|
||||
private var cachedFO: (b0: Double, b1: Double, na1: Double) = (0, 0, 0)
|
||||
private var prevFreq: Double = -1.0
|
||||
private var prevSampleRate: Double = -1.0
|
||||
private let _mulAdd: MulAddSpec
|
||||
|
||||
// MARK: - vDSP cascade (background-thread Option B, RT-safe)
|
||||
|
||||
// Current live Double biquad setup. nil until background thread delivers first setup.
|
||||
// Only accessed from _computeSamples (RT thread) — no concurrent access.
|
||||
private var _vdspSetup: OpaquePointer?
|
||||
// Delay buffer: 2*(numBiquads+1) Doubles. Pre-allocated; never resized.
|
||||
private var _vdspDelay: [Double]
|
||||
// RT → bg: new coefficient packets to build a setup from.
|
||||
private let _vdspCoeffQueue: SPSCQueue<BiquadCoeffPacket>
|
||||
// bg → RT: newly-built setups ready to swap in.
|
||||
private let _vdspRespQueue: SPSCQueue<OpaquePointer>
|
||||
// RT → bg: old setups to destroy (avoids dealloc on RT thread).
|
||||
private let _vdspKillQueue: SPSCQueue<OpaquePointer>
|
||||
// Signals deinit that the background thread has exited cleanly.
|
||||
private let _bgDoneSema: DispatchSemaphore
|
||||
// Doubles as sleep timer and stop signal: deinit signals it to wake the thread early.
|
||||
// Thread.cancel() / pthread_cancel is NOT used — pthread_cancel kills the thread at
|
||||
// nanosleep (a POSIX cancellation point), bypassing doneSema.signal() and deadlocking
|
||||
// _bgDoneSema.wait() in deinit.
|
||||
private let _bgSleepSema: DispatchSemaphore
|
||||
private var _vdspThread: Thread?
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to filter.
|
||||
/// - freq: Cutoff frequency in Hz. No internal clamping; stay below Nyquist (sampleRate / 2).
|
||||
/// - order: Filter order 1–8 (clamped internally). Each order adds −6 dB/oct slope. Higher order = steeper rolloff but higher CPU cost. Defaults to `4`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public init(
|
||||
input: any ValidGeneratorInput,
|
||||
freq: any ValidGeneratorInput,
|
||||
order: Int,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
let resolvedFreq: any ValidGeneratorInput = freq._resolvedInput()
|
||||
self.inputSource = resolvedInput
|
||||
self.freqInput = resolvedFreq
|
||||
self.freqIsGenerator = resolvedFreq is any Generator
|
||||
let clampedOrder: Int = min(max(order, 1), maxButterworthOrder)
|
||||
self.order = clampedOrder
|
||||
|
||||
let numBiquads: Int = clampedOrder / 2
|
||||
var qs: [Double] = [Double]()
|
||||
if numBiquads > 0 {
|
||||
for k: Int in 1...numBiquads {
|
||||
let angle: Double = Double.pi * Double(2 * k + clampedOrder - 1)
|
||||
/ Double(2 * clampedOrder)
|
||||
qs.append(-1.0 / (2.0 * cos(angle)))
|
||||
}
|
||||
}
|
||||
self.butterworthQs = qs
|
||||
self.biquadStages = [BiquadState](repeating: BiquadState(), count: numBiquads)
|
||||
self.firstOrderState = clampedOrder % 2 == 1 ? FirstOrderState() : nil
|
||||
self._scratch = makeSampleBuffer()
|
||||
self.cachedBiquadCoeffs = [BiquadCoeffs](repeating: .zero, count: numBiquads)
|
||||
|
||||
self._vdspSetup = nil
|
||||
let biquadDelayStateCount: Int = 2 * (numBiquads + 1)
|
||||
self._vdspDelay = numBiquads > 0
|
||||
? [Double](repeating: 0, count: biquadDelayStateCount)
|
||||
: []
|
||||
self._vdspCoeffQueue = SPSCQueue(capacity: butterworthCoeffQueueCapacity)
|
||||
self._vdspRespQueue = SPSCQueue(capacity: butterworthRespQueueCapacity)
|
||||
self._vdspKillQueue = SPSCQueue(capacity: butterworthKillQueueCapacity)
|
||||
self._bgDoneSema = DispatchSemaphore(value: 0)
|
||||
self._bgSleepSema = DispatchSemaphore(value: 0)
|
||||
self._mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
|
||||
// Start background setup thread only when there are biquad sections (order >= 2).
|
||||
if numBiquads > 0 {
|
||||
let cq: SPSCQueue<BiquadCoeffPacket> = _vdspCoeffQueue
|
||||
let rq: SPSCQueue<OpaquePointer> = _vdspRespQueue
|
||||
let kq: SPSCQueue<OpaquePointer> = _vdspKillQueue
|
||||
let doneSema: DispatchSemaphore = _bgDoneSema
|
||||
let sleepSema: DispatchSemaphore = _bgSleepSema
|
||||
let t: Thread = Thread {
|
||||
var shouldStop: Bool = false
|
||||
while !shouldStop {
|
||||
while let ptr: OpaquePointer = kq.dequeue() {
|
||||
vDSP_biquad_DestroySetupD(ptr)
|
||||
}
|
||||
if let packet: BiquadCoeffPacket = cq.dequeue() {
|
||||
packet.withUnsafeCoeffPtr { ptr in
|
||||
if let setup: vDSP_biquad_SetupD = vDSP_biquad_CreateSetupD(
|
||||
ptr, vDSP_Length(packet.numSections)
|
||||
) {
|
||||
if !rq.enqueue(setup) {
|
||||
vDSP_biquad_DestroySetupD(setup)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// .success = woken early by deinit (stop signal); .timedOut = normal poll.
|
||||
if sleepSema.wait(timeout: .now() + Audio.bgPollInterval) == .success { shouldStop = true }
|
||||
}
|
||||
// Drain queues on exit so deinit can safely claim ownership.
|
||||
while let ptr: OpaquePointer = kq.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
|
||||
while let ptr: OpaquePointer = rq.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
|
||||
doneSema.signal()
|
||||
}
|
||||
t.name = "LyrebirdButterworthLP.vDSP"
|
||||
t.qualityOfService = .userInteractive
|
||||
_vdspThread = t
|
||||
t.start()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Deinit
|
||||
|
||||
deinit {
|
||||
if _vdspThread != nil {
|
||||
_bgSleepSema.signal() // wake thread from its 1ms sleep, stop signal
|
||||
_bgDoneSema.wait() // wait for thread to drain queues and exit
|
||||
}
|
||||
if let setup: OpaquePointer = _vdspSetup {
|
||||
vDSP_biquad_DestroySetupD(setup)
|
||||
}
|
||||
// Thread drained these on exit; drain again as safety (no-ops when already empty).
|
||||
while let ptr: OpaquePointer = _vdspRespQueue.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
|
||||
while let ptr: OpaquePointer = _vdspKillQueue.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
|
||||
}
|
||||
|
||||
// MARK: - Generator protocol
|
||||
// MARK: - Compute
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
guard let inputBlock: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first else {
|
||||
return _result
|
||||
}
|
||||
let sr: Double = graph.engine.sampleRate
|
||||
let hasFO: Bool = firstOrderState != nil
|
||||
let totalStages: Int = biquadStages.count + (hasFO ? 1 : 0)
|
||||
|
||||
guard totalStages > 0 else {
|
||||
let n: Int = min(count, inputBlock.count)
|
||||
inputBlock.withUnsafeBufferPointer { srcBuf in
|
||||
_result[0].withUnsafeMutableBufferPointer { dstBuf in
|
||||
guard let srcBase: UnsafePointer<Double> = srcBuf.baseAddress,
|
||||
let dstBase: UnsafeMutablePointer<Double> = dstBuf.baseAddress else { return }
|
||||
if n > 0 { dstBase.update(from: srcBase, count: n) }
|
||||
if n < count {
|
||||
vDSP_vclrD(dstBase + n, 1, vDSP_Length(count - n))
|
||||
}
|
||||
}
|
||||
}
|
||||
return _result
|
||||
}
|
||||
|
||||
if freqIsGenerator {
|
||||
let freqSamplesOuter: [[Double]] = freqInput.calculatedSamples(graph: graph, count: count)
|
||||
let f0: Double
|
||||
let fN: Double
|
||||
if let freqSamples: [Double] = freqSamplesOuter.first, !freqSamples.isEmpty {
|
||||
f0 = freqSamples[0]
|
||||
fN = freqSamples[min(freqSamples.count - 1, count - 1)]
|
||||
} else {
|
||||
f0 = freqInput.floatValue(graph: graph)
|
||||
fN = f0
|
||||
}
|
||||
runAudioRate(input: inputBlock, f0: f0, fN: fN, sr: sr, N: totalStages, count: count)
|
||||
} else {
|
||||
let freq: Double = freqInput.floatValue(graph: graph)
|
||||
if freq != prevFreq || sr != prevSampleRate {
|
||||
recomputeScalarCoeffs(freq: freq, sr: sr)
|
||||
prevFreq = freq; prevSampleRate = sr
|
||||
if !biquadStages.isEmpty {
|
||||
let packet: BiquadCoeffPacket = BiquadCoeffPacket(from: cachedBiquadCoeffs)
|
||||
if !_vdspCoeffQueue.enqueue(packet) {
|
||||
// Queue full — reset sentinels so next block retries.
|
||||
prevFreq = -1.0; prevSampleRate = -1.0
|
||||
}
|
||||
}
|
||||
}
|
||||
// Swap in any new setup the background thread prepared.
|
||||
if let newSetup: OpaquePointer = _vdspRespQueue.dequeue() {
|
||||
if let old: OpaquePointer = _vdspSetup {
|
||||
if !_vdspKillQueue.enqueue(old) {
|
||||
// Kill queue full (capacity 32, bg thread drains every 1ms).
|
||||
// Emergency same-thread destroy to prevent leak; violates RT-alloc rule
|
||||
// but is unreachable under normal operation.
|
||||
vDSP_biquad_DestroySetupD(old)
|
||||
}
|
||||
}
|
||||
_vdspSetup = newSetup
|
||||
}
|
||||
if let setup: OpaquePointer = _vdspSetup {
|
||||
runVDSP(input: inputBlock, count: count, setup: setup)
|
||||
} else {
|
||||
runScalar(input: inputBlock, N: totalStages, count: count)
|
||||
}
|
||||
}
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
// MARK: - Coefficient computation
|
||||
|
||||
private func recomputeScalarCoeffs(
|
||||
freq: Double,
|
||||
sr: Double
|
||||
) {
|
||||
if firstOrderState != nil {
|
||||
cachedFO = foLPCoeffs(freq: freq, sr: sr)
|
||||
}
|
||||
for i: Int in 0..<biquadStages.count {
|
||||
cachedBiquadCoeffs[i] = rbjLowPassCoeffs(freq: freq, q: butterworthQs[i], sampleRate: sr)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - vDSP cascade path
|
||||
|
||||
/// Runs the biquad cascade via `vDSP_biquadD`. For odd orders, the first-order section
|
||||
/// runs scalar first (into `_scratch`); the biquad cascade then reads from `_scratch`.
|
||||
private func runVDSP(
|
||||
input: [Double],
|
||||
count: Int,
|
||||
setup: OpaquePointer
|
||||
) {
|
||||
if var fo: FirstOrderState = firstOrderState {
|
||||
fo.processBlock(input: input,
|
||||
b0: cachedFO.b0, b1: cachedFO.b1, na1: cachedFO.na1,
|
||||
into: &_scratch, count: count)
|
||||
firstOrderState = fo
|
||||
_scratch.withUnsafeBufferPointer { inBuf in
|
||||
_result[0].withUnsafeMutableBufferPointer { outBuf in
|
||||
_vdspDelay.withUnsafeMutableBufferPointer { delay in
|
||||
guard let d: UnsafeMutablePointer<Double> = delay.baseAddress, let i: UnsafePointer<Double> = inBuf.baseAddress,
|
||||
let o: UnsafeMutablePointer<Double> = outBuf.baseAddress else { return }
|
||||
vDSP_biquadD(setup, d, i, 1, o, 1, vDSP_Length(count))
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
input.withUnsafeBufferPointer { inBuf in
|
||||
_result[0].withUnsafeMutableBufferPointer { outBuf in
|
||||
_vdspDelay.withUnsafeMutableBufferPointer { delay in
|
||||
guard let d: UnsafeMutablePointer<Double> = delay.baseAddress, let i: UnsafePointer<Double> = inBuf.baseAddress,
|
||||
let o: UnsafeMutablePointer<Double> = outBuf.baseAddress else { return }
|
||||
vDSP_biquadD(setup, d, i, 1, o, 1, vDSP_Length(count))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Scalar cascade path
|
||||
|
||||
/// Buffer routing rule: stage `i` of `N` total writes to `_result[0]` when
|
||||
/// `(N + i) % 2 == 1`, otherwise writes to `_scratch`.
|
||||
/// When `i > 0` and writes to `_result[0]`, it reads from `_scratch` and vice versa.
|
||||
|
||||
private func runScalar(
|
||||
input: [Double],
|
||||
N: Int,
|
||||
count: Int
|
||||
) {
|
||||
var si: Int = 0
|
||||
if var fo: FirstOrderState = firstOrderState {
|
||||
let writesResult: Bool = (N + 0) % 2 == 1
|
||||
if writesResult {
|
||||
fo.processBlock(input: input,
|
||||
b0: cachedFO.b0, b1: cachedFO.b1, na1: cachedFO.na1,
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
fo.processBlock(input: input,
|
||||
b0: cachedFO.b0, b1: cachedFO.b1, na1: cachedFO.na1,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
firstOrderState = fo
|
||||
si = 1
|
||||
}
|
||||
for bi: Int in 0..<biquadStages.count {
|
||||
let i: Int = si + bi
|
||||
let writesResult: Bool = (N + i) % 2 == 1
|
||||
let readsResult: Bool = i > 0 && (N + i) % 2 == 0
|
||||
if writesResult {
|
||||
if i == 0 {
|
||||
biquadStages[bi].processBlock(input: input, coeffs: cachedBiquadCoeffs[bi],
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
biquadStages[bi].processBlock(input: _scratch, coeffs: cachedBiquadCoeffs[bi],
|
||||
into: &_result[0], count: count)
|
||||
}
|
||||
} else {
|
||||
if readsResult {
|
||||
biquadStages[bi].processBlock(input: _result[0], coeffs: cachedBiquadCoeffs[bi],
|
||||
into: &_scratch, count: count)
|
||||
} else {
|
||||
biquadStages[bi].processBlock(input: input, coeffs: cachedBiquadCoeffs[bi],
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func runAudioRate(
|
||||
input: [Double],
|
||||
f0: Double,
|
||||
fN: Double,
|
||||
sr: Double,
|
||||
N: Int,
|
||||
count: Int
|
||||
) {
|
||||
var si: Int = 0
|
||||
if var fo: FirstOrderState = firstOrderState {
|
||||
let s: (b0: Double, b1: Double, na1: Double) = foLPCoeffs(freq: f0, sr: sr)
|
||||
let e: (b0: Double, b1: Double, na1: Double) = foLPCoeffs(freq: fN, sr: sr)
|
||||
let writesResult: Bool = (N + 0) % 2 == 1
|
||||
if writesResult {
|
||||
fo.processBlock(input: input,
|
||||
startB0: s.b0, startB1: s.b1, startNa1: s.na1,
|
||||
endB0: e.b0, endB1: e.b1, endNa1: e.na1,
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
fo.processBlock(input: input,
|
||||
startB0: s.b0, startB1: s.b1, startNa1: s.na1,
|
||||
endB0: e.b0, endB1: e.b1, endNa1: e.na1,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
firstOrderState = fo
|
||||
si = 1
|
||||
}
|
||||
for bi: Int in 0..<biquadStages.count {
|
||||
let i: Int = si + bi
|
||||
let writesResult: Bool = (N + i) % 2 == 1
|
||||
let readsResult: Bool = i > 0 && (N + i) % 2 == 0
|
||||
let startC: BiquadCoeffs = rbjLowPassCoeffs(freq: f0, q: butterworthQs[bi], sampleRate: sr)
|
||||
let endC: BiquadCoeffs = rbjLowPassCoeffs(freq: fN, q: butterworthQs[bi], sampleRate: sr)
|
||||
if writesResult {
|
||||
if i == 0 {
|
||||
biquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_result[0], count: count)
|
||||
} else {
|
||||
biquadStages[bi].processBlock(input: _scratch, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_result[0], count: count)
|
||||
}
|
||||
} else {
|
||||
if readsResult {
|
||||
biquadStages[bi].processBlock(input: _result[0], startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_scratch, count: count)
|
||||
} else {
|
||||
biquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &_scratch, count: count)
|
||||
}
|
||||
}
|
||||
/// - Parameters:
|
||||
/// - input: Signal to filter.
|
||||
/// - freq: Cutoff frequency in Hz. No internal clamping; stay below Nyquist (sampleRate / 2).
|
||||
/// - order: Filter order 1–8 (clamped internally). Each order adds −6 dB/oct slope. Higher order = steeper rolloff but higher CPU cost. Defaults to `4`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public init(
|
||||
input: any ValidGeneratorInput,
|
||||
freq: any ValidGeneratorInput,
|
||||
order: Int,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(
|
||||
input: input,
|
||||
freq: freq,
|
||||
order: order,
|
||||
mul: mul,
|
||||
add: add,
|
||||
foCoeffs: { foLPCoeffs(freq: $0, sr: $1) },
|
||||
biquadCoeffs: { rbjLowPassCoeffs(freq: $0, q: $1, sampleRate: $2) },
|
||||
threadName: "LyrebirdButterworthLP.vDSP"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
} // close enum ButterworthLowPass
|
||||
|
||||
// MARK: - First-order LP coefficient helper
|
||||
|
||||
|
||||
@@ -0,0 +1,409 @@
|
||||
// ButterworthSectionEngine.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import Foundation
|
||||
|
||||
/// Internal cascade engine for a single Butterworth LP or HP section.
|
||||
///
|
||||
/// Encapsulates all single-cascade machinery: biquad stages, optional first-order
|
||||
/// state, cached coefficients, scratch buffer, and the background-thread
|
||||
/// `vDSP_biquad_SetupD` builder (SPSC queues + semaphore deinit handshake).
|
||||
/// Coefficient formulas are injected via two stored closures and a thread name.
|
||||
///
|
||||
/// This class is NOT a `Generator`. It is a shared computation engine owned by
|
||||
/// `_ButterworthCascadeBase` (one engine, LP/HP), `ButterworthBandPass.Audio`
|
||||
/// (two engines in series), and `ButterworthBandReject.Audio` (two engines in
|
||||
/// parallel, summed). All buffer writes go into the caller-supplied `output`
|
||||
/// inout slice — no internal `_result` allocation.
|
||||
///
|
||||
/// Order is fixed at `init`. For even orders the filter is all biquad stages;
|
||||
/// for odd orders a first-order section precedes the biquad cascade. All buffers
|
||||
/// are pre-allocated — no heap allocation occurs on the RT thread.
|
||||
///
|
||||
/// ## vDSP acceleration
|
||||
/// For constant or block-rate `freq` (non-generator), a background thread builds
|
||||
/// a `vDSP_biquad_SetupD` from the current coefficients and delivers it via a
|
||||
/// lock-free `SPSCQueue`. Once the setup arrives the biquad cascade uses
|
||||
/// `vDSP_biquadD`; the first-order section (odd orders) stays scalar. Audio-rate
|
||||
/// `freq` always uses the scalar interpolating path.
|
||||
final class ButterworthSectionEngine {
|
||||
|
||||
private static let bgPollInterval: TimeInterval = 0.001
|
||||
|
||||
/// Filter order, clamped to `[1, maxButterworthOrder]` at init.
|
||||
let order: Int
|
||||
|
||||
/// Per-stage Butterworth Q values — `⌊order/2⌋` entries, computed once at init.
|
||||
let butterworthQs: [Double]
|
||||
|
||||
private var biquadStages: [BiquadState]
|
||||
private var firstOrderState: FirstOrderState?
|
||||
|
||||
private var scratch: [Double]
|
||||
|
||||
private var cachedBiquadCoeffs: [BiquadCoeffs]
|
||||
private var cachedFO: (b0: Double, b1: Double, na1: Double) = (0, 0, 0)
|
||||
private var prevFreq: Double = -1.0
|
||||
private var prevSampleRate: Double = -1.0
|
||||
|
||||
/// First-order section coefficients for a cutoff `freq` at sample rate `sr`.
|
||||
private let foCoeffs: (Double, Double) -> (b0: Double, b1: Double, na1: Double)
|
||||
/// Biquad-stage coefficients for `(freq, q, sampleRate)`.
|
||||
private let biquadCoeffsFunc: (Double, Double, Double) -> BiquadCoeffs
|
||||
|
||||
// MARK: - vDSP cascade (background-thread RT-safe)
|
||||
|
||||
// Current live Double biquad setup. nil until background thread delivers first setup.
|
||||
// Only accessed from process(...) (RT thread) — no concurrent access.
|
||||
private var vdspSetup: OpaquePointer?
|
||||
// Delay buffer: 2*(numBiquads+1) Doubles. Pre-allocated; never resized.
|
||||
private var vdspDelay: [Double]
|
||||
// RT → bg: new coefficient packets to build a setup from.
|
||||
private let vdspCoeffQueue: SPSCQueue<BiquadCoeffPacket>
|
||||
// bg → RT: newly-built setups ready to swap in.
|
||||
private let vdspRespQueue: SPSCQueue<OpaquePointer>
|
||||
// RT → bg: old setups to destroy (avoids dealloc on RT thread).
|
||||
private let vdspKillQueue: SPSCQueue<OpaquePointer>
|
||||
// Signals deinit that the background thread has exited cleanly.
|
||||
private let bgDoneSema: DispatchSemaphore
|
||||
// Doubles as sleep timer and stop signal: deinit signals it to wake the thread early.
|
||||
// Thread.cancel() / pthread_cancel is NOT used — pthread_cancel kills the thread at
|
||||
// nanosleep (a POSIX cancellation point), bypassing doneSema.signal() and deadlocking
|
||||
// bgDoneSema.wait() in deinit.
|
||||
private let bgSleepSema: DispatchSemaphore
|
||||
private var vdspThread: Thread?
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a single-cascade Butterworth section engine.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - order: Filter order 1–8 (clamped internally).
|
||||
/// - foCoeffs: First-order section coefficient formula `(freq, sr) -> (b0, b1, na1)`.
|
||||
/// - biquadCoeffs: Biquad-stage coefficient formula `(freq, q, sampleRate) -> BiquadCoeffs`.
|
||||
/// - threadName: Name for the background vDSP setup-builder thread.
|
||||
init(
|
||||
order: Int,
|
||||
foCoeffs: @escaping (Double, Double) -> (b0: Double, b1: Double, na1: Double),
|
||||
biquadCoeffs: @escaping (Double, Double, Double) -> BiquadCoeffs,
|
||||
threadName: String
|
||||
) {
|
||||
let clampedOrder: Int = min(max(order, 1), maxButterworthOrder)
|
||||
self.order = clampedOrder
|
||||
self.foCoeffs = foCoeffs
|
||||
self.biquadCoeffsFunc = biquadCoeffs
|
||||
|
||||
let numBiquads: Int = clampedOrder / 2
|
||||
self.butterworthQs = computeButterworthQs(order: clampedOrder)
|
||||
self.biquadStages = [BiquadState](repeating: BiquadState(), count: numBiquads)
|
||||
self.firstOrderState = clampedOrder % 2 == 1 ? FirstOrderState() : nil
|
||||
self.scratch = makeSampleBuffer()
|
||||
self.cachedBiquadCoeffs = [BiquadCoeffs](repeating: .zero, count: numBiquads)
|
||||
|
||||
self.vdspSetup = nil
|
||||
let biquadDelayStateCount: Int = 2 * (numBiquads + 1)
|
||||
self.vdspDelay = numBiquads > 0
|
||||
? [Double](repeating: 0, count: biquadDelayStateCount)
|
||||
: []
|
||||
self.vdspCoeffQueue = SPSCQueue(capacity: butterworthCoeffQueueCapacity)
|
||||
self.vdspRespQueue = SPSCQueue(capacity: butterworthRespQueueCapacity)
|
||||
self.vdspKillQueue = SPSCQueue(capacity: butterworthKillQueueCapacity)
|
||||
self.bgDoneSema = DispatchSemaphore(value: 0)
|
||||
self.bgSleepSema = DispatchSemaphore(value: 0)
|
||||
|
||||
// Start background setup thread only when there are biquad sections (order >= 2).
|
||||
if numBiquads > 0 {
|
||||
let cq: SPSCQueue<BiquadCoeffPacket> = vdspCoeffQueue
|
||||
let rq: SPSCQueue<OpaquePointer> = vdspRespQueue
|
||||
let kq: SPSCQueue<OpaquePointer> = vdspKillQueue
|
||||
let doneSema: DispatchSemaphore = bgDoneSema
|
||||
let sleepSema: DispatchSemaphore = bgSleepSema
|
||||
let pollInterval: TimeInterval = ButterworthSectionEngine.bgPollInterval
|
||||
let t: Thread = Thread {
|
||||
var shouldStop: Bool = false
|
||||
while !shouldStop {
|
||||
while let ptr: OpaquePointer = kq.dequeue() {
|
||||
vDSP_biquad_DestroySetupD(ptr)
|
||||
}
|
||||
if let packet: BiquadCoeffPacket = cq.dequeue() {
|
||||
packet.withUnsafeCoeffPtr { ptr in
|
||||
if let setup: vDSP_biquad_SetupD = vDSP_biquad_CreateSetupD(
|
||||
ptr, vDSP_Length(packet.numSections)
|
||||
) {
|
||||
if !rq.enqueue(setup) {
|
||||
vDSP_biquad_DestroySetupD(setup)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// .success = woken early by deinit (stop signal); .timedOut = normal poll.
|
||||
if sleepSema.wait(timeout: .now() + pollInterval) == .success { shouldStop = true }
|
||||
}
|
||||
// Drain queues on exit so deinit can safely claim ownership.
|
||||
while let ptr: OpaquePointer = kq.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
|
||||
while let ptr: OpaquePointer = rq.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
|
||||
doneSema.signal()
|
||||
}
|
||||
t.name = threadName
|
||||
t.qualityOfService = .userInteractive
|
||||
vdspThread = t
|
||||
t.start()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Deinit
|
||||
|
||||
deinit {
|
||||
if vdspThread != nil {
|
||||
bgSleepSema.signal() // wake thread from its 1ms sleep, stop signal
|
||||
bgDoneSema.wait() // wait for thread to drain queues and exit
|
||||
}
|
||||
if let setup: OpaquePointer = vdspSetup {
|
||||
vDSP_biquad_DestroySetupD(setup)
|
||||
}
|
||||
// Thread drained these on exit; drain again as safety (no-ops when already empty).
|
||||
while let ptr: OpaquePointer = vdspRespQueue.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
|
||||
while let ptr: OpaquePointer = vdspKillQueue.dequeue() { vDSP_biquad_DestroySetupD(ptr) }
|
||||
}
|
||||
|
||||
// MARK: - Process
|
||||
|
||||
/// Runs one block of the cascade, writing results into `output`.
|
||||
///
|
||||
/// This method is the RT-safe per-block entry point. It selects the correct
|
||||
/// path (vDSP accelerated, scalar, or audio-rate interpolated) based on
|
||||
/// `freqIsGenerator` and the current coefficient cache state.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Input sample block. Must have at least `count` elements.
|
||||
/// - freqIsGenerator: `true` when `freq` was classified as a `Generator` at init time.
|
||||
/// - scalarFreq: Scalar frequency value (used when `freqIsGenerator == false`).
|
||||
/// - f0: Frequency at the start of this block (used when `freqIsGenerator == true`).
|
||||
/// - fN: Frequency at the end of this block (used when `freqIsGenerator == true`).
|
||||
/// - sr: Current sample rate in Hz.
|
||||
/// - count: Number of samples to process.
|
||||
/// - output: Destination buffer. Must have at least `count` writable elements.
|
||||
func process(
|
||||
input: [Double],
|
||||
freqIsGenerator: Bool,
|
||||
scalarFreq: Double,
|
||||
f0: Double,
|
||||
fN: Double,
|
||||
sr: Double,
|
||||
count: Int,
|
||||
into output: inout [Double]
|
||||
) {
|
||||
let hasFO: Bool = firstOrderState != nil
|
||||
let totalStages: Int = biquadStages.count + (hasFO ? 1 : 0)
|
||||
|
||||
guard totalStages > 0 else {
|
||||
let n: Int = min(count, input.count)
|
||||
input.withUnsafeBufferPointer { srcBuf in
|
||||
output.withUnsafeMutableBufferPointer { dstBuf in
|
||||
guard let srcBase: UnsafePointer<Double> = srcBuf.baseAddress,
|
||||
let dstBase: UnsafeMutablePointer<Double> = dstBuf.baseAddress else { return }
|
||||
if n > 0 { dstBase.update(from: srcBase, count: n) }
|
||||
if n < count {
|
||||
vDSP_vclrD(dstBase + n, 1, vDSP_Length(count - n))
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if freqIsGenerator {
|
||||
runAudioRate(input: input, f0: f0, fN: fN, sr: sr, N: totalStages,
|
||||
count: count, into: &output)
|
||||
} else {
|
||||
if scalarFreq != prevFreq || sr != prevSampleRate {
|
||||
recomputeScalarCoeffs(freq: scalarFreq, sr: sr)
|
||||
prevFreq = scalarFreq; prevSampleRate = sr
|
||||
if !biquadStages.isEmpty {
|
||||
let packet: BiquadCoeffPacket = BiquadCoeffPacket(from: cachedBiquadCoeffs)
|
||||
if !vdspCoeffQueue.enqueue(packet) {
|
||||
// Queue full — reset sentinels so next block retries.
|
||||
prevFreq = -1.0; prevSampleRate = -1.0
|
||||
}
|
||||
}
|
||||
}
|
||||
// Swap in any new setup the background thread prepared.
|
||||
if let newSetup: OpaquePointer = vdspRespQueue.dequeue() {
|
||||
if let old: OpaquePointer = vdspSetup {
|
||||
if !vdspKillQueue.enqueue(old) {
|
||||
// Kill queue full (capacity 32, bg thread drains every 1ms).
|
||||
// Emergency same-thread destroy to prevent leak; violates RT-alloc rule
|
||||
// but is unreachable under normal operation.
|
||||
vDSP_biquad_DestroySetupD(old)
|
||||
}
|
||||
}
|
||||
vdspSetup = newSetup
|
||||
}
|
||||
if let setup: OpaquePointer = vdspSetup {
|
||||
runVDSP(input: input, count: count, setup: setup, into: &output)
|
||||
} else {
|
||||
runScalar(input: input, N: totalStages, count: count, into: &output)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Coefficient computation
|
||||
|
||||
private func recomputeScalarCoeffs(
|
||||
freq: Double,
|
||||
sr: Double
|
||||
) {
|
||||
if firstOrderState != nil {
|
||||
cachedFO = foCoeffs(freq, sr)
|
||||
}
|
||||
for i: Int in 0..<biquadStages.count {
|
||||
cachedBiquadCoeffs[i] = biquadCoeffsFunc(freq, butterworthQs[i], sr)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - vDSP cascade path
|
||||
|
||||
/// Runs the biquad cascade via `vDSP_biquadD`. For odd orders, the first-order section
|
||||
/// runs scalar first (into `scratch`); the biquad cascade then reads from `scratch`.
|
||||
private func runVDSP(
|
||||
input: [Double],
|
||||
count: Int,
|
||||
setup: OpaquePointer,
|
||||
into output: inout [Double]
|
||||
) {
|
||||
if var fo: FirstOrderState = firstOrderState {
|
||||
fo.processBlock(input: input,
|
||||
b0: cachedFO.b0, b1: cachedFO.b1, na1: cachedFO.na1,
|
||||
into: &scratch, count: count)
|
||||
firstOrderState = fo
|
||||
scratch.withUnsafeBufferPointer { inBuf in
|
||||
output.withUnsafeMutableBufferPointer { outBuf in
|
||||
vdspDelay.withUnsafeMutableBufferPointer { delay in
|
||||
guard let d: UnsafeMutablePointer<Double> = delay.baseAddress,
|
||||
let i: UnsafePointer<Double> = inBuf.baseAddress,
|
||||
let o: UnsafeMutablePointer<Double> = outBuf.baseAddress else { return }
|
||||
vDSP_biquadD(setup, d, i, 1, o, 1, vDSP_Length(count))
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
input.withUnsafeBufferPointer { inBuf in
|
||||
output.withUnsafeMutableBufferPointer { outBuf in
|
||||
vdspDelay.withUnsafeMutableBufferPointer { delay in
|
||||
guard let d: UnsafeMutablePointer<Double> = delay.baseAddress,
|
||||
let i: UnsafePointer<Double> = inBuf.baseAddress,
|
||||
let o: UnsafeMutablePointer<Double> = outBuf.baseAddress else { return }
|
||||
vDSP_biquadD(setup, d, i, 1, o, 1, vDSP_Length(count))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Scalar cascade path
|
||||
|
||||
/// Buffer routing rule: stage `i` of `N` total writes to `output` when
|
||||
/// `(N + i) % 2 == 1`, otherwise writes to `scratch`.
|
||||
/// When `i > 0` and writes to `output`, it reads from `scratch` and vice versa.
|
||||
private func runScalar(
|
||||
input: [Double],
|
||||
N: Int,
|
||||
count: Int,
|
||||
into output: inout [Double]
|
||||
) {
|
||||
var si: Int = 0
|
||||
if var fo: FirstOrderState = firstOrderState {
|
||||
let writesResult: Bool = (N + 0) % 2 == 1
|
||||
if writesResult {
|
||||
fo.processBlock(input: input,
|
||||
b0: cachedFO.b0, b1: cachedFO.b1, na1: cachedFO.na1,
|
||||
into: &output, count: count)
|
||||
} else {
|
||||
fo.processBlock(input: input,
|
||||
b0: cachedFO.b0, b1: cachedFO.b1, na1: cachedFO.na1,
|
||||
into: &scratch, count: count)
|
||||
}
|
||||
firstOrderState = fo
|
||||
si = 1
|
||||
}
|
||||
for bi: Int in 0..<biquadStages.count {
|
||||
let i: Int = si + bi
|
||||
let writesResult: Bool = (N + i) % 2 == 1
|
||||
let readsResult: Bool = i > 0 && (N + i) % 2 == 0
|
||||
if writesResult {
|
||||
if i == 0 {
|
||||
biquadStages[bi].processBlock(input: input, coeffs: cachedBiquadCoeffs[bi],
|
||||
into: &output, count: count)
|
||||
} else {
|
||||
biquadStages[bi].processBlock(input: scratch, coeffs: cachedBiquadCoeffs[bi],
|
||||
into: &output, count: count)
|
||||
}
|
||||
} else {
|
||||
if readsResult {
|
||||
biquadStages[bi].processBlock(input: output, coeffs: cachedBiquadCoeffs[bi],
|
||||
into: &scratch, count: count)
|
||||
} else {
|
||||
biquadStages[bi].processBlock(input: input, coeffs: cachedBiquadCoeffs[bi],
|
||||
into: &scratch, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func runAudioRate(
|
||||
input: [Double],
|
||||
f0: Double,
|
||||
fN: Double,
|
||||
sr: Double,
|
||||
N: Int,
|
||||
count: Int,
|
||||
into output: inout [Double]
|
||||
) {
|
||||
var si: Int = 0
|
||||
if var fo: FirstOrderState = firstOrderState {
|
||||
let s: (b0: Double, b1: Double, na1: Double) = foCoeffs(f0, sr)
|
||||
let e: (b0: Double, b1: Double, na1: Double) = foCoeffs(fN, sr)
|
||||
let writesResult: Bool = (N + 0) % 2 == 1
|
||||
if writesResult {
|
||||
fo.processBlock(input: input,
|
||||
startB0: s.b0, startB1: s.b1, startNa1: s.na1,
|
||||
endB0: e.b0, endB1: e.b1, endNa1: e.na1,
|
||||
into: &output, count: count)
|
||||
} else {
|
||||
fo.processBlock(input: input,
|
||||
startB0: s.b0, startB1: s.b1, startNa1: s.na1,
|
||||
endB0: e.b0, endB1: e.b1, endNa1: e.na1,
|
||||
into: &scratch, count: count)
|
||||
}
|
||||
firstOrderState = fo
|
||||
si = 1
|
||||
}
|
||||
for bi: Int in 0..<biquadStages.count {
|
||||
let i: Int = si + bi
|
||||
let writesResult: Bool = (N + i) % 2 == 1
|
||||
let readsResult: Bool = i > 0 && (N + i) % 2 == 0
|
||||
let startC: BiquadCoeffs = biquadCoeffsFunc(f0, butterworthQs[bi], sr)
|
||||
let endC: BiquadCoeffs = biquadCoeffsFunc(fN, butterworthQs[bi], sr)
|
||||
if writesResult {
|
||||
if i == 0 {
|
||||
biquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &output, count: count)
|
||||
} else {
|
||||
biquadStages[bi].processBlock(input: scratch, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &output, count: count)
|
||||
}
|
||||
} else {
|
||||
if readsResult {
|
||||
biquadStages[bi].processBlock(input: output, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &scratch, count: count)
|
||||
} else {
|
||||
biquadStages[bi].processBlock(input: input, startCoeffs: startC, endCoeffs: endC,
|
||||
into: &scratch, count: count)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -81,7 +81,7 @@ public final class CombFilter: GeneratorBase, AudioGenerator {
|
||||
self.interpolation = interpolation
|
||||
|
||||
let maxSamples: Int = Int(ceil(maxDelay * sampleRate)) + 1
|
||||
let bufSize: Int = Self.nextPowerOf2(max(maxSamples, 2))
|
||||
let bufSize: Int = lyrebirdNextPowerOfTwo(max(maxSamples, 2))
|
||||
self.buffer = [Double](repeating: 0, count: bufSize)
|
||||
self.bufferMask = bufSize - 1
|
||||
self.maxDelaySamples = maxSamples - 1
|
||||
@@ -231,13 +231,6 @@ public final class CombFilter: GeneratorBase, AudioGenerator {
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
private static func nextPowerOf2(_ n: Int) -> Int {
|
||||
guard n > 1 else { return 1 }
|
||||
var r: Int = 1
|
||||
while r < n { r <<= 1 }
|
||||
return r
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Catmull-Rom cubic interpolation (local copy, avoids cross-file dependency)
|
||||
|
||||
@@ -4,8 +4,6 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Darwin
|
||||
|
||||
/// Butterworth Q (1/√2) — maximally flat magnitude response, no resonant peak. Default for SVF.
|
||||
public let svfButterworthQ: Double = 0.7071067811865475 // 1.0 / sqrt(2.0)
|
||||
|
||||
@@ -153,74 +151,21 @@ public enum SVF {
|
||||
let scalarQ: Double = qSamples == nil ? qInput.floatValue(graph: graph) : 0.0
|
||||
|
||||
let piOverSr: Double = Double.pi / sampleRate // π/sr; freq coeff = 2·sin(π·f/sr)
|
||||
let minQDamping: Double = 0.0001 // prevents 1/q divide-by-zero
|
||||
let fCoeffMax: Double = 1.0 // stability bound for Chamberlin SVF
|
||||
|
||||
// Pre-compute scalar coefficients when inputs are not generators.
|
||||
let scalarF: Double
|
||||
let scalarQ1: Double
|
||||
if !freqIsGenerator && !qIsGenerator {
|
||||
scalarF = min(fCoeffMax, max(0.0, 2.0 * Darwin.sin(piOverSr * scalarFreq)))
|
||||
scalarQ1 = 1.0 / max(minQDamping, scalarQ)
|
||||
} else {
|
||||
scalarF = 0.0
|
||||
scalarQ1 = 0.0
|
||||
}
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = ins[min(ins.count - 1, i)]
|
||||
|
||||
// Resolve per-sample freq/q when driven by generators.
|
||||
let f: Double
|
||||
let q1: Double
|
||||
if freqIsGenerator || qIsGenerator {
|
||||
let rawFreq: Double
|
||||
let rawQ: Double
|
||||
if let fs: [Double] = freqSamples {
|
||||
rawFreq = fs[min(fs.count - 1, i)]
|
||||
} else {
|
||||
rawFreq = scalarFreq
|
||||
}
|
||||
if let qs: [Double] = qSamples {
|
||||
rawQ = qs[min(qs.count - 1, i)]
|
||||
} else {
|
||||
rawQ = scalarQ
|
||||
}
|
||||
guard rawFreq > 0.0 else {
|
||||
_result[0][i] = 0.0
|
||||
_result[1][i] = 0.0
|
||||
_result[2][i] = 0.0
|
||||
_result[3][i] = 0.0
|
||||
continue
|
||||
}
|
||||
f = min(fCoeffMax, 2.0 * Darwin.sin(piOverSr * rawFreq))
|
||||
q1 = 1.0 / max(minQDamping, rawQ)
|
||||
} else {
|
||||
guard scalarFreq > 0.0 else {
|
||||
_result[0][i] = 0.0
|
||||
_result[1][i] = 0.0
|
||||
_result[2][i] = 0.0
|
||||
_result[3][i] = 0.0
|
||||
continue
|
||||
}
|
||||
f = scalarF
|
||||
q1 = scalarQ1
|
||||
}
|
||||
|
||||
// Chamberlin SVF recurrence.
|
||||
low = low + f * band
|
||||
let high: Double = x - low - q1 * band
|
||||
band = f * high + band
|
||||
let notch: Double = high + low
|
||||
|
||||
low = denormalsToZero(low)
|
||||
band = denormalsToZero(band)
|
||||
|
||||
_result[0][i] = low
|
||||
_result[1][i] = high
|
||||
_result[2][i] = band
|
||||
_result[3][i] = notch
|
||||
}
|
||||
runSVFBlock(
|
||||
ins: ins,
|
||||
freqSamples: freqSamples,
|
||||
qSamples: qSamples,
|
||||
scalarFreq: scalarFreq,
|
||||
scalarQ: scalarQ,
|
||||
freqIsGenerator: freqIsGenerator,
|
||||
qIsGenerator: qIsGenerator,
|
||||
piOverSr: piOverSr,
|
||||
low: &low,
|
||||
band: &band,
|
||||
result: &_result,
|
||||
count: count
|
||||
)
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
@@ -323,72 +268,21 @@ public enum SVF {
|
||||
let scalarQ: Double = qSamples == nil ? qInput.floatValue(graph: graph) : 0.0
|
||||
|
||||
let piOverSr: Double = Double.pi / sampleRate
|
||||
let minQDamping: Double = 0.0001
|
||||
let fCoeffMax: Double = 1.0
|
||||
|
||||
let scalarF: Double
|
||||
let scalarQ1: Double
|
||||
if !freqIsGenerator && !qIsGenerator {
|
||||
scalarF = min(fCoeffMax, max(0.0, 2.0 * Darwin.sin(piOverSr * scalarFreq)))
|
||||
scalarQ1 = 1.0 / max(minQDamping, scalarQ)
|
||||
} else {
|
||||
scalarF = 0.0
|
||||
scalarQ1 = 0.0
|
||||
}
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = ins[min(ins.count - 1, i)]
|
||||
|
||||
let f: Double
|
||||
let q1: Double
|
||||
if freqIsGenerator || qIsGenerator {
|
||||
let rawFreq: Double
|
||||
let rawQ: Double
|
||||
if let fs: [Double] = freqSamples {
|
||||
rawFreq = fs[min(fs.count - 1, i)]
|
||||
} else {
|
||||
rawFreq = scalarFreq
|
||||
}
|
||||
if let qs: [Double] = qSamples {
|
||||
rawQ = qs[min(qs.count - 1, i)]
|
||||
} else {
|
||||
rawQ = scalarQ
|
||||
}
|
||||
guard rawFreq > 0.0 else {
|
||||
_result[0][i] = 0.0
|
||||
_result[1][i] = 0.0
|
||||
_result[2][i] = 0.0
|
||||
_result[3][i] = 0.0
|
||||
continue
|
||||
}
|
||||
f = min(fCoeffMax, 2.0 * Darwin.sin(piOverSr * rawFreq))
|
||||
q1 = 1.0 / max(minQDamping, rawQ)
|
||||
} else {
|
||||
guard scalarFreq > 0.0 else {
|
||||
_result[0][i] = 0.0
|
||||
_result[1][i] = 0.0
|
||||
_result[2][i] = 0.0
|
||||
_result[3][i] = 0.0
|
||||
continue
|
||||
}
|
||||
f = scalarF
|
||||
q1 = scalarQ1
|
||||
}
|
||||
|
||||
// Chamberlin SVF recurrence.
|
||||
low = low + f * band
|
||||
let high: Double = x - low - q1 * band
|
||||
band = f * high + band
|
||||
let notch: Double = high + low
|
||||
|
||||
low = denormalsToZero(low)
|
||||
band = denormalsToZero(band)
|
||||
|
||||
_result[0][i] = low
|
||||
_result[1][i] = high
|
||||
_result[2][i] = band
|
||||
_result[3][i] = notch
|
||||
}
|
||||
runSVFBlock(
|
||||
ins: ins,
|
||||
freqSamples: freqSamples,
|
||||
qSamples: qSamples,
|
||||
scalarFreq: scalarFreq,
|
||||
scalarQ: scalarQ,
|
||||
freqIsGenerator: freqIsGenerator,
|
||||
qIsGenerator: qIsGenerator,
|
||||
piOverSr: piOverSr,
|
||||
low: &low,
|
||||
band: &band,
|
||||
result: &_result,
|
||||
count: count
|
||||
)
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
// SVFHelpers.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Darwin
|
||||
|
||||
/// Minimum damping denominator — prevents the `1/q` divide-by-zero in the SVF.
|
||||
let svfMinQDamping: Double = 0.0001
|
||||
|
||||
/// Stability bound for the Chamberlin SVF frequency coefficient `f`.
|
||||
let svfFCoeffMax: Double = 1.0
|
||||
|
||||
/// Shared per-block body for `SVF.Audio` and `SVF.Control` — runs the Chamberlin
|
||||
/// state-variable recurrence over `count` samples, writing the four outputs
|
||||
/// (low / high / band / notch) into `result` rows 0…3.
|
||||
///
|
||||
/// `low` and `band` are the two IIR delay elements, advanced in place.
|
||||
///
|
||||
/// ## Frequency-coefficient interpolation
|
||||
/// When `freq` is generator-driven the cutoff coefficient `f = 2·sin(π·freq/sr)`
|
||||
/// is evaluated with `sin()` only at the first and last sample of the block and
|
||||
/// linearly interpolated for the samples in between — the same coefficient-ramp
|
||||
/// technique the RBJ biquads use. This replaces one transcendental call per
|
||||
/// sample with two per block. The per-sample `freq > 0 → silence` guard is still
|
||||
/// applied from the raw (un-interpolated) frequency so individual samples whose
|
||||
/// cutoff drops to zero are zeroed exactly as before.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - ins: Input signal block (last value repeats if shorter than `count`).
|
||||
/// - freqSamples: Per-sample cutoff in Hz when `freq` is generator-driven, else `nil`.
|
||||
/// - qSamples: Per-sample Q when `q` is generator-driven, else `nil`.
|
||||
/// - scalarFreq: Cutoff in Hz used when `freq` is not generator-driven.
|
||||
/// - scalarQ: Q used when `q` is not generator-driven.
|
||||
/// - freqIsGenerator: Whether `freq` is generator-driven (classified at init).
|
||||
/// - qIsGenerator: Whether `q` is generator-driven (classified at init).
|
||||
/// - piOverSr: `π / sampleRate`, precomputed by the caller.
|
||||
/// - low: Lowpass IIR accumulator, advanced in place.
|
||||
/// - band: Bandpass IIR accumulator, advanced in place.
|
||||
/// - result: Output buffer; rows 0…3 receive low / high / band / notch.
|
||||
/// - count: Number of samples to process.
|
||||
@inline(__always)
|
||||
func runSVFBlock(
|
||||
ins: [Double],
|
||||
freqSamples: [Double]?,
|
||||
qSamples: [Double]?,
|
||||
scalarFreq: Double,
|
||||
scalarQ: Double,
|
||||
freqIsGenerator: Bool,
|
||||
qIsGenerator: Bool,
|
||||
piOverSr: Double,
|
||||
low: inout Double,
|
||||
band: inout Double,
|
||||
result: inout [[Double]],
|
||||
count: Int
|
||||
) {
|
||||
let minQDamping: Double = svfMinQDamping
|
||||
let fCoeffMax: Double = svfFCoeffMax
|
||||
|
||||
// Scalar coefficients reused for whichever input is not generator-driven.
|
||||
// `scalarFCoeff` is computed whenever `freq` is scalar — even if `q` is a
|
||||
// generator — matching the original per-sample formula for that mixed case.
|
||||
let scalarFCoeff: Double = freqIsGenerator
|
||||
? 0.0
|
||||
: min(fCoeffMax, max(0.0, 2.0 * Darwin.sin(piOverSr * scalarFreq)))
|
||||
let scalarQ1: Double = qIsGenerator ? 0.0 : 1.0 / max(minQDamping, scalarQ)
|
||||
|
||||
// Block-boundary cutoff-coefficient ramp for the generator-driven case.
|
||||
var fFirst: Double = 0.0
|
||||
var fStep: Double = 0.0
|
||||
if freqIsGenerator, let fs: [Double] = freqSamples, count > 0, !fs.isEmpty {
|
||||
let firstRaw: Double = fs[0]
|
||||
let lastRaw: Double = fs[min(fs.count - 1, count - 1)]
|
||||
// `max(0.0, ...)` matches the scalar path: a freq above the sample rate makes
|
||||
// `sin(π·freq/sr)` negative, which would destabilise the Chamberlin recurrence.
|
||||
let cFirst: Double = firstRaw > 0.0 ? min(fCoeffMax, max(0.0, 2.0 * Darwin.sin(piOverSr * firstRaw))) : 0.0
|
||||
let cLast: Double = lastRaw > 0.0 ? min(fCoeffMax, max(0.0, 2.0 * Darwin.sin(piOverSr * lastRaw))) : 0.0
|
||||
fFirst = cFirst
|
||||
fStep = count > 1 ? (cLast - cFirst) / Double(count - 1) : 0.0
|
||||
}
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = ins[min(ins.count - 1, i)]
|
||||
|
||||
let f: Double
|
||||
let q1: Double
|
||||
if freqIsGenerator || qIsGenerator {
|
||||
let rawFreq: Double
|
||||
if freqIsGenerator, let fs: [Double] = freqSamples {
|
||||
rawFreq = fs[min(fs.count - 1, i)]
|
||||
} else {
|
||||
rawFreq = scalarFreq
|
||||
}
|
||||
guard rawFreq > 0.0 else {
|
||||
result[0][i] = 0.0
|
||||
result[1][i] = 0.0
|
||||
result[2][i] = 0.0
|
||||
result[3][i] = 0.0
|
||||
continue
|
||||
}
|
||||
f = freqIsGenerator ? (fFirst + fStep * Double(i)) : scalarFCoeff
|
||||
if qIsGenerator, let qs: [Double] = qSamples {
|
||||
q1 = 1.0 / max(minQDamping, qs[min(qs.count - 1, i)])
|
||||
} else {
|
||||
q1 = scalarQ1
|
||||
}
|
||||
} else {
|
||||
guard scalarFreq > 0.0 else {
|
||||
result[0][i] = 0.0
|
||||
result[1][i] = 0.0
|
||||
result[2][i] = 0.0
|
||||
result[3][i] = 0.0
|
||||
continue
|
||||
}
|
||||
f = scalarFCoeff
|
||||
q1 = scalarQ1
|
||||
}
|
||||
|
||||
// Chamberlin SVF recurrence.
|
||||
low = low + f * band
|
||||
let high: Double = x - low - q1 * band
|
||||
band = f * high + band
|
||||
let notch: Double = high + low
|
||||
|
||||
low = denormalsToZero(low)
|
||||
band = denormalsToZero(band)
|
||||
|
||||
result[0][i] = low
|
||||
result[1][i] = high
|
||||
result[2][i] = band
|
||||
result[3][i] = notch
|
||||
}
|
||||
}
|
||||
@@ -44,8 +44,7 @@ public enum Abs {
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
let block: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first ?? []
|
||||
let n: Int = block.count
|
||||
for i: Int in 0..<count { _result[0][i] = Swift.abs(i < n ? block[i] : 0.0) }
|
||||
unaryVectorAbs(block, into: &_result, count: count)
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
@@ -78,6 +78,9 @@ public final class BinaryOpGenerator: GeneratorBase, AudioGenerator {
|
||||
private let rhs: any ValidGeneratorInput
|
||||
private let op: (Double, Double) -> Double
|
||||
|
||||
/// Arithmetic operator kind for vDSP dispatch, or `nil` for an arbitrary
|
||||
/// closure (`.other`-style), which uses the per-sample `op` fallback.
|
||||
private let kind: BinaryOpKind?
|
||||
|
||||
/// Output channel count — `max(lhsChannels, rhsChannels)`. Read by downstream
|
||||
/// `BinaryOpGenerator` instances to compose multi-channel arithmetic.
|
||||
@@ -95,16 +98,18 @@ public final class BinaryOpGenerator: GeneratorBase, AudioGenerator {
|
||||
/// Channel count of `rhs` at init.
|
||||
private let rhsChannels: Int
|
||||
|
||||
public init(
|
||||
private init(
|
||||
lhs: any ValidGeneratorInput,
|
||||
rhs: any ValidGeneratorInput,
|
||||
op: @escaping (Double, Double) -> Double
|
||||
op: @escaping (Double, Double) -> Double,
|
||||
kind: BinaryOpKind?
|
||||
) {
|
||||
let resolvedLhs: any ValidGeneratorInput = lhs._resolvedInput()
|
||||
let resolvedRhs: any ValidGeneratorInput = rhs._resolvedInput()
|
||||
self.lhs = resolvedLhs
|
||||
self.rhs = resolvedRhs
|
||||
self.op = op
|
||||
self.kind = kind
|
||||
// Classify inputs at construction time — types are fixed after init, so we only
|
||||
// pay the is-any-Generator runtime cost once rather than once per RT block.
|
||||
self.lhsIsLiteral = !resolvedLhs.needsInterpolation() && !(resolvedLhs is any Generator)
|
||||
@@ -123,6 +128,34 @@ public final class BinaryOpGenerator: GeneratorBase, AudioGenerator {
|
||||
super.init(channels: max(lhsCh, rhsCh))
|
||||
}
|
||||
|
||||
/// Construct from an arbitrary closure. The per-sample closure path is used
|
||||
/// (no vDSP dispatch) since the operation is not one of the four arithmetic kinds.
|
||||
public convenience init(
|
||||
lhs: any ValidGeneratorInput,
|
||||
rhs: any ValidGeneratorInput,
|
||||
op: @escaping (Double, Double) -> Double
|
||||
) {
|
||||
self.init(lhs: lhs, rhs: rhs, op: op, kind: nil)
|
||||
}
|
||||
|
||||
/// Construct from one of the four arithmetic operator kinds — enables the
|
||||
/// vDSP dispatch path. The matching scalar closure backs the fallback loop
|
||||
/// (both-literals, short/unaligned rows).
|
||||
convenience init(
|
||||
lhs: any ValidGeneratorInput,
|
||||
rhs: any ValidGeneratorInput,
|
||||
kind: BinaryOpKind
|
||||
) {
|
||||
let opClosure: (Double, Double) -> Double
|
||||
switch kind {
|
||||
case .add: opClosure = (+)
|
||||
case .subtract: opClosure = (-)
|
||||
case .multiply: opClosure = (*)
|
||||
case .divide: opClosure = (/)
|
||||
}
|
||||
self.init(lhs: lhs, rhs: rhs, op: opClosure, kind: kind)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
@@ -161,7 +194,11 @@ public final class BinaryOpGenerator: GeneratorBase, AudioGenerator {
|
||||
continue
|
||||
}
|
||||
let ls: [Double] = lhsSamples[lhsRow]
|
||||
for i: Int in 0..<count { _result[ch][i] = op(ls[i], rhsScalar) }
|
||||
if let k: BinaryOpKind = kind, ls.count >= count {
|
||||
binaryOpVectorScalarRHS(ls, rhsScalar, k, into: &_result[ch], count: count)
|
||||
} else {
|
||||
for i: Int in 0..<count { _result[ch][i] = op(ls[i], rhsScalar) }
|
||||
}
|
||||
} else if lhsIsLiteral {
|
||||
// Scalar op generator (e.g. 0.5 * stereoGen)
|
||||
guard rhsRow < rhsSamples.count else {
|
||||
@@ -169,7 +206,11 @@ public final class BinaryOpGenerator: GeneratorBase, AudioGenerator {
|
||||
continue
|
||||
}
|
||||
let rs: [Double] = rhsSamples[rhsRow]
|
||||
for i: Int in 0..<count { _result[ch][i] = op(lhsScalar, rs[i]) }
|
||||
if let k: BinaryOpKind = kind, rs.count >= count {
|
||||
binaryOpScalarLHSVector(lhsScalar, rs, k, into: &_result[ch], count: count)
|
||||
} else {
|
||||
for i: Int in 0..<count { _result[ch][i] = op(lhsScalar, rs[i]) }
|
||||
}
|
||||
} else {
|
||||
// Both generators
|
||||
guard lhsRow < lhsSamples.count, rhsRow < rhsSamples.count else {
|
||||
@@ -178,7 +219,11 @@ public final class BinaryOpGenerator: GeneratorBase, AudioGenerator {
|
||||
}
|
||||
let ls: [Double] = lhsSamples[lhsRow]
|
||||
let rs: [Double] = rhsSamples[rhsRow]
|
||||
for i: Int in 0..<count { _result[ch][i] = op(ls[i], rs[i]) }
|
||||
if let k: BinaryOpKind = kind, ls.count >= count, rs.count >= count {
|
||||
binaryOpVectorVector(ls, rs, k, into: &_result[ch], count: count)
|
||||
} else {
|
||||
for i: Int in 0..<count { _result[ch][i] = op(ls[i], rs[i]) }
|
||||
}
|
||||
}
|
||||
}
|
||||
return _result
|
||||
@@ -202,44 +247,44 @@ public final class BinaryOpGenerator: GeneratorBase, AudioGenerator {
|
||||
|
||||
// Generator op Generator (tiebreaker — avoids ambiguity when both sides conform to Generator)
|
||||
public func + <L: Generator, R: Generator>(lhs: L, rhs: R) -> BinaryOpGenerator {
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: +)
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .add)
|
||||
}
|
||||
public func - <L: Generator, R: Generator>(lhs: L, rhs: R) -> BinaryOpGenerator {
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: -)
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .subtract)
|
||||
}
|
||||
public func * <L: Generator, R: Generator>(lhs: L, rhs: R) -> BinaryOpGenerator {
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: *)
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .multiply)
|
||||
}
|
||||
public func / <L: Generator, R: Generator>(lhs: L, rhs: R) -> BinaryOpGenerator {
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: /)
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .divide)
|
||||
}
|
||||
|
||||
// Generator op ValidGeneratorInput
|
||||
public func + <L: Generator>(lhs: L, rhs: any ValidGeneratorInput) -> BinaryOpGenerator {
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: +)
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .add)
|
||||
}
|
||||
public func - <L: Generator>(lhs: L, rhs: any ValidGeneratorInput) -> BinaryOpGenerator {
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: -)
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .subtract)
|
||||
}
|
||||
public func * <L: Generator>(lhs: L, rhs: any ValidGeneratorInput) -> BinaryOpGenerator {
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: *)
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .multiply)
|
||||
}
|
||||
public func / <L: Generator>(lhs: L, rhs: any ValidGeneratorInput) -> BinaryOpGenerator {
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: /)
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .divide)
|
||||
}
|
||||
|
||||
// ValidGeneratorInput op Generator
|
||||
public func + <R: Generator>(lhs: any ValidGeneratorInput, rhs: R) -> BinaryOpGenerator {
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: +)
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .add)
|
||||
}
|
||||
public func - <R: Generator>(lhs: any ValidGeneratorInput, rhs: R) -> BinaryOpGenerator {
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: -)
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .subtract)
|
||||
}
|
||||
public func * <R: Generator>(lhs: any ValidGeneratorInput, rhs: R) -> BinaryOpGenerator {
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: *)
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .multiply)
|
||||
}
|
||||
public func / <R: Generator>(lhs: any ValidGeneratorInput, rhs: R) -> BinaryOpGenerator {
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: /)
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .divide)
|
||||
}
|
||||
|
||||
// ValidGeneratorInput op ValidGeneratorInput — both existential.
|
||||
@@ -247,14 +292,14 @@ public func / <R: Generator>(lhs: any ValidGeneratorInput, rhs: R) -> BinaryOpGe
|
||||
// `freq: any ValidGeneratorInput`). Swift still picks the stdlib `Double op Double`
|
||||
// overload for concrete Double expressions, so pure scalar arithmetic is unaffected.
|
||||
public func + (lhs: any ValidGeneratorInput, rhs: any ValidGeneratorInput) -> BinaryOpGenerator {
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: +)
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .add)
|
||||
}
|
||||
public func - (lhs: any ValidGeneratorInput, rhs: any ValidGeneratorInput) -> BinaryOpGenerator {
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: -)
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .subtract)
|
||||
}
|
||||
public func * (lhs: any ValidGeneratorInput, rhs: any ValidGeneratorInput) -> BinaryOpGenerator {
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: *)
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .multiply)
|
||||
}
|
||||
public func / (lhs: any ValidGeneratorInput, rhs: any ValidGeneratorInput) -> BinaryOpGenerator {
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, op: /)
|
||||
BinaryOpGenerator(lhs: lhs, rhs: rhs, kind: .divide)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
// BinaryOpVectorHelpers.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
|
||||
/// The four arithmetic operators `BinaryOpGenerator` can dispatch to vDSP. A
|
||||
/// generator built from an arbitrary closure (not one of these four) carries no
|
||||
/// kind and falls back to the per-sample closure loop.
|
||||
enum BinaryOpKind {
|
||||
case add
|
||||
case subtract
|
||||
case multiply
|
||||
case divide
|
||||
}
|
||||
|
||||
// Vectorised `BinaryOpGenerator` inner loops. Each dispatches one output row.
|
||||
// All four operators map to correctly-rounded vDSP routines, so results are
|
||||
// bit-identical to the scalar `lhs op rhs` loop — divide uses true division
|
||||
// (vsdivD / svdivD / vdivD), never reciprocal-multiply, to preserve that.
|
||||
//
|
||||
// vDSP subtract/divide take operands in `C = A - B` / `C = A / B` order with the
|
||||
// "B" (subtrahend / divisor) pointer FIRST — the calls below pass them reversed
|
||||
// accordingly.
|
||||
|
||||
/// `out[i] = ls[i] <op> scalar`. Caller guarantees `ls.count >= count`.
|
||||
@inline(__always)
|
||||
func binaryOpVectorScalarRHS(
|
||||
_ ls: [Double],
|
||||
_ scalar: Double,
|
||||
_ kind: BinaryOpKind,
|
||||
into out: inout [Double],
|
||||
count: Int
|
||||
) {
|
||||
var s: Double = scalar
|
||||
ls.withUnsafeBufferPointer { lp in
|
||||
out.withUnsafeMutableBufferPointer { op in
|
||||
guard let a: UnsafePointer<Double> = lp.baseAddress,
|
||||
let c: UnsafeMutablePointer<Double> = op.baseAddress else { return }
|
||||
let n: vDSP_Length = vDSP_Length(count)
|
||||
switch kind {
|
||||
case .add:
|
||||
vDSP_vsaddD(a, 1, &s, c, 1, n)
|
||||
case .multiply:
|
||||
vDSP_vsmulD(a, 1, &s, c, 1, n)
|
||||
case .subtract:
|
||||
var neg: Double = -scalar // ls - s == ls + (-s), bit-exact
|
||||
vDSP_vsaddD(a, 1, &neg, c, 1, n)
|
||||
case .divide:
|
||||
vDSP_vsdivD(a, 1, &s, c, 1, n) // C[i] = ls[i] / s (true division)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `out[i] = scalar <op> rs[i]`. Caller guarantees `rs.count >= count`.
|
||||
@inline(__always)
|
||||
func binaryOpScalarLHSVector(
|
||||
_ scalar: Double,
|
||||
_ rs: [Double],
|
||||
_ kind: BinaryOpKind,
|
||||
into out: inout [Double],
|
||||
count: Int
|
||||
) {
|
||||
var s: Double = scalar
|
||||
rs.withUnsafeBufferPointer { rp in
|
||||
out.withUnsafeMutableBufferPointer { op in
|
||||
guard let b: UnsafePointer<Double> = rp.baseAddress,
|
||||
let c: UnsafeMutablePointer<Double> = op.baseAddress else { return }
|
||||
let n: vDSP_Length = vDSP_Length(count)
|
||||
switch kind {
|
||||
case .add:
|
||||
vDSP_vsaddD(b, 1, &s, c, 1, n) // s + rs == rs + s
|
||||
case .multiply:
|
||||
vDSP_vsmulD(b, 1, &s, c, 1, n) // commutative
|
||||
case .subtract:
|
||||
var negOne: Double = -1.0 // rs*(-1) + s == s - rs, bit-exact
|
||||
vDSP_vsmsaD(b, 1, &negOne, &s, c, 1, n)
|
||||
case .divide:
|
||||
vDSP_svdivD(&s, b, 1, c, 1, n) // C[i] = s / rs[i] (true division)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `out[i] = ls[i] <op> rs[i]`. Caller guarantees both counts `>= count`.
|
||||
@inline(__always)
|
||||
func binaryOpVectorVector(
|
||||
_ ls: [Double],
|
||||
_ rs: [Double],
|
||||
_ kind: BinaryOpKind,
|
||||
into out: inout [Double],
|
||||
count: Int
|
||||
) {
|
||||
ls.withUnsafeBufferPointer { lp in
|
||||
rs.withUnsafeBufferPointer { rp in
|
||||
out.withUnsafeMutableBufferPointer { op in
|
||||
guard let a: UnsafePointer<Double> = lp.baseAddress,
|
||||
let b: UnsafePointer<Double> = rp.baseAddress,
|
||||
let c: UnsafeMutablePointer<Double> = op.baseAddress else { return }
|
||||
let n: vDSP_Length = vDSP_Length(count)
|
||||
switch kind {
|
||||
case .add:
|
||||
vDSP_vaddD(a, 1, b, 1, c, 1, n)
|
||||
case .multiply:
|
||||
vDSP_vmulD(a, 1, b, 1, c, 1, n)
|
||||
case .subtract:
|
||||
vDSP_vsubD(b, 1, a, 1, c, 1, n) // C = A - B = ls - rs (B first)
|
||||
case .divide:
|
||||
vDSP_vdivD(b, 1, a, 1, c, 1, n) // C = A / B = ls / rs (B first)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -46,8 +46,7 @@ public enum Ceil {
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
let block: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first ?? []
|
||||
let n: Int = block.count
|
||||
for i: Int in 0..<count { _result[0][i] = Foundation.ceil(i < n ? block[i] : 0.0) }
|
||||
unaryVectorCeil(block, into: &_result, count: count)
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
@@ -47,8 +47,7 @@ public enum Cos {
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
let block: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first ?? []
|
||||
let n: Int = block.count
|
||||
for i: Int in 0..<count { _result[0][i] = Foundation.cos(i < n ? block[i] : 0.0) }
|
||||
unaryVectorCos(block, into: &_result, count: count)
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
@@ -46,8 +46,7 @@ public enum Exp {
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
let block: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first ?? []
|
||||
let n: Int = block.count
|
||||
for i: Int in 0..<count { _result[0][i] = Foundation.exp(i < n ? block[i] : 0.0) }
|
||||
unaryVectorExp(block, into: &_result, count: count)
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
@@ -46,8 +46,7 @@ public enum Floor {
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
let block: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first ?? []
|
||||
let n: Int = block.count
|
||||
for i: Int in 0..<count { _result[0][i] = Foundation.floor(i < n ? block[i] : 0.0) }
|
||||
unaryVectorFloor(block, into: &_result, count: count)
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
|
||||
// MARK: - LinLin
|
||||
|
||||
/// Maps signal from [inLo, inHi] linearly to [outLo, outHi].
|
||||
@@ -88,10 +90,25 @@ public enum LinLin {
|
||||
let outLo: Double = outLoInput.floatValue(graph: graph)
|
||||
let outRange: Double = outHiInput.floatValue(graph: graph) - outLo
|
||||
// inRange == 0 produces NaN/±Inf per IEEE 754 — intentional.
|
||||
// The map is affine in x: f(x) = a·x + b with a = outRange/inRange,
|
||||
// b = outLo − inLo·a. The full-block path applies it as one fused
|
||||
// multiply-add (vDSP_vsmsaD).
|
||||
let n: Int = block.count
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = i < n ? block[i] : 0.0
|
||||
_result[0][i] = outLo + (x - inLo) / inRange * outRange
|
||||
if n >= count {
|
||||
var a: Double = outRange / inRange
|
||||
var b: Double = outLo - inLo * a
|
||||
block.withUnsafeBufferPointer { src in
|
||||
_result[0].withUnsafeMutableBufferPointer { dst in
|
||||
guard let s: UnsafePointer<Double> = src.baseAddress,
|
||||
let d: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
|
||||
vDSP_vsmsaD(s, 1, &a, &b, d, 1, vDSP_Length(count))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = i < n ? block[i] : 0.0
|
||||
_result[0][i] = outLo + (x - inLo) / inRange * outRange
|
||||
}
|
||||
}
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
|
||||
@@ -46,8 +46,7 @@ public enum Log {
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
let block: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first ?? []
|
||||
let n: Int = block.count
|
||||
for i: Int in 0..<count { _result[0][i] = Foundation.log(i < n ? block[i] : 1.0) }
|
||||
unaryVectorLog(block, into: &_result, count: count)
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
@@ -47,8 +47,7 @@ public enum Sin {
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
let block: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first ?? []
|
||||
let n: Int = block.count
|
||||
for i: Int in 0..<count { _result[0][i] = Foundation.sin(i < n ? block[i] : 0.0) }
|
||||
unaryVectorSin(block, into: &_result, count: count)
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
@@ -46,8 +46,7 @@ public enum Sqrt {
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
let block: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first ?? []
|
||||
let n: Int = block.count
|
||||
for i: Int in 0..<count { _result[0][i] = Foundation.sqrt(i < n ? block[i] : 0.0) }
|
||||
unaryVectorSqrt(block, into: &_result, count: count)
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
// UnaryMathVectorHelpers.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
|
||||
// Vectorised inner loops for the unary math waveshapers (Sin / Cos / Exp / Log /
|
||||
// Sqrt / Floor / Ceil / Abs). Each `.Audio._computeSamples` resolves its input
|
||||
// block, then calls the matching `unaryVector*` wrapper instead of a per-sample
|
||||
// scalar `Foundation.*` loop.
|
||||
//
|
||||
// Split-path strategy: when the upstream block is full-length (`n >= count`,
|
||||
// the normal case at any block size) the whole block is transformed in one
|
||||
// Accelerate call. Only a short upstream block (`n < count`) falls back to the
|
||||
// staged path, which zero/pad-extends into the output row and transforms it in
|
||||
// place — so the vForce/vDSP routine still runs, just over a padded buffer.
|
||||
|
||||
/// Core split-path driver. `transform(dst, src, n)` must transform `src[0..<n]`
|
||||
/// into `dst[0..<n]` (in-place safe — the fallback passes `dst` as both).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - block: Resolved input samples (may be shorter than `count`).
|
||||
/// - pad: Value substituted for samples past the end of a short input block.
|
||||
/// - result: Output buffer; row 0 receives the transformed samples.
|
||||
/// - count: Number of samples to produce.
|
||||
/// - transform: Vector transform applied to `count` samples (src → dst).
|
||||
@inline(__always)
|
||||
func applyUnaryVectorTransform(
|
||||
_ block: [Double],
|
||||
pad: Double,
|
||||
into result: inout [[Double]],
|
||||
count: Int,
|
||||
_ transform: (_ dst: UnsafeMutablePointer<Double>, _ src: UnsafePointer<Double>, _ n: Int) -> Void
|
||||
) {
|
||||
let n: Int = block.count
|
||||
result[0].withUnsafeMutableBufferPointer { dst in
|
||||
guard let d: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
|
||||
if n >= count {
|
||||
block.withUnsafeBufferPointer { src in
|
||||
guard let s: UnsafePointer<Double> = src.baseAddress else { return }
|
||||
transform(d, s, count)
|
||||
}
|
||||
} else {
|
||||
for i: Int in 0..<count { d[i] = i < n ? block[i] : pad }
|
||||
transform(d, UnsafePointer(d), count)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
func unaryVectorSin(_ block: [Double], into result: inout [[Double]], count: Int) {
|
||||
applyUnaryVectorTransform(block, pad: 0.0, into: &result, count: count) { d, s, c in
|
||||
var len: Int32 = Int32(c)
|
||||
vvsin(d, s, &len)
|
||||
}
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
func unaryVectorCos(_ block: [Double], into result: inout [[Double]], count: Int) {
|
||||
applyUnaryVectorTransform(block, pad: 0.0, into: &result, count: count) { d, s, c in
|
||||
var len: Int32 = Int32(c)
|
||||
vvcos(d, s, &len)
|
||||
}
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
func unaryVectorExp(_ block: [Double], into result: inout [[Double]], count: Int) {
|
||||
applyUnaryVectorTransform(block, pad: 0.0, into: &result, count: count) { d, s, c in
|
||||
var len: Int32 = Int32(c)
|
||||
vvexp(d, s, &len)
|
||||
}
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
func unaryVectorLog(_ block: [Double], into result: inout [[Double]], count: Int) {
|
||||
// Pad with 1.0 so padded samples map to log(1) = 0, matching the scalar fallback.
|
||||
applyUnaryVectorTransform(block, pad: 1.0, into: &result, count: count) { d, s, c in
|
||||
var len: Int32 = Int32(c)
|
||||
vvlog(d, s, &len)
|
||||
}
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
func unaryVectorSqrt(_ block: [Double], into result: inout [[Double]], count: Int) {
|
||||
applyUnaryVectorTransform(block, pad: 0.0, into: &result, count: count) { d, s, c in
|
||||
var len: Int32 = Int32(c)
|
||||
vvsqrt(d, s, &len)
|
||||
}
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
func unaryVectorFloor(_ block: [Double], into result: inout [[Double]], count: Int) {
|
||||
applyUnaryVectorTransform(block, pad: 0.0, into: &result, count: count) { d, s, c in
|
||||
var len: Int32 = Int32(c)
|
||||
vvfloor(d, s, &len)
|
||||
}
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
func unaryVectorCeil(_ block: [Double], into result: inout [[Double]], count: Int) {
|
||||
applyUnaryVectorTransform(block, pad: 0.0, into: &result, count: count) { d, s, c in
|
||||
var len: Int32 = Int32(c)
|
||||
vvceil(d, s, &len)
|
||||
}
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
func unaryVectorAbs(_ block: [Double], into result: inout [[Double]], count: Int) {
|
||||
applyUnaryVectorTransform(block, pad: 0.0, into: &result, count: count) { d, s, c in
|
||||
vDSP_vabsD(s, 1, d, 1, vDSP_Length(c))
|
||||
}
|
||||
}
|
||||
@@ -81,6 +81,13 @@ public enum Chorus {
|
||||
// MARK: Delay line and LFO state
|
||||
|
||||
private var _delayLine: [Double]
|
||||
/// `_delayLine.count - 1`. The buffer is sized to a power of two so the
|
||||
/// circular index wrap is `& _delayMask` rather than `% count`.
|
||||
private let _delayMask: Int
|
||||
/// Maximum fractional delay in samples — derived from `maxDelayTime`, not
|
||||
/// the (power-of-two-rounded) buffer length, so the audible delay range is
|
||||
/// unchanged by the buffer over-allocation.
|
||||
private let _maxDelayFrac: Double
|
||||
private var _writePos: Int = 0
|
||||
/// Phase for tap 0 (channel 0 / left). Normalised [0, 1).
|
||||
private var _lfoPhase0: Double = 0.0
|
||||
@@ -146,7 +153,12 @@ public enum Chorus {
|
||||
_sampleRate = sampleRate
|
||||
_sampleRateRecip = 1.0 / sampleRate
|
||||
|
||||
_delayLine = [Double](repeating: 0, count: delayLineLength)
|
||||
// Semantic max delay comes from delayLineLength; the backing buffer is
|
||||
// rounded up to a power of two so the index wrap is a single AND.
|
||||
_maxDelayFrac = Double(delayLineLength - 2)
|
||||
let bufferLength: Int = lyrebirdNextPowerOfTwo(delayLineLength)
|
||||
_delayMask = bufferLength - 1
|
||||
_delayLine = [Double](repeating: 0, count: bufferLength)
|
||||
_mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
// Two output channels: left (tap 0) and right (tap 1).
|
||||
super.init(channels: 2)
|
||||
@@ -156,62 +168,26 @@ public enum Chorus {
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
let delayLineCount: Int = _delayLine.count
|
||||
let wrapOffset: Int = delayLineCount * 2
|
||||
let maxDelayFrac: Double = Double(delayLineCount - 2)
|
||||
let delayMask: Int = _delayMask
|
||||
let wrapOffset: Int = _delayLine.count // multiple of (mask + 1): vanishes under & mask
|
||||
let maxDelayFrac: Double = _maxDelayFrac
|
||||
|
||||
// Fetch input blocks.
|
||||
let inputSamples: [Double]?
|
||||
let scalarInput: Double
|
||||
if _inputIsGenerator {
|
||||
inputSamples = _inputSource.calculatedSamples(graph: graph, count: count).first
|
||||
scalarInput = 0
|
||||
} else {
|
||||
inputSamples = nil
|
||||
scalarInput = _inputSource.floatValue(graph: graph)
|
||||
}
|
||||
|
||||
let delayTimeSamples: [Double]?
|
||||
let scalarDelayTime: Double
|
||||
if _delayTimeIsGenerator {
|
||||
delayTimeSamples = _delayTimeSource.calculatedSamples(graph: graph, count: count).first
|
||||
scalarDelayTime = 0
|
||||
} else {
|
||||
delayTimeSamples = nil
|
||||
scalarDelayTime = _delayTimeSource.floatValue(graph: graph)
|
||||
}
|
||||
|
||||
let depthSamples: [Double]?
|
||||
let scalarDepth: Double
|
||||
if _depthIsGenerator {
|
||||
depthSamples = _depthSource.calculatedSamples(graph: graph, count: count).first
|
||||
scalarDepth = 0
|
||||
} else {
|
||||
depthSamples = nil
|
||||
scalarDepth = _depthSource.floatValue(graph: graph)
|
||||
}
|
||||
|
||||
let rateSamples: [Double]?
|
||||
let scalarRate: Double
|
||||
if _rateIsGenerator {
|
||||
rateSamples = _rateSource.calculatedSamples(graph: graph, count: count).first
|
||||
scalarRate = 0
|
||||
} else {
|
||||
rateSamples = nil
|
||||
scalarRate = _rateSource.floatValue(graph: graph)
|
||||
}
|
||||
|
||||
let mixSamples: [Double]?
|
||||
let scalarMix: Double
|
||||
if _mixIsGenerator {
|
||||
mixSamples = _mixSource.calculatedSamples(graph: graph, count: count).first
|
||||
scalarMix = 0
|
||||
} else {
|
||||
mixSamples = nil
|
||||
scalarMix = _mixSource.floatValue(graph: graph)
|
||||
}
|
||||
|
||||
let twoPi: Double = 2.0 * Double.pi
|
||||
let (inputSamples, scalarInput) = resolveGeneratorOrScalar(
|
||||
_inputSource, isGenerator: _inputIsGenerator, graph: graph, count: count
|
||||
)
|
||||
let (delayTimeSamples, scalarDelayTime) = resolveGeneratorOrScalar(
|
||||
_delayTimeSource, isGenerator: _delayTimeIsGenerator, graph: graph, count: count
|
||||
)
|
||||
let (depthSamples, scalarDepth) = resolveGeneratorOrScalar(
|
||||
_depthSource, isGenerator: _depthIsGenerator, graph: graph, count: count
|
||||
)
|
||||
let (rateSamples, scalarRate) = resolveGeneratorOrScalar(
|
||||
_rateSource, isGenerator: _rateIsGenerator, graph: graph, count: count
|
||||
)
|
||||
let (mixSamples, scalarMix) = resolveGeneratorOrScalar(
|
||||
_mixSource, isGenerator: _mixIsGenerator, graph: graph, count: count
|
||||
)
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let dry: Double
|
||||
@@ -263,24 +239,24 @@ public enum Chorus {
|
||||
let baseDelaySamples: Double = baseDelaySec * _sampleRate
|
||||
|
||||
// --- Tap 0 (left channel, LFO phase 0) ---
|
||||
let lfo0: Double = sin(_lfoPhase0 * twoPi)
|
||||
let lfo0: Double = sin(_lfoPhase0 * lyrebirdTwoPi)
|
||||
let delay0: Double = max(1.0, min(maxDelayFrac, baseDelaySamples + clampedDepth * baseDelaySamples * lfo0))
|
||||
let iDelay0: Int = Int(delay0)
|
||||
let frac0: Double = delay0 - Double(iDelay0)
|
||||
let pos0a: Int = (_writePos - iDelay0 + wrapOffset) % delayLineCount
|
||||
let pos0b: Int = (_writePos - iDelay0 - 1 + wrapOffset) % delayLineCount
|
||||
let pos0a: Int = (_writePos - iDelay0 + wrapOffset) & delayMask
|
||||
let pos0b: Int = (_writePos - iDelay0 - 1 + wrapOffset) & delayMask
|
||||
let tap0: Double = _delayLine[pos0a] * (1.0 - frac0) + _delayLine[pos0b] * frac0
|
||||
|
||||
// --- Tap 1 (right channel, LFO phase π) ---
|
||||
let lfo1: Double = sin(_lfoPhase1 * twoPi)
|
||||
let lfo1: Double = sin(_lfoPhase1 * lyrebirdTwoPi)
|
||||
let delay1: Double = max(1.0, min(maxDelayFrac, baseDelaySamples + clampedDepth * baseDelaySamples * lfo1))
|
||||
let iDelay1: Int = Int(delay1)
|
||||
let frac1: Double = delay1 - Double(iDelay1)
|
||||
let pos1a: Int = (_writePos - iDelay1 + wrapOffset) % delayLineCount
|
||||
let pos1b: Int = (_writePos - iDelay1 - 1 + wrapOffset) % delayLineCount
|
||||
let pos1a: Int = (_writePos - iDelay1 + wrapOffset) & delayMask
|
||||
let pos1b: Int = (_writePos - iDelay1 - 1 + wrapOffset) & delayMask
|
||||
let tap1: Double = _delayLine[pos1a] * (1.0 - frac1) + _delayLine[pos1b] * frac1
|
||||
|
||||
_writePos = (_writePos + 1) % delayLineCount
|
||||
_writePos = (_writePos + 1) & delayMask
|
||||
|
||||
let clampedMix: Double = max(0.0, min(1.0, mix))
|
||||
let dryGain: Double = 1.0 - clampedMix
|
||||
|
||||
@@ -91,6 +91,12 @@ public enum Flanger {
|
||||
// MARK: Delay line state
|
||||
|
||||
private var _delayLine: [Double]
|
||||
/// `_delayLine.count - 1`. Buffer is power-of-two sized so the circular
|
||||
/// index wrap is `& _delayMask` rather than `% count`.
|
||||
private let _delayMask: Int
|
||||
/// Maximum fractional delay in samples — from `maxDelayTime`, not the
|
||||
/// power-of-two buffer length, so the audible delay range is unchanged.
|
||||
private let _maxDelayFrac: Double
|
||||
private var _writePos: Int = 0
|
||||
private var _lfoPhase: Double = 0.0
|
||||
|
||||
@@ -157,7 +163,12 @@ public enum Flanger {
|
||||
_sampleRate = sampleRate
|
||||
_sampleRateRecip = 1.0 / sampleRate
|
||||
|
||||
_delayLine = [Double](repeating: 0, count: delayLineLength)
|
||||
// Semantic max delay from delayLineLength; backing buffer rounded up
|
||||
// to a power of two so the index wrap is a single AND.
|
||||
_maxDelayFrac = Double(delayLineLength - 2)
|
||||
let bufferLength: Int = lyrebirdNextPowerOfTwo(delayLineLength)
|
||||
_delayMask = bufferLength - 1
|
||||
_delayLine = [Double](repeating: 0, count: bufferLength)
|
||||
_mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
|
||||
super.init()
|
||||
@@ -167,73 +178,32 @@ public enum Flanger {
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
let delayLineCount: Int = _delayLine.count
|
||||
// Wrap offset large enough to keep subtracted positions positive.
|
||||
let wrapOffset: Int = delayLineCount * 2
|
||||
let delayMask: Int = _delayMask
|
||||
// Wrap offset large enough to keep subtracted positions positive;
|
||||
// a multiple of (mask + 1), so it vanishes under & mask.
|
||||
let wrapOffset: Int = _delayLine.count
|
||||
|
||||
// Fetch input blocks.
|
||||
let inputSamples: [Double]?
|
||||
let scalarInput: Double
|
||||
if _inputIsGenerator {
|
||||
inputSamples = _inputSource.calculatedSamples(graph: graph, count: count).first
|
||||
scalarInput = 0
|
||||
} else {
|
||||
inputSamples = nil
|
||||
scalarInput = _inputSource.floatValue(graph: graph)
|
||||
}
|
||||
let (inputSamples, scalarInput) = resolveGeneratorOrScalar(
|
||||
_inputSource, isGenerator: _inputIsGenerator, graph: graph, count: count
|
||||
)
|
||||
let (delayTimeSamples, scalarDelayTime) = resolveGeneratorOrScalar(
|
||||
_delayTimeSource, isGenerator: _delayTimeIsGenerator, graph: graph, count: count
|
||||
)
|
||||
let (depthSamples, scalarDepth) = resolveGeneratorOrScalar(
|
||||
_depthSource, isGenerator: _depthIsGenerator, graph: graph, count: count
|
||||
)
|
||||
let (rateSamples, scalarRate) = resolveGeneratorOrScalar(
|
||||
_rateSource, isGenerator: _rateIsGenerator, graph: graph, count: count
|
||||
)
|
||||
let (feedbackSamples, scalarFeedback) = resolveGeneratorOrScalar(
|
||||
_feedbackSource, isGenerator: _feedbackIsGenerator, graph: graph, count: count
|
||||
)
|
||||
let (mixSamples, scalarMix) = resolveGeneratorOrScalar(
|
||||
_mixSource, isGenerator: _mixIsGenerator, graph: graph, count: count
|
||||
)
|
||||
|
||||
let delayTimeSamples: [Double]?
|
||||
let scalarDelayTime: Double
|
||||
if _delayTimeIsGenerator {
|
||||
delayTimeSamples = _delayTimeSource.calculatedSamples(graph: graph, count: count).first
|
||||
scalarDelayTime = 0
|
||||
} else {
|
||||
delayTimeSamples = nil
|
||||
scalarDelayTime = _delayTimeSource.floatValue(graph: graph)
|
||||
}
|
||||
|
||||
let depthSamples: [Double]?
|
||||
let scalarDepth: Double
|
||||
if _depthIsGenerator {
|
||||
depthSamples = _depthSource.calculatedSamples(graph: graph, count: count).first
|
||||
scalarDepth = 0
|
||||
} else {
|
||||
depthSamples = nil
|
||||
scalarDepth = _depthSource.floatValue(graph: graph)
|
||||
}
|
||||
|
||||
let rateSamples: [Double]?
|
||||
let scalarRate: Double
|
||||
if _rateIsGenerator {
|
||||
rateSamples = _rateSource.calculatedSamples(graph: graph, count: count).first
|
||||
scalarRate = 0
|
||||
} else {
|
||||
rateSamples = nil
|
||||
scalarRate = _rateSource.floatValue(graph: graph)
|
||||
}
|
||||
|
||||
let feedbackSamples: [Double]?
|
||||
let scalarFeedback: Double
|
||||
if _feedbackIsGenerator {
|
||||
feedbackSamples = _feedbackSource.calculatedSamples(graph: graph, count: count).first
|
||||
scalarFeedback = 0
|
||||
} else {
|
||||
feedbackSamples = nil
|
||||
scalarFeedback = _feedbackSource.floatValue(graph: graph)
|
||||
}
|
||||
|
||||
let mixSamples: [Double]?
|
||||
let scalarMix: Double
|
||||
if _mixIsGenerator {
|
||||
mixSamples = _mixSource.calculatedSamples(graph: graph, count: count).first
|
||||
scalarMix = 0
|
||||
} else {
|
||||
mixSamples = nil
|
||||
scalarMix = _mixSource.floatValue(graph: graph)
|
||||
}
|
||||
|
||||
let twoPi: Double = 2.0 * Double.pi
|
||||
let maxDelayFrac: Double = Double(delayLineCount - 2)
|
||||
let maxDelayFrac: Double = _maxDelayFrac
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let dry: Double
|
||||
@@ -283,7 +253,7 @@ public enum Flanger {
|
||||
if _lfoPhase >= 1.0 { _lfoPhase -= 1.0 }
|
||||
|
||||
// Compute modulated delay in samples (LFO sine output in [-1, 1]).
|
||||
let lfoOut: Double = sin(_lfoPhase * twoPi)
|
||||
let lfoOut: Double = sin(_lfoPhase * lyrebirdTwoPi)
|
||||
let clampedDepth: Double = max(0.0, min(1.0, depth))
|
||||
let modDelay: Double = baseDelay * _sampleRate * (1.0 + clampedDepth * lfoOut)
|
||||
let clampedDelay: Double = max(1.0, min(maxDelayFrac, modDelay))
|
||||
@@ -293,8 +263,8 @@ public enum Flanger {
|
||||
let frac: Double = clampedDelay - Double(iDelay)
|
||||
|
||||
// Circular read positions.
|
||||
let pos0: Int = (_writePos - iDelay + wrapOffset) % delayLineCount
|
||||
let pos1: Int = (_writePos - iDelay - 1 + wrapOffset) % delayLineCount
|
||||
let pos0: Int = (_writePos - iDelay + wrapOffset) & delayMask
|
||||
let pos1: Int = (_writePos - iDelay - 1 + wrapOffset) & delayMask
|
||||
let delayed: Double = _delayLine[pos0] * (1.0 - frac) + _delayLine[pos1] * frac
|
||||
|
||||
// Write feedback-enhanced input into delay line.
|
||||
@@ -302,7 +272,7 @@ public enum Flanger {
|
||||
let clampedFeedback: Double = max(0.0, min(maxFeedbackGain, feedback))
|
||||
_delayLine[_writePos] = denormalsToZero(dry + clampedFeedback * delayed)
|
||||
|
||||
_writePos = (_writePos + 1) % delayLineCount
|
||||
_writePos = (_writePos + 1) & delayMask
|
||||
|
||||
// Dry/wet mix.
|
||||
let clampedMix: Double = max(0.0, min(1.0, mix))
|
||||
|
||||
@@ -182,67 +182,25 @@ public enum Phaser {
|
||||
_checkCount(count)
|
||||
|
||||
// Fetch input blocks.
|
||||
let inputSamples: [Double]?
|
||||
let scalarInput: Double
|
||||
if _inputIsGenerator {
|
||||
inputSamples = _inputSource.calculatedSamples(graph: graph, count: count).first
|
||||
scalarInput = 0
|
||||
} else {
|
||||
inputSamples = nil
|
||||
scalarInput = _inputSource.floatValue(graph: graph)
|
||||
}
|
||||
let (inputSamples, scalarInput) = resolveGeneratorOrScalar(
|
||||
_inputSource, isGenerator: _inputIsGenerator, graph: graph, count: count
|
||||
)
|
||||
let (rateSamples, scalarRate) = resolveGeneratorOrScalar(
|
||||
_rateSource, isGenerator: _rateIsGenerator, graph: graph, count: count
|
||||
)
|
||||
let (depthSamples, scalarDepth) = resolveGeneratorOrScalar(
|
||||
_depthSource, isGenerator: _depthIsGenerator, graph: graph, count: count
|
||||
)
|
||||
let (centerFreqSamples, scalarCenterFreq) = resolveGeneratorOrScalar(
|
||||
_centerFreqSource, isGenerator: _centerFreqIsGenerator, graph: graph, count: count
|
||||
)
|
||||
let (feedbackSamples, scalarFeedback) = resolveGeneratorOrScalar(
|
||||
_feedbackSource, isGenerator: _feedbackIsGenerator, graph: graph, count: count
|
||||
)
|
||||
let (mixSamples, scalarMix) = resolveGeneratorOrScalar(
|
||||
_mixSource, isGenerator: _mixIsGenerator, graph: graph, count: count
|
||||
)
|
||||
|
||||
let rateSamples: [Double]?
|
||||
let scalarRate: Double
|
||||
if _rateIsGenerator {
|
||||
rateSamples = _rateSource.calculatedSamples(graph: graph, count: count).first
|
||||
scalarRate = 0
|
||||
} else {
|
||||
rateSamples = nil
|
||||
scalarRate = _rateSource.floatValue(graph: graph)
|
||||
}
|
||||
|
||||
let depthSamples: [Double]?
|
||||
let scalarDepth: Double
|
||||
if _depthIsGenerator {
|
||||
depthSamples = _depthSource.calculatedSamples(graph: graph, count: count).first
|
||||
scalarDepth = 0
|
||||
} else {
|
||||
depthSamples = nil
|
||||
scalarDepth = _depthSource.floatValue(graph: graph)
|
||||
}
|
||||
|
||||
let centerFreqSamples: [Double]?
|
||||
let scalarCenterFreq: Double
|
||||
if _centerFreqIsGenerator {
|
||||
centerFreqSamples = _centerFreqSource.calculatedSamples(graph: graph, count: count).first
|
||||
scalarCenterFreq = 0
|
||||
} else {
|
||||
centerFreqSamples = nil
|
||||
scalarCenterFreq = _centerFreqSource.floatValue(graph: graph)
|
||||
}
|
||||
|
||||
let feedbackSamples: [Double]?
|
||||
let scalarFeedback: Double
|
||||
if _feedbackIsGenerator {
|
||||
feedbackSamples = _feedbackSource.calculatedSamples(graph: graph, count: count).first
|
||||
scalarFeedback = 0
|
||||
} else {
|
||||
feedbackSamples = nil
|
||||
scalarFeedback = _feedbackSource.floatValue(graph: graph)
|
||||
}
|
||||
|
||||
let mixSamples: [Double]?
|
||||
let scalarMix: Double
|
||||
if _mixIsGenerator {
|
||||
mixSamples = _mixSource.calculatedSamples(graph: graph, count: count).first
|
||||
scalarMix = 0
|
||||
} else {
|
||||
mixSamples = nil
|
||||
scalarMix = _mixSource.floatValue(graph: graph)
|
||||
}
|
||||
|
||||
let twoPi: Double = 2.0 * Double.pi
|
||||
let piOverSr: Double = Double.pi * _sampleRateRecip
|
||||
let minFreq: Double = 1.0
|
||||
|
||||
@@ -295,7 +253,7 @@ public enum Phaser {
|
||||
|
||||
// Compute sweep frequency from LFO.
|
||||
let clampedDepth: Double = max(0.0, min(1.0, depth))
|
||||
let lfoOut: Double = sin(_lfoPhase * twoPi)
|
||||
let lfoOut: Double = sin(_lfoPhase * lyrebirdTwoPi)
|
||||
let sweepFreq: Double = max(minFreq, min(_nyquistLimit, centerFreq * (1.0 + clampedDepth * lfoOut)))
|
||||
|
||||
// Compute first-order all-pass coefficient.
|
||||
|
||||
@@ -202,7 +202,7 @@ public enum LFDutyCycle {
|
||||
|
||||
let dt: Double = freq / sampleRate
|
||||
_phase += dt * countFloat
|
||||
normalizeLFPhase(&_phase)
|
||||
normalizeOscPhase(&_phase)
|
||||
|
||||
let target: Double = _phase < duty ? 1.0 : -1.0
|
||||
|
||||
|
||||
@@ -13,13 +13,5 @@ let lfHalfPhase: Double = 0.5
|
||||
/// Amplitude spans 2 over a half period (0.5), so slope = 2 / 0.5 = 4.
|
||||
let lfTriangleSlope: Double = 4.0
|
||||
|
||||
/// Normalises `phase` to `[0, 1)` after a block-sized increment.
|
||||
/// Fast path handles the common case; slow path handles extreme freq × count.
|
||||
@inline(__always)
|
||||
func normalizeLFPhase(_ phase: inout Double) {
|
||||
if phase >= 1.0 { phase -= 1.0 }
|
||||
if phase >= 1.0 || phase < 0 {
|
||||
phase = phase.truncatingRemainder(dividingBy: 1.0)
|
||||
if phase < 0 { phase += 1.0 }
|
||||
}
|
||||
}
|
||||
// Phase normalisation is provided by `normalizeOscPhase` in OscBandLimitedHelpers.swift,
|
||||
// shared by all LF and band-limited oscillators.
|
||||
|
||||
@@ -149,7 +149,7 @@ public enum LFSawtooth {
|
||||
|
||||
let dt: Double = freq / sampleRate
|
||||
_phase += dt * countFloat
|
||||
normalizeLFPhase(&_phase)
|
||||
normalizeOscPhase(&_phase)
|
||||
|
||||
let target: Double = 2.0 * _phase - 1.0
|
||||
|
||||
|
||||
@@ -149,7 +149,7 @@ public enum LFSquare {
|
||||
|
||||
let dt: Double = freq / sampleRate
|
||||
_phase += dt * countFloat
|
||||
normalizeLFPhase(&_phase)
|
||||
normalizeOscPhase(&_phase)
|
||||
|
||||
let target: Double = _phase < lfHalfPhase ? 1.0 : -1.0
|
||||
|
||||
|
||||
@@ -156,7 +156,7 @@ public enum LFTriangle {
|
||||
|
||||
let dt: Double = freq / sampleRate
|
||||
_phase += dt * countFloat
|
||||
normalizeLFPhase(&_phase)
|
||||
normalizeOscPhase(&_phase)
|
||||
|
||||
let triangleDescendingIntercept: Double = lfTriangleSlope - 1.0
|
||||
let target: Double
|
||||
|
||||
@@ -70,9 +70,12 @@ let oscBLHalfPhase: Double = 0.5
|
||||
let oscBLTriangleSlope: Double = 4.0
|
||||
|
||||
/// Normalises `phase` to `[0, 1)` after a block-sized increment.
|
||||
/// Fast path handles the common case; slow path (truncatingRemainder) handles extreme freq × count.
|
||||
///
|
||||
/// Fast path subtracts 1.0 for the common single-wrap case; slow path uses
|
||||
/// `truncatingRemainder` to handle extreme `freq × count` values. Shared by
|
||||
/// all LF and band-limited oscillators.
|
||||
@inline(__always)
|
||||
func normalizeBLPhase(_ phase: inout Double) {
|
||||
func normalizeOscPhase(_ phase: inout Double) {
|
||||
if phase >= 1.0 { phase -= 1.0 }
|
||||
if phase >= 1.0 || phase < 0 {
|
||||
phase = phase.truncatingRemainder(dividingBy: 1.0)
|
||||
|
||||
@@ -216,7 +216,7 @@ public enum OscDutyCycle {
|
||||
|
||||
let dt: Double = freq / sampleRate
|
||||
_phase += dt * countFloat
|
||||
normalizeBLPhase(&_phase)
|
||||
normalizeOscPhase(&_phase)
|
||||
|
||||
let target: Double = _phase < duty ? 1.0 : -1.0
|
||||
|
||||
|
||||
@@ -157,7 +157,7 @@ public enum OscSawtooth {
|
||||
|
||||
let dt: Double = freq / sampleRate
|
||||
_phase += dt * countFloat
|
||||
normalizeBLPhase(&_phase)
|
||||
normalizeOscPhase(&_phase)
|
||||
|
||||
let target: Double = 2.0 * _phase - 1.0
|
||||
|
||||
|
||||
@@ -158,7 +158,7 @@ public enum OscSquare {
|
||||
|
||||
let dt: Double = freq / sampleRate
|
||||
_phase += dt * countFloat
|
||||
normalizeBLPhase(&_phase)
|
||||
normalizeOscPhase(&_phase)
|
||||
|
||||
let target: Double = _phase < oscBLHalfPhase ? 1.0 : -1.0
|
||||
|
||||
|
||||
@@ -169,7 +169,7 @@ public enum OscTriangle {
|
||||
|
||||
let dt: Double = freq / sampleRate
|
||||
_phase += dt * countFloat
|
||||
normalizeBLPhase(&_phase)
|
||||
normalizeOscPhase(&_phase)
|
||||
|
||||
let triangleDescendingIntercept: Double = oscBLTriangleSlope - 1.0
|
||||
let target: Double
|
||||
|
||||
@@ -387,7 +387,6 @@ public enum ScannedSynthesizer {
|
||||
private func _applyInitialDisplacement(_ shape: ScannedSynthesizerShape) {
|
||||
let n: Int = _massCount
|
||||
let nFloat: Double = _massCountFloat
|
||||
let twoPi: Double = 2.0 * Double.pi
|
||||
switch shape {
|
||||
case .zeros:
|
||||
// Already zero from init.
|
||||
@@ -395,7 +394,7 @@ public enum ScannedSynthesizer {
|
||||
|
||||
case .sine:
|
||||
for i: Int in 0..<n {
|
||||
_positions[i] = sin(twoPi * Double(i) / nFloat)
|
||||
_positions[i] = sin(lyrebirdTwoPi * Double(i) / nFloat)
|
||||
}
|
||||
|
||||
case .impulse:
|
||||
|
||||
@@ -144,10 +144,9 @@ public enum Jitter {
|
||||
|
||||
// One-pole smoothing coefficient: exp(-2π × speed × dt)
|
||||
// dt = count / sampleRate seconds (one audio block).
|
||||
let twoPi: Double = 2.0 * Double.pi
|
||||
let dt: Double = Double(count) / sampleRate
|
||||
let safeSpeed: Double = max(0.0, speed)
|
||||
let coeff: Double = safeSpeed > 0.0 ? exp(-twoPi * safeSpeed * dt) : 1.0
|
||||
let coeff: Double = safeSpeed > 0.0 ? exp(-lyrebirdTwoPi * safeSpeed * dt) : 1.0
|
||||
|
||||
// Bipolar random step in [-amount, amount], scaled by (1 - coeff) to
|
||||
// inject energy proportional to how fast the smoother will respond.
|
||||
|
||||
@@ -522,3 +522,8 @@ extension ConvolutionReverb.Audio {
|
||||
/// Right output channel (channel 1). Available only when IR has 2+ channels.
|
||||
public var right: ChannelSelect.Audio { self[1] }
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
|
||||
// `GeneratorEnum` conformance is intentionally omitted — this is an Audio-only
|
||||
// generator with no paired `Control` variant.
|
||||
|
||||
@@ -284,3 +284,8 @@ extension FreeVerb.Audio {
|
||||
/// Right output channel (channel 1). Equivalent to `self[1]`.
|
||||
public var right: ChannelSelect.Audio { self[1] }
|
||||
}
|
||||
|
||||
// MARK: - GeneratorEnum
|
||||
|
||||
// `GeneratorEnum` conformance is intentionally omitted — this is an Audio-only
|
||||
// generator with no paired `Control` variant.
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user