// ReplaceOut.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT /// Bus-write generators with audio-rate (`ReplaceOut.Audio`) and control-rate /// (`ReplaceOut.Control`) variants. Unlike ``Out``, these **overwrite** the /// target bus instead of accumulating into it. /// /// Use ReplaceOut when a synth needs to take ownership of a bus's content for /// the remainder of the block — e.g. a master amp scaler that reads, multiplies, /// and writes back to the same bus; a bus-level limiter; or a decoder that /// replaces raw B-format on hardware-out buses with the decoded speaker feeds. /// /// ## Important — Overwrite Semantics /// /// ReplaceOut wipes any prior writes to its target bus in the current block. /// Position the synth in the node tree **after** any additive ``Out`` writers /// whose contribution should be reflected in the input the ReplaceOut reads. /// Additive ``Out`` writers that run **after** ReplaceOut accumulate into the /// replaced content as normal. /// /// Inside a ``ParallelGroup``, ReplaceOut routes through `ScratchBuses.replace` /// and only overwrites *this child's scratch contribution*. It does not scrub /// other siblings' parallel writes nor any pre-parallel engine-bus content. See /// `docs/engine/eventlist-routing-design.md` for the full semantic table. /// /// Both variants conform to ``RootRegistering``. Constructed inside /// ``SynthesizerBase/build()`` they auto-register as synth roots — no explicit /// ``SynthesizerBase/addOutputGenerator(_:)`` or ``SynthesizerBase/replaceOutput(bus:source:)`` /// call is required and the return value may be discarded. public enum ReplaceOut { // MARK: - Shared base public class _Base: GeneratorBase { public let bus: Int let source: any ValidGeneratorInput /// Maximum channels to write. `Int.max` = unlimited (plain `Int` bus — write all source channels). /// Set to `bus.channelCount` when constructed from an ``AudioBus`` or ``ControlBus``. let _maxChannels: Int init( bus: Int, source: any ValidGeneratorInput, maxChannels: Int = Int.max, channels: Int = 1 ) { let resolvedSource: any ValidGeneratorInput = source._resolvedInput() self.bus = bus self.source = resolvedSource self._maxChannels = maxChannels super.init(channels: channels) } } // MARK: - Audio /// Overwrites one or more consecutive audio buses with the source signal /// (wipes any prior writes to those buses in the current block). /// /// The `bus` parameter takes a plain `Int` index or an ``AudioBus`` allocation /// (writing clamped to `bus.channelCount` channels). A ``ControlBus`` traps — /// an audio `ReplaceOut` addresses the audio-bus pool; use ``ReplaceOut/Control`` /// for a control bus. /// /// ## Multi-channel sources /// /// When `source` returns N channels, `ReplaceOut.Audio` writes channel 0 /// to `bus.index`, channel 1 to `bus.index + 1`, ..., channel N-1 to /// `bus.index + N - 1`. Mono sources behave identically to single-bus /// usage. If `source.outputChannelCount < bus.channelCount`, the unwritten /// buses in `[bus.index + N, bus.index + bus.channelCount)` are left /// untouched — they are *not* wiped. Use a source whose channel count /// matches the bus when full overwrite is required. /// /// ```swift /// // Scale a 4-channel bus in place by `amp` (read, multiply, replace). /// replaceOutput(bus: myAudioBus, source: In.Audio(bus: myAudioBus) * smoothAmp) /// ``` /// /// - Parameters: /// - bus: Destination bus — `Int` index (no channel clamping) or ``AudioBus`` /// (clamped to `channelCount`). A ``ControlBus`` traps; use ``ReplaceOut/Control``. /// - source: Signal to write. Multi-channel sources overwrite consecutive /// buses starting at `bus.index`. public final class Audio: _Base, AudioGenerator, RootRegistering { /// `ReplaceOut.Audio` returns `source.calculatedSamples` directly /// (pass-through), so its effective output channel count is /// `source.outputChannelCount`. Read at init-time only when /// `ReplaceOut.Audio` is used as a `BinaryOpGenerator` operand — never /// on the RT thread. Non-`Generator` sources (`Double`, `Int`, /// `Closure`) report 1. public override var outputChannelCount: Int { // Build-time only: the `as? any Generator` cast must not run on the // RT thread. Trap in debug builds if accidentally called from RT; // release builds compile the assert away. _lyrebirdAssertNotOnRTThread() return (source as? any Generator)?.outputChannelCount ?? 1 } /// - Parameters: /// - bus: Destination bus — `Int` index or ``AudioBus`` (writing clamped to /// `bus.channelCount`). A ``ControlBus`` traps; use ``ReplaceOut/Control``. /// - source: Signal to write. Multi-channel sources overwrite consecutive buses. public init( bus: any ValidBus, source: any ValidGeneratorInput ) { _preconditionAudioRateBus(bus) super.init(bus: bus.index, source: source, maxChannels: bus.channelCount) _registerAsRootIfBuilding() } public func _computeSamples( graph: SynthGraph, count: Int ) -> [[Double]] { _checkCount(count) let sourceSamples: [[Double]] = source.calculatedSamples(graph: graph, count: count) let offset: Int = graph.busOffset // Note: `graph.setSamplesOnAudioBus` asserts `offset + count <= bus.count` // internally; no need to duplicate that bound check here. for (ch, samples) in sourceSamples.enumerated() { guard ch < _maxChannels else { break } let targetBus: Int = bus + ch guard targetBus >= 0 && targetBus < graph.engine.numAudioBuses else { continue } guard samples.count >= count else { continue } graph.setSamplesOnAudioBus(targetBus, offset: offset, samples: samples, count: count) } return sourceSamples } /// ReplaceOut.Audio is a bus-write sink, not a value-producing operand — /// returns `0` to satisfy the protocol. Mirrors ``Out/Audio/floatValue(graph:)``. /// Treat ReplaceOut purely as a side-effect-only root in the graph. public func floatValue(graph: SynthGraph) -> Double { 0 } } // MARK: - Control /// Overwrites one or more consecutive control buses with the last sample of /// each source channel block (wipes any prior write to those buses in the /// current block). /// /// `ReplaceOut.Control` is a bus-write effector, not a signal producer — /// `calculatedSamples` performs the bus overwrite and returns the source /// value as a passthrough. Does not use the default ControlGenerator /// interpolation (no ramp is appropriate for a sink whose output is a /// control bus write). `previousOutputValue` is required by the /// ControlGenerator protocol but is not used. /// /// The `bus` parameter takes a plain `Int` index or a ``ControlBus`` allocation /// (writing clamped to `bus.channelCount` channels). An ``AudioBus`` traps — /// a control `ReplaceOut` addresses the control-bus pool; use ``ReplaceOut/Audio`` /// for an audio bus. /// /// ## Multi-channel sources /// /// When `source` returns N channels, `ReplaceOut.Control` writes channel 0 /// to `bus.index`, channel 1 to `bus.index + 1`, ..., channel N-1 to /// `bus.index + N - 1`. Mono sources behave identically to single-bus /// usage. /// /// - Parameters: /// - bus: Destination bus — `Int` index (1 channel, no clamping) or /// ``ControlBus`` (clamped to `channelCount`). An ``AudioBus`` traps; use ``ReplaceOut/Audio``. /// - source: Signal to write. The last sample of each channel block is /// written to the corresponding control bus. public final class Control: _Base, BlockRateControlGenerator, RootRegistering { /// Satisfies ControlGenerator protocol requirement — unused; Control conforms to `BlockRateControlGenerator`. public var previousOutputValue: Double = 0.0 /// Number of channels to write. Governs `_result` row count. /// /// - Note: Channel-count policy intentionally mirrors ``Out/Control``: a /// plain `Int` bus resolves to 1 channel (extra source channels are /// silently dropped); a ``ControlBus`` resolves to its explicit /// `channelCount`. ``ReplaceOut/Audio`` differs — a plain /// `Int` bus there writes all source channels via `_maxChannels = /// Int.max`. Use a typed bus allocation if you want explicit /// multi-channel writes from a plain index. private let _channels: Int public override var outputChannelCount: Int { _channels } /// - Parameters: /// - bus: Destination bus — `Int` index or ``ControlBus`` (writing clamped to /// `bus.channelCount`). An ``AudioBus`` traps; use ``ReplaceOut/Audio``. /// - source: Signal to write. Multi-channel sources overwrite consecutive buses. public init( bus: any ValidBus, source: any ValidGeneratorInput ) { _preconditionControlRateBus(bus) let ch: Int = _resolvedChannelCount(bus) self._channels = ch super.init(bus: bus.index, source: source, maxChannels: bus.channelCount, channels: ch) _registerAsRootIfBuilding() } public func _computeSamples( graph: SynthGraph, count: Int ) -> [[Double]] { _checkCount(count) let sourceSamples: [[Double]] = source.calculatedSamples(graph: graph, count: count) for ch: Int in 0..<_channels { let busIdx: Int = bus + ch guard busIdx >= 0 && busIdx < graph.engine.numControlBuses else { for i: Int in 0.. 0, "ReplaceOut.Control: row classified non-empty above") let val: Double = row[min(rowCount - 1, count - 1)] graph.engine.setControlBus(busIdx, value: Float(val)) for i: Int in 0.. Double { Double(graph.engine.controlBuses[bus]) } } } extension ReplaceOut: GeneratorEnum { public typealias AudioType = ReplaceOut.Audio public typealias ControlType = ReplaceOut.Control }