1 #define __NR_FILTER_GAUSSIAN_CPP__
3 /*
4 * Gaussian blur renderer
5 *
6 * Authors:
7 * Niko Kiirala <niko@kiirala.com>
8 * bulia byak
9 * Jasper van de Gronde <th.v.d.gronde@hccnet.nl>
10 *
11 * Copyright (C) 2006 authors
12 *
13 * Released under GNU GPL, read the file 'COPYING' for more information
14 */
16 #include <algorithm>
17 #include <cmath>
18 #include <complex>
19 #include <cstdlib>
20 #include <glib.h>
21 #include <limits>
22 #if HAVE_OPENMP
23 #include <omp.h>
24 #endif //HAVE_OPENMP
26 #include "2geom/isnan.h"
28 #include "display/nr-filter-primitive.h"
29 #include "display/nr-filter-gaussian.h"
30 #include "display/nr-filter-types.h"
31 #include "display/nr-filter-units.h"
32 #include "libnr/nr-pixblock.h"
33 #include "libnr/nr-matrix.h"
34 #include "libnr/nr-matrix-fns.h"
35 #include "util/fixed_point.h"
36 #include "preferences.h"
38 // IIR filtering method based on:
39 // L.J. van Vliet, I.T. Young, and P.W. Verbeek, Recursive Gaussian Derivative Filters,
40 // in: A.K. Jain, S. Venkatesh, B.C. Lovell (eds.),
41 // ICPR'98, Proc. 14th Int. Conference on Pattern Recognition (Brisbane, Aug. 16-20),
42 // IEEE Computer Society Press, Los Alamitos, 1998, 509-514.
43 //
44 // Using the backwards-pass initialization procedure from:
45 // Boundary Conditions for Young - van Vliet Recursive Filtering
46 // Bill Triggs, Michael Sdika
47 // IEEE Transactions on Signal Processing, Volume 54, Number 5 - may 2006
49 // Number of IIR filter coefficients used. Currently only 3 is supported.
50 // "Recursive Gaussian Derivative Filters" says this is enough though (and
51 // some testing indeed shows that the quality doesn't improve much if larger
52 // filters are used).
53 static size_t const N = 3;
55 template<typename InIt, typename OutIt, typename Size>
56 void copy_n(InIt beg_in, Size N, OutIt beg_out) {
57 std::copy(beg_in, beg_in+N, beg_out);
58 }
60 // Type used for IIR filter coefficients (can be 10.21 signed fixed point, see Anisotropic Gaussian Filtering Using Fixed Point Arithmetic, Christoph H. Lampert & Oliver Wirjadi, 2006)
61 typedef double IIRValue;
63 // Type used for FIR filter coefficients (can be 16.16 unsigned fixed point, should have 8 or more bits in the fractional part, the integer part should be capable of storing approximately 20*255)
64 typedef Inkscape::Util::FixedPoint<unsigned int,16> FIRValue;
66 template<typename T> static inline T sqr(T const& v) { return v*v; }
68 template<typename T> static inline T clip(T const& v, T const& a, T const& b) {
69 if ( v < a ) return a;
70 if ( v > b ) return b;
71 return v;
72 }
74 template<typename Tt, typename Ts>
75 static inline Tt round_cast(Ts const& v) {
76 static Ts const rndoffset(.5);
77 return static_cast<Tt>(v+rndoffset);
78 }
80 template<typename Tt, typename Ts>
81 static inline Tt clip_round_cast(Ts const& v, Tt const minval=std::numeric_limits<Tt>::min(), Tt const maxval=std::numeric_limits<Tt>::max()) {
82 if ( v < minval ) return minval;
83 if ( v > maxval ) return maxval;
84 return round_cast<Tt>(v);
85 }
87 namespace NR {
89 FilterGaussian::FilterGaussian()
90 {
91 _deviation_x = _deviation_y = 0.0;
92 }
94 FilterPrimitive *FilterGaussian::create()
95 {
96 return new FilterGaussian();
97 }
99 FilterGaussian::~FilterGaussian()
100 {
101 // Nothing to do here
102 }
104 static int
105 _effect_area_scr(double const deviation)
106 {
107 return (int)std::ceil(deviation * 3.0);
108 }
110 static void
111 _make_kernel(FIRValue *const kernel, double const deviation)
112 {
113 int const scr_len = _effect_area_scr(deviation);
114 double const d_sq = sqr(deviation) * 2;
115 double k[scr_len+1]; // This is only called for small kernel sizes (above approximately 10 coefficients the IIR filter is used)
117 // Compute kernel and sum of coefficients
118 // Note that actually only half the kernel is computed, as it is symmetric
119 double sum = 0;
120 for ( int i = scr_len; i >= 0 ; i-- ) {
121 k[i] = std::exp(-sqr(i) / d_sq);
122 if ( i > 0 ) sum += k[i];
123 }
124 // the sum of the complete kernel is twice as large (plus the center element which we skipped above to prevent counting it twice)
125 sum = 2*sum + k[0];
127 // Normalize kernel (making sure the sum is exactly 1)
128 double ksum = 0;
129 FIRValue kernelsum = 0;
130 for ( int i = scr_len; i >= 1 ; i-- ) {
131 ksum += k[i]/sum;
132 kernel[i] = ksum-static_cast<double>(kernelsum);
133 kernelsum += kernel[i];
134 }
135 kernel[0] = FIRValue(1)-2*kernelsum;
136 }
138 // Return value (v) should satisfy:
139 // 2^(2*v)*255<2^32
140 // 255<2^(32-2*v)
141 // 2^8<=2^(32-2*v)
142 // 8<=32-2*v
143 // 2*v<=24
144 // v<=12
145 static int
146 _effect_subsample_step_log2(double const deviation, int const quality)
147 {
148 // To make sure FIR will always be used (unless the kernel is VERY big):
149 // deviation/step <= 3
150 // deviation/3 <= step
151 // log(deviation/3) <= log(step)
152 // So when x below is >= 1/3 FIR will almost always be used.
153 // This means IIR is almost only used with the modes BETTER or BEST.
154 int stepsize_l2;
155 switch (quality) {
156 case BLUR_QUALITY_WORST:
157 // 2 == log(x*8/3))
158 // 2^2 == x*2^3/3
159 // x == 3/2
160 stepsize_l2 = clip(static_cast<int>(log(deviation*(3./2.))/log(2.)), 0, 12);
161 break;
162 case BLUR_QUALITY_WORSE:
163 // 2 == log(x*16/3))
164 // 2^2 == x*2^4/3
165 // x == 3/2^2
166 stepsize_l2 = clip(static_cast<int>(log(deviation*(3./4.))/log(2.)), 0, 12);
167 break;
168 case BLUR_QUALITY_BETTER:
169 // 2 == log(x*32/3))
170 // 2 == x*2^5/3
171 // x == 3/2^4
172 stepsize_l2 = clip(static_cast<int>(log(deviation*(3./16.))/log(2.)), 0, 12);
173 break;
174 case BLUR_QUALITY_BEST:
175 stepsize_l2 = 0; // no subsampling at all
176 break;
177 case BLUR_QUALITY_NORMAL:
178 default:
179 // 2 == log(x*16/3))
180 // 2 == x*2^4/3
181 // x == 3/2^3
182 stepsize_l2 = clip(static_cast<int>(log(deviation*(3./8.))/log(2.)), 0, 12);
183 break;
184 }
185 return stepsize_l2;
186 }
188 /**
189 * Sanity check function for indexing pixblocks.
190 * Catches reading and writing outside the pixblock area.
191 * When enabled, decreases filter rendering speed massively.
192 */
193 static inline void
194 _check_index(NRPixBlock const * const pb, int const location, int const line)
195 {
196 if (false) {
197 int max_loc = pb->rs * (pb->area.y1 - pb->area.y0);
198 if (location < 0 || location >= max_loc)
199 g_warning("Location %d out of bounds (0 ... %d) at line %d", location, max_loc, line);
200 }
201 }
203 static void calcFilter(double const sigma, double b[N]) {
204 assert(N==3);
205 std::complex<double> const d1_org(1.40098, 1.00236);
206 double const d3_org = 1.85132;
207 double qbeg = 1; // Don't go lower than sigma==2 (we'd probably want a normal convolution in that case anyway)
208 double qend = 2*sigma;
209 double const sigmasqr = sqr(sigma);
210 double s;
211 do { // Binary search for right q (a linear interpolation scheme is suggested, but this should work fine as well)
212 double const q = (qbeg+qend)/2;
213 // Compute scaled filter coefficients
214 std::complex<double> const d1 = pow(d1_org, 1.0/q);
215 double const d3 = pow(d3_org, 1.0/q);
216 double const absd1sqr = std::norm(d1);
217 double const re2d1 = 2*d1.real();
218 double const bscale = 1.0/(absd1sqr*d3);
219 b[2] = -bscale;
220 b[1] = bscale*(d3+re2d1);
221 b[0] = -bscale*(absd1sqr+d3*re2d1);
222 // Compute actual sigma^2
223 double const ssqr = 2*(2*(d1/sqr(d1-1.)).real()+d3/sqr(d3-1.));
224 if ( ssqr < sigmasqr ) {
225 qbeg = q;
226 } else {
227 qend = q;
228 }
229 s = sqrt(ssqr);
230 } while(qend-qbeg>(sigma/(1<<30)));
231 }
233 static void calcTriggsSdikaM(double const b[N], double M[N*N]) {
234 assert(N==3);
235 double a1=b[0], a2=b[1], a3=b[2];
236 double const Mscale = 1.0/((1+a1-a2+a3)*(1-a1-a2-a3)*(1+a2+(a1-a3)*a3));
237 M[0] = 1-a2-a1*a3-sqr(a3);
238 M[1] = (a1+a3)*(a2+a1*a3);
239 M[2] = a3*(a1+a2*a3);
240 M[3] = a1+a2*a3;
241 M[4] = (1-a2)*(a2+a1*a3);
242 M[5] = a3*(1-a2-a1*a3-sqr(a3));
243 M[6] = a1*(a1+a3)+a2*(1-a2);
244 M[7] = a1*(a2-sqr(a3))+a3*(1+a2*(a2-1)-sqr(a3));
245 M[8] = a3*(a1+a2*a3);
246 for(unsigned int i=0; i<9; i++) M[i] *= Mscale;
247 }
249 template<unsigned int SIZE>
250 static void calcTriggsSdikaInitialization(double const M[N*N], IIRValue const uold[N][SIZE], IIRValue const uplus[SIZE], IIRValue const vplus[SIZE], IIRValue const alpha, IIRValue vold[N][SIZE]) {
251 for(unsigned int c=0; c<SIZE; c++) {
252 double uminp[N];
253 for(unsigned int i=0; i<N; i++) uminp[i] = uold[i][c] - uplus[c];
254 for(unsigned int i=0; i<N; i++) {
255 double voldf = 0;
256 for(unsigned int j=0; j<N; j++) {
257 voldf += uminp[j]*M[i*N+j];
258 }
259 // Properly takes care of the scaling coefficient alpha and vplus (which is already appropriately scaled)
260 // This was arrived at by starting from a version of the blur filter that ignored the scaling coefficient
261 // (and scaled the final output by alpha^2) and then gradually reintroducing the scaling coefficient.
262 vold[i][c] = voldf*alpha;
263 vold[i][c] += vplus[c];
264 }
265 }
266 }
268 // Filters over 1st dimension
269 template<typename PT, unsigned int PC, bool PREMULTIPLIED_ALPHA>
270 static void
271 filter2D_IIR(PT *const dest, int const dstr1, int const dstr2,
272 PT const *const src, int const sstr1, int const sstr2,
273 int const n1, int const n2, IIRValue const b[N+1], double const M[N*N],
274 IIRValue *const tmpdata[], int const num_threads)
275 {
276 #if HAVE_OPENMP
277 #pragma omp parallel for num_threads(num_threads)
278 #endif // HAVE_OPENMP
279 for ( int c2 = 0 ; c2 < n2 ; c2++ ) {
280 #if HAVE_OPENMP
281 unsigned int tid = omp_get_thread_num();
282 #else
283 unsigned int tid = 0;
284 #endif // HAVE_OPENMP
285 // corresponding line in the source and output buffer
286 PT const * srcimg = src + c2*sstr2;
287 PT * dstimg = dest + c2*dstr2 + n1*dstr1;
288 // Border constants
289 IIRValue imin[PC]; copy_n(srcimg + (0)*sstr1, PC, imin);
290 IIRValue iplus[PC]; copy_n(srcimg + (n1-1)*sstr1, PC, iplus);
291 // Forward pass
292 IIRValue u[N+1][PC];
293 for(unsigned int i=0; i<N; i++) copy_n(imin, PC, u[i]);
294 for ( int c1 = 0 ; c1 < n1 ; c1++ ) {
295 for(unsigned int i=N; i>0; i--) copy_n(u[i-1], PC, u[i]);
296 copy_n(srcimg, PC, u[0]);
297 srcimg += sstr1;
298 for(unsigned int c=0; c<PC; c++) u[0][c] *= b[0];
299 for(unsigned int i=1; i<N+1; i++) {
300 for(unsigned int c=0; c<PC; c++) u[0][c] += u[i][c]*b[i];
301 }
302 copy_n(u[0], PC, tmpdata[tid]+c1*PC);
303 }
304 // Backward pass
305 IIRValue v[N+1][PC];
306 calcTriggsSdikaInitialization<PC>(M, u, iplus, iplus, b[0], v);
307 dstimg -= dstr1;
308 if ( PREMULTIPLIED_ALPHA ) {
309 dstimg[PC-1] = clip_round_cast<PT>(v[0][PC-1]);
310 for(unsigned int c=0; c<PC-1; c++) dstimg[c] = clip_round_cast<PT>(v[0][c], std::numeric_limits<PT>::min(), dstimg[PC-1]);
311 } else {
312 for(unsigned int c=0; c<PC; c++) dstimg[c] = clip_round_cast<PT>(v[0][c]);
313 }
314 int c1=n1-1;
315 while(c1-->0) {
316 for(unsigned int i=N; i>0; i--) copy_n(v[i-1], PC, v[i]);
317 copy_n(tmpdata[tid]+c1*PC, PC, v[0]);
318 for(unsigned int c=0; c<PC; c++) v[0][c] *= b[0];
319 for(unsigned int i=1; i<N+1; i++) {
320 for(unsigned int c=0; c<PC; c++) v[0][c] += v[i][c]*b[i];
321 }
322 dstimg -= dstr1;
323 if ( PREMULTIPLIED_ALPHA ) {
324 dstimg[PC-1] = clip_round_cast<PT>(v[0][PC-1]);
325 for(unsigned int c=0; c<PC-1; c++) dstimg[c] = clip_round_cast<PT>(v[0][c], std::numeric_limits<PT>::min(), dstimg[PC-1]);
326 } else {
327 for(unsigned int c=0; c<PC; c++) dstimg[c] = clip_round_cast<PT>(v[0][c]);
328 }
329 }
330 }
331 }
333 // Filters over 1st dimension
334 // Assumes kernel is symmetric
335 // scr_len should be size of kernel - 1
336 template<typename PT, unsigned int PC>
337 static void
338 filter2D_FIR(PT *const dst, int const dstr1, int const dstr2,
339 PT const *const src, int const sstr1, int const sstr2,
340 int const n1, int const n2, FIRValue const *const kernel, int const scr_len, int const num_threads)
341 {
342 // Past pixels seen (to enable in-place operation)
343 PT history[scr_len+1][PC];
345 #if HAVE_OPENMP
346 #pragma omp parallel for num_threads(num_threads) private(history)
347 #endif // HAVE_OPENMP
348 for ( int c2 = 0 ; c2 < n2 ; c2++ ) {
350 // corresponding line in the source buffer
351 int const src_line = c2 * sstr2;
353 // current line in the output buffer
354 int const dst_line = c2 * dstr2;
356 int skipbuf[4] = {INT_MIN, INT_MIN, INT_MIN, INT_MIN};
358 // history initialization
359 PT imin[PC]; copy_n(src + src_line, PC, imin);
360 for(int i=0; i<scr_len; i++) copy_n(imin, PC, history[i]);
362 for ( int c1 = 0 ; c1 < n1 ; c1++ ) {
364 int const src_disp = src_line + c1 * sstr1;
365 int const dst_disp = dst_line + c1 * sstr1;
367 // update history
368 for(int i=scr_len; i>0; i--) copy_n(history[i-1], PC, history[i]);
369 copy_n(src + src_disp, PC, history[0]);
371 // for all bytes of the pixel
372 for ( unsigned int byte = 0 ; byte < PC ; byte++) {
374 if(skipbuf[byte] > c1) continue;
376 FIRValue sum = 0;
377 int last_in = -1;
378 int different_count = 0;
380 // go over our point's neighbours in the history
381 for ( int i = 0 ; i <= scr_len ; i++ ) {
382 // value at the pixel
383 PT in_byte = history[i][byte];
385 // is it the same as last one we saw?
386 if(in_byte != last_in) different_count++;
387 last_in = in_byte;
389 // sum pixels weighted by the kernel
390 sum += in_byte * kernel[i];
391 }
393 // go over our point's neighborhood on x axis in the in buffer
394 int nb_src_disp = src_disp + byte;
395 for ( int i = 1 ; i <= scr_len ; i++ ) {
396 // the pixel we're looking at
397 int c1_in = c1 + i;
398 if (c1_in >= n1) {
399 c1_in = n1 - 1;
400 } else {
401 nb_src_disp += sstr1;
402 }
404 // value at the pixel
405 PT in_byte = src[nb_src_disp];
407 // is it the same as last one we saw?
408 if(in_byte != last_in) different_count++;
409 last_in = in_byte;
411 // sum pixels weighted by the kernel
412 sum += in_byte * kernel[i];
413 }
415 // store the result in bufx
416 dst[dst_disp + byte] = round_cast<PT>(sum);
418 // optimization: if there was no variation within this point's neighborhood,
419 // skip ahead while we keep seeing the same last_in byte:
420 // blurring flat color would not change it anyway
421 if (different_count <= 1) {
422 int pos = c1 + 1;
423 int nb_src_disp = src_disp + (1+scr_len)*sstr1 + byte; // src_line + (pos+scr_len) * sstr1 + byte
424 int nb_dst_disp = dst_disp + (1) *dstr1 + byte; // dst_line + (pos) * sstr1 + byte
425 while(pos + scr_len < n1 && src[nb_src_disp] == last_in) {
426 dst[nb_dst_disp] = last_in;
427 pos++;
428 nb_src_disp += sstr1;
429 nb_dst_disp += sstr1;
430 }
431 skipbuf[byte] = pos;
432 }
433 }
434 }
435 }
436 }
438 template<typename PT, unsigned int PC>
439 static void
440 downsample(PT *const dst, int const dstr1, int const dstr2, int const dn1, int const dn2,
441 PT const *const src, int const sstr1, int const sstr2, int const sn1, int const sn2,
442 int const step1_l2, int const step2_l2)
443 {
444 unsigned int const divisor_l2 = step1_l2+step2_l2; // step1*step2=2^(step1_l2+step2_l2)
445 unsigned int const round_offset = (1<<divisor_l2)/2;
446 int const step1 = 1<<step1_l2;
447 int const step2 = 1<<step2_l2;
448 int const step1_2 = step1/2;
449 int const step2_2 = step2/2;
450 for(int dc2 = 0 ; dc2 < dn2 ; dc2++) {
451 int const sc2_begin = (dc2<<step2_l2)-step2_2;
452 int const sc2_end = sc2_begin+step2;
453 for(int dc1 = 0 ; dc1 < dn1 ; dc1++) {
454 int const sc1_begin = (dc1<<step1_l2)-step1_2;
455 int const sc1_end = sc1_begin+step1;
456 unsigned int sum[PC];
457 std::fill_n(sum, PC, 0);
458 for(int sc2 = sc2_begin ; sc2 < sc2_end ; sc2++) {
459 for(int sc1 = sc1_begin ; sc1 < sc1_end ; sc1++) {
460 for(unsigned int ch = 0 ; ch < PC ; ch++) {
461 sum[ch] += src[clip(sc2,0,sn2-1)*sstr2+clip(sc1,0,sn1-1)*sstr1+ch];
462 }
463 }
464 }
465 for(unsigned int ch = 0 ; ch < PC ; ch++) {
466 dst[dc2*dstr2+dc1*dstr1+ch] = static_cast<PT>((sum[ch]+round_offset)>>divisor_l2);
467 }
468 }
469 }
470 }
472 template<typename PT, unsigned int PC>
473 static void
474 upsample(PT *const dst, int const dstr1, int const dstr2, unsigned int const dn1, unsigned int const dn2,
475 PT const *const src, int const sstr1, int const sstr2, unsigned int const sn1, unsigned int const sn2,
476 unsigned int const step1_l2, unsigned int const step2_l2)
477 {
478 assert(((sn1-1)<<step1_l2)>=dn1 && ((sn2-1)<<step2_l2)>=dn2); // The last pixel of the source image should fall outside the destination image
479 unsigned int const divisor_l2 = step1_l2+step2_l2; // step1*step2=2^(step1_l2+step2_l2)
480 unsigned int const round_offset = (1<<divisor_l2)/2;
481 unsigned int const step1 = 1<<step1_l2;
482 unsigned int const step2 = 1<<step2_l2;
483 for ( unsigned int sc2 = 0 ; sc2 < sn2-1 ; sc2++ ) {
484 unsigned int const dc2_begin = (sc2 << step2_l2);
485 unsigned int const dc2_end = std::min(dn2, dc2_begin+step2);
486 for ( unsigned int sc1 = 0 ; sc1 < sn1-1 ; sc1++ ) {
487 unsigned int const dc1_begin = (sc1 << step1_l2);
488 unsigned int const dc1_end = std::min(dn1, dc1_begin+step1);
489 for ( unsigned int byte = 0 ; byte < PC ; byte++) {
491 // get 4 values at the corners of the pixel from src
492 PT a00 = src[sstr2* sc2 + sstr1* sc1 + byte];
493 PT a10 = src[sstr2* sc2 + sstr1*(sc1+1) + byte];
494 PT a01 = src[sstr2*(sc2+1) + sstr1* sc1 + byte];
495 PT a11 = src[sstr2*(sc2+1) + sstr1*(sc1+1) + byte];
497 // initialize values for linear interpolation
498 unsigned int a0 = a00*step2/*+a01*0*/;
499 unsigned int a1 = a10*step2/*+a11*0*/;
501 // iterate over the rectangle to be interpolated
502 for ( unsigned int dc2 = dc2_begin ; dc2 < dc2_end ; dc2++ ) {
504 // prepare linear interpolation for this row
505 unsigned int a = a0*step1/*+a1*0*/+round_offset;
507 for ( unsigned int dc1 = dc1_begin ; dc1 < dc1_end ; dc1++ ) {
509 // simple linear interpolation
510 dst[dstr2*dc2 + dstr1*dc1 + byte] = static_cast<PT>(a>>divisor_l2);
512 // compute a = a0*(ix-1)+a1*(xi+1)+round_offset
513 a = a - a0 + a1;
514 }
516 // compute a0 = a00*(iy-1)+a01*(yi+1) and similar for a1
517 a0 = a0 - a00 + a01;
518 a1 = a1 - a10 + a11;
519 }
520 }
521 }
522 }
523 }
525 int FilterGaussian::render(FilterSlot &slot, FilterUnits const &units)
526 {
527 /* in holds the input pixblock */
528 NRPixBlock *in = slot.get(_input);
529 if (!in) {
530 g_warning("Missing source image for feGaussianBlur (in=%d)", _input);
531 return 1;
532 }
534 Matrix trans = units.get_matrix_primitiveunits2pb();
536 /* If to either direction, the standard deviation is zero or
537 * input image is not defined,
538 * a transparent black image should be returned. */
539 if (_deviation_x <= 0 || _deviation_y <= 0 || in == NULL) {
540 NRPixBlock *out = new NRPixBlock;
541 if (in == NULL) {
542 // A bit guessing here, but source graphic is likely to be of
543 // right size
544 in = slot.get(NR_FILTER_SOURCEGRAPHIC);
545 }
546 nr_pixblock_setup_fast(out, in->mode, in->area.x0, in->area.y0,
547 in->area.x1, in->area.y1, true);
548 if (out->data.px != NULL) {
549 out->empty = false;
550 slot.set(_output, out);
551 }
552 return 0;
553 }
555 // Some common constants
556 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
557 int const width_org = in->area.x1-in->area.x0, height_org = in->area.y1-in->area.y0;
558 double const deviation_x_org = _deviation_x * NR::expansionX(trans);
559 double const deviation_y_org = _deviation_y * NR::expansionY(trans);
560 int const PC = NR_PIXBLOCK_BPP(in);
561 #if HAVE_OPENMP
562 int const NTHREADS = std::max(1,std::min(8,prefs->getInt("/options/threading/numthreads",omp_get_num_procs())));
563 #else
564 int const NTHREADS = 1;
565 #endif // HAVE_OPENMP
567 // Subsampling constants
568 int const quality = prefs->getInt("/options/blurquality/value");
569 int const x_step_l2 = _effect_subsample_step_log2(deviation_x_org, quality);
570 int const y_step_l2 = _effect_subsample_step_log2(deviation_y_org, quality);
571 int const x_step = 1<<x_step_l2;
572 int const y_step = 1<<y_step_l2;
573 bool const resampling = x_step > 1 || y_step > 1;
574 int const width = resampling ? static_cast<int>(ceil(static_cast<double>(width_org)/x_step))+1 : width_org;
575 int const height = resampling ? static_cast<int>(ceil(static_cast<double>(height_org)/y_step))+1 : height_org;
576 double const deviation_x = deviation_x_org / x_step;
577 double const deviation_y = deviation_y_org / y_step;
578 int const scr_len_x = _effect_area_scr(deviation_x);
579 int const scr_len_y = _effect_area_scr(deviation_y);
581 // Decide which filter to use for X and Y
582 // This threshold was determined by trial-and-error for one specific machine,
583 // so there's a good chance that it's not optimal.
584 // Whatever you do, don't go below 1 (and preferrably not even below 2), as
585 // the IIR filter gets unstable there.
586 bool const use_IIR_x = deviation_x > 3;
587 bool const use_IIR_y = deviation_y > 3;
589 // new buffer for the subsampled output
590 NRPixBlock *out = new NRPixBlock;
591 nr_pixblock_setup_fast(out, in->mode, in->area.x0/x_step, in->area.y0/y_step,
592 in->area.x0/x_step+width, in->area.y0/y_step+height, true);
593 if (out->size != NR_PIXBLOCK_SIZE_TINY && out->data.px == NULL) {
594 // alas, we've accomplished a lot, but ran out of memory - so abort
595 return 0;
596 }
597 // Temporary storage for IIR filter
598 // NOTE: This can be eliminated, but it reduces the precision a bit
599 IIRValue * tmpdata[NTHREADS];
600 std::fill_n(tmpdata, NTHREADS, (IIRValue*)0);
601 if ( use_IIR_x || use_IIR_y ) {
602 for(int i=0; i<NTHREADS; i++) {
603 tmpdata[i] = new IIRValue[std::max(width,height)*PC];
604 if (tmpdata[i] == NULL) {
605 nr_pixblock_release(out);
606 while(i-->0) {
607 delete[] tmpdata[i];
608 }
609 delete out;
610 return 0;
611 }
612 }
613 }
614 NRPixBlock *ssin = in;
615 if ( resampling ) {
616 ssin = out;
617 // Downsample
618 switch(in->mode) {
619 case NR_PIXBLOCK_MODE_A8: ///< Grayscale
620 downsample<unsigned char,1>(NR_PIXBLOCK_PX(out), 1, out->rs, width, height, NR_PIXBLOCK_PX(in), 1, in->rs, width_org, height_org, x_step_l2, y_step_l2);
621 break;
622 case NR_PIXBLOCK_MODE_R8G8B8: ///< 8 bit RGB
623 downsample<unsigned char,3>(NR_PIXBLOCK_PX(out), 3, out->rs, width, height, NR_PIXBLOCK_PX(in), 3, in->rs, width_org, height_org, x_step_l2, y_step_l2);
624 break;
625 case NR_PIXBLOCK_MODE_R8G8B8A8N: ///< Normal 8 bit RGBA
626 downsample<unsigned char,4>(NR_PIXBLOCK_PX(out), 4, out->rs, width, height, NR_PIXBLOCK_PX(in), 4, in->rs, width_org, height_org, x_step_l2, y_step_l2);
627 break;
628 case NR_PIXBLOCK_MODE_R8G8B8A8P: ///< Premultiplied 8 bit RGBA
629 downsample<unsigned char,4>(NR_PIXBLOCK_PX(out), 4, out->rs, width, height, NR_PIXBLOCK_PX(in), 4, in->rs, width_org, height_org, x_step_l2, y_step_l2);
630 break;
631 default:
632 assert(false);
633 };
634 }
636 if (use_IIR_x) {
637 // Filter variables
638 IIRValue b[N+1]; // scaling coefficient + filter coefficients (can be 10.21 fixed point)
639 double bf[N]; // computed filter coefficients
640 double M[N*N]; // matrix used for initialization procedure (has to be double)
642 // Compute filter (x)
643 calcFilter(deviation_x, bf);
644 for(size_t i=0; i<N; i++) bf[i] = -bf[i];
645 b[0] = 1; // b[0] == alpha (scaling coefficient)
646 for(size_t i=0; i<N; i++) {
647 b[i+1] = bf[i];
648 b[0] -= b[i+1];
649 }
651 // Compute initialization matrix (x)
652 calcTriggsSdikaM(bf, M);
654 // Filter (x)
655 switch(in->mode) {
656 case NR_PIXBLOCK_MODE_A8: ///< Grayscale
657 filter2D_IIR<unsigned char,1,false>(NR_PIXBLOCK_PX(out), 1, out->rs, NR_PIXBLOCK_PX(ssin), 1, ssin->rs, width, height, b, M, tmpdata, NTHREADS);
658 break;
659 case NR_PIXBLOCK_MODE_R8G8B8: ///< 8 bit RGB
660 filter2D_IIR<unsigned char,3,false>(NR_PIXBLOCK_PX(out), 3, out->rs, NR_PIXBLOCK_PX(ssin), 3, ssin->rs, width, height, b, M, tmpdata, NTHREADS);
661 break;
662 case NR_PIXBLOCK_MODE_R8G8B8A8N: ///< Normal 8 bit RGBA
663 filter2D_IIR<unsigned char,4,false>(NR_PIXBLOCK_PX(out), 4, out->rs, NR_PIXBLOCK_PX(ssin), 4, ssin->rs, width, height, b, M, tmpdata, NTHREADS);
664 break;
665 case NR_PIXBLOCK_MODE_R8G8B8A8P: ///< Premultiplied 8 bit RGBA
666 filter2D_IIR<unsigned char,4,true >(NR_PIXBLOCK_PX(out), 4, out->rs, NR_PIXBLOCK_PX(ssin), 4, ssin->rs, width, height, b, M, tmpdata, NTHREADS);
667 break;
668 default:
669 assert(false);
670 };
671 } else { // !use_IIR_x
672 // Filter kernel for x direction
673 FIRValue kernel[scr_len_x];
674 _make_kernel(kernel, deviation_x);
676 // Filter (x)
677 switch(in->mode) {
678 case NR_PIXBLOCK_MODE_A8: ///< Grayscale
679 filter2D_FIR<unsigned char,1>(NR_PIXBLOCK_PX(out), 1, out->rs, NR_PIXBLOCK_PX(ssin), 1, ssin->rs, width, height, kernel, scr_len_x, NTHREADS);
680 break;
681 case NR_PIXBLOCK_MODE_R8G8B8: ///< 8 bit RGB
682 filter2D_FIR<unsigned char,3>(NR_PIXBLOCK_PX(out), 3, out->rs, NR_PIXBLOCK_PX(ssin), 3, ssin->rs, width, height, kernel, scr_len_x, NTHREADS);
683 break;
684 case NR_PIXBLOCK_MODE_R8G8B8A8N: ///< Normal 8 bit RGBA
685 filter2D_FIR<unsigned char,4>(NR_PIXBLOCK_PX(out), 4, out->rs, NR_PIXBLOCK_PX(ssin), 4, ssin->rs, width, height, kernel, scr_len_x, NTHREADS);
686 break;
687 case NR_PIXBLOCK_MODE_R8G8B8A8P: ///< Premultiplied 8 bit RGBA
688 filter2D_FIR<unsigned char,4>(NR_PIXBLOCK_PX(out), 4, out->rs, NR_PIXBLOCK_PX(ssin), 4, ssin->rs, width, height, kernel, scr_len_x, NTHREADS);
689 break;
690 default:
691 assert(false);
692 };
693 }
695 if (use_IIR_y) {
696 // Filter variables
697 IIRValue b[N+1]; // scaling coefficient + filter coefficients (can be 10.21 fixed point)
698 double bf[N]; // computed filter coefficients
699 double M[N*N]; // matrix used for initialization procedure (has to be double)
701 // Compute filter (y)
702 calcFilter(deviation_y, bf);
703 for(size_t i=0; i<N; i++) bf[i] = -bf[i];
704 b[0] = 1; // b[0] == alpha (scaling coefficient)
705 for(size_t i=0; i<N; i++) {
706 b[i+1] = bf[i];
707 b[0] -= b[i+1];
708 }
710 // Compute initialization matrix (y)
711 calcTriggsSdikaM(bf, M);
713 // Filter (y)
714 switch(in->mode) {
715 case NR_PIXBLOCK_MODE_A8: ///< Grayscale
716 filter2D_IIR<unsigned char,1,false>(NR_PIXBLOCK_PX(out), out->rs, 1, NR_PIXBLOCK_PX(out), out->rs, 1, height, width, b, M, tmpdata, NTHREADS);
717 break;
718 case NR_PIXBLOCK_MODE_R8G8B8: ///< 8 bit RGB
719 filter2D_IIR<unsigned char,3,false>(NR_PIXBLOCK_PX(out), out->rs, 3, NR_PIXBLOCK_PX(out), out->rs, 3, height, width, b, M, tmpdata, NTHREADS);
720 break;
721 case NR_PIXBLOCK_MODE_R8G8B8A8N: ///< Normal 8 bit RGBA
722 filter2D_IIR<unsigned char,4,false>(NR_PIXBLOCK_PX(out), out->rs, 4, NR_PIXBLOCK_PX(out), out->rs, 4, height, width, b, M, tmpdata, NTHREADS);
723 break;
724 case NR_PIXBLOCK_MODE_R8G8B8A8P: ///< Premultiplied 8 bit RGBA
725 filter2D_IIR<unsigned char,4,true >(NR_PIXBLOCK_PX(out), out->rs, 4, NR_PIXBLOCK_PX(out), out->rs, 4, height, width, b, M, tmpdata, NTHREADS);
726 break;
727 default:
728 assert(false);
729 };
730 } else { // !use_IIR_y
731 // Filter kernel for y direction
732 FIRValue kernel[scr_len_y];
733 _make_kernel(kernel, deviation_y);
735 // Filter (y)
736 switch(in->mode) {
737 case NR_PIXBLOCK_MODE_A8: ///< Grayscale
738 filter2D_FIR<unsigned char,1>(NR_PIXBLOCK_PX(out), out->rs, 1, NR_PIXBLOCK_PX(out), out->rs, 1, height, width, kernel, scr_len_y, NTHREADS);
739 break;
740 case NR_PIXBLOCK_MODE_R8G8B8: ///< 8 bit RGB
741 filter2D_FIR<unsigned char,3>(NR_PIXBLOCK_PX(out), out->rs, 3, NR_PIXBLOCK_PX(out), out->rs, 3, height, width, kernel, scr_len_y, NTHREADS);
742 break;
743 case NR_PIXBLOCK_MODE_R8G8B8A8N: ///< Normal 8 bit RGBA
744 filter2D_FIR<unsigned char,4>(NR_PIXBLOCK_PX(out), out->rs, 4, NR_PIXBLOCK_PX(out), out->rs, 4, height, width, kernel, scr_len_y, NTHREADS);
745 break;
746 case NR_PIXBLOCK_MODE_R8G8B8A8P: ///< Premultiplied 8 bit RGBA
747 filter2D_FIR<unsigned char,4>(NR_PIXBLOCK_PX(out), out->rs, 4, NR_PIXBLOCK_PX(out), out->rs, 4, height, width, kernel, scr_len_y, NTHREADS);
748 break;
749 default:
750 assert(false);
751 };
752 }
754 for(int i=0; i<NTHREADS; i++) {
755 delete[] tmpdata[i]; // deleting a nullptr has no effect, so this is safe
756 }
758 if ( !resampling ) {
759 // No upsampling needed
760 out->empty = FALSE;
761 slot.set(_output, out);
762 } else {
763 // New buffer for the final output, same resolution as the in buffer
764 NRPixBlock *finalout = new NRPixBlock;
765 nr_pixblock_setup_fast(finalout, in->mode, in->area.x0, in->area.y0,
766 in->area.x1, in->area.y1, true);
767 if (finalout->size != NR_PIXBLOCK_SIZE_TINY && finalout->data.px == NULL) {
768 // alas, we've accomplished a lot, but ran out of memory - so abort
769 nr_pixblock_release(out);
770 delete out;
771 return 0;
772 }
774 // Upsample
775 switch(in->mode) {
776 case NR_PIXBLOCK_MODE_A8: ///< Grayscale
777 upsample<unsigned char,1>(NR_PIXBLOCK_PX(finalout), 1, finalout->rs, width_org, height_org, NR_PIXBLOCK_PX(out), 1, out->rs, width, height, x_step_l2, y_step_l2);
778 break;
779 case NR_PIXBLOCK_MODE_R8G8B8: ///< 8 bit RGB
780 upsample<unsigned char,3>(NR_PIXBLOCK_PX(finalout), 3, finalout->rs, width_org, height_org, NR_PIXBLOCK_PX(out), 3, out->rs, width, height, x_step_l2, y_step_l2);
781 break;
782 case NR_PIXBLOCK_MODE_R8G8B8A8N: ///< Normal 8 bit RGBA
783 upsample<unsigned char,4>(NR_PIXBLOCK_PX(finalout), 4, finalout->rs, width_org, height_org, NR_PIXBLOCK_PX(out), 4, out->rs, width, height, x_step_l2, y_step_l2);
784 break;
785 case NR_PIXBLOCK_MODE_R8G8B8A8P: ///< Premultiplied 8 bit RGBA
786 upsample<unsigned char,4>(NR_PIXBLOCK_PX(finalout), 4, finalout->rs, width_org, height_org, NR_PIXBLOCK_PX(out), 4, out->rs, width, height, x_step_l2, y_step_l2);
787 break;
788 default:
789 assert(false);
790 };
792 // We don't need the out buffer anymore
793 nr_pixblock_release(out);
794 delete out;
796 // The final out buffer gets returned
797 finalout->empty = FALSE;
798 slot.set(_output, finalout);
799 }
801 return 0;
802 }
804 void FilterGaussian::area_enlarge(NRRectL &area, Matrix const &trans)
805 {
806 int area_x = _effect_area_scr(_deviation_x * NR::expansionX(trans));
807 int area_y = _effect_area_scr(_deviation_y * NR::expansionY(trans));
808 // maximum is used because rotations can mix up these directions
809 // TODO: calculate a more tight-fitting rendering area
810 int area_max = std::max(area_x, area_y);
811 area.x0 -= area_max;
812 area.x1 += area_max;
813 area.y0 -= area_max;
814 area.y1 += area_max;
815 }
817 FilterTraits FilterGaussian::get_input_traits() {
818 return TRAIT_PARALLER;
819 }
821 void FilterGaussian::set_deviation(double deviation)
822 {
823 if(IS_FINITE(deviation) && deviation >= 0) {
824 _deviation_x = _deviation_y = deviation;
825 }
826 }
828 void FilterGaussian::set_deviation(double x, double y)
829 {
830 if(IS_FINITE(x) && x >= 0 && IS_FINITE(y) && y >= 0) {
831 _deviation_x = x;
832 _deviation_y = y;
833 }
834 }
836 } /* namespace NR */
838 /*
839 Local Variables:
840 mode:c++
841 c-file-style:"stroustrup"
842 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
843 indent-tabs-mode:nil
844 fill-column:99
845 End:
846 */
847 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :