Repository Public License
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Arcade9// File : Games/PulseBeat/PulseModel.swift10// Description : Pulse Beat — pure gameplay model: timing windows and11// judgement, scoring and combo tiers, the run state machine12// fed by time-stamped touches, grades, the autoplay bot,13// calibration maths and the audio-clock model.14// Module : Games15// Repository : https://git.spboucher.ai/orix-arcade16// Created : 2026-11-2217// Last Modified : 2026-11-2218//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author : Simon-Pierre Boucher24// Position : Professor of Finance25// Institution : Université du Québec en Outaouais (UQO)26// Department : Département des sciences administratives27// Organization : SP Boucher28//29// Website : https://spboucher.ai30// Git : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General : info@spboucher.ai37// Professional : contact@spboucher.ai38// Direct : simon@spboucher.ai39// Research : research@spboucher.ai40// Development : dev@spboucher.ai41// Support : support@spboucher.ai42// Security/Admin : admin@spboucher.ai43// Notifications : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification : Public70// Distribution : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License : Proprietary, all rights reserved (see license file)84// License File : LICENSE85// Maintainer : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import Foundation9394nonisolated enum PulseJudgement: Int, Codable, CaseIterable, Sendable, Comparable {95 case perfect, great, good, miss9697 var title: String {98 switch self {99 case .perfect: "PERFECT"100 case .great: "GREAT"101 case .good: "GOOD"102 case .miss: "MISS"103 }104 }105106 /// Share of a note's value this judgement earns towards accuracy.107 var weight: Double {108 switch self {109 case .perfect: 1110 case .great: 0.7111 case .good: 0.4112 case .miss: 0113 }114 }115116 var points: Int {117 switch self {118 case .perfect: 300119 case .great: 200120 case .good: 100121 case .miss: 0122 }123 }124125 var hex: UInt32 {126 switch self {127 case .perfect: 0xFFE14D128 case .great: 0x4DF0FF129 case .good: 0x4DE3A1130 case .miss: 0xFF5470131 }132 }133134 static func < (a: PulseJudgement, b: PulseJudgement) -> Bool { a.rawValue < b.rawValue }135}136137nonisolated enum PulseGrade: Int, Codable, CaseIterable, Sendable, Comparable {138 case d, c, b, a, s139140 var title: String {141 switch self {142 case .d: "D"143 case .c: "C"144 case .b: "B"145 case .a: "A"146 case .s: "S"147 }148 }149150 var hex: UInt32 {151 switch self {152 case .d: 0x767BA6153 case .c: 0x4DE3A1154 case .b: 0x4DD8FF155 case .a: 0xC86BFF156 case .s: 0xFFC94D157 }158 }159160 /// Lowest accuracy (0…1) that earns the grade.161 var threshold: Double {162 switch self {163 case .d: 0164 case .c: 0.65165 case .b: 0.8166 case .a: 0.9167 case .s: 0.95168 }169 }170171 var stars: Int {172 switch self {173 case .d: 0174 case .c: 1175 case .b, .a: 2176 case .s: 3177 }178 }179180 static func < (a: PulseGrade, b: PulseGrade) -> Bool { a.rawValue < b.rawValue }181}182183/// The rules of the game. The windows are the same on every difficulty and are shown to the player as they are here.184nonisolated enum PulseRules {185 static let perfectWindow = 0.035186 static let greatWindow = 0.070187 static let goodWindow = 0.110188 /// Notes going by, holds ending and swipes timing out are only applied this long after they happen, so a touch still in flight is never overtaken.189 static let missGrace = 0.05190 /// After the tap of a swipe note, the flick has to follow within this time.191 static let flickWindow = 0.28192 /// A held note pays a small flat bonus every `holdTick` seconds.193 static let holdTick = 0.1194 static let holdTickPoints = 20195 static let swipeBonus = 100196 static let comboTiers = [10, 25, 50]197 /// A chart counts as cleared from this grade up.198 static let clearGrade = PulseGrade.c199200 static var windowsLabel: String {201 "Perfect ±\(Int(perfectWindow * 1000)) ms · Great ±\(Int(greatWindow * 1000)) ms · Good ±\(Int(goodWindow * 1000)) ms"202 }203204 /// Judges a tap `offset` seconds after (positive) or before (negative) its note. `nil` outside every window.205 static func judge(offset: Double) -> PulseJudgement? {206 let distance = abs(offset)207 let epsilon = 1e-9208 if distance <= perfectWindow + epsilon { return .perfect }209 if distance <= greatWindow + epsilon { return .great }210 if distance <= goodWindow + epsilon { return .good }211 return nil212 }213214 /// Judges the release of a hold `remaining` seconds before its end (zero or negative: held to the end).215 static func judgeRelease(remaining: Double) -> PulseJudgement {216 if remaining <= 0 { return .perfect }217 return judge(offset: remaining) ?? .miss218 }219220 static func multiplier(combo: Int) -> Int {221 1 + comboTiers.filter { combo >= $0 }.count222 }223224 static func grade(accuracy: Double) -> PulseGrade {225 PulseGrade.allCases.last { accuracy >= $0.threshold - 1e-9 } ?? .d226 }227228 static func isMilestone(_ combo: Int) -> Bool { combo == 25 || (combo > 0 && combo % 50 == 0) }229}230231nonisolated enum PulsePart: Int, Sendable, Equatable { case tap, head, tail, swipe }232233nonisolated enum PulseEvent: Sendable, Equatable {234 /// `offset` is the signed timing error in seconds (positive: late); nil for misses and held releases.235 case judged(note: Int, lane: Int, judgement: PulseJudgement, offset: Double?, part: PulsePart, combo: Int, points: Int)236 case holdTick(note: Int, lane: Int)237 case comboBreak(lost: Int)238 case milestone(combo: Int)239 case multiplier(Int)240 /// A tap with no note in reach. Costs nothing.241 case ghost(lane: Int)242 /// A swipe note that was tapped in time but not flicked the right way.243 case swipeFailed(note: Int, lane: Int)244}245246nonisolated struct PulseTally: Sendable, Equatable {247 /// Indexed by `PulseJudgement.rawValue`.248 var counts = [0, 0, 0, 0]249 var score = 0250 var combo = 0251 var maxCombo = 0252 var early = 0253 var late = 0254 var offsetSum = 0.0255 var offsetCount = 0256 var holdsCompleted = 0257 var swipesClean = 0258 var ghosts = 0259260 var judged: Int { counts.reduce(0, +) }261 var hits: Int { judged - counts[PulseJudgement.miss.rawValue] }262 var perfects: Int { counts[PulseJudgement.perfect.rawValue] }263 var misses: Int { counts[PulseJudgement.miss.rawValue] }264 var weightSum: Double { zip(counts, PulseJudgement.allCases).reduce(0) { $0 + Double($1.0) * $1.1.weight } }265 /// Accuracy over what has been judged so far; 1 before the first note.266 var accuracy: Double { judged > 0 ? weightSum / Double(judged) : 1 }267 /// Mean signed timing error of the hits, in seconds (positive: late).268 var meanOffset: Double { offsetCount > 0 ? offsetSum / Double(offsetCount) : 0 }269}270271nonisolated struct PulseResult: Sendable, Equatable {272 var trackID: String273 var difficulty: PulseDifficulty274 var tally: PulseTally275 var totalJudgements: Int276 var autoplay = false277278 /// Accuracy over the whole chart: anything not judged counts as zero.279 var accuracy: Double { totalJudgements > 0 ? tally.weightSum / Double(totalJudgements) : 0 }280 var grade: PulseGrade { PulseRules.grade(accuracy: accuracy) }281 var cleared: Bool { grade >= PulseRules.clearGrade }282 var fullCombo: Bool { totalJudgements > 0 && tally.judged == totalJudgements && tally.misses == 0 }283 var allPerfect: Bool { totalJudgements > 0 && tally.perfects == totalJudgements }284 var accuracyPermille: Int { Int((accuracy * 1000).rounded(.down)) }285 var accuracyLabel: String { String(format: "%.1f%%", Double(accuracyPermille) / 10) }286}287288nonisolated struct PulseInput: Sendable, Equatable {289 enum Action: Sendable, Equatable {290 case down(lane: Int)291 case up292 case flick(PulseSwipe)293 }294 /// Seconds on the audio timeline.295 var time: Double296 var touch: Int297 var action: Action298}299300/// One play of a chart. It only ever sees audio-timeline timestamps: touches bring their own, and `advance` is told the current one.301/// Nothing here depends on frame rate — the same inputs give the same result however often `advance` is called.302nonisolated struct PulseRun: Sendable {303 let chart: PulseChart304 private enum State: Sendable, Equatable {305 case pending306 case holding(touch: Int, ticks: Int)307 case flicking(touch: Int, judgement: PulseJudgement, offset: Double, deadline: Double)308 case done309 }310 private var states: [State]311 private var queues: [[Int]]312 private var cursors: [Int]313 private var active: [Int] = []314 private(set) var tally = PulseTally()315 private(set) var time = -Double.infinity316 private var resolved = 0317318 init(chart: PulseChart) {319 self.chart = chart320 states = Array(repeating: .pending, count: chart.notes.count)321 queues = Array(repeating: [], count: PulseChartBuilder.lanes)322 for (index, note) in chart.notes.enumerated() where note.lane >= 0 && note.lane < PulseChartBuilder.lanes { queues[note.lane].append(index) }323 cursors = Array(repeating: 0, count: PulseChartBuilder.lanes)324 }325326 var isFinished: Bool { resolved == chart.notes.count }327 var multiplier: Int { PulseRules.multiplier(combo: tally.combo) }328 var result: PulseResult { PulseResult(trackID: chart.trackID, difficulty: chart.difficulty, tally: tally, totalJudgements: chart.judgements) }329330 func isPending(_ note: Int) -> Bool { states[note] == .pending }331 func isResolved(_ note: Int) -> Bool { states[note] == .done }332 func isHeld(_ note: Int) -> Bool { if case .holding = states[note] { true } else { false } }333 func isAwaitingFlick(_ note: Int) -> Bool { if case .flicking = states[note] { true } else { false } }334 /// Lanes with a hold currently down.335 var heldLanes: Set<Int> { Set(active.filter { isHeld($0) }.map { chart.notes[$0].lane }) }336337 private func current(_ lane: Int) -> Int? {338 guard lane >= 0, lane < queues.count, cursors[lane] < queues[lane].count else { return nil }339 return queues[lane][cursors[lane]]340 }341342 // MARK: Scoring343344 private mutating func score(_ judgement: PulseJudgement, note: Int, offset: Double?, part: PulsePart, bonus: Int = 0, into events: inout [PulseEvent]) {345 let lane = chart.notes[note].lane346 tally.counts[judgement.rawValue] += 1347 if judgement == .miss {348 let lost = tally.combo349 tally.combo = 0350 events.append(.judged(note: note, lane: lane, judgement: .miss, offset: nil, part: part, combo: 0, points: 0))351 if lost > 0 {352 events.append(.comboBreak(lost: lost))353 if PulseRules.multiplier(combo: lost) > 1 { events.append(.multiplier(1)) }354 }355 return356 }357 let before = PulseRules.multiplier(combo: tally.combo)358 tally.combo += 1359 tally.maxCombo = max(tally.maxCombo, tally.combo)360 let multiplier = PulseRules.multiplier(combo: tally.combo)361 let points = (judgement.points + bonus) * multiplier362 tally.score += points363 if let offset {364 tally.offsetSum += offset365 tally.offsetCount += 1366 if judgement != .perfect { if offset < 0 { tally.early += 1 } else { tally.late += 1 } }367 }368 events.append(.judged(note: note, lane: lane, judgement: judgement, offset: offset, part: part, combo: tally.combo, points: points))369 if multiplier != before { events.append(.multiplier(multiplier)) }370 if PulseRules.isMilestone(tally.combo) { events.append(.milestone(combo: tally.combo)) }371 }372373 private mutating func finish(_ note: Int) {374 states[note] = .done375 resolved += 1376 active.removeAll { $0 == note }377 }378379 private mutating func miss(_ note: Int, into events: inout [PulseEvent]) {380 let isHold = chart.notes[note].isHold381 score(.miss, note: note, offset: nil, part: isHold ? .head : .tap, into: &events)382 if isHold { score(.miss, note: note, offset: nil, part: .tail, into: &events) }383 cursors[chart.notes[note].lane] += 1384 finish(note)385 }386387 /// Pays the sustain bonus of a hold up to `stamp`. Flat points, so the total never depends on when it is paid.388 private mutating func payTicks(_ note: Int, upTo stamp: Double) -> Bool {389 guard case .holding(let touch, let ticks) = states[note] else { return false }390 let info = chart.notes[note]391 let due = Int(((min(stamp, info.end) - info.time) / PulseRules.holdTick + 1e-9).rounded(.down))392 guard due > ticks else { return false }393 tally.score += (due - ticks) * PulseRules.holdTickPoints394 states[note] = .holding(touch: touch, ticks: due)395 return true396 }397398 // MARK: Time399400 /// Things that happen by themselves, each at an exact time: a note goes by unplayed (its window closes), a held note reaches its end,401 /// a tapped swipe is never flicked.402 private enum Automatic { case miss(Int), complete(Int), timeout(Int) }403404 private func nextAutomatic() -> (time: Double, event: Automatic)? {405 var best: (time: Double, event: Automatic)?406 for lane in 0..<queues.count {407 guard let note = current(lane) else { continue }408 let time = chart.notes[note].time + PulseRules.goodWindow409 if best == nil || time < (best?.time ?? 0) { best = (time, .miss(note)) }410 }411 for note in active {412 switch states[note] {413 case .holding:414 let time = chart.notes[note].end415 if best == nil || time < (best?.time ?? 0) { best = (time, .complete(note)) }416 case .flicking(_, _, _, let deadline):417 if best == nil || deadline < (best?.time ?? 0) { best = (deadline, .timeout(note)) }418 default:419 break420 }421 }422 return best423 }424425 /// Applies every automatic event up to `limit`, in the order they happen. Touches call it with their own timestamp first, so the whole426 /// run is one chronological sequence however rarely `advance` is called.427 private mutating func settle(upTo limit: Double, inclusive: Bool, into events: inout [PulseEvent]) {428 while let next = nextAutomatic(), inclusive ? next.time <= limit : next.time < limit - 1e-9 {429 switch next.event {430 case .miss(let note):431 miss(note, into: &events)432 case .complete(let note):433 _ = payTicks(note, upTo: chart.notes[note].end)434 tally.holdsCompleted += 1435 score(.perfect, note: note, offset: nil, part: .tail, into: &events)436 finish(note)437 case .timeout(let note):438 guard case .flicking(_, let judgement, let offset, _) = states[note] else { return }439 events.append(.swipeFailed(note: note, lane: chart.notes[note].lane))440 score(max(judgement, .good), note: note, offset: offset, part: .swipe, into: &events)441 finish(note)442 }443 }444 }445446 /// Moves the run to `now`. Automatic events are applied `missGrace` late, so a touch still on its way is never overtaken.447 @discardableResult448 mutating func advance(to now: Double) -> [PulseEvent] {449 var events: [PulseEvent] = []450 time = max(time, now)451 let settled = time - PulseRules.missGrace452 settle(upTo: settled, inclusive: true, into: &events)453 for note in active where payTicks(note, upTo: settled) { events.append(.holdTick(note: note, lane: chart.notes[note].lane)) }454 return events455 }456457 // MARK: Touches458459 @discardableResult460 mutating func touchDown(_ touch: Int, lane: Int, at stamp: Double) -> [PulseEvent] {461 var events: [PulseEvent] = []462 guard lane >= 0, lane < queues.count else { return events }463 settle(upTo: stamp, inclusive: false, into: &events)464 guard let note = current(lane), let judgement = PulseRules.judge(offset: stamp - chart.notes[note].time) else {465 tally.ghosts += 1466 events.append(.ghost(lane: lane))467 return events468 }469 let info = chart.notes[note]470 let offset = stamp - info.time471 cursors[lane] += 1472 switch info.kind {473 case .tap:474 score(judgement, note: note, offset: offset, part: .tap, into: &events)475 finish(note)476 case .hold:477 score(judgement, note: note, offset: offset, part: .head, into: &events)478 states[note] = .holding(touch: touch, ticks: 0)479 active.append(note)480 case .swipe:481 states[note] = .flicking(touch: touch, judgement: judgement, offset: offset, deadline: stamp + PulseRules.flickWindow)482 active.append(note)483 }484 return events485 }486487 @discardableResult488 mutating func touchUp(_ touch: Int, at stamp: Double) -> [PulseEvent] {489 var events: [PulseEvent] = []490 settle(upTo: stamp, inclusive: false, into: &events)491 for note in active {492 switch states[note] {493 case .holding(let owner, _) where owner == touch:494 let info = chart.notes[note]495 _ = payTicks(note, upTo: stamp)496 let judgement = PulseRules.judgeRelease(remaining: info.end - stamp)497 if judgement != .miss { tally.holdsCompleted += 1 }498 score(judgement, note: note, offset: nil, part: .tail, into: &events)499 finish(note)500 case .flicking(let owner, let judgement, let offset, _) where owner == touch:501 events.append(.swipeFailed(note: note, lane: chart.notes[note].lane))502 score(max(judgement, .good), note: note, offset: offset, part: .swipe, into: &events)503 finish(note)504 default:505 break506 }507 }508 return events509 }510511 @discardableResult512 mutating func flick(_ touch: Int, direction: PulseSwipe, at stamp: Double) -> [PulseEvent] {513 var events: [PulseEvent] = []514 settle(upTo: stamp, inclusive: false, into: &events)515 for note in active {516 guard case .flicking(let owner, let judgement, let offset, let deadline) = states[note], owner == touch else { continue }517 if direction == chart.notes[note].swipe, stamp <= deadline + 1e-9 {518 tally.swipesClean += 1519 score(judgement, note: note, offset: offset, part: .swipe, bonus: PulseRules.swipeBonus, into: &events)520 } else {521 events.append(.swipeFailed(note: note, lane: chart.notes[note].lane))522 score(max(judgement, .good), note: note, offset: offset, part: .swipe, into: &events)523 }524 finish(note)525 }526 return events527 }528529 /// Called when the game pauses: fingers leave the glass, so holds that are down carry on by themselves to their end.530 mutating func suspendHolds() {531 for note in active {532 if case .holding(_, let ticks) = states[note] { states[note] = .holding(touch: -1, ticks: ticks) }533 }534 }535536 @discardableResult537 mutating func apply(_ input: PulseInput) -> [PulseEvent] {538 switch input.action {539 case .down(let lane): touchDown(input.touch, lane: lane, at: input.time)540 case .up: touchUp(input.touch, at: input.time)541 case .flick(let direction): flick(input.touch, direction: direction, at: input.time)542 }543 }544545 /// Plays a whole timeline of touches. `frame` > 0 also advances the run on a fixed frame grid, as the live game does.546 static func simulate(_ chart: PulseChart, inputs: [PulseInput], frame: Double = 0) -> PulseResult {547 var run = PulseRun(chart: chart)548 var clock = -1.0549 for input in inputs.sorted(by: { $0.time < $1.time }) {550 if frame > 0 {551 while clock + frame < input.time {552 clock += frame553 run.advance(to: clock)554 }555 } else {556 run.advance(to: input.time)557 }558 run.apply(input)559 }560 if frame > 0 {561 while clock < chart.duration + 1 {562 clock += frame563 run.advance(to: clock)564 }565 }566 run.advance(to: chart.duration + 1)567 return run.result568 }569}570571/// The built-in player: taps, holds and flicks every note with a small seeded timing error, so its scores look like a good human's.572nonisolated enum PulseBot {573 static func inputs(for chart: PulseChart, seed: UInt64, sigma: Double = 0.02, missRate: Double = 0.004) -> [PulseInput] {574 var rng = SeededRNG(seed: seed ^ 0xB07)575 var inputs: [PulseInput] = []576 for (index, note) in chart.notes.enumerated() {577 let skip = rng.chance(missRate)578 // Three uniforms summed: close to a normal distribution with standard deviation `sigma`.579 let error = ((rng.unit() + rng.unit() + rng.unit() - 1.5) * 2 * sigma).clamped(-0.09, 0.09)580 if skip { continue }581 let down = note.time + error582 inputs.append(PulseInput(time: down, touch: index, action: .down(lane: note.lane)))583 switch note.kind {584 case .tap:585 inputs.append(PulseInput(time: down + 0.06, touch: index, action: .up))586 case .hold:587 inputs.append(PulseInput(time: note.end + 0.04, touch: index, action: .up))588 case .swipe:589 inputs.append(PulseInput(time: down + 0.05, touch: index, action: .flick(note.swipe ?? .up)))590 inputs.append(PulseInput(time: down + 0.09, touch: index, action: .up))591 }592 }593 return inputs.enumerated().sorted { $0.element.time != $1.element.time ? $0.element.time < $1.element.time : $0.offset < $1.offset }.map(\.element)594 }595596 static func play(_ chart: PulseChart, seed: UInt64, sigma: Double = 0.02, missRate: Double = 0.004) -> PulseResult {597 var result = PulseRun.simulate(chart, inputs: inputs(for: chart, seed: seed, sigma: sigma, missRate: missRate))598 result.autoplay = true599 return result600 }601}602603// MARK: - Timing604605/// How a position on the rendered audio timeline becomes what the player hears and sees.606nonisolated struct PulseTiming: Sendable, Equatable {607 /// Seconds between rendering a sample and hearing it, as reported by the system for the current route.608 var latency = 0.0609 /// The player's calibration for the current route, in seconds. Positive: judge later.610 var offset = 0.0611 /// Shifts only the drawing. Positive: notes reach the line earlier.612 var visualOffset = 0.0613614 /// The audio-timeline position the player is hearing when the renderer is at `raw`.615 func judged(raw: Double) -> Double { raw - latency + offset }616 func visual(judged: Double) -> Double { judged + visualOffset }617}618619nonisolated enum PulseCalibration {620 static let clickCount = 16621 static let interval = 0.6622 static let lead = 1.2623 /// The first clicks only set the pulse; taps on them are not measured.624 static let warmUp = 4625 static let minimumTaps = 6626 static let limitMs = 400627628 struct Measurement: Sendable, Equatable {629 /// Median of (tap − click) on the rendered timeline, in seconds: what the player's ears and thumb add up to.630 var delay: Double631 /// Median absolute deviation of the taps, in seconds: how steady they were.632 var spread: Double633 var used: Int634 }635636 /// Matches each tap to the click it answers and returns the median delay. Taps may come up to 150 ms before their click637 /// (anticipation) and up to `interval − 150 ms` after it (a slow route). `nil` when there are too few usable taps.638 static func measure(taps: [Double], clicks: [Double], interval: Double = PulseCalibration.interval, warmUp: Int = PulseCalibration.warmUp) -> Measurement? {639 guard clicks.count > warmUp else { return nil }640 let measured = Array(clicks.dropFirst(warmUp))641 var delays: [Double] = []642 for tap in taps {643 guard let click = measured.last(where: { $0 <= tap + 0.15 }) else { continue }644 let delay = tap - click645 if delay < interval - 0.15 { delays.append(delay) }646 }647 guard delays.count >= minimumTaps else { return nil }648 let center = median(delays)649 let spread = median(delays.map { abs($0 - center) })650 let kept = delays.filter { abs($0 - center) <= max(0.06, spread * 2.5) }651 guard kept.count >= minimumTaps else { return nil }652 let refined = median(kept)653 return Measurement(delay: refined, spread: median(kept.map { abs($0 - refined) }), used: kept.count)654 }655656 /// The calibration offset that makes a tap on the heard click judge as exactly on time, given the latency the system already reports.657 static func offsetMs(delay: Double, reportedLatency: Double) -> Int {658 Int(((reportedLatency - delay) * 1000).rounded()).clamped(-limitMs, limitMs)659 }660661 static func median(_ values: [Double]) -> Double {662 guard !values.isEmpty else { return 0 }663 let sorted = values.sorted()664 let middle = sorted.count / 2665 return sorted.count.isMultiple(of: 2) ? (sorted[middle - 1] + sorted[middle]) / 2 : sorted[middle]666 }667}668669/// The playback clock. A segment of the track starts on a known frame at a known host time; between audio render callbacks the position is670/// extrapolated with the host clock, and every render timestamp nudges the estimate back onto the audio so the two can never drift apart.671nonisolated struct PulseClock: Sendable, Equatable {672 static let rate = Synth.sampleRate673 /// Share of the measured error corrected by each observation: small enough that notes never visibly step.674 static let slew = 0.08675 /// Beyond this the audio really jumped (a glitch, a stall): follow it at once.676 static let snapThreshold = 0.08677678 /// Frame of the track the current segment starts on.679 private(set) var baseFrame = 0680 /// Host time (seconds) at which `baseFrame` is rendered; nil while paused.681 private(set) var anchorHost: Double?682 private(set) var correction = 0.0683 private var lastObservedHost = -Double.infinity684 private(set) var observations = 0685 private(set) var largestError = 0.0686687 var isRunning: Bool { anchorHost != nil }688 var basePosition: Double { Double(baseFrame) / Self.rate }689690 mutating func start(fromFrame frame: Int, atHost host: Double) {691 baseFrame = max(0, frame)692 anchorHost = host693 correction = 0694 lastObservedHost = -Double.infinity695 }696697 /// Position on the rendered timeline, in seconds, at host time `host`. Negative before a segment that starts at frame 0 (the count-in).698 func position(atHost host: Double) -> Double {699 guard let anchorHost else { return basePosition }700 return basePosition + (host - anchorHost) + correction701 }702703 /// Feeds one audio render timestamp: at host time `host` the player had rendered `playedFrames` frames of this segment.704 mutating func observe(playedFrames: Double, atHost host: Double) {705 guard anchorHost != nil, host > lastObservedHost, playedFrames >= 0 else { return }706 lastObservedHost = host707 let error = basePosition + playedFrames / Self.rate - position(atHost: host)708 observations += 1709 largestError = max(largestError, abs(error))710 correction += abs(error) > Self.snapThreshold ? error : error * Self.slew711 }712713 /// Stops the clock and returns the frame to resume from: where it was, minus `rewind` seconds (audio rendered but never heard).714 @discardableResult715 mutating func pause(atHost host: Double, rewind: Double = 0) -> Int {716 guard anchorHost != nil else { return baseFrame }717 baseFrame = max(0, Int(((position(atHost: host) - rewind) * Self.rate).rounded()))718 anchorHost = nil719 correction = 0720 lastObservedHost = -Double.infinity721 return baseFrame722 }723}724