Add FlutterMetalLayer as optional alternative to CAMetalLayer (flutter/engine#48226)

This PR implements `FlutterMetalLayer`, a drop-in (as far as Flutter is
concerned) replacement for `CAMetalLayer`. The biggest difference is
that `FlutterMetalLayer` can present frames from background thread
within a `CATransaction`.

`FlutterMetalLayer` is disabled by default. To opt-in, add the following
item to `Info.plist`:

```xml
        <key>FLTUseFlutterMetalLayer</key>
	<true/>
```

The performance seems quite good, consistent 120hz on iPhone 13 Pro.

Benefits
- presenting with transaction from background thread, which, down the
line, would allow for platform views without thread merging.
- fine control over how the surface is displayed - we can display single
surface on multiple `CALayers`, each showing different part, allowing
for performant implementation of unobstructed platform views.
 
Drawbacks
- this not being a metal layer makes working with metal instrument tools
more awkward
This commit is contained in:
Matej Knopp
2023-12-16 21:53:32 +01:00
committed by GitHub
parent 9e4365fe11
commit 33a6339c63
8 changed files with 718 additions and 5 deletions

View File

@@ -6626,6 +6626,9 @@ ORIGIN: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterKeySe
ORIGIN: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.h + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.mm + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManagerTest.mm + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayer.h + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayer.mm + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayerTest.mm + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterOverlayView.h + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterOverlayView.mm + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformPlugin.h + ../../../flutter/LICENSE
@@ -9452,6 +9455,9 @@ FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterKeySeco
FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.h
FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.mm
FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManagerTest.mm
FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayer.h
FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayer.mm
FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayerTest.mm
FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterOverlayView.h
FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterOverlayView.mm
FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformPlugin.h

View File

@@ -264,7 +264,12 @@ bool SurfaceMTL::Present() const {
[command_buffer waitUntilScheduled];
[drawable_ present];
} else {
[command_buffer presentDrawable:drawable_];
// The drawable may come from a FlutterMetalLayer, so it can't be
// presented through the command buffer.
id<CAMetalDrawable> drawable = drawable_;
[command_buffer addScheduledHandler:^(id<MTLCommandBuffer> buffer) {
[drawable present];
}];
[command_buffer commit];
}
}

View File

@@ -58,12 +58,17 @@ source_set("flutter_framework_source_arc") {
public_configs = [ "//flutter:config" ]
sources = [
"framework/Source/FlutterMetalLayer.h",
"framework/Source/FlutterMetalLayer.mm",
"framework/Source/FlutterTextInputDelegate.h",
"framework/Source/FlutterTextInputPlugin.h",
"framework/Source/FlutterTextInputPlugin.mm",
]
frameworks = [ "UIKit.framework" ]
frameworks = [
"UIKit.framework",
"IOSurface.framework",
]
}
source_set("flutter_framework_source") {
@@ -257,6 +262,7 @@ shared_library("ios_test_flutter") {
"framework/Source/FlutterFakeKeyEvents.h",
"framework/Source/FlutterFakeKeyEvents.mm",
"framework/Source/FlutterKeyboardManagerTest.mm",
"framework/Source/FlutterMetalLayerTest.mm",
"framework/Source/FlutterPlatformPluginTest.mm",
"framework/Source/FlutterPlatformViewsTest.mm",
"framework/Source/FlutterPluginAppLifeCycleDelegateTest.mm",

View File

@@ -0,0 +1,26 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <QuartzCore/QuartzCore.h>
/// Drop-in replacement (as far as Flutter is concerned) for CAMetalLayer
/// that can present with transaction from a background thread.
@interface FlutterMetalLayer : CALayer
@property(nullable, retain) id<MTLDevice> device;
@property(nullable, readonly) id<MTLDevice> preferredDevice;
@property MTLPixelFormat pixelFormat;
@property BOOL framebufferOnly;
@property CGSize drawableSize;
@property BOOL presentsWithTransaction;
@property(nullable) CGColorSpaceRef colorspace;
@property BOOL wantsExtendedDynamicRangeContent;
- (nullable id<CAMetalDrawable>)nextDrawable;
/// Returns whether the Metal layer is enabled.
/// This is controlled by FLTUseFlutterMetalLayer value in Info.plist.
+ (BOOL)enabled;
@end

View File

@@ -0,0 +1,423 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <IOSurface/IOSurfaceObjC.h>
#include <Metal/Metal.h>
#include <UIKit/UIKit.h>
#include "flutter/fml/logging.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayer.h"
@interface DisplayLinkManager : NSObject
@property(class, nonatomic, readonly) BOOL maxRefreshRateEnabledOnIPhone;
+ (double)displayRefreshRate;
@end
@class FlutterTexture;
@class FlutterDrawable;
extern CFTimeInterval display_link_target;
@interface FlutterMetalLayer () {
id<MTLDevice> _preferredDevice;
CGSize _drawableSize;
NSUInteger _nextDrawableId;
NSMutableSet<FlutterTexture*>* _availableTextures;
NSUInteger _totalTextures;
FlutterTexture* _front;
// There must be a CADisplayLink scheduled *on main thread* otherwise
// core animation only updates layers 60 times a second.
CADisplayLink* _displayLink;
NSUInteger _displayLinkPauseCountdown;
// Used to track whether the content was set during this display link.
// When unlocking phone the layer (main thread) display link and raster thread
// display link get out of sync for several seconds. Even worse, layer display
// link does not seem to reflect actual vsync. Forcing the layer link
// to max rate (instead range) temporarily seems to fix the issue.
BOOL _didSetContentsDuringThisDisplayLinkPeriod;
// Whether layer displayLink is forced to max rate.
BOOL _displayLinkForcedMaxRate;
}
- (void)presentTexture:(FlutterTexture*)texture;
- (void)returnTexture:(FlutterTexture*)texture;
@end
@interface FlutterTexture : NSObject {
id<MTLTexture> _texture;
IOSurface* _surface;
CFTimeInterval _presentedTime;
}
@property(readonly, nonatomic) id<MTLTexture> texture;
@property(readonly, nonatomic) IOSurface* surface;
@property(readwrite, nonatomic) CFTimeInterval presentedTime;
@end
@implementation FlutterTexture
@synthesize texture = _texture;
@synthesize surface = _surface;
@synthesize presentedTime = _presentedTime;
- (instancetype)initWithTexture:(id<MTLTexture>)texture surface:(IOSurface*)surface {
if (self = [super init]) {
_texture = texture;
_surface = surface;
}
return self;
}
@end
@interface FlutterDrawable : NSObject <CAMetalDrawable> {
FlutterTexture* _texture;
__weak FlutterMetalLayer* _layer;
NSUInteger _drawableId;
BOOL _presented;
}
- (instancetype)initWithTexture:(FlutterTexture*)texture
layer:(FlutterMetalLayer*)layer
drawableId:(NSUInteger)drawableId;
@end
@implementation FlutterDrawable
- (instancetype)initWithTexture:(FlutterTexture*)texture
layer:(FlutterMetalLayer*)layer
drawableId:(NSUInteger)drawableId {
if (self = [super init]) {
_texture = texture;
_layer = layer;
_drawableId = drawableId;
}
return self;
}
- (id<MTLTexture>)texture {
return self->_texture.texture;
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunguarded-availability-new"
- (CAMetalLayer*)layer {
return (id)self->_layer;
}
#pragma clang diagnostic pop
- (NSUInteger)drawableID {
return self->_drawableId;
}
- (CFTimeInterval)presentedTime {
return 0;
}
- (void)present {
[_layer presentTexture:self->_texture];
self->_presented = YES;
}
- (void)dealloc {
if (!_presented) {
[_layer returnTexture:self->_texture];
}
}
- (void)addPresentedHandler:(nonnull MTLDrawablePresentedHandler)block {
FML_LOG(WARNING) << "FlutterMetalLayer drawable does not implement addPresentedHandler:";
}
- (void)presentAtTime:(CFTimeInterval)presentationTime {
FML_LOG(WARNING) << "FlutterMetalLayer drawable does not implement presentAtTime:";
}
- (void)presentAfterMinimumDuration:(CFTimeInterval)duration {
FML_LOG(WARNING) << "FlutterMetalLayer drawable does not implement presentAfterMinimumDuration:";
}
@end
@implementation FlutterMetalLayer
@synthesize preferredDevice = _preferredDevice;
@synthesize device = _device;
@synthesize pixelFormat = _pixelFormat;
@synthesize framebufferOnly = _framebufferOnly;
@synthesize colorspace = _colorspace;
@synthesize wantsExtendedDynamicRangeContent = _wantsExtendedDynamicRangeContent;
- (instancetype)init {
if (self = [super init]) {
_preferredDevice = MTLCreateSystemDefaultDevice();
self.device = self.preferredDevice;
self.pixelFormat = MTLPixelFormatBGRA8Unorm;
_availableTextures = [[NSMutableSet alloc] init];
_displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(onDisplayLink:)];
[self setMaxRefreshRate:[DisplayLinkManager displayRefreshRate] forceMax:NO];
[_displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(didEnterBackground:)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
}
return self;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)setMaxRefreshRate:(double)refreshRate forceMax:(BOOL)forceMax {
// This is copied from vsync_waiter_ios.mm. The vsync waiter has display link scheduled on UI
// thread which does not trigger actual core animation frame. As a workaround FlutterMetalLayer
// has it's own displaylink scheduled on main thread, which is used to trigger core animation
// frame allowing for 120hz updates.
if (!DisplayLinkManager.maxRefreshRateEnabledOnIPhone) {
return;
}
double maxFrameRate = fmax(refreshRate, 60);
double minFrameRate = fmax(maxFrameRate / 2, 60);
if (@available(iOS 15.0, *)) {
_displayLink.preferredFrameRateRange =
CAFrameRateRangeMake(forceMax ? maxFrameRate : minFrameRate, maxFrameRate, maxFrameRate);
} else {
_displayLink.preferredFramesPerSecond = maxFrameRate;
}
}
- (void)onDisplayLink:(CADisplayLink*)link {
_didSetContentsDuringThisDisplayLinkPeriod = NO;
// Do not pause immediately, this seems to prevent 120hz while touching.
if (_displayLinkPauseCountdown == 3) {
_displayLink.paused = YES;
if (_displayLinkForcedMaxRate) {
[self setMaxRefreshRate:[DisplayLinkManager displayRefreshRate] forceMax:NO];
_displayLinkForcedMaxRate = NO;
}
} else {
++_displayLinkPauseCountdown;
}
}
- (BOOL)isKindOfClass:(Class)aClass {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunguarded-availability-new"
// Pretend that we're a CAMetalLayer so that the rest of Flutter plays along
if ([aClass isEqual:[CAMetalLayer class]]) {
return YES;
}
#pragma clang diagnostic pop
return [super isKindOfClass:aClass];
}
- (void)setDrawableSize:(CGSize)drawableSize {
[_availableTextures removeAllObjects];
_front = nil;
_totalTextures = 0;
_drawableSize = drawableSize;
}
- (void)didEnterBackground:(id)notification {
[_availableTextures removeAllObjects];
_totalTextures = _front != nil ? 1 : 0;
_displayLink.paused = YES;
}
- (CGSize)drawableSize {
return _drawableSize;
}
- (IOSurface*)createIOSurface {
unsigned pixelFormat;
unsigned bytesPerElement;
if (self.pixelFormat == MTLPixelFormatRGBA16Float) {
pixelFormat = kCVPixelFormatType_64RGBAHalf;
bytesPerElement = 8;
} else if (self.pixelFormat == MTLPixelFormatBGRA8Unorm) {
pixelFormat = kCVPixelFormatType_32BGRA;
bytesPerElement = 4;
} else {
FML_LOG(ERROR) << "Unsupported pixel format: " << self.pixelFormat;
return nil;
}
size_t bytesPerRow =
IOSurfaceAlignProperty(kIOSurfaceBytesPerRow, _drawableSize.width * bytesPerElement);
size_t totalBytes =
IOSurfaceAlignProperty(kIOSurfaceAllocSize, _drawableSize.height * bytesPerRow);
NSDictionary* options = @{
(id)kIOSurfaceWidth : @(_drawableSize.width),
(id)kIOSurfaceHeight : @(_drawableSize.height),
(id)kIOSurfacePixelFormat : @(pixelFormat),
(id)kIOSurfaceBytesPerElement : @(bytesPerElement),
(id)kIOSurfaceBytesPerRow : @(bytesPerRow),
(id)kIOSurfaceAllocSize : @(totalBytes),
};
IOSurfaceRef res = IOSurfaceCreate((CFDictionaryRef)options);
if (res == nil) {
FML_LOG(ERROR) << "Failed to create IOSurface with options "
<< options.debugDescription.UTF8String;
return nil;
}
if (self.colorspace != nil) {
CFStringRef name = CGColorSpaceGetName(self.colorspace);
IOSurfaceSetValue(res, CFSTR("IOSurfaceColorSpace"), name);
} else {
IOSurfaceSetValue(res, CFSTR("IOSurfaceColorSpace"), kCGColorSpaceSRGB);
}
return (__bridge_transfer IOSurface*)res;
}
- (FlutterTexture*)nextTexture {
@synchronized(self) {
if (_totalTextures < 3) {
++_totalTextures;
IOSurface* surface = [self createIOSurface];
if (surface == nil) {
return nil;
}
MTLTextureDescriptor* textureDescriptor =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:_pixelFormat
width:_drawableSize.width
height:_drawableSize.height
mipmapped:NO];
if (_framebufferOnly) {
textureDescriptor.usage = MTLTextureUsageRenderTarget;
} else {
textureDescriptor.usage =
MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead | MTLTextureUsageShaderWrite;
}
id<MTLTexture> texture = [self.device newTextureWithDescriptor:textureDescriptor
iosurface:(__bridge IOSurfaceRef)surface
plane:0];
FlutterTexture* flutterTexture = [[FlutterTexture alloc] initWithTexture:texture
surface:surface];
return flutterTexture;
} else {
// Make sure raster thread doesn't have too many drawables in flight.
if (_availableTextures.count == 0) {
CFTimeInterval start = CACurrentMediaTime();
while (_availableTextures.count == 0 && CACurrentMediaTime() - start < 1.0) {
usleep(100);
}
CFTimeInterval elapsed = CACurrentMediaTime() - start;
if (_availableTextures.count == 0) {
NSLog(@"Waited %f seconds for a drawable, giving up.", elapsed);
return nil;
} else {
NSLog(@"Had to wait %f seconds for a drawable", elapsed);
}
}
// Prefer surface that is not in use and has been presented the longest
// time ago.
// When isInUse is false, the surface is definitely not used by the compositor.
// When isInUse is true, the surface may be used by the compositor.
// When both surfaces are in use, the one presented earlier will be returned.
// The assumption here is that the compositor is already aware of the
// newer texture and is unlikely to read from the older one, even though it
// has not decreased the use count yet (there seems to be certain latency).
FlutterTexture* res = nil;
for (FlutterTexture* texture in _availableTextures) {
if (res == nil) {
res = texture;
} else if (res.surface.isInUse && !texture.surface.isInUse) {
// prefer texture that is not in use.
res = texture;
} else if (res.surface.isInUse == texture.surface.isInUse &&
texture.presentedTime < res.presentedTime) {
// prefer texture with older presented time.
res = texture;
}
}
[_availableTextures removeObject:res];
return res;
}
}
}
- (id<CAMetalDrawable>)nextDrawable {
FlutterTexture* texture = [self nextTexture];
if (texture == nil) {
return nil;
}
FlutterDrawable* drawable = [[FlutterDrawable alloc] initWithTexture:texture
layer:self
drawableId:_nextDrawableId++];
return drawable;
}
- (void)presentOnMainThread:(FlutterTexture*)texture {
// This is needed otherwise frame gets skipped on touch begin / end. Go figure.
// Might also be placebo
[self setNeedsDisplay];
[CATransaction begin];
[CATransaction setDisableActions:YES];
self.contents = texture.surface;
texture.presentedTime = CACurrentMediaTime();
[CATransaction commit];
_displayLink.paused = NO;
_displayLinkPauseCountdown = 0;
if (!_didSetContentsDuringThisDisplayLinkPeriod) {
_didSetContentsDuringThisDisplayLinkPeriod = YES;
} else if (!_displayLinkForcedMaxRate) {
_displayLinkForcedMaxRate = YES;
[self setMaxRefreshRate:[DisplayLinkManager displayRefreshRate] forceMax:YES];
}
}
- (void)presentTexture:(FlutterTexture*)texture {
@synchronized(self) {
if (_front != nil) {
[_availableTextures addObject:_front];
}
_front = texture;
if ([NSThread isMainThread]) {
[self presentOnMainThread:texture];
} else {
// Core animation layers can only be updated on main thread.
dispatch_async(dispatch_get_main_queue(), ^{
[self presentOnMainThread:texture];
});
}
}
}
- (void)returnTexture:(FlutterTexture*)texture {
@synchronized(self) {
[_availableTextures addObject:texture];
}
}
+ (BOOL)enabled {
static BOOL enabled = NO;
static BOOL didCheckInfoPlist = NO;
if (!didCheckInfoPlist) {
didCheckInfoPlist = YES;
NSNumber* use_flutter_metal_layer =
[[NSBundle mainBundle] objectForInfoDictionaryKey:@"FLTUseFlutterMetalLayer"];
if (use_flutter_metal_layer != nil && [use_flutter_metal_layer boolValue]) {
enabled = YES;
FML_LOG(WARNING) << "Using FlutterMetalLayer. This is an experimental feature.";
}
}
return enabled;
}
@end

View File

@@ -0,0 +1,239 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <Metal/Metal.h>
#import <QuartzCore/QuartzCore.h>
#import <XCTest/XCTest.h>
#include "flutter/fml/logging.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayer.h"
@interface FlutterMetalLayerTest : XCTestCase
@end
@interface TestFlutterMetalLayerView : UIView
@end
@implementation TestFlutterMetalLayerView
+ (Class)layerClass {
return [FlutterMetalLayer class];
}
@end
/// A fake compositor that simulates presenting layer surface by increasing
/// and decreasing IOSurface use count.
@interface TestCompositor : NSObject {
FlutterMetalLayer* _layer;
IOSurfaceRef _presentedSurface;
}
@end
@implementation TestCompositor
- (instancetype)initWithLayer:(FlutterMetalLayer*)layer {
self = [super init];
if (self) {
self->_layer = layer;
}
return self;
}
/// Increment use count of currently presented surface and decrement use count
/// of previously presented surface.
- (void)commitTransaction {
IOSurfaceRef surface = (__bridge IOSurfaceRef)self->_layer.contents;
if (self->_presentedSurface) {
IOSurfaceDecrementUseCount(self->_presentedSurface);
}
IOSurfaceIncrementUseCount(surface);
self->_presentedSurface = surface;
}
- (void)dealloc {
if (self->_presentedSurface) {
IOSurfaceDecrementUseCount(self->_presentedSurface);
}
}
@end
@implementation FlutterMetalLayerTest
- (FlutterMetalLayer*)addMetalLayer {
TestFlutterMetalLayerView* view =
[[TestFlutterMetalLayerView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
FlutterMetalLayer* layer = (FlutterMetalLayer*)view.layer;
layer.drawableSize = CGSizeMake(100, 100);
return layer;
}
- (void)removeMetalLayer:(FlutterMetalLayer*)layer {
}
// For unknown reason sometimes CI fails to create IOSurface. Bail out
// to prevent flakiness.
#define BAIL_IF_NO_DRAWABLE(drawable) \
if (drawable == nil) { \
FML_LOG(ERROR) << "Could not allocate drawable"; \
return; \
}
- (void)testFlip {
FlutterMetalLayer* layer = [self addMetalLayer];
TestCompositor* compositor = [[TestCompositor alloc] initWithLayer:layer];
id<MTLTexture> t1, t2, t3;
id<CAMetalDrawable> drawable = [layer nextDrawable];
BAIL_IF_NO_DRAWABLE(drawable);
t1 = drawable.texture;
[drawable present];
[compositor commitTransaction];
drawable = [layer nextDrawable];
BAIL_IF_NO_DRAWABLE(drawable);
t2 = drawable.texture;
[drawable present];
[compositor commitTransaction];
drawable = [layer nextDrawable];
BAIL_IF_NO_DRAWABLE(drawable);
t3 = drawable.texture;
[drawable present];
[compositor commitTransaction];
// If there was no frame drop, layer should return oldest presented
// texture.
drawable = [layer nextDrawable];
XCTAssertEqual(drawable.texture, t1);
[drawable present];
[compositor commitTransaction];
drawable = [layer nextDrawable];
XCTAssertEqual(drawable.texture, t2);
[drawable present];
[compositor commitTransaction];
drawable = [layer nextDrawable];
XCTAssertEqual(drawable.texture, t3);
[drawable present];
[compositor commitTransaction];
drawable = [layer nextDrawable];
XCTAssertEqual(drawable.texture, t1);
[drawable present];
[self removeMetalLayer:layer];
}
- (void)testFlipWithDroppedFrame {
FlutterMetalLayer* layer = [self addMetalLayer];
TestCompositor* compositor = [[TestCompositor alloc] initWithLayer:layer];
id<MTLTexture> t1, t2, t3;
id<CAMetalDrawable> drawable = [layer nextDrawable];
BAIL_IF_NO_DRAWABLE(drawable);
t1 = drawable.texture;
[drawable present];
[compositor commitTransaction];
XCTAssertTrue(IOSurfaceIsInUse(t1.iosurface));
drawable = [layer nextDrawable];
BAIL_IF_NO_DRAWABLE(drawable);
t2 = drawable.texture;
[drawable present];
[compositor commitTransaction];
drawable = [layer nextDrawable];
BAIL_IF_NO_DRAWABLE(drawable);
t3 = drawable.texture;
[drawable present];
[compositor commitTransaction];
// Simulate compositor holding on to t3 for a while.
IOSurfaceIncrementUseCount(t3.iosurface);
// Here the drawable is presented, but immediately replaced by another drawable
// (before the compositor has a chance to pick it up). This should result
// in same drawable returned in next call to nextDrawable.
drawable = [layer nextDrawable];
XCTAssertEqual(drawable.texture, t1);
XCTAssertFalse(IOSurfaceIsInUse(drawable.texture.iosurface));
[drawable present];
drawable = [layer nextDrawable];
XCTAssertEqual(drawable.texture, t2);
[drawable present];
[compositor commitTransaction];
// Next drawable should be t1, since it was never picked up by compositor.
drawable = [layer nextDrawable];
XCTAssertEqual(drawable.texture, t1);
IOSurfaceDecrementUseCount(t3.iosurface);
[self removeMetalLayer:layer];
}
- (void)testDroppedDrawableReturnsTextureToPool {
FlutterMetalLayer* layer = [self addMetalLayer];
// FlutterMetalLayer will keep creating new textures until it has 3.
@autoreleasepool {
for (int i = 0; i < 3; ++i) {
id<CAMetalDrawable> drawable = [layer nextDrawable];
BAIL_IF_NO_DRAWABLE(drawable);
}
}
id<MTLTexture> texture;
{
@autoreleasepool {
id<CAMetalDrawable> drawable = [layer nextDrawable];
XCTAssertNotNil(drawable);
texture = (id<MTLTexture>)drawable.texture;
// Dropping the drawable must return texture to pool, so
// next drawable should return the same texture.
}
}
{
id<CAMetalDrawable> drawable = [layer nextDrawable];
XCTAssertEqual(texture, drawable.texture);
}
[self removeMetalLayer:layer];
}
- (void)testLayerLimitsDrawableCount {
FlutterMetalLayer* layer = [self addMetalLayer];
id<CAMetalDrawable> d1 = [layer nextDrawable];
BAIL_IF_NO_DRAWABLE(d1);
id<CAMetalDrawable> d2 = [layer nextDrawable];
BAIL_IF_NO_DRAWABLE(d2);
id<CAMetalDrawable> d3 = [layer nextDrawable];
BAIL_IF_NO_DRAWABLE(d3);
XCTAssertNotNil(d3);
// Layer should not return more than 3 drawables.
id<CAMetalDrawable> d4 = [layer nextDrawable];
XCTAssertNil(d4);
[d1 present];
// Still no drawable, until the front buffer returns to pool
id<CAMetalDrawable> d5 = [layer nextDrawable];
XCTAssertNil(d5);
[d2 present];
id<CAMetalDrawable> d6 = [layer nextDrawable];
XCTAssertNotNil(d6);
[self removeMetalLayer:layer];
}
@end

View File

@@ -14,6 +14,8 @@
#include "flutter/fml/logging.h"
#include "flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayer.h"
namespace flutter {
#if SHELL_ENABLE_METAL
@@ -64,7 +66,11 @@ Class GetCoreAnimationLayerClassForRenderingAPI(IOSRenderingAPI rendering_api) {
return [CALayer class];
case IOSRenderingAPI::kMetal:
if (@available(iOS METAL_IOS_VERSION_BASELINE, *)) {
return [CAMetalLayer class];
if ([FlutterMetalLayer enabled]) {
return [FlutterMetalLayer class];
} else {
return [CAMetalLayer class];
}
}
FML_CHECK(false) << "Metal availability should already have been checked";
break;

View File

@@ -69,10 +69,11 @@
0D6AB6C922BB05E200EEE540 /* IosUnitTestsTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = IosUnitTestsTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
0D6AB6CF22BB05E200EEE540 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
0D6AB73E22BD8F0200EEE540 /* FlutterEngineConfig.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = FlutterEngineConfig.xcconfig; sourceTree = "<group>"; };
3DD7D38C27D2B81000DA365C /* FlutterUndoManagerPluginTest.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = FlutterUndoManagerPluginTest.mm; sourceTree = "<group>"; };
689EC1E2281B30D3008FEB58 /* FlutterSpellCheckPluginTest.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = FlutterSpellCheckPluginTest.mm; sourceTree = "<group>"; };
68B6091227F62F990036AC78 /* VsyncWaiterIosTest.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = VsyncWaiterIosTest.mm; sourceTree = "<group>"; };
3DD7D38C27D2B81000DA365C /* FlutterUndoManagerPluginTest.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = FlutterUndoManagerPluginTest.mm; sourceTree = "<group>"; };
73F12C22288F92FF00AFC3A6 /* FlutterViewControllerTest_mrc.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = FlutterViewControllerTest_mrc.mm; sourceTree = "<group>"; };
73F12C22288F92FF00AFC3A6 /* FlutterViewControllerTest_mrc.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = FlutterViewControllerTest_mrc.mm; sourceTree = "<group>"; };
D2D361A52B234EAC0018964E /* FlutterMetalLayerTest.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = FlutterMetalLayerTest.mm; sourceTree = "<group>"; };
F7521D7226BB671E005F15C5 /* libios_test_flutter.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libios_test_flutter.dylib; path = "../../../../out/$(FLUTTER_ENGINE)/libios_test_flutter.dylib"; sourceTree = "<group>"; };
F7521D7526BB673E005F15C5 /* libocmock_shared.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libocmock_shared.dylib; path = "../../../../out/$(FLUTTER_ENGINE)/libocmock_shared.dylib"; sourceTree = "<group>"; };
F77E081726FA9CE6003E6E4C /* Flutter.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Flutter.framework; path = "../../../../out/$(FLUTTER_ENGINE)/Flutter.framework"; sourceTree = "<group>"; };
@@ -114,6 +115,7 @@
0AC2331924BA71D300A85907 /* FlutterPluginAppLifeCycleDelegateTest.mm */,
0AC2332124BA71D300A85907 /* FlutterViewControllerTest.mm */,
73F12C22288F92FF00AFC3A6 /* FlutterViewControllerTest_mrc.mm */,
D2D361A52B234EAC0018964E /* FlutterMetalLayerTest.mm */,
);
name = Source;
path = ../../../shell/platform/darwin/ios/framework/Source;