2 Commits

Author SHA1 Message Date
josh 8a2eb191a2 improve freq trackers 2026-07-02 14:48:37 -07:00
josh 676e8d3278 1.2.1 release to support some ShoeGaze features 2026-07-02 10:20:40 -07:00
14 changed files with 785 additions and 32 deletions
+7
View File
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:.">
</FileRef>
</Workspace>
@@ -117,6 +117,9 @@ import Synchronization
/// `invalidate()` uses a `.releasing` store; `isValid` uses an `.acquiring` load.
/// `LyrebirdBuffer` is safe to share across threads:
/// - The validity flag is protected by `Atomic<Bool>`.
/// - `loopLength` is likewise an `Atomic<Int>` (`.acquiring` load / `.releasing` store
/// via ``setLoopLength(_:)``) — read every sample by `PlayBuffer`-family generators,
/// written once (non-RT) after e.g. a looper pedal finishes recording a take.
/// - `channelCount` and `count` are `let` constants — freely readable on any thread.
/// - Sample data can be written from the RT thread by `RecordBuffer` via the internal
/// `write(_:frame:channel:)` method. The buffer is **not safe for concurrent non-RT
@@ -240,6 +243,45 @@ public final class LyrebirdBuffer: @unchecked Sendable {
return bufRate / engineSampleRate
}
/// Number of frames that `PlayBuffer`-family generators should wrap (looping) or
/// clamp (non-looping) against, distinct from `count` (the full allocated size).
///
/// Defaults to `count` at init, matching the historical full-buffer looping
/// behaviour. Narrow this after recording a take that is shorter than the
/// buffer's max-duration allocation — e.g. a looper pedal that pre-allocates
/// 60 seconds but records a shorter take — so playback wraps only over the
/// actually-recorded region without reallocating the buffer.
///
/// **RT contract.** Stored as an `Atomic<Int>` rather than behind `_writeLock`:
/// this value is read on every sample inside `PlayBuffer`'s per-sample read loop
/// (`lyrebirdBufferRead`), so a lock acquired every sample would be the wrong
/// tool. An atomic load costs nothing close to a lock and gives torn-free reads
/// of a single `Int`. Set from a non-RT thread via ``setLoopLength(_:)``, e.g.
/// once after recording stops.
private let _loopLength: Atomic<Int>
/// Current loop/clamp bound for `PlayBuffer`-family generators, in frames.
///
/// `1...count`, defaulting to `count`. Read with an `.acquiring` load — safe to
/// call from the RT thread inside a per-sample read loop.
public var loopLength: Int {
_loopLength.load(ordering: .acquiring)
}
/// Narrow (or restore) the frame count that `PlayBuffer`-family generators wrap
/// or clamp against.
///
/// Call from a non-RT thread — typically once, right after recording stops
/// (e.g. a looper pedal calling this with the frame count `RecordBuffer`
/// actually wrote, so playback loops over just the recorded take instead of
/// the full max-duration allocation).
///
/// - Parameter length: Desired loop length in frames. Clamped to `[1, count]`.
public func setLoopLength(_ length: Int) {
let clamped: Int = max(1, min(length, count))
_loopLength.store(clamped, ordering: .releasing)
}
/// Atomic validity flag. `true` after `init`, `false` after `invalidate()`.
private let _isValid: Atomic<Bool>
@@ -460,6 +502,7 @@ public final class LyrebirdBuffer: @unchecked Sendable {
_storage = UnsafeMutablePointer<Double>.allocate(capacity: total)
_storage.initialize(repeating: 0, count: total)
_isValid = Atomic<Bool>(true)
_loopLength = Atomic<Int>(count)
}
deinit {
@@ -10,10 +10,14 @@ import Synchronization
/// Interpolated read from `buffer` at a fractional frame `phase` for one `channel`.
///
/// - For `loop == true`: frames wrap modulo `buffer.count` (seamless looping). `wrappedFrame`
/// handles negative frame indices via `r += frameCount`, so backward reads across the loop
/// point are correct.
/// - For `loop == false`: frames are clamped to `[0, buffer.count − 1]` (hold at ends).
/// - For `loop == true`: frames wrap modulo `buffer.loopLength` (seamless looping).
/// `wrappedFrame` handles negative frame indices via `r += frameCount`, so backward
/// reads across the loop point are correct.
/// - For `loop == false`: frames are clamped to `[0, buffer.loopLength − 1]` (hold at ends).
///
/// `buffer.loopLength` defaults to `buffer.count` (full-buffer looping) but may be
/// narrowed at runtime — e.g. a looper pedal that recorded a take shorter than its
/// max-duration buffer allocation — to bound wrap/clamp to just the recorded region.
///
/// Used by `PlayBuffer.Audio` and `PlayBuffer.Control`; exposed as `internal` for reuse by
/// future buffer-reading generators (e.g. `BufferGrain`).
@@ -25,7 +29,7 @@ internal func lyrebirdBufferRead(
interpolation: TableInterpolation,
loop: Bool
) -> Double {
let frameCount: Int = buffer.count
let frameCount: Int = buffer.loopLength
@inline(__always)
func clampedFrame(_ f: Int) -> Int {
@@ -356,7 +360,7 @@ public enum PlayBuffer {
return _result
}
let bufferFrames: Double = Double(buffer.count)
let bufferFrames: Double = Double(buffer.loopLength)
@inline(__always)
func rateAt(_ i: Int) -> Double {
@@ -526,7 +530,7 @@ public enum PlayBuffer {
// Read one output value for this block.
let outputVal: Double
if let buffer: LyrebirdBuffer = _slot.load(engine: graph.engine), buffer.isValid, !_isDone {
let bufferFrames: Double = Double(buffer.count)
let bufferFrames: Double = Double(buffer.loopLength)
outputVal = lyrebirdBufferRead(
buffer, channel: 0, phase: _phase,
interpolation: interpolation, loop: loop
@@ -90,6 +90,27 @@ public enum RecordBuffer {
var _isDone: Bool = false
let _needsFree: Atomic<Bool> = Atomic(false)
/// Set by `requestReset()` on a non-RT thread, consumed once at the top of the
/// next `_computeSamples` call on the RT thread.
let _resetRequested: Atomic<Bool> = Atomic(false)
/// Block-rate snapshot of `writePos`, published once per audio block rather
/// than per sample to avoid extra atomic-store overhead in the hot per-sample
/// write loops. Updated at the end of every `_computeSamples` call.
let _writePosSnapshot: Atomic<Int> = Atomic(0)
/// Number of frames written to `buffer` so far, safe to read from a non-RT
/// thread.
///
/// `writePos` itself is a plain `var` mutated per-sample on the RT thread and
/// is not safe for concurrent non-RT reads. This snapshot is published once
/// per audio block (`.releasing` store at the end of `_computeSamples`) and
/// read here with an `.acquiring` load, so a caller can safely read "how many
/// frames were recorded" after stopping recording (e.g. setting `run = 0`) —
/// for example a looper pedal narrowing `buffer.loopLength` to the actually
/// recorded region once the take finishes.
public var recordedFrameCount: Int { _writePosSnapshot.load(ordering: .acquiring) }
/// `true` when `doneAction == .freeNode` and recording has completed.
///
/// Read from a non-RT context after `processBlock` returns and schedule
@@ -122,9 +143,42 @@ public enum RecordBuffer {
// MARK: - Shared
/// Requests that recording restart from frame 0 on the next processed block.
///
/// Safe to call from any non-RT thread at any time (e.g. a "reset" UI action on
/// a looper pedal). Sets an `Atomic<Bool>` flag consumed once at the top of the
/// next `_computeSamples` call — `writePos` is reset to `0`, `_isDone` cleared,
/// and any pending `.freeNode` completion (`needsFree`) is cleared so the same
/// instance can be reused for a fresh take. Because the flag is only checked at
/// block boundaries, the reset takes effect at the start of the next block, not
/// mid-block — acceptable for a user-triggered action.
///
/// Does **not** touch `buffer` contents or `buffer.loopLength`. Callers that want
/// a fully blank take should also call `buffer.clear()` and
/// `buffer.setLoopLength(buffer.count)` themselves before or after calling this.
public func requestReset() {
_resetRequested.store(true, ordering: .releasing)
}
/// Consumes a pending reset request, if any. Call once at the top of
/// `_computeSamples` before touching `writePos` / `_isDone`.
@inline(__always)
func _consumeResetIfRequested() {
let (exchanged, _): (Bool, Bool) = _resetRequested.compareExchange(
expected: true,
desired: false,
ordering: .acquiringAndReleasing
)
if exchanged {
writePos = 0
_isDone = false
_needsFree.store(false, ordering: .releasing)
}
}
func handleEndOfBuffer() {
_isDone = true
writePos = buffer.count - 1
writePos = buffer.loopLength - 1
switch doneAction {
case .nothing:
break
@@ -202,6 +256,10 @@ public enum RecordBuffer {
) -> [[Double]] {
_checkCount(count)
guard count > 0 else { return _result }
_consumeResetIfRequested()
// Publish `writePos` once per block (not per sample) for non-RT readers —
// see `recordedFrameCount` doc-comment.
defer { _writePosSnapshot.store(writePos, ordering: .releasing) }
let runSamples: [Double] = $run.calculatedSamples(graph: graph, count: count).first
?? _zeroFallback
@@ -212,7 +270,12 @@ public enum RecordBuffer {
let chCount: Int = channelCount
let bufferIsLive: Bool = buffer.isValid
let bufferCount: Int = buffer.count
// Wrap/overrun bound is the caller-narrowed `loopLength` (defaults to `count`), for
// both `loop == true` (a looping overdub recorder re-writes exactly the recorded
// take instead of the full allocated buffer) and `loop == false` (the overrun pins
// `writePos` to `loopLength - 1` via `handleEndOfBuffer()`, consistent with this bound
// regardless of when the caller narrows `loopLength`).
let bufferCount: Int = buffer.loopLength
let canRecord: Bool = bufferIsLive && !_isDone
let localLoop: Bool = loop
@@ -524,6 +587,10 @@ public enum RecordBuffer {
) -> [[Double]] {
_checkCount(count)
guard count > 0 else { return _result }
_consumeResetIfRequested()
// Publish `writePos` once per block (not per sample) for non-RT readers —
// see `recordedFrameCount` doc-comment.
defer { _writePosSnapshot.store(writePos, ordering: .releasing) }
// Evaluate params: advance ParameterNode state; use settled (last-sample) value.
let runSamples: [Double] = $run.calculatedSamples(graph: graph, count: count).first
@@ -551,7 +618,7 @@ public enum RecordBuffer {
let existing: Double = buffer[writePos, 0]
buffer.write(recVal * inputVal + preVal * existing, frame: writePos, channel: 0)
writePos += 1
if writePos >= buffer.count {
if writePos >= buffer.loopLength {
if loop { writePos = 0 }
else { handleEndOfBuffer() }
}
@@ -10,7 +10,9 @@ import Darwin
///
/// Accumulates samples into a ring buffer and re-evaluates every `hopSize` samples.
/// Between hops the output holds the previous result — frequency stabilises after
/// one or two hops (~46 ms at the default settings and 44100 Hz sample rate).
/// one or two hops (~46 ms at the default settings, `decimation: 1`, and 44100 Hz sample
/// rate). Settle time scales with `decimation` (each hop spans `decimation×` more
/// wall-clock time), so `decimation: 4` stabilises in ~184 ms.
///
/// ## Output
/// Returns a two-channel buffer:
@@ -19,10 +21,13 @@ import Darwin
///
/// ## Parameters
/// - `in`: signal to analyse (Audio-rate input evaluated per sample)
/// - `fftSize`: analysis window in samples (must be power of 2, set at init)
/// - `hopSize`: samples between re-analyses (set at init; default `fftSize / 2`)
/// - `fftSize`: analysis window in **decimated** samples (must be power of 2, set at init)
/// - `hopSize`: decimated samples between re-analyses (set at init; default `fftSize / 2`)
/// - `minFreq`: lower search bound in Hz (default 60.0)
/// - `maxFreq`: upper search bound in Hz (default 3000.0)
/// - `decimation`: keep only every Nth input sample before analysis (default `1`), lowering
/// the effective rate to `sampleRate / decimation` to reach lower fundamentals. Caller must
/// band-limit below the decimated Nyquist first. See the `init` doc for full detail.
///
/// ## Usage
/// ```swift
@@ -62,6 +67,7 @@ public final class FreqTracker: GeneratorBase, AudioGenerator {
private let _hopSize: Int
private let _minFreq: Double
private let _maxFreq: Double
private let _decimation: Int
// MARK: - Input
@@ -82,6 +88,11 @@ public final class FreqTracker: GeneratorBase, AudioGenerator {
private var _lastFreq: Double = 0.0
private var _lastConfidence: Double = 0.0
// Counts raw input samples toward the next decimated (stored) sample. Only every
// `_decimation`-th input sample is written into the ring; the ring/hop machinery then
// operates entirely in the decimated time base.
private var _decimationCounter: Int = 0
// MARK: - Output
// MARK: - Fan-out cache
@@ -89,18 +100,32 @@ public final class FreqTracker: GeneratorBase, AudioGenerator {
/// - Parameters:
/// - input: Signal to track.
/// - fftSize: Analysis window in samples. Power of 2 in [64, 512]. Default 512.
/// Larger values increase latency and YIN cost (O(halfSize²) per hop);
/// 512 gives ~5.8 ms at 44100 Hz and is the maximum RT-safe value.
/// - hopSize: Samples between analysis updates. Default `fftSize / 2`.
/// - fftSize: Analysis window in **decimated** samples. Power of 2 in [64, 512].
/// Default 512. Larger values increase latency and YIN cost (O(halfSize²)
/// per hop); 512 gives ~5.8 ms at 44100 Hz and is the maximum RT-safe value.
/// - hopSize: Decimated samples between analysis updates. Default `fftSize / 2`.
/// - minFreq: Minimum tracked frequency in Hz. Default 60.0.
/// - maxFreq: Maximum tracked frequency in Hz. Default 3000.0.
/// - decimation: Keep only every `decimation`-th input sample before analysis, lowering
/// the effective sample rate to `sampleRate / decimation`. Default `1` (no
/// decimation — original behaviour). A 512-sample window can then span
/// `decimation ×` more time, extending the **minimum** detectable frequency
/// down to roughly `sampleRate / (decimation × (fftSize/2 − 1))` while keeping
/// YIN's O(halfSize²) cost fixed — ideal for low-pitched monophonic sources
/// (bass, low guitar strings) where high-frequency resolution isn't needed.
/// **The caller must band-limit the input below the decimated Nyquist
/// (`sampleRate / (2 × decimation)`) first** — decimation does no anti-alias
/// filtering of its own. The `maxFreq` search bound must also stay below that
/// decimated Nyquist. Latency to a stable reading scales with `decimation`
/// (each hop spans `decimation×` more wall-clock time), so `decimation: 4`
/// settles in ~4× the undecimated hop-based time.
public init(
in input: any ValidGeneratorInput,
fftSize: Int = 512,
hopSize: Int? = nil,
minFreq: Double = 60.0,
maxFreq: Double = 3000.0
maxFreq: Double = 3000.0,
decimation: Int = 1
) {
precondition(fftSize >= 64 && fftSize <= 512 && (fftSize & (fftSize - 1)) == 0,
"FreqTracker: fftSize must be a power of 2 in [64, 512]; got \(fftSize). "
@@ -108,6 +133,8 @@ public final class FreqTracker: GeneratorBase, AudioGenerator {
+ "Reduce fftSize or implement background-thread YIN in a future phase.")
precondition(minFreq > 0 && maxFreq > minFreq,
"FreqTracker: minFreq must be > 0 and < maxFreq")
precondition(decimation >= 1,
"FreqTracker: decimation must be >= 1; got \(decimation).")
_fftSize = fftSize
_hopSize = hopSize ?? fftSize / 2
@@ -119,6 +146,7 @@ public final class FreqTracker: GeneratorBase, AudioGenerator {
+ "Larger values cause the YIN window to read stale data.")
_minFreq = minFreq
_maxFreq = maxFreq
_decimation = decimation
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
_input = resolvedInput
_inputRing = [Double](repeating: 0.0, count: fftSize)
@@ -135,16 +163,23 @@ public final class FreqTracker: GeneratorBase, AudioGenerator {
_checkCount(count)
let sr: Double = graph.engine.sampleRate
// Analysis runs in the decimated time base: the ring holds every `_decimation`-th
// input sample, so lag→frequency conversion uses the decimated effective rate.
let effectiveRate: Double = sr / Double(_decimation)
let inputSamples: [[Double]] = _input.calculatedSamples(graph: graph, count: count)
guard let ins: [Double] = inputSamples.first else {
// No input — advance ring with zeros, still fire hops so state advances correctly.
for _ in 0..<count {
_inputRing[_ringPos % _fftSize] = 0.0
_ringPos &+= 1
_samplesUntilHop -= 1
if _samplesUntilHop <= 0 {
_samplesUntilHop = _hopSize
_runYIN(sampleRate: sr)
_decimationCounter &+= 1
if _decimationCounter >= _decimation {
_decimationCounter = 0
_inputRing[_ringPos % _fftSize] = 0.0
_ringPos &+= 1
_samplesUntilHop -= 1
if _samplesUntilHop <= 0 {
_samplesUntilHop = _hopSize
_runYIN(sampleRate: effectiveRate)
}
}
}
for i: Int in 0..<count {
@@ -155,15 +190,21 @@ public final class FreqTracker: GeneratorBase, AudioGenerator {
}
for i: Int in 0..<count {
// Write incoming sample into ring buffer.
let sample: Double = Double(ins[i])
_inputRing[_ringPos % _fftSize] = sample
_ringPos &+= 1
// Write every `_decimation`-th incoming sample into the ring buffer. Naive
// decimation (take-every-Nth) is correct because the caller band-limits below
// the decimated Nyquist — see the `decimation` parameter docs.
_decimationCounter &+= 1
if _decimationCounter >= _decimation {
_decimationCounter = 0
let sample: Double = Double(ins[i])
_inputRing[_ringPos % _fftSize] = sample
_ringPos &+= 1
_samplesUntilHop -= 1
if _samplesUntilHop <= 0 {
_samplesUntilHop = _hopSize
_runYIN(sampleRate: sr)
_samplesUntilHop -= 1
if _samplesUntilHop <= 0 {
_samplesUntilHop = _hopSize
_runYIN(sampleRate: effectiveRate)
}
}
_result[0][i] = _lastFreq
_result[1][i] = _lastConfidence
@@ -0,0 +1,62 @@
// DbAmp.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// MARK: - DbAmp
/// Converts a decibel value to a linear amplitude multiplier: `10^(dB / 20)`.
///
/// Control-rate only — intended for live gain knobs authored in dB (e.g. a pedal's
/// output-level control) that need to drive another generator's linear gain input
/// every block. Wraps the scalar ``dbToAmp(_:)`` helper so the conversion formula
/// lives in one place.
///
/// - Parameter signal: Input value in decibels.
public enum DbAmp {
public class _Base: GeneratorBase {
let inputSource: any ValidGeneratorInput
let _mulAdd: MulAddSpec
public init(
_ signal: any ValidGeneratorInput,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
let resolvedSignal: any ValidGeneratorInput = signal._resolvedInput()
inputSource = resolvedSignal
_mulAdd = MulAddSpec(mul: mul, add: add)
}
}
/// - Parameters:
/// - signal: Input value in decibels.
/// - 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:
/// - signal: Input value in decibels.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public override init(
_ signal: any ValidGeneratorInput,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) { super.init(signal, mul: mul, add: add); _setupSubBlockBuffer() }
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
var target: Double = dbToAmp(inputSource.floatValue(graph: graph))
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
}
}
}
@@ -114,6 +114,44 @@ struct PlayBufferTests {
engine.stop()
}
// MARK: - loopLength narrowing
@Test func narrowedLoopLengthWrapsWithinBoundNotFullBuffer() throws {
// 32-frame buffer, loopLength narrowed to 8 — loop:true should wrap every
// 8 frames instead of every 32.
let engine: SynthesisEngine = try makeEngine(blockSize: 16)
let graph: SynthGraph = makeSynthGraph(engine: engine)
let buf: LyrebirdBuffer = makeRampBuffer(frames: 32)
let narrowedLength: Int = 8
buf.setLoopLength(narrowedLength)
let player: PlayBuffer.Audio = PlayBuffer.Audio(buffer: buf, loop: true, interpolation: .none)
let out: [[Double]] = player.calculatedSamples(graph: graph, count: 16)
// Frames 0–7 then 0–7 again (loopLength == 8), not 0–15 (full buffer.count).
let expected: [Double] = [0,1,2,3,4,5,6,7, 0,1,2,3,4,5,6,7]
for i: Int in 0..<16 {
#expect(abs(out[0][i] - expected[i]) < 1e-9,
"sample \(i): expected \(expected[i]), got \(out[0][i])")
}
engine.stop()
}
@Test func narrowedLoopLengthClampsWithoutLoop() throws {
// 32-frame buffer, loopLength narrowed to 8, loop:false — non-interpolated reads
// must clamp to loopLength - 1 (frame 7), not buffer.count - 1 (frame 31).
let buf: LyrebirdBuffer = makeRampBuffer(frames: 32)
let narrowedLength: Int = 8
buf.setLoopLength(narrowedLength)
let result: Double = lyrebirdBufferRead(
buf, channel: 0, phase: 100.0, interpolation: .none, loop: false
)
#expect(abs(result - Double(narrowedLength - 1)) < 1e-9,
"clamped read should hold at loopLength-1 (\(narrowedLength - 1)), got \(result)")
}
// MARK: - doneAction
@Test func doneActionFreeNodeSetsNeedsFree() throws {
@@ -450,6 +450,148 @@ struct RecordBufferTests {
#expect(rec.buffer.channelCount == 1)
}
// MARK: - recordedFrameCount
@Test func recordedFrameCountReflectsWritePosAfterStoppingMidBuffer() throws {
// Record 8 frames into a 32-frame buffer, then stop (run = 0), then verify
// recordedFrameCount reflects the frames actually written (8), not the full
// buffer allocation (32) — mirrors a looper pedal reading "how many frames
// were recorded" after calling run = 0.
let engine: SynthesisEngine = try makeEngine(blockSize: 8)
let buf: LyrebirdBuffer = LyrebirdBuffer(count: 32)
let rec: RecordBuffer.Audio = RecordBuffer.Audio(input: 1.0, buffer: buf, loop: false)
#expect(rec.recordedFrameCount == 0, "no frames recorded before first block")
// Block 1: writes 8 frames.
do {
let graph: SynthGraph = makeSynthGraph(engine: engine)
_ = rec.calculatedSamples(graph: graph, count: 8)
}
#expect(rec.recordedFrameCount == 8,
"recordedFrameCount should equal writePos after one block")
advanceBlock(engine)
// Stop recording.
rec.run = 0.0
// Block 2: run ramps toward 0 across the block, so a few more frames may be
// written before the gate fully closes; regardless recordedFrameCount must
// track writePos exactly and stay well short of the full 32-frame buffer.
do {
let graph: SynthGraph = makeSynthGraph(engine: engine)
_ = rec.calculatedSamples(graph: graph, count: 8)
}
#expect(rec.recordedFrameCount > 8, "some frames should be written while run ramps down")
#expect(rec.recordedFrameCount < buf.count, "recording stopped short of the full buffer")
engine.stop()
}
@Test func recordedFrameCountControlVariantTracksWritePos() throws {
let engine: SynthesisEngine = try makeEngine(blockSize: 8)
let buf: LyrebirdBuffer = LyrebirdBuffer(count: 16)
let rec: RecordBuffer.Control = RecordBuffer.Control(input: 1.0, buffer: buf, loop: false)
for blockIdx: Int in 0..<3 {
let graph: SynthGraph = makeSynthGraph(engine: engine)
_ = rec.calculatedSamples(graph: graph, count: 8)
#expect(rec.recordedFrameCount == blockIdx + 1,
"block \(blockIdx): expected recordedFrameCount \(blockIdx + 1)")
advanceBlock(engine)
}
engine.stop()
}
// MARK: - requestReset
@Test func requestResetRestartsWritePosAtNextBlock() throws {
// Simulate a looper "reset" action: record a few frames of one value, call
// requestReset(), then record a new value — the second take must overwrite
// starting at frame 0, not continue from the mid-buffer writePos.
let engine: SynthesisEngine = try makeEngine(blockSize: 8)
let buf: LyrebirdBuffer = LyrebirdBuffer(count: 32)
let rec: RecordBuffer.Audio = RecordBuffer.Audio(input: 1.0, buffer: buf, loop: false)
// First take: 8 frames of 1.0.
do {
let graph: SynthGraph = makeSynthGraph(engine: engine)
_ = rec.calculatedSamples(graph: graph, count: 8)
}
#expect(rec.recordedFrameCount == 8, "first take should write 8 frames")
advanceBlock(engine)
rec.requestReset()
// recLevel is a ParameterNode-backed @LiveParam: it ramps toward its new target
// over one block. Block A (frames 0–7, writePos restarted at 0 by the reset)
// ramps recLevel 1.0→2.0 with varying values; Block B (frames 8–15) records
// with recLevel flat at 2.0 — mirrors the recLevelScalesNewSignal pattern above.
rec.recLevel = 2.0
do {
let graph: SynthGraph = makeSynthGraph(engine: engine)
_ = rec.calculatedSamples(graph: graph, count: 8)
}
#expect(rec.recordedFrameCount == 8,
"reset should restart writePos at 0, so this block again reaches frame count 8")
advanceBlock(engine)
do {
let graph: SynthGraph = makeSynthGraph(engine: engine)
_ = rec.calculatedSamples(graph: graph, count: 8)
}
#expect(rec.recordedFrameCount == 16,
"writePos should continue advancing normally after the reset settles")
for i: Int in 8..<16 {
#expect(abs(buf[i, 0] - 2.0) < 1e-9,
"frame \(i): expected fresh take value 2.0 after reset, got \(buf[i, 0])")
}
for i: Int in 16..<32 {
#expect(buf[i, 0] == 0.0,
"frame \(i): region never reached by either take should remain unwritten")
}
engine.stop()
}
@Test func requestResetClearsDoneAndNeedsFree() throws {
// A prior .freeNode completion (isDone == true, needsFree == true) must be
// fully cleared by requestReset() so the same instance can record again.
let engine: SynthesisEngine = try makeEngine(blockSize: 8)
let buf: LyrebirdBuffer = LyrebirdBuffer(count: 8)
let rec: RecordBuffer.Audio = RecordBuffer.Audio(
input: 1.0,
buffer: buf,
loop: false,
doneAction: .freeNode
)
do {
let graph: SynthGraph = makeSynthGraph(engine: engine)
_ = rec.calculatedSamples(graph: graph, count: 8)
}
#expect(rec.needsFree, "doneAction .freeNode should set needsFree once buffer fills")
advanceBlock(engine)
rec.requestReset()
do {
let graph: SynthGraph = makeSynthGraph(engine: engine)
_ = rec.calculatedSamples(graph: graph, count: 8)
}
// handleEndOfBuffer pins writePos at buffer.count - 1 (matches
// doneActionFreeNodeSetsNeedsFree convention above) rather than buffer.count.
#expect(rec.recordedFrameCount == buf.count - 1,
"recording should resume and refill the buffer after reset")
#expect(rec.needsFree, "recording to the end again should re-trigger needsFree")
engine.stop()
}
// MARK: - Fast-path coverage
/// Default-mode hot path: `recLevel == 1`, `preLevel == 0`, `run == 1`, `loop == true`.
@@ -285,6 +285,55 @@ struct FreqTrackerTests {
#expect(avgFreq > 800.0 && avgFreq < 960.0)
}
}
@Test func decimationEnablesLowFrequencyTracking() {
// Low-E guitar string (E2 ≈ 82.4 Hz). At 44100 Hz with fftSize 512 (halfSize 256),
// the undecimated tracker floors out around 173 Hz and cannot see this pitch. With
// 4× decimation the effective rate is ~11025 Hz, dropping the floor to ~43 Hz, so
// the fundamental is now trackable with the same (cheap) 256-lag YIN window.
let e2: Double = 82.41
let sine: OscSin.Audio = OscSin.Audio(freq: e2, mul: 0.8)
let tracker: FreqTracker = FreqTracker(
in: sine,
fftSize: 512,
hopSize: 256,
minFreq: 40.0,
maxFreq: 660.0,
decimation: 4
)
// Decimation means each hop needs 4× more input samples, so render longer.
let blocks: Int = (512 * 4 / engine.blockSize) + 60
let (freqs, _) = collect2ch(tracker, engine: engine, blocks: blocks)
let tail: [Double] = Array(freqs.suffix(engine.blockSize * 5))
let nonZero: [Double] = tail.filter { $0 > 0 }
#expect(!nonZero.isEmpty, "4× decimation should let FreqTracker detect an 82 Hz tone")
if !nonZero.isEmpty {
let avgFreq: Double = nonZero.reduce(0.0, +) / Double(nonZero.count)
#expect(avgFreq > 78.0 && avgFreq < 87.0, "Expected ~82 Hz, got \(avgFreq)")
}
}
@Test func decimationDefaultsToUnchangedBehaviour() {
// decimation: 1 (default) must reproduce the plain-A440 tracking result.
let sine: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.8)
let tracker: FreqTracker = FreqTracker(
in: sine,
fftSize: 512,
hopSize: 128,
minFreq: 60.0,
maxFreq: 3000.0,
decimation: 1
)
let warmUpBlocks: Int = (512 / engine.blockSize) + 10
let (freqs, _) = collect2ch(tracker, engine: engine, blocks: warmUpBlocks)
let tail: [Double] = Array(freqs.suffix(engine.blockSize * 5))
let nonZero: [Double] = tail.filter { $0 > 0 }
#expect(!nonZero.isEmpty, "decimation: 1 must still track A440 (regression guard)")
if !nonZero.isEmpty {
let avgFreq: Double = nonZero.reduce(0.0, +) / Double(nonZero.count)
#expect(avgFreq > 420.0 && avgFreq < 460.0)
}
}
}
// MARK: - LookAheadLimiter Tests
@@ -0,0 +1,39 @@
// DbAmpTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("DbAmp")
struct DbAmpTests {
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
var graph: SynthGraph { makeSynthGraph(engine: engine) }
init() throws { try engine.start() }
@Test func zeroDbReachesUnityGain() {
let s: [[Double]] = DbAmp.Control(ConstantAudioGen(0.0)).calculatedSamples(graph: graph, count: 8)
#expect(abs(s[0][7] - 1.0) < 1e-10)
}
@Test func minusTwentyDbReachesOneTenth() {
let s: [[Double]] = DbAmp.Control(ConstantAudioGen(-20.0)).calculatedSamples(graph: graph, count: 8)
#expect(abs(s[0][7] - 0.1) < 1e-9)
}
@Test func mulAddAppliedAfterConversion() {
let mulValue: Double = 2.0
let addValue: Double = 0.5
let s: [[Double]] = DbAmp.Control(
ConstantAudioGen(0.0),
mul: mulValue,
add: addValue
).calculatedSamples(graph: graph, count: 8)
#expect(abs(s[0][7] - (1.0 * mulValue + addValue)) < 1e-10)
}
}
@@ -151,6 +151,40 @@ struct LyrebirdBufferTests {
#expect(!buffer.isValid)
}
// MARK: - loopLength
@Test("loopLength defaults to count")
func testLoopLengthDefaultsToCount() {
let bufferSize: Int = 64
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: bufferSize)
#expect(buffer.loopLength == bufferSize)
}
@Test("setLoopLength narrows loopLength")
func testSetLoopLengthNarrows() {
let bufferSize: Int = 64
let narrowed: Int = 20
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: bufferSize)
buffer.setLoopLength(narrowed)
#expect(buffer.loopLength == narrowed)
#expect(buffer.count == bufferSize)
}
@Test("setLoopLength clamps to [1, count]")
func testSetLoopLengthClamps() {
let bufferSize: Int = 32
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: bufferSize)
buffer.setLoopLength(0)
#expect(buffer.loopLength == 1)
buffer.setLoopLength(-10)
#expect(buffer.loopLength == 1)
buffer.setLoopLength(bufferSize + 100)
#expect(buffer.loopLength == bufferSize)
}
// MARK: - Shared tables
@Test("SharedTables sineTable is valid and sized correctly")
@@ -0,0 +1,169 @@
---
name: lyrebird_external_review
description: Run a Lyrebird RT-safety and protocol-correctness review on an out-of-tree Swift package that depends on Lyrebird — custom Generators, Synthesizers, pedals, effects, or any code that runs on the audio render thread. Use this in projects that import Lyrebird but live OUTSIDE the Lyrebird repo (e.g. ShoeGaze, third-party extension packages). Invokes lyrebird_review_agent against the project's diff and the vendored Lyrebird checkout. Do not use inside the Lyrebird repo itself — use lyrebird_review there.
---
# Lyrebird External Review
Run a strict Lyrebird review of changes in an **out-of-tree** Swift package that depends on
the `Lyrebird` core module. This is the sibling of `lyrebird_review`, adapted for projects
that live outside the Lyrebird repository — they have no `main`-branch phase workflow, no
`docs/00-working-order.md`, and no agent/skill mirror to keep in sync, but they DO build
`Generator` / `Synthesizer` implementations that run on the real-time audio thread and must
obey the same hard constraints.
This review enforces the constraints that survive the repo boundary:
- No allocation, deallocation, locking, blocking, `print`, `String` construction, or
`is` / `as?` runtime type checks on the RT render thread
- No force unwraps (`!`, `try!`) in render-path code
- Correct `Generator` / `Synthesizer` / `GeneratorBase` protocol conformance
- Pre-allocated, never-resized buffers; `_checkCount(count)` as the first line of every
`_computeSamples`; no grow path
- Proper use of Lyrebird's shared RT-safe helpers instead of re-inlined boilerplate
- Input classification (generator vs scalar) at `init`, never on the RT thread
- Test coverage for every new public `Generator` (a deterministic input→output assertion,
not only an integration "not silent" check)
It deliberately does **not** enforce Lyrebird-internal repo conventions that cannot apply to
an external package: the `Sources/Lyrebird/` subfolder taxonomy, phase-history / working-order
docs, the agent/skill mirror sync, or Lyrebird's exact SPDX header text. Those are flagged (if
at all) as nits against the *project's own* conventions, never as blockers.
## Step 0: Confirm context and locate the Lyrebird reference checkout
This skill is for a package that **imports** Lyrebird, not the Lyrebird repo. Sanity-check:
```bash
# Should find a Lyrebird dependency, NOT be the Lyrebird package itself.
grep -RInE 'Lyrebird' Package.swift 2>/dev/null | head
test -f Package.swift && ! grep -qE 'name:\s*"Lyrebird"\s*,' Package.swift && echo "OK: external package" || echo "WARNING: looks like the Lyrebird repo — use lyrebird_review instead"
```
The architecture agent compares against canonical Lyrebird source. For SwiftPM projects this is
resolved under `.build/checkouts/Lyrebird/Sources/Lyrebird/`. Make sure it exists:
```bash
LYREBIRD_REF="$(pwd)/.build/checkouts/Lyrebird/Sources/Lyrebird"
if [ ! -d "$LYREBIRD_REF" ]; then
echo "Reference checkout missing — running 'swift build' to resolve dependencies..."
swift build >/dev/null 2>&1 || true
fi
test -d "$LYREBIRD_REF" && echo "Reference: $LYREBIRD_REF" || echo "No vendored Lyrebird checkout found — agent will review without canonical comparison."
```
If the project vendors Lyrebird differently (git submodule, sibling path, Xcode workspace),
ask the user for the path to the Lyrebird `Sources/Lyrebird` directory and pass that as the
reference instead.
## Step 1: Build the review diff
External repos do not follow Lyrebird's `main...` branch model — changes may be uncommitted,
untracked, or on an arbitrary branch. Capture everything under review.
- **If the user names a base ref** (branch, tag, commit), diff against it:
```bash
git diff --no-color <base> > review.diff
```
- **Otherwise** (default — review all local changes, committed-or-not, including new files):
```bash
# Intent-add untracked files so they appear in the diff as additions.
git add -N $(git ls-files --others --exclude-standard) 2>/dev/null || true
git diff --no-color HEAD > review.diff 2>/dev/null || git diff --no-color > review.diff
git reset -q 2>/dev/null || true # undo the intent-to-add; leaves working tree untouched
wc -l review.diff
```
If `review.diff` is empty, stop and report that there is nothing to review (the changes may
already be committed and merged — ask the user for a base ref to diff against).
## Step 2: Run the tests
Use the project's own test command. For a SwiftPM package that is `swift test`. If the suite
exercises multi-engine or multi-core paths it can hit Lyrebird's known parallel-teardown flake
(`_ContiguousArrayStorage retain count`) — add `--no-parallel` in that case.
```bash
swift test 2>&1 # or: swift test --no-parallel 2>&1
```
If tests fail, report the failures and stop — do not proceed to review until the suite is green.
## Step 3: Run reviews in parallel
Launch **both agents in a single message** (two Agent tool calls).
### Agent A — Lyrebird RT-safety / protocol review (`lyrebird_review_agent`)
Pass the diff path and the reference checkout path. Use a prompt of this shape (fill in the
real paths and branch name):
```
Working directory: <project root>. This is an OUT-OF-TREE Swift package that depends on the
Lyrebird core module — it is NOT the Lyrebird repository. The diff under review is at
<project root>/review.diff. Canonical Lyrebird source for comparison is at
<LYREBIRD_REF> (e.g. .build/checkouts/Lyrebird/Sources/Lyrebird) — read from it to verify
protocol shapes, helper signatures, and to compare new Generators against close analogs
(e.g. Generators/Analysis/ZeroCrossing.swift).
Read the FULL content of every changed file, not only the diff hunks. Review both changed and
unchanged portions of those files.
APPLY (blocking): RT thread safety in any _computeSamples / render path (no allocation, locks,
blocking, print, String construction, is/as? checks; no force unwraps; _checkCount first;
pre-allocated never-resized buffers; no grow path); input classification at init; correct
Generator/Synthesizer/GeneratorBase conformance and outputChannelCount; proper use of Lyrebird
shared RT-safe helpers instead of re-inlined boilerplate; bus memory rules; scheduling model
compliance; a deterministic input→output unit test for every new public Generator.
DO NOT flag as blocking (these are Lyrebird-internal repo rules that cannot apply to an
external package): the Sources/Lyrebird/ subfolder taxonomy, phase-history or working-order
docs, agent/skill mirror sync, or Lyrebird's exact SPDX header string. Header/file-org/style
conventions are the PROJECT's to set — mention deviations only as nits.
Generate a summary titled "Lyrebird External Review Results for '<project name>'".
```
### Agent B — Caveman line-level sweep (`general-purpose` agent)
```
You are doing a fast, terse code review of Swift changes in a package that depends on the
Lyrebird audio framework. Read the diff at <project root>/review.diff (or run
`git diff --no-color HEAD`). Pay special attention to any code that runs on the RT render
thread (_computeSamples, render callbacks).
Review every changed line. One line of output per finding. Format exactly:
L<line>: <severity> <problem>. <fix>.
Severity levels: bug, risk, nit, q
- bug = definite defect, wrong output, crash risk
- risk = potential issue under specific conditions
- nit = style, naming, minor clarity
- q = question / needs clarification
Skip praise. Skip obvious. Skip anything already correct.
If all changes look good, output exactly: LGTM
```
## Step 4: Present results
Two sections:
**Section 1 — Lyrebird External Review Results** — Agent A's summary, unmodified.
**Section 2 — Caveman Line Sweep** — Agent B's findings. If Agent B returned "LGTM", say so in
one line.
## Step 5: Resolve and re-run
If there are blocking findings, fix them and re-run this skill from Step 1 until the review is
clean. There is **no** memory-file or phase-doc bookkeeping for external packages — once the
review passes with no blocking findings, report the clean result and (optionally) suggest the
project record the change in its own CHANGELOG or release notes.
## Cleanup
Remove the temporary diff when done:
```bash
rm -f review.diff
```
+41
View File
@@ -131,6 +131,47 @@ Lyrebird 1.x:
them (`"atk.azimuth"`, not `"azimuth"`) to avoid collisions in user code that mixes
multiple extension packages.
## Reviewing your extension package — `lyrebird_external_review`
Out-of-tree packages run their custom `Generator` / `Synthesizer` code on the same real-time
audio thread as the core, under the same hard constraints (no allocation, locks, force unwraps,
or runtime type checks in `_computeSamples`; `_checkCount` first; pre-allocated, never-resized
buffers; input classification at `init`). The Lyrebird-internal `lyrebird_review` skill assumes
the Lyrebird repo's branch-and-phase workflow and `docs/00-working-order.md`, so it is the wrong
tool for an external package.
For that case there is a dedicated skill: **`lyrebird_external_review`**. It applies the same
RT-safety and protocol-correctness checks, but adapted for a package that merely *depends on*
Lyrebird:
- Builds a review diff from local changes (committed or not, including new untracked files),
or against a base ref you name — no `main`-branch assumption.
- Locates the vendored Lyrebird source (`.build/checkouts/Lyrebird/Sources/Lyrebird/`) and points
the reviewer at it, so new generators are compared against canonical analogs (e.g.
`ZeroCrossing`) and helper signatures are verified against the real API.
- Runs the project's own test suite (`swift test`, `--no-parallel` if multi-engine flakes appear).
- Invokes `lyrebird_review_agent` (RT safety, protocol conformance, shared-helper usage, unit-test
coverage for new generators) plus a terse line-level sweep, in parallel.
- Skips all Lyrebird-internal bookkeeping (phase history, working-order docs, the
`Sources/Lyrebird/` subfolder taxonomy, agent/skill mirror sync) and treats file-organisation
and header conventions as the *project's* to set — flagged as nits, never blockers.
**Usage** — from the root of the dependent package (e.g. a `ShoeGaze` checkout or any
`Lyrebird<Vendor>` extension repo):
```
/lyrebird_external_review
```
Optionally pass a base ref to scope the diff (`/lyrebird_external_review v0.3.0`). Fix any
blocking findings and re-run until clean.
The skill ships with Lyrebird at `claude/skills/lyrebird_external_review/` (installer source,
copied into a consuming project by `claude/install.sh`) and is mirrored at
`.claude/skills/lyrebird_external_review/` for auto-discovery when working inside this repo.
Install it into your extension package so contributors get the same pre-merge RT review you get
in-tree.
## See also
- [Writing Generators](writing-generators.md) — full generator-author guide.
+17
View File
@@ -184,6 +184,23 @@ In the UI, "Save Version" snapshots the live board, the Versions menu loads one
---
## Sharing — the `.shoegaze` document type
Exporting and sharing use a single registered document type: **`.shoegaze`** (UTType `net.realizedsound.shoegaze`, conforming to `public.json`, so the file stays text-readable). The two builder apps (macOS `ShoeGazeBuilder`, iPad `ShoeGazeBuilderiOS`) declare it (`CFBundleDocumentTypes` + `UTExportedTypeDeclarations`) and implement opening (`application(_:open:)` / `.onOpenURL` → import into the library), so the system associates `.shoegaze` files with them for Open and Share. The minimal player demos do not claim the type — they have no library or share UI.
- `ShoeGazeDocument` (in `LyrebirdShoeGaze`) is a versioned envelope around one of two payloads: `.rigs(RigArchive)` (one or many rigs — a single shared rig is a one-rig archive) or `.board(BoardVersion)` (a single board). `data()` encodes pretty-printed JSON; `ShoeGazeDocument.decoded(from:)` reads it back and also accepts the two legacy shapes (a bare `RigArchive`, a bare `ShoeGazeState`).
- `RigLibraryStore.exportDocumentData()` writes the whole library as a `.shoegaze` document; `importArchive(from:)` accepts `.shoegaze`, bare `RigArchive`, and legacy single-rig JSON (internal per-rig library files stay plain `.json`).
- The rig-library sidebar (`Share…` per rig) and the board editor's Versions menu (`Share…` per version) present the OS share sheet via SwiftUI `ShareLink`, backed by the `Transferable` wrappers `RigShareItem` / `BoardShareItem` (in `LyrebirdShoeGazeUI`). No backend — share targets are AirDrop, Mail, Messages, and Files.
```swift
// Export the library to a .shoegaze file:
let data = try library.exportDocumentData()
// Import a received .shoegaze (or legacy) file:
let added = try library.importArchive(from: receivedData)
```
---
## Demo apps
The package ships two in-repo demo apps in the workspace — a macOS app and an iOS app.