blob: 2871b8a5ef11eaf2f25fe99d85c5b9c019b716a8 [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]) {
Anders Carlsson358f2e02018-06-04 10:24:37 +020081#if defined(WEBRTC_IOS) && !defined(RTC_APPRTCMOBILE_BROADCAST_EXTENSION)
andersc9a85f072017-09-13 07:31:46 -070082 [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
Anders Carlsson2a1bbc32018-04-04 12:49:43 +020095- (NSInteger)startDecodeWithNumberOfCores:(int)numberOfCores {
96 return WEBRTC_VIDEO_CODEC_OK;
97}
98
magjed73c0eb52017-08-07 06:55:28 -070099- (NSInteger)startDecodeWithSettings:(RTCVideoEncoderSettings *)settings
100 numberOfCores:(int)numberOfCores {
101 return WEBRTC_VIDEO_CODEC_OK;
102}
103
Niels Möllerc199fae2018-04-26 09:54:25 +0200104- (NSInteger)decode:(RTCEncodedImage *)inputImage
105 missingFrames:(BOOL)missingFrames
106 codecSpecificInfo:(nullable id<RTCCodecSpecificInfo>)info
107 renderTimeMs:(int64_t)renderTimeMs {
magjed73c0eb52017-08-07 06:55:28 -0700108 RTC_DCHECK(inputImage.buffer);
109
Kári Tristan Helgason86de7e82017-12-01 13:48:48 +0100110 if (_error != noErr) {
111 RTC_LOG(LS_WARNING) << "Last frame decode failed.";
112 _error = noErr;
113 return WEBRTC_VIDEO_CODEC_ERROR;
114 }
115
Anders Carlsson358f2e02018-06-04 10:24:37 +0200116#if defined(WEBRTC_IOS) && !defined(RTC_APPRTCMOBILE_BROADCAST_EXTENSION)
magjed73c0eb52017-08-07 06:55:28 -0700117 if (![[RTCUIApplicationStatusObserver sharedInstance] isApplicationActive]) {
118 // Ignore all decode requests when app isn't active. In this state, the
119 // hardware decoder has been invalidated by the OS.
120 // Reset video format so that we won't process frames until the next
121 // keyframe.
122 [self setVideoFormat:nullptr];
123 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
124 }
125#endif
Guy Hershenbaum2fcb8342018-02-20 21:33:36 -0800126 rtc::ScopedCFTypeRef<CMVideoFormatDescriptionRef> inputFormat =
127 rtc::ScopedCF(webrtc::CreateVideoFormatDescription((uint8_t *)inputImage.buffer.bytes,
128 inputImage.buffer.length));
129 if (inputFormat) {
130 // Check if the video format has changed, and reinitialize decoder if
131 // needed.
132 if (!CMFormatDescriptionEqual(inputFormat.get(), _videoFormat)) {
133 [self setVideoFormat:inputFormat.get()];
134 int resetDecompressionSessionError = [self resetDecompressionSession];
135 if (resetDecompressionSessionError != WEBRTC_VIDEO_CODEC_OK) {
136 return resetDecompressionSessionError;
magjed73c0eb52017-08-07 06:55:28 -0700137 }
magjed73c0eb52017-08-07 06:55:28 -0700138 }
139 }
140 if (!_videoFormat) {
141 // We received a frame but we don't have format information so we can't
142 // decode it.
143 // This can happen after backgrounding. We need to wait for the next
144 // sps/pps before we can resume so we request a keyframe by returning an
145 // error.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100146 RTC_LOG(LS_WARNING) << "Missing video format. Frame with sps/pps required.";
magjed73c0eb52017-08-07 06:55:28 -0700147 return WEBRTC_VIDEO_CODEC_ERROR;
148 }
149 CMSampleBufferRef sampleBuffer = nullptr;
150 if (!webrtc::H264AnnexBBufferToCMSampleBuffer((uint8_t *)inputImage.buffer.bytes,
151 inputImage.buffer.length,
152 _videoFormat,
153 &sampleBuffer)) {
154 return WEBRTC_VIDEO_CODEC_ERROR;
155 }
156 RTC_DCHECK(sampleBuffer);
157 VTDecodeFrameFlags decodeFlags = kVTDecodeFrame_EnableAsynchronousDecompression;
158 std::unique_ptr<RTCFrameDecodeParams> frameDecodeParams;
159 frameDecodeParams.reset(new RTCFrameDecodeParams(_callback, inputImage.timeStamp));
160 OSStatus status = VTDecompressionSessionDecodeFrame(
161 _decompressionSession, sampleBuffer, decodeFlags, frameDecodeParams.release(), nullptr);
162#if defined(WEBRTC_IOS)
163 // Re-initialize the decoder if we have an invalid session while the app is
164 // active and retry the decode request.
165 if (status == kVTInvalidSessionErr && [self resetDecompressionSession] == WEBRTC_VIDEO_CODEC_OK) {
166 frameDecodeParams.reset(new RTCFrameDecodeParams(_callback, inputImage.timeStamp));
167 status = VTDecompressionSessionDecodeFrame(
168 _decompressionSession, sampleBuffer, decodeFlags, frameDecodeParams.release(), nullptr);
169 }
170#endif
171 CFRelease(sampleBuffer);
172 if (status != noErr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100173 RTC_LOG(LS_ERROR) << "Failed to decode frame with code: " << status;
magjed73c0eb52017-08-07 06:55:28 -0700174 return WEBRTC_VIDEO_CODEC_ERROR;
175 }
176 return WEBRTC_VIDEO_CODEC_OK;
177}
178
179- (void)setCallback:(RTCVideoDecoderCallback)callback {
180 _callback = callback;
181}
182
Kári Tristan Helgason86de7e82017-12-01 13:48:48 +0100183- (void)setError:(OSStatus)error {
184 _error = error;
185}
186
magjed73c0eb52017-08-07 06:55:28 -0700187- (NSInteger)releaseDecoder {
188 // Need to invalidate the session so that callbacks no longer occur and it
189 // is safe to null out the callback.
190 [self destroyDecompressionSession];
191 [self setVideoFormat:nullptr];
192 _callback = nullptr;
193 return WEBRTC_VIDEO_CODEC_OK;
194}
195
196#pragma mark - Private
197
198- (int)resetDecompressionSession {
199 [self destroyDecompressionSession];
200
201 // Need to wait for the first SPS to initialize decoder.
202 if (!_videoFormat) {
203 return WEBRTC_VIDEO_CODEC_OK;
204 }
205
206 // Set keys for OpenGL and IOSurface compatibilty, which makes the encoder
207 // create pixel buffers with GPU backed memory. The intent here is to pass
208 // the pixel buffers directly so we avoid a texture upload later during
209 // rendering. This currently is moot because we are converting back to an
210 // I420 frame after decode, but eventually we will be able to plumb
211 // CVPixelBuffers directly to the renderer.
212 // TODO(tkchin): Maybe only set OpenGL/IOSurface keys if we know that that
213 // we can pass CVPixelBuffers as native handles in decoder output.
214 static size_t const attributesSize = 3;
215 CFTypeRef keys[attributesSize] = {
216#if defined(WEBRTC_IOS)
217 kCVPixelBufferOpenGLESCompatibilityKey,
218#elif defined(WEBRTC_MAC)
219 kCVPixelBufferOpenGLCompatibilityKey,
220#endif
221 kCVPixelBufferIOSurfacePropertiesKey,
222 kCVPixelBufferPixelFormatTypeKey
223 };
224 CFDictionaryRef ioSurfaceValue = CreateCFTypeDictionary(nullptr, nullptr, 0);
225 int64_t nv12type = kCVPixelFormatType_420YpCbCr8BiPlanarFullRange;
226 CFNumberRef pixelFormat = CFNumberCreate(nullptr, kCFNumberLongType, &nv12type);
227 CFTypeRef values[attributesSize] = {kCFBooleanTrue, ioSurfaceValue, pixelFormat};
228 CFDictionaryRef attributes = CreateCFTypeDictionary(keys, values, attributesSize);
229 if (ioSurfaceValue) {
230 CFRelease(ioSurfaceValue);
231 ioSurfaceValue = nullptr;
232 }
233 if (pixelFormat) {
234 CFRelease(pixelFormat);
235 pixelFormat = nullptr;
236 }
237 VTDecompressionOutputCallbackRecord record = {
Kári Tristan Helgasondb6145f2018-02-13 13:58:10 +0100238 decompressionOutputCallback, (__bridge void *)self,
magjed73c0eb52017-08-07 06:55:28 -0700239 };
240 OSStatus status = VTDecompressionSessionCreate(
241 nullptr, _videoFormat, nullptr, attributes, &record, &_decompressionSession);
242 CFRelease(attributes);
243 if (status != noErr) {
Yura Yaroshevich27af5db2018-04-10 19:43:20 +0300244 RTC_LOG(LS_ERROR) << "Failed to create decompression session: " << status;
magjed73c0eb52017-08-07 06:55:28 -0700245 [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