diff --git a/data/darktableconfig.xml.in b/data/darktableconfig.xml.in index 3f6223e87e32..cebfc924a2db 100644 --- a/data/darktableconfig.xml.in +++ b/data/darktableconfig.xml.in @@ -3079,6 +3079,13 @@ height of color balance rgb graph in per cent height of color balance rgb graph in per cent + + plugins/darkroom/toneequal/graphheight + int + 300 + height of tone equalizer graph in per cent + height of tone equalizer graph in per cent + plugins/darkroom/histogram/mode diff --git a/src/common/luminance_mask.h b/src/common/luminance_mask.h index 99183c4a1957..4f5fbbf182ad 100644 --- a/src/common/luminance_mask.h +++ b/src/common/luminance_mask.h @@ -43,10 +43,12 @@ typedef enum dt_iop_luminance_mask_method_t DT_TONEEQ_LIGHTNESS, // $DESCRIPTION: "HSL lightness" DT_TONEEQ_VALUE, // $DESCRIPTION: "HSV value / RGB max" DT_TONEEQ_NORM_1, // $DESCRIPTION: "RGB sum" - DT_TONEEQ_NORM_2, // $DESCRIPTION: "RGB euclidean norm") + DT_TONEEQ_NORM_2, // $DESCRIPTION: "RGB euclidean norm" DT_TONEEQ_NORM_POWER, // $DESCRIPTION: "RGB power norm" DT_TONEEQ_GEOMEAN, // $DESCRIPTION: "RGB geometric mean" - DT_TONEEQ_LAST + DT_TONEEQ_REC709W, // $DESCRIPTION: "Rec. 709 weights" + DT_TONEEQ_LAST, + DT_TONEEQ_CUSTOM, // $DESCRIPTION: "Custom" } dt_iop_luminance_mask_method_t; /** @@ -78,11 +80,9 @@ static float linear_contrast(const float pixel, const float fulcrum, const float DT_OMP_DECLARE_SIMD(aligned(image, luminance:64) uniform(image, luminance)) __DT_CLONE_TARGETS__ -static void pixel_rgb_mean(const float *const restrict image, +static float pixel_rgb_mean(const float *const restrict image, float *const restrict luminance, - const size_t k, - const float exposure_boost, - const float fulcrum, const float contrast_boost) + const size_t k) { // mean(RGB) is the intensity @@ -92,67 +92,67 @@ static void pixel_rgb_mean(const float *const restrict image, for(int c = 0; c < 3; ++c) lum += image[k + c]; - luminance[k / 4] = linear_contrast(exposure_boost * lum / 3.0f, fulcrum, contrast_boost); + return lum / 3.0f; + + //luminance[k / 4] = linear_contrast(exposure_boost * lum / 3.0f, fulcrum, contrast_boost); } DT_OMP_DECLARE_SIMD(aligned(image, luminance:64) uniform(image, luminance)) __DT_CLONE_TARGETS__ -static void pixel_rgb_value(const float *const restrict image, +static float pixel_rgb_value(const float *const restrict image, float *const restrict luminance, - const size_t k, - const float exposure_boost, - const float fulcrum, const float contrast_boost) + const size_t k) { // max(RGB) is equivalent to HSV value - const float lum = exposure_boost * MAX(MAX(image[k], image[k + 1]), image[k + 2]); - luminance[k / 4] = linear_contrast(lum, fulcrum, contrast_boost); + const float lum = MAX(MAX(image[k], image[k + 1]), image[k + 2]); + return lum; + + //luminance[k / 4] = linear_contrast(lum, fulcrum, contrast_boost); } DT_OMP_DECLARE_SIMD(aligned(image, luminance:64) uniform(image, luminance)) __DT_CLONE_TARGETS__ -static void pixel_rgb_lightness(const float *const restrict image, +static float pixel_rgb_lightness(const float *const restrict image, float *const restrict luminance, - const size_t k, - const float exposure_boost, - const float fulcrum, const float contrast_boost) + const size_t k) { // (max(RGB) + min(RGB)) / 2 is equivalent to HSL lightness const float max_rgb = MAX(MAX(image[k], image[k + 1]), image[k + 2]); const float min_rgb = MIN(MIN(image[k], image[k + 1]), image[k + 2]); - luminance[k / 4] = linear_contrast(exposure_boost * (max_rgb + min_rgb) / 2.0f, fulcrum, contrast_boost); + return (max_rgb + min_rgb) / 2.0f; + + //luminance[k / 4] = linear_contrast(exposure_boost * (max_rgb + min_rgb) / 2.0f, fulcrum, contrast_boost); } DT_OMP_DECLARE_SIMD(aligned(image, luminance:64) uniform(image, luminance)) __DT_CLONE_TARGETS__ -static void pixel_rgb_norm_1(const float *const restrict image, +static float pixel_rgb_norm_1(const float *const restrict image, float *const restrict luminance, - const size_t k, - const float exposure_boost, - const float fulcrum, const float contrast_boost) + const size_t k) { // vector norm L1 float lum = 0.0f; - DT_OMP_SIMD(reduction(+:lum) aligned(image:64)) - for(int c = 0; c < 3; ++c) - lum += fabsf(image[k + c]); + DT_OMP_SIMD(reduction(+:lum) aligned(image:64)) + for(int c = 0; c < 3; ++c) + lum += fabsf(image[k + c]); - luminance[k / 4] = linear_contrast(exposure_boost * lum, fulcrum, contrast_boost); + return lum; + + // luminance[k / 4] = linear_contrast(exposure_boost * lum, fulcrum, contrast_boost); } DT_OMP_DECLARE_SIMD(aligned(image, luminance:64) uniform(image, luminance)) __DT_CLONE_TARGETS__ -static void pixel_rgb_norm_2(const float *const restrict image, +static float pixel_rgb_norm_2(const float *const restrict image, float *const restrict luminance, - const size_t k, - const float exposure_boost, - const float fulcrum, const float contrast_boost) + const size_t k) { // vector norm L2 : euclidean norm @@ -162,17 +162,17 @@ static void pixel_rgb_norm_2(const float *const restrict image, for(int c = 0; c < 3; ++c) result += image[k + c] * image[k + c]; - luminance[k / 4] = linear_contrast(exposure_boost * sqrtf(result), fulcrum, contrast_boost); + return sqrtf(result); + + // luminance[k / 4] = linear_contrast(exposure_boost * sqrtf(result), fulcrum, contrast_boost); } DT_OMP_DECLARE_SIMD(aligned(image, luminance:64) uniform(image, luminance)) __DT_CLONE_TARGETS__ -static void pixel_rgb_norm_power(const float *const restrict image, +static float pixel_rgb_norm_power(const float *const restrict image, float *const restrict luminance, - const size_t k, - const float exposure_boost, - const float fulcrum, const float contrast_boost) + const size_t k) { // weird norm sort of perceptual. This is black magic really, but it looks good. @@ -189,16 +189,16 @@ static void pixel_rgb_norm_power(const float *const restrict image, denominator += RGB_square; } - luminance[k / 4] = linear_contrast(exposure_boost * numerator / denominator, fulcrum, contrast_boost); + return numerator / denominator; + + // luminance[k / 4] = linear_contrast(exposure_boost * numerator / denominator, fulcrum, contrast_boost); } DT_OMP_DECLARE_SIMD(aligned(image, luminance:64) uniform(image, luminance)) __DT_CLONE_TARGETS__ -static void pixel_rgb_geomean(const float *const restrict image, +static float pixel_rgb_geomean(const float *const restrict image, float *const restrict luminance, - const size_t k, - const float exposure_boost, - const float fulcrum, const float contrast_boost) + const size_t k) { // geometric_mean(RGB). Kind of interesting for saturated colours (maps them to shadows) @@ -210,7 +210,35 @@ static void pixel_rgb_geomean(const float *const restrict image, lum *= fabsf(image[k + c]); } - luminance[k / 4] = linear_contrast(exposure_boost * powf(lum, 1.0f / 3.0f), fulcrum, contrast_boost); + return powf(lum, 1.0f / 3.0f); + + // luminance[k / 4] = linear_contrast(exposure_boost * powf(lum, 1.0f / 3.0f), fulcrum, contrast_boost); +} + +DT_OMP_DECLARE_SIMD(aligned(image, luminance:64) uniform(image, luminance)) +__DT_CLONE_TARGETS__ +static float pixel_rgb_r709w(const float *const restrict image, + float *const restrict luminance, + const size_t k) +{ + const float lum = 0.2126 * image[k] + 0.7152 * image[k + 1] + 0.0722 * image[k + 2]; + return lum; + // luminance[k / 4] = linear_contrast(lum, fulcrum, contrast_boost); +} + + +DT_OMP_DECLARE_SIMD(aligned(image, luminance:64) uniform(image, luminance)) +__DT_CLONE_TARGETS__ +static float pixel_rgb_custom(const float *const restrict image, + float *const restrict luminance, + const size_t k, + const float r_weight, + const float g_weight, + const float b_weight) +{ + const float lum = MAX(MIN_FLOAT, r_weight * image[k] + g_weight * image[k + 1] + b_weight * image[k + 2]); + return lum; + // luminance[k / 4] = linear_contrast(lum, fulcrum, contrast_boost); } @@ -221,11 +249,16 @@ static void pixel_rgb_geomean(const float *const restrict image, #define LOOP(fn) \ { \ _Pragma ("omp parallel for simd default(none) schedule(static) \ - dt_omp_firstprivate(num_elem, in, out, exposure_boost, fulcrum, contrast_boost)\ + dt_omp_firstprivate(num_elem, in, out, exposure_boost, fulcrum, contrast_boost, r_weight, g_weight, b_weight)\ + reduction(min:min_lum) reduction(max:max_lum) \ aligned(in, out:64)" ) \ for(size_t k = 0; k < num_elem; k += 4) \ { \ - fn(in, out, k, exposure_boost, fulcrum, contrast_boost); \ + const float lum = COMPUTE_LUM(fn); \ + const float lum_boosted = linear_contrast(exposure_boost * lum, fulcrum, contrast_boost); \ + min_lum = MIN(min_lum, lum_boosted); \ + max_lum = MAX(max_lum, lum_boosted); \ + out[k / 4] = lum_boosted; \ } \ break; \ } @@ -234,7 +267,11 @@ static void pixel_rgb_geomean(const float *const restrict image, { \ for(size_t k = 0; k < num_elem; k += 4) \ { \ - fn(in, out, k, exposure_boost, fulcrum, contrast_boost); \ + const float lum = COMPUTE_LUM(fn); \ + const float lum_boosted = linear_contrast(exposure_boost * lum, fulcrum, contrast_boost); \ + min_lum = MIN(min_lum, lum_boosted); \ + max_lum = MAX(max_lum, lum_boosted); \ + out[k / 4] = lum_boosted; \ } \ break; \ } @@ -249,11 +286,23 @@ static inline void luminance_mask(const float *const restrict in, const dt_iop_luminance_mask_method_t method, const float exposure_boost, const float fulcrum, - const float contrast_boost) + const float contrast_boost, + const float r_weight, + const float g_weight, + const float b_weight, + float *image_min_ev, + float *image_max_ev) { const size_t num_elem = width * height * 4; + float min_lum = INFINITY; + float max_lum = -INFINITY; + + printf("luminance_mask: method=%d, exposure_boost=%f, fulcrum=%f, contrast_boost=%f, r_weight=%f, g_weight=%f, b_weight=%f\n", + method, exposure_boost, fulcrum, contrast_boost, r_weight, g_weight, b_weight); + switch(method) { + #define COMPUTE_LUM(fn) fn(in, out, k) case DT_TONEEQ_MEAN: LOOP(pixel_rgb_mean); @@ -275,12 +324,71 @@ static inline void luminance_mask(const float *const restrict in, case DT_TONEEQ_GEOMEAN: LOOP(pixel_rgb_geomean); + case DT_TONEEQ_REC709W: + LOOP(pixel_rgb_r709w); + + #undef COMPUTE_LUM + #define COMPUTE_LUM(fn) fn(in, out, k, r_weight, g_weight, b_weight) + case DT_TONEEQ_CUSTOM: + LOOP(pixel_rgb_custom); + default: break; } + + *image_min_ev = log2f(min_lum); + *image_max_ev = log2f(max_lum); } + + +// __DT_CLONE_TARGETS__ +// static inline void luminance_mask2(const float *const restrict in, +// float *const restrict out, +// const size_t width, +// const size_t height, +// const dt_iop_luminance_mask_method_t method, +// const float exposure_boost, +// const float fulcrum, +// const float contrast_boost +// const float r_weight, +// const float g_weight, +// const float b_weight) +// { + +// const size_t num_elem = width * height * 4; +// switch(method) +// { +// case DT_TONEEQ_MEAN: +// LOOP(pixel_rgb_mean); + +// case DT_TONEEQ_LIGHTNESS: +// LOOP(pixel_rgb_lightness); + +// case DT_TONEEQ_VALUE: +// LOOP(pixel_rgb_value); + +// case DT_TONEEQ_NORM_1: +// LOOP(pixel_rgb_norm_1); + +// case DT_TONEEQ_NORM_2: +// LOOP(pixel_rgb_norm_2); + +// case DT_TONEEQ_NORM_POWER: +// LOOP(pixel_rgb_norm_power); + +// case DT_TONEEQ_GEOMEAN: +// LOOP(pixel_rgb_geomean); + +// case DT_TONEEQ_REC709W: +// LOOP(pixel_rgb_r709w); + +// default: +// break; +// } +// } + // clang-format off // modelines: These editor modelines have been set for all relevant files by tools/update_modelines.py // vim: shiftwidth=2 expandtab tabstop=2 cindent diff --git a/src/iop/toneequal.c b/src/iop/toneequal.c index 3a89a3a32936..fbee8cd6b1ff 100644 --- a/src/iop/toneequal.c +++ b/src/iop/toneequal.c @@ -37,14 +37,14 @@ * 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 + * 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 + * 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 @@ -73,7 +73,7 @@ * * 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 + * optimize the luminance mask, performing histogram analysis, 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 @@ -92,8 +92,10 @@ #include #include + #include "bauhaus/bauhaus.h" #include "common/darktable.h" +// #include "common/curve_tools.h" #include "common/fast_guided_filter.h" #include "common/eigf.h" #include "common/interpolation.h" @@ -123,25 +125,117 @@ #include #endif +// #define MF_DEBUG +#ifdef MF_DEBUG +#include // Only needed for debug printf of hashes, TODO remove +#endif + +#include +#include + +#define dbg_plot_width 49 +#define dbg_plot_height 5 // y = +2, +1, 0, -1, -2 + + +void plot_ascii(const float y_values[49], float mark1, float mark2) { + const float x_start = -16.0f; + const float x_step = 0.5f; + + // Prepare the graph: fill with spaces + char graph[dbg_plot_height][dbg_plot_width + 1]; + for (int row = 0; row < dbg_plot_height; ++row) { + for (int col = 0; col < dbg_plot_width; ++col) { + // Draw dashed lines at y = +2 (row 0), y = 0 (row 2), y = -2 (row 4) + if (row == 0 || row == 2 || row == 4) + graph[row][col] = '-'; + else + graph[row][col] = ' '; + } + graph[row][dbg_plot_width] = '\0'; + } + + // Overwrite with stars for the data points + for (int col = 0; col < dbg_plot_width; ++col) { + float y = y_values[col]; + // Map y in [-2,2] to row index: +2->0, 0->2, -2->4 + int row = (int)round((2.0f - y) * (dbg_plot_height) / 5.0f); + if (row < 0) row = 0; + if (row >= dbg_plot_height) row = dbg_plot_height; + graph[row][col] = '*'; + } + + // Prepare the x-axis marker row + char x_axis[dbg_plot_width + 1]; + for (int col = 0; col < dbg_plot_width; ++col) { + float x = x_start + col * x_step; + if (fabsf(x - mark1) < x_step / 2 || fabsf(x - mark2) < x_step / 2) { + x_axis[col] = '^'; + } else if (fmodf(x + 16, 2.0f) < 0.01f) { + x_axis[col] = '|'; + } else { + x_axis[col] = ' '; + } + } + x_axis[dbg_plot_width] = '\0'; + + // Print the top border and +2 label -DT_MODULE_INTROSPECTION(2, dt_iop_toneequalizer_params_t) + // Print each row of the graph with labels + for (int row = 0; row < dbg_plot_height; ++row) { + printf("%s", graph[row]); + if (row == 0) printf(" +2\n"); + else if (row == 2) printf(" 0\n"); + else if (row == 4) printf(" -2\n"); + else printf("\n"); + } + // Print the x-axis markers + printf("%s\n", x_axis); + // Print the x-axis labels + printf("-16 -14 -12 -10 -8 -6 -4 -2 0 2 4 6 8\n"); + printf("\n"); +} +DT_MODULE_INTROSPECTION(3, dt_iop_toneequalizer_params_t) + +/**************************************************************************** + * + * Definition of constants + * + ****************************************************************************/ -#define UI_SAMPLES 256 // 128 is a bit small for 4K resolution +#define UI_HISTO_SAMPLES 256 // 128 is a bit small for 4K resolution +#define HDR_HISTO_SAMPLES UI_HISTO_SAMPLES * 32 #define CONTRAST_FULCRUM exp2f(-4.0f) #define MIN_FLOAT exp2f(-16.0f) +#define DT_TONEEQ_MIN_EV (-8.0f) +#define DT_TONEEQ_MAX_EV (0.0f) + +// We need more space for the histogram and also for the LUT +// This needs to comprise the possible scaled/shifted range of +// the original 8EV. +#define HDR_MIN_EV -16.0f +#define HDR_MAX_EV 8.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 +#define NUM_SLIDERS 9 +#define NUM_OCTAVES 8 + +// TODO MF: Alway use the term "octave" for "graph EVs" + +// Resolution per Octave. 2048 * 8 = 16k +// So the final size with floats in it should be 64k. +// We use 2047, so we have space for one extra border +// point (the 0 EV point) in the lut and are still +// below 16k entries for cache efficiency. +#define LUT_RESOLUTION 2047 // radial distances used for pixel ops -static const float centers_ops[PIXEL_CHAN] DT_ALIGNED_ARRAY = +static const float centers_ops[NUM_OCTAVES] DT_ALIGNED_ARRAY = {-56.0f / 7.0f, // = -8.0f -48.0f / 7.0f, -40.0f / 7.0f, @@ -149,12 +243,24 @@ static const float centers_ops[PIXEL_CHAN] DT_ALIGNED_ARRAY = -24.0f / 7.0f, -16.0f / 7.0f, -8.0f / 7.0f, - 0.0f / 7.0f}; // split 8 EV into 7 evenly-spaced channels + 0.0f / 7.0f}; // split 8 EV into 7 evenly-spaced NUM_SLIDERS -static const float centers_params[CHANNELS] DT_ALIGNED_ARRAY = +static const float centers_params[NUM_SLIDERS] DT_ALIGNED_ARRAY = { -8.0f, -7.0f, -6.0f, -5.0f, -4.0f, -3.0f, -2.0f, -1.0f, 0.0f}; +// 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 } }; + + +/**************************************************************************** + * + * Types + * + ****************************************************************************/ typedef enum dt_iop_toneequalizer_filter_t { @@ -165,40 +271,76 @@ typedef enum dt_iop_toneequalizer_filter_t DT_TONEEQ_EIGF // $DESCRIPTION: "EIGF" } dt_iop_toneequalizer_filter_t; +typedef enum dt_iop_toneequalizer_version_t +{ + DT_TONEEQ_VERSION_2 = 2, // $DESCRIPTION: "v2" + DT_TONEEQ_VERSION_3 = 3, // $DESCRIPTION: "v3" +} dt_iop_toneequalizer_version_t; + +typedef enum dt_iop_toneequalizer_curve_t +{ + DT_TONEEQ_CURVE_GAUSS = 2, // $DESCRIPTION: "Gauss (for large changes)" + DT_TONEEQ_CURVE_CATMULL = 3, // $DESCRIPTION: "Catmull-Rom (for small changes)" +} dt_iop_toneequalizer_curve_t; typedef struct dt_iop_toneequalizer_params_t { - float noise; // $MIN: -2.0 $MAX: 2.0 $DEFAULT: 0.0 $DESCRIPTION: "blacks" + // v1 + 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" + 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: 0.0 + 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 filter; // $DEFAULT: DT_TONEEQ_EIGF + dt_iop_luminance_mask_method_t lum_estimator; // $DEFAULT: DT_TONEEQ_CUSTOM $DESCRIPTION: "luminance estimator" + int iterations; // $MIN: 1 $MAX: 20 $DEFAULT: 1 $DESCRIPTION: "filter diffusion" + + // v3 + dt_iop_toneequalizer_version_t version; // $DEFAULT: DT_TONEEQ_VERSION_3 $DESCRIPTION: "module version" + dt_iop_toneequalizer_curve_t curve_type; // $DEFAULT: DT_TONEEQ_CURVE_GAUSS $DESCRIPTION: "curve type" + float post_scale_base; // $DEFAULT: 0.0f + float post_shift_base; // $DEFAULT: 0.0f + float post_scale; // $MIN: -3.0 $MAX: 3.0 $DEFAULT: 0.0 $DESCRIPTION: "mask contrast / scale histogram" + float post_shift; // $MIN: -8.0 $MAX: 8.0 $DEFAULT: 0.0 $DESCRIPTION: "mask brightness / shift histogram" + float post_pivot; // $MIN: -8.0 $MAX: 0.0 $DEFAULT: -4.0 $DESCRIPTION: "histogram scale pivot" + float global_exposure; // $MIN: -8.0 $MAX: 8.0 $DEFAULT: 0.0 $DESCRIPTION: "global exposure" + float scale_curve; // $MIN: -2.0 $MAX: 2.0 $DEFAULT: 1.0 $DESCRIPTION: "scale curve vertically" + float pre_contrast_width; // $MIN: 0.5 $MAX: 10.0 $DEFAULT: 5.0 $DESCRIPTION: "width" + float pre_contrast_strength; // $MIN: 0.0 $MAX: 0.1 $DEFAULT: 0.0 $DESCRIPTION: "strength" + float pre_contrast_midpoint; // $MIN: -8.0f $MAX: 0.0f $DEFAULT: -4.0f $DESCRIPTION: "midpoint" + float lum_estimator_R; // $MIN: -1.0 $MAX: 1.0 $DEFAULT: 0.33333 $DESCRIPTION: "red channel weight" + float lum_estimator_G; // $MIN: -1.0 $MAX: 1.0 $DEFAULT: 0.33333 $DESCRIPTION: "green channel weight" + float lum_estimator_B; // $MIN: -1.0 $MAX: 1.0 $DEFAULT: 0.33333 $DESCRIPTION: "blue channel weight" + gboolean lum_estimator_normalize; // $DEFAULT: TRUE $DESCRIPTION: "normalize RGB weights" } 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 gauss_factors[NUM_OCTAVES] DT_ALIGNED_ARRAY; + float catmull_y[NUM_SLIDERS+2] DT_ALIGNED_ARRAY; + float catmull_tangents[NUM_SLIDERS] DT_ALIGNED_ARRAY; float correction_lut[NUM_OCTAVES * LUT_RESOLUTION + 1] DT_ALIGNED_ARRAY; + float lut_min_ev, lut_max_ev; float blending, feathering, contrast_boost, exposure_boost, quantization, smoothing; + float post_scale_base, post_shift_base, post_scale, post_shift, post_pivot, global_exposure, scale_curve; + dt_iop_toneequalizer_curve_t curve_type; float scale; int radius; int iterations; - dt_iop_luminance_mask_method_t method; - dt_iop_toneequalizer_filter_t details; + dt_iop_luminance_mask_method_t lum_estimator; + float lum_estimator_R, lum_estimator_G, lum_estimator_B; + float pre_contrast_width, pre_contrast_strength, pre_contrast_midpoint; + dt_iop_toneequalizer_filter_t filter; } dt_iop_toneequalizer_data_t; @@ -207,51 +349,144 @@ 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_lut_t +{ + +} dt_iop_toneequalizer_lut_t; + +typedef struct dt_iop_toneequalizer_histogram_stats_t +{ + int samples[HDR_HISTO_SAMPLES] DT_ALIGNED_ARRAY; + unsigned int num_samples; + float min_ev; + float max_ev; + float lo_percentile_ev; + float hi_percentile_ev; +} dt_iop_toneequalizer_histogram_stats_t; + +static void _hdr_histo_init(dt_iop_toneequalizer_histogram_stats_t *histo) +{ + histo->num_samples = HDR_HISTO_SAMPLES; + histo->min_ev = HDR_MIN_EV; + histo->max_ev = HDR_MAX_EV; + histo->lo_percentile_ev = HDR_MIN_EV; + histo->hi_percentile_ev = HDR_MAX_EV; +} + +typedef struct dt_iop_toneequalizer_ui_histogram_t +{ + int samples[UI_HISTO_SAMPLES] DT_ALIGNED_ARRAY; + GdkRGBA curve_colors[UI_HISTO_SAMPLES] DT_ALIGNED_ARRAY; + unsigned int num_samples; + int max_val; + int max_val_ignore_border_bins; + float scsh_min_ev; // post scaled- and shifted version of min_ev + float scsh_max_ev; + float scsh_lo_percentile_ev; + float scsh_hi_percentile_ev; + +} dt_iop_toneequalizer_ui_histogram_t; + +static void _ui_histo_init(dt_iop_toneequalizer_ui_histogram_t *histo) +{ + histo->num_samples = UI_HISTO_SAMPLES; + histo->max_val = 1; + histo->max_val_ignore_border_bins = 1; + histo->scsh_min_ev = HDR_MIN_EV; // post scaled- and shifted version of min_ev + histo->scsh_max_ev = HDR_MAX_EV; + histo->scsh_lo_percentile_ev = HDR_MIN_EV; + histo->scsh_hi_percentile_ev = HDR_MAX_EV; +} typedef struct dt_iop_toneequalizer_gui_data_t { // Mem arrays 64-bytes 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 gauss_factors[NUM_OCTAVES] DT_ALIGNED_ARRAY; + float gauss_interpolation_matrix[NUM_SLIDERS * NUM_OCTAVES] DT_ALIGNED_ARRAY; + float catmull_y[NUM_SLIDERS+2] DT_ALIGNED_ARRAY; + float catmull_tangents[NUM_SLIDERS] DT_ALIGNED_ARRAY; + + float gui_curve[UI_HISTO_SAMPLES] DT_ALIGNED_ARRAY; // LUT for the UI graph + GdkRGBA gui_curve_colors[UI_HISTO_SAMPLES] DT_ALIGNED_ARRAY; // color for the UI graph + dt_iop_toneequalizer_histogram_stats_t mask_hdr_histo; // HDR mask histogram + dt_iop_toneequalizer_histogram_stats_t mask_hq_histo; // Mask histogram in HQ mode + dt_iop_toneequalizer_ui_histogram_t ui_histo; // Histogram for the UI graph + dt_iop_toneequalizer_ui_histogram_t ui_hq_histo; // HQ mode version of the UI histogram + + float prv_image_ev_min, prv_image_ev_max; + + float temp_user_params[NUM_SLIDERS] DT_ALIGNED_ARRAY; float cursor_exposure; // store the exposure value at current cursor position float step; // scrolling step // 14 int to pack - contiguous memory gboolean 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 - dt_hash_t ui_preview_hash; - dt_hash_t thumb_preview_hash; - size_t full_preview_buf_width, full_preview_buf_height; - size_t thumb_preview_buf_width, thumb_preview_buf_height; + dt_hash_t full_upstream_hash; + dt_hash_t preview_upstream_hash; + + size_t preview_buf_width, preview_buf_height; + size_t full_buf_width, full_buf_height; + int full_buf_x, full_buf_y; // top left corner of the main window + + // Heap arrays, 64 bits-aligned, unknown length + float *preview_buf; // For performance and to get the mask luminance under the mouse cursor + float *full_buf; // For performance and for displaying the mask as greyscale // Misc stuff, contiguity, length and alignment unknown + float image_EV_per_UI_sample; 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; + // automatic values for post scale/shift + float post_scale_value; + float post_shift_value; + + // Hash for synchronization between PREVIEW and FULL + // dt_hash_t sync_hash; + + // Drawing area flags + gboolean area_vscale; + gboolean area_ignore_border_bins; + gboolean warning_icon_active; // 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; + GtkDrawingArea *area; GtkNotebook *notebook; + + // Align Tab + GtkWidget *align_button; + GtkDrawingArea *warning_icon_area; + GtkLabel *label_base_shift, *label_base_scale; + GtkWidget *post_scale, *post_shift, *post_pivot; // New main mask alignment controls + GtkWidget *smoothing; // curve smoothing + + // Exposure Tab + GtkWidget *global_exposure, *scale_curve, *curve_type; + dt_gui_collapsible_section_t sliders_section; + GtkWidget *noise, *ultra_deep_blacks, *deep_blacks, *blacks, *shadows, *midtones, *highlights, *whites, *speculars; + + // Masking Tab + dt_gui_collapsible_section_t guided_filter_section; + GtkWidget *filter; + GtkWidget *iterations, *blending, *feathering; // Filter diffusion, smoothing diameter, edges refinement + + dt_gui_collapsible_section_t pre_processing_section; + GtkWidget *exposure_boost, *contrast_boost; // Exposure compensation, contrast compensation + GtkWidget *pre_contrast_width, *pre_contrast_strength, *pre_contrast_midpoint; // targeted mask contrast (pre-processing) + + dt_gui_collapsible_section_t lum_estimator_section; + GtkWidget *lum_estimator; + GtkWidget *lum_estimator_R, *lum_estimator_G, *lum_estimator_B, *lum_estimator_normalize; + + dt_gui_collapsible_section_t adv_section; + GtkWidget *quantization; + GtkWidget *version; // module version + GtkWidget *show_luminance_mask; // Cache Pango and Cairo stuff for the equalizer drawing @@ -259,6 +494,7 @@ typedef struct dt_iop_toneequalizer_gui_data_t float sign_width; float graph_width; float graph_height; + float graph_w_gradients_height; float gradient_left_limit; float gradient_right_limit; float gradient_top_limit; @@ -277,8 +513,8 @@ typedef struct dt_iop_toneequalizer_gui_data_t GtkStyleContext *context; // Event for equalizer drawing - float nodes_x[CHANNELS] DT_ALIGNED_ARRAY; - float nodes_y[CHANNELS] DT_ALIGNED_ARRAY; + float nodes_x[NUM_SLIDERS] DT_ALIGNED_ARRAY; + float nodes_y[NUM_SLIDERS] DT_ALIGNED_ARRAY; float area_x; // x coordinate of cursor over graph/drawing area float area_y; // y coordinate int area_active_node; @@ -294,23 +530,39 @@ typedef struct dt_iop_toneequalizer_gui_data_t gboolean has_focus; // TRUE if the widget has the focus from GTK // Flags for buffer caches invalidation - gboolean interpolation_valid; // TRUE if the interpolation_matrix is ready - gboolean luminance_valid; // TRUE if the luminance cache is ready - gboolean histogram_valid; // TRUE if the histogram cache and stats are ready - gboolean lut_valid; // TRUE if the gui_lut is ready + gboolean prv_luminance_valid; // TRUE if the preview luminance cache is ready, + // HDR_histogram and prv deciles are valid + gboolean full_luminance_valid;// TRUE if the full luminance cache is ready, + // full deciles are valid + + gboolean gui_histogram_valid; // TRUE if the histogram cache and stats are ready gboolean graph_valid; // TRUE if the UI graph view is ready + + // For the curve interpolation + gboolean interpolation_valid; // TRUE if the gauss_interpolation_matrix is ready + gboolean user_param_valid; // TRUE if users params set in // interactive view are in bounds - gboolean factors_valid; // TRUE if radial-basis coeffs are ready + gboolean gauss_factors_valid; // TRUE if radial-basis coeffs are ready + gboolean gui_curve_valid; // TRUE if the gui_curve is ready - gboolean distort_signal_actif; + gboolean distort_signal_active; } dt_iop_toneequalizer_gui_data_t; + /* the signal DT_SIGNAL_DEVELOP_DISTORT is used to refresh the internal cached image buffer used for the on-canvas luminance picker. */ static void _set_distort_signal(dt_iop_module_t *self); static void _unset_distort_signal(dt_iop_module_t *self); +/**************************************************************************** + * + * Darktable housekeeping functions + * + ****************************************************************************/ +// empty marker function to make navigating the function list easier +__attribute__((unused)) static void HOUSEKEEPING_FUNCTIONS_MARKER() {} + const char *name() { return _("tone equalizer"); @@ -321,7 +573,6 @@ const char *aliases() return _("tone curve|tone mapping|relight|background light|shadows highlights"); } - const char **description(dt_iop_module_t *self) { return dt_iop_set_description @@ -356,7 +607,11 @@ int legacy_params(dt_iop_module_t *self, int32_t *new_params_size, int *new_version) { - typedef struct dt_iop_toneequalizer_params_v2_t +#ifdef MF_DEBUG + printf("legacy_params old_version=%d\n", old_version); +#endif + + typedef struct dt_iop_toneequalizer_params_v3_t { float noise; float ultra_deep_blacks; @@ -373,10 +628,26 @@ int legacy_params(dt_iop_module_t *self, float quantization; float contrast_boost; float exposure_boost; - dt_iop_toneequalizer_filter_t details; - dt_iop_luminance_mask_method_t method; + dt_iop_toneequalizer_filter_t filter; + dt_iop_luminance_mask_method_t lum_estimator; int iterations; - } dt_iop_toneequalizer_params_v2_t; + dt_iop_toneequalizer_version_t version; + dt_iop_toneequalizer_curve_t curve_type; + float post_scale_base; + float post_shift_base; + float post_scale; + float post_shift; + float post_pivot; + float global_exposure; + float scale_curve; + float pre_contrast_width; + float pre_contrast_strength; + float pre_contrast_midpoint; + float lum_estimator_R; + float lum_estimator_G; + float lum_estimator_B; + gboolean lum_estimator_normalize; + } dt_iop_toneequalizer_params_v3_t; if(old_version == 1) { @@ -385,13 +656,13 @@ int legacy_params(dt_iop_module_t *self, float noise, ultra_deep_blacks, deep_blacks, blacks; float shadows, midtones, highlights, whites, speculars; float blending, feathering, contrast_boost, exposure_boost; - dt_iop_toneequalizer_filter_t details; + dt_iop_toneequalizer_filter_t filter; int iterations; - dt_iop_luminance_mask_method_t method; + dt_iop_luminance_mask_method_t lum_estimator; } dt_iop_toneequalizer_params_v1_t; const dt_iop_toneequalizer_params_v1_t *o = old_params; - dt_iop_toneequalizer_params_v2_t *n = malloc(sizeof(dt_iop_toneequalizer_params_v2_t)); + dt_iop_toneequalizer_params_v3_t *n = malloc(sizeof(dt_iop_toneequalizer_params_v3_t)); // Olds params n->noise = o->noise; @@ -409,23 +680,97 @@ int legacy_params(dt_iop_module_t *self, n->contrast_boost = o->contrast_boost; n->exposure_boost = o->exposure_boost; - n->details = o->details; + n->filter = o->filter; n->iterations = o->iterations; - n->method = o->method; + n->lum_estimator = o->lum_estimator; - // New params + // V2 params n->quantization = 0.0f; - n->smoothing = sqrtf(2.0f); + n->smoothing = 0.0f; + + // V3 params + n->version = 3; + n->curve_type = DT_TONEEQ_CURVE_GAUSS; + n->post_scale_base = 0.0f; + n->post_shift_base = 0.0f; + n->post_scale = 0.0f; + n->post_shift = 0.0f; + n->post_pivot = -4.0f; + n->global_exposure = 0.0f; + n->scale_curve = 1.0f; + n->pre_contrast_width = 5.0f; + n->pre_contrast_strength = 0.0f; + n->pre_contrast_midpoint = -4.0f; + n->lum_estimator_R = 1.0f / 3.0f; + n->lum_estimator_G = 1.0f / 3.0f; + n->lum_estimator_B = 1.0f / 3.0f; + n->lum_estimator_normalize = TRUE; + + *new_params = n; + *new_params_size = sizeof(dt_iop_toneequalizer_params_v3_t); + *new_version = 3; + return 0; + } + + if(old_version == 2) + { + typedef struct dt_iop_toneequalizer_params_v2_t + { + float noise; float ultra_deep_blacks; float deep_blacks; float blacks; + float shadows; float midtones; float highlights; float whites; + float speculars; float blending; float smoothing; float feathering; + float quantization; float contrast_boost; float exposure_boost; + dt_iop_toneequalizer_filter_t filter; + dt_iop_luminance_mask_method_t lum_estimator; + int iterations; + } dt_iop_toneequalizer_params_v2_t; + + const dt_iop_toneequalizer_params_v2_t *o = old_params; + dt_iop_toneequalizer_params_v3_t *n = malloc(sizeof(dt_iop_toneequalizer_params_v3_t)); + memcpy(n, o, sizeof(dt_iop_toneequalizer_params_v2_t)); + + // changed smoothing + // old smoothing was sigma with a range of 1...sqrt(2)...2 + // new smoothing is the displayed value of -1...0...1 + n->smoothing = logf(o->smoothing) / logf(sqrtf(2.0f)) - 1.0f; + + // V3 params + n->version = 3; + n->curve_type = DT_TONEEQ_CURVE_GAUSS; + n->post_scale_base = 0.0f; + n->post_shift_base = 0.0f; + n->post_scale = 0.0f; + n->post_shift = 0.0f; + n->post_pivot = -4.0f; + n->global_exposure = 0.0f; + n->scale_curve = 1.0f; + n->pre_contrast_width = 5.0f; + n->pre_contrast_strength = 0.0f; + n->pre_contrast_midpoint = -4.0f; + n->lum_estimator_R = 1.0f / 3.0f; + n->lum_estimator_G = 1.0f / 3.0f; + n->lum_estimator_B = 1.0f / 3.0f; + n->lum_estimator_normalize = TRUE; *new_params = n; - *new_params_size = sizeof(dt_iop_toneequalizer_params_v2_t); - *new_version = 2; + *new_params_size = sizeof(dt_iop_toneequalizer_params_v3_t); + *new_version = 3; return 0; } + return 1; } -static void compress_shadows_highlight_preset_set_exposure_params + +/**************************************************************************** + * + * Presets + * + ****************************************************************************/ +// empty marker function to make navigating the function list easier +__attribute__((unused)) static void PRESETS_MARKER() {} + +static void _compress_shadows_highlight_preset_set_exposure_params (dt_iop_toneequalizer_params_t* p, const float step) { @@ -443,8 +788,26 @@ static void compress_shadows_highlight_preset_set_exposure_params p->speculars = -step; } +static void _compress_shadows_highlight_linear_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 = 15.f / 9.f * step; + p->deep_blacks = 10.f / 9.f * step; + p->blacks = 5.f / 9.f * step; + p->shadows = 0.0f; + p->midtones = -5.f / 9.f * step; + p->highlights = -10.f / 9.f * step; + p->whites = -15.f / 9.f * step; + p->speculars = -step; +} + -static void dilate_shadows_highlight_preset_set_exposure_params +static void _dilate_shadows_highlight_preset_set_exposure_params (dt_iop_toneequalizer_params_t* p, const float step) { @@ -466,15 +829,34 @@ 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.lum_estimator = DT_TONEEQ_NORM_POWER; p.contrast_boost = 0.0f; - p.details = DT_TONEEQ_NONE; + p.filter = DT_TONEEQ_NONE; p.exposure_boost = -0.5f; p.feathering = 1.0f; p.iterations = 1; - p.smoothing = sqrtf(2.0f); + p.smoothing = 0.0f; p.quantization = 0.0f; + // V3 params + p.version = 3; + p.post_scale_base = 0.0f; + p.post_shift_base = 0.0f; + p.post_scale = 0.0f; + p.post_shift = 0.0f; + p.post_pivot = -4.0f; + p.global_exposure = 0.0f; + p.scale_curve = 1.0f; + p.pre_contrast_width = 1.0f; + p.pre_contrast_strength = 0.0f; + p.pre_contrast_midpoint = 0.0f; + p.curve_type = DT_TONEEQ_CURVE_GAUSS; + + p.lum_estimator_R = 1.0f / 3.0f; + p.lum_estimator_G = 1.0f / 3.0f; + p.lum_estimator_B = 1.0f / 3.0f; + p.lum_estimator_normalize = TRUE; + // Init exposure settings p.noise = p.ultra_deep_blacks = p.deep_blacks = p.blacks = 0.0f; p.shadows = p.midtones = p.highlights = p.whites = p. speculars = 0.0f; @@ -485,8 +867,8 @@ void init_presets(dt_iop_module_so_t *self) self->version(), &p, sizeof(p), 1, DEVELOP_BLEND_CS_RGB_SCENE); // Simple utils blendings - p.details = DT_TONEEQ_EIGF; - p.method = DT_TONEEQ_NORM_2; + p.filter = DT_TONEEQ_EIGF; + p.lum_estimator = DT_TONEEQ_NORM_2; p.blending = 5.0f; p.feathering = 1.0f; @@ -514,67 +896,94 @@ void init_presets(dt_iop_module_so_t *self) p.iterations = 5; p.quantization = 0.0f; + // Modified names to gentle / medium / strong, so the alphabetical + // sort order matches the order of strengths. + // slight modification to give higher compression - p.details = DT_TONEEQ_EIGF; + p.filter = DT_TONEEQ_EIGF; p.feathering = 20.0f; - compress_shadows_highlight_preset_set_exposure_params(&p, 0.65f); + _compress_shadows_highlight_preset_set_exposure_params(&p, 0.65f); dt_gui_presets_add_generic - (_("compress shadows/highlights | EIGF | strong"), self->op, + (_("compress shadows/highlights | classic EIGF | strong"), self->op, self->version(), &p, sizeof(p), 1, DEVELOP_BLEND_CS_RGB_SCENE); - p.details = DT_TONEEQ_GUIDED; + p.filter = DT_TONEEQ_GUIDED; p.feathering = 500.0f; dt_gui_presets_add_generic - (_("compress shadows/highlights | GF | strong"), self->op, + (_("compress shadows/highlights | classic GF | strong"), self->op, self->version(), &p, sizeof(p), 1, DEVELOP_BLEND_CS_RGB_SCENE); - p.details = DT_TONEEQ_EIGF; + p.filter = DT_TONEEQ_EIGF; p.blending = 3.0f; p.feathering = 7.0f; p.iterations = 3; - compress_shadows_highlight_preset_set_exposure_params(&p, 0.45f); + _compress_shadows_highlight_preset_set_exposure_params(&p, 0.45f); dt_gui_presets_add_generic - (_("compress shadows/highlights | EIGF | medium"), self->op, + (_("compress shadows/highlights | classic EIGF | medium"), self->op, self->version(), &p, sizeof(p), 1, DEVELOP_BLEND_CS_RGB_SCENE); - p.details = DT_TONEEQ_GUIDED; + p.filter = DT_TONEEQ_GUIDED; p.feathering = 500.0f; dt_gui_presets_add_generic - (_("compress shadows/highlights | GF | medium"), self->op, + (_("compress shadows/highlights | classic GF | medium"), self->op, self->version(), &p, sizeof(p), 1, DEVELOP_BLEND_CS_RGB_SCENE); - p.details = DT_TONEEQ_EIGF; + p.filter = DT_TONEEQ_EIGF; p.blending = 5.0f; p.feathering = 1.0f; p.iterations = 1; - compress_shadows_highlight_preset_set_exposure_params(&p, 0.25f); + _compress_shadows_highlight_preset_set_exposure_params(&p, 0.25f); dt_gui_presets_add_generic - (_("compress shadows/highlights | EIGF | soft"), self->op, + (_("compress shadows/highlights | classic EIGF | gentle"), self->op, self->version(), &p, sizeof(p), 1, DEVELOP_BLEND_CS_RGB_SCENE); - p.details = DT_TONEEQ_GUIDED; + p.filter = DT_TONEEQ_GUIDED; p.feathering = 500.0f; dt_gui_presets_add_generic - (_("compress shadows/highlights | GF | soft"), self->op, + (_("compress shadows/highlights | classic GF | gentle"), self->op, + self->version(), &p, sizeof(p), 1, DEVELOP_BLEND_CS_RGB_SCENE); + + // New compress shadows & highlights with a more linear curve + p.filter = DT_TONEEQ_EIGF; + p.feathering = 20.0f; + _compress_shadows_highlight_linear_preset_set_exposure_params(&p, 0.65f); + dt_gui_presets_add_generic + (_("compress shadows/highlights | v3 EIGF | strong"), self->op, + self->version(), &p, sizeof(p), 1, DEVELOP_BLEND_CS_RGB_SCENE); + + p.blending = 3.0f; + p.feathering = 7.0f; + p.iterations = 3; + _compress_shadows_highlight_linear_preset_set_exposure_params(&p, 0.45f); + dt_gui_presets_add_generic + (_("compress shadows/highlights | v3 EIGF | medium"), self->op, + self->version(), &p, sizeof(p), 1, DEVELOP_BLEND_CS_RGB_SCENE); + + p.blending = 5.0f; + p.feathering = 1.0f; + p.iterations = 1; + _compress_shadows_highlight_linear_preset_set_exposure_params(&p, 0.25f); + dt_gui_presets_add_generic + (_("compress shadows/highlights | v3 EIGF | gentle"), self->op, self->version(), &p, sizeof(p), 1, DEVELOP_BLEND_CS_RGB_SCENE); // 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); + p.filter = DT_TONEEQ_NONE; + _dilate_shadows_highlight_preset_set_exposure_params(&p, 0.25f); dt_gui_presets_add_generic - (_("contrast tone curve | soft"), self->op, + (_("contrast tone curve | gentle"), self->op, self->version(), &p, sizeof(p), 1, DEVELOP_BLEND_CS_RGB_SCENE); - dilate_shadows_highlight_preset_set_exposure_params(&p, 0.45f); + _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_SCENE); - dilate_shadows_highlight_preset_set_exposure_params(&p, 0.65f); + _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_SCENE); // relight - p.details = DT_TONEEQ_EIGF; + p.filter = DT_TONEEQ_EIGF; p.blending = 5.0f; p.feathering = 1.0f; p.iterations = 1; @@ -598,283 +1007,218 @@ void init_presets(dt_iop_module_so_t *self) } -/** - * 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; -} +/**************************************************************************** + * + * Functions that are needed by process and therefore + * are part of worker threads + * + ****************************************************************************/ +// empty marker function to make navigating the function list easier +__attribute__((unused)) static void PROCESS_DEPENDENCIES_MARKER() {} -static void hash_set_get(const dt_hash_t *hash_in, - dt_hash_t *hash_out, - dt_pthread_mutex_t *lock) +__DT_CLONE_TARGETS__ +static inline void _compute_min_max_ev(const float *const restrict luminance, + const size_t num_elem, + float *min_ev, + float *max_ev) { - // 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); -} + float min_lum = INFINITY; + float max_lum = -INFINITY; + DT_OMP_FOR_SIMD(reduction(min:min_lum) reduction(max:max_lum)) + for(size_t k = 0; k < num_elem; k++) + { + min_lum = MIN(min_lum, luminance[k]); + max_lum = MAX(max_lum, luminance[k]); + } -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 = self->gui_data; - - dt_iop_gui_enter_critical_section(self); - g->max_histogram = 1; - g->luminance_valid = FALSE; - g->histogram_valid = FALSE; - g->thumb_preview_hash = DT_INVALID_HASH; - g->ui_preview_hash = DT_INVALID_HASH; - dt_iop_gui_leave_critical_section(self); - dt_iop_refresh_all(self); + *min_ev = log2f(min_lum); + *max_ev = log2f(max_lum); } -// 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) +static inline void _compute_hdr_histogram_and_stats(const float *const restrict luminance, + const size_t num_elem, + dt_iop_toneequalizer_histogram_stats_t *histo, + dt_dev_pixelpipe_type_t const debug_pipe) { - // 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 + // This expects histo to be pre-polulated with min_ev and max_ev - float luminance = 0.0f; - if(x > 1 && 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; - } + // The GUI histogram comprises 8 EV (UI_HISTO_SAMPLES, -8 to 0). + // The high resolution histogram extends this to an exta 8 EV before and + // 8EV after, for a total of 24. + // Also the resolution is increased to compensate for the fact that the user + // can scale the histogram. + const float temp_ev_range = histo->max_ev - histo->min_ev; - 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 + // (Re)init the histogram + int* samples = histo->samples; + memset(samples, 0, sizeof(int) * histo->num_samples); - // convolution - for(int i = 0; i < 3; ++i) + // Split exposure in bins + DT_OMP_FOR_SIMD(reduction(+:samples[:histo->num_samples])) + for(size_t k = 0; k < num_elem; k++) { - const size_t y_i = y_abs[i]; - for_each_channel(j) - luminance += buffer[width * y_i + x_abs[j]] * gauss_kernel[i][j]; + const int index = + CLAMP((int)(((log2f(luminance[k]) - histo->min_ev) / temp_ev_range) * (float)histo->num_samples), + 0, histo->num_samples - 1); + samples[index] += 1; } - return luminance; -} - -static void _get_point(dt_iop_module_t *self, - const int c_x, - const int c_y, - int *x, - int *y) -{ - // TODO: For this to fully work non depending on the place of the module - // in the pipe we need a dt_dev_distort_backtransform_plus that - // can skip crop only. With the current version if toneequalizer - // is moved below rotation & perspective it will fail as we are - // then missing all the transform after tone-eq. - const double crop_order = - dt_ioppr_get_iop_order(self->dev->iop_order_list, "crop", 0); - - float pts[2] = { c_x, c_y }; - // only a forward backtransform as the buffer already contains all the transforms - // done before toneequal and we are speaking of on-screen cursor coordinates. - // also we do transform only after crop as crop does change roi for the whole pipe - // and so it is already part of the preview buffer cached in this implementation. - dt_dev_distort_backtransform_plus(darktable.develop, darktable.develop->preview_pipe, - crop_order, - DT_DEV_TRANSFORM_DIR_FORW_EXCL, pts, 1); - *x = pts[0]; - *y = pts[1]; -} + const int low_percentile_pop = (int)((float)num_elem * 0.05f); + const int high_percentile_pop = (int)((float)num_elem * (1.0f - 0.95f)); -static float _luminance_from_module_buffer(dt_iop_module_t *self) -{ - dt_iop_toneequalizer_gui_data_t *g = self->gui_data; + int low_percentile_pos = 0; + int high_percentile_pos = 0; - const size_t c_x = g->cursor_pos_x; - const size_t c_y = g->cursor_pos_y; + // Scout the extended histogram bins looking for deciles. + // These would not be accurate with the gui histogram. + DT_OMP_PRAGMA(parallel sections) + { + DT_OMP_PRAGMA(section) + { + int population = 0; + for(int k=0; k < histo->num_samples; ++k) + { + population += samples[k]; + if(population >= low_percentile_pop) + { + low_percentile_pos = k; + break; + } + } + } - // get buffer x,y given the cursor position - int b_x = 0; - int b_y = 0; + DT_OMP_PRAGMA(section) + { + int population = 0; + for(int k = histo->num_samples; k >= 0; --k) + { + population += samples[k]; + if(population >= high_percentile_pop) + { + high_percentile_pos = k; + break; + } + } + } + } - _get_point(self, c_x, c_y, &b_x, &b_y); + // Convert positions to exposures + histo->lo_percentile_ev = (temp_ev_range * ((float)low_percentile_pos / (float)(histo->num_samples - 1))) + histo->min_ev; + histo->hi_percentile_ev = (temp_ev_range * ((float)high_percentile_pos / (float)(histo->num_samples - 1))) + histo->min_ev; - return get_luminance_from_buffer(g->thumb_preview_buf, - g->thumb_preview_buf_width, - g->thumb_preview_buf_height, - b_x, - b_y); + printf("_compute_hdr_histogram_and_stats: pipe=%d, histo->min_ev=%f, histo->max_ev=%f, lo_percentile_ev=%f, hi_percentile_ev=%f\n", debug_pipe, histo->min_ev, histo->max_ev, histo->lo_percentile_ev, histo->hi_percentile_ev); } -/*** - * 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) - * - ***/ - -DT_OMP_DECLARE_SIMD() __DT_CLONE_TARGETS__ -static float gaussian_denom(const float sigma) +static inline void _compute_targeted_contrast(float *const restrict image, + const size_t width, + const size_t height, + const float pre_contrast_width, + const float pre_contrast_strength, + const float pre_contrast_midpoint + ) { - // 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; -} - + // Apply an s-shaped curve centered around x_0 + // The currently used curve is + // f(x)=x\ +\tanh(k\cdot(x-x_{0}))\cdot e^{-b\cdot(x-x_{0})^{2}} + // logically this should be a logarithmic curve. We are in linear space, + // but brightness perception is logarithmic, which is why the S shape + // should be smaller near 0 and get bigger with increasing x. + // I tried the following option, but it was worse: + // f(x)=x+a\cdot\tanh(k\cdot\log(x/x_{0}))\cdot e^{-b\cdot(\log\left(x/x_{0}\right))^{2}} + + // don't do anything if strength is zero + if (fabsf(pre_contrast_strength) < 0.00001f) + return; -DT_OMP_DECLARE_SIMD() -__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); + const size_t num_elem = width * height; + const float log_x_0 = pre_contrast_midpoint; + const float b = pre_contrast_width; + // const float k = exp2f(pre_contrast_strength); + // const float x0 = pre_contrast_midpoint; + const float k = pre_contrast_strength; + // const float b = pre_contrast_width; + + DT_OMP_FOR_SIMD() + for (size_t i = 0; i < num_elem; i++) { + // const float log_x = log2f(image[i]); + + // // The term inside the tanh and exp functions + // const float log_ratio = log_x - log_x_0; + // const float log_ratio_sq = log_ratio * log_ratio; + const float x = image[i]; + const float x_diff = log2f(image[i]) - log_x_0; + + // The full computation + const float term = (tanh(k * x_diff) * exp(-b * x_diff * x_diff)); + + image[i] = image[i] + term; + if (i % 100000 == 0) { + // printf("_compute_targeted_contrast: i=%ld, x=%f, log_x=%f, log_ratio=%f, term=%f, result=%f\n", + // i, image[i], log_x, log_ratio, term, image[i]); + printf("_compute_targeted_contrast: i=%ld, x=%f, log2(x)=%f, log_x_0=%f, k=%f, b=%f, x_diff=%f, tanh=%f, exp=%f, log_term=%f, term=%f, result=%f\n", + i, x, log2f(x), log_x_0, k, b, x_diff, tanh(k * x_diff), exp(-b * x_diff * x_diff), log2f(term), term, image[i]); + } + } } -#define DT_TONEEQ_MIN_EV (-8.0f) -#define DT_TONEEQ_MAX_EV (0.0f) -#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 dt_iop_toneequalizer_data_t *const d) +static inline void _compute_luminance_mask(const float *const restrict in, + float *const restrict luminance, + const size_t width, + const size_t height, + const dt_iop_toneequalizer_data_t *const d, + float *image_min_lum, + float *image_max_lum, + dt_dev_pixelpipe_type_t const debug_pipe) { - const size_t npixels = (size_t)roi_in->width * roi_in->height; - const float* restrict lut = d->correction_lut; - const float lutres = LUT_RESOLUTION; +#ifdef MF_DEBUG + printf("_compute_luminance_mask pipe=%d width=%ld height=%ld first luminance=%f estimator=%d " + "exposure_boost=%f contrast_boost=%f radius=%d feathering=%f iterations=%d scale=%f quantization=%f\n", + debug_pipe, width, height, luminance[0], d->lum_estimator, + d->exposure_boost, d->contrast_boost, d->radius, d->feathering, + d->iterations, d->scale, d->quantization); +#endif - DT_OMP_FOR() - for(size_t k = 0; k < npixels; k++) - { - // The radial-basis interpolation is valid in [-8; 0] EV and can quickly diverge outside. - // Note: not doing an explicit lut[index] check is safe as long we take care of proper - // DT_TONEEQ_MIN_EV and DT_TONEEQ_MAX_EV and allocated lut size LUT_RESOLUTION+1 - const float exposure = fast_clamp(log2f(luminance[k]), DT_TONEEQ_MIN_EV, DT_TONEEQ_MAX_EV); - const float correction = lut[(unsigned)roundf((exposure - DT_TONEEQ_MIN_EV) * lutres)]; - // apply correction - for_each_channel(c) - out[4 * k + c] = correction * in[4 * k + 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 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); - - DT_OMP_FOR(shared(centers_ops)) - 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]), DT_TONEEQ_MIN_EV, DT_TONEEQ_MAX_EV); - - DT_OMP_SIMD(aligned(luminance, centers_ops, factors:64) safelen(PIXEL_CHAN) reduction(+:result)) - 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 - const float correction = fast_clamp(result, 0.25f, 4.0f); - - // apply correction - for_each_channel(c) - out[4 * k + c] = correction * in[4 * k + 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, DT_TONEEQ_MIN_EV, DT_TONEEQ_MAX_EV); - - DT_OMP_SIMD(aligned(centers_ops, factors:64) safelen(PIXEL_CHAN) reduction(+:result)) - 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 dt_iop_toneequalizer_data_t *const d) -{ - switch(d->details) +// TODO MF: +// - convert to greyscale (luminance_mask.h) +// - custom luminance estimator to mix RGB +// - calculate min_ev and max_ev in the process +// (used for LUT size and for curve warnings) +// - Calculate the LUT +// - combine the tanh function with the normal exposure boost +// and linear contrast +// - no matter the GF type! +// - apply the LUT +// - run guided filter +// - calculate fask_min_ev and mask_max_ev +// - calculate histogram (mask_min_ev to mask_max_ev) of the result if pipe is preview (UI) +// - calculate the final LUT (max(-8, mask_min_ev) to min(0,mask_max_ev) in every pipe +// - apply final LUT +// +// New histogram calculation: +// - min ev and max ev are input parameters instead of being calculated in the process +// - percentile calculation is a separate function + // const int num_elem = width * height; + + switch(d->filter) { case(DT_TONEEQ_NONE): { // No contrast boost here luminance_mask(in, luminance, width, height, - d->method, d->exposure_boost, 0.0f, 1.0f); + d->lum_estimator, d->exposure_boost, 0.0f, 1.0f, + d->lum_estimator_R, d->lum_estimator_G, d->lum_estimator_B, + image_min_lum, image_max_lum); + printf("pre_contrast_strength=%f pre_contrast_width=%f pre_contrast_midpoint=%f\n", + d->pre_contrast_strength, d->pre_contrast_width, d->pre_contrast_midpoint); + _compute_targeted_contrast(luminance, width, height, + d->pre_contrast_width, + d->pre_contrast_strength, + d->pre_contrast_midpoint); break; } @@ -882,7 +1226,15 @@ static inline void compute_luminance_mask(const float *const restrict in, { // Still no contrast boost luminance_mask(in, luminance, width, height, - d->method, d->exposure_boost, 0.0f, 1.0f); + d->lum_estimator, d->exposure_boost, 0.0f, 1.0f, + d->lum_estimator_R, d->lum_estimator_G, d->lum_estimator_B, + image_min_lum, image_max_lum); + printf("pre_contrast_strength=%f pre_contrast_width=%f pre_contrast_midpoint=%f\n", + d->pre_contrast_strength, d->pre_contrast_width, d->pre_contrast_midpoint); + _compute_targeted_contrast(luminance, width, height, + d->pre_contrast_width, + d->pre_contrast_strength, + d->pre_contrast_midpoint); 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); @@ -893,13 +1245,21 @@ static inline void compute_luminance_mask(const float *const restrict in, { // 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 + // the dynamic range along all exposure NUM_SLIDERS, because guided filters // tend to flatten the luminance mask a lot around an average ± 2 EV - // which makes only 2-3 channels usable. + // which makes only 2-3 NUM_SLIDERS 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, d->method, d->exposure_boost, - CONTRAST_FULCRUM, d->contrast_boost); + luminance_mask(in, luminance, width, height, d->lum_estimator, d->exposure_boost, + CONTRAST_FULCRUM, d->contrast_boost, + d->lum_estimator_R, d->lum_estimator_G, d->lum_estimator_B, + image_min_lum, image_max_lum); + printf("pre_contrast_strength=%f pre_contrast_width=%f pre_contrast_midpoint=%f\n", + d->pre_contrast_strength, d->pre_contrast_width, d->pre_contrast_midpoint); + _compute_targeted_contrast(luminance, width, height, + d->pre_contrast_width, + d->pre_contrast_strength, + d->pre_contrast_midpoint); 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); @@ -910,7 +1270,15 @@ static inline void compute_luminance_mask(const float *const restrict in, { // Still no contrast boost luminance_mask(in, luminance, width, height, - d->method, d->exposure_boost, 0.0f, 1.0f); + d->lum_estimator, d->exposure_boost, 0.0f, 1.0f, + d->lum_estimator_R, d->lum_estimator_G, d->lum_estimator_B, + image_min_lum, image_max_lum); + printf("pre_contrast_strength=%f pre_contrast_width=%f pre_contrast_midpoint=%f\n", + d->pre_contrast_strength, d->pre_contrast_width, d->pre_contrast_midpoint); + _compute_targeted_contrast(luminance, width, height, + d->pre_contrast_width, + d->pre_contrast_strength, + d->pre_contrast_midpoint); fast_eigf_surface_blur(luminance, width, height, d->radius, d->feathering, d->iterations, DT_GF_BLENDING_GEOMEAN, d->scale, @@ -920,8 +1288,18 @@ static inline void compute_luminance_mask(const float *const restrict in, case(DT_TONEEQ_EIGF): { - luminance_mask(in, luminance, width, height, d->method, d->exposure_boost, - CONTRAST_FULCRUM, d->contrast_boost); + luminance_mask(in, luminance, width, height, d->lum_estimator, d->exposure_boost, + CONTRAST_FULCRUM, d->contrast_boost, + d->lum_estimator_R, d->lum_estimator_G, d->lum_estimator_B, + image_min_lum, image_max_lum); + + printf("pre_contrast_strength=%f pre_contrast_width=%f pre_contrast_midpoint=%f\n", + d->pre_contrast_strength, d->pre_contrast_width, d->pre_contrast_midpoint); + _compute_targeted_contrast(luminance, width, height, + d->pre_contrast_width, + d->pre_contrast_strength, + d->pre_contrast_midpoint); + fast_eigf_surface_blur(luminance, width, height, d->radius, d->feathering, d->iterations, DT_GF_BLENDING_LINEAR, d->scale, @@ -932,26 +1310,80 @@ static inline void compute_luminance_mask(const float *const restrict in, default: { luminance_mask(in, luminance, width, height, - d->method, d->exposure_boost, 0.0f, 1.0f); + d->lum_estimator, d->exposure_boost, 0.0f, 1.0f, + d->lum_estimator_R, d->lum_estimator_G, d->lum_estimator_B, + image_min_lum, image_max_lum); + printf("pre_contrast_strength=%f pre_contrast_width=%f pre_contrast_midpoint=%f\n", + d->pre_contrast_strength, d->pre_contrast_width, d->pre_contrast_midpoint); + _compute_targeted_contrast(luminance, width, height, + d->pre_contrast_width, + d->pre_contrast_strength, + d->pre_contrast_midpoint); break; } } } -/*** - * Actual transfer functions - **/ +// This is similar to exposure/contrast boost. +// However it is applied AFTER the guided filter calculation, so it is much +// easier to control and does not mess with the detail detection of the +// guided filter. +// Note: Scaling is stored logarithmically in p for UI, but +// this function needs the linear version (i.e. from d)! + DT_OMP_DECLARE_SIMD() +__DT_CLONE_TARGETS__ +static inline float _post_scale_shift(const float v, + const float post_scale_base, + const float post_shift_base, + const float post_scale, + const float post_shift, + const float post_pivot) +{ + + // const float scale_exp = exp2f(post_scale); + // signifficant range -8..0, centering around the middle + const float base_aligned = (v * post_scale_base) + post_shift_base; + return ((base_aligned - post_pivot) * post_scale) + post_pivot + post_shift; +} +DT_OMP_DECLARE_SIMD() __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) +static inline float _inverse_post_scale_shift(const float v, + const float post_scale_base, + const float post_shift_base, + const float post_scale, + const float post_shift, + const float post_pivot) +{ + const float base_aligned = ((v - post_pivot - post_shift) / post_scale) + post_pivot; + return (base_aligned - post_shift_base) / post_scale_base; +} + + +__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 float post_scale_base, + const float post_shift_base, + const float post_scale, + const float post_shift, + const float post_pivot, + dt_dev_pixelpipe_type_t const debug_pipe) { 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; +#ifdef MF_DEBUG + printf("display_luminance_mask pipe=%d offset_x=%ld offset_y=%ld roi_in %d %d %d %d roi_out %d %d %d %d, post_scale=%f, post_shift=%f\n", + debug_pipe, offset_x, offset_y, + roi_in->x, roi_in->y, roi_in->width, roi_in->height, + roi_out->x, roi_out->y, roi_out->width, roi_out->height, + post_scale, post_shift); +#endif + // 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 @@ -970,11 +1402,21 @@ static inline void display_luminance_mask(const float *const restrict in, { // normalize the mask intensity between -8 EV and 0 EV for clarity, // and add a "gamma" 2.0 for better legibility in shadows + const int lum_index = (i + offset_y) * in_width + (j + offset_x); + const float lum_log = log2f(luminance[lum_index]); + const float lum_corrected = _post_scale_shift(lum_log, post_scale_base, post_shift_base, post_scale, post_shift, post_pivot); + + // IMHO it would be fine, to show the log version of the mask to the user. + // const float intensity = + // fminf(fmaxf((lum_corrected + 8.0f) / 8.0f, 0.f), 1.f); + // However to keep everything identical to before, we go back to linear + // space and apply the square root/"gamma". + const float lum_linear = exp2f(lum_corrected); const float intensity = sqrtf(fminf( - fmaxf(luminance[(i + offset_y) * in_width + (j + offset_x)] - 0.00390625f, - 0.f) / 0.99609375f, + fmaxf(lum_linear - 0.00390625f, 0.f) / 0.99609375f, 1.f)); + const size_t index = (i * out_width + j) * 4; // set gray level for the mask for_each_channel(c,aligned(out)) @@ -986,219 +1428,765 @@ static inline void display_luminance_mask(const float *const restrict in, } } +/*** + * Exposure compensation computation + * + * Construct the final correction factor by summing the octaves + * NUM_SLIDERS gains weighted by the gaussian of the radial distance + * (pixel exposure - octave center) + * + ***/ +DT_OMP_DECLARE_SIMD() +__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; +} + +DT_OMP_DECLARE_SIMD() +__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); +} + +// This assumes "ghost points", an extra point in the beginning and an extra +// point in the end, that are used for tangent calcculation but don't need +// tangents themselves. +DT_OMP_DECLARE_SIMD() +__DT_CLONE_TARGETS__ +#pragma omp declare simd +static inline void catmull_rom_tangents(const float y[NUM_SLIDERS+2], float tangents[NUM_SLIDERS], const float tangent_scale) { + + const float scale = fabsf(tangent_scale) * 2.0f; + + DT_OMP_FOR_SIMD(aligned(y, tangents:64)) + for (int i = 1; i <= NUM_SLIDERS; i++) { + tangents[i - 1] = ((y[i + 1] - y[i - 1]) / 2.0f) * scale; + } +} + + +// TODO MF: Similar to curve_tools.c catmull_rom_val, but with OpenMP +DT_OMP_DECLARE_SIMD() +__DT_CLONE_TARGETS__ +float catmull_rom_val(const int n, const float start_x, const float xval, const float y[NUM_SLIDERS+2], const float tangents[NUM_SLIDERS]) { + assert(xval >= start_x); + assert(xval <= start_x + n - 1); + + const int ival = (int)(xval - start_x); + + const float m0 = tangents[ival]; + const float m1 = tangents[ival + 1]; + + const float dx = (xval - (float)(start_x + ival)); + const float dx2 = dx * dx; + const float dx3 = dx * dx2; + + const float h00 = (2.0f * dx3) - (3.0f * dx2) + 1.0f; + const float h10 = (1.0f * dx3) - (2.0f * dx2) + dx; + const float h01 = (-2.0f * dx3) + (3.0f * dx2); + const float h11 = (1.0f * dx3) - (1.0f * dx2); + + return (h00 * y[ival + 1]) + + (h10 * m0) + + (h01 * y[ival + 2]) + + (h11 * m1); +} + +static void _compute_correction_lut(dt_iop_toneequalizer_data_t *const d, + dt_dev_pixelpipe_type_t const debug_pipe, + const float debug_first_decile, const float debug_last_decile + ) +{ +#ifdef MF_DEBUG + // printf("_compute_correction_lut pipe=%d, post_scale=%f, post_shift=%f\n", debug_pipe, post_scale, post_shift); +#endif + + // The LUT only needs to be calculated for the -8 to 0 graph EV range + d->lut_min_ev = _inverse_post_scale_shift(-8.0f, d->post_scale_base, d->post_shift_base, d->post_scale, d->post_shift, d->post_pivot); + d->lut_max_ev = _inverse_post_scale_shift(0.0f, d->post_scale_base, d->post_shift_base, d->post_scale, d->post_shift, d->post_pivot); + // printf("_compute_correction_lut: lut_min_ev=%f lut_max_ev=%f\n", d->lut_min_ev, d->lut_max_ev); + + // float lut_range_ev = d->lut_max_ev - d->lut_min_ev; + unsigned int lut_max_index = LUT_RESOLUTION * NUM_OCTAVES; // the array has space for 0...max (inclusive) + //printf("_compute_correction_lut: lut_min_ev=%f lut_max_ev=%f lut_range_ev=%f real_ev_per_octave=%f\n", d->lut_min_ev, d->lut_max_ev, lut_range_ev, real_ev_per_octave); + + const float sigma = powf(sqrtf(2.0f), 1.0f + d->smoothing); + const float gauss_denom = _gaussian_denom(sigma); + const float global_exposure_exp = exp2f(d->global_exposure); + + if (d->curve_type == DT_TONEEQ_CURVE_GAUSS) { + float* gauss_factors = d->gauss_factors; + DT_OMP_FOR_SIMD(shared(centers_ops) aligned(centers_ops, gauss_factors:64)) + for(int j = 0; j <= lut_max_index; j++) + { + // build the correction for each pixel + // as the sum of the contribution of each luminance channelcorrection + + // 0..1 (inclusive) + const float normalized = (float)j / (float)(lut_max_index); + + // -8..0 (inclusive) + const float exposure = normalized * NUM_OCTAVES + DT_TONEEQ_MIN_EV; + + float result = 0.0f; + + DT_OMP_SIMD(safelen(NUM_OCTAVES) reduction(+:result)) + for(int i = 0; i < NUM_OCTAVES; i++) + { + result += _gaussian_func(exposure - centers_ops[i], gauss_denom) * gauss_factors[i]; + } + + // if (j % 1000 == 0) + // { + // printf("_compute_correction_lut/GAUSS: j=%d, normalized=%f, exposure=%f, result=%f\n", + // j, normalized, exposure, result); + // } + + // the user-set correction is expected in [-2;+2] EV, so is the interpolated one + d->correction_lut[j] = fast_clamp(pow(result, d->scale_curve), 0.25f, 4.0f) * global_exposure_exp; + } + } + else + { + float* catmull_y = d->catmull_y; + float* catmull_tangents = d->catmull_tangents; + DT_OMP_FOR_SIMD(shared(centers_ops) aligned(centers_ops, catmull_y, catmull_tangents:64)) + for(int j = 0; j <= lut_max_index; j++) + { + // build the correction for each pixel + // as the sum of the contribution of each luminance channelcorrection + + // 0..1 (inclusive) + const float normalized = (float)j / (float)(lut_max_index); + + // -8..0 (inclusive) + const float exposure = normalized * NUM_OCTAVES + DT_TONEEQ_MIN_EV; + + float result = catmull_rom_val(NUM_SLIDERS, DT_TONEEQ_MIN_EV, exposure, catmull_y, catmull_tangents); + + // if (j % 1000 == 0) + // { + // printf("_compute_correction_lut/CATMULL: j=%d, normalized=%f, exposure=%f, result=%f, catmull_y=%f %f %f %f %f %f %f %f %f %f %f catmull_tangents=%f %f %f %f %f %f %f %f %f \n", + // j, normalized, exposure, result, catmull_y[0], catmull_y[1], catmull_y[2], catmull_y[3], catmull_y[4], catmull_y[5], catmull_y[6], catmull_y[7], catmull_y[8], catmull_y[9], catmull_y[10], + // catmull_tangents[0], catmull_tangents[1], catmull_tangents[2], catmull_tangents[3], catmull_tangents[4], catmull_tangents[5], catmull_tangents[6], catmull_tangents[7], catmull_tangents[8]); + // } + + // the user-set correction is expected in [-2;+2] EV, so is the interpolated one + d->correction_lut[j] = fast_clamp(pow(result, d->scale_curve), 0.25f, 4.0f) * global_exposure_exp; + } + } + +#ifdef MF_DEBUG + if (!isnan(debug_first_decile)) + { + float values[49]; + for(int j = 0; j <= 2 * LUT_OCTAVES; j++) + { + values[j] = log2f(lut[j * (int)(LUT_RESOLUTION/2)]); + } + plot_ascii(values, debug_first_decile, debug_last_decile); + } +#endif +} +// this is the version currently used, as using a lut gives a +// big performance speedup on some cpus +__DT_CLONE_TARGETS__ +__attribute__((unused)) 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_toneequalizer_data_t *const d, + dt_dev_pixelpipe_type_t const debug_pipe) +{ + + + // printf("_apply_toneequalizer pipe=%d first luminance=%f roi_in %d %d %d %d roi_out %d %d %d %d post_scale=%f, post_shift=%f\n", + // debug_pipe, luminance[0], + // roi_in->x, roi_in->y, roi_in->width, roi_in->height, + // roi_out->x, roi_out->y, roi_out->width, roi_out->height, + // d->post_scale, d->post_shift); + + const size_t npixels = (size_t)roi_in->width * roi_in->height; + const float* restrict lut = d->correction_lut; + + float lut_range_ev = d->lut_max_ev - d->lut_min_ev; + float lut_max_index = LUT_RESOLUTION * NUM_OCTAVES; + + // printf("_apply_toneequalizer: lut_min_ev=%f lut_max_ev=%f lut_range_ev=%f\n", + // d->lut_min_ev, d->lut_max_ev, lut_range_ev); + + DT_OMP_FOR() + for(size_t k = 0; k < npixels; k++) + { + // The radial-basis interpolation is valid in [-8; 0] EV and can quickly diverge outside. + // Note: not doing an explicit lut[index] check is safe as long we take care of proper + // DT_TONEEQ_MIN_EV and DT_TONEEQ_MAX_EV and allocated lut size LUT_RESOLUTION+1 + + // lut_min_ev to (including) lut_max_ev + const float exposure = fast_clamp(log2f(luminance[k]), d->lut_min_ev, d->lut_max_ev); + + // 0.0 to (including) 1.0 + const float normalized = (exposure - d->lut_min_ev) / lut_range_ev; + + // 0 to (including) lut_max_index + const unsigned int lookup = (unsigned)roundf(normalized * lut_max_index); + const float correction = lut[lookup]; + // apply correction + for_each_channel(c) + out[4 * k + c] = correction * in[4 * k + c]; + + if (k % 100000 == 0) { + printf("_apply_toneequalizer: k=%ld exposure=%f correction=%f\n", k, exposure, correction); + } + } +} + + +// linearly interpolated version +__DT_CLONE_TARGETS__ +static inline void _apply_toneequalizer_linear( + 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_toneequalizer_data_t *const d, + dt_dev_pixelpipe_type_t const debug_pipe) +{ +#ifdef MF_DEBUG + // printf("_apply_toneequalizer pipe=%d first luminance=%f roi_in %d %d %d %d roi_out %d %d %d %d post_scale=%f, post_shift=%f\n", + // debug_pipe, luminance[0], + // roi_in->x, roi_in->y, roi_in->width, roi_in->height, + // roi_out->x, roi_out->y, roi_out->width, roi_out->height, + // d->post_scale, d->post_shift); +#endif + const size_t npixels = (size_t)roi_in->width * roi_in->height; + const float* restrict lut = d->correction_lut; + + // Number of elements in LUT. + // The LUT still starts at 0, so the max index is lut_elem-1 + const int lut_elem = NUM_OCTAVES * LUT_RESOLUTION + 1; + + float lut_range_ev = d->lut_max_ev - d->lut_min_ev; + float lut_max_index = LUT_RESOLUTION * NUM_OCTAVES; + + // printf("_apply_toneequalizer_linear: lut_min_ev=%f lut_max_ev=%f lut_range_ev=%f\n", + // d->lut_min_ev, d->lut_max_ev, lut_range_ev); + + DT_OMP_FOR_SIMD() + for(size_t k = 0; k < npixels; k++) + { + // The radial-basis interpolation is valid in [-8; 0] EV and can quickly diverge outside. + const float exposure = fast_clamp(log2f(luminance[k]), d->lut_min_ev, d->lut_max_ev); + + // 0.0 to (including) 1.0 + const float normalized = (exposure - d->lut_min_ev) / lut_range_ev; + + // 0 to (including) lut_max_index + const unsigned int idx = (unsigned)roundf(normalized * lut_max_index); + + int i0 = (int)floorf(idx); + int i1 = i0 + 1; + float w = idx - i0; + + // Lowest allowed i0 is 0 in case that exposure = HDR_MIN_EV. + // Highest allowed i1 is LUT_OCTAVES * LUT_RESOLUTION + if(i0 < 0) { i0 = 0; i1 = 0; w = 0.0f; } + if(i1 >= lut_elem) { i1 = lut_elem - 1; i0 = lut_elem - 1; w = 0.0f; } + + const float lut0 = lut[i0]; + const float lut1 = lut[i1]; + const float correction = lut0 * (1.0f - w) + lut1 * w; + + // apply correction + for_each_channel(c) + out[4 * k + c] = correction * in[4 * k + c]; + + // if (k % 100000 == 0) { + // printf("_apply_toneequalizer_linear: k=%ld exposure=%f correction=%f\n", k, exposure, correction); + // } + } +} + +float adjust_radius_to_scale(const dt_dev_pixelpipe_iop_t *piece, const dt_iop_roi_t *roi, int full_width, int full_height) +{ + dt_iop_toneequalizer_data_t *const d = piece->data; + + // Get the scaled window radius for the box average + // This should be relative to the current full image dimensions. + // roi.width/height refer to a segment instead of the full image, so these + // values are not useful for us. + const int max_size = (full_width > full_height) ? full_width : full_height; + const float diameter = d->blending * max_size * roi->scale; + const int radius = (int)((diameter - 1.0f) / ( 2.0f)); + return radius; +} + + +// empty marker function to make navigating the function list easier +__attribute__((unused)) static void PROCESS_MARKER() {} + +/*** + * PROCESS + * + * General steps: + * 1. Compute the luminance mask + * 2. Compute the histogram of the luminance mask. In this step + * we also get the 5th and 95th percentiles. + * 3. Optionally compute auto align -> post scale and shift + * 4. Compute a correction LUT based on the user's curve in the GUI + * and post scale/shift + * 5. Correct the image based on curve and luminance mask + * + * The guided filter is scale dependent, so the results with differently + * sized input images will be different. + * + * + * We can be in one of four pipelines: + * + * DT_DEV_PIXELPIPE_PREVIEW (4) + * - In this case the input is a slightly blurry version of the full image, + * which is about 900px high. The fact that the input is blurry makes + * guided filter calculations deviate from the other pipes. + * - We cache the calculated mask in g. This version of the mask is used to + * determine the luminance at the mouse cursor position for interactive + * editing. It is also cached, so it does not need to be re-calculated + * as long as nothing changes upstream. + * - The histogram is cached in g and used for the GUI. The percentiles are + * calculated and stored in g. These are needed for the original + * exposure/contrast boost magic wands. All these statictics calculations + * deviate from the full image signifficantly, but this has been the case + * for tone equalizer from the beginning. + * DT_DEV_PIXELPIPE_FULL (2) + * - The input image is whatever is displayed in the main view. This can be + * a segment of the full image if the user has zoomed in. + * - The luminance mask for this pipe is also cached, so it does not need to + * be re-calculated as long as nothing changes upstream. This also allows + * for switching to the mask view (greyscale) quickly. + * - Special case: HQ mode. In High Quality mode, the full image will be + * supplied to process. This allows for calculating an exact histogram + * which can then be displayed in the GUI to inform the user about the + * differences. The HQ histogram is not used for any calculations. + * DT_DEV_PIXELPIPE_EXPORT (1) + * - Input is the full image. The current setting are applied. + * OTHER (i.e. DT_DEV_PIXELPIPE_THUMBNAIL) + * - The input image is a scaled-down version of the full image. The output + * will deviate from FULL/EXPORT, but since the image is very small, + * nobody will notice. + ***/ __DT_CLONE_TARGETS__ static -void toneeq_process(dt_iop_module_t *self, +void _toneeq_process(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 = piece->data; + dt_iop_toneequalizer_data_t *const d = piece->data; dt_iop_toneequalizer_gui_data_t *const g = self->gui_data; + // TODO + // imageop.h + // Align so that DT_ALIGNED_ARRAY may be used within gui_data struct + // module->gui_data = dt_calloc_aligned(size); + const float *const restrict in = (float *const)ivoid; float *const restrict out = (float *const)ovoid; - float *restrict luminance = NULL; - - const size_t width = roi_in->width; - const size_t height = roi_in->height; - const size_t num_elem = width * height; - // Get the hash of the upstream pipe to track changes - const dt_hash_t hash = dt_dev_pixelpipe_piece_hash(piece, roi_out, TRUE); + const size_t num_elem = roi_out->width * roi_out->height; + const gboolean hq = darktable.develop->late_scaling.enabled; // Sanity checks - if(width < 1 || height < 1) return; + if(roi_in->width < 1 || roi_in->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 - // Init the luminance masks buffers - gboolean cached = FALSE; + // Get the hash of the upstream pipe to track changes + const dt_hash_t current_upstream_hash = dt_dev_pixelpipe_piece_hash(piece, roi_out, FALSE); + + // This will be either local memory or cache stored in g + float *restrict luminance = NULL; + dt_iop_toneequalizer_histogram_stats_t *hdr_histogram = NULL; + + // Remember to free local buffers that are allocated in this function + gboolean local_luminance = FALSE; + gboolean local_hdr_hist = FALSE; + // printf("_toneeq_process: pipe=%d hq=%d piece->buf_in->width=%d piece->buf_in->height=%d iwidth=%d iheight=%d roi_in x=%d y=%d w=%d h=%d s=%f roi_out x=%d y=%d w=%d h=%d s=%f radius=%d mode=%d\n", + // piece->pipe->type, hq, piece->buf_in.width, piece->buf_in.height, piece->iwidth, piece->iheight, + // roi_in->x, roi_in->y, roi_in->width, roi_in->height, roi_in->scale, + // roi_out->x, roi_out->y, roi_out->width, roi_out->height, roi_out->scale, + // d->radius, darktable.color_profiles->mode); + + /************************************************************************** + * Initialization + **************************************************************************/ if(self->dev->gui_attached) { // If the module instance has changed order in the pipe, invalidate the caches if(g->pipe_order != piece->module->iop_order) { dt_iop_gui_enter_critical_section(self); - g->ui_preview_hash = DT_INVALID_HASH; - g->thumb_preview_hash = DT_INVALID_HASH; g->pipe_order = piece->module->iop_order; - g->luminance_valid = FALSE; - g->histogram_valid = FALSE; + + g->full_upstream_hash = DT_INVALID_HASH; + g->preview_upstream_hash = DT_INVALID_HASH; + g->prv_luminance_valid = FALSE; + g->full_luminance_valid = FALSE; + g->gui_histogram_valid = FALSE; dt_iop_gui_leave_critical_section(self); } - if(piece->pipe->type & DT_DEV_PIXELPIPE_FULL) + if(piece->pipe->type & DT_DEV_PIXELPIPE_PREVIEW) + { + // For DT_DEV_PIXELPIPE_PREVIEW, we need to cache the luminace mask + // and the HDR histogram for GUI. + // Locks are required since GUI reads and writes on that buffer. + + // Re-allocate a new buffer if the thumb preview size has changed + dt_iop_gui_enter_critical_section(self); + if(g->preview_buf_width != roi_out->width || g->preview_buf_height != roi_out->height) + { + dt_free_align(g->preview_buf); + g->preview_buf = dt_alloc_align_float(num_elem); + g->preview_buf_width = roi_out->width; + g->preview_buf_height = roi_out->height; + g->prv_luminance_valid = FALSE; + g->gui_histogram_valid = FALSE; + } + + luminance = g->preview_buf; + hdr_histogram = &g->mask_hdr_histo; + + dt_iop_gui_leave_critical_section(self); + } + else if (piece->pipe->type & 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_buf_width != roi_out->width || g->full_buf_height != roi_out->height) { - dt_free_align(g->full_preview_buf); - g->full_preview_buf = dt_alloc_align_float(num_elem); - g->full_preview_buf_width = width; - g->full_preview_buf_height = height; + dt_free_align(g->full_buf); + g->full_buf = dt_alloc_align_float(num_elem); + g->full_buf_width = roi_out->width; + g->full_buf_height = roi_out->height; + g->full_luminance_valid = FALSE; // TODO: critial needed for this value? } - luminance = g->full_preview_buf; - cached = TRUE; - } - else if(piece->pipe->type & DT_DEV_PIXELPIPE_PREVIEW) - { - // For DT_DEV_PIXELPIPE_PREVIEW, we need to cache it too to - // compute the full image stats upon user request in GUI threads - // locks are required since GUI reads and writes on that buffer. - - // Re-allocate a new buffer if the thumb preview size has changed - dt_iop_gui_enter_critical_section(self); - if(g->thumb_preview_buf_width != width || g->thumb_preview_buf_height != height) + // handle scrolling of the main area + if (g->full_buf_x != roi_out->x || g->full_buf_y != roi_out->y) { - dt_free_align(g->thumb_preview_buf); - g->thumb_preview_buf = dt_alloc_align_float(num_elem); - g->thumb_preview_buf_width = width; - g->thumb_preview_buf_height = height; - g->luminance_valid = FALSE; + g->full_buf_x = roi_out->x; + g->full_buf_y = roi_out->y; + g->full_luminance_valid = FALSE; } - luminance = g->thumb_preview_buf; - cached = TRUE; + luminance = g->full_buf; - dt_iop_gui_leave_critical_section(self); + hdr_histogram = dt_calloc_aligned(sizeof(dt_iop_toneequalizer_histogram_stats_t)); + _hdr_histo_init(hdr_histogram); + local_hdr_hist = TRUE; } - else // just to please GCC + else // Should not happen. GUI, but neither PREVIEW nor FULL. { luminance = dt_alloc_align_float(num_elem); + local_luminance = TRUE; + hdr_histogram = dt_calloc_aligned(sizeof(dt_iop_toneequalizer_histogram_stats_t)); + _hdr_histo_init(hdr_histogram); + local_hdr_hist = TRUE; } - } else { - // no interactive editing/caching : just allocate a local temp buffer + // no interactive editing/caching: just allocate local temp buffers luminance = dt_alloc_align_float(num_elem); + local_luminance = TRUE; + hdr_histogram = dt_calloc_aligned(sizeof(dt_iop_toneequalizer_histogram_stats_t)); + _hdr_histo_init(hdr_histogram); + local_hdr_hist = TRUE; } // Check if the luminance buffer exists - if(!luminance) + if(!luminance || !hdr_histogram) { dt_control_log(_("tone equalizer failed to allocate memory, check your RAM settings")); return; } - // Compute the luminance mask - if(cached) + d->radius = adjust_radius_to_scale(piece, roi_in, piece->iwidth, piece->iheight); + +#ifdef MF_DEBUG + printf("_toneeq_process (%d) after adjust_radius_to_scale: d->radius=%d roi in %d %d %d %d scale %f iwidth %d iheight %d\n", piece->pipe->type, d->radius, + roi_in->x, roi_in->y, roi_in->width, roi_in->height, roi_in->scale, + piece->iwidth, piece->iheight); +#endif + + /************************************************************************** + * Compute the luminance mask + **************************************************************************/ + if(self->dev->gui_attached && (piece->pipe->type & DT_DEV_PIXELPIPE_PREVIEW)) { - // caching path : store the luminance mask for GUI access + // DT_DEV_PIXELPIPE_PREVIEW: + // - Sees the whole image, but at a lower resolution and blurry. + // - Needs to store the luminance mask, HDR histogram and deciles + // for GUI. - if(piece->pipe->type & DT_DEV_PIXELPIPE_FULL) + dt_iop_gui_enter_critical_section(self); + const dt_hash_t saved_upstream_hash = g->preview_upstream_hash; + const gboolean prv_luminance_valid = g->prv_luminance_valid; + dt_iop_gui_leave_critical_section(self); + +#ifdef MF_DEBUG + printf("_toneeq_process GUI PIXELPIPE_PREVIEW: hash=%"PRIu64" saved_hash=%"PRIu64" prv_luminance_valid=%d\n", + current_upstream_hash, saved_upstream_hash, prv_luminance_valid); +#endif + + if(saved_upstream_hash != current_upstream_hash || !prv_luminance_valid) { - dt_hash_t saved_hash; - hash_set_get(&g->ui_preview_hash, &saved_hash, &self->gui_lock); + /* compute only if upstream pipe state has changed */ dt_iop_gui_enter_critical_section(self); - const gboolean luminance_valid = g->luminance_valid; - dt_iop_gui_leave_critical_section(self); + g->preview_upstream_hash = current_upstream_hash; + g->gui_histogram_valid = FALSE; - if(hash != saved_hash || !luminance_valid) - { - /* compute only if upstream pipe state has changed */ - compute_luminance_mask(in, luminance, width, height, d); - hash_set_get(&hash, &g->ui_preview_hash, &self->gui_lock); - } + _compute_luminance_mask(in, luminance, roi_out->width, roi_out->height, d, + &g->prv_image_ev_min, &g->prv_image_ev_max, + piece->pipe->type); + + // min/max ev + float min_ev, max_ev; + _compute_min_max_ev(luminance, num_elem, &min_ev, &max_ev); + hdr_histogram->min_ev = min_ev; + hdr_histogram->max_ev = max_ev; + + // Histogram and deciles + _compute_hdr_histogram_and_stats(luminance, num_elem, hdr_histogram, + piece->pipe->type); + + // GUI can assume that mask, histogram and deciles are valid + g->prv_luminance_valid = TRUE; + dt_iop_gui_leave_critical_section(self); } - else if(piece->pipe->type & DT_DEV_PIXELPIPE_PREVIEW) - { - dt_hash_t saved_hash; - hash_set_get(&g->thumb_preview_hash, &saved_hash, &self->gui_lock); + //const dt_hash_t sync_hash = dt_dev_hash_plus(self->dev, piece->pipe, self->iop_order, DT_DEV_TRANSFORM_DIR_BACK_INCL); + //dt_iop_gui_enter_critical_section(self); + // compute_auto_post_scale_shift(d->post_auto_align, + // hdr_histogram, + // &post_scale, &post_shift, + // piece->pipe->type); + //g->sync_hash = sync_hash; + // TODO: Race condition? + // t_dev_hash_plus blocks a "history mutex". + // I had DT hanging because t_dev_hash_plus was stuck there and + // blocked the GUI critical section for commit params. + //dt_iop_gui_leave_critical_section(self); + +#ifdef MF_DEBUG + printf("_toneeq_process PIXELPIPE_PREVIEW (%d): roi with=%d roi_height=%d post_align=%d d->post_scale=%f d->post_shift=%f final post_scale=%f final post_shift=%f hash=%"PRIu64" saved_hash=%"PRIu64" prv_luminance_valid=%d \n", + piece->pipe->type, + roi_in->width, roi_in->height, + d->post_auto_align, d->post_scale, d->post_shift, + post_scale, post_shift, + current_upstream_hash, saved_upstream_hash, prv_luminance_valid + ); +#endif + + // TODO MF: Not completely sure in which cases this must be called. + // Assumption is once per output image change by this module and + // only when the GUI is active. + dt_dev_pixelpipe_cache_invalidate_later(piece->pipe, self->iop_order); + } + else if(self->dev->gui_attached && (piece->pipe->type & DT_DEV_PIXELPIPE_FULL)) + { + + + // FULL may only see a part of the image if the user has zoomed in. + // We need to compute a luminance mask for this pipe and cache it for + // quick reuse (i.e. if the user only changes the curve). + // But we can not compute deciles here. + + // roi_in and roi_out must be the same + assert(roi_in->x == roi_out->x && roi_in->y == roi_out->y && roi_in->width == roi_out->width + && roi_in->height == roi_out->height && roi_in->scale == roi_out->scale); + + dt_iop_gui_enter_critical_section(self); + const dt_hash_t saved_upstream_hash = g->full_upstream_hash; + const gboolean full_luminance_valid = g->full_luminance_valid; + dt_iop_gui_leave_critical_section(self); + +#ifdef MF_DEBUG + printf("_toneeq_process GUI PIXELPIPE_FULL: hash=%" PRIu64 " saved_hash=%" PRIu64 " full_luminance_valid=%d\n", + current_upstream_hash, saved_upstream_hash, full_luminance_valid); +#endif + + // If the upstream state has changed, re-compute the mask of the displayed image part + if(current_upstream_hash != saved_upstream_hash || !full_luminance_valid) + { + /* compute only if upstream pipe state has changed */ dt_iop_gui_enter_critical_section(self); - const gboolean luminance_valid = g->luminance_valid; + g->full_upstream_hash = current_upstream_hash; dt_iop_gui_leave_critical_section(self); - if(saved_hash != hash || !luminance_valid) - { - /* compute only if upstream pipe state has changed */ - dt_iop_gui_enter_critical_section(self); - g->thumb_preview_hash = hash; - g->histogram_valid = FALSE; - compute_luminance_mask(in, luminance, width, height, d); - g->luminance_valid = TRUE; - dt_iop_gui_leave_critical_section(self); - dt_dev_pixelpipe_cache_invalidate_later(piece->pipe, self->iop_order); - } + float image_lum_min, image_lum_max; + _compute_luminance_mask(in, luminance, roi_out->width, roi_out->height, d, + &image_lum_min, &image_lum_max, + piece->pipe->type); + g->full_luminance_valid = TRUE; } - else // make it dummy-proof + + // dt_iop_gui_enter_critical_section(self); + // const dt_hash_t sync_hash = g->sync_hash; + // dt_iop_gui_leave_critical_section(self); + + // if(sync_hash != DT_INVALID_HASH + // && !dt_dev_sync_pixelpipe_hash(self->dev, piece->pipe, self->iop_order, + // DT_DEV_TRANSFORM_DIR_BACK_INCL, + // &self->gui_lock, &g->sync_hash)) + // { + // dt_control_log(_("inconsistent output")); + // } + + if (hq) { - compute_luminance_mask(in, luminance, width, height, d); + // Compute the high quality histogram + dt_iop_gui_enter_critical_section(self); + float min_ev, max_ev; + _compute_min_max_ev(luminance, num_elem, &min_ev, &max_ev); + hdr_histogram->min_ev = min_ev; + hdr_histogram->max_ev = max_ev; + _compute_hdr_histogram_and_stats(luminance, num_elem, + &g->mask_hq_histo, piece->pipe->type); + dt_iop_gui_leave_critical_section(self); } } else { - // no caching path : compute no matter what - compute_luminance_mask(in, luminance, width, height, d); + // No caching path: compute no matter what + // We are in PIXELPIPE_EXPORT or PIXELPIPE_THUMBNAIL + + float image_lum_min, image_lum_max; + _compute_luminance_mask(in, luminance, roi_out->width, roi_out->height, d, + &image_lum_min, &image_lum_max, + piece->pipe->type); + } - // Display output - if(self->dev->gui_attached && (piece->pipe->type & DT_DEV_PIXELPIPE_FULL)) + /************************************************************************** + * Display output + **************************************************************************/ + if(self->dev->gui_attached && (piece->pipe->type & DT_DEV_PIXELPIPE_FULL) && g->mask_display) { - if(g->mask_display) - { - display_luminance_mask(in, luminance, out, roi_in, roi_out); - piece->pipe->mask_display = DT_DEV_PIXELPIPE_DISPLAY_PASSTHRU; - } - else - apply_toneequalizer(in, luminance, out, roi_in, roi_out, d); + _display_luminance_mask(in, luminance, out, roi_in, roi_out, + d->post_scale_base, d->post_shift_base, + d->post_scale, d->post_shift, d->post_pivot, + piece->pipe->type); + piece->pipe->mask_display = DT_DEV_PIXELPIPE_DISPLAY_PASSTHRU; } else { - apply_toneequalizer(in, luminance, out, roi_in, roi_out, d); + + + _compute_correction_lut(d, piece->pipe->type, NAN, NAN); + + _apply_toneequalizer_linear(in, luminance, out, + roi_in, + d, piece->pipe->type); + } + + /************************************************************************** + * Cleanup + **************************************************************************/ + if(local_luminance) { + dt_free_align(luminance); + } + if(local_hdr_hist) { + dt_free_align(hdr_histogram); } - if(!cached) dt_free_align(luminance); +#ifdef MF_DEBUG + printf("_toneeq_process DONE: pipe=%d hq=%d piece->buf_in->width=%d piece->buf_in->height=%d iwidth=%d iheight=%d roi_in x=%d y=%d w=%d h=%d s=%f roi_out x=%d y=%d w=%d h=%d s=%f radius=%d mode=%d\n", + piece->pipe->type, hq, piece->buf_in.width, piece->buf_in.height, piece->iwidth, piece->iheight, + roi_in->x, roi_in->y, roi_in->width, roi_in->height, roi_in->scale, + roi_out->x, roi_out->y, roi_out->width, roi_out->height, roi_out->scale, + d->radius, darktable.color_profiles->mode); +#endif +} + +void process(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) +{ + _toneeq_process(self, piece, ivoid, ovoid, roi_in, roi_out); +} + + +/**************************************************************************** + * + * Initialization and Cleanup + * + ****************************************************************************/ + +void init_global(dt_iop_module_so_t *self) +{ + dt_iop_toneequalizer_global_data_t *gd = malloc(sizeof(dt_iop_toneequalizer_global_data_t)); + + self->data = gd; +} + +void cleanup_global(dt_iop_module_so_t *self) +{ + free(self->data); + self->data = NULL; } -void process(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) +void init_pipe(dt_iop_module_t *self, + dt_dev_pixelpipe_t *pipe, + dt_dev_pixelpipe_iop_t *piece) { - toneeq_process(self, piece, ivoid, ovoid, roi_in, roi_out); + piece->data = dt_calloc1_align_type(dt_iop_toneequalizer_data_t); } +void cleanup_pipe(dt_iop_module_t *self, + dt_dev_pixelpipe_t *pipe, + dt_dev_pixelpipe_iop_t *piece) +{ + dt_free_align(piece->data); + piece->data = NULL; +} void modify_roi_in(dt_iop_module_t *self, dt_dev_pixelpipe_iop_t *piece, const dt_iop_roi_t *roi_out, dt_iop_roi_t *roi_in) { - // Pad the zoomed-in view to avoid weird stuff with local averages - // at the borders of the preview - - dt_iop_toneequalizer_data_t *const d = piece->data; - - // Get the scaled window radius for the box average - const int max_size = (piece->iwidth > piece->iheight) ? piece->iwidth : piece->iheight; - const float diameter = d->blending * max_size * roi_in->scale; - const int radius = (int)((diameter - 1.0f) / ( 2.0f)); - d->radius = radius; + // Nothing to do here for now... } /*** * Setters and Getters for parameters * - * Remember the user params split the [-8; 0] EV range in 9 channels + * Remember the user params split the [-8; 0] EV range in 9 NUM_SLIDERS * and define a set of (x, y) coordinates, where x are the exposure - * channels (evenly-spaced by 1 EV in [-8; 0] EV) and y are the + * NUM_SLIDERS (evenly-spaced by 1 EV in [-8; 0] EV) and y are the * desired exposure compensation for each channel. * * This (x, y) set is interpolated by radial-basis function using a @@ -1220,135 +2208,170 @@ void modify_roi_in(dt_iop_module_t *self, * should be used in combination with a tone curve or filmic. * ***/ +static void _gauss_get_channels_gains(float gauss_factors[NUM_SLIDERS], + const dt_iop_toneequalizer_params_t *p) +{ + assert(NUM_SLIDERS == 9); + + // Get user-set NUM_SLIDERS gains in EV (log2) + gauss_factors[0] = p->noise; // -8 EV + gauss_factors[1] = p->ultra_deep_blacks; // -7 EV + gauss_factors[2] = p->deep_blacks; // -6 EV + gauss_factors[3] = p->blacks; // -5 EV + gauss_factors[4] = p->shadows; // -4 EV + gauss_factors[5] = p->midtones; // -3 EV + gauss_factors[6] = p->highlights; // -2 EV + gauss_factors[7] = p->whites; // -1 EV + gauss_factors[8] = p->speculars; // +0 EV +} -static void compute_correction_lut(float* restrict lut, - const float sigma, - const float *const restrict factors) +static void _gauss_get_channels_factors(float gauss_factors[NUM_SLIDERS], + const dt_iop_toneequalizer_params_t *p) { - const float gauss_denom = gaussian_denom(sigma); - assert(PIXEL_CHAN == 8); + assert(NUM_SLIDERS == 9); - DT_OMP_FOR(shared(centers_ops)) - for(int j = 0; j <= LUT_RESOLUTION * PIXEL_CHAN; j++) - { - // build the correction for each pixel - // as the sum of the contribution of each luminance channelcorrection - const float exposure = (float)j / (float)LUT_RESOLUTION + DT_TONEEQ_MIN_EV; - float result = 0.0f; - 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 - lut[j] = fast_clamp(result, 0.25f, 4.0f); - } + // Get user-set NUM_SLIDERS gains in EV (log2) + _gauss_get_channels_gains(gauss_factors, p); + + // Convert from EV offsets to linear factors + DT_OMP_SIMD(aligned(gauss_factors:64)) + for(int c = 0; c < NUM_SLIDERS; ++c) + gauss_factors[c] = exp2f(gauss_factors[c]); } -static void get_channels_gains(float factors[CHANNELS], - const dt_iop_toneequalizer_params_t *p) +static inline void _catmull_fill_array(float cat_y[NUM_SLIDERS+2], + const dt_iop_toneequalizer_params_t *p) { - assert(CHANNELS == 9); - - // Get user-set channels gains in EV (log2) - factors[0] = p->noise; // -8 EV - factors[1] = p->ultra_deep_blacks; // -7 EV - factors[2] = p->deep_blacks; // -6 EV - factors[3] = p->blacks; // -5 EV - factors[4] = p->shadows; // -4 EV - factors[5] = p->midtones; // -3 EV - factors[6] = p->highlights; // -2 EV - factors[7] = p->whites; // -1 EV - factors[8] = p->speculars; // +0 EV + assert(NUM_SLIDERS+2 == 11); + + // For positive smoothing, place the shadow points horizontal (y = same as next point). + // For negative smoothing continue the slope. + // In the smoothing switch zone, interpolate linearly between the two. + const float smoothing_switch_zone = 0.1; + + // map -0.1...0.1 to -1...1 + const float zone_pos = fast_clamp(p->smoothing / smoothing_switch_zone, -1.0f, 1.0f); + // map -1...1 to 0...1 + const float t = (zone_pos + 1.0f) * 0.5f; + + // phantom point + cat_y[0] = exp2f(t * p->noise + (1-t) * (2*p->noise - p->ultra_deep_blacks)); + + // regular points + cat_y[1] = exp2f(p->noise); + cat_y[2] = exp2f(p->ultra_deep_blacks); + cat_y[3] = exp2f(p->deep_blacks); + cat_y[4] = exp2f(p->blacks); + cat_y[5] = exp2f(p->shadows); + cat_y[6] = exp2f(p->midtones); + cat_y[7] = exp2f(p->highlights); + cat_y[8] = exp2f(p->whites); + cat_y[9] = exp2f(p->speculars); + + // phantom point + cat_y[10] = exp2f(t * p->speculars + (1-t) * (2*p->speculars - p->whites)); } -static void get_channels_factors(float factors[CHANNELS], - const dt_iop_toneequalizer_params_t *p) +__DT_CLONE_TARGETS__ +static inline float _gauss_pixel_correction(const float exposure, + const float *const restrict gauss_factors, + const float sigma) { - assert(CHANNELS == 9); + // 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, DT_TONEEQ_MIN_EV, DT_TONEEQ_MAX_EV); - // Get user-set channels gains in EV (log2) - get_channels_gains(factors, p); + DT_OMP_SIMD(aligned(centers_ops, gauss_factors:64) safelen(NUM_OCTAVES) reduction(+:result)) + for(int i = 0; i < NUM_OCTAVES; ++i) + result += _gaussian_func(expo - centers_ops[i], gauss_denom) * gauss_factors[i]; - // Convert from EV offsets to linear factors - DT_OMP_SIMD(aligned(factors:64)) - for(int c = 0; c < CHANNELS; ++c) - factors[c] = exp2f(factors[c]); + return fast_clamp(result, 0.25f, 4.0f); } __DT_CLONE_TARGETS__ -static gboolean compute_channels_factors(const float factors[PIXEL_CHAN], - float out[CHANNELS], - const float sigma) +static gboolean _gauss_compute_channels_factors(const float gauss_factors[NUM_OCTAVES], + float out[NUM_SLIDERS], + const float sigma) { // Input factors are the weights for the radial-basis curve // approximation of user params Output factors are the gains of the - // user parameters channels aka the y coordinates of the - // approximation for x = { CHANNELS } - assert(PIXEL_CHAN == 8); + // user parameters NUM_SLIDERS aka the y coordinates of the + // approximation for x = { NUM_SLIDERS } + assert(NUM_OCTAVES == 8); - DT_OMP_FOR_SIMD(aligned(factors, out, centers_params:64) firstprivate(centers_params)) - for(int i = 0; i < CHANNELS; ++i) + DT_OMP_FOR_SIMD(aligned(gauss_factors, out, centers_params:64) firstprivate(centers_params)) + for(int i = 0; i < NUM_SLIDERS; ++i) { - // Compute the new channels factors; pixel_correction clamps the factors, so we don't + // Compute the new NUM_SLIDERS factors; _gauss_pixel_correction clamps the factors, so we don't // need to check for validity here - out[i] = pixel_correction(centers_params[i], factors, sigma); + out[i] = _gauss_pixel_correction(centers_params[i], gauss_factors, sigma); } return TRUE; } - __DT_CLONE_TARGETS__ -static void compute_channels_gains(const float in[CHANNELS], - float out[CHANNELS]) +static void _compute_channels_gains(const float in[NUM_SLIDERS], + float out[NUM_SLIDERS]) { - // Helper function to compute the new channels gains (log) from the factors (linear) - assert(PIXEL_CHAN == 8); + // Helper function to compute the new NUM_SLIDERS gains (log) from the factors (linear) + assert(NUM_OCTAVES == 8); - for(int i = 0; i < CHANNELS; ++i) + for(int i = 0; i < NUM_SLIDERS; ++i) out[i] = log2f(in[i]); } - -static void commit_channels_gains(const float factors[CHANNELS], - dt_iop_toneequalizer_params_t *p) +static void _commit_channels_gains(const float gauss_factors[NUM_SLIDERS], + dt_iop_toneequalizer_params_t *p) { - p->noise = factors[0]; - p->ultra_deep_blacks = factors[1]; - p->deep_blacks = factors[2]; - p->blacks = factors[3]; - p->shadows = factors[4]; - p->midtones = factors[5]; - p->highlights = factors[6]; - p->whites = factors[7]; - p->speculars = factors[8]; + p->noise = gauss_factors[0]; + p->ultra_deep_blacks = gauss_factors[1]; + p->deep_blacks = gauss_factors[2]; + p->blacks = gauss_factors[3]; + p->shadows = gauss_factors[4]; + p->midtones = gauss_factors[5]; + p->highlights = gauss_factors[6]; + p->whites = gauss_factors[7]; + p->speculars = gauss_factors[8]; } -/*** - * Cache invalidation and initializatiom - ***/ - - -static void gui_cache_init(dt_iop_module_t *self) +/**************************************************************************** + * + * Cache invalidation and initialization + * + ****************************************************************************/ +static void _gui_cache_init(dt_iop_module_t *self) { dt_iop_toneequalizer_gui_data_t *g = self->gui_data; if(g == NULL) return; dt_iop_gui_enter_critical_section(self); - g->ui_preview_hash = DT_INVALID_HASH; - g->thumb_preview_hash = DT_INVALID_HASH; - g->max_histogram = 1; + g->full_upstream_hash = DT_INVALID_HASH; + g->preview_upstream_hash = DT_INVALID_HASH; + + _ui_histo_init(&g->ui_histo); + _ui_histo_init(&g->ui_hq_histo); + + _hdr_histo_init(&g->mask_hdr_histo); + _hdr_histo_init(&g->mask_hq_histo); + g->scale = 1.0f; g->sigma = sqrtf(2.0f); g->mask_display = FALSE; + g->image_EV_per_UI_sample = 0.00001; // In case no value is calculated yet, use something small, but not 0 - g->interpolation_valid = FALSE; // TRUE if the interpolation_matrix is ready - g->luminance_valid = FALSE; // TRUE if the luminance cache is ready - g->histogram_valid = FALSE; // TRUE if the histogram cache and stats are ready - g->lut_valid = FALSE; // TRUE if the gui_lut is ready + g->interpolation_valid = FALSE; // TRUE if the gauss_interpolation_matrix is ready + g->prv_luminance_valid = FALSE; // TRUE if the luminance cache is ready + g->full_luminance_valid = FALSE; // TRUE if the luminance cache is ready + g->gui_histogram_valid = FALSE; // TRUE if the histogram cache and stats are ready + g->gui_curve_valid = FALSE; // TRUE if the gui_curve_lut is ready g->graph_valid = FALSE; // TRUE if the UI graph view is ready g->user_param_valid = FALSE; // TRUE if users params set in interactive view are in bounds - g->factors_valid = TRUE; // TRUE if radial-basis coeffs are ready + g->gauss_factors_valid = TRUE; // TRUE if radial-basis coeffs are ready g->valid_nodes_x = FALSE; // TRUE if x coordinates of graph nodes have been inited g->valid_nodes_y = FALSE; // TRUE if y coordinates of graph nodes have been inited @@ -1357,13 +2380,19 @@ static void gui_cache_init(dt_iop_module_t *self) g->cursor_valid = FALSE; // TRUE if mouse cursor is over the preview image g->has_focus = FALSE; // TRUE if module has focus from GTK - g->full_preview_buf = NULL; - g->full_preview_buf_width = 0; - g->full_preview_buf_height = 0; + g->area_vscale = FALSE; + g->area_ignore_border_bins = FALSE; + g->warning_icon_active = TRUE; - g->thumb_preview_buf = NULL; - g->thumb_preview_buf_width = 0; - g->thumb_preview_buf_height = 0; + g->preview_buf = NULL; + g->preview_buf_width = 0; + g->preview_buf_height = 0; + + g->full_buf = NULL; + g->full_buf_width = 0; + g->full_buf_height = 0; + g->full_buf_x = 0; + g->full_buf_y = 0; g->desc = NULL; g->layout = NULL; @@ -1375,145 +2404,124 @@ static void gui_cache_init(dt_iop_module_t *self) dt_iop_gui_leave_critical_section(self); } - -static inline void build_interpolation_matrix(float A[CHANNELS * PIXEL_CHAN], - const float sigma) +static void _invalidate_luminance_cache(dt_iop_module_t *const self) { - // Build the symmetrical definite positive part of the augmented matrix - // of the radial-basis interpolation weights - - const float gauss_denom = gaussian_denom(sigma); +#ifdef MF_DEBUG + printf("_invalidate_luminance_cache\n"); +#endif + // Invalidate the private luminance cache and histogram when + // the luminance mask extraction parameters have changed + dt_iop_toneequalizer_gui_data_t *const restrict g = self->gui_data; - DT_OMP_SIMD(aligned(A, centers_ops, centers_params:64) collapse(2)) - for(int i = 0; i < CHANNELS; ++i) - for(int j = 0; j < PIXEL_CHAN; ++j) - A[i * PIXEL_CHAN + j] = - gaussian_func(centers_params[i] - centers_ops[j], gauss_denom); + dt_iop_gui_enter_critical_section(self); + g->prv_luminance_valid = FALSE; + g->preview_upstream_hash = DT_INVALID_HASH; + g->full_luminance_valid = FALSE; + g->full_upstream_hash = DT_INVALID_HASH; + + g->gui_curve_valid = FALSE; + g->gui_histogram_valid = FALSE; + g->ui_histo.max_val = 1; + g->ui_histo.max_val_ignore_border_bins = 1; + g->ui_hq_histo.max_val = 1; + g->ui_hq_histo.max_val_ignore_border_bins = 1; + dt_iop_gui_leave_critical_section(self); + dt_iop_refresh_all(self); } - -__DT_CLONE_TARGETS__ -static inline void compute_log_histogram_and_stats(const float *const restrict luminance, - int histogram[UI_SAMPLES], - const size_t num_elem, - int *max_histogram, - float *first_decile, - float *last_decile) +static void _invalidate_lut_and_histogram(dt_iop_module_t *const self) { - // (Re)init the histogram - memset(histogram, 0, sizeof(int) * UI_SAMPLES); - - // we first calculate an extended histogram for better accuracy - #define TEMP_SAMPLES 2 * UI_SAMPLES - int temp_hist[TEMP_SAMPLES]; - memset(temp_hist, 0, sizeof(int) * TEMP_SAMPLES); - - // Split exposure in bins - DT_OMP_FOR_SIMD(reduction(+:temp_hist[:TEMP_SAMPLES])) - for(size_t k = 0; k < num_elem; k++) - { - // extended histogram bins between [-10; +6] EV remapped between [0 ; 2 * UI_SAMPLES] - const int index = - CLAMP((int)(((log2f(luminance[k]) + 10.0f) / 16.0f) * (float)TEMP_SAMPLES), - 0, TEMP_SAMPLES - 1); - temp_hist[index] += 1; - } - - const int first = (int)((float)num_elem * 0.05f); - const int last = (int)((float)num_elem * (1.0f - 0.95f)); - int population = 0; - int first_pos = 0; - int last_pos = 0; - - // scout the extended histogram bins looking for deciles - // these would not be accurate with the regular histogram - for(int k = 0; k < TEMP_SAMPLES; ++k) - { - const size_t prev_population = population; - population += temp_hist[k]; - if(prev_population < first && first <= population) - { - first_pos = k; - break; - } - } - population = 0; - for(int k = TEMP_SAMPLES - 1; k >= 0; --k) - { - const size_t prev_population = population; - population += temp_hist[k]; - if(prev_population < last && last <= population) - { - last_pos = k; - break; - } - } +#ifdef MF_DEBUG + printf("_invalidate_lut_and_histogram\n"); +#endif + dt_iop_toneequalizer_gui_data_t *const restrict g = self->gui_data; - // Convert decile positions to exposures - *first_decile = 16.0 * (float)first_pos / (float)(TEMP_SAMPLES - 1) - 10.0; - *last_decile = 16.0 * (float)last_pos / (float)(TEMP_SAMPLES - 1) - 10.0; + dt_iop_gui_enter_critical_section(self); + g->gui_curve_valid = FALSE; + g->gui_histogram_valid = FALSE; + g->ui_histo.max_val = 1; + g->ui_histo.max_val_ignore_border_bins = 1; + g->ui_hq_histo.max_val = 1; + g->ui_hq_histo.max_val_ignore_border_bins = 1; + dt_iop_gui_leave_critical_section(self); + dt_iop_refresh_all(self); +} - // remap the extended histogram into the normal one - // bins between [-8; 0] EV remapped between [0 ; UI_SAMPLES] - for(size_t k = 0; k < TEMP_SAMPLES; ++k) - { - float EV = 16.0 * (float)k / (float)(TEMP_SAMPLES - 1) - 10.0; - const int i = - CLAMP((int)(((EV + 8.0f) / 8.0f) * (float)UI_SAMPLES), - 0, UI_SAMPLES - 1); - histogram[i] += temp_hist[k]; - // store the max numbers of elements in bins for later normalization - *max_histogram = histogram[i] > *max_histogram ? histogram[i] : *max_histogram; - } -} +/**************************************************************************** + * + * Curve Interpolation + * + ****************************************************************************/ +// empty marker function to make navigating the function list easier +__attribute__((unused)) static void CURVE_INTERPOLATION_MARKER() {} -static inline void update_histogram(dt_iop_module_t *const self) +static inline void _gauss_build_interpolation_matrix(float A[NUM_SLIDERS * NUM_OCTAVES], + const float sigma) { - dt_iop_toneequalizer_gui_data_t *const g = self->gui_data; - if(g == NULL) return; + // Build the symmetrical definite positive part of the augmented matrix + // of the radial-basis interpolation weights - dt_iop_gui_enter_critical_section(self); - if(!g->histogram_valid && g->luminance_valid) - { - const size_t num_elem = g->thumb_preview_buf_height * g->thumb_preview_buf_width; - compute_log_histogram_and_stats(g->thumb_preview_buf, g->histogram, num_elem, - &g->max_histogram, - &g->histogram_first_decile, &g->histogram_last_decile); - g->histogram_average = (g->histogram_first_decile + g->histogram_last_decile) / 2.0f; - g->histogram_valid = TRUE; - } - dt_iop_gui_leave_critical_section(self); -} + const float gauss_denom = _gaussian_denom(sigma); + DT_OMP_SIMD(aligned(A, centers_ops, centers_params:64) collapse(2)) + for(int i = 0; i < NUM_SLIDERS; ++i) + for(int j = 0; j < NUM_OCTAVES; ++j) + A[i * NUM_OCTAVES + j] = + _gaussian_func(centers_params[i] - centers_ops[j], gauss_denom); +} __DT_CLONE_TARGETS__ -static inline void compute_lut_correction(dt_iop_toneequalizer_gui_data_t *g, - const float offset, - const float scaling) +static inline void _compute_gui_curve(dt_iop_toneequalizer_gui_data_t *g, dt_iop_toneequalizer_params_t *p) { - // Compute the LUT of the exposure corrections in EV, + // Compute the curve of the exposure corrections in EV, // offset and scale it for display in GUI widget graph if(g == NULL) return; - float *const restrict LUT = g->gui_lut; - const float *const restrict factors = g->factors; + float *const restrict curve = g->gui_curve; const float sigma = g->sigma; - DT_OMP_FOR_SIMD(aligned(LUT, factors:64)) - for(int k = 0; k < UI_SAMPLES; k++) - { - // build the inset graph curve LUT - // the x range is [-14;+2] EV - const float x = (8.0f * (((float)k) / ((float)(UI_SAMPLES - 1)))) - 8.0f; - LUT[k] = offset - log2f(pixel_correction(x, factors, sigma)) / scaling; + // printf("_compute_gui_curve: sigma=%f curve_type=%d\n", sigma, p->curve_type); + + if (p->curve_type == DT_TONEEQ_CURVE_GAUSS) { + const float *const restrict gauss_factors = g->gauss_factors; + + DT_OMP_FOR_SIMD(aligned(curve, gauss_factors:64)) + for(int k = 0; k < UI_HISTO_SAMPLES; k++) + { + // build the inset graph curve LUT + const float x = (8.0f * (((float)k) / ((float)(UI_HISTO_SAMPLES - 1)))) - 8.0f; + curve[k] = log2f(_gauss_pixel_correction(x, gauss_factors, sigma)); + } + } else { // CATMULL ROM + + // printf("_compute_gui_curve/CATMULL: catmull_y=%f %f %f %f %f %f %f %f %f %f %f catmull_tangents=%f %f %f %f %f %f %f %f %f\n", + // g->catmull_y[0], g->catmull_y[1], g->catmull_y[2], g->catmull_y[3], g->catmull_y[4], + // g->catmull_y[5], g->catmull_y[6], g->catmull_y[7], g->catmull_y[8], g->catmull_y[9], g->catmull_y[10], + // g->catmull_tangents[0], g->catmull_tangents[1], g->catmull_tangents[2], g->catmull_tangents[3], + // g->catmull_tangents[4], g->catmull_tangents[5], g->catmull_tangents[6], g->catmull_tangents[7], + // g->catmull_tangents[8] + // ); + + const float *const restrict catmull_y = g->catmull_y; + const float *const restrict catmull_tangents = g->catmull_tangents; + + DT_OMP_FOR_SIMD(aligned(curve, catmull_y, catmull_tangents:64)) + for(int k = 0; k < UI_HISTO_SAMPLES; k++) + { + // build the inset graph curve LUT + const float x = (8.0f * (((float)k) / ((float)(UI_HISTO_SAMPLES - 1)))) - 8.0f; + curve[k] = log2f(catmull_rom_val(NUM_SLIDERS, DT_TONEEQ_MIN_EV, x, catmull_y, catmull_tangents)); + // if (k % 25 == 0) { + // printf("_compute_gui_curve/CATMULL: k=%d x=%f curve=%f\n", k, x, curve[k]); + // } + } } } - -static inline gboolean update_curve_lut(dt_iop_module_t *self) +static inline gboolean _curve_interpolation(dt_iop_module_t *self) { dt_iop_toneequalizer_params_t *p = self->params; dt_iop_toneequalizer_gui_data_t *g = self->gui_data; @@ -1524,72 +2532,90 @@ static inline gboolean update_curve_lut(dt_iop_module_t *self) dt_iop_gui_enter_critical_section(self); - if(!g->interpolation_valid) + if(p->curve_type == DT_TONEEQ_CURVE_GAUSS) { - build_interpolation_matrix(g->interpolation_matrix, g->sigma); - g->interpolation_valid = TRUE; - g->factors_valid = FALSE; - } - if(!g->user_param_valid) - { - float factors[CHANNELS] DT_ALIGNED_ARRAY; - get_channels_factors(factors, p); - dt_simd_memcpy(factors, g->temp_user_params, CHANNELS); - g->user_param_valid = TRUE; - g->factors_valid = FALSE; - } + if(!g->interpolation_valid) + { - if(!g->factors_valid && g->user_param_valid) - { - float factors[CHANNELS] DT_ALIGNED_ARRAY; - dt_simd_memcpy(g->temp_user_params, factors, CHANNELS); - valid = pseudo_solve(g->interpolation_matrix, factors, CHANNELS, PIXEL_CHAN, TRUE); - if(valid) dt_simd_memcpy(factors, g->factors, PIXEL_CHAN); - else dt_print(DT_DEBUG_PIPE, "tone equalizer pseudo solve problem"); - g->factors_valid = TRUE; - g->lut_valid = FALSE; - } + g->sigma = powf(sqrtf(2.0f), 1.0f + p->smoothing); - if(!g->lut_valid && g->factors_valid) - { - compute_lut_correction(g, 0.5f, 4.0f); - g->lut_valid = TRUE; - } + _gauss_build_interpolation_matrix(g->gauss_interpolation_matrix, g->sigma); - dt_iop_gui_leave_critical_section(self); + g->interpolation_valid = TRUE; + g->gauss_factors_valid = FALSE; + } - return valid; -} + if(!g->user_param_valid) + { + float gauss_factors[NUM_SLIDERS] DT_ALIGNED_ARRAY; + _gauss_get_channels_factors(gauss_factors, p); + dt_simd_memcpy(gauss_factors, g->temp_user_params, NUM_SLIDERS); -void init_global(dt_iop_module_so_t *self) -{ - dt_iop_toneequalizer_global_data_t *gd = malloc(sizeof(dt_iop_toneequalizer_global_data_t)); + g->user_param_valid = TRUE; + g->gauss_factors_valid = FALSE; + } - self->data = gd; -} + if(!g->gauss_factors_valid && g->user_param_valid) + { + float gauss_factors[NUM_SLIDERS] DT_ALIGNED_ARRAY; + dt_simd_memcpy(g->temp_user_params, gauss_factors, NUM_SLIDERS); + valid = pseudo_solve(g->gauss_interpolation_matrix, gauss_factors, NUM_SLIDERS, NUM_OCTAVES, TRUE); + if(valid) + dt_simd_memcpy(gauss_factors, g->gauss_factors, NUM_OCTAVES); + else + dt_print(DT_DEBUG_PIPE, "tone equalizer pseudo solve problem"); -void cleanup_global(dt_iop_module_so_t *self) -{ - free(self->data); - self->data = NULL; + g->gauss_factors_valid = TRUE; + g->gui_curve_valid = FALSE; + } + + if(!g->gui_curve_valid && g->gauss_factors_valid) + { + _compute_gui_curve(g, p); + g->gui_curve_valid = TRUE; + } + } + else // catmull rom curve + { + _catmull_fill_array(g->catmull_y, p); + catmull_rom_tangents(g->catmull_y, g->catmull_tangents, p->smoothing); + _compute_gui_curve(g, p); + g->gui_curve_valid = TRUE; + + dt_simd_memcpy(&g->catmull_y[1], g->temp_user_params, NUM_SLIDERS); + g->user_param_valid = TRUE; + valid = TRUE; + } + + dt_iop_gui_leave_critical_section(self); + return valid; } -void commit_params(dt_iop_module_t *self, - dt_iop_params_t *p1, - dt_dev_pixelpipe_t *pipe, +/**************************************************************************** + * + * Commit Params + * + ****************************************************************************/ +void commit_params(dt_iop_module_t *self, dt_iop_params_t *p1, dt_dev_pixelpipe_t *pipe, dt_dev_pixelpipe_iop_t *piece) { + dt_iop_toneequalizer_params_t *p = (dt_iop_toneequalizer_params_t *)p1; dt_iop_toneequalizer_data_t *d = piece->data; dt_iop_toneequalizer_gui_data_t *g = self->gui_data; +#ifdef MF_DEBUG + printf("commit_params pipe=%d p->post_scale=%f p->post_shift=%f d->post_scale=%f d->post_shift=%f\n", + pipe->type, p->post_scale, p->post_shift, d->post_scale, d->post_shift); +#endif + // Trivial params passing - d->method = p->method; - d->details = p->details; + d->lum_estimator = p->lum_estimator; + d->filter = p->filter; d->iterations = p->iterations; d->smoothing = p->smoothing; d->quantization = p->quantization; @@ -1605,65 +2631,211 @@ void commit_params(dt_iop_module_t *self, d->contrast_boost = exp2f(p->contrast_boost); d->exposure_boost = exp2f(p->exposure_boost); + // scaling is also stored as log + d->post_scale_base = exp2f(p->post_scale_base); + d->post_shift_base = p->post_shift_base; + d->post_scale = exp2f(p->post_scale); + d->post_shift = p->post_shift; + d->post_pivot = p->post_pivot; + + d->global_exposure = p->global_exposure; + d->scale_curve = p->scale_curve; + d->curve_type = p->curve_type; + + // RGB weights for luminance estimator + if (p->lum_estimator_normalize) + { + const float sum = MAX(NORM_MIN, p->lum_estimator_R + p->lum_estimator_G + p->lum_estimator_B); + d->lum_estimator_R = p->lum_estimator_R / sum; + d->lum_estimator_G = p->lum_estimator_G / sum; + d->lum_estimator_B = p->lum_estimator_B / sum; + } + else + { + d->lum_estimator_R = p->lum_estimator_R; + d->lum_estimator_G = p->lum_estimator_G; + d->lum_estimator_B = p->lum_estimator_B; + } + + d->pre_contrast_width = p->pre_contrast_width; + d->pre_contrast_strength = p->pre_contrast_strength; + d->pre_contrast_midpoint = p->pre_contrast_midpoint; + /* * Perform a radial-based interpolation using a series gaussian functions */ - if(self->dev->gui_attached && g) + + if (self->dev->gui_attached && g) { dt_iop_gui_enter_critical_section(self); - if(g->sigma != p->smoothing) - g->interpolation_valid = FALSE; - g->sigma = p->smoothing; - g->user_param_valid = FALSE; // force updating channels factors - dt_iop_gui_leave_critical_section(self); - update_curve_lut(self); + float sigma = powf(sqrtf(2.0f), 1.0f + p->smoothing); - dt_iop_gui_enter_critical_section(self); - dt_simd_memcpy(g->factors, d->factors, PIXEL_CHAN); + if(g->sigma != sigma) g->interpolation_valid = FALSE; + + g->sigma = sigma; + g->user_param_valid = FALSE; // force updating NUM_SLIDERS factors // TODO MF: Comment dt_iop_gui_leave_critical_section(self); + + _curve_interpolation(self); + + if (p->curve_type == DT_TONEEQ_CURVE_GAUSS) { + dt_iop_gui_enter_critical_section(self); + dt_simd_memcpy(g->gauss_factors, d->gauss_factors, NUM_OCTAVES); + dt_iop_gui_leave_critical_section(self); + } + else + { + dt_iop_gui_enter_critical_section(self); + dt_simd_memcpy(g->catmull_y, d->catmull_y, NUM_SLIDERS+2); + dt_simd_memcpy(g->catmull_tangents, d->catmull_tangents, NUM_SLIDERS); + dt_iop_gui_leave_critical_section(self); + } } - else + else // no GUI { - // No cache : Build / Solve interpolation matrix - float factors[CHANNELS] DT_ALIGNED_ARRAY; - get_channels_factors(factors, p); + if (p->curve_type == DT_TONEEQ_CURVE_GAUSS) + { + // No cache : Build / Solve interpolation matrix + float gauss_factors[NUM_SLIDERS] DT_ALIGNED_ARRAY; + _gauss_get_channels_factors(gauss_factors, p); - float A[CHANNELS * PIXEL_CHAN] DT_ALIGNED_ARRAY; - build_interpolation_matrix(A, p->smoothing); - pseudo_solve(A, factors, CHANNELS, PIXEL_CHAN, FALSE); + const float sigma = powf(sqrtf(2.0f), 1.0f + p->smoothing); - dt_simd_memcpy(factors, d->factors, PIXEL_CHAN); - } + float A[NUM_SLIDERS * NUM_OCTAVES] DT_ALIGNED_ARRAY; + _gauss_build_interpolation_matrix(A, sigma); + pseudo_solve(A, gauss_factors, NUM_SLIDERS, NUM_OCTAVES, FALSE); - // compute the correction LUT here to spare some time in process - // when computing several times toneequalizer with same parameters - compute_correction_lut(d->correction_lut, d->smoothing, d->factors); + dt_simd_memcpy(gauss_factors, d->gauss_factors, NUM_OCTAVES); + } + else + { + // TODO MF: changing parameters in front or back? + _catmull_fill_array(d->catmull_y, p); + catmull_rom_tangents(d->catmull_y, d->catmull_tangents, p->smoothing); + } + } } -void init_pipe(dt_iop_module_t *self, - dt_dev_pixelpipe_t *pipe, - dt_dev_pixelpipe_iop_t *piece) +/**************************************************************************** + * + * GUI Helpers + * + ****************************************************************************/ +// empty marker function to make navigating the function list easier +__attribute__((unused)) static void GUI_HELPERS_MARKER() {} + +static inline void _compute_gui_histogram(dt_iop_toneequalizer_histogram_stats_t *hdr_histogram, + dt_iop_toneequalizer_ui_histogram_t *ui_histogram, + const float post_scale_base_log, + const float post_shift_base, + const float post_scale_log, + const float post_shift, + const float post_pivot) { - piece->data = dt_calloc1_align_type(dt_iop_toneequalizer_data_t); -} +#ifdef MF_DEBUG + printf("_compute_gui_histogram: scale=%f shift=%f value from hdr_histogram=%d ui_histogram->samples %d\n", histogram_scale, histogram_shift, hdr_histogram->samples[hdr_histogram->num_samples / 2], ui_histogram->num_samples); +#endif + // (Re)init the histogram + memset(ui_histogram->samples, 0, sizeof(int) * ui_histogram->num_samples); + const float hdr_ev_range = hdr_histogram->max_ev - hdr_histogram->min_ev; -void cleanup_pipe(dt_iop_module_t *self, - dt_dev_pixelpipe_t *pipe, - dt_dev_pixelpipe_iop_t *piece) + // scaling values shown to the user in the UI are logs + const float post_scale_base = exp2f(post_scale_base_log); + const float post_scale = exp2f(post_scale_log); + + // remap the extended histogram into the gui histogram + // bins between [-8; 0] EV remapped between [0 ; UI_HISTO_SAMPLES] + // TODO: OpenMP, parallel may be possible if collisions + // in ui_histogram->samples[i] are rare. + for(size_t k = 0; k < hdr_histogram->num_samples; ++k) + { + // from [0...num_samples] to [-16...8EV] + const float EV = hdr_ev_range * (float)k / (float)(hdr_histogram->num_samples - 1) + hdr_histogram->min_ev; + + // apply shift & scale to the EV value, clamp to [-8...0] + const float shift_scaled_EV = fast_clamp(_post_scale_shift(EV, post_scale_base, post_shift_base, post_scale, post_shift, post_pivot), DT_TONEEQ_MIN_EV, DT_TONEEQ_MAX_EV); + + // from [-8...0] EV to [0...UI_HISTO_SAMPLES] + const int i = (((shift_scaled_EV + 8.0f) / 8.0f) * (float)ui_histogram->num_samples); + + ui_histogram->samples[i] += hdr_histogram->samples[k]; + } + + // store the max numbers of elements in bins for later normalization + // ignore the first and last value to keep the histogram readable + int max_val_ignore_border_bins = 1; + DT_OMP_SIMD(reduction(max: max_val_ignore_border_bins)) + for (int i = 1; i < ui_histogram->num_samples - 1; i++) + { + max_val_ignore_border_bins = MAX(ui_histogram->samples[i], max_val_ignore_border_bins); + } + + // Compare the fist and last values too, so we have + // the overall maximum available as well + ui_histogram->max_val = MAX(hdr_histogram->samples[0], max_val_ignore_border_bins); + ui_histogram->max_val = MAX(hdr_histogram->samples[ui_histogram->num_samples - 1], ui_histogram->max_val); + ui_histogram->max_val_ignore_border_bins = max_val_ignore_border_bins; + // printf("_compute_gui_histogram: ui_histogram->max_val_ignore_border_bins=%d ui_histogram->max_val=%d\n", ui_histogram->max_val_ignore_border_bins, ui_histogram->max_val); + +} + +static inline void _update_gui_histogram(dt_iop_module_t *const self) { - dt_free_align(piece->data); - piece->data = NULL; + dt_iop_toneequalizer_gui_data_t *const g = self->gui_data; + dt_iop_toneequalizer_params_t *const p = self->params; + if(g == NULL) return; + + + dt_iop_gui_enter_critical_section(self); + if(!g->gui_histogram_valid && g->prv_luminance_valid) + { + // TODO MF: Pixelpipe full might not be ready yet, in this case we + // don't have auto-align values. Right now I have no idea + // how to solve this, other to draw no histogram at all. + + // compute_auto_post_scale_shift(p->post_auto_align, + // g->full_histogram_first_decile, g->full_histogram_last_decile, + // &p->post_scale, &p->post_shift, + // 999); + + _compute_gui_histogram(&g->mask_hdr_histo, &g->ui_histo, + p->post_scale_base, p->post_shift_base, + p->post_scale, p->post_shift, p->post_pivot); + + // Computation of "image_EV_per_UI_sample" + // The graph shows 8EV, but when we align the histogram, we consider 6EV [-7; -1] ("target") + const float target_EV_range = 6.0f; + const float full_EV_range = 8.0f; + const float target_to_full = full_EV_range / target_EV_range; + + // What is the real dynamic range of the histogram-part [-7; -1])? We unscale. + const float mask_EV_of_target = target_EV_range / (exp2f(p->post_scale)); + + // The histogram shows mask EV, but for evaluating curve steepness, we need image EVs + const float mask_to_image = (g->prv_image_ev_max - g->prv_image_ev_min) + / (g->mask_hdr_histo.max_ev - g->mask_hdr_histo.min_ev); + + g->image_EV_per_UI_sample = (mask_EV_of_target * mask_to_image * target_to_full) / (float)UI_HISTO_SAMPLES; + + // printf("_update_gui_histogram: image fist %f, image last %f, mask first %f, mask last %f", g->img_hdr_histo.lo_percentile_ev, g->img_hdr_histo.hi_percentile_ev, g->mask_hdr_histo.lo_percentile_ev, g->mask_hdr_histo.hi_percentile_ev); + + // if (g->show_two_histograms) + // _compute_gui_histogram(g->image_hdr_histogram, g->image_histogram, p->post_scale, p->post_shift, &g->image_max_histogram); + + g->gui_histogram_valid = TRUE; + } + dt_iop_gui_leave_critical_section(self); } -static void show_guiding_controls(dt_iop_module_t *self) +static void _show_guiding_controls(dt_iop_module_t *self) { dt_iop_toneequalizer_gui_data_t *g = self->gui_data; - const dt_iop_toneequalizer_params_t *p = self->params; + dt_iop_toneequalizer_params_t *p = self->params; - switch(p->details) + switch(p->filter) { case(DT_TONEEQ_NONE): { @@ -1694,37 +2866,61 @@ static void show_guiding_controls(dt_iop_module_t *self) gtk_widget_set_visible(g->iterations, TRUE); gtk_widget_set_visible(g->contrast_boost, TRUE); gtk_widget_set_visible(g->quantization, TRUE); - break; - } - } -} - -void update_exposure_sliders(dt_iop_toneequalizer_gui_data_t *g, - dt_iop_toneequalizer_params_t *p) -{ - ++darktable.gui->reset; - dt_bauhaus_slider_set(g->noise, p->noise); - dt_bauhaus_slider_set(g->ultra_deep_blacks, p->ultra_deep_blacks); - dt_bauhaus_slider_set(g->deep_blacks, p->deep_blacks); - dt_bauhaus_slider_set(g->blacks, p->blacks); - dt_bauhaus_slider_set(g->shadows, p->shadows); - dt_bauhaus_slider_set(g->midtones, p->midtones); - dt_bauhaus_slider_set(g->highlights, p->highlights); - dt_bauhaus_slider_set(g->whites, p->whites); - dt_bauhaus_slider_set(g->speculars, p->speculars); - --darktable.gui->reset; + break; + } + } + + switch (p->lum_estimator) { + case (DT_TONEEQ_CUSTOM): + gtk_widget_set_visible(g->lum_estimator_R, TRUE); + gtk_widget_set_visible(g->lum_estimator_G, TRUE); + gtk_widget_set_visible(g->lum_estimator_B, TRUE); + gtk_widget_set_visible(g->lum_estimator_normalize, TRUE); + break; + default: + gtk_widget_set_visible(g->lum_estimator_R, FALSE); + gtk_widget_set_visible(g->lum_estimator_G, FALSE); + gtk_widget_set_visible(g->lum_estimator_B, FALSE); + gtk_widget_set_visible(g->lum_estimator_normalize, FALSE); + } } +/**************************************************************************** + * + * GUI Callbacks + * + ****************************************************************************/ +// empty marker function to make navigating the function list easier +__attribute__((unused)) static void GUI_CALLBACKS_MARKER() {} + +void update_label_with_float(GtkLabel *label, float value) { + char buffer[32]; + // Format with 2 decimal places + snprintf(buffer, sizeof(buffer), "%.2f", value); + gtk_label_set_text(label, buffer); +} + void gui_update(dt_iop_module_t *self) { +#ifdef MF_DEBUG + printf("gui_update\n"); +#endif dt_iop_toneequalizer_gui_data_t *g = self->gui_data; dt_iop_toneequalizer_params_t *p = self->params; - dt_bauhaus_slider_set(g->smoothing, logf(p->smoothing) / logf(sqrtf(2.0f)) - 1.0f); +#ifdef MF_DEBUG + printf("gui_update: p->smoothing=%f\n", p->smoothing); +#endif + // TODO MF: not needed any more? + dt_bauhaus_slider_set(g->smoothing, p->smoothing); + + update_label_with_float(GTK_LABEL(g->label_base_scale), p->post_scale_base); + update_label_with_float(GTK_LABEL(g->label_base_shift), p->post_shift_base); - show_guiding_controls(self); - invalidate_luminance_cache(self); + _show_guiding_controls(self); + + _invalidate_luminance_cache(self); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(g->show_luminance_mask), g->mask_display); } @@ -1733,42 +2929,87 @@ void gui_changed(dt_iop_module_t *self, GtkWidget *w, void *previous) { +#ifdef MF_DEBUG + printf("gui_changed\n"); +#endif dt_iop_toneequalizer_gui_data_t *g = self->gui_data; + dt_iop_toneequalizer_params_t *p = self->params; - if(w == g->method - || w == g->blending + if(w == g->blending || w == g->feathering || w == g->iterations - || w == g->quantization) + || w == g->quantization + || w == g->lum_estimator_R + || w == g->lum_estimator_G + || w == g->lum_estimator_B + || w == g->lum_estimator_normalize + || w == g->pre_contrast_strength + || w == g->pre_contrast_width + || w == g->pre_contrast_midpoint) { - invalidate_luminance_cache(self); + _invalidate_luminance_cache(self); } - else if(w == g->details) + else if(w == g->filter + || w == g->lum_estimator) { - invalidate_luminance_cache(self); - show_guiding_controls(self); + _invalidate_luminance_cache(self); + _show_guiding_controls(self); } else if(w == g->contrast_boost || w == g->exposure_boost) { - invalidate_luminance_cache(self); + _invalidate_luminance_cache(self); dt_bauhaus_widget_set_quad_active(w, FALSE); } + else if (w == g->post_scale + || w == g->post_shift + || w == g->post_pivot) + { + _invalidate_lut_and_histogram(self); + } + else if (w == g->curve_type) + { + g->interpolation_valid = FALSE; + g->gauss_factors_valid = FALSE; + g->user_param_valid = FALSE; + g->gui_curve_valid = FALSE; + + switch(p->curve_type) + { + case(DT_TONEEQ_CURVE_GAUSS): + { + p->smoothing = 0.0f; + ++darktable.gui->reset; + dt_bauhaus_slider_set(g->smoothing, p->smoothing); + --darktable.gui->reset; + break; + } + case(DT_TONEEQ_CURVE_CATMULL): + { + p->smoothing = 0.5f; + ++darktable.gui->reset; + dt_bauhaus_slider_set(g->smoothing, p->smoothing); + --darktable.gui->reset; + break; + } + } + } } -static void smoothing_callback(GtkWidget *slider, dt_iop_module_t *self) +static void _smoothing_callback(GtkWidget *slider, + dt_iop_module_t *self) { if(darktable.gui->reset) return; dt_iop_toneequalizer_params_t *p = self->params; dt_iop_toneequalizer_gui_data_t *g = self->gui_data; - p->smoothing= powf(sqrtf(2.0f), 1.0f + dt_bauhaus_slider_get(slider)); - - float factors[CHANNELS] DT_ALIGNED_ARRAY; - get_channels_factors(factors, p); + p->smoothing = dt_bauhaus_slider_get(slider); +#ifdef MF_DEBUG + printf("smoothing_callback: p->smoothing=%f\n", p->smoothing); +#endif // Solve the interpolation by least-squares to check the validity of the smoothing param - if(!update_curve_lut(self)) + if(!_curve_interpolation(self)) dt_control_log (_("the interpolation is unstable, decrease the curve smoothing")); @@ -1781,7 +3022,108 @@ static void smoothing_callback(GtkWidget *slider, dt_iop_module_t *self) dt_iop_color_picker_reset(self, TRUE); } -static void auto_adjust_exposure_boost(GtkWidget *quad, dt_iop_module_t *self) +static gboolean _smoothing_button_press(GtkWidget *slider, + GdkEventButton *event, + dt_iop_module_t *self) { + // Double-click: reset to correct default value + if (event->type == GDK_2BUTTON_PRESS) { + dt_iop_toneequalizer_params_t *p = self->params; + switch(p->curve_type) + { + case(DT_TONEEQ_CURVE_GAUSS): + { + p->smoothing = 0.0f; + ++darktable.gui->reset; + dt_bauhaus_slider_set(slider, p->smoothing); + --darktable.gui->reset; + break; + } + case(DT_TONEEQ_CURVE_CATMULL): + { + p->smoothing = 0.5f; + ++darktable.gui->reset; + dt_bauhaus_slider_set(slider, p->smoothing); + --darktable.gui->reset; + break; + } + } + + return TRUE; // Event handled + } + return FALSE; // Event not handled, propagate further +} + +static void _auto_adjust_alignment(GtkWidget *btn, + GdkEventButton *event, + dt_iop_module_t *self) +{ + dt_iop_toneequalizer_params_t *p = self->params; + dt_iop_toneequalizer_gui_data_t *g = self->gui_data; + + if(darktable.gui->reset) return; + + dt_iop_request_focus(self); + + if(!self->enabled) + { + // activate module and do nothing + ++darktable.gui->reset; + dt_bauhaus_slider_set(g->contrast_boost, p->contrast_boost); + --darktable.gui->reset; + + _invalidate_luminance_cache(self); + dt_dev_add_history_item(darktable.develop, self, TRUE); + return; + } + + // Leftclick? + if (event->type != GDK_BUTTON_PRESS || event->button != 1) { + return; + } + + // Ctrl-click + if (event->state & GDK_CONTROL_MASK) { + p->post_scale_base = 0.0f; + p->post_shift_base = 0.0f; + //dt_iop_gui_enter_critical_section(self); + update_label_with_float(GTK_LABEL(g->label_base_scale), p->post_scale_base); + update_label_with_float(GTK_LABEL(g->label_base_shift), p->post_shift_base); + _invalidate_lut_and_histogram(self); + //dt_iop_gui_leave_critical_section(self); + dt_dev_add_history_item(darktable.develop, self, TRUE); + return; + } + + if(!g->prv_luminance_valid || self->dev->full.pipe->processing || !g->gui_histogram_valid) + { + dt_control_log(_("wait for the preview to finish recomputing")); + return; + } + + + const float post_scale_base_lin = 8.0f / (g->mask_hdr_histo.max_ev + - g->mask_hdr_histo.min_ev); + p->post_scale_base = log2f(post_scale_base_lin); + p->post_shift_base = -8.0f - (g->mask_hdr_histo.min_ev * post_scale_base_lin); + + printf("_auto_adjust_alignment: min_used_ev=%f, max_used_ev=%f, post_scale_base_lin=%f, post_shift_base=%f\n", g->mask_hdr_histo.min_ev, g->mask_hdr_histo.max_ev, post_scale_base_lin, p->post_shift_base); + + // The goal is to spread 90 % of the exposure histogram in the [-7, -1] EV + dt_iop_gui_enter_critical_section(self); + g->gui_histogram_valid = FALSE; + dt_iop_gui_leave_critical_section(self); + + update_label_with_float(GTK_LABEL(g->label_base_scale), p->post_scale_base); + update_label_with_float(GTK_LABEL(g->label_base_shift), p->post_shift_base); + _invalidate_lut_and_histogram(self); + dt_dev_add_history_item(darktable.develop, self, TRUE); + + // Unlock the colour picker so we can display our own custom cursor + dt_iop_color_picker_reset(self, TRUE); +} + +static void _auto_adjust_exposure_boost(GtkWidget *quad, + dt_iop_module_t *self) { dt_iop_toneequalizer_params_t *p = self->params; dt_iop_toneequalizer_gui_data_t *g = self->gui_data; @@ -1797,12 +3139,12 @@ static void auto_adjust_exposure_boost(GtkWidget *quad, dt_iop_module_t *self) dt_bauhaus_slider_set(g->exposure_boost, p->exposure_boost); --darktable.gui->reset; - invalidate_luminance_cache(self); + _invalidate_luminance_cache(self); dt_dev_add_history_item(darktable.develop, self, TRUE); return; } - if(!g->luminance_valid || self->dev->full.pipe->processing || !g->histogram_valid) + if(!g->prv_luminance_valid || self->dev->full.pipe->processing || !g->gui_histogram_valid) { dt_control_log(_("wait for the preview to finish recomputing")); return; @@ -1812,16 +3154,15 @@ static void auto_adjust_exposure_boost(GtkWidget *quad, dt_iop_module_t *self) // to spread it over as many nodes as possible for better exposure control. // Controls nodes are between -8 and 0 EV, // so we aim at centering the exposure distribution on -4 EV - dt_iop_gui_enter_critical_section(self); - g->histogram_valid = FALSE; + g->gui_histogram_valid = FALSE; dt_iop_gui_leave_critical_section(self); - update_histogram(self); + _update_gui_histogram(self); // calculate exposure correction - const float fd_new = exp2f(g->histogram_first_decile); - const float ld_new = exp2f(g->histogram_last_decile); + const float fd_new = exp2f(g->mask_hdr_histo.lo_percentile_ev); + const float ld_new = exp2f(g->mask_hdr_histo.hi_percentile_ev); const float e = exp2f(p->exposure_boost); const float c = exp2f(p->contrast_boost); // revert current transformation @@ -1839,15 +3180,15 @@ static void auto_adjust_exposure_boost(GtkWidget *quad, dt_iop_module_t *self) ++darktable.gui->reset; dt_bauhaus_slider_set(g->exposure_boost, p->exposure_boost); --darktable.gui->reset; - invalidate_luminance_cache(self); + _invalidate_luminance_cache(self); dt_dev_add_history_item(darktable.develop, self, TRUE); // Unlock the colour picker so we can display our own custom cursor dt_iop_color_picker_reset(self, TRUE); } - -static void auto_adjust_contrast_boost(GtkWidget *quad, dt_iop_module_t *self) +static void _auto_adjust_contrast_boost(GtkWidget *quad, + dt_iop_module_t *self) { dt_iop_toneequalizer_params_t *p = self->params; dt_iop_toneequalizer_gui_data_t *g = self->gui_data; @@ -1863,12 +3204,12 @@ static void auto_adjust_contrast_boost(GtkWidget *quad, dt_iop_module_t *self) dt_bauhaus_slider_set(g->contrast_boost, p->contrast_boost); --darktable.gui->reset; - invalidate_luminance_cache(self); + _invalidate_luminance_cache(self); dt_dev_add_history_item(darktable.develop, self, TRUE); return; } - if(!g->luminance_valid || self->dev->full.pipe->processing || !g->histogram_valid) + if(!g->prv_luminance_valid || self->dev->full.pipe->processing || !g->gui_histogram_valid) { dt_control_log(_("wait for the preview to finish recomputing")); return; @@ -1876,14 +3217,14 @@ static void auto_adjust_contrast_boost(GtkWidget *quad, dt_iop_module_t *self) // The goal is to spread 90 % of the exposure histogram in the [-7, -1] EV dt_iop_gui_enter_critical_section(self); - g->histogram_valid = FALSE; + g->gui_histogram_valid = FALSE; dt_iop_gui_leave_critical_section(self); - update_histogram(self); + _update_gui_histogram(self); // calculate contrast correction - const float fd_new = exp2f(g->histogram_first_decile); - const float ld_new = exp2f(g->histogram_last_decile); + const float fd_new = exp2f(g->mask_hdr_histo.lo_percentile_ev); + const float ld_new = exp2f(g->mask_hdr_histo.hi_percentile_ev); const float e = exp2f(p->exposure_boost); float c = exp2f(p->contrast_boost); // revert current transformation @@ -1900,7 +3241,7 @@ static void auto_adjust_contrast_boost(GtkWidget *quad, dt_iop_module_t *self) // when adding contrast, blur filters modify the histogram in a way // difficult to predict here we implement a heuristic correction // based on a set of images and regression analysis - if(p->details == DT_TONEEQ_EIGF && c > 0.0f) + if(p->filter == DT_TONEEQ_EIGF && c > 0.0f) { const float correction = -0.0276f + 0.01823 * p->feathering + (0.7566f - 1.0f) * c; if(p->feathering < 5.0f) @@ -1908,7 +3249,7 @@ static void auto_adjust_contrast_boost(GtkWidget *quad, dt_iop_module_t *self) else if(p->feathering < 10.0f) c += correction * (2.0f - p->feathering / 5.0f); } - else if(p->details == DT_TONEEQ_GUIDED && c > 0.0f) + else if(p->filter == DT_TONEEQ_GUIDED && c > 0.0f) c = 0.0235f + 1.1225f * c; p->contrast_boost += c; @@ -1917,17 +3258,16 @@ static void auto_adjust_contrast_boost(GtkWidget *quad, dt_iop_module_t *self) ++darktable.gui->reset; dt_bauhaus_slider_set(g->contrast_boost, p->contrast_boost); --darktable.gui->reset; - invalidate_luminance_cache(self); + _invalidate_luminance_cache(self); dt_dev_add_history_item(darktable.develop, self, TRUE); // Unlock the colour picker so we can display our own custom cursor dt_iop_color_picker_reset(self, TRUE); } - -static void show_luminance_mask_callback(GtkWidget *togglebutton, - GdkEventButton *event, - dt_iop_module_t *self) +static void _show_luminance_mask_callback(GtkWidget *togglebutton, + GdkEventButton *event, + dt_iop_module_t *self) { if(darktable.gui->reset) return; dt_iop_request_focus(self); @@ -1956,11 +3296,124 @@ static void show_luminance_mask_callback(GtkWidget *togglebutton, } -/*** +/**************************************************************************** + * * GUI Interactivity - **/ + * + ****************************************************************************/ +static void _get_point(dt_iop_module_t *self, const int c_x, const int c_y, int *x, int *y) +{ + // TODO: For this to fully work non depending on the place of the module + // in the pipe we need a dt_dev_distort_backtransform_plus that + // can skip crop only. With the current version if toneequalizer + // is moved below rotation & perspective it will fail as we are + // then missing all the transform after tone-eq. + const double crop_order = dt_ioppr_get_iop_order(self->dev->iop_order_list, "crop", 0); + + float pts[2] = { c_x, c_y }; + + // only a forward backtransform as the buffer already contains all the transforms + // done before toneequal and we are speaking of on-screen cursor coordinates. + // also we do transform only after crop as crop does change roi for the whole pipe + // and so it is already part of the preview buffer cached in this implementation. + dt_dev_distort_backtransform_plus(darktable.develop, darktable.develop->preview_pipe, crop_order, + DT_DEV_TRANSFORM_DIR_FORW_EXCL, pts, 1); + *x = pts[0]; + *y = pts[1]; +} + +__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 > 1 && 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; +} + +// unify with _get_luminance_from_buffer +static float _luminance_from_thumb_preview_buf(dt_iop_module_t *self) +{ + dt_iop_toneequalizer_gui_data_t *g = self->gui_data; + + const size_t c_x = g->cursor_pos_x; + const size_t c_y = g->cursor_pos_y; + + // get buffer x,y given the cursor position + int b_x = 0; + int b_y = 0; + + _get_point(self, c_x, c_y, &b_x, &b_y); + + return _get_luminance_from_buffer(g->preview_buf, + g->preview_buf_width, + g->preview_buf_height, + b_x, + b_y); +} + +void update_exposure_sliders(dt_iop_toneequalizer_gui_data_t *g, dt_iop_toneequalizer_params_t *p) +{ + // Params to GUI + ++darktable.gui->reset; + dt_bauhaus_slider_set(g->noise, p->noise); + dt_bauhaus_slider_set(g->ultra_deep_blacks, p->ultra_deep_blacks); + dt_bauhaus_slider_set(g->deep_blacks, p->deep_blacks); + dt_bauhaus_slider_set(g->blacks, p->blacks); + dt_bauhaus_slider_set(g->shadows, p->shadows); + dt_bauhaus_slider_set(g->midtones, p->midtones); + dt_bauhaus_slider_set(g->highlights, p->highlights); + dt_bauhaus_slider_set(g->whites, p->whites); + dt_bauhaus_slider_set(g->speculars, p->speculars); + --darktable.gui->reset; +} -static void switch_cursors(dt_iop_module_t *self) +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 _switch_cursors(dt_iop_module_t *self) { dt_iop_toneequalizer_gui_data_t *g = self->gui_data; @@ -1970,7 +3423,7 @@ static void switch_cursors(dt_iop_module_t *self) GtkWidget *widget = dt_ui_main_window(darktable.gui->ui); // if we are editing masks or using colour-pickers, do not display controls - if(in_mask_editing(self) + if(_in_mask_editing(self) || dt_iop_canvas_not_sensitive(self->dev)) { // display default cursor @@ -2051,6 +3504,7 @@ int mouse_moved(dt_iop_module_t *self, const dt_develop_t *dev = self->dev; dt_iop_toneequalizer_gui_data_t *g = self->gui_data; + dt_iop_toneequalizer_params_t *const p = self->params; if(g == NULL) return 0; @@ -2078,15 +3532,16 @@ int mouse_moved(dt_iop_module_t *self, dt_iop_gui_leave_critical_section(self); // store the actual exposure too, to spare I/O op - if(g->cursor_valid && !dev->full.pipe->processing && g->luminance_valid) - g->cursor_exposure = log2f(_luminance_from_module_buffer(self)); + if(g->cursor_valid && !dev->full.pipe->processing && g->prv_luminance_valid) { + const float lum = log2f(_luminance_from_thumb_preview_buf(self)); + g->cursor_exposure = fast_clamp(_post_scale_shift(lum, exp2f(p->post_scale_base), p->post_shift_base, exp2f(p->post_scale), p->post_shift, p->post_pivot), DT_TONEEQ_MIN_EV, DT_TONEEQ_MAX_EV); + } - switch_cursors(self); + _switch_cursors(self); return 1; } - int mouse_leave(dt_iop_module_t *self) { dt_iop_toneequalizer_gui_data_t *g = self->gui_data; @@ -2109,66 +3564,80 @@ int mouse_leave(dt_iop_module_t *self) return 1; } - -static inline gboolean set_new_params_interactive(const float control_exposure, - const float exposure_offset, - const float blending_sigma, - dt_iop_toneequalizer_gui_data_t *g, - dt_iop_toneequalizer_params_t *p) +static inline gboolean _set_new_params_interactive(const float control_exposure, + const float exposure_offset, + const float sigma, + dt_iop_toneequalizer_gui_data_t *g, + dt_iop_toneequalizer_params_t *p) { // Apply an exposure offset optimized smoothly over all the exposure channels, // taking user instruction to apply exposure_offset EV at control_exposure EV, - // and commit the new params is the solution is valid. + // and commit the new params if the solution is valid. // Raise the user params accordingly to control correction and // distance from cursor exposure to blend smoothly the desired // correction - const float std = gaussian_denom(blending_sigma); + + float std; + if (p->curve_type == DT_TONEEQ_CURVE_GAUSS) + std = _gaussian_denom(sigma * sigma / 2.0f); + else + // always small region for catmull + std = 1.0f; + if(g->user_param_valid) { - for(int i = 0; i < CHANNELS; ++i) + for(int i = 0; i < NUM_SLIDERS; ++i) g->temp_user_params[i] *= - exp2f(gaussian_func(centers_params[i] - control_exposure, std) * exposure_offset); + exp2f(_gaussian_func(centers_params[i] - control_exposure, std) * exposure_offset); } - // Get the new weights for the radial-basis approximation - float factors[CHANNELS] DT_ALIGNED_ARRAY; - dt_simd_memcpy(g->temp_user_params, factors, CHANNELS); - if(g->user_param_valid) - g->user_param_valid = pseudo_solve(g->interpolation_matrix, factors, CHANNELS, PIXEL_CHAN, TRUE); - if(!g->user_param_valid) - dt_control_log(_("the interpolation is unstable, decrease the curve smoothing")); - - // Compute new user params for channels and store them locally - if(g->user_param_valid) - g->user_param_valid = compute_channels_factors(factors, g->temp_user_params, g->sigma); - if(!g->user_param_valid) dt_control_log(_("some parameters are out-of-bounds")); - - const gboolean commit = g->user_param_valid; - - if(commit) + if (p->curve_type == DT_TONEEQ_CURVE_GAUSS) { - // Accept the solution - dt_simd_memcpy(factors, g->factors, PIXEL_CHAN); - g->lut_valid = FALSE; + // Get the new weights for the radial-basis approximation + float gauss_factors[NUM_SLIDERS] DT_ALIGNED_ARRAY; + dt_simd_memcpy(g->temp_user_params, gauss_factors, NUM_SLIDERS); + if(g->user_param_valid) // TODO MF: What is this fi for? + g->user_param_valid = pseudo_solve(g->gauss_interpolation_matrix, gauss_factors, NUM_SLIDERS, NUM_OCTAVES, TRUE); + if(!g->user_param_valid) + dt_control_log(_("the interpolation is unstable, decrease the curve smoothing")); + + // Compute new user params for NUM_SLIDERS and store them locally + if(g->user_param_valid) + g->user_param_valid = _gauss_compute_channels_factors(gauss_factors, g->temp_user_params, g->sigma); + if(!g->user_param_valid) dt_control_log(_("some parameters are out-of-bounds")); + + const gboolean commit = g->user_param_valid; + + if(commit) + { + // Accept the solution + dt_simd_memcpy(gauss_factors, g->gauss_factors, NUM_OCTAVES); + g->gui_curve_valid = FALSE; + + // Convert the linear temp parameters to log gains and commit + float gains[NUM_SLIDERS] DT_ALIGNED_ARRAY; + _compute_channels_gains(g->temp_user_params, gains); + _commit_channels_gains(gains, p); + } + else + { + // Reset the GUI copy of user params + _gauss_get_channels_factors(gauss_factors, p); + dt_simd_memcpy(gauss_factors, g->temp_user_params, NUM_SLIDERS); + g->user_param_valid = TRUE; + } - // Convert the linear temp parameters to log gains and commit - float gains[CHANNELS] DT_ALIGNED_ARRAY; - compute_channels_gains(g->temp_user_params, gains); - commit_channels_gains(gains, p); - } - else - { - // Reset the GUI copy of user params - get_channels_factors(factors, p); - dt_simd_memcpy(factors, g->temp_user_params, CHANNELS); - g->user_param_valid = TRUE; + return commit; } - return commit; + // CATMULL + float gains[NUM_SLIDERS] DT_ALIGNED_ARRAY; + _compute_channels_gains(g->temp_user_params, gains); + _commit_channels_gains(gains, p); + return TRUE; } - int scrolled(dt_iop_module_t *self, const float x, const float y, @@ -2187,14 +3656,20 @@ int scrolled(dt_iop_module_t *self, if(!self->enabled) if(self->off) gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(self->off), 1); - if(in_mask_editing(self)) return 0; + if(_in_mask_editing(self)) return 0; + + // ALT/Option should work for zooming + if (dt_modifier_is(state, GDK_MOD1_MASK)) return 0; // if GUI buffers not ready, exit but still handle the cursor dt_iop_gui_enter_critical_section(self); + printf("scrolled: !g->cursor_valid=%d !g->prv_luminance_valid=%d !g->interpolation_valid=%d !g->user_param_valid=%d dev->full.pipe->processing=%d !g->has_focus=%d\n", + !g->cursor_valid, !g->prv_luminance_valid, !g->interpolation_valid, !g->user_param_valid, dev->full.pipe->processing, !g->has_focus); + const gboolean fail = !g->cursor_valid - || !g->luminance_valid - || !g->interpolation_valid + || !g->prv_luminance_valid + || (p->curve_type == DT_TONEEQ_CURVE_GAUSS && !g->interpolation_valid) || !g->user_param_valid || dev->full.pipe->processing || !g->has_focus; @@ -2204,7 +3679,9 @@ int scrolled(dt_iop_module_t *self, // re-read the exposure in case it has changed dt_iop_gui_enter_critical_section(self); - g->cursor_exposure = log2f(_luminance_from_module_buffer(self)); + + const float lum = log2f(_luminance_from_thumb_preview_buf(self)); + g->cursor_exposure = fast_clamp(_post_scale_shift(lum, exp2f(p->post_scale_base), p->post_shift_base, exp2f(p->post_scale), p->post_shift, p->post_pivot), DT_TONEEQ_MIN_EV, DT_TONEEQ_MAX_EV); dt_iop_gui_leave_critical_section(self); @@ -2221,10 +3698,10 @@ int scrolled(dt_iop_module_t *self, const float offset = step * ((float)increment); - // Get the desired correction on exposure channels + // Get the desired correction on exposure NUM_SLIDERS dt_iop_gui_enter_critical_section(self); - const gboolean commit = set_new_params_interactive(g->cursor_exposure, offset, - g->sigma * g->sigma / 2.0f, g, p); + const gboolean commit = _set_new_params_interactive(g->cursor_exposure, offset, + g->sigma, g, p); dt_iop_gui_leave_critical_section(self); gtk_widget_queue_draw(GTK_WIDGET(g->area)); @@ -2240,9 +3717,14 @@ int scrolled(dt_iop_module_t *self, return 1; } -/*** + + /**************************************************************************** + * * GTK/Cairo drawings and custom widgets - **/ + * + ****************************************************************************/ +// empty marker function to make navigating the function list easier +__attribute__((unused)) static void GTK_CAIRO_MARKER() {} static inline gboolean _init_drawing(dt_iop_module_t *const restrict self, GtkWidget *widget, @@ -2277,9 +3759,9 @@ void cairo_draw_hatches(cairo_t *cr, } } -static void get_shade_from_luminance(cairo_t *cr, - const float luminance, - const float alpha) +static void _get_shade_from_luminance(cairo_t *cr, + const float luminance, + const float alpha) { // TODO: fetch screen gamma from ICC display profile const float gamma = 1.0f / 2.2f; @@ -2287,22 +3769,21 @@ static void get_shade_from_luminance(cairo_t *cr, cairo_set_source_rgba(cr, shade, shade, shade, alpha); } - -static void draw_exposure_cursor(cairo_t *cr, - const double pointerx, - const double pointery, - const double radius, - const float luminance, - const float zoom_scale, - const int instances, - const float alpha) +static void _draw_exposure_cursor(cairo_t *cr, + const double pointerx, + const double pointery, + const double radius, + const float luminance, + const float zoom_scale, + const int instances, + const float alpha) { // Draw a circle cursor filled with a grey shade corresponding to a luminance value // or hatches if the value is above the overexposed threshold const double radius_z = radius / zoom_scale; - get_shade_from_luminance(cr, luminance, alpha); + _get_shade_from_luminance(cr, luminance, alpha); cairo_arc(cr, pointerx, pointery, radius_z, 0, 2 * M_PI); cairo_fill_preserve(cr); cairo_save(cr); @@ -2319,10 +3800,9 @@ static void draw_exposure_cursor(cairo_t *cr, cairo_restore(cr); } - -static void match_color_to_background(cairo_t *cr, - const float exposure, - const float alpha) +static void _match_color_to_background(cairo_t *cr, + const float exposure, + const float alpha) { float shade = 0.0f; // TODO: put that as a preference in darktablerc @@ -2333,10 +3813,9 @@ static void match_color_to_background(cairo_t *cr, else shade = (fmaxf(exposure / contrast, -5.0f) + 2.5f); - get_shade_from_luminance(cr, exp2f(shade), alpha); + _get_shade_from_luminance(cr, exp2f(shade), alpha); } - void gui_post_expose(dt_iop_module_t *self, cairo_t *cr, const float width, @@ -2349,14 +3828,16 @@ void gui_post_expose(dt_iop_module_t *self, dt_develop_t *dev = self->dev; dt_iop_toneequalizer_gui_data_t *g = self->gui_data; + dt_iop_toneequalizer_params_t *p = self->params; // if we are editing masks, do not display controls - if(in_mask_editing(self)) return; + if(_in_mask_editing(self)) return; dt_iop_gui_enter_critical_section(self); const gboolean fail = !g->cursor_valid - || !g->interpolation_valid + || (p->curve_type == DT_TONEEQ_CURVE_GAUSS && !g->interpolation_valid) + || (p->curve_type == DT_TONEEQ_CURVE_CATMULL && !g->gui_curve_valid) || dev->full.pipe->processing || !g->has_focus; @@ -2369,8 +3850,10 @@ void gui_post_expose(dt_iop_module_t *self, return; // re-read the exposure in case it has changed - if(g->luminance_valid && self->enabled) - g->cursor_exposure = log2f(_luminance_from_module_buffer(self)); + if(g->prv_luminance_valid && self->enabled) { + const float lum = log2f(_luminance_from_thumb_preview_buf(self)); + g->cursor_exposure = _post_scale_shift(lum, exp2f(p->post_scale_base), p->post_shift_base, exp2f(p->post_scale), p->post_shift, p->post_pivot); + } dt_iop_gui_enter_critical_section(self); @@ -2383,14 +3866,18 @@ void gui_post_expose(dt_iop_module_t *self, float correction = 0.0f; float exposure_out = 0.0f; float luminance_out = 0.0f; - if(g->luminance_valid && self->enabled) + if(g->prv_luminance_valid && self->enabled) { // Get the corresponding exposure exposure_in = g->cursor_exposure; luminance_in = exp2f(exposure_in); // Get the corresponding correction and compute resulting exposure - correction = log2f(pixel_correction(exposure_in, g->factors, g->sigma)); + if (p->curve_type == DT_TONEEQ_CURVE_GAUSS) + correction = log2f(_gauss_pixel_correction(exposure_in, g->gauss_factors, g->sigma)); + else // CATMULL + correction = log2f(catmull_rom_val(NUM_SLIDERS, DT_TONEEQ_MIN_EV, exposure_in, g->catmull_y, g->catmull_tangents)); + exposure_out = exposure_in + correction; luminance_out = exp2f(exposure_out); } @@ -2406,7 +3893,7 @@ void gui_post_expose(dt_iop_module_t *self, const double fill_width = DT_PIXEL_APPLY_DPI(4. / zoom_scale); // setting fill bars - match_color_to_background(cr, exposure_out, 1.0); + _match_color_to_background(cr, exposure_out, 1.0); cairo_set_line_width(cr, 2.0 * fill_width); cairo_move_to(cr, x_pointer - setting_offset_x, y_pointer); @@ -2438,9 +3925,9 @@ void gui_post_expose(dt_iop_module_t *self, cairo_stroke(cr); // draw exposure cursor - draw_exposure_cursor(cr, x_pointer, y_pointer, outer_radius, + _draw_exposure_cursor(cr, x_pointer, y_pointer, outer_radius, luminance_in, zoom_scale, 6, .9); - draw_exposure_cursor(cr, x_pointer, y_pointer, inner_radius, + _draw_exposure_cursor(cr, x_pointer, y_pointer, inner_radius, luminance_out, zoom_scale, 3, .9); // Create Pango objects : texts @@ -2458,7 +3945,7 @@ void gui_post_expose(dt_iop_module_t *self, pango_cairo_context_set_resolution(pango_layout_get_context(layout), darktable.gui->dpi); // Build text object - if(g->luminance_valid && self->enabled) + if(g->prv_luminance_valid && self->enabled) snprintf(text, sizeof(text), _("%+.1f EV"), exposure_in); else snprintf(text, sizeof(text), "? EV"); @@ -2466,7 +3953,7 @@ void gui_post_expose(dt_iop_module_t *self, pango_layout_get_pixel_extents(layout, &ink, NULL); // Draw the text plain blackground - get_shade_from_luminance(cr, luminance_out, 0.75); + _get_shade_from_luminance(cr, luminance_out, 0.75); cairo_rectangle(cr, x_pointer + (outer_radius + 2. * g->inner_padding) / zoom_scale, y_pointer - ink.y - ink.height / 2.0 - g->inner_padding / zoom_scale, @@ -2475,7 +3962,7 @@ void gui_post_expose(dt_iop_module_t *self, cairo_fill(cr); // Display the EV reading - match_color_to_background(cr, exposure_out, 1.0); + _match_color_to_background(cr, exposure_out, 1.0); cairo_move_to(cr, x_pointer + (outer_radius + 4. * g->inner_padding) / zoom_scale, y_pointer - ink.y - ink.height / 2.); pango_cairo_show_layout(cr, layout); @@ -2485,13 +3972,13 @@ void gui_post_expose(dt_iop_module_t *self, pango_font_description_free(desc); g_object_unref(layout); - if(g->luminance_valid && self->enabled) + if(g->prv_luminance_valid && self->enabled) { // Search for nearest node in graph and highlight it const float radius_threshold = 0.45f; g->area_active_node = -1; if(g->cursor_valid) - for(int i = 0; i < CHANNELS; ++i) + for(int i = 0; i < NUM_SLIDERS; ++i) { const float delta_x = fabsf(g->cursor_exposure - centers_params[i]); if(delta_x < radius_threshold) @@ -2507,7 +3994,7 @@ static void _develop_distort_callback(gpointer instance, { dt_iop_toneequalizer_gui_data_t *g = self->gui_data; if(g == NULL) return; - if(!g->distort_signal_actif) return; + if(!g->distort_signal_active) return; /* disable the distort signal now to avoid recursive call on this signal as we are about to reprocess the preview pipe which has some module doing distortion. */ @@ -2523,30 +4010,33 @@ static void _develop_distort_callback(gpointer instance, static void _set_distort_signal(dt_iop_module_t *self) { dt_iop_toneequalizer_gui_data_t *g = self->gui_data; - if(self->enabled && !g->distort_signal_actif) + if(self->enabled && !g->distort_signal_active) { DT_CONTROL_SIGNAL_HANDLE(DT_SIGNAL_DEVELOP_DISTORT, _develop_distort_callback); - g->distort_signal_actif = TRUE; + g->distort_signal_active = TRUE; } } static void _unset_distort_signal(dt_iop_module_t *self) { dt_iop_toneequalizer_gui_data_t *g = self->gui_data; - if(g->distort_signal_actif) + if(g->distort_signal_active) { DT_CONTROL_SIGNAL_DISCONNECT(_develop_distort_callback, self); - g->distort_signal_actif = FALSE; + g->distort_signal_active = FALSE; } } void gui_focus(dt_iop_module_t *self, gboolean in) { +#ifdef MF_DEBUG + printf("gui_focus %d\n", in); +#endif dt_iop_toneequalizer_gui_data_t *g = self->gui_data; dt_iop_gui_enter_critical_section(self); g->has_focus = in; dt_iop_gui_leave_critical_section(self); - switch_cursors(self); + _switch_cursors(self); if(!in) { //lost focus - stop showing mask @@ -2570,7 +4060,6 @@ void gui_focus(dt_iop_module_t *self, gboolean in) } } - static inline gboolean _init_drawing(dt_iop_module_t *const restrict self, GtkWidget *widget, dt_iop_toneequalizer_gui_data_t *const restrict g) @@ -2580,8 +4069,10 @@ static inline gboolean _init_drawing(dt_iop_module_t *const restrict self, if(g->cst) cairo_surface_destroy(g->cst); + + g->graph_w_gradients_height = g->allocation.height - DT_RESIZE_HANDLE_SIZE - g->inner_padding; g->cst = dt_cairo_image_surface_create(CAIRO_FORMAT_ARGB32, - g->allocation.width, g->allocation.height); + g->allocation.width, g->graph_w_gradients_height); if(g->cr) cairo_destroy(g->cr); @@ -2621,7 +4112,7 @@ static inline gboolean _init_drawing(dt_iop_module_t *const restrict self, // align the right border on sliders: g->graph_width = g->allocation.width - g->inset - 2.0 * g->line_height; // give room to nodes: - g->graph_height = g->allocation.height - g->inset - 2.0 * g->line_height; + g->graph_height = g->graph_w_gradients_height - g->inset - 2.0 * g->line_height; g->gradient_left_limit = 0.0; g->gradient_right_limit = g->graph_width; g->gradient_top_limit = g->graph_height + 2 * g->inner_padding; @@ -2629,7 +4120,7 @@ static inline gboolean _init_drawing(dt_iop_module_t *const restrict self, g->legend_top_limit = -0.5 * g->line_height - 2.0 * g->inner_padding; g->x_label = g->graph_width + g->sign_width + 3.0 * g->inner_padding; - gtk_render_background(g->context, g->cr, 0, 0, g->allocation.width, g->allocation.height); + gtk_render_background(g->context, g->cr, 0, 0, g->allocation.width, g->graph_w_gradients_height); // set the graph as the origin of the coordinates cairo_translate(g->cr, g->line_height + 2 * g->inner_padding, @@ -2640,10 +4131,10 @@ static inline gboolean _init_drawing(dt_iop_module_t *const restrict self, float value = -8.0f; - for(int k = 0; k < CHANNELS; k++) + for(int k = 0; k < NUM_SLIDERS; k++) { const float xn = - (((float)k) / ((float)(CHANNELS - 1))) * g->graph_width - g->sign_width; + (((float)k) / ((float)(NUM_SLIDERS - 1))) * g->graph_width - g->sign_width; snprintf(text, sizeof(text), "%+.0f", value); pango_layout_set_text(g->layout, text, -1); @@ -2712,42 +4203,138 @@ static inline gboolean _init_drawing(dt_iop_module_t *const restrict self, return TRUE; } - // must be called while holding self->gui_lock -static inline void init_nodes_x(dt_iop_toneequalizer_gui_data_t *g) +static inline void _init_nodes_x(dt_iop_toneequalizer_gui_data_t *g) { if(g == NULL) return; if(!g->valid_nodes_x && g->graph_width > 0) { - for(int i = 0; i < CHANNELS; ++i) - g->nodes_x[i] = (((float)i) / ((float)(CHANNELS - 1))) * g->graph_width; + for(int i = 0; i < NUM_SLIDERS; ++i) + g->nodes_x[i] = (((float)i) / ((float)(NUM_SLIDERS - 1))) * g->graph_width; g->valid_nodes_x = TRUE; } } +// must be called while holding self->gui_lock +static inline void _init_nodes_y(dt_iop_toneequalizer_gui_data_t *g) +{ + if(g == NULL) return; + + if(g->user_param_valid && g->graph_height > 0) + { + for(int i = 0; i < NUM_SLIDERS; ++i) + g->nodes_y[i] = // assumes factors in [-2 ; 2] EV + (0.5 - log2f(g->temp_user_params[i]) / 4.0) * g->graph_height; + g->valid_nodes_y = TRUE; + } +} + +static inline void _interpolate_gui_color(GdkRGBA a, + GdkRGBA b, + float t, + GdkRGBA *out) +{ + float t_clamp = fast_clamp(t, 0.0f, 1.0f); + out->red = a.red + t_clamp * (b.red - a.red); + out->green = a.green + t_clamp * (b.green - a.green); + out->blue = a.blue + t_clamp * (b.blue - a.blue); + out->alpha = a.alpha + t_clamp * (b.alpha - a.alpha); +} + +static inline void _compute_gui_curve_colors(dt_iop_module_t *self) +{ + dt_iop_toneequalizer_gui_data_t *g = self->gui_data; + dt_iop_toneequalizer_params_t *p = self->params; + + const float *const restrict curve = g->gui_curve; + GdkRGBA *const restrict colors = g->gui_curve_colors; + const gboolean filter_active = (p->filter != DT_TONEEQ_NONE); + const float ev_dx = g->image_EV_per_UI_sample; + + const GdkRGBA standard = darktable.bauhaus->graph_fg; + const GdkRGBA warning = {0.75, 0.5, 0.0, 1.0}; + const GdkRGBA error = {1.0, 0.0, 0.0, 1.0}; + GdkRGBA temp_color = {0.0, 0.0, 0.0, 1.0}; + + const int shadows_limit = (int)UI_HISTO_SAMPLES * 0.3333; + const int highlights_limit = (int)UI_HISTO_SAMPLES * 0.6666; + + if (!g->gui_histogram_valid || !g->gui_curve_valid) { + // the module is not completely initialized, set all colors to standard + for(int k = 0; k < UI_HISTO_SAMPLES; k++) + colors[k] = standard; + return; + }; + + colors[0] = standard; + for(int k = 1; k < UI_HISTO_SAMPLES; k++) + { + float ev_dy = (curve[k] - curve[k - 1]); + float steepness = ev_dy / ev_dx; + colors[k] = standard; -// must be called while holding self->gui_lock -static inline void init_nodes_y(dt_iop_toneequalizer_gui_data_t *g) -{ - if(g == NULL) return; + if(filter_active && k < shadows_limit && curve[k] < 0.0f) + { + // Lower shadows with filter active, this does not provide the local + // contrast that the user probably expects. + const float x_dist = ((float)(shadows_limit - k) / (float)UI_HISTO_SAMPLES) * 8.0f; + const float color_dist = fminf(x_dist, -curve[k]); + _interpolate_gui_color(standard, warning, color_dist, &temp_color); + colors[k] = temp_color; + } + else if(filter_active && k > highlights_limit && curve[k] > 0.0f) + { + // Raise highlights with filter active, this does not provide the local + // contrast that the user probably expects. + const float x_dist = ((float)(k - highlights_limit) / (float)UI_HISTO_SAMPLES) * 8.0f; + const float color_dist = fminf(x_dist, curve[k]); + _interpolate_gui_color(standard, warning, color_dist, &temp_color); + colors[k] = temp_color; + } + else if(!filter_active && k < shadows_limit && curve[k] > 0.0f) + { + // Raise shadows without filter, this leads to a loss of contrast. + const float x_dist = ((float)(shadows_limit - k) / (float)UI_HISTO_SAMPLES) * 8.0f; + const float color_dist = fminf(x_dist, curve[k]); + _interpolate_gui_color(standard, warning, color_dist, &temp_color); + colors[k] = temp_color; + } + else if(!filter_active && k > highlights_limit && curve[k] < 0.0f) + { + // Lower highlights without filter, this leads to a loss of contrast. + const float x_dist = ((float)(k - highlights_limit) / (float)UI_HISTO_SAMPLES) * 8.0f; + const float color_dist = fminf(x_dist, -curve[k]); + _interpolate_gui_color(standard, warning, color_dist, &temp_color); + colors[k] = temp_color; + } - if(g->user_param_valid && g->graph_height > 0) - { - for(int i = 0; i < CHANNELS; ++i) - g->nodes_y[i] = // assumes factors in [-2 ; 2] EV - (0.5 - log2f(g->temp_user_params[i]) / 4.0) * g->graph_height; - g->valid_nodes_y = TRUE; + // Too steep downward slopes. + // These warnings take precedence, even if the segment was already + // colored, we overwrite the colors here. + if(steepness < -0.5f && steepness > -1.0f) + { + colors[k] = warning; + } + else if(steepness <= -1.0f) + { + colors[k] = error; + } + +#ifdef MF_DEBUG + // printf("curve[%d]=%f ev_dx=%f ev_dy=%f steepness=%f colors[%d]=%f\n", k, curve[k], ev_dx, ev_dy, steepness, k, colors[k].red); +#endif } } - -static gboolean area_draw(GtkWidget *widget, - cairo_t *cr, - dt_iop_module_t *self) +static gboolean _area_draw(GtkWidget *widget, + cairo_t *cr, + dt_iop_module_t *self) { // Draw the widget equalizer view dt_iop_toneequalizer_gui_data_t *g = self->gui_data; + dt_iop_toneequalizer_params_t *p = self->params; + if(g == NULL) return FALSE; // Init or refresh the drawing cache @@ -2767,15 +4354,45 @@ static gboolean area_draw(GtkWidget *widget, dt_iop_gui_leave_critical_section(self); // Refresh cached UI elements - update_histogram(self); - update_curve_lut(self); + _update_gui_histogram(self); + _curve_interpolation(self); - // Draw graph background + // The colors depend on the histogram and the curve + _compute_gui_curve_colors(self); + + // Draw graph background cairo_set_line_width(g->cr, DT_PIXEL_APPLY_DPI(0.5)); cairo_rectangle(g->cr, 0, 0, g->graph_width, g->graph_height); set_color(g->cr, darktable.bauhaus->graph_bg); cairo_fill(g->cr); + // draw warnings if outside of module range + if (g->gui_histogram_valid && self->enabled) + { + // Histograms are computed from -24 to +8 EV. + // Draw warnings if parts outside of this area end up in the graph + // after shift/scale. + GdkRGBA warning_color; + GdkRGBA red = {1.0, 0.0, 0.0, 1.0}; + _interpolate_gui_color(darktable.bauhaus->graph_bg, red, 0.1f, &warning_color); + const float hdr_min_scaled = _post_scale_shift(HDR_MIN_EV, exp2f(p->post_scale_base), p->post_shift_base, exp2f(p->post_scale), p->post_shift, p->post_pivot); + if (hdr_min_scaled > DT_TONEEQ_MIN_EV) + { + const float end_x = fast_clamp((hdr_min_scaled + 8.0f) / 8.0f, 0.0f, 1.0f); + cairo_rectangle(g->cr, 0, 0, end_x * g->graph_width, g->graph_height); + set_color(g->cr, warning_color); + cairo_fill(g->cr); + } + const float hdr_max_scaled = _post_scale_shift(HDR_MAX_EV, exp2f(p->post_scale_base), p->post_shift_base, exp2f(p->post_scale), p->post_shift, p->post_pivot); + if (hdr_max_scaled < DT_TONEEQ_MAX_EV) + { + const float start_x = fast_clamp((hdr_max_scaled + 8.0f) / 8.0f, 0.0f, 1.0f); + cairo_rectangle(g->cr, start_x * g->graph_width, 0, (1.0f - start_x) * g->graph_width, g->graph_height); + set_color(g->cr, warning_color); + cairo_fill(g->cr); + } + } + // draw grid cairo_set_line_width(g->cr, DT_PIXEL_APPLY_DPI(0.5)); set_color(g->cr, darktable.bauhaus->graph_border); @@ -2788,26 +4405,27 @@ static gboolean area_draw(GtkWidget *widget, cairo_line_to(g->cr, g->graph_width, 0.5 * g->graph_height); cairo_stroke(g->cr); - if(g->histogram_valid && self->enabled) + if(g->gui_histogram_valid && self->enabled) { - // draw the inset histogram + dt_iop_toneequalizer_ui_histogram_t *histo = &g->ui_histo; + // draw the mask histogram background set_color(g->cr, darktable.bauhaus->inset_histogram); cairo_set_line_width(g->cr, DT_PIXEL_APPLY_DPI(4.0)); cairo_move_to(g->cr, 0, g->graph_height); - for(int k = 0; k < UI_SAMPLES; k++) + for(int k = 0; k < histo->num_samples; k++) { // the x range is [-8;+0] EV - const float x_temp = (8.0 * (float)k / (float)(UI_SAMPLES - 1)) - 8.0; - const float y_temp = (float)(g->histogram[k]) / (float)(g->max_histogram) * 0.96; + const float x_temp = (8.0 * (float)k / (float)(UI_HISTO_SAMPLES - 1)) - 8.0; + const float y_temp = 1.0f - fast_clamp((float)(histo->samples[k]) / (float)(histo->max_val), 0.0f, 1.0f) * 0.96; cairo_line_to(g->cr, (x_temp + 8.0) * g->graph_width / 8.0, - (1.0 - y_temp) * g->graph_height ); + (g->graph_height * y_temp)); } cairo_line_to(g->cr, g->graph_width, g->graph_height); cairo_close_path(g->cr); cairo_fill(g->cr); - if(g->histogram_last_decile > -0.1f) + if(_post_scale_shift(g->mask_hdr_histo.hi_percentile_ev, exp2f(p->post_scale_base), p->post_shift_base, exp2f(p->post_scale), p->post_shift, p->post_pivot) > -0.1f) { // histogram overflows controls in highlights : display warning cairo_save(g->cr); @@ -2819,7 +4437,7 @@ static gboolean area_draw(GtkWidget *widget, cairo_restore(g->cr); } - if(g->histogram_first_decile < -7.9f) + if(_post_scale_shift(g->mask_hdr_histo.lo_percentile_ev, exp2f(p->post_scale_base), p->post_shift_base, exp2f(p->post_scale), p->post_shift, p->post_pivot) < -7.9f) { // histogram overflows controls in lowlights : display warning cairo_save(g->cr); @@ -2832,37 +4450,53 @@ static gboolean area_draw(GtkWidget *widget, } } - if(g->lut_valid) + // TODO MF: The order of operations has become a bit complicated here + // - The thin (unscaled) curve should be under bullets and bars + // - The thick (scaled) curve should be above the bars, but under the bullets + + if(g->gui_curve_valid && p->scale_curve != 1.0f) { - // draw the interpolation curve - set_color(g->cr, darktable.bauhaus->graph_fg); - cairo_move_to(g->cr, 0, g->gui_lut[0] * g->graph_height); - cairo_set_line_width(g->cr, DT_PIXEL_APPLY_DPI(3)); + // draw the thin unscaled curve - for(int k = 1; k < UI_SAMPLES; k++) + float x_draw, y_draw; + + // The coloring of the curve makes it necessary to draw it as individual segments. + // However this led to aliasing artifacts, therefore we draw overlapping segments + // from k-1 to k+1. + // unscaled curve + cairo_set_line_width(g->cr, DT_PIXEL_APPLY_DPI(1)); + set_color(g->cr, darktable.bauhaus->graph_fg); + for(int k = 1; k < UI_HISTO_SAMPLES - 1; k++) { - // the x range is [-8;+0] EV - const float x_temp = (8.0f * (((float)k) / ((float)(UI_SAMPLES - 1)))) - 8.0f; - const float y_temp = g->gui_lut[k]; - cairo_line_to(g->cr, (x_temp + 8.0f) * g->graph_width / 8.0f, - y_temp * g->graph_height ); + // Map [0;UI_HISTO_SAMPLES] to [0;1] and then to g->graph_width. + x_draw = ((float)(k - 1) / (float)(UI_HISTO_SAMPLES - 1)) * g->graph_width; + // Map [-2;+2] EV to graph_height, with graph pixel 0 at the top + y_draw = (0.5f - g->gui_curve[k - 1] / 4.0f) * g->graph_height; + + cairo_move_to(g->cr, x_draw, y_draw); + + // Map [0;UI_HISTO_SAMPLES] to [0;1] and then to g->graph_width. + x_draw = ((float)(k+1) / (float)(UI_HISTO_SAMPLES - 1)) * g->graph_width; + // Map [-2;+2] EV to graph_height, with graph pixel 0 at the top + y_draw = (0.5f - g->gui_curve[k+1] / 4.0f) * g->graph_height; + + cairo_line_to(g->cr, x_draw, y_draw); + cairo_stroke(g->cr); } - cairo_stroke(g->cr); } dt_iop_gui_enter_critical_section(self); - init_nodes_x(g); + _init_nodes_x(g); dt_iop_gui_leave_critical_section(self); dt_iop_gui_enter_critical_section(self); - init_nodes_y(g); + _init_nodes_y(g); dt_iop_gui_leave_critical_section(self); if(g->user_param_valid) { - // draw nodes positions - for(int k = 0; k < CHANNELS; k++) + for(int k = 0; k < NUM_SLIDERS; k++) { const float xn = g->nodes_x[k]; const float yn = g->nodes_y[k]; @@ -2873,6 +4507,44 @@ static gboolean area_draw(GtkWidget *widget, cairo_move_to(g->cr, xn, 0.5 * g->graph_height); cairo_line_to(g->cr, xn, yn); cairo_stroke(g->cr); + } + } + + if(g->gui_curve_valid) + { + // draw the interpolation curve + + float x_draw, y_draw; + + cairo_set_line_width(g->cr, DT_PIXEL_APPLY_DPI(3)); + for(int k = 1; k < UI_HISTO_SAMPLES - 1; k++) + { + set_color(g->cr, g->gui_curve_colors[k]); + + // Map [0;UI_HISTO_SAMPLES] to [0;1] and then to g->graph_width. + x_draw = ((float)(k - 1) / (float)(UI_HISTO_SAMPLES - 1)) * g->graph_width; + // Map [-2;+2] EV to graph_height, with graph pixel 0 at the top + y_draw = (0.5f - (g->gui_curve[k - 1] * p->scale_curve) / 4.0f) * g->graph_height; + + cairo_move_to(g->cr, x_draw, y_draw); + + // Map [0;UI_HISTO_SAMPLES] to [0;1] and then to g->graph_width. + x_draw = ((float)(k+1) / (float)(UI_HISTO_SAMPLES - 1)) * g->graph_width; + // Map [-2;+2] EV to graph_height, with graph pixel 0 at the top + y_draw = (0.5f - (g->gui_curve[k + 1] * p->scale_curve) / 4.0f) * g->graph_height; + + cairo_line_to(g->cr, x_draw, y_draw); + cairo_stroke(g->cr); + } + } + + if(g->user_param_valid) + { + // draw nodes positions + for(int k = 0; k < NUM_SLIDERS; k++) + { + const float xn = g->nodes_x[k]; + const float yn = g->nodes_y[k]; // bullets cairo_set_line_width(g->cr, DT_PIXEL_APPLY_DPI(3)); @@ -2893,11 +4565,17 @@ static gboolean area_draw(GtkWidget *widget, { if(g->area_cursor_valid) { - const float radius = g->sigma * g->graph_width / 8.0f / sqrtf(2.0f); + float radius; + if (p->curve_type == DT_TONEEQ_CURVE_GAUSS) + radius = g->sigma * g->graph_width / 8.0f / sqrtf(2.0f); + else + // small ring for catmull + radius = g->graph_width / 10.0f; + cairo_set_line_width(g->cr, DT_PIXEL_APPLY_DPI(1.5)); - const float y = - g->gui_lut[(int)CLAMP(((UI_SAMPLES - 1) * g->area_x / g->graph_width), - 0, UI_SAMPLES - 1)]; + const float y = 0.5f - + g->gui_curve[(int)CLAMP(((UI_HISTO_SAMPLES - 1) * g->area_x / g->graph_width), + 0, UI_HISTO_SAMPLES - 1)] / 4.0f; cairo_arc(g->cr, g->area_x, y * g->graph_height, radius, 0, 2. * M_PI); set_color(g->cr, darktable.bauhaus->graph_fg); cairo_stroke(g->cr); @@ -2908,13 +4586,13 @@ static gboolean area_draw(GtkWidget *widget, float x_pos = (g->cursor_exposure + 8.0f) / 8.0f * g->graph_width; - if(x_pos > g->graph_width || x_pos < 0.0f) + if(x_pos >= g->graph_width || x_pos <= 0.0f) { // exposure at current position is outside [-8; 0] EV : // bound it in the graph limits and show it in orange cairo_set_source_rgb(g->cr, 0.75, 0.50, 0.); cairo_set_line_width(g->cr, DT_PIXEL_APPLY_DPI(3)); - x_pos = (x_pos < 0.0f) ? 0.0f : g->graph_width; + x_pos = (x_pos <= 0.0f) ? 0.0f : g->graph_width; } else { @@ -2932,81 +4610,12 @@ static gboolean area_draw(GtkWidget *widget, cairo_set_source_surface(cr, g->cst, 0, 0); cairo_paint(cr); - return TRUE; -} - -static gboolean _toneequalizer_bar_draw(GtkWidget *widget, - cairo_t *crf, - dt_iop_module_t *self) -{ - // Draw the widget equalizer view - dt_iop_toneequalizer_gui_data_t *g = self->gui_data; - - update_histogram(self); - - GtkAllocation allocation; - gtk_widget_get_allocation(widget, &allocation); - cairo_surface_t *cst = dt_cairo_image_surface_create(CAIRO_FORMAT_ARGB32, - allocation.width, allocation.height); - cairo_t *cr = cairo_create(cst); - - // draw background - set_color(cr, darktable.bauhaus->graph_bg); - cairo_rectangle(cr, 0, 0, allocation.width, allocation.height); - cairo_fill_preserve(cr); - cairo_clip(cr); - - dt_iop_gui_enter_critical_section(self); - - if(g->histogram_valid) - { - // draw histogram span - const float left = (g->histogram_first_decile + 8.0f) / 8.0f; - const float right = (g->histogram_last_decile + 8.0f) / 8.0f; - const float width = (right - left); - set_color(cr, darktable.bauhaus->inset_histogram); - cairo_rectangle(cr, left * allocation.width, 0, - width * allocation.width, allocation.height); - cairo_fill(cr); - - // draw average bar - set_color(cr, darktable.bauhaus->graph_fg); - cairo_set_line_width(cr, DT_PIXEL_APPLY_DPI(3)); - const float average = (g->histogram_average + 8.0f) / 8.0f; - cairo_move_to(cr, average * allocation.width, 0.0); - cairo_line_to(cr, average * allocation.width, allocation.height); - cairo_stroke(cr); - - // draw clipping bars - cairo_set_source_rgb(cr, 0.75, 0.50, 0); - cairo_set_line_width(cr, DT_PIXEL_APPLY_DPI(6)); - if(g->histogram_first_decile < -7.9f) - { - cairo_move_to(cr, DT_PIXEL_APPLY_DPI(3), 0.0); - cairo_line_to(cr, DT_PIXEL_APPLY_DPI(3), allocation.height); - cairo_stroke(cr); - } - if(g->histogram_last_decile > - 0.1f) - { - cairo_move_to(cr, allocation.width - DT_PIXEL_APPLY_DPI(3), 0.0); - cairo_line_to(cr, allocation.width - DT_PIXEL_APPLY_DPI(3), allocation.height); - cairo_stroke(cr); - } - } - - dt_iop_gui_leave_critical_section(self); - - cairo_set_source_surface(crf, cst, 0, 0); - cairo_paint(crf); - cairo_destroy(cr); - cairo_surface_destroy(cst); - return TRUE; + return FALSE; // Draw the handle next } - -static gboolean area_enter_leave_notify(GtkWidget *widget, - GdkEventCrossing *event, - dt_iop_module_t *self) +static gboolean _area_enter_leave_notify(GtkWidget *widget, + GdkEventCrossing *event, + dt_iop_module_t *self) { if(darktable.gui->reset) return TRUE; if(!self->enabled) return FALSE; @@ -3037,12 +4646,10 @@ static gboolean area_enter_leave_notify(GtkWidget *widget, return FALSE; } - -static gboolean area_button_press(GtkWidget *widget, - GdkEventButton *event, - dt_iop_module_t *self) +static gboolean _area_button_press(GtkWidget *widget, + GdkEventButton *event, + dt_iop_module_t *self) { - if(darktable.gui->reset) return TRUE; dt_iop_toneequalizer_gui_data_t *g = self->gui_data; @@ -3084,7 +4691,7 @@ static gboolean area_button_press(GtkWidget *widget, { dt_dev_add_history_item(darktable.develop, self, TRUE); } - return TRUE; + return FALSE; } // Unlock the colour picker so we can display our own custom cursor @@ -3093,10 +4700,9 @@ static gboolean area_button_press(GtkWidget *widget, return FALSE; } - -static gboolean area_motion_notify(GtkWidget *widget, - GdkEventMotion *event, - dt_iop_module_t *self) +static gboolean _area_motion_notify(GtkWidget *widget, + GdkEventMotion *event, + dt_iop_module_t *self) { if(darktable.gui->reset) return TRUE; if(!self->enabled) return FALSE; @@ -3113,8 +4719,8 @@ static gboolean area_motion_notify(GtkWidget *widget, const float cursor_exposure = g->area_x / g->graph_width * 8.0f - 8.0f; // Get the desired correction on exposure channels - g->area_dragging = set_new_params_interactive(cursor_exposure, offset, - g->sigma * g->sigma / 2.0f, g, p); + g->area_dragging = _set_new_params_interactive(cursor_exposure, offset, + g->sigma, g, p); dt_iop_gui_leave_critical_section(self); } @@ -3131,7 +4737,7 @@ static gboolean area_motion_notify(GtkWidget *widget, if(g->valid_nodes_x) { const float radius_threshold = fabsf(g->nodes_x[1] - g->nodes_x[0]) * 0.45f; - for(int i = 0; i < CHANNELS; ++i) + for(int i = 0; i < NUM_SLIDERS; ++i) { const float delta_x = fabsf(g->area_x - g->nodes_x[i]); if(delta_x < radius_threshold) @@ -3144,13 +4750,12 @@ static gboolean area_motion_notify(GtkWidget *widget, dt_iop_gui_leave_critical_section(self); gtk_widget_queue_draw(GTK_WIDGET(g->area)); - return TRUE; + return FALSE; } - -static gboolean area_button_release(GtkWidget *widget, - GdkEventButton *event, - dt_iop_module_t *self) +static gboolean _area_button_release(GtkWidget *widget, + GdkEventButton *event, + dt_iop_module_t *self) { if(darktable.gui->reset) return TRUE; if(!self->enabled) return FALSE; @@ -3175,23 +4780,41 @@ static gboolean area_button_release(GtkWidget *widget, g->area_dragging = FALSE; dt_iop_gui_leave_critical_section(self); - return TRUE; + return FALSE; } } return FALSE; } -static gboolean area_scroll(GtkWidget *widget, - GdkEventScroll *event, - gpointer user_data) +static gboolean _area_scroll(GtkWidget *widget, + GdkEventScroll *event, + gpointer user_data) { // do not propagate to tab bar unless scrolling sidebar return !dt_gui_ignore_scroll(event); } -static gboolean notebook_button_press(GtkWidget *widget, - GdkEventButton *event, - dt_iop_module_t *self) +static gboolean _warning_icon_draw(GtkWidget *widget, + cairo_t *cr, + dt_iop_module_t *self) +{ + dt_iop_toneequalizer_gui_data_t *g = self->gui_data; + + if (g->warning_icon_active) + { + int h = gtk_widget_get_allocated_height(widget); + int s = MIN(gtk_widget_get_allocated_width(widget), h); + int v_margin = (h - s) / 2; + + cairo_set_source_rgb(cr, 0.75, 0.50, 0.); + dtgtk_cairo_paint_gamut_check(cr, 0.1 * s, v_margin + 0.1 * s, 0.8 * s, 0.8 * s, 0, NULL); + } + return TRUE; +} + +static gboolean _notebook_button_press(GtkWidget *widget, + GdkEventButton *event, + dt_iop_module_t *self) { if(darktable.gui->reset) return TRUE; @@ -3222,13 +4845,15 @@ GSList *mouse_actions(dt_iop_module_t *self) /** * Post pipe events **/ - static void _develop_ui_pipe_started_callback(gpointer instance, dt_iop_module_t *self) { +#ifdef MF_DEBUG + printf("ui pipe started callback\n"); +#endif dt_iop_toneequalizer_gui_data_t *g = self->gui_data; if(g == NULL) return; - switch_cursors(self); + _switch_cursors(self); if(!self->expanded || !self->enabled) { @@ -3246,10 +4871,12 @@ static void _develop_ui_pipe_started_callback(gpointer instance, --darktable.gui->reset; } - static void _develop_preview_pipe_finished_callback(gpointer instance, dt_iop_module_t *self) { +#ifdef MF_DEBUG + printf("preview pipe finished callback\n"); +#endif dt_iop_toneequalizer_gui_data_t *g = self->gui_data; if(g == NULL) return; @@ -3259,18 +4886,21 @@ static void _develop_preview_pipe_finished_callback(gpointer instance, // reprocess of the preview has been scheduled. _set_distort_signal(self); - switch_cursors(self); + _switch_cursors(self); gtk_widget_queue_draw(GTK_WIDGET(g->area)); - gtk_widget_queue_draw(GTK_WIDGET(g->bar)); + // gtk_widget_queue_draw(GTK_WIDGET(g->bar)); } - static void _develop_ui_pipe_finished_callback(gpointer instance, dt_iop_module_t *self) { +#ifdef MF_DEBUG + printf("ui pipe finished callback\n"); +#endif dt_iop_toneequalizer_gui_data_t *g = self->gui_data; if(g == NULL) return; - switch_cursors(self); + + _switch_cursors(self); } void gui_reset(dt_iop_module_t *self) @@ -3286,20 +4916,166 @@ void gui_reset(dt_iop_module_t *self) gtk_widget_queue_draw(GTK_WIDGET(g->area)); } +// empty marker function to make navigating the function list easier +__attribute__((unused)) static void GUI_INIT_MARKER() {} void gui_init(dt_iop_module_t *self) { dt_iop_toneequalizer_gui_data_t *g = IOP_GUI_ALLOC(toneequalizer); - gui_cache_init(self); + _gui_cache_init(self); + + g->area = GTK_DRAWING_AREA(dt_ui_resize_wrap(NULL, + 0, + "plugins/darkroom/toneequal/graphheight")); + + // Main Drawing area + GtkWidget *wrapper = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); // for CSS size + gtk_box_pack_start(GTK_BOX(wrapper), GTK_WIDGET(g->area), TRUE, TRUE, 0); + g_object_set_data(G_OBJECT(wrapper), "iop-instance", self); + gtk_widget_set_name(GTK_WIDGET(wrapper), "toneeqgraph"); + dt_action_define_iop(self, NULL, N_("graph"), GTK_WIDGET(wrapper), NULL); + + gtk_widget_add_events(GTK_WIDGET(g->area), + GDK_POINTER_MOTION_MASK | darktable.gui->scroll_mask + | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK + | GDK_ENTER_NOTIFY_MASK | GDK_LEAVE_NOTIFY_MASK); + gtk_widget_set_can_focus(GTK_WIDGET(g->area), TRUE); + g_signal_connect(G_OBJECT(g->area), "draw", G_CALLBACK(_area_draw), self); + g_signal_connect(G_OBJECT(g->area), "button-press-event", + G_CALLBACK(_area_button_press), self); + g_signal_connect(G_OBJECT(g->area), "button-release-event", + G_CALLBACK(_area_button_release), self); + g_signal_connect(G_OBJECT(g->area), "leave-notify-event", + G_CALLBACK(_area_enter_leave_notify), self); + g_signal_connect(G_OBJECT(g->area), "enter-notify-event", + G_CALLBACK(_area_enter_leave_notify), self); + g_signal_connect(G_OBJECT(g->area), "motion-notify-event", + G_CALLBACK(_area_motion_notify), self); + g_signal_connect(G_OBJECT(g->area), "scroll-event", + G_CALLBACK(_area_scroll), self); + gtk_widget_set_tooltip_text(GTK_WIDGET(g->area), _("double-click to reset the curve")); + // Notebook (tabs) static dt_action_def_t notebook_def = { }; g->notebook = dt_ui_notebook_new(¬ebook_def); dt_action_define_iop(self, NULL, N_("page"), GTK_WIDGET(g->notebook), ¬ebook_def); - // Simple view + // Main view (former "advanced" page) + self->widget = dt_ui_notebook_page(g->notebook, N_("alignment"), NULL); + gtk_widget_set_vexpand(GTK_WIDGET(self->widget), TRUE); + + // Row with align button + GtkWidget *box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); + GtkWidget *lbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); + GtkWidget *spacer = gtk_label_new(NULL); + GtkWidget *rbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); + + g->align_button = gtk_button_new_with_label(N_("align")); + gtk_widget_set_tooltip_text + (g->align_button, + _("ctrl-click to set alignment to 0.")); + g_signal_connect(g->align_button, "button-press-event", G_CALLBACK(_auto_adjust_alignment), self); + + g->warning_icon_area = GTK_DRAWING_AREA(gtk_drawing_area_new()); + // gtk_widget_set_vexpand(GTK_WIDGET(g->warning_icon_area), TRUE); + g_signal_connect(G_OBJECT(g->warning_icon_area), "draw", G_CALLBACK(_warning_icon_draw), self); + gtk_widget_set_size_request(GTK_WIDGET(g->warning_icon_area), 20, -1); + + GtkWidget *shift_label = gtk_label_new(_("base shift:")); + g->label_base_shift = GTK_LABEL(gtk_label_new("+0.00")); + + GtkWidget *scale_label = gtk_label_new(_(" scale:")); + g->label_base_scale = GTK_LABEL(gtk_label_new("+0.00")); + + gtk_box_pack_start(GTK_BOX(lbox), g->align_button, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(lbox), GTK_WIDGET(g->warning_icon_area), FALSE, FALSE, 2); + + gtk_box_pack_start(GTK_BOX(rbox), shift_label, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(rbox), GTK_WIDGET(g->label_base_shift), FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(rbox), scale_label, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(rbox), GTK_WIDGET(g->label_base_scale), FALSE, FALSE, 0); + + gtk_box_pack_start(GTK_BOX(box), GTK_WIDGET(lbox), FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(box), spacer, TRUE, TRUE, 0); + gtk_box_pack_end(GTK_BOX(box), GTK_WIDGET(rbox), FALSE, FALSE, 0); + + gtk_box_pack_start(GTK_BOX(self->widget), box, FALSE, FALSE, 0); - self->widget = dt_ui_notebook_page(g->notebook, N_("simple"), NULL); + // g->pre_processing_label = dt_ui_section_label_new(C_("section", "mask pre-processing")); + // gtk_box_pack_start(GTK_BOX(self->widget), + // g->pre_processing_label, + // FALSE, FALSE, 0); + + GtkWidget *section_label = dt_ui_section_label_new(C_("section", "manual alignment")); + gtk_box_pack_start(GTK_BOX(self->widget), + section_label, + FALSE, FALSE, 0); + + g->post_shift = dt_bauhaus_slider_from_params(self, "post_shift"); + dt_bauhaus_slider_set_soft_range(g->post_shift, -4.0, 4.0); + gtk_widget_set_tooltip_text + (g->post_shift, + _("set the mask exposure / shift the histogram")); + + g->post_scale = dt_bauhaus_slider_from_params(self, "post_scale"); + dt_bauhaus_slider_set_soft_range(g->post_scale, -2.0, 2.0); + gtk_widget_set_tooltip_text + (g->post_scale, + _("set the mask contrast / scale the histogram")); + + g->post_pivot = dt_bauhaus_slider_from_params(self, "post_pivot"); + gtk_widget_set_tooltip_text + (g->post_pivot, + _("pivot point for scaling the histogram")); + + self->widget = dt_ui_notebook_page(g->notebook, N_("exposure"), NULL); + + g->global_exposure = dt_bauhaus_slider_from_params(self, "global_exposure"); + dt_bauhaus_slider_set_soft_range(g->global_exposure, -4.0, 4.0); + gtk_widget_set_tooltip_text + (g->global_exposure, + _("globally brighten/darken the image")); + + g->scale_curve = dt_bauhaus_slider_from_params(self, "scale_curve"); + dt_bauhaus_slider_set_soft_range(g->scale_curve, 0.0, 2.0); + gtk_widget_set_tooltip_text + (g->global_exposure, + _("scale the curve vertically")); + + g->smoothing = dt_bauhaus_slider_new_with_range(self, -2.33f, +1.67f, 0, 0.0f, 2); + dt_bauhaus_slider_set_soft_range(g->smoothing, -1.0f, 1.0f); + dt_bauhaus_widget_set_label(g->smoothing, NULL, N_("curve smoothing")); + gtk_widget_set_tooltip_text(g->smoothing, + _("positive values will produce more progressive tone transitions\n" + "but the curve might become oscillatory in some settings.\n" + "negative values will avoid oscillations and behave more robustly\n" + "but may produce brutal tone transitions and damage local contrast.")); + gtk_box_pack_start(GTK_BOX(self->widget), g->smoothing, FALSE, FALSE, 0); + g_signal_connect(G_OBJECT(g->smoothing), "value-changed", G_CALLBACK(_smoothing_callback), self); + g_signal_connect(G_OBJECT(g->smoothing), "button-press-event", G_CALLBACK(_smoothing_button_press), self); + + g->curve_type = dt_bauhaus_combobox_from_params(self, "curve_type"); + dt_bauhaus_widget_set_label(g->curve_type, NULL, N_("curve type")); + gtk_widget_set_tooltip_text( + g->curve_type, _("curve_type")); + + // sliders section (former "simple" page) + dt_gui_new_collapsible_section(&g->sliders_section, "plugins/darkroom/toneequal/expand_sliders", _("sliders"), + GTK_BOX(self->widget), DT_ACTION(self)); + gtk_widget_set_tooltip_text(g->sliders_section.expander, _("sliders")); + + // TODO MF dirty hack: + // dt_gui_new_collapsible_section always uses gtk_box_pack_end to align the collapsible + // section at the bottom of the parent container. + // I want the collapsible section to be aligned at the top, therefore I remove it from the + // parent again and pack it manually. + g_object_ref(g->sliders_section.expander); + gtk_container_remove(GTK_CONTAINER(self->widget), g->sliders_section.expander); + gtk_box_pack_start(GTK_BOX(self->widget), g->sliders_section.expander, FALSE, FALSE, 0); + g_object_unref(g->sliders_section.expander); + + self->widget = GTK_WIDGET(g->sliders_section.container); g->noise = dt_bauhaus_slider_from_params(self, "noise"); dt_bauhaus_slider_set_format(g->noise, _(" EV")); @@ -3338,131 +5114,76 @@ void gui_init(dt_iop_module_t *self) dt_bauhaus_widget_set_label(g->whites, N_("simple"), N_("-1 EV")); dt_bauhaus_widget_set_label(g->speculars, N_("simple"), N_("+0 EV")); - // Advanced view - - self->widget = dt_ui_notebook_page(g->notebook, N_("advanced"), NULL); - - g->area = GTK_DRAWING_AREA(gtk_drawing_area_new()); - GtkWidget *wrapper = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); // for CSS size - gtk_box_pack_start(GTK_BOX(wrapper), GTK_WIDGET(g->area), TRUE, TRUE, 0); - g_object_set_data(G_OBJECT(wrapper), "iop-instance", self); - gtk_widget_set_name(GTK_WIDGET(wrapper), "toneeqgraph"); - dt_action_define_iop(self, NULL, N_("graph"), GTK_WIDGET(wrapper), NULL); - gtk_box_pack_start(GTK_BOX(self->widget), GTK_WIDGET(wrapper), TRUE, TRUE, 0); - gtk_widget_add_events(GTK_WIDGET(g->area), - GDK_POINTER_MOTION_MASK | darktable.gui->scroll_mask - | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK - | GDK_ENTER_NOTIFY_MASK | GDK_LEAVE_NOTIFY_MASK); - gtk_widget_set_can_focus(GTK_WIDGET(g->area), TRUE); - g_signal_connect(G_OBJECT(g->area), "draw", G_CALLBACK(area_draw), self); - g_signal_connect(G_OBJECT(g->area), "button-press-event", - G_CALLBACK(area_button_press), self); - g_signal_connect(G_OBJECT(g->area), "button-release-event", - G_CALLBACK(area_button_release), self); - g_signal_connect(G_OBJECT(g->area), "leave-notify-event", - G_CALLBACK(area_enter_leave_notify), self); - g_signal_connect(G_OBJECT(g->area), "enter-notify-event", - G_CALLBACK(area_enter_leave_notify), self); - g_signal_connect(G_OBJECT(g->area), "motion-notify-event", - G_CALLBACK(area_motion_notify), self); - g_signal_connect(G_OBJECT(g->area), "scroll-event", - G_CALLBACK(area_scroll), self); - gtk_widget_set_tooltip_text(GTK_WIDGET(g->area), _("double-click to reset the curve")); - - g->smoothing = dt_bauhaus_slider_new_with_range(self, -2.33f, +1.67f, 0, 0.0f, 2); - dt_bauhaus_slider_set_soft_range(g->smoothing, -1.0f, 1.0f); - dt_bauhaus_widget_set_label(g->smoothing, NULL, N_("curve smoothing")); - gtk_widget_set_tooltip_text - (g->smoothing, - _("positive values will produce more progressive tone transitions\n" - "but the curve might become oscillatory in some settings.\n" - "negative values will avoid oscillations and behave more robustly\n" - "but may produce brutal tone transitions and damage local contrast.")); - gtk_box_pack_start(GTK_BOX(self->widget), g->smoothing, FALSE, FALSE, 0); - g_signal_connect(G_OBJECT(g->smoothing), "value-changed", - G_CALLBACK(smoothing_callback), self); - // Masking options - self->widget = dt_ui_notebook_page(g->notebook, N_("masking"), NULL); - - g->method = dt_bauhaus_combobox_from_params(self, "method"); - gtk_widget_set_tooltip_text - (g->method, - _("preview the mask and chose the estimator that gives you the\n" - "higher contrast between areas to dodge and areas to burn")); - - g->details = dt_bauhaus_combobox_from_params(self, N_("details")); - dt_bauhaus_widget_set_label(g->details, NULL, N_("preserve details")); - gtk_widget_set_tooltip_text - (g->details, - _("'no' affects global and local contrast (safe if you only add contrast)\n" - "'guided filter' only affects global contrast and tries to preserve local contrast\n" - "'averaged guided filter' is a geometric mean of 'no' and 'guided filter' methods\n" - "'EIGF' (exposure-independent guided filter) is a guided filter that is" - " exposure-independent, it smooths shadows and highlights the same way" - " (contrary to guided filter which smooths less the highlights)\n" - "'averaged EIGF' is a geometric mean of 'no' and 'exposure-independent" - " guided filter' methods")); + GtkWidget *masking_page = self->widget; + + // guided filter section + dt_gui_new_collapsible_section(&g->guided_filter_section, "plugins/darkroom/toneequal/expand_sliders", + _("guided filter"), GTK_BOX(masking_page), DT_ACTION(self)); + gtk_widget_set_tooltip_text(g->guided_filter_section.expander, _("guided filter")); + + // Hack to make the collapsible section align at the top + g_object_ref(g->guided_filter_section.expander); + gtk_container_remove(GTK_CONTAINER(masking_page), g->guided_filter_section.expander); + gtk_box_pack_start(GTK_BOX(masking_page), g->guided_filter_section.expander, FALSE, FALSE, 0); + g_object_unref(g->guided_filter_section.expander); + + self->widget = GTK_WIDGET(g->guided_filter_section.container); + + g->filter = dt_bauhaus_combobox_from_params(self, N_("filter")); + dt_bauhaus_widget_set_label(g->filter, NULL, N_("preserve details")); + gtk_widget_set_tooltip_text( + g->filter, _("'no' affects global and local contrast (safe if you only add contrast)\n" + "'guided filter' only affects global contrast and tries to preserve local contrast\n" + "'averaged guided filter' is a geometric mean of 'no' and 'guided filter' methods\n" + "'EIGF' (exposure-independent guided filter) is a guided filter that is" + " exposure-independent, it smooths shadows and highlights the same way" + " (contrary to guided filter which smooths less the highlights)\n" + "'averaged EIGF' is a geometric mean of 'no' and 'exposure-independent" + " guided filter' methods")); g->iterations = dt_bauhaus_slider_from_params(self, "iterations"); dt_bauhaus_slider_set_soft_max(g->iterations, 5); - gtk_widget_set_tooltip_text - (g->iterations, - _("number of passes of guided filter to apply\n" - "helps diffusing the edges of the filter at the expense of speed")); + gtk_widget_set_tooltip_text(g->iterations, _("number of passes of guided filter to apply\n" + "helps diffusing the edges of the filter at the expense of speed")); g->blending = dt_bauhaus_slider_from_params(self, "blending"); dt_bauhaus_slider_set_soft_range(g->blending, 1.0, 45.0); dt_bauhaus_slider_set_format(g->blending, "%"); - gtk_widget_set_tooltip_text - (g->blending, - _("diameter of the blur in percent of the largest image size\n" - "warning: big values of this parameter can make the darkroom\n" - "preview much slower if denoise profiled is used.")); + gtk_widget_set_tooltip_text(g->blending, _("diameter of the blur in percent of the largest image size\n" + "warning: big values of this parameter can make the darkroom\n" + "preview much slower if denoise profiled is used.")); g->feathering = dt_bauhaus_slider_from_params(self, "feathering"); dt_bauhaus_slider_set_soft_range(g->feathering, 0.1, 50.0); - gtk_widget_set_tooltip_text - (g->feathering, - _("precision of the feathering:\n" - "higher values force the mask to follow edges more closely\n" - "but may void the effect of the smoothing\n" - "lower values give smoother gradients and better smoothing\n" - "but may lead to inaccurate edges taping and halos")); + gtk_widget_set_tooltip_text(g->feathering, _("precision of the feathering:\n" + "higher values force the mask to follow edges more closely\n" + "but may void the effect of the smoothing\n" + "lower values give smoother gradients and better smoothing\n" + "but may lead to inaccurate edges taping and halos")); - gtk_box_pack_start(GTK_BOX(self->widget), - dt_ui_section_label_new(C_("section", "mask post-processing")), - FALSE, FALSE, 0); + // Collapsible section mask pre-processing + dt_gui_new_collapsible_section(&g->pre_processing_section, "plugins/darkroom/toneequal/expand_mask_proprocessing", + _("mask pre-processing"), GTK_BOX(masking_page), DT_ACTION(self)); + gtk_widget_set_tooltip_text(g->pre_processing_section.expander, _("mask pre-processing")); - g->bar = GTK_DRAWING_AREA(gtk_drawing_area_new()); - gtk_widget_set_size_request(GTK_WIDGET(g->bar), -1, 4); - gtk_box_pack_start(GTK_BOX(self->widget), GTK_WIDGET(g->bar), TRUE, TRUE, 0); - gtk_widget_set_can_focus(GTK_WIDGET(g->bar), TRUE); - g_signal_connect(G_OBJECT(g->bar), "draw", - G_CALLBACK(_toneequalizer_bar_draw), self); - gtk_widget_set_tooltip_text - (GTK_WIDGET(g->bar), - _("mask histogram span between the first and last deciles.\n" - "the central line shows the average. orange bars appear at extrema" - " if clipping occurs.")); + // Hack to make the collapsible section align at the top + g_object_ref(g->pre_processing_section.expander); + gtk_container_remove(GTK_CONTAINER(masking_page), g->pre_processing_section.expander); + gtk_box_pack_start(GTK_BOX(masking_page), g->pre_processing_section.expander, FALSE, FALSE, 0); + g_object_unref(g->pre_processing_section.expander); - g->quantization = dt_bauhaus_slider_from_params(self, "quantization"); - dt_bauhaus_slider_set_format(g->quantization, _(" EV")); - gtk_widget_set_tooltip_text - (g->quantization, - _("0 disables the quantization.\n" - "higher values posterize the luminance mask to help the guiding\n" - "produce piece-wise smooth areas when using high feathering values")); + self->widget = GTK_WIDGET(g->pre_processing_section.container); g->exposure_boost = dt_bauhaus_slider_from_params(self, "exposure_boost"); dt_bauhaus_slider_set_soft_range(g->exposure_boost, -4.0, 4.0); dt_bauhaus_slider_set_format(g->exposure_boost, _(" EV")); gtk_widget_set_tooltip_text (g->exposure_boost, - _("use this to slide the mask average exposure along channels\n" + _("use this to slide the mask average exposure along sliders\n" "for a better control of the exposure correction with the available nodes.")); - dt_bauhaus_widget_set_quad(g->exposure_boost, self, dtgtk_cairo_paint_wand, FALSE, auto_adjust_exposure_boost, + dt_bauhaus_widget_set_quad(g->exposure_boost, self, dtgtk_cairo_paint_wand, FALSE, _auto_adjust_exposure_boost, _("auto-adjust the average exposure")); g->contrast_boost = dt_bauhaus_slider_from_params(self, "contrast_boost"); @@ -3472,11 +5193,88 @@ void gui_init(dt_iop_module_t *self) (g->contrast_boost, _("use this to counter the averaging effect of the guided filter\n" "and dilate the mask contrast around -4EV\n" - "this allows to spread the exposure histogram over more channels\n" + "this allows to spread the exposure histogram over more sliders\n" "for a better control of the exposure correction.")); - dt_bauhaus_widget_set_quad(g->contrast_boost, self, dtgtk_cairo_paint_wand, FALSE, auto_adjust_contrast_boost, + dt_bauhaus_widget_set_quad(g->contrast_boost, self, dtgtk_cairo_paint_wand, FALSE, _auto_adjust_contrast_boost, _("auto-adjust the contrast")); + section_label = dt_ui_section_label_new(C_("section", "targeted mask contrast")); + gtk_box_pack_start(GTK_BOX(self->widget), + section_label, + FALSE, FALSE, 0); + + g->pre_contrast_strength = dt_bauhaus_slider_from_params(self, "pre_contrast_strength"); + gtk_widget_set_tooltip_text(g->pre_contrast_strength, _("amount of targeted contrast to apply before guided filter\n")); + + g->pre_contrast_width = dt_bauhaus_slider_from_params(self, "pre_contrast_width"); + gtk_widget_set_tooltip_text(g->pre_contrast_width, _("tonal range of mask that is made more contrasty before the guided filter\n")); + + g->pre_contrast_midpoint = dt_bauhaus_slider_from_params(self, "pre_contrast_midpoint"); + gtk_widget_set_tooltip_text(g->pre_contrast_midpoint, _("center of targeted contrast\n")); + + self->widget = masking_page; + + // Collapsible section "advanced" + dt_gui_new_collapsible_section(&g->lum_estimator_section, "plugins/darkroom/toneequal/expand_luminance_estimator", + _("luminance estimator"), GTK_BOX(masking_page), DT_ACTION(self)); + gtk_widget_set_tooltip_text(g->lum_estimator_section.expander, _("luminance estimator")); + + // Hack to make the collapsible section align at the top + g_object_ref(g->lum_estimator_section.expander); + gtk_container_remove(GTK_CONTAINER(masking_page), g->lum_estimator_section.expander); + gtk_box_pack_start(GTK_BOX(masking_page), g->lum_estimator_section.expander, FALSE, FALSE, 0); + g_object_unref(g->lum_estimator_section.expander); + + self->widget = GTK_WIDGET(g->lum_estimator_section.container); + + g->lum_estimator = dt_bauhaus_combobox_from_params(self, "lum_estimator"); + gtk_widget_set_tooltip_text(g->lum_estimator, _("preview the mask and chose the estimator that gives you the\n" + "higher contrast between areas to dodge and areas to burn")); + + g->lum_estimator_R = dt_bauhaus_slider_from_params(self, "lum_estimator_R"); + dt_bauhaus_slider_set_soft_range(g->lum_estimator_R, 0.0, 1.0); + gtk_widget_set_tooltip_text(g->lum_estimator_R, _("red weight for greyscale mask\n")); + + g->lum_estimator_G = dt_bauhaus_slider_from_params(self, "lum_estimator_G"); + dt_bauhaus_slider_set_soft_range(g->lum_estimator_G, 0.0, 1.0); + gtk_widget_set_tooltip_text(g->lum_estimator_G, _("green weight for greyscale mask\n")); + + g->lum_estimator_B = dt_bauhaus_slider_from_params(self, "lum_estimator_B"); + dt_bauhaus_slider_set_soft_range(g->lum_estimator_B, 0.0, 1.0); + gtk_widget_set_tooltip_text(g->lum_estimator_B, _("blue weight for greyscale mask\n")); + + g->lum_estimator_normalize = dt_bauhaus_toggle_from_params + (self, "lum_estimator_normalize"); + + self->widget = masking_page; + + // Collapsible section "advanced" + dt_gui_new_collapsible_section(&g->adv_section, "plugins/darkroom/toneequal/expand_advanced_masking", + _("advanced"), GTK_BOX(masking_page), DT_ACTION(self)); + gtk_widget_set_tooltip_text(g->adv_section.expander, _("advanced")); + + // Hack to make the collapsible section align at the top + g_object_ref(g->adv_section.expander); + gtk_container_remove(GTK_CONTAINER(masking_page), g->adv_section.expander); + gtk_box_pack_start(GTK_BOX(masking_page), g->adv_section.expander, FALSE, FALSE, 0); + g_object_unref(g->adv_section.expander); + + self->widget = GTK_WIDGET(g->adv_section.container); + + + g->quantization = dt_bauhaus_slider_from_params(self, "quantization"); + dt_bauhaus_slider_set_format(g->quantization, _(" EV")); + gtk_widget_set_tooltip_text + (g->quantization, + _("0 disables the quantization.\n" + "higher values posterize the luminance mask to help the guiding\n" + "produce piece-wise smooth areas when using high feathering values")); + + // g->version = dt_bauhaus_combobox_from_params(self, "version"); + // gtk_widget_set_tooltip_text(g->version, _("v2 classic tone equalizer (2018)\n" + // "v3 new version from 2025")); + + // start building top level widget self->widget = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); @@ -3484,8 +5282,10 @@ void gui_init(dt_iop_module_t *self) gtk_widget_show(gtk_notebook_get_nth_page(g->notebook, active_page)); gtk_notebook_set_current_page(g->notebook, active_page); + gtk_box_pack_start(GTK_BOX(self->widget), GTK_WIDGET(wrapper), TRUE, TRUE, 0); + g_signal_connect(G_OBJECT(g->notebook), "button-press-event", - G_CALLBACK(notebook_button_press), self); + G_CALLBACK(_notebook_button_press), self); gtk_box_pack_start(GTK_BOX(self->widget), GTK_WIDGET(g->notebook), FALSE, FALSE, 0); GtkWidget *hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); @@ -3493,7 +5293,7 @@ void gui_init(dt_iop_module_t *self) dt_ui_label_new(_("display exposure mask")), TRUE, TRUE, 0); g->show_luminance_mask = dt_iop_togglebutton_new (self, NULL, - N_("display exposure mask"), NULL, G_CALLBACK(show_luminance_mask_callback), + N_("display exposure mask"), NULL, G_CALLBACK(_show_luminance_mask_callback), FALSE, 0, 0, dtgtk_cairo_paint_showmask, hbox); dt_gui_add_class(g->show_luminance_mask, "dt_transparent_background"); dtgtk_togglebutton_set_paint(DTGTK_TOGGLEBUTTON(g->show_luminance_mask), @@ -3515,8 +5315,8 @@ void gui_cleanup(dt_iop_module_t *self) dt_conf_set_int("plugins/darkroom/toneequal/gui_page", gtk_notebook_get_current_page (g->notebook)); - dt_free_align(g->thumb_preview_buf); - dt_free_align(g->full_preview_buf); + dt_free_align(g->preview_buf); + dt_free_align(g->full_buf); if(g->desc) pango_font_description_free(g->desc); if(g->layout) g_object_unref(g->layout);