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->getXfermode() || 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     const uint32_t layerColor = layerPaint.getColor();
124     // The layer paint color must have only alpha component.
125     if (SK_ColorTRANSPARENT != SkColorSetA(layerColor, SK_AlphaTRANSPARENT)) {
126         return false;
127     }
128 
129     // The layer paint can not have any effects.
130     if (layerPaint.getPathEffect() ||
131         layerPaint.getShader()      ||
132         layerPaint.getXfermode()    ||
133         layerPaint.getMaskFilter()  ||
134         layerPaint.getColorFilter() ||
135         layerPaint.getRasterizer()  ||
136         layerPaint.getLooper()      ||
137         layerPaint.getImageFilter()) {
138         return false;
139     }
140 
141     paint->setAlpha(SkMulDiv255Round(paint->getAlpha(), SkColorGetA(layerColor)));
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 // For some SaveLayer-[drawing command]-Restore patterns, merge the SaveLayer's alpha into the
175 // draw, and no-op the SaveLayer and Restore.
176 struct SaveLayerDrawRestoreNooper {
177     typedef Pattern<Is<SaveLayer>, IsDraw, Is<Restore>> Match;
178 
onMatchSaveLayerDrawRestoreNooper179     bool onMatch(SkRecord* record, Match* match, int begin, int end) {
180         if (match->first<SaveLayer>()->backdrop) {
181             // can't throw away the layer if we have a backdrop
182             return false;
183         }
184 
185         // A SaveLayer's bounds field is just a hint, so we should be free to ignore it.
186         SkPaint* layerPaint = match->first<SaveLayer>()->paint;
187         if (nullptr == layerPaint) {
188             // There wasn't really any point to this SaveLayer at all.
189             return KillSaveLayerAndRestore(record, begin);
190         }
191 
192         SkPaint* drawPaint = match->second<SkPaint>();
193         if (drawPaint == nullptr) {
194             // We can just give the draw the SaveLayer's paint.
195             // TODO(mtklein): figure out how to do this clearly
196             return false;
197         }
198 
199         if (!fold_opacity_layer_color_to_paint(*layerPaint, false /*isSaveLayer*/, drawPaint)) {
200             return false;
201         }
202 
203         return KillSaveLayerAndRestore(record, begin);
204     }
205 
KillSaveLayerAndRestoreSaveLayerDrawRestoreNooper206     static bool KillSaveLayerAndRestore(SkRecord* record, int saveLayerIndex) {
207         record->replace<NoOp>(saveLayerIndex);    // SaveLayer
208         record->replace<NoOp>(saveLayerIndex+2);  // Restore
209         return true;
210     }
211 };
SkRecordNoopSaveLayerDrawRestores(SkRecord * record)212 void SkRecordNoopSaveLayerDrawRestores(SkRecord* record) {
213     SaveLayerDrawRestoreNooper pass;
214     apply(&pass, record);
215 }
216 
217 
218 /* For SVG generated:
219   SaveLayer (non-opaque, typically for CSS opacity)
220     Save
221       ClipRect
222       SaveLayer (typically for SVG filter)
223       Restore
224     Restore
225   Restore
226 */
227 struct SvgOpacityAndFilterLayerMergePass {
228     typedef Pattern<Is<SaveLayer>, Is<Save>, Is<ClipRect>, Is<SaveLayer>,
229                     Is<Restore>, Is<Restore>, Is<Restore>> Match;
230 
onMatchSvgOpacityAndFilterLayerMergePass231     bool onMatch(SkRecord* record, Match* match, int begin, int end) {
232         if (match->first<SaveLayer>()->backdrop) {
233             // can't throw away the layer if we have a backdrop
234             return false;
235         }
236 
237         SkPaint* opacityPaint = match->first<SaveLayer>()->paint;
238         if (nullptr == opacityPaint) {
239             // There wasn't really any point to this SaveLayer at all.
240             return KillSaveLayerAndRestore(record, begin);
241         }
242 
243         // This layer typically contains a filter, but this should work for layers with for other
244         // purposes too.
245         SkPaint* filterLayerPaint = match->fourth<SaveLayer>()->paint;
246         if (filterLayerPaint == nullptr) {
247             // We can just give the inner SaveLayer the paint of the outer SaveLayer.
248             // TODO(mtklein): figure out how to do this clearly
249             return false;
250         }
251 
252         if (!fold_opacity_layer_color_to_paint(*opacityPaint, true /*isSaveLayer*/,
253                                                filterLayerPaint)) {
254             return false;
255         }
256 
257         return KillSaveLayerAndRestore(record, begin);
258     }
259 
KillSaveLayerAndRestoreSvgOpacityAndFilterLayerMergePass260     static bool KillSaveLayerAndRestore(SkRecord* record, int saveLayerIndex) {
261         record->replace<NoOp>(saveLayerIndex);     // SaveLayer
262         record->replace<NoOp>(saveLayerIndex + 6); // Restore
263         return true;
264     }
265 };
266 
SkRecordMergeSvgOpacityAndFilterLayers(SkRecord * record)267 void SkRecordMergeSvgOpacityAndFilterLayers(SkRecord* record) {
268     SvgOpacityAndFilterLayerMergePass pass;
269     apply(&pass, record);
270 }
271 
272 ///////////////////////////////////////////////////////////////////////////////////////////////////
273 
SkRecordOptimize(SkRecord * record)274 void SkRecordOptimize(SkRecord* record) {
275     // This might be useful  as a first pass in the future if we want to weed
276     // out junk for other optimization passes.  Right now, nothing needs it,
277     // and the bounding box hierarchy will do the work of skipping no-op
278     // Save-NoDraw-Restore sequences better than we can here.
279     //SkRecordNoopSaveRestores(record);
280 
281     SkRecordNoopSaveLayerDrawRestores(record);
282     SkRecordMergeSvgOpacityAndFilterLayers(record);
283 
284     record->defrag();
285 }
286 
SkRecordOptimize2(SkRecord * record)287 void SkRecordOptimize2(SkRecord* record) {
288     multiple_set_matrices(record);
289     SkRecordNoopSaveRestores(record);
290     SkRecordNoopSaveLayerDrawRestores(record);
291     SkRecordMergeSvgOpacityAndFilterLayers(record);
292 
293     record->defrag();
294 }
295 
296