forked from darktable-org/darktable
/
toneequal.c
3324 lines (2752 loc) · 122 KB
/
toneequal.c
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) 2018-2021 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/>.
*/
/*** DOCUMENTATION
*
* This module aims at relighting the scene by performing an exposure compensation
* selectively on specified exposures octaves, the same way HiFi audio equalizers allow to set
* a gain for each octave.
*
* It is intended to work in scene-linear camera RGB, to behave as if light was physically added
* or removed from the scene. As such, it should be put before input profile in the pipe, but preferably
* after exposure. It also need to be placed after the rotation, perspective and cropping modules
* for the interactive editing to work properly (so the image buffer overlap perfectly with the
* image preview).
*
* Because it works before camera RGB -> XYZ conversion, the exposure cannot be computed from
* any human-based perceptual colour model (Y channel), hence why several RGB norms are provided as estimators of
* the pixel energy to compute a luminance map. None of them is perfect, and I'm still
* looking forward to a real spectral energy estimator. The best physically-accurate norm should be the euclidean
* norm, but the best looking is often the power norm, which has no theoretical background.
* The geometric mean also display interesting properties as it interprets saturated colours
* as low-lights, allowing to lighten and desaturate them in a realistic way.
*
* The exposure correction is computed as a series of each octave's gain weighted by the
* gaussian of the radial distance between the current pixel exposure and each octave's center.
* This allows for a smooth and continuous infinite-order interpolation, preserving exposure gradients
* as best as possible. The radius of the kernel is user-defined and can be tweaked to get
* a smoother interpolation (possibly generating oscillations), or a more monotonous one
* (possibly less smooth). The actual factors of the gaussian series are computed by
* solving the linear system taking the user-input parameters as target exposures compensations.
*
* Notice that every pixel operation is performed in linear space. The exposures in log2 (EV)
* are only used for user-input parameters and for the gaussian weights of the radial distance
* between pixel exposure and octave's centers.
*
* The details preservation modes make use of a fast guided filter optimized to perform
* an edge-aware surface blur on the luminance mask, in the same spirit as the bilateral
* filter, but without its classic issues of gradient reversal around sharp edges. This
* surface blur will allow to perform piece-wise smooth exposure compensation, so local contrast
* will be preserved inside contiguous regions. Various mask refinements are provided to help
* the edge-taping of the filter (feathering parameter) while keeping smooth contiguous region
* (quantization parameter), but also to translate (exposure boost) and dilate (contrast boost)
* the exposure histogram through the control octaves, to center it on the control view
* and make maximum use of the available channels.
*
* Users should be aware that not all the available octaves will be useful on every pictures.
* Some automatic options will help them to optimize the luminance mask, performing histogram
* analyse, mapping the average exposure to -4EV, and mapping the first and last deciles of
* the histogram on its average ± 4EV. These automatic helpers usually fail on X-Trans sensors,
* maybe because of bad demosaicing, possibly resulting in outliers\negative RGB values.
* Since they fail the same way on filmic's auto-tuner, we might need to investigate X-Trans
* algos at some point.
*
***/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <assert.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include "bauhaus/bauhaus.h"
#include "common/darktable.h"
#include "common/fast_guided_filter.h"
#include "common/eigf.h"
#include "common/interpolation.h"
#include "common/luminance_mask.h"
#include "common/opencl.h"
#include "common/collection.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 "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/iop_group.h"
#ifdef _OPENMP
#include <omp.h>
#endif
DT_MODULE_INTROSPECTION(2, dt_iop_toneequalizer_params_t)
/** Note :
* we use finite-math-only and fast-math because divisions by zero are manually avoided in the code
* fp-contract=fast enables hardware-accelerated Fused Multiply-Add
* the rest is loop reorganization and vectorization optimization
**/
#if defined(__GNUC__)
#pragma GCC optimize ("unroll-loops", "tree-loop-if-convert", \
"tree-loop-distribution", "no-strict-aliasing", \
"loop-interchange", "loop-nest-optimize", "tree-loop-im", \
"unswitch-loops", "tree-loop-ivcanon", "ira-loop-pressure", \
"split-ivs-in-unroller", "variable-expansion-in-unroller", \
"split-loops", "ivopts", "predictive-commoning",\
"tree-loop-linear", "loop-block", "loop-strip-mine", \
"finite-math-only", "fp-contract=fast", "fast-math", \
"tree-vectorize")
#endif
#define UI_SAMPLES 256 // 128 is a bit small for 4K resolution
#define CONTRAST_FULCRUM exp2f(-4.0f)
#define MIN_FLOAT exp2f(-16.0f)
/**
* Build the exposures octaves :
* band-pass filters with gaussian windows spaced by 1 EV
**/
#define CHANNELS 9
#define PIXEL_CHAN 8
#define LUT_RESOLUTION 10000
// radial distances used for pixel ops
static const float centers_ops[PIXEL_CHAN] DT_ALIGNED_ARRAY = {-56.0f / 7.0f, // = -8.0f
-48.0f / 7.0f,
-40.0f / 7.0f,
-32.0f / 7.0f,
-24.0f / 7.0f,
-16.0f / 7.0f,
-8.0f / 7.0f,
0.0f / 7.0f}; // split 8 EV into 7 evenly-spaced channels
static const float centers_params[CHANNELS] DT_ALIGNED_ARRAY = { -8.0f, -7.0f, -6.0f, -5.0f,
-4.0f, -3.0f, -2.0f, -1.0f, 0.0f};
typedef enum dt_iop_toneequalizer_filter_t
{
DT_TONEEQ_NONE = 0, // $DESCRIPTION: "no"
DT_TONEEQ_AVG_GUIDED, // $DESCRIPTION: "averaged guided filter"
DT_TONEEQ_GUIDED, // $DESCRIPTION: "guided filter"
DT_TONEEQ_AVG_EIGF, // $DESCRIPTION: "averaged eigf"
DT_TONEEQ_EIGF // $DESCRIPTION: "eigf"
} dt_iop_toneequalizer_filter_t;
typedef struct dt_iop_toneequalizer_params_t
{
float noise; // $MIN: -2.0 $MAX: 2.0 $DEFAULT: 0.0 $DESCRIPTION: "blacks"
float ultra_deep_blacks; // $MIN: -2.0 $MAX: 2.0 $DEFAULT: 0.0 $DESCRIPTION: "deep shadows"
float deep_blacks; // $MIN: -2.0 $MAX: 2.0 $DEFAULT: 0.0 $DESCRIPTION: "shadows"
float blacks; // $MIN: -2.0 $MAX: 2.0 $DEFAULT: 0.0 $DESCRIPTION: "light shadows"
float shadows; // $MIN: -2.0 $MAX: 2.0 $DEFAULT: 0.0 $DESCRIPTION: "mid-tones"
float midtones; // $MIN: -2.0 $MAX: 2.0 $DEFAULT: 0.0 $DESCRIPTION: "dark highlights"
float highlights; // $MIN: -2.0 $MAX: 2.0 $DEFAULT: 0.0 $DESCRIPTION: "highlights"
float whites; // $MIN: -2.0 $MAX: 2.0 $DEFAULT: 0.0 $DESCRIPTION: "whites"
float speculars; // $MIN: -2.0 $MAX: 2.0 $DEFAULT: 0.0 $DESCRIPTION: "speculars"
float blending; // $MIN: 0.01 $MAX: 100.0 $DEFAULT: 5.0 $DESCRIPTION: "smoothing diameter"
float smoothing; // $DEFAULT: 1.414213562 sqrtf(2.0f)
float feathering; // $MIN: 0.01 $MAX: 10000.0 $DEFAULT: 1.0 $DESCRIPTION: "edges refinement/feathering"
float quantization; // $MIN: 0.0 $MAX: 2.0 $DEFAULT: 0.0 $DESCRIPTION: "mask quantization"
float contrast_boost; // $MIN: -16.0 $MAX: 16.0 $DEFAULT: 0.0 $DESCRIPTION: "mask contrast compensation"
float exposure_boost; // $MIN: -16.0 $MAX: 16.0 $DEFAULT: 0.0 $DESCRIPTION: "mask exposure compensation"
dt_iop_toneequalizer_filter_t details; // $DEFAULT: DT_TONEEQ_EIGF
dt_iop_luminance_mask_method_t method; // $DEFAULT: DT_TONEEQ_NORM_2 $DESCRIPTION: "luminance estimator"
int iterations; // $MIN: 1 $MAX: 20 $DEFAULT: 1 $DESCRIPTION: "filter diffusion"
} dt_iop_toneequalizer_params_t;
typedef struct dt_iop_toneequalizer_data_t
{
float factors[PIXEL_CHAN] DT_ALIGNED_ARRAY;
float correction_lut[PIXEL_CHAN * LUT_RESOLUTION + 1] DT_ALIGNED_ARRAY;
float blending, feathering, contrast_boost, exposure_boost, quantization, smoothing;
float scale;
int radius;
int iterations;
dt_iop_luminance_mask_method_t method;
dt_iop_toneequalizer_filter_t details;
} dt_iop_toneequalizer_data_t;
typedef struct dt_iop_toneequalizer_global_data_t
{
// TODO: put OpenCL kernels here at some point
} dt_iop_toneequalizer_global_data_t;
typedef struct dt_iop_toneequalizer_gui_data_t
{
// Mem arrays 64-bits aligned - contiguous memory
float factors[PIXEL_CHAN] DT_ALIGNED_ARRAY;
float gui_lut[UI_SAMPLES] DT_ALIGNED_ARRAY; // LUT for the UI graph
float interpolation_matrix[CHANNELS * PIXEL_CHAN] DT_ALIGNED_ARRAY;
int histogram[UI_SAMPLES] DT_ALIGNED_ARRAY; // histogram for the UI graph
float temp_user_params[CHANNELS] DT_ALIGNED_ARRAY;
float cursor_exposure; // store the exposure value at current cursor position
float step; // scrolling step
// 14 int to pack - contiguous memory
int mask_display;
int max_histogram;
int buf_width;
int buf_height;
int cursor_pos_x;
int cursor_pos_y;
int pipe_order;
// 6 uint64 to pack - contiguous-ish memory
uint64_t ui_preview_hash;
uint64_t thumb_preview_hash;
size_t full_preview_buf_width, full_preview_buf_height;
size_t thumb_preview_buf_width, thumb_preview_buf_height;
// Misc stuff, contiguity, length and alignment unknown
float scale;
float sigma;
float histogram_average;
float histogram_first_decile;
float histogram_last_decile;
// Heap arrays, 64 bits-aligned, unknown length
float *thumb_preview_buf;
float *full_preview_buf;
// GTK garbage, nobody cares, no SIMD here
GtkWidget *noise, *ultra_deep_blacks, *deep_blacks, *blacks, *shadows, *midtones, *highlights, *whites, *speculars;
GtkDrawingArea *area, *bar;
GtkWidget *blending, *smoothing, *quantization;
GtkWidget *method;
GtkWidget *details, *feathering, *contrast_boost, *iterations, *exposure_boost;
GtkNotebook *notebook;
GtkWidget *show_luminance_mask;
// Cache Pango and Cairo stuff for the equalizer drawing
float line_height;
float sign_width;
float graph_width;
float graph_height;
float gradient_left_limit;
float gradient_right_limit;
float gradient_top_limit;
float gradient_width;
float legend_top_limit;
float x_label;
int inset;
int inner_padding;
GtkAllocation allocation;
cairo_surface_t *cst;
cairo_t *cr;
PangoLayout *layout;
PangoRectangle ink;
PangoFontDescription *desc;
GtkStyleContext *context;
// Event for equalizer drawing
float nodes_x[CHANNELS];
float nodes_y[CHANNELS];
float area_x; // x coordinate of cursor over graph/drawing area
float area_y; // y coordinate
int area_active_node;
// Flags for UI events
int valid_nodes_x; // TRUE if x coordinates of graph nodes have been inited
int valid_nodes_y; // TRUE if y coordinates of graph nodes have been inited
int area_cursor_valid; // TRUE if mouse cursor is over the graph area
int area_dragging; // TRUE if left-button has been pushed but not released and cursor motion is recorded
int cursor_valid; // TRUE if mouse cursor is over the preview image
int has_focus; // TRUE if the widget has the focus from GTK
// Flags for buffer caches invalidation
int interpolation_valid; // TRUE if the interpolation_matrix is ready
int luminance_valid; // TRUE if the luminance cache is ready
int histogram_valid; // TRUE if the histogram cache and stats are ready
int lut_valid; // TRUE if the gui_lut is ready
int graph_valid; // TRUE if the UI graph view is ready
int user_param_valid; // TRUE if users params set in interactive view are in bounds
int factors_valid; // TRUE if radial-basis coeffs are ready
} dt_iop_toneequalizer_gui_data_t;
const char *name()
{
return _("tone equalizer");
}
const char *aliases()
{
return _("tone curve|tone mapping|relight|background light|shadows highlights");
}
const char *description(struct dt_iop_module_t *self)
{
return dt_iop_set_description(self, _("relight the scene as if the lighting was done directly on the scene"),
_("corrective and creative"),
_("linear, RGB, scene-referred"),
_("quasi-linear, RGB"),
_("quasi-linear, RGB, scene-referred"));
}
int default_group()
{
return IOP_GROUP_BASIC | IOP_GROUP_GRADING;
}
int flags()
{
return IOP_FLAGS_INCLUDE_IN_STYLES | IOP_FLAGS_SUPPORTS_BLENDING;
}
int default_colorspace(dt_iop_module_t *self, dt_dev_pixelpipe_t *pipe, dt_dev_pixelpipe_iop_t *piece)
{
return iop_cs_rgb;
}
int legacy_params(dt_iop_module_t *self, const void *const old_params, const int old_version, void *new_params,
const int new_version)
{
if(old_version == 1 && new_version == 2)
{
typedef struct dt_iop_toneequalizer_params_v1_t
{
float noise, ultra_deep_blacks, deep_blacks, blacks, shadows, midtones, highlights, whites, speculars;
float blending, feathering, contrast_boost, exposure_boost;
dt_iop_toneequalizer_filter_t details;
int iterations;
dt_iop_luminance_mask_method_t method;
} dt_iop_toneequalizer_params_v1_t;
dt_iop_toneequalizer_params_v1_t *o = (dt_iop_toneequalizer_params_v1_t *)old_params;
dt_iop_toneequalizer_params_t *n = (dt_iop_toneequalizer_params_t *)new_params;
dt_iop_toneequalizer_params_t *d = (dt_iop_toneequalizer_params_t *)self->default_params;
*n = *d; // start with a fresh copy of default parameters
// Olds params
n->noise = o->noise;
n->ultra_deep_blacks = o->ultra_deep_blacks;
n->deep_blacks = o->deep_blacks;
n->blacks = o->blacks;
n->shadows = o->shadows;
n->midtones = o->midtones;
n->highlights = o->highlights;
n->whites = o->whites;
n->speculars = o->speculars;
n->blending = o->blending;
n->feathering = o->feathering;
n->contrast_boost = o->contrast_boost;
n->exposure_boost = o->exposure_boost;
n->details = o->details;
n->iterations = o->iterations;
n->method = o->method;
// New params
n->quantization = 0.01f;
n->smoothing = sqrtf(2.0f);
return 0;
}
return 1;
}
static void compress_shadows_highlight_preset_set_exposure_params(dt_iop_toneequalizer_params_t* p, const float step)
{
// this function is used to set the exposure params for the 4 "compress shadows
// highlights" presets, which use basically the same curve, centered around
// -4EV with an exposure compensation that puts middle-grey at -4EV.
p->noise = step;
p->ultra_deep_blacks = 5.f / 3.f * step;
p->deep_blacks = 5.f / 3.f * step;
p->blacks = step;
p->shadows = 0.0f;
p->midtones = -step;
p->highlights = -5.f / 3.f * step;
p->whites = -5.f / 3.f * step;
p->speculars = -step;
}
static void dilate_shadows_highlight_preset_set_exposure_params(dt_iop_toneequalizer_params_t* p, const float step)
{
// create a tone curve meant to be used without filter (as a flat, non-local, 1D tone curve) that reverts
// the local settings above.
p->noise = -15.f / 9.f * step;
p->ultra_deep_blacks = -14.f / 9.f * step;
p->deep_blacks = -12.f / 9.f * step;
p->blacks = -8.f / 9.f * step;
p->shadows = 0.f;
p->midtones = 8.f / 9.f * step;
p->highlights = 12.f / 9.f * step;
p->whites = 14.f / 9.f * step;
p->speculars = 15.f / 9.f * step;
}
void init_presets(dt_iop_module_so_t *self)
{
dt_iop_toneequalizer_params_t p;
memset(&p, 0, sizeof(p));
p.method = DT_TONEEQ_NORM_POWER;
p.contrast_boost = 0.0f;
p.details = DT_TONEEQ_NONE;
p.exposure_boost = -0.5f;
p.feathering = 1.0f;
p.iterations = 1;
p.smoothing = sqrtf(2.0f);
p.quantization = 0.0f;
// Init exposure settings
p.noise = p.ultra_deep_blacks = p.deep_blacks = p.blacks = p.shadows = p.midtones = p.highlights = p.whites = p. speculars = 0.0f;
// No blending
dt_gui_presets_add_generic(_("simple tone curve"), self->op,
self->version(), &p, sizeof(p), 1, DEVELOP_BLEND_CS_RGB_DISPLAY);
// Simple utils blendings
p.details = DT_TONEEQ_EIGF;
p.method = DT_TONEEQ_NORM_2;
p.blending = 5.0f;
p.feathering = 1.0f;
p.iterations = 1;
p.quantization = 0.0f;
p.exposure_boost = 0.0f;
p.contrast_boost = 0.0f;
dt_gui_presets_add_generic(_("mask blending : all purposes"), self->op,
self->version(), &p, sizeof(p), 1, DEVELOP_BLEND_CS_RGB_DISPLAY);
p.blending = 1.0f;
p.feathering = 10.0f;
p.iterations = 3;
dt_gui_presets_add_generic(_("mask blending : people with backlight"), self->op,
self->version(), &p, sizeof(p), 1, DEVELOP_BLEND_CS_RGB_DISPLAY);
// Shadows/highlights presets
// move middle-grey to the center of the range
p.exposure_boost = -1.57f;
p.contrast_boost = 0.0f;
p.blending = 2.0f;
p.feathering = 50.0f;
p.iterations = 5;
p.quantization = 0.0f;
// slight modification to give higher compression
p.details = DT_TONEEQ_EIGF;
p.feathering = 20.0f;
compress_shadows_highlight_preset_set_exposure_params(&p, 0.65f);
dt_gui_presets_add_generic(_("compress shadows/highlights (eigf) : strong"), self->op,
self->version(), &p, sizeof(p), 1, DEVELOP_BLEND_CS_RGB_DISPLAY);
p.details = DT_TONEEQ_GUIDED;
p.feathering = 500.0f;
dt_gui_presets_add_generic(_("compress shadows/highlights (gf) : strong"), self->op,
self->version(), &p, sizeof(p), 1, DEVELOP_BLEND_CS_RGB_DISPLAY);
p.details = DT_TONEEQ_EIGF;
p.blending = 3.0f;
p.feathering = 7.0f;
p.iterations = 3;
compress_shadows_highlight_preset_set_exposure_params(&p, 0.45f);
dt_gui_presets_add_generic(_("compress shadows/highlights (eigf) : medium"), self->op,
self->version(), &p, sizeof(p), 1, DEVELOP_BLEND_CS_RGB_DISPLAY);
p.details = DT_TONEEQ_GUIDED;
p.feathering = 500.0f;
dt_gui_presets_add_generic(_("compress shadows/highlights (gf) : medium"), self->op,
self->version(), &p, sizeof(p), 1, DEVELOP_BLEND_CS_RGB_DISPLAY);
p.details = DT_TONEEQ_EIGF;
p.blending = 5.0f;
p.feathering = 1.0f;
p.iterations = 1;
compress_shadows_highlight_preset_set_exposure_params(&p, 0.25f);
dt_gui_presets_add_generic(_("compress shadows/highlights (eigf) : soft"), self->op,
self->version(), &p, sizeof(p), 1, DEVELOP_BLEND_CS_RGB_DISPLAY);
p.details = DT_TONEEQ_GUIDED;
p.feathering = 500.0f;
dt_gui_presets_add_generic(_("compress shadows/highlights (gf) : soft"), self->op,
self->version(), &p, sizeof(p), 1, DEVELOP_BLEND_CS_RGB_DISPLAY);
// build the 1D contrast curves that revert the local compression of contrast above
p.details = DT_TONEEQ_NONE;
dilate_shadows_highlight_preset_set_exposure_params(&p, 0.25f);
dt_gui_presets_add_generic(_("contrast tone curve: soft"), self->op,
self->version(), &p, sizeof(p), 1, DEVELOP_BLEND_CS_RGB_DISPLAY);
dilate_shadows_highlight_preset_set_exposure_params(&p, 0.45f);
dt_gui_presets_add_generic(_("contrast tone curve: medium"), self->op,
self->version(), &p, sizeof(p), 1, DEVELOP_BLEND_CS_RGB_DISPLAY);
dilate_shadows_highlight_preset_set_exposure_params(&p, 0.65f);
dt_gui_presets_add_generic(_("contrast tone curve: strong"), self->op,
self->version(), &p, sizeof(p), 1, DEVELOP_BLEND_CS_RGB_DISPLAY);
// relight
p.details = DT_TONEEQ_EIGF;
p.blending = 5.0f;
p.feathering = 1.0f;
p.iterations = 1;
p.quantization = 0.0f;
p.exposure_boost = -0.5f;
p.contrast_boost = 0.0f;
p.noise = 0.0f;
p.ultra_deep_blacks = 0.15f;
p.deep_blacks = 0.6f;
p.blacks = 1.15f;
p.shadows = 1.33f;
p.midtones = 1.15f;
p.highlights = 0.6f;
p.whites = 0.15f;
p.speculars = 0.0f;
dt_gui_presets_add_generic(_("relight : fill-in"), self->op,
self->version(), &p, sizeof(p), 1, DEVELOP_BLEND_CS_RGB_DISPLAY);
}
/**
* Helper functions
**/
static gboolean in_mask_editing(dt_iop_module_t *self)
{
const dt_develop_t *dev = self->dev;
return dev->form_gui && dev->form_visible;
}
static void hash_set_get(uint64_t *hash_in, uint64_t *hash_out, dt_pthread_mutex_t *lock)
{
// Set or get a hash in a struct the thread-safe way
dt_pthread_mutex_lock(lock);
*hash_out = *hash_in;
dt_pthread_mutex_unlock(lock);
}
static void invalidate_luminance_cache(dt_iop_module_t *const self)
{
// Invalidate the private luminance cache and histogram when
// the luminance mask extraction parameters have changed
dt_iop_toneequalizer_gui_data_t *const restrict g = (dt_iop_toneequalizer_gui_data_t *)self->gui_data;
dt_iop_gui_enter_critical_section(self);
g->max_histogram = 1;
//g->luminance_valid = 0;
g->histogram_valid = 0;
g->thumb_preview_hash = 0;
g->ui_preview_hash = 0;
dt_iop_gui_leave_critical_section(self);
}
static int sanity_check(dt_iop_module_t *self)
{
// If tone equalizer is put after flip/orientation module,
// the pixel buffer will be in landscape orientation even for pictures displayed in portrait orientation
// so the interactive editing will fail. Disable the module and issue a warning then.
const double position_self = self->iop_order;
const double position_min = dt_ioppr_get_iop_order(self->dev->iop_order_list, "flip", 0);
if(position_self < position_min && self->enabled)
{
dt_control_log(_("tone equalizer needs to be after distortion modules in the pipeline – disabled"));
fprintf(stdout, "tone equalizer needs to be after distortion modules in the pipeline – disabled\n");
self->enabled = 0;
dt_dev_add_history_item(darktable.develop, self, FALSE);
if(self->dev->gui_attached)
{
// Repaint the on/off icon
if(self->off)
{
++darktable.gui->reset;
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(self->off), self->enabled);
--darktable.gui->reset;
}
}
return 0;
}
return 1;
}
// gaussian-ish kernel - sum is == 1.0f so we don't care much about actual coeffs
static const dt_colormatrix_t gauss_kernel =
{ { 0.076555024f, 0.124401914f, 0.076555024f },
{ 0.124401914f, 0.196172249f, 0.124401914f },
{ 0.076555024f, 0.124401914f, 0.076555024f } };
__DT_CLONE_TARGETS__
static float get_luminance_from_buffer(const float *const buffer,
const size_t width, const size_t height,
const size_t x, const size_t y)
{
// Get the weighted average luminance of the 3×3 pixels region centered in (x, y)
// x and y are ratios in [0, 1] of the width and height
if(y >= height || x >= width) return NAN;
const size_t y_abs[4] DT_ALIGNED_PIXEL =
{ MAX(y, 1) - 1, // previous line
y, // center line
MIN(y + 1, height - 1), // next line
y }; // padding for vectorization
float luminance = 0.0f;
if (x > 0 && x < width - 2)
{
// no clamping needed on x, which allows us to vectorize
// apply the convolution
for(int i = 0; i < 3; ++i)
{
const size_t y_i = y_abs[i];
for_each_channel(j)
luminance += buffer[width * y_i + x-1 + j] * gauss_kernel[i][j];
}
return luminance;
}
const size_t x_abs[4] DT_ALIGNED_PIXEL =
{ MAX(x, 1) - 1, // previous column
x, // center column
MIN(x + 1, width - 1), // next column
x }; // padding for vectorization
// convolution
for(int i = 0; i < 3; ++i)
{
const size_t y_i = y_abs[i];
for_each_channel(j)
luminance += buffer[width * y_i + x_abs[j]] * gauss_kernel[i][j];
}
return luminance;
}
/***
* Exposure compensation computation
*
* Construct the final correction factor by summing the octaves channels gains weighted by
* the gaussian of the radial distance (pixel exposure - octave center)
*
***/
#ifdef _OPENMP
#pragma omp declare simd
#endif
__DT_CLONE_TARGETS__
static float gaussian_denom(const float sigma)
{
// Gaussian function denominator such that y = exp(- radius^2 / denominator)
// this is the constant factor of the exponential, so we don't need to recompute it
// for every single pixel
return 2.0f * sigma * sigma;
}
#ifdef _OPENMP
#pragma omp declare simd
#endif
__DT_CLONE_TARGETS__
static float gaussian_func(const float radius, const float denominator)
{
// Gaussian function without normalization
// this is the variable part of the exponential
// the denominator should be evaluated with `gaussian_denom`
// ahead of the array loop for optimal performance
return expf(- radius * radius / denominator);
}
#define DT_TONEEQ_USE_LUT TRUE
#if DT_TONEEQ_USE_LUT
// this is the version currently used, as using a lut gives a
// big performance speedup on some cpus
__DT_CLONE_TARGETS__
static inline void apply_toneequalizer(const float *const restrict in,
const float *const restrict luminance,
float *const restrict out,
const dt_iop_roi_t *const roi_in, const dt_iop_roi_t *const roi_out,
const size_t ch,
const dt_iop_toneequalizer_data_t *const d)
{
const size_t num_elem = (size_t)roi_in->width * roi_in->height;
const int min_ev = -8;
const int max_ev = 0;
const float* restrict lut = d->correction_lut;
#ifdef _OPENMP
#pragma omp parallel for default(none) schedule(static) \
dt_omp_firstprivate(in, out, num_elem, luminance, lut, min_ev, max_ev, ch)
#endif
for(size_t k = 0; k < num_elem; ++k)
{
// The radial-basis interpolation is valid in [-8; 0] EV and can quickely diverge outside
const float exposure = fast_clamp(log2f(luminance[k]), min_ev, max_ev);
float correction = lut[(unsigned)roundf((exposure - min_ev) * LUT_RESOLUTION)];
// apply correction
for(size_t c = 0; c < ch; c++)
{
if(c == 3)
out[k * ch + c] = in[k * ch + c];
else
out[k * ch + c] = correction * in[k * ch + c];
}
}
}
#else
// we keep this version for further reference (e.g. for implementing
// a gpu version)
__DT_CLONE_TARGETS__
static inline void apply_toneequalizer(const float *const restrict in,
const float *const restrict luminance,
float *const restrict out,
const dt_iop_roi_t *const roi_in, const dt_iop_roi_t *const roi_out,
const size_t ch,
const dt_iop_toneequalizer_data_t *const d)
{
const size_t num_elem = roi_in->width * roi_in->height;
const float *const restrict factors = d->factors;
const float sigma = d->smoothing;
const float gauss_denom = gaussian_denom(sigma);
#ifdef _OPENMP
#pragma omp parallel for default(none) schedule(static) \
dt_omp_firstprivate(in, out, num_elem, luminance, factors, centers_ops, gauss_denom, ch)
#endif
for(size_t k = 0; k < num_elem; ++k)
{
// build the correction for the current pixel
// as the sum of the contribution of each luminance channelcorrection
float result = 0.0f;
// The radial-basis interpolation is valid in [-8; 0] EV and can quickely diverge outside
const float exposure = fast_clamp(log2f(luminance[k]), -8.0f, 0.0f);
#ifdef _OPENMP
#pragma omp simd aligned(luminance, centers_ops, factors:64) safelen(PIXEL_CHAN) reduction(+:result)
#endif
for(int i = 0; i < PIXEL_CHAN; ++i)
result += gaussian_func(exposure - centers_ops[i], gauss_denom) * factors[i];
// the user-set correction is expected in [-2;+2] EV, so is the interpolated one
float correction = fast_clamp(result, 0.25f, 4.0f);
// apply correction
for(size_t c = 0; c < ch; c++)
{
if(c == 3)
out[k * ch + c] = in[k * ch + c];
else
out[k * ch + c] = correction * in[k * ch + c];
}
}
}
#endif // USE_LUT
__DT_CLONE_TARGETS__
static inline float pixel_correction(const float exposure,
const float *const restrict factors,
const float sigma)
{
// build the correction for the current pixel
// as the sum of the contribution of each luminance channel
float result = 0.0f;
const float gauss_denom = gaussian_denom(sigma);
const float expo = fast_clamp(exposure, -8.0f, 0.0f);
#ifdef _OPENMP
#pragma omp simd aligned(centers_ops, factors:64) safelen(PIXEL_CHAN) reduction(+:result)
#endif
for(int i = 0; i < PIXEL_CHAN; ++i)
result += gaussian_func(expo - centers_ops[i], gauss_denom) * factors[i];
return fast_clamp(result, 0.25f, 4.0f);
}
__DT_CLONE_TARGETS__
static inline void compute_luminance_mask(const float *const restrict in, float *const restrict luminance,
const size_t width, const size_t height, const size_t ch,
const dt_iop_toneequalizer_data_t *const d)
{
switch(d->details)
{
case(DT_TONEEQ_NONE):
{
// No contrast boost here
luminance_mask(in, luminance, width, height, ch, d->method, d->exposure_boost, 0.0f, 1.0f);
break;
}
case(DT_TONEEQ_AVG_GUIDED):
{
// Still no contrast boost
luminance_mask(in, luminance, width, height, ch, d->method, d->exposure_boost, 0.0f, 1.0f);
fast_surface_blur(luminance, width, height, d->radius, d->feathering, d->iterations,
DT_GF_BLENDING_GEOMEAN, d->scale, d->quantization, exp2f(-14.0f), 4.0f);
break;
}
case(DT_TONEEQ_GUIDED):
{
// Contrast boosting is done around the average luminance of the mask.
// This is to make exposure corrections easier to control for users, by spreading
// the dynamic range along all exposure channels, because guided filters
// tend to flatten the luminance mask a lot around an average ± 2 EV
// which makes only 2-3 channels usable.
// we assume the distribution is centered around -4EV, e.g. the center of the nodes
// the exposure boost should be used to make this assumption true
luminance_mask(in, luminance, width, height, ch, d->method, d->exposure_boost,
CONTRAST_FULCRUM, d->contrast_boost);
fast_surface_blur(luminance, width, height, d->radius, d->feathering, d->iterations,
DT_GF_BLENDING_LINEAR, d->scale, d->quantization, exp2f(-14.0f), 4.0f);
break;
}
case(DT_TONEEQ_AVG_EIGF):
{
// Still no contrast boost
luminance_mask(in, luminance, width, height, ch, d->method, d->exposure_boost, 0.0f, 1.0f);
fast_eigf_surface_blur(luminance, width, height, d->radius, d->feathering, d->iterations,
DT_GF_BLENDING_GEOMEAN, d->scale, d->quantization, exp2f(-14.0f), 4.0f);
break;
}
case(DT_TONEEQ_EIGF):
{
luminance_mask(in, luminance, width, height, ch, d->method, d->exposure_boost,
CONTRAST_FULCRUM, d->contrast_boost);
fast_eigf_surface_blur(luminance, width, height, d->radius, d->feathering, d->iterations,
DT_GF_BLENDING_LINEAR, d->scale, d->quantization, exp2f(-14.0f), 4.0f);
break;
}
default:
{
luminance_mask(in, luminance, width, height, ch, d->method, d->exposure_boost, 0.0f, 1.0f);
break;
}
}
}
/***
* Actual transfer functions
**/
__DT_CLONE_TARGETS__
static inline void display_luminance_mask(const float *const restrict in,
const float *const restrict luminance,
float *const restrict out,
const dt_iop_roi_t *const roi_in, const dt_iop_roi_t *const roi_out,
const size_t ch)
{
const size_t offset_x = (roi_in->x < roi_out->x) ? -roi_in->x + roi_out->x : 0;
const size_t offset_y = (roi_in->y < roi_out->y) ? -roi_in->y + roi_out->y : 0;
// The output dimensions need to be smaller or equal to the input ones
// there is no logical reason they shouldn't, except some weird bug in the pipe
// in this case, ensure we don't segfault
const size_t in_width = roi_in->width;
const size_t out_width = (roi_in->width > roi_out->width) ? roi_out->width : roi_in->width;
const size_t out_height = (roi_in->height > roi_out->height) ? roi_out->height : roi_in->height;
#ifdef _OPENMP
#pragma omp parallel for default(none) \
dt_omp_firstprivate(luminance, out, in, in_width, out_width, out_height, offset_x, offset_y, ch) \
schedule(static) collapse(2)
#endif
for(size_t i = 0 ; i < out_height; ++i)
for(size_t j = 0; j < out_width; ++j)
{
// normalize the mask intensity between -8 EV and 0 EV for clarity,
// and add a "gamma" 2.0 for better legibility in shadows
const float intensity = sqrtf(fminf(fmaxf(luminance[(i + offset_y) * in_width + (j + offset_x)] - 0.00390625f, 0.f) / 0.99609375f, 1.f));
const size_t index = (i * out_width + j) * ch;
// set gray level for the mask
for_each_channel(c,aligned(out))
{
out[index + c] = intensity;
}
// copy alpha channel
out[index + 3] = in[((i + offset_y) * in_width + (j + offset_x)) * ch + 3];
}
}
__DT_CLONE_TARGETS__
static
void toneeq_process(struct dt_iop_module_t *self, dt_dev_pixelpipe_iop_t *piece,
const void *const restrict ivoid, void *const restrict ovoid,
const dt_iop_roi_t *const roi_in, const dt_iop_roi_t *const roi_out)
{
const dt_iop_toneequalizer_data_t *const d = (const dt_iop_toneequalizer_data_t *const)piece->data;
dt_iop_toneequalizer_gui_data_t *const g = (dt_iop_toneequalizer_gui_data_t *)self->gui_data;
const float *const restrict in = dt_check_sse_aligned((float *const)ivoid);
float *const restrict out = dt_check_sse_aligned((float *const)ovoid);
float *restrict luminance = NULL;
if(in == NULL || out == NULL)
{
// Pointers are not 64-bits aligned, and SSE code will segfault
dt_control_log(_("tone equalizer in/out buffer are ill-aligned, please report the bug to the developers"));
fprintf(stdout, "tone equalizer in/out buffer are ill-aligned, please report the bug to the developers\n");
return;
}
const size_t width = roi_in->width;
const size_t height = roi_in->height;
const size_t num_elem = width * height;
const size_t ch = 4;
// Get the hash of the upstream pipe to track changes
const int position = self->iop_order;
uint64_t hash = dt_dev_pixelpipe_cache_hash(piece->pipe->image.id, roi_out, piece->pipe, position);
// Sanity checks
if(width < 1 || height < 1) return;
if(roi_in->width < roi_out->width || roi_in->height < roi_out->height) return; // input should be at least as large as output
if(piece->colors != 4) return; // we need RGB signal
if(!sanity_check(self))
{
// if module just got disabled by sanity checks, due to pipe position, just pass input through
dt_simd_memcpy(in, out, num_elem * ch);
return;
}
// Init the luminance masks buffers
gboolean cached = FALSE;
if(self->dev->gui_attached)
{
// If the module instance has changed order in the pipe, invalidate the caches
if(g->pipe_order != position)
{
dt_iop_gui_enter_critical_section(self);
g->ui_preview_hash = 0;
g->thumb_preview_hash = 0;
g->pipe_order = position;
g->luminance_valid = FALSE;
g->histogram_valid = FALSE;
dt_iop_gui_leave_critical_section(self);
}
if((piece->pipe->type & DT_DEV_PIXELPIPE_FULL) == DT_DEV_PIXELPIPE_FULL)
{
// For DT_DEV_PIXELPIPE_FULL, we cache the luminance mask for performance
// but it's not accessed from GUI
// no need for threads lock since no other function is writing/reading that buffer
// Re-allocate a new buffer if the full preview size has changed
if(g->full_preview_buf_width != width || g->full_preview_buf_height != height)
{
if(g->full_preview_buf) dt_free_align(g->full_preview_buf);
g->full_preview_buf = dt_alloc_sse_ps(num_elem);
g->full_preview_buf_width = width;
g->full_preview_buf_height = height;
}
luminance = g->full_preview_buf;
cached = TRUE;
}
else if((piece->pipe->type & DT_DEV_PIXELPIPE_PREVIEW) == DT_DEV_PIXELPIPE_PREVIEW)
{
// For DT_DEV_PIXELPIPE_PREVIEW, we need to cache is too to compute the full image stats
// upon user request in GUI
// threads locks are required since GUI reads and writes on that buffer.