// 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-.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-.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. private 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 } } }