From 88185e0b3e7f7e1a58d528a994c5d5cb54353453 Mon Sep 17 00:00:00 2001 From: Chris Bracken Date: Fri, 8 Nov 2024 12:55:23 -0800 Subject: [PATCH] fml: Use CFRef where possible and add docs (flutter/engine#56436) Document where CFRef takes over or hands back ownership of the underlying CoreFoundation object memory. Migrates manual CoreFoundation object management to CFRef in: * impeller/golden_tests/metal_screenshot.mm * shell/platform/darwin/graphics/FlutterDarwinContextMetalSkia.mm * shell/platform/darwin/graphics/FlutterDarwinExternalTextureMetal.mm * shell/platform/darwin/ios/framework/Source/FlutterView.mm * shell/platform/darwin/macos/framework/Source/FlutterSurface.mm Adds a `Retain()` method to take shared ownership of the underlying object, as opposed to Reset, where ownership is transferred to the CFRef wrapper. Adds a `Get()` method to make dealing with bridged Objective-C casts more convenient: ```objc fml::CFRef cfString(...); NSString* aString = (__bridge NSString*)cfString.Get(); ``` as opposed to: ```objc fml::CFRef cfString(...); NSString* aString = (__bridge NSString*)static_cast(cfString); ``` I considered making use of `fml::scoped_policy::OwnershipPolicy` to add a second parameter to the ctor and `Reset` but, but I think documentation and addition of a `Retain()` method makes things a little clearer at the call site. It's also more consistent with `sk_cfp`, which we use in some Skia bits of the codebase. [C++, Objective-C, Java style guides]: https://github.com/flutter/engine/blob/main/CONTRIBUTING.md#style --- .../flutter/fml/platform/darwin/cf_utils.h | 66 ++++++++++++++++--- .../fml/platform/darwin/cf_utils_unittests.mm | 23 +++++++ .../flutter/impeller/golden_tests/BUILD.gn | 1 + .../impeller/golden_tests/metal_screenshot.h | 17 ++++- .../impeller/golden_tests/metal_screenshot.mm | 15 ++--- .../graphics/FlutterDarwinContextMetalSkia.mm | 37 ++++++----- .../FlutterDarwinExternalTextureMetal.mm | 18 +++-- .../ios/framework/Source/FlutterView.mm | 5 +- .../macos/framework/Source/FlutterSurface.mm | 10 ++- .../Source/FlutterViewControllerTest.mm | 8 +-- 10 files changed, 141 insertions(+), 59 deletions(-) diff --git a/engine/src/flutter/fml/platform/darwin/cf_utils.h b/engine/src/flutter/fml/platform/darwin/cf_utils.h index 02fd3229d7..8a1773d3d4 100644 --- a/engine/src/flutter/fml/platform/darwin/cf_utils.h +++ b/engine/src/flutter/fml/platform/darwin/cf_utils.h @@ -11,53 +11,103 @@ namespace fml { +/// Default retain and release implementations for CFRef. +template +struct CFRefTraits { + static void Retain(T instance) { CFRetain(instance); } + static void Release(T instance) { CFRelease(instance); } +}; + +/// RAII-based smart pointer wrapper for CoreFoundation objects. +/// +/// CFRef takes over ownership of the object it wraps and ensures that retain +/// and release are called as appropriate on creation, assignment, and disposal. template class CFRef { public: + /// Creates a new null CFRef. CFRef() : instance_(nullptr) {} - // NOLINTNEXTLINE(google-explicit-constructor) - CFRef(T instance) : instance_(instance) {} + /// Takes over ownership of `instance`, which is expected to be already + /// retained. + explicit CFRef(T instance) : instance_(instance) {} + /// Copy ctor: Creates a retained copy of the CoreFoundation object owned by + /// `other`. CFRef(const CFRef& other) : instance_(other.instance_) { if (instance_) { - CFRetain(instance_); + CFRefTraits::Retain(instance_); } } + /// Move ctor: Takes over ownership of the CoreFoundation object owned + /// by `other`. The object owned by `other` is set to null. CFRef(CFRef&& other) : instance_(other.instance_) { other.instance_ = nullptr; } + /// Takes over ownership of the CoreFoundation object owned by `other`. CFRef& operator=(CFRef&& other) { Reset(other.Release()); return *this; } + /// Releases the underlying CoreFoundation object, if non-null. ~CFRef() { - if (instance_ != nullptr) { - CFRelease(instance_); + if (instance_) { + CFRefTraits::Release(instance_); } instance_ = nullptr; } + /// Takes over ownership of `instance`, null by default. The object is + /// expected to be already retained if non-null. + /// + /// Releases the previous object, if non-null. void Reset(T instance = nullptr) { - if (instance_ != nullptr) { - CFRelease(instance_); + if (instance_) { + CFRefTraits::Release(instance_); } - instance_ = instance; } + /// Retains a shared copy of `instance`. The previous object is released if + /// non-null. Has no effect if `instance` is the currently-held object. + void Retain(T instance = nullptr) { + if (instance_ == instance) { + return; + } + if (instance) { + CFRefTraits::Retain(instance); + } + Reset(instance); + } + + /// Returns and transfers ownership of the underlying CoreFoundation object + /// to the caller. The caller is responsible for calling `CFRelease` when done + /// with the object. [[nodiscard]] T Release() { auto instance = instance_; instance_ = nullptr; return instance; } + /// Returns the underlying CoreFoundation object. Ownership of the returned + /// object follows The Get Rule. + /// + /// See: + /// https://developer.apple.com/library/archive/documentation/CoreFoundation/Conceptual/CFMemoryMgmt/Concepts/Ownership.html#//apple_ref/doc/uid/20001148-SW1 + T Get() const { return instance_; } + + /// Returns the underlying CoreFoundation object. Ownership of the returned + /// object follows The Get Rule. + /// + /// See: + /// https://developer.apple.com/library/archive/documentation/CoreFoundation/Conceptual/CFMemoryMgmt/Concepts/Ownership.html#//apple_ref/doc/uid/20001148-SW1 // NOLINTNEXTLINE(google-explicit-constructor) operator T() const { return instance_; } + /// Returns true if the underlying CoreFoundation object is non-null. explicit operator bool() const { return instance_ != nullptr; } private: diff --git a/engine/src/flutter/fml/platform/darwin/cf_utils_unittests.mm b/engine/src/flutter/fml/platform/darwin/cf_utils_unittests.mm index 902850d03e..2128d72554 100644 --- a/engine/src/flutter/fml/platform/darwin/cf_utils_unittests.mm +++ b/engine/src/flutter/fml/platform/darwin/cf_utils_unittests.mm @@ -60,5 +60,28 @@ TEST(CFTest, CanCreateRefs) { } } +TEST(CFTest, GetReturnsUnderlyingObject) { + CFMutableStringRef cf_string = CFStringCreateMutable(kCFAllocatorDefault, 100u); + const CFIndex ref_count_before = CFGetRetainCount(cf_string); + CFRef string_ref(cf_string); + + CFMutableStringRef returned_string = string_ref.Get(); + const CFIndex ref_count_after = CFGetRetainCount(cf_string); + EXPECT_EQ(cf_string, returned_string); + EXPECT_EQ(ref_count_before, ref_count_after); +} + +TEST(CFTest, RetainSharesOwnership) { + CFMutableStringRef cf_string = CFStringCreateMutable(kCFAllocatorDefault, 100u); + const CFIndex ref_count_before = CFGetRetainCount(cf_string); + + CFRef string_ref; + string_ref.Retain(cf_string); + const CFIndex ref_count_after = CFGetRetainCount(cf_string); + + EXPECT_EQ(cf_string, string_ref); + EXPECT_EQ(ref_count_before + 1u, ref_count_after); +} + } // namespace testing } // namespace fml diff --git a/engine/src/flutter/impeller/golden_tests/BUILD.gn b/engine/src/flutter/impeller/golden_tests/BUILD.gn index 2149a522e7..c58591baac 100644 --- a/engine/src/flutter/impeller/golden_tests/BUILD.gn +++ b/engine/src/flutter/impeller/golden_tests/BUILD.gn @@ -67,6 +67,7 @@ if (is_mac) { deps = [ ":screenshot", "//flutter/display_list", + "//flutter/fml", "//flutter/impeller/display_list", "//flutter/impeller/playground", "//flutter/impeller/renderer/backend/metal:metal", diff --git a/engine/src/flutter/impeller/golden_tests/metal_screenshot.h b/engine/src/flutter/impeller/golden_tests/metal_screenshot.h index becd4b4230..3e0cbb2135 100644 --- a/engine/src/flutter/impeller/golden_tests/metal_screenshot.h +++ b/engine/src/flutter/impeller/golden_tests/metal_screenshot.h @@ -11,6 +11,19 @@ #include #include +#include "flutter/fml/platform/darwin/cf_utils.h" + +namespace fml { + +/// Default retain and release implementations for CGImageRef. +template <> +struct CFRefTraits { + static void Retain(CGImageRef instance) { CGImageRetain(instance); } + static void Release(CGImageRef instance) { CGImageRelease(instance); } +}; + +} // namespace fml + namespace impeller { namespace testing { @@ -35,8 +48,8 @@ class MetalScreenshot : public Screenshot { MetalScreenshot(const MetalScreenshot&) = delete; MetalScreenshot& operator=(const MetalScreenshot&) = delete; - CGImageRef cg_image_; - CFDataRef pixel_data_; + fml::CFRef cg_image_; + fml::CFRef pixel_data_; }; } // namespace testing } // namespace impeller diff --git a/engine/src/flutter/impeller/golden_tests/metal_screenshot.mm b/engine/src/flutter/impeller/golden_tests/metal_screenshot.mm index fd7ab0c083..7062372e74 100644 --- a/engine/src/flutter/impeller/golden_tests/metal_screenshot.mm +++ b/engine/src/flutter/impeller/golden_tests/metal_screenshot.mm @@ -9,13 +9,10 @@ namespace testing { MetalScreenshot::MetalScreenshot(CGImageRef cgImage) : cg_image_(cgImage) { CGDataProviderRef data_provider = CGImageGetDataProvider(cgImage); - pixel_data_ = CGDataProviderCopyData(data_provider); + pixel_data_.Reset(CGDataProviderCopyData(data_provider)); } -MetalScreenshot::~MetalScreenshot() { - CFRelease(pixel_data_); - CGImageRelease(cg_image_); -} +MetalScreenshot::~MetalScreenshot() = default; const uint8_t* MetalScreenshot::GetBytes() const { return CFDataGetBytePtr(pixel_data_); @@ -37,17 +34,15 @@ bool MetalScreenshot::WriteToPNG(const std::string& path) const { bool result = false; NSURL* output_url = [NSURL fileURLWithPath:[NSString stringWithUTF8String:path.c_str()]]; - CGImageDestinationRef destination = CGImageDestinationCreateWithURL( - (__bridge CFURLRef)output_url, kUTTypePNG, 1, nullptr); - if (destination != nullptr) { + fml::CFRef destination(CGImageDestinationCreateWithURL( + (__bridge CFURLRef)output_url, kUTTypePNG, 1, nullptr)); + if (destination) { CGImageDestinationAddImage(destination, cg_image_, (__bridge CFDictionaryRef) @{}); if (CGImageDestinationFinalize(destination)) { result = true; } - - CFRelease(destination); } return result; } diff --git a/engine/src/flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalSkia.mm b/engine/src/flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalSkia.mm index 6998861091..16642cd154 100644 --- a/engine/src/flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalSkia.mm +++ b/engine/src/flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalSkia.mm @@ -8,6 +8,7 @@ #include "flutter/common/graphics/persistent_cache.h" #include "flutter/fml/logging.h" +#include "flutter/fml/platform/darwin/cf_utils.h" #include "flutter/shell/common/context_options.h" #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" #include "third_party/skia/include/gpu/ganesh/GrDirectContext.h" @@ -16,7 +17,9 @@ FLUTTER_ASSERT_ARC -@implementation FlutterDarwinContextMetalSkia +@implementation FlutterDarwinContextMetalSkia { + fml::CFRef _textureCache; +} - (instancetype)initWithDefaultMTLDevice { id device = MTLCreateSystemDefaultDevice(); @@ -43,15 +46,19 @@ FLUTTER_ASSERT_ARC [_commandQueue setLabel:@"Flutter Main Queue"]; - CVReturn cvReturn = CVMetalTextureCacheCreate(kCFAllocatorDefault, // allocator - nil, // cache attributes (nil default) - _device, // metal device - nil, // texture attributes (nil default) - &_textureCache // [out] cache - ); - if (cvReturn != kCVReturnSuccess) { - FML_DLOG(ERROR) << "Could not create Metal texture cache."; - return nil; + { + CVMetalTextureCacheRef cache = nullptr; + CVReturn cvReturn = CVMetalTextureCacheCreate(kCFAllocatorDefault, // allocator + nil, // cache attributes (nil default) + _device, // metal device + nil, // texture attributes (nil default) + &cache // [out] cache + ); + _textureCache.Reset(cache); + if (cvReturn != kCVReturnSuccess) { + FML_DLOG(ERROR) << "Could not create Metal texture cache."; + return nil; + } } // The devices are in the same "sharegroup" because they share the same device and command @@ -96,12 +103,6 @@ FLUTTER_ASSERT_ARC return GrDirectContexts::MakeMetal(backendContext, contextOptions); } -- (void)dealloc { - if (_textureCache) { - CFRelease(_textureCache); - } -} - - (FlutterDarwinExternalTextureMetal*) createExternalTextureWithIdentifier:(int64_t)textureID texture:(NSObject*)texture { @@ -111,6 +112,10 @@ FLUTTER_ASSERT_ARC enableImpeller:NO]; } +- (CVMetalTextureCacheRef)textureCache { + return _textureCache; +} + @end #endif // !SLIMPELLER diff --git a/engine/src/flutter/shell/platform/darwin/graphics/FlutterDarwinExternalTextureMetal.mm b/engine/src/flutter/shell/platform/darwin/graphics/FlutterDarwinExternalTextureMetal.mm index 5938458018..580443d409 100644 --- a/engine/src/flutter/shell/platform/darwin/graphics/FlutterDarwinExternalTextureMetal.mm +++ b/engine/src/flutter/shell/platform/darwin/graphics/FlutterDarwinExternalTextureMetal.mm @@ -3,7 +3,9 @@ // found in the LICENSE file. #import "flutter/shell/platform/darwin/graphics/FlutterDarwinExternalTextureMetal.h" + #include "flutter/display_list/image/dl_image.h" +#include "flutter/fml/platform/darwin/cf_utils.h" #include "impeller/base/validation.h" #include "impeller/display_list/aiks_context.h" #include "impeller/display_list/dl_image_impeller.h" @@ -23,7 +25,7 @@ FLUTTER_ASSERT_ARC @implementation FlutterDarwinExternalTextureMetal { - CVMetalTextureCacheRef _textureCache; + fml::CFRef _textureCache; NSObject* _externalTexture; BOOL _textureFrameAvailable; sk_sp _externalImage; @@ -37,8 +39,7 @@ FLUTTER_ASSERT_ARC texture:(NSObject*)texture enableImpeller:(BOOL)enableImpeller { if (self = [super init]) { - _textureCache = textureCache; - CFRetain(_textureCache); + _textureCache.Retain(textureCache); _textureID = textureID; _externalTexture = texture; _enableImpeller = enableImpeller; @@ -50,10 +51,7 @@ FLUTTER_ASSERT_ARC - (void)dealloc { CVPixelBufferRelease(_lastPixelBuffer); if (_textureCache) { - CVMetalTextureCacheFlush(_textureCache, // cache - 0 // options (must be zero) - ); - CFRelease(_textureCache); + CVMetalTextureCacheFlush(_textureCache, /* options (must be zero) */ 0); } } @@ -107,9 +105,9 @@ FLUTTER_ASSERT_ARC // buffer will be used to materialize the image in case the application fails to provide a new // one. _externalImage.reset(); - CVMetalTextureCacheFlush(_textureCache, // cache - 0 // options (must be zero) - ); + if (_textureCache) { + CVMetalTextureCacheFlush(_textureCache, /* options (must be zero) */ 0); + } } - (void)markNewFrameAvailable { diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterView.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterView.mm index 137b1f712d..1f26954009 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterView.mm +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterView.mm @@ -3,9 +3,9 @@ // found in the LICENSE file. #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h" -#import "flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.h" #include "flutter/fml/platform/darwin/cf_utils.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.h" FLUTTER_ASSERT_ARC @@ -107,9 +107,8 @@ static void PrintWideGamutWarningOnce() { layer.framebufferOnly = flutter::Settings::kSurfaceDataAccessible ? NO : YES; BOOL isWideGamutSupported = self.isWideGamutSupported; if (_isWideGamutEnabled && isWideGamutSupported) { - CGColorSpaceRef srgb = CGColorSpaceCreateWithName(kCGColorSpaceExtendedSRGB); + fml::CFRef srgb(CGColorSpaceCreateWithName(kCGColorSpaceExtendedSRGB)); layer.colorspace = srgb; - CFRelease(srgb); layer.pixelFormat = MTLPixelFormatBGRA10_XR; } else if (_isWideGamutEnabled && !isWideGamutSupported) { PrintWideGamutWarningOnce(); diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterSurface.mm b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterSurface.mm index f61f81c5bf..d2726560d7 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterSurface.mm +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterSurface.mm @@ -6,9 +6,11 @@ #import +#import "flutter/fml/platform/darwin/cf_utils.h" + @interface FlutterSurface () { CGSize _size; - IOSurfaceRef _ioSurface; + fml::CFRef _ioSurface; id _texture; // Used for testing. BOOL _isInUseOverride; @@ -44,7 +46,7 @@ - (instancetype)initWithSize:(CGSize)size device:(id)device { if (self = [super init]) { self->_size = size; - self->_ioSurface = [FlutterSurface createIOSurfaceWithSize:size]; + self->_ioSurface.Reset([FlutterSurface createIOSurfaceWithSize:size]); self->_texture = [FlutterSurface createTextureForIOSurface:_ioSurface size:size device:device]; } return self; @@ -71,10 +73,6 @@ static void ReleaseSurface(void* surface) { return (__bridge FlutterSurface*)texture->user_data; } -- (void)dealloc { - CFRelease(_ioSurface); -} - + (IOSurfaceRef)createIOSurfaceWithSize:(CGSize)size { unsigned pixelFormat = 'BGRA'; unsigned bytesPerElement = 4; diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTest.mm b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTest.mm index 2316c8c8a0..cc03fc5c69 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTest.mm +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTest.mm @@ -1023,14 +1023,14 @@ TEST_F(FlutterViewControllerTest, testViewControllerIsReleased) { // Test for pan events. // Start gesture. - fml::CFRef cgEventStart = - CGEventCreateScrollWheelEvent(NULL, kCGScrollEventUnitPixel, 1, 0); + fml::CFRef cgEventStart( + CGEventCreateScrollWheelEvent(NULL, kCGScrollEventUnitPixel, 1, 0)); CGEventSetType(cgEventStart, kCGEventScrollWheel); CGEventSetIntegerValueField(cgEventStart, kCGScrollWheelEventScrollPhase, kCGScrollPhaseBegan); CGEventSetIntegerValueField(cgEventStart, kCGScrollWheelEventIsContinuous, 1); [viewController scrollWheel:[NSEvent eventWithCGEvent:cgEventStart]]; - fml::CFRef cgEventUpdate = CGEventCreateCopy(cgEventStart); + fml::CFRef cgEventUpdate(CGEventCreateCopy(cgEventStart)); CGEventSetIntegerValueField(cgEventUpdate, kCGScrollWheelEventScrollPhase, kCGScrollPhaseChanged); CGEventSetIntegerValueField(cgEventUpdate, kCGScrollWheelEventDeltaAxis2, 1); // pan_x CGEventSetIntegerValueField(cgEventUpdate, kCGScrollWheelEventDeltaAxis1, 2); // pan_y @@ -1041,7 +1041,7 @@ TEST_F(FlutterViewControllerTest, testViewControllerIsReleased) { [viewController mouseExited:mouseEvent]; // End gesture. - fml::CFRef cgEventEnd = CGEventCreateCopy(cgEventStart); + fml::CFRef cgEventEnd(CGEventCreateCopy(cgEventStart)); CGEventSetIntegerValueField(cgEventEnd, kCGScrollWheelEventScrollPhase, kCGScrollPhaseEnded); [viewController scrollWheel:[NSEvent eventWithCGEvent:cgEventEnd]];