Skip to content

Commit 3874e02

Browse files
authored
Started caching text shadows by content. (flutter#190681)
fixes flutter#190395 This replaces `TextShadowCacheKey::identifier`, which was a cast of the TextFrame pointer, with a content aware fingerprint. This allows cache hits across frames. It also removes the possible error where the pointer is recycled for a different TextFrame on the next frame. The fingerprint approach was chosen over storing a shared_ptr to a TextFrame and performing equality checks on it. The fingerprint avoids shared_ptr and indirection overhead in the TextShadowCacheKey. Instead of just relying on the hash we added extra fields to create the full fingerprint to make the probability of a false cache essentially zero (the texts on the same frame would have to have the same length, start, end, and hash code to create a false cache hit). I measured this locally with a windows machine with the reproduction from flutter#190395, after this the shadowed text frames measure the same as the non-shadowed text frames. flutter#190861 adds a benchmark, the PR was measured on macos with that benchmark as well. ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [AI contribution guidelines] and understand my responsibilities, or I am not using AI tools. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. If this change needs to override an active code freeze, provide a comment explaining why. The code freeze workflow can be overridden by code reviewers. See pinned issues for any active code freezes with guidance. **Note**: The Flutter team is currently trialing the use of [Gemini Code Assist for GitHub](https://developers.google.com/gemini-code-assist/docs/review-github-code). Comments from the `gemini-code-assist` bot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed. <!-- Links --> [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [AI contribution guidelines]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#ai-contribution-guidelines [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md
1 parent 2c80e9b commit 3874e02

7 files changed

Lines changed: 271 additions & 39 deletions

File tree

‎engine/src/flutter/impeller/display_list/BUILD.gn‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,8 @@ impeller_component("display_list") {
5757
"//flutter/skia",
5858
]
5959

60+
deps = [ "//third_party/abseil-cpp/absl/hash" ]
61+
6062
if (impeller_supports_rendering) {
6163
public_deps += [ "//flutter/impeller/runtime_stage" ]
6264
}

‎engine/src/flutter/impeller/display_list/aiks_dl_text_unittests.cc‎

Lines changed: 166 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -44,12 +44,14 @@ struct TextRenderOptions {
4444
bool is_subpixel = false;
4545
};
4646

47-
bool RenderTextInCanvasSkia(const std::shared_ptr<Context>& context,
48-
DisplayListBuilder& canvas,
49-
const std::string& text,
50-
const std::string_view& font_fixture,
51-
const TextRenderOptions& options = {},
52-
const std::optional<SkFont>& font = std::nullopt) {
47+
bool RenderTextInCanvasSkia(
48+
const std::shared_ptr<Context>& context,
49+
DisplayListBuilder& canvas,
50+
const std::string& text,
51+
const std::string_view& font_fixture,
52+
const TextRenderOptions& options = {},
53+
const std::optional<SkFont>& font = std::nullopt,
54+
std::map<std::string, sk_sp<SkTypeface>>* typeface_cache = nullptr) {
5355
// Draw the baseline.
5456
DlPaint paint;
5557
paint.setColor(DlColor::kAqua().withAlpha(255 * 0.25));
@@ -65,13 +67,29 @@ bool RenderTextInCanvasSkia(const std::shared_ptr<Context>& context,
6567
SkFont selected_font;
6668
if (!font.has_value()) {
6769
auto c_font_fixture = std::string(font_fixture);
68-
auto mapping =
69-
flutter::testing::OpenFixtureAsSkData(c_font_fixture.c_str());
70-
if (!mapping) {
71-
return false;
70+
sk_sp<SkTypeface> typeface;
71+
if (typeface_cache) {
72+
auto it = typeface_cache->find(c_font_fixture);
73+
if (it != typeface_cache->end()) {
74+
typeface = it->second;
75+
}
76+
}
77+
if (!typeface) {
78+
auto mapping =
79+
flutter::testing::OpenFixtureAsSkData(c_font_fixture.c_str());
80+
if (!mapping) {
81+
return false;
82+
}
83+
sk_sp<SkFontMgr> font_mgr = txt::GetDefaultFontManager();
84+
typeface = font_mgr->makeFromData(mapping);
85+
if (!typeface) {
86+
return false;
87+
}
88+
if (typeface_cache) {
89+
(*typeface_cache)[c_font_fixture] = typeface;
90+
}
7291
}
73-
sk_sp<SkFontMgr> font_mgr = txt::GetDefaultFontManager();
74-
selected_font = SkFont(font_mgr->makeFromData(mapping), options.font_size);
92+
selected_font = SkFont(typeface, options.font_size);
7593
if (options.is_subpixel) {
7694
selected_font.setSubpixel(true);
7795
}
@@ -867,22 +885,155 @@ TEST_P(AiksTest, MultipleTextWithShadowCache) {
867885

868886
for (auto i = 0; i < 5; i++) {
869887
ASSERT_TRUE(RenderTextInCanvasSkia(
870-
GetContext(), builder, "Hello World", kFontFixture,
888+
GetContext(), builder,
889+
(std::string("Hello World ") + std::to_string(i)).c_str(), kFontFixture,
871890
TextRenderOptions{
872891
.color = DlColor::kBlue(),
873892
.filter = DlBlurMaskFilter::Make(DlBlurStyle::kNormal, 4)}));
874893
}
875894

876895
DisplayListToTexture(builder.Build(), {400, 400}, aiks_context);
877896

878-
// Text should be cached. Each text gets its own entry as we don't analyze the
879-
// strings.
897+
// Each distinct text gets its own cache entry.
880898
EXPECT_EQ(aiks_context.GetContentContext()
881899
.GetTextShadowCache()
882900
.GetCacheSizeForTesting(),
883901
5u);
884902
}
885903

904+
TEST_P(AiksTest, DuplicateTextWithShadowCache) {
905+
DisplayListBuilder builder;
906+
builder.Scale(GetContentScale().x, GetContentScale().y);
907+
DlPaint paint;
908+
paint.setColor(DlColor::ARGB(1, 0.1, 0.1, 0.1));
909+
builder.DrawPaint(paint);
910+
911+
AiksContext aiks_context(GetContext(),
912+
std::make_shared<TypographerContextSkia>());
913+
// Cache empty
914+
EXPECT_EQ(aiks_context.GetContentContext()
915+
.GetTextShadowCache()
916+
.GetCacheSizeForTesting(),
917+
0u);
918+
919+
std::map<std::string, sk_sp<SkTypeface>> typeface_cache;
920+
for (auto i = 0; i < 5; i++) {
921+
ASSERT_TRUE(RenderTextInCanvasSkia(
922+
GetContext(), builder, "Hello World", kFontFixture,
923+
TextRenderOptions{
924+
.color = DlColor::kBlue(),
925+
.filter = DlBlurMaskFilter::Make(DlBlurStyle::kNormal, 4)},
926+
std::nullopt, &typeface_cache));
927+
}
928+
929+
DisplayListToTexture(builder.Build(), {400, 400}, aiks_context);
930+
931+
// Duplicate text frames with identical layout share the single cache entry.
932+
EXPECT_EQ(aiks_context.GetContentContext()
933+
.GetTextShadowCache()
934+
.GetCacheSizeForTesting(),
935+
1u);
936+
}
937+
938+
TEST_P(AiksTest, TextShadowCacheKeyCollisionSafety) {
939+
SkFont font = flutter::testing::CreateTestFontOfSize(12);
940+
941+
Font impeller_font(
942+
MakeTextFrameFromTextBlobSkia(SkTextBlob::MakeFromString("Text A", font))
943+
->GetFont());
944+
945+
TextFrameFingerprint fp1{
946+
.run_count = 1,
947+
.total_glyph_count = 6,
948+
.first_glyph_id = 10,
949+
.last_glyph_id = 20,
950+
.full_hash = 12345,
951+
};
952+
953+
TextFrameFingerprint fp2{
954+
.run_count = 1,
955+
.total_glyph_count = 6,
956+
.first_glyph_id = 10,
957+
.last_glyph_id = 21, // Different last glyph ID
958+
.full_hash = 12345, // Simulated hash collision on full_hash!
959+
};
960+
961+
// Construct two keys with the exact same identifier & full_hash (simulating a
962+
// hash collision) but with different fingerprints (e.g. different
963+
// last_glyph_id).
964+
TextShadowCache::TextShadowCacheKey key1(
965+
/*p_max_basis=*/1.0f,
966+
/*p_is_single_glyph=*/false,
967+
/*p_font=*/impeller_font,
968+
/*p_sigma=*/Sigma{4.0f},
969+
/*p_color=*/Color::Blue(),
970+
/*p_fingerprint=*/fp1);
971+
972+
TextShadowCache::TextShadowCacheKey key2(
973+
/*p_max_basis=*/1.0f,
974+
/*p_is_single_glyph=*/false,
975+
/*p_font=*/impeller_font,
976+
/*p_sigma=*/Sigma{4.0f},
977+
/*p_color=*/Color::Blue(),
978+
/*p_fingerprint=*/fp2);
979+
980+
TextShadowCache::TextShadowCacheKey::Equal equal;
981+
// Key comparison must fail because fingerprints differ despite identical
982+
// hash.
983+
EXPECT_FALSE(equal(key1, key2));
984+
985+
TextShadowCache::TextShadowCacheKey key3(
986+
/*p_max_basis=*/1.0f,
987+
/*p_is_single_glyph=*/false,
988+
/*p_font=*/impeller_font,
989+
/*p_sigma=*/Sigma{4.0f},
990+
/*p_color=*/Color::Blue(),
991+
/*p_fingerprint=*/fp1);
992+
993+
// Key comparison must succeed for identical fingerprints.
994+
EXPECT_TRUE(equal(key1, key3));
995+
}
996+
997+
TEST_P(AiksTest, SingleGlyphTextShadowCache) {
998+
DisplayListBuilder builder;
999+
builder.Scale(GetContentScale().x, GetContentScale().y);
1000+
DlPaint paint;
1001+
paint.setColor(DlColor::ARGB(1, 0.1, 0.1, 0.1));
1002+
builder.DrawPaint(paint);
1003+
1004+
AiksContext aiks_context(GetContext(),
1005+
std::make_shared<TypographerContextSkia>());
1006+
EXPECT_EQ(aiks_context.GetContentContext()
1007+
.GetTextShadowCache()
1008+
.GetCacheSizeForTesting(),
1009+
0u);
1010+
1011+
SkFont font = flutter::testing::CreateTestFontOfSize(12);
1012+
TextRenderOptions options{
1013+
.color = DlColor::kBlue(),
1014+
.filter = DlBlurMaskFilter::Make(DlBlurStyle::kNormal, 4)};
1015+
1016+
// Draw single glyph "A".
1017+
ASSERT_TRUE(RenderTextInCanvasSkia(GetContext(), builder, "A", kFontFixture,
1018+
options, font));
1019+
1020+
// Draw single glyph "B" (different glyph ID, identical font/color/sigma).
1021+
ASSERT_TRUE(RenderTextInCanvasSkia(GetContext(), builder, "B", kFontFixture,
1022+
options, font));
1023+
1024+
// Draw single glyph "A" again (duplicate glyph ID).
1025+
ASSERT_TRUE(RenderTextInCanvasSkia(GetContext(), builder, "A", kFontFixture,
1026+
options, font));
1027+
1028+
DisplayListToTexture(builder.Build(), {400, 400}, aiks_context);
1029+
1030+
// Single glyphs "A" and "B" get distinct entries; duplicate "A" reuses "A".
1031+
EXPECT_EQ(aiks_context.GetContentContext()
1032+
.GetTextShadowCache()
1033+
.GetCacheSizeForTesting(),
1034+
2u);
1035+
}
1036+
8861037
TEST_P(AiksTest, MultipleColorWithShadowCache) {
8871038
DisplayListBuilder builder;
8881039
builder.Scale(GetContentScale().x, GetContentScale().y);

‎engine/src/flutter/impeller/display_list/canvas.cc‎

Lines changed: 48 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -65,11 +65,53 @@
6565
#include "impeller/geometry/scalar.h"
6666
#include "impeller/geometry/vector.h"
6767
#include "impeller/renderer/command_buffer.h"
68+
#include "third_party/abseil-cpp/absl/hash/hash.h"
6869

6970
namespace impeller {
7071

7172
namespace {
7273

74+
uint32_t PackGlyphId(const Glyph& glyph) {
75+
return (static_cast<uint32_t>(glyph.type) << 16) | glyph.index;
76+
}
77+
78+
TextFrameFingerprint ComputeTextFrameFingerprint(const TextFrame& text_frame) {
79+
TextFrameFingerprint fp;
80+
const std::vector<TextRun>& runs = text_frame.GetRuns();
81+
fp.run_count = runs.size();
82+
83+
size_t hash = absl::HashOf(text_frame.HasColor(),
84+
text_frame.GetEnableGammaCorrection());
85+
86+
for (const TextRun& run : runs) {
87+
hash = absl::HashOf(hash, run.GetFont().GetHash());
88+
const std::vector<TextRun::GlyphPosition>& glyphs = run.GetGlyphPositions();
89+
fp.total_glyph_count += glyphs.size();
90+
91+
for (const TextRun::GlyphPosition& glyph_pos : glyphs) {
92+
hash = absl::HashOf(hash, static_cast<uint32_t>(glyph_pos.glyph.type),
93+
glyph_pos.glyph.index, glyph_pos.position.x,
94+
glyph_pos.position.y);
95+
}
96+
}
97+
98+
if (!runs.empty()) {
99+
const std::vector<TextRun::GlyphPosition>& first_glyphs =
100+
runs.front().GetGlyphPositions();
101+
if (!first_glyphs.empty()) {
102+
fp.first_glyph_id = PackGlyphId(first_glyphs.front().glyph);
103+
}
104+
const std::vector<TextRun::GlyphPosition>& last_glyphs =
105+
runs.back().GetGlyphPositions();
106+
if (!last_glyphs.empty()) {
107+
fp.last_glyph_id = PackGlyphId(last_glyphs.back().glyph);
108+
}
109+
}
110+
111+
fp.full_hash = hash;
112+
return fp;
113+
}
114+
73115
constexpr Scalar kAntialiasPadding = 1.0f;
74116

75117
bool IsPipelineBlendOrMatrixFilter(const flutter::DlColorFilter* filter) {
@@ -2101,16 +2143,17 @@ bool Canvas::AttemptBlurredTextOptimization(
21012143
/*is_solid_color=*/true, GetCurrentTransform());
21022144

21032145
std::optional<Glyph> maybe_glyph = text_frame->AsSingleGlyph();
2104-
int64_t identifier = maybe_glyph.has_value()
2105-
? maybe_glyph.value().index
2106-
: reinterpret_cast<int64_t>(text_frame.get());
2146+
TextFrameFingerprint fingerprint =
2147+
maybe_glyph.has_value()
2148+
? TextFrameFingerprint{.full_hash = PackGlyphId(maybe_glyph.value())}
2149+
: ComputeTextFrameFingerprint(*text_frame);
21072150
TextShadowCache::TextShadowCacheKey cache_key(
21082151
/*p_max_basis=*/entity.GetTransform().GetMaxBasisLengthXY(),
2109-
/*p_identifier=*/identifier,
21102152
/*p_is_single_glyph=*/maybe_glyph.has_value(),
21112153
/*p_font=*/text_frame->GetFont(),
21122154
/*p_sigma=*/paint.mask_blur_descriptor->sigma,
2113-
/*p_color=*/paint.color);
2155+
/*p_color=*/paint.color,
2156+
/*p_fingerprint=*/fingerprint);
21142157

21152158
std::optional<Entity> result = renderer_.GetTextShadowCache().Lookup(
21162159
renderer_, entity, filter, cache_key);

‎engine/src/flutter/impeller/entity/BUILD.gn‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,7 @@ impeller_component("entity") {
262262
"../typographer",
263263
"//flutter/display_list",
264264
"//third_party/abseil-cpp/absl/container:flat_hash_map",
265+
"//third_party/abseil-cpp/absl/hash",
265266
]
266267

267268
deps = [ "//flutter/fml" ]

‎engine/src/flutter/impeller/entity/contents/text_shadow_cache.cc‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,19 +15,20 @@ namespace impeller {
1515
// Rounds sigma values for gaussian blur to nearest decimal.
1616
static constexpr int32_t kMaxSigmaDenominator = 10;
1717

18-
TextShadowCache::TextShadowCacheKey::TextShadowCacheKey(Scalar p_max_basis,
19-
int64_t p_identifier,
20-
bool p_is_single_glyph,
21-
const Font& p_font,
22-
Sigma p_sigma,
23-
Color p_color)
18+
TextShadowCache::TextShadowCacheKey::TextShadowCacheKey(
19+
Scalar p_max_basis,
20+
bool p_is_single_glyph,
21+
const Font& p_font,
22+
Sigma p_sigma,
23+
Color p_color,
24+
TextFrameFingerprint p_fingerprint)
2425
: max_basis(p_max_basis),
25-
identifier(p_identifier),
2626
is_single_glyph(p_is_single_glyph),
2727
font(p_font),
2828
rounded_sigma(Rational(std::round(p_sigma.sigma * kMaxSigmaDenominator),
2929
kMaxSigmaDenominator)),
30-
color(p_color) {}
30+
color(p_color),
31+
fingerprint(p_fingerprint) {}
3132

3233
void TextShadowCache::MarkFrameStart() {
3334
for (auto& entry : entries_) {

0 commit comments

Comments
 (0)