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