1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include <stddef.h>
6 #include <stdint.h>
7
8 #include <algorithm>
9 #include <limits>
10
11 #include "skia/ext/image_operations.h"
12
13 #include "base/containers/stack_container.h"
14 #include "base/logging.h"
15 #include "base/macros.h"
16 #include "base/metrics/histogram_macros.h"
17 #include "base/numerics/math_constants.h"
18 #include "base/time/time.h"
19 #include "base/trace_event/trace_event.h"
20 #include "build/build_config.h"
21 #include "skia/ext/convolver.h"
22 #include "third_party/skia/include/core/SkColorPriv.h"
23 #include "third_party/skia/include/core/SkRect.h"
24
25 namespace skia {
26
27 namespace {
28
29 // Returns the ceiling/floor as an integer.
CeilInt(float val)30 inline int CeilInt(float val) {
31 return static_cast<int>(ceil(val));
32 }
FloorInt(float val)33 inline int FloorInt(float val) {
34 return static_cast<int>(floor(val));
35 }
36
37 // Filter function computation -------------------------------------------------
38
39 // Evaluates the box filter, which goes from -0.5 to +0.5.
EvalBox(float x)40 float EvalBox(float x) {
41 return (x >= -0.5f && x < 0.5f) ? 1.0f : 0.0f;
42 }
43
44 // Evaluates the Lanczos filter of the given filter size window for the given
45 // position.
46 //
47 // |filter_size| is the width of the filter (the "window"), outside of which
48 // the value of the function is 0. Inside of the window, the value is the
49 // normalized sinc function:
50 // lanczos(x) = sinc(x) * sinc(x / filter_size);
51 // where
52 // sinc(x) = sin(pi*x) / (pi*x);
EvalLanczos(int filter_size,float x)53 float EvalLanczos(int filter_size, float x) {
54 if (x <= -filter_size || x >= filter_size)
55 return 0.0f; // Outside of the window.
56 if (x > -std::numeric_limits<float>::epsilon() &&
57 x < std::numeric_limits<float>::epsilon())
58 return 1.0f; // Special case the discontinuity at the origin.
59 float xpi = x * base::kPiFloat;
60 return (sin(xpi) / xpi) * // sinc(x)
61 sin(xpi / filter_size) / (xpi / filter_size); // sinc(x/filter_size)
62 }
63
64 // Evaluates the Hamming filter of the given filter size window for the given
65 // position.
66 //
67 // The filter covers [-filter_size, +filter_size]. Outside of this window
68 // the value of the function is 0. Inside of the window, the value is sinus
69 // cardinal multiplied by a recentered Hamming function. The traditional
70 // Hamming formula for a window of size N and n ranging in [0, N-1] is:
71 // hamming(n) = 0.54 - 0.46 * cos(2 * pi * n / (N-1)))
72 // In our case we want the function centered for x == 0 and at its minimum
73 // on both ends of the window (x == +/- filter_size), hence the adjusted
74 // formula:
75 // hamming(x) = (0.54 -
76 // 0.46 * cos(2 * pi * (x - filter_size)/ (2 * filter_size)))
77 // = 0.54 - 0.46 * cos(pi * x / filter_size - pi)
78 // = 0.54 + 0.46 * cos(pi * x / filter_size)
EvalHamming(int filter_size,float x)79 float EvalHamming(int filter_size, float x) {
80 if (x <= -filter_size || x >= filter_size)
81 return 0.0f; // Outside of the window.
82 if (x > -std::numeric_limits<float>::epsilon() &&
83 x < std::numeric_limits<float>::epsilon())
84 return 1.0f; // Special case the sinc discontinuity at the origin.
85 const float xpi = x * base::kPiFloat;
86
87 return ((sin(xpi) / xpi) * // sinc(x)
88 (0.54f + 0.46f * cos(xpi / filter_size))); // hamming(x)
89 }
90
91 // ResizeFilter ----------------------------------------------------------------
92
93 // Encapsulates computation and storage of the filters required for one complete
94 // resize operation.
95 class ResizeFilter {
96 public:
97 ResizeFilter(ImageOperations::ResizeMethod method,
98 int src_full_width, int src_full_height,
99 int dest_width, int dest_height,
100 const SkIRect& dest_subset);
101
102 // Returns the filled filter values.
x_filter()103 const ConvolutionFilter1D& x_filter() { return x_filter_; }
y_filter()104 const ConvolutionFilter1D& y_filter() { return y_filter_; }
105
106 private:
107 // Returns the number of pixels that the filer spans, in filter space (the
108 // destination image).
GetFilterSupport(float scale)109 float GetFilterSupport(float scale) {
110 switch (method_) {
111 case ImageOperations::RESIZE_BOX:
112 // The box filter just scales with the image scaling.
113 return 0.5f; // Only want one side of the filter = /2.
114 case ImageOperations::RESIZE_HAMMING1:
115 // The Hamming filter takes as much space in the source image in
116 // each direction as the size of the window = 1 for Hamming1.
117 return 1.0f;
118 case ImageOperations::RESIZE_LANCZOS3:
119 // The Lanczos filter takes as much space in the source image in
120 // each direction as the size of the window = 3 for Lanczos3.
121 return 3.0f;
122 default:
123 NOTREACHED();
124 return 1.0f;
125 }
126 }
127
128 // Computes one set of filters either horizontally or vertically. The caller
129 // will specify the "min" and "max" rather than the bottom/top and
130 // right/bottom so that the same code can be re-used in each dimension.
131 //
132 // |src_depend_lo| and |src_depend_size| gives the range for the source
133 // depend rectangle (horizontally or vertically at the caller's discretion
134 // -- see above for what this means).
135 //
136 // Likewise, the range of destination values to compute and the scale factor
137 // for the transform is also specified.
138 void ComputeFilters(int src_size,
139 int dest_subset_lo, int dest_subset_size,
140 float scale,
141 ConvolutionFilter1D* output);
142
143 // Computes the filter value given the coordinate in filter space.
ComputeFilter(float pos)144 inline float ComputeFilter(float pos) {
145 switch (method_) {
146 case ImageOperations::RESIZE_BOX:
147 return EvalBox(pos);
148 case ImageOperations::RESIZE_HAMMING1:
149 return EvalHamming(1, pos);
150 case ImageOperations::RESIZE_LANCZOS3:
151 return EvalLanczos(3, pos);
152 default:
153 NOTREACHED();
154 return 0;
155 }
156 }
157
158 ImageOperations::ResizeMethod method_;
159
160 ConvolutionFilter1D x_filter_;
161 ConvolutionFilter1D y_filter_;
162
163 DISALLOW_COPY_AND_ASSIGN(ResizeFilter);
164 };
165
ResizeFilter(ImageOperations::ResizeMethod method,int src_full_width,int src_full_height,int dest_width,int dest_height,const SkIRect & dest_subset)166 ResizeFilter::ResizeFilter(ImageOperations::ResizeMethod method,
167 int src_full_width,
168 int src_full_height,
169 int dest_width,
170 int dest_height,
171 const SkIRect& dest_subset)
172 : method_(method) {
173 // method_ will only ever refer to an "algorithm method".
174 SkASSERT((ImageOperations::RESIZE_FIRST_ALGORITHM_METHOD <= method) &&
175 (method <= ImageOperations::RESIZE_LAST_ALGORITHM_METHOD));
176
177 float scale_x = static_cast<float>(dest_width) /
178 static_cast<float>(src_full_width);
179 float scale_y = static_cast<float>(dest_height) /
180 static_cast<float>(src_full_height);
181
182 ComputeFilters(src_full_width, dest_subset.fLeft, dest_subset.width(),
183 scale_x, &x_filter_);
184 ComputeFilters(src_full_height, dest_subset.fTop, dest_subset.height(),
185 scale_y, &y_filter_);
186 }
187
188 // TODO(egouriou): Take advantage of periods in the convolution.
189 // Practical resizing filters are periodic outside of the border area.
190 // For Lanczos, a scaling by a (reduced) factor of p/q (q pixels in the
191 // source become p pixels in the destination) will have a period of p.
192 // A nice consequence is a period of 1 when downscaling by an integral
193 // factor. Downscaling from typical display resolutions is also bound
194 // to produce interesting periods as those are chosen to have multiple
195 // small factors.
196 // Small periods reduce computational load and improve cache usage if
197 // the coefficients can be shared. For periods of 1 we can consider
198 // loading the factors only once outside the borders.
ComputeFilters(int src_size,int dest_subset_lo,int dest_subset_size,float scale,ConvolutionFilter1D * output)199 void ResizeFilter::ComputeFilters(int src_size,
200 int dest_subset_lo, int dest_subset_size,
201 float scale,
202 ConvolutionFilter1D* output) {
203 int dest_subset_hi = dest_subset_lo + dest_subset_size; // [lo, hi)
204
205 // When we're doing a magnification, the scale will be larger than one. This
206 // means the destination pixels are much smaller than the source pixels, and
207 // that the range covered by the filter won't necessarily cover any source
208 // pixel boundaries. Therefore, we use these clamped values (max of 1) for
209 // some computations.
210 float clamped_scale = std::min(1.0f, scale);
211
212 // This is how many source pixels from the center we need to count
213 // to support the filtering function.
214 float src_support = GetFilterSupport(clamped_scale) / clamped_scale;
215
216 // Speed up the divisions below by turning them into multiplies.
217 float inv_scale = 1.0f / scale;
218
219 base::StackVector<float, 64> filter_values;
220 base::StackVector<int16_t, 64> fixed_filter_values;
221
222 // Loop over all pixels in the output range. We will generate one set of
223 // filter values for each one. Those values will tell us how to blend the
224 // source pixels to compute the destination pixel.
225 for (int dest_subset_i = dest_subset_lo; dest_subset_i < dest_subset_hi;
226 dest_subset_i++) {
227 // Reset the arrays. We don't declare them inside so they can re-use the
228 // same malloc-ed buffer.
229 filter_values->clear();
230 fixed_filter_values->clear();
231
232 // This is the pixel in the source directly under the pixel in the dest.
233 // Note that we base computations on the "center" of the pixels. To see
234 // why, observe that the destination pixel at coordinates (0, 0) in a 5.0x
235 // downscale should "cover" the pixels around the pixel with *its center*
236 // at coordinates (2.5, 2.5) in the source, not those around (0, 0).
237 // Hence we need to scale coordinates (0.5, 0.5), not (0, 0).
238 float src_pixel = (static_cast<float>(dest_subset_i) + 0.5f) * inv_scale;
239
240 // Compute the (inclusive) range of source pixels the filter covers.
241 int src_begin = std::max(0, FloorInt(src_pixel - src_support));
242 int src_end = std::min(src_size - 1, CeilInt(src_pixel + src_support));
243
244 // Compute the unnormalized filter value at each location of the source
245 // it covers.
246 float filter_sum = 0.0f; // Sub of the filter values for normalizing.
247 for (int cur_filter_pixel = src_begin; cur_filter_pixel <= src_end;
248 cur_filter_pixel++) {
249 // Distance from the center of the filter, this is the filter coordinate
250 // in source space. We also need to consider the center of the pixel
251 // when comparing distance against 'src_pixel'. In the 5x downscale
252 // example used above the distance from the center of the filter to
253 // the pixel with coordinates (2, 2) should be 0, because its center
254 // is at (2.5, 2.5).
255 float src_filter_dist =
256 ((static_cast<float>(cur_filter_pixel) + 0.5f) - src_pixel);
257
258 // Since the filter really exists in dest space, map it there.
259 float dest_filter_dist = src_filter_dist * clamped_scale;
260
261 // Compute the filter value at that location.
262 float filter_value = ComputeFilter(dest_filter_dist);
263 filter_values->push_back(filter_value);
264
265 filter_sum += filter_value;
266 }
267 DCHECK(!filter_values->empty()) << "We should always get a filter!";
268
269 // The filter must be normalized so that we don't affect the brightness of
270 // the image. Convert to normalized fixed point.
271 int16_t fixed_sum = 0;
272 for (size_t i = 0; i < filter_values->size(); i++) {
273 int16_t cur_fixed = output->FloatToFixed(filter_values[i] / filter_sum);
274 fixed_sum += cur_fixed;
275 fixed_filter_values->push_back(cur_fixed);
276 }
277
278 // The conversion to fixed point will leave some rounding errors, which
279 // we add back in to avoid affecting the brightness of the image. We
280 // arbitrarily add this to the center of the filter array (this won't always
281 // be the center of the filter function since it could get clipped on the
282 // edges, but it doesn't matter enough to worry about that case).
283 int16_t leftovers = output->FloatToFixed(1.0f) - fixed_sum;
284 fixed_filter_values[fixed_filter_values->size() / 2] += leftovers;
285
286 // Now it's ready to go.
287 output->AddFilter(src_begin, &fixed_filter_values[0],
288 static_cast<int>(fixed_filter_values->size()));
289 }
290
291 output->PaddingForSIMD();
292 }
293
ResizeMethodToAlgorithmMethod(ImageOperations::ResizeMethod method)294 ImageOperations::ResizeMethod ResizeMethodToAlgorithmMethod(
295 ImageOperations::ResizeMethod method) {
296 // Convert any "Quality Method" into an "Algorithm Method"
297 if (method >= ImageOperations::RESIZE_FIRST_ALGORITHM_METHOD &&
298 method <= ImageOperations::RESIZE_LAST_ALGORITHM_METHOD) {
299 return method;
300 }
301 // The call to ImageOperationsGtv::Resize() above took care of
302 // GPU-acceleration in the cases where it is possible. So now we just
303 // pick the appropriate software method for each resize quality.
304 switch (method) {
305 // Users of RESIZE_GOOD are willing to trade a lot of quality to
306 // get speed, allowing the use of linear resampling to get hardware
307 // acceleration (SRB). Hence any of our "good" software filters
308 // will be acceptable, and we use the fastest one, Hamming-1.
309 case ImageOperations::RESIZE_GOOD:
310 // Users of RESIZE_BETTER are willing to trade some quality in order
311 // to improve performance, but are guaranteed not to devolve to a linear
312 // resampling. In visual tests we see that Hamming-1 is not as good as
313 // Lanczos-2, however it is about 40% faster and Lanczos-2 itself is
314 // about 30% faster than Lanczos-3. The use of Hamming-1 has been deemed
315 // an acceptable trade-off between quality and speed.
316 case ImageOperations::RESIZE_BETTER:
317 return ImageOperations::RESIZE_HAMMING1;
318 default:
319 return ImageOperations::RESIZE_LANCZOS3;
320 }
321 }
322
323 } // namespace
324
325 // Resize ----------------------------------------------------------------------
326
327 // static
Resize(const SkPixmap & source,ResizeMethod method,int dest_width,int dest_height,const SkIRect & dest_subset,SkBitmap::Allocator * allocator)328 SkBitmap ImageOperations::Resize(const SkPixmap& source,
329 ResizeMethod method,
330 int dest_width,
331 int dest_height,
332 const SkIRect& dest_subset,
333 SkBitmap::Allocator* allocator) {
334 TRACE_EVENT2("disabled-by-default-skia", "ImageOperations::Resize",
335 "src_pixels", source.width() * source.height(), "dst_pixels",
336 dest_width * dest_height);
337 // Ensure that the ResizeMethod enumeration is sound.
338 SkASSERT(((RESIZE_FIRST_QUALITY_METHOD <= method) &&
339 (method <= RESIZE_LAST_QUALITY_METHOD)) ||
340 ((RESIZE_FIRST_ALGORITHM_METHOD <= method) &&
341 (method <= RESIZE_LAST_ALGORITHM_METHOD)));
342
343 // Time how long this takes to see if it's a problem for users.
344 base::TimeTicks resize_start = base::TimeTicks::Now();
345
346 // If the size of source or destination is 0, i.e. 0x0, 0xN or Nx0, just
347 // return empty.
348 if (source.width() < 1 || source.height() < 1 ||
349 dest_width < 1 || dest_height < 1)
350 return SkBitmap();
351
352 SkIRect dest = {0, 0, dest_width, dest_height};
353 DCHECK(dest.contains(dest_subset))
354 << "The supplied subset does not fall within the destination image.";
355
356 method = ResizeMethodToAlgorithmMethod(method);
357 // Check that we deal with an "algorithm methods" from this point onward.
358 SkASSERT((ImageOperations::RESIZE_FIRST_ALGORITHM_METHOD <= method) &&
359 (method <= ImageOperations::RESIZE_LAST_ALGORITHM_METHOD));
360
361 if (!source.addr() || source.colorType() != kN32_SkColorType)
362 return SkBitmap();
363
364 ResizeFilter filter(method, source.width(), source.height(),
365 dest_width, dest_height, dest_subset);
366
367 // Get a source bitmap encompassing this touched area. We construct the
368 // offsets and row strides such that it looks like a new bitmap, while
369 // referring to the old data.
370 const uint8_t* source_subset =
371 reinterpret_cast<const uint8_t*>(source.addr());
372
373 // Convolve into the result.
374 SkBitmap result;
375 result.setInfo(
376 source.info().makeWH(dest_subset.width(), dest_subset.height()));
377 result.allocPixels(allocator);
378 if (!result.readyToDraw())
379 return SkBitmap();
380
381 BGRAConvolve2D(source_subset, static_cast<int>(source.rowBytes()),
382 !source.isOpaque(), filter.x_filter(), filter.y_filter(),
383 static_cast<int>(result.rowBytes()),
384 static_cast<unsigned char*>(result.getPixels()),
385 true);
386
387 base::TimeDelta delta = base::TimeTicks::Now() - resize_start;
388 UMA_HISTOGRAM_TIMES("Image.ResampleMS", delta);
389
390 return result;
391 }
392
393 // static
Resize(const SkBitmap & source,ResizeMethod method,int dest_width,int dest_height,const SkIRect & dest_subset,SkBitmap::Allocator * allocator)394 SkBitmap ImageOperations::Resize(const SkBitmap& source,
395 ResizeMethod method,
396 int dest_width,
397 int dest_height,
398 const SkIRect& dest_subset,
399 SkBitmap::Allocator* allocator) {
400 SkPixmap pixmap;
401 if (!source.peekPixels(&pixmap))
402 return SkBitmap();
403 return Resize(pixmap, method, dest_width, dest_height, dest_subset,
404 allocator);
405 }
406
407 // static
Resize(const SkBitmap & source,ResizeMethod method,int dest_width,int dest_height,SkBitmap::Allocator * allocator)408 SkBitmap ImageOperations::Resize(const SkBitmap& source,
409 ResizeMethod method,
410 int dest_width, int dest_height,
411 SkBitmap::Allocator* allocator) {
412 SkIRect dest_subset = { 0, 0, dest_width, dest_height };
413 return Resize(source, method, dest_width, dest_height, dest_subset,
414 allocator);
415 }
416
417 } // namespace skia
418