Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(28)

Side by Side Diff: webrtc/sdk/objc/Framework/Classes/Metal/RTCMTLNV12Renderer.mm

Issue 2784243003: iOS/MacOS:Refactor metal rendering by extracting common implementation (Closed)
Patch Set: Created 3 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 /* 1 /*
2 * Copyright 2017 The WebRTC project authors. All Rights Reserved. 2 * Copyright 2017 The WebRTC Project Authors. All rights reserved.
3 * 3 *
4 * Use of this source code is governed by a BSD-style license 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 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 6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may 7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree. 8 * be found in the AUTHORS file in the root of the source tree.
9 */ 9 */
10 10
11 #import "RTCMTLNV12Renderer.h" 11 #import "RTCMTLNV12Renderer.h"
12 12
13 #import <Metal/Metal.h> 13 #import <Metal/Metal.h>
14 #import <MetalKit/MetalKit.h> 14 #import <MetalKit/MetalKit.h>
15 15
16 #import "WebRTC/RTCLogging.h" 16 #import "WebRTC/RTCLogging.h"
17 #import "WebRTC/RTCVideoFrame.h" 17 #import "WebRTC/RTCVideoFrame.h"
18 18
19 #include "webrtc/api/video/video_rotation.h" 19 #import "RTCMTLRenderer+Private.h"
20 20
21 #define MTL_STRINGIFY(s) @ #s 21 #define MTL_STRINGIFY(s) @ #s
22 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( 23 static NSString *const shaderSource = MTL_STRINGIFY(
60 using namespace metal; typedef struct { 24 using namespace metal; typedef struct {
61 packed_float2 position; 25 packed_float2 position;
62 packed_float2 texcoord; 26 packed_float2 texcoord;
63 } Vertex; 27 } Vertex;
64 28
65 typedef struct { 29 typedef struct {
66 float4 position[[position]]; 30 float4 position[[position]];
67 float2 texcoord; 31 float2 texcoord;
68 } Varyings; 32 } Varyings;
69 33
70 vertex Varyings vertexPassthrough(device Vertex * verticies[[buffer(0)]], 34 vertex Varyings vertexPassthrough(device Vertex * verticies[[buffer(0)]],
71 unsigned int vid[[vertex_id]]) { 35 unsigned int vid[[vertex_id]]) {
72 Varyings out; 36 Varyings out;
73 device Vertex &v = verticies[vid]; 37 device Vertex &v = verticies[vid];
74 out.position = float4(float2(v.position), 0.0, 1.0); 38 out.position = float4(float2(v.position), 0.0, 1.0);
75 out.texcoord = v.texcoord; 39 out.texcoord = v.texcoord;
76
77 return out; 40 return out;
78 } 41 }
79 42
80 // Receiving YCrCb textures. 43 // Receiving YCrCb textures.
81 fragment half4 fragmentColorConversion( 44 fragment half4 fragmentColorConversion(
82 Varyings in[[stage_in]], texture2d<float, access::sample> textureY[[text ure(0)]], 45 Varyings in[[stage_in]], texture2d<float, access::sample> textureY[[text ure(0)]],
83 texture2d<float, access::sample> textureCbCr[[texture(1)]]) { 46 texture2d<float, access::sample> textureCbCr[[texture(1)]]) {
84 constexpr sampler s(address::clamp_to_edge, filter::linear); 47 constexpr sampler s(address::clamp_to_edge, filter::linear);
85 float y; 48 float y;
86 float2 uv; 49 float2 uv;
87 y = textureY.sample(s, in.texcoord).r; 50 y = textureY.sample(s, in.texcoord).r;
88 uv = textureCbCr.sample(s, in.texcoord).rg - float2(0.5, 0.5); 51 uv = textureCbCr.sample(s, in.texcoord).rg - float2(0.5, 0.5);
89 52
90 // Conversion for YUV to rgb from http://www.fourcc.org/fccyvrgb.php 53 // 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); 54 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 55
93 return half4(out); 56 return half4(out);
94 }); 57 });
95 58
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 { 59 @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. 60 // Textures.
114 CVMetalTextureCacheRef _textureCache; 61 CVMetalTextureCacheRef _textureCache;
115 id<MTLTexture> _yTexture; 62 id<MTLTexture> _yTexture;
116 id<MTLTexture> _CrCbTexture; 63 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 } 64 }
134 65
135 - (BOOL)addRenderingDestination:(__kindof MTKView *)view { 66 - (BOOL)addRenderingDestination:(__kindof MTKView *)view {
136 return [self setupWithView:view]; 67 if ([super addRenderingDestination: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]; 68 [self initializeTextureCache];
148 success = YES; 69 return YES;
149 } 70 }
150 return success; 71 return NO;
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 } 72 }
219 73
220 - (void)initializeTextureCache { 74 - (void)initializeTextureCache {
221 CVReturn status = 75 CVReturn status = CVMetalTextureCacheCreate(kCFAllocatorDefault, nil, [self cu rrentMetalDevice],
222 CVMetalTextureCacheCreate(kCFAllocatorDefault, nil, _device, nil, &_textur eCache); 76 nil, &_textureCache);
223 if (status != kCVReturnSuccess) { 77 if (status != kCVReturnSuccess) {
224 RTCLogError(@"Metal: Failed to initialize metal texture cache. Return status is %d", status); 78 RTCLogError(@"Metal: Failed to initialize metal texture cache. Return status is %d", status);
225 } 79 }
226 } 80 }
227 81
228 - (void)render { 82 - (NSString *)shaderSource {
229 // Wait until the inflight (curently sent to GPU) command buffer 83 return shaderSource;
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.currentRenderPassDescrip tor;
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 @autoreleasepool {
273 if ([self setupTexturesForFrame:frame])
274 [self render];
275 }
276 } 84 }
277 85
278 - (BOOL)setupTexturesForFrame:(nonnull RTCVideoFrame *)frame { 86 - (BOOL)setupTexturesForFrame:(nonnull RTCVideoFrame *)frame {
87 [super setupTexturesForFrame:frame];
279 CVPixelBufferRef pixelBuffer = frame.nativeHandle; 88 CVPixelBufferRef pixelBuffer = frame.nativeHandle;
280 89
281 id<MTLTexture> lumaTexture = nil; 90 id<MTLTexture> lumaTexture = nil;
282 id<MTLTexture> chromaTexture = nil; 91 id<MTLTexture> chromaTexture = nil;
283 CVMetalTextureRef outTexture = nullptr; 92 CVMetalTextureRef outTexture = nullptr;
284 93
285 // Luma (y) texture. 94 // Luma (y) texture.
286 int lumaWidth = CVPixelBufferGetWidthOfPlane(pixelBuffer, 0); 95 int lumaWidth = CVPixelBufferGetWidthOfPlane(pixelBuffer, 0);
287 int lumaHeight = CVPixelBufferGetHeightOfPlane(pixelBuffer, 0); 96 int lumaHeight = CVPixelBufferGetHeightOfPlane(pixelBuffer, 0);
288 97
(...skipping 16 matching lines...) Expand all
305 kCFAllocatorDefault, _textureCache, pixelBuffer, nil, MTLPixelFormatRG8Uno rm, lumaWidth / 2, 114 kCFAllocatorDefault, _textureCache, pixelBuffer, nil, MTLPixelFormatRG8Uno rm, lumaWidth / 2,
306 lumaHeight / 2, indexPlane, &outTexture); 115 lumaHeight / 2, indexPlane, &outTexture);
307 if (result == kCVReturnSuccess) { 116 if (result == kCVReturnSuccess) {
308 chromaTexture = CVMetalTextureGetTexture(outTexture); 117 chromaTexture = CVMetalTextureGetTexture(outTexture);
309 } 118 }
310 CVBufferRelease(outTexture); 119 CVBufferRelease(outTexture);
311 120
312 if (lumaTexture != nil && chromaTexture != nil) { 121 if (lumaTexture != nil && chromaTexture != nil) {
313 _yTexture = lumaTexture; 122 _yTexture = lumaTexture;
314 _CrCbTexture = chromaTexture; 123 _CrCbTexture = chromaTexture;
315 _offset = offsetForRotation((webrtc::VideoRotation)frame.rotation);
316 return YES; 124 return YES;
317 } 125 }
318 return NO; 126 return NO;
319 } 127 }
320 128
129 - (void)uploadTexturesToRenderEncoder:(id<MTLRenderCommandEncoder>)renderEncoder {
130 [renderEncoder setFragmentTexture:_yTexture atIndex:0];
131 [renderEncoder setFragmentTexture:_CrCbTexture atIndex:1];
132 }
133
321 @end 134 @end
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698