File: Blur.cpp

package info (click to toggle)
firefox 147.0.2-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,683,484 kB
  • sloc: cpp: 7,607,246; javascript: 6,533,185; ansic: 3,775,227; python: 1,415,393; xml: 634,561; asm: 438,951; java: 186,241; sh: 62,752; makefile: 18,079; objc: 13,092; perl: 12,808; yacc: 4,583; cs: 3,846; pascal: 3,448; lex: 1,720; ruby: 1,003; php: 436; lisp: 258; awk: 247; sql: 66; sed: 54; csh: 10; exp: 6
file content (405 lines) | stat: -rw-r--r-- 12,843 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "Blur.h"

#include <algorithm>
#include <math.h>
#include <string.h>

#include "NumericTools.h"

#include "2D.h"
#include "DataSurfaceHelpers.h"
#include "HelpersSkia.h"
#include "Tools.h"

#include "skia/include/core/SkCanvas.h"
#include "skia/include/core/SkSurface.h"
#include "skia/include/effects/SkImageFilters.h"

namespace mozilla {
namespace gfx {

template <typename T>
struct PixelValue {
  T value;

  explicit PixelValue(T aValue) : value(aValue) {}

  void Spread(const PixelValue& aOther) {
    value = std::max(value, aOther.value);
  }
};

template <>
struct PixelValue<uint32_t> {
  union {
    struct {
      uint8_t r;
      uint8_t g;
      uint8_t b;
      uint8_t a;
    };
    uint32_t value;
  };

  explicit PixelValue(uint32_t aValue) { value = aValue; }

  void Spread(const PixelValue& aOther) {
    r = std::max(r, aOther.r);
    g = std::max(g, aOther.g);
    b = std::max(b, aOther.b);
    a = std::max(a, aOther.a);
  }
};

template <typename T>
static void SpreadHorizontal(const T* aInput, T* aOutput, int32_t aRadius,
                             int32_t aWidth, int32_t aRows, int32_t aStride,
                             const IntRect& aSkipRect) {
  if (aRadius == 0) {
    memcpy(aOutput, aInput, aStride * aRows * sizeof(T));
    return;
  }

  bool skipRectCoversWholeRow =
      0 >= aSkipRect.X() && aWidth <= aSkipRect.XMost();
  for (int32_t y = 0; y < aRows; y++) {
    // Check whether the skip rect intersects this row. If the skip
    // rect covers the whole surface in this row, we can avoid
    // this row entirely (and any others along the skip rect).
    bool inSkipRectY = aSkipRect.ContainsY(y);
    if (inSkipRectY && skipRectCoversWholeRow) {
      y = aSkipRect.YMost() - 1;
      continue;
    }

    T* dst = &aOutput[aStride * y];
    for (int32_t x = 0; x < aWidth; x++) {
      // Check whether we are within the skip rect. If so, go
      // to the next point outside the skip rect.
      if (inSkipRectY && aSkipRect.ContainsX(x)) {
        x = aSkipRect.XMost();
        if (x >= aWidth) break;
      }

      int32_t sMin = std::max(x - aRadius, 0);
      int32_t sMax = std::min(x + aRadius, aWidth - 1);
      const auto* src =
          reinterpret_cast<const PixelValue<T>*>(&aInput[aStride * y + sMin]);
      PixelValue<T> v(0);
      for (int32_t s = sMin; s <= sMax; ++s) {
        v.Spread(*src);
        ++src;
      }
      *dst = v.value;
      ++dst;
    }
  }
}

template <typename T>
static void SpreadVertical(const T* aInput, T* aOutput, int32_t aRadius,
                           int32_t aWidth, int32_t aRows, int32_t aStride,
                           const IntRect& aSkipRect) {
  if (aRadius == 0) {
    memcpy(aOutput, aInput, aStride * aRows * sizeof(T));
    return;
  }

  bool skipRectCoversWholeColumn =
      0 >= aSkipRect.Y() && aRows <= aSkipRect.YMost();
  for (int32_t x = 0; x < aWidth; x++) {
    bool inSkipRectX = aSkipRect.ContainsX(x);
    if (inSkipRectX && skipRectCoversWholeColumn) {
      x = aSkipRect.XMost() - 1;
      continue;
    }

    T* dst = &aOutput[x];
    for (int32_t y = 0; y < aRows; y++) {
      // Check whether we are within the skip rect. If so, go
      // to the next point outside the skip rect.
      if (inSkipRectX && aSkipRect.ContainsY(y)) {
        y = aSkipRect.YMost();
        if (y >= aRows) break;
      }

      int32_t sMin = std::max(y - aRadius, 0);
      int32_t sMax = std::min(y + aRadius, aRows - 1);
      const auto* src =
          reinterpret_cast<const PixelValue<T>*>(&aInput[aStride * sMin + x]);
      PixelValue<T> v(0);
      for (int32_t s = sMin; s <= sMax; ++s) {
        v.Spread(*src);
        src += aStride;
      }
      *dst = v.value;
      dst += aStride;
    }
  }
}

GaussianBlur::GaussianBlur(const Rect& aRect, const IntSize& aSpreadRadius,
                           const Point& aSigma, const Rect* aDirtyRect,
                           const Rect* aSkipRect, SurfaceFormat aFormat,
                           bool aClamp) {
  Init(aRect, aSpreadRadius, aSigma, aDirtyRect, aSkipRect, aFormat, aClamp);
}

GaussianBlur::GaussianBlur() {}

void GaussianBlur::Init(const Rect& aRect, const IntSize& aSpreadRadius,
                        const Point& aBlurSigma, const Rect* aDirtyRect,
                        const Rect* aSkipRect, SurfaceFormat aFormat,
                        bool aClamp) {
  switch (aFormat) {
    case SurfaceFormat::A8:
    case SurfaceFormat::B8G8R8A8:
    case SurfaceFormat::B8G8R8X8:
    case SurfaceFormat::R8G8B8A8:
    case SurfaceFormat::R8G8B8X8:
    case SurfaceFormat::A8R8G8B8:
    case SurfaceFormat::X8R8G8B8:
      break;
    default:
      MOZ_RELEASE_ASSERT(false, "Unsupported format for GaussianBlur");
      break;
  }

  mFormat = aFormat;
  mClamp = aClamp;
  mSpreadRadius = aSpreadRadius;
  mBlurSigma = aBlurSigma;
  mBlurRadius = GaussianBlur::CalculateBlurRadius(aBlurSigma);

  Rect rect(aRect);
  rect.Inflate(Size(mBlurRadius + aSpreadRadius));
  rect.RoundOut();

  if (aDirtyRect) {
    // If we get passed a dirty rect from layout, we can minimize the
    // shadow size and make painting faster.
    mHasDirtyRect = true;
    mDirtyRect = *aDirtyRect;
    Rect requiredBlurArea = mDirtyRect.Intersect(rect);
    requiredBlurArea.Inflate(Size(mBlurRadius + aSpreadRadius));
    rect = requiredBlurArea.Intersect(rect);
  } else {
    mHasDirtyRect = false;
  }

  mRect = TruncatedToInt(rect);
  if (mRect.IsEmpty()) {
    return;
  }

  if (aSkipRect) {
    // If we get passed a skip rect, we can lower the amount of
    // blurring/spreading we need to do. We convert it to IntRect to avoid
    // expensive int<->float conversions if we were to use Rect instead.
    Rect skipRect = *aSkipRect;
    skipRect.Deflate(Size(mBlurRadius + aSpreadRadius));
    mSkipRect = RoundedIn(skipRect);
    mSkipRect = mSkipRect.Intersect(mRect);
    if (mSkipRect.IsEqualInterior(mRect)) {
      return;
    }

    mSkipRect -= mRect.TopLeft();
    if (mSkipRect.IsEmpty()) {
      mSkipRect = IntRect();
    }
  } else {
    mSkipRect = IntRect();
  }

  int32_t stride = StrideForFormatAndWidth(mFormat, mRect.Width());
  if (stride >= 0) {
    mStride = stride;

    // We need to leave room for an additional 3 bytes for a potential overrun
    // in our blurring code.
    size_t size = BufferSizeFromStrideAndHeight(mStride, mRect.Height(), 3);
    if (size != 0) {
      mSurfaceAllocationSize = size;
    }
  }
}

GaussianBlur::GaussianBlur(const Point& aSigma, bool aClamp)
    : mBlurSigma(aSigma),
      mBlurRadius(CalculateBlurRadius(aSigma)),
      mClamp(aClamp) {}

GaussianBlur::~GaussianBlur() = default;

IntSize GaussianBlur::GetSize() const { return mRect.Size(); }

SurfaceFormat GaussianBlur::GetFormat() const { return mFormat; }

int32_t GaussianBlur::GetStride() const { return mStride; }

IntRect GaussianBlur::GetRect() const { return mRect; }

Rect* GaussianBlur::GetDirtyRect() {
  if (mHasDirtyRect) {
    return &mDirtyRect;
  }

  return nullptr;
}

size_t GaussianBlur::GetSurfaceAllocationSize() const {
  return mSurfaceAllocationSize;
}

bool GaussianBlur::Spread(uint8_t* aData, int32_t aStride, const IntSize& aSize,
                          SurfaceFormat aFormat) const {
  size_t bufSize = BufferSizeFromStrideAndHeight(aStride, aSize.height);
  if (!bufSize) {
    return false;
  }
  uint8_t* tmpData = (uint8_t*)calloc(1, bufSize);
  if (!tmpData) {
    return false;
  }
  if (aFormat == SurfaceFormat::A8) {
    SpreadHorizontal(aData, tmpData, mSpreadRadius.width, aSize.width,
                     aSize.height, aStride, mSkipRect);
    SpreadVertical(tmpData, aData, mSpreadRadius.height, aSize.width,
                   aSize.height, aStride, mSkipRect);
  } else {
    uint32_t* data32 = reinterpret_cast<uint32_t*>(aData);
    uint32_t* tmpData32 = reinterpret_cast<uint32_t*>(tmpData);
    int32_t stride32 = aStride / sizeof(uint32_t);
    SpreadHorizontal(data32, tmpData32, mSpreadRadius.width, aSize.width,
                     aSize.height, stride32, mSkipRect);
    SpreadVertical(tmpData32, data32, mSpreadRadius.height, aSize.width,
                   aSize.height, stride32, mSkipRect);
  }
  free(tmpData);
  return true;
}

void GaussianBlur::Blur(uint8_t* aData, int32_t aStride, const IntSize& aSize,
                        SurfaceFormat aFormat) const {
  if (!aData || aStride <= 0) {
    return;
  }
  if (aFormat == SurfaceFormat::UNKNOWN) {
    aFormat = mFormat;
    if (aFormat == SurfaceFormat::UNKNOWN) {
      return;
    }
  }
  if (mBlurRadius.width > 0 || mBlurRadius.height > 0 ||
      mSpreadRadius.width > 0 || mSpreadRadius.height > 0) {
    if (sk_sp<SkSurface> surface = SkSurfaces::WrapPixels(
            MakeSkiaImageInfo(aSize, aFormat), aData, aStride)) {
      BlurSkSurface(surface.get());
    }
  }
}

bool GaussianBlur::BlurSkSurface(SkSurface* aSurface) const {
  IntSize size(aSurface->width(), aSurface->height());
  MOZ_ASSERT(mRect.IsEmpty() || size == mRect.Size());
  SkCanvas* canvas = aSurface->getCanvas();
  if (!canvas) {
    return false;
  }

  if (mSpreadRadius.width > 0 || mSpreadRadius.height > 0) {
    SkImageInfo info;
    size_t rowBytes = 0;
    uint8_t* pixels = (uint8_t*)canvas->accessTopLayerPixels(&info, &rowBytes);
    if (!pixels ||
        !Spread(pixels, rowBytes, IntSize(info.width(), info.height()),
                SkiaColorTypeToGfxFormat(info.colorType()))) {
      return false;
    }
  }

  if (mBlurRadius.width <= 0 && mBlurRadius.height <= 0) {
    return true;
  }

  sk_sp<SkImage> snapshot = aSurface->makeImageSnapshot();
  if (!snapshot) {
    return false;
  }
  canvas->save();
  canvas->resetMatrix();
  SkPaint blurPaint;
  blurPaint.setBlendMode(SkBlendMode::kSrc);
  sk_sp<SkImageFilter> blurFilter(SkImageFilters::Blur(
      mBlurSigma.x, mBlurSigma.y,
      mClamp ? SkTileMode::kClamp : SkTileMode::kDecal, nullptr));
  blurPaint.setImageFilter(blurFilter);
  SkSamplingOptions sampling(SkFilterMode::kNearest);
  auto constraint = SkCanvas::kFast_SrcRectConstraint;
  if (mSkipRect.IsEmpty()) {
    canvas->drawImage(snapshot, 0, 0, sampling, &blurPaint);
  } else {
    SkRect top = SkRect::MakeIWH(size.width, size.height);
    if (top.intersect(SkRect::MakeLTRB(0, 0, size.width, mSkipRect.y))) {
      canvas->drawImageRect(snapshot, top, top, sampling, &blurPaint,
                            constraint);
    }
    SkRect left = SkRect::MakeIWH(size.width, size.height);
    if (left.intersect(
            SkRect::MakeLTRB(0, mSkipRect.y, mSkipRect.x, mSkipRect.YMost()))) {
      canvas->drawImageRect(snapshot, left, left, sampling, &blurPaint,
                            constraint);
    }
    SkRect right = SkRect::MakeIWH(size.width, size.height);
    if (right.intersect(SkRect::MakeLTRB(mSkipRect.XMost(), mSkipRect.y,
                                         size.width, mSkipRect.YMost()))) {
      canvas->drawImageRect(snapshot, right, right, sampling, &blurPaint,
                            constraint);
    }
    SkRect bottom = SkRect::MakeIWH(size.width, size.height);
    if (bottom.intersect(
            SkRect::MakeLTRB(0, mSkipRect.YMost(), size.width, size.height))) {
      canvas->drawImageRect(snapshot, bottom, bottom, sampling, &blurPaint,
                            constraint);
    }
  }
  canvas->restore();
  return true;
}

/**
 * Compute the box blur size (which we're calling the blur radius) from
 * the standard deviation.
 *
 * Much of this, the 3 * sqrt(2 * pi) / 4, is the known value for
 * approximating a Gaussian using box blurs.  This yields quite a good
 * approximation for a Gaussian.  Then we multiply this by 1.5 since our
 * code wants the radius of the entire triple-box-blur kernel instead of
 * the diameter of an individual box blur.  For more details, see:
 *   http://www.w3.org/TR/SVG11/filters.html#feGaussianBlurElement
 *   https://bugzilla.mozilla.org/show_bug.cgi?id=590039#c19
 */
constexpr double sqrt_2_PI = 0x1.40d931ff62705p+1;  // sqrt is not constexpr
static constexpr Float GAUSSIAN_SCALE_FACTOR = Float((3 * sqrt_2_PI / 4) * 1.5);

IntSize GaussianBlur::CalculateBlurRadius(const Point& aStd) {
  IntSize size(
      static_cast<int32_t>(floor(aStd.x * GAUSSIAN_SCALE_FACTOR + 0.5f)),
      static_cast<int32_t>(floor(aStd.y * GAUSSIAN_SCALE_FACTOR + 0.5f)));

  return size;
}

Float GaussianBlur::CalculateBlurSigma(int32_t aBlurRadius) {
  return aBlurRadius / GAUSSIAN_SCALE_FACTOR;
}

}  // namespace gfx
}  // namespace mozilla