Reclaim paragraph memory more aggressively (flutter/engine#26438)

* delete paragraphs between layout and render
This commit is contained in:
Yegor
2021-05-27 13:58:41 -07:00
committed by GitHub
parent ec4b23c9e9
commit e4ed8ffcd8
5 changed files with 377 additions and 97 deletions

View File

@@ -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();
}
}

View File

@@ -1786,7 +1786,7 @@ class SkParagraph {
SkRectHeightStyle heightStyle,
SkRectWidthStyle widthStyle,
);
external List<Float32List> getRectsForPlaceholders();
external List<dynamic> getRectsForPlaceholders();
external SkTextPosition getGlyphPositionAtCoordinate(
double x,
double y,

View File

@@ -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<SkiaObject> _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<SkiaObject, DoubleLinkedQueueEntry<SkiaObject>> _itemMap;
SynchronousSkiaObjectCache(this.maximumSize)
: _itemQueue = DoubleLinkedQueue<SkiaObject>(),
_itemMap = <SkiaObject, DoubleLinkedQueueEntry<SkiaObject>>{};
/// 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<SkiaObject>? 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<R extends StackTraceDebugger, T extends Object>
/// If asserts are enabled, the [StackTrace]s representing when a reference
/// was created.
List<StackTrace>? debugGetStackTraces() {
List<StackTrace> debugGetStackTraces() {
if (assertionsEnabled) {
return debugReferrers
.map<StackTrace>((R referrer) => referrer.debugStackTrace)
.toList();
}
return null;
throw UnsupportedError('');
}
/// The Skia object whose lifecycle is being managed.

View File

@@ -524,15 +524,25 @@ SkFontStyle toSkFontStyle(ui.FontWeight? fontWeight, ui.FontStyle? fontStyle) {
return style;
}
class CkParagraph extends ManagedSkiaObject<SkParagraph>
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<SkParagraph> 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<SkParagraph>
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<ui.TextBox> getBoxesForPlaceholders() {
List<List<double>> 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<ui.TextBox> getBoxesForPlaceholders() => _boxesForPlaceholders!;
List<ui.TextBox>? _boxesForPlaceholders;
@override
List<ui.TextBox> getBoxesForRange(
int start,
@@ -633,7 +707,8 @@ class CkParagraph extends ManagedSkiaObject<SkParagraph>
return const <ui.TextBox>[];
}
List<List<double>> skRects = skiaObject.getRectsForRange(
final SkParagraph paragraph = _ensureInitialized(_lastLayoutConstraints!);
final List<List<double>> skRects = paragraph.getRectsForRange(
start,
end,
toSkRectHeightStyle(boxHeightStyle),
@@ -643,7 +718,7 @@ class CkParagraph extends ManagedSkiaObject<SkParagraph>
return skRectsToTextBoxes(skRects);
}
List<ui.TextBox> skRectsToTextBoxes(List<List<double>> skRects) {
List<ui.TextBox> skRectsToTextBoxes(List<dynamic> skRects) {
List<ui.TextBox> result = <ui.TextBox>[];
for (int i = 0; i < skRects.length; i++) {
@@ -662,8 +737,9 @@ class CkParagraph extends ManagedSkiaObject<SkParagraph>
@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<SkParagraph>
@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<SkLineMetrics> metrics = skiaObject.getLineMetrics();
final SkParagraph paragraph = _ensureInitialized(_lastLayoutConstraints!);
final List<SkLineMetrics> 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<SkParagraph>
@override
List<ui.LineMetrics> computeLineMetrics() {
final List<SkLineMetrics> skLineMetrics = skiaObject.getLineMetrics();
final SkParagraph paragraph = _ensureInitialized(_lastLayoutConstraints!);
final List<SkLineMetrics> skLineMetrics = paragraph.getLineMetrics();
final List<ui.LineMetrics> result = <ui.LineMetrics>[];
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;

View File

@@ -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<TestBoxWrapper, TestSkDeletable> box;
late SkiaObjectBox<TestBoxWrapper, TestSkDeletable> box;
void dispose() {
box.unref(this);
@@ -304,4 +389,44 @@ class TestSkiaObject extends ManagedSkiaObject<SkPaint> {
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> {
TestSkDeletable? _skiaObject = TestSkDeletable();
@override
void delete() {
_skiaObject!.delete();
}
@override
void didDelete() {
_skiaObject = null;
}
@override
TestSkDeletable get skiaObject => throw UnimplementedError();
}