summaryrefslogtreecommitdiffstats
path: root/video/out/gpu/video_shaders.c
blob: 19fb0ccde8efb7b7ce148cf9ef31a86129d8ab6c (plain)
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
/*
 * This file is part of mpv.
 *
 * mpv 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.
 *
 * mpv 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 mpv.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <math.h>

#include "video_shaders.h"
#include "video.h"

#define GLSL(x) gl_sc_add(sc, #x "\n");
#define GLSLF(...) gl_sc_addf(sc, __VA_ARGS__)
#define GLSLH(x) gl_sc_hadd(sc, #x "\n");
#define GLSLHF(...) gl_sc_haddf(sc, __VA_ARGS__)

// Set up shared/commonly used variables and macros
void sampler_prelude(struct gl_shader_cache *sc, int tex_num)
{
    GLSLF("#undef tex\n");
    GLSLF("#undef texmap\n");
    GLSLF("#define tex texture%d\n", tex_num);
    GLSLF("#define texmap texmap%d\n", tex_num);
    GLSLF("vec2 pos = texcoord%d;\n", tex_num);
    GLSLF("vec2 size = texture_size%d;\n", tex_num);
    GLSLF("vec2 pt = pixel_size%d;\n", tex_num);
}

static void pass_sample_separated_get_weights(struct gl_shader_cache *sc,
                                              struct scaler *scaler)
{
    gl_sc_uniform_texture(sc, "lut", scaler->lut);
    GLSLF("float ypos = LUT_POS(fcoord, %d.0);\n", scaler->lut_size);

    int N = scaler->kernel->size;
    int width = (N + 3) / 4; // round up

    GLSLF("float weights[%d];\n", N);
    for (int i = 0; i < N; i++) {
        if (i % 4 == 0)
            GLSLF("c = texture(lut, vec2(%f, ypos));\n", (i / 4 + 0.5) / width);
        GLSLF("weights[%d] = c[%d];\n", i, i % 4);
    }
}

// Handle a single pass (either vertical or horizontal). The direction is given
// by the vector (d_x, d_y). If the vector is 0, then planar interpolation is
// used instead (samples from texture0 through textureN)
void pass_sample_separated_gen(struct gl_shader_cache *sc, struct scaler *scaler,
                               int d_x, int d_y)
{
    int N = scaler->kernel->size;
    bool use_ar = scaler->conf.antiring > 0;
    bool planar = d_x == 0 && d_y == 0;
    GLSL(color = vec4(0.0);)
    GLSLF("{\n");
    if (!planar) {
        GLSLF("vec2 dir = vec2(%d.0, %d.0);\n", d_x, d_y);
        GLSL(pt *= dir;)
        GLSL(float fcoord = dot(fract(pos * size - vec2(0.5)), dir);)
        GLSLF("vec2 base = pos - fcoord * pt - pt * vec2(%d.0);\n", N / 2 - 1);
    }
    GLSL(vec4 c;)
    if (use_ar) {
        GLSL(vec4 hi = vec4(0.0);)
        GLSL(vec4 lo = vec4(1.0);)
    }
    pass_sample_separated_get_weights(sc, scaler);
    GLSLF("// scaler samples\n");
    for (int n = 0; n < N; n++) {
        if (planar) {
            GLSLF("c = texture(texture%d, texcoord%d);\n", n, n);
        } else {
            GLSLF("c = texture(tex, base + pt * vec2(%d.0));\n", n);
        }
        GLSLF("color += vec4(weights[%d]) * c;\n", n);
        if (use_ar && (n == N/2-1 || n == N/2)) {
            GLSL(lo = min(lo, c);)
            GLSL(hi = max(hi, c);)
        }
    }
    if (use_ar)
        GLSLF("color = mix(color, clamp(color, lo, hi), %f);\n",
              scaler->conf.antiring);
    GLSLF("}\n");
}

// Subroutine for computing and adding an individual texel contribution
// If planar is false, samples directly
// If planar is true, takes the pixel from inX[idx] where X is the component and
// `idx` must be defined by the caller
static void polar_sample(struct gl_shader_cache *sc, struct scaler *scaler,
                         int x, int y, int components, bool planar)
{
    double radius = scaler->kernel->f.radius * scaler->kernel->filter_scale;
    double radius_cutoff = scaler->kernel->radius_cutoff;

    // Since we can't know the subpixel position in advance, assume a
    // worst case scenario
    int yy = y > 0 ? y-1 : y;
    int xx = x > 0 ? x-1 : x;
    double dmax = sqrt(xx*xx + yy*yy);
    // Skip samples definitely outside the radius
    if (dmax >= radius_cutoff)
        return;
    GLSLF("d = length(vec2(%d.0, %d.0) - fcoord);\n", x, y);
    // Check for samples that might be skippable
    bool maybe_skippable = dmax >= radius_cutoff - M_SQRT2;
    if (maybe_skippable)
        GLSLF("if (d < %f) {\n", radius_cutoff);

    // get the weight for this pixel
    if (scaler->lut->params.dimensions == 1) {
        GLSLF("w = tex1D(lut, LUT_POS(d * 1.0/%f, %d.0)).r;\n",
              radius, scaler->lut_size);
    } else {
        GLSLF("w = texture(lut, vec2(0.5, LUT_POS(d * 1.0/%f, %d.0))).r;\n",
              radius, scaler->lut_size);
    }
    GLSL(wsum += w;)

    if (planar) {
        for (int n = 0; n < components; n++)
            GLSLF("color[%d] += w * in%d[idx];\n", n, n);
    } else {
        GLSLF("in0 = texture(tex, base + pt * vec2(%d.0, %d.0));\n", x, y);
        GLSL(color += vec4(w) * in0;)
    }

    if (maybe_skippable)
        GLSLF("}\n");
}

void pass_sample_polar(struct gl_shader_cache *sc, struct scaler *scaler,
                       int components, bool sup_gather)
{
    GLSL(color = vec4(0.0);)
    GLSLF("{\n");
    GLSL(vec2 fcoord = fract(pos * size - vec2(0.5));)
    GLSL(vec2 base = pos - fcoord * pt;)
    GLSLF("float w, d, wsum = 0.0;\n");
    for (int n = 0; n < components; n++)
        GLSLF("vec4 in%d;\n", n);
    GLSL(int idx;)

    gl_sc_uniform_texture(sc, "lut", scaler->lut);

    GLSLF("// scaler samples\n");
    int bound = ceil(scaler->kernel->radius_cutoff);
    for (int y = 1-bound; y <= bound; y += 2) {
        for (int x = 1-bound; x <= bound; x += 2) {
            // First we figure out whether it's more efficient to use direct
            // sampling or gathering. The problem is that gathering 4 texels
            // only to discard some of them is very wasteful, so only do it if
            // we suspect it will be a win rather than a loss. This is the case
            // exactly when all four texels are within bounds
            bool use_gather = sqrt(x*x + y*y) < scaler->kernel->radius_cutoff;

            if (!sup_gather)
                use_gather = false;

            if (use_gather) {
                // Gather the four surrounding texels simultaneously
                for (int n = 0; n < components; n++) {
                    GLSLF("in%d = textureGatherOffset(tex, base, "
                          "ivec2(%d, %d), %d);\n", n, x, y, n);
                }

                // Mix in all of the points with their weights
                for (int p = 0; p < 4; p++) {
                    // The four texels are gathered counterclockwise starting
                    // from the bottom left
                    static const int xo[4] = {0, 1, 1, 0};
                    static const int yo[4] = {1, 1, 0, 0};
                    if (x+xo[p] > bound || y+yo[p] > bound)
                        continue;
                    GLSLF("idx = %d;\n", p);
                    polar_sample(sc, scaler, x+xo[p], y+yo[p], components, true);
                }
            } else {
                // switch to direct sampling instead, for efficiency/compatibility
                for (int yy = y; yy <= bound && yy <= y+1; yy++) {
                    for (int xx = x; xx <= bound && xx <= x+1; xx++)
                        polar_sample(sc, scaler, xx, yy, components, false);
                }
            }
        }
    }

    GLSL(color = color / vec4(wsum);)
    GLSLF("}\n");
}

// bw/bh: block size
// iw/ih: input size (pre-calculated to fit all required texels)
void pass_compute_polar(struct gl_shader_cache *sc, struct scaler *scaler,
                        int components, int bw, int bh, int iw, int ih)
{
    int bound = ceil(scaler->kernel->radius_cutoff);
    int offset = bound - 1; // padding top/left

    GLSL(color = vec4(0.0);)
    GLSLF("{\n");
    GLSL(vec2 wpos = texmap(gl_WorkGroupID * gl_WorkGroupSize);)
    GLSL(vec2 wbase = wpos - pt * fract(wpos * size - vec2(0.5));)
    GLSL(vec2 fcoord = fract(pos * size - vec2(0.5));)
    GLSL(vec2 base = pos - pt * fcoord;)
    GLSL(ivec2 rel = ivec2(round((base - wbase) * size));)
    GLSL(int idx;)
    GLSLF("float w, d, wsum = 0.0;\n");
    gl_sc_uniform_texture(sc, "lut", scaler->lut);

    // Load all relevant texels into shmem
    for (int c = 0; c < components; c++)
        GLSLHF("shared float in%d[%d];\n", c, ih * iw);

    GLSL(vec4 c;)
    GLSLF("for (int y = int(gl_LocalInvocationID.y); y < %d; y += %d) {\n", ih, bh);
    GLSLF("for (int x = int(gl_LocalInvocationID.x); x < %d; x += %d) {\n", iw, bw);
    GLSLF("c = texture(tex, wbase + pt * vec2(x - %d, y - %d));\n", offset, offset);
    for (int c = 0; c < components; c++)
        GLSLF("in%d[%d * y + x] = c[%d];\n", c, iw, c);
    GLSLF("}}\n");
    GLSL(groupMemoryBarrier();)
    GLSL(barrier();)

    // Dispatch the actual samples
    GLSLF("// scaler samples\n");
    for (int y = 1-bound; y <= bound; y++) {
        for (int x = 1-bound; x <= bound; x++) {
            GLSLF("idx = %d * rel.y + rel.x + %d;\n", iw,
                  iw * (y + offset) + x + offset);
            polar_sample(sc, scaler, x, y, components, true);
        }
    }

    GLSL(color = color / vec4(wsum);)
    GLSLF("}\n");
}

static void bicubic_calcweights(struct gl_shader_cache *sc, const char *t, const char *s)
{
    // Explanation of how bicubic scaling with only 4 texel fetches is done:
    //   http://www.mate.tue.nl/mate/pdfs/10318.pdf
    //   'Efficient GPU-Based Texture Interpolation using Uniform B-Splines'
    // Explanation why this algorithm normally always blurs, even with unit
    // scaling:
    //   http://bigwww.epfl.ch/preprints/ruijters1001p.pdf
    //   'GPU Prefilter for Accurate Cubic B-spline Interpolation'
    GLSLF("vec4 %s = vec4(-0.5, 0.1666, 0.3333, -0.3333) * %s"
                " + vec4(1, 0, -0.5, 0.5);\n", t, s);
    GLSLF("%s = %s * %s + vec4(0, 0, -0.5, 0.5);\n", t, t, s);
    GLSLF("%s = %s * %s + vec4(-0.6666, 0, 0.8333, 0.1666);\n", t, t, s);
    GLSLF("%s.xy *= vec2(1, 1) / vec2(%s.z, %s.w);\n", t, t, t);
    GLSLF("%s.xy += vec2(1.0 + %s, 1.0 - %s);\n", t, s, s);
}

void pass_sample_bicubic_fast(struct gl_shader_cache *sc)
{
    GLSLF("{\n");
    GLSL(vec2 fcoord = fract(pos * size + vec2(0.5, 0.5));)
    bicubic_calcweights(sc, "parmx", "fcoord.x");
    bicubic_calcweights(sc, "parmy", "fcoord.y");
    GLSL(vec4 cdelta;)
    GLSL(cdelta.xz = parmx.rg * vec2(-pt.x, pt.x);)
    GLSL(cdelta.yw = parmy.rg * vec2(-pt.y, pt.y);)
    // first y-interpolation
    GLSL(vec4 ar = texture(tex, pos + cdelta.xy);)
    GLSL(vec4 ag = texture(tex, pos + cdelta.xw);)
    GLSL(vec4 ab = mix(ag, ar, parmy.b);)
    // second y-interpolation
    GLSL(vec4 br = texture(tex, pos + cdelta.zy);)
    GLSL(vec4 bg = texture(tex, pos + cdelta.zw);)
    GLSL(vec4 aa = mix(bg, br, parmy.b);)
    // x-interpolation
    GLSL(color = mix(aa, ab, parmx.b);)
    GLSLF("}\n");
}

void pass_sample_oversample(struct gl_shader_cache *sc, struct scaler *scaler,
                                   int w, int h)
{
    GLSLF("{\n");
    GLSL(vec2 pos = pos - vec2(0.5) * pt;) // round to nearest
    GLSL(vec2 fcoord = fract(pos * size - vec2(0.5));)
    // Determine the mixing coefficient vector
    gl_sc_uniform_vec2(sc, "output_size", (float[2]){w, h});
    GLSL(vec2 coeff = fcoord * output_size/size;)
    float threshold = scaler->conf.kernel.params[0];
    threshold = isnan(threshold) ? 0.0 : threshold;
    GLSLF("coeff = (coeff - %f) * 1.0/%f;\n", threshold, 1.0 - 2 * threshold);
    GLSL(coeff = clamp(coeff, 0.0, 1.0);)
    // Compute the right blend of colors
    GLSL(color = texture(tex, pos + pt * (coeff - fcoord));)
    GLSLF("}\n");
}

// Common constants for SMPTE ST.2084 (HDR)
static const float PQ_M1 = 2610./4096 * 1./4,
                   PQ_M2 = 2523./4096 * 128,
                   PQ_C1 = 3424./4096,
                   PQ_C2 = 2413./4096 * 32,
                   PQ_C3 = 2392./4096 * 32;

// Common constants for ARIB STD-B67 (HLG)
static const float HLG_A = 0.17883277,
                   HLG_B = 0.28466892,
                   HLG_C = 0.55991073;

// Common constants for Panasonic V-Log
static const float VLOG_B = 0.00873,
                   VLOG_C = 0.241514,
                   VLOG_D = 0.598206;

// Common constants for Sony S-Log
static const float SLOG_A = 0.432699,
                   SLOG_B = 0.037584,
                   SLOG_C = 0.616596 + 0.03,
                   SLOG_P = 3.538813,
                   SLOG_Q = 0.030001,
                   SLOG_K2 = 155.0 / 219.0;

// Linearize (expand), given a TRC as input. In essence, this is the ITU-R
// EOTF, calculated on an idealized (reference) monitor with a white point of
// MP_REF_WHITE and infinite contrast.
//
// These functions always output to a normalized scale of [0,1], for
// convenience of the video.c code that calls it. To get the values in an
// absolute scale, multiply the result by `mp_trc_nom_peak(trc)`
void pass_linearize(struct gl_shader_cache *sc, enum mp_csp_trc trc)
{
    if (trc == MP_CSP_TRC_LINEAR)
        return;

    GLSLF("// linearize\n");

    // 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 clip anyway for sanity.
    GLSL(color.rgb = clamp(color.rgb, 0.0, 1.0);)

    switch (trc) {
    case MP_CSP_TRC_SRGB:
        GLSL(color.rgb = mix(color.rgb * vec3(1.0/12.92),
                             pow((color.rgb + vec3(0.055))/vec3(1.055), vec3(2.4)),
                             lessThan(vec3(0.04045), color.rgb));)
        break;
    case MP_CSP_TRC_BT_1886:
        GLSL(color.rgb = pow(color.rgb, vec3(2.4));)
        break;
    case MP_CSP_TRC_GAMMA18:
        GLSL(color.rgb = pow(color.rgb, vec3(1.8));)
        break;
    case MP_CSP_TRC_GAMMA22:
        GLSL(color.rgb = pow(color.rgb, vec3(2.2));)
        break;
    case MP_CSP_TRC_GAMMA28:
        GLSL(color.rgb = pow(color.rgb, vec3(2.8));)
        break;
    case MP_CSP_TRC_PRO_PHOTO:
        GLSL(color.rgb = mix(color.rgb * vec3(1.0/16.0),
                             pow(color.rgb, vec3(1.8)),
                             lessThan(vec3(0.03125), color.rgb));)
        break;
    case MP_CSP_TRC_PQ:
        GLSLF("color.rgb = pow(color.rgb, vec3(1.0/%f));\n", PQ_M2);
        GLSLF("color.rgb = max(color.rgb - vec3(%f), vec3(0.0)) \n"
              "             / (vec3(%f) - vec3(%f) * color.rgb);\n",
              PQ_C1, PQ_C2, PQ_C3);
        GLSLF("color.rgb = pow(color.rgb, vec3(1.0/%f));\n", PQ_M1);
        // PQ's output range is 0-10000, but we need it to be relative to to
        // MP_REF_WHITE instead, so rescale
        GLSLF("color.rgb *= vec3(%f);\n", 10000 / MP_REF_WHITE);
        break;
    case MP_CSP_TRC_HLG:
        GLSLF("color.rgb = mix(vec3(4.0) * color.rgb * color.rgb,\n"
              "                exp((color.rgb - vec3(%f)) * vec3(1.0/%f)) + vec3(%f),\n"
              "                lessThan(vec3(0.5), color.rgb));\n",
              HLG_C, HLG_A, HLG_B);
        break;
    case MP_CSP_TRC_V_LOG:
        GLSLF("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);
        break;
    case MP_CSP_TRC_S_LOG1:
        GLSLF("color.rgb = pow(vec3(10.0), (color.rgb - vec3(%f)) * vec3(1.0/%f))\n"
              "            - vec3(%f);\n",
              SLOG_C, SLOG_A, SLOG_B);
        break;
    case MP_CSP_TRC_S_LOG2:
        GLSLF("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);
        break;
    default:
        abort();
    }

    // Rescale to prevent clipping on non-float textures
    GLSLF("color.rgb *= vec3(1.0/%f);\n", mp_trc_nom_peak(trc));
}

// Delinearize (compress), given a TRC as output. This corresponds to the
// inverse EOTF (not the OETF) in ITU-R terminology, again assuming a
// reference monitor.
//
// Like pass_linearize, this functions ingests values on an normalized scale
void pass_delinearize(struct gl_shader_cache *sc, enum mp_csp_trc trc)
{
    if (trc == MP_CSP_TRC_LINEAR)
        return;

    GLSLF("// delinearize\n");
    GLSL(color.rgb = clamp(color.rgb, 0.0, 1.0);)
    GLSLF("color.rgb *= vec3(%f);\n", mp_trc_nom_peak(trc));

    switch (trc) {
    case MP_CSP_TRC_SRGB:
        GLSL(color.rgb = mix(color.rgb * vec3(12.92),
                             vec3(1.055) * pow(color.rgb, vec3(1.0/2.4))
                                 - vec3(0.055),
                             lessThanEqual(vec3(0.0031308), color.rgb));)
        break;
    case MP_CSP_TRC_BT_1886:
        GLSL(color.rgb = pow(color.rgb, vec3(1.0/2.4));)
        break;
    case MP_CSP_TRC_GAMMA18:
        GLSL(color.rgb = pow(color.rgb, vec3(1.0/1.8));)
        break;
    case MP_CSP_TRC_GAMMA22:
        GLSL(color.rgb = pow(color.rgb, vec3(1.0/2.2));)
        break;
    case MP_CSP_TRC_GAMMA28:
        GLSL(color.rgb = pow(color.rgb, vec3(1.0/2.8));)
        break;
    case MP_CSP_TRC_PRO_PHOTO:
        GLSL(color.rgb = mix(color.rgb * vec3(16.0),
                             pow(color.rgb, vec3(1.0/1.8)),
                             lessThanEqual(vec3(0.001953), color.rgb));)
        break;
    case MP_CSP_TRC_PQ:
        GLSLF("color.rgb *= vec3(1.0/%f);\n", 10000 / MP_REF_WHITE);
        GLSLF("color.rgb = pow(color.rgb, vec3(%f));\n", PQ_M1);
        GLSLF("color.rgb = (vec3(%f) + vec3(%f) * color.rgb) \n"
              "             / (vec3(1.0) + vec3(%f) * color.rgb);\n",
              PQ_C1, PQ_C2, PQ_C3);
        GLSLF("color.rgb = pow(color.rgb, vec3(%f));\n", PQ_M2);
        break;
    case MP_CSP_TRC_HLG:
        GLSLF("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_A, HLG_B, HLG_C);
        break;
    case MP_CSP_TRC_V_LOG:
        GLSLF("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);
        break;
    case MP_CSP_TRC_S_LOG1:
        GLSLF("color.rgb = vec3(%f) * log(color.rgb + vec3(%f)) + vec3(%f);\n",
              SLOG_A / M_LN10, SLOG_B, SLOG_C);
        break;
    case MP_CSP_TRC_S_LOG2:
        GLSLF("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);
        break;
    default:
        abort();
    }
}

// Apply the OOTF mapping from a given light type to display-referred light.
// Assumes absolute scale values. `peak` is used to tune the OOTF where
// applicable (currently only HLG).
static void pass_ootf(struct gl_shader_cache *sc, enum mp_csp_light light,
                      float peak)
{
    if (light == MP_CSP_LIGHT_DISPLAY)
        return;

    GLSLF("// apply ootf\n");

    switch (light)
    {
    case MP_CSP_LIGHT_SCENE_HLG: {
        // HLG OOTF from BT.2100, scaled to the chosen display peak
        float gamma = MPMAX(1.0, 1.2 + 0.42 * log10(peak * MP_REF_WHITE / 1000.0));
        GLSLF("color.rgb *= vec3(%f * pow(dot(src_luma, color.rgb), %f));\n",
              peak / pow(12, gamma), gamma - 1.0);
        break;
    }
    case MP_CSP_LIGHT_SCENE_709_1886:
        // This OOTF is defined by encoding the result as 709 and then decoding
        // it as 1886; although this is called 709_1886 we actually use the
        // more precise (by one decimal) values from BT.2020 instead
        GLSL(color.rgb = mix(color.rgb * vec3(4.5),
                             vec3(1.0993) * pow(color.rgb, vec3(0.45)) - vec3(0.0993),
                             lessThan(vec3(0.0181), color.rgb));)
        GLSL(color.rgb = pow(color.rgb, vec3(2.4));)
        break;
    case MP_CSP_LIGHT_SCENE_1_2:
        GLSL(color.rgb = pow(color.rgb, vec3(1.2));)
        break;
    default:
        abort();
    }
}

// Inverse of the function pass_ootf, for completeness' sake.
static void pass_inverse_ootf(struct gl_shader_cache *sc, enum mp_csp_light light,
                              float peak)
{
    if (light == MP_CSP_LIGHT_DISPLAY)
        return;

    GLSLF("// apply inverse ootf\n");

    switch (light)
    {
    case MP_CSP_LIGHT_SCENE_HLG: {
        float gamma = MPMAX(1.0, 1.2 + 0.42 * log10(peak * MP_REF_WHITE / 1000.0));
        GLSLF("color.rgb *= vec3(1.0/%f);\n", peak / pow(12, gamma));
        GLSLF("color.rgb /= vec3(max(1e-6, pow(dot(src_luma, color.rgb), %f)));\n",
              (gamma - 1.0) / gamma);
        break;
    }
    case MP_CSP_LIGHT_SCENE_709_1886:
        GLSL(color.rgb = pow(color.rgb, vec3(1.0/2.4));)
        GLSL(color.rgb = mix(color.rgb * vec3(1.0/4.5),
                             pow((color.rgb + vec3(0.0993)) * vec3(1.0/1.0993),
                                 vec3(1/0.45)),
                             lessThan(vec3(0.08145), color.rgb));)
        break;
    case MP_CSP_LIGHT_SCENE_1_2:
        GLSL(color.rgb = pow(color.rgb, vec3(1.0/1.2));)
        break;
    default:
        abort();
    }
}

// Average light level for SDR signals. This is equal to a signal level of 0.5
// under a typical presentation gamma of about 2.0.
static const float sdr_avg = 0.25;

// The threshold for which to consider an average luminance difference to be
// a sign of a scene change.
static const int scene_threshold = 0.2 * MP_REF_WHITE;

static void hdr_update_peak(struct gl_shader_cache *sc)
{
    // For performance, we want to do as few atomic operations on global
    // memory as possible, so use an atomic in shmem for the work group.
    GLSLH(shared uint wg_sum;);
    GLSL(wg_sum = 0;)

    // Have each thread update the work group sum with the local value
    GLSL(barrier();)
    GLSLF("atomicAdd(wg_sum, uint(sig * %f));\n", MP_REF_WHITE);

    // Have one thread per work group update the global atomics. We use the
    // work group average even for the global sum, to make the values slightly
    // more stable and smooth out tiny super-highlights.
    GLSL(memoryBarrierShared();)
    GLSL(barrier();)
    GLSL(if (gl_LocalInvocationIndex == 0) {)
    GLSL(    uint wg_avg = wg_sum / (gl_WorkGroupSize.x * gl_WorkGroupSize.y);)
    GLSL(    atomicMax(frame_max[frame_idx], wg_avg);)
    GLSL(    atomicAdd(frame_avg[frame_idx], wg_avg);)
    GLSL(})

    const float refi = 1.0 / MP_REF_WHITE;

    // Update the sig_peak/sig_avg from the old SSBO state
    GLSL(uint num_wg = gl_NumWorkGroups.x * gl_NumWorkGroups.y;)
    GLSL(if (frame_num > 0) {)
    GLSLF("    float peak = %f * float(total_max) / float(frame_num);\n", refi);
    GLSLF("    float avg = %f * float(total_avg) / float(frame_num);\n", refi);
    GLSLF("    sig_peak = max(1.0, peak);\n");
    GLSLF("    sig_avg  = max(%f, avg);\n", sdr_avg);
    GLSL(});

    // Finally, to update the global state, we increment a counter per dispatch
    GLSL(memoryBarrierBuffer();)
    GLSL(barrier();)
    GLSL(if (gl_LocalInvocationIndex == 0 && atomicAdd(counter, 1) == num_wg - 1) {)

    // Since we sum up all the workgroups, we also still need to divide the
    // average by the number of work groups
    GLSL(    counter = 0;)
    GLSL(    frame_avg[frame_idx] /= num_wg;)
    GLSL(    uint cur_max = frame_max[frame_idx];)
    GLSL(    uint cur_avg = frame_avg[frame_idx];)

    // Scene change detection
    GLSL(    int diff = int(frame_num * cur_avg) - int(total_avg);)
    GLSLF("  if (abs(diff) > frame_num * %d) {\n", scene_threshold);
    GLSL(        frame_num = 0;)
    GLSL(        total_max = total_avg = 0;)
    GLSLF("      for (uint i = 0; i < %d; i++)\n", PEAK_DETECT_FRAMES+1);
    GLSL(            frame_max[i] = frame_avg[i] = 0;)
    GLSL(        frame_max[frame_idx] = cur_max;)
    GLSL(        frame_avg[frame_idx] = cur_avg;)
    GLSL(    })

    // Add the current frame, then subtract and reset the next frame
    GLSLF("  uint next = (frame_idx + 1) %% %d;\n", PEAK_DETECT_FRAMES+1);
    GLSL(    total_max += cur_max - frame_max[next];)
    GLSL(    total_avg += cur_avg - frame_avg[next];)
    GLSL(    frame_max[next] = frame_avg[next] = 0;)

    // Update the index and count
    GLSL(    frame_idx = next;)
    GLSLF("  frame_num = min(frame_num + 1, %d);\n", PEAK_DETECT_FRAMES);
    GLSL(    memoryBarrierBuffer();)
    GLSL(})
}

// Tone map from a known peak brightness to the range [0,1]. If ref_peak
// is 0, we will use peak detection instead
static void pass_tone_map(struct gl_shader_cache *sc, bool detect_peak,
                          float src_peak, float dst_peak,
                          enum tone_mapping algo, float param, float desat)
{
    GLSLF("// HDR tone mapping\n");

    // To prevent discoloration due to out-of-bounds clipping, we need to make
    // sure to reduce the value range as far as necessary to keep the entire
    // signal in range, so tone map based on the brightest component.
    GLSL(float sig = max(max(color.r, color.g), color.b);)
    GLSLF("float sig_peak = %f;\n", src_peak);
    GLSLF("float sig_avg = %f;\n", sdr_avg);

    // Desaturate the color using a coefficient dependent on the signal
    // Do this before peak detection in order to try and reclaim as much
    // dynamic range as possible.
    if (desat > 0) {
        float base = 0.18 * dst_peak;
        GLSL(float luma = dot(dst_luma, color.rgb);)
        GLSLF("float coeff = max(sig - %f, 1e-6) / max(sig, 1e-6);\n", base);
        GLSLF("coeff = pow(coeff, %f);\n", 10.0 / desat);
        GLSL(color.rgb = mix(color.rgb, vec3(luma), coeff);)
        GLSL(sig = mix(sig, luma, coeff);) // also make sure to update `sig`
    }

    if (detect_peak)
        hdr_update_peak(sc);

    // Rescale the variables in order to bring it into a representation where
    // 1.0 represents the dst_peak. This is because all of the tone mapping
    // algorithms are defined in such a way that they map to the range [0.0, 1.0].
    if (dst_peak > 1.0) {
        GLSLF("sig *= %f;\n", 1.0 / dst_peak);
        GLSLF("sig_peak *= %f;\n", 1.0 / dst_peak);
    }

    GLSL(float sig_orig = sig;)
    GLSLF("float slope = min(1.0, %f / sig_avg);\n", sdr_avg);
    GLSL(sig *= slope;)
    GLSL(sig_peak *= slope;)

    switch (algo) {
    case TONE_MAPPING_CLIP:
        GLSLF("sig = %f * sig;\n", isnan(param) ? 1.0 : param);
        break;

    case TONE_MAPPING_MOBIUS:
        GLSLF("if (sig_peak > (1.0 + 1e-6)) {\n");
        GLSLF("const float j = %f;\n", isnan(param) ? 0.3 : param);
        // solve for M(j) = j; M(sig_peak) = 1.0; M'(j) = 1.0
        // where M(x) = scale * (x+a)/(x+b)
        GLSLF("float a = -j*j * (sig_peak - 1.0) / (j*j - 2.0*j + sig_peak);\n");
        GLSLF("float b = (j*j - 2.0*j*sig_peak + sig_peak) / "
              "max(1e-6, sig_peak - 1.0);\n");
        GLSLF("float scale = (b*b + 2.0*b*j + j*j) / (b-a);\n");
        GLSL(sig = sig > j ? scale * (sig + a) / (sig + b) : si