Files
Lyrebird/Sources/Lyrebird/Generators/Routing/Select.swift
T
2026-06-21 11:45:58 -07:00

223 lines
9.3 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Select.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// File-scope zero-fill block for Select — fallback when upstream returns no channel.
private let selectZeroBlock: [Double] = [Double](
repeating: 0,
count: lyrebirdDefaultResultBufferSize
)
// MARK: - Select
/// Index-selected N-input switch. Equivalent to SuperCollider `Select`.
///
/// Outputs the input at integer index `which` (truncated toward zero, clamped to
/// `[0, N−1]`). All inputs are pulled every block so their internal state advances —
/// SC semantics. Mono output (channel 0 of each input is used).
///
/// **SC parity note:** in SuperCollider `Select` all inputs are evaluated every block
/// regardless of which is selected. This keeps sequenced and modulated sources in sync
/// when switching between them. Lyrebird preserves this behaviour.
///
/// ```swift
/// // Switch between three oscillators.
/// let sel = Select.Audio(which: lfo, inputs: [osc1, osc2, osc3])
/// ```
///
/// - Parameters:
/// - which: Input index. Truncated toward zero; clamped to `[0, N−1]`. Can be a
/// generator for per-sample switching (audio rate) or block-rate switching (control rate).
/// - inputs: Array of signal sources. Must contain at least one element.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public enum Select {
// MARK: - Shared base
/// Shared stored properties for `Select.Audio` and `Select.Control`.
public class _Base: GeneratorBase {
let _inputs: [any ValidGeneratorInput]
let _whichInput: any ValidGeneratorInput
let _whichIsGenerator: Bool
/// Per-input generator classification, resolved at `init` time. `true` when the
/// corresponding element of `_inputs` is an `any Generator`; `false` for scalar /
/// Closure inputs. Classified on the resolved value — never queried on the RT thread.
let _inputIsGenerator: [Bool]
let _inputCount: Int
let _mulAdd: MulAddSpec
/// Pre-allocated per-input scratch rows: `_inputCount` rows of
/// `lyrebirdDefaultResultBufferSize` each. Populated in `_computeSamples` before
/// the output loop; never resized on the RT thread.
var _scratch: [[Double]]
init(
which: any ValidGeneratorInput,
inputs: [any ValidGeneratorInput],
mul: any ValidGeneratorInput,
add: any ValidGeneratorInput
) {
precondition(!inputs.isEmpty, "Select requires at least one input")
let resolvedWhich: any ValidGeneratorInput = which._resolvedInput()
let resolvedInputs: [any ValidGeneratorInput] = inputs.map { $0._resolvedInput() }
_whichInput = resolvedWhich
_whichIsGenerator = resolvedWhich is any Generator
_inputs = resolvedInputs
_inputIsGenerator = resolvedInputs.map { $0 is any Generator }
_inputCount = resolvedInputs.count
_mulAdd = MulAddSpec(mul: mul, add: add)
_scratch = makeResultBuffer(channels: resolvedInputs.count)
}
}
// MARK: - Audio rate
/// Audio-rate N-input index switch.
///
/// All inputs are pulled every block (SC semantics). Per-sample `which` selects the
/// source index at audio rate. Non-integer `which` truncates toward zero.
///
/// - Parameters:
/// - which: Input index. Truncated toward zero; clamped to `[0, N−1]`.
/// - inputs: Array of signal sources. Must contain at least one element.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public final class Audio: _Base, AudioGenerator {
/// - Parameters:
/// - which: Input index. Truncated toward zero; clamped to `[0, N−1]`.
/// - inputs: Array of signal sources. Must contain at least one element.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public override init(
which: any ValidGeneratorInput,
inputs: [any ValidGeneratorInput],
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
super.init(which: which, inputs: inputs, mul: mul, add: add)
}
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
// Pull all inputs (SC semantics: every input advances every block).
// Generator inputs: calculatedSamples — copy channel 0 into scratch via pointer.
// Scalar/Closure inputs: floatValue — fill scratch row with the scalar (no alloc).
for k: Int in 0..<_inputCount {
if _inputIsGenerator[k] {
let srcBlock: [Double] = _inputs[k].calculatedSamples(
graph: graph, count: count).first ?? selectZeroBlock
srcBlock.withUnsafeBufferPointer { srcBuf in
guard let srcBase: UnsafePointer<Double> = srcBuf.baseAddress else { return }
_scratch[k].withUnsafeMutableBufferPointer { dstBuf in
guard let dstBase: UnsafeMutablePointer<Double> = dstBuf.baseAddress
else { return }
dstBase.update(from: srcBase, count: count)
}
}
} else {
let scalar: Double = _inputs[k].floatValue(graph: graph)
_scratch[k].withUnsafeMutableBufferPointer { dstBuf in
guard let dstBase: UnsafeMutablePointer<Double> = dstBuf.baseAddress
else { return }
for i: Int in 0..<count {
dstBase[i] = scalar
}
}
}
}
let lastIdx: Int = _inputCount - 1
let (whichSamples, scalarWhich) = resolveGeneratorOrScalar(
_whichInput, isGenerator: _whichIsGenerator, graph: graph, count: count)
for i: Int in 0..<count {
let rawIdx: Double = sampleOrFallback(whichSamples, scalar: scalarWhich, at: i)
let idx: Int = Swift.max(0, Swift.min(lastIdx, Int(rawIdx)))
_result[0][i] = _scratch[idx][i]
}
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
}
// MARK: - Control rate
/// Control-rate N-input index switch.
///
/// Reads all inputs via `floatValue` every block (advancing their state), then computes
/// the selected index from `which.floatValue`. At control rate a `which` change glides
/// over the sub-block ramp. Non-integer `which` truncates toward zero.
///
/// - Parameters:
/// - which: Input index. Truncated toward zero; clamped to `[0, N−1]`.
/// - inputs: Array of signal sources. Must contain at least one element.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public final class Control: _Base, ControlGenerator {
public var previousOutputValue: Double = 0.0
/// - Parameters:
/// - which: Input index. Truncated toward zero; clamped to `[0, N−1]`.
/// - inputs: Array of signal sources. Must contain at least one element.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public override init(
which: any ValidGeneratorInput,
inputs: [any ValidGeneratorInput],
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
super.init(which: which, inputs: inputs, mul: mul, add: add)
_setupSubBlockBuffer()
}
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
// Pull all inputs via floatValue (advances state, SC semantics).
// Cache values so we can re-read the selected one without a second floatValue call.
for k: Int in 0..<_inputCount {
_scratch[k][0] = _inputs[k].floatValue(graph: graph)
}
let lastIdx: Int = _inputCount - 1
let rawIdx: Double = _whichInput.floatValue(graph: graph)
let idx: Int = Swift.max(0, Swift.min(lastIdx, Int(rawIdx)))
var target: Double = _scratch[idx][0]
if !_mulAdd.isIdentity {
target = target * _mulAdd.mulInput.floatValue(graph: graph)
+ _mulAdd.addInput.floatValue(graph: graph)
}
fillScalarRampedResult(
into: &_result,
previousOutputValue: &previousOutputValue,
target: target,
count: count
)
return _result
}
public func floatValue(graph: SynthGraph) -> Double { previousOutputValue }
}
}
// MARK: - GeneratorEnum
extension Select: GeneratorEnum {
public typealias AudioType = Select.Audio
public typealias ControlType = Select.Control
}