Music XML updates and optimizations
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
# Live coding with `LyrebirdScratchView`
|
||||
|
||||
A SwiftUI scratchpad for hot-swapping snippets through `LyrebirdLiveCompile`.
|
||||
|
||||
## Overview
|
||||
|
||||
`LyrebirdScratchView` pairs an `NSTextView`-backed Swift editor with a `LiveSession`
|
||||
that owns the audio engine. Pressing **⌘↩** wraps the snippet body in the standard
|
||||
harness, shells out to `swiftc`, `dlopen`s the resulting dylib, and calls the
|
||||
snippet's `lyrebird_snippet_entry` with a `SnippetContext` bound to the session.
|
||||
Synthesizers played via `context.play(_:)` are tracked, so the next non-additive
|
||||
run replaces them. **⌘⇧↩** layers a new snippet on top of the prior ones.
|
||||
|
||||
Compile diagnostics from a failing snippet are parsed by `DiagnosticParser`
|
||||
and rendered beneath the editor with line numbers already remapped from the wrapped
|
||||
source back to the user's snippet coordinates.
|
||||
|
||||
The view is macOS-only — `LyrebirdLiveCompile` shells out to `swiftc`, which is
|
||||
unavailable on iOS. The nested `LiveCompile/` sub-package declares
|
||||
`platforms: [.macOS(.v15)]` and cannot be added to an iOS target.
|
||||
|
||||
## Hosting
|
||||
|
||||
```swift
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI // LyrebirdWindow
|
||||
import LyrebirdLiveCompile // LiveSession
|
||||
import LyrebirdLiveCompileUI // LyrebirdScratchView
|
||||
|
||||
let engine = SynthesisEngine(/* … */)
|
||||
try engine.start()
|
||||
|
||||
let session = LiveSession(engine: engine)
|
||||
let window = LyrebirdWindow(title: "Lyrebird Scratch", width: 640, height: 480)
|
||||
window.open {
|
||||
LyrebirdScratchView(session: session)
|
||||
}
|
||||
```
|
||||
|
||||
## Keyboard shortcuts
|
||||
|
||||
| Shortcut | Action |
|
||||
|----------|--------|
|
||||
| ⌘↩ | Compile + run. Removes synths from the previous run before executing. |
|
||||
| ⌘⇧↩ | Compile + run additively. Keeps previously played synths in the engine. |
|
||||
|
||||
The toolbar exposes both as buttons plus a `Clear Synths` button that calls
|
||||
`LiveSession.clearTracked()` directly.
|
||||
|
||||
## Snippet API surface
|
||||
|
||||
A snippet has one local in scope:
|
||||
|
||||
```swift
|
||||
context: SnippetContext
|
||||
```
|
||||
|
||||
`SnippetContext` is intentionally minimal in v1:
|
||||
|
||||
- `context.engine` — the host `SynthesisEngine`.
|
||||
- `context.play(_:)` — add a `Synthesizer` to the engine and register it for
|
||||
cleanup on the next non-additive run.
|
||||
- `context.reportMessage(_:)` — write back to the host (used by tests; handy for
|
||||
`print`-style probes during development).
|
||||
|
||||
## Threading
|
||||
|
||||
All UI is `@MainActor`-isolated. `LiveSession.compileAndRun` is invoked
|
||||
synchronously inside the button action, so the editor freezes for the duration
|
||||
of the `swiftc` invocation (≈ 1 second cold, much faster on warm cache). v1
|
||||
accepts that trade-off; an off-main compile path is on the polish list.
|
||||
|
||||
## Limitations
|
||||
|
||||
- macOS only.
|
||||
- No syntax highlighting, code completion, or line-number gutter (deferred).
|
||||
- Compiled dylibs are leaked by design — types in a loaded snippet may still be
|
||||
referenced by tracked synths; unloading is unsafe.
|
||||
- The host `.app` must not be sandboxed and must allow library validation to be
|
||||
disabled, since `swiftc` is invoked via `Process` and the resulting unsigned
|
||||
dylib is `dlopen`'d.
|
||||
|
||||
## Topics
|
||||
|
||||
- ``LyrebirdScratchView``
|
||||
- ``LyrebirdScratchModel``
|
||||
@@ -0,0 +1,288 @@
|
||||
// LyrebirdScratchMenuController.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import AppKit
|
||||
import UniformTypeIdentifiers
|
||||
import LyrebirdSynth
|
||||
import LyrebirdLiveCompile
|
||||
|
||||
/// Builds and installs the macOS application menu bar for a live-coding host
|
||||
/// driven by a `LyrebirdScratchModel`. Owns the action targets so menu items
|
||||
/// stay wired for the lifetime of the controller.
|
||||
@MainActor
|
||||
public final class LyrebirdScratchMenuController: NSObject {
|
||||
|
||||
public let model: LyrebirdScratchModel
|
||||
|
||||
public init(model: LyrebirdScratchModel) {
|
||||
self.model = model
|
||||
}
|
||||
|
||||
/// Construct the full menu bar (App / File / Edit / Run / View / Window /
|
||||
/// Help) and assign it to `NSApplication.shared.mainMenu`.
|
||||
public func installMainMenu(appName: String = "LyrebirdScratchDemo") {
|
||||
let mainMenu: NSMenu = NSMenu()
|
||||
|
||||
mainMenu.addItem(appMenuItem(appName: appName))
|
||||
mainMenu.addItem(fileMenuItem())
|
||||
mainMenu.addItem(editMenuItem())
|
||||
mainMenu.addItem(runMenuItem())
|
||||
mainMenu.addItem(viewMenuItem())
|
||||
mainMenu.addItem(windowMenuItem())
|
||||
|
||||
NSApplication.shared.mainMenu = mainMenu
|
||||
}
|
||||
|
||||
// MARK: App menu
|
||||
|
||||
private func appMenuItem(appName: String) -> NSMenuItem {
|
||||
let item: NSMenuItem = NSMenuItem()
|
||||
let menu: NSMenu = NSMenu(title: appName)
|
||||
menu.addItem(NSMenuItem(title: "About \(appName)",
|
||||
action: #selector(NSApplication.orderFrontStandardAboutPanel(_:)),
|
||||
keyEquivalent: ""))
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
let services: NSMenuItem = NSMenuItem(title: "Services", action: nil, keyEquivalent: "")
|
||||
let servicesMenu: NSMenu = NSMenu(title: "Services")
|
||||
services.submenu = servicesMenu
|
||||
NSApplication.shared.servicesMenu = servicesMenu
|
||||
menu.addItem(services)
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(NSMenuItem(title: "Hide \(appName)",
|
||||
action: #selector(NSApplication.hide(_:)),
|
||||
keyEquivalent: "h"))
|
||||
let hideOthers: NSMenuItem = NSMenuItem(title: "Hide Others",
|
||||
action: #selector(NSApplication.hideOtherApplications(_:)),
|
||||
keyEquivalent: "h")
|
||||
hideOthers.keyEquivalentModifierMask = [.command, .option]
|
||||
menu.addItem(hideOthers)
|
||||
menu.addItem(NSMenuItem(title: "Show All",
|
||||
action: #selector(NSApplication.unhideAllApplications(_:)),
|
||||
keyEquivalent: ""))
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(NSMenuItem(title: "Quit \(appName)",
|
||||
action: #selector(NSApplication.terminate(_:)),
|
||||
keyEquivalent: "q"))
|
||||
item.submenu = menu
|
||||
return item
|
||||
}
|
||||
|
||||
// MARK: File menu
|
||||
|
||||
private func fileMenuItem() -> NSMenuItem {
|
||||
let item: NSMenuItem = NSMenuItem()
|
||||
let menu: NSMenu = NSMenu(title: "File")
|
||||
menu.addItem(target(NSMenuItem(title: "New",
|
||||
action: #selector(newSnippet(_:)),
|
||||
keyEquivalent: "n")))
|
||||
menu.addItem(target(NSMenuItem(title: "Open…",
|
||||
action: #selector(openSnippet(_:)),
|
||||
keyEquivalent: "o")))
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(target(NSMenuItem(title: "Save",
|
||||
action: #selector(saveSnippet(_:)),
|
||||
keyEquivalent: "s")))
|
||||
let saveAs: NSMenuItem = NSMenuItem(title: "Save As…",
|
||||
action: #selector(saveSnippetAs(_:)),
|
||||
keyEquivalent: "s")
|
||||
saveAs.keyEquivalentModifierMask = [.command, .shift]
|
||||
menu.addItem(target(saveAs))
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(NSMenuItem(title: "Close",
|
||||
action: #selector(NSWindow.performClose(_:)),
|
||||
keyEquivalent: "w"))
|
||||
item.submenu = menu
|
||||
return item
|
||||
}
|
||||
|
||||
// MARK: Edit menu — wires to the first responder so NSTextView gets it
|
||||
|
||||
private func editMenuItem() -> NSMenuItem {
|
||||
let item: NSMenuItem = NSMenuItem()
|
||||
let menu: NSMenu = NSMenu(title: "Edit")
|
||||
menu.addItem(NSMenuItem(title: "Undo",
|
||||
action: Selector(("undo:")),
|
||||
keyEquivalent: "z"))
|
||||
let redo: NSMenuItem = NSMenuItem(title: "Redo",
|
||||
action: Selector(("redo:")),
|
||||
keyEquivalent: "z")
|
||||
redo.keyEquivalentModifierMask = [.command, .shift]
|
||||
menu.addItem(redo)
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(NSMenuItem(title: "Cut",
|
||||
action: #selector(NSText.cut(_:)),
|
||||
keyEquivalent: "x"))
|
||||
menu.addItem(NSMenuItem(title: "Copy",
|
||||
action: #selector(NSText.copy(_:)),
|
||||
keyEquivalent: "c"))
|
||||
menu.addItem(NSMenuItem(title: "Paste",
|
||||
action: #selector(NSText.paste(_:)),
|
||||
keyEquivalent: "v"))
|
||||
menu.addItem(NSMenuItem(title: "Select All",
|
||||
action: #selector(NSText.selectAll(_:)),
|
||||
keyEquivalent: "a"))
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
let find: NSMenuItem = NSMenuItem(title: "Find…",
|
||||
action: #selector(NSTextView.performFindPanelAction(_:)),
|
||||
keyEquivalent: "f")
|
||||
find.tag = Int(NSFindPanelAction.showFindPanel.rawValue)
|
||||
menu.addItem(find)
|
||||
item.submenu = menu
|
||||
return item
|
||||
}
|
||||
|
||||
// MARK: Run menu
|
||||
|
||||
private func runMenuItem() -> NSMenuItem {
|
||||
let item: NSMenuItem = NSMenuItem()
|
||||
let menu: NSMenu = NSMenu(title: "Run")
|
||||
menu.addItem(target(NSMenuItem(title: "Run",
|
||||
action: #selector(runSnippet(_:)),
|
||||
keyEquivalent: "\r")))
|
||||
let runAdd: NSMenuItem = NSMenuItem(title: "Run Additive",
|
||||
action: #selector(runSnippetAdditive(_:)),
|
||||
keyEquivalent: "\r")
|
||||
runAdd.keyEquivalentModifierMask = [.command, .shift]
|
||||
menu.addItem(target(runAdd))
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(target(NSMenuItem(title: "Clear Tracked Synths",
|
||||
action: #selector(clearSynths(_:)),
|
||||
keyEquivalent: "k")))
|
||||
item.submenu = menu
|
||||
return item
|
||||
}
|
||||
|
||||
// MARK: View menu
|
||||
|
||||
private func viewMenuItem() -> NSMenuItem {
|
||||
let item: NSMenuItem = NSMenuItem()
|
||||
let menu: NSMenu = NSMenu(title: "View")
|
||||
let wrap: NSMenuItem = target(NSMenuItem(title: "Wrap Lines",
|
||||
action: #selector(toggleWrap(_:)),
|
||||
keyEquivalent: "l"))
|
||||
wrap.keyEquivalentModifierMask = [.command, .option]
|
||||
menu.addItem(wrap)
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
let inc: NSMenuItem = target(NSMenuItem(title: "Increase Font Size",
|
||||
action: #selector(increaseFontSize(_:)),
|
||||
keyEquivalent: "+"))
|
||||
menu.addItem(inc)
|
||||
menu.addItem(target(NSMenuItem(title: "Decrease Font Size",
|
||||
action: #selector(decreaseFontSize(_:)),
|
||||
keyEquivalent: "-")))
|
||||
menu.addItem(target(NSMenuItem(title: "Reset Font Size",
|
||||
action: #selector(resetFontSize(_:)),
|
||||
keyEquivalent: "0")))
|
||||
item.submenu = menu
|
||||
return item
|
||||
}
|
||||
|
||||
// MARK: Window menu
|
||||
|
||||
private func windowMenuItem() -> NSMenuItem {
|
||||
let item: NSMenuItem = NSMenuItem()
|
||||
let menu: NSMenu = NSMenu(title: "Window")
|
||||
menu.addItem(NSMenuItem(title: "Minimize",
|
||||
action: #selector(NSWindow.performMiniaturize(_:)),
|
||||
keyEquivalent: "m"))
|
||||
menu.addItem(NSMenuItem(title: "Zoom",
|
||||
action: #selector(NSWindow.performZoom(_:)),
|
||||
keyEquivalent: ""))
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(NSMenuItem(title: "Bring All to Front",
|
||||
action: #selector(NSApplication.arrangeInFront(_:)),
|
||||
keyEquivalent: ""))
|
||||
item.submenu = menu
|
||||
NSApplication.shared.windowsMenu = menu
|
||||
return item
|
||||
}
|
||||
|
||||
// MARK: - Action targets
|
||||
|
||||
private func target(_ item: NSMenuItem) -> NSMenuItem {
|
||||
item.target = self
|
||||
return item
|
||||
}
|
||||
|
||||
@objc private func newSnippet(_ sender: Any?) {
|
||||
model.text = LyrebirdScratchModel.defaultPlaceholder
|
||||
}
|
||||
|
||||
@objc private func openSnippet(_ sender: Any?) {
|
||||
let panel: NSOpenPanel = NSOpenPanel()
|
||||
panel.allowedContentTypes = [.swiftSource]
|
||||
panel.allowsMultipleSelection = false
|
||||
panel.canChooseDirectories = false
|
||||
panel.message = "Open a Lyrebird snippet"
|
||||
if panel.runModal() == .OK, let url: URL = panel.url {
|
||||
do {
|
||||
try model.load(from: url)
|
||||
} catch {
|
||||
model.reportLoadError(url: url, error: error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func saveSnippet(_ sender: Any?) {
|
||||
if let url: URL = model.documentURL {
|
||||
do {
|
||||
try model.save(to: url)
|
||||
} catch {
|
||||
model.reportSaveError(url: url, error: error)
|
||||
}
|
||||
return
|
||||
}
|
||||
saveSnippetAs(sender)
|
||||
}
|
||||
|
||||
@objc private func saveSnippetAs(_ sender: Any?) {
|
||||
let panel: NSSavePanel = NSSavePanel()
|
||||
panel.allowedContentTypes = [.swiftSource]
|
||||
panel.nameFieldStringValue = model.documentURL?.lastPathComponent ?? "snippet.swift"
|
||||
panel.message = "Save Lyrebird snippet"
|
||||
if panel.runModal() == .OK, let url: URL = panel.url {
|
||||
do {
|
||||
try model.save(to: url)
|
||||
} catch {
|
||||
model.reportSaveError(url: url, error: error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func runSnippet(_ sender: Any?) {
|
||||
Task { @MainActor in _ = await model.run(additive: false) }
|
||||
}
|
||||
|
||||
@objc private func runSnippetAdditive(_ sender: Any?) {
|
||||
Task { @MainActor in _ = await model.run(additive: true) }
|
||||
}
|
||||
|
||||
@objc private func clearSynths(_ sender: Any?) {
|
||||
model.clearTracked()
|
||||
}
|
||||
|
||||
@objc private func toggleWrap(_ sender: Any?) {
|
||||
model.toggleWrapsLines()
|
||||
if let item: NSMenuItem = sender as? NSMenuItem {
|
||||
item.state = model.wrapsLines ? .on : .off
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func increaseFontSize(_ sender: Any?) {
|
||||
model.bumpFontSize(by: 1)
|
||||
}
|
||||
|
||||
@objc private func decreaseFontSize(_ sender: Any?) {
|
||||
model.bumpFontSize(by: -1)
|
||||
}
|
||||
|
||||
@objc private func resetFontSize(_ sender: Any?) {
|
||||
model.resetFontSize()
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,231 @@
|
||||
// LyrebirdScratchModel.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdUI/LiveCompile
|
||||
//
|
||||
// Backing model for `LyrebirdScratchView`. Owns the editable snippet text, the
|
||||
// most recent compile result, and the host `LiveSession`. Pulled out of the
|
||||
// view so logic can be exercised without instantiating SwiftUI.
|
||||
//
|
||||
// macOS only — wraps `LyrebirdLiveCompile`, which itself is macOS-only.
|
||||
|
||||
#if os(macOS)
|
||||
import Foundation
|
||||
import CoreGraphics
|
||||
import LyrebirdSynth
|
||||
// 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`.
|
||||
///
|
||||
/// Drives one live-coding editor pane. `run(additive:)` awaits
|
||||
/// `LiveSession.compileAndRunAsync` so the swiftc invocation runs off the main
|
||||
/// actor and the editor stays responsive. ``isCompiling`` flips around the
|
||||
/// await so SwiftUI can disable the Run buttons and surface a "Compiling…"
|
||||
/// status while the dylib build is in flight.
|
||||
@MainActor
|
||||
public final class LyrebirdScratchModel: ObservableObject {
|
||||
|
||||
/// Default placeholder text loaded into a fresh model. Walks the user
|
||||
/// through the two keyboard shortcuts and the in-snippet API surface.
|
||||
/// `nonisolated` so callers in a non-main context (e.g. SwiftUI init's
|
||||
/// default-argument evaluation, which is not implicitly main-actor) can
|
||||
/// reference it without a Swift 6 isolation diagnostic.
|
||||
public nonisolated static let defaultPlaceholder: String = """
|
||||
// ⌘↩ — compile + run (removes synths from the previous run first).
|
||||
// ⌘⇧↩ — additive run (keep previously played synths around).
|
||||
//
|
||||
// The snippet body has `context: SnippetContext` in scope.
|
||||
// `context.engine` → the host `SynthesisEngine`.
|
||||
// `context.play(synth)` → adds a `Synthesizer` and tracks it for cleanup.
|
||||
// `context.reportMessage(_)`→ writes back to the host (useful for `print`-style probes).
|
||||
|
||||
class SineSynth: SynthesizerBase {
|
||||
override func build() {
|
||||
let sine = OscSin.Audio(freq: 440, mul: 0.15)
|
||||
let stereo = Pan2(input: sine, pan: 0)
|
||||
output(bus: 0, source: stereo)
|
||||
}
|
||||
}
|
||||
|
||||
let synth = SineSynth()
|
||||
_ = context.play(synth)
|
||||
context.reportMessage("playing 440 Hz sine — stereo, centered")
|
||||
|
||||
"""
|
||||
|
||||
/// Current editor text. View binds to this; user edits flow back here via
|
||||
/// the `NSTextView` delegate inside `LyrebirdScratchView`.
|
||||
@Published public var text: String
|
||||
|
||||
/// Parsed swiftc diagnostics from the last `run(additive:)` invocation.
|
||||
/// Empty when the last run compiled cleanly or has not yet been attempted.
|
||||
@Published public private(set) var diagnostics: [Diagnostic] = []
|
||||
|
||||
/// Single-line human-readable status line shown beneath the editor.
|
||||
/// Updated by `run(additive:)` and `clearTracked()`.
|
||||
@Published public private(set) var statusMessage: String = ""
|
||||
|
||||
/// Mirror of `session.trackedSynthCount`, refreshed after every `run` /
|
||||
/// `clearTracked` call so the toolbar can show the count without polling.
|
||||
@Published public private(set) var trackedSynthCount: Int
|
||||
|
||||
/// `true` while a `run(additive:)` invocation is awaiting the background
|
||||
/// swiftc compile. View code disables Run / Run Additive buttons against
|
||||
/// this so a second compile cannot stack on top of a still-running one.
|
||||
@Published public private(set) var isCompiling: Bool = false
|
||||
|
||||
/// URL of the file the editor text was last saved to or loaded from. `nil`
|
||||
/// when the editor holds unsaved scratch content. The view uses this to
|
||||
/// distinguish a silent overwrite (⌘S) from a Save As… prompt.
|
||||
@Published public private(set) var documentURL: URL?
|
||||
|
||||
/// Editor font size in points. Clamped to `[minFontSize, maxFontSize]`.
|
||||
@Published public var fontSize: CGFloat = 13
|
||||
|
||||
/// When `true`, lines wrap at the editor's right edge instead of scrolling
|
||||
/// horizontally.
|
||||
@Published public var wrapsLines: Bool = true
|
||||
|
||||
public let session: LiveSession
|
||||
|
||||
public nonisolated static let minFontSize: CGFloat = 9
|
||||
public nonisolated static let maxFontSize: CGFloat = 32
|
||||
public nonisolated static let defaultFontSize: CGFloat = 13
|
||||
|
||||
public func bumpFontSize(by delta: CGFloat) {
|
||||
fontSize = max(LyrebirdScratchModel.minFontSize,
|
||||
min(LyrebirdScratchModel.maxFontSize, fontSize + delta))
|
||||
}
|
||||
|
||||
public func resetFontSize() {
|
||||
fontSize = LyrebirdScratchModel.defaultFontSize
|
||||
}
|
||||
|
||||
public func toggleWrapsLines() {
|
||||
wrapsLines.toggle()
|
||||
}
|
||||
|
||||
/// - Parameters:
|
||||
/// - session: Host `LiveSession` the model forwards compile + cleanup
|
||||
/// calls to. Retained for the model's lifetime.
|
||||
/// - initialText: Seed text loaded into `text`. Defaults to
|
||||
/// ``defaultPlaceholder``.
|
||||
public init(
|
||||
session: LiveSession,
|
||||
initialText: String = LyrebirdScratchModel.defaultPlaceholder
|
||||
) {
|
||||
self.session = session
|
||||
self.text = initialText
|
||||
self.trackedSynthCount = session.trackedSynthCount
|
||||
}
|
||||
|
||||
/// Compile and execute the current `text`. Updates `diagnostics`,
|
||||
/// `statusMessage`, `trackedSynthCount`, and ``isCompiling``.
|
||||
///
|
||||
/// Awaits `LiveSession.compileAndRunAsync`, which runs swiftc on a
|
||||
/// `Task.detached`. The view's Run / Run Additive buttons bind to
|
||||
/// ``isCompiling`` and stay disabled until this method returns.
|
||||
///
|
||||
/// - Parameter additive: When `false`, the session removes every
|
||||
/// previously tracked synth before running. When `true`, prior synths
|
||||
/// stay in the engine (⌘⇧↩ in the view).
|
||||
/// - Returns: `true` when the snippet compiled and its entry returned
|
||||
/// without throwing; `false` otherwise.
|
||||
@discardableResult
|
||||
public func run(additive: Bool) async -> Bool {
|
||||
guard !isCompiling else { return false }
|
||||
let body: String = text
|
||||
diagnostics = []
|
||||
statusMessage = "Compiling…"
|
||||
isCompiling = true
|
||||
defer {
|
||||
isCompiling = false
|
||||
trackedSynthCount = session.trackedSynthCount
|
||||
}
|
||||
do {
|
||||
try await session.compileAndRunAsync(body, additive: additive)
|
||||
let mode: String = additive ? "additive" : "replaced"
|
||||
statusMessage = "Ran (\(mode)). Tracked synths: \(session.trackedSynthCount)."
|
||||
return true
|
||||
} catch let sessionError as LiveSessionError {
|
||||
switch sessionError {
|
||||
case .snippetCompileFailed(let diags, let underlying):
|
||||
if diags.isEmpty {
|
||||
diagnostics = [Diagnostic(
|
||||
line: nil,
|
||||
column: 0,
|
||||
severity: .error,
|
||||
message: "\(underlying)",
|
||||
rawLine: 0
|
||||
)]
|
||||
statusMessage = "Compile failed — see diagnostics below."
|
||||
} else {
|
||||
diagnostics = diags
|
||||
let plural: String = diags.count == 1 ? "" : "s"
|
||||
statusMessage = "Compile failed — \(diags.count) diagnostic\(plural)."
|
||||
}
|
||||
case .compilerError(let underlying):
|
||||
statusMessage = "Compiler error: \(underlying)"
|
||||
}
|
||||
return false
|
||||
} catch {
|
||||
statusMessage = "Error: \(error)"
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Forward to `LiveSession.clearTracked()` and refresh `trackedSynthCount`.
|
||||
public func clearTracked() {
|
||||
session.clearTracked()
|
||||
trackedSynthCount = session.trackedSynthCount
|
||||
statusMessage = "Cleared tracked synths."
|
||||
}
|
||||
|
||||
// MARK: - Snippet save / load
|
||||
|
||||
/// Replace `text` with the UTF-8 contents at `url`, set ``documentURL``
|
||||
/// for subsequent saves, and refresh the status line.
|
||||
///
|
||||
/// - Parameter url: File to read. Caller (view) is responsible for the
|
||||
/// `NSOpenPanel` UI; this method does the IO.
|
||||
public func load(from url: URL) throws {
|
||||
let loaded: String = try String(contentsOf: url, encoding: .utf8)
|
||||
text = loaded
|
||||
documentURL = url
|
||||
diagnostics = []
|
||||
statusMessage = "Loaded \(url.lastPathComponent)."
|
||||
}
|
||||
|
||||
/// Write `text` to `url` as UTF-8, set ``documentURL``, refresh status.
|
||||
///
|
||||
/// - Parameter url: Destination. Overwrites if present. Caller drives the
|
||||
/// `NSSavePanel` UI.
|
||||
public func save(to url: URL) throws {
|
||||
try text.write(to: url, atomically: true, encoding: .utf8)
|
||||
documentURL = url
|
||||
statusMessage = "Saved \(url.lastPathComponent)."
|
||||
}
|
||||
|
||||
/// Surface a load failure on the status line without throwing across the
|
||||
/// view layer. Called by the view after `NSOpenPanel` returned a URL that
|
||||
/// `load(from:)` rejected.
|
||||
public func reportLoadError(url: URL, error: Error) {
|
||||
statusMessage = "Load failed (\(url.lastPathComponent)): \(error.localizedDescription)"
|
||||
}
|
||||
|
||||
/// Surface a save failure on the status line without throwing across the
|
||||
/// view layer. Called by the view after `NSSavePanel` returned a URL that
|
||||
/// `save(to:)` rejected.
|
||||
public func reportSaveError(url: URL, error: Error) {
|
||||
statusMessage = "Save failed (\(url.lastPathComponent)): \(error.localizedDescription)"
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,409 @@
|
||||
// LyrebirdScratchView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdUI/LiveCompile
|
||||
//
|
||||
// `LyrebirdScratchView` — SwiftUI scratchpad editor for live-coded snippets.
|
||||
// Wraps an `NSTextView` for the editor surface, drives a `LyrebirdScratchModel`
|
||||
// for compile state, and surfaces parsed `Diagnostic`s in a scrollable list
|
||||
// below the editor. macOS-only; iOS hosting is deferred (no swiftc on device).
|
||||
|
||||
#if os(macOS)
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
import UniformTypeIdentifiers
|
||||
import LyrebirdSynth
|
||||
import LyrebirdLiveCompile
|
||||
|
||||
/// SwiftUI scratchpad for live-compiled Lyrebird snippets.
|
||||
///
|
||||
/// Pair with a `LiveSession` that owns the audio engine, drop the view into a
|
||||
/// `LyrebirdWindow`, and ⌘↩ replaces the prior run while ⌘⇧↩ adds to it.
|
||||
/// Diagnostics from a failed compile are listed under the editor with the
|
||||
/// user's snippet-row coordinates already mapped by `DiagnosticParser`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - session: Host `LiveSession` owning the `SynthesisEngine`. Forwarded
|
||||
/// into the backing ``LyrebirdScratchModel``.
|
||||
/// - initialText: Seed text loaded into the editor. Defaults to
|
||||
/// ``LyrebirdScratchModel/defaultPlaceholder``.
|
||||
///
|
||||
/// ## Hosting
|
||||
///
|
||||
/// ```swift
|
||||
/// import LyrebirdUI // LyrebirdWindow
|
||||
/// import LyrebirdLiveCompile // LiveSession
|
||||
/// import LyrebirdLiveCompileUI // LyrebirdScratchView
|
||||
///
|
||||
/// let session = LiveSession(engine: engine)
|
||||
/// let win = LyrebirdWindow(title: "Lyrebird Scratch", width: 640, height: 480)
|
||||
/// win.open { LyrebirdScratchView(session: session) }
|
||||
/// ```
|
||||
///
|
||||
/// ## Threading
|
||||
///
|
||||
/// All UI work is `@MainActor`-isolated. The Run / Run Additive buttons
|
||||
/// dispatch a `Task` that awaits `LyrebirdScratchModel.run(additive:)`, which
|
||||
/// itself awaits `LiveSession.compileAndRunAsync`. The swiftc subprocess runs
|
||||
/// on a background `Task.detached`; the snippet entry then resumes on the
|
||||
/// main actor so it can touch UI-side state. Both Run buttons disable while
|
||||
/// ``LyrebirdScratchModel/isCompiling`` is `true`.
|
||||
@MainActor
|
||||
public struct LyrebirdScratchView: View {
|
||||
|
||||
@StateObject private var model: LyrebirdScratchModel
|
||||
@State private var engineTick: Int = 0
|
||||
private let engineRefresh = Timer.publish(every: 0.5, on: .main, in: .common).autoconnect()
|
||||
|
||||
/// Construct with a fresh `LyrebirdScratchModel` wrapping `session`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - session: Host live-coding session owning the audio engine. The view
|
||||
/// does not retain a reference of its own; the wrapped model does.
|
||||
/// - initialText: Seed text loaded into the editor. Defaults to the
|
||||
/// onboarding placeholder explaining the two keyboard shortcuts.
|
||||
public init(
|
||||
session: LiveSession,
|
||||
initialText: String = LyrebirdScratchModel.defaultPlaceholder
|
||||
) {
|
||||
_model = StateObject(wrappedValue: LyrebirdScratchModel(
|
||||
session: session,
|
||||
initialText: initialText
|
||||
))
|
||||
}
|
||||
|
||||
/// Construct against a pre-built model. Lets tests or alternate hosts
|
||||
/// inject a model with custom session, text, or pre-populated state.
|
||||
public init(model: LyrebirdScratchModel) {
|
||||
_model = StateObject(wrappedValue: model)
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
engineBar
|
||||
Divider()
|
||||
ScratchEditor(
|
||||
text: Binding(
|
||||
get: { model.text },
|
||||
set: { model.text = $0 }
|
||||
),
|
||||
fontSize: model.fontSize,
|
||||
wrapsLines: model.wrapsLines
|
||||
)
|
||||
.frame(minHeight: editorMinHeight)
|
||||
Divider()
|
||||
statusBar
|
||||
if !model.diagnostics.isEmpty {
|
||||
Divider()
|
||||
diagnosticsList
|
||||
}
|
||||
}
|
||||
.frame(minWidth: scratchMinWidth, minHeight: scratchMinHeight)
|
||||
.onReceive(engineRefresh) { _ in engineTick &+= 1 }
|
||||
}
|
||||
|
||||
private var engineBar: some View {
|
||||
let engine: SynthesisEngine = model.session.engine
|
||||
return HStack(spacing: toolbarSpacing) {
|
||||
Circle()
|
||||
.fill(engine.isRunning ? Color.green : Color.red)
|
||||
.frame(width: engineDotSize, height: engineDotSize)
|
||||
Text(engine.isRunning ? "engine running" : "engine stopped")
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
Spacer()
|
||||
Text("\(Int(engine.sampleRate)) Hz · \(engine.numOutputChannels) ch · CPU \(formatCPU(engine.averageCPU))")
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
Spacer().frame(width: 8)
|
||||
Text("synths: \(model.trackedSynthCount)")
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.padding(.horizontal, toolbarPadding)
|
||||
.padding(.vertical, 6)
|
||||
.id(engineTick)
|
||||
}
|
||||
|
||||
private func formatCPU(_ value: Double) -> String {
|
||||
String(format: "%.0f%%", value * 100)
|
||||
}
|
||||
|
||||
public func runSnippet(additive: Bool) {
|
||||
Task { @MainActor in
|
||||
_ = await model.run(additive: additive)
|
||||
}
|
||||
}
|
||||
|
||||
public func presentOpenPanel() {
|
||||
let panel: NSOpenPanel = NSOpenPanel()
|
||||
panel.allowedContentTypes = [.swiftSource]
|
||||
panel.allowsMultipleSelection = false
|
||||
panel.canChooseDirectories = false
|
||||
panel.message = "Open a Lyrebird snippet"
|
||||
if panel.runModal() == .OK, let url: URL = panel.url {
|
||||
do {
|
||||
try model.load(from: url)
|
||||
} catch {
|
||||
model.reportLoadError(url: url, error: error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func saveOrPromptForLocation() {
|
||||
if let url: URL = model.documentURL {
|
||||
do {
|
||||
try model.save(to: url)
|
||||
} catch {
|
||||
model.reportSaveError(url: url, error: error)
|
||||
}
|
||||
return
|
||||
}
|
||||
presentSavePanel()
|
||||
}
|
||||
|
||||
public func presentSavePanel() {
|
||||
let panel: NSSavePanel = NSSavePanel()
|
||||
panel.allowedContentTypes = [.swiftSource]
|
||||
panel.nameFieldStringValue = model.documentURL?.lastPathComponent ?? "snippet.swift"
|
||||
panel.message = "Save Lyrebird snippet"
|
||||
if panel.runModal() == .OK, let url: URL = panel.url {
|
||||
do {
|
||||
try model.save(to: url)
|
||||
} catch {
|
||||
model.reportSaveError(url: url, error: error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var statusBar: some View {
|
||||
HStack {
|
||||
Text(model.statusMessage.isEmpty ? "Ready." : model.statusMessage)
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
.lineLimit(1)
|
||||
.truncationMode(.middle)
|
||||
Spacer()
|
||||
}
|
||||
.padding(.horizontal, statusHPad)
|
||||
.padding(.vertical, statusVPad)
|
||||
}
|
||||
|
||||
private var diagnosticsList: some View {
|
||||
ScrollView {
|
||||
LazyVStack(alignment: .leading, spacing: diagnosticRowSpacing) {
|
||||
ForEach(Array(model.diagnostics.enumerated()), id: \.offset) { _, diag in
|
||||
DiagnosticRow(diagnostic: diag)
|
||||
}
|
||||
}
|
||||
.padding(diagnosticListPadding)
|
||||
}
|
||||
.frame(minHeight: diagnosticsMinHeight, maxHeight: diagnosticsMaxHeight)
|
||||
}
|
||||
|
||||
// Layout constants — all in points. Kept private; tuned to match
|
||||
// LyrebirdEngineStatusView's visual density.
|
||||
private let scratchMinWidth: CGFloat = 520
|
||||
private let scratchMinHeight: CGFloat = 420
|
||||
private let editorMinHeight: CGFloat = 240
|
||||
private let toolbarSpacing: CGFloat = 8
|
||||
private let toolbarPadding: CGFloat = 8
|
||||
private let toolbarDividerHeight: CGFloat = 18
|
||||
private let statusHPad: CGFloat = 8
|
||||
private let statusVPad: CGFloat = 4
|
||||
private let diagnosticRowSpacing: CGFloat = 2
|
||||
private let diagnosticListPadding: CGFloat = 8
|
||||
private let diagnosticsMinHeight: CGFloat = 80
|
||||
private let diagnosticsMaxHeight: CGFloat = 200
|
||||
private let engineDotSize: CGFloat = 8
|
||||
}
|
||||
|
||||
/// One row in the diagnostics list. Renders `(line:col)`, severity, and
|
||||
/// message in a compact monospaced row.
|
||||
private struct DiagnosticRow: View {
|
||||
|
||||
let diagnostic: Diagnostic
|
||||
|
||||
var body: some View {
|
||||
HStack(alignment: .firstTextBaseline, spacing: rowGutter) {
|
||||
Text(locationString)
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(minWidth: locationColumnWidth, alignment: .leading)
|
||||
Text(diagnostic.severity.rawValue)
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(color(for: diagnostic.severity))
|
||||
.frame(minWidth: severityColumnWidth, alignment: .leading)
|
||||
Text(diagnostic.message)
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.textSelection(.enabled)
|
||||
.multilineTextAlignment(.leading)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
}
|
||||
|
||||
private var locationString: String {
|
||||
if let line: Int = diagnostic.line {
|
||||
return "\(line):\(diagnostic.column)"
|
||||
}
|
||||
return "preamble:\(diagnostic.rawLine):\(diagnostic.column)"
|
||||
}
|
||||
|
||||
private func color(for severity: DiagnosticSeverity) -> Color {
|
||||
switch severity {
|
||||
case .error: return .red
|
||||
case .warning: return .orange
|
||||
case .note: return .secondary
|
||||
}
|
||||
}
|
||||
|
||||
private let rowGutter: CGFloat = 8
|
||||
private let locationColumnWidth: CGFloat = 80
|
||||
private let severityColumnWidth: CGFloat = 56
|
||||
}
|
||||
|
||||
/// `NSViewRepresentable` wrapping a vanilla `NSTextView` inside an
|
||||
/// `NSScrollView`. Monospaced 13 pt, plain text, no smart-quote / dash /
|
||||
/// auto-correct interference — matches the editor expectations of someone
|
||||
/// typing Swift code.
|
||||
private struct ScratchEditor: NSViewRepresentable {
|
||||
|
||||
@Binding var text: String
|
||||
let fontSize: CGFloat
|
||||
let wrapsLines: Bool
|
||||
|
||||
final class Coordinator: NSObject, NSTextViewDelegate {
|
||||
var parent: ScratchEditor
|
||||
init(_ parent: ScratchEditor) { self.parent = parent }
|
||||
|
||||
func textDidChange(_ notification: Notification) {
|
||||
guard let tv: NSTextView = notification.object as? NSTextView else { return }
|
||||
parent.text = tv.string
|
||||
}
|
||||
}
|
||||
|
||||
func makeCoordinator() -> Coordinator { Coordinator(self) }
|
||||
|
||||
func makeNSView(context: Context) -> NSScrollView {
|
||||
let scroll: NSScrollView = NSTextView.scrollableTextView()
|
||||
if let tv: NSTextView = scroll.documentView as? NSTextView {
|
||||
configure(tv, in: scroll, with: context.coordinator)
|
||||
}
|
||||
return scroll
|
||||
}
|
||||
|
||||
func updateNSView(_ scroll: NSScrollView, context: Context) {
|
||||
context.coordinator.parent = self
|
||||
guard let tv: NSTextView = scroll.documentView as? NSTextView else { return }
|
||||
let font: NSFont = NSFont.monospacedSystemFont(ofSize: fontSize, weight: .regular)
|
||||
let fontChanged: Bool = (tv.font?.pointSize ?? -1) != fontSize
|
||||
if fontChanged {
|
||||
tv.font = font
|
||||
}
|
||||
let paragraphStyle: NSParagraphStyle = makeParagraphStyle(for: font)
|
||||
tv.defaultParagraphStyle = paragraphStyle
|
||||
tv.typingAttributes = makeAttrs(font: font, paragraph: paragraphStyle)
|
||||
applyWrap(to: tv, in: scroll)
|
||||
if tv.string != text {
|
||||
replaceText(in: tv, with: text, font: font, paragraph: paragraphStyle)
|
||||
} else if fontChanged {
|
||||
reapplyAttrs(to: tv, font: font, paragraph: paragraphStyle)
|
||||
}
|
||||
}
|
||||
|
||||
private func makeAttrs(font: NSFont, paragraph: NSParagraphStyle) -> [NSAttributedString.Key: Any] {
|
||||
[
|
||||
.font: font,
|
||||
.foregroundColor: NSColor.labelColor,
|
||||
.paragraphStyle: paragraph,
|
||||
]
|
||||
}
|
||||
|
||||
private func makeParagraphStyle(for font: NSFont) -> NSParagraphStyle {
|
||||
let style: NSMutableParagraphStyle = NSMutableParagraphStyle()
|
||||
let spaceAdvance: CGFloat = (" " as NSString).size(withAttributes: [.font: font]).width
|
||||
let tabWidth: CGFloat = spaceAdvance * tabSpaces
|
||||
style.tabStops = []
|
||||
style.defaultTabInterval = tabWidth
|
||||
return style
|
||||
}
|
||||
|
||||
private func replaceText(in tv: NSTextView,
|
||||
with newText: String,
|
||||
font: NSFont,
|
||||
paragraph: NSParagraphStyle) {
|
||||
let attrs: [NSAttributedString.Key : Any] = makeAttrs(font: font, paragraph: paragraph)
|
||||
let attributed: NSAttributedString = NSAttributedString(string: newText, attributes: attrs)
|
||||
tv.textStorage?.setAttributedString(attributed)
|
||||
tv.typingAttributes = attrs
|
||||
}
|
||||
|
||||
private func reapplyAttrs(to tv: NSTextView,
|
||||
font: NSFont,
|
||||
paragraph: NSParagraphStyle) {
|
||||
guard let storage: NSTextStorage = tv.textStorage else { return }
|
||||
let attrs: [NSAttributedString.Key : Any] = makeAttrs(font: font, paragraph: paragraph)
|
||||
let range: NSRange = NSRange(location: 0, length: storage.length)
|
||||
storage.setAttributes(attrs, range: range)
|
||||
tv.typingAttributes = attrs
|
||||
}
|
||||
|
||||
private func applyWrap(to tv: NSTextView, in scroll: NSScrollView) {
|
||||
guard let container: NSTextContainer = tv.textContainer else { return }
|
||||
if wrapsLines {
|
||||
scroll.hasHorizontalScroller = false
|
||||
tv.isHorizontallyResizable = false
|
||||
tv.autoresizingMask = [.width]
|
||||
container.widthTracksTextView = true
|
||||
container.containerSize = NSSize(width: CGFloat.greatestFiniteMagnitude,
|
||||
height: CGFloat.greatestFiniteMagnitude)
|
||||
} else {
|
||||
scroll.hasHorizontalScroller = true
|
||||
tv.isHorizontallyResizable = true
|
||||
tv.autoresizingMask = []
|
||||
container.widthTracksTextView = false
|
||||
container.containerSize = NSSize(width: CGFloat.greatestFiniteMagnitude,
|
||||
height: CGFloat.greatestFiniteMagnitude)
|
||||
tv.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude,
|
||||
height: CGFloat.greatestFiniteMagnitude)
|
||||
}
|
||||
tv.needsDisplay = true
|
||||
}
|
||||
|
||||
private func configure(_ tv: NSTextView, in scroll: NSScrollView, with coordinator: Coordinator) {
|
||||
tv.delegate = coordinator
|
||||
let editorFont: NSFont = NSFont.monospacedSystemFont(ofSize: fontSize, weight: .regular)
|
||||
tv.font = editorFont
|
||||
tv.isRichText = false
|
||||
tv.isAutomaticQuoteSubstitutionEnabled = false
|
||||
tv.isAutomaticDashSubstitutionEnabled = false
|
||||
tv.isAutomaticTextReplacementEnabled = false
|
||||
tv.isAutomaticSpellingCorrectionEnabled = false
|
||||
tv.smartInsertDeleteEnabled = false
|
||||
tv.allowsUndo = true
|
||||
tv.usesFindBar = true
|
||||
tv.textContainerInset = NSSize(width: editorInset, height: editorInset)
|
||||
tv.drawsBackground = true
|
||||
tv.backgroundColor = .textBackgroundColor
|
||||
tv.textColor = .labelColor
|
||||
tv.insertionPointColor = .labelColor
|
||||
tv.selectedTextAttributes = [
|
||||
.backgroundColor: NSColor.selectedTextBackgroundColor,
|
||||
.foregroundColor: NSColor.selectedTextColor,
|
||||
]
|
||||
let paragraphStyle: NSParagraphStyle = makeParagraphStyle(for: editorFont)
|
||||
tv.defaultParagraphStyle = paragraphStyle
|
||||
tv.typingAttributes = makeAttrs(font: editorFont, paragraph: paragraphStyle)
|
||||
applyWrap(to: tv, in: scroll)
|
||||
replaceText(in: tv, with: text, font: editorFont, paragraph: paragraphStyle)
|
||||
}
|
||||
|
||||
private let editorInset: CGFloat = 6
|
||||
private let tabSpaces: CGFloat = 4
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,145 @@
|
||||
// ScratchLineNumberRuler.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdUI/LiveCompile
|
||||
//
|
||||
// Vertical line-number gutter for `ScratchEditor`'s `NSTextView`. Installed as
|
||||
// the scroll view's `verticalRulerView` so it tracks scroll position for free.
|
||||
// Reads laid-out glyph rects from the text view's layout manager and writes one
|
||||
// 1-based line label per visible line into the ruler's bounds.
|
||||
|
||||
#if os(macOS)
|
||||
import AppKit
|
||||
|
||||
/// `NSRulerView` subclass rendering one right-aligned line number per laid-out
|
||||
/// line of the host `NSTextView`. Tracks the text view's scroll origin via the
|
||||
/// `boundsDidChangeNotification` posted by the enclosing `NSClipView` and
|
||||
/// invalidates itself on every text edit and frame change.
|
||||
final class ScratchLineNumberRuler: NSRulerView {
|
||||
|
||||
/// Re-resolved on every `draw` so the ruler picks up font / layout-manager
|
||||
/// swaps the text view performs after attachment.
|
||||
private weak var textView: NSTextView?
|
||||
|
||||
init(scrollView: NSScrollView, textView: NSTextView) {
|
||||
self.textView = textView
|
||||
super.init(scrollView: scrollView, orientation: .verticalRuler)
|
||||
self.clientView = textView
|
||||
self.ruleThickness = gutterWidth
|
||||
let center: NotificationCenter = NotificationCenter.default
|
||||
center.addObserver(self,
|
||||
selector: #selector(invalidateForChange(_:)),
|
||||
name: NSText.didChangeNotification,
|
||||
object: textView)
|
||||
center.addObserver(self,
|
||||
selector: #selector(invalidateForChange(_:)),
|
||||
name: NSView.frameDidChangeNotification,
|
||||
object: textView)
|
||||
let clipView: NSClipView = scrollView.contentView
|
||||
clipView.postsBoundsChangedNotifications = true
|
||||
center.addObserver(self,
|
||||
selector: #selector(invalidateForChange(_:)),
|
||||
name: NSView.boundsDidChangeNotification,
|
||||
object: clipView)
|
||||
}
|
||||
|
||||
required init(coder: NSCoder) {
|
||||
fatalError("ScratchLineNumberRuler does not support NSCoder init")
|
||||
}
|
||||
|
||||
deinit {
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
}
|
||||
|
||||
@objc private func invalidateForChange(_ note: Notification) {
|
||||
needsDisplay = true
|
||||
}
|
||||
|
||||
override func drawHashMarksAndLabels(in rect: NSRect) {
|
||||
guard let textView: NSTextView,
|
||||
let layoutManager: NSLayoutManager = textView.layoutManager,
|
||||
let textContainer: NSTextContainer = textView.textContainer else {
|
||||
return
|
||||
}
|
||||
|
||||
gutterFillColor.setFill()
|
||||
rect.fill()
|
||||
gutterDividerColor.setStroke()
|
||||
let dividerPath: NSBezierPath = NSBezierPath()
|
||||
let dividerX: CGFloat = bounds.maxX - dividerHalfPixel
|
||||
dividerPath.move(to: NSPoint(x: dividerX, y: rect.minY))
|
||||
dividerPath.line(to: NSPoint(x: dividerX, y: rect.maxY))
|
||||
dividerPath.lineWidth = 1
|
||||
dividerPath.stroke()
|
||||
|
||||
let nsText: NSString = textView.string as NSString
|
||||
let totalLength: Int = nsText.length
|
||||
let visibleRect: NSRect = scrollView?.contentView.bounds ?? .zero
|
||||
let glyphRange: NSRange = layoutManager.glyphRange(forBoundingRect: visibleRect, in: textContainer)
|
||||
let charRange: NSRange = layoutManager.characterRange(forGlyphRange: glyphRange, actualGlyphRange: nil)
|
||||
let inset: CGFloat = textView.textContainerInset.height
|
||||
let attrs: [NSAttributedString.Key: Any] = [
|
||||
.font: rulerFont,
|
||||
.foregroundColor: gutterTextColor,
|
||||
]
|
||||
|
||||
var lineIndex: Int = lineNumber(at: charRange.location, in: nsText)
|
||||
var cursor: Int = charRange.location
|
||||
let visibleEnd: Int = NSMaxRange(charRange)
|
||||
while cursor < visibleEnd && cursor <= totalLength {
|
||||
// `lineRange(for:)` advances cursor by the full line including its
|
||||
// terminator, so `\r`, `\n`, and `\r\n` line endings are all
|
||||
// handled by Foundation.
|
||||
let probeLength: Int = (cursor == totalLength) ? 0 : 0
|
||||
let lineRange: NSRange = nsText.lineRange(for: NSRange(location: cursor, length: probeLength))
|
||||
let lineGlyphRange: NSRange = layoutManager.glyphRange(forCharacterRange: lineRange,
|
||||
actualCharacterRange: nil)
|
||||
let usedRect: NSRect = layoutManager.boundingRect(forGlyphRange: lineGlyphRange,
|
||||
in: textContainer)
|
||||
let yInView: CGFloat = usedRect.minY + inset - visibleRect.minY
|
||||
let label: NSString = "\(lineIndex)" as NSString
|
||||
let size: CGSize = label.size(withAttributes: attrs)
|
||||
let drawPoint: NSPoint = NSPoint(
|
||||
x: bounds.maxX - size.width - rightInset,
|
||||
y: yInView + ((usedRect.height - size.height) * 0.5)
|
||||
)
|
||||
label.draw(at: drawPoint, withAttributes: attrs)
|
||||
|
||||
let advance: Int = NSMaxRange(lineRange)
|
||||
if advance <= cursor { break } // defensive — empty trailing line
|
||||
cursor = advance
|
||||
lineIndex += 1
|
||||
}
|
||||
}
|
||||
|
||||
// 1-based line number of the character at `loc`. Delegates to
|
||||
// `NSString.enumerateSubstrings(.byLines)` so CR, LF, and CRLF endings are
|
||||
// all counted correctly. Linear in `loc`, runs once per draw on the prefix
|
||||
// that precedes the first visible line.
|
||||
private func lineNumber(at loc: Int, in text: NSString) -> Int {
|
||||
if loc <= 0 { return 1 }
|
||||
var line: Int = 1
|
||||
let prefixRange: NSRange = NSRange(location: 0, length: loc)
|
||||
text.enumerateSubstrings(in: prefixRange,
|
||||
options: [.byLines, .substringNotRequired]) { _, _, _, _ in
|
||||
line += 1
|
||||
}
|
||||
return line
|
||||
}
|
||||
|
||||
private let gutterWidth: CGFloat = 40
|
||||
private let rightInset: CGFloat = 6
|
||||
private let dividerHalfPixel: CGFloat = 0.5 // crisp 1px divider on Retina
|
||||
private let rulerFontSize: CGFloat = 11
|
||||
private let gutterFillColor: NSColor = NSColor.controlBackgroundColor
|
||||
private let gutterDividerColor: NSColor = NSColor.separatorColor
|
||||
private let gutterTextColor: NSColor = NSColor.tertiaryLabelColor
|
||||
private var rulerFont: NSFont {
|
||||
NSFont.monospacedSystemFont(ofSize: rulerFontSize, weight: .regular)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,57 +0,0 @@
|
||||
# Lyrebird
|
||||
|
||||
Lyrebird is a native macOS audio synthesis framework written in Swift. Users write Swift code that implements the `Generator` and `Synthesizer` protocols against the Lyrebird engine — there is no separate scripting language. The framework handles Core Audio I/O, a pre-allocated bus memory system, and a node tree for ordering signal evaluation. The design is informed by 20+ years of SuperCollider practice, adapted to Swift idioms and a single-process architecture.
|
||||
|
||||
Development follows an interpret-then-compile workflow: sketch and perform in the Swift REPL with Lyrebird loaded, then graduate working code to a Swift Package project for compiled, optimized execution.
|
||||
|
||||
## Locked Decisions
|
||||
|
||||
| Decision | Choice |
|
||||
|---|---|
|
||||
| Implementation language | Swift |
|
||||
| Platform | macOS 15+ (requires `Synchronization.Atomic` for SPSCQueue) |
|
||||
| Swift tools version | 6.0 (required for macOS 15 platform target) |
|
||||
| Audio I/O | Direct Core Audio (`kAudioUnitSubType_HALOutput`) — no AVAudioEngine |
|
||||
| NRT rendering | `NRTDriver` — fixed-duration tight loop, `ExtAudioFile` AIFF/WAV output; event-driven stop is a stretch goal |
|
||||
| Execution model | Interpreted (REPL) → compiled (Swift Package) |
|
||||
| Bus system | Pre-allocated, SC convention (128 audio / 4096 control) |
|
||||
| Block size | Configurable at engine init |
|
||||
| Testing | Swift Testing framework — no Xcode Playgrounds |
|
||||
| REPL | Swift REPL + LineNoise |
|
||||
| Hot reload | Interpret-then-compile |
|
||||
| Inter-file modularity | Swift Package module system |
|
||||
| Package targets | `Lyrebird` (library), `LyrebirdDemo` (executable smoke test), `LyrebirdTests` (test) |
|
||||
|
||||
## SuperCollider Lineage
|
||||
|
||||
The designer has 20+ years of SC experience. SC concepts map to Lyrebird as follows:
|
||||
|
||||
| SuperCollider | Lyrebird |
|
||||
|---|---|
|
||||
| UGen | `Generator` protocol |
|
||||
| SynthDef / Synth | `Synthesizer` protocol |
|
||||
| Group | `Group` (node tree ordering) |
|
||||
| Audio/control bus | Pre-allocated bus memory |
|
||||
| `In` / `Out` UGen | `In` / `Out` generators |
|
||||
| sclang | Swift |
|
||||
| scsynth | `SynthesisEngine` |
|
||||
|
||||
## Document Index
|
||||
|
||||
| Doc | Topic |
|
||||
|---|---|
|
||||
| `docs/00-working-order.md` | Phased implementation sequence |
|
||||
| `docs/engine/synthesis-engine.md` | SynthesisEngine, Core Audio AUHAL |
|
||||
| `docs/engine/bus-system.md` | Bus memory model, In/Out |
|
||||
| `docs/engine/scheduling.md` | Sample-accurate scheduling, SPSCQueue, sub-block splitting |
|
||||
| `docs/protocols/generator.md` | Generator protocol hierarchy |
|
||||
| `docs/protocols/synthesizer.md` | Synthesizer protocol, node tree |
|
||||
| `docs/signal-flow/signal-flow.md` | DAG evaluation, block processing |
|
||||
| `docs/tooling/repl.md` | REPL, LineNoise, hot-swap |
|
||||
| `docs/tooling/project-system.md` | Swift Package model, CLI |
|
||||
| `docs/stdlib/generators.md` | Built-in generator library |
|
||||
| `docs/ui/gui-system.md` | Native SwiftUI GUI, parameter binding, control windows |
|
||||
|
||||
## Legacy Reference
|
||||
|
||||
`legacy/Lyrebird/LyrebirdSynth/Lyrebird/` — a working prototype from ~10 years ago. Good source for: `ValidGeneratorInput` protocol pattern, operator overloading approach, sine table oscillator, envelope curve math, delay interpolation. Do not copy verbatim — modernize to Swift concurrency, add Core Audio integration, expand test coverage.
|
||||
+64
@@ -7,6 +7,70 @@ 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
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
// main.swift
|
||||
// MainActorConsumer (Phase 201 regression fixture)
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
|
||||
// PHASE 201 GUARANTEE: a consumer under the MainActor-default build mode subclasses
|
||||
// `SynthesizerBase` and overrides `build()` with NO `nonisolated`, NO `@preconcurrency`,
|
||||
// NO `@MainActor`, NO `nonisolated override init`. If this stops compiling, the
|
||||
// language-side actor-isolation guarantee has regressed.
|
||||
final class ToneSynth: SynthesizerBase {
|
||||
@LiveParam var freq: Double = 440
|
||||
override func build() {
|
||||
output(bus: 0, source: OscSin.Audio(freq: $freq) * 0.2)
|
||||
}
|
||||
}
|
||||
|
||||
let synth = ToneSynth()
|
||||
print("Phase 201 regression fixture OK: \(synth)")
|
||||
@@ -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)") }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -128,6 +128,13 @@ func lyrebirdSeedXorshift64(from seed: UInt64?) -> UInt64 {
|
||||
lyrebirdSeedXorshift64(from: seed, mixConstant: 0)
|
||||
}
|
||||
|
||||
// MARK: - Mathematical constants
|
||||
|
||||
/// Two π: the radian measure of a full cycle.
|
||||
///
|
||||
/// Shared by oscillator, modulation, and filter code. Avoids per-function `let twoPi` locals.
|
||||
internal let lyrebirdTwoPi: Double = 2.0 * Double.pi
|
||||
|
||||
// MARK: - Sample rate limits
|
||||
|
||||
/// Maximum sample rate supported by Lyrebird hardware drivers.
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
// PowerOfTwo.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Smallest power of two `>= n`. Returns `1` for `n <= 1`.
|
||||
///
|
||||
/// Used to size circular buffers so the read/write index wrap can be a single
|
||||
/// bitwise `& (count - 1)` instead of an integer `% count`.
|
||||
@inline(__always)
|
||||
func lyrebirdNextPowerOfTwo(_ n: Int) -> Int {
|
||||
guard n > 1 else { return 1 }
|
||||
var result: Int = 1
|
||||
while result < n { result <<= 1 }
|
||||
return result
|
||||
}
|
||||
@@ -10,13 +10,12 @@
|
||||
/// Gamma draws (shared `_sampleBetaRand` helper with `lo: 0, hi: 1`).
|
||||
/// `length == -1` runs forever. `reset()` rewinds the response counter but
|
||||
/// intentionally does not restore the PRNG seed.
|
||||
internal final class BetaPatternEngine: _PatternEngine {
|
||||
internal final class BetaPatternEngine: _RandomPatternBase, _PatternEngine {
|
||||
internal typealias Element = Double
|
||||
|
||||
private let _alpha: Double
|
||||
private let _beta: Double
|
||||
private let _length: Int
|
||||
private var _rngState: UInt64
|
||||
private var _index: Int = 0
|
||||
|
||||
internal init(
|
||||
@@ -28,11 +27,11 @@ internal final class BetaPatternEngine: _PatternEngine {
|
||||
_alpha = alpha
|
||||
_beta = beta
|
||||
_length = length
|
||||
_rngState = lyrebirdSeedXorshift64(from: seed)
|
||||
super.init(seed: seed)
|
||||
}
|
||||
|
||||
internal var isExhausted: Bool {
|
||||
_length >= 0 && _index >= _length
|
||||
isCounterExhausted(count: _index, limit: _length)
|
||||
}
|
||||
|
||||
internal func next() -> Double? {
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
/// midpoint. `length == -1` runs forever. `reset()` restores the starting
|
||||
/// position but intentionally does not restore the PRNG seed — mirrors the
|
||||
/// `DemandRandom` convention.
|
||||
internal final class BrownianPatternEngine: _PatternEngine {
|
||||
internal final class BrownianPatternEngine: _RandomPatternBase, _PatternEngine {
|
||||
internal typealias Element = Double
|
||||
|
||||
private let _low: Double
|
||||
@@ -19,7 +19,6 @@ internal final class BrownianPatternEngine: _PatternEngine {
|
||||
private let _step: Double
|
||||
private let _initialState: Double
|
||||
private let _length: Int
|
||||
private var _rngState: UInt64
|
||||
private var _index: Int = 0
|
||||
private var _current: Double
|
||||
|
||||
@@ -37,12 +36,12 @@ internal final class BrownianPatternEngine: _PatternEngine {
|
||||
let midpoint: Double = (low + high) * 0.5
|
||||
_initialState = start ?? midpoint
|
||||
_length = length
|
||||
_rngState = lyrebirdSeedXorshift64(from: seed)
|
||||
_current = _initialState
|
||||
super.init(seed: seed)
|
||||
}
|
||||
|
||||
internal var isExhausted: Bool {
|
||||
_length >= 0 && _index >= _length
|
||||
isCounterExhausted(count: _index, limit: _length)
|
||||
}
|
||||
|
||||
internal func next() -> Double? {
|
||||
|
||||
@@ -11,13 +11,12 @@
|
||||
/// `_sampleCauchy` helper, `posOnly: false`). `length == -1` runs forever.
|
||||
/// `reset()` rewinds the response counter but intentionally does not restore
|
||||
/// the PRNG seed.
|
||||
internal final class CauchyPatternEngine: _PatternEngine {
|
||||
internal final class CauchyPatternEngine: _RandomPatternBase, _PatternEngine {
|
||||
internal typealias Element = Double
|
||||
|
||||
private let _location: Double
|
||||
private let _scale: Double
|
||||
private let _length: Int
|
||||
private var _rngState: UInt64
|
||||
private var _index: Int = 0
|
||||
|
||||
internal init(
|
||||
@@ -29,11 +28,11 @@ internal final class CauchyPatternEngine: _PatternEngine {
|
||||
_location = location
|
||||
_scale = scale
|
||||
_length = length
|
||||
_rngState = lyrebirdSeedXorshift64(from: seed)
|
||||
super.init(seed: seed)
|
||||
}
|
||||
|
||||
internal var isExhausted: Bool {
|
||||
_length >= 0 && _index >= _length
|
||||
isCounterExhausted(count: _index, limit: _length)
|
||||
}
|
||||
|
||||
internal func next() -> Double? {
|
||||
|
||||
@@ -37,9 +37,7 @@ internal final class ConcatenatePatternEngine<T>: _PatternEngine {
|
||||
}
|
||||
|
||||
internal func reset() {
|
||||
for p: Pattern<T> in _patterns {
|
||||
p.reset()
|
||||
}
|
||||
resetAll(_patterns)
|
||||
_activeIndex = 0
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,13 +10,12 @@
|
||||
/// `stdDev` via Box-Muller transform (shared `_sampleGauss` helper).
|
||||
/// `length == -1` runs forever. `reset()` rewinds the response counter but
|
||||
/// intentionally does not restore the PRNG seed.
|
||||
internal final class GaussianPatternEngine: _PatternEngine {
|
||||
internal final class GaussianPatternEngine: _RandomPatternBase, _PatternEngine {
|
||||
internal typealias Element = Double
|
||||
|
||||
private let _mean: Double
|
||||
private let _stdDev: Double
|
||||
private let _length: Int
|
||||
private var _rngState: UInt64
|
||||
private var _index: Int = 0
|
||||
|
||||
internal init(
|
||||
@@ -28,11 +27,11 @@ internal final class GaussianPatternEngine: _PatternEngine {
|
||||
_mean = mean
|
||||
_stdDev = stdDev
|
||||
_length = length
|
||||
_rngState = lyrebirdSeedXorshift64(from: seed)
|
||||
super.init(seed: seed)
|
||||
}
|
||||
|
||||
internal var isExhausted: Bool {
|
||||
_length >= 0 && _index >= _length
|
||||
isCounterExhausted(count: _index, limit: _length)
|
||||
}
|
||||
|
||||
internal func next() -> Double? {
|
||||
|
||||
@@ -29,7 +29,7 @@ internal final class GeometricPatternEngine: _PatternEngine {
|
||||
}
|
||||
|
||||
internal var isExhausted: Bool {
|
||||
_length >= 0 && _index >= _length
|
||||
isCounterExhausted(count: _index, limit: _length)
|
||||
}
|
||||
|
||||
internal func next() -> Double? {
|
||||
|
||||
@@ -18,13 +18,12 @@
|
||||
/// non-repetition is required.
|
||||
///
|
||||
/// Single-element pools always return that value (no constraint to enforce).
|
||||
internal final class NonRepeatingRandomPatternEngine<T>: _PatternEngine {
|
||||
internal final class NonRepeatingRandomPatternEngine<T>: _RandomPatternBase, _PatternEngine {
|
||||
internal typealias Element = T
|
||||
|
||||
private let _values: [T]
|
||||
private let _repeats: Int
|
||||
private var _responseCount: Int = 0
|
||||
private var _rngState: UInt64
|
||||
private var _lastIndex: Int = -1
|
||||
|
||||
internal init(
|
||||
@@ -34,11 +33,11 @@ internal final class NonRepeatingRandomPatternEngine<T>: _PatternEngine {
|
||||
) {
|
||||
_values = values
|
||||
_repeats = repeats
|
||||
_rngState = lyrebirdSeedXorshift64(from: seed)
|
||||
super.init(seed: seed)
|
||||
}
|
||||
|
||||
internal var isExhausted: Bool {
|
||||
_repeats >= 0 && _responseCount >= _repeats
|
||||
isCounterExhausted(count: _responseCount, limit: _repeats)
|
||||
}
|
||||
|
||||
internal func next() -> T? {
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
// PatternEngineHelpers.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Returns `true` when a finite counter has reached or exceeded its limit.
|
||||
/// `limit < 0` means infinite — always returns `false`.
|
||||
@inline(__always)
|
||||
func isCounterExhausted(count: Int, limit: Int) -> Bool {
|
||||
limit >= 0 && count >= limit
|
||||
}
|
||||
|
||||
/// Calls `reset()` on every pattern in `patterns`.
|
||||
func resetAll<T>(_ patterns: [Pattern<T>]) {
|
||||
for p: Pattern<T> in patterns { p.reset() }
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// RandomPatternBase.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Shared base for pattern engines that own a persistent xorshift64 PRNG state.
|
||||
///
|
||||
/// Subclasses inherit `_rngState` and call `super.init(seed:)` to seed it via
|
||||
/// `lyrebirdSeedXorshift64(from:)`. `reset()` intentionally does not reseed —
|
||||
/// mirrors the `DemandRandom` convention so retriggering avoids audible repetition.
|
||||
internal class _RandomPatternBase {
|
||||
/// xorshift64 PRNG state. Subclasses read and advance this via `xorshift64NextRaw`.
|
||||
internal var _rngState: UInt64
|
||||
|
||||
internal init(seed: UInt64?) {
|
||||
_rngState = lyrebirdSeedXorshift64(from: seed)
|
||||
}
|
||||
}
|
||||
@@ -53,9 +53,7 @@ internal final class RoundRobinPatternEngine<T>: _PatternEngine {
|
||||
}
|
||||
|
||||
internal func reset() {
|
||||
for p: Pattern<T> in _patterns {
|
||||
p.reset()
|
||||
}
|
||||
resetAll(_patterns)
|
||||
for i: Int in 0..<_alive.count {
|
||||
_alive[i] = true
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ internal final class SequencePatternEngine<T>: _PatternEngine {
|
||||
}
|
||||
|
||||
internal var isExhausted: Bool {
|
||||
_repeats >= 0 && _cycleCount >= _repeats
|
||||
isCounterExhausted(count: _cycleCount, limit: _repeats)
|
||||
}
|
||||
|
||||
internal func next() -> T? {
|
||||
|
||||
@@ -27,7 +27,7 @@ internal final class SeriesPatternEngine: _PatternEngine {
|
||||
}
|
||||
|
||||
internal var isExhausted: Bool {
|
||||
_length >= 0 && _index >= _length
|
||||
isCounterExhausted(count: _index, limit: _length)
|
||||
}
|
||||
|
||||
internal func next() -> Double? {
|
||||
|
||||
@@ -38,7 +38,7 @@ internal final class ShufflePatternEngine<T>: _PatternEngine {
|
||||
}
|
||||
|
||||
internal var isExhausted: Bool {
|
||||
_repeats >= 0 && _cycleCount >= _repeats
|
||||
isCounterExhausted(count: _cycleCount, limit: _repeats)
|
||||
}
|
||||
|
||||
internal func next() -> T? {
|
||||
|
||||
@@ -49,9 +49,7 @@ internal final class SwitchPatternEngine<T>: _PatternEngine {
|
||||
}
|
||||
|
||||
internal func reset() {
|
||||
for p: Pattern<T> in _patterns {
|
||||
p.reset()
|
||||
}
|
||||
resetAll(_patterns)
|
||||
_indexPattern.reset()
|
||||
_exhaustedLatch = false
|
||||
}
|
||||
|
||||
@@ -44,9 +44,7 @@ internal final class TuplePatternEngine<T>: _PatternEngine {
|
||||
}
|
||||
|
||||
internal func reset() {
|
||||
for p: Pattern<T> in _patterns {
|
||||
p.reset()
|
||||
}
|
||||
resetAll(_patterns)
|
||||
_exhaustedLatch = false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,13 +11,12 @@
|
||||
/// counter but intentionally does not restore the PRNG seed — mirrors the
|
||||
/// `DemandRandom` convention so rhythmic retriggering of the same pattern
|
||||
/// instance does not produce audible repetition.
|
||||
internal final class UniformRandomPatternEngine: _PatternEngine {
|
||||
internal final class UniformRandomPatternEngine: _RandomPatternBase, _PatternEngine {
|
||||
internal typealias Element = Double
|
||||
|
||||
private let _low: Double
|
||||
private let _high: Double
|
||||
private let _length: Int
|
||||
private var _rngState: UInt64
|
||||
private var _index: Int = 0
|
||||
|
||||
internal init(
|
||||
@@ -29,11 +28,11 @@ internal final class UniformRandomPatternEngine: _PatternEngine {
|
||||
_low = low
|
||||
_high = high
|
||||
_length = length
|
||||
_rngState = lyrebirdSeedXorshift64(from: seed)
|
||||
super.init(seed: seed)
|
||||
}
|
||||
|
||||
internal var isExhausted: Bool {
|
||||
_length >= 0 && _index >= _length
|
||||
isCounterExhausted(count: _index, limit: _length)
|
||||
}
|
||||
|
||||
internal func next() -> Double? {
|
||||
|
||||
@@ -15,14 +15,13 @@
|
||||
/// Weights are normalised at init into a cumulative distribution; `next()` is
|
||||
/// O(N) linear search (acceptable — pools are typically small). All weights
|
||||
/// must be ≥ 0 and the sum must be > 0; violations trap at init.
|
||||
internal final class WeightedRandomPatternEngine<T>: _PatternEngine {
|
||||
internal final class WeightedRandomPatternEngine<T>: _RandomPatternBase, _PatternEngine {
|
||||
internal typealias Element = T
|
||||
|
||||
private let _values: [T]
|
||||
private let _cumulative: [Double] // normalised, last entry == 1.0
|
||||
private let _repeats: Int
|
||||
private var _responseCount: Int = 0
|
||||
private var _rngState: UInt64
|
||||
|
||||
internal init(
|
||||
values: [T],
|
||||
@@ -61,11 +60,11 @@ internal final class WeightedRandomPatternEngine<T>: _PatternEngine {
|
||||
_values = values
|
||||
_cumulative = cum
|
||||
_repeats = repeats
|
||||
_rngState = lyrebirdSeedXorshift64(from: seed)
|
||||
super.init(seed: seed)
|
||||
}
|
||||
|
||||
internal var isExhausted: Bool {
|
||||
_repeats >= 0 && _responseCount >= _repeats
|
||||
isCounterExhausted(count: _responseCount, limit: _repeats)
|
||||
}
|
||||
|
||||
internal func next() -> T? {
|
||||
|
||||
@@ -297,9 +297,8 @@ public final class LyrebirdProcessContext: @unchecked Sendable {
|
||||
}
|
||||
for synth: any Synthesizer in synths {
|
||||
let args: ContextAddArgs = ContextAddArgs(engine, synth, nodePosition)
|
||||
DispatchQueue.main.async {
|
||||
do { try args.engine.add(args.synth, position: args.position) }
|
||||
catch { print("[Lyrebird] ProcessContext.add failed: \(error)") }
|
||||
lyrebirdDispatchEngineOp("ProcessContext.add") {
|
||||
try args.engine.add(args.synth, position: args.position)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -187,9 +187,8 @@ public final class LyrebirdRoutineContext: @unchecked Sendable {
|
||||
|
||||
public func add(_ synth: any Synthesizer) {
|
||||
let args: Args = Args(_engine, synth)
|
||||
DispatchQueue.main.async {
|
||||
do { try args.engine.add(args.synth) }
|
||||
catch { print("[Lyrebird] RoutineContext.add failed: \(error)") }
|
||||
lyrebirdDispatchEngineOp("RoutineContext.add") {
|
||||
try args.engine.add(args.synth)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -198,9 +197,8 @@ public final class LyrebirdRoutineContext: @unchecked Sendable {
|
||||
at time: SampleTime
|
||||
) {
|
||||
let args: Args = Args(_engine, synth)
|
||||
DispatchQueue.main.async {
|
||||
do { try args.engine.schedule(args.synth, at: time) }
|
||||
catch { print("[Lyrebird] RoutineContext.schedule(at:) failed: \(error)") }
|
||||
lyrebirdDispatchEngineOp("RoutineContext.schedule(at:)") {
|
||||
try args.engine.schedule(args.synth, at: time)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -209,9 +207,8 @@ public final class LyrebirdRoutineContext: @unchecked Sendable {
|
||||
after seconds: Double
|
||||
) {
|
||||
let args: Args = Args(_engine, synth)
|
||||
DispatchQueue.main.async {
|
||||
do { try args.engine.schedule(args.synth, after: seconds) }
|
||||
catch { print("[Lyrebird] RoutineContext.schedule(after:) failed: \(error)") }
|
||||
lyrebirdDispatchEngineOp("RoutineContext.schedule(after:)") {
|
||||
try args.engine.schedule(args.synth, after: seconds)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
// MusicXMLDirectionHelpers.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// MARK: - Shared direction-wrapper helper
|
||||
|
||||
/// Emit a `<direction placement="P">` wrapper with an inner `<direction-type>` block.
|
||||
///
|
||||
/// Produces exactly:
|
||||
/// ```
|
||||
/// <direction placement="P">
|
||||
/// <direction-type>
|
||||
/// …content()…
|
||||
/// </direction-type>
|
||||
/// <staff>N</staff> ← only when staff != nil
|
||||
/// …trailing…
|
||||
/// </direction>
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - placement: MusicXML `placement` attribute value (e.g. `"above"`, `"below"`).
|
||||
/// - staff: When non-nil, emits `<staff>N</staff>` after `</direction-type>`.
|
||||
/// - trailing: Raw XML appended after `</direction-type>` (and after `<staff>` when present)
|
||||
/// and before `</direction>`. Defaults to `""`.
|
||||
/// - content: Closure returning the inner markup placed inside `<direction-type>`.
|
||||
/// - Returns: The complete direction XML fragment including trailing newline.
|
||||
func directionXML(
|
||||
placement: String,
|
||||
staff: Int? = nil,
|
||||
trailing: String = "",
|
||||
content: () -> String
|
||||
) -> String {
|
||||
var xml: String = ""
|
||||
xml += " <direction placement=\"\(placement)\">\n"
|
||||
xml += " <direction-type>\n"
|
||||
xml += content()
|
||||
xml += " </direction-type>\n"
|
||||
if let staffNumber: Int = staff {
|
||||
xml += " <staff>\(staffNumber)</staff>\n"
|
||||
}
|
||||
xml += trailing
|
||||
xml += " </direction>\n"
|
||||
return xml
|
||||
}
|
||||
|
||||
// MARK: - Shared pitch-block helper
|
||||
|
||||
/// Emit a `<pitch>` block with step, optional alter, and octave.
|
||||
///
|
||||
/// Produces exactly:
|
||||
/// ```
|
||||
/// <pitch>
|
||||
/// <step>S</step>
|
||||
/// <alter>A</alter> ← only when alter != nil and alter != 0
|
||||
/// <octave>O</octave>
|
||||
/// </pitch>
|
||||
/// ```
|
||||
///
|
||||
/// The `<alter>` value is formatted via `Score.formatAlter(_:)` — the same
|
||||
/// formatter used by `encodeNamedPitch`. Integer alter values (e.g. `1.0`,
|
||||
/// `-1.0`) produce the same digit string as plain `Int` interpolation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - stepGlyph: The letter glyph, e.g. `"C"`, `"F"`.
|
||||
/// - alter: Semitone adjustment in `Double`. Pass `nil` (or `0`) to suppress the `<alter>` line.
|
||||
/// - octave: MusicXML octave number.
|
||||
/// - Returns: The `<pitch>…</pitch>` XML fragment including trailing newline.
|
||||
func pitchBlockXML(stepGlyph: String, alter: Double?, octave: Int) -> String {
|
||||
var xml: String = ""
|
||||
xml += " <pitch>\n"
|
||||
xml += " <step>\(stepGlyph)</step>\n"
|
||||
if let a: Double = alter, a != 0.0 {
|
||||
xml += " <alter>\(Score.formatAlter(a))</alter>\n"
|
||||
}
|
||||
xml += " <octave>\(octave)</octave>\n"
|
||||
xml += " </pitch>\n"
|
||||
return xml
|
||||
}
|
||||
@@ -802,16 +802,12 @@ extension Score {
|
||||
name: NoteName,
|
||||
octave: Int
|
||||
) -> String {
|
||||
var xml: String = ""
|
||||
xml += " <pitch>\n"
|
||||
xml += " <step>\(name.letter.glyph)</step>\n"
|
||||
let alter: Double = name.accidental.semitones
|
||||
if alter != 0.0 {
|
||||
xml += " <alter>\(formatAlter(alter))</alter>\n"
|
||||
}
|
||||
xml += " <octave>\(octave)</octave>\n"
|
||||
xml += " </pitch>\n"
|
||||
return xml
|
||||
return pitchBlockXML(
|
||||
stepGlyph: name.letter.glyph,
|
||||
alter: alter != 0.0 ? alter : nil,
|
||||
octave: octave
|
||||
)
|
||||
}
|
||||
|
||||
/// Map a MIDI note number to a natural-letter spelling, preferring
|
||||
@@ -820,15 +816,11 @@ extension Score {
|
||||
let octave: Int = (midi / Pitch.semitonesPerOctave) - Pitch.midiOctaveOffset
|
||||
let semitone: Int = midi % Pitch.semitonesPerOctave
|
||||
let (letter, alter): (Letter, Int) = Score.midiSemitoneSpelling[semitone]
|
||||
var xml: String = ""
|
||||
xml += " <pitch>\n"
|
||||
xml += " <step>\(letter.glyph)</step>\n"
|
||||
if alter != 0 {
|
||||
xml += " <alter>\(alter)</alter>\n"
|
||||
}
|
||||
xml += " <octave>\(octave)</octave>\n"
|
||||
xml += " </pitch>\n"
|
||||
return xml
|
||||
return pitchBlockXML(
|
||||
stepGlyph: letter.glyph,
|
||||
alter: alter != 0 ? Double(alter) : nil,
|
||||
octave: octave
|
||||
)
|
||||
}
|
||||
|
||||
/// Default spelling used for `Pitch.midi(_:)` events.
|
||||
@@ -855,24 +847,16 @@ extension Score {
|
||||
/// Only the open event (crescendo or diminuendo) is emitted here; the close
|
||||
/// is emitted by ``emitWedgeStopDirectionXML()``.
|
||||
func emitWedgeStartDirectionXML(kind: WedgeKind) -> String {
|
||||
var xml: String = ""
|
||||
xml += " <direction placement=\"below\">\n"
|
||||
xml += " <direction-type>\n"
|
||||
xml += " <wedge type=\"\(kind.musicXMLType)\"/>\n"
|
||||
xml += " </direction-type>\n"
|
||||
xml += " </direction>\n"
|
||||
return xml
|
||||
directionXML(placement: "below") {
|
||||
" <wedge type=\"\(kind.musicXMLType)\"/>\n"
|
||||
}
|
||||
}
|
||||
|
||||
/// Emit a `<direction placement="below">` block containing a wedge-stop event.
|
||||
func emitWedgeStopDirectionXML() -> String {
|
||||
var xml: String = ""
|
||||
xml += " <direction placement=\"below\">\n"
|
||||
xml += " <direction-type>\n"
|
||||
xml += " <wedge type=\"stop\"/>\n"
|
||||
xml += " </direction-type>\n"
|
||||
xml += " </direction>\n"
|
||||
return xml
|
||||
directionXML(placement: "below") {
|
||||
" <wedge type=\"stop\"/>\n"
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Pedal direction emission
|
||||
@@ -892,16 +876,9 @@ extension Score {
|
||||
kind: PedalKind,
|
||||
staff: Int?
|
||||
) -> String {
|
||||
var xml: String = ""
|
||||
xml += " <direction placement=\"below\">\n"
|
||||
xml += " <direction-type>\n"
|
||||
xml += " <pedal type=\"\(kind.musicXMLType)\" line=\"yes\"/>\n"
|
||||
xml += " </direction-type>\n"
|
||||
if let staffNumber: Int = staff {
|
||||
xml += " <staff>\(staffNumber)</staff>\n"
|
||||
directionXML(placement: "below", staff: staff) {
|
||||
" <pedal type=\"\(kind.musicXMLType)\" line=\"yes\"/>\n"
|
||||
}
|
||||
xml += " </direction>\n"
|
||||
return xml
|
||||
}
|
||||
|
||||
// MARK: - Grace note emission
|
||||
@@ -1041,20 +1018,20 @@ extension Score {
|
||||
let nienteAttribute: String = (nienteAtStart || nienteAtEnd) ? " niente=\"yes\"" : ""
|
||||
|
||||
// Wedge start
|
||||
xml += " <direction placement=\"below\">\n"
|
||||
xml += " <direction-type>\n"
|
||||
xml += " <wedge type=\"\(wedgeKind)\"\(nienteAttribute)/>\n"
|
||||
xml += " </direction-type>\n"
|
||||
xml += " <offset>\(offsetDivisions)</offset>\n"
|
||||
xml += " </direction>\n"
|
||||
xml += directionXML(
|
||||
placement: "below",
|
||||
trailing: " <offset>\(offsetDivisions)</offset>\n"
|
||||
) {
|
||||
" <wedge type=\"\(wedgeKind)\"\(nienteAttribute)/>\n"
|
||||
}
|
||||
|
||||
// Wedge stop
|
||||
xml += " <direction placement=\"below\">\n"
|
||||
xml += " <direction-type>\n"
|
||||
xml += " <wedge type=\"stop\"/>\n"
|
||||
xml += " </direction-type>\n"
|
||||
xml += " <offset>\(nextOffsetDivisions)</offset>\n"
|
||||
xml += " </direction>\n"
|
||||
xml += directionXML(
|
||||
placement: "below",
|
||||
trailing: " <offset>\(nextOffsetDivisions)</offset>\n"
|
||||
) {
|
||||
" <wedge type=\"stop\"/>\n"
|
||||
}
|
||||
}
|
||||
}
|
||||
return xml
|
||||
@@ -1076,21 +1053,21 @@ extension Score {
|
||||
dynamic: Dynamic,
|
||||
offsetDivisions: Int
|
||||
) -> String {
|
||||
var xml: String = ""
|
||||
xml += " <direction placement=\"below\">\n"
|
||||
xml += " <direction-type>\n"
|
||||
xml += " <dynamics>\n"
|
||||
if let name: String = dynamic.musicXMLDynamic {
|
||||
xml += " <\(name)/>\n"
|
||||
} else if case .raw(let v) = dynamic {
|
||||
let safe: Double = v.isFinite ? v : 0.0
|
||||
xml += " <other-dynamics>\(safe)</other-dynamics>\n"
|
||||
directionXML(
|
||||
placement: "below",
|
||||
trailing: " <offset>\(offsetDivisions)</offset>\n"
|
||||
) {
|
||||
var inner: String = ""
|
||||
inner += " <dynamics>\n"
|
||||
if let name: String = dynamic.musicXMLDynamic {
|
||||
inner += " <\(name)/>\n"
|
||||
} else if case .raw(let v) = dynamic {
|
||||
let safe: Double = v.isFinite ? v : 0.0
|
||||
inner += " <other-dynamics>\(safe)</other-dynamics>\n"
|
||||
}
|
||||
inner += " </dynamics>\n"
|
||||
return inner
|
||||
}
|
||||
xml += " </dynamics>\n"
|
||||
xml += " </direction-type>\n"
|
||||
xml += " <offset>\(offsetDivisions)</offset>\n"
|
||||
xml += " </direction>\n"
|
||||
return xml
|
||||
}
|
||||
|
||||
// MARK: - Dynamic direction emission
|
||||
@@ -1142,23 +1119,21 @@ extension Score {
|
||||
/// is the Lyrebird-side playback path (`ScoreEvent.velocity`), not a
|
||||
/// MusicXML playback signal.
|
||||
func emitDirectionXML(dynamic: Dynamic) -> String {
|
||||
var xml: String = ""
|
||||
xml += " <direction placement=\"below\">\n"
|
||||
xml += " <direction-type>\n"
|
||||
xml += " <dynamics>\n"
|
||||
if let name: String = dynamic.musicXMLDynamic {
|
||||
xml += " <\(name)/>\n"
|
||||
} else if case .raw(let v) = dynamic {
|
||||
// Swift's default Double description is the shortest decimal that
|
||||
// round-trips back to the same bit pattern via `Double(_:)`.
|
||||
// Guard non-finite (NaN/±Inf carry no velocity meaning).
|
||||
let safe: Double = v.isFinite ? v : 0.0
|
||||
xml += " <other-dynamics>\(safe)</other-dynamics>\n"
|
||||
directionXML(placement: "below") {
|
||||
var inner: String = ""
|
||||
inner += " <dynamics>\n"
|
||||
if let name: String = dynamic.musicXMLDynamic {
|
||||
inner += " <\(name)/>\n"
|
||||
} else if case .raw(let v) = dynamic {
|
||||
// Swift's default Double description is the shortest decimal that
|
||||
// round-trips back to the same bit pattern via `Double(_:)`.
|
||||
// Guard non-finite (NaN/±Inf carry no velocity meaning).
|
||||
let safe: Double = v.isFinite ? v : 0.0
|
||||
inner += " <other-dynamics>\(safe)</other-dynamics>\n"
|
||||
}
|
||||
inner += " </dynamics>\n"
|
||||
return inner
|
||||
}
|
||||
xml += " </dynamics>\n"
|
||||
xml += " </direction-type>\n"
|
||||
xml += " </direction>\n"
|
||||
return xml
|
||||
}
|
||||
|
||||
// MARK: - Numeric formatting helpers
|
||||
|
||||
@@ -1157,6 +1157,50 @@ extension Score {
|
||||
measureOpen = true
|
||||
}
|
||||
}
|
||||
|
||||
// The atom's FINAL piece exactly filled the current measure
|
||||
// (`leftover` and `remaining` reached zero together, so the
|
||||
// in-loop close above — guarded by `leftover > .zero` — did not
|
||||
// fire). Close the now-full measure here, mirroring the fit
|
||||
// branch's `remaining == .zero` close. Without this the measure
|
||||
// stays open with `remaining == .zero`; the NEXT atom then can
|
||||
// neither fit (`sd <= 0` is false) nor split cleanly — the split
|
||||
// loop emits a spurious `max(1, …)` one-division piece before the
|
||||
// bar finally closes, shifting every following note by a division.
|
||||
if remaining == .zero && measureOpen {
|
||||
// Flush trailing zero-duration atoms (grace notes, clef
|
||||
// changes, pedal marks) into the just-filled measure.
|
||||
while let nextAtom: _Atom = atomQueue.first, nextAtom.soundingDuration == .zero {
|
||||
let zeroAtom: _Atom = atomQueue.removeFirst()
|
||||
emitZeroDurationAtom(zeroAtom, isMultiStaff: isMultiStaff, into: &xml)
|
||||
}
|
||||
xml += rightBarlineXML(measureNumber: measureIndex, repeats: repeats)
|
||||
xml += " </measure>\n"
|
||||
measureOpen = false
|
||||
measureIndex += 1
|
||||
measureCap = measureCapacity(forMeasure: measureIndex, meterMap: meterMap)
|
||||
remaining = measureCap
|
||||
if !atomQueue.isEmpty {
|
||||
xml += openMeasure(
|
||||
number: measureIndex,
|
||||
divisions: divisions,
|
||||
bpm: bpm,
|
||||
meterMap: meterMap,
|
||||
keySignature: keySignature,
|
||||
clef: clef,
|
||||
transpose: transpose,
|
||||
isFirst: false,
|
||||
repeats: repeats,
|
||||
tempoChanges: tempoChanges,
|
||||
rehearsalMarks: rehearsalMarks,
|
||||
isMultiStaff: isMultiStaff,
|
||||
staveCount: staveCount,
|
||||
staffClefs: staffClefs,
|
||||
rehearsalMarksAsStaffText: rehearsalMarksAsStaffText
|
||||
)
|
||||
measureOpen = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1370,17 +1414,13 @@ extension Score {
|
||||
/// Defaults to `false`.
|
||||
/// - Returns: The XML string fragment (including trailing newline).
|
||||
func rehearsalDirectionXML(label: String, asStaffText: Bool = false) -> String {
|
||||
var xml: String = ""
|
||||
xml += " <direction placement=\"above\">\n"
|
||||
xml += " <direction-type>\n"
|
||||
if asStaffText {
|
||||
xml += " <words enclosure=\"rectangle\" font-weight=\"bold\">\(escape(label))</words>\n"
|
||||
} else {
|
||||
xml += " <rehearsal>\(escape(label))</rehearsal>\n"
|
||||
directionXML(placement: "above") {
|
||||
if asStaffText {
|
||||
" <words enclosure=\"rectangle\" font-weight=\"bold\">\(escape(label))</words>\n"
|
||||
} else {
|
||||
" <rehearsal>\(escape(label))</rehearsal>\n"
|
||||
}
|
||||
}
|
||||
xml += " </direction-type>\n"
|
||||
xml += " </direction>\n"
|
||||
return xml
|
||||
}
|
||||
|
||||
/// Emit a complete tempo `<direction placement="above">` block.
|
||||
@@ -1391,17 +1431,17 @@ extension Score {
|
||||
/// - Parameter bpm: Tempo in quarter-note beats per minute.
|
||||
/// - Returns: The XML string fragment (including trailing newline).
|
||||
func tempoDirectionXML(bpm: Double) -> String {
|
||||
var xml: String = ""
|
||||
xml += " <direction placement=\"above\">\n"
|
||||
xml += " <direction-type>\n"
|
||||
xml += " <metronome>\n"
|
||||
xml += " <beat-unit>quarter</beat-unit>\n"
|
||||
xml += " <per-minute>\(formatBPM(bpm))</per-minute>\n"
|
||||
xml += " </metronome>\n"
|
||||
xml += " </direction-type>\n"
|
||||
xml += " <sound tempo=\"\(formatBPM(bpm))\"/>\n"
|
||||
xml += " </direction>\n"
|
||||
return xml
|
||||
directionXML(
|
||||
placement: "above",
|
||||
trailing: " <sound tempo=\"\(formatBPM(bpm))\"/>\n"
|
||||
) {
|
||||
var inner: String = ""
|
||||
inner += " <metronome>\n"
|
||||
inner += " <beat-unit>quarter</beat-unit>\n"
|
||||
inner += " <per-minute>\(formatBPM(bpm))</per-minute>\n"
|
||||
inner += " </metronome>\n"
|
||||
return inner
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Barline helpers
|
||||
|
||||
@@ -172,15 +172,14 @@ public struct Score: Sendable {
|
||||
self.keySignature = keySignature
|
||||
self.repeats = repeats
|
||||
self.tempoChanges = tempoChanges
|
||||
// Expand FillMeasure markers against each part's effective meter.
|
||||
// Parts with a per-part meterMap use their own map; others use the resolved
|
||||
// score-level map. This is the final funnel for flat, DSL, and section paths.
|
||||
// Resolve each part's entrance offset (prepended rests) and expand
|
||||
// FillMeasure markers against the part's effective meter. Parts with a
|
||||
// per-part meterMap use their own map; others use the resolved score-level
|
||||
// map. This is the final funnel for flat, DSL, and section paths — the
|
||||
// assembled parts carry `offset: nil` (the offset is consumed into rests).
|
||||
self.parts = parts.map { part in
|
||||
let effectiveMap: MeterMap = part.meterMap ?? resolvedMap
|
||||
let expanded: [ScoreElement] = Score.expandFillMeasures(
|
||||
in: part.elements,
|
||||
meter: effectiveMap
|
||||
)
|
||||
let expanded: [ScoreElement] = Score._resolvePartElements(part, meter: effectiveMap)
|
||||
return ScorePart(
|
||||
name: part.name,
|
||||
channel: part.channel,
|
||||
@@ -457,21 +456,19 @@ public struct Score: Sendable {
|
||||
)
|
||||
}
|
||||
|
||||
// Expand FillMeasure markers in this section's parts against the
|
||||
// section's effective meter BEFORE the beat-span calculation so that
|
||||
// the resolved rests count toward `_beatSpan` and `_measureSpan`.
|
||||
// After expansion the section parts carry no `.fillMeasure` elements,
|
||||
// so site-1's expansion in the designated init is a harmless no-op.
|
||||
// Resolve each part's entrance offset (prepended rests) and expand
|
||||
// FillMeasure markers against the section's effective meter BEFORE the
|
||||
// beat-span calculation so that both count toward `_beatSpan` and
|
||||
// `_measureSpan`. After this the section parts carry no offset and no
|
||||
// `.fillMeasure` elements, so site-1's expansion in the designated init
|
||||
// is a harmless no-op.
|
||||
var sectionExpandedParts: [ScorePart] = []
|
||||
sectionExpandedParts.reserveCapacity(section.parts.count)
|
||||
for part: ScorePart in section.parts {
|
||||
// A polymetric part inside a section fills to ITS OWN bar grid,
|
||||
// matching the designated-init policy (`part.meterMap ?? score map`).
|
||||
// A polymetric part inside a section offsets / fills to ITS OWN bar
|
||||
// grid, matching the designated-init policy (`part.meterMap ?? map`).
|
||||
let partMeter: MeterMap = part.meterMap ?? effectiveSectionMap
|
||||
let expanded: [ScoreElement] = Score.expandFillMeasures(
|
||||
in: part.elements,
|
||||
meter: partMeter
|
||||
)
|
||||
let expanded: [ScoreElement] = Score._resolvePartElements(part, meter: partMeter)
|
||||
sectionExpandedParts.append(ScorePart(
|
||||
name: part.name,
|
||||
channel: part.channel,
|
||||
@@ -583,7 +580,16 @@ public struct Score: Sendable {
|
||||
var elems: [ScoreElement] = sectionPart.elements
|
||||
let gap: Fraction = sectionBeatSpan - partBeats
|
||||
if gap > .zero {
|
||||
let padRests: [ScoreElement] = Score._makeRestElements(beats: gap)
|
||||
// Bar-aligned pad: full bars in the gap become clean
|
||||
// whole-measure rests instead of greedy largest-value
|
||||
// rests that straddle barlines and fragment into
|
||||
// metrically-wrong groupings (e.g. a quarter + dotted-half
|
||||
// crossing the mid-bar beat).
|
||||
let padRests: [ScoreElement] = Score._makeBarAlignedRestElements(
|
||||
startBeat: partBeats,
|
||||
gap: gap,
|
||||
meterMap: effectiveSectionMap
|
||||
)
|
||||
elems.append(contentsOf: padRests)
|
||||
}
|
||||
accumulatedElements[partID, default: []].append(contentsOf: elems)
|
||||
@@ -794,6 +800,49 @@ public struct Score: Sendable {
|
||||
elements.reduce(Fraction.zero) { $0 + scoreElementBeatSpan($1) }
|
||||
}
|
||||
|
||||
/// Resolve a ``ScoreOffset`` into the leading rest elements that delay a
|
||||
/// part's entrance, measured against `meter`.
|
||||
///
|
||||
/// - ``ScoreOffset/measures(_:)`` → one whole-measure rest per bar (bars
|
||||
/// `1..count` under `meter`), so the empty bars engrave cleanly.
|
||||
/// - ``ScoreOffset/beats(_:)`` / ``ScoreOffset/fraction(_:)`` → a decomposed
|
||||
/// rest of that many quarter-beats (may land mid-bar).
|
||||
///
|
||||
/// Returns `[]` for `nil` or a non-positive offset.
|
||||
static func _resolveOffsetRests(
|
||||
_ offset: ScoreOffset?,
|
||||
meter: MeterMap
|
||||
) -> [ScoreElement] {
|
||||
guard let offset: ScoreOffset = offset else { return [] }
|
||||
switch offset {
|
||||
case .measures(let count):
|
||||
guard count > 0 else { return [] }
|
||||
return Score._makeTacetRests(measureCount: count, meterMap: meter)
|
||||
case .beats(let beats):
|
||||
guard beats > 0 else { return [] }
|
||||
return Score._makeRestElements(beats: fractionFromBeats(beats))
|
||||
case .fraction(let frac):
|
||||
guard frac > .zero else { return [] }
|
||||
return Score._makeRestElements(beats: frac)
|
||||
}
|
||||
}
|
||||
|
||||
/// Prepend a part's resolved offset rests, then expand any `.fillMeasure`
|
||||
/// markers — the canonical per-part build-time element transform shared by
|
||||
/// the flat designated init and section lowering.
|
||||
///
|
||||
/// Offset rests are prepended BEFORE expansion so a later `.fillMeasure`
|
||||
/// fills relative to the part's delayed entrance (the cursor origin includes
|
||||
/// the offset).
|
||||
static func _resolvePartElements(
|
||||
_ part: ScorePart,
|
||||
meter: MeterMap
|
||||
) -> [ScoreElement] {
|
||||
let offsetRests: [ScoreElement] = Score._resolveOffsetRests(part.offset, meter: meter)
|
||||
let withOffset: [ScoreElement] = offsetRests + part.elements
|
||||
return Score.expandFillMeasures(in: withOffset, meter: meter)
|
||||
}
|
||||
|
||||
/// Compute the number of full bars required to contain `beats` quarters
|
||||
/// under `meterMap`.
|
||||
///
|
||||
@@ -860,6 +909,90 @@ public struct Score: Sendable {
|
||||
return result
|
||||
}
|
||||
|
||||
/// Build rest elements filling `gap` quarters starting at `startBeat`,
|
||||
/// aligned to the bar grid of `meterMap`.
|
||||
///
|
||||
/// Unlike ``_makeRestElements(beats:)`` — which greedily decomposes a span
|
||||
/// into the largest representable note values regardless of metric position
|
||||
/// (a 21-beat gap becomes three double-dotted-whole rests that straddle
|
||||
/// barlines) — this walks the bar grid from `startBeat`:
|
||||
///
|
||||
/// 1. A leading pickup region (when `meterMap.anacrusis > 0` and `startBeat`
|
||||
/// falls inside it) is filled up to the bar-1 downbeat.
|
||||
/// 2. Every FULL bar in the span emits a single bar-capacity rest, so the
|
||||
/// encoder renders a clean whole-measure rest rather than a fragmented
|
||||
/// pair (e.g. quarter + dotted-half crossing the mid-bar strong beat).
|
||||
/// 3. Partial bars at the start (mid-bar entrance) or end are decomposed
|
||||
/// with ``_makeRestElements(beats:)``.
|
||||
///
|
||||
/// Used by section lowering to pad a short part to its section's beat span.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - startBeat: Absolute quarter-beat where the gap begins (the part's
|
||||
/// content beat span), measured from beat 0 including any pickup.
|
||||
/// - gap: Number of quarter-beats to fill.
|
||||
/// - meterMap: Meter grid the rests align to.
|
||||
/// - Returns: Bar-aligned rest elements totalling `gap` quarters.
|
||||
static func _makeBarAlignedRestElements(
|
||||
startBeat: Fraction,
|
||||
gap: Fraction,
|
||||
meterMap: MeterMap
|
||||
) -> [ScoreElement] {
|
||||
guard gap > .zero else { return [] }
|
||||
var result: [ScoreElement] = []
|
||||
var cursor: Fraction = startBeat
|
||||
var remainingGap: Fraction = gap
|
||||
|
||||
// Pickup region [0, anacrusis): fill up to the bar-1 downbeat first so
|
||||
// the subsequent full-bar logic starts on a barline.
|
||||
let anacrusis: Fraction = meterMap.anacrusis
|
||||
if anacrusis > .zero && cursor < anacrusis {
|
||||
let toDownbeat: Fraction = anacrusis - cursor
|
||||
let piece: Fraction = remainingGap <= toDownbeat ? remainingGap : toDownbeat
|
||||
result.append(contentsOf: Score._makeRestElements(beats: piece))
|
||||
cursor = cursor + piece
|
||||
remainingGap = remainingGap - piece
|
||||
}
|
||||
|
||||
// Full bars: walk the grid, emitting one bar-capacity rest per full bar
|
||||
// and decomposing any partial entrance / tail.
|
||||
var bar: Int = 1
|
||||
var barStart: Fraction = anacrusis
|
||||
while remainingGap > .zero {
|
||||
let cap: Fraction = meterMap.timeSignature(atBar: bar).measureQuarters
|
||||
guard cap > .zero else {
|
||||
// Degenerate meter (zero-capacity bar) — never produced by a
|
||||
// valid MeterMap, but never silently drop the remaining gap:
|
||||
// fall back to a flat decomposition so the part still spans the
|
||||
// full section length.
|
||||
result.append(contentsOf: Score._makeRestElements(beats: remainingGap))
|
||||
remainingGap = .zero
|
||||
break
|
||||
}
|
||||
let barEnd: Fraction = barStart + cap
|
||||
if cursor >= barEnd {
|
||||
barStart = barEnd
|
||||
bar += 1
|
||||
continue
|
||||
}
|
||||
let offsetInBar: Fraction = cursor - barStart
|
||||
let toBarEnd: Fraction = cap - offsetInBar
|
||||
let piece: Fraction = remainingGap <= toBarEnd ? remainingGap : toBarEnd
|
||||
if offsetInBar == .zero && piece == cap {
|
||||
result.append(.rest(duration: .fraction(cap)))
|
||||
} else {
|
||||
result.append(contentsOf: Score._makeRestElements(beats: piece))
|
||||
}
|
||||
cursor = cursor + piece
|
||||
remainingGap = remainingGap - piece
|
||||
if cursor == barEnd {
|
||||
barStart = barEnd
|
||||
bar += 1
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/// Build whole-measure rest elements for `measureCount` bars under `meterMap`.
|
||||
///
|
||||
/// Each bar gets a single rest whose duration equals the bar's capacity.
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
// ScoreOffset.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// A leading delay applied to a ``ScorePart`` so the instrument enters later
|
||||
/// than the start of its section (or, in a flat score, later than beat 0).
|
||||
///
|
||||
/// The offset is **resolved at Score build time** into concrete leading rests
|
||||
/// prepended to the part's elements — exactly the way ``ScoreElement/fillMeasure``
|
||||
/// is resolved. Once resolved it flows through every downstream path (section
|
||||
/// beat-span sizing, rest-pad-to-span, MusicXML bar splitting, ``ScorePart/flatten()``)
|
||||
/// with no special handling, and the stored ``ScorePart/offset`` on the assembled
|
||||
/// score is `nil` (the offset has been *consumed* into rests).
|
||||
///
|
||||
/// ## Units
|
||||
///
|
||||
/// - ``measures(_:)`` — meter-dependent. Counts whole bars under the part's
|
||||
/// effective meter, starting from the part's first full bar. Resolves to one
|
||||
/// whole-measure rest per bar so the empty bars engrave cleanly. An anacrusis
|
||||
/// pickup (first section only) is **not** consumed by the offset — measures
|
||||
/// count from bar 1.
|
||||
/// - ``beats(_:)`` — meter-agnostic. A count of quarter-beats (`1.0` = one
|
||||
/// quarter note), resolved to a decomposed rest. May land mid-bar; the encoder
|
||||
/// already splits following content across barlines.
|
||||
/// - ``fraction(_:)`` — meter-agnostic, exact quarter-beats as a ``Fraction``.
|
||||
///
|
||||
/// ## Round-trip
|
||||
///
|
||||
/// Like ``ScoreElement/fillMeasure``, an offset is **emit-resolved**, not a
|
||||
/// stored MusicXML concept — a score decoded from MusicXML carries `offset == nil`
|
||||
/// (the leading rests are its representation).
|
||||
public enum ScoreOffset: Sendable, Equatable {
|
||||
|
||||
/// Enter `count` whole bars into the part's timeline (meter-dependent).
|
||||
/// Negative or zero counts resolve to no offset.
|
||||
case measures(Int)
|
||||
|
||||
/// Enter `count` quarter-beats into the part's timeline (meter-agnostic,
|
||||
/// `1.0` = one quarter note). Negative or zero values resolve to no offset.
|
||||
case beats(Double)
|
||||
|
||||
/// Enter an exact ``Fraction`` of quarter-beats into the part's timeline
|
||||
/// (meter-agnostic). Negative or zero values resolve to no offset.
|
||||
case fraction(Fraction)
|
||||
}
|
||||
@@ -90,6 +90,22 @@ public struct ScorePart: Sendable {
|
||||
/// ``Score/fromMusicXML(data:)``.
|
||||
public let meterMap: MeterMap?
|
||||
|
||||
/// Leading entrance delay for this part.
|
||||
///
|
||||
/// When non-nil, the part enters later than the start of its section (or, in
|
||||
/// a flat score, later than beat 0): a leading rest of the resolved length is
|
||||
/// prepended to ``elements`` at Score build time. See ``ScoreOffset``.
|
||||
///
|
||||
/// This is **consumed** during ``Score`` construction — the offset is turned
|
||||
/// into concrete leading rests and the assembled score's stored parts carry
|
||||
/// `offset == nil` (the rests are its representation, exactly as
|
||||
/// ``ScoreElement/fillMeasure`` markers are gone after expansion). Authoring
|
||||
/// values are set here; do not expect to read a non-nil `offset` back off an
|
||||
/// assembled or decoded ``Score``.
|
||||
///
|
||||
/// Defaults to `nil` (no delay — the part starts at beat 0).
|
||||
public let offset: ScoreOffset?
|
||||
|
||||
/// Top-level elements in document order.
|
||||
public let elements: [ScoreElement]
|
||||
|
||||
@@ -106,6 +122,8 @@ public struct ScorePart: Sendable {
|
||||
/// - meterMap: Per-part meter-map override for polymeter — a complete,
|
||||
/// all-or-nothing replacement of the score-level ``Score/meterMap``. `nil`
|
||||
/// (default) inherits the score map.
|
||||
/// - offset: Leading entrance delay, resolved to prepended rests at build
|
||||
/// time. `nil` (default) starts the part at beat 0. See ``ScoreOffset``.
|
||||
/// - elements: Top-level ``ScoreElement`` values in document order.
|
||||
/// - id: Cross-section identity key. When `nil` (the default), `id` is set
|
||||
/// equal to `name`. Used by ``ScoreSection`` lowering to match the same
|
||||
@@ -117,6 +135,7 @@ public struct ScorePart: Sendable {
|
||||
keySignature: KeySignature? = nil,
|
||||
transpose: Transpose? = nil,
|
||||
meterMap: MeterMap? = nil,
|
||||
offset: ScoreOffset? = nil,
|
||||
elements: [ScoreElement],
|
||||
id: String? = nil
|
||||
) {
|
||||
@@ -129,6 +148,7 @@ public struct ScorePart: Sendable {
|
||||
self.keySignature = keySignature
|
||||
self.transpose = transpose
|
||||
self.meterMap = meterMap
|
||||
self.offset = offset
|
||||
self.elements = elements
|
||||
}
|
||||
|
||||
|
||||
@@ -66,6 +66,10 @@ public enum ScorePartBuilder {
|
||||
/// this part uses its own complete ``MeterMap`` instead of the score-level
|
||||
/// ``Score/meterMap`` — an all-or-nothing override. Defaults to `nil`
|
||||
/// (inherit the score map).
|
||||
/// - offset: Leading entrance delay — the part starts later than the section
|
||||
/// start (or beat 0 in a flat score) by the resolved number of measures or
|
||||
/// beats. Resolved to prepended rests at build time. Defaults to `nil`
|
||||
/// (enter at beat 0). See ``ScoreOffset``.
|
||||
/// - id: Cross-section identity key. When `nil` (the default), `id` is set
|
||||
/// equal to `name`. Used by ``ScoreSection`` lowering to match the same
|
||||
/// instrument across sections even when the display `name` changes.
|
||||
@@ -77,6 +81,7 @@ public func Part(
|
||||
keySignature: KeySignature? = nil,
|
||||
transpose: Transpose? = nil,
|
||||
meterMap: MeterMap? = nil,
|
||||
offset: ScoreOffset? = nil,
|
||||
id: String? = nil,
|
||||
@ScoreBuilder elements: () -> [ScoreElement]
|
||||
) -> ScorePart {
|
||||
@@ -87,6 +92,7 @@ public func Part(
|
||||
keySignature: keySignature,
|
||||
transpose: transpose,
|
||||
meterMap: meterMap,
|
||||
offset: offset,
|
||||
elements: elements(),
|
||||
id: id
|
||||
)
|
||||
|
||||
@@ -23,16 +23,14 @@
|
||||
/// let stream = TemporalStream(walk, seed: 7)
|
||||
/// while let freq = stream.next() { ... }
|
||||
/// ```
|
||||
public final class TemporalBrownian: TemporalAlgorithm {
|
||||
public final class TemporalBrownian: TemporalAlgorithmBase {
|
||||
|
||||
private let _lo: TemporalParameter
|
||||
private let _hi: TemporalParameter
|
||||
private let _stepSize: TemporalParameter
|
||||
private let _repeats: Int
|
||||
private let _explicitStart: Double?
|
||||
|
||||
private var _current: Double = 0.0
|
||||
private var _callCount: Int = 0
|
||||
private var _initialised: Bool = false
|
||||
|
||||
/// - Parameters:
|
||||
@@ -49,21 +47,18 @@ public final class TemporalBrownian: TemporalAlgorithm {
|
||||
start: Double? = nil,
|
||||
repeats: Int = -1
|
||||
) {
|
||||
|
||||
_lo = lo
|
||||
_hi = hi
|
||||
_stepSize = stepSize
|
||||
_repeats = repeats
|
||||
_explicitStart = start
|
||||
if let s: Double = start {
|
||||
_current = s
|
||||
_initialised = true
|
||||
}
|
||||
super.init(repeats: repeats)
|
||||
}
|
||||
|
||||
public var isExhausted: Bool { _repeats >= 0 && _callCount >= _repeats }
|
||||
|
||||
public func nextValue(
|
||||
override public func nextValue(
|
||||
elapsed: Double,
|
||||
counter: Int,
|
||||
rng: inout UInt64
|
||||
@@ -85,8 +80,8 @@ public final class TemporalBrownian: TemporalAlgorithm {
|
||||
return _current
|
||||
}
|
||||
|
||||
public func reset() {
|
||||
_callCount = 0
|
||||
override public func reset() {
|
||||
super.reset()
|
||||
_initialised = false
|
||||
if let s: Double = _explicitStart {
|
||||
_current = s
|
||||
|
||||
@@ -44,7 +44,7 @@
|
||||
/// - Out-of-range `to` indices are clamped to `[0, stateCount-1]`.
|
||||
/// - Cumulative weights are pre-computed at init; `nextValue` is allocation-free.
|
||||
/// - A state with no transitions (empty `transitions` array) stays in place forever.
|
||||
public final class TemporalMarkov: TemporalAlgorithm {
|
||||
public final class TemporalMarkov: TemporalAlgorithmBase {
|
||||
|
||||
// MARK: - Nested types
|
||||
|
||||
@@ -107,11 +107,9 @@ public final class TemporalMarkov: TemporalAlgorithm {
|
||||
|
||||
private let _states: [State]
|
||||
private let _initialState: Int
|
||||
private let _repeats: Int
|
||||
private let _cumulativeWeights: [[Double]]
|
||||
|
||||
private var _currentState: Int
|
||||
private var _callCount: Int = 0
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
@@ -127,7 +125,6 @@ public final class TemporalMarkov: TemporalAlgorithm {
|
||||
_states = states
|
||||
_initialState = max(0, min(initialState, states.count - 1))
|
||||
_currentState = _initialState
|
||||
_repeats = repeats
|
||||
_cumulativeWeights = states.map { state in
|
||||
var cumulative: [Double] = [Double]()
|
||||
cumulative.reserveCapacity(state.transitions.count)
|
||||
@@ -138,13 +135,12 @@ public final class TemporalMarkov: TemporalAlgorithm {
|
||||
}
|
||||
return cumulative
|
||||
}
|
||||
super.init(repeats: repeats)
|
||||
}
|
||||
|
||||
// MARK: - TemporalAlgorithm
|
||||
// MARK: - TemporalAlgorithmBase
|
||||
|
||||
public var isExhausted: Bool { _repeats >= 0 && _callCount >= _repeats }
|
||||
|
||||
public func nextValue(
|
||||
override public func nextValue(
|
||||
elapsed: Double,
|
||||
counter: Int,
|
||||
rng: inout UInt64
|
||||
@@ -174,8 +170,8 @@ public final class TemporalMarkov: TemporalAlgorithm {
|
||||
return value
|
||||
}
|
||||
|
||||
public func reset() {
|
||||
override public func reset() {
|
||||
super.reset()
|
||||
_currentState = _initialState
|
||||
_callCount = 0
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,11 +19,9 @@
|
||||
/// let stream = TemporalStream(pick, seed: 1)
|
||||
/// while let freq = stream.next() { ... } // 10 random picks, then nil
|
||||
/// ```
|
||||
public final class TemporalRandomPick: TemporalAlgorithm {
|
||||
public final class TemporalRandomPick: TemporalAlgorithmBase {
|
||||
|
||||
private let _values: [TemporalParameter]
|
||||
private let _repeats: Int
|
||||
private var _callCount: Int = 0
|
||||
|
||||
/// - Parameters:
|
||||
/// - values: Pool to pick from. Each can be `.value`, `.envelope`, or `.closure`.
|
||||
@@ -33,12 +31,10 @@ public final class TemporalRandomPick: TemporalAlgorithm {
|
||||
repeats: Int = -1
|
||||
) {
|
||||
_values = values
|
||||
_repeats = repeats
|
||||
super.init(repeats: repeats)
|
||||
}
|
||||
|
||||
public var isExhausted: Bool { _repeats >= 0 && _callCount >= _repeats }
|
||||
|
||||
public func nextValue(
|
||||
override public func nextValue(
|
||||
elapsed: Double,
|
||||
counter: Int,
|
||||
rng: inout UInt64
|
||||
@@ -51,7 +47,7 @@ public final class TemporalRandomPick: TemporalAlgorithm {
|
||||
return result
|
||||
}
|
||||
|
||||
public func reset() {
|
||||
_callCount = 0
|
||||
override public func reset() {
|
||||
super.reset()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,6 +18,9 @@
|
||||
/// let stream = TemporalStream(seq)
|
||||
/// while let freq = stream.next() { ... } // 6 values, then nil
|
||||
/// ```
|
||||
/// Exhaustion is cycle-based (counts full passes through `values`), so this stays a
|
||||
/// direct `TemporalAlgorithm` conformer rather than subclassing `TemporalAlgorithmBase`
|
||||
/// (whose counter is per-call); it still shares the `isCounterExhausted` guard helper.
|
||||
public final class TemporalSequence: TemporalAlgorithm {
|
||||
|
||||
private let _values: [TemporalParameter]
|
||||
@@ -36,7 +39,9 @@ public final class TemporalSequence: TemporalAlgorithm {
|
||||
_repeats = repeats
|
||||
}
|
||||
|
||||
public var isExhausted: Bool { _repeats >= 0 && _cycleCount >= _repeats }
|
||||
public var isExhausted: Bool {
|
||||
isCounterExhausted(count: _cycleCount, limit: _repeats)
|
||||
}
|
||||
|
||||
public func nextValue(
|
||||
elapsed: Double,
|
||||
|
||||
@@ -55,15 +55,13 @@
|
||||
/// let points = TemporalStream(tendency, seed: 1).collect(200)
|
||||
/// LyrebirdScatterView(points)
|
||||
/// ```
|
||||
public final class TemporalTendency: TemporalAlgorithm {
|
||||
public final class TemporalTendency: TemporalAlgorithmBase {
|
||||
|
||||
private let _distribution: DistributionKind
|
||||
private let _parX: TemporalParameter
|
||||
private let _parY: TemporalParameter
|
||||
private let _parA: TemporalParameter?
|
||||
private let _parB: TemporalParameter?
|
||||
private let _repeats: Int
|
||||
private var _callCount: Int = 0
|
||||
|
||||
/// - Parameters:
|
||||
/// - distribution: Which distribution family to sample from.
|
||||
@@ -84,18 +82,15 @@ public final class TemporalTendency: TemporalAlgorithm {
|
||||
parB: TemporalParameter? = nil,
|
||||
repeats: Int = -1
|
||||
) {
|
||||
|
||||
_distribution = distribution
|
||||
_parX = parX
|
||||
_parY = parY
|
||||
_parA = parA
|
||||
_parB = parB
|
||||
_repeats = repeats
|
||||
super.init(repeats: repeats)
|
||||
}
|
||||
|
||||
public var isExhausted: Bool { _repeats >= 0 && _callCount >= _repeats }
|
||||
|
||||
public func nextValue(
|
||||
override public func nextValue(
|
||||
elapsed: Double,
|
||||
counter: Int,
|
||||
rng: inout UInt64
|
||||
@@ -110,8 +105,8 @@ public final class TemporalTendency: TemporalAlgorithm {
|
||||
return sample
|
||||
}
|
||||
|
||||
public func reset() {
|
||||
_callCount = 0
|
||||
override public func reset() {
|
||||
super.reset()
|
||||
}
|
||||
|
||||
// MARK: - Private
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
// TemporalAlgorithmBase.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Shared base for counter-driven `TemporalAlgorithm` implementations.
|
||||
///
|
||||
/// Provides `_repeats` and `_callCount` storage, a counter-based `isExhausted`,
|
||||
/// and a `reset()` that zeroes `_callCount`. Subclasses override
|
||||
/// `nextValue(elapsed:counter:rng:)` and extend `reset()` via `super.reset()`
|
||||
/// to clear algorithm-specific state.
|
||||
///
|
||||
/// `TemporalClosure` does not subclass this because it exhausts via closure nil
|
||||
/// rather than a repeat counter.
|
||||
open class TemporalAlgorithmBase: TemporalAlgorithm {
|
||||
|
||||
/// Total calls before exhaustion. `-1` = infinite.
|
||||
let _repeats: Int
|
||||
|
||||
/// Number of `nextValue` calls completed so far.
|
||||
var _callCount: Int = 0
|
||||
|
||||
/// - Parameter repeats: Total calls before exhaustion. `-1` = infinite.
|
||||
public init(repeats: Int) {
|
||||
_repeats = repeats
|
||||
}
|
||||
|
||||
/// `true` once `_callCount` has reached `_repeats`. Always `false` when `_repeats < 0`.
|
||||
open var isExhausted: Bool {
|
||||
isCounterExhausted(count: _callCount, limit: _repeats)
|
||||
}
|
||||
|
||||
/// Resets `_callCount` to zero. Subclasses must call `super.reset()` then
|
||||
/// reset algorithm-specific state.
|
||||
open func reset() {
|
||||
_callCount = 0
|
||||
}
|
||||
|
||||
/// Subclasses must override this method to produce values.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - elapsed: Seconds (or beats) since the owning `TemporalStream` received its first call.
|
||||
/// - counter: Zero-based call index from the owning `TemporalStream`.
|
||||
/// - rng: Shared PRNG state from the owning stream.
|
||||
/// - Returns: The next value, or `nil` to signal exhaustion.
|
||||
open func nextValue(
|
||||
elapsed: Double,
|
||||
counter: Int,
|
||||
rng: inout UInt64
|
||||
) -> Double? {
|
||||
fatalError("TemporalAlgorithmBase: subclass must override nextValue(elapsed:counter:rng:)")
|
||||
}
|
||||
}
|
||||
@@ -458,3 +458,163 @@ benchEngine(label: " PitchShift.Audio ×16",
|
||||
warmupIter: psWarmup, benchIter: psIter)
|
||||
|
||||
print("\nblockSize=\(blockSize) sampleRate=44100 graph=16×(OscSin→EnvGen→Pan2→Out) warmup=\(crWarmup) iterations=\(crIter)")
|
||||
|
||||
// ============================================================
|
||||
// MARK: - Generator consolidation + RT performance baseline (GP group)
|
||||
//
|
||||
// Reference numbers for the GP perf phases. Each synth drives a target
|
||||
// generator hard (chained instances) so the target dominates the constant
|
||||
// engine/Pan2/Out overhead; the before/after delta on the identical graph
|
||||
// isolates the generator change. Driven via benchEngine so the engine advances
|
||||
// its segment serial every block (no fan-out cache artifact). Swept at
|
||||
// cbs=512 (one control tick/callback) and cbs=64 (8 sub-blocks/callback) to
|
||||
// show the win-curve across control block sizes.
|
||||
// ============================================================
|
||||
|
||||
print("\n--- GP performance baseline (8-voice target graphs) ---\n")
|
||||
|
||||
let gpVoiceCount: Int = 8
|
||||
let gpWarmup: Int = 500
|
||||
let gpIter: Int = 10_000
|
||||
|
||||
/// `gen × gen` and `gen + gen` arithmetic tree — exercises BinaryOpGenerator's
|
||||
/// generator-vs-generator path (vDSP_vmulD / vDSP_vaddD targets in GP-5).
|
||||
final class BinaryOpVectorSynth: SynthesizerBase {
|
||||
let freq: Double
|
||||
let bus: Int
|
||||
init(freq: Double, bus: Int) {
|
||||
self.freq = freq
|
||||
self.bus = bus
|
||||
super.init()
|
||||
}
|
||||
override func build() {
|
||||
let f: Double = freq
|
||||
let o1: OscSin.Audio = OscSin.Audio(freq: f)
|
||||
let o2: OscSin.Audio = OscSin.Audio(freq: f * 1.5)
|
||||
let o3: OscSin.Audio = OscSin.Audio(freq: f * 2.0)
|
||||
let o4: OscSin.Audio = OscSin.Audio(freq: f * 0.5)
|
||||
let mix: any Generator = (o1 * o2) + (o3 * o4)
|
||||
let mix2: any Generator = (mix * o3) + (o2 * o4)
|
||||
Out.Audio(bus: bus, source: Pan2(input: mix2 * 0.2, pan: 0.0))
|
||||
}
|
||||
}
|
||||
|
||||
/// Alternating `gen × scalar` / `gen + scalar` chain — exercises
|
||||
/// BinaryOpGenerator's generator-vs-scalar path (vDSP_vsmulD / vsaddD in GP-5).
|
||||
final class BinaryOpScalarSynth: SynthesizerBase {
|
||||
let freq: Double
|
||||
let bus: Int
|
||||
init(freq: Double, bus: Int) {
|
||||
self.freq = freq
|
||||
self.bus = bus
|
||||
super.init()
|
||||
}
|
||||
override func build() {
|
||||
let o: OscSin.Audio = OscSin.Audio(freq: freq)
|
||||
let chain: any Generator = ((((o * 0.8) + 0.1) * 0.7) + 0.05) * 0.6
|
||||
Out.Audio(bus: bus, source: Pan2(input: chain, pan: 0.0))
|
||||
}
|
||||
}
|
||||
|
||||
/// Chained unary transcendental math — `Exp(Sqrt(Abs(Sin(x))))`. GP-4 vForce
|
||||
/// targets (vvsin / vvsqrt / vvexp; Abs → vDSP_vabsD). Abs keeps Sqrt input
|
||||
/// non-negative.
|
||||
final class UnaryMathSynth: SynthesizerBase {
|
||||
let freq: Double
|
||||
let bus: Int
|
||||
init(freq: Double, bus: Int) {
|
||||
self.freq = freq
|
||||
self.bus = bus
|
||||
super.init()
|
||||
}
|
||||
override func build() {
|
||||
let o: OscSin.Audio = OscSin.Audio(freq: freq)
|
||||
let s: Sin.Audio = Sin.Audio(o)
|
||||
let a: Abs.Audio = Abs.Audio(s)
|
||||
let r: Sqrt.Audio = Sqrt.Audio(a)
|
||||
let e: Exp.Audio = Exp.Audio(r, mul: 0.1)
|
||||
Out.Audio(bus: bus, source: Pan2(input: e, pan: 0.0))
|
||||
}
|
||||
}
|
||||
|
||||
/// `LinLin.Audio` linear remap — GP-6 `vDSP_vsmsaD` target.
|
||||
final class LinLinSynth: SynthesizerBase {
|
||||
let freq: Double
|
||||
let bus: Int
|
||||
init(freq: Double, bus: Int) {
|
||||
self.freq = freq
|
||||
self.bus = bus
|
||||
super.init()
|
||||
}
|
||||
override func build() {
|
||||
let o: OscSin.Audio = OscSin.Audio(freq: freq)
|
||||
let m: LinLin.Audio = LinLin.Audio(o, inLo: -1.0, inHi: 1.0, outLo: 0.0, outHi: 0.2)
|
||||
Out.Audio(bus: bus, source: Pan2(input: m, pan: 0.0))
|
||||
}
|
||||
}
|
||||
|
||||
/// `SVF.Audio` with a generator-driven cutoff (OscSin LFO sweeping 500–2500 Hz)
|
||||
/// — forces the per-sample `sin()` coefficient path that GP-2/P4 replaces with
|
||||
/// block-boundary interpolation.
|
||||
final class SVFGenFreqSynth: SynthesizerBase {
|
||||
let freq: Double
|
||||
let bus: Int
|
||||
init(freq: Double, bus: Int) {
|
||||
self.freq = freq
|
||||
self.bus = bus
|
||||
super.init()
|
||||
}
|
||||
override func build() {
|
||||
let o: OscSin.Audio = OscSin.Audio(freq: freq)
|
||||
let lfo: OscSin.Audio = OscSin.Audio(freq: 2.0, mul: 1000.0, add: 1500.0)
|
||||
let svf: SVF.Audio = SVF.Audio(input: o, freq: lfo, q: 2.0)
|
||||
Out.Audio(bus: bus, source: Pan2(input: svf.lowpass, pan: 0.0))
|
||||
}
|
||||
}
|
||||
|
||||
/// `Chorus.Audio` on a single oscillator — GP-7 power-of-two delay-line target.
|
||||
final class ChorusBenchSynth: SynthesizerBase {
|
||||
let freq: Double
|
||||
let bus: Int
|
||||
init(freq: Double, bus: Int) {
|
||||
self.freq = freq
|
||||
self.bus = bus
|
||||
super.init()
|
||||
}
|
||||
override func build() {
|
||||
let o: OscSin.Audio = OscSin.Audio(freq: freq)
|
||||
let ch: Chorus.Audio = Chorus.Audio(input: o)
|
||||
Out.Audio(bus: bus, source: Pan2(input: ch, pan: 0.0))
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor func gpPopulate(_ engine: SynthesisEngine, _ make: (Double, Int) -> SynthesizerBase) {
|
||||
for i: Int in 0..<gpVoiceCount {
|
||||
let f: Double = 220.0 * pow(2.0, Double(i) / 12.0)
|
||||
do {
|
||||
try engine.add(make(f, 0))
|
||||
} catch {
|
||||
fatalError("engine.add failed in gpPopulate: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let gpTargets: [(label: String, make: (Double, Int) -> SynthesizerBase)] = [
|
||||
("BinaryOp gen×gen / gen+gen", { BinaryOpVectorSynth(freq: $0, bus: $1) }),
|
||||
("BinaryOp gen×scalar / +scalar", { BinaryOpScalarSynth(freq: $0, bus: $1) }),
|
||||
("Unary math Exp(Sqrt(Abs(Sin)))", { UnaryMathSynth(freq: $0, bus: $1) }),
|
||||
("LinLin.Audio", { LinLinSynth(freq: $0, bus: $1) }),
|
||||
("SVF.Audio gen-driven freq", { SVFGenFreqSynth(freq: $0, bus: $1) }),
|
||||
("Chorus.Audio", { ChorusBenchSynth(freq: $0, bus: $1) }),
|
||||
]
|
||||
|
||||
for target: (label: String, make: (Double, Int) -> SynthesizerBase) in gpTargets {
|
||||
for cbs: Int in [512, 64] {
|
||||
benchEngine(label: " \(target.label) cbs=\(cbs)",
|
||||
controlBlockSize: cbs,
|
||||
populate: { gpPopulate($0, target.make) },
|
||||
warmupIter: gpWarmup, benchIter: gpIter)
|
||||
}
|
||||
}
|
||||
|
||||
print("\nblockSize=\(blockSize) voices=\(gpVoiceCount) warmup=\(gpWarmup) iterations=\(gpIter)")
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
// CLICommand.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Top-level commands parsed from `CommandLine.arguments`.
|
||||
public enum CLICommand: Equatable {
|
||||
/// Build the current package, then launch `swift repl` with Lyrebird available.
|
||||
case repl
|
||||
/// Enter the LineNoise-powered `lyrebird>` interactive shell (no subcommand given).
|
||||
case interactive
|
||||
/// Print usage help.
|
||||
case help
|
||||
/// Print the lyrebird version string.
|
||||
case version
|
||||
/// Scaffold a new Lyrebird project in a directory named `name` using `template`.
|
||||
/// When `lyrebirdPath` is set, the generated `Package.swift` and (where
|
||||
/// applicable) `.xcodeproj` reference Lyrebird as a local SPM package at
|
||||
/// that absolute path instead of pulling from the published Git URL.
|
||||
case new(name: String, template: ProjectTemplate, lyrebirdPath: String?)
|
||||
/// Run the current project with `swift run`.
|
||||
case run(release: Bool)
|
||||
/// Export a named Synthesizer template to a Swift source file.
|
||||
/// When `overwrite` is `true`, an existing file at the destination is replaced.
|
||||
case export(name: String, to: String?, overwrite: Bool)
|
||||
/// Install Lyrebird Xcode file templates to the user template directory.
|
||||
/// When `force` is `true`, replaces any existing installation.
|
||||
case installTemplates(force: Bool)
|
||||
/// Remove Lyrebird Xcode file templates from the user template directory.
|
||||
case uninstallTemplates
|
||||
|
||||
/// Parse the command from a raw arguments array (typically `CommandLine.arguments`).
|
||||
///
|
||||
/// - Parameter arguments: The full argument vector. `arguments[0]` is the binary name;
|
||||
/// `arguments[1]` (if present) is the subcommand.
|
||||
/// - Returns: The matching command, or `.help` for unrecognised or malformed subcommands.
|
||||
public static func parse(_ arguments: [String]) -> CLICommand {
|
||||
guard arguments.count > 1 else { return .interactive }
|
||||
switch arguments[1].lowercased() {
|
||||
case "repl":
|
||||
return .repl
|
||||
|
||||
case "version", "--version":
|
||||
return .version
|
||||
|
||||
case "help", "--help", "-h":
|
||||
return .help
|
||||
|
||||
case "new":
|
||||
guard arguments.count > 2, !arguments[2].isEmpty else { return .help }
|
||||
// If the positional argument looks like a flag, the user omitted the name.
|
||||
guard !arguments[2].hasPrefix("-") else { return .help }
|
||||
let template: ProjectTemplate
|
||||
if let tIdx: Array<String>.Index = arguments.firstIndex(of: "--template"),
|
||||
tIdx + 1 < arguments.count,
|
||||
let t: ProjectTemplate = ProjectTemplate(string: arguments[tIdx + 1]) {
|
||||
template = t
|
||||
} else {
|
||||
template = .basic
|
||||
}
|
||||
// Optional `--lyrebird-path <abs-path>` for local-checkout use.
|
||||
// Value must not be a flag token.
|
||||
let lyrebirdPath: String?
|
||||
if let pIdx: Array<String>.Index = arguments.firstIndex(of: "--lyrebird-path"),
|
||||
pIdx + 1 < arguments.count,
|
||||
!arguments[pIdx + 1].hasPrefix("-") {
|
||||
lyrebirdPath = arguments[pIdx + 1]
|
||||
} else {
|
||||
lyrebirdPath = nil
|
||||
}
|
||||
return .new(name: arguments[2],
|
||||
template: template,
|
||||
lyrebirdPath: lyrebirdPath)
|
||||
|
||||
case "run":
|
||||
let release: Bool = arguments.contains("--release")
|
||||
return .run(release: release)
|
||||
|
||||
case "install-templates":
|
||||
let force: Bool = arguments.contains("--force")
|
||||
return .installTemplates(force: force)
|
||||
|
||||
case "uninstall-templates":
|
||||
return .uninstallTemplates
|
||||
|
||||
case "export":
|
||||
guard arguments.count > 2, !arguments[2].isEmpty else { return .help }
|
||||
let synthName: String = arguments[2]
|
||||
// If the positional argument looks like a flag, the user omitted the name.
|
||||
guard !synthName.hasPrefix("-") else { return .help }
|
||||
// Look for `--to <path>` anywhere after the subcommand.
|
||||
// Guard that the value following `--to` is not itself a flag token.
|
||||
let toPath: String?
|
||||
if let toIdx: Array<String>.Index = arguments.firstIndex(of: "--to"),
|
||||
toIdx + 1 < arguments.count,
|
||||
!arguments[toIdx + 1].hasPrefix("-") {
|
||||
toPath = arguments[toIdx + 1]
|
||||
} else {
|
||||
toPath = nil
|
||||
}
|
||||
let overwrite: Bool = arguments.contains("--overwrite")
|
||||
return .export(name: synthName, to: toPath, overwrite: overwrite)
|
||||
|
||||
default:
|
||||
return .help
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
// ProjectRunner.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
// MARK: - ProjectRunner
|
||||
|
||||
/// Wraps `swift run` to build and launch the current Lyrebird project.
|
||||
///
|
||||
/// `lyrebird run` and `lyrebird run --release` are thin wrappers: they locate the
|
||||
/// `swift` binary and exec `swift run` (optionally with `-c release`) in the current
|
||||
/// working directory. stdin / stdout / stderr are inherited so compiler output and
|
||||
/// runtime output appear directly in the user's terminal.
|
||||
///
|
||||
/// The runner does **not** verify that a `Package.swift` is present before launching —
|
||||
/// SPM provides a clear error message in that case.
|
||||
public enum ProjectRunner {
|
||||
|
||||
// MARK: - Errors
|
||||
|
||||
/// Errors thrown by `ProjectRunner`.
|
||||
public enum Error: Swift.Error, Equatable {
|
||||
/// The `swift` binary could not be found on this system.
|
||||
case swiftNotFound
|
||||
/// The process exited with a non-zero status.
|
||||
case buildFailed(exitCode: Int32)
|
||||
}
|
||||
|
||||
// MARK: - Public API
|
||||
|
||||
/// Build and run the Swift package in `directory`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - release: When `true`, passes `-c release` to `swift run` for an optimised build.
|
||||
/// - directory: The directory containing `Package.swift`.
|
||||
/// Defaults to the current working directory.
|
||||
/// - Throws: `ProjectRunner.Error.swiftNotFound` if the toolchain is absent;
|
||||
/// `ProjectRunner.Error.buildFailed` if `swift run` exits non-zero.
|
||||
public static func run(
|
||||
release: Bool = false,
|
||||
in directory: String = FileManager.default.currentDirectoryPath
|
||||
) throws {
|
||||
let process: Process = try makeProcess(release: release, in: directory)
|
||||
try process.run()
|
||||
process.waitUntilExit()
|
||||
let exitCode: Int32 = process.terminationStatus
|
||||
guard exitCode == 0 else {
|
||||
throw Error.buildFailed(exitCode: exitCode)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Internal
|
||||
|
||||
/// Builds a `Process` configured to run `swift run` (or `swift run -c release`).
|
||||
///
|
||||
/// Exposed for testing so callers can inspect the process configuration without
|
||||
/// actually launching a build.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - release: When `true`, appends `-c release` to the swift arguments.
|
||||
/// - directory: Working directory for the SPM invocation.
|
||||
/// - Throws: `ProjectRunner.Error.swiftNotFound` if the toolchain is absent.
|
||||
public static func makeProcess(
|
||||
release: Bool = false,
|
||||
in directory: String = FileManager.default.currentDirectoryPath
|
||||
) throws -> Process {
|
||||
let swiftPath: String = try findSwift()
|
||||
var arguments: [String] = ["run"]
|
||||
if release {
|
||||
arguments += ["-c", "release"]
|
||||
}
|
||||
let process: Process = Process()
|
||||
process.executableURL = URL(fileURLWithPath: swiftPath)
|
||||
process.arguments = arguments
|
||||
process.currentDirectoryURL = URL(fileURLWithPath: directory)
|
||||
// stdin / stdout / stderr intentionally not set — inherited for interactive output.
|
||||
return process
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
/// Returns the path to the `swift` binary.
|
||||
///
|
||||
/// Checks, in order:
|
||||
/// - `/usr/bin/swift` — Xcode Command Line Tools / Xcode toolchain
|
||||
/// - `/usr/local/bin/swift` — standalone toolchain (Intel Mac default)
|
||||
/// - `/opt/homebrew/bin/swift` — Homebrew toolchain on Apple Silicon
|
||||
///
|
||||
/// Throws `ProjectRunner.Error.swiftNotFound` if none of the candidates exist.
|
||||
static func findSwift() throws -> String {
|
||||
let candidates: [String] = ["/usr/bin/swift", "/usr/local/bin/swift", "/opt/homebrew/bin/swift"]
|
||||
for path: String in candidates where FileManager.default.isExecutableFile(atPath: path) {
|
||||
return path
|
||||
}
|
||||
throw Error.swiftNotFound
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,898 @@
|
||||
// ProjectScaffolder.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
// MARK: - ProjectTemplate
|
||||
|
||||
/// Template style for a scaffolded Lyrebird project.
|
||||
public enum ProjectTemplate: String, CaseIterable, Equatable {
|
||||
/// Minimal engine setup with `CoreAudioDriver` and `RunLoop.main.run()`.
|
||||
case basic = "basic"
|
||||
/// Real-time demo: `SineTone` synthesizer with `@LiveParam` frequency and amplitude.
|
||||
case demo = "demo"
|
||||
/// GUI demo: `@UIParam` synthesizer with a `LyrebirdWindow` SwiftUI panel.
|
||||
case uiDemo = "ui-demo"
|
||||
/// Non-real-time render: `NRTDriver` writes a `.caf` file and exits.
|
||||
case nrt = "nrt"
|
||||
/// Score / MusicXML render: builds a `Score` with the DSL, exports a
|
||||
/// `.musicxml` document, and renders the score offline with `NRTDriver`.
|
||||
case score = "score"
|
||||
/// macOS `.app` bundle wrapping an AppKit + SwiftUI host of a `@UIParam` synth.
|
||||
/// Generates a full `<name>.xcodeproj` referencing Lyrebird via remote SPM dep.
|
||||
case macosUIXcode = "macos-ui-xcode"
|
||||
/// iOS `.app` bundle with `iOSAudioDriver` + SwiftUI UI.
|
||||
/// Generates a full `<name>.xcodeproj` referencing Lyrebird via remote SPM dep.
|
||||
case iosUI = "ios-ui"
|
||||
/// AUv3 host `.app` + `aumu` plugin extension wrapping a Lyrebird synth.
|
||||
/// Generates a full `<name>.xcodeproj` with two targets and entitlements files.
|
||||
case auv3 = "auv3"
|
||||
|
||||
/// Case-insensitive init from a raw string. Accepts hyphen-free aliases too.
|
||||
public init?(string: String) {
|
||||
switch string.lowercased() {
|
||||
case "basic": self = .basic
|
||||
case "demo": self = .demo
|
||||
case "ui-demo", "uidemo", "ui_demo": self = .uiDemo
|
||||
case "nrt": self = .nrt
|
||||
case "score", "score-musicxml", "scoremusicxml", "musicxml":
|
||||
self = .score
|
||||
case "macos-ui-xcode", "macosuixcode", "macos_ui_xcode":
|
||||
self = .macosUIXcode
|
||||
case "ios-ui", "iosui", "ios_ui":
|
||||
self = .iosUI
|
||||
case "auv3", "au-v3", "au_v3":
|
||||
self = .auv3
|
||||
default: return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// True when the template emits a full `.xcodeproj` skeleton in addition
|
||||
/// to the Swift Package. The simpler four templates (basic/demo/ui-demo/nrt)
|
||||
/// rely on Xcode's "Open Package.swift" path; these three need a real
|
||||
/// `.xcodeproj` because they ship an `.app` bundle, app entitlements, or
|
||||
/// (auv3) an `.appex` extension target — none of which SwiftPM can express.
|
||||
public var shipsXcodeProject: Bool {
|
||||
switch self {
|
||||
case .basic, .demo, .uiDemo, .nrt, .score: return false
|
||||
case .macosUIXcode, .iosUI, .auv3: return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ProjectScaffolder
|
||||
|
||||
/// Scaffolds a new Lyrebird project as a Swift Package.
|
||||
///
|
||||
/// `lyrebird new <name>` creates:
|
||||
///
|
||||
/// ```
|
||||
/// <name>/
|
||||
/// ├── Package.swift
|
||||
/// ├── <name>.xcworkspace/
|
||||
/// │ └── contents.xcworkspacedata (references Package.swift — open in Xcode)
|
||||
/// ├── Sources/
|
||||
/// │ └── <name>/
|
||||
/// │ └── main.swift (+ AppDelegate.swift, <name>Synth.swift for ui-demo)
|
||||
/// └── Tests/
|
||||
/// └── <name>Tests/
|
||||
/// └── <name>Tests.swift
|
||||
/// ```
|
||||
///
|
||||
/// Pass `--template demo`, `--template ui-demo`, or `--template nrt` to get richer
|
||||
/// starting points.
|
||||
public enum ProjectScaffolder {
|
||||
|
||||
// MARK: - Errors
|
||||
|
||||
/// Errors thrown by `ProjectScaffolder`.
|
||||
public enum Error: Swift.Error, Equatable {
|
||||
/// The project directory already exists.
|
||||
case projectExists(name: String)
|
||||
/// The project name is empty or contains characters not valid in a Swift module name.
|
||||
case invalidName(name: String)
|
||||
/// A file or directory could not be created.
|
||||
case fileSystemError(path: String, reason: String)
|
||||
}
|
||||
|
||||
// MARK: - Public API
|
||||
|
||||
/// Absolute path to the Lyrebird checkout this CLI was *built* from, derived
|
||||
/// from the compile-time source location of this file
|
||||
/// (`<root>/Sources/LyrebirdCLI/ProjectScaffolder.swift`).
|
||||
///
|
||||
/// Used as the default SPM dependency for scaffolded projects when the caller
|
||||
/// passes no explicit `--lyrebird-path`, so generated projects track the
|
||||
/// current `main` API rather than the published `from:` tag — which lags
|
||||
/// unreleased Score/Generator features (e.g. `Part(clef:)`,
|
||||
/// `ScoreEvent.performedDuration`). This is the pre-1.0-stable policy: the
|
||||
/// template source and the dependency it pins both come from one checkout, so
|
||||
/// they never drift.
|
||||
///
|
||||
/// Returns `nil` when the derived root no longer holds the Lyrebird
|
||||
/// `Package.swift` (the binary was installed away from its source tree);
|
||||
/// callers then fall back to the remote versioned dependency.
|
||||
static var defaultLyrebirdCheckoutPath: String? {
|
||||
lyrebirdCheckoutRoot(forSourceFile: #filePath)
|
||||
}
|
||||
|
||||
/// Testable core of ``defaultLyrebirdCheckoutPath``. Given a source file at
|
||||
/// `<root>/Sources/LyrebirdCLI/<file>.swift`, walks up three directory
|
||||
/// levels to `<root>` and returns it iff `<root>/Package.swift` exists and
|
||||
/// names Lyrebird. Returns `nil` otherwise. Split out so the happy- and
|
||||
/// nil-paths can be unit-tested with synthetic paths (the computed property
|
||||
/// is hard-wired to its own `#filePath`).
|
||||
static func lyrebirdCheckoutRoot(forSourceFile sourceFile: String) -> String? {
|
||||
let root: URL = URL(fileURLWithPath: sourceFile)
|
||||
.deletingLastPathComponent() // strip <file>.swift → Sources/LyrebirdCLI/
|
||||
.deletingLastPathComponent() // → Sources/
|
||||
.deletingLastPathComponent() // → <root>/
|
||||
let manifest: String = root.appendingPathComponent("Package.swift").path
|
||||
guard FileManager.default.fileExists(atPath: manifest) else { return nil }
|
||||
// Guard against pointing at an unrelated parent Package.swift.
|
||||
guard let contents: String = try? String(contentsOfFile: manifest, encoding: .utf8),
|
||||
contents.contains("Lyrebird") else { return nil }
|
||||
return root.path
|
||||
}
|
||||
|
||||
/// Scaffold a new Lyrebird project named `name` inside `parentDirectory`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - name: The project name. Must be a non-empty identifier valid as a Swift module name.
|
||||
/// - template: Starter template style (default `.basic`).
|
||||
/// - parentDirectory: Directory in which to create the project folder.
|
||||
/// Defaults to the current working directory.
|
||||
/// - lyrebirdPath: Absolute path to a local Lyrebird checkout to wire into
|
||||
/// the generated `Package.swift` as a `path:` dependency. `nil` → use
|
||||
/// the published remote package. This is a faithful passthrough: the
|
||||
/// `new` CLI command resolves `nil` to ``defaultLyrebirdCheckoutPath``
|
||||
/// *before* calling this (see `LyrebirdCLI.runNew`), so default
|
||||
/// scaffolds track current `main`; direct library callers get the
|
||||
/// documented `nil` → remote behaviour.
|
||||
/// - Throws: `ProjectScaffolder.Error` on name validation failure or file system errors.
|
||||
public static func scaffold(
|
||||
name: String,
|
||||
template: ProjectTemplate = .basic,
|
||||
in parentDirectory: String = FileManager.default.currentDirectoryPath,
|
||||
lyrebirdPath: String? = nil
|
||||
) throws {
|
||||
try validateName(name)
|
||||
|
||||
let projectRoot: String = (parentDirectory as NSString).appendingPathComponent(name)
|
||||
let fm: FileManager = FileManager.default
|
||||
|
||||
guard !fm.fileExists(atPath: projectRoot) else {
|
||||
throw Error.projectExists(name: name)
|
||||
}
|
||||
|
||||
do {
|
||||
try fm.createDirectory(atPath: projectRoot,
|
||||
withIntermediateDirectories: true,
|
||||
attributes: nil)
|
||||
} catch {
|
||||
throw Error.fileSystemError(path: projectRoot,
|
||||
reason: error.localizedDescription)
|
||||
}
|
||||
|
||||
if template.shipsXcodeProject {
|
||||
try scaffoldXcodeProject(name: name,
|
||||
template: template,
|
||||
projectRoot: projectRoot,
|
||||
lyrebirdPath: lyrebirdPath,
|
||||
fm: fm)
|
||||
} else {
|
||||
try scaffoldSwiftPackage(name: name,
|
||||
template: template,
|
||||
projectRoot: projectRoot,
|
||||
lyrebirdPath: lyrebirdPath,
|
||||
fm: fm)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SPM-only scaffold
|
||||
|
||||
private static func scaffoldSwiftPackage(
|
||||
name: String,
|
||||
template: ProjectTemplate,
|
||||
projectRoot: String,
|
||||
lyrebirdPath: String?,
|
||||
fm: FileManager
|
||||
) throws {
|
||||
let sourcesDir: String = (projectRoot as NSString)
|
||||
.appendingPathComponent("Sources/\(name)")
|
||||
let testsDir: String = (projectRoot as NSString)
|
||||
.appendingPathComponent("Tests/\(name)Tests")
|
||||
let workspaceDir: String = (projectRoot as NSString)
|
||||
.appendingPathComponent("\(name).xcworkspace")
|
||||
|
||||
for dir: String in [sourcesDir, testsDir, workspaceDir] {
|
||||
do {
|
||||
try fm.createDirectory(atPath: dir,
|
||||
withIntermediateDirectories: true,
|
||||
attributes: nil)
|
||||
} catch {
|
||||
try? fm.removeItem(atPath: projectRoot)
|
||||
throw Error.fileSystemError(path: dir,
|
||||
reason: error.localizedDescription)
|
||||
}
|
||||
}
|
||||
|
||||
var files: [(path: String, content: String)] = [
|
||||
(
|
||||
(projectRoot as NSString).appendingPathComponent("Package.swift"),
|
||||
packageManifest(name: name, template: template, lyrebirdPath: lyrebirdPath)
|
||||
),
|
||||
(
|
||||
(sourcesDir as NSString).appendingPathComponent("main.swift"),
|
||||
mainSwift(name: name, template: template)
|
||||
),
|
||||
(
|
||||
(testsDir as NSString).appendingPathComponent("\(name)Tests.swift"),
|
||||
testsSwift(name: name)
|
||||
),
|
||||
(
|
||||
(workspaceDir as NSString).appendingPathComponent("contents.xcworkspacedata"),
|
||||
workspaceContents()
|
||||
),
|
||||
]
|
||||
|
||||
if template == .uiDemo {
|
||||
files += [
|
||||
(
|
||||
(sourcesDir as NSString).appendingPathComponent("AppDelegate.swift"),
|
||||
appDelegateSwift(name: name)
|
||||
),
|
||||
(
|
||||
(sourcesDir as NSString).appendingPathComponent("\(name)Synth.swift"),
|
||||
synthSwift(name: name)
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
try writeFiles(files.map { ($0.path, $0.content) },
|
||||
fm: fm, projectRoot: projectRoot)
|
||||
}
|
||||
|
||||
// MARK: - Xcode-project scaffold dispatch
|
||||
|
||||
private static func scaffoldXcodeProject(
|
||||
name: String,
|
||||
template: ProjectTemplate,
|
||||
projectRoot: String,
|
||||
lyrebirdPath: String?,
|
||||
fm: FileManager
|
||||
) throws {
|
||||
// Every xcode-bearing template ships an `<name>.xcworkspace` that
|
||||
// references the generated `<name>.xcodeproj`. The workspace is
|
||||
// separate from the SPM-only `workspaceContents()` shape because
|
||||
// there is no `Package.swift` at the project root here.
|
||||
let workspaceDir: String = (projectRoot as NSString)
|
||||
.appendingPathComponent("\(name).xcworkspace")
|
||||
do {
|
||||
try fm.createDirectory(atPath: workspaceDir,
|
||||
withIntermediateDirectories: true,
|
||||
attributes: nil)
|
||||
} catch {
|
||||
try? fm.removeItem(atPath: projectRoot)
|
||||
throw Error.fileSystemError(path: workspaceDir,
|
||||
reason: error.localizedDescription)
|
||||
}
|
||||
|
||||
let workspaceFile: String = (workspaceDir as NSString)
|
||||
.appendingPathComponent("contents.xcworkspacedata")
|
||||
try writeFiles([(workspaceFile,
|
||||
xcodeWorkspaceContents(name: name,
|
||||
lyrebirdPath: lyrebirdPath))],
|
||||
fm: fm, projectRoot: projectRoot)
|
||||
|
||||
switch template {
|
||||
case .macosUIXcode:
|
||||
try writeMacOSUIXcodeFiles(name: name, projectRoot: projectRoot,
|
||||
lyrebirdPath: lyrebirdPath, fm: fm)
|
||||
case .iosUI:
|
||||
try writeIOSUIFiles(name: name, projectRoot: projectRoot,
|
||||
lyrebirdPath: lyrebirdPath, fm: fm)
|
||||
case .auv3:
|
||||
try writeAUv3Files(name: name, projectRoot: projectRoot,
|
||||
lyrebirdPath: lyrebirdPath, fm: fm)
|
||||
case .basic, .demo, .uiDemo, .nrt, .score:
|
||||
// Unreachable — shipsXcodeProject filters these out at dispatch.
|
||||
try? fm.removeItem(atPath: projectRoot)
|
||||
throw Error.fileSystemError(
|
||||
path: projectRoot,
|
||||
reason: "scaffoldXcodeProject called with non-Xcode template \(template.rawValue)"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Workspace XML for xcode-bearing templates — references the generated
|
||||
/// `<name>.xcodeproj`. When `lyrebirdPath` is set, the workspace also
|
||||
/// references the Lyrebird `Package.swift` at that absolute path so
|
||||
/// Xcode's IDE-level SPM resolver picks it up at workspace open.
|
||||
/// Without this extra FileRef, opening the workspace in Xcode (vs.
|
||||
/// running `xcodebuild` from the CLI) can fail with "Missing package
|
||||
/// product 'LyrebirdUI'" — the IDE resolver doesn't always crawl into
|
||||
/// member-project `XCLocalSwiftPackageReference` deps automatically.
|
||||
public static func xcodeWorkspaceContents(
|
||||
name: String,
|
||||
lyrebirdPath: String? = nil
|
||||
) -> String {
|
||||
var refs: String = " <FileRef\n location = \"group:\(name).xcodeproj\">\n </FileRef>"
|
||||
if let path: String = lyrebirdPath {
|
||||
let escaped: String = pbxQuoteEscape(path)
|
||||
refs += "\n <FileRef\n location = \"absolute:\(escaped)\">\n </FileRef>"
|
||||
}
|
||||
return """
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Workspace
|
||||
version = "1.0">
|
||||
\(refs)
|
||||
</Workspace>
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: - Template constants
|
||||
|
||||
// Module-internal so extension files (Xcode-template generators) can
|
||||
// reach them. Single source of truth for the engine defaults written
|
||||
// into every scaffolded `main.swift` / app delegate / iOS app shell.
|
||||
static let scaffoldDefaultBlockSize: Int = 512
|
||||
static let scaffoldDefaultSampleRate: Int = 44100
|
||||
static let scaffoldDefaultOutputChannels: Int = 2
|
||||
static let scaffoldDefaultInputChannels: Int = 2
|
||||
static let scaffoldDefaultNRTDuration: Double = 4.0
|
||||
|
||||
// MARK: - Package manifest
|
||||
|
||||
/// `Package.swift` content for a project using the given template.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - name: Module / package name written into the generated manifest.
|
||||
/// Must already be validated as a legal Swift identifier.
|
||||
/// - template: Starter template the manifest is tailored for. Controls
|
||||
/// which target/product entries appear. Defaults to `.basic`.
|
||||
/// - lyrebirdPath: When non-nil, Lyrebird is declared as a local SPM
|
||||
/// dependency (`.package(path: ...)`) at this absolute path. When
|
||||
/// nil, falls back to the published Git URL (``lyrebirdPackageURL``).
|
||||
/// Used by `lyrebird new --lyrebird-path` for users who don't yet
|
||||
/// have access to the public repository.
|
||||
public static func packageManifest(
|
||||
name: String,
|
||||
template: ProjectTemplate = .basic,
|
||||
lyrebirdPath: String? = nil
|
||||
) -> String {
|
||||
// byName resolves only when the product name matches the package
|
||||
// name (`Lyrebird`). Sibling products (`LyrebirdUI`) need the
|
||||
// explicit `.product(name:package:)` form regardless of whether
|
||||
// the dep is local or remote.
|
||||
let targetDeps: String
|
||||
switch template {
|
||||
case .basic, .demo, .nrt, .score:
|
||||
targetDeps = #""Lyrebird""#
|
||||
case .uiDemo:
|
||||
targetDeps = #""Lyrebird", .product(name: "LyrebirdUI", package: "Lyrebird")"#
|
||||
case .macosUIXcode, .iosUI, .auv3:
|
||||
// Xcode-bearing templates don't emit a `Package.swift` — dispatch
|
||||
// never reaches this function for them. Defensive fallthrough.
|
||||
targetDeps = #""Lyrebird", .product(name: "LyrebirdUI", package: "Lyrebird")"#
|
||||
}
|
||||
let depLine: String
|
||||
if let path: String = lyrebirdPath {
|
||||
// `name:` is required so byName target deps (e.g. `"Lyrebird"`)
|
||||
// resolve — SPM otherwise uses the directory basename as the
|
||||
// package identity, which is unlikely to match `"Lyrebird"`
|
||||
// (worktree paths, renamed checkouts, etc.).
|
||||
// Path escaped for safe embedding in a Swift string literal —
|
||||
// same `\\` then `"` escape semantics as `pbxQuoteEscape`.
|
||||
let escapedPath: String = pbxQuoteEscape(path)
|
||||
depLine = #".package(name: "Lyrebird", path: "\#(escapedPath)"),"#
|
||||
} else {
|
||||
depLine = #".package(url: "\#(lyrebirdPackageURL)", from: "\#(lyrebirdMinimumVersion)"),"#
|
||||
}
|
||||
return """
|
||||
// swift-tools-version: 6.0
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "\(name)",
|
||||
platforms: [.macOS(.v15)],
|
||||
dependencies: [
|
||||
\(depLine)
|
||||
],
|
||||
targets: [
|
||||
.executableTarget(
|
||||
name: "\(name)",
|
||||
dependencies: [\(targetDeps)]
|
||||
),
|
||||
.testTarget(
|
||||
name: "\(name)Tests",
|
||||
dependencies: ["\(name)"]
|
||||
),
|
||||
]
|
||||
)
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: - main.swift templates
|
||||
|
||||
/// `main.swift` content for the given template (defaults to `.basic`).
|
||||
public static func mainSwift(
|
||||
name: String,
|
||||
template: ProjectTemplate = .basic
|
||||
) -> String {
|
||||
switch template {
|
||||
case .basic: return mainSwiftBasic(name: name)
|
||||
case .demo: return mainSwiftDemo(name: name)
|
||||
case .uiDemo: return mainSwiftUIDemo(name: name)
|
||||
case .nrt: return mainSwiftNRT(name: name)
|
||||
case .score: return mainSwiftScore(name: name)
|
||||
case .macosUIXcode, .iosUI, .auv3:
|
||||
// Xcode-bearing templates don't emit a `main.swift` under
|
||||
// `Sources/<name>/`. Dispatch never reaches this function for
|
||||
// them. Defensive fallthrough to the basic skeleton.
|
||||
return mainSwiftBasic(name: name)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: basic
|
||||
|
||||
private static func mainSwiftBasic(name: String) -> String {
|
||||
"""
|
||||
// \(name) — entry point
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
// Configure the synthesis engine.
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: \(scaffoldDefaultBlockSize),
|
||||
sampleRate: \(scaffoldDefaultSampleRate),
|
||||
numOutputChannels: \(scaffoldDefaultOutputChannels),
|
||||
numInputChannels: \(scaffoldDefaultInputChannels),
|
||||
driver: CoreAudioDriver()
|
||||
)
|
||||
|
||||
// Add your Synthesizers here.
|
||||
// try engine.add(MySynth())
|
||||
|
||||
do {
|
||||
try engine.start()
|
||||
} catch {
|
||||
fatalError("Engine failed to start: \\(error)")
|
||||
}
|
||||
|
||||
print("\(name) running — press Ctrl+C to stop")
|
||||
RunLoop.main.run()
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: demo
|
||||
|
||||
private static func mainSwiftDemo(name: String) -> String {
|
||||
"""
|
||||
// \(name) — real-time demo
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
// MARK: - SineTone
|
||||
|
||||
final class SineTone: SynthesizerBase {
|
||||
@LiveParam var freq: Double = 440.0
|
||||
@LiveParam var amp: Double = 0.25
|
||||
|
||||
override func build() {
|
||||
let osc = OscSin.Audio(freq: $freq)
|
||||
output(bus: 0, source: Pan2(input: osc * $amp))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Main
|
||||
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: \(scaffoldDefaultBlockSize),
|
||||
sampleRate: \(scaffoldDefaultSampleRate),
|
||||
numOutputChannels: \(scaffoldDefaultOutputChannels),
|
||||
numInputChannels: \(scaffoldDefaultInputChannels),
|
||||
driver: CoreAudioDriver()
|
||||
)
|
||||
|
||||
do {
|
||||
try engine.start()
|
||||
} catch {
|
||||
fatalError("Engine failed to start: \\(error)")
|
||||
}
|
||||
|
||||
let tone = SineTone()
|
||||
do {
|
||||
try engine.add(tone)
|
||||
} catch {
|
||||
fatalError("Engine.add failed: \\(error)")
|
||||
}
|
||||
|
||||
print("\(name) running — press Ctrl+C to stop")
|
||||
print("Update tone.freq or tone.amp from the REPL to change parameters.")
|
||||
RunLoop.main.run()
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: ui-demo (main.swift only — AppDelegate and Synth are separate files)
|
||||
|
||||
private static func mainSwiftUIDemo(name: String) -> String {
|
||||
"""
|
||||
// \(name) — GUI demo
|
||||
import AppKit
|
||||
import LyrebirdSynth
|
||||
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: \(scaffoldDefaultBlockSize),
|
||||
sampleRate: \(scaffoldDefaultSampleRate),
|
||||
numOutputChannels: \(scaffoldDefaultOutputChannels),
|
||||
numInputChannels: 0,
|
||||
driver: CoreAudioDriver()
|
||||
)
|
||||
|
||||
let delegate = AppDelegate(engine: engine)
|
||||
NSApplication.shared.setActivationPolicy(.regular)
|
||||
NSApplication.shared.delegate = delegate
|
||||
NSApplication.shared.run()
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: nrt
|
||||
|
||||
private static func mainSwiftNRT(name: String) -> String {
|
||||
"""
|
||||
// \(name) — non-real-time render
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
// MARK: - \(name)Synth
|
||||
|
||||
final class \(name)Synth: SynthesizerBase {
|
||||
override func build() {
|
||||
let env = EnvelopeGen.Audio(
|
||||
envelope: Envelope(
|
||||
levels: [0, 1, 0.6, 0],
|
||||
durations: [0.02, 0.46, 0.5],
|
||||
curves: [0, 0, 0]
|
||||
)
|
||||
)
|
||||
let osc = OscSin.Audio(freq: 440.0) * env * 0.3
|
||||
output(bus: 0, source: Pan2(input: osc))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Render
|
||||
|
||||
let outputURL = URL(fileURLWithPath: "output.caf")
|
||||
let renderDuration = \(scaffoldDefaultNRTDuration)
|
||||
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: \(scaffoldDefaultBlockSize),
|
||||
sampleRate: \(scaffoldDefaultSampleRate),
|
||||
numOutputChannels: \(scaffoldDefaultOutputChannels),
|
||||
numInputChannels: 0,
|
||||
driver: NRTDriver(outputURL: outputURL, duration: renderDuration)
|
||||
)
|
||||
|
||||
// Add synthesizers BEFORE start() — NRTDriver renders synchronously inside start().
|
||||
do {
|
||||
try engine.add(\(name)Synth())
|
||||
} catch {
|
||||
fputs("engine.add failed: \\(error)\\n", stderr)
|
||||
exit(1)
|
||||
}
|
||||
|
||||
do {
|
||||
try engine.start()
|
||||
print("Rendered \\(renderDuration)s → \\(outputURL.path)")
|
||||
} catch {
|
||||
fputs("Render failed: \\(error)\\n", stderr)
|
||||
exit(1)
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: score
|
||||
|
||||
private static func mainSwiftScore(name: String) -> String {
|
||||
"""
|
||||
// \(name) — Score / MusicXML render
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
// MARK: - ScoreVoice
|
||||
|
||||
/// One self-freeing voice per score event. The envelope's `freeNode`
|
||||
/// done-action removes the synth when its note finishes, so scheduled
|
||||
/// voices never accumulate during the offline render.
|
||||
final class ScoreVoice: SynthesizerBase {
|
||||
let freqHz: Double
|
||||
let amp: Double
|
||||
let durSeconds: Double
|
||||
let pan: Double
|
||||
|
||||
init(freqHz: Double, amp: Double, durSeconds: Double, pan: Double = 0.0) {
|
||||
self.freqHz = freqHz
|
||||
self.amp = amp
|
||||
self.durSeconds = durSeconds
|
||||
self.pan = pan
|
||||
super.init()
|
||||
}
|
||||
|
||||
override func build() {
|
||||
let attack = 0.01
|
||||
let release = 0.06
|
||||
let sustain = max(0.0, durSeconds - attack - release)
|
||||
let envelope = Envelope(
|
||||
levels: [0.0, 1.0, 0.8, 0.0],
|
||||
durations: [attack, sustain, release],
|
||||
curves: [-4.0, 0.0, -6.0]
|
||||
)
|
||||
let osc = OscSawtooth.Audio(freq: freqHz)
|
||||
let env = EnvelopeGen.Control(envelope: envelope, doneAction: .freeNode)
|
||||
output(bus: 0, source: Pan2(input: osc * env * amp, pan: pan))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Build the score
|
||||
|
||||
let bpm = 120.0
|
||||
let secondsPerBeat = 60.0 / bpm
|
||||
|
||||
// Author music with the Score DSL: Note, Rest, Chord, Tuplet, dynamics,
|
||||
// and articulations. Pitch spelling (letter + accidental) is preserved
|
||||
// through MusicXML export. `Generate` and `PatternNotes` add algorithmic
|
||||
// generation (see the "texture" part below).
|
||||
//
|
||||
// Further notation (see the Lyrebird ScoreSystem docs): Slur / Crescendo /
|
||||
// Diminuendo spans, per-note `spanners:` (overlapping spans, glissandi /
|
||||
// slides), per-note `display:` (NoteDisplay — notehead/size/hide stem or
|
||||
// beam), `Section("…") { }` blocks with rehearsal marks, and a `pageLayout:`
|
||||
// (PageLayout — page size, orientation, margins).
|
||||
let score = Score(bpm: bpm, timeSignature: TimeSignature(4, 4)) {
|
||||
Part("lead") {
|
||||
// A crescendo hairpin over the opening arpeggio (notation-only).
|
||||
Crescendo {
|
||||
Note(.named(.c, 5), dur: .quarter, dyn: .mf, art: .staccato)
|
||||
Note(.named(.e, 5), dur: .quarter, dyn: .mf, art: .staccato)
|
||||
Note(.named(.g, 5), dur: .quarter, dyn: .f, art: .accent)
|
||||
}
|
||||
Rest(dur: .quarter)
|
||||
Tuplet(3, inTimeOf: 2) {
|
||||
Note(.named(.b, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.a, 5), dur: .quarter, dyn: .mp)
|
||||
Note(.named(.g, 5), dur: .quarter, dyn: .mp)
|
||||
}
|
||||
Chord([.named(.c, 5), .named(.e, 5), .named(.g, 5)], dur: .half, dyn: .f, art: .tenuto)
|
||||
}
|
||||
Part("bass", channel: 1, clef: .bass) {
|
||||
Note(.named(.c, 3), dur: .whole, dyn: .mp)
|
||||
Note(.named(.g, 2), dur: .half, dyn: .p)
|
||||
Note(.named(.c, 3), dur: .half, dyn: .mp, art: .tenuto)
|
||||
}
|
||||
// Texture — algorithmic generation. `Generate` maps an index range
|
||||
// through the builder; `PatternNotes` pulls from a `Pattern` source.
|
||||
Part("texture", channel: 2) {
|
||||
Generate(8) { i in
|
||||
Note(midi: 72 + (i % 6) * 2, dur: .sixteenth, dyn: .pp, art: .staccato)
|
||||
}
|
||||
PatternNotes(count: 4, midi: Pattern.series(start: 60, step: 3, length: 4), dur: .eighth, dyn: .p)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Output location
|
||||
|
||||
// Write next to this project's source rather than the launch directory.
|
||||
// `LyrebirdPaths.projectRoot()` walks up from this file to the folder
|
||||
// containing Package.swift, so output lands in the project regardless of
|
||||
// how the binary is launched (lyrebird run, swift run, or Xcode — whose
|
||||
// working directory is DerivedData). Dev-time convenience; for a shipped
|
||||
// app writing user data, use `LyrebirdPaths.documents` instead.
|
||||
let outputDir = LyrebirdPaths.projectRoot() ?? LyrebirdPaths.currentWorkingDirectory
|
||||
|
||||
// MARK: - Export MusicXML
|
||||
|
||||
let xmlURL = outputDir.appendingPathComponent("score.musicxml")
|
||||
do {
|
||||
let xml = score.toMusicXMLString()
|
||||
try xml.write(to: xmlURL, atomically: true, encoding: .utf8)
|
||||
print("MusicXML written → \\(xmlURL.path)")
|
||||
} catch {
|
||||
fputs("MusicXML export failed: \\(error)\\n", stderr)
|
||||
exit(1)
|
||||
}
|
||||
|
||||
// Round-trip sanity check: parse the document back in and compare counts.
|
||||
do {
|
||||
let restored = try Score.fromMusicXML(data: score.toMusicXMLData())
|
||||
print("Round-trip events: \\(score.allEvents.count) → \\(restored.allEvents.count)")
|
||||
} catch {
|
||||
fputs("MusicXML round-trip failed: \\(error)\\n", stderr)
|
||||
}
|
||||
|
||||
// MARK: - Render the score offline
|
||||
|
||||
let tailSeconds = 1.5
|
||||
let renderDuration = score.totalBeats * secondsPerBeat + tailSeconds
|
||||
let outputURL = outputDir.appendingPathComponent("score.caf")
|
||||
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: \(scaffoldDefaultBlockSize),
|
||||
sampleRate: \(scaffoldDefaultSampleRate),
|
||||
numOutputChannels: \(scaffoldDefaultOutputChannels),
|
||||
numInputChannels: 0,
|
||||
driver: NRTDriver(outputURL: outputURL, duration: renderDuration)
|
||||
)
|
||||
|
||||
// Schedule one voice per sounding event BEFORE start() — NRTDriver
|
||||
// renders synchronously inside start().
|
||||
var scheduled = 0
|
||||
for event in score.allEvents {
|
||||
guard !event.isRest else { continue }
|
||||
guard let freqHz = event.pitch.frequency else { continue }
|
||||
let pan = event.channel == 0 ? -0.4 : 0.5
|
||||
let voice = ScoreVoice(
|
||||
freqHz: freqHz,
|
||||
amp: event.velocity * 0.35,
|
||||
durSeconds: event.performedDuration * secondsPerBeat,
|
||||
pan: pan
|
||||
)
|
||||
do {
|
||||
try engine.schedule(voice, after: event.beat * secondsPerBeat)
|
||||
scheduled += 1
|
||||
} catch {
|
||||
fputs("engine.schedule failed: \\(error)\\n", stderr)
|
||||
}
|
||||
}
|
||||
print("Scheduled \\(scheduled) voices.")
|
||||
|
||||
do {
|
||||
try engine.start()
|
||||
print("Rendered \\(renderDuration)s → \\(outputURL.path)")
|
||||
} catch {
|
||||
fputs("Render failed: \\(error)\\n", stderr)
|
||||
exit(1)
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: - ui-demo additional files
|
||||
|
||||
/// `AppDelegate.swift` content for a ui-demo project.
|
||||
public static func appDelegateSwift(name: String) -> String {
|
||||
"""
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
let engine: SynthesisEngine
|
||||
let synth: \(name)Synth
|
||||
var window: LyrebirdWindow?
|
||||
|
||||
@MainActor
|
||||
init(engine: SynthesisEngine) {
|
||||
self.engine = engine
|
||||
self.synth = \(name)Synth()
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func applicationDidFinishLaunching(_ notification: Notification) {
|
||||
do {
|
||||
try engine.start()
|
||||
} catch {
|
||||
print("Engine.start failed: \\(error)")
|
||||
NSApp.terminate(nil)
|
||||
return
|
||||
}
|
||||
do {
|
||||
try engine.add(synth)
|
||||
} catch {
|
||||
print("Engine.add failed: \\(error)")
|
||||
engine.stop()
|
||||
NSApp.terminate(nil)
|
||||
return
|
||||
}
|
||||
|
||||
window = LyrebirdWindow(title: "\(name)", width: 320, height: 200)
|
||||
window?.open {
|
||||
VStack(spacing: 16) {
|
||||
ParameterSlider("Frequency", node: self.synth.$freq, range: 110...1760)
|
||||
ParameterKnob("Amplitude", node: self.synth.$amp, range: 0...1)
|
||||
ParameterKnob("Pan", node: self.synth.$pan, range: -1...1)
|
||||
}
|
||||
.padding(24)
|
||||
}
|
||||
}
|
||||
|
||||
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
|
||||
true
|
||||
}
|
||||
|
||||
func applicationWillTerminate(_ notification: Notification) {
|
||||
engine.stop()
|
||||
}
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
/// `<name>Synth.swift` content for a ui-demo project.
|
||||
public static func synthSwift(name: String) -> String {
|
||||
"""
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
final class \(name)Synth: SynthesizerBase {
|
||||
@UIParam var freq: Double = 440.0
|
||||
@UIParam var amp: Double = 0.25
|
||||
@UIParam var pan: Double = 0.0
|
||||
|
||||
override func build() {
|
||||
let osc = OscSin.Audio(freq: $freq)
|
||||
output(bus: 0, source: Pan2(input: osc * $amp, pan: $pan))
|
||||
}
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: - Xcode workspace
|
||||
|
||||
/// `contents.xcworkspacedata` body. The single `FileRef` points at the
|
||||
/// workspace's enclosing directory (`group:.`) — the package root that
|
||||
/// holds `Package.swift` — so Xcode recognises it as a Swift package and
|
||||
/// opens the full `Sources/` / `Tests/` tree with a runnable scheme.
|
||||
/// (Referencing the `Package.swift` *file* instead loads a single loose
|
||||
/// document with no schemes — `xcodebuild -list` reports "no schemes".)
|
||||
/// Identical for every SPM template — the file lives at
|
||||
/// `<name>.xcworkspace/contents.xcworkspacedata`.
|
||||
public static func workspaceContents() -> String {
|
||||
"""
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Workspace
|
||||
version = "1.0">
|
||||
<FileRef
|
||||
location = "group:.">
|
||||
</FileRef>
|
||||
</Workspace>
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: - Tests template
|
||||
|
||||
/// Starter test file content (shared across all templates).
|
||||
public static func testsSwift(name: String) -> String {
|
||||
"""
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
|
||||
@Suite("\(name)")
|
||||
struct \(name)Tests {
|
||||
|
||||
@Test func engineStartsClean() throws {
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: \(scaffoldDefaultBlockSize),
|
||||
sampleRate: \(scaffoldDefaultSampleRate),
|
||||
numOutputChannels: \(scaffoldDefaultOutputChannels),
|
||||
numInputChannels: \(scaffoldDefaultInputChannels),
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
try engine.start()
|
||||
engine.processBlock(inputSamples: [])
|
||||
engine.stop()
|
||||
#expect(engine.audioBuses[0].allSatisfy { $0 == 0.0 })
|
||||
}
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
/// Validate that `name` is a non-empty Swift-compatible identifier.
|
||||
static func validateName(_ name: String) throws {
|
||||
try validateSwiftIdentifier(name, invalidNameError: Error.invalidName(name: name))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
// REPLLauncher.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Errors thrown by `REPLLauncher`.
|
||||
public enum CLIError: Error {
|
||||
/// The `swift` binary could not be found on this system.
|
||||
case swiftNotFound
|
||||
/// `swift build` exited non-zero. REPL launch was aborted.
|
||||
case buildFailed(exitCode: Int32)
|
||||
}
|
||||
|
||||
/// Locates the Swift toolchain, builds the current package, and launches `swift repl`
|
||||
/// with module/library flags pointing at the package's `.build/debug` artifacts so
|
||||
/// `import LyrebirdSynth` works immediately.
|
||||
///
|
||||
/// The Swift Package Manager's `swift package repl` subcommand was removed from the
|
||||
/// toolchain. The replacement is a two-step invocation: `swift build` to produce the
|
||||
/// package's `.swiftmodule` + library, then `swift repl` with `-I` / `-L` / `-l` flags
|
||||
/// pointing at `.build/debug`. See `docs/tooling/repl.md`.
|
||||
public enum REPLLauncher {
|
||||
|
||||
/// Arguments passed to `swift` for the build step that precedes the REPL.
|
||||
public static let buildArguments: [String] = ["build"]
|
||||
|
||||
/// Arguments passed to `swift` to start the REPL. Resolves modules from the package's
|
||||
/// `.build/debug` directory:
|
||||
/// - `-I .build/debug/Modules` — Swift modules (LyrebirdSynth.swiftmodule, ...)
|
||||
/// - `-I .build/debug/LyrebirdC.build` — LyrebirdC C-module modulemap
|
||||
/// - `-L .build/debug -lLyrebird` — link the Lyrebird dylib
|
||||
///
|
||||
/// Paths are relative; `makeProcess(in:)` sets the working directory so the user can
|
||||
/// run from a project root whose `Package.swift` depends on Lyrebird (or from the
|
||||
/// Lyrebird package directory itself).
|
||||
public static let replArguments: [String] = [
|
||||
"repl",
|
||||
"-I", ".build/debug/Modules",
|
||||
"-I", ".build/debug/LyrebirdC.build",
|
||||
"-L", ".build/debug",
|
||||
"-lLyrebird"
|
||||
]
|
||||
|
||||
/// Path to the shared Lyrebird history file used by the interactive shell
|
||||
/// and other tooling that needs persistent command history.
|
||||
public static var historyFilePath: String {
|
||||
FileManager.default.homeDirectoryForCurrentUser
|
||||
.appendingPathComponent(".lyrebird_history").path
|
||||
}
|
||||
|
||||
/// Returns the path to the `swift` binary.
|
||||
///
|
||||
/// Checks `/usr/bin/swift` (Xcode toolchain on macOS) and `/usr/local/bin/swift`
|
||||
/// (standalone toolchain). Throws `CLIError.swiftNotFound` if neither exists.
|
||||
public static func findSwift() throws -> String {
|
||||
let candidates: [String] = ["/usr/bin/swift", "/usr/local/bin/swift"]
|
||||
for path: String in candidates where FileManager.default.isExecutableFile(atPath: path) {
|
||||
return path
|
||||
}
|
||||
throw CLIError.swiftNotFound
|
||||
}
|
||||
|
||||
/// Builds a `Process` that runs `swift` with the given arguments in `directory`.
|
||||
/// stdin / stdout / stderr inherited from the calling process.
|
||||
public static func makeProcess(
|
||||
arguments: [String],
|
||||
in directory: String = FileManager.default.currentDirectoryPath
|
||||
) throws -> Process {
|
||||
let swiftPath: String = try findSwift()
|
||||
let process: Process = Process()
|
||||
process.executableURL = URL(fileURLWithPath: swiftPath)
|
||||
process.arguments = arguments
|
||||
process.currentDirectoryURL = URL(fileURLWithPath: directory)
|
||||
return process
|
||||
}
|
||||
|
||||
/// Builds a `Process` configured to run `swift repl` with module/library flags in `directory`.
|
||||
public static func makeProcess(
|
||||
in directory: String = FileManager.default.currentDirectoryPath
|
||||
) throws -> Process {
|
||||
try makeProcess(arguments: replArguments, in: directory)
|
||||
}
|
||||
|
||||
/// Runs `swift build` and waits for it to finish. Throws `CLIError.buildFailed`
|
||||
/// if the build exited non-zero. If the build was killed by a signal,
|
||||
/// `exitCode` is reported as `1` (rather than the raw signal number, which
|
||||
/// would mislead callers that propagate it through `exit(_:)`).
|
||||
public static func build(
|
||||
in directory: String = FileManager.default.currentDirectoryPath
|
||||
) throws {
|
||||
let process: Process = try makeProcess(arguments: buildArguments, in: directory)
|
||||
try process.run()
|
||||
process.waitUntilExit()
|
||||
if process.terminationReason != .exit {
|
||||
throw CLIError.buildFailed(exitCode: 1)
|
||||
}
|
||||
if process.terminationStatus != 0 {
|
||||
throw CLIError.buildFailed(exitCode: process.terminationStatus)
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds the package, then launches `swift repl` with Lyrebird available.
|
||||
/// Blocks until the REPL session ends.
|
||||
///
|
||||
/// - Parameter directory: Working directory for the SPM + REPL invocation.
|
||||
/// Defaults to the current directory. Must contain a `Package.swift`.
|
||||
public static func launch(
|
||||
in directory: String = FileManager.default.currentDirectoryPath
|
||||
) throws {
|
||||
try build(in: directory)
|
||||
let process: Process = try makeProcess(in: directory)
|
||||
try process.run()
|
||||
process.waitUntilExit()
|
||||
}
|
||||
}
|
||||
Vendored
+1
-1
@@ -157,7 +157,7 @@ public enum ___FILEBASENAMEASIDENTIFIER___ {
|
||||
|
||||
let dt = freq / sampleRate
|
||||
_phase += dt * countFloat
|
||||
normalizeLFPhase(&_phase)
|
||||
normalizeOscPhase(&_phase)
|
||||
|
||||
let target = ___FILEBASENAMEASIDENTIFIER___._waveform(_phase)
|
||||
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
// TemplateInstaller.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Installs the bundled Lyrebird Xcode file templates into the user template
|
||||
/// directory so Xcode's New File dialog (⌘N) discovers them.
|
||||
///
|
||||
/// The templates ship as a copied SPM resource on the `LyrebirdCLI` target —
|
||||
/// `Bundle.module.resourceURL.appendingPathComponent("XcodeTemplates")` resolves
|
||||
/// to the directory holding every `.xctemplate` bundle.
|
||||
///
|
||||
/// User template destination:
|
||||
/// `~/Library/Developer/Xcode/Templates/File Templates/Lyrebird/`
|
||||
///
|
||||
/// Apple guarantees this path is the user-scoped template scan root used by
|
||||
/// every recent Xcode version. No Xcode restart is required — the dialog
|
||||
/// rescans on next open.
|
||||
public enum TemplateInstaller {
|
||||
|
||||
/// Errors thrown by `install` / `uninstall`.
|
||||
public enum Error: Swift.Error, Equatable {
|
||||
/// Resource bundle did not contain the expected `XcodeTemplates` directory.
|
||||
/// Indicates a build configuration problem, not a user error.
|
||||
case bundleMissingTemplates(expectedPath: String)
|
||||
/// Destination exists already and `force` was `false`.
|
||||
case destinationExists(path: String)
|
||||
/// Underlying `FileManager` error wrapped with the path that failed.
|
||||
case fileSystemError(path: String, reason: String)
|
||||
}
|
||||
|
||||
/// Subdirectory name inside the LyrebirdCLI resource bundle.
|
||||
static let resourceSubdir: String = "XcodeTemplates"
|
||||
|
||||
/// Last path component under the user's Xcode template dir. The "File Templates"
|
||||
/// parent is fixed by Xcode; only this trailing segment is owned by Lyrebird and
|
||||
/// can therefore be safely removed by `uninstall`.
|
||||
public static let installDirName: String = "Lyrebird"
|
||||
|
||||
/// `~/Library/Developer/Xcode/Templates/File Templates/Lyrebird/`
|
||||
public static var destinationURL: URL {
|
||||
FileManager.default.homeDirectoryForCurrentUser
|
||||
.appendingPathComponent("Library/Developer/Xcode/Templates/File Templates/\(installDirName)", isDirectory: true)
|
||||
}
|
||||
|
||||
/// Resolves `Bundle.module`'s `XcodeTemplates` resource subdir, or throws if missing.
|
||||
static func sourceURL() throws -> URL {
|
||||
guard let resourceURL: URL = Bundle.module.resourceURL else {
|
||||
throw Error.bundleMissingTemplates(expectedPath: "<no resourceURL>")
|
||||
}
|
||||
let candidate: URL = resourceURL.appendingPathComponent(resourceSubdir, isDirectory: true)
|
||||
guard FileManager.default.fileExists(atPath: candidate.path) else {
|
||||
throw Error.bundleMissingTemplates(expectedPath: candidate.path)
|
||||
}
|
||||
return candidate
|
||||
}
|
||||
|
||||
/// Lists the `.xctemplate` bundle names inside the source resource directory.
|
||||
public static func availableTemplates() throws -> [String] {
|
||||
let src: URL = try sourceURL()
|
||||
let contents: [String] = try FileManager.default.contentsOfDirectory(atPath: src.path)
|
||||
return contents.filter { $0.hasSuffix(".xctemplate") }.sorted()
|
||||
}
|
||||
|
||||
/// Copies every `.xctemplate` from the bundle to `destinationURL`.
|
||||
///
|
||||
/// - Parameter force: When `true`, overwrites an existing destination directory.
|
||||
/// When `false`, throws `Error.destinationExists` if the destination already
|
||||
/// exists. Per-template overwrite is unconditional once we've decided to write
|
||||
/// — `force` is the top-level guard.
|
||||
/// - Returns: Number of templates copied.
|
||||
@discardableResult
|
||||
public static func install(force: Bool = false) throws -> Int {
|
||||
let src: URL = try sourceURL()
|
||||
let dest: URL = destinationURL
|
||||
let fm: FileManager = FileManager.default
|
||||
|
||||
if fm.fileExists(atPath: dest.path) {
|
||||
if !force {
|
||||
throw Error.destinationExists(path: dest.path)
|
||||
}
|
||||
do {
|
||||
try fm.removeItem(at: dest)
|
||||
} catch {
|
||||
throw Error.fileSystemError(path: dest.path, reason: error.localizedDescription)
|
||||
}
|
||||
}
|
||||
|
||||
// Recreate the destination dir.
|
||||
do {
|
||||
try fm.createDirectory(at: dest, withIntermediateDirectories: true)
|
||||
} catch {
|
||||
throw Error.fileSystemError(path: dest.path, reason: error.localizedDescription)
|
||||
}
|
||||
|
||||
// Copy each .xctemplate bundle.
|
||||
let templates: [String] = try availableTemplates()
|
||||
for name: String in templates {
|
||||
let from: URL = src.appendingPathComponent(name, isDirectory: true)
|
||||
let to: URL = dest.appendingPathComponent(name, isDirectory: true)
|
||||
do {
|
||||
try fm.copyItem(at: from, to: to)
|
||||
} catch {
|
||||
throw Error.fileSystemError(path: to.path, reason: error.localizedDescription)
|
||||
}
|
||||
}
|
||||
|
||||
return templates.count
|
||||
}
|
||||
|
||||
/// Removes the entire `~/Library/.../File Templates/Lyrebird/` directory.
|
||||
///
|
||||
/// - Returns: `true` if the directory existed and was removed; `false` if it
|
||||
/// was not installed.
|
||||
@discardableResult
|
||||
public static func uninstall() throws -> Bool {
|
||||
let dest: URL = destinationURL
|
||||
let fm: FileManager = FileManager.default
|
||||
guard fm.fileExists(atPath: dest.path) else { return false }
|
||||
do {
|
||||
try fm.removeItem(at: dest)
|
||||
} catch {
|
||||
throw Error.fileSystemError(path: dest.path, reason: error.localizedDescription)
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -134,6 +134,37 @@ struct BinaryOpGeneratorTests {
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == 7.0 })
|
||||
}
|
||||
|
||||
// Order-sensitive operands: a flipped vDSP subtract/divide argument order
|
||||
// would produce the reciprocal/negated value, so these lock the orientation.
|
||||
|
||||
@Test func scalarMinusGenerator() {
|
||||
let count: Int = 8
|
||||
let gen: BinaryOpGenerator = (1.0 as Double) - ConstantAudioGen(0.25)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == 0.75 })
|
||||
}
|
||||
|
||||
@Test func scalarDividedByGenerator() {
|
||||
let count: Int = 8
|
||||
let gen: BinaryOpGenerator = (1.0 as Double) / ConstantAudioGen(4.0)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == 0.25 })
|
||||
}
|
||||
|
||||
@Test func generatorMinusGenerator() {
|
||||
let count: Int = 8
|
||||
let gen: BinaryOpGenerator = ConstantAudioGen(3.0) - ConstantAudioGen(2.0)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == 1.0 })
|
||||
}
|
||||
|
||||
@Test func generatorDividedByGenerator() {
|
||||
let count: Int = 8
|
||||
let gen: BinaryOpGenerator = ConstantAudioGen(8.0) / ConstantAudioGen(2.0)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == 4.0 })
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Multi-channel broadcast
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
// MusicXMLBarlineExactFillTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
/// Regression coverage for two MusicXML-export defects exposed by sectioned
|
||||
/// scores with rest-padded short parts.
|
||||
///
|
||||
/// 1. **Barline-exact-fill rounding.** In the single-voice encoder, when a
|
||||
/// note/rest that crosses a barline has its FINAL piece land exactly on the
|
||||
/// next barline (`leftover` and the measure's `remaining` capacity reach zero
|
||||
/// together), the measure was left open with `remaining == 0`. The next
|
||||
/// sounding atom could then neither fit nor split cleanly: the split loop
|
||||
/// emitted a spurious `max(1, …)` one-division piece before the bar finally
|
||||
/// closed, tying it forward and shifting every later note by one division
|
||||
/// (visually turning constant 4/4 bars into 5/4).
|
||||
/// 2. **Non-bar-aligned rest padding.** Section auto-padding decomposed the
|
||||
/// whole gap greedily into the largest representable rests (a 21-beat gap
|
||||
/// became three double-dotted-whole rests) with no bar alignment, so the
|
||||
/// encoder split them into metrically-wrong fragments (a quarter + dotted-half
|
||||
/// rest crossing the mid-bar strong beat) instead of clean whole-measure rests.
|
||||
@MainActor
|
||||
@Suite("MusicXML — barline-exact-fill rounding")
|
||||
struct MusicXMLBarlineExactFillTests {
|
||||
|
||||
/// Split a part's body into `(measureNumber, measureBody)` pairs using the
|
||||
/// codebase's string-splitting idiom (no regex).
|
||||
private func measureBlocks(_ xml: String, part pid: String) -> [(number: String, body: String)] {
|
||||
guard let partStart: Range<String.Index> = xml.range(of: "<part id=\"\(pid)\">"),
|
||||
let partEnd: Range<String.Index> = xml.range(
|
||||
of: "</part>",
|
||||
range: partStart.upperBound..<xml.endIndex
|
||||
) else {
|
||||
return []
|
||||
}
|
||||
let partBody: String = String(xml[partStart.upperBound..<partEnd.lowerBound])
|
||||
var blocks: [(number: String, body: String)] = []
|
||||
let chunks: [String] = partBody.components(separatedBy: "<measure number=\"")
|
||||
for chunk: String in chunks.dropFirst() {
|
||||
guard let quote: Range<String.Index> = chunk.range(of: "\"") else { continue }
|
||||
let number: String = String(chunk[chunk.startIndex..<quote.lowerBound])
|
||||
blocks.append((number: number, body: chunk))
|
||||
}
|
||||
return blocks
|
||||
}
|
||||
|
||||
/// Sum the `<duration>` of every non-chord `<note>` in a measure body.
|
||||
private func durationSum(_ measureBody: String) -> Int {
|
||||
var total: Int = 0
|
||||
let notes: [String] = measureBody.components(separatedBy: "<note>")
|
||||
for note: String in notes.dropFirst() {
|
||||
if note.contains("<chord/>") { continue }
|
||||
guard let open: Range<String.Index> = note.range(of: "<duration>"),
|
||||
let close: Range<String.Index> = note.range(
|
||||
of: "</duration>",
|
||||
range: open.upperBound..<note.endIndex
|
||||
),
|
||||
let value: Int = Int(note[open.upperBound..<close.lowerBound]) else {
|
||||
continue
|
||||
}
|
||||
total += value
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
/// A breve (8 beats) in 4/4 exactly fills two bars; the following whole note
|
||||
/// must land cleanly on bar 3, NOT be split into a 1-division sliver in bar 2.
|
||||
@Test func breveThenWholeNoteNoSliver() {
|
||||
let divisions: Int = 480
|
||||
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
|
||||
Part("lead") {
|
||||
Note(.c, 4, dur: .doubleWhole) // fills bars 1-2 exactly (8 beats)
|
||||
Note(.d, 4, dur: .whole) // must be bar 3, all 4 beats
|
||||
Note(.e, 4, dur: .whole) // bar 4
|
||||
}
|
||||
}
|
||||
let xml: String = score.toMusicXMLString(divisions: divisions)
|
||||
for block: (number: String, body: String) in measureBlocks(xml, part: "P1") {
|
||||
#expect(
|
||||
durationSum(block.body) == 4 * divisions,
|
||||
"measure \(block.number) holds \(durationSum(block.body)) divisions, expected \(4 * divisions)"
|
||||
)
|
||||
}
|
||||
// No one-division phantom note anywhere.
|
||||
#expect(!xml.contains("<duration>1</duration>"))
|
||||
}
|
||||
|
||||
/// The sectioned-score path that originally surfaced the bug: a part with a
|
||||
/// long rest-pad tail that ends exactly on a barline, immediately followed by
|
||||
/// a new section whose note enters on the downbeat. Models the
|
||||
/// melody-section-then-chord-section boundary.
|
||||
@Test func sectionPadTailThenDownbeatNoteNoSliver() {
|
||||
let divisions: Int = 480
|
||||
let melody: ScoreSection = Section(
|
||||
"A",
|
||||
meterMap: MeterMap(TimeSignature(4, 4))
|
||||
) {
|
||||
// Short part: 23 beats of content, padded to the section's 44-beat
|
||||
// span (max part length) with rests whose tail ends on a barline.
|
||||
Part("lead") {
|
||||
for _: Int in 0..<23 { Note(.c, 4, dur: .quarter) }
|
||||
}
|
||||
// Long part forces the section span to 11 bars (44 beats).
|
||||
Part("bass") {
|
||||
for _: Int in 0..<44 { Note(.c, 2, dur: .quarter) }
|
||||
}
|
||||
}
|
||||
let chords: ScoreSection = Section(
|
||||
"B",
|
||||
meterMap: MeterMap(TimeSignature(4, 4))
|
||||
) {
|
||||
Part("lead") { Note(.f, 5, dur: .whole) }
|
||||
Part("bass") { Note(.f, 2, dur: .whole) }
|
||||
}
|
||||
let score: Score = Score(sections: [melody, chords], bpm: 120)
|
||||
let xml: String = score.toMusicXMLString(divisions: divisions)
|
||||
for pid: String in ["P1", "P2"] {
|
||||
for block: (number: String, body: String) in measureBlocks(xml, part: pid) {
|
||||
#expect(
|
||||
durationSum(block.body) == 4 * divisions,
|
||||
"\(pid) measure \(block.number) holds \(durationSum(block.body)) divisions, expected \(4 * divisions)"
|
||||
)
|
||||
}
|
||||
}
|
||||
#expect(!xml.contains("<duration>1</duration>"))
|
||||
}
|
||||
|
||||
/// A short part padded to its section's beat span must fill whole empty bars
|
||||
/// with single whole-measure rests, not greedy largest-value rests that
|
||||
/// straddle barlines and fragment into metrically-wrong groupings (a quarter
|
||||
/// + dotted-half rest crossing the mid-bar strong beat reads as malformed).
|
||||
@Test func sectionPadFillsWholeBarsAsMeasureRests() {
|
||||
let divisions: Int = 480
|
||||
// 23 quarter-beats of content → ends mid-bar (bar 6, beat 3). The 44-beat
|
||||
// section span (set by the long part) leaves a 21-beat pad spanning the
|
||||
// rest of bar 6 plus full bars 7-11.
|
||||
let section: ScoreSection = Section(
|
||||
"A",
|
||||
meterMap: MeterMap(TimeSignature(4, 4))
|
||||
) {
|
||||
Part("lead") { for _: Int in 0..<23 { Note(.c, 4, dur: .quarter) } }
|
||||
Part("bass") { for _: Int in 0..<44 { Note(.c, 2, dur: .quarter) } }
|
||||
}
|
||||
let score: Score = Score(sections: [section], bpm: 120)
|
||||
let xml: String = score.toMusicXMLString(divisions: divisions)
|
||||
|
||||
// The lead part's empty bars 7-11 must each be a whole-measure rest.
|
||||
var measureRestBars: Set<String> = []
|
||||
for block: (number: String, body: String) in measureBlocks(xml, part: "P1") {
|
||||
if block.body.contains("<rest measure=\"yes\"") {
|
||||
measureRestBars.insert(block.number)
|
||||
}
|
||||
}
|
||||
for bar: String in ["7", "8", "9", "10", "11"] {
|
||||
#expect(
|
||||
measureRestBars.contains(bar),
|
||||
"bar \(bar) should be a single whole-measure rest"
|
||||
)
|
||||
}
|
||||
// No fragmented one-division phantom anywhere.
|
||||
#expect(!xml.contains("<duration>1</duration>"))
|
||||
}
|
||||
}
|
||||
@@ -429,6 +429,29 @@ struct SVFTests {
|
||||
#expect(!allSame, "SVF.Audio with LFO-driven freq must produce non-constant output")
|
||||
}
|
||||
|
||||
// MARK: 18b. Generator-driven freq above the sample rate stays stable (no divergence)
|
||||
|
||||
@Test func freqAboveSampleRateStaysFinite() {
|
||||
// A generator cutoff swept well past the sample rate drives sin(π·freq/sr)
|
||||
// negative; the coefficient must clamp to 0 rather than produce a negative
|
||||
// f that diverges the Chamberlin recurrence.
|
||||
let hugeFreq: Double = 2.0 * sampleRate
|
||||
let lfo: OscSin.Audio = OscSin.Audio(freq: 0.5, mul: hugeFreq, add: hugeFreq)
|
||||
let input: OscSin.Audio = OscSin.Audio(freq: 100.0, mul: 0.5)
|
||||
let svf: SVF.Audio = SVF.Audio(input: input, freq: lfo, q: svfButterworthQ)
|
||||
|
||||
var allFinite: Bool = true
|
||||
for _ in 0..<8 {
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let result: [[Double]] = svf.calculatedSamples(graph: g, count: blockSize)
|
||||
for ch: Int in 0..<result.count {
|
||||
for s: Double in result[ch].prefix(blockSize) where !s.isFinite { allFinite = false }
|
||||
}
|
||||
advanceBlock(engine)
|
||||
}
|
||||
#expect(allFinite, "SVF.Audio with above-Nyquist generator freq must not diverge")
|
||||
}
|
||||
|
||||
// MARK: 19. Q driven by audio generator (per-sample q path)
|
||||
|
||||
@Test func qDrivenByAudioGenerator() {
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
// ScorePartOffsetTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// MARK: - ScorePartOffsetTests
|
||||
|
||||
@MainActor
|
||||
@Suite("ScorePart entrance offset")
|
||||
struct ScorePartOffsetTests {
|
||||
|
||||
// MARK: - Flat-score offset (no sections)
|
||||
|
||||
@Test func measuresOffsetDelaysEntranceWholeBars() {
|
||||
// 2 bars of 4/4 lead = 8 quarter beats before the first note.
|
||||
let score: Score = Score(timeSignature: TimeSignature(4, 4)) {
|
||||
Part("lead", offset: .measures(2)) {
|
||||
Note(.c, 5, dur: .whole)
|
||||
}
|
||||
}
|
||||
let events: [ScoreEvent] = score.parts[0].flatten()
|
||||
#expect(events.count == 1)
|
||||
#expect(events[0].beat == 8.0)
|
||||
}
|
||||
|
||||
@Test func beatsOffsetDelaysEntranceMidBar() {
|
||||
let score: Score = Score(timeSignature: TimeSignature(4, 4)) {
|
||||
Part("lead", offset: .beats(2.5)) {
|
||||
Note(.c, 5, dur: .quarter)
|
||||
}
|
||||
}
|
||||
let events: [ScoreEvent] = score.parts[0].flatten()
|
||||
#expect(events.count == 1)
|
||||
#expect(events[0].beat == 2.5)
|
||||
}
|
||||
|
||||
@Test func fractionOffsetIsExact() {
|
||||
let score: Score = Score {
|
||||
Part("lead", offset: .fraction(Fraction(3, 2))) {
|
||||
Note(.c, 5, dur: .quarter)
|
||||
}
|
||||
}
|
||||
let events: [ScoreEvent] = score.parts[0].flatten()
|
||||
#expect(events.count == 1)
|
||||
#expect(events[0].beat == 1.5)
|
||||
}
|
||||
|
||||
@Test func nonPositiveOffsetIsNoOp() {
|
||||
// Every case's documented "negative or zero → no offset" contract.
|
||||
let zeroMeasures: Score = Score {
|
||||
Part("a", offset: .measures(0)) { Note(.c, 5, dur: .quarter) }
|
||||
}
|
||||
let negBeats: Score = Score {
|
||||
Part("b", offset: .beats(-3)) { Note(.c, 5, dur: .quarter) }
|
||||
}
|
||||
let zeroFraction: Score = Score {
|
||||
Part("c", offset: .fraction(Fraction(0, 1))) { Note(.c, 5, dur: .quarter) }
|
||||
}
|
||||
let negFraction: Score = Score {
|
||||
Part("d", offset: .fraction(Fraction(-1, 2))) { Note(.c, 5, dur: .quarter) }
|
||||
}
|
||||
#expect(zeroMeasures.parts[0].flatten()[0].beat == 0.0)
|
||||
#expect(negBeats.parts[0].flatten()[0].beat == 0.0)
|
||||
#expect(zeroFraction.parts[0].flatten()[0].beat == 0.0)
|
||||
#expect(negFraction.parts[0].flatten()[0].beat == 0.0)
|
||||
}
|
||||
|
||||
// MARK: - Consumed-into-rests invariant
|
||||
|
||||
@Test func offsetIsConsumedNilOnAssembledScore() {
|
||||
let score: Score = Score {
|
||||
Part("lead", offset: .measures(2)) { Note(.c, 5, dur: .whole) }
|
||||
}
|
||||
#expect(score.parts[0].offset == nil)
|
||||
}
|
||||
|
||||
@Test func noOffsetByteIdenticalToExplicitNil() {
|
||||
let withNil: Score = Score {
|
||||
Part("lead") { Note(.c, 5, dur: .whole) }
|
||||
}
|
||||
let explicitNil: Score = Score {
|
||||
Part("lead", offset: nil) { Note(.c, 5, dur: .whole) }
|
||||
}
|
||||
#expect(withNil.toMusicXMLString() == explicitNil.toMusicXMLString())
|
||||
}
|
||||
|
||||
// MARK: - Section offset
|
||||
|
||||
@Test func sectionOffsetDelaysEntranceWithinSection() {
|
||||
// Single-section score: section start == beat 0, so the offset part's
|
||||
// first event lands at the offset (2 bars = beat 8).
|
||||
let score: Score = Score {
|
||||
Section("A") {
|
||||
Part("violin") {
|
||||
Note(.g, 5, dur: .whole)
|
||||
Note(.g, 5, dur: .whole)
|
||||
Note(.g, 5, dur: .whole)
|
||||
Note(.g, 5, dur: .whole)
|
||||
}
|
||||
Part("cello", offset: .measures(2)) {
|
||||
Note(.c, 3, dur: .whole)
|
||||
}
|
||||
}
|
||||
}
|
||||
let violin: [ScoreEvent] = score.parts[0].flatten()
|
||||
let cello: [ScoreEvent] = score.parts[1].flatten()
|
||||
#expect(violin[0].beat == 0.0)
|
||||
#expect(cello[0].beat == 8.0)
|
||||
}
|
||||
|
||||
@Test func offsetCountsTowardSectionSpan() {
|
||||
// Cello: 3-bar offset + 1 whole note = 4 bars; violin only 1 bar.
|
||||
// The section must size to the longest = 4 bars (16 quarter beats).
|
||||
let score: Score = Score {
|
||||
Section("A") {
|
||||
Part("violin") { Note(.g, 5, dur: .whole) }
|
||||
Part("cello", offset: .measures(3)) { Note(.c, 3, dur: .whole) }
|
||||
}
|
||||
}
|
||||
// Both parts pad to the same section span. Violin's last (padded) beat
|
||||
// and the cello's entrance prove the span grew to 4 bars.
|
||||
let cello: [ScoreEvent] = score.parts[1].flatten()
|
||||
#expect(cello[0].beat == 12.0)
|
||||
// Violin part sounding end = its single whole note (4 beats).
|
||||
#expect(score.parts[0].lastBeat() == 4.0)
|
||||
// The encoded score has 4 measures for both parts.
|
||||
let xml: String = score.toMusicXMLString()
|
||||
let violinMeasures: Int = xml.components(separatedBy: "<measure number=\"4\"").count - 1
|
||||
#expect(violinMeasures >= 1)
|
||||
}
|
||||
|
||||
@Test func polymetricPartOffsetUsesOwnMeter() {
|
||||
// Cello in 3/4 with a 2-bar offset = 6 quarter beats before entrance.
|
||||
let score: Score = Score(timeSignature: TimeSignature(4, 4)) {
|
||||
Section("A") {
|
||||
Part("violin") { Note(.g, 5, dur: .whole) }
|
||||
Part("cello", meterMap: MeterMap(TimeSignature(3, 4)), offset: .measures(2)) {
|
||||
Note(.c, 3, dur: .quarter)
|
||||
}
|
||||
}
|
||||
}
|
||||
let cello: [ScoreEvent] = score.parts[1].flatten()
|
||||
#expect(cello[0].beat == 6.0)
|
||||
}
|
||||
|
||||
@Test func offsetThenFillMeasureFillsFromDelayedEntrance() {
|
||||
// Offset 1 bar (4 beats), then a half note, then FillMeasure → the fill
|
||||
// should complete bar 2 (the entrance bar), i.e. 2 more beats of rest.
|
||||
let score: Score = Score(timeSignature: TimeSignature(4, 4)) {
|
||||
Part("lead", offset: .measures(1)) {
|
||||
Note(.c, 5, dur: .half)
|
||||
FillMeasure()
|
||||
}
|
||||
}
|
||||
// First (and only) note at beat 4; total part span fills to end of bar 2
|
||||
// = 8 beats. lastBeat = note end (4 + 0.5*2? half note = 2 beats) = 6.
|
||||
let events: [ScoreEvent] = score.parts[0].flatten()
|
||||
#expect(events.count == 1)
|
||||
#expect(events[0].beat == 4.0)
|
||||
#expect(events[0].beat + events[0].duration == 6.0)
|
||||
}
|
||||
}
|
||||
@@ -301,6 +301,138 @@ complete.**
|
||||
New work beyond this group is scoped from the **Deferred / Future** and **Not
|
||||
planned** lists below as demand appears.
|
||||
|
||||
### Generator Consolidation + RT Performance group (GP-1 … GP-9)
|
||||
|
||||
Goal: collapse remaining duplicated per-sample / per-init Generator code into
|
||||
shared helpers, and land a set of benchmark-gated real-time performance wins on
|
||||
the audio render path (`_computeSamples` / `calculatedSamples`). Sourced from an
|
||||
architecture sweep of `Sources/Lyrebird/Generators/` + `GeneratorCore/`.
|
||||
|
||||
Splits into two work-streams: **dedup** (no behaviour change, gated on tests
|
||||
only) and **perf** (gated on before/after benchmark + tests + review). Each
|
||||
phase is its own branch off `main` per the standing phase-branch policy.
|
||||
|
||||
**Locked decisions (with Josh):**
|
||||
|
||||
- **vDSP/vForce strategy = split-path, keep scalar fallback.** Each vectorised
|
||||
generator branches on `n == count` (upstream block full-length — the normal
|
||||
case at *any* block size, including small control blocks like 64). Only the
|
||||
rare short-upstream-block case (`n < count`) falls to the existing scalar
|
||||
loop. The vDSP/vForce call fires for 64-sample control blocks too — the gate
|
||||
is upstream-fullness, not absolute block size. If benchmarks show vDSP call
|
||||
overhead losing at *tiny* counts (1/2/4), add a `count >= minVectorCount`
|
||||
threshold (strictly better than "vDSP everywhere"). Revisit a
|
||||
"vDSP-everywhere + zero-pad" variant only if the split-path data warrants it.
|
||||
- **Benchmark harness = existing `Sources/LyrebirdBenchmark/main.swift`.** Add
|
||||
one timed case per perf phase (`ContinuousClock`, warmup + N timed iters,
|
||||
reports ns/block + ns/sample; `OfflineDriver` for in-context `processBlock`).
|
||||
Run release only: `swift run -c release LyrebirdBenchmark`. The control-block
|
||||
sweep (512 → 1) already in the harness shows the win-curve across block sizes.
|
||||
- **Per-phase gate.** Dedup phases: `swift test --no-parallel` green +
|
||||
`/lyrebird_review` clean. Perf phases: same, *plus* a committed before/after
|
||||
benchmark delta; keep the change only if it shows a real win with no test
|
||||
regression. Capture baseline numbers in the phase branch's first commit.
|
||||
|
||||
#### Phase GP-0 — Benchmark baseline capture
|
||||
|
||||
Add timed cases to `LyrebirdBenchmark` for every perf target *before* touching
|
||||
code: `BinaryOpGenerator` (scalar-mul, vector-add), unary math (`Sin`/`Exp`/
|
||||
`Sqrt`/`Abs`), `LinLin.Audio`, SVF generator-driven `freq`, `Chorus.Audio`.
|
||||
Run the control-block sweep on each. Commit the baseline numbers as the
|
||||
reference all GP perf phases diff against. No production code change.
|
||||
|
||||
#### Phase GP-1 — Trivial / low-risk dedup (no perf risk) ✓ *(complete — merged to main)*
|
||||
|
||||
Pure consolidation, semantically identical, gated on tests + review only:
|
||||
|
||||
- **D1** — Merge byte-identical `normalizeLFPhase` / `normalizeBLPhase` into one
|
||||
`normalizeOscPhase(_:)` helper. 8 oscillator `.Control` callers
|
||||
(LF/Osc Sawtooth/Square/Triangle/DutyCycle).
|
||||
- **D7** — Add `lyrebirdTwoPi` to `Math/LyrebirdConstants.swift`; replace 5
|
||||
inline `let twoPi = 2.0 * .pi` locals (Chorus/Flanger/Phaser/Jitter/
|
||||
ScannedSynthesizer). Removes magic-number-rule smell on the hot path.
|
||||
- **D4** — Adopt existing `resolveGeneratorOrScalar(...)` in `Chorus`/`Flanger`/
|
||||
`Phaser._computeSamples` — replaces ~17 hand-rolled 8-line input-resolution
|
||||
blocks. Helper already proven in Flute/Clarinet/Pan*/PlateReverb.
|
||||
- **D2** — Extract `computeButterworthQs(order:) -> [Double]` (new
|
||||
`Filters/ButterworthHelpers.swift`); 4 Butterworth filters call it at init.
|
||||
|
||||
#### Phase GP-2 — SVF helper extraction + coefficient interpolation (D6 + P4) ✓ *(complete — merged to main; −5.9% on gen-driven-freq bench)*
|
||||
|
||||
Bundles a dedup and a perf win that touch the same code:
|
||||
|
||||
- **D6** — Extract `runSVFBlock(...)` (Chamberlin recurrence + denormal flush +
|
||||
zero-fill); `SVF.Audio` and `SVF.Control._computeSamples` collapse to setup +
|
||||
one call + `mulAdd`. Name `svfMinQDamping` / `svfFCoeffMax` constants.
|
||||
- **P4** — In the generator-driven-`freq` path, replace per-sample
|
||||
`Darwin.sin(piOverSr·freq)` with block-boundary `fFirst`/`fLast` + linear
|
||||
interpolation (same technique as `runRBJBiquadBlock`). Eliminates ~510 of 512
|
||||
`sin` calls/block on that path. Benchmark the gen-driven-freq case.
|
||||
|
||||
Gate: tests + review + benchmark (perf component).
|
||||
|
||||
#### Phase GP-3 — Butterworth LP/HP cascade engine extraction (D3) ✓ *(complete — merged to main; ~250 dup lines removed, behavior-identical)*
|
||||
|
||||
- **D3** — Extract shared background-thread vDSP cascade machinery
|
||||
(`runScalar`/`runVDSP`/`runAudioRate`/deinit drain + the `_vdsp*Queue` set)
|
||||
into a `ButterworthCascadeEngine` in `ButterworthHelpers.swift`. LP and HP
|
||||
inject two coefficient closures and become thin wrappers. Removes ~250 lines
|
||||
of duplicated thread lifecycle. Medium risk — match the thread teardown
|
||||
exactly. Gate: tests + review. Sets up GP-9.
|
||||
|
||||
#### Phase GP-4 — Unary math vForce/vDSP fast path (P3) ✓ *(complete — merged to main; −66.9% / ~3× on the 4-op unary chain)*
|
||||
|
||||
- **P3** — Split-path vectorisation for `Sin`/`Cos`/`Exp`/`Log`/`Sqrt`/`Floor`/
|
||||
`Ceil` (`vvsin`/`vvcos`/`vvexp`/`vvlog`/`vvsqrt`/`vvfloor`/`vvceil`) and
|
||||
`Abs` (`vDSP_vabsD`). `n == count` → vectorised; `n < count` → existing scalar
|
||||
loop. No allocation (write into pre-zeroed `_result`). Highest single-generator
|
||||
throughput win (~4–10×). Benchmark each across the control-block sweep; apply
|
||||
`minVectorCount` threshold if tiny blocks regress.
|
||||
|
||||
#### Phase GP-5 — `BinaryOpGenerator` enum dispatch + vDSP (P2) ✓ *(complete — merged to main; gen×gen −56%, gen×scalar −72%)*
|
||||
|
||||
- **P2** — Replace the stored `op: (Double,Double)->Double` closure with an
|
||||
operator enum (`.add`/`.subtract`/`.multiply`/`.divide`) classified at init;
|
||||
dispatch aligned gen-vs-gen / gen-vs-scalar paths to `vDSP_vaddD`/`vsubD`/
|
||||
`vmulD`/`vdivD`/`vsaddD`/`vsmulD`. Keep the per-sample closure fallback for
|
||||
non-arithmetic / unaligned-count cases. Highest *graph-wide* win — every
|
||||
`osc * 0.5 + env` chain. Preserve IEEE-754 divide-by-zero behaviour. Medium
|
||||
risk — enumerate all variants, keep closure escape hatch. Benchmark scalar-mul
|
||||
+ vector-add cases.
|
||||
|
||||
#### Phase GP-6 — `LinLin` vDSP fast path (P7) ✓ *(complete — merged to main; −26.9%. LinExp/ExpLin deferred)*
|
||||
|
||||
- **P7** — `LinLin.Audio` → single `vDSP_vsmsaD` (`a·x + b`, coefficients
|
||||
hoisted out of loop; range params are always block-scalar so unconditional).
|
||||
Short-block fallback keeps the exact per-sample formula.
|
||||
- *Deferred:* `LinExp`/`ExpLin` (build the linear stage via vDSP then `vvexp` —
|
||||
needs a pre-allocated scratch buffer at init; modest incremental win, revisit
|
||||
if a profile flags them).
|
||||
|
||||
#### Phase GP-7 — Power-of-two delay-line wrapping (P5) ✓ *(complete — merged to main; Chorus −3.3%)*
|
||||
|
||||
- **P5** — `Chorus`/`Flanger` circular delay lines: size up to next power of two
|
||||
at init, replace per-sample `% delayLineCount` (3–4 per sample) with
|
||||
`& (delayLineCount - 1)`. ~2× delay-buffer memory (≈64 KB at max delay) for
|
||||
~6–9 cycles/sample saved. Add init-time `roundUpToPowerOfTwo(_:)`. Benchmark
|
||||
`Chorus.Audio`.
|
||||
|
||||
#### Phase GP-8 — Butterworth band-pass / band-reject vDSP cascade (P6) ✓ *(complete — merged to main; shared ButterworthSectionEngine, BP/BR gain vDSP + dedup)*
|
||||
|
||||
- **P6** — Extend the GP-3 `ButterworthCascadeEngine` vDSP path to
|
||||
`ButterworthBandPass` (sequenced HP→LP) and `ButterworthBandReject` (parallel
|
||||
LP+HP summed via `vDSP_vaddD`). Matches the LP/HP acceleration. Depends on
|
||||
GP-3. Band-reject needs two vDSP setups + dual kill-queue drain. Benchmark a
|
||||
4th-order bandpass.
|
||||
|
||||
**Sequencing:** GP-0 (baseline) → GP-1 (safe dedup) → GP-2/GP-3 (helper
|
||||
extractions, GP-3 before GP-8) → GP-4/GP-5 (highest-value perf) → GP-6/GP-7 →
|
||||
GP-8. Each lands on `main` via `--no-ff` before the next starts, per policy.
|
||||
|
||||
**Not pursued:** D5 (`OscSin.Audio` inlined switch) — intentional audio-rate
|
||||
choice (three branchless loops vs per-sample function call); leave as-is, revisit
|
||||
only if `OscillatorTableReadHelpers` gains a bitmask-wrap variant.
|
||||
|
||||
### Longer-term — Not planned
|
||||
|
||||
#### Phase 96b — Ableton Link *(not planned)*
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
# GP Performance Baseline
|
||||
|
||||
Reference numbers for the Generator Consolidation + RT Performance group
|
||||
(GP-0 … GP-8, see `docs/00-working-order.md`). Each perf phase diffs its
|
||||
before/after against this table.
|
||||
|
||||
**Harness:** `Sources/LyrebirdBenchmark/main.swift`, GP section.
|
||||
**Command:** `swift run -c release LyrebirdBenchmark` (release build mandatory).
|
||||
**Graph:** 8 voices per target, each `target → Pan2 → Out`, driven via
|
||||
`OfflineDriver`; engine advances segment serial per block (no fan-out cache
|
||||
artifact). Swept at `cbs=512` (1 control tick/callback) and `cbs=64`
|
||||
(8 sub-blocks/callback).
|
||||
|
||||
> Absolute ns vary by machine/thermal state. What matters is the **delta** on
|
||||
> the same machine before vs after a change. Re-run the baseline on the working
|
||||
> machine if comparing across hardware.
|
||||
|
||||
## Baseline (captured on `gp-0-benchmark-baseline`)
|
||||
|
||||
| Target | Phase | cbs=512 ns/block | cbs=512 ns/sample | cbs=64 ns/block |
|
||||
|---|---|---|---|---|
|
||||
| BinaryOp gen×gen / gen+gen | GP-5 | 141716.7 | 276.79 | 141195.9 |
|
||||
| BinaryOp gen×scalar / +scalar | GP-5 | 79927.6 | 156.11 | 79395.5 |
|
||||
| Unary math Exp(Sqrt(Abs(Sin))) | GP-4 | 93944.7 | 183.49 | 94131.2 |
|
||||
| LinLin.Audio | GP-6 | 27768.1 | 54.23 | 27561.8 |
|
||||
| SVF.Audio gen-driven freq | GP-2 | 80005.9 | 156.26 | 78595.2 |
|
||||
| Chorus.Audio | GP-7 | 93432.5 | 182.49 | 93420.9 |
|
||||
|
||||
`blockSize=512 voices=8 warmup=500 iterations=10000`
|
||||
|
||||
Note: control block size has negligible effect on these targets — all are
|
||||
`.Audio`-rate generators whose inner loop runs at audio rate regardless of the
|
||||
control sub-block split. The cbs=64 column is retained as a regression guard
|
||||
(a change must not introduce sub-block sensitivity).
|
||||
|
||||
## How each phase reports
|
||||
|
||||
Each GP perf phase appends an "After" row (or a side-by-side block) under its
|
||||
section here with the same command, same machine, and states the delta as a
|
||||
percentage. Keep the change only if the delta is a real win with no
|
||||
`swift test --no-parallel` regression.
|
||||
|
||||
## Results
|
||||
|
||||
### GP-2 — SVF helper extraction + block-boundary cutoff interpolation
|
||||
|
||||
| Target | Before ns/sample | After ns/sample | Delta |
|
||||
|---|---|---|---|
|
||||
| SVF.Audio gen-driven freq (cbs=512) | 156.26 | 147.10 | −5.9% |
|
||||
|
||||
Graph-level number; the SVF inner-loop saving is larger but diluted by the
|
||||
constant OscSin-input / OscSin-LFO / Pan2 / Out overhead in the bench voice.
|
||||
Faithful: per-sample `freq > 0 → silence` guard preserved exactly; slow cutoff
|
||||
motion is numerically ≈ identical to per-sample `sin()`. Full suite 4882/4882.
|
||||
|
||||
### GP-4 — unary math vForce/vDSP fast path
|
||||
|
||||
| Target | Before ns/sample | After ns/sample | Delta |
|
||||
|---|---|---|---|
|
||||
| Unary math Exp(Sqrt(Abs(Sin))) (cbs=512) | 183.49 | 60.78 | −66.9% |
|
||||
|
||||
Split-path vectorisation of Sin/Cos/Exp/Log/Sqrt/Floor/Ceil (`vvsin`/`vvcos`/
|
||||
`vvexp`/`vvlog`/`vvsqrt`/`vvfloor`/`vvceil`) and Abs (`vDSP_vabsD`) via the shared
|
||||
`unaryVector*` helpers (`Generators/Math/UnaryMathVectorHelpers.swift`). The
|
||||
bench chains 4 of these ops, so the ~3× speedup reflects the stacked saving.
|
||||
vForce transcendentals are within tolerance of `Foundation.*` (suite asserts
|
||||
`< 1e-10`); floor/ceil/abs are exact. Full suite 4883/4883.
|
||||
|
||||
### GP-5 — BinaryOpGenerator kind dispatch + vDSP
|
||||
|
||||
| Target | Before ns/sample | After ns/sample | Delta |
|
||||
|---|---|---|---|
|
||||
| BinaryOp gen×gen / gen+gen (cbs=512) | 276.79 | 120.97 | −56.3% |
|
||||
| BinaryOp gen×scalar / +scalar (cbs=512) | 156.11 | 44.16 | −71.7% |
|
||||
|
||||
`op` closure replaced by a `BinaryOpKind` enum classified at init (operator
|
||||
overloads pass `.add/.subtract/.multiply/.divide`; the closure init still exists
|
||||
for arbitrary ops → `kind=nil` → closure fallback). Aligned generator rows
|
||||
dispatch to vDSP (`vDSP_vaddD/vmulD/vsubD/vdivD`, `vsaddD/vsmulD/vsdivD`,
|
||||
`vsmsaD/svdivD`). Subtract via `+(-s)` / `vsmsaD`, divide via true-division
|
||||
routines (never reciprocal-multiply) → **bit-identical** to the scalar loop, so
|
||||
no tolerance concern; only arg-order risk, covered by the full suite + new
|
||||
order-sensitive tests. Highest graph-wide win (BinaryOp is ubiquitous). Full
|
||||
suite 4883→4887/4887 (4 new tests).
|
||||
|
||||
### GP-6 — LinLin.Audio vDSP_vsmsaD
|
||||
|
||||
| Target | Before ns/sample | After ns/sample | Delta |
|
||||
|---|---|---|---|
|
||||
| LinLin.Audio (cbs=512) | 54.23 | 39.66 | −26.9% |
|
||||
|
||||
The range params are always block-scalar (`floatValue`), so the affine map
|
||||
`f(x) = a·x + b` (`a = outRange/inRange`, `b = outLo − inLo·a`) applies
|
||||
unconditionally — full block in one `vDSP_vsmsaD`. Short upstream blocks keep
|
||||
the original exact per-sample formula (byte-identical fallback). The affine
|
||||
reorder is within the suite's `< 1e-8` tolerance. LinLin is a cheap op so the
|
||||
graph-level win is moderate (Osc/Pan2/Out dominate the bench voice). Full suite
|
||||
4887/4887.
|
||||
|
||||
### GP-7 — power-of-two delay-line wrap (Chorus / Flanger)
|
||||
|
||||
| Target | Before ns/sample | After ns/sample | Delta |
|
||||
|---|---|---|---|
|
||||
| Chorus.Audio (cbs=512) | 182.49 | 176.45 | −3.3% |
|
||||
|
||||
Delay buffers rounded up to a power of two (shared `lyrebirdNextPowerOfTwo`);
|
||||
the 5 (Chorus) / 3 (Flanger) per-sample `% delayLineCount` index wraps become
|
||||
`& delayMask`. The semantic max delay (`_maxDelayFrac`) is kept separate from
|
||||
the over-allocated buffer length, so the audible delay range and the delayed
|
||||
content are unchanged (larger ring, identical relative reads → bit-identical
|
||||
output; Chorus/Flanger tests pass). Modest win — the two per-sample LFO `sin()`
|
||||
calls dominate, not the modulo. Aligns Chorus/Flanger with the pow2-delay
|
||||
convention already used by CombFilter / AllpassFilter / DelayLine. Full suite
|
||||
4887/4887.
|
||||
|
||||
### GP-3 / GP-8 — Butterworth cascade engine extraction (dedup + capability)
|
||||
|
||||
No isolated benchmark — these are structural. GP-3 extracted the shared LP/HP
|
||||
cascade machinery into `_ButterworthCascadeBase`; GP-8 extracted a reusable
|
||||
non-Generator `ButterworthSectionEngine` so BandPass (HP→LP series) and
|
||||
BandReject (LP+HP parallel sum, now `vDSP_vaddD`) compose it — gaining the same
|
||||
background-thread `vDSP_biquad_SetupD` path LP/HP already had, and removing their
|
||||
duplicated scalar-cascade code. The vDSP biquad acceleration was already
|
||||
characterised on LP/HP; for BP/BR it only materially helps at high order
|
||||
(default order 2 = 1 biquad/section, where scalar ≈ vDSP). Net effect is large
|
||||
dedup (GP-3 −278 LOC; GP-8 removes BP/BR cascade duplication) + vDSP capability
|
||||
for high-order band filters. Behavior-identical (full Butterworth suite + 4887
|
||||
total pass).
|
||||
@@ -997,7 +997,7 @@ Add these to the forbidden list in §6 alongside heap allocation and locking.
|
||||
|
||||
## 13. Shared RT-Safe Helper Functions
|
||||
|
||||
Three module-level free functions and one method exist to eliminate repeated boilerplate. **Always use them** — do not re-inline the patterns they replace.
|
||||
A family of module-level free functions, base classes, and methods exist to eliminate repeated boilerplate. **Always use them** — do not re-inline the patterns they replace.
|
||||
|
||||
> **Out-of-tree extension packages:** these helpers are exposed as `@_spi(LyrebirdExtensions) public`. Add `@_spi(LyrebirdExtensions) import LyrebirdSynth` to any generator implementation file outside the core module. Full surface and stability policy: [extension-sdk.md](extension-sdk.md).
|
||||
|
||||
@@ -1167,6 +1167,18 @@ _zeroFallback = [Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)
|
||||
_zeroFallback = makeSampleBuffer()
|
||||
```
|
||||
|
||||
### Accelerate-backed vectorisation helpers (Math / Filters / Delays)
|
||||
|
||||
These wrap the common pattern *"vectorise the full-block case, fall back to a scalar loop for short upstream blocks"* — the split-path strategy: branch on `n == count` (upstream block full-length, the normal case at any block size), run one Accelerate call, and keep a scalar fallback for `n < count`. All are RT-safe (no allocation; closures passed in capture only global functions).
|
||||
|
||||
- **`unaryVector{Sin,Cos,Exp,Log,Sqrt,Floor,Ceil,Abs}(_:into:count:)`** — `Generators/Math/UnaryMathVectorHelpers.swift`. One per unary `Math.Audio` waveshaper. Replaces the per-sample `Foundation.<fn>(i < n ? block[i] : pad)` loop with a single vForce (`vvsin`/`vvcos`/`vvexp`/`vvlog`/`vvsqrt`/`vvfloor`/`vvceil`) or `vDSP_vabsD` call. `Log` pads `1.0` (→ `log(1)=0`); the rest pad `0.0`. Built on the private `applyUnaryVectorTransform(_:pad:into:count:_:)` driver — add a new wrapper there if you add a unary op with a vForce/vDSP equivalent. `.Control` variants stay scalar.
|
||||
- **`BinaryOpKind` + `binaryOpVectorScalarRHS` / `binaryOpScalarLHSVector` / `binaryOpVectorVector`** — `Generators/Math/BinaryOpVectorHelpers.swift`. The vDSP dispatch path for `BinaryOpGenerator`'s four arithmetic kinds. `+ − × ÷` map to correctly-rounded vDSP routines, so results are **bit-identical** to the scalar `lhs op rhs` loop. Divide uses true-division (`vDSP_vsdivD` / `vDSP_svdivD` / `vDSP_vdivD`), never reciprocal-multiply. Note `vDSP_vsubD` / `vDSP_vdivD` take the subtrahend / divisor pointer **first** (`C = A − B` / `A / B`). `BinaryOpGenerator` stores `kind: BinaryOpKind?` — `nil` means an arbitrary closure was supplied and the per-sample `op` fallback runs.
|
||||
- **`runSVFBlock(...)`** — `Generators/Filters/SVFHelpers.swift`. The shared Chamberlin SVF per-block body for `SVF.Audio` and `SVF.Control` (four outputs: low / high / band / notch). When `freq` is generator-driven, the cutoff coefficient `f = 2·sin(π·freq/sr)` is evaluated with `sin()` only at the block's first/last sample and linearly interpolated between (same coefficient-ramp technique as `runRBJBiquadBlock`); the per-sample `freq > 0 → silence` guard is preserved exactly. `low` / `band` state mutated `inout`. (`LinLin.Audio` uses the same interpolation-free idea inline via `vDSP_vsmsaD` for its affine map — no helper, single call site.)
|
||||
- **`_ButterworthCascadeBase` / `ButterworthSectionEngine`** — `Generators/Filters/ButterworthCascadeBase.swift`, `ButterworthSectionEngine.swift`. `ButterworthSectionEngine` is a reusable (non-Generator) order-1…8 biquad-cascade engine: per-stage Butterworth Q, scalar + audio-rate-interpolated paths, and a background-thread `vDSP_biquad_SetupD` builder (Option B, RT-safe). Coefficient formulas are injected as init closures + a thread name. `_ButterworthCascadeBase` is the thin Generator shell owning one engine (LP/HP subclass it); `ButterworthBandPass` chains two engines (HP→LP series) and `ButterworthBandReject` sums two parallel (LP+HP via `vDSP_vaddD`). Build a new Butterworth-family filter by composing engines — never re-inline the cascade/thread machinery.
|
||||
- **`computeButterworthQs(order:)`** — `Generators/Filters/ButterworthHelpers.swift`. Init-time per-stage Butterworth pole-Q array. Call from any Butterworth-family `init`; do not inline the `−1/(2·cos(...))` loop.
|
||||
- **`lyrebirdNextPowerOfTwo(_:)`** — `Math/PowerOfTwo.swift`. Smallest power of two `≥ n` (1 for `n ≤ 1`). Use at init to size any circular buffer whose index wrap should be a single `& (count − 1)` instead of `% count` (CombFilter / AllpassFilter / DelayLine / DelayLineFeedback / Chorus / Flanger). Keep the *semantic* length separate from the rounded buffer length so the audible range is unchanged.
|
||||
- **`lyrebirdTwoPi`** — `Math/LyrebirdConstants.swift`. Canonical `2π` constant; use instead of an inline `let twoPi = 2.0 * .pi` local in any `_computeSamples`.
|
||||
|
||||
### Summary table
|
||||
|
||||
| Helper | Location | Use when |
|
||||
@@ -1197,6 +1209,13 @@ _zeroFallback = makeSampleBuffer()
|
||||
| `lyrebirdSeedXorshift64(from:mixConstant:)` | `LyrebirdConstants.swift` | Init-time PRNG seeding for Audio/Control pairs that must decorrelate via a per-variant `mixConstant` |
|
||||
| `lyrebirdSeedXorshift64(from:)` | `LyrebirdConstants.swift` | Init-time PRNG seeding for stand-alone single-state owners (e.g. `DemandTemporalTendency`, `DemandTemporalBrownian`) — convenience for the two-arg form with `mixConstant: 0` |
|
||||
| `_registerAutoFreeIfNeeded(_:)` | `Envelopes/DoneActionWatchable.swift` (extension) | Last line of every `DoneActionWatchable` generator's designated `init` (after `super.init`). If `doneAction == .freeNode`, self-registers with the currently-building `SynthesizerBase` so the synth auto-frees on completion. No-op outside `Synthesizer.build()`. |
|
||||
| `unaryVector{Sin,Cos,Exp,Log,Sqrt,Floor,Ceil,Abs}(_:into:count:)` | `Generators/Math/UnaryMathVectorHelpers.swift` | Unary `Math.Audio` waveshaper inner loop — vForce / `vDSP_vabsD` full-block fast path with scalar fallback. Add a wrapper via `applyUnaryVectorTransform` for a new vectorisable unary op. `.Control` stays scalar. |
|
||||
| `BinaryOpKind` + `binaryOpVectorScalarRHS` / `binaryOpScalarLHSVector` / `binaryOpVectorVector` | `Generators/Math/BinaryOpVectorHelpers.swift` | `BinaryOpGenerator` arithmetic dispatch. `+ − × ÷` → correctly-rounded vDSP (bit-identical to scalar). Divide is true-division; `vsubD`/`vdivD` take subtrahend/divisor first. `kind == nil` → closure fallback. |
|
||||
| `runSVFBlock(...)` | `Generators/Filters/SVFHelpers.swift` | Chamberlin SVF per-block body shared by `SVF.Audio` / `SVF.Control`. Generator-driven cutoff uses block-boundary `sin()` interpolation; per-sample `freq > 0` silence guard preserved. `low`/`band` `inout`. |
|
||||
| `ButterworthSectionEngine` / `_ButterworthCascadeBase` | `Generators/Filters/ButterworthSectionEngine.swift`, `ButterworthCascadeBase.swift` | Order-1…8 biquad cascade (scalar + audio-rate + background-thread vDSP setup). Compose for any Butterworth-family filter (LP/HP subclass the base; BandPass chains two engines, BandReject sums two). Never re-inline the cascade/thread machinery. |
|
||||
| `computeButterworthQs(order:)` | `Generators/Filters/ButterworthHelpers.swift` | Init-time per-stage Butterworth pole-Q array. Call from any Butterworth-family `init`. |
|
||||
| `lyrebirdNextPowerOfTwo(_:)` | `Math/PowerOfTwo.swift` | Init-time circular-buffer sizing so the index wrap is `& (count − 1)` not `% count`. Keep semantic length separate from the rounded buffer length. |
|
||||
| `lyrebirdTwoPi` | `Math/LyrebirdConstants.swift` | Canonical `2π`; use instead of an inline `2.0 * .pi` local in `_computeSamples`. |
|
||||
|
||||
---
|
||||
|
||||
|
||||
Reference in New Issue
Block a user