Coverage Report

Created: 2026-07-15 07:31

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ffmpeg/libswscale/graph.c
Line
Count
Source
1
/*
2
 * Copyright (C) 2024 Niklas Haas
3
 *
4
 * This file is part of FFmpeg.
5
 *
6
 * FFmpeg is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU Lesser General Public
8
 * License as published by the Free Software Foundation; either
9
 * version 2.1 of the License, or (at your option) any later version.
10
 *
11
 * FFmpeg is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
 * Lesser General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU Lesser General Public
17
 * License along with FFmpeg; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19
 */
20
21
#include "libavutil/avassert.h"
22
#include "libavutil/cpu.h"
23
#include "libavutil/error.h"
24
#include "libavutil/hwcontext.h"
25
#include "libavutil/imgutils.h"
26
#include "libavutil/macros.h"
27
#include "libavutil/mem.h"
28
#include "libavutil/opt.h"
29
#include "libavutil/pixdesc.h"
30
#include "libavutil/refstruct.h"
31
#include "libavutil/slicethread.h"
32
33
#include "libswscale/swscale.h"
34
#include "libswscale/format.h"
35
36
#include "cms.h"
37
#include "lut3d.h"
38
#include "swscale_internal.h"
39
#include "graph.h"
40
#include "ops.h"
41
#include "ops_dispatch.h"
42
#if CONFIG_VULKAN
43
#include "vulkan/ops.h"
44
#endif
45
46
int ff_sws_pass_aligned_width(const SwsPass *pass, int width)
47
0
{
48
0
    if (!pass)
49
0
        return width;
50
51
0
    size_t aligned_w = width;
52
0
    aligned_w = FFALIGN(aligned_w, pass->output->width_align);
53
0
    aligned_w += pass->output->width_pad;
54
0
    return aligned_w <= INT_MAX ? aligned_w : width;
55
0
}
56
57
/* Allocates one buffer per plane */
58
static int frame_alloc_planes(AVFrame *dst)
59
0
{
60
0
    int ret = av_image_check_size2(dst->width, dst->height, INT64_MAX,
61
0
                                   dst->format, 0, NULL);
62
0
    if (ret < 0)
63
0
        return ret;
64
65
0
    const int align = av_cpu_max_align();
66
0
    const int aligned_w = FFALIGN(dst->width, align);
67
0
    ret = av_image_fill_linesizes(dst->linesize, dst->format, aligned_w);
68
0
    if (ret < 0)
69
0
        return ret;
70
71
0
    ptrdiff_t linesize1[4];
72
0
    for (int i = 0; i < 4; i++)
73
0
        linesize1[i] = dst->linesize[i] = FFALIGN(dst->linesize[i], align);
74
75
0
    size_t sizes[4];
76
0
    ret = av_image_fill_plane_sizes(sizes, dst->format, dst->height, linesize1);
77
0
    if (ret < 0)
78
0
        return ret;
79
80
0
    for (int i = 0; i < 4; i++) {
81
0
        if (!sizes[i])
82
0
            break;
83
0
        AVBufferRef *buf = av_buffer_alloc(sizes[i]);
84
0
        if (!buf)
85
0
            return AVERROR(ENOMEM);
86
0
        dst->data[i] = buf->data;
87
0
        dst->buf[i] = buf;
88
0
    }
89
90
0
    return 0;
91
0
}
92
93
#if CONFIG_VULKAN
94
static int pass_alloc_output_hw(SwsPass *pass, AVFrame *avframe,
95
                                AVBufferRef *dev_ref)
96
{
97
    SwsPassBuffer *buffer = pass->output;
98
    AVBufferRef *frames_ref = av_hwframe_ctx_alloc(dev_ref);
99
    if (!frames_ref)
100
        return AVERROR(ENOMEM);
101
102
    AVHWFramesContext *hwfc = (AVHWFramesContext *)frames_ref->data;
103
    hwfc->format    = AV_PIX_FMT_VULKAN;
104
    hwfc->sw_format = pass->format;
105
    hwfc->width     = buffer->width;
106
    hwfc->height    = buffer->height;
107
108
    int ret = av_hwframe_ctx_init(frames_ref);
109
    if (ret >= 0) {
110
        avframe->format = AV_PIX_FMT_VULKAN;
111
        ret = av_hwframe_get_buffer(frames_ref, avframe, 0);
112
    }
113
    av_buffer_unref(&frames_ref);
114
    return ret;
115
}
116
#endif
117
118
static int pass_alloc_output(SwsPass *pass)
119
0
{
120
0
    if (!pass || pass->output->avframe)
121
0
        return 0;
122
123
0
    SwsPassBuffer *buffer = pass->output;
124
0
    AVFrame *avframe = av_frame_alloc();
125
0
    if (!avframe)
126
0
        return AVERROR(ENOMEM);
127
0
    avframe->width  = buffer->width;
128
0
    avframe->height = buffer->height;
129
130
0
    int ret;
131
132
#if CONFIG_VULKAN
133
    const SwsGraph *graph = pass->graph;
134
    if (graph->src.hw_format == AV_PIX_FMT_VULKAN &&
135
        graph->dst.hw_format == AV_PIX_FMT_VULKAN) {
136
        AVBufferRef *dev_ref = ff_sws_vk_device_ref(graph->ctx);
137
        if (dev_ref) {
138
            ret = pass_alloc_output_hw(pass, avframe, dev_ref);
139
            if (ret >= 0)
140
                goto done;
141
            av_frame_unref(avframe);
142
        }
143
    }
144
#endif
145
146
0
    avframe->format = pass->format;
147
0
    ret = frame_alloc_planes(avframe);
148
0
    if (ret < 0) {
149
0
        av_frame_free(&avframe);
150
0
        return ret;
151
0
    }
152
153
#if CONFIG_VULKAN
154
done:
155
#endif
156
0
    buffer->avframe = avframe;
157
0
    ff_sws_frame_from_avframe(&buffer->frame, avframe);
158
0
    return 0;
159
0
}
160
161
static void free_buffer(AVRefStructOpaque opaque, void *obj)
162
0
{
163
0
    SwsPassBuffer *buffer = obj;
164
0
    av_frame_free(&buffer->avframe);
165
0
}
166
167
static void pass_free(SwsPass *pass)
168
0
{
169
0
    if (pass->free)
170
0
        pass->free(pass->priv);
171
0
    av_refstruct_unref(&pass->output);
172
0
    av_free(pass);
173
0
}
174
175
int ff_sws_graph_add_pass(SwsGraph *graph, enum AVPixelFormat fmt,
176
                          int width, int height, SwsPass *input,
177
                          int lines, int align,
178
                          SwsPassFunc run, SwsPassSetup setup,
179
                          void *priv, void (*free_cb)(void *priv),
180
                          SwsPass **out_pass)
181
0
{
182
0
    int ret;
183
0
    SwsPass *pass = av_mallocz(sizeof(*pass));
184
0
    if (!pass) {
185
0
        if (free_cb)
186
0
            free_cb(priv);
187
0
        return AVERROR(ENOMEM);
188
0
    }
189
190
0
    if (!lines)
191
0
        lines = height;
192
193
0
    pass->graph  = graph;
194
0
    pass->run    = run;
195
0
    pass->setup  = setup;
196
0
    pass->priv   = priv;
197
0
    pass->free   = free_cb;
198
0
    pass->format = fmt;
199
0
    pass->lines  = lines;
200
0
    pass->input  = input;
201
0
    pass->output = av_refstruct_alloc_ext(sizeof(*pass->output), 0, NULL, free_buffer);
202
0
    if (!pass->output) {
203
0
        ret = AVERROR(ENOMEM);
204
0
        goto fail;
205
0
    }
206
207
0
    pass->output->height = height;
208
0
    pass->output->width  = width;
209
0
    pass->output->width_align = 1;
210
211
0
    if (!align) {
212
0
        pass->slice_h = pass->lines;
213
0
        pass->num_slices = 1;
214
0
    } else {
215
0
        pass->slice_h = (pass->lines + graph->num_threads - 1) / graph->num_threads;
216
0
        pass->slice_h = FFALIGN(pass->slice_h, align);
217
0
        pass->num_slices = (pass->lines + pass->slice_h - 1) / pass->slice_h;
218
0
    }
219
220
0
    ret = av_dynarray_add_nofree(&graph->passes, &graph->num_passes, pass);
221
0
    if (ret < 0)
222
0
        goto fail;
223
224
0
    *out_pass = pass;
225
0
    return 0;
226
227
0
fail:
228
0
    pass_free(pass);
229
0
    return ret;
230
0
}
231
232
void ff_sws_pass_link_output(SwsPass *dst, const SwsPass *src)
233
0
{
234
0
    if (!dst || !src || dst == src)
235
0
        return;
236
237
0
    av_assert0(dst->format == src->format);
238
0
    SwsPassBuffer *keep = src->output, *drop = dst->output;
239
240
0
    av_assert1(keep->width  == drop->width);
241
0
    av_assert1(keep->height == drop->height);
242
0
    keep->width_align = FFMAX(keep->width_align, drop->width_align);
243
0
    keep->width_pad   = FFMAX(keep->width_pad,   drop->width_pad);
244
245
0
    av_refstruct_replace(&dst->output, src->output);
246
0
}
247
248
static void frame_shift(const SwsFrame *f, const int y, uint8_t *data[4])
249
0
{
250
0
    for (int i = 0; i < 4; i++) {
251
0
        if (f->data[i])
252
0
            data[i] = f->data[i] + (y >> ff_fmt_vshift(f->format, i)) * f->linesize[i];
253
0
        else
254
0
            data[i] = NULL;
255
0
    }
256
0
}
257
258
static void run_copy(const SwsFrame *out, const SwsFrame *in, int y, int h,
259
                     const SwsPass *pass)
260
0
{
261
0
    uint8_t *in_data[4], *out_data[4];
262
0
    frame_shift(in,  y, in_data);
263
0
    frame_shift(out, y, out_data);
264
265
0
    for (int i = 0; i < 4 && out_data[i]; i++) {
266
0
        const int lines = h >> ff_fmt_vshift(in->format, i);
267
0
        av_assert1(in_data[i]);
268
269
0
        if (in_data[i] == out_data[i]) {
270
0
            av_assert0(in->linesize[i] == out->linesize[i]);
271
0
        } else if (in->linesize[i] == out->linesize[i]) {
272
0
            memcpy(out_data[i], in_data[i], lines * out->linesize[i]);
273
0
        } else {
274
0
            const int linesize = FFMIN(out->linesize[i], in->linesize[i]);
275
0
            for (int j = 0; j < lines; j++) {
276
0
                memcpy(out_data[i], in_data[i], linesize);
277
0
                in_data[i]  += in->linesize[i];
278
0
                out_data[i] += out->linesize[i];
279
0
            }
280
0
        }
281
0
    }
282
0
}
283
284
static void run_rgb0(const SwsFrame *out, const SwsFrame *in, int y, int h,
285
                     const SwsPass *pass)
286
0
{
287
0
    SwsInternal *c = pass->priv;
288
0
    const int x0 = c->src0Alpha - 1;
289
0
    const int w4 = 4 * out->width;
290
0
    const int src_stride = in->linesize[0];
291
0
    const int dst_stride = out->linesize[0];
292
0
    const uint8_t *src = in->data[0] + y * src_stride;
293
0
    uint8_t *dst = out->data[0] + y * dst_stride;
294
295
0
    for (int y = 0; y < h; y++) {
296
0
        memcpy(dst, src, w4 * sizeof(*dst));
297
0
        for (int x = x0; x < w4; x += 4)
298
0
            dst[x] = 0xFF;
299
300
0
        src += src_stride;
301
0
        dst += dst_stride;
302
0
    }
303
0
}
304
305
static void run_xyz2rgb(const SwsFrame *out, const SwsFrame *in, int y, int h,
306
                        const SwsPass *pass)
307
0
{
308
0
    const SwsInternal *c = pass->priv;
309
0
    c->xyz12Torgb48(c, out->data[0] + y * out->linesize[0], out->linesize[0],
310
0
                    in->data[0] + y * in->linesize[0], in->linesize[0],
311
0
                    out->width, h);
312
0
}
313
314
static void run_rgb2xyz(const SwsFrame *out, const SwsFrame *in, int y, int h,
315
                        const SwsPass *pass)
316
0
{
317
0
    const SwsInternal *c = pass->priv;
318
0
    c->rgb48Toxyz12(c, out->data[0] + y * out->linesize[0], out->linesize[0],
319
0
                    in->data[0] + y * in->linesize[0], in->linesize[0],
320
0
                    out->width, h);
321
0
}
322
323
/***********************************************************************
324
 * Internal ff_swscale() wrapper. This reuses the legacy scaling API. *
325
 * This is considered fully deprecated, and will be replaced by a full *
326
 * reimplementation ASAP.                                              *
327
 ***********************************************************************/
328
329
static void free_legacy_swscale(void *priv)
330
0
{
331
0
    SwsContext *sws = priv;
332
0
    sws_free_context(&sws);
333
0
}
334
335
static int setup_legacy_swscale(const SwsFrame *out, const SwsFrame *in,
336
                                const SwsPass *pass)
337
0
{
338
0
    SwsContext *sws = pass->priv;
339
0
    SwsInternal *c = sws_internal(sws);
340
0
    if (sws->flags & SWS_BITEXACT && sws->dither == SWS_DITHER_ED && c->dither_error[0]) {
341
0
        for (int i = 0; i < 4; i++)
342
0
            memset(c->dither_error[i], 0, sizeof(c->dither_error[0][0]) * (sws->dst_w + 2));
343
0
    }
344
345
0
    if (usePal(sws->src_format))
346
0
        ff_update_palette(c, (const uint32_t *) in->data[1]);
347
348
0
    return 0;
349
0
}
350
351
static inline SwsContext *slice_ctx(const SwsPass *pass, int y)
352
0
{
353
0
    SwsContext *sws = pass->priv;
354
0
    SwsInternal *parent = sws_internal(sws);
355
0
    if (pass->num_slices == 1)
356
0
        return sws;
357
358
0
    av_assert1(parent->nb_slice_ctx == pass->num_slices);
359
0
    sws = parent->slice_ctx[y / pass->slice_h];
360
361
0
    if (usePal(sws->src_format)) {
362
0
        SwsInternal *sub = sws_internal(sws);
363
0
        memcpy(sub->pal_yuv, parent->pal_yuv, sizeof(sub->pal_yuv));
364
0
        memcpy(sub->pal_rgb, parent->pal_rgb, sizeof(sub->pal_rgb));
365
0
    }
366
367
0
    return sws;
368
0
}
369
370
static void run_legacy_unscaled(const SwsFrame *out, const SwsFrame *in,
371
                                int y, int h, const SwsPass *pass)
372
0
{
373
0
    SwsContext *sws = slice_ctx(pass, y);
374
0
    SwsInternal *c = sws_internal(sws);
375
0
    uint8_t *in_data[4];
376
0
    frame_shift(in, y, in_data);
377
378
0
    c->convert_unscaled(c, (const uint8_t *const *) in_data, in->linesize, y, h,
379
0
                        out->data, out->linesize);
380
0
}
381
382
static void run_legacy_swscale(const SwsFrame *out, const SwsFrame *in,
383
                               int y, int h, const SwsPass *pass)
384
0
{
385
0
    SwsContext *sws = slice_ctx(pass, y);
386
0
    SwsInternal *c = sws_internal(sws);
387
0
    uint8_t *out_data[4];
388
0
    frame_shift(out, y, out_data);
389
390
0
    ff_swscale(c, (const uint8_t *const *) in->data, in->linesize, 0,
391
0
               sws->src_h, out_data, out->linesize, y, h);
392
0
}
393
394
static void legacy_chr_pos(SwsGraph *graph, int *chr_pos, int override, int *warned)
395
0
{
396
0
    if (override == -513 || override == *chr_pos)
397
0
        return;
398
399
0
    if (!*warned) {
400
0
        av_log(NULL, AV_LOG_WARNING,
401
0
               "Setting chroma position directly is deprecated, make sure "
402
0
               "the frame is tagged with the correct chroma location.\n");
403
0
        *warned = 1;
404
0
    }
405
406
0
    *chr_pos = override;
407
0
}
408
409
/* Takes over ownership of `sws` */
410
static int init_legacy_subpass(SwsGraph *graph, SwsContext *sws,
411
                               SwsPass *input, SwsPass **output)
412
0
{
413
0
    SwsInternal *c = sws_internal(sws);
414
0
    const int src_w = sws->src_w, src_h = sws->src_h;
415
0
    const int dst_w = sws->dst_w, dst_h = sws->dst_h;
416
0
    const int unscaled = src_w == dst_w && src_h == dst_h;
417
0
    int align = c->dst_slice_align;
418
0
    SwsPass *pass = NULL;
419
0
    int ret;
420
421
0
    if (c->cascaded_context[0]) {
422
0
        const int num_cascaded = c->cascaded_context[2] ? 3 : 2;
423
0
        for (int i = 0; i < num_cascaded; i++) {
424
0
            const int is_last = i + 1 == num_cascaded;
425
426
            /* Steal cascaded context, so we can manage its lifetime independently */
427
0
            SwsContext *sub = c->cascaded_context[i];
428
0
            c->cascaded_context[i] = NULL;
429
430
0
            ret = init_legacy_subpass(graph, sub, input, is_last ? output : &input);
431
0
            if (ret < 0)
432
0
                break;
433
0
        }
434
435
0
        sws_free_context(&sws);
436
0
        return ret;
437
0
    }
438
439
0
    if (sws->dither == SWS_DITHER_ED && !c->convert_unscaled)
440
0
        align = 0; /* disable slice threading */
441
442
0
    if (c->src0Alpha && !c->dst0Alpha && isALPHA(sws->dst_format)) {
443
0
        ret = ff_sws_graph_add_pass(graph, AV_PIX_FMT_RGBA, src_w, src_h, input,
444
0
                                    0, 1, run_rgb0, NULL, c, NULL, &input);
445
0
        if (ret < 0) {
446
0
            sws_free_context(&sws);
447
0
            return ret;
448
0
        }
449
0
    }
450
451
0
    if (c->srcXYZ && !(c->dstXYZ && unscaled)) {
452
0
        ret = ff_sws_graph_add_pass(graph, AV_PIX_FMT_RGB48, src_w, src_h, input,
453
0
                                    0, 1, run_xyz2rgb, NULL, c, NULL, &input);
454
0
        if (ret < 0) {
455
0
            sws_free_context(&sws);
456
0
            return ret;
457
0
        }
458
0
    }
459
460
0
    ret = ff_sws_graph_add_pass(graph, sws->dst_format, dst_w, dst_h, input, 0, align,
461
0
                                c->convert_unscaled ? run_legacy_unscaled : run_legacy_swscale,
462
0
                                setup_legacy_swscale, sws, free_legacy_swscale, &pass);
463
0
    if (ret < 0)
464
0
        return ret;
465
0
    pass->backend = SWS_BACKEND_LEGACY;
466
467
    /**
468
     * For slice threading, we need to create sub contexts, similar to how
469
     * swscale normally handles it internally. The most important difference
470
     * is that we handle cascaded contexts before threaded contexts; whereas
471
     * context_init_threaded() does it the other way around.
472
     */
473
474
0
    if (pass->num_slices > 1) {
475
0
        c->slice_ctx = av_calloc(pass->num_slices, sizeof(*c->slice_ctx));
476
0
        if (!c->slice_ctx)
477
0
            return AVERROR(ENOMEM);
478
479
0
        for (int i = 0; i < pass->num_slices; i++) {
480
0
            SwsContext *slice;
481
0
            SwsInternal *c2;
482
0
            slice = c->slice_ctx[i] = sws_alloc_context();
483
0
            if (!slice)
484
0
                return AVERROR(ENOMEM);
485
0
            c->nb_slice_ctx++;
486
487
0
            c2 = sws_internal(slice);
488
0
            c2->parent = sws;
489
490
0
            ret = av_opt_copy(slice, sws);
491
0
            if (ret < 0)
492
0
                return ret;
493
494
0
            ret = ff_sws_init_single_context(slice, NULL, NULL);
495
0
            if (ret < 0)
496
0
                return ret;
497
498
0
            sws_setColorspaceDetails(slice, c->srcColorspaceTable,
499
0
                                     slice->src_range, c->dstColorspaceTable,
500
0
                                     slice->dst_range, c->brightness, c->contrast,
501
0
                                     c->saturation);
502
503
0
            for (int i = 0; i < FF_ARRAY_ELEMS(c->srcColorspaceTable); i++) {
504
0
                c2->srcColorspaceTable[i] = c->srcColorspaceTable[i];
505
0
                c2->dstColorspaceTable[i] = c->dstColorspaceTable[i];
506
0
            }
507
0
        }
508
0
    }
509
510
0
    if (c->dstXYZ && !(c->srcXYZ && unscaled)) {
511
0
        ret = ff_sws_graph_add_pass(graph, AV_PIX_FMT_RGB48, dst_w, dst_h, pass,
512
0
                                    0, 1, run_rgb2xyz, NULL, c, NULL, &pass);
513
0
        if (ret < 0)
514
0
            return ret;
515
0
    }
516
517
0
    *output = pass;
518
0
    return 0;
519
0
}
520
521
static int add_legacy_sws_pass(SwsGraph *graph, const SwsFormat *src,
522
                               const SwsFormat *dst, SwsPass *input,
523
                               SwsPass **output)
524
0
{
525
0
    int ret, warned = 0;
526
0
    SwsContext *const ctx = graph->ctx;
527
0
    const SwsBackend backend = ff_sws_enabled_backends(ctx);
528
0
    if (!(backend & SWS_BACKEND_LEGACY))
529
0
        return AVERROR(ENOTSUP);
530
0
    if (src->hw_format != AV_PIX_FMT_NONE || dst->hw_format != AV_PIX_FMT_NONE)
531
0
        return AVERROR(ENOTSUP);
532
533
    /* Re-check this here because this might not be excluded if the caller was
534
     * testing against multiple backends */
535
0
    if (!sws_isSupportedInput(src->format) || !sws_isSupportedOutput(dst->format))
536
0
        return AVERROR(ENOTSUP);
537
538
0
    SwsContext *sws = sws_alloc_context();
539
0
    if (!sws)
540
0
        return AVERROR(ENOMEM);
541
542
0
    sws->flags       = ctx->flags;
543
0
    sws->dither      = ctx->dither;
544
0
    sws->alpha_blend = ctx->alpha_blend;
545
0
    sws->gamma_flag  = ctx->gamma_flag;
546
0
    sws->scaler      = ctx->scaler;
547
0
    sws->scaler_sub  = ctx->scaler_sub;
548
549
0
    sws->src_w       = src->width;
550
0
    sws->src_h       = src->height;
551
0
    sws->src_format  = src->format;
552
0
    sws->src_range   = src->range == AVCOL_RANGE_JPEG;
553
554
0
    sws->dst_w      = dst->width;
555
0
    sws->dst_h      = dst->height;
556
0
    sws->dst_format = dst->format;
557
0
    sws->dst_range  = dst->range == AVCOL_RANGE_JPEG;
558
0
    ff_sws_chroma_pos(src, &graph->incomplete, &sws->src_h_chr_pos, &sws->src_v_chr_pos);
559
0
    ff_sws_chroma_pos(dst, &graph->incomplete, &sws->dst_h_chr_pos, &sws->dst_v_chr_pos);
560
561
0
    graph->incomplete |= src->range == AVCOL_RANGE_UNSPECIFIED;
562
0
    graph->incomplete |= dst->range == AVCOL_RANGE_UNSPECIFIED;
563
564
    /* Allow overriding chroma position with the legacy API */
565
0
    legacy_chr_pos(graph, &sws->src_h_chr_pos, ctx->src_h_chr_pos, &warned);
566
0
    legacy_chr_pos(graph, &sws->src_v_chr_pos, ctx->src_v_chr_pos, &warned);
567
0
    legacy_chr_pos(graph, &sws->dst_h_chr_pos, ctx->dst_h_chr_pos, &warned);
568
0
    legacy_chr_pos(graph, &sws->dst_v_chr_pos, ctx->dst_v_chr_pos, &warned);
569
570
    /* Explicitly strip chroma offsets when not subsampling, because it
571
     * interferes with the operation of flags like SWS_FULL_CHR_H_INP */
572
0
    if (!src->desc->log2_chroma_w)
573
0
        sws->src_h_chr_pos = -513;
574
0
    if (!src->desc->log2_chroma_h)
575
0
        sws->src_v_chr_pos = -513;
576
0
    if (!dst->desc->log2_chroma_w)
577
0
        sws->dst_h_chr_pos = -513;
578
0
    if (!dst->desc->log2_chroma_h)
579
0
        sws->dst_v_chr_pos = -513;
580
581
0
    for (int i = 0; i < SWS_NUM_SCALER_PARAMS; i++)
582
0
        sws->scaler_params[i] = ctx->scaler_params[i];
583
584
0
    ret = sws_init_context(sws, NULL, NULL);
585
0
    if (ret < 0) {
586
0
        sws_free_context(&sws);
587
0
        return ret;
588
0
    }
589
590
    /* Set correct color matrices */
591
0
    {
592
0
        int in_full, out_full, brightness, contrast, saturation;
593
0
        const int *inv_table, *table;
594
0
        sws_getColorspaceDetails(sws, (int **)&inv_table, &in_full,
595
0
                                (int **)&table, &out_full,
596
0
                                &brightness, &contrast, &saturation);
597
598
0
        inv_table = sws_getCoefficients(src->csp);
599
0
        table     = sws_getCoefficients(dst->csp);
600
601
0
        graph->incomplete |= src->csp != dst->csp &&
602
0
                            (src->csp == AVCOL_SPC_UNSPECIFIED ||
603
0
                             dst->csp == AVCOL_SPC_UNSPECIFIED);
604
605
0
        sws_setColorspaceDetails(sws, inv_table, in_full, table, out_full,
606
0
                                brightness, contrast, saturation);
607
0
    }
608
609
0
    return init_legacy_subpass(graph, sws, input, output);
610
0
}
611
612
/*********************************
613
 * Format conversion and scaling *
614
 *********************************/
615
616
static int add_ops_convert_pass(SwsGraph *graph, const SwsFormat *src,
617
                                const SwsFormat *dst, SwsPass *input,
618
                                SwsPass **output)
619
0
{
620
0
#if CONFIG_UNSTABLE
621
0
    SwsContext *ctx = graph->ctx;
622
623
    /* Preemptively skip the ops list generation if the backend was
624
     * constrained to the legacy implementation only. This would
625
     * normally also fail in ff_sws_compile_pass() with the same
626
     * error, but this way saves a bit of unnecessary overhead */
627
0
    const SwsBackend backends = ff_sws_enabled_backends(ctx);
628
0
    if (backends == SWS_BACKEND_LEGACY)
629
0
        return AVERROR(ENOTSUP);
630
631
0
    SwsOpList *ops;
632
0
    int ret = ff_sws_op_list_generate(ctx, src, dst, &ops, &graph->incomplete);
633
0
    if (ret < 0)
634
0
        return ret;
635
636
0
    av_log(ctx, AV_LOG_VERBOSE, "Conversion pass for %s -> %s:\n",
637
0
           av_get_pix_fmt_name(src->format), av_get_pix_fmt_name(dst->format));
638
639
0
    av_log(ctx, AV_LOG_DEBUG, "Unoptimized operation list:\n");
640
0
    ff_sws_op_list_print(ctx, AV_LOG_DEBUG, AV_LOG_TRACE, ops);
641
642
0
    const int flags = SWS_OP_FLAG_OPTIMIZE | SWS_OP_FLAG_SPLIT_MEMCPY;
643
0
    return ff_sws_compile_pass(graph, NULL, &ops, flags, input, output);
644
#else
645
    return AVERROR(ENOTSUP);
646
#endif
647
0
}
648
649
static bool prefer_ops_backend(SwsContext *ctx, const SwsFormat *src, const SwsFormat *dst)
650
0
{
651
0
    if (ctx->flags & SWS_UNSTABLE)
652
0
        return true;
653
0
    if (isFloat(src->format) || isFloat(dst->format))
654
0
        return true; /* ops backend has better support for float formats */
655
0
    return false; /* default to legacy for stability reasons */
656
0
}
657
658
static int add_convert_pass(SwsGraph *graph, const SwsFormat *src,
659
                            const SwsFormat *dst, SwsPass *input,
660
                            SwsPass **output)
661
0
{
662
0
    SwsContext *ctx = graph->ctx;
663
0
    int ret;
664
665
0
    if (prefer_ops_backend(ctx, src, dst)) {
666
0
        ret = add_ops_convert_pass(graph, src, dst, input, output);
667
0
        if (ret == AVERROR(ENOTSUP))
668
0
            ret = add_legacy_sws_pass(graph, src, dst, input, output);
669
0
    } else {
670
0
        ret = add_legacy_sws_pass(graph, src, dst, input, output);
671
0
        if (ret == AVERROR(ENOTSUP))
672
0
            ret = add_ops_convert_pass(graph, src, dst, input, output);
673
0
    }
674
675
0
    return ret;
676
0
}
677
678
/**************************
679
 * Gamut and tone mapping *
680
 **************************/
681
682
static void free_lut3d(void *priv)
683
0
{
684
0
    SwsLut3D *lut = priv;
685
0
    ff_sws_lut3d_free(&lut);
686
0
}
687
688
static int setup_lut3d(const SwsFrame *out, const SwsFrame *in, const SwsPass *pass)
689
0
{
690
0
    SwsLut3D *lut = pass->priv;
691
692
    /* Update dynamic frame metadata from the original source frame */
693
0
    ff_sws_lut3d_update(lut, &pass->graph->src.color);
694
0
    return 0;
695
0
}
696
697
static void run_lut3d(const SwsFrame *out, const SwsFrame *in, int y, int h,
698
                      const SwsPass *pass)
699
0
{
700
0
    SwsLut3D *lut = pass->priv;
701
0
    uint8_t *in_data[4], *out_data[4];
702
0
    frame_shift(in,  y, in_data);
703
0
    frame_shift(out, y, out_data);
704
705
0
    ff_sws_lut3d_apply(lut, in_data[0], in->linesize[0], out_data[0],
706
0
                       out->linesize[0], out->width, h);
707
0
}
708
709
static int adapt_colors(SwsGraph *graph, const SwsFormat *src_fmt,
710
                        const SwsFormat *dst_fmt, SwsPass *input,
711
                        SwsPass **output)
712
0
{
713
0
    SwsFormat src = *src_fmt;
714
0
    SwsFormat dst = *dst_fmt;
715
0
    enum AVPixelFormat fmt_in, fmt_out;
716
0
    SwsColorMap map = {0};
717
0
    SwsLut3D *lut;
718
0
    int ret;
719
720
    /**
721
     * Grayspace does not really have primaries, so just force the use of
722
     * the equivalent other primary set to avoid a conversion. Technically,
723
     * this does affect the weights used for the Grayscale conversion, but
724
     * in practise, that should give the expected results more often than not.
725
     */
726
0
    if (isGray(dst.format)) {
727
0
        dst.color = src.color;
728
0
    } else if (isGray(src.format)) {
729
0
        src.color = dst.color;
730
0
    }
731
732
    /* Fully infer color spaces before color mapping logic */
733
0
    graph->incomplete |= ff_infer_colors(&src.color, &dst.color);
734
735
0
    map.intent = graph->ctx->intent;
736
0
    map.src    = src.color;
737
0
    map.dst    = dst.color;
738
739
0
    if (ff_sws_color_map_noop(&map))
740
0
        return 0;
741
742
0
    if (src.hw_format != AV_PIX_FMT_NONE || dst.hw_format != AV_PIX_FMT_NONE)
743
0
        return AVERROR(ENOTSUP);
744
745
0
    lut = ff_sws_lut3d_alloc();
746
0
    if (!lut)
747
0
        return AVERROR(ENOMEM);
748
749
0
    fmt_in  = ff_sws_lut3d_pick_pixfmt(&src, 0);
750
0
    fmt_out = ff_sws_lut3d_pick_pixfmt(&dst, 1);
751
0
    if (fmt_in != src.format) {
752
0
        SwsFormat tmp = src;
753
0
        tmp.format = fmt_in;
754
0
        ret = add_convert_pass(graph, &src, &tmp, input, &input);
755
0
        if (ret < 0) {
756
0
            ff_sws_lut3d_free(&lut);
757
0
            return ret;
758
0
        }
759
0
    }
760
761
0
    ret = ff_sws_lut3d_generate(lut, fmt_in, fmt_out, &map);
762
0
    if (ret < 0) {
763
0
        ff_sws_lut3d_free(&lut);
764
0
        return ret;
765
0
    }
766
767
0
    return ff_sws_graph_add_pass(graph, fmt_out, src.width, src.height,
768
0
                                 input, 0, 1, run_lut3d, setup_lut3d, lut,
769
0
                                 free_lut3d, output);
770
0
}
771
772
/***************************************
773
 * Main filter graph construction code *
774
 ***************************************/
775
776
static int init_passes(SwsGraph *graph)
777
0
{
778
0
    SwsFormat src = graph->src;
779
0
    SwsFormat dst = graph->dst;
780
0
    SwsPass *pass = NULL; /* read from main input image */
781
0
    int ret;
782
783
0
    ret = adapt_colors(graph, &src, &dst, pass, &pass);
784
0
    if (ret < 0)
785
0
        return ret;
786
0
    src.format = pass ? pass->format : src.format;
787
0
    src.color  = dst.color;
788
789
0
    if (!ff_fmt_equal(&src, &dst)) {
790
0
        ret = add_convert_pass(graph, &src, &dst, pass, &pass);
791
0
        if (ret < 0)
792
0
            return ret;
793
0
    }
794
795
0
    if (pass)
796
0
        return 0;
797
798
    /* No passes were added, so no operations were necessary */
799
0
    graph->noop = 1;
800
801
    /* Add threaded memcpy pass */
802
0
    return ff_sws_graph_add_pass(graph, dst.format, dst.width, dst.height,
803
0
                                 pass, 0, 1, run_copy, NULL, NULL, NULL, &pass);
804
0
}
805
806
static void sws_graph_worker(void *priv, int jobnr, int threadnr, int nb_jobs,
807
                             int nb_threads)
808
0
{
809
0
    SwsGraph *graph = priv;
810
0
    const SwsPass *pass = graph->exec.pass;
811
0
    const int slice_y = jobnr * pass->slice_h;
812
0
    const int slice_h = FFMIN(pass->slice_h, pass->lines - slice_y);
813
814
0
    pass->run(graph->exec.output, graph->exec.input, slice_y, slice_h, pass);
815
0
}
816
817
SwsGraph *ff_sws_graph_alloc(void)
818
0
{
819
0
    return av_mallocz(sizeof(SwsGraph));
820
0
}
821
822
static void graph_uninit(SwsGraph *graph)
823
0
{
824
0
    avpriv_slicethread_free(&graph->slicethread);
825
826
0
    for (int i = 0; i < graph->num_passes; i++)
827
0
        pass_free(graph->passes[i]);
828
0
    av_free(graph->passes);
829
830
0
    memset(graph, 0, sizeof(*graph));
831
0
}
832
833
int ff_sws_graph_init(SwsGraph *graph, SwsContext *ctx, const SwsFormat *dst,
834
                      const SwsFormat *src)
835
0
{
836
0
    int ret;
837
0
    if (graph->ctx) {
838
0
        av_log(ctx, AV_LOG_ERROR, "Graph is already initialized\n");
839
0
        return AVERROR(EINVAL);
840
0
    }
841
842
0
    graph->ctx = ctx;
843
0
    graph->src = *src;
844
0
    graph->dst = *dst;
845
0
    graph->opts_copy = *ctx;
846
0
    av_assert0(src->interlaced == dst->interlaced);
847
0
    av_assert0(src->field      == dst->field);
848
849
0
    if (ctx->threads == 1) {
850
0
        graph->num_threads = 1;
851
0
    } else {
852
0
        ret = avpriv_slicethread_create(&graph->slicethread, (void *) graph,
853
0
                                        sws_graph_worker, NULL, ctx->threads);
854
0
        if (ret == AVERROR(ENOSYS)) {
855
            /* Fall back to single threaded operation */
856
0
            graph->num_threads = 1;
857
0
        } else if (ret < 0) {
858
0
            goto error;
859
0
        } else {
860
0
            graph->num_threads = ret;
861
0
        }
862
0
    }
863
864
0
    ret = init_passes(graph);
865
0
    if (ret < 0)
866
0
        goto error;
867
868
    /* Resolve output buffers for all intermediate passes */
869
0
    for (int i = 0; i < graph->num_passes; i++) {
870
0
        graph->backend |= graph->passes[i]->backend;
871
0
        ret = pass_alloc_output(graph->passes[i]->input);
872
0
        if (ret < 0)
873
0
            goto error;
874
0
    }
875
876
0
    return 0;
877
878
0
error:
879
0
    graph_uninit(graph);
880
0
    return ret;
881
0
}
882
883
void ff_sws_graph_rollback(SwsGraph *graph, int since_idx)
884
0
{
885
0
    for (int i = since_idx; i < graph->num_passes; i++)
886
0
        pass_free(graph->passes[i]);
887
0
    graph->num_passes = since_idx;
888
0
}
889
890
void ff_sws_graph_free(SwsGraph **pgraph)
891
0
{
892
0
    SwsGraph *graph = *pgraph;
893
0
    if (!graph)
894
0
        return;
895
896
0
    graph_uninit(graph);
897
0
    av_free(graph);
898
0
    *pgraph = NULL;
899
0
}
900
901
/* Tests only options relevant to SwsGraph */
902
static int opts_equal(const SwsContext *c1, const SwsContext *c2)
903
0
{
904
0
    return c1->flags         == c2->flags         &&
905
0
           c1->threads       == c2->threads       &&
906
0
           c1->dither        == c2->dither        &&
907
0
           c1->alpha_blend   == c2->alpha_blend   &&
908
0
           c1->gamma_flag    == c2->gamma_flag    &&
909
0
           c1->src_h_chr_pos == c2->src_h_chr_pos &&
910
0
           c1->src_v_chr_pos == c2->src_v_chr_pos &&
911
0
           c1->dst_h_chr_pos == c2->dst_h_chr_pos &&
912
0
           c1->dst_v_chr_pos == c2->dst_v_chr_pos &&
913
0
           c1->intent        == c2->intent        &&
914
0
           c1->scaler        == c2->scaler        &&
915
0
           c1->scaler_sub    == c2->scaler_sub    &&
916
0
           c1->backends      == c2->backends      &&
917
0
           !memcmp(c1->scaler_params, c2->scaler_params, sizeof(c1->scaler_params));
918
919
0
}
920
921
int ff_sws_graph_reinit(SwsGraph *graph, SwsContext *ctx, const SwsFormat *dst,
922
                        const SwsFormat *src)
923
0
{
924
0
    if (ff_fmt_equal(&graph->src, src) && ff_fmt_equal(&graph->dst, dst) &&
925
0
        opts_equal(ctx, &graph->opts_copy))
926
0
    {
927
0
        ff_sws_graph_update_metadata(graph, &src->color);
928
0
        return 0;
929
0
    }
930
931
0
    graph_uninit(graph);
932
0
    return ff_sws_graph_init(graph, ctx, dst, src);
933
0
}
934
935
void ff_sws_graph_update_metadata(SwsGraph *graph, const SwsColor *color)
936
0
{
937
0
    if (!color)
938
0
        return;
939
940
0
    ff_color_update_dynamic(&graph->src.color, color);
941
0
}
942
943
static void get_field(SwsGraph *graph, const SwsFormat *fmt,
944
                      const AVFrame *avframe, SwsFrame *frame)
945
0
{
946
0
    ff_sws_frame_from_avframe(frame, avframe);
947
948
0
    if (!(avframe->flags & AV_FRAME_FLAG_INTERLACED)) {
949
0
        av_assert1(!fmt->field);
950
0
        return;
951
0
    }
952
953
0
    if (fmt->field == FIELD_BOTTOM) {
954
        /* Odd rows, offset by one line */
955
0
        const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
956
0
        for (int i = 0; i < 4; i++) {
957
0
            if (frame->data[i])
958
0
                frame->data[i] += frame->linesize[i];
959
0
            if (desc->flags & AV_PIX_FMT_FLAG_PAL)
960
0
                break;
961
0
        }
962
0
    }
963
964
    /* Take only every second line */
965
0
    for (int i = 0; i < 4; i++)
966
0
        frame->linesize[i] <<= 1;
967
968
0
    frame->height = (frame->height + (fmt->field == FIELD_TOP)) >> 1;
969
0
}
970
971
int ff_sws_graph_run(SwsGraph *graph, const AVFrame *dst, const AVFrame *src)
972
0
{
973
0
    av_assert0(dst->format == graph->dst.hw_format || dst->format == graph->dst.format);
974
0
    av_assert0(src->format == graph->src.hw_format || src->format == graph->src.format);
975
976
0
    SwsFrame src_field, dst_field;
977
0
    get_field(graph, &graph->dst, dst, &dst_field);
978
0
    get_field(graph, &graph->src, src, &src_field);
979
980
0
    for (int i = 0; i < graph->num_passes; i++) {
981
0
        const SwsPass *pass = graph->passes[i];
982
0
        graph->exec.pass   = pass;
983
0
        graph->exec.input  = pass->input ? &pass->input->output->frame : &src_field;
984
0
        graph->exec.output = pass->output->avframe ? &pass->output->frame : &dst_field;
985
0
        if (pass->setup) {
986
0
            int ret = pass->setup(graph->exec.output, graph->exec.input, pass);
987
0
            if (ret < 0)
988
0
                return ret;
989
0
        }
990
991
0
        if (pass->num_slices == 1) {
992
0
            pass->run(graph->exec.output, graph->exec.input, 0, pass->lines, pass);
993
0
        } else {
994
0
            avpriv_slicethread_execute(graph->slicethread, pass->num_slices, 0);
995
0
        }
996
0
    }
997
998
0
    return 0;
999
0
}