blob: 10cf47b17852f6b49f7c5d66364385ad32d39cf4 [file] [log] [blame]
Kateryna Kostiuk00dcbff2019-07-11 15:42:13 -04001/*
2 * Copyright (C) 2019 Savoir-faire Linux Inc.
3 * Author: Kateryna Kostiuk <kateryna.kostiuk@savoirfairelinux.com>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20#import "CallMTKView.h"
21
22@implementation CallMTKView {
23 id <MTLBuffer> vertexBuffer;
24 id <MTLDepthStencilState> depthState;
25 id<MTLCommandQueue> commandQueue;
26 id<MTLRenderPipelineState> pipeline;
27 CVMetalTextureCacheRef textureCache;
28}
29
30// Vertex data for an image plane
31static const float kImagePlaneVertexData[16] = {
32 -1.0, -1.0, 0.0, 1.0,
33 1.0, -1.0, 1.0, 1.0,
34 -1.0, 1.0, 0.0, 0.0,
35 1.0, 1.0, 1.0, 0.0,
36};
37
38typedef enum BufferIndices {
39 kBufferIndexMeshPositions = 0,
40} BufferIndices;
41
42typedef enum VertexAttributes {
43 kVertexAttributePosition = 0,
44 kVertexAttributeTexcoord = 1,
45} VertexAttributes;
46
47struct Uniforms {
48 simd::float4x4 projectionMatrix;
49 simd::float4x4 rotationMatrix;
50};
51
52- (instancetype)initWithFrame:(NSRect)frame
53{
54 self = [super initWithFrame:frame];
55 if (self) {
Kateryna Kostiuk5d90c3b2019-07-18 12:03:52 -040056 [self setupView];
Kateryna Kostiuk00dcbff2019-07-11 15:42:13 -040057 }
58 return self;
59}
60
Kateryna Kostiuk5d90c3b2019-07-18 12:03:52 -040061-(void)setupView {
62 id<MTLDevice> device = MTLCreateSystemDefaultDevice();
63 self.device = device;
64 commandQueue = [device newCommandQueue];
65 self.colorPixelFormat = MTLPixelFormatBGRA8Unorm;
66 commandQueue = [device newCommandQueue];
67
68 CVReturn err = CVMetalTextureCacheCreate(kCFAllocatorDefault,
69 NULL,
70 self.device,
71 NULL,
72 &textureCache);
73
74 vertexBuffer = [device newBufferWithBytes:&kImagePlaneVertexData
75 length:sizeof(kImagePlaneVertexData)
76 options:MTLResourceCPUCacheModeDefaultCache];
77
78 NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
79 NSString *libraryPath = [resourcePath stringByAppendingPathComponent:@"Shader.metallib"];
80 id <MTLLibrary> library = [device newLibraryWithFile:libraryPath error:nil];
81 id<MTLFunction> vertexFunc = [library newFunctionWithName:@"imageVertex"];
82 id<MTLFunction> fragmentFunc = [library newFunctionWithName:@"imageFragment"];
83
84 // Create a vertex descriptor for our image plane vertex buffer
85 MTLVertexDescriptor *imagePlaneVertexDescriptor = [[MTLVertexDescriptor alloc] init];
86
87 // Positions.
88 imagePlaneVertexDescriptor.attributes[kVertexAttributePosition].format = MTLVertexFormatFloat2;
89 imagePlaneVertexDescriptor.attributes[kVertexAttributePosition].offset = 0;
90 imagePlaneVertexDescriptor.attributes[kVertexAttributePosition].bufferIndex = kBufferIndexMeshPositions;
91
92 // Texture coordinates.
93 imagePlaneVertexDescriptor.attributes[kVertexAttributeTexcoord].format = MTLVertexFormatFloat2;
94 imagePlaneVertexDescriptor.attributes[kVertexAttributeTexcoord].offset = 8;
95 imagePlaneVertexDescriptor.attributes[kVertexAttributeTexcoord].bufferIndex = kBufferIndexMeshPositions;
96
97 // Position Buffer Layout
98 imagePlaneVertexDescriptor.layouts[kBufferIndexMeshPositions].stride = 16;
99 imagePlaneVertexDescriptor.layouts[kBufferIndexMeshPositions].stepRate = 1;
100 imagePlaneVertexDescriptor.layouts[kBufferIndexMeshPositions].stepFunction = MTLVertexStepFunctionPerVertex;
101
102 MTLRenderPipelineDescriptor *pipelineDescriptor = [MTLRenderPipelineDescriptor new];
103 pipelineDescriptor.vertexFunction = vertexFunc;
104 pipelineDescriptor.fragmentFunction = fragmentFunc;
105 pipelineDescriptor.colorAttachments[0].pixelFormat = MTLPixelFormatBGRA8Unorm;
106 pipelineDescriptor.vertexDescriptor = imagePlaneVertexDescriptor;
107
108 pipeline = [device newRenderPipelineStateWithDescriptor:pipelineDescriptor error:NULL];
109 MTLDepthStencilDescriptor *depthStateDescriptor = [[MTLDepthStencilDescriptor alloc] init];
110 depthStateDescriptor.depthCompareFunction = MTLCompareFunctionAlways;
111 depthStateDescriptor.depthWriteEnabled = NO;
112 depthState = [device newDepthStencilStateWithDescriptor:depthStateDescriptor];
113 self.preferredFramesPerSecond = 30;
Kateryna Kostiuk8f77b792019-10-07 17:08:26 -0400114 self.paused = YES;
115 self.enableSetNeedsDisplay = NO;
Kateryna Kostiuk5d90c3b2019-07-18 12:03:52 -0400116}
117
Kateryna Kostiuk00dcbff2019-07-11 15:42:13 -0400118- (void)fillWithBlack {
119 NSUInteger width = self.frame.size.width;
120 NSUInteger height = self.frame.size.height;
121 CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
122 uint8_t *rawData = (uint8_t *)calloc(height * width * 4, sizeof(uint8_t));
123 NSUInteger bytesPerPixel = 4;
124 NSUInteger bytesPerRow = bytesPerPixel * width;
125 NSUInteger bitsPerComponent = 8;
126 MTLTextureDescriptor *textureDescriptor =
127 [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm
128 width:width
129 height:height
130 mipmapped:YES];
131 textureDescriptor.usage = MTLTextureUsageRenderTarget;
132 id<MTLTexture> texture = [self.device newTextureWithDescriptor:textureDescriptor];
133 MTLRegion region = MTLRegionMake2D(0, 0, width, height);
134 [texture replaceRegion:region mipmapLevel:0 withBytes:rawData bytesPerRow:bytesPerRow];
135 id<MTLCommandBuffer> commandBuffer = [commandQueue commandBuffer];
136 MTLRenderPassDescriptor *renderPass = self.currentRenderPassDescriptor;
137 id<MTLRenderCommandEncoder> commandEncoder = [commandBuffer renderCommandEncoderWithDescriptor:renderPass];
138 [commandEncoder setFragmentTexture:texture atIndex:0];
139 [commandEncoder endEncoding];
140 [commandBuffer presentDrawable:self.currentDrawable];
141 [commandBuffer commit];
142}
143
144bool frameDisplayed = false;
145
146- (void)renderWithPixelBuffer:(CVPixelBufferRef)buffer
147 size:(CGSize)size
148 rotation: (float)rotation
149 fillFrame: (bool)fill {
150 if(frameDisplayed) {
151 return;
152 }
153 if(_stopRendering) {
154 self.releaseDrawables;
155 return;
156 }
157 if (buffer == nil) return;
158 frameDisplayed = true;
159 CFRetain(buffer);
160 CVPixelBufferLockBaseAddress(buffer, 0);
161 id<MTLTexture> textureY = [self getTexture:buffer pixelFormat:MTLPixelFormatR8Unorm planeIndex:0];
162 id<MTLTexture> textureCbCr = [self getTexture:buffer pixelFormat:MTLPixelFormatRG8Unorm planeIndex:1];
163 CVPixelBufferUnlockBaseAddress(buffer, 0);
164 if(textureY == NULL || textureCbCr == NULL) {
165 frameDisplayed = false;
166 CVPixelBufferRelease(buffer);
167 return;
168 }
169 id<CAMetalDrawable> drawable = self.currentDrawable;
170 if (!drawable.texture) {
171 frameDisplayed = false;
172 CVPixelBufferRelease(buffer);
173 return;
174 }
175 NSSize frameSize = self.frame.size;
176
Kateryna Kostiukb61b0fa2019-09-24 17:56:30 -0400177 float viewRatio = (rotation == 90 || rotation == -90) ?
Kateryna Kostiuk00dcbff2019-07-11 15:42:13 -0400178 frameSize.height/frameSize.width : frameSize.width/frameSize.height;
179 float frameRatio = ((float)size.width)/((float)size.height);
180 simd::float4x4 projectionMatrix;
181 float ratio = viewRatio * (1/frameRatio);
Kateryna Kostiukb9b9e562019-11-09 17:44:48 -0500182 if (ratio < 1.0 && !fill || fill && ratio > 1.0)
183 projectionMatrix = [self getScalingMatrix: ratio axis: 'y'];
184 else
185 projectionMatrix = [self getScalingMatrix: 1/ratio axis: 'x'];
Kateryna Kostiuk1fd950b2019-11-09 18:52:08 -0500186 float radians = (rotation * M_PI) / 180;
Kateryna Kostiuk00dcbff2019-07-11 15:42:13 -0400187 simd::float4x4 rotationMatrix = [self getRotationMatrix:radians];
188 Uniforms bytes = Uniforms{projectionMatrix: projectionMatrix, rotationMatrix: rotationMatrix};
189 id<MTLCommandBuffer> commandBuffer = [commandQueue commandBuffer];
190 [commandBuffer addCompletedHandler:^(id<MTLCommandBuffer> cbuffer) {
191 frameDisplayed = false;
192 CVPixelBufferRelease(buffer);
193 }];
194 MTLRenderPassDescriptor *renderPass = self.currentRenderPassDescriptor;
195 renderPass.colorAttachments[0].texture = drawable.texture;
196 id<MTLRenderCommandEncoder> commandEncoder = [commandBuffer renderCommandEncoderWithDescriptor:renderPass];
197 [commandEncoder setRenderPipelineState: pipeline];
198 [commandEncoder setDepthStencilState:depthState];
199 [commandEncoder setVertexBytes: &bytes length:sizeof(bytes) atIndex:1];
200 [commandEncoder setVertexBuffer:vertexBuffer offset:0 atIndex:kBufferIndexMeshPositions];
201 [commandEncoder setFragmentTexture:textureY atIndex: 1];
202 [commandEncoder setFragmentTexture:textureCbCr atIndex:2];
203 [commandEncoder drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:4];
204 [commandEncoder endEncoding];
205 [commandBuffer presentDrawable:drawable];
206 [commandBuffer commit];
Kateryna Kostiukbbac5ca2019-10-02 13:40:49 -0400207 [self draw];
Kateryna Kostiuk00dcbff2019-07-11 15:42:13 -0400208}
209
210-(simd::float4x4) getScalingMatrix:(CGFloat) ratio axis:(char) axis {
211 simd::float4x4 N = 0.0;
212 simd::float4 v[4] = {0.0, 0.0, 0.0, 0.0};
213 float xMultyplier = axis == 'x' ? ratio: 1;
214 float yMultyplier = axis == 'y' ? ratio: 1;
215 v[0] = { xMultyplier, 0, 0, 0 };
216 v[1] = { 0, yMultyplier, 0, 0 };
217 v[2] = { 0, 0, 1, 0 };
218 v[3] = { 0, 0, 0, 1 };
219 N = matrix_from_rows(v[0], v[1], v[2], v[3]);
220 return N;
221}
222
223-(simd::float4x4) getRotationMatrix:(float) rotation {
224 simd::float4x4 N = 0.0;
225 simd::float4 v[4] = {0.0, 0.0, 0.0, 0.0};
226 v[0] = { cos(rotation), sin(rotation), 0, 0 };
227 v[1] = { -sin(rotation), cos(rotation), 0, 0 };
228 v[2] = { 0, 0, 1, 0 };
229 v[3] = { 0, 0, 0, 1 };
230 N = matrix_from_rows(v[0], v[1], v[2], v[3]);
231 return N;
232}
233
234- (id<MTLTexture>)getTexture:(CVPixelBufferRef)image pixelFormat:(MTLPixelFormat)pixelFormat planeIndex:(int)planeIndex {
235 id<MTLTexture> texture;
236 size_t width, height;
237 if (planeIndex == -1)
238 {
239 width = CVPixelBufferGetWidth(image);
240 height = CVPixelBufferGetHeight(image);
241 planeIndex = 0;
242 }
243 else
244 {
245 width = CVPixelBufferGetWidthOfPlane(image, planeIndex);
246 height = CVPixelBufferGetHeightOfPlane(image, planeIndex);
247 }
248 auto format = CVPixelBufferGetPixelFormatType(image);
249 CVMetalTextureRef textureRef = NULL;
250 CVReturn status = CVMetalTextureCacheCreateTextureFromImage(NULL, textureCache, image, NULL, pixelFormat, width, height, planeIndex, &textureRef);
251 if(status == kCVReturnSuccess)
252 {
253 texture = CVMetalTextureGetTexture(textureRef);
254 CFRelease(textureRef);
255 }
256 else
257 {
258 NSLog(@"CVMetalTextureCacheCreateTextureFromImage failed with return stats %d", status);
259 return NULL;
260 }
261 return texture;
262}
263
264@end