| 1 | /* |
| 2 | * Copyright 2025 LiveKit, Inc. |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #include "livekit/sck_window_capturer.h" |
| 18 | |
| 19 | #if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS) |
| 20 | |
| 21 | #import <CoreGraphics/CoreGraphics.h> |
| 22 | #import <CoreMedia/CoreMedia.h> |
| 23 | #import <CoreVideo/CoreVideo.h> |
| 24 | #import <Foundation/Foundation.h> |
| 25 | #import <IOSurface/IOSurface.h> |
| 26 | #import <ScreenCaptureKit/ScreenCaptureKit.h> |
| 27 | #import <dispatch/dispatch.h> |
| 28 | |
| 29 | #include <climits> |
| 30 | #include <cmath> |
| 31 | #include <cstddef> |
| 32 | #include <cstdint> |
| 33 | #include <cstdlib> |
| 34 | #include <memory> |
| 35 | #include <utility> |
| 36 | |
| 37 | #include "modules/desktop_capture/desktop_frame.h" |
| 38 | #include "modules/desktop_capture/desktop_geometry.h" |
| 39 | #include "modules/desktop_capture/mac/sck_picker_handle.h" |
| 40 | |
| 41 | namespace { |
| 42 | |
| 43 | constexpr size_t kMinCaptureDimension = 2; |
| 44 | constexpr size_t kMaxCaptureDimension = 16384; |
| 45 | constexpr uint32_t kDefaultMaxFps = 30; |
| 46 | |
| 47 | livekit_ffi::SckCaptureStatus status_for_stop_error(NSError* error) { |
| 48 | if ([error.domain isEqualToString:SCStreamErrorDomain]) { |
| 49 | if (error.code == SCStreamErrorUserStopped) { |
| 50 | return livekit_ffi::SckCaptureStatus::kStoppedByUser; |
| 51 | } |
| 52 | if (error.code == SCStreamErrorNoCaptureSource) { |
| 53 | return livekit_ffi::SckCaptureStatus::kWindowGone; |
| 54 | } |
| 55 | } |
| 56 | return livekit_ffi::SckCaptureStatus::kInterrupted; |
| 57 | } |
| 58 | |
| 59 | size_t clamp_dimension(double pixels) { |
| 60 | if (!std::isfinite(pixels) || pixels < static_cast<double>(kMinCaptureDimension)) { |
| 61 | return kMinCaptureDimension; |
| 62 | } |
| 63 | if (pixels > static_cast<double>(kMaxCaptureDimension)) { |
| 64 | return kMaxCaptureDimension; |
| 65 | } |
| 66 | return static_cast<size_t>(std::llround(pixels)); |
| 67 | } |
| 68 | |
| 69 | double clamp_double(double value, double lo, double hi) { |
| 70 | if (value < lo) { |
| 71 | return lo; |
| 72 | } |
| 73 | if (value > hi) { |
| 74 | return hi; |
| 75 | } |
| 76 | return value; |
| 77 | } |
| 78 | |
| 79 | } // namespace |
| 80 | |
| 81 | @interface LiveKitMacWindowSession |
| 82 | : NSObject <SCStreamDelegate, SCStreamOutput, SCContentSharingPickerObserver> |
| 83 | - (instancetype)initWithMaxFps:(uint32_t)maxFps includeCursor:(BOOL)includeCursor; |
| 84 | - (void)startPickerWithPicker:(SCContentSharingPicker*)picker; |
| 85 | - (void)setMaxFps:(uint32_t)maxFps; |
| 86 | - (BOOL)pollFrame:(std::unique_ptr<webrtc::DesktopFrame>*)outFrame |
| 87 | status:(livekit_ffi::SckCaptureStatus*)outStatus; |
| 88 | - (void)stop; |
| 89 | @end |
| 90 | |
| 91 | @implementation LiveKitMacWindowSession { |
| 92 | BOOL _stopped; |
| 93 | BOOL _pickerCancelled; |
| 94 | BOOL _pickerFailed; |
| 95 | // Set when ScreenCaptureKit stops the running stream; kActive while running. |
| 96 | livekit_ffi::SckCaptureStatus _endStatus; |
| 97 | // The shared window is closed (macOS 15.2+). It may come back. |
| 98 | BOOL _windowClosed; |
| 99 | BOOL _includeCursor; |
| 100 | uint32_t _maxFps; |
| 101 | SCStream* _stream; |
| 102 | SCContentFilter* _filter; |
| 103 | size_t _configuredWidth; |
| 104 | size_t _configuredHeight; |
| 105 | IOSurfaceRef _latestSurface; |
| 106 | CGRect _latestCropRect; |
| 107 | dispatch_queue_t _captureQueue; |
| 108 | // Guarded by @synchronized(self): read on the main queue when presenting and |
| 109 | // cleared in stop. |
| 110 | SCContentSharingPicker* _picker; |
| 111 | SCContentSharingPickerConfiguration* _previousPickerConfig; |
| 112 | BOOL _savedPickerConfig; |
| 113 | // Serializes all updateContentFilter and updateConfiguration calls on _stream. |
| 114 | // replayd checks each updateConfiguration against the picked content; one sent |
| 115 | // before the picked filter is in place fails that check and falls back to the |
| 116 | // Screen Recording permission. At most one async update runs at a time, and a |
| 117 | // pending filter always runs before any configuration change (size or fps). |
| 118 | BOOL _streamOpInFlight; |
| 119 | BOOL _filterUpdateInFlight; |
| 120 | SCContentFilter* _pendingFilter; |
| 121 | BOOL _configDirty; |
| 122 | } |
| 123 | |
| 124 | - (instancetype)initWithMaxFps:(uint32_t)maxFps includeCursor:(BOOL)includeCursor { |
| 125 | self = [super init]; |
| 126 | if (self) { |
| 127 | _endStatus = livekit_ffi::SckCaptureStatus::kActive; |
| 128 | _maxFps = maxFps; |
| 129 | _includeCursor = includeCursor; |
| 130 | _captureQueue = dispatch_queue_create("org.rusty-teams.sck-window", DISPATCH_QUEUE_SERIAL); |
| 131 | } |
| 132 | return self; |
| 133 | } |
| 134 | |
| 135 | - (void)dealloc { |
| 136 | if (_latestSurface != NULL) { |
| 137 | IOSurfaceDecrementUseCount(_latestSurface); |
| 138 | CFRelease(_latestSurface); |
| 139 | _latestSurface = NULL; |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | - (SCStreamConfiguration*)buildConfigWithWidth:(size_t)width |
| 144 | height:(size_t)height |
| 145 | maxFps:(uint32_t)maxFps |
| 146 | includeCursor:(BOOL)includeCursor { |
| 147 | SCStreamConfiguration* config = [[SCStreamConfiguration alloc] init]; |
| 148 | config.pixelFormat = kCVPixelFormatType_32BGRA; |
| 149 | config.colorSpaceName = kCGColorSpaceSRGB; |
| 150 | config.showsCursor = includeCursor; |
| 151 | config.captureResolution = SCCaptureResolutionBest; |
| 152 | config.width = width < kMinCaptureDimension ? kMinCaptureDimension : width; |
| 153 | config.height = height < kMinCaptureDimension ? kMinCaptureDimension : height; |
| 154 | config.minimumFrameInterval = |
| 155 | maxFps > 0 ? CMTimeMake(1, static_cast<int32_t>(maxFps)) : kCMTimeZero; |
| 156 | return config; |
| 157 | } |
| 158 | |
| 159 | // `picker` comes from a webrtc::SckPickerHandle, which owns its `active` and |
| 160 | // `maximumStreamCount` properties. They are shared with WebRTC's own SCK |
| 161 | // capturer, so this session must not change them. |
| 162 | - (void)startPickerWithPicker:(SCContentSharingPicker*)picker { |
| 163 | @synchronized(self) { |
| 164 | if (_stopped) { |
| 165 | return; |
| 166 | } |
| 167 | _picker = picker; |
| 168 | _previousPickerConfig = [picker.defaultConfiguration copy]; |
| 169 | _savedPickerConfig = YES; |
| 170 | } |
| 171 | [picker addObserver:self]; |
| 172 | SCContentSharingPickerConfiguration* config = [[SCContentSharingPickerConfiguration alloc] init]; |
| 173 | config.allowedPickerModes = SCContentSharingPickerModeSingleWindow; |
| 174 | config.allowsChangingSelectedContent = YES; |
| 175 | picker.defaultConfiguration = config; |
| 176 | |
| 177 | // ScreenCaptureKit presents the picker on the main queue. Async avoids |
| 178 | // deadlocking if the main thread stops the capture and joins portal-share. |
| 179 | __weak LiveKitMacWindowSession* weakSelf = self; |
| 180 | dispatch_async(dispatch_get_main_queue(), ^{ |
| 181 | LiveKitMacWindowSession* strongSelf = weakSelf; |
| 182 | if (strongSelf == nil) { |
| 183 | return; |
| 184 | } |
| 185 | SCContentSharingPicker* activePicker = nil; |
| 186 | @synchronized(strongSelf) { |
| 187 | if (strongSelf->_stopped) { |
| 188 | return; |
| 189 | } |
| 190 | activePicker = strongSelf->_picker; |
| 191 | } |
| 192 | if (activePicker != nil) { |
| 193 | [activePicker presentPickerUsingContentStyle:SCShareableContentStyleWindow]; |
| 194 | } |
| 195 | }); |
| 196 | } |
| 197 | |
| 198 | - (void)drainStreamUpdates { |
| 199 | [self runNextStreamUpdateCompletingOp:NO wasFilter:NO forStream:nil filterError:nil]; |
| 200 | } |
| 201 | |
| 202 | // Transitions directly from a completing async SCStream op to the next queued |
| 203 | // update under one @synchronized(self) acquisition, so no resize frame can slip |
| 204 | // in between a picked filter update and its matching configuration update. |
| 205 | - (void)runNextStreamUpdateCompletingOp:(BOOL)completingOp |
| 206 | wasFilter:(BOOL)wasFilter |
| 207 | forStream:(nullable SCStream*)completedStream |
| 208 | filterError:(nullable NSError*)filterError { |
| 209 | SCStream* stream = nil; |
| 210 | SCContentFilter* filterToApply = nil; |
| 211 | SCStreamConfiguration* configToApply = nil; |
| 212 | |
| 213 | @synchronized(self) { |
| 214 | if (completingOp) { |
| 215 | _streamOpInFlight = NO; |
| 216 | if (wasFilter) { |
| 217 | _filterUpdateInFlight = NO; |
| 218 | } |
| 219 | if (_stopped || _pickerFailed || completedStream == nil || _stream != completedStream) { |
| 220 | return; |
| 221 | } |
| 222 | if (wasFilter && filterError != nil) { |
| 223 | _pickerFailed = YES; |
| 224 | _pendingFilter = nil; |
| 225 | _configDirty = NO; |
| 226 | return; |
| 227 | } |
| 228 | } else if (_stopped || _pickerFailed || _stream == nil || _streamOpInFlight) { |
| 229 | return; |
| 230 | } |
| 231 | |
| 232 | stream = _stream; |
| 233 | if (_pendingFilter != nil) { |
| 234 | filterToApply = _pendingFilter; |
| 235 | _pendingFilter = nil; |
| 236 | _streamOpInFlight = YES; |
| 237 | _filterUpdateInFlight = YES; |
| 238 | } else if (_configDirty && _configuredWidth >= kMinCaptureDimension && |
| 239 | _configuredHeight >= kMinCaptureDimension) { |
| 240 | _configDirty = NO; |
| 241 | configToApply = [self buildConfigWithWidth:_configuredWidth |
| 242 | height:_configuredHeight |
| 243 | maxFps:_maxFps |
| 244 | includeCursor:_includeCursor]; |
| 245 | _streamOpInFlight = YES; |
| 246 | } else { |
| 247 | return; |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | // Weak: the stream keeps this handler until the update completes. |
| 252 | __weak LiveKitMacWindowSession* weakSelf = self; |
| 253 | __weak SCStream* weakStream = stream; |
| 254 | if (filterToApply != nil) { |
| 255 | [stream updateContentFilter:filterToApply |
| 256 | completionHandler:^(NSError* _Nullable error) { |
| 257 | LiveKitMacWindowSession* strongSelf = weakSelf; |
| 258 | if (strongSelf == nil) { |
| 259 | return; |
| 260 | } |
| 261 | [strongSelf runNextStreamUpdateCompletingOp:YES |
| 262 | wasFilter:YES |
| 263 | forStream:weakStream |
| 264 | filterError:error]; |
| 265 | }]; |
| 266 | return; |
| 267 | } |
| 268 | |
| 269 | [stream updateConfiguration:configToApply |
| 270 | completionHandler:^(NSError* _Nullable configError) { |
| 271 | (void)configError; |
| 272 | LiveKitMacWindowSession* strongSelf = weakSelf; |
| 273 | if (strongSelf == nil) { |
| 274 | return; |
| 275 | } |
| 276 | [strongSelf runNextStreamUpdateCompletingOp:YES |
| 277 | wasFilter:NO |
| 278 | forStream:weakStream |
| 279 | filterError:nil]; |
| 280 | }]; |
| 281 | } |
| 282 | |
| 283 | - (void)setMaxFps:(uint32_t)maxFps { |
| 284 | BOOL shouldDrain = NO; |
| 285 | @synchronized(self) { |
| 286 | if (_stopped || _pickerFailed || _maxFps == maxFps) { |
| 287 | return; |
| 288 | } |
| 289 | _maxFps = maxFps; |
| 290 | if (_stream != nil && _configuredWidth >= kMinCaptureDimension && |
| 291 | _configuredHeight >= kMinCaptureDimension) { |
| 292 | _configDirty = YES; |
| 293 | shouldDrain = !_streamOpInFlight; |
| 294 | } |
| 295 | } |
| 296 | if (shouldDrain) { |
| 297 | [self drainStreamUpdates]; |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | - (BOOL)pollFrame:(std::unique_ptr<webrtc::DesktopFrame>*)outFrame |
| 302 | status:(livekit_ffi::SckCaptureStatus*)outStatus { |
| 303 | *outFrame = nullptr; |
| 304 | *outStatus = livekit_ffi::SckCaptureStatus::kActive; |
| 305 | |
| 306 | IOSurfaceRef surface = NULL; |
| 307 | CGRect crop = CGRectZero; |
| 308 | @synchronized(self) { |
| 309 | if (_stopped) { |
| 310 | *outStatus = livekit_ffi::SckCaptureStatus::kPickerCancelled; |
| 311 | return NO; |
| 312 | } |
| 313 | if (_pickerFailed) { |
| 314 | *outStatus = livekit_ffi::SckCaptureStatus::kStartFailed; |
| 315 | return NO; |
| 316 | } |
| 317 | if (_pickerCancelled) { |
| 318 | *outStatus = livekit_ffi::SckCaptureStatus::kPickerCancelled; |
| 319 | return NO; |
| 320 | } |
| 321 | if (_endStatus != livekit_ffi::SckCaptureStatus::kActive) { |
| 322 | *outStatus = _endStatus; |
| 323 | return NO; |
| 324 | } |
| 325 | if (_windowClosed) { |
| 326 | *outStatus = livekit_ffi::SckCaptureStatus::kWindowGone; |
| 327 | return NO; |
| 328 | } |
| 329 | if (_latestSurface == NULL) { |
| 330 | *outStatus = livekit_ffi::SckCaptureStatus::kActive; |
| 331 | return NO; |
| 332 | } |
| 333 | surface = _latestSurface; |
| 334 | crop = _latestCropRect; |
| 335 | CFRetain(surface); |
| 336 | IOSurfaceIncrementUseCount(surface); |
| 337 | } |
| 338 | |
| 339 | BOOL captured = NO; |
| 340 | if (IOSurfaceLock(surface, kIOSurfaceLockReadOnly, NULL) == kIOReturnSuccess) { |
| 341 | const uint8_t* base = static_cast<const uint8_t*>(IOSurfaceGetBaseAddress(surface)); |
| 342 | size_t surfW = IOSurfaceGetWidth(surface); |
| 343 | size_t surfH = IOSurfaceGetHeight(surface); |
| 344 | size_t stride = IOSurfaceGetBytesPerRow(surface); |
| 345 | size_t bpp = IOSurfaceGetBytesPerElement(surface); |
| 346 | if (base != NULL && bpp == 4 && surfW >= kMinCaptureDimension && |
| 347 | surfH >= kMinCaptureDimension && stride >= surfW * 4) { |
| 348 | size_t x = 0; |
| 349 | size_t y = 0; |
| 350 | size_t w = surfW; |
| 351 | size_t h = surfH; |
| 352 | if (!CGRectIsEmpty(crop)) { |
| 353 | size_t cx = static_cast<size_t>(crop.origin.x); |
| 354 | size_t cy = static_cast<size_t>(crop.origin.y); |
| 355 | size_t cw = static_cast<size_t>(crop.size.width); |
| 356 | size_t ch = static_cast<size_t>(crop.size.height); |
| 357 | if (cx < surfW && cy < surfH && cw >= kMinCaptureDimension && ch >= kMinCaptureDimension && |
| 358 | cx + cw <= surfW && cy + ch <= surfH) { |
| 359 | x = cx; |
| 360 | y = cy; |
| 361 | w = cw; |
| 362 | h = ch; |
| 363 | } |
| 364 | } |
| 365 | size_t offset = y * stride + x * 4; |
| 366 | size_t totalBytes = surfH * stride; |
| 367 | if (offset < totalBytes) { |
| 368 | size_t availableBytes = totalBytes - offset; |
| 369 | size_t rowBytes = w * 4; |
| 370 | size_t minNeeded = (h - 1) * stride + rowBytes; |
| 371 | if (w <= INT_MAX && h <= INT_MAX && stride <= INT_MAX && availableBytes >= minNeeded) { |
| 372 | auto frame = std::make_unique<webrtc::BasicDesktopFrame>( |
| 373 | webrtc::DesktopSize(static_cast<int>(w), static_cast<int>(h))); |
| 374 | frame->CopyPixelsFrom( |
| 375 | base + offset, |
| 376 | static_cast<int>(stride), |
| 377 | webrtc::DesktopRect::MakeWH(static_cast<int>(w), static_cast<int>(h))); |
| 378 | frame->set_may_contain_cursor(_includeCursor ? true : false); |
| 379 | *outFrame = std::move(frame); |
| 380 | captured = YES; |
| 381 | } |
| 382 | } |
| 383 | } |
| 384 | IOSurfaceUnlock(surface, kIOSurfaceLockReadOnly, NULL); |
| 385 | } |
| 386 | |
| 387 | IOSurfaceDecrementUseCount(surface); |
| 388 | CFRelease(surface); |
| 389 | return captured; |
| 390 | } |
| 391 | |
| 392 | - (void)stop { |
| 393 | SCStream* streamToStop = nil; |
| 394 | SCContentSharingPicker* picker = nil; |
| 395 | SCContentSharingPickerConfiguration* previousConfig = nil; |
| 396 | BOOL restoreConfig = NO; |
| 397 | IOSurfaceRef surfaceToRelease = NULL; |
| 398 | @synchronized(self) { |
| 399 | if (_stopped) { |
| 400 | return; |
| 401 | } |
| 402 | _stopped = YES; |
| 403 | streamToStop = _stream; |
| 404 | _stream = nil; |
| 405 | _filter = nil; |
| 406 | _pendingFilter = nil; |
| 407 | _configDirty = NO; |
| 408 | picker = _picker; |
| 409 | _picker = nil; |
| 410 | previousConfig = _previousPickerConfig; |
| 411 | _previousPickerConfig = nil; |
| 412 | restoreConfig = _savedPickerConfig; |
| 413 | _savedPickerConfig = NO; |
| 414 | surfaceToRelease = _latestSurface; |
| 415 | _latestSurface = NULL; |
| 416 | } |
| 417 | |
| 418 | if (picker != nil) { |
| 419 | [picker removeObserver:self]; |
| 420 | if (restoreConfig) { |
| 421 | picker.defaultConfiguration = previousConfig != nil ? |
| 422 | previousConfig : |
| 423 | [[SCContentSharingPickerConfiguration alloc] init]; |
| 424 | } |
| 425 | } |
| 426 | if (streamToStop != nil) { |
| 427 | [streamToStop removeStreamOutput:self type:SCStreamOutputTypeScreen error:nil]; |
| 428 | [streamToStop stopCaptureWithCompletionHandler:nil]; |
| 429 | } |
| 430 | |
| 431 | if (surfaceToRelease != NULL) { |
| 432 | IOSurfaceDecrementUseCount(surfaceToRelease); |
| 433 | CFRelease(surfaceToRelease); |
| 434 | } |
| 435 | } |
| 436 | |
| 437 | - (void)maybeReconfigureWidth:(size_t)desiredW height:(size_t)desiredH { |
| 438 | BOOL shouldDrain = NO; |
| 439 | @synchronized(self) { |
| 440 | // Do not overwrite dimensions or send a configuration update while a newly |
| 441 | // picked filter is waiting or in flight; its completion applies the new |
| 442 | // window's size and later frames resize from there. |
| 443 | if (_stopped || _pickerFailed || _stream == nil || _pendingFilter != nil || |
| 444 | _filterUpdateInFlight) { |
| 445 | return; |
| 446 | } |
| 447 | long dw = static_cast<long>(desiredW) - static_cast<long>(_configuredWidth); |
| 448 | long dh = static_cast<long>(desiredH) - static_cast<long>(_configuredHeight); |
| 449 | if (std::labs(dw) < 2 && std::labs(dh) < 2) { |
| 450 | return; |
| 451 | } |
| 452 | _configuredWidth = desiredW; |
| 453 | _configuredHeight = desiredH; |
| 454 | _configDirty = YES; |
| 455 | shouldDrain = !_streamOpInFlight; |
| 456 | } |
| 457 | if (shouldDrain) { |
| 458 | [self drainStreamUpdates]; |
| 459 | } |
| 460 | } |
| 461 | |
| 462 | - (void)contentSharingPicker:(SCContentSharingPicker*)picker |
| 463 | didUpdateWithFilter:(SCContentFilter*)filter |
| 464 | forStream:(nullable SCStream*)stream { |
| 465 | (void)picker; |
| 466 | BOOL updateExisting = NO; |
| 467 | SCStream* newStream = nil; |
| 468 | SCStreamConfiguration* config = nil; |
| 469 | dispatch_queue_t queue = nil; |
| 470 | |
| 471 | @synchronized(self) { |
| 472 | if (_stopped || _pickerFailed) { |
| 473 | return; |
| 474 | } |
| 475 | if (stream != nil && stream != _stream) { |
| 476 | return; |
| 477 | } |
| 478 | |
| 479 | CGRect contentRect = filter.contentRect; |
| 480 | double scale = filter.pointPixelScale > 0.0f ? filter.pointPixelScale : 1.0; |
| 481 | size_t width = clamp_dimension(contentRect.size.width * scale); |
| 482 | size_t height = clamp_dimension(contentRect.size.height * scale); |
| 483 | |
| 484 | _filter = filter; |
| 485 | _windowClosed = NO; |
| 486 | _configuredWidth = width; |
| 487 | _configuredHeight = height; |
| 488 | |
| 489 | if (_stream != nil) { |
| 490 | _pendingFilter = filter; |
| 491 | _configDirty = YES; |
| 492 | updateExisting = YES; |
| 493 | } else { |
| 494 | config = [self buildConfigWithWidth:width |
| 495 | height:height |
| 496 | maxFps:_maxFps |
| 497 | includeCursor:_includeCursor]; |
| 498 | newStream = [[SCStream alloc] initWithFilter:filter configuration:config delegate:self]; |
| 499 | _stream = newStream; |
| 500 | queue = _captureQueue; |
| 501 | } |
| 502 | } |
| 503 | |
| 504 | if (updateExisting) { |
| 505 | [self drainStreamUpdates]; |
| 506 | return; |
| 507 | } |
| 508 | |
| 509 | if (newStream == nil) { |
| 510 | @synchronized(self) { |
| 511 | _pickerFailed = YES; |
| 512 | } |
| 513 | return; |
| 514 | } |
| 515 | |
| 516 | // Rely on `picker.defaultConfiguration` rather than calling |
| 517 | // `[picker setConfiguration:forStream:]`: mutating the per-stream picker |
| 518 | // configuration dispatches an async `updateStream:withContentFilter:` IPC |
| 519 | // whose filter no longer matches the picker-authorized filter in `replayd`, |
| 520 | // causing `verifyContentPickerFilter:` to fail and trigger spurious Screen |
| 521 | // Recording TCC prompts on macOS 27. |
| 522 | |
| 523 | NSError* error = nil; |
| 524 | BOOL added = [newStream addStreamOutput:self |
| 525 | type:SCStreamOutputTypeScreen |
| 526 | sampleHandlerQueue:queue |
| 527 | error:&error]; |
| 528 | if (!added || error != nil) { |
| 529 | @synchronized(self) { |
| 530 | _pickerFailed = YES; |
| 531 | } |
| 532 | return; |
| 533 | } |
| 534 | |
| 535 | __weak LiveKitMacWindowSession* weakSelf = self; |
| 536 | [newStream startCaptureWithCompletionHandler:^(NSError* _Nullable startError) { |
| 537 | if (startError == nil) { |
| 538 | return; |
| 539 | } |
| 540 | LiveKitMacWindowSession* strongSelf = weakSelf; |
| 541 | if (strongSelf == nil) { |
| 542 | return; |
| 543 | } |
| 544 | // A capture that never starts is a failure to report, not a cancel. |
| 545 | @synchronized(strongSelf) { |
| 546 | strongSelf->_pickerFailed = YES; |
| 547 | } |
| 548 | }]; |
| 549 | } |
| 550 | |
| 551 | - (void)contentSharingPicker:(SCContentSharingPicker*)picker |
| 552 | didCancelForStream:(nullable SCStream*)stream { |
| 553 | (void)picker; |
| 554 | @synchronized(self) { |
| 555 | if (_stopped || _pickerFailed) { |
| 556 | return; |
| 557 | } |
| 558 | // Only treat cancelling the initial picker as cancellation; cancelling a |
| 559 | // mid-share "Change Window" sheet keeps the active capture running. |
| 560 | if (stream == nil && _stream == nil) { |
| 561 | _pickerCancelled = YES; |
| 562 | } |
| 563 | } |
| 564 | } |
| 565 | |
| 566 | - (void)contentSharingPickerStartDidFailWithError:(NSError*)error { |
| 567 | (void)error; |
| 568 | @synchronized(self) { |
| 569 | if (!_stopped && _stream == nil) { |
| 570 | _pickerFailed = YES; |
| 571 | } |
| 572 | } |
| 573 | } |
| 574 | |
| 575 | - (void)stream:(SCStream*)stream |
| 576 | didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer |
| 577 | ofType:(SCStreamOutputType)type { |
| 578 | (void)stream; |
| 579 | if (type != SCStreamOutputTypeScreen) { |
| 580 | return; |
| 581 | } |
| 582 | CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer); |
| 583 | if (imageBuffer == NULL) { |
| 584 | return; |
| 585 | } |
| 586 | IOSurfaceRef ioSurface = CVPixelBufferGetIOSurface(imageBuffer); |
| 587 | if (ioSurface == NULL) { |
| 588 | return; |
| 589 | } |
| 590 | CFArrayRef attachments = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, false); |
| 591 | if (attachments == NULL || CFArrayGetCount(attachments) == 0) { |
| 592 | return; |
| 593 | } |
| 594 | NSDictionary* dict = (__bridge NSDictionary*)CFArrayGetValueAtIndex(attachments, 0); |
| 595 | if (dict == nil) { |
| 596 | return; |
| 597 | } |
| 598 | |
| 599 | NSNumber* statusNum = dict[SCStreamFrameInfoStatus]; |
| 600 | if (statusNum == nil) { |
| 601 | return; |
| 602 | } |
| 603 | NSInteger status = [statusNum integerValue]; |
| 604 | if (status != SCFrameStatusComplete && status != SCFrameStatusStarted) { |
| 605 | return; |
| 606 | } |
| 607 | |
| 608 | double scaleFactor = 1.0; |
| 609 | NSNumber* scaleNum = dict[SCStreamFrameInfoScaleFactor]; |
| 610 | if (scaleNum != nil && [scaleNum doubleValue] > 0.0) { |
| 611 | scaleFactor = [scaleNum doubleValue]; |
| 612 | } |
| 613 | |
| 614 | double contentScale = 1.0; |
| 615 | NSNumber* contentScaleNum = dict[SCStreamFrameInfoContentScale]; |
| 616 | if (contentScaleNum != nil && [contentScaleNum doubleValue] > 0.0) { |
| 617 | contentScale = [contentScaleNum doubleValue]; |
| 618 | } |
| 619 | |
| 620 | CGRect contentRect = CGRectZero; |
| 621 | id rectObj = dict[SCStreamFrameInfoContentRect]; |
| 622 | if (rectObj != nil) { |
| 623 | if (!CGRectMakeWithDictionaryRepresentation((__bridge CFDictionaryRef)rectObj, &contentRect)) { |
| 624 | contentRect = CGRectZero; |
| 625 | } |
| 626 | } |
| 627 | |
| 628 | size_t surfW = IOSurfaceGetWidth(ioSurface); |
| 629 | size_t surfH = IOSurfaceGetHeight(ioSurface); |
| 630 | CGRect cropRect = CGRectZero; |
| 631 | if (!CGRectIsEmpty(contentRect) && surfW >= kMinCaptureDimension && |
| 632 | surfH >= kMinCaptureDimension) { |
| 633 | double rx = std::floor(contentRect.origin.x * scaleFactor); |
| 634 | double ry = std::floor(contentRect.origin.y * scaleFactor); |
| 635 | double rw = static_cast<double>(std::llround(contentRect.size.width * scaleFactor)); |
| 636 | double rh = static_cast<double>(std::llround(contentRect.size.height * scaleFactor)); |
| 637 | rx = clamp_double(rx, 0.0, static_cast<double>(surfW)); |
| 638 | ry = clamp_double(ry, 0.0, static_cast<double>(surfH)); |
| 639 | rw = clamp_double(rw, 0.0, static_cast<double>(surfW) - rx); |
| 640 | rh = clamp_double(rh, 0.0, static_cast<double>(surfH) - ry); |
| 641 | if (rw >= static_cast<double>(kMinCaptureDimension) && |
| 642 | rh >= static_cast<double>(kMinCaptureDimension)) { |
| 643 | cropRect = CGRectMake(rx, ry, rw, rh); |
| 644 | } |
| 645 | } |
| 646 | |
| 647 | if (!CGRectIsEmpty(contentRect)) { |
| 648 | size_t desiredW = clamp_dimension((contentRect.size.width / contentScale) * scaleFactor); |
| 649 | size_t desiredH = clamp_dimension((contentRect.size.height / contentScale) * scaleFactor); |
| 650 | [self maybeReconfigureWidth:desiredW height:desiredH]; |
| 651 | } |
| 652 | |
| 653 | IOSurfaceRef oldSurface = NULL; |
| 654 | @synchronized(self) { |
| 655 | if (_stopped || _pickerFailed) { |
| 656 | return; |
| 657 | } |
| 658 | CFRetain(ioSurface); |
| 659 | IOSurfaceIncrementUseCount(ioSurface); |
| 660 | oldSurface = _latestSurface; |
| 661 | _latestSurface = ioSurface; |
| 662 | _latestCropRect = cropRect; |
| 663 | } |
| 664 | |
| 665 | if (oldSurface != NULL) { |
| 666 | IOSurfaceDecrementUseCount(oldSurface); |
| 667 | CFRelease(oldSurface); |
| 668 | } |
| 669 | } |
| 670 | |
| 671 | // Stopping from the menu bar arrives as SCStreamErrorUserStopped. |
| 672 | - (void)stream:(SCStream*)stream didStopWithError:(NSError*)error { |
| 673 | @synchronized(self) { |
| 674 | if (!_stopped && stream == _stream && _endStatus == livekit_ffi::SckCaptureStatus::kActive) { |
| 675 | _endStatus = status_for_stop_error(error); |
| 676 | } |
| 677 | } |
| 678 | } |
| 679 | |
| 680 | // macOS 15.2+: every shared window was closed. The stream keeps running and |
| 681 | // would otherwise repeat the last frame. |
| 682 | - (void)streamDidBecomeInactive:(SCStream*)stream { |
| 683 | @synchronized(self) { |
| 684 | if (!_stopped && stream == _stream) { |
| 685 | _windowClosed = YES; |
| 686 | } |
| 687 | } |
| 688 | } |
| 689 | |
| 690 | - (void)streamDidBecomeActive:(SCStream*)stream { |
| 691 | @synchronized(self) { |
| 692 | if (stream == _stream) { |
| 693 | _windowClosed = NO; |
| 694 | } |
| 695 | } |
| 696 | } |
| 697 | |
| 698 | @end |
| 699 | |
| 700 | namespace livekit_ffi { |
| 701 | |
| 702 | namespace { |
| 703 | |
| 704 | class SckWindowCapturerImpl final : public SckWindowCapturer { |
| 705 | public: |
| 706 | explicit SckWindowCapturerImpl(const webrtc::DesktopCaptureOptions& options) |
| 707 | : include_cursor_(options.prefer_cursor_embedded()) {} |
| 708 | |
| 709 | ~SckWindowCapturerImpl() override { |
| 710 | @autoreleasepool { |
| 711 | if (session_ != nil) { |
| 712 | [session_ stop]; |
| 713 | session_ = nil; |
| 714 | } |
| 715 | // After the session has stopped its stream and left the picker: the |
| 716 | // last handle released deactivates the shared picker. |
| 717 | picker_handle_.reset(); |
| 718 | } |
| 719 | } |
| 720 | |
| 721 | void Start(Callback* callback) override { |
| 722 | callback_ = callback; |
| 723 | @autoreleasepool { |
| 724 | if (session_ != nil) { |
| 725 | [session_ stop]; |
| 726 | session_ = nil; |
| 727 | } |
| 728 | // Like WebRTC's ScreenCapturerSck, keep one handle for the capturer's |
| 729 | // lifetime; each session runs at most one stream at a time. |
| 730 | if (!picker_handle_) { |
| 731 | picker_handle_ = webrtc::CreateSckPickerHandle(); |
| 732 | } |
| 733 | if (!picker_handle_) { |
| 734 | // The shared picker reached its stream limit. With no session, |
| 735 | // CaptureFrame() reports kStartFailed. |
| 736 | return; |
| 737 | } |
| 738 | session_ = [[LiveKitMacWindowSession alloc] initWithMaxFps:max_fps_ |
| 739 | includeCursor:include_cursor_ ? YES : NO]; |
| 740 | [session_ startPickerWithPicker:picker_handle_->GetPicker()]; |
| 741 | } |
| 742 | } |
| 743 | |
| 744 | void SetMaxFrameRate(uint32_t max_frame_rate) override { |
| 745 | max_fps_ = max_frame_rate; |
| 746 | @autoreleasepool { |
| 747 | if (session_ != nil) { |
| 748 | [session_ setMaxFps:max_fps_]; |
| 749 | } |
| 750 | } |
| 751 | } |
| 752 | |
| 753 | void CaptureFrame() override { |
| 754 | if (!callback_) { |
| 755 | return; |
| 756 | } |
| 757 | @autoreleasepool { |
| 758 | if (session_ == nil) { |
| 759 | last_status_ = SckCaptureStatus::kStartFailed; |
| 760 | callback_->OnCaptureResult(Result::ERROR_PERMANENT, nullptr); |
| 761 | return; |
| 762 | } |
| 763 | std::unique_ptr<webrtc::DesktopFrame> frame; |
| 764 | SckCaptureStatus status = SckCaptureStatus::kActive; |
| 765 | if ([session_ pollFrame:&frame status:&status] && frame) { |
| 766 | last_status_ = SckCaptureStatus::kActive; |
| 767 | callback_->OnCaptureResult(Result::SUCCESS, std::move(frame)); |
| 768 | return; |
| 769 | } |
| 770 | last_status_ = status; |
| 771 | if (status == SckCaptureStatus::kActive || status == SckCaptureStatus::kWindowGone) { |
| 772 | callback_->OnCaptureResult(Result::ERROR_TEMPORARY, nullptr); |
| 773 | } else { |
| 774 | callback_->OnCaptureResult(Result::ERROR_PERMANENT, nullptr); |
| 775 | } |
| 776 | } |
| 777 | } |
| 778 | |
| 779 | bool GetSourceList(SourceList* sources) override { |
| 780 | if (sources) { |
| 781 | sources->clear(); |
| 782 | } |
| 783 | return true; |
| 784 | } |
| 785 | |
| 786 | bool SelectSource(SourceId /*id*/) override { return true; } |
| 787 | |
| 788 | SckCaptureStatus last_status() const override { return last_status_; } |
| 789 | |
| 790 | private: |
| 791 | bool include_cursor_ = true; |
| 792 | uint32_t max_fps_ = kDefaultMaxFps; |
| 793 | Callback* callback_ = nullptr; |
| 794 | SckCaptureStatus last_status_ = SckCaptureStatus::kActive; |
| 795 | // Created and released on the capturer thread, as SckPickerHandle requires. |
| 796 | std::unique_ptr<webrtc::SckPickerHandleInterface> picker_handle_; |
| 797 | LiveKitMacWindowSession* session_ = nil; |
| 798 | }; |
| 799 | |
| 800 | } // namespace |
| 801 | |
| 802 | std::unique_ptr<SckWindowCapturer> CreateSckWindowCapturer( |
| 803 | const webrtc::DesktopCaptureOptions& options) { |
| 804 | return std::make_unique<SckWindowCapturerImpl>(options); |
| 805 | } |
| 806 | |
| 807 | } // namespace livekit_ffi |
| 808 | |
| 809 | #endif // defined(WEBRTC_MAC) && !defined(WEBRTC_IOS) |