Files
ShoeGaze/Sources/LyrebirdShoeGaze/Recording/ShoeGaze+Recording.swift
T
josh 947dfe427a Add looper pedal: beat-quantized transport, undo, reverse, timeline
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>
2026-07-03 09:22:20 -07:00

197 lines
8.8 KiB
Swift

// ShoeGaze+Recording.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LyrebirdSynth
// MARK: - Recording constants
/// Preferred number of interleaved output channels captured by the output record tap.
/// Clamped to `engine.numOutputChannels` at recording time so a mono engine never reads
/// an input bus as if it were a second output channel.
private let recordingOutputChannelCount: Int = 2
/// Number of channels captured by the input record tap (always mono — hardware input is mono).
private let recordingInputChannelCount: Int = 1
/// `DateFormatter` format string used to build timestamped file names.
private let recordingTimestampFormat: String = "yyyyMMdd-HHmmss"
/// POSIX locale used for the timestamp `DateFormatter` so the filename always uses the
/// Gregorian calendar regardless of the user's system locale.
private let posixLocaleIdentifier: String = "en_US_POSIX"
// MARK: - ShoeGaze + Recording
extension ShoeGaze {
// MARK: - Start
/// Starts recording the overall output and (when possible) the raw input to timestamped
/// WAV files in ``recordingFolder``.
///
/// Two files are written:
/// - `output-<timestamp>.wav` — the final mix read from hardware output buses starting at 0.
/// The channel count is `min(2, engine.numOutputChannels)` so a mono-output engine records
/// only one channel (bus 0) instead of accidentally reading bus 1 (which is the first input
/// bus on a mono-output configuration).
/// - `input-<timestamp>.wav` — the raw mono input signal. For `.liveInput(channel:)` this is
/// the hardware input bus; for `.testLoop` this is the head bus of the first board. If no
/// board exists when using `.testLoop`, only the output file is created and a note is printed.
/// If `.liveInput(channel:)` specifies an out-of-range channel, only the output file is
/// created and a note is printed.
///
/// Both taps are inserted `.after(engine.mainGroup)` so they evaluate after every board and
/// master synth, guaranteeing they read final bus values for each block.
///
/// If a tap's output file cannot be opened (e.g. disk full or permissions error), any taps
/// that were already added to the engine are removed, and
/// `ShoeGazeError.recordTapFailedToOpen` is thrown. `isRecording` remains `false`.
///
/// - Throws:
/// - `ShoeGazeError.recordingFolderNotSet` if ``recordingFolder`` is `nil`.
/// - Any error thrown by `FileManager.createDirectory` if the folder cannot be created.
/// - `EngineAddError` if the engine rejects a tap insertion.
/// - `ShoeGazeError.recordTapFailedToOpen` if a `DiskOut.Audio` could not open its file.
public func startRecording() throws {
guard let folder: URL = recordingFolder else {
throw ShoeGazeError.recordingFolderNotSet
}
guard !isRecording else { return }
// Ensure the destination folder exists.
try FileManager.default.createDirectory(
at: folder,
withIntermediateDirectories: true,
attributes: nil
)
// Build a timestamp string using POSIX locale so the Gregorian calendar is always
// used, regardless of the user's system locale or calendar setting.
let formatter: DateFormatter = DateFormatter()
formatter.dateFormat = recordingTimestampFormat
formatter.locale = Locale(identifier: posixLocaleIdentifier)
let timestamp: String = formatter.string(from: Date())
// Clamp the output channel count to the engine's actual output channel count so we
// never read bus index 1 on a mono-output engine (bus 1 would be the first input bus).
let outChannels: Int = min(recordingOutputChannelCount, engine.numOutputChannels)
guard outChannels >= 1 else {
// Engine has no output channels — nothing to record.
print("[ShoeGaze] startRecording: engine has no output channels — skipping output tap.")
return
}
// --- Output tap ---
let outputFileURL: URL = folder
.appendingPathComponent("output-\(timestamp).wav")
let outputTap: RecordTap = RecordTap(
firstBusIndex: 0,
channelCount: outChannels,
fileURL: outputFileURL,
sampleRate: engine.sampleRate
)
try engine.add(outputTap, position: .after(engine.mainGroup))
// Guard that DiskOut actually opened — build() prints the error; we surface it here.
guard outputTap.diskOut != nil else {
engine.remove(outputTap)
throw ShoeGazeError.recordTapFailedToOpen(outputFileURL)
}
recordTaps.append(outputTap)
// --- Input tap (mono) ---
let inputBusIndex: Int? = resolvedInputBusIndex()
if let busIndex: Int = inputBusIndex {
let inputFileURL: URL = folder
.appendingPathComponent("input-\(timestamp).wav")
let inputTap: RecordTap = RecordTap(
firstBusIndex: busIndex,
channelCount: recordingInputChannelCount,
fileURL: inputFileURL,
sampleRate: engine.sampleRate
)
do {
try engine.add(inputTap, position: .after(engine.mainGroup))
} catch {
// The output tap was already added — remove it before propagating.
engine.remove(outputTap)
outputTap.diskOut?.close()
recordTaps.removeAll()
throw error
}
guard inputTap.diskOut != nil else {
// Input file could not be opened — roll back both taps cleanly.
engine.remove(inputTap)
engine.remove(outputTap)
outputTap.diskOut?.close()
recordTaps.removeAll()
throw ShoeGazeError.recordTapFailedToOpen(inputFileURL)
}
recordTaps.append(inputTap)
}
isRecording = true
}
// MARK: - Stop
/// Stops an active recording, flushes all buffered frames to disk, and closes the output files.
///
/// Each tap is removed from the engine then `DiskOut.close()` is called synchronously to
/// flush any remaining buffered frames and dispose the file handle.
///
/// > Important: `engine.remove(_:)` is asynchronous — it enqueues the removal for the next
/// > render block. When the engine is still running, the RT thread may render one or two
/// > additional blocks after `stopRecording()` returns; those frames are written to the
/// > `DiskOut` ring buffer but the ring buffer drainer may not flush them before `close()`
/// > is called, resulting in a bounded tail truncation of those final blocks. This is not
/// > file corruption — the WAV header length is written on `close()`. For a sample-accurate
/// > tail with no truncation, stop the engine (`engine.stop()`) before calling
/// > `stopRecording()`, then close.
///
/// No-op if `isRecording` is `false`.
public func stopRecording() {
guard isRecording else { return }
for tap: RecordTap in recordTaps {
engine.remove(tap)
tap.diskOut?.close()
}
recordTaps.removeAll()
isRecording = false
}
// MARK: - Private helpers
/// Resolves the audio bus index of the raw input signal based on the current `inputSource`.
///
/// - `.liveInput(channel:)` → validated via `liveInputBusIndex(channel:engine:)`. Returns
/// `nil` (with a printed note) if the channel is out of range rather than recording an
/// incorrect bus; the output track is still written.
/// - `.testLoop` → `boards.first?.headBus.index` (the first board's head bus). Returns `nil`
/// if there are no boards; the input track is skipped and a note is printed.
/// Exposed `internal` (not `private`) so other rig-level features that need the clean
/// pre-effects input signal — e.g. `ShoeGaze+Tuner.swift` — can reuse this resolution
/// instead of duplicating the `.liveInput`/`.testLoop` switch.
internal func resolvedInputBusIndex() -> Int? {
switch inputSource {
case .liveInput(let channel):
do {
return try liveInputBusIndex(channel: channel, engine: engine)
} catch {
print("[ShoeGaze] startRecording: invalid .liveInput channel — skipping input tap. (\(error))")
return nil
}
case .testLoop:
guard let firstBoard: PedalBoard = boards.first else {
print("[ShoeGaze] startRecording: no boards available for .testLoop input tap — recording output only.")
return nil
}
return firstBoard.headBus.index
}
}
}