| 7 | * in the file PATENTS. All contributing project authors may |
| 8 | * be found in the AUTHORS file in the root of the source tree. |
| 9 | * |
| 10 | */ |
| 11 |
| 12 | #import "TGRTCVideoEncoderH265.h" |
| 13 |
| 14 | #import <VideoToolbox/VideoToolbox.h> |
| 15 | #include <vector> |
| 16 |
| 17 | #import "RTCCodecSpecificInfoH265.h" |
| 18 | #import "api/peerconnection/RTCRtpFragmentationHeader+Private.h" |
| 19 | #import "api/peerconnection/RTCVideoCodecInfo+Private.h" |
| 20 | #import "base/RTCI420Buffer.h" |
| 21 | #import "base/RTCVideoFrame.h" |
| 22 | #import "base/RTCVideoFrameBuffer.h" |
| 23 | #import "components/video_frame_buffer/RTCCVPixelBuffer.h" |
| 24 | #import "helpers.h" |
| 25 |
| 26 | #if defined(WEBRTC_IOS) |
| 27 | #import "helpers/UIDevice+RTCDevice.h" |
| 28 | #endif |
| 29 |
| 30 | #include "common_video/h264/profile_level_id.h" |
| 31 | #include "common_video/h265/h265_bitstream_parser.h" |
| 32 | #include "common_video/include/bitrate_adjuster.h" |
| 33 | #include "libyuv/convert_from.h" |
| 34 | #include "modules/include/module_common_types.h" |
| 35 | #include "modules/video_coding/include/video_error_codes.h" |
| 36 | #include "rtc_base/buffer.h" |
| 37 | #include "rtc_base/logging.h" |
| 38 | #include "rtc_base/time_utils.h" |
| 39 | #include "sdk/objc/Framework/Classes/VideoToolbox/nalu_rewriter.h" |
| 40 | #include "system_wrappers/include/clock.h" |
| 41 |
| 42 | @interface TGRTCVideoEncoderH265 () |
| 43 |
| 44 | - (void)frameWasEncoded:(OSStatus)status |
| 45 | flags:(VTEncodeInfoFlags)infoFlags |
| 46 | sampleBuffer:(CMSampleBufferRef)sampleBuffer |
| 47 | width:(int32_t)width |
| 48 | height:(int32_t)height |
| 49 | renderTimeMs:(int64_t)renderTimeMs |
| 50 | timestamp:(uint32_t)timestamp |
| 51 | rotation:(RTCVideoRotation)rotation; |
| 52 |
| 53 | @end |
| 54 |
| 55 | namespace { // anonymous namespace |
| 56 |
| 57 | // The ratio between kVTCompressionPropertyKey_DataRateLimits and |
| 58 | // kVTCompressionPropertyKey_AverageBitRate. The data rate limit is set higher |
| 59 | // than the average bit rate to avoid undershooting the target. |
| 60 | const float kLimitToAverageBitRateFactor = 1.5f; |
| 61 | // These thresholds deviate from the default h265 QP thresholds, as they |
| 62 | // have been found to work better on devices that support VideoToolbox |
| 63 | const int kLowh265QpThreshold = 28; |
| 64 | const int kHighh265QpThreshold = 39; |
| 65 |
| 66 | // Struct that we pass to the encoder per frame to encode. We receive it again |
| 67 | // in the encoder callback. |
| 68 | struct API_AVAILABLE(ios(11.0)) RTCFrameEncodeParams { |
| 69 | RTCFrameEncodeParams(TGRTCVideoEncoderH265* e, |
| 70 | int32_t w, |
| 71 | int32_t h, |
| 72 | int64_t rtms, |
| 73 | uint32_t ts, |
| 74 | RTCVideoRotation r) |
| 75 | : encoder(e), |
| 76 | width(w), |
| 77 | height(h), |
| 78 | render_time_ms(rtms), |
| 79 | timestamp(ts), |
| 80 | rotation(r) {} |
| 81 |
| 82 | TGRTCVideoEncoderH265* encoder; |
| 83 | int32_t width; |
| 84 | int32_t height; |
| 85 | int64_t render_time_ms; |
| 86 | uint32_t timestamp; |
| 87 | RTCVideoRotation rotation; |
| 88 | }; |
| 89 |
| 90 | // We receive I420Frames as input, but we need to feed CVPixelBuffers into the |
| 91 | // encoder. This performs the copy and format conversion. |
| 92 | // TODO(tkchin): See if encoder will accept i420 frames and compare performance. |
| 93 | bool CopyVideoFrameToPixelBuffer(id<RTCI420Buffer> frameBuffer, |
| 94 | CVPixelBufferRef pixelBuffer) { |
| 95 | RTC_DCHECK(pixelBuffer); |
| 96 | RTC_DCHECK_EQ(CVPixelBufferGetPixelFormatType(pixelBuffer), |
| 97 | kCVPixelFormatType_420YpCbCr8BiPlanarFullRange); |
| 98 | RTC_DCHECK_EQ(CVPixelBufferGetHeightOfPlane(pixelBuffer, 0), |
| 99 | frameBuffer.height); |
| 100 | RTC_DCHECK_EQ(CVPixelBufferGetWidthOfPlane(pixelBuffer, 0), |
| 101 | frameBuffer.width); |
| 102 |
| 103 | CVReturn cvRet = CVPixelBufferLockBaseAddress(pixelBuffer, 0); |
| 104 | if (cvRet != kCVReturnSuccess) { |
| 105 | RTC_LOG(LS_ERROR) << "Failed to lock base address: " << cvRet; |
| 106 | return false; |
| 107 | } |
| 108 |
| 109 | uint8_t* dstY = reinterpret_cast<uint8_t*>( |
| 110 | CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 0)); |
| 111 | int dstStrideY = (int)CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer, 0); |
| 112 | uint8_t* dstUV = reinterpret_cast<uint8_t*>( |
| 113 | CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 1)); |
| 114 | int dstStrideUV = (int)CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer, 1); |
| 115 | // Convert I420 to NV12. |
| 116 | int ret = libyuv::I420ToNV12( |
| 117 | frameBuffer.dataY, frameBuffer.strideY, frameBuffer.dataU, |
| 118 | frameBuffer.strideU, frameBuffer.dataV, frameBuffer.strideV, dstY, |
| 119 | dstStrideY, dstUV, dstStrideUV, frameBuffer.width, frameBuffer.height); |
| 120 | CVPixelBufferUnlockBaseAddress(pixelBuffer, 0); |
| 121 | if (ret) { |
| 122 | RTC_LOG(LS_ERROR) << "Error converting I420 VideoFrame to NV12 :" << ret; |
| 123 | return false; |
| 124 | } |
| 125 | return true; |
| 126 | } |
| 127 |
| 128 | CVPixelBufferRef CreatePixelBuffer(CVPixelBufferPoolRef pixel_buffer_pool) { |
| 129 | if (!pixel_buffer_pool) { |
| 130 | RTC_LOG(LS_ERROR) << "Failed to get pixel buffer pool."; |
| 131 | return nullptr; |
| 132 | } |
| 133 | CVPixelBufferRef pixel_buffer; |
| 134 | CVReturn ret = CVPixelBufferPoolCreatePixelBuffer(nullptr, pixel_buffer_pool, |
| 135 | &pixel_buffer); |
| 136 | if (ret != kCVReturnSuccess) { |
| 137 | RTC_LOG(LS_ERROR) << "Failed to create pixel buffer: " << ret; |
| 138 | // We probably want to drop frames here, since failure probably means |
| 139 | // that the pool is empty. |
| 140 | return nullptr; |
| 141 | } |
| 142 | return pixel_buffer; |
| 143 | } |
| 144 |
| 145 | // This is the callback function that VideoToolbox calls when encode is |
| 146 | // complete. From inspection this happens on its own queue. |
| 147 | void compressionOutputCallback(void* encoder, |
| 148 | void* params, |
| 149 | OSStatus status, |
| 150 | VTEncodeInfoFlags infoFlags, |
| 151 | CMSampleBufferRef sampleBuffer) |
| 152 | API_AVAILABLE(ios(11.0)) { |
| 153 | RTC_CHECK(params); |
| 154 | std::unique_ptr<RTCFrameEncodeParams> encodeParams( |
| 155 | reinterpret_cast<RTCFrameEncodeParams*>(params)); |
| 156 | RTC_CHECK(encodeParams->encoder); |
| 157 | [encodeParams->encoder frameWasEncoded:status |
| 158 | flags:infoFlags |
| 159 | sampleBuffer:sampleBuffer |
| 160 | width:encodeParams->width |
| 161 | height:encodeParams->height |
| 162 | renderTimeMs:encodeParams->render_time_ms |
| 163 | timestamp:encodeParams->timestamp |
| 164 | rotation:encodeParams->rotation]; |
| 165 | } |
| 166 | } // namespace |
| 167 |
| 168 | @implementation TGRTCVideoEncoderH265 { |
| 169 | RTCVideoCodecInfo* _codecInfo; |
| 170 | std::unique_ptr<webrtc::BitrateAdjuster> _bitrateAdjuster; |
| 171 | uint32_t _targetBitrateBps; |
| 172 | uint32_t _encoderBitrateBps; |
| 173 | CFStringRef _profile; |
| 174 | RTCVideoEncoderCallback _callback; |
| 175 | int32_t _width; |
| 176 | int32_t _height; |
| 177 | VTCompressionSessionRef _compressionSession; |
| 178 | RTCVideoCodecMode _mode; |
| 179 | int framesLeft; |
| 180 |
| 181 | webrtc::H265BitstreamParser _h265BitstreamParser; |
| 182 | std::vector<uint8_t> _nv12ScaleBuffer; |
| 183 | } |
| 184 |
| 185 | // .5 is set as a mininum to prevent overcompensating for large temporary |
| 186 | // overshoots. We don't want to degrade video quality too badly. |
| 187 | // .95 is set to prevent oscillations. When a lower bitrate is set on the |
| 188 | // encoder than previously set, its output seems to have a brief period of |
| 189 | // drastically reduced bitrate, so we want to avoid that. In steady state |
| 190 | // conditions, 0.95 seems to give us better overall bitrate over long periods |
| 191 | // of time. |
| 192 | - (instancetype)initWithCodecInfo:(RTCVideoCodecInfo*)codecInfo { |
| 193 | if (self = [super init]) { |
| 194 | _codecInfo = codecInfo; |
| 195 | _bitrateAdjuster.reset(new webrtc::BitrateAdjuster(.5, .95)); |
| 196 | RTC_CHECK([codecInfo.name isEqualToString:@"H265"]); |
| 197 | } |
| 198 | return self; |
| 199 | } |
| 200 |
| 201 | - (void)dealloc { |
| 202 | [self destroyCompressionSession]; |
| 203 | } |
| 204 |
| 205 | - (NSInteger)startEncodeWithSettings:(RTCVideoEncoderSettings*)settings |
| 206 | numberOfCores:(int)numberOfCores { |
| 207 | RTC_DCHECK(settings); |
| 208 | RTC_DCHECK([settings.name isEqualToString:@"H265"]); |
| 209 |
| 210 | _width = settings.width; |
| 211 | _height = settings.height; |
| 212 | _mode = settings.mode; |
| 213 |
| 214 | // We can only set average bitrate on the HW encoder. |
| 215 | _targetBitrateBps = settings.startBitrate; |
| 216 | _bitrateAdjuster->SetTargetBitrateBps(_targetBitrateBps); |
| 217 |
| 218 | // TODO(tkchin): Try setting payload size via |
| 219 | // kVTCompressionPropertyKey_Maxh265SliceBytes. |
| 220 |
| 221 | return [self resetCompressionSession]; |
| 222 | } |
| 223 |
| 224 | - (NSInteger)encode:(RTCVideoFrame*)frame |
| 225 | codecSpecificInfo:(id<RTCCodecSpecificInfo>)codecSpecificInfo |
| 226 | frameTypes:(NSArray<NSNumber*>*)frameTypes { |
| 227 | RTC_DCHECK_EQ(frame.width, _width); |
| 228 | RTC_DCHECK_EQ(frame.height, _height); |
| 229 | if (!_callback || !_compressionSession) { |
| 230 | return WEBRTC_VIDEO_CODEC_UNINITIALIZED; |
| 231 | } |
| 232 | BOOL isKeyframeRequired = NO; |
| 233 |
| 234 | // Get a pixel buffer from the pool and copy frame data over. |
| 235 | CVPixelBufferPoolRef pixelBufferPool = |
| 236 | VTCompressionSessionGetPixelBufferPool(_compressionSession); |
| 237 |
| 238 | #if defined(WEBRTC_IOS) |
| 239 | if (!pixelBufferPool) { |
| 240 | // Kind of a hack. On backgrounding, the compression session seems to get |
| 241 | // invalidated, which causes this pool call to fail when the application |
| 242 | // is foregrounded and frames are being sent for encoding again. |
| 243 | // Resetting the session when this happens fixes the issue. |
| 244 | // In addition we request a keyframe so video can recover quickly. |
| 245 | [self resetCompressionSession]; |
| 246 | pixelBufferPool = |
| 247 | VTCompressionSessionGetPixelBufferPool(_compressionSession); |
| 248 | isKeyframeRequired = YES; |
| 249 | RTC_LOG(LS_INFO) << "Resetting compression session due to invalid pool."; |
| 250 | } |
| 251 | #endif |
| 252 |
| 253 | CVPixelBufferRef pixelBuffer = nullptr; |
| 254 | if ([frame.buffer isKindOfClass:[RTCCVPixelBuffer class]]) { |
| 255 | // Native frame buffer |
| 256 | RTCCVPixelBuffer* rtcPixelBuffer = (RTCCVPixelBuffer*)frame.buffer; |
| 257 | if (![rtcPixelBuffer requiresCropping]) { |
| 258 | // This pixel buffer might have a higher resolution than what the |
| 259 | // compression session is configured to. The compression session can |
| 260 | // handle that and will output encoded frames in the configured |
| 261 | // resolution regardless of the input pixel buffer resolution. |
| 262 | pixelBuffer = rtcPixelBuffer.pixelBuffer; |
| 263 | CVBufferRetain(pixelBuffer); |
| 264 | } else { |
| 265 | // Cropping required, we need to crop and scale to a new pixel buffer. |
| 266 | pixelBuffer = CreatePixelBuffer(pixelBufferPool); |
| 267 | if (!pixelBuffer) { |
| 268 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 269 | } |
| 270 | int dstWidth = (int)CVPixelBufferGetWidth(pixelBuffer); |
| 271 | int dstHeight = (int)CVPixelBufferGetHeight(pixelBuffer); |
| 272 | if ([rtcPixelBuffer requiresScalingToWidth:dstWidth height:dstHeight]) { |
| 273 | int size = |
| 274 | [rtcPixelBuffer bufferSizeForCroppingAndScalingToWidth:dstWidth |
| 275 | height:dstHeight]; |
| 276 | _nv12ScaleBuffer.resize(size); |
| 277 | } else { |
| 278 | _nv12ScaleBuffer.clear(); |
| 279 | } |
| 280 | _nv12ScaleBuffer.shrink_to_fit(); |
| 281 | if (![rtcPixelBuffer cropAndScaleTo:pixelBuffer |
| 282 | withTempBuffer:_nv12ScaleBuffer.data()]) { |
| 283 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 284 | } |
| 285 | } |
| 286 | } |
| 287 |
| 288 | if (!pixelBuffer) { |
| 289 | // We did not have a native frame buffer |
| 290 | pixelBuffer = CreatePixelBuffer(pixelBufferPool); |
| 291 | if (!pixelBuffer) { |
| 292 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 293 | } |
| 294 | RTC_DCHECK(pixelBuffer); |
| 295 | if (!CopyVideoFrameToPixelBuffer([frame.buffer toI420], pixelBuffer)) { |
| 296 | RTC_LOG(LS_ERROR) << "Failed to copy frame data."; |
| 297 | CVBufferRelease(pixelBuffer); |
| 298 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 299 | } |
| 300 | } |
| 301 |
| 302 | // Check if we need a keyframe. |
| 303 | if (!isKeyframeRequired && frameTypes) { |
| 304 | for (NSNumber* frameType in frameTypes) { |
| 305 | if ((RTCFrameType)frameType.intValue == RTCFrameTypeVideoFrameKey) { |
| 306 | isKeyframeRequired = YES; |
| 307 | break; |
| 308 | } |
| 309 | } |
| 310 | } |
| 311 |
| 312 | CMTime presentationTimeStamp = |
| 313 | CMTimeMake(frame.timeStampNs / rtc::kNumNanosecsPerMillisec, 1000); |
| 314 | CFDictionaryRef frameProperties = nullptr; |
| 315 | if (isKeyframeRequired) { |
| 316 | CFTypeRef keys[] = {kVTEncodeFrameOptionKey_ForceKeyFrame}; |
| 317 | CFTypeRef values[] = {kCFBooleanTrue}; |
| 318 | frameProperties = CreateCFTypeDictionary(keys, values, 1); |
| 319 | } |
| 320 |
| 321 | std::unique_ptr<RTCFrameEncodeParams> encodeParams; |
| 322 | encodeParams.reset(new RTCFrameEncodeParams( |
| 323 | self, _width, _height, frame.timeStampNs / rtc::kNumNanosecsPerMillisec, |
| 324 | frame.timeStamp, frame.rotation)); |
| 325 |
| 326 | // Update the bitrate if needed. |
| 327 | [self setBitrateBps:_bitrateAdjuster->GetAdjustedBitrateBps()]; |
| 328 |
| 329 | OSStatus status = VTCompressionSessionEncodeFrame( |
| 330 | _compressionSession, pixelBuffer, presentationTimeStamp, kCMTimeInvalid, |
| 331 | frameProperties, encodeParams.release(), nullptr); |
| 332 | if (frameProperties) { |
| 333 | CFRelease(frameProperties); |
| 334 | } |
| 335 | if (pixelBuffer) { |
| 336 | CVBufferRelease(pixelBuffer); |
| 337 | } |
| 338 | if (status != noErr) { |
| 339 | RTC_LOG(LS_ERROR) << "Failed to encode frame with code: " << status; |
| 340 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 341 | } |
| 342 | return WEBRTC_VIDEO_CODEC_OK; |
| 343 | } |
| 344 |
| 345 | - (void)setCallback:(RTCVideoEncoderCallback)callback { |
| 346 | _callback = callback; |
| 347 | } |
| 348 |
| 349 | - (int)setBitrate:(uint32_t)bitrateKbit framerate:(uint32_t)framerate { |
| 350 | _targetBitrateBps = 1000 * bitrateKbit; |
| 351 | _bitrateAdjuster->SetTargetBitrateBps(_targetBitrateBps); |
| 352 | [self setBitrateBps:_bitrateAdjuster->GetAdjustedBitrateBps()]; |
| 353 | return WEBRTC_VIDEO_CODEC_OK; |
| 354 | } |
| 355 |
| 356 | #pragma mark - Private |
| 357 |
| 358 | - (NSInteger)releaseEncoder { |
| 359 | // Need to destroy so that the session is invalidated and won't use the |
| 360 | // callback anymore. Do not remove callback until the session is invalidated |
| 361 | // since async encoder callbacks can occur until invalidation. |
| 362 | [self destroyCompressionSession]; |
| 363 | _callback = nullptr; |
| 364 | return WEBRTC_VIDEO_CODEC_OK; |
| 365 | } |
| 366 |
| 367 | - (int)resetCompressionSession { |
| 368 | [self destroyCompressionSession]; |
| 369 |
| 370 | // Set source image buffer attributes. These attributes will be present on |
| 371 | // buffers retrieved from the encoder's pixel buffer pool. |
| 372 | const size_t attributesSize = 3; |
| 373 | CFTypeRef keys[attributesSize] = { |
| 374 | #if defined(WEBRTC_IOS) |
| 375 | kCVPixelBufferOpenGLESCompatibilityKey, |
| 376 | #elif defined(WEBRTC_MAC) |
| 377 | kCVPixelBufferOpenGLCompatibilityKey, |
| 378 | #endif |
| 379 | kCVPixelBufferIOSurfacePropertiesKey, |
| 380 | kCVPixelBufferPixelFormatTypeKey |
| 381 | }; |
| 382 | CFDictionaryRef ioSurfaceValue = CreateCFTypeDictionary(nullptr, nullptr, 0); |
| 383 | int64_t nv12type = kCVPixelFormatType_420YpCbCr8BiPlanarFullRange; |
| 384 | CFNumberRef pixelFormat = |
| 385 | CFNumberCreate(nullptr, kCFNumberLongType, &nv12type); |
| 386 | CFTypeRef values[attributesSize] = {kCFBooleanTrue, ioSurfaceValue, |
| 387 | pixelFormat}; |
| 388 | CFDictionaryRef sourceAttributes = |
| 389 | CreateCFTypeDictionary(keys, values, attributesSize); |
| 390 | if (ioSurfaceValue) { |
| 391 | CFRelease(ioSurfaceValue); |
| 392 | ioSurfaceValue = nullptr; |
| 393 | } |
| 394 | if (pixelFormat) { |
| 395 | CFRelease(pixelFormat); |
| 396 | pixelFormat = nullptr; |
| 397 | } |
| 398 | CFMutableDictionaryRef encoder_specs = nullptr; |
| 399 | #if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS) |
| 400 | // Currently hw accl is supported above 360p on mac, below 360p |
| 401 | // the compression session will be created with hw accl disabled. |
| 402 | encoder_specs = |
| 403 | CFDictionaryCreateMutable(nullptr, 1, &kCFTypeDictionaryKeyCallBacks, |
| 404 | &kCFTypeDictionaryValueCallBacks); |
| 405 | CFDictionarySetValue( |
| 406 | encoder_specs, |
| 407 | kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder, |
| 408 | kCFBooleanTrue); |
| 409 | #endif |
| 410 | OSStatus status = VTCompressionSessionCreate( |
| 411 | nullptr, // use default allocator |
| 412 | _width, _height, kCMVideoCodecType_HEVC, |
| 413 | encoder_specs, // use hardware accelerated encoder if available |
| 414 | sourceAttributes, |
| 415 | nullptr, // use default compressed data allocator |
| 416 | compressionOutputCallback, nullptr, &_compressionSession); |
| 417 | if (sourceAttributes) { |
| 418 | CFRelease(sourceAttributes); |
| 419 | sourceAttributes = nullptr; |
| 420 | } |
| 421 | if (encoder_specs) { |
| 422 | CFRelease(encoder_specs); |
| 423 | encoder_specs = nullptr; |
| 424 | } |
| 425 | if (status != noErr) { |
| 426 | RTC_LOG(LS_ERROR) << "Failed to create compression session: " << status; |
| 427 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 428 | } |
| 429 | #if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS) |
| 430 | CFBooleanRef hwaccl_enabled = nullptr; |
| 431 | status = VTSessionCopyProperty( |
| 432 | _compressionSession, |
| 433 | kVTCompressionPropertyKey_UsingHardwareAcceleratedVideoEncoder, nullptr, |
| 434 | &hwaccl_enabled); |
| 435 | if (status == noErr && (CFBooleanGetValue(hwaccl_enabled))) { |
| 436 | RTC_LOG(LS_INFO) << "Compression session created with hw accl enabled"; |
| 437 | } else { |
| 438 | RTC_LOG(LS_INFO) << "Compression session created with hw accl disabled"; |
| 439 | } |
| 440 | #endif |
| 441 | [self configureCompressionSession]; |
| 442 | return WEBRTC_VIDEO_CODEC_OK; |
| 443 | } |
| 444 |
| 445 | - (void)configureCompressionSession { |
| 446 | RTC_DCHECK(_compressionSession); |
| 447 | SetVTSessionProperty(_compressionSession, kVTCompressionPropertyKey_RealTime, |
| 448 | false); |
| 449 | // SetVTSessionProperty(_compressionSession, |
| 450 | // kVTCompressionPropertyKey_ProfileLevel, _profile); |
| 451 | SetVTSessionProperty(_compressionSession, |
| 452 | kVTCompressionPropertyKey_AllowFrameReordering, false); |
| 453 | [self setEncoderBitrateBps:_targetBitrateBps]; |
| 454 | // TODO(tkchin): Look at entropy mode and colorspace matrices. |
| 455 | // TODO(tkchin): Investigate to see if there's any way to make this work. |
| 456 | // May need it to interop with Android. Currently this call just fails. |
| 457 | // On inspecting encoder output on iOS8, this value is set to 6. |
| 458 | // internal::SetVTSessionProperty(compression_session_, |
| 459 | // kVTCompressionPropertyKey_MaxFrameDelayCount, |
| 460 | // 1); |
| 461 |
| 462 | // Set a relatively large value for keyframe emission (7200 frames or 4 |
| 463 | // minutes). |
| 464 | SetVTSessionProperty(_compressionSession, |
| 465 | kVTCompressionPropertyKey_MaxKeyFrameInterval, 7200); |
| 466 | SetVTSessionProperty(_compressionSession, |
| 467 | kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration, |
| 468 | 240); |
| 469 | OSStatus status = |
| 470 | VTCompressionSessionPrepareToEncodeFrames(_compressionSession); |
| 471 | if (status != noErr) { |
| 472 | RTC_LOG(LS_ERROR) << "Compression session failed to prepare encode frames."; |
| 473 | } |
| 474 | } |
| 475 |
| 476 | - (void)destroyCompressionSession { |
| 477 | if (_compressionSession) { |
| 478 | VTCompressionSessionInvalidate(_compressionSession); |
| 479 | CFRelease(_compressionSession); |
| 480 | _compressionSession = nullptr; |
| 481 | } |
| 482 | } |
| 483 |
| 484 | - (NSString*)implementationName { |
| 485 | return @"VideoToolbox"; |
| 486 | } |
| 487 |
| 488 | - (void)setBitrateBps:(uint32_t)bitrateBps { |
| 489 | if (_encoderBitrateBps != bitrateBps) { |
| 490 | [self setEncoderBitrateBps:bitrateBps]; |
| 491 | } |
| 492 | } |
| 493 |
| 494 | - (void)setEncoderBitrateBps:(uint32_t)bitrateBps { |
| 495 | if (_compressionSession) { |
| 496 | SetVTSessionProperty(_compressionSession, |
| 497 | kVTCompressionPropertyKey_AverageBitRate, bitrateBps); |
| 498 |
| 499 | // TODO(tkchin): Add a helper method to set array value. |
| 500 | int64_t dataLimitBytesPerSecondValue = |
| 501 | static_cast<int64_t>(bitrateBps * kLimitToAverageBitRateFactor / 8); |
| 502 | CFNumberRef bytesPerSecond = |
| 503 | CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, |
| 504 | &dataLimitBytesPerSecondValue); |
| 505 | int64_t oneSecondValue = 1; |
| 506 | CFNumberRef oneSecond = CFNumberCreate( |
| 507 | kCFAllocatorDefault, kCFNumberSInt64Type, &oneSecondValue); |
| 508 | const void* nums[2] = {bytesPerSecond, oneSecond}; |
| 509 | CFArrayRef dataRateLimits = |
| 510 | CFArrayCreate(nullptr, nums, 2, &kCFTypeArrayCallBacks); |
| 511 | OSStatus status = VTSessionSetProperty( |
| 512 | _compressionSession, kVTCompressionPropertyKey_DataRateLimits, |
| 513 | dataRateLimits); |
| 514 | if (bytesPerSecond) { |
| 515 | CFRelease(bytesPerSecond); |
| 516 | } |
| 517 | if (oneSecond) { |
| 518 | CFRelease(oneSecond); |
| 519 | } |
| 520 | if (dataRateLimits) { |
| 521 | CFRelease(dataRateLimits); |
| 522 | } |
| 523 | if (status != noErr) { |
| 524 | RTC_LOG(LS_ERROR) << "Failed to set data rate limit"; |
| 525 | } |
| 526 |
| 527 | _encoderBitrateBps = bitrateBps; |
| 528 | } |
| 529 | } |
| 530 |
| 531 | - (void)frameWasEncoded:(OSStatus)status |
| 532 | flags:(VTEncodeInfoFlags)infoFlags |
| 533 | sampleBuffer:(CMSampleBufferRef)sampleBuffer |
| 534 | width:(int32_t)width |
| 535 | height:(int32_t)height |
| 536 | renderTimeMs:(int64_t)renderTimeMs |
| 537 | timestamp:(uint32_t)timestamp |
| 538 | rotation:(RTCVideoRotation)rotation { |
| 539 | if (status != noErr) { |
| 540 | RTC_LOG(LS_ERROR) << "h265 encode failed."; |
| 541 | return; |
| 542 | } |
| 543 | if (infoFlags & kVTEncodeInfo_FrameDropped) { |
| 544 | RTC_LOG(LS_INFO) << "h265 encoder dropped a frame."; |
| 545 | return; |
| 546 | } |
| 547 |
| 548 | BOOL isKeyframe = NO; |
| 549 | CFArrayRef attachments = |
| 550 | CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, 0); |
| 551 | if (attachments != nullptr && CFArrayGetCount(attachments)) { |
| 552 | CFDictionaryRef attachment = |
| 553 | static_cast<CFDictionaryRef>(CFArrayGetValueAtIndex(attachments, 0)); |
| 554 | isKeyframe = |
| 555 | !CFDictionaryContainsKey(attachment, kCMSampleAttachmentKey_NotSync); |
| 556 | } |
| 557 |
| 558 | if (isKeyframe) { |
| 559 | RTC_LOG(LS_INFO) << "Generated keyframe"; |
| 560 | } |
| 561 |
| 562 | // Convert the sample buffer into a buffer suitable for RTP packetization. |
| 563 | // TODO(tkchin): Allocate buffers through a pool. |
| 564 | std::unique_ptr<rtc::Buffer> buffer(new rtc::Buffer()); |
| 565 | RTCRtpFragmentationHeader* header; |
| 566 | { |
| 567 | std::unique_ptr<webrtc::RTPFragmentationHeader> header_cpp; |
| 568 | bool result = H265CMSampleBufferToAnnexBBuffer(sampleBuffer, isKeyframe, |
| 569 | buffer.get(), &header_cpp); |
| 570 | header = [[RTCRtpFragmentationHeader alloc] |
| 571 | initWithNativeFragmentationHeader:header_cpp.get()]; |
| 572 | if (!result) { |
| 573 | RTC_LOG(LS_ERROR) << "Failed to convert sample buffer."; |
| 574 | return; |
| 575 | } |
| 576 | } |
| 577 |
| 578 | RTCEncodedImage* frame = [[RTCEncodedImage alloc] init]; |
| 579 | frame.buffer = [NSData dataWithBytesNoCopy:buffer->data() |
| 580 | length:buffer->size() |
| 581 | freeWhenDone:NO]; |
| 582 | frame.encodedWidth = width; |
| 583 | frame.encodedHeight = height; |
| 584 | frame.completeFrame = YES; |
| 585 | frame.frameType = |
| 586 | isKeyframe ? RTCFrameTypeVideoFrameKey : RTCFrameTypeVideoFrameDelta; |
| 587 | frame.captureTimeMs = renderTimeMs; |
| 588 | frame.timeStamp = timestamp; |
| 589 | frame.rotation = rotation; |
| 590 | frame.contentType = (_mode == RTCVideoCodecModeScreensharing) |
| 591 | ? RTCVideoContentTypeScreenshare |
| 592 | : RTCVideoContentTypeUnspecified; |
| 593 | frame.flags = webrtc::VideoSendTiming::kInvalid; |
| 594 |
| 595 | int qp; |
| 596 | _h265BitstreamParser.ParseBitstream(buffer->data(), buffer->size()); |
| 597 | _h265BitstreamParser.GetLastSliceQp(&qp); |
| 598 | frame.qp = @(qp); |
| 599 |
| 600 | BOOL res = _callback(frame, [[RTCCodecSpecificInfoH265 alloc] init], header); |
| 601 | if (!res) { |
| 602 | RTC_LOG(LS_ERROR) << "Encode callback failed."; |
| 603 | return; |
| 604 | } |
| 605 | _bitrateAdjuster->Update(frame.buffer.length); |
| 606 | } |
| 607 |
| 608 | - (RTCVideoEncoderQpThresholds*)scalingSettings { |
| 609 | return [[RTCVideoEncoderQpThresholds alloc] |
| 610 | initWithThresholdsLow:kLowh265QpThreshold |
| 611 | high:kHighh265QpThreshold]; |
| 612 | } |
| 613 |
| 614 | @end |
| 615 |