Files
Lyrebird/docs/stdlib/buffer-io-generators.md
T
2026-06-01 18:27:40 -07:00

376 lines
12 KiB
Markdown
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.
# Buffer I/O Generators — RecordBuffer + PlayBuffer
Record signal into a `LyrebirdBuffer` and play it back at variable rate.
Both generators come in two rate variants following the `_Base`/`Audio`/`Control` enum pattern:
| Type | Rate | Use |
|---|---|---|
| `RecordBuffer.Audio` | Audio (per-sample) | Record audio signals, multi-channel |
| `RecordBuffer.Control` | Control (per-block) | Record automation curves (LFO, envelopes) |
| `PlayBuffer.Audio` | Audio (per-sample) | Playback at variable rate with interpolation |
| `PlayBuffer.Control` | Control (per-block) | Playback of control automation data |
---
## RecordBuffer
Writes its input signal into a `LyrebirdBuffer` and passes the signal through as output. Recording and monitoring happen simultaneously.
### RecordBuffer.Audio
Audio-rate recording — writes one buffer frame per sample.
```swift
let buf = LyrebirdBuffer(count: 44100, channelCount: 1)
let rec = RecordBuffer.Audio(input: someOsc, buffer: buf, loop: false, doneAction: .freeNode)
output(bus: 0, source: rec)
```
### RecordBuffer.Control
Control-rate recording — writes one buffer frame per block. Use for automation curves (LFO outputs, envelope followers).
```swift
let automationBuf = LyrebirdBuffer(count: 1000)
let lfo = OscSin.Control(freq: 0.5)
let rec = RecordBuffer.Control(input: lfo, buffer: automationBuf, loop: false)
```
Requires a **mono** buffer (`channelCount == 1`). Use `RecordBuffer.Audio` for multi-channel.
### Shared parameters
```swift
// Both variants inherit these from RecordBuffer._Base:
@LiveParam public var run: LyrebirdFloat // > 0 = recording, ≤ 0 = paused (default 1.0)
@LiveParam public var recLevel: LyrebirdFloat // scale on incoming signal (default 1.0)
@LiveParam public var preLevel: LyrebirdFloat // scale on existing buffer (default 0.0 = overwrite)
public let buffer: LyrebirdBuffer
public let doneAction: DoneAction
public var needsFree: Bool // acquiring Atomic<Bool> load
```
### Init
```swift
RecordBuffer.Audio(
input: any ValidGeneratorInput,
buffer: LyrebirdBuffer,
loop: Bool = true,
doneAction: DoneAction = .nothing
)
RecordBuffer.Control(
input: any ValidGeneratorInput,
buffer: LyrebirdBuffer, // must be mono (channelCount == 1)
loop: Bool = true,
doneAction: DoneAction = .nothing
)
```
### Write formula
Each frame:
```
buffer[frame, ch] = recLevel × input[ch] + preLevel × buffer[frame, ch]
```
`preLevel = 0.0` overwrites; `preLevel = 1.0` mixes new signal on top of existing content.
### Multi-channel (Audio variant)
Supply a `GeneratorArray` for stereo or N-channel buffers. Channel count must match `buffer.channelCount` — enforced by `precondition` in `_computeSamples`.
```swift
let buf = LyrebirdBuffer(count: 44100, channelCount: 2)
let stereoSrc = expand([leftSig, rightSig]) { $0 }
let rec = RecordBuffer.Audio(input: stereoSrc, buffer: buf)
output(bus: 0, source: rec) // stereo passthrough + stereo recording
```
### run param
Set `run = 0.0` to pause recording (write head holds position). Set `run = 1.0` to resume. The write head does not reset on resume.
### RT-safety note
Both variants write to `LyrebirdBuffer` storage from the RT thread. The buffer is **not safe for concurrent non-RT reads while recording is active**. Stop recording before reading from another thread.
### doneAction (loop == false)
| `DoneAction` | Behaviour |
|---|---|
| `.nothing` | Recording stops; generator stays in graph outputting passthrough |
| `.freeNode` | Sets `needsFree = true`; poll from main thread and call `engine.remove` |
| `.loop` | Resets write head to frame 0 (equivalent to `loop: true`) |
---
## PlayBuffer
Reads back a `LyrebirdBuffer` at a variable rate with interpolation.
### PlayBuffer.Audio
Audio-rate playback — reads one buffer frame per sample with interpolation. Output channel count equals `buffer.channelCount`.
```swift
let player = PlayBuffer.Audio(buffer: buf, loop: false, doneAction: .freeNode)
output(bus: 0, source: player)
```
### PlayBuffer.Control
Control-rate playback — advances phase once per block. Produces a linear-ramp output matching the `ControlGenerator` ramp convention. Use to play back automation curves recorded by `RecordBuffer.Control`.
```swift
let player = PlayBuffer.Control(buffer: automationBuf, loop: true)
```
Requires a **mono** buffer (`channelCount == 1`). Use `PlayBuffer.Audio` for multi-channel.
### Shared parameters
```swift
// Both variants inherit these from PlayBuffer._Base:
public let buffer: LyrebirdBuffer
public let doneAction: DoneAction
public var needsFree: Bool
```
### Init
```swift
PlayBuffer.Audio(
buffer: LyrebirdBuffer,
loop: Bool = true,
interpolation: TableInterpolation = .linear,
doneAction: DoneAction = .nothing,
startPos: Double = 0.0, // fractional frame index to begin playback
rate: any ValidGeneratorInput = 1.0, // playback rate multiplier
trigger: any ValidGeneratorInput = 0.0 // ≤0 → >0 edge resets play head
)
PlayBuffer.Control(
buffer: LyrebirdBuffer, // must be mono (channelCount == 1)
loop: Bool = true,
interpolation: TableInterpolation = .linear,
doneAction: DoneAction = .nothing,
startPos: Double = 0.0,
rate: any ValidGeneratorInput = 1.0,
trigger: any ValidGeneratorInput = 0.0
)
```
### Rate
| `rate` | Effect |
|---|---|
| `1.0` | Original speed (forward) |
| `2.0` | Double speed, pitch up one octave |
| `0.5` | Half speed, pitch down one octave |
| `-1.0` | Original speed, reversed |
| `-2.0` | Double speed, reversed, pitch up one octave |
`rate` accepts any `ValidGeneratorInput` — pass a generator for varispeed / vibrato:
```swift
// Constant rate (scalar at init):
let player = PlayBuffer.Audio(buffer: buf, rate: 2.0)
// Generator-driven rate (LFO vibrato):
let lfo = OscSin.Audio(freq: 5.0, mul: 0.05, add: 1.0)
let player = PlayBuffer.Audio(buffer: buf, rate: lfo)
```
### Reverse playback
Set `rate` negative to play the buffer in reverse. Use `startPos` to begin from the last frame:
```swift
let player = PlayBuffer.Audio(
buffer: buf,
loop: true,
startPos: Double(buf.count - 1),
rate: -1.0
)
```
With `loop: true` and a negative rate, `_phase` wraps from 0 back to the end of the buffer (seamless reverse loop). With `loop: false`, reaching `_phase < 0` fires `doneAction` and holds playback at frame 0.
### Trigger
`trigger` accepts any `ValidGeneratorInput`. Edge detection (≤0 → >0 transition) resets the play head to frame 0 and clears the `_isDone` flag.
```swift
// Scalar: always high — fires once on first sample (since _prevTrigger starts at 0).
let oneshot = PlayBuffer.Audio(buffer: buf, loop: false, trigger: 1.0)
// Generator: impulse-driven sample-accurate retrigger.
let imp = Impulse.Audio(freq: 2.0)
let player = PlayBuffer.Audio(buffer: buf, loop: false, trigger: imp)
// Mutable ParameterNode (when trigger must change over time):
let trigNode = ParameterNode(0.0)
let player = PlayBuffer.Audio(buffer: buf, trigger: trigNode)
// ... later, from non-RT thread:
trigNode.value = 1.0 // arm trigger
trigNode.value = 0.0 // lower, ready for next retrigger
```
### Multi-channel (Audio variant)
A stereo buffer produces two output channels. Wire through `output(bus:source:)`:
```swift
let stereoPlayer = PlayBuffer.Audio(buffer: stereoBuffer)
output(bus: 0, source: stereoPlayer) // bus 0 = left, bus 1 = right
```
### Interpolation
| Mode | Quality | Cost |
|---|---|---|
| `.none` | Truncate to nearest frame | Cheapest |
| `.linear` | Two-sample blend (default) | Low |
| `.cubic` | Catmull-Rom four-sample | Highest quality |
### doneAction (loop == false)
Same as `RecordBuffer` — `.freeNode` is the typical choice for one-shot samples.
```swift
let player = PlayBuffer.Audio(buffer: buf, loop: false, doneAction: .freeNode)
try engine.add(samplePlayer)
// Poll on main thread:
if player.needsFree { engine.remove(samplePlayer) }
```
---
## Sample-rate compensation
`LyrebirdBuffer` stores the native sample rate of its audio data:
```swift
public var sampleRate: Double? = nil
```
This is set automatically when loading from a file via `LyrebirdBuffer.load(url:)` or `loadAllChannels(url:)`. For manually-filled buffers, set `sampleRate` explicitly.
When playing a file recorded at a different sample rate than the engine, ask the buffer for the correcting `playRate` multiplier via `LyrebirdBuffer.nativeRateScale(engineSampleRate:)`. The helper is on the buffer itself so any buffer-consuming generator (`PlayBuffer`, granular, future warp/scrubbers) can reuse it:
```swift
let buf = try LyrebirdBuffer.loadAllChannels(url: url) // buf.sampleRate set automatically
// Example — your synthesizer, defined by subclassing SynthesizerBase
final class SamplePlayer: SynthesizerBase {
override func build() {
let rateScale = buf.nativeRateScale(engineSampleRate: engine.sampleRate)
let player = PlayBuffer.Audio(buffer: buf, loop: false,
doneAction: .freeNode, rate: rateScale)
output(bus: 0, source: player)
}
}
```
Returns `1.0` when `buffer.sampleRate` is `nil` (rate unknown).
---
## lyrebirdBufferRead
Free function used by `PlayBuffer` (and available to future generators like `GrainBuf`):
```swift
internal func lyrebirdBufferRead(
_ buffer: LyrebirdBuffer,
channel: Int,
phase: LyrebirdFloat,
interpolation: TableInterpolation,
loop: Bool
) -> LyrebirdFloat
```
Frame boundaries are **clamped** when `loop == false`, **wrapped modulo** `buffer.count` when `loop == true`.
---
## Combined example: looper
```swift
// Example — your synthesizer, defined by subclassing SynthesizerBase
final class Looper: SynthesizerBase {
let recordBuf = LyrebirdBuffer(count: 44100 * 4, channelCount: 2) // 4-second stereo buffer
lazy var recorder = RecordBuffer.Audio(input: micInput, buffer: recordBuf, loop: false, doneAction: .nothing)
lazy var player = PlayBuffer.Audio(buffer: recordBuf, loop: true)
override func build() {
output(bus: 0, source: recorder) // monitor mic while recording
// player is added separately after recording finishes
}
}
// Stop recording after 4 seconds, start playback:
looper.recorder.run = 0.0
try engine.add(playerSynth)
```
## Combined example: control automation round-trip
```swift
let automationBuf = LyrebirdBuffer(count: 1000)
// Record an LFO curve
let lfo = OscSin.Control(freq: 0.5)
let rec = RecordBuffer.Control(input: lfo, buffer: automationBuf, loop: false, doneAction: .nothing)
// Play it back later
let player = PlayBuffer.Control(buffer: automationBuf, loop: true)
// Wire player output to a parameter (e.g. oscillator frequency)
```
---
## Live buffer swap
`PlayBuffer.Audio`, `PlayBuffer.Control`, `BufferRead.Audio`, and
`BufferRead.Control` all expose a `setBuffer(_:engine:)` method that replaces
the source buffer on a running engine without rebuilding the synth graph.
```swift
let player = PlayBuffer.Audio(buffer: bufA, loop: true)
// later, while the engine is running:
player.setBuffer(bufB, engine: engine) // swap source
player.setBuffer(nil, engine: engine) // silence (slot empty)
```
Constraints (precondition-trapped):
- New buffer's `channelCount` must equal the initial buffer's `channelCount` —
the generator's output buffer shape is fixed at init.
- Frame `count` may differ; phase wrapping uses the loaded buffer's `count` on
each block. If `_phase` overshoots the new (smaller) buffer, the next sample
read is clamped (`loop == false`) or wrapped (`loop == true`) by
`lyrebirdBufferRead`, and the in-loop wrap normalises `_phase` afterwards.
- `PlayBuffer.Control` was preconditioned mono at init; the setter inherits
that — any swap-in buffer must satisfy `channelCount == 1`.
The previously installed buffer's retain is routed through
`engine.bufferSwapKillQueue` and released by the engine's background
`freeWorker`, never on the RT thread. See ``BufferGuide`` § "Live Buffer Swap"
for the full pattern.
---
## See also
- `Sources/Lyrebird/Generators/RecordBuffer.swift`
- `Sources/Lyrebird/Generators/PlayBuffer.swift`
- `Sources/Lyrebird/Buffers/LyrebirdBuffer.swift` — buffer allocation, fill, invalidation, sampleRate
- `Sources/Lyrebird/Buffers/RTBufferSlot.swift` — atomic slot powering live buffer swap
- `docs/stdlib/generators.md` — built-in generator index
- `docs/engine/bus-system.md` — bus layout