SkBitmapScaler.cpp revision dcfaa73e68f54f19c7900577b71f585fb8a7e1ae
1#include "SkBitmapScaler.h"
2#include "SkBitmapFilter.h"
3#include "SkRect.h"
4#include "SkTArray.h"
5#include "SkErrorInternals.h"
6#include "SkConvolver.h"
7
8// SkResizeFilter ----------------------------------------------------------------
9
10// Encapsulates computation and storage of the filters required for one complete
11// resize operation.
12class SkResizeFilter {
13public:
14    SkResizeFilter(SkBitmapScaler::ResizeMethod method,
15                   int srcFullWidth, int srcFullHeight,
16                   int destWidth, int destHeight,
17                   const SkIRect& destSubset,
18                   const SkConvolutionProcs& convolveProcs);
19    ~SkResizeFilter() {
20        SkDELETE( fBitmapFilter );
21    }
22
23    // Returns the filled filter values.
24    const SkConvolutionFilter1D& xFilter() { return fXFilter; }
25    const SkConvolutionFilter1D& yFilter() { return fYFilter; }
26
27private:
28
29    SkBitmapFilter* fBitmapFilter;
30
31    // Computes one set of filters either horizontally or vertically. The caller
32    // will specify the "min" and "max" rather than the bottom/top and
33    // right/bottom so that the same code can be re-used in each dimension.
34    //
35    // |srcDependLo| and |srcDependSize| gives the range for the source
36    // depend rectangle (horizontally or vertically at the caller's discretion
37    // -- see above for what this means).
38    //
39    // Likewise, the range of destination values to compute and the scale factor
40    // for the transform is also specified.
41
42    void computeFilters(int srcSize,
43                        int destSubsetLo, int destSubsetSize,
44                        float scale,
45                        SkConvolutionFilter1D* output,
46                        const SkConvolutionProcs& convolveProcs);
47
48    SkConvolutionFilter1D fXFilter;
49    SkConvolutionFilter1D fYFilter;
50};
51
52SkResizeFilter::SkResizeFilter(SkBitmapScaler::ResizeMethod method,
53                               int srcFullWidth, int srcFullHeight,
54                               int destWidth, int destHeight,
55                               const SkIRect& destSubset,
56                               const SkConvolutionProcs& convolveProcs) {
57
58    // method will only ever refer to an "algorithm method".
59    SkASSERT((SkBitmapScaler::RESIZE_FIRST_ALGORITHM_METHOD <= method) &&
60             (method <= SkBitmapScaler::RESIZE_LAST_ALGORITHM_METHOD));
61
62    switch(method) {
63        case SkBitmapScaler::RESIZE_BOX:
64            fBitmapFilter = SkNEW(SkBoxFilter);
65            break;
66        case SkBitmapScaler::RESIZE_TRIANGLE:
67            fBitmapFilter = SkNEW(SkTriangleFilter);
68            break;
69        case SkBitmapScaler::RESIZE_MITCHELL:
70            fBitmapFilter = SkNEW_ARGS(SkMitchellFilter, (1.f/3.f, 1.f/3.f));
71            break;
72        case SkBitmapScaler::RESIZE_HAMMING:
73            fBitmapFilter = SkNEW(SkHammingFilter);
74            break;
75        case SkBitmapScaler::RESIZE_LANCZOS3:
76            fBitmapFilter = SkNEW(SkLanczosFilter);
77            break;
78        default:
79            // NOTREACHED:
80            fBitmapFilter = SkNEW_ARGS(SkMitchellFilter, (1.f/3.f, 1.f/3.f));
81            break;
82    }
83
84
85    float scaleX = static_cast<float>(destWidth) /
86                   static_cast<float>(srcFullWidth);
87    float scaleY = static_cast<float>(destHeight) /
88                   static_cast<float>(srcFullHeight);
89
90    this->computeFilters(srcFullWidth, destSubset.fLeft, destSubset.width(),
91                         scaleX, &fXFilter, convolveProcs);
92    this->computeFilters(srcFullHeight, destSubset.fTop, destSubset.height(),
93                         scaleY, &fYFilter, convolveProcs);
94}
95
96// TODO(egouriou): Take advantage of periods in the convolution.
97// Practical resizing filters are periodic outside of the border area.
98// For Lanczos, a scaling by a (reduced) factor of p/q (q pixels in the
99// source become p pixels in the destination) will have a period of p.
100// A nice consequence is a period of 1 when downscaling by an integral
101// factor. Downscaling from typical display resolutions is also bound
102// to produce interesting periods as those are chosen to have multiple
103// small factors.
104// Small periods reduce computational load and improve cache usage if
105// the coefficients can be shared. For periods of 1 we can consider
106// loading the factors only once outside the borders.
107void SkResizeFilter::computeFilters(int srcSize,
108                                  int destSubsetLo, int destSubsetSize,
109                                  float scale,
110                                  SkConvolutionFilter1D* output,
111                                  const SkConvolutionProcs& convolveProcs) {
112  int destSubsetHi = destSubsetLo + destSubsetSize;  // [lo, hi)
113
114  // When we're doing a magnification, the scale will be larger than one. This
115  // means the destination pixels are much smaller than the source pixels, and
116  // that the range covered by the filter won't necessarily cover any source
117  // pixel boundaries. Therefore, we use these clamped values (max of 1) for
118  // some computations.
119  float clampedScale = SkTMin(1.0f, scale);
120
121  // This is how many source pixels from the center we need to count
122  // to support the filtering function.
123  float srcSupport = fBitmapFilter->width() / clampedScale;
124
125  // Speed up the divisions below by turning them into multiplies.
126  float invScale = 1.0f / scale;
127
128  SkTArray<float> filterValues(64);
129  SkTArray<short> fixedFilterValues(64);
130
131  // Loop over all pixels in the output range. We will generate one set of
132  // filter values for each one. Those values will tell us how to blend the
133  // source pixels to compute the destination pixel.
134  for (int destSubsetI = destSubsetLo; destSubsetI < destSubsetHi;
135       destSubsetI++) {
136    // Reset the arrays. We don't declare them inside so they can re-use the
137    // same malloc-ed buffer.
138    filterValues.reset();
139    fixedFilterValues.reset();
140
141    // This is the pixel in the source directly under the pixel in the dest.
142    // Note that we base computations on the "center" of the pixels. To see
143    // why, observe that the destination pixel at coordinates (0, 0) in a 5.0x
144    // downscale should "cover" the pixels around the pixel with *its center*
145    // at coordinates (2.5, 2.5) in the source, not those around (0, 0).
146    // Hence we need to scale coordinates (0.5, 0.5), not (0, 0).
147    float srcPixel = (static_cast<float>(destSubsetI) + 0.5f) * invScale;
148
149    // Compute the (inclusive) range of source pixels the filter covers.
150    int srcBegin = SkTMax(0, SkScalarFloorToInt(srcPixel - srcSupport));
151    int srcEnd = SkTMin(srcSize - 1, SkScalarCeilToInt(srcPixel + srcSupport));
152
153    // Compute the unnormalized filter value at each location of the source
154    // it covers.
155    float filterSum = 0.0f;  // Sub of the filter values for normalizing.
156    for (int curFilterPixel = srcBegin; curFilterPixel <= srcEnd;
157         curFilterPixel++) {
158      // Distance from the center of the filter, this is the filter coordinate
159      // in source space. We also need to consider the center of the pixel
160      // when comparing distance against 'srcPixel'. In the 5x downscale
161      // example used above the distance from the center of the filter to
162      // the pixel with coordinates (2, 2) should be 0, because its center
163      // is at (2.5, 2.5).
164      float srcFilterDist =
165          ((static_cast<float>(curFilterPixel) + 0.5f) - srcPixel);
166
167      // Since the filter really exists in dest space, map it there.
168      float destFilterDist = srcFilterDist * clampedScale;
169
170      // Compute the filter value at that location.
171      float filterValue = fBitmapFilter->evaluate(destFilterDist);
172      filterValues.push_back(filterValue);
173
174      filterSum += filterValue;
175    }
176    SkASSERT(!filterValues.empty());
177
178    // The filter must be normalized so that we don't affect the brightness of
179    // the image. Convert to normalized fixed point.
180    short fixedSum = 0;
181    for (int i = 0; i < filterValues.count(); i++) {
182      short curFixed = output->FloatToFixed(filterValues[i] / filterSum);
183      fixedSum += curFixed;
184      fixedFilterValues.push_back(curFixed);
185    }
186
187    // The conversion to fixed point will leave some rounding errors, which
188    // we add back in to avoid affecting the brightness of the image. We
189    // arbitrarily add this to the center of the filter array (this won't always
190    // be the center of the filter function since it could get clipped on the
191    // edges, but it doesn't matter enough to worry about that case).
192    short leftovers = output->FloatToFixed(1.0f) - fixedSum;
193    fixedFilterValues[fixedFilterValues.count() / 2] += leftovers;
194
195    // Now it's ready to go.
196    output->AddFilter(srcBegin, &fixedFilterValues[0],
197                      static_cast<int>(fixedFilterValues.count()));
198  }
199
200  if (convolveProcs.fApplySIMDPadding) {
201      convolveProcs.fApplySIMDPadding( output );
202  }
203}
204
205static SkBitmapScaler::ResizeMethod ResizeMethodToAlgorithmMethod(
206                                    SkBitmapScaler::ResizeMethod method) {
207    // Convert any "Quality Method" into an "Algorithm Method"
208    if (method >= SkBitmapScaler::RESIZE_FIRST_ALGORITHM_METHOD &&
209    method <= SkBitmapScaler::RESIZE_LAST_ALGORITHM_METHOD) {
210        return method;
211    }
212    // The call to SkBitmapScalerGtv::Resize() above took care of
213    // GPU-acceleration in the cases where it is possible. So now we just
214    // pick the appropriate software method for each resize quality.
215    switch (method) {
216        // Users of RESIZE_GOOD are willing to trade a lot of quality to
217        // get speed, allowing the use of linear resampling to get hardware
218        // acceleration (SRB). Hence any of our "good" software filters
219        // will be acceptable, so we use a triangle.
220        case SkBitmapScaler::RESIZE_GOOD:
221            return SkBitmapScaler::RESIZE_TRIANGLE;
222        // Users of RESIZE_BETTER are willing to trade some quality in order
223        // to improve performance, but are guaranteed not to devolve to a linear
224        // resampling. In visual tests we see that Hamming-1 is not as good as
225        // Lanczos-2, however it is about 40% faster and Lanczos-2 itself is
226        // about 30% faster than Lanczos-3. The use of Hamming-1 has been deemed
227        // an acceptable trade-off between quality and speed.
228        case SkBitmapScaler::RESIZE_BETTER:
229            return SkBitmapScaler::RESIZE_HAMMING;
230        default:
231#ifdef SK_HIGH_QUALITY_IS_LANCZOS
232            return SkBitmapScaler::RESIZE_LANCZOS3;
233#else
234            return SkBitmapScaler::RESIZE_MITCHELL;
235#endif
236    }
237}
238
239// static
240bool SkBitmapScaler::Resize(SkBitmap* resultPtr,
241                            const SkBitmap& source,
242                            ResizeMethod method,
243                            int destWidth, int destHeight,
244                            const SkIRect& destSubset,
245                            const SkConvolutionProcs& convolveProcs,
246                            SkBitmap::Allocator* allocator) {
247  // Ensure that the ResizeMethod enumeration is sound.
248    SkASSERT(((RESIZE_FIRST_QUALITY_METHOD <= method) &&
249        (method <= RESIZE_LAST_QUALITY_METHOD)) ||
250        ((RESIZE_FIRST_ALGORITHM_METHOD <= method) &&
251        (method <= RESIZE_LAST_ALGORITHM_METHOD)));
252
253    SkIRect dest = { 0, 0, destWidth, destHeight };
254    if (!dest.contains(destSubset)) {
255        SkErrorInternals::SetError( kInvalidArgument_SkError,
256                                    "Sorry, you passed me a bitmap resize "
257                                    " method I have never heard of: %d",
258                                    method );
259    }
260
261    // If the size of source or destination is 0, i.e. 0x0, 0xN or Nx0, just
262    // return empty.
263    if (source.width() < 1 || source.height() < 1 ||
264        destWidth < 1 || destHeight < 1) {
265        // todo: seems like we could handle negative dstWidth/Height, since that
266        // is just a negative scale (flip)
267        return false;
268    }
269
270    method = ResizeMethodToAlgorithmMethod(method);
271
272    // Check that we deal with an "algorithm methods" from this point onward.
273    SkASSERT((SkBitmapScaler::RESIZE_FIRST_ALGORITHM_METHOD <= method) &&
274        (method <= SkBitmapScaler::RESIZE_LAST_ALGORITHM_METHOD));
275
276    SkAutoLockPixels locker(source);
277    if (!source.readyToDraw() ||
278        source.config() != SkBitmap::kARGB_8888_Config) {
279        return false;
280    }
281
282    SkResizeFilter filter(method, source.width(), source.height(),
283                          destWidth, destHeight, destSubset, convolveProcs);
284
285    // Get a source bitmap encompassing this touched area. We construct the
286    // offsets and row strides such that it looks like a new bitmap, while
287    // referring to the old data.
288    const unsigned char* sourceSubset =
289        reinterpret_cast<const unsigned char*>(source.getPixels());
290
291    // Convolve into the result.
292    SkBitmap result;
293    result.setConfig(SkBitmap::kARGB_8888_Config,
294                     destSubset.width(), destSubset.height(), 0,
295                     source.alphaType());
296    result.allocPixels(allocator, NULL);
297    if (!result.readyToDraw()) {
298        return false;
299    }
300
301    BGRAConvolve2D(sourceSubset, static_cast<int>(source.rowBytes()),
302        !source.isOpaque(), filter.xFilter(), filter.yFilter(),
303        static_cast<int>(result.rowBytes()),
304        static_cast<unsigned char*>(result.getPixels()),
305        convolveProcs, true);
306
307    *resultPtr = result;
308    resultPtr->lockPixels();
309    SkASSERT(NULL != resultPtr->getPixels());
310    return true;
311}
312
313// static
314bool SkBitmapScaler::Resize(SkBitmap* resultPtr,
315                            const SkBitmap& source,
316                            ResizeMethod method,
317                            int destWidth, int destHeight,
318                            const SkConvolutionProcs& convolveProcs,
319                            SkBitmap::Allocator* allocator) {
320    SkIRect destSubset = { 0, 0, destWidth, destHeight };
321    return Resize(resultPtr, source, method, destWidth, destHeight, destSubset,
322                  convolveProcs, allocator);
323}
324