diff --git a/Sources/LyrebirdShoeGaze/PedalSwitch.swift b/Sources/LyrebirdShoeGaze/PedalSwitch.swift index 295cf4a..a141bbe 100644 --- a/Sources/LyrebirdShoeGaze/PedalSwitch.swift +++ b/Sources/LyrebirdShoeGaze/PedalSwitch.swift @@ -49,6 +49,11 @@ public struct PedalSwitch { /// three-state switch. Must contain at least two options. public let options: [Option] + /// `true` when this switch controls a tempo-synced behaviour (e.g. the looper's + /// Sync-to-Tempo mode). A generic UI can disable such switches — and the host can force them + /// to their first (off) option — while the tempo indicator is turned off. Defaults to `false`. + public let tempoDependent: Bool + /// Creates a switch descriptor. /// /// - Parameters: @@ -56,15 +61,18 @@ public struct PedalSwitch { /// - node: The `UIParamNode` projected value of an `@UIParam` property /// (`pedal.$mode`, `pedal.$direction`, …). /// - options: Ordered switch positions, left to right. At least two. + /// - tempoDependent: `true` if the switch depends on the tempo/clock. Defaults to `false`. public init( label: String, node: UIParamNode, - options: [Option] + options: [Option], + tempoDependent: Bool = false ) { precondition(options.count >= 2, "PedalSwitch requires at least two options") self.label = label self.node = node self.options = options + self.tempoDependent = tempoDependent } /// The value of the next option after the one nearest `current`, wrapping to the first — so a diff --git a/Sources/LyrebirdShoeGaze/Pedals/LooperPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/LooperPedal.swift index da10429..5694ff6 100644 --- a/Sources/LyrebirdShoeGaze/Pedals/LooperPedal.swift +++ b/Sources/LyrebirdShoeGaze/Pedals/LooperPedal.swift @@ -167,8 +167,22 @@ public final class LooperPedal: Pedal { private var recordStartSample: SampleTime = 0 private var playStartSample: SampleTime = 0 + /// Play-head position tracking that survives direction changes. `playHeadAnchor01` is the + /// normalised play-head fraction at the last anchor event (playback start or a reverse flip); + /// `playHeadAnchorSample` is the engine sample at that event. Between events the position is + /// `anchor01 + direction · (elapsed / masterLength)`, wrapped into `[0, 1)`. This mirrors the + /// actual `PlayBuffer` play-head — which reverses smoothly from its live phase — instead of the + /// old `1 − forward` reflection that jumped the read-out to the mirror point on every reverse. + private var playHeadAnchor01: Double = 0.0 + private var playHeadAnchorSample: SampleTime = 0 + private var transportRoutine: LyrebirdRoutine? private var stopRoutine: LyrebirdRoutine? + private var reverseRoutine: LyrebirdRoutine? + + /// Generation guard for a beat-deferred reverse. Separate from `transportGeneration` so + /// scheduling a reverse never invalidates a pending record/close (and vice versa). + private(set) var reverseGeneration: Int = 0 /// Transient notice shown in place of the state description for `noticeDuration` seconds. private var noticeText: String? @@ -205,12 +219,13 @@ public final class LooperPedal: Pedal { public override var effectSwitches: [PedalSwitch] { [ PedalSwitch( - label: "Sync", + label: "Sync to Tempo", node: $syncToBeat, options: [ PedalSwitch.Option(title: "Free", value: 0.0), PedalSwitch.Option(title: "Sync", value: 1.0), - ] + ], + tempoDependent: true ), ] } @@ -278,11 +293,20 @@ public final class LooperPedal: Pedal { guard phase == .playing, masterLength > 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(masterLength)) - let forward: Double = Double(framesInto) / Double(masterLength) - return reverse >= 0.5 ? (1.0 - forward) : forward + return playHeadFraction(at: engine.currentTime) + } + + /// The normalised play-head fraction in `[0, 1)` at engine sample `sample`, integrating the + /// signed distance travelled since the last anchor (playback start or reverse flip). Reversal + /// simply changes the sign of the accumulation from the current position — no jump. + func playHeadFraction(at sample: SampleTime) -> Double { + guard masterLength > 0 else { return 0.0 } + let direction: Double = reverse >= 0.5 ? -1.0 : 1.0 + let elapsed: Double = Double(sample - playHeadAnchorSample) + let raw: Double = playHeadAnchor01 + direction * elapsed / Double(masterLength) + var frac: Double = raw.truncatingRemainder(dividingBy: 1.0) + if frac < 0 { frac += 1.0 } + return frac } /// Caption for the Loop footswitch describing what the *next* press does. @@ -480,10 +504,55 @@ public final class LooperPedal: Pedal { syncToBeat = sync.nextValue(after: syncToBeat) } - /// Flips playback direction. Engaging reverse ends any active overdub, since overdub records + /// Flips playback direction from the current play-head position. In Sync mode the flip is + /// deferred to the next beat; in Free mode (or with no clock/engine, or when not playing) it + /// applies immediately. Engaging reverse ends any active overdub, since overdub records /// forward-in-time and can't follow a backward-reading play-head (see the class doc). public func toggleReverse() { + reverseRoutine?.stop() + reverseRoutine = nil + + // Not playing: no live play-head to reverse — just flip the direction for the next start. + guard phase == .playing else { + applyReverse(at: hostEngine?.currentTime ?? playHeadAnchorSample) + return + } + + reverseGeneration += 1 + let generation: Int = reverseGeneration + + // Free mode, or no clock/engine to schedule against → reverse immediately from here. + guard syncToBeat >= 0.5, let clock: LyrebirdClock = clock, let engine: SynthesisEngine = hostEngine else { + applyReverse(at: hostEngine?.currentTime ?? playHeadAnchorSample) + return + } + + // Sync mode: reverse on the next beat, from wherever the play-head is at that beat. + let target: SampleTime = clock.nextBeat() + let routine: LyrebirdRoutine = LyrebirdRoutine { [weak self] ctx in + try ctx.waitUntil(sampleTime: target) + DispatchQueue.main.async { self?.applyDeferredReverse(generation: generation, at: target) } + } + reverseRoutine = routine + routine.start(engine: engine) + } + + /// Applies a beat-deferred reverse once its target beat is reached, unless superseded by a + /// newer reverse press or a transport change. + func applyDeferredReverse(generation: Int, at beatSample: SampleTime) { + guard generation == reverseGeneration, phase == .playing else { return } + reverseRoutine = nil + applyReverse(at: beatSample) + } + + /// Flips the playback direction, re-anchoring the position read-out to the current play-head so + /// it continues smoothly in the new direction. `sample` is the point the flip takes effect. + func applyReverse(at sample: SampleTime) { let engagingReverse: Bool = reverse < 0.5 + // Re-anchor at the current play-head fraction *before* flipping, so the new-direction + // accumulation starts from where we actually are. + playHeadAnchor01 = playHeadFraction(at: sample) + playHeadAnchorSample = sample reverse = engagingReverse ? 1.0 : 0.0 if engagingReverse, overdubbingTrack != nil { overdubbingTrack = nil @@ -497,6 +566,8 @@ public final class LooperPedal: Pedal { transportGeneration += 1 stopRoutine?.stop() stopRoutine = nil + reverseRoutine?.stop() + reverseRoutine = nil cueStopArmed = 0.0 overdubbingTrack = nil updateOverdubGates() @@ -579,6 +650,8 @@ public final class LooperPedal: Pedal { transportRoutine = nil stopRoutine?.stop() stopRoutine = nil + reverseRoutine?.stop() + reverseRoutine = nil transportGeneration += 1 // Gate the recorders off (they run off `$isPlaying`) and stop the master BEFORE clearing, @@ -634,6 +707,8 @@ public final class LooperPedal: Pedal { transportRoutine = nil stopRoutine?.stop() stopRoutine = nil + reverseRoutine?.stop() + reverseRoutine = nil buffers.removeAll() players.removeAll() overdubRecorders.removeAll() @@ -689,6 +764,10 @@ public final class LooperPedal: Pedal { recorder.requestReset() // realign every write head to the top } playStartSample = sample + // Play head resets to the top (frame 0) via the playTrigger edge below; anchor the + // position read-out there so direction changes accumulate from a known origin. + playHeadAnchor01 = 0.0 + playHeadAnchorSample = sample isPlaying = 1.0 stoppedIndicator = 0.0 overdubbingTrack = overdubTrack diff --git a/Sources/LyrebirdShoeGaze/ShoeGaze.swift b/Sources/LyrebirdShoeGaze/ShoeGaze.swift index 95834f1..30b871e 100644 --- a/Sources/LyrebirdShoeGaze/ShoeGaze.swift +++ b/Sources/LyrebirdShoeGaze/ShoeGaze.swift @@ -125,10 +125,30 @@ public final class ShoeGaze { // MARK: - Tempo state + /// `true` when the tempo indicator (BPM readout / TAP / beat LED) is shown and tempo-synced + /// features are available. Toggle with ``setTempoEnabled(_:)``; when turned off, every + /// tempo-dependent pedal switch (e.g. the looper's Sync-to-Tempo mode) is forced to its + /// first (off) position so nothing keeps quantizing to a hidden clock. + public private(set) var tempoEnabled: Bool = true + /// Timestamps of recent `tapTempo()` calls, oldest first. `internal` so /// `ShoeGaze+Tempo.swift` (same module, different file) can mutate it. internal var tapTimestamps: [Date] = [] + /// Shows or hides the tempo indicator and, when hiding, deactivates every tempo-synced + /// control by forcing each ``PedalSwitch/tempoDependent`` switch to its first option. + public func setTempoEnabled(_ enabled: Bool) { + tempoEnabled = enabled + guard !enabled else { return } + for pedal: Pedal in allPedals() { + for pedalSwitch: PedalSwitch in pedal.effectSwitches where pedalSwitch.tempoDependent { + if let off: PedalSwitch.Option = pedalSwitch.options.first { + pedalSwitch.node.update(off.value) + } + } + } + } + // MARK: - Scope state /// Scope tap over the hardware input + output buses, feeding the debug scope view. diff --git a/Sources/LyrebirdShoeGazeUI/BoardBarView.swift b/Sources/LyrebirdShoeGazeUI/BoardBarView.swift index e28cb6e..c77b915 100644 --- a/Sources/LyrebirdShoeGazeUI/BoardBarView.swift +++ b/Sources/LyrebirdShoeGazeUI/BoardBarView.swift @@ -56,6 +56,9 @@ public struct BoardBarView: View { private static let ledDimBrightness: Double = 0.16 private static let ledRimOpacity: Double = 0.30 private static let soloButtonSize: CGFloat = 22 + /// Fixed size for the rig mute glyph so the slash / wave states don't shift the volume row. + private static let muteIconWidth: CGFloat = 16 + private static let muteIconHeight: CGFloat = 16 private static let editingBorderWidth: CGFloat = 2 private static let idleBorderOpacity: Double = 0.18 private static let cellBackgroundBrightness: Double = 0.14 @@ -71,6 +74,7 @@ public struct BoardBarView: View { @Binding private var editingBoardIndex: Int @Binding private var crossfadeSeconds: Double private let onAddBoard: () -> Void + private let onClearBoards: (() -> Void)? @State private var mode: PlayMode = .solo @@ -84,16 +88,20 @@ public struct BoardBarView: View { /// tap writes this). /// - crossfadeSeconds: Crossfade duration applied to every board switch / toggle. /// - onAddBoard: Called when the trailing **+** button is tapped. + /// - onClearBoards: Called when the trailing **Clear** button is tapped. When `nil` + /// (the default) no Clear button is shown. public init( shoeGaze: ShoeGaze, editingBoardIndex: Binding, crossfadeSeconds: Binding, - onAddBoard: @escaping () -> Void + onAddBoard: @escaping () -> Void, + onClearBoards: (() -> Void)? = nil ) { self.shoeGaze = shoeGaze self._editingBoardIndex = editingBoardIndex self._crossfadeSeconds = crossfadeSeconds self.onAddBoard = onAddBoard + self.onClearBoards = onClearBoards } // MARK: - Body @@ -109,6 +117,11 @@ public struct BoardBarView: View { boardCell(index: pair.offset, board: pair.element) } addButton + if let onClearBoards: () -> Void = onClearBoards { + Button("Clear") { onClearBoards() } + .buttonStyle(.bordered).tint(.red) + .help("Remove all boards in the current rig (with the option to save first)") + } } .frame(height: BoardBarView.barHeight) } @@ -175,7 +188,10 @@ public struct BoardBarView: View { Button { shoeGaze.toggleRigMuted() } label: { + // Fixed width: the slash / wave glyphs differ in width, which would otherwise + // shift the whole volume row a few pixels when toggling mute. Image(systemName: shoeGaze.rigMuted ? "speaker.slash.fill" : "speaker.wave.2.fill") + .frame(width: BoardBarView.muteIconWidth, height: BoardBarView.muteIconHeight) } .buttonStyle(.bordered) .tint(shoeGaze.rigMuted ? .red : .orange) diff --git a/Sources/LyrebirdShoeGazeUI/HelpView.swift b/Sources/LyrebirdShoeGazeUI/HelpView.swift index 0c17815..58a5f0a 100644 --- a/Sources/LyrebirdShoeGazeUI/HelpView.swift +++ b/Sources/LyrebirdShoeGazeUI/HelpView.swift @@ -66,6 +66,33 @@ public struct HelpView: View { + "Delete, and Erase All.", ] ) + topicSection( + icon: "repeat", + title: "The Looper Pedal", + intro: "The Looper records a phrase and plays it back in a loop, with up to four " + + "overdub tracks (A–D). The big Record button is a smart footswitch whose job " + + "changes with the looper's state.", + steps: [ + "Record (smart footswitch): first press records track A; press again to set the " + + "loop end and start playback (auto-overdubbing A); while playing it toggles " + + "overdub on the selected track.", + "Free vs Sync to Tempo: Free loops are whatever length you play, captured instantly. " + + "Sync quantizes record-start and loop-close to the beat clock — so every loop is " + + "a whole number of beats. Sync needs the Tempo indicator On; it is disabled while " + + "tempo is off.", + "Knobs: Playback sets loop level against your live signal; Overdub sets the record " + + "level of new overdubs; Feedback sets how much existing audio survives each pass " + + "(1.0 = keep forever); Crossfade smooths loop mute/unmute so it doesn't click.", + "Reverse flips playback direction from the current position (in Sync it waits for the " + + "next beat). Stop halts now; Cue Stop arms a stop at the next loop end (press again " + + "to cancel); Reset clears every track back to empty.", + "Tracks A–D: tap a dot to select the track Record overdubs into; tap a selected, " + + "recorded track again to mute or unmute it.", + "MIDI: Record, Stop, Cue Stop, Reverse, Sync, Reset, and each Track A–D map as " + + "footswitch (Program Change) actions in MIDI Mapping; the Crossfade / Playback / " + + "Overdub / Feedback knobs sweep from an expression pedal like any pedal knob.", + ] + ) topicSection( icon: "square.and.arrow.down", title: "Saving & Autosave", diff --git a/Sources/LyrebirdShoeGazeUI/PedalSwitchView.swift b/Sources/LyrebirdShoeGazeUI/PedalSwitchView.swift index 4ab1301..65c3608 100644 --- a/Sources/LyrebirdShoeGazeUI/PedalSwitchView.swift +++ b/Sources/LyrebirdShoeGazeUI/PedalSwitchView.swift @@ -43,10 +43,15 @@ public struct PedalSwitchView: View { private static let borderLineWidth: CGFloat = 1 private static let activeTextBrightness: Double = 0.12 + /// Opacity applied to a tempo-dependent switch while the tempo indicator is turned off. + private static let tempoDisabledOpacity: Double = 0.4 + // MARK: - Properties private let pedalSwitch: PedalSwitch + @Environment(\.shoeGazeTempoEnabled) private var tempoEnabled: Bool + // MARK: - Init /// Creates a segmented switch view. @@ -62,6 +67,8 @@ public struct PedalSwitchView: View { // Reading `node.value` registers this view for @Observable re-render on change. let current: Double = pedalSwitch.node.value let selectedIndex: Int = nearestIndex(to: current) + // A tempo-synced switch is inert while the tempo indicator is turned off. + let inert: Bool = pedalSwitch.tempoDependent && !tempoEnabled VStack(spacing: PedalSwitchView.labelSpacing) { HStack(spacing: PedalSwitchView.segmentSpacing) { @@ -77,10 +84,12 @@ public struct PedalSwitchView: View { lineWidth: PedalSwitchView.borderLineWidth) ) - Text(pedalSwitch.label) + Text(inert ? "\(pedalSwitch.label) (tempo off)" : pedalSwitch.label) .font(.system(size: PedalSwitchView.captionFontSize)) .foregroundStyle(Color.white) } + .disabled(inert) + .opacity(inert ? PedalSwitchView.tempoDisabledOpacity : 1.0) } // MARK: - Subviews diff --git a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift index 7898438..5e7a8a5 100644 --- a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift +++ b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift @@ -384,8 +384,7 @@ public struct ShoeGazeBuilderView: View { /// board canvas. private var builderColumn: some View { VStack(alignment: .leading, spacing: ShoeGazeBuilderView.sectionSpacing) { - transportRow - ioRow + headerSection #if !os(macOS) recordingRow #endif @@ -395,6 +394,7 @@ public struct ShoeGazeBuilderView: View { boardArea } .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + .environment(\.shoeGazeTempoEnabled, shoeGaze.tempoEnabled) } /// Top section: the scope + CPU meters on the left (sized to align with the mixer's @@ -415,7 +415,8 @@ public struct ShoeGazeBuilderView: View { shoeGaze: shoeGaze, editingBoardIndex: $selectedBoardIndex, crossfadeSeconds: $crossfadeSeconds, - onAddBoard: { addBoard() } + onAddBoard: { addBoard() }, + onClearBoards: { showClearDialog = true } ) Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity)) pedalPickerRow @@ -530,9 +531,12 @@ public struct ShoeGazeBuilderView: View { // MARK: - Transport row - private var transportRow: some View { + /// Two-row header. Left: the title with the Tempo / Tuner toggles stacked and left-aligned + /// beside it. Right: the engine options (row 1) over the input controls (row 2), trailing- + /// aligned so both right edges line up. Keeping it two rows tall frees canvas for the pedals. + private var headerSection: some View { _ = transportTick - return HStack(spacing: ShoeGazeBuilderView.rowSpacing) { + return HStack(alignment: .top, spacing: ShoeGazeBuilderView.rowSpacing) { VStack(alignment: .leading, spacing: 1) { Text("ShoeGaze Builder") .font(.title2).bold() @@ -551,19 +555,60 @@ public struct ShoeGazeBuilderView: View { .foregroundStyle(Color.red) } } - Spacer() - TempoView(shoeGaze: shoeGaze) - TunerView(shoeGaze: shoeGaze) - if let midi: MIDIController = midi { - MIDIIndicatorView(controller: midi) { showMIDISheet = true } + + // Tempo over Tuner, left-aligned to each other. + VStack(alignment: .leading, spacing: ShoeGazeBuilderView.rowSpacing) { + TempoView(shoeGaze: shoeGaze) + TunerView(shoeGaze: shoeGaze) + } + + Spacer() + + // Right column: engine options over input controls, both right-aligned. + VStack(alignment: .trailing, spacing: ShoeGazeBuilderView.rowSpacing) { + HStack(spacing: ShoeGazeBuilderView.rowSpacing) { + if let midi: MIDIController = midi { + MIDIIndicatorView(controller: midi) { showMIDISheet = true } + } + helpButton + rigBypassButton + EngineConfigView( + shoeGaze: shoeGaze, + hardwareSampleRate: hardwareSampleRate, + onConfigApplied: { transportTick.toggle() } + ) + } + .frame(height: TempoView.enabledHeight) + + HStack(spacing: ShoeGazeBuilderView.rowSpacing) { + // Mute-rig-while-tuning toggle sits to the left of the input selector. + Toggle("Mute rig", isOn: Binding( + get: { shoeGaze.tunerMutesRig }, + set: { shoeGaze.tunerMutesRig = $0 } + )) + .toggleStyle(.switch) + + Text("Input:") + .font(.subheadline) + .foregroundStyle(Color.white.opacity(ShoeGazeBuilderView.labelOpacity)) + Picker("Input", selection: inputBinding) { + Text("Test Loop").tag(ShoeGazeBuilderView.testLoopTag) + if shoeGaze.engine.numInputChannels > 0 { + ForEach(Array(0.. 0 { - ForEach(Array(0.. (ShoeGaze, SynthesisEngine, URL, LooperPedal) { + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1) + let sg: ShoeGaze = ShoeGaze(engine: engine) + let board: PedalBoard = try sg.addBoard() + guard let looper: LooperPedal = PedalRegistry.makePedal(type: "Looper") as? LooperPedal else { + fatalError("Looper pedal must be registered") + } + try board.add(looper) + try sg.finalizeBoard(board) + return (sg, engine, url, looper) + } + + @Test func tempoEnabledDefaultsOn() throws { + let (sg, _, url, _): (ShoeGaze, SynthesisEngine, URL, LooperPedal) = try makeRigWithLooper() + defer { try? FileManager.default.removeItem(at: url) } + #expect(sg.tempoEnabled, "tempo indicator is on by default") + } + + @Test func looperSyncSwitchIsTempoDependent() throws { + let (_, _, url, looper): (ShoeGaze, SynthesisEngine, URL, LooperPedal) = try makeRigWithLooper() + defer { try? FileManager.default.removeItem(at: url) } + let syncSwitch: PedalSwitch? = looper.effectSwitches.first { $0.tempoDependent } + #expect(syncSwitch != nil, "the looper Sync-to-Tempo switch must be marked tempo-dependent") + } + + @Test func disablingTempoForcesSyncSwitchesOff() throws { + let (sg, _, url, looper): (ShoeGaze, SynthesisEngine, URL, LooperPedal) = try makeRigWithLooper() + defer { try? FileManager.default.removeItem(at: url) } + + looper.syncToBeat = 1.0 // engage Sync + sg.setTempoEnabled(false) + #expect(!sg.tempoEnabled) + #expect(looper.syncToBeat == 0.0, "disabling tempo forces the looper back to Free") + + // Re-enabling leaves it Free — the user re-selects Sync if wanted. + sg.setTempoEnabled(true) + #expect(sg.tempoEnabled) + #expect(looper.syncToBeat == 0.0) + } +}