| 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 | #import "GLVideoView.h" |
| 12 |
| 13 | #import <GLKit/GLKit.h> |
| 14 |
| 15 | #import "RTCDefaultShader.h" |
| 16 | #import "RTCDisplayLinkTimer.h" |
| 17 | #import "RTCI420TextureCache.h" |
| 18 | #import "RTCNV12TextureCache.h" |
| 19 | #import "base/RTCLogging.h" |
| 20 | #import "base/RTCVideoFrame.h" |
| 21 | #import "base/RTCVideoFrameBuffer.h" |
| 22 | #import "components/video_frame_buffer/RTCCVPixelBuffer.h" |
| 23 | #include "sdk/objc/native/api/video_frame.h" |
| 24 | #import "rtc_base/time_utils.h" |
| 25 | #include "sdk/objc/native/src/objc_frame_buffer.h" |
| 26 |
| 27 | namespace { |
| 28 |
| 29 | static RTCVideoFrame *customToObjCVideoFrame(const webrtc::VideoFrame &frame, RTCVideoRotation &rotation) { |
| 30 | rotation = RTCVideoRotation(frame.rotation()); |
| 31 | RTCVideoFrame *videoFrame = |
| 32 | [[RTCVideoFrame alloc] initWithBuffer:webrtc::ToObjCVideoFrameBuffer(frame.video_frame_buffer()) |
| 33 | rotation:RTCVideoRotation_90 |
| 34 | timeStampNs:frame.timestamp_us() * rtc::kNumNanosecsPerMicrosec]; |
| 35 | videoFrame.timeStamp = frame.timestamp(); |
| 36 |
| 37 | return videoFrame; |
| 38 | } |
| 39 |
| 40 | class VideoRendererAdapterImpl : public rtc::VideoSinkInterface<webrtc::VideoFrame> { |
| 41 | public: |
| 42 | VideoRendererAdapterImpl(void (^frameReceived)(CGSize, RTCVideoFrame *, RTCVideoRotation)) { |
| 43 | _frameReceived = [frameReceived copy]; |
| 44 | } |
| 45 |
| 46 | void OnFrame(const webrtc::VideoFrame& nativeVideoFrame) override { |
| 47 | RTCVideoRotation rotation = RTCVideoRotation_90; |
| 48 | RTCVideoFrame* videoFrame = customToObjCVideoFrame(nativeVideoFrame, rotation); |
| 49 |
| 50 | CGSize currentSize = CGSizeMake(videoFrame.height, videoFrame.width); |
| 51 |
| 52 | if (_frameReceived) { |
| 53 | _frameReceived(currentSize, videoFrame, rotation); |
| 54 | } |
| 55 | } |
| 56 |
| 57 | private: |
| 58 | void (^_frameReceived)(CGSize, RTCVideoFrame *, RTCVideoRotation); |
| 59 | }; |
| 60 |
| 61 | } |
| 62 |
| 63 | static CGSize scaleToFillSize(CGSize size, CGSize maxSize) { |
| 64 | if (size.width < 1.0f) { |
| 65 | size.width = 1.0f; |
| 66 | } |
| 67 | if (size.height < 1.0f) { |
| 68 | size.height = 1.0f; |
| 69 | } |
| 70 | if (size.width < maxSize.width) { |
| 71 | size.height = floor(maxSize.width * size.height / MAX(1.0f, size.width)); |
| 72 | size.width = maxSize.width; |
| 73 | } |
| 74 | if (size.height < maxSize.height) { |
| 75 | size.width = floor(maxSize.height * size.width / MAX(1.0f, size.height)); |
| 76 | size.height = maxSize.height; |
| 77 | } |
| 78 | return size; |
| 79 | } |
| 80 |
| 81 | // GLVideoView wraps a GLKView which is setup with |
| 82 | // enableSetNeedsDisplay = NO for the purpose of gaining control of |
| 83 | // exactly when to call -[GLKView display]. This need for extra |
| 84 | // control is required to avoid triggering method calls on GLKView |
| 85 | // that results in attempting to bind the underlying render buffer |
| 86 | // when the drawable size would be empty which would result in the |
| 87 | // error GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT. -[GLKView display] is |
| 88 | // the method that will trigger the binding of the render |
| 89 | // buffer. Because the standard behaviour of -[UIView setNeedsDisplay] |
| 90 | // is disabled for the reasons above, the GLVideoView maintains |
| 91 | // its own |isDirty| flag. |
| 92 |
| 93 | @interface GLVideoView () <GLKViewDelegate> |
| 94 | // |videoFrame| is set when we receive a frame from a worker thread and is read |
| 95 | // from the display link callback so atomicity is required. |
| 96 | @property(atomic, strong) RTCVideoFrame *videoFrame; |
| 97 | @property(nonatomic, readonly) GLKView *glkView; |
| 98 | @end |
| 99 |
| 100 | @implementation GLVideoView { |
| 101 | RTCDisplayLinkTimer *_timer; |
| 102 | EAGLContext *_glContext; |
| 103 | // This flag should only be set and read on the main thread (e.g. by |
| 104 | // setNeedsDisplay) |
| 105 | BOOL _isDirty; |
| 106 | id<RTCVideoViewShading> _shader; |
| 107 | RTCNV12TextureCache *_nv12TextureCache; |
| 108 | RTCI420TextureCache *_i420TextureCache; |
| 109 | // As timestamps should be unique between frames, will store last |
| 110 | // drawn frame timestamp instead of the whole frame to reduce memory usage. |
| 111 | int64_t _lastDrawnFrameTimeStampNs; |
| 112 |
| 113 | CGSize _currentSize; |
| 114 |
| 115 | void (^_onFirstFrameReceived)(); |
| 116 | bool _firstFrameReceivedReported; |
| 117 |
| 118 | void (^_onOrientationUpdated)(int); |
| 119 |
| 120 | std::shared_ptr<VideoRendererAdapterImpl> _sink; |
| 121 | } |
| 122 |
| 123 | @synthesize delegate = _delegate; |
| 124 | @synthesize videoFrame = _videoFrame; |
| 125 | @synthesize glkView = _glkView; |
| 126 | @synthesize rotationOverride = _rotationOverride; |
| 127 |
| 128 | - (instancetype)initWithFrame:(CGRect)frame { |
| 129 | return [self initWithFrame:frame shader:[[RTCDefaultShader alloc] init]]; |
| 130 | } |
| 131 |
| 132 | - (instancetype)initWithCoder:(NSCoder *)aDecoder { |
| 133 | return [self initWithCoder:aDecoder shader:[[RTCDefaultShader alloc] init]]; |
| 134 | } |
| 135 |
| 136 | - (instancetype)initWithFrame:(CGRect)frame shader:(id<RTCVideoViewShading>)shader { |
| 137 | if (self = [super initWithFrame:frame]) { |
| 138 | _shader = shader; |
| 139 | if (![self configure]) { |
| 140 | return nil; |
| 141 | } |
| 142 | } |
| 143 | return self; |
| 144 | } |
| 145 |
| 146 | - (instancetype)initWithCoder:(NSCoder *)aDecoder shader:(id<RTCVideoViewShading>)shader { |
| 147 | if (self = [super initWithCoder:aDecoder]) { |
| 148 | _shader = shader; |
| 149 | if (![self configure]) { |
| 150 | return nil; |
| 151 | } |
| 152 | } |
| 153 | return self; |
| 154 | } |
| 155 |
| 156 | - (BOOL)configure { |
| 157 | EAGLContext *glContext = |
| 158 | [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES3]; |
| 159 | if (!glContext) { |
| 160 | glContext = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2]; |
| 161 | } |
| 162 | if (!glContext) { |
| 163 | RTCLogError(@"Failed to create EAGLContext"); |
| 164 | return NO; |
| 165 | } |
| 166 | _glContext = glContext; |
| 167 |
| 168 | // GLKView manages a framebuffer for us. |
| 169 | _glkView = [[GLKView alloc] initWithFrame:CGRectZero |
| 170 | context:_glContext]; |
| 171 | _glkView.drawableColorFormat = GLKViewDrawableColorFormatRGBA8888; |
| 172 | _glkView.drawableDepthFormat = GLKViewDrawableDepthFormatNone; |
| 173 | _glkView.drawableStencilFormat = GLKViewDrawableStencilFormatNone; |
| 174 | _glkView.drawableMultisample = GLKViewDrawableMultisampleNone; |
| 175 | _glkView.delegate = self; |
| 176 | _glkView.layer.masksToBounds = YES; |
| 177 | _glkView.enableSetNeedsDisplay = NO; |
| 178 | [self addSubview:_glkView]; |
| 179 |
| 180 | // Listen to application state in order to clean up OpenGL before app goes |
| 181 | // away. |
| 182 | NSNotificationCenter *notificationCenter = |
| 183 | [NSNotificationCenter defaultCenter]; |
| 184 | [notificationCenter addObserver:self |
| 185 | selector:@selector(willResignActive) |
| 186 | name:UIApplicationWillResignActiveNotification |
| 187 | object:nil]; |
| 188 | [notificationCenter addObserver:self |
| 189 | selector:@selector(didBecomeActive) |
| 190 | name:UIApplicationDidBecomeActiveNotification |
| 191 | object:nil]; |
| 192 |
| 193 | // Frames are received on a separate thread, so we poll for current frame |
| 194 | // using a refresh rate proportional to screen refresh frequency. This |
| 195 | // occurs on the main thread. |
| 196 | __weak GLVideoView *weakSelf = self; |
| 197 | _timer = [[RTCDisplayLinkTimer alloc] initWithTimerHandler:^{ |
| 198 | GLVideoView *strongSelf = weakSelf; |
| 199 | [strongSelf displayLinkTimerDidFire]; |
| 200 | }]; |
| 201 | if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) { |
| 202 | [self setupGL]; |
| 203 | } |
| 204 |
| 205 | _sink.reset(new VideoRendererAdapterImpl(^(CGSize size, RTCVideoFrame *videoFrame, RTCVideoRotation rotation) { |
| 206 | dispatch_async(dispatch_get_main_queue(), ^{ |
| 207 | __strong GLVideoView *strongSelf = weakSelf; |
| 208 | if (strongSelf == nil) { |
| 209 | return; |
| 210 | } |
| 211 | if (!CGSizeEqualToSize(size, strongSelf->_currentSize)) { |
| 212 | strongSelf->_currentSize = size; |
| 213 | [strongSelf setSize:size]; |
| 214 | } |
| 215 |
| 216 | int mappedValue = 0; |
| 217 | switch (rotation) { |
| 218 | case RTCVideoRotation_90: |
| 219 | mappedValue = 0; |
| 220 | break; |
| 221 | case RTCVideoRotation_180: |
| 222 | mappedValue = 1; |
| 223 | break; |
| 224 | case RTCVideoRotation_270: |
| 225 | mappedValue = 2; |
| 226 | break; |
| 227 | default: |
| 228 | mappedValue = 0; |
| 229 | break; |
| 230 | } |
| 231 | [strongSelf setInternalOrientation:mappedValue]; |
| 232 |
| 233 | [strongSelf renderFrame:videoFrame]; |
| 234 | }); |
| 235 | })); |
| 236 |
| 237 | return YES; |
| 238 | } |
| 239 |
| 240 | - (void)setMultipleTouchEnabled:(BOOL)multipleTouchEnabled { |
| 241 | [super setMultipleTouchEnabled:multipleTouchEnabled]; |
| 242 | _glkView.multipleTouchEnabled = multipleTouchEnabled; |
| 243 | } |
| 244 |
| 245 | - (void)dealloc { |
| 246 | [[NSNotificationCenter defaultCenter] removeObserver:self]; |
| 247 | UIApplicationState appState = |
| 248 | [UIApplication sharedApplication].applicationState; |
| 249 | if (appState == UIApplicationStateActive) { |
| 250 | [self teardownGL]; |
| 251 | } |
| 252 | [_timer invalidate]; |
| 253 | [self ensureGLContext]; |
| 254 | _shader = nil; |
| 255 | if (_glContext && [EAGLContext currentContext] == _glContext) { |
| 256 | [EAGLContext setCurrentContext:nil]; |
| 257 | } |
| 258 | } |
| 259 |
| 260 | #pragma mark - UIView |
| 261 |
| 262 | - (void)setNeedsDisplay { |
| 263 | [super setNeedsDisplay]; |
| 264 | _isDirty = YES; |
| 265 | } |
| 266 |
| 267 | - (void)setNeedsDisplayInRect:(CGRect)rect { |
| 268 | [super setNeedsDisplayInRect:rect]; |
| 269 | _isDirty = YES; |
| 270 | } |
| 271 |
| 272 | - (void)layoutSubviews { |
| 273 | [super layoutSubviews]; |
| 274 |
| 275 | if (self.bounds.size.width > 0.0f) { |
| 276 | CGSize contentSize = scaleToFillSize(_currentSize, self.bounds.size); |
| 277 | _glkView.frame = CGRectMake(floor((self.bounds.size.width - contentSize.width) / 2.0), floor((self.bounds.size.height - contentSize.height) / 2.0), contentSize.width, contentSize.height); |
| 278 | } |
| 279 | } |
| 280 |
| 281 | #pragma mark - GLKViewDelegate |
| 282 |
| 283 | // This method is called when the GLKView's content is dirty and needs to be |
| 284 | // redrawn. This occurs on main thread. |
| 285 | - (void)glkView:(GLKView *)view drawInRect:(CGRect)rect { |
| 286 | // The renderer will draw the frame to the framebuffer corresponding to the |
| 287 | // one used by |view|. |
| 288 | RTCVideoFrame *frame = self.videoFrame; |
| 289 | if (!frame || frame.timeStampNs == _lastDrawnFrameTimeStampNs) { |
| 290 | return; |
| 291 | } |
| 292 | RTCVideoRotation rotation = frame.rotation; |
| 293 | if(_rotationOverride != nil) { |
| 294 | [_rotationOverride getValue: &rotation]; |
| 295 | } |
| 296 | [self ensureGLContext]; |
| 297 | glClear(GL_COLOR_BUFFER_BIT); |
| 298 | if ([frame.buffer isKindOfClass:[RTCCVPixelBuffer class]]) { |
| 299 | if (!_nv12TextureCache) { |
| 300 | _nv12TextureCache = [[RTCNV12TextureCache alloc] initWithContext:_glContext]; |
| 301 | } |
| 302 | if (_nv12TextureCache) { |
| 303 | [_nv12TextureCache uploadFrameToTextures:frame]; |
| 304 | [_shader applyShadingForFrameWithWidth:frame.width |
| 305 | height:frame.height |
| 306 | rotation:rotation |
| 307 | yPlane:_nv12TextureCache.yTexture |
| 308 | uvPlane:_nv12TextureCache.uvTexture]; |
| 309 | [_nv12TextureCache releaseTextures]; |
| 310 |
| 311 | _lastDrawnFrameTimeStampNs = self.videoFrame.timeStampNs; |
| 312 | } |
| 313 | } else { |
| 314 | if (!_i420TextureCache) { |
| 315 | _i420TextureCache = [[RTCI420TextureCache alloc] initWithContext:_glContext]; |
| 316 | } |
| 317 | [_i420TextureCache uploadFrameToTextures:frame]; |
| 318 | [_shader applyShadingForFrameWithWidth:frame.width |
| 319 | height:frame.height |
| 320 | rotation:rotation |
| 321 | yPlane:_i420TextureCache.yTexture |
| 322 | uPlane:_i420TextureCache.uTexture |
| 323 | vPlane:_i420TextureCache.vTexture]; |
| 324 |
| 325 | _lastDrawnFrameTimeStampNs = self.videoFrame.timeStampNs; |
| 326 | } |
| 327 | } |
| 328 |
| 329 | #pragma mark - RTCVideoRenderer |
| 330 |
| 331 | - (void)setSize:(CGSize)size { |
| 332 | [self.delegate videoView:self didChangeVideoSize:size]; |
| 333 |
| 334 | if (self.bounds.size.width > 0.0f) { |
| 335 | CGSize contentSize = scaleToFillSize(size, self.bounds.size); |
| 336 | _glkView.frame = CGRectMake(floor((self.bounds.size.width - contentSize.width) / 2.0), floor((self.bounds.size.height - contentSize.height) / 2.0), contentSize.width, contentSize.height); |
| 337 | } |
| 338 | } |
| 339 |
| 340 | - (void)renderFrame:(RTCVideoFrame *)frame { |
| 341 | self.videoFrame = frame; |
| 342 | } |
| 343 |
| 344 | #pragma mark - Private |
| 345 |
| 346 | - (void)displayLinkTimerDidFire { |
| 347 | // Don't render unless video frame have changed or the view content |
| 348 | // has explicitly been marked dirty. |
| 349 | if (!_isDirty && _lastDrawnFrameTimeStampNs == self.videoFrame.timeStampNs) { |
| 350 | return; |
| 351 | } |
| 352 |
| 353 | // Always reset isDirty at this point, even if -[GLKView display] |
| 354 | // won't be called in the case the drawable size is empty. |
| 355 | _isDirty = NO; |
| 356 |
| 357 | // Only call -[GLKView display] if the drawable size is |
| 358 | // non-empty. Calling display will make the GLKView setup its |
| 359 | // render buffer if necessary, but that will fail with error |
| 360 | // GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT if size is empty. |
| 361 | if (self.bounds.size.width > 0 && self.bounds.size.height > 0) { |
| 362 | [_glkView display]; |
| 363 | } |
| 364 | } |
| 365 |
| 366 | - (void)setupGL { |
| 367 | [self ensureGLContext]; |
| 368 | glDisable(GL_DITHER); |
| 369 | _timer.isPaused = NO; |
| 370 | } |
| 371 |
| 372 | - (void)teardownGL { |
| 373 | self.videoFrame = nil; |
| 374 | _timer.isPaused = YES; |
| 375 | [_glkView deleteDrawable]; |
| 376 | [self ensureGLContext]; |
| 377 | _nv12TextureCache = nil; |
| 378 | _i420TextureCache = nil; |
| 379 | } |
| 380 |
| 381 | - (void)didBecomeActive { |
| 382 | [self setupGL]; |
| 383 | } |
| 384 |
| 385 | - (void)willResignActive { |
| 386 | [self teardownGL]; |
| 387 | } |
| 388 |
| 389 | - (void)ensureGLContext { |
| 390 | NSAssert(_glContext, @"context shouldn't be nil"); |
| 391 | if ([EAGLContext currentContext] != _glContext) { |
| 392 | [EAGLContext setCurrentContext:_glContext]; |
| 393 | } |
| 394 | } |
| 395 |
| 396 | - (std::shared_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>>)getSink { |
| 397 | assert([NSThread isMainThread]); |
| 398 |
| 399 | return _sink; |
| 400 | } |
| 401 |
| 402 | - (void)setOnFirstFrameReceived:(void (^ _Nullable)())onFirstFrameReceived { |
| 403 | _onFirstFrameReceived = [onFirstFrameReceived copy]; |
| 404 | _firstFrameReceivedReported = false; |
| 405 | } |
| 406 |
| 407 | - (void)setInternalOrientation:(int)internalOrientation { |
| 408 | _internalOrientation = internalOrientation; |
| 409 | if (_onOrientationUpdated) { |
| 410 | _onOrientationUpdated(internalOrientation); |
| 411 | } |
| 412 | } |
| 413 |
| 414 | - (void)internalSetOnOrientationUpdated:(void (^ _Nullable)(int))onOrientationUpdated { |
| 415 | _onOrientationUpdated = [onOrientationUpdated copy]; |
| 416 | } |
| 417 |
| 418 | - (void)internalSetOnIsMirroredUpdated:(void (^ _Nullable)(bool))onIsMirroredUpdated { |
| 419 | } |
| 420 |
| 421 | @end |
| 422 |