From e4ed8ffcd87810a04db9c64a304c2378e026c09f Mon Sep 17 00:00:00 2001 From: Yegor Date: Thu, 27 May 2021 13:58:41 -0700 Subject: [PATCH] Reclaim paragraph memory more aggressively (flutter/engine#26438) * delete paragraphs between layout and render --- .../lib/src/engine/canvaskit/canvas.dart | 2 + .../src/engine/canvaskit/canvaskit_api.dart | 2 +- .../engine/canvaskit/skia_object_cache.dart | 83 ++++++- .../web_ui/lib/src/engine/canvaskit/text.dart | 232 ++++++++++++------ .../canvaskit/skia_objects_cache_test.dart | 155 ++++++++++-- 5 files changed, 377 insertions(+), 97 deletions(-) diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/canvas.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/canvas.dart index 4b9890db30..7e55dc206b 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/canvas.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/canvas.dart @@ -209,6 +209,7 @@ class CkCanvas { offset.dx, offset.dy, ); + paragraph.markUsed(); } void drawPath(CkPath path, CkPaint paint) { @@ -1088,6 +1089,7 @@ class CkDrawParagraphCommand extends CkPaintCommand { offset.dx, offset.dy, ); + paragraph.markUsed(); } } diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/canvaskit_api.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/canvaskit_api.dart index 0a840eac3e..481adf4f0e 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/canvaskit_api.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/canvaskit_api.dart @@ -1786,7 +1786,7 @@ class SkParagraph { SkRectHeightStyle heightStyle, SkRectWidthStyle widthStyle, ); - external List getRectsForPlaceholders(); + external List getRectsForPlaceholders(); external SkTextPosition getGlyphPositionAtCoordinate( double x, double y, diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/skia_object_cache.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/skia_object_cache.dart index 53e1eebe66..33b2193496 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/skia_object_cache.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/skia_object_cache.dart @@ -87,6 +87,85 @@ class SkiaObjectCache { } } +/// Like [SkiaObjectCache] but enforces the [maximumSize] of the cache +/// synchronously instead of waiting until a post-frame callback. +class SynchronousSkiaObjectCache { + /// This cache will never exceed this limit, even temporarily. + final int maximumSize; + + /// A doubly linked list of the objects in the cache. + /// + /// This makes it fast to move a recently used object to the front. + final DoubleLinkedQueue _itemQueue; + + /// A map of objects to their associated node in the [_itemQueue]. + /// + /// This makes it fast to find the node in the queue when we need to + /// move the object to the front of the queue. + final Map> _itemMap; + + SynchronousSkiaObjectCache(this.maximumSize) + : _itemQueue = DoubleLinkedQueue(), + _itemMap = >{}; + + /// The number of objects in the cache. + int get length => _itemQueue.length; + + /// Whether or not [object] is in the cache. + /// + /// This is only for testing. + @visibleForTesting + bool debugContains(SkiaObject object) { + return _itemMap.containsKey(object); + } + + /// Adds [object] to the cache. + /// + /// If adding [object] causes the total size of the cache to exceed + /// [maximumSize], then the least recently used objects are evicted and + /// deleted. + void add(SkiaObject object) { + assert( + !_itemMap.containsKey(object), + 'Cannot add object. Object is already in the cache: $object', + ); + _itemQueue.addFirst(object); + _itemMap[object] = _itemQueue.firstEntry()!; + _enforceCacheLimit(); + } + + /// Marks the [object] as most recently used. + /// + /// If [object] is in the cache returns true. If the object is not in + /// the cache, for example, because it was never added or because it was + /// evicted as a result of the app reaching the cache limit, returns false. + bool markUsed(SkiaObject object) { + final DoubleLinkedQueueEntry? item = _itemMap[object]; + + if (item == null) { + return false; + } + + item.remove(); + _itemQueue.addFirst(object); + _itemMap[object] = _itemQueue.firstEntry()!; + return true; + } + + /// Ensures the cache does not exceed [maximumSize], evicting objects if + /// necessary. + /// + /// Calls `delete` and `didDelete` on objects evicted from the cache. + void _enforceCacheLimit() { + while (_itemQueue.length > maximumSize) { + final SkiaObject oldObject = _itemQueue.removeLast(); + _itemMap.remove(oldObject); + oldObject.delete(); + oldObject.didDelete(); + } + } +} + /// An object backed by a JavaScript object mapped onto a Skia C++ object in the /// WebAssembly heap. /// @@ -304,13 +383,13 @@ class SkiaObjectBox /// If asserts are enabled, the [StackTrace]s representing when a reference /// was created. - List? debugGetStackTraces() { + List debugGetStackTraces() { if (assertionsEnabled) { return debugReferrers .map((R referrer) => referrer.debugStackTrace) .toList(); } - return null; + throw UnsupportedError(''); } /// The Skia object whose lifecycle is being managed. diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/text.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/text.dart index 3ff176329f..a274341d55 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/text.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/canvaskit/text.dart @@ -524,15 +524,25 @@ SkFontStyle toSkFontStyle(ui.FontWeight? fontWeight, ui.FontStyle? fontStyle) { return style; } -class CkParagraph extends ManagedSkiaObject - implements ui.Paragraph { +/// The CanvasKit implementation of [ui.Paragraph]. +/// +/// This class does not use [ManagedSkiaObject] because it requires that its +/// memory is reclaimed synchronously. This protects our memory usage from +/// blowing up if within a single frame the framework needs to layout a lot of +/// paragraphs. One common use-case is `ListView.builder`, which needs to layout +/// more of its content than it actually renders to compute the scroll position. +/// More generally, this protects from the pattern of laying out a lot of text +/// while painting a small subset of it. To achieve this a +/// [SynchronousSkiaObjectCache] is used that limits the number of live laid out +/// paragraphs at any point in time within or outside the frame. +class CkParagraph extends SkiaObject implements ui.Paragraph { CkParagraph( - this._initialParagraph, this._paragraphStyle, this._paragraphCommands); + this._skParagraph, this._paragraphStyle, this._paragraphCommands); /// The result of calling `build()` on the JS CkParagraphBuilder. /// /// This may be invalidated later. - final SkParagraph _initialParagraph; + SkParagraph? _skParagraph; /// The paragraph style used to build this paragraph. /// @@ -553,75 +563,139 @@ class CkParagraph extends ManagedSkiaObject ui.ParagraphConstraints? _lastLayoutConstraints; @override - SkParagraph createDefault() => _initialParagraph; + SkParagraph get skiaObject => _ensureInitialized(_lastLayoutConstraints!); - @override - SkParagraph resurrect() { - final builder = CkParagraphBuilder(_paragraphStyle); - for (_ParagraphCommand command in _paragraphCommands) { - switch (command.type) { - case _ParagraphCommandType.addText: - builder.addText(command.text!); - break; - case _ParagraphCommandType.pop: - builder.pop(); - break; - case _ParagraphCommandType.pushStyle: - builder.pushStyle(command.style!); - break; - case _ParagraphCommandType.addPlaceholder: - builder._addPlaceholder(command.placeholderStyle!); - break; + SkParagraph _ensureInitialized(ui.ParagraphConstraints constraints) { + SkParagraph? paragraph = _skParagraph; + + // Paragraph objects are immutable. It's OK to skip initialization and reuse + // existing object. + bool didRebuildSkiaObject = false; + if (paragraph == null) { + final builder = CkParagraphBuilder(_paragraphStyle); + for (_ParagraphCommand command in _paragraphCommands) { + switch (command.type) { + case _ParagraphCommandType.addText: + builder.addText(command.text!); + break; + case _ParagraphCommandType.pop: + builder.pop(); + break; + case _ParagraphCommandType.pushStyle: + builder.pushStyle(command.style!); + break; + case _ParagraphCommandType.addPlaceholder: + builder._addPlaceholder(command.placeholderStyle!); + break; + } + } + paragraph = builder._buildSkParagraph(); + _skParagraph = paragraph; + didRebuildSkiaObject = true; + } + + final bool constraintsChanged = _lastLayoutConstraints != constraints; + if (didRebuildSkiaObject || constraintsChanged) { + _lastLayoutConstraints = constraints; + // TODO(het): CanvasKit throws an exception when laid out with + // a font that wasn't registered. + try { + paragraph.layout(constraints.width); + _alphabeticBaseline = paragraph.getAlphabeticBaseline(); + _didExceedMaxLines = paragraph.didExceedMaxLines(); + _height = paragraph.getHeight(); + _ideographicBaseline = paragraph.getIdeographicBaseline(); + _longestLine = paragraph.getLongestLine(); + _maxIntrinsicWidth = paragraph.getMaxIntrinsicWidth(); + _minIntrinsicWidth = paragraph.getMinIntrinsicWidth(); + _width = paragraph.getMaxWidth(); + _boxesForPlaceholders = skRectsToTextBoxes(paragraph.getRectsForPlaceholders()); + } catch (e) { + printWarning('CanvasKit threw an exception while laying ' + 'out the paragraph. The font was "${_paragraphStyle._fontFamily}". ' + 'Exception:\n$e'); + rethrow; } } - final SkParagraph result = builder._buildCkParagraph(); - if (_lastLayoutConstraints != null) { - // We need to set the Skia object early so layout works. - rawSkiaObject = result; - this.layout(_lastLayoutConstraints!); + return paragraph; + } + + // Caches laid out paragraphs and synchronously reclaims memory if there's + // memory pressure. + // + // On May 26, 2021, 500 seemed like a reasonable number to pick for the cache + // size. At the time a single laid out SkParagraph used 100KB of memory. So, + // 500 items in the cache is roughly 50MB of memory, which is not too high, + // while at the same time enough for most use-cases. + // + // TODO(yjbanov): this strategy is not sufficient for the use-case where a + // lot of paragraphs are laid out _and_ rendered. To support + // this use-case without blowing up memory usage we need this: + // https://github.com/flutter/flutter/issues/81224 + static SynchronousSkiaObjectCache _paragraphCache = SynchronousSkiaObjectCache(500); + + /// Marks this paragraph as having been used this frame. + /// + /// Puts this paragraph in a [SynchronousSkiaObjectCache], which will delete it + /// if there's memory pressure to do so. This protects our memory usage from + /// blowing up if within a single frame the framework needs to layout a lot of + /// paragraphs. One common use-case is `ListView.builder`, which needs to layout + /// more of its content than it actually renders to compute the scroll position. + void markUsed() { + // If the paragraph is already in the cache, just mark it as most recently + // used. Otherwise, add to cache. + if (!_paragraphCache.markUsed(this)) { + _paragraphCache.add(this); } - return result; } @override void delete() { - rawSkiaObject?.delete(); + _skParagraph!.delete(); } @override - bool get isResurrectionExpensive => true; - - @override - double get alphabeticBaseline => skiaObject.getAlphabeticBaseline(); - - @override - bool get didExceedMaxLines => skiaObject.didExceedMaxLines(); - - @override - double get height => skiaObject.getHeight(); - - @override - double get ideographicBaseline => skiaObject.getIdeographicBaseline(); - - @override - double get longestLine => skiaObject.getLongestLine(); - - @override - double get maxIntrinsicWidth => skiaObject.getMaxIntrinsicWidth(); - - @override - double get minIntrinsicWidth => skiaObject.getMinIntrinsicWidth(); - - @override - double get width => skiaObject.getMaxWidth(); - - @override - List getBoxesForPlaceholders() { - List> skRects = skiaObject.getRectsForPlaceholders(); - return skRectsToTextBoxes(skRects); + void didDelete() { + _skParagraph = null; } + @override + double get alphabeticBaseline => _alphabeticBaseline; + double _alphabeticBaseline = 0; + + @override + bool get didExceedMaxLines => _didExceedMaxLines; + bool _didExceedMaxLines = false; + + @override + double get height => _height; + double _height = 0; + + @override + double get ideographicBaseline => _ideographicBaseline; + double _ideographicBaseline = 0; + + @override + double get longestLine => _longestLine; + double _longestLine = 0; + + @override + double get maxIntrinsicWidth => _maxIntrinsicWidth; + double _maxIntrinsicWidth = 0; + + @override + double get minIntrinsicWidth => _minIntrinsicWidth; + double _minIntrinsicWidth = 0; + + @override + double get width => _width; + double _width = 0; + + @override + List getBoxesForPlaceholders() => _boxesForPlaceholders!; + List? _boxesForPlaceholders; + @override List getBoxesForRange( int start, @@ -633,7 +707,8 @@ class CkParagraph extends ManagedSkiaObject return const []; } - List> skRects = skiaObject.getRectsForRange( + final SkParagraph paragraph = _ensureInitialized(_lastLayoutConstraints!); + final List> skRects = paragraph.getRectsForRange( start, end, toSkRectHeightStyle(boxHeightStyle), @@ -643,7 +718,7 @@ class CkParagraph extends ManagedSkiaObject return skRectsToTextBoxes(skRects); } - List skRectsToTextBoxes(List> skRects) { + List skRectsToTextBoxes(List skRects) { List result = []; for (int i = 0; i < skRects.length; i++) { @@ -662,8 +737,9 @@ class CkParagraph extends ManagedSkiaObject @override ui.TextPosition getPositionForOffset(ui.Offset offset) { + final SkParagraph paragraph = _ensureInitialized(_lastLayoutConstraints!); final SkTextPosition positionWithAffinity = - skiaObject.getGlyphPositionAtCoordinate( + paragraph.getGlyphPositionAtCoordinate( offset.dx, offset.dy, ); @@ -672,29 +748,27 @@ class CkParagraph extends ManagedSkiaObject @override ui.TextRange getWordBoundary(ui.TextPosition position) { - final SkTextRange skRange = skiaObject.getWordBoundary(position.offset); + final SkParagraph paragraph = _ensureInitialized(_lastLayoutConstraints!); + final SkTextRange skRange = paragraph.getWordBoundary(position.offset); return ui.TextRange(start: skRange.start, end: skRange.end); } @override void layout(ui.ParagraphConstraints constraints) { - _lastLayoutConstraints = constraints; - - // TODO(het): CanvasKit throws an exception when laid out with - // a font that wasn't registered. - try { - skiaObject.layout(constraints.width); - } catch (e) { - printWarning('CanvasKit threw an exception while laying ' - 'out the paragraph. The font was "${_paragraphStyle._fontFamily}". ' - 'Exception:\n$e'); - rethrow; + if (_lastLayoutConstraints == constraints) { + return; } + _ensureInitialized(constraints); + + // See class-level and _paragraphCache doc comments for why we're releasing + // the paragraph immediately after layout. + markUsed(); } @override ui.TextRange getLineBoundary(ui.TextPosition position) { - final List metrics = skiaObject.getLineMetrics(); + final SkParagraph paragraph = _ensureInitialized(_lastLayoutConstraints!); + final List metrics = paragraph.getLineMetrics(); final int offset = position.offset; for (final SkLineMetrics metric in metrics) { if (offset >= metric.startIndex && offset <= metric.endIndex) { @@ -706,7 +780,8 @@ class CkParagraph extends ManagedSkiaObject @override List computeLineMetrics() { - final List skLineMetrics = skiaObject.getLineMetrics(); + final SkParagraph paragraph = _ensureInitialized(_lastLayoutConstraints!); + final List skLineMetrics = paragraph.getLineMetrics(); final List result = []; for (final SkLineMetrics metric in skLineMetrics) { result.add(CkLineMetrics._(metric)); @@ -997,15 +1072,14 @@ class CkParagraphBuilder implements ui.ParagraphBuilder { _commands.add(_ParagraphCommand.addText(text)); _paragraphBuilder.addText(text); } - @override CkParagraph build() { - final builtParagraph = _buildCkParagraph(); + final builtParagraph = _buildSkParagraph(); return CkParagraph(builtParagraph, _style, _commands); } /// Builds the CkParagraph with the builder and deletes the builder. - SkParagraph _buildCkParagraph() { + SkParagraph _buildSkParagraph() { final SkParagraph result = _paragraphBuilder.build(); _paragraphBuilder.delete(); return result; diff --git a/engine/src/flutter/lib/web_ui/test/canvaskit/skia_objects_cache_test.dart b/engine/src/flutter/lib/web_ui/test/canvaskit/skia_objects_cache_test.dart index 2845c062b4..e386064cf0 100644 --- a/engine/src/flutter/lib/web_ui/test/canvaskit/skia_objects_cache_test.dart +++ b/engine/src/flutter/lib/web_ui/test/canvaskit/skia_objects_cache_test.dart @@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// @dart = 2.6 +// @dart = 2.12 -import 'package:mockito/mockito.dart'; import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; +import 'package:ui/ui.dart'; import '../matchers.dart'; import 'common.dart'; @@ -37,13 +37,8 @@ void _tests() { group(ManagedSkiaObject, () { test('implements create, cache, delete, resurrect, delete lifecycle', () { - int addPostFrameCallbackCount = 0; - - MockRasterizer mockRasterizer = MockRasterizer(); - when(mockRasterizer.addPostFrameCallback(any)).thenAnswer((_) { - addPostFrameCallbackCount++; - }); - EnginePlatformDispatcher.instance.rasterizer = mockRasterizer; + FakeRasterizer fakeRasterizer = FakeRasterizer(); + EnginePlatformDispatcher.instance.rasterizer = fakeRasterizer; // Trigger first create final TestSkiaObject testObject = TestSkiaObject(); @@ -63,7 +58,7 @@ void _tests() { // Trigger first delete SkiaObjects.postFrameCleanUp(); expect(SkiaObjects.resurrectableObjects, isEmpty); - expect(addPostFrameCallbackCount, 1); + expect(fakeRasterizer.addPostFrameCallbackCount, 1); expect(testObject.createDefaultCount, 1); expect(testObject.resurrectCount, 0); expect(testObject.deleteCount, 1); @@ -73,7 +68,7 @@ void _tests() { expect(skiaObject2, isNotNull); expect(skiaObject2, isNot(same(skiaObject1))); expect(SkiaObjects.resurrectableObjects.single, testObject); - expect(addPostFrameCallbackCount, 1); + expect(fakeRasterizer.addPostFrameCallbackCount, 1); expect(testObject.createDefaultCount, 1); expect(testObject.resurrectCount, 1); expect(testObject.deleteCount, 1); @@ -81,7 +76,7 @@ void _tests() { // Trigger final delete SkiaObjects.postFrameCleanUp(); expect(SkiaObjects.resurrectableObjects, isEmpty); - expect(addPostFrameCallbackCount, 1); + expect(fakeRasterizer.addPostFrameCallbackCount, 1); expect(testObject.createDefaultCount, 1); expect(testObject.resurrectCount, 1); expect(testObject.deleteCount, 2); @@ -204,6 +199,96 @@ void _tests() { expect(object.box.isDeletedPermanently, true); }); }); + + group('$SynchronousSkiaObjectCache', () { + test('is initialized empty', () { + expect(SynchronousSkiaObjectCache(10), hasLength(0)); + }); + + test('adds objects', () { + final SynchronousSkiaObjectCache cache = SynchronousSkiaObjectCache(2); + cache.add(TestSelfManagedObject()); + expect(cache, hasLength(1)); + cache.add(TestSelfManagedObject()); + expect(cache, hasLength(2)); + }); + + test('forbids adding the same object twice', () { + final SynchronousSkiaObjectCache cache = SynchronousSkiaObjectCache(2); + final TestSelfManagedObject object = TestSelfManagedObject(); + cache.add(object); + expect(cache, hasLength(1)); + expect(() => cache.add(object), throwsAssertionError); + }); + + void expectObjectInCache( + SynchronousSkiaObjectCache cache, + TestSelfManagedObject object, + ) { + expect(cache.debugContains(object), isTrue); + expect(object._skiaObject, isNotNull); + } + + void expectObjectNotInCache( + SynchronousSkiaObjectCache cache, + TestSelfManagedObject object, + ) { + expect(cache.debugContains(object), isFalse); + expect(object._skiaObject, isNull); + } + + test('respects maximumSize', () { + final SynchronousSkiaObjectCache cache = SynchronousSkiaObjectCache(2); + final TestSelfManagedObject object1 = TestSelfManagedObject(); + final TestSelfManagedObject object2 = TestSelfManagedObject(); + final TestSelfManagedObject object3 = TestSelfManagedObject(); + final TestSelfManagedObject object4 = TestSelfManagedObject(); + + cache.add(object1); + expect(cache, hasLength(1)); + expectObjectInCache(cache, object1); + + cache.add(object2); + expect(cache, hasLength(2)); + expectObjectInCache(cache, object1); + expectObjectInCache(cache, object2); + + cache.add(object3); + expect(cache, hasLength(2)); + expectObjectNotInCache(cache, object1); + expectObjectInCache(cache, object2); + expectObjectInCache(cache, object3); + + cache.add(object4); + expect(cache, hasLength(2)); + expectObjectNotInCache(cache, object1); + expectObjectNotInCache(cache, object2); + expectObjectInCache(cache, object3); + expectObjectInCache(cache, object4); + }); + + test('uses RLU strategy', () { + final SynchronousSkiaObjectCache cache = SynchronousSkiaObjectCache(2); + final TestSelfManagedObject object1 = TestSelfManagedObject(); + final TestSelfManagedObject object2 = TestSelfManagedObject(); + final TestSelfManagedObject object3 = TestSelfManagedObject(); + final TestSelfManagedObject object4 = TestSelfManagedObject(); + + cache.add(object1); + expectObjectInCache(cache, object1); + cache.add(object2); + expectObjectInCache(cache, object2); + cache.add(object3); + expectObjectInCache(cache, object3); + expectObjectNotInCache(cache, object1); + + cache.markUsed(object2); + cache.add(object4); + expectObjectInCache(cache, object2); + expectObjectNotInCache(cache, object3); + expectObjectInCache(cache, object4); + }); + }); } /// A simple class that wraps a [SkiaObjectBox]. @@ -235,9 +320,9 @@ class TestBoxWrapper implements StackTraceDebugger { @override StackTrace get debugStackTrace => _debugStackTrace; - StackTrace _debugStackTrace; + late StackTrace _debugStackTrace; - SkiaObjectBox box; + late SkiaObjectBox box; void dispose() { box.unref(this); @@ -304,4 +389,44 @@ class TestSkiaObject extends ManagedSkiaObject { bool get isResurrectionExpensive => isExpensive; } -class MockRasterizer extends Mock implements Rasterizer {} +class FakeRasterizer implements Rasterizer { + int addPostFrameCallbackCount = 0; + + @override + void addPostFrameCallback(VoidCallback callback) { + addPostFrameCallbackCount++; + } + + @override + CompositorContext get context => throw UnimplementedError(); + + @override + void draw(LayerTree layerTree) { + throw UnimplementedError(); + } + + @override + void setSkiaResourceCacheMaxBytes(int bytes) { + throw UnimplementedError(); + } + + @override + Surface get surface => throw UnimplementedError(); +} + +class TestSelfManagedObject extends SkiaObject { + TestSkDeletable? _skiaObject = TestSkDeletable(); + + @override + void delete() { + _skiaObject!.delete(); + } + + @override + void didDelete() { + _skiaObject = null; + } + + @override + TestSkDeletable get skiaObject => throw UnimplementedError(); +}