// 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 rowSpacing: CGFloat = 14 private static let readoutSpacing: CGFloat = 10 private static let noteFontSize: CGFloat = 24 private static let statusFontSize: CGFloat = 10 /// Fixed row height = the engaged (readout-visible) height, so toggling doesn't shift layout. static let engagedHeight: CGFloat = 34 // 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 { // Single horizontal row so engaging the tuner grows it sideways, not downward — the // transport row keeps its height and the pedals below don't jump. HStack(spacing: TunerView.rowSpacing) { Button(shoeGaze.tunerEngaged ? "Tuner: On" : "Tuner: Off") { shoeGaze.toggleTunerEngaged() } .buttonStyle(.bordered) .tint(shoeGaze.tunerEngaged ? .green : .gray) .fixedSize() if shoeGaze.tunerEngaged { readout } } // Pin to the engaged height (the taller readout state) so toggling the tuner on/off never // shifts the surrounding layout by a few pixels. .frame(height: TunerView.engagedHeight) .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 { HStack(spacing: TunerView.readoutSpacing) { 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 { HStack(spacing: TunerView.readoutSpacing) { 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)" } }