blob: f6690b6d86188241480e3f3e9f5197660579fffa [file] [log] [blame]
magjed73c0eb52017-08-07 06:55:28 -07001/*
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 Carlsson7bca8ca2018-08-30 09:30:29 +020012#import "RTCVideoEncoderH264.h"
magjed73c0eb52017-08-07 06:55:28 -070013
14#import <VideoToolbox/VideoToolbox.h>
15#include <vector>
16
17#if defined(WEBRTC_IOS)
Anders Carlsson7bca8ca2018-08-30 09:30:29 +020018#import "helpers/UIDevice+RTCDevice.h"
magjed73c0eb52017-08-07 06:55:28 -070019#endif
Anders Carlsson7bca8ca2018-08-30 09:30:29 +020020#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 Bonadei92ea95e2017-09-15 06:47:31 +020032#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"
39#include "rtc_base/timeutils.h"
Anders Carlsson7bca8ca2018-08-30 09:30:29 +020040#include "sdk/objc/components/video_codec/nalu_rewriter.h"
Mirko Bonadei65432062017-12-11 09:32:13 +010041#include "third_party/libyuv/include/libyuv/convert_from.h"
magjed73c0eb52017-08-07 06:55:28 -070042
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 Helgason0bf60712017-09-25 10:26:42 +020057namespace { // anonymous namespace
58
magjed73c0eb52017-08-07 06:55:28 -070059// 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.
62const 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
65const int kLowH264QpThreshold = 28;
66const int kHighH264QpThreshold = 39;
67
Anders Carlssonf3ee3b72017-10-23 15:23:00 +020068const OSType kNV12PixelFormat = kCVPixelFormatType_420YpCbCr8BiPlanarFullRange;
69
magjed73c0eb52017-08-07 06:55:28 -070070// Struct that we pass to the encoder per frame to encode. We receive it again
71// in the encoder callback.
72struct 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 Carlssonf3ee3b72017-10-23 15:23:00 +0200100bool CopyVideoFrameToNV12PixelBuffer(id<RTCI420Buffer> frameBuffer, CVPixelBufferRef pixelBuffer) {
magjed73c0eb52017-08-07 06:55:28 -0700101 RTC_DCHECK(pixelBuffer);
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200102 RTC_DCHECK_EQ(CVPixelBufferGetPixelFormatType(pixelBuffer), kNV12PixelFormat);
magjed73c0eb52017-08-07 06:55:28 -0700103 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 Bonadei675513b2017-11-09 11:09:25 +0100108 RTC_LOG(LS_ERROR) << "Failed to lock base address: " << cvRet;
magjed73c0eb52017-08-07 06:55:28 -0700109 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 Bonadei675513b2017-11-09 11:09:25 +0100130 RTC_LOG(LS_ERROR) << "Error converting I420 VideoFrame to NV12 :" << ret;
magjed73c0eb52017-08-07 06:55:28 -0700131 return false;
132 }
133 return true;
134}
135
136CVPixelBufferRef CreatePixelBuffer(CVPixelBufferPoolRef pixel_buffer_pool) {
137 if (!pixel_buffer_pool) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100138 RTC_LOG(LS_ERROR) << "Failed to get pixel buffer pool.";
magjed73c0eb52017-08-07 06:55:28 -0700139 return nullptr;
140 }
141 CVPixelBufferRef pixel_buffer;
142 CVReturn ret = CVPixelBufferPoolCreatePixelBuffer(nullptr, pixel_buffer_pool, &pixel_buffer);
143 if (ret != kCVReturnSuccess) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100144 RTC_LOG(LS_ERROR) << "Failed to create pixel buffer: " << ret;
magjed73c0eb52017-08-07 06:55:28 -0700145 // 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.
154void compressionOutputCallback(void *encoder,
155 void *params,
156 OSStatus status,
157 VTEncodeInfoFlags infoFlags,
158 CMSampleBufferRef sampleBuffer) {
Anders Carlssoned2b1c92017-11-02 13:15:15 +0100159 if (!params) {
160 // If there are pending callbacks when the encoder is destroyed, this can happen.
161 return;
162 }
magjed73c0eb52017-08-07 06:55:28 -0700163 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 Jedvert8b4e92d2018-04-13 15:36:43 +0200176// Extract VideoToolbox profile out of the webrtc::SdpVideoFormat. If there is
177// no specific VideoToolbox profile for the specified level, AutoLevel will be
magjed73c0eb52017-08-07 06:55:28 -0700178// returned. The user must initialize the encoder with a resolution and
179// framerate conforming to the selected H264 level regardless.
Anders Carlsson7e042812017-10-05 16:55:38 +0200180CFStringRef ExtractProfile(webrtc::SdpVideoFormat videoFormat) {
Danil Chapovalov196100e2018-06-21 10:17:24 +0200181 const absl::optional<webrtc::H264::ProfileLevelId> profile_level_id =
Anders Carlsson7e042812017-10-05 16:55:38 +0200182 webrtc::H264::ParseSdpProfileLevelId(videoFormat.parameters);
magjed73c0eb52017-08-07 06:55:28 -0700183 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 Helgason0bf60712017-09-25 10:26:42 +0200281} // namespace
magjed73c0eb52017-08-07 06:55:28 -0700282
283@implementation RTCVideoEncoderH264 {
284 RTCVideoCodecInfo *_codecInfo;
Danielaf3282822017-09-29 14:14:54 +0200285 std::unique_ptr<webrtc::BitrateAdjuster> _bitrateAdjuster;
magjed73c0eb52017-08-07 06:55:28 -0700286 uint32_t _targetBitrateBps;
Qiang Chen59a01b02018-11-19 10:30:04 -0800287 uint32_t _encoderFrameRate;
magjed73c0eb52017-08-07 06:55:28 -0700288 uint32_t _encoderBitrateBps;
289 RTCH264PacketizationMode _packetizationMode;
290 CFStringRef _profile;
291 RTCVideoEncoderCallback _callback;
292 int32_t _width;
293 int32_t _height;
294 VTCompressionSessionRef _compressionSession;
Peter Hanspersf9052862018-07-26 10:41:35 +0200295 CVPixelBufferPoolRef _pixelBufferPool;
magjed73c0eb52017-08-07 06:55:28 -0700296 RTCVideoCodecMode _mode;
297
298 webrtc::H264BitstreamParser _h264BitstreamParser;
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200299 std::vector<uint8_t> _frameScaleBuffer;
magjed73c0eb52017-08-07 06:55:28 -0700300}
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öller2cb7b5e2018-04-19 10:02:26 +0200312 _bitrateAdjuster.reset(new webrtc::BitrateAdjuster(.5, .95));
magjed73c0eb52017-08-07 06:55:28 -0700313 _packetizationMode = RTCH264PacketizationModeNonInterleaved;
Anders Carlsson7e042812017-10-05 16:55:38 +0200314 _profile = ExtractProfile([codecInfo nativeSdpVideoFormat]);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100315 RTC_LOG(LS_INFO) << "Using profile " << CFStringToString(_profile);
Kári Tristan Helgasonfc313dc2017-10-20 11:01:22 +0200316 RTC_CHECK([codecInfo.name isEqualToString:kRTCVideoCodecH264Name]);
magjed73c0eb52017-08-07 06:55:28 -0700317 }
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 Helgasonfc313dc2017-10-20 11:01:22 +0200328 RTC_DCHECK([settings.name isEqualToString:kRTCVideoCodecH264Name]);
magjed73c0eb52017-08-07 06:55:28 -0700329
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 Helgason87c54632018-04-05 09:56:14 +0200335 _targetBitrateBps = settings.startBitrate * 1000; // startBitrate is in kbps.
magjed73c0eb52017-08-07 06:55:28 -0700336 _bitrateAdjuster->SetTargetBitrateBps(_targetBitrateBps);
Qiang Chen59a01b02018-11-19 10:30:04 -0800337 _encoderFrameRate = settings.maxFramerate;
magjed73c0eb52017-08-07 06:55:28 -0700338
339 // TODO(tkchin): Try setting payload size via
340 // kVTCompressionPropertyKey_MaxH264SliceBytes.
341
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200342 return [self resetCompressionSessionWithPixelFormat:kNV12PixelFormat];
magjed73c0eb52017-08-07 06:55:28 -0700343}
344
345- (NSInteger)encode:(RTCVideoFrame *)frame
Peter Hanspersd9b64cd2018-01-12 16:16:18 +0100346 codecSpecificInfo:(nullable id<RTCCodecSpecificInfo>)codecSpecificInfo
magjed73c0eb52017-08-07 06:55:28 -0700347 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 }
magjed73c0eb52017-08-07 06:55:28 -0700353 BOOL isKeyframeRequired = NO;
354
355 // Get a pixel buffer from the pool and copy frame data over.
Peter Hanspersf9052862018-07-26 10:41:35 +0200356 if ([self resetCompressionSessionIfNeededWithFrame:frame]) {
magjed73c0eb52017-08-07 06:55:28 -0700357 isKeyframeRequired = YES;
magjed73c0eb52017-08-07 06:55:28 -0700358 }
magjed73c0eb52017-08-07 06:55:28 -0700359
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 Hanspersf9052862018-07-26 10:41:35 +0200373 pixelBuffer = CreatePixelBuffer(_pixelBufferPool);
magjed73c0eb52017-08-07 06:55:28 -0700374 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 Carlssonf3ee3b72017-10-23 15:23:00 +0200382 _frameScaleBuffer.resize(size);
magjed73c0eb52017-08-07 06:55:28 -0700383 } else {
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200384 _frameScaleBuffer.clear();
magjed73c0eb52017-08-07 06:55:28 -0700385 }
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200386 _frameScaleBuffer.shrink_to_fit();
387 if (![rtcPixelBuffer cropAndScaleTo:pixelBuffer withTempBuffer:_frameScaleBuffer.data()]) {
Peter Hanspers56df67b2018-06-01 14:21:10 +0200388 CVBufferRelease(pixelBuffer);
magjed73c0eb52017-08-07 06:55:28 -0700389 return WEBRTC_VIDEO_CODEC_ERROR;
390 }
391 }
392 }
393
394 if (!pixelBuffer) {
395 // We did not have a native frame buffer
Peter Hanspersf9052862018-07-26 10:41:35 +0200396 pixelBuffer = CreatePixelBuffer(_pixelBufferPool);
magjed73c0eb52017-08-07 06:55:28 -0700397 if (!pixelBuffer) {
398 return WEBRTC_VIDEO_CODEC_ERROR;
399 }
400 RTC_DCHECK(pixelBuffer);
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200401 if (!CopyVideoFrameToNV12PixelBuffer([frame.buffer toI420], pixelBuffer)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100402 RTC_LOG(LS_ERROR) << "Failed to copy frame data.";
magjed73c0eb52017-08-07 06:55:28 -0700403 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 Chen59a01b02018-11-19 10:30:04 -0800437 [self setBitrateBps:_bitrateAdjuster->GetAdjustedBitrateBps() frameRate:_encoderFrameRate];
magjed73c0eb52017-08-07 06:55:28 -0700438
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 Hanspersf9052862018-07-26 10:41:35 +0200452
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 Bonadei675513b2017-11-09 11:09:25 +0100460 RTC_LOG(LS_ERROR) << "Failed to encode frame with code: " << status;
magjed73c0eb52017-08-07 06:55:28 -0700461 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 Chen59a01b02018-11-19 10:30:04 -0800473 [self setBitrateBps:_bitrateAdjuster->GetAdjustedBitrateBps() frameRate:framerate];
magjed73c0eb52017-08-07 06:55:28 -0700474 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 Hanspersf9052862018-07-26 10:41:35 +0200488- (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 Carlssonf3ee3b72017-10-23 15:23:00 +0200499 BOOL resetCompressionSession = NO;
500
Anders Carlsson5b07c242018-04-13 14:12:22 +0200501 // 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 Hanspersf9052862018-07-26 10:41:35 +0200503 OSType framePixelFormat = [self pixelFormatOfFrame:frame];
Anders Carlsson5b07c242018-04-13 14:12:22 +0200504
Peter Hanspersf9052862018-07-26 10:41:35 +0200505 if (_compressionSession) {
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200506 // The pool attribute `kCVPixelBufferPixelFormatTypeKey` can contain either an array of pixel
507 // formats or a single pixel format.
508 NSDictionary *poolAttributes =
Peter Hanspersf9052862018-07-26 10:41:35 +0200509 (__bridge NSDictionary *)CVPixelBufferPoolGetPixelBufferAttributes(_pixelBufferPool);
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200510 id pixelFormats =
511 [poolAttributes objectForKey:(__bridge NSString *)kCVPixelBufferPixelFormatTypeKey];
512 NSArray<NSNumber *> *compressionSessionPixelFormats = nil;
513 if ([pixelFormats isKindOfClass:[NSArray class]]) {
514 compressionSessionPixelFormats = (NSArray *)pixelFormats;
Peter Hanspersf9052862018-07-26 10:41:35 +0200515 } else if ([pixelFormats isKindOfClass:[NSNumber class]]) {
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200516 compressionSessionPixelFormats = @[ (NSNumber *)pixelFormats ];
517 }
518
519 if (![compressionSessionPixelFormats
520 containsObject:[NSNumber numberWithLong:framePixelFormat]]) {
521 resetCompressionSession = YES;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100522 RTC_LOG(LS_INFO) << "Resetting compression session due to non-matching pixel format.";
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200523 }
Peter Hanspersf9052862018-07-26 10:41:35 +0200524 } else {
525 resetCompressionSession = YES;
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200526 }
527
528 if (resetCompressionSession) {
529 [self resetCompressionSessionWithPixelFormat:framePixelFormat];
530 }
531 return resetCompressionSession;
532}
533
534- (int)resetCompressionSessionWithPixelFormat:(OSType)framePixelFormat {
magjed73c0eb52017-08-07 06:55:28 -0700535 [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 Carlssonf3ee3b72017-10-23 15:23:00 +0200550 int64_t pixelFormatType = framePixelFormat;
551 CFNumberRef pixelFormat = CFNumberCreate(nullptr, kCFNumberLongType, &pixelFormatType);
magjed73c0eb52017-08-07 06:55:28 -0700552 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 }
kthelgasona4955b42017-08-24 04:22:58 -0700562 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);
magjed73c0eb52017-08-07 06:55:28 -0700583 if (sourceAttributes) {
584 CFRelease(sourceAttributes);
585 sourceAttributes = nullptr;
586 }
kthelgasona4955b42017-08-24 04:22:58 -0700587 if (encoder_specs) {
588 CFRelease(encoder_specs);
589 encoder_specs = nullptr;
590 }
magjed73c0eb52017-08-07 06:55:28 -0700591 if (status != noErr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100592 RTC_LOG(LS_ERROR) << "Failed to create compression session: " << status;
magjed73c0eb52017-08-07 06:55:28 -0700593 return WEBRTC_VIDEO_CODEC_ERROR;
594 }
kthelgasona4955b42017-08-24 04:22:58 -0700595#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 Bonadei675513b2017-11-09 11:09:25 +0100602 RTC_LOG(LS_INFO) << "Compression session created with hw accl enabled";
kthelgasona4955b42017-08-24 04:22:58 -0700603 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100604 RTC_LOG(LS_INFO) << "Compression session created with hw accl disabled";
kthelgasona4955b42017-08-24 04:22:58 -0700605 }
606#endif
magjed73c0eb52017-08-07 06:55:28 -0700607 [self configureCompressionSession];
Peter Hanspersf9052862018-07-26 10:41:35 +0200608
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
magjed73c0eb52017-08-07 06:55:28 -0700613 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 Chen59a01b02018-11-19 10:30:04 -0800621 [self setEncoderBitrateBps:_targetBitrateBps frameRate:_encoderFrameRate];
magjed73c0eb52017-08-07 06:55:28 -0700622 // 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 Hanspersf9052862018-07-26 10:41:35 +0200641 _pixelBufferPool = nullptr;
magjed73c0eb52017-08-07 06:55:28 -0700642 }
643}
644
645- (NSString *)implementationName {
646 return @"VideoToolbox";
647}
648
Qiang Chen59a01b02018-11-19 10:30:04 -0800649- (void)setBitrateBps:(uint32_t)bitrateBps frameRate:(uint32_t)frameRate {
650 if (_encoderBitrateBps != bitrateBps || _encoderFrameRate != frameRate) {
651 [self setEncoderBitrateBps:bitrateBps frameRate:frameRate];
magjed73c0eb52017-08-07 06:55:28 -0700652 }
653}
654
Qiang Chen59a01b02018-11-19 10:30:04 -0800655- (void)setEncoderBitrateBps:(uint32_t)bitrateBps frameRate:(uint32_t)frameRate {
magjed73c0eb52017-08-07 06:55:28 -0700656 if (_compressionSession) {
657 SetVTSessionProperty(_compressionSession, kVTCompressionPropertyKey_AverageBitRate, bitrateBps);
Qiang Chen59a01b02018-11-19 10:30:04 -0800658 SetVTSessionProperty(
659 _compressionSession, kVTCompressionPropertyKey_ExpectedFrameRate, frameRate);
magjed73c0eb52017-08-07 06:55:28 -0700660
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 Yaroshevich27af5db2018-04-10 19:43:20 +0300683 RTC_LOG(LS_ERROR) << "Failed to set data rate limit with code: " << status;
magjed73c0eb52017-08-07 06:55:28 -0700684 }
685
686 _encoderBitrateBps = bitrateBps;
Qiang Chen59a01b02018-11-19 10:30:04 -0800687 _encoderFrameRate = frameRate;
magjed73c0eb52017-08-07 06:55:28 -0700688 }
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 Yaroshevich27af5db2018-04-10 19:43:20 +0300701 RTC_LOG(LS_ERROR) << "H264 encode failed with code: " << status;
magjed73c0eb52017-08-07 06:55:28 -0700702 return;
703 }
704 if (infoFlags & kVTEncodeInfo_FrameDropped) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100705 RTC_LOG(LS_INFO) << "H264 encode dropped frame.";
magjed73c0eb52017-08-07 06:55:28 -0700706 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 Bonadei675513b2017-11-09 11:09:25 +0100718 RTC_LOG(LS_INFO) << "Generated keyframe";
magjed73c0eb52017-08-07 06:55:28 -0700719 }
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 {
kthelgasonf8084d42017-08-30 04:47:10 -0700726 std::unique_ptr<webrtc::RTPFragmentationHeader> header_cpp;
magjed73c0eb52017-08-07 06:55:28 -0700727 bool result =
728 H264CMSampleBufferToAnnexBBuffer(sampleBuffer, isKeyframe, buffer.get(), &header_cpp);
kthelgasonf8084d42017-08-30 04:47:10 -0700729 header = [[RTCRtpFragmentationHeader alloc] initWithNativeFragmentationHeader:header_cpp.get()];
magjed73c0eb52017-08-07 06:55:28 -0700730 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 Nikolaevskiyb6c462d2018-06-05 15:21:32 +0200746 frame.flags = webrtc::VideoSendTiming::kInvalid;
magjed73c0eb52017-08-07 06:55:28 -0700747
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 Bonadei675513b2017-11-09 11:09:25 +0100755 RTC_LOG(LS_ERROR) << "Encode callback failed";
magjed73c0eb52017-08-07 06:55:28 -0700756 return;
757 }
758 _bitrateAdjuster->Update(frame.buffer.length);
759}
760
Anders Carlsson2ac27392018-09-03 14:17:03 +0200761- (nullable RTCVideoEncoderQpThresholds *)scalingSettings {
magjed73c0eb52017-08-07 06:55:28 -0700762 return [[RTCVideoEncoderQpThresholds alloc] initWithThresholdsLow:kLowH264QpThreshold
763 high:kHighH264QpThreshold];
764}
765
766@end