forked from darktable-org/darktable
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterpolation.c
More file actions
1616 lines (1407 loc) · 52.3 KB
/
interpolation.c
File metadata and controls
1616 lines (1407 loc) · 52.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* --------------------------------------------------------------------------
This file is part of darktable,
Copyright (C) 2012-2025 darktable developers.
darktable is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
darktable is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with darktable. If not, see <http://www.gnu.org/licenses/>.
* ------------------------------------------------------------------------*/
#include "common/interpolation.h"
#include "common/darktable.h"
#include "common/math.h"
#include "control/conf.h"
#include <assert.h>
#include <glib.h>
#include <inttypes.h>
#include <stddef.h>
#include <stdint.h>
/** Border extrapolation modes */
enum border_mode
{
BORDER_REPLICATE, // aaaa|abcdefg|gggg
BORDER_WRAP, // defg|abcdefg|abcd
BORDER_MIRROR, // edcb|abcdefg|fedc
BORDER_CLAMP // ....|abcdefg|....
};
/* Supporting them all might be overkill, let the compiler trim all
* unnecessary modes in clip for resampling codepath*/
#define RESAMPLING_BORDER_MODE BORDER_REPLICATE
/* Supporting them all might be overkill, let the compiler trim all
* unnecessary modes in interpolation codepath */
#define INTERPOLATION_BORDER_MODE BORDER_MIRROR
// Defines the maximum kernel half length
// !! Make sure to sync this with the filter array !!
#define MAX_HALF_FILTER_WIDTH 3
// Add *verbose* (like one msg per pixel out) debug message to stderr
#define DEBUG_PRINT_VERBOSE 0
/* --------------------------------------------------------------------------
* Debug helpers
* ------------------------------------------------------------------------*/
static void _show_2_times(const dt_times_t *start,
const dt_times_t *mid,
const char *prefix)
{
if(darktable.unmuted & DT_DEBUG_PERF)
{
dt_times_t end;
dt_get_times(&end);
dt_print(DT_DEBUG_PERF,
"[%s] plan %.3f secs (%.3f CPU) resample %.3f secs (%.3f CPU)",
prefix, mid->clock - start->clock, mid->user - start->user,
end.clock - mid->clock, end.user - mid->user);
}
}
/* --------------------------------------------------------------------------
* Generic helpers
* ------------------------------------------------------------------------*/
/** Clip into specified range
* @param idx index to filter
* @param length length of line
*/
static inline ssize_t _clip(ssize_t i,
const ssize_t min,
const ssize_t max,
enum border_mode mode)
{
switch(mode)
{
case BORDER_REPLICATE:
if(i < min)
{
i = min;
}
else if(i > max)
{
i = max;
}
break;
case BORDER_MIRROR:
if(i < min)
{
// i == min - 1 --> min + 1
// i == min - 2 --> min + 2, etc.
// but as min == 0 in all current cases, this really optimizes to i = -i
i = min + (min - i);
}
else if(i > max)
{
// i == max + 1 --> max - 1
// i == max + 2 --> max - 2, etc.
i = max - (i - max);
}
break;
case BORDER_WRAP:
if(i < min)
{
i = 1 + max - (min - i);
}
else if(i > max)
{
i = min + (i - max) - 1;
}
break;
case BORDER_CLAMP:
if(i < min || i > max)
{
/* Should not be used as is, we prevent -1 usage, filtering the taps
* we clip the sample indexes for. So understand this function is
* specific to its caller. */
i = -1;
}
break;
}
return i;
}
static inline void _prepare_tap_boundaries(int *tap_first,
int *tap_last,
const enum border_mode mode,
const int filterwidth,
const int t,
const int max)
{
/* Check lower bound pixel index and skip as many pixels as necessary to
* fall into range */
*tap_first = 0;
if(mode == BORDER_CLAMP && t < 0)
{
*tap_first = -t;
}
// Same for upper bound pixel
*tap_last = filterwidth;
if(mode == BORDER_CLAMP && t + filterwidth >= max)
{
*tap_last = max - t;
}
}
/* --------------------------------------------------------------------------
* Interpolation kernels
* ------------------------------------------------------------------------*/
/* --------------------------------------------------------------------------
* Bilinear interpolation
* ------------------------------------------------------------------------*/
static float _maketaps_bilinear(float *taps,
const size_t num_taps,
const float width,
const float first_tap,
const float interval)
{
static const dt_aligned_pixel_t bootstrap = { 0.0f, 1.0f, 2.0f, 3.0f };
dt_aligned_pixel_t iter;
dt_aligned_pixel_t vt;
for_four_channels(c)
iter[c] = 4.0f * interval;
for_four_channels(c)
vt[c] = first_tap + bootstrap[c] * interval;
const int runs = (num_taps + 3) / 4;
for(size_t i = 0; i < runs; i++)
{
// compute and store the values for the current four taps
for_four_channels(c)
taps[4*i + c] = 1.0f - (vt[c] < 0.0f ? -vt[c] : vt[c]);
// prepare next iteration
for_four_channels(c)
vt[c] += iter[c];
}
return 1.0f; //kernel norm is 1.0f by construction
}
/* --------------------------------------------------------------------------
* Bicubic interpolation
* ------------------------------------------------------------------------*/
static float _maketaps_bicubic(float *taps,
const size_t num_taps,
const float width,
const float first_tap,
const float interval)
{
static const dt_aligned_pixel_t bootstrap = { 0.0f, 1.0f, 2.0f, 3.0f };
static const dt_aligned_pixel_t half = { .5f, .5f, .5f, .5f };
static const dt_aligned_pixel_t two = { 2.f, 2.f, 2.f, 2.f };
static const dt_aligned_pixel_t three = { 3.f, 3.f, 3.f, 3.f };
static const dt_aligned_pixel_t four = { 4.f, 4.f, 4.f, 4.f };
static const dt_aligned_pixel_t five = { 5.f, 5.f, 5.f, 5.f };
static const dt_aligned_pixel_t eight = { 8.f, 8.f, 8.f, 8.f };
dt_aligned_pixel_t iter;
dt_aligned_pixel_t vt;
for_four_channels(c)
iter[c] = 4.0f * interval;
for_four_channels(c)
vt[c] = first_tap + bootstrap[c] * interval;
const int runs = (num_taps + 3) / 4;
for(size_t i = 0; i < runs; i++)
{
// compute and store the values for the current four taps
dt_aligned_pixel_t vt_abs;
dt_aligned_pixel_t t2; // tap-squared
for_four_channels(c)
{
vt_abs[c] = vt[c] < 0.0f ? -vt[c] : vt[c];
t2[c] = vt[c] * vt[c];
}
dt_aligned_pixel_t t5;
dt_aligned_pixel_t mt2_add_t5_sub_8;
for_four_channels(c)
{
t5[c] = five[c] * vt_abs[c];
mt2_add_t5_sub_8[c] = t5[c] - eight[c] - t2[c];
}
dt_aligned_pixel_t b;
dt_aligned_pixel_t r12;
for_four_channels(c)
{
b[c] = vt_abs[c] * mt2_add_t5_sub_8[c] + four[c];
r12[c] = b[c] * half[c]; // the value for 1 < t < 2
}
dt_aligned_pixel_t t23;
dt_aligned_pixel_t e;
dt_aligned_pixel_t r01;
for_four_channels(c)
{
t23[c] = three[c] * t2[c] - t5[c];
e[c] = t23[c] * vt_abs[c] + two[c];
r01[c] = e[c] * half[c];
}
// combine the values depending on whether abs(tap) is less than one or not
for_four_channels(c)
{
taps[4*i + c] = vt_abs[c] <= 1.0f ? r01[c] : r12[c];
}
// prepare next iteration
for_four_channels(c)
vt[c] += iter[c];
}
return 1.0f; //kernel norm is 1.0f by construction
}
/* --------------------------------------------------------------------------
* Lanczos interpolation
* ------------------------------------------------------------------------*/
#define DT_LANCZOS_EPSILON (1e-9f)
#if 0
// Reference version left here for ... documentation
static inline float
lanczos(const float width, const float t)
{
float r;
if(t<-width || t>width)
{
r = 0.f;
}
else if(t>-DT_LANCZOS_EPSILON && t<DT_LANCZOS_EPSILON)
{
r = 1.f;
}
else
{
r = width*sinf(M_PI*t)*sinf(M_PI*t/width)/(M_PI*M_PI*t*t);
}
return r;
}
#endif
/* Fast lanczos version, no calls to math.h functions, too accurate, too slow
*
* Based on a forum entry at
* http://devmaster.net/forums/topic/4648-fast-and-accurate-sinecosine/
*
* Apart the fast sine function approximation, the only trick is to compute:
* sin(pi.t) = sin(a.pi + r.pi) where t = a + r = trunc(t) + r
* = sin(a.pi).cos(r.pi) + sin(r.pi).cos(a.pi)
* = 0*cos(r.pi) + sin(r.pi).cos(a.pi)
* = sign.sin(r.pi) where sign = 1 if the a is even
* = -1 if the a is odd
*
* Of course we know that lanczos func will only be called for
* the range -width < t < width so we can additionally avoid the
* range check. */
static float _maketaps_lanczos(float *taps,
const size_t num_taps,
const float width,
const float first_tap,
const float interval)
{
static const dt_aligned_pixel_t bootstrap = { 0.0f, 1.0f, 2.0f, 3.0f };
dt_aligned_pixel_t iter;
dt_aligned_pixel_t vt;
for_four_channels(c)
iter[c] = 4.0f * interval;
for_four_channels(c)
vt[c] = first_tap + bootstrap[c] * interval;
dt_aligned_pixel_t vw;
for_four_channels(c)
vw[c] = width;
const int runs = (num_taps + 3) / 4;
for(size_t i = 0; i < runs; i++)
{
// compute and store the values for the current four taps
static const dt_aligned_pixel_t eps
= { DT_LANCZOS_EPSILON, DT_LANCZOS_EPSILON, DT_LANCZOS_EPSILON, DT_LANCZOS_EPSILON };
static const dt_aligned_pixel_t pi = { M_PI_F, M_PI_F, M_PI_F, M_PI_F };
static const dt_aligned_pixel_t pi2
= { M_PI_F*M_PI_F, M_PI_F*M_PI_F, M_PI_F*M_PI_F, M_PI_F*M_PI_F };
dt_aligned_pixel_t r;
dt_aligned_pixel_t sign;
for_four_channels(c)
{
const int a = (int)vt[c];
r[c] = vt[c] - (float)a;
sign[c] = (a & 1) ? -1.0f : 1.0f;
}
dt_aligned_pixel_t sine_arg1;
dt_aligned_pixel_t sine_arg2;
for_four_channels(c)
{
sine_arg1[c] = pi[c] * r[c];
sine_arg2[c] = pi[c] * vt[c] / vw[c];
}
dt_aligned_pixel_t sine1;
dt_aligned_pixel_t sine2;
dt_vector_sin(sine_arg1, sine1);
dt_vector_sin(sine_arg2, sine2);
dt_aligned_pixel_t num;
dt_aligned_pixel_t denom;
for_four_channels(c)
{
num[c] = (vw[c] * sign[c] * sine1[c] * sine2[c]) + eps[c];
denom[c] = (pi2[c] * vt[c] * vt[c]) + eps[c];
}
for_four_channels(c)
{
taps[4*i + c] = num[c] / denom[c];
}
// prepare next iteration
for_four_channels(c)
vt[c] += iter[c];
}
// we need to compute the norm, even though it is very close to 1.0
// and causes an increase of maxDE on the integration tests only
// from 1.1 to 1.7, because not doing so generates visible moire
// banding in smooth gradients. Unfortunately, this costs an extra
// 15-20% runtime....
float norm = 0.0f;
for(size_t i = 0; i < num_taps; i++)
norm += taps[i];
return norm;
}
#undef DT_LANCZOS_EPSILON
/* --------------------------------------------------------------------------
* All our known interpolators
* ------------------------------------------------------------------------*/
/* !!! !!! !!!
* Make sure MAX_HALF_FILTER_WIDTH is at least equal to the maximum width
* of this filter list. Otherwise bad things will happen
* !!! !!! !!!
*/
static const dt_interpolation_t dt_interpolator[] = {
{.id = DT_INTERPOLATION_BILINEAR,
.name = "bilinear",
.width = 1,
.maketaps = &_maketaps_bilinear,
},
{.id = DT_INTERPOLATION_BICUBIC,
.name = "bicubic",
.width = 2,
.maketaps = &_maketaps_bicubic,
},
{.id = DT_INTERPOLATION_LANCZOS2,
.name = "lanczos2",
.width = 2,
.maketaps = &_maketaps_lanczos,
},
{.id = DT_INTERPOLATION_LANCZOS3,
.name = "lanczos3",
.width = 3,
.maketaps = &_maketaps_lanczos,
},
};
/* --------------------------------------------------------------------------
* Kernel utility methods
* ------------------------------------------------------------------------*/
static inline float _compute_upsampling_kernel(const dt_interpolation_t *itor,
float *kernel,
int *first,
float t)
{
// find first pixel contributing to the filter's kernel. We need
// floorf() because a simple cast to int truncates toward zero,
// yielding an incorrect result for the slightly-negative positions
// that can occur at the top and left edges when doing perspective
// correction
const int f = (int)floorf(t) - itor->width + 1;
if(first)
{
*first = f;
}
/* Find closest integer position and then offset that to match first
* filtered sample position */
t = t - (float)f;
// compute the taps and return the kernel norm
return itor->maketaps(kernel, 2*itor->width, itor->width, t, -1.0f);
}
/** Computes a downsampling filtering kernel (vectorized version, four taps
* per inner loop iteration)
*
* @param itor [in] Interpolator used
* @param kernelsize [out] Number of taps
* @param kernel [out] resulting taps (at least itor->width/inoout + 4 elements for no overflow)
* @param norm [out] Kernel norm
* @param first [out] index of the first sample for which the kernel is to be applied
* @param outoinratio [in] "out samples" over "in samples" ratio
* @param xout [in] Output coordinate */
static inline void _compute_downsampling_kernel(const dt_interpolation_t *itor,
int *taps,
int *first,
float *kernel,
float *norm,
const float outoinratio,
const int xout)
{
// Keep this at hand
const float w = (float)itor->width;
/* Compute the phase difference between output pixel and its
* input corresponding input pixel */
const float xin = ceil_fast(((float)xout - w) / outoinratio);
if(first)
{
*first = (int)xin;
}
// Compute first interpolator parameter
const float t = xin * outoinratio - (float)xout;
// Compute all filter taps
const int num_taps = *taps = (int)((w - t) / outoinratio);
itor->maketaps(kernel, num_taps, itor->width, t, outoinratio);
// compute the kernel norm if requested
if(norm)
{
float n = 0.0f;
for(size_t i = 0; i < num_taps; i++)
n += kernel[i];
*norm = n;
}
}
/* --------------------------------------------------------------------------
* Sample interpolation function (see usage in iop/lens.c and iop/clipping.c)
* ------------------------------------------------------------------------*/
#define MAX_KERNEL_REQ ((2 * (MAX_HALF_FILTER_WIDTH) + 3) & (~3))
float dt_interpolation_compute_sample(const dt_interpolation_t *itor,
const float *in,
const float x,
const float y,
const int width,
const int height,
const int samplestride,
const int linestride)
{
assert(itor->width < (MAX_HALF_FILTER_WIDTH + 1));
float DT_ALIGNED_ARRAY kernelh[MAX_KERNEL_REQ];
float DT_ALIGNED_ARRAY kernelv[MAX_KERNEL_REQ];
// Compute both horizontal and vertical kernels
const float normh = _compute_upsampling_kernel(itor, kernelh, NULL, x);
const float normv = _compute_upsampling_kernel(itor, kernelv, NULL, y);
int ix = (int)x;
int iy = (int)y;
/* Now 2 cases, the pixel + filter width goes outside the image
* in that case we have to use index clipping to keep all reads
* in the input image (slow path) or we are sure it won't fall
* outside and can do more simple code */
float r;
if(ix >= (itor->width - 1)
&& iy >= (itor->width - 1)
&& ix < (width - itor->width)
&& iy < (height - itor->width))
{
// Inside image boundary case
// Go to top left pixel
in = (float *)in + linestride * iy + ix * samplestride;
in = in - (itor->width - 1) * (samplestride + linestride);
// Apply the kernel
float s = 0.f;
for(int i = 0; i < 2 * itor->width; i++)
{
float h = 0.0f;
for(int j = 0; j < 2 * itor->width; j++)
{
h += kernelh[j] * in[j * samplestride];
}
s += kernelv[i] * h;
in += linestride;
}
r = s / (normh * normv);
}
else if(ix >= 0 && iy >= 0 && ix < width && iy < height)
{
// At least a valid coordinate
// Point to the upper left pixel index wise
iy -= itor->width - 1;
ix -= itor->width - 1;
static const enum border_mode bordermode = INTERPOLATION_BORDER_MODE;
assert(bordermode != BORDER_CLAMP); // XXX in clamp mode, norms would be wrong
int xtap_first;
int xtap_last;
_prepare_tap_boundaries(&xtap_first, &xtap_last,
bordermode, 2 * itor->width, ix, width);
int ytap_first;
int ytap_last;
_prepare_tap_boundaries(&ytap_first, &ytap_last,
bordermode, 2 * itor->width, iy, height);
// Apply the kernel
float s = 0.f;
for(ssize_t i = ytap_first; i < ytap_last; i++)
{
const ssize_t clip_y = _clip(iy + i, 0, height - 1, bordermode);
float h = 0.0f;
for(ssize_t j = xtap_first; j < xtap_last; j++)
{
const ssize_t clip_x = _clip(ix + j, 0, width - 1, bordermode);
const float *ipixel = in + clip_y * linestride + clip_x * samplestride;
h += kernelh[j] * ipixel[0];
}
s += kernelv[i] * h;
}
r = s / (normh * normv);
}
else
{
// invalid coordinate
r = 0.0f;
}
return fmaxf(0.0f, r); // make sure we don't push NaNs
}
/* --------------------------------------------------------------------------
* Pixel interpolation function (see usage in iop/lens.c and iop/clipping.c)
* ------------------------------------------------------------------------*/
void dt_interpolation_compute_pixel4c(const dt_interpolation_t *itor,
const float *in,
float *out,
const float x,
const float y,
const int width,
const int height,
const int linestride)
{
assert(itor->width < (MAX_HALF_FILTER_WIDTH + 1));
// Quite a bit of space for kernels
float DT_ALIGNED_ARRAY kernelh[MAX_KERNEL_REQ];
float DT_ALIGNED_ARRAY kernelv[MAX_KERNEL_REQ];
// Compute both horizontal and vertical kernels
const float normh = _compute_upsampling_kernel(itor, kernelh, NULL, x);
const float normv = _compute_upsampling_kernel(itor, kernelv, NULL, y);
// Precompute the inverse of the filter norm for later use
const float oonorm = (1.f / (normh * normv));
/* Now 2 cases, the pixel + filter width goes outside the image
* in that case we have to use index clipping to keep all reads
* in the input image (slow path) or we are sure it won't fall
* outside and can do more simple code */
int ix = (int)x;
int iy = (int)y;
if(ix >= (itor->width - 1)
&& iy >= (itor->width - 1)
&& ix < (width - itor->width)
&& iy < (height - itor->width))
{
// Inside image boundary case
// Go to top left pixel
in = (float *)in + linestride * iy + ix * 4;
in = in - (itor->width - 1) * (4 + linestride);
const size_t itor_width = 2 * itor->width;
// Apply the kernel
dt_aligned_pixel_t pixel = { 0.0f, 0.0f, 0.0f, 0.0f };
for(size_t i = 0; i < itor_width; i++)
{
dt_aligned_pixel_t h = { 0.0f, 0.0f, 0.0f, 0.0f };
for(size_t j = 0; j < itor_width; j++)
{
const float kern = kernelh[j];
dt_aligned_pixel_t inpx;
copy_pixel(inpx, in + 4*j);
for_each_channel(c)
h[c] = h[c] + kern * inpx[c];
}
for_each_channel(c)
pixel[c] += kernelv[i] * h[c];
in += linestride;
}
for_each_channel(c,aligned(out))
out[c] = fmaxf(0.0f, oonorm * pixel[c]);
}
else if(ix >= 0 && iy >= 0 && ix < width && iy < height)
{
// At least a valid coordinate
// Point to the upper left pixel index wise
iy -= itor->width - 1;
ix -= itor->width - 1;
static const enum border_mode bordermode = INTERPOLATION_BORDER_MODE;
assert(bordermode != BORDER_CLAMP); // XXX in clamp mode, norms would be wrong
int xtap_first;
int xtap_last;
_prepare_tap_boundaries(&xtap_first, &xtap_last,
bordermode, 2 * itor->width, ix, width);
int ytap_first;
int ytap_last;
_prepare_tap_boundaries(&ytap_first, &ytap_last,
bordermode, 2 * itor->width, iy, height);
// Apply the kernel
dt_aligned_pixel_t pixel = { 0.0f, 0.0f, 0.0f, 0.0f };
for(ssize_t i = ytap_first; i < ytap_last; i++)
{
const ssize_t clip_y = _clip(iy + i, 0, height - 1, bordermode);
dt_aligned_pixel_t h = { 0.0f, 0.0f, 0.0f, 0.0f };
const float *ipixel = in + clip_y * linestride;
for(ssize_t j = xtap_first; j < xtap_last; j++)
{
const ssize_t clip_x = _clip(ix + j, 0, width - 1, bordermode);
dt_aligned_pixel_t inpx;
copy_pixel(inpx, ipixel + 4 * clip_x);
const float kern = kernelh[j];
for_each_channel(c)
h[c] += kern * inpx[c];
}
for_each_channel(c)
pixel[c] += kernelv[i] * h[c];
}
for_each_channel(c,aligned(out))
out[c] = fmaxf(0.0f, oonorm * pixel[c]);
}
else
{
// data for *out has no valid *in location so just set to zero.
for_each_channel(c,aligned(out))
out[c] = 0.0f;
}
}
/* --------------------------------------------------------------------------
* Interpolation factory
* ------------------------------------------------------------------------*/
const dt_interpolation_t *dt_interpolation_new(enum dt_interpolation_type type)
{
const dt_interpolation_t *itor = NULL;
if(type == DT_INTERPOLATION_USERPREF)
{
// Find user preferred interpolation method
const char *uipref =
dt_conf_get_string_const("plugins/lighttable/export/pixel_interpolator");
for(int i = DT_INTERPOLATION_FIRST;
uipref && i < DT_INTERPOLATION_LAST;
i++)
{
if(!strcmp(uipref, dt_interpolator[i].name))
{
// Found the one
itor = &dt_interpolator[i];
break;
}
}
/* In the case the search failed (!uipref or name not found),
* prepare later search pass with default fallback */
type = DT_INTERPOLATION_DEFAULT;
}
else if(type == DT_INTERPOLATION_USERPREF_WARP)
{
// Find user preferred interpolation method
const char *uipref =
dt_conf_get_string_const("plugins/lighttable/export/pixel_interpolator_warp");
for(int i = DT_INTERPOLATION_FIRST;
uipref && i < DT_INTERPOLATION_LAST;
i++)
{
if(!strcmp(uipref, dt_interpolator[i].name))
{
// Found the one
itor = &dt_interpolator[i];
break;
}
}
/* In the case the search failed (!uipref or name not found),
* prepare later search pass with default fallback */
type = DT_INTERPOLATION_DEFAULT_WARP;
}
if(!itor)
{
// Did not find the userpref one or we've been asked for a specific one
for(int i = DT_INTERPOLATION_FIRST; i < DT_INTERPOLATION_LAST; i++)
{
if(dt_interpolator[i].id == type)
{
itor = &dt_interpolator[i];
break;
}
if(dt_interpolator[i].id == DT_INTERPOLATION_DEFAULT)
{
itor = &dt_interpolator[i];
}
}
}
return itor;
}
/* --------------------------------------------------------------------------
* Image resampling
* ------------------------------------------------------------------------*/
/** Prepares a 1D resampling plan
*
* This consists of the following information
* <ul>
* <li>A list of lengths that tell how many pixels are relevant for the
* next output</li>
* <li>A list of required filter kernels</li>
* <li>A list of sample indexes</li>
* </ul>
*
* How to apply the resampling plan:
* <ol>
* <li>Pick a length from the length array</li>
* <li>until length is reached
* <ol>
* <li>pick a kernel tap></li>
* <li>pick the relevant sample according to the picked index</li>
* <li>multiply them and accumulate</li>
* </ol>
* </li>
* <li>here goes a single output sample</li>
* </ol>
*
* This until you reach the number of output pixels
*
* @param itor interpolator used to resample
* @param in [in] Number of input samples
* @param out [in] Number of output samples
* @param plength [out] Array of lengths for each pixel filtering (number
* of taps/indexes to use). This array mus be freed with dt_free_align() when you're
* done with the plan.
* @param pkernel [out] Array of filter kernel taps
* @param pindex [out] Array of sample indexes to be used for applying each kernel tap
* arrays of information
* @param pmeta [out] Array of int triplets (length, kernel, index) telling where to
* start for an arbitrary
* out position meta[3*out]
* @return FALSE for success, TRUE for failure
*/
static gboolean _prepare_resampling_plan(const dt_interpolation_t *itor,
const int in,
const int out,
const int shift,
const float scale,
int **plength,
float **pkernel,
int **pindex,
int **pmeta)
{
// Safe return values
*plength = NULL;
*pkernel = NULL;
*pindex = NULL;
if(pmeta)
{
*pmeta = NULL;
}
if(scale == 1.f)
{
// No resampling required
return FALSE;
}
// Compute common upsampling/downsampling memory requirements
int maxtapsapixel;
if(scale > 1.f)
{
// Upscale... the easy one. The values are exact
maxtapsapixel = 2 * itor->width;
}
else
{
// Downscale... going for worst case values memory wise
maxtapsapixel = ceil_fast((float)2 * (float)itor->width / scale);
}
int nlengths = out;
const int nindex = maxtapsapixel * out;
const int nkernel = maxtapsapixel * out;
const size_t lengthreq = dt_round_size(nlengths * sizeof(int), DT_CACHELINE_BYTES);
const size_t indexreq = dt_round_size(nindex * sizeof(int), DT_CACHELINE_BYTES);
const size_t kernelreq = dt_round_size(nkernel * sizeof(float), DT_CACHELINE_BYTES);
const size_t scratchreq = dt_round_size(maxtapsapixel * sizeof(float) + 4 * sizeof(float), DT_CACHELINE_BYTES);
// NB: because sse versions compute four taps a time
const size_t metareq = dt_round_size(pmeta ? 4 * sizeof(int) * out : 0, DT_CACHELINE_BYTES);
const size_t totalreq = kernelreq + lengthreq + indexreq + scratchreq + metareq;
void *blob = dt_alloc_aligned(totalreq);
if(!blob) return TRUE;
int *lengths = (int *)blob;
blob = (char *)blob + lengthreq;
int *index = (int *)blob;
blob = (char *)blob + indexreq;
float *kernel = (float *)blob;
blob = (char *)blob + kernelreq;
float *scratchpad = scratchreq ? (float *)blob : NULL;
blob = (char *)blob + scratchreq;
int *meta = metareq ? (int *)blob : NULL;
// blob = (char *)blob + metareq;
/* setting this as a const should help the compilers trim all unnecessary
* codepaths */
const enum border_mode bordermode = RESAMPLING_BORDER_MODE;
/* Upscale and downscale differ in subtle points, getting rid of code
* duplication might have been tricky and i prefer keeping the code
* as straight as possible */
if(scale > 1.f)
{
int kidx = 0;
int iidx = 0;
int lidx = 0;
int midx = 0;
for(int x = 0; x < out; x++)
{
if(meta)
{
meta[midx++] = lidx;
meta[midx++] = kidx;
meta[midx++] = iidx;
}
// Projected position in input samples
float fx = (float)(shift + x) / scale;
// Compute the filter kernel at that position
int first;
(void)_compute_upsampling_kernel(itor, scratchpad, &first, fx);
/* Check lower and higher bound pixel index and skip as many pixels as
* necessary to fall into range */
int tap_first;
int tap_last;
_prepare_tap_boundaries(&tap_first, &tap_last, bordermode, 2 * itor->width, first, in);
// Track number of taps that will be used
lengths[lidx++] = tap_last - tap_first;
// Precompute the inverse of the norm
float norm = 0.f;
for(int tap = tap_first; tap < tap_last; tap++)
{
norm += scratchpad[tap];
}
norm = 1.f / norm;
/* Unlike single pixel or single sample code, here it's interesting to
* precompute the normalized filter kernel as this will avoid dividing
* by the norm for all processed samples/pixels
* NB: use the same loop to put in place the index list */
first += tap_first;
for(int tap = tap_first; tap < tap_last; tap++)
{
kernel[kidx++] = scratchpad[tap] * norm;
index[iidx++] = _clip(first++, 0, in - 1, bordermode);
}
}
}
else
{
int kidx = 0;
int iidx = 0;
int lidx = 0;
int midx = 0;
for(int x = 0; x < out; x++)
{
if(meta)
{
meta[midx++] = lidx;
meta[midx++] = kidx;
meta[midx++] = iidx;
}
// Compute downsampling kernel centered on output position
int taps;
int first;
_compute_downsampling_kernel(itor, &taps, &first, scratchpad, NULL, scale, shift + x);
/* Check lower and higher bound pixel index and skip as many pixels as
* necessary to fall into range */
int tap_first;
int tap_last;
_prepare_tap_boundaries(&tap_first, &tap_last, bordermode, taps, first, in);
// Track number of taps that will be used
lengths[lidx++] = tap_last - tap_first;
// Precompute the inverse of the norm
float norm = 0.f;
for(int tap = tap_first; tap < tap_last; tap++)
{
norm += scratchpad[tap];
}
norm = 1.f / norm;
/* Unlike single pixel or single sample code, here it's interesting to
* precompute the normalized filter kernel as this will avoid dividing
* by the norm for all processed samples/pixels
* NB: use the same loop to put in place the index list */
first += tap_first;
for(int tap = tap_first; tap < tap_last; tap++)
{
kernel[kidx++] = scratchpad[tap] * norm;
index[iidx++] = _clip(first++, 0, in - 1, bordermode);
}
}
}
// Validate plan wrt caller
*plength = lengths;