SPB Git

Repository Public License

PulseTransport.swift 12.4 KB 294 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Arcade9// File             : Games/PulseBeat/PulseTransport.swift10// Description      : Pulse Beat — the live audio side: a transport that plays a11//                    rendered track on its own player node and reads the12//                    playback position from the audio clock, the audio-route13//                    lookup, and the off-main-thread track renderer with its14//                    one-track cache.15// Module           : Games16// Repository       : https://git.spboucher.ai/orix-arcade17// Created          : 2026-11-2218// Last Modified    : 2026-11-2219//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author           : Simon-Pierre Boucher25// Position         : Professor of Finance26// Institution      : Université du Québec en Outaouais (UQO)27// Department       : Département des sciences administratives28// Organization     : SP Boucher29//30// Website          : https://spboucher.ai31// Git              : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General          : info@spboucher.ai38// Professional     : contact@spboucher.ai39// Direct           : simon@spboucher.ai40// Research         : research@spboucher.ai41// Development      : dev@spboucher.ai42// Support          : support@spboucher.ai43// Security/Admin   : admin@spboucher.ai44// Notifications    : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification   : Public71// Distribution     : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License          : Proprietary, all rights reserved (see license file)85// License File     : LICENSE86// Maintainer       : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import AVFoundation94import QuartzCore9596/// The kind of output the sound is going to. Calibration is stored separately for each, because Bluetooth adds latency the system under-reports.97nonisolated enum PulseRoute: String, Sendable, CaseIterable {98    case wired, bluetooth99100    var title: String {101        switch self {102        case .wired: "Speaker or wired"103        case .bluetooth: "Bluetooth"104        }105    }106107    var symbol: String {108        switch self {109        case .wired: "speaker.wave.2.fill"110        case .bluetooth: "headphones"111        }112    }113114    static var current: PulseRoute {115        let wireless: Set<AVAudioSession.Port> = [.bluetoothA2DP, .bluetoothLE, .bluetoothHFP]116        return AVAudioSession.sharedInstance().currentRoute.outputs.contains { wireless.contains($0.portType) } ? .bluetooth : .wired117    }118}119120/// A rendered track, ready to play. The buffer is nil when audio is disabled (`-ORIXMute YES`): the game then runs on the host clock alone.121final class PulsePrepared {122    let trackID: String123    let buffer: AVAudioPCMBuffer?124    let frames: Int125    let envelope: PulseEnvelope126    /// Seconds the synthesiser took, measured for the notes.127    let renderSeconds: Double128129    init(trackID: String, buffer: AVAudioPCMBuffer?, frames: Int, envelope: PulseEnvelope, renderSeconds: Double) {130        self.trackID = trackID131        self.buffer = buffer132        self.frames = frames133        self.envelope = envelope134        self.renderSeconds = renderSeconds135    }136137    /// Bytes held by the playback buffer (stereo Float32).138    var bytes: Int { buffer == nil ? 0 : frames * 8 }139}140141private nonisolated final class PulseRenderBox: @unchecked Sendable {142    let buffer: AVAudioPCMBuffer?143    let frames: Int144    let envelope: PulseEnvelope145    let seconds: Double146    init(buffer: AVAudioPCMBuffer?, frames: Int, envelope: PulseEnvelope, seconds: Double) {147        self.buffer = buffer148        self.frames = frames149        self.envelope = envelope150        self.seconds = seconds151    }152}153154/// Renders tracks off the main thread and keeps the last one, so a retry starts at once. Released when the game closes.155final class PulseTrackStore {156    private var cached: PulsePrepared?157158    func prepared(for spec: PulseTrackSpec, playable: Bool) async -> PulsePrepared {159        if let cached, cached.trackID == spec.id, cached.buffer != nil || !playable { return cached }160        cached = nil161        let id = spec.id162        let box = await Task.detached(priority: .userInitiated) { () -> PulseRenderBox in163            let started = CACurrentMediaTime()164            let mono = PulseSynth.render(PulseLibrary.song(id))165            let envelope = PulseSynth.envelope(of: mono)166            let buffer = playable ? AudioDirector.makeBuffer(mono: mono) : nil167            return PulseRenderBox(buffer: buffer, frames: mono.count, envelope: envelope, seconds: CACurrentMediaTime() - started)168        }.value169        let prepared = PulsePrepared(trackID: id, buffer: box.buffer, frames: box.frames, envelope: box.envelope, renderSeconds: box.seconds)170        cached = prepared171        return prepared172    }173174    func release() { cached = nil }175}176177/// Plays one buffer and tells the time.178///179/// A segment is scheduled to start on a known frame at a known host time (`AVAudioPlayerNode.play(at:)`), which anchors `PulseClock`.180/// Every frame, `poll()` reads the player's own sample position from the last render timestamp and feeds it to the clock, so the estimate181/// follows the audio hardware rather than the display. Without a running audio engine the same clock simply runs on the host time.182final class PulseTransport {183    private let audio: AudioDirector184    private var player: AVAudioPlayerNode?185    private var buffer: AVAudioPCMBuffer?186    private var segment: AVAudioPCMBuffer?187    private(set) var clock = PulseClock()188    private(set) var frames = 0189    /// True while the current segment is really sounding through the engine.190    private(set) var usingAudio = false191    var timing = PulseTiming()192193    init(audio: AudioDirector) {194        self.audio = audio195    }196197    var duration: Double { Double(frames) / PulseClock.rate }198    var isRunning: Bool { clock.isRunning }199200    func load(buffer: AVAudioPCMBuffer?, frames: Int) {201        stop()202        self.buffer = buffer203        self.frames = frames204        if buffer != nil, player == nil { player = audio.makeMusicPlayer() }205    }206207    /// Re-reads the output latency of the current route. Call before each start: the route may have changed while paused.208    func refreshLatency() {209        timing.latency = audio.isRunning ? audio.outputLatency : 0210    }211212    /// Starts playing from `frame`, `delay` seconds from now. Before that moment the position runs up to it from below (the count-in).213    func start(fromFrame frame: Int, delay: Double) {214        let from = min(max(0, frame), max(0, frames - 1))215        player?.stop()216        segment = nil217        usingAudio = false218        refreshLatency()219        var anchor = CACurrentMediaTime() + delay220        if let player, let buffer, audio.isRunning, let tail = Self.tail(of: buffer, from: from) {221            let startTicks = mach_absolute_time() + AVAudioTime.hostTime(forSeconds: delay)222            player.scheduleBuffer(tail, at: nil, options: [])223            player.play(at: AVAudioTime(hostTime: startTicks))224            anchor = AVAudioTime.seconds(forHostTime: startTicks)225            segment = tail226            usingAudio = true227        }228        clock.start(fromFrame: from, atHost: anchor)229    }230231    /// Stops the sound and freezes the clock. Returns the frame to resume from: what was heard, not what was merely rendered.232    @discardableResult233    func pause() -> Int {234        let frame = clock.pause(atHost: CACurrentMediaTime(), rewind: usingAudio ? timing.latency : 0)235        player?.stop()236        segment = nil237        usingAudio = false238        return frame239    }240241    func stop() {242        player?.stop()243        segment = nil244        usingAudio = false245        clock = PulseClock()246    }247248    /// Releases the player node. The transport cannot be used afterwards.249    func dispose() {250        stop()251        if let player { audio.releasePlayer(player) }252        player = nil253        buffer = nil254    }255256    /// Feeds the clock with the newest audio render timestamp. Call once per frame.257    func poll() {258        guard usingAudio, let player, player.isPlaying, let nodeTime = player.lastRenderTime, nodeTime.isSampleTimeValid, nodeTime.isHostTimeValid,259              let playerTime = player.playerTime(forNodeTime: nodeTime), playerTime.sampleTime >= 0, playerTime.sampleRate > 0 else { return }260        clock.observe(playedFrames: Double(playerTime.sampleTime) * PulseClock.rate / playerTime.sampleRate,261                      atHost: AVAudioTime.seconds(forHostTime: nodeTime.hostTime))262    }263264    /// True when the segment should be sounding but the engine or the player stopped underneath it (interruption, route change).265    var isStalled: Bool {266        guard usingAudio, clock.isRunning else { return false }267        let now = CACurrentMediaTime()268        guard rawPosition(atHost: now) > 0.25, rawPosition(atHost: now) < duration - 0.25 else { return false }269        return !audio.isRunning || player?.isPlaying != true270    }271272    /// Position on the rendered timeline at a host time (the timebase of `CACurrentMediaTime` and `UITouch.timestamp`).273    func rawPosition(atHost host: Double) -> Double { clock.position(atHost: host) }274    /// The position the player is hearing at a host time: what touches are judged against.275    func judgedPosition(atHost host: Double) -> Double { timing.judged(raw: clock.position(atHost: host)) }276    func judgedNow() -> Double { judgedPosition(atHost: CACurrentMediaTime()) }277278    /// The part of `buffer` from `frame` to its end, as a buffer of its own. Copied only when resuming after a pause (a plain memory copy,279    /// at most the size of the track), and released as soon as the segment stops.280    private static func tail(of buffer: AVAudioPCMBuffer, from frame: Int) -> AVAudioPCMBuffer? {281        let length = Int(buffer.frameLength)282        guard frame < length else { return nil }283        if frame == 0 { return buffer }284        let remaining = length - frame285        guard let source = buffer.floatChannelData, let tail = AVAudioPCMBuffer(pcmFormat: buffer.format, frameCapacity: AVAudioFrameCount(remaining)),286              let target = tail.floatChannelData else { return nil }287        for channel in 0..<Int(buffer.format.channelCount) {288            target[channel].update(from: source[channel] + frame, count: remaining)289        }290        tail.frameLength = AVAudioFrameCount(remaining)291        return tail292    }293}294
Files main
Menu

Theme