blob: c167e54757dbb5b377a6f8c4722bb912627f8bb2 [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
12#import "WebRTC/RTCVideoCodecH264.h"
13
14#import <VideoToolbox/VideoToolbox.h>
15#include <vector>
16
17#if defined(WEBRTC_IOS)
18#import "Common/RTCUIApplicationStatusObserver.h"
19#import "WebRTC/UIDevice+RTCDevice.h"
20#endif
21#import "PeerConnection/RTCVideoCodec+Private.h"
22#import "WebRTC/RTCVideoCodec.h"
23#import "WebRTC/RTCVideoFrame.h"
24#import "WebRTC/RTCVideoFrameBuffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "common_video/h264/h264_bitstream_parser.h"
26#include "common_video/h264/profile_level_id.h"
27#include "common_video/include/bitrate_adjuster.h"
Mirko Bonadei65432062017-12-11 09:32:13 +010028#import "helpers.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "modules/include/module_common_types.h"
30#include "modules/video_coding/include/video_error_codes.h"
31#include "rtc_base/buffer.h"
32#include "rtc_base/logging.h"
33#include "rtc_base/timeutils.h"
34#include "sdk/objc/Framework/Classes/VideoToolbox/nalu_rewriter.h"
Mirko Bonadei65432062017-12-11 09:32:13 +010035#include "third_party/libyuv/include/libyuv/convert_from.h"
magjed73c0eb52017-08-07 06:55:28 -070036
37@interface RTCVideoEncoderH264 ()
38
39- (void)frameWasEncoded:(OSStatus)status
40 flags:(VTEncodeInfoFlags)infoFlags
41 sampleBuffer:(CMSampleBufferRef)sampleBuffer
42 codecSpecificInfo:(id<RTCCodecSpecificInfo>)codecSpecificInfo
43 width:(int32_t)width
44 height:(int32_t)height
45 renderTimeMs:(int64_t)renderTimeMs
46 timestamp:(uint32_t)timestamp
47 rotation:(RTCVideoRotation)rotation;
48
49@end
50
Kári Tristan Helgason0bf60712017-09-25 10:26:42 +020051namespace { // anonymous namespace
52
magjed73c0eb52017-08-07 06:55:28 -070053// The ratio between kVTCompressionPropertyKey_DataRateLimits and
54// kVTCompressionPropertyKey_AverageBitRate. The data rate limit is set higher
55// than the average bit rate to avoid undershooting the target.
56const float kLimitToAverageBitRateFactor = 1.5f;
57// These thresholds deviate from the default h264 QP thresholds, as they
58// have been found to work better on devices that support VideoToolbox
59const int kLowH264QpThreshold = 28;
60const int kHighH264QpThreshold = 39;
61
Anders Carlssonf3ee3b72017-10-23 15:23:00 +020062const OSType kNV12PixelFormat = kCVPixelFormatType_420YpCbCr8BiPlanarFullRange;
63
magjed73c0eb52017-08-07 06:55:28 -070064// Struct that we pass to the encoder per frame to encode. We receive it again
65// in the encoder callback.
66struct RTCFrameEncodeParams {
67 RTCFrameEncodeParams(RTCVideoEncoderH264 *e,
68 RTCCodecSpecificInfoH264 *csi,
69 int32_t w,
70 int32_t h,
71 int64_t rtms,
72 uint32_t ts,
73 RTCVideoRotation r)
74 : encoder(e), width(w), height(h), render_time_ms(rtms), timestamp(ts), rotation(r) {
75 if (csi) {
76 codecSpecificInfo = csi;
77 } else {
78 codecSpecificInfo = [[RTCCodecSpecificInfoH264 alloc] init];
79 }
80 }
81
82 RTCVideoEncoderH264 *encoder;
83 RTCCodecSpecificInfoH264 *codecSpecificInfo;
84 int32_t width;
85 int32_t height;
86 int64_t render_time_ms;
87 uint32_t timestamp;
88 RTCVideoRotation rotation;
89};
90
91// We receive I420Frames as input, but we need to feed CVPixelBuffers into the
92// encoder. This performs the copy and format conversion.
93// TODO(tkchin): See if encoder will accept i420 frames and compare performance.
Anders Carlssonf3ee3b72017-10-23 15:23:00 +020094bool CopyVideoFrameToNV12PixelBuffer(id<RTCI420Buffer> frameBuffer, CVPixelBufferRef pixelBuffer) {
magjed73c0eb52017-08-07 06:55:28 -070095 RTC_DCHECK(pixelBuffer);
Anders Carlssonf3ee3b72017-10-23 15:23:00 +020096 RTC_DCHECK_EQ(CVPixelBufferGetPixelFormatType(pixelBuffer), kNV12PixelFormat);
magjed73c0eb52017-08-07 06:55:28 -070097 RTC_DCHECK_EQ(CVPixelBufferGetHeightOfPlane(pixelBuffer, 0), frameBuffer.height);
98 RTC_DCHECK_EQ(CVPixelBufferGetWidthOfPlane(pixelBuffer, 0), frameBuffer.width);
99
100 CVReturn cvRet = CVPixelBufferLockBaseAddress(pixelBuffer, 0);
101 if (cvRet != kCVReturnSuccess) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100102 RTC_LOG(LS_ERROR) << "Failed to lock base address: " << cvRet;
magjed73c0eb52017-08-07 06:55:28 -0700103 return false;
104 }
105 uint8_t *dstY = reinterpret_cast<uint8_t *>(CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 0));
106 int dstStrideY = CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer, 0);
107 uint8_t *dstUV = reinterpret_cast<uint8_t *>(CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 1));
108 int dstStrideUV = CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer, 1);
109 // Convert I420 to NV12.
110 int ret = libyuv::I420ToNV12(frameBuffer.dataY,
111 frameBuffer.strideY,
112 frameBuffer.dataU,
113 frameBuffer.strideU,
114 frameBuffer.dataV,
115 frameBuffer.strideV,
116 dstY,
117 dstStrideY,
118 dstUV,
119 dstStrideUV,
120 frameBuffer.width,
121 frameBuffer.height);
122 CVPixelBufferUnlockBaseAddress(pixelBuffer, 0);
123 if (ret) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100124 RTC_LOG(LS_ERROR) << "Error converting I420 VideoFrame to NV12 :" << ret;
magjed73c0eb52017-08-07 06:55:28 -0700125 return false;
126 }
127 return true;
128}
129
130CVPixelBufferRef CreatePixelBuffer(CVPixelBufferPoolRef pixel_buffer_pool) {
131 if (!pixel_buffer_pool) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100132 RTC_LOG(LS_ERROR) << "Failed to get pixel buffer pool.";
magjed73c0eb52017-08-07 06:55:28 -0700133 return nullptr;
134 }
135 CVPixelBufferRef pixel_buffer;
136 CVReturn ret = CVPixelBufferPoolCreatePixelBuffer(nullptr, pixel_buffer_pool, &pixel_buffer);
137 if (ret != kCVReturnSuccess) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100138 RTC_LOG(LS_ERROR) << "Failed to create pixel buffer: " << ret;
magjed73c0eb52017-08-07 06:55:28 -0700139 // We probably want to drop frames here, since failure probably means
140 // that the pool is empty.
141 return nullptr;
142 }
143 return pixel_buffer;
144}
145
146// This is the callback function that VideoToolbox calls when encode is
147// complete. From inspection this happens on its own queue.
148void compressionOutputCallback(void *encoder,
149 void *params,
150 OSStatus status,
151 VTEncodeInfoFlags infoFlags,
152 CMSampleBufferRef sampleBuffer) {
Anders Carlssoned2b1c92017-11-02 13:15:15 +0100153 if (!params) {
154 // If there are pending callbacks when the encoder is destroyed, this can happen.
155 return;
156 }
magjed73c0eb52017-08-07 06:55:28 -0700157 std::unique_ptr<RTCFrameEncodeParams> encodeParams(
158 reinterpret_cast<RTCFrameEncodeParams *>(params));
159 [encodeParams->encoder frameWasEncoded:status
160 flags:infoFlags
161 sampleBuffer:sampleBuffer
162 codecSpecificInfo:encodeParams->codecSpecificInfo
163 width:encodeParams->width
164 height:encodeParams->height
165 renderTimeMs:encodeParams->render_time_ms
166 timestamp:encodeParams->timestamp
167 rotation:encodeParams->rotation];
168}
169
Magnus Jedvert8b4e92d2018-04-13 15:36:43 +0200170// Extract VideoToolbox profile out of the webrtc::SdpVideoFormat. If there is
171// no specific VideoToolbox profile for the specified level, AutoLevel will be
magjed73c0eb52017-08-07 06:55:28 -0700172// returned. The user must initialize the encoder with a resolution and
173// framerate conforming to the selected H264 level regardless.
Anders Carlsson7e042812017-10-05 16:55:38 +0200174CFStringRef ExtractProfile(webrtc::SdpVideoFormat videoFormat) {
Danil Chapovalov196100e2018-06-21 10:17:24 +0200175 const absl::optional<webrtc::H264::ProfileLevelId> profile_level_id =
Anders Carlsson7e042812017-10-05 16:55:38 +0200176 webrtc::H264::ParseSdpProfileLevelId(videoFormat.parameters);
magjed73c0eb52017-08-07 06:55:28 -0700177 RTC_DCHECK(profile_level_id);
178 switch (profile_level_id->profile) {
179 case webrtc::H264::kProfileConstrainedBaseline:
180 case webrtc::H264::kProfileBaseline:
181 switch (profile_level_id->level) {
182 case webrtc::H264::kLevel3:
183 return kVTProfileLevel_H264_Baseline_3_0;
184 case webrtc::H264::kLevel3_1:
185 return kVTProfileLevel_H264_Baseline_3_1;
186 case webrtc::H264::kLevel3_2:
187 return kVTProfileLevel_H264_Baseline_3_2;
188 case webrtc::H264::kLevel4:
189 return kVTProfileLevel_H264_Baseline_4_0;
190 case webrtc::H264::kLevel4_1:
191 return kVTProfileLevel_H264_Baseline_4_1;
192 case webrtc::H264::kLevel4_2:
193 return kVTProfileLevel_H264_Baseline_4_2;
194 case webrtc::H264::kLevel5:
195 return kVTProfileLevel_H264_Baseline_5_0;
196 case webrtc::H264::kLevel5_1:
197 return kVTProfileLevel_H264_Baseline_5_1;
198 case webrtc::H264::kLevel5_2:
199 return kVTProfileLevel_H264_Baseline_5_2;
200 case webrtc::H264::kLevel1:
201 case webrtc::H264::kLevel1_b:
202 case webrtc::H264::kLevel1_1:
203 case webrtc::H264::kLevel1_2:
204 case webrtc::H264::kLevel1_3:
205 case webrtc::H264::kLevel2:
206 case webrtc::H264::kLevel2_1:
207 case webrtc::H264::kLevel2_2:
208 return kVTProfileLevel_H264_Baseline_AutoLevel;
209 }
210
211 case webrtc::H264::kProfileMain:
212 switch (profile_level_id->level) {
213 case webrtc::H264::kLevel3:
214 return kVTProfileLevel_H264_Main_3_0;
215 case webrtc::H264::kLevel3_1:
216 return kVTProfileLevel_H264_Main_3_1;
217 case webrtc::H264::kLevel3_2:
218 return kVTProfileLevel_H264_Main_3_2;
219 case webrtc::H264::kLevel4:
220 return kVTProfileLevel_H264_Main_4_0;
221 case webrtc::H264::kLevel4_1:
222 return kVTProfileLevel_H264_Main_4_1;
223 case webrtc::H264::kLevel4_2:
224 return kVTProfileLevel_H264_Main_4_2;
225 case webrtc::H264::kLevel5:
226 return kVTProfileLevel_H264_Main_5_0;
227 case webrtc::H264::kLevel5_1:
228 return kVTProfileLevel_H264_Main_5_1;
229 case webrtc::H264::kLevel5_2:
230 return kVTProfileLevel_H264_Main_5_2;
231 case webrtc::H264::kLevel1:
232 case webrtc::H264::kLevel1_b:
233 case webrtc::H264::kLevel1_1:
234 case webrtc::H264::kLevel1_2:
235 case webrtc::H264::kLevel1_3:
236 case webrtc::H264::kLevel2:
237 case webrtc::H264::kLevel2_1:
238 case webrtc::H264::kLevel2_2:
239 return kVTProfileLevel_H264_Main_AutoLevel;
240 }
241
242 case webrtc::H264::kProfileConstrainedHigh:
243 case webrtc::H264::kProfileHigh:
244 switch (profile_level_id->level) {
245 case webrtc::H264::kLevel3:
246 return kVTProfileLevel_H264_High_3_0;
247 case webrtc::H264::kLevel3_1:
248 return kVTProfileLevel_H264_High_3_1;
249 case webrtc::H264::kLevel3_2:
250 return kVTProfileLevel_H264_High_3_2;
251 case webrtc::H264::kLevel4:
252 return kVTProfileLevel_H264_High_4_0;
253 case webrtc::H264::kLevel4_1:
254 return kVTProfileLevel_H264_High_4_1;
255 case webrtc::H264::kLevel4_2:
256 return kVTProfileLevel_H264_High_4_2;
257 case webrtc::H264::kLevel5:
258 return kVTProfileLevel_H264_High_5_0;
259 case webrtc::H264::kLevel5_1:
260 return kVTProfileLevel_H264_High_5_1;
261 case webrtc::H264::kLevel5_2:
262 return kVTProfileLevel_H264_High_5_2;
263 case webrtc::H264::kLevel1:
264 case webrtc::H264::kLevel1_b:
265 case webrtc::H264::kLevel1_1:
266 case webrtc::H264::kLevel1_2:
267 case webrtc::H264::kLevel1_3:
268 case webrtc::H264::kLevel2:
269 case webrtc::H264::kLevel2_1:
270 case webrtc::H264::kLevel2_2:
271 return kVTProfileLevel_H264_High_AutoLevel;
272 }
273 }
274}
Kári Tristan Helgason0bf60712017-09-25 10:26:42 +0200275} // namespace
magjed73c0eb52017-08-07 06:55:28 -0700276
277@implementation RTCVideoEncoderH264 {
278 RTCVideoCodecInfo *_codecInfo;
Danielaf3282822017-09-29 14:14:54 +0200279 std::unique_ptr<webrtc::BitrateAdjuster> _bitrateAdjuster;
magjed73c0eb52017-08-07 06:55:28 -0700280 uint32_t _targetBitrateBps;
281 uint32_t _encoderBitrateBps;
282 RTCH264PacketizationMode _packetizationMode;
283 CFStringRef _profile;
284 RTCVideoEncoderCallback _callback;
285 int32_t _width;
286 int32_t _height;
287 VTCompressionSessionRef _compressionSession;
Peter Hanspersf9052862018-07-26 10:41:35 +0200288 CVPixelBufferPoolRef _pixelBufferPool;
magjed73c0eb52017-08-07 06:55:28 -0700289 RTCVideoCodecMode _mode;
290
291 webrtc::H264BitstreamParser _h264BitstreamParser;
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200292 std::vector<uint8_t> _frameScaleBuffer;
magjed73c0eb52017-08-07 06:55:28 -0700293}
294
295// .5 is set as a mininum to prevent overcompensating for large temporary
296// overshoots. We don't want to degrade video quality too badly.
297// .95 is set to prevent oscillations. When a lower bitrate is set on the
298// encoder than previously set, its output seems to have a brief period of
299// drastically reduced bitrate, so we want to avoid that. In steady state
300// conditions, 0.95 seems to give us better overall bitrate over long periods
301// of time.
302- (instancetype)initWithCodecInfo:(RTCVideoCodecInfo *)codecInfo {
303 if (self = [super init]) {
304 _codecInfo = codecInfo;
Niels Möller2cb7b5e2018-04-19 10:02:26 +0200305 _bitrateAdjuster.reset(new webrtc::BitrateAdjuster(.5, .95));
magjed73c0eb52017-08-07 06:55:28 -0700306 _packetizationMode = RTCH264PacketizationModeNonInterleaved;
Anders Carlsson7e042812017-10-05 16:55:38 +0200307 _profile = ExtractProfile([codecInfo nativeSdpVideoFormat]);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100308 RTC_LOG(LS_INFO) << "Using profile " << CFStringToString(_profile);
Kári Tristan Helgasonfc313dc2017-10-20 11:01:22 +0200309 RTC_CHECK([codecInfo.name isEqualToString:kRTCVideoCodecH264Name]);
andersc9a85f072017-09-13 07:31:46 -0700310
Anders Carlsson358f2e02018-06-04 10:24:37 +0200311#if defined(WEBRTC_IOS) && !defined(RTC_APPRTCMOBILE_BROADCAST_EXTENSION)
andersc9a85f072017-09-13 07:31:46 -0700312 [RTCUIApplicationStatusObserver prepareForUse];
313#endif
magjed73c0eb52017-08-07 06:55:28 -0700314 }
315 return self;
316}
317
318- (void)dealloc {
319 [self destroyCompressionSession];
320}
321
322- (NSInteger)startEncodeWithSettings:(RTCVideoEncoderSettings *)settings
323 numberOfCores:(int)numberOfCores {
324 RTC_DCHECK(settings);
Kári Tristan Helgasonfc313dc2017-10-20 11:01:22 +0200325 RTC_DCHECK([settings.name isEqualToString:kRTCVideoCodecH264Name]);
magjed73c0eb52017-08-07 06:55:28 -0700326
327 _width = settings.width;
328 _height = settings.height;
329 _mode = settings.mode;
330
331 // We can only set average bitrate on the HW encoder.
Kári Tristan Helgason87c54632018-04-05 09:56:14 +0200332 _targetBitrateBps = settings.startBitrate * 1000; // startBitrate is in kbps.
magjed73c0eb52017-08-07 06:55:28 -0700333 _bitrateAdjuster->SetTargetBitrateBps(_targetBitrateBps);
334
335 // TODO(tkchin): Try setting payload size via
336 // kVTCompressionPropertyKey_MaxH264SliceBytes.
337
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200338 return [self resetCompressionSessionWithPixelFormat:kNV12PixelFormat];
magjed73c0eb52017-08-07 06:55:28 -0700339}
340
341- (NSInteger)encode:(RTCVideoFrame *)frame
Peter Hanspersd9b64cd2018-01-12 16:16:18 +0100342 codecSpecificInfo:(nullable id<RTCCodecSpecificInfo>)codecSpecificInfo
magjed73c0eb52017-08-07 06:55:28 -0700343 frameTypes:(NSArray<NSNumber *> *)frameTypes {
344 RTC_DCHECK_EQ(frame.width, _width);
345 RTC_DCHECK_EQ(frame.height, _height);
346 if (!_callback || !_compressionSession) {
347 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
348 }
Anders Carlsson358f2e02018-06-04 10:24:37 +0200349#if defined(WEBRTC_IOS) && !defined(RTC_APPRTCMOBILE_BROADCAST_EXTENSION)
magjed73c0eb52017-08-07 06:55:28 -0700350 if (![[RTCUIApplicationStatusObserver sharedInstance] isApplicationActive]) {
351 // Ignore all encode requests when app isn't active. In this state, the
352 // hardware encoder has been invalidated by the OS.
353 return WEBRTC_VIDEO_CODEC_OK;
354 }
355#endif
356 BOOL isKeyframeRequired = NO;
357
358 // Get a pixel buffer from the pool and copy frame data over.
Peter Hanspersf9052862018-07-26 10:41:35 +0200359 if ([self resetCompressionSessionIfNeededWithFrame:frame]) {
magjed73c0eb52017-08-07 06:55:28 -0700360 isKeyframeRequired = YES;
magjed73c0eb52017-08-07 06:55:28 -0700361 }
magjed73c0eb52017-08-07 06:55:28 -0700362
363 CVPixelBufferRef pixelBuffer = nullptr;
364 if ([frame.buffer isKindOfClass:[RTCCVPixelBuffer class]]) {
365 // Native frame buffer
366 RTCCVPixelBuffer *rtcPixelBuffer = (RTCCVPixelBuffer *)frame.buffer;
367 if (![rtcPixelBuffer requiresCropping]) {
368 // This pixel buffer might have a higher resolution than what the
369 // compression session is configured to. The compression session can
370 // handle that and will output encoded frames in the configured
371 // resolution regardless of the input pixel buffer resolution.
372 pixelBuffer = rtcPixelBuffer.pixelBuffer;
373 CVBufferRetain(pixelBuffer);
374 } else {
375 // Cropping required, we need to crop and scale to a new pixel buffer.
Peter Hanspersf9052862018-07-26 10:41:35 +0200376 pixelBuffer = CreatePixelBuffer(_pixelBufferPool);
magjed73c0eb52017-08-07 06:55:28 -0700377 if (!pixelBuffer) {
378 return WEBRTC_VIDEO_CODEC_ERROR;
379 }
380 int dstWidth = CVPixelBufferGetWidth(pixelBuffer);
381 int dstHeight = CVPixelBufferGetHeight(pixelBuffer);
382 if ([rtcPixelBuffer requiresScalingToWidth:dstWidth height:dstHeight]) {
383 int size =
384 [rtcPixelBuffer bufferSizeForCroppingAndScalingToWidth:dstWidth height:dstHeight];
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200385 _frameScaleBuffer.resize(size);
magjed73c0eb52017-08-07 06:55:28 -0700386 } else {
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200387 _frameScaleBuffer.clear();
magjed73c0eb52017-08-07 06:55:28 -0700388 }
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200389 _frameScaleBuffer.shrink_to_fit();
390 if (![rtcPixelBuffer cropAndScaleTo:pixelBuffer withTempBuffer:_frameScaleBuffer.data()]) {
Peter Hanspers56df67b2018-06-01 14:21:10 +0200391 CVBufferRelease(pixelBuffer);
magjed73c0eb52017-08-07 06:55:28 -0700392 return WEBRTC_VIDEO_CODEC_ERROR;
393 }
394 }
395 }
396
397 if (!pixelBuffer) {
398 // We did not have a native frame buffer
Peter Hanspersf9052862018-07-26 10:41:35 +0200399 pixelBuffer = CreatePixelBuffer(_pixelBufferPool);
magjed73c0eb52017-08-07 06:55:28 -0700400 if (!pixelBuffer) {
401 return WEBRTC_VIDEO_CODEC_ERROR;
402 }
403 RTC_DCHECK(pixelBuffer);
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200404 if (!CopyVideoFrameToNV12PixelBuffer([frame.buffer toI420], pixelBuffer)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100405 RTC_LOG(LS_ERROR) << "Failed to copy frame data.";
magjed73c0eb52017-08-07 06:55:28 -0700406 CVBufferRelease(pixelBuffer);
407 return WEBRTC_VIDEO_CODEC_ERROR;
408 }
409 }
410
411 // Check if we need a keyframe.
412 if (!isKeyframeRequired && frameTypes) {
413 for (NSNumber *frameType in frameTypes) {
414 if ((RTCFrameType)frameType.intValue == RTCFrameTypeVideoFrameKey) {
415 isKeyframeRequired = YES;
416 break;
417 }
418 }
419 }
420
421 CMTime presentationTimeStamp = CMTimeMake(frame.timeStampNs / rtc::kNumNanosecsPerMillisec, 1000);
422 CFDictionaryRef frameProperties = nullptr;
423 if (isKeyframeRequired) {
424 CFTypeRef keys[] = {kVTEncodeFrameOptionKey_ForceKeyFrame};
425 CFTypeRef values[] = {kCFBooleanTrue};
426 frameProperties = CreateCFTypeDictionary(keys, values, 1);
427 }
428
429 std::unique_ptr<RTCFrameEncodeParams> encodeParams;
430 encodeParams.reset(new RTCFrameEncodeParams(self,
431 codecSpecificInfo,
432 _width,
433 _height,
434 frame.timeStampNs / rtc::kNumNanosecsPerMillisec,
435 frame.timeStamp,
436 frame.rotation));
437 encodeParams->codecSpecificInfo.packetizationMode = _packetizationMode;
438
439 // Update the bitrate if needed.
440 [self setBitrateBps:_bitrateAdjuster->GetAdjustedBitrateBps()];
441
442 OSStatus status = VTCompressionSessionEncodeFrame(_compressionSession,
443 pixelBuffer,
444 presentationTimeStamp,
445 kCMTimeInvalid,
446 frameProperties,
447 encodeParams.release(),
448 nullptr);
449 if (frameProperties) {
450 CFRelease(frameProperties);
451 }
452 if (pixelBuffer) {
453 CVBufferRelease(pixelBuffer);
454 }
Peter Hanspersf9052862018-07-26 10:41:35 +0200455
456 if (status == kVTInvalidSessionErr) {
457 // This error occurs when entering foreground after backgrounding the app.
458 RTC_LOG(LS_ERROR) << "Invalid compression session, resetting.";
459 [self resetCompressionSessionWithPixelFormat:[self pixelFormatOfFrame:frame]];
460
461 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
462 } else if (status != noErr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100463 RTC_LOG(LS_ERROR) << "Failed to encode frame with code: " << status;
magjed73c0eb52017-08-07 06:55:28 -0700464 return WEBRTC_VIDEO_CODEC_ERROR;
465 }
466 return WEBRTC_VIDEO_CODEC_OK;
467}
468
469- (void)setCallback:(RTCVideoEncoderCallback)callback {
470 _callback = callback;
471}
472
473- (int)setBitrate:(uint32_t)bitrateKbit framerate:(uint32_t)framerate {
474 _targetBitrateBps = 1000 * bitrateKbit;
475 _bitrateAdjuster->SetTargetBitrateBps(_targetBitrateBps);
476 [self setBitrateBps:_bitrateAdjuster->GetAdjustedBitrateBps()];
477 return WEBRTC_VIDEO_CODEC_OK;
478}
479
480#pragma mark - Private
481
482- (NSInteger)releaseEncoder {
483 // Need to destroy so that the session is invalidated and won't use the
484 // callback anymore. Do not remove callback until the session is invalidated
485 // since async encoder callbacks can occur until invalidation.
486 [self destroyCompressionSession];
487 _callback = nullptr;
488 return WEBRTC_VIDEO_CODEC_OK;
489}
490
Peter Hanspersf9052862018-07-26 10:41:35 +0200491- (OSType)pixelFormatOfFrame:(RTCVideoFrame *)frame {
492 // Use NV12 for non-native frames.
493 if ([frame.buffer isKindOfClass:[RTCCVPixelBuffer class]]) {
494 RTCCVPixelBuffer *rtcPixelBuffer = (RTCCVPixelBuffer *)frame.buffer;
495 return CVPixelBufferGetPixelFormatType(rtcPixelBuffer.pixelBuffer);
496 }
497
498 return kNV12PixelFormat;
499}
500
501- (BOOL)resetCompressionSessionIfNeededWithFrame:(RTCVideoFrame *)frame {
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200502 BOOL resetCompressionSession = NO;
503
Anders Carlsson5b07c242018-04-13 14:12:22 +0200504 // If we're capturing native frames in another pixel format than the compression session is
505 // configured with, make sure the compression session is reset using the correct pixel format.
Peter Hanspersf9052862018-07-26 10:41:35 +0200506 OSType framePixelFormat = [self pixelFormatOfFrame:frame];
Anders Carlsson5b07c242018-04-13 14:12:22 +0200507
Peter Hanspersf9052862018-07-26 10:41:35 +0200508 if (_compressionSession) {
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200509 // The pool attribute `kCVPixelBufferPixelFormatTypeKey` can contain either an array of pixel
510 // formats or a single pixel format.
511 NSDictionary *poolAttributes =
Peter Hanspersf9052862018-07-26 10:41:35 +0200512 (__bridge NSDictionary *)CVPixelBufferPoolGetPixelBufferAttributes(_pixelBufferPool);
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200513 id pixelFormats =
514 [poolAttributes objectForKey:(__bridge NSString *)kCVPixelBufferPixelFormatTypeKey];
515 NSArray<NSNumber *> *compressionSessionPixelFormats = nil;
516 if ([pixelFormats isKindOfClass:[NSArray class]]) {
517 compressionSessionPixelFormats = (NSArray *)pixelFormats;
Peter Hanspersf9052862018-07-26 10:41:35 +0200518 } else if ([pixelFormats isKindOfClass:[NSNumber class]]) {
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200519 compressionSessionPixelFormats = @[ (NSNumber *)pixelFormats ];
520 }
521
522 if (![compressionSessionPixelFormats
523 containsObject:[NSNumber numberWithLong:framePixelFormat]]) {
524 resetCompressionSession = YES;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100525 RTC_LOG(LS_INFO) << "Resetting compression session due to non-matching pixel format.";
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200526 }
Peter Hanspersf9052862018-07-26 10:41:35 +0200527 } else {
528 resetCompressionSession = YES;
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200529 }
530
531 if (resetCompressionSession) {
532 [self resetCompressionSessionWithPixelFormat:framePixelFormat];
533 }
534 return resetCompressionSession;
535}
536
537- (int)resetCompressionSessionWithPixelFormat:(OSType)framePixelFormat {
magjed73c0eb52017-08-07 06:55:28 -0700538 [self destroyCompressionSession];
539
540 // Set source image buffer attributes. These attributes will be present on
541 // buffers retrieved from the encoder's pixel buffer pool.
542 const size_t attributesSize = 3;
543 CFTypeRef keys[attributesSize] = {
544#if defined(WEBRTC_IOS)
545 kCVPixelBufferOpenGLESCompatibilityKey,
546#elif defined(WEBRTC_MAC)
547 kCVPixelBufferOpenGLCompatibilityKey,
548#endif
549 kCVPixelBufferIOSurfacePropertiesKey,
550 kCVPixelBufferPixelFormatTypeKey
551 };
552 CFDictionaryRef ioSurfaceValue = CreateCFTypeDictionary(nullptr, nullptr, 0);
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200553 int64_t pixelFormatType = framePixelFormat;
554 CFNumberRef pixelFormat = CFNumberCreate(nullptr, kCFNumberLongType, &pixelFormatType);
magjed73c0eb52017-08-07 06:55:28 -0700555 CFTypeRef values[attributesSize] = {kCFBooleanTrue, ioSurfaceValue, pixelFormat};
556 CFDictionaryRef sourceAttributes = CreateCFTypeDictionary(keys, values, attributesSize);
557 if (ioSurfaceValue) {
558 CFRelease(ioSurfaceValue);
559 ioSurfaceValue = nullptr;
560 }
561 if (pixelFormat) {
562 CFRelease(pixelFormat);
563 pixelFormat = nullptr;
564 }
kthelgasona4955b42017-08-24 04:22:58 -0700565 CFMutableDictionaryRef encoder_specs = nullptr;
566#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
567 // Currently hw accl is supported above 360p on mac, below 360p
568 // the compression session will be created with hw accl disabled.
569 encoder_specs = CFDictionaryCreateMutable(
570 nullptr, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
571 CFDictionarySetValue(encoder_specs,
572 kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
573 kCFBooleanTrue);
574#endif
575 OSStatus status =
576 VTCompressionSessionCreate(nullptr, // use default allocator
577 _width,
578 _height,
579 kCMVideoCodecType_H264,
580 encoder_specs, // use hardware accelerated encoder if available
581 sourceAttributes,
582 nullptr, // use default compressed data allocator
583 compressionOutputCallback,
584 nullptr,
585 &_compressionSession);
magjed73c0eb52017-08-07 06:55:28 -0700586 if (sourceAttributes) {
587 CFRelease(sourceAttributes);
588 sourceAttributes = nullptr;
589 }
kthelgasona4955b42017-08-24 04:22:58 -0700590 if (encoder_specs) {
591 CFRelease(encoder_specs);
592 encoder_specs = nullptr;
593 }
magjed73c0eb52017-08-07 06:55:28 -0700594 if (status != noErr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100595 RTC_LOG(LS_ERROR) << "Failed to create compression session: " << status;
magjed73c0eb52017-08-07 06:55:28 -0700596 return WEBRTC_VIDEO_CODEC_ERROR;
597 }
kthelgasona4955b42017-08-24 04:22:58 -0700598#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
599 CFBooleanRef hwaccl_enabled = nullptr;
600 status = VTSessionCopyProperty(_compressionSession,
601 kVTCompressionPropertyKey_UsingHardwareAcceleratedVideoEncoder,
602 nullptr,
603 &hwaccl_enabled);
604 if (status == noErr && (CFBooleanGetValue(hwaccl_enabled))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100605 RTC_LOG(LS_INFO) << "Compression session created with hw accl enabled";
kthelgasona4955b42017-08-24 04:22:58 -0700606 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100607 RTC_LOG(LS_INFO) << "Compression session created with hw accl disabled";
kthelgasona4955b42017-08-24 04:22:58 -0700608 }
609#endif
magjed73c0eb52017-08-07 06:55:28 -0700610 [self configureCompressionSession];
Peter Hanspersf9052862018-07-26 10:41:35 +0200611
612 // The pixel buffer pool is dependent on the compression session so if the session is reset, the
613 // pool should be reset as well.
614 _pixelBufferPool = VTCompressionSessionGetPixelBufferPool(_compressionSession);
615
magjed73c0eb52017-08-07 06:55:28 -0700616 return WEBRTC_VIDEO_CODEC_OK;
617}
618
619- (void)configureCompressionSession {
620 RTC_DCHECK(_compressionSession);
621 SetVTSessionProperty(_compressionSession, kVTCompressionPropertyKey_RealTime, true);
622 SetVTSessionProperty(_compressionSession, kVTCompressionPropertyKey_ProfileLevel, _profile);
623 SetVTSessionProperty(_compressionSession, kVTCompressionPropertyKey_AllowFrameReordering, false);
624 [self setEncoderBitrateBps:_targetBitrateBps];
625 // TODO(tkchin): Look at entropy mode and colorspace matrices.
626 // TODO(tkchin): Investigate to see if there's any way to make this work.
627 // May need it to interop with Android. Currently this call just fails.
628 // On inspecting encoder output on iOS8, this value is set to 6.
629 // internal::SetVTSessionProperty(compression_session_,
630 // kVTCompressionPropertyKey_MaxFrameDelayCount,
631 // 1);
632
633 // Set a relatively large value for keyframe emission (7200 frames or 4 minutes).
634 SetVTSessionProperty(_compressionSession, kVTCompressionPropertyKey_MaxKeyFrameInterval, 7200);
635 SetVTSessionProperty(
636 _compressionSession, kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration, 240);
637}
638
639- (void)destroyCompressionSession {
640 if (_compressionSession) {
641 VTCompressionSessionInvalidate(_compressionSession);
642 CFRelease(_compressionSession);
643 _compressionSession = nullptr;
Peter Hanspersf9052862018-07-26 10:41:35 +0200644 _pixelBufferPool = nullptr;
magjed73c0eb52017-08-07 06:55:28 -0700645 }
646}
647
648- (NSString *)implementationName {
649 return @"VideoToolbox";
650}
651
652- (void)setBitrateBps:(uint32_t)bitrateBps {
653 if (_encoderBitrateBps != bitrateBps) {
654 [self setEncoderBitrateBps:bitrateBps];
655 }
656}
657
658- (void)setEncoderBitrateBps:(uint32_t)bitrateBps {
659 if (_compressionSession) {
660 SetVTSessionProperty(_compressionSession, kVTCompressionPropertyKey_AverageBitRate, bitrateBps);
661
662 // TODO(tkchin): Add a helper method to set array value.
663 int64_t dataLimitBytesPerSecondValue =
664 static_cast<int64_t>(bitrateBps * kLimitToAverageBitRateFactor / 8);
665 CFNumberRef bytesPerSecond =
666 CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, &dataLimitBytesPerSecondValue);
667 int64_t oneSecondValue = 1;
668 CFNumberRef oneSecond =
669 CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, &oneSecondValue);
670 const void *nums[2] = {bytesPerSecond, oneSecond};
671 CFArrayRef dataRateLimits = CFArrayCreate(nullptr, nums, 2, &kCFTypeArrayCallBacks);
672 OSStatus status = VTSessionSetProperty(
673 _compressionSession, kVTCompressionPropertyKey_DataRateLimits, dataRateLimits);
674 if (bytesPerSecond) {
675 CFRelease(bytesPerSecond);
676 }
677 if (oneSecond) {
678 CFRelease(oneSecond);
679 }
680 if (dataRateLimits) {
681 CFRelease(dataRateLimits);
682 }
683 if (status != noErr) {
Yura Yaroshevich27af5db2018-04-10 19:43:20 +0300684 RTC_LOG(LS_ERROR) << "Failed to set data rate limit with code: " << status;
magjed73c0eb52017-08-07 06:55:28 -0700685 }
686
687 _encoderBitrateBps = bitrateBps;
688 }
689}
690
691- (void)frameWasEncoded:(OSStatus)status
692 flags:(VTEncodeInfoFlags)infoFlags
693 sampleBuffer:(CMSampleBufferRef)sampleBuffer
694 codecSpecificInfo:(id<RTCCodecSpecificInfo>)codecSpecificInfo
695 width:(int32_t)width
696 height:(int32_t)height
697 renderTimeMs:(int64_t)renderTimeMs
698 timestamp:(uint32_t)timestamp
699 rotation:(RTCVideoRotation)rotation {
700 if (status != noErr) {
Yura 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
761- (RTCVideoEncoderQpThresholds *)scalingSettings {
762 return [[RTCVideoEncoderQpThresholds alloc] initWithThresholdsLow:kLowH264QpThreshold
763 high:kHighH264QpThreshold];
764}
765
766@end