1 /*
2  * Copyright (C) 2012 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <cmath>
18 #include <cstdint>
19 
20 #include "RenderScriptToolkit.h"
21 #include "TaskProcessor.h"
22 #include "Utils.h"
23 
24 namespace renderscript {
25 
26 #define LOG_TAG "renderscript.toolkit.Blur"
27 
28 /**
29  * Blurs an image or a section of an image.
30  *
31  * Our algorithm does two passes: a vertical blur followed by an horizontal blur.
32  */
33 class BlurTask : public Task {
34     // The image we're blurring.
35     const uchar* mIn;
36     // Where we store the blurred image.
37     uchar* outArray;
38     // The size of the kernel radius is limited to 25 in ScriptIntrinsicBlur.java.
39     // So, the max kernel size is 51 (= 2 * 25 + 1).
40     // Considering SSSE3 case, which requires the size is multiple of 4,
41     // at least 52 words are necessary. Values outside of the kernel should be 0.
42     float mFp[104];
43     uint16_t mIp[104];
44 
45     // Working area to store the result of the vertical blur, to be used by the horizontal pass.
46     // There's one area per thread. Since the needed working area may be too large to put on the
47     // stack, we are allocating it from the heap. To avoid paying the allocation cost for each
48     // tile, we cache the scratch area here.
49     std::vector<void*> mScratch;       // Pointers to the scratch areas, one per thread.
50     std::vector<size_t> mScratchSize;  // The size in bytes of the scratch areas, one per thread.
51 
52     // The radius of the blur, in floating point and integer format.
53     float mRadius;
54     int mIradius;
55 
56     void kernelU4(void* outPtr, uint32_t xstart, uint32_t xend, uint32_t currentY,
57                   uint32_t threadIndex);
58     void kernelU1(void* outPtr, uint32_t xstart, uint32_t xend, uint32_t currentY);
59     void ComputeGaussianWeights();
60 
61     // Process a 2D tile of the overall work. threadIndex identifies which thread does the work.
62     void processData(int threadIndex, size_t startX, size_t startY, size_t endX,
63                      size_t endY) override;
64 
65    public:
BlurTask(const uint8_t * in,uint8_t * out,size_t sizeX,size_t sizeY,size_t vectorSize,uint32_t threadCount,float radius,const Restriction * restriction)66     BlurTask(const uint8_t* in, uint8_t* out, size_t sizeX, size_t sizeY, size_t vectorSize,
67              uint32_t threadCount, float radius, const Restriction* restriction)
68         : Task{sizeX, sizeY, vectorSize, false, restriction},
69           mIn{in},
70           outArray{out},
71           mScratch{threadCount},
72           mScratchSize{threadCount},
73           mRadius{std::min(25.0f, radius)} {
74         ComputeGaussianWeights();
75     }
76 
~BlurTask()77     ~BlurTask() {
78         for (size_t i = 0; i < mScratch.size(); i++) {
79             if (mScratch[i]) {
80                 free(mScratch[i]);
81             }
82         }
83     }
84 };
85 
ComputeGaussianWeights()86 void BlurTask::ComputeGaussianWeights() {
87     memset(mFp, 0, sizeof(mFp));
88     memset(mIp, 0, sizeof(mIp));
89 
90     // Compute gaussian weights for the blur
91     // e is the euler's number
92     float e = 2.718281828459045f;
93     float pi = 3.1415926535897932f;
94     // g(x) = (1 / (sqrt(2 * pi) * sigma)) * e ^ (-x^2 / (2 * sigma^2))
95     // x is of the form [-radius .. 0 .. radius]
96     // and sigma varies with the radius.
97     // Based on some experimental radius values and sigmas,
98     // we approximately fit sigma = f(radius) as
99     // sigma = radius * 0.4  + 0.6
100     // The larger the radius gets, the more our gaussian blur
101     // will resemble a box blur since with large sigma
102     // the gaussian curve begins to lose its shape
103     float sigma = 0.4f * mRadius + 0.6f;
104 
105     // Now compute the coefficients. We will store some redundant values to save
106     // some math during the blur calculations precompute some values
107     float coeff1 = 1.0f / (sqrtf(2.0f * pi) * sigma);
108     float coeff2 = - 1.0f / (2.0f * sigma * sigma);
109 
110     float normalizeFactor = 0.0f;
111     float floatR = 0.0f;
112     int r;
113     mIradius = (float)ceil(mRadius) + 0.5f;
114     for (r = -mIradius; r <= mIradius; r ++) {
115         floatR = (float)r;
116         mFp[r + mIradius] = coeff1 * powf(e, floatR * floatR * coeff2);
117         normalizeFactor += mFp[r + mIradius];
118     }
119 
120     // Now we need to normalize the weights because all our coefficients need to add up to one
121     normalizeFactor = 1.0f / normalizeFactor;
122     for (r = -mIradius; r <= mIradius; r ++) {
123         mFp[r + mIradius] *= normalizeFactor;
124         mIp[r + mIradius] = (uint16_t)(mFp[r + mIradius] * 65536.0f + 0.5f);
125     }
126 }
127 
128 /**
129  * Vertical blur of a uchar4 line.
130  *
131  * @param sizeY Number of cells of the input array in the vertical direction.
132  * @param out Where to place the computed value.
133  * @param x Coordinate of the point we're blurring.
134  * @param y Coordinate of the point we're blurring.
135  * @param ptrIn Start of the input array.
136  * @param iStride The size in byte of a row of the input array.
137  * @param gPtr The gaussian coefficients.
138  * @param iradius The radius of the blur.
139  */
OneVU4(uint32_t sizeY,float4 * out,int32_t x,int32_t y,const uchar * ptrIn,int iStride,const float * gPtr,int iradius)140 static void OneVU4(uint32_t sizeY, float4* out, int32_t x, int32_t y, const uchar* ptrIn,
141                    int iStride, const float* gPtr, int iradius) {
142     const uchar *pi = ptrIn + x*4;
143 
144     float4 blurredPixel = 0;
145     for (int r = -iradius; r <= iradius; r ++) {
146         int validY = std::max((y + r), 0);
147         validY = std::min(validY, (int)(sizeY - 1));
148         const uchar4 *pvy = (const uchar4 *)&pi[validY * iStride];
149         float4 pf = convert<float4>(pvy[0]);
150         blurredPixel += pf * gPtr[0];
151         gPtr++;
152     }
153 
154     out[0] = blurredPixel;
155 }
156 
157 /**
158  * Vertical blur of a uchar1 line.
159  *
160  * @param sizeY Number of cells of the input array in the vertical direction.
161  * @param out Where to place the computed value.
162  * @param x Coordinate of the point we're blurring.
163  * @param y Coordinate of the point we're blurring.
164  * @param ptrIn Start of the input array.
165  * @param iStride The size in byte of a row of the input array.
166  * @param gPtr The gaussian coefficients.
167  * @param iradius The radius of the blur.
168  */
OneVU1(uint32_t sizeY,float * out,int32_t x,int32_t y,const uchar * ptrIn,int iStride,const float * gPtr,int iradius)169 static void OneVU1(uint32_t sizeY, float *out, int32_t x, int32_t y,
170                    const uchar *ptrIn, int iStride, const float* gPtr, int iradius) {
171 
172     const uchar *pi = ptrIn + x;
173 
174     float blurredPixel = 0;
175     for (int r = -iradius; r <= iradius; r ++) {
176         int validY = std::max((y + r), 0);
177         validY = std::min(validY, (int)(sizeY - 1));
178         float pf = (float)pi[validY * iStride];
179         blurredPixel += pf * gPtr[0];
180         gPtr++;
181     }
182 
183     out[0] = blurredPixel;
184 }
185 
186 
187 extern "C" void rsdIntrinsicBlurU1_K(uchar *out, uchar const *in, size_t w, size_t h,
188                  size_t p, size_t x, size_t y, size_t count, size_t r, uint16_t const *tab);
189 extern "C" void rsdIntrinsicBlurU4_K(uchar4 *out, uchar4 const *in, size_t w, size_t h,
190                  size_t p, size_t x, size_t y, size_t count, size_t r, uint16_t const *tab);
191 
192 #if defined(ARCH_X86_HAVE_SSSE3)
193 extern void rsdIntrinsicBlurVFU4_K(void *dst, const void *pin, int stride, const void *gptr,
194                                    int rct, int x1, int ct);
195 extern void rsdIntrinsicBlurHFU4_K(void *dst, const void *pin, const void *gptr, int rct, int x1,
196                                    int ct);
197 extern void rsdIntrinsicBlurHFU1_K(void *dst, const void *pin, const void *gptr, int rct, int x1,
198                                    int ct);
199 #endif
200 
201 /**
202  * Vertical blur of a line of RGBA, knowing that there's enough rows above and below us to avoid
203  * dealing with boundary conditions.
204  *
205  * @param out Where to store the results. This is the input to the horizontal blur.
206  * @param ptrIn The input data for this line.
207  * @param iStride The width of the input.
208  * @param gPtr The gaussian coefficients.
209  * @param ct The diameter of the blur.
210  * @param len How many cells to blur.
211  * @param usesSimd Whether this processor supports SIMD.
212  */
OneVFU4(float4 * out,const uchar * ptrIn,int iStride,const float * gPtr,int ct,int x2,bool usesSimd)213 static void OneVFU4(float4 *out, const uchar *ptrIn, int iStride, const float* gPtr, int ct,
214                     int x2, bool usesSimd) {
215     int x1 = 0;
216 #if defined(ARCH_X86_HAVE_SSSE3)
217     if (usesSimd) {
218         int t = (x2 - x1);
219         t &= ~1;
220         if (t) {
221             rsdIntrinsicBlurVFU4_K(out, ptrIn, iStride, gPtr, ct, x1, x1 + t);
222         }
223         x1 += t;
224         out += t;
225         ptrIn += t << 2;
226     }
227 #else
228     (void) usesSimd; // Avoid unused parameter warning.
229 #endif
230     while(x2 > x1) {
231         const uchar *pi = ptrIn;
232         float4 blurredPixel = 0;
233         const float* gp = gPtr;
234 
235         for (int r = 0; r < ct; r++) {
236             float4 pf = convert<float4>(((const uchar4 *)pi)[0]);
237             blurredPixel += pf * gp[0];
238             pi += iStride;
239             gp++;
240         }
241         out->xyzw = blurredPixel;
242         x1++;
243         out++;
244         ptrIn+=4;
245     }
246 }
247 
248 /**
249  * Vertical blur of a line of U_8, knowing that there's enough rows above and below us to avoid
250  * dealing with boundary conditions.
251  *
252  * @param out Where to store the results. This is the input to the horizontal blur.
253  * @param ptrIn The input data for this line.
254  * @param iStride The width of the input.
255  * @param gPtr The gaussian coefficients.
256  * @param ct The diameter of the blur.
257  * @param len How many cells to blur.
258  * @param usesSimd Whether this processor supports SIMD.
259  */
OneVFU1(float * out,const uchar * ptrIn,int iStride,const float * gPtr,int ct,int len,bool usesSimd)260 static void OneVFU1(float* out, const uchar* ptrIn, int iStride, const float* gPtr, int ct, int len,
261                     bool usesSimd) {
262     int x1 = 0;
263 
264     while((len > x1) && (((uintptr_t)ptrIn) & 0x3)) {
265         const uchar *pi = ptrIn;
266         float blurredPixel = 0;
267         const float* gp = gPtr;
268 
269         for (int r = 0; r < ct; r++) {
270             float pf = (float)pi[0];
271             blurredPixel += pf * gp[0];
272             pi += iStride;
273             gp++;
274         }
275         out[0] = blurredPixel;
276         x1++;
277         out++;
278         ptrIn++;
279         len--;
280     }
281 #if defined(ARCH_X86_HAVE_SSSE3)
282     if (usesSimd && (len > x1)) {
283         int t = (len - x1) >> 2;
284         t &= ~1;
285         if (t) {
286             rsdIntrinsicBlurVFU4_K(out, ptrIn, iStride, gPtr, ct, 0, t );
287             len -= t << 2;
288             ptrIn += t << 2;
289             out += t << 2;
290         }
291     }
292 #else
293     (void) usesSimd; // Avoid unused parameter warning.
294 #endif
295     while(len > 0) {
296         const uchar *pi = ptrIn;
297         float blurredPixel = 0;
298         const float* gp = gPtr;
299 
300         for (int r = 0; r < ct; r++) {
301             float pf = (float)pi[0];
302             blurredPixel += pf * gp[0];
303             pi += iStride;
304             gp++;
305         }
306         out[0] = blurredPixel;
307         len--;
308         out++;
309         ptrIn++;
310     }
311 }
312 
313 /**
314  * Horizontal blur of a uchar4 line.
315  *
316  * @param sizeX Number of cells of the input array in the horizontal direction.
317  * @param out Where to place the computed value.
318  * @param x Coordinate of the point we're blurring.
319  * @param ptrIn The start of the input row from which we're indexing x.
320  * @param gPtr The gaussian coefficients.
321  * @param iradius The radius of the blur.
322  */
OneHU4(uint32_t sizeX,uchar4 * out,int32_t x,const float4 * ptrIn,const float * gPtr,int iradius)323 static void OneHU4(uint32_t sizeX, uchar4* out, int32_t x, const float4* ptrIn, const float* gPtr,
324                    int iradius) {
325     float4 blurredPixel = 0;
326     for (int r = -iradius; r <= iradius; r ++) {
327         int validX = std::max((x + r), 0);
328         validX = std::min(validX, (int)(sizeX - 1));
329         float4 pf = ptrIn[validX];
330         blurredPixel += pf * gPtr[0];
331         gPtr++;
332     }
333 
334     out->xyzw = convert<uchar4>(blurredPixel);
335 }
336 
337 /**
338  * Horizontal blur of a uchar line.
339  *
340  * @param sizeX Number of cells of the input array in the horizontal direction.
341  * @param out Where to place the computed value.
342  * @param x Coordinate of the point we're blurring.
343  * @param ptrIn The start of the input row from which we're indexing x.
344  * @param gPtr The gaussian coefficients.
345  * @param iradius The radius of the blur.
346  */
OneHU1(uint32_t sizeX,uchar * out,int32_t x,const float * ptrIn,const float * gPtr,int iradius)347 static void OneHU1(uint32_t sizeX, uchar* out, int32_t x, const float* ptrIn, const float* gPtr,
348                    int iradius) {
349     float blurredPixel = 0;
350     for (int r = -iradius; r <= iradius; r ++) {
351         int validX = std::max((x + r), 0);
352         validX = std::min(validX, (int)(sizeX - 1));
353         float pf = ptrIn[validX];
354         blurredPixel += pf * gPtr[0];
355         gPtr++;
356     }
357 
358     out[0] = (uchar)blurredPixel;
359 }
360 
361 /**
362  * Full blur of a line of RGBA data.
363  *
364  * @param outPtr Where to store the results
365  * @param xstart The index of the section we're starting to blur.
366  * @param xend  The end index of the section.
367  * @param currentY The index of the line we're blurring.
368  * @param usesSimd Whether this processor supports SIMD.
369  */
kernelU4(void * outPtr,uint32_t xstart,uint32_t xend,uint32_t currentY,uint32_t threadIndex)370 void BlurTask::kernelU4(void *outPtr, uint32_t xstart, uint32_t xend, uint32_t currentY,
371                         uint32_t threadIndex) {
372     float4 stackbuf[2048];
373     float4 *buf = &stackbuf[0];
374     const uint32_t stride = mSizeX * mVectorSize;
375 
376     uchar4 *out = (uchar4 *)outPtr;
377     uint32_t x1 = xstart;
378     uint32_t x2 = xend;
379 
380 #if defined(ARCH_ARM_USE_INTRINSICS)
381     if (mUsesSimd && mSizeX >= 4) {
382       rsdIntrinsicBlurU4_K(out, (uchar4 const *)(mIn + stride * currentY),
383                  mSizeX, mSizeY,
384                  stride, x1, currentY, x2 - x1, mIradius, mIp + mIradius);
385         return;
386     }
387 #endif
388 
389     if (mSizeX > 2048) {
390         if ((mSizeX > mScratchSize[threadIndex]) || !mScratch[threadIndex]) {
391             // Pad the side of the allocation by one unit to allow alignment later
392             mScratch[threadIndex] = realloc(mScratch[threadIndex], (mSizeX + 1) * 16);
393             mScratchSize[threadIndex] = mSizeX;
394         }
395         // realloc only aligns to 8 bytes so we manually align to 16.
396         buf = (float4 *) ((((intptr_t)mScratch[threadIndex]) + 15) & ~0xf);
397     }
398     float4 *fout = (float4 *)buf;
399     int y = currentY;
400     if ((y > mIradius) && (y < ((int)mSizeY - mIradius))) {
401         const uchar *pi = mIn + (y - mIradius) * stride;
402         OneVFU4(fout, pi, stride, mFp, mIradius * 2 + 1, mSizeX, mUsesSimd);
403     } else {
404         x1 = 0;
405         while(mSizeX > x1) {
406             OneVU4(mSizeY, fout, x1, y, mIn, stride, mFp, mIradius);
407             fout++;
408             x1++;
409         }
410     }
411 
412     x1 = xstart;
413     while ((x1 < (uint32_t)mIradius) && (x1 < x2)) {
414         OneHU4(mSizeX, out, x1, buf, mFp, mIradius);
415         out++;
416         x1++;
417     }
418 #if defined(ARCH_X86_HAVE_SSSE3)
419     if (mUsesSimd) {
420         if ((x1 + mIradius) < x2) {
421             rsdIntrinsicBlurHFU4_K(out, buf - mIradius, mFp,
422                                    mIradius * 2 + 1, x1, x2 - mIradius);
423             out += (x2 - mIradius) - x1;
424             x1 = x2 - mIradius;
425         }
426     }
427 #endif
428     while(x2 > x1) {
429         OneHU4(mSizeX, out, x1, buf, mFp, mIradius);
430         out++;
431         x1++;
432     }
433 }
434 
435 /**
436  * Full blur of a line of U_8 data.
437  *
438  * @param outPtr Where to store the results
439  * @param xstart The index of the section we're starting to blur.
440  * @param xend  The end index of the section.
441  * @param currentY The index of the line we're blurring.
442  */
kernelU1(void * outPtr,uint32_t xstart,uint32_t xend,uint32_t currentY)443 void BlurTask::kernelU1(void *outPtr, uint32_t xstart, uint32_t xend, uint32_t currentY) {
444     float buf[4 * 2048];
445     const uint32_t stride = mSizeX * mVectorSize;
446 
447     uchar *out = (uchar *)outPtr;
448     uint32_t x1 = xstart;
449     uint32_t x2 = xend;
450 
451 #if defined(ARCH_ARM_USE_INTRINSICS)
452     if (mUsesSimd && mSizeX >= 16) {
453         // The specialisation for r<=8 has an awkward prefill case, which is
454         // fiddly to resolve, where starting close to the right edge can cause
455         // a read beyond the end of input.  So avoid that case here.
456         if (mIradius > 8 || (mSizeX - std::max(0, (int32_t)x1 - 8)) >= 16) {
457             rsdIntrinsicBlurU1_K(out, mIn + stride * currentY, mSizeX, mSizeY,
458                      stride, x1, currentY, x2 - x1, mIradius, mIp + mIradius);
459             return;
460         }
461     }
462 #endif
463 
464     float *fout = (float *)buf;
465     int y = currentY;
466     if ((y > mIradius) && (y < ((int)mSizeY - mIradius -1))) {
467         const uchar *pi = mIn + (y - mIradius) * stride;
468         OneVFU1(fout, pi, stride, mFp, mIradius * 2 + 1, mSizeX, mUsesSimd);
469     } else {
470         x1 = 0;
471         while(mSizeX > x1) {
472             OneVU1(mSizeY, fout, x1, y, mIn, stride, mFp, mIradius);
473             fout++;
474             x1++;
475         }
476     }
477 
478     x1 = xstart;
479     while ((x1 < x2) &&
480            ((x1 < (uint32_t)mIradius) || (((uintptr_t)out) & 0x3))) {
481         OneHU1(mSizeX, out, x1, buf, mFp, mIradius);
482         out++;
483         x1++;
484     }
485 #if defined(ARCH_X86_HAVE_SSSE3)
486     if (mUsesSimd) {
487         if ((x1 + mIradius) < x2) {
488             uint32_t len = x2 - (x1 + mIradius);
489             len &= ~3;
490 
491             // rsdIntrinsicBlurHFU1_K() processes each four float values in |buf| at once, so it
492             // nees to ensure four more values can be accessed in order to avoid accessing
493             // uninitialized buffer.
494             if (len > 4) {
495                 len -= 4;
496                 rsdIntrinsicBlurHFU1_K(out, ((float *)buf) - mIradius, mFp,
497                                        mIradius * 2 + 1, x1, x1 + len);
498                 out += len;
499                 x1 += len;
500             }
501         }
502     }
503 #endif
504     while(x2 > x1) {
505         OneHU1(mSizeX, out, x1, buf, mFp, mIradius);
506         out++;
507         x1++;
508     }
509 }
510 
processData(int threadIndex,size_t startX,size_t startY,size_t endX,size_t endY)511 void BlurTask::processData(int threadIndex, size_t startX, size_t startY, size_t endX,
512                            size_t endY) {
513     for (size_t y = startY; y < endY; y++) {
514         void* outPtr = outArray + (mSizeX * y + startX) * mVectorSize;
515         if (mVectorSize == 4) {
516             kernelU4(outPtr, startX, endX, y, threadIndex);
517         } else {
518             kernelU1(outPtr, startX, endX, y);
519         }
520     }
521 }
522 
blur(const uint8_t * in,uint8_t * out,size_t sizeX,size_t sizeY,size_t vectorSize,int radius,const Restriction * restriction)523 void RenderScriptToolkit::blur(const uint8_t* in, uint8_t* out, size_t sizeX, size_t sizeY,
524                                size_t vectorSize, int radius, const Restriction* restriction) {
525 #ifdef ANDROID_RENDERSCRIPT_TOOLKIT_VALIDATE
526     if (!validRestriction(LOG_TAG, sizeX, sizeY, restriction)) {
527         return;
528     }
529     if (radius <= 0 || radius > 25) {
530         ALOGE("The radius should be between 1 and 25. %d provided.", radius);
531     }
532     if (vectorSize != 1 && vectorSize != 4) {
533         ALOGE("The vectorSize should be 1 or 4. %zu provided.", vectorSize);
534     }
535 #endif
536 
537     BlurTask task(in, out, sizeX, sizeY, vectorSize, processor->getNumberOfThreads(), radius,
538                   restriction);
539     processor->doTask(&task);
540 }
541 
542 }  // namespace renderscript
543