947dfe427a
Extend the looper into a double-width tempo-aware pedal: - Beat-quantized transport: record start and loop close both snap to the next beat via a LyrebirdRoutine waiting on the shared clock; loop length is an exact whole-beat span. Falls back to immediate/unquantized when no clock is present. - Loop-length read-outs (frames/seconds/beats), transport state, and a sample-clock-derived play-head position for the UI timeline. - Overdub undo (pre-dub snapshot + restore), reverse playback (live rate flip), and feedback-decay overdub (overdub preLevel via a Feedback knob). - Inject the shared LyrebirdClock + SynthesisEngine into Pedal via PedalBoard/ChainRouter so tempo-aware pedals can reach them. - New double-width LooperTimelineView (state badge, length read-out, sweeping play-head) wired into PedalView via Pedal.widthUnits. Concurrency hardening from RT-safety review: a transportGeneration counter drops superseded deferred beat/undo callbacks that LyrebirdRoutine.stop() cannot recall once enqueued; the undo restore is deferred past the RT overdub gate-close; transport routines use non-blocking stop(). Note: this commit also snapshots pre-existing uncommitted work-in-progress already in the tree (MIDI control refactor, Tuner, Tempo, preset changes), which is interleaved with the looper changes through shared files and could not be split into a separately-building commit. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
144 lines
5.0 KiB
Swift
144 lines
5.0 KiB
Swift
// OfflineRender.swift
|
|
// Lyrebird
|
|
//
|
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
import Foundation
|
|
import AudioToolbox
|
|
import LyrebirdSynth
|
|
import LyrebirdUI
|
|
|
|
// MARK: - NRT engine factory
|
|
|
|
/// Creates an `NRTDriver`-backed `SynthesisEngine` and renders to a temporary CAF file.
|
|
///
|
|
/// - Parameters:
|
|
/// - duration: Render duration in seconds.
|
|
/// - blockSize: Audio block size. Defaults to 512.
|
|
/// - sampleRate: Engine sample rate. Defaults to 44100.
|
|
/// - numOutputChannels: Hardware output channel count. Defaults to 2.
|
|
/// - numInputChannels: Hardware input channel count. Defaults to 0.
|
|
/// - numAudioBuses: Total audio bus pool size. Defaults to 64.
|
|
/// - Returns: `(engine, outputURL)` — caller must delete `outputURL` when done.
|
|
@MainActor
|
|
func makeNRTEngine(
|
|
duration: Double,
|
|
blockSize: Int = 512,
|
|
sampleRate: Double = 44100.0,
|
|
numOutputChannels: Int = 2,
|
|
numInputChannels: Int = 0,
|
|
numAudioBuses: Int = 64
|
|
) -> (SynthesisEngine, URL) {
|
|
/// Number of control buses to allocate in the test engine.
|
|
let numControlBuses: Int = 512
|
|
let url: URL = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent(UUID().uuidString + ".caf")
|
|
let driver: NRTDriver = NRTDriver(outputURL: url, duration: duration)
|
|
let engine: SynthesisEngine = SynthesisEngine(
|
|
blockSize: blockSize,
|
|
sampleRate: sampleRate,
|
|
numOutputChannels: numOutputChannels,
|
|
numInputChannels: numInputChannels,
|
|
numAudioBuses: numAudioBuses,
|
|
numControlBuses: numControlBuses,
|
|
driver: driver
|
|
)
|
|
return (engine, url)
|
|
}
|
|
|
|
// MARK: - CAF reader
|
|
|
|
/// Reads all interleaved Float32 samples from a stereo CAF file written by NRTDriver.
|
|
///
|
|
/// - Parameters:
|
|
/// - url: Path of the CAF file.
|
|
/// - sampleRate: Sample rate of the file.
|
|
/// - Returns: Interleaved stereo samples, or an empty array on error.
|
|
func readStereoCAF(url: URL, sampleRate: Double = 44100.0) -> [Float] {
|
|
let stereoChannelCount: UInt32 = 2
|
|
let bytesPerSample: UInt32 = 4
|
|
let bitsPerSample: UInt32 = 32
|
|
let bytesPerFrame: UInt32 = stereoChannelCount * bytesPerSample
|
|
|
|
var fileRef: ExtAudioFileRef?
|
|
guard ExtAudioFileOpenURL(url as CFURL, &fileRef) == noErr,
|
|
let fileRef: ExtAudioFileRef else { return [] }
|
|
defer { ExtAudioFileDispose(fileRef) }
|
|
|
|
var clientFormat: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
|
mSampleRate: sampleRate,
|
|
mFormatID: kAudioFormatLinearPCM,
|
|
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
|
mBytesPerPacket: bytesPerFrame,
|
|
mFramesPerPacket: 1,
|
|
mBytesPerFrame: bytesPerFrame,
|
|
mChannelsPerFrame: stereoChannelCount,
|
|
mBitsPerChannel: bitsPerSample,
|
|
mReserved: 0
|
|
)
|
|
guard ExtAudioFileSetProperty(
|
|
fileRef,
|
|
kExtAudioFileProperty_ClientDataFormat,
|
|
UInt32(MemoryLayout<AudioStreamBasicDescription>.size),
|
|
&clientFormat
|
|
) == noErr else { return [] }
|
|
|
|
// Read the whole file in fixed-size chunks — a single `ExtAudioFileRead` call only
|
|
// fills one chunk's worth of frames, so anything past `chunkFrames` would otherwise be
|
|
// silently dropped for renders longer than one chunk.
|
|
let chunkFrames: UInt32 = 4096
|
|
var chunk: [Float] = [Float](repeating: 0, count: Int(chunkFrames) * 2)
|
|
var allSamples: [Float] = []
|
|
while true {
|
|
var framesRead: UInt32 = chunkFrames
|
|
chunk.withUnsafeMutableBufferPointer { ptr in
|
|
var bufList: AudioBufferList = AudioBufferList(
|
|
mNumberBuffers: 1,
|
|
mBuffers: AudioBuffer(
|
|
mNumberChannels: 2,
|
|
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
|
|
mData: ptr.baseAddress
|
|
)
|
|
)
|
|
_ = ExtAudioFileRead(fileRef, &framesRead, &bufList)
|
|
}
|
|
guard framesRead > 0 else { break }
|
|
allSamples.append(contentsOf: chunk.prefix(Int(framesRead) * 2))
|
|
if framesRead < chunkFrames { break }
|
|
}
|
|
return allSamples
|
|
}
|
|
|
|
// MARK: - Signal analysis
|
|
|
|
/// Returns `true` if any sample in `samples` has absolute value greater than `threshold`.
|
|
func hasNonSilentOutput(_ samples: [Float], threshold: Float = 1e-6) -> Bool {
|
|
samples.contains { abs($0) > threshold }
|
|
}
|
|
|
|
// MARK: - TestRouteMaster
|
|
|
|
/// A minimal `SynthesizerBase` that reads a mono bus and routes it to hardware stereo output.
|
|
/// Used only in tests — not part of the public ShoeGaze API.
|
|
final class TestRouteMaster: SynthesizerBase {
|
|
|
|
private let inputBusIndex: Int
|
|
|
|
/// Gain applied before panning to hardware output.
|
|
private let outputGain: Double = 0.8
|
|
|
|
/// Stereo pan position (0 = centre).
|
|
private let pan: Double = 0.0
|
|
|
|
init(inputBusIndex: Int) {
|
|
self.inputBusIndex = inputBusIndex
|
|
super.init()
|
|
}
|
|
|
|
override func build() {
|
|
let sig: In.Audio = input(bus: inputBusIndex)
|
|
output(bus: 0, source: Pan2(input: sig * outputGain, pan: pan))
|
|
}
|
|
}
|