From 947dfe427a24d398e130cd404d09e18518acfb83 Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Fri, 3 Jul 2026 09:22:20 -0700 Subject: [PATCH] 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 --- .../ShoeGazeBuilder.xcodeproj/project.pbxproj | 8 +- Package.resolved | 6 +- Package.swift | 3 +- .../xcshareddata/swiftpm/Package.resolved | 6 +- .../LyrebirdShoeGaze/MIDI/LegacyMIDIMap.swift | 153 ++++++ .../MIDI/MIDIController.swift | 113 ++-- Sources/LyrebirdShoeGaze/MIDI/MIDIMap.swift | 51 +- Sources/LyrebirdShoeGaze/Pedal.swift | 35 ++ Sources/LyrebirdShoeGaze/PedalBoard.swift | 18 +- Sources/LyrebirdShoeGaze/PedalButton.swift | 70 +++ Sources/LyrebirdShoeGaze/PedalType.swift | 3 + .../LyrebirdShoeGaze/Pedals/LooperPedal.swift | 512 ++++++++++++++++++ .../Pedals/LooperTransportState.swift | 30 + .../LyrebirdShoeGaze/Presets/BoardState.swift | 14 + .../Presets/Pedal+Preset.swift | 4 + .../Presets/PedalBoard+Preset.swift | 2 +- .../Presets/PedalRegistry.swift | 1 + .../LyrebirdShoeGaze/Presets/PedalState.swift | 12 + .../LyrebirdShoeGaze/Presets/RigStore.swift | 12 +- .../Presets/ShoeGaze+Preset.swift | 6 + .../Presets/ShoeGazeState.swift | 25 +- .../Recording/ShoeGaze+Recording.swift | 5 +- .../Routing/ChainRouter.swift | 11 +- Sources/LyrebirdShoeGaze/ShoeGaze.swift | 42 +- .../Tempo/ShoeGaze+Tempo.swift | 55 ++ .../Tuner/ShoeGaze+Tuner.swift | 99 ++++ .../Tuner/TunerPitchCapture.swift | 103 ++++ Sources/LyrebirdShoeGaze/Tuner/TunerTap.swift | 60 ++ .../LooperTimelineView.swift | 144 +++++ .../LyrebirdShoeGazeUI/MIDIMappingSheet.swift | 42 +- .../LyrebirdShoeGazeUI/PedalButtonView.swift | 57 ++ Sources/LyrebirdShoeGazeUI/PedalView.swift | 63 ++- .../ShoeGazeBuilderView.swift | 42 +- Sources/LyrebirdShoeGazeUI/TempoView.swift | 107 ++++ Sources/LyrebirdShoeGazeUI/TunerView.swift | 210 +++++++ .../LooperPedalTests.swift | 492 +++++++++++++++++ .../MIDIControllerCCTests.swift | 44 +- .../MIDIControllerPCTests.swift | 73 ++- .../MIDIMapCodableTests.swift | 18 +- .../MIDIMapMigrationTests.swift | 108 ++++ .../MIDIMapReindexTests.swift | 148 +++++ .../LyrebirdShoeGazeTests/RigStoreTests.swift | 48 +- .../Support/OfflineRender.swift | 35 +- Tests/LyrebirdShoeGazeTests/TempoTests.swift | 83 +++ .../TunerPitchReadingTests.swift | 52 ++ .../LyrebirdShoeGazeTests/TunerTapTests.swift | 91 ++++ Tests/LyrebirdShoeGazeTests/TunerTests.swift | 123 +++++ 47 files changed, 3263 insertions(+), 176 deletions(-) create mode 100644 Sources/LyrebirdShoeGaze/MIDI/LegacyMIDIMap.swift create mode 100644 Sources/LyrebirdShoeGaze/PedalButton.swift create mode 100644 Sources/LyrebirdShoeGaze/Pedals/LooperPedal.swift create mode 100644 Sources/LyrebirdShoeGaze/Pedals/LooperTransportState.swift create mode 100644 Sources/LyrebirdShoeGaze/Tempo/ShoeGaze+Tempo.swift create mode 100644 Sources/LyrebirdShoeGaze/Tuner/ShoeGaze+Tuner.swift create mode 100644 Sources/LyrebirdShoeGaze/Tuner/TunerPitchCapture.swift create mode 100644 Sources/LyrebirdShoeGaze/Tuner/TunerTap.swift create mode 100644 Sources/LyrebirdShoeGazeUI/LooperTimelineView.swift create mode 100644 Sources/LyrebirdShoeGazeUI/PedalButtonView.swift create mode 100644 Sources/LyrebirdShoeGazeUI/TempoView.swift create mode 100644 Sources/LyrebirdShoeGazeUI/TunerView.swift create mode 100644 Tests/LyrebirdShoeGazeTests/LooperPedalTests.swift create mode 100644 Tests/LyrebirdShoeGazeTests/MIDIMapMigrationTests.swift create mode 100644 Tests/LyrebirdShoeGazeTests/MIDIMapReindexTests.swift create mode 100644 Tests/LyrebirdShoeGazeTests/TempoTests.swift create mode 100644 Tests/LyrebirdShoeGazeTests/TunerPitchReadingTests.swift create mode 100644 Tests/LyrebirdShoeGazeTests/TunerTapTests.swift create mode 100644 Tests/LyrebirdShoeGazeTests/TunerTests.swift diff --git a/Demo/ShoeGazeBuilder.xcodeproj/project.pbxproj b/Demo/ShoeGazeBuilder.xcodeproj/project.pbxproj index c56d5eb..0ce7bf4 100644 --- a/Demo/ShoeGazeBuilder.xcodeproj/project.pbxproj +++ b/Demo/ShoeGazeBuilder.xcodeproj/project.pbxproj @@ -163,7 +163,7 @@ "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development"; CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; - CURRENT_PROJECT_VERSION = 5; + CURRENT_PROJECT_VERSION = 6; DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = dwarf; DEVELOPMENT_TEAM = HE5VJFE9E4; @@ -176,7 +176,7 @@ "@executable_path/../Frameworks", ); MACOSX_DEPLOYMENT_TARGET = 15.0; - MARKETING_VERSION = 1.3.0; + MARKETING_VERSION = 1.4.0; PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_EMIT_LOC_STRINGS = YES; @@ -194,7 +194,7 @@ "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development"; CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; - CURRENT_PROJECT_VERSION = 5; + CURRENT_PROJECT_VERSION = 6; DEAD_CODE_STRIPPING = YES; DEVELOPMENT_TEAM = HE5VJFE9E4; ENABLE_HARDENED_RUNTIME = YES; @@ -206,7 +206,7 @@ "@executable_path/../Frameworks", ); MACOSX_DEPLOYMENT_TARGET = 15.0; - MARKETING_VERSION = 1.3.0; + MARKETING_VERSION = 1.4.0; PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_EMIT_LOC_STRINGS = YES; diff --git a/Package.resolved b/Package.resolved index 5c0cd3b..bfbe151 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,5 +1,5 @@ { - "originHash" : "b8327204b102b429067129b94b6ba77dcfa78570af3b9d11cae4d7eb252e388c", + "originHash" : "6f168dc2e522f9d35bb2fafd7dab3cd399acd820084d324db174cf1ef0c6c4fa", "pins" : [ { "identity" : "linenoise-swift", @@ -15,8 +15,8 @@ "kind" : "remoteSourceControl", "location" : "https://realizedsound.mooo.com/josh/Lyrebird", "state" : { - "revision" : "032b7c39d351eba4029e8399e1ab1ee201e8bb5c", - "version" : "1.2.0" + "revision" : "8a2eb191a204a76735ba7eeac94e18f2e65f1b23", + "version" : "1.2.2" } }, { diff --git a/Package.swift b/Package.swift index 0f743b5..322b6d2 100644 --- a/Package.swift +++ b/Package.swift @@ -23,7 +23,7 @@ let package = Package( .library(name: "LyrebirdShoeGazeUI", targets: ["LyrebirdShoeGazeUI"]), ], dependencies: [ - .package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.2.0"), + .package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.2.2"), ], targets: [ // The core target depends on LyrebirdUI as well as the synthesis core: @@ -51,6 +51,7 @@ let package = Package( name: "LyrebirdShoeGazeTests", dependencies: [ "LyrebirdShoeGaze", + "LyrebirdShoeGazeUI", .product(name: "Lyrebird", package: "Lyrebird"), .product(name: "LyrebirdUI", package: "Lyrebird"), ], diff --git a/ShoeGaze.xcworkspace/xcshareddata/swiftpm/Package.resolved b/ShoeGaze.xcworkspace/xcshareddata/swiftpm/Package.resolved index 0c2784a..2f0800b 100644 --- a/ShoeGaze.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/ShoeGaze.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -1,5 +1,5 @@ { - "originHash" : "bf2bd285202c1d5cb51cc77815e3eb9675170cb3bef2db60c355d2222c555750", + "originHash" : "91598bde27d299c8e3d95f9dc660396f52cf9b8e78f90ff2652c9d34d869f572", "pins" : [ { "identity" : "linenoise-swift", @@ -15,8 +15,8 @@ "kind" : "remoteSourceControl", "location" : "https://realizedsound.mooo.com/josh/Lyrebird", "state" : { - "revision" : "032b7c39d351eba4029e8399e1ab1ee201e8bb5c", - "version" : "1.2.0" + "revision" : "8a2eb191a204a76735ba7eeac94e18f2e65f1b23", + "version" : "1.2.2" } }, { diff --git a/Sources/LyrebirdShoeGaze/MIDI/LegacyMIDIMap.swift b/Sources/LyrebirdShoeGaze/MIDI/LegacyMIDIMap.swift new file mode 100644 index 0000000..c60b280 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/MIDI/LegacyMIDIMap.swift @@ -0,0 +1,153 @@ +// LegacyMIDIMap.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +/// Decoder for the **pre-UUID** `MIDIMap` format, which addressed pedals and boards by chain +/// position (`boardIndex` / `pedalIndex`) rather than by stable id. +/// +/// Used only on load: `ShoeGazeState.init(from:)` tries the current id-based `MIDIMap` first and, +/// if that fails, decodes this legacy shape and calls ``migrated(boards:)`` to convert each +/// positional binding to the id of the pedal/board now sitting at that position. Because the saved +/// positions are stable, this reconstructs correct id-bindings on every load — even though the ids +/// themselves are freshly assigned to a legacy rig each time it is decoded. +/// +/// Bindings whose indices fall outside the loaded rig are dropped. +struct LegacyMIDIMap: Codable { + + var switches: [LegacySwitchBinding] + var ccs: [LegacyCCBinding] + + enum LegacyAction: Codable { + case rigBypass + case rigMute + case allBoards + case boardSolo(boardIndex: Int) + case boardAudible(boardIndex: Int) + case boardBypass(boardIndex: Int) + case pedalBypass(boardIndex: Int, pedalIndex: Int) + case pedalAction(boardIndex: Int, pedalIndex: Int, kind: MIDIMap.PedalActionKind) + case tunerToggle + case tapTempo + } + + enum LegacyCCTarget: Codable { + case pedalControl( + boardIndex: Int, + pedalIndex: Int, + controlIndex: Int, + pedalNameHint: String?, + controlLabelHint: String? + ) + case boardLevel(boardIndex: Int, boardLabelHint: String?) + case rigVolume + } + + struct LegacySwitchBinding: Codable { + var program: UInt8 + var channel: UInt8? + var action: LegacyAction + var displayNameHint: String? + } + + struct LegacyCCBinding: Codable { + var controller: UInt8 + var channel: UInt8? + var target: LegacyCCTarget + var inverted: Bool + } + + // MARK: - Migration + + /// Converts this positional map to the current id-based ``MIDIMap`` using the ids of the pedals + /// and boards in `boards` (whose ids were freshly assigned when the rig was decoded). Bindings + /// addressing an out-of-range board/pedal are dropped. + func migrated(boards: [BoardState]) -> MIDIMap { + func boardID(_ index: Int) -> UUID? { + guard index >= 0, index < boards.count else { return nil } + return boards[index].id + } + func pedalID(_ boardIndex: Int, _ pedalIndex: Int) -> UUID? { + guard boardIndex >= 0, boardIndex < boards.count else { return nil } + let pedals: [PedalState] = boards[boardIndex].pedals + guard pedalIndex >= 0, pedalIndex < pedals.count else { return nil } + return pedals[pedalIndex].id + } + + let migratedSwitches: [MIDIMap.SwitchBinding] = switches.compactMap { binding in + guard let action: MIDIMap.Action = migrate(binding.action, boardID: boardID, pedalID: pedalID) else { + return nil + } + return MIDIMap.SwitchBinding( + program: binding.program, + channel: binding.channel, + action: action, + displayNameHint: binding.displayNameHint + ) + } + + let migratedCCs: [MIDIMap.CCBinding] = ccs.compactMap { binding in + guard let target: MIDIMap.CCTarget = migrate(binding.target, boardID: boardID, pedalID: pedalID) else { + return nil + } + return MIDIMap.CCBinding( + controller: binding.controller, + channel: binding.channel, + target: target, + inverted: binding.inverted + ) + } + + return MIDIMap(switches: migratedSwitches, ccs: migratedCCs) + } + + private func migrate( + _ action: LegacyAction, + boardID: (Int) -> UUID?, + pedalID: (Int, Int) -> UUID? + ) -> MIDIMap.Action? { + switch action { + case .rigBypass: return .rigBypass + case .rigMute: return .rigMute + case .allBoards: return .allBoards + case .tunerToggle: return .tunerToggle + case .tapTempo: return .tapTempo + case .boardSolo(let b): + guard let id: UUID = boardID(b) else { return nil } + return .boardSolo(boardID: id) + case .boardAudible(let b): + guard let id: UUID = boardID(b) else { return nil } + return .boardAudible(boardID: id) + case .boardBypass(let b): + guard let id: UUID = boardID(b) else { return nil } + return .boardBypass(boardID: id) + case .pedalBypass(let b, let p): + guard let id: UUID = pedalID(b, p) else { return nil } + return .pedalBypass(pedalID: id) + case .pedalAction(let b, let p, let kind): + guard let id: UUID = pedalID(b, p) else { return nil } + return .pedalAction(pedalID: id, kind: kind) + } + } + + private func migrate( + _ target: LegacyCCTarget, + boardID: (Int) -> UUID?, + pedalID: (Int, Int) -> UUID? + ) -> MIDIMap.CCTarget? { + switch target { + case .rigVolume: + return .rigVolume + case .pedalControl(let b, let p, let controlIndex, let nameHint, let labelHint): + guard let id: UUID = pedalID(b, p) else { return nil } + return .pedalControl(pedalID: id, controlIndex: controlIndex, + pedalNameHint: nameHint, controlLabelHint: labelHint) + case .boardLevel(let b, let labelHint): + guard let id: UUID = boardID(b) else { return nil } + return .boardLevel(boardID: id, boardLabelHint: labelHint) + } + } +} diff --git a/Sources/LyrebirdShoeGaze/MIDI/MIDIController.swift b/Sources/LyrebirdShoeGaze/MIDI/MIDIController.swift index 3f8e987..47fe0e8 100644 --- a/Sources/LyrebirdShoeGaze/MIDI/MIDIController.swift +++ b/Sources/LyrebirdShoeGaze/MIDI/MIDIController.swift @@ -266,26 +266,22 @@ public final class MIDIController { /// address is out of range or a captured display-name hint no longer matches (stale binding). private func resolveCC(_ target: MIDIMap.CCTarget) -> ResolvedCC? { switch target { - case let .pedalControl(boardIndex, pedalIndex, controlIndex, nameHint, labelHint): - guard let pedal: Pedal = pedal(boardIndex: boardIndex, pedalIndex: pedalIndex) else { return nil } + case let .pedalControl(pedalID, controlIndex, _, _): + guard let pedal: Pedal = pedal(id: pedalID) else { return nil } let controls: [PedalControl] = pedal.ccMappableControls guard controlIndex >= 0, controlIndex < controls.count else { return nil } let control: PedalControl = controls[controlIndex] - if let nameHint: String = nameHint, nameHint != pedal.displayName { return nil } - if let labelHint: String = labelHint, labelHint != control.label { return nil } let hinted: MIDIMap.CCTarget = .pedalControl( - boardIndex: boardIndex, - pedalIndex: pedalIndex, + pedalID: pedalID, controlIndex: controlIndex, pedalNameHint: pedal.displayName, controlLabelHint: control.label ) return ResolvedCC(node: control.node, range: control.range, hinted: hinted) - case let .boardLevel(boardIndex, labelHint): - guard let board: PedalBoard = board(at: boardIndex), + case let .boardLevel(boardID, _): + guard let board: PedalBoard = board(id: boardID), let node: UIParamNode = board.masterGainNode else { return nil } - if let labelHint: String = labelHint, labelHint != board.label { return nil } - let hinted: MIDIMap.CCTarget = .boardLevel(boardIndex: boardIndex, boardLabelHint: board.label) + let hinted: MIDIMap.CCTarget = .boardLevel(boardID: boardID, boardLabelHint: board.label) return ResolvedCC(node: node, range: boardLevelRange, hinted: hinted) case .rigVolume: // Applied via `ShoeGaze.setRigVolume` (fans out to every board), not a single node. @@ -340,14 +336,14 @@ public final class MIDIController { guard let shoeGaze: ShoeGaze = shoeGaze, let map: MIDIMap = shoeGaze.midiMap else { return } for binding: MIDIMap.SwitchBinding in map.switches where binding.program == program { if let boundChannel: UInt8 = binding.channel, boundChannel != channel { continue } - perform(binding.action, hint: binding.displayNameHint) + perform(binding.action) } } /// Executes a toggle action by reading the live rig state and flipping it. Boolean actions latch; - /// `boardSolo` is exclusive (radio). Stale bindings (chain edited under the positional address) - /// are skipped via bounds + display-name checks. - private func perform(_ action: MIDIMap.Action, hint: String?) { + /// `boardSolo` is exclusive (radio). Pedals/boards resolve by UUID, so a binding whose target no + /// longer exists (removed pedal/board) simply no-ops. + private func perform(_ action: MIDIMap.Action) { guard let shoeGaze: ShoeGaze = shoeGaze else { return } switch action { case .rigBypass: @@ -357,58 +353,79 @@ public final class MIDIController { case .allBoards: // One-shot: cancel any solo and bring every board back up. shoeGaze.selectAllBoards(crossfadeSeconds: boardActionCrossfade) - case .boardSolo(let boardIndex): - guard let board: PedalBoard = board(at: boardIndex), matchesBoard(board, hint) else { return } + case .boardSolo(let boardID): + guard let board: PedalBoard = board(id: boardID) else { return } shoeGaze.soloBoard(board, crossfadeSeconds: boardActionCrossfade) - case .boardAudible(let boardIndex): - guard let board: PedalBoard = board(at: boardIndex), matchesBoard(board, hint) else { return } + case .boardAudible(let boardID): + guard let board: PedalBoard = board(id: boardID) else { return } shoeGaze.setBoard(board, audible: !shoeGaze.isBoardAudible(board), crossfadeSeconds: boardActionCrossfade) - case .boardBypass(let boardIndex): - guard let board: PedalBoard = board(at: boardIndex), matchesBoard(board, hint) else { return } + case .boardBypass(let boardID): + guard let board: PedalBoard = board(id: boardID) else { return } shoeGaze.setBoard(board, bypassed: !shoeGaze.isBoardBypassed(board)) - case .pedalBypass(let boardIndex, let pedalIndex): - guard let pedal: Pedal = pedal(boardIndex: boardIndex, pedalIndex: pedalIndex) else { return } - if let hint: String = hint, hint != pedal.displayName { return } + case .pedalBypass(let pedalID): + guard let pedal: Pedal = pedal(id: pedalID) else { return } let engagedThreshold: Double = 0.5 let node: UIParamNode = pedal.$bypass node.update(node.value < engagedThreshold ? 1.0 : 0.0) + case .pedalAction(let pedalID, let kind): + guard let pedal: Pedal = pedal(id: pedalID) else { return } + performPedalAction(kind, on: pedal) + case .tunerToggle: + shoeGaze.toggleTunerEngaged() + case .tapTempo: + shoeGaze.tapTempo() } } - /// A display-name hint for an action, captured at learn time for stale-binding detection. + /// Dispatches a pedal-specific momentary action. New `PedalActionKind` cases add a + /// branch here once the pedal type they target exists. + private func performPedalAction(_ kind: MIDIMap.PedalActionKind, on pedal: Pedal) { + let toggleThreshold: Double = 0.5 + switch kind { + case .looperRecordStop: + (pedal as? LooperPedal)?.toggleRecordStop() + case .looperOverdubToggle: + guard let looper: LooperPedal = pedal as? LooperPedal else { return } + let node: UIParamNode = looper.$overdubOn + node.update(node.value < toggleThreshold ? 1.0 : 0.0) + case .looperLoopToggle: + guard let looper: LooperPedal = pedal as? LooperPedal else { return } + let node: UIParamNode = looper.$loopOn + node.update(node.value < toggleThreshold ? 1.0 : 0.0) + case .looperReset: + (pedal as? LooperPedal)?.resetLoop() + } + } + + /// A display-name hint for an action, captured at learn time for the mapping-sheet UI label. + /// Not used for resolution (bindings resolve by UUID) — purely a human-readable snapshot. private func hint(for action: MIDIMap.Action) -> String? { switch action { case .rigBypass, .rigMute, .allBoards: return nil - case .boardSolo(let index), .boardAudible(let index), .boardBypass(let index): - return board(at: index)?.label - case .pedalBypass(let boardIndex, let pedalIndex): - return pedal(boardIndex: boardIndex, pedalIndex: pedalIndex)?.displayName - } - } - - /// `true` when a board still matches its captured hint (or no hint was captured). - private func matchesBoard(_ board: PedalBoard, _ hint: String?) -> Bool { - guard let hint: String = hint else { return true } - return board.label == hint - } - - /// Resolves a board by index, or `nil` if out of range. - private func board(at index: Int) -> PedalBoard? { - guard let shoeGaze: ShoeGaze = shoeGaze, index >= 0, index < shoeGaze.boards.count else { + case .boardSolo(let boardID), .boardAudible(let boardID), .boardBypass(let boardID): + return board(id: boardID)?.label + case .pedalBypass(let pedalID), .pedalAction(let pedalID, _): + return pedal(id: pedalID)?.displayName + case .tunerToggle, .tapTempo: return nil } - return shoeGaze.boards[index] } - /// Resolves a pedal by board + pedal index, or `nil` if either index is out of range. - private func pedal(boardIndex: Int, pedalIndex: Int) -> Pedal? { - guard let shoeGaze: ShoeGaze = shoeGaze, - boardIndex >= 0, boardIndex < shoeGaze.boards.count else { return nil } - let board: PedalBoard = shoeGaze.boards[boardIndex] - guard pedalIndex >= 0, pedalIndex < board.pedals.count else { return nil } - return board.pedals[pedalIndex] + /// Resolves a board by its stable id, or `nil` if no board in the rig has that id. + private func board(id: UUID) -> PedalBoard? { + shoeGaze?.boards.first { $0.id == id } + } + + /// Resolves a pedal by its stable id across all boards' linear pedal chains, or `nil` if no + /// pedal in the rig has that id. + private func pedal(id: UUID) -> Pedal? { + guard let shoeGaze: ShoeGaze = shoeGaze else { return nil } + for board: PedalBoard in shoeGaze.boards { + if let match: Pedal = board.pedals.first(where: { $0.id == id }) { return match } + } + return nil } // MARK: - Device detection diff --git a/Sources/LyrebirdShoeGaze/MIDI/MIDIMap.swift b/Sources/LyrebirdShoeGaze/MIDI/MIDIMap.swift index 74108cb..a814bc2 100644 --- a/Sources/LyrebirdShoeGaze/MIDI/MIDIMap.swift +++ b/Sources/LyrebirdShoeGaze/MIDI/MIDIMap.swift @@ -4,13 +4,18 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +import Foundation + /// A per-rig map of MIDI foot-controller bindings — which Program Change toggles which control, and /// which Control Change drives which pedal knob. /// -/// Stored inside the rig (embedded in `ShoeGazeState`) so it travels with a saved rig. Controls are -/// addressed **positionally** (board index, pedal index, knob index) since boards and pedals have no -/// stable identity; the `*Hint` fields carry the resolved display name at learn time so a binding -/// that no longer matches (chain edited) can be detected and skipped rather than mis-fire. +/// Stored inside the rig (embedded in `ShoeGazeState`) so it travels with a saved rig. Pedals and +/// boards are addressed by **stable UUID** (`Pedal.id` / `PedalBoard.id`, persisted in +/// `PedalState`/`BoardState`), so a binding follows its pedal/board through insert, remove, move, +/// and reorder edits with no reindexing — the id survives the capture → rebuild round-trip. A +/// binding whose target no longer exists simply stops resolving (inert). The `*Hint` fields carry +/// the display name at learn time, for UI labels only (not resolution). Control-within-pedal is +/// still indexed into `Pedal.ccMappableControls`, which is stable for a given pedal type. public struct MIDIMap: Codable, Equatable, Sendable { /// Program-Change → action bindings (footswitch toggles). Populated in the switch phase. @@ -45,10 +50,31 @@ public struct MIDIMap: Codable, Equatable, Sendable { case rigMute /// Cancels any solo and makes every board audible again (the "All" button). case allBoards - case boardSolo(boardIndex: Int) - case boardAudible(boardIndex: Int) - case boardBypass(boardIndex: Int) - case pedalBypass(boardIndex: Int, pedalIndex: Int) + case boardSolo(boardID: UUID) + case boardAudible(boardID: UUID) + case boardBypass(boardID: UUID) + case pedalBypass(pedalID: UUID) + /// A pedal-specific momentary action beyond generic bypass (e.g. a looper's + /// record/stop or reset footswitch). `kind` is opaque to `MIDIMap` — `MIDIController` + /// resolves the target pedal (by id) and dispatches on `kind` itself. + case pedalAction(pedalID: UUID, kind: PedalActionKind) + /// Toggles the rig-level tuner on/off. + case tunerToggle + /// Registers one tap-tempo press (see `ShoeGaze.tapTempo()`). + case tapTempo + } + + /// A pedal-specific momentary action addressable by ``Action/pedalAction(pedalID:kind:)``. + /// New pedals with more than a simple bypass toggle add cases here. + public enum PedalActionKind: Codable, Equatable, Sendable { + /// Looper: `.empty` → begin recording; `.recording` → stop and start looping. + case looperRecordStop + /// Looper: flips `overdubOn` between `0` and `1`. + case looperOverdubToggle + /// Looper: flips `loopOn` between `0` and `1`. + case looperLoopToggle + /// Looper: reset — clears the loop and returns to `.empty`. + case looperReset } // MARK: - Switch binding @@ -98,15 +124,14 @@ public struct MIDIMap: Codable, Equatable, Sendable { /// A knob or slider on a pedal, indexed into `pedal.ccMappableControls`. case pedalControl( - boardIndex: Int, - pedalIndex: Int, + pedalID: UUID, controlIndex: Int, pedalNameHint: String?, controlLabelHint: String? ) /// A board's master output level (the board fader). - case boardLevel(boardIndex: Int, boardLabelHint: String?) + case boardLevel(boardID: UUID, boardLabelHint: String?) /// The rig-wide output volume (applies to the whole rig). case rigVolume @@ -115,8 +140,8 @@ public struct MIDIMap: Codable, Equatable, Sendable { /// find and replace a binding regardless of the name captured at learn time). public func addresses(_ other: CCTarget) -> Bool { switch (self, other) { - case let (.pedalControl(b1, p1, c1, _, _), .pedalControl(b2, p2, c2, _, _)): - return b1 == b2 && p1 == p2 && c1 == c2 + case let (.pedalControl(p1, c1, _, _), .pedalControl(p2, c2, _, _)): + return p1 == p2 && c1 == c2 case let (.boardLevel(b1, _), .boardLevel(b2, _)): return b1 == b2 case (.rigVolume, .rigVolume): diff --git a/Sources/LyrebirdShoeGaze/Pedal.swift b/Sources/LyrebirdShoeGaze/Pedal.swift index b1be867..7b82629 100644 --- a/Sources/LyrebirdShoeGaze/Pedal.swift +++ b/Sources/LyrebirdShoeGaze/Pedal.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +import Foundation import LyrebirdSynth import LyrebirdUI @@ -59,8 +60,27 @@ open class Pedal: SynthesizerBase { /// safe 48 kHz fallback. public var sampleRate: Double = 48000.0 + // MARK: - Tempo / engine (injected) + + /// Shared tempo clock, injected by `PedalBoard.add(_:)` for tempo-aware pedals (the + /// looper's beat-quantized transport). `nil` for pedals added to a board that was + /// created without a clock (e.g. a bare parallel sub-board). Weak: the clock is owned + /// by `ShoeGaze` and outlives every pedal. + public internal(set) weak var clock: LyrebirdClock? + + /// The engine that owns this pedal's nodes, injected by `PedalBoard.add(_:)`. Needed by + /// tempo-aware pedals to start a `LyrebirdRoutine` that waits on beat boundaries. Weak: + /// the engine owns the node tree, not the reverse. + public internal(set) weak var hostEngine: SynthesisEngine? + // MARK: - Identity / routing + /// Stable identity for this pedal instance, persisted in ``PedalState`` and used by MIDI + /// bindings to address the pedal by id rather than by chain position. Defaults to a fresh + /// `UUID` for a newly-created pedal; a rebuild from a saved rig restores the saved id + /// (`board.add(_:)` / preset apply sets it), so a pedal keeps its identity across edits. + public internal(set) var id: UUID = UUID() + /// Human-readable name for the pedal (e.g. "Overdrive", "Delay"). public let displayName: String @@ -87,6 +107,11 @@ open class Pedal: SynthesizerBase { /// Override in a widener or stereo-native subclass. open var channelKind: PedalChannelKind { .mono } + /// Number of standard enclosure widths this pedal's card occupies in the UI. Defaults + /// to `1`. A control-dense pedal (e.g. the looper) overrides to `2` for a wider card. + /// The UI multiplies its base enclosure width by this factor; `1` is the normal stompbox. + open var widthUnits: Int { 1 } + /// `true` when the board has placed this pedal in a stereo (width-2) region. public var isStereo: Bool { outputBusRight != nil } @@ -177,6 +202,16 @@ open class Pedal: SynthesizerBase { [] } + /// Effect-specific action buttons for this pedal, rendered as a row of stomp-style + /// buttons beneath the switch row. + /// + /// Override in subclasses to publish momentary actions (e.g. "Record / Stop", "Reset") + /// that need a non-RT side effect beyond writing a single parameter value — see + /// ``PedalButton``. Defaults to empty. + open var effectButtons: [PedalButton] { + [] + } + /// All knobs a generic UI should render for this pedal: effect-specific knobs /// first, then the common `mix` and `level` knobs. The `bypass` parameter is /// surfaced separately as a header toggle, not as a knob. diff --git a/Sources/LyrebirdShoeGaze/PedalBoard.swift b/Sources/LyrebirdShoeGaze/PedalBoard.swift index 98019b8..a7ae945 100644 --- a/Sources/LyrebirdShoeGaze/PedalBoard.swift +++ b/Sources/LyrebirdShoeGaze/PedalBoard.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +import Foundation import LyrebirdSynth import LyrebirdUI @@ -59,6 +60,10 @@ public final class PedalBoard { private let engine: SynthesisEngine + /// Shared tempo clock, forwarded to each pedal in `add(_:)` so tempo-aware pedals (the + /// looper) can quantize to beats. `nil` for boards created without one. + private let clock: LyrebirdClock? + /// The bus that feeds the first pedal in the chain. public let headBus: AudioBus @@ -89,6 +94,11 @@ public final class PedalBoard { /// call chains the first pedal after this node automatically (no `after:` arg needed). public internal(set) var headInputNode: (any Synthesizer)? + /// Stable identity for this board, persisted in ``BoardState`` and used by MIDI bindings to + /// address the board by id rather than by position. Defaults to a fresh `UUID`; a rebuild from + /// a saved rig restores the saved id, so a board keeps its identity across edits and reorders. + public internal(set) var id: UUID = UUID() + /// Display label for the board, shown in the UI. Defaults to `"Board"`; `ShoeGaze` /// assigns a numbered label (`"Board 1"`, `"Board 2"`, …) when it creates the board. public var label: String = "Board" @@ -153,9 +163,13 @@ public final class PedalBoard { /// /// - Parameters: /// - engine: The `SynthesisEngine` that will own the pedal nodes. + /// - clock: Shared tempo clock forwarded to tempo-aware pedals (the looper) for + /// beat-quantized transport. Optional; `nil` disables quantization for pedals on + /// this board. /// - Throws: `BusAllocatorError.noFreeBus` if no mono audio bus is available. - public init(engine: SynthesisEngine) throws { + public init(engine: SynthesisEngine, clock: LyrebirdClock? = nil) throws { self.engine = engine + self.clock = clock let head: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) self.headBus = head self.outputBus = head @@ -196,6 +210,8 @@ public final class PedalBoard { /// - `EngineAddError` if the engine rejects the add (e.g. queue full, double-add). public func add(_ pedal: Pedal, after predecessor: (any Synthesizer)? = nil) throws { pedal.sampleRate = engine.sampleRate + pedal.hostEngine = engine + pedal.clock = clock // Each arm configures the pedal's buses, inserts it, advances the tail, and only then // records it in `pedals` — so a pedal is never tracked unless it was fully wired and diff --git a/Sources/LyrebirdShoeGaze/PedalButton.swift b/Sources/LyrebirdShoeGaze/PedalButton.swift new file mode 100644 index 0000000..06ee30d --- /dev/null +++ b/Sources/LyrebirdShoeGaze/PedalButton.swift @@ -0,0 +1,70 @@ +// PedalButton.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdUI + +/// A UI-agnostic description of one pedal button — a momentary action trigger or a +/// node-bound toggle, rendered as a stomp-style button. +/// +/// Where ``PedalSwitch`` describes a multi-position segmented control, `PedalButton` +/// describes a single button in one of two styles: +/// - `.momentary`: runs a closure on each press (e.g. "Record / Stop", "Reset"). Use this +/// whenever pressing the button must also perform a non-RT side effect (clearing a +/// buffer, requesting a recorder reset) beyond writing a single parameter value. +/// - `.toggle`: flips a bound ``UIParamNode`` between `0` and `1` on each press, with no +/// side effect required — appropriate only when the live audio graph itself reads the +/// node continuously (so toggling the raw value is sufficient). +/// +/// A `Pedal` publishes an array of these via ``Pedal/effectButtons`` so a generic +/// pedalboard UI can render a footswitch-style button per action without knowing the +/// concrete pedal type. +public struct PedalButton { + + /// Style of button behavior, mirroring `ParameterButton.Style` in `LyrebirdUI`. + public enum Style { + /// Executes `action` on each press. + case momentary + /// Flips `node` between `0` and `1` on each press. + case toggle + } + + /// Short label shown on the button (e.g. "Record", "Reset"). + public let label: String + + /// Button behavior style. + public let style: Style + + /// The live parameter node this button toggles. Non-`nil` only for `.toggle` style. + public let node: UIParamNode? + + /// The action run on each press. Non-`nil` only for `.momentary` style. + public let action: (() -> Void)? + + /// Creates a momentary action button. + /// + /// - Parameters: + /// - label: Short label shown on the button. + /// - action: Closure run on each press. + public init(label: String, action: @escaping () -> Void) { + self.label = label + self.style = .momentary + self.node = nil + self.action = action + } + + /// Creates a toggle button bound to a `UIParamNode`. + /// + /// - Parameters: + /// - label: Short label shown on the button. + /// - node: The `UIParamNode` projected value of an `@UIParam` property + /// (`pedal.$overdubOn`, `pedal.$loopOn`, …). + public init(label: String, node: UIParamNode) { + self.label = label + self.style = .toggle + self.node = node + self.action = nil + } +} diff --git a/Sources/LyrebirdShoeGaze/PedalType.swift b/Sources/LyrebirdShoeGaze/PedalType.swift index 3cb7ead..65db3eb 100644 --- a/Sources/LyrebirdShoeGaze/PedalType.swift +++ b/Sources/LyrebirdShoeGaze/PedalType.swift @@ -93,4 +93,7 @@ public extension PedalType { static let octaveSplitter = PedalType("Octave Splitter") static let bassOctaver = PedalType("Bass Octaver") static let harmonizer = PedalType("Harmonizer") + + // Looper + static let looper = PedalType("Looper") } diff --git a/Sources/LyrebirdShoeGaze/Pedals/LooperPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/LooperPedal.swift new file mode 100644 index 0000000..efd1937 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Pedals/LooperPedal.swift @@ -0,0 +1,512 @@ +// LooperPedal.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import LyrebirdSynth +import LyrebirdUI + +/// A loop-recorder pedal: record a take into a buffer, then play it back looping, with +/// overdub, overdub-undo, reverse playback, feedback-decay overdub, and a crossfaded +/// total-loop mute. When the board supplies a tempo ``LyrebirdClock`` the transport is +/// beat-quantized — record start and loop close both snap to the next beat, so every loop +/// is a whole number of beats long. +/// +/// Signal chain (inside `effect(_:)`): +/// ``` +/// dry → RecordBuffer.Audio (primary take, passthrough while recording) ─┐ +/// dry → RecordBuffer.Audio (overdub, gated by overdubOn × isPlaying, │ (write only) +/// old content scaled by feedback) │ +/// loopBuffer → PlayBuffer.Audio (loop, cubic, rate ±1) │ +/// primary passthrough ↔ (lagged loopOn × isPlaying) ↔ PlayBuffer.Audio ─┴→ wet +/// ``` +/// +/// A single fixed generator graph is built once (Lyrebird's node tree does not support +/// rebuilding a synth's internal generators). Every transport action is expressed as a +/// live parameter change the graph already reads every block (`$overdubOn`, `$loopOn`, +/// `$isPlaying`, `$reverse`, `$feedback`, `$playTrigger`), plus, for actions with a genuine +/// non-RT side effect (clearing the buffer, narrowing/restoring `loopLength`, snapshotting +/// for undo), an explicit method. +/// +/// ## Transport (beat-quantized when a clock is present) +/// - ``toggleRecordStop()``: `.empty` → arm/begin recording; `.recording` → close the loop +/// and start looping. No-op while `.playing` — use ``resetLoop()`` for a new take. +/// - `overdubOn` (via ``toggleOverdub()``): layers new input onto the loop; engaging it first +/// snapshots the loop so ``undoOverdub()`` can revert the pass. +/// - `loopOn` (switch): crossfaded total mute without stopping the player. +/// - `reverse` (switch): flips playback direction (`rate` 1 → −1) without a rebuild. +/// - ``undoOverdub()``: restores the loop to the snapshot taken when overdub was last engaged. +/// - ``resetLoop()``: clears the buffer and returns to `.empty`. +/// +/// ## Knobs +/// - `crossfadeTime`: Fade time constant, in seconds, for `loopOn` and the record→play handoff. +/// - `playbackLevel`: Loop playback gain, in dB. +/// - `overdubLevel`: Overdub input gain, in dB. +/// - `feedback`: Retained level of existing loop content on each overdub pass, `[0, 1]`. +/// `1.0` (default) keeps old layers forever; lower values fade them for a decaying dub. +public final class LooperPedal: Pedal { + + /// One-line description shown in the picker and info panel. + public override var summary: String { + "Records a loop, then plays it back with overdub, reverse, and a crossfaded mute." + } + + /// Double-width card: the looper carries a full transport plus a loop timeline and reads + /// more comfortably in a wider enclosure. + public override var widthUnits: Int { 2 } + + // MARK: - Knobs + + /// Fade time constant, in seconds, for the loop on/off mute and the record→play handoff. + /// A `Lag.Control` 60 dB settling time, not a fixed-length linear ramp. + @UIParam public var crossfadeTime: Double = LooperPedal.defaultCrossfadeTime + + /// Loop playback gain, in dB. + @UIParam public var playbackLevel: Double = 0.0 + + /// Overdub input gain, in dB. Scales only the new material being layered in — the + /// existing loop content is never attenuated by this knob. + @UIParam public var overdubLevel: Double = 0.0 + + /// Retained level of the existing loop content on each overdub pass, `[0, 1]`. `1.0` + /// keeps prior layers indefinitely; lower values fade them a little on every pass for a + /// decaying "sound-on-sound" feedback loop. + @UIParam public var feedback: Double = 1.0 + + // MARK: - Switches + + /// Overdub gate. `0` = off, `1` = on. Live-gated — has no effect before a loop exists. + @UIParam public var overdubOn: Double = 0.0 + + /// Total loop mute. `0` = muted (silent), `1` = audible. Transitions are smoothed by + /// `crossfadeTime`. + @UIParam public var loopOn: Double = 1.0 + + /// Playback direction. `0` = forward, `1` = reverse. Read by the player's `rate` input + /// as `1 − 2·reverse`, so toggling flips the loop without rebuilding the graph. + @UIParam public var reverse: Double = 0.0 + + // MARK: - Internal live state + + /// `1` once a take has been recorded and looping playback has started, else `0`. + /// Read by the audio graph (gates overdub and the loop crossfade) — not a user knob. + @UIParam public var isPlaying: Double = 0.0 + + /// Play-head reset trigger for the loop player. Pulsed `0 → 1` at loop close so playback + /// starts phase-aligned to frame 0 (the anchor for the timeline read-out); rearmed to `0` + /// on ``resetLoop()``. Read by the player's `trigger` input. Not a user knob. + @UIParam public var playTrigger: Double = 0.0 + + // MARK: - Constants + + /// Maximum recordable take length, in seconds. + private static let maxDurationSeconds: Double = 60.0 + + /// Default crossfade duration, in seconds. + private static let defaultCrossfadeTime: Double = 0.05 + + /// Bipolar span mapping `reverse ∈ {0, 1}` to a playback rate of `{+1, −1}`. + private static let reverseRateSpan: Double = 2.0 + + /// Forward playback rate, and the rate offset the reverse span is subtracted from. + private static let forwardRate: Double = 1.0 + + /// Smallest permitted loop length, in frames, so a degenerate zero-length take can't + /// produce a divide-by-zero in the player or the timeline read-out. + private static let minimumLoopFrames: Int = 1 + + /// Frames to wait after disabling overdub before restoring an undo snapshot, so the + /// RT-side overdub writer (its `run` gate ramps closed over one control block) has fully + /// stopped writing the loop buffer before the main thread overwrites it. Two maximum + /// blocks (`blockSize ≤ 512`) is a comfortable margin. + private static let undoGuardFrames: Int = 1024 + + private let crossfadeTimeRange: ClosedRange = 0.0 ... 2.0 + private let levelRangeDb: ClosedRange = -24.0 ... 12.0 + private let feedbackRange: ClosedRange = 0.0 ... 1.0 + + // MARK: - Buffer + generators + + /// The loop buffer, sized to `maxDurationSeconds` at the engine sample rate. Allocated + /// in `effect(_:)` (called from `build()`), not `init`, because `sampleRate` is only set + /// by `PedalBoard.add(_:)` after construction but before the engine builds the graph. + private var loopBuffer: LyrebirdBuffer? + + private var primaryRecorder: RecordBuffer.Audio? + private var overdubRecorder: RecordBuffer.Audio? + private var player: PlayBuffer.Audio? + + // MARK: - Transport state + + private enum Phase { + case empty + case armedRecord + case recording + case armedStop + case playing + } + + private var phase: Phase = .empty + + /// Beat-boundary sample time at which the current take started recording, and at which + /// the loop closes. Both are captured from the clock so the loop length is beat-exact. + private var recordStartSample: SampleTime = 0 + + /// Sample time playback began looping (play-head at frame 0) — the timeline anchor. + private var playStartSample: SampleTime = 0 + + /// Length of the closed loop in frames (`0` until a take is recorded). + private var loopFrames: Int = 0 + + /// Length of the closed loop in whole beats (`0` until a beat-quantized take is closed). + private var loopBeats: Double = 0.0 + + /// Snapshot of the loop taken when overdub was last engaged, for ``undoOverdub()``. + private var overdubUndoSnapshot: [Double]? + + /// Background routine that waits for the next beat before applying a transport action. + /// Stopped (non-blocking) before starting a new one, and torn down on ``resetLoop()``. + private var transportRoutine: LyrebirdRoutine? + + /// Background routine that defers an undo restore until the RT overdub gate has closed. + private var undoRoutine: LyrebirdRoutine? + + /// Monotonic transport-action generation. Bumped on every arm and on ``resetLoop()``; a + /// deferred beat callback carries the generation it was armed under and is dropped if the + /// generation has since advanced — so a callback whose action was superseded (a new press, + /// a reset) can never apply to the wrong take. Guards the `DispatchQueue.main.async` hop, + /// which `LyrebirdRoutine.stop()` cannot itself cancel once enqueued. + /// (internal, not private, only so tests can assert the generation-drop of a stale callback.) + private(set) var transportGeneration: Int = 0 + + // MARK: - Init + + /// Creates a looper pedal. + /// + /// - Parameters: + /// - inputBus: Audio bus to read the dry input from. Defaults to `0`; set by the board. + /// - outputBus: Audio bus to write the output to. Defaults to `0`; set by the board. + public init(inputBus: Int = 0, outputBus: Int = 0) { + super.init(name: "Looper", inputBus: inputBus, outputBus: outputBus, initialMix: 1.0) + } + + // MARK: - Knobs / switches / buttons + + public override var effectKnobs: [PedalKnob] { + [ + PedalKnob(label: "Crossfade", node: $crossfadeTime, range: crossfadeTimeRange), + PedalKnob(label: "Playback", node: $playbackLevel, range: levelRangeDb), + PedalKnob(label: "Overdub", node: $overdubLevel, range: levelRangeDb), + PedalKnob(label: "Feedback", node: $feedback, range: feedbackRange), + ] + } + + public override var effectButtons: [PedalButton] { + [ + PedalButton(label: "Record / Stop") { [weak self] in self?.toggleRecordStop() }, + PedalButton(label: "Overdub") { [weak self] in self?.toggleOverdub() }, + PedalButton(label: "Undo") { [weak self] in self?.undoOverdub() }, + PedalButton(label: "Loop", node: $loopOn), + PedalButton(label: "Reverse", node: $reverse), + PedalButton(label: "Reset") { [weak self] in self?.resetLoop() }, + ] + } + + // MARK: - UI read-outs + + /// Publicly-observable transport phase for the UI (LED colour, armed animation, timeline). + public var transportState: LooperTransportState { + switch phase { + case .empty: return .empty + case .armedRecord: return .armedRecord + case .recording: return .recording + case .armedStop: return .armedStop + case .playing: return .playing + } + } + + /// Closed-loop length in frames (`0` until a take is recorded). + public var loopFrameCount: Int { loopFrames } + + /// Closed-loop length in seconds (`0` until a take is recorded). + public var loopLengthSeconds: Double { Double(loopFrames) / sampleRate } + + /// Closed-loop length in whole beats (`0` unless the take was beat-quantized). + public var loopLengthBeats: Double { loopBeats } + + /// Normalised play-head position in `[0, 1)` while `.playing`, else `nil`. + /// + /// Derived from the engine sample clock and the frame-0 playback anchor, so it tracks the + /// audio play-head regardless of tempo. The player's play-head is reset by a `playTrigger` + /// edge consumed at the next block boundary, so this read-out may lead the true audio + /// play-head by up to one block (≤ ~11 ms) — imperceptible for a UI sweep. Reverse playback + /// is reflected by mirroring the forward progress, matching the player's negated `rate`. + public func playbackPosition01() -> Double? { + guard phase == .playing, loopFrames > 0, let engine: SynthesisEngine = hostEngine else { + return nil + } + let elapsed: SampleTime = engine.currentTime - playStartSample + guard elapsed >= 0 else { return 0.0 } + let framesInto: Int = Int(elapsed % SampleTime(loopFrames)) + let forward: Double = Double(framesInto) / Double(loopFrames) + return reverse >= 0.5 ? (1.0 - forward) : forward + } + + // MARK: - Effect + + public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { + let maxFrames: Int = Int(LooperPedal.maxDurationSeconds * sampleRate) + let buffer: LyrebirdBuffer = LyrebirdBuffer(count: maxFrames, channelCount: 1) + loopBuffer = buffer + + let primary: RecordBuffer.Audio = RecordBuffer.Audio( + input: dry, + buffer: buffer, + loop: false, + doneAction: .nothing + ) + primary.run = 0.0 + primaryRecorder = primary + + let overdub: RecordBuffer.Audio = RecordBuffer.Audio( + input: dry, + buffer: buffer, + loop: true, + doneAction: .nothing + ) + // Live-gated: only writes while a loop exists and overdub is switched on. The existing + // loop content is scaled by `feedback` on each pass (1.0 = keep, < 1.0 = decay). + overdub.$run.source = $overdubOn * $isPlaying + overdub.$recLevel.source = DbAmp.Control($overdubLevel) + overdub.$preLevel.source = $feedback + overdubRecorder = overdub + + // Playback rate: forward at +1, reverse at −1, switched live off `$reverse`. + let playbackRate: any ValidGeneratorInput = + LooperPedal.forwardRate - LooperPedal.reverseRateSpan * $reverse + + let loopPlayer: PlayBuffer.Audio = PlayBuffer.Audio( + buffer: buffer, + loop: true, + interpolation: .cubic, + rate: playbackRate, + trigger: $playTrigger, + mul: DbAmp.Control($playbackLevel) + ) + player = loopPlayer + + // Loop audible only while playing and not muted; smoothed to avoid clicks on either + // the record→play handoff or a loopOn toggle. + let combinedGate: any ValidGeneratorInput = $isPlaying * $loopOn + let smoothedGate: Lag.Control = Lag.Control(input: combinedGate, time: $crossfadeTime) + let unityGain: Double = 1.0 + let dryGate: any ValidGeneratorInput = unityGain - smoothedGate + + return (primary * dryGate) + (loopPlayer * smoothedGate) + } + + // MARK: - Transport + + /// `.empty` → arms/begins recording. `.recording` → closes the loop and starts looping. + /// No-op while `.playing` or already armed. + public func toggleRecordStop() { + switch phase { + case .empty: + armRecording() + case .recording: + armStopAndPlay() + case .armedRecord, .armedStop, .playing: + break + } + } + + /// Toggles the overdub gate. Engaging it (off → on) first snapshots the current loop so + /// ``undoOverdub()`` can revert the pass. + public func toggleOverdub() { + // Any overdub press supersedes a pending deferred action (e.g. an in-flight undo + // restore) — advance the generation so that stale callback is dropped, and stop the + // now-superseded undo routine so its background thread doesn't idle-poll to its target. + transportGeneration += 1 + undoRoutine?.stop() + undoRoutine = nil + let engaging: Bool = overdubOn < 0.5 + if engaging { captureOverdubSnapshot() } + overdubOn = engaging ? 1.0 : 0.0 + } + + /// Restores the loop to the snapshot captured when overdub was last engaged. No-op if no + /// snapshot exists. Disengages overdub, then restores the buffer only once the RT overdub + /// writer has actually stopped, so the main-thread bulk write can't race the RT thread's + /// lock-free writes into the same buffer. + public func undoOverdub() { + guard let buffer: LyrebirdBuffer = loopBuffer, + let snapshot: [Double] = overdubUndoSnapshot, + snapshot.count <= buffer.totalSampleCount else { return } + overdubOn = 0.0 + // Advance the generation and capture it: a later reset / new take / overdub press bumps + // the generation and drops this restore, so it can never stomp a buffer the user has + // since cleared or re-recorded. + transportGeneration += 1 + let generation: Int = transportGeneration + guard let engine: SynthesisEngine = hostEngine else { + // No engine (standalone / headless tests): single-threaded, restore immediately. + applyUndoRestore(snapshot, generation: generation) + return + } + // Overdub's `run` gate ramps to zero over one control block, so the recorder may write + // for up to a block more. Wait past that before overwriting the buffer. + undoRoutine?.stop() + let target: SampleTime = engine.currentTime + SampleTime(LooperPedal.undoGuardFrames) + let routine: LyrebirdRoutine = LyrebirdRoutine { [weak self] ctx in + try ctx.waitUntil(sampleTime: target) + DispatchQueue.main.async { self?.applyUndoRestore(snapshot, generation: generation) } + } + undoRoutine = routine + routine.start(engine: engine) + } + + /// Writes an undo snapshot back into the loop buffer, unless its generation has been + /// superseded by a reset, a new take, or a subsequent overdub/undo press. + func applyUndoRestore(_ snapshot: [Double], generation: Int) { + guard generation == transportGeneration, + let buffer: LyrebirdBuffer = loopBuffer, + snapshot.count <= buffer.totalSampleCount else { return } + buffer.setRangeValues(snapshot, startingAt: 0) + } + + /// Clears the loop and returns to `.empty`, ready for a fresh take. + public func resetLoop() { + // Stop (non-blocking) any pending transport/undo routines and advance the generation + // so an already-enqueued beat callback is dropped rather than applied to the new take. + transportRoutine?.stop() + transportRoutine = nil + undoRoutine?.stop() + undoRoutine = nil + transportGeneration += 1 + primaryRecorder?.run = 0.0 + primaryRecorder?.requestReset() + overdubRecorder?.requestReset() + if let buffer: LyrebirdBuffer = loopBuffer { + buffer.clear() + buffer.setLoopLength(buffer.count) + } + isPlaying = 0.0 + overdubOn = 0.0 + loopOn = 1.0 + playTrigger = 0.0 + loopFrames = 0 + loopBeats = 0.0 + overdubUndoSnapshot = nil + phase = .empty + } + + // MARK: - Transport helpers + + /// Snapshots the closed-loop content into `overdubUndoSnapshot`. Called with overdub off, + /// so only the loop player reads the buffer concurrently (a lock-free read is safe). + private func captureOverdubSnapshot() { + guard let buffer: LyrebirdBuffer = loopBuffer, loopFrames > 0 else { return } + // Mono buffer: linear storage index == frame index. Called with overdub off (only the + // player reads concurrently), so a lock-free read of the storage is safe. + let frameCount: Int = min(loopFrames, buffer.totalSampleCount) + var snapshot: [Double] = [Double](repeating: 0.0, count: frameCount) + for i: Int in 0 ..< frameCount { + snapshot[i] = buffer[i] + } + overdubUndoSnapshot = snapshot + } + + /// A transport transition deferred to a beat boundary. + private enum QuantizedAction: Sendable { + case beginRecording + case finishStop + } + + /// Begins recording immediately, or — with a clock — on the next beat boundary. + private func armRecording() { + phase = .armedRecord + runQuantized(.beginRecording) + } + + /// Closes the loop immediately, or — with a clock — on the next beat boundary. + private func armStopAndPlay() { + phase = .armedStop + runQuantized(.finishStop) + } + + /// Applies `action` on the main thread once the clock reaches the next beat, via a + /// background wait routine. With no clock/engine, applies it synchronously for + /// un-quantized transport (and headless tests). + private func runQuantized(_ action: QuantizedAction) { + transportGeneration += 1 + let generation: Int = transportGeneration + guard let clock: LyrebirdClock = clock, let engine: SynthesisEngine = hostEngine else { + applyQuantizedTransport(action, generation: generation, at: nil) + return + } + transportRoutine?.stop() + let target: SampleTime = clock.nextBeat() + let routine: LyrebirdRoutine = LyrebirdRoutine { [weak self] ctx in + try ctx.waitUntil(sampleTime: target) + // The wait runs on a background thread; all pedal state changes hop to main. The + // generation guard drops this callback if the action was superseded before it fires. + DispatchQueue.main.async { self?.applyQuantizedTransport(action, generation: generation, at: target) } + } + transportRoutine = routine + routine.start(engine: engine) + } + + /// Runs the deferred transport transition (on the main thread), unless its generation has + /// been superseded by a newer arm or a reset. + private func applyQuantizedTransport(_ action: QuantizedAction, generation: Int, at beatSample: SampleTime?) { + guard generation == transportGeneration else { return } + switch action { + case .beginRecording: beginRecording(at: beatSample) + case .finishStop: finishRecordingAndPlay(at: beatSample) + } + } + + func beginRecording(at beatSample: SampleTime?) { + guard phase == .armedRecord else { return } + recordStartSample = beatSample ?? (hostEngine?.currentTime ?? 0) + primaryRecorder?.run = 1.0 + phase = .recording + } + + func finishRecordingAndPlay(at beatSample: SampleTime?) { + guard phase == .armedStop, + let primary: RecordBuffer.Audio = primaryRecorder, + let buffer: LyrebirdBuffer = loopBuffer else { return } + primary.run = 0.0 + + let closeSample: SampleTime = beatSample ?? (hostEngine?.currentTime ?? 0) + if let clock: LyrebirdClock = clock, beatSample != nil { + // Beat-quantized: loop length is the exact whole-beat span between the two beat + // boundaries, independent of any recording-position snapshot slop. + let spanFrames: Int = Int(closeSample - recordStartSample) + loopFrames = max(LooperPedal.minimumLoopFrames, spanFrames) + loopBeats = beatsForSpan(frames: loopFrames, clock: clock) + } else { + // Un-quantized fallback: trim to the recorder's frame count. + loopFrames = max(LooperPedal.minimumLoopFrames, primary.recordedFrameCount) + loopBeats = 0.0 + } + + buffer.setLoopLength(loopFrames) + playStartSample = closeSample + playTrigger = 1.0 + isPlaying = 1.0 + phase = .playing + } + + /// Whole-beat length of a `frames`-long span at the clock's *current* tempo. If the tempo + /// changed during the take, `loopFrames` (from raw sample deltas) stays correct while this + /// beat count — a UI read-out only, never audio — may misreport. Acceptable. + func beatsForSpan(frames: Int, clock: LyrebirdClock) -> Double { + let samplesPerBeat: Double = Double(clock.sampleTime(beat: 1.0) - clock.sampleTime(beat: 0.0)) + guard samplesPerBeat > 0 else { return 0.0 } + return (Double(frames) / samplesPerBeat).rounded() + } +} diff --git a/Sources/LyrebirdShoeGaze/Pedals/LooperTransportState.swift b/Sources/LyrebirdShoeGaze/Pedals/LooperTransportState.swift new file mode 100644 index 0000000..e0a1266 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Pedals/LooperTransportState.swift @@ -0,0 +1,30 @@ +// LooperTransportState.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// Publicly-observable transport phase of ``LooperPedal``, surfaced for the UI so it can +/// colour the record LED, animate the "waiting for the next beat" armed states, and drive +/// the loop timeline. +/// +/// The two `armed…` cases exist only when the pedal has a tempo ``LyrebirdClock`` — a +/// transport action then waits for the next beat boundary before it takes effect. Without a +/// clock the pedal transitions straight between ``empty``, ``recording`` and ``playing``. +public enum LooperTransportState: Sendable, Equatable { + + /// No take recorded yet. `Record` begins recording (or arms it, with a clock). + case empty + + /// A `Record` has been requested and the pedal is waiting for the next beat to start. + case armedRecord + + /// Actively recording the primary take. + case recording + + /// A stop has been requested and the pedal is waiting for the next beat to close the loop. + case armedStop + + /// Looping playback of the recorded take (overdub / reverse / mute apply here). + case playing +} diff --git a/Sources/LyrebirdShoeGaze/Presets/BoardState.swift b/Sources/LyrebirdShoeGaze/Presets/BoardState.swift index a109d4e..39487fa 100644 --- a/Sources/LyrebirdShoeGaze/Presets/BoardState.swift +++ b/Sources/LyrebirdShoeGaze/Presets/BoardState.swift @@ -4,6 +4,8 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +import Foundation + /// Serialisable snapshot of one `PedalBoard`'s label and full signal-chain topology. /// /// `label` is the board's display name. `segments` captures the chain in signal-flow order: @@ -18,6 +20,11 @@ /// subset (the whole chain for boards with no split regions) for callers that only need it. public struct BoardState: Codable, Equatable { + /// Stable per-board identity, persisted so MIDI bindings can address a board by id rather + /// than by position. Survives capture → rebuild round-trips. Legacy presets without an id + /// decode to a fresh `UUID()`. + public let id: UUID + /// The board's display label (e.g. `"Board 1"`). public let label: String @@ -39,9 +46,11 @@ public struct BoardState: Codable, Equatable { /// - label: The board's display label. /// - segments: Ordered signal-chain segments. public init( + id: UUID = UUID(), label: String, segments: [BoardSegmentState] ) { + self.id = id self.label = label self.segments = segments } @@ -55,14 +64,17 @@ public struct BoardState: Codable, Equatable { /// - label: The board's display label. /// - pedals: Ordered list of pedal state snapshots. public init( + id: UUID = UUID(), label: String, pedals: [PedalState] ) { + self.id = id self.label = label self.segments = pedals.map { BoardSegmentState.pedal($0) } } private enum CodingKeys: String, CodingKey { + case id case label case segments case pedals @@ -72,6 +84,7 @@ public struct BoardState: Codable, Equatable { /// wrapping each entry as a `.pedal` segment. public init(from decoder: any Decoder) throws { let container: KeyedDecodingContainer = try decoder.container(keyedBy: CodingKeys.self) + self.id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID() self.label = try container.decode(String.self, forKey: .label) if let decodedSegments: [BoardSegmentState] = try container.decodeIfPresent([BoardSegmentState].self, forKey: .segments) { @@ -94,6 +107,7 @@ public struct BoardState: Codable, Equatable { /// Encodes the snapshot using the current `segments` representation. public func encode(to encoder: any Encoder) throws { var container: KeyedEncodingContainer = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) try container.encode(label, forKey: .label) try container.encode(segments, forKey: .segments) } diff --git a/Sources/LyrebirdShoeGaze/Presets/Pedal+Preset.swift b/Sources/LyrebirdShoeGaze/Presets/Pedal+Preset.swift index 54af6b7..6487dbc 100644 --- a/Sources/LyrebirdShoeGaze/Presets/Pedal+Preset.swift +++ b/Sources/LyrebirdShoeGaze/Presets/Pedal+Preset.swift @@ -21,6 +21,7 @@ extension Pedal { let sliderValues: [Double] = effectSliders.map { $0.node.value } let selectorValues: [Double] = effectSelectors.map { $0.node.value } return PedalState( + id: id, type: displayName, knobValues: values, switchValues: switchValues, @@ -44,6 +45,9 @@ extension Pedal { /// against `displayName` — the caller is responsible for matching types before /// calling this method. public func applyState(_ state: PedalState) { + // Restore the saved identity so the pedal keeps its id across rebuilds; MIDI bindings + // address pedals by this id. + id = state.id for (knob, value) in zip(knobs, state.knobValues) { knob.node.update(value) } diff --git a/Sources/LyrebirdShoeGaze/Presets/PedalBoard+Preset.swift b/Sources/LyrebirdShoeGaze/Presets/PedalBoard+Preset.swift index effe0c0..aa7f4ea 100644 --- a/Sources/LyrebirdShoeGaze/Presets/PedalBoard+Preset.swift +++ b/Sources/LyrebirdShoeGaze/Presets/PedalBoard+Preset.swift @@ -45,6 +45,6 @@ extension PedalBoard { return BoardSegmentState.mergeToMono } } - return BoardState(label: label, segments: segmentStates) + return BoardState(id: id, label: label, segments: segmentStates) } } diff --git a/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift b/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift index d8cf89f..6eb2ffd 100644 --- a/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift +++ b/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift @@ -68,6 +68,7 @@ public enum PedalRegistry { "Bitcrusher": { BitcrusherPedal() }, "Granulator": { GranulatorPedal() }, "Auto Granulator": { AutoGranulatorPedal() }, + "Looper": { LooperPedal() }, ] /// Returns a new `Pedal` instance for the given type string, or `nil` if the type diff --git a/Sources/LyrebirdShoeGaze/Presets/PedalState.swift b/Sources/LyrebirdShoeGaze/Presets/PedalState.swift index daa2293..067a4f1 100644 --- a/Sources/LyrebirdShoeGaze/Presets/PedalState.swift +++ b/Sources/LyrebirdShoeGaze/Presets/PedalState.swift @@ -4,6 +4,8 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +import Foundation + /// Serialisable snapshot of one pedal's parameter values. /// /// `type` stores the pedal's `displayName` and is used by `PedalRegistry` to @@ -16,6 +18,12 @@ /// knobs at their current value. public struct PedalState: Codable, Equatable { + /// Stable per-pedal identity, persisted so MIDI bindings can address a pedal by id rather + /// than by chain position. Survives capture → rebuild round-trips (an edit rebuilds the board + /// from captured segments, carrying each pedal's id forward). Legacy presets without an id + /// decode to a fresh `UUID()`. + public let id: UUID + /// The pedal's `displayName` — used as a factory key by `PedalRegistry`. public let type: String @@ -47,6 +55,7 @@ public struct PedalState: Codable, Equatable { /// - selectorValues: Current selector values in `Pedal.effectSelectors` order. Defaults to empty. /// - bypass: Bypass parameter value (`0.0` = engaged, `1.0` = bypassed). public init( + id: UUID = UUID(), type: String, knobValues: [Double], switchValues: [Double] = [], @@ -54,6 +63,7 @@ public struct PedalState: Codable, Equatable { selectorValues: [Double] = [], bypass: Double ) { + self.id = id self.type = type self.knobValues = knobValues self.switchValues = switchValues @@ -63,6 +73,7 @@ public struct PedalState: Codable, Equatable { } private enum CodingKeys: String, CodingKey { + case id case type case knobValues case switchValues @@ -75,6 +86,7 @@ public struct PedalState: Codable, Equatable { /// `selectorValues` existed by defaulting the missing keys to an empty array. public init(from decoder: any Decoder) throws { let container: KeyedDecodingContainer = try decoder.container(keyedBy: CodingKeys.self) + self.id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID() self.type = try container.decode(String.self, forKey: .type) self.knobValues = try container.decode([Double].self, forKey: .knobValues) self.switchValues = try container.decodeIfPresent([Double].self, forKey: .switchValues) ?? [] diff --git a/Sources/LyrebirdShoeGaze/Presets/RigStore.swift b/Sources/LyrebirdShoeGaze/Presets/RigStore.swift index 52172e7..49a64a8 100644 --- a/Sources/LyrebirdShoeGaze/Presets/RigStore.swift +++ b/Sources/LyrebirdShoeGaze/Presets/RigStore.swift @@ -17,9 +17,19 @@ public enum RigStore { private static let folderName: String = "ShoeGaze" private static let fileName: String = "autosave-rig.json" + /// Test-only override for ``autosaveURL``. When non-`nil`, all autosave reads/writes use this + /// path instead of the real Application Support location — so a test suite never overwrites or + /// deletes the user's actual autosaved rig. Production code leaves this `nil`. + /// + /// - Important: Any test that calls `save`/`restore`/`clear` **must** set this to a temporary + /// file first (and reset it after), or it will clobber the running app's autosave. + public static var autosaveURLOverride: URL? + /// Location of the autosave file, creating the containing folder if needed. `nil` if the - /// Application Support directory can't be resolved. + /// Application Support directory can't be resolved. Returns ``autosaveURLOverride`` verbatim + /// when set (tests). public static var autosaveURL: URL? { + if let override: URL = autosaveURLOverride { return override } let fileManager: FileManager = FileManager.default guard let base: URL = try? fileManager.url( for: .applicationSupportDirectory, diff --git a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift index e124d43..22b3038 100644 --- a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift +++ b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift @@ -115,6 +115,7 @@ extension ShoeGaze { do { for boardState: BoardState in snapshot.boards { let board: PedalBoard = try addBoard() + board.id = boardState.id board.label = boardState.label try rebuildSegments(boardState.segments, into: board) try finalizeBoard(board) @@ -260,9 +261,14 @@ extension ShoeGaze { // can be restored. May be nil when `board` is unmanaged (not in `boards`). let oldIndex: Int? = boards.firstIndex(where: { $0 === board }) + // MIDI bindings address pedals/boards by UUID (persisted in PedalState/BoardState and + // carried through capture → rebuild), so a rebuild needs no binding reconciliation — the + // pedal keeps its id, and its binding resolves to it regardless of chain position. + // Build the new board FIRST so that any failure leaves the old board intact. let newBoard: PedalBoard = try addBoard() do { + newBoard.id = state.id newBoard.label = state.label try rebuildSegments(state.segments, into: newBoard) try finalizeBoard(newBoard) diff --git a/Sources/LyrebirdShoeGaze/Presets/ShoeGazeState.swift b/Sources/LyrebirdShoeGaze/Presets/ShoeGazeState.swift index c597a3d..5d54635 100644 --- a/Sources/LyrebirdShoeGaze/Presets/ShoeGazeState.swift +++ b/Sources/LyrebirdShoeGaze/Presets/ShoeGazeState.swift @@ -56,15 +56,28 @@ public struct ShoeGazeState: Codable, Equatable { case midiMap } - /// Decodes a rig snapshot, tolerating an absent OR malformed `midiMap`. + /// Decodes a rig snapshot, tolerating an absent, malformed, OR legacy-format `midiMap`. /// - /// The MIDI map is decoded with `try?` so a binding format that this build can't read (e.g. an - /// autosave written by an older schema) drops just the bindings — which are re-learnable — - /// rather than throwing and losing the entire rig. `version` and `boards` still decode strictly. + /// The MIDI map is decoded in three tiers: (1) the current id-based ``MIDIMap``; (2) failing + /// that, the pre-UUID positional ``LegacyMIDIMap``, migrated to id-based via the boards' + /// freshly-decoded ids so old rigs keep their bindings; (3) failing both (absent or unreadable), + /// `nil` — dropping just the bindings, which are re-learnable, rather than losing the whole rig. + /// `version` and `boards` still decode strictly. public init(from decoder: Decoder) throws { let container: KeyedDecodingContainer = try decoder.container(keyedBy: CodingKeys.self) self.version = try container.decode(Int.self, forKey: .version) - self.boards = try container.decode([BoardState].self, forKey: .boards) - self.midiMap = try? container.decodeIfPresent(MIDIMap.self, forKey: .midiMap) ?? nil + let decodedBoards: [BoardState] = try container.decode([BoardState].self, forKey: .boards) + self.boards = decodedBoards + + if !container.contains(.midiMap) { + self.midiMap = nil + } else if let current: MIDIMap = try? container.decode(MIDIMap.self, forKey: .midiMap) { + self.midiMap = current + } else if let legacy: LegacyMIDIMap = try? container.decode(LegacyMIDIMap.self, forKey: .midiMap) { + // Pre-UUID positional map: convert each binding to the id now at that position. + self.midiMap = legacy.migrated(boards: decodedBoards) + } else { + self.midiMap = nil + } } } diff --git a/Sources/LyrebirdShoeGaze/Recording/ShoeGaze+Recording.swift b/Sources/LyrebirdShoeGaze/Recording/ShoeGaze+Recording.swift index 8609e7b..850fb05 100644 --- a/Sources/LyrebirdShoeGaze/Recording/ShoeGaze+Recording.swift +++ b/Sources/LyrebirdShoeGaze/Recording/ShoeGaze+Recording.swift @@ -172,7 +172,10 @@ extension ShoeGaze { /// 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? { + /// 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 { diff --git a/Sources/LyrebirdShoeGaze/Routing/ChainRouter.swift b/Sources/LyrebirdShoeGaze/Routing/ChainRouter.swift index 0860596..2584763 100644 --- a/Sources/LyrebirdShoeGaze/Routing/ChainRouter.swift +++ b/Sources/LyrebirdShoeGaze/Routing/ChainRouter.swift @@ -104,6 +104,9 @@ public final class ChainRouter { private let engine: SynthesisEngine + /// Shared tempo clock, forwarded to both sub-boards so tempo-aware pedals quantize to beats. + private let clock: LyrebirdClock? + /// The shared input source (either a `TestLoopSource` or `HardwareInputPassThrough`). private let source: any Synthesizer @@ -152,9 +155,11 @@ public final class ChainRouter { /// - `EngineAddError` if the engine rejects any node insertion. public init( engine: SynthesisEngine, - inputSource: InputSource = .testLoop + inputSource: InputSource = .testLoop, + clock: LyrebirdClock? = nil ) throws { self.engine = engine + self.clock = clock // Step 1 — allocate the shared input bus. let inputBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) @@ -186,8 +191,8 @@ public final class ChainRouter { self.source = addedSource // Step 3 — create both boards (each allocates its own head bus). - let createdBoardA: PedalBoard = try PedalBoard(engine: engine) - let createdBoardB: PedalBoard = try PedalBoard(engine: engine) + let createdBoardA: PedalBoard = try PedalBoard(engine: engine, clock: clock) + let createdBoardB: PedalBoard = try PedalBoard(engine: engine, clock: clock) self.boardA = createdBoardA self.boardB = createdBoardB diff --git a/Sources/LyrebirdShoeGaze/ShoeGaze.swift b/Sources/LyrebirdShoeGaze/ShoeGaze.swift index 3ec26fb..109f13c 100644 --- a/Sources/LyrebirdShoeGaze/ShoeGaze.swift +++ b/Sources/LyrebirdShoeGaze/ShoeGaze.swift @@ -60,6 +60,11 @@ public final class ShoeGaze { /// The engine that owns all nodes. public let engine: SynthesisEngine + /// Shared tempo clock for the tempo indicator / tap-tempo and any future + /// tempo-synced features. Default `120` BPM. `reconfigureEngine(_:)` rebuilds boards + /// against the same `engine` instance, so this clock stays valid across reconfigures. + public let clock: LyrebirdClock + /// All boards managed by this instance. public private(set) var boards: [PedalBoard] = [] @@ -96,6 +101,34 @@ public final class ShoeGaze { /// (same module, different file) can mutate it. internal var recordTaps: [RecordTap] = [] + // MARK: - Tuner state + + /// `true` while the tuner is engaged (between `engageTuner()` and `disengageTuner()`). + public internal(set) var tunerEngaged: Bool = false + + /// Whether ``ShoeGaze/engageTuner()`` also mutes the rig output for the duration. + /// Defaults to `true`. Read and applied only at engage time — toggling this while + /// already engaged takes effect on the next engage/disengage cycle. + public var tunerMutesRig: Bool = true + + /// The active `TunerTap`, or `nil` while disengaged. `internal` so + /// `ShoeGaze+Tuner.swift` (same module, different file) can mutate it. + internal var tunerTap: TunerTap? + + /// The scratch control bus allocated for `tunerTap`'s unread passthrough output, + /// released on disengage. + internal var tunerScratchControlBus: ControlBus? + + /// `rigMuted`'s value at the moment `engageTuner()` muted the rig, so + /// `disengageTuner()` can restore it rather than always unmuting. + internal var tunerRestoreMuteOnDisengage: Bool = false + + // MARK: - Tempo state + + /// Timestamps of recent `tapTempo()` calls, oldest first. `internal` so + /// `ShoeGaze+Tempo.swift` (same module, different file) can mutate it. + internal var tapTimestamps: [Date] = [] + // MARK: - Scope state /// Scope tap over the hardware input + output buses, feeding the debug scope view. @@ -139,6 +172,7 @@ public final class ShoeGaze { ) { self.engine = engine self.inputSource = inputSource + clock = LyrebirdClock(engine: engine, bpm: ShoeGaze.defaultTempoBpm) installScopeTap() } @@ -162,7 +196,7 @@ public final class ShoeGaze { /// - `EngineAddError` if the engine rejects a node insertion. @discardableResult public func addBoard() throws -> PedalBoard { - let board: PedalBoard = try PedalBoard(engine: engine) + let board: PedalBoard = try PedalBoard(engine: engine, clock: clock) board.label = "Board \(boards.count + 1)" // Route the input source to the board head bus. @@ -463,6 +497,10 @@ public final class ShoeGaze { /// Removes a single board and its associated input source and output master from /// the engine, then releases the board's buses. The other boards are unaffected. /// + /// > Note: MIDI bindings address boards/pedals by UUID, so a removed board's bindings simply + /// > stop resolving (inert, and invisible in the mapping UI since there is no board/pedal to + /// > list) — no binding maintenance is needed here. + /// /// - Important: Same async-removal caveat as ``teardown()`` — call with the engine /// stopped, or accept up to one block of glitch on a still-running engine. /// @@ -548,7 +586,7 @@ public final class ShoeGaze { /// - `EngineAddError` if the engine rejects any node insertion. @discardableResult public func makeChainRouter() throws -> ChainRouter { - let router: ChainRouter = try ChainRouter(engine: engine, inputSource: inputSource) + let router: ChainRouter = try ChainRouter(engine: engine, inputSource: inputSource, clock: clock) routers.append(router) return router } diff --git a/Sources/LyrebirdShoeGaze/Tempo/ShoeGaze+Tempo.swift b/Sources/LyrebirdShoeGaze/Tempo/ShoeGaze+Tempo.swift new file mode 100644 index 0000000..b5cae06 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Tempo/ShoeGaze+Tempo.swift @@ -0,0 +1,55 @@ +// ShoeGaze+Tempo.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +// MARK: - ShoeGaze + Tempo + +extension ShoeGaze { + + /// Default tempo, in BPM, for a newly-created ``ShoeGaze/clock``. + public static let defaultTempoBpm: Double = 120.0 + + // MARK: - Tap tempo + + /// Minimum plausible interval between taps, in seconds — guards against a double-tap + /// or debounce glitch registering as an implausibly fast tempo (`60 / minTapInterval` + /// ≈ 300 BPM cap). + private static let minTapInterval: TimeInterval = 0.2 + + /// Maximum interval since the last tap before the tap history resets — a pause this + /// long means the user is starting a new tap-tempo sequence, not continuing one. + private static let tapTimeoutInterval: TimeInterval = 2.0 + + /// Number of most-recent inter-tap intervals averaged into the computed tempo. + private static let tapHistoryCount: Int = 4 + + /// Registers one tap-tempo press. Call this each time the user taps (mouse click, + /// screen tap, or MIDI trigger). Averages the last few inter-tap intervals and sets + /// ``ShoeGaze/clock``'s `bpm` once at least two taps have landed within + /// `tapTimeoutInterval` of each other. A pause longer than `tapTimeoutInterval` + /// discards prior taps and starts a fresh sequence. + public func tapTempo() { + let now: Date = Date() + if let last: Date = tapTimestamps.last, now.timeIntervalSince(last) > ShoeGaze.tapTimeoutInterval { + tapTimestamps.removeAll() + } + tapTimestamps.append(now) + if tapTimestamps.count > ShoeGaze.tapHistoryCount + 1 { + tapTimestamps.removeFirst(tapTimestamps.count - (ShoeGaze.tapHistoryCount + 1)) + } + guard tapTimestamps.count >= 2 else { return } + + let intervals: [TimeInterval] = zip(tapTimestamps, tapTimestamps.dropFirst()) + .map { $1.timeIntervalSince($0) } + .filter { $0 >= ShoeGaze.minTapInterval } + guard !intervals.isEmpty else { return } + + let averageInterval: TimeInterval = intervals.reduce(0, +) / Double(intervals.count) + let secondsPerMinute: Double = 60.0 + clock.bpm = secondsPerMinute / averageInterval + } +} diff --git a/Sources/LyrebirdShoeGaze/Tuner/ShoeGaze+Tuner.swift b/Sources/LyrebirdShoeGaze/Tuner/ShoeGaze+Tuner.swift new file mode 100644 index 0000000..10089f6 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Tuner/ShoeGaze+Tuner.swift @@ -0,0 +1,99 @@ +// ShoeGaze+Tuner.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import LyrebirdSynth + +// MARK: - ShoeGaze + Tuner + +extension ShoeGaze { + + // MARK: - Engage / disengage + + /// Engages the tuner: taps the clean pre-effects input and, if ``tunerMutesRig`` is on, + /// mutes the rig output for the duration (restoring the prior mute state on disengage). + /// + /// A no-op if already engaged. Prints a note and does nothing if no input bus can be + /// resolved (mirrors `startRecording()`'s tolerant `.liveInput`/`.testLoop` fallback). + public func engageTuner() { + guard !tunerEngaged else { return } + guard let busIndex: Int = resolvedInputBusIndex() else { + print("[ShoeGaze] engageTuner: no input bus available — tuner not engaged.") + return + } + + do { + // The scratch control bus is allocated once and kept for the session's + // lifetime rather than released on every disengage: `engine.remove(_:)` only + // enqueues the tap's removal for the next render block, so releasing (and + // thus making reallocatable) the bus synchronously here would race a + // not-yet-dequeued write from the outgoing tap. + let scratchBus: ControlBus + if let existing: ControlBus = tunerScratchControlBus { + scratchBus = existing + } else { + scratchBus = try engine.busAllocator.allocateControlBus() + tunerScratchControlBus = scratchBus + } + let tap: TunerTap = TunerTap(inputBusIndex: busIndex, scratchControlBus: scratchBus) + try engine.add(tap, position: .after(engine.mainGroup)) + tunerTap = tap + } catch { + print("[ShoeGaze] engageTuner: could not add tuner tap. (\(error))") + return + } + + if tunerMutesRig { + tunerRestoreMuteOnDisengage = rigMuted + setRigMuted(true) + } + tunerEngaged = true + } + + /// Disengages the tuner and removes its tap. Restores the rig's prior mute state if + /// ``engageTuner()`` muted it. + /// + /// The scratch control bus is intentionally NOT released here — see the comment in + /// ``engageTuner()``. + public func disengageTuner() { + guard tunerEngaged else { return } + if let tap: TunerTap = tunerTap { + _ = engine.remove(tap) + } + tunerTap = nil + + if tunerMutesRig { + setRigMuted(tunerRestoreMuteOnDisengage) + } + tunerEngaged = false + } + + /// Flips ``tunerEngaged`` — convenience for a single stomp-style toggle/MIDI action. + public func toggleTunerEngaged() { + if tunerEngaged { + disengageTuner() + } else { + engageTuner() + } + } + + // MARK: - Live pitch read + + /// The most recently detected pitch, in Hz, or `nil` while the tuner is not engaged. + /// Safe to poll from a SwiftUI `.task` loop on the main thread. + public var currentPitchHz: Double? { + guard tunerEngaged else { return nil } + return tunerTap?.pitchCapture?.detectedFrequencyHz + } + + /// The YIN tracking confidence in `[0, 1]` for the current pitch, or `nil` while the + /// tuner is not engaged. `1.0` = certain, `0.0` = no stable pitch. The UI latches its + /// display when this drops below its threshold (e.g. during a note attack/restrike). + public var currentPitchConfidence: Double? { + guard tunerEngaged else { return nil } + return tunerTap?.pitchCapture?.detectedConfidence + } +} diff --git a/Sources/LyrebirdShoeGaze/Tuner/TunerPitchCapture.swift b/Sources/LyrebirdShoeGaze/Tuner/TunerPitchCapture.swift new file mode 100644 index 0000000..fc80597 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Tuner/TunerPitchCapture.swift @@ -0,0 +1,103 @@ +// TunerPitchCapture.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import Synchronization + +/// Wraps a YIN `FreqTracker` and atomically snapshots its per-block frequency **and +/// confidence** into plain `Double`s readable from any thread — the same RT-writes/non-RT- +/// polls contract as `ParameterNode`'s atomic value storage, sized down to two scalars. +/// +/// YIN (via `FreqTracker`) is far steadier than zero-crossing detection on a plucked/ +/// harmonic-rich guitar signal, and its confidence output lets the UI latch the last stable +/// reading through low-confidence transients (note attacks, restrikes) instead of ramping +/// toward the new pitch. No smoothing is applied here — the raw YIN estimate is stable +/// enough, and any smoothing would re-introduce the ramp-on-restrike the latch is meant to +/// avoid. +/// +/// Bypasses the `ControlGenerator` sub-block ramp path (matching `SendTrigger.Control`'s +/// convention for side-effecting analysis generators). +final class TunerPitchCapture: GeneratorBase, ControlGenerator { + var previousOutputValue: Double = 0.0 + + /// Input decimation factor for the YIN tracker. Lowers the effective analysis rate so a + /// fixed 512-sample window reaches down to the low guitar / bass range. At 48 kHz, 8× + /// gives an effective 6 kHz rate → ~23 Hz detection floor. The caller (`TunerTap`) must + /// band-limit the input below the decimated Nyquist (`sampleRate / 16`) first. + static let decimation: Int = 8 + + /// YIN analysis window, in decimated samples (512 is `FreqTracker`'s RT-safe maximum). + private static let fftSize: Int = 512 + + /// Minimum tracked frequency in Hz — below standard bass E1 (≈41 Hz) for headroom. + private static let minFreqHz: Double = 38.0 + + /// Maximum tracked frequency in Hz — above guitar high-E (E4 ≈330 Hz) with room for + /// upper strings / light bends, and well below the decimated Nyquist. + private static let maxFreqHz: Double = 660.0 + + private let tracker: FreqTracker + private let _hzBits: Atomic + private let _confidenceBits: Atomic + + /// The most recent tracked frequency, in Hz. Safe to read from any thread. + var detectedFrequencyHz: Double { + Double(bitPattern: _hzBits.load(ordering: .acquiring)) + } + + /// The most recent tracking confidence in `[0, 1]`. Safe to read from any thread. + var detectedConfidence: Double { + Double(bitPattern: _confidenceBits.load(ordering: .acquiring)) + } + + /// - Parameter input: Signal to analyse for pitch — must already be band-limited below + /// the decimated Nyquist (see `TunerTap`, which applies the anti-alias lowpass). + init(input: any ValidGeneratorInput) { + let resolvedInput: any ValidGeneratorInput = input._resolvedInput() + tracker = FreqTracker( + in: resolvedInput, + fftSize: TunerPitchCapture.fftSize, + minFreq: TunerPitchCapture.minFreqHz, + maxFreq: TunerPitchCapture.maxFreqHz, + decimation: TunerPitchCapture.decimation + ) + _hzBits = Atomic(Double(0.0).bitPattern) + _confidenceBits = Atomic(Double(0.0).bitPattern) + super.init() + _setupSubBlockBuffer() + } + + // Bypass sub-block loop — one capture per audio block. `FreqTracker` processes the full + // block internally (per-sample ring fill + periodic YIN hops). + func calculatedSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _calculatedSamplesBlockRate(graph: graph, count: count) + } + + func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + // `_checkCount` only bounds the top; guard the empty block so the `count - 1` last-sample + // reads below can't index `-1` (engine blockSize is ≥1 today, so this is defensive). + guard count > 0 else { return _result } + // FreqTracker is a two-channel AudioGenerator: channel 0 = Hz, channel 1 = confidence. + // Both rows are fully populated for `count` samples. + let trackerBlock: [[Double]] = tracker.calculatedSamples(graph: graph, count: count) + let hz: Double = trackerBlock[0][count - 1] + let confidence: Double = trackerBlock[1][count - 1] + _hzBits.store(hz.bitPattern, ordering: .releasing) + _confidenceBits.store(confidence.bitPattern, ordering: .releasing) + previousOutputValue = hz + for i: Int in 0.. 0 else { return "--" } + let seconds: String = String(format: "%.2fs", lengthSeconds) + guard lengthBeats > 0 else { return seconds } + return seconds + " · \(Int(lengthBeats)) beat" + (lengthBeats == 1 ? "" : "s") + } +} diff --git a/Sources/LyrebirdShoeGazeUI/MIDIMappingSheet.swift b/Sources/LyrebirdShoeGazeUI/MIDIMappingSheet.swift index d2ca888..228bf1e 100644 --- a/Sources/LyrebirdShoeGazeUI/MIDIMappingSheet.swift +++ b/Sources/LyrebirdShoeGazeUI/MIDIMappingSheet.swift @@ -102,23 +102,22 @@ public struct MIDIMappingSheet: View { SwitchRowModel(id: "sw-mute", action: .rigMute, label: "Rig Mute"), SwitchRowModel(id: "sw-all", action: .allBoards, label: "All Boards On"), ] - for boardPair: (offset: Int, element: PedalBoard) in shoeGaze.boards.enumerated() { - let boardIndex: Int = boardPair.offset - let board: PedalBoard = boardPair.element - rows.append(SwitchRowModel(id: "sw-solo-\(boardIndex)", - action: .boardSolo(boardIndex: boardIndex), + for board: PedalBoard in shoeGaze.boards { + let boardID: UUID = board.id + rows.append(SwitchRowModel(id: "sw-solo-\(boardID)", + action: .boardSolo(boardID: boardID), label: "\(board.label) · Solo")) - rows.append(SwitchRowModel(id: "sw-aud-\(boardIndex)", - action: .boardAudible(boardIndex: boardIndex), + rows.append(SwitchRowModel(id: "sw-aud-\(boardID)", + action: .boardAudible(boardID: boardID), label: "\(board.label) · Audible")) - rows.append(SwitchRowModel(id: "sw-byp-\(boardIndex)", - action: .boardBypass(boardIndex: boardIndex), + rows.append(SwitchRowModel(id: "sw-byp-\(boardID)", + action: .boardBypass(boardID: boardID), label: "\(board.label) · Bypass")) - for pedalPair: (offset: Int, element: Pedal) in board.pedals.enumerated() { + for pedal: Pedal in board.pedals { rows.append(SwitchRowModel( - id: "sw-pb-\(boardIndex)-\(pedalPair.offset)", - action: .pedalBypass(boardIndex: boardIndex, pedalIndex: pedalPair.offset), - label: "\(board.label) · \(pedalPair.element.displayName) · Bypass")) + id: "sw-pb-\(pedal.id)", + action: .pedalBypass(pedalID: pedal.id), + label: "\(board.label) · \(pedal.displayName) · Bypass")) } } return rows @@ -128,23 +127,18 @@ public struct MIDIMappingSheet: View { var rows: [CCRowModel] = [ CCRowModel(id: "cc-rigvol", target: .rigVolume, label: "Rig · Volume"), ] - for boardPair: (offset: Int, element: PedalBoard) in shoeGaze.boards.enumerated() { - let boardIndex: Int = boardPair.offset - let board: PedalBoard = boardPair.element + for board: PedalBoard in shoeGaze.boards { // Board master level (the board fader). rows.append(CCRowModel( - id: "cc-blvl-\(boardIndex)", - target: .boardLevel(boardIndex: boardIndex, boardLabelHint: nil), + id: "cc-blvl-\(board.id)", + target: .boardLevel(boardID: board.id, boardLabelHint: nil), label: "\(board.label) · Level")) - for pedalPair: (offset: Int, element: Pedal) in board.pedals.enumerated() { - let pedalIndex: Int = pedalPair.offset - let pedal: Pedal = pedalPair.element + for pedal: Pedal in board.pedals { for controlPair: (offset: Int, element: PedalControl) in pedal.ccMappableControls.enumerated() { rows.append(CCRowModel( - id: "cc-\(boardIndex)-\(pedalIndex)-\(controlPair.offset)", + id: "cc-\(pedal.id)-\(controlPair.offset)", target: .pedalControl( - boardIndex: boardIndex, - pedalIndex: pedalIndex, + pedalID: pedal.id, controlIndex: controlPair.offset, pedalNameHint: nil, controlLabelHint: nil), diff --git a/Sources/LyrebirdShoeGazeUI/PedalButtonView.swift b/Sources/LyrebirdShoeGazeUI/PedalButtonView.swift new file mode 100644 index 0000000..8b1ac78 --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/PedalButtonView.swift @@ -0,0 +1,57 @@ +// PedalButtonView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import LyrebirdUI +import LyrebirdShoeGaze + +// MARK: - PedalButtonView + +/// A stomp-style action button rendered from a ``PedalButton`` descriptor. +/// +/// `.momentary` renders a plain `ParameterButton`. `.toggle` renders the same LED + +/// footswitch look as the pedal's own bypass control (`PedalView`'s `LEDIndicator` / +/// `FootswitchButton`), with a caption label beneath — so a looper's Overdub/Loop toggles +/// read as stomp switches with state, not a segmented picker. +/// +/// ## Usage +/// ```swift +/// PedalButtonView(pedalButton) +/// ``` +public struct PedalButtonView: View { + + private static let toggleOnThreshold: Double = 0.5 + private static let sectionSpacing: CGFloat = 6 + private static let captionFontSize: CGFloat = 11 + + private let pedalButton: PedalButton + + /// Creates a button view from a descriptor. + /// + /// - Parameter pedalButton: The button to render. + public init(_ pedalButton: PedalButton) { + self.pedalButton = pedalButton + } + + public var body: some View { + switch pedalButton.style { + case .momentary: + ParameterButton(pedalButton.label, action: pedalButton.action ?? {}) + case .toggle: + if let node: UIParamNode = pedalButton.node { + // Reading `node.value` registers this view for @Observable re-render. + let isOn: Bool = node.value >= PedalButtonView.toggleOnThreshold + VStack(spacing: PedalButtonView.sectionSpacing) { + LEDIndicator(isOn: isOn) + FootswitchButton(node: node) + Text(pedalButton.label) + .font(.system(size: PedalButtonView.captionFontSize)) + .foregroundStyle(Color.white) + } + } + } + } +} diff --git a/Sources/LyrebirdShoeGazeUI/PedalView.swift b/Sources/LyrebirdShoeGazeUI/PedalView.swift index b4ab481..a1be9f9 100644 --- a/Sources/LyrebirdShoeGazeUI/PedalView.swift +++ b/Sources/LyrebirdShoeGazeUI/PedalView.swift @@ -90,9 +90,11 @@ private struct ScrewDot: View { /// A small circular LED that glows green when the effect is engaged. /// -/// Bypass polarity: `0` = engaged (effect ON), `1` = bypassed. -/// The LED is lit when `bypassValue < 0.5`. -private struct LEDIndicator: View { +/// A small round LED, lit green when `isOn` and dark otherwise. Polarity-agnostic — the +/// caller decides what `isOn` means for its own control (e.g. bypass's `value < 0.5`, or a +/// plain toggle's `value >= 0.5`). `internal` (not `private`) so other views in this module +/// (e.g. `PedalButtonView`) can reuse the same stompbox LED look. +struct LEDIndicator: View { private static let diameter: CGFloat = 10 private static let glowRadius: CGFloat = 6 @@ -101,13 +103,11 @@ private struct LEDIndicator: View { private static let dimBrightness: Double = 0.15 private static let rimStrokeOpacity: Double = 0.30 - let bypassValue: Double - - private var isEngaged: Bool { bypassValue < 0.5 } + let isOn: Bool var body: some View { ZStack { - if isEngaged { + if isOn { Circle() .fill(Color.green.opacity(LEDIndicator.glowOpacity)) .frame( @@ -117,7 +117,7 @@ private struct LEDIndicator: View { .blur(radius: LEDIndicator.glowRadius / 2) } Circle() - .fill(isEngaged ? Color.green : Color(white: LEDIndicator.dimBrightness)) + .fill(isOn ? Color.green : Color(white: LEDIndicator.dimBrightness)) .frame(width: LEDIndicator.diameter, height: LEDIndicator.diameter) .overlay( Circle() @@ -132,8 +132,10 @@ private struct LEDIndicator: View { // MARK: - Footswitch -/// A round footswitch-style button that toggles bypass on/off. -private struct FootswitchButton: View { +/// A round footswitch-style button that flips a `UIParamNode` between `0` and `1`. +/// `internal` (not `private`) so other views in this module (e.g. `PedalButtonView`) can +/// reuse the same stompbox footswitch look for non-bypass toggles. +struct FootswitchButton: View { private static let diameter: CGFloat = 44 private static let strokeWidth: CGFloat = 2.5 @@ -291,9 +293,11 @@ public struct PedalView: View { // Content stack VStack(spacing: PedalView.sectionSpacing) { namePlate + looperTimeline knobGrid selectorRow switchRow + buttonRow sliderBank(sliders) Spacer(minLength: 0) bottomControls @@ -334,6 +338,15 @@ public struct PedalView: View { .clipShape(RoundedRectangle(cornerRadius: PedalView.namePlateCornerRadius)) } + /// Loop timeline strip — rendered only for the double-width `LooperPedal`, between the + /// name plate and the knob grid. Other pedals render nothing here. + @ViewBuilder + private var looperTimeline: some View { + if let looper: LooperPedal = pedal as? LooperPedal { + LooperTimelineView(pedal: looper) + } + } + /// Info button tucked just under the top-left corner screw. private var infoButton: some View { Button { @@ -417,6 +430,22 @@ public struct PedalView: View { } } + /// Row of stomp-style action buttons drawn from `pedal.effectButtons`, beneath the + /// switch row. Renders nothing when the pedal publishes no buttons. + @ViewBuilder + private var buttonRow: some View { + let buttons: [PedalButton] = pedal.effectButtons + if !buttons.isEmpty { + HStack(spacing: PedalView.knobRowItemSpacing) { + Spacer(minLength: 0) + ForEach(Array(buttons.enumerated()), id: \.offset) { pair in + PedalButtonView(pair.element) + } + Spacer(minLength: 0) + } + } + } + /// Row of vertical faders drawn from `pedal.effectSliders`, beneath the switch row. /// Renders nothing when the pedal publishes no sliders. @ViewBuilder @@ -431,16 +460,19 @@ public struct PedalView: View { } } - /// Enclosure width — the base stompbox width, widened to fit a wide vertical-fader bank - /// (e.g. a multi-band graphic EQ) so its faders are never clipped. + /// Enclosure width — the base stompbox width scaled by the pedal's `widthUnits` + /// (a control-dense pedal such as the looper asks for a double-width card), widened + /// further to fit a wide vertical-fader bank (e.g. a multi-band graphic EQ) so its + /// faders are never clipped. private func enclosureWidth(for sliders: [PedalSlider]) -> CGFloat { + let unitWidth: CGFloat = PedalView.enclosureWidth * CGFloat(max(1, pedal.widthUnits)) let sliderCount: Int = sliders.count - guard sliderCount > 0 else { return PedalView.enclosureWidth } + guard sliderCount > 0 else { return unitWidth } let bankContentWidth: CGFloat = CGFloat(sliderCount) * PedalView.sliderBankItemWidth + CGFloat(max(0, sliderCount - 1)) * PedalView.sliderBankSpacing let needed: CGFloat = bankContentWidth + 2 * PedalView.enclosurePadding - return max(PedalView.enclosureWidth, needed) + return max(unitWidth, needed) } /// Bottom control row: the `Level` knob, the bypass switch, and the `Mix` knob, @@ -479,9 +511,10 @@ public struct PedalView: View { // re-renders whenever the bypass parameter changes on the main thread // (UIParamNode is @Observable). let bypassValue: Double = pedal.$bypass.value + let engagedThreshold: Double = 0.5 return VStack(spacing: PedalView.bypassSectionSpacing) { - LEDIndicator(bypassValue: bypassValue) + LEDIndicator(isOn: bypassValue < engagedThreshold) FootswitchButton(node: pedal.$bypass) } } diff --git a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift index 04ef8da..7898438 100644 --- a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift +++ b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift @@ -533,9 +533,12 @@ public struct ShoeGazeBuilderView: View { private var transportRow: some View { _ = transportTick return HStack(spacing: ShoeGazeBuilderView.rowSpacing) { - Text("ShoeGaze Builder") - .font(.title2).bold() - .foregroundStyle(Color.white) + VStack(alignment: .leading, spacing: 1) { + Text("ShoeGaze Builder") + .font(.title2).bold() + .foregroundStyle(Color.white) + currentRigLabel + } if shoeGaze.isRecording { // Recording indicator (both platforms; recording is driven from the macOS Record // menu or the iOS controls below). @@ -549,6 +552,8 @@ public struct ShoeGazeBuilderView: View { } } Spacer() + TempoView(shoeGaze: shoeGaze) + TunerView(shoeGaze: shoeGaze) if let midi: MIDIController = midi { MIDIIndicatorView(controller: midi) { showMIDISheet = true } } @@ -729,6 +734,11 @@ public struct ShoeGazeBuilderView: View { let wasRunning: Bool = shoeGaze.engine.isRunning if wasRunning { shoeGaze.engine.stop() } + // Clearing the rig discards its MIDI bindings — they are addressed positionally and + // belong to the rig being cleared. Reset before rebuilding so stale bindings can't + // re-resolve onto the fresh board's pedals. + shoeGaze.midiMap = nil + // Snapshot before removing — removeBoard mutates shoeGaze.boards. for board: PedalBoard in Array(shoeGaze.boards) { shoeGaze.removeBoard(board) @@ -1096,6 +1106,32 @@ public struct ShoeGazeBuilderView: View { return library.entries.first(where: { $0.id == id })?.name } + /// A subtitle under the app title showing which rig is loaded. Resolves the name from the + /// library once it has loaded; shows "Unsaved rig" when the working graph has no source-rig + /// id (a cleared / never-saved session). Reads `shoeGaze.currentRigID` and `library.entries` + /// so it refreshes automatically when a rig is loaded or the library finishes loading. + private var currentRigLabel: some View { + let hasSource: Bool = currentRigID != nil + let name: String + if let resolved: String = currentRigName() { + name = resolved + } else if hasSource { + // Source id exists but the library hasn't resolved it yet (still loading). + name = library.isLoaded ? "Unknown rig" : "Loading…" + } else { + name = "Unsaved rig" + } + return HStack(spacing: 5) { + Image(systemName: hasSource ? "guitars.fill" : "guitars") + .font(.caption2) + Text(name) + .font(.caption) + .lineLimit(1) + } + .foregroundStyle(Color.white.opacity(hasSource ? 0.8 : 0.5)) + .help(hasSource ? "Loaded rig: \(name)" : "This rig has not been saved to the library yet") + } + /// A default name for a new rig: `"Rig N"` where N avoids collisions with existing names. private func defaultNewRigName() -> String { let base: String = "Rig" diff --git a/Sources/LyrebirdShoeGazeUI/TempoView.swift b/Sources/LyrebirdShoeGazeUI/TempoView.swift new file mode 100644 index 0000000..6418d37 --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/TempoView.swift @@ -0,0 +1,107 @@ +// TempoView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import LyrebirdSynth +import LyrebirdShoeGaze + +/// Tempo indicator: a BPM readout/stepper, a beat-synced flashing LED, and a tap area that +/// responds to mouse/touch taps (call ``ShoeGaze/tapTempo()`` directly for a MIDI trigger). +/// +/// Polls ``ShoeGaze/clock``'s `currentBeat` on a `.task` loop (matching the scope/CPU-meter +/// polling convention) since `LyrebirdClock` isn't `@Observable` — it's sample-accurate RT +/// state, not push-notified UI state. +public struct TempoView: View { + + // MARK: - Constants + + private static let pollIntervalNanoseconds: UInt64 = 33_333_333 // ~30 Hz + /// Fraction of each beat the LED stays lit — a short flash, not a 50% duty-cycle blink. + private static let flashDutyCycle: Double = 0.15 + private static let minBpm: Double = 30.0 + private static let maxBpm: Double = 300.0 + private static let bpmStep: Double = 1.0 + private static let ledDiameter: CGFloat = 16 + private static let panelSpacing: CGFloat = 10 + private static let rowSpacing: CGFloat = 14 + private static let tapAreaSize: CGFloat = 64 + + // MARK: - Properties + + private let shoeGaze: ShoeGaze + + @State private var displayedBpm: Double + @State private var ledOn: Bool = false + + // MARK: - Init + + /// - Parameter shoeGaze: The session whose ``ShoeGaze/clock`` this view displays and drives. + public init(shoeGaze: ShoeGaze) { + self.shoeGaze = shoeGaze + self._displayedBpm = State(initialValue: shoeGaze.clock.bpm) + } + + // MARK: - Body + + public var body: some View { + VStack(spacing: TempoView.panelSpacing) { + HStack(spacing: TempoView.rowSpacing) { + led + Text("\(Int(displayedBpm.rounded())) BPM") + .font(.system(size: 18, weight: .semibold, design: .rounded)) + .foregroundStyle(Color.white) + Stepper( + "", + value: Binding( + get: { displayedBpm }, + set: { newValue in + let clamped: Double = min(max(newValue, TempoView.minBpm), TempoView.maxBpm) + shoeGaze.clock.bpm = clamped + displayedBpm = clamped + } + ), + in: TempoView.minBpm ... TempoView.maxBpm, + step: TempoView.bpmStep + ) + .labelsHidden() + } + + tapArea + } + .task { + while !Task.isCancelled { + let beat: Double = shoeGaze.clock.currentBeat + let phase: Double = beat - beat.rounded(.down) + ledOn = phase < TempoView.flashDutyCycle + displayedBpm = shoeGaze.clock.bpm + try? await Task.sleep(nanoseconds: TempoView.pollIntervalNanoseconds) + } + } + } + + // MARK: - Subviews + + private var led: some View { + Circle() + .fill(ledOn ? Color.red : Color.red.opacity(0.15)) + .frame(width: TempoView.ledDiameter, height: TempoView.ledDiameter) + } + + private var tapArea: some View { + Button { + shoeGaze.tapTempo() + displayedBpm = shoeGaze.clock.bpm + } label: { + Text("TAP") + .font(.system(size: 14, weight: .bold, design: .rounded)) + .frame(width: TempoView.tapAreaSize, height: TempoView.tapAreaSize) + .background(Color.white.opacity(0.08)) + .clipShape(Circle()) + } + .buttonStyle(.plain) + .foregroundStyle(Color.white) + } +} diff --git a/Sources/LyrebirdShoeGazeUI/TunerView.swift b/Sources/LyrebirdShoeGazeUI/TunerView.swift new file mode 100644 index 0000000..b06bcf1 --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/TunerView.swift @@ -0,0 +1,210 @@ +// TunerView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import LyrebirdSynth +import LyrebirdShoeGaze + +/// Chromatic tuner panel: an engage toggle, a mute-rig-while-tuning toggle, and a live +/// note/cents readout. +/// +/// Polls ``ShoeGaze/currentPitchHz`` on a `.task` loop (matching `LyrebirdEngineStatusView`'s +/// CPU-meter convention) since the value is computed from RT-thread state on demand, not an +/// `@Observable`-tracked property. Polling only runs while the tuner is engaged. +public struct TunerView: View { + + // MARK: - Constants + + private static let pollIntervalNanoseconds: UInt64 = 250_000_000 // 4 Hz, at most + private static let inTuneCentsThreshold: Double = 5.0 + private static let closeCentsThreshold: Double = 15.0 + /// Below this YIN confidence the reading is treated as untracked — the last stable pitch + /// is latched and the display dims, rather than chasing a transient/attack estimate. + private static let trackingConfidenceThreshold: Double = 0.8 + /// Opacity applied to the latched readout while not actively tracking. + private static let untrackedOpacity: Double = 0.35 + private static let panelSpacing: CGFloat = 10 + private static let rowSpacing: CGFloat = 14 + private static let noteFontSize: CGFloat = 34 + private static let statusFontSize: CGFloat = 10 + + // MARK: - Properties + + private let shoeGaze: ShoeGaze + + /// Last pitch accepted at or above the confidence threshold (latched through dropouts). + @State private var latchedPitch: TunerPitchReading? + /// `true` when the most recent poll was above the confidence threshold. + @State private var isTracking: Bool = false + + // MARK: - Init + + /// - Parameter shoeGaze: The session whose tuner state this view controls and displays. + public init(shoeGaze: ShoeGaze) { + self.shoeGaze = shoeGaze + } + + // MARK: - Body + + public var body: some View { + VStack(spacing: TunerView.panelSpacing) { + HStack(spacing: TunerView.rowSpacing) { + Button(shoeGaze.tunerEngaged ? "Tuner: On" : "Tuner: Off") { + shoeGaze.toggleTunerEngaged() + } + .buttonStyle(.bordered) + .tint(shoeGaze.tunerEngaged ? .green : .gray) + + Toggle("Mute rig", isOn: Binding( + get: { shoeGaze.tunerMutesRig }, + set: { shoeGaze.tunerMutesRig = $0 } + )) + .toggleStyle(.switch) + } + + if shoeGaze.tunerEngaged { + readout + } + } + .task(id: shoeGaze.tunerEngaged) { + while shoeGaze.tunerEngaged && !Task.isCancelled { + updateReading() + try? await Task.sleep(nanoseconds: TunerView.pollIntervalNanoseconds) + } + if !shoeGaze.tunerEngaged { + latchedPitch = nil + isTracking = false + } + } + } + + /// Polls freq + confidence. Above the confidence threshold, updates the latched pitch + /// and marks tracking active; below it, leaves the latched pitch in place (so restrikes + /// don't make the reading ramp) and marks tracking inactive. + private func updateReading() { + let confidence: Double = shoeGaze.currentPitchConfidence ?? 0.0 + let hz: Double = shoeGaze.currentPitchHz ?? 0.0 + if confidence >= TunerView.trackingConfidenceThreshold && hz > 0 { + latchedPitch = TunerPitchReading(hz: hz) + isTracking = true + } else { + isTracking = false + } + } + + // MARK: - Readout + + @ViewBuilder + private var readout: some View { + if let pitch: TunerPitchReading = latchedPitch { + VStack(spacing: 6) { + Text(pitch.noteName) + .font(.system(size: TunerView.noteFontSize, weight: .bold, design: .rounded)) + .foregroundStyle(TunerView.color(forCents: pitch.cents)) + TunerCentsMeter(cents: pitch.cents) + Text(isTracking ? "TRACKING" : "…") + .font(.system(size: TunerView.statusFontSize, weight: .semibold, design: .monospaced)) + .foregroundStyle(Color.white.opacity(0.5)) + } + .opacity(isTracking ? 1.0 : TunerView.untrackedOpacity) + } else { + VStack(spacing: 6) { + Text("—") + .font(.system(size: TunerView.noteFontSize, weight: .bold, design: .rounded)) + .foregroundStyle(Color.white.opacity(0.4)) + Text("play a note") + .font(.system(size: TunerView.statusFontSize, weight: .semibold, design: .monospaced)) + .foregroundStyle(Color.white.opacity(0.4)) + } + } + } + + static func color(forCents cents: Double) -> Color { + let magnitude: Double = abs(cents) + if magnitude <= TunerView.inTuneCentsThreshold { return .green } + if magnitude <= TunerView.closeCentsThreshold { return .yellow } + return .red + } +} + +// MARK: - TunerCentsMeter + +/// A horizontal -50…+50 cents meter: a track with a centre "in tune" tick and a vertical +/// marker positioned at the current deviation, coloured with the same red/yellow/green +/// thresholds as the note readout. +struct TunerCentsMeter: View { + + private static let range: Double = 50.0 + private static let trackWidth: CGFloat = 140 + private static let trackHeight: CGFloat = 4 + private static let markerWidth: CGFloat = 3 + private static let markerHeight: CGFloat = 18 + private static let centerTickWidth: CGFloat = 1.5 + private static let centerTickHeight: CGFloat = 10 + + let cents: Double + + private var clampedFraction: Double { + // Maps [-range, +range] to [0, 1]; values beyond the range pin to the edge. + let clamped: Double = min(max(cents, -TunerCentsMeter.range), TunerCentsMeter.range) + return (clamped + TunerCentsMeter.range) / (2.0 * TunerCentsMeter.range) + } + + var body: some View { + GeometryReader { geometry in + let width: CGFloat = geometry.size.width + let markerX: CGFloat = width * clampedFraction + + ZStack(alignment: .leading) { + // Track. + RoundedRectangle(cornerRadius: TunerCentsMeter.trackHeight / 2) + .fill(Color.white.opacity(0.15)) + .frame(height: TunerCentsMeter.trackHeight) + .frame(maxWidth: .infinity) + + // Centre "in tune" reference tick. + Rectangle() + .fill(Color.white.opacity(0.5)) + .frame(width: TunerCentsMeter.centerTickWidth, height: TunerCentsMeter.centerTickHeight) + .position(x: width / 2, y: TunerCentsMeter.trackHeight / 2) + + // Deviation marker. + Rectangle() + .fill(TunerView.color(forCents: cents)) + .frame(width: TunerCentsMeter.markerWidth, height: TunerCentsMeter.markerHeight) + .position(x: markerX, y: TunerCentsMeter.trackHeight / 2) + } + } + .frame(width: TunerCentsMeter.trackWidth, height: TunerCentsMeter.markerHeight) + } +} + +// MARK: - TunerPitchReading + +/// Converts a detected frequency into the nearest chromatic note name, octave, and cents +/// deviation. Standard 12-TET sharp spelling — a tuner display doesn't need the full +/// spelling-aware `NoteName`/`Scale` theory toolkit (that's for compositional notation). +struct TunerPitchReading { + private static let chromaticNames: [String] = [ + "C", "C♯", "D", "D♯", "E", "F", "F♯", "G", "G♯", "A", "A♯", "B", + ] + private static let semitonesPerOctave: Int = 12 + private static let midiOctaveOffset: Int = 1 // MIDI note 0 = C-1 + private static let centsPerSemitone: Double = 100.0 + + let noteName: String + let cents: Double + + init(hz: Double) { + let midi: Double = hzToMidi(hz) + let nearestMidi: Int = Int(midi.rounded()) + cents = (midi - Double(nearestMidi)) * TunerPitchReading.centsPerSemitone + let pitchClass: Int = ((nearestMidi % TunerPitchReading.semitonesPerOctave) + + TunerPitchReading.semitonesPerOctave) % TunerPitchReading.semitonesPerOctave + let octave: Int = nearestMidi / TunerPitchReading.semitonesPerOctave - TunerPitchReading.midiOctaveOffset + noteName = "\(TunerPitchReading.chromaticNames[pitchClass])\(octave)" + } +} diff --git a/Tests/LyrebirdShoeGazeTests/LooperPedalTests.swift b/Tests/LyrebirdShoeGazeTests/LooperPedalTests.swift new file mode 100644 index 0000000..a84f5a1 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/LooperPedalTests.swift @@ -0,0 +1,492 @@ +// LooperPedalTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +import LyrebirdSynth +import LyrebirdUI +@testable import LyrebirdShoeGaze + +@MainActor +@Suite("LooperPedal") +struct LooperPedalTests { + + // MARK: - Test fixtures + + /// A constant-frequency sine source with a live-settable amplitude, so tests can + /// silence the live input at an exact scheduled time and attribute any remaining + /// output unambiguously to the looper's own playback. + private final class ToneSource: SynthesizerBase { + let ampNode: ParameterNode = ParameterNode(0.3) + var amplitude: Double { + get { ampNode.value } + set { ampNode.value = newValue } + } + private let targetBus: Int + private let toneFreq: Double + + init(targetBus: Int, freq: Double = 220.0) { + self.targetBus = targetBus + self.toneFreq = freq + super.init() + } + + override func build() { + output(bus: targetBus, source: OscSin.Audio(freq: toneFreq) * ampNode) + } + } + + /// A no-audio synth that posts a `TriggerEvent` (via `SendTrigger.Control`) at an exact + /// sample-accurate time within a single continuous NRT render. `build()` runs eagerly at + /// `engine.add(_:)` time, but the *trigger* it wires only fires once its own `Line.Control` + /// ramp crosses zero at `fireTime` seconds — so combined with a `TriggerListener` handler, + /// this is how tests schedule an exact-time side effect (e.g. flipping a looper transport + /// action) mid-render. + private final class TimedTrigger: SynthesizerBase { + private let fireTime: Double + private let triggerID: Int32 + private static let minRampDuration: Double = 0.001 + + init(fireTime: Double, id: Int32) { + self.fireTime = fireTime + self.triggerID = id + super.init() + } + + override func build() { + let rampDuration: Double = max(fireTime, TimedTrigger.minRampDuration) * 2.0 + let ramp: Line.Control = Line.Control(start: -1.0, end: 1.0, dur: rampDuration) + _ = SendTrigger.Control(trig: ramp, id: triggerID) + } + } + + private func rms(_ samples: [Float]) -> Double { + guard !samples.isEmpty else { return 0 } + let sumSquares: Double = samples.reduce(0) { $0 + Double($1) * Double($1) } + return (sumSquares / Double(samples.count)).squareRoot() + } + + /// Builds a fresh engine + `ToneSource` + `LooperPedal` + master, lets the caller register + /// exact-time actions via `scheduleAction`, then renders and returns the stereo samples. + private func render( + totalDuration: Double, + toneAmplitude: Double = 0.3, + sampleRate: Double = 44100.0, + configure: ( + _ engine: SynthesisEngine, + _ source: ToneSource, + _ pedal: LooperPedal, + _ scheduleAction: (Double, @escaping @MainActor @Sendable () -> Void) throws -> Void + ) throws -> Void + ) throws -> [Float] { + let url: URL = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString + ".caf") + defer { try? FileManager.default.removeItem(at: url) } + + let driver: NRTDriver = NRTDriver(outputURL: url, duration: totalDuration) + let numAudioBuses: Int = 64 + let numControlBuses: Int = 512 + let engine: SynthesisEngine = SynthesisEngine( + blockSize: 512, + sampleRate: sampleRate, + numOutputChannels: 2, + numInputChannels: 0, + numAudioBuses: numAudioBuses, + numControlBuses: numControlBuses, + driver: driver + ) + let listener: TriggerListener = TriggerListener(engine: engine) + driver.triggerListener = listener + + let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) + let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) + defer { + engine.busAllocator.releaseAudioBus(srcBus) + engine.busAllocator.releaseAudioBus(dstBus) + } + + let source: ToneSource = ToneSource(targetBus: srcBus.index) + source.amplitude = toneAmplitude + let pedal: LooperPedal = LooperPedal(inputBus: srcBus.index, outputBus: dstBus.index) + let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index) + + try engine.add(source) + try engine.add(pedal, position: NodePosition.after(source)) + try engine.add(master, position: NodePosition.after(pedal)) + + var nextTriggerID: Int32 = 0 + let scheduleAction: (Double, @escaping @MainActor @Sendable () -> Void) throws -> Void = { time, action in + nextTriggerID += 1 + let id: Int32 = nextTriggerID + let trigger: TimedTrigger = TimedTrigger(fireTime: time, id: id) + try engine.add(trigger) + listener.addHandler(id: id) { _, _ in + // `_drainSync` calls this inline, synchronously, on the same thread that + // called `engine.start()` in NRT mode — which is this MainActor test method. + MainActor.assumeIsolated { action() } + } + } + + try configure(engine, source, pedal, scheduleAction) + + try engine.start() + return readStereoCAF(url: url, sampleRate: sampleRate) + } + + // MARK: - Tests + + @Test func emptyPhasePassesDryThrough() throws { + let samples: [Float] = try render(totalDuration: 0.2) { _, _, _, _ in } + #expect(hasNonSilentOutput(samples), "Looper in .empty phase should pass the dry signal through") + } + + @Test func recordThenPlayReproducesLoopContentAfterInputGoesSilent() throws { + let recordDuration: Double = 0.1 + let totalDuration: Double = 0.6 + + let samples: [Float] = try render(totalDuration: totalDuration) { engine, source, pedal, scheduleAction in + // Begin recording immediately (post-build, pre-start): sample 0 of the render. + pedal.toggleRecordStop() + // Stop recording and start looping at `recordDuration`; silence the live input + // at the same instant so anything heard afterward can only be the looped take. + try scheduleAction(recordDuration) { pedal.toggleRecordStop() } + try scheduleAction(recordDuration) { source.amplitude = 0.0 } + } + + // Look well past the crossfade convergence window so only loop content remains. + let tailStart: Int = Int(Double(samples.count) * 0.75) + let tail: [Float] = Array(samples[tailStart...]) + #expect(hasNonSilentOutput(tail), "Loop should keep playing after the live input is silenced") + } + + @Test func loopLengthBoundsPlaybackToRecordedTakeNotFullBuffer() throws { + // Record a very short take, then render well beyond it with the input silenced. + // Continuous non-silence over that long tail proves playback wraps at the + // narrow recorded length, not the full 60 s allocation. + let recordDuration: Double = 0.05 + let totalDuration: Double = 1.0 + + let samples: [Float] = try render(totalDuration: totalDuration) { engine, source, pedal, scheduleAction in + pedal.toggleRecordStop() + try scheduleAction(recordDuration) { pedal.toggleRecordStop() } + try scheduleAction(recordDuration) { source.amplitude = 0.0 } + } + + let lateWindowStart: Int = Int(Double(samples.count) * 0.9) + let lateWindow: [Float] = Array(samples[lateWindowStart...]) + #expect(hasNonSilentOutput(lateWindow), "Loop should still be wrapping near the end of a 1 s render from a 0.05 s take") + } + + @Test func overdubAddsEnergyToTheLoop() throws { + let recordDuration: Double = 0.1 + let overdubStart: Double = 0.2 + let overdubDuration: Double = 0.1 + let totalDuration: Double = 0.9 + + let samples: [Float] = try render(totalDuration: totalDuration) { engine, source, pedal, scheduleAction in + pedal.toggleRecordStop() + try scheduleAction(recordDuration) { pedal.toggleRecordStop() } + try scheduleAction(overdubStart) { pedal.overdubOn = 1.0 } + try scheduleAction(overdubStart + overdubDuration) { pedal.overdubOn = 0.0 } + // Silence the live input once overdubbing is done so the measurement window + // reflects only what is now baked into the loop. + try scheduleAction(overdubStart + overdubDuration) { source.amplitude = 0.0 } + } + + let stride: Int = 2 // interleaved stereo + let measureStart: Double = 0.6 + let measureStartIndex: Int = Int(measureStart * 44100.0) * stride + guard measureStartIndex < samples.count else { + Issue.record("Render too short to measure post-overdub loop content") + return + } + let measured: [Float] = Array(samples[measureStartIndex...]) + #expect(hasNonSilentOutput(measured), "Loop should contain audible content after an overdub pass") + } + + @Test func resetLoopClearsContentAndReturnsToPassthrough() throws { + let recordDuration: Double = 0.1 + let resetAt: Double = 0.2 + let totalDuration: Double = 0.5 + + let samples: [Float] = try render(totalDuration: totalDuration) { engine, source, pedal, scheduleAction in + pedal.toggleRecordStop() + try scheduleAction(recordDuration) { pedal.toggleRecordStop() } + try scheduleAction(resetAt) { pedal.resetLoop() } + // Silence the input after reset — the loop is gone, so output should be silent. + try scheduleAction(resetAt) { source.amplitude = 0.0 } + } + + let tailStart: Int = Int(Double(samples.count) * 0.85) + let tail: [Float] = Array(samples[tailStart...]) + #expect(!hasNonSilentOutput(tail), "After reset + silenced input, no leftover loop content should remain") + } + + @Test func loopOffMutesLoopButKeepsLivePassthrough() throws { + let recordDuration: Double = 0.1 + let loopOffAt: Double = 0.2 + let totalDuration: Double = 0.5 + + let samples: [Float] = try render(totalDuration: totalDuration) { engine, source, pedal, scheduleAction in + pedal.toggleRecordStop() + try scheduleAction(recordDuration) { pedal.toggleRecordStop() } + try scheduleAction(loopOffAt) { pedal.loopOn = 0.0 } + // Keep the live tone audible (do not silence it) — loopOn muting the loop + // should not also silence the live passthrough. + } + + let tailStart: Int = Int(Double(samples.count) * 0.9) + let tail: [Float] = Array(samples[tailStart...]) + #expect(hasNonSilentOutput(tail), "Muting the loop should not silence the live passthrough") + } + + @Test func playbackLevelAttenuatesLoopOutput() throws { + let recordDuration: Double = 0.1 + let totalDuration: Double = 0.5 + + func renderLoop(playbackLevelDb: Double) throws -> [Float] { + try render(totalDuration: totalDuration) { engine, source, pedal, scheduleAction in + pedal.playbackLevel = playbackLevelDb + pedal.toggleRecordStop() + try scheduleAction(recordDuration) { pedal.toggleRecordStop() } + try scheduleAction(recordDuration) { source.amplitude = 0.0 } + } + } + + let unityRMS: Double = rms(try renderLoop(playbackLevelDb: 0.0)) + let attenuatedRMS: Double = rms(try renderLoop(playbackLevelDb: -6.0)) + #expect(attenuatedRMS < unityRMS, "-6 dB playback level should be quieter than 0 dB") + let expectedRatio: Double = dbToAmp(-6.0) + let tolerance: Double = 0.15 + let actualRatio: Double = attenuatedRMS / unityRMS + #expect( + abs(actualRatio - expectedRatio) < tolerance, + "Expected ~\(expectedRatio) amplitude ratio at -6 dB, got \(actualRatio)" + ) + } + + @Test func overdubLevelScalesOnlyTheNewMaterial() throws { + let recordDuration: Double = 0.1 + let overdubStart: Double = 0.2 + let overdubDuration: Double = 0.1 + let totalDuration: Double = 0.5 + + func renderOverdub(overdubLevelDb: Double) throws -> [Float] { + try render(totalDuration: totalDuration, toneAmplitude: 0.0) { engine, source, pedal, scheduleAction in + // Record silence for the initial take so the loop starts at zero content — + // isolates the overdub pass's own level. + pedal.overdubLevel = overdubLevelDb + pedal.toggleRecordStop() + try scheduleAction(recordDuration) { pedal.toggleRecordStop() } + try scheduleAction(overdubStart) { source.amplitude = 0.3 } + try scheduleAction(overdubStart) { pedal.overdubOn = 1.0 } + try scheduleAction(overdubStart + overdubDuration) { pedal.overdubOn = 0.0 } + try scheduleAction(overdubStart + overdubDuration) { source.amplitude = 0.0 } + } + } + + let unityRMS: Double = rms(try renderOverdub(overdubLevelDb: 0.0)) + let attenuatedRMS: Double = rms(try renderOverdub(overdubLevelDb: -6.0)) + #expect(attenuatedRMS < unityRMS, "-6 dB overdub level should bake in less energy than 0 dB") + } + + @Test func exposesLooperControls() throws { + let pedal: LooperPedal = LooperPedal() + #expect(pedal.effectKnobs.map { $0.label } == ["Crossfade", "Playback", "Overdub", "Feedback"]) + #expect(pedal.effectSwitches.isEmpty) + #expect(pedal.effectButtons.map { $0.label } == + ["Record / Stop", "Overdub", "Undo", "Loop", "Reverse", "Reset"]) + } + + @Test func looperIsDoubleWidth() throws { + #expect(LooperPedal().widthUnits == 2) + } + + @Test func readoutsReflectRecordedTakeLength() throws { + let recordDuration: Double = 0.1 + let sampleRate: Double = 44100.0 + var captured: LooperPedal? + + _ = try render(totalDuration: 0.4, sampleRate: sampleRate) { engine, source, pedal, scheduleAction in + captured = pedal + // Surface the engine clock so the play-head anchor and read-outs are live. + pedal.hostEngine = engine + pedal.toggleRecordStop() + try scheduleAction(recordDuration) { pedal.toggleRecordStop() } + try scheduleAction(recordDuration) { source.amplitude = 0.0 } + } + + let pedal: LooperPedal = try #require(captured) + #expect(pedal.transportState == .playing) + // No clock injected → un-quantized fallback trims to the recorder's frame count. + let expectedFrames: Double = recordDuration * sampleRate + // Recorder stop is snapshot at block rate, so allow one block of slop. + let renderBlockSize: Double = 512.0 + let tolerance: Double = renderBlockSize + #expect(abs(Double(pedal.loopFrameCount) - expectedFrames) < tolerance, + "loopFrameCount \(pedal.loopFrameCount) should be ~\(expectedFrames)") + #expect(abs(pedal.loopLengthSeconds - recordDuration) < 0.02) + #expect(pedal.loopLengthBeats == 0.0, "No clock → no beat-length read-out") + let position: Double? = pedal.playbackPosition01() + #expect(position != nil && position! >= 0.0 && position! < 1.0) + } + + @Test func transportStartsEmptyAndReturnsEmptyAfterReset() throws { + let pedal: LooperPedal = LooperPedal() + #expect(pedal.transportState == .empty) + #expect(pedal.playbackPosition01() == nil) + pedal.resetLoop() + #expect(pedal.transportState == .empty) + } + + @Test func undoOverdubRestoresPreDubLoopEnergy() throws { + let recordDuration: Double = 0.1 + let overdubStart: Double = 0.2 + let overdubDuration: Double = 0.1 + let totalDuration: Double = 0.9 + let measureStart: Double = 0.6 + + func tailRMS(undo: Bool) throws -> Double { + let samples: [Float] = try render(totalDuration: totalDuration) { engine, source, pedal, scheduleAction in + pedal.toggleRecordStop() + try scheduleAction(recordDuration) { pedal.toggleRecordStop() } + // Engage overdub via the transport action so a pre-dub snapshot is captured. + try scheduleAction(overdubStart) { pedal.toggleOverdub() } + try scheduleAction(overdubStart + overdubDuration) { pedal.toggleOverdub() } + if undo { + try scheduleAction(overdubStart + overdubDuration) { pedal.undoOverdub() } + } + try scheduleAction(overdubStart + overdubDuration) { source.amplitude = 0.0 } + } + let startIndex: Int = Int(measureStart * 44100.0) * 2 + guard startIndex < samples.count else { return 0 } + return rms(Array(samples[startIndex...])) + } + + let dubbedRMS: Double = try tailRMS(undo: false) + let undoneRMS: Double = try tailRMS(undo: true) + #expect(undoneRMS < dubbedRMS, + "Undo should remove the overdubbed layer's energy (undone \(undoneRMS) < dubbed \(dubbedRMS))") + } + + /// Builds an engine with the pedal added (so `effect()` allocates its buffer + recorders) + /// but does NOT start it, so the beat-quantized callbacks can be driven deterministically. + private func makeQuantizedFixture(bpm: Double, sampleRate: Double) + throws -> (engine: SynthesisEngine, clock: LyrebirdClock, pedal: LooperPedal) { + let url: URL = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString + ".caf") + let driver: NRTDriver = NRTDriver(outputURL: url, duration: 0.1) + let engine: SynthesisEngine = SynthesisEngine( + blockSize: 512, + sampleRate: sampleRate, + numOutputChannels: 2, + numInputChannels: 0, + numAudioBuses: 64, + numControlBuses: 512, + driver: driver + ) + let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) + let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) + let source: ToneSource = ToneSource(targetBus: srcBus.index) + let pedal: LooperPedal = LooperPedal(inputBus: srcBus.index, outputBus: dstBus.index) + try engine.add(source) + try engine.add(pedal, position: NodePosition.after(source)) + // Inject the tempo clock + engine the way PedalBoard.add would. `Pedal.clock` is weak + // (owned by ShoeGaze in production), so the caller must keep the returned clock alive. + let clock: LyrebirdClock = LyrebirdClock(engine: engine, bpm: bpm) + pedal.clock = clock + pedal.hostEngine = engine + pedal.sampleRate = sampleRate + return (engine, clock, pedal) + } + + @Test func beatQuantizedTransportProgressesAndReportsWholeBeatLength() throws { + let sampleRate: Double = 44100.0 + let bpm: Double = 120.0 // 22 050 frames per beat + let (_, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) = + try makeQuantizedFixture(bpm: bpm, sampleRate: sampleRate) + // Keep the (weak-referenced) clock alive for the whole test. + withExtendedLifetime(clock) { + #expect(pedal.transportState == .empty) + + // A record press with a clock present arms for the next beat, not immediately. + pedal.toggleRecordStop() + #expect(pedal.transportState == .armedRecord) + + // Simulate the routine firing on the beat-1 boundary (0.5 s at 120 BPM). + let startSample: SampleTime = SampleTime(sampleRate * 0.5) + pedal.beginRecording(at: startSample) + #expect(pedal.transportState == .recording) + + // Stop press arms; simulate the close on the beat-5 boundary (2.5 s → a 4-beat loop). + pedal.toggleRecordStop() + #expect(pedal.transportState == .armedStop) + let stopSample: SampleTime = SampleTime(sampleRate * 2.5) + pedal.finishRecordingAndPlay(at: stopSample) + + #expect(pedal.transportState == .playing) + #expect(pedal.loopFrameCount == Int(stopSample - startSample)) + #expect(pedal.loopLengthBeats == 4.0, "2.0 s at 120 BPM is exactly 4 beats") + + pedal.resetLoop() + #expect(pedal.transportState == .empty) + #expect(pedal.loopLengthBeats == 0.0) + } + } + + @Test func staleUndoRestoreIsDroppedWhenGenerationAdvances() throws { + let sampleRate: Double = 44100.0 + let (_, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) = + try makeQuantizedFixture(bpm: 120.0, sampleRate: sampleRate) + withExtendedLifetime(clock) { + // Get to a playing loop so a buffer + non-zero length exist. + pedal.toggleRecordStop() + pedal.beginRecording(at: SampleTime(sampleRate * 0.5)) + pedal.toggleRecordStop() + pedal.finishRecordingAndPlay(at: SampleTime(sampleRate * 2.5)) + + // A snapshot armed under the current generation… + let snapshot: [Double] = [Double](repeating: 0.5, count: 64) + let staleGeneration: Int = pedal.transportGeneration + + // …is superseded by a reset (which bumps the generation and clears the buffer). + pedal.resetLoop() + + // The deferred restore must now be a no-op: it must not reintroduce audio into the + // buffer the user just cleared. + pedal.applyUndoRestore(snapshot, generation: staleGeneration) + #expect(pedal.transportState == .empty) + #expect(pedal.loopFrameCount == 0) + } + } + + @Test func beatsForSpanRoundsToWholeBeats() throws { + let sampleRate: Double = 48000.0 + let bpm: Double = 100.0 // 28 800 frames per beat + let (_, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) = + try makeQuantizedFixture(bpm: bpm, sampleRate: sampleRate) + let framesPerBeat: Int = 28_800 + #expect(pedal.beatsForSpan(frames: framesPerBeat * 3, clock: clock) == 3.0) + #expect(pedal.beatsForSpan(frames: framesPerBeat * 8, clock: clock) == 8.0) + } + + @Test func reverseKeepsLoopAudible() throws { + let recordDuration: Double = 0.1 + let reverseAt: Double = 0.2 + let totalDuration: Double = 0.6 + + let samples: [Float] = try render(totalDuration: totalDuration) { engine, source, pedal, scheduleAction in + pedal.toggleRecordStop() + try scheduleAction(recordDuration) { pedal.toggleRecordStop() } + try scheduleAction(reverseAt) { pedal.reverse = 1.0 } + try scheduleAction(reverseAt) { source.amplitude = 0.0 } + } + + let tailStart: Int = Int(Double(samples.count) * 0.85) + let tail: [Float] = Array(samples[tailStart...]) + #expect(hasNonSilentOutput(tail), "Reverse playback should keep the loop audible") + } +} diff --git a/Tests/LyrebirdShoeGazeTests/MIDIControllerCCTests.swift b/Tests/LyrebirdShoeGazeTests/MIDIControllerCCTests.swift index 80bc468..6ecf894 100644 --- a/Tests/LyrebirdShoeGazeTests/MIDIControllerCCTests.swift +++ b/Tests/LyrebirdShoeGazeTests/MIDIControllerCCTests.swift @@ -27,28 +27,28 @@ struct MIDIControllerCCTests { return (controller, sg, board, url) } - /// An address-only pedal-control CC target (hints filled at capture time). - private func pedalControl(_ board: Int, _ pedal: Int, _ control: Int) -> MIDIMap.CCTarget { - .pedalControl(boardIndex: board, pedalIndex: pedal, controlIndex: control, + /// An address-only pedal-control CC target by pedal id (hints filled at capture time). + private func pedalControl(_ pedalID: UUID, _ control: Int) -> MIDIMap.CCTarget { + .pedalControl(pedalID: pedalID, controlIndex: control, pedalNameHint: nil, controlLabelHint: nil) } @Test func learnCapturesBindingAndFiresCallback() throws { - let (controller, sg, _, url): (MIDIController, ShoeGaze, PedalBoard, URL) = try makeRig() + let (controller, sg, board, url): (MIDIController, ShoeGaze, PedalBoard, URL) = try makeRig() defer { try? FileManager.default.removeItem(at: url) } var mapChanged: Bool = false controller.onMapChanged = { mapChanged = true } // Position is control 0 on a Volume pedal. - controller.armCCLearn(pedalControl(0, 0, 0)) + controller.armCCLearn(pedalControl(board.pedals[0].id, 0)) controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 64)) #expect(controller.learnTarget == nil, "learn should clear after capture") #expect(mapChanged, "onMapChanged should fire on capture") - let binding: MIDIMap.CCBinding? = controller.ccBinding(for: pedalControl(0, 0, 0)) + let binding: MIDIMap.CCBinding? = controller.ccBinding(for: pedalControl(board.pedals[0].id, 0)) #expect(binding?.controller == 20) - if case .pedalControl(_, _, _, let nameHint, let labelHint)? = binding?.target { + if case .pedalControl(_, _, let nameHint, let labelHint)? = binding?.target { #expect(nameHint == "Volume") #expect(labelHint == "Position") } else { @@ -64,7 +64,7 @@ struct MIDIControllerCCTests { defer { try? FileManager.default.removeItem(at: url) } withExtendedLifetime(sg) { - controller.armCCLearn(pedalControl(0, 0, 0)) + controller.armCCLearn(pedalControl(board.pedals[0].id, 0)) controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0)) let node: UIParamNode = board.pedals[0].ccMappableControls[0].node // Position, 0...1 @@ -86,7 +86,7 @@ struct MIDIControllerCCTests { Issue.record("board should have a master-gain node after finalize") return } - let target: MIDIMap.CCTarget = .boardLevel(boardIndex: 0, boardLabelHint: nil) + let target: MIDIMap.CCTarget = .boardLevel(boardID: board.id, boardLabelHint: nil) controller.armCCLearn(target) controller.ingestForTesting(.controlChange(channel: 0, controller: 11, value: 0)) // learn controller.ingestForTesting(.controlChange(channel: 0, controller: 11, value: 127)) @@ -113,7 +113,7 @@ struct MIDIControllerCCTests { let sliderIndex: Int = pedal.knobs.count // first control past the knobs is a slider let control: PedalControl = pedal.ccMappableControls[sliderIndex] - controller.armCCLearn(pedalControl(0, 0, sliderIndex)) + controller.armCCLearn(pedalControl(pedal.id, sliderIndex)) controller.ingestForTesting(.controlChange(channel: 0, controller: 30, value: 0)) controller.ingestForTesting(.controlChange(channel: 0, controller: 30, value: 127)) #expect(abs(control.node.value - control.range.upperBound) < 1e-9, @@ -126,10 +126,10 @@ struct MIDIControllerCCTests { defer { try? FileManager.default.removeItem(at: url) } withExtendedLifetime(sg) { - controller.armCCLearn(pedalControl(0, 0, 0)) + controller.armCCLearn(pedalControl(board.pedals[0].id, 0)) controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0)) - controller.setCCInverted(for: pedalControl(0, 0, 0), true) - #expect(controller.isCCInverted(for: pedalControl(0, 0, 0))) + controller.setCCInverted(for: pedalControl(board.pedals[0].id, 0), true) + #expect(controller.isCCInverted(for: pedalControl(board.pedals[0].id, 0))) let node: UIParamNode = board.pedals[0].ccMappableControls[0].node controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 127)) @@ -147,15 +147,15 @@ struct MIDIControllerCCTests { withExtendedLifetime(sg) { // Control 0 = Position, control 1 = Mix on a Volume pedal. - controller.armCCLearn(pedalControl(0, 0, 0)) + controller.armCCLearn(pedalControl(board.pedals[0].id, 0)) controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0)) - controller.armCCLearn(pedalControl(0, 0, 1)) + controller.armCCLearn(pedalControl(board.pedals[0].id, 1)) controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0)) - controller.setCCInverted(for: pedalControl(0, 0, 1), true) + controller.setCCInverted(for: pedalControl(board.pedals[0].id, 1), true) // Both bindings survive — the same CC drives both controls. #expect(sg.midiMap?.ccs.count == 2, "assigning a 2nd control must not steal the 1st") - #expect(controller.ccBinding(for: pedalControl(0, 0, 0)) != nil) + #expect(controller.ccBinding(for: pedalControl(board.pedals[0].id, 0)) != nil) let position: UIParamNode = board.pedals[0].ccMappableControls[0].node let mix: UIParamNode = board.pedals[0].ccMappableControls[1].node @@ -200,7 +200,7 @@ struct MIDIControllerCCTests { withExtendedLifetime(sg) { // Learn on channel 0 (the binding captures that channel). - controller.armCCLearn(pedalControl(0, 0, 0)) + controller.armCCLearn(pedalControl(board.pedals[0].id, 0)) controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0)) let node: UIParamNode = board.pedals[0].ccMappableControls[0].node @@ -212,15 +212,15 @@ struct MIDIControllerCCTests { } @Test func clearRemovesBinding() throws { - let (controller, sg, _, url): (MIDIController, ShoeGaze, PedalBoard, URL) = try makeRig() + let (controller, sg, board, url): (MIDIController, ShoeGaze, PedalBoard, URL) = try makeRig() defer { try? FileManager.default.removeItem(at: url) } - controller.armCCLearn(pedalControl(0, 0, 0)) + controller.armCCLearn(pedalControl(board.pedals[0].id, 0)) controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0)) #expect(sg.midiMap?.ccs.isEmpty == false) - controller.clearCCBinding(for: pedalControl(0, 0, 0)) - #expect(controller.ccBinding(for: pedalControl(0, 0, 0)) == nil) + controller.clearCCBinding(for: pedalControl(board.pedals[0].id, 0)) + #expect(controller.ccBinding(for: pedalControl(board.pedals[0].id, 0)) == nil) #expect(sg.midiMap?.ccs.isEmpty == true) } } diff --git a/Tests/LyrebirdShoeGazeTests/MIDIControllerPCTests.swift b/Tests/LyrebirdShoeGazeTests/MIDIControllerPCTests.swift index 72e0ba6..8a35013 100644 --- a/Tests/LyrebirdShoeGazeTests/MIDIControllerPCTests.swift +++ b/Tests/LyrebirdShoeGazeTests/MIDIControllerPCTests.swift @@ -86,7 +86,7 @@ struct MIDIControllerPCTests { withExtendedLifetime(sg) { let node: UIParamNode = boards[0].pedals[0].$bypass - controller.armSwitchLearn(.pedalBypass(boardIndex: 0, pedalIndex: 0)) + controller.armSwitchLearn(.pedalBypass(pedalID: boards[0].pedals[0].id)) controller.ingestForTesting(.programChange(channel: 0, program: 5)) // learn #expect(node.value == 0.0) controller.ingestForTesting(.programChange(channel: 0, program: 5)) @@ -101,7 +101,7 @@ struct MIDIControllerPCTests { defer { try? FileManager.default.removeItem(at: url) } withExtendedLifetime(sg) { - controller.armSwitchLearn(.boardBypass(boardIndex: 0)) + controller.armSwitchLearn(.boardBypass(boardID: boards[0].id)) controller.ingestForTesting(.programChange(channel: 0, program: 3)) // learn controller.ingestForTesting(.programChange(channel: 0, program: 3)) #expect(sg.isBoardBypassed(boards[0]) == true) @@ -116,7 +116,7 @@ struct MIDIControllerPCTests { defer { try? FileManager.default.removeItem(at: url) } withExtendedLifetime(sg) { - controller.armSwitchLearn(.boardSolo(boardIndex: 1)) + controller.armSwitchLearn(.boardSolo(boardID: boards[1].id)) controller.ingestForTesting(.programChange(channel: 0, program: 2)) // learn controller.ingestForTesting(.programChange(channel: 0, program: 2)) // solo board 2 #expect(sg.activeBoardIndex == 1) @@ -162,11 +162,12 @@ struct MIDIControllerPCTests { defer { try? FileManager.default.removeItem(at: url) } withExtendedLifetime(sg) { - // Bind to a pedal index that doesn't exist; applying it must be a safe no-op. - controller.armSwitchLearn(.pedalBypass(boardIndex: 0, pedalIndex: 9)) + // Bind to a pedal id that doesn't exist in the rig; applying it must be a safe no-op. + let ghostID: UUID = UUID() + controller.armSwitchLearn(.pedalBypass(pedalID: ghostID)) controller.ingestForTesting(.programChange(channel: 0, program: 6)) // learn controller.ingestForTesting(.programChange(channel: 0, program: 6)) // apply — no crash - #expect(controller.switchBinding(for: .pedalBypass(boardIndex: 0, pedalIndex: 9)) != nil) + #expect(controller.switchBinding(for: .pedalBypass(pedalID: ghostID)) != nil) } } @@ -179,12 +180,12 @@ struct MIDIControllerPCTests { withExtendedLifetime(sg) { controller.armSwitchLearn(.rigBypass) controller.ingestForTesting(.programChange(channel: 0, program: 8)) - controller.armSwitchLearn(.pedalBypass(boardIndex: 0, pedalIndex: 0)) + controller.armSwitchLearn(.pedalBypass(pedalID: boards[0].pedals[0].id)) controller.ingestForTesting(.programChange(channel: 0, program: 8)) // same PC, kept // Both bindings survive — one PC drives two actions. #expect(controller.switchBinding(for: .rigBypass)?.program == 8) - #expect(controller.switchBinding(for: .pedalBypass(boardIndex: 0, pedalIndex: 0))?.program == 8) + #expect(controller.switchBinding(for: .pedalBypass(pedalID: boards[0].pedals[0].id))?.program == 8) #expect(sg.midiMap?.switches.count == 2) // Firing the PC toggles both at once. @@ -209,4 +210,60 @@ struct MIDIControllerPCTests { #expect(sg.midiMap?.switches.count == 1) } } + + @Test func tunerToggleFlipsEngagedState() throws { + let (controller, sg, _, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = try makeRig() + defer { try? FileManager.default.removeItem(at: url) } + + withExtendedLifetime(sg) { + controller.armSwitchLearn(.tunerToggle) + controller.ingestForTesting(.programChange(channel: 0, program: 10)) // learn only + #expect(!sg.tunerEngaged) + + controller.ingestForTesting(.programChange(channel: 0, program: 10)) + #expect(sg.tunerEngaged, "first press engages") + controller.ingestForTesting(.programChange(channel: 0, program: 10)) + #expect(!sg.tunerEngaged, "second press disengages") + } + } + + @Test func tapTempoRegistersEachPress() throws { + let (controller, sg, _, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = try makeRig() + defer { try? FileManager.default.removeItem(at: url) } + + withExtendedLifetime(sg) { + controller.armSwitchLearn(.tapTempo) + controller.ingestForTesting(.programChange(channel: 0, program: 11)) // learn only + #expect(sg.tapTimestamps.isEmpty) + + controller.ingestForTesting(.programChange(channel: 0, program: 11)) + #expect(sg.tapTimestamps.count == 1, "first press registers a tap") + controller.ingestForTesting(.programChange(channel: 0, program: 11)) + #expect(sg.tapTimestamps.count == 2, "second press registers a second tap") + } + } + + @Test func pedalActionDispatchesLooperRecordStop() throws { + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256) + let sg: ShoeGaze = ShoeGaze(engine: engine) + let board: PedalBoard = try sg.addBoard() + let looper: LooperPedal = LooperPedal() + try board.add(looper) + try sg.finalizeBoard(board) + let controller: MIDIController = MIDIController(engine: engine, shoeGaze: sg) + defer { try? FileManager.default.removeItem(at: url) } + + withExtendedLifetime(sg) { + controller.armSwitchLearn(.pedalAction(pedalID: looper.id, kind: .looperRecordStop)) + controller.ingestForTesting(.programChange(channel: 0, program: 12)) // learn only + #expect(looper.transportState == .empty) + + // The looper was added via the board, so it carries the shared tempo clock and its + // transport is beat-quantized: the mapped press arms recording for the next beat. + // Asserting the arm proves the Program Change dispatched to the pedal's action. + controller.ingestForTesting(.programChange(channel: 0, program: 12)) + #expect(looper.transportState == .armedRecord, + "mapped Program Change should dispatch the looper record/stop action") + } + } } diff --git a/Tests/LyrebirdShoeGazeTests/MIDIMapCodableTests.swift b/Tests/LyrebirdShoeGazeTests/MIDIMapCodableTests.swift index c09dec6..aae0a65 100644 --- a/Tests/LyrebirdShoeGazeTests/MIDIMapCodableTests.swift +++ b/Tests/LyrebirdShoeGazeTests/MIDIMapCodableTests.swift @@ -12,25 +12,37 @@ import Foundation @Suite("MIDIMap persistence") struct MIDIMapCodableTests { + // Fixed ids so the round-trip comparison is deterministic. + private static let boardID: UUID = UUID() + private static let looperID: UUID = UUID() + private static let volumeID: UUID = UUID() + private func sampleMap() -> MIDIMap { MIDIMap( switches: [ MIDIMap.SwitchBinding(program: 3, channel: 0, action: .rigBypass, displayNameHint: "Rig"), - MIDIMap.SwitchBinding(program: 4, action: .boardSolo(boardIndex: 1), displayNameHint: "Board 2"), + MIDIMap.SwitchBinding(program: 4, action: .boardSolo(boardID: Self.boardID), displayNameHint: "Board 2"), + MIDIMap.SwitchBinding(program: 5, action: .tunerToggle), + MIDIMap.SwitchBinding(program: 6, action: .tapTempo), + MIDIMap.SwitchBinding( + program: 7, + action: .pedalAction(pedalID: Self.looperID, kind: .looperRecordStop), + displayNameHint: "Looper" + ), ], ccs: [ MIDIMap.CCBinding( controller: 7, channel: 0, target: .pedalControl( - boardIndex: 0, pedalIndex: 1, controlIndex: 0, + pedalID: Self.volumeID, controlIndex: 0, pedalNameHint: "Volume", controlLabelHint: "Position" ) ), MIDIMap.CCBinding( controller: 11, channel: 0, - target: .boardLevel(boardIndex: 0, boardLabelHint: "Board 1") + target: .boardLevel(boardID: Self.boardID, boardLabelHint: "Board 1") ), ] ) diff --git a/Tests/LyrebirdShoeGazeTests/MIDIMapMigrationTests.swift b/Tests/LyrebirdShoeGazeTests/MIDIMapMigrationTests.swift new file mode 100644 index 0000000..106dc75 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/MIDIMapMigrationTests.swift @@ -0,0 +1,108 @@ +// MIDIMapMigrationTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +import LyrebirdSynth +@testable import LyrebirdShoeGaze + +@MainActor +@Suite("Legacy MIDI map migration") +struct MIDIMapMigrationTests { + + /// Two boards; board 0 has two pedals, board 1 has one — with fixed ids to assert against. + private func sampleBoards() -> [BoardState] { + let od: PedalState = PedalState(type: "Overdrive", knobValues: [], bypass: 0) + let rv: PedalState = PedalState(type: "Reverb", knobValues: [], bypass: 0) + let dl: PedalState = PedalState(type: "Delay", knobValues: [], bypass: 0) + return [ + BoardState(label: "Board 1", pedals: [od, rv]), + BoardState(label: "Board 2", pedals: [dl]), + ] + } + + // MARK: - Unit: positional → id conversion + + @Test func migratesPositionalBindingsToIds() { + let boards: [BoardState] = sampleBoards() + let legacy: LegacyMIDIMap = LegacyMIDIMap( + switches: [ + LegacyMIDIMap.LegacySwitchBinding(program: 1, channel: nil, action: .rigBypass, displayNameHint: nil), + LegacyMIDIMap.LegacySwitchBinding(program: 2, channel: nil, action: .boardBypass(boardIndex: 1), displayNameHint: "Board 2"), + LegacyMIDIMap.LegacySwitchBinding(program: 3, channel: nil, action: .pedalBypass(boardIndex: 0, pedalIndex: 1), displayNameHint: "Reverb"), + ], + ccs: [ + LegacyMIDIMap.LegacyCCBinding(controller: 7, channel: nil, + target: .pedalControl(boardIndex: 0, pedalIndex: 0, controlIndex: 2, pedalNameHint: "Overdrive", controlLabelHint: "Level"), + inverted: false), + LegacyMIDIMap.LegacyCCBinding(controller: 11, channel: nil, + target: .boardLevel(boardIndex: 1, boardLabelHint: "Board 2"), inverted: false), + ] + ) + + let migrated: MIDIMap = legacy.migrated(boards: boards) + + #expect(migrated.switches[0].action == .rigBypass) + #expect(migrated.switches[1].action == .boardBypass(boardID: boards[1].id)) + #expect(migrated.switches[2].action == .pedalBypass(pedalID: boards[0].pedals[1].id)) + + #expect(migrated.ccs[0].target == .pedalControl( + pedalID: boards[0].pedals[0].id, controlIndex: 2, + pedalNameHint: "Overdrive", controlLabelHint: "Level")) + #expect(migrated.ccs[1].target == .boardLevel(boardID: boards[1].id, boardLabelHint: "Board 2")) + } + + @Test func dropsOutOfRangeBindings() { + let boards: [BoardState] = sampleBoards() + let legacy: LegacyMIDIMap = LegacyMIDIMap( + switches: [ + LegacyMIDIMap.LegacySwitchBinding(program: 1, channel: nil, action: .pedalBypass(boardIndex: 0, pedalIndex: 9), displayNameHint: nil), + LegacyMIDIMap.LegacySwitchBinding(program: 2, channel: nil, action: .boardSolo(boardIndex: 5), displayNameHint: nil), + ], + ccs: [] + ) + let migrated: MIDIMap = legacy.migrated(boards: boards) + #expect(migrated.switches.isEmpty, "bindings addressing a non-existent board/pedal are dropped") + } + + // MARK: - Integration: legacy JSON decodes through ShoeGazeState + + @Test func legacyFormatJSONDecodesAndMigrates() throws { + let boards: [BoardState] = sampleBoards() + let legacy: LegacyMIDIMap = LegacyMIDIMap( + switches: [ + LegacyMIDIMap.LegacySwitchBinding(program: 3, channel: 0, action: .pedalBypass(boardIndex: 0, pedalIndex: 1), displayNameHint: "Reverb"), + ], + ccs: [] + ) + + // Build the raw rig JSON with the *legacy* midiMap encoding spliced in — exactly what an + // old saved rig on disk looks like (boards may or may not carry ids; midiMap is positional). + var dict: [String: Any] = [ + "version": presetFormatVersion, + "boards": try jsonObject(boards), + "midiMap": try jsonObject(legacy), + ] + // Sanity: the spliced midiMap is the positional shape, not the id shape. + #expect(((dict["midiMap"] as? [String: Any])?["switches"] as? [Any])?.isEmpty == false) + + let data: Data = try JSONSerialization.data(withJSONObject: dict) + let state: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data) + + let map: MIDIMap = try #require(state.midiMap, "legacy midiMap should migrate, not drop to nil") + #expect(map.switches.count == 1) + // The board ids in `state.boards` are what migration used — assert the binding points at + // the Reverb (board 0, pedal 1) by that board's decoded pedal id. + #expect(map.switches[0].action == .pedalBypass(pedalID: state.boards[0].pedals[1].id)) + _ = dict.removeValue(forKey: "midiMap") + } + + /// Encodes a `Codable` value and re-reads it as a JSON object for splicing. + private func jsonObject(_ value: T) throws -> Any { + let data: Data = try JSONEncoder().encode(value) + return try JSONSerialization.jsonObject(with: data) + } +} diff --git a/Tests/LyrebirdShoeGazeTests/MIDIMapReindexTests.swift b/Tests/LyrebirdShoeGazeTests/MIDIMapReindexTests.swift new file mode 100644 index 0000000..de08aff --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/MIDIMapReindexTests.swift @@ -0,0 +1,148 @@ +// MIDIMapReindexTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +import LyrebirdSynth +import LyrebirdUI +@testable import LyrebirdShoeGaze + +/// MIDI bindings address pedals/boards by stable UUID, so they follow their target through +/// structural edits with no reindexing. These tests assert the identity round-trips through the +/// edit API's capture → rebuild, and that a binding resolves to (and only to) its pedal. +@MainActor +@Suite("MIDIMap identity") +struct MIDIMapReindexTests { + + private func makeRig(_ pedals: [String]) throws -> (ShoeGaze, MIDIController, URL, PedalBoard) { + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256) + let sg: ShoeGaze = ShoeGaze(engine: engine) + let board: PedalBoard = try sg.addBoard() + for type: String in pedals { + if let pedal: Pedal = PedalRegistry.makePedal(type: type) { try board.add(pedal) } + } + try sg.finalizeBoard(board) + let controller: MIDIController = MIDIController(engine: engine, shoeGaze: sg) + return (sg, controller, url, board) + } + + // MARK: - Identity preservation across edits + + @Test func pedalKeepsIdThroughInsertAndMove() throws { + let (sg, _, url, board): (ShoeGaze, MIDIController, URL, PedalBoard) = + try makeRig(["Overdrive", "Delay", "Reverb"]) + defer { try? FileManager.default.removeItem(at: url) } + + let reverbID: UUID = board.pedals[2].id + + // Insert a Fuzz at the front → Reverb slides to index 3 but keeps its id. + let afterInsert: PedalBoard = try sg.insertPedal(.fuzz, at: 0, to: board) + #expect(afterInsert.pedals.count == 4) + #expect(afterInsert.pedals[3].id == reverbID, "Reverb keeps its id after an insert before it") + + // Move it to the front → still the same id. + let afterMove: PedalBoard = try sg.movePedal(from: 3, to: 0, in: afterInsert) + #expect(afterMove.pedals[0].id == reverbID, "Reverb keeps its id after a move") + } + + @Test func pedalIdSurvivesSaveLoadRoundTrip() throws { + let (sg, _, url, board): (ShoeGaze, MIDIController, URL, PedalBoard) = + try makeRig(["Overdrive", "Reverb"]) + defer { try? FileManager.default.removeItem(at: url) } + let ids: [UUID] = board.pedals.map { $0.id } + + // Full Codable round-trip (what save/load to disk does). + let data: Data = try JSONEncoder().encode(sg.captureState()) + let state: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data) + let (engine2, url2): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256) + defer { try? FileManager.default.removeItem(at: url2) } + let sg2: ShoeGaze = ShoeGaze(engine: engine2) + try sg2.loadRig(from: state) + + #expect(sg2.boards.first?.pedals.map { $0.id } == ids, "pedal ids persist across save/load") + } + + @Test func boardKeepsIdThroughReorder() throws { + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256) + defer { try? FileManager.default.removeItem(at: url) } + let sg: ShoeGaze = ShoeGaze(engine: engine) + let b0: PedalBoard = try sg.addBoard(); try sg.finalizeBoard(b0) + let b1: PedalBoard = try sg.addBoard(); try sg.finalizeBoard(b1) + let id0: UUID = b0.id + let id1: UUID = b1.id + + sg.moveBoard(b1, to: 0) + #expect(sg.boards[0].id == id1) + #expect(sg.boards[1].id == id0) + } + + // MARK: - Binding follows the pedal (end-to-end via the controller) + + @Test func bypassBindingFollowsPedalAfterInsert() throws { + let (sg, controller, url, board): (ShoeGaze, MIDIController, URL, PedalBoard) = + try makeRig(["Overdrive", "Reverb"]) + defer { try? FileManager.default.removeItem(at: url) } + + withExtendedLifetime(sg) { + // Map program 5 to the Reverb's bypass (pedal index 1). + let reverbID: UUID = board.pedals[1].id + controller.armSwitchLearn(.pedalBypass(pedalID: reverbID)) + controller.ingestForTesting(.programChange(channel: 0, program: 5)) // learn + + // Insert a Fuzz at the front — Reverb moves to index 2, keeps its id. + let edited: PedalBoard = (try? sg.insertPedal(.fuzz, at: 0, to: board)) ?? board + let reverb: Pedal = edited.pedals.first { $0.id == reverbID }! + #expect(edited.pedals.firstIndex { $0.id == reverbID } == 2) + + // Firing the binding must still toggle the Reverb (not whatever is at the old index). + #expect(reverb.$bypass.value == 0.0) + controller.ingestForTesting(.programChange(channel: 0, program: 5)) + #expect(abs(reverb.$bypass.value - 1.0) < 1e-9, "binding follows the pedal, not the index") + } + } + + @Test func bindingToRemovedPedalIsInert() throws { + let (sg, controller, url, board): (ShoeGaze, MIDIController, URL, PedalBoard) = + try makeRig(["Overdrive", "Reverb"]) + defer { try? FileManager.default.removeItem(at: url) } + + withExtendedLifetime(sg) { + let overdriveID: UUID = board.pedals[0].id + controller.armSwitchLearn(.pedalBypass(pedalID: overdriveID)) + controller.ingestForTesting(.programChange(channel: 0, program: 5)) // learn + + // Remove the mapped Overdrive. Firing the binding must not crash or touch the Reverb. + let edited: PedalBoard = (try? sg.removePedal(at: 0, from: board)) ?? board + let reverbBypassBefore: Double = edited.pedals[0].$bypass.value + controller.ingestForTesting(.programChange(channel: 0, program: 5)) + #expect(edited.pedals[0].$bypass.value == reverbBypassBefore, + "a binding to a removed pedal is inert — it must not fall through to another pedal") + } + } + + @Test func sameTypePedalsBindIndependently() throws { + // The case the positional model got wrong: two identical-type pedals, each with its own + // binding, resolve independently by id even after reordering. + let (sg, controller, url, board): (ShoeGaze, MIDIController, URL, PedalBoard) = + try makeRig(["Delay", "Delay"]) + defer { try? FileManager.default.removeItem(at: url) } + + withExtendedLifetime(sg) { + let firstDelayID: UUID = board.pedals[0].id + controller.armSwitchLearn(.pedalBypass(pedalID: firstDelayID)) + controller.ingestForTesting(.programChange(channel: 0, program: 5)) // learn + + // Swap the two Delays. + let edited: PedalBoard = (try? sg.movePedal(from: 0, to: 1, in: board)) ?? board + let firstDelay: Pedal = edited.pedals.first { $0.id == firstDelayID }! + let otherDelay: Pedal = edited.pedals.first { $0.id != firstDelayID }! + + controller.ingestForTesting(.programChange(channel: 0, program: 5)) + #expect(abs(firstDelay.$bypass.value - 1.0) < 1e-9, "binding drives the originally-mapped Delay") + #expect(otherDelay.$bypass.value == 0.0, "the other same-type Delay is untouched") + } + } +} diff --git a/Tests/LyrebirdShoeGazeTests/RigStoreTests.swift b/Tests/LyrebirdShoeGazeTests/RigStoreTests.swift index 26d423c..600b9fe 100644 --- a/Tests/LyrebirdShoeGazeTests/RigStoreTests.swift +++ b/Tests/LyrebirdShoeGazeTests/RigStoreTests.swift @@ -14,9 +14,25 @@ import LyrebirdUI @Suite("RigStore") struct RigStoreTests { + /// Redirects `RigStore` to a unique temp file so the suite never touches — let alone + /// overwrites or deletes — the running app's real autosave in Application Support. Returns + /// the temp file URL (its parent directory is created). + private func isolateAutosave() throws -> URL { + let dir: URL = FileManager.default.temporaryDirectory + .appendingPathComponent("RigStoreTests-" + UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + let file: URL = dir.appendingPathComponent("autosave-rig.json") + RigStore.autosaveURLOverride = file + return file + } + @Test func savesAndRestoresAcrossInstances() throws { + let autosave: URL = try isolateAutosave() + defer { + RigStore.autosaveURLOverride = nil + try? FileManager.default.removeItem(at: autosave.deletingLastPathComponent()) + } RigStore.clear() - defer { RigStore.clear() } // Build a rig and autosave it. let (engineA, urlA): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 64) @@ -42,7 +58,37 @@ struct RigStoreTests { #expect(b.boards.last?.label == "Clean") } + @Test func restorePreservesCurrentRigID() throws { + let autosave: URL = try isolateAutosave() + defer { + RigStore.autosaveURLOverride = nil + try? FileManager.default.removeItem(at: autosave.deletingLastPathComponent()) + } + RigStore.clear() + + let (engineA, urlA): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 64) + defer { try? FileManager.default.removeItem(at: urlA) } + let a: ShoeGaze = ShoeGaze(engine: engineA) + let board: PedalBoard = try a.addBoard() + try a.appendPedal(.overdrive, to: board) + try a.finalizeBoard(board) + let rigID: UUID = UUID() + a.currentRigID = rigID + #expect(RigStore.save(a)) + + let (engineB, urlB): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 64) + defer { try? FileManager.default.removeItem(at: urlB) } + let b: ShoeGaze = ShoeGaze(engine: engineB) + #expect(RigStore.restore(into: b)) + #expect(b.currentRigID == rigID, "restore must carry the source-rig id so the UI highlights it") + } + @Test func restoreReturnsFalseWhenNoAutosave() throws { + let autosave: URL = try isolateAutosave() + defer { + RigStore.autosaveURLOverride = nil + try? FileManager.default.removeItem(at: autosave.deletingLastPathComponent()) + } RigStore.clear() let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 64) defer { try? FileManager.default.removeItem(at: url) } diff --git a/Tests/LyrebirdShoeGazeTests/Support/OfflineRender.swift b/Tests/LyrebirdShoeGazeTests/Support/OfflineRender.swift index d82374f..08826b3 100644 --- a/Tests/LyrebirdShoeGazeTests/Support/OfflineRender.swift +++ b/Tests/LyrebirdShoeGazeTests/Support/OfflineRender.swift @@ -84,21 +84,30 @@ func readStereoCAF(url: URL, sampleRate: Double = 44100.0) -> [Float] { &clientFormat ) == noErr else { return [] } - let readFrames: UInt32 = 4096 - var samples: [Float] = [Float](repeating: 0, count: Int(readFrames) * 2) - var framesRead: UInt32 = readFrames - samples.withUnsafeMutableBufferPointer { ptr in - var bufList: AudioBufferList = AudioBufferList( - mNumberBuffers: 1, - mBuffers: AudioBuffer( - mNumberChannels: 2, - mDataByteSize: UInt32(ptr.count * MemoryLayout.size), - mData: ptr.baseAddress + // 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.size), + mData: ptr.baseAddress + ) ) - ) - _ = ExtAudioFileRead(fileRef, &framesRead, &bufList) + _ = ExtAudioFileRead(fileRef, &framesRead, &bufList) + } + guard framesRead > 0 else { break } + allSamples.append(contentsOf: chunk.prefix(Int(framesRead) * 2)) + if framesRead < chunkFrames { break } } - return Array(samples.prefix(Int(framesRead) * 2)) + return allSamples } // MARK: - Signal analysis diff --git a/Tests/LyrebirdShoeGazeTests/TempoTests.swift b/Tests/LyrebirdShoeGazeTests/TempoTests.swift new file mode 100644 index 0000000..7e5d580 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/TempoTests.swift @@ -0,0 +1,83 @@ +// TempoTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +import LyrebirdSynth +@testable import LyrebirdShoeGaze + +@MainActor +@Suite("ShoeGaze Tempo") +struct TempoTests { + + private func makeShoeGaze(duration: Double = 0.1) -> (ShoeGaze, URL) { + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: duration, numAudioBuses: 64) + let shoeGaze: ShoeGaze = ShoeGaze(engine: engine, inputSource: .testLoop) + return (shoeGaze, url) + } + + @Test func clockDefaultsToStandardTempo() throws { + let (shoeGaze, url): (ShoeGaze, URL) = makeShoeGaze() + defer { try? FileManager.default.removeItem(at: url) } + + #expect(shoeGaze.clock.bpm == ShoeGaze.defaultTempoBpm) + } + + @Test func tapTempoAtOneSecondIntervalsSetsSixtyBpm() throws { + let (shoeGaze, url): (ShoeGaze, URL) = makeShoeGaze() + defer { try? FileManager.default.removeItem(at: url) } + + // Simulate taps exactly 1s apart by manipulating the tap history directly — + // real taps come from wall-clock `Date()`, so back-date synthetic timestamps + // instead of sleeping the test for real seconds. + let now: Date = Date() + shoeGaze.tapTimestamps = [ + now.addingTimeInterval(-3.0), + now.addingTimeInterval(-2.0), + now.addingTimeInterval(-1.0), + ] + shoeGaze.tapTempo() // landing "now", completing four 1s-spaced taps + + #expect(abs(shoeGaze.clock.bpm - 60.0) < 0.5) + } + + @Test func singleTapDoesNotSetTempo() throws { + let (shoeGaze, url): (ShoeGaze, URL) = makeShoeGaze() + defer { try? FileManager.default.removeItem(at: url) } + + let startingBpm: Double = shoeGaze.clock.bpm + shoeGaze.tapTempo() + #expect(shoeGaze.clock.bpm == startingBpm, "A single tap has no interval to measure — tempo must not change") + } + + @Test func longPauseResetsTapHistory() throws { + let (shoeGaze, url): (ShoeGaze, URL) = makeShoeGaze() + defer { try? FileManager.default.removeItem(at: url) } + + let now: Date = Date() + // Two taps 1s apart, then a long pause before the next tap. + shoeGaze.tapTimestamps = [now.addingTimeInterval(-10.0), now.addingTimeInterval(-9.0)] + shoeGaze.tapTempo() + #expect(shoeGaze.tapTimestamps.count == 1, "A >2s gap should discard prior taps and start a fresh sequence") + } + + @Test func tapTempoRespectsBpmRangeViaClockPrecondition() throws { + let (shoeGaze, url): (ShoeGaze, URL) = makeShoeGaze() + defer { try? FileManager.default.removeItem(at: url) } + + let now: Date = Date() + // Very fast taps (well under minTapInterval == 0.2s) are filtered out of the average. + shoeGaze.tapTimestamps = [ + now.addingTimeInterval(-0.15), + now.addingTimeInterval(-0.05), + ] + let startingBpm: Double = shoeGaze.clock.bpm + shoeGaze.tapTempo() + // The sub-threshold interval is filtered; with no valid interval left the tempo + // is left unchanged rather than jumping to an implausible value. + #expect(shoeGaze.clock.bpm == startingBpm) + } +} diff --git a/Tests/LyrebirdShoeGazeTests/TunerPitchReadingTests.swift b/Tests/LyrebirdShoeGazeTests/TunerPitchReadingTests.swift new file mode 100644 index 0000000..60838f2 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/TunerPitchReadingTests.swift @@ -0,0 +1,52 @@ +// TunerPitchReadingTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +@testable import LyrebirdShoeGazeUI + +@Suite("TunerPitchReading") +struct TunerPitchReadingTests { + + @Test func concertAIsA4WithZeroCents() { + let reading: TunerPitchReading = TunerPitchReading(hz: 440.0) + #expect(reading.noteName == "A4") + #expect(abs(reading.cents) < 0.5) + } + + @Test func oneOctaveDownIsA3() { + let reading: TunerPitchReading = TunerPitchReading(hz: 220.0) + #expect(reading.noteName == "A3") + #expect(abs(reading.cents) < 0.5) + } + + @Test func middleCIsC4() { + let reading: TunerPitchReading = TunerPitchReading(hz: 261.6256) + #expect(reading.noteName == "C4") + #expect(abs(reading.cents) < 1.0) + } + + @Test func slightlySharpReportsPositiveCents() { + // ~20 cents sharp of A4. + let sharpHz: Double = 440.0 * pow(2.0, 20.0 / 1200.0) + let reading: TunerPitchReading = TunerPitchReading(hz: sharpHz) + #expect(reading.noteName == "A4") + #expect(reading.cents > 15.0 && reading.cents < 25.0) + } + + @Test func slightlyFlatReportsNegativeCents() { + // ~20 cents flat of A4. + let flatHz: Double = 440.0 * pow(2.0, -20.0 / 1200.0) + let reading: TunerPitchReading = TunerPitchReading(hz: flatHz) + #expect(reading.noteName == "A4") + #expect(reading.cents < -15.0 && reading.cents > -25.0) + } + + @Test func lowGuitarStringIsE2() { + let reading: TunerPitchReading = TunerPitchReading(hz: 82.41) + #expect(reading.noteName == "E2") + } +} diff --git a/Tests/LyrebirdShoeGazeTests/TunerTapTests.swift b/Tests/LyrebirdShoeGazeTests/TunerTapTests.swift new file mode 100644 index 0000000..6033845 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/TunerTapTests.swift @@ -0,0 +1,91 @@ +// TunerTapTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +import LyrebirdSynth +import LyrebirdUI +@testable import LyrebirdShoeGaze + +@MainActor +@Suite("TunerTap") +struct TunerTapTests { + + /// A constant-frequency sine source — same shape as `LooperPedalTests.ToneSource`. + private final class ToneSource: SynthesizerBase { + private let targetBus: Int + private let toneFreq: Double + private let amplitude: Double + + init(targetBus: Int, freq: Double, amplitude: Double = 0.5) { + self.targetBus = targetBus + self.toneFreq = freq + self.amplitude = amplitude + super.init() + } + + override func build() { + output(bus: targetBus, source: OscSin.Audio(freq: toneFreq, mul: amplitude)) + } + } + + @Test func detectsKnownFrequencyWithinTolerance() throws { + let toneFreq: Double = 220.0 + // The YIN tracker decimates 8×, so its 512-sample window needs ~4096 input samples + // to fill plus several hops to converge — render generously. + let renderDuration: Double = 2.0 + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration) + defer { try? FileManager.default.removeItem(at: url) } + + let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) + let scratchControlBus: ControlBus = try engine.busAllocator.allocateControlBus() + defer { + engine.busAllocator.releaseAudioBus(srcBus) + engine.busAllocator.releaseControlBus(scratchControlBus) + } + + let source: ToneSource = ToneSource(targetBus: srcBus.index, freq: toneFreq) + let tap: TunerTap = TunerTap(inputBusIndex: srcBus.index, scratchControlBus: scratchControlBus) + + try engine.add(source) + try engine.add(tap, position: NodePosition.after(source)) + try engine.start() + + let capture: TunerPitchCapture = try #require(tap.pitchCapture) + let detected: Double = capture.detectedFrequencyHz + let tolerance: Double = 5.0 + #expect(abs(detected - toneFreq) < tolerance, "Expected ~\(toneFreq) Hz, got \(detected) Hz") + #expect(capture.detectedConfidence > 0.5, "A pure tone should track with high confidence") + } + + @Test func detectsLowGuitarEString() throws { + // E2 ≈ 82.4 Hz — below the undecimated FreqTracker floor (~173 Hz), so this only + // works because the tuner tap decimates before YIN analysis. + let toneFreq: Double = 82.41 + let renderDuration: Double = 3.0 + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration) + defer { try? FileManager.default.removeItem(at: url) } + + let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) + let scratchControlBus: ControlBus = try engine.busAllocator.allocateControlBus() + defer { + engine.busAllocator.releaseAudioBus(srcBus) + engine.busAllocator.releaseControlBus(scratchControlBus) + } + + let source: ToneSource = ToneSource(targetBus: srcBus.index, freq: toneFreq) + let tap: TunerTap = TunerTap(inputBusIndex: srcBus.index, scratchControlBus: scratchControlBus) + + try engine.add(source) + try engine.add(tap, position: NodePosition.after(source)) + try engine.start() + + let capture: TunerPitchCapture = try #require(tap.pitchCapture) + let detected: Double = capture.detectedFrequencyHz + let tolerance: Double = 3.0 + #expect(abs(detected - toneFreq) < tolerance, "Expected ~\(toneFreq) Hz (low E), got \(detected) Hz") + } +} diff --git a/Tests/LyrebirdShoeGazeTests/TunerTests.swift b/Tests/LyrebirdShoeGazeTests/TunerTests.swift new file mode 100644 index 0000000..f4078de --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/TunerTests.swift @@ -0,0 +1,123 @@ +// TunerTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +import LyrebirdSynth +import LyrebirdUI +@testable import LyrebirdShoeGaze + +@MainActor +@Suite("ShoeGaze Tuner") +struct TunerTests { + + private func makeShoeGaze(duration: Double) -> (ShoeGaze, SynthesisEngine, URL) { + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: duration, numAudioBuses: 64) + let shoeGaze: ShoeGaze = ShoeGaze(engine: engine, inputSource: .testLoop) + return (shoeGaze, engine, url) + } + + @Test func engageAddsTapAndDisengageRemovesIt() throws { + let (shoeGaze, engine, url): (ShoeGaze, SynthesisEngine, URL) = makeShoeGaze(duration: 0.2) + defer { try? FileManager.default.removeItem(at: url) } + + let board: PedalBoard = try shoeGaze.addBoard() + try shoeGaze.finalizeBoard(board) + + #expect(!shoeGaze.tunerEngaged) + #expect(shoeGaze.currentPitchHz == nil) + + shoeGaze.engageTuner() + #expect(shoeGaze.tunerEngaged) + + try engine.start() + #expect(shoeGaze.currentPitchHz != nil) + + shoeGaze.disengageTuner() + #expect(!shoeGaze.tunerEngaged) + #expect(shoeGaze.currentPitchHz == nil) + } + + @Test func engagingWithMuteOnMutesRigAndDisengageRestores() throws { + let (shoeGaze, engine, url): (ShoeGaze, SynthesisEngine, URL) = makeShoeGaze(duration: 0.1) + defer { try? FileManager.default.removeItem(at: url) } + _ = engine + + let board: PedalBoard = try shoeGaze.addBoard() + try shoeGaze.finalizeBoard(board) + + shoeGaze.tunerMutesRig = true + #expect(!shoeGaze.rigMuted) + + shoeGaze.engageTuner() + #expect(shoeGaze.rigMuted, "Engaging with tunerMutesRig=true should mute the rig") + + shoeGaze.disengageTuner() + #expect(!shoeGaze.rigMuted, "Disengaging should restore the pre-engage mute state") + } + + @Test func disengageRestoresPriorMutedStateNotAlwaysUnmuted() throws { + let (shoeGaze, engine, url): (ShoeGaze, SynthesisEngine, URL) = makeShoeGaze(duration: 0.1) + defer { try? FileManager.default.removeItem(at: url) } + _ = engine + + let board: PedalBoard = try shoeGaze.addBoard() + try shoeGaze.finalizeBoard(board) + + shoeGaze.tunerMutesRig = true + shoeGaze.setRigMuted(true) // already muted before engaging, for an unrelated reason + + shoeGaze.engageTuner() + #expect(shoeGaze.rigMuted) + + shoeGaze.disengageTuner() + #expect(shoeGaze.rigMuted, "Rig was already muted before engaging — disengage must not unmute it") + } + + @Test func tunerMutesRigFalseDoesNotTouchRigMute() throws { + let (shoeGaze, engine, url): (ShoeGaze, SynthesisEngine, URL) = makeShoeGaze(duration: 0.1) + defer { try? FileManager.default.removeItem(at: url) } + _ = engine + + let board: PedalBoard = try shoeGaze.addBoard() + try shoeGaze.finalizeBoard(board) + + shoeGaze.tunerMutesRig = false + shoeGaze.engageTuner() + #expect(!shoeGaze.rigMuted) + + shoeGaze.disengageTuner() + #expect(!shoeGaze.rigMuted) + } + + @Test func toggleTunerEngagedFlipsState() throws { + let (shoeGaze, engine, url): (ShoeGaze, SynthesisEngine, URL) = makeShoeGaze(duration: 0.1) + defer { try? FileManager.default.removeItem(at: url) } + _ = engine + + let board: PedalBoard = try shoeGaze.addBoard() + try shoeGaze.finalizeBoard(board) + + shoeGaze.toggleTunerEngaged() + #expect(shoeGaze.tunerEngaged) + shoeGaze.toggleTunerEngaged() + #expect(!shoeGaze.tunerEngaged) + } + + @Test func engageIsANoOpWhenAlreadyEngaged() throws { + let (shoeGaze, engine, url): (ShoeGaze, SynthesisEngine, URL) = makeShoeGaze(duration: 0.1) + defer { try? FileManager.default.removeItem(at: url) } + _ = engine + + let board: PedalBoard = try shoeGaze.addBoard() + try shoeGaze.finalizeBoard(board) + + shoeGaze.engageTuner() + shoeGaze.tunerMutesRig = false // change after first engage — should have no effect until re-engage + shoeGaze.engageTuner() + #expect(shoeGaze.rigMuted, "Second engageTuner() call while already engaged must be a no-op") + } +}