SPB Git

Repository Public

Preflight.swift 9.6 KB 176 lines swift

1// SP Lecture Studio — LectureCapture2// File: Packages/LectureCapture/Sources/Preflight.swift3// Description: Preflight test before a lecture (permissions, input level, storage, battery, thermal state, output settings) and system status helpers.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import AVFoundation9import LectureCore10import LectureStorage11#if os(iOS)12import UIKit13#elseif os(macOS)14import IOKit.ps15#endif1617public enum SystemStatus {18    /// Battery charge in percent, nil when the device has no battery (desktop Mac) or the level is unknown.19    public static func batteryPercent() -> Int? {20        #if os(iOS)21        let level: Float = MainActorBridge.sync { UIDevice.current.isBatteryMonitoringEnabled = true; return UIDevice.current.batteryLevel }22        return level >= 0 ? Int((level * 100).rounded()) : nil23        #else24        guard let info = IOPSCopyPowerSourcesInfo()?.takeRetainedValue(), let list = IOPSCopyPowerSourcesList(info)?.takeRetainedValue() as? [CFTypeRef] else { return nil }25        for ps in list {26            guard let d = IOPSGetPowerSourceDescription(info, ps)?.takeUnretainedValue() as? [String: Any], d[kIOPSTypeKey] as? String == kIOPSInternalBatteryType,27                  let cur = d[kIOPSCurrentCapacityKey] as? Int, let max = d[kIOPSMaxCapacityKey] as? Int, max > 0 else { continue }28            return cur * 100 / max29        }30        return nil31        #endif32    }3334    public static func isCharging() -> Bool {35        #if os(iOS)36        let state: UIDevice.BatteryState = MainActorBridge.sync { UIDevice.current.isBatteryMonitoringEnabled = true; return UIDevice.current.batteryState }37        return state == .charging || state == .full38        #else39        guard let info = IOPSCopyPowerSourcesInfo()?.takeRetainedValue() else { return true }40        return (IOPSGetProvidingPowerSourceType(info)?.takeUnretainedValue() as String?) == kIOPMACPowerKey41        #endif42    }43}4445enum MainActorBridge {46    /// Runs a UIKit read on the main thread from any thread without deadlocking when already on it.47    static func sync<T>(_ body: @MainActor () -> T) -> T {48        if Thread.isMainThread { return MainActor.assumeIsolated(body) }49        return DispatchQueue.main.sync { MainActor.assumeIsolated(body) }50    }51}5253public enum PreflightStatus: String, Sendable { case ok, warning, failure }5455public enum PreflightItemKind: String, Sendable, CaseIterable { case microphone, camera, inputLevel, storage, battery, thermal, output }5657public struct PreflightItem: Sendable, Hashable, Identifiable {58    public var kind: PreflightItemKind59    public var status: PreflightStatus60    /// Machine-readable reason, localized by the app.61    public var code: String62    /// Numbers to insert in the message (levels in dB, minutes, percent…).63    public var values: [Double]64    public var id: String { kind.rawValue }65}6667public struct PreflightMeasurement: Sendable {68    public var microphone: CapturePermission69    public var camera: CapturePermission70    public var cameraWanted: Bool71    /// Level samples (dBFS RMS) collected during the test; empty when the microphone could not be opened.72    public var levels: [Double]73    public var peak: Float74    public var freeBytes: Int6475    public var plannedMinutes: Double76    public var batteryPercent: Int?77    public var charging: Bool78    public var thermal: ProcessInfo.ThermalState79    public var settings: (width: Int, height: Int, hevc: Bool, hevcAvailable: Bool)8081    public init(microphone: CapturePermission, camera: CapturePermission, cameraWanted: Bool, levels: [Double], peak: Float, freeBytes: Int64, plannedMinutes: Double,82                batteryPercent: Int?, charging: Bool, thermal: ProcessInfo.ThermalState, settings: (width: Int, height: Int, hevc: Bool, hevcAvailable: Bool)) {83        self.microphone = microphone; self.camera = camera; self.cameraWanted = cameraWanted; self.levels = levels; self.peak = peak; self.freeBytes = freeBytes84        self.plannedMinutes = plannedMinutes; self.batteryPercent = batteryPercent; self.charging = charging; self.thermal = thermal; self.settings = settings85    }86}8788public enum Preflight {89    /// Bytes of source media per minute of recording: 16-bit mono PCM audio, plus the camera when used.90    public static func bytesPerMinute(sampleRate: Double = 48_000, camera: Bool) -> Int64 {91        Int64(sampleRate * 2 * 60) + (camera ? 45_000_000 : 0)92    }9394    /// Pure evaluation of the measurements (unit-tested); the app collects them with the real devices.95    public static func evaluate(_ m: PreflightMeasurement) -> [PreflightItem] {96        var items: [PreflightItem] = []97        switch m.microphone {98        case .granted: items.append(.init(kind: .microphone, status: .ok, code: "mic.granted", values: []))99        case .undetermined: items.append(.init(kind: .microphone, status: .warning, code: "mic.undetermined", values: []))100        case .denied: items.append(.init(kind: .microphone, status: .failure, code: "mic.denied", values: []))101        }102        if m.cameraWanted {103            switch m.camera {104            case .granted: items.append(.init(kind: .camera, status: .ok, code: "camera.granted", values: []))105            case .undetermined: items.append(.init(kind: .camera, status: .warning, code: "camera.undetermined", values: []))106            case .denied: items.append(.init(kind: .camera, status: .warning, code: "camera.denied", values: []))107            }108        }109        if m.microphone == .granted {110            if m.levels.isEmpty {111                items.append(.init(kind: .inputLevel, status: .failure, code: "level.nosignal", values: []))112            } else {113                let sorted = m.levels.sorted()114                let loud = sorted[Int(Double(sorted.count - 1) * 0.9)], floor = sorted[Int(Double(sorted.count - 1) * 0.1)]115                if loud < -70 { items.append(.init(kind: .inputLevel, status: .failure, code: "level.silent", values: [loud])) }116                else if m.peak >= 0.99 { items.append(.init(kind: .inputLevel, status: .warning, code: "level.clipping", values: [loud])) }117                else if loud < -38 { items.append(.init(kind: .inputLevel, status: .warning, code: "level.low", values: [loud])) }118                else if loud - floor < 12 { items.append(.init(kind: .inputLevel, status: .warning, code: "level.noisy", values: [loud, floor])) }119                else { items.append(.init(kind: .inputLevel, status: .ok, code: "level.good", values: [loud, floor])) }120            }121        }122        let perMinute = bytesPerMinute(camera: m.cameraWanted && m.camera == .granted)123        let minutes = Double(m.freeBytes) / Double(perMinute)124        // Keep room for the export too (roughly as much again).125        if minutes < m.plannedMinutes { items.append(.init(kind: .storage, status: .failure, code: "storage.insufficient", values: [minutes, m.plannedMinutes])) }126        else if minutes < m.plannedMinutes * 3 { items.append(.init(kind: .storage, status: .warning, code: "storage.tight", values: [minutes, m.plannedMinutes])) }127        else { items.append(.init(kind: .storage, status: .ok, code: "storage.good", values: [min(minutes, 100_000), m.plannedMinutes])) }128        if let b = m.batteryPercent {129            if m.charging { items.append(.init(kind: .battery, status: .ok, code: "battery.charging", values: [Double(b)])) }130            else if b < 20 { items.append(.init(kind: .battery, status: .failure, code: "battery.low", values: [Double(b)])) }131            else if b < 50 && m.plannedMinutes > 45 { items.append(.init(kind: .battery, status: .warning, code: "battery.medium", values: [Double(b)])) }132            else { items.append(.init(kind: .battery, status: .ok, code: "battery.good", values: [Double(b)])) }133        }134        switch m.thermal {135        case .nominal, .fair: items.append(.init(kind: .thermal, status: .ok, code: "thermal.good", values: []))136        case .serious: items.append(.init(kind: .thermal, status: .warning, code: "thermal.serious", values: []))137        case .critical: items.append(.init(kind: .thermal, status: .failure, code: "thermal.critical", values: []))138        @unknown default: break139        }140        if m.settings.hevc && !m.settings.hevcAvailable { items.append(.init(kind: .output, status: .warning, code: "output.hevc.unavailable", values: [])) }141        else { items.append(.init(kind: .output, status: .ok, code: "output.good", values: [Double(m.settings.width), Double(m.settings.height)])) }142        return items143    }144145    public static func worst(_ items: [PreflightItem]) -> PreflightStatus {146        items.contains { $0.status == .failure } ? .failure : items.contains { $0.status == .warning } ? .warning : .ok147    }148}149150/// Collects input levels for the preflight test (and for the idle microphone meter).151public final class LevelSampler {152    private let source: MicrophoneSource153    private let lock = NSLock()154    private var levels: [Double] = []155    private var peak: Float = 0156    public var onLevel: ((Double, Float) -> Void)?157158    public init(deviceID: String? = nil) { source = MicrophoneSource(); source.preferredDeviceID = deviceID }159160    public func start() throws {161        source.onBuffer = { [weak self] buffer, _ in162            guard let self else { return }163            let (rms, pk) = RecordingEngine.level(buffer)164            self.lock.lock(); self.levels.append(Double(rms)); self.peak = max(self.peak, pk); self.lock.unlock()165            let cb = self.onLevel166            DispatchQueue.main.async { cb?(Double(rms), pk) }167        }168        try source.start()169    }170    public func stop() -> (levels: [Double], peak: Float) {171        source.stop()172        lock.lock(); defer { lock.unlock() }173        return (levels, peak)174    }175}176
Files main
Menu

Theme