• 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/SkAlphaType.h"
9 #include "include/core/SkBitmap.h"
10 #include "include/core/SkColor.h"
11 #include "include/core/SkColorType.h"
12 #include "include/core/SkFlattenable.h"
13 #include "include/core/SkImageFilter.h"
14 #include "include/core/SkImageInfo.h"
15 #include "include/core/SkMatrix.h"
16 #include "include/core/SkPoint.h"
17 #include "include/core/SkRect.h"
18 #include "include/core/SkRefCnt.h"
19 #include "include/core/SkScalar.h"
20 #include "include/core/SkSize.h"
21 #include "include/core/SkString.h"
22 #include "include/core/SkTypes.h"
23 #include "include/effects/SkImageFilters.h"
24 #include "include/private/SkColorData.h"
25 #include "include/private/SkSLSampleUsage.h"
26 #include "include/private/base/SkTo.h"
27 #include "src/core/SkImageFilter_Base.h"
28 #include "src/core/SkReadBuffer.h"
29 #include "src/core/SkSpecialImage.h"
30 #include "src/core/SkWriteBuffer.h"
31 
32 #include <algorithm>
33 #include <cstdint>
34 #include <memory>
35 #include <utility>
36 
37 #if defined(SK_GANESH)
38 #include "include/gpu/GpuTypes.h"
39 #include "include/gpu/GrRecordingContext.h"
40 #include "include/gpu/GrTypes.h"
41 #include "include/private/gpu/ganesh/GrTypesPriv.h"
42 #include "src/core/SkSLTypeShared.h"
43 #include "src/gpu/KeyBuilder.h"
44 #include "src/gpu/SkBackingFit.h"
45 #include "src/gpu/ganesh/GrColorInfo.h"
46 #include "src/gpu/ganesh/GrFragmentProcessor.h"
47 #include "src/gpu/ganesh/GrImageInfo.h"
48 #include "src/gpu/ganesh/GrProcessorUnitTest.h"
49 #include "src/gpu/ganesh/GrRecordingContextPriv.h"
50 #include "src/gpu/ganesh/GrSurfaceProxy.h"
51 #include "src/gpu/ganesh/GrSurfaceProxyView.h"
52 #include "src/gpu/ganesh/SurfaceFillContext.h"
53 #include "src/gpu/ganesh/effects/GrTextureEffect.h"
54 #include "src/gpu/ganesh/glsl/GrGLSLFragmentShaderBuilder.h"
55 #include "src/gpu/ganesh/glsl/GrGLSLProgramDataManager.h"
56 #include "src/gpu/ganesh/glsl/GrGLSLUniformHandler.h"
57 
58 struct GrShaderCaps;
59 #endif
60 
61 #if GR_TEST_UTILS
62 #include "src/base/SkRandom.h"
63 #endif
64 
65 #if SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSE2
66     #include <emmintrin.h>
67 #endif
68 
69 #if defined(SK_ARM_HAS_NEON)
70     #include <arm_neon.h>
71 #endif
72 
73 namespace {
74 
75 enum class MorphType {
76     kErode,
77     kDilate,
78     kLastType = kDilate
79 };
80 
81 enum class MorphDirection { kX, kY };
82 
83 class SkMorphologyImageFilter final : public SkImageFilter_Base {
84 public:
SkMorphologyImageFilter(MorphType type,SkScalar radiusX,SkScalar radiusY,sk_sp<SkImageFilter> input,const SkRect * cropRect)85     SkMorphologyImageFilter(MorphType type, SkScalar radiusX, SkScalar radiusY,
86                             sk_sp<SkImageFilter> input, const SkRect* cropRect)
87             : INHERITED(&input, 1, cropRect)
88             , fType(type)
89             , fRadius(SkSize::Make(radiusX, radiusY)) {}
90 
91     SkRect computeFastBounds(const SkRect& src) const override;
92     SkIRect onFilterNodeBounds(const SkIRect& src, const SkMatrix& ctm,
93                                MapDirection, const SkIRect* inputRect) const override;
94 
95     /**
96      * All morphology procs have the same signature: src is the source buffer, dst the
97      * destination buffer, radius is the morphology radius, width and height are the bounds
98      * of the destination buffer (in pixels), and srcStride and dstStride are the
99      * number of pixels per row in each buffer. All buffers are 8888.
100      */
101 
102     typedef void (*Proc)(const SkPMColor* src, SkPMColor* dst, int radius,
103                          int width, int height, int srcStride, int dstStride);
104 
105 protected:
106     sk_sp<SkSpecialImage> onFilterImage(const Context&, SkIPoint* offset) const override;
107     void flatten(SkWriteBuffer&) const override;
108 
mappedRadius(const SkMatrix & ctm) const109     SkSize mappedRadius(const SkMatrix& ctm) const {
110       SkVector radiusVector = SkVector::Make(fRadius.width(), fRadius.height());
111       ctm.mapVectors(&radiusVector, 1);
112       radiusVector.setAbs(radiusVector);
113       return SkSize::Make(radiusVector.x(), radiusVector.y());
114     }
115 
116 private:
117     friend void ::SkRegisterMorphologyImageFilterFlattenables();
118 
119     SK_FLATTENABLE_HOOKS(SkMorphologyImageFilter)
120 
121     MorphType fType;
122     SkSize    fRadius;
123 
124     using INHERITED = SkImageFilter_Base;
125 };
126 
127 } // end namespace
128 
Dilate(SkScalar radiusX,SkScalar radiusY,sk_sp<SkImageFilter> input,const CropRect & cropRect)129 sk_sp<SkImageFilter> SkImageFilters::Dilate(SkScalar radiusX, SkScalar radiusY,
130                                             sk_sp<SkImageFilter> input,
131                                             const CropRect& cropRect) {
132     if (radiusX < 0 || radiusY < 0) {
133         return nullptr;
134     }
135     return sk_sp<SkImageFilter>(new SkMorphologyImageFilter(
136             MorphType::kDilate, radiusX, radiusY, std::move(input), cropRect));
137 }
138 
Erode(SkScalar radiusX,SkScalar radiusY,sk_sp<SkImageFilter> input,const CropRect & cropRect)139 sk_sp<SkImageFilter> SkImageFilters::Erode(SkScalar radiusX, SkScalar radiusY,
140                                            sk_sp<SkImageFilter> input,
141                                            const CropRect& cropRect) {
142     if (radiusX < 0 || radiusY < 0) {
143         return nullptr;
144     }
145     return sk_sp<SkImageFilter>(new SkMorphologyImageFilter(
146             MorphType::kErode, radiusX, radiusY,  std::move(input), cropRect));
147 }
148 
SkRegisterMorphologyImageFilterFlattenables()149 void SkRegisterMorphologyImageFilterFlattenables() {
150     SK_REGISTER_FLATTENABLE(SkMorphologyImageFilter);
151     // TODO (michaelludwig): Remove after grace period for SKPs to stop using old name
152     SkFlattenable::Register("SkMorphologyImageFilterImpl", SkMorphologyImageFilter::CreateProc);
153 }
154 
CreateProc(SkReadBuffer & buffer)155 sk_sp<SkFlattenable> SkMorphologyImageFilter::CreateProc(SkReadBuffer& buffer) {
156     SK_IMAGEFILTER_UNFLATTEN_COMMON(common, 1);
157 
158     SkScalar width = buffer.readScalar();
159     SkScalar height = buffer.readScalar();
160     MorphType filterType = buffer.read32LE(MorphType::kLastType);
161 
162     if (filterType == MorphType::kDilate) {
163         return SkImageFilters::Dilate(width, height, common.getInput(0), common.cropRect());
164     } else if (filterType == MorphType::kErode) {
165         return SkImageFilters::Erode(width, height, common.getInput(0), common.cropRect());
166     } else {
167         return nullptr;
168     }
169 }
170 
flatten(SkWriteBuffer & buffer) const171 void SkMorphologyImageFilter::flatten(SkWriteBuffer& buffer) const {
172     this->INHERITED::flatten(buffer);
173     buffer.writeScalar(fRadius.fWidth);
174     buffer.writeScalar(fRadius.fHeight);
175     buffer.writeInt(static_cast<int>(fType));
176 }
177 
178 ///////////////////////////////////////////////////////////////////////////////
179 
call_proc_X(SkMorphologyImageFilter::Proc procX,const SkBitmap & src,SkBitmap * dst,int radiusX,const SkIRect & bounds)180 static void call_proc_X(SkMorphologyImageFilter::Proc procX,
181                         const SkBitmap& src, SkBitmap* dst,
182                         int radiusX, const SkIRect& bounds) {
183     procX(src.getAddr32(bounds.left(), bounds.top()), dst->getAddr32(0, 0),
184           radiusX, bounds.width(), bounds.height(),
185           src.rowBytesAsPixels(), dst->rowBytesAsPixels());
186 }
187 
call_proc_Y(SkMorphologyImageFilter::Proc procY,const SkPMColor * src,int srcRowBytesAsPixels,SkBitmap * dst,int radiusY,const SkIRect & bounds)188 static void call_proc_Y(SkMorphologyImageFilter::Proc procY,
189                         const SkPMColor* src, int srcRowBytesAsPixels, SkBitmap* dst,
190                         int radiusY, const SkIRect& bounds) {
191     procY(src, dst->getAddr32(0, 0),
192           radiusY, bounds.height(), bounds.width(),
193           srcRowBytesAsPixels, dst->rowBytesAsPixels());
194 }
195 
computeFastBounds(const SkRect & src) const196 SkRect SkMorphologyImageFilter::computeFastBounds(const SkRect& src) const {
197     SkRect bounds = this->getInput(0) ? this->getInput(0)->computeFastBounds(src) : src;
198     bounds.outset(fRadius.width(), fRadius.height());
199     return bounds;
200 }
201 
onFilterNodeBounds(const SkIRect & src,const SkMatrix & ctm,MapDirection,const SkIRect * inputRect) const202 SkIRect SkMorphologyImageFilter::onFilterNodeBounds(
203         const SkIRect& src, const SkMatrix& ctm, MapDirection, const SkIRect* inputRect) const {
204     SkSize radius = mappedRadius(ctm);
205     return src.makeOutset(SkScalarCeilToInt(radius.width()), SkScalarCeilToInt(radius.height()));
206 }
207 
208 #if defined(SK_GANESH)
209 
210 ///////////////////////////////////////////////////////////////////////////////
211 /**
212  * Morphology effects. Depending upon the type of morphology, either the
213  * component-wise min (Erode_Type) or max (Dilate_Type) of all pixels in the
214  * kernel is selected as the new color. The new color is modulated by the input
215  * color.
216  */
217 class GrMorphologyEffect : public GrFragmentProcessor {
218 public:
Make(std::unique_ptr<GrFragmentProcessor> inputFP,GrSurfaceProxyView view,SkAlphaType srcAlphaType,MorphDirection dir,int radius,MorphType type)219     static std::unique_ptr<GrFragmentProcessor> Make(
220             std::unique_ptr<GrFragmentProcessor> inputFP, GrSurfaceProxyView view,
221             SkAlphaType srcAlphaType, MorphDirection dir, int radius, MorphType type) {
222         return std::unique_ptr<GrFragmentProcessor>(
223                 new GrMorphologyEffect(std::move(inputFP), std::move(view), srcAlphaType, dir,
224                                        radius, type, /*range=*/nullptr));
225     }
226 
Make(std::unique_ptr<GrFragmentProcessor> inputFP,GrSurfaceProxyView view,SkAlphaType srcAlphaType,MorphDirection dir,int radius,MorphType type,const float range[2])227     static std::unique_ptr<GrFragmentProcessor> Make(
228             std::unique_ptr<GrFragmentProcessor> inputFP, GrSurfaceProxyView view,
229             SkAlphaType srcAlphaType, MorphDirection dir, int radius, MorphType type,
230             const float range[2]) {
231         return std::unique_ptr<GrFragmentProcessor>(new GrMorphologyEffect(
232                 std::move(inputFP), std::move(view), srcAlphaType, dir, radius, type, range));
233     }
234 
name() const235     const char* name() const override { return "Morphology"; }
236 
clone() const237     std::unique_ptr<GrFragmentProcessor> clone() const override {
238         return std::unique_ptr<GrFragmentProcessor>(new GrMorphologyEffect(*this));
239     }
240 
241 private:
242     MorphDirection fDirection;
243     int fRadius;
244     MorphType fType;
245     bool fUseRange;
246     float fRange[2];
247 
248     std::unique_ptr<ProgramImpl> onMakeProgramImpl() const override;
249 
250     void onAddToKey(const GrShaderCaps&, skgpu::KeyBuilder*) const override;
251 
252     bool onIsEqual(const GrFragmentProcessor&) const override;
253     GrMorphologyEffect(std::unique_ptr<GrFragmentProcessor> inputFP, GrSurfaceProxyView,
254                        SkAlphaType srcAlphaType, MorphDirection, int radius, MorphType,
255                        const float range[2]);
256     explicit GrMorphologyEffect(const GrMorphologyEffect&);
257 
258     GR_DECLARE_FRAGMENT_PROCESSOR_TEST
259 
260     using INHERITED = GrFragmentProcessor;
261 };
262 
onMakeProgramImpl() const263 std::unique_ptr<GrFragmentProcessor::ProgramImpl> GrMorphologyEffect::onMakeProgramImpl() const {
264     class Impl : public ProgramImpl {
265     public:
266         void emitCode(EmitArgs& args) override {
267             constexpr int kInputFPIndex = 0;
268             constexpr int kTexEffectIndex = 1;
269 
270             const GrMorphologyEffect& me = args.fFp.cast<GrMorphologyEffect>();
271 
272             GrGLSLUniformHandler* uniformHandler = args.fUniformHandler;
273             fRangeUni = uniformHandler->addUniform(&me, kFragment_GrShaderFlag, SkSLType::kFloat2,
274                                                    "Range");
275             const char* range = uniformHandler->getUniformCStr(fRangeUni);
276 
277             GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;
278 
279             const char* func = me.fType == MorphType::kErode ? "min" : "max";
280 
281             char initialValue = me.fType == MorphType::kErode ? '1' : '0';
282             fragBuilder->codeAppendf("half4 color = half4(%c);", initialValue);
283 
284             char dir = me.fDirection == MorphDirection::kX ? 'x' : 'y';
285 
286             int width = 2 * me.fRadius + 1;
287 
288             // float2 coord = coord2D;
289             fragBuilder->codeAppendf("float2 coord = %s;", args.fSampleCoord);
290             // coord.x -= radius;
291             fragBuilder->codeAppendf("coord.%c -= %d;", dir, me.fRadius);
292             if (me.fUseRange) {
293                 // highBound = min(highBound, coord.x + (width-1));
294                 fragBuilder->codeAppendf("float highBound = min(%s.y, coord.%c + %f);", range, dir,
295                                          float(width - 1));
296                 // coord.x = max(lowBound, coord.x);
297                 fragBuilder->codeAppendf("coord.%c = max(%s.x, coord.%c);", dir, range, dir);
298             }
299             fragBuilder->codeAppendf("for (int i = 0; i < %d; i++) {", width);
300             SkString sample = this->invokeChild(kTexEffectIndex, args, "coord");
301             fragBuilder->codeAppendf("    color = %s(color, %s);", func, sample.c_str());
302             // coord.x += 1;
303             fragBuilder->codeAppendf("    coord.%c += 1;", dir);
304             if (me.fUseRange) {
305                 // coord.x = min(highBound, coord.x);
306                 fragBuilder->codeAppendf("    coord.%c = min(highBound, coord.%c);", dir, dir);
307             }
308             fragBuilder->codeAppend("}");
309 
310             SkString inputColor = this->invokeChild(kInputFPIndex, args);
311             fragBuilder->codeAppendf("return color * %s;", inputColor.c_str());
312         }
313 
314     private:
315         void onSetData(const GrGLSLProgramDataManager& pdman,
316                        const GrFragmentProcessor& proc) override {
317             const GrMorphologyEffect& m = proc.cast<GrMorphologyEffect>();
318             if (m.fUseRange) {
319                 pdman.set2f(fRangeUni, m.fRange[0], m.fRange[1]);
320             }
321         }
322 
323         GrGLSLProgramDataManager::UniformHandle fRangeUni;
324     };
325 
326     return std::make_unique<Impl>();
327 }
328 
onAddToKey(const GrShaderCaps & caps,skgpu::KeyBuilder * b) const329 void GrMorphologyEffect::onAddToKey(const GrShaderCaps& caps, skgpu::KeyBuilder* b) const {
330     uint32_t key = static_cast<uint32_t>(fRadius);
331     key |= (static_cast<uint32_t>(fType) << 8);
332     key |= (static_cast<uint32_t>(fDirection) << 9);
333     if (fUseRange) {
334         key |= 1 << 10;
335     }
336     b->add32(key);
337 }
338 
GrMorphologyEffect(std::unique_ptr<GrFragmentProcessor> inputFP,GrSurfaceProxyView view,SkAlphaType srcAlphaType,MorphDirection direction,int radius,MorphType type,const float range[2])339 GrMorphologyEffect::GrMorphologyEffect(std::unique_ptr<GrFragmentProcessor> inputFP,
340                                        GrSurfaceProxyView view,
341                                        SkAlphaType srcAlphaType,
342                                        MorphDirection direction,
343                                        int radius,
344                                        MorphType type,
345                                        const float range[2])
346         : INHERITED(kGrMorphologyEffect_ClassID, ModulateForClampedSamplerOptFlags(srcAlphaType))
347         , fDirection(direction)
348         , fRadius(radius)
349         , fType(type)
350         , fUseRange(SkToBool(range)) {
351     this->setUsesSampleCoordsDirectly();
352     this->registerChild(std::move(inputFP));
353     this->registerChild(GrTextureEffect::Make(std::move(view), srcAlphaType),
354                         SkSL::SampleUsage::Explicit());
355     if (fUseRange) {
356         fRange[0] = range[0];
357         fRange[1] = range[1];
358     }
359 }
360 
GrMorphologyEffect(const GrMorphologyEffect & that)361 GrMorphologyEffect::GrMorphologyEffect(const GrMorphologyEffect& that)
362         : INHERITED(that)
363         , fDirection(that.fDirection)
364         , fRadius(that.fRadius)
365         , fType(that.fType)
366         , fUseRange(that.fUseRange) {
367     if (that.fUseRange) {
368         fRange[0] = that.fRange[0];
369         fRange[1] = that.fRange[1];
370     }
371 }
372 
onIsEqual(const GrFragmentProcessor & sBase) const373 bool GrMorphologyEffect::onIsEqual(const GrFragmentProcessor& sBase) const {
374     const GrMorphologyEffect& s = sBase.cast<GrMorphologyEffect>();
375     return this->fRadius    == s.fRadius    &&
376            this->fDirection == s.fDirection &&
377            this->fUseRange  == s.fUseRange  &&
378            this->fType      == s.fType;
379 }
380 
381 ///////////////////////////////////////////////////////////////////////////////
382 
GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrMorphologyEffect)383 GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrMorphologyEffect)
384 
385 #if GR_TEST_UTILS
386 std::unique_ptr<GrFragmentProcessor> GrMorphologyEffect::TestCreate(GrProcessorTestData* d) {
387     auto [view, ct, at] = d->randomView();
388 
389     MorphDirection dir = d->fRandom->nextBool() ? MorphDirection::kX : MorphDirection::kY;
390     static const int kMaxRadius = 10;
391     int radius = d->fRandom->nextRangeU(1, kMaxRadius);
392     MorphType type = d->fRandom->nextBool() ? MorphType::kErode : MorphType::kDilate;
393     return GrMorphologyEffect::Make(d->inputFP(), std::move(view), at, dir, radius, type);
394 }
395 #endif
396 
apply_morphology_rect(skgpu::v1::SurfaceFillContext * sfc,GrSurfaceProxyView view,SkAlphaType srcAlphaType,const SkIRect & srcRect,const SkIRect & dstRect,int radius,MorphType morphType,const float range[2],MorphDirection direction)397 static void apply_morphology_rect(skgpu::v1::SurfaceFillContext* sfc,
398                                   GrSurfaceProxyView view,
399                                   SkAlphaType srcAlphaType,
400                                   const SkIRect& srcRect,
401                                   const SkIRect& dstRect,
402                                   int radius,
403                                   MorphType morphType,
404                                   const float range[2],
405                                   MorphDirection direction) {
406     auto fp = GrMorphologyEffect::Make(/*inputFP=*/nullptr,
407                                        std::move(view),
408                                        srcAlphaType,
409                                        direction,
410                                        radius,
411                                        morphType,
412                                        range);
413     sfc->fillRectToRectWithFP(srcRect, dstRect, std::move(fp));
414 }
415 
apply_morphology_rect_no_bounds(skgpu::v1::SurfaceFillContext * sfc,GrSurfaceProxyView view,SkAlphaType srcAlphaType,const SkIRect & srcRect,const SkIRect & dstRect,int radius,MorphType morphType,MorphDirection direction)416 static void apply_morphology_rect_no_bounds(skgpu::v1::SurfaceFillContext* sfc,
417                                             GrSurfaceProxyView view,
418                                             SkAlphaType srcAlphaType,
419                                             const SkIRect& srcRect,
420                                             const SkIRect& dstRect,
421                                             int radius,
422                                             MorphType morphType,
423                                             MorphDirection direction) {
424     auto fp = GrMorphologyEffect::Make(
425             /*inputFP=*/nullptr, std::move(view), srcAlphaType, direction, radius, morphType);
426     sfc->fillRectToRectWithFP(srcRect, dstRect, std::move(fp));
427 }
428 
apply_morphology_pass(skgpu::v1::SurfaceFillContext * sfc,GrSurfaceProxyView view,SkAlphaType srcAlphaType,const SkIRect & srcRect,const SkIRect & dstRect,int radius,MorphType morphType,MorphDirection direction)429 static void apply_morphology_pass(skgpu::v1::SurfaceFillContext* sfc,
430                                   GrSurfaceProxyView view,
431                                   SkAlphaType srcAlphaType,
432                                   const SkIRect& srcRect,
433                                   const SkIRect& dstRect,
434                                   int radius,
435                                   MorphType morphType,
436                                   MorphDirection direction) {
437     float bounds[2] = { 0.0f, 1.0f };
438     SkIRect lowerSrcRect = srcRect, lowerDstRect = dstRect;
439     SkIRect middleSrcRect = srcRect, middleDstRect = dstRect;
440     SkIRect upperSrcRect = srcRect, upperDstRect = dstRect;
441     if (direction == MorphDirection::kX) {
442         bounds[0] = SkIntToScalar(srcRect.left()) + 0.5f;
443         bounds[1] = SkIntToScalar(srcRect.right()) - 0.5f;
444         lowerSrcRect.fRight = srcRect.left() + radius;
445         lowerDstRect.fRight = dstRect.left() + radius;
446         upperSrcRect.fLeft = srcRect.right() - radius;
447         upperDstRect.fLeft = dstRect.right() - radius;
448         middleSrcRect.inset(radius, 0);
449         middleDstRect.inset(radius, 0);
450     } else {
451         bounds[0] = SkIntToScalar(srcRect.top()) + 0.5f;
452         bounds[1] = SkIntToScalar(srcRect.bottom()) - 0.5f;
453         lowerSrcRect.fBottom = srcRect.top() + radius;
454         lowerDstRect.fBottom = dstRect.top() + radius;
455         upperSrcRect.fTop = srcRect.bottom() - radius;
456         upperDstRect.fTop = dstRect.bottom() - radius;
457         middleSrcRect.inset(0, radius);
458         middleDstRect.inset(0, radius);
459     }
460     if (middleSrcRect.width() <= 0) {
461         // radius covers srcRect; use bounds over entire draw
462         apply_morphology_rect(sfc, std::move(view), srcAlphaType, srcRect,
463                               dstRect, radius, morphType, bounds, direction);
464     } else {
465         // Draw upper and lower margins with bounds; middle without.
466         apply_morphology_rect(sfc, view, srcAlphaType, lowerSrcRect,
467                               lowerDstRect, radius, morphType, bounds, direction);
468         apply_morphology_rect(sfc, view, srcAlphaType, upperSrcRect,
469                               upperDstRect, radius, morphType, bounds, direction);
470         apply_morphology_rect_no_bounds(sfc, std::move(view), srcAlphaType,
471                                         middleSrcRect, middleDstRect, radius, morphType, direction);
472     }
473 }
474 
apply_morphology(GrRecordingContext * rContext,SkSpecialImage * input,const SkIRect & rect,MorphType morphType,SkISize radius,const SkImageFilter_Base::Context & ctx)475 static sk_sp<SkSpecialImage> apply_morphology(
476         GrRecordingContext* rContext, SkSpecialImage* input, const SkIRect& rect,
477         MorphType morphType, SkISize radius, const SkImageFilter_Base::Context& ctx) {
478     GrSurfaceProxyView srcView = input->view(rContext);
479     SkAlphaType srcAlphaType = input->alphaType();
480     SkASSERT(srcView.asTextureProxy());
481 
482     GrSurfaceProxy* proxy = srcView.proxy();
483 
484     const SkIRect dstRect = SkIRect::MakeWH(rect.width(), rect.height());
485     SkIRect srcRect = rect;
486     // Map into proxy space
487     srcRect.offset(input->subset().x(), input->subset().y());
488     SkASSERT(radius.width() > 0 || radius.height() > 0);
489 
490     GrImageInfo info(ctx.grColorType(), kPremul_SkAlphaType, ctx.refColorSpace(), rect.size());
491 
492     if (radius.fWidth > 0) {
493         auto dstFillContext =
494                 rContext->priv().makeSFC(info,
495                                          "SpecialImage_ApplyMorphology_Width",
496                                          SkBackingFit::kApprox,
497                                          1,
498                                          GrMipmapped::kNo,
499                                          proxy->isProtected(),
500                                          kBottomLeft_GrSurfaceOrigin);
501         if (!dstFillContext) {
502             return nullptr;
503         }
504 
505         apply_morphology_pass(dstFillContext.get(), std::move(srcView), srcAlphaType,
506                               srcRect, dstRect, radius.fWidth, morphType, MorphDirection::kX);
507         SkIRect clearRect = SkIRect::MakeXYWH(dstRect.fLeft, dstRect.fBottom,
508                                               dstRect.width(), radius.fHeight);
509         SkPMColor4f clearColor = MorphType::kErode == morphType
510                 ? SK_PMColor4fWHITE : SK_PMColor4fTRANSPARENT;
511         dstFillContext->clear(clearRect, clearColor);
512 
513         srcView = dstFillContext->readSurfaceView();
514         srcAlphaType = dstFillContext->colorInfo().alphaType();
515         srcRect = dstRect;
516     }
517     if (radius.fHeight > 0) {
518         auto dstFillContext =
519                 rContext->priv().makeSFC(info,
520                                          "SpecialImage_ApplyMorphology_Height",
521                                          SkBackingFit::kApprox,
522                                          1,
523                                          GrMipmapped::kNo,
524                                          srcView.proxy()->isProtected(),
525                                          kBottomLeft_GrSurfaceOrigin);
526         if (!dstFillContext) {
527             return nullptr;
528         }
529 
530         apply_morphology_pass(dstFillContext.get(), std::move(srcView), srcAlphaType,
531                               srcRect, dstRect, radius.fHeight, morphType, MorphDirection::kY);
532 
533         srcView = dstFillContext->readSurfaceView();
534     }
535 
536     return SkSpecialImage::MakeDeferredFromGpu(rContext,
537                                                SkIRect::MakeWH(rect.width(), rect.height()),
538                                                kNeedNewImageUniqueID_SpecialImage,
539                                                std::move(srcView),
540                                                info.colorInfo(),
541                                                input->props());
542 }
543 #endif
544 
545 namespace {
546 
547 #if SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSE2
548     template<MorphType type, MorphDirection direction>
morph(const SkPMColor * src,SkPMColor * dst,int radius,int width,int height,int srcStride,int dstStride)549     static void morph(const SkPMColor* src, SkPMColor* dst,
550                       int radius, int width, int height, int srcStride, int dstStride) {
551         const int srcStrideX = direction == MorphDirection::kX ? 1 : srcStride;
552         const int dstStrideX = direction == MorphDirection::kX ? 1 : dstStride;
553         const int srcStrideY = direction == MorphDirection::kX ? srcStride : 1;
554         const int dstStrideY = direction == MorphDirection::kX ? dstStride : 1;
555         radius = std::min(radius, width - 1);
556         const SkPMColor* upperSrc = src + radius * srcStrideX;
557         for (int x = 0; x < width; ++x) {
558             const SkPMColor* lp = src;
559             const SkPMColor* up = upperSrc;
560             SkPMColor* dptr = dst;
561             for (int y = 0; y < height; ++y) {
562                 __m128i extreme = (type == MorphType::kDilate) ? _mm_setzero_si128()
563                                                                : _mm_set1_epi32(0xFFFFFFFF);
564                 for (const SkPMColor* p = lp; p <= up; p += srcStrideX) {
565                     __m128i src_pixel = _mm_cvtsi32_si128(*p);
566                     extreme = (type == MorphType::kDilate) ? _mm_max_epu8(src_pixel, extreme)
567                                                            : _mm_min_epu8(src_pixel, extreme);
568                 }
569                 *dptr = _mm_cvtsi128_si32(extreme);
570                 dptr += dstStrideY;
571                 lp += srcStrideY;
572                 up += srcStrideY;
573             }
574             if (x >= radius) { src += srcStrideX; }
575             if (x + radius < width - 1) { upperSrc += srcStrideX; }
576             dst += dstStrideX;
577         }
578     }
579 
580 #elif defined(SK_ARM_HAS_NEON)
581     template<MorphType type, MorphDirection direction>
582     static void morph(const SkPMColor* src, SkPMColor* dst,
583                       int radius, int width, int height, int srcStride, int dstStride) {
584         const int srcStrideX = direction == MorphDirection::kX ? 1 : srcStride;
585         const int dstStrideX = direction == MorphDirection::kX ? 1 : dstStride;
586         const int srcStrideY = direction == MorphDirection::kX ? srcStride : 1;
587         const int dstStrideY = direction == MorphDirection::kX ? dstStride : 1;
588         radius = std::min(radius, width - 1);
589         const SkPMColor* upperSrc = src + radius * srcStrideX;
590         for (int x = 0; x < width; ++x) {
591             const SkPMColor* lp = src;
592             const SkPMColor* up = upperSrc;
593             SkPMColor* dptr = dst;
594             for (int y = 0; y < height; ++y) {
595                 uint8x8_t extreme = vdup_n_u8(type == MorphType::kDilate ? 0 : 255);
596                 for (const SkPMColor* p = lp; p <= up; p += srcStrideX) {
597                     uint8x8_t src_pixel = vreinterpret_u8_u32(vdup_n_u32(*p));
598                     extreme = (type == MorphType::kDilate) ? vmax_u8(src_pixel, extreme)
599                                                            : vmin_u8(src_pixel, extreme);
600                 }
601                 *dptr = vget_lane_u32(vreinterpret_u32_u8(extreme), 0);
602                 dptr += dstStrideY;
603                 lp += srcStrideY;
604                 up += srcStrideY;
605             }
606             if (x >= radius) src += srcStrideX;
607             if (x + radius < width - 1) upperSrc += srcStrideX;
608             dst += dstStrideX;
609         }
610     }
611 
612 #else
613     template<MorphType type, MorphDirection direction>
614     static void morph(const SkPMColor* src, SkPMColor* dst,
615                       int radius, int width, int height, int srcStride, int dstStride) {
616         const int srcStrideX = direction == MorphDirection::kX ? 1 : srcStride;
617         const int dstStrideX = direction == MorphDirection::kX ? 1 : dstStride;
618         const int srcStrideY = direction == MorphDirection::kX ? srcStride : 1;
619         const int dstStrideY = direction == MorphDirection::kX ? dstStride : 1;
620         radius = std::min(radius, width - 1);
621         const SkPMColor* upperSrc = src + radius * srcStrideX;
622         for (int x = 0; x < width; ++x) {
623             const SkPMColor* lp = src;
624             const SkPMColor* up = upperSrc;
625             SkPMColor* dptr = dst;
626             for (int y = 0; y < height; ++y) {
627                 // If we're maxing (dilate), start from 0; if minning (erode), start from 255.
628                 const int start = (type == MorphType::kDilate) ? 0 : 255;
629                 int B = start, G = start, R = start, A = start;
630                 for (const SkPMColor* p = lp; p <= up; p += srcStrideX) {
631                     int b = SkGetPackedB32(*p),
632                         g = SkGetPackedG32(*p),
633                         r = SkGetPackedR32(*p),
634                         a = SkGetPackedA32(*p);
635                     if (type == MorphType::kDilate) {
636                         B = std::max(b, B);
637                         G = std::max(g, G);
638                         R = std::max(r, R);
639                         A = std::max(a, A);
640                     } else {
641                         B = std::min(b, B);
642                         G = std::min(g, G);
643                         R = std::min(r, R);
644                         A = std::min(a, A);
645                     }
646                 }
647                 *dptr = SkPackARGB32(A, R, G, B);
648                 dptr += dstStrideY;
649                 lp += srcStrideY;
650                 up += srcStrideY;
651             }
652             if (x >= radius) { src += srcStrideX; }
653             if (x + radius < width - 1) { upperSrc += srcStrideX; }
654             dst += dstStrideX;
655         }
656     }
657 #endif
658 }  // namespace
659 
onFilterImage(const Context & ctx,SkIPoint * offset) const660 sk_sp<SkSpecialImage> SkMorphologyImageFilter::onFilterImage(const Context& ctx,
661                                                              SkIPoint* offset) const {
662     SkIPoint inputOffset = SkIPoint::Make(0, 0);
663     sk_sp<SkSpecialImage> input(this->filterInput(0, ctx, &inputOffset));
664     if (!input) {
665         return nullptr;
666     }
667 
668     SkIRect bounds;
669     input = this->applyCropRectAndPad(this->mapContext(ctx), input.get(), &inputOffset, &bounds);
670     if (!input) {
671         return nullptr;
672     }
673 
674     SkSize radius = mappedRadius(ctx.ctm());
675     int width = SkScalarRoundToInt(radius.width());
676     int height = SkScalarRoundToInt(radius.height());
677 
678     // Width (or height) must fit in a signed 32-bit int to avoid UBSAN issues (crbug.com/1018190)
679     // Further, we limit the radius to something much smaller, to avoid extremely slow draw calls:
680     // (crbug.com/1123035):
681     constexpr int kMaxRadius = 100; // (std::numeric_limits<int>::max() - 1) / 2;
682 
683     if (width < 0 || height < 0 || width > kMaxRadius || height > kMaxRadius) {
684         return nullptr;
685     }
686 
687     SkIRect srcBounds = bounds;
688     srcBounds.offset(-inputOffset);
689 
690     if (0 == width && 0 == height) {
691         offset->fX = bounds.left();
692         offset->fY = bounds.top();
693         return input->makeSubset(srcBounds);
694     }
695 
696 #if defined(SK_GANESH)
697     if (ctx.gpuBacked()) {
698         auto context = ctx.getContext();
699 
700         // Ensure the input is in the destination color space. Typically applyCropRect will have
701         // called pad_image to account for our dilation of bounds, so the result will already be
702         // moved to the destination color space. If a filter DAG avoids that, then we use this
703         // fall-back, which saves us from having to do the xform during the filter itself.
704         input = ImageToColorSpace(input.get(), ctx.colorType(), ctx.colorSpace(),
705                                   ctx.surfaceProps());
706 
707         sk_sp<SkSpecialImage> result(apply_morphology(context, input.get(), srcBounds, fType,
708                                                       SkISize::Make(width, height), ctx));
709         if (result) {
710             offset->fX = bounds.left();
711             offset->fY = bounds.top();
712         }
713         return result;
714     }
715 #endif
716 
717     SkBitmap inputBM;
718 
719     if (!input->getROPixels(&inputBM)) {
720         return nullptr;
721     }
722 
723     if (inputBM.colorType() != kN32_SkColorType) {
724         return nullptr;
725     }
726 
727     SkImageInfo info = SkImageInfo::Make(bounds.size(), inputBM.colorType(), inputBM.alphaType());
728 
729     SkBitmap dst;
730     if (!dst.tryAllocPixels(info)) {
731         return nullptr;
732     }
733 
734     SkMorphologyImageFilter::Proc procX, procY;
735 
736     if (MorphType::kDilate == fType) {
737         procX = &morph<MorphType::kDilate, MorphDirection::kX>;
738         procY = &morph<MorphType::kDilate, MorphDirection::kY>;
739     } else {
740         procX = &morph<MorphType::kErode,  MorphDirection::kX>;
741         procY = &morph<MorphType::kErode,  MorphDirection::kY>;
742     }
743 
744     if (width > 0 && height > 0) {
745         SkBitmap tmp;
746         if (!tmp.tryAllocPixels(info)) {
747             return nullptr;
748         }
749 
750         call_proc_X(procX, inputBM, &tmp, width, srcBounds);
751         SkIRect tmpBounds = SkIRect::MakeWH(srcBounds.width(), srcBounds.height());
752         call_proc_Y(procY,
753                     tmp.getAddr32(tmpBounds.left(), tmpBounds.top()), tmp.rowBytesAsPixels(),
754                     &dst, height, tmpBounds);
755     } else if (width > 0) {
756         call_proc_X(procX, inputBM, &dst, width, srcBounds);
757     } else if (height > 0) {
758         call_proc_Y(procY,
759                     inputBM.getAddr32(srcBounds.left(), srcBounds.top()),
760                     inputBM.rowBytesAsPixels(),
761                     &dst, height, srcBounds);
762     }
763     offset->fX = bounds.left();
764     offset->fY = bounds.top();
765 
766     return SkSpecialImage::MakeFromRaster(SkIRect::MakeWH(bounds.width(), bounds.height()),
767                                           dst, ctx.surfaceProps());
768 }
769