blob: debd5047907fccde78df2306a638dcd8eae9f1a3 [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"
25
26#if defined(WEBRTC_IOS)
27#import "Common/RTCUIApplicationStatusObserver.h"
JT Teha6368d12017-09-28 11:00:39 -070028#import "WebRTC/UIDevice+RTCDevice.h"
magjed73c0eb52017-08-07 06:55:28 -070029#endif
30
31// Struct that we pass to the decoder per frame to decode. We receive it again
32// in the decoder callback.
33struct RTCFrameDecodeParams {
34 RTCFrameDecodeParams(RTCVideoDecoderCallback cb, int64_t ts) : callback(cb), timestamp(ts) {}
35 RTCVideoDecoderCallback callback;
36 int64_t timestamp;
37};
38
Kári Tristan Helgason86de7e82017-12-01 13:48:48 +010039@interface RTCVideoDecoderH264 ()
40- (void)setError:(OSStatus)error;
41@end
42
magjed73c0eb52017-08-07 06:55:28 -070043// This is the callback function that VideoToolbox calls when decode is
44// complete.
Kári Tristan Helgason86de7e82017-12-01 13:48:48 +010045void decompressionOutputCallback(void *decoderRef,
magjed73c0eb52017-08-07 06:55:28 -070046 void *params,
47 OSStatus status,
48 VTDecodeInfoFlags infoFlags,
49 CVImageBufferRef imageBuffer,
50 CMTime timestamp,
51 CMTime duration) {
52 std::unique_ptr<RTCFrameDecodeParams> decodeParams(
53 reinterpret_cast<RTCFrameDecodeParams *>(params));
54 if (status != noErr) {
Kári Tristan Helgason86de7e82017-12-01 13:48:48 +010055 RTCVideoDecoderH264 *decoder = (__bridge RTCVideoDecoderH264 *)decoderRef;
56 [decoder setError:status];
Mirko Bonadei675513b2017-11-09 11:09:25 +010057 RTC_LOG(LS_ERROR) << "Failed to decode frame. Status: " << status;
magjed73c0eb52017-08-07 06:55:28 -070058 return;
59 }
60 // TODO(tkchin): Handle CVO properly.
61 RTCCVPixelBuffer *frameBuffer = [[RTCCVPixelBuffer alloc] initWithPixelBuffer:imageBuffer];
62 RTCVideoFrame *decodedFrame =
63 [[RTCVideoFrame alloc] initWithBuffer:frameBuffer
64 rotation:RTCVideoRotation_0
65 timeStampNs:CMTimeGetSeconds(timestamp) * rtc::kNumNanosecsPerSec];
66 decodedFrame.timeStamp = decodeParams->timestamp;
67 decodeParams->callback(decodedFrame);
68}
69
70// Decoder.
71@implementation RTCVideoDecoderH264 {
72 CMVideoFormatDescriptionRef _videoFormat;
73 VTDecompressionSessionRef _decompressionSession;
74 RTCVideoDecoderCallback _callback;
Kári Tristan Helgason86de7e82017-12-01 13:48:48 +010075 OSStatus _error;
magjed73c0eb52017-08-07 06:55:28 -070076}
77
andersc9a85f072017-09-13 07:31:46 -070078- (instancetype)init {
79 if (self = [super init]) {
80#if defined(WEBRTC_IOS)
81 [RTCUIApplicationStatusObserver prepareForUse];
Kári Tristan Helgason86de7e82017-12-01 13:48:48 +010082 _error = noErr;
andersc9a85f072017-09-13 07:31:46 -070083#endif
84 }
85
86 return self;
87}
88
magjed73c0eb52017-08-07 06:55:28 -070089- (void)dealloc {
90 [self destroyDecompressionSession];
91 [self setVideoFormat:nullptr];
92}
93
94- (NSInteger)startDecodeWithSettings:(RTCVideoEncoderSettings *)settings
95 numberOfCores:(int)numberOfCores {
96 return WEBRTC_VIDEO_CODEC_OK;
97}
98
99- (NSInteger)decode:(RTCEncodedImage *)inputImage
100 missingFrames:(BOOL)missingFrames
101 fragmentationHeader:(RTCRtpFragmentationHeader *)fragmentationHeader
102 codecSpecificInfo:(__nullable id<RTCCodecSpecificInfo>)info
103 renderTimeMs:(int64_t)renderTimeMs {
104 RTC_DCHECK(inputImage.buffer);
105
Kári Tristan Helgason86de7e82017-12-01 13:48:48 +0100106 if (_error != noErr) {
107 RTC_LOG(LS_WARNING) << "Last frame decode failed.";
108 _error = noErr;
109 return WEBRTC_VIDEO_CODEC_ERROR;
110 }
111
magjed73c0eb52017-08-07 06:55:28 -0700112#if defined(WEBRTC_IOS)
113 if (![[RTCUIApplicationStatusObserver sharedInstance] isApplicationActive]) {
114 // Ignore all decode requests when app isn't active. In this state, the
115 // hardware decoder has been invalidated by the OS.
116 // Reset video format so that we won't process frames until the next
117 // keyframe.
118 [self setVideoFormat:nullptr];
119 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
120 }
121#endif
122 CMVideoFormatDescriptionRef inputFormat = nullptr;
123 if (webrtc::H264AnnexBBufferHasVideoFormatDescription((uint8_t *)inputImage.buffer.bytes,
124 inputImage.buffer.length)) {
125 inputFormat = webrtc::CreateVideoFormatDescription((uint8_t *)inputImage.buffer.bytes,
126 inputImage.buffer.length);
127 if (inputFormat) {
128 // Check if the video format has changed, and reinitialize decoder if
129 // needed.
130 if (!CMFormatDescriptionEqual(inputFormat, _videoFormat)) {
131 [self setVideoFormat:inputFormat];
132 [self resetDecompressionSession];
133 }
134 CFRelease(inputFormat);
135 }
136 }
137 if (!_videoFormat) {
138 // We received a frame but we don't have format information so we can't
139 // decode it.
140 // This can happen after backgrounding. We need to wait for the next
141 // sps/pps before we can resume so we request a keyframe by returning an
142 // error.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100143 RTC_LOG(LS_WARNING) << "Missing video format. Frame with sps/pps required.";
magjed73c0eb52017-08-07 06:55:28 -0700144 return WEBRTC_VIDEO_CODEC_ERROR;
145 }
146 CMSampleBufferRef sampleBuffer = nullptr;
147 if (!webrtc::H264AnnexBBufferToCMSampleBuffer((uint8_t *)inputImage.buffer.bytes,
148 inputImage.buffer.length,
149 _videoFormat,
150 &sampleBuffer)) {
151 return WEBRTC_VIDEO_CODEC_ERROR;
152 }
153 RTC_DCHECK(sampleBuffer);
154 VTDecodeFrameFlags decodeFlags = kVTDecodeFrame_EnableAsynchronousDecompression;
155 std::unique_ptr<RTCFrameDecodeParams> frameDecodeParams;
156 frameDecodeParams.reset(new RTCFrameDecodeParams(_callback, inputImage.timeStamp));
157 OSStatus status = VTDecompressionSessionDecodeFrame(
158 _decompressionSession, sampleBuffer, decodeFlags, frameDecodeParams.release(), nullptr);
159#if defined(WEBRTC_IOS)
160 // Re-initialize the decoder if we have an invalid session while the app is
161 // active and retry the decode request.
162 if (status == kVTInvalidSessionErr && [self resetDecompressionSession] == WEBRTC_VIDEO_CODEC_OK) {
163 frameDecodeParams.reset(new RTCFrameDecodeParams(_callback, inputImage.timeStamp));
164 status = VTDecompressionSessionDecodeFrame(
165 _decompressionSession, sampleBuffer, decodeFlags, frameDecodeParams.release(), nullptr);
166 }
167#endif
168 CFRelease(sampleBuffer);
169 if (status != noErr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100170 RTC_LOG(LS_ERROR) << "Failed to decode frame with code: " << status;
magjed73c0eb52017-08-07 06:55:28 -0700171 return WEBRTC_VIDEO_CODEC_ERROR;
172 }
173 return WEBRTC_VIDEO_CODEC_OK;
174}
175
176- (void)setCallback:(RTCVideoDecoderCallback)callback {
177 _callback = callback;
178}
179
Kári Tristan Helgason86de7e82017-12-01 13:48:48 +0100180- (void)setError:(OSStatus)error {
181 _error = error;
182}
183
magjed73c0eb52017-08-07 06:55:28 -0700184- (NSInteger)releaseDecoder {
185 // Need to invalidate the session so that callbacks no longer occur and it
186 // is safe to null out the callback.
187 [self destroyDecompressionSession];
188 [self setVideoFormat:nullptr];
189 _callback = nullptr;
190 return WEBRTC_VIDEO_CODEC_OK;
191}
192
193#pragma mark - Private
194
195- (int)resetDecompressionSession {
196 [self destroyDecompressionSession];
197
198 // Need to wait for the first SPS to initialize decoder.
199 if (!_videoFormat) {
200 return WEBRTC_VIDEO_CODEC_OK;
201 }
202
203 // Set keys for OpenGL and IOSurface compatibilty, which makes the encoder
204 // create pixel buffers with GPU backed memory. The intent here is to pass
205 // the pixel buffers directly so we avoid a texture upload later during
206 // rendering. This currently is moot because we are converting back to an
207 // I420 frame after decode, but eventually we will be able to plumb
208 // CVPixelBuffers directly to the renderer.
209 // TODO(tkchin): Maybe only set OpenGL/IOSurface keys if we know that that
210 // we can pass CVPixelBuffers as native handles in decoder output.
211 static size_t const attributesSize = 3;
212 CFTypeRef keys[attributesSize] = {
213#if defined(WEBRTC_IOS)
214 kCVPixelBufferOpenGLESCompatibilityKey,
215#elif defined(WEBRTC_MAC)
216 kCVPixelBufferOpenGLCompatibilityKey,
217#endif
218 kCVPixelBufferIOSurfacePropertiesKey,
219 kCVPixelBufferPixelFormatTypeKey
220 };
221 CFDictionaryRef ioSurfaceValue = CreateCFTypeDictionary(nullptr, nullptr, 0);
222 int64_t nv12type = kCVPixelFormatType_420YpCbCr8BiPlanarFullRange;
223 CFNumberRef pixelFormat = CFNumberCreate(nullptr, kCFNumberLongType, &nv12type);
224 CFTypeRef values[attributesSize] = {kCFBooleanTrue, ioSurfaceValue, pixelFormat};
225 CFDictionaryRef attributes = CreateCFTypeDictionary(keys, values, attributesSize);
226 if (ioSurfaceValue) {
227 CFRelease(ioSurfaceValue);
228 ioSurfaceValue = nullptr;
229 }
230 if (pixelFormat) {
231 CFRelease(pixelFormat);
232 pixelFormat = nullptr;
233 }
234 VTDecompressionOutputCallbackRecord record = {
235 decompressionOutputCallback, nullptr,
236 };
237 OSStatus status = VTDecompressionSessionCreate(
238 nullptr, _videoFormat, nullptr, attributes, &record, &_decompressionSession);
239 CFRelease(attributes);
240 if (status != noErr) {
241 [self destroyDecompressionSession];
242 return WEBRTC_VIDEO_CODEC_ERROR;
243 }
244 [self configureDecompressionSession];
245
246 return WEBRTC_VIDEO_CODEC_OK;
247}
248
249- (void)configureDecompressionSession {
250 RTC_DCHECK(_decompressionSession);
251#if defined(WEBRTC_IOS)
252 VTSessionSetProperty(_decompressionSession, kVTDecompressionPropertyKey_RealTime, kCFBooleanTrue);
253#endif
254}
255
256- (void)destroyDecompressionSession {
257 if (_decompressionSession) {
JT Teha6368d12017-09-28 11:00:39 -0700258#if defined(WEBRTC_IOS)
259 if ([UIDevice isIOS11OrLater]) {
260 VTDecompressionSessionWaitForAsynchronousFrames(_decompressionSession);
261 }
262#endif
magjed73c0eb52017-08-07 06:55:28 -0700263 VTDecompressionSessionInvalidate(_decompressionSession);
264 CFRelease(_decompressionSession);
265 _decompressionSession = nullptr;
266 }
267}
268
269- (void)setVideoFormat:(CMVideoFormatDescriptionRef)videoFormat {
270 if (_videoFormat == videoFormat) {
271 return;
272 }
273 if (_videoFormat) {
274 CFRelease(_videoFormat);
275 }
276 _videoFormat = videoFormat;
277 if (_videoFormat) {
278 CFRetain(_videoFormat);
279 }
280}
281
282- (NSString *)implementationName {
283 return @"VideoToolbox";
284}
285
286@end