1 // Copyright (c) 2006-2011 The Chromium Authors. All rights reserved.
2 //
3 // Redistribution and use in source and binary forms, with or without
4 // modification, are permitted provided that the following conditions
5 // are met:
6 //  * Redistributions of source code must retain the above copyright
7 //    notice, this list of conditions and the following disclaimer.
8 //  * Redistributions in binary form must reproduce the above copyright
9 //    notice, this list of conditions and the following disclaimer in
10 //    the documentation and/or other materials provided with the
11 //    distribution.
12 //  * Neither the name of Google, Inc. nor the names of its contributors
13 //    may be used to endorse or promote products derived from this
14 //    software without specific prior written permission.
15 //
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
19 // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
20 // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
21 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
22 // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
23 // OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24 // AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
25 // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
26 // OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 // SUCH DAMAGE.
28 
29 #ifndef SKIA_EXT_IMAGE_OPERATIONS_H_
30 #define SKIA_EXT_IMAGE_OPERATIONS_H_
31 
32 #include "skia/include/core/SkTypes.h"
33 #include "Types.h"
34 #include "convolver.h"
35 #include "skia/include/core/SkRect.h"
36 
37 class SkBitmap;
38 struct SkIRect;
39 
40 namespace skia {
41 
42 class ImageOperations {
43  public:
44   enum ResizeMethod {
45     //
46     // Quality Methods
47     //
48     // Those enumeration values express a desired quality/speed tradeoff.
49     // They are translated into an algorithm-specific method that depends
50     // on the capabilities (CPU, GPU) of the underlying platform.
51     // It is possible for all three methods to be mapped to the same
52     // algorithm on a given platform.
53 
54     // Good quality resizing. Fastest resizing with acceptable visual quality.
55     // This is typically intended for use during interactive layouts
56     // where slower platforms may want to trade image quality for large
57     // increase in resizing performance.
58     //
59     // For example the resizing implementation may devolve to linear
60     // filtering if this enables GPU acceleration to be used.
61     //
62     // Note that the underlying resizing method may be determined
63     // on the fly based on the parameters for a given resize call.
64     // For example an implementation using a GPU-based linear filter
65     // in the common case may still use a higher-quality software-based
66     // filter in cases where using the GPU would actually be slower - due
67     // to too much latency - or impossible - due to image format or size
68     // constraints.
69     RESIZE_GOOD,
70 
71     // Medium quality resizing. Close to high quality resizing (better
72     // than linear interpolation) with potentially some quality being
73     // traded-off for additional speed compared to RESIZE_BEST.
74     //
75     // This is intended, for example, for generation of large thumbnails
76     // (hundreds of pixels in each dimension) from large sources, where
77     // a linear filter would produce too many artifacts but where
78     // a RESIZE_HIGH might be too costly time-wise.
79     RESIZE_BETTER,
80 
81     // High quality resizing. The algorithm is picked to favor image quality.
82     RESIZE_BEST,
83 
84     //
85     // Algorithm-specific enumerations
86     //
87 
88     // Box filter. This is a weighted average of all of the pixels touching
89     // the destination pixel. For enlargement, this is nearest neighbor.
90     //
91     // You probably don't want this, it is here for testing since it is easy to
92     // compute. Use RESIZE_LANCZOS3 instead.
93     RESIZE_BOX,
94 
95     // 1-cycle Hamming filter. This is tall is the middle and falls off towards
96     // the window edges but without going to 0. This is about 40% faster than
97     // a 2-cycle Lanczos.
98     RESIZE_HAMMING1,
99 
100     // 2-cycle Lanczos filter. This is tall in the middle, goes negative on
101     // each side, then returns to zero. Does not provide as good a frequency
102     // response as a 3-cycle Lanczos but is roughly 30% faster.
103     RESIZE_LANCZOS2,
104 
105     // 3-cycle Lanczos filter. This is tall in the middle, goes negative on
106     // each side, then oscillates 2 more times. It gives nice sharp edges.
107     RESIZE_LANCZOS3,
108 
109     // Lanczos filter + subpixel interpolation. If subpixel rendering is not
110     // appropriate we automatically fall back to Lanczos.
111     RESIZE_SUBPIXEL,
112 
113     // enum aliases for first and last methods by algorithm or by quality.
114     RESIZE_FIRST_QUALITY_METHOD = RESIZE_GOOD,
115     RESIZE_LAST_QUALITY_METHOD = RESIZE_BEST,
116     RESIZE_FIRST_ALGORITHM_METHOD = RESIZE_BOX,
117     RESIZE_LAST_ALGORITHM_METHOD = RESIZE_SUBPIXEL,
118   };
119 
120   // Resizes the given source bitmap using the specified resize method, so that
121   // the entire image is (dest_size) big. The dest_subset is the rectangle in
122   // this destination image that should actually be returned.
123   //
124   // The output image will be (dest_subset.width(), dest_subset.height()). This
125   // will save work if you do not need the entire bitmap.
126   //
127   // The destination subset must be smaller than the destination image.
128   static SkBitmap Resize(const SkBitmap& source,
129                          ResizeMethod method,
130                          int dest_width, int dest_height,
131                          const SkIRect& dest_subset,
132                          void* dest_pixels = nullptr);
133 
134   // Alternate version for resizing and returning the entire bitmap rather than
135   // a subset.
136   static SkBitmap Resize(const SkBitmap& source,
137                          ResizeMethod method,
138                          int dest_width, int dest_height,
139                          void* dest_pixels = nullptr);
140 
141  private:
142   ImageOperations();  // Class for scoping only.
143 
144   // Supports all methods except RESIZE_SUBPIXEL.
145   static SkBitmap ResizeBasic(const SkBitmap& source,
146                               ResizeMethod method,
147                               int dest_width, int dest_height,
148                               const SkIRect& dest_subset,
149                               void* dest_pixels = nullptr);
150 
151   // Subpixel renderer.
152   static SkBitmap ResizeSubpixel(const SkBitmap& source,
153                                  int dest_width, int dest_height,
154                                  const SkIRect& dest_subset);
155 };
156 
157 // Returns the ceiling/floor as an integer.
CeilInt(float val)158 inline int CeilInt(float val) {
159   return static_cast<int>(ceil(val));
160 }
FloorInt(float val)161 inline int FloorInt(float val) {
162   return static_cast<int>(floor(val));
163 }
164 
165 // Filter function computation -------------------------------------------------
166 
167 // Evaluates the box filter, which goes from -0.5 to +0.5.
EvalBox(float x)168 inline float EvalBox(float x) {
169   return (x >= -0.5f && x < 0.5f) ? 1.0f : 0.0f;
170 }
171 
172 // Evaluates the Lanczos filter of the given filter size window for the given
173 // position.
174 //
175 // |filter_size| is the width of the filter (the "window"), outside of which
176 // the value of the function is 0. Inside of the window, the value is the
177 // normalized sinc function:
178 //   lanczos(x) = sinc(x) * sinc(x / filter_size);
179 // where
180 //   sinc(x) = sin(pi*x) / (pi*x);
EvalLanczos(int filter_size,float x)181 inline float EvalLanczos(int filter_size, float x) {
182   if (x <= -filter_size || x >= filter_size)
183     return 0.0f;  // Outside of the window.
184   if (x > -std::numeric_limits<float>::epsilon() &&
185       x < std::numeric_limits<float>::epsilon())
186     return 1.0f;  // Special case the discontinuity at the origin.
187   float xpi = x * static_cast<float>(M_PI);
188   return (sinf(xpi) / xpi) *  // sinc(x)
189           sinf(xpi / filter_size) / (xpi / filter_size);  // sinc(x/filter_size)
190 }
191 
192 // Evaluates the Hamming filter of the given filter size window for the given
193 // position.
194 //
195 // The filter covers [-filter_size, +filter_size]. Outside of this window
196 // the value of the function is 0. Inside of the window, the value is sinus
197 // cardinal multiplied by a recentered Hamming function. The traditional
198 // Hamming formula for a window of size N and n ranging in [0, N-1] is:
199 //   hamming(n) = 0.54 - 0.46 * cos(2 * pi * n / (N-1)))
200 // In our case we want the function centered for x == 0 and at its minimum
201 // on both ends of the window (x == +/- filter_size), hence the adjusted
202 // formula:
203 //   hamming(x) = (0.54 -
204 //                 0.46 * cos(2 * pi * (x - filter_size)/ (2 * filter_size)))
205 //              = 0.54 - 0.46 * cos(pi * x / filter_size - pi)
206 //              = 0.54 + 0.46 * cos(pi * x / filter_size)
EvalHamming(int filter_size,float x)207 inline float EvalHamming(int filter_size, float x) {
208   if (x <= -filter_size || x >= filter_size)
209     return 0.0f;  // Outside of the window.
210   if (x > -std::numeric_limits<float>::epsilon() &&
211       x < std::numeric_limits<float>::epsilon())
212     return 1.0f;  // Special case the sinc discontinuity at the origin.
213   const float xpi = x * static_cast<float>(M_PI);
214 
215   return ((sinf(xpi) / xpi) *  // sinc(x)
216           (0.54f + 0.46f * cosf(xpi / filter_size)));  // hamming(x)
217 }
218 
219 // ResizeFilter ----------------------------------------------------------------
220 
221 // Encapsulates computation and storage of the filters required for one complete
222 // resize operation.
223 
224 namespace resize {
225 
226   // Returns the number of pixels that the filer spans, in filter space (the
227   // destination image).
GetFilterSupport(ImageOperations::ResizeMethod method,float scale)228   inline float GetFilterSupport(ImageOperations::ResizeMethod method,
229                                 float scale) {
230     switch (method) {
231       case ImageOperations::RESIZE_BOX:
232         // The box filter just scales with the image scaling.
233         return 0.5f;  // Only want one side of the filter = /2.
234       case ImageOperations::RESIZE_HAMMING1:
235         // The Hamming filter takes as much space in the source image in
236         // each direction as the size of the window = 1 for Hamming1.
237         return 1.0f;
238       case ImageOperations::RESIZE_LANCZOS2:
239         // The Lanczos filter takes as much space in the source image in
240         // each direction as the size of the window = 2 for Lanczos2.
241         return 2.0f;
242       case ImageOperations::RESIZE_LANCZOS3:
243         // The Lanczos filter takes as much space in the source image in
244         // each direction as the size of the window = 3 for Lanczos3.
245         return 3.0f;
246       default:
247         return 1.0f;
248     }
249   }
250 
251   // Computes one set of filters either horizontally or vertically. The caller
252   // will specify the "min" and "max" rather than the bottom/top and
253   // right/bottom so that the same code can be re-used in each dimension.
254   //
255   // |src_depend_lo| and |src_depend_size| gives the range for the source
256   // depend rectangle (horizontally or vertically at the caller's discretion
257   // -- see above for what this means).
258   //
259   // Likewise, the range of destination values to compute and the scale factor
260   // for the transform is also specified.
261   void ComputeFilters(ImageOperations::ResizeMethod method,
262                       int src_size, int dst_size,
263                       int dest_subset_lo, int dest_subset_size,
264                       ConvolutionFilter1D* output);
265 
266   // Computes the filter value given the coordinate in filter space.
ComputeFilter(ImageOperations::ResizeMethod method,float pos)267   inline float ComputeFilter(ImageOperations::ResizeMethod method, float pos) {
268     switch (method) {
269       case ImageOperations::RESIZE_BOX:
270         return EvalBox(pos);
271       case ImageOperations::RESIZE_HAMMING1:
272         return EvalHamming(1, pos);
273       case ImageOperations::RESIZE_LANCZOS2:
274         return EvalLanczos(2, pos);
275       case ImageOperations::RESIZE_LANCZOS3:
276         return EvalLanczos(3, pos);
277       default:
278         return 0;
279     }
280   }
281 }
282 
283 }  // namespace skia
284 
285 #endif  // SKIA_EXT_IMAGE_OPERATIONS_H_
286