xref: /aosp_15_r20/external/skia/src/core/SkRecordOpts.cpp (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
1 /*
2  * Copyright 2014 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #include "src/core/SkRecordOpts.h"
9 
10 #include "include/core/SkBlendMode.h"
11 #include "include/core/SkCanvas.h"
12 #include "include/core/SkColor.h"
13 #include "include/core/SkPaint.h"
14 #include "include/core/SkRefCnt.h"
15 #include "include/private/base/SkMath.h"
16 #include "include/private/base/SkTemplates.h"
17 #include "src/core/SkRecord.h"
18 #include "src/core/SkRecordPattern.h"
19 #include "src/core/SkRecords.h"
20 
21 #include <cstdint>
22 #include <optional>
23 
24 using namespace SkRecords;
25 
26 // Most of the optimizations in this file are pattern-based.  These are all defined as structs with:
27 //   - a Match typedef
28 //   - a bool onMatch(SkRceord*, Match*, int begin, int end) method,
29 //     which returns true if it made changes and false if not.
30 
31 // Run a pattern-based optimization once across the SkRecord, returning true if it made any changes.
32 // It looks for spans which match Pass::Match, and when found calls onMatch() with that pattern,
33 // record, and [begin,end) span of the commands that matched.
34 template <typename Pass>
apply(Pass * pass,SkRecord * record)35 static bool apply(Pass* pass, SkRecord* record) {
36     typename Pass::Match match;
37     bool changed = false;
38     int begin, end = 0;
39 
40     while (match.search(record, &begin, &end)) {
41         changed |= pass->onMatch(record, &match, begin, end);
42     }
43     return changed;
44 }
45 
46 ///////////////////////////////////////////////////////////////////////////////////////////////////
47 
48 // Turns the logical NoOp Save and Restore in Save-Draw*-Restore patterns into actual NoOps.
49 struct SaveOnlyDrawsRestoreNooper {
50     typedef Pattern<Is<Save>,
51                     Greedy<Or<Is<NoOp>, IsDraw>>,
52                     Is<Restore>>
53         Match;
54 
onMatchSaveOnlyDrawsRestoreNooper55     bool onMatch(SkRecord* record, Match*, int begin, int end) {
56         record->replace<NoOp>(begin);  // Save
57         record->replace<NoOp>(end-1);  // Restore
58         return true;
59     }
60 };
61 
fold_opacity_layer_color_to_paint(const SkPaint * layerPaint,bool isSaveLayer,SkPaint * paint)62 static bool fold_opacity_layer_color_to_paint(const SkPaint* layerPaint,
63                                               bool isSaveLayer,
64                                               SkPaint* paint) {
65     // We assume layerPaint is always from a saveLayer.  If isSaveLayer is
66     // true, we assume paint is too.
67 
68     // The alpha folding can proceed if the filter layer paint does not have properties which cause
69     // the resulting filter layer to be "blended" in complex ways to the parent layer.
70     // TODO: most likely only some xfer modes are the hard constraints
71     if (!paint->isSrcOver()) {
72         return false;
73     }
74 
75     if (!isSaveLayer && paint->getImageFilter()) {
76         // For normal draws, the paint color is used as one input for the color for the draw. Image
77         // filter will operate on the result, and thus we can not change the input.
78         // For layer saves, the image filter is applied to the layer contents. The layer is then
79         // modulated with the paint color, so it's fine to proceed with the fold for saveLayer
80         // paints with image filters.
81         return false;
82     }
83 
84     if (paint->getColorFilter()) {
85         // Filter input depends on the paint color.
86 
87         // Here we could filter the color if we knew the draw is going to be uniform color.  This
88         // should be detectable as drawPath/drawRect/.. without a shader being uniform, while
89         // drawBitmap/drawSprite or a shader being non-uniform. However, current matchers don't
90         // give the type out easily, so just do not optimize that at the moment.
91         return false;
92     }
93 
94     if (layerPaint) {
95         const uint32_t layerColor = layerPaint->getColor();
96         // The layer paint color must have only alpha component.
97         if (SK_ColorTRANSPARENT != SkColorSetA(layerColor, SK_AlphaTRANSPARENT)) {
98             return false;
99         }
100 
101         // The layer paint can not have any effects.
102         if (layerPaint->getPathEffect()  ||
103             layerPaint->getShader()      ||
104             !layerPaint->isSrcOver()     ||
105             layerPaint->getMaskFilter()  ||
106             layerPaint->getColorFilter() ||
107             layerPaint->getImageFilter()) {
108             return false;
109         }
110         paint->setAlpha(SkMulDiv255Round(paint->getAlpha(), SkColorGetA(layerColor)));
111     }
112 
113     return true;
114 }
115 
116 // Turns logical no-op Save-[non-drawing command]*-Restore patterns into actual no-ops.
117 struct SaveNoDrawsRestoreNooper {
118     // Greedy matches greedily, so we also have to exclude Save and Restore.
119     // Nested SaveLayers need to be excluded, or we'll match their Restore!
120     typedef Pattern<Is<Save>,
121                     Greedy<Not<Or<Is<Save>,
122                                   Is<SaveLayer>,
123                                   Is<Restore>,
124                                   IsDraw>>>,
125                     Is<Restore>>
126         Match;
127 
onMatchSaveNoDrawsRestoreNooper128     bool onMatch(SkRecord* record, Match*, int begin, int end) {
129         // The entire span between Save and Restore (inclusively) does nothing.
130         for (int i = begin; i < end; i++) {
131             record->replace<NoOp>(i);
132         }
133         return true;
134     }
135 };
SkRecordNoopSaveRestores(SkRecord * record)136 void SkRecordNoopSaveRestores(SkRecord* record) {
137     SaveOnlyDrawsRestoreNooper onlyDraws;
138     SaveNoDrawsRestoreNooper noDraws;
139 
140     // Run until they stop changing things.
141     while (apply(&onlyDraws, record) || apply(&noDraws, record));
142 }
143 
144 #ifndef SK_BUILD_FOR_ANDROID_FRAMEWORK
effectively_srcover(const SkPaint * paint)145 static bool effectively_srcover(const SkPaint* paint) {
146     if (!paint || paint->isSrcOver()) {
147         return true;
148     }
149     // src-mode with opaque and no effects (which might change opaqueness) is ok too.
150     return !paint->getShader() && !paint->getColorFilter() && !paint->getImageFilter() &&
151            0xFF == paint->getAlpha() && paint->asBlendMode() == SkBlendMode::kSrc;
152 }
153 
154 // For some SaveLayer-[drawing command]-Restore patterns, merge the SaveLayer's alpha into the
155 // draw, and no-op the SaveLayer and Restore.
156 struct SaveLayerDrawRestoreNooper {
157     // Note that we use IsSingleDraw here, to avoid matching drawAtlas, drawVertices, etc...
158     // Those operations (can) draw multiple, overlapping primitives that blend with each other.
159     // Applying this operation to them changes their behavior. (skbug.com/14554)
160     typedef Pattern<Is<SaveLayer>, IsSingleDraw, Is<Restore>> Match;
161 
onMatchSaveLayerDrawRestoreNooper162     bool onMatch(SkRecord* record, Match* match, int begin, int end) {
163         if (match->first<SaveLayer>()->backdrop) {
164             // can't throw away the layer if we have a backdrop
165             return false;
166         }
167 
168         if (!match->first<SaveLayer>()->filters.empty()) {
169             // Our optimizations don't handle the filter list correctly - don't bother trying
170             return false;
171         }
172 
173         // A SaveLayer's bounds field is just a hint, so we should be free to ignore it.
174         SkPaint* layerPaint = match->first<SaveLayer>()->paint;
175         SkPaint* drawPaint = match->second<SkPaint>();
176 
177         if (nullptr == layerPaint && effectively_srcover(drawPaint)) {
178             // There wasn't really any point to this SaveLayer at all.
179             return KillSaveLayerAndRestore(record, begin);
180         }
181 
182         if (drawPaint == nullptr) {
183             // We can just give the draw the SaveLayer's paint.
184             // TODO(mtklein): figure out how to do this clearly
185             return false;
186         }
187 
188         if (!fold_opacity_layer_color_to_paint(layerPaint, false /*isSaveLayer*/, drawPaint)) {
189             return false;
190         }
191 
192         return KillSaveLayerAndRestore(record, begin);
193     }
194 
KillSaveLayerAndRestoreSaveLayerDrawRestoreNooper195     static bool KillSaveLayerAndRestore(SkRecord* record, int saveLayerIndex) {
196         record->replace<NoOp>(saveLayerIndex);    // SaveLayer
197         record->replace<NoOp>(saveLayerIndex+2);  // Restore
198         return true;
199     }
200 };
SkRecordNoopSaveLayerDrawRestores(SkRecord * record)201 void SkRecordNoopSaveLayerDrawRestores(SkRecord* record) {
202     SaveLayerDrawRestoreNooper pass;
203     apply(&pass, record);
204 }
205 #endif
206 
207 /* For SVG generated:
208   SaveLayer (non-opaque, typically for CSS opacity)
209     Save
210       ClipRect
211       SaveLayer (typically for SVG filter)
212       Restore
213     Restore
214   Restore
215 */
216 struct SvgOpacityAndFilterLayerMergePass {
217     typedef Pattern<Is<SaveLayer>, Is<Save>, Is<ClipRect>, Is<SaveLayer>,
218                     Is<Restore>, Is<Restore>, Is<Restore>> Match;
219 
onMatchSvgOpacityAndFilterLayerMergePass220     bool onMatch(SkRecord* record, Match* match, int begin, int end) {
221         if (match->first<SaveLayer>()->backdrop) {
222             // can't throw away the layer if we have a backdrop
223             return false;
224         }
225 
226         if (!match->first<SaveLayer>()->filters.empty() ||
227             !match->fourth<SaveLayer>()->filters.empty()) {
228             // Our optimizations don't handle the filter list correctly - don't bother trying
229             return false;
230         }
231 
232         SkPaint* opacityPaint = match->first<SaveLayer>()->paint;
233         if (nullptr == opacityPaint) {
234             // There wasn't really any point to this SaveLayer at all.
235             return KillSaveLayerAndRestore(record, begin);
236         }
237 
238         // This layer typically contains a filter, but this should work for layers with for other
239         // purposes too.
240         SkPaint* filterLayerPaint = match->fourth<SaveLayer>()->paint;
241         if (filterLayerPaint == nullptr) {
242             // We can just give the inner SaveLayer the paint of the outer SaveLayer.
243             // TODO(mtklein): figure out how to do this clearly
244             return false;
245         }
246 
247         if (!fold_opacity_layer_color_to_paint(opacityPaint, true /*isSaveLayer*/,
248                                                filterLayerPaint)) {
249             return false;
250         }
251 
252         return KillSaveLayerAndRestore(record, begin);
253     }
254 
KillSaveLayerAndRestoreSvgOpacityAndFilterLayerMergePass255     static bool KillSaveLayerAndRestore(SkRecord* record, int saveLayerIndex) {
256         record->replace<NoOp>(saveLayerIndex);     // SaveLayer
257         record->replace<NoOp>(saveLayerIndex + 6); // Restore
258         return true;
259     }
260 };
261 
SkRecordMergeSvgOpacityAndFilterLayers(SkRecord * record)262 void SkRecordMergeSvgOpacityAndFilterLayers(SkRecord* record) {
263     SvgOpacityAndFilterLayerMergePass pass;
264     apply(&pass, record);
265 }
266 
267 ///////////////////////////////////////////////////////////////////////////////////////////////////
268 
SkRecordOptimize(SkRecord * record)269 void SkRecordOptimize(SkRecord* record) {
270     // This might be useful  as a first pass in the future if we want to weed
271     // out junk for other optimization passes.  Right now, nothing needs it,
272     // and the bounding box hierarchy will do the work of skipping no-op
273     // Save-NoDraw-Restore sequences better than we can here.
274     // As there is a known problem with this peephole and drawAnnotation, disable this.
275     // If we want to enable this we must first fix this bug:
276     //     https://bugs.chromium.org/p/skia/issues/detail?id=5548
277 //    SkRecordNoopSaveRestores(record);
278 
279     // Turn off this optimization completely for Android framework
280     // because it makes the following Android CTS test fail:
281     // android.uirendering.cts.testclasses.LayerTests#testSaveLayerClippedWithAlpha
282 #ifndef SK_BUILD_FOR_ANDROID_FRAMEWORK
283     SkRecordNoopSaveLayerDrawRestores(record);
284 #endif
285     SkRecordMergeSvgOpacityAndFilterLayers(record);
286 
287     record->defrag();
288 }
289