Coverage Report

Created: 2026-11-30 06:48

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/mpv/video/out/gpu/video.c
Line
Count
Source
1
/*
2
 * This file is part of mpv.
3
 *
4
 * mpv is free software; you can redistribute it and/or
5
 * modify it under the terms of the GNU Lesser General Public
6
 * License as published by the Free Software Foundation; either
7
 * version 2.1 of the License, or (at your option) any later version.
8
 *
9
 * mpv is distributed in the hope that it will be useful,
10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
 * GNU Lesser General Public License for more details.
13
 *
14
 * You should have received a copy of the GNU Lesser General Public
15
 * License along with mpv.  If not, see <http://www.gnu.org/licenses/>.
16
 */
17
18
#include <assert.h>
19
#include <float.h>
20
#include <inttypes.h>
21
#include <math.h>
22
#include <stdarg.h>
23
#include <stdbool.h>
24
#include <string.h>
25
26
#include <libavutil/common.h>
27
#include <libavutil/lfg.h>
28
29
#include "video.h"
30
31
#include "misc/bstr.h"
32
#include "options/m_config.h"
33
#include "options/path.h"
34
#include "options/options.h"
35
#include "utils.h"
36
#include "hwdec.h"
37
#include "osd.h"
38
#include "ra.h"
39
#include "stream/stream.h"
40
#include "video_shaders.h"
41
#include "user_shaders.h"
42
#include "error_diffusion.h"
43
#include "video/out/filter_kernels.h"
44
#include "video/out/aspect.h"
45
#include "video/out/dither.h"
46
#include "video/out/vo.h"
47
48
// must be sorted, and terminated with 0
49
int filter_sizes[] =
50
    {2, 4, 6, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64, 0};
51
int tscale_sizes[] = {2, 4, 6, 8, 0};
52
53
struct vertex_pt {
54
    float x, y;
55
};
56
57
struct texplane {
58
    struct ra_tex *tex;
59
    int w, h;
60
    bool flipped;
61
};
62
63
struct video_image {
64
    struct texplane planes[4];
65
    struct mp_image *mpi;       // original input image
66
    uint64_t id;                // unique ID identifying mpi contents
67
    bool hwdec_mapped;
68
};
69
70
enum plane_type {
71
    PLANE_NONE = 0,
72
    PLANE_RGB,
73
    PLANE_LUMA,
74
    PLANE_CHROMA,
75
    PLANE_ALPHA,
76
    PLANE_XYZ,
77
};
78
79
static const char *plane_names[] = {
80
    [PLANE_NONE] = "unknown",
81
    [PLANE_RGB] = "rgb",
82
    [PLANE_LUMA] = "luma",
83
    [PLANE_CHROMA] = "chroma",
84
    [PLANE_ALPHA] = "alpha",
85
    [PLANE_XYZ] = "xyz",
86
};
87
88
// A self-contained description of a source image which can be bound to a
89
// texture unit and sampled from. Contains metadata about how it's to be used
90
struct image {
91
    enum plane_type type; // must be set to something non-zero
92
    int components; // number of relevant coordinates
93
    float multiplier; // multiplier to be used when sampling
94
    struct ra_tex *tex;
95
    int w, h; // logical size (after transformation)
96
    struct gl_transform transform; // rendering transformation
97
    int padding; // number of leading padding components (e.g. 2 = rg is padding)
98
};
99
100
// A named image, for user scripting purposes
101
struct saved_img {
102
    const char *name;
103
    struct image img;
104
};
105
106
// A texture hook. This is some operation that transforms a named texture as
107
// soon as it's generated
108
struct tex_hook {
109
    const char *save_tex;
110
    const char *hook_tex[SHADER_MAX_HOOKS];
111
    const char *bind_tex[SHADER_MAX_BINDS];
112
    int components; // how many components are relevant (0 = same as input)
113
    bool align_offset; // whether to align hooked tex with reference.
114
    void *priv; // this gets talloc_freed when the tex_hook is removed
115
    void (*hook)(struct gl_video *p, struct image img, // generates GLSL
116
                 struct gl_transform *trans, void *priv);
117
    bool (*cond)(struct gl_video *p, struct image img, void *priv);
118
};
119
120
struct surface {
121
    struct ra_tex *tex;
122
    uint64_t id;
123
    double pts;
124
};
125
126
0
#define SURFACES_MAX 10
127
128
struct cached_file {
129
    char *path;
130
    struct bstr body;
131
};
132
133
struct pass_info {
134
    struct bstr desc;
135
    struct mp_pass_perf perf;
136
};
137
138
struct dr_buffer {
139
    struct ra_buf *buf;
140
    // The mpi reference will keep the data from being recycled (or from other
141
    // references gaining write access) while the GPU is accessing the buffer.
142
    struct mp_image *mpi;
143
};
144
145
struct gl_video {
146
    struct ra *ra;
147
148
    struct mpv_global *global;
149
    struct mp_log *log;
150
    struct gl_video_opts opts;
151
    struct m_config_cache *opts_cache;
152
    struct gl_lcms *cms;
153
154
    int fb_depth;               // actual bits available in GL main framebuffer
155
    struct m_color clear_color;
156
    bool force_clear_color;
157
158
    struct gl_shader_cache *sc;
159
160
    struct osd_state *osd_state;
161
    struct mpgl_osd *osd;
162
    double osd_pts;
163
164
    struct ra_tex *lut_3d_texture;
165
    bool use_lut_3d;
166
    int lut_3d_size[3];
167
168
    struct ra_tex *dither_texture;
169
170
    struct mp_image_params real_image_params;   // configured format
171
    struct mp_image_params image_params;        // texture format (mind hwdec case)
172
    struct mp_image_params target_params;       // target format
173
    struct ra_imgfmt_desc ra_format;            // texture format
174
    int plane_count;
175
176
    bool is_gray;
177
    bool has_alpha;
178
    char color_swizzle[5];
179
    bool use_integer_conversion;
180
181
    struct video_image image;
182
183
    struct dr_buffer *dr_buffers;
184
    int num_dr_buffers;
185
186
    bool using_dr_path;
187
188
    bool dumb_mode;
189
    bool forced_dumb_mode;
190
191
    // Cached vertex array, to avoid re-allocation per frame. For simplicity,
192
    // our vertex format is simply a list of `vertex_pt`s, since this greatly
193
    // simplifies offset calculation at the cost of (unneeded) flexibility.
194
    struct vertex_pt *tmp_vertex;
195
    struct ra_renderpass_input *vao;
196
    int vao_len;
197
198
    const struct ra_format *fbo_format;
199
    struct ra_tex *merge_tex[4];
200
    struct ra_tex *scale_tex[4];
201
    struct ra_tex *integer_tex[4];
202
    struct ra_tex *chroma_tex[4];
203
    struct ra_tex *indirect_tex;
204
    struct ra_tex *blend_subs_tex;
205
    struct ra_tex *error_diffusion_tex[2];
206
    struct ra_tex *screen_tex;
207
    struct ra_tex *output_tex;
208
    struct ra_tex **hook_textures;
209
    int num_hook_textures;
210
    int idx_hook_textures;
211
212
    struct ra_buf *hdr_peak_ssbo;
213
    struct surface surfaces[SURFACES_MAX];
214
215
    // user pass descriptions and textures
216
    struct tex_hook *tex_hooks;
217
    int num_tex_hooks;
218
    struct gl_user_shader_tex *user_textures;
219
    int num_user_textures;
220
221
    int surface_idx;
222
    int surface_now;
223
    int frames_drawn;
224
    bool is_interpolated;
225
    bool output_tex_valid;
226
227
    // state for configured scalers
228
    struct scaler scaler[SCALER_COUNT];
229
230
    struct mp_csp_equalizer_state *video_eq;
231
232
    struct mp_rect src_rect;    // displayed part of the source video
233
    struct mp_rect dst_rect;    // video rectangle on output window
234
    struct mp_osd_res osd_rect; // OSD size/margins
235
236
    // temporary during rendering
237
    struct compute_info pass_compute; // compute shader metadata for this pass
238
    struct image *pass_imgs;          // bound images for this pass
239
    int num_pass_imgs;
240
    struct saved_img *saved_imgs;     // saved (named) images for this frame
241
    int num_saved_imgs;
242
243
    // effective current texture metadata - this will essentially affect the
244
    // next render pass target, as well as implicitly tracking what needs to
245
    // be done with the image
246
    int texture_w, texture_h;
247
    struct gl_transform texture_offset; // texture transform without rotation
248
    int components;
249
    bool use_linear;
250
    float user_gamma;
251
252
    // pass info / metrics
253
    struct pass_info pass_fresh[VO_PASS_PERF_MAX];
254
    struct pass_info pass_redraw[VO_PASS_PERF_MAX];
255
    struct pass_info *pass;
256
    int pass_idx;
257
    struct timer_pool *upload_timer;
258
    struct timer_pool *blit_timer;
259
    struct timer_pool *osd_timer;
260
261
    int frames_uploaded;
262
    int frames_rendered;
263
    AVLFG lfg;
264
265
    // Cached because computing it can take relatively long
266
    int last_dither_matrix_size;
267
    float *last_dither_matrix;
268
269
    struct cached_file *files;
270
    int num_files;
271
272
    struct ra_hwdec_ctx hwdec_ctx;
273
    struct ra_hwdec_mapper *hwdec_mapper;
274
    struct ra_hwdec *hwdec_overlay;
275
    bool hwdec_active;
276
277
    bool dsi_warned;
278
    bool broken_frame; // temporary error state
279
280
    bool colorspace_override_warned;
281
    bool correct_downscaling_warned;
282
};
283
284
#define FIXED_SCALE_KERNELS \
285
    {"bilinear",             SCALER_BILINEAR}, \
286
    {"bicubic_fast",         SCALER_BICUBIC_FAST}, \
287
    {"oversample",           SCALER_OVERSAMPLE}, \
288
289
#define NON_POLAR_FILTER_KERNELS \
290
    {"spline16",      SCALER_SPLINE16}, \
291
    {"spline36",      SCALER_SPLINE36}, \
292
    {"spline64",      SCALER_SPLINE64}, \
293
    {"sinc",          SCALER_SINC}, \
294
    {"lanczos",       SCALER_LANCZOS}, \
295
    {"ginseng",       SCALER_GINSENG}, \
296
    {"bicubic",       SCALER_BICUBIC}, \
297
    {"hermite",       SCALER_HERMITE}, \
298
    {"catmull_rom",   SCALER_CATMULL_ROM}, \
299
    {"mitchell",      SCALER_MITCHELL}, \
300
    {"robidoux",      SCALER_ROBIDOUX}, \
301
    {"robidouxsharp", SCALER_ROBIDOUXSHARP}, \
302
    {"box",           SCALER_BOX}, \
303
    {"nearest",       SCALER_NEAREST}, \
304
    {"triangle",      SCALER_TRIANGLE}, \
305
    {"gaussian",      SCALER_GAUSSIAN}, \
306
307
#define POLAR_FILTER_KERNELS \
308
    {"jinc",                 SCALER_JINC}, \
309
    {"ewa_lanczos",          SCALER_EWA_LANCZOS}, \
310
    {"ewa_hanning",          SCALER_EWA_HANNING}, \
311
    {"ewa_ginseng",          SCALER_EWA_GINSENG}, \
312
    {"ewa_lanczossharp",     SCALER_EWA_LANCZOSSHARP}, \
313
    {"ewa_lanczos4sharpest", SCALER_EWA_LANCZOS4SHARPEST}, \
314
    {"ewa_lanczossoft",      SCALER_EWA_LANCZOSSOFT}, \
315
    {"haasnsoft",            SCALER_HAASNSOFT}, \
316
    {"ewa_robidoux",         SCALER_EWA_ROBIDOUX}, \
317
    {"ewa_robidouxsharp",    SCALER_EWA_ROBIDOUXSHARP}, \
318
319
#define FILTER_WINDOWS \
320
    {"bartlett", WINDOW_BARTLETT}, \
321
    {"cosine",   WINDOW_COSINE}, \
322
    {"hanning",  WINDOW_HANNING}, \
323
    {"tukey",    WINDOW_TUKEY}, \
324
    {"hamming",  WINDOW_HAMMING}, \
325
    {"quadric",  WINDOW_QUADRIC}, \
326
    {"welch",    WINDOW_WELCH}, \
327
    {"kaiser",   WINDOW_KAISER}, \
328
    {"blackman", WINDOW_BLACKMAN}, \
329
    {"sphinx",   WINDOW_SPHINX}, \
330
331
static const struct m_opt_choice_alternatives scale_filters[] = {
332
    FIXED_SCALE_KERNELS
333
    NON_POLAR_FILTER_KERNELS
334
    POLAR_FILTER_KERNELS
335
    FILTER_WINDOWS
336
    {0},
337
};
338
339
static const struct m_opt_choice_alternatives cdscale_filters[] = {
340
    {"", SCALER_INHERIT},
341
    FIXED_SCALE_KERNELS
342
    NON_POLAR_FILTER_KERNELS
343
    POLAR_FILTER_KERNELS
344
    FILTER_WINDOWS
345
    {0},
346
};
347
348
static const struct m_opt_choice_alternatives tscale_filters[] = {
349
    {"oversample", SCALER_OVERSAMPLE},
350
    {"linear",     SCALER_LINEAR},
351
    NON_POLAR_FILTER_KERNELS
352
    FILTER_WINDOWS
353
    {"jinc",       WINDOW_JINC},
354
    {0},
355
};
356
357
static const struct m_opt_choice_alternatives filter_windows[] = {
358
    {"",     WINDOW_PREFERRED},
359
    FILTER_WINDOWS
360
    {"jinc", WINDOW_JINC},
361
    {0},
362
};
363
364
static const struct gl_video_opts gl_video_opts_def = {
365
    .dither_algo = DITHER_FRUIT,
366
    .dither_size = 6,
367
    .temporal_dither_period = 1,
368
    .error_diffusion = "sierra-lite",
369
    .fbo_format = "auto",
370
    .sigmoid_center = 0.75,
371
    .sigmoid_slope = 6.5,
372
    .scaler = {
373
        [SCALER_SCALE] =  {
374
            {SCALER_LANCZOS, .params = {NAN, NAN}, .functions = scale_filters},
375
            {WINDOW_PREFERRED, .params = {NAN, NAN}, .functions = filter_windows},
376
        },
377
        [SCALER_DSCALE] = {
378
            {SCALER_HERMITE, .params = {NAN, NAN}, .functions = cdscale_filters},
379
            {WINDOW_PREFERRED, .params = {NAN, NAN}, .functions = filter_windows},
380
        },
381
        [SCALER_CSCALE] = {
382
            {SCALER_INHERIT, .params = {NAN, NAN}, .functions = cdscale_filters},
383
            {WINDOW_PREFERRED, .params = {NAN, NAN}, .functions = filter_windows},
384
        },
385
        [SCALER_TSCALE] = {
386
            {SCALER_OVERSAMPLE, .params = {NAN, NAN}, .functions = tscale_filters},
387
            {WINDOW_PREFERRED, .params = {NAN, NAN}, .functions = filter_windows},
388
        },
389
    },
390
    .scaler_resizes_only = true,
391
    .correct_downscaling = true,
392
    .linear_downscaling = true,
393
    .sigmoid_upscaling = true,
394
    .interpolation_threshold = 0.01,
395
    .background = BACKGROUND_TILES,
396
    .background_color = {0, 0, 0, 255},
397
    .background_tile_color = {{237, 237, 237, 255},
398
                              {222, 222, 222, 255}},
399
    .background_tile_size = 16,
400
    .gamma = 1.0f,
401
    .tone_map = {
402
        .curve = TONE_MAPPING_AUTO,
403
        .curve_param = NAN,
404
        .max_boost = 1.0,
405
        .decay_rate = 20.0,
406
        .scene_threshold_low = 1.0,
407
        .scene_threshold_high = 3.0,
408
        .contrast_smoothness = 3.5,
409
        .mastering_clip = 1.0,
410
        .film_strength = 0.3,
411
    },
412
    .early_flush = -1,
413
    .shader_cache = true,
414
    .hwdec_interop = "auto",
415
    .treat_srgb_as_power22 = 1|2|4, // auto
416
};
417
418
static OPT_STRING_VALIDATE_FUNC(validate_error_diffusion_opt);
419
static OPT_STRING_VALIDATE_FUNC(validate_target_gamut);
420
421
#define OPT_BASE_STRUCT struct gl_video_opts
422
423
// Use for options which use NAN for defaults.
424
#define OPT_FLOATDEF(field) \
425
    OPT_FLOAT(field), \
426
    .flags = M_OPT_DEFAULT_NAN
427
428
#define SCALER_OPTS(n, i) \
429
    {n"-param1", OPT_FLOATDEF(scaler[i].kernel.params[0])},                \
430
    {n"-param2", OPT_FLOATDEF(scaler[i].kernel.params[1])},                \
431
    {n"-blur",   OPT_FLOAT(scaler[i].kernel.blur)},                        \
432
    {n"-taper",  OPT_FLOAT(scaler[i].kernel.taper), M_RANGE(0.0, 1.0)},    \
433
    {n"-wparam", OPT_FLOATDEF(scaler[i].window.params[0])},                \
434
    {n"-wtaper", OPT_FLOAT(scaler[i].window.taper), M_RANGE(0.0, 1.0)},    \
435
    {n"-clamp",  OPT_FLOAT(scaler[i].clamp), M_RANGE(0.0, 1.0)},           \
436
    {n"-radius", OPT_FLOAT(scaler[i].radius), M_RANGE(0.5, 16.0)},         \
437
    {n"-antiring", OPT_FLOAT(scaler[i].antiring), M_RANGE(0.0, 1.0)},      \
438
    {n"-window", OPT_CHOICE_C(scaler[i].window.function, filter_windows)}
439
440
const struct m_sub_options gl_video_conf = {
441
    .opts = (const m_option_t[]) {
442
        {"gpu-dumb-mode", OPT_CHOICE(dumb_mode,
443
            {"auto", 0}, {"yes", 1}, {"no", -1})},
444
        {"gamma-factor", OPT_FLOAT(gamma), M_RANGE(0.1, 2.0)},
445
        {"gamma-auto", OPT_BOOL(gamma_auto),
446
            .deprecation_message = "replacement: gamma-auto.lua"},
447
        {"target-prim", OPT_CHOICE_C(target_prim, pl_csp_prim_names)},
448
        {"target-trc", OPT_CHOICE_C(target_trc, pl_csp_trc_names)},
449
        {"target-peak", OPT_CHOICE(target_peak, {"auto", 0}),
450
            M_RANGE(10, 10000)},
451
        {"hdr-reference-white", OPT_CHOICE(hdr_reference_white, {"auto", 0}),
452
            M_RANGE(10, 10000)},
453
        {"sdr-adjust-gamma", OPT_CHOICE(sdr_adjust_gamma,
454
            {"auto", 0}, {"yes", 1}, {"no", -1})},
455
        {"treat-srgb-as-power22", OPT_CHOICE(treat_srgb_as_power22,
456
            {"no", 0}, {"input", 1}, {"output", 2}, {"both", 1|2}, {"auto", 1|2|4})},
457
        {"target-contrast", OPT_CHOICE(target_contrast, {"auto", 0}, {"inf", -1}),
458
            M_RANGE(10, 10 / PL_COLOR_HDR_BLACK)},
459
        {"target-gamut", OPT_STRING_VALIDATE(target_gamut, validate_target_gamut)},
460
        {"tone-mapping", OPT_CHOICE(tone_map.curve,
461
            {"auto",     TONE_MAPPING_AUTO},
462
            {"clip",     TONE_MAPPING_CLIP},
463
            {"mobius",   TONE_MAPPING_MOBIUS},
464
            {"reinhard", TONE_MAPPING_REINHARD},
465
            {"hable",    TONE_MAPPING_HABLE},
466
            {"gamma",    TONE_MAPPING_GAMMA},
467
            {"linear",   TONE_MAPPING_LINEAR},
468
            {"spline",   TONE_MAPPING_SPLINE},
469
            {"bt.2390",  TONE_MAPPING_BT_2390},
470
            {"bt.2446a", TONE_MAPPING_BT_2446A},
471
            {"st2094-40", TONE_MAPPING_ST2094_40},
472
            {"st2094-10", TONE_MAPPING_ST2094_10})},
473
        {"tone-mapping-param", OPT_FLOATDEF(tone_map.curve_param)},
474
        {"inverse-tone-mapping", OPT_BOOL(tone_map.inverse)},
475
        {"tone-mapping-max-boost", OPT_FLOAT(tone_map.max_boost),
476
            M_RANGE(1.0, 10.0)},
477
        {"tone-mapping-visualize", OPT_BOOL(tone_map.visualize)},
478
        {"gamut-mapping-mode", OPT_CHOICE(tone_map.gamut_mode,
479
            {"auto",        GAMUT_AUTO},
480
            {"clip",        GAMUT_CLIP},
481
            {"perceptual",  GAMUT_PERCEPTUAL},
482
            {"relative",    GAMUT_RELATIVE},
483
            {"saturation",  GAMUT_SATURATION},
484
            {"absolute",    GAMUT_ABSOLUTE},
485
            {"desaturate",  GAMUT_DESATURATE},
486
            {"darken",      GAMUT_DARKEN},
487
            {"warn",        GAMUT_WARN},
488
            {"linear",      GAMUT_LINEAR})},
489
        {"hdr-compute-peak", OPT_CHOICE(tone_map.compute_peak,
490
            {"auto", 0},
491
            {"yes", 1},
492
            {"no", -1})},
493
        {"hdr-peak-percentile", OPT_FLOAT(tone_map.peak_percentile),
494
            M_RANGE(0.0, 100.0)},
495
        {"hdr-peak-decay-rate", OPT_FLOAT(tone_map.decay_rate),
496
            M_RANGE(0.0, 1000.0)},
497
        {"hdr-scene-threshold-low", OPT_FLOAT(tone_map.scene_threshold_low),
498
            M_RANGE(0, 20.0)},
499
        {"hdr-scene-threshold-high", OPT_FLOAT(tone_map.scene_threshold_high),
500
            M_RANGE(0, 20.0)},
501
        {"hdr-contrast-recovery", OPT_FLOAT(tone_map.contrast_recovery),
502
            M_RANGE(0, 2.0)},
503
        {"hdr-contrast-smoothness", OPT_FLOAT(tone_map.contrast_smoothness),
504
            M_RANGE(1.0, 100.0)},
505
        {"hdr-mastering-clip", OPT_FLOAT(tone_map.mastering_clip),
506
            M_RANGE(0.0, 1.0)},
507
        {"hdr-film-strength", OPT_FLOAT(tone_map.film_strength),
508
            M_RANGE(0.0, 2.0)},
509
        {"opengl-pbo", OPT_BOOL(pbo)},
510
        {"scale", OPT_CHOICE_C(scaler[SCALER_SCALE].kernel.function, scale_filters)},
511
        SCALER_OPTS("scale",  SCALER_SCALE),
512
        {"dscale", OPT_CHOICE_C(scaler[SCALER_DSCALE].kernel.function, cdscale_filters)},
513
        SCALER_OPTS("dscale", SCALER_DSCALE),
514
        {"cscale", OPT_CHOICE_C(scaler[SCALER_CSCALE].kernel.function, cdscale_filters)},
515
        SCALER_OPTS("cscale", SCALER_CSCALE),
516
        {"tscale", OPT_CHOICE_C(scaler[SCALER_TSCALE].kernel.function, tscale_filters)},
517
        SCALER_OPTS("tscale", SCALER_TSCALE),
518
        {"scaler-resizes-only", OPT_BOOL(scaler_resizes_only)},
519
        {"correct-downscaling", OPT_BOOL(correct_downscaling)},
520
        {"linear-downscaling", OPT_BOOL(linear_downscaling)},
521
        {"linear-upscaling", OPT_BOOL(linear_upscaling)},
522
        {"sigmoid-upscaling", OPT_BOOL(sigmoid_upscaling)},
523
        {"sigmoid-center", OPT_FLOAT(sigmoid_center), M_RANGE(0.0, 1.0)},
524
        {"sigmoid-slope", OPT_FLOAT(sigmoid_slope), M_RANGE(1.0, 20.0)},
525
        {"fbo-format", OPT_STRING(fbo_format)},
526
        {"dither-depth", OPT_CHOICE(dither_depth, {"no", -1}, {"auto", 0}),
527
            M_RANGE(-1, 16)},
528
        {"dither", OPT_CHOICE(dither_algo,
529
            {"fruit", DITHER_FRUIT},
530
            {"ordered", DITHER_ORDERED},
531
            {"error-diffusion", DITHER_ERROR_DIFFUSION},
532
            {"no", DITHER_NONE})},
533
        {"dither-size-fruit", OPT_INT(dither_size), M_RANGE(2, 8)},
534
        {"temporal-dither", OPT_BOOL(temporal_dither)},
535
        {"temporal-dither-period", OPT_INT(temporal_dither_period),
536
            M_RANGE(1, 128)},
537
        {"error-diffusion",
538
            OPT_STRING_VALIDATE(error_diffusion, validate_error_diffusion_opt)},
539
        {"background", OPT_CHOICE(background,
540
            {"none", BACKGROUND_NONE},
541
            {"color", BACKGROUND_COLOR},
542
            {"tiles", BACKGROUND_TILES})},
543
        {"opengl-rectangle-textures", OPT_BOOL(use_rectangle)},
544
        {"background-color", OPT_COLOR(background_color)},
545
        {"background-tile-color-0", OPT_COLOR(background_tile_color[0])},
546
        {"background-tile-color-1", OPT_COLOR(background_tile_color[1])},
547
        {"background-tile-size", OPT_INT(background_tile_size), M_RANGE(1, 4096)},
548
        {"interpolation", OPT_BOOL(interpolation)},
549
        {"interpolation-threshold", OPT_FLOAT(interpolation_threshold)},
550
        {"blend-subtitles", OPT_CHOICE(blend_subs,
551
            {"no", BLEND_SUBS_NO},
552
            {"yes", BLEND_SUBS_YES},
553
            {"video", BLEND_SUBS_VIDEO})},
554
        {"glsl-shaders", OPT_PATHLIST(user_shaders), .flags = M_OPT_FILE},
555
        {"glsl-shader", OPT_CLI_ALIAS("glsl-shaders-append")},
556
        {"glsl-shader-opts", OPT_KEYVALUELIST(user_shader_opts)},
557
        {"deband", OPT_BOOL(deband)},
558
        {"deband", OPT_SUBSTRUCT(deband_opts, deband_conf)},
559
        {"sharpen", OPT_FLOAT(unsharp)},
560
        {"gpu-tex-pad-x", OPT_INT(tex_pad_x), M_RANGE(0, 4096)},
561
        {"gpu-tex-pad-y", OPT_INT(tex_pad_y), M_RANGE(0, 4096)},
562
        {"", OPT_SUBSTRUCT(icc_opts, mp_icc_conf)},
563
        {"gpu-shader-cache", OPT_BOOL(shader_cache)},
564
        {"gpu-shader-cache-dir", OPT_STRING(shader_cache_dir), .flags = M_OPT_FILE},
565
        {"gpu-hwdec-interop",
566
            OPT_STRING_VALIDATE(hwdec_interop, ra_hwdec_validate_opt)},
567
        {"gamut-warning", OPT_REMOVED("Replaced by --gamut-mapping-mode=warn")},
568
        {"gamut-clipping", OPT_REMOVED("Replaced by --gamut-mapping-mode=desaturate")},
569
        {"tone-mapping-desaturate", OPT_REMOVED("Replaced by --tone-mapping-mode")},
570
        {"tone-mapping-desaturate-exponent", OPT_REMOVED("Replaced by --tone-mapping-mode")},
571
        {0}
572
    },
573
    .size = sizeof(struct gl_video_opts),
574
    .defaults = &gl_video_opts_def,
575
    .change_flags = UPDATE_VIDEO,
576
};
577
578
static void uninit_rendering(struct gl_video *p);
579
static void uninit_scaler(struct gl_video *p, struct scaler *scaler);
580
static void check_gl_features(struct gl_video *p);
581
static bool pass_upload_image(struct gl_video *p, struct mp_image *mpi, uint64_t id);
582
static void reinit_from_options(struct gl_video *p);
583
static void get_scale_factors(struct gl_video *p, bool transpose_rot, double xy[2]);
584
static void gl_video_setup_hooks(struct gl_video *p);
585
static void gl_video_update_options(struct gl_video *p);
586
587
0
#define GLSL(x) gl_sc_add(p->sc, #x "\n");
588
0
#define GLSLF(...) gl_sc_addf(p->sc, __VA_ARGS__)
589
0
#define GLSLHF(...) gl_sc_haddf(p->sc, __VA_ARGS__)
590
0
#define PRELUDE(...) gl_sc_paddf(p->sc, __VA_ARGS__)
591
592
static struct bstr load_cached_file(struct gl_video *p, const char *path)
593
0
{
594
0
    if (!path || !path[0])
595
0
        return (struct bstr){0};
596
0
    for (int n = 0; n < p->num_files; n++) {
597
0
        if (strcmp(p->files[n].path, path) == 0)
598
0
            return p->files[n].body;
599
0
    }
600
    // not found -> load it
601
0
    char *fname = mp_get_user_path(NULL, p->global, path);
602
0
    struct bstr s = stream_read_file(fname, p, p->global, 1000000000); // 1GB
603
0
    talloc_free(fname);
604
0
    if (s.len) {
605
0
        struct cached_file new = {
606
0
            .path = talloc_strdup(p, path),
607
0
            .body = s,
608
0
        };
609
0
        MP_TARRAY_APPEND(p, p->files, p->num_files, new);
610
0
        return new.body;
611
0
    }
612
0
    return (struct bstr){0};
613
0
}
614
615
static void debug_check_gl(struct gl_video *p, const char *msg)
616
0
{
617
0
    if (p->ra->fns->debug_marker)
618
0
        p->ra->fns->debug_marker(p->ra, msg);
619
0
}
620
621
static void gl_video_reset_surfaces(struct gl_video *p)
622
0
{
623
0
    for (int i = 0; i < SURFACES_MAX; i++) {
624
0
        p->surfaces[i].id = 0;
625
0
        p->surfaces[i].pts = MP_NOPTS_VALUE;
626
0
    }
627
0
    p->surface_idx = 0;
628
0
    p->surface_now = 0;
629
0
    p->frames_drawn = 0;
630
0
    p->output_tex_valid = false;
631
0
}
632
633
static void gl_video_reset_hooks(struct gl_video *p)
634
0
{
635
0
    for (int i = 0; i < p->num_tex_hooks; i++)
636
0
        talloc_free(p->tex_hooks[i].priv);
637
638
0
    for (int i = 0; i < p->num_user_textures; i++)
639
0
        ra_tex_free(p->ra, &p->user_textures[i].tex);
640
641
0
    p->num_tex_hooks = 0;
642
0
    p->num_user_textures = 0;
643
0
}
644
645
static inline int surface_wrap(int id)
646
0
{
647
0
    id = id % SURFACES_MAX;
648
0
    return id < 0 ? id + SURFACES_MAX : id;
649
0
}
650
651
static void reinit_osd(struct gl_video *p)
652
0
{
653
0
    mpgl_osd_destroy(p->osd);
654
0
    p->osd = NULL;
655
0
    if (p->osd_state)
656
0
        p->osd = mpgl_osd_init(p->ra, p->log, p->osd_state);
657
0
}
658
659
static void uninit_rendering(struct gl_video *p)
660
0
{
661
0
    for (int n = 0; n < SCALER_COUNT; n++)
662
0
        uninit_scaler(p, &p->scaler[n]);
663
664
0
    ra_tex_free(p->ra, &p->dither_texture);
665
666
0
    for (int n = 0; n < 4; n++) {
667
0
        ra_tex_free(p->ra, &p->merge_tex[n]);
668
0
        ra_tex_free(p->ra, &p->scale_tex[n]);
669
0
        ra_tex_free(p->ra, &p->integer_tex[n]);
670
0
        ra_tex_free(p->ra, &p->chroma_tex[n]);
671
0
    }
672
673
0
    ra_tex_free(p->ra, &p->indirect_tex);
674
0
    ra_tex_free(p->ra, &p->blend_subs_tex);
675
0
    ra_tex_free(p->ra, &p->screen_tex);
676
0
    ra_tex_free(p->ra, &p->output_tex);
677
678
0
    for (int n = 0; n < 2; n++)
679
0
        ra_tex_free(p->ra, &p->error_diffusion_tex[n]);
680
681
0
    for (int n = 0; n < SURFACES_MAX; n++)
682
0
        ra_tex_free(p->ra, &p->surfaces[n].tex);
683
684
0
    for (int n = 0; n < p->num_hook_textures; n++)
685
0
        ra_tex_free(p->ra, &p->hook_textures[n]);
686
687
0
    gl_video_reset_surfaces(p);
688
0
    gl_video_reset_hooks(p);
689
690
0
    gl_sc_reset_error(p->sc);
691
0
}
692
693
bool gl_video_gamma_auto_enabled(struct gl_video *p)
694
0
{
695
0
    return p->opts.gamma_auto;
696
0
}
697
698
// Warning: profile.start must point to a ta allocation, and the function
699
//          takes over ownership.
700
void gl_video_set_icc_profile(struct gl_video *p, bstr icc_data)
701
0
{
702
0
    if (gl_lcms_set_memory_profile(p->cms, icc_data))
703
0
        reinit_from_options(p);
704
0
}
705
706
bool gl_video_icc_auto_enabled(struct gl_video *p)
707
0
{
708
0
    return p->opts.icc_opts ? p->opts.icc_opts->profile_auto : false;
709
0
}
710
711
static bool gl_video_get_lut3d(struct gl_video *p, enum pl_color_primaries prim,
712
                               enum pl_color_transfer trc)
713
0
{
714
0
    if (!p->use_lut_3d)
715
0
        return false;
716
717
0
    struct AVBufferRef *icc = NULL;
718
0
    if (p->image.mpi)
719
0
        icc = p->image.mpi->icc_profile;
720
721
0
    if (p->lut_3d_texture && !gl_lcms_has_changed(p->cms, prim, trc, icc))
722
0
        return true;
723
724
    // GLES3 doesn't provide filtered 16 bit integer textures
725
    // GLES2 doesn't even provide 3D textures
726
0
    const struct ra_format *fmt = ra_find_unorm_format(p->ra, 2, 4);
727
0
    if (!fmt || !(p->ra->caps & RA_CAP_TEX_3D)) {
728
0
        p->use_lut_3d = false;
729
0
        MP_WARN(p, "Disabling color management (no RGBA16 3D textures).\n");
730
0
        return false;
731
0
    }
732
733
0
    struct lut3d *lut3d = NULL;
734
0
    if (!fmt || !gl_lcms_get_lut3d(p->cms, &lut3d, prim, trc, icc) || !lut3d) {
735
0
        p->use_lut_3d = false;
736
0
        return false;
737
0
    }
738
739
0
    ra_tex_free(p->ra, &p->lut_3d_texture);
740
741
0
    struct ra_tex_params params = {
742
0
        .dimensions = 3,
743
0
        .w = lut3d->size[0],
744
0
        .h = lut3d->size[1],
745
0
        .d = lut3d->size[2],
746
0
        .format = fmt,
747
0
        .render_src = true,
748
0
        .src_linear = true,
749
0
        .initial_data = lut3d->data,
750
0
    };
751
0
    p->lut_3d_texture = ra_tex_create(p->ra, &params);
752
753
0
    debug_check_gl(p, "after 3d lut creation");
754
755
0
    for (int i = 0; i < 3; i++)
756
0
        p->lut_3d_size[i] = lut3d->size[i];
757
758
0
    talloc_free(lut3d);
759
760
0
    if (!p->lut_3d_texture) {
761
0
        p->use_lut_3d = false;
762
0
        return false;
763
0
    }
764
765
0
    return true;
766
0
}
767
768
// Fill an image struct from a ra_tex + some metadata
769
static struct image image_wrap(struct ra_tex *tex, enum plane_type type,
770
                               int components)
771
0
{
772
0
    mp_assert(type != PLANE_NONE);
773
0
    return (struct image){
774
0
        .type = type,
775
0
        .tex = tex,
776
0
        .multiplier = 1.0,
777
0
        .w = tex ? tex->params.w : 1,
778
0
        .h = tex ? tex->params.h : 1,
779
0
        .transform = identity_trans,
780
0
        .components = components,
781
0
    };
782
0
}
783
784
// Bind an image to a free texture unit and return its ID.
785
static int pass_bind(struct gl_video *p, struct image img)
786
0
{
787
0
    int idx = p->num_pass_imgs;
788
0
    MP_TARRAY_APPEND(p, p->pass_imgs, p->num_pass_imgs, img);
789
0
    return idx;
790
0
}
791
792
// Rotation by 90° and flipping.
793
// w/h is used for recentering.
794
static void get_transform(float w, float h, int rotate, bool flip,
795
                          struct gl_transform *out_tr)
796
0
{
797
0
    int a = rotate % 90 ? 0 : (rotate / 90) % 4;
798
0
    int sin90[4] = {0, 1, 0, -1}; // just to avoid rounding issues etc.
799
0
    int cos90[4] = {1, 0, -1, 0};
800
0
    struct gl_transform tr = {{{ cos90[a], sin90[a]},
801
0
                               {-sin90[a], cos90[a]}}};
802
803
    // basically, recenter to keep the whole image in view
804
0
    float b[2] = {1, 1};
805
0
    gl_transform_vec(tr, &b[0], &b[1]);
806
0
    tr.t[0] += b[0] < 0 ? w : 0;
807
0
    tr.t[1] += b[1] < 0 ? h : 0;
808
809
0
    if (flip) {
810
0
        struct gl_transform fliptr = {{{1, 0}, {0, -1}}, {0, h}};
811
0
        gl_transform_trans(fliptr, &tr);
812
0
    }
813
814
0
    *out_tr = tr;
815
0
}
816
817
// Return the chroma plane upscaled to luma size, but with additional padding
818
// for image sizes not aligned to subsampling.
819
static int chroma_upsize(int size, int pixel)
820
0
{
821
0
    return (size + pixel - 1) / pixel * pixel;
822
0
}
823
824
// If a and b are on the same plane, return what plane type should be used.
825
// If a or b are none, the other type always wins.
826
// Usually: LUMA/RGB/XYZ > CHROMA > ALPHA
827
static enum plane_type merge_plane_types(enum plane_type a, enum plane_type b)
828
0
{
829
0
    if (a == PLANE_NONE)
830
0
        return b;
831
0
    if (b == PLANE_LUMA || b == PLANE_RGB || b == PLANE_XYZ)
832
0
        return b;
833
0
    if (b != PLANE_NONE && a == PLANE_ALPHA)
834
0
        return b;
835
0
    return a;
836
0
}
837
838
// Places a video_image's image textures + associated metadata into img[]. The
839
// number of textures is equal to p->plane_count. Any necessary plane offsets
840
// are stored in off. (e.g. chroma position)
841
static void pass_get_images(struct gl_video *p, struct video_image *vimg,
842
                            struct image img[4], struct gl_transform off[4])
843
0
{
844
0
    mp_assert(vimg->mpi);
845
846
0
    int w = p->image_params.w;
847
0
    int h = p->image_params.h;
848
849
    // Determine the chroma offset
850
0
    float ls_w = 1.0 / p->ra_format.chroma_w;
851
0
    float ls_h = 1.0 / p->ra_format.chroma_h;
852
853
0
    struct gl_transform chroma = {{{ls_w, 0.0}, {0.0, ls_h}}};
854
855
0
    if (p->image_params.chroma_location != PL_CHROMA_CENTER) {
856
0
        float cx, cy;
857
0
        pl_chroma_location_offset(p->image_params.chroma_location, &cx, &cy);
858
        // By default texture coordinates are such that chroma is centered with
859
        // any chroma subsampling. If a specific direction is given, make it
860
        // so that the luma and chroma sample line up exactly.
861
        // For 4:4:4, setting chroma location should have no effect at all.
862
        // luma sample size (in chroma coord. space)
863
0
        chroma.t[0] = ls_w < 1 ? ls_w * -cx : 0;
864
0
        chroma.t[1] = ls_h < 1 ? ls_h * -cy : 0;
865
0
    }
866
867
0
    memset(img, 0, 4 * sizeof(img[0]));
868
0
    for (int n = 0; n < p->plane_count; n++) {
869
0
        struct texplane *t = &vimg->planes[n];
870
871
0
        enum plane_type type = PLANE_NONE;
872
0
        int padding = 0;
873
0
        for (int i = 0; i < 4; i++) {
874
0
            int c = p->ra_format.components[n][i];
875
0
            enum plane_type ctype;
876
0
            if (c == 0) {
877
0
                ctype = PLANE_NONE;
878
0
            } else if (c == 4) {
879
0
                ctype = PLANE_ALPHA;
880
0
            } else if (p->image_params.repr.sys == PL_COLOR_SYSTEM_RGB) {
881
0
                ctype = PLANE_RGB;
882
0
            } else if (p->image_params.repr.sys == PL_COLOR_SYSTEM_XYZ) {
883
0
                ctype = PLANE_XYZ;
884
0
            } else {
885
0
                ctype = c == 1 ? PLANE_LUMA : PLANE_CHROMA;
886
0
            }
887
0
            type = merge_plane_types(type, ctype);
888
0
            if (!c && padding == i)
889
0
                padding = i + 1;
890
0
        }
891
892
0
        int msb_valid_bits =
893
0
            p->ra_format.component_bits + MPMIN(p->ra_format.component_pad, 0);
894
0
        int csp = type == PLANE_ALPHA ? PL_COLOR_SYSTEM_RGB : p->image_params.repr.sys;
895
0
        float tex_mul =
896
0
            1.0 / mp_get_csp_mul(csp, msb_valid_bits, p->ra_format.component_bits);
897
0
        if (p->ra_format.component_type == RA_CTYPE_FLOAT)
898
0
            tex_mul = 1.0;
899
900
0
        img[n] = (struct image){
901
0
            .type = type,
902
0
            .tex = t->tex,
903
0
            .multiplier = tex_mul,
904
0
            .w = t->w,
905
0
            .h = t->h,
906
0
            .padding = padding,
907
0
        };
908
909
0
        for (int i = 0; i < 4; i++)
910
0
            img[n].components += !!p->ra_format.components[n][i];
911
912
0
        get_transform(t->w, t->h, p->image_params.rotate, t->flipped,
913
0
                      &img[n].transform);
914
0
        if (p->image_params.rotate % 180 == 90)
915
0
            MPSWAP(int, img[n].w, img[n].h);
916
917
0
        off[n] = identity_trans;
918
919
0
        if (type == PLANE_CHROMA) {
920
0
            struct gl_transform rot;
921
            // Reverse the rotation direction here because the different
922
            // coordinate system of chroma offset results in rotation
923
            // in the opposite direction.
924
0
            get_transform(0, 0, 360 - p->image_params.rotate, t->flipped, &rot);
925
926
0
            struct gl_transform tr = chroma;
927
0
            gl_transform_vec(rot, &tr.t[0], &tr.t[1]);
928
929
0
            float dx = (chroma_upsize(w, p->ra_format.chroma_w) - w) * ls_w;
930
0
            float dy = (chroma_upsize(h, p->ra_format.chroma_h) - h) * ls_h;
931
932
            // Adjust the chroma offset if the real chroma size is fractional
933
            // due image sizes not aligned to chroma subsampling.
934
0
            if (rot.m[0][0] < 0)
935
0
                tr.t[0] += dx;
936
0
            if (rot.m[1][0] < 0)
937
0
                tr.t[0] += dy;
938
0
            if (rot.m[0][1] < 0)
939
0
                tr.t[1] += dx;
940
0
            if (rot.m[1][1] < 0)
941
0
                tr.t[1] += dy;
942
943
0
            off[n] = tr;
944
0
        }
945
0
    }
946
0
}
947
948
// Return the index of the given component (assuming all non-padding components
949
// of all planes are concatenated into a linear list).
950
static int find_comp(struct ra_imgfmt_desc *desc, int component)
951
0
{
952
0
    int cur = 0;
953
0
    for (int n = 0; n < desc->num_planes; n++) {
954
0
        for (int i = 0; i < 4; i++) {
955
0
            if (desc->components[n][i]) {
956
0
                if (desc->components[n][i] == component)
957
0
                    return cur;
958
0
                cur++;
959
0
            }
960
0
        }
961
0
    }
962
0
    return -1;
963
0
}
964
965
static void init_video(struct gl_video *p)
966
0
{
967
0
    p->use_integer_conversion = false;
968
969
0
    struct ra_hwdec *hwdec = ra_hwdec_get(&p->hwdec_ctx, p->image_params.imgfmt);
970
0
    if (hwdec) {
971
0
        if (hwdec->driver->overlay_frame) {
972
0
            MP_WARN(p, "Using HW-overlay mode. No GL filtering is performed "
973
0
                       "on the video!\n");
974
0
            p->hwdec_overlay = hwdec;
975
0
        } else {
976
0
            p->hwdec_mapper = ra_hwdec_mapper_create(hwdec, &p->image_params);
977
0
            if (!p->hwdec_mapper)
978
0
                MP_ERR(p, "Initializing texture for hardware decoding failed.\n");
979
0
        }
980
0
        if (p->hwdec_mapper)
981
0
            p->image_params = p->hwdec_mapper->dst_params;
982
0
        const char **exts = hwdec->glsl_extensions;
983
0
        for (int n = 0; exts && exts[n]; n++)
984
0
            gl_sc_enable_extension(p->sc, (char *)exts[n]);
985
0
        p->hwdec_active = true;
986
0
    }
987
988
0
    p->ra_format = (struct ra_imgfmt_desc){0};
989
0
    ra_get_imgfmt_desc(p->ra, p->image_params.imgfmt, &p->ra_format);
990
991
0
    p->plane_count = p->ra_format.num_planes;
992
993
0
    p->has_alpha = false;
994
0
    p->is_gray = true;
995
996
0
    for (int n = 0; n < p->ra_format.num_planes; n++) {
997
0
        for (int i = 0; i < 4; i++) {
998
0
            if (p->ra_format.components[n][i]) {
999
0
                p->has_alpha |= p->ra_format.components[n][i] == 4;
1000
0
                p->is_gray &= p->ra_format.components[n][i] == 1 ||
1001
0
                              p->ra_format.components[n][i] == 4;
1002
0
            }
1003
0
        }
1004
0
    }
1005
1006
0
    for (int c = 0; c < 4; c++) {
1007
0
        int loc = find_comp(&p->ra_format, c + 1);
1008
0
        p->color_swizzle[c] = "rgba"[loc >= 0 && loc < 4 ? loc : 0];
1009
0
    }
1010
0
    p->color_swizzle[4] = '\0';
1011
1012
0
    mp_image_params_restore_dovi_mapping(&p->image_params);
1013
0
    mp_image_params_guess_csp(&p->image_params);
1014
1015
0
    av_lfg_init(&p->lfg, 1);
1016
1017
0
    debug_check_gl(p, "before video texture creation");
1018
1019
0
    if (!p->hwdec_active) {
1020
0
        struct video_image *vimg = &p->image;
1021
1022
0
        struct mp_image layout = {0};
1023
0
        mp_image_set_params(&layout, &p->image_params);
1024
1025
0
        for (int n = 0; n < p->plane_count; n++) {
1026
0
            struct texplane *plane = &vimg->planes[n];
1027
0
            const struct ra_format *format = p->ra_format.planes[n];
1028
1029
0
            plane->w = mp_image_plane_w(&layout, n);
1030
0
            plane->h = mp_image_plane_h(&layout, n);
1031
1032
0
            struct ra_tex_params params = {
1033
0
                .dimensions = 2,
1034
0
                .w = plane->w + p->opts.tex_pad_x,
1035
0
                .h = plane->h + p->opts.tex_pad_y,
1036
0
                .d = 1,
1037
0
                .format = format,
1038
0
                .render_src = true,
1039
0
                .src_linear = format->linear_filter,
1040
0
                .non_normalized = p->opts.use_rectangle,
1041
0
                .host_mutable = true,
1042
0
            };
1043
1044
0
            MP_VERBOSE(p, "Texture for plane %d: %dx%d\n", n,
1045
0
                       params.w, params.h);
1046
1047
0
            plane->tex = ra_tex_create(p->ra, &params);
1048
0
            p->use_integer_conversion |= format->ctype == RA_CTYPE_UINT;
1049
0
        }
1050
0
    }
1051
1052
0
    debug_check_gl(p, "after video texture creation");
1053
1054
    // Format-dependent checks.
1055
0
    check_gl_features(p);
1056
1057
0
    gl_video_setup_hooks(p);
1058
0
}
1059
1060
static struct dr_buffer *gl_find_dr_buffer(struct gl_video *p, uint8_t *ptr)
1061
0
{
1062
0
    for (int i = 0; i < p->num_dr_buffers; i++) {
1063
0
        struct dr_buffer *buffer = &p->dr_buffers[i];
1064
0
        uint8_t *bufptr = buffer->buf->data;
1065
0
        size_t size = buffer->buf->params.size;
1066
0
        if (ptr >= bufptr && ptr < bufptr + size)
1067
0
            return buffer;
1068
0
    }
1069
1070
0
    return NULL;
1071
0
}
1072
1073
static void gc_pending_dr_fences(struct gl_video *p, bool force)
1074
0
{
1075
0
again:;
1076
0
    for (int n = 0; n < p->num_dr_buffers; n++) {
1077
0
        struct dr_buffer *buffer = &p->dr_buffers[n];
1078
0
        if (!buffer->mpi)
1079
0
            continue;
1080
1081
0
        bool res = p->ra->fns->buf_poll(p->ra, buffer->buf);
1082
0
        if (res || force) {
1083
            // Unreferencing the image could cause gl_video_dr_free_buffer()
1084
            // to be called by the talloc destructor (if it was the last
1085
            // reference). This will implicitly invalidate the buffer pointer
1086
            // and change the p->dr_buffers array. To make it worse, it could
1087
            // free multiple dr_buffers due to weird theoretical corner cases.
1088
            // This is also why we use the goto to iterate again from the
1089
            // start, because everything gets fucked up. Hail satan!
1090
0
            struct mp_image *ref = buffer->mpi;
1091
0
            buffer->mpi = NULL;
1092
0
            talloc_free(ref);
1093
0
            goto again;
1094
0
        }
1095
0
    }
1096
0
}
1097
1098
static void unref_current_image(struct gl_video *p)
1099
0
{
1100
0
    struct video_image *vimg = &p->image;
1101
1102
0
    if (vimg->hwdec_mapped) {
1103
0
        mp_assert(p->hwdec_active && p->hwdec_mapper);
1104
0
        ra_hwdec_mapper_end_access(p->hwdec_mapper);
1105
0
        ra_hwdec_mapper_unmap(p->hwdec_mapper);
1106
0
        memset(vimg->planes, 0, sizeof(vimg->planes));
1107
0
        vimg->hwdec_mapped = false;
1108
0
    }
1109
1110
0
    vimg->id = 0;
1111
1112
0
    mp_image_unrefp(&vimg->mpi);
1113
1114
    // While we're at it, also garbage collect pending fences in here to
1115
    // get it out of the way.
1116
0
    gc_pending_dr_fences(p, false);
1117
0
}
1118
1119
// If overlay mode is used, make sure to remove the overlay.
1120
// Be careful with this. Removing the overlay and adding another one will
1121
// lead to flickering artifacts.
1122
static void unmap_overlay(struct gl_video *p)
1123
0
{
1124
0
    if (p->hwdec_overlay)
1125
0
        p->hwdec_overlay->driver->overlay_frame(p->hwdec_overlay, NULL, NULL, NULL, true);
1126
0
}
1127
1128
static void uninit_video(struct gl_video *p)
1129
0
{
1130
0
    uninit_rendering(p);
1131
1132
0
    struct video_image *vimg = &p->image;
1133
1134
0
    unmap_overlay(p);
1135
0
    unref_current_image(p);
1136
1137
0
    for (int n = 0; n < p->plane_count; n++) {
1138
0
        struct texplane *plane = &vimg->planes[n];
1139
0
        ra_tex_free(p->ra, &plane->tex);
1140
0
    }
1141
0
    *vimg = (struct video_image){0};
1142
1143
    // Invalidate image_params to ensure that gl_video_config() will call
1144
    // init_video() on uninitialized gl_video.
1145
0
    p->real_image_params = (struct mp_image_params){0};
1146
0
    p->image_params = p->real_image_params;
1147
0
    p->hwdec_active = false;
1148
0
    p->hwdec_overlay = NULL;
1149
0
    ra_hwdec_mapper_free(&p->hwdec_mapper);
1150
0
}
1151
1152
static void pass_record(struct gl_video *p, const struct mp_pass_perf *perf)
1153
0
{
1154
0
    if (!p->pass || p->pass_idx == VO_PASS_PERF_MAX)
1155
0
        return;
1156
1157
0
    struct pass_info *pass = &p->pass[p->pass_idx];
1158
0
    pass->perf = *perf;
1159
1160
0
    if (pass->desc.len == 0)
1161
0
        bstr_xappend(p, &pass->desc, bstr0("(unknown)"));
1162
1163
0
    p->pass_idx++;
1164
0
}
1165
1166
MP_PRINTF_ATTRIBUTE(2, 3)
1167
static void pass_describe(struct gl_video *p, const char *textf, ...)
1168
0
{
1169
0
    if (!p->pass || p->pass_idx == VO_PASS_PERF_MAX)
1170
0
        return;
1171
1172
0
    struct pass_info *pass = &p->pass[p->pass_idx];
1173
1174
0
    if (pass->desc.len > 0)
1175
0
        bstr_xappend(p, &pass->desc, bstr0(" + "));
1176
1177
0
    va_list ap;
1178
0
    va_start(ap, textf);
1179
0
    bstr_xappend_vasprintf(p, &pass->desc, textf, ap);
1180
0
    va_end(ap);
1181
0
}
1182
1183
static void pass_info_reset(struct gl_video *p, bool is_redraw)
1184
0
{
1185
0
    p->pass = is_redraw ? p->pass_redraw : p->pass_fresh;
1186
0
    p->pass_idx = 0;
1187
1188
0
    for (int i = 0; i < VO_PASS_PERF_MAX; i++) {
1189
0
        p->pass[i].desc.len = 0;
1190
0
    }
1191
0
}
1192
1193
static void pass_report_performance(struct gl_video *p)
1194
0
{
1195
0
    if (!p->pass)
1196
0
        return;
1197
1198
0
    for (int i = 0; i < VO_PASS_PERF_MAX; i++) {
1199
0
        struct pass_info *pass = &p->pass[i];
1200
0
        if (!pass->desc.len)
1201
0
            break;
1202
0
        MP_TRACE(p, "pass '%.*s': last %dus avg %dus peak %dus\n",
1203
0
                 BSTR_P(pass->desc),
1204
0
                 (int)pass->perf.last/1000,
1205
0
                 (int)pass->perf.avg/1000,
1206
0
                 (int)pass->perf.peak/1000);
1207
0
    }
1208
0
}
1209
1210
static void pass_prepare_src_tex(struct gl_video *p)
1211
0
{
1212
0
    struct gl_shader_cache *sc = p->sc;
1213
1214
0
    for (int n = 0; n < p->num_pass_imgs; n++) {
1215
0
        struct image *s = &p->pass_imgs[n];
1216
0
        if (!s->tex)
1217
0
            continue;
1218
1219
0
        char *texture_name = mp_tprintf(32, "texture%d", n);
1220
0
        char *texture_size = mp_tprintf(32, "texture_size%d", n);
1221
0
        char *texture_rot = mp_tprintf(32, "texture_rot%d", n);
1222
0
        char *texture_off = mp_tprintf(32, "texture_off%d", n);
1223
0
        char *pixel_size = mp_tprintf(32, "pixel_size%d", n);
1224
1225
0
        gl_sc_uniform_texture(sc, texture_name, s->tex);
1226
0
        float f[2] = {1, 1};
1227
0
        if (!s->tex->params.non_normalized) {
1228
0
            f[0] = s->tex->params.w;
1229
0
            f[1] = s->tex->params.h;
1230
0
        }
1231
0
        gl_sc_uniform_vec2(sc, texture_size, f);
1232
0
        gl_sc_uniform_mat2(sc, texture_rot, true, (float *)s->transform.m);
1233
0
        gl_sc_uniform_vec2(sc, texture_off, (float *)s->transform.t);
1234
0
        gl_sc_uniform_vec2(sc, pixel_size, (float[]){1.0f / f[0],
1235
0
                                                     1.0f / f[1]});
1236
0
    }
1237
0
}
1238
1239
static void cleanup_binds(struct gl_video *p)
1240
0
{
1241
0
    p->num_pass_imgs = 0;
1242
0
}
1243
1244
// Sets the appropriate compute shader metadata for an implicit compute pass
1245
// bw/bh: block size
1246
static void pass_is_compute(struct gl_video *p, int bw, int bh, bool flexible)
1247
0
{
1248
0
    if (p->pass_compute.active && flexible) {
1249
        // Avoid overwriting existing block sizes when using a flexible pass
1250
0
        bw = p->pass_compute.block_w;
1251
0
        bh = p->pass_compute.block_h;
1252
0
    }
1253
1254
0
    p->pass_compute = (struct compute_info){
1255
0
        .active = true,
1256
0
        .block_w = bw,
1257
0
        .block_h = bh,
1258
0
    };
1259
0
}
1260
1261
// w/h: the width/height of the compute shader's operating domain (e.g. the
1262
// target that needs to be written, or the source texture that needs to
1263
// be reduced)
1264
static void dispatch_compute(struct gl_video *p, int w, int h,
1265
                             struct compute_info info)
1266
0
{
1267
0
    PRELUDE("layout (local_size_x = %d, local_size_y = %d) in;\n",
1268
0
            info.threads_w > 0 ? info.threads_w : info.block_w,
1269
0
            info.threads_h > 0 ? info.threads_h : info.block_h);
1270
1271
0
    pass_prepare_src_tex(p);
1272
1273
    // Since we don't actually have vertices, we pretend for convenience
1274
    // reasons that we do and calculate the right texture coordinates based on
1275
    // the output sample ID
1276
0
    gl_sc_uniform_vec2(p->sc, "out_scale", (float[2]){ 1.0 / w, 1.0 / h });
1277
0
    PRELUDE("#define outcoord(id) (out_scale * (vec2(id) + vec2(0.5)))\n");
1278
1279
0
    for (int n = 0; n < p->num_pass_imgs; n++) {
1280
0
        struct image *s = &p->pass_imgs[n];
1281
0
        if (!s->tex)
1282
0
            continue;
1283
1284
0
        PRELUDE("#define texmap%d(id) (texture_rot%d * outcoord(id) + "
1285
0
               "pixel_size%d * texture_off%d)\n", n, n, n, n);
1286
0
        PRELUDE("#define texcoord%d texmap%d(gl_GlobalInvocationID)\n", n, n);
1287
0
    }
1288
1289
    // always round up when dividing to make sure we don't leave off a part of
1290
    // the image
1291
0
    int num_x = info.block_w > 0 ? (w + info.block_w - 1) / info.block_w : 1,
1292
0
        num_y = info.block_h > 0 ? (h + info.block_h - 1) / info.block_h : 1;
1293
1294
0
    if (!(p->ra->caps & RA_CAP_NUM_GROUPS))
1295
0
        PRELUDE("#define gl_NumWorkGroups uvec3(%d, %d, 1)\n", num_x, num_y);
1296
1297
0
    struct mp_pass_perf perf = gl_sc_dispatch_compute(p->sc, num_x, num_y, 1);
1298
0
    pass_record(p, &perf);
1299
0
    cleanup_binds(p);
1300
0
}
1301
1302
static struct mp_pass_perf render_pass_quad(struct gl_video *p,
1303
                                            const struct ra_fbo *fbo, bool discard,
1304
                                            const struct mp_rect *dst)
1305
0
{
1306
    // The first element is reserved for `vec2 position`
1307
0
    int num_vertex_attribs = 1 + p->num_pass_imgs;
1308
0
    size_t vertex_stride = num_vertex_attribs * sizeof(struct vertex_pt);
1309
1310
    // Expand the VAO if necessary
1311
0
    while (p->vao_len < num_vertex_attribs) {
1312
0
        MP_TARRAY_APPEND(p, p->vao, p->vao_len, (struct ra_renderpass_input) {
1313
0
            .name = talloc_asprintf(p, "texcoord%d", p->vao_len - 1),
1314
0
            .type = RA_VARTYPE_FLOAT,
1315
0
            .dim_v = 2,
1316
0
            .dim_m = 1,
1317
0
            .offset = p->vao_len * sizeof(struct vertex_pt),
1318
0
        });
1319
0
    }
1320
1321
0
    int num_vertices = 6; // quad as triangle list
1322
0
    int num_attribs_total = num_vertices * num_vertex_attribs;
1323
0
    MP_TARRAY_GROW(p, p->tmp_vertex, num_attribs_total);
1324
1325
0
    struct gl_transform t;
1326
0
    gl_transform_ortho_fbo(&t, fbo);
1327
1328
0
    float x[2] = {dst->x0, dst->x1};
1329
0
    float y[2] = {dst->y0, dst->y1};
1330
0
    gl_transform_vec(t, &x[0], &y[0]);
1331
0
    gl_transform_vec(t, &x[1], &y[1]);
1332
1333
0
    for (int n = 0; n < 4; n++) {
1334
0
        struct vertex_pt *vs = &p->tmp_vertex[num_vertex_attribs * n];
1335
        // vec2 position in idx 0
1336
0
        vs[0].x = x[n / 2];
1337
0
        vs[0].y = y[n % 2];
1338
0
        for (int i = 0; i < p->num_pass_imgs; i++) {
1339
0
            struct image *s = &p->pass_imgs[i];
1340
0
            if (!s->tex)
1341
0
                continue;
1342
0
            struct gl_transform tr = s->transform;
1343
0
            float tx = (n / 2) * s->w;
1344
0
            float ty = (n % 2) * s->h;
1345
0
            gl_transform_vec(tr, &tx, &ty);
1346
0
            bool rect = s->tex->params.non_normalized;
1347
            // vec2 texcoordN in idx N+1
1348
0
            vs[i + 1].x = tx / (rect ? 1 : s->tex->params.w);
1349
0
            vs[i + 1].y = ty / (rect ? 1 : s->tex->params.h);
1350
0
        }
1351
0
    }
1352
1353
0
    memmove(&p->tmp_vertex[num_vertex_attribs * 4],
1354
0
            &p->tmp_vertex[num_vertex_attribs * 2],
1355
0
            vertex_stride);
1356
1357
0
    memmove(&p->tmp_vertex[num_vertex_attribs * 5],
1358
0
            &p->tmp_vertex[num_vertex_attribs * 1],
1359
0
            vertex_stride);
1360
1361
0
    return gl_sc_dispatch_draw(p->sc, fbo->tex, discard, p->vao, num_vertex_attribs,
1362
0
                               vertex_stride, p->tmp_vertex, num_vertices);
1363
0
}
1364
1365
static void finish_pass_fbo(struct gl_video *p, const struct ra_fbo *fbo,
1366
                            bool discard, const struct mp_rect *dst)
1367
0
{
1368
0
    pass_prepare_src_tex(p);
1369
0
    struct mp_pass_perf perf = render_pass_quad(p, fbo, discard, dst);
1370
0
    pass_record(p, &perf);
1371
0
    debug_check_gl(p, "after rendering");
1372
0
    cleanup_binds(p);
1373
0
}
1374
1375
// dst_fbo: this will be used for rendering; possibly reallocating the whole
1376
//          FBO, if the required parameters have changed
1377
// w, h: required FBO target dimension, and also defines the target rectangle
1378
//       used for rasterization
1379
static void finish_pass_tex(struct gl_video *p, struct ra_tex **dst_tex,
1380
                            int w, int h)
1381
0
{
1382
0
    if (!ra_tex_resize(p->ra, p->log, dst_tex, w, h, p->fbo_format)) {
1383
0
        cleanup_binds(p);
1384
0
        gl_sc_reset(p->sc);
1385
0
        return;
1386
0
    }
1387
1388
    // If RA_CAP_PARALLEL_COMPUTE is set, try to prefer compute shaders
1389
    // over fragment shaders wherever possible.
1390
0
    if (!p->pass_compute.active && (p->ra->caps & RA_CAP_PARALLEL_COMPUTE) &&
1391
0
        (*dst_tex)->params.storage_dst)
1392
0
    {
1393
0
        pass_is_compute(p, 16, 16, true);
1394
0
    }
1395
1396
0
    if (p->pass_compute.active) {
1397
0
        gl_sc_uniform_image2D_wo(p->sc, "out_image", *dst_tex);
1398
0
        if (!p->pass_compute.directly_writes)
1399
0
            GLSL(imageStore(out_image, ivec2(gl_GlobalInvocationID), color);)
1400
1401
0
        dispatch_compute(p, w, h, p->pass_compute);
1402
0
        p->pass_compute = (struct compute_info){0};
1403
1404
0
        debug_check_gl(p, "after dispatching compute shader");
1405
0
    } else {
1406
0
        struct ra_fbo fbo = { .tex = *dst_tex, };
1407
0
        finish_pass_fbo(p, &fbo, true, &(struct mp_rect){0, 0, w, h});
1408
0
    }
1409
0
}
1410
1411
static const char *get_tex_swizzle(struct image *img)
1412
0
{
1413
0
    if (!img->tex)
1414
0
        return "rgba";
1415
0
    if (img->tex->params.format->luminance_alpha)
1416
0
        return "raaa";
1417
0
    return img->tex->params.format->ordered ? "rgba" : "bgra";
1418
0
}
1419
1420
// Copy a texture to the vec4 color, while increasing offset. Also applies
1421
// the texture multiplier to the sampled color
1422
static void copy_image(struct gl_video *p, unsigned int *offset, struct image img)
1423
0
{
1424
0
    const unsigned int count = img.components;
1425
0
    char src[5] = {0};
1426
0
    char dst[5] = {0};
1427
1428
0
    mp_assert(*offset + count < sizeof(dst));
1429
0
    mp_assert(img.padding + count < sizeof(src));
1430
1431
0
    int id = pass_bind(p, img);
1432
1433
0
    const char *tex_fmt = get_tex_swizzle(&img);
1434
0
    const char *dst_fmt = "rgba";
1435
0
    for (unsigned int i = 0; i < count; i++) {
1436
0
        src[i] = tex_fmt[img.padding + i];
1437
0
        dst[i] = dst_fmt[*offset + i];
1438
0
    }
1439
1440
0
    if (img.tex && img.tex->params.format->ctype == RA_CTYPE_UINT) {
1441
0
        uint64_t tex_max = 1ull << p->ra_format.component_bits;
1442
0
        img.multiplier *= 1.0 / (tex_max - 1);
1443
0
    }
1444
1445
0
    GLSLF("color.%s = %f * vec4(texture(texture%d, texcoord%d)).%s;\n",
1446
0
          dst, img.multiplier, id, id, src);
1447
1448
0
    *offset += count;
1449
0
}
1450
1451
static void skip_unused(struct gl_video *p, int num_components)
1452
0
{
1453
0
    for (int i = num_components; i < 4; i++)
1454
0
        GLSLF("color.%c = %f;\n", "rgba"[i], i < 3 ? 0.0 : 1.0);
1455
0
}
1456
1457
static void uninit_scaler(struct gl_video *p, struct scaler *scaler)
1458
0
{
1459
0
    ra_tex_free(p->ra, &scaler->sep_fbo);
1460
0
    ra_tex_free(p->ra, &scaler->lut);
1461
0
    scaler->kernel = NULL;
1462
0
    scaler->initialized = false;
1463
0
}
1464
1465
static void hook_prelude(struct gl_video *p, const char *name, int id,
1466
                         struct image img)
1467
0
{
1468
0
    GLSLHF("#define %s_raw texture%d\n", name, id);
1469
0
    GLSLHF("#define %s_pos texcoord%d\n", name, id);
1470
0
    GLSLHF("#define %s_size texture_size%d\n", name, id);
1471
0
    GLSLHF("#define %s_rot texture_rot%d\n", name, id);
1472
0
    GLSLHF("#define %s_off texture_off%d\n", name, id);
1473
0
    GLSLHF("#define %s_pt pixel_size%d\n", name, id);
1474
0
    GLSLHF("#define %s_map texmap%d\n", name, id);
1475
0
    GLSLHF("#define %s_mul %f\n", name, img.multiplier);
1476
1477
0
    char crap[5] = "";
1478
0
    snprintf(crap, sizeof(crap), "%s", get_tex_swizzle(&img));
1479
1480
    // Remove leading padding by rotating the swizzle mask.
1481
0
    int len = strlen(crap);
1482
0
    for (int n = 0; n < img.padding; n++) {
1483
0
        if (len) {
1484
0
            char f = crap[0];
1485
0
            memmove(crap, crap + 1, len - 1);
1486
0
            crap[len - 1] = f;
1487
0
        }
1488
0
    }
1489
1490
    // Set up the sampling functions
1491
0
    GLSLHF("#define %s_tex(pos) (%s_mul * vec4(texture(%s_raw, pos)).%s)\n",
1492
0
           name, name, name, crap);
1493
1494
0
    if (p->ra->caps & RA_CAP_GATHER) {
1495
0
        GLSLHF("#define %s_gather(pos, c) (%s_mul * vec4("
1496
0
               "textureGather(%s_raw, pos, c)))\n", name, name, name);
1497
0
    }
1498
1499
    // Since the extra matrix multiplication impacts performance,
1500
    // skip it unless the texture was actually rotated
1501
0
    if (gl_transform_eq(img.transform, identity_trans)) {
1502
0
        GLSLHF("#define %s_texOff(off) %s_tex(%s_pos + %s_pt * vec2(off))\n",
1503
0
               name, name, name, name);
1504
0
    } else {
1505
0
        GLSLHF("#define %s_texOff(off) "
1506
0
                   "%s_tex(%s_pos + %s_rot * vec2(off)/%s_size)\n",
1507
0
               name, name, name, name, name);
1508
0
    }
1509
0
}
1510
1511
static bool saved_img_find(struct gl_video *p, const char *name,
1512
                           struct image *out)
1513
0
{
1514
0
    if (!name || !out)
1515
0
        return false;
1516
1517
0
    for (int i = 0; i < p->num_saved_imgs; i++) {
1518
0
        if (strcmp(p->saved_imgs[i].name, name) == 0) {
1519
0
            *out = p->saved_imgs[i].img;
1520
0
            return true;
1521
0
        }
1522
0
    }
1523
1524
0
    return false;
1525
0
}
1526
1527
static void saved_img_store(struct gl_video *p, const char *name,
1528
                            struct image img)
1529
0
{
1530
0
    mp_assert(name);
1531
1532
0
    for (int i = 0; i < p->num_saved_imgs; i++) {
1533
0
        if (strcmp(p->saved_imgs[i].name, name) == 0) {
1534
0
            p->saved_imgs[i].img = img;
1535
0
            return;
1536
0
        }
1537
0
    }
1538
1539
0
    MP_TARRAY_APPEND(p, p->saved_imgs, p->num_saved_imgs, (struct saved_img) {
1540
0
        .name = name,
1541
0
        .img = img
1542
0
    });
1543
0
}
1544
1545
static bool pass_hook_setup_binds(struct gl_video *p, const char *name,
1546
                                  struct image img, struct tex_hook *hook)
1547
0
{
1548
0
    for (int t = 0; t < SHADER_MAX_BINDS; t++) {
1549
0
        char *bind_name = (char *)hook->bind_tex[t];
1550
1551
0
        if (!bind_name)
1552
0
            continue;
1553
1554
        // This is a special name that means "currently hooked texture"
1555
0
        if (strcmp(bind_name, "HOOKED") == 0) {
1556
0
            int id = pass_bind(p, img);
1557
0
            hook_prelude(p, "HOOKED", id, img);
1558
0
            hook_prelude(p, name, id, img);
1559
0
            continue;
1560
0
        }
1561
1562
        // BIND can also be used to load user-defined textures, in which
1563
        // case we will directly load them as a uniform instead of
1564
        // generating the hook_prelude boilerplate
1565
0
        for (int u = 0; u < p->num_user_textures; u++) {
1566
0
            struct gl_user_shader_tex *utex = &p->user_textures[u];
1567
0
            if (bstr_equals0(utex->name, bind_name)) {
1568
0
                gl_sc_uniform_texture(p->sc, bind_name, utex->tex);
1569
0
                goto next_bind;
1570
0
            }
1571
0
        }
1572
1573
0
        struct image bind_img;
1574
0
        if (!saved_img_find(p, bind_name, &bind_img)) {
1575
            // Clean up texture bindings and move on to the next hook
1576
0
            MP_TRACE(p, "Skipping hook on %s due to no texture named %s.\n",
1577
0
                     name, bind_name);
1578
0
            p->num_pass_imgs -= t;
1579
0
            return false;
1580
0
        }
1581
1582
0
        hook_prelude(p, bind_name, pass_bind(p, bind_img), bind_img);
1583
1584
0
next_bind: ;
1585
0
    }
1586
1587
0
    return true;
1588
0
}
1589
1590
static struct ra_tex **next_hook_tex(struct gl_video *p)
1591
0
{
1592
0
    if (p->idx_hook_textures == p->num_hook_textures)
1593
0
        MP_TARRAY_APPEND(p, p->hook_textures, p->num_hook_textures, NULL);
1594
1595
0
    return &p->hook_textures[p->idx_hook_textures++];
1596
0
}
1597
1598
// Process hooks for a plane, saving the result and returning a new image
1599
// If 'trans' is NULL, the shader is forbidden from transforming img
1600
static struct image pass_hook(struct gl_video *p, const char *name,
1601
                              struct image img, struct gl_transform *trans,
1602
                              int max_output_components)
1603
0
{
1604
0
    if (!name)
1605
0
        return img;
1606
1607
0
    saved_img_store(p, name, img);
1608
1609
0
    MP_TRACE(p, "Running hooks for %s\n", name);
1610
0
    for (int i = 0; i < p->num_tex_hooks; i++) {
1611
0
        struct tex_hook *hook = &p->tex_hooks[i];
1612
1613
        // Figure out if this pass hooks this texture
1614
0
        for (int h = 0; h < SHADER_MAX_HOOKS; h++) {
1615
0
            if (hook->hook_tex[h] && strcmp(hook->hook_tex[h], name) == 0)
1616
0
                goto found;
1617
0
        }
1618
1619
0
        continue;
1620
1621
0
found:
1622
        // Check the hook's condition
1623
0
        if (hook->cond && !hook->cond(p, img, hook->priv)) {
1624
0
            MP_TRACE(p, "Skipping hook on %s due to condition.\n", name);
1625
0
            continue;
1626
0
        }
1627
1628
0
        const char *store_name = hook->save_tex ? hook->save_tex : name;
1629
0
        bool is_overwrite = strcmp(store_name, name) == 0;
1630
0
        int comps = hook->components ? hook->components : img.components;
1631
1632
0
        if (is_overwrite && comps > max_output_components) {
1633
0
            MP_ERR(p, "Hook tried to overwrite %s COMPONENTS to "
1634
0
                   "unsupported value: %d (max supported: %d)\n",
1635
0
                   name, comps, max_output_components);
1636
0
            continue;
1637
0
        }
1638
1639
        // If user shader is set to align HOOKED with reference and fix its
1640
        // offset, it requires HOOKED to be resizable and overwritten.
1641
0
        if (is_overwrite && hook->align_offset) {
1642
0
            if (!trans) {
1643
0
                MP_ERR(p, "Hook tried to align unresizable texture %s!\n",
1644
0
                       name);
1645
0
                return img;
1646
0
            }
1647
1648
0
            struct gl_transform align_off = identity_trans;
1649
0
            align_off.t[0] = trans->t[0];
1650
0
            align_off.t[1] = trans->t[1];
1651
1652
0
            gl_transform_trans(align_off, &img.transform);
1653
0
        }
1654
1655
0
        if (!pass_hook_setup_binds(p, name, img, hook))
1656
0
            continue;
1657
1658
        // Run the actual hook. This generates a series of GLSL shader
1659
        // instructions sufficient for drawing the hook's output
1660
0
        struct gl_transform hook_off = identity_trans;
1661
0
        hook->hook(p, img, &hook_off, hook->priv);
1662
1663
0
        skip_unused(p, comps);
1664
1665
        // Compute the updated FBO dimensions and store the result
1666
0
        struct mp_rect_f sz = {0, 0, img.w, img.h};
1667
0
        gl_transform_rect(hook_off, &sz);
1668
0
        int w = lroundf(fabs(sz.x1 - sz.x0));
1669
0
        int h = lroundf(fabs(sz.y1 - sz.y0));
1670
1671
0
        struct ra_tex **tex = next_hook_tex(p);
1672
0
        finish_pass_tex(p, tex, w, h);
1673
0
        struct image saved_img = image_wrap(*tex, img.type, comps);
1674
1675
        // If the texture we're saving overwrites the "current" texture, also
1676
        // update the tex parameter so that the future loop cycles will use the
1677
        // updated values, and export the offset
1678
0
        if (is_overwrite) {
1679
0
            if (!trans && !gl_transform_eq(hook_off, identity_trans)) {
1680
0
                MP_ERR(p, "Hook tried changing size of unscalable texture %s!\n",
1681
0
                       name);
1682
0
                return img;
1683
0
            }
1684
1685
0
            img = saved_img;
1686
0
            if (trans) {
1687
0
                gl_transform_trans(hook_off, trans);
1688
1689
                // If user shader is set to align HOOKED, the offset it produces
1690
                // is dynamic (with static resizing factor though).
1691
                // Align it with reference manually to get offset fixed.
1692
0
                if (hook->align_offset) {
1693
0
                    trans->t[0] = 0.0;
1694
0
                    trans->t[1] = 0.0;
1695
0
                }
1696
0
            }
1697
0
        }
1698
1699
0
        saved_img_store(p, store_name, saved_img);
1700
0
    }
1701
1702
0
    return img;
1703
0
}
1704
1705
// This can be used at any time in the middle of rendering to specify an
1706
// optional hook point, which if triggered will render out to a new FBO and
1707
// load the result back into vec4 color. Offsets applied by the hooks are
1708
// accumulated in tex_trans, and the FBO is dimensioned according
1709
// to p->texture_w/h
1710
static void pass_opt_hook_point(struct gl_video *p, const char *name,
1711
                                struct gl_transform *tex_trans)
1712
0
{
1713
0
    if (!name)
1714
0
        return;
1715
1716
0
    for (int i = 0; i < p->num_tex_hooks; i++) {
1717
0
        struct tex_hook *hook = &p->tex_hooks[i];
1718
1719
0
        for (int h = 0; h < SHADER_MAX_HOOKS; h++) {
1720
0
            if (hook->hook_tex[h] && strcmp(hook->hook_tex[h], name) == 0)
1721
0
                goto found;
1722
0
        }
1723
1724
0
        for (int b = 0; b < SHADER_MAX_BINDS; b++) {
1725
0
            if (hook->bind_tex[b] && strcmp(hook->bind_tex[b], name) == 0)
1726
0
                goto found;
1727
0
        }
1728
0
    }
1729
1730
    // Nothing uses this texture, don't bother storing it
1731
0
    return;
1732
1733
0
found: ;
1734
0
    struct ra_tex **tex = next_hook_tex(p);
1735
0
    finish_pass_tex(p, tex, p->texture_w, p->texture_h);
1736
0
    struct image img = image_wrap(*tex, PLANE_RGB, p->components);
1737
0
    img = pass_hook(p, name, img, tex_trans, 4);
1738
0
    copy_image(p, &(int){0}, img);
1739
0
    p->texture_w = img.w;
1740
0
    p->texture_h = img.h;
1741
0
    p->components = img.components;
1742
0
    pass_describe(p, "(remainder pass)");
1743
0
}
1744
1745
static void load_shader(struct gl_video *p, struct bstr body)
1746
0
{
1747
0
    gl_sc_hadd_bstr(p->sc, body);
1748
0
    gl_sc_uniform_dynamic(p->sc);
1749
0
    gl_sc_uniform_f(p->sc, "random", (double)av_lfg_get(&p->lfg) / UINT32_MAX);
1750
0
    gl_sc_uniform_dynamic(p->sc);
1751
0
    gl_sc_uniform_i(p->sc, "frame", p->frames_uploaded);
1752
0
    gl_sc_uniform_vec2(p->sc, "input_size",
1753
0
                       (float[]){(p->src_rect.x1 - p->src_rect.x0) *
1754
0
                                  p->texture_offset.m[0][0],
1755
0
                                  (p->src_rect.y1 - p->src_rect.y0) *
1756
0
                                  p->texture_offset.m[1][1]});
1757
0
    gl_sc_uniform_vec2(p->sc, "target_size",
1758
0
                       (float[]){p->dst_rect.x1 - p->dst_rect.x0,
1759
0
                                 p->dst_rect.y1 - p->dst_rect.y0});
1760
0
    gl_sc_uniform_vec2(p->sc, "tex_offset",
1761
0
                       (float[]){p->src_rect.x0 * p->texture_offset.m[0][0] +
1762
0
                                 p->texture_offset.t[0],
1763
0
                                 p->src_rect.y0 * p->texture_offset.m[1][1] +
1764
0
                                 p->texture_offset.t[1]});
1765
0
}
1766
1767
// Semantic equality
1768
static bool double_seq(double a, double b)
1769
0
{
1770
0
    return (isnan(a) && isnan(b)) || a == b;
1771
0
}
1772
1773
static bool scaler_fun_eq(struct scaler_fun a, struct scaler_fun b)
1774
0
{
1775
0
    return a.function == b.function &&
1776
0
           double_seq(a.params[0], b.params[0]) &&
1777
0
           double_seq(a.params[1], b.params[1]) &&
1778
0
           a.blur == b.blur &&
1779
0
           a.taper == b.taper;
1780
0
}
1781
1782
static bool scaler_conf_eq(struct scaler_config a, struct scaler_config b)
1783
0
{
1784
    // Note: antiring isn't compared because it doesn't affect LUT
1785
    // generation
1786
0
    return scaler_fun_eq(a.kernel, b.kernel) &&
1787
0
           scaler_fun_eq(a.window, b.window) &&
1788
0
           a.radius == b.radius &&
1789
0
           a.clamp == b.clamp;
1790
0
}
1791
1792
void scaler_conf_merge(struct scaler_config *dst, const struct scaler_config *src,
1793
                       enum scaler_unit unit)
1794
0
{
1795
0
    if (dst->kernel.function != SCALER_INHERIT)
1796
0
        return;
1797
0
    mp_assert(src->kernel.function != SCALER_INHERIT);
1798
0
    dst->kernel.function = src->kernel.function;
1799
1800
0
    const struct scaler_config *def = &gl_video_opts_def.scaler[unit];
1801
0
    for (int i = 0; i < MP_ARRAY_SIZE(dst->kernel.params); i++) {
1802
0
        if (isnan(dst->kernel.params[i]) || dst->kernel.params[i] == def->kernel.params[i])
1803
0
            dst->kernel.params[i] = src->kernel.params[i];
1804
0
        if (isnan(dst->window.params[i]) || dst->window.params[i] == def->window.params[i])
1805
0
            dst->window.params[i] = src->window.params[i];
1806
0
    }
1807
0
    if (dst->kernel.blur == def->kernel.blur)
1808
0
        dst->kernel.blur = src->kernel.blur;
1809
0
    if (dst->kernel.taper == def->kernel.taper)
1810
0
        dst->kernel.taper = src->kernel.taper;
1811
0
    if (dst->window.taper == def->window.taper)
1812
0
        dst->window.taper = src->window.taper;
1813
0
    if (dst->clamp == def->clamp)
1814
0
        dst->clamp = src->clamp;
1815
0
    if (dst->radius == def->radius)
1816
0
        dst->radius = src->radius;
1817
0
    if (dst->antiring == def->antiring)
1818
0
        dst->antiring = src->antiring;
1819
0
    if (dst->window.function == def->window.function)
1820
0
        dst->window.function = src->window.function;
1821
0
}
1822
1823
static void reinit_scaler(struct gl_video *p, struct scaler *scaler,
1824
                          const struct scaler_config *conf,
1825
                          double scale_factor,
1826
                          int sizes[])
1827
0
{
1828
0
    mp_assert(conf);
1829
0
    mp_assert(conf->kernel.function != SCALER_INHERIT);
1830
0
    if (scaler_conf_eq(scaler->conf, *conf) &&
1831
0
        scaler->scale_factor == scale_factor &&
1832
0
        scaler->initialized)
1833
0
        return;
1834
1835
0
    uninit_scaler(p, scaler);
1836
1837
0
    struct filter_kernel bare_window;
1838
0
    const struct filter_kernel *t_kernel = mp_find_filter_kernel(conf->kernel.function);
1839
0
    const struct filter_window *t_window = mp_find_filter_window(conf->window.function);
1840
0
    if (!t_kernel) {
1841
0
        const struct filter_window *window = mp_find_filter_window(conf->kernel.function);
1842
0
        if (window) {
1843
0
            bare_window = (struct filter_kernel) { .f = *window };
1844
0
            t_kernel = &bare_window;
1845
0
        }
1846
0
    }
1847
1848
0
    scaler->conf = *conf;
1849
0
    scaler->scale_factor = scale_factor;
1850
0
    scaler->insufficient = false;
1851
0
    scaler->initialized = true;
1852
0
    if (!t_kernel)
1853
0
        return;
1854
1855
0
    scaler->kernel_storage = *t_kernel;
1856
0
    scaler->kernel = &scaler->kernel_storage;
1857
1858
0
    if (!t_window) {
1859
        // fall back to the scaler's default window if available
1860
0
        t_window = mp_find_filter_window(t_kernel->window);
1861
0
    }
1862
0
    if (t_window)
1863
0
        scaler->kernel->w = *t_window;
1864
1865
0
    for (int n = 0; n < 2; n++) {
1866
0
        if (!isnan(conf->kernel.params[n]))
1867
0
            scaler->kernel->f.params[n] = conf->kernel.params[n];
1868
0
        if (!isnan(conf->window.params[n]))
1869
0
            scaler->kernel->w.params[n] = conf->window.params[n];
1870
0
    }
1871
1872
0
    if (conf->kernel.blur > 0.0)
1873
0
        scaler->kernel->f.blur = conf->kernel.blur;
1874
0
    if (conf->window.blur > 0.0)
1875
0
        scaler->kernel->w.blur = conf->window.blur;
1876
1877
0
    if (conf->kernel.taper > 0.0)
1878
0
        scaler->kernel->f.taper = conf->kernel.taper;
1879
0
    if (conf->window.taper > 0.0)
1880
0
        scaler->kernel->w.taper = conf->window.taper;
1881
1882
0
    if (scaler->kernel->f.resizable && conf->radius > 0.0)
1883
0
        scaler->kernel->f.radius = conf->radius;
1884
1885
0
    scaler->kernel->clamp = conf->clamp;
1886
0
    scaler->insufficient = !mp_init_filter(scaler->kernel, sizes, scale_factor);
1887
1888
0
    int size = scaler->kernel->size;
1889
0
    int num_components = size > 2 ? 4 : size;
1890
0
    const struct ra_format *fmt = ra_find_float16_format(p->ra, num_components);
1891
0
    mp_assert(fmt);
1892
1893
0
    int width = (size + num_components - 1) / num_components; // round up
1894
0
    int stride = width * num_components;
1895
0
    mp_assert(size <= stride);
1896
1897
0
    static const int lut_size = 256;
1898
0
    float *weights = talloc_array(NULL, float, lut_size * stride);
1899
0
    mp_compute_lut(scaler->kernel, lut_size, stride, weights);
1900
1901
0
    for (int n = 0; n < lut_size; n++) {
1902
0
        float *row = weights + n * stride;
1903
0
        for (int i = size; i < stride; i++)
1904
0
            row[i] = row[i - num_components];
1905
0
    }
1906
1907
0
    bool use_1d = scaler->kernel->polar && (p->ra->caps & RA_CAP_TEX_1D);
1908
1909
0
    struct ra_tex_params lut_params = {
1910
0
        .dimensions = use_1d ? 1 : 2,
1911
0
        .w = use_1d ? lut_size : width,
1912
0
        .h = use_1d ? 1 : lut_size,
1913
0
        .d = 1,
1914
0
        .format = fmt,
1915
0
        .render_src = true,
1916
0
        .src_linear = true,
1917
0
        .initial_data = weights,
1918
0
    };
1919
0
    scaler->lut = ra_tex_create(p->ra, &lut_params);
1920
1921
0
    talloc_free(weights);
1922
1923
0
    debug_check_gl(p, "after initializing scaler");
1924
0
}
1925
1926
// Special helper for sampling from two separated stages
1927
static void pass_sample_separated(struct gl_video *p, struct image src,
1928
                                  struct scaler *scaler, int w, int h)
1929
0
{
1930
    // Separate the transformation into x and y components, per pass
1931
0
    struct gl_transform t_x = {
1932
0
        .m = {{src.transform.m[0][0], 0.0}, {src.transform.m[1][0], 1.0}},
1933
0
        .t = {src.transform.t[0], 0.0},
1934
0
    };
1935
0
    struct gl_transform t_y = {
1936
0
        .m = {{1.0, src.transform.m[0][1]}, {0.0, src.transform.m[1][1]}},
1937
0
        .t = {0.0, src.transform.t[1]},
1938
0
    };
1939
1940
    // First pass (scale only in the y dir)
1941
0
    src.transform = t_y;
1942
0
    sampler_prelude(p->sc, pass_bind(p, src));
1943
0
    GLSLF("// first pass\n");
1944
0
    pass_sample_separated_gen(p->sc, scaler, 0, 1);
1945
0
    GLSLF("color *= %f;\n", src.multiplier);
1946
0
    finish_pass_tex(p, &scaler->sep_fbo, src.w, h);
1947
1948
    // Second pass (scale only in the x dir)
1949
0
    src = image_wrap(scaler->sep_fbo, src.type, src.components);
1950
0
    src.transform = t_x;
1951
0
    pass_describe(p, "%s second pass",
1952
0
                  m_opt_choice_str(scaler->conf.kernel.functions,
1953
0
                                   scaler->conf.kernel.function));
1954
0
    sampler_prelude(p->sc, pass_bind(p, src));
1955
0
    pass_sample_separated_gen(p->sc, scaler, 1, 0);
1956
0
}
1957
1958
// Picks either the compute shader version or the regular sampler version
1959
// depending on hardware support
1960
static void pass_dispatch_sample_polar(struct gl_video *p, struct scaler *scaler,
1961
                                       struct image img, int w, int h)
1962
0
{
1963
0
    uint64_t reqs = RA_CAP_COMPUTE;
1964
0
    if ((p->ra->caps & reqs) != reqs)
1965
0
        goto fallback;
1966
1967
0
    int bound = ceil(scaler->kernel->radius_cutoff);
1968
0
    int offset = bound - 1; // padding top/left
1969
0
    int padding = offset + bound; // total padding
1970
1971
0
    float ratiox = (float)w / img.w,
1972
0
          ratioy = (float)h / img.h;
1973
1974
    // For performance we want to load at least as many pixels
1975
    // horizontally as there are threads in a warp (32 for nvidia), as
1976
    // well as enough to take advantage of shmem parallelism
1977
0
    const int warp_size = 32, threads = 256;
1978
0
    int bw = warp_size;
1979
0
    int bh = threads / bw;
1980
1981
    // We need to sample everything from base_min to base_max, so make sure
1982
    // we have enough room in shmem
1983
0
    int iw = (int)ceil(bw / ratiox) + padding + 1,
1984
0
        ih = (int)ceil(bh / ratioy) + padding + 1;
1985
1986
0
    int shmem_req = iw * ih * img.components * sizeof(float);
1987
0
    if (shmem_req > p->ra->max_shmem)
1988
0
        goto fallback;
1989
1990
0
    pass_is_compute(p, bw, bh, false);
1991
0
    pass_compute_polar(p->sc, scaler, img.components, bw, bh, iw, ih);
1992
0
    return;
1993
1994
0
fallback:
1995
    // Fall back to regular polar shader when compute shaders are unsupported
1996
    // or the kernel is too big for shmem
1997
0
    pass_sample_polar(p->sc, scaler, img.components,
1998
0
                      p->ra->caps & RA_CAP_GATHER);
1999
0
}
2000
2001
// Sample from image, with the src rectangle given by it.
2002
// The dst rectangle is implicit by what the caller will do next, but w and h
2003
// must still be what is going to be used (to dimension FBOs correctly).
2004
// This will write the scaled contents to the vec4 "color".
2005
// The scaler unit is initialized by this function; in order to avoid cache
2006
// thrashing, the scaler unit should usually use the same parameters.
2007
static void pass_sample(struct gl_video *p, struct image img,
2008
                        struct scaler *scaler, const struct scaler_config *conf,
2009
                        double scale_factor, int w, int h)
2010
0
{
2011
0
    reinit_scaler(p, scaler, conf, scale_factor, filter_sizes);
2012
2013
    // Describe scaler
2014
0
    const char *scaler_opt[] = {
2015
0
        [SCALER_SCALE] = "scale",
2016
0
        [SCALER_DSCALE] = "dscale",
2017
0
        [SCALER_CSCALE] = "cscale",
2018
0
        [SCALER_TSCALE] = "tscale",
2019
0
    };
2020
2021
0
    pass_describe(p, "%s=%s (%s)", scaler_opt[scaler->index],
2022
0
                  m_opt_choice_str(scaler->conf.kernel.functions,
2023
0
                                   scaler->conf.kernel.function),
2024
0
                  plane_names[img.type]);
2025
2026
0
    bool is_separated = scaler->kernel && !scaler->kernel->polar;
2027
2028
    // Set up the transformation+prelude and bind the texture, for everything
2029
    // other than separated scaling (which does this in the subfunction)
2030
0
    if (!is_separated)
2031
0
        sampler_prelude(p->sc, pass_bind(p, img));
2032
2033
    // Dispatch the scaler. They're all wildly different.
2034
0
    if (scaler->conf.kernel.function == SCALER_BILINEAR) {
2035
0
        GLSL(color = texture(tex, pos);)
2036
0
    } else if (scaler->conf.kernel.function == SCALER_BICUBIC_FAST) {
2037
0
        pass_sample_bicubic_fast(p->sc);
2038
0
    } else if (scaler->conf.kernel.function == SCALER_OVERSAMPLE) {
2039
0
        pass_sample_oversample(p->sc, scaler, w, h);
2040
0
    } else if (scaler->kernel && scaler->kernel->polar) {
2041
0
        pass_dispatch_sample_polar(p, scaler, img, w, h);
2042
0
    } else if (scaler->kernel) {
2043
0
        pass_sample_separated(p, img, scaler, w, h);
2044
0
    } else {
2045
0
        MP_ASSERT_UNREACHABLE(); // should never happen
2046
0
    }
2047
2048
    // Apply any required multipliers. Separated scaling already does this in
2049
    // its first stage
2050
0
    if (!is_separated)
2051
0
        GLSLF("color *= %f;\n", img.multiplier);
2052
2053
    // Micro-optimization: Avoid scaling unneeded channels
2054
0
    skip_unused(p, img.components);
2055
0
}
2056
2057
// Returns true if two images are semantically equivalent (same metadata)
2058
static bool image_equiv(struct image a, struct image b)
2059
0
{
2060
0
    return a.type == b.type &&
2061
0
           a.components == b.components &&
2062
0
           a.multiplier == b.multiplier &&
2063
0
           a.tex->params.format == b.tex->params.format &&
2064
0
           a.tex->params.w == b.tex->params.w &&
2065
0
           a.tex->params.h == b.tex->params.h &&
2066
0
           a.w == b.w &&
2067
0
           a.h == b.h &&
2068
0
           gl_transform_eq(a.transform, b.transform);
2069
0
}
2070
2071
static void deband_hook(struct gl_video *p, struct image img,
2072
                        struct gl_transform *trans, void *priv)
2073
0
{
2074
0
    pass_describe(p, "debanding (%s)", plane_names[img.type]);
2075
0
    pass_sample_deband(p->sc, p->opts.deband_opts, &p->lfg,
2076
0
                       p->image_params.color.transfer);
2077
0
}
2078
2079
static void unsharp_hook(struct gl_video *p, struct image img,
2080
                         struct gl_transform *trans, void *priv)
2081
0
{
2082
0
    pass_describe(p, "unsharp masking");
2083
0
    pass_sample_unsharp(p->sc, p->opts.unsharp);
2084
0
}
2085
2086
struct szexp_ctx {
2087
    struct gl_video *p;
2088
    struct image img;
2089
    struct gl_user_shader_hook *shader;
2090
};
2091
2092
static bool szexp_tex_lookup(void *priv, struct bstr var, float size[2])
2093
0
{
2094
0
    struct szexp_ctx *ctx = priv;
2095
0
    struct gl_video *p = ctx->p;
2096
2097
0
    if (bstr_equals0(var, "NATIVE_CROPPED")) {
2098
0
        size[0] = (p->src_rect.x1 - p->src_rect.x0) * p->texture_offset.m[0][0];
2099
0
        size[1] = (p->src_rect.y1 - p->src_rect.y0) * p->texture_offset.m[1][1];
2100
0
        return true;
2101
0
    }
2102
2103
    // The size of OUTPUT is determined. It could be useful for certain
2104
    // user shaders to skip passes.
2105
0
    if (bstr_equals0(var, "OUTPUT")) {
2106
0
        size[0] = p->dst_rect.x1 - p->dst_rect.x0;
2107
0
        size[1] = p->dst_rect.y1 - p->dst_rect.y0;
2108
0
        return true;
2109
0
    }
2110
2111
    // HOOKED is a special case
2112
0
    if (bstr_equals0(var, "HOOKED")) {
2113
0
        size[0] = ctx->img.w;
2114
0
        size[1] = ctx->img.h;
2115
0
        return true;
2116
0
    }
2117
2118
0
    for (int o = 0; o < p->num_saved_imgs; o++) {
2119
0
        if (bstr_equals0(var, p->saved_imgs[o].name)) {
2120
0
            size[0] = p->saved_imgs[o].img.w;
2121
0
            size[1] = p->saved_imgs[o].img.h;
2122
0
            return true;
2123
0
        }
2124
0
    }
2125
2126
0
    return false;
2127
0
}
2128
2129
static bool szexp_param_lookup(void *priv, struct bstr var, float *out)
2130
0
{
2131
0
    struct szexp_ctx *ctx = priv;
2132
2133
0
    for (int i = 0; i < ctx->shader->num_params; i++) {
2134
0
        const struct gl_user_shader_param *param = &ctx->shader->params[i];
2135
0
        if (bstr_equals(var, param->name)) {
2136
0
            double value = param->value;
2137
0
            gpu_get_auto_param(ctx->p->image.mpi, param->name, &value);
2138
0
            *out = value;
2139
0
            return true;
2140
0
        }
2141
0
        int idx = resolve_shader_enum_name(param, var);
2142
0
        if (idx >= 0) {
2143
0
            *out = idx;
2144
0
            return true;
2145
0
        }
2146
0
    }
2147
2148
0
    return false;
2149
0
}
2150
2151
static bool user_hook_cond(struct gl_video *p, struct image img, void *priv)
2152
0
{
2153
0
    struct gl_user_shader_hook *shader = priv;
2154
0
    mp_assert(shader);
2155
2156
0
    float res = false;
2157
0
    struct szexp_ctx ctx = {p, img, shader};
2158
0
    eval_szexpr(p->log, &ctx, szexp_tex_lookup, szexp_param_lookup,
2159
0
                shader->cond, &res);
2160
0
    return res;
2161
0
}
2162
2163
static void update_user_shader_opts(struct gl_video *p, const char *path,
2164
                                    struct gl_user_shader_hook *shader)
2165
0
{
2166
0
    for (int i = 0; i < shader->num_params; i++)
2167
0
        shader->params[i].value = shader->params[i].initial;
2168
2169
0
    if (!p->opts.user_shader_opts)
2170
0
        return;
2171
2172
0
    struct bstr shadername = mp_strip_ext(mp_basename_bstr(bstr0(path)));
2173
2174
0
    for (int n = 0; p->opts.user_shader_opts[n * 2]; n++) {
2175
0
        struct bstr key = bstr0(p->opts.user_shader_opts[n * 2 + 0]);
2176
0
        struct bstr val = bstr0(p->opts.user_shader_opts[n * 2 + 1]);
2177
2178
0
        int pos = bstrchr(key, '/');
2179
0
        if (pos >= 0) {
2180
0
            if (!bstr_equals(bstr_splice(key, 0, pos), shadername))
2181
0
                continue;
2182
0
            key = bstr_cut(key, pos + 1);
2183
0
        }
2184
2185
0
        for (int i = 0; i < shader->num_params; i++) {
2186
0
            struct gl_user_shader_param *param = &shader->params[i];
2187
0
            if (!bstr_equals(key, param->name))
2188
0
                continue;
2189
0
            parse_shader_param_value(p->log, param, val, &param->value);
2190
0
        }
2191
0
    }
2192
0
}
2193
2194
static void user_hook(struct gl_video *p, struct image img,
2195
                      struct gl_transform *trans, void *priv)
2196
0
{
2197
0
    struct gl_user_shader_hook *shader = priv;
2198
0
    mp_assert(shader);
2199
2200
0
    for (int i = 0; i < shader->num_params; i++) {
2201
0
        const struct gl_user_shader_param *param = &shader->params[i];
2202
2203
0
        struct bstr enum_rest = param->enum_body;
2204
0
        int idx = 0;
2205
0
        while (enum_rest.len > 0) {
2206
0
            struct bstr enum_line = bstr_strip(bstr_getline(enum_rest, &enum_rest));
2207
0
            if (enum_line.len == 0)
2208
0
                continue;
2209
0
            GLSLHF("#define %.*s %d\n", BSTR_P(enum_line), idx);
2210
0
            idx++;
2211
0
        }
2212
2213
0
        double value = param->value;
2214
0
        gpu_get_auto_param(p->image.mpi, param->name, &value);
2215
2216
0
        switch (param->type) {
2217
0
        case GL_USER_SHADER_PARAM_FLOAT:
2218
0
            gl_sc_uniform_f_bstr(p->sc, param->name, value);
2219
0
            break;
2220
0
        case GL_USER_SHADER_PARAM_INT:
2221
0
            gl_sc_uniform_i_bstr(p->sc, param->name, lrint(value));
2222
0
            break;
2223
0
        case GL_USER_SHADER_PARAM_DEFINE:
2224
0
            GLSLHF("#define %.*s %d\n", BSTR_P(param->name), (int)lrint(value));
2225
0
            break;
2226
0
        }
2227
0
    }
2228
2229
0
    load_shader(p, shader->pass_body);
2230
2231
0
    pass_describe(p, "user shader: %.*s (%s)", BSTR_P(shader->pass_desc),
2232
0
                  plane_names[img.type]);
2233
2234
0
    if (shader->compute.active) {
2235
0
        p->pass_compute = shader->compute;
2236
0
        GLSLF("hook();\n");
2237
0
    } else {
2238
0
        GLSLF("color = hook();\n");
2239
0
    }
2240
2241
    // Make sure we at least create a legal FBO on failure, since it's better
2242
    // to do this and display an error message than just crash OpenGL
2243
0
    float w = 1.0, h = 1.0;
2244
2245
0
    eval_szexpr(p->log, &(struct szexp_ctx){p, img, shader}, szexp_tex_lookup,
2246
0
                szexp_param_lookup, shader->width, &w);
2247
0
    eval_szexpr(p->log, &(struct szexp_ctx){p, img, shader}, szexp_tex_lookup,
2248
0
                szexp_param_lookup, shader->height, &h);
2249
2250
0
    *trans = (struct gl_transform){{{w / img.w, 0}, {0, h / img.h}}};
2251
0
    gl_transform_trans(shader->offset, trans);
2252
0
}
2253
2254
static bool add_user_hook(void *priv, const char *path,
2255
                          const struct gl_user_shader_hook *hook)
2256
0
{
2257
0
    struct gl_video *p = priv;
2258
0
    struct gl_user_shader_hook *copy = talloc_dup(p, (struct gl_user_shader_hook *)hook);
2259
0
    update_user_shader_opts(p, path, copy);
2260
0
    struct tex_hook texhook = {
2261
0
        .save_tex = bstrdup0(copy, copy->save_tex),
2262
0
        .components = copy->components,
2263
0
        .align_offset = copy->align_offset,
2264
0
        .hook = user_hook,
2265
0
        .cond = user_hook_cond,
2266
0
        .priv = copy,
2267
0
    };
2268
2269
0
    for (int h = 0; h < SHADER_MAX_HOOKS; h++)
2270
0
        texhook.hook_tex[h] = bstrdup0(copy, copy->hook_tex[h]);
2271
0
    for (int h = 0; h < SHADER_MAX_BINDS; h++)
2272
0
        texhook.bind_tex[h] = bstrdup0(copy, copy->bind_tex[h]);
2273
2274
0
    MP_TARRAY_APPEND(p, p->tex_hooks, p->num_tex_hooks, texhook);
2275
0
    return true;
2276
0
}
2277
2278
static bool add_user_tex(void *priv, struct gl_user_shader_tex tex)
2279
0
{
2280
0
    struct gl_video *p = priv;
2281
2282
0
    tex.tex = ra_tex_create(p->ra, &tex.params);
2283
0
    TA_FREEP(&tex.params.initial_data);
2284
2285
0
    if (!tex.tex)
2286
0
        return false;
2287
2288
0
    MP_TARRAY_APPEND(p, p->user_textures, p->num_user_textures, tex);
2289
0
    return true;
2290
0
}
2291
2292
static void load_user_shaders(struct gl_video *p, char **shaders)
2293
0
{
2294
0
    if (!shaders)
2295
0
        return;
2296
2297
0
    for (int n = 0; shaders[n] != NULL; n++) {
2298
0
        struct bstr file = load_cached_file(p, shaders[n]);
2299
0
        parse_user_shader(p->log, p->ra, file, shaders[n], p, add_user_hook, add_user_tex);
2300
0
    }
2301
0
}
2302
2303
static void gl_video_setup_hooks(struct gl_video *p)
2304
0
{
2305
0
    gl_video_reset_hooks(p);
2306
2307
0
    if (p->opts.deband) {
2308
0
        MP_TARRAY_APPEND(p, p->tex_hooks, p->num_tex_hooks, (struct tex_hook) {
2309
0
            .hook_tex = {"LUMA", "CHROMA", "RGB", "XYZ"},
2310
0
            .bind_tex = {"HOOKED"},
2311
0
            .hook = deband_hook,
2312
0
        });
2313
0
    }
2314
2315
0
    if (p->opts.unsharp != 0.0) {
2316
0
        MP_TARRAY_APPEND(p, p->tex_hooks, p->num_tex_hooks, (struct tex_hook) {
2317
0
            .hook_tex = {"MAIN"},
2318
0
            .bind_tex = {"HOOKED"},
2319
0
            .hook = unsharp_hook,
2320
0
        });
2321
0
    }
2322
2323
0
    load_user_shaders(p, p->opts.user_shaders);
2324
0
}
2325
2326
// sample from video textures, set "color" variable to yuv value
2327
static void pass_read_video(struct gl_video *p)
2328
0
{
2329
0
    struct image img[4];
2330
0
    struct gl_transform offsets[4];
2331
0
    pass_get_images(p, &p->image, img, offsets);
2332
2333
    // To keep the code as simple as possibly, we currently run all shader
2334
    // stages even if they would be unnecessary (e.g. no hooks for a texture).
2335
    // In the future, deferred image should optimize this away.
2336
2337
    // Merge semantically identical textures. This loop is done from back
2338
    // to front so that merged textures end up in the right order while
2339
    // simultaneously allowing us to skip unnecessary merges
2340
0
    for (int n = 3; n >= 0; n--) {
2341
0
        if (img[n].type == PLANE_NONE)
2342
0
            continue;
2343
2344
0
        int first = n;
2345
0
        int num = 0;
2346
2347
0
        for (int i = 0; i < n; i++) {
2348
0
            if (image_equiv(img[n], img[i]) &&
2349
0
                gl_transform_eq(offsets[n], offsets[i]))
2350
0
            {
2351
0
                GLSLF("// merging plane %d ...\n", i);
2352
0
                copy_image(p, &num, img[i]);
2353
0
                first = MPMIN(first, i);
2354
0
                img[i] = (struct image){0};
2355
0
            }
2356
0
        }
2357
2358
0
        if (num > 0) {
2359
0
            GLSLF("// merging plane %d ... into %d\n", n, first);
2360
0
            copy_image(p, &num, img[n]);
2361
0
            pass_describe(p, "merging planes");
2362
0
            finish_pass_tex(p, &p->merge_tex[n], img[n].w, img[n].h);
2363
0
            img[first] = image_wrap(p->merge_tex[n], img[n].type, num);
2364
0
            img[n] = (struct image){0};
2365
0
        }
2366
0
    }
2367
2368
    // If any textures are still in integer format by this point, we need
2369
    // to introduce an explicit conversion pass to avoid breaking hooks/scaling
2370
0
    for (int n = 0; n < 4; n++) {
2371
0
        if (img[n].tex && img[n].tex->params.format->ctype == RA_CTYPE_UINT) {
2372
0
            GLSLF("// use_integer fix for plane %d\n", n);
2373
0
            copy_image(p, &(int){0}, img[n]);
2374
0
            pass_describe(p, "use_integer fix");
2375
0
            finish_pass_tex(p, &p->integer_tex[n], img[n].w, img[n].h);
2376
0
            img[n] = image_wrap(p->integer_tex[n], img[n].type,
2377
0
                                img[n].components);
2378
0
        }
2379
0
    }
2380
2381
    // The basic idea is we assume the rgb/luma texture is the "reference" and
2382
    // scale everything else to match, after all planes are finalized.
2383
    // We find the reference texture first, in order to maintain texture offset
2384
    // between hooks on different type of planes.
2385
0
    int reference_tex_num = 0;
2386
0
    for (int n = 0; n < 4; n++) {
2387
0
        switch (img[n].type) {
2388
0
        case PLANE_RGB:
2389
0
        case PLANE_XYZ:
2390
0
        case PLANE_LUMA: break;
2391
0
        default: continue;
2392
0
        }
2393
2394
0
        reference_tex_num = n;
2395
0
        break;
2396
0
    }
2397
2398
    // Dispatch the hooks for all of these textures, saving and perhaps
2399
    // modifying them in the process
2400
0
    for (int n = 0; n < 4; n++) {
2401
0
        const char *name;
2402
0
        switch (img[n].type) {
2403
0
        case PLANE_RGB:    name = "RGB";    break;
2404
0
        case PLANE_LUMA:   name = "LUMA";   break;
2405
0
        case PLANE_CHROMA: name = "CHROMA"; break;
2406
0
        case PLANE_ALPHA:  name = "ALPHA";  break;
2407
0
        case PLANE_XYZ:    name = "XYZ";    break;
2408
0
        default: continue;
2409
0
        }
2410
2411
0
        img[n] = pass_hook(p, name, img[n], &offsets[n], img[n].components);
2412
2413
0
        if (reference_tex_num == n) {
2414
            // The reference texture is finalized now.
2415
0
            p->texture_w = img[n].w;
2416
0
            p->texture_h = img[n].h;
2417
0
            p->texture_offset = offsets[n];
2418
0
        }
2419
0
    }
2420
2421
    // If chroma textures are in a subsampled semi-planar format and rotated,
2422
    // introduce an explicit conversion pass to avoid breaking chroma scalers.
2423
0
    for (int n = 0; n < 4; n++) {
2424
0
        if (img[n].tex && img[n].type == PLANE_CHROMA &&
2425
0
            img[n].tex->params.format->num_components == 2 &&
2426
0
            p->image_params.rotate % 180 == 90 &&
2427
0
            p->ra_format.chroma_w != 1)
2428
0
        {
2429
0
            GLSLF("// chroma fix for rotated plane %d\n", n);
2430
0
            copy_image(p, &(int){0}, img[n]);
2431
0
            pass_describe(p, "chroma fix for rotated plane");
2432
0
            finish_pass_tex(p, &p->chroma_tex[n], img[n].w, img[n].h);
2433
0
            img[n] = image_wrap(p->chroma_tex[n], img[n].type,
2434
0
                                img[n].components);
2435
0
        }
2436
0
    }
2437
2438
    // At this point all planes are finalized but they may not be at the
2439
    // required size yet. Furthermore, they may have texture offsets that
2440
    // require realignment.
2441
2442
    // Compute the reference rect
2443
0
    struct mp_rect_f src = {0.0, 0.0, p->image_params.w, p->image_params.h};
2444
0
    struct mp_rect_f ref = src;
2445
0
    gl_transform_rect(p->texture_offset, &ref);
2446
2447
    // Explicitly scale all of the textures that don't match
2448
0
    for (int n = 0; n < 4; n++) {
2449
0
        if (img[n].type == PLANE_NONE)
2450
0
            continue;
2451
2452
        // If the planes are aligned identically, we will end up with the
2453
        // exact same source rectangle.
2454
0
        struct mp_rect_f rect = src;
2455
0
        gl_transform_rect(offsets[n], &rect);
2456
0
        if (mp_rect_f_seq(ref, rect))
2457
0
            continue;
2458
2459
        // If the rectangles differ, then our planes have a different
2460
        // alignment and/or size. First of all, we have to compute the
2461
        // corrections required to meet the target rectangle
2462
0
        struct gl_transform fix = {
2463
0
            .m = {{(ref.x1 - ref.x0) / (rect.x1 - rect.x0), 0.0},
2464
0
                  {0.0, (ref.y1 - ref.y0) / (rect.y1 - rect.y0)}},
2465
0
            .t = {ref.x0, ref.y0},
2466
0
        };
2467
2468
        // Since the scale in texture space is different from the scale in
2469
        // absolute terms, we have to scale the coefficients down to be
2470
        // relative to the texture's physical dimensions and local offset
2471
0
        struct gl_transform scale = {
2472
0
            .m = {{(float)img[n].w / p->texture_w, 0.0},
2473
0
                  {0.0, (float)img[n].h / p->texture_h}},
2474
0
            .t = {-rect.x0, -rect.y0},
2475
0
        };
2476
0
        if (p->image_params.rotate % 180 == 90)
2477
0
            MPSWAP(double, scale.m[0][0], scale.m[1][1]);
2478
2479
0
        gl_transform_trans(scale, &fix);
2480
2481
        // Since the texture transform is a function of the texture coordinates
2482
        // to texture space, rather than the other way around, we have to
2483
        // actually apply the *inverse* of this. Fortunately, calculating
2484
        // the inverse is relatively easy here.
2485
0
        fix.m[0][0] = 1.0 / fix.m[0][0];
2486
0
        fix.m[1][1] = 1.0 / fix.m[1][1];
2487
0
        fix.t[0] = fix.m[0][0] * -fix.t[0];
2488
0
        fix.t[1] = fix.m[1][1] * -fix.t[1];
2489
0
        gl_transform_trans(fix, &img[n].transform);
2490
2491
0
        int scaler_id = -1;
2492
0
        const char *name = NULL;
2493
0
        switch (img[n].type) {
2494
0
        case PLANE_RGB:
2495
0
        case PLANE_LUMA:
2496
0
        case PLANE_XYZ:
2497
0
            scaler_id = SCALER_SCALE;
2498
            // these aren't worth hooking, fringe hypothetical cases only
2499
0
            break;
2500
0
        case PLANE_CHROMA:
2501
0
            scaler_id = SCALER_CSCALE;
2502
0
            name = "CHROMA_SCALED";
2503
0
            break;
2504
0
        case PLANE_ALPHA:
2505
            // alpha always uses bilinear
2506
0
            name = "ALPHA_SCALED";
2507
0
        }
2508
2509
0
        if (scaler_id < 0)
2510
0
            continue;
2511
2512
0
        const struct scaler_config *conf = &p->opts.scaler[scaler_id];
2513
0
        struct scaler_config tmp;
2514
0
        if (conf->kernel.function == SCALER_INHERIT) {
2515
0
            tmp = *conf;
2516
0
            scaler_conf_merge(&tmp, &p->opts.scaler[SCALER_SCALE], scaler_id);
2517
0
            conf = &tmp;
2518
0
        }
2519
2520
0
        struct scaler *scaler = &p->scaler[scaler_id];
2521
2522
        // bilinear scaling is a free no-op thanks to GPU sampling
2523
0
        if (conf->kernel.function != SCALER_BILINEAR) {
2524
0
            GLSLF("// upscaling plane %d\n", n);
2525
0
            pass_sample(p, img[n], scaler, conf, 1.0, p->texture_w, p->texture_h);
2526
0
            finish_pass_tex(p, &p->scale_tex[n], p->texture_w, p->texture_h);
2527
0
            img[n] = image_wrap(p->scale_tex[n], img[n].type, img[n].components);
2528
0
        }
2529
2530
        // Run any post-scaling hooks
2531
0
        img[n] = pass_hook(p, name, img[n], NULL, img[n].components);
2532
0
    }
2533
2534
    // All planes are of the same size and properly aligned at this point
2535
0
    pass_describe(p, "combining planes");
2536
0
    int coord = 0;
2537
0
    for (int i = 0; i < 4; i++) {
2538
0
        if (img[i].type != PLANE_NONE)
2539
0
            copy_image(p, &coord, img[i]);
2540
0
    }
2541
0
    p->components = coord;
2542
0
}
2543
2544
// Utility function that simply binds a texture and reads from it, without any
2545
// transformations.
2546
static void pass_read_tex(struct gl_video *p, struct ra_tex *tex)
2547
0
{
2548
0
    struct image img = image_wrap(tex, PLANE_RGB, p->components);
2549
0
    copy_image(p, &(int){0}, img);
2550
0
}
2551
2552
// yuv conversion, and any other conversions before main up/down-scaling
2553
static void pass_convert_yuv(struct gl_video *p)
2554
0
{
2555
0
    struct gl_shader_cache *sc = p->sc;
2556
2557
0
    struct mp_csp_params cparams = MP_CSP_PARAMS_DEFAULTS;
2558
0
    cparams.gray = p->is_gray;
2559
0
    cparams.is_float = p->ra_format.component_type == RA_CTYPE_FLOAT;
2560
0
    mp_csp_set_image_params(&cparams, &p->image_params);
2561
0
    mp_csp_equalizer_state_get(p->video_eq, &cparams);
2562
0
    p->user_gamma = 1.0 / (cparams.gamma * p->opts.gamma);
2563
2564
0
    pass_describe(p, "color conversion");
2565
2566
0
    if (p->color_swizzle[0])
2567
0
        GLSLF("color = color.%s;\n", p->color_swizzle);
2568
2569
    // Pre-colormatrix input gamma correction
2570
0
    if (cparams.repr.sys == PL_COLOR_SYSTEM_XYZ)
2571
0
        pass_linearize(p->sc, p->image_params.color.transfer);
2572
2573
    // We always explicitly normalize the range in pass_read_video
2574
0
    cparams.input_bits = cparams.texture_bits = 0;
2575
2576
    // Conversion to RGB. For RGB itself, this still applies e.g. brightness
2577
    // and contrast controls, or expansion of e.g. LSB-packed 10 bit data.
2578
0
    struct pl_transform3x3 m = {0};
2579
0
    mp_get_csp_matrix(&cparams, &m);
2580
0
    gl_sc_uniform_mat3(sc, "colormatrix", true, &m.mat.m[0][0]);
2581
0
    gl_sc_uniform_vec3(sc, "colormatrix_c", m.c);
2582
2583
0
    GLSL(color.rgb = mat3(colormatrix) * color.rgb + colormatrix_c;)
2584
2585
0
    if (cparams.repr.sys == PL_COLOR_SYSTEM_XYZ)
2586
0
        pass_delinearize(p->sc, p->image_params.color.transfer);
2587
2588
0
    if (p->image_params.repr.sys == PL_COLOR_SYSTEM_BT_2020_C) {
2589
        // Conversion for C'rcY'cC'bc via the BT.2020 CL system:
2590
        // C'bc = (B'-Y'c) / (2 Nb)  | C'bc <= 0
2591
        //      = (B'-Y'c) / (2 Pb)  | C'bc >  0
2592
        //
2593
        // C'rc = (R'-Y'c) / (2 Nr)  | C'rc <= 0
2594
        //      = (R'-Y'c) / (2 Pr)  | C'rc >  0
2595
        //
2596
        // with Nb = OETF(1 - Kb), Pb = 1 - OETF(Kb), Nr = OETF(1 - Kr) and
2597
        // Pr = 1 - OETF(Kr), as per the BT.2020-2 specification, table 4.
2598
        // This is a non-linear transformation because (constant) luminance
2599
        // receives non-equal contributions from the three different channels.
2600
0
        GLSLF("// constant luminance conversion \n"
2601
0
              "color.br = color.br * mix(vec2(1.5819708492989484, 0.99382959526841756), \n"
2602
0
              "                         vec2(1.9403433056341009, 1.7182419845671139),  \n"
2603
0
              "                         %s(lessThanEqual(color.br, vec2(0))))           \n"
2604
0
              "          + color.gg;                                                   \n",
2605
0
              gl_sc_bvec(p->sc, 2));
2606
        // Expand channels to camera-linear light, through the BT.2020 gamma
2607
        // function with the exact alpha and beta of BT.2020-2, which its 10
2608
        // and 12-bit values approximate
2609
0
        GLSLF("color.rgb = mix(color.rgb * vec3(1.0/4.5),                                             \n"
2610
0
              "                pow((color.rgb + vec3(0.09929682680944294))*vec3(1.0/1.0992968268094429), \n"
2611
0
              "                    vec3(1.0/0.45)),                                                   \n"
2612
0
              "                %s(lessThanEqual(vec3(0.081242858298635133), color.rgb)));            \n",
2613
0
              gl_sc_bvec(p->sc, 3));
2614
        // Calculate the green channel from the expanded RYcB
2615
        // The BT.2020 specification says Yc = 0.2627*R + 0.6780*G + 0.0593*B
2616
0
        GLSL(color.g = (color.g - 0.2627*color.r - 0.0593*color.b)*1.0/0.6780;)
2617
        // Recompress to receive the R'G'B' result, same as other systems
2618
0
        GLSLF("color.rgb = mix(color.rgb * vec3(4.5),                                     \n"
2619
0
              "                vec3(1.0992968268094429) * pow(color.rgb, vec3(0.45))      \n"
2620
0
              "                    - vec3(0.09929682680944294),                           \n"
2621
0
              "                %s(lessThanEqual(vec3(0.018053968510807807), color.rgb))); \n",
2622
0
              gl_sc_bvec(p->sc, 3));
2623
0
    }
2624
2625
0
    p->components = 3;
2626
0
    if (!p->has_alpha) {
2627
0
        GLSL(color.a = 1.0;)
2628
0
    } else if (p->image_params.repr.alpha == PL_ALPHA_PREMULTIPLIED) {
2629
0
        p->components = 4;
2630
0
    } else {
2631
0
        p->components = 4;
2632
0
        GLSL(color = vec4(color.rgb * color.a, color.a);) // straight -> premul
2633
0
    }
2634
0
}
2635
2636
static void get_scale_factors(struct gl_video *p, bool transpose_rot, double xy[2])
2637
0
{
2638
0
    double target_w = p->src_rect.x1 - p->src_rect.x0;
2639
0
    double target_h = p->src_rect.y1 - p->src_rect.y0;
2640
0
    if (transpose_rot && p->image_params.rotate % 180 == 90)
2641
0
        MPSWAP(double, target_w, target_h);
2642
0
    xy[0] = (p->dst_rect.x1 - p->dst_rect.x0) / target_w;
2643
0
    xy[1] = (p->dst_rect.y1 - p->dst_rect.y0) / target_h;
2644
0
}
2645
2646
// Cropping.
2647
static void compute_src_transform(struct gl_video *p, struct gl_transform *tr)
2648
0
{
2649
0
    float sx = (p->src_rect.x1 - p->src_rect.x0) / (float)p->texture_w,
2650
0
          sy = (p->src_rect.y1 - p->src_rect.y0) / (float)p->texture_h,
2651
0
          ox = p->src_rect.x0,
2652
0
          oy = p->src_rect.y0;
2653
0
    struct gl_transform transform = {{{sx, 0}, {0, sy}}, {ox, oy}};
2654
2655
0
    gl_transform_trans(p->texture_offset, &transform);
2656
2657
0
    *tr = transform;
2658
0
}
2659
2660
// Takes care of the main scaling and pre/post-conversions
2661
static void pass_scale_main(struct gl_video *p)
2662
0
{
2663
    // Figure out the main scaler.
2664
0
    double xy[2];
2665
0
    get_scale_factors(p, true, xy);
2666
2667
    // actual scale factor should be divided by the scale factor of prescaling.
2668
0
    xy[0] /= p->texture_offset.m[0][0];
2669
0
    xy[1] /= p->texture_offset.m[1][1];
2670
2671
    // The calculation of scale factor involves 32-bit float(from gl_transform),
2672
    // use non-strict equality test to tolerate precision loss.
2673
0
    bool downscaling = xy[0] < 1.0 - FLT_EPSILON || xy[1] < 1.0 - FLT_EPSILON;
2674
0
    bool upscaling = !downscaling && (xy[0] > 1.0 + FLT_EPSILON ||
2675
0
                                      xy[1] > 1.0 + FLT_EPSILON);
2676
0
    double scale_factor = 1.0;
2677
2678
0
    struct scaler *scaler = &p->scaler[SCALER_SCALE];
2679
0
    struct scaler_config scaler_conf = p->opts.scaler[SCALER_SCALE];
2680
0
    if (p->opts.scaler_resizes_only && !downscaling && !upscaling) {
2681
0
        scaler_conf.kernel.function = SCALER_BILINEAR;
2682
        // For scaler-resizes-only, we round the texture offset to
2683
        // the nearest round value in order to prevent ugly blurriness
2684
        // (in exchange for slightly shifting the image by up to half a
2685
        // subpixel)
2686
0
        p->texture_offset.t[0] = roundf(p->texture_offset.t[0]);
2687
0
        p->texture_offset.t[1] = roundf(p->texture_offset.t[1]);
2688
0
    }
2689
0
    if (downscaling) {
2690
0
        scaler_conf = p->opts.scaler[SCALER_DSCALE];
2691
0
        scaler = &p->scaler[SCALER_DSCALE];
2692
0
        scaler_conf_merge(&scaler_conf, &p->opts.scaler[SCALER_SCALE], SCALER_DSCALE);
2693
0
    }
2694
2695
    // When requesting correct-downscaling and the clip is anamorphic, and
2696
    // because only a single scale factor is used for both axes, enable it only
2697
    // when both axes are downscaled, and use the milder of the factors to not
2698
    // end up with too much blur on one axis (even if we end up with sub-optimal
2699
    // scale factor on the other axis). This is better than not respecting
2700
    // correct scaling at all for anamorphic clips.
2701
0
    double f = MPMAX(xy[0], xy[1]);
2702
0
    if (p->opts.correct_downscaling && f < 1.0)
2703
0
        scale_factor = 1.0 / f;
2704
2705
    // Pre-conversion, like linear light/sigmoidization
2706
0
    GLSLF("// scaler pre-conversion\n");
2707
0
    bool use_linear = false;
2708
0
    if (downscaling) {
2709
0
        use_linear = p->opts.linear_downscaling;
2710
2711
        // Linear light downscaling results in nasty artifacts for HDR curves
2712
        // due to the potentially extreme brightness differences severely
2713
        // compounding any ringing. So just scale in gamma light instead.
2714
0
        if (pl_color_space_is_hdr(&p->image_params.color))
2715
0
            use_linear = false;
2716
0
    } else if (upscaling) {
2717
0
        use_linear = p->opts.linear_upscaling || p->opts.sigmoid_upscaling;
2718
0
    }
2719
2720
0
    if (use_linear) {
2721
0
        p->use_linear = true;
2722
0
        pass_linearize(p->sc, p->image_params.color.transfer);
2723
0
        pass_opt_hook_point(p, "LINEAR", NULL);
2724
0
    }
2725
2726
0
    bool use_sigmoid = use_linear && p->opts.sigmoid_upscaling && upscaling;
2727
0
    float sig_center, sig_slope, sig_offset, sig_scale;
2728
0
    if (use_sigmoid) {
2729
        // Coefficients for the sigmoidal transform are taken from the
2730
        // formula here: http://www.imagemagick.org/Usage/color_mods/#sigmoidal
2731
0
        sig_center = p->opts.sigmoid_center;
2732
0
        sig_slope  = p->opts.sigmoid_slope;
2733
        // This function needs to go through (0,0) and (1,1) so we compute the
2734
        // values at 1 and 0, and then scale/shift them, respectively.
2735
0
        sig_offset = 1.0/(1+expf(sig_slope * sig_center));
2736
0
        sig_scale  = 1.0/(1+expf(sig_slope * (sig_center-1))) - sig_offset;
2737
0
        GLSL(color.rgb = clamp(color.rgb, 0.0, 1.0);)
2738
0
        GLSLF("color.rgb = %f - log(1.0/(color.rgb * %f + %f) - 1.0) * 1.0/%f;\n",
2739
0
                sig_center, sig_scale, sig_offset, sig_slope);
2740
0
        pass_opt_hook_point(p, "SIGMOID", NULL);
2741
0
    }
2742
2743
0
    pass_opt_hook_point(p, "PREKERNEL", NULL);
2744
2745
0
    int vp_w = p->dst_rect.x1 - p->dst_rect.x0;
2746
0
    int vp_h = p->dst_rect.y1 - p->dst_rect.y0;
2747
0
    struct gl_transform transform;
2748
0
    compute_src_transform(p, &transform);
2749
2750
0
    GLSLF("// main scaling\n");
2751
0
    finish_pass_tex(p, &p->indirect_tex, p->texture_w, p->texture_h);
2752
0
    struct image src = image_wrap(p->indirect_tex, PLANE_RGB, p->components);
2753
0
    gl_transform_trans(transform, &src.transform);
2754
0
    pass_sample(p, src, scaler, &scaler_conf, scale_factor, vp_w, vp_h);
2755
2756
    // Changes the texture size to display size after main scaler.
2757
0
    p->texture_w = vp_w;
2758
0
    p->texture_h = vp_h;
2759
2760
0
    pass_opt_hook_point(p, "POSTKERNEL", NULL);
2761
2762
0
    GLSLF("// scaler post-conversion\n");
2763
0
    if (use_sigmoid) {
2764
        // Inverse of the transformation above
2765
0
        GLSL(color.rgb = clamp(color.rgb, 0.0, 1.0);)
2766
0
        GLSLF("color.rgb = (1.0/(1.0 + exp(%f * (%f - color.rgb))) - %f) * 1.0/%f;\n",
2767
0
                sig_slope, sig_center, sig_offset, sig_scale);
2768
0
    }
2769
0
}
2770
2771
// Adapts the colors to the right output color space. (Final pass during
2772
// rendering)
2773
// If OSD is true, ignore any changes that may have been made to the video
2774
// by previous passes (i.e. linear scaling)
2775
static void pass_colormanage(struct gl_video *p, struct pl_color_space src,
2776
                             enum mp_csp_light src_light,
2777
                             const struct pl_color_space *fbo_csp, int flags, bool osd)
2778
0
{
2779
0
    struct ra *ra = p->ra;
2780
2781
    // Configure the destination according to the FBO color space,
2782
    // unless specific transfer function, primaries or target peak
2783
    // is set. If values are set to _AUTO, the most likely intended
2784
    // values are guesstimated later in this function.
2785
0
    struct pl_color_space dst = {
2786
0
        .transfer = p->opts.target_trc == PL_COLOR_TRC_UNKNOWN ?
2787
0
                        fbo_csp->transfer : p->opts.target_trc,
2788
0
        .primaries = p->opts.target_prim == PL_COLOR_PRIM_UNKNOWN ?
2789
0
                     fbo_csp->primaries : p->opts.target_prim,
2790
0
        .hdr.max_luma = !p->opts.target_peak ?
2791
0
                        fbo_csp->hdr.max_luma : p->opts.target_peak,
2792
0
    };
2793
2794
0
    if (!p->colorspace_override_warned &&
2795
0
        ((fbo_csp->transfer && dst.transfer != fbo_csp->transfer) ||
2796
0
         (fbo_csp->primaries && dst.primaries != fbo_csp->primaries)))
2797
0
    {
2798
0
        MP_WARN(p, "One or more colorspace value is being overridden "
2799
0
                   "by user while the FBO provides colorspace information: "
2800
0
                   "transfer function: (dst: %s, fbo: %s), "
2801
0
                   "primaries: (dst: %s, fbo: %s). "
2802
0
                   "Rendering can lead to incorrect results!\n",
2803
0
                m_opt_choice_str(pl_csp_trc_names,  dst.transfer),
2804
0
                m_opt_choice_str(pl_csp_trc_names,  fbo_csp->transfer),
2805
0
                m_opt_choice_str(pl_csp_prim_names, dst.primaries),
2806
0
                m_opt_choice_str(pl_csp_prim_names, fbo_csp->primaries));
2807
0
        p->colorspace_override_warned = true;
2808
0
    }
2809
2810
0
    enum mp_csp_light dst_light = dst.transfer == PL_COLOR_TRC_HLG ?
2811
0
                                    MP_CSP_LIGHT_SCENE_HLG : MP_CSP_LIGHT_DISPLAY;
2812
2813
0
    if (p->use_lut_3d && (flags & RENDER_SCREEN_COLOR)) {
2814
        // The 3DLUT is always generated against the video's original source
2815
        // space, *not* the reference space. (To avoid having to regenerate
2816
        // the 3DLUT for the OSD on every frame)
2817
0
        enum pl_color_primaries prim_orig = p->image_params.color.primaries;
2818
0
        enum pl_color_transfer trc_orig = p->image_params.color.transfer;
2819
2820
        // One exception: HDR is not implemented by LittleCMS for technical
2821
        // limitation reasons, so we use a gamma 2.2 input curve here instead.
2822
        // We could pick any value we want here, the difference is just coding
2823
        // efficiency.
2824
0
        if (pl_color_space_is_hdr(&p->image_params.color))
2825
0
            trc_orig = PL_COLOR_TRC_GAMMA22;
2826
2827
0
        if (gl_video_get_lut3d(p, prim_orig, trc_orig)) {
2828
0
            dst.primaries = prim_orig;
2829
0
            dst.transfer = trc_orig;
2830
0
            mp_assert(dst.primaries && dst.transfer);
2831
0
        }
2832
0
    }
2833
2834
0
    if (dst.primaries == PL_COLOR_PRIM_UNKNOWN) {
2835
        // The vast majority of people are on sRGB or BT.709 displays, so pick
2836
        // this as the default output color space.
2837
0
        dst.primaries = PL_COLOR_PRIM_BT_709;
2838
2839
0
        if (src.primaries == PL_COLOR_PRIM_BT_601_525 ||
2840
0
            src.primaries == PL_COLOR_PRIM_BT_601_625)
2841
0
        {
2842
            // Since we auto-pick BT.601 and BT.709 based on the dimensions,
2843
            // combined with the fact that they're very similar to begin with,
2844
            // and to avoid confusing the average user, just don't adapt BT.601
2845
            // content automatically at all.
2846
0
            dst.primaries = src.primaries;
2847
0
        }
2848
0
    }
2849
2850
0
    if (dst.transfer == PL_COLOR_TRC_UNKNOWN) {
2851
        // Most people seem to complain when the image is darker or brighter
2852
        // than what they're "used to", so just avoid changing the gamma
2853
        // altogether by default. The only exceptions to this rule apply to
2854
        // very unusual TRCs, which even hardcode technoluddites would probably
2855
        // not enjoy viewing unaltered.
2856
0
        dst.transfer = src.transfer;
2857
2858
        // Avoid outputting linear light or HDR content "by default". For these
2859
        // just pick gamma 2.2 as a default, since it's a good estimate for
2860
        // the response of typical displays
2861
0
        if (dst.transfer == PL_COLOR_TRC_LINEAR || pl_color_space_is_hdr(&dst))
2862
0
            dst.transfer = PL_COLOR_TRC_GAMMA22;
2863
0
    }
2864
2865
    // If there's no specific signal peak known for the output display, infer
2866
    // it from the chosen transfer function. Also normalize the src peak, in
2867
    // case it was unknown
2868
0
    if (!dst.hdr.max_luma)
2869
0
        dst.hdr.max_luma = pl_color_transfer_nominal_peak(dst.transfer) * MP_REF_WHITE;
2870
0
    if (!src.hdr.max_luma)
2871
0
        src.hdr.max_luma = pl_color_transfer_nominal_peak(src.transfer) * MP_REF_WHITE;
2872
2873
    // Whitelist supported modes
2874
0
    switch (p->opts.tone_map.curve) {
2875
0
    case TONE_MAPPING_AUTO:
2876
0
    case TONE_MAPPING_CLIP:
2877
0
    case TONE_MAPPING_MOBIUS:
2878
0
    case TONE_MAPPING_REINHARD:
2879
0
    case TONE_MAPPING_HABLE:
2880
0
    case TONE_MAPPING_GAMMA:
2881
0
    case TONE_MAPPING_LINEAR:
2882
0
    case TONE_MAPPING_BT_2390:
2883
0
        break;
2884
0
    default:
2885
0
        MP_WARN(p, "Tone mapping curve unsupported by vo_gpu, falling back.\n");
2886
0
        p->opts.tone_map.curve = TONE_MAPPING_AUTO;
2887
0
        break;
2888
0
    }
2889
2890
0
    switch (p->opts.tone_map.gamut_mode) {
2891
0
    case GAMUT_AUTO:
2892
0
    case GAMUT_WARN:
2893
0
    case GAMUT_CLIP:
2894
0
    case GAMUT_DESATURATE:
2895
0
        break;
2896
0
    default:
2897
0
        MP_WARN(p, "Gamut mapping mode unsupported by vo_gpu, falling back.\n");
2898
0
        p->opts.tone_map.gamut_mode = GAMUT_AUTO;
2899
0
        break;
2900
0
    }
2901
2902
0
    struct gl_tone_map_opts tone_map = p->opts.tone_map;
2903
0
    bool detect_peak = tone_map.compute_peak >= 0 && pl_color_space_is_hdr(&src)
2904
0
                       && src.hdr.max_luma > dst.hdr.max_luma;
2905
2906
0
    if (detect_peak && !p->hdr_peak_ssbo) {
2907
0
        struct {
2908
0
            float average[2];
2909
0
            int32_t frame_sum;
2910
0
            uint32_t frame_max;
2911
0
            uint32_t counter;
2912
0
        } peak_ssbo = {0};
2913
2914
0
        struct ra_buf_params params = {
2915
0
            .type = RA_BUF_TYPE_SHADER_STORAGE,
2916
0
            .size = sizeof(peak_ssbo),
2917
0
            .initial_data = &peak_ssbo,
2918
0
        };
2919
2920
0
        p->hdr_peak_ssbo = ra_buf_create(ra, &params);
2921
0
        if (!p->hdr_peak_ssbo) {
2922
0
            MP_WARN(p, "Failed to create HDR peak detection SSBO, disabling.\n");
2923
0
            tone_map.compute_peak = p->opts.tone_map.compute_peak = -1;
2924
0
            detect_peak = false;
2925
0
        }
2926
0
    }
2927
2928
0
    if (detect_peak) {
2929
0
        pass_describe(p, "detect HDR peak");
2930
0
        pass_is_compute(p, 8, 8, true); // 8x8 is good for performance
2931
0
        gl_sc_ssbo(p->sc, "PeakDetect", p->hdr_peak_ssbo,
2932
0
            "vec2 average;"
2933
0
            "int frame_sum;"
2934
0
            "uint frame_max;"
2935
0
            "uint counter;"
2936
0
        );
2937
0
    } else {
2938
0
        tone_map.compute_peak = -1;
2939
0
    }
2940
2941
    // Adapt from src to dst as necessary
2942
0
    pass_color_map(p->sc, p->use_linear && !osd, &src, &dst, src_light, dst_light, &tone_map);
2943
2944
0
    if (!osd) {
2945
0
        struct mp_csp_params cparams = MP_CSP_PARAMS_DEFAULTS;
2946
0
        mp_csp_equalizer_state_get(p->video_eq, &cparams);
2947
0
        if (cparams.levels_out == PL_COLOR_LEVELS_UNKNOWN)
2948
0
            cparams.levels_out = PL_COLOR_LEVELS_FULL;
2949
0
        p->target_params = (struct mp_image_params){
2950
0
            .imgfmt_name = p->fbo_format ? p->fbo_format->name : "unknown",
2951
0
            .w = mp_rect_w(p->dst_rect),
2952
0
            .h = mp_rect_h(p->dst_rect),
2953
0
            .color = dst,
2954
0
            .repr = {.sys = PL_COLOR_SYSTEM_RGB, .levels = cparams.levels_out},
2955
0
            .rotate = p->image_params.rotate,
2956
0
        };
2957
0
    }
2958
2959
0
    if (p->use_lut_3d && (flags & RENDER_SCREEN_COLOR)) {
2960
0
        gl_sc_uniform_texture(p->sc, "lut_3d", p->lut_3d_texture);
2961
0
        GLSL(vec3 cpos;)
2962
0
        for (int i = 0; i < 3; i++)
2963
0
            GLSLF("cpos[%d] = LUT_POS(color[%d], %d.0);\n", i, i, p->lut_3d_size[i]);
2964
0
        GLSL(color.rgb = tex3D(lut_3d, cpos).rgb;)
2965
0
    }
2966
0
}
2967
2968
void gl_video_set_fb_depth(struct gl_video *p, int fb_depth)
2969
0
{
2970
0
    p->fb_depth = fb_depth;
2971
0
}
2972
2973
static void pass_dither(struct gl_video *p, const struct ra_fbo *fbo)
2974
0
{
2975
    // Assume 8 bits per component if unknown.
2976
0
    int dst_depth = p->fb_depth > 0 ? p->fb_depth : 8;
2977
0
    if (p->opts.dither_depth > 0)
2978
0
        dst_depth = p->opts.dither_depth;
2979
2980
0
    if (p->opts.dither_depth < 0 || p->opts.dither_algo == DITHER_NONE)
2981
0
        return;
2982
2983
0
    if (p->opts.dither_algo == DITHER_ERROR_DIFFUSION) {
2984
0
        const struct error_diffusion_kernel *kernel =
2985
0
            mp_find_error_diffusion_kernel(p->opts.error_diffusion);
2986
0
        int o_w = p->dst_rect.x1 - p->dst_rect.x0,
2987
0
            o_h = p->dst_rect.y1 - p->dst_rect.y0;
2988
2989
0
        int shmem_req = mp_ef_compute_shared_memory_size(kernel, o_h);
2990
0
        if (shmem_req > p->ra->max_shmem) {
2991
0
            MP_WARN(p, "Fallback to dither=fruit because there is no enough "
2992
0
                       "shared memory (%d/%d).\n",
2993
0
                       shmem_req, (int)p->ra->max_shmem);
2994
0
            p->opts.dither_algo = DITHER_FRUIT;
2995
0
        } else {
2996
0
            finish_pass_tex(p, &p->error_diffusion_tex[0], o_w, o_h);
2997
2998
0
            struct image img = image_wrap(p->error_diffusion_tex[0], PLANE_RGB, p->components);
2999
3000
            // Ensure the block size doesn't exceed the maximum of the
3001
            // implementation.
3002
0
            int block_size = MPMIN(p->ra->max_compute_group_threads, o_h);
3003
3004
0
            pass_describe(p, "dither=error-diffusion (kernel=%s, depth=%d)",
3005
0
                             kernel->name, dst_depth);
3006
3007
0
            p->pass_compute = (struct compute_info) {
3008
0
                .active = true,
3009
0
                .threads_w = block_size,
3010
0
                .threads_h = 1,
3011
0
                .directly_writes = true
3012
0
            };
3013
3014
0
            int tex_id = pass_bind(p, img);
3015
3016
0
            pass_error_diffusion(p->sc, kernel, tex_id, o_w, o_h,
3017
0
                                 dst_depth, block_size);
3018
3019
0
            finish_pass_tex(p, &p->error_diffusion_tex[1], o_w, o_h);
3020
3021
0
            img = image_wrap(p->error_diffusion_tex[1], PLANE_RGB, p->components);
3022
0
            copy_image(p, &(int){0}, img);
3023
3024
0
            return;
3025
0
        }
3026
0
    }
3027
3028
0
    if (!p->dither_texture) {
3029
0
        MP_VERBOSE(p, "Dither to %d.\n", dst_depth);
3030
3031
0
        int tex_size = 0;
3032
0
        void *tex_data = NULL;
3033
0
        const struct ra_format *fmt = NULL;
3034
0
        void *temp = NULL;
3035
3036
0
        if (p->opts.dither_algo == DITHER_FRUIT) {
3037
0
            int sizeb = p->opts.dither_size;
3038
0
            int size = 1 << sizeb;
3039
3040
0
            if (p->last_dither_matrix_size != size) {
3041
0
                p->last_dither_matrix = talloc_realloc(p, p->last_dither_matrix,
3042
0
                                                       float, size * size);
3043
0
                mp_make_fruit_dither_matrix(p->last_dither_matrix, sizeb);
3044
0
                p->last_dither_matrix_size = size;
3045
0
            }
3046
3047
            // Prefer R16 texture since they provide higher precision.
3048
0
            fmt = ra_find_unorm_format(p->ra, 2, 1);
3049
0
            if (!fmt)
3050
0
                fmt = ra_find_float16_format(p->ra, 1);
3051
0
            if (fmt) {
3052
0
                tex_size = size;
3053
0
                tex_data = p->last_dither_matrix;
3054
0
                if (fmt->ctype == RA_CTYPE_UNORM) {
3055
0
                    uint16_t *t = temp = talloc_array(NULL, uint16_t, size * size);
3056
0
                    for (int n = 0; n < size * size; n++)
3057
0
                        t[n] = p->last_dither_matrix[n] * UINT16_MAX;
3058
0
                    tex_data = t;
3059
0
                }
3060
0
            } else {
3061
0
                MP_VERBOSE(p, "GL too old. Falling back to ordered dither.\n");
3062
0
                p->opts.dither_algo = DITHER_ORDERED;
3063
0
            }
3064
0
        }
3065
3066
0
        if (p->opts.dither_algo == DITHER_ORDERED) {
3067
0
            temp = talloc_array(NULL, char, 8 * 8);
3068
0
            mp_make_ordered_dither_matrix(temp, 8);
3069
3070
0
            fmt = ra_find_unorm_format(p->ra, 1, 1);
3071
0
            tex_size = 8;
3072
0
            tex_data = temp;
3073
0
        }
3074
3075
0
        struct ra_tex_params params = {
3076
0
            .dimensions = 2,
3077
0
            .w = tex_size,
3078
0
            .h = tex_size,
3079
0
            .d = 1,
3080
0
            .format = fmt,
3081
0
            .render_src = true,
3082
0
            .src_repeat = true,
3083
0
            .initial_data = tex_data,
3084
0
        };
3085
0
        p->dither_texture = ra_tex_create(p->ra, &params);
3086
3087
0
        debug_check_gl(p, "dither setup");
3088
3089
0
        talloc_free(temp);
3090
3091
0
        if (!p->dither_texture)
3092
0
            return;
3093
0
    }
3094
3095
0
    GLSLF("// dithering\n");
3096
3097
    // This defines how many bits are considered significant for output on
3098
    // screen. The superfluous bits will be used for rounding according to the
3099
    // dither matrix. The precision of the source implicitly decides how many
3100
    // dither patterns can be visible.
3101
0
    uint32_t dither_quantization = UINT32_MAX >> (32 - dst_depth);
3102
0
    int dither_size = p->dither_texture->params.w;
3103
3104
0
    gl_sc_uniform_texture(p->sc, "dither", p->dither_texture);
3105
3106
0
    GLSLF("vec2 dither_coord = vec2(gl_FragCoord.x, %d.0 + %f * gl_FragCoord.y);",
3107
0
          fbo->flip ? fbo->tex->params.h : 0, fbo->flip ? -1.0 : 1.0);
3108
0
    GLSLF("vec2 dither_pos = dither_coord * 1.0/%d.0;\n", dither_size);
3109
3110
0
    if (p->opts.temporal_dither) {
3111
0
        int phase = (p->frames_rendered / p->opts.temporal_dither_period) % 8u;
3112
0
        float r = phase * (M_PI / 2); // rotate
3113
0
        float m = phase < 4 ? 1 : -1; // mirror
3114
3115
0
        float matrix[2][2] = {{cos(r),     -sin(r)    },
3116
0
                              {sin(r) * m,  cos(r) * m}};
3117
0
        gl_sc_uniform_dynamic(p->sc);
3118
0
        gl_sc_uniform_mat2(p->sc, "dither_trafo", true, &matrix[0][0]);
3119
3120
0
        GLSL(dither_pos = dither_trafo * dither_pos;)
3121
0
    }
3122
3123
0
    GLSL(float dither_value = texture(dither, dither_pos).r;)
3124
0
    GLSLF("color = floor(color * %" PRIu32 ".0 + dither_value + 0.5 / %d.0) * "
3125
0
          "1.0/%" PRIu32 ".0;\n",
3126
0
          dither_quantization, dither_size * dither_size, dither_quantization);
3127
0
}
3128
3129
// Draws the OSD, in scene-referred colors.. If cms is true, subtitles are
3130
// instead adapted to the display's gamut.
3131
static void pass_draw_osd(struct gl_video *p, int osd_flags, int frame_flags,
3132
                          double pts, struct mp_osd_res rect, const struct ra_fbo *fbo,
3133
                          bool cms)
3134
0
{
3135
0
    if (frame_flags & RENDER_FRAME_VF_SUBS)
3136
0
        osd_flags |= OSD_DRAW_SUB_FILTER;
3137
3138
0
    if ((osd_flags & OSD_DRAW_SUB_ONLY) && (osd_flags & OSD_DRAW_OSD_ONLY))
3139
0
        return;
3140
3141
0
    mpgl_osd_generate(p->osd, rect, pts, p->image_params.stereo3d, osd_flags);
3142
3143
0
    timer_pool_start(p->osd_timer);
3144
0
    for (int n = 0; n < MAX_OSD_PARTS; n++) {
3145
        // (This returns false if this part is empty with nothing to draw.)
3146
0
        if (!mpgl_osd_draw_prepare(p->osd, n, p->sc))
3147
0
            continue;
3148
        // When subtitles need to be color managed, assume they're in sRGB
3149
        // (for lack of anything saner to do)
3150
0
        if (cms) {
3151
0
            pass_colormanage(p, pl_color_space_srgb, MP_CSP_LIGHT_DISPLAY,
3152
0
                             &fbo->color_space, frame_flags, true);
3153
0
        }
3154
0
        mpgl_osd_draw_finish(p->osd, n, p->sc, fbo);
3155
0
    }
3156
3157
0
    timer_pool_stop(p->osd_timer);
3158
0
    pass_describe(p, "drawing osd");
3159
0
    struct mp_pass_perf perf = timer_pool_measure(p->osd_timer);
3160
0
    pass_record(p, &perf);
3161
0
}
3162
3163
static float chroma_realign(int size, int pixel)
3164
0
{
3165
0
    return size / (float)chroma_upsize(size, pixel);
3166
0
}
3167
3168
// Minimal rendering code path, for GLES or OpenGL 2.1 without proper FBOs.
3169
static void pass_render_frame_dumb(struct gl_video *p)
3170
0
{
3171
0
    struct image img[4];
3172
0
    struct gl_transform off[4];
3173
0
    pass_get_images(p, &p->image, img, off);
3174
3175
0
    struct gl_transform transform;
3176
0
    compute_src_transform(p, &transform);
3177
3178
0
    int index = 0;
3179
0
    for (int i = 0; i < p->plane_count; i++) {
3180
0
        int cw = img[i].type == PLANE_CHROMA ? p->ra_format.chroma_w : 1;
3181
0
        int ch = img[i].type == PLANE_CHROMA ? p->ra_format.chroma_h : 1;
3182
0
        if (p->image_params.rotate % 180 == 90)
3183
0
            MPSWAP(int, cw, ch);
3184
3185
0
        struct gl_transform t = transform;
3186
0
        t.m[0][0] *= chroma_realign(p->texture_w, cw);
3187
0
        t.m[1][1] *= chroma_realign(p->texture_h, ch);
3188
3189
0
        t.t[0] /= cw;
3190
0
        t.t[1] /= ch;
3191
3192
0
        t.t[0] += off[i].t[0];
3193
0
        t.t[1] += off[i].t[1];
3194
3195
0
        gl_transform_trans(img[i].transform, &t);
3196
0
        img[i].transform = t;
3197
3198
0
        copy_image(p, &index, img[i]);
3199
0
    }
3200
3201
0
    pass_convert_yuv(p);
3202
0
}
3203
3204
// The main rendering function, takes care of everything up to and including
3205
// upscaling. p->image is rendered.
3206
// flags: bit set of RENDER_FRAME_* flags
3207
static bool pass_render_frame(struct gl_video *p, struct mp_image *mpi,
3208
                              uint64_t id, int flags)
3209
0
{
3210
    // initialize the texture parameters and temporary variables
3211
0
    p->texture_w = p->image_params.w;
3212
0
    p->texture_h = p->image_params.h;
3213
0
    p->texture_offset = identity_trans;
3214
0
    p->components = 0;
3215
0
    p->num_saved_imgs = 0;
3216
0
    p->idx_hook_textures = 0;
3217
0
    p->use_linear = false;
3218
3219
    // try uploading the frame
3220
0
    if (!pass_upload_image(p, mpi, id))
3221
0
        return false;
3222
3223
0
    if (p->image_params.rotate % 180 == 90)
3224
0
        MPSWAP(int, p->texture_w, p->texture_h);
3225
3226
0
    if (p->dumb_mode)
3227
0
        return true;
3228
3229
0
    pass_read_video(p);
3230
0
    pass_opt_hook_point(p, "NATIVE", &p->texture_offset);
3231
0
    pass_convert_yuv(p);
3232
0
    pass_opt_hook_point(p, "MAINPRESUB", &p->texture_offset);
3233
3234
    // For subtitles
3235
0
    double vpts = p->image.mpi->pts;
3236
0
    if (vpts == MP_NOPTS_VALUE)
3237
0
        vpts = p->osd_pts;
3238
3239
0
    if (p->osd && p->opts.blend_subs == BLEND_SUBS_VIDEO &&
3240
0
        (flags & RENDER_FRAME_SUBS))
3241
0
    {
3242
0
        double scale[2];
3243
0
        get_scale_factors(p, false, scale);
3244
0
        struct mp_osd_res rect = {
3245
0
            .w = p->texture_w, .h = p->texture_h,
3246
0
            .display_par = scale[1] / scale[0], // counter compensate scaling
3247
0
        };
3248
0
        finish_pass_tex(p, &p->blend_subs_tex, rect.w, rect.h);
3249
0
        struct ra_fbo fbo = { p->blend_subs_tex };
3250
0
        pass_draw_osd(p, OSD_DRAW_SUB_ONLY, flags, vpts, rect, &fbo, false);
3251
0
        pass_read_tex(p, p->blend_subs_tex);
3252
0
        pass_describe(p, "blend subs video");
3253
0
    }
3254
0
    pass_opt_hook_point(p, "MAIN", &p->texture_offset);
3255
3256
0
    pass_scale_main(p);
3257
3258
0
    int vp_w = p->dst_rect.x1 - p->dst_rect.x0,
3259
0
        vp_h = p->dst_rect.y1 - p->dst_rect.y0;
3260
0
    if (p->osd && p->opts.blend_subs == BLEND_SUBS_YES &&
3261
0
        (flags & RENDER_FRAME_SUBS))
3262
0
    {
3263
        // Recreate the real video size from the src/dst rects
3264
0
        struct mp_osd_res rect = {
3265
0
            .w = vp_w, .h = vp_h,
3266
0
            .ml = -p->src_rect.x0, .mr = p->src_rect.x1 - p->image_params.w,
3267
0
            .mt = -p->src_rect.y0, .mb = p->src_rect.y1 - p->image_params.h,
3268
0
            .display_par = 1.0,
3269
0
        };
3270
        // Adjust margins for scale
3271
0
        double scale[2];
3272
0
        get_scale_factors(p, true, scale);
3273
0
        rect.ml *= scale[0]; rect.mr *= scale[0];
3274
0
        rect.mt *= scale[1]; rect.mb *= scale[1];
3275
        // We should always blend subtitles in non-linear light
3276
0
        if (p->use_linear) {
3277
0
            pass_delinearize(p->sc, p->image_params.color.transfer);
3278
0
            p->use_linear = false;
3279
0
        }
3280
0
        finish_pass_tex(p, &p->blend_subs_tex, p->texture_w, p->texture_h);
3281
0
        struct ra_fbo fbo = { p->blend_subs_tex };
3282
0
        pass_draw_osd(p, OSD_DRAW_SUB_ONLY, flags, vpts, rect, &fbo, false);
3283
0
        pass_read_tex(p, p->blend_subs_tex);
3284
0
        pass_describe(p, "blend subs");
3285
0
    }
3286
3287
0
    pass_opt_hook_point(p, "SCALED", NULL);
3288
3289
0
    return true;
3290
0
}
3291
3292
static void pass_draw_to_screen(struct gl_video *p, const struct ra_fbo *fbo, int flags)
3293
0
{
3294
0
    if (p->dumb_mode)
3295
0
        pass_render_frame_dumb(p);
3296
3297
    // Adjust the overall gamma before drawing to screen
3298
0
    if (p->user_gamma != 1) {
3299
0
        gl_sc_uniform_f(p->sc, "user_gamma", p->user_gamma);
3300
0
        GLSL(color.rgb = clamp(color.rgb, 0.0, 1.0);)
3301
0
        GLSL(color.rgb = pow(color.rgb, vec3(user_gamma));)
3302
0
    }
3303
3304
0
    pass_colormanage(p, p->image_params.color, p->image_params.light,
3305
0
                     &fbo->color_space, flags, false);
3306
3307
    // Since finish_pass_fbo doesn't work with compute shaders, and neither
3308
    // does the checkerboard/dither code, we may need an indirection via
3309
    // p->screen_tex here.
3310
0
    if (p->pass_compute.active) {
3311
0
        int o_w = p->dst_rect.x1 - p->dst_rect.x0,
3312
0
            o_h = p->dst_rect.y1 - p->dst_rect.y0;
3313
0
        finish_pass_tex(p, &p->screen_tex, o_w, o_h);
3314
0
        struct image tmp = image_wrap(p->screen_tex, PLANE_RGB, p->components);
3315
0
        copy_image(p, &(int){0}, tmp);
3316
0
    }
3317
3318
0
    if (p->has_alpha) {
3319
0
        if (p->opts.background == BACKGROUND_TILES) {
3320
            // Draw checkerboard pattern to indicate transparency
3321
0
            struct m_color *c = p->opts.background_tile_color;
3322
0
            GLSLF("// transparency checkerboard\n");
3323
0
            GLSLF("vec2 tile_coord = vec2(gl_FragCoord.x, %d.0 + %f * gl_FragCoord.y);\n",
3324
0
                  fbo->flip ? fbo->tex->params.h : 0, fbo->flip ? -1.0 : 1.0);
3325
0
            GLSLF("bvec2 tile = lessThan(fract(tile_coord * 1.0 / %d.0), vec2(0.5));\n",
3326
0
                  p->opts.background_tile_size * 2);
3327
0
            GLSLF("vec3 background = tile.x == tile.y ? vec3(%f, %f, %f) : vec3(%f, %f, %f);\n",
3328
0
                  c[0].r / 255.0, c[0].g / 255.0, c[0].b / 255.0,
3329
0
                  c[1].r / 255.0, c[1].g / 255.0, c[1].b / 255.0);
3330
0
            GLSL(color.rgb += background.rgb * (1.0 - color.a);)
3331
0
            GLSL(color.a = 1.0;)
3332
0
        } else if (p->opts.background == BACKGROUND_COLOR) {
3333
            // Blend into background color (usually black)
3334
0
            struct m_color c = p->opts.background_color;
3335
0
            GLSLF("vec4 background = vec4(%f, %f, %f, %f);\n",
3336
0
                  c.r / 255.0, c.g / 255.0, c.b / 255.0, c.a / 255.0);
3337
0
            GLSL(color += background * (1.0 - color.a);)
3338
0
            GLSL(color.rgb *= vec3(color.a););
3339
0
        }
3340
0
    }
3341
3342
0
    pass_opt_hook_point(p, "OUTPUT", NULL);
3343
3344
0
    if (flags & RENDER_SCREEN_COLOR)
3345
0
        pass_dither(p, fbo);
3346
0
    pass_describe(p, "output to screen");
3347
0
    finish_pass_fbo(p, fbo, false, &p->dst_rect);
3348
0
}
3349
3350
// flags: bit set of RENDER_FRAME_* flags
3351
static bool update_surface(struct gl_video *p, struct mp_image *mpi,
3352
                           uint64_t id, struct surface *surf, int flags)
3353
0
{
3354
0
    int vp_w = p->dst_rect.x1 - p->dst_rect.x0,
3355
0
        vp_h = p->dst_rect.y1 - p->dst_rect.y0;
3356
3357
0
    pass_info_reset(p, false);
3358
0
    if (!pass_render_frame(p, mpi, id, flags))
3359
0
        return false;
3360
3361
    // Frame blending should always be done in linear light to preserve the
3362
    // overall brightness, otherwise this will result in flashing dark frames
3363
    // because mixing in compressed light artificially darkens the results
3364
0
    if (!p->use_linear) {
3365
0
        p->use_linear = true;
3366
0
        pass_linearize(p->sc, p->image_params.color.transfer);
3367
0
    }
3368
3369
0
    finish_pass_tex(p, &surf->tex, vp_w, vp_h);
3370
0
    surf->id  = id;
3371
0
    surf->pts = mpi->pts;
3372
0
    return true;
3373
0
}
3374
3375
// Draws an interpolate frame to fbo, based on the frame timing in t
3376
// flags: bit set of RENDER_FRAME_* flags
3377
static void gl_video_interpolate_frame(struct gl_video *p, struct vo_frame *t,
3378
                                       const struct ra_fbo *fbo, int flags)
3379
0
{
3380
0
    bool is_new = false;
3381
3382
    // Reset the queue completely if this is a still image, to avoid any
3383
    // interpolation artifacts from surrounding frames when unpausing or
3384
    // framestepping
3385
0
    if (t->still)
3386
0
        gl_video_reset_surfaces(p);
3387
3388
    // First of all, figure out if we have a frame available at all, and draw
3389
    // it manually + reset the queue if not
3390
0
    if (p->surfaces[p->surface_now].id == 0) {
3391
0
        struct surface *now = &p->surfaces[p->surface_now];
3392
0
        if (!update_surface(p, t->current, t->frame_id, now, flags))
3393
0
            return;
3394
0
        p->surface_idx = p->surface_now;
3395
0
        is_new = true;
3396
0
    }
3397
3398
    // Find the right frame for this instant
3399
0
    if (t->current) {
3400
0
        int next = surface_wrap(p->surface_now + 1);
3401
0
        while (p->surfaces[next].id &&
3402
0
               p->surfaces[next].id > p->surfaces[p->surface_now].id &&
3403
0
               p->surfaces[p->surface_now].id < t->frame_id)
3404
0
        {
3405
0
            p->surface_now = next;
3406
0
            next = surface_wrap(next + 1);
3407
0
        }
3408
0
    }
3409
3410
    // Figure out the queue size. For illustration, a filter radius of 2 would
3411
    // look like this: _ A [B] C D _
3412
    // A is surface_bse, B is surface_now, C is surface_now+1 and D is
3413
    // surface_end.
3414
0
    struct scaler *tscale = &p->scaler[SCALER_TSCALE];
3415
0
    reinit_scaler(p, tscale, &p->opts.scaler[SCALER_TSCALE], 1, tscale_sizes);
3416
0
    bool oversample = tscale->conf.kernel.function == SCALER_OVERSAMPLE;
3417
0
    bool linear = tscale->conf.kernel.function == SCALER_LINEAR;
3418
0
    int size;
3419
3420
0
    if (oversample || linear) {
3421
0
        size = 2;
3422
0
    } else {
3423
0
        mp_assert(tscale->kernel && !tscale->kernel->polar);
3424
0
        size = ceil(tscale->kernel->size);
3425
0
    }
3426
3427
0
    int radius = size/2;
3428
0
    int surface_now = p->surface_now;
3429
0
    int surface_bse = surface_wrap(surface_now - (radius-1));
3430
0
    int surface_end = surface_wrap(surface_now + radius);
3431
0
    mp_assert(surface_wrap(surface_bse + size-1) == surface_end);
3432
3433
    // Render new frames while there's room in the queue. Note that technically,
3434
    // this should be done before the step where we find the right frame, but
3435
    // it only barely matters at the very beginning of playback, and this way
3436
    // makes the code much more linear.
3437
0
    int surface_dst = surface_wrap(p->surface_idx + 1);
3438
0
    for (int i = 0; i < t->num_frames; i++) {
3439
        // Avoid overwriting data we might still need
3440
0
        if (surface_dst == surface_bse - 1)
3441
0
            break;
3442
3443
0
        struct mp_image *f = t->frames[i];
3444
0
        uint64_t f_id = t->frame_id + i;
3445
0
        if (!mp_image_params_static_equal(&f->params, &p->real_image_params))
3446
0
            continue;
3447
3448
0
        if (f_id > p->surfaces[p->surface_idx].id) {
3449
0
            struct surface *dst = &p->surfaces[surface_dst];
3450
0
            if (!update_surface(p, f, f_id, dst, flags))
3451
0
                return;
3452
0
            p->surface_idx = surface_dst;
3453
0
            surface_dst = surface_wrap(surface_dst + 1);
3454
0
            is_new = true;
3455
0
        }
3456
0
    }
3457
3458
    // Figure out whether the queue is "valid". A queue is invalid if the
3459
    // frames' PTS is not monotonically increasing. Anything else is invalid,
3460
    // so avoid blending incorrect data and just draw the latest frame as-is.
3461
    // Possible causes for failure of this condition include seeks, pausing,
3462
    // end of playback or start of playback.
3463
0
    bool valid = true;
3464
0
    for (int i = surface_bse, ii; valid && i != surface_end; i = ii) {
3465
0
        ii = surface_wrap(i + 1);
3466
0
        if (p->surfaces[i].id == 0 || p->surfaces[ii].id == 0) {
3467
0
            valid = false;
3468
0
        } else if (p->surfaces[ii].id < p->surfaces[i].id) {
3469
0
            valid = false;
3470
0
            MP_DBG(p, "interpolation queue underrun\n");
3471
0
        }
3472
0
    }
3473
3474
    // Update OSD PTS to synchronize subtitles with the displayed frame
3475
0
    p->osd_pts = p->surfaces[surface_now].pts;
3476
3477
    // Finally, draw the right mix of frames to the screen.
3478
0
    if (!is_new)
3479
0
        pass_info_reset(p, true);
3480
0
    pass_describe(p, "interpolation");
3481
0
    if (!valid || t->still) {
3482
        // surface_now is guaranteed to be valid, so we can safely use it.
3483
0
        pass_read_tex(p, p->surfaces[surface_now].tex);
3484
0
        p->is_interpolated = false;
3485
0
    } else {
3486
0
        double mix = t->vsync_offset / t->ideal_frame_duration;
3487
        // The scaler code always wants the fcoord to be between 0 and 1,
3488
        // so we try to adjust by using the previous set of N frames instead
3489
        // (which requires some extra checking to make sure it's valid)
3490
0
        if (mix < 0.0) {
3491
0
            int prev = surface_wrap(surface_bse - 1);
3492
0
            if (p->surfaces[prev].id != 0 &&
3493
0
                p->surfaces[prev].id < p->surfaces[surface_bse].id)
3494
0
            {
3495
0
                mix += 1.0;
3496
0
                surface_bse = prev;
3497
0
            } else {
3498
0
                mix = 0.0; // at least don't blow up, this should only
3499
                           // ever happen at the start of playback
3500
0
            }
3501
0
        }
3502
3503
0
        if (oversample) {
3504
            // Oversample uses the frame area as mix ratio, not the vsync
3505
            // position itself
3506
0
            double vsync_dist = t->vsync_interval / t->ideal_frame_duration,
3507
0
                   threshold = tscale->conf.kernel.params[0];
3508
0
            threshold = isnan(threshold) ? 0.0 : threshold;
3509
0
            mix = (1 - mix) / vsync_dist;
3510
0
            mix = mix <= 0 + threshold ? 0 : mix;
3511
0
            mix = mix >= 1 - threshold ? 1 : mix;
3512
0
            mix = 1 - mix;
3513
0
        }
3514
3515
        // Blend the frames together
3516
0
        if (oversample || linear) {
3517
0
            gl_sc_uniform_dynamic(p->sc);
3518
0
            gl_sc_uniform_f(p->sc, "inter_coeff", mix);
3519
0
            GLSL(color = mix(texture(texture0, texcoord0),
3520
0
                             texture(texture1, texcoord1),
3521
0
                             inter_coeff);)
3522
0
        } else {
3523
0
            gl_sc_uniform_dynamic(p->sc);
3524
0
            gl_sc_uniform_f(p->sc, "fcoord", mix);
3525
0
            pass_sample_separated_gen(p->sc, tscale, 0, 0);
3526
0
        }
3527
3528
        // Load all the required frames
3529
0
        for (int i = 0; i < size; i++) {
3530
0
            struct image img =
3531
0
                image_wrap(p->surfaces[surface_wrap(surface_bse+i)].tex,
3532
0
                           PLANE_RGB, p->components);
3533
            // Since the code in pass_sample_separated currently assumes
3534
            // the textures are bound in-order and starting at 0, we just
3535
            // assert to make sure this is the case (which it should always be)
3536
0
            int id = pass_bind(p, img);
3537
0
            mp_assert(id == i);
3538
0
        }
3539
3540
0
        MP_TRACE(p, "inter frame dur: %f vsync: %f, mix: %f\n",
3541
0
                 t->ideal_frame_duration, t->vsync_interval, mix);
3542
0
        p->is_interpolated = true;
3543
0
    }
3544
0
    pass_draw_to_screen(p, fbo, flags);
3545
3546
0
    p->frames_drawn += 1;
3547
0
}
3548
3549
void gl_video_render_frame(struct gl_video *p, struct vo_frame *frame,
3550
                           const struct ra_fbo *fbo, int flags)
3551
0
{
3552
0
    gl_video_update_options(p);
3553
3554
0
    struct mp_rect target_rc = {0, 0, fbo->tex->params.w, fbo->tex->params.h};
3555
3556
0
    p->broken_frame = false;
3557
3558
0
    bool has_frame = !!frame->current;
3559
3560
0
    struct m_color c = p->clear_color;
3561
0
    float clear_color[4] = {c.r / 255.0, c.g / 255.0, c.b / 255.0, c.a / 255.0};
3562
0
    clear_color[0] *= clear_color[3];
3563
0
    clear_color[1] *= clear_color[3];
3564
0
    clear_color[2] *= clear_color[3];
3565
0
    p->ra->fns->clear(p->ra, fbo->tex, clear_color, &target_rc);
3566
3567
0
    if (p->hwdec_overlay) {
3568
0
        if (has_frame) {
3569
0
            float *color = p->hwdec_overlay->overlay_colorkey;
3570
0
            p->ra->fns->clear(p->ra, fbo->tex, color, &p->dst_rect);
3571
0
        }
3572
3573
0
        p->hwdec_overlay->driver->overlay_frame(p->hwdec_overlay, frame->current,
3574
0
                                                &p->src_rect, &p->dst_rect,
3575
0
                                                frame->frame_id != p->image.id);
3576
3577
0
        if (frame->current)
3578
0
            p->osd_pts = frame->current->pts;
3579
3580
        // Disable GL rendering
3581
0
        has_frame = false;
3582
0
    }
3583
3584
0
    if (has_frame) {
3585
0
        bool interpolate = p->opts.interpolation && frame->display_synced &&
3586
0
                           (p->frames_drawn || !frame->still);
3587
0
        if (interpolate) {
3588
0
            double ratio = frame->ideal_frame_duration / frame->vsync_interval;
3589
0
            if (fabs(ratio - 1.0) < p->opts.interpolation_threshold)
3590
0
                interpolate = false;
3591
0
        }
3592
3593
0
        if (interpolate) {
3594
0
            gl_video_interpolate_frame(p, frame, fbo, flags);
3595
0
        } else {
3596
0
            bool is_new = frame->frame_id != p->image.id;
3597
3598
            // Redrawing a frame might update subtitles.
3599
0
            if (frame->still && p->opts.blend_subs)
3600
0
                is_new = true;
3601
3602
0
            if (is_new || !p->output_tex_valid) {
3603
0
                p->output_tex_valid = false;
3604
3605
0
                pass_info_reset(p, !is_new);
3606
0
                if (!pass_render_frame(p, frame->current, frame->frame_id, flags))
3607
0
                    goto done;
3608
3609
                // For the non-interpolation case, we draw to a single "cache"
3610
                // texture to speed up subsequent re-draws (if any exist)
3611
0
                bool repeats = frame->num_vsyncs > 1 && frame->display_synced;
3612
0
                bool r = false;
3613
0
                if ((repeats || frame->still) && !p->dumb_mode &&
3614
0
                    (p->ra->caps & RA_CAP_BLIT) && fbo->tex->params.blit_dst)
3615
0
                {
3616
                    // Attempt to use the same format as the destination FBO
3617
                    // if possible. Some RAs use a wrapped dummy format here,
3618
                    // so fall back to the fbo_format in that case.
3619
0
                    const struct ra_format *fmt = fbo->tex->params.format;
3620
0
                    if (fmt->dummy_format)
3621
0
                        fmt = p->fbo_format;
3622
0
                    r = ra_tex_resize(p->ra, p->log, &p->output_tex,
3623
0
                                      fbo->tex->params.w, fbo->tex->params.h,
3624
0
                                      fmt);
3625
0
                }
3626
0
                const struct ra_fbo *dest_fbo =
3627
0
                    r ? &(struct ra_fbo) { .tex = p->output_tex, .color_space = fbo->color_space } : fbo;
3628
0
                p->output_tex_valid = r;
3629
0
                pass_draw_to_screen(p, dest_fbo, flags);
3630
0
            }
3631
3632
            // "output tex valid" and "output tex needed" are equivalent
3633
0
            if (p->output_tex_valid && fbo->tex->params.blit_dst) {
3634
0
                pass_info_reset(p, true);
3635
0
                pass_describe(p, "redraw cached frame");
3636
0
                struct mp_rect src = p->dst_rect;
3637
0
                struct mp_rect dst = src;
3638
0
                if (fbo->flip) {
3639
0
                    dst.y0 = fbo->tex->params.h - src.y0;
3640
0
                    dst.y1 = fbo->tex->params.h - src.y1;
3641
0
                }
3642
0
                timer_pool_start(p->blit_timer);
3643
0
                p->ra->fns->blit(p->ra, fbo->tex, p->output_tex, &dst, &src);
3644
0
                timer_pool_stop(p->blit_timer);
3645
0
                struct mp_pass_perf perf = timer_pool_measure(p->blit_timer);
3646
0
                pass_record(p, &perf);
3647
0
            }
3648
0
        }
3649
0
    }
3650
3651
0
done:
3652
3653
0
    debug_check_gl(p, "after video rendering");
3654
3655
0
    if (p->osd && (flags & (RENDER_FRAME_SUBS | RENDER_FRAME_OSD))) {
3656
        // If we haven't actually drawn anything so far, then we technically
3657
        // need to consider this the start of a new pass. Let's call it a
3658
        // redraw just because, since it's basically a blank frame anyway
3659
0
        if (!has_frame)
3660
0
            pass_info_reset(p, true);
3661
3662
0
        int osd_flags = p->opts.blend_subs ? OSD_DRAW_OSD_ONLY : 0;
3663
0
        if (!(flags & RENDER_FRAME_SUBS))
3664
0
            osd_flags |= OSD_DRAW_OSD_ONLY;
3665
0
        if (!(flags & RENDER_FRAME_OSD))
3666
0
            osd_flags |= OSD_DRAW_SUB_ONLY;
3667
3668
0
        pass_draw_osd(p, osd_flags, flags, p->osd_pts, p->osd_rect, fbo, true);
3669
0
        debug_check_gl(p, "after OSD rendering");
3670
0
    }
3671
3672
0
    p->broken_frame |= gl_sc_error_state(p->sc);
3673
0
    if (p->broken_frame) {
3674
        // Make the screen solid blue to make it visually clear that an
3675
        // error has occurred
3676
0
        float color[4] = {0.0, 0.05, 0.5, 1.0};
3677
0
        p->ra->fns->clear(p->ra, fbo->tex, color, &target_rc);
3678
0
    }
3679
3680
0
    p->frames_rendered++;
3681
0
    pass_report_performance(p);
3682
0
}
3683
3684
void gl_video_screenshot(struct gl_video *p, struct vo_frame *frame,
3685
                         struct voctrl_screenshot *args)
3686
0
{
3687
0
    if (!p->ra->fns->tex_download)
3688
0
        return;
3689
3690
0
    bool ok = false;
3691
0
    struct mp_image *res = NULL;
3692
0
    struct ra_tex *target = NULL;
3693
0
    struct mp_rect old_src = p->src_rect;
3694
0
    struct mp_rect old_dst = p->dst_rect;
3695
0
    struct mp_osd_res old_osd = p->osd_rect;
3696
0
    struct vo_frame *nframe = vo_frame_ref(frame);
3697
3698
    // Disable interpolation and such.
3699
0
    nframe->redraw = true;
3700
0
    nframe->repeat = false;
3701
0
    nframe->still = true;
3702
0
    nframe->pts = 0;
3703
0
    nframe->duration = -1;
3704
3705
0
    if (!args->scaled) {
3706
0
        int w, h;
3707
0
        mp_image_params_get_dsize(&p->image_params, &w, &h);
3708
0
        if (w < 1 || h < 1)
3709
0
            return;
3710
3711
0
        int src_w = p->image_params.w;
3712
0
        int src_h = p->image_params.h;
3713
0
        struct mp_rect src = {0, 0, src_w, src_h};
3714
0
        struct mp_rect dst = {0, 0, w, h};
3715
3716
0
        if (mp_image_crop_valid(&p->image_params))
3717
0
            src = p->image_params.crop;
3718
3719
0
        if (p->image_params.rotate % 180 == 90) {
3720
0
            MPSWAP(int, w, h);
3721
0
            MPSWAP(int, src_w, src_h);
3722
0
        }
3723
0
        mp_rect_rotate(&src, src_w, src_h, p->image_params.rotate);
3724
0
        mp_rect_rotate(&dst, w, h, p->image_params.rotate);
3725
3726
0
        struct mp_osd_res osd = {
3727
0
            .display_par = 1.0,
3728
0
            .w = mp_rect_w(dst),
3729
0
            .h = mp_rect_h(dst),
3730
0
        };
3731
0
        gl_video_resize(p, &src, &dst, &osd);
3732
0
    }
3733
3734
0
    gl_video_reset_surfaces(p);
3735
3736
0
    struct ra_tex_params params = {
3737
0
        .dimensions = 2,
3738
0
        .downloadable = true,
3739
0
        .w = p->osd_rect.w,
3740
0
        .h = p->osd_rect.h,
3741
0
        .d = 1,
3742
0
        .render_dst = true,
3743
0
    };
3744
3745
0
    params.format = ra_find_unorm_format(p->ra, 1, 4);
3746
0
    int mpfmt = p->has_alpha ? IMGFMT_RGBA : IMGFMT_RGB0;
3747
0
    if (args->high_bit_depth && p->ra_format.component_bits > 8) {
3748
0
        const struct ra_format *fmt = ra_find_unorm_format(p->ra, 2, 4);
3749
0
        if (fmt && fmt->renderable) {
3750
0
            params.format = fmt;
3751
0
            mpfmt = IMGFMT_RGBA64;
3752
0
        }
3753
0
    }
3754
3755
0
    if (!params.format || !params.format->renderable)
3756
0
        goto done;
3757
0
    target = ra_tex_create(p->ra, &params);
3758
0
    if (!target)
3759
0
        goto done;
3760
3761
0
    int flags = 0;
3762
0
    if (args->subs)
3763
0
        flags |= RENDER_FRAME_SUBS;
3764
0
    if (args->osd)
3765
0
        flags |= RENDER_FRAME_OSD;
3766
0
    if (args->scaled)
3767
0
        flags |= RENDER_SCREEN_COLOR;
3768
0
    gl_video_render_frame(p, nframe, &(struct ra_fbo){target}, flags);
3769
3770
0
    res = mp_image_alloc(mpfmt, params.w, params.h);
3771
0
    if (!res)
3772
0
        goto done;
3773
3774
0
    struct ra_tex_download_params download_params = {
3775
0
        .tex = target,
3776
0
        .dst = res->planes[0],
3777
0
        .stride = res->stride[0],
3778
0
    };
3779
0
    if (!p->ra->fns->tex_download(p->ra, &download_params))
3780
0
        goto done;
3781
3782
0
    if (p->broken_frame)
3783
0
        goto done;
3784
3785
0
    ok = true;
3786
0
done:
3787
0
    talloc_free(nframe);
3788
0
    ra_tex_free(p->ra, &target);
3789
0
    gl_video_resize(p, &old_src, &old_dst, &old_osd);
3790
0
    gl_video_reset_surfaces(p);
3791
0
    if (!ok)
3792
0
        TA_FREEP(&res);
3793
0
    args->res = res;
3794
0
}
3795
3796
// Use this color instead of the global option.
3797
void gl_video_set_clear_color(struct gl_video *p, struct m_color c)
3798
0
{
3799
0
    p->force_clear_color = true;
3800
0
    p->clear_color = c;
3801
0
}
3802
3803
void gl_video_set_osd_pts(struct gl_video *p, double pts)
3804
0
{
3805
0
    p->osd_pts = pts;
3806
0
}
3807
3808
void gl_video_resize(struct gl_video *p,
3809
                     struct mp_rect *src, struct mp_rect *dst,
3810
                     struct mp_osd_res *osd)
3811
0
{
3812
0
    if (mp_rect_equals(&p->src_rect, src) &&
3813
0
        mp_rect_equals(&p->dst_rect, dst) &&
3814
0
        osd_res_equals(p->osd_rect, *osd))
3815
0
        return;
3816
3817
0
    p->src_rect = *src;
3818
0
    p->dst_rect = *dst;
3819
0
    p->osd_rect = *osd;
3820
3821
0
    gl_video_reset_surfaces(p);
3822
3823
0
    if (p->osd)
3824
0
        mpgl_osd_resize(p->osd, p->osd_rect, p->image_params.stereo3d);
3825
0
}
3826
3827
static void frame_perf_data(struct pass_info pass[], struct mp_frame_perf *out)
3828
0
{
3829
0
    for (int i = 0; i < VO_PASS_PERF_MAX; i++) {
3830
0
        if (!pass[i].desc.len)
3831
0
            break;
3832
0
        out->perf[out->count] = pass[i].perf;
3833
0
        strncpy(out->desc[out->count], pass[i].desc.start,
3834
0
                sizeof(out->desc[out->count]) - 1);
3835
0
        out->desc[out->count][sizeof(out->desc[out->count]) - 1] = '\0';
3836
0
        out->count++;
3837
0
    }
3838
0
}
3839
3840
void gl_video_perfdata(struct gl_video *p, struct voctrl_performance_data *out)
3841
0
{
3842
0
    *out = (struct voctrl_performance_data){0};
3843
0
    frame_perf_data(p->pass_fresh,  &out->fresh);
3844
0
    frame_perf_data(p->pass_redraw, &out->redraw);
3845
0
}
3846
3847
// Returns false on failure.
3848
static bool pass_upload_image(struct gl_video *p, struct mp_image *mpi, uint64_t id)
3849
0
{
3850
0
    struct video_image *vimg = &p->image;
3851
3852
0
    if (vimg->id == id)
3853
0
        return true;
3854
3855
0
    unref_current_image(p);
3856
3857
0
    mpi = mp_image_new_ref(mpi);
3858
0
    if (!mpi)
3859
0
        goto error;
3860
3861
0
    vimg->mpi = mpi;
3862
0
    vimg->id = id;
3863
0
    p->osd_pts = mpi->pts;
3864
0
    p->frames_uploaded++;
3865
3866
0
    if (p->hwdec_active) {
3867
        // Hardware decoding
3868
3869
0
        if (!p->hwdec_mapper)
3870
0
            goto error;
3871
3872
0
        pass_describe(p, "map frame (hwdec)");
3873
0
        timer_pool_start(p->upload_timer);
3874
0
        bool ok = ra_hwdec_mapper_map(p->hwdec_mapper, vimg->mpi) >= 0;
3875
0
        vimg->hwdec_mapped = ok;
3876
        // The frame stays mapped and in use until it is replaced.
3877
0
        if (ok)
3878
0
            ok = ra_hwdec_mapper_begin_access(p->hwdec_mapper) >= 0;
3879
0
        timer_pool_stop(p->upload_timer);
3880
0
        struct mp_pass_perf perf = timer_pool_measure(p->upload_timer);
3881
0
        pass_record(p, &perf);
3882
3883
0
        if (ok) {
3884
0
            struct ra_tex **tex = p->hwdec_mapper->tex;
3885
0
            for (int n = 0; n < p->plane_count; n++) {
3886
0
                vimg->planes[n] = (struct texplane){
3887
0
                    .w = tex[n]->params.w,
3888
0
                    .h = tex[n]->params.h,
3889
0
                    .tex = tex[n],
3890
0
                    .flipped = p->image_params.vflip,
3891
0
                };
3892
0
            }
3893
0
        } else {
3894
0
            MP_FATAL(p, "Mapping hardware decoded surface failed.\n");
3895
0
            goto error;
3896
0
        }
3897
0
        return true;
3898
0
    }
3899
3900
    // Software decoding
3901
0
    mp_assert(mpi->num_planes == p->plane_count);
3902
3903
0
    timer_pool_start(p->upload_timer);
3904
3905
0
    if (mpi->params.vflip)
3906
0
        mp_image_vflip(mpi);
3907
3908
0
    for (int n = 0; n < p->plane_count; n++) {
3909
0
        struct texplane *plane = &vimg->planes[n];
3910
0
        if (!plane->tex) {
3911
0
            timer_pool_stop(p->upload_timer);
3912
0
            goto error;
3913
0
        }
3914
3915
0
        struct ra_tex_upload_params params = {
3916
0
            .tex = plane->tex,
3917
0
            .src = mpi->planes[n],
3918
0
            .invalidate = true,
3919
0
            .stride = mpi->stride[n],
3920
0
        };
3921
3922
0
        plane->flipped = params.stride < 0;
3923
0
        if (plane->flipped) {
3924
0
            int h = mp_image_plane_h(mpi, n);
3925
0
            params.src = (char *)params.src + (h - 1) * params.stride;
3926
0
            params.stride = -params.stride;
3927
0
        }
3928
3929
0
        struct dr_buffer *mapped = gl_find_dr_buffer(p, mpi->planes[n]);
3930
0
        if (mapped) {
3931
0
            params.buf = mapped->buf;
3932
0
            params.buf_offset = (uintptr_t)params.src -
3933
0
                                (uintptr_t)mapped->buf->data;
3934
0
            params.src = NULL;
3935
0
        }
3936
3937
0
        if (p->using_dr_path != !!mapped) {
3938
0
            p->using_dr_path = !!mapped;
3939
0
            MP_VERBOSE(p, "DR enabled: %s\n", p->using_dr_path ? "yes" : "no");
3940
0
        }
3941
3942
0
        if (!p->ra->fns->tex_upload(p->ra, &params)) {
3943
0
            timer_pool_stop(p->upload_timer);
3944
0
            goto error;
3945
0
        }
3946
3947
0
        if (mapped && !mapped->mpi)
3948
0
            mapped->mpi = mp_image_new_ref(mpi);
3949
0
    }
3950
0
    timer_pool_stop(p->upload_timer);
3951
3952
0
    bool using_pbo = p->ra->use_pbo || !(p->ra->caps & RA_CAP_DIRECT_UPLOAD);
3953
0
    const char *mode = p->using_dr_path ? "DR" : using_pbo ? "PBO" : "naive";
3954
0
    pass_describe(p, "upload frame (%s)", mode);
3955
0
    struct mp_pass_perf perf = timer_pool_measure(p->upload_timer);
3956
0
    pass_record(p, &perf);
3957
3958
0
    return true;
3959
3960
0
error:
3961
0
    unref_current_image(p);
3962
0
    p->broken_frame = true;
3963
0
    return false;
3964
0
}
3965
3966
static bool test_fbo(struct gl_video *p, const struct ra_format *fmt)
3967
0
{
3968
0
    MP_VERBOSE(p, "Testing FBO format %s\n", fmt->name);
3969
0
    struct ra_tex *tex = NULL;
3970
0
    bool success = ra_tex_resize(p->ra, p->log, &tex, 16, 16, fmt);
3971
0
    ra_tex_free(p->ra, &tex);
3972
0
    return success;
3973
0
}
3974
3975
// Return whether dumb-mode can be used without disabling any features.
3976
// Essentially, vo_gpu with --profile=fast will return true.
3977
static bool check_dumb_mode(struct gl_video *p)
3978
0
{
3979
0
    struct gl_video_opts *o = &p->opts;
3980
0
    if (p->use_integer_conversion)
3981
0
        return false;
3982
0
    if (o->dumb_mode > 0) // requested by user
3983
0
        return true;
3984
0
    if (o->dumb_mode < 0) // disabled by user
3985
0
        return false;
3986
3987
    // otherwise, use auto-detection
3988
0
    if (o->correct_downscaling || o->linear_downscaling ||
3989
0
        o->linear_upscaling || o->sigmoid_upscaling || o->interpolation ||
3990
0
        o->blend_subs || o->deband || o->unsharp)
3991
0
        return false;
3992
    // check remaining scalers (tscale is already implicitly excluded above)
3993
0
    for (int i = 0; i < SCALER_COUNT; i++) {
3994
0
        if (i != SCALER_TSCALE) {
3995
0
            if (o->scaler[i].kernel.function != SCALER_BILINEAR &&
3996
0
                o->scaler[i].kernel.function != SCALER_INHERIT)
3997
0
                return false;
3998
0
        }
3999
0
    }
4000
0
    if (o->user_shaders && o->user_shaders[0])
4001
0
        return false;
4002
0
    return true;
4003
0
}
4004
4005
// Disable features that are not supported with the current OpenGL version.
4006
static void check_gl_features(struct gl_video *p)
4007
0
{
4008
0
    struct ra *ra = p->ra;
4009
0
    bool have_float_tex = !!ra_find_float16_format(ra, 1);
4010
0
    bool have_mglsl = ra->glsl_version >= 130; // modern GLSL
4011
0
    const struct ra_format *rg_tex = ra_find_unorm_format(p->ra, 1, 2);
4012
0
    bool have_texrg = rg_tex && !rg_tex->luminance_alpha;
4013
0
    bool have_compute = ra->caps & RA_CAP_COMPUTE;
4014
0
    bool have_ssbo = ra->caps & RA_CAP_BUF_RW;
4015
0
    bool have_fragcoord = ra->caps & RA_CAP_FRAGCOORD;
4016
4017
0
    const char *auto_fbo_fmts[] = {"rgba16f", "rgba16hf", "rgba16",
4018
0
                                   "rgb10_a2", "rgba8", 0};
4019
0
    const char *user_fbo_fmts[] = {p->opts.fbo_format, 0};
4020
0
    const char **fbo_fmts = user_fbo_fmts[0] && strcmp(user_fbo_fmts[0], "auto")
4021
0
                          ? user_fbo_fmts : auto_fbo_fmts;
4022
0
    bool user_specified_fbo_fmt = fbo_fmts == user_fbo_fmts;
4023
0
    bool fbo_test_result = false;
4024
0
    bool have_fbo = false;
4025
0
    p->fbo_format = NULL;
4026
0
    for (int n = 0; fbo_fmts[n]; n++) {
4027
0
        const char *fmt = fbo_fmts[n];
4028
0
        const struct ra_format *f = ra_find_named_format(p->ra, fmt);
4029
0
        if (!f && user_specified_fbo_fmt)
4030
0
            MP_WARN(p, "FBO format '%s' not found!\n", fmt);
4031
0
        if (f && f->renderable && f->linear_filter &&
4032
0
            (fbo_test_result = test_fbo(p, f))) {
4033
0
            MP_VERBOSE(p, "Using FBO format %s.\n", f->name);
4034
0
            have_fbo = true;
4035
0
            p->fbo_format = f;
4036
0
            break;
4037
0
        }
4038
4039
0
        if (user_specified_fbo_fmt) {
4040
0
            MP_WARN(p, "User-specified FBO format '%s' failed to initialize! "
4041
0
                       "(exists=%d, renderable=%d, linear_filter=%d, "
4042
0
                       "fbo_test_result=%d)\n",
4043
0
                    fmt, !!f, f ? f->renderable : 0,  f ? f->linear_filter : 0,
4044
0
                    fbo_test_result);
4045
0
        }
4046
0
    }
4047
4048
0
    if (!have_fragcoord && p->opts.dither_depth >= 0 &&
4049
0
        p->opts.dither_algo != DITHER_NONE)
4050
0
    {
4051
0
        p->opts.dither_algo = DITHER_NONE;
4052
0
        MP_WARN(p, "Disabling dithering (no gl_FragCoord).\n");
4053
0
    }
4054
0
    if (!have_fragcoord && p->opts.background == BACKGROUND_TILES) {
4055
0
        p->opts.background = BACKGROUND_COLOR;
4056
0
        MP_VERBOSE(p, "Disabling alpha checkerboard (no gl_FragCoord).\n");
4057
0
    }
4058
0
    if (!have_fbo && have_compute) {
4059
0
        have_compute = false;
4060
0
        MP_WARN(p, "Force-disabling compute shaders as an FBO format was not "
4061
0
                   "available! See your FBO format configuration!\n");
4062
0
    }
4063
4064
0
    if (have_compute && have_fbo && !p->fbo_format->storable) {
4065
0
        have_compute = false;
4066
0
        MP_WARN(p, "Force-disabling compute shaders as the chosen FBO format "
4067
0
                "is not storable! See your FBO format configuration!\n");
4068
0
    }
4069
4070
0
    if (!have_compute && p->opts.dither_algo == DITHER_ERROR_DIFFUSION) {
4071
0
        MP_WARN(p, "Disabling error diffusion dithering because compute shader "
4072
0
                   "was not supported. Fallback to dither=fruit instead.\n");
4073
0
        p->opts.dither_algo = DITHER_FRUIT;
4074
0
    }
4075
4076
0
    bool have_compute_peak = have_compute && have_ssbo;
4077
0
    if (!have_compute_peak && p->opts.tone_map.compute_peak >= 0) {
4078
0
        int msgl = p->opts.tone_map.compute_peak == 1 ? MSGL_WARN : MSGL_V;
4079
0
        MP_MSG(p, msgl, "Disabling HDR peak computation (one or more of the "
4080
0
                        "following is not supported: compute shaders=%d, "
4081
0
                        "SSBO=%d).\n", have_compute, have_ssbo);
4082
0
        p->opts.tone_map.compute_peak = -1;
4083
0
    }
4084
4085
0
    p->forced_dumb_mode = p->opts.dumb_mode > 0 || !have_fbo || !have_texrg;
4086
0
    bool voluntarily_dumb = check_dumb_mode(p);
4087
0
    if (p->forced_dumb_mode || voluntarily_dumb) {
4088
0
        if (voluntarily_dumb) {
4089
0
            MP_VERBOSE(p, "No advanced processing required. Enabling dumb mode.\n");
4090
0
        } else if (p->opts.dumb_mode <= 0) {
4091
0
            MP_WARN(p, "High bit depth FBOs unsupported. Enabling dumb mode.\n"
4092
0
                       "Most extended features will be disabled.\n");
4093
0
        }
4094
0
        p->dumb_mode = true;
4095
        // Most things don't work, so whitelist all options that still work.
4096
0
        p->opts = (struct gl_video_opts){
4097
0
            .scaler = {
4098
0
                [SCALER_SCALE] = {
4099
0
                    {SCALER_BILINEAR, .params = {NAN, NAN}, .functions = scale_filters},
4100
0
                    {WINDOW_PREFERRED, .params = {NAN, NAN}, .functions = filter_windows},
4101
0
                },
4102
0
                [SCALER_DSCALE] = {
4103
0
                    {SCALER_BILINEAR, .params = {NAN, NAN}, .functions = cdscale_filters},
4104
0
                    {WINDOW_PREFERRED, .params = {NAN, NAN}, .functions = filter_windows},
4105
0
                },
4106
0
                [SCALER_CSCALE] = {
4107
0
                    {SCALER_BILINEAR, .params = {NAN, NAN}, .functions = cdscale_filters},
4108
0
                    {WINDOW_PREFERRED, .params = {NAN, NAN}, .functions = filter_windows},
4109
0
                },
4110
0
                [SCALER_TSCALE] = {
4111
0
                    {SCALER_BILINEAR, .params = {NAN, NAN}, .functions = tscale_filters},
4112
0
                    {WINDOW_PREFERRED, .params = {NAN, NAN}, .functions = filter_windows},
4113
0
                },
4114
0
            },
4115
0
            .gamma = p->opts.gamma,
4116
0
            .gamma_auto = p->opts.gamma_auto,
4117
0
            .pbo = p->opts.pbo,
4118
0
            .fbo_format = p->opts.fbo_format,
4119
0
            .background = p->opts.background,
4120
0
            .use_rectangle = p->opts.use_rectangle,
4121
0
            .background_color = p->opts.background_color,
4122
0
            .background_tile_color[0] = p->opts.background_tile_color[0],
4123
0
            .background_tile_color[1] = p->opts.background_tile_color[1],
4124
0
            .background_tile_size = p->opts.background_tile_size,
4125
0
            .dither_algo = p->opts.dither_algo,
4126
0
            .dither_depth = p->opts.dither_depth,
4127
0
            .dither_size = p->opts.dither_size,
4128
0
            .error_diffusion = p->opts.error_diffusion,
4129
0
            .temporal_dither = p->opts.temporal_dither,
4130
0
            .temporal_dither_period = p->opts.temporal_dither_period,
4131
0
            .tex_pad_x = p->opts.tex_pad_x,
4132
0
            .tex_pad_y = p->opts.tex_pad_y,
4133
0
            .tone_map = p->opts.tone_map,
4134
0
            .early_flush = p->opts.early_flush,
4135
0
            .icc_opts = p->opts.icc_opts,
4136
0
            .hwdec_interop = p->opts.hwdec_interop,
4137
0
            .target_trc = p->opts.target_trc,
4138
0
            .target_prim = p->opts.target_prim,
4139
0
            .target_peak = p->opts.target_peak,
4140
0
        };
4141
0
        if (!have_fbo)
4142
0
            p->use_lut_3d = false;
4143
0
        return;
4144
0
    }
4145
0
    p->dumb_mode = false;
4146
4147
    // Normally, we want to disable them by default if FBOs are unavailable,
4148
    // because they will be slow (not critically slow, but still slower).
4149
    // Without FP textures, we must always disable them.
4150
    // I don't know if luminance alpha float textures exist, so disregard them.
4151
0
    for (int n = 0; n < SCALER_COUNT; n++) {
4152
0
        const struct filter_kernel *kernel =
4153
0
            mp_find_filter_kernel(p->opts.scaler[n].kernel.function);
4154
0
        if (kernel) {
4155
0
            char *reason = NULL;
4156
0
            if (!have_float_tex)
4157
0
                reason = "(float tex. missing)";
4158
0
            if (!have_mglsl)
4159
0
                reason = "(GLSL version too old)";
4160
0
            if (reason) {
4161
0
                MP_WARN(p, "Disabling scaler #%d %s %s.\n", n,
4162
0
                        m_opt_choice_str(p->opts.scaler[n].kernel.functions,
4163
0
                                         p->opts.scaler[n].kernel.function),
4164
0
                        reason);
4165
4166
                // p->opts is a copy => we can just mess with it.
4167
0
                p->opts.scaler[n].kernel.function = SCALER_BILINEAR;
4168
0
                if (n == SCALER_TSCALE)
4169
0
                    p->opts.interpolation = false;
4170
0
            }
4171
0
        }
4172
0
    }
4173
4174
0
    int use_cms = p->opts.target_prim != PL_COLOR_PRIM_UNKNOWN ||
4175
0
                  p->opts.target_trc != PL_COLOR_TRC_UNKNOWN || p->use_lut_3d;
4176
4177
    // mix() is needed for some gamma functions
4178
0
    if (!have_mglsl && (p->opts.linear_downscaling ||
4179
0
                        p->opts.linear_upscaling || p->opts.sigmoid_upscaling))
4180
0
    {
4181
0
        p->opts.linear_downscaling = false;
4182
0
        p->opts.linear_upscaling = false;
4183
0
        p->opts.sigmoid_upscaling = false;
4184
0
        MP_WARN(p, "Disabling linear/sigmoid scaling (GLSL version too old).\n");
4185
0
    }
4186
0
    if (!have_mglsl && use_cms) {
4187
0
        p->opts.target_prim = PL_COLOR_PRIM_UNKNOWN;
4188
0
        p->opts.target_trc = PL_COLOR_TRC_UNKNOWN;
4189
0
        p->use_lut_3d = false;
4190
0
        MP_WARN(p, "Disabling color management (GLSL version too old).\n");
4191
0
    }
4192
0
    if (!have_mglsl && p->opts.deband) {
4193
0
        p->opts.deband = false;
4194
0
        MP_WARN(p, "Disabling debanding (GLSL version too old).\n");
4195
0
    }
4196
0
}
4197
4198
static void init_gl(struct gl_video *p)
4199
0
{
4200
0
    debug_check_gl(p, "before init_gl");
4201
4202
0
    p->upload_timer = timer_pool_create(p->ra);
4203
0
    p->blit_timer = timer_pool_create(p->ra);
4204
0
    p->osd_timer = timer_pool_create(p->ra);
4205
4206
0
    debug_check_gl(p, "after init_gl");
4207
4208
0
    ra_dump_tex_formats(p->ra, MSGL_DEBUG);
4209
0
    ra_dump_img_formats(p->ra, MSGL_DEBUG);
4210
0
}
4211
4212
void gl_video_uninit(struct gl_video *p)
4213
0
{
4214
0
    if (!p)
4215
0
        return;
4216
4217
0
    uninit_video(p);
4218
0
    ra_hwdec_ctx_uninit(&p->hwdec_ctx);
4219
0
    gl_sc_destroy(p->sc);
4220
4221
0
    ra_tex_free(p->ra, &p->lut_3d_texture);
4222
0
    ra_buf_free(p->ra, &p->hdr_peak_ssbo);
4223
4224
0
    timer_pool_destroy(p->upload_timer);
4225
0
    timer_pool_destroy(p->blit_timer);
4226
0
    timer_pool_destroy(p->osd_timer);
4227
4228
0
    for (int i = 0; i < VO_PASS_PERF_MAX; i++) {
4229
0
        talloc_free(p->pass_fresh[i].desc.start);
4230
0
        talloc_free(p->pass_redraw[i].desc.start);
4231
0
    }
4232
4233
0
    mpgl_osd_destroy(p->osd);
4234
4235
    // Forcibly destroy possibly remaining image references. This should also
4236
    // cause gl_video_dr_free_buffer() to be called for the remaining buffers.
4237
0
    gc_pending_dr_fences(p, true);
4238
4239
    // Should all have been unreffed already.
4240
0
    mp_assert(!p->num_dr_buffers);
4241
4242
0
    talloc_free(p);
4243
0
}
4244
4245
void gl_video_reset(struct gl_video *p)
4246
0
{
4247
0
    gl_video_reset_surfaces(p);
4248
0
}
4249
4250
bool gl_video_showing_interpolated_frame(struct gl_video *p)
4251
0
{
4252
0
    return p->is_interpolated;
4253
0
}
4254
4255
static bool is_imgfmt_desc_supported(struct gl_video *p,
4256
                                     const struct ra_imgfmt_desc *desc)
4257
0
{
4258
0
    if (!desc->num_planes)
4259
0
        return false;
4260
4261
0
    if (desc->planes[0]->ctype == RA_CTYPE_UINT && p->forced_dumb_mode)
4262
0
        return false;
4263
4264
0
    return true;
4265
0
}
4266
4267
bool gl_video_check_format(struct gl_video *p, int mp_format)
4268
0
{
4269
0
    struct ra_imgfmt_desc desc;
4270
0
    if (ra_get_imgfmt_desc(p->ra, mp_format, &desc) &&
4271
0
        is_imgfmt_desc_supported(p, &desc))
4272
0
        return true;
4273
0
    if (ra_hwdec_get(&p->hwdec_ctx, mp_format))
4274
0
        return true;
4275
0
    return false;
4276
0
}
4277
4278
void gl_video_config(struct gl_video *p, struct mp_image_params *params)
4279
0
{
4280
0
    unmap_overlay(p);
4281
0
    unref_current_image(p);
4282
4283
0
    if (!mp_image_params_static_equal(&p->real_image_params, params)) {
4284
0
        uninit_video(p);
4285
0
        p->real_image_params = *params;
4286
0
        p->image_params = *params;
4287
0
        if (params->imgfmt)
4288
0
            init_video(p);
4289
0
    }
4290
4291
0
    gl_video_reset_surfaces(p);
4292
0
}
4293
4294
void gl_video_set_osd_source(struct gl_video *p, struct osd_state *osd)
4295
0
{
4296
0
    mpgl_osd_destroy(p->osd);
4297
0
    p->osd = NULL;
4298
0
    p->osd_state = osd;
4299
0
    reinit_osd(p);
4300
0
}
4301
4302
struct gl_video *gl_video_init(struct ra *ra, struct mp_log *log,
4303
                               struct mpv_global *g)
4304
0
{
4305
0
    struct gl_video *p = talloc_ptrtype(NULL, p);
4306
0
    *p = (struct gl_video) {
4307
0
        .ra = ra,
4308
0
        .global = g,
4309
0
        .log = log,
4310
0
        .sc = gl_sc_create(ra, g, log),
4311
0
        .video_eq = mp_csp_equalizer_create(p, g),
4312
0
        .opts_cache = m_config_cache_alloc(p, g, &gl_video_conf),
4313
0
    };
4314
    // make sure this variable is initialized to *something*
4315
0
    p->pass = p->pass_fresh;
4316
0
    struct gl_video_opts *opts = p->opts_cache->opts;
4317
0
    p->cms = gl_lcms_init(p, log, g, opts->icc_opts),
4318
0
    p->opts = *opts;
4319
0
    for (int n = 0; n < SCALER_COUNT; n++)
4320
0
        p->scaler[n] = (struct scaler){.index = n};
4321
    // our VAO always has the vec2 position as the first element
4322
0
    MP_TARRAY_APPEND(p, p->vao, p->vao_len, (struct ra_renderpass_input) {
4323
0
        .name = "position",
4324
0
        .type = RA_VARTYPE_FLOAT,
4325
0
        .dim_v = 2,
4326
0
        .dim_m = 1,
4327
0
        .offset = 0,
4328
0
    });
4329
0
    init_gl(p);
4330
0
    reinit_from_options(p);
4331
0
    return p;
4332
0
}
4333
4334
static void gl_video_update_options(struct gl_video *p)
4335
0
{
4336
0
    if (m_config_cache_update(p->opts_cache)) {
4337
0
        gl_lcms_update_options(p->cms);
4338
0
        reinit_from_options(p);
4339
0
    }
4340
4341
0
    if (mp_csp_equalizer_state_changed(p->video_eq))
4342
0
        p->output_tex_valid = false;
4343
0
}
4344
4345
static void reinit_from_options(struct gl_video *p)
4346
0
{
4347
0
    p->use_lut_3d = gl_lcms_has_profile(p->cms);
4348
4349
    // Copy the option fields, so that check_gl_features() can mutate them.
4350
    // This works only for the fields themselves of course, not for any memory
4351
    // referenced by them.
4352
0
    p->opts = *(struct gl_video_opts *)p->opts_cache->opts;
4353
4354
0
    if (!p->force_clear_color)
4355
0
        p->clear_color = p->opts.background_color;
4356
4357
0
    check_gl_features(p);
4358
0
    uninit_rendering(p);
4359
0
    if (p->opts.shader_cache)
4360
0
        gl_sc_set_cache_dir(p->sc, p->opts.shader_cache_dir);
4361
0
    p->ra->use_pbo = p->opts.pbo;
4362
0
    gl_video_setup_hooks(p);
4363
0
    reinit_osd(p);
4364
4365
0
    struct mp_vo_opts *vo_opts = mp_get_config_group(p, p->global, &vo_sub_opts);
4366
0
    if (p->opts.interpolation && !vo_opts->video_sync && !p->dsi_warned) {
4367
0
        MP_WARN(p, "Interpolation now requires enabling display-sync mode.\n"
4368
0
                   "E.g.: --video-sync=display-resample\n");
4369
0
        p->dsi_warned = true;
4370
0
    }
4371
0
    talloc_free(vo_opts);
4372
4373
0
    if (p->opts.correct_downscaling && !p->correct_downscaling_warned) {
4374
0
        if (p->opts.scaler[SCALER_DSCALE].kernel.function == SCALER_BILINEAR ||
4375
0
            (p->opts.scaler[SCALER_DSCALE].kernel.function == SCALER_INHERIT &&
4376
0
             p->opts.scaler[SCALER_SCALE].kernel.function == SCALER_BILINEAR)) {
4377
0
            MP_WARN(p, "correct-downscaling requires non-bilinear scaler.\n");
4378
0
            p->correct_downscaling_warned = true;
4379
0
        }
4380
0
    }
4381
0
}
4382
4383
void gl_video_configure_queue(struct gl_video *p, struct vo *vo)
4384
0
{
4385
0
    gl_video_update_options(p);
4386
4387
0
    int queue_size = 1;
4388
4389
    // Figure out an adequate size for the interpolation queue. The larger
4390
    // the radius, the earlier we need to queue frames.
4391
0
    if (p->opts.interpolation) {
4392
0
        const struct filter_kernel *kernel =
4393
0
            mp_find_filter_kernel(p->opts.scaler[SCALER_TSCALE].kernel.function);
4394
0
        if (kernel) {
4395
            // filter_scale wouldn't be correctly initialized were we to use it here.
4396
            // This is fine since we're always upsampling, but beware if downsampling
4397
            // is added!
4398
0
            double radius = kernel->f.radius;
4399
0
            radius = radius > 0 ? radius : p->opts.scaler[SCALER_TSCALE].radius;
4400
0
            queue_size += 1 + ceil(radius);
4401
0
        } else {
4402
            // Oversample/linear case
4403
0
            queue_size += 2;
4404
0
        }
4405
0
    }
4406
4407
0
    queue_size = MPMIN(queue_size, VO_MAX_REQ_FRAMES);
4408
0
    vo_set_queue_params(vo, 0, queue_size, queue_size + 1);
4409
0
}
4410
4411
static int validate_error_diffusion_opt(struct mp_log *log, const m_option_t *opt,
4412
                                        struct bstr name, const char **value)
4413
0
{
4414
0
    struct bstr param = bstr0(*value);
4415
0
    char s[32] = {0};
4416
0
    int r = 1;
4417
0
    if (bstr_equals0(param, "help")) {
4418
0
        r = M_OPT_EXIT;
4419
0
    } else {
4420
0
        snprintf(s, sizeof(s), "%.*s", BSTR_P(param));
4421
0
        const struct error_diffusion_kernel *k = mp_find_error_diffusion_kernel(s);
4422
0
        if (!k)
4423
0
            r = M_OPT_INVALID;
4424
0
    }
4425
0
    if (r < 1) {
4426
0
        mp_info(log, "Available error diffusion kernels:\n");
4427
0
        for (int n = 0; mp_error_diffusion_kernels[n].name; n++)
4428
0
            mp_info(log, "    %s\n", mp_error_diffusion_kernels[n].name);
4429
0
        if (s[0])
4430
0
            mp_fatal(log, "No error diffusion kernel named '%s' found!\n", s);
4431
0
    }
4432
0
    return r;
4433
0
}
4434
4435
static int validate_target_gamut(struct mp_log *log, const m_option_t *opt,
4436
                                 struct bstr name, const char **value)
4437
39
{
4438
39
    struct pl_raw_primaries tmp;
4439
39
    return mp_parse_raw_primaries(log, *value, &tmp);
4440
39
}
4441
4442
void gl_video_set_ambient_lux(struct gl_video *p, double lux)
4443
0
{
4444
0
    if (p->opts.gamma_auto) {
4445
0
        p->opts.gamma = gl_video_scale_ambient_lux(16.0, 256.0, 1.0, 1.2, lux);
4446
0
        MP_TRACE(p, "ambient light changed: %f lux (gamma: %f)\n", lux,
4447
0
                 p->opts.gamma);
4448
0
    }
4449
0
}
4450
4451
static void *gl_video_dr_alloc_buffer(struct gl_video *p, size_t size)
4452
0
{
4453
0
    struct ra_buf_params params = {
4454
0
        .type = RA_BUF_TYPE_TEX_UPLOAD,
4455
0
        .host_mapped = true,
4456
0
        .size = size,
4457
0
    };
4458
4459
0
    struct ra_buf *buf = ra_buf_create(p->ra, &params);
4460
0
    if (!buf)
4461
0
        return NULL;
4462
4463
0
    MP_TARRAY_GROW(p, p->dr_buffers, p->num_dr_buffers);
4464
0
    p->dr_buffers[p->num_dr_buffers++] = (struct dr_buffer){ .buf = buf };
4465
4466
0
    return buf->data;
4467
0
}
4468
4469
static void gl_video_dr_free_buffer(void *opaque, uint8_t *data)
4470
0
{
4471
0
    struct gl_video *p = opaque;
4472
4473
0
    for (int n = 0; n < p->num_dr_buffers; n++) {
4474
0
        struct dr_buffer *buffer = &p->dr_buffers[n];
4475
0
        if (buffer->buf->data == data) {
4476
0
            mp_assert(!buffer->mpi); // can't be freed while it has a ref
4477
0
            ra_buf_free(p->ra, &buffer->buf);
4478
0
            MP_TARRAY_REMOVE_AT(p->dr_buffers, p->num_dr_buffers, n);
4479
0
            return;
4480
0
        }
4481
0
    }
4482
    // not found - must not happen
4483
0
    MP_ASSERT_UNREACHABLE();
4484
0
}
4485
4486
struct mp_image *gl_video_get_image(struct gl_video *p, int imgfmt, int w, int h,
4487
                                    int stride_align, int flags)
4488
0
{
4489
0
    if (flags & VO_DR_FLAG_HOST_CACHED) {
4490
0
        if (p->ra->caps & RA_CAP_SLOW_DR) {
4491
0
            MP_VERBOSE(p, "DR path suspected slow/uncached, disabling.\n");
4492
0
            return NULL;
4493
0
        }
4494
0
    }
4495
4496
0
    if (!gl_video_check_format(p, imgfmt))
4497
0
        return NULL;
4498
4499
0
    int size = mp_image_get_alloc_size(imgfmt, w, h, stride_align);
4500
0
    if (size < 0)
4501
0
        return NULL;
4502
4503
0
    int alloc_size = size + stride_align;
4504
0
    void *ptr = gl_video_dr_alloc_buffer(p, alloc_size);
4505
0
    if (!ptr)
4506
0
        return NULL;
4507
4508
    // (we expect vo.c to proxy the free callback, so it happens in the same
4509
    // thread it was allocated in, removing the need for synchronization)
4510
0
    struct mp_image *res = mp_image_from_buffer(imgfmt, w, h, stride_align,
4511
0
                                                ptr, alloc_size, p,
4512
0
                                                gl_video_dr_free_buffer);
4513
0
    if (!res)
4514
0
        gl_video_dr_free_buffer(p, ptr);
4515
0
    return res;
4516
0
}
4517
4518
void gl_video_init_hwdecs(struct gl_video *p, struct ra_ctx *ra_ctx,
4519
                          struct mp_hwdec_devices *devs,
4520
                          bool load_all_by_default)
4521
0
{
4522
0
    mp_assert(!p->hwdec_ctx.ra_ctx);
4523
0
    p->hwdec_ctx = (struct ra_hwdec_ctx) {
4524
0
        .log = p->log,
4525
0
        .global = p->global,
4526
0
        .ra_ctx = ra_ctx,
4527
0
    };
4528
4529
0
    ra_hwdec_ctx_init(&p->hwdec_ctx, devs, p->opts.hwdec_interop, load_all_by_default);
4530
0
}
4531
4532
void gl_video_load_hwdecs_for_img_fmt(struct gl_video *p, struct mp_hwdec_devices *devs,
4533
                                      struct hwdec_imgfmt_request *params)
4534
0
{
4535
0
    mp_assert(p->hwdec_ctx.ra_ctx);
4536
0
    ra_hwdec_ctx_load_fmt(&p->hwdec_ctx, devs, params);
4537
0
}
4538
4539
struct mp_image_params *gl_video_get_target_params_ptr(struct gl_video *p)
4540
0
{
4541
0
    return &p->target_params;
4542
0
}