7 #import <Metal/Metal.h>
29 return reinterpret_cast<int64_t
>(
_texture);
33 return _isInUseOverride || IOSurfaceIsInUse(_ioSurface);
37 return _isInUseOverride;
40 - (void)setIsInUseOverride:(BOOL)isInUseOverride {
44 - (instancetype)initWithSize:(CGSize)size device:(
id<MTLDevice>)device {
45 if (
self = [super init]) {
48 self->_texture = [
FlutterSurface createTextureForIOSurface:_ioSurface size:size device:device];
53 static void ReleaseSurface(
void* surface) {
54 if (surface !=
nullptr) {
55 CFBridgingRelease(surface);
60 FlutterMetalTexture res;
61 memset(&res, 0,
sizeof(FlutterMetalTexture));
62 res.struct_size =
sizeof(FlutterMetalTexture);
63 res.texture = (__bridge
void*)
_texture;
64 res.texture_id =
self.textureId;
65 res.user_data = (
void*)CFBridgingRetain(
self);
66 res.destruction_callback = ReleaseSurface;
70 + (
FlutterSurface*)fromFlutterMetalTexture:(const FlutterMetalTexture*)texture {
75 CFRelease(_ioSurface);
78 + (IOSurfaceRef)createIOSurfaceWithSize:(CGSize)size {
79 unsigned pixelFormat =
'BGRA';
80 unsigned bytesPerElement = 4;
82 size_t bytesPerRow = IOSurfaceAlignProperty(kIOSurfaceBytesPerRow,
size.width * bytesPerElement);
83 size_t totalBytes = IOSurfaceAlignProperty(kIOSurfaceAllocSize,
size.height * bytesPerRow);
84 NSDictionary* options = @{
85 (id)kIOSurfaceWidth : @(
size.width),
86 (id)kIOSurfaceHeight : @(
size.height),
87 (id)kIOSurfacePixelFormat : @(pixelFormat),
88 (id)kIOSurfaceBytesPerElement : @(bytesPerElement),
89 (id)kIOSurfaceBytesPerRow : @(bytesPerRow),
90 (id)kIOSurfaceAllocSize : @(totalBytes),
93 IOSurfaceRef res = IOSurfaceCreate((CFDictionaryRef)options);
94 IOSurfaceSetValue(res, CFSTR(
"IOSurfaceColorSpace"), kCGColorSpaceSRGB);
98 + (id<MTLTexture>)createTextureForIOSurface:(IOSurfaceRef)surface
100 device:(
id<MTLDevice>)device {
101 MTLTextureDescriptor* textureDescriptor =
102 [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
106 textureDescriptor.usage =
107 MTLTextureUsageShaderRead | MTLTextureUsageRenderTarget | MTLTextureUsageShaderWrite;
109 return [device newTextureWithDescriptor:textureDescriptor iosurface:surface plane:0];