Kateryna Kostiuk | 00dcbff | 2019-07-11 15:42:13 -0400 | [diff] [blame] | 1 | /* |
| 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 |
| 31 | static 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 | |
| 38 | typedef enum BufferIndices { |
| 39 | kBufferIndexMeshPositions = 0, |
| 40 | } BufferIndices; |
| 41 | |
| 42 | typedef enum VertexAttributes { |
| 43 | kVertexAttributePosition = 0, |
| 44 | kVertexAttributeTexcoord = 1, |
| 45 | } VertexAttributes; |
| 46 | |
| 47 | struct 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 Kostiuk | 5d90c3b | 2019-07-18 12:03:52 -0400 | [diff] [blame] | 56 | [self setupView]; |
Kateryna Kostiuk | 00dcbff | 2019-07-11 15:42:13 -0400 | [diff] [blame] | 57 | } |
| 58 | return self; |
| 59 | } |
| 60 | |
Kateryna Kostiuk | 5d90c3b | 2019-07-18 12:03:52 -0400 | [diff] [blame] | 61 | -(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; |
| 114 | } |
| 115 | |
Kateryna Kostiuk | 00dcbff | 2019-07-11 15:42:13 -0400 | [diff] [blame] | 116 | - (void)fillWithBlack { |
| 117 | NSUInteger width = self.frame.size.width; |
| 118 | NSUInteger height = self.frame.size.height; |
| 119 | CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); |
| 120 | uint8_t *rawData = (uint8_t *)calloc(height * width * 4, sizeof(uint8_t)); |
| 121 | NSUInteger bytesPerPixel = 4; |
| 122 | NSUInteger bytesPerRow = bytesPerPixel * width; |
| 123 | NSUInteger bitsPerComponent = 8; |
| 124 | MTLTextureDescriptor *textureDescriptor = |
| 125 | [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm |
| 126 | width:width |
| 127 | height:height |
| 128 | mipmapped:YES]; |
| 129 | textureDescriptor.usage = MTLTextureUsageRenderTarget; |
| 130 | id<MTLTexture> texture = [self.device newTextureWithDescriptor:textureDescriptor]; |
| 131 | MTLRegion region = MTLRegionMake2D(0, 0, width, height); |
| 132 | [texture replaceRegion:region mipmapLevel:0 withBytes:rawData bytesPerRow:bytesPerRow]; |
| 133 | id<MTLCommandBuffer> commandBuffer = [commandQueue commandBuffer]; |
| 134 | MTLRenderPassDescriptor *renderPass = self.currentRenderPassDescriptor; |
| 135 | id<MTLRenderCommandEncoder> commandEncoder = [commandBuffer renderCommandEncoderWithDescriptor:renderPass]; |
| 136 | [commandEncoder setFragmentTexture:texture atIndex:0]; |
| 137 | [commandEncoder endEncoding]; |
| 138 | [commandBuffer presentDrawable:self.currentDrawable]; |
| 139 | [commandBuffer commit]; |
| 140 | } |
| 141 | |
| 142 | bool frameDisplayed = false; |
| 143 | |
| 144 | - (void)renderWithPixelBuffer:(CVPixelBufferRef)buffer |
| 145 | size:(CGSize)size |
| 146 | rotation: (float)rotation |
| 147 | fillFrame: (bool)fill { |
| 148 | if(frameDisplayed) { |
| 149 | return; |
| 150 | } |
| 151 | if(_stopRendering) { |
| 152 | self.releaseDrawables; |
| 153 | return; |
| 154 | } |
| 155 | if (buffer == nil) return; |
| 156 | frameDisplayed = true; |
| 157 | CFRetain(buffer); |
| 158 | CVPixelBufferLockBaseAddress(buffer, 0); |
| 159 | id<MTLTexture> textureY = [self getTexture:buffer pixelFormat:MTLPixelFormatR8Unorm planeIndex:0]; |
| 160 | id<MTLTexture> textureCbCr = [self getTexture:buffer pixelFormat:MTLPixelFormatRG8Unorm planeIndex:1]; |
| 161 | CVPixelBufferUnlockBaseAddress(buffer, 0); |
| 162 | if(textureY == NULL || textureCbCr == NULL) { |
| 163 | frameDisplayed = false; |
| 164 | CVPixelBufferRelease(buffer); |
| 165 | return; |
| 166 | } |
| 167 | id<CAMetalDrawable> drawable = self.currentDrawable; |
| 168 | if (!drawable.texture) { |
| 169 | frameDisplayed = false; |
| 170 | CVPixelBufferRelease(buffer); |
| 171 | return; |
| 172 | } |
| 173 | NSSize frameSize = self.frame.size; |
| 174 | |
Kateryna Kostiuk | b61b0fa | 2019-09-24 17:56:30 -0400 | [diff] [blame] | 175 | float viewRatio = (rotation == 90 || rotation == -90) ? |
Kateryna Kostiuk | 00dcbff | 2019-07-11 15:42:13 -0400 | [diff] [blame] | 176 | frameSize.height/frameSize.width : frameSize.width/frameSize.height; |
| 177 | float frameRatio = ((float)size.width)/((float)size.height); |
| 178 | simd::float4x4 projectionMatrix; |
| 179 | float ratio = viewRatio * (1/frameRatio); |
| 180 | if((viewRatio >= 1 && frameRatio >= 1) || |
| 181 | (viewRatio < 1 && frameRatio < 1) || |
| 182 | (ratio > 0.5 && ratio < 1.5) ) { |
| 183 | if (ratio <= 1.0 && ratio >= 0.5) |
| 184 | projectionMatrix = [self getScalingMatrix: 1/ratio axis: 'x']; |
| 185 | else if (ratio < 0.5) |
| 186 | projectionMatrix = [self getScalingMatrix: ratio axis: 'y']; |
| 187 | else if (ratio > 1 && ratio < 2) |
| 188 | projectionMatrix = [self getScalingMatrix: ratio axis: 'y']; |
| 189 | else |
| 190 | projectionMatrix = [self getScalingMatrix: 1/ratio axis: 'x']; |
| 191 | } else { |
| 192 | if (ratio < 1.0 && !fill || fill && ratio > 1.0) |
| 193 | projectionMatrix = [self getScalingMatrix: ratio axis: 'y']; |
| 194 | else |
| 195 | projectionMatrix = [self getScalingMatrix: 1/ratio axis: 'x']; |
| 196 | } |
| 197 | float radians = (-rotation * M_PI) / 180; |
| 198 | simd::float4x4 rotationMatrix = [self getRotationMatrix:radians]; |
| 199 | Uniforms bytes = Uniforms{projectionMatrix: projectionMatrix, rotationMatrix: rotationMatrix}; |
| 200 | id<MTLCommandBuffer> commandBuffer = [commandQueue commandBuffer]; |
| 201 | [commandBuffer addCompletedHandler:^(id<MTLCommandBuffer> cbuffer) { |
| 202 | frameDisplayed = false; |
| 203 | CVPixelBufferRelease(buffer); |
| 204 | }]; |
| 205 | MTLRenderPassDescriptor *renderPass = self.currentRenderPassDescriptor; |
| 206 | renderPass.colorAttachments[0].texture = drawable.texture; |
| 207 | id<MTLRenderCommandEncoder> commandEncoder = [commandBuffer renderCommandEncoderWithDescriptor:renderPass]; |
| 208 | [commandEncoder setRenderPipelineState: pipeline]; |
| 209 | [commandEncoder setDepthStencilState:depthState]; |
| 210 | [commandEncoder setVertexBytes: &bytes length:sizeof(bytes) atIndex:1]; |
| 211 | [commandEncoder setVertexBuffer:vertexBuffer offset:0 atIndex:kBufferIndexMeshPositions]; |
| 212 | [commandEncoder setFragmentTexture:textureY atIndex: 1]; |
| 213 | [commandEncoder setFragmentTexture:textureCbCr atIndex:2]; |
| 214 | [commandEncoder drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:4]; |
| 215 | [commandEncoder endEncoding]; |
| 216 | [commandBuffer presentDrawable:drawable]; |
| 217 | [commandBuffer commit]; |
Kateryna Kostiuk | bbac5ca | 2019-10-02 13:40:49 -0400 | [diff] [blame] | 218 | [self draw]; |
Kateryna Kostiuk | 00dcbff | 2019-07-11 15:42:13 -0400 | [diff] [blame] | 219 | } |
| 220 | |
| 221 | -(simd::float4x4) getScalingMatrix:(CGFloat) ratio axis:(char) axis { |
| 222 | simd::float4x4 N = 0.0; |
| 223 | simd::float4 v[4] = {0.0, 0.0, 0.0, 0.0}; |
| 224 | float xMultyplier = axis == 'x' ? ratio: 1; |
| 225 | float yMultyplier = axis == 'y' ? ratio: 1; |
| 226 | v[0] = { xMultyplier, 0, 0, 0 }; |
| 227 | v[1] = { 0, yMultyplier, 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 | -(simd::float4x4) getRotationMatrix:(float) rotation { |
| 235 | simd::float4x4 N = 0.0; |
| 236 | simd::float4 v[4] = {0.0, 0.0, 0.0, 0.0}; |
| 237 | v[0] = { cos(rotation), sin(rotation), 0, 0 }; |
| 238 | v[1] = { -sin(rotation), cos(rotation), 0, 0 }; |
| 239 | v[2] = { 0, 0, 1, 0 }; |
| 240 | v[3] = { 0, 0, 0, 1 }; |
| 241 | N = matrix_from_rows(v[0], v[1], v[2], v[3]); |
| 242 | return N; |
| 243 | } |
| 244 | |
| 245 | - (id<MTLTexture>)getTexture:(CVPixelBufferRef)image pixelFormat:(MTLPixelFormat)pixelFormat planeIndex:(int)planeIndex { |
| 246 | id<MTLTexture> texture; |
| 247 | size_t width, height; |
| 248 | if (planeIndex == -1) |
| 249 | { |
| 250 | width = CVPixelBufferGetWidth(image); |
| 251 | height = CVPixelBufferGetHeight(image); |
| 252 | planeIndex = 0; |
| 253 | } |
| 254 | else |
| 255 | { |
| 256 | width = CVPixelBufferGetWidthOfPlane(image, planeIndex); |
| 257 | height = CVPixelBufferGetHeightOfPlane(image, planeIndex); |
| 258 | } |
| 259 | auto format = CVPixelBufferGetPixelFormatType(image); |
| 260 | CVMetalTextureRef textureRef = NULL; |
| 261 | CVReturn status = CVMetalTextureCacheCreateTextureFromImage(NULL, textureCache, image, NULL, pixelFormat, width, height, planeIndex, &textureRef); |
| 262 | if(status == kCVReturnSuccess) |
| 263 | { |
| 264 | texture = CVMetalTextureGetTexture(textureRef); |
| 265 | CFRelease(textureRef); |
| 266 | } |
| 267 | else |
| 268 | { |
| 269 | NSLog(@"CVMetalTextureCacheCreateTextureFromImage failed with return stats %d", status); |
| 270 | return NULL; |
| 271 | } |
| 272 | return texture; |
| 273 | } |
| 274 | |
| 275 | @end |