-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocessing.cpp
More file actions
2123 lines (1852 loc) · 78.8 KB
/
Copy pathprocessing.cpp
File metadata and controls
2123 lines (1852 loc) · 78.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "processing.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <chrono>
#include <vector>
#include <algorithm>
#include <string>
#include <cstdarg>
#include <deque>
#include <unordered_set>
#include <libraw/libraw.h>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include <stb_image_write.h>
#ifdef _WIN32
#include <initguid.h>
#include <objbase.h>
#include <wincodec.h>
#endif
// -----------------------------------------------------------------------------
// Global Instances
// -----------------------------------------------------------------------------
static ImageState make_default_image_state() {
ImageState s = {};
s.zoom = 1.0f;
s.image_temperature = 5000.0f;
s.show_r = true;
s.show_g = true;
s.show_b = true;
s.show_luma = true;
s.lod_strength = 3;
s.histogram_quality = 8;
s.histogram_interval_ms = 120;
s.last_zoom = 1.0f;
s.using_proxy_source = true;
return s;
}
ImageState g_image = make_default_image_state();
EditorParams g_params = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 5000.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
const EditorParams g_default_params = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 5000.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
std::atomic<bool> g_processing_complete(false);
std::atomic<bool> g_keep_running(true);
std::atomic<bool> g_interaction_active(false);
std::atomic<bool> g_turbo_preview_enabled(true);
std::atomic<bool> g_export_in_progress(false);
std::atomic<bool> g_export_done(false);
std::atomic<bool> g_export_success(false);
std::atomic<float> g_export_progress(0.0f);
std::atomic<bool> g_load_in_progress(false);
std::atomic<bool> g_load_done(false);
std::atomic<bool> g_load_success(false);
std::atomic<float> g_load_progress(0.0f);
std::atomic<float> g_last_process_ms(0.0f);
std::atomic<float> g_last_histogram_ms(0.0f);
std::atomic<int> g_current_processing_step(1);
std::atomic<float> g_current_effective_decimation(1.0f);
std::atomic<int> g_current_adaptive_pixels(0);
std::atomic<bool> g_full_refresh_requested(false);
std::atomic<int> g_completed_x_start(0);
std::atomic<int> g_completed_y_start(0);
std::atomic<int> g_completed_x_end(0);
std::atomic<int> g_completed_y_end(0);
std::mutex g_buffer_mutex;
std::mutex g_export_mutex;
std::mutex g_request_mutex;
std::condition_variable g_request_cv;
std::atomic<uint64_t> g_request_seq(0);
static const float kMinTempK = 2000.0f;
static const float kMaxTempK = 15000.0f;
static std::chrono::steady_clock::time_point g_last_histogram_compute = std::chrono::steady_clock::now() - std::chrono::milliseconds(1000);
char g_current_image_path[1024] = {0};
static EditorParams g_last_processed_params = {};
static bool g_has_last_processed_params = false;
static std::mutex g_thumbnail_mutex;
static std::condition_variable g_thumbnail_cv;
static std::deque<std::string> g_thumbnail_queue;
static std::unordered_set<std::string> g_thumbnail_seen;
static std::deque<ThumbnailPreview> g_thumbnail_ready_queue;
static bool convert_bitmap_thumb_to_rgba(const libraw_processed_image_t* thumb, ThumbnailPreview* out_preview) {
if (!thumb || !out_preview || !thumb->data || thumb->width <= 0 || thumb->height <= 0) return false;
const int pixels = thumb->width * thumb->height;
const int channels = (thumb->colors >= 1 && thumb->colors <= 4) ? thumb->colors : 3;
out_preview->width = thumb->width;
out_preview->height = thumb->height;
out_preview->rgba_pixels.resize((size_t)pixels * 4u);
const uint8_t* src = thumb->data;
for (int i = 0; i < pixels; ++i) {
uint8_t r = 0, g = 0, b = 0, a = 255;
if (channels == 1) {
r = g = b = src[i];
} else if (channels == 3) {
r = src[i * 3 + 0];
g = src[i * 3 + 1];
b = src[i * 3 + 2];
} else {
r = src[i * 4 + 0];
g = src[i * 4 + 1];
b = src[i * 4 + 2];
a = src[i * 4 + 3];
}
size_t dst = (size_t)i * 4u;
out_preview->rgba_pixels[dst + 0] = r;
out_preview->rgba_pixels[dst + 1] = g;
out_preview->rgba_pixels[dst + 2] = b;
out_preview->rgba_pixels[dst + 3] = a;
}
return true;
}
#ifdef _WIN32
static bool decode_jpeg_thumb_with_wic(const uint8_t* data, size_t size, ThumbnailPreview* out_preview) {
if (!data || size == 0 || !out_preview) return false;
HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
bool should_uninit = SUCCEEDED(hr);
if (hr == RPC_E_CHANGED_MODE) {
should_uninit = false;
} else if (FAILED(hr)) {
return false;
}
IWICImagingFactory* factory = NULL;
IWICStream* stream = NULL;
IWICBitmapDecoder* decoder = NULL;
IWICBitmapFrameDecode* frame = NULL;
IWICFormatConverter* converter = NULL;
bool ok = false;
do {
if (FAILED(CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&factory)))) break;
if (FAILED(factory->CreateStream(&stream))) break;
if (FAILED(stream->InitializeFromMemory((BYTE*)data, (DWORD)size))) break;
if (FAILED(factory->CreateDecoderFromStream(stream, NULL, WICDecodeMetadataCacheOnLoad, &decoder))) break;
if (FAILED(decoder->GetFrame(0, &frame))) break;
if (FAILED(factory->CreateFormatConverter(&converter))) break;
if (FAILED(converter->Initialize(frame, GUID_WICPixelFormat32bppRGBA, WICBitmapDitherTypeNone, NULL, 0.0, WICBitmapPaletteTypeCustom))) break;
UINT width = 0;
UINT height = 0;
if (FAILED(converter->GetSize(&width, &height))) break;
if (width == 0 || height == 0) break;
out_preview->width = (int)width;
out_preview->height = (int)height;
out_preview->rgba_pixels.resize((size_t)width * (size_t)height * 4u);
if (FAILED(converter->CopyPixels(NULL, width * 4u, (UINT)out_preview->rgba_pixels.size(), out_preview->rgba_pixels.data()))) break;
ok = true;
} while (false);
if (converter) converter->Release();
if (frame) frame->Release();
if (decoder) decoder->Release();
if (stream) stream->Release();
if (factory) factory->Release();
if (should_uninit) CoUninitialize();
return ok;
}
#endif
static bool decode_raw_thumbnail(const char* filepath, ThumbnailPreview* out_preview) {
if (!filepath || !filepath[0] || !out_preview) return false;
libraw_data_t* processor = libraw_init(0);
if (!processor) return false;
bool ok = false;
int err = 0;
do {
if (libraw_open_file(processor, filepath) != LIBRAW_SUCCESS) break;
if (libraw_unpack_thumb(processor) != LIBRAW_SUCCESS) break;
libraw_processed_image_t* thumb = libraw_dcraw_make_mem_thumb(processor, &err);
if (!thumb) break;
snprintf(out_preview->path, sizeof(out_preview->path), "%s", filepath);
if (thumb->type == LIBRAW_IMAGE_BITMAP) {
ok = convert_bitmap_thumb_to_rgba(thumb, out_preview);
} else if (thumb->type == LIBRAW_IMAGE_JPEG) {
#ifdef _WIN32
ok = decode_jpeg_thumb_with_wic(thumb->data, thumb->data_size, out_preview);
#endif
}
libraw_dcraw_clear_mem(thumb);
} while (false);
libraw_close(processor);
return ok;
}
static float load_stage_base(enum LibRaw_progress stage) {
switch (stage) {
case LIBRAW_PROGRESS_START: return 0.01f;
case LIBRAW_PROGRESS_OPEN: return 0.05f;
case LIBRAW_PROGRESS_IDENTIFY: return 0.12f;
case LIBRAW_PROGRESS_SIZE_ADJUST: return 0.20f;
case LIBRAW_PROGRESS_LOAD_RAW: return 0.35f;
case LIBRAW_PROGRESS_RAW2_IMAGE: return 0.62f;
case LIBRAW_PROGRESS_REMOVE_ZEROES: return 0.70f;
case LIBRAW_PROGRESS_BAD_PIXELS: return 0.74f;
case LIBRAW_PROGRESS_DARK_FRAME: return 0.78f;
case LIBRAW_PROGRESS_FOVEON_INTERPOLATE: return 0.82f;
case LIBRAW_PROGRESS_SCALE_COLORS: return 0.86f;
case LIBRAW_PROGRESS_PRE_INTERPOLATE: return 0.90f;
case LIBRAW_PROGRESS_INTERPOLATE: return 0.93f;
default: return 0.0f;
}
}
static int load_progress_callback(void* /*data*/, enum LibRaw_progress stage, int iteration, int expected) {
float base = load_stage_base(stage);
float span = 0.0f;
switch (stage) {
case LIBRAW_PROGRESS_START:
case LIBRAW_PROGRESS_OPEN:
case LIBRAW_PROGRESS_IDENTIFY:
case LIBRAW_PROGRESS_SIZE_ADJUST:
case LIBRAW_PROGRESS_LOAD_RAW:
case LIBRAW_PROGRESS_RAW2_IMAGE:
case LIBRAW_PROGRESS_REMOVE_ZEROES:
case LIBRAW_PROGRESS_BAD_PIXELS:
case LIBRAW_PROGRESS_DARK_FRAME:
case LIBRAW_PROGRESS_FOVEON_INTERPOLATE:
case LIBRAW_PROGRESS_SCALE_COLORS:
case LIBRAW_PROGRESS_PRE_INTERPOLATE:
case LIBRAW_PROGRESS_INTERPOLATE:
span = 0.04f;
break;
default:
span = 0.0f;
break;
}
float local = 0.0f;
if (expected > 0) {
local = (float)iteration / (float)expected;
if (local < 0.0f) local = 0.0f;
if (local > 1.0f) local = 1.0f;
}
float progress = base + span * local;
if (progress < 0.0f) progress = 0.0f;
if (progress > 0.98f) progress = 0.98f;
g_load_progress = progress;
return 0;
}
void debug_log(const char* fmt, ...) {
char message[2048];
va_list args;
va_start(args, fmt);
vsnprintf(message, sizeof(message), fmt, args);
va_end(args);
double seconds = std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count();
unsigned long long thread_id = (unsigned long long)std::hash<std::thread::id>{}(std::this_thread::get_id());
fprintf(stderr, "[%.3f][tid=%llu] %s\n", seconds, thread_id, message);
fflush(stderr);
}
// -----------------------------------------------------------------------------
// Core Processing Math
// -----------------------------------------------------------------------------
inline float clamp(float x, float min_val, float max_val) {
return (x < min_val) ? min_val : (x > max_val) ? max_val : x;
}
static inline float mixf(float a, float b, float t) {
return a + (b - a) * t;
}
static inline float luminance709(float r, float g, float b) {
return 0.2126f * r + 0.7152f * g + 0.0722f * b;
}
static inline float srgb_encode(float v) {
v = clamp(v, 0.0f, 1.0f);
if (v >= 1.0f) return 1.0f; // Fast-path to prevent IEEE 754 precision loss
if (v <= 0.0f) return 0.0f;
if (v <= 0.0031308f) return 12.92f * v;
return 1.055f * powf(v, 1.0f / 2.4f) - 0.055f;
}
static inline float srgb_encode_fast(float v) {
const int LUT_SIZE = 4096;
static bool lut_ready = false;
static float lut[LUT_SIZE + 1];
if (!lut_ready) {
for (int i = 0; i <= LUT_SIZE; ++i) {
float x = (float)i / (float)LUT_SIZE;
lut[i] = srgb_encode(x);
}
lut_ready = true;
}
v = clamp(v, 0.0f, 1.0f);
float f = v * (float)LUT_SIZE;
int i0 = (int)f;
int i1 = (i0 < LUT_SIZE) ? (i0 + 1) : LUT_SIZE;
float t = f - (float)i0;
return mixf(lut[i0], lut[i1], t);
}
static inline float srgb_decode_fast(float v) {
v = clamp(v, 0.0f, 1.0f);
if (v <= 0.04045f) return v / 12.92f;
return powf((v + 0.055f) / 1.055f, 2.4f);
}
static bool params_equal_except_exposure(const EditorParams& a, const EditorParams& b, float eps = 1e-5f) {
const float* pa = (const float*)&a;
const float* pb = (const float*)&b;
int count = (int)(sizeof(EditorParams) / sizeof(float));
for (int i = 0; i < count; ++i) {
if (i == 0) continue; // exposure
if (fabsf(pa[i] - pb[i]) > eps) return false;
}
return true;
}
static void rebuild_histogram_from_buffer(const float* buffer, int width, int height, HistogramData& histogram) {
memset(&histogram, 0, sizeof(HistogramData));
if (!buffer || width <= 0 || height <= 0) return;
unsigned int hw_threads = std::thread::hardware_concurrency();
if (hw_threads == 0) hw_threads = 4;
int threads = (int)std::min<unsigned int>(hw_threads, (unsigned int)std::max(height, 1));
if (threads <= 1) {
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
int idx = (y * width + x) * 3;
float r = buffer[idx];
float g = buffer[idx + 1];
float b = buffer[idx + 2];
int bin_r = (int)(clamp(r, 0.0f, 1.0f) * 255.999f);
int bin_g = (int)(clamp(g, 0.0f, 1.0f) * 255.999f);
int bin_b = (int)(clamp(b, 0.0f, 1.0f) * 255.999f);
float luma = 0.299f * r + 0.587f * g + 0.114f * b;
int bin_luma = (int)(clamp(luma, 0.0f, 1.0f) * 255.999f);
histogram.r[bin_r]++;
histogram.g[bin_g]++;
histogram.b[bin_b]++;
histogram.luma[bin_luma]++;
}
}
} else {
std::vector<HistogramData> partial((size_t)threads);
auto worker = [&](int y0, int y1, HistogramData& h) {
for (int y = y0; y < y1; ++y) {
for (int x = 0; x < width; ++x) {
int idx = (y * width + x) * 3;
float r = buffer[idx];
float g = buffer[idx + 1];
float b = buffer[idx + 2];
int bin_r = (int)(clamp(r, 0.0f, 1.0f) * 255.999f);
int bin_g = (int)(clamp(g, 0.0f, 1.0f) * 255.999f);
int bin_b = (int)(clamp(b, 0.0f, 1.0f) * 255.999f);
float luma = 0.299f * r + 0.587f * g + 0.114f * b;
int bin_luma = (int)(clamp(luma, 0.0f, 1.0f) * 255.999f);
h.r[bin_r]++;
h.g[bin_g]++;
h.b[bin_b]++;
h.luma[bin_luma]++;
}
}
};
int chunk = (height + threads - 1) / threads;
std::vector<std::thread> workers;
workers.reserve((size_t)threads - 1);
for (int t = 0; t < threads - 1; ++t) {
int y0 = t * chunk;
int y1 = std::min(height, y0 + chunk);
if (y0 < y1) workers.emplace_back(worker, y0, y1, std::ref(partial[(size_t)t]));
}
int my_y0 = (threads - 1) * chunk;
if (my_y0 < height) worker(my_y0, height, partial[(size_t)threads - 1]);
for (auto& thread : workers) thread.join();
for (int t = 0; t < threads; ++t) {
for (int i = 0; i < 256; ++i) {
histogram.r[i] += partial[(size_t)t].r[i];
histogram.g[i] += partial[(size_t)t].g[i];
histogram.b[i] += partial[(size_t)t].b[i];
histogram.luma[i] += partial[(size_t)t].luma[i];
}
}
}
histogram.max_val = 0.0f;
for (int i = 0; i < 256; ++i) {
if (histogram.r[i] > histogram.max_val) histogram.max_val = histogram.r[i];
if (histogram.g[i] > histogram.max_val) histogram.max_val = histogram.g[i];
if (histogram.b[i] > histogram.max_val) histogram.max_val = histogram.b[i];
if (histogram.luma[i] > histogram.max_val) histogram.max_val = histogram.luma[i];
}
}
static inline float smoothstep01(float x) {
x = clamp(x, 0.0f, 1.0f);
return x * x * (3.0f - 2.0f * x);
}
static inline float smoothstep(float e0, float e1, float x) {
float t = (x - e0) / (e1 - e0);
return smoothstep01(t);
}
static inline float inverse_smoothstep(float x) {
x = clamp(x, 0.0f, 1.0f);
return 0.5f - sinf(asinf(1.0f - 2.0f * x) / 3.0f);
}
static inline float soft_slider(float v, float gamma) {
float n = clamp(v / 100.0f, -1.0f, 1.0f);
float a = powf(fabsf(n), gamma);
return (n < 0.0f) ? -a : a;
}
static void mat3_mul(const float a[9], const float b[9], float out[9]) {
for (int r = 0; r < 3; ++r) {
for (int c = 0; c < 3; ++c) {
out[r * 3 + c] =
a[r * 3 + 0] * b[0 * 3 + c] +
a[r * 3 + 1] * b[1 * 3 + c] +
a[r * 3 + 2] * b[2 * 3 + c];
}
}
}
static void mat3_vec_mul(const float m[9], float x, float y, float z, float* ox, float* oy, float* oz) {
*ox = m[0] * x + m[1] * y + m[2] * z;
*oy = m[3] * x + m[4] * y + m[5] * z;
*oz = m[6] * x + m[7] * y + m[8] * z;
}
static void kelvin_to_xy(float kelvin, float* x, float* y) {
float t = clamp(kelvin, 1000.0f, 40000.0f);
float x_c;
if (t <= 4000.0f) {
x_c = -0.2661239e9f / (t * t * t) - 0.2343589e6f / (t * t) + 0.8776956e3f / t + 0.179910f;
} else {
x_c = -3.0258469e9f / (t * t * t) + 2.1070379e6f / (t * t) + 0.2226347e3f / t + 0.240390f;
}
float y_c;
if (t <= 2222.0f) {
y_c = -1.1063814f * x_c * x_c * x_c - 1.34811020f * x_c * x_c + 2.18555832f * x_c - 0.20219683f;
} else if (t <= 4000.0f) {
y_c = -0.9549476f * x_c * x_c * x_c - 1.37418593f * x_c * x_c + 2.09137015f * x_c - 0.16748867f;
} else {
y_c = 3.0817580f * x_c * x_c * x_c - 5.87338670f * x_c * x_c + 3.75112997f * x_c - 0.37001483f;
}
*x = x_c;
*y = y_c;
}
static void kelvin_to_xyz(float kelvin, float* X, float* Y, float* Z) {
float x, y;
kelvin_to_xy(kelvin, &x, &y);
*Y = 1.0f;
*X = x / y;
*Z = (1.0f - x - y) / y;
}
struct ProcessingContext {
EditorParams params;
int width;
int height;
int stage_x0;
int stage_y0;
int stage_x1;
int stage_y1;
int stage_w;
int stage_h;
const float* src_buffer;
float exp_mult;
float wb_rgb[9];
float clarity_amt;
float texture_amt;
float dehaze_amt;
float saturation;
float vibrance;
float nr_amt;
float cnr_amt;
bool use_spatial;
bool use_dehaze;
bool use_nr;
bool use_cnr;
bool has_ycbcr_maps;
std::vector<float> staged_rgb;
std::vector<float> luma;
std::vector<float> cb;
std::vector<float> cr;
std::vector<float> blur_small;
std::vector<float> blur_large;
std::vector<float> dark_blur;
std::vector<float> luma_nr;
std::vector<float> cb_nr;
std::vector<float> cr_nr;
float atmosphere;
float atmosphere_rgb[3];
};
static const float* g_active_source_buffer = NULL;
static float median_window(const std::vector<float>& src, int w, int h, int x, int y, int radius);
static void box_blur_1d_h(const std::vector<float>& src, std::vector<float>& dst, int w, int h, int r) {
if (r <= 0) {
dst = src;
return;
}
dst.assign((size_t)w * h, 0.0f);
int ksize = 2 * r + 1;
for (int y = 0; y < h; ++y) {
float sum = 0.0f;
int row = y * w;
for (int k = -r; k <= r; ++k) {
int x = k;
if (x < 0) x = 0;
if (x >= w) x = w - 1;
sum += src[row + x];
}
dst[row] = sum / (float)ksize;
for (int x = 1; x < w; ++x) {
int add_x = x + r;
int sub_x = x - r - 1;
if (add_x >= w) add_x = w - 1;
if (sub_x < 0) sub_x = 0;
sum += src[row + add_x] - src[row + sub_x];
dst[row + x] = sum / (float)ksize;
}
}
}
static void box_blur_1d_v(const std::vector<float>& src, std::vector<float>& dst, int w, int h, int r) {
if (r <= 0) {
dst = src;
return;
}
dst.assign((size_t)w * h, 0.0f);
int ksize = 2 * r + 1;
for (int x = 0; x < w; ++x) {
float sum = 0.0f;
for (int k = -r; k <= r; ++k) {
int y = k;
if (y < 0) y = 0;
if (y >= h) y = h - 1;
sum += src[y * w + x];
}
dst[x] = sum / (float)ksize;
for (int y = 1; y < h; ++y) {
int add_y = y + r;
int sub_y = y - r - 1;
if (add_y >= h) add_y = h - 1;
if (sub_y < 0) sub_y = 0;
sum += src[add_y * w + x] - src[sub_y * w + x];
dst[y * w + x] = sum / (float)ksize;
}
}
}
static void box_blur(const std::vector<float>& src, std::vector<float>& dst, int w, int h, int radius) {
std::vector<float> tmp;
box_blur_1d_h(src, tmp, w, h, radius);
box_blur_1d_v(tmp, dst, w, h, radius);
}
static void median_filter_map(const std::vector<float>& src, std::vector<float>& dst, int w, int h, int radius) {
dst.resize((size_t)w * h);
for (int y = 0; y < h; ++y) {
for (int x = 0; x < w; ++x) {
dst[(size_t)y * w + x] = median_window(src, w, h, x, y, radius);
}
}
}
static void build_luma_nr_map(const std::vector<float>& luma, std::vector<float>& out_nr, int w, int h, float nr_amt) {
int radius = (nr_amt > 0.66f) ? 3 : ((nr_amt > 0.33f) ? 2 : 1);
std::vector<float> blurred;
box_blur(luma, blurred, w, h, radius);
out_nr.resize((size_t)w * h);
for (int i = 0; i < w * h; ++i) {
float y = luma[i];
float b = blurred[i];
float diff = fabsf(y - b);
float thresh = 0.01f + 0.08f * clamp(y, 0.0f, 1.0f);
float edge = clamp(diff / (thresh + 1e-6f), 0.0f, 1.0f);
float blend = nr_amt * (1.0f - edge);
out_nr[i] = mixf(y, b, blend);
}
}
static void build_wb_matrix(float source_kelvin, float target_kelvin, float tint, float out_rgb_matrix[9]) {
const float rgb_to_xyz[9] = {
0.4124564f, 0.3575761f, 0.1804375f,
0.2126729f, 0.7151522f, 0.0721750f,
0.0193339f, 0.1191920f, 0.9503041f
};
const float xyz_to_rgb[9] = {
3.2404542f, -1.5371385f, -0.4985314f,
-0.9692660f, 1.8760108f, 0.0415560f,
0.0556434f, -0.2040259f, 1.0572252f
};
const float bradford[9] = {
0.8951f, 0.2664f, -0.1614f,
-0.7502f, 1.7135f, 0.0367f,
0.0389f, -0.0685f, 1.0296f
};
const float bradford_inv[9] = {
0.9869929f, -0.1470543f, 0.1599627f,
0.4323053f, 0.5183603f, 0.0492912f,
-0.0085287f, 0.0400428f, 0.9684867f
};
float src_X, src_Y, src_Z;
float dst_X, dst_Y, dst_Z;
kelvin_to_xyz(source_kelvin, &src_X, &src_Y, &src_Z);
kelvin_to_xyz(target_kelvin, &dst_X, &dst_Y, &dst_Z);
float src_l, src_m, src_s;
float dst_l, dst_m, dst_s;
mat3_vec_mul(bradford, src_X, src_Y, src_Z, &src_l, &src_m, &src_s);
mat3_vec_mul(bradford, dst_X, dst_Y, dst_Z, &dst_l, &dst_m, &dst_s);
float tint_n = clamp(tint / 150.0f, -1.0f, 1.0f);
dst_l *= (1.0f + 0.10f * tint_n);
dst_m *= (1.0f - 0.10f * tint_n);
float diag[9] = {
dst_l / (src_l + 1e-8f), 0.0f, 0.0f,
0.0f, dst_m / (src_m + 1e-8f), 0.0f,
0.0f, 0.0f, dst_s / (src_s + 1e-8f)
};
float tmp0[9];
float adapt_xyz[9];
mat3_mul(diag, bradford, tmp0);
mat3_mul(bradford_inv, tmp0, adapt_xyz);
float tmp1[9];
mat3_mul(adapt_xyz, rgb_to_xyz, tmp1);
mat3_mul(xyz_to_rgb, tmp1, out_rgb_matrix);
}
static inline void rgb_to_ycbcr(float r, float g, float b, float* y, float* cb, float* cr) {
*y = luminance709(r, g, b);
*cb = (b - *y) / 1.8556f;
*cr = (r - *y) / 1.5748f;
}
static inline void ycbcr_to_rgb(float y, float cb, float cr, float* r, float* g, float* b) {
*r = y + 1.5748f * cr;
*b = y + 1.8556f * cb;
*g = (y - 0.2126f * (*r) - 0.0722f * (*b)) / 0.7152f;
}
static inline void apply_wb_and_exposure(const ProcessingContext& ctx, float r, float g, float b, float* out_r, float* out_g, float* out_b) {
float wr, wg, wb;
mat3_vec_mul(ctx.wb_rgb, r, g, b, &wr, &wg, &wb);
*out_r = wr * ctx.exp_mult;
*out_g = wg * ctx.exp_mult;
*out_b = wb * ctx.exp_mult;
}
static inline int stage_index_clamped(const ProcessingContext& ctx, int x, int y) {
int sx = x;
int sy = y;
if (sx < ctx.stage_x0) sx = ctx.stage_x0;
if (sy < ctx.stage_y0) sy = ctx.stage_y0;
if (sx >= ctx.stage_x1) sx = ctx.stage_x1 - 1;
if (sy >= ctx.stage_y1) sy = ctx.stage_y1 - 1;
return (sy - ctx.stage_y0) * ctx.stage_w + (sx - ctx.stage_x0);
}
static inline void sample_staged_rgb(const ProcessingContext& ctx, int x, int y, float* r, float* g, float* b) {
int local_idx = stage_index_clamped(ctx, x, y);
int rgb_idx = local_idx * 3;
*r = ctx.staged_rgb[(size_t)rgb_idx];
*g = ctx.staged_rgb[(size_t)rgb_idx + 1];
*b = ctx.staged_rgb[(size_t)rgb_idx + 2];
}
static void atrous_denoise(std::vector<float>& buffer, int w, int h, int levels, float amount) {
if (levels <= 0 || amount <= 1e-6f) return;
std::vector<float> c = buffer;
std::vector<float> next_c(w * h, 0.0f);
std::vector<float> reconstructed(w * h, 0.0f);
std::vector<float> temp(w * h, 0.0f);
const float kernel[5] = {1.0f/16.0f, 4.0f/16.0f, 6.0f/16.0f, 4.0f/16.0f, 1.0f/16.0f};
for (int level = 0; level < levels; ++level) {
int step = 1 << level;
// Separable horizontal pass
for (int y = 0; y < h; ++y) {
int row = y * w;
for (int x = 0; x < w; ++x) {
float sum = 0.0f;
for (int k = -2; k <= 2; ++k) {
int sx = clamp(x + k * step, 0, w - 1);
sum += c[row + sx] * kernel[k + 2];
}
temp[row + x] = sum;
}
}
// Separable vertical pass
for (int x = 0; x < w; ++x) {
for (int y = 0; y < h; ++y) {
float sum = 0.0f;
for (int k = -2; k <= 2; ++k) {
int sy = clamp(y + k * step, 0, h - 1);
sum += temp[sy * w + x] * kernel[k + 2];
}
next_c[y * w + x] = sum;
}
}
// Soft thresholding detail coefficients
float level_threshold = amount / (float)(1 << level);
for (int i = 0; i < w * h; ++i) {
float detail = c[i] - next_c[i];
float sign = (detail > 0.0f) ? 1.0f : -1.0f;
float thresholded = fmaxf(fabsf(detail) - level_threshold, 0.0f) * sign;
reconstructed[i] += thresholded;
}
c = next_c;
}
// Add final residual back to thresholded details
for (int i = 0; i < w * h; ++i) {
buffer[i] = reconstructed[i] + c[i];
}
}
static inline void sample_linear_ycbcr(const ProcessingContext& ctx, int x, int y, float* yv, float* cbv, float* crv) {
int idx = stage_index_clamped(ctx, x, y);
if (ctx.has_ycbcr_maps) {
*yv = ctx.luma[(size_t)idx];
*cbv = ctx.cb[(size_t)idx];
*crv = ctx.cr[(size_t)idx];
return;
}
int rgb_idx = idx * 3;
rgb_to_ycbcr(
ctx.staged_rgb[(size_t)rgb_idx],
ctx.staged_rgb[(size_t)rgb_idx + 1],
ctx.staged_rgb[(size_t)rgb_idx + 2],
yv, cbv, crv);
}
static ProcessingContext build_processing_context_from_snapshot(bool fast_preview, const EditorParams& params,
int width, int height, int vis_x0, int vis_y0, int vis_x1, int vis_y1,
const float* source_buffer, float source_temperature) {
ProcessingContext ctx = {};
ctx.params = params;
ctx.width = width;
ctx.height = height;
ctx.exp_mult = powf(2.0f, params.exposure);
ctx.clarity_amt = params.clarity / 100.0f;
ctx.texture_amt = params.texture / 100.0f;
ctx.dehaze_amt = clamp(params.dehaze / 100.0f, -1.0f, 1.0f);
ctx.saturation = 1.0f + (params.saturation / 100.0f);
ctx.vibrance = params.vibrance / 100.0f;
ctx.nr_amt = clamp(params.noise_reduction / 100.0f, 0.0f, 1.0f);
ctx.cnr_amt = clamp(params.color_noise_reduction / 100.0f, 0.0f, 1.0f);
if (fast_preview) {
// Keep controls responsive in preview by disabling the heaviest kernels.
ctx.clarity_amt *= 0.45f;
ctx.texture_amt *= 0.45f;
ctx.dehaze_amt = 0.0f;
ctx.nr_amt = 0.0f;
ctx.cnr_amt = 0.0f;
}
ctx.use_spatial = (fabsf(ctx.clarity_amt) > 1e-4f) || (fabsf(ctx.texture_amt) > 1e-4f);
ctx.use_dehaze = (fabsf(ctx.dehaze_amt) > 1e-4f);
ctx.use_nr = (ctx.nr_amt > 1e-4f);
ctx.use_cnr = (ctx.cnr_amt > 1e-4f);
ctx.has_ycbcr_maps = false;
ctx.src_buffer = source_buffer;
float src_temp = source_temperature;
if (src_temp <= 1000.0f) src_temp = 5000.0f;
build_wb_matrix(src_temp, clamp(params.temperature, kMinTempK, kMaxTempK), params.tint, ctx.wb_rgb);
if (vis_x0 >= vis_x1 || vis_y0 >= vis_y1) {
vis_x0 = 0;
vis_y0 = 0;
vis_x1 = ctx.width;
vis_y1 = ctx.height;
}
int kernel_pad = 0;
if (ctx.use_spatial) kernel_pad = std::max(kernel_pad, 6);
if (ctx.use_dehaze) kernel_pad = std::max(kernel_pad, 8);
if (ctx.use_nr) kernel_pad = std::max(kernel_pad, 16);
if (ctx.use_cnr) kernel_pad = std::max(kernel_pad, 32);
ctx.stage_x0 = vis_x0 - kernel_pad;
ctx.stage_y0 = vis_y0 - kernel_pad;
ctx.stage_x1 = vis_x1 + kernel_pad;
ctx.stage_y1 = vis_y1 + kernel_pad;
if (ctx.stage_x0 < 0) ctx.stage_x0 = 0;
if (ctx.stage_y0 < 0) ctx.stage_y0 = 0;
if (ctx.stage_x1 > ctx.width) ctx.stage_x1 = ctx.width;
if (ctx.stage_y1 > ctx.height) ctx.stage_y1 = ctx.height;
ctx.stage_w = ctx.stage_x1 - ctx.stage_x0;
ctx.stage_h = ctx.stage_y1 - ctx.stage_y0;
if (ctx.stage_w <= 0 || ctx.stage_h <= 0) {
ctx.stage_x0 = 0;
ctx.stage_y0 = 0;
ctx.stage_x1 = ctx.width;
ctx.stage_y1 = ctx.height;
ctx.stage_w = ctx.width;
ctx.stage_h = ctx.height;
}
size_t n = (size_t)ctx.stage_w * (size_t)ctx.stage_h;
ctx.staged_rgb.resize(n * 3);
bool need_luma = ctx.use_spatial || ctx.use_dehaze || ctx.use_nr || ctx.use_cnr;
bool need_chroma = ctx.use_nr || ctx.use_cnr;
bool need_dark = ctx.use_dehaze;
if (need_luma) ctx.luma.resize(n);
if (need_chroma) {
ctx.cb.resize(n);
ctx.cr.resize(n);
ctx.has_ycbcr_maps = true;
}
std::vector<float> dark;
if (need_dark) dark.resize(n);
float atmosphere = 0.0f;
float top_dark = -1.0f;
float top_r = 1.0f, top_g = 1.0f, top_b = 1.0f;
if (ctx.src_buffer && n > 0) {
for (int y = ctx.stage_y0; y < ctx.stage_y1; ++y) {
for (int x = ctx.stage_x0; x < ctx.stage_x1; ++x) {
int src_idx = (y * ctx.width + x) * 3;
int local_idx = (y - ctx.stage_y0) * ctx.stage_w + (x - ctx.stage_x0);
float r, g, b;
apply_wb_and_exposure(ctx,
ctx.src_buffer[src_idx],
ctx.src_buffer[src_idx + 1],
ctx.src_buffer[src_idx + 2],
&r, &g, &b);
int rgb_idx = local_idx * 3;
ctx.staged_rgb[(size_t)rgb_idx] = r;
ctx.staged_rgb[(size_t)rgb_idx + 1] = g;
ctx.staged_rgb[(size_t)rgb_idx + 2] = b;
if (need_luma || need_chroma) {
float yv, cbv, crv;
rgb_to_ycbcr(r, g, b, &yv, &cbv, &crv);
if (need_luma) ctx.luma[(size_t)local_idx] = yv;
if (need_chroma) {
ctx.cb[(size_t)local_idx] = cbv;
ctx.cr[(size_t)local_idx] = crv;
}
}
if (need_dark) {
dark[(size_t)local_idx] = fminf(r, fminf(g, b));
float local_max = fmaxf(r, fmaxf(g, b));
if (local_max > atmosphere) atmosphere = local_max;
if (dark[(size_t)local_idx] > top_dark) {
top_dark = dark[(size_t)local_idx];
top_r = r;
top_g = g;
top_b = b;
}
}
}
}
}
// Denoise linear maps first so downstream spatial filters inherit the clean signal
if (ctx.use_nr) {
atrous_denoise(ctx.luma, ctx.stage_w, ctx.stage_h, 4, ctx.nr_amt * 0.05f);
}
if (ctx.use_cnr) {
atrous_denoise(ctx.cb, ctx.stage_w, ctx.stage_h, 5, ctx.cnr_amt * 0.08f);
atrous_denoise(ctx.cr, ctx.stage_w, ctx.stage_h, 5, ctx.cnr_amt * 0.08f);
}
if (ctx.use_spatial) {
box_blur(ctx.luma, ctx.blur_small, ctx.stage_w, ctx.stage_h, 2);
box_blur(ctx.luma, ctx.blur_large, ctx.stage_w, ctx.stage_h, 6);
}
if (ctx.use_dehaze) {
box_blur(dark, ctx.dark_blur, ctx.stage_w, ctx.stage_h, 8);
}
ctx.atmosphere = atmosphere;
if (ctx.atmosphere < 1e-4f) ctx.atmosphere = 1.0f;
ctx.atmosphere_rgb[0] = fmaxf(top_r, 1e-4f);
ctx.atmosphere_rgb[1] = fmaxf(top_g, 1e-4f);
ctx.atmosphere_rgb[2] = fmaxf(top_b, 1e-4f);
return ctx;
}
static ProcessingContext build_processing_context(bool fast_preview, const EditorParams& params) {
return build_processing_context_from_snapshot(
fast_preview,
params,
g_image.width,
g_image.height,
g_image.vis_x_start,
g_image.vis_y_start,
g_image.vis_x_end,
g_image.vis_y_end,
g_active_source_buffer,
g_image.image_temperature);
}
static float median_window(const std::vector<float>& src, int w, int h, int x, int y, int radius) {
float vals[49];
int n = 0;
for (int ky = -radius; ky <= radius; ++ky) {
int sy = y + ky;
if (sy < 0) sy = 0;
if (sy >= h) sy = h - 1;
for (int kx = -radius; kx <= radius; ++kx) {
int sx = x + kx;
if (sx < 0) sx = 0;
if (sx >= w) sx = w - 1;
vals[n++] = src[sy * w + sx];
}
}
int mid = n / 2;
std::nth_element(vals, vals + mid, vals + n);
return vals[mid];
}
static float apply_luma_tone(const ProcessingContext& ctx, float y) {
y = fmaxf(y, 0.0f);
float h = soft_slider(ctx.params.highlights, 1.20f);
float s = soft_slider(ctx.params.shadows, 1.50f);
float m = soft_slider(ctx.params.midtones, 1.25f);
float w = soft_slider(ctx.params.whites, 1.25f);
float b = soft_slider(ctx.params.blacks, 1.25f);
// 1. Blacks: shift the absolute black point, smoothly decaying
if (fabsf(b) > 1e-4f) {
float black_shift = b * 0.05f;
y = fmaxf(0.0f, y + black_shift * (1.0f - smoothstep(0.0f, 0.2f, y)));
}
// 2. Shadows: toe curve compression/lift
float shadow_pivot = 0.25f;
if (y < shadow_pivot && y > 0.0f) {
float t = y / shadow_pivot;
// s > 0 lifts shadows (bows up), s < 0 crushes (bows down)
float curve = s > 0.0f ? powf(t, 1.0f - s * 0.5f) : powf(t, 1.0f - s * 1.2f);
y = mixf(t, curve, fabsf(s)) * shadow_pivot;
}
// 3. Midtones: gamma curve pivoted around middle gray
if (fabsf(m) > 1e-4f) {
float gray = 0.18f;
float gamma = expf(-m * 1.5f);
y = gray * powf(fmaxf(y / gray, 0.0f), gamma);