|
| 1 | +// |
| 2 | +// Copyright © 2025 Stream.io Inc. All rights reserved. |
| 3 | +// |
| 4 | + |
| 5 | +import AVFoundation |
| 6 | +import Combine |
| 7 | +import Foundation |
| 8 | +import StreamWebRTC |
| 9 | + |
| 10 | +/// Handles camera-related interruptions by observing `AVCaptureSession` interruption notifications. |
| 11 | +final class CameraInterruptionsHandler: StreamVideoCapturerActionHandler, @unchecked Sendable { |
| 12 | + |
| 13 | + /// Represents the current camera session state (idle or running). |
| 14 | + private enum State { |
| 15 | + /// No active camera session. |
| 16 | + case idle |
| 17 | + /// An active camera session with a disposable bag for cleanup. |
| 18 | + case running(session: AVCaptureSession, disposableBag: DisposableBag) |
| 19 | + } |
| 20 | + |
| 21 | + private var state: State = .idle |
| 22 | + /// Ensures serialized handling of interruption events. |
| 23 | + private let processingQueue = OperationQueue(maxConcurrentOperationCount: 1) |
| 24 | + |
| 25 | + // MARK: - StreamVideoCapturerActionHandler |
| 26 | + |
| 27 | + /// Handles camera-related actions triggered by the video capturer. |
| 28 | + func handle(_ action: StreamVideoCapturer.Action) async throws { |
| 29 | + switch action { |
| 30 | + /// Handle start capture event and register for interruption notifications. |
| 31 | + case let .startCapture(_, _, _, _, videoCapturer, _): |
| 32 | + if let cameraCapturer = videoCapturer as? RTCCameraVideoCapturer { |
| 33 | + didStartCapture(session: cameraCapturer.captureSession) |
| 34 | + } else { |
| 35 | + didStopCapture() |
| 36 | + } |
| 37 | + /// Handle stop capture event and cleanup. |
| 38 | + case .stopCapture: |
| 39 | + didStopCapture() |
| 40 | + default: |
| 41 | + break |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + // MARK: - Private |
| 46 | + |
| 47 | + /// Sets up observers and state when camera capture starts. |
| 48 | + private func didStartCapture(session: AVCaptureSession) { |
| 49 | + let disposableBag = DisposableBag() |
| 50 | + |
| 51 | + let interruptedNotification: Notification.Name = { |
| 52 | + #if compiler(>=6.0) |
| 53 | + return AVCaptureSession.wasInterruptedNotification |
| 54 | + #else |
| 55 | + return .AVCaptureSessionWasInterrupted |
| 56 | + #endif |
| 57 | + }() |
| 58 | + |
| 59 | + /// Observe AVCaptureSession interruptions and log reasons. |
| 60 | + NotificationCenter |
| 61 | + .default |
| 62 | + .publisher(for: interruptedNotification) |
| 63 | + .compactMap { (notification: Notification) -> String? in |
| 64 | + guard |
| 65 | + let userInfo = notification.userInfo, |
| 66 | + let reasonRawValue = userInfo[AVCaptureSessionInterruptionReasonKey] as? NSNumber, |
| 67 | + let reason = AVCaptureSession.InterruptionReason(rawValue: reasonRawValue.intValue) |
| 68 | + else { |
| 69 | + return nil |
| 70 | + } |
| 71 | + return reason.description |
| 72 | + } |
| 73 | + .compactMap { $0 } |
| 74 | + .log(.debug, subsystems: .webRTC) { "CameraCapture session was interrupted with reason: \($0)." } |
| 75 | + .receive(on: processingQueue) |
| 76 | + .sink { _ in } |
| 77 | + .store(in: disposableBag) |
| 78 | + |
| 79 | + /// Observe end of AVCaptureSession interruptions and restart session if needed. |
| 80 | + NotificationCenter |
| 81 | + .default |
| 82 | + .publisher(for: .AVCaptureSessionInterruptionEnded) |
| 83 | + .log(.debug, subsystems: .webRTC) { _ in "CameraCapture session interruption ended." } |
| 84 | + .receive(on: processingQueue) |
| 85 | + .sink { [weak self] _ in self?.handleInterruptionEnded() } |
| 86 | + .store(in: disposableBag) |
| 87 | + |
| 88 | + state = .running(session: session, disposableBag: disposableBag) |
| 89 | + } |
| 90 | + |
| 91 | + /// Cleans up resources and resets state when camera capture stops. |
| 92 | + private func didStopCapture() { |
| 93 | + switch state { |
| 94 | + case .idle: |
| 95 | + break |
| 96 | + case let .running(_, disposableBag): |
| 97 | + disposableBag.removeAll() |
| 98 | + processingQueue.cancelAllOperations() |
| 99 | + } |
| 100 | + state = .idle |
| 101 | + } |
| 102 | + |
| 103 | + /// Restarts the session if it was interrupted and not running. |
| 104 | + private func handleInterruptionEnded() { |
| 105 | + switch state { |
| 106 | + case .idle: |
| 107 | + break |
| 108 | + case let .running(session, _): |
| 109 | + guard !session.isRunning else { |
| 110 | + return |
| 111 | + } |
| 112 | + session.startRunning() |
| 113 | + } |
| 114 | + } |
| 115 | +} |
| 116 | + |
| 117 | +#if compiler(>=6.0) |
| 118 | +extension AVCaptureSession.InterruptionReason: @retroactive CustomStringConvertible {} |
| 119 | +#else |
| 120 | +extension AVCaptureSession.InterruptionReason: CustomStringConvertible {} |
| 121 | +#endif |
| 122 | + |
| 123 | +extension AVCaptureSession.InterruptionReason { |
| 124 | + /// Provides a readable description for each interruption reason. |
| 125 | + public var description: String { |
| 126 | + switch self { |
| 127 | + case .videoDeviceNotAvailableInBackground: |
| 128 | + return ".videoDeviceNotAvailableInBackground" |
| 129 | + case .audioDeviceInUseByAnotherClient: |
| 130 | + return ".audioDeviceInUseByAnotherClient" |
| 131 | + case .videoDeviceInUseByAnotherClient: |
| 132 | + return ".videoDeviceInUseByAnotherClient" |
| 133 | + case .videoDeviceNotAvailableWithMultipleForegroundApps: |
| 134 | + return ".videoDeviceNotAvailableWithMultipleForegroundApps" |
| 135 | + case .videoDeviceNotAvailableDueToSystemPressure: |
| 136 | + return ".videoDeviceNotAvailableDueToSystemPressure" |
| 137 | + @unknown default: |
| 138 | + return "\(self)" |
| 139 | + } |
| 140 | + } |
| 141 | +} |
0 commit comments