forked from darktable-org/darktable
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcolorequal.c
More file actions
3201 lines (2777 loc) · 116 KB
/
Copy pathcolorequal.c
File metadata and controls
3201 lines (2777 loc) · 116 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) 2022-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/>.
*/
/* Midi mapping is supported, here is the reference for loupedeck+
midi:D7=iop/colorequal/page;hue
midi:D#7=iop/colorequal/page
midi:E7=iop/colorequal/page;brightness
None;midi:CC1=iop/colorequal/hue/red
None;midi:CC2=iop/colorequal/hue/orange
None;midi:CC3=iop/colorequal/hue/yellow
None;midi:CC4=iop/colorequal/hue/green
None;midi:CC5=iop/colorequal/hue/cyan
None;midi:CC6=iop/colorequal/hue/blue
None;midi:CC7=iop/colorequal/hue/lavender
None;midi:CC8=iop/colorequal/hue/magenta
None;midi:CC9=iop/colorequal/saturation/red
None;midi:CC10=iop/colorequal/saturation/orange
None;midi:CC11=iop/colorequal/saturation/yellow
None;midi:CC12=iop/colorequal/saturation/green
None;midi:CC13=iop/colorequal/saturation/cyan
None;midi:CC14=iop/colorequal/saturation/blue
None;midi:CC15=iop/colorequal/saturation/lavender
None;midi:CC16=iop/colorequal/saturation/magenta
None;midi:CC17=iop/colorequal/brightness/red
None;midi:CC18=iop/colorequal/brightness/orange
None;midi:CC19=iop/colorequal/brightness/yellow
None;midi:CC20=iop/colorequal/brightness/green
None;midi:CC21=iop/colorequal/brightness/cyan
None;midi:CC22=iop/colorequal/brightness/blue
None;midi:CC23=iop/colorequal/brightness/lavender
None;midi:CC24=iop/colorequal/brightness/magenta
*/
//#include "common/extra_optimizations.h" // results in crashes on some systems
#include <assert.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include "bauhaus/bauhaus.h"
#include "common/chromatic_adaptation.h"
#include "common/darktable_ucs_22_helpers.h"
#include "common/darktable.h"
#include "common/eigf.h"
#include "common/interpolation.h"
#include "common/opencl.h"
#include "common/color_picker.h"
#include "control/conf.h"
#include "control/control.h"
#include "develop/blend.h"
#include "develop/develop.h"
#include "develop/imageop.h"
#include "develop/imageop_math.h"
#include "develop/imageop_gui.h"
#include "develop/tiling.h"
#include "dtgtk/drawingarea.h"
#include "dtgtk/expander.h"
#include "gui/accelerators.h"
#include "gui/color_picker_proxy.h"
#include "gui/draw.h"
#include "gui/gtk.h"
#include "gui/presets.h"
#include "gui/color_picker_proxy.h"
#include "iop/iop_api.h"
#include "iop/choleski.h"
#include "common/colorspaces_inline_conversions.h"
#ifdef _OPENMP
#include <omp.h>
#endif
#define NODES 8
#define SATSIZE 4096
#define SLIDER_BRIGHTNESS 0.65f // 65 %
#define SAT_EFFECT 2.0f
#define BRIGHT_EFFECT 8.0f
DT_MODULE_INTROSPECTION(4, dt_iop_colorequal_params_t)
typedef struct dt_iop_colorequal_params_t
{
float threshold; // $MIN: 0.0 $MAX: 0.3 $DEFAULT: 0.1 $DESCRIPTION: "saturation threshold"
float smoothing_hue; // $MIN: 0.05 $MAX: 2.0 $DEFAULT: 1.0 $DESCRIPTION: "hue curve"
float contrast; // $MIN: -1.0 $MAX: 1.0 $DEFAULT: 0.0 $DESCRIPTION: "contrast"
float white_level; // $MIN: -2.0 $MAX: 16.0 $DEFAULT: 1.0 $DESCRIPTION: "white level"
float chroma_size; // $MIN: 1.0 $MAX: 10.0 $DEFAULT: 1.5 $DESCRIPTION: "hue analysis radius"
float param_size; // $MIN: 1.0 $MAX: 128. $DEFAULT: 1.0 $DESCRIPTION: "effect radius"
gboolean use_filter; // $DEFAULT: TRUE $DESCRIPTION: "use guided filter"
// Note: what follows is tedious because each param needs to be declared separately.
// A more efficient way would be to use 3 arrays of 8 elements,
// but then GUI sliders would need to be wired manually to the correct array index.
// So we do it the tedious way here, and let the introspection magic connect sliders to params automatically,
// then we pack the params in arrays in commit_params().
float sat_red; // $MIN: 0. $MAX: 2. $DEFAULT: 1.0 $DESCRIPTION: "red"
float sat_orange; // $MIN: 0. $MAX: 2. $DEFAULT: 1.0 $DESCRIPTION: "orange"
float sat_yellow; // $MIN: 0. $MAX: 2. $DEFAULT: 1.0 $DESCRIPTION: "yellow"
float sat_green; // $MIN: 0. $MAX: 2. $DEFAULT: 1.0 $DESCRIPTION: "green"
float sat_cyan; // $MIN: 0. $MAX: 2. $DEFAULT: 1.0 $DESCRIPTION: "cyan"
float sat_blue; // $MIN: 0. $MAX: 2. $DEFAULT: 1.0 $DESCRIPTION: "blue"
float sat_lavender; // $MIN: 0. $MAX: 2. $DEFAULT: 1.0 $DESCRIPTION: "lavender"
float sat_magenta; // $MIN: 0. $MAX: 2. $DEFAULT: 1.0 $DESCRIPTION: "magenta"
float hue_red; // $MIN: -180. $MAX: 180. $DEFAULT: 0.0 $DESCRIPTION: "red"
float hue_orange; // $MIN: -180. $MAX: 180. $DEFAULT: 0.0 $DESCRIPTION: "orange"
float hue_yellow; // $MIN: -180. $MAX: 180. $DEFAULT: 0.0 $DESCRIPTION: "yellow"
float hue_green; // $MIN: -180. $MAX: 180. $DEFAULT: 0.0 $DESCRIPTION: "green"
float hue_cyan; // $MIN: -180. $MAX: 180. $DEFAULT: 0.0 $DESCRIPTION: "cyan"
float hue_blue; // $MIN: -180. $MAX: 180. $DEFAULT: 0.0 $DESCRIPTION: "blue"
float hue_lavender; // $MIN: -180. $MAX: 180. $DEFAULT: 0.0 $DESCRIPTION: "lavender"
float hue_magenta; // $MIN: -180. $MAX: 180. $DEFAULT: 0.0 $DESCRIPTION: "magenta"
float bright_red; // $MIN: 0. $MAX: 2. $DEFAULT: 1.0 $DESCRIPTION: "red"
float bright_orange; // $MIN: 0. $MAX: 2. $DEFAULT: 1.0 $DESCRIPTION: "orange"
float bright_yellow; // $MIN: 0. $MAX: 2. $DEFAULT: 1.0 $DESCRIPTION: "yellow"
float bright_green; // $MIN: 0. $MAX: 2. $DEFAULT: 1.0 $DESCRIPTION: "green"
float bright_cyan; // $MIN: 0. $MAX: 2. $DEFAULT: 1.0 $DESCRIPTION: "cyan"
float bright_blue; // $MIN: 0. $MAX: 2. $DEFAULT: 1.0 $DESCRIPTION: "blue"
float bright_lavender; // $MIN: 0. $MAX: 2. $DEFAULT: 1.0 $DESCRIPTION: "lavender"
float bright_magenta; // $MIN: 0. $MAX: 2. $DEFAULT: 1.0 $DESCRIPTION: "magenta"
float hue_shift; // $MIN: -23. $MAX: 23. $DEFAULT: 0.0 $DESCRIPTION: "node placement"
} dt_iop_colorequal_params_t;
typedef enum dt_iop_colorequal_channel_t
{
HUE = 0,
SATURATION = 1,
BRIGHTNESS = 2,
NUM_CHANNELS = 3,
GRAD_SWITCH = 4,
SATURATION_GRAD = SATURATION + GRAD_SWITCH,
BRIGHTNESS_GRAD = BRIGHTNESS + GRAD_SWITCH
} dt_iop_colorequal_channel_t;
typedef struct dt_iop_colorequal_data_t
{
float *LUT_saturation;
float *LUT_hue;
float *LUT_brightness;
float *gamut_LUT;
gboolean lut_inited;
float white_level;
float chroma_size;
float chroma_feathering;
float param_size;
float param_feathering;
gboolean use_filter;
dt_iop_order_iccprofile_info_t *work_profile;
float hue_shift;
float threshold;
float max_brightness;
float contrast;
} dt_iop_colorequal_data_t;
typedef struct dt_iop_colorequal_global_data_t
{
int ce_init_covariance;
int ce_finish_covariance;
int ce_prepare_prefilter;
int ce_apply_prefilter;
int ce_prepare_correlations;
int ce_finish_correlations;
int ce_final_guide;
int ce_apply_guided;
int ce_sample_input;
int ce_process_data;
int ce_write_output;
int ce_write_visual;
int ce_draw_weight;
int ce_bilinear1;
int ce_bilinear2;
int ce_bilinear4;
} dt_iop_colorequal_global_data_t;
const char *name()
{
return _("color equalizer");
}
const char *aliases()
{
return _("color zones|hsl");
}
const char **description(dt_iop_module_t *self)
{
return dt_iop_set_description
(self,
_("change saturation, hue and brightness\n"
"depending on local hue"),
_("corrective and creative"),
_("linear, RGB, scene-referred"),
_("quasi-linear, RGB"),
_("quasi-linear, RGB, scene-referred"));
}
int default_group()
{
return IOP_GROUP_COLOR;
}
int flags()
{
return IOP_FLAGS_ALLOW_TILING | IOP_FLAGS_INCLUDE_IN_STYLES | IOP_FLAGS_SUPPORTS_BLENDING;
}
dt_iop_colorspace_type_t default_colorspace(dt_iop_module_t *self,
dt_dev_pixelpipe_t *pipe,
dt_dev_pixelpipe_iop_t *piece)
{
return IOP_CS_RGB;
}
typedef struct dt_iop_colorequal_gui_data_t
{
GtkWidget *white_level;
GtkWidget *sat_red, *sat_orange, *sat_yellow, *sat_green;
GtkWidget *sat_cyan, *sat_blue, *sat_lavender, *sat_magenta;
GtkWidget *hue_red, *hue_orange, *hue_yellow, *hue_green;
GtkWidget *hue_cyan, *hue_blue, *hue_lavender, *hue_magenta;
GtkWidget *bright_red, *bright_orange, *bright_yellow, *bright_green;
GtkWidget *bright_cyan, *bright_blue, *bright_lavender, *bright_magenta;
GtkWidget *smoothing_hue, *threshold, *contrast;
GtkWidget *chroma_size, *param_size, *use_filter;
GtkWidget *hue_shift;
// Array-like re-indexing of the above for efficient uniform
// handling in loops. Populate the array in gui_init()
GtkWidget *sat_sliders[NODES];
GtkWidget *hue_sliders[NODES];
GtkWidget *bright_sliders[NODES];
int page_num;
GtkNotebook *notebook;
GtkDrawingArea *area;
GtkStack *stack;
dt_gui_collapsible_section_t cs;
float *LUT;
dt_iop_colorequal_channel_t channel;
dt_iop_order_iccprofile_info_t *work_profile;
dt_iop_order_iccprofile_info_t *white_adapted_profile;
unsigned char *b_data[NUM_CHANNELS];
cairo_surface_t *b_surface[NUM_CHANNELS];
float graph_height;
float max_saturation;
gboolean gradients_cached;
float *gamut_LUT;
int mask_mode;
gboolean dragging;
gboolean on_node;
int selected;
float points[NODES+1][2];
} dt_iop_colorequal_gui_data_t;
void init_global(dt_iop_module_so_t *self)
{
const int program = 37; // colorequal.cl, from programs.conf
dt_iop_colorequal_global_data_t *gd = malloc(sizeof(dt_iop_colorequal_global_data_t));
self->data = gd;
gd->ce_init_covariance = dt_opencl_create_kernel(program, "init_covariance");
gd->ce_finish_covariance = dt_opencl_create_kernel(program, "finish_covariance");
gd->ce_prepare_prefilter = dt_opencl_create_kernel(program, "prepare_prefilter");
gd->ce_apply_prefilter = dt_opencl_create_kernel(program, "apply_prefilter");
gd->ce_prepare_correlations = dt_opencl_create_kernel(program, "prepare_correlations");
gd->ce_finish_correlations = dt_opencl_create_kernel(program, "finish_correlations");
gd->ce_final_guide = dt_opencl_create_kernel(program, "final_guide");
gd->ce_apply_guided = dt_opencl_create_kernel(program, "apply_guided");
gd->ce_sample_input = dt_opencl_create_kernel(program, "sample_input");
gd->ce_process_data = dt_opencl_create_kernel(program, "process_data");
gd->ce_write_output = dt_opencl_create_kernel(program, "write_output");
gd->ce_write_visual = dt_opencl_create_kernel(program, "write_visual");
gd->ce_draw_weight = dt_opencl_create_kernel(program, "draw_weight");
gd->ce_bilinear1 = dt_opencl_create_kernel(program, "bilinear1");
gd->ce_bilinear2 = dt_opencl_create_kernel(program, "bilinear2");
gd->ce_bilinear4 = dt_opencl_create_kernel(program, "bilinear4");
}
void cleanup_global(dt_iop_module_so_t *self)
{
const dt_iop_colorequal_global_data_t *gd = self->data;
dt_opencl_free_kernel(gd->ce_init_covariance);
dt_opencl_free_kernel(gd->ce_finish_covariance);
dt_opencl_free_kernel(gd->ce_prepare_prefilter);
dt_opencl_free_kernel(gd->ce_apply_prefilter);
dt_opencl_free_kernel(gd->ce_prepare_correlations);
dt_opencl_free_kernel(gd->ce_finish_correlations);
dt_opencl_free_kernel(gd->ce_final_guide);
dt_opencl_free_kernel(gd->ce_apply_guided);
dt_opencl_free_kernel(gd->ce_sample_input);
dt_opencl_free_kernel(gd->ce_process_data);
dt_opencl_free_kernel(gd->ce_write_output);
dt_opencl_free_kernel(gd->ce_write_visual);
dt_opencl_free_kernel(gd->ce_draw_weight);
dt_opencl_free_kernel(gd->ce_bilinear1);
dt_opencl_free_kernel(gd->ce_bilinear2);
dt_opencl_free_kernel(gd->ce_bilinear4);
free(self->data);
self->data = NULL;
}
static inline float _get_scaling(const float sigma)
{
return MAX(1.0f, MIN(4.0f, floorf(sigma - 1.5f)));
}
void tiling_callback(dt_iop_module_t *self,
dt_dev_pixelpipe_iop_t *piece,
const dt_iop_roi_t *roi_in,
const dt_iop_roi_t *roi_out,
dt_develop_tiling_t *tiling)
{
const dt_iop_colorequal_data_t *data = piece->data;
tiling->maxbuf = 1.0f;
tiling->xalign = 1;
tiling->yalign = 1;
tiling->overhead = (2 * SATSIZE + 4 * LUT_ELEM) * sizeof(float);
const int maxradius = MAX(data->chroma_size, data->param_size);
tiling->overlap = 16 + maxradius; // safe feathering
tiling->factor = 4.5f; // in/out buffers plus mainloop incl gaussian
if(data->use_filter)
{
// calculate relative size of downsampled buffers
const float sigma = (float)maxradius * MAX(0.5f, roi_in->scale / piece->iscale);
const float scaling = _get_scaling(sigma);
tiling->factor += scaling == 1.0f
? 3.0f
: (1.0f + 4.0f / sqrf(scaling));
}
}
int legacy_params(dt_iop_module_t *self,
const void *const old_params,
const int old_version,
void **new_params,
int32_t *new_params_size,
int *new_version)
{
if(old_version == 1)
{
const dt_iop_colorequal_params_t *o = old_params;
dt_iop_colorequal_params_t *n = malloc(sizeof(dt_iop_colorequal_params_t));
memcpy(n, o, sizeof(dt_iop_colorequal_params_t) - sizeof(float));
n->hue_shift = 0.0f;
*new_params = n;
*new_params_size = sizeof(dt_iop_colorequal_params_t);
*new_version = 2;
return 0;
}
if(old_version == 2)
{
const dt_iop_colorequal_params_t *o = old_params;
dt_iop_colorequal_params_t *n = malloc(sizeof(dt_iop_colorequal_params_t));
memcpy(n, o, sizeof(dt_iop_colorequal_params_t) - sizeof(float));
n->threshold = 0.024f; // in v1/2 we had an inflection point of 0.1
// brightness and saturation slider ranges have been expanded by 4:3 so we correct here
const float *sodata = &o->sat_red;
const float *bodata = &o->bright_red;
float *sndata = &n->sat_red;
float *bndata = &n->bright_red;
for(int i = 0; i < NODES; i++)
{
sndata[i] = 1.0f + 0.75f * (sodata[i] - 1.0f);
bndata[i] = 1.0f + 0.75f * (bodata[i] - 1.0f);
}
*new_params = n;
*new_params_size = sizeof(dt_iop_colorequal_params_t);
*new_version = 3;
return 0;
}
if(old_version == 3)
{
const dt_iop_colorequal_params_t *o = old_params;
dt_iop_colorequal_params_t *n = malloc(sizeof(dt_iop_colorequal_params_t));
memcpy(n, o, sizeof(dt_iop_colorequal_params_t) - sizeof(float));
n->threshold = o->threshold + 0.1f;
n->contrast = -5.0f * MAX(0.0f, o->threshold - 0.024f); // sort of magic from what we had
*new_params = n;
*new_params_size = sizeof(dt_iop_colorequal_params_t);
*new_version = 4;
return 0;
}
return 1;
}
void _mean_gaussian(float *const buf,
const int width,
const int height,
const uint32_t ch,
const float sigma)
{
// We use unbounded signals, so don't care for the internal value clipping
const float range = 1.0e9;
const dt_aligned_pixel_t max = {range, range, range, range};
const dt_aligned_pixel_t min = {-range, -range, -range, -range};
dt_gaussian_t *g = dt_gaussian_init(width, height, ch, max, min, sigma, DT_IOP_GAUSSIAN_ZERO);
if(!g) return;
if(ch == 4)
dt_gaussian_blur_4c(g, buf, buf);
else
dt_gaussian_blur(g, buf, buf);
dt_gaussian_free(g);
}
// sRGB primary red records at 20° of hue in darktable UCS 22, so we offset the whole hue range
// such that red is the origin hues in the GUI. This is consistent with HSV/HSL color wheels UI.
#define ANGLE_SHIFT +20.f
static inline float _conventional_hue_deg_to_ucs_rad(const float angle)
{
return deg2radf(angle + ANGLE_SHIFT);
}
/* We use precalculated data for the logistic weighting function for performance and stability
and do linear interpolation at runtime. Avoids banding effects and allows a sharp transition.
*/
static float satweights[2 * SATSIZE + 1];
static float lastcontrast = NAN;
static void _init_satweights(const float contrast)
{
if(lastcontrast == contrast)
return;
lastcontrast = contrast;
const double factor = -60.0 - 40.0 * (double)contrast;
for(int i = -SATSIZE; i < SATSIZE + 1; i++)
{
const double val = 0.5 / (double)SATSIZE * (double)i;
satweights[i+SATSIZE] = (float)(1.0 / (1.0 + exp(factor * val)));
}
}
static inline float _get_satweight(const float sat)
{
const float isat = (float)SATSIZE * (1.0f + CLAMP(sat, -1.0f, 1.0f-(1.0f/SATSIZE)));
const float base = floorf(isat);
const int i = base;
return satweights[i] + (isat - base) * (satweights[i+1] - satweights[i]);
}
DT_OMP_DECLARE_SIMD(aligned(UV))
static float *const _init_covariance(const size_t pixels, const float *const restrict UV)
{
// Init the symmetric covariance matrix of the guide (4 elements by pixel) :
// covar = [[ covar(U, U), covar(U, V)],
// [ covar(V, U), covar(V, V)]]
// with covar(x, y) = avg(x * y) - avg(x) * avg(y), corr(x, y) = x * y
// so here, we init it with x * y, compute all the avg() at the next step
// and subtract avg(x) * avg(y) later
float *const restrict covariance = dt_alloc_align_float(pixels * 4);
if(!covariance)
return covariance;
DT_OMP_FOR()
for(size_t k = 0; k < pixels; k++)
{
// corr(U, U)
covariance[4 * k + 0] = UV[2 * k + 0] * UV[2 * k + 0];
// corr(U, V)
covariance[4 * k + 1] = covariance[4 * k + 2] = UV[2 * k] * UV[2 * k + 1];
// corr(V, V)
covariance[4 * k + 3] = UV[2 * k + 1] * UV[2 * k + 1];
}
return covariance;
}
DT_OMP_DECLARE_SIMD(aligned(UV, covariance: 64))
static void _finish_covariance(const size_t pixels,
const float *const restrict UV,
float *const restrict covariance)
{
// Finish the UV covariance matrix computation by subtracting avg(x) * avg(y)
// to avg(x * y) already computed
DT_OMP_FOR()
for(size_t k = 0; k < pixels; k++)
{
// covar(U, U) = var(U)
covariance[4 * k + 0] -= UV[2 * k + 0] * UV[2 * k + 0];
// covar(U, V)
covariance[4 * k + 1] -= UV[2 * k + 0] * UV[2 * k + 1];
covariance[4 * k + 2] -= UV[2 * k + 0] * UV[2 * k + 1];
// covar(V, V) = var(V)
covariance[4 * k + 3] -= UV[2 * k + 1] * UV[2 * k + 1];
}
}
DT_OMP_DECLARE_SIMD(aligned(UV, covariance, a, b: 64))
static void _prepare_prefilter(const size_t pixels,
const float *const restrict UV,
const float *const restrict covariance,
float *const restrict a,
float *const restrict b,
const float eps)
{
DT_OMP_FOR()
for(size_t k = 0; k < pixels; k++)
{
// Extract the 2×2 covariance matrix sigma = cov(U, V) at current pixel
// and add the variance threshold : sigma' = sigma + epsilon * Identity
const dt_aligned_pixel_t Sigma = {covariance[4 * k + 0] + eps,
covariance[4 * k + 1],
covariance[4 * k + 2],
covariance[4 * k + 3] + eps};
// Invert the 2×2 sigma matrix algebraically
// see https://www.mathcentre.ac.uk/resources/uploaded/sigma-matrices7-2009-1.pdf
const float det = Sigma[0] * Sigma[3] - Sigma[1] * Sigma[2];
// a(chan) = dot_product(cov(chan, uv), sigma_inv)
if(fabsf(det) > 4.f * FLT_EPSILON)
{
const dt_aligned_pixel_t sigma_inv = { Sigma[3] / det, -Sigma[1] / det,
-Sigma[2] / det, Sigma[0] / det };
// find a_1, a_2 s.t. U' = a_1 * U + a_2 * V
a[4 * k + 0] = (covariance[4 * k + 0] * sigma_inv[0]
+ covariance[4 * k + 1] * sigma_inv[1]);
a[4 * k + 1] = (covariance[4 * k + 0] * sigma_inv[2]
+ covariance[4 * k + 1] * sigma_inv[3]);
// find a_3, a_4 s.t. V' = a_3 * U + a_4 V
a[4 * k + 2] = (covariance[4 * k + 2] * sigma_inv[0]
+ covariance[4 * k + 3] * sigma_inv[1]);
a[4 * k + 3] = (covariance[4 * k + 2] * sigma_inv[2]
+ covariance[4 * k + 3] * sigma_inv[3]);
}
else
{
// determinant too close to 0: singular matrix
a[4 * k + 0] = a[4 * k + 1] = a[4 * k + 2] = a[4 * k + 3] = 0.f;
}
b[2 * k + 0] = UV[2 * k + 0] - a[4 * k + 0] * UV[2 * k + 0] - a[4 * k + 1] * UV[2 * k + 1];
b[2 * k + 1] = UV[2 * k + 1] - a[4 * k + 2] * UV[2 * k + 0] - a[4 * k + 3] * UV[2 * k + 1];
}
}
DT_OMP_DECLARE_SIMD(aligned(a, b, saturation, UV: 64))
static void _apply_prefilter(const size_t npixels,
const float sat_shift,
float *const restrict UV,
const float *const restrict saturation,
const float *const restrict a,
const float *const restrict b)
{
DT_OMP_FOR_SIMD()
for(size_t k = 0; k < npixels; k++)
{
// For each correction factor, we re-express it as a[0] * U + a[1] * V + b
const float uv[2] = { UV[2 * k + 0], UV[2 * k + 1] };
const float cv[2] = { a[4 * k + 0] * uv[0] + a[4 * k + 1] * uv[1] + b[2 * k + 0],
a[4 * k + 2] * uv[0] + a[4 * k + 3] * uv[1] + b[2 * k + 1] };
// we avoid chroma blurring into achromatic areas by interpolating
// input UV vs corrected UV
const float satweight = _get_satweight(saturation[k] - sat_shift);
UV[2 * k + 0] = interpolatef(satweight, cv[0], uv[0]);
UV[2 * k + 1] = interpolatef(satweight, cv[1], uv[1]);
}
}
static void _prefilter_chromaticity(float *const restrict UV,
const float *const restrict saturation,
const int width,
const int height,
const float sigma,
const float eps,
const float sat_shift)
{
// We guide the 3-channels corrections with the 2-channels
// chromaticity coordinates UV aka we express corrections = a * UV +
// b where a is a 2×2 matrix and b a constant Therefore the guided
// filter computation is a bit more complicated than the typical
// 1-channel case. We use by-the-book 3-channels fast guided filter
// as in http://kaiminghe.com/eccv10/ but obviously reduced to 2.
// We know that it tends to oversmooth the input where its intensity
// is close to 0, but this is actually desirable here since
// chromaticity -> 0 means neutral greys and we want to discard them
// as much as possible from any color equalization.
// possibly downsample for speed-up
const size_t pixels = (size_t)width * height;
const float scaling = _get_scaling(sigma);
const float gsigma = MAX(0.2f, sigma / scaling);
const int ds_height = height / scaling;
const int ds_width = width / scaling;
const size_t ds_pixels = (size_t)ds_width * ds_height;
const gboolean resized = width != ds_width || height != ds_height;
float *ds_UV = UV;
if(resized)
{
ds_UV = dt_alloc_align_float(ds_pixels * 2);
if(!ds_UV)
return; //out of memory, can't run the prefilter
interpolate_bilinear(UV, width, height, ds_UV, ds_width, ds_height, 2);
}
float *const restrict covariance = _init_covariance(ds_pixels, ds_UV);
if(!covariance)
{
if(ds_UV != UV) dt_free_align(ds_UV);
return;
}
// Compute the local averages of everything over the window size We
// use a gaussian blur as a weighted local average because it's a
// radial function so it will not favour vertical and horizontal
// edges over diagonal ones as the by-the-book box blur (unweighted
// local average) would.
_mean_gaussian(ds_UV, ds_width, ds_height, 2, gsigma);
_mean_gaussian(covariance, ds_width, ds_height, 4, gsigma);
_finish_covariance(ds_pixels, ds_UV, covariance);
// Compute a and b the params of the guided filters
float *const restrict ds_a = dt_alloc_align_float(4 * ds_pixels);
float *const restrict ds_b = dt_alloc_align_float(2 * ds_pixels);
if(ds_a && ds_b)
_prepare_prefilter(ds_pixels, ds_UV, covariance, ds_a, ds_b, eps);
dt_free_align(covariance);
if(ds_UV != UV) dt_free_align(ds_UV);
if(!ds_a || !ds_b)
{
dt_free_align(ds_a);
dt_free_align(ds_b);
return;
}
// Compute the averages of a and b for each filter
_mean_gaussian(ds_a, ds_width, ds_height, 4, gsigma);
_mean_gaussian(ds_b, ds_width, ds_height, 2, gsigma);
// Upsample a and b to real-size image
float *a = ds_a;
float *b = ds_b;
if(resized)
{
a = dt_alloc_align_float(pixels * 4);
b = dt_alloc_align_float(pixels * 2);
if(a && b)
{
interpolate_bilinear(ds_a, ds_width, ds_height, a, width, height, 4);
interpolate_bilinear(ds_b, ds_width, ds_height, b, width, height, 2);
dt_free_align(ds_a);
dt_free_align(ds_b);
}
else
{
dt_free_align(ds_a);
dt_free_align(ds_b);
return;
}
}
// Apply the guided filter
_apply_prefilter(pixels, sat_shift, UV, saturation, a, b);
dt_free_align(a);
dt_free_align(b);
}
static void _guide_with_chromaticity(float *const restrict UV,
float *const restrict corrections,
const float *const restrict saturation,
float *const restrict b_corrections,
const float *const restrict gradients,
const int width,
const int height,
const float sigma,
const float eps,
const float bright_shift,
const float sat_shift)
{
// We guide the 3-channels corrections with the 2-channels
// chromaticity coordinates UV aka we express corrections = a * UV +
// b where a is a 2×2 matrix and b a constant Therefore the guided
// filter computation is a bit more complicated than the typical
// 1-channel case. We use by-the-book 3-channels fast guided filter
// as in http://kaiminghe.com/eccv10/ but obviously reduced to 2.
// We know that it tends to oversmooth the input where its intensity
// is close to 0, but this is actually desirable here since
// chromaticity -> 0 means neutral greys and we want to discard them
// as much as possible from any color equalization.
// Downsample for speed-up
const size_t pixels = (size_t)width * height;
const float scaling = _get_scaling(sigma);
const float gsigma = MAX(0.2f, sigma / scaling);
const int ds_height = height / scaling;
const int ds_width = width / scaling;
const size_t ds_pixels = (size_t)ds_width * ds_height;
const gboolean resized = width != ds_width || height != ds_height;
float *ds_UV = UV;
float *ds_corrections = corrections;
float *ds_b_corrections = b_corrections;
if(resized)
{
ds_UV = dt_alloc_align_float(ds_pixels * 2);
ds_corrections = dt_alloc_align_float(ds_pixels * 2);
ds_b_corrections = dt_alloc_align_float(ds_pixels);
if(ds_UV && ds_corrections && ds_b_corrections)
{
interpolate_bilinear(UV, width, height, ds_UV, ds_width, ds_height, 2);
interpolate_bilinear(corrections, width, height, ds_corrections, ds_width, ds_height, 2);
interpolate_bilinear(b_corrections, width, height, ds_b_corrections, ds_width, ds_height, 1);
}
else
{
dt_free_align(ds_UV);
dt_free_align(ds_corrections);
dt_free_align(ds_b_corrections);
return;
}
}
float *const restrict covariance = _init_covariance(ds_pixels, ds_UV);
// Get the correlations between corrections and UV
float *const restrict correlations = dt_alloc_align_float(ds_pixels * 4);
if(!covariance || !correlations)
{
// ran out of memory, so we won't be able to apply the guided filter.
// clean up and return now
if(resized)
{
dt_free_align(ds_UV);
dt_free_align(ds_corrections);
dt_free_align(ds_b_corrections);
}
dt_free_align(covariance);
dt_free_align(correlations);
return;
}
DT_OMP_FOR_SIMD(aligned(ds_UV, ds_corrections, ds_b_corrections, correlations: 64))
for(size_t k = 0; k < ds_pixels; k++)
{
// corr(sat, U)
correlations[4 * k + 0] = ds_UV[2 * k + 0] * ds_corrections[2 * k + 1];
// corr(sat, V)
correlations[4 * k + 1] = ds_UV[2 * k + 1] * ds_corrections[2 * k + 1];
// corr(bright, U)
correlations[4 * k + 2] = ds_UV[2 * k + 0] * ds_b_corrections[k];
// corr(bright, V)
correlations[4 * k + 3] = ds_UV[2 * k + 1] * ds_b_corrections[k];
}
// Compute the local averages of everything over the window size We
// use a gaussian blur as a weighted local average because it's a
// radial function so it will not favour vertical and horizontal
// edges over diagonal ones as the by-the-book box blur (unweighted
// local average) would.
// We use unbounded signals, so don't care for the internal value clipping
_mean_gaussian(ds_UV, ds_width, ds_height, 2, gsigma);
_mean_gaussian(covariance, ds_width, ds_height, 4, gsigma);
_mean_gaussian(ds_corrections, ds_width, ds_height, 2, gsigma);
_mean_gaussian(ds_b_corrections, ds_width, ds_height, 1, 0.1f * gsigma);
_mean_gaussian(correlations, ds_width, ds_height, 4, gsigma);
_finish_covariance(ds_pixels, ds_UV, covariance);
// Finish the guide * guided correlation computation
DT_OMP_FOR_SIMD(aligned(ds_UV, ds_corrections, correlations: 64))
for(size_t k = 0; k < ds_pixels; k++)
{
correlations[4 * k + 0] -= ds_UV[2 * k + 0] * ds_corrections[2 * k + 1];
correlations[4 * k + 1] -= ds_UV[2 * k + 1] * ds_corrections[2 * k + 1];
correlations[4 * k + 2] -= ds_UV[2 * k + 0] * ds_b_corrections[k];
correlations[4 * k + 3] -= ds_UV[2 * k + 1] * ds_b_corrections[k];
}
// Compute a and b the params of the guided filters
float *const restrict ds_a = dt_alloc_align_float(4 * ds_pixels);
float *const restrict ds_b = dt_alloc_align_float(2 * ds_pixels);
if(!ds_a || !ds_b)
{
dt_free_align(ds_a);
dt_free_align(ds_b);
dt_free_align(correlations);
dt_free_align(covariance);
if(resized)
{
dt_free_align(ds_corrections);
dt_free_align(ds_b_corrections);
dt_free_align(ds_UV);
}
return;
}
DT_OMP_FOR_SIMD(aligned(ds_UV, covariance, correlations, ds_corrections, ds_b_corrections, ds_a, ds_b: 64))
for(size_t k = 0; k < ds_pixels; k++)
{
// Extract the 2×2 covariance matrix sigma = cov(U, V) at current pixel
// and add the covariance threshold : sigma' = sigma + epsilon * Identity
const dt_aligned_pixel_t Sigma
= { covariance[4 * k + 0] + eps,
covariance[4 * k + 1],
covariance[4 * k + 2],
covariance[4 * k + 3] + eps };
// Invert the 2×2 sigma matrix algebraically
// see https://www.mathcentre.ac.uk/resources/uploaded/sigma-matrices7-2009-1.pdf
const float det = Sigma[0] * Sigma[3] - Sigma[1] * Sigma[2];
// Note : epsilon prevents determinant == 0 so the invert exists all the time
if(fabsf(det) > 4.f * FLT_EPSILON)
{
const dt_aligned_pixel_t sigma_inv = { Sigma[3] / det, -Sigma[1] / det, -Sigma[2] / det, Sigma[0] / det };
ds_a[4 * k + 0] = (correlations[4 * k + 0] * sigma_inv[0] + correlations[4 * k + 1] * sigma_inv[1]);
ds_a[4 * k + 1] = (correlations[4 * k + 0] * sigma_inv[2] + correlations[4 * k + 1] * sigma_inv[3]);
ds_a[4 * k + 2] = (correlations[4 * k + 2] * sigma_inv[0] + correlations[4 * k + 3] * sigma_inv[1]);
ds_a[4 * k + 3] = (correlations[4 * k + 2] * sigma_inv[2] + correlations[4 * k + 3] * sigma_inv[3]);
}
else
{
ds_a[4 * k + 0] = ds_a[4 * k + 1] = ds_a[4 * k + 2] = ds_a[4 * k + 3] = 0.f;
}
// b = avg(chan) - dot_product(a_chan * avg(UV))
ds_b[2 * k + 0] = ds_corrections[2 * k + 1] - ds_a[4 * k + 0] * ds_UV[2 * k + 0] - ds_a[4 * k + 1] * ds_UV[2 * k + 1];
ds_b[2 * k + 1] = ds_b_corrections[k] - ds_a[4 * k + 2] * ds_UV[2 * k + 0] - ds_a[4 * k + 3] * ds_UV[2 * k + 1];
}
if(resized)
{
dt_free_align(ds_corrections);
dt_free_align(ds_b_corrections);
dt_free_align(ds_UV);
}
dt_free_align(correlations);
dt_free_align(covariance);
// Compute the averages of a and b for each filter and blur
_mean_gaussian(ds_a, ds_width, ds_height, 4, gsigma);
_mean_gaussian(ds_b, ds_width, ds_height, 2, gsigma);
// Upsample a and b to real-size image
float *a = ds_a;
float *b = ds_b;
if(resized)
{
a = dt_alloc_align_float(pixels * 4);
b = dt_alloc_align_float(pixels * 2);
if(a && b)
{
interpolate_bilinear(ds_a, ds_width, ds_height, a, width, height, 4);
interpolate_bilinear(ds_b, ds_width, ds_height, b, width, height, 2);
dt_free_align(ds_a);
dt_free_align(ds_b);
}
else
{
dt_free_align(ds_a);
dt_free_align(ds_b);
return;
}
}
// Apply the guided filter
DT_OMP_FOR_SIMD(aligned(a, b, corrections, saturation, gradients, UV: 64))
for(size_t k = 0; k < pixels; k++)
{
// For each correction factor, we re-express it as a[0] * U + a[1] * V + b
const float uv[2] = { UV[2 * k + 0], UV[2 * k + 1] };
const float cv[2] = { a[4 * k + 0] * uv[0] + a[4 * k + 1] * uv[1] + b[2 * k + 0],
a[4 * k + 2] * uv[0] + a[4 * k + 3] * uv[1] + b[2 * k + 1] };
corrections[2 * k + 1] = interpolatef(_get_satweight(saturation[k] - sat_shift), cv[0], 1.0f);
const float gradient_weight = 1.0f - CLIP(gradients[k]);
b_corrections[k] = interpolatef(gradient_weight * _get_satweight(saturation[k] - bright_shift), cv[1], 0.0f);
}
dt_free_align(a);
dt_free_align(b);
}
static void _prepare_process(const float roi_scale,
const dt_iop_colorequal_data_t *d,
// parameters to be setup
float *white,
float *sat_shift,
float *max_brightness_shift,
float *corr_max_brightness_shift,
float *bright_shift,
float *gradient_amp,
float *hue_sigma,
float *par_sigma,
float *sat_sigma,
float *scharr_sigma)
{
*white = Y_to_dt_UCS_L_star(d->white_level);
/* We use the logistic weighting function to diminish effects in the guided filter for locations
with low chromacity. The logistic function is precalculated for a inflection point of zero
so we have to shift the input value (saturation) for both brightness and saturation corrections.
The default can be shifted by the threshold slider.
Depending on the maximum for the eight brightness sliders we increase the brightness shift, the value
of 0.01 has been found by a lot of testing to be safe.
As increased param_size leads to propagation of brightness into achromatic parts we have to correct for that too.
*/
*sat_shift = d->threshold;
*max_brightness_shift = 0.01f * d->max_brightness;
*corr_max_brightness_shift = *max_brightness_shift * MIN(5.0f, sqrtf(d->param_size));
*bright_shift = *sat_shift + *corr_max_brightness_shift;
/* We want information about sharp transitions of saturation for halo suppression.
As the scharr operator is faster and more stable for scale changes we use
it instead of local variance.
We reduce chroma noise effects by using a minimum threshold and by sqaring the gradient.
The gradient_amp corrects a gradient of 0.5 to be 1.0 and takes care
of maximum changed brightness and roi_scale.
*/
*gradient_amp = 4.0f * sqrtf(d->max_brightness) * sqrf(roi_scale);
*hue_sigma = 0.5f * d->chroma_size * roi_scale;
*par_sigma = 0.5f * d->param_size * roi_scale;
*sat_sigma = MAX(0.5f, roi_scale);
*scharr_sigma = MAX(0.5f, roi_scale);
_init_satweights(d->contrast);
}
void process(dt_iop_module_t *self,
dt_dev_pixelpipe_iop_t *piece,
const void *const i,
void *const o,
const dt_iop_roi_t *const roi_in,
const dt_iop_roi_t *const roi_out)
{
if(!dt_iop_have_required_input_format(4 /*we need full-color pixels*/,
self, piece->colors, i, o, roi_in, roi_out))
return;
const int width = roi_out->width;
const int height = roi_out->height;
const size_t npixels = (size_t)width * height;
float *restrict UV = NULL;
float *restrict corrections = NULL;
float *restrict b_corrections = NULL;
float *restrict Lscharr = NULL;
float *restrict saturation = NULL;
if(!dt_iop_alloc_image_buffers(self, roi_in, roi_out,
2/*ch per pix*/ | DT_IMGSZ_OUTPUT | DT_IMGSZ_FULL, &UV,
2 | DT_IMGSZ_OUTPUT | DT_IMGSZ_FULL, &corrections,
1 | DT_IMGSZ_OUTPUT | DT_IMGSZ_FULL, &b_corrections,
1 | DT_IMGSZ_OUTPUT | DT_IMGSZ_FULL, &Lscharr,
1 | DT_IMGSZ_OUTPUT | DT_IMGSZ_FULL, &saturation,
0/*end of list*/))
{
// Uh oh, we didn't have enough memory! Any buffers that had
// already been allocated have been freed, and the module's
// trouble flag has been set. We can simply pass through the
// input image and return now, since there isn't anything else we