blob: 16ad1ff47aa9924ce1a68c636f716ecb5fe0fdca [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;
287 uint32_t _encoderBitrateBps;
288 RTCH264PacketizationMode _packetizationMode;
289 CFStringRef _profile;
290 RTCVideoEncoderCallback _callback;
291 int32_t _width;
292 int32_t _height;
293 VTCompressionSessionRef _compressionSession;
Peter Hanspersf9052862018-07-26 10:41:35 +0200294 CVPixelBufferPoolRef _pixelBufferPool;
magjed73c0eb52017-08-07 06:55:28 -0700295 RTCVideoCodecMode _mode;
296
297 webrtc::H264BitstreamParser _h264BitstreamParser;
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200298 std::vector<uint8_t> _frameScaleBuffer;
magjed73c0eb52017-08-07 06:55:28 -0700299}
300
301// .5 is set as a mininum to prevent overcompensating for large temporary
302// overshoots. We don't want to degrade video quality too badly.
303// .95 is set to prevent oscillations. When a lower bitrate is set on the
304// encoder than previously set, its output seems to have a brief period of
305// drastically reduced bitrate, so we want to avoid that. In steady state
306// conditions, 0.95 seems to give us better overall bitrate over long periods
307// of time.
308- (instancetype)initWithCodecInfo:(RTCVideoCodecInfo *)codecInfo {
309 if (self = [super init]) {
310 _codecInfo = codecInfo;
Niels Möller2cb7b5e2018-04-19 10:02:26 +0200311 _bitrateAdjuster.reset(new webrtc::BitrateAdjuster(.5, .95));
magjed73c0eb52017-08-07 06:55:28 -0700312 _packetizationMode = RTCH264PacketizationModeNonInterleaved;
Anders Carlsson7e042812017-10-05 16:55:38 +0200313 _profile = ExtractProfile([codecInfo nativeSdpVideoFormat]);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100314 RTC_LOG(LS_INFO) << "Using profile " << CFStringToString(_profile);
Kári Tristan Helgasonfc313dc2017-10-20 11:01:22 +0200315 RTC_CHECK([codecInfo.name isEqualToString:kRTCVideoCodecH264Name]);
magjed73c0eb52017-08-07 06:55:28 -0700316 }
317 return self;
318}
319
320- (void)dealloc {
321 [self destroyCompressionSession];
322}
323
324- (NSInteger)startEncodeWithSettings:(RTCVideoEncoderSettings *)settings
325 numberOfCores:(int)numberOfCores {
326 RTC_DCHECK(settings);
Kári Tristan Helgasonfc313dc2017-10-20 11:01:22 +0200327 RTC_DCHECK([settings.name isEqualToString:kRTCVideoCodecH264Name]);
magjed73c0eb52017-08-07 06:55:28 -0700328
329 _width = settings.width;
330 _height = settings.height;
331 _mode = settings.mode;
332
333 // We can only set average bitrate on the HW encoder.
Kári Tristan Helgason87c54632018-04-05 09:56:14 +0200334 _targetBitrateBps = settings.startBitrate * 1000; // startBitrate is in kbps.
magjed73c0eb52017-08-07 06:55:28 -0700335 _bitrateAdjuster->SetTargetBitrateBps(_targetBitrateBps);
336
337 // TODO(tkchin): Try setting payload size via
338 // kVTCompressionPropertyKey_MaxH264SliceBytes.
339
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200340 return [self resetCompressionSessionWithPixelFormat:kNV12PixelFormat];
magjed73c0eb52017-08-07 06:55:28 -0700341}
342
343- (NSInteger)encode:(RTCVideoFrame *)frame
Peter Hanspersd9b64cd2018-01-12 16:16:18 +0100344 codecSpecificInfo:(nullable id<RTCCodecSpecificInfo>)codecSpecificInfo
magjed73c0eb52017-08-07 06:55:28 -0700345 frameTypes:(NSArray<NSNumber *> *)frameTypes {
346 RTC_DCHECK_EQ(frame.width, _width);
347 RTC_DCHECK_EQ(frame.height, _height);
348 if (!_callback || !_compressionSession) {
349 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
350 }
magjed73c0eb52017-08-07 06:55:28 -0700351 BOOL isKeyframeRequired = NO;
352
353 // Get a pixel buffer from the pool and copy frame data over.
Peter Hanspersf9052862018-07-26 10:41:35 +0200354 if ([self resetCompressionSessionIfNeededWithFrame:frame]) {
magjed73c0eb52017-08-07 06:55:28 -0700355 isKeyframeRequired = YES;
magjed73c0eb52017-08-07 06:55:28 -0700356 }
magjed73c0eb52017-08-07 06:55:28 -0700357
358 CVPixelBufferRef pixelBuffer = nullptr;
359 if ([frame.buffer isKindOfClass:[RTCCVPixelBuffer class]]) {
360 // Native frame buffer
361 RTCCVPixelBuffer *rtcPixelBuffer = (RTCCVPixelBuffer *)frame.buffer;
362 if (![rtcPixelBuffer requiresCropping]) {
363 // This pixel buffer might have a higher resolution than what the
364 // compression session is configured to. The compression session can
365 // handle that and will output encoded frames in the configured
366 // resolution regardless of the input pixel buffer resolution.
367 pixelBuffer = rtcPixelBuffer.pixelBuffer;
368 CVBufferRetain(pixelBuffer);
369 } else {
370 // Cropping required, we need to crop and scale to a new pixel buffer.
Peter Hanspersf9052862018-07-26 10:41:35 +0200371 pixelBuffer = CreatePixelBuffer(_pixelBufferPool);
magjed73c0eb52017-08-07 06:55:28 -0700372 if (!pixelBuffer) {
373 return WEBRTC_VIDEO_CODEC_ERROR;
374 }
375 int dstWidth = CVPixelBufferGetWidth(pixelBuffer);
376 int dstHeight = CVPixelBufferGetHeight(pixelBuffer);
377 if ([rtcPixelBuffer requiresScalingToWidth:dstWidth height:dstHeight]) {
378 int size =
379 [rtcPixelBuffer bufferSizeForCroppingAndScalingToWidth:dstWidth height:dstHeight];
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200380 _frameScaleBuffer.resize(size);
magjed73c0eb52017-08-07 06:55:28 -0700381 } else {
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200382 _frameScaleBuffer.clear();
magjed73c0eb52017-08-07 06:55:28 -0700383 }
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200384 _frameScaleBuffer.shrink_to_fit();
385 if (![rtcPixelBuffer cropAndScaleTo:pixelBuffer withTempBuffer:_frameScaleBuffer.data()]) {
Peter Hanspers56df67b2018-06-01 14:21:10 +0200386 CVBufferRelease(pixelBuffer);
magjed73c0eb52017-08-07 06:55:28 -0700387 return WEBRTC_VIDEO_CODEC_ERROR;
388 }
389 }
390 }
391
392 if (!pixelBuffer) {
393 // We did not have a native frame buffer
Peter Hanspersf9052862018-07-26 10:41:35 +0200394 pixelBuffer = CreatePixelBuffer(_pixelBufferPool);
magjed73c0eb52017-08-07 06:55:28 -0700395 if (!pixelBuffer) {
396 return WEBRTC_VIDEO_CODEC_ERROR;
397 }
398 RTC_DCHECK(pixelBuffer);
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200399 if (!CopyVideoFrameToNV12PixelBuffer([frame.buffer toI420], pixelBuffer)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100400 RTC_LOG(LS_ERROR) << "Failed to copy frame data.";
magjed73c0eb52017-08-07 06:55:28 -0700401 CVBufferRelease(pixelBuffer);
402 return WEBRTC_VIDEO_CODEC_ERROR;
403 }
404 }
405
406 // Check if we need a keyframe.
407 if (!isKeyframeRequired && frameTypes) {
408 for (NSNumber *frameType in frameTypes) {
409 if ((RTCFrameType)frameType.intValue == RTCFrameTypeVideoFrameKey) {
410 isKeyframeRequired = YES;
411 break;
412 }
413 }
414 }
415
416 CMTime presentationTimeStamp = CMTimeMake(frame.timeStampNs / rtc::kNumNanosecsPerMillisec, 1000);
417 CFDictionaryRef frameProperties = nullptr;
418 if (isKeyframeRequired) {
419 CFTypeRef keys[] = {kVTEncodeFrameOptionKey_ForceKeyFrame};
420 CFTypeRef values[] = {kCFBooleanTrue};
421 frameProperties = CreateCFTypeDictionary(keys, values, 1);
422 }
423
424 std::unique_ptr<RTCFrameEncodeParams> encodeParams;
425 encodeParams.reset(new RTCFrameEncodeParams(self,
426 codecSpecificInfo,
427 _width,
428 _height,
429 frame.timeStampNs / rtc::kNumNanosecsPerMillisec,
430 frame.timeStamp,
431 frame.rotation));
432 encodeParams->codecSpecificInfo.packetizationMode = _packetizationMode;
433
434 // Update the bitrate if needed.
435 [self setBitrateBps:_bitrateAdjuster->GetAdjustedBitrateBps()];
436
437 OSStatus status = VTCompressionSessionEncodeFrame(_compressionSession,
438 pixelBuffer,
439 presentationTimeStamp,
440 kCMTimeInvalid,
441 frameProperties,
442 encodeParams.release(),
443 nullptr);
444 if (frameProperties) {
445 CFRelease(frameProperties);
446 }
447 if (pixelBuffer) {
448 CVBufferRelease(pixelBuffer);
449 }
Peter Hanspersf9052862018-07-26 10:41:35 +0200450
451 if (status == kVTInvalidSessionErr) {
452 // This error occurs when entering foreground after backgrounding the app.
453 RTC_LOG(LS_ERROR) << "Invalid compression session, resetting.";
454 [self resetCompressionSessionWithPixelFormat:[self pixelFormatOfFrame:frame]];
455
456 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
457 } else if (status != noErr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100458 RTC_LOG(LS_ERROR) << "Failed to encode frame with code: " << status;
magjed73c0eb52017-08-07 06:55:28 -0700459 return WEBRTC_VIDEO_CODEC_ERROR;
460 }
461 return WEBRTC_VIDEO_CODEC_OK;
462}
463
464- (void)setCallback:(RTCVideoEncoderCallback)callback {
465 _callback = callback;
466}
467
468- (int)setBitrate:(uint32_t)bitrateKbit framerate:(uint32_t)framerate {
469 _targetBitrateBps = 1000 * bitrateKbit;
470 _bitrateAdjuster->SetTargetBitrateBps(_targetBitrateBps);
471 [self setBitrateBps:_bitrateAdjuster->GetAdjustedBitrateBps()];
472 return WEBRTC_VIDEO_CODEC_OK;
473}
474
475#pragma mark - Private
476
477- (NSInteger)releaseEncoder {
478 // Need to destroy so that the session is invalidated and won't use the
479 // callback anymore. Do not remove callback until the session is invalidated
480 // since async encoder callbacks can occur until invalidation.
481 [self destroyCompressionSession];
482 _callback = nullptr;
483 return WEBRTC_VIDEO_CODEC_OK;
484}
485
Peter Hanspersf9052862018-07-26 10:41:35 +0200486- (OSType)pixelFormatOfFrame:(RTCVideoFrame *)frame {
487 // Use NV12 for non-native frames.
488 if ([frame.buffer isKindOfClass:[RTCCVPixelBuffer class]]) {
489 RTCCVPixelBuffer *rtcPixelBuffer = (RTCCVPixelBuffer *)frame.buffer;
490 return CVPixelBufferGetPixelFormatType(rtcPixelBuffer.pixelBuffer);
491 }
492
493 return kNV12PixelFormat;
494}
495
496- (BOOL)resetCompressionSessionIfNeededWithFrame:(RTCVideoFrame *)frame {
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200497 BOOL resetCompressionSession = NO;
498
Anders Carlsson5b07c242018-04-13 14:12:22 +0200499 // If we're capturing native frames in another pixel format than the compression session is
500 // configured with, make sure the compression session is reset using the correct pixel format.
Peter Hanspersf9052862018-07-26 10:41:35 +0200501 OSType framePixelFormat = [self pixelFormatOfFrame:frame];
Anders Carlsson5b07c242018-04-13 14:12:22 +0200502
Peter Hanspersf9052862018-07-26 10:41:35 +0200503 if (_compressionSession) {
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200504 // The pool attribute `kCVPixelBufferPixelFormatTypeKey` can contain either an array of pixel
505 // formats or a single pixel format.
506 NSDictionary *poolAttributes =
Peter Hanspersf9052862018-07-26 10:41:35 +0200507 (__bridge NSDictionary *)CVPixelBufferPoolGetPixelBufferAttributes(_pixelBufferPool);
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200508 id pixelFormats =
509 [poolAttributes objectForKey:(__bridge NSString *)kCVPixelBufferPixelFormatTypeKey];
510 NSArray<NSNumber *> *compressionSessionPixelFormats = nil;
511 if ([pixelFormats isKindOfClass:[NSArray class]]) {
512 compressionSessionPixelFormats = (NSArray *)pixelFormats;
Peter Hanspersf9052862018-07-26 10:41:35 +0200513 } else if ([pixelFormats isKindOfClass:[NSNumber class]]) {
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200514 compressionSessionPixelFormats = @[ (NSNumber *)pixelFormats ];
515 }
516
517 if (![compressionSessionPixelFormats
518 containsObject:[NSNumber numberWithLong:framePixelFormat]]) {
519 resetCompressionSession = YES;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100520 RTC_LOG(LS_INFO) << "Resetting compression session due to non-matching pixel format.";
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200521 }
Peter Hanspersf9052862018-07-26 10:41:35 +0200522 } else {
523 resetCompressionSession = YES;
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200524 }
525
526 if (resetCompressionSession) {
527 [self resetCompressionSessionWithPixelFormat:framePixelFormat];
528 }
529 return resetCompressionSession;
530}
531
532- (int)resetCompressionSessionWithPixelFormat:(OSType)framePixelFormat {
magjed73c0eb52017-08-07 06:55:28 -0700533 [self destroyCompressionSession];
534
535 // Set source image buffer attributes. These attributes will be present on
536 // buffers retrieved from the encoder's pixel buffer pool.
537 const size_t attributesSize = 3;
538 CFTypeRef keys[attributesSize] = {
539#if defined(WEBRTC_IOS)
540 kCVPixelBufferOpenGLESCompatibilityKey,
541#elif defined(WEBRTC_MAC)
542 kCVPixelBufferOpenGLCompatibilityKey,
543#endif
544 kCVPixelBufferIOSurfacePropertiesKey,
545 kCVPixelBufferPixelFormatTypeKey
546 };
547 CFDictionaryRef ioSurfaceValue = CreateCFTypeDictionary(nullptr, nullptr, 0);
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200548 int64_t pixelFormatType = framePixelFormat;
549 CFNumberRef pixelFormat = CFNumberCreate(nullptr, kCFNumberLongType, &pixelFormatType);
magjed73c0eb52017-08-07 06:55:28 -0700550 CFTypeRef values[attributesSize] = {kCFBooleanTrue, ioSurfaceValue, pixelFormat};
551 CFDictionaryRef sourceAttributes = CreateCFTypeDictionary(keys, values, attributesSize);
552 if (ioSurfaceValue) {
553 CFRelease(ioSurfaceValue);
554 ioSurfaceValue = nullptr;
555 }
556 if (pixelFormat) {
557 CFRelease(pixelFormat);
558 pixelFormat = nullptr;
559 }
kthelgasona4955b42017-08-24 04:22:58 -0700560 CFMutableDictionaryRef encoder_specs = nullptr;
561#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
562 // Currently hw accl is supported above 360p on mac, below 360p
563 // the compression session will be created with hw accl disabled.
564 encoder_specs = CFDictionaryCreateMutable(
565 nullptr, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
566 CFDictionarySetValue(encoder_specs,
567 kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
568 kCFBooleanTrue);
569#endif
570 OSStatus status =
571 VTCompressionSessionCreate(nullptr, // use default allocator
572 _width,
573 _height,
574 kCMVideoCodecType_H264,
575 encoder_specs, // use hardware accelerated encoder if available
576 sourceAttributes,
577 nullptr, // use default compressed data allocator
578 compressionOutputCallback,
579 nullptr,
580 &_compressionSession);
magjed73c0eb52017-08-07 06:55:28 -0700581 if (sourceAttributes) {
582 CFRelease(sourceAttributes);
583 sourceAttributes = nullptr;
584 }
kthelgasona4955b42017-08-24 04:22:58 -0700585 if (encoder_specs) {
586 CFRelease(encoder_specs);
587 encoder_specs = nullptr;
588 }
magjed73c0eb52017-08-07 06:55:28 -0700589 if (status != noErr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100590 RTC_LOG(LS_ERROR) << "Failed to create compression session: " << status;
magjed73c0eb52017-08-07 06:55:28 -0700591 return WEBRTC_VIDEO_CODEC_ERROR;
592 }
kthelgasona4955b42017-08-24 04:22:58 -0700593#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
594 CFBooleanRef hwaccl_enabled = nullptr;
595 status = VTSessionCopyProperty(_compressionSession,
596 kVTCompressionPropertyKey_UsingHardwareAcceleratedVideoEncoder,
597 nullptr,
598 &hwaccl_enabled);
599 if (status == noErr && (CFBooleanGetValue(hwaccl_enabled))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100600 RTC_LOG(LS_INFO) << "Compression session created with hw accl enabled";
kthelgasona4955b42017-08-24 04:22:58 -0700601 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100602 RTC_LOG(LS_INFO) << "Compression session created with hw accl disabled";
kthelgasona4955b42017-08-24 04:22:58 -0700603 }
604#endif
magjed73c0eb52017-08-07 06:55:28 -0700605 [self configureCompressionSession];
Peter Hanspersf9052862018-07-26 10:41:35 +0200606
607 // The pixel buffer pool is dependent on the compression session so if the session is reset, the
608 // pool should be reset as well.
609 _pixelBufferPool = VTCompressionSessionGetPixelBufferPool(_compressionSession);
610
magjed73c0eb52017-08-07 06:55:28 -0700611 return WEBRTC_VIDEO_CODEC_OK;
612}
613
614- (void)configureCompressionSession {
615 RTC_DCHECK(_compressionSession);
616 SetVTSessionProperty(_compressionSession, kVTCompressionPropertyKey_RealTime, true);
617 SetVTSessionProperty(_compressionSession, kVTCompressionPropertyKey_ProfileLevel, _profile);
618 SetVTSessionProperty(_compressionSession, kVTCompressionPropertyKey_AllowFrameReordering, false);
619 [self setEncoderBitrateBps:_targetBitrateBps];
620 // TODO(tkchin): Look at entropy mode and colorspace matrices.
621 // TODO(tkchin): Investigate to see if there's any way to make this work.
622 // May need it to interop with Android. Currently this call just fails.
623 // On inspecting encoder output on iOS8, this value is set to 6.
624 // internal::SetVTSessionProperty(compression_session_,
625 // kVTCompressionPropertyKey_MaxFrameDelayCount,
626 // 1);
627
628 // Set a relatively large value for keyframe emission (7200 frames or 4 minutes).
629 SetVTSessionProperty(_compressionSession, kVTCompressionPropertyKey_MaxKeyFrameInterval, 7200);
630 SetVTSessionProperty(
631 _compressionSession, kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration, 240);
632}
633
634- (void)destroyCompressionSession {
635 if (_compressionSession) {
636 VTCompressionSessionInvalidate(_compressionSession);
637 CFRelease(_compressionSession);
638 _compressionSession = nullptr;
Peter Hanspersf9052862018-07-26 10:41:35 +0200639 _pixelBufferPool = nullptr;
magjed73c0eb52017-08-07 06:55:28 -0700640 }
641}
642
643- (NSString *)implementationName {
644 return @"VideoToolbox";
645}
646
647- (void)setBitrateBps:(uint32_t)bitrateBps {
648 if (_encoderBitrateBps != bitrateBps) {
649 [self setEncoderBitrateBps:bitrateBps];
650 }
651}
652
653- (void)setEncoderBitrateBps:(uint32_t)bitrateBps {
654 if (_compressionSession) {
655 SetVTSessionProperty(_compressionSession, kVTCompressionPropertyKey_AverageBitRate, bitrateBps);
656
657 // TODO(tkchin): Add a helper method to set array value.
658 int64_t dataLimitBytesPerSecondValue =
659 static_cast<int64_t>(bitrateBps * kLimitToAverageBitRateFactor / 8);
660 CFNumberRef bytesPerSecond =
661 CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, &dataLimitBytesPerSecondValue);
662 int64_t oneSecondValue = 1;
663 CFNumberRef oneSecond =
664 CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, &oneSecondValue);
665 const void *nums[2] = {bytesPerSecond, oneSecond};
666 CFArrayRef dataRateLimits = CFArrayCreate(nullptr, nums, 2, &kCFTypeArrayCallBacks);
667 OSStatus status = VTSessionSetProperty(
668 _compressionSession, kVTCompressionPropertyKey_DataRateLimits, dataRateLimits);
669 if (bytesPerSecond) {
670 CFRelease(bytesPerSecond);
671 }
672 if (oneSecond) {
673 CFRelease(oneSecond);
674 }
675 if (dataRateLimits) {
676 CFRelease(dataRateLimits);
677 }
678 if (status != noErr) {
Yura Yaroshevich27af5db2018-04-10 19:43:20 +0300679 RTC_LOG(LS_ERROR) << "Failed to set data rate limit with code: " << status;
magjed73c0eb52017-08-07 06:55:28 -0700680 }
681
682 _encoderBitrateBps = bitrateBps;
683 }
684}
685
686- (void)frameWasEncoded:(OSStatus)status
687 flags:(VTEncodeInfoFlags)infoFlags
688 sampleBuffer:(CMSampleBufferRef)sampleBuffer
689 codecSpecificInfo:(id<RTCCodecSpecificInfo>)codecSpecificInfo
690 width:(int32_t)width
691 height:(int32_t)height
692 renderTimeMs:(int64_t)renderTimeMs
693 timestamp:(uint32_t)timestamp
694 rotation:(RTCVideoRotation)rotation {
695 if (status != noErr) {
Yura Yaroshevich27af5db2018-04-10 19:43:20 +0300696 RTC_LOG(LS_ERROR) << "H264 encode failed with code: " << status;
magjed73c0eb52017-08-07 06:55:28 -0700697 return;
698 }
699 if (infoFlags & kVTEncodeInfo_FrameDropped) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100700 RTC_LOG(LS_INFO) << "H264 encode dropped frame.";
magjed73c0eb52017-08-07 06:55:28 -0700701 return;
702 }
703
704 BOOL isKeyframe = NO;
705 CFArrayRef attachments = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, 0);
706 if (attachments != nullptr && CFArrayGetCount(attachments)) {
707 CFDictionaryRef attachment =
708 static_cast<CFDictionaryRef>(CFArrayGetValueAtIndex(attachments, 0));
709 isKeyframe = !CFDictionaryContainsKey(attachment, kCMSampleAttachmentKey_NotSync);
710 }
711
712 if (isKeyframe) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100713 RTC_LOG(LS_INFO) << "Generated keyframe";
magjed73c0eb52017-08-07 06:55:28 -0700714 }
715
716 // Convert the sample buffer into a buffer suitable for RTP packetization.
717 // TODO(tkchin): Allocate buffers through a pool.
718 std::unique_ptr<rtc::Buffer> buffer(new rtc::Buffer());
719 RTCRtpFragmentationHeader *header;
720 {
kthelgasonf8084d42017-08-30 04:47:10 -0700721 std::unique_ptr<webrtc::RTPFragmentationHeader> header_cpp;
magjed73c0eb52017-08-07 06:55:28 -0700722 bool result =
723 H264CMSampleBufferToAnnexBBuffer(sampleBuffer, isKeyframe, buffer.get(), &header_cpp);
kthelgasonf8084d42017-08-30 04:47:10 -0700724 header = [[RTCRtpFragmentationHeader alloc] initWithNativeFragmentationHeader:header_cpp.get()];
magjed73c0eb52017-08-07 06:55:28 -0700725 if (!result) {
726 return;
727 }
728 }
729
730 RTCEncodedImage *frame = [[RTCEncodedImage alloc] init];
731 frame.buffer = [NSData dataWithBytesNoCopy:buffer->data() length:buffer->size() freeWhenDone:NO];
732 frame.encodedWidth = width;
733 frame.encodedHeight = height;
734 frame.completeFrame = YES;
735 frame.frameType = isKeyframe ? RTCFrameTypeVideoFrameKey : RTCFrameTypeVideoFrameDelta;
736 frame.captureTimeMs = renderTimeMs;
737 frame.timeStamp = timestamp;
738 frame.rotation = rotation;
739 frame.contentType = (_mode == RTCVideoCodecModeScreensharing) ? RTCVideoContentTypeScreenshare :
740 RTCVideoContentTypeUnspecified;
Ilya Nikolaevskiyb6c462d2018-06-05 15:21:32 +0200741 frame.flags = webrtc::VideoSendTiming::kInvalid;
magjed73c0eb52017-08-07 06:55:28 -0700742
743 int qp;
744 _h264BitstreamParser.ParseBitstream(buffer->data(), buffer->size());
745 _h264BitstreamParser.GetLastSliceQp(&qp);
746 frame.qp = @(qp);
747
748 BOOL res = _callback(frame, codecSpecificInfo, header);
749 if (!res) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100750 RTC_LOG(LS_ERROR) << "Encode callback failed";
magjed73c0eb52017-08-07 06:55:28 -0700751 return;
752 }
753 _bitrateAdjuster->Update(frame.buffer.length);
754}
755
Anders Carlsson2ac27392018-09-03 14:17:03 +0200756- (nullable RTCVideoEncoderQpThresholds *)scalingSettings {
magjed73c0eb52017-08-07 06:55:28 -0700757 return [[RTCVideoEncoderQpThresholds alloc] initWithThresholdsLow:kLowH264QpThreshold
758 high:kHighH264QpThreshold];
759}
760
761@end