| 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 "TGRTCVideoEncoderH264.h" |
| 13 |
| 14 | #import <VideoToolbox/VideoToolbox.h> |
| 15 | #include <vector> |
| 16 |
| 17 | #if defined(WEBRTC_IOS) |
| 18 | #import "helpers/UIDevice+RTCDevice.h" |
| 19 | #endif |
| 20 | #import "RTCCodecSpecificInfoH264.h" |
| 21 | #import "RTCH264ProfileLevelId.h" |
| 22 | #import "api/peerconnection/RTCVideoCodecInfo+Private.h" |
| 23 | #import "base/RTCCodecSpecificInfo.h" |
| 24 | #import "base/RTCI420Buffer.h" |
| 25 | #import "base/RTCVideoEncoder.h" |
| 26 | #import "base/RTCVideoFrame.h" |
| 27 | #import "base/RTCVideoFrameBuffer.h" |
| 28 | #import "components/video_frame_buffer/RTCCVPixelBuffer.h" |
| 29 | #import "helpers.h" |
| 30 |
| 31 | #include "common_video/h264/h264_bitstream_parser.h" |
| 32 |
| 33 | #include "api/video_codecs/h264_profile_level_id.h" |
| 34 |
| 35 | #include "common_video/include/bitrate_adjuster.h" |
| 36 | #include "modules/include/module_common_types.h" |
| 37 | #include "modules/video_coding/include/video_error_codes.h" |
| 38 | #include "rtc_base/buffer.h" |
| 39 | #include "rtc_base/logging.h" |
| 40 | #include "rtc_base/time_utils.h" |
| 41 | #include "sdk/objc/components/video_codec/nalu_rewriter.h" |
| 42 | #include "third_party/libyuv/include/libyuv/convert_from.h" |
| 43 |
| 44 | @interface TGRTCVideoEncoderH264 () |
| 45 |
| 46 | - (void)frameWasEncoded:(OSStatus)status |
| 47 | flags:(VTEncodeInfoFlags)infoFlags |
| 48 | sampleBuffer:(CMSampleBufferRef)sampleBuffer |
| 49 | codecSpecificInfo:(id<RTCCodecSpecificInfo>)codecSpecificInfo |
| 50 | width:(int32_t)width |
| 51 | height:(int32_t)height |
| 52 | renderTimeMs:(int64_t)renderTimeMs |
| 53 | timestamp:(uint32_t)timestamp |
| 54 | rotation:(RTCVideoRotation)rotation; |
| 55 |
| 56 | @end |
| 57 |
| 58 | namespace { // anonymous namespace |
| 59 |
| 60 | // The ratio between kVTCompressionPropertyKey_DataRateLimits and |
| 61 | // kVTCompressionPropertyKey_AverageBitRate. The data rate limit is set higher |
| 62 | // than the average bit rate to avoid undershooting the target. |
| 63 | const float kLimitToAverageBitRateFactor = 1.5f; |
| 64 | // These thresholds deviate from the default h264 QP thresholds, as they |
| 65 | // have been found to work better on devices that support VideoToolbox |
| 66 | const int kLowH264QpThreshold = 28; |
| 67 | const int kHighH264QpThreshold = 39; |
| 68 |
| 69 | const OSType kNV12PixelFormat = kCVPixelFormatType_420YpCbCr8BiPlanarFullRange; |
| 70 |
| 71 | // Struct that we pass to the encoder per frame to encode. We receive it again |
| 72 | // in the encoder callback. |
| 73 | struct RTCFrameEncodeParams { |
| 74 | RTCFrameEncodeParams(TGRTCVideoEncoderH264 *e, |
| 75 | RTCCodecSpecificInfoH264 *csi, |
| 76 | int32_t w, |
| 77 | int32_t h, |
| 78 | int64_t rtms, |
| 79 | uint32_t ts, |
| 80 | RTCVideoRotation r) |
| 81 | : encoder(e), width(w), height(h), render_time_ms(rtms), timestamp(ts), rotation(r) { |
| 82 | if (csi) { |
| 83 | codecSpecificInfo = csi; |
| 84 | } else { |
| 85 | codecSpecificInfo = [[RTCCodecSpecificInfoH264 alloc] init]; |
| 86 | } |
| 87 | } |
| 88 |
| 89 | TGRTCVideoEncoderH264 *encoder; |
| 90 | RTCCodecSpecificInfoH264 *codecSpecificInfo; |
| 91 | int32_t width; |
| 92 | int32_t height; |
| 93 | int64_t render_time_ms; |
| 94 | uint32_t timestamp; |
| 95 | RTCVideoRotation rotation; |
| 96 | }; |
| 97 |
| 98 | // We receive I420Frames as input, but we need to feed CVPixelBuffers into the |
| 99 | // encoder. This performs the copy and format conversion. |
| 100 | // TODO(tkchin): See if encoder will accept i420 frames and compare performance. |
| 101 | static bool CopyVideoFrameToNV12PixelBuffer(id<RTCI420Buffer> frameBuffer, CVPixelBufferRef pixelBuffer) { |
| 102 | RTC_DCHECK(pixelBuffer); |
| 103 | RTC_DCHECK_EQ(CVPixelBufferGetPixelFormatType(pixelBuffer), kNV12PixelFormat); |
| 104 | RTC_DCHECK_EQ(CVPixelBufferGetHeightOfPlane(pixelBuffer, 0), frameBuffer.height); |
| 105 | RTC_DCHECK_EQ(CVPixelBufferGetWidthOfPlane(pixelBuffer, 0), frameBuffer.width); |
| 106 |
| 107 | CVReturn cvRet = CVPixelBufferLockBaseAddress(pixelBuffer, 0); |
| 108 | if (cvRet != kCVReturnSuccess) { |
| 109 | RTC_LOG(LS_ERROR) << "Failed to lock base address: " << cvRet; |
| 110 | return false; |
| 111 | } |
| 112 | uint8_t *dstY = reinterpret_cast<uint8_t *>(CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 0)); |
| 113 | int dstStrideY = CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer, 0); |
| 114 | uint8_t *dstUV = reinterpret_cast<uint8_t *>(CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 1)); |
| 115 | int dstStrideUV = CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer, 1); |
| 116 | // Convert I420 to NV12. |
| 117 | int ret = libyuv::I420ToNV12(frameBuffer.dataY, |
| 118 | frameBuffer.strideY, |
| 119 | frameBuffer.dataU, |
| 120 | frameBuffer.strideU, |
| 121 | frameBuffer.dataV, |
| 122 | frameBuffer.strideV, |
| 123 | dstY, |
| 124 | dstStrideY, |
| 125 | dstUV, |
| 126 | dstStrideUV, |
| 127 | frameBuffer.width, |
| 128 | frameBuffer.height); |
| 129 | CVPixelBufferUnlockBaseAddress(pixelBuffer, 0); |
| 130 | if (ret) { |
| 131 | RTC_LOG(LS_ERROR) << "Error converting I420 VideoFrame to NV12 :" << ret; |
| 132 | return false; |
| 133 | } |
| 134 | return true; |
| 135 | } |
| 136 |
| 137 | static CVPixelBufferRef CreatePixelBuffer(CVPixelBufferPoolRef pixel_buffer_pool) { |
| 138 | if (!pixel_buffer_pool) { |
| 139 | RTC_LOG(LS_ERROR) << "Failed to get pixel buffer pool."; |
| 140 | return nullptr; |
| 141 | } |
| 142 | CVPixelBufferRef pixel_buffer; |
| 143 | CVReturn ret = CVPixelBufferPoolCreatePixelBuffer(nullptr, pixel_buffer_pool, &pixel_buffer); |
| 144 | if (ret != kCVReturnSuccess) { |
| 145 | RTC_LOG(LS_ERROR) << "Failed to create pixel buffer: " << ret; |
| 146 | // We probably want to drop frames here, since failure probably means |
| 147 | // that the pool is empty. |
| 148 | return nullptr; |
| 149 | } |
| 150 | return pixel_buffer; |
| 151 | } |
| 152 |
| 153 | // This is the callback function that VideoToolbox calls when encode is |
| 154 | // complete. From inspection this happens on its own queue. |
| 155 | static void compressionOutputCallback(void *encoder, |
| 156 | void *params, |
| 157 | OSStatus status, |
| 158 | VTEncodeInfoFlags infoFlags, |
| 159 | CMSampleBufferRef sampleBuffer) { |
| 160 | if (!params) { |
| 161 | // If there are pending callbacks when the encoder is destroyed, this can happen. |
| 162 | return; |
| 163 | } |
| 164 | std::unique_ptr<RTCFrameEncodeParams> encodeParams( |
| 165 | reinterpret_cast<RTCFrameEncodeParams *>(params)); |
| 166 | [encodeParams->encoder frameWasEncoded:status |
| 167 | flags:infoFlags |
| 168 | sampleBuffer:sampleBuffer |
| 169 | codecSpecificInfo:encodeParams->codecSpecificInfo |
| 170 | width:encodeParams->width |
| 171 | height:encodeParams->height |
| 172 | renderTimeMs:encodeParams->render_time_ms |
| 173 | timestamp:encodeParams->timestamp |
| 174 | rotation:encodeParams->rotation]; |
| 175 | } |
| 176 |
| 177 | // Extract VideoToolbox profile out of the webrtc::SdpVideoFormat. If there is |
| 178 | // no specific VideoToolbox profile for the specified level, AutoLevel will be |
| 179 | // returned. The user must initialize the encoder with a resolution and |
| 180 | // framerate conforming to the selected H264 level regardless. |
| 181 | CFStringRef ExtractProfile(const webrtc::H264ProfileLevelId &profile_level_id) { |
| 182 | switch (profile_level_id.profile) { |
| 183 | case webrtc::H264Profile::kProfileConstrainedBaseline: |
| 184 | case webrtc::H264Profile::kProfileBaseline: |
| 185 | switch (profile_level_id.level) { |
| 186 | case webrtc::H264Level::kLevel3: |
| 187 | return kVTProfileLevel_H264_Baseline_3_0; |
| 188 | case webrtc::H264Level::kLevel3_1: |
| 189 | return kVTProfileLevel_H264_Baseline_3_1; |
| 190 | case webrtc::H264Level::kLevel3_2: |
| 191 | return kVTProfileLevel_H264_Baseline_3_2; |
| 192 | case webrtc::H264Level::kLevel4: |
| 193 | return kVTProfileLevel_H264_Baseline_4_0; |
| 194 | case webrtc::H264Level::kLevel4_1: |
| 195 | return kVTProfileLevel_H264_Baseline_4_1; |
| 196 | case webrtc::H264Level::kLevel4_2: |
| 197 | return kVTProfileLevel_H264_Baseline_4_2; |
| 198 | case webrtc::H264Level::kLevel5: |
| 199 | return kVTProfileLevel_H264_Baseline_5_0; |
| 200 | case webrtc::H264Level::kLevel5_1: |
| 201 | return kVTProfileLevel_H264_Baseline_5_1; |
| 202 | case webrtc::H264Level::kLevel5_2: |
| 203 | return kVTProfileLevel_H264_Baseline_5_2; |
| 204 | case webrtc::H264Level::kLevel1: |
| 205 | case webrtc::H264Level::kLevel1_b: |
| 206 | case webrtc::H264Level::kLevel1_1: |
| 207 | case webrtc::H264Level::kLevel1_2: |
| 208 | case webrtc::H264Level::kLevel1_3: |
| 209 | case webrtc::H264Level::kLevel2: |
| 210 | case webrtc::H264Level::kLevel2_1: |
| 211 | case webrtc::H264Level::kLevel2_2: |
| 212 | return kVTProfileLevel_H264_Baseline_AutoLevel; |
| 213 | } |
| 214 |
| 215 | case webrtc::H264Profile::kProfileMain: |
| 216 | switch (profile_level_id.level) { |
| 217 | case webrtc::H264Level::kLevel3: |
| 218 | return kVTProfileLevel_H264_Main_3_0; |
| 219 | case webrtc::H264Level::kLevel3_1: |
| 220 | return kVTProfileLevel_H264_Main_3_1; |
| 221 | case webrtc::H264Level::kLevel3_2: |
| 222 | return kVTProfileLevel_H264_Main_3_2; |
| 223 | case webrtc::H264Level::kLevel4: |
| 224 | return kVTProfileLevel_H264_Main_4_0; |
| 225 | case webrtc::H264Level::kLevel4_1: |
| 226 | return kVTProfileLevel_H264_Main_4_1; |
| 227 | case webrtc::H264Level::kLevel4_2: |
| 228 | return kVTProfileLevel_H264_Main_4_2; |
| 229 | case webrtc::H264Level::kLevel5: |
| 230 | return kVTProfileLevel_H264_Main_5_0; |
| 231 | case webrtc::H264Level::kLevel5_1: |
| 232 | return kVTProfileLevel_H264_Main_5_1; |
| 233 | case webrtc::H264Level::kLevel5_2: |
| 234 | return kVTProfileLevel_H264_Main_5_2; |
| 235 | case webrtc::H264Level::kLevel1: |
| 236 | case webrtc::H264Level::kLevel1_b: |
| 237 | case webrtc::H264Level::kLevel1_1: |
| 238 | case webrtc::H264Level::kLevel1_2: |
| 239 | case webrtc::H264Level::kLevel1_3: |
| 240 | case webrtc::H264Level::kLevel2: |
| 241 | case webrtc::H264Level::kLevel2_1: |
| 242 | case webrtc::H264Level::kLevel2_2: |
| 243 | return kVTProfileLevel_H264_Main_AutoLevel; |
| 244 | } |
| 245 |
| 246 | case webrtc::H264Profile::kProfileConstrainedHigh: |
| 247 | case webrtc::H264Profile::kProfileHigh: |
| 248 | #ifdef __aarch64__ |
| 249 | if (profile_level_id.level < webrtc::H264Level::kLevel4) { |
| 250 | return kVTProfileLevel_H264_Main_4_0; |
| 251 | } |
| 252 | #endif |
| 253 |
| 254 | switch (profile_level_id.level) { |
| 255 | case webrtc::H264Level::kLevel3: |
| 256 | return kVTProfileLevel_H264_High_3_0; |
| 257 | case webrtc::H264Level::kLevel3_1: |
| 258 | return kVTProfileLevel_H264_High_3_1; |
| 259 | case webrtc::H264Level::kLevel3_2: |
| 260 | return kVTProfileLevel_H264_High_3_2; |
| 261 | case webrtc::H264Level::kLevel4: |
| 262 | return kVTProfileLevel_H264_High_4_0; |
| 263 | case webrtc::H264Level::kLevel4_1: |
| 264 | return kVTProfileLevel_H264_High_4_1; |
| 265 | case webrtc::H264Level::kLevel4_2: |
| 266 | return kVTProfileLevel_H264_High_4_2; |
| 267 | case webrtc::H264Level::kLevel5: |
| 268 | return kVTProfileLevel_H264_High_5_0; |
| 269 | case webrtc::H264Level::kLevel5_1: |
| 270 | return kVTProfileLevel_H264_High_5_1; |
| 271 | case webrtc::H264Level::kLevel5_2: |
| 272 | return kVTProfileLevel_H264_High_5_2; |
| 273 | case webrtc::H264Level::kLevel1: |
| 274 | case webrtc::H264Level::kLevel1_b: |
| 275 | case webrtc::H264Level::kLevel1_1: |
| 276 | case webrtc::H264Level::kLevel1_2: |
| 277 | case webrtc::H264Level::kLevel1_3: |
| 278 | case webrtc::H264Level::kLevel2: |
| 279 | case webrtc::H264Level::kLevel2_1: |
| 280 | case webrtc::H264Level::kLevel2_2: |
| 281 | return kVTProfileLevel_H264_High_AutoLevel; |
| 282 | } |
| 283 | } |
| 284 | return {}; |
| 285 | } |
| 286 |
| 287 | // The function returns the max allowed sample rate (pixels per second) that |
| 288 | // can be processed by given encoder with |profile_level_id|. |
| 289 | // See https://www.itu.int/rec/dologin_pub.asp?lang=e&id=T-REC-H.264-201610-S!!PDF-E&type=items |
| 290 | // for details. |
| 291 | NSUInteger GetMaxSampleRate(const webrtc::H264ProfileLevelId &profile_level_id) { |
| 292 | switch (profile_level_id.level) { |
| 293 | case webrtc::H264Level::kLevel3: |
| 294 | return 10368000; |
| 295 | case webrtc::H264Level::kLevel3_1: |
| 296 | return 27648000; |
| 297 | case webrtc::H264Level::kLevel3_2: |
| 298 | return 55296000; |
| 299 | case webrtc::H264Level::kLevel4: |
| 300 | case webrtc::H264Level::kLevel4_1: |
| 301 | return 62914560; |
| 302 | case webrtc::H264Level::kLevel4_2: |
| 303 | return 133693440; |
| 304 | case webrtc::H264Level::kLevel5: |
| 305 | return 150994944; |
| 306 | case webrtc::H264Level::kLevel5_1: |
| 307 | return 251658240; |
| 308 | case webrtc::H264Level::kLevel5_2: |
| 309 | return 530841600; |
| 310 | case webrtc::H264Level::kLevel1: |
| 311 | case webrtc::H264Level::kLevel1_b: |
| 312 | case webrtc::H264Level::kLevel1_1: |
| 313 | case webrtc::H264Level::kLevel1_2: |
| 314 | case webrtc::H264Level::kLevel1_3: |
| 315 | case webrtc::H264Level::kLevel2: |
| 316 | case webrtc::H264Level::kLevel2_1: |
| 317 | case webrtc::H264Level::kLevel2_2: |
| 318 | // Zero means auto rate setting. |
| 319 | return 0; |
| 320 | } |
| 321 | } |
| 322 | } // namespace |
| 323 |
| 324 | @implementation TGRTCVideoEncoderH264 { |
| 325 | RTCVideoCodecInfo *_codecInfo; |
| 326 | std::unique_ptr<webrtc::BitrateAdjuster> _bitrateAdjuster; |
| 327 | uint32_t _targetBitrateBps; |
| 328 | uint32_t _encoderBitrateBps; |
| 329 | uint32_t _encoderFrameRate; |
| 330 | uint32_t _maxAllowedFrameRate; |
| 331 | RTCH264PacketizationMode _packetizationMode; |
| 332 | absl::optional<webrtc::H264ProfileLevelId> _profile_level_id; |
| 333 | RTCVideoEncoderCallback _callback; |
| 334 | int32_t _width; |
| 335 | int32_t _height; |
| 336 | VTCompressionSessionRef _compressionSession; |
| 337 | CVPixelBufferPoolRef _pixelBufferPool; |
| 338 | RTCVideoCodecMode _mode; |
| 339 |
| 340 | webrtc::H264BitstreamParser _h264BitstreamParser; |
| 341 | std::vector<uint8_t> _frameScaleBuffer; |
| 342 | } |
| 343 |
| 344 | // .5 is set as a mininum to prevent overcompensating for large temporary |
| 345 | // overshoots. We don't want to degrade video quality too badly. |
| 346 | // .95 is set to prevent oscillations. When a lower bitrate is set on the |
| 347 | // encoder than previously set, its output seems to have a brief period of |
| 348 | // drastically reduced bitrate, so we want to avoid that. In steady state |
| 349 | // conditions, 0.95 seems to give us better overall bitrate over long periods |
| 350 | // of time. |
| 351 | - (instancetype)initWithCodecInfo:(RTCVideoCodecInfo *)codecInfo { |
| 352 | if (self = [super init]) { |
| 353 | _codecInfo = codecInfo; |
| 354 | _bitrateAdjuster.reset(new webrtc::BitrateAdjuster(.5, .95)); |
| 355 | _packetizationMode = RTCH264PacketizationModeNonInterleaved; |
| 356 | _profile_level_id = |
| 357 | webrtc::ParseSdpForH264ProfileLevelId([codecInfo nativeSdpVideoFormat].parameters); |
| 358 | RTC_DCHECK(_profile_level_id); |
| 359 | RTC_LOG(LS_INFO) << "Using profile " << CFStringToString(ExtractProfile(*_profile_level_id)); |
| 360 | RTC_CHECK([codecInfo.name isEqualToString:kRTCVideoCodecH264Name]); |
| 361 | } |
| 362 | return self; |
| 363 | } |
| 364 |
| 365 | - (void)dealloc { |
| 366 | [self destroyCompressionSession]; |
| 367 | } |
| 368 |
| 369 | - (NSInteger)startEncodeWithSettings:(RTCVideoEncoderSettings *)settings |
| 370 | numberOfCores:(int)numberOfCores { |
| 371 | RTC_DCHECK(settings); |
| 372 | RTC_DCHECK([settings.name isEqualToString:kRTCVideoCodecH264Name]); |
| 373 |
| 374 | _width = settings.width; |
| 375 | _height = settings.height; |
| 376 | _mode = settings.mode; |
| 377 |
| 378 | uint32_t aligned_width = (((_width + 15) >> 4) << 4); |
| 379 | uint32_t aligned_height = (((_height + 15) >> 4) << 4); |
| 380 | _maxAllowedFrameRate = static_cast<uint32_t>(GetMaxSampleRate(*_profile_level_id) / |
| 381 | (aligned_width * aligned_height)); |
| 382 |
| 383 | // We can only set average bitrate on the HW encoder. |
| 384 | _targetBitrateBps = settings.startBitrate * 1000; // startBitrate is in kbps. |
| 385 | _bitrateAdjuster->SetTargetBitrateBps(_targetBitrateBps); |
| 386 | _encoderFrameRate = MIN(settings.maxFramerate, _maxAllowedFrameRate); |
| 387 | if (settings.maxFramerate > _maxAllowedFrameRate && _maxAllowedFrameRate > 0) { |
| 388 | RTC_LOG(LS_WARNING) << "Initial encoder frame rate setting " << settings.maxFramerate |
| 389 | << " is larger than the " |
| 390 | << "maximal allowed frame rate " << _maxAllowedFrameRate << "."; |
| 391 | } |
| 392 |
| 393 | // TODO(tkchin): Try setting payload size via |
| 394 | // kVTCompressionPropertyKey_MaxH264SliceBytes. |
| 395 |
| 396 | return [self resetCompressionSessionWithPixelFormat:kNV12PixelFormat]; |
| 397 | } |
| 398 |
| 399 | - (NSInteger)encode:(RTCVideoFrame *)frame |
| 400 | codecSpecificInfo:(nullable id<RTCCodecSpecificInfo>)codecSpecificInfo |
| 401 | frameTypes:(NSArray<NSNumber *> *)frameTypes { |
| 402 | //RTC_DCHECK_EQ(frame.width, _width); |
| 403 | //RTC_DCHECK_EQ(frame.height, _height); |
| 404 | if (!_callback || !_compressionSession) { |
| 405 | return WEBRTC_VIDEO_CODEC_UNINITIALIZED; |
| 406 | } |
| 407 | BOOL isKeyframeRequired = NO; |
| 408 |
| 409 | // Get a pixel buffer from the pool and copy frame data over. |
| 410 | if ([self resetCompressionSessionIfNeededWithFrame:frame]) { |
| 411 | isKeyframeRequired = YES; |
| 412 | } |
| 413 |
| 414 | CVPixelBufferRef pixelBuffer = nullptr; |
| 415 | if ([frame.buffer isKindOfClass:[RTCCVPixelBuffer class]]) { |
| 416 | // Native frame buffer |
| 417 | RTCCVPixelBuffer *rtcPixelBuffer = (RTCCVPixelBuffer *)frame.buffer; |
| 418 | if (![rtcPixelBuffer requiresCropping]) { |
| 419 | // This pixel buffer might have a higher resolution than what the |
| 420 | // compression session is configured to. The compression session can |
| 421 | // handle that and will output encoded frames in the configured |
| 422 | // resolution regardless of the input pixel buffer resolution. |
| 423 | pixelBuffer = rtcPixelBuffer.pixelBuffer; |
| 424 | CVBufferRetain(pixelBuffer); |
| 425 | } else { |
| 426 | // Cropping required, we need to crop and scale to a new pixel buffer. |
| 427 | pixelBuffer = CreatePixelBuffer(_pixelBufferPool); |
| 428 | if (!pixelBuffer) { |
| 429 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 430 | } |
| 431 | int dstWidth = CVPixelBufferGetWidth(pixelBuffer); |
| 432 | int dstHeight = CVPixelBufferGetHeight(pixelBuffer); |
| 433 | if ([rtcPixelBuffer requiresScalingToWidth:dstWidth height:dstHeight]) { |
| 434 | int size = |
| 435 | [rtcPixelBuffer bufferSizeForCroppingAndScalingToWidth:dstWidth height:dstHeight]; |
| 436 | _frameScaleBuffer.resize(size); |
| 437 | } else { |
| 438 | _frameScaleBuffer.clear(); |
| 439 | } |
| 440 | _frameScaleBuffer.shrink_to_fit(); |
| 441 | if (![rtcPixelBuffer cropAndScaleTo:pixelBuffer withTempBuffer:_frameScaleBuffer.data()]) { |
| 442 | CVBufferRelease(pixelBuffer); |
| 443 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 444 | } |
| 445 | } |
| 446 | } |
| 447 |
| 448 | if (!pixelBuffer) { |
| 449 | // We did not have a native frame buffer |
| 450 | pixelBuffer = CreatePixelBuffer(_pixelBufferPool); |
| 451 | if (!pixelBuffer) { |
| 452 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 453 | } |
| 454 | RTC_DCHECK(pixelBuffer); |
| 455 | if (!CopyVideoFrameToNV12PixelBuffer([frame.buffer toI420], pixelBuffer)) { |
| 456 | RTC_LOG(LS_ERROR) << "Failed to copy frame data."; |
| 457 | CVBufferRelease(pixelBuffer); |
| 458 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 459 | } |
| 460 | } |
| 461 |
| 462 | // Check if we need a keyframe. |
| 463 | if (!isKeyframeRequired && frameTypes) { |
| 464 | for (NSNumber *frameType in frameTypes) { |
| 465 | if ((RTCFrameType)frameType.intValue == RTCFrameTypeVideoFrameKey) { |
| 466 | isKeyframeRequired = YES; |
| 467 | break; |
| 468 | } |
| 469 | } |
| 470 | } |
| 471 |
| 472 | CMTime presentationTimeStamp = CMTimeMake(frame.timeStampNs / rtc::kNumNanosecsPerMillisec, 1000); |
| 473 | CFDictionaryRef frameProperties = nullptr; |
| 474 | if (isKeyframeRequired) { |
| 475 | CFTypeRef keys[] = {kVTEncodeFrameOptionKey_ForceKeyFrame}; |
| 476 | CFTypeRef values[] = {kCFBooleanTrue}; |
| 477 | frameProperties = CreateCFTypeDictionary(keys, values, 1); |
| 478 | } |
| 479 |
| 480 | std::unique_ptr<RTCFrameEncodeParams> encodeParams; |
| 481 | encodeParams.reset(new RTCFrameEncodeParams(self, |
| 482 | codecSpecificInfo, |
| 483 | _width, |
| 484 | _height, |
| 485 | frame.timeStampNs / rtc::kNumNanosecsPerMillisec, |
| 486 | frame.timeStamp, |
| 487 | frame.rotation)); |
| 488 | encodeParams->codecSpecificInfo.packetizationMode = _packetizationMode; |
| 489 |
| 490 | // Update the bitrate if needed. |
| 491 | [self setBitrateBps:_bitrateAdjuster->GetAdjustedBitrateBps() frameRate:_encoderFrameRate]; |
| 492 |
| 493 | OSStatus status = VTCompressionSessionEncodeFrame(_compressionSession, |
| 494 | pixelBuffer, |
| 495 | presentationTimeStamp, |
| 496 | kCMTimeInvalid, |
| 497 | frameProperties, |
| 498 | encodeParams.release(), |
| 499 | nullptr); |
| 500 | if (frameProperties) { |
| 501 | CFRelease(frameProperties); |
| 502 | } |
| 503 | if (pixelBuffer) { |
| 504 | CVBufferRelease(pixelBuffer); |
| 505 | } |
| 506 |
| 507 | if (status == kVTInvalidSessionErr) { |
| 508 | // This error occurs when entering foreground after backgrounding the app. |
| 509 | RTC_LOG(LS_ERROR) << "Invalid compression session, resetting."; |
| 510 | [self resetCompressionSessionWithPixelFormat:[self pixelFormatOfFrame:frame]]; |
| 511 |
| 512 | return WEBRTC_VIDEO_CODEC_NO_OUTPUT; |
| 513 | } else if (status == kVTVideoEncoderMalfunctionErr) { |
| 514 | // Sometimes the encoder malfunctions and needs to be restarted. |
| 515 | RTC_LOG(LS_ERROR) |
| 516 | << "Encountered video encoder malfunction error. Resetting compression session."; |
| 517 | [self resetCompressionSessionWithPixelFormat:[self pixelFormatOfFrame:frame]]; |
| 518 |
| 519 | return WEBRTC_VIDEO_CODEC_NO_OUTPUT; |
| 520 | } else if (status != noErr) { |
| 521 | RTC_LOG(LS_ERROR) << "Failed to encode frame with code: " << status; |
| 522 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 523 | } |
| 524 | return WEBRTC_VIDEO_CODEC_OK; |
| 525 | } |
| 526 |
| 527 | - (void)setCallback:(RTCVideoEncoderCallback)callback { |
| 528 | _callback = callback; |
| 529 | } |
| 530 |
| 531 | - (int)setBitrate:(uint32_t)bitrateKbit framerate:(uint32_t)framerate { |
| 532 | _targetBitrateBps = 1000 * bitrateKbit; |
| 533 | _bitrateAdjuster->SetTargetBitrateBps(_targetBitrateBps); |
| 534 | if (framerate > _maxAllowedFrameRate && _maxAllowedFrameRate > 0) { |
| 535 | RTC_LOG(LS_WARNING) << "Encoder frame rate setting " << framerate << " is larger than the " |
| 536 | << "maximal allowed frame rate " << _maxAllowedFrameRate << "."; |
| 537 | } |
| 538 | framerate = MIN(framerate, _maxAllowedFrameRate); |
| 539 | [self setBitrateBps:_bitrateAdjuster->GetAdjustedBitrateBps() frameRate:framerate]; |
| 540 | return WEBRTC_VIDEO_CODEC_OK; |
| 541 | } |
| 542 |
| 543 | - (NSInteger)resolutionAlignment { |
| 544 | return 1; |
| 545 | } |
| 546 |
| 547 | - (BOOL)applyAlignmentToAllSimulcastLayers { |
| 548 | return NO; |
| 549 | } |
| 550 |
| 551 | - (BOOL)supportsNativeHandle { |
| 552 | return YES; |
| 553 | } |
| 554 |
| 555 | #pragma mark - Private |
| 556 |
| 557 | - (NSInteger)releaseEncoder { |
| 558 | // Need to destroy so that the session is invalidated and won't use the |
| 559 | // callback anymore. Do not remove callback until the session is invalidated |
| 560 | // since async encoder callbacks can occur until invalidation. |
| 561 | [self destroyCompressionSession]; |
| 562 | _callback = nullptr; |
| 563 | return WEBRTC_VIDEO_CODEC_OK; |
| 564 | } |
| 565 |
| 566 | - (OSType)pixelFormatOfFrame:(RTCVideoFrame *)frame { |
| 567 | // Use NV12 for non-native frames. |
| 568 | if ([frame.buffer isKindOfClass:[RTCCVPixelBuffer class]]) { |
| 569 | RTCCVPixelBuffer *rtcPixelBuffer = (RTCCVPixelBuffer *)frame.buffer; |
| 570 | return CVPixelBufferGetPixelFormatType(rtcPixelBuffer.pixelBuffer); |
| 571 | } |
| 572 |
| 573 | return kNV12PixelFormat; |
| 574 | } |
| 575 |
| 576 | - (BOOL)resetCompressionSessionIfNeededWithFrame:(RTCVideoFrame *)frame { |
| 577 | BOOL resetCompressionSession = NO; |
| 578 |
| 579 | // If we're capturing native frames in another pixel format than the compression session is |
| 580 | // configured with, make sure the compression session is reset using the correct pixel format. |
| 581 | OSType framePixelFormat = [self pixelFormatOfFrame:frame]; |
| 582 |
| 583 | if (_compressionSession) { |
| 584 | _pixelBufferPool = VTCompressionSessionGetPixelBufferPool(_compressionSession); |
| 585 | // The pool attribute `kCVPixelBufferPixelFormatTypeKey` can contain either an array of pixel |
| 586 | // formats or a single pixel format. |
| 587 | NSDictionary *poolAttributes = |
| 588 | (__bridge NSDictionary *)CVPixelBufferPoolGetPixelBufferAttributes(_pixelBufferPool); |
| 589 | id pixelFormats = |
| 590 | [poolAttributes objectForKey:(__bridge NSString *)kCVPixelBufferPixelFormatTypeKey]; |
| 591 | NSArray<NSNumber *> *compressionSessionPixelFormats = nil; |
| 592 | if ([pixelFormats isKindOfClass:[NSArray class]]) { |
| 593 | compressionSessionPixelFormats = (NSArray *)pixelFormats; |
| 594 | } else if ([pixelFormats isKindOfClass:[NSNumber class]]) { |
| 595 | compressionSessionPixelFormats = @[ (NSNumber *)pixelFormats ]; |
| 596 | } |
| 597 |
| 598 | if (![compressionSessionPixelFormats |
| 599 | containsObject:[NSNumber numberWithLong:framePixelFormat]]) { |
| 600 | resetCompressionSession = YES; |
| 601 | RTC_LOG(LS_INFO) << "Resetting compression session due to non-matching pixel format."; |
| 602 | } |
| 603 | } else { |
| 604 | resetCompressionSession = YES; |
| 605 | } |
| 606 |
| 607 | if (resetCompressionSession) { |
| 608 | [self resetCompressionSessionWithPixelFormat:framePixelFormat]; |
| 609 | } |
| 610 | return resetCompressionSession; |
| 611 | } |
| 612 |
| 613 | - (int)resetCompressionSessionWithPixelFormat:(OSType)framePixelFormat { |
| 614 | [self destroyCompressionSession]; |
| 615 |
| 616 | // Set source image buffer attributes. These attributes will be present on |
| 617 | // buffers retrieved from the encoder's pixel buffer pool. |
| 618 | const size_t attributesSize = 3; |
| 619 | CFTypeRef keys[attributesSize] = { |
| 620 | #if defined(WEBRTC_IOS) |
| 621 | kCVPixelBufferOpenGLESCompatibilityKey, |
| 622 | #elif defined(WEBRTC_MAC) |
| 623 | kCVPixelBufferOpenGLCompatibilityKey, |
| 624 | #endif |
| 625 | kCVPixelBufferIOSurfacePropertiesKey, |
| 626 | kCVPixelBufferPixelFormatTypeKey |
| 627 | }; |
| 628 | CFDictionaryRef ioSurfaceValue = CreateCFTypeDictionary(nullptr, nullptr, 0); |
| 629 | int64_t pixelFormatType = framePixelFormat; |
| 630 | CFNumberRef pixelFormat = CFNumberCreate(nullptr, kCFNumberLongType, &pixelFormatType); |
| 631 | CFTypeRef values[attributesSize] = {kCFBooleanTrue, ioSurfaceValue, pixelFormat}; |
| 632 | CFDictionaryRef sourceAttributes = CreateCFTypeDictionary(keys, values, attributesSize); |
| 633 | if (ioSurfaceValue) { |
| 634 | CFRelease(ioSurfaceValue); |
| 635 | ioSurfaceValue = nullptr; |
| 636 | } |
| 637 | if (pixelFormat) { |
| 638 | CFRelease(pixelFormat); |
| 639 | pixelFormat = nullptr; |
| 640 | } |
| 641 | CFMutableDictionaryRef encoder_specs = nullptr; |
| 642 | #if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS) |
| 643 | // Currently hw accl is supported above 360p on mac, below 360p |
| 644 | // the compression session will be created with hw accl disabled. |
| 645 | encoder_specs = CFDictionaryCreateMutable( |
| 646 | nullptr, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); |
| 647 | CFDictionarySetValue(encoder_specs, |
| 648 | kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder, |
| 649 | kCFBooleanTrue); |
| 650 | #endif |
| 651 | OSStatus status = |
| 652 | VTCompressionSessionCreate(nullptr, // use default allocator |
| 653 | _width, |
| 654 | _height, |
| 655 | kCMVideoCodecType_H264, |
| 656 | encoder_specs, // use hardware accelerated encoder if available |
| 657 | sourceAttributes, |
| 658 | nullptr, // use default compressed data allocator |
| 659 | compressionOutputCallback, |
| 660 | nullptr, |
| 661 | &_compressionSession); |
| 662 | if (sourceAttributes) { |
| 663 | CFRelease(sourceAttributes); |
| 664 | sourceAttributes = nullptr; |
| 665 | } |
| 666 | if (encoder_specs) { |
| 667 | CFRelease(encoder_specs); |
| 668 | encoder_specs = nullptr; |
| 669 | } |
| 670 | if (status != noErr) { |
| 671 | RTC_LOG(LS_ERROR) << "Failed to create compression session: " << status; |
| 672 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 673 | } |
| 674 | #if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS) |
| 675 | CFBooleanRef hwaccl_enabled = nullptr; |
| 676 | status = VTSessionCopyProperty(_compressionSession, |
| 677 | kVTCompressionPropertyKey_UsingHardwareAcceleratedVideoEncoder, |
| 678 | nullptr, |
| 679 | &hwaccl_enabled); |
| 680 | if (status == noErr && (CFBooleanGetValue(hwaccl_enabled))) { |
| 681 | RTC_LOG(LS_INFO) << "Compression session created with hw accl enabled"; |
| 682 | } else { |
| 683 | RTC_LOG(LS_INFO) << "Compression session created with hw accl disabled"; |
| 684 | } |
| 685 | #endif |
| 686 | [self configureCompressionSession]; |
| 687 |
| 688 | // The pixel buffer pool is dependent on the compression session so if the session is reset, the |
| 689 | // pool should be reset as well. |
| 690 | _pixelBufferPool = VTCompressionSessionGetPixelBufferPool(_compressionSession); |
| 691 |
| 692 | return WEBRTC_VIDEO_CODEC_OK; |
| 693 | } |
| 694 |
| 695 | - (void)configureCompressionSession { |
| 696 | RTC_DCHECK(_compressionSession); |
| 697 | SetVTSessionProperty(_compressionSession, kVTCompressionPropertyKey_RealTime, false); |
| 698 | SetVTSessionProperty(_compressionSession, |
| 699 | kVTCompressionPropertyKey_ProfileLevel, |
| 700 | ExtractProfile(*_profile_level_id)); |
| 701 | SetVTSessionProperty(_compressionSession, kVTCompressionPropertyKey_AllowFrameReordering, false); |
| 702 | [self setEncoderBitrateBps:_targetBitrateBps frameRate:_encoderFrameRate]; |
| 703 | // TODO(tkchin): Look at entropy mode and colorspace matrices. |
| 704 | // TODO(tkchin): Investigate to see if there's any way to make this work. |
| 705 | // May need it to interop with Android. Currently this call just fails. |
| 706 | // On inspecting encoder output on iOS8, this value is set to 6. |
| 707 | // internal::SetVTSessionProperty(compression_session_, |
| 708 | // kVTCompressionPropertyKey_MaxFrameDelayCount, |
| 709 | // 1); |
| 710 |
| 711 | // Set a relatively large value for keyframe emission (7200 frames or 4 minutes). |
| 712 | SetVTSessionProperty(_compressionSession, kVTCompressionPropertyKey_MaxKeyFrameInterval, 7200); |
| 713 | SetVTSessionProperty( |
| 714 | _compressionSession, kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration, 240); |
| 715 | } |
| 716 |
| 717 | - (void)destroyCompressionSession { |
| 718 | if (_compressionSession) { |
| 719 | VTCompressionSessionInvalidate(_compressionSession); |
| 720 | CFRelease(_compressionSession); |
| 721 | _compressionSession = nullptr; |
| 722 | _pixelBufferPool = nullptr; |
| 723 | } |
| 724 | } |
| 725 |
| 726 | - (NSString *)implementationName { |
| 727 | return @"VideoToolbox"; |
| 728 | } |
| 729 |
| 730 | - (void)setBitrateBps:(uint32_t)bitrateBps frameRate:(uint32_t)frameRate { |
| 731 | if (_encoderBitrateBps != bitrateBps || _encoderFrameRate != frameRate) { |
| 732 | [self setEncoderBitrateBps:bitrateBps frameRate:frameRate]; |
| 733 | } |
| 734 | } |
| 735 |
| 736 | - (void)setEncoderBitrateBps:(uint32_t)bitrateBps frameRate:(uint32_t)frameRate { |
| 737 | if (_compressionSession) { |
| 738 | RTC_LOG(LS_ERROR) << "TGRTCVideoEncoderH264: setting bitrate to " << bitrateBps / 1024 << " kbit/s"; |
| 739 |
| 740 | SetVTSessionProperty(_compressionSession, kVTCompressionPropertyKey_AverageBitRate, bitrateBps); |
| 741 |
| 742 | // With zero |_maxAllowedFrameRate|, we fall back to automatic frame rate detection. |
| 743 | if (_maxAllowedFrameRate > 0) { |
| 744 | SetVTSessionProperty( |
| 745 | _compressionSession, kVTCompressionPropertyKey_ExpectedFrameRate, frameRate); |
| 746 | } |
| 747 |
| 748 | // TODO(tkchin): Add a helper method to set array value. |
| 749 | int64_t dataLimitBytesPerSecondValue = |
| 750 | static_cast<int64_t>(bitrateBps * kLimitToAverageBitRateFactor / 8); |
| 751 | CFNumberRef bytesPerSecond = |
| 752 | CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, &dataLimitBytesPerSecondValue); |
| 753 | int64_t oneSecondValue = 1; |
| 754 | CFNumberRef oneSecond = |
| 755 | CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, &oneSecondValue); |
| 756 | const void *nums[2] = {bytesPerSecond, oneSecond}; |
| 757 | CFArrayRef dataRateLimits = CFArrayCreate(nullptr, nums, 2, &kCFTypeArrayCallBacks); |
| 758 | OSStatus status = VTSessionSetProperty( |
| 759 | _compressionSession, kVTCompressionPropertyKey_DataRateLimits, dataRateLimits); |
| 760 | if (bytesPerSecond) { |
| 761 | CFRelease(bytesPerSecond); |
| 762 | } |
| 763 | if (oneSecond) { |
| 764 | CFRelease(oneSecond); |
| 765 | } |
| 766 | if (dataRateLimits) { |
| 767 | CFRelease(dataRateLimits); |
| 768 | } |
| 769 | if (status != noErr) { |
| 770 | RTC_LOG(LS_ERROR) << "Failed to set data rate limit with code: " << status; |
| 771 | } |
| 772 |
| 773 | _encoderBitrateBps = bitrateBps; |
| 774 | _encoderFrameRate = frameRate; |
| 775 | } |
| 776 | } |
| 777 |
| 778 | - (void)frameWasEncoded:(OSStatus)status |
| 779 | flags:(VTEncodeInfoFlags)infoFlags |
| 780 | sampleBuffer:(CMSampleBufferRef)sampleBuffer |
| 781 | codecSpecificInfo:(id<RTCCodecSpecificInfo>)codecSpecificInfo |
| 782 | width:(int32_t)width |
| 783 | height:(int32_t)height |
| 784 | renderTimeMs:(int64_t)renderTimeMs |
| 785 | timestamp:(uint32_t)timestamp |
| 786 | rotation:(RTCVideoRotation)rotation { |
| 787 | if (status != noErr) { |
| 788 | RTC_LOG(LS_ERROR) << "H264 encode failed with code: " << status; |
| 789 | return; |
| 790 | } |
| 791 | if (infoFlags & kVTEncodeInfo_FrameDropped) { |
| 792 | RTC_LOG(LS_INFO) << "H264 encode dropped frame."; |
| 793 | return; |
| 794 | } |
| 795 |
| 796 | BOOL isKeyframe = NO; |
| 797 | CFArrayRef attachments = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, 0); |
| 798 | if (attachments != nullptr && CFArrayGetCount(attachments)) { |
| 799 | CFDictionaryRef attachment = |
| 800 | static_cast<CFDictionaryRef>(CFArrayGetValueAtIndex(attachments, 0)); |
| 801 | isKeyframe = !CFDictionaryContainsKey(attachment, kCMSampleAttachmentKey_NotSync); |
| 802 | } |
| 803 |
| 804 | if (isKeyframe) { |
| 805 | RTC_LOG(LS_INFO) << "Generated keyframe"; |
| 806 | } |
| 807 |
| 808 | __block std::unique_ptr<rtc::Buffer> buffer = std::make_unique<rtc::Buffer>(); |
| 809 | { |
| 810 | bool result = webrtc::H264CMSampleBufferToAnnexBBuffer(sampleBuffer, isKeyframe, buffer.get()); |
| 811 | if (!result) { |
| 812 | return; |
| 813 | } |
| 814 | } |
| 815 |
| 816 | RTCEncodedImage *frame = [[RTCEncodedImage alloc] init]; |
| 817 | // This assumes ownership of `buffer` and is responsible for freeing it when done. |
| 818 | frame.buffer = [[NSData alloc] initWithBytesNoCopy:buffer->data() |
| 819 | length:buffer->size() |
| 820 | deallocator:^(void *bytes, NSUInteger size) { |
| 821 | buffer.reset(); |
| 822 | }]; |
| 823 | frame.encodedWidth = width; |
| 824 | frame.encodedHeight = height; |
| 825 | //frame.completeFrame = YES; |
| 826 | frame.frameType = isKeyframe ? RTCFrameTypeVideoFrameKey : RTCFrameTypeVideoFrameDelta; |
| 827 | frame.captureTimeMs = renderTimeMs; |
| 828 | frame.timeStamp = timestamp; |
| 829 | frame.rotation = rotation; |
| 830 | frame.contentType = (_mode == RTCVideoCodecModeScreensharing) ? RTCVideoContentTypeScreenshare : |
| 831 | RTCVideoContentTypeUnspecified; |
| 832 | frame.flags = webrtc::VideoSendTiming::kInvalid; |
| 833 |
| 834 | int qp; |
| 835 | _h264BitstreamParser.ParseBitstream(*buffer); |
| 836 | frame.qp = @(_h264BitstreamParser.GetLastSliceQp().value_or(-1)); |
| 837 |
| 838 | BOOL res = _callback(frame, codecSpecificInfo); |
| 839 | if (!res) { |
| 840 | RTC_LOG(LS_ERROR) << "Encode callback failed"; |
| 841 | return; |
| 842 | } |
| 843 | _bitrateAdjuster->Update(frame.buffer.length); |
| 844 | } |
| 845 |
| 846 | - (nullable RTCVideoEncoderQpThresholds *)scalingSettings { |
| 847 | return [[RTCVideoEncoderQpThresholds alloc] initWithThresholdsLow:kLowH264QpThreshold |
| 848 | high:kHighH264QpThreshold]; |
| 849 | } |
| 850 |
| 851 | @end |
| 852 |