| OLD | NEW |
| (Empty) |
| 1 /* | |
| 2 * Copyright 2017 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 #import "RTCMTLNV12Renderer.h" | |
| 12 | |
| 13 #import <Metal/Metal.h> | |
| 14 #import <MetalKit/MetalKit.h> | |
| 15 | |
| 16 #import "WebRTC/RTCLogging.h" | |
| 17 #import "WebRTC/RTCVideoFrame.h" | |
| 18 | |
| 19 #include "webrtc/api/video/video_rotation.h" | |
| 20 | |
| 21 #define MTL_STRINGIFY(s) @ #s | |
| 22 | |
| 23 // As defined in shaderSource. | |
| 24 static NSString *const vertexFunctionName = @"vertexPassthrough"; | |
| 25 static NSString *const fragmentFunctionName = @"fragmentColorConversion"; | |
| 26 | |
| 27 static NSString *const pipelineDescriptorLabel = @"RTCPipeline"; | |
| 28 static NSString *const commandBufferLabel = @"RTCCommandBuffer"; | |
| 29 static NSString *const renderEncoderLabel = @"RTCEncoder"; | |
| 30 static NSString *const renderEncoderDebugGroup = @"RTCDrawFrame"; | |
| 31 | |
| 32 static const float cubeVertexData[64] = { | |
| 33 -1.0, -1.0, 0.0, 1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.
0, 0.0, | |
| 34 | |
| 35 // rotation = 90, offset = 16. | |
| 36 -1.0, -1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 0.0, -1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.
0, 0.0, | |
| 37 | |
| 38 // rotation = 180, offset = 32. | |
| 39 -1.0, -1.0, 1.0, 0.0, 1.0, -1.0, 0.0, 0.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.
0, 1.0, | |
| 40 | |
| 41 // rotation = 270, offset = 48. | |
| 42 -1.0, -1.0, 0.0, 0.0, 1.0, -1.0, 0.0, 1.0, -1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.
0, 1.0, | |
| 43 }; | |
| 44 | |
| 45 static inline int offsetForRotation(webrtc::VideoRotation rotation) { | |
| 46 switch (rotation) { | |
| 47 case webrtc::kVideoRotation_0: | |
| 48 return 0; | |
| 49 case webrtc::kVideoRotation_90: | |
| 50 return 16; | |
| 51 case webrtc::kVideoRotation_180: | |
| 52 return 32; | |
| 53 case webrtc::kVideoRotation_270: | |
| 54 return 48; | |
| 55 } | |
| 56 return 0; | |
| 57 } | |
| 58 | |
| 59 static NSString *const shaderSource = MTL_STRINGIFY( | |
| 60 using namespace metal; typedef struct { | |
| 61 packed_float2 position; | |
| 62 packed_float2 texcoord; | |
| 63 } Vertex; | |
| 64 | |
| 65 typedef struct { | |
| 66 float4 position[[position]]; | |
| 67 float2 texcoord; | |
| 68 } Varyings; | |
| 69 | |
| 70 vertex Varyings vertexPassthrough(device Vertex * verticies[[buffer(0)]], | |
| 71 unsigned int vid[[vertex_id]]) { | |
| 72 Varyings out; | |
| 73 device Vertex &v = verticies[vid]; | |
| 74 out.position = float4(float2(v.position), 0.0, 1.0); | |
| 75 out.texcoord = v.texcoord; | |
| 76 | |
| 77 return out; | |
| 78 } | |
| 79 | |
| 80 // Receiving YCrCb textures. | |
| 81 fragment half4 fragmentColorConversion( | |
| 82 Varyings in[[stage_in]], texture2d<float, access::sample> textureY[[text
ure(0)]], | |
| 83 texture2d<float, access::sample> textureCbCr[[texture(1)]]) { | |
| 84 constexpr sampler s(address::clamp_to_edge, filter::linear); | |
| 85 float y; | |
| 86 float2 uv; | |
| 87 y = textureY.sample(s, in.texcoord).r; | |
| 88 uv = textureCbCr.sample(s, in.texcoord).rg - float2(0.5, 0.5); | |
| 89 | |
| 90 // Conversion for YUV to rgb from http://www.fourcc.org/fccyvrgb.php | |
| 91 float4 out = float4(y + 1.403 * uv.y, y - 0.344 * uv.x - 0.714 * uv.y, y +
1.770 * uv.x, 1.0); | |
| 92 | |
| 93 return half4(out); | |
| 94 }); | |
| 95 | |
| 96 // The max number of command buffers in flight (submitted to GPU). | |
| 97 // For now setting it up to 1. | |
| 98 // In future we might use triple buffering method if it improves performance. | |
| 99 static const NSInteger kMaxInflightBuffers = 1; | |
| 100 | |
| 101 @implementation RTCMTLNV12Renderer { | |
| 102 __kindof MTKView *_view; | |
| 103 | |
| 104 // Controller. | |
| 105 dispatch_semaphore_t _inflight_semaphore; | |
| 106 | |
| 107 // Renderer. | |
| 108 id<MTLDevice> _device; | |
| 109 id<MTLCommandQueue> _commandQueue; | |
| 110 id<MTLLibrary> _defaultLibrary; | |
| 111 id<MTLRenderPipelineState> _pipelineState; | |
| 112 | |
| 113 // Textures. | |
| 114 CVMetalTextureCacheRef _textureCache; | |
| 115 id<MTLTexture> _yTexture; | |
| 116 id<MTLTexture> _CrCbTexture; | |
| 117 | |
| 118 // Buffers. | |
| 119 id<MTLBuffer> _vertexBuffer; | |
| 120 | |
| 121 // RTC Frame parameters. | |
| 122 int _offset; | |
| 123 } | |
| 124 | |
| 125 - (instancetype)init { | |
| 126 if (self = [super init]) { | |
| 127 // _offset of 0 is equal to rotation of 0. | |
| 128 _offset = 0; | |
| 129 _inflight_semaphore = dispatch_semaphore_create(kMaxInflightBuffers); | |
| 130 } | |
| 131 | |
| 132 return self; | |
| 133 } | |
| 134 | |
| 135 - (BOOL)addRenderingDestination:(__kindof MTKView *)view { | |
| 136 return [self setupWithView:view]; | |
| 137 } | |
| 138 | |
| 139 #pragma mark - Private | |
| 140 | |
| 141 - (BOOL)setupWithView:(__kindof MTKView *)view { | |
| 142 BOOL success = NO; | |
| 143 if ([self setupMetal]) { | |
| 144 [self setupView:view]; | |
| 145 [self loadAssets]; | |
| 146 [self setupBuffers]; | |
| 147 [self initializeTextureCache]; | |
| 148 success = YES; | |
| 149 } | |
| 150 return success; | |
| 151 } | |
| 152 | |
| 153 #pragma mark - GPU methods | |
| 154 | |
| 155 - (BOOL)setupMetal { | |
| 156 // Set the view to use the default device. | |
| 157 _device = MTLCreateSystemDefaultDevice(); | |
| 158 if (!_device) { | |
| 159 return NO; | |
| 160 } | |
| 161 | |
| 162 // Create a new command queue. | |
| 163 _commandQueue = [_device newCommandQueue]; | |
| 164 | |
| 165 // Load metal library from source. | |
| 166 NSError *libraryError = nil; | |
| 167 | |
| 168 id<MTLLibrary> sourceLibrary = | |
| 169 [_device newLibraryWithSource:shaderSource options:NULL error:&libraryErro
r]; | |
| 170 | |
| 171 if (libraryError) { | |
| 172 RTCLogError(@"Metal: Library with source failed\n%@", libraryError); | |
| 173 return NO; | |
| 174 } | |
| 175 | |
| 176 if (!sourceLibrary) { | |
| 177 RTCLogError(@"Metal: Failed to load library. %@", libraryError); | |
| 178 return NO; | |
| 179 } | |
| 180 _defaultLibrary = sourceLibrary; | |
| 181 | |
| 182 return YES; | |
| 183 } | |
| 184 | |
| 185 - (void)setupView:(__kindof MTKView *)view { | |
| 186 view.device = _device; | |
| 187 | |
| 188 view.preferredFramesPerSecond = 30; | |
| 189 view.autoResizeDrawable = NO; | |
| 190 | |
| 191 // We need to keep reference to the view as it's needed down the rendering pip
eline. | |
| 192 _view = view; | |
| 193 } | |
| 194 | |
| 195 - (void)loadAssets { | |
| 196 id<MTLFunction> vertexFunction = [_defaultLibrary newFunctionWithName:vertexFu
nctionName]; | |
| 197 id<MTLFunction> fragmentFunction = | |
| 198 [_defaultLibrary newFunctionWithName:fragmentFunctionName]; | |
| 199 | |
| 200 MTLRenderPipelineDescriptor *pipelineDescriptor = [[MTLRenderPipelineDescripto
r alloc] init]; | |
| 201 pipelineDescriptor.label = pipelineDescriptorLabel; | |
| 202 pipelineDescriptor.vertexFunction = vertexFunction; | |
| 203 pipelineDescriptor.fragmentFunction = fragmentFunction; | |
| 204 pipelineDescriptor.colorAttachments[0].pixelFormat = _view.colorPixelFormat; | |
| 205 pipelineDescriptor.depthAttachmentPixelFormat = MTLPixelFormatInvalid; | |
| 206 NSError *error = nil; | |
| 207 _pipelineState = [_device newRenderPipelineStateWithDescriptor:pipelineDescrip
tor error:&error]; | |
| 208 | |
| 209 if (!_pipelineState) { | |
| 210 RTCLogError(@"Metal: Failed to create pipeline state. %@", error); | |
| 211 } | |
| 212 } | |
| 213 | |
| 214 - (void)setupBuffers { | |
| 215 _vertexBuffer = [_device newBufferWithBytes:cubeVertexData | |
| 216 length:sizeof(cubeVertexData) | |
| 217 options:MTLResourceOptionCPUCacheModeDefau
lt]; | |
| 218 } | |
| 219 | |
| 220 - (void)initializeTextureCache { | |
| 221 CVReturn status = | |
| 222 CVMetalTextureCacheCreate(kCFAllocatorDefault, nil, _device, nil, &_textur
eCache); | |
| 223 if (status != kCVReturnSuccess) { | |
| 224 RTCLogError(@"Metal: Failed to initialize metal texture cache. Return status
is %d", status); | |
| 225 } | |
| 226 } | |
| 227 | |
| 228 - (void)render { | |
| 229 // Wait until the inflight (curently sent to GPU) command buffer | |
| 230 // has completed the GPU work. | |
| 231 dispatch_semaphore_wait(_inflight_semaphore, DISPATCH_TIME_FOREVER); | |
| 232 | |
| 233 id<MTLCommandBuffer> commandBuffer = [_commandQueue commandBuffer]; | |
| 234 commandBuffer.label = commandBufferLabel; | |
| 235 | |
| 236 __block dispatch_semaphore_t block_semaphore = _inflight_semaphore; | |
| 237 [commandBuffer addCompletedHandler:^(id<MTLCommandBuffer> _Nonnull) { | |
| 238 // GPU work completed. | |
| 239 dispatch_semaphore_signal(block_semaphore); | |
| 240 }]; | |
| 241 | |
| 242 MTLRenderPassDescriptor *_renderPassDescriptor = _view.currentRenderPassDescri
ptor; | |
| 243 if (_renderPassDescriptor) { // Valid drawable. | |
| 244 id<MTLRenderCommandEncoder> renderEncoder = | |
| 245 [commandBuffer renderCommandEncoderWithDescriptor:_renderPassDescriptor]
; | |
| 246 renderEncoder.label = renderEncoderLabel; | |
| 247 | |
| 248 // Set context state. | |
| 249 [renderEncoder pushDebugGroup:renderEncoderDebugGroup]; | |
| 250 [renderEncoder setRenderPipelineState:_pipelineState]; | |
| 251 [renderEncoder setVertexBuffer:_vertexBuffer offset:_offset * sizeof(float)
atIndex:0]; | |
| 252 [renderEncoder setFragmentTexture:_yTexture atIndex:0]; | |
| 253 [renderEncoder setFragmentTexture:_CrCbTexture atIndex:1]; | |
| 254 | |
| 255 [renderEncoder drawPrimitives:MTLPrimitiveTypeTriangleStrip | |
| 256 vertexStart:0 | |
| 257 vertexCount:4 | |
| 258 instanceCount:1]; | |
| 259 [renderEncoder popDebugGroup]; | |
| 260 [renderEncoder endEncoding]; | |
| 261 | |
| 262 [commandBuffer presentDrawable:_view.currentDrawable]; | |
| 263 } | |
| 264 | |
| 265 // CPU work is completed, GPU work can be started. | |
| 266 [commandBuffer commit]; | |
| 267 } | |
| 268 | |
| 269 #pragma mark - RTCMTLRenderer | |
| 270 | |
| 271 - (void)drawFrame:(RTCVideoFrame *)frame { | |
| 272 [self setupTexturesForFrame:frame]; | |
| 273 @autoreleasepool { | |
| 274 [self render]; | |
| 275 } | |
| 276 } | |
| 277 | |
| 278 - (void)setupTexturesForFrame:(nonnull RTCVideoFrame *)frame { | |
| 279 CVPixelBufferRef pixelBuffer = frame.nativeHandle; | |
| 280 | |
| 281 id<MTLTexture> lumaTexture = nil; | |
| 282 id<MTLTexture> chromaTexture = nil; | |
| 283 CVMetalTextureRef outTexture = nullptr; | |
| 284 | |
| 285 // Luma (y) texture. | |
| 286 int lumaWidth = CVPixelBufferGetWidthOfPlane(pixelBuffer, 0); | |
| 287 int lumaHeight = CVPixelBufferGetHeightOfPlane(pixelBuffer, 0); | |
| 288 | |
| 289 int indexPlane = 0; | |
| 290 CVReturn result = CVMetalTextureCacheCreateTextureFromImage( | |
| 291 kCFAllocatorDefault, _textureCache, pixelBuffer, nil, MTLPixelFormatR8Unor
m, lumaWidth, | |
| 292 lumaHeight, indexPlane, &outTexture); | |
| 293 | |
| 294 if (result == kCVReturnSuccess) { | |
| 295 lumaTexture = CVMetalTextureGetTexture(outTexture); | |
| 296 } | |
| 297 | |
| 298 // Same as CFRelease except it can be passed NULL without crashing. | |
| 299 CVBufferRelease(outTexture); | |
| 300 outTexture = nullptr; | |
| 301 | |
| 302 // Chroma (CrCb) texture. | |
| 303 indexPlane = 1; | |
| 304 result = CVMetalTextureCacheCreateTextureFromImage( | |
| 305 kCFAllocatorDefault, _textureCache, pixelBuffer, nil, MTLPixelFormatRG8Uno
rm, lumaWidth / 2, | |
| 306 lumaHeight / 2, indexPlane, &outTexture); | |
| 307 if (result == kCVReturnSuccess) { | |
| 308 chromaTexture = CVMetalTextureGetTexture(outTexture); | |
| 309 } | |
| 310 CVBufferRelease(outTexture); | |
| 311 | |
| 312 if (lumaTexture != nil && chromaTexture != nil) { | |
| 313 _yTexture = lumaTexture; | |
| 314 _CrCbTexture = chromaTexture; | |
| 315 _offset = offsetForRotation((webrtc::VideoRotation)frame.rotation); | |
| 316 } | |
| 317 } | |
| 318 | |
| 319 @end | |
| OLD | NEW |