6 Commits

Author SHA1 Message Date
josh 9f244b1939 v2.3.0 release: onEditingEnded edit-ended callback on continuous controls
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-25 13:59:52 -08:00
josh 24ea32e47c v2.2.0 release: live-parameter ramp origin primed at synth add
A @UIParam/@LiveParam value assigned after construction but before the first render
is now delivered flat on the first block instead of ramping from the property-
declaration default (fixes e.g. a NoiseGate restored from saved rig state latching
open and ignoring its threshold). Backed by a new internal-facing
LiveParameterValue._primeRampOrigin() (default no-op, source-compatible); live
changes after start still ramp. See RELEASES.md for the full behavior-change note.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-03 12:25:29 -08:00
josh c14efe998a docs(readme): add Linux equivalents for adding the package and opening the project
Mirror of Lyrebird dev HEAD. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-18 18:44:50 -07:00
josh 63b630b317 docs(readme): name VS Code as the Linux IDE in Requirements
Mirror of Lyrebird dev HEAD. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-18 16:40:58 -07:00
josh 3668739d20 docs(readme): add Linux row to the Requirements table
Mirror of Lyrebird dev HEAD. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-18 16:40:05 -07:00
josh 6e7f4c0076 docs(readme): note Linux support alongside macOS/iOS
Mirror of Lyrebird dev HEAD (c8cbb52f). README intro + quick-taste engine line now
name the platform audio backends (Core Audio on Apple, ALSA on Linux). No code change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-18 16:36:10 -07:00
16 changed files with 609 additions and 13 deletions
+47 -6
View File
@@ -1,6 +1,6 @@
# Lyrebird
A native macOS/iOS audio synthesis framework written in Swift. Implement `Generator` and `Synthesizer` protocols; the Lyrebird engine handles Core Audio I/O and signal graph evaluation with no heap allocation on the real-time thread.
A native macOS, iOS, and Linux audio synthesis framework written in Swift. Implement `Generator` and `Synthesizer` protocols; the Lyrebird engine handles platform audio I/O (Core Audio on Apple, ALSA on Linux) and signal graph evaluation with no heap allocation on the real-time thread.
Informed by 20+ years of SuperCollider practice, adapted to Swift idioms and a single-process architecture.
@@ -8,7 +8,7 @@ Informed by 20+ years of SuperCollider practice, adapted to Swift idioms and a s
## A quick taste
Three layers, each usable on its own: **Generators** are the unit signal graph, **Synthesizers** package a graph plus live parameters into a playable voice, and the **Engine** drives Core Audio and schedules voices sample-accurately.
Three layers, each usable on its own: **Generators** are the unit signal graph, **Synthesizers** package a graph plus live parameters into a playable voice, and the **Engine** drives the platform audio backend (Core Audio on Apple, ALSA on Linux) and schedules voices sample-accurately.
### Generators — compose a signal graph with operators
@@ -128,10 +128,15 @@ The REPL is text-only and works from any project that depends on Lyrebird; the s
## Requirements
| Platform | OS | Xcode | Swift |
| Platform | OS | IDE | Swift |
|---|---|---|---|
| macOS | 15+ | 16+ | 6.0 |
| iOS | 18+ | 16+ | 6.0 |
| macOS | 15+ | Xcode 16+ | 6.0 |
| iOS | 18+ | Xcode 16+ | 6.0 |
| Linux | Ubuntu 22.04+ ¹ | VS Code ² | 6.0 |
¹ Any swift.org-supported distribution with a Swift 6.0+ toolchain. Install `libasound2-dev` for live audio via the ALSA driver; offline/NRT rendering needs no audio device or ALSA.
² VS Code with the [Swift extension](https://marketplace.visualstudio.com/items?itemName=swiftlang.swift-vscode) (build/debug via SourceKit-LSP); any editor works with the `swift` CLI. Linux setup walk-through: [`docs/linux-getting-started.md`](docs/linux-getting-started.md).
---
@@ -149,7 +154,24 @@ That's it — the `Lyrebird` product links **statically**, so there's no dynamic
Full walk-through (SPM manifest form, local-path dev dependency, per-template details): [`INSTALLATION_AND_USAGE.md`](INSTALLATION_AND_USAGE.md). DocC version: **Getting Started ▸ Adding Lyrebird to your own Xcode project**.
**On Linux?** The non-UI core — engine, generators, CLI, offline render, live ALSA audio, MIDI, and OSC — builds and runs on Linux (no Xcode, no SwiftUI). Start here: [`docs/linux-getting-started.md`](docs/linux-getting-started.md).
**On Linux (or any SwiftPM project without the Xcode UI)** — there's no "Add Package Dependencies" dialog, so declare it in `Package.swift`:
```swift
dependencies: [
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.0.0"),
],
targets: [
.executableTarget(
name: "MyApp",
dependencies: [
.product(name: "Lyrebird", package: "Lyrebird"),
// .product(name: "LyrebirdUI", package: "Lyrebird"), // Apple-only — SwiftUI controls
]
),
]
```
Then `import LyrebirdSynth`. On Linux the non-UI core — engine, generators, CLI, offline render, live ALSA audio, MIDI, and OSC — builds and runs with no Xcode and no SwiftUI (`LyrebirdUI` is Apple-only; a GTK4 UI ships as a separate demo). Full setup: [`docs/linux-getting-started.md`](docs/linux-getting-started.md).
---
@@ -192,6 +214,25 @@ Use `Lyrebird-Package` for day-to-day development of the engine and tests.
| Build fails with Swift driver errors | Xcode 26 bug affecting the **demo workspace** (which dynamic-links for live-coding) — it already sets `SWIFT_USE_INTEGRATED_DRIVER = NO` + `parallelizeBuildables = NO`. Your own project links Lyrebird statically and is unaffected. |
| `dyld: Library not loaded` | Only the bundled demos/AUv3 use the dynamic `LyrebirdDynamic` product; their entitlements already set `disable-library-validation`. External consumers link the static `Lyrebird` product and never hit this. |
### On Linux — VS Code or any editor (no Xcode)
Xcode, the `.xcworkspace`, and the schemes above are Apple-only. On Linux there's no workspace to open — point an editor at the package directory and drive it from the terminal:
```bash
code --install-extension swiftlang.swift-vscode # once: the official Swift extension (SourceKit-LSP: autocomplete, jump-to-def, debug)
code . # open the package in VS Code
```
There are no schemes — run targets directly:
```bash
swift build && swift test # build + run the Linux test suites
swift run LyrebirdCLI repl # the CLI (also `new`, scaffolding, …)
LYREBIRD_ENABLE_LINUX_UI=1 swift run LyrebirdUILinuxDemo # the GTK4 UI demo
```
The SwiftUI / AUv3 / iOS demos in the scheme table do not build on Linux. Full walk-through — toolchain, VS Code, building, running a sample: [`docs/linux-getting-started.md`](docs/linux-getting-started.md).
---
## Building and testing from the terminal
+72
View File
@@ -7,6 +7,78 @@ functionality in a backward-compatible way.
---
## 2.3.0 — Edit-ended callback on continuous controls
A small, additive, source-compatible release. The continuous `LyrebirdUI`
controls drive their parameter node(s) continuously while dragging, which gives
a host no single "the user finished this edit" signal. This adds one.
**New — `.onEditingEnded` on the continuous controls.** `ParameterKnob`,
`ParameterSlider`, `ParameterXY`, and `MultiSlider` gain an `.onEditingEnded`
modifier (both the SwiftUI and the Linux/GTK4 variants) that fires **once per
drag gesture**, reporting the value(s) at the start and end of the drag. A host
can use it to record a single edit per gesture — an undo checkpoint, say —
instead of one per intermediate update. The payload matches each control:
`(previous, new)` doubles for the knob and slider, a pair of `(x, y)` tuples for
the XY pad, and the before/after cell-value arrays for the multi-slider.
Additive and drop-in over 2.2.x: every control's public initializer is
unchanged (the callback is attached by the modifier), so existing call sites and
DocC links are unaffected. See `docs/ui/gui-system.md` for examples.
---
## 2.2.0 — Live-parameter ramp origin primed at synth add
A small-but-behavioral release. One fix to how `@UIParam` / `@LiveParam` values
are delivered on a synth's first rendered block, plus the internal hook that
backs it. The public API is source-compatible — the one new protocol member is
internal-facing and ships with a default implementation — so this is drop-in
over 2.1.x, but the delivery change is observable and is called out below.
**Fix — a parameter set before the first render is now delivered flat.** When a
value is assigned to an `@UIParam` / `@LiveParam` *after the synth is
constructed but before it first renders* — most commonly when restoring saved
state onto a freshly built synth — the parameter is now delivered as a flat
block at that value from sample 0. Previously the first rendered block ramped
from the property-declaration default up to the assigned value over one
(sub-)block, because the property-wrapper setter advances the atomic target but
not the interpolation origin, which stayed at the construction-time default.
For most parameters that one-block (~a few ms) glide was benign. For a value
feeding a decision stage it was not: a `Schmidt` trigger fed a threshold that
swept up from the default would latch on the transient and, if the steady signal
sat inside the hysteresis band, never reset — e.g. a `NoiseGate` restored from a
saved rig would open on load and ignore its threshold. Priming the origin at add
removes the sweep.
Mechanically: `SynthesizerBase`, as part of the `Mirror`-based live-parameter
auto-registration it already runs at add time (`rebuildGraph()`, main thread,
before the node is visible to the RT thread), now also primes each parameter's
ramp origin to its current value via a new `LiveParameterValue._primeRampOrigin()`.
`ParameterNode` and `UIParamNode` implement it; external conformers inherit a
no-op default, so nothing is source-broken. A re-add (`remove` → change value →
`add`) likewise re-primes to the then-current value.
**Behavior change to be aware of.** Two deliveries changed, both toward "the
value you set before starting is the value you get":
- A value assigned between construction and first render is **flat** on block
one, not a ramp from the declaration default. Code that (knowingly or not)
relied on that opening glide will no longer see it. If you want an opening
ramp, drive the parameter from a source/envelope or change it after start.
- A synth removed, re-assigned while out of the tree, then re-added starts
**flat at the new value** rather than gliding from the value it last rendered.
Live changes made **while the synth is running** are unchanged — they still ramp
per (sub-)block from the last rendered value, as before. The source-slot /
crossfade path is unaffected (the source overwrites the origin each block).
Pinned by `LiveParamRampOriginTests` (flat delivery for `@UIParam` and
`@LiveParam`, live-change-still-ramps, remove/change/re-add, and source-slot
non-interference).
---
## 2.1.1 — Delay-click fix + internal consolidation
A patch release: one audible bug fix in the delay/comb/allpass family, plus a
@@ -82,6 +82,12 @@ at the end of `rebuildGraph()`. The property name (with the leading `_` of prope
backing storage stripped) becomes the parameter key for `updateParameter` and
``LyrebirdMessageContext/set(_:to:on:)``. No `declareParameter` call is needed.
Auto-registration also **primes each parameter's ramp origin** to its current value (before the
RT thread sees the node), so a value assigned between construction and the synth's first render —
for example restoring saved state onto a freshly built synth — is delivered **flat on the first
block**, not as a ramp up from the property-declaration default. Changes made after the synth is
running still ramp as usual.
### Block-rate vs sub-block-rate ramping
When `controlBlockSize == blockSize` (the engine default), the framework calls
@@ -245,7 +245,10 @@ Do not call `engine.remove` from within the RT callback.
- `parameterTable.inputs` is populated by `_autoRegisterLiveParams()` at the end of
`rebuildGraph()` (main thread, before add) and read during `evaluate()` (RT thread,
after add). No concurrent access.
after add). No concurrent access. The same pass also primes each live parameter's ramp
origin to its current value, so a value assigned before the first render (e.g. restored
state) is delivered flat; this write is main-thread-only and precedes the add, so it never
races the RT thread.
- `updateParameter` issues a releasing atomic store on the projected `ParameterNode` /
`UIParamNode`; the RT thread picks up the new value via an acquiring atomic load at the
start of the next (sub-)block — no queue, no dictionary mutation on the RT thread.
@@ -34,6 +34,32 @@ public protocol LiveParameterValue: AnyObject {
/// `UIParamNode` (`@Observable` stored property) satisfy this requirement via their
/// existing public `value` accessor.
var value: Double { get }
/// Moves the interpolation origin (`previousOutputValue`) to the current target value, so the
/// next rendered block is a flat buffer at that value with no ramp.
///
/// `SynthesizerBase` calls this on every live parameter when a synth is (re-)added to the engine
/// — on the main thread, before the RT thread sees the node. Any value assigned to the parameter
/// **before the first render** (e.g. restoring saved state) is therefore delivered flat, while a
/// value changed **after** the synth is running still ramps from the last rendered value.
///
/// Without this, assigning a parameter after construction leaves the ramp origin at the
/// property-declaration default, so the first block ramps default → assigned. For most
/// parameters that is a brief, benign glide; for a decision threshold feeding a `Schmidt`
/// trigger it can latch the trigger into the wrong state.
///
/// - Important: NOT RT-safe — must be called from the control side only, and only while the
/// node is not yet observed by the RT thread. It writes `previousOutputValue` (a plain
/// `Double`) without synchronisation, which is safe because `SynthesizerBase` calls it before
/// the add event is enqueued. A node shared with a synth that is already active must not be
/// primed.
func _primeRampOrigin()
}
public extension LiveParameterValue {
/// Default no-op so external conformers are not source-broken by this requirement. The two
/// in-tree conformers (`ParameterNode`, `UIParamNode`) provide real implementations.
func _primeRampOrigin() {}
}
/// A property wrapper that backs a synthesizer parameter with a `ParameterNode`.
@@ -320,6 +320,12 @@ public final class ParameterNode: GeneratorBase, ControlGenerator, LiveParameter
value = newValue
}
/// `LiveParameterValue` conformance — resets the ramp origin to the current target so the next
/// block is flat (no ramp). See the protocol requirement for when `SynthesizerBase` calls this.
public func _primeRampOrigin() {
previousOutputValue = value
}
// MARK: - Init-time priming
/// Resets both the atomic backing and the ramp origin (`previousOutputValue`) to
@@ -119,6 +119,13 @@ public final class UIParamNode: GeneratorBase, ControlGenerator, LiveParameterVa
update(newValue)
}
/// `LiveParameterValue` conformance — resets the ramp origin to the current target so the next
/// block is flat (no ramp). Delegates to `_node`, which owns the RT interpolation state the
/// render thread reads. See the protocol requirement for when `SynthesizerBase` calls this.
public func _primeRampOrigin() {
_node._primeRampOrigin()
}
// MARK: - Source property (delegates to _node)
/// Generator wired into this parameter slot. When non-nil, the parameter's
@@ -666,9 +666,13 @@ open class SynthesizerBase: Synthesizer {
///
/// **Value survival across re-add.** `parameterTable.inputs` is repopulated by
/// `_autoRegisterLiveParams()` on every call, but each `@LiveParam` / `@UIParam` property
/// wrapper holds its projected node (`ParameterNode` / `UIParamNode`) as a `let` —
/// the same instance is re-registered, so its atomic value and ramp state are preserved
/// across `engine.remove` + `engine.add` cycles.
/// wrapper holds its projected node (`ParameterNode` / `UIParamNode`) as a `let` — the same
/// instance is re-registered, so its **atomic value** is preserved across `engine.remove` +
/// `engine.add` cycles. The **ramp origin** is not preserved: `_autoRegisterLiveParams()`
/// re-primes it to that current value on every add (see
/// ``LiveParameterValue/_primeRampOrigin()``), so the first block after an add is flat at the
/// value in effect — a value assigned between construction (or a remove) and the add is
/// delivered without a ramp, while changes made after the synth is running still ramp.
///
/// - Precondition: the Synthesizer must NOT currently be active in the node tree.
/// Calling this while `evaluate()` may be running on the RT thread is a data race on
@@ -708,7 +712,16 @@ open class SynthesizerBase: Synthesizer {
guard let label: String = child.label else { continue }
let key: String = label.hasPrefix("_") ? String(label.dropFirst()) : label
if let wrapper: any LiveParameterWrapper = child.value as? LiveParameterWrapper {
parameterTable.inputs[key] = wrapper._projectedAsValidInput
let node: any ValidGeneratorInput = wrapper._projectedAsValidInput
parameterTable.inputs[key] = node
// Flatten the ramp origin to the value held right now (before the RT thread first
// sees this node). A value assigned after construction but before the engine
// starts — e.g. restoring saved state — is otherwise delivered as a first-block
// ramp from the property-declaration default, which can latch a downstream
// Schmidt/decision stage into the wrong state. Live changes after start still ramp.
if let primeable: any LiveParameterValue = node as? LiveParameterValue {
primeable._primeRampOrigin()
}
}
}
}
+1 -1
View File
@@ -5,7 +5,7 @@
// SPDX-License-Identifier: MIT
/// The current Lyrebird framework and CLI version.
public let lyrebirdVersion: String = "2.1.1"
public let lyrebirdVersion: String = "2.3.0"
/// The banner printed when the interactive shell or REPL session starts.
public let welcomeBanner: String = """
@@ -43,6 +43,14 @@ public struct MultiSlider: View {
@State private var values: [Double]
/// Snapshot of `values` captured when a drag begins, so ``onEditingEnded(_:)`` can report the
/// cells' `(previous, new)` state — a drag can paint across several columns.
@State private var dragStartValues: [Double]?
/// Called once when a drag ends, with the `count` cell values before and after the drag (aligned
/// to `startIndex`). Set via ``onEditingEnded(_:)``; lets a host record one edit per gesture.
private var onEditingEndedAction: ((_ previous: [Double], _ new: [Double]) -> Void)?
// MARK: - Init
/// - Parameters:
@@ -112,6 +120,7 @@ public struct MultiSlider: View {
.gesture(
DragGesture(minimumDistance: 0)
.onChanged { drag in
if dragStartValues == nil { dragStartValues = values }
let column: Int = Int(drag.location.x / columnWidth)
guard column >= 0 && column < count else { return }
let yClamped: CGFloat = min(max(drag.location.y, 0), geo.size.height)
@@ -126,6 +135,12 @@ public struct MultiSlider: View {
values[column] = value
buffer.setValue(value, at: startIndex + column)
}
.onEnded { _ in
if let previous: [Double] = dragStartValues {
onEditingEndedAction?(previous, values)
}
dragStartValues = nil
}
)
}
.frame(height: height)
@@ -133,6 +148,18 @@ public struct MultiSlider: View {
Rectangle().stroke(Color.lyrebirdSeparator, lineWidth: 1)
)
}
/// Returns a copy that calls `action` when a drag ends — once per gesture — with the `count` cell
/// values before and after the drag (aligned to `startIndex`). A drag may paint several columns,
/// so both arrays are supplied for the host to diff. Matches ``ParameterKnob/onEditingEnded(_:)``.
///
/// - Parameter action: Receives `(previous, new)` cell-value arrays.
/// - Returns: A slider row that reports the end of each edit.
public func onEditingEnded(_ action: @escaping (_ previous: [Double], _ new: [Double]) -> Void) -> MultiSlider {
var copy: MultiSlider = self
copy.onEditingEndedAction = action
return copy
}
}
#else
@@ -168,6 +195,13 @@ public struct MultiSlider: View {
@State private var values: [Double]
/// Snapshot of `values` at drag start, so ``onEditingEnded(_:)`` can report `(previous, new)`.
@State private var dragStartValues: [Double]?
/// Called once when a drag ends, with the `count` cell values before and after. Set via
/// ``onEditingEnded(_:)``; mirrors the macOS multi-slider.
private var onEditingEndedAction: ((_ previous: [Double], _ new: [Double]) -> Void)?
// Fixed per-column width (points). The Apple side fills the available width
// via GeometryReader; on Linux the Canvas needs a concrete width, so each bar
// gets a fixed column and the row is `count × columnWidth` wide.
@@ -243,6 +277,7 @@ public struct MultiSlider: View {
.onDrag(
minimumDistance: 0,
onChanged: { (drag: DragGestureValue) in
if dragStartValues == nil { dragStartValues = values }
let column: Int = Int(drag.location.x / columnWidth)
guard column >= 0 && column < count else { return }
let hgt: Double = Double(height)
@@ -252,8 +287,26 @@ public struct MultiSlider: View {
let value: Double = range.lowerBound + norm * span
values[column] = value
buffer.setValue(value, at: startIndex + column)
},
onEnded: { (_: DragGestureValue) in
if let previous: [Double] = dragStartValues {
onEditingEndedAction?(previous, values)
}
dragStartValues = nil
}
)
}
/// Returns a copy that calls `action` when a drag ends — once per gesture — with the `count` cell
/// values before and after (aligned to `startIndex`). Mirrors the macOS multi-slider's
/// ``onEditingEnded(_:)``.
///
/// - Parameter action: Receives `(previous, new)` cell-value arrays.
/// - Returns: A slider row that reports the end of each edit.
public func onEditingEnded(_ action: @escaping (_ previous: [Double], _ new: [Double]) -> Void) -> MultiSlider {
var copy: MultiSlider = self
copy.onEditingEndedAction = action
return copy
}
}
#endif
@@ -27,6 +27,11 @@ public struct ParameterKnob: View {
/// Pixels of vertical drag that span the full parameter range. Default 200.
public var dragSensitivity: Double = 200
/// Called once when a drag gesture ends, with the value at the start of the drag and the final
/// value. Set via ``onEditingEnded(_:)``. Lets a host record a single edit per gesture (e.g. for
/// undo) rather than one per intermediate `node.update(_:)`.
private var onEditingEndedAction: ((Double, Double) -> Void)?
// MARK: - Private drag state
@State private var dragStartPosition: CGFloat = 0
@@ -116,12 +121,30 @@ public struct ParameterKnob: View {
node.update(clamped)
}
.onEnded { _ in
let previousValue: Double = dragStartValue
dragInProgress = false
dragStartPosition = 0
dragStartValue = 0
onEditingEndedAction?(previousValue, node.value)
}
}
// MARK: - Modifiers
/// Returns a copy of the knob that calls `action` each time a drag gesture ends — once per
/// gesture, not per intermediate update — with the value at the start of the drag and the final
/// value. Use it to record a single edit (for example an undo checkpoint) when the user finishes
/// turning the knob.
///
/// - Parameter action: Receives `(previousValue, newValue)` — the knob's value when the drag
/// began and when it ended.
/// - Returns: A knob that reports the end of each edit.
public func onEditingEnded(_ action: @escaping (Double, Double) -> Void) -> ParameterKnob {
var copy: ParameterKnob = self
copy.onEditingEndedAction = action
return copy
}
// MARK: - Helpers
private func normalise(_ value: Double) -> Double {
@@ -173,6 +196,10 @@ public struct ParameterKnob: View {
/// macOS knob's default.
public var dragSensitivity: Double = 200
/// Called once when a drag ends, with the drag's start value and final value. Set via
/// ``onEditingEnded(_:)``; mirrors the macOS knob so a host can record one edit per gesture.
private var onEditingEndedAction: ((Double, Double) -> Void)?
// Drag origin, captured on the first `onChanged` of each gesture. An
// explicit flag avoids a sentinel collision when the value is genuinely at
// the range's lower bound.
@@ -235,7 +262,9 @@ public struct ParameterKnob: View {
node.update(target)
},
onEnded: { (_: DragGestureValue) in
let previousValue: Double = dragStartValue
dragInProgress = false
onEditingEndedAction?(previousValue, node.value)
}
)
Text(label)
@@ -243,6 +272,17 @@ public struct ParameterKnob: View {
.padding()
}
/// Returns a copy of the knob that calls `action` each time a drag ends — once per gesture —
/// with the drag's start value and final value. Mirrors the macOS knob's ``onEditingEnded(_:)``.
///
/// - Parameter action: Receives `(previousValue, newValue)`.
/// - Returns: A knob that reports the end of each edit.
public func onEditingEnded(_ action: @escaping (Double, Double) -> Void) -> ParameterKnob {
var copy: ParameterKnob = self
copy.onEditingEndedAction = action
return copy
}
private func normalise(_ value: Double) -> Double {
let lo: Double = range.lowerBound
let hi: Double = range.upperBound
@@ -35,6 +35,13 @@ public struct ParameterSlider: View {
private let range: ClosedRange<Double>
private let taper: Taper
/// Called once when a drag ends, with the value when the drag began and the final value. Set via
/// ``onEditingEnded(_:)``; lets a host record one edit per gesture (e.g. for undo).
private var onEditingEndedAction: ((Double, Double) -> Void)?
/// Value captured when a drag begins, so ``onEditingEnded(_:)`` can report `(previous, new)`.
@State private var dragStartValue: Double = 0
// MARK: - Init
/// Creates a slider bound to a `UIParamNode`.
@@ -63,13 +70,33 @@ public struct ParameterSlider: View {
HStack {
Text(label)
.frame(minWidth: 80, alignment: .leading)
Slider(value: binding, in: linearRange) { _ in }
Slider(value: binding, in: linearRange) { editing in
if editing {
dragStartValue = node.value
} else {
onEditingEndedAction?(dragStartValue, node.value)
}
}
Text(formattedValue)
.frame(minWidth: 60, alignment: .trailing)
.monospacedDigit()
}
}
// MARK: - Modifiers
/// Returns a copy of the slider that calls `action` each time a drag ends — once per gesture —
/// with the value when the drag began and the final value. Use it to record a single edit (for
/// example an undo checkpoint). Matches ``ParameterKnob/onEditingEnded(_:)``.
///
/// - Parameter action: Receives `(previousValue, newValue)`.
/// - Returns: A slider that reports the end of each edit.
public func onEditingEnded(_ action: @escaping (Double, Double) -> Void) -> ParameterSlider {
var copy: ParameterSlider = self
copy.onEditingEndedAction = action
return copy
}
// MARK: - Private helpers
/// Linear range always 0...1; taper mapping happens inside the Binding.
@@ -176,6 +203,14 @@ public struct ParameterSlider: View {
/// visible at both ends.
private let thumbRadius: Double = 7
/// Called once when a drag ends, with the drag's start value and final value. Set via
/// ``onEditingEnded(_:)``; mirrors the macOS slider.
private var onEditingEndedAction: ((Double, Double) -> Void)?
// Drag origin, captured on the first `onChanged`.
@State private var dragStartValue: Double = 0
@State private var dragInProgress: Bool = false
// MARK: - Init
/// Creates a slider bound to a `UIParamNode`.
@@ -237,11 +272,19 @@ public struct ParameterSlider: View {
.onDrag(
minimumDistance: 0,
onChanged: { (drag: DragGestureValue) in
if !dragInProgress {
dragInProgress = true
dragStartValue = node.value
}
// Absolute: the thumb follows the pointer x within the track.
let x0: Double = thumbRadius
let usable: Double = max(trackWidth - 2 * thumbRadius, 1)
let pos: Double = min(1, max(0, (drag.location.x - x0) / usable))
node.update(fromLinear(pos))
},
onEnded: { (_: DragGestureValue) in
dragInProgress = false
onEditingEndedAction?(dragStartValue, node.value)
}
)
Text(formattedValue)
@@ -250,6 +293,17 @@ public struct ParameterSlider: View {
}
}
/// Returns a copy of the slider that calls `action` each time a drag ends — once per gesture —
/// with the drag's start value and final value. Mirrors the macOS slider's ``onEditingEnded(_:)``.
///
/// - Parameter action: Receives `(previousValue, newValue)`.
/// - Returns: A slider that reports the end of each edit.
public func onEditingEnded(_ action: @escaping (Double, Double) -> Void) -> ParameterSlider {
var copy: ParameterSlider = self
copy.onEditingEndedAction = action
return copy
}
// MARK: - Private helpers
private func toLinear(_ value: Double) -> Double {
@@ -31,6 +31,15 @@ public struct ParameterXY: View {
private let yNode: UIParamNode
private let yRange: ClosedRange<Double>
/// Called once when a drag ends, with the `(x, y)` values when the drag began and when it ended.
/// Set via ``onEditingEnded(_:)``; lets a host record one edit per gesture across both axes.
private var onEditingEndedAction: ((_ previous: (x: Double, y: Double), _ new: (x: Double, y: Double)) -> Void)?
// Both nodes' values captured when a drag begins.
@State private var dragStartX: Double = 0
@State private var dragStartY: Double = 0
@State private var dragInProgress: Bool = false
// MARK: - Init
/// Creates an XY pad bound to two `UIParamNode` values.
@@ -59,6 +68,20 @@ public struct ParameterXY: View {
self.yRange = yRange
}
/// Returns a copy of the pad that calls `action` each time a drag ends — once per gesture — with
/// the `(x, y)` values when the drag began and when it ended. Use it to record a single
/// two-axis edit (for example an undo checkpoint). Matches ``ParameterKnob/onEditingEnded(_:)``.
///
/// - Parameter action: Receives `(previous, new)`, each an `(x, y)` value pair.
/// - Returns: A pad that reports the end of each edit.
public func onEditingEnded(
_ action: @escaping (_ previous: (x: Double, y: Double), _ new: (x: Double, y: Double)) -> Void
) -> ParameterXY {
var copy: ParameterXY = self
copy.onEditingEndedAction = action
return copy
}
// MARK: - Body
public var body: some View {
@@ -134,11 +157,20 @@ public struct ParameterXY: View {
private func dragGesture(in size: CGSize) -> some Gesture {
DragGesture(minimumDistance: 0)
.onChanged { gesture in
if !dragInProgress {
dragInProgress = true
dragStartX = xNode.value
dragStartY = yNode.value
}
let nx: CGFloat = min(max(gesture.location.x / size.width, 0), 1)
let ny: CGFloat = min(max(gesture.location.y / size.height, 0), 1)
xNode.update(denormalise(nx, range: xRange))
yNode.update(denormalise(1.0 - ny, range: yRange)) // flip Y
}
.onEnded { _ in
dragInProgress = false
onEditingEndedAction?((x: dragStartX, y: dragStartY), (x: xNode.value, y: yNode.value))
}
}
// MARK: - Helpers
@@ -203,6 +235,14 @@ public struct ParameterXY: View {
private let padSize: Double = 160
private let cursorRadius: Double = 6
/// Called once when a drag ends, with the `(x, y)` values at the drag's start and end. Set via
/// ``onEditingEnded(_:)``; mirrors the macOS pad.
private var onEditingEndedAction: ((_ previous: (x: Double, y: Double), _ new: (x: Double, y: Double)) -> Void)?
@State private var dragStartX: Double = 0
@State private var dragStartY: Double = 0
@State private var dragInProgress: Bool = false
// MARK: - Init
/// Creates an XY pad bound to two `UIParamNode` values.
@@ -274,11 +314,20 @@ public struct ParameterXY: View {
.onDrag(
minimumDistance: 0,
onChanged: { (drag: DragGestureValue) in
if !dragInProgress {
dragInProgress = true
dragStartX = xNode.value
dragStartY = yNode.value
}
// Absolute position: the touch point is the cursor.
let nx: Double = min(max(drag.location.x / padSize, 0), 1)
let ny: Double = min(max(drag.location.y / padSize, 0), 1)
xNode.update(denormalise(nx, range: xRange))
yNode.update(denormalise(1.0 - ny, range: yRange)) // flip Y
},
onEnded: { (_: DragGestureValue) in
dragInProgress = false
onEditingEndedAction?((x: dragStartX, y: dragStartY), (x: xNode.value, y: yNode.value))
}
)
Text("\(xLabel): \(formattedParameterValue(xNode.value))")
@@ -289,6 +338,19 @@ public struct ParameterXY: View {
.padding()
}
/// Returns a copy of the pad that calls `action` each time a drag ends — once per gesture — with
/// the `(x, y)` values at the drag's start and end. Mirrors the macOS pad's ``onEditingEnded(_:)``.
///
/// - Parameter action: Receives `(previous, new)`, each an `(x, y)` value pair.
/// - Returns: A pad that reports the end of each edit.
public func onEditingEnded(
_ action: @escaping (_ previous: (x: Double, y: Double), _ new: (x: Double, y: Double)) -> Void
) -> ParameterXY {
var copy: ParameterXY = self
copy.onEditingEndedAction = action
return copy
}
// MARK: - Helpers
private func normalise(
@@ -0,0 +1,120 @@
// LiveParamRampOriginTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
/// A synth whose only output is a `@UIParam` written straight to a bus, so a rendered block
/// reveals the parameter's delivered ramp. Declaration default `0.1`.
@MainActor
private final class UIParamProbe: SynthesizerBase {
@UIParam var p: Double = 0.1
let bus: Int
init(bus: Int = 0) { self.bus = bus; super.init() }
override func build() {
output(bus: bus, source: $p)
}
}
/// Same, but backed by `@LiveParam` (`ParameterNode`) — a separate priming code path from
/// `@UIParam`'s `UIParamNode` delegation.
@MainActor
private final class LiveParamProbe: SynthesizerBase {
@LiveParam var p: Double = 0.1
let bus: Int
init(bus: Int = 0) { self.bus = bus; super.init() }
override func build() {
output(bus: bus, source: $p)
}
}
@MainActor
@Suite("Live parameter ramp origin")
struct LiveParamRampOriginTests {
let engine: SynthesisEngine = makeTestEngine(blockSize: 16)
init() throws {
try engine.start()
}
@Test func uiParamAssignedAfterConstructionIsDeliveredFlat() throws {
// Assign AFTER construction (declaration default 0.1) but BEFORE the first render. Without
// priming at add time the first block would ramp 0.1 → 0.9; the fix primes the ramp origin
// when the synth is added, so the block is flat at 0.9 from sample 0.
let probe: UIParamProbe = UIParamProbe(bus: 0)
probe.p = 0.9
try engine.add(probe)
engine.processBlock(inputSamples: [])
for i: Int in 0..<engine.blockSize {
#expect(abs(engine.audioBuses[0][i] - 0.9) < 1e-6,
"sample \(i) should be flat 0.9, not a ramp from the 0.1 default")
}
}
@Test func liveParamAssignedAfterConstructionIsDeliveredFlat() throws {
// Same guarantee for @LiveParam (ParameterNode direct, no UIParamNode delegation).
let probe: LiveParamProbe = LiveParamProbe(bus: 0)
probe.p = 0.9
try engine.add(probe)
engine.processBlock(inputSamples: [])
for i: Int in 0..<engine.blockSize {
#expect(abs(engine.audioBuses[0][i] - 0.9) < 1e-6,
"@LiveParam sample \(i) should be flat 0.9, not a ramp from the 0.1 default")
}
}
@Test func valueChangedWhileRunningStillRamps() throws {
// A change made while the synth is running must still ramp from the last rendered value —
// the fix must not flatten live updates, only prime the pre-first-render origin.
let probe: UIParamProbe = UIParamProbe(bus: 0) // starts at 0.1
try engine.add(probe)
engine.processBlock(inputSamples: []) // render a block, origin settles at 0.1
#expect(abs(engine.audioBuses[0][0] - 0.1) < 1e-6, "first block should be flat 0.1")
probe.p = 0.9 // live change → next block ramps
engine.processBlock(inputSamples: [])
let first: Float = engine.audioBuses[0][0]
let last: Float = engine.audioBuses[0][engine.blockSize - 1]
#expect(first < 0.9, "live change should ramp (first sample below target), got \(first)")
#expect(abs(last - 0.9) < 1e-5, "ramp should reach the target by block end, got \(last)")
}
@Test func valueChangedWhileRemovedIsDeliveredFlatOnReAdd() throws {
// Add, render, remove, change the value while out of the tree, then re-add. The re-add
// re-primes the origin to the new value, so the first block after re-add is flat at 0.9
// (no glide up from the 0.1 it last rendered). Pins the "re-add re-primes" behaviour that
// the rebuildGraph doc describes.
let probe: UIParamProbe = UIParamProbe(bus: 0) // 0.1
try engine.add(probe)
engine.processBlock(inputSamples: []) // renders 0.1, origin now 0.1
_ = engine.remove(probe)
engine.processBlock(inputSamples: []) // the documented one block between remove and re-add
probe.p = 0.9 // changed while removed
try engine.add(probe)
engine.processBlock(inputSamples: [])
for i: Int in 0..<engine.blockSize {
#expect(abs(engine.audioBuses[0][i] - 0.9) < 1e-6,
"re-added synth sample \(i) should be flat 0.9, not a ramp from 0.1")
}
}
@Test func sourceSlotSetBeforeAddIsUnaffectedByPriming() throws {
// With a generator wired into the parameter's source slot before add, the source output
// drives the block — priming the scalar ramp origin must not interfere. The source holds a
// constant 0.7, so the output is ~0.7 regardless of the 0.1 scalar default / 0.9 scalar set.
let probe: UIParamProbe = UIParamProbe(bus: 0)
probe.p = 0.9 // scalar value (should be overridden by source)
let constantSource: ParameterNode = ParameterNode(0.7)
probe.$p.source = constantSource
try engine.add(probe)
engine.processBlock(inputSamples: [])
let last: Float = engine.audioBuses[0][engine.blockSize - 1]
#expect(abs(last - 0.7) < 1e-5,
"source-slot output should be ~0.7, not the scalar value, got \(last)")
}
}
@@ -0,0 +1,65 @@
// OnEditingEndedTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
@testable import LyrebirdUI
import LyrebirdSynth
/// Coverage for the `.onEditingEnded` edit-reporting modifier on the continuous controls.
///
/// A SwiftUI gesture can't be driven from a unit test (same limitation noted in
/// ``MultiSliderTests``), so these are structural smokes: they construct each control, attach
/// `.onEditingEnded` with that control's payload shape, and confirm the builder returns a usable
/// value of the same concrete type. Their real job is to **lock the public API** — the per-control
/// closure signatures — so a later signature change breaks the build here rather than silently at a
/// call site. The gesture → `(previous, new)` firing itself is covered by the control's own drag
/// handler and is exercised in app use, not here.
@MainActor
@Suite("onEditingEnded")
struct OnEditingEndedTests {
@Test func knobBuilderCarriesTheAction() {
let node: UIParamNode = UIParamNode(0.5)
var reported: (Double, Double)?
let knob: ParameterKnob = ParameterKnob("Cutoff", node: node, range: 0...1)
.onEditingEnded { previous, new in reported = (previous, new) }
_ = knob
// The closure has not been invoked (no gesture), so nothing is reported yet.
#expect(reported == nil)
}
@Test func sliderBuilderCarriesTheAction() {
let node: UIParamNode = UIParamNode(0.25)
let slider: ParameterSlider = ParameterSlider("Amp", node: node, range: 0...1)
.onEditingEnded { _, _ in }
_ = slider
}
@Test func xyBuilderCarriesTheAction() {
let xNode: UIParamNode = UIParamNode(0.0)
let yNode: UIParamNode = UIParamNode(0.0)
let pad: ParameterXY = ParameterXY(
xLabel: "Pan", xNode: xNode, xRange: -1...1,
yLabel: "Amp", yNode: yNode, yRange: 0...1
)
.onEditingEnded { previous, new in
// Payload is a pair of (x, y) tuples — reference the members so a shape change breaks here.
_ = (previous.x, previous.y, new.x, new.y)
}
_ = pad
}
@Test func multiSliderBuilderCarriesTheAction() {
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: 8)
buffer.fill(with: 0.3)
let bars: MultiSlider = MultiSlider(buffer: buffer, count: 4, range: 0...1)
.onEditingEnded { previous, new in
// Payload is the cell-value arrays before / after the drag.
_ = (previous.count, new.count)
}
_ = bars
}
}
+28
View File
@@ -189,6 +189,34 @@ ParameterLabel("Level", node: synth.$amplitude)
ParameterLabel("Freq (Hz)", node: synth.$frequency, decimalPlaces: 1)
```
### Reporting the end of an edit (`onEditingEnded`)
The continuous controls — `ParameterKnob`, `ParameterSlider`, `ParameterXY`, and `MultiSlider` —
drive their node(s) continuously while dragging. Attach `.onEditingEnded` to be told **once per
drag gesture**, with the value(s) at the start and end of the drag, so a host can record a single
edit (an undo checkpoint, say) instead of one per intermediate update:
```swift
ParameterKnob("Cutoff", node: synth.$cutoff, range: 20...20000)
.onEditingEnded { previous, new in
undo.record(previous, new) // called once, when the drag ends
}
```
The payload differs per control:
| Control | `onEditingEnded` closure |
|---|---|
| `ParameterKnob` / `ParameterSlider` | `(previous: Double, new: Double)` |
| `ParameterXY` | `(previous: (x: Double, y: Double), new: (x: Double, y: Double))` — one gesture drives both nodes |
| `MultiSlider` | `(previous: [Double], new: [Double])` — the `count` cell values before/after (a drag can paint several bars) |
Notes:
- It fires once per gesture **even when the value didn't net-change** (e.g. a `MultiSlider` tap on an
unchanged bar). Filter on `previous == new` if your host wants to skip no-op edits.
- `ParameterSlider` (the SwiftUI variant) rides the native `Slider`'s editing-changed signal, so it
also fires for keyboard / accessibility adjustments, not only pointer drags.
### LyrebirdStatusView
Compact engine status display showing average and peak CPU load. Polls the engine at 10 Hz;