From 33a6339c63be8b33a127f179c597fa2f89b44b22 Mon Sep 17 00:00:00 2001 From: Matej Knopp Date: Sat, 16 Dec 2023 21:53:32 +0100 Subject: [PATCH] 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 FLTUseFlutterMetalLayer ``` 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 --- .../ci/licenses_golden/licenses_flutter | 6 + .../renderer/backend/metal/surface_mtl.mm | 7 +- .../shell/platform/darwin/ios/BUILD.gn | 8 +- .../ios/framework/Source/FlutterMetalLayer.h | 26 ++ .../ios/framework/Source/FlutterMetalLayer.mm | 423 ++++++++++++++++++ .../framework/Source/FlutterMetalLayerTest.mm | 239 ++++++++++ .../darwin/ios/rendering_api_selection.mm | 8 +- .../IosUnitTests.xcodeproj/project.pbxproj | 6 +- 8 files changed, 718 insertions(+), 5 deletions(-) create mode 100644 engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayer.h create mode 100644 engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayer.mm create mode 100644 engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayerTest.mm diff --git a/engine/src/flutter/ci/licenses_golden/licenses_flutter b/engine/src/flutter/ci/licenses_golden/licenses_flutter index 0c24e1839e..268a248e75 100644 --- a/engine/src/flutter/ci/licenses_golden/licenses_flutter +++ b/engine/src/flutter/ci/licenses_golden/licenses_flutter @@ -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 diff --git a/engine/src/flutter/impeller/renderer/backend/metal/surface_mtl.mm b/engine/src/flutter/impeller/renderer/backend/metal/surface_mtl.mm index 1d73324e3f..dc7779bf33 100644 --- a/engine/src/flutter/impeller/renderer/backend/metal/surface_mtl.mm +++ b/engine/src/flutter/impeller/renderer/backend/metal/surface_mtl.mm @@ -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 drawable = drawable_; + [command_buffer addScheduledHandler:^(id buffer) { + [drawable present]; + }]; [command_buffer commit]; } } diff --git a/engine/src/flutter/shell/platform/darwin/ios/BUILD.gn b/engine/src/flutter/shell/platform/darwin/ios/BUILD.gn index bfcb4fcbb7..93356958a1 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/BUILD.gn +++ b/engine/src/flutter/shell/platform/darwin/ios/BUILD.gn @@ -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", diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayer.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayer.h new file mode 100644 index 0000000000..2538aaeac9 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayer.h @@ -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 + +/// 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 device; +@property(nullable, readonly) id preferredDevice; +@property MTLPixelFormat pixelFormat; +@property BOOL framebufferOnly; +@property CGSize drawableSize; +@property BOOL presentsWithTransaction; +@property(nullable) CGColorSpaceRef colorspace; +@property BOOL wantsExtendedDynamicRangeContent; + +- (nullable id)nextDrawable; + +/// Returns whether the Metal layer is enabled. +/// This is controlled by FLTUseFlutterMetalLayer value in Info.plist. ++ (BOOL)enabled; + +@end diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayer.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayer.mm new file mode 100644 index 0000000000..94d4c04e67 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayer.mm @@ -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 +#include +#include + +#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 _preferredDevice; + CGSize _drawableSize; + + NSUInteger _nextDrawableId; + + NSMutableSet* _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 _texture; + IOSurface* _surface; + CFTimeInterval _presentedTime; +} + +@property(readonly, nonatomic) id 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)texture surface:(IOSurface*)surface { + if (self = [super init]) { + _texture = texture; + _surface = surface; + } + return self; +} + +@end + +@interface FlutterDrawable : NSObject { + 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)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 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)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 diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayerTest.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayerTest.mm new file mode 100644 index 0000000000..1265fdd216 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterMetalLayerTest.mm @@ -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 +#import +#import + +#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 t1, t2, t3; + + id 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 t1, t2, t3; + + id 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 drawable = [layer nextDrawable]; + BAIL_IF_NO_DRAWABLE(drawable); + } + } + id texture; + { + @autoreleasepool { + id drawable = [layer nextDrawable]; + XCTAssertNotNil(drawable); + texture = (id)drawable.texture; + // Dropping the drawable must return texture to pool, so + // next drawable should return the same texture. + } + } + { + id drawable = [layer nextDrawable]; + XCTAssertEqual(texture, drawable.texture); + } + + [self removeMetalLayer:layer]; +} + +- (void)testLayerLimitsDrawableCount { + FlutterMetalLayer* layer = [self addMetalLayer]; + + id d1 = [layer nextDrawable]; + BAIL_IF_NO_DRAWABLE(d1); + id d2 = [layer nextDrawable]; + BAIL_IF_NO_DRAWABLE(d2); + id d3 = [layer nextDrawable]; + BAIL_IF_NO_DRAWABLE(d3); + XCTAssertNotNil(d3); + + // Layer should not return more than 3 drawables. + id d4 = [layer nextDrawable]; + XCTAssertNil(d4); + + [d1 present]; + + // Still no drawable, until the front buffer returns to pool + id d5 = [layer nextDrawable]; + XCTAssertNil(d5); + + [d2 present]; + id d6 = [layer nextDrawable]; + XCTAssertNotNil(d6); + + [self removeMetalLayer:layer]; +} + +@end diff --git a/engine/src/flutter/shell/platform/darwin/ios/rendering_api_selection.mm b/engine/src/flutter/shell/platform/darwin/ios/rendering_api_selection.mm index 73cf47abc5..f7b969066f 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/rendering_api_selection.mm +++ b/engine/src/flutter/shell/platform/darwin/ios/rendering_api_selection.mm @@ -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; diff --git a/engine/src/flutter/testing/ios/IosUnitTests/IosUnitTests.xcodeproj/project.pbxproj b/engine/src/flutter/testing/ios/IosUnitTests/IosUnitTests.xcodeproj/project.pbxproj index 4a85c39afb..e67b60cdfc 100644 --- a/engine/src/flutter/testing/ios/IosUnitTests/IosUnitTests.xcodeproj/project.pbxproj +++ b/engine/src/flutter/testing/ios/IosUnitTests/IosUnitTests.xcodeproj/project.pbxproj @@ -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 = ""; }; 0D6AB73E22BD8F0200EEE540 /* FlutterEngineConfig.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = FlutterEngineConfig.xcconfig; sourceTree = ""; }; + 3DD7D38C27D2B81000DA365C /* FlutterUndoManagerPluginTest.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = FlutterUndoManagerPluginTest.mm; sourceTree = ""; }; 689EC1E2281B30D3008FEB58 /* FlutterSpellCheckPluginTest.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = FlutterSpellCheckPluginTest.mm; sourceTree = ""; }; 68B6091227F62F990036AC78 /* VsyncWaiterIosTest.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = VsyncWaiterIosTest.mm; sourceTree = ""; }; - 3DD7D38C27D2B81000DA365C /* FlutterUndoManagerPluginTest.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = FlutterUndoManagerPluginTest.mm; sourceTree = ""; }; - 73F12C22288F92FF00AFC3A6 /* FlutterViewControllerTest_mrc.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = FlutterViewControllerTest_mrc.mm; sourceTree = ""; }; + 73F12C22288F92FF00AFC3A6 /* FlutterViewControllerTest_mrc.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = FlutterViewControllerTest_mrc.mm; sourceTree = ""; }; + D2D361A52B234EAC0018964E /* FlutterMetalLayerTest.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = FlutterMetalLayerTest.mm; sourceTree = ""; }; 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 = ""; }; F7521D7526BB673E005F15C5 /* libocmock_shared.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libocmock_shared.dylib; path = "../../../../out/$(FLUTTER_ENGINE)/libocmock_shared.dylib"; sourceTree = ""; }; F77E081726FA9CE6003E6E4C /* Flutter.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Flutter.framework; path = "../../../../out/$(FLUTTER_ENGINE)/Flutter.framework"; sourceTree = ""; }; @@ -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;