PR #26387 opened by michaelni
URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/26387
Patch URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/26387.patch


>From f2bb42fd69d48f583547389dbec5cdb6577e2d40 Mon Sep 17 00:00:00 2001
From: Raja-89 <[email protected]>
Date: Mon, 27 Jul 2026 21:50:47 +0530
Subject: [PATCH 01/18] avfilter/dnn: prevent crash on parameterless LibTorch
 models

When loading a TorchScript model that does not contain any learnable
parameters (e.g., a purely functional model), the Torch backend would
crash during inference. This occurred because the code attempted to
dereference the first iterator of the model's parameter list
`parameters().begin()` to determine the device, which results in
Undefined Behavior when the parameter list is empty.
This commit fixes the issue by determining the inference device directly
from the user-configured `ctx->device` string instead of probing the
model parameters, allowing parameterless models to execute safely.

Testing:
1. Generate a parameterless model:
cat << 'EOF' > generate_model.py
import torch
class DummyModel(torch.nn.Module):
    def forward(self, x):
        return x
scripted_model = torch.jit.script(DummyModel())
scripted_model.save("dummy_model.pt")
EOF
python3 generate_model.py
2. Run inference (previously crashed, now succeeds):
./ffmpeg -y -i input.mp4 -vf 
'format=rgb24,dnn_processing=dnn_backend=torch:model=dummy_model.pt' -frames:v 
5 -f null -
Signed-off-by: Raja Rathour <[email protected]>

(cherry picked from commit a234fc1130e6b17d550371dede849918202a303a)
Signed-off-by: Michael Niedermayer <[email protected]>
---
 libavfilter/dnn/dnn_backend_torch.cpp | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/libavfilter/dnn/dnn_backend_torch.cpp 
b/libavfilter/dnn/dnn_backend_torch.cpp
index 5f16234b8e2..0cbfc1a2c35 100644
--- a/libavfilter/dnn/dnn_backend_torch.cpp
+++ b/libavfilter/dnn/dnn_backend_torch.cpp
@@ -248,7 +248,8 @@ static int th_start_inference(void *args)
         return DNN_GENERIC_ERROR;
     }
     // Transfer tensor to the same device as model
-    c10::Device device = (*th_model->jit_model->parameters().begin()).device();
+    const char *device_name = ctx->device ? ctx->device : "cpu";
+    c10::Device device(device_name);
     if (infer_request->input_tensor->device() != device)
         *infer_request->input_tensor = infer_request->input_tensor->to(device);
     inputs.push_back(*infer_request->input_tensor);
-- 
2.54.1


>From 4553c80c6a8bdc898dabd37053e3c16a8a142f54 Mon Sep 17 00:00:00 2001
From: Guo Yejun <[email protected]>
Date: Sun, 26 Jul 2026 16:25:58 +0800
Subject: [PATCH 02/18] avfilter/dnn: fix race when querying queue length

Replace av_usleep polling with a condition variable wait.

(cherry picked from commit a7e72069f15efbef1e25b25d35c4e0511b43262e)
Signed-off-by: Michael Niedermayer <[email protected]>
---
 libavfilter/dnn/dnn_backend_common.c |  5 ++---
 libavfilter/dnn/safe_queue.c         | 11 +++++++++++
 libavfilter/dnn/safe_queue.h         |  8 ++++++++
 3 files changed, 21 insertions(+), 3 deletions(-)

diff --git a/libavfilter/dnn/dnn_backend_common.c 
b/libavfilter/dnn/dnn_backend_common.c
index 4d6752ae335..82627c7a962 100644
--- a/libavfilter/dnn/dnn_backend_common.c
+++ b/libavfilter/dnn/dnn_backend_common.c
@@ -22,7 +22,6 @@
  */
 
 #include "libavutil/mem.h"
-#include "libavutil/time.h"
 #include "dnn_backend_common.h"
 
 #define DNN_ASYNC_SUCCESS (void *)0
@@ -107,8 +106,8 @@ void ff_dnn_wait_requests(SafeQueue *request_queue, int 
nireq)
 {
     if (!request_queue)
         return;
-    while (ff_safe_queue_size(request_queue) < nireq)
-        av_usleep(10000);
+
+    ff_safe_queue_wait_for_size(request_queue, nireq);
 }
 
 int ff_dnn_start_inference_async(void *ctx, DNNAsyncExecModule *async_module)
diff --git a/libavfilter/dnn/safe_queue.c b/libavfilter/dnn/safe_queue.c
index e962d4cb7e4..f7aa31d42e6 100644
--- a/libavfilter/dnn/safe_queue.c
+++ b/libavfilter/dnn/safe_queue.c
@@ -82,6 +82,17 @@ size_t ff_safe_queue_size(SafeQueue *sq)
     return sq ? ff_queue_size(sq->q) : 0;
 }
 
+void ff_safe_queue_wait_for_size(SafeQueue *sq, size_t min_size)
+{
+    if (!sq)
+        return;
+
+    ff_mutex_lock(&sq->mutex);
+    while (ff_queue_size(sq->q) < min_size)
+        dnn_cond_wait(&sq->cond, &sq->mutex);
+    ff_mutex_unlock(&sq->mutex);
+}
+
 int ff_safe_queue_push_front(SafeQueue *sq, void *v)
 {
     int ret;
diff --git a/libavfilter/dnn/safe_queue.h b/libavfilter/dnn/safe_queue.h
index 577a02e24d2..b0b32d90e0a 100644
--- a/libavfilter/dnn/safe_queue.h
+++ b/libavfilter/dnn/safe_queue.h
@@ -47,6 +47,14 @@ void ff_safe_queue_destroy(SafeQueue *sq);
  */
 size_t ff_safe_queue_size(SafeQueue *sq);
 
+/**
+ * @brief Wait until queue length reaches at least min_size.
+ *
+ * @param sq pointer to the SafeQueue
+ * @param min_size target queue length
+ */
+void ff_safe_queue_wait_for_size(SafeQueue *sq, size_t min_size);
+
 /**
  * @brief Add data to the head of queue in the
  * SafeQueue after locking mutex. After adding
-- 
2.54.1


>From 04fc4bd5df14582208038d65c7dfb7213afc9973 Mon Sep 17 00:00:00 2001
From: Diego de Souza <[email protected]>
Date: Wed, 8 Jul 2026 21:22:24 +0000
Subject: [PATCH 03/18] avfilter/vf_scale_cuda: select separable passes per
 plane

Plan luma and chroma passes from their sampling geometry. Allocate
intermediate storage only for planes needing horizontal scaling and
inherit untouched input textures.

Use virtual chroma extents to handle odd sizes and subsampling changes.

Signed-off-by: Diego de Souza <[email protected]>
(cherry picked from commit 255276f780c3deeda1730acf42e4254a68e81833)
Signed-off-by: Michael Niedermayer <[email protected]>
---
 libavfilter/vf_scale_cuda.c | 382 ++++++++++++++++++++++++------------
 1 file changed, 261 insertions(+), 121 deletions(-)

diff --git a/libavfilter/vf_scale_cuda.c b/libavfilter/vf_scale_cuda.c
index 36c53288bee..9d6f14f13ec 100644
--- a/libavfilter/vf_scale_cuda.c
+++ b/libavfilter/vf_scale_cuda.c
@@ -96,6 +96,24 @@ enum {
     FILTER_NB,
 };
 
+enum {
+    CUDA_SCALE_DIR_NONE = -1,
+    CUDA_SCALE_DIR_X,
+    CUDA_SCALE_DIR_Y,
+};
+
+enum {
+    CUDA_SCALE_PLANE_PRIMARY = 1 << 0,
+    CUDA_SCALE_PLANE_CHROMA  = 1 << 1,
+};
+
+typedef struct CUDAScalePassPlan {
+    int dir[FILTER_NB];
+    /* Plane groups whose sample grids change along each axis. */
+    unsigned int x_planes;
+    unsigned int y_planes;
+} CUDAScalePassPlan;
+
 typedef struct CUDAScaleFilter {
     CUdeviceptr weights; ///< float[dst_size][filter_size]
     CUdeviceptr offsets; ///< int[dst_size]
@@ -156,12 +174,81 @@ typedef struct CUDAScaleContext {
     CUDAScaleFilter filters[FILTER_NB];
     CUDAScaleFilter filters_uv[FILTER_NB];
     CUDATex inter_tex;
+    CUDAScalePassPlan pass_plan;
     int use_filters; /* -1 for auto */
-    int pass_x, pass_y;
 
     float param;
 } CUDAScaleContext;
 
+/*
+ * Compare the unrounded plane scale. AV_CEIL_RSHIFT() can hide a change
+ * in sample geometry for odd dimensions: 3px 4:4:4 -> 5px 4:2:0 has
+ * three stored chroma samples on each side, but the virtual plane size
+ * changes from 3 to 2.5 and still requires filtering.
+ */
+static int cudascale_plane_needs_scale(int in_size, int out_size,
+                                       int in_sub, int out_sub)
+{
+    return (int64_t)out_size * (1 << in_sub) !=
+           (int64_t)in_size  * (1 << out_sub);
+}
+
+static int cudascale_plane_is_downscaled(int in_size, int out_size,
+                                         int in_sub, int out_sub)
+{
+    return (int64_t)out_size * (1 << in_sub) <
+           (int64_t)in_size  * (1 << out_sub);
+}
+
+static double cudascale_plane_virtual_size(int src_size,
+                                           int in_size, int out_size,
+                                           int in_sub, int out_sub)
+{
+    return src_size * ((double) out_size / in_size) *
+           (1 << in_sub) / (1 << out_sub);
+}
+
+static void cudascale_plan_passes(CUDAScalePassPlan *plan,
+                                  int in_width, int in_height,
+                                  int out_width, int out_height,
+                                  int in_sub_x, int in_sub_y,
+                                  int out_sub_x, int out_sub_y,
+                                  int has_chroma)
+{
+    unsigned int x_planes = 0;
+    unsigned int y_planes = 0;
+
+    *plan = (CUDAScalePassPlan) {
+        .dir = { CUDA_SCALE_DIR_NONE, CUDA_SCALE_DIR_NONE },
+    };
+
+    if (cudascale_plane_needs_scale(in_width, out_width, 0, 0))
+        x_planes |= CUDA_SCALE_PLANE_PRIMARY;
+    if (cudascale_plane_needs_scale(in_height, out_height, 0, 0))
+        y_planes |= CUDA_SCALE_PLANE_PRIMARY;
+
+    if (has_chroma) {
+        if (cudascale_plane_needs_scale(in_width, out_width,
+                                        in_sub_x, out_sub_x))
+            x_planes |= CUDA_SCALE_PLANE_CHROMA;
+        if (cudascale_plane_needs_scale(in_height, out_height,
+                                        in_sub_y, out_sub_y))
+            y_planes |= CUDA_SCALE_PLANE_CHROMA;
+    }
+
+    plan->x_planes = x_planes;
+    plan->y_planes = y_planes;
+
+    if (x_planes && y_planes) {
+        plan->dir[FILTER_TMP] = CUDA_SCALE_DIR_X;
+        plan->dir[FILTER_OUT] = CUDA_SCALE_DIR_Y;
+    } else if (x_planes) {
+        plan->dir[FILTER_OUT] = CUDA_SCALE_DIR_X;
+    } else if (y_planes) {
+        plan->dir[FILTER_OUT] = CUDA_SCALE_DIR_Y;
+    }
+}
+
 static av_cold int cudascale_init(AVFilterContext *ctx)
 {
     CUDAScaleContext *s = ctx->priv;
@@ -264,7 +351,8 @@ fail:
     return ret;
 }
 
-static av_cold int inter_buf_init(AVFilterContext *ctx, int out_width, int 
in_height)
+static av_cold int inter_buf_init(AVFilterContext *ctx, int out_width, int 
in_height,
+                                  unsigned int planes)
 {
     CUDAScaleContext *s = ctx->priv;
     CudaFunctions *cu = s->hwctx->internal->cuda_dl;
@@ -282,6 +370,8 @@ static av_cold int inter_buf_init(AVFilterContext *ctx, int 
out_width, int in_he
 
     for (int i = 0; i < s->in_planes; i++) {
         const int is_chroma = i == 1 || i == 2;
+        const unsigned int plane = is_chroma ? CUDA_SCALE_PLANE_CHROMA :
+                                               CUDA_SCALE_PLANE_PRIMARY;
         const int sub_x   = is_chroma ? s->inter_tex.log2_chroma_w : 0;
         const int sub_y   = is_chroma ? s->inter_tex.log2_chroma_h : 0;
         const int plane_w = AV_CEIL_RSHIFT(out_width, sub_x);
@@ -289,6 +379,9 @@ static av_cold int inter_buf_init(AVFilterContext *ctx, int 
out_width, int in_he
         const int sizeof_pixel = (s->in_plane_depths[i] <= 8 ? 1 : 2) *
                                   s->in_plane_channels[i];
 
+        if (!(planes & plane))
+            continue;
+
         size_t pitch;
         ret = CHECK_CU(cu->cuMemAllocPitch(&s->inter_tex.data[i], &pitch,
                                            (size_t) plane_w * sizeof_pixel,
@@ -369,32 +462,6 @@ static av_cold void set_format_info(AVFilterContext *ctx, 
enum AVPixelFormat in_
     }
 }
 
-static av_cold void cudascale_setup_passes(AVFilterContext *ctx)
-{
-    CUDAScaleContext *s = ctx->priv;
-    AVFilterLink  *inlink = ctx->inputs[0];
-    AVFilterLink *outlink = ctx->outputs[0];
-
-    s->pass_x = s->pass_y = -1;
-    if (!s->use_filters)
-        return;
-
-    const int scale_x = inlink->w != outlink->w ||
-                        s->in_desc->log2_chroma_w != 
s->out_desc->log2_chroma_w;
-    const int scale_y = inlink->h != outlink->h ||
-                        s->in_desc->log2_chroma_h != 
s->out_desc->log2_chroma_h;
-
-    if (scale_x && scale_y) {
-        /* Always perform the horizontal scaling pass first */
-        s->pass_x = FILTER_TMP;
-        s->pass_y = FILTER_OUT;
-    } else if (scale_x) {
-        s->pass_x = FILTER_OUT;
-    } else {
-        s->pass_y = FILTER_OUT;
-    }
-}
-
 static av_cold int init_processing_chain(AVFilterContext *ctx, int in_width, 
int in_height,
                                          int out_width, int out_height)
 {
@@ -429,6 +496,13 @@ static av_cold int init_processing_chain(AVFilterContext 
*ctx, int in_width, int
     }
 
     set_format_info(ctx, in_format, out_format);
+    cudascale_plan_passes(&s->pass_plan,
+                          in_width, in_height, out_width, out_height,
+                          s->in_desc->log2_chroma_w,
+                          s->in_desc->log2_chroma_h,
+                          s->out_desc->log2_chroma_w,
+                          s->out_desc->log2_chroma_h,
+                          s->in_planes > 1 && s->out_planes > 1);
 
     if (s->passthrough && in_width == out_width && in_height == out_height && 
in_format == out_format) {
         s->frames_ctx = av_buffer_ref(inl->hw_frames_ctx);
@@ -447,24 +521,31 @@ static av_cold int init_processing_chain(AVFilterContext 
*ctx, int in_width, int
             in_format == out_format && s->interp_algo == INTERP_ALGO_DEFAULT)
             s->interp_algo = INTERP_ALGO_NEAREST;
 
-        if (s->interp_algo == INTERP_ALGO_NEAREST) {
+        if (!s->pass_plan.x_planes && !s->pass_plan.y_planes) {
             s->use_filters = 0;
-        } else if (s->use_filters < 0 && (
-                       out_width < in_width || out_height < in_height ||
-                       AV_CEIL_RSHIFT(out_width, s->out_desc->log2_chroma_w) < 
AV_CEIL_RSHIFT(in_width, s->in_desc->log2_chroma_w) ||
-                       AV_CEIL_RSHIFT(out_height, s->out_desc->log2_chroma_h) 
< AV_CEIL_RSHIFT(in_height, s->in_desc->log2_chroma_h)
-                   ))
-            s->use_filters = 1; /* downscaling; needed for anti-aliasing */
-        else if (s->use_filters < 0)
+        } else if (s->interp_algo == INTERP_ALGO_NEAREST) {
             s->use_filters = 0;
+        } else if (s->use_filters < 0) {
+            s->use_filters = cudascale_plane_is_downscaled(in_width, out_width,
+                                                            0, 0) ||
+                             cudascale_plane_is_downscaled(in_height, 
out_height,
+                                                           0, 0) ||
+                             (s->in_planes > 1 && s->out_planes > 1 &&
+                              (cudascale_plane_is_downscaled(
+                                   in_width, out_width,
+                                   s->in_desc->log2_chroma_w,
+                                   s->out_desc->log2_chroma_w) ||
+                               cudascale_plane_is_downscaled(
+                                   in_height, out_height,
+                                   s->in_desc->log2_chroma_h,
+                                   s->out_desc->log2_chroma_h)));
+        }
     }
 
     outl->hw_frames_ctx = av_buffer_ref(s->frames_ctx);
     if (!outl->hw_frames_ctx)
         return AVERROR(ENOMEM);
 
-    cudascale_setup_passes(ctx);
-
     return 0;
 }
 
@@ -480,42 +561,49 @@ static av_cold int 
cudascale_load_functions(AVFilterContext *ctx)
     const char *out_fmt_name = get_format_name(s->out_fmt);
 
     const char *function_infix = "";
+    const char *fixed_infix;
+    int fixed_use_linear;
+    int fixed_as_integer;
 
     extern const unsigned char ff_vf_scale_cuda_ptx_data[];
     extern const unsigned int ff_vf_scale_cuda_ptx_len;
 
+    switch (s->interp_algo) {
+    case INTERP_ALGO_NEAREST:
+        fixed_infix = "Nearest";
+        fixed_use_linear = 0;
+        fixed_as_integer = 1;
+        break;
+    case INTERP_ALGO_BILINEAR:
+        fixed_infix = "Bilinear";
+        fixed_use_linear = 1;
+        fixed_as_integer = 1;
+        break;
+    case INTERP_ALGO_DEFAULT:
+    case INTERP_ALGO_BICUBIC:
+        fixed_infix = "Bicubic";
+        fixed_use_linear = 0;
+        fixed_as_integer = 0;
+        break;
+    case INTERP_ALGO_LANCZOS:
+        fixed_infix = "Lanczos";
+        fixed_use_linear = 0;
+        fixed_as_integer = 0;
+        break;
+    default:
+        av_log(ctx, AV_LOG_ERROR, "Unknown interpolation algorithm\n");
+        return AVERROR_BUG;
+    }
+
     if (s->use_filters) {
-        /* Final pass is always vertical unless not vertically scaling */
-        function_infix = s->pass_y == FILTER_OUT ? "Generic_v" : "Generic_h";
+        function_infix = s->pass_plan.dir[FILTER_OUT] == CUDA_SCALE_DIR_X ?
+                         "Generic_h" : "Generic_v";
         s->interp_use_linear = 0;
         s->interp_as_integer = 0;
     } else {
-        switch(s->interp_algo) {
-        case INTERP_ALGO_NEAREST:
-            function_infix = "Nearest";
-            s->interp_use_linear = 0;
-            s->interp_as_integer = 1;
-            break;
-        case INTERP_ALGO_BILINEAR:
-            function_infix = "Bilinear";
-            s->interp_use_linear = 1;
-            s->interp_as_integer = 1;
-            break;
-        case INTERP_ALGO_DEFAULT:
-        case INTERP_ALGO_BICUBIC:
-            function_infix = "Bicubic";
-            s->interp_use_linear = 0;
-            s->interp_as_integer = 0;
-            break;
-        case INTERP_ALGO_LANCZOS:
-            function_infix = "Lanczos";
-            s->interp_use_linear = 0;
-            s->interp_as_integer = 0;
-            break;
-        default:
-            av_log(ctx, AV_LOG_ERROR, "Unknown interpolation algorithm\n");
-            return AVERROR_BUG;
-        }
+        function_infix = fixed_infix;
+        s->interp_use_linear = fixed_use_linear;
+        s->interp_as_integer = fixed_as_integer;
     }
 
     ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_ctx));
@@ -544,15 +632,23 @@ static av_cold int 
cudascale_load_functions(AVFilterContext *ctx)
 
     if (s->use_filters) {
         /* Intermediate pass is always horizontal */
-        snprintf(buf, sizeof(buf), "Subsample_Generic_h_%s_%s", in_fmt_name, 
in_fmt_name);
-        ret = CHECK_CU(cu->cuModuleGetFunction(&s->cu_func[FILTER_TMP], 
s->cu_module, buf));
-        if (ret < 0)
-            goto fail;
+        if (s->filters[FILTER_TMP].weights) {
+            snprintf(buf, sizeof(buf), "Subsample_Generic_h_%s_%s",
+                     in_fmt_name, in_fmt_name);
+            ret = CHECK_CU(cu->cuModuleGetFunction(&s->cu_func[FILTER_TMP],
+                                                   s->cu_module, buf));
+            if (ret < 0)
+                goto fail;
+        }
 
-        snprintf(buf, sizeof(buf), "Subsample_Generic_h_%s_%s_uv", 
in_fmt_name, in_fmt_name);
-        ret = CHECK_CU(cu->cuModuleGetFunction(&s->cu_func_uv[FILTER_TMP], 
s->cu_module, buf));
-        if (ret < 0)
-            goto fail;
+        if (s->filters_uv[FILTER_TMP].weights) {
+            snprintf(buf, sizeof(buf), "Subsample_Generic_h_%s_%s_uv",
+                     in_fmt_name, in_fmt_name);
+            ret = CHECK_CU(cu->cuModuleGetFunction(&s->cu_func_uv[FILTER_TMP],
+                                                   s->cu_module, buf));
+            if (ret < 0)
+                goto fail;
+        }
     }
 
 fail:
@@ -564,7 +660,7 @@ fail:
 static av_cold int cudascale_filter_init(AVFilterContext *ctx,
                                          CUDAScaleFilter *f,
                                          int src_size, int dst_size,
-                                         double virtual_size)
+                                         double virtual_size, int needs_scale)
 {
     CUDAScaleContext *s = ctx->priv;
     CudaFunctions *cu = s->hwctx->internal->cuda_dl;
@@ -576,17 +672,22 @@ static av_cold int cudascale_filter_init(AVFilterContext 
*ctx,
         .virtual_size  = virtual_size,
     };
 
-    switch (s->interp_algo) {
-    case INTERP_ALGO_NEAREST:  return 0; /* no weights needed */
-    case INTERP_ALGO_BILINEAR: params.scaler = SWS_SCALE_BILINEAR; break;
-    case INTERP_ALGO_LANCZOS:  params.scaler = SWS_SCALE_LANCZOS;  break;
-    case INTERP_ALGO_DEFAULT:
-    case INTERP_ALGO_BICUBIC:
-        params.scaler = SWS_SCALE_BICUBIC;
-        params.scaler_params[0] = params.scaler_params[1] = 0.0;
-        if (s->param != SCALE_CUDA_PARAM_DEFAULT)
-            params.scaler_params[1] = s->param;
-        break;
+    if (!needs_scale) {
+        params.scaler = SWS_SCALE_POINT;
+        params.virtual_size = 0.0;
+    } else {
+        switch (s->interp_algo) {
+        case INTERP_ALGO_NEAREST:  return 0; /* no weights needed */
+        case INTERP_ALGO_BILINEAR: params.scaler = SWS_SCALE_BILINEAR; break;
+        case INTERP_ALGO_LANCZOS:  params.scaler = SWS_SCALE_LANCZOS;  break;
+        case INTERP_ALGO_DEFAULT:
+        case INTERP_ALGO_BICUBIC:
+            params.scaler = SWS_SCALE_BICUBIC;
+            params.scaler_params[0] = params.scaler_params[1] = 0.0;
+            if (s->param != SCALE_CUDA_PARAM_DEFAULT)
+                params.scaler_params[1] = s->param;
+            break;
+        }
     }
 
     SwsFilterWeights *weights = NULL;
@@ -656,40 +757,66 @@ static av_cold int 
cudascale_setup_filters(AVFilterContext *ctx)
     if (ret < 0)
         return ret;
 
-    if (s->pass_x >= 0) {
-        ret = cudascale_filter_init(ctx, &s->filters[s->pass_x],
-                                    inlink->w, outlink->w, 0.0);
-        if (ret < 0)
-            goto fail;
-        if (s->in_planes > 1) {
+    const int has_chroma = s->in_planes > 1 && s->out_planes > 1;
+    const unsigned int all_planes = CUDA_SCALE_PLANE_PRIMARY |
+                                    (has_chroma ? CUDA_SCALE_PLANE_CHROMA : 0);
+    const int pass_x = s->pass_plan.dir[FILTER_TMP] == CUDA_SCALE_DIR_X ?
+                       FILTER_TMP :
+                       s->pass_plan.dir[FILTER_OUT] == CUDA_SCALE_DIR_X ?
+                       FILTER_OUT : -1;
+    const int pass_y = s->pass_plan.dir[FILTER_OUT] == CUDA_SCALE_DIR_Y ?
+                       FILTER_OUT : -1;
+
+    if (pass_x >= 0) {
+        const unsigned int planes = pass_x == FILTER_TMP ?
+                                    s->pass_plan.x_planes : all_planes;
+
+        if (planes & CUDA_SCALE_PLANE_PRIMARY) {
+            ret = cudascale_filter_init(ctx, &s->filters[pass_x],
+                                        inlink->w, outlink->w, 0.0,
+                                        !!(s->pass_plan.x_planes &
+                                           CUDA_SCALE_PLANE_PRIMARY));
+            if (ret < 0)
+                goto fail;
+        }
+        if (planes & CUDA_SCALE_PLANE_CHROMA) {
             const int src_size = AV_CEIL_RSHIFT(inlink->w,  in_sub_x);
             const int dst_size = AV_CEIL_RSHIFT(outlink->w, out_sub_x);
-            const double virtual_size = (double) outlink->w / (1 << out_sub_x);
-            ret = cudascale_filter_init(ctx, &s->filters_uv[s->pass_x],
-                                        src_size, dst_size, virtual_size);
+            const double virtual_size = cudascale_plane_virtual_size(
+                src_size, inlink->w, outlink->w, in_sub_x, out_sub_x);
+            ret = cudascale_filter_init(ctx, &s->filters_uv[pass_x],
+                                        src_size, dst_size, virtual_size,
+                                        !!(s->pass_plan.x_planes &
+                                           CUDA_SCALE_PLANE_CHROMA));
             if (ret < 0)
                 goto fail;
         }
     }
 
-    if (s->pass_y >= 0) {
-        ret = cudascale_filter_init(ctx, &s->filters[s->pass_y],
-                                    inlink->h, outlink->h, 0.0);
+    if (pass_y >= 0) {
+        ret = cudascale_filter_init(ctx, &s->filters[pass_y],
+                                    inlink->h, outlink->h, 0.0,
+                                    !!(s->pass_plan.y_planes &
+                                       CUDA_SCALE_PLANE_PRIMARY));
         if (ret < 0)
             goto fail;
-        if (s->in_planes > 1) {
+        if (all_planes & CUDA_SCALE_PLANE_CHROMA) {
             const int src_size = AV_CEIL_RSHIFT(inlink->h,  in_sub_y);
             const int dst_size = AV_CEIL_RSHIFT(outlink->h, out_sub_y);
-            const double virtual_size = (double) outlink->h / (1 << out_sub_y);
-            ret = cudascale_filter_init(ctx, &s->filters_uv[s->pass_y],
-                                        src_size, dst_size, virtual_size);
+            const double virtual_size = cudascale_plane_virtual_size(
+                src_size, inlink->h, outlink->h, in_sub_y, out_sub_y);
+            ret = cudascale_filter_init(ctx, &s->filters_uv[pass_y],
+                                        src_size, dst_size, virtual_size,
+                                        !!(s->pass_plan.y_planes &
+                                           CUDA_SCALE_PLANE_CHROMA));
             if (ret < 0)
                 goto fail;
         }
     }
 
-    if (s->pass_x == FILTER_TMP) {
-        ret = inter_buf_init(ctx, outlink->w, inlink->h);
+    if (pass_x == FILTER_TMP) {
+        ret = inter_buf_init(ctx, outlink->w, inlink->h,
+                             s->pass_plan.x_planes);
         if (ret < 0)
             goto fail;
     }
@@ -780,7 +907,7 @@ fail:
 /* if depths/channels are NULL, only maps pointers without creating textures */
 static int cuda_tex_map_frame(AVFilterContext *ctx, const AVFrame *frame,
                               const int depths[4], const int channels[4],
-                              CUDATex *tex)
+                              CUDATex *tex, int use_linear, int as_integer)
 {
     CUDAScaleContext *s = ctx->priv;
     CudaFunctions *cu = s->hwctx->internal->cuda_dl;
@@ -809,10 +936,10 @@ static int cuda_tex_map_frame(AVFilterContext *ctx, const 
AVFrame *frame,
             continue;
 
         CUDA_TEXTURE_DESC tex_desc = {
-            .filterMode = s->interp_use_linear ?
+            .filterMode = use_linear ?
                           CU_TR_FILTER_MODE_LINEAR :
                           CU_TR_FILTER_MODE_POINT,
-            .flags = s->interp_as_integer ? CU_TRSF_READ_AS_INTEGER : 0,
+            .flags = as_integer ? CU_TRSF_READ_AS_INTEGER : 0,
         };
 
         const int is_chroma = i == 1 || i == 2;
@@ -893,17 +1020,20 @@ static int scalecuda_resize(AVFilterContext *ctx, int 
pass,
     if (pass == FILTER_TMP)
         out_planes = s->in_planes;
 
-    // scale primary plane(s). Usually Y (and A), or single plane of RGB 
frames.
-    ret = call_resize_kernel(ctx, s->cu_func[pass],
-                             in->tex, in->crop_left, in->crop_top,
-                             in->crop_width, in->crop_height,
-                             out->data, out->width, out->height,
-                             out->linesize[0], mpeg_range,
-                             &s->filters[pass]);
-    if (ret < 0)
-        return ret;
+    if (pass != FILTER_TMP || s->filters[pass].weights) {
+        // scale primary plane(s). Usually Y (and A), or single plane of RGB 
frames.
+        ret = call_resize_kernel(ctx, s->cu_func[pass],
+                                 in->tex, in->crop_left, in->crop_top,
+                                 in->crop_width, in->crop_height,
+                                 out->data, out->width, out->height,
+                                 out->linesize[0], mpeg_range,
+                                 &s->filters[pass]);
+        if (ret < 0)
+            return ret;
+    }
 
-    if (out_planes > 1) {
+    if (out_planes > 1 &&
+        (pass != FILTER_TMP || s->filters_uv[pass].weights)) {
         // scale UV plane. Scale function sets both U and V plane, or singular 
interleaved plane.
         ret = call_resize_kernel(ctx, s->cu_func_uv[pass], in->tex,
                                  AV_CEIL_RSHIFT(in->crop_left, 
in->log2_chroma_w),
@@ -930,22 +1060,32 @@ static int cudascale_scale(AVFilterContext *ctx, AVFrame 
*out, AVFrame *in)
     int ret = 0;
 
     CUDATex in_tex = {0}, out_tex = {0};
-    ret = cuda_tex_map_frame(ctx, in, s->in_plane_depths, 
s->in_plane_channels, &in_tex);
+    ret = cuda_tex_map_frame(ctx, in, s->in_plane_depths,
+                             s->in_plane_channels, &in_tex,
+                             s->interp_use_linear, s->interp_as_integer);
     if (ret < 0)
         goto fail;
 
-    ret = cuda_tex_map_frame(ctx, s->frame, NULL, NULL, &out_tex);
+    ret = cuda_tex_map_frame(ctx, s->frame, NULL, NULL, &out_tex, 0, 0);
     if (ret < 0)
         goto fail;
 
     const CUDATex *src = &in_tex;
-    if (s->pass_x == FILTER_TMP) {
+    CUDATex inter_tex;
+    if (s->use_filters &&
+        s->pass_plan.dir[FILTER_TMP] != CUDA_SCALE_DIR_NONE) {
         /* Handle first pass separately */
         s->inter_tex.color_range = in->color_range;
+        inter_tex = s->inter_tex;
+        /* Reuse input textures for plane groups not touched by this pass. */
+        for (int i = 0; i < s->in_planes; i++) {
+            if (!inter_tex.tex[i])
+                inter_tex.tex[i] = in_tex.tex[i];
+        }
         ret = scalecuda_resize(ctx, FILTER_TMP, &s->inter_tex, src);
         if (ret < 0)
             goto fail;
-        src = &s->inter_tex;
+        src = &inter_tex;
     }
 
     ret = scalecuda_resize(ctx, FILTER_OUT, &out_tex, src);
-- 
2.54.1


>From 8295b5e94b82a218ec55da27b47c94ce4fb3caa0 Mon Sep 17 00:00:00 2001
From: Diego de Souza <[email protected]>
Date: Wed, 12 Aug 2026 17:14:10 +0200
Subject: [PATCH 04/18] avfilter/vf_scale_cuda: encapsulate generic filter
 resources

Group filter weights, the pass plan, and intermediate textures in a
replaceable filter set. Route generic kernel selection through the
active set and load both output directions so it owns all
geometry-dependent state.

Keep the requested use_filters value separate from the resolved mode.
Support a one-tap generic copy when no plane needs scaling.

Signed-off-by: Diego de Souza <[email protected]>
(cherry picked from commit 41045c5c6ab8d37dbb6ff971ad3377ccd5eeeb83)
Signed-off-by: Michael Niedermayer <[email protected]>
---
 libavfilter/vf_scale_cuda.c | 319 ++++++++++++++++++++++--------------
 1 file changed, 199 insertions(+), 120 deletions(-)

diff --git a/libavfilter/vf_scale_cuda.c b/libavfilter/vf_scale_cuda.c
index 9d6f14f13ec..1e46d14e987 100644
--- a/libavfilter/vf_scale_cuda.c
+++ b/libavfilter/vf_scale_cuda.c
@@ -24,6 +24,7 @@
 #include <stdio.h>
 #include <string.h>
 
+#include "libavutil/avassert.h"
 #include "libavutil/common.h"
 #include "libavutil/hwcontext.h"
 #include "libavutil/hwcontext_cuda_internal.h"
@@ -132,6 +133,14 @@ typedef struct CUDATex {
     int         external_data;
 } CUDATex;
 
+typedef struct CUDAScaleFilterSet {
+    CUDAScaleFilter filters[FILTER_NB];
+    CUDAScaleFilter filters_uv[FILTER_NB];
+    CUDATex inter_tex;
+    CUDAScalePassPlan pass_plan;
+    unsigned int tmp_planes;
+} CUDAScaleFilterSet;
+
 typedef struct CUDAScaleContext {
     const AVClass *class;
 
@@ -163,19 +172,21 @@ typedef struct CUDAScaleContext {
 
     CUcontext   cu_ctx;
     CUmodule    cu_module;
-    CUfunction  cu_func[FILTER_NB];
-    CUfunction  cu_func_uv[FILTER_NB];
+    CUfunction  cu_func_fixed;
+    CUfunction  cu_func_fixed_uv;
+    CUfunction  cu_func_out[2];
+    CUfunction  cu_func_out_uv[2];
+    CUfunction  cu_func_tmp;
+    CUfunction  cu_func_tmp_uv;
     CUstream    cu_stream;
 
     int interp_algo;
     int interp_use_linear;
     int interp_as_integer;
 
-    CUDAScaleFilter filters[FILTER_NB];
-    CUDAScaleFilter filters_uv[FILTER_NB];
-    CUDATex inter_tex;
-    CUDAScalePassPlan pass_plan;
-    int use_filters; /* -1 for auto */
+    CUDAScaleFilterSet filter_set;
+    int use_filters;
+    int use_filters_opt; /* -1 for auto */
 
     float param;
 } CUDAScaleContext;
@@ -285,6 +296,17 @@ static void cuda_tex_uninit(CudaFunctions *cu, CUDATex *t)
     memset(t, 0, sizeof(*t));
 }
 
+static av_cold void filter_set_uninit(CudaFunctions *cu,
+                                      CUDAScaleFilterSet *set)
+{
+    cuda_tex_uninit(cu, &set->inter_tex);
+    for (int i = 0; i < FF_ARRAY_ELEMS(set->filters); i++) {
+        filter_uninit(cu, &set->filters[i]);
+        filter_uninit(cu, &set->filters_uv[i]);
+    }
+    memset(set, 0, sizeof(*set));
+}
+
 static av_cold void cudascale_uninit(AVFilterContext *ctx)
 {
     CUDAScaleContext *s = ctx->priv;
@@ -295,11 +317,7 @@ static av_cold void cudascale_uninit(AVFilterContext *ctx)
 
         CHECK_CU(cu->cuCtxPushCurrent(s->hwctx->cuda_ctx));
 
-        cuda_tex_uninit(cu, &s->inter_tex);
-        for (int i = 0; i < FF_ARRAY_ELEMS(s->filters); i++) {
-            filter_uninit(cu, &s->filters[i]);
-            filter_uninit(cu, &s->filters_uv[i]);
-        }
+        filter_set_uninit(cu, &s->filter_set);
 
         if (s->cu_module) {
             CHECK_CU(cu->cuModuleUnload(s->cu_module));
@@ -351,15 +369,15 @@ fail:
     return ret;
 }
 
-static av_cold int inter_buf_init(AVFilterContext *ctx, int out_width, int 
in_height,
+static av_cold int inter_buf_init(AVFilterContext *ctx, CUDATex *tex,
+                                  int out_width, int in_height,
                                   unsigned int planes)
 {
     CUDAScaleContext *s = ctx->priv;
     CudaFunctions *cu = s->hwctx->internal->cuda_dl;
     int ret = 0;
 
-    cuda_tex_uninit(cu, &s->inter_tex);
-    s->inter_tex = (CUDATex) {
+    *tex = (CUDATex) {
         .width          = out_width,
         .height         = in_height,
         .crop_width     = out_width,
@@ -372,8 +390,8 @@ static av_cold int inter_buf_init(AVFilterContext *ctx, int 
out_width, int in_he
         const int is_chroma = i == 1 || i == 2;
         const unsigned int plane = is_chroma ? CUDA_SCALE_PLANE_CHROMA :
                                                CUDA_SCALE_PLANE_PRIMARY;
-        const int sub_x   = is_chroma ? s->inter_tex.log2_chroma_w : 0;
-        const int sub_y   = is_chroma ? s->inter_tex.log2_chroma_h : 0;
+        const int sub_x   = is_chroma ? tex->log2_chroma_w : 0;
+        const int sub_y   = is_chroma ? tex->log2_chroma_h : 0;
         const int plane_w = AV_CEIL_RSHIFT(out_width, sub_x);
         const int plane_h = AV_CEIL_RSHIFT(in_height, sub_y);
         const int sizeof_pixel = (s->in_plane_depths[i] <= 8 ? 1 : 2) *
@@ -383,12 +401,12 @@ static av_cold int inter_buf_init(AVFilterContext *ctx, 
int out_width, int in_he
             continue;
 
         size_t pitch;
-        ret = CHECK_CU(cu->cuMemAllocPitch(&s->inter_tex.data[i], &pitch,
+        ret = CHECK_CU(cu->cuMemAllocPitch(&tex->data[i], &pitch,
                                            (size_t) plane_w * sizeof_pixel,
                                            plane_h, 16));
         if (ret < 0)
             goto fail;
-        s->inter_tex.linesize[i] = pitch;
+        tex->linesize[i] = pitch;
 
         CUDA_TEXTURE_DESC tex_desc = {
             /* inter tex is always read as float */
@@ -401,13 +419,13 @@ static av_cold int inter_buf_init(AVFilterContext *ctx, 
int out_width, int in_he
                                   CU_AD_FORMAT_UNSIGNED_INT8 :
                                   CU_AD_FORMAT_UNSIGNED_INT16,
             .res.pitch2D.numChannels  = s->in_plane_channels[i],
-            .res.pitch2D.devPtr       = s->inter_tex.data[i],
+            .res.pitch2D.devPtr       = tex->data[i],
             .res.pitch2D.pitchInBytes = pitch,
             .res.pitch2D.width        = plane_w,
             .res.pitch2D.height       = plane_h,
         };
 
-        ret = CHECK_CU(cu->cuTexObjectCreate(&s->inter_tex.tex[i], &res_desc,
+        ret = CHECK_CU(cu->cuTexObjectCreate(&tex->tex[i], &res_desc,
                                              &tex_desc, NULL));
         if (ret < 0)
             goto fail;
@@ -416,7 +434,7 @@ static av_cold int inter_buf_init(AVFilterContext *ctx, int 
out_width, int in_he
     return 0;
 
 fail:
-    cuda_tex_uninit(cu, &s->inter_tex);
+    cuda_tex_uninit(cu, tex);
     return ret;
 }
 
@@ -496,14 +514,6 @@ static av_cold int init_processing_chain(AVFilterContext 
*ctx, int in_width, int
     }
 
     set_format_info(ctx, in_format, out_format);
-    cudascale_plan_passes(&s->pass_plan,
-                          in_width, in_height, out_width, out_height,
-                          s->in_desc->log2_chroma_w,
-                          s->in_desc->log2_chroma_h,
-                          s->out_desc->log2_chroma_w,
-                          s->out_desc->log2_chroma_h,
-                          s->in_planes > 1 && s->out_planes > 1);
-
     if (s->passthrough && in_width == out_width && in_height == out_height && 
in_format == out_format) {
         s->frames_ctx = av_buffer_ref(inl->hw_frames_ctx);
         if (!s->frames_ctx)
@@ -518,14 +528,15 @@ static av_cold int init_processing_chain(AVFilterContext 
*ctx, int in_width, int
             return ret;
 
         if (in_width == out_width && in_height == out_height &&
-            in_format == out_format && s->interp_algo == INTERP_ALGO_DEFAULT)
+            in_format == out_format && s->interp_algo == INTERP_ALGO_DEFAULT &&
+            s->use_filters_opt != 1)
             s->interp_algo = INTERP_ALGO_NEAREST;
 
-        if (!s->pass_plan.x_planes && !s->pass_plan.y_planes) {
+        if (s->interp_algo == INTERP_ALGO_NEAREST) {
             s->use_filters = 0;
-        } else if (s->interp_algo == INTERP_ALGO_NEAREST) {
-            s->use_filters = 0;
-        } else if (s->use_filters < 0) {
+        } else if (s->use_filters_opt >= 0) {
+            s->use_filters = s->use_filters_opt;
+        } else {
             s->use_filters = cudascale_plane_is_downscaled(in_width, out_width,
                                                             0, 0) ||
                              cudascale_plane_is_downscaled(in_height, 
out_height,
@@ -560,7 +571,6 @@ static av_cold int cudascale_load_functions(AVFilterContext 
*ctx)
     const char *in_fmt_name = get_format_name(s->in_fmt);
     const char *out_fmt_name = get_format_name(s->out_fmt);
 
-    const char *function_infix = "";
     const char *fixed_infix;
     int fixed_use_linear;
     int fixed_as_integer;
@@ -595,17 +605,6 @@ static av_cold int 
cudascale_load_functions(AVFilterContext *ctx)
         return AVERROR_BUG;
     }
 
-    if (s->use_filters) {
-        function_infix = s->pass_plan.dir[FILTER_OUT] == CUDA_SCALE_DIR_X ?
-                         "Generic_h" : "Generic_v";
-        s->interp_use_linear = 0;
-        s->interp_as_integer = 0;
-    } else {
-        function_infix = fixed_infix;
-        s->interp_use_linear = fixed_use_linear;
-        s->interp_as_integer = fixed_as_integer;
-    }
-
     ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_ctx));
     if (ret < 0)
         return ret;
@@ -615,42 +614,70 @@ static av_cold int 
cudascale_load_functions(AVFilterContext *ctx)
     if (ret < 0)
         goto fail;
 
-    snprintf(buf, sizeof(buf), "Subsample_%s_%s_%s", function_infix, 
in_fmt_name, out_fmt_name);
-    ret = CHECK_CU(cu->cuModuleGetFunction(&s->cu_func[FILTER_OUT], 
s->cu_module, buf));
-    if (ret < 0) {
-        av_log(ctx, AV_LOG_FATAL, "Unsupported conversion: %s -> %s\n", 
in_fmt_name, out_fmt_name);
-        ret = AVERROR(ENOSYS);
-        goto fail;
-    }
-    av_log(ctx, AV_LOG_DEBUG, "Luma filter: %s (%s -> %s)\n", buf, 
av_get_pix_fmt_name(s->in_fmt), av_get_pix_fmt_name(s->out_fmt));
-
-    snprintf(buf, sizeof(buf), "Subsample_%s_%s_%s_uv", function_infix, 
in_fmt_name, out_fmt_name);
-    ret = CHECK_CU(cu->cuModuleGetFunction(&s->cu_func_uv[FILTER_OUT], 
s->cu_module, buf));
-    if (ret < 0)
-        goto fail;
-    av_log(ctx, AV_LOG_DEBUG, "Chroma filter: %s (%s -> %s)\n", buf, 
av_get_pix_fmt_name(s->in_fmt), av_get_pix_fmt_name(s->out_fmt));
-
     if (s->use_filters) {
-        /* Intermediate pass is always horizontal */
-        if (s->filters[FILTER_TMP].weights) {
-            snprintf(buf, sizeof(buf), "Subsample_Generic_h_%s_%s",
-                     in_fmt_name, in_fmt_name);
-            ret = CHECK_CU(cu->cuModuleGetFunction(&s->cu_func[FILTER_TMP],
+        static const char *const infix[] = { "Generic_h", "Generic_v" };
+        const char *tmp_infix = "Generic_h";
+
+        s->interp_use_linear = 0;
+        s->interp_as_integer = 0;
+
+        for (int dir = CUDA_SCALE_DIR_X; dir <= CUDA_SCALE_DIR_Y; dir++) {
+            snprintf(buf, sizeof(buf), "Subsample_%s_%s_%s",
+                     infix[dir], in_fmt_name, out_fmt_name);
+            ret = CHECK_CU(cu->cuModuleGetFunction(&s->cu_func_out[dir],
                                                    s->cu_module, buf));
             if (ret < 0)
-                goto fail;
+                goto unsupported;
+
+            snprintf(buf, sizeof(buf), "Subsample_%s_%s_%s_uv",
+                     infix[dir], in_fmt_name, out_fmt_name);
+            ret = CHECK_CU(cu->cuModuleGetFunction(&s->cu_func_out_uv[dir],
+                                                   s->cu_module, buf));
+            if (ret < 0)
+                goto unsupported;
         }
 
-        if (s->filters_uv[FILTER_TMP].weights) {
-            snprintf(buf, sizeof(buf), "Subsample_Generic_h_%s_%s_uv",
+        snprintf(buf, sizeof(buf), "Subsample_%s_%s_%s", tmp_infix,
+                 in_fmt_name, in_fmt_name);
+        ret = CHECK_CU(cu->cuModuleGetFunction(&s->cu_func_tmp,
+                                               s->cu_module, buf));
+        if (ret < 0)
+            goto unsupported;
+
+        if (s->in_planes > 1) {
+            snprintf(buf, sizeof(buf), "Subsample_%s_%s_%s_uv", tmp_infix,
                      in_fmt_name, in_fmt_name);
-            ret = CHECK_CU(cu->cuModuleGetFunction(&s->cu_func_uv[FILTER_TMP],
+            ret = CHECK_CU(cu->cuModuleGetFunction(&s->cu_func_tmp_uv,
                                                    s->cu_module, buf));
             if (ret < 0)
-                goto fail;
+                goto unsupported;
         }
+    } else {
+        s->interp_use_linear = fixed_use_linear;
+        s->interp_as_integer = fixed_as_integer;
+
+        snprintf(buf, sizeof(buf), "Subsample_%s_%s_%s", fixed_infix,
+                 in_fmt_name, out_fmt_name);
+        ret = CHECK_CU(cu->cuModuleGetFunction(&s->cu_func_fixed,
+                                               s->cu_module, buf));
+        if (ret < 0)
+            goto unsupported;
+
+        snprintf(buf, sizeof(buf), "Subsample_%s_%s_%s_uv", fixed_infix,
+                 in_fmt_name, out_fmt_name);
+        ret = CHECK_CU(cu->cuModuleGetFunction(&s->cu_func_fixed_uv,
+                                               s->cu_module, buf));
+        if (ret < 0)
+            goto unsupported;
     }
 
+    goto fail;
+
+unsupported:
+    av_log(ctx, AV_LOG_FATAL, "Unsupported conversion: %s -> %s\n",
+           in_fmt_name, out_fmt_name);
+    ret = AVERROR(ENOSYS);
+
 fail:
     CHECK_CU(cu->cuCtxPopCurrent(&dummy));
 
@@ -739,13 +766,12 @@ fail:
     return ret;
 }
 
-static av_cold int cudascale_setup_filters(AVFilterContext *ctx)
+static av_cold int cudascale_filter_set_init(AVFilterContext *ctx,
+                                             CUDAScaleFilterSet *set,
+                                             int in_width, int in_height)
 {
     CUDAScaleContext *s = ctx->priv;
-    AVFilterLink  *inlink = ctx->inputs[0];
     AVFilterLink *outlink = ctx->outputs[0];
-    CudaFunctions *cu = s->hwctx->internal->cuda_dl;
-    CUcontext dummy;
     int ret;
 
     const int in_sub_x  = s->in_desc->log2_chroma_w;
@@ -753,40 +779,52 @@ static av_cold int 
cudascale_setup_filters(AVFilterContext *ctx)
     const int out_sub_x = s->out_desc->log2_chroma_w;
     const int out_sub_y = s->out_desc->log2_chroma_h;
 
-    ret = CHECK_CU(cu->cuCtxPushCurrent(s->hwctx->cuda_ctx));
-    if (ret < 0)
-        return ret;
-
     const int has_chroma = s->in_planes > 1 && s->out_planes > 1;
     const unsigned int all_planes = CUDA_SCALE_PLANE_PRIMARY |
                                     (has_chroma ? CUDA_SCALE_PLANE_CHROMA : 0);
-    const int pass_x = s->pass_plan.dir[FILTER_TMP] == CUDA_SCALE_DIR_X ?
-                       FILTER_TMP :
-                       s->pass_plan.dir[FILTER_OUT] == CUDA_SCALE_DIR_X ?
-                       FILTER_OUT : -1;
-    const int pass_y = s->pass_plan.dir[FILTER_OUT] == CUDA_SCALE_DIR_Y ?
-                       FILTER_OUT : -1;
+    int pass_x, pass_y;
+
+    cudascale_plan_passes(&set->pass_plan,
+                          in_width, in_height, outlink->w, outlink->h,
+                          in_sub_x, in_sub_y, out_sub_x, out_sub_y,
+                          has_chroma);
+
+    /* The generic path also handles non-scaling copies and format
+     * conversions with a one-tap horizontal filter. */
+    if (set->pass_plan.dir[FILTER_OUT] == CUDA_SCALE_DIR_NONE)
+        set->pass_plan.dir[FILTER_OUT] = CUDA_SCALE_DIR_X;
+
+    pass_x = set->pass_plan.dir[FILTER_TMP] == CUDA_SCALE_DIR_X ?
+             FILTER_TMP :
+             set->pass_plan.dir[FILTER_OUT] == CUDA_SCALE_DIR_X ?
+             FILTER_OUT : -1;
+    pass_y = set->pass_plan.dir[FILTER_OUT] == CUDA_SCALE_DIR_Y ?
+             FILTER_OUT : -1;
 
     if (pass_x >= 0) {
         const unsigned int planes = pass_x == FILTER_TMP ?
-                                    s->pass_plan.x_planes : all_planes;
+                                    set->pass_plan.x_planes :
+                                    all_planes;
+
+        if (pass_x == FILTER_TMP)
+            set->tmp_planes = planes;
 
         if (planes & CUDA_SCALE_PLANE_PRIMARY) {
-            ret = cudascale_filter_init(ctx, &s->filters[pass_x],
-                                        inlink->w, outlink->w, 0.0,
-                                        !!(s->pass_plan.x_planes &
+            ret = cudascale_filter_init(ctx, &set->filters[pass_x],
+                                        in_width, outlink->w, 0.0,
+                                        !!(set->pass_plan.x_planes &
                                            CUDA_SCALE_PLANE_PRIMARY));
             if (ret < 0)
                 goto fail;
         }
         if (planes & CUDA_SCALE_PLANE_CHROMA) {
-            const int src_size = AV_CEIL_RSHIFT(inlink->w,  in_sub_x);
+            const int src_size = AV_CEIL_RSHIFT(in_width,  in_sub_x);
             const int dst_size = AV_CEIL_RSHIFT(outlink->w, out_sub_x);
             const double virtual_size = cudascale_plane_virtual_size(
-                src_size, inlink->w, outlink->w, in_sub_x, out_sub_x);
-            ret = cudascale_filter_init(ctx, &s->filters_uv[pass_x],
+                src_size, in_width, outlink->w, in_sub_x, out_sub_x);
+            ret = cudascale_filter_init(ctx, &set->filters_uv[pass_x],
                                         src_size, dst_size, virtual_size,
-                                        !!(s->pass_plan.x_planes &
+                                        !!(set->pass_plan.x_planes &
                                            CUDA_SCALE_PLANE_CHROMA));
             if (ret < 0)
                 goto fail;
@@ -794,20 +832,20 @@ static av_cold int 
cudascale_setup_filters(AVFilterContext *ctx)
     }
 
     if (pass_y >= 0) {
-        ret = cudascale_filter_init(ctx, &s->filters[pass_y],
-                                    inlink->h, outlink->h, 0.0,
-                                    !!(s->pass_plan.y_planes &
+        ret = cudascale_filter_init(ctx, &set->filters[pass_y],
+                                    in_height, outlink->h, 0.0,
+                                    !!(set->pass_plan.y_planes &
                                        CUDA_SCALE_PLANE_PRIMARY));
         if (ret < 0)
             goto fail;
         if (all_planes & CUDA_SCALE_PLANE_CHROMA) {
-            const int src_size = AV_CEIL_RSHIFT(inlink->h,  in_sub_y);
+            const int src_size = AV_CEIL_RSHIFT(in_height,  in_sub_y);
             const int dst_size = AV_CEIL_RSHIFT(outlink->h, out_sub_y);
             const double virtual_size = cudascale_plane_virtual_size(
-                src_size, inlink->h, outlink->h, in_sub_y, out_sub_y);
-            ret = cudascale_filter_init(ctx, &s->filters_uv[pass_y],
+                src_size, in_height, outlink->h, in_sub_y, out_sub_y);
+            ret = cudascale_filter_init(ctx, &set->filters_uv[pass_y],
                                         src_size, dst_size, virtual_size,
-                                        !!(s->pass_plan.y_planes &
+                                        !!(set->pass_plan.y_planes &
                                            CUDA_SCALE_PLANE_CHROMA));
             if (ret < 0)
                 goto fail;
@@ -815,8 +853,9 @@ static av_cold int cudascale_setup_filters(AVFilterContext 
*ctx)
     }
 
     if (pass_x == FILTER_TMP) {
-        ret = inter_buf_init(ctx, outlink->w, inlink->h,
-                             s->pass_plan.x_planes);
+        ret = inter_buf_init(ctx, &set->inter_tex,
+                             outlink->w, in_height,
+                             set->tmp_planes);
         if (ret < 0)
             goto fail;
     }
@@ -824,6 +863,24 @@ static av_cold int cudascale_setup_filters(AVFilterContext 
*ctx)
     ret = 0;
 
 fail:
+    return ret;
+}
+
+static av_cold int cudascale_setup_filters(AVFilterContext *ctx,
+                                           int in_width, int in_height)
+{
+    CUDAScaleContext *s = ctx->priv;
+    CudaFunctions *cu = s->hwctx->internal->cuda_dl;
+    CUcontext dummy;
+    int ret;
+
+    ret = CHECK_CU(cu->cuCtxPushCurrent(s->hwctx->cuda_ctx));
+    if (ret < 0)
+        return ret;
+
+    ret = cudascale_filter_set_init(ctx, &s->filter_set,
+                                    in_width, in_height);
+
     CHECK_CU(cu->cuCtxPopCurrent(&dummy));
     return ret;
 }
@@ -889,7 +946,7 @@ static av_cold int cudascale_config_props(AVFilterLink 
*outlink)
            s->passthrough ? " (passthrough)" : "");
 
     if (s->use_filters) {
-        ret = cudascale_setup_filters(ctx);
+        ret = cudascale_setup_filters(ctx, inlink->w, inlink->h);
         if (ret < 0)
             return ret;
     }
@@ -1009,33 +1066,55 @@ static int call_resize_kernel(AVFilterContext *ctx, 
CUfunction func,
                                        BLOCKX, BLOCKY, 1, 0, s->cu_stream, 
args, NULL));
 }
 
-static int scalecuda_resize(AVFilterContext *ctx, int pass,
+static int scalecuda_resize(AVFilterContext *ctx,
+                            const CUDAScaleFilterSet *set, int pass,
                             const CUDATex *out, const CUDATex *in)
 {
     CUDAScaleContext *s = ctx->priv;
+    const CUDAScaleFilter *filter = NULL;
+    const CUDAScaleFilter *filter_uv = NULL;
+    CUfunction func, func_uv;
     int mpeg_range = in->color_range != AVCOL_RANGE_JPEG;
     int ret;
 
     int out_planes = s->out_planes;
-    if (pass == FILTER_TMP)
+    if (pass == FILTER_TMP) {
         out_planes = s->in_planes;
+        func    = s->cu_func_tmp;
+        func_uv = s->cu_func_tmp_uv;
+    } else if (s->use_filters) {
+        const int dir = set->pass_plan.dir[FILTER_OUT];
 
-    if (pass != FILTER_TMP || s->filters[pass].weights) {
+        av_assert0(dir == CUDA_SCALE_DIR_X || dir == CUDA_SCALE_DIR_Y);
+        func    = s->cu_func_out[dir];
+        func_uv = s->cu_func_out_uv[dir];
+    } else {
+        func    = s->cu_func_fixed;
+        func_uv = s->cu_func_fixed_uv;
+    }
+
+    if (s->use_filters) {
+        filter    = &set->filters[pass];
+        filter_uv = &set->filters_uv[pass];
+    }
+
+    if (pass != FILTER_TMP ||
+        (set->tmp_planes & CUDA_SCALE_PLANE_PRIMARY)) {
         // scale primary plane(s). Usually Y (and A), or single plane of RGB 
frames.
-        ret = call_resize_kernel(ctx, s->cu_func[pass],
+        ret = call_resize_kernel(ctx, func,
                                  in->tex, in->crop_left, in->crop_top,
                                  in->crop_width, in->crop_height,
                                  out->data, out->width, out->height,
-                                 out->linesize[0], mpeg_range,
-                                 &s->filters[pass]);
+                                 out->linesize[0], mpeg_range, filter);
         if (ret < 0)
             return ret;
     }
 
     if (out_planes > 1 &&
-        (pass != FILTER_TMP || s->filters_uv[pass].weights)) {
+        (pass != FILTER_TMP ||
+         (set->tmp_planes & CUDA_SCALE_PLANE_CHROMA))) {
         // scale UV plane. Scale function sets both U and V plane, or singular 
interleaved plane.
-        ret = call_resize_kernel(ctx, s->cu_func_uv[pass], in->tex,
+        ret = call_resize_kernel(ctx, func_uv, in->tex,
                                  AV_CEIL_RSHIFT(in->crop_left, 
in->log2_chroma_w),
                                  AV_CEIL_RSHIFT(in->crop_top, 
in->log2_chroma_h),
                                  AV_CEIL_RSHIFT(in->crop_width, 
in->log2_chroma_w),
@@ -1043,8 +1122,7 @@ static int scalecuda_resize(AVFilterContext *ctx, int 
pass,
                                  out->data,
                                  AV_CEIL_RSHIFT(out->width, 
out->log2_chroma_w),
                                  AV_CEIL_RSHIFT(out->height, 
out->log2_chroma_h),
-                                 out->linesize[1], mpeg_range,
-                                 &s->filters_uv[pass]);
+                                 out->linesize[1], mpeg_range, filter_uv);
         if (ret < 0)
             return ret;
     }
@@ -1073,22 +1151,23 @@ static int cudascale_scale(AVFilterContext *ctx, 
AVFrame *out, AVFrame *in)
     const CUDATex *src = &in_tex;
     CUDATex inter_tex;
     if (s->use_filters &&
-        s->pass_plan.dir[FILTER_TMP] != CUDA_SCALE_DIR_NONE) {
+        s->filter_set.pass_plan.dir[FILTER_TMP] != CUDA_SCALE_DIR_NONE) {
         /* Handle first pass separately */
-        s->inter_tex.color_range = in->color_range;
-        inter_tex = s->inter_tex;
+        s->filter_set.inter_tex.color_range = in->color_range;
+        inter_tex = s->filter_set.inter_tex;
         /* Reuse input textures for plane groups not touched by this pass. */
         for (int i = 0; i < s->in_planes; i++) {
             if (!inter_tex.tex[i])
                 inter_tex.tex[i] = in_tex.tex[i];
         }
-        ret = scalecuda_resize(ctx, FILTER_TMP, &s->inter_tex, src);
+        ret = scalecuda_resize(ctx, &s->filter_set, FILTER_TMP,
+                               &s->filter_set.inter_tex, src);
         if (ret < 0)
             goto fail;
         src = &inter_tex;
     }
 
-    ret = scalecuda_resize(ctx, FILTER_OUT, &out_tex, src);
+    ret = scalecuda_resize(ctx, &s->filter_set, FILTER_OUT, &out_tex, src);
     if (ret < 0)
         goto fail;
 
@@ -1185,7 +1264,7 @@ static const AVOption options[] = {
         { "lanczos",  "lanczos",  0, AV_OPT_TYPE_CONST, { .i64 = 
INTERP_ALGO_LANCZOS  }, 0, 0, FLAGS, .unit = "interp_algo" },
     { "format", "Output video pixel format", OFFSET(format), 
AV_OPT_TYPE_PIXEL_FMT, { .i64 = AV_PIX_FMT_NONE }, INT_MIN, INT_MAX, 
.flags=FLAGS },
     { "passthrough", "Do not process frames at all if parameters match", 
OFFSET(passthrough), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, FLAGS },
-    { "use_filters", "Use generic filters instead of fixed function kernels", 
OFFSET(use_filters), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, FLAGS, .unit = 
"use_filters" },
+    { "use_filters", "Use generic filters instead of fixed function kernels", 
OFFSET(use_filters_opt), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, FLAGS, .unit = 
"use_filters" },
         { "auto",    NULL,  0, AV_OPT_TYPE_CONST, {.i64 = -1}, 0, 0, FLAGS, 
.unit = "use_filters" },
     { "param", "Algorithm-Specific parameter", OFFSET(param), 
AV_OPT_TYPE_FLOAT, { .dbl = SCALE_CUDA_PARAM_DEFAULT }, -FLT_MAX, FLT_MAX, 
FLAGS },
     { "force_original_aspect_ratio", "decrease or increase w/h if necessary to 
keep the original AR", OFFSET(force_original_aspect_ratio), AV_OPT_TYPE_INT, { 
.i64 = 0 }, 0, SCALE_FORCE_OAR_NB-1, FLAGS, .unit = "force_oar" },
-- 
2.54.1


>From 2815d24da902785c25d44f4488df4d5467eb3487 Mon Sep 17 00:00:00 2001
From: Diego de Souza <[email protected]>
Date: Wed, 12 Aug 2026 17:15:17 +0200
Subject: [PATCH 05/18] avfilter/vf_scale_cuda: regenerate filters for cropped
 frames

Generic filter coefficients depend on visible input dimensions, which
can change through per-frame crop metadata. Rebuild the filter set when
that geometry changes and synchronize before freeing active CUDA
resources.

Match av_frame_apply_cropping() for subsampled planes by flooring crop
origins while rounding visible extents up. This prevents odd left or top
crops from shifting chroma by one sample.

Clear applied cropping and size-dependent side data from the output.
Use visible dimensions when updating the sample aspect ratio.

Signed-off-by: Diego de Souza <[email protected]>
(cherry picked from commit a2b7a8210e3fbffbbb959752f832484b57864325)
Signed-off-by: Michael Niedermayer <[email protected]>
---
 libavfilter/vf_scale_cuda.c | 146 ++++++++++++++++++++++++++++++------
 1 file changed, 124 insertions(+), 22 deletions(-)

diff --git a/libavfilter/vf_scale_cuda.c b/libavfilter/vf_scale_cuda.c
index 1e46d14e987..d527783f568 100644
--- a/libavfilter/vf_scale_cuda.c
+++ b/libavfilter/vf_scale_cuda.c
@@ -139,6 +139,8 @@ typedef struct CUDAScaleFilterSet {
     CUDATex inter_tex;
     CUDAScalePassPlan pass_plan;
     unsigned int tmp_planes;
+    int in_width, in_height;
+    int normalize_crop;
 } CUDAScaleFilterSet;
 
 typedef struct CUDAScaleContext {
@@ -296,8 +298,7 @@ static void cuda_tex_uninit(CudaFunctions *cu, CUDATex *t)
     memset(t, 0, sizeof(*t));
 }
 
-static av_cold void filter_set_uninit(CudaFunctions *cu,
-                                      CUDAScaleFilterSet *set)
+static void filter_set_uninit(CudaFunctions *cu, CUDAScaleFilterSet *set)
 {
     cuda_tex_uninit(cu, &set->inter_tex);
     for (int i = 0; i < FF_ARRAY_ELEMS(set->filters); i++) {
@@ -369,9 +370,9 @@ fail:
     return ret;
 }
 
-static av_cold int inter_buf_init(AVFilterContext *ctx, CUDATex *tex,
-                                  int out_width, int in_height,
-                                  unsigned int planes)
+static int inter_buf_init(AVFilterContext *ctx, CUDATex *tex,
+                          int out_width, int in_height,
+                          unsigned int planes)
 {
     CUDAScaleContext *s = ctx->priv;
     CudaFunctions *cu = s->hwctx->internal->cuda_dl;
@@ -684,10 +685,10 @@ fail:
     return ret;
 }
 
-static av_cold int cudascale_filter_init(AVFilterContext *ctx,
-                                         CUDAScaleFilter *f,
-                                         int src_size, int dst_size,
-                                         double virtual_size, int needs_scale)
+static int cudascale_filter_init(AVFilterContext *ctx,
+                                 CUDAScaleFilter *f,
+                                 int src_size, int dst_size,
+                                 double virtual_size, int needs_scale)
 {
     CUDAScaleContext *s = ctx->priv;
     CudaFunctions *cu = s->hwctx->internal->cuda_dl;
@@ -766,9 +767,10 @@ fail:
     return ret;
 }
 
-static av_cold int cudascale_filter_set_init(AVFilterContext *ctx,
-                                             CUDAScaleFilterSet *set,
-                                             int in_width, int in_height)
+static int cudascale_filter_set_init(AVFilterContext *ctx,
+                                     CUDAScaleFilterSet *set,
+                                     int in_width, int in_height,
+                                     int normalize_crop)
 {
     CUDAScaleContext *s = ctx->priv;
     AVFilterLink *outlink = ctx->outputs[0];
@@ -784,6 +786,10 @@ static av_cold int 
cudascale_filter_set_init(AVFilterContext *ctx,
                                     (has_chroma ? CUDA_SCALE_PLANE_CHROMA : 0);
     int pass_x, pass_y;
 
+    set->in_width       = in_width;
+    set->in_height      = in_height;
+    set->normalize_crop = normalize_crop;
+
     cudascale_plan_passes(&set->pass_plan,
                           in_width, in_height, outlink->w, outlink->h,
                           in_sub_x, in_sub_y, out_sub_x, out_sub_y,
@@ -803,7 +809,8 @@ static av_cold int 
cudascale_filter_set_init(AVFilterContext *ctx,
 
     if (pass_x >= 0) {
         const unsigned int planes = pass_x == FILTER_TMP ?
-                                    set->pass_plan.x_planes :
+                                    (normalize_crop ? all_planes :
+                                                      set->pass_plan.x_planes) 
:
                                     all_planes;
 
         if (pass_x == FILTER_TMP)
@@ -866,6 +873,48 @@ fail:
     return ret;
 }
 
+static int cudascale_prepare_filter_set(AVFilterContext *ctx,
+                                        int in_width, int in_height,
+                                        int normalize_crop)
+{
+    CUDAScaleContext *s = ctx->priv;
+    CudaFunctions *cu = s->hwctx->internal->cuda_dl;
+    CUDAScaleFilterSet next = { 0 };
+    CUDAScaleFilterSet old;
+    int ret;
+
+    if (s->filter_set.in_width == in_width &&
+        s->filter_set.in_height == in_height &&
+        s->filter_set.normalize_crop == normalize_crop)
+        return 0;
+
+    ret = cudascale_filter_set_init(ctx, &next, in_width, in_height,
+                                    normalize_crop);
+    if (ret < 0)
+        goto fail;
+
+    if (s->filter_set.in_width) {
+        /* Queued kernels may still reference the active LUTs and texture. */
+        ret = CHECK_CU(cu->cuStreamSynchronize(s->cu_stream));
+        if (ret < 0)
+            goto fail;
+    }
+
+    old = s->filter_set;
+    s->filter_set = next;
+    memset(&next, 0, sizeof(next));
+    filter_set_uninit(cu, &old);
+
+    av_log(ctx, AV_LOG_VERBOSE,
+           "Prepared generic filters for visible input %dx%d%s\n",
+           in_width, in_height, normalize_crop ? " (cropped)" : "");
+    return 0;
+
+fail:
+    filter_set_uninit(cu, &next);
+    return ret;
+}
+
 static av_cold int cudascale_setup_filters(AVFilterContext *ctx,
                                            int in_width, int in_height)
 {
@@ -878,8 +927,7 @@ static av_cold int cudascale_setup_filters(AVFilterContext 
*ctx,
     if (ret < 0)
         return ret;
 
-    ret = cudascale_filter_set_init(ctx, &s->filter_set,
-                                    in_width, in_height);
+    ret = cudascale_prepare_filter_set(ctx, in_width, in_height, 0);
 
     CHECK_CU(cu->cuCtxPopCurrent(&dummy));
     return ret;
@@ -961,6 +1009,36 @@ fail:
     return ret;
 }
 
+static int cudascale_frame_geometry(AVFilterContext *ctx, const AVFrame *frame,
+                                    int *width, int *height,
+                                    int *normalize_crop)
+{
+    AVFilterLink *inlink = ctx->inputs[0];
+    size_t frame_width, frame_height;
+
+    if (frame->width <= 0 || frame->height <= 0) {
+        av_log(ctx, AV_LOG_ERROR, "Invalid crop rectangle\n");
+        return AVERROR(EINVAL);
+    }
+
+    frame_width  = frame->width;
+    frame_height = frame->height;
+    if (frame->crop_left >= frame_width ||
+        frame->crop_right >= frame_width - frame->crop_left ||
+        frame->crop_top >= frame_height ||
+        frame->crop_bottom >= frame_height - frame->crop_top) {
+        av_log(ctx, AV_LOG_ERROR, "Invalid crop rectangle\n");
+        return AVERROR(EINVAL);
+    }
+
+    *width  = (int)(frame_width  - frame->crop_left - frame->crop_right);
+    *height = (int)(frame_height - frame->crop_top  - frame->crop_bottom);
+    *normalize_crop = frame->crop_left || frame->crop_top ||
+                      *width != inlink->w || *height != inlink->h;
+
+    return 0;
+}
+
 /* if depths/channels are NULL, only maps pointers without creating textures */
 static int cuda_tex_map_frame(AVFilterContext *ctx, const AVFrame *frame,
                               const int depths[4], const int channels[4],
@@ -1114,9 +1192,11 @@ static int scalecuda_resize(AVFilterContext *ctx,
         (pass != FILTER_TMP ||
          (set->tmp_planes & CUDA_SCALE_PLANE_CHROMA))) {
         // scale UV plane. Scale function sets both U and V plane, or singular 
interleaved plane.
+        /* Match av_frame_apply_cropping(): subsampled plane origins round
+         * down, while visible plane extents round up. */
         ret = call_resize_kernel(ctx, func_uv, in->tex,
-                                 AV_CEIL_RSHIFT(in->crop_left, 
in->log2_chroma_w),
-                                 AV_CEIL_RSHIFT(in->crop_top, 
in->log2_chroma_h),
+                                 in->crop_left >> in->log2_chroma_w,
+                                 in->crop_top  >> in->log2_chroma_h,
                                  AV_CEIL_RSHIFT(in->crop_width, 
in->log2_chroma_w),
                                  AV_CEIL_RSHIFT(in->crop_height, 
in->log2_chroma_h),
                                  out->data,
@@ -1130,13 +1210,21 @@ static int scalecuda_resize(AVFilterContext *ctx,
     return 0;
 }
 
-static int cudascale_scale(AVFilterContext *ctx, AVFrame *out, AVFrame *in)
+static int cudascale_scale(AVFilterContext *ctx, AVFrame *out, AVFrame *in,
+                           int in_width, int in_height, int normalize_crop)
 {
     CUDAScaleContext *s = ctx->priv;
     CudaFunctions *cu = s->hwctx->internal->cuda_dl;
     AVFilterLink *outlink = ctx->outputs[0];
     int ret = 0;
 
+    if (s->use_filters) {
+        ret = cudascale_prepare_filter_set(ctx, in_width, in_height,
+                                           normalize_crop);
+        if (ret < 0)
+            return ret;
+    }
+
     CUDATex in_tex = {0}, out_tex = {0};
     ret = cuda_tex_map_frame(ctx, in, s->in_plane_depths,
                              s->in_plane_channels, &in_tex,
@@ -1185,7 +1273,14 @@ static int cudascale_scale(AVFilterContext *ctx, AVFrame 
*out, AVFrame *in)
     if (ret < 0)
         goto fail;
 
-    if (out->width != in->width || out->height != in->height) {
+    out->crop_top    = 0;
+    out->crop_bottom = 0;
+    out->crop_left   = 0;
+    out->crop_right  = 0;
+
+    if (in->crop_left || in->crop_right ||
+        in->crop_top  || in->crop_bottom ||
+        out->width != in_width || out->height != in_height) {
         av_frame_side_data_remove_by_props(&out->side_data, &out->nb_side_data,
                                            AV_SIDE_DATA_PROP_SIZE_DEPENDENT);
     }
@@ -1205,11 +1300,17 @@ static int cudascale_filter_frame(AVFilterLink *link, 
AVFrame *in)
 
     AVFrame *out = NULL;
     CUcontext dummy;
+    int in_width, in_height, normalize_crop;
     int ret = 0;
 
     if (s->passthrough)
         return ff_filter_frame(outlink, in);
 
+    ret = cudascale_frame_geometry(ctx, in, &in_width, &in_height,
+                                   &normalize_crop);
+    if (ret < 0)
+        goto fail;
+
     out = av_frame_alloc();
     if (!out) {
         ret = AVERROR(ENOMEM);
@@ -1220,7 +1321,8 @@ static int cudascale_filter_frame(AVFilterLink *link, 
AVFrame *in)
     if (ret < 0)
         goto fail;
 
-    ret = cudascale_scale(ctx, out, in);
+    ret = cudascale_scale(ctx, out, in, in_width, in_height,
+                          normalize_crop);
 
     CHECK_CU(cu->cuCtxPopCurrent(&dummy));
     if (ret < 0)
@@ -1230,8 +1332,8 @@ static int cudascale_filter_frame(AVFilterLink *link, 
AVFrame *in)
         out->sample_aspect_ratio = (AVRational){1, 1};
     } else {
         av_reduce(&out->sample_aspect_ratio.num, &out->sample_aspect_ratio.den,
-                  (int64_t)in->sample_aspect_ratio.num * outlink->h * link->w,
-                  (int64_t)in->sample_aspect_ratio.den * outlink->w * link->h,
+                  (int64_t)in->sample_aspect_ratio.num * outlink->h * in_width,
+                  (int64_t)in->sample_aspect_ratio.den * outlink->w * 
in_height,
                   INT_MAX);
     }
 
-- 
2.54.1


>From 7fd1ecee5f895f3cb7f58e16e0b26481ba445aaf Mon Sep 17 00:00:00 2001
From: Diego de Souza <[email protected]>
Date: Fri, 10 Jul 2026 19:24:08 +0200
Subject: [PATCH 06/18] avfilter/vf_scale_cuda: quantize generic output to
 source depth

Clamp generic-filter output to the logical source depth before restoring
its storage alignment. This prevents filter overshoot from setting
padding bits in formats such as P010 and P012.

Signed-off-by: Diego de Souza <[email protected]>
(cherry picked from commit c4887d9de309d14e6ead84a730a6b7e7e3996434)
Signed-off-by: Michael Niedermayer <[email protected]>
---
 libavfilter/vf_scale_cuda.c  |  5 +++++
 libavfilter/vf_scale_cuda.cu | 26 ++++++++++++++++++--------
 libavfilter/vf_scale_cuda.h  |  2 ++
 3 files changed, 25 insertions(+), 8 deletions(-)

diff --git a/libavfilter/vf_scale_cuda.c b/libavfilter/vf_scale_cuda.c
index d527783f568..6f924b42a68 100644
--- a/libavfilter/vf_scale_cuda.c
+++ b/libavfilter/vf_scale_cuda.c
@@ -1129,6 +1129,11 @@ static int call_resize_kernel(AVFilterContext *ctx, 
CUfunction func,
         .src_height = src_height,
         .param = s->param,
         .mpeg_range = mpeg_range,
+        /* Supported input formats use the same depth and shift for
+         * every component. */
+        .src_depth = s->in_desc->comp[0].depth,
+        .src_storage_max = ((1U << s->in_desc->comp[0].depth) - 1) <<
+                           s->in_desc->comp[0].shift,
     };
 
     if (filter) {
diff --git a/libavfilter/vf_scale_cuda.cu b/libavfilter/vf_scale_cuda.cu
index 01398c3db88..8c9ed0a41f5 100644
--- a/libavfilter/vf_scale_cuda.cu
+++ b/libavfilter/vf_scale_cuda.cu
@@ -28,7 +28,8 @@ using subsample_function_t = T (*)(cudaTextureObject_t tex, 
int xo, int yo,
                                    int dst_width, int dst_height,
                                    int src_left, int src_top,
                                    int src_width, int src_height,
-                                   int bit_depth, float param,
+                                   int bit_depth, int src_depth, int 
storage_max,
+                                   float param,
                                    const float *weights, const int *offsets,
                                    int filter_size);
 
@@ -92,7 +93,7 @@ static inline __device__ ushort conv_16to10pl(ushort in)
     __device__ static inline void N(cudaTextureObject_t src_tex[4], T *dst[4], 
int xo, int yo, \
                                     int dst_width, int dst_height, int 
dst_pitch,              \
                                     int src_left, int src_top, int src_width, 
int src_height,  \
-                                    float param, int mpeg_range,               
                \
+                                    int src_depth, int storage_max, float 
param, int mpeg_range, \
                                     const float *weights, const int *offsets, 
int filter_size)
 
 #define SUB_F(m, plane) \
@@ -100,7 +101,7 @@ static inline __device__ ushort conv_16to10pl(ushort in)
                        dst_width, dst_height,  \
                        src_left, src_top,      \
                        src_width, src_height,  \
-                       in_bit_depth, param,    \
+                       in_bit_depth, src_depth, storage_max, param, \
                        weights, offsets, filter_size)
 
 // FFmpeg passes pitch in bytes, CUDA uses potentially larger types
@@ -1099,7 +1100,8 @@ __device__ static inline T 
Subsample_Nearest(cudaTextureObject_t tex,
                                              int dst_width, int dst_height,
                                              int src_left, int src_top,
                                              int src_width, int src_height,
-                                             int bit_depth, float param,
+                                             int bit_depth, int src_depth, int 
storage_max,
+                                             float param,
                                              const float *weights, const int 
*offsets,
                                              int filter_size)
 {
@@ -1117,7 +1119,8 @@ __device__ static inline T 
Subsample_Bilinear(cudaTextureObject_t tex,
                                               int dst_width, int dst_height,
                                               int src_left, int src_top,
                                               int src_width, int src_height,
-                                              int bit_depth, float param,
+                                              int bit_depth, int src_depth, 
int storage_max,
+                                              float param,
                                               const float *weights, const int 
*offsets,
                                               int filter_size)
 {
@@ -1151,7 +1154,8 @@ __device__ static inline T 
Subsample_Bicubic(cudaTextureObject_t tex,
                                              int dst_width, int dst_height,
                                              int src_left, int src_top,
                                              int src_width, int src_height,
-                                             int bit_depth, float param,
+                                             int bit_depth, int src_depth, int 
storage_max,
+                                             float param,
                                              const float *weights, const int 
*offsets,
                                              int filter_size)
 {
@@ -1197,11 +1201,14 @@ __device__ static inline T 
Subsample_Generic(cudaTextureObject_t tex,
                                              int dst_width, int dst_height,
                                              int src_left, int src_top,
                                              int src_width, int src_height,
-                                             int bit_depth, float param,
+                                             int bit_depth, int src_depth, int 
storage_max,
+                                             float param,
                                              const float *weights, const int 
*offsets,
                                              int filter_size)
 {
     const float factor = bit_depth > 8 ? 0xFFFF : 0xFF;
+    const float code_max = (1U << src_depth) - 1;
+    const float sample_step = storage_max / code_max;
 
     floatT sum;
     vec_set_scalar(sum, 0.0f);
@@ -1220,7 +1227,9 @@ __device__ static inline T 
Subsample_Generic(cudaTextureObject_t tex,
             sum += tex2D<floatT>(tex, x, y + i) * col[i];
     }
 
-    return from_floatN<T, floatT>(sum * factor);
+    return from_floatN<T, floatT>(
+        saturate_rintf(sum * (factor / storage_max), code_max) * sample_step
+    );
 }
 
 /// --- FUNCTION EXPORTS ---
@@ -1244,6 +1253,7 @@ __device__ static inline T 
Subsample_Generic(cudaTextureObject_t tex,
         params.dst_width, params.dst_height, params.dst_pitch, \
         params.src_left, params.src_top,                \
         params.src_width, params.src_height,            \
+        params.src_depth, params.src_storage_max,       \
         params.param, params.mpeg_range,                \
         (const float*) params.weights,                  \
         (const int*) params.offsets,                    \
diff --git a/libavfilter/vf_scale_cuda.h b/libavfilter/vf_scale_cuda.h
index 391631699ef..7bf2fa002d4 100644
--- a/libavfilter/vf_scale_cuda.h
+++ b/libavfilter/vf_scale_cuda.h
@@ -44,6 +44,8 @@ typedef struct {
     int src_height;
     float param;
     int mpeg_range;
+    int src_depth;
+    int src_storage_max;
 
     /* Weights for the generic filter kernel */
     CUdeviceptr weights;
-- 
2.54.1


>From 3224dd4e8f1ce4f244fc7b5aecacb0feb9c07a56 Mon Sep 17 00:00:00 2001
From: Michael Niedermayer <[email protected]>
Date: Sun, 20 Sep 2026 12:44:33 +0000
Subject: [PATCH 07/18] avformat/mov: allow explicit zero sample sizes in trun

03d81a044ad587ea83567f75dc36bc3d64278199 rejected every zero-sized
sample to avoid pathological runs of empty samples. This also prevents
opening fragmented recordings with occasional explicit zero sizes.

Allow explicit zero sample sizes, whose count is bounded by the trun
payload checks. Continue rejecting nonempty runs that inherit a zero
default size, but do so before allocating or updating the sample index.
Keep empty samples in the index to preserve sample numbering and timing.

Add a generated FATE test with an empty sample at the end of one fragment
followed by another fragment. No external sample is needed.

Fixes #23807.

Assisted-by: Fairy
(cherry picked from commit e9dc8fd4d6c4f46a02fe9d739141efb32596f7fe)
Signed-off-by: Michael Niedermayer <[email protected]>
---
 libavformat/mov.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)

diff --git a/libavformat/mov.c b/libavformat/mov.c
index 660f4aeae28..662e8bb56d7 100644
--- a/libavformat/mov.c
+++ b/libavformat/mov.c
@@ -6033,6 +6033,11 @@ static int mov_read_trun(MOVContext *c, AVIOContext *pb, 
MOVAtom atom)
     entries = avio_rb32(pb);
     av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %u\n", flags, entries);
 
+    /* Explicit zero sizes are bounded by the trun payload. Reject a zero
+     * default size before allocating or updating the sample index. */
+    if (entries && !frag->size && !(flags & MOV_TRUN_SAMPLE_SIZE))
+        return AVERROR_INVALIDDATA;
+
     if ((uint64_t)entries+sc->tts_count >= UINT_MAX/sizeof(*sc->tts_data))
         return AVERROR_INVALIDDATA;
     if (flags & MOV_TRUN_DATA_OFFSET)        data_offset        = 
avio_rb32(pb);
@@ -6236,8 +6241,6 @@ static int mov_read_trun(MOVContext *c, AVIOContext *pb, 
MOVAtom atom)
         distance++;
         if (av_sat_add64(dts, sample_duration) != dts + 
(uint64_t)sample_duration)
             return AVERROR_INVALIDDATA;
-        if (!sample_size)
-            return AVERROR_INVALIDDATA;
         dts += sample_duration;
         offset += sample_size;
         sc->data_size += sample_size;
-- 
2.54.1


>From af02cbf125f9e811d1a1e2bd5a922118785daa26 Mon Sep 17 00:00:00 2001
From: Jack Boykin <[email protected]>
Date: Sun, 11 Oct 2026 09:49:15 -0500
Subject: [PATCH 08/18] vulkan_decode: keep DRM modifiers off the DPB pool when
 DISTINCT is set

With DPB_AND_OUTPUT_DISTINCT, DPB images never leave the decoder, but the
pool still copied the output's DRM modifier list and tiling. Drivers
needn't support modifier tiling for DPB-only usage, and radv doesn't, so
the pool broke VUID-VkImageCreateInfo-pNext-06811.

Regression since: 25e187f849
Assisted-by: Claude Opus 5.5

(cherry picked from commit b7e835e06913e4374a4567003fe8c75cebfffb98)
Signed-off-by: Michael Niedermayer <[email protected]>
---
 libavcodec/vulkan_decode.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/libavcodec/vulkan_decode.c b/libavcodec/vulkan_decode.c
index 3053395efba..97e6d55bd7b 100644
--- a/libavcodec/vulkan_decode.c
+++ b/libavcodec/vulkan_decode.c
@@ -1406,12 +1406,12 @@ int ff_vk_decode_init(AVCodecContext *avctx)
         dpb_hwfc = dpb_frames->hwctx;
         void *profile_list = (void 
*)ff_vk_find_struct(ctx->s.hwfc->create_pnext,
                                                        
VK_STRUCTURE_TYPE_VIDEO_PROFILE_LIST_INFO_KHR);
-        /* Reference (DPB) images use the same tiling and pNext chain as 
output.
-         * If VK_VIDEO_DECODE_CAPABILITY_DPB_AND_OUTPUT_DISTINCT_BIT_KHR is 0, 
the
-         * driver does not support separate output and DPB with different 
layouts/tiling. */
+        /* With DPB_AND_OUTPUT_DISTINCT, DPB images never leave the decoder,
+         * so they don't need the output's DRM modifiers. */
         void *drm_create_pnext = (void 
*)ff_vk_find_struct(ctx->s.hwfc->create_pnext,
                                                            
VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_LIST_CREATE_INFO_EXT);
-        if (drm_create_pnext) {
+        if (drm_create_pnext &&
+            !(ctx->dec_caps.flags & 
VK_VIDEO_DECODE_CAPABILITY_DPB_AND_OUTPUT_DISTINCT_BIT_KHR)) {
             dpb_hwfc->create_pnext = drm_create_pnext;
             dpb_hwfc->tiling       = VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT;
             av_assert2(ff_vk_find_struct(drm_create_pnext, 
VK_STRUCTURE_TYPE_VIDEO_PROFILE_LIST_INFO_KHR));
-- 
2.54.1


>From 20028f6ca1150dcfef70f36010836fd9697b810c Mon Sep 17 00:00:00 2001
From: Michael Niedermayer <[email protected]>
Date: Tue, 13 Oct 2026 06:10:51 +0200
Subject: [PATCH 09/18] avfilter/dnn_backend_torch: wait only for the inference
 requests that were created

Fixes: nC3u8khGyx61
Fixes: hang on teardown
Hang on teardown Replicated through UnModified FFmpeg with gdb
Found during triage of the review of 
https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/24617

(cherry picked from commit dd01289032d2f7f67db5b6ab28260ddb8cf3bafd)
Signed-off-by: Michael Niedermayer <[email protected]>
---
 libavfilter/dnn/dnn_backend_torch.cpp | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/libavfilter/dnn/dnn_backend_torch.cpp 
b/libavfilter/dnn/dnn_backend_torch.cpp
index 0cbfc1a2c35..de741c546a1 100644
--- a/libavfilter/dnn/dnn_backend_torch.cpp
+++ b/libavfilter/dnn/dnn_backend_torch.cpp
@@ -42,6 +42,7 @@ typedef struct THModel {
     SafeQueue *request_queue;
     Queue *task_queue;
     Queue *lltask_queue;
+    int nb_requests;
 } THModel;
 
 typedef struct THInferRequest {
@@ -121,7 +122,7 @@ static void dnn_free_model_th(DNNModel **model)
     th_model = (THModel *)(*model);
 
     if (th_model->request_queue) {
-        ff_dnn_wait_requests(th_model->request_queue, th_model->ctx->nireq);
+        ff_dnn_wait_requests(th_model->request_queue, th_model->nb_requests);
         while (ff_safe_queue_size(th_model->request_queue) != 0) {
             THRequestItem *item = (THRequestItem 
*)ff_safe_queue_pop_front(th_model->request_queue);
             destroy_request_item(&item);
@@ -483,6 +484,7 @@ static DNNModel *dnn_load_model_th(DnnContext *ctx, 
DNNFunctionType func_type, A
     if (ff_safe_queue_push_back(th_model->request_queue, item) < 0) {
         goto fail;
     }
+    th_model->nb_requests++;
     item = NULL;
 
     th_model->task_queue = ff_queue_create();
-- 
2.54.1


>From 04770dccb0cb2442a9f466bd5329a4edf9066a92 Mon Sep 17 00:00:00 2001
From: Romain Beauxis <[email protected]>
Date: Sat, 17 Oct 2026 06:32:53 +0200
Subject: [PATCH 10/18] avformat/hls: accept EXT-X-START in Master Playlists

EXT-X-START may appear in both Master and Media Playlists (RFC 8216
4.3.5.2). Parsing it allocated a Media Playlist, so a Master Playlist
carrying it before its EXT-X-STREAM-INF entries was rejected since
0e6eef3551.

Record the offset while parsing and apply it once the playlist type is
known. A value from a Master Playlist applies to all its Media
Playlists, which then ignore their own, as RFC 8216 4.3.5 recommends.

Defer EXT-X-ENDLIST the same way, so that it is not lost when it
precedes the first tag allocating the Media Playlist.

(cherry picked from commit 8191fa0b8c05da7919f5ffecf631a7aa669b9203)
Signed-off-by: Michael Niedermayer <[email protected]>
---
 libavformat/hls.c | 36 ++++++++++++++++++++++++++++--------
 1 file changed, 28 insertions(+), 8 deletions(-)

diff --git a/libavformat/hls.c b/libavformat/hls.c
index f26c5b3d1ce..8195113f27f 100644
--- a/libavformat/hls.c
+++ b/libavformat/hls.c
@@ -231,6 +231,7 @@ typedef struct HLSContext {
     int m3u8_hold_counters;
     int live_start_index;
     int prefer_x_start;
+    int master_time_offset_flag; ///< EXT-X-START was set by the Master 
Playlist
     int first_packet;
     int64_t first_timestamp;
     struct playlist *first_timestamp_pls;
@@ -837,6 +838,9 @@ static int parse_playlist(HLSContext *c, const char *url,
     struct segment **prev_segments = NULL;
     int prev_n_segments = 0;
     int64_t prev_start_seq_no = -1;
+    int64_t start_time_offset = 0;
+    int time_offset_flag = 0;
+    int finished = 0;
 
     if (is_http && !in && c->http_persistent && c->playlist_pb) {
         in = c->playlist_pb;
@@ -995,15 +999,11 @@ static int parse_playlist(HLSContext *c, const char *url,
 
         } else if (av_strstart(line, "#EXT-X-START:", &ptr)) {
             const char *time_offset_value = NULL;
-            ret = ensure_playlist(c, &pls, url);
-            if (ret < 0) {
-                goto fail;
-            }
             if (av_strstart(ptr, "TIME-OFFSET=", &time_offset_value)) {
                 double offset = strtod(time_offset_value, NULL) * AV_TIME_BASE;
                 if (offset >= -0x1p63 && offset < 0x1p63) {
-                    pls->start_time_offset = offset;
-                    pls->time_offset_flag = 1;
+                    start_time_offset = offset;
+                    time_offset_flag  = 1;
                 } else {
                     av_log(c->ctx, AV_LOG_WARNING, "TIME-OFFSET value is"
                                                     "invalid, it will be 
ignored");
@@ -1014,8 +1014,7 @@ static int parse_playlist(HLSContext *c, const char *url,
                 continue;
             }
         } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
-            if (pls)
-                pls->finished = 1;
+            finished = 1;
         } else if (av_strstart(line, "#EXTINF:", &ptr)) {
             double d = atof(ptr) * AV_TIME_BASE;
             if (d < 0 || d > INT64_MAX || isnan(d)) {
@@ -1150,6 +1149,27 @@ static int parse_playlist(HLSContext *c, const char *url,
     if (pls)
         pls->last_load_time = av_gettime_relative();
 
+    /* Media Playlist tags may precede the first tag that allocates the
+     * playlist. */
+    if (pls && finished)
+        pls->finished = 1;
+
+    /* EXT-X-START is valid in both playlist types. A value from the Master
+     * Playlist applies to all its Media Playlists, which then ignore their
+     * own (RFC 8216 4.3.5). */
+    if (time_offset_flag && !c->master_time_offset_flag) {
+        if (pls) {
+            pls->start_time_offset = start_time_offset;
+            pls->time_offset_flag  = 1;
+        } else {
+            c->master_time_offset_flag = 1;
+            for (int i = 0; i < c->n_playlists; i++) {
+                c->playlists[i]->start_time_offset = start_time_offset;
+                c->playlists[i]->time_offset_flag  = 1;
+            }
+        }
+    }
+
 fail:
     av_free(new_url);
     if (close_in)
-- 
2.54.1


>From 83585030b6218ef4e40859cf8f7aca07ed80eb66 Mon Sep 17 00:00:00 2001
From: Rainbaby <[email protected]>
Date: Sat, 5 Sep 2026 16:00:55 +0900
Subject: [PATCH 11/18] avcodec/cavsdec: check decode_pic() return value

A picture that failed to decode, whether from an invalid header, a
missing reference, a refused feature or truncated data, was reported
as consumed with no frame and no error. The error now reaches the
caller.

Signed-off-by: Rainbaby <[email protected]>
(cherry picked from commit 72833c7fba27a9665392a908dc96526feb613538)
Signed-off-by: Michael Niedermayer <[email protected]>
---
 libavcodec/cavsdec.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/libavcodec/cavsdec.c b/libavcodec/cavsdec.c
index d866924dbcb..9810b9acdf1 100644
--- a/libavcodec/cavsdec.c
+++ b/libavcodec/cavsdec.c
@@ -1316,8 +1316,9 @@ static int cavs_decode_frame(AVCodecContext *avctx, 
AVFrame *rframe,
             if (!h->got_keyframe)
                 break;
             h->stc = stc;
-            if (decode_pic(h))
-                break;
+            ret = decode_pic(h);
+            if (ret < 0)
+                return ret;
             *got_frame = 1;
             if (h->cur.f->pict_type != AV_PICTURE_TYPE_B) {
                 if (h->DPB[!h->low_delay].f->data[0]) {
-- 
2.54.1


>From aea6256fd220f13515e3283ef65c3a870a60d7e6 Mon Sep 17 00:00:00 2001
From: Rainbaby <[email protected]>
Date: Fri, 28 Aug 2026 16:18:07 +0900
Subject: [PATCH 12/18] avcodec/cavsdec: clear the residual after a failed
 dequant

dequant() writes each coefficient as it goes and only then rejects a
position past the end, so a failed block left its coefficients in
h->block for the next block to add through the inverse transform.

Signed-off-by: Rainbaby <[email protected]>
(cherry picked from commit e3f2e92f14449ea500462a4acf35da7ab5ca7511)
Signed-off-by: Michael Niedermayer <[email protected]>
---
 libavcodec/cavsdec.c | 11 ++++++-----
 1 file changed, 6 insertions(+), 5 deletions(-)

diff --git a/libavcodec/cavsdec.c b/libavcodec/cavsdec.c
index 9810b9acdf1..8a106ac6623 100644
--- a/libavcodec/cavsdec.c
+++ b/libavcodec/cavsdec.c
@@ -587,12 +587,13 @@ static int decode_residual_block(AVSContext *h, 
GetBitContext *gb,
         level_buf[i] = level;
         run_buf[i]   = run;
     }
-    if ((ret = dequant(h, level_buf, run_buf, block, dequant_mul[qp],
-                      dequant_shift[qp], i)) < 0)
-        return ret;
-    h->cdsp.cavs_idct8_add(dst, block, stride);
+    ret = dequant(h, level_buf, run_buf, block, dequant_mul[qp],
+                  dequant_shift[qp], i);
+    if (ret >= 0)
+        h->cdsp.cavs_idct8_add(dst, block, stride);
+    /* dequant() can write before it fails, so always clear the block */
     h->bdsp.clear_block(block);
-    return 0;
+    return ret;
 }
 
 
-- 
2.54.1


>From 9560a555de69a441ddef798bf7aa8f6869a84406 Mon Sep 17 00:00:00 2001
From: Ruk Doe <[email protected]>
Date: Sat, 10 Oct 2026 18:39:40 +0900
Subject: [PATCH 13/18] avcodec/libaribcaption: seed the bitmap CLUT once per
 caption

The CLUT seed is built from every region that may be drawn, so it is
the same for every image of a caption, but it was rebuilt for each one.
Build it once instead. Converting an image only appends colors past the
seed and never changes the alpha table, so restoring the CLUT size at
the start of each image restores the seed.

The output is unchanged: the encoded bitmaps of both aribcaption FATE
samples are identical, with and without ignore_ruby.

Reported-by: Forgejo_Fairy
Reference: #24992
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01DdDiDRusmi6eD7qSrKBjHb
(cherry picked from commit 34908ab5e11b93f650dd17f598f3dcf9149f1750)
Signed-off-by: Michael Niedermayer <[email protected]>
---
 libavcodec/libaribcaption.c | 22 ++++++++++++++--------
 1 file changed, 14 insertions(+), 8 deletions(-)

diff --git a/libavcodec/libaribcaption.c b/libavcodec/libaribcaption.c
index daa95c5219c..4185d33f93c 100644
--- a/libavcodec/libaribcaption.c
+++ b/libavcodec/libaribcaption.c
@@ -298,7 +298,7 @@ static int 
aribcaption_trans_bitmap_subtitle(ARIBCaptionContext *ctx)
 {
     int ret = 0;
     AVSubtitle *sub = ctx->sub;
-    int status, rect_idx, image_count = 0;
+    int status, rect_idx, image_count = 0, seed_idx, seed_overflow;
     int old_width = ctx->frame_width;
     int old_height = ctx->frame_height;
 
@@ -391,18 +391,24 @@ static int 
aribcaption_trans_bitmap_subtitle(ARIBCaptionContext *ctx)
         }
     }
 
+    /* The renderer drops ruby regions with ignore_ruby and regions too small
+       to draw, without telling which region an image comes from. Seed the
+       CLUT with the colors of every region that may be drawn, once. Each
+       image only appends colors past the seed, so dropping them restores it. 
*/
+    clut_reset(ctx);
+    for (int i = 0; i < ctx->caption.region_count; i++)
+        if (!(ctx->ignore_ruby && ctx->caption.regions[i].is_ruby))
+            clut_add_region(ctx, &ctx->caption.regions[i]);
+    seed_idx = ctx->clut_idx;
+    seed_overflow = ctx->clut_overflow;
+
     for (rect_idx = 0; rect_idx < image_count; rect_idx++) {
         AVSubtitleRect *rect = sub->rects[rect_idx];
         aribcc_image_t *image = &ctx->render_result.images[rect_idx];
         int w, h, shrink_height, dst_idx;
 
-        /* The renderer drops ruby regions with ignore_ruby and regions too
-           small to draw, without telling which region an image comes from.
-           Seed the CLUT with the colors of every region that may be drawn. */
-        clut_reset(ctx);
-        for (int i = 0; i < ctx->caption.region_count; i++)
-            if (!(ctx->ignore_ruby && ctx->caption.regions[i].is_ruby))
-                clut_add_region(ctx, &ctx->caption.regions[i]);
+        ctx->clut_idx = seed_idx;
+        ctx->clut_overflow = seed_overflow;
 
         rect->w = image->width * ctx->bitmap_plane_width / ctx->frame_width;
         rect->h = image->height * ctx->bitmap_plane_height / ctx->frame_height;
-- 
2.54.1


>From 5687240bc0537051da413f0da5a434c73a3e0413 Mon Sep 17 00:00:00 2001
From: Matthew Crossley <[email protected]>
Date: Mon, 9 Nov 2026 09:21:14 +0000
Subject: [PATCH 14/18] avformat/dashdec: compute segment bounds after
 refreshing manifest

min_seq_no and max_seq_no were computed before refresh_manifest(), so
were using the bounds of the previous manifest. Segments only available
in refreshed manifest were treated as not yet available.

A sequence equal to the refreshed minimum is still available, so retain
it instead of treating it as expired and selecting a new live position.

Calculate the bounds after refresh instead.

Signed-off-by: Matthew Crossley <[email protected]>
(cherry picked from commit b9fada3b794978e287fec371c1db235081fefba5)
Signed-off-by: Michael Niedermayer <[email protected]>
---
 libavformat/dashdec.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)

diff --git a/libavformat/dashdec.c b/libavformat/dashdec.c
index 717e8c2c5de..b5499116ad6 100644
--- a/libavformat/dashdec.c
+++ b/libavformat/dashdec.c
@@ -1733,7 +1733,10 @@ static struct fragment *get_current_fragment(struct 
representation *pls)
         if (pls->timelines || pls->fragments) {
             refresh_manifest(pls->parent);
         }
-        if (pls->cur_seq_no <= min_seq_no) {
+        min_seq_no = calc_min_seg_no(pls->parent, pls);
+        max_seq_no = calc_max_seg_no(pls, c);
+
+        if (pls->cur_seq_no < min_seq_no) {
             av_log(pls->parent, AV_LOG_VERBOSE, "old fragment: cur[%"PRId64"] 
min[%"PRId64"] max[%"PRId64"]\n", (int64_t)pls->cur_seq_no, min_seq_no, 
max_seq_no);
             pls->cur_seq_no = calc_cur_seg_no(pls->parent, pls);
         } else if (pls->cur_seq_no > max_seq_no) {
-- 
2.54.1


>From a8b3aaa42fef6ed4443be79d89b5aa77dfd81484 Mon Sep 17 00:00:00 2001
From: Matthew Crossley <[email protected]>
Date: Tue, 10 Nov 2026 15:30:35 +0000
Subject: [PATCH 15/18] avformat/dashdec: keep timeline position in ticks on
 manifest refresh

refresh_manifest() converted the current segment start time to whole seconds
by dividing by the timescale, then multiplied it back which loses fractional
seconds. Non-whole segment durations could look up an earlier segment than
the one being read. On a live manifest this can replay the first segment
indefinitely.

Drop the extra arithmetic and keep the position in timescale ticks.

Signed-off-by: Matthew Crossley <[email protected]>
(cherry picked from commit 44178a53618ee33c2931b54b870ebc4e444efd6a)
Signed-off-by: Michael Niedermayer <[email protected]>
---
 libavformat/dashdec.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/libavformat/dashdec.c b/libavformat/dashdec.c
index b5499116ad6..fbc952ddc16 100644
--- a/libavformat/dashdec.c
+++ b/libavformat/dashdec.c
@@ -1639,9 +1639,9 @@ static int refresh_manifest(AVFormatContext *s)
         struct representation *ccur_video = c->videos[i];
         if (cur_video->timelines && cur_video->fragment_timescale > 0) {
             // calc current time
-            int64_t currentTime = 
get_segment_start_time_based_on_timeline(cur_video, cur_video->cur_seq_no) / 
cur_video->fragment_timescale;
+            int64_t currentTime = 
get_segment_start_time_based_on_timeline(cur_video, cur_video->cur_seq_no);
             // update segments
-            ccur_video->cur_seq_no = 
calc_next_seg_no_from_timelines(ccur_video, currentTime * 
cur_video->fragment_timescale - 1);
+            ccur_video->cur_seq_no = 
calc_next_seg_no_from_timelines(ccur_video, currentTime - 1);
             if (ccur_video->cur_seq_no >= 0) {
                 move_timelines(ccur_video, cur_video, c);
             }
@@ -1655,9 +1655,9 @@ static int refresh_manifest(AVFormatContext *s)
         struct representation *ccur_audio = c->audios[i];
         if (cur_audio->timelines && cur_audio->fragment_timescale > 0) {
             // calc current time
-            int64_t currentTime = 
get_segment_start_time_based_on_timeline(cur_audio, cur_audio->cur_seq_no) / 
cur_audio->fragment_timescale;
+            int64_t currentTime = 
get_segment_start_time_based_on_timeline(cur_audio, cur_audio->cur_seq_no);
             // update segments
-            ccur_audio->cur_seq_no = 
calc_next_seg_no_from_timelines(ccur_audio, currentTime * 
cur_audio->fragment_timescale - 1);
+            ccur_audio->cur_seq_no = 
calc_next_seg_no_from_timelines(ccur_audio, currentTime - 1);
             if (ccur_audio->cur_seq_no >= 0) {
                 move_timelines(ccur_audio, cur_audio, c);
             }
-- 
2.54.1


>From 910cf68ba249168b3f122617bc75832f37005a13 Mon Sep 17 00:00:00 2001
From: Matthew Crossley <[email protected]>
Date: Fri, 6 Nov 2026 12:11:26 +0000
Subject: [PATCH 16/18] avformat/dashdec: pace fragment-open retries to avoid
 exhausting max reloads on live content

Mirror the sleep mechanism from HLS demuxer's `reload_playlist`.

Demuxer would attempt to open fragments that do not yet exist in manifest and 
burn through
allowed reloads before fragment is written.

When next segment beyond advertised range of manifest, sleep for half a segment 
duration
(or minimumUpdatePeriod if not available) then refresh before retrying.
Open-ended timelines (negative repeats), SegmentList and duration-only 
representations are not paced,
since the advertised range cannot be relied on for them.

Subtitles and representations with a nonpositive parsed timescale are
also excluded from pacing. A positive minimumUpdatePeriod caps the
polling interval.

Treat absent minimumUpdatePeriod as unset (-1) instead of 0, restore it if 
refresh fails.

Signed-off-by: Matthew Crossley <[email protected]>
(cherry picked from commit 0e164cf74ada548b7e3b3359dcffe2024a989edf)
Signed-off-by: Michael Niedermayer <[email protected]>
---
 libavformat/dashdec.c | 70 +++++++++++++++++++++++++++++++++++++++----
 1 file changed, 64 insertions(+), 6 deletions(-)

diff --git a/libavformat/dashdec.c b/libavformat/dashdec.c
index fbc952ddc16..b3449c7d714 100644
--- a/libavformat/dashdec.c
+++ b/libavformat/dashdec.c
@@ -85,6 +85,7 @@ struct representation {
     AVFormatContext *parent;
     AVFormatContext *ctx;
     int stream_index;
+    enum AVMediaType type;
 
     char *id;
     char *lang;
@@ -1171,6 +1172,7 @@ static int parse_manifest_representation(AVFormatContext 
*s, const char *url,
         }
     }
 
+    rep->type = type;
     switch (type) {
     case AVMEDIA_TYPE_VIDEO:
         ret = av_dynarray_add_nofree(&c->videos, &c->n_videos, rep);
@@ -1371,6 +1373,8 @@ static int parse_manifest(AVFormatContext *s, const char 
*url, AVIOContext *in)
             c->is_live = 1;
         xmlFree(val);
 
+        c->minimum_update_period = -1;
+
         attr = node->properties;
         while (attr) {
             val = xmlGetProp(node, attr->name);
@@ -1603,6 +1607,7 @@ static int refresh_manifest(AVFormatContext *s)
     int n_subtitles = c->n_subtitles;
     struct representation **subtitles = c->subtitles;
     char *base_url = c->base_url;
+    int64_t minimum_update_period = c->minimum_update_period;
 
     c->base_url = NULL;
     c->n_videos = 0;
@@ -1611,6 +1616,7 @@ static int refresh_manifest(AVFormatContext *s)
     c->audios = NULL;
     c->n_subtitles = 0;
     c->subtitles = NULL;
+    c->minimum_update_period = -1;
     ret = parse_manifest(s, s->url, NULL);
     if (ret)
         goto finish;
@@ -1673,6 +1679,8 @@ finish:
         av_free(base_url);
     else
         c->base_url  = base_url;
+    if (ret)
+        c->minimum_update_period = minimum_update_period;
 
     if (c->subtitles)
         free_subtitle_list(c);
@@ -1727,10 +1735,12 @@ static struct fragment *get_current_fragment(struct 
representation *pls)
         }
     }
     if (c->is_live) {
-        min_seq_no = calc_min_seg_no(pls->parent, pls);
-        max_seq_no = calc_max_seg_no(pls, c);
-
-        if (pls->timelines || pls->fragments) {
+        int64_t reload_interval;
+        int64_t last_load;
+        int can_refresh;
+reload:
+        can_refresh = pls->timelines || pls->fragments;
+        if (can_refresh) {
             refresh_manifest(pls->parent);
         }
         min_seq_no = calc_min_seg_no(pls->parent, pls);
@@ -1741,6 +1751,54 @@ static struct fragment *get_current_fragment(struct 
representation *pls)
             pls->cur_seq_no = calc_cur_seg_no(pls->parent, pls);
         } else if (pls->cur_seq_no > max_seq_no) {
             av_log(pls->parent, AV_LOG_VERBOSE, "new fragment: min[%"PRId64"] 
max[%"PRId64"]\n", min_seq_no, max_seq_no);
+
+            int has_negative_repeat = 0;
+            for (int i = 0; i < pls->n_timelines; i++)
+                has_negative_repeat |= pls->timelines[i]->repeat < 0;
+
+            /* Only wait if refresh can reveal new segments or finalisation:
+             * can_refresh/minimum_update_period: manifest is dynamic and 
still updating
+             * type: subtitles must not block audio/video
+             * n_timelines: SegmentTimeline tells us where the end is
+             * has_negative_repeat: max_seq_no cannot be derived with negative 
repeats
+             * fragment_timescale: needed to compute poll interval */
+            if (
+                can_refresh &&
+                c->minimum_update_period != -1 &&
+                pls->type != AVMEDIA_TYPE_SUBTITLE &&
+                pls->n_timelines &&
+                !has_negative_repeat &&
+                pls->fragment_timescale > 0
+            ) {
+                reload_count++;
+                if (reload_count > c->max_reload) {
+                    av_log(pls->parent, AV_LOG_ERROR,
+                       "Reached max manifest reloads (%d) at seq %"PRId64"\n",
+                       c->max_reload, pls->cur_seq_no);
+                    return NULL;
+                }
+
+                /* Poll at half a segment duration, falling back to the
+                 * update period, with a floor to avoid busy-looping. */
+                int64_t duration = pls->fragment_duration <= 0 ?
+                                   pls->timelines[pls->n_timelines - 
1]->duration :
+                                   pls->fragment_duration;
+                reload_interval = duration > 0 ?
+                                  av_rescale(duration, AV_TIME_BASE, 
pls->fragment_timescale) :
+                                  c->minimum_update_period * AV_TIME_BASE;
+                reload_interval = FFMAX(reload_interval / 2, 100 * 1000);
+                if (c->minimum_update_period > 0)
+                    reload_interval = FFMIN(reload_interval,
+                                            c->minimum_update_period * 
AV_TIME_BASE);
+
+                last_load = av_gettime_relative();
+                while (av_gettime_relative() - last_load < reload_interval) {
+                    if (ff_check_interrupt(c->interrupt_callback))
+                        return NULL;
+                    av_usleep(100*1000);
+                }
+                goto reload;
+            }
         }
         seg = av_mallocz(sizeof(struct fragment));
         if (!seg) {
@@ -1901,7 +1959,7 @@ restart:
         free_fragment(&v->cur_seg);
         v->cur_seg = get_current_fragment(v);
         if (!v->cur_seg) {
-            ret = AVERROR_EOF;
+            ret = ff_check_interrupt(c->interrupt_callback) ? AVERROR_EXIT : 
AVERROR_EOF;
             goto end;
         }
 
@@ -1944,7 +2002,7 @@ restart:
         v->cur_seg = get_current_fragment(v);
     }
     if (!v->cur_seg) {
-        ret = AVERROR_EOF;
+        ret = ff_check_interrupt(c->interrupt_callback) ? AVERROR_EXIT : 
AVERROR_EOF;
         goto end;
     }
     ret = read_from_url(v, v->cur_seg, buf, buf_size);
-- 
2.54.1


>From 48148778f95d8b73e25ac058a8eade5ae2957bd3 Mon Sep 17 00:00:00 2001
From: Michael Niedermayer <[email protected]>
Date: Thu, 26 Nov 2026 22:33:15 +0100
Subject: [PATCH 17/18] avutil/hwcontext_cuda: return the error code from
 cuda_transfer_data()

A failed copy and the size check added by 2c647e6c6f0 jump to exit,
which returned 0. On master this was changed as part of ef3dcf4ea61.

Signed-off-by: Michael Niedermayer <[email protected]>
---
 libavutil/hwcontext_cuda.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/libavutil/hwcontext_cuda.c b/libavutil/hwcontext_cuda.c
index 4103ba36b1e..77f9b194ca9 100644
--- a/libavutil/hwcontext_cuda.c
+++ b/libavutil/hwcontext_cuda.c
@@ -300,7 +300,7 @@ static int cuda_transfer_data(AVHWFramesContext *ctx, 
AVFrame *dst,
 exit:
     CHECK_CU(cu->cuCtxPopCurrent(&dummy));
 
-    return 0;
+    return ret;
 }
 
 static void cuda_device_uninit(AVHWDeviceContext *device_ctx)
-- 
2.54.1


>From d4d81bbe3dff519abb49a8f2b71d0af0f22c12af Mon Sep 17 00:00:00 2001
From: Michael Niedermayer <[email protected]>
Date: Thu, 26 Nov 2026 22:33:15 +0100
Subject: [PATCH 18/18] Changelog: update

Signed-off-by: Michael Niedermayer <[email protected]>
---
 Changelog | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)

diff --git a/Changelog b/Changelog
index 1ba596888b2..c31fb4d6bd1 100644
--- a/Changelog
+++ b/Changelog
@@ -2,6 +2,23 @@ Entries are sorted chronologically from oldest to youngest 
within each release,
 releases are sorted from youngest to oldest.
 
 version 9.0.3:
+ avutil/hwcontext_cuda: return the error code from cuda_transfer_data()
+ avformat/dashdec: pace fragment-open retries to avoid exhausting max reloads 
on live content
+ avformat/dashdec: keep timeline position in ticks on manifest refresh
+ avformat/dashdec: compute segment bounds after refreshing manifest
+ avcodec/libaribcaption: seed the bitmap CLUT once per caption
+ avcodec/cavsdec: clear the residual after a failed dequant
+ avcodec/cavsdec: check decode_pic() return value
+ avformat/hls: accept EXT-X-START in Master Playlists
+ avfilter/dnn_backend_torch: wait only for the inference requests that were 
created
+ vulkan_decode: keep DRM modifiers off the DPB pool when DISTINCT is set
+ avformat/mov: allow explicit zero sample sizes in trun
+ avfilter/vf_scale_cuda: quantize generic output to source depth
+ avfilter/vf_scale_cuda: regenerate filters for cropped frames
+ avfilter/vf_scale_cuda: encapsulate generic filter resources
+ avfilter/vf_scale_cuda: select separable passes per plane
+ avfilter/dnn: fix race when querying queue length
+ avfilter/dnn: prevent crash on parameterless LibTorch models
  avcodec/lcevcdec: flush pictures on decoder flush
  avcodec/libaribcaption: free the render result after converting it
  avcodec/vulkan_encode_av1: zero constantQIndex when rate control is on
-- 
2.54.1

_______________________________________________
ffmpeg-devel mailing list -- [email protected]
To unsubscribe send an email to [email protected]

Reply via email to