| 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 | #ifndef WEBRTC_DISABLE_H265 |
| 13 |
| 14 | #import "TGRTCVideoDecoderH265.h" |
| 15 |
| 16 | #import <VideoToolbox/VideoToolbox.h> |
| 17 |
| 18 | #import "base/RTCVideoFrame.h" |
| 19 | #import "base/RTCVideoFrameBuffer.h" |
| 20 | #import "components/video_frame_buffer/RTCCVPixelBuffer.h" |
| 21 | #import "helpers.h" |
| 22 | #import "helpers/scoped_cftyperef.h" |
| 23 |
| 24 | #if defined(WEBRTC_IOS) |
| 25 | #import "helpers/UIDevice+RTCDevice.h" |
| 26 | #endif |
| 27 |
| 28 | #include "modules/video_coding/include/video_error_codes.h" |
| 29 | #include "rtc_base/checks.h" |
| 30 | #include "rtc_base/logging.h" |
| 31 | #include "rtc_base/time_utils.h" |
| 32 | #include "rtc_base/thread.h" |
| 33 | #include "sdk/objc/components/video_codec/nalu_rewriter.h" |
| 34 | #include "h265_nalu_rewriter.h" |
| 35 |
| 36 | #include "StaticThreads.h" |
| 37 |
| 38 | @interface MarkedDecodedH2651RTCCVPixelBuffer : RTCCVPixelBuffer |
| 39 |
| 40 | @end |
| 41 |
| 42 | @implementation MarkedDecodedH2651RTCCVPixelBuffer |
| 43 |
| 44 | @end |
| 45 |
| 46 | typedef void (^TGRTCVideoDecoderRequestKeyframeCallback)(); |
| 47 |
| 48 | // Struct that we pass to the decoder per frame to decode. We receive it again |
| 49 | // in the decoder callback. |
| 50 | struct RTCH265FrameDecodeParams { |
| 51 | RTCH265FrameDecodeParams(RTCVideoDecoderCallback cb, int64_t ts, TGRTCVideoDecoderRequestKeyframeCallback requestFrame) |
| 52 | : callback(cb), timestamp(ts), requestFrame(requestFrame) {} |
| 53 | RTCVideoDecoderCallback callback; |
| 54 | int64_t timestamp; |
| 55 | TGRTCVideoDecoderRequestKeyframeCallback requestFrame; |
| 56 | }; |
| 57 |
| 58 | // This is the callback function that VideoToolbox calls when decode is |
| 59 | // complete. |
| 60 | static void tg_h265DecompressionOutputCallback(void* decoder, |
| 61 | void* params, |
| 62 | OSStatus status, |
| 63 | VTDecodeInfoFlags infoFlags, |
| 64 | CVImageBufferRef imageBuffer, |
| 65 | CMTime timestamp, |
| 66 | CMTime duration) { |
| 67 | std::unique_ptr<RTCH265FrameDecodeParams> decodeParams( |
| 68 | reinterpret_cast<RTCH265FrameDecodeParams*>(params)); |
| 69 | if (status != noErr) { |
| 70 | RTC_LOG(LS_ERROR) << "Failed to decode frame. Status: " << status; |
| 71 | if (status == -12909) { |
| 72 | decodeParams->requestFrame(); |
| 73 | } |
| 74 | return; |
| 75 | } |
| 76 | // TODO(tkchin): Handle CVO properly. |
| 77 | RTCCVPixelBuffer* frameBuffer = |
| 78 | [[MarkedDecodedH2651RTCCVPixelBuffer alloc] initWithPixelBuffer:imageBuffer]; |
| 79 | RTCVideoFrame* decodedFrame = [[RTCVideoFrame alloc] |
| 80 | initWithBuffer:frameBuffer |
| 81 | rotation:RTCVideoRotation_0 |
| 82 | timeStampNs:CMTimeGetSeconds(timestamp) * rtc::kNumNanosecsPerSec]; |
| 83 | decodedFrame.timeStamp = (int32_t)decodeParams->timestamp; |
| 84 | decodeParams->callback(decodedFrame); |
| 85 | } |
| 86 |
| 87 | @interface TGRTCVideoDecoderH265RequestKeyframeHolder : NSObject |
| 88 |
| 89 | @property (nonatomic, strong) NSLock *lock; |
| 90 | @property (nonatomic) bool shouldRequestKeyframe; |
| 91 |
| 92 | @end |
| 93 |
| 94 | @implementation TGRTCVideoDecoderH265RequestKeyframeHolder |
| 95 |
| 96 | - (instancetype)init { |
| 97 | self = [super init]; |
| 98 | if (self != nil) { |
| 99 | _lock = [[NSLock alloc] init]; |
| 100 | } |
| 101 | return self; |
| 102 | } |
| 103 |
| 104 | @end |
| 105 |
| 106 | // Decoder. |
| 107 | @implementation TGRTCVideoDecoderH265 { |
| 108 | CMVideoFormatDescriptionRef _videoFormat; |
| 109 | VTDecompressionSessionRef _decompressionSession; |
| 110 | RTCVideoDecoderCallback _callback; |
| 111 | TGRTCVideoDecoderH265RequestKeyframeHolder *_requestKeyframeHolder; |
| 112 | TGRTCVideoDecoderRequestKeyframeCallback _requestFrame; |
| 113 | OSStatus _error; |
| 114 | } |
| 115 |
| 116 | - (instancetype)init { |
| 117 | if (self = [super init]) { |
| 118 | _requestKeyframeHolder = [[TGRTCVideoDecoderH265RequestKeyframeHolder alloc] init]; |
| 119 | TGRTCVideoDecoderH265RequestKeyframeHolder *requestKeyframeHolder = _requestKeyframeHolder; |
| 120 | _requestFrame = ^{ |
| 121 | [requestKeyframeHolder.lock lock]; |
| 122 | requestKeyframeHolder.shouldRequestKeyframe = true; |
| 123 | [requestKeyframeHolder.lock unlock]; |
| 124 | }; |
| 125 | NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; |
| 126 | #ifdef WEBRTC_IOS |
| 127 | [center addObserver:self |
| 128 | selector:@selector(handleApplicationDidBecomeActive:) |
| 129 | name:UIApplicationWillEnterForegroundNotification |
| 130 | object:[UIApplication sharedApplication]]; |
| 131 | #endif |
| 132 | } |
| 133 |
| 134 | return self; |
| 135 | } |
| 136 |
| 137 | - (void)dealloc { |
| 138 | [self destroyDecompressionSession]; |
| 139 | [self setVideoFormat:nullptr]; |
| 140 | [[NSNotificationCenter defaultCenter] removeObserver:self]; |
| 141 | } |
| 142 |
| 143 | - (NSInteger)startDecodeWithNumberOfCores:(int)numberOfCores { |
| 144 | return WEBRTC_VIDEO_CODEC_OK; |
| 145 | } |
| 146 |
| 147 | - (void)handleApplicationDidBecomeActive:(NSNotification *)notification { |
| 148 | __weak TGRTCVideoDecoderH265 *weakSelf = self; |
| 149 | tgcalls::StaticThreads::getMediaThread()->PostTask([weakSelf]() { |
| 150 | __strong TGRTCVideoDecoderH265 *strongSelf = weakSelf; |
| 151 | if (strongSelf == nil) { |
| 152 | return; |
| 153 | } |
| 154 | strongSelf->_videoFormat = nil; |
| 155 | }); |
| 156 | } |
| 157 |
| 158 | - (NSInteger)decode:(RTCEncodedImage*)inputImage |
| 159 | missingFrames:(BOOL)missingFrames |
| 160 | codecSpecificInfo:(__nullable id<RTCCodecSpecificInfo>)info |
| 161 | renderTimeMs:(int64_t)renderTimeMs { |
| 162 | RTC_DCHECK(inputImage.buffer); |
| 163 |
| 164 | if (_error != noErr) { |
| 165 | RTC_LOG(LS_WARNING) << "Last frame decode failed."; |
| 166 | _error = noErr; |
| 167 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 168 | } |
| 169 |
| 170 | rtc::ScopedCFTypeRef<CMVideoFormatDescriptionRef> inputFormat = |
| 171 | rtc::ScopedCF(webrtc::CreateH265VideoFormatDescription( |
| 172 | (uint8_t*)inputImage.buffer.bytes, inputImage.buffer.length)); |
| 173 | if (inputFormat) { |
| 174 | CMVideoDimensions dimensions = |
| 175 | CMVideoFormatDescriptionGetDimensions(inputFormat.get()); |
| 176 | RTC_LOG(LS_INFO) << "Resolution: " << dimensions.width << " x " |
| 177 | << dimensions.height; |
| 178 | // Check if the video format has changed, and reinitialize decoder if |
| 179 | // needed. |
| 180 | if (!CMFormatDescriptionEqual(inputFormat.get(), _videoFormat)) { |
| 181 | [self setVideoFormat:inputFormat.get()]; |
| 182 | int resetDecompressionSessionError = [self resetDecompressionSession]; |
| 183 | if (resetDecompressionSessionError != WEBRTC_VIDEO_CODEC_OK) { |
| 184 | return resetDecompressionSessionError; |
| 185 | } |
| 186 | } |
| 187 | } |
| 188 | if (!_videoFormat) { |
| 189 | // We received a frame but we don't have format information so we can't |
| 190 | // decode it. |
| 191 | // This can happen after backgrounding. We need to wait for the next |
| 192 | // sps/pps before we can resume so we request a keyframe by returning an |
| 193 | // error. |
| 194 | RTC_LOG(LS_WARNING) << "Missing video format. Frame with sps/pps required."; |
| 195 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 196 | } |
| 197 | CMSampleBufferRef sampleBuffer = nullptr; |
| 198 | if (!webrtc::H265AnnexBBufferToCMSampleBuffer( |
| 199 | (uint8_t*)inputImage.buffer.bytes, inputImage.buffer.length, |
| 200 | _videoFormat, &sampleBuffer)) { |
| 201 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 202 | } |
| 203 | RTC_DCHECK(sampleBuffer); |
| 204 | VTDecodeFrameFlags decodeFlags = |
| 205 | kVTDecodeFrame_EnableAsynchronousDecompression; |
| 206 | std::unique_ptr<RTCH265FrameDecodeParams> frameDecodeParams; |
| 207 | frameDecodeParams.reset( |
| 208 | new RTCH265FrameDecodeParams(_callback, inputImage.timeStamp, _requestFrame)); |
| 209 | OSStatus status = VTDecompressionSessionDecodeFrame( |
| 210 | _decompressionSession, sampleBuffer, decodeFlags, |
| 211 | frameDecodeParams.release(), nullptr); |
| 212 | #if defined(WEBRTC_IOS) |
| 213 | // Re-initialize the decoder if we have an invalid session while the app is |
| 214 | // active and retry the decode request. |
| 215 | if (status == kVTInvalidSessionErr && |
| 216 | [self resetDecompressionSession] == WEBRTC_VIDEO_CODEC_OK) { |
| 217 | frameDecodeParams.reset( |
| 218 | new RTCH265FrameDecodeParams(_callback, inputImage.timeStamp, _requestFrame)); |
| 219 | status = VTDecompressionSessionDecodeFrame( |
| 220 | _decompressionSession, sampleBuffer, decodeFlags, |
| 221 | frameDecodeParams.release(), nullptr); |
| 222 | } |
| 223 | #endif |
| 224 | CFRelease(sampleBuffer); |
| 225 | if (status != noErr) { |
| 226 | RTC_LOG(LS_ERROR) << "Failed to decode frame with code: " << status; |
| 227 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 228 | } |
| 229 |
| 230 | bool requestKeyframe = false; |
| 231 |
| 232 | [_requestKeyframeHolder.lock lock]; |
| 233 | if (_requestKeyframeHolder.shouldRequestKeyframe) { |
| 234 | _requestKeyframeHolder.shouldRequestKeyframe = false; |
| 235 | requestKeyframe = true; |
| 236 | } |
| 237 | [_requestKeyframeHolder.lock unlock]; |
| 238 |
| 239 | if (requestKeyframe) { |
| 240 | RTC_LOG(LS_ERROR) << "Decoder asynchronously asked to request keyframe"; |
| 241 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 242 | } |
| 243 |
| 244 | return WEBRTC_VIDEO_CODEC_OK; |
| 245 | } |
| 246 |
| 247 | - (void)setCallback:(RTCVideoDecoderCallback)callback { |
| 248 | _callback = callback; |
| 249 | } |
| 250 |
| 251 | - (NSInteger)releaseDecoder { |
| 252 | // Need to invalidate the session so that callbacks no longer occur and it |
| 253 | // is safe to null out the callback. |
| 254 | [self destroyDecompressionSession]; |
| 255 | [self setVideoFormat:nullptr]; |
| 256 | _callback = nullptr; |
| 257 | return WEBRTC_VIDEO_CODEC_OK; |
| 258 | } |
| 259 |
| 260 | #pragma mark - Private |
| 261 |
| 262 | - (int)resetDecompressionSession { |
| 263 | [self destroyDecompressionSession]; |
| 264 |
| 265 | // Need to wait for the first SPS to initialize decoder. |
| 266 | if (!_videoFormat) { |
| 267 | return WEBRTC_VIDEO_CODEC_OK; |
| 268 | } |
| 269 |
| 270 | // Set keys for OpenGL and IOSurface compatibilty, which makes the encoder |
| 271 | // create pixel buffers with GPU backed memory. The intent here is to pass |
| 272 | // the pixel buffers directly so we avoid a texture upload later during |
| 273 | // rendering. This currently is moot because we are converting back to an |
| 274 | // I420 frame after decode, but eventually we will be able to plumb |
| 275 | // CVPixelBuffers directly to the renderer. |
| 276 | // TODO(tkchin): Maybe only set OpenGL/IOSurface keys if we know that that |
| 277 | // we can pass CVPixelBuffers as native handles in decoder output. |
| 278 | static size_t const attributesSize = 3; |
| 279 | CFTypeRef keys[attributesSize] = { |
| 280 | #if defined(WEBRTC_IOS) |
| 281 | kCVPixelBufferOpenGLESCompatibilityKey, |
| 282 | #elif defined(WEBRTC_MAC) |
| 283 | kCVPixelBufferOpenGLCompatibilityKey, |
| 284 | #endif |
| 285 | kCVPixelBufferIOSurfacePropertiesKey, |
| 286 | kCVPixelBufferPixelFormatTypeKey |
| 287 | }; |
| 288 | CFDictionaryRef ioSurfaceValue = CreateCFTypeDictionary(nullptr, nullptr, 0); |
| 289 | int64_t nv12type = kCVPixelFormatType_420YpCbCr8BiPlanarFullRange; |
| 290 | CFNumberRef pixelFormat = |
| 291 | CFNumberCreate(nullptr, kCFNumberLongType, &nv12type); |
| 292 | CFTypeRef values[attributesSize] = {kCFBooleanTrue, ioSurfaceValue, |
| 293 | pixelFormat}; |
| 294 | CFDictionaryRef attributes = |
| 295 | CreateCFTypeDictionary(keys, values, attributesSize); |
| 296 | if (ioSurfaceValue) { |
| 297 | CFRelease(ioSurfaceValue); |
| 298 | ioSurfaceValue = nullptr; |
| 299 | } |
| 300 | if (pixelFormat) { |
| 301 | CFRelease(pixelFormat); |
| 302 | pixelFormat = nullptr; |
| 303 | } |
| 304 | VTDecompressionOutputCallbackRecord record = { |
| 305 | tg_h265DecompressionOutputCallback, |
| 306 | nullptr, |
| 307 | }; |
| 308 | OSStatus status = |
| 309 | VTDecompressionSessionCreate(nullptr, _videoFormat, nullptr, attributes, |
| 310 | &record, &_decompressionSession); |
| 311 | CFRelease(attributes); |
| 312 | if (status != noErr) { |
| 313 | [self destroyDecompressionSession]; |
| 314 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 315 | } |
| 316 | [self configureDecompressionSession]; |
| 317 |
| 318 | return WEBRTC_VIDEO_CODEC_OK; |
| 319 | } |
| 320 |
| 321 | - (void)configureDecompressionSession { |
| 322 | RTC_DCHECK(_decompressionSession); |
| 323 | #if defined(WEBRTC_IOS) |
| 324 | // VTSessionSetProperty(_decompressionSession, |
| 325 | // kVTDecompressionPropertyKey_RealTime, kCFBooleanTrue); |
| 326 | #endif |
| 327 | } |
| 328 |
| 329 | - (void)destroyDecompressionSession { |
| 330 | if (_decompressionSession) { |
| 331 | #if defined(WEBRTC_IOS) |
| 332 | VTDecompressionSessionWaitForAsynchronousFrames(_decompressionSession); |
| 333 | #endif |
| 334 | VTDecompressionSessionInvalidate(_decompressionSession); |
| 335 | CFRelease(_decompressionSession); |
| 336 | _decompressionSession = nullptr; |
| 337 | } |
| 338 | } |
| 339 |
| 340 | - (void)setVideoFormat:(CMVideoFormatDescriptionRef)videoFormat { |
| 341 | if (_videoFormat == videoFormat) { |
| 342 | return; |
| 343 | } |
| 344 | if (_videoFormat) { |
| 345 | CFRelease(_videoFormat); |
| 346 | } |
| 347 | _videoFormat = videoFormat; |
| 348 | if (_videoFormat) { |
| 349 | CFRetain(_videoFormat); |
| 350 | } |
| 351 | } |
| 352 |
| 353 | - (NSString*)implementationName { |
| 354 | return @"VideoToolbox"; |
| 355 | } |
| 356 |
| 357 | @end |
| 358 |
| 359 | #endif |
| 360 |