blob: e7ce739f50d5afd3a80e5df0f8a385325d8cf9f0 [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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020016#include "modules/video_coding/include/video_error_codes.h"
17#include "rtc_base/checks.h"
18#include "rtc_base/logging.h"
19#include "rtc_base/timeutils.h"
20#include "sdk/objc/Framework/Classes/VideoToolbox/nalu_rewriter.h"
magjed73c0eb52017-08-07 06:55:28 -070021
22#import "WebRTC/RTCVideoFrame.h"
23#import "WebRTC/RTCVideoFrameBuffer.h"
24#import "helpers.h"
Peter Hanspersd9b64cd2018-01-12 16:16:18 +010025#import "scoped_cftyperef.h"
magjed73c0eb52017-08-07 06:55:28 -070026
27#if defined(WEBRTC_IOS)
28#import "Common/RTCUIApplicationStatusObserver.h"
JT Teha6368d12017-09-28 11:00:39 -070029#import "WebRTC/UIDevice+RTCDevice.h"
magjed73c0eb52017-08-07 06:55:28 -070030#endif
31
32// Struct that we pass to the decoder per frame to decode. We receive it again
33// in the decoder callback.
34struct RTCFrameDecodeParams {
35 RTCFrameDecodeParams(RTCVideoDecoderCallback cb, int64_t ts) : callback(cb), timestamp(ts) {}
36 RTCVideoDecoderCallback callback;
37 int64_t timestamp;
38};
39
Kári Tristan Helgason86de7e82017-12-01 13:48:48 +010040@interface RTCVideoDecoderH264 ()
41- (void)setError:(OSStatus)error;
42@end
43
magjed73c0eb52017-08-07 06:55:28 -070044// This is the callback function that VideoToolbox calls when decode is
45// complete.
Kári Tristan Helgason86de7e82017-12-01 13:48:48 +010046void decompressionOutputCallback(void *decoderRef,
magjed73c0eb52017-08-07 06:55:28 -070047 void *params,
48 OSStatus status,
49 VTDecodeInfoFlags infoFlags,
50 CVImageBufferRef imageBuffer,
51 CMTime timestamp,
52 CMTime duration) {
53 std::unique_ptr<RTCFrameDecodeParams> decodeParams(
54 reinterpret_cast<RTCFrameDecodeParams *>(params));
55 if (status != noErr) {
Kári Tristan Helgason86de7e82017-12-01 13:48:48 +010056 RTCVideoDecoderH264 *decoder = (__bridge RTCVideoDecoderH264 *)decoderRef;
57 [decoder setError:status];
Mirko Bonadei675513b2017-11-09 11:09:25 +010058 RTC_LOG(LS_ERROR) << "Failed to decode frame. Status: " << status;
magjed73c0eb52017-08-07 06:55:28 -070059 return;
60 }
61 // TODO(tkchin): Handle CVO properly.
62 RTCCVPixelBuffer *frameBuffer = [[RTCCVPixelBuffer alloc] initWithPixelBuffer:imageBuffer];
63 RTCVideoFrame *decodedFrame =
64 [[RTCVideoFrame alloc] initWithBuffer:frameBuffer
65 rotation:RTCVideoRotation_0
66 timeStampNs:CMTimeGetSeconds(timestamp) * rtc::kNumNanosecsPerSec];
67 decodedFrame.timeStamp = decodeParams->timestamp;
68 decodeParams->callback(decodedFrame);
69}
70
71// Decoder.
72@implementation RTCVideoDecoderH264 {
73 CMVideoFormatDescriptionRef _videoFormat;
74 VTDecompressionSessionRef _decompressionSession;
75 RTCVideoDecoderCallback _callback;
Kári Tristan Helgason86de7e82017-12-01 13:48:48 +010076 OSStatus _error;
magjed73c0eb52017-08-07 06:55:28 -070077}
78
andersc9a85f072017-09-13 07:31:46 -070079- (instancetype)init {
80 if (self = [super init]) {
81#if defined(WEBRTC_IOS)
82 [RTCUIApplicationStatusObserver prepareForUse];
Kári Tristan Helgason86de7e82017-12-01 13:48:48 +010083 _error = noErr;
andersc9a85f072017-09-13 07:31:46 -070084#endif
85 }
86
87 return self;
88}
89
magjed73c0eb52017-08-07 06:55:28 -070090- (void)dealloc {
91 [self destroyDecompressionSession];
92 [self setVideoFormat:nullptr];
93}
94
95- (NSInteger)startDecodeWithSettings:(RTCVideoEncoderSettings *)settings
96 numberOfCores:(int)numberOfCores {
97 return WEBRTC_VIDEO_CODEC_OK;
98}
99
100- (NSInteger)decode:(RTCEncodedImage *)inputImage
101 missingFrames:(BOOL)missingFrames
102 fragmentationHeader:(RTCRtpFragmentationHeader *)fragmentationHeader
Peter Hanspersd9b64cd2018-01-12 16:16:18 +0100103 codecSpecificInfo:(nullable id<RTCCodecSpecificInfo>)info
magjed73c0eb52017-08-07 06:55:28 -0700104 renderTimeMs:(int64_t)renderTimeMs {
105 RTC_DCHECK(inputImage.buffer);
106
Kári Tristan Helgason86de7e82017-12-01 13:48:48 +0100107 if (_error != noErr) {
108 RTC_LOG(LS_WARNING) << "Last frame decode failed.";
109 _error = noErr;
110 return WEBRTC_VIDEO_CODEC_ERROR;
111 }
112
magjed73c0eb52017-08-07 06:55:28 -0700113#if defined(WEBRTC_IOS)
114 if (![[RTCUIApplicationStatusObserver sharedInstance] isApplicationActive]) {
115 // Ignore all decode requests when app isn't active. In this state, the
116 // hardware decoder has been invalidated by the OS.
117 // Reset video format so that we won't process frames until the next
118 // keyframe.
119 [self setVideoFormat:nullptr];
120 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
121 }
122#endif
magjed73c0eb52017-08-07 06:55:28 -0700123 if (webrtc::H264AnnexBBufferHasVideoFormatDescription((uint8_t *)inputImage.buffer.bytes,
124 inputImage.buffer.length)) {
Peter Hanspersd9b64cd2018-01-12 16:16:18 +0100125 rtc::ScopedCFTypeRef<CMVideoFormatDescriptionRef> inputFormat =
126 rtc::ScopedCF(webrtc::CreateVideoFormatDescription((uint8_t *)inputImage.buffer.bytes,
127 inputImage.buffer.length));
magjed73c0eb52017-08-07 06:55:28 -0700128 if (inputFormat) {
129 // Check if the video format has changed, and reinitialize decoder if
130 // needed.
Peter Hanspersd9b64cd2018-01-12 16:16:18 +0100131 if (!CMFormatDescriptionEqual(inputFormat.get(), _videoFormat)) {
132 [self setVideoFormat:inputFormat.get()];
133
134 int resetDecompressionSessionError = [self resetDecompressionSession];
135 if (resetDecompressionSessionError != WEBRTC_VIDEO_CODEC_OK) {
136 return resetDecompressionSessionError;
137 }
magjed73c0eb52017-08-07 06:55:28 -0700138 }
magjed73c0eb52017-08-07 06:55:28 -0700139 }
140 }
141 if (!_videoFormat) {
142 // We received a frame but we don't have format information so we can't
143 // decode it.
144 // This can happen after backgrounding. We need to wait for the next
145 // sps/pps before we can resume so we request a keyframe by returning an
146 // error.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100147 RTC_LOG(LS_WARNING) << "Missing video format. Frame with sps/pps required.";
magjed73c0eb52017-08-07 06:55:28 -0700148 return WEBRTC_VIDEO_CODEC_ERROR;
149 }
150 CMSampleBufferRef sampleBuffer = nullptr;
151 if (!webrtc::H264AnnexBBufferToCMSampleBuffer((uint8_t *)inputImage.buffer.bytes,
152 inputImage.buffer.length,
153 _videoFormat,
154 &sampleBuffer)) {
155 return WEBRTC_VIDEO_CODEC_ERROR;
156 }
157 RTC_DCHECK(sampleBuffer);
158 VTDecodeFrameFlags decodeFlags = kVTDecodeFrame_EnableAsynchronousDecompression;
159 std::unique_ptr<RTCFrameDecodeParams> frameDecodeParams;
160 frameDecodeParams.reset(new RTCFrameDecodeParams(_callback, inputImage.timeStamp));
161 OSStatus status = VTDecompressionSessionDecodeFrame(
162 _decompressionSession, sampleBuffer, decodeFlags, frameDecodeParams.release(), nullptr);
163#if defined(WEBRTC_IOS)
164 // Re-initialize the decoder if we have an invalid session while the app is
165 // active and retry the decode request.
166 if (status == kVTInvalidSessionErr && [self resetDecompressionSession] == WEBRTC_VIDEO_CODEC_OK) {
167 frameDecodeParams.reset(new RTCFrameDecodeParams(_callback, inputImage.timeStamp));
168 status = VTDecompressionSessionDecodeFrame(
169 _decompressionSession, sampleBuffer, decodeFlags, frameDecodeParams.release(), nullptr);
170 }
171#endif
172 CFRelease(sampleBuffer);
173 if (status != noErr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100174 RTC_LOG(LS_ERROR) << "Failed to decode frame with code: " << status;
magjed73c0eb52017-08-07 06:55:28 -0700175 return WEBRTC_VIDEO_CODEC_ERROR;
176 }
177 return WEBRTC_VIDEO_CODEC_OK;
178}
179
180- (void)setCallback:(RTCVideoDecoderCallback)callback {
181 _callback = callback;
182}
183
Kári Tristan Helgason86de7e82017-12-01 13:48:48 +0100184- (void)setError:(OSStatus)error {
185 _error = error;
186}
187
magjed73c0eb52017-08-07 06:55:28 -0700188- (NSInteger)releaseDecoder {
189 // Need to invalidate the session so that callbacks no longer occur and it
190 // is safe to null out the callback.
191 [self destroyDecompressionSession];
192 [self setVideoFormat:nullptr];
193 _callback = nullptr;
194 return WEBRTC_VIDEO_CODEC_OK;
195}
196
197#pragma mark - Private
198
199- (int)resetDecompressionSession {
200 [self destroyDecompressionSession];
201
202 // Need to wait for the first SPS to initialize decoder.
203 if (!_videoFormat) {
204 return WEBRTC_VIDEO_CODEC_OK;
205 }
206
207 // Set keys for OpenGL and IOSurface compatibilty, which makes the encoder
208 // create pixel buffers with GPU backed memory. The intent here is to pass
209 // the pixel buffers directly so we avoid a texture upload later during
210 // rendering. This currently is moot because we are converting back to an
211 // I420 frame after decode, but eventually we will be able to plumb
212 // CVPixelBuffers directly to the renderer.
213 // TODO(tkchin): Maybe only set OpenGL/IOSurface keys if we know that that
214 // we can pass CVPixelBuffers as native handles in decoder output.
215 static size_t const attributesSize = 3;
216 CFTypeRef keys[attributesSize] = {
217#if defined(WEBRTC_IOS)
218 kCVPixelBufferOpenGLESCompatibilityKey,
219#elif defined(WEBRTC_MAC)
220 kCVPixelBufferOpenGLCompatibilityKey,
221#endif
222 kCVPixelBufferIOSurfacePropertiesKey,
223 kCVPixelBufferPixelFormatTypeKey
224 };
225 CFDictionaryRef ioSurfaceValue = CreateCFTypeDictionary(nullptr, nullptr, 0);
226 int64_t nv12type = kCVPixelFormatType_420YpCbCr8BiPlanarFullRange;
227 CFNumberRef pixelFormat = CFNumberCreate(nullptr, kCFNumberLongType, &nv12type);
228 CFTypeRef values[attributesSize] = {kCFBooleanTrue, ioSurfaceValue, pixelFormat};
229 CFDictionaryRef attributes = CreateCFTypeDictionary(keys, values, attributesSize);
230 if (ioSurfaceValue) {
231 CFRelease(ioSurfaceValue);
232 ioSurfaceValue = nullptr;
233 }
234 if (pixelFormat) {
235 CFRelease(pixelFormat);
236 pixelFormat = nullptr;
237 }
238 VTDecompressionOutputCallbackRecord record = {
Kári Tristan Helgasondb6145f2018-02-13 13:58:10 +0100239 decompressionOutputCallback, (__bridge void *)self,
magjed73c0eb52017-08-07 06:55:28 -0700240 };
241 OSStatus status = VTDecompressionSessionCreate(
242 nullptr, _videoFormat, nullptr, attributes, &record, &_decompressionSession);
243 CFRelease(attributes);
244 if (status != noErr) {
245 [self destroyDecompressionSession];
246 return WEBRTC_VIDEO_CODEC_ERROR;
247 }
248 [self configureDecompressionSession];
249
250 return WEBRTC_VIDEO_CODEC_OK;
251}
252
253- (void)configureDecompressionSession {
254 RTC_DCHECK(_decompressionSession);
255#if defined(WEBRTC_IOS)
256 VTSessionSetProperty(_decompressionSession, kVTDecompressionPropertyKey_RealTime, kCFBooleanTrue);
257#endif
258}
259
260- (void)destroyDecompressionSession {
261 if (_decompressionSession) {
JT Teha6368d12017-09-28 11:00:39 -0700262#if defined(WEBRTC_IOS)
263 if ([UIDevice isIOS11OrLater]) {
264 VTDecompressionSessionWaitForAsynchronousFrames(_decompressionSession);
265 }
266#endif
magjed73c0eb52017-08-07 06:55:28 -0700267 VTDecompressionSessionInvalidate(_decompressionSession);
268 CFRelease(_decompressionSession);
269 _decompressionSession = nullptr;
270 }
271}
272
273- (void)setVideoFormat:(CMVideoFormatDescriptionRef)videoFormat {
274 if (_videoFormat == videoFormat) {
275 return;
276 }
277 if (_videoFormat) {
278 CFRelease(_videoFormat);
279 }
280 _videoFormat = videoFormat;
281 if (_videoFormat) {
282 CFRetain(_videoFormat);
283 }
284}
285
286- (NSString *)implementationName {
287 return @"VideoToolbox";
288}
289
290@end