blob: d9b103cc04ea021d8f5d2fd3724630fd34d628cd [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) {
magjed73c0eb52017-08-07 06:55:28 -0700175 const rtc::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;
288 RTCVideoCodecMode _mode;
289
290 webrtc::H264BitstreamParser _h264BitstreamParser;
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200291 std::vector<uint8_t> _frameScaleBuffer;
magjed73c0eb52017-08-07 06:55:28 -0700292}
293
294// .5 is set as a mininum to prevent overcompensating for large temporary
295// overshoots. We don't want to degrade video quality too badly.
296// .95 is set to prevent oscillations. When a lower bitrate is set on the
297// encoder than previously set, its output seems to have a brief period of
298// drastically reduced bitrate, so we want to avoid that. In steady state
299// conditions, 0.95 seems to give us better overall bitrate over long periods
300// of time.
301- (instancetype)initWithCodecInfo:(RTCVideoCodecInfo *)codecInfo {
302 if (self = [super init]) {
303 _codecInfo = codecInfo;
Niels Möller2cb7b5e2018-04-19 10:02:26 +0200304 _bitrateAdjuster.reset(new webrtc::BitrateAdjuster(.5, .95));
magjed73c0eb52017-08-07 06:55:28 -0700305 _packetizationMode = RTCH264PacketizationModeNonInterleaved;
Anders Carlsson7e042812017-10-05 16:55:38 +0200306 _profile = ExtractProfile([codecInfo nativeSdpVideoFormat]);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100307 RTC_LOG(LS_INFO) << "Using profile " << CFStringToString(_profile);
Kári Tristan Helgasonfc313dc2017-10-20 11:01:22 +0200308 RTC_CHECK([codecInfo.name isEqualToString:kRTCVideoCodecH264Name]);
andersc9a85f072017-09-13 07:31:46 -0700309
Anders Carlsson358f2e02018-06-04 10:24:37 +0200310#if defined(WEBRTC_IOS) && !defined(RTC_APPRTCMOBILE_BROADCAST_EXTENSION)
andersc9a85f072017-09-13 07:31:46 -0700311 [RTCUIApplicationStatusObserver prepareForUse];
312#endif
magjed73c0eb52017-08-07 06:55:28 -0700313 }
314 return self;
315}
316
317- (void)dealloc {
318 [self destroyCompressionSession];
319}
320
321- (NSInteger)startEncodeWithSettings:(RTCVideoEncoderSettings *)settings
322 numberOfCores:(int)numberOfCores {
323 RTC_DCHECK(settings);
Kári Tristan Helgasonfc313dc2017-10-20 11:01:22 +0200324 RTC_DCHECK([settings.name isEqualToString:kRTCVideoCodecH264Name]);
magjed73c0eb52017-08-07 06:55:28 -0700325
326 _width = settings.width;
327 _height = settings.height;
328 _mode = settings.mode;
329
330 // We can only set average bitrate on the HW encoder.
Kári Tristan Helgason87c54632018-04-05 09:56:14 +0200331 _targetBitrateBps = settings.startBitrate * 1000; // startBitrate is in kbps.
magjed73c0eb52017-08-07 06:55:28 -0700332 _bitrateAdjuster->SetTargetBitrateBps(_targetBitrateBps);
333
334 // TODO(tkchin): Try setting payload size via
335 // kVTCompressionPropertyKey_MaxH264SliceBytes.
336
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200337 return [self resetCompressionSessionWithPixelFormat:kNV12PixelFormat];
magjed73c0eb52017-08-07 06:55:28 -0700338}
339
340- (NSInteger)encode:(RTCVideoFrame *)frame
Peter Hanspersd9b64cd2018-01-12 16:16:18 +0100341 codecSpecificInfo:(nullable id<RTCCodecSpecificInfo>)codecSpecificInfo
magjed73c0eb52017-08-07 06:55:28 -0700342 frameTypes:(NSArray<NSNumber *> *)frameTypes {
343 RTC_DCHECK_EQ(frame.width, _width);
344 RTC_DCHECK_EQ(frame.height, _height);
345 if (!_callback || !_compressionSession) {
346 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
347 }
Anders Carlsson358f2e02018-06-04 10:24:37 +0200348#if defined(WEBRTC_IOS) && !defined(RTC_APPRTCMOBILE_BROADCAST_EXTENSION)
magjed73c0eb52017-08-07 06:55:28 -0700349 if (![[RTCUIApplicationStatusObserver sharedInstance] isApplicationActive]) {
350 // Ignore all encode requests when app isn't active. In this state, the
351 // hardware encoder has been invalidated by the OS.
352 return WEBRTC_VIDEO_CODEC_OK;
353 }
354#endif
355 BOOL isKeyframeRequired = NO;
356
357 // Get a pixel buffer from the pool and copy frame data over.
358 CVPixelBufferPoolRef pixelBufferPool =
359 VTCompressionSessionGetPixelBufferPool(_compressionSession);
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200360 if ([self resetCompressionSessionIfNeededForPool:pixelBufferPool withFrame:frame]) {
magjed73c0eb52017-08-07 06:55:28 -0700361 pixelBufferPool = VTCompressionSessionGetPixelBufferPool(_compressionSession);
362 isKeyframeRequired = YES;
magjed73c0eb52017-08-07 06:55:28 -0700363 }
magjed73c0eb52017-08-07 06:55:28 -0700364
365 CVPixelBufferRef pixelBuffer = nullptr;
366 if ([frame.buffer isKindOfClass:[RTCCVPixelBuffer class]]) {
367 // Native frame buffer
368 RTCCVPixelBuffer *rtcPixelBuffer = (RTCCVPixelBuffer *)frame.buffer;
369 if (![rtcPixelBuffer requiresCropping]) {
370 // This pixel buffer might have a higher resolution than what the
371 // compression session is configured to. The compression session can
372 // handle that and will output encoded frames in the configured
373 // resolution regardless of the input pixel buffer resolution.
374 pixelBuffer = rtcPixelBuffer.pixelBuffer;
375 CVBufferRetain(pixelBuffer);
376 } else {
377 // Cropping required, we need to crop and scale to a new pixel buffer.
378 pixelBuffer = CreatePixelBuffer(pixelBufferPool);
379 if (!pixelBuffer) {
380 return WEBRTC_VIDEO_CODEC_ERROR;
381 }
382 int dstWidth = CVPixelBufferGetWidth(pixelBuffer);
383 int dstHeight = CVPixelBufferGetHeight(pixelBuffer);
384 if ([rtcPixelBuffer requiresScalingToWidth:dstWidth height:dstHeight]) {
385 int size =
386 [rtcPixelBuffer bufferSizeForCroppingAndScalingToWidth:dstWidth height:dstHeight];
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200387 _frameScaleBuffer.resize(size);
magjed73c0eb52017-08-07 06:55:28 -0700388 } else {
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200389 _frameScaleBuffer.clear();
magjed73c0eb52017-08-07 06:55:28 -0700390 }
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200391 _frameScaleBuffer.shrink_to_fit();
392 if (![rtcPixelBuffer cropAndScaleTo:pixelBuffer withTempBuffer:_frameScaleBuffer.data()]) {
Peter Hanspers56df67b2018-06-01 14:21:10 +0200393 CVBufferRelease(pixelBuffer);
magjed73c0eb52017-08-07 06:55:28 -0700394 return WEBRTC_VIDEO_CODEC_ERROR;
395 }
396 }
397 }
398
399 if (!pixelBuffer) {
400 // We did not have a native frame buffer
401 pixelBuffer = CreatePixelBuffer(pixelBufferPool);
402 if (!pixelBuffer) {
403 return WEBRTC_VIDEO_CODEC_ERROR;
404 }
405 RTC_DCHECK(pixelBuffer);
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200406 if (!CopyVideoFrameToNV12PixelBuffer([frame.buffer toI420], pixelBuffer)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100407 RTC_LOG(LS_ERROR) << "Failed to copy frame data.";
magjed73c0eb52017-08-07 06:55:28 -0700408 CVBufferRelease(pixelBuffer);
409 return WEBRTC_VIDEO_CODEC_ERROR;
410 }
411 }
412
413 // Check if we need a keyframe.
414 if (!isKeyframeRequired && frameTypes) {
415 for (NSNumber *frameType in frameTypes) {
416 if ((RTCFrameType)frameType.intValue == RTCFrameTypeVideoFrameKey) {
417 isKeyframeRequired = YES;
418 break;
419 }
420 }
421 }
422
423 CMTime presentationTimeStamp = CMTimeMake(frame.timeStampNs / rtc::kNumNanosecsPerMillisec, 1000);
424 CFDictionaryRef frameProperties = nullptr;
425 if (isKeyframeRequired) {
426 CFTypeRef keys[] = {kVTEncodeFrameOptionKey_ForceKeyFrame};
427 CFTypeRef values[] = {kCFBooleanTrue};
428 frameProperties = CreateCFTypeDictionary(keys, values, 1);
429 }
430
431 std::unique_ptr<RTCFrameEncodeParams> encodeParams;
432 encodeParams.reset(new RTCFrameEncodeParams(self,
433 codecSpecificInfo,
434 _width,
435 _height,
436 frame.timeStampNs / rtc::kNumNanosecsPerMillisec,
437 frame.timeStamp,
438 frame.rotation));
439 encodeParams->codecSpecificInfo.packetizationMode = _packetizationMode;
440
441 // Update the bitrate if needed.
442 [self setBitrateBps:_bitrateAdjuster->GetAdjustedBitrateBps()];
443
444 OSStatus status = VTCompressionSessionEncodeFrame(_compressionSession,
445 pixelBuffer,
446 presentationTimeStamp,
447 kCMTimeInvalid,
448 frameProperties,
449 encodeParams.release(),
450 nullptr);
451 if (frameProperties) {
452 CFRelease(frameProperties);
453 }
454 if (pixelBuffer) {
455 CVBufferRelease(pixelBuffer);
456 }
457 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
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200486- (BOOL)resetCompressionSessionIfNeededForPool:(CVPixelBufferPoolRef)pixelBufferPool
487 withFrame:(RTCVideoFrame *)frame {
488 BOOL resetCompressionSession = NO;
489
Anders Carlsson5b07c242018-04-13 14:12:22 +0200490 // If we're capturing native frames in another pixel format than the compression session is
491 // configured with, make sure the compression session is reset using the correct pixel format.
492 // If we're capturing non-native frames and the compression session is configured with a non-NV12
493 // format, reset it to NV12.
494 OSType framePixelFormat = kNV12PixelFormat;
495 if ([frame.buffer isKindOfClass:[RTCCVPixelBuffer class]]) {
496 RTCCVPixelBuffer *rtcPixelBuffer = (RTCCVPixelBuffer *)frame.buffer;
497 framePixelFormat = CVPixelBufferGetPixelFormatType(rtcPixelBuffer.pixelBuffer);
498 }
499
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200500#if defined(WEBRTC_IOS)
501 if (!pixelBufferPool) {
502 // Kind of a hack. On backgrounding, the compression session seems to get
503 // invalidated, which causes this pool call to fail when the application
504 // is foregrounded and frames are being sent for encoding again.
505 // Resetting the session when this happens fixes the issue.
506 // In addition we request a keyframe so video can recover quickly.
507 resetCompressionSession = YES;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100508 RTC_LOG(LS_INFO) << "Resetting compression session due to invalid pool.";
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200509 }
510#endif
511
Anders Carlsson4df8e1a2017-12-15 10:57:57 +0100512 if (pixelBufferPool) {
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200513 // The pool attribute `kCVPixelBufferPixelFormatTypeKey` can contain either an array of pixel
514 // formats or a single pixel format.
515 NSDictionary *poolAttributes =
516 (__bridge NSDictionary *)CVPixelBufferPoolGetPixelBufferAttributes(pixelBufferPool);
517 id pixelFormats =
518 [poolAttributes objectForKey:(__bridge NSString *)kCVPixelBufferPixelFormatTypeKey];
519 NSArray<NSNumber *> *compressionSessionPixelFormats = nil;
520 if ([pixelFormats isKindOfClass:[NSArray class]]) {
521 compressionSessionPixelFormats = (NSArray *)pixelFormats;
522 } else {
523 compressionSessionPixelFormats = @[ (NSNumber *)pixelFormats ];
524 }
525
526 if (![compressionSessionPixelFormats
527 containsObject:[NSNumber numberWithLong:framePixelFormat]]) {
528 resetCompressionSession = YES;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100529 RTC_LOG(LS_INFO) << "Resetting compression session due to non-matching pixel format.";
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200530 }
531 }
532
533 if (resetCompressionSession) {
534 [self resetCompressionSessionWithPixelFormat:framePixelFormat];
535 }
536 return resetCompressionSession;
537}
538
539- (int)resetCompressionSessionWithPixelFormat:(OSType)framePixelFormat {
magjed73c0eb52017-08-07 06:55:28 -0700540 [self destroyCompressionSession];
541
542 // Set source image buffer attributes. These attributes will be present on
543 // buffers retrieved from the encoder's pixel buffer pool.
544 const size_t attributesSize = 3;
545 CFTypeRef keys[attributesSize] = {
546#if defined(WEBRTC_IOS)
547 kCVPixelBufferOpenGLESCompatibilityKey,
548#elif defined(WEBRTC_MAC)
549 kCVPixelBufferOpenGLCompatibilityKey,
550#endif
551 kCVPixelBufferIOSurfacePropertiesKey,
552 kCVPixelBufferPixelFormatTypeKey
553 };
554 CFDictionaryRef ioSurfaceValue = CreateCFTypeDictionary(nullptr, nullptr, 0);
Anders Carlssonf3ee3b72017-10-23 15:23:00 +0200555 int64_t pixelFormatType = framePixelFormat;
556 CFNumberRef pixelFormat = CFNumberCreate(nullptr, kCFNumberLongType, &pixelFormatType);
magjed73c0eb52017-08-07 06:55:28 -0700557 CFTypeRef values[attributesSize] = {kCFBooleanTrue, ioSurfaceValue, pixelFormat};
558 CFDictionaryRef sourceAttributes = CreateCFTypeDictionary(keys, values, attributesSize);
559 if (ioSurfaceValue) {
560 CFRelease(ioSurfaceValue);
561 ioSurfaceValue = nullptr;
562 }
563 if (pixelFormat) {
564 CFRelease(pixelFormat);
565 pixelFormat = nullptr;
566 }
kthelgasona4955b42017-08-24 04:22:58 -0700567 CFMutableDictionaryRef encoder_specs = nullptr;
568#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
569 // Currently hw accl is supported above 360p on mac, below 360p
570 // the compression session will be created with hw accl disabled.
571 encoder_specs = CFDictionaryCreateMutable(
572 nullptr, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
573 CFDictionarySetValue(encoder_specs,
574 kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
575 kCFBooleanTrue);
576#endif
577 OSStatus status =
578 VTCompressionSessionCreate(nullptr, // use default allocator
579 _width,
580 _height,
581 kCMVideoCodecType_H264,
582 encoder_specs, // use hardware accelerated encoder if available
583 sourceAttributes,
584 nullptr, // use default compressed data allocator
585 compressionOutputCallback,
586 nullptr,
587 &_compressionSession);
magjed73c0eb52017-08-07 06:55:28 -0700588 if (sourceAttributes) {
589 CFRelease(sourceAttributes);
590 sourceAttributes = nullptr;
591 }
kthelgasona4955b42017-08-24 04:22:58 -0700592 if (encoder_specs) {
593 CFRelease(encoder_specs);
594 encoder_specs = nullptr;
595 }
magjed73c0eb52017-08-07 06:55:28 -0700596 if (status != noErr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100597 RTC_LOG(LS_ERROR) << "Failed to create compression session: " << status;
magjed73c0eb52017-08-07 06:55:28 -0700598 return WEBRTC_VIDEO_CODEC_ERROR;
599 }
kthelgasona4955b42017-08-24 04:22:58 -0700600#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
601 CFBooleanRef hwaccl_enabled = nullptr;
602 status = VTSessionCopyProperty(_compressionSession,
603 kVTCompressionPropertyKey_UsingHardwareAcceleratedVideoEncoder,
604 nullptr,
605 &hwaccl_enabled);
606 if (status == noErr && (CFBooleanGetValue(hwaccl_enabled))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100607 RTC_LOG(LS_INFO) << "Compression session created with hw accl enabled";
kthelgasona4955b42017-08-24 04:22:58 -0700608 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100609 RTC_LOG(LS_INFO) << "Compression session created with hw accl disabled";
kthelgasona4955b42017-08-24 04:22:58 -0700610 }
611#endif
magjed73c0eb52017-08-07 06:55:28 -0700612 [self configureCompressionSession];
613 return WEBRTC_VIDEO_CODEC_OK;
614}
615
616- (void)configureCompressionSession {
617 RTC_DCHECK(_compressionSession);
618 SetVTSessionProperty(_compressionSession, kVTCompressionPropertyKey_RealTime, true);
619 SetVTSessionProperty(_compressionSession, kVTCompressionPropertyKey_ProfileLevel, _profile);
620 SetVTSessionProperty(_compressionSession, kVTCompressionPropertyKey_AllowFrameReordering, false);
621 [self setEncoderBitrateBps:_targetBitrateBps];
622 // TODO(tkchin): Look at entropy mode and colorspace matrices.
623 // TODO(tkchin): Investigate to see if there's any way to make this work.
624 // May need it to interop with Android. Currently this call just fails.
625 // On inspecting encoder output on iOS8, this value is set to 6.
626 // internal::SetVTSessionProperty(compression_session_,
627 // kVTCompressionPropertyKey_MaxFrameDelayCount,
628 // 1);
629
630 // Set a relatively large value for keyframe emission (7200 frames or 4 minutes).
631 SetVTSessionProperty(_compressionSession, kVTCompressionPropertyKey_MaxKeyFrameInterval, 7200);
632 SetVTSessionProperty(
633 _compressionSession, kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration, 240);
634}
635
636- (void)destroyCompressionSession {
637 if (_compressionSession) {
638 VTCompressionSessionInvalidate(_compressionSession);
639 CFRelease(_compressionSession);
640 _compressionSession = nullptr;
641 }
642}
643
644- (NSString *)implementationName {
645 return @"VideoToolbox";
646}
647
648- (void)setBitrateBps:(uint32_t)bitrateBps {
649 if (_encoderBitrateBps != bitrateBps) {
650 [self setEncoderBitrateBps:bitrateBps];
651 }
652}
653
654- (void)setEncoderBitrateBps:(uint32_t)bitrateBps {
655 if (_compressionSession) {
656 SetVTSessionProperty(_compressionSession, kVTCompressionPropertyKey_AverageBitRate, bitrateBps);
657
658 // TODO(tkchin): Add a helper method to set array value.
659 int64_t dataLimitBytesPerSecondValue =
660 static_cast<int64_t>(bitrateBps * kLimitToAverageBitRateFactor / 8);
661 CFNumberRef bytesPerSecond =
662 CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, &dataLimitBytesPerSecondValue);
663 int64_t oneSecondValue = 1;
664 CFNumberRef oneSecond =
665 CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, &oneSecondValue);
666 const void *nums[2] = {bytesPerSecond, oneSecond};
667 CFArrayRef dataRateLimits = CFArrayCreate(nullptr, nums, 2, &kCFTypeArrayCallBacks);
668 OSStatus status = VTSessionSetProperty(
669 _compressionSession, kVTCompressionPropertyKey_DataRateLimits, dataRateLimits);
670 if (bytesPerSecond) {
671 CFRelease(bytesPerSecond);
672 }
673 if (oneSecond) {
674 CFRelease(oneSecond);
675 }
676 if (dataRateLimits) {
677 CFRelease(dataRateLimits);
678 }
679 if (status != noErr) {
Yura Yaroshevich27af5db2018-04-10 19:43:20 +0300680 RTC_LOG(LS_ERROR) << "Failed to set data rate limit with code: " << status;
magjed73c0eb52017-08-07 06:55:28 -0700681 }
682
683 _encoderBitrateBps = bitrateBps;
684 }
685}
686
687- (void)frameWasEncoded:(OSStatus)status
688 flags:(VTEncodeInfoFlags)infoFlags
689 sampleBuffer:(CMSampleBufferRef)sampleBuffer
690 codecSpecificInfo:(id<RTCCodecSpecificInfo>)codecSpecificInfo
691 width:(int32_t)width
692 height:(int32_t)height
693 renderTimeMs:(int64_t)renderTimeMs
694 timestamp:(uint32_t)timestamp
695 rotation:(RTCVideoRotation)rotation {
696 if (status != noErr) {
Yura Yaroshevich27af5db2018-04-10 19:43:20 +0300697 RTC_LOG(LS_ERROR) << "H264 encode failed with code: " << status;
magjed73c0eb52017-08-07 06:55:28 -0700698 return;
699 }
700 if (infoFlags & kVTEncodeInfo_FrameDropped) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100701 RTC_LOG(LS_INFO) << "H264 encode dropped frame.";
magjed73c0eb52017-08-07 06:55:28 -0700702 return;
703 }
704
705 BOOL isKeyframe = NO;
706 CFArrayRef attachments = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, 0);
707 if (attachments != nullptr && CFArrayGetCount(attachments)) {
708 CFDictionaryRef attachment =
709 static_cast<CFDictionaryRef>(CFArrayGetValueAtIndex(attachments, 0));
710 isKeyframe = !CFDictionaryContainsKey(attachment, kCMSampleAttachmentKey_NotSync);
711 }
712
713 if (isKeyframe) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100714 RTC_LOG(LS_INFO) << "Generated keyframe";
magjed73c0eb52017-08-07 06:55:28 -0700715 }
716
717 // Convert the sample buffer into a buffer suitable for RTP packetization.
718 // TODO(tkchin): Allocate buffers through a pool.
719 std::unique_ptr<rtc::Buffer> buffer(new rtc::Buffer());
720 RTCRtpFragmentationHeader *header;
721 {
kthelgasonf8084d42017-08-30 04:47:10 -0700722 std::unique_ptr<webrtc::RTPFragmentationHeader> header_cpp;
magjed73c0eb52017-08-07 06:55:28 -0700723 bool result =
724 H264CMSampleBufferToAnnexBBuffer(sampleBuffer, isKeyframe, buffer.get(), &header_cpp);
kthelgasonf8084d42017-08-30 04:47:10 -0700725 header = [[RTCRtpFragmentationHeader alloc] initWithNativeFragmentationHeader:header_cpp.get()];
magjed73c0eb52017-08-07 06:55:28 -0700726 if (!result) {
727 return;
728 }
729 }
730
731 RTCEncodedImage *frame = [[RTCEncodedImage alloc] init];
732 frame.buffer = [NSData dataWithBytesNoCopy:buffer->data() length:buffer->size() freeWhenDone:NO];
733 frame.encodedWidth = width;
734 frame.encodedHeight = height;
735 frame.completeFrame = YES;
736 frame.frameType = isKeyframe ? RTCFrameTypeVideoFrameKey : RTCFrameTypeVideoFrameDelta;
737 frame.captureTimeMs = renderTimeMs;
738 frame.timeStamp = timestamp;
739 frame.rotation = rotation;
740 frame.contentType = (_mode == RTCVideoCodecModeScreensharing) ? RTCVideoContentTypeScreenshare :
741 RTCVideoContentTypeUnspecified;
sprangba050a62017-08-18 02:51:12 -0700742 frame.flags = webrtc::TimingFrameFlags::kInvalid;
magjed73c0eb52017-08-07 06:55:28 -0700743
744 int qp;
745 _h264BitstreamParser.ParseBitstream(buffer->data(), buffer->size());
746 _h264BitstreamParser.GetLastSliceQp(&qp);
747 frame.qp = @(qp);
748
749 BOOL res = _callback(frame, codecSpecificInfo, header);
750 if (!res) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100751 RTC_LOG(LS_ERROR) << "Encode callback failed";
magjed73c0eb52017-08-07 06:55:28 -0700752 return;
753 }
754 _bitrateAdjuster->Update(frame.buffer.length);
755}
756
757- (RTCVideoEncoderQpThresholds *)scalingSettings {
758 return [[RTCVideoEncoderQpThresholds alloc] initWithThresholdsLow:kLowH264QpThreshold
759 high:kHighH264QpThreshold];
760}
761
762@end