• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "SkRecordOpts.h"
9 
10 #include "SkRecordPattern.h"
11 #include "SkRecords.h"
12 #include "SkTDArray.h"
13 
14 using namespace SkRecords;
15 
16 // Most of the optimizations in this file are pattern-based.  These are all defined as structs with:
17 //   - a Match typedef
18 //   - a bool onMatch(SkRceord*, Match*, int begin, int end) method,
19 //     which returns true if it made changes and false if not.
20 
21 // Run a pattern-based optimization once across the SkRecord, returning true if it made any changes.
22 // It looks for spans which match Pass::Match, and when found calls onMatch() with that pattern,
23 // record, and [begin,end) span of the commands that matched.
24 template <typename Pass>
apply(Pass * pass,SkRecord * record)25 static bool apply(Pass* pass, SkRecord* record) {
26     typename Pass::Match match;
27     bool changed = false;
28     int begin, end = 0;
29 
30     while (match.search(record, &begin, &end)) {
31         changed |= pass->onMatch(record, &match, begin, end);
32     }
33     return changed;
34 }
35 
36 ///////////////////////////////////////////////////////////////////////////////////////////////////
37 
multiple_set_matrices(SkRecord * record)38 static void multiple_set_matrices(SkRecord* record) {
39     struct {
40         typedef Pattern<Is<SetMatrix>,
41                         Greedy<Is<NoOp>>,
42                         Is<SetMatrix> >
43             Match;
44 
45         bool onMatch(SkRecord* record, Match* pattern, int begin, int end) {
46             record->replace<NoOp>(begin);  // first SetMatrix
47             return true;
48         }
49     } pass;
50     while (apply(&pass, record));
51 }
52 
53 ///////////////////////////////////////////////////////////////////////////////////////////////////
54 
55 #if 0   // experimental, but needs knowledge of previous matrix to operate correctly
56 static void apply_matrix_to_draw_params(SkRecord* record) {
57     struct {
58         typedef Pattern<Is<SetMatrix>,
59                         Greedy<Is<NoOp>>,
60                         Is<SetMatrix> >
61             Pattern;
62 
63         bool onMatch(SkRecord* record, Pattern* pattern, int begin, int end) {
64             record->replace<NoOp>(begin);  // first SetMatrix
65             return true;
66         }
67     } pass;
68     // No need to loop, as we never "open up" opportunities for more of this type of optimization.
69     apply(&pass, record);
70 }
71 #endif
72 
73 ///////////////////////////////////////////////////////////////////////////////////////////////////
74 
75 // Turns the logical NoOp Save and Restore in Save-Draw*-Restore patterns into actual NoOps.
76 struct SaveOnlyDrawsRestoreNooper {
77     typedef Pattern<Is<Save>,
78                     Greedy<Or<Is<NoOp>, IsDraw>>,
79                     Is<Restore>>
80         Match;
81 
onMatchSaveOnlyDrawsRestoreNooper82     bool onMatch(SkRecord* record, Match*, int begin, int end) {
83         record->replace<NoOp>(begin);  // Save
84         record->replace<NoOp>(end-1);  // Restore
85         return true;
86     }
87 };
88 
fold_opacity_layer_color_to_paint(const SkPaint * layerPaint,bool isSaveLayer,SkPaint * paint)89 static bool fold_opacity_layer_color_to_paint(const SkPaint* layerPaint,
90                                               bool isSaveLayer,
91                                               SkPaint* paint) {
92     // We assume layerPaint is always from a saveLayer.  If isSaveLayer is
93     // true, we assume paint is too.
94 
95     // The alpha folding can proceed if the filter layer paint does not have properties which cause
96     // the resulting filter layer to be "blended" in complex ways to the parent layer. For example,
97     // looper drawing unmodulated filter layer twice and then modulating the result produces
98     // different image to drawing modulated filter layer twice.
99     // TODO: most likely the looper and only some xfer modes are the hard constraints
100     if (!paint->isSrcOver() || paint->getLooper()) {
101         return false;
102     }
103 
104     if (!isSaveLayer && paint->getImageFilter()) {
105         // For normal draws, the paint color is used as one input for the color for the draw. Image
106         // filter will operate on the result, and thus we can not change the input.
107         // For layer saves, the image filter is applied to the layer contents. The layer is then
108         // modulated with the paint color, so it's fine to proceed with the fold for saveLayer
109         // paints with image filters.
110         return false;
111     }
112 
113     if (paint->getColorFilter()) {
114         // Filter input depends on the paint color.
115 
116         // Here we could filter the color if we knew the draw is going to be uniform color.  This
117         // should be detectable as drawPath/drawRect/.. without a shader being uniform, while
118         // drawBitmap/drawSprite or a shader being non-uniform. However, current matchers don't
119         // give the type out easily, so just do not optimize that at the moment.
120         return false;
121     }
122 
123     if (layerPaint) {
124         const uint32_t layerColor = layerPaint->getColor();
125         // The layer paint color must have only alpha component.
126         if (SK_ColorTRANSPARENT != SkColorSetA(layerColor, SK_AlphaTRANSPARENT)) {
127             return false;
128         }
129 
130         // The layer paint can not have any effects.
131         if (layerPaint->getPathEffect()  ||
132             layerPaint->getShader()      ||
133             !layerPaint->isSrcOver()     ||
134             layerPaint->getMaskFilter()  ||
135             layerPaint->getColorFilter() ||
136             layerPaint->getLooper()      ||
137             layerPaint->getImageFilter()) {
138             return false;
139         }
140         paint->setAlpha(SkMulDiv255Round(paint->getAlpha(), SkColorGetA(layerColor)));
141     }
142 
143     return true;
144 }
145 
146 // Turns logical no-op Save-[non-drawing command]*-Restore patterns into actual no-ops.
147 struct SaveNoDrawsRestoreNooper {
148     // Greedy matches greedily, so we also have to exclude Save and Restore.
149     // Nested SaveLayers need to be excluded, or we'll match their Restore!
150     typedef Pattern<Is<Save>,
151                     Greedy<Not<Or<Is<Save>,
152                                   Is<SaveLayer>,
153                                   Is<Restore>,
154                                   IsDraw>>>,
155                     Is<Restore>>
156         Match;
157 
onMatchSaveNoDrawsRestoreNooper158     bool onMatch(SkRecord* record, Match*, int begin, int end) {
159         // The entire span between Save and Restore (inclusively) does nothing.
160         for (int i = begin; i < end; i++) {
161             record->replace<NoOp>(i);
162         }
163         return true;
164     }
165 };
SkRecordNoopSaveRestores(SkRecord * record)166 void SkRecordNoopSaveRestores(SkRecord* record) {
167     SaveOnlyDrawsRestoreNooper onlyDraws;
168     SaveNoDrawsRestoreNooper noDraws;
169 
170     // Run until they stop changing things.
171     while (apply(&onlyDraws, record) || apply(&noDraws, record));
172 }
173 
174 #ifndef SK_BUILD_FOR_ANDROID_FRAMEWORK
effectively_srcover(const SkPaint * paint)175 static bool effectively_srcover(const SkPaint* paint) {
176     if (!paint || paint->isSrcOver()) {
177         return true;
178     }
179     // src-mode with opaque and no effects (which might change opaqueness) is ok too.
180     return !paint->getShader() && !paint->getColorFilter() && !paint->getImageFilter() &&
181            0xFF == paint->getAlpha() && paint->getBlendMode() == SkBlendMode::kSrc;
182 }
183 
184 // For some SaveLayer-[drawing command]-Restore patterns, merge the SaveLayer's alpha into the
185 // draw, and no-op the SaveLayer and Restore.
186 struct SaveLayerDrawRestoreNooper {
187     typedef Pattern<Is<SaveLayer>, IsDraw, Is<Restore>> Match;
188 
onMatchSaveLayerDrawRestoreNooper189     bool onMatch(SkRecord* record, Match* match, int begin, int end) {
190         if (match->first<SaveLayer>()->backdrop || match->first<SaveLayer>()->clipMask) {
191             // can't throw away the layer if we have a backdrop or clip mask
192             return false;
193         }
194 
195         if (match->first<SaveLayer>()->saveLayerFlags & (1U << 31)) {
196             // can't throw away the layer if the kDontClipToLayer_PrivateSaveLayerFlag is set
197             return false;
198         }
199 
200         // A SaveLayer's bounds field is just a hint, so we should be free to ignore it.
201         SkPaint* layerPaint = match->first<SaveLayer>()->paint;
202         SkPaint* drawPaint = match->second<SkPaint>();
203 
204         if (nullptr == layerPaint && effectively_srcover(drawPaint)) {
205             // There wasn't really any point to this SaveLayer at all.
206             return KillSaveLayerAndRestore(record, begin);
207         }
208 
209         if (drawPaint == nullptr) {
210             // We can just give the draw the SaveLayer's paint.
211             // TODO(mtklein): figure out how to do this clearly
212             return false;
213         }
214 
215         if (!fold_opacity_layer_color_to_paint(layerPaint, false /*isSaveLayer*/, drawPaint)) {
216             return false;
217         }
218 
219         return KillSaveLayerAndRestore(record, begin);
220     }
221 
KillSaveLayerAndRestoreSaveLayerDrawRestoreNooper222     static bool KillSaveLayerAndRestore(SkRecord* record, int saveLayerIndex) {
223         record->replace<NoOp>(saveLayerIndex);    // SaveLayer
224         record->replace<NoOp>(saveLayerIndex+2);  // Restore
225         return true;
226     }
227 };
SkRecordNoopSaveLayerDrawRestores(SkRecord * record)228 void SkRecordNoopSaveLayerDrawRestores(SkRecord* record) {
229     SaveLayerDrawRestoreNooper pass;
230     apply(&pass, record);
231 }
232 #endif
233 
234 /* For SVG generated:
235   SaveLayer (non-opaque, typically for CSS opacity)
236     Save
237       ClipRect
238       SaveLayer (typically for SVG filter)
239       Restore
240     Restore
241   Restore
242 */
243 struct SvgOpacityAndFilterLayerMergePass {
244     typedef Pattern<Is<SaveLayer>, Is<Save>, Is<ClipRect>, Is<SaveLayer>,
245                     Is<Restore>, Is<Restore>, Is<Restore>> Match;
246 
onMatchSvgOpacityAndFilterLayerMergePass247     bool onMatch(SkRecord* record, Match* match, int begin, int end) {
248         if (match->first<SaveLayer>()->backdrop) {
249             // can't throw away the layer if we have a backdrop
250             return false;
251         }
252 
253         SkPaint* opacityPaint = match->first<SaveLayer>()->paint;
254         if (nullptr == opacityPaint) {
255             // There wasn't really any point to this SaveLayer at all.
256             return KillSaveLayerAndRestore(record, begin);
257         }
258 
259         // This layer typically contains a filter, but this should work for layers with for other
260         // purposes too.
261         SkPaint* filterLayerPaint = match->fourth<SaveLayer>()->paint;
262         if (filterLayerPaint == nullptr) {
263             // We can just give the inner SaveLayer the paint of the outer SaveLayer.
264             // TODO(mtklein): figure out how to do this clearly
265             return false;
266         }
267 
268         if (!fold_opacity_layer_color_to_paint(opacityPaint, true /*isSaveLayer*/,
269                                                filterLayerPaint)) {
270             return false;
271         }
272 
273         return KillSaveLayerAndRestore(record, begin);
274     }
275 
KillSaveLayerAndRestoreSvgOpacityAndFilterLayerMergePass276     static bool KillSaveLayerAndRestore(SkRecord* record, int saveLayerIndex) {
277         record->replace<NoOp>(saveLayerIndex);     // SaveLayer
278         record->replace<NoOp>(saveLayerIndex + 6); // Restore
279         return true;
280     }
281 };
282 
SkRecordMergeSvgOpacityAndFilterLayers(SkRecord * record)283 void SkRecordMergeSvgOpacityAndFilterLayers(SkRecord* record) {
284     SvgOpacityAndFilterLayerMergePass pass;
285     apply(&pass, record);
286 }
287 
288 ///////////////////////////////////////////////////////////////////////////////////////////////////
289 
SkRecordOptimize(SkRecord * record)290 void SkRecordOptimize(SkRecord* record) {
291     // This might be useful  as a first pass in the future if we want to weed
292     // out junk for other optimization passes.  Right now, nothing needs it,
293     // and the bounding box hierarchy will do the work of skipping no-op
294     // Save-NoDraw-Restore sequences better than we can here.
295     // As there is a known problem with this peephole and drawAnnotation, disable this.
296     // If we want to enable this we must first fix this bug:
297     //     https://bugs.chromium.org/p/skia/issues/detail?id=5548
298 //    SkRecordNoopSaveRestores(record);
299 
300     // Turn off this optimization completely for Android framework
301     // because it makes the following Android CTS test fail:
302     // android.uirendering.cts.testclasses.LayerTests#testSaveLayerClippedWithAlpha
303 #ifndef SK_BUILD_FOR_ANDROID_FRAMEWORK
304     SkRecordNoopSaveLayerDrawRestores(record);
305 #endif
306     SkRecordMergeSvgOpacityAndFilterLayers(record);
307 
308     record->defrag();
309 }
310 
SkRecordOptimize2(SkRecord * record)311 void SkRecordOptimize2(SkRecord* record) {
312     multiple_set_matrices(record);
313     SkRecordNoopSaveRestores(record);
314     // See why we turn this off in SkRecordOptimize above.
315 #ifndef SK_BUILD_FOR_ANDROID_FRAMEWORK
316     SkRecordNoopSaveLayerDrawRestores(record);
317 #endif
318     SkRecordMergeSvgOpacityAndFilterLayers(record);
319 
320     record->defrag();
321 }
322