| 7 |
| #import "base/RTCVideoFrameBuffer.h" |
| 8 | #import "components/video_frame_buffer/RTCCVPixelBuffer.h" |
| 9 | #import "sdk/objc/native/src/objc_video_track_source.h" |
| 10 | #import "sdk/objc/native/src/objc_frame_buffer.h" |
| 11 | #import <CoreMediaIO/CMIOHardware.h> |
| 12 | #import "TGCMIODevice.h" |
| 13 | #import "helpers/AVCaptureSession+DevicePosition.h" |
| 14 | #import "helpers/RTCDispatcher+Private.h" |
| 15 | #import "base/RTCVideoFrame.h" |
| 16 |
| 17 | #include "common_video/libyuv/include/webrtc_libyuv.h" |
| 18 | #include "rtc_base/checks.h" |
| 19 | #include "rtc_base/logging.h" |
| 20 | #include "pc/video_track_source_proxy.h" |
| 21 | #include "third_party/libyuv/include/libyuv.h" |
| 22 | #include "DarwinVideoSource.h" |
| 23 |
| 24 | struct CameraFrameSize { |
| 25 | int width = 0; |
| 26 | int height = 0; |
| 27 | }; |
| 28 |
| 29 | CameraFrameSize AspectFitted(CameraFrameSize from, CameraFrameSize to) { |
| 30 | double scale = std::min( |
| 31 | from.width / std::max(1., double(to.width)), |
| 32 | from.height / std::max(1., double(to.height))); |
| 33 | return { |
| 34 | int(std::ceil(to.width * scale)), |
| 35 | int(std::ceil(to.height * scale)) |
| 36 | }; |
| 37 | } |
| 38 |
| 39 | static const int64_t kNanosecondsPerSecond = 1000000000; |
| 40 |
| 41 | static tgcalls::DarwinVideoTrackSource *getObjCVideoSource(const rtc::scoped_refptr<webrtc::VideoTrackSourceInterface> nativeSource) { |
| 42 | webrtc::VideoTrackSourceProxy *proxy_source = |
| 43 | static_cast<webrtc::VideoTrackSourceProxy *>(nativeSource.get()); |
| 44 | return static_cast<tgcalls::DarwinVideoTrackSource *>(proxy_source->internal()); |
| 45 | } |
| 46 |
| 47 |
| 48 | @interface RTCCVPixelBuffer (CustomCropping) |
| 49 |
| 50 | @end |
| 51 |
| 52 | @implementation RTCCVPixelBuffer (CustomCropping) |
| 53 |
| 54 | - (BOOL)custom_cropAndScaleTo:(CVPixelBufferRef)outputPixelBuffer |
| 55 | withTempBuffer:(nullable uint8_t*)tmpBuffer { |
| 56 | const OSType srcPixelFormat = CVPixelBufferGetPixelFormatType(self.pixelBuffer); |
| 57 | const OSType dstPixelFormat = CVPixelBufferGetPixelFormatType(outputPixelBuffer); |
| 58 |
| 59 | switch (srcPixelFormat) { |
| 60 | case kCVPixelFormatType_420YpCbCr8BiPlanarFullRange: |
| 61 | case kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange: { |
| 62 | size_t dstWidth = CVPixelBufferGetWidth(outputPixelBuffer); |
| 63 | size_t dstHeight = CVPixelBufferGetHeight(outputPixelBuffer); |
| 64 | if (dstWidth > 0 && dstHeight > 0) { |
| 65 | RTC_DCHECK(dstPixelFormat == kCVPixelFormatType_420YpCbCr8BiPlanarFullRange || |
| 66 | dstPixelFormat == kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange); |
| 67 | if ([self requiresScalingToWidth:(int)dstWidth height:(int)dstHeight]) { |
| 68 | RTC_DCHECK(tmpBuffer); |
| 69 | } |
| 70 | [self custom_cropAndScaleNV12To:outputPixelBuffer withTempBuffer:tmpBuffer]; |
| 71 | } |
| 72 | break; |
| 73 | } |
| 74 | case kCVPixelFormatType_32BGRA: |
| 75 | case kCVPixelFormatType_32ARGB: { |
| 76 | RTC_DCHECK(srcPixelFormat == dstPixelFormat); |
| 77 | [self custom_cropAndScaleARGBTo:outputPixelBuffer]; |
| 78 | break; |
| 79 | } |
| 80 | default: { RTC_DCHECK_NOTREACHED() << "Unsupported pixel format."; } |
| 81 | } |
| 82 |
| 83 | return YES; |
| 84 | } |
| 85 |
| 86 | - (void)custom_cropAndScaleNV12To:(CVPixelBufferRef)outputPixelBuffer withTempBuffer:(uint8_t*)tmpBuffer { |
| 87 | // Prepare output pointers. |
| 88 | CVReturn cvRet = CVPixelBufferLockBaseAddress(outputPixelBuffer, 0); |
| 89 | if (cvRet != kCVReturnSuccess) { |
| 90 | RTC_LOG(LS_ERROR) << "Failed to lock base address: " << cvRet; |
| 91 | } |
| 92 | const int dstWidth = (int)CVPixelBufferGetWidth(outputPixelBuffer); |
| 93 | const int dstHeight = (int)CVPixelBufferGetHeight(outputPixelBuffer); |
| 94 | uint8_t* dstY = |
| 95 | reinterpret_cast<uint8_t*>(CVPixelBufferGetBaseAddressOfPlane(outputPixelBuffer, 0)); |
| 96 | const int dstYStride = (int)CVPixelBufferGetBytesPerRowOfPlane(outputPixelBuffer, 0); |
| 97 | uint8_t* dstUV = |
| 98 | reinterpret_cast<uint8_t*>(CVPixelBufferGetBaseAddressOfPlane(outputPixelBuffer, 1)); |
| 99 | const int dstUVStride = (int)CVPixelBufferGetBytesPerRowOfPlane(outputPixelBuffer, 1); |
| 100 |
| 101 | // Prepare source pointers. |
| 102 | CVPixelBufferLockBaseAddress(self.pixelBuffer, kCVPixelBufferLock_ReadOnly); |
| 103 | const uint8_t* srcY = static_cast<uint8_t*>(CVPixelBufferGetBaseAddressOfPlane(self.pixelBuffer, 0)); |
| 104 | const int srcYStride = (int)CVPixelBufferGetBytesPerRowOfPlane(self.pixelBuffer, 0); |
| 105 | const uint8_t* srcUV = static_cast<uint8_t*>(CVPixelBufferGetBaseAddressOfPlane(self.pixelBuffer, 1)); |
| 106 | const int srcUVStride = (int)CVPixelBufferGetBytesPerRowOfPlane(self.pixelBuffer, 1); |
| 107 |
| 108 | // Crop just by modifying pointers. |
| 109 | srcY += srcYStride * self.cropY + self.cropX; |
| 110 | srcUV += srcUVStride * (self.cropY / 2) + self.cropX; |
| 111 |
| 112 | webrtc::NV12Scale(tmpBuffer, |
| 113 | srcY, |
| 114 | srcYStride, |
| 115 | srcUV, |
| 116 | srcUVStride, |
| 117 | self.cropWidth, |
| 118 | self.cropHeight, |
| 119 | dstY, |
| 120 | dstYStride, |
| 121 | dstUV, |
| 122 | dstUVStride, |
| 123 | dstWidth, |
| 124 | dstHeight); |
| 125 |
| 126 | CVPixelBufferUnlockBaseAddress(self.pixelBuffer, kCVPixelBufferLock_ReadOnly); |
| 127 | CVPixelBufferUnlockBaseAddress(outputPixelBuffer, 0); |
| 128 | } |
| 129 |
| 130 | - (void)custom_cropAndScaleARGBTo:(CVPixelBufferRef)outputPixelBuffer { |
| 131 | // Prepare output pointers. |
| 132 | CVReturn cvRet = CVPixelBufferLockBaseAddress(outputPixelBuffer, 0); |
| 133 | if (cvRet != kCVReturnSuccess) { |
| 134 | RTC_LOG(LS_ERROR) << "Failed to lock base address: " << cvRet; |
| 135 | } |
| 136 | const int dstWidth = (int)CVPixelBufferGetWidth(outputPixelBuffer); |
| 137 | const int dstHeight = (int)CVPixelBufferGetHeight(outputPixelBuffer); |
| 138 |
| 139 | uint8_t* dst = reinterpret_cast<uint8_t*>(CVPixelBufferGetBaseAddress(outputPixelBuffer)); |
| 140 | const int dstStride = (int)CVPixelBufferGetBytesPerRow(outputPixelBuffer); |
| 141 |
| 142 | // Prepare source pointers. |
| 143 | CVPixelBufferLockBaseAddress(self.pixelBuffer, kCVPixelBufferLock_ReadOnly); |
| 144 | const uint8_t* src = static_cast<uint8_t*>(CVPixelBufferGetBaseAddress(self.pixelBuffer)); |
| 145 | const int srcStride = (int)CVPixelBufferGetBytesPerRow(self.pixelBuffer); |
| 146 |
| 147 | // Crop just by modifying pointers. Need to ensure that src pointer points to a byte corresponding |
| 148 | // to the start of a new pixel (byte with B for BGRA) so that libyuv scales correctly. |
| 149 | const int bytesPerPixel = 4; |
| 150 | src += srcStride * self.cropY + (self.cropX * bytesPerPixel); |
| 151 |
| 152 | // kCVPixelFormatType_32BGRA corresponds to libyuv::FOURCC_ARGB |
| 153 | libyuv::ARGBScale(src, |
| 154 | srcStride, |
| 155 | self.cropWidth, |
| 156 | self.cropHeight, |
| 157 | dst, |
| 158 | dstStride, |
| 159 | dstWidth, |
| 160 | dstHeight, |
| 161 | libyuv::kFilterBox); |
| 162 |
| 163 | CVPixelBufferUnlockBaseAddress(self.pixelBuffer, kCVPixelBufferLock_ReadOnly); |
| 164 | CVPixelBufferUnlockBaseAddress(outputPixelBuffer, 0); |
| 165 | } |
| 166 |
| 167 | @end |
| 168 |
| 169 |
| 170 |
| 171 | @interface VideoCameraCapturer () <AVCaptureVideoDataOutputSampleBufferDelegate> { |
| 172 | rtc::scoped_refptr<webrtc::VideoTrackSourceInterface> _source; |
| 173 |
| 174 | dispatch_queue_t _frameQueue; |
| 175 | AVCaptureDevice *_currentDevice; |
| 176 | AVCaptureInput *_currentInput; |
| 177 |
| 178 | // Live on RTCDispatcherTypeCaptureSession. |
| 179 | BOOL _hasRetriedOnFatalError; |
| 180 | BOOL _hadFatalError; |
| 181 | BOOL _isRunning; |
| 182 |
| 183 | BOOL _shouldBeMirrored; |
| 184 |
| 185 | // Live on RTCDispatcherTypeCaptureSession and main thread. |
| 186 | std::atomic<bool> _willBeRunning; |
| 187 |
| 188 | AVCaptureVideoDataOutput *_videoDataOutput; |
| 189 | AVCaptureSession *_captureSession; |
| 190 |
| 191 | AVCaptureConnection *_videoConnection; |
| 192 | AVCaptureDevice *_videoDevice; |
| 193 | AVCaptureDeviceInput *_videoInputDevice; |
| 194 | FourCharCode _preferredOutputPixelFormat; |
| 195 | FourCharCode _outputPixelFormat; |
| 196 | RTCVideoRotation _rotation; |
| 197 |
| 198 | // Live on mainThread. |
| 199 | void (^_isActiveUpdated)(bool); |
| 200 | bool _isActiveValue; |
| 201 | bool _inForegroundValue; |
| 202 |
| 203 | // Live on frameQueue and main thread. |
| 204 | std::atomic<bool> _isPaused; |
| 205 | std::atomic<int> _skippedFrame; |
| 206 |
| 207 | // Live on frameQueue; |
| 208 | float _aspectRatio; |
| 209 | std::vector<uint8_t> _croppingBuffer; |
| 210 | std::shared_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> _uncroppedSink; |
| 211 | std::function<void ()> _onFatalError; |
| 212 | int _warmupFrameCount; |
| 213 | } |
| 214 |
| 215 | @end |
| 216 |
| 217 | @implementation VideoCameraCapturer |
| 218 |
| 219 | - (instancetype)initWithSource:(rtc::scoped_refptr<webrtc::VideoTrackSourceInterface>)source isActiveUpdated:(void (^)(bool))isActiveUpdated { |
| 220 | self = [super init]; |
| 221 | if (self != nil) { |
| 222 | _source = source; |
| 223 | _isActiveUpdated = [isActiveUpdated copy]; |
| 224 | _isActiveValue = true; |
| 225 | _inForegroundValue = true; |
| 226 | _isPaused = false; |
| 227 | _skippedFrame = 0; |
| 228 | _rotation = RTCVideoRotation_0; |
| 229 |
| 230 | _warmupFrameCount = 100; |
| 231 |
| 232 | if (![self setupCaptureSession:[[AVCaptureSession alloc] init]]) { |
| 233 | return nil; |
| 234 | } |
| 235 | } |
| 236 | return self; |
| 237 | } |
| 238 |
| 239 | - (void)dealloc { |
| 240 |
| 241 |
| 242 | NSAssert(!_willBeRunning, @"Session was still running in RTCCameraVideoCapturer dealloc. Forgot to call stopCapture?"); |
| 243 | [[NSNotificationCenter defaultCenter] removeObserver:self]; |
| 244 | } |
| 245 |
| 246 | + (NSArray<AVCaptureDevice *> *)captureDevices { |
| 247 | AVCaptureDevice * defaultDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; |
| 248 | NSMutableArray<AVCaptureDevice *> * devices = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] mutableCopy]; |
| 249 |
| 250 | [devices addObjectsFromArray:[AVCaptureDevice devicesWithMediaType:AVMediaTypeMuxed]]; |
| 251 |
| 252 | if ([devices count] > 0) { |
| 253 | [devices insertObject:defaultDevice atIndex:0]; |
| 254 | } |
| 255 |
| 256 | return devices; |
| 257 | } |
| 258 |
| 259 | - (BOOL)deviceIsCaptureCompitable:(AVCaptureDevice *)device { |
| 260 | if (![device isConnected] || [device isSuspended]) { |
| 261 | return NO; |
| 262 | } |
| 263 | AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil]; |
| 264 |
| 265 | return [_captureSession canAddInput:input]; |
| 266 | } |
| 267 |
| 268 | + (NSArray<AVCaptureDeviceFormat *> *)supportedFormatsForDevice:(AVCaptureDevice *)device { |
| 269 | // Support opening the device in any format. We make sure it's converted to a format we |
| 270 | // can handle, if needed, in the method `-setupVideoDataOutput`. |
| 271 | return device.formats; |
| 272 | } |
| 273 |
| 274 | - (FourCharCode)preferredOutputPixelFormat { |
| 275 | return _preferredOutputPixelFormat; |
| 276 | } |
| 277 |
| 278 | - (void)setupCaptureWithDevice:(AVCaptureDevice *)device |
| 279 | format:(AVCaptureDeviceFormat *)format |
| 280 | fps:(NSInteger)fps { |
| 281 | [self setupCaptureWithDevice:device format:format fps:fps completionHandler:nil]; |
| 282 | } |
| 283 |
| 284 | -(void)setOnFatalError:(std::function<void ()>)error { |
| 285 | if (!self->_hadFatalError) { |
| 286 | _onFatalError = std::move(error); |
| 287 | } else if (error) { |
| 288 | error(); |
| 289 | } |
| 290 | } |
| 291 |
| 292 | -(void)setOnPause:(std::function<void (bool)>)pause { |
| 293 |
| 294 | } |
| 295 |
| 296 | - (void)stop { |
| 297 | _isActiveUpdated = nil; |
| 298 | [self stopCaptureWithCompletionHandler:nil]; |
| 299 | } |
| 300 |
| 301 |
| 302 | - (void)setIsEnabled:(bool)isEnabled { |
| 303 | BOOL updated = _isPaused != !isEnabled; |
| 304 | _isPaused = !isEnabled; |
| 305 | _skippedFrame = 0; |
| 306 | if (updated) { |
| 307 | if (_isPaused) { |
| 308 | // [RTCDispatcher |
| 309 | // dispatchAsyncOnType:RTCDispatcherTypeCaptureSession |
| 310 | // block:^{ |
| 311 | [self->_captureSession stopRunning]; |
| 312 | self->_isRunning = NO; |
| 313 | // }]; |
| 314 | } else { |
| 315 | // [RTCDispatcher |
| 316 | // dispatchAsyncOnType:RTCDispatcherTypeCaptureSession |
| 317 | // block:^{ |
| 318 | [self->_captureSession startRunning]; |
| 319 | self->_isRunning = YES; |
| 320 | // }]; |
| 321 | } |
| 322 | } |
| 323 |
| 324 | [self updateIsActiveValue]; |
| 325 | } |
| 326 |
| 327 |
| 328 | - (void)setUncroppedSink:(std::shared_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>>)sink { |
| 329 | dispatch_async(self.frameQueue, ^{ |
| 330 | self->_uncroppedSink = sink; |
| 331 | }); |
| 332 | } |
| 333 |
| 334 | - (void)setPreferredCaptureAspectRatio:(float)aspectRatio { |
| 335 | dispatch_async(self.frameQueue, ^{ |
| 336 | self->_aspectRatio = aspectRatio; |
| 337 | }); |
| 338 | } |
| 339 |
| 340 | - (void)updateIsActiveValue { |
| 341 | bool isActive = _inForegroundValue && !_isPaused; |
| 342 | if (isActive != _isActiveValue) { |
| 343 | _isActiveValue = isActive; |
| 344 | if (_isActiveUpdated) { |
| 345 | _isActiveUpdated(_isActiveValue); |
| 346 | } |
| 347 | } |
| 348 | } |
| 349 |
| 350 |
| 351 | - (void)setupCaptureWithDevice:(AVCaptureDevice *)device |
| 352 | format:(AVCaptureDeviceFormat *)format |
| 353 | fps:(NSInteger)fps |
| 354 | completionHandler:(nullable void (^)(NSError *))completionHandler { |
| 355 |
| 356 |
| 357 | CMIOObjectPropertyAddress latency_pa = { |
| 358 | kCMIODevicePropertyLatency, |
| 359 | kCMIOObjectPropertyScopeWildcard, |
| 360 | kCMIOObjectPropertyElementWildcard |
| 361 | }; |
| 362 | UInt32 dataSize = 0; |
| 363 |
| 364 | NSNumber *_connectionID = ((NSNumber *)[device valueForKey:@"_connectionID"]); |
| 365 |
| 366 | CMIODeviceID deviceId = (CMIODeviceID)[_connectionID intValue]; |
| 367 |
| 368 | if (device) { |
| 369 | if (CMIOObjectGetPropertyDataSize(deviceId, &latency_pa, 0, nil, &dataSize) == noErr) { |
| 370 | _shouldBeMirrored = NO; |
| 371 | } else { |
| 372 | _shouldBeMirrored = YES; |
| 373 | } |
| 374 | } else { |
| 375 | _shouldBeMirrored = [device hasMediaType:AVMediaTypeVideo]; |
| 376 | } |
| 377 | // [RTCDispatcher |
| 378 | // dispatchAsyncOnType:RTCDispatcherTypeCaptureSession |
| 379 | // block:^{ |
| 380 | RTCLogInfo("startCaptureWithDevice %@ @ %ld fps", format, (long)fps); |
| 381 | NSError *error = nil; |
| 382 |
| 383 | self->_currentDevice = device; |
| 384 |
| 385 |
| 386 | self->_currentInput = [[AVCaptureDeviceInput alloc] initWithDevice:device error:&error]; |
| 387 | if (![self->_currentDevice lockForConfiguration:&error]) { |
| 388 | RTCLogError(@"Failed to lock device %@. Error: %@", |
| 389 | self->_currentDevice, |
| 390 | error.userInfo); |
| 391 | if (completionHandler) { |
| 392 | completionHandler(error); |
| 393 | } |
| 394 | self->_willBeRunning = false; |
| 395 | return; |
| 396 | } |
| 397 | [self updateDeviceCaptureFormat:format fps:fps]; |
| 398 | [self updateVideoDataOutputPixelFormat:format]; |
| 399 | [self->_currentDevice unlockForConfiguration]; |
| 400 | [self reconfigureCaptureSessionInput]; |
| 401 | if (completionHandler) { |
| 402 | completionHandler(nil); |
| 403 | } |
| 404 | // }]; |
| 405 | } |
| 406 |
| 407 | -(void)start { |
| 408 | _willBeRunning = true; |
| 409 | // [RTCDispatcher |
| 410 | // dispatchAsyncOnType:RTCDispatcherTypeCaptureSession |
| 411 | // block:^{ |
| 412 | [self->_captureSession startRunning]; |
| 413 | self->_isRunning = YES; |
| 414 | // }]; |
| 415 | } |
| 416 |
| 417 |
| 418 |
| 419 | - (void)stopCaptureWithCompletionHandler:(nullable void (^)(void))completionHandler { |
| 420 | _willBeRunning = false; |
| 421 | // [RTCDispatcher |
| 422 | // dispatchAsyncOnType:RTCDispatcherTypeCaptureSession |
| 423 | // block:^{ |
| 424 | RTCLogInfo("Stop"); |
| 425 | self->_currentDevice = nil; |
| 426 | for (AVCaptureDeviceInput *oldInput in [self->_captureSession.inputs copy]) { |
| 427 | [self->_captureSession removeInput:oldInput]; |
| 428 | } |
| 429 | [self->_captureSession stopRunning]; |
| 430 |
| 431 | self->_isRunning = NO; |
| 432 | if (completionHandler) { |
| 433 | completionHandler(); |
| 434 | } |
| 435 | // }]; |
| 436 | } |
| 437 |
| 438 |
| 439 | #pragma mark AVCaptureVideoDataOutputSampleBufferDelegate |
| 440 |
| 441 | - (void)captureOutput:(AVCaptureOutput *)captureOutput |
| 442 | didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer |
| 443 | fromConnection:(AVCaptureConnection *)connection { |
| 444 | NSParameterAssert(captureOutput == _videoDataOutput); |
| 445 |
| 446 | int minWarmupFrameCount = 12; |
| 447 | _warmupFrameCount++; |
| 448 | if (_warmupFrameCount < minWarmupFrameCount) { |
| 449 | return; |
| 450 | } |
| 451 |
| 452 | if (CMSampleBufferGetNumSamples(sampleBuffer) != 1 || !CMSampleBufferIsValid(sampleBuffer) || |
| 453 | !CMSampleBufferDataIsReady(sampleBuffer)) { |
| 454 | return; |
| 455 | } |
| 456 |
| 457 | CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer); |
| 458 | if (pixelBuffer == nil) { |
| 459 | return; |
| 460 | } |
| 461 |
| 462 | int width = (int)CVPixelBufferGetWidth(pixelBuffer); |
| 463 | int height = (int)CVPixelBufferGetHeight(pixelBuffer); |
| 464 |
| 465 | CameraFrameSize fittedSize = { width, height }; |
| 466 |
| 467 | fittedSize.width -= (fittedSize.width % 32); |
| 468 | fittedSize.height -= (fittedSize.height % 4); |
| 469 |
| 470 | TGRTCCVPixelBuffer *rtcPixelBuffer = [[TGRTCCVPixelBuffer alloc] initWithPixelBuffer:pixelBuffer adaptedWidth:fittedSize.width adaptedHeight:fittedSize.height cropWidth:width cropHeight:height cropX:0 cropY:0]; |
| 471 |
| 472 | rtcPixelBuffer.shouldBeMirrored = _shouldBeMirrored; |
| 473 |
| 474 | if (!_isPaused && _uncroppedSink) { |
| 475 | int64_t timeStampNs = CMTimeGetSeconds(CMSampleBufferGetPresentationTimeStamp(sampleBuffer)) * |
| 476 | kNanosecondsPerSecond; |
| 477 | RTCVideoFrame *frame = [[RTCVideoFrame alloc] initWithBuffer:rtcPixelBuffer |
| 478 | rotation:_rotation |
| 479 | timeStampNs:timeStampNs]; |
| 480 |
| 481 | const int64_t timestamp_us = frame.timeStampNs / rtc::kNumNanosecsPerMicrosec; |
| 482 |
| 483 | rtc::scoped_refptr<webrtc::VideoFrameBuffer> buffer; |
| 484 | buffer = new rtc::RefCountedObject<webrtc::ObjCFrameBuffer>(frame.buffer); |
| 485 |
| 486 | webrtc::VideoRotation rotation = static_cast<webrtc::VideoRotation>(frame.rotation); |
| 487 |
| 488 | _uncroppedSink->OnFrame(webrtc::VideoFrame::Builder() |
| 489 | .set_video_frame_buffer(buffer) |
| 490 | .set_rotation(rotation) |
| 491 | .set_timestamp_us(timestamp_us) |
| 492 | .build()); |
| 493 | } |
| 494 |
| 495 |
| 496 | int64_t timeStampNs = CMTimeGetSeconds(CMSampleBufferGetPresentationTimeStamp(sampleBuffer)) * |
| 497 | kNanosecondsPerSecond; |
| 498 | RTCVideoFrame *videoFrame = [[RTCVideoFrame alloc] initWithBuffer:rtcPixelBuffer |
| 499 | rotation:_rotation |
| 500 | timeStampNs:timeStampNs]; |
| 501 | if (!_isPaused) { |
| 502 | getObjCVideoSource(_source)->OnCapturedFrame(videoFrame); |
| 503 | } |
| 504 | _skippedFrame = MIN(_skippedFrame + 1, 16); |
| 505 | } |
| 506 |
| 507 | - (void)captureOutput:(AVCaptureOutput *)captureOutput |
| 508 | didDropSampleBuffer:(CMSampleBufferRef)sampleBuffer |
| 509 | fromConnection:(AVCaptureConnection *)connection { |
| 510 | NSString *droppedReason = |
| 511 | (__bridge NSString *)CMGetAttachment(sampleBuffer, kCMSampleBufferAttachmentKey_DroppedFrameReason, nil); |
| 512 | RTCLogError(@"Dropped sample buffer. Reason: %@", droppedReason); |
| 513 | } |
| 514 |
| 515 | #pragma mark - AVCaptureSession notifications |
| 516 |
| 517 | - (void)handleCaptureSessionInterruption:(NSNotification *)notification { |
| 518 |
| 519 | } |
| 520 |
| 521 | - (void)handleCaptureSessionInterruptionEnded:(NSNotification *)notification { |
| 522 | RTCLog(@"Capture session interruption ended."); |
| 523 | } |
| 524 |
| 525 | - (void)handleCaptureSessionRuntimeError:(NSNotification *)notification { |
| 526 | NSError *error = [notification.userInfo objectForKey:AVCaptureSessionErrorKey]; |
| 527 | RTCLogError(@"Capture session runtime error: %@", error); |
| 528 |
| 529 | // [RTCDispatcher dispatchAsyncOnType:RTCDispatcherTypeCaptureSession |
| 530 | // block:^{ |
| 531 | [self handleFatalError]; |
| 532 | // }]; |
| 533 | } |
| 534 |
| 535 | - (void)handleCaptureSessionDidStartRunning:(NSNotification *)notification { |
| 536 | RTCLog(@"Capture session started."); |
| 537 |
| 538 | // [RTCDispatcher dispatchAsyncOnType:RTCDispatcherTypeCaptureSession |
| 539 | // block:^{ |
| 540 | // If we successfully restarted after an unknown error, |
| 541 | // allow future retries on fatal errors. |
| 542 | self->_hasRetriedOnFatalError = NO; |
| 543 | self->_hadFatalError = NO; |
| 544 | // }]; |
| 545 |
| 546 |
| 547 | _inForegroundValue = true; |
| 548 | [self updateIsActiveValue]; |
| 549 | } |
| 550 |
| 551 | - (void)handleCaptureSessionDidStopRunning:(NSNotification *)notification { |
| 552 | RTCLog(@"Capture session stopped."); |
| 553 | _inForegroundValue = false; |
| 554 | [self updateIsActiveValue]; |
| 555 |
| 556 | } |
| 557 |
| 558 | - (void)handleFatalError { |
| 559 | // [RTCDispatcher |
| 560 | // dispatchAsyncOnType:RTCDispatcherTypeCaptureSession |
| 561 | // block:^{ |
| 562 | if (!self->_hasRetriedOnFatalError) { |
| 563 | RTCLogWarning(@"Attempting to recover from fatal capture error."); |
| 564 | [self handleNonFatalError]; |
| 565 | self->_warmupFrameCount = 0; |
| 566 | self->_hasRetriedOnFatalError = YES; |
| 567 | } else { |
| 568 | RTCLogError(@"Previous fatal error recovery failed."); |
| 569 | if (_onFatalError) { |
| 570 | _onFatalError(); |
| 571 | } else { |
| 572 | self->_hadFatalError = YES; |
| 573 | } |
| 574 | } |
| 575 | // }]; |
| 576 | } |
| 577 |
| 578 | - (void)handleNonFatalError { |
| 579 | // [RTCDispatcher dispatchAsyncOnType:RTCDispatcherTypeCaptureSession |
| 580 | // block:^{ |
| 581 | RTCLog(@"Restarting capture session after error."); |
| 582 | if (self->_isRunning) { |
| 583 | self->_warmupFrameCount = 0; |
| 584 | [self->_captureSession startRunning]; |
| 585 | } |
| 586 | // }]; |
| 587 | } |
| 588 |
| 589 | #pragma mark - UIApplication notifications |
| 590 |
| 591 | - (void)handleApplicationDidBecomeActive:(NSNotification *)notification { |
| 592 | // [RTCDispatcher dispatchAsyncOnType:RTCDispatcherTypeCaptureSession |
| 593 | // block:^{ |
| 594 | if (self->_isRunning && !self->_captureSession.isRunning) { |
| 595 | RTCLog(@"Restarting capture session on active."); |
| 596 | self->_warmupFrameCount = 0; |
| 597 | [self->_captureSession startRunning]; |
| 598 | } |
| 599 | // }]; |
| 600 | } |
| 601 |
| 602 | #pragma mark - Private |
| 603 |
| 604 | - (dispatch_queue_t)frameQueue { |
| 605 | if (!_frameQueue) { |
| 606 | _frameQueue = |
| 607 | dispatch_queue_create("org.webrtc.cameravideocapturer.video", DISPATCH_QUEUE_SERIAL); |
| 608 | dispatch_set_target_queue(_frameQueue, |
| 609 | dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)); |
| 610 | } |
| 611 | return _frameQueue; |
| 612 | } |
| 613 |
| 614 | - (BOOL)setupCaptureSession:(AVCaptureSession *)captureSession { |
| 615 | NSAssert(_captureSession == nil, @"Setup capture session called twice."); |
| 616 | _captureSession = captureSession; |
| 617 |
| 618 | [self setupVideoDataOutput]; |
| 619 | // Add the output. |
| 620 | if (![_captureSession canAddOutput:_videoDataOutput]) { |
| 621 | RTCLogError(@"Video data output unsupported."); |
| 622 | return NO; |
| 623 | } |
| 624 | [_captureSession addOutput:_videoDataOutput]; |
| 625 |
| 626 |
| 627 | return YES; |
| 628 | } |
| 629 |
| 630 |
| 631 |
| 632 | - (void)setupVideoDataOutput { |
| 633 | NSAssert(_videoDataOutput == nil, @"Setup video data output called twice."); |
| 634 | AVCaptureVideoDataOutput *videoDataOutput = [[AVCaptureVideoDataOutput alloc] init]; |
| 635 |
| 636 | // `videoDataOutput.availableVideoCVPixelFormatTypes` returns the pixel formats supported by the |
| 637 | // device with the most efficient output format first. Find the first format that we support. |
| 638 | NSSet<NSNumber *> *supportedPixelFormats = [RTCCVPixelBuffer supportedPixelFormats]; |
| 639 | NSMutableOrderedSet *availablePixelFormats = |
| 640 | [NSMutableOrderedSet orderedSetWithArray:videoDataOutput.availableVideoCVPixelFormatTypes]; |
| 641 | [availablePixelFormats intersectSet:supportedPixelFormats]; |
| 642 | NSNumber *pixelFormat = availablePixelFormats.firstObject; |
| 643 | NSAssert(pixelFormat, @"Output device has no supported formats."); |
| 644 |
| 645 | _preferredOutputPixelFormat = [pixelFormat unsignedIntValue]; |
| 646 | _outputPixelFormat = _preferredOutputPixelFormat; |
| 647 | videoDataOutput.videoSettings = @{(NSString *)kCVPixelBufferPixelFormatTypeKey : pixelFormat}; |
| 648 | videoDataOutput.alwaysDiscardsLateVideoFrames = YES; |
| 649 |
| 650 | [videoDataOutput setSampleBufferDelegate:self queue:self.frameQueue]; |
| 651 | _videoDataOutput = videoDataOutput; |
| 652 | } |
| 653 |
| 654 | - (void)updateVideoDataOutputPixelFormat:(AVCaptureDeviceFormat *)format { |
| 655 | FourCharCode mediaSubType = CMFormatDescriptionGetMediaSubType(format.formatDescription); |
| 656 | if (![[RTCCVPixelBuffer supportedPixelFormats] containsObject:@(mediaSubType)]) { |
| 657 | mediaSubType = _preferredOutputPixelFormat; |
| 658 | } |
| 659 | CMVideoDimensions dimensions = CMVideoFormatDescriptionGetDimensions(format.formatDescription); |
| 660 |
| 661 | if (mediaSubType != _outputPixelFormat) { |
| 662 | _outputPixelFormat = mediaSubType; |
| 663 | _videoDataOutput.videoSettings = |
| 664 | @{ (NSString *)kCVPixelBufferPixelFormatTypeKey : @(mediaSubType) }; |
| 665 | } else { |
| 666 | // _videoDataOutput.videoSettings = |
| 667 | // @{ (NSString *)kCVPixelBufferWidthKey: @(dimensions.width), (NSString *)kCVPixelBufferHeightKey: @(dimensions.height) }; |
| 668 | } |
| 669 | AVCaptureConnection *connection = [_videoDataOutput connectionWithMediaType:AVMediaTypeVideo]; |
| 670 |
| 671 | } |
| 672 |
| 673 | #pragma mark - Private, called inside capture queue |
| 674 |
| 675 | - (void)updateDeviceCaptureFormat:(AVCaptureDeviceFormat *)format fps:(NSInteger)fps { |
| 676 | // NSAssert([RTCDispatcher isOnQueueForType:RTCDispatcherTypeCaptureSession], |
| 677 | // @"updateDeviceCaptureFormat must be called on the capture queue."); |
| 678 | @try { |
| 679 | _currentDevice.activeFormat = format; |
| 680 | if (format.videoSupportedFrameRateRanges.count > 0) { |
| 681 | int target = 24; |
| 682 | int closest = -1; |
| 683 | CMTime result; |
| 684 | for (int i = 0; i < format.videoSupportedFrameRateRanges.count; i++) { |
| 685 | const auto rateRange = format.videoSupportedFrameRateRanges[i]; |
| 686 | int gap = abs(rateRange.minFrameRate - target); |
| 687 | if (gap <= closest || closest == -1) { |
| 688 | closest = gap; |
| 689 | result = rateRange.maxFrameDuration; |
| 690 | } |
| 691 | } |
| 692 | if (closest >= 0) { |
| 693 | _currentDevice.activeVideoMaxFrameDuration = result; |
| 694 | } |
| 695 | } |
| 696 | } @catch (NSException *exception) { |
| 697 | RTCLogError(@"Failed to set active format!\n User info:%@", exception.userInfo); |
| 698 | return; |
| 699 | } |
| 700 | } |
| 701 |
| 702 | - (void)reconfigureCaptureSessionInput { |
| 703 | // NSAssert([RTCDispatcher isOnQueueForType:RTCDispatcherTypeCaptureSession], |
| 704 | // @"reconfigureCaptureSessionInput must be called on the capture queue."); |
| 705 | NSError *error = nil; |
| 706 | AVCaptureInput *input = _currentInput; |
| 707 | if (!input) { |
| 708 | RTCLogError(@"Failed to create front camera input: %@", error.localizedDescription); |
| 709 | return; |
| 710 | } |
| 711 | [_captureSession beginConfiguration]; |
| 712 | for (AVCaptureInput *oldInput in [_captureSession.inputs copy]) { |
| 713 | [_captureSession removeInput:oldInput]; |
| 714 | } |
| 715 | if ([_captureSession canAddInput:input]) { |
| 716 | [_captureSession addInput:input]; |
| 717 | } else { |
| 718 | RTCLogError(@"Cannot add camera as an input to the session."); |
| 719 | } |
| 720 | [_captureSession commitConfiguration]; |
| 721 | } |
| 722 |
| 723 |
| 724 | @end |
| 725 |
| 726 |