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