947dfe427a
Extend the looper into a double-width tempo-aware pedal: - Beat-quantized transport: record start and loop close both snap to the next beat via a LyrebirdRoutine waiting on the shared clock; loop length is an exact whole-beat span. Falls back to immediate/unquantized when no clock is present. - Loop-length read-outs (frames/seconds/beats), transport state, and a sample-clock-derived play-head position for the UI timeline. - Overdub undo (pre-dub snapshot + restore), reverse playback (live rate flip), and feedback-decay overdub (overdub preLevel via a Feedback knob). - Inject the shared LyrebirdClock + SynthesisEngine into Pedal via PedalBoard/ChainRouter so tempo-aware pedals can reach them. - New double-width LooperTimelineView (state badge, length read-out, sweeping play-head) wired into PedalView via Pedal.widthUnits. Concurrency hardening from RT-safety review: a transportGeneration counter drops superseded deferred beat/undo callbacks that LyrebirdRoutine.stop() cannot recall once enqueued; the undo restore is deferred past the RT overdub gate-close; transport routines use non-blocking stop(). Note: this commit also snapshots pre-existing uncommitted work-in-progress already in the tree (MIDI control refactor, Tuner, Tempo, preset changes), which is interleaved with the looper changes through shared files and could not be split into a separately-building commit. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
211 lines
8.4 KiB
Swift
211 lines
8.4 KiB
Swift
// 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)"
|
|
}
|
|
}
|