blob: 98d0afcaf4856b446746a342b8909ee96393ec38 [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};
Kateryna Kostiuk06681682020-05-07 20:50:56 -040051@synthesize videoRunning;
Kateryna Kostiuk00dcbff2019-07-11 15:42:13 -040052
53- (instancetype)initWithFrame:(NSRect)frame
54{
55 self = [super initWithFrame:frame];
56 if (self) {
Kateryna Kostiuk5d90c3b2019-07-18 12:03:52 -040057 [self setupView];
Kateryna Kostiuk00dcbff2019-07-11 15:42:13 -040058 }
59 return self;
60}
61
Kateryna Kostiuk5d90c3b2019-07-18 12:03:52 -040062-(void)setupView {
63 id<MTLDevice> device = MTLCreateSystemDefaultDevice();
64 self.device = device;
65 commandQueue = [device newCommandQueue];
66 self.colorPixelFormat = MTLPixelFormatBGRA8Unorm;
67 commandQueue = [device newCommandQueue];
68
69 CVReturn err = CVMetalTextureCacheCreate(kCFAllocatorDefault,
70 NULL,
71 self.device,
72 NULL,
73 &textureCache);
74
75 vertexBuffer = [device newBufferWithBytes:&kImagePlaneVertexData
76 length:sizeof(kImagePlaneVertexData)
77 options:MTLResourceCPUCacheModeDefaultCache];
78
79 NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
80 NSString *libraryPath = [resourcePath stringByAppendingPathComponent:@"Shader.metallib"];
81 id <MTLLibrary> library = [device newLibraryWithFile:libraryPath error:nil];
82 id<MTLFunction> vertexFunc = [library newFunctionWithName:@"imageVertex"];
83 id<MTLFunction> fragmentFunc = [library newFunctionWithName:@"imageFragment"];
84
85 // Create a vertex descriptor for our image plane vertex buffer
86 MTLVertexDescriptor *imagePlaneVertexDescriptor = [[MTLVertexDescriptor alloc] init];
87
88 // Positions.
89 imagePlaneVertexDescriptor.attributes[kVertexAttributePosition].format = MTLVertexFormatFloat2;
90 imagePlaneVertexDescriptor.attributes[kVertexAttributePosition].offset = 0;
91 imagePlaneVertexDescriptor.attributes[kVertexAttributePosition].bufferIndex = kBufferIndexMeshPositions;
92
93 // Texture coordinates.
94 imagePlaneVertexDescriptor.attributes[kVertexAttributeTexcoord].format = MTLVertexFormatFloat2;
95 imagePlaneVertexDescriptor.attributes[kVertexAttributeTexcoord].offset = 8;
96 imagePlaneVertexDescriptor.attributes[kVertexAttributeTexcoord].bufferIndex = kBufferIndexMeshPositions;
97
98 // Position Buffer Layout
99 imagePlaneVertexDescriptor.layouts[kBufferIndexMeshPositions].stride = 16;
100 imagePlaneVertexDescriptor.layouts[kBufferIndexMeshPositions].stepRate = 1;
101 imagePlaneVertexDescriptor.layouts[kBufferIndexMeshPositions].stepFunction = MTLVertexStepFunctionPerVertex;
102
103 MTLRenderPipelineDescriptor *pipelineDescriptor = [MTLRenderPipelineDescriptor new];
104 pipelineDescriptor.vertexFunction = vertexFunc;
105 pipelineDescriptor.fragmentFunction = fragmentFunc;
106 pipelineDescriptor.colorAttachments[0].pixelFormat = MTLPixelFormatBGRA8Unorm;
107 pipelineDescriptor.vertexDescriptor = imagePlaneVertexDescriptor;
108
109 pipeline = [device newRenderPipelineStateWithDescriptor:pipelineDescriptor error:NULL];
110 MTLDepthStencilDescriptor *depthStateDescriptor = [[MTLDepthStencilDescriptor alloc] init];
111 depthStateDescriptor.depthCompareFunction = MTLCompareFunctionAlways;
112 depthStateDescriptor.depthWriteEnabled = NO;
113 depthState = [device newDepthStencilStateWithDescriptor:depthStateDescriptor];
114 self.preferredFramesPerSecond = 30;
Kateryna Kostiuk8f77b792019-10-07 17:08:26 -0400115 self.paused = YES;
116 self.enableSetNeedsDisplay = NO;
Kateryna Kostiuk5d90c3b2019-07-18 12:03:52 -0400117}
118
Kateryna Kostiuk00dcbff2019-07-11 15:42:13 -0400119- (void)fillWithBlack {
120 NSUInteger width = self.frame.size.width;
121 NSUInteger height = self.frame.size.height;
122 CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
123 uint8_t *rawData = (uint8_t *)calloc(height * width * 4, sizeof(uint8_t));
124 NSUInteger bytesPerPixel = 4;
125 NSUInteger bytesPerRow = bytesPerPixel * width;
126 NSUInteger bitsPerComponent = 8;
127 MTLTextureDescriptor *textureDescriptor =
128 [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm
129 width:width
130 height:height
131 mipmapped:YES];
132 textureDescriptor.usage = MTLTextureUsageRenderTarget;
133 id<MTLTexture> texture = [self.device newTextureWithDescriptor:textureDescriptor];
134 MTLRegion region = MTLRegionMake2D(0, 0, width, height);
135 [texture replaceRegion:region mipmapLevel:0 withBytes:rawData bytesPerRow:bytesPerRow];
136 id<MTLCommandBuffer> commandBuffer = [commandQueue commandBuffer];
137 MTLRenderPassDescriptor *renderPass = self.currentRenderPassDescriptor;
138 id<MTLRenderCommandEncoder> commandEncoder = [commandBuffer renderCommandEncoderWithDescriptor:renderPass];
139 [commandEncoder setFragmentTexture:texture atIndex:0];
140 [commandEncoder endEncoding];
141 [commandBuffer presentDrawable:self.currentDrawable];
142 [commandBuffer commit];
“Kateryna”63fcf2c2020-04-08 11:03:58 -0400143 [self draw];
Kateryna Kostiuk00dcbff2019-07-11 15:42:13 -0400144}
145
146bool frameDisplayed = false;
147
148- (void)renderWithPixelBuffer:(CVPixelBufferRef)buffer
149 size:(CGSize)size
150 rotation: (float)rotation
151 fillFrame: (bool)fill {
152 if(frameDisplayed) {
153 return;
154 }
Kateryna Kostiuk06681682020-05-07 20:50:56 -0400155 if(!self.videoRunning) {
Kateryna Kostiuk00dcbff2019-07-11 15:42:13 -0400156 self.releaseDrawables;
157 return;
158 }
159 if (buffer == nil) return;
160 frameDisplayed = true;
161 CFRetain(buffer);
162 CVPixelBufferLockBaseAddress(buffer, 0);
163 id<MTLTexture> textureY = [self getTexture:buffer pixelFormat:MTLPixelFormatR8Unorm planeIndex:0];
164 id<MTLTexture> textureCbCr = [self getTexture:buffer pixelFormat:MTLPixelFormatRG8Unorm planeIndex:1];
165 CVPixelBufferUnlockBaseAddress(buffer, 0);
166 if(textureY == NULL || textureCbCr == NULL) {
167 frameDisplayed = false;
168 CVPixelBufferRelease(buffer);
169 return;
170 }
171 id<CAMetalDrawable> drawable = self.currentDrawable;
172 if (!drawable.texture) {
173 frameDisplayed = false;
174 CVPixelBufferRelease(buffer);
175 return;
176 }
177 NSSize frameSize = self.frame.size;
178
Kateryna Kostiukb61b0fa2019-09-24 17:56:30 -0400179 float viewRatio = (rotation == 90 || rotation == -90) ?
Kateryna Kostiuk00dcbff2019-07-11 15:42:13 -0400180 frameSize.height/frameSize.width : frameSize.width/frameSize.height;
181 float frameRatio = ((float)size.width)/((float)size.height);
182 simd::float4x4 projectionMatrix;
183 float ratio = viewRatio * (1/frameRatio);
Kateryna Kostiukb9b9e562019-11-09 17:44:48 -0500184 if (ratio < 1.0 && !fill || fill && ratio > 1.0)
185 projectionMatrix = [self getScalingMatrix: ratio axis: 'y'];
186 else
187 projectionMatrix = [self getScalingMatrix: 1/ratio axis: 'x'];
Kateryna Kostiuk1fd950b2019-11-09 18:52:08 -0500188 float radians = (rotation * M_PI) / 180;
Kateryna Kostiuk00dcbff2019-07-11 15:42:13 -0400189 simd::float4x4 rotationMatrix = [self getRotationMatrix:radians];
190 Uniforms bytes = Uniforms{projectionMatrix: projectionMatrix, rotationMatrix: rotationMatrix};
191 id<MTLCommandBuffer> commandBuffer = [commandQueue commandBuffer];
192 [commandBuffer addCompletedHandler:^(id<MTLCommandBuffer> cbuffer) {
193 frameDisplayed = false;
194 CVPixelBufferRelease(buffer);
195 }];
196 MTLRenderPassDescriptor *renderPass = self.currentRenderPassDescriptor;
197 renderPass.colorAttachments[0].texture = drawable.texture;
198 id<MTLRenderCommandEncoder> commandEncoder = [commandBuffer renderCommandEncoderWithDescriptor:renderPass];
199 [commandEncoder setRenderPipelineState: pipeline];
200 [commandEncoder setDepthStencilState:depthState];
201 [commandEncoder setVertexBytes: &bytes length:sizeof(bytes) atIndex:1];
202 [commandEncoder setVertexBuffer:vertexBuffer offset:0 atIndex:kBufferIndexMeshPositions];
203 [commandEncoder setFragmentTexture:textureY atIndex: 1];
204 [commandEncoder setFragmentTexture:textureCbCr atIndex:2];
205 [commandEncoder drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:4];
206 [commandEncoder endEncoding];
207 [commandBuffer presentDrawable:drawable];
208 [commandBuffer commit];
Kateryna Kostiukbbac5ca2019-10-02 13:40:49 -0400209 [self draw];
Kateryna Kostiuk00dcbff2019-07-11 15:42:13 -0400210}
211
212-(simd::float4x4) getScalingMatrix:(CGFloat) ratio axis:(char) axis {
213 simd::float4x4 N = 0.0;
214 simd::float4 v[4] = {0.0, 0.0, 0.0, 0.0};
215 float xMultyplier = axis == 'x' ? ratio: 1;
216 float yMultyplier = axis == 'y' ? ratio: 1;
217 v[0] = { xMultyplier, 0, 0, 0 };
218 v[1] = { 0, yMultyplier, 0, 0 };
219 v[2] = { 0, 0, 1, 0 };
220 v[3] = { 0, 0, 0, 1 };
221 N = matrix_from_rows(v[0], v[1], v[2], v[3]);
222 return N;
223}
224
225-(simd::float4x4) getRotationMatrix:(float) rotation {
226 simd::float4x4 N = 0.0;
227 simd::float4 v[4] = {0.0, 0.0, 0.0, 0.0};
228 v[0] = { cos(rotation), sin(rotation), 0, 0 };
229 v[1] = { -sin(rotation), cos(rotation), 0, 0 };
230 v[2] = { 0, 0, 1, 0 };
231 v[3] = { 0, 0, 0, 1 };
232 N = matrix_from_rows(v[0], v[1], v[2], v[3]);
233 return N;
234}
235
236- (id<MTLTexture>)getTexture:(CVPixelBufferRef)image pixelFormat:(MTLPixelFormat)pixelFormat planeIndex:(int)planeIndex {
237 id<MTLTexture> texture;
238 size_t width, height;
239 if (planeIndex == -1)
240 {
241 width = CVPixelBufferGetWidth(image);
242 height = CVPixelBufferGetHeight(image);
243 planeIndex = 0;
244 }
245 else
246 {
247 width = CVPixelBufferGetWidthOfPlane(image, planeIndex);
248 height = CVPixelBufferGetHeightOfPlane(image, planeIndex);
249 }
250 auto format = CVPixelBufferGetPixelFormatType(image);
251 CVMetalTextureRef textureRef = NULL;
252 CVReturn status = CVMetalTextureCacheCreateTextureFromImage(NULL, textureCache, image, NULL, pixelFormat, width, height, planeIndex, &textureRef);
253 if(status == kCVReturnSuccess)
254 {
255 texture = CVMetalTextureGetTexture(textureRef);
256 CFRelease(textureRef);
257 }
258 else
259 {
260 NSLog(@"CVMetalTextureCacheCreateTextureFromImage failed with return stats %d", status);
261 return NULL;
262 }
263 return texture;
264}
265
266@end