• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2012 The Android Open Source Project
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 "include/core/SkImageFilter.h"
9 
10 #include "include/core/SkCanvas.h"
11 #include "include/core/SkRect.h"
12 #include "include/private/SkSafe32.h"
13 #include "src/core/SkFuzzLogging.h"
14 #include "src/core/SkImageFilterCache.h"
15 #include "src/core/SkImageFilter_Base.h"
16 #include "src/core/SkLocalMatrixImageFilter.h"
17 #include "src/core/SkMatrixImageFilter.h"
18 #include "src/core/SkReadBuffer.h"
19 #include "src/core/SkSpecialImage.h"
20 #include "src/core/SkSpecialSurface.h"
21 #include "src/core/SkValidationUtils.h"
22 #include "src/core/SkWriteBuffer.h"
23 #if SK_SUPPORT_GPU
24 #include "include/gpu/GrRecordingContext.h"
25 #include "src/gpu/GrColorSpaceXform.h"
26 #include "src/gpu/GrDirectContextPriv.h"
27 #include "src/gpu/GrRecordingContextPriv.h"
28 #include "src/gpu/GrTextureProxy.h"
29 #include "src/gpu/SkGr.h"
30 #include "src/gpu/SurfaceFillContext.h"
31 #endif
32 #include <atomic>
33 
34 ///////////////////////////////////////////////////////////////////////////////////////////////////
35 // SkImageFilter - A number of the public APIs on SkImageFilter downcast to SkImageFilter_Base
36 // in order to perform their actual work.
37 ///////////////////////////////////////////////////////////////////////////////////////////////////
38 
39 /**
40  *  Returns the number of inputs this filter will accept (some inputs can
41  *  be NULL).
42  */
countInputs() const43 int SkImageFilter::countInputs() const { return as_IFB(this)->fInputs.count(); }
44 
45 /**
46  *  Returns the input filter at a given index, or NULL if no input is
47  *  connected.  The indices used are filter-specific.
48  */
getInput(int i) const49 const SkImageFilter* SkImageFilter::getInput(int i) const {
50     SkASSERT(i < this->countInputs());
51     return as_IFB(this)->fInputs[i].get();
52 }
53 
isColorFilterNode(SkColorFilter ** filterPtr) const54 bool SkImageFilter::isColorFilterNode(SkColorFilter** filterPtr) const {
55     return as_IFB(this)->onIsColorFilterNode(filterPtr);
56 }
57 
filterBounds(const SkIRect & src,const SkMatrix & ctm,MapDirection direction,const SkIRect * inputRect) const58 SkIRect SkImageFilter::filterBounds(const SkIRect& src, const SkMatrix& ctm,
59                                     MapDirection direction, const SkIRect* inputRect) const {
60     // The old filterBounds() function uses SkIRects that are defined in layer space so, while
61     // we still are supporting it, bypass SkIF_B's new public filter bounds functions and go right
62     // to the internal layer-space calculations.
63     skif::Mapping mapping(SkMatrix::I(), ctm);
64     if (kReverse_MapDirection == direction) {
65         skif::LayerSpace<SkIRect> targetOutput(src);
66         if (as_IFB(this)->cropRectIsSet()) {
67            skif::LayerSpace<SkIRect> outputCrop = mapping.paramToLayer(
68                     skif::ParameterSpace<SkRect>(as_IFB(this)->getCropRect().rect())).roundOut();
69             // Just intersect directly; unlike the forward-mapping case, since we start with the
70             // external target output, there's no need to embiggen due to affecting trans. black
71             if (!targetOutput.intersect(outputCrop)) {
72                 // Nothing would be output by the filter, so return empty rect
73                 return SkIRect::MakeEmpty();
74             }
75         }
76         skif::LayerSpace<SkIRect> content(inputRect ? *inputRect : src);
77         return SkIRect(as_IFB(this)->onGetInputLayerBounds(mapping, targetOutput, content));
78     } else {
79         SkASSERT(!inputRect);
80         skif::LayerSpace<SkIRect> content(src);
81         skif::LayerSpace<SkIRect> output = as_IFB(this)->onGetOutputLayerBounds(mapping, content);
82         // Manually apply the crop rect for now, until cropping is performed by a dedicated SkIF.
83         SkIRect dst;
84         as_IFB(this)->getCropRect().applyTo(
85                 SkIRect(output), ctm, as_IFB(this)->onAffectsTransparentBlack(), &dst);
86         return dst;
87     }
88 }
89 
computeFastBounds(const SkRect & src) const90 SkRect SkImageFilter::computeFastBounds(const SkRect& src) const {
91     if (0 == this->countInputs()) {
92         return src;
93     }
94     SkRect combinedBounds = this->getInput(0) ? this->getInput(0)->computeFastBounds(src) : src;
95     for (int i = 1; i < this->countInputs(); i++) {
96         const SkImageFilter* input = this->getInput(i);
97         if (input) {
98             combinedBounds.join(input->computeFastBounds(src));
99         } else {
100             combinedBounds.join(src);
101         }
102     }
103     return combinedBounds;
104 }
105 
canComputeFastBounds() const106 bool SkImageFilter::canComputeFastBounds() const {
107     return !as_IFB(this)->affectsTransparentBlack();
108 }
109 
affectsTransparentBlack() const110 bool SkImageFilter_Base::affectsTransparentBlack() const {
111     if (this->onAffectsTransparentBlack()) {
112         return true;
113     }
114     for (int i = 0; i < this->countInputs(); i++) {
115         const SkImageFilter* input = this->getInput(i);
116         if (input && as_IFB(input)->affectsTransparentBlack()) {
117             return true;
118         }
119     }
120     return false;
121 }
122 
asAColorFilter(SkColorFilter ** filterPtr) const123 bool SkImageFilter::asAColorFilter(SkColorFilter** filterPtr) const {
124     SkASSERT(nullptr != filterPtr);
125     if (!this->isColorFilterNode(filterPtr)) {
126         return false;
127     }
128     if (nullptr != this->getInput(0) || as_CFB(*filterPtr)->affectsTransparentBlack()) {
129         (*filterPtr)->unref();
130         return false;
131     }
132     return true;
133 }
134 
makeWithLocalMatrix(const SkMatrix & matrix) const135 sk_sp<SkImageFilter> SkImageFilter::makeWithLocalMatrix(const SkMatrix& matrix) const {
136     return SkLocalMatrixImageFilter::Make(matrix, this->refMe());
137 }
138 
139 ///////////////////////////////////////////////////////////////////////////////////////////////////
140 // SkImageFilter_Base
141 ///////////////////////////////////////////////////////////////////////////////////////////////////
142 
next_image_filter_unique_id()143 static int32_t next_image_filter_unique_id() {
144     static std::atomic<int32_t> nextID{1};
145 
146     int32_t id;
147     do {
148         id = nextID.fetch_add(1, std::memory_order_relaxed);
149     } while (id == 0);
150     return id;
151 }
152 
SkImageFilter_Base(sk_sp<SkImageFilter> const * inputs,int inputCount,const SkRect * cropRect)153 SkImageFilter_Base::SkImageFilter_Base(sk_sp<SkImageFilter> const* inputs,
154                                        int inputCount, const SkRect* cropRect)
155         : fUsesSrcInput(false)
156         , fCropRect(cropRect)
157         , fUniqueID(next_image_filter_unique_id()) {
158     fInputs.reset(inputCount);
159 
160     for (int i = 0; i < inputCount; ++i) {
161         if (!inputs[i] || as_IFB(inputs[i])->fUsesSrcInput) {
162             fUsesSrcInput = true;
163         }
164         fInputs[i] = inputs[i];
165     }
166 }
167 
~SkImageFilter_Base()168 SkImageFilter_Base::~SkImageFilter_Base() {
169     SkImageFilterCache::Get()->purgeByImageFilter(this);
170 }
171 
unflatten(SkReadBuffer & buffer,int expectedCount)172 bool SkImageFilter_Base::Common::unflatten(SkReadBuffer& buffer, int expectedCount) {
173     const int count = buffer.readInt();
174     if (!buffer.validate(count >= 0)) {
175         return false;
176     }
177     if (!buffer.validate(expectedCount < 0 || count == expectedCount)) {
178         return false;
179     }
180 
181 #if defined(SK_BUILD_FOR_FUZZER)
182     if (count > 4) {
183         return false;
184     }
185 #endif
186 
187     SkASSERT(fInputs.empty());
188     for (int i = 0; i < count; i++) {
189         fInputs.push_back(buffer.readBool() ? buffer.readImageFilter() : nullptr);
190         if (!buffer.isValid()) {
191             return false;
192         }
193     }
194     SkRect rect;
195     buffer.readRect(&rect);
196     if (!buffer.isValid() || !buffer.validate(SkIsValidRect(rect))) {
197         return false;
198     }
199 
200     uint32_t flags = buffer.readUInt();
201     if (!buffer.isValid() ||
202         !buffer.validate(flags == 0x0 || flags == CropRect::kHasAll_CropEdge)) {
203         return false;
204     }
205     fCropRect = CropRect(flags ? &rect : nullptr);
206     return buffer.isValid();
207 }
208 
flatten(SkWriteBuffer & buffer) const209 void SkImageFilter_Base::flatten(SkWriteBuffer& buffer) const {
210     buffer.writeInt(fInputs.count());
211     for (int i = 0; i < fInputs.count(); i++) {
212         const SkImageFilter* input = this->getInput(i);
213         buffer.writeBool(input != nullptr);
214         if (input != nullptr) {
215             buffer.writeFlattenable(input);
216         }
217     }
218     buffer.writeRect(fCropRect.rect());
219     buffer.writeUInt(fCropRect.flags());
220 }
221 
filterImage(const skif::Context & context) const222 skif::FilterResult SkImageFilter_Base::filterImage(const skif::Context& context) const {
223     // TODO (michaelludwig) - Old filters have an implicit assumption that the source image
224     // (originally passed separately) has an origin of (0, 0). SkComposeImageFilter makes an effort
225     // to ensure that remains the case. Once everyone uses the new type systems for bounds, non
226     // (0, 0) source origins will be easy to support.
227     SkASSERT(context.source().layerOrigin().x() == 0 && context.source().layerOrigin().y() == 0);
228 
229     skif::FilterResult result;
230     if (!context.isValid()) {
231         return result;
232     }
233 
234     uint32_t srcGenID = fUsesSrcInput ? context.sourceImage()->uniqueID() : 0;
235     const SkIRect srcSubset = fUsesSrcInput ? context.sourceImage()->subset()
236                                             : SkIRect::MakeWH(0, 0);
237 
238     SkImageFilterCacheKey key(fUniqueID, context.mapping().layerMatrix(), context.clipBounds(),
239                               srcGenID, srcSubset);
240     if (context.cache() && context.cache()->get(key, &result)) {
241         return result;
242     }
243 
244     result = this->onFilterImage(context);
245 
246     if (context.gpuBacked()) {
247         SkASSERT(!result.image() || result.image()->isTextureBacked());
248     }
249 
250     if (context.cache()) {
251         context.cache()->set(key, this, result);
252     }
253 
254     return result;
255 }
256 
getInputBounds(const skif::Mapping & mapping,const skif::DeviceSpace<SkIRect> & desiredOutput,const skif::ParameterSpace<SkRect> * knownContentBounds) const257 skif::LayerSpace<SkIRect> SkImageFilter_Base::getInputBounds(
258         const skif::Mapping& mapping, const skif::DeviceSpace<SkIRect>& desiredOutput,
259         const skif::ParameterSpace<SkRect>* knownContentBounds) const {
260     // Map both the device-space desired coverage area and the known content bounds to layer space
261     skif::LayerSpace<SkIRect> desiredBounds = mapping.deviceToLayer(desiredOutput);
262 
263     // TODO (michaelludwig) - To be removed once cropping is its own filter, since then an output
264     // crop would automatically adjust the required input of its child filter in this same way.
265     if (this->cropRectIsSet()) {
266         skif::LayerSpace<SkIRect> outputCrop =
267                 mapping.paramToLayer(skif::ParameterSpace<SkRect>(fCropRect.rect())).roundOut();
268         if (!desiredBounds.intersect(outputCrop)) {
269             // Nothing would be output by the filter, so return empty rect
270             return skif::LayerSpace<SkIRect>(SkIRect::MakeEmpty());
271         }
272     }
273 
274     // If we have no known content bounds use the desired coverage area, because that is the most
275     // conservative possibility.
276     skif::LayerSpace<SkIRect> contentBounds =
277             knownContentBounds ? mapping.paramToLayer(*knownContentBounds).roundOut()
278                                : desiredBounds;
279 
280     // Process the layer-space desired output with the filter DAG to determine required input
281     skif::LayerSpace<SkIRect> requiredInput = this->onGetInputLayerBounds(
282             mapping, desiredBounds, contentBounds);
283     // If we know what's actually going to be drawn into the layer, and we don't change transparent
284     // black, then we can further restrict the layer to what the known content is
285     // TODO (michaelludwig) - This logic could be moved into visitInputLayerBounds() when an input
286     // filter is null. Additionally, once all filters are robust to FilterResults with tile modes,
287     // we can always restrict the required input by content bounds since any additional transparent
288     // black is handled when producing the output result and sampling outside the input image with
289     // a decal tile mode.
290     if (knownContentBounds && !this->affectsTransparentBlack()) {
291         if (!requiredInput.intersect(contentBounds)) {
292             // Nothing would be output by the filter, so return empty rect
293             return skif::LayerSpace<SkIRect>(SkIRect::MakeEmpty());
294         }
295     }
296     return requiredInput;
297 }
298 
getOutputBounds(const skif::Mapping & mapping,const skif::ParameterSpace<SkRect> & contentBounds) const299 skif::DeviceSpace<SkIRect> SkImageFilter_Base::getOutputBounds(
300         const skif::Mapping& mapping, const skif::ParameterSpace<SkRect>& contentBounds) const {
301     // Map the input content into the layer space where filtering will occur
302     skif::LayerSpace<SkRect> layerContent = mapping.paramToLayer(contentBounds);
303     // Determine the filter DAGs output bounds in layer space
304     skif::LayerSpace<SkIRect> filterOutput = this->onGetOutputLayerBounds(
305             mapping, layerContent.roundOut());
306     // FIXME (michaelludwig) - To be removed once cropping is isolated, but remain consistent with
307     // old filterBounds(kForward) behavior.
308     SkIRect dst;
309     as_IFB(this)->getCropRect().applyTo(
310             SkIRect(filterOutput), mapping.layerMatrix(),
311             as_IFB(this)->onAffectsTransparentBlack(), &dst);
312 
313     // Map all the way to device space
314     return mapping.layerToDevice(skif::LayerSpace<SkIRect>(dst));
315 }
316 
317 // TODO (michaelludwig) - Default to using the old onFilterImage, as filters are updated one by one.
318 // Once the old function is gone, this onFilterImage() will be made a pure virtual.
onFilterImage(const skif::Context & context) const319 skif::FilterResult SkImageFilter_Base::onFilterImage(const skif::Context& context) const {
320     SkIPoint origin;
321     auto image = this->onFilterImage(context, &origin);
322     return skif::FilterResult(std::move(image), skif::LayerSpace<SkIPoint>(origin));
323 }
324 
getCTMCapability() const325 SkImageFilter_Base::MatrixCapability SkImageFilter_Base::getCTMCapability() const {
326     MatrixCapability result = this->onGetCTMCapability();
327     // CropRects need to apply in the source coordinate system, but are not aware of complex CTMs
328     // when performing clipping. For a simple fix, any filter with a crop rect set cannot support
329     // more than scale+translate CTMs until that's updated.
330     if (this->cropRectIsSet()) {
331         result = std::min(result, MatrixCapability::kScaleTranslate);
332     }
333     const int count = this->countInputs();
334     for (int i = 0; i < count; ++i) {
335         if (const SkImageFilter_Base* input = as_IFB(this->getInput(i))) {
336             result = std::min(result, input->getCTMCapability());
337         }
338     }
339     return result;
340 }
341 
applyTo(const SkIRect & imageBounds,const SkMatrix & ctm,bool embiggen,SkIRect * cropped) const342 void SkImageFilter_Base::CropRect::applyTo(const SkIRect& imageBounds, const SkMatrix& ctm,
343                                            bool embiggen, SkIRect* cropped) const {
344     *cropped = imageBounds;
345     if (fFlags) {
346         SkRect devCropR;
347         ctm.mapRect(&devCropR, fRect);
348         SkIRect devICropR = devCropR.roundOut();
349 
350         // Compute the left/top first, in case we need to modify the right/bottom for a missing edge
351         if (fFlags & kHasLeft_CropEdge) {
352             if (embiggen || devICropR.fLeft > cropped->fLeft) {
353                 cropped->fLeft = devICropR.fLeft;
354             }
355         } else {
356             devICropR.fRight = Sk32_sat_add(cropped->fLeft, devICropR.width());
357         }
358         if (fFlags & kHasTop_CropEdge) {
359             if (embiggen || devICropR.fTop > cropped->fTop) {
360                 cropped->fTop = devICropR.fTop;
361             }
362         } else {
363             devICropR.fBottom = Sk32_sat_add(cropped->fTop, devICropR.height());
364         }
365         if (fFlags & kHasWidth_CropEdge) {
366             if (embiggen || devICropR.fRight < cropped->fRight) {
367                 cropped->fRight = devICropR.fRight;
368             }
369         }
370         if (fFlags & kHasHeight_CropEdge) {
371             if (embiggen || devICropR.fBottom < cropped->fBottom) {
372                 cropped->fBottom = devICropR.fBottom;
373             }
374         }
375     }
376 }
377 
applyCropRect(const Context & ctx,const SkIRect & srcBounds,SkIRect * dstBounds) const378 bool SkImageFilter_Base::applyCropRect(const Context& ctx, const SkIRect& srcBounds,
379                                        SkIRect* dstBounds) const {
380     SkIRect tmpDst = this->onFilterNodeBounds(srcBounds, ctx.ctm(), kForward_MapDirection, nullptr);
381     fCropRect.applyTo(tmpDst, ctx.ctm(), this->onAffectsTransparentBlack(), dstBounds);
382     // Intersect against the clip bounds, in case the crop rect has
383     // grown the bounds beyond the original clip. This can happen for
384     // example in tiling, where the clip is much smaller than the filtered
385     // primitive. If we didn't do this, we would be processing the filter
386     // at the full crop rect size in every tile.
387     return dstBounds->intersect(ctx.clipBounds());
388 }
389 
390 // Return a larger (newWidth x newHeight) copy of 'src' with black padding
391 // around it.
pad_image(SkSpecialImage * src,const SkImageFilter_Base::Context & ctx,int newWidth,int newHeight,int offX,int offY)392 static sk_sp<SkSpecialImage> pad_image(SkSpecialImage* src, const SkImageFilter_Base::Context& ctx,
393                                        int newWidth, int newHeight, int offX, int offY) {
394     // We would like to operate in the source's color space (so that we return an "identical"
395     // image, other than the padding. To achieve that, we'd create a new context using
396     // src->getColorSpace() to replace ctx.colorSpace().
397 
398     // That fails in at least two ways. For formats that are texturable but not renderable (like
399     // F16 on some ES implementations), we can't create a surface to do the work. For sRGB, images
400     // may be tagged with an sRGB color space (which leads to an sRGB config in makeSurface). But
401     // the actual config of that sRGB image on a device with no sRGB support is non-sRGB.
402     //
403     // Rather than try to special case these situations, we execute the image padding in the
404     // destination color space. This should not affect the output of the DAG in (almost) any case,
405     // because the result of this call is going to be used as an input, where it would have been
406     // switched to the destination space anyway. The one exception would be a filter that expected
407     // to consume unclamped F16 data, but the padded version of the image is pre-clamped to 8888.
408     // We can revisit this logic if that ever becomes an actual problem.
409     sk_sp<SkSpecialSurface> surf(ctx.makeSurface(SkISize::Make(newWidth, newHeight)));
410     if (!surf) {
411         return nullptr;
412     }
413 
414     SkCanvas* canvas = surf->getCanvas();
415     SkASSERT(canvas);
416 
417     canvas->clear(0x0);
418 
419     src->draw(canvas, offX, offY);
420 
421     return surf->makeImageSnapshot();
422 }
423 
applyCropRectAndPad(const Context & ctx,SkSpecialImage * src,SkIPoint * srcOffset,SkIRect * bounds) const424 sk_sp<SkSpecialImage> SkImageFilter_Base::applyCropRectAndPad(const Context& ctx,
425                                                               SkSpecialImage* src,
426                                                               SkIPoint* srcOffset,
427                                                               SkIRect* bounds) const {
428     const SkIRect srcBounds = SkIRect::MakeXYWH(srcOffset->x(), srcOffset->y(),
429                                                 src->width(), src->height());
430 
431     if (!this->applyCropRect(ctx, srcBounds, bounds)) {
432         return nullptr;
433     }
434 
435     if (srcBounds.contains(*bounds)) {
436         return sk_sp<SkSpecialImage>(SkRef(src));
437     } else {
438         sk_sp<SkSpecialImage> img(pad_image(src, ctx, bounds->width(), bounds->height(),
439                                             Sk32_sat_sub(srcOffset->x(), bounds->x()),
440                                             Sk32_sat_sub(srcOffset->y(), bounds->y())));
441         *srcOffset = SkIPoint::Make(bounds->x(), bounds->y());
442         return img;
443     }
444 }
445 
446 // NOTE: The new onGetOutputLayerBounds() and onGetInputLayerBounds() default to calling into the
447 // deprecated onFilterBounds and onFilterNodeBounds. While these functions are not tagged, they do
448 // match the documented default behavior for the new bounds functions.
onFilterBounds(const SkIRect & src,const SkMatrix & ctm,MapDirection dir,const SkIRect * inputRect) const449 SkIRect SkImageFilter_Base::onFilterBounds(const SkIRect& src, const SkMatrix& ctm,
450                                            MapDirection dir, const SkIRect* inputRect) const {
451     if (this->countInputs() < 1) {
452         return src;
453     }
454 
455     SkIRect totalBounds;
456     for (int i = 0; i < this->countInputs(); ++i) {
457         const SkImageFilter* filter = this->getInput(i);
458         SkIRect rect = filter ? filter->filterBounds(src, ctm, dir, inputRect) : src;
459         if (0 == i) {
460             totalBounds = rect;
461         } else {
462             totalBounds.join(rect);
463         }
464     }
465 
466     return totalBounds;
467 }
468 
onFilterNodeBounds(const SkIRect & src,const SkMatrix &,MapDirection,const SkIRect *) const469 SkIRect SkImageFilter_Base::onFilterNodeBounds(const SkIRect& src, const SkMatrix&,
470                                                MapDirection, const SkIRect*) const {
471     return src;
472 }
473 
visitInputLayerBounds(const skif::Mapping & mapping,const skif::LayerSpace<SkIRect> & desiredOutput,const skif::LayerSpace<SkIRect> & contentBounds) const474 skif::LayerSpace<SkIRect> SkImageFilter_Base::visitInputLayerBounds(
475         const skif::Mapping& mapping, const skif::LayerSpace<SkIRect>& desiredOutput,
476         const skif::LayerSpace<SkIRect>& contentBounds) const {
477     if (this->countInputs() < 1) {
478         // TODO (michaelludwig) - if a filter doesn't have any inputs, it doesn't need any
479         // implicit source image, so arguably we could return an empty rect here. 'desiredOutput' is
480         // consistent with original behavior, so empty bounds may have unintended side effects
481         // but should be explored later. Of note is that right now an empty layer bounds assumes
482         // that there's no need to filter on restore, which is not the case for these filters.
483         return desiredOutput;
484     }
485 
486     skif::LayerSpace<SkIRect> netInput;
487     for (int i = 0; i < this->countInputs(); ++i) {
488         const SkImageFilter* filter = this->getInput(i);
489         // The required input for this input filter, or 'targetOutput' if the filter is null and
490         // the source image is used (so must be sized to cover 'targetOutput').
491         // TODO (michaelludwig) - Right now contentBounds is applied conditionally at the end of
492         // the root getInputLayerBounds() based on affecting transparent black. Once that bit only
493         // changes output behavior, we can have the required bounds for a null input filter be the
494         // intersection of the desired output and the content bounds.
495         skif::LayerSpace<SkIRect> requiredInput =
496                 filter ? as_IFB(filter)->onGetInputLayerBounds(mapping, desiredOutput,
497                                                                contentBounds)
498                        : desiredOutput;
499         // Accumulate with all other filters
500         if (i == 0) {
501             netInput = requiredInput;
502         } else {
503             netInput.join(requiredInput);
504         }
505     }
506     return netInput;
507 }
508 
visitOutputLayerBounds(const skif::Mapping & mapping,const skif::LayerSpace<SkIRect> & contentBounds) const509 skif::LayerSpace<SkIRect> SkImageFilter_Base::visitOutputLayerBounds(
510         const skif::Mapping& mapping, const skif::LayerSpace<SkIRect>& contentBounds) const {
511     if (this->countInputs() < 1) {
512         // TODO (michaelludwig) - if a filter doesn't have any inputs, it presumably is determining
513         // its output size from something other than the implicit source contentBounds, in which
514         // case it shouldn't be calling this helper function, so explore adding an unreachable test
515         return contentBounds;
516     }
517 
518     skif::LayerSpace<SkIRect> netOutput;
519     for (int i = 0; i < this->countInputs(); ++i) {
520         const SkImageFilter* filter = this->getInput(i);
521         // The output for just this input filter, or 'contentBounds' if the filter is null and
522         // the source image is used (i.e. the identity filter applied to the source).
523         skif::LayerSpace<SkIRect> output =
524                 filter ? as_IFB(filter)->onGetOutputLayerBounds(mapping, contentBounds)
525                        : contentBounds;
526         // Accumulate with all other filters
527         if (i == 0) {
528             netOutput = output;
529         } else {
530             netOutput.join(output);
531         }
532     }
533     return netOutput;
534 }
535 
onGetInputLayerBounds(const skif::Mapping & mapping,const skif::LayerSpace<SkIRect> & desiredOutput,const skif::LayerSpace<SkIRect> & contentBounds,VisitChildren recurse) const536 skif::LayerSpace<SkIRect> SkImageFilter_Base::onGetInputLayerBounds(
537         const skif::Mapping& mapping, const skif::LayerSpace<SkIRect>& desiredOutput,
538         const skif::LayerSpace<SkIRect>& contentBounds, VisitChildren recurse) const {
539     // Call old functions for now since they may have been overridden by a subclass that's not been
540     // updated yet; eventually this will be a pure virtual and impls control visiting children
541     SkIRect content = SkIRect(contentBounds);
542     SkIRect input = this->onFilterNodeBounds(SkIRect(desiredOutput), mapping.layerMatrix(),
543                                              kReverse_MapDirection, &content);
544     if (recurse == VisitChildren::kYes) {
545         SkIRect aggregate = this->onFilterBounds(input, mapping.layerMatrix(),
546                                                  kReverse_MapDirection, &input);
547         return skif::LayerSpace<SkIRect>(aggregate);
548     } else {
549         return skif::LayerSpace<SkIRect>(input);
550     }
551 }
552 
onGetOutputLayerBounds(const skif::Mapping & mapping,const skif::LayerSpace<SkIRect> & contentBounds) const553 skif::LayerSpace<SkIRect> SkImageFilter_Base::onGetOutputLayerBounds(
554         const skif::Mapping& mapping, const skif::LayerSpace<SkIRect>& contentBounds) const {
555     // Call old functions for now; eventually this will be a pure virtual
556     SkIRect aggregate = this->onFilterBounds(SkIRect(contentBounds), mapping.layerMatrix(),
557                                              kForward_MapDirection, nullptr);
558     SkIRect output = this->onFilterNodeBounds(aggregate, mapping.layerMatrix(),
559                                               kForward_MapDirection, nullptr);
560     return skif::LayerSpace<SkIRect>(output);
561 }
562 
filterInput(int index,const skif::Context & ctx) const563 skif::FilterResult SkImageFilter_Base::filterInput(int index, const skif::Context& ctx) const {
564     const SkImageFilter* input = this->getInput(index);
565     if (!input) {
566         // Null image filters late bind to the source image
567         return ctx.source();
568     }
569 
570     skif::FilterResult result = as_IFB(input)->filterImage(this->mapContext(ctx));
571     SkASSERT(!result.image() || ctx.gpuBacked() == result.image()->isTextureBacked());
572 
573     return result;
574 }
575 
mapContext(const Context & ctx) const576 SkImageFilter_Base::Context SkImageFilter_Base::mapContext(const Context& ctx) const {
577     // We don't recurse through the child input filters because that happens automatically
578     // as part of the filterImage() evaluation. In this case, we want the bounds for the
579     // edge from this node to its children, without the effects of the child filters.
580     skif::LayerSpace<SkIRect> childOutput = this->onGetInputLayerBounds(
581             ctx.mapping(), ctx.desiredOutput(), ctx.desiredOutput(), VisitChildren::kNo);
582     return ctx.withNewDesiredOutput(childOutput);
583 }
584 
585 #if SK_SUPPORT_GPU
DrawWithFP(GrRecordingContext * rContext,std::unique_ptr<GrFragmentProcessor> fp,const SkIRect & bounds,SkColorType colorType,const SkColorSpace * colorSpace,const SkSurfaceProps & surfaceProps,GrProtected isProtected)586 sk_sp<SkSpecialImage> SkImageFilter_Base::DrawWithFP(GrRecordingContext* rContext,
587                                                      std::unique_ptr<GrFragmentProcessor> fp,
588                                                      const SkIRect& bounds,
589                                                      SkColorType colorType,
590                                                      const SkColorSpace* colorSpace,
591                                                      const SkSurfaceProps& surfaceProps,
592                                                      GrProtected isProtected) {
593     GrImageInfo info(SkColorTypeToGrColorType(colorType),
594                      kPremul_SkAlphaType,
595                      sk_ref_sp(colorSpace),
596                      bounds.size());
597 
598     auto sfc = rContext->priv().makeSFC(info,
599                                         SkBackingFit::kApprox,
600                                         1,
601                                         GrMipmapped::kNo,
602                                         isProtected,
603                                         kBottomLeft_GrSurfaceOrigin);
604     if (!sfc) {
605         return nullptr;
606     }
607 
608     SkIRect dstIRect = SkIRect::MakeWH(bounds.width(), bounds.height());
609     SkRect srcRect = SkRect::Make(bounds);
610     sfc->fillRectToRectWithFP(srcRect, dstIRect, std::move(fp));
611 
612     return SkSpecialImage::MakeDeferredFromGpu(rContext,
613                                                dstIRect,
614                                                kNeedNewImageUniqueID_SpecialImage,
615                                                sfc->readSurfaceView(),
616                                                sfc->colorInfo().colorType(),
617                                                sfc->colorInfo().refColorSpace(),
618                                                surfaceProps);
619 }
620 
ImageToColorSpace(SkSpecialImage * src,SkColorType colorType,SkColorSpace * colorSpace,const SkSurfaceProps & surfaceProps)621 sk_sp<SkSpecialImage> SkImageFilter_Base::ImageToColorSpace(SkSpecialImage* src,
622                                                             SkColorType colorType,
623                                                             SkColorSpace* colorSpace,
624                                                             const SkSurfaceProps& surfaceProps) {
625     // There are several conditions that determine if we actually need to convert the source to the
626     // destination's color space. Rather than duplicate that logic here, just try to make an xform
627     // object. If that produces something, then both are tagged, and the source is in a different
628     // gamut than the dest. There is some overhead to making the xform, but those are cached, and
629     // if we get one back, that means we're about to use it during the conversion anyway.
630     auto colorSpaceXform = GrColorSpaceXform::Make(src->getColorSpace(),  src->alphaType(),
631                                                    colorSpace, kPremul_SkAlphaType);
632 
633     if (!colorSpaceXform) {
634         // No xform needed, just return the original image
635         return sk_ref_sp(src);
636     }
637 
638     sk_sp<SkSpecialSurface> surf(src->makeSurface(colorType, colorSpace,
639                                                   SkISize::Make(src->width(), src->height()),
640                                                   kPremul_SkAlphaType, surfaceProps));
641     if (!surf) {
642         return sk_ref_sp(src);
643     }
644 
645     SkCanvas* canvas = surf->getCanvas();
646     SkASSERT(canvas);
647     SkPaint p;
648     p.setBlendMode(SkBlendMode::kSrc);
649     src->draw(canvas, 0, 0, SkSamplingOptions(), &p);
650     return surf->makeImageSnapshot();
651 }
652 #endif
653 
654 // In repeat mode, when we are going to sample off one edge of the srcBounds we require the
655 // opposite side be preserved.
DetermineRepeatedSrcBound(const SkIRect & srcBounds,const SkIVector & filterOffset,const SkISize & filterSize,const SkIRect & originalSrcBounds)656 SkIRect SkImageFilter_Base::DetermineRepeatedSrcBound(const SkIRect& srcBounds,
657                                                       const SkIVector& filterOffset,
658                                                       const SkISize& filterSize,
659                                                       const SkIRect& originalSrcBounds) {
660     SkIRect tmp = srcBounds;
661     tmp.adjust(-filterOffset.fX, -filterOffset.fY,
662                filterSize.fWidth - filterOffset.fX, filterSize.fHeight - filterOffset.fY);
663 
664     if (tmp.fLeft < originalSrcBounds.fLeft || tmp.fRight > originalSrcBounds.fRight) {
665         tmp.fLeft = originalSrcBounds.fLeft;
666         tmp.fRight = originalSrcBounds.fRight;
667     }
668     if (tmp.fTop < originalSrcBounds.fTop || tmp.fBottom > originalSrcBounds.fBottom) {
669         tmp.fTop = originalSrcBounds.fTop;
670         tmp.fBottom = originalSrcBounds.fBottom;
671     }
672 
673     return tmp;
674 }
675 
PurgeCache()676 void SkImageFilter_Base::PurgeCache() {
677     SkImageFilterCache::Get()->purge();
678 }
679