-
Notifications
You must be signed in to change notification settings - Fork 28
[Enhancement]Handle camera session interruptions #907
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
ipavlidakis
merged 3 commits into
develop
from
enhancement/restart-avcapturesession-when-coming-to-foreground
Aug 8, 2025
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
141 changes: 141 additions & 0 deletions
141
...reamVideo/WebRTC/v2/VideoCapturing/ActionHandlers/Camera/CameraInterruptionsHandler.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,141 @@ | ||
// | ||
// Copyright © 2025 Stream.io Inc. All rights reserved. | ||
// | ||
|
||
import AVFoundation | ||
import Combine | ||
import Foundation | ||
import StreamWebRTC | ||
|
||
/// Handles camera-related interruptions by observing `AVCaptureSession` interruption notifications. | ||
final class CameraInterruptionsHandler: StreamVideoCapturerActionHandler, @unchecked Sendable { | ||
|
||
/// Represents the current camera session state (idle or running). | ||
private enum State { | ||
/// No active camera session. | ||
case idle | ||
/// An active camera session with a disposable bag for cleanup. | ||
case running(session: AVCaptureSession, disposableBag: DisposableBag) | ||
} | ||
|
||
private var state: State = .idle | ||
/// Ensures serialized handling of interruption events. | ||
private let processingQueue = OperationQueue(maxConcurrentOperationCount: 1) | ||
|
||
// MARK: - StreamVideoCapturerActionHandler | ||
|
||
/// Handles camera-related actions triggered by the video capturer. | ||
func handle(_ action: StreamVideoCapturer.Action) async throws { | ||
switch action { | ||
/// Handle start capture event and register for interruption notifications. | ||
case let .startCapture(_, _, _, _, videoCapturer, _): | ||
if let cameraCapturer = videoCapturer as? RTCCameraVideoCapturer { | ||
didStartCapture(session: cameraCapturer.captureSession) | ||
} else { | ||
didStopCapture() | ||
} | ||
/// Handle stop capture event and cleanup. | ||
case .stopCapture: | ||
didStopCapture() | ||
default: | ||
break | ||
} | ||
} | ||
|
||
// MARK: - Private | ||
|
||
/// Sets up observers and state when camera capture starts. | ||
private func didStartCapture(session: AVCaptureSession) { | ||
let disposableBag = DisposableBag() | ||
|
||
let interruptedNotification: Notification.Name = { | ||
#if compiler(>=6.0) | ||
return AVCaptureSession.wasInterruptedNotification | ||
#else | ||
return .AVCaptureSessionWasInterrupted | ||
#endif | ||
}() | ||
|
||
/// Observe AVCaptureSession interruptions and log reasons. | ||
NotificationCenter | ||
.default | ||
.publisher(for: interruptedNotification) | ||
.compactMap { (notification: Notification) -> String? in | ||
guard | ||
let userInfo = notification.userInfo, | ||
let reasonRawValue = userInfo[AVCaptureSessionInterruptionReasonKey] as? NSNumber, | ||
let reason = AVCaptureSession.InterruptionReason(rawValue: reasonRawValue.intValue) | ||
else { | ||
return nil | ||
} | ||
return reason.description | ||
} | ||
.compactMap { $0 } | ||
.log(.debug, subsystems: .webRTC) { "CameraCapture session was interrupted with reason: \($0)." } | ||
.receive(on: processingQueue) | ||
.sink { _ in } | ||
.store(in: disposableBag) | ||
|
||
/// Observe end of AVCaptureSession interruptions and restart session if needed. | ||
NotificationCenter | ||
.default | ||
.publisher(for: .AVCaptureSessionInterruptionEnded) | ||
.log(.debug, subsystems: .webRTC) { _ in "CameraCapture session interruption ended." } | ||
.receive(on: processingQueue) | ||
.sink { [weak self] _ in self?.handleInterruptionEnded() } | ||
.store(in: disposableBag) | ||
|
||
state = .running(session: session, disposableBag: disposableBag) | ||
} | ||
|
||
/// Cleans up resources and resets state when camera capture stops. | ||
private func didStopCapture() { | ||
switch state { | ||
case .idle: | ||
break | ||
case let .running(_, disposableBag): | ||
disposableBag.removeAll() | ||
processingQueue.cancelAllOperations() | ||
} | ||
state = .idle | ||
} | ||
|
||
/// Restarts the session if it was interrupted and not running. | ||
private func handleInterruptionEnded() { | ||
switch state { | ||
case .idle: | ||
break | ||
case let .running(session, _): | ||
guard !session.isRunning else { | ||
return | ||
} | ||
session.startRunning() | ||
} | ||
} | ||
} | ||
|
||
#if compiler(>=6.0) | ||
extension AVCaptureSession.InterruptionReason: @retroactive CustomStringConvertible {} | ||
#else | ||
extension AVCaptureSession.InterruptionReason: CustomStringConvertible {} | ||
#endif | ||
|
||
extension AVCaptureSession.InterruptionReason { | ||
/// Provides a readable description for each interruption reason. | ||
public var description: String { | ||
switch self { | ||
case .videoDeviceNotAvailableInBackground: | ||
return ".videoDeviceNotAvailableInBackground" | ||
case .audioDeviceInUseByAnotherClient: | ||
return ".audioDeviceInUseByAnotherClient" | ||
case .videoDeviceInUseByAnotherClient: | ||
return ".videoDeviceInUseByAnotherClient" | ||
case .videoDeviceNotAvailableWithMultipleForegroundApps: | ||
return ".videoDeviceNotAvailableWithMultipleForegroundApps" | ||
case .videoDeviceNotAvailableDueToSystemPressure: | ||
return ".videoDeviceNotAvailableDueToSystemPressure" | ||
@unknown default: | ||
return "\(self)" | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.