Code

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