• 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/base/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/SkReadBuffer.h"
18 #include "src/core/SkSpecialImage.h"
19 #include "src/core/SkSpecialSurface.h"
20 #include "src/core/SkValidationUtils.h"
21 #include "src/core/SkWriteBuffer.h"
22 #if defined(SK_GANESH)
23 #include "include/gpu/GrRecordingContext.h"
24 #include "src/gpu/SkBackingFit.h"
25 #include "src/gpu/ganesh/GrColorSpaceXform.h"
26 #include "src/gpu/ganesh/GrDirectContextPriv.h"
27 #include "src/gpu/ganesh/GrRecordingContextPriv.h"
28 #include "src/gpu/ganesh/GrTextureProxy.h"
29 #include "src/gpu/ganesh/SkGr.h"
30 #include "src/gpu/ganesh/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{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().layerBounds().left() == 0 &&
228              context.source().layerBounds().top() == 0 &&
229              context.source().layerBounds().right() == context.source().image()->width() &&
230              context.source().layerBounds().bottom() == context.source().image()->height());
231 
232     skif::FilterResult result;
233     if (context.desiredOutput().isEmpty() || !context.isValid()) {
234         return result;
235     }
236 
237     uint32_t srcGenID = fUsesSrcInput ? context.sourceImage()->uniqueID() : 0;
238     const SkIRect srcSubset = fUsesSrcInput ? context.sourceImage()->subset()
239                                             : SkIRect::MakeWH(0, 0);
240 
241     SkImageFilterCacheKey key(fUniqueID, context.mapping().layerMatrix(), context.clipBounds(),
242                               srcGenID, srcSubset);
243     if (context.cache() && context.cache()->get(key, &result)) {
244         return result;
245     }
246 
247     result = this->onFilterImage(context);
248 
249     if (context.gpuBacked()) {
250         SkASSERT(!result.image() || result.image()->isTextureBacked());
251     }
252 
253     if (context.cache()) {
254         context.cache()->set(key, this, result);
255     }
256 
257     return result;
258 }
259 
getInputBounds(const skif::Mapping & mapping,const skif::DeviceSpace<SkIRect> & desiredOutput,const skif::ParameterSpace<SkRect> * knownContentBounds) const260 skif::LayerSpace<SkIRect> SkImageFilter_Base::getInputBounds(
261         const skif::Mapping& mapping, const skif::DeviceSpace<SkIRect>& desiredOutput,
262         const skif::ParameterSpace<SkRect>* knownContentBounds) const {
263     // Map both the device-space desired coverage area and the known content bounds to layer space
264     skif::LayerSpace<SkIRect> desiredBounds = mapping.deviceToLayer(desiredOutput);
265 
266     // TODO (michaelludwig) - To be removed once cropping is its own filter, since then an output
267     // crop would automatically adjust the required input of its child filter in this same way.
268     if (this->cropRectIsSet()) {
269         skif::LayerSpace<SkIRect> outputCrop =
270                 mapping.paramToLayer(skif::ParameterSpace<SkRect>(fCropRect.rect())).roundOut();
271         if (!desiredBounds.intersect(outputCrop)) {
272             // Nothing would be output by the filter, so return empty rect
273             return skif::LayerSpace<SkIRect>(SkIRect::MakeEmpty());
274         }
275     }
276 
277     // If we have no known content bounds use the desired coverage area, because that is the most
278     // conservative possibility.
279     skif::LayerSpace<SkIRect> contentBounds =
280             knownContentBounds ? mapping.paramToLayer(*knownContentBounds).roundOut()
281                                : desiredBounds;
282 
283     // Process the layer-space desired output with the filter DAG to determine required input
284     skif::LayerSpace<SkIRect> requiredInput = this->onGetInputLayerBounds(
285             mapping, desiredBounds, contentBounds);
286     // If we know what's actually going to be drawn into the layer, and we don't change transparent
287     // black, then we can further restrict the layer to what the known content is
288     // TODO (michaelludwig) - This logic could be moved into visitInputLayerBounds() when an input
289     // filter is null. Additionally, once all filters are robust to FilterResults with tile modes,
290     // we can always restrict the required input by content bounds since any additional transparent
291     // black is handled when producing the output result and sampling outside the input image with
292     // a decal tile mode.
293     if (knownContentBounds && !this->affectsTransparentBlack()) {
294         if (!requiredInput.intersect(contentBounds)) {
295             // Nothing would be output by the filter, so return empty rect
296             return skif::LayerSpace<SkIRect>(SkIRect::MakeEmpty());
297         }
298     }
299     return requiredInput;
300 }
301 
getOutputBounds(const skif::Mapping & mapping,const skif::ParameterSpace<SkRect> & contentBounds) const302 skif::DeviceSpace<SkIRect> SkImageFilter_Base::getOutputBounds(
303         const skif::Mapping& mapping, const skif::ParameterSpace<SkRect>& contentBounds) const {
304     // Map the input content into the layer space where filtering will occur
305     skif::LayerSpace<SkRect> layerContent = mapping.paramToLayer(contentBounds);
306     // Determine the filter DAGs output bounds in layer space
307     skif::LayerSpace<SkIRect> filterOutput = this->onGetOutputLayerBounds(
308             mapping, layerContent.roundOut());
309     // FIXME (michaelludwig) - To be removed once cropping is isolated, but remain consistent with
310     // old filterBounds(kForward) behavior.
311     SkIRect dst;
312     as_IFB(this)->getCropRect().applyTo(
313             SkIRect(filterOutput), mapping.layerMatrix(),
314             as_IFB(this)->onAffectsTransparentBlack(), &dst);
315 
316     // Map all the way to device space
317     return mapping.layerToDevice(skif::LayerSpace<SkIRect>(dst));
318 }
319 
320 // TODO (michaelludwig) - Default to using the old onFilterImage, as filters are updated one by one.
321 // Once the old function is gone, this onFilterImage() will be made a pure virtual.
onFilterImage(const skif::Context & context) const322 skif::FilterResult SkImageFilter_Base::onFilterImage(const skif::Context& context) const {
323     SkIPoint origin = {0, 0};
324     auto image = this->onFilterImage(context, &origin);
325     return skif::FilterResult(std::move(image), skif::LayerSpace<SkIPoint>(origin));
326 }
327 
getCTMCapability() const328 SkImageFilter_Base::MatrixCapability SkImageFilter_Base::getCTMCapability() const {
329     MatrixCapability result = this->onGetCTMCapability();
330     // CropRects need to apply in the source coordinate system, but are not aware of complex CTMs
331     // when performing clipping. For a simple fix, any filter with a crop rect set cannot support
332     // more than scale+translate CTMs until that's updated.
333     if (this->cropRectIsSet()) {
334         result = std::min(result, MatrixCapability::kScaleTranslate);
335     }
336     const int count = this->countInputs();
337     for (int i = 0; i < count; ++i) {
338         if (const SkImageFilter_Base* input = as_IFB(this->getInput(i))) {
339             result = std::min(result, input->getCTMCapability());
340         }
341     }
342     return result;
343 }
344 
applyTo(const SkIRect & imageBounds,const SkMatrix & ctm,bool embiggen,SkIRect * cropped) const345 void SkImageFilter_Base::CropRect::applyTo(const SkIRect& imageBounds, const SkMatrix& ctm,
346                                            bool embiggen, SkIRect* cropped) const {
347     *cropped = imageBounds;
348     if (fFlags) {
349         SkRect devCropR;
350         ctm.mapRect(&devCropR, fRect);
351         SkIRect devICropR = devCropR.roundOut();
352 
353         // Compute the left/top first, in case we need to modify the right/bottom for a missing edge
354         if (fFlags & kHasLeft_CropEdge) {
355             if (embiggen || devICropR.fLeft > cropped->fLeft) {
356                 cropped->fLeft = devICropR.fLeft;
357             }
358         } else {
359             devICropR.fRight = Sk32_sat_add(cropped->fLeft, devICropR.width());
360         }
361         if (fFlags & kHasTop_CropEdge) {
362             if (embiggen || devICropR.fTop > cropped->fTop) {
363                 cropped->fTop = devICropR.fTop;
364             }
365         } else {
366             devICropR.fBottom = Sk32_sat_add(cropped->fTop, devICropR.height());
367         }
368         if (fFlags & kHasWidth_CropEdge) {
369             if (embiggen || devICropR.fRight < cropped->fRight) {
370                 cropped->fRight = devICropR.fRight;
371             }
372         }
373         if (fFlags & kHasHeight_CropEdge) {
374             if (embiggen || devICropR.fBottom < cropped->fBottom) {
375                 cropped->fBottom = devICropR.fBottom;
376             }
377         }
378     }
379 }
380 
applyCropRect(const Context & ctx,const SkIRect & srcBounds,SkIRect * dstBounds) const381 bool SkImageFilter_Base::applyCropRect(const Context& ctx, const SkIRect& srcBounds,
382                                        SkIRect* dstBounds) const {
383     SkIRect tmpDst = this->onFilterNodeBounds(srcBounds, ctx.ctm(), kForward_MapDirection, nullptr);
384     fCropRect.applyTo(tmpDst, ctx.ctm(), this->onAffectsTransparentBlack(), dstBounds);
385     // Intersect against the clip bounds, in case the crop rect has
386     // grown the bounds beyond the original clip. This can happen for
387     // example in tiling, where the clip is much smaller than the filtered
388     // primitive. If we didn't do this, we would be processing the filter
389     // at the full crop rect size in every tile.
390     return dstBounds->intersect(ctx.clipBounds());
391 }
392 
393 // Return a larger (newWidth x newHeight) copy of 'src' with black padding
394 // around it.
pad_image(SkSpecialImage * src,const SkImageFilter_Base::Context & ctx,int newWidth,int newHeight,int offX,int offY)395 static sk_sp<SkSpecialImage> pad_image(SkSpecialImage* src, const SkImageFilter_Base::Context& ctx,
396                                        int newWidth, int newHeight, int offX, int offY) {
397     // We would like to operate in the source's color space (so that we return an "identical"
398     // image, other than the padding. To achieve that, we'd create a new context using
399     // src->getColorSpace() to replace ctx.colorSpace().
400 
401     // That fails in at least two ways. For formats that are texturable but not renderable (like
402     // F16 on some ES implementations), we can't create a surface to do the work. For sRGB, images
403     // may be tagged with an sRGB color space (which leads to an sRGB config in makeSurface). But
404     // the actual config of that sRGB image on a device with no sRGB support is non-sRGB.
405     //
406     // Rather than try to special case these situations, we execute the image padding in the
407     // destination color space. This should not affect the output of the DAG in (almost) any case,
408     // because the result of this call is going to be used as an input, where it would have been
409     // switched to the destination space anyway. The one exception would be a filter that expected
410     // to consume unclamped F16 data, but the padded version of the image is pre-clamped to 8888.
411     // We can revisit this logic if that ever becomes an actual problem.
412     sk_sp<SkSpecialSurface> surf(ctx.makeSurface(SkISize::Make(newWidth, newHeight)));
413     if (!surf) {
414         return nullptr;
415     }
416 
417     SkCanvas* canvas = surf->getCanvas();
418     SkASSERT(canvas);
419 
420     canvas->clear(0x0);
421 
422     src->draw(canvas, offX, offY);
423 
424     return surf->makeImageSnapshot();
425 }
426 
applyCropRectAndPad(const Context & ctx,SkSpecialImage * src,SkIPoint * srcOffset,SkIRect * bounds) const427 sk_sp<SkSpecialImage> SkImageFilter_Base::applyCropRectAndPad(const Context& ctx,
428                                                               SkSpecialImage* src,
429                                                               SkIPoint* srcOffset,
430                                                               SkIRect* bounds) const {
431     const SkIRect srcBounds = SkIRect::MakeXYWH(srcOffset->x(), srcOffset->y(),
432                                                 src->width(), src->height());
433 
434     if (!this->applyCropRect(ctx, srcBounds, bounds)) {
435         return nullptr;
436     }
437 
438     if (srcBounds.contains(*bounds)) {
439         return sk_sp<SkSpecialImage>(SkRef(src));
440     } else {
441         sk_sp<SkSpecialImage> img(pad_image(src, ctx, bounds->width(), bounds->height(),
442                                             Sk32_sat_sub(srcOffset->x(), bounds->x()),
443                                             Sk32_sat_sub(srcOffset->y(), bounds->y())));
444         *srcOffset = SkIPoint::Make(bounds->x(), bounds->y());
445         return img;
446     }
447 }
448 
449 // NOTE: The new onGetOutputLayerBounds() and onGetInputLayerBounds() default to calling into the
450 // deprecated onFilterBounds and onFilterNodeBounds. While these functions are not tagged, they do
451 // match the documented default behavior for the new bounds functions.
onFilterBounds(const SkIRect & src,const SkMatrix & ctm,MapDirection dir,const SkIRect * inputRect) const452 SkIRect SkImageFilter_Base::onFilterBounds(const SkIRect& src, const SkMatrix& ctm,
453                                            MapDirection dir, const SkIRect* inputRect) const {
454     if (this->countInputs() < 1) {
455         return src;
456     }
457 
458     SkIRect totalBounds;
459     for (int i = 0; i < this->countInputs(); ++i) {
460         const SkImageFilter* filter = this->getInput(i);
461         SkIRect rect = filter ? filter->filterBounds(src, ctm, dir, inputRect) : src;
462         if (0 == i) {
463             totalBounds = rect;
464         } else {
465             totalBounds.join(rect);
466         }
467     }
468 
469     return totalBounds;
470 }
471 
onFilterNodeBounds(const SkIRect & src,const SkMatrix &,MapDirection,const SkIRect *) const472 SkIRect SkImageFilter_Base::onFilterNodeBounds(const SkIRect& src, const SkMatrix&,
473                                                MapDirection, const SkIRect*) const {
474     return src;
475 }
476 
visitInputLayerBounds(const skif::Mapping & mapping,const skif::LayerSpace<SkIRect> & desiredOutput,const skif::LayerSpace<SkIRect> & contentBounds) const477 skif::LayerSpace<SkIRect> SkImageFilter_Base::visitInputLayerBounds(
478         const skif::Mapping& mapping, const skif::LayerSpace<SkIRect>& desiredOutput,
479         const skif::LayerSpace<SkIRect>& contentBounds) const {
480     if (this->countInputs() < 1) {
481         // TODO (michaelludwig) - if a filter doesn't have any inputs, it doesn't need any
482         // implicit source image, so arguably we could return an empty rect here. 'desiredOutput' is
483         // consistent with original behavior, so empty bounds may have unintended side effects
484         // but should be explored later. Of note is that right now an empty layer bounds assumes
485         // that there's no need to filter on restore, which is not the case for these filters.
486         return desiredOutput;
487     }
488 
489     skif::LayerSpace<SkIRect> netInput;
490     for (int i = 0; i < this->countInputs(); ++i) {
491         const SkImageFilter* filter = this->getInput(i);
492         // The required input for this input filter, or 'targetOutput' if the filter is null and
493         // the source image is used (so must be sized to cover 'targetOutput').
494         // TODO (michaelludwig) - Right now contentBounds is applied conditionally at the end of
495         // the root getInputLayerBounds() based on affecting transparent black. Once that bit only
496         // changes output behavior, we can have the required bounds for a null input filter be the
497         // intersection of the desired output and the content bounds.
498         skif::LayerSpace<SkIRect> requiredInput =
499                 filter ? as_IFB(filter)->onGetInputLayerBounds(mapping, desiredOutput,
500                                                                contentBounds)
501                        : desiredOutput;
502         // Accumulate with all other filters
503         if (i == 0) {
504             netInput = requiredInput;
505         } else {
506             netInput.join(requiredInput);
507         }
508     }
509     return netInput;
510 }
511 
visitOutputLayerBounds(const skif::Mapping & mapping,const skif::LayerSpace<SkIRect> & contentBounds) const512 skif::LayerSpace<SkIRect> SkImageFilter_Base::visitOutputLayerBounds(
513         const skif::Mapping& mapping, const skif::LayerSpace<SkIRect>& contentBounds) const {
514     if (this->countInputs() < 1) {
515         // TODO (michaelludwig) - if a filter doesn't have any inputs, it presumably is determining
516         // its output size from something other than the implicit source contentBounds, in which
517         // case it shouldn't be calling this helper function, so explore adding an unreachable test
518         return contentBounds;
519     }
520 
521     skif::LayerSpace<SkIRect> netOutput;
522     for (int i = 0; i < this->countInputs(); ++i) {
523         const SkImageFilter* filter = this->getInput(i);
524         // The output for just this input filter, or 'contentBounds' if the filter is null and
525         // the source image is used (i.e. the identity filter applied to the source).
526         skif::LayerSpace<SkIRect> output =
527                 filter ? as_IFB(filter)->onGetOutputLayerBounds(mapping, contentBounds)
528                        : contentBounds;
529         // Accumulate with all other filters
530         if (i == 0) {
531             netOutput = output;
532         } else {
533             netOutput.join(output);
534         }
535     }
536     return netOutput;
537 }
538 
onGetInputLayerBounds(const skif::Mapping & mapping,const skif::LayerSpace<SkIRect> & desiredOutput,const skif::LayerSpace<SkIRect> & contentBounds,VisitChildren recurse) const539 skif::LayerSpace<SkIRect> SkImageFilter_Base::onGetInputLayerBounds(
540         const skif::Mapping& mapping, const skif::LayerSpace<SkIRect>& desiredOutput,
541         const skif::LayerSpace<SkIRect>& contentBounds, VisitChildren recurse) const {
542     // Call old functions for now since they may have been overridden by a subclass that's not been
543     // updated yet; eventually this will be a pure virtual and impls control visiting children
544     SkIRect content = SkIRect(contentBounds);
545     SkIRect input = this->onFilterNodeBounds(SkIRect(desiredOutput), mapping.layerMatrix(),
546                                              kReverse_MapDirection, &content);
547     if (recurse == VisitChildren::kYes) {
548         SkIRect aggregate = this->onFilterBounds(input, mapping.layerMatrix(),
549                                                  kReverse_MapDirection, &input);
550         return skif::LayerSpace<SkIRect>(aggregate);
551     } else {
552         return skif::LayerSpace<SkIRect>(input);
553     }
554 }
555 
onGetOutputLayerBounds(const skif::Mapping & mapping,const skif::LayerSpace<SkIRect> & contentBounds) const556 skif::LayerSpace<SkIRect> SkImageFilter_Base::onGetOutputLayerBounds(
557         const skif::Mapping& mapping, const skif::LayerSpace<SkIRect>& contentBounds) const {
558     // Call old functions for now; eventually this will be a pure virtual
559     SkIRect aggregate = this->onFilterBounds(SkIRect(contentBounds), mapping.layerMatrix(),
560                                              kForward_MapDirection, nullptr);
561     SkIRect output = this->onFilterNodeBounds(aggregate, mapping.layerMatrix(),
562                                               kForward_MapDirection, nullptr);
563     return skif::LayerSpace<SkIRect>(output);
564 }
565 
filterInput(int index,const skif::Context & ctx) const566 skif::FilterResult SkImageFilter_Base::filterInput(int index, const skif::Context& ctx) const {
567     const SkImageFilter* input = this->getInput(index);
568     if (!input) {
569         // Null image filters late bind to the source image
570         return ctx.source();
571     }
572 
573     skif::FilterResult result = as_IFB(input)->filterImage(this->mapContext(ctx));
574     SkASSERT(!result.image() || ctx.gpuBacked() == result.image()->isTextureBacked());
575 
576     return result;
577 }
578 
mapContext(const Context & ctx) const579 SkImageFilter_Base::Context SkImageFilter_Base::mapContext(const Context& ctx) const {
580     // We don't recurse through the child input filters because that happens automatically
581     // as part of the filterImage() evaluation. In this case, we want the bounds for the
582     // edge from this node to its children, without the effects of the child filters.
583     skif::LayerSpace<SkIRect> childOutput = this->onGetInputLayerBounds(
584             ctx.mapping(), ctx.desiredOutput(), ctx.desiredOutput(), VisitChildren::kNo);
585     return ctx.withNewDesiredOutput(childOutput);
586 }
587 
588 #if defined(SK_GANESH)
DrawWithFP(GrRecordingContext * rContext,std::unique_ptr<GrFragmentProcessor> fp,const SkIRect & bounds,SkColorType colorType,const SkColorSpace * colorSpace,const SkSurfaceProps & surfaceProps,GrSurfaceOrigin surfaceOrigin,GrProtected isProtected)589 sk_sp<SkSpecialImage> SkImageFilter_Base::DrawWithFP(GrRecordingContext* rContext,
590                                                      std::unique_ptr<GrFragmentProcessor> fp,
591                                                      const SkIRect& bounds,
592                                                      SkColorType colorType,
593                                                      const SkColorSpace* colorSpace,
594                                                      const SkSurfaceProps& surfaceProps,
595                                                      GrSurfaceOrigin surfaceOrigin,
596                                                      GrProtected isProtected) {
597     GrImageInfo info(SkColorTypeToGrColorType(colorType),
598                      kPremul_SkAlphaType,
599                      sk_ref_sp(colorSpace),
600                      bounds.size());
601 
602     auto sfc = rContext->priv().makeSFC(info,
603                                         "ImageFilterBase_DrawWithFP",
604                                         SkBackingFit::kApprox,
605                                         1,
606                                         GrMipmapped::kNo,
607                                         isProtected,
608                                         surfaceOrigin);
609     if (!sfc) {
610         return nullptr;
611     }
612 
613     SkIRect dstIRect = SkIRect::MakeWH(bounds.width(), bounds.height());
614     SkRect srcRect = SkRect::Make(bounds);
615     sfc->fillRectToRectWithFP(srcRect, dstIRect, std::move(fp));
616 
617     return SkSpecialImage::MakeDeferredFromGpu(rContext,
618                                                dstIRect,
619                                                kNeedNewImageUniqueID_SpecialImage,
620                                                sfc->readSurfaceView(),
621                                                sfc->colorInfo(),
622                                                surfaceProps);
623 }
624 
ImageToColorSpace(SkSpecialImage * src,SkColorType colorType,SkColorSpace * colorSpace,const SkSurfaceProps & surfaceProps)625 sk_sp<SkSpecialImage> SkImageFilter_Base::ImageToColorSpace(SkSpecialImage* src,
626                                                             SkColorType colorType,
627                                                             SkColorSpace* colorSpace,
628                                                             const SkSurfaceProps& surfaceProps) {
629     // There are several conditions that determine if we actually need to convert the source to the
630     // destination's color space. Rather than duplicate that logic here, just try to make an xform
631     // object. If that produces something, then both are tagged, and the source is in a different
632     // gamut than the dest. There is some overhead to making the xform, but those are cached, and
633     // if we get one back, that means we're about to use it during the conversion anyway.
634     auto colorSpaceXform = GrColorSpaceXform::Make(src->getColorSpace(),  src->alphaType(),
635                                                    colorSpace, kPremul_SkAlphaType);
636 
637     if (!colorSpaceXform) {
638         // No xform needed, just return the original image
639         return sk_ref_sp(src);
640     }
641 
642     sk_sp<SkSpecialSurface> surf(src->makeSurface(colorType, colorSpace,
643                                                   SkISize::Make(src->width(), src->height()),
644                                                   kPremul_SkAlphaType, surfaceProps));
645     if (!surf) {
646         return sk_ref_sp(src);
647     }
648 
649     SkCanvas* canvas = surf->getCanvas();
650     SkASSERT(canvas);
651     SkPaint p;
652     p.setBlendMode(SkBlendMode::kSrc);
653     src->draw(canvas, 0, 0, SkSamplingOptions(), &p);
654     return surf->makeImageSnapshot();
655 }
656 #endif
657 
658 // In repeat mode, when we are going to sample off one edge of the srcBounds we require the
659 // opposite side be preserved.
DetermineRepeatedSrcBound(const SkIRect & srcBounds,const SkIVector & filterOffset,const SkISize & filterSize,const SkIRect & originalSrcBounds)660 SkIRect SkImageFilter_Base::DetermineRepeatedSrcBound(const SkIRect& srcBounds,
661                                                       const SkIVector& filterOffset,
662                                                       const SkISize& filterSize,
663                                                       const SkIRect& originalSrcBounds) {
664     SkIRect tmp = srcBounds;
665     tmp.adjust(-filterOffset.fX, -filterOffset.fY,
666                filterSize.fWidth - filterOffset.fX, filterSize.fHeight - filterOffset.fY);
667 
668     if (tmp.fLeft < originalSrcBounds.fLeft || tmp.fRight > originalSrcBounds.fRight) {
669         tmp.fLeft = originalSrcBounds.fLeft;
670         tmp.fRight = originalSrcBounds.fRight;
671     }
672     if (tmp.fTop < originalSrcBounds.fTop || tmp.fBottom > originalSrcBounds.fBottom) {
673         tmp.fTop = originalSrcBounds.fTop;
674         tmp.fBottom = originalSrcBounds.fBottom;
675     }
676 
677     return tmp;
678 }
679 
PurgeCache()680 void SkImageFilter_Base::PurgeCache() {
681     SkImageFilterCache::Get()->purge();
682 }
683