Files
Lyrebird/Sources/LyrebirdUI/UIParamNode.swift
T
2026-06-01 18:27:40 -07:00

192 lines
8.4 KiB
Swift

// UIParamNode.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Observation
import LyrebirdSynth
/// UIParamNode — the `@Observable` backing object for an `@UIParam` property wrapper.
///
/// A `UIParamNode` is simultaneously:
/// - A `ControlGenerator`: wired directly into a synthesizer's signal DAG, delivering a
/// linearly-interpolated ramp from the previous block's value to the new atomic target.
/// - An `@Observable` value: SwiftUI views bind to `value` and update automatically.
/// - RT-thread-safe: the audio render callback reads via the internal `ParameterNode`
/// which uses an `Atomic<UInt64>` for lock-free main→RT communication.
///
/// `@UIParam` is a strict superset of `@LiveParam`: identical RT-thread behavior plus
/// SwiftUI binding. Use `@UIParam` when SwiftUI controls observe the parameter,
/// `@LiveParam` when no UI is involved.
///
/// ## Threading model
///
/// | Thread | Reads | Writes |
/// |-------------|------------------------------------------|------------------------------------------|
/// | Main thread | `value` (observable) | `value` + `_node.value` (atomic store) |
/// | RT thread | `_node`'s atomic backing, output buffer | `_node`'s output buffer |
///
/// The main thread never touches `_node`'s RT-only state; the RT thread never touches
/// `value` or the `@Observable` registrar. The `Atomic<UInt64>` inside `_node` is the
/// sole cross-thread communication channel.
///
/// ## Rate
///
/// `UIParamNode` conforms to `ControlGenerator`. When `controlBlockSize == blockSize`
/// (engine default) the framework calls `_computeSamples(count: blockSize)` once per audio
/// block. When `controlBlockSize < blockSize` the framework calls K = blockSize / controlBlockSize
/// times per audio block, assembling into the inherited `_subBlockBuffer`. Each sub-block
/// re-reads `_node`'s atomic, so a fresh main-thread write becomes audible at sub-block
/// granularity rather than waiting until the next full audio block. Total work across the
/// audio block is identical in both modes.
///
/// ## Fan-out
///
/// `ControlGenerator.calculatedSamples` extension caches the result in `_cachedResult`
/// for the duration of the current segment. Multiple downstream consumers of the same
/// `UIParamNode` see `_computeSamples` invoked exactly once per segment.
@Observable
// @unchecked Sendable: _node is read by RT generators via calculatedSamples and written on the
// main thread; fan-out cache (segmentSerial) guarantees write-once-per-segment safety.
public final class UIParamNode: GeneratorBase, ControlGenerator, LiveParameterValue, @unchecked Sendable {
// MARK: - Main-thread observable state
/// The current display / code-accessible value. Written and read on the main thread only.
///
/// `@Observable` tracks this property so SwiftUI views re-render when it changes.
/// The RT audio thread never accesses this property — it reads the atomic inside `_node`.
public internal(set) var value: Double
// MARK: - ControlGenerator conformance
/// Required by the `ControlGenerator` protocol but not used by this type's
/// `_computeSamples` (which delegates to `_node`, where the actual ramp state lives).
/// Kept in sync with `_node.previousOutputValue` for any caller that explicitly reads it.
@ObservationIgnored
public var previousOutputValue: Double {
get { _node.previousOutputValue }
set { _node.previousOutputValue = newValue }
}
// MARK: - RT engine (delegation target)
/// The underlying RT-safe parameter node.
///
/// Owns the `Atomic<UInt64>`, the interpolation state, and the pre-allocated result buffer.
/// All RT-thread work delegates here.
@ObservationIgnored
private let _node: ParameterNode
// MARK: - Init
/// Creates a `UIParamNode` with the given initial value.
public init(_ initialValue: Double) {
self.value = initialValue
self._node = ParameterNode(initialValue)
super.init()
_setupSubBlockBuffer()
}
// MARK: - Main-thread update
/// Update the parameter value from the main thread.
///
/// Sets the `@Observable` `value` property (triggering SwiftUI re-renders) and
/// atomically stores the new bits for the RT thread to pick up at the next block.
///
/// - Important: must be called from the main thread. The `@Observable` registrar is not
/// thread-safe; calling `update` from the RT audio thread is a data race.
/// - Parameter newValue: The new parameter value.
public func update(_ newValue: Double) {
value = newValue
_node.value = newValue
}
// MARK: - LiveParameterValue conformance
/// Atomically writes `newValue`. Used by `SynthesizerBase.updateParameter(_:value:)`
/// to dispatch by-name writes without knowing the concrete projected-node type.
/// Main-thread-only — delegates to `update(_:)` to keep the `@Observable` `value`
/// in sync with the atomic.
public func _writeAtomicValue(_ newValue: Double) {
update(newValue)
}
// MARK: - Source property (delegates to _node)
/// Generator wired into this parameter slot. When non-nil, the parameter's
/// output is driven by this generator instead of the scalar ramp path.
/// Setting `nil` reverts to the scalar path.
///
/// Delegates to the underlying `ParameterNode`. See `ParameterNode.source`
/// for the full threading contract and example.
///
/// ## Threading
///
/// **Main thread only.** Same SPSC-enqueue path as `ParameterNode.source`.
public var source: (any Generator)? {
get { _node.source }
set { _node.source = newValue }
}
/// Swap the source with an optional crossfade. `crossfadeBlocks = 0`
/// (default) matches the property setter — hard swap.
///
/// Delegates to the underlying `ParameterNode`. See `ParameterNode.setSource(_:crossfadeBlocks:)`
/// for the full threading contract.
///
/// - Parameters:
/// - source: Generator to wire in as the new source, or `nil` to revert
/// to the scalar ramp path.
/// - crossfadeBlocks: Number of audio blocks to crossfade. `0` = hard
/// swap (default). Larger values produce a smooth linear mix from
/// the old slot's output to the new one over N blocks.
///
/// ## Threading
///
/// **Main thread only.** Same SPSC-enqueue path as `ParameterNode.setSource(_:crossfadeBlocks:)`.
public func setSource(_ source: (any Generator)?, crossfadeBlocks: UInt16 = 0) {
_node.setSource(source, crossfadeBlocks: crossfadeBlocks)
}
// MARK: - ValidGeneratorInput / Generator (delegate to _node for RT work)
/// Returns the current target value as a block-constant scalar — direct atomic load,
/// no ramp computation. Generators that detect `UIParamNode` as a `Generator` route
/// through `calculatedSamples` instead.
public func floatValue(graph: SynthGraph) -> Double {
_node.floatValue(graph: graph)
}
/// Delegates to `_node._computeSamples`. Only reachable if a generator
/// bypasses `calculatedSamples` and calls `_computeSamples` directly —
/// unusual but kept as a fallback for protocol compliance. The
/// runtime-source-swap path lives in `ParameterNode.calculatedSamples`,
/// not `_computeSamples`, so see the `calculatedSamples` override below
/// for the live signal path.
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_node._computeSamples(graph: graph, count: count)
}
/// Forwards to `_node.calculatedSamples(graph:count:)`, which is the
/// only path that drains `_node._sourceQueue` and runs the
/// crossfade / source-slot state machine. If we instead let the
/// `ControlGenerator.calculatedSamples` protocol extension dispatch
/// to `_node._computeSamples` directly, the source-swap pipeline
/// would be silently bypassed when a `UIParamNode` appears in a graph.
///
/// `_node` performs its own segment-serial caching, so we don't
/// double-cache here.
public func calculatedSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_node.calculatedSamples(graph: graph, count: count)
}
}