public struct FrameBatch: Sendable, Equatable { public let identifier: UInt64 public let appID: MotionAppID public let frames: [MotionFrame] public let dispatchedAt: Double public func resampled(_ sample: (MotionFrame) throws -> MotionFrame) rethrows -> Self { let updated = try frames.map(sample) precondition( zip(frames, updated).allSatisfy { $0.windowID == $1.windowID && $0.appID == $1.appID && $0.generation == $1.generation && $0.revision == $1.revision }) return Self(identifier: identifier, appID: appID, frames: updated, dispatchedAt: dispatchedAt) } } public struct FrameCoalescer: Sendable { public let fullFrameRate: Double public private(set) var pendingCount: Int = 0 public var inFlightCount: Int { inFlight.count } public var metricsSnapshot: [MotionAppID: AppWriteMetrics] { metrics } private var pending: [MotionAppID: [MotionWindowID: MotionFrame]] = [:] private var appOrder: [MotionAppID] = [] private var newest: [MotionWindowID: MotionFrame] = [:] private var inFlight: [MotionAppID: UInt64] = [:] private var lastDispatch: [MotionAppID: Double] = [:] private var displayRates: [MotionAppID: Double] = [:] private var metrics: [MotionAppID: AppWriteMetrics] = [:] private var generations: [MotionWindowID: UInt64] = [:] private var activeWindows: [MotionWindowID: MotionAppID] = [:] private var inactiveApps: Set = [] private var timestamp: Double? private var nextBatch: UInt64 = 0 public init(fullFrameRate: Double = 120) { precondition(fullFrameRate.isFinite && fullFrameRate > 0) self.fullFrameRate = fullFrameRate } @discardableResult public mutating func submit(_ frame: MotionFrame) throws -> Bool { guard frame.timestamp.isFinite else { throw MotionError.invalidTimestamp } guard !inactiveApps.contains(frame.appID) else { return false } if generations[frame.windowID] == nil && frame.generation == 0 { generations[frame.windowID] = 0 activeWindows[frame.windowID] = frame.appID } guard activeWindows[frame.windowID] == frame.appID, generations[frame.windowID] == frame.generation else { return false } if let previous = newest[frame.windowID] { if frame.revision < previous.revision { return false } if frame.revision == previous.revision && frame.timestamp <= previous.timestamp { return false } } if pending[frame.appID] == nil { pending[frame.appID] = [:] appOrder.append(frame.appID) appOrder.sort() } if pending[frame.appID]?.updateValue(frame, forKey: frame.windowID) == nil { pendingCount += 1 } newest[frame.windowID] = frame return true } public mutating func takeReady(at timestamp: Double) throws -> [FrameBatch] { try validateTime(timestamp) self.timestamp = timestamp var batches: [FrameBatch] = [] for appID in appOrder { guard inFlight[appID] == nil, pending[appID]?.isEmpty == false else { continue } let interval = 1 / frameRate(for: appID) // Display timestamps are rounded at system-uptime magnitude, not near zero. let tolerance = max(interval * 0.000_001, timestamp.ulp * 4) if let last = lastDispatch[appID], timestamp - last + tolerance < interval { continue } let frames = pending[appID, default: [:]].values.filter { $0.timestamp <= timestamp } .sorted { $0.windowID < $1.windowID } guard !frames.isEmpty else { continue } nextBatch += 1 let batch = FrameBatch(identifier: nextBatch, appID: appID, frames: frames, dispatchedAt: timestamp) inFlight[appID] = batch.identifier lastDispatch[appID] = timestamp pendingCount -= frames.count if frames.count == pending[appID]?.count { pending[appID]?.removeAll(keepingCapacity: true) } else { for frame in frames { pending[appID]?[frame.windowID] = nil } } batches.append(batch) } return batches } public mutating func complete( _ batch: FrameBatch, duration: Double, writtenWindows: Int? = nil, timedOut: Bool = false, at timestamp: Double ) throws { try validateTime(timestamp) guard inFlight[batch.appID] == batch.identifier else { throw MotionError.unknownBatch } var appMetrics = metrics[batch.appID] ?? AppWriteMetrics() let count = writtenWindows ?? batch.frames.count precondition(count > 0) try appMetrics.record(duration: duration / Double(count), timedOut: timedOut, at: timestamp) metrics[batch.appID] = appMetrics inFlight[batch.appID] = nil self.timestamp = timestamp } public mutating func setDisplayRate(_ rate: Double, for appID: MotionAppID) { precondition(rate.isFinite && rate > 0) displayRates[appID] = rate } public func frameRate(for appID: MotionAppID) -> Double { let fullRate = displayRates[appID] ?? fullFrameRate return metrics[appID]?.frameRate(fullRate: fullRate, windowsInMotion: max(1, pending[appID]?.count ?? 0)) ?? fullRate } public mutating func setMetrics(_ metrics: AppWriteMetrics, for appID: MotionAppID) { self.metrics[appID] = metrics } public mutating func resetMetrics(for appID: MotionAppID) { metrics[appID] = nil } /// Start a new generation before transferring between animators or reusing a window identifier. public mutating func activate(_ windowID: MotionWindowID, appID: MotionAppID) -> UInt64 { discardPending(windowID) let generation = generations[windowID, default: 0] + 1 generations[windowID] = generation activeWindows[windowID] = appID inactiveApps.remove(appID) newest[windowID] = nil return generation } public func generation(for windowID: MotionWindowID) -> UInt64? { activeWindows[windowID] == nil ? nil : generations[windowID] } private mutating func discardPending(_ windowID: MotionWindowID) { guard let app = activeWindows[windowID] else { return } if pending[app]?.removeValue(forKey: windowID) != nil { pendingCount -= 1 } } public mutating func remove(_ windowID: MotionWindowID) { discardPending(windowID) // Keep the watermark so a late producer cannot resurrect a removed window. if generations[windowID] == nil { generations[windowID] = 0 } activeWindows[windowID] = nil newest[windowID] = nil } public mutating func removeApp(_ appID: MotionAppID) { for windowID in activeWindows.keys.filter({ activeWindows[$0] == appID }) { remove(windowID) } pending[appID] = nil appOrder.removeAll { $0 == appID } inFlight[appID] = nil lastDispatch[appID] = nil displayRates[appID] = nil metrics[appID] = nil inactiveApps.insert(appID) } private func validateTime(_ timestamp: Double) throws { guard timestamp.isFinite else { throw MotionError.invalidTimestamp } if let previous = self.timestamp, timestamp < previous { throw MotionError.timestampWentBackwards } } }