Repository Public
1// SP Lecture Studio — LectureCore2// File: Packages/LectureCore/Sources/AutoPause.swift3// Description: Opt-in automatic pause / stop policies as a pure, testable state machine (manual control always wins).4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation89/// Every policy is off by default. Nothing is ever discarded: the strongest automatic action is a clean stop that saves the session.10public struct AutoPausePolicy: Sendable, Codable, Hashable {11 public var silenceEnabled = false12 /// Seconds without voice before a pause is suggested.13 public var silenceSeconds: Double = 4514 public var inactivityEnabled = false15 /// Seconds without voice AND without slide / ink interaction before the countdown starts.16 public var inactivitySeconds: Double = 30017 public var maxDurationEnabled = false18 public var maxDurationSeconds: Double = 3 * 360019 public var endTimeEnabled = false20 public var endTime: Date?21 /// Length of the warning countdown shown before an automatic pause or stop.22 public var countdownSeconds: Double = 3023 /// When the countdown ends: false = pause (default, resumable), true = stop and save.24 public var stopWhenCountdownEnds = false25 public var voiceThresholdDB: Double = -4226 /// Level must fall this much below the threshold before speech is considered finished.27 public var hysteresisDB: Double = 628 /// Voice is still considered active this long after the last loud frame (protects quiet word endings).29 public var hangoverSeconds: Double = 0.630 public var endPhraseEnabled = false31 public var endPhrase = "fin de l'enregistrement"32 public var retakePhraseEnabled = false33 public var retakePhrase = "reprendre"34 /// Audio kept from just before a resume so that the first syllable is not clipped.35 public var preRollSeconds: Double = 0.336 public init() {}37 public var anyEnabled: Bool { silenceEnabled || inactivityEnabled || maxDurationEnabled || endTimeEnabled || endPhraseEnabled }38}3940public struct AutoPauseEngine: Sendable {41 public enum Output: Sendable, Hashable {42 case suggestPause(AutoPolicyKind)43 case withdrawSuggestion44 case countdownStarted(AutoPolicyKind, seconds: Double)45 case countdownCancelled(AutoPolicyKind)46 /// The countdown ended without any reaction: pause (or stop when `stop` is true).47 case countdownFinished(AutoPolicyKind, stop: Bool)48 }4950 public private(set) var policy: AutoPausePolicy51 public private(set) var voiceActive = false52 public private(set) var suggestionActive = false53 public private(set) var countdown: (kind: AutoPolicyKind, endsAt: Double)?54 private var lastVoice: Double = 055 private var lastLoud: Double = 056 private var lastInteraction: Double = 057 private var suspended = false58 private var dismissedSilenceUntilVoice = false59 private var maxDurationSnoozedUntil: Double = 0 // recorded seconds60 private var endTimeSnoozedUntil: Date = .distantPast61 private var inactivityArmed = true6263 /// `now` values are monotonic seconds (any origin).64 public init(policy: AutoPausePolicy, now: Double) {65 self.policy = policy; lastVoice = now; lastLoud = now; lastInteraction = now66 }6768 public mutating func updatePolicy(_ p: AutoPausePolicy) { policy = p }6970 public var countdownRemaining: Double? { nil }71 public func remaining(now: Double) -> Double? { countdown.map { max(0, $0.endsAt - now) } }7273 /// Feeds one audio level measurement (dBFS).74 public mutating func ingest(levelDB: Double, now: Double) {75 if levelDB >= policy.voiceThresholdDB { lastLoud = now; voiceActive = true }76 else if voiceActive, levelDB < policy.voiceThresholdDB - policy.hysteresisDB, now - lastLoud > policy.hangoverSeconds { voiceActive = false }77 else if voiceActive, now - lastLoud > max(policy.hangoverSeconds, 1.5) { voiceActive = false } // hovering inside the hysteresis band78 if voiceActive { lastVoice = now }79 }8081 /// Slide change, ink, pointer: the instructor is present even when silent.82 public mutating func noteInteraction(now: Double) { lastInteraction = now }8384 /// Manual pause: every automatic timer is frozen (manual control always wins).85 public mutating func userPaused() -> [Output] {86 suspended = true87 var out: [Output] = []88 if suggestionActive { suggestionActive = false; out.append(.withdrawSuggestion) }89 if let c = countdown { countdown = nil; out.append(.countdownCancelled(c.kind)) }90 return out91 }92 public mutating func userResumed(now: Double) {93 suspended = false; lastVoice = now; lastLoud = now; lastInteraction = now94 dismissedSilenceUntilVoice = false; inactivityArmed = true95 }9697 /// "Continue recording" on a warning: the countdown is cancelled and the policy that fired is snoozed.98 public mutating func userContinued(now: Double, recordedSeconds: Double, wall: Date) -> [Output] {99 var out: [Output] = []100 if suggestionActive { suggestionActive = false; dismissedSilenceUntilVoice = true; out.append(.withdrawSuggestion) }101 if let c = countdown {102 countdown = nil; out.append(.countdownCancelled(c.kind))103 switch c.kind {104 case .maxDuration: maxDurationSnoozedUntil = recordedSeconds + 15 * 60105 case .endTime: endTimeSnoozedUntil = wall.addingTimeInterval(15 * 60)106 default: lastInteraction = now107 }108 }109 return out110 }111112 /// The end phrase was recognized locally.113 public mutating func endPhraseHeard(now: Double) -> [Output] {114 guard policy.endPhraseEnabled, !suspended, countdown == nil else { return [] }115 countdown = (.endPhrase, now + min(policy.countdownSeconds, 10))116 return [.countdownStarted(.endPhrase, seconds: min(policy.countdownSeconds, 10))]117 }118119 public mutating func tick(now: Double, recordedSeconds: Double, wall: Date) -> [Output] {120 guard !suspended else { return [] }121 var out: [Output] = []122123 // Silence → suggestion only.124 if policy.silenceEnabled {125 let silentFor = now - lastVoice126 if voiceActive { dismissedSilenceUntilVoice = false }127 if suggestionActive, voiceActive { suggestionActive = false; out.append(.withdrawSuggestion) }128 else if !suggestionActive, !dismissedSilenceUntilVoice, countdown == nil, silentFor >= policy.silenceSeconds {129 suggestionActive = true; out.append(.suggestPause(.silence))130 }131 } else if suggestionActive { suggestionActive = false; out.append(.withdrawSuggestion) }132133 // Running countdown.134 if let c = countdown {135 let activity = max(lastVoice, lastInteraction)136 if c.kind == .inactivity, activity > c.endsAt - policy.countdownSeconds {137 countdown = nil; out.append(.countdownCancelled(.inactivity))138 } else if now >= c.endsAt {139 countdown = nil; inactivityArmed = false140 // The session is now paused or stopped by the caller; do not fire the same policy again right away.141 if c.kind == .maxDuration { maxDurationSnoozedUntil = recordedSeconds + 15 * 60 }142 if c.kind == .endTime { endTimeSnoozedUntil = wall.addingTimeInterval(15 * 60) }143 out.append(.countdownFinished(c.kind, stop: policy.stopWhenCountdownEnds || c.kind == .endPhrase && policy.stopWhenCountdownEnds))144 }145 return out146 }147148 if policy.maxDurationEnabled, recordedSeconds >= maxDurationSnoozedUntil,149 recordedSeconds >= policy.maxDurationSeconds - policy.countdownSeconds {150 let secs = max(1, min(policy.countdownSeconds, policy.maxDurationSeconds - recordedSeconds + policy.countdownSeconds))151 countdown = (.maxDuration, now + min(secs, policy.countdownSeconds))152 out.append(.countdownStarted(.maxDuration, seconds: min(secs, policy.countdownSeconds)))153 } else if policy.endTimeEnabled, let end = policy.endTime, wall >= endTimeSnoozedUntil,154 wall >= end.addingTimeInterval(-policy.countdownSeconds), wall < end.addingTimeInterval(6 * 3600) {155 countdown = (.endTime, now + policy.countdownSeconds)156 out.append(.countdownStarted(.endTime, seconds: policy.countdownSeconds))157 } else if policy.inactivityEnabled {158 let idle = now - max(lastVoice, lastInteraction)159 if idle < policy.inactivitySeconds { inactivityArmed = true }160 else if inactivityArmed {161 countdown = (.inactivity, now + policy.countdownSeconds)162 out.append(.countdownStarted(.inactivity, seconds: policy.countdownSeconds))163 }164 }165 return out166 }167}168