-
-
Notifications
You must be signed in to change notification settings - Fork 76
/
colorspace.c
2069 lines (1847 loc) · 88.4 KB
/
colorspace.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of libplacebo.
*
* libplacebo is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* libplacebo is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with libplacebo. If not, see <http://www.gnu.org/licenses/>.
*/
#include <math.h>
#include "cache.h"
#include "colorspace.h"
#include "shaders.h"
#include <libplacebo/shaders/colorspace.h>
void pl_shader_set_alpha(pl_shader sh, struct pl_color_repr *repr,
enum pl_alpha_mode mode)
{
bool src_has_alpha = repr->alpha == PL_ALPHA_INDEPENDENT ||
repr->alpha == PL_ALPHA_PREMULTIPLIED;
bool dst_not_premul = mode == PL_ALPHA_INDEPENDENT ||
mode == PL_ALPHA_NONE;
if (repr->alpha == PL_ALPHA_PREMULTIPLIED && dst_not_premul) {
GLSL("if (color.a > 1e-6) \n"
" color.rgb /= vec3(color.a); \n");
repr->alpha = PL_ALPHA_INDEPENDENT;
}
if (repr->alpha == PL_ALPHA_INDEPENDENT && mode == PL_ALPHA_PREMULTIPLIED) {
GLSL("color.rgb *= vec3(color.a); \n");
repr->alpha = PL_ALPHA_PREMULTIPLIED;
}
if (src_has_alpha && mode == PL_ALPHA_NONE) {
GLSL("color.a = 1.0; \n");
repr->alpha = PL_ALPHA_NONE;
}
}
#ifdef PL_HAVE_DOVI
static inline void reshape_mmr(pl_shader sh, ident_t mmr, bool single,
int min_order, int max_order)
{
if (single) {
GLSL("const uint mmr_idx = 0u; \n");
} else {
GLSL("uint mmr_idx = uint(coeffs.y); \n");
}
assert(min_order <= max_order);
if (min_order < max_order)
GLSL("uint order = uint(coeffs.w); \n");
GLSL("vec4 sigX; \n"
"s = coeffs.x; \n"
"sigX.xyz = sig.xxy * sig.yzz; \n"
"sigX.w = sigX.x * sig.z; \n"
"s += dot("$"[mmr_idx + 0].xyz, sig); \n"
"s += dot("$"[mmr_idx + 1], sigX); \n",
mmr, mmr);
if (max_order >= 2) {
if (min_order < 2)
GLSL("if (order >= 2) { \n");
GLSL("vec3 sig2 = sig * sig; \n"
"vec4 sigX2 = sigX * sigX; \n"
"s += dot("$"[mmr_idx + 2].xyz, sig2); \n"
"s += dot("$"[mmr_idx + 3], sigX2); \n",
mmr, mmr);
if (max_order == 3) {
if (min_order < 3)
GLSL("if (order >= 3 { \n");
GLSL("s += dot("$"[mmr_idx + 4].xyz, sig2 * sig); \n"
"s += dot("$"[mmr_idx + 5], sigX2 * sigX); \n",
mmr, mmr);
if (min_order < 3)
GLSL("} \n");
}
if (min_order < 2)
GLSL("} \n");
}
}
static inline void reshape_poly(pl_shader sh)
{
GLSL("s = (coeffs.z * s + coeffs.y) * s + coeffs.x; \n");
}
#endif
void pl_shader_dovi_reshape(pl_shader sh, const struct pl_dovi_metadata *data)
{
#ifdef PL_HAVE_DOVI
if (!sh_require(sh, PL_SHADER_SIG_COLOR, 0, 0) || !data)
return;
sh_describe(sh, "reshaping");
GLSL("// pl_shader_reshape \n"
"{ \n"
"vec3 sig; \n"
"vec4 coeffs; \n"
"float s; \n"
"sig = clamp(color.rgb, 0.0, 1.0); \n");
float coeffs_data[8][4];
float mmr_packed_data[8*6][4];
for (int c = 0; c < 3; c++) {
const struct pl_reshape_data *comp = &data->comp[c];
if (!comp->num_pivots)
continue;
pl_assert(comp->num_pivots >= 2 && comp->num_pivots <= 9);
GLSL("s = sig[%d]; \n", c);
// Prepare coefficients for GPU
bool has_poly = false, has_mmr = false, mmr_single = true;
int mmr_idx = 0, min_order = 3, max_order = 1;
memset(coeffs_data, 0, sizeof(coeffs_data));
for (int i = 0; i < comp->num_pivots - 1; i++) {
switch (comp->method[i]) {
case 0: // polynomial
has_poly = true;
coeffs_data[i][3] = 0.0; // order=0 signals polynomial
for (int k = 0; k < 3; k++)
coeffs_data[i][k] = comp->poly_coeffs[i][k];
break;
case 1:
min_order = PL_MIN(min_order, comp->mmr_order[i]);
max_order = PL_MAX(max_order, comp->mmr_order[i]);
mmr_single = !has_mmr;
has_mmr = true;
coeffs_data[i][3] = (float) comp->mmr_order[i];
coeffs_data[i][0] = comp->mmr_constant[i];
coeffs_data[i][1] = (float) mmr_idx;
for (int j = 0; j < comp->mmr_order[i]; j++) {
// store weights per order as two packed vec4s
float *mmr = &mmr_packed_data[mmr_idx][0];
mmr[0] = comp->mmr_coeffs[i][j][0];
mmr[1] = comp->mmr_coeffs[i][j][1];
mmr[2] = comp->mmr_coeffs[i][j][2];
mmr[3] = 0.0; // unused
mmr[4] = comp->mmr_coeffs[i][j][3];
mmr[5] = comp->mmr_coeffs[i][j][4];
mmr[6] = comp->mmr_coeffs[i][j][5];
mmr[7] = comp->mmr_coeffs[i][j][6];
mmr_idx += 2;
}
break;
default:
pl_unreachable();
}
}
if (comp->num_pivots > 2) {
// Skip the (irrelevant) lower and upper bounds
float pivots_data[7];
memcpy(pivots_data, comp->pivots + 1,
(comp->num_pivots - 2) * sizeof(pivots_data[0]));
// Fill the remainder with a quasi-infinite sentinel pivot
for (int i = comp->num_pivots - 2; i < PL_ARRAY_SIZE(pivots_data); i++)
pivots_data[i] = 1e9f;
ident_t pivots = sh_var(sh, (struct pl_shader_var) {
.data = pivots_data,
.var = {
.name = "pivots",
.type = PL_VAR_FLOAT,
.dim_v = 1,
.dim_m = 1,
.dim_a = PL_ARRAY_SIZE(pivots_data),
},
});
ident_t coeffs = sh_var(sh, (struct pl_shader_var) {
.data = coeffs_data,
.var = {
.name = "coeffs",
.type = PL_VAR_FLOAT,
.dim_v = 4,
.dim_m = 1,
.dim_a = PL_ARRAY_SIZE(coeffs_data),
},
});
// Efficiently branch into the correct set of coefficients
GLSL("#define test(i) bvec4(s >= "$"[i]) \n"
"#define coef(i) "$"[i] \n"
"coeffs = mix(mix(mix(coef(0), coef(1), test(0)), \n"
" mix(coef(2), coef(3), test(2)), \n"
" test(1)), \n"
" mix(mix(coef(4), coef(5), test(4)), \n"
" mix(coef(6), coef(7), test(6)), \n"
" test(5)), \n"
" test(3)); \n"
"#undef test \n"
"#undef coef \n",
pivots, coeffs);
} else {
// No need for a single pivot, just set the coeffs directly
GLSL("coeffs = "$"; \n", sh_var(sh, (struct pl_shader_var) {
.var = pl_var_vec4("coeffs"),
.data = coeffs_data,
}));
}
ident_t mmr = NULL_IDENT;
if (has_mmr) {
mmr = sh_var(sh, (struct pl_shader_var) {
.data = mmr_packed_data,
.var = {
.name = "mmr",
.type = PL_VAR_FLOAT,
.dim_v = 4,
.dim_m = 1,
.dim_a = mmr_idx,
},
});
}
if (has_mmr && has_poly) {
GLSL("if (coeffs.w == 0.0) { \n");
reshape_poly(sh);
GLSL("} else { \n");
reshape_mmr(sh, mmr, mmr_single, min_order, max_order);
GLSL("} \n");
} else if (has_poly) {
reshape_poly(sh);
} else {
assert(has_mmr);
GLSL("{ \n");
reshape_mmr(sh, mmr, mmr_single, min_order, max_order);
GLSL("} \n");
}
ident_t lo = sh_var(sh, (struct pl_shader_var) {
.var = pl_var_float("lo"),
.data = &comp->pivots[0],
});
ident_t hi = sh_var(sh, (struct pl_shader_var) {
.var = pl_var_float("hi"),
.data = &comp->pivots[comp->num_pivots - 1],
});
GLSL("color[%d] = clamp(s, "$", "$"); \n", c, lo, hi);
}
GLSL("} \n");
#else
SH_FAIL(sh, "libplacebo was compiled without support for dolbyvision reshaping");
#endif
}
void pl_shader_decode_color(pl_shader sh, struct pl_color_repr *repr,
const struct pl_color_adjustment *params)
{
if (!sh_require(sh, PL_SHADER_SIG_COLOR, 0, 0))
return;
sh_describe(sh, "color decoding");
GLSL("// pl_shader_decode_color \n"
"{ \n");
// Do this first because the following operations are potentially nonlinear
pl_shader_set_alpha(sh, repr, PL_ALPHA_INDEPENDENT);
if (repr->sys == PL_COLOR_SYSTEM_XYZ ||
repr->sys == PL_COLOR_SYSTEM_DOLBYVISION)
{
ident_t scale = SH_FLOAT(pl_color_repr_normalize(repr));
GLSL("color.rgb *= vec3("$"); \n", scale);
}
if (repr->sys == PL_COLOR_SYSTEM_XYZ) {
pl_shader_linearize(sh, &(struct pl_color_space) {
.transfer = PL_COLOR_TRC_ST428,
});
}
if (repr->sys == PL_COLOR_SYSTEM_DOLBYVISION)
pl_shader_dovi_reshape(sh, repr->dovi);
enum pl_color_system orig_sys = repr->sys;
pl_transform3x3 tr = pl_color_repr_decode(repr, params);
if (memcmp(&tr, &pl_transform3x3_identity, sizeof(tr))) {
ident_t cmat = sh_var(sh, (struct pl_shader_var) {
.var = pl_var_mat3("cmat"),
.data = PL_TRANSPOSE_3X3(tr.mat.m),
});
ident_t cmat_c = sh_var(sh, (struct pl_shader_var) {
.var = pl_var_vec3("cmat_c"),
.data = tr.c,
});
GLSL("color.rgb = "$" * color.rgb + "$"; \n", cmat, cmat_c);
}
switch (orig_sys) {
case PL_COLOR_SYSTEM_BT_2020_C:
// Conversion for C'rcY'cC'bc via the BT.2020 CL system:
// C'bc = (B'-Y'c) / 1.9404 | C'bc <= 0
// = (B'-Y'c) / 1.5816 | C'bc > 0
//
// C'rc = (R'-Y'c) / 1.7184 | C'rc <= 0
// = (R'-Y'c) / 0.9936 | C'rc > 0
//
// as per the BT.2020 specification, table 4. This is a non-linear
// transformation because (constant) luminance receives non-equal
// contributions from the three different channels.
GLSL("// constant luminance conversion \n"
"color.br = color.br * mix(vec2(1.5816, 0.9936), \n"
" vec2(1.9404, 1.7184), \n"
" lessThanEqual(color.br, vec2(0.0))) \n"
" + color.gg; \n");
// Expand channels to camera-linear light. This shader currently just
// assumes everything uses the BT.2020 12-bit gamma function, since the
// difference between 10 and 12-bit is negligible for anything other
// than 12-bit content.
GLSL("vec3 lin = mix(color.rgb * vec3(1.0/4.5), \n"
" pow((color.rgb + vec3(0.0993))*vec3(1.0/1.0993), \n"
" vec3(1.0/0.45)), \n"
" lessThanEqual(vec3(0.08145), color.rgb)); \n");
// Calculate the green channel from the expanded RYcB, and recompress to G'
// The BT.2020 specification says Yc = 0.2627*R + 0.6780*G + 0.0593*B
GLSL("color.g = (lin.g - 0.2627*lin.r - 0.0593*lin.b)*1.0/0.6780; \n"
"color.g = mix(color.g * 4.5, \n"
" 1.0993 * pow(color.g, 0.45) - 0.0993, \n"
" 0.0181 <= color.g); \n");
break;
case PL_COLOR_SYSTEM_BT_2100_PQ:;
// Conversion process from the spec:
//
// 1. L'M'S' = cmat * ICtCp
// 2. LMS = linearize(L'M'S') (EOTF for PQ, inverse OETF for HLG)
// 3. RGB = lms2rgb * LMS
//
// After this we need to invert step 2 to arrive at non-linear RGB.
// (It's important we keep the transfer function conversion separate
// from the color system decoding, so we have to partially undo our
// work here even though we will end up linearizing later on anyway)
GLSL(// PQ EOTF
"color.rgb = pow(max(color.rgb, 0.0), vec3(1.0/%f)); \n"
"color.rgb = max(color.rgb - vec3(%f), 0.0) \n"
" / (vec3(%f) - vec3(%f) * color.rgb); \n"
"color.rgb = pow(color.rgb, vec3(1.0/%f)); \n"
// LMS matrix
"color.rgb = mat3( 3.43661, -0.79133, -0.0259499, \n"
" -2.50645, 1.98360, -0.0989137, \n"
" 0.06984, -0.192271, 1.12486) * color.rgb; \n"
// PQ OETF
"color.rgb = pow(max(color.rgb, 0.0), vec3(%f)); \n"
"color.rgb = (vec3(%f) + vec3(%f) * color.rgb) \n"
" / (vec3(1.0) + vec3(%f) * color.rgb); \n"
"color.rgb = pow(color.rgb, vec3(%f)); \n",
PQ_M2, PQ_C1, PQ_C2, PQ_C3, PQ_M1,
PQ_M1, PQ_C1, PQ_C2, PQ_C3, PQ_M2);
break;
case PL_COLOR_SYSTEM_BT_2100_HLG:
GLSL(// HLG OETF^-1
"color.rgb = mix(vec3(4.0) * color.rgb * color.rgb, \n"
" exp((color.rgb - vec3(%f)) * vec3(1.0/%f)) \n"
" + vec3(%f), \n"
" lessThan(vec3(0.5), color.rgb)); \n"
// LMS matrix
"color.rgb = mat3( 3.43661, -0.79133, -0.0259499, \n"
" -2.50645, 1.98360, -0.0989137, \n"
" 0.06984, -0.192271, 1.12486) * color.rgb; \n"
// HLG OETF
"color.rgb = mix(vec3(0.5) * sqrt(color.rgb), \n"
" vec3(%f) * log(color.rgb - vec3(%f)) + vec3(%f), \n"
" lessThan(vec3(1.0), color.rgb)); \n",
HLG_C, HLG_A, HLG_B,
HLG_A, HLG_B, HLG_C);
break;
case PL_COLOR_SYSTEM_DOLBYVISION:;
#ifdef PL_HAVE_DOVI
// Dolby Vision always outputs BT.2020-referred HPE LMS, so hard-code
// the inverse LMS->RGB matrix corresponding to this color space.
pl_matrix3x3 dovi_lms2rgb = {{
{ 3.06441879, -2.16597676, 0.10155818},
{-0.65612108, 1.78554118, -0.12943749},
{ 0.01736321, -0.04725154, 1.03004253},
}};
pl_matrix3x3_mul(&dovi_lms2rgb, &repr->dovi->linear);
ident_t mat = sh_var(sh, (struct pl_shader_var) {
.var = pl_var_mat3("lms2rgb"),
.data = PL_TRANSPOSE_3X3(dovi_lms2rgb.m),
});
// PQ EOTF
GLSL("color.rgb = pow(max(color.rgb, 0.0), vec3(1.0/%f)); \n"
"color.rgb = max(color.rgb - vec3(%f), 0.0) \n"
" / (vec3(%f) - vec3(%f) * color.rgb); \n"
"color.rgb = pow(color.rgb, vec3(1.0/%f)); \n",
PQ_M2, PQ_C1, PQ_C2, PQ_C3, PQ_M1);
// LMS matrix
GLSL("color.rgb = "$" * color.rgb; \n", mat);
// PQ OETF
GLSL("color.rgb = pow(max(color.rgb, 0.0), vec3(%f)); \n"
"color.rgb = (vec3(%f) + vec3(%f) * color.rgb) \n"
" / (vec3(1.0) + vec3(%f) * color.rgb); \n"
"color.rgb = pow(color.rgb, vec3(%f)); \n",
PQ_M1, PQ_C1, PQ_C2, PQ_C3, PQ_M2);
break;
#else
SH_FAIL(sh, "libplacebo was compiled without support for dolbyvision reshaping");
return;
#endif
case PL_COLOR_SYSTEM_UNKNOWN:
case PL_COLOR_SYSTEM_RGB:
case PL_COLOR_SYSTEM_XYZ:
case PL_COLOR_SYSTEM_BT_601:
case PL_COLOR_SYSTEM_BT_709:
case PL_COLOR_SYSTEM_SMPTE_240M:
case PL_COLOR_SYSTEM_BT_2020_NC:
case PL_COLOR_SYSTEM_YCGCO:
break; // no special post-processing needed
case PL_COLOR_SYSTEM_COUNT:
pl_unreachable();
}
// Gamma adjustment. Doing this here (in non-linear light) is technically
// somewhat wrong, but this is just an aesthetic parameter and not really
// meant for colorimetric precision, so we don't care too much.
if (params && params->gamma == 0) {
// Avoid division by zero
GLSL("color.rgb = vec3(0.0); \n");
} else if (params && params->gamma != 1) {
ident_t gamma = sh_var(sh, (struct pl_shader_var) {
.var = pl_var_float("gamma"),
.data = &(float){ 1 / params->gamma },
});
GLSL("color.rgb = pow(max(color.rgb, vec3(0.0)), vec3("$")); \n", gamma);
}
GLSL("}\n");
}
void pl_shader_encode_color(pl_shader sh, const struct pl_color_repr *repr)
{
if (!sh_require(sh, PL_SHADER_SIG_COLOR, 0, 0))
return;
sh_describe(sh, "color encoding");
GLSL("// pl_shader_encode_color \n"
"{ \n");
switch (repr->sys) {
case PL_COLOR_SYSTEM_BT_2020_C:
// Expand R'G'B' to RGB
GLSL("vec3 lin = mix(color.rgb * vec3(1.0/4.5), \n"
" pow((color.rgb + vec3(0.0993))*vec3(1.0/1.0993), \n"
" vec3(1.0/0.45)), \n"
" lessThanEqual(vec3(0.08145), color.rgb)); \n");
// Compute Yc from RGB and compress to R'Y'cB'
GLSL("color.g = dot(vec3(0.2627, 0.6780, 0.0593), lin); \n"
"color.g = mix(color.g * 4.5, \n"
" 1.0993 * pow(color.g, 0.45) - 0.0993, \n"
" 0.0181 <= color.g); \n");
// Compute C'bc and C'rc into color.br
GLSL("color.br = color.br - color.gg; \n"
"color.br *= mix(vec2(1.0/1.5816, 1.0/0.9936), \n"
" vec2(1.0/1.9404, 1.0/1.7184), \n"
" lessThanEqual(color.br, vec2(0.0))); \n");
break;
case PL_COLOR_SYSTEM_BT_2100_PQ:;
GLSL("color.rgb = pow(max(color.rgb, 0.0), vec3(1.0/%f)); \n"
"color.rgb = max(color.rgb - vec3(%f), 0.0) \n"
" / (vec3(%f) - vec3(%f) * color.rgb); \n"
"color.rgb = pow(color.rgb, vec3(1.0/%f)); \n"
"color.rgb = mat3(0.412109, 0.166748, 0.024170, \n"
" 0.523925, 0.720459, 0.075440, \n"
" 0.063965, 0.112793, 0.900394) * color.rgb; \n"
"color.rgb = pow(color.rgb, vec3(%f)); \n"
"color.rgb = (vec3(%f) + vec3(%f) * color.rgb) \n"
" / (vec3(1.0) + vec3(%f) * color.rgb); \n"
"color.rgb = pow(color.rgb, vec3(%f)); \n",
PQ_M2, PQ_C1, PQ_C2, PQ_C3, PQ_M1,
PQ_M1, PQ_C1, PQ_C2, PQ_C3, PQ_M2);
break;
case PL_COLOR_SYSTEM_BT_2100_HLG:
GLSL("color.rgb = mix(vec3(4.0) * color.rgb * color.rgb, \n"
" exp((color.rgb - vec3(%f)) * vec3(1.0/%f)) \n"
" + vec3(%f), \n"
" lessThan(vec3(0.5), color.rgb)); \n"
"color.rgb = mat3(0.412109, 0.166748, 0.024170, \n"
" 0.523925, 0.720459, 0.075440, \n"
" 0.063965, 0.112793, 0.900394) * color.rgb; \n"
"color.rgb = mix(vec3(0.5) * sqrt(color.rgb), \n"
" vec3(%f) * log(color.rgb - vec3(%f)) + vec3(%f), \n"
" lessThan(vec3(1.0), color.rgb)); \n",
HLG_C, HLG_A, HLG_B,
HLG_A, HLG_B, HLG_C);
break;
case PL_COLOR_SYSTEM_DOLBYVISION:
SH_FAIL(sh, "Cannot un-apply dolbyvision yet (no inverse reshaping)!");
return;
case PL_COLOR_SYSTEM_UNKNOWN:
case PL_COLOR_SYSTEM_RGB:
case PL_COLOR_SYSTEM_XYZ:
case PL_COLOR_SYSTEM_BT_601:
case PL_COLOR_SYSTEM_BT_709:
case PL_COLOR_SYSTEM_SMPTE_240M:
case PL_COLOR_SYSTEM_BT_2020_NC:
case PL_COLOR_SYSTEM_YCGCO:
break; // no special pre-processing needed
case PL_COLOR_SYSTEM_COUNT:
pl_unreachable();
}
// Since this is a relatively rare operation, bypass it as much as possible
bool skip = true;
skip &= PL_DEF(repr->sys, PL_COLOR_SYSTEM_RGB) == PL_COLOR_SYSTEM_RGB;
skip &= PL_DEF(repr->levels, PL_COLOR_LEVELS_FULL) == PL_COLOR_LEVELS_FULL;
skip &= !repr->bits.sample_depth || !repr->bits.color_depth ||
repr->bits.sample_depth == repr->bits.color_depth;
skip &= !repr->bits.bit_shift;
if (!skip) {
struct pl_color_repr copy = *repr;
ident_t xyzscale = NULL_IDENT;
if (repr->sys == PL_COLOR_SYSTEM_XYZ)
xyzscale = SH_FLOAT(1.0 / pl_color_repr_normalize(©));
pl_transform3x3 tr = pl_color_repr_decode(©, NULL);
pl_transform3x3_invert(&tr);
ident_t cmat = sh_var(sh, (struct pl_shader_var) {
.var = pl_var_mat3("cmat"),
.data = PL_TRANSPOSE_3X3(tr.mat.m),
});
ident_t cmat_c = sh_var(sh, (struct pl_shader_var) {
.var = pl_var_vec3("cmat_c"),
.data = tr.c,
});
GLSL("color.rgb = "$" * color.rgb + "$"; \n", cmat, cmat_c);
if (repr->sys == PL_COLOR_SYSTEM_XYZ) {
pl_shader_delinearize(sh, &(struct pl_color_space) {
.transfer = PL_COLOR_TRC_ST428,
});
GLSL("color.rgb *= vec3("$"); \n", xyzscale);
}
}
if (repr->alpha == PL_ALPHA_PREMULTIPLIED)
GLSL("color.rgb *= vec3(color.a); \n");
GLSL("}\n");
}
static ident_t sh_luma_coeffs(pl_shader sh, const struct pl_color_space *csp)
{
pl_matrix3x3 rgb2xyz;
rgb2xyz = pl_get_rgb2xyz_matrix(pl_raw_primaries_get(csp->primaries));
// FIXME: Cannot use `const vec3` due to glslang bug #2025
ident_t coeffs = sh_fresh(sh, "luma_coeffs");
GLSLH("#define "$" vec3("$", "$", "$") \n", coeffs,
SH_FLOAT(rgb2xyz.m[1][0]), // RGB->Y vector
SH_FLOAT(rgb2xyz.m[1][1]),
SH_FLOAT(rgb2xyz.m[1][2]));
return coeffs;
}
void pl_shader_linearize(pl_shader sh, const struct pl_color_space *csp)
{
if (!sh_require(sh, PL_SHADER_SIG_COLOR, 0, 0))
return;
if (csp->transfer == PL_COLOR_TRC_LINEAR)
return;
float csp_min, csp_max;
pl_color_space_nominal_luma_ex(pl_nominal_luma_params(
.color = csp,
.metadata = PL_HDR_METADATA_HDR10,
.scaling = PL_HDR_NORM,
.out_min = &csp_min,
.out_max = &csp_max,
));
// Note that this clamp may technically violate the definition of
// ITU-R BT.2100, which allows for sub-blacks and super-whites to be
// displayed on the display where such would be possible. That said, the
// problem is that not all gamma curves are well-defined on the values
// outside this range, so we ignore it and just clamp anyway for sanity.
GLSL("// pl_shader_linearize \n"
"color.rgb = max(color.rgb, 0.0); \n");
switch (csp->transfer) {
case PL_COLOR_TRC_SRGB:
GLSL("color.rgb = mix(color.rgb * vec3(1.0/12.92), \n"
" pow((color.rgb + vec3(0.055))/vec3(1.055), \n"
" vec3(2.4)), \n"
" lessThan(vec3(0.04045), color.rgb)); \n");
goto scale_out;
case PL_COLOR_TRC_BT_1886: {
const float lb = powf(csp_min, 1/2.4f);
const float lw = powf(csp_max, 1/2.4f);
const float a = powf(lw - lb, 2.4f);
const float b = lb / (lw - lb);
GLSL("color.rgb = "$" * pow(color.rgb + vec3("$"), vec3(2.4)); \n",
SH_FLOAT(a), SH_FLOAT(b));
return;
}
case PL_COLOR_TRC_GAMMA18:
GLSL("color.rgb = pow(color.rgb, vec3(1.8));\n");
goto scale_out;
case PL_COLOR_TRC_GAMMA20:
GLSL("color.rgb = pow(color.rgb, vec3(2.0));\n");
goto scale_out;
case PL_COLOR_TRC_UNKNOWN:
case PL_COLOR_TRC_GAMMA22:
GLSL("color.rgb = pow(color.rgb, vec3(2.2));\n");
goto scale_out;
case PL_COLOR_TRC_GAMMA24:
GLSL("color.rgb = pow(color.rgb, vec3(2.4));\n");
goto scale_out;
case PL_COLOR_TRC_GAMMA26:
GLSL("color.rgb = pow(color.rgb, vec3(2.6));\n");
goto scale_out;
case PL_COLOR_TRC_GAMMA28:
GLSL("color.rgb = pow(color.rgb, vec3(2.8));\n");
goto scale_out;
case PL_COLOR_TRC_PRO_PHOTO:
GLSL("color.rgb = mix(color.rgb * vec3(1.0/16.0), \n"
" pow(color.rgb, vec3(1.8)), \n"
" lessThan(vec3(0.03125), color.rgb)); \n");
goto scale_out;
case PL_COLOR_TRC_ST428:
GLSL("color.rgb = vec3(52.37/48.0) * pow(color.rgb, vec3(2.6));\n");
goto scale_out;
case PL_COLOR_TRC_PQ:
GLSL("color.rgb = pow(color.rgb, vec3(1.0/%f)); \n"
"color.rgb = max(color.rgb - vec3(%f), 0.0) \n"
" / (vec3(%f) - vec3(%f) * color.rgb); \n"
"color.rgb = pow(color.rgb, vec3(1.0/%f)); \n"
// PQ's output range is 0-10000, but we need it to be relative to
// to PL_COLOR_SDR_WHITE instead, so rescale
"color.rgb *= vec3(%f); \n",
PQ_M2, PQ_C1, PQ_C2, PQ_C3, PQ_M1, 10000.0 / PL_COLOR_SDR_WHITE);
return;
case PL_COLOR_TRC_HLG: {
const float y = fmaxf(1.2f + 0.42f * log10f(csp_max / HLG_REF), 1);
const float b = sqrtf(3 * powf(csp_min / csp_max, 1 / y));
// OETF^-1
GLSL("color.rgb = "$" * color.rgb + vec3("$"); \n"
"color.rgb = mix(vec3(4.0) * color.rgb * color.rgb, \n"
" exp((color.rgb - vec3(%f)) * vec3(1.0/%f))\n"
" + vec3(%f), \n"
" lessThan(vec3(0.5), color.rgb)); \n",
SH_FLOAT(1 - b), SH_FLOAT(b),
HLG_C, HLG_A, HLG_B);
// OOTF
GLSL("color.rgb *= 1.0 / 12.0; \n"
"color.rgb *= "$" * pow(max(dot("$", color.rgb), 0.0), "$"); \n",
SH_FLOAT(csp_max), sh_luma_coeffs(sh, csp), SH_FLOAT(y - 1));
return;
}
case PL_COLOR_TRC_V_LOG:
GLSL("color.rgb = mix((color.rgb - vec3(0.125)) * vec3(1.0/5.6), \n"
" pow(vec3(10.0), (color.rgb - vec3(%f)) * vec3(1.0/%f)) \n"
" - vec3(%f), \n"
" lessThanEqual(vec3(0.181), color.rgb)); \n",
VLOG_D, VLOG_C, VLOG_B);
return;
case PL_COLOR_TRC_S_LOG1:
GLSL("color.rgb = pow(vec3(10.0), (color.rgb - vec3(%f)) * vec3(1.0/%f)) \n"
" - vec3(%f); \n",
SLOG_C, SLOG_A, SLOG_B);
return;
case PL_COLOR_TRC_S_LOG2:
GLSL("color.rgb = mix((color.rgb - vec3(%f)) * vec3(1.0/%f), \n"
" (pow(vec3(10.0), (color.rgb - vec3(%f)) * vec3(1.0/%f)) \n"
" - vec3(%f)) * vec3(1.0/%f), \n"
" lessThanEqual(vec3(%f), color.rgb)); \n",
SLOG_Q, SLOG_P, SLOG_C, SLOG_A, SLOG_B, SLOG_K2, SLOG_Q);
return;
case PL_COLOR_TRC_LINEAR:
case PL_COLOR_TRC_COUNT:
break;
}
pl_unreachable();
scale_out:
if (csp_max != 1 || csp_min != 0) {
GLSL("color.rgb = "$" * color.rgb + vec3("$"); \n",
SH_FLOAT(csp_max - csp_min), SH_FLOAT(csp_min));
}
}
void pl_shader_delinearize(pl_shader sh, const struct pl_color_space *csp)
{
if (!sh_require(sh, PL_SHADER_SIG_COLOR, 0, 0))
return;
if (csp->transfer == PL_COLOR_TRC_LINEAR)
return;
float csp_min, csp_max;
pl_color_space_nominal_luma_ex(pl_nominal_luma_params(
.color = csp,
.metadata = PL_HDR_METADATA_HDR10,
.scaling = PL_HDR_NORM,
.out_min = &csp_min,
.out_max = &csp_max,
));
GLSL("// pl_shader_delinearize \n");
if (pl_color_space_is_black_scaled(csp) &&
csp->transfer != PL_COLOR_TRC_HLG &&
(csp_max != 1 || csp_min != 0))
{
GLSL("color.rgb = "$" * color.rgb + vec3("$"); \n",
SH_FLOAT(1 / (csp_max - csp_min)),
SH_FLOAT(-csp_min / (csp_max - csp_min)));
}
GLSL("color.rgb = max(color.rgb, 0.0); \n");
switch (csp->transfer) {
case PL_COLOR_TRC_SRGB:
GLSL("color.rgb = mix(color.rgb * vec3(12.92), \n"
" vec3(1.055) * pow(color.rgb, vec3(1.0/2.4)) \n"
" - vec3(0.055), \n"
" lessThanEqual(vec3(0.0031308), color.rgb)); \n");
return;
case PL_COLOR_TRC_BT_1886: {
const float lb = powf(csp_min, 1/2.4f);
const float lw = powf(csp_max, 1/2.4f);
const float a = powf(lw - lb, 2.4f);
const float b = lb / (lw - lb);
GLSL("color.rgb = pow("$" * color.rgb, vec3(1.0/2.4)) - vec3("$"); \n",
SH_FLOAT(1.0 / a), SH_FLOAT(b));
return;
}
case PL_COLOR_TRC_GAMMA18:
GLSL("color.rgb = pow(color.rgb, vec3(1.0/1.8));\n");
return;
case PL_COLOR_TRC_GAMMA20:
GLSL("color.rgb = pow(color.rgb, vec3(1.0/2.0));\n");
return;
case PL_COLOR_TRC_UNKNOWN:
case PL_COLOR_TRC_GAMMA22:
GLSL("color.rgb = pow(color.rgb, vec3(1.0/2.2));\n");
return;
case PL_COLOR_TRC_GAMMA24:
GLSL("color.rgb = pow(color.rgb, vec3(1.0/2.4));\n");
return;
case PL_COLOR_TRC_GAMMA26:
GLSL("color.rgb = pow(color.rgb, vec3(1.0/2.6));\n");
return;
case PL_COLOR_TRC_GAMMA28:
GLSL("color.rgb = pow(color.rgb, vec3(1.0/2.8));\n");
return;
case PL_COLOR_TRC_ST428:
GLSL("color.rgb = pow(color.rgb * vec3(48.0/52.37), vec3(1.0/2.6));\n");
return;
case PL_COLOR_TRC_PRO_PHOTO:
GLSL("color.rgb = mix(color.rgb * vec3(16.0), \n"
" pow(color.rgb, vec3(1.0/1.8)), \n"
" lessThanEqual(vec3(0.001953), color.rgb)); \n");
return;
case PL_COLOR_TRC_PQ:
GLSL("color.rgb *= vec3(1.0/%f); \n"
"color.rgb = pow(color.rgb, vec3(%f)); \n"
"color.rgb = (vec3(%f) + vec3(%f) * color.rgb) \n"
" / (vec3(1.0) + vec3(%f) * color.rgb); \n"
"color.rgb = pow(color.rgb, vec3(%f)); \n",
10000 / PL_COLOR_SDR_WHITE, PQ_M1, PQ_C1, PQ_C2, PQ_C3, PQ_M2);
return;
case PL_COLOR_TRC_HLG: {
const float y = fmaxf(1.2f + 0.42f * log10f(csp_max / HLG_REF), 1);
const float b = sqrtf(3 * powf(csp_min / csp_max, 1 / y));
// OOTF^-1
GLSL("color.rgb *= 1.0 / "$"; \n"
"color.rgb *= 12.0 * max(1e-6, pow(dot("$", color.rgb), "$")); \n",
SH_FLOAT(csp_max), sh_luma_coeffs(sh, csp), SH_FLOAT((1 - y) / y));
// OETF
GLSL("color.rgb = mix(vec3(0.5) * sqrt(color.rgb), \n"
" vec3(%f) * log(color.rgb - vec3(%f)) + vec3(%f), \n"
" lessThan(vec3(1.0), color.rgb)); \n"
"color.rgb = "$" * color.rgb + vec3("$"); \n",
HLG_A, HLG_B, HLG_C,
SH_FLOAT(1 / (1 - b)), SH_FLOAT(-b / (1 - b)));
return;
}
case PL_COLOR_TRC_V_LOG:
GLSL("color.rgb = mix(vec3(5.6) * color.rgb + vec3(0.125), \n"
" vec3(%f) * log(color.rgb + vec3(%f)) \n"
" + vec3(%f), \n"
" lessThanEqual(vec3(0.01), color.rgb)); \n",
VLOG_C / M_LN10, VLOG_B, VLOG_D);
return;
case PL_COLOR_TRC_S_LOG1:
GLSL("color.rgb = vec3(%f) * log(color.rgb + vec3(%f)) + vec3(%f);\n",
SLOG_A / M_LN10, SLOG_B, SLOG_C);
return;
case PL_COLOR_TRC_S_LOG2:
GLSL("color.rgb = mix(vec3(%f) * color.rgb + vec3(%f), \n"
" vec3(%f) * log(vec3(%f) * color.rgb + vec3(%f)) \n"
" + vec3(%f), \n"
" lessThanEqual(vec3(0.0), color.rgb)); \n",
SLOG_P, SLOG_Q, SLOG_A / M_LN10, SLOG_K2, SLOG_B, SLOG_C);
return;
case PL_COLOR_TRC_LINEAR:
case PL_COLOR_TRC_COUNT:
break;
}
pl_unreachable();
}
const struct pl_sigmoid_params pl_sigmoid_default_params = { PL_SIGMOID_DEFAULTS };
void pl_shader_sigmoidize(pl_shader sh, const struct pl_sigmoid_params *params)
{
if (!sh_require(sh, PL_SHADER_SIG_COLOR, 0, 0))
return;
params = PL_DEF(params, &pl_sigmoid_default_params);
float center = PL_DEF(params->center, pl_sigmoid_default_params.center);
float slope = PL_DEF(params->slope, pl_sigmoid_default_params.slope);
// This function needs to go through (0,0) and (1,1), so we compute the
// values at 1 and 0, and then scale/shift them, respectively.
float offset = 1.0 / (1 + expf(slope * center));
float scale = 1.0 / (1 + expf(slope * (center - 1))) - offset;
GLSL("// pl_shader_sigmoidize \n"
"color.rgb = clamp(color.rgb, 0.0, 1.0); \n"
"color.rgb = vec3("$") - vec3("$") * \n"
" log(vec3(1.0) / (color.rgb * vec3("$") + vec3("$")) \n"
" - vec3(1.0)); \n",
SH_FLOAT(center), SH_FLOAT(1.0 / slope),
SH_FLOAT(scale), SH_FLOAT(offset));
}
void pl_shader_unsigmoidize(pl_shader sh, const struct pl_sigmoid_params *params)
{
if (!sh_require(sh, PL_SHADER_SIG_COLOR, 0, 0))
return;
// See: pl_shader_sigmoidize
params = PL_DEF(params, &pl_sigmoid_default_params);
float center = PL_DEF(params->center, pl_sigmoid_default_params.center);
float slope = PL_DEF(params->slope, pl_sigmoid_default_params.slope);
float offset = 1.0 / (1 + expf(slope * center));
float scale = 1.0 / (1 + expf(slope * (center - 1))) - offset;
GLSL("// pl_shader_unsigmoidize \n"
"color.rgb = clamp(color.rgb, 0.0, 1.0); \n"
"color.rgb = vec3("$") / \n"
" (vec3(1.0) + exp(vec3("$") * (vec3("$") - color.rgb))) \n"
" - vec3("$"); \n",
SH_FLOAT(1.0 / scale),
SH_FLOAT(slope), SH_FLOAT(center),
SH_FLOAT(offset / scale));
}
const struct pl_peak_detect_params pl_peak_detect_default_params = { PL_PEAK_DETECT_DEFAULTS };
const struct pl_peak_detect_params pl_peak_detect_high_quality_params = { PL_PEAK_DETECT_HQ_DEFAULTS };
static bool peak_detect_params_eq(const struct pl_peak_detect_params *a,
const struct pl_peak_detect_params *b)
{
return a->smoothing_period == b->smoothing_period &&
a->scene_threshold_low == b->scene_threshold_low &&
a->scene_threshold_high == b->scene_threshold_high &&
a->percentile == b->percentile;
// don't compare `allow_delayed` because it doesn't change measurement
}
enum {
// Split the peak buffer into several independent slices to reduce pressure
// on global atomics
SLICES = 12,
// How many bits to use for storing PQ data. Be careful when setting this
// too high, as it may overflow `unsigned int` on large video sources.
//
// The value chosen is enough to guarantee no overflow for an 8K x 4K frame
// consisting entirely of 100% 10k nits PQ values, with 16x16 workgroups.
PQ_BITS = 14,
PQ_MAX = (1 << PQ_BITS) - 1,
// How many bits to use for the histogram. We bias the histogram down
// by half the PQ range (~90 nits), effectively clumping the SDR part
// of the image into a single histogram bin.
HIST_BITS = 7,
HIST_BIAS = 1 << (HIST_BITS - 1),
HIST_BINS = (1 << HIST_BITS) - HIST_BIAS,
// Convert from histogram bin to (starting) PQ value
#define HIST_PQ(bin) (((bin) + HIST_BIAS) << (PQ_BITS - HIST_BITS))
};
pl_static_assert(PQ_BITS >= HIST_BITS);
struct peak_buf_data {
unsigned frame_wg_count[SLICES]; // number of work groups processed
unsigned frame_wg_active[SLICES];// number of active (nonzero) work groups
unsigned frame_sum_pq[SLICES]; // sum of PQ Y values over all WGs (PQ_BITS)
unsigned frame_max_pq[SLICES]; // maximum PQ Y value among these WGs (PQ_BITS)
unsigned frame_hist[SLICES][HIST_BINS]; // always allocated, conditionally used
};
static const struct pl_buffer_var peak_buf_vars[] = {
#define VAR(field) { \
.var = { \
.name = #field, \
.type = PL_VAR_UINT, \
.dim_v = 1, \
.dim_m = 1, \
.dim_a = sizeof(((struct peak_buf_data *) NULL)->field) / \
sizeof(unsigned), \
}, \
.layout = { \
.offset = offsetof(struct peak_buf_data, field), \
.size = sizeof(((struct peak_buf_data *) NULL)->field), \
.stride = sizeof(unsigned), \
}, \
}
VAR(frame_wg_count),
VAR(frame_wg_active),
VAR(frame_sum_pq),
VAR(frame_max_pq),
VAR(frame_hist),
#undef VAR
};
struct sh_color_map_obj {
// Tone map state
struct {
struct pl_tone_map_params params;
pl_shader_obj lut;
} tone;
// Gamut map state
struct {
pl_shader_obj lut;
} gamut;
// Peak detection state
struct {
struct pl_peak_detect_params params; // currently active parameters
pl_buf buf; // pending peak detection buffer
pl_buf readback; // readback buffer (fallback)
float avg_pq; // current (smoothed) values
float max_pq;
} peak;
};
// Excluding size, since this is checked by sh_lut
static uint64_t gamut_map_signature(const struct pl_gamut_map_params *par)
{
uint64_t sig = CACHE_KEY_GAMUT_LUT;
pl_hash_merge(&sig, pl_str0_hash(par->function->name));