blob: 4028e7acee0cb65bcc802d3ccdd2192eaa0f2121 [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"
Steve Anton10542f22019-01-11 09:11:00 -080039#include "rtc_base/time_utils.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.
Qiang Chenfa1ca1e2019-01-14 10:03:26 -0800180CFStringRef ExtractProfile(const webrtc::H264::ProfileLevelId &profile_level_id) {
181 switch (profile_level_id.profile) {
magjed73c0eb52017-08-07 06:55:28 -0700182 case webrtc::H264::kProfileConstrainedBaseline:
183 case webrtc::H264::kProfileBaseline:
Qiang Chenfa1ca1e2019-01-14 10:03:26 -0800184 switch (profile_level_id.level) {
magjed73c0eb52017-08-07 06:55:28 -0700185 case webrtc::H264::kLevel3:
186 return kVTProfileLevel_H264_Baseline_3_0;
187 case webrtc::H264::kLevel3_1:
188 return kVTProfileLevel_H264_Baseline_3_1;
189 case webrtc::H264::kLevel3_2:
190 return kVTProfileLevel_H264_Baseline_3_2;
191 case webrtc::H264::kLevel4:
192 return kVTProfileLevel_H264_Baseline_4_0;
193 case webrtc::H264::kLevel4_1:
194 return kVTProfileLevel_H264_Baseline_4_1;
195 case webrtc::H264::kLevel4_2:
196 return kVTProfileLevel_H264_Baseline_4_2;
197 case webrtc::H264::kLevel5:
198 return kVTProfileLevel_H264_Baseline_5_0;
199 case webrtc::H264::kLevel5_1:
200 return kVTProfileLevel_H264_Baseline_5_1;
201 case webrtc::H264::kLevel5_2:
202 return kVTProfileLevel_H264_Baseline_5_2;
203 case webrtc::H264::kLevel1:
204 case webrtc::H264::kLevel1_b:
205 case webrtc::H264::kLevel1_1:
206 case webrtc::H264::kLevel1_2:
207 case webrtc::H264::kLevel1_3:
208 case webrtc::H264::kLevel2:
209 case webrtc::H264::kLevel2_1:
210 case webrtc::H264::kLevel2_2:
211 return kVTProfileLevel_H264_Baseline_AutoLevel;
212 }
213
214 case webrtc::H264::kProfileMain:
Qiang Chenfa1ca1e2019-01-14 10:03:26 -0800215 switch (profile_level_id.level) {
magjed73c0eb52017-08-07 06:55:28 -0700216 case webrtc::H264::kLevel3:
217 return kVTProfileLevel_H264_Main_3_0;
218 case webrtc::H264::kLevel3_1:
219 return kVTProfileLevel_H264_Main_3_1;
220 case webrtc::H264::kLevel3_2:
221 return kVTProfileLevel_H264_Main_3_2;
222 case webrtc::H264::kLevel4:
223 return kVTProfileLevel_H264_Main_4_0;
224 case webrtc::H264::kLevel4_1:
225 return kVTProfileLevel_H264_Main_4_1;
226 case webrtc::H264::kLevel4_2:
227 return kVTProfileLevel_H264_Main_4_2;
228 case webrtc::H264::kLevel5:
229 return kVTProfileLevel_H264_Main_5_0;
230 case webrtc::H264::kLevel5_1:
231 return kVTProfileLevel_H264_Main_5_1;
232 case webrtc::H264::kLevel5_2:
233 return kVTProfileLevel_H264_Main_5_2;
234 case webrtc::H264::kLevel1:
235 case webrtc::H264::kLevel1_b:
236 case webrtc::H264::kLevel1_1:
237 case webrtc::H264::kLevel1_2:
238 case webrtc::H264::kLevel1_3:
239 case webrtc::H264::kLevel2:
240 case webrtc::H264::kLevel2_1:
241 case webrtc::H264::kLevel2_2:
242 return kVTProfileLevel_H264_Main_AutoLevel;
243 }
244
245 case webrtc::H264::kProfileConstrainedHigh:
246 case webrtc::H264::kProfileHigh:
Qiang Chenfa1ca1e2019-01-14 10:03:26 -0800247 switch (profile_level_id.level) {
magjed73c0eb52017-08-07 06:55:28 -0700248 case webrtc::H264::kLevel3:
249 return kVTProfileLevel_H264_High_3_0;
250 case webrtc::H264::kLevel3_1:
251 return kVTProfileLevel_H264_High_3_1;
252 case webrtc::H264::kLevel3_2:
253 return kVTProfileLevel_H264_High_3_2;
254 case webrtc::H264::kLevel4:
255 return kVTProfileLevel_H264_High_4_0;
256 case webrtc::H264::kLevel4_1:
257 return kVTProfileLevel_H264_High_4_1;
258 case webrtc::H264::kLevel4_2:
259 return kVTProfileLevel_H264_High_4_2;
260 case webrtc::H264::kLevel5:
261 return kVTProfileLevel_H264_High_5_0;
262 case webrtc::H264::kLevel5_1:
263 return kVTProfileLevel_H264_High_5_1;
264 case webrtc::H264::kLevel5_2:
265 return kVTProfileLevel_H264_High_5_2;
266 case webrtc::H264::kLevel1:
267 case webrtc::H264::kLevel1_b:
268 case webrtc::H264::kLevel1_1:
269 case webrtc::H264::kLevel1_2:
270 case webrtc::H264::kLevel1_3:
271 case webrtc::H264::kLevel2:
272 case webrtc::H264::kLevel2_1:
273 case webrtc::H264::kLevel2_2:
274 return kVTProfileLevel_H264_High_AutoLevel;
275 }
276 }
277}
Qiang Chenfa1ca1e2019-01-14 10:03:26 -0800278
279// The function returns the max allowed sample rate (pixels per second) that
280// can be processed by given encoder with |profile_level_id|.
281// See https://www.itu.int/rec/dologin_pub.asp?lang=e&id=T-REC-H.264-201610-S!!PDF-E&type=items
282// for details.
283NSUInteger GetMaxSampleRate(const webrtc::H264::ProfileLevelId &profile_level_id) {
284 switch (profile_level_id.level) {
285 case webrtc::H264::kLevel3:
286 return 10368000;
287 case webrtc::H264::kLevel3_1:
288 return 27648000;
289 case webrtc::H264::kLevel3_2:
290 return 55296000;
291 case webrtc::H264::kLevel4:
292 case webrtc::H264::kLevel4_1:
293 return 62914560;
294 case webrtc::H264::kLevel4_2:
295 return 133693440;
296 case webrtc::H264::kLevel5:
297 return 150994944;
298 case webrtc::H264::kLevel5_1:
299 return 251658240;
300 case webrtc::H264::kLevel5_2:
301 return 530841600;
302 case webrtc::H264::kLevel1:
303 case webrtc::H264::kLevel1_b:
304 case webrtc::H264::kLevel1_1:
305 case webrtc::H264::kLevel1_2:
306 case webrtc::H264::kLevel1_3:
307 case webrtc::H264::kLevel2:
308 case webrtc::H264::kLevel2_1:
309 case webrtc::H264::kLevel2_2:
310 // Zero means auto rate setting.
311 return 0;
312 }
313}
Kári Tristan Helgason0bf60712017-09-25 10:26:42 +0200314} // namespace
magjed73c0eb52017-08-07 06:55:28 -0700315
316@implementation RTCVideoEncoderH264 {
317 RTCVideoCodecInfo *_codecInfo;
Danielaf3282822017-09-29 14:14:54 +0200318 std::unique_ptr<webrtc::BitrateAdjuster> _bitrateAdjuster;
magjed73c0eb52017-08-07 06:55:28 -0700319 uint32_t _targetBitrateBps;
320 uint32_t _encoderBitrateBps;
Qiang Chenfa1ca1e2019-01-14 10:03:26 -0800321 uint32_t _encoderFrameRate;
322 uint32_t _maxAllowedFrameRate;
magjed73c0eb52017-08-07 06:55:28 -0700323 RTCH264PacketizationMode _packetizationMode;
Qiang Chenfa1ca1e2019-01-14 10:03:26 -0800324 absl::optional<webrtc::H264::ProfileLevelId> _profile_level_id;
magjed73c0eb52017-08-07 06:55:28 -0700325 RTCVideoEncoderCallback _callback;
326 int32_t _width;
327 int32_t _height;
328 VTCompressionSessionRef _compressionSession;
Peter Hanspersf9052862018-07-26 10:41:35 +0200329 CVPixelBufferPoolRef _pixelBufferPool;
magjed73c0eb52017-08-07 06:55:28 -0700330 RTCVideoCodecMode _mode;
331
332 webrtc::H264BitstreamParser _h264BitstreamParser;
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200333 std::vector<uint8_t> _frameScaleBuffer;
magjed73c0eb52017-08-07 06:55:28 -0700334}
335
336// .5 is set as a mininum to prevent overcompensating for large temporary
337// overshoots. We don't want to degrade video quality too badly.
338// .95 is set to prevent oscillations. When a lower bitrate is set on the
339// encoder than previously set, its output seems to have a brief period of
340// drastically reduced bitrate, so we want to avoid that. In steady state
341// conditions, 0.95 seems to give us better overall bitrate over long periods
342// of time.
343- (instancetype)initWithCodecInfo:(RTCVideoCodecInfo *)codecInfo {
344 if (self = [super init]) {
345 _codecInfo = codecInfo;
Niels Möller2cb7b5e2018-04-19 10:02:26 +0200346 _bitrateAdjuster.reset(new webrtc::BitrateAdjuster(.5, .95));
magjed73c0eb52017-08-07 06:55:28 -0700347 _packetizationMode = RTCH264PacketizationModeNonInterleaved;
Qiang Chenfa1ca1e2019-01-14 10:03:26 -0800348 _profile_level_id =
349 webrtc::H264::ParseSdpProfileLevelId([codecInfo nativeSdpVideoFormat].parameters);
350 RTC_DCHECK(_profile_level_id);
351 RTC_LOG(LS_INFO) << "Using profile " << CFStringToString(ExtractProfile(*_profile_level_id));
Kári Tristan Helgasonfc313dc2017-10-20 11:01:22 +0200352 RTC_CHECK([codecInfo.name isEqualToString:kRTCVideoCodecH264Name]);
magjed73c0eb52017-08-07 06:55:28 -0700353 }
354 return self;
355}
356
357- (void)dealloc {
358 [self destroyCompressionSession];
359}
360
361- (NSInteger)startEncodeWithSettings:(RTCVideoEncoderSettings *)settings
362 numberOfCores:(int)numberOfCores {
363 RTC_DCHECK(settings);
Kári Tristan Helgasonfc313dc2017-10-20 11:01:22 +0200364 RTC_DCHECK([settings.name isEqualToString:kRTCVideoCodecH264Name]);
magjed73c0eb52017-08-07 06:55:28 -0700365
366 _width = settings.width;
367 _height = settings.height;
368 _mode = settings.mode;
369
Qiang Chenfa1ca1e2019-01-14 10:03:26 -0800370 uint32_t aligned_width = (((_width + 15) >> 4) << 4);
371 uint32_t aligned_height = (((_height + 15) >> 4) << 4);
372 _maxAllowedFrameRate = static_cast<uint32_t>(GetMaxSampleRate(*_profile_level_id) /
373 (aligned_width * aligned_height));
374
magjed73c0eb52017-08-07 06:55:28 -0700375 // We can only set average bitrate on the HW encoder.
Kári Tristan Helgason87c54632018-04-05 09:56:14 +0200376 _targetBitrateBps = settings.startBitrate * 1000; // startBitrate is in kbps.
magjed73c0eb52017-08-07 06:55:28 -0700377 _bitrateAdjuster->SetTargetBitrateBps(_targetBitrateBps);
Qiang Chenfa1ca1e2019-01-14 10:03:26 -0800378 _encoderFrameRate = MIN(settings.maxFramerate, _maxAllowedFrameRate);
379 if (settings.maxFramerate > _maxAllowedFrameRate && _maxAllowedFrameRate > 0) {
380 RTC_LOG(LS_WARNING) << "Initial encoder frame rate setting " << settings.maxFramerate
381 << " is larger than the "
382 << "maximal allowed frame rate " << _maxAllowedFrameRate << ".";
383 }
magjed73c0eb52017-08-07 06:55:28 -0700384
385 // TODO(tkchin): Try setting payload size via
386 // kVTCompressionPropertyKey_MaxH264SliceBytes.
387
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200388 return [self resetCompressionSessionWithPixelFormat:kNV12PixelFormat];
magjed73c0eb52017-08-07 06:55:28 -0700389}
390
391- (NSInteger)encode:(RTCVideoFrame *)frame
Peter Hanspersd9b64cd2018-01-12 16:16:18 +0100392 codecSpecificInfo:(nullable id<RTCCodecSpecificInfo>)codecSpecificInfo
magjed73c0eb52017-08-07 06:55:28 -0700393 frameTypes:(NSArray<NSNumber *> *)frameTypes {
394 RTC_DCHECK_EQ(frame.width, _width);
395 RTC_DCHECK_EQ(frame.height, _height);
396 if (!_callback || !_compressionSession) {
397 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
398 }
magjed73c0eb52017-08-07 06:55:28 -0700399 BOOL isKeyframeRequired = NO;
400
401 // Get a pixel buffer from the pool and copy frame data over.
Peter Hanspersf9052862018-07-26 10:41:35 +0200402 if ([self resetCompressionSessionIfNeededWithFrame:frame]) {
magjed73c0eb52017-08-07 06:55:28 -0700403 isKeyframeRequired = YES;
magjed73c0eb52017-08-07 06:55:28 -0700404 }
magjed73c0eb52017-08-07 06:55:28 -0700405
406 CVPixelBufferRef pixelBuffer = nullptr;
407 if ([frame.buffer isKindOfClass:[RTCCVPixelBuffer class]]) {
408 // Native frame buffer
409 RTCCVPixelBuffer *rtcPixelBuffer = (RTCCVPixelBuffer *)frame.buffer;
410 if (![rtcPixelBuffer requiresCropping]) {
411 // This pixel buffer might have a higher resolution than what the
412 // compression session is configured to. The compression session can
413 // handle that and will output encoded frames in the configured
414 // resolution regardless of the input pixel buffer resolution.
415 pixelBuffer = rtcPixelBuffer.pixelBuffer;
416 CVBufferRetain(pixelBuffer);
417 } else {
418 // Cropping required, we need to crop and scale to a new pixel buffer.
Peter Hanspersf9052862018-07-26 10:41:35 +0200419 pixelBuffer = CreatePixelBuffer(_pixelBufferPool);
magjed73c0eb52017-08-07 06:55:28 -0700420 if (!pixelBuffer) {
421 return WEBRTC_VIDEO_CODEC_ERROR;
422 }
423 int dstWidth = CVPixelBufferGetWidth(pixelBuffer);
424 int dstHeight = CVPixelBufferGetHeight(pixelBuffer);
425 if ([rtcPixelBuffer requiresScalingToWidth:dstWidth height:dstHeight]) {
426 int size =
427 [rtcPixelBuffer bufferSizeForCroppingAndScalingToWidth:dstWidth height:dstHeight];
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200428 _frameScaleBuffer.resize(size);
magjed73c0eb52017-08-07 06:55:28 -0700429 } else {
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200430 _frameScaleBuffer.clear();
magjed73c0eb52017-08-07 06:55:28 -0700431 }
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200432 _frameScaleBuffer.shrink_to_fit();
433 if (![rtcPixelBuffer cropAndScaleTo:pixelBuffer withTempBuffer:_frameScaleBuffer.data()]) {
Peter Hanspers56df67b2018-06-01 14:21:10 +0200434 CVBufferRelease(pixelBuffer);
magjed73c0eb52017-08-07 06:55:28 -0700435 return WEBRTC_VIDEO_CODEC_ERROR;
436 }
437 }
438 }
439
440 if (!pixelBuffer) {
441 // We did not have a native frame buffer
Peter Hanspersf9052862018-07-26 10:41:35 +0200442 pixelBuffer = CreatePixelBuffer(_pixelBufferPool);
magjed73c0eb52017-08-07 06:55:28 -0700443 if (!pixelBuffer) {
444 return WEBRTC_VIDEO_CODEC_ERROR;
445 }
446 RTC_DCHECK(pixelBuffer);
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200447 if (!CopyVideoFrameToNV12PixelBuffer([frame.buffer toI420], pixelBuffer)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100448 RTC_LOG(LS_ERROR) << "Failed to copy frame data.";
magjed73c0eb52017-08-07 06:55:28 -0700449 CVBufferRelease(pixelBuffer);
450 return WEBRTC_VIDEO_CODEC_ERROR;
451 }
452 }
453
454 // Check if we need a keyframe.
455 if (!isKeyframeRequired && frameTypes) {
456 for (NSNumber *frameType in frameTypes) {
457 if ((RTCFrameType)frameType.intValue == RTCFrameTypeVideoFrameKey) {
458 isKeyframeRequired = YES;
459 break;
460 }
461 }
462 }
463
464 CMTime presentationTimeStamp = CMTimeMake(frame.timeStampNs / rtc::kNumNanosecsPerMillisec, 1000);
465 CFDictionaryRef frameProperties = nullptr;
466 if (isKeyframeRequired) {
467 CFTypeRef keys[] = {kVTEncodeFrameOptionKey_ForceKeyFrame};
468 CFTypeRef values[] = {kCFBooleanTrue};
469 frameProperties = CreateCFTypeDictionary(keys, values, 1);
470 }
471
472 std::unique_ptr<RTCFrameEncodeParams> encodeParams;
473 encodeParams.reset(new RTCFrameEncodeParams(self,
474 codecSpecificInfo,
475 _width,
476 _height,
477 frame.timeStampNs / rtc::kNumNanosecsPerMillisec,
478 frame.timeStamp,
479 frame.rotation));
480 encodeParams->codecSpecificInfo.packetizationMode = _packetizationMode;
481
482 // Update the bitrate if needed.
Qiang Chen59a01b02018-11-19 10:30:04 -0800483 [self setBitrateBps:_bitrateAdjuster->GetAdjustedBitrateBps() frameRate:_encoderFrameRate];
magjed73c0eb52017-08-07 06:55:28 -0700484
485 OSStatus status = VTCompressionSessionEncodeFrame(_compressionSession,
486 pixelBuffer,
487 presentationTimeStamp,
488 kCMTimeInvalid,
489 frameProperties,
490 encodeParams.release(),
491 nullptr);
492 if (frameProperties) {
493 CFRelease(frameProperties);
494 }
495 if (pixelBuffer) {
496 CVBufferRelease(pixelBuffer);
497 }
Peter Hanspersf9052862018-07-26 10:41:35 +0200498
499 if (status == kVTInvalidSessionErr) {
500 // This error occurs when entering foreground after backgrounding the app.
501 RTC_LOG(LS_ERROR) << "Invalid compression session, resetting.";
502 [self resetCompressionSessionWithPixelFormat:[self pixelFormatOfFrame:frame]];
503
504 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
505 } else if (status != noErr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100506 RTC_LOG(LS_ERROR) << "Failed to encode frame with code: " << status;
magjed73c0eb52017-08-07 06:55:28 -0700507 return WEBRTC_VIDEO_CODEC_ERROR;
508 }
509 return WEBRTC_VIDEO_CODEC_OK;
510}
511
512- (void)setCallback:(RTCVideoEncoderCallback)callback {
513 _callback = callback;
514}
515
516- (int)setBitrate:(uint32_t)bitrateKbit framerate:(uint32_t)framerate {
517 _targetBitrateBps = 1000 * bitrateKbit;
518 _bitrateAdjuster->SetTargetBitrateBps(_targetBitrateBps);
Qiang Chenfa1ca1e2019-01-14 10:03:26 -0800519 if (framerate > _maxAllowedFrameRate && _maxAllowedFrameRate > 0) {
520 RTC_LOG(LS_WARNING) << "Encoder frame rate setting " << framerate << " is larger than the "
521 << "maximal allowed frame rate " << _maxAllowedFrameRate << ".";
522 }
523 framerate = MIN(framerate, _maxAllowedFrameRate);
Qiang Chen59a01b02018-11-19 10:30:04 -0800524 [self setBitrateBps:_bitrateAdjuster->GetAdjustedBitrateBps() frameRate:framerate];
magjed73c0eb52017-08-07 06:55:28 -0700525 return WEBRTC_VIDEO_CODEC_OK;
526}
527
528#pragma mark - Private
529
530- (NSInteger)releaseEncoder {
531 // Need to destroy so that the session is invalidated and won't use the
532 // callback anymore. Do not remove callback until the session is invalidated
533 // since async encoder callbacks can occur until invalidation.
534 [self destroyCompressionSession];
535 _callback = nullptr;
536 return WEBRTC_VIDEO_CODEC_OK;
537}
538
Peter Hanspersf9052862018-07-26 10:41:35 +0200539- (OSType)pixelFormatOfFrame:(RTCVideoFrame *)frame {
540 // Use NV12 for non-native frames.
541 if ([frame.buffer isKindOfClass:[RTCCVPixelBuffer class]]) {
542 RTCCVPixelBuffer *rtcPixelBuffer = (RTCCVPixelBuffer *)frame.buffer;
543 return CVPixelBufferGetPixelFormatType(rtcPixelBuffer.pixelBuffer);
544 }
545
546 return kNV12PixelFormat;
547}
548
549- (BOOL)resetCompressionSessionIfNeededWithFrame:(RTCVideoFrame *)frame {
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200550 BOOL resetCompressionSession = NO;
551
Anders Carlsson5b07c242018-04-13 14:12:22 +0200552 // If we're capturing native frames in another pixel format than the compression session is
553 // configured with, make sure the compression session is reset using the correct pixel format.
Peter Hanspersf9052862018-07-26 10:41:35 +0200554 OSType framePixelFormat = [self pixelFormatOfFrame:frame];
Anders Carlsson5b07c242018-04-13 14:12:22 +0200555
Peter Hanspersf9052862018-07-26 10:41:35 +0200556 if (_compressionSession) {
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200557 // The pool attribute `kCVPixelBufferPixelFormatTypeKey` can contain either an array of pixel
558 // formats or a single pixel format.
559 NSDictionary *poolAttributes =
Peter Hanspersf9052862018-07-26 10:41:35 +0200560 (__bridge NSDictionary *)CVPixelBufferPoolGetPixelBufferAttributes(_pixelBufferPool);
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200561 id pixelFormats =
562 [poolAttributes objectForKey:(__bridge NSString *)kCVPixelBufferPixelFormatTypeKey];
563 NSArray<NSNumber *> *compressionSessionPixelFormats = nil;
564 if ([pixelFormats isKindOfClass:[NSArray class]]) {
565 compressionSessionPixelFormats = (NSArray *)pixelFormats;
Peter Hanspersf9052862018-07-26 10:41:35 +0200566 } else if ([pixelFormats isKindOfClass:[NSNumber class]]) {
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200567 compressionSessionPixelFormats = @[ (NSNumber *)pixelFormats ];
568 }
569
570 if (![compressionSessionPixelFormats
571 containsObject:[NSNumber numberWithLong:framePixelFormat]]) {
572 resetCompressionSession = YES;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100573 RTC_LOG(LS_INFO) << "Resetting compression session due to non-matching pixel format.";
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200574 }
Peter Hanspersf9052862018-07-26 10:41:35 +0200575 } else {
576 resetCompressionSession = YES;
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200577 }
578
579 if (resetCompressionSession) {
580 [self resetCompressionSessionWithPixelFormat:framePixelFormat];
581 }
582 return resetCompressionSession;
583}
584
585- (int)resetCompressionSessionWithPixelFormat:(OSType)framePixelFormat {
magjed73c0eb52017-08-07 06:55:28 -0700586 [self destroyCompressionSession];
587
588 // Set source image buffer attributes. These attributes will be present on
589 // buffers retrieved from the encoder's pixel buffer pool.
590 const size_t attributesSize = 3;
591 CFTypeRef keys[attributesSize] = {
592#if defined(WEBRTC_IOS)
593 kCVPixelBufferOpenGLESCompatibilityKey,
594#elif defined(WEBRTC_MAC)
595 kCVPixelBufferOpenGLCompatibilityKey,
596#endif
597 kCVPixelBufferIOSurfacePropertiesKey,
598 kCVPixelBufferPixelFormatTypeKey
599 };
600 CFDictionaryRef ioSurfaceValue = CreateCFTypeDictionary(nullptr, nullptr, 0);
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200601 int64_t pixelFormatType = framePixelFormat;
602 CFNumberRef pixelFormat = CFNumberCreate(nullptr, kCFNumberLongType, &pixelFormatType);
magjed73c0eb52017-08-07 06:55:28 -0700603 CFTypeRef values[attributesSize] = {kCFBooleanTrue, ioSurfaceValue, pixelFormat};
604 CFDictionaryRef sourceAttributes = CreateCFTypeDictionary(keys, values, attributesSize);
605 if (ioSurfaceValue) {
606 CFRelease(ioSurfaceValue);
607 ioSurfaceValue = nullptr;
608 }
609 if (pixelFormat) {
610 CFRelease(pixelFormat);
611 pixelFormat = nullptr;
612 }
kthelgasona4955b42017-08-24 04:22:58 -0700613 CFMutableDictionaryRef encoder_specs = nullptr;
614#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
615 // Currently hw accl is supported above 360p on mac, below 360p
616 // the compression session will be created with hw accl disabled.
617 encoder_specs = CFDictionaryCreateMutable(
618 nullptr, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
619 CFDictionarySetValue(encoder_specs,
620 kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
621 kCFBooleanTrue);
622#endif
623 OSStatus status =
624 VTCompressionSessionCreate(nullptr, // use default allocator
625 _width,
626 _height,
627 kCMVideoCodecType_H264,
628 encoder_specs, // use hardware accelerated encoder if available
629 sourceAttributes,
630 nullptr, // use default compressed data allocator
631 compressionOutputCallback,
632 nullptr,
633 &_compressionSession);
magjed73c0eb52017-08-07 06:55:28 -0700634 if (sourceAttributes) {
635 CFRelease(sourceAttributes);
636 sourceAttributes = nullptr;
637 }
kthelgasona4955b42017-08-24 04:22:58 -0700638 if (encoder_specs) {
639 CFRelease(encoder_specs);
640 encoder_specs = nullptr;
641 }
magjed73c0eb52017-08-07 06:55:28 -0700642 if (status != noErr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100643 RTC_LOG(LS_ERROR) << "Failed to create compression session: " << status;
magjed73c0eb52017-08-07 06:55:28 -0700644 return WEBRTC_VIDEO_CODEC_ERROR;
645 }
kthelgasona4955b42017-08-24 04:22:58 -0700646#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
647 CFBooleanRef hwaccl_enabled = nullptr;
648 status = VTSessionCopyProperty(_compressionSession,
649 kVTCompressionPropertyKey_UsingHardwareAcceleratedVideoEncoder,
650 nullptr,
651 &hwaccl_enabled);
652 if (status == noErr && (CFBooleanGetValue(hwaccl_enabled))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100653 RTC_LOG(LS_INFO) << "Compression session created with hw accl enabled";
kthelgasona4955b42017-08-24 04:22:58 -0700654 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100655 RTC_LOG(LS_INFO) << "Compression session created with hw accl disabled";
kthelgasona4955b42017-08-24 04:22:58 -0700656 }
657#endif
magjed73c0eb52017-08-07 06:55:28 -0700658 [self configureCompressionSession];
Peter Hanspersf9052862018-07-26 10:41:35 +0200659
660 // The pixel buffer pool is dependent on the compression session so if the session is reset, the
661 // pool should be reset as well.
662 _pixelBufferPool = VTCompressionSessionGetPixelBufferPool(_compressionSession);
663
magjed73c0eb52017-08-07 06:55:28 -0700664 return WEBRTC_VIDEO_CODEC_OK;
665}
666
667- (void)configureCompressionSession {
668 RTC_DCHECK(_compressionSession);
669 SetVTSessionProperty(_compressionSession, kVTCompressionPropertyKey_RealTime, true);
Qiang Chenfa1ca1e2019-01-14 10:03:26 -0800670 SetVTSessionProperty(_compressionSession,
671 kVTCompressionPropertyKey_ProfileLevel,
672 ExtractProfile(*_profile_level_id));
magjed73c0eb52017-08-07 06:55:28 -0700673 SetVTSessionProperty(_compressionSession, kVTCompressionPropertyKey_AllowFrameReordering, false);
Qiang Chen59a01b02018-11-19 10:30:04 -0800674 [self setEncoderBitrateBps:_targetBitrateBps frameRate:_encoderFrameRate];
magjed73c0eb52017-08-07 06:55:28 -0700675 // TODO(tkchin): Look at entropy mode and colorspace matrices.
676 // TODO(tkchin): Investigate to see if there's any way to make this work.
677 // May need it to interop with Android. Currently this call just fails.
678 // On inspecting encoder output on iOS8, this value is set to 6.
679 // internal::SetVTSessionProperty(compression_session_,
680 // kVTCompressionPropertyKey_MaxFrameDelayCount,
681 // 1);
682
683 // Set a relatively large value for keyframe emission (7200 frames or 4 minutes).
684 SetVTSessionProperty(_compressionSession, kVTCompressionPropertyKey_MaxKeyFrameInterval, 7200);
685 SetVTSessionProperty(
686 _compressionSession, kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration, 240);
687}
688
689- (void)destroyCompressionSession {
690 if (_compressionSession) {
691 VTCompressionSessionInvalidate(_compressionSession);
692 CFRelease(_compressionSession);
693 _compressionSession = nullptr;
Peter Hanspersf9052862018-07-26 10:41:35 +0200694 _pixelBufferPool = nullptr;
magjed73c0eb52017-08-07 06:55:28 -0700695 }
696}
697
698- (NSString *)implementationName {
699 return @"VideoToolbox";
700}
701
Qiang Chen59a01b02018-11-19 10:30:04 -0800702- (void)setBitrateBps:(uint32_t)bitrateBps frameRate:(uint32_t)frameRate {
703 if (_encoderBitrateBps != bitrateBps || _encoderFrameRate != frameRate) {
704 [self setEncoderBitrateBps:bitrateBps frameRate:frameRate];
magjed73c0eb52017-08-07 06:55:28 -0700705 }
706}
707
Qiang Chen59a01b02018-11-19 10:30:04 -0800708- (void)setEncoderBitrateBps:(uint32_t)bitrateBps frameRate:(uint32_t)frameRate {
magjed73c0eb52017-08-07 06:55:28 -0700709 if (_compressionSession) {
710 SetVTSessionProperty(_compressionSession, kVTCompressionPropertyKey_AverageBitRate, bitrateBps);
Qiang Chenfa1ca1e2019-01-14 10:03:26 -0800711
712 // With zero |_maxAllowedFrameRate|, we fall back to automatic frame rate detection.
713 if (_maxAllowedFrameRate > 0) {
714 SetVTSessionProperty(
715 _compressionSession, kVTCompressionPropertyKey_ExpectedFrameRate, frameRate);
716 }
magjed73c0eb52017-08-07 06:55:28 -0700717
718 // TODO(tkchin): Add a helper method to set array value.
719 int64_t dataLimitBytesPerSecondValue =
720 static_cast<int64_t>(bitrateBps * kLimitToAverageBitRateFactor / 8);
721 CFNumberRef bytesPerSecond =
722 CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, &dataLimitBytesPerSecondValue);
723 int64_t oneSecondValue = 1;
724 CFNumberRef oneSecond =
725 CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, &oneSecondValue);
726 const void *nums[2] = {bytesPerSecond, oneSecond};
727 CFArrayRef dataRateLimits = CFArrayCreate(nullptr, nums, 2, &kCFTypeArrayCallBacks);
728 OSStatus status = VTSessionSetProperty(
729 _compressionSession, kVTCompressionPropertyKey_DataRateLimits, dataRateLimits);
730 if (bytesPerSecond) {
731 CFRelease(bytesPerSecond);
732 }
733 if (oneSecond) {
734 CFRelease(oneSecond);
735 }
736 if (dataRateLimits) {
737 CFRelease(dataRateLimits);
738 }
739 if (status != noErr) {
Yura Yaroshevich27af5db2018-04-10 19:43:20 +0300740 RTC_LOG(LS_ERROR) << "Failed to set data rate limit with code: " << status;
magjed73c0eb52017-08-07 06:55:28 -0700741 }
742
743 _encoderBitrateBps = bitrateBps;
Qiang Chen59a01b02018-11-19 10:30:04 -0800744 _encoderFrameRate = frameRate;
magjed73c0eb52017-08-07 06:55:28 -0700745 }
746}
747
748- (void)frameWasEncoded:(OSStatus)status
749 flags:(VTEncodeInfoFlags)infoFlags
750 sampleBuffer:(CMSampleBufferRef)sampleBuffer
751 codecSpecificInfo:(id<RTCCodecSpecificInfo>)codecSpecificInfo
752 width:(int32_t)width
753 height:(int32_t)height
754 renderTimeMs:(int64_t)renderTimeMs
755 timestamp:(uint32_t)timestamp
756 rotation:(RTCVideoRotation)rotation {
757 if (status != noErr) {
Yura Yaroshevich27af5db2018-04-10 19:43:20 +0300758 RTC_LOG(LS_ERROR) << "H264 encode failed with code: " << status;
magjed73c0eb52017-08-07 06:55:28 -0700759 return;
760 }
761 if (infoFlags & kVTEncodeInfo_FrameDropped) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100762 RTC_LOG(LS_INFO) << "H264 encode dropped frame.";
magjed73c0eb52017-08-07 06:55:28 -0700763 return;
764 }
765
766 BOOL isKeyframe = NO;
767 CFArrayRef attachments = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, 0);
768 if (attachments != nullptr && CFArrayGetCount(attachments)) {
769 CFDictionaryRef attachment =
770 static_cast<CFDictionaryRef>(CFArrayGetValueAtIndex(attachments, 0));
771 isKeyframe = !CFDictionaryContainsKey(attachment, kCMSampleAttachmentKey_NotSync);
772 }
773
774 if (isKeyframe) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100775 RTC_LOG(LS_INFO) << "Generated keyframe";
magjed73c0eb52017-08-07 06:55:28 -0700776 }
777
778 // Convert the sample buffer into a buffer suitable for RTP packetization.
779 // TODO(tkchin): Allocate buffers through a pool.
780 std::unique_ptr<rtc::Buffer> buffer(new rtc::Buffer());
781 RTCRtpFragmentationHeader *header;
782 {
kthelgasonf8084d42017-08-30 04:47:10 -0700783 std::unique_ptr<webrtc::RTPFragmentationHeader> header_cpp;
magjed73c0eb52017-08-07 06:55:28 -0700784 bool result =
785 H264CMSampleBufferToAnnexBBuffer(sampleBuffer, isKeyframe, buffer.get(), &header_cpp);
kthelgasonf8084d42017-08-30 04:47:10 -0700786 header = [[RTCRtpFragmentationHeader alloc] initWithNativeFragmentationHeader:header_cpp.get()];
magjed73c0eb52017-08-07 06:55:28 -0700787 if (!result) {
788 return;
789 }
790 }
791
792 RTCEncodedImage *frame = [[RTCEncodedImage alloc] init];
793 frame.buffer = [NSData dataWithBytesNoCopy:buffer->data() length:buffer->size() freeWhenDone:NO];
794 frame.encodedWidth = width;
795 frame.encodedHeight = height;
796 frame.completeFrame = YES;
797 frame.frameType = isKeyframe ? RTCFrameTypeVideoFrameKey : RTCFrameTypeVideoFrameDelta;
798 frame.captureTimeMs = renderTimeMs;
799 frame.timeStamp = timestamp;
800 frame.rotation = rotation;
801 frame.contentType = (_mode == RTCVideoCodecModeScreensharing) ? RTCVideoContentTypeScreenshare :
802 RTCVideoContentTypeUnspecified;
Ilya Nikolaevskiyb6c462d2018-06-05 15:21:32 +0200803 frame.flags = webrtc::VideoSendTiming::kInvalid;
magjed73c0eb52017-08-07 06:55:28 -0700804
805 int qp;
806 _h264BitstreamParser.ParseBitstream(buffer->data(), buffer->size());
807 _h264BitstreamParser.GetLastSliceQp(&qp);
808 frame.qp = @(qp);
809
810 BOOL res = _callback(frame, codecSpecificInfo, header);
811 if (!res) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100812 RTC_LOG(LS_ERROR) << "Encode callback failed";
magjed73c0eb52017-08-07 06:55:28 -0700813 return;
814 }
815 _bitrateAdjuster->Update(frame.buffer.length);
816}
817
Anders Carlsson2ac27392018-09-03 14:17:03 +0200818- (nullable RTCVideoEncoderQpThresholds *)scalingSettings {
magjed73c0eb52017-08-07 06:55:28 -0700819 return [[RTCVideoEncoderQpThresholds alloc] initWithThresholdsLow:kLowH264QpThreshold
820 high:kHighH264QpThreshold];
821}
822
823@end