@stream-io/video-react-native-sdk 1.29.4 → 1.30.1-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/commonjs/components/Call/CallContent/CallContent.js +13 -7
  3. package/dist/commonjs/components/Call/CallContent/CallContent.js.map +1 -1
  4. package/dist/commonjs/components/Call/CallContent/RTCViewPipIOS.js +50 -14
  5. package/dist/commonjs/components/Call/CallContent/RTCViewPipIOS.js.map +1 -1
  6. package/dist/commonjs/components/Call/CallContent/RTCViewPipNative.js +27 -0
  7. package/dist/commonjs/components/Call/CallContent/RTCViewPipNative.js.map +1 -1
  8. package/dist/commonjs/components/Call/CallLayout/CallParticipantsGrid.js +19 -10
  9. package/dist/commonjs/components/Call/CallLayout/CallParticipantsGrid.js.map +1 -1
  10. package/dist/commonjs/components/Call/CallLayout/CallParticipantsSpotlight.js +12 -9
  11. package/dist/commonjs/components/Call/CallLayout/CallParticipantsSpotlight.js.map +1 -1
  12. package/dist/commonjs/components/Call/CallParticipantsList/CallParticipantsList.js +19 -4
  13. package/dist/commonjs/components/Call/CallParticipantsList/CallParticipantsList.js.map +1 -1
  14. package/dist/commonjs/contexts/ThemeContext.js +14 -3
  15. package/dist/commonjs/contexts/ThemeContext.js.map +1 -1
  16. package/dist/commonjs/utils/hooks/index.js +0 -11
  17. package/dist/commonjs/utils/hooks/index.js.map +1 -1
  18. package/dist/commonjs/version.js +1 -1
  19. package/dist/commonjs/version.js.map +1 -1
  20. package/dist/module/components/Call/CallContent/CallContent.js +10 -4
  21. package/dist/module/components/Call/CallContent/CallContent.js.map +1 -1
  22. package/dist/module/components/Call/CallContent/RTCViewPipIOS.js +52 -16
  23. package/dist/module/components/Call/CallContent/RTCViewPipIOS.js.map +1 -1
  24. package/dist/module/components/Call/CallContent/RTCViewPipNative.js +27 -0
  25. package/dist/module/components/Call/CallContent/RTCViewPipNative.js.map +1 -1
  26. package/dist/module/components/Call/CallLayout/CallParticipantsGrid.js +19 -10
  27. package/dist/module/components/Call/CallLayout/CallParticipantsGrid.js.map +1 -1
  28. package/dist/module/components/Call/CallLayout/CallParticipantsSpotlight.js +15 -12
  29. package/dist/module/components/Call/CallLayout/CallParticipantsSpotlight.js.map +1 -1
  30. package/dist/module/components/Call/CallParticipantsList/CallParticipantsList.js +20 -5
  31. package/dist/module/components/Call/CallParticipantsList/CallParticipantsList.js.map +1 -1
  32. package/dist/module/contexts/ThemeContext.js +13 -1
  33. package/dist/module/contexts/ThemeContext.js.map +1 -1
  34. package/dist/module/utils/hooks/index.js +0 -1
  35. package/dist/module/utils/hooks/index.js.map +1 -1
  36. package/dist/module/version.js +1 -1
  37. package/dist/module/version.js.map +1 -1
  38. package/dist/typescript/components/Call/CallContent/CallContent.d.ts.map +1 -1
  39. package/dist/typescript/components/Call/CallContent/RTCViewPipIOS.d.ts.map +1 -1
  40. package/dist/typescript/components/Call/CallContent/RTCViewPipNative.d.ts +18 -0
  41. package/dist/typescript/components/Call/CallContent/RTCViewPipNative.d.ts.map +1 -1
  42. package/dist/typescript/components/Call/CallLayout/CallParticipantsGrid.d.ts.map +1 -1
  43. package/dist/typescript/components/Call/CallLayout/CallParticipantsSpotlight.d.ts.map +1 -1
  44. package/dist/typescript/components/Call/CallParticipantsList/CallParticipantsList.d.ts.map +1 -1
  45. package/dist/typescript/contexts/ThemeContext.d.ts.map +1 -1
  46. package/dist/typescript/utils/hooks/index.d.ts +0 -1
  47. package/dist/typescript/utils/hooks/index.d.ts.map +1 -1
  48. package/dist/typescript/version.d.ts +1 -1
  49. package/dist/typescript/version.d.ts.map +1 -1
  50. package/ios/PictureInPicture/PictureInPictureAvatarView.swift +273 -0
  51. package/ios/PictureInPicture/PictureInPictureConnectionQualityIndicator.swift +162 -0
  52. package/ios/PictureInPicture/PictureInPictureContent.swift +173 -0
  53. package/ios/PictureInPicture/PictureInPictureContentState.swift +123 -0
  54. package/ios/PictureInPicture/PictureInPictureDelegateProxy.swift +89 -0
  55. package/ios/PictureInPicture/PictureInPictureEnforcedStopAdapter.swift +166 -0
  56. package/ios/PictureInPicture/PictureInPictureLogger.swift +16 -0
  57. package/ios/PictureInPicture/PictureInPictureParticipantOverlayView.swift +217 -0
  58. package/ios/PictureInPicture/PictureInPictureReconnectionView.swift +193 -0
  59. package/ios/PictureInPicture/StreamAVPictureInPictureVideoCallViewController.swift +125 -7
  60. package/ios/PictureInPicture/StreamPictureInPictureController.swift +237 -63
  61. package/ios/PictureInPicture/StreamPictureInPictureControllerProtocol.swift +30 -0
  62. package/ios/PictureInPicture/StreamPictureInPictureVideoRenderer.swift +384 -12
  63. package/ios/RTCViewPip.swift +187 -21
  64. package/ios/RTCViewPipManager.mm +9 -0
  65. package/ios/RTCViewPipManager.swift +3 -3
  66. package/ios/StreamVideoReactNative.xcodeproj/project.xcworkspace/xcuserdata/santhoshvaiyapuri.xcuserdatad/UserInterfaceState.xcuserstate +0 -0
  67. package/ios/StreamVideoReactNative.xcodeproj/xcuserdata/santhoshvaiyapuri.xcuserdatad/xcschemes/xcschememanagement.plist +14 -0
  68. package/package.json +5 -7
  69. package/src/components/Call/CallContent/CallContent.tsx +16 -8
  70. package/src/components/Call/CallContent/RTCViewPipIOS.tsx +81 -15
  71. package/src/components/Call/CallContent/RTCViewPipNative.tsx +36 -0
  72. package/src/components/Call/CallLayout/CallParticipantsGrid.tsx +28 -14
  73. package/src/components/Call/CallLayout/CallParticipantsSpotlight.tsx +19 -10
  74. package/src/components/Call/CallParticipantsList/CallParticipantsList.tsx +20 -5
  75. package/src/contexts/ThemeContext.tsx +20 -2
  76. package/src/utils/hooks/index.ts +0 -1
  77. package/src/version.ts +1 -1
  78. package/dist/commonjs/utils/hooks/useDebouncedValue.js +0 -24
  79. package/dist/commonjs/utils/hooks/useDebouncedValue.js.map +0 -1
  80. package/dist/module/utils/hooks/useDebouncedValue.js +0 -19
  81. package/dist/module/utils/hooks/useDebouncedValue.js.map +0 -1
  82. package/dist/typescript/utils/hooks/useDebouncedValue.d.ts +0 -8
  83. package/dist/typescript/utils/hooks/useDebouncedValue.d.ts.map +0 -1
  84. package/src/utils/hooks/useDebouncedValue.ts +0 -21
@@ -0,0 +1,173 @@
1
+ //
2
+ // Copyright © 2024 Stream.io Inc. All rights reserved.
3
+ //
4
+ // Adapted from stream-video-swift for React Native SDK
5
+ // Original: https://github.com/GetStream/stream-video-swift/blob/develop/Sources/StreamVideoSwiftUI/Utils/PictureInPicture/PictureInPictureContent.swift
6
+ //
7
+
8
+ import Foundation
9
+
10
+ /// Represents the content state for the Picture-in-Picture window.
11
+ ///
12
+ /// This enum defines the different states that the PiP window can display:
13
+ /// - `inactive`: No content is being shown (PiP is not active)
14
+ /// - `video`: Live video from a participant (camera or screen share)
15
+ /// - `avatar`: Participant avatar placeholder (when video is disabled)
16
+ /// - `screenSharing`: Screen share content with indicator overlay
17
+ /// - `reconnecting`: Connection recovery indicator
18
+ ///
19
+ /// The React Native SDK receives content state from the JavaScript layer through
20
+ /// the bridge, unlike the upstream Swift SDK which observes call state internally.
21
+ enum PictureInPictureContent: Equatable, CustomStringConvertible {
22
+ /// No content - PiP is inactive or transitioning
23
+ case inactive
24
+
25
+ /// Video content from a participant
26
+ /// - Parameters:
27
+ /// - track: The WebRTC video track to render
28
+ /// - participantName: The participant's display name (for fallback)
29
+ /// - participantImageURL: URL to participant's profile image (for fallback)
30
+ case video(track: RTCVideoTrack?, participantName: String?, participantImageURL: String?)
31
+
32
+ /// Screen sharing content
33
+ /// - Parameters:
34
+ /// - track: The WebRTC video track containing screen share
35
+ /// - participantName: Name of the participant sharing their screen
36
+ case screenSharing(track: RTCVideoTrack?, participantName: String?)
37
+
38
+ /// Avatar placeholder shown when video is disabled
39
+ /// - Parameters:
40
+ /// - participantName: The participant's display name (for initials)
41
+ /// - participantImageURL: URL to participant's profile image
42
+ case avatar(participantName: String?, participantImageURL: String?)
43
+
44
+ /// Connection recovery indicator
45
+ case reconnecting
46
+
47
+ // MARK: - CustomStringConvertible
48
+
49
+ var description: String {
50
+ switch self {
51
+ case .inactive:
52
+ return ".inactive"
53
+ case let .video(track, name, _):
54
+ return ".video(track:\(track?.trackId ?? "nil"), name:\(name ?? "-"))"
55
+ case let .screenSharing(track, name):
56
+ return ".screenSharing(track:\(track?.trackId ?? "nil"), name:\(name ?? "-"))"
57
+ case let .avatar(name, _):
58
+ return ".avatar(name:\(name ?? "-"))"
59
+ case .reconnecting:
60
+ return ".reconnecting"
61
+ }
62
+ }
63
+
64
+ // MARK: - Equatable
65
+
66
+ static func == (lhs: PictureInPictureContent, rhs: PictureInPictureContent) -> Bool {
67
+ switch (lhs, rhs) {
68
+ case (.inactive, .inactive):
69
+ return true
70
+ case let (.video(lhsTrack, lhsName, lhsImage), .video(rhsTrack, rhsName, rhsImage)):
71
+ return isSameTrackInstance(lhsTrack, rhsTrack)
72
+ && lhsName == rhsName
73
+ && lhsImage == rhsImage
74
+ case let (.screenSharing(lhsTrack, lhsName), .screenSharing(rhsTrack, rhsName)):
75
+ return isSameTrackInstance(lhsTrack, rhsTrack)
76
+ && lhsName == rhsName
77
+ case let (.avatar(lhsName, lhsImage), .avatar(rhsName, rhsImage)):
78
+ return lhsName == rhsName
79
+ && lhsImage == rhsImage
80
+ case (.reconnecting, .reconnecting):
81
+ return true
82
+ default:
83
+ return false
84
+ }
85
+ }
86
+
87
+ /// Track identity must be reference-based so reconnect-created tracks
88
+ /// with reused `trackId` still propagate through content updates.
89
+ private static func isSameTrackInstance(_ lhs: RTCVideoTrack?, _ rhs: RTCVideoTrack?) -> Bool {
90
+ switch (lhs, rhs) {
91
+ case (nil, nil):
92
+ return true
93
+ case let (lhsTrack?, rhsTrack?):
94
+ return lhsTrack === rhsTrack
95
+ default:
96
+ return false
97
+ }
98
+ }
99
+
100
+ // MARK: - Convenience Properties
101
+
102
+ /// Returns the video track if this content has one, nil otherwise
103
+ var track: RTCVideoTrack? {
104
+ switch self {
105
+ case let .video(track, _, _):
106
+ return track
107
+ case let .screenSharing(track, _):
108
+ return track
109
+ case .inactive, .avatar, .reconnecting:
110
+ return nil
111
+ }
112
+ }
113
+
114
+ /// Returns the participant name if available
115
+ var participantName: String? {
116
+ switch self {
117
+ case let .video(_, name, _):
118
+ return name
119
+ case let .screenSharing(_, name):
120
+ return name
121
+ case let .avatar(name, _):
122
+ return name
123
+ case .inactive, .reconnecting:
124
+ return nil
125
+ }
126
+ }
127
+
128
+ /// Returns the participant image URL if available
129
+ var participantImageURL: String? {
130
+ switch self {
131
+ case let .video(_, _, imageURL):
132
+ return imageURL
133
+ case let .avatar(_, imageURL):
134
+ return imageURL
135
+ case .inactive, .screenSharing, .reconnecting:
136
+ return nil
137
+ }
138
+ }
139
+
140
+ /// Whether this content represents an active video stream
141
+ var hasActiveVideo: Bool {
142
+ switch self {
143
+ case .video, .screenSharing:
144
+ return true
145
+ case .inactive, .avatar, .reconnecting:
146
+ return false
147
+ }
148
+ }
149
+
150
+ /// Whether this content is screen sharing
151
+ var isScreenSharing: Bool {
152
+ if case .screenSharing = self {
153
+ return true
154
+ }
155
+ return false
156
+ }
157
+
158
+ /// Whether this content shows an avatar
159
+ var isShowingAvatar: Bool {
160
+ if case .avatar = self {
161
+ return true
162
+ }
163
+ return false
164
+ }
165
+
166
+ /// Whether this content shows the reconnection view
167
+ var isReconnecting: Bool {
168
+ if case .reconnecting = self {
169
+ return true
170
+ }
171
+ return false
172
+ }
173
+ }
@@ -0,0 +1,123 @@
1
+ //
2
+ // Copyright © 2024 Stream.io Inc. All rights reserved.
3
+ //
4
+ // Adapted from stream-video-swift PictureInPictureStore for React Native SDK
5
+ // The React Native SDK receives state from the JavaScript bridge rather than
6
+ // observing call state internally, so this is a simplified state container.
7
+ //
8
+
9
+ import Combine
10
+ import Foundation
11
+
12
+ /// Manages the content state for the Picture-in-Picture window.
13
+ ///
14
+ /// This class provides centralized state management for the PiP content view system.
15
+ /// Unlike the upstream `PictureInPictureStore` which uses a Flux-like action/dispatch pattern,
16
+ /// this implementation is optimized for the React Native bridge where state updates come
17
+ /// from the JavaScript layer.
18
+ ///
19
+ /// State changes are published via Combine to allow reactive updates in the view layer.
20
+ ///
21
+ /// Concurrency model:
22
+ /// - This state container is main-thread confined.
23
+ /// - `RTCVideoTrack` references are never sent across queues.
24
+ final class PictureInPictureContentState {
25
+
26
+ /// A full state snapshot that can be applied atomically.
27
+ struct Snapshot {
28
+ var track: RTCVideoTrack?
29
+ var participantName: String?
30
+ var participantImageURL: String?
31
+ var isVideoEnabled: Bool
32
+ var isScreenSharing: Bool
33
+ var isReconnecting: Bool
34
+ }
35
+
36
+ // MARK: - Published State
37
+
38
+ /// The current content being displayed in the PiP window.
39
+ @Published private(set) var content: PictureInPictureContent = .inactive
40
+
41
+ /// Publisher for observing content changes.
42
+ var contentPublisher: AnyPublisher<PictureInPictureContent, Never> {
43
+ $content.eraseToAnyPublisher()
44
+ }
45
+
46
+ // MARK: - Private
47
+
48
+ private var snapshot: Snapshot = makeDefaultSnapshot()
49
+
50
+ // MARK: - Initialization
51
+
52
+ init() {}
53
+
54
+ // MARK: - State Update
55
+
56
+ /// Applies all content inputs in one step to avoid parallel update paths.
57
+ func apply(_ snapshot: Snapshot) {
58
+ ensureMainThread()
59
+ self.snapshot = snapshot
60
+ publishIfNeeded(for: snapshot)
61
+ }
62
+
63
+ /// Resets all state to defaults.
64
+ /// Called when cleaning up after a call ends.
65
+ func reset() {
66
+ ensureMainThread()
67
+ snapshot = Self.makeDefaultSnapshot()
68
+ if content != .inactive {
69
+ content = .inactive
70
+ }
71
+ }
72
+
73
+ /// Computes and publishes content based on the latest snapshot.
74
+ private func publishIfNeeded(for snapshot: Snapshot) {
75
+ let newContent: PictureInPictureContent
76
+
77
+ // Priority order: reconnecting > screen sharing > avatar (video disabled) > video > avatar fallback
78
+ if snapshot.isReconnecting {
79
+ newContent = .reconnecting
80
+ } else if snapshot.isScreenSharing {
81
+ newContent = .screenSharing(
82
+ track: snapshot.track,
83
+ participantName: snapshot.participantName
84
+ )
85
+ } else if !snapshot.isVideoEnabled {
86
+ newContent = .avatar(
87
+ participantName: snapshot.participantName,
88
+ participantImageURL: snapshot.participantImageURL
89
+ )
90
+ } else if snapshot.isVideoEnabled, snapshot.track != nil {
91
+ newContent = .video(
92
+ track: snapshot.track,
93
+ participantName: snapshot.participantName,
94
+ participantImageURL: snapshot.participantImageURL
95
+ )
96
+ } else {
97
+ newContent = .avatar(
98
+ participantName: snapshot.participantName,
99
+ participantImageURL: snapshot.participantImageURL
100
+ )
101
+ }
102
+
103
+ if content != newContent {
104
+ content = newContent
105
+ }
106
+ }
107
+
108
+ /// PiP content state is expected to be mutated on the main thread only.
109
+ private func ensureMainThread() {
110
+ dispatchPrecondition(condition: .onQueue(.main))
111
+ }
112
+
113
+ private static func makeDefaultSnapshot() -> Snapshot {
114
+ Snapshot(
115
+ track: nil,
116
+ participantName: nil,
117
+ participantImageURL: nil,
118
+ isVideoEnabled: true,
119
+ isScreenSharing: false,
120
+ isReconnecting: false
121
+ )
122
+ }
123
+ }
@@ -0,0 +1,89 @@
1
+ //
2
+ // Copyright © 2024 Stream.io Inc. All rights reserved.
3
+ //
4
+
5
+ import AVKit
6
+ import Combine
7
+
8
+ /// A wrapper around AVPictureInPictureControllerDelegate that publishes all
9
+ /// delegate method calls via a single Combine publisher.
10
+ ///
11
+ /// This proxy enables reactive handling of PiP lifecycle events and allows
12
+ /// multiple subscribers to observe PiP state changes through a unified interface.
13
+ final class PictureInPictureDelegateProxy: NSObject, AVPictureInPictureControllerDelegate {
14
+
15
+ /// Enum representing each AVPictureInPictureControllerDelegate method call
16
+ /// with its respective associated values.
17
+ enum Event: CustomStringConvertible {
18
+ case willStart(AVPictureInPictureController)
19
+ case didStart(AVPictureInPictureController)
20
+ case failedToStart(AVPictureInPictureController, Error)
21
+ case willStop(AVPictureInPictureController)
22
+ case didStop(AVPictureInPictureController)
23
+ case restoreUI(AVPictureInPictureController, (Bool) -> Void)
24
+
25
+ var description: String {
26
+ switch self {
27
+ case .willStart:
28
+ return ".willStart"
29
+ case .didStart:
30
+ return ".didStart"
31
+ case let .failedToStart(_, error):
32
+ return ".failedToStart(error: \(error.localizedDescription))"
33
+ case .willStop:
34
+ return ".willStop"
35
+ case .didStop:
36
+ return ".didStop"
37
+ case .restoreUI:
38
+ return ".restoreUI"
39
+ }
40
+ }
41
+ }
42
+
43
+ /// The Combine publisher that emits Picture-in-Picture delegate events.
44
+ var publisher: AnyPublisher<Event, Never> {
45
+ eventSubject.eraseToAnyPublisher()
46
+ }
47
+
48
+ private let eventSubject = PassthroughSubject<Event, Never>()
49
+
50
+ // MARK: - AVPictureInPictureControllerDelegate
51
+
52
+ func pictureInPictureControllerWillStartPictureInPicture(
53
+ _ pictureInPictureController: AVPictureInPictureController
54
+ ) {
55
+ eventSubject.send(.willStart(pictureInPictureController))
56
+ }
57
+
58
+ func pictureInPictureControllerDidStartPictureInPicture(
59
+ _ pictureInPictureController: AVPictureInPictureController
60
+ ) {
61
+ eventSubject.send(.didStart(pictureInPictureController))
62
+ }
63
+
64
+ func pictureInPictureController(
65
+ _ pictureInPictureController: AVPictureInPictureController,
66
+ failedToStartPictureInPictureWithError error: Error
67
+ ) {
68
+ eventSubject.send(.failedToStart(pictureInPictureController, error))
69
+ }
70
+
71
+ func pictureInPictureControllerWillStopPictureInPicture(
72
+ _ pictureInPictureController: AVPictureInPictureController
73
+ ) {
74
+ eventSubject.send(.willStop(pictureInPictureController))
75
+ }
76
+
77
+ func pictureInPictureControllerDidStopPictureInPicture(
78
+ _ pictureInPictureController: AVPictureInPictureController
79
+ ) {
80
+ eventSubject.send(.didStop(pictureInPictureController))
81
+ }
82
+
83
+ func pictureInPictureController(
84
+ _ pictureInPictureController: AVPictureInPictureController,
85
+ restoreUserInterfaceForPictureInPictureStopWithCompletionHandler completionHandler: @escaping (Bool) -> Void
86
+ ) {
87
+ eventSubject.send(.restoreUI(pictureInPictureController, completionHandler))
88
+ }
89
+ }
@@ -0,0 +1,166 @@
1
+ //
2
+ // Copyright © 2024 Stream.io Inc. All rights reserved.
3
+ //
4
+
5
+ import AVKit
6
+ import Combine
7
+ import UIKit
8
+
9
+ /// An adapter responsible for enforcing the stop of Picture-in-Picture
10
+ /// playback when the application returns to the foreground.
11
+ ///
12
+ /// This adapter listens to application state changes and PiP activity to ensure
13
+ /// PiP is stopped when the app becomes active (foreground). This behavior matches
14
+ /// iOS user expectations where PiP should dismiss when returning to the app.
15
+ final class PictureInPictureEnforcedStopAdapter {
16
+
17
+ private enum DisposableKey: String {
18
+ case stopEnforceOperation
19
+ }
20
+
21
+ private enum ApplicationState: Equatable {
22
+ case foreground
23
+ case background
24
+ case unknown
25
+ }
26
+
27
+ /// Refresh-rate-based timer interval used for enforcement attempts.
28
+ private let refreshRate: TimeInterval
29
+
30
+ /// Lifecycle subscriptions.
31
+ private var cancellables: Set<AnyCancellable> = []
32
+
33
+ /// Keyed operations that can be replaced/cancelled independently.
34
+ private var operationCancellables: [String: AnyCancellable] = [:]
35
+
36
+ /// Initializes the adapter with a Picture-in-Picture controller and
37
+ /// starts observing application state and PiP activity to enforce stop.
38
+ ///
39
+ /// - Parameter pictureInPictureController: The PiP controller to manage.
40
+ init(_ pictureInPictureController: StreamPictureInPictureControllerProtocol) {
41
+ refreshRate = Self.makeRefreshRate()
42
+
43
+ // Keep enforcement strictly state-driven: we only run the stop loop
44
+ // while the app is foregrounded *and* PiP is still active.
45
+ Publishers
46
+ .CombineLatest(
47
+ Self.makeApplicationStatePublisher(),
48
+ pictureInPictureController
49
+ .isPictureInPictureActivePublisher
50
+ .removeDuplicates()
51
+ )
52
+ .receive(on: DispatchQueue.main)
53
+ .sink { [weak self, weak pictureInPictureController] applicationState, isActive in
54
+ self?.didUpdate(
55
+ applicationState: applicationState,
56
+ isPictureInPictureActive: isActive,
57
+ pictureInPictureController: pictureInPictureController
58
+ )
59
+ }
60
+ .store(in: &cancellables)
61
+ }
62
+
63
+ deinit {
64
+ cancellables.removeAll()
65
+ removeAllOperations()
66
+ }
67
+
68
+ // MARK: - Private helpers
69
+
70
+ private func didUpdate(
71
+ applicationState: ApplicationState,
72
+ isPictureInPictureActive: Bool,
73
+ pictureInPictureController: StreamPictureInPictureControllerProtocol?
74
+ ) {
75
+ switch (applicationState, isPictureInPictureActive) {
76
+ case (.foreground, true):
77
+ // Foreground + active PiP is the only state where we enforce stop.
78
+ startStopEnforcement(for: pictureInPictureController)
79
+ default:
80
+ // Any other state (background/inactive PiP) should tear down the loop.
81
+ removeOperation(for: DisposableKey.stopEnforceOperation.rawValue)
82
+ }
83
+ }
84
+
85
+ private func startStopEnforcement(
86
+ for pictureInPictureController: StreamPictureInPictureControllerProtocol?
87
+ ) {
88
+ guard let pictureInPictureController else {
89
+ removeOperation(for: DisposableKey.stopEnforceOperation.rawValue)
90
+ return
91
+ }
92
+
93
+ let operation = Timer
94
+ .publish(every: refreshRate, on: .main, in: .common)
95
+ .autoconnect()
96
+ .filter { _ in
97
+ UIApplication.shared.applicationState == .active
98
+ }
99
+ .sink { [weak pictureInPictureController] _ in
100
+ // Calling stop repeatedly at display cadence covers cases where
101
+ // AVKit does not settle PiP shutdown on the first attempt.
102
+ pictureInPictureController?.stopPictureInPicture()
103
+ }
104
+
105
+ store(operation, key: DisposableKey.stopEnforceOperation.rawValue)
106
+ }
107
+
108
+ private func store(_ operation: AnyCancellable, key: String) {
109
+ // Keyed replacement ensures exactly one enforcement loop is active.
110
+ removeOperation(for: key)
111
+ operationCancellables[key] = operation
112
+ }
113
+
114
+ private func removeOperation(for key: String) {
115
+ operationCancellables[key]?.cancel()
116
+ operationCancellables[key] = nil
117
+ }
118
+
119
+ private func removeAllOperations() {
120
+ operationCancellables.values.forEach { $0.cancel() }
121
+ operationCancellables.removeAll()
122
+ }
123
+
124
+ private static func makeApplicationStatePublisher(
125
+ notificationCenter: NotificationCenter = .default
126
+ ) -> AnyPublisher<ApplicationState, Never> {
127
+ let foreground = Publishers.Merge(
128
+ notificationCenter
129
+ .publisher(for: UIApplication.willEnterForegroundNotification)
130
+ .map { _ in ApplicationState.foreground },
131
+ notificationCenter
132
+ .publisher(for: UIApplication.didBecomeActiveNotification)
133
+ .map { _ in ApplicationState.foreground }
134
+ )
135
+ let background = notificationCenter
136
+ .publisher(for: UIApplication.didEnterBackgroundNotification)
137
+ .map { _ in ApplicationState.background }
138
+
139
+ return Publishers.Merge(foreground, background)
140
+ // Emit the current app state immediately so newly created adapters
141
+ // do not wait for the next lifecycle notification.
142
+ .prepend(currentApplicationState())
143
+ .removeDuplicates()
144
+ .eraseToAnyPublisher()
145
+ }
146
+
147
+ private static func currentApplicationState() -> ApplicationState {
148
+ switch UIApplication.shared.applicationState {
149
+ case .active:
150
+ return .foreground
151
+ case .background:
152
+ return .background
153
+ case .inactive:
154
+ return .unknown
155
+ @unknown default:
156
+ return .unknown
157
+ }
158
+ }
159
+
160
+ private static func makeRefreshRate() -> TimeInterval {
161
+ // Keep cadence aligned to the device's display refresh rate while
162
+ // enforcing a practical minimum (30fps) for older/limited devices.
163
+ let maximumFramesPerSecond = max(30, UIScreen.main.maximumFramesPerSecond)
164
+ return 1.0 / Double(maximumFramesPerSecond)
165
+ }
166
+ }
@@ -0,0 +1,16 @@
1
+ //
2
+ // Copyright © 2024 Stream.io Inc. All rights reserved.
3
+ //
4
+
5
+ import Foundation
6
+
7
+ /// Centralized logger for Picture in Picture diagnostics.
8
+ ///
9
+ /// Logging is debug-only to avoid production noise and overhead.
10
+ enum PictureInPictureLogger {
11
+ static func log(_ message: @autoclosure () -> String) {
12
+ #if DEBUG
13
+ NSLog("PiP - %@", message())
14
+ #endif
15
+ }
16
+ }