-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathtiling.c
More file actions
2022 lines (1746 loc) · 80.9 KB
/
Copy pathtiling.c
File metadata and controls
2022 lines (1746 loc) · 80.9 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) 2011-2026 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 "develop/tiling.h"
#include "common/opencl.h"
#include "control/control.h"
#include "develop/blend.h"
#include "develop/pixelpipe.h"
#include <assert.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
/* parameter RESERVE for extended roi_in sizes due to inaccuracies when doing
roi_out -> roi_in estimations.
Needs to be increased if tiling fails due to insufficient buffer sizes. */
#define RESERVE 5
#ifdef HAVE_OPENCL
/* greatest common divisor */
static unsigned _gcd(unsigned a, unsigned b)
{
unsigned t;
while(b != 0)
{
t = b;
b = a % b;
a = t;
}
return MAX(a, 1);
}
/* least common multiple */
static unsigned _lcm(const unsigned a, const unsigned b)
{
return (((unsigned long)a * b) / _gcd(a, b));
}
#endif
static inline int _align_up(const int n, const int a)
{
return n + a - (n % a);
}
static inline int _align_down(const int n, const int a)
{
return n - (n % a);
}
static inline int _align_close(const int n, const int a)
{
const int off = n % a;
const int shift = (off > a/2) ? a - off : -off;
return n + shift;
}
/*
_maximum_number_tiles is the assumed maximum sane number of tiles
if during tiling this number is exceeded darktable assumes that tiling is not possible and falls back
to untiled processing - with all system memory limits taking full effect.
For huge images like stitched panos the user might choose resourcelevel="unrestricted", in that
case the allowed number of tiles is practically unlimited
*/
static inline int _maximum_number_tiles()
{
return (darktable.dtresources.level == 3) ? 0x40000000 : 10000;
}
static inline void _print_roi(const dt_iop_roi_t *roi, const char *label)
{
dt_print(DT_DEBUG_TILING | DT_DEBUG_VERBOSE," {%5d %5d ->%5d %5d (%5dx%5d) %.6f } %s",
roi->x, roi->y, roi->x + roi->width, roi->y + roi->height,
roi->width, roi->height, roi->scale, label);
}
static double _nm_fitness(double x[], void *rest[])
{
struct dt_iop_module_t *self = (struct dt_iop_module_t *)rest[0];
struct dt_dev_pixelpipe_iop_t *piece = (struct dt_dev_pixelpipe_iop_t *)rest[1];
struct dt_iop_roi_t *iroi = (struct dt_iop_roi_t *)rest[2];
struct dt_iop_roi_t *oroi = (struct dt_iop_roi_t *)rest[3];
dt_iop_roi_t oroi_test = *oroi;
oroi_test.x = x[0] * piece->iwidth;
oroi_test.y = x[1] * piece->iheight;
oroi_test.width = x[2] * piece->iwidth;
oroi_test.height = x[3] * piece->iheight;
dt_iop_roi_t iroi_probe = *iroi;
self->modify_roi_in(self, piece, &oroi_test, &iroi_probe);
double fitness = 0.0;
fitness += (double)(iroi_probe.x - iroi->x) * (iroi_probe.x - iroi->x);
fitness += (double)(iroi_probe.y - iroi->y) * (iroi_probe.y - iroi->y);
fitness += (double)(iroi_probe.width - iroi->width) * (iroi_probe.width - iroi->width);
fitness += (double)(iroi_probe.height - iroi->height) * (iroi_probe.height - iroi->height);
return fitness;
}
/* We use a Nelder-Mead simplex algorithm based on an implementation of Michael F. Hutt.
It is covered by the following copyright notice: */
/*
* Program: nmsimplex.c
* Author : Michael F. Hutt
* http://www.mikehutt.com
* 11/3/97
*
* An implementation of the Nelder-Mead simplex method.
*
* Copyright (c) 1997-2011 <Michael F. Hutt>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#define ALPHA 1.0 /* reflection coefficient */
#define BETA 0.5 /* contraction coefficient */
#define GAMMA 2.0 /* expansion coefficient */
// #define DT_TILING_DEBUG
static int _simplex(double (*objfunc)(double[], void *[]),
const double start[],
const int n,
const double EPSILON,
const double scale,
const int maxiter,
void (*constrain)(double[], int n),
void *rest[])
{
int vs; /* vertex with smallest value */
int vh; /* vertex with next smallest value */
int vg; /* vertex with largest value */
int i, j = 0, m, row;
int itr; /* track the number of iterations */
double **v; /* holds vertices of simplex */
double pn, qn; /* values used to create initial simplex */
double *f; /* value of function at each vertex */
double fr; /* value of function at reflection point */
double fe; /* value of function at expansion point */
double fc; /* value of function at contraction point */
double *vr; /* reflection - coordinates */
double *ve; /* expansion - coordinates */
double *vc; /* contraction - coordinates */
double *vm; /* centroid - coordinates */
double fsum, favg, s, cent;
/* dynamically allocate arrays */
/* allocate the rows of the arrays */
v = (double **)malloc(sizeof(double *) * (n + 1));
f = (double *)malloc(sizeof(double) * (n + 1));
vr = (double *)malloc(sizeof(double) * n);
ve = (double *)malloc(sizeof(double) * n);
vc = (double *)malloc(sizeof(double) * n);
vm = (double *)malloc(sizeof(double) * n);
/* allocate the columns of the arrays */
for(i = 0; i <= n; i++)
{
v[i] = (double *)malloc(sizeof(double) * n);
}
/* create the initial simplex */
/* assume one of the vertices is 0,0 */
pn = scale * (sqrt(n + 1) - 1 + n) / (n * sqrt(2));
qn = scale * (sqrt(n + 1) - 1) / (n * sqrt(2));
for(i = 0; i < n; i++)
{
v[0][i] = start[i];
}
for(i = 1; i <= n; i++)
{
for(j = 0; j < n; j++)
{
if(i - 1 == j)
{
v[i][j] = pn + start[j];
}
else
{
v[i][j] = qn + start[j];
}
}
}
if(constrain != NULL)
{
constrain(v[j], n);
}
/* find the initial function values */
for(j = 0; j <= n; j++)
{
f[j] = objfunc(v[j], rest);
}
#ifdef DT_TILING_DEBUG
/* print out the initial values */
printf ("Initial Values\n");
for(j = 0; j <= n; j++)
{
for(i = 0; i < n; i++)
{
printf ("%f %f\n", v[j][i], f[j]);
}
}
#endif
/* begin the main loop of the minimization */
for(itr = 1; itr <= maxiter; itr++)
{
/* find the index of the largest value */
vg = 0;
for(j = 0; j <= n; j++)
{
if(f[j] > f[vg])
{
vg = j;
}
}
/* find the index of the smallest value */
vs = 0;
for(j = 0; j <= n; j++)
{
if(f[j] < f[vs])
{
vs = j;
}
}
/* find the index of the second largest value */
vh = vs;
for(j = 0; j <= n; j++)
{
if(f[j] > f[vh] && f[j] < f[vg])
{
vh = j;
}
}
/* calculate the centroid */
for(j = 0; j <= n - 1; j++)
{
cent = 0.0;
for(m = 0; m <= n; m++)
{
if(m != vg)
{
cent += v[m][j];
}
}
vm[j] = cent / n;
}
/* reflect vg to new vertex vr */
for(j = 0; j <= n - 1; j++)
{
/*vr[j] = (1+ALPHA)*vm[j] - ALPHA*v[vg][j]; */
vr[j] = vm[j] + ALPHA * (vm[j] - v[vg][j]);
}
if(constrain != NULL)
{
constrain(vr, n);
}
fr = objfunc(vr, rest);
if(fr < f[vh] && fr >= f[vs])
{
for(j = 0; j <= n - 1; j++)
{
v[vg][j] = vr[j];
}
f[vg] = fr;
}
/* investigate a step further in this direction */
if(fr < f[vs])
{
for(j = 0; j <= n - 1; j++)
{
/*ve[j] = GAMMA*vr[j] + (1-GAMMA)*vm[j]; */
ve[j] = vm[j] + GAMMA * (vr[j] - vm[j]);
}
if(constrain != NULL)
{
constrain(ve, n);
}
fe = objfunc(ve, rest);
/* by making fe < fr as opposed to fe < f[vs],
Rosenbrocks function takes 63 iterations as opposed
to 64 when using double variables. */
if(fe < fr)
{
for(j = 0; j <= n - 1; j++)
{
v[vg][j] = ve[j];
}
f[vg] = fe;
}
else
{
for(j = 0; j <= n - 1; j++)
{
v[vg][j] = vr[j];
}
f[vg] = fr;
}
}
/* check to see if a contraction is necessary */
if(fr >= f[vh])
{
if(fr < f[vg] && fr >= f[vh])
{
/* perform outside contraction */
for(j = 0; j <= n - 1; j++)
{
/*vc[j] = BETA*v[vg][j] + (1-BETA)*vm[j]; */
vc[j] = vm[j] + BETA * (vr[j] - vm[j]);
}
if(constrain != NULL)
{
constrain(vc, n);
}
fc = objfunc(vc, rest);
}
else
{
/* perform inside contraction */
for(j = 0; j <= n - 1; j++)
{
/*vc[j] = BETA*v[vg][j] + (1-BETA)*vm[j]; */
vc[j] = vm[j] - BETA * (vm[j] - v[vg][j]);
}
if(constrain != NULL)
{
constrain(vc, n);
}
fc = objfunc(vc, rest);
}
if(fc < f[vg])
{
for(j = 0; j <= n - 1; j++)
{
v[vg][j] = vc[j];
}
f[vg] = fc;
}
/* at this point the contraction is not successful,
we must halve the distance from vs to all the
vertices of the simplex and then continue.
10/31/97 - modified to account for ALL vertices.
*/
else
{
for(row = 0; row <= n; row++)
{
if(row != vs)
{
for(j = 0; j <= n - 1; j++)
{
v[row][j] = v[vs][j] + (v[row][j] - v[vs][j]) / 2.0;
}
}
}
if(constrain != NULL)
{
constrain(v[vg], n);
}
f[vg] = objfunc(v[vg], rest);
if(constrain != NULL)
{
constrain(v[vh], n);
}
f[vh] = objfunc(v[vh], rest);
}
}
#ifdef DT_TILING_DEBUG
/* print out the value at each iteration */
printf ("Iteration %d\n", itr);
for(j = 0; j <= n; j++)
{
for(i = 0; i < n; i++)
{
printf ("%f %f\n", v[j][i], f[j]);
}
}
#endif
/* test for convergence */
fsum = 0.0;
for(j = 0; j <= n; j++)
{
fsum += f[j];
}
favg = fsum / (n + 1);
s = 0.0;
for(j = 0; j <= n; j++)
{
s += pow((f[j] - favg), 2.0) / (n);
}
s = sqrt(s);
if(s < EPSILON) break;
}
/* end main loop of the minimization */
/* find the index of the smallest value */
vs = 0;
for(j = 0; j <= n; j++)
{
if(f[j] < f[vs])
{
vs = j;
}
}
#ifdef DT_TILING_DEBUG
printf ("The minimum was found at\n");
for(j = 0; j < n; j++)
{
printf ("%e\n", v[vs][j]);
start[j] = v[vs][j];
}
double min = objfunc (v[vs], rest);
printf ("Function value at minimum %f\n", min);
k++;
printf ("%d Function Evaluations\n", k);
printf ("%d Iterations through program\n", itr);
#endif
free(f);
free(vr);
free(ve);
free(vc);
free(vm);
for(i = 0; i <= n; i++)
{
free(v[i]);
}
free(v);
return itr;
}
static gboolean _nm_fit_output_to_input_roi(const dt_iop_module_t *self,
const dt_dev_pixelpipe_iop_t *piece,
const dt_iop_roi_t *iroi,
dt_iop_roi_t *oroi,
const int delta)
{
void *rest[4] = { (void *)self, (void *)piece, (void *)iroi, (void *)oroi };
double start[4] = { (float)oroi->x / piece->iwidth, (float)oroi->y / piece->iheight,
(float)oroi->width / piece->iwidth, (float)oroi->height / piece->iheight };
const double epsilon = (double)delta / MIN(piece->iwidth, piece->iheight);
const int maxiter = 1000;
const int iter = _simplex(_nm_fitness, start, 4, epsilon, 1.0, maxiter, NULL, rest);
dt_print(DT_DEBUG_TILING | DT_DEBUG_VERBOSE,
"[_nm_fit_output_to_input_roi] _simplex: %d, delta: %d, epsilon: %f",
iter, delta, epsilon);
oroi->x = start[0] * piece->iwidth;
oroi->y = start[1] * piece->iheight;
oroi->width = start[2] * piece->iwidth;
oroi->height = start[3] * piece->iheight;
return (iter <= maxiter);
}
/* find a matching oroi_full by probing start value of oroi and get corresponding input roi into iroi_probe.
We search in two steps. first by a simplicistic iterative search which will succeed in most cases.
If this does not converge, we do a downhill simplex (nelder-mead) fitting */
static gboolean _fit_output_to_input_roi(dt_iop_module_t *self,
dt_dev_pixelpipe_iop_t *piece,
dt_iop_roi_t *iroi,
dt_iop_roi_t *oroi,
const int delta,
int iter)
{
dt_iop_roi_t iroi_probe = *iroi;
dt_iop_roi_t save_oroi = *oroi;
// try to go the easy way. this works in many cases where output is
// just like input, only scaled down
self->modify_roi_in(self, piece, oroi, &iroi_probe);
while((abs((int)iroi_probe.x - (int)iroi->x) > delta || abs((int)iroi_probe.y - (int)iroi->y) > delta
|| abs((int)iroi_probe.width - (int)iroi->width) > delta
|| abs((int)iroi_probe.height - (int)iroi->height) > delta) && iter > 0)
{
_print_roi(&iroi_probe, "tile iroi_probe");
_print_roi(oroi, "tile oroi old");
oroi->x += (iroi->x - iroi_probe.x) * oroi->scale / iroi->scale;
oroi->y += (iroi->y - iroi_probe.y) * oroi->scale / iroi->scale;
oroi->width += (iroi->width - iroi_probe.width) * oroi->scale / iroi->scale;
oroi->height += (iroi->height - iroi_probe.height) * oroi->scale / iroi->scale;
_print_roi(oroi, "tile oroi new");
self->modify_roi_in(self, piece, oroi, &iroi_probe);
iter--;
}
if(iter > 0) return TRUE;
*oroi = save_oroi;
// simplicistic approach did not converge.
// try simplex downhill fitting now.
// it's crucial that we have a good starting point in oroi, else this
// will not converge as well.
return _nm_fit_output_to_input_roi(self, piece, iroi, oroi, delta);
}
/* simple tiling algorithm for roi_in == roi_out, i.e. for pixel to pixel modules/operations */
static void _default_process_tiling_ptp(dt_iop_module_t *self,
dt_dev_pixelpipe_iop_t *piece,
const void *const ivoid,
void *const ovoid,
const dt_iop_roi_t *const roi_in,
const dt_iop_roi_t *const roi_out,
const int in_bpp)
{
void *input = NULL;
void *output = NULL;
dt_iop_buffer_dsc_t dsc;
self->output_format(self, piece->pipe, piece, &dsc);
const int out_bpp = dt_iop_buffer_dsc_to_bpp(&dsc);
const int ipitch = roi_in->width * in_bpp;
const int opitch = roi_out->width * out_bpp;
const int max_bpp = MAX(in_bpp, out_bpp);
/* get tiling requirements of module */
dt_develop_tiling_t tiling = { 0 };
tiling.factor_cl = tiling.maxbuf_cl = -1;
self->tiling_callback(self, piece, roi_in, roi_out, &tiling);
if(tiling.factor_cl < 0) tiling.factor_cl = tiling.factor;
if(tiling.maxbuf_cl < 0) tiling.maxbuf_cl = tiling.maxbuf;
/* tiling really does not make sense in these cases. standard process() is not better or worse than we are
*/
if((tiling.factor < 2.2f)
&& (tiling.overhead < 0.2f * roi_in->width * roi_in->height * max_bpp))
{
dt_print(DT_DEBUG_PIPE | DT_DEBUG_TILING,
"[default_process_tiling_ptp] [%s] no need to use tiling for module '%s%s' "
"as no real memory saving to be expected",
dt_dev_pixelpipe_type_to_str(piece->pipe->type), self->op, dt_iop_get_instance_id(self));
goto fallback;
}
/* calculate optimal size of tiles */
float available = dt_get_available_pipe_mem(piece->pipe);
assert(available >= 500.0f * 1024.0f * 1024.0f);
/* correct for size of ivoid and ovoid which are needed on top of tiling */
available = fmaxf(available - ((float)roi_out->width * roi_out->height * out_bpp)
- ((float)roi_in->width * roi_in->height * in_bpp) - tiling.overhead,
0);
/* we ignore the above value if singlebuffer_limit (is defined and) is higher than available/tiling.factor.
this will mainly allow tiling for modules with high and "unpredictable" memory demand which is
reflected in high values of tiling.factor (take bilateral noise reduction as an example). */
float singlebuffer = dt_get_singlebuffer_mem();
const float factor = fmaxf(tiling.factor, 1.0f);
const float maxbuf = fmaxf(tiling.maxbuf, 1.0f);
singlebuffer = fmaxf(available / factor, singlebuffer);
int width = roi_in->width;
int height = roi_in->height;
/* shrink tile size in case it would exceed singlebuffer size */
if((float)width * height * max_bpp * maxbuf > singlebuffer)
{
const float scale = singlebuffer / ((float)width * height * max_bpp * maxbuf);
/* TODO: can we make this more efficient to minimize total overlap between tiles? */
if(width < height && scale >= 0.333f)
{
height = floorf(height * scale);
}
else if(height <= width && scale >= 0.333f)
{
width = floorf(width * scale);
}
else
{
width = floorf(width * sqrtf(scale));
height = floorf(height * sqrtf(scale));
}
dt_print(DT_DEBUG_TILING | DT_DEBUG_VERBOSE,
"[default_process_tiling_ptp] buffer exceeds singlebuffer, corrected to %dx%d",
width, height);
}
/* make sure we have a reasonably effective tile dimension. if not try square tiles */
if(3 * tiling.overlap > width || 3 * tiling.overlap > height)
{
width = height = floorf(sqrtf((float)width * height));
dt_print(DT_DEBUG_TILING | DT_DEBUG_VERBOSE,
"[default_process_tiling_roi] use squares because of overlap, corrected to %dx%d",
width, height);
}
/* Alignment rules: we need to make sure that alignment requirements of module are fulfilled.
Modules will report alignment requirements via align within tiling_callback().
We guarantee alignment by selecting image width/height and overlap accordingly. For a tile width/height
that is identical to image width/height no special alignment is needed. */
const unsigned int align = tiling.align;
assert(align != 0);
/* properly align tile width and height by making them smaller if needed */
if(width < roi_in->width) width = (width / align) * align;
if(height < roi_in->height) height = (height / align) * align;
/* also make sure that overlap follows alignment rules by making it wider when needed */
const int overlap = tiling.overlap % align != 0 ? (tiling.overlap / align + 1) * align
: tiling.overlap;
/* calculate effective tile size */
const int tile_wd = width - 2 * overlap > 0 ? width - 2 * overlap : 1;
const int tile_ht = height - 2 * overlap > 0 ? height - 2 * overlap : 1;
/* calculate number of tiles */
const int tiles_x = width < roi_in->width ? ceilf(roi_in->width / (float)tile_wd) : 1;
const int tiles_y = height < roi_in->height ? ceilf(roi_in->height / (float)tile_ht) : 1;
/* sanity check: don't run wild on too many tiles */
if(tiles_x * tiles_y > _maximum_number_tiles())
{
dt_print(DT_DEBUG_PIPE | DT_DEBUG_TILING,
"[default_process_tiling_ptp] [%s] gave up tiling for module '%s%s'. too many tiles: %d x %d",
dt_dev_pixelpipe_type_to_str(piece->pipe->type),
self->op, dt_iop_get_instance_id(self), tiles_x, tiles_y);
goto error;
}
/* reserve input and output buffers for tiles */
input = dt_alloc_aligned((size_t)width * height * in_bpp);
if(input == NULL)
{
dt_print(DT_DEBUG_TILING,
"[default_process_tiling_ptp] [%s] could not alloc input buffer for module '%s%s'",
dt_dev_pixelpipe_type_to_str(piece->pipe->type), self->op, dt_iop_get_instance_id(self));
goto error;
}
output = dt_alloc_aligned((size_t)width * height * out_bpp);
if(output == NULL)
{
dt_print(DT_DEBUG_TILING,
"[default_process_tiling_ptp] [%s] could not alloc output buffer for module '%s%s'",
dt_dev_pixelpipe_type_to_str(piece->pipe->type), self->op, dt_iop_get_instance_id(self));
goto error;
}
/* store processed_maximum to be re-used and aggregated */
dt_aligned_pixel_t processed_maximum_saved;
dt_aligned_pixel_t processed_maximum_new = { 1.0f };
for_four_channels(k) processed_maximum_saved[k] = piece->pipe->dsc.processed_maximum[k];
piece->pipe->tiling = TRUE;
dt_print_pipe(DT_DEBUG_PIPE | DT_DEBUG_TILING,
"default *tiled* ptp", piece->pipe, piece->module, DT_DEVICE_CPU, roi_in, roi_out,
"%dx%d tiles, size=%dx%d, overlap=%d",
tiles_x, tiles_y, tile_wd, tile_ht, overlap);
/* iterate over tiles */
for(size_t tx = 0; tx < tiles_x; tx++)
{
const size_t wd = tx * tile_wd + width > roi_in->width ? roi_in->width - tx * tile_wd : width;
for(size_t ty = 0; ty < tiles_y; ty++)
{
const size_t ht = ty * tile_ht + height > roi_in->height ? roi_in->height - ty * tile_ht : height;
/* no need to process end-tiles that are smaller than the total overlap area */
const gboolean skipped = (wd <= 2 * overlap && tx > 0) || (ht <= 2 * overlap && ty > 0);
/* origin and region of effective part of tile, which we want to store later */
size_t origin[2] = { 0, 0 };
size_t region[2] = { wd, ht };
/* roi_in and roi_out for process_cl on subbuffer */
dt_iop_roi_t iroi = { roi_in->x + tx * tile_wd, roi_in->y + ty * tile_ht, wd, ht, roi_in->scale };
dt_iop_roi_t oroi = { roi_out->x + tx * tile_wd, roi_out->y + ty * tile_ht, wd, ht, roi_out->scale };
/* offsets of tile into ivoid and ovoid */
const size_t ioffs = (ty * tile_ht) * ipitch + (tx * tile_wd) * in_bpp;
size_t ooffs = (ty * tile_ht) * opitch + (tx * tile_wd) * out_bpp;
dt_print_pipe(DT_DEBUG_TILING,
skipped ? " tile ptp skipped" : " tile ptp", piece->pipe, piece->module, DT_DEVICE_CPU, &iroi, &oroi,
"tile (%zu,%zu)", tx, ty);
if(skipped) continue;
/* prepare input tile buffer */
DT_OMP_FOR()
for(size_t j = 0; j < ht; j++)
memcpy((char *)input + j * wd * in_bpp, (char *)ivoid + ioffs + j * ipitch, (size_t)wd * in_bpp);
/* take original processed_maximum as starting point */
for(int k = 0; k < 4; k++) piece->pipe->dsc.processed_maximum[k] = processed_maximum_saved[k];
dt_dev_prepare_piece_cfa(piece, &iroi);
/* call process() of module */
self->process(self, piece, input, output, &iroi, &oroi);
/* aggregate resulting processed_maximum */
/* TODO: check if there really can be differences between tiles and take
appropriate action (calculate minimum, maximum, average, ...?) */
for(int k = 0; k < 4; k++)
{
if(tx + ty > 0 && fabs(processed_maximum_new[k] - piece->pipe->dsc.processed_maximum[k]) > 1.0e-6f)
dt_print(DT_DEBUG_TILING,
"[default_process_tiling_ptp] [%s] processed_maximum[%d] differs between tiles in module '%s%s'",
dt_dev_pixelpipe_type_to_str(piece->pipe->type), k,
self->op, dt_iop_get_instance_id(self));
processed_maximum_new[k] = piece->pipe->dsc.processed_maximum[k];
}
/* correct origin and region of tile for overlap.
make sure that we only copy back the "good" part. */
if(tx > 0)
{
origin[0] += overlap;
region[0] -= overlap;
ooffs += (size_t)overlap * out_bpp;
}
if(ty > 0)
{
origin[1] += overlap;
region[1] -= overlap;
ooffs += (size_t)overlap * opitch;
}
/* copy "good" part of tile to output buffer */
DT_OMP_FOR(shared(origin, region))
for(size_t j = 0; j < region[1]; j++)
memcpy((char *)ovoid + ooffs + j * opitch,
(char *)output + ((j + origin[1]) * wd + origin[0]) * out_bpp, (size_t)region[0] * out_bpp);
}
}
/* copy back final processed_maximum */
for(int k = 0; k < 4; k++) piece->pipe->dsc.processed_maximum[k] = processed_maximum_new[k];
dt_free_align(input);
dt_free_align(output);
piece->pipe->tiling = FALSE;
return;
error:
dt_control_log(_("tiling failed for module '%s%s'. the output most likely will be OK, but you might want to check."),
self->op, dt_iop_get_instance_id(self));
// fall through
fallback:
dt_free_align(input);
dt_free_align(output);
piece->pipe->tiling = FALSE;
dt_print(DT_DEBUG_TILING,
"[default_process_tiling_ptp] [%s] fall back to standard processing for module '%s%s'",
dt_dev_pixelpipe_type_to_str(piece->pipe->type), self->op, dt_iop_get_instance_id(self));
self->process(self, piece, ivoid, ovoid, roi_in, roi_out);
return;
}
/* more elaborate tiling algorithm for roi_in != roi_out: slower than the ptp variant,
more tiles and larger overlap */
static void _default_process_tiling_roi(dt_iop_module_t *self,
dt_dev_pixelpipe_iop_t *piece,
const void *const ivoid,
void *const ovoid,
const dt_iop_roi_t *const roi_in,
const dt_iop_roi_t *const roi_out,
const int in_bpp)
{
void *input = NULL;
void *output = NULL;
dt_iop_buffer_dsc_t dsc;
self->output_format(self, piece->pipe, piece, &dsc);
const int out_bpp = dt_iop_buffer_dsc_to_bpp(&dsc);
const int ipitch = roi_in->width * in_bpp;
const int opitch = roi_out->width * out_bpp;
const int max_bpp = MAX(in_bpp, out_bpp);
float fullscale = fmaxf(roi_in->scale / roi_out->scale, sqrtf(((float)roi_in->width * roi_in->height)
/ ((float)roi_out->width * roi_out->height)));
/* inaccuracy for roi_in elements in roi_out -> roi_in calculations */
const int delta = ceilf(fullscale);
/* estimate for additional (space) requirement in buffer dimensions due to inaccuracies */
const int inacc = RESERVE * delta;
/* get tiling requirements of module */
dt_develop_tiling_t tiling = { 0 };
tiling.factor_cl = tiling.maxbuf_cl = -1;
self->tiling_callback(self, piece, roi_in, roi_out, &tiling);
if(tiling.factor_cl < 0) tiling.factor_cl = tiling.factor;
if(tiling.maxbuf_cl < 0) tiling.maxbuf_cl = tiling.maxbuf;
/* tiling really does not make sense in these cases. standard process() is not better or worse than we are
*/
if((tiling.factor < 2.2f && tiling.overhead < 0.2f * roi_in->width * roi_in->height * max_bpp))
{
dt_print(DT_DEBUG_TILING,
"[default_process_tiling_roi] [%s] no need to use tiling for module "
"'%s%s' as no memory saving is expected",
dt_dev_pixelpipe_type_to_str(piece->pipe->type), self->op, dt_iop_get_instance_id(self));
goto fallback;
}
/* calculate optimal size of tiles */
float available = dt_get_available_pipe_mem(piece->pipe);
assert(available >= 500.0f * 1024.0f * 1024.0f);
/* correct for size of ivoid and ovoid which are needed on top of tiling */
available = fmaxf(available - ((float)roi_out->width * roi_out->height * out_bpp)
- ((float)roi_in->width * roi_in->height * in_bpp) - tiling.overhead,
0);
/* we ignore the above value if singlebuffer_limit (is defined and) is higher than available/tiling.factor.
this will mainly allow tiling for modules with high and "unpredictable" memory demand which is
reflected in high values of tiling.factor (take bilateral noise reduction as an example). */
float singlebuffer = dt_get_singlebuffer_mem();
const float factor = fmaxf(tiling.factor, 1.0f);
const float maxbuf = fmaxf(tiling.maxbuf, 1.0f);
singlebuffer = fmaxf(available / factor, singlebuffer);
int width = MAX(roi_in->width, roi_out->width);
int height = MAX(roi_in->height, roi_out->height);
/* Alignment rules: we need to make sure that alignment requirements of module are fulfilled.
Modules will report alignment requirements via align within tiling_callback(). */
const unsigned int align = tiling.align;
assert(align != 0);
/* shrink tile size in case it would exceed singlebuffer size */
if((float)width * height * max_bpp * maxbuf > singlebuffer)
{
const float scale = singlebuffer / ((float)width * height * max_bpp * maxbuf);
/* TODO: can we make this more efficient to minimize total overlap between tiles? */
if(width < height && scale >= 0.333f)
{
height = _align_down((int)floorf(height * scale), align);
}
else if(height <= width && scale >= 0.333f)
{
width = _align_down((int)floorf(width * scale), align);
}
else
{
width = _align_down((int)floorf(width * sqrtf(scale)), align);
height = _align_down((int)floorf(height * sqrtf(scale)), align);
}
dt_print(DT_DEBUG_TILING | DT_DEBUG_VERBOSE,
"[default_process_tiling_roi] [%s] buffer exceeds singlebuffer, corrected to %dx%d",
dt_dev_pixelpipe_type_to_str(piece->pipe->type), width, height);
}
/* make sure we have a reasonably effective tile dimension. if not try square tiles */
if(3 * tiling.overlap > width || 3 * tiling.overlap > height)
{
width = height = _align_down((int)floorf(sqrtf((float)width * height)), align);
dt_print(DT_DEBUG_TILING | DT_DEBUG_VERBOSE,
"[default_process_tiling_roi] [%s] use squares because of overlap, corrected to %dx%d",
dt_dev_pixelpipe_type_to_str(piece->pipe->type), width, height);
}
/* make sure that overlap follows alignment rules by making it wider when needed.
overlap_in needs to be aligned, overlap_out is only here to calculate output buffer size */
const int overlap_in = _align_up(tiling.overlap, align);
const int overlap_out = ceilf((float)overlap_in / fullscale);
int tiles_x = 1, tiles_y = 1;
/* calculate number of tiles taking the larger buffer (input or output) as a guiding one.
normally it is roi_in > roi_out; but let's be prepared */
if(roi_in->width > roi_out->width)
tiles_x = width < roi_in->width
? ceilf((float)roi_in->width / (float)MAX(width - 2 * overlap_in - inacc, 1))
: 1;
else
tiles_x = width < roi_out->width ? ceilf((float)roi_out->width / (float)MAX(width - 2 * overlap_out, 1))
: 1;
if(roi_in->height > roi_out->height)
tiles_y = height < roi_in->height
? ceilf((float)roi_in->height / (float)MAX(height - 2 * overlap_in - inacc, 1))
: 1;
else
tiles_y = height < roi_out->height
? ceilf((float)roi_out->height / (float)MAX(height - 2 * overlap_out, 1))
: 1;
/* sanity check: don't run wild on too many tiles */
if(tiles_x * tiles_y > _maximum_number_tiles())
{
dt_print(DT_DEBUG_TILING,
"[default_process_tiling_roi] [%s] gave up tiling for module '%s%s'. too many tiles: %d x %d",
dt_dev_pixelpipe_type_to_str(piece->pipe->type),
self->op, dt_iop_get_instance_id(self), tiles_x, tiles_y);
goto error;
}
/* calculate tile width and height excl. overlap (i.e. the good part) for output.
values are important for all following processing steps. */
const int tile_wd = _align_up(
roi_out->width % tiles_x == 0 ? roi_out->width / tiles_x : roi_out->width / tiles_x + 1, align);
const int tile_ht = _align_up(
roi_out->height % tiles_y == 0 ? roi_out->height / tiles_y : roi_out->height / tiles_y + 1, align);
dt_print_pipe(DT_DEBUG_PIPE | DT_DEBUG_TILING,
"process *tiled* roi", piece->pipe, piece->module, DT_DEVICE_CPU, roi_in, roi_out,
"%dx%d tiles, size=%dx%d",
tiles_x, tiles_y, tile_wd, tile_ht);
/* store processed_maximum to be re-used and aggregated */
dt_aligned_pixel_t processed_maximum_saved;
dt_aligned_pixel_t processed_maximum_new = { 1.0f };
for_four_channels(k) processed_maximum_saved[k] = piece->pipe->dsc.processed_maximum[k];
/* iterate over tiles */
for(size_t tx = 0; tx < tiles_x; tx++)
for(size_t ty = 0; ty < tiles_y; ty++)
{
piece->pipe->tiling = TRUE;
/* the output dimensions of the good part of this specific tile */
const size_t wd = (tx + 1) * tile_wd > roi_out->width ? (size_t)roi_out->width - tx * tile_wd : tile_wd;
const size_t ht = (ty + 1) * tile_ht > roi_out->height ? (size_t)roi_out->height - ty * tile_ht : tile_ht;
/* roi_in and roi_out of good part: oroi_good easy to calculate based on number and dimension of tile.
iroi_good is calculated by modify_roi_in() of respective module */
dt_iop_roi_t iroi_good = { roi_in->x + tx * tile_wd, roi_in->y + ty * tile_ht, wd, ht, roi_in->scale };
dt_iop_roi_t oroi_good = { roi_out->x + tx * tile_wd, roi_out->y + ty * tile_ht, wd, ht, roi_out->scale };