| 7 |
| #import "base/RTCVideoFrameBuffer.h" |
| 8 | #import "TGRTCCVPixelBuffer.h" |
| 9 | #import "sdk/objc/native/src/objc_video_track_source.h" |
| 10 | #import "sdk/objc/native/src/objc_frame_buffer.h" |
| 11 | #import "pc/video_track_source_proxy.h" |
| 12 |
| 13 | #import "helpers/UIDevice+RTCDevice.h" |
| 14 |
| 15 | #import "helpers/AVCaptureSession+DevicePosition.h" |
| 16 | #import "helpers/RTCDispatcher+Private.h" |
| 17 | #import "base/RTCVideoFrame.h" |
| 18 | #include "DarwinVideoSource.h" |
| 19 |
| 20 | #include "common_video/libyuv/include/webrtc_libyuv.h" |
| 21 | #include "rtc_base/checks.h" |
| 22 | #include "rtc_base/logging.h" |
| 23 | #include "third_party/libyuv/include/libyuv.h" |
| 24 | #include "api/video/i420_buffer.h" |
| 25 | #include "api/video/nv12_buffer.h" |
| 26 |
| 27 | #include "VideoCaptureView.h" |
| 28 |
| 29 | namespace { |
| 30 |
| 31 | static const int64_t kNanosecondsPerSecond = 1000000000; |
| 32 |
| 33 | static tgcalls::DarwinVideoTrackSource *getObjCVideoSource(const webrtc::scoped_refptr<webrtc::VideoTrackSourceInterface> nativeSource) { |
| 34 | webrtc::VideoTrackSourceProxy *proxy_source = |
| 35 | static_cast<webrtc::VideoTrackSourceProxy *>(nativeSource.get()); |
| 36 | return static_cast<tgcalls::DarwinVideoTrackSource *>(proxy_source->internal()); |
| 37 | } |
| 38 |
| 39 | static UIDeviceOrientation deviceOrientation(UIInterfaceOrientation orientation) { |
| 40 | switch (orientation) { |
| 41 | case UIInterfaceOrientationPortrait: |
| 42 | return UIDeviceOrientationPortrait; |
| 43 | case UIInterfaceOrientationPortraitUpsideDown: |
| 44 | return UIDeviceOrientationPortraitUpsideDown; |
| 45 | case UIInterfaceOrientationLandscapeLeft: |
| 46 | return UIDeviceOrientationLandscapeRight; |
| 47 | case UIInterfaceOrientationLandscapeRight: |
| 48 | return UIDeviceOrientationLandscapeLeft; |
| 49 | default: |
| 50 | return UIDeviceOrientationPortrait; |
| 51 | } |
| 52 | } |
| 53 |
| 54 | } |
| 55 |
| 56 | @interface VideoCameraCapturerPreviewRecord : NSObject |
| 57 |
| 58 | @property (nonatomic, weak) VideoCaptureView *view; |
| 59 |
| 60 | @end |
| 61 |
| 62 | @implementation VideoCameraCapturerPreviewRecord |
| 63 |
| 64 | - (instancetype)initWithCaptureView:(VideoCaptureView *)view { |
| 65 | self = [super init]; |
| 66 | if (self != nil) { |
| 67 | self.view = view; |
| 68 | } |
| 69 | return self; |
| 70 | } |
| 71 |
| 72 | @end |
| 73 |
| 74 | @interface VideoCameraCapturer () <AVCaptureVideoDataOutputSampleBufferDelegate> { |
| 75 | webrtc::scoped_refptr<webrtc::VideoTrackSourceInterface> _source; |
| 76 |
| 77 | // Live on main thread. |
| 78 | bool _isFrontCamera; |
| 79 | bool _keepLandscape; |
| 80 |
| 81 | dispatch_queue_t _frameQueue; |
| 82 |
| 83 | // Live on RTCDispatcherTypeCaptureSession. |
| 84 | AVCaptureDevice *_currentDevice; |
| 85 | BOOL _hasRetriedOnFatalError; |
| 86 | BOOL _isRunning; |
| 87 |
| 88 | // Live on RTCDispatcherTypeCaptureSession and main thread. |
| 89 | std::atomic<bool> _willBeRunning; |
| 90 |
| 91 | AVCaptureVideoDataOutput *_videoDataOutput; |
| 92 | AVCaptureSession *_captureSession; |
| 93 | FourCharCode _preferredOutputPixelFormat; |
| 94 | FourCharCode _outputPixelFormat; |
| 95 | RTCVideoRotation _rotation; |
| 96 | UIDeviceOrientation _orientation; |
| 97 | bool _didReceiveOrientationUpdate; |
| 98 | bool _rotationLock; |
| 99 |
| 100 | // Live on mainThread. |
| 101 | void (^_isActiveUpdated)(bool); |
| 102 | bool _isActiveValue; |
| 103 | bool _inForegroundValue; |
| 104 |
| 105 | void (^_rotationUpdated)(int); |
| 106 |
| 107 | // Live on frameQueue and main thread. |
| 108 | std::atomic<bool> _isPaused; |
| 109 |
| 110 | // Live on frameQueue. |
| 111 | float _aspectRatio; |
| 112 | std::vector<uint8_t> _croppingBuffer; |
| 113 | std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> _uncroppedSink; |
| 114 |
| 115 | // Live on frameQueue and RTCDispatcherTypeCaptureSession. |
| 116 | std::atomic<int> _warmupFrameCount; |
| 117 |
| 118 | webrtc::NV12ToI420Scaler _nv12ToI420Scaler; |
| 119 |
| 120 | NSMutableArray<VideoCameraCapturerPreviewRecord *> *_previews; |
| 121 | std::vector<std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>>> _directSinks; |
| 122 | } |
| 123 |
| 124 | @end |
| 125 |
| 126 | @implementation VideoCameraCapturer |
| 127 |
| 128 | - (instancetype)initWithSource:(webrtc::scoped_refptr<webrtc::VideoTrackSourceInterface>)source useFrontCamera:(bool)useFrontCamera keepLandscape:(bool)keepLandscape isActiveUpdated:(void (^)(bool))isActiveUpdated rotationUpdated:(void (^)(int))rotationUpdated { |
| 129 | self = [super init]; |
| 130 | if (self != nil) { |
| 131 | _source = source; |
| 132 | _isFrontCamera = useFrontCamera; |
| 133 | _keepLandscape = keepLandscape; |
| 134 | _isActiveValue = true; |
| 135 | _inForegroundValue = true; |
| 136 | _isPaused = false; |
| 137 | _isActiveUpdated = [isActiveUpdated copy]; |
| 138 | _rotationUpdated = [rotationUpdated copy]; |
| 139 |
| 140 | _warmupFrameCount = 100; |
| 141 |
| 142 | _previews = [[NSMutableArray alloc] init]; |
| 143 |
| 144 | if (![self setupCaptureSession:[[AVCaptureSession alloc] init]]) { |
| 145 | return nil; |
| 146 | } |
| 147 |
| 148 | NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; |
| 149 | _orientation = deviceOrientation([[UIApplication sharedApplication] statusBarOrientation]); |
| 150 | _rotation = RTCVideoRotation_90; |
| 151 |
| 152 | switch (_orientation) { |
| 153 | case UIDeviceOrientationPortrait: |
| 154 | _rotation = RTCVideoRotation_90; |
| 155 | break; |
| 156 | case UIDeviceOrientationPortraitUpsideDown: |
| 157 | _rotation = RTCVideoRotation_270; |
| 158 | break; |
| 159 | case UIDeviceOrientationLandscapeLeft: |
| 160 | _rotation = useFrontCamera ? RTCVideoRotation_180 : RTCVideoRotation_0; |
| 161 | break; |
| 162 | case UIDeviceOrientationLandscapeRight: |
| 163 | _rotation = useFrontCamera ? RTCVideoRotation_0 : RTCVideoRotation_180; |
| 164 | break; |
| 165 | case UIDeviceOrientationFaceUp: |
| 166 | case UIDeviceOrientationFaceDown: |
| 167 | case UIDeviceOrientationUnknown: |
| 168 | // Ignore. |
| 169 | break; |
| 170 | } |
| 171 |
| 172 | if (_rotationUpdated) { |
| 173 | int angle = 0; |
| 174 | switch (_rotation) { |
| 175 | case RTCVideoRotation_0: { |
| 176 | angle = 0; |
| 177 | break; |
| 178 | } |
| 179 | case RTCVideoRotation_90: { |
| 180 | angle = 90; |
| 181 | break; |
| 182 | } |
| 183 | case RTCVideoRotation_180: { |
| 184 | angle = 180; |
| 185 | break; |
| 186 | } |
| 187 | case RTCVideoRotation_270: { |
| 188 | angle = 270; |
| 189 | break; |
| 190 | } |
| 191 | default: { |
| 192 | break; |
| 193 | } |
| 194 | } |
| 195 | _rotationUpdated(angle); |
| 196 | } |
| 197 | [center addObserver:self |
| 198 | selector:@selector(deviceOrientationDidChange:) |
| 199 | name:UIDeviceOrientationDidChangeNotification |
| 200 | object:nil]; |
| 201 | [center addObserver:self |
| 202 | selector:@selector(handleCaptureSessionInterruption:) |
| 203 | name:AVCaptureSessionWasInterruptedNotification |
| 204 | object:_captureSession]; |
| 205 | [center addObserver:self |
| 206 | selector:@selector(handleCaptureSessionInterruptionEnded:) |
| 207 | name:AVCaptureSessionInterruptionEndedNotification |
| 208 | object:_captureSession]; |
| 209 | [center addObserver:self |
| 210 | selector:@selector(handleApplicationDidBecomeActive:) |
| 211 | name:UIApplicationDidBecomeActiveNotification |
| 212 | object:[UIApplication sharedApplication]]; |
| 213 | [center addObserver:self |
| 214 | selector:@selector(handleApplicationWillEnterForeground:) |
| 215 | name:UIApplicationWillEnterForegroundNotification |
| 216 | object:[UIApplication sharedApplication]]; |
| 217 | [center addObserver:self |
| 218 | selector:@selector(handleCaptureSessionRuntimeError:) |
| 219 | name:AVCaptureSessionRuntimeErrorNotification |
| 220 | object:_captureSession]; |
| 221 | [center addObserver:self |
| 222 | selector:@selector(handleCaptureSessionDidStartRunning:) |
| 223 | name:AVCaptureSessionDidStartRunningNotification |
| 224 | object:_captureSession]; |
| 225 | [center addObserver:self |
| 226 | selector:@selector(handleCaptureSessionDidStopRunning:) |
| 227 | name:AVCaptureSessionDidStopRunningNotification |
| 228 | object:_captureSession]; |
| 229 | } |
| 230 | return self; |
| 231 | } |
| 232 |
| 233 | - (void)dealloc { |
| 234 | NSAssert(!_willBeRunning, @"Session was still running in RTCCameraVideoCapturer dealloc. Forgot to call stopCapture?"); |
| 235 | [[NSNotificationCenter defaultCenter] removeObserver:self]; |
| 236 | } |
| 237 |
| 238 | + (NSArray<AVCaptureDevice *> *)captureDevices { |
| 239 | if (@available(iOS 10.0, *)) { |
| 240 | AVCaptureDeviceDiscoverySession *session = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:@[AVCaptureDeviceTypeBuiltInWideAngleCamera] mediaType:AVMediaTypeVideo position:AVCaptureDevicePositionUnspecified]; |
| 241 | return session.devices; |
| 242 | } else { |
| 243 | NSMutableArray<AVCaptureDevice *> *result = [[NSMutableArray alloc] init]; |
| 244 | for (AVCaptureDevice *device in [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]) { |
| 245 | if (device.position == AVCaptureDevicePositionFront || device.position == AVCaptureDevicePositionBack) { |
| 246 | [result addObject:device]; |
| 247 | } |
| 248 | } |
| 249 | return result; |
| 250 | } |
| 251 | } |
| 252 |
| 253 | + (NSArray<AVCaptureDeviceFormat *> *)supportedFormatsForDevice:(AVCaptureDevice *)device { |
| 254 | // Support opening the device in any format. We make sure it's converted to a format we |
| 255 | // can handle, if needed, in the method `-setupVideoDataOutput`. |
| 256 | return device.formats; |
| 257 | } |
| 258 |
| 259 | - (FourCharCode)preferredOutputPixelFormat { |
| 260 | return _preferredOutputPixelFormat; |
| 261 | } |
| 262 |
| 263 | - (void)startCaptureWithDevice:(AVCaptureDevice *)device |
| 264 | format:(AVCaptureDeviceFormat *)format |
| 265 | fps:(NSInteger)fps { |
| 266 | [self startCaptureWithDevice:device format:format fps:fps completionHandler:nil]; |
| 267 | } |
| 268 |
| 269 | - (void)stopCapture { |
| 270 | _isActiveUpdated = nil; |
| 271 | [self stopCaptureWithCompletionHandler:nil]; |
| 272 | } |
| 273 |
| 274 | - (void)setIsEnabled:(bool)isEnabled { |
| 275 | _isPaused = !isEnabled; |
| 276 | [self updateIsActiveValue]; |
| 277 | } |
| 278 |
| 279 | - (void)setUncroppedSink:(std::shared_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>>)sink { |
| 280 | dispatch_async(self.frameQueue, ^{ |
| 281 | _uncroppedSink = sink; |
| 282 | }); |
| 283 | } |
| 284 |
| 285 | - (int)getRotation { |
| 286 | switch (_rotation) { |
| 287 | case RTCVideoRotation_0: |
| 288 | return 0; |
| 289 | case RTCVideoRotation_90: |
| 290 | return 90; |
| 291 | case RTCVideoRotation_180: |
| 292 | return 180; |
| 293 | case RTCVideoRotation_270: |
| 294 | return 270; |
| 295 | default: |
| 296 | return 0; |
| 297 | } |
| 298 | } |
| 299 |
| 300 | - (void)addPreviewView:(VideoCaptureView *)previewView { |
| 301 | [_previews addObject:[[VideoCameraCapturerPreviewRecord alloc] initWithCaptureView:previewView]]; |
| 302 | [previewView previewLayer].session = _captureSession; |
| 303 | } |
| 304 |
| 305 | - (void)addDirectSink:(std::weak_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>>)directSink { |
| 306 | _directSinks.push_back(directSink); |
| 307 | } |
| 308 |
| 309 | - (void)setPreferredCaptureAspectRatio:(float)aspectRatio { |
| 310 | dispatch_async(self.frameQueue, ^{ |
| 311 | _aspectRatio = aspectRatio; |
| 312 | }); |
| 313 | } |
| 314 |
| 315 | - (void)startCaptureWithDevice:(AVCaptureDevice *)device |
| 316 | format:(AVCaptureDeviceFormat *)format |
| 317 | fps:(NSInteger)fps |
| 318 | completionHandler:(nullable void (^)(NSError *))completionHandler { |
| 319 | _willBeRunning = true; |
| 320 | [RTCDispatcher |
| 321 | dispatchAsyncOnType:RTCDispatcherTypeCaptureSession |
| 322 | block:^{ |
| 323 | RTCLogInfo("startCaptureWithDevice %@ @ %ld fps", format, (long)fps); |
| 324 |
| 325 | dispatch_async(dispatch_get_main_queue(), ^{ |
| 326 | [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; |
| 327 | }); |
| 328 |
| 329 | _currentDevice = device; |
| 330 |
| 331 | NSError *error = nil; |
| 332 | if (![_currentDevice lockForConfiguration:&error]) { |
| 333 | RTCLogError(@"Failed to lock device %@. Error: %@", |
| 334 | _currentDevice, |
| 335 | error.userInfo); |
| 336 | if (completionHandler) { |
| 337 | completionHandler(error); |
| 338 | } |
| 339 | _willBeRunning = false; |
| 340 | return; |
| 341 | } |
| 342 | [self reconfigureCaptureSessionInput]; |
| 343 | [self updateDeviceCaptureFormat:format fps:fps]; |
| 344 | [self updateVideoDataOutputPixelFormat:format]; |
| 345 | [_captureSession startRunning]; |
| 346 | [_currentDevice unlockForConfiguration]; |
| 347 | _isRunning = YES; |
| 348 | if (completionHandler) { |
| 349 | completionHandler(nil); |
| 350 | } |
| 351 | }]; |
| 352 | } |
| 353 |
| 354 | - (void)stopCaptureWithCompletionHandler:(nullable void (^)(void))completionHandler { |
| 355 | _willBeRunning = false; |
| 356 | [RTCDispatcher |
| 357 | dispatchAsyncOnType:RTCDispatcherTypeCaptureSession |
| 358 | block:^{ |
| 359 | RTCLogInfo("Stop"); |
| 360 | _currentDevice = nil; |
| 361 | for (AVCaptureDeviceInput *oldInput in [_captureSession.inputs copy]) { |
| 362 | [_captureSession removeInput:oldInput]; |
| 363 | } |
| 364 | [_captureSession stopRunning]; |
| 365 |
| 366 | dispatch_async(dispatch_get_main_queue(), ^{ |
| 367 | [[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications]; |
| 368 | }); |
| 369 | _isRunning = NO; |
| 370 | if (completionHandler) { |
| 371 | completionHandler(); |
| 372 | } |
| 373 | }]; |
| 374 | } |
| 375 |
| 376 | #pragma mark iOS notifications |
| 377 |
| 378 | #if TARGET_OS_IPHONE |
| 379 | - (void)deviceOrientationDidChange:(NSNotification *)notification { |
| 380 | [RTCDispatcher dispatchAsyncOnType:RTCDispatcherTypeCaptureSession block:^{ |
| 381 | _didReceiveOrientationUpdate = true; |
| 382 | [self updateOrientation]; |
| 383 | }]; |
| 384 | } |
| 385 | #endif |
| 386 |
| 387 | #pragma mark AVCaptureVideoDataOutputSampleBufferDelegate |
| 388 |
| 389 | - (webrtc::scoped_refptr<webrtc::VideoFrameBuffer>)prepareI420Buffer:(CVPixelBufferRef)pixelBuffer { |
| 390 | if (!pixelBuffer) { |
| 391 | return nullptr; |
| 392 | } |
| 393 |
| 394 | const OSType pixelFormat = CVPixelBufferGetPixelFormatType(pixelBuffer); |
| 395 |
| 396 | CVPixelBufferLockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly); |
| 397 |
| 398 | auto resultBuffer = rtc::make_ref_counted<webrtc::I420Buffer>(CVPixelBufferGetWidth(pixelBuffer), CVPixelBufferGetHeight(pixelBuffer)); |
| 399 |
| 400 | switch (pixelFormat) { |
| 401 | case kCVPixelFormatType_420YpCbCr8BiPlanarFullRange: |
| 402 | case kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange: { |
| 403 | const uint8_t* srcY = |
| 404 | static_cast<uint8_t*>(CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 0)); |
| 405 | const int srcYStride = (int)CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer, 0); |
| 406 | const uint8_t* srcUV = |
| 407 | static_cast<uint8_t*>(CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 1)); |
| 408 | const int srcUVStride = (int)CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer, 1); |
| 409 |
| 410 | // TODO(magjed): Use a frame buffer pool. |
| 411 | _nv12ToI420Scaler.NV12ToI420Scale(srcY, |
| 412 | srcYStride, |
| 413 | srcUV, |
| 414 | srcUVStride, |
| 415 | resultBuffer->width(), |
| 416 | resultBuffer->height(), |
| 417 | resultBuffer->MutableDataY(), |
| 418 | resultBuffer->StrideY(), |
| 419 | resultBuffer->MutableDataU(), |
| 420 | resultBuffer->StrideU(), |
| 421 | resultBuffer->MutableDataV(), |
| 422 | resultBuffer->StrideV(), |
| 423 | resultBuffer->width(), |
| 424 | resultBuffer->height()); |
| 425 | break; |
| 426 | } |
| 427 | case kCVPixelFormatType_32BGRA: |
| 428 | case kCVPixelFormatType_32ARGB: { |
| 429 | return nullptr; |
| 430 | } |
| 431 | default: { RTC_DCHECK_NOTREACHED() << "Unsupported pixel format."; } |
| 432 | } |
| 433 |
| 434 | CVPixelBufferUnlockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly); |
| 435 |
| 436 | return resultBuffer; |
| 437 | } |
| 438 |
| 439 | - (webrtc::scoped_refptr<webrtc::VideoFrameBuffer>)prepareNV12Buffer:(CVPixelBufferRef)pixelBuffer { |
| 440 | if (!pixelBuffer) { |
| 441 | return nullptr; |
| 442 | } |
| 443 |
| 444 | const OSType pixelFormat = CVPixelBufferGetPixelFormatType(pixelBuffer); |
| 445 |
| 446 | CVPixelBufferLockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly); |
| 447 |
| 448 | switch (pixelFormat) { |
| 449 | case kCVPixelFormatType_420YpCbCr8BiPlanarFullRange: |
| 450 | case kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange: { |
| 451 | const uint8_t* srcY = |
| 452 | static_cast<uint8_t*>(CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 0)); |
| 453 | const int srcYStride = (int)CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer, 0); |
| 454 | const uint8_t* srcUV = |
| 455 | static_cast<uint8_t*>(CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 1)); |
| 456 | const int srcUVStride = (int)CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer, 1); |
| 457 |
| 458 | const int srcWidth = (int)CVPixelBufferGetWidth(pixelBuffer); |
| 459 | const int srcHeight = (int)CVPixelBufferGetHeight(pixelBuffer); |
| 460 |
| 461 | int resultWidth = (int)(srcWidth * 0.8f); |
| 462 | resultWidth &= ~1; |
| 463 | int resultHeight = (int)(srcHeight * 0.8f); |
| 464 | resultHeight &= ~1; |
| 465 |
| 466 | webrtc::scoped_refptr<webrtc::NV12Buffer> resultBuffer = rtc::make_ref_counted<webrtc::NV12Buffer>(resultWidth, resultHeight, srcYStride, srcUVStride); |
| 467 |
| 468 | libyuv::NV12Scale(srcY, srcYStride, srcUV, srcUVStride, |
| 469 | resultWidth, resultHeight, resultBuffer->MutableDataY(), |
| 470 | resultBuffer->StrideY(), resultBuffer->MutableDataUV(), resultBuffer->StrideUV(), resultBuffer->width(), |
| 471 | resultBuffer->height(), libyuv::kFilterBilinear); |
| 472 |
| 473 | CVPixelBufferUnlockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly); |
| 474 |
| 475 | return resultBuffer; |
| 476 | } |
| 477 | case kCVPixelFormatType_32BGRA: |
| 478 | case kCVPixelFormatType_32ARGB: { |
| 479 | CVPixelBufferUnlockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly); |
| 480 | return nullptr; |
| 481 | } |
| 482 | default: { RTC_DCHECK_NOTREACHED() << "Unsupported pixel format."; } |
| 483 | } |
| 484 |
| 485 | return nullptr; |
| 486 | } |
| 487 |
| 488 | - (void)captureOutput:(AVCaptureOutput *)captureOutput |
| 489 | didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer |
| 490 | fromConnection:(AVCaptureConnection *)connection { |
| 491 | NSParameterAssert(captureOutput == _videoDataOutput); |
| 492 |
| 493 | int minWarmupFrameCount = 12; |
| 494 | _warmupFrameCount++; |
| 495 | if (_warmupFrameCount < minWarmupFrameCount) { |
| 496 | return; |
| 497 | } |
| 498 |
| 499 | if (CMSampleBufferGetNumSamples(sampleBuffer) != 1 || !CMSampleBufferIsValid(sampleBuffer) || |
| 500 | !CMSampleBufferDataIsReady(sampleBuffer)) { |
| 501 | return; |
| 502 | } |
| 503 |
| 504 | CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer); |
| 505 | if (pixelBuffer == nil) { |
| 506 | return; |
| 507 | } |
| 508 |
| 509 | // Default to portrait orientation on iPhone. |
| 510 | BOOL usingFrontCamera = NO; |
| 511 | // Check the image's EXIF for the camera the image came from as the image could have been |
| 512 | // delayed as we set alwaysDiscardsLateVideoFrames to NO. |
| 513 | AVCaptureDevicePosition cameraPosition = |
| 514 | [AVCaptureSession devicePositionForSampleBuffer:sampleBuffer]; |
| 515 | if (cameraPosition != AVCaptureDevicePositionUnspecified) { |
| 516 | usingFrontCamera = AVCaptureDevicePositionFront == cameraPosition; |
| 517 | } else { |
| 518 | AVCaptureDeviceInput *deviceInput = |
| 519 | (AVCaptureDeviceInput *)((AVCaptureInputPort *)connection.inputPorts.firstObject).input; |
| 520 | usingFrontCamera = AVCaptureDevicePositionFront == deviceInput.device.position; |
| 521 | } |
| 522 | int deviceRelativeVideoRotation = usingFrontCamera ? RTCVideoRotation_90 : RTCVideoRotation_90; |
| 523 | if (!_rotationLock) { |
| 524 | RTCVideoRotation updatedRotation = _rotation; |
| 525 | switch (_orientation) { |
| 526 | case UIDeviceOrientationPortrait: |
| 527 | updatedRotation = RTCVideoRotation_90; |
| 528 | break; |
| 529 | case UIDeviceOrientationPortraitUpsideDown: |
| 530 | updatedRotation = RTCVideoRotation_270; |
| 531 | break; |
| 532 | case UIDeviceOrientationLandscapeLeft: |
| 533 | updatedRotation = usingFrontCamera ? RTCVideoRotation_180 : RTCVideoRotation_0; |
| 534 | break; |
| 535 | case UIDeviceOrientationLandscapeRight: |
| 536 | updatedRotation = usingFrontCamera ? RTCVideoRotation_0 : RTCVideoRotation_180; |
| 537 | break; |
| 538 | case UIDeviceOrientationFaceUp: |
| 539 | case UIDeviceOrientationFaceDown: |
| 540 | case UIDeviceOrientationUnknown: |
| 541 | // Ignore. |
| 542 | break; |
| 543 | } |
| 544 | if (_rotation != updatedRotation) { |
| 545 | _rotation = updatedRotation; |
| 546 | if (_rotationUpdated) { |
| 547 | int angle = 0; |
| 548 | switch (_rotation) { |
| 549 | case RTCVideoRotation_0: { |
| 550 | angle = 0; |
| 551 | break; |
| 552 | } |
| 553 | case RTCVideoRotation_90: { |
| 554 | angle = 90; |
| 555 | break; |
| 556 | } |
| 557 | case RTCVideoRotation_180: { |
| 558 | angle = 180; |
| 559 | break; |
| 560 | } |
| 561 | case RTCVideoRotation_270: { |
| 562 | angle = 270; |
| 563 | break; |
| 564 | } |
| 565 | default: { |
| 566 | break; |
| 567 | } |
| 568 | } |
| 569 | _rotationUpdated(angle); |
| 570 | } |
| 571 | } |
| 572 | } |
| 573 |
| 574 | TGRTCCVPixelBuffer *rtcPixelBuffer = [[TGRTCCVPixelBuffer alloc] initWithPixelBuffer:pixelBuffer]; |
| 575 | rtcPixelBuffer.shouldBeMirrored = usingFrontCamera; |
| 576 | rtcPixelBuffer.deviceRelativeVideoRotation = deviceRelativeVideoRotation; |
| 577 |
| 578 | TGRTCCVPixelBuffer *uncroppedRtcPixelBuffer = rtcPixelBuffer; |
| 579 |
| 580 | CGSize initialSize = CGSizeMake(uncroppedRtcPixelBuffer.width, uncroppedRtcPixelBuffer.height); |
| 581 |
| 582 | if (_aspectRatio > FLT_EPSILON) { |
| 583 | float aspect = 1.0f / _aspectRatio; |
| 584 |
| 585 | int width = rtcPixelBuffer.width; |
| 586 | int height = rtcPixelBuffer.height; |
| 587 |
| 588 | int cropX = 0; |
| 589 | int cropY = 0; |
| 590 |
| 591 | if (_keepLandscape && width > height) { |
| 592 | float aspectWidth = 404.0f; |
| 593 | float aspectHeight = 720.0f; |
| 594 | cropX = (int)((width - aspectWidth) / 2.0f); |
| 595 | cropY = (int)((height - aspectHeight) / 2.0f); |
| 596 | width = aspectWidth; |
| 597 | height = aspectHeight; |
| 598 | } else { |
| 599 | float aspectWidth = width; |
| 600 | float aspectHeight = ((float)(width)) / aspect; |
| 601 | cropX = (int)((width - aspectWidth) / 2.0f); |
| 602 | cropY = (int)((height - aspectHeight) / 2.0f); |
| 603 | width = (int)aspectWidth; |
| 604 | width &= ~1; |
| 605 | height = (int)aspectHeight; |
| 606 | height &= ~1; |
| 607 | } |
| 608 |
| 609 | height = MIN(rtcPixelBuffer.height, height + 16); |
| 610 |
| 611 | if (width < rtcPixelBuffer.width || height < rtcPixelBuffer.height) { |
| 612 | rtcPixelBuffer = [[TGRTCCVPixelBuffer alloc] initWithPixelBuffer:pixelBuffer adaptedWidth:width adaptedHeight:height cropWidth:width cropHeight:height cropX:cropX cropY:cropY]; |
| 613 | rtcPixelBuffer.shouldBeMirrored = usingFrontCamera; |
| 614 | rtcPixelBuffer.deviceRelativeVideoRotation = deviceRelativeVideoRotation; |
| 615 |
| 616 | CVPixelBufferRef outputPixelBufferRef = NULL; |
| 617 | OSType pixelFormat = CVPixelBufferGetPixelFormatType(rtcPixelBuffer.pixelBuffer); |
| 618 | CVPixelBufferCreate(NULL, width, height, pixelFormat, NULL, &outputPixelBufferRef); |
| 619 | if (outputPixelBufferRef) { |
| 620 | int bufferSize = [rtcPixelBuffer bufferSizeForCroppingAndScalingToWidth:width height:height]; |
| 621 | if (_croppingBuffer.size() < bufferSize) { |
| 622 | _croppingBuffer.resize(bufferSize); |
| 623 | } |
| 624 | if ([rtcPixelBuffer cropAndScaleTo:outputPixelBufferRef withTempBuffer:_croppingBuffer.data()]) { |
| 625 | rtcPixelBuffer = [[TGRTCCVPixelBuffer alloc] initWithPixelBuffer:outputPixelBufferRef]; |
| 626 | rtcPixelBuffer.shouldBeMirrored = usingFrontCamera; |
| 627 | rtcPixelBuffer.deviceRelativeVideoRotation = deviceRelativeVideoRotation; |
| 628 | } |
| 629 | CVPixelBufferRelease(outputPixelBufferRef); |
| 630 | } |
| 631 | } |
| 632 | } |
| 633 |
| 634 | int64_t timeStampNs = CMTimeGetSeconds(CMSampleBufferGetPresentationTimeStamp(sampleBuffer)) * kNanosecondsPerSecond; |
| 635 |
| 636 | //RTCVideoFrame *videoFrame = [[RTCVideoFrame alloc] initWithBuffer:rtcPixelBuffer rotation:_rotation timeStampNs:timeStampNs]; |
| 637 |
| 638 | //RTCVideoFrame *videoFrame = [[RTCVideoFrame alloc] initWithBuffer:(id<RTCVideoFrameBuffer>)[rtcPixelBuffer toI420] rotation:_rotation timeStampNs:timeStampNs]; |
| 639 |
| 640 | webrtc::VideoRotation rotation = static_cast<webrtc::VideoRotation>(_rotation); |
| 641 |
| 642 | int previewRotation = 0; |
| 643 | CGSize previewSize = initialSize; |
| 644 | if (rotation == 90 || rotation == 270) { |
| 645 | previewSize = CGSizeMake(previewSize.height, previewSize.width); |
| 646 | } |
| 647 |
| 648 | for (VideoCameraCapturerPreviewRecord *record in _previews) { |
| 649 | dispatch_async(dispatch_get_main_queue(), ^{ |
| 650 | VideoCaptureView *captureView = record.view; |
| 651 | [captureView onFrameGenerated:previewSize isMirrored:true rotation:previewRotation]; |
| 652 | }); |
| 653 | } |
| 654 |
| 655 | auto i420Buffer = [self prepareI420Buffer:[rtcPixelBuffer pixelBuffer]]; |
| 656 |
| 657 | if (!_isPaused && i420Buffer) { |
| 658 | auto videoFrame = webrtc::VideoFrame::Builder() |
| 659 | .set_video_frame_buffer(i420Buffer) |
| 660 | .set_rotation(rotation) |
| 661 | .set_timestamp_us(timeStampNs) |
| 662 | .build(); |
| 663 |
| 664 | if (getObjCVideoSource(_source)->OnCapturedFrame(videoFrame)) { |
| 665 | if (!_directSinks.empty()) { |
| 666 | for (const auto &it : _directSinks) { |
| 667 | if (const auto value = it.lock()) { |
| 668 | value->OnFrame(videoFrame); |
| 669 | } |
| 670 | } |
| 671 | } |
| 672 | } |
| 673 |
| 674 | if (uncroppedRtcPixelBuffer) { |
| 675 | const auto uncroppedSink = _uncroppedSink.lock(); |
| 676 | if (uncroppedSink) { |
| 677 | int64_t timeStampNs = CMTimeGetSeconds(CMSampleBufferGetPresentationTimeStamp(sampleBuffer)) * |
| 678 | kNanosecondsPerSecond; |
| 679 | RTCVideoFrame *frame = [[RTCVideoFrame alloc] initWithBuffer:uncroppedRtcPixelBuffer rotation:_rotation timeStampNs:timeStampNs]; |
| 680 |
| 681 | const int64_t timestamp_us = frame.timeStampNs / rtc::kNumNanosecsPerMicrosec; |
| 682 |
| 683 | webrtc::scoped_refptr<webrtc::VideoFrameBuffer> buffer; |
| 684 | buffer = new rtc::RefCountedObject<webrtc::ObjCFrameBuffer>(frame.buffer); |
| 685 |
| 686 | webrtc::VideoRotation rotation = static_cast<webrtc::VideoRotation>(frame.rotation); |
| 687 |
| 688 | uncroppedSink->OnFrame(webrtc::VideoFrame::Builder() |
| 689 | .set_video_frame_buffer(buffer) |
| 690 | .set_rotation(rotation) |
| 691 | .set_timestamp_us(timestamp_us) |
| 692 | .build()); |
| 693 | } |
| 694 | } |
| 695 | } |
| 696 | } |
| 697 |
| 698 | - (void)captureOutput:(AVCaptureOutput *)captureOutput |
| 699 | didDropSampleBuffer:(CMSampleBufferRef)sampleBuffer |
| 700 | fromConnection:(AVCaptureConnection *)connection { |
| 701 | NSString *droppedReason = |
| 702 | (__bridge NSString *)CMGetAttachment(sampleBuffer, kCMSampleBufferAttachmentKey_DroppedFrameReason, nil); |
| 703 | RTCLogError(@"Dropped sample buffer. Reason: %@", droppedReason); |
| 704 | } |
| 705 |
| 706 | #pragma mark - AVCaptureSession notifications |
| 707 |
| 708 | - (void)handleCaptureSessionInterruption:(NSNotification *)notification { |
| 709 | NSString *reasonString = nil; |
| 710 | NSNumber *reason = notification.userInfo[AVCaptureSessionInterruptionReasonKey]; |
| 711 | if (reason) { |
| 712 | switch (reason.intValue) { |
| 713 | case AVCaptureSessionInterruptionReasonVideoDeviceNotAvailableInBackground: |
| 714 | reasonString = @"VideoDeviceNotAvailableInBackground"; |
| 715 | break; |
| 716 | case AVCaptureSessionInterruptionReasonAudioDeviceInUseByAnotherClient: |
| 717 | reasonString = @"AudioDeviceInUseByAnotherClient"; |
| 718 | break; |
| 719 | case AVCaptureSessionInterruptionReasonVideoDeviceInUseByAnotherClient: |
| 720 | reasonString = @"VideoDeviceInUseByAnotherClient"; |
| 721 | break; |
| 722 | case AVCaptureSessionInterruptionReasonVideoDeviceNotAvailableWithMultipleForegroundApps: |
| 723 | reasonString = @"VideoDeviceNotAvailableWithMultipleForegroundApps"; |
| 724 | break; |
| 725 | } |
| 726 | } |
| 727 | RTCLog(@"Capture session interrupted: %@", reasonString); |
| 728 | } |
| 729 |
| 730 | - (void)handleCaptureSessionInterruptionEnded:(NSNotification *)notification { |
| 731 | RTCLog(@"Capture session interruption ended."); |
| 732 | } |
| 733 |
| 734 | - (void)handleCaptureSessionRuntimeError:(NSNotification *)notification { |
| 735 | NSError *error = [notification.userInfo objectForKey:AVCaptureSessionErrorKey]; |
| 736 | RTCLogError(@"Capture session runtime error: %@", error); |
| 737 |
| 738 | [RTCDispatcher dispatchAsyncOnType:RTCDispatcherTypeCaptureSession |
| 739 | block:^{ |
| 740 | if (error.code == AVErrorMediaServicesWereReset) { |
| 741 | [self handleNonFatalError]; |
| 742 | } else { |
| 743 | [self handleFatalError]; |
| 744 | } |
| 745 | }]; |
| 746 | } |
| 747 |
| 748 | - (void)handleCaptureSessionDidStartRunning:(NSNotification *)notification { |
| 749 | RTCLog(@"Capture session started."); |
| 750 |
| 751 | [RTCDispatcher dispatchAsyncOnType:RTCDispatcherTypeCaptureSession |
| 752 | block:^{ |
| 753 | // If we successfully restarted after an unknown error, |
| 754 | // allow future retries on fatal errors. |
| 755 | _hasRetriedOnFatalError = NO; |
| 756 | }]; |
| 757 |
| 758 | _inForegroundValue = true; |
| 759 | [self updateIsActiveValue]; |
| 760 | } |
| 761 |
| 762 | - (void)handleCaptureSessionDidStopRunning:(NSNotification *)notification { |
| 763 | RTCLog(@"Capture session stopped."); |
| 764 | _inForegroundValue = false; |
| 765 | [self updateIsActiveValue]; |
| 766 | } |
| 767 |
| 768 | - (void)updateIsActiveValue { |
| 769 | bool isActive = _inForegroundValue && !_isPaused; |
| 770 | if (isActive != _isActiveValue) { |
| 771 | _isActiveValue = isActive; |
| 772 | if (_isActiveUpdated) { |
| 773 | _isActiveUpdated(_isActiveValue); |
| 774 | } |
| 775 | } |
| 776 | } |
| 777 |
| 778 | - (void)handleFatalError { |
| 779 | [RTCDispatcher |
| 780 | dispatchAsyncOnType:RTCDispatcherTypeCaptureSession |
| 781 | block:^{ |
| 782 | if (!_hasRetriedOnFatalError) { |
| 783 | RTCLogWarning(@"Attempting to recover from fatal capture error."); |
| 784 | [self handleNonFatalError]; |
| 785 | _hasRetriedOnFatalError = YES; |
| 786 | } else { |
| 787 | RTCLogError(@"Previous fatal error recovery failed."); |
| 788 | } |
| 789 | }]; |
| 790 | } |
| 791 |
| 792 | - (void)handleNonFatalError { |
| 793 | [RTCDispatcher dispatchAsyncOnType:RTCDispatcherTypeCaptureSession |
| 794 | block:^{ |
| 795 | RTCLog(@"Restarting capture session after error."); |
| 796 | if (_isRunning) { |
| 797 | [_captureSession startRunning]; |
| 798 | } |
| 799 | }]; |
| 800 | } |
| 801 |
| 802 | #pragma mark - UIApplication notifications |
| 803 |
| 804 | - (void)handleApplicationDidBecomeActive:(NSNotification *)notification { |
| 805 | [RTCDispatcher dispatchAsyncOnType:RTCDispatcherTypeCaptureSession |
| 806 | block:^{ |
| 807 | if (_isRunning && !_captureSession.isRunning) { |
| 808 | RTCLog(@"Restarting capture session on active."); |
| 809 | _warmupFrameCount = 0; |
| 810 | [_captureSession startRunning]; |
| 811 | } |
| 812 | }]; |
| 813 | } |
| 814 |
| 815 | - (void)handleApplicationWillEnterForeground:(NSNotification *)notification { |
| 816 | [RTCDispatcher dispatchAsyncOnType:RTCDispatcherTypeCaptureSession |
| 817 | block:^{ |
| 818 | RTCLog(@"Resetting warmup due to backgrounding."); |
| 819 | _warmupFrameCount = 0; |
| 820 | }]; |
| 821 | } |
| 822 |
| 823 | #pragma mark - Private |
| 824 |
| 825 | - (dispatch_queue_t)frameQueue { |
| 826 | if (!_frameQueue) { |
| 827 | _frameQueue = |
| 828 | dispatch_queue_create("org.webrtc.cameravideocapturer.video", DISPATCH_QUEUE_SERIAL); |
| 829 | dispatch_set_target_queue(_frameQueue, |
| 830 | dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)); |
| 831 | } |
| 832 | return _frameQueue; |
| 833 | } |
| 834 |
| 835 | - (BOOL)setupCaptureSession:(AVCaptureSession *)captureSession { |
| 836 | NSAssert(_captureSession == nil, @"Setup capture session called twice."); |
| 837 | _captureSession = captureSession; |
| 838 | _captureSession.sessionPreset = AVCaptureSessionPresetInputPriority; |
| 839 | _captureSession.usesApplicationAudioSession = true; |
| 840 | if (@available(iOS 16.0, *)) { |
| 841 | if (_captureSession.isMultitaskingCameraAccessSupported) { |
| 842 | _captureSession.multitaskingCameraAccessEnabled = true; |
| 843 | } |
| 844 | } |
| 845 | [self setupVideoDataOutput]; |
| 846 | // Add the output. |
| 847 | if (![_captureSession canAddOutput:_videoDataOutput]) { |
| 848 | RTCLogError(@"Video data output unsupported."); |
| 849 | return NO; |
| 850 | } |
| 851 | [_captureSession addOutput:_videoDataOutput]; |
| 852 |
| 853 | return YES; |
| 854 | } |
| 855 |
| 856 | - (void)setupVideoDataOutput { |
| 857 | NSAssert(_videoDataOutput == nil, @"Setup video data output called twice."); |
| 858 | AVCaptureVideoDataOutput *videoDataOutput = [[AVCaptureVideoDataOutput alloc] init]; |
| 859 |
| 860 | // `videoDataOutput.availableVideoCVPixelFormatTypes` returns the pixel formats supported by the |
| 861 | // device with the most efficient output format first. Find the first format that we support. |
| 862 | NSSet<NSNumber *> *supportedPixelFormats = [TGRTCCVPixelBuffer supportedPixelFormats]; |
| 863 | NSMutableOrderedSet *availablePixelFormats = |
| 864 | [NSMutableOrderedSet orderedSetWithArray:videoDataOutput.availableVideoCVPixelFormatTypes]; |
| 865 | [availablePixelFormats intersectSet:supportedPixelFormats]; |
| 866 | NSNumber *pixelFormat = availablePixelFormats.firstObject; |
| 867 | NSAssert(pixelFormat, @"Output device has no supported formats."); |
| 868 |
| 869 | _preferredOutputPixelFormat = [pixelFormat unsignedIntValue]; |
| 870 | _outputPixelFormat = _preferredOutputPixelFormat; |
| 871 | videoDataOutput.videoSettings = @{(NSString *)kCVPixelBufferPixelFormatTypeKey : pixelFormat}; |
| 872 | videoDataOutput.alwaysDiscardsLateVideoFrames = NO; |
| 873 | [videoDataOutput setSampleBufferDelegate:self queue:self.frameQueue]; |
| 874 | _videoDataOutput = videoDataOutput; |
| 875 | } |
| 876 |
| 877 | - (void)updateVideoDataOutputPixelFormat:(AVCaptureDeviceFormat *)format { |
| 878 | FourCharCode mediaSubType = CMFormatDescriptionGetMediaSubType(format.formatDescription); |
| 879 | if (![[TGRTCCVPixelBuffer supportedPixelFormats] containsObject:@(mediaSubType)]) { |
| 880 | mediaSubType = _preferredOutputPixelFormat; |
| 881 | } |
| 882 |
| 883 | if (mediaSubType != _outputPixelFormat) { |
| 884 | _outputPixelFormat = mediaSubType; |
| 885 | _videoDataOutput.videoSettings = |
| 886 | @{ (NSString *)kCVPixelBufferPixelFormatTypeKey : @(mediaSubType) }; |
| 887 | } |
| 888 | } |
| 889 |
| 890 | #pragma mark - Private, called inside capture queue |
| 891 |
| 892 | - (void)updateDeviceCaptureFormat:(AVCaptureDeviceFormat *)format fps:(NSInteger)fps { |
| 893 | NSAssert([RTCDispatcher isOnQueueForType:RTCDispatcherTypeCaptureSession], |
| 894 | @"updateDeviceCaptureFormat must be called on the capture queue."); |
| 895 | @try { |
| 896 | _currentDevice.activeFormat = format; |
| 897 | _currentDevice.activeVideoMinFrameDuration = CMTimeMake(1, (int32_t)fps); |
| 898 | } @catch (NSException *exception) { |
| 899 | RTCLogError(@"Failed to set active format!\n User info:%@", exception.userInfo); |
| 900 | return; |
| 901 | } |
| 902 | } |
| 903 |
| 904 | - (void)reconfigureCaptureSessionInput { |
| 905 | NSAssert([RTCDispatcher isOnQueueForType:RTCDispatcherTypeCaptureSession], |
| 906 | @"reconfigureCaptureSessionInput must be called on the capture queue."); |
| 907 | NSError *error = nil; |
| 908 | AVCaptureDeviceInput *input = |
| 909 | [AVCaptureDeviceInput deviceInputWithDevice:_currentDevice error:&error]; |
| 910 | if (!input) { |
| 911 | RTCLogError(@"Failed to create front camera input: %@", error.localizedDescription); |
| 912 | return; |
| 913 | } |
| 914 | [_captureSession beginConfiguration]; |
| 915 | for (AVCaptureDeviceInput *oldInput in [_captureSession.inputs copy]) { |
| 916 | [_captureSession removeInput:oldInput]; |
| 917 | } |
| 918 | if ([_captureSession canAddInput:input]) { |
| 919 | [_captureSession addInput:input]; |
| 920 | } else { |
| 921 | RTCLogError(@"Cannot add camera as an input to the session."); |
| 922 | } |
| 923 | [_captureSession commitConfiguration]; |
| 924 | } |
| 925 |
| 926 | - (void)updateOrientation { |
| 927 | NSAssert([RTCDispatcher isOnQueueForType:RTCDispatcherTypeCaptureSession], |
| 928 | @"updateOrientation must be called on the capture queue."); |
| 929 | if (_didReceiveOrientationUpdate) { |
| 930 | _orientation = [UIDevice currentDevice].orientation; |
| 931 | } |
| 932 | } |
| 933 |
| 934 | @end |
| 935 | // |
| 936 |