// LyrebirdScopeModel.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT #if !canImport(SwiftUI) import LyrebirdSynth import Observation import Foundation /// Observable model that polls a `ScopeCapture` on a main-thread timer and /// publishes the latest per-channel sample frame for ``LyrebirdScopeView`` to draw. /// /// `@unchecked Sendable`: every access is confined to the UI (GTK main) thread — /// the poll `Timer` fires on `RunLoop.main`, and `start`/`stop`/`channels` are /// only touched from that thread — but `Timer`'s block is `@Sendable`, so the /// capture requires the conformance. The confinement, not the type system, is /// what makes it safe (same rationale as `UIParamNode`). @Observable public final class LyrebirdScopeModel: @unchecked Sendable { /// Latest snapshot: `[channelIndex][sampleIndex]`. Written on the main thread /// by the poll timer; read by the `Canvas` renderer. public internal(set) var channels: [[Float]] = [] @ObservationIgnored private var timer: Timer? @ObservationIgnored private let capture: ScopeCapture @ObservationIgnored private let pollInterval: TimeInterval /// - Parameters: /// - capture: The `ScopeCapture` to poll (typically the engine's `scopeTap`). /// - pollInterval: Seconds between snapshots. Default ≈ 30 Hz. public init( capture: ScopeCapture, pollInterval: TimeInterval = 1.0 / 30.0 ) { self.capture = capture self.pollInterval = pollInterval } deinit { timer?.invalidate() } /// Begin polling. Idempotent. Must be called on the main thread. public func start() { guard timer == nil else { return } let t: Timer = Timer.scheduledTimer(withTimeInterval: pollInterval, repeats: true) { [weak self] _ in guard let self else { return } self.channels = self.capture.snapshot() } timer = t } /// Stop polling. Idempotent. public func stop() { timer?.invalidate() timer = nil } } #endif